agent-afk 5.185.0 → 5.186.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent/tools/handlers/patch-apply-engine.d.ts +2 -0
- package/dist/cli.mjs +453 -453
- package/dist/index.mjs +49 -49
- package/dist/telegram.mjs +4 -4
- package/dist/utils/diff.d.ts +1 -0
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var FR=Object.defineProperty;var se=(t,e)=>()=>(t&&(e=t(t=0)),e);var Os=(t,e)=>{for(var n in e)FR(t,n,{get:e[n],enumerable:!0})};function Nr(t){return Ur.find(e=>e.name===t)}function Ds(t){return process.env[t]!==void 0}var cm=se(()=>{"use strict";C()});var Ur,lm,b,C=se(()=>{"use strict";cm();Ur=[{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_COMPACT_SHRINK_FRACTION",description:"Context-fullness fraction (0\u20131, exclusive) at/above which /compact and auto-compaction relax the keep-window so a short-but-full session (few turns, huge tool exchanges) can still be summarized instead of no-oping on turn count. Default 0.7 (see shared/compaction.ts DEFAULT_COMPACT_SHRINK_THRESHOLD).",type:"number",required:!1,example:"0.8",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_CONCURRENT_SAFE_TOOL_CALLS",description:"Maximum concurrency-safe tool calls run simultaneously within one dispatcher batch. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"4",category:"model"},{name:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",description:"Maximum subagent calls run simultaneously from one compose/DAG layer or skill wave. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"2",category:"model"},{name:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",description:"Maximum background subagent jobs running simultaneously in one registry. Default 10; accepted range 1-64; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"10",example:"5",category:"model"},{name:"AFK_MAX_NESTING_DEPTH",description:"Maximum sub-agent/skill nesting depth; 0 disables nested delegation entirely (the agent, skill, AND compose tools all refuse). A top-level session is depth 0, so the default 3 permits three generations of forked descendants (depth 1 \u2192 2 \u2192 3) and refuses the agent and skill tools at depth 3. Resolved once at the root of each session and propagated down through child AgentConfig, so descendants inherit the root value rather than re-reading the environment. Raise with care: depth is a fan-out exponent (a width-N wave at depth D reaches ~N^D concurrent children), so values above 4 invite provider rate-limit (429) cascades. Accepted range 0-6; unset, empty, unparseable, negative, or out-of-range input falls back to the default. An explicit programmatic maxDepth (SubagentExecutorContext / SkillExecutorContext) still wins.",type:"number",required:!1,default:"3",example:"2",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. When unset, falls back to the model output ceiling (AFK's own per-model limit, 64k\u2013128k \u2014 NOT a small provider default), so every request advertises the full ceiling by default. An over-ceiling value is clamped down with a warning.",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_MICROCOMPACT_KEEP_LAST",description:"Number of the most-recent tool_result blocks that tool-result microcompaction keeps intact regardless of size, so the agent does not lose the tool output it is actively reasoning over. Older results are the safe ones to trim. Default 4 (see shared/compaction.ts DEFAULT_MICROCOMPACT_KEEP_LAST). Values <= 0 protect nothing.",type:"number",required:!1,default:"4",example:"3",category:"model"},{name:"AFK_MICROCOMPACT_TOOL_RESULT_BYTES",description:"Byte threshold (tool_result content length) at/above which a tool_result block becomes a microcompaction candidate. When /compact and auto-compaction would otherwise no-op on a short-but-full session, microcompaction clears large/old tool_result CONTENT in place (largest first) \u2014 replacing it with a short placeholder, never removing the block \u2014 to reclaim context deterministically (no LLM call). Blocks below this size are left intact. Default 2048 (see shared/compaction.ts DEFAULT_MICROCOMPACT_TOOL_RESULT_BYTES).",type:"number",required:!1,default:"2048",example:"4096",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), fixed-identity aliases (opus, sonnet, haiku, fable), or full model IDs. Migration: AFK_MODEL=sonnet now pins the fixed Sonnet identity rather than following a rebound medium tier.",type:"string",required:!1,default:"medium",example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_TTFB_TIMEOUT_MS",description:"Per-ROUND time-to-first-token budget (ms) for the anthropic-direct streaming loop. Bounds how long a round may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response is governed instead by the progress-aware AFK_MODEL_STALL_TIMEOUT_MS window, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. The budget is divided into 3 shorter first-byte ATTEMPTS (each ~2/3 of this value, so the worst-case wall time per round is unchanged from the previous 2-attempt regime while a transient stall gets 3 chances instead of 2). NOTE: a request whose FIRST token takes longer than the per-attempt bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted and re-driven, then surfaces as an error once the budget is spent (raise this value or set 0 for such workloads); this trims the degrading-call tail instead of a silent ~10-min hang on the SDK default. Default 180000 (180s \u2248 2\xD7 the measured p99 ttfb), i.e. 3 \xD7 120s. Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_MODEL_STALL_TIMEOUT_MS",description:"Progress-aware POST-first-byte stall window (ms) for the anthropic-direct streaming loop. Bounds how long a stream that has ALREADY produced content may then go completely silent. Every streamed output event resets the window, so this is NOT a total-round cap: a legitimately long, actively-streaming round (large code emission, extended thinking) survives indefinitely, while a stream wedged mid-flight is aborted and surfaces as a real terminal error instead of hanging. Complements AFK_MODEL_TTFB_TIMEOUT_MS, which governs only the window BEFORE the first token; this one takes over after it. Default 1200000 (20min) \u2014 above the 18.5min maximum post-first-byte stream duration observed across 86,076 rounds in 12,381 local traces (p99 122s, p99.9 234s), so no healthy round trips it. Set to 0 to disable (issue #762).",type:"number",required:!1,default:"1200000",example:"600000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",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-5",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_OVERLOAD_PAUSE_MS",description:"Wall-clock ceiling (ms) for the bounded pause after a mid-stream overload (529) exhausts its retry budget. Overrides the per-surface default for ALL surfaces: 0 disables the pause (fail fast). Interactive surfaces (cli/repl/telegram) default to 600000; daemon/cron default to 0 so an always-on runner never silently parks on upstream capacity.",type:"number",required:!1,example:"600000",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_PROMPT",description:"Enable LLM-generated empty-prompt suggestions \u2014 a proposed next action shown as ghost text when the prompt is blank, accepted with Tab or Right-arrow. Fires only after a turn has completed in the session: the startup prompt (and the prompt right after /clear) is left clean because there is no session context to ground a proposal in. Set to 1/true/yes/on to activate. Off by default. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",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 | max | 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:"AFK_WORKSPACE_DISABLED",description:"Disable the shared agent workspace (WorkspaceStore + workspace_publish/workspace_query tools + preamble injection). When set to 1, subagents do not get workspace tools and no workspace preamble is injected at fork time \u2014 each agent works in full isolation as before v5.133. Used as the control arm of the file-read deduplication A/B experiment. Default: workspace enabled (unset or 0).",type:"boolean",required:!1,default:"0",example:"1",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:"XAI_API_KEY",description:"xAI API key for the xai provider (Grok models) in API-key mode. Metered; distinct from SuperGrok / SuperGrok Heavy / X Premium+ OAuth.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_XAI_BASE_URL",description:"Base URL for xAI API-key mode. Default https://api.x.ai/v1. The OpenAI SDK appends /chat/completions.",type:"string",required:!1,example:"https://api.x.ai/v1",category:"model"},{name:"AFK_XAI_OAUTH_BASE_URL",description:"Base URL for xAI SuperGrok / SuperGrok Heavy / X Premium+ OAuth inference. Default https://cli-chat-proxy.grok.com/v1 (subscription path). Some accounts work on https://api.x.ai/v1 with OAuth \u2014 override if needed. Distinct from AFK_XAI_BASE_URL (API-key mode).",type:"string",required:!1,example:"https://cli-chat-proxy.grok.com/v1",category:"model"},{name:"AFK_XAI_GROK_CLIENT_VERSION",description:"Override the semver sent as x-grok-client-version to the xAI OAuth CLI chat proxy. Use only if the proxy raises its required Grok CLI version before agent-afk is updated; invalid values fall back to the official Grok Build version file or built-in compatible default.",type:"string",required:!1,example:"1.0.6",category:"model"},{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 | xai | xai-oauth). 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_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",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 a truthy value ('1'/'true'/'yes'/'on', case-insensitive) to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"TMUX",description:"OS-level tmux session identifier. Set automatically by tmux to the socket path and session info (e.g. /tmp/tmux-501/default,12345,0) inside any tmux pane. Not set by AFK. Read by configureColor() to detect a tmux environment; for truecolor support on Node \u2264 24, set FORCE_COLOR=3 in your shell or ~/.afk/config/afk.env.",type:"string",required:!1,example:"/tmp/tmux-501/default,12345,0",category:"process"},{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:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",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:"APPDATA",description:"Windows %APPDATA% (Roaming). Used for VS Code/Cursor settings discovery and credential denylist paths.",type:"string",required:!1,category:"process"},{name:"LOCALAPPDATA",description:"Windows %LOCALAPPDATA%. Used for browser credential denylist paths (Chrome, Firefox, Edge, etc.).",type:"string",required:!1,category:"process"},{name:"USERPROFILE",description:"Windows %USERPROFILE%. Used for credential denylist paths (.ssh, .aws, .gnupg) on win32.",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_WEB_PORT",description:"Port for the `afk web` browser surface. Defaults to 4141; falls back to an ephemeral port when taken. Overridden by --port.",type:"number",required:!1,example:"4141",category:"daemon"},{name:"AFK_WEB_HOST",description:"Bind address for the `afk web` browser surface. Defaults to 127.0.0.1. Unlike the daemon control surface, a non-loopback bind is REFUSED unless AFK_WEB_TOKEN (or --token) is also set, because this surface can submit prompts and approve tool use. Overridden by --host.",type:"string",required:!1,example:"127.0.0.1",category:"daemon"},{name:"AFK_WEB_TOKEN",description:"Bearer token for the `afk web` surface. When unset, a random per-run token is minted and printed in the startup URL. Setting this explicitly is also what permits a non-loopback bind.",type:"string",required:!1,category:"daemon",secret:!0},{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_ON_EXIT",description:"Clean-worktree quit policy for interactive --worktree sessions: ask, keep, or remove.",type:"string",required:!1,example:"ask",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:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_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_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",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_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_GOBLIN_MASCOT",description:"Reacting goblin mini-sprite in the reserved footer band while the agent runs tools (3 rows, animated). 1 = on, unset/0 = off (default). Claims terminal rows, so it is opt-in.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"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_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | umber | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark; umber matches the Umber terminal, is dark-only, and is never chosen by auto. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"AFK_TEXT_MEASURE",description:"Maximum line length (columns) for unbordered streamed text in the interactive REPL: assistant prose, thinking blocks, tool-lane text, and subagent text. Display-only \u2014 affects wrapping, never behavior. Bordered elements (cards, error boxes) already cap at 100; this applies the same ceiling to the unbordered surfaces, which previously scaled to the full terminal width. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable capping and restore full-width wrapping. Unparseable or below-minimum values fall back to the default. No-op on terminals at or below the measure, so narrow terminals are unaffected.",type:"string",required:!1,default:"100",example:"full",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"COLORTERM",description:"OS-level terminal color-depth hint. Accepted values: truecolor or 24bit (24-bit color), 256color (256-color). Set by the outer terminal emulator, not by AFK. Read by chalk's supports-color to set its initial color level; also read by configureColor() to recommend FORCE_COLOR=3 for tmux truecolor users on Node \u2264 24.",type:"string",required:!1,example:"truecolor",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_WITNESS_RETENTION_DISABLE",description:"Disable the witness-tree retention sweep entirely, so no session directory is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_MAX_AGE_DAYS",description:"Evict a witness session directory once its newest content is older than this many days. Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_WITNESS_MAX_BYTES",description:"Aggregate byte cap for the witness tree; oldest session directories are evicted first once exceeded. Default 2147483648 (2 GiB).",type:"number",required:!1,default:"2147483648",category:"debug"},{name:"AFK_SESSION_RETENTION_DISABLE",description:"Disable the session sidecar retention sweep entirely, so no state/sessions/*.json file is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SESSION_MAX_AGE_DAYS",description:"Evict a session sidecar file once it is older than this many days (based on savedAt). Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_SESSION_MAX_COUNT",description:"Count-based safety valve: evict oldest session sidecars first once the total exceeds this number. Default 1000.",type:"number",required:!1,default:"1000",category:"debug"},{name:"AFK_WAVE_MANIFEST_DISABLED",description:"Disable the wave manifest system entirely. When set to 1, no manifest is written for parallel subagent waves, and no resumption offer is made at session start.",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{name:"AFK_WAVE_MANIFEST_TTL_HOURS",description:"Time-to-live for wave manifests in hours. Manifests older than this are deleted on reconciliation and by the witness sweep. Default 48 (two days).",type:"number",required:!1,default:"48",example:"24",category:"misc"},{name:"AFK_WAVE_RESUME_UNATTENDED",description:"When set to 1, surface wave resumption offers even on non-interactive surfaces (daemon, one-shot chat). By default, offers are only made on interactive surfaces (REPL, Telegram).",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{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:"AFK_CAPTURE_SUBAGENT_PROMPTS",description:"Opt-in: when set to 1, every prompt a parent session sends to a subagent is written as a redacted markdown file under state/witness/<label>/prompts/. Off by default because nothing prunes the witness tree and prompts may carry secrets the regex redactor cannot catch (connection strings, PEM blocks, PII).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_OUTPUT",description:"Opt-in: when set to 1, a subagent's conversational OUTPUT (assistant text plus each tool call with its arguments) is appended incrementally to a redacted markdown transcript under state/witness/<label>/outputs/. Flushed at every tool-call boundary, so a child killed by a timeout still leaves a usable partial record \u2014 the case where final-message capture yields nothing. Off by default for the same reasons as AFK_CAPTURE_SUBAGENT_PROMPTS (unpruned witness tree, best-effort regex redaction).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_SUBAGENT_RESULT_CAP_BYTES",description:"Foreground subagent result size cap in bytes. When a subagent's final message exceeds this threshold, the full output is spilled to a sidecar file (state/sessions/<id>/subagent-handoffs/<subagentId>.txt) and the parent receives a head+tail slice with a read_file pointer. Prevents large subagent outputs from bloating parent context. Set to 0 to disable the cap entirely. Default 32768 (32KB). Note: sidecar files contain unredacted subagent output (same caveats as AFK_CAPTURE_SUBAGENT_OUTPUT). No automatic GC covers subagent-handoffs/ today; retention is tied to session-directory cleanup.",type:"number",required:!1,default:"32768",example:"16384",category:"model"},{name:"AFK_SUBAGENT_LOG",description:"Opt-in per-subagent conversation log. Writes OutputEvent JSONL to state/subagent-logs/<sessionLabel>/<subagentId>.jsonl for both foreground and background subagents. Powers /tasks:view replay. OFF by default (raw tool arguments are written without redaction \u2014 consistent with AFK_CAPTURE_SUBAGENT_PROMPTS / AFK_CAPTURE_SUBAGENT_OUTPUT). Set to 1 to enable.",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 on every AFK surface \u2014 the CLI entrypoint reports surface `afk`, which is in the headless set \u2014 so watching the agent work in a visible window is opt-in via `AFK_BROWSER_HEADLESS=0`, not implied by running the REPL. Note headed and headless use different chromium downloads (`chromium-*` vs `chromium_headless_shell-*`).",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:"Browser provider backend: auto (default, prefer Agent Browser, fall back to Playwright), agent-browser (require Agent Browser), or playwright (headless only).",type:"string",required:!1,default:"auto",example:"agent-browser",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_READ_DENYLIST",description:"Colon-separated list of additional absolute paths the read_file/grep/glob/list_directory tools refuse to read, and that the bash-restriction hook refuses to let a shell command reference on interactive surfaces (REPL, Telegram) \u2014 on headless surfaces (afk chat, daemon) bash fails open regardless of this list. A leading ~/ is expanded (~user/ is not \u2014 spell those absolutely). Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed. One built-in exception exists: ~/.afk/config/mcp.json (the MCP registry) IS readable \u2014 paths listed here outrank that carve-out, so set this to ~/.afk/config/mcp.json if your registry holds inline secrets rather than ${VAR} placeholders.",type:"string",required:!1,example:"/Users/me/project/.env:/Users/me/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_RATE_LIMIT_ADMISSION_DISABLED",description:"Bypass the process-wide rate-limit admission gate (issue #941). Set to 1 to skip pre-request capacity checks. Default 0 (gate active). OAuth subscription accounts already pass through automatically when no per-minute headers are returned.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_RATE_LIMIT_STAGGER_MAX_MS",description:"Jitter ceiling (ms) for the rate-limit admission bucket: each waiter at a window boundary wakes at reset + random(0..ceiling) to avoid re-storming the API. Default 500. Set to 0 in tests for deterministic timing.",type:"number",required:!1,default:"500",example:"0",category:"model"},{name:"AFK_WEB_ALLOW_PRIVATE_HOSTS",description:"Opt out of the web_scrape SSRF egress guard. When unset (default) the guard is ACTIVE: the markdown, raw, and headless-render paths refuse loopback (127/8, ::1), link-local (169.254/16 \u2014 including the 169.254.169.254 cloud instance-metadata endpoint), RFC1918 (10/8, 172.16/12, 192.168/16), carrier-grade NAT (100.64/10), IPv6 unique-local (fc00::/7), 0.0.0.0/8, and the IPv4-mapped/compatible IPv6 forms of all of those. Hostnames are resolved and the RESOLVED addresses are classified (DNS-rebinding guard), and the check is re-applied on every redirect hop. Set to 1/true to allow private-host access \u2014 needed only to scrape a local dev server. Enabling it restores a model-reachable SSRF path (issue #575).",type:"boolean",required:!1,example:"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:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",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"},{name:"AFK_LEASE_TTL_MS",description:"Lease TTL in milliseconds for durable task execution (issue #1411). A leased task whose lease expires before it completes is recovered and re-enqueued (or dead-lettered if maxAttempts is exhausted). Default: 600000 (10 minutes).",type:"number",required:!1,example:"600000",category:"misc"}],lm={};for(let t of Ur){let e=t.name;Object.defineProperty(lm,e,{get(){return process.env[e]},enumerable:!("secret"in t&&t.secret),configurable:!0})}b=lm});function LR(){return b.AFK_DEBUG==="1"||b.DEBUG==="1"}function P(...t){LR()&&console.log(...t)}var J=se(()=>{"use strict";C()});import{existsSync as dm,mkdirSync as NR,renameSync as UR,cpSync as $R,rmSync as BR}from"fs";import{join as L,dirname as Il,basename as jR,isAbsolute as Cl}from"path";import{homedir as fm}from"os";import{fileURLToPath as HR}from"url";function ne(){let t=b.AFK_HOME;if(t!==void 0&&t!==""){if(!Cl(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return L(fm(),".afk")}function De(){let t=b.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!Cl(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return L(ne(),"agent-framework")}function Fs(){return L(De(),"forge-telemetry.jsonl")}function mm(){return L(De(),"briefs")}function gm(){return L(De(),"facets")}function $r(){return L(ne(),"skills")}function xn(){return L(ne(),"plugins")}function hm(t=process.cwd()){return L(t,".afk")}function ym(t=process.cwd()){return L(hm(t),"skills")}function bm(t=process.cwd()){return L(hm(t),"plugins")}function wm(t=process.cwd()){return L(t,".afk","plans")}function Ls(){return L(xn(),".index.json")}function Pl(){return L(Br(),"schedules.json")}function Sm(){let t=HR(import.meta.url),e=Il(t);return L(e,"bundled-plugins")}function Br(){return L(ne(),"config")}function Q(){let t=b.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Cl(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return L(ne(),"state")}function re(){return L(Q(),"sessions")}function Ns(){return L(Q(),"presence")}function Us(){return L(Q(),"memory")}function $s(){return L(Q(),"kv","kv.db")}function Bs(){return L(Q(),"session-grants.jsonl")}function km(){return L(ne(),"farms")}function vm(t){return L(km(),t)}function js(t){if(!WR.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function jr(){return L(Q(),"witness")}function Pt(t){return js(t),L(jr(),t)}function Tm(t){return L(Pt(t),"inbound-attachments")}function _m(t){return L(Pt(t),"prompts")}function Em(t){return L(Pt(t),"outputs")}function Rn(t){return!t||t.startsWith("in-memory:")?null:jR(Il(t))}function Am(t="default"){return L(Q(),"daemon",`agent-afk@${t}`)}function xm(){return L(Q(),"worktree-sweep.lock")}function Hs(){return L(Q(),"worktree-roots.json")}function Ml(){return L(Br(),"afk.env")}function In(){return L(Br(),"afk.config.json")}function Ws(){return L(fm(),".afk.config.json")}function KR(){return L(ne(),"sessions")}function qR(t,e){if(t!==e&&dm(t)&&!dm(e))try{NR(Il(e),{recursive:!0});try{UR(t,e)}catch(n){if(n.code==="EXDEV")try{$R(t,e,{recursive:!0}),BR(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
|
|
2
2
|
`)}}}catch{}}function Rm(){qR(KR(),re())}function Im(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid jobId: must be a non-empty string");if(t.length>um)throw new Error(`Invalid jobId: exceeds ${um} chars`);if(!GR.test(t))throw new Error(`Invalid jobId: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function Ol(){return L(Q(),"subagent-logs")}function Dl(t){return Im(t),L(Ol(),t)}function Cm(t,e){return Im(e),L(Dl(t),`${e}.jsonl`)}function Fl(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>pm)throw new Error(`Invalid browser profile: exceeds ${pm} chars`);if(!XR.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function zR(){return L(Q(),"browser")}function JR(t){return Fl(t),L(zR(),t)}function Ll(t){return L(JR(t),"storageState.json")}function Cn(t){return typeof t=="string"&&t.length>0&&t.length<=YR&&VR.test(t)}function Hr(t){if(!Cn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return L(re(),t)}function Wr(t){return L(Hr(t),"events.jsonl")}function Pm(t){return L(Hr(t),"session.key")}function Pn(){return L(Q(),"waves")}function Mn(t){return L(Pn(),`${t}.json`)}var WR,GR,um,XR,pm,VR,YR,M=se(()=>{"use strict";C();WR=/^[a-zA-Z0-9_-]+$/;GR=/^[A-Za-z0-9_-]+$/,um=128;XR=/^[A-Za-z0-9_-]+$/,pm=128;VR=/^[A-Za-z0-9_-]+$/,YR=128});var Qd={};Os(Qd,{enforceDomainPolicy:()=>Ze,loadBrowserConfig:()=>Yd});import{readFileSync as QD}from"node:fs";import{join as ZD}from"path";function eF(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function hb(t,e){return eF(e).test(t)}function rF(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(tF.has(e))return!0;if(nF.has(e))return!1}return!1}function yb(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function oF(t){if(t===void 0||t==="")return"auto";if(t==="playwright"||t==="agent-browser"||t==="auto")return t;throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${t}`)}function bb(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Fl(e),e}function sF(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function iF(t){try{return QD(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function aF(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"||e.backend==="agent-browser"||e.backend==="auto")n.backend=e.backend;else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=bb(e.defaultProfile)),n}function Yd(t){let e=t?.env??b,n=t?.readFileSync??iF,r=t?.surface??e.AGENT_SURFACE,o=rF(e.AFK_BROWSER_HEADLESS,r),s=yb(e.AFK_BROWSER_ALLOWED_DOMAINS),i=yb(e.AFK_BROWSER_BLOCKED_DOMAINS),a=sF(e.AFK_BROWSER_DOM_SNAPSHOTS),c=oF(e.AFK_BROWSER_BACKEND),l=bb(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():ZD(Br(),"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=aF(d,m);return g.configPath=p,g}function Ze(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(hb(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>hb(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var tF,nF,Ht=se(()=>{"use strict";C();M();tF=new Set(["daemon","subagent","telegram","afk"]),nF=new Set(["repl","interactive","cli"])});import{readFileSync as cF}from"node:fs";import{join as lF}from"node:path";import{homedir as dF}from"node:os";function pF(t){let e=t??uF,n;try{n=cF(e,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(typeof r!="object"||r===null||Array.isArray(r))return null;let o=r;if(typeof o.url!="string"||typeof o.token!="string"||typeof o.pid!="number")return null;let s;try{s=new URL(o.url)}catch{return null}let{hostname:i,protocol:a}=s;if(!(i==="127.0.0.1"||i==="localhost"||i==="::1")||a!=="http:")throw new Error(`Agent Browser connection file contains an untrusted URL: ${o.url}. Only http://127.0.0.1 or http://localhost is permitted.`);return{url:o.url,token:o.token,pid:o.pid,version:typeof o.version=="string"?o.version:"unknown"}}function fF(t){try{return process.kill(t,0),!0}catch{return!1}}async function mF(t,e,n=2e3){try{let r=new AbortController,o=setTimeout(()=>r.abort(),n),s=await fetch(`${t}/health`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Host:"127.0.0.1:8833"},signal:r.signal});return clearTimeout(o),s.ok}catch{return!1}}async function Zd(t){let e=pF(t);return e===null?{available:!1,connection:null,reason:"connection file missing or invalid"}:fF(e.pid)?await mF(e.url,e.token)?{available:!0,connection:e,reason:null}:{available:!1,connection:e,reason:`health probe failed at ${e.url}`}:{available:!1,connection:e,reason:`stale connection file: PID ${e.pid} not alive`}}var uF,wb=se(()=>{"use strict";uF=lF(dF(),".config","agent-browser","connection.json")});async function Sb(t){let{config:e,surface:n}=t;if(e.backend==="playwright")return{backend:"playwright",reason:"explicit config: backend=playwright",probeMs:0,availability:null};if(e.backend==="agent-browser"){let i=Date.now(),a=await Zd(),c=Date.now()-i;if(!a.available)throw new Error(`AFK_BROWSER_BACKEND=agent-browser but Agent Browser is not available: ${a.reason}`);return{backend:"agent-browser",reason:"explicit config: backend=agent-browser",probeMs:c,availability:a}}if(n&&gF.has(n))return{backend:"playwright",reason:`auto: surface "${n}" excluded from Agent Browser`,probeMs:0,availability:null};if(e.headless)return{backend:"playwright",reason:"auto: headless mode requires Playwright",probeMs:0,availability:null};let r=Date.now(),o=await Zd(),s=Date.now()-r;return o.available?{backend:"agent-browser",reason:"auto: Agent Browser available and preferred",probeMs:s,availability:o}:{backend:"playwright",reason:`auto: Agent Browser unavailable (${o.reason})`,probeMs:s,availability:o}}var gF,kb=se(()=>{"use strict";wb();gF=new Set(["daemon","subagent"])});import{createHash as hF}from"crypto";function vb(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&yF.test(t.label))}function Tb(t){return hF("sha256").update(t,"utf8").digest("hex").slice(0,8)}function _b(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var yF,qi=se(()=>{"use strict";yF=/password|secret|token|api[_-]?key|otp|2fa/i});import{randomBytes as bF}from"crypto";import{mkdir as wF,stat as SF,writeFile as kF}from"fs/promises";import{join as eu}from"path";import{gzip as vF}from"zlib";import{promisify as TF}from"util";function _F(t){return eu(Pt(t),"browser")}function EF(t){return eu(_F(t),"screenshots")}function AF(){return new Date().toISOString().replace(/[:.]/g,"-")}function xF(){return bF(3).toString("hex")}async function Yn(t,e,n){if(e.length>Eb)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Eb} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=EF(t);await wF(r,{recursive:!0});let o=`${AF()}-${xF()}-${n}.png`,s=eu(r,o);await kF(s,e);let{size:i}=await SF(s);return{path:s,bytes:i}}var u3,Eb,tu=se(()=>{"use strict";M();qi();u3=TF(vF);Eb=5*1024*1024});var Gi,Ab=se(()=>{"use strict";Gi=class{baseUrl;token;constructor(e){this.baseUrl=e.url,this.token=e.token}async call(e,n,r=3e4){let o={version:1,method:e,params:n},s=new AbortController,i=setTimeout(()=>s.abort(),r);try{let a=await fetch(`${this.baseUrl}/agent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,Host:new URL(this.baseUrl).host},body:JSON.stringify(o),signal:s.signal});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Agent Browser ${e} failed (HTTP ${a.status}): ${c}`)}return await a.json()}finally{clearTimeout(i)}}async listTabs(){return(await this.call("tabs.list",null)).tabs}async openTab(e){return{tabId:(await this.call("tabs.open",{url:e},6e4)).tab_id}}async closeTab(e){await this.call("tabs.close",{tab_id:e})}async read(e,n){return this.call("page.read",{tab_id:e,mode:n?.mode??"main",...n?.query?{query:n.query}:{},...n?.budget?{budget:n.budget}:{}})}async inspect(e,n){return this.call("page.inspect",{tab_id:e,mode:n?.mode??"interactive",...n?.query?{query:n.query}:{},...n?.limit?{limit:n.limit}:{}})}async click(e,n){await this.call("page.click",{tab_id:e,element_id:n})}async fill(e,n,r){await this.call("page.fill",{tab_id:e,element_id:n,value:r})}async press(e,n,r){await this.call("page.press",{tab_id:e,key:n,...r?{element_id:r}:{}})}async select(e,n,r){await this.call("page.select",{tab_id:e,element_id:n,value:r})}async waitFor(e,n,r){await this.call("page.wait",{tab_id:e,condition:n,...r?.value?{value:r.value}:{},...r?.timeout?{timeout:r.timeout}:{}},(r?.timeout??3e4)+5e3)}async evalScript(e,n){return this.call("page.eval",{tab_id:e,script:n})}async screenshot(e){return this.call("page.screenshot",{tab_id:e})}}});function nu(t){return{id:t.id,role:t.role,label:t.label,kind:t.kind,value:t.value,state:{disabled:t.disabled,...t.checked!==void 0?{checked:t.checked}:{},...t.selected!==void 0?{selected:t.selected}:{},...t.expanded!==void 0?{expanded:t.expanded}:{}},bbox:t.bbox,...t.selector?{selector:t.selector}:{}}}function xb(t,e){switch(e.kind){case"element_id":if(t.has(e.elementId))return e.elementId;throw new Error(`Element ${e.elementId} not found in current observation. Call browser_observe to refresh.`);case"selector":return null;case"semantic":return null}}async function ru(t,e,n,r,o,s){switch(n){case"click":await t.click(e,r);break;case"fill":if(o===void 0)throw new Error("fill requires a value");await t.fill(e,r,o);break;case"press":if(o===void 0)throw new Error("press requires a value (key combo)");await t.press(e,o,r);break;case"select":if(o===void 0)throw new Error("select requires a value");await t.select(e,r,o);break;case"hover":throw new Error("hover is not supported by Agent Browser; use element_id from a prior observation to target clicks instead");case"scroll_to":{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');await t.evalScript(e,`document.querySelector('[data-element-id="${i}"]')?.scrollIntoView({behavior:'smooth',block:'center'})`);break}case"wait_for":await t.waitFor(e,"element",{value:r,timeout:s??1e4});break;default:throw new Error(`Unknown action: ${n}`)}}async function Rb(t,e){if(e.target.kind!=="semantic")throw new Error("resolveSemanticAndAct called with non-semantic target");let{elements:n}=await t.client.inspect(t.tabId,{mode:"interactive",query:e.target.text,limit:10}),r=n;if(e.target.role){let c=e.target.role.toLowerCase();r=n.filter(l=>l.role.toLowerCase()===c)}if(r.length===0)throw new Error(`No element found matching semantic target: text="${e.target.text}"`+(e.target.role?`, role="${e.target.role}"`:""));if(r.length>1)return{outcome:"ambiguous_target",query:{text:e.target.text,...e.target.role?{role:e.target.role}:{}},candidates:r.slice(0,5).map(nu)};let s=r[0].id;await ru(t.client,t.tabId,e.action,s,e.value,e.timeoutMs);let i=await t.client.read(t.tabId,{mode:"main"}),a=Ze(i.url,t.config);return a.allowed?{elementId:s}:{outcome:"blocked_by_policy",url:i.url,reason:`action navigated to blocked domain: ${a.reason}`}}var Ib=se(()=>{"use strict";Ht()});var Cb={};Os(Cb,{AgentBrowserProvider:()=>ou});var ou,Pb=se(()=>{"use strict";Ht();tu();Ab();Ib();ou=class{name="agent-browser";config;client;sessions=new Map;constructor(e,n){this.config=e,this.client=new Gi(n)}async open(e){let n=Ze(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let r=this.sessions.get(e.sessionId);if(r)await this.client.evalScript(r.tabId,`window.location.href = ${JSON.stringify(e.url)}`),await this.client.waitFor(r.tabId,"load",{timeout:e.timeoutMs??3e4});else{let{tabId:i}=await this.client.openTab(e.url);await this.client.waitFor(i,"load",{timeout:e.timeoutMs??3e4}),r={tabId:i,observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null},this.sessions.set(e.sessionId,r)}let o=await this.client.read(r.tabId,{mode:"main"}),s=Ze(o.url,this.config);return s.allowed?this.buildObservation(r,e.sessionId,e.screenshot,void 0,"browser_open"):(await this.client.evalScript(r.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`redirected to blocked domain: ${s.reason}`})}async observe(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);return this.buildObservation(n,e.sessionId,e.screenshot,e.maxElements,"browser_observe")}async act(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);let r=xb(n.knownElements,e.target);if(r===null){if(e.target.kind==="semantic"){let i=await Rb({client:this.client,config:this.config,tabId:n.tabId},e);return"outcome"in i?i:(n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString(),this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"))}throw e.target.kind==="selector"?new Error("selector targets are not supported by Agent Browser; use element_id or semantic targets"):new Error(`Cannot resolve target: ${JSON.stringify(e.target)}`)}await ru(this.client,n.tabId,e.action,r,e.value,e.timeoutMs),n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString();let o=await this.client.read(n.tabId,{mode:"main"}),s=Ze(o.url,this.config);return s.allowed?this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"):(await this.client.evalScript(n.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`action navigated to blocked domain: ${s.reason}`})}async render(e){throw new Error("AgentBrowserProvider does not support render(). Use PlaywrightProvider for one-shot content fetches.")}async screenshot(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);if(e.target!==void 0||e.fullPage)throw new Error("Agent Browser does not support element or full-page screenshots; omit target and fullPage.");let r=await this.client.screenshot(n.tabId),o=Buffer.from(r.data,"base64"),s=o.length>=24?o.readUInt32BE(16):0,i=o.length>=24?o.readUInt32BE(20):0;return{path:(await Yn(e.sessionId,o,"browser_screenshot")).path,bytes:o.length,width:s,height:i,dataBase64:r.data,mediaType:"image/png"}}async extract(e){throw new Error("AgentBrowserProvider does not support extract() yet.")}async close(e){let n=this.sessions.get(e.sessionId);if(n){try{await this.client.closeTab(n.tabId)}catch{}this.sessions.delete(e.sessionId)}}describe(e){let n=this.sessions.get(e);return n?{active:!0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:1}:null}async shutdown(){let e=Array.from(this.sessions.entries()).map(async([,n])=>{try{await this.client.closeTab(n.tabId)}catch{}});await Promise.all(e),this.sessions.clear()}async buildObservation(e,n,r,o,s="browser_open"){let[i,a]=await Promise.all([this.client.read(e.tabId,{mode:"main",budget:4e3}),this.client.inspect(e.tabId,{mode:"interactive",limit:o??80})]),c=a.elements.map(nu),l=o??80,d=c.slice(0,l);e.observationCounter+=1,e.knownElements=new Map(d.map(g=>[g.id,g])),e.currentUrl=i.url,e.currentTitle=i.title;let u=[];c.length>l&&u.push(`page has ${c.length} interactive elements; showing first ${l}`);let p=null;if(r)try{let g=await this.client.screenshot(e.tabId),h=Buffer.from(g.data,"base64");p=(await Yn(n,h,s)).path}catch{u.push("screenshot capture failed")}let f=`obs_${e.observationCounter.toString(36)}`,m={httpStatus:null,loadingState:"idle",hasDialog:!1,consoleErrors:0};return{observationId:f,url:i.url,title:i.title,textSummary:i.content.slice(0,4e3),interactive:d,status:m,warnings:u,screenshotPath:p,capturedAt:new Date().toISOString()}}}});import{existsSync as RF,readFileSync as IF}from"node:fs";import{createRequire as CF}from"node:module";import{dirname as PF,join as MF}from"node:path";function Db(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<DF&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function Re(t){let e=Db(t);return Ob.some(n=>e.includes(n))}function FF(){try{let e=CF(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(IF(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=MF(PF(e),o);return RF(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function Po(){return Mb??=FF()??OF,Mb}function su(t){return t.includes("install chromium")}function Ke(t,e){let n=Db(t),r=e?.latched===!0?` ${LF}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${Po()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Po()}). Or pick a different tool.${r}`}function Xi(t,e,n=!1){if(!Re(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
3
3
|
|
|
4
|
-
${Ke(t,{headless:e,latched:n})}`,{cause:t})}var Ob,OF,DF,Mb,LF,iu=se(()=>{"use strict";Ob=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],OF="pnpm exec playwright install chromium",DF=4;LF="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import hn from"node:fs";import zi from"node:path";import{randomBytes as NF}from"node:crypto";function UF(){try{return"5.185.0"}catch{}try{let t=zi.resolve(import.meta.dirname,"../../../package.json"),e=hn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var $F,Ji,Fb=se(()=>{"use strict";iu();M();J();$F=UF(),Ji=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=Xi(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Xi(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),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;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{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",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),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){this.clearLaunchFailure();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.clearLaunchFailure(),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/${$F}`}}loadStorageState(e){let n=Ll(e);try{if(!hn.existsSync(n))return;let r=JSON.parse(hn.readFileSync(n,"utf8"));return P("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){P("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ll(e);if(!hn.existsSync(r))return;let o=await n.storageState(),s=zi.join(zi.dirname(r),`.${zi.basename(r)}.${process.pid}.${NF(4).toString("hex")}.tmp`);hn.writeFileSync(s,JSON.stringify(o),{mode:384}),hn.chmodSync(s,384),hn.renameSync(s,r),P("[browser/vault] saved session",{profile:e,file:r})}catch(r){P("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as BF}from"node:crypto";function jF(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function HF(t,e,n){return`el_${BF("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function WF(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Lb(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Ub(t,e){let n=t.role??"",r=t.name??"";Nb.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Ub(s,e)}async function KF(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},$b).catch(()=>[])}async function qF(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},$b).catch(()=>[])}function GF(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Vi(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=GF(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=KF(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),h,y=!1;u!==null?(h=[],Ub(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await qF(t)).filter(D=>Nb.has(D.role??"")));let w=new Map;for(let R of p){let D=Lb(R.name),G=w.get(D);(!G||G.bbox.w===0&&R.bbox.w>0)&&w.set(D,R)}let k=h.map(R=>({ax:R,dom:w.get(Lb(R.name??""))})),v=r?k:k.filter(R=>R.dom?R.dom.bbox.w>0||R.dom.bbox.h>0:!0);v.sort((R,D)=>{let G=R.dom?.bbox.y??0,F=D.dom?.bbox.y??0;if(G!==F)return G-F;let N=R.dom?.bbox.x??0,O=D.dom?.bbox.x??0;return N-O}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=v.slice(0,n).map((R,D)=>{let G=R.ax.role??"generic",F=R.ax.name??"",N=HF(G,F,D),O=R.dom?.bbox??{x:0,y:0,w:0,h:0},U=R.dom?.type??null,q=null;R.ax.value!==void 0&&R.ax.value!==null&&(q=String(R.ax.value)),R.ax.checked!==void 0&&(q=String(R.ax.checked)),vb({role:G,kind:U})&&(q="[redacted]");let H={disabled:R.ax.disabled??!1};R.ax.checked!==void 0&&(H.checked=R.ax.checked===!0||R.ax.checked==="mixed"),R.ax.selected!==void 0&&(H.selected=R.ax.selected),R.ax.expanded!==void 0&&(H.expanded=R.ax.expanded);let de;R.dom?.testId?de=`[data-testid="${R.dom.testId}"]`:R.dom?.id&&(de=`#${R.dom.id}`);let ft={id:N,role:G,label:jF(F),kind:U,value:q,state:H,bbox:O};return de!==void 0&&(ft.selector=de),ft}),T="idle";try{let R=await t.evaluate(()=>document.readyState);R==="loading"?T="loading":R==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=WF(f),S=`obs_${e.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:S,url:m,title:g,textSummary:I,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:T,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:A}}var Nb,$b,Bb=se(()=>{"use strict";qi();Nb=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);$b="a[href], button, input, select, textarea, [role], [tabindex], label"});async function jb(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function au(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>jb(t,s)))).filter(o=>o!==null)}async function XF(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function cu(t,e,n){switch(e.kind){case"element_id":return zF(t,e,n);case"selector":return JF(t,e);case"semantic":return VF(t,e)}}async function zF(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await au(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function JF(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 au(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function VF(t,e){return e.role!==void 0?YF(t,e.text,e.role):QF(t,e.text,e)}async function YF(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 au(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function QF(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await XF(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 y=await jb(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,k=0;for(let v=0;v<w.length;v++)k=k*31+w.charCodeAt(v)>>>0;f.push({...y,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Hb=se(()=>{"use strict"});async function lu(t,e,n,r){let o=t.url();if(o===n)return null;let s=Ze(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var Wb=se(()=>{"use strict";Ht()});var uu={};Os(uu,{PlaywrightProvider:()=>du});function Kb(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 du,pu=se(()=>{"use strict";Fb();Bb();Hb();Ht();Wb();tu();du=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Ji(e)}async open(e){let n=Ze(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(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await lu(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await Vi(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,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}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 Vi(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 cu(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Kb(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){l=h}else l=g}let u=await lu(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Vi(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),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}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 cu(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Kb(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 Yn(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Yn(n,o,r);return s}catch{return null}}}});var bn={};Os(bn,{__resetBrowserRegistryForTests:()=>oL,browserProviderActive:()=>tL,closeBrowserProvider:()=>mu,getBrowserProvider:()=>eL,getLastRoutingDecision:()=>rL,peekBrowserProvider:()=>nL});function qb(){Promise.resolve(mu()).then(()=>{process.exit(130)})}function Gb(){Promise.resolve(mu()).then(()=>{process.exit(143)})}function Xb(){it=null}function ZF(){Yi||(process.on("SIGINT",qb),process.on("SIGTERM",Gb),process.on("exit",Xb),Yi=!0)}function zb(){Yi&&(process.removeListener("SIGINT",qb),process.removeListener("SIGTERM",Gb),process.removeListener("exit",Xb),Yi=!1)}async function eL(t){return it!==null?it:(yn!==null||(yn=(async()=>{let e=Yd(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??b.AGENT_SURFACE,r=await Sb({config:e,surface:n});fu=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(Pb(),Cb)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(pu(),uu));o=new s(e)}return ZF(),it=o,yn=null,o})()),yn)}async function mu(){if(it===null)return;let t=it;it=null,yn=null,zb(),await t.shutdown()}function tL(){return it!==null}function nL(){return it}function rL(){return fu}function oL(){it=null,yn=null,fu=null,zb()}var it,yn,Yi,fu,wn=se(()=>{"use strict";Ht();kb();C();it=null,yn=null,Yi=!1,fu=null});J();C();M();import{randomBytes as pI}from"node:crypto";import{mkdir as fI,writeFile as mI}from"node:fs/promises";import{join as gI}from"node:path";J();var QR=256,Mm=new WeakMap,Kr=new Map;function ZR(t){return t instanceof Error?t.message:String(t)}function eI(t,e){if(typeof e=="object"&&e!==null){let r=Mm.get(e);return r||(r=new Set,Mm.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(Kr.has(n))return!1;if(Kr.set(n,!0),Kr.size>QR){let r=Kr.keys().next().value;r!==void 0&&Kr.delete(r)}return!0}function ue(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${ZR(r)}`;if(!eI(t,e)){P(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}C();import{mkdirSync as nI,appendFileSync as rI,existsSync as oI}from"fs";import{resolve as sI}from"path";import{dirname as iI}from"path";function et(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>Nl(e)||tI(e)?e:"[REDACTED]")}function Nl(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function tI(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var aI=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
4
|
+
${Ke(t,{headless:e,latched:n})}`,{cause:t})}var Ob,OF,DF,Mb,LF,iu=se(()=>{"use strict";Ob=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],OF="pnpm exec playwright install chromium",DF=4;LF="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import hn from"node:fs";import zi from"node:path";import{randomBytes as NF}from"node:crypto";function UF(){try{return"5.186.0"}catch{}try{let t=zi.resolve(import.meta.dirname,"../../../package.json"),e=hn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var $F,Ji,Fb=se(()=>{"use strict";iu();M();J();$F=UF(),Ji=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=Xi(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=Xi(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),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;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{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",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),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){this.clearLaunchFailure();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.clearLaunchFailure(),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/${$F}`}}loadStorageState(e){let n=Ll(e);try{if(!hn.existsSync(n))return;let r=JSON.parse(hn.readFileSync(n,"utf8"));return P("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){P("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ll(e);if(!hn.existsSync(r))return;let o=await n.storageState(),s=zi.join(zi.dirname(r),`.${zi.basename(r)}.${process.pid}.${NF(4).toString("hex")}.tmp`);hn.writeFileSync(s,JSON.stringify(o),{mode:384}),hn.chmodSync(s,384),hn.renameSync(s,r),P("[browser/vault] saved session",{profile:e,file:r})}catch(r){P("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as BF}from"node:crypto";function jF(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function HF(t,e,n){return`el_${BF("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function WF(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Lb(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Ub(t,e){let n=t.role??"",r=t.name??"";Nb.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Ub(s,e)}async function KF(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},$b).catch(()=>[])}async function qF(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},$b).catch(()=>[])}function GF(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Vi(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=GF(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=KF(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),h,y=!1;u!==null?(h=[],Ub(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await qF(t)).filter(D=>Nb.has(D.role??"")));let w=new Map;for(let R of p){let D=Lb(R.name),G=w.get(D);(!G||G.bbox.w===0&&R.bbox.w>0)&&w.set(D,R)}let S=h.map(R=>({ax:R,dom:w.get(Lb(R.name??""))})),v=r?S:S.filter(R=>R.dom?R.dom.bbox.w>0||R.dom.bbox.h>0:!0);v.sort((R,D)=>{let G=R.dom?.bbox.y??0,F=D.dom?.bbox.y??0;if(G!==F)return G-F;let N=R.dom?.bbox.x??0,O=D.dom?.bbox.x??0;return N-O}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=v.slice(0,n).map((R,D)=>{let G=R.ax.role??"generic",F=R.ax.name??"",N=HF(G,F,D),O=R.dom?.bbox??{x:0,y:0,w:0,h:0},U=R.dom?.type??null,q=null;R.ax.value!==void 0&&R.ax.value!==null&&(q=String(R.ax.value)),R.ax.checked!==void 0&&(q=String(R.ax.checked)),vb({role:G,kind:U})&&(q="[redacted]");let H={disabled:R.ax.disabled??!1};R.ax.checked!==void 0&&(H.checked=R.ax.checked===!0||R.ax.checked==="mixed"),R.ax.selected!==void 0&&(H.selected=R.ax.selected),R.ax.expanded!==void 0&&(H.expanded=R.ax.expanded);let de;R.dom?.testId?de=`[data-testid="${R.dom.testId}"]`:R.dom?.id&&(de=`#${R.dom.id}`);let ft={id:N,role:G,label:jF(F),kind:U,value:q,state:H,bbox:O};return de!==void 0&&(ft.selector=de),ft}),T="idle";try{let R=await t.evaluate(()=>document.readyState);R==="loading"?T="loading":R==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=WF(f),k=`obs_${e.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:k,url:m,title:g,textSummary:I,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:T,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:A}}var Nb,$b,Bb=se(()=>{"use strict";qi();Nb=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);$b="a[href], button, input, select, textarea, [role], [tabindex], label"});async function jb(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function au(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>jb(t,s)))).filter(o=>o!==null)}async function XF(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function cu(t,e,n){switch(e.kind){case"element_id":return zF(t,e,n);case"selector":return JF(t,e);case"semantic":return VF(t,e)}}async function zF(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await au(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function JF(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 au(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function VF(t,e){return e.role!==void 0?YF(t,e.text,e.role):QF(t,e.text,e)}async function YF(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 au(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function QF(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await XF(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 y=await jb(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,S=0;for(let v=0;v<w.length;v++)S=S*31+w.charCodeAt(v)>>>0;f.push({...y,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Hb=se(()=>{"use strict"});async function lu(t,e,n,r){let o=t.url();if(o===n)return null;let s=Ze(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var Wb=se(()=>{"use strict";Ht()});var uu={};Os(uu,{PlaywrightProvider:()=>du});function Kb(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 du,pu=se(()=>{"use strict";Fb();Bb();Hb();Ht();Wb();tu();du=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Ji(e)}async open(e){let n=Ze(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(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await lu(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await Vi(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,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}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 Vi(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 cu(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Kb(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){l=h}else l=g}let u=await lu(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Vi(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),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}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 cu(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Kb(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 Yn(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Yn(n,o,r);return s}catch{return null}}}});var bn={};Os(bn,{__resetBrowserRegistryForTests:()=>oL,browserProviderActive:()=>tL,closeBrowserProvider:()=>mu,getBrowserProvider:()=>eL,getLastRoutingDecision:()=>rL,peekBrowserProvider:()=>nL});function qb(){Promise.resolve(mu()).then(()=>{process.exit(130)})}function Gb(){Promise.resolve(mu()).then(()=>{process.exit(143)})}function Xb(){it=null}function ZF(){Yi||(process.on("SIGINT",qb),process.on("SIGTERM",Gb),process.on("exit",Xb),Yi=!0)}function zb(){Yi&&(process.removeListener("SIGINT",qb),process.removeListener("SIGTERM",Gb),process.removeListener("exit",Xb),Yi=!1)}async function eL(t){return it!==null?it:(yn!==null||(yn=(async()=>{let e=Yd(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??b.AGENT_SURFACE,r=await Sb({config:e,surface:n});fu=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(Pb(),Cb)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(pu(),uu));o=new s(e)}return ZF(),it=o,yn=null,o})()),yn)}async function mu(){if(it===null)return;let t=it;it=null,yn=null,zb(),await t.shutdown()}function tL(){return it!==null}function nL(){return it}function rL(){return fu}function oL(){it=null,yn=null,fu=null,zb()}var it,yn,Yi,fu,wn=se(()=>{"use strict";Ht();kb();C();it=null,yn=null,Yi=!1,fu=null});J();C();M();import{randomBytes as pI}from"node:crypto";import{mkdir as fI,writeFile as mI}from"node:fs/promises";import{join as gI}from"node:path";J();var QR=256,Mm=new WeakMap,Kr=new Map;function ZR(t){return t instanceof Error?t.message:String(t)}function eI(t,e){if(typeof e=="object"&&e!==null){let r=Mm.get(e);return r||(r=new Set,Mm.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(Kr.has(n))return!1;if(Kr.set(n,!0),Kr.size>QR){let r=Kr.keys().next().value;r!==void 0&&Kr.delete(r)}return!0}function ue(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${ZR(r)}`;if(!eI(t,e)){P(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}C();import{mkdirSync as nI,appendFileSync as rI,existsSync as oI}from"fs";import{resolve as sI}from"path";import{dirname as iI}from"path";function et(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>Nl(e)||tI(e)?e:"[REDACTED]")}function Nl(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function tI(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var aI=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
5
5
|
`,cI=/key|token|secret|password|credential|auth/i;function Om(t){let e=t[1],n=t[2],r=n[0],o=(r==='"'||r==="'")&&n.at(-1)===r?n.slice(1,-1):n,s=/(?:^|_)(?:PATH|FILE)(?:_|$)/i.test(e),i=o.startsWith("/")||o.startsWith("~/"),c=o.split("/").filter(Boolean).some(l=>/[A-Z0-9.\-]/.test(l));return s&&i&&c&&Nl(o)?`${e}=${n}`:`${e}=<REDACTED length=${n.length}>`}var lI=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,t=>`<REDACTED sk-ant length=${t[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,t=>`<REDACTED sk- length=${t[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,t=>`<REDACTED Bearer length=${t[0].length}>`],[/AKIA[A-Z0-9]{16}/g,t=>`<REDACTED AKIA length=${t[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,t=>`<REDACTED xox token length=${t[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,t=>`<REDACTED Telegram token length=${t[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,Om],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,Om]];function qr(t){let e=t;for(let[n,r]of lI)e=e.replace(n,(...o)=>{let s=o.slice(0,o.length-2);return r(s)});return e}function Ul(t){return typeof t=="string"?qr(t):Array.isArray(t)?t.map(Ul):t}function dI(t){if(t===null||typeof t!="object")return t;let e=t,n={...e},r=e.env;if(r&&typeof r=="object"){let o={};for(let[s,i]of Object.entries(r))cI.test(s)&&typeof i=="string"?o[s]=`<REDACTED length=${i.length}>`:o[s]=i;n.env=o}return"system"in e&&(n.system=Ul(e.system)),"systemPrompt"in e&&(n.systemPrompt=Ul(e.systemPrompt)),n}function uI(t){if(t==null)return{kind:"undefined",note:"SDK uses minimal prompt; claude_code preset NOT loaded"};if(typeof t=="string")return{kind:"custom-string",note:"SDK uses this string as full system prompt; claude_code preset NOT loaded"};if(Array.isArray(t))return{kind:"custom-string-array",note:"SDK uses array as full system prompt with cache boundaries; claude_code preset NOT loaded"};if(typeof t=="object"){let e=t;if(e.type==="preset"&&e.preset==="claude_code"){let n={kind:"preset-claude-code",note:"claude_code preset loaded"};return typeof e.append=="string"&&(n.append={length:e.append.length}),e.excludeDynamicSections===!0&&(n.excludeDynamicSections=!0),n}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}function Dm(t){let e=b.AFK_DUMP_PROMPT;if(!e||e===""||e==="0"||e.toLowerCase()==="false")return;process.stderr.write(`[--dump-prompt] WARNING: dump may contain secrets from system prompt or messages. Inspect before sharing.
|
|
6
6
|
`);let n=t.options,r=typeof n=="object"&&n!==null?n.systemPrompt:void 0,o=uI(r),s={timestamp:new Date().toISOString(),prompt:t.prompt,options:dI(t.options),provenance:t.provenance,resolution:o};if(e==="1"||e.toLowerCase()==="true"||e.toLowerCase()==="stderr"){let c=JSON.stringify(s,null,2)+`
|
|
7
7
|
`;process.stderr.write(c);return}let i=sI(e),a=iI(i);try{nI(a,{recursive:!0});let l=(!oI(i)?aI:"")+JSON.stringify(s)+`
|
|
@@ -25,7 +25,7 @@ ${r}
|
|
|
25
25
|
### end \xB7 ${e.reason??"unknown"} \xB7 ${n}
|
|
26
26
|
`}function Bm(t){if(!_I(t))return null;let e=Em(t.sessionId),n=vI(e,`${EI(t.subagentId)}.md`),r=[],o=0,s=!1,i=!1,a=!1,c=Promise.resolve(),l=u=>{if(s)return;o>=Um&&(s=!0,u=`
|
|
27
27
|
<!-- CAP REACHED at ${Um} bytes \u2014 capture stopped -->
|
|
28
|
-
`),o+=Buffer.byteLength(u,"utf8");let p=i?u:`${AI(t)}${u}`;i=!0,c=c.then(async()=>{await kI(e,{recursive:!0,mode:448}),await SI(n,p,{encoding:"utf8",mode:384})}).catch(f=>{ue("subagent-output-capture",t.sessionId??"unknown","write",f)})},d=()=>{if(r.length===0)return;let u=r.join("").trim();r=[],u.length>0&&(l(Gs("say",{text:u})),a=!0)};return{observe(u){try{if(u.type==="chunk"){let p=u.chunk;if(p.type==="content"){r.push(p.content);return}if(p.type==="tool_use_detail"){if(p.pending)return;d(),l(Gs("tool",{toolName:p.toolName,toolInput:p.toolInputCapture??p.toolInputRaw??p.toolInput}))}return}if(u.type==="message"){if(!a&&r.length===0){let p=u.message.content.trim();p.length>0&&(l(Gs("say",{text:p})),a=!0)}return}(u.type==="done"||u.type==="error")&&(d(),a=!1)}catch(p){ue("subagent-output-capture",t.sessionId??"unknown","observe",p)}},end(u){try{d(),l(Gs("end",{reason:u}))}catch(p){ue("subagent-output-capture",t.sessionId??"unknown","end",p)}}}}var Fe=class extends Error{constructor(e){super(e),this.name="AbortError"}},_e=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Xs=class extends _e{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},W=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),s?.injectContext!==void 0&&(this.injectContext=s.injectContext)}event;reason;cause;injectContext},Le=class extends Error{toolResultsGathered;constructor(e){super(e),this.name="StreamIncompleteError"}},tt=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},On=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}};var zs=class{subscribers=new Set;closed=!1;push(e){for(let n of this.subscribers)if(n.resolve){let r=n.resolve;n.resolve=null,r({value:e,done:!1})}else n.buffer.push(e)}close(){this.closed=!0;for(let e of this.subscribers)if(e.resolve){let n=e.resolve;e.resolve=null,n({value:void 0,done:!0})}}subscribe(){let e={buffer:[],resolve:null};this.subscribers.add(e);let n=this,r={next(){return e.buffer.length>0?Promise.resolve({value:e.buffer.shift(),done:!1}):n.closed?(n.subscribers.delete(e),Promise.resolve({value:void 0,done:!0})):new Promise(o=>{e.resolve=o})},return(){if(e.resolve){let o=e.resolve;e.resolve=null,o({value:void 0,done:!0})}return n.subscribers.delete(e),Promise.resolve({value:void 0,done:!0})}};return{[Symbol.asyncIterator]:()=>r}}};async function nn(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){ue("trace.emit",t,"tool_call",n)}}async function Mt(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){ue("trace.emit",t,"hook_decision",n)}}async function rn(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){ue("trace.emit",t,"subagent_lifecycle",n)}}async function jm(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){ue("trace.emit",t,"budget",n)}}async function Hm(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){ue("trace.emit",t,"abort",n)}}async function Js(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){ue("trace.emit",t,"compaction",n)}}async function Wm(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){ue("trace.emit",t,"closure",n)}}async function ae(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){ue("trace.emit",t,"browser_event",n)}}async function Bl(t,e){if(t)try{await t.write({kind:"queued_user_message",payload:e})}catch(n){ue("trace.emit",t,"queued_user_message",n)}}async function $(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){ue("trace.emit",t,"session_phase",n)}}import NI from"@anthropic-ai/sdk";var xI="fast-mode-2026-02-01";function Km(t){let e=[...t.oauthEntries??[],...t.effort?[t.effortEntry]:[],...t.extendedCacheTtl?[t.extendedCacheEntry]:[],...t.fast?[xI]:[]].filter(Boolean);return[...new Set(e)].join(",")||void 0}var qm="extended-cache-ttl-2025-04-11",RI=`claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,${qm}`,II="effort-2025-11-24",CI="claude-cli/1.0.0 (external, cli)",PI="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function Vs(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Gr(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 Ot(t,e,n,r,o,s){let i=Km({oauthEntries:t==="oauth"?RI.split(","):[],effort:t==="oauth"&&r===!0,extendedCacheTtl:o,fast:s,effortEntry:II,extendedCacheEntry:qm});return t!=="oauth"?i?{"anthropic-beta":i}:{}:{"anthropic-beta":i,"x-app":"cli","User-Agent":CI,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Gm(t){return t!=="oauth"?null:[{type:"text",text:PI}]}C();var zr=["local","small","medium","large"],zm="claude-haiku-4-5-20251001",Xr="claude-sonnet-4-6",Hl="claude-opus-5",Kl="claude-fable-5",MI="grok-4.6",on={local:{id:""},small:{id:zm},medium:{id:Xr},large:{id:Hl}},Jm="auto",ql={opus:Hl,opus_1m:Hl,sonnet:Xr,sonnet_1m:Xr,haiku:zm,fable:Kl,grok:MI},OI=["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-5.5"],sn=[...zr,...Object.keys(ql),...OI],Wl;function Gl(t){Wl=t}function jl(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function Ys(t,e,n){let r={},o=jl(t);o&&(r.id=o);let s=jl(e);s&&(r.baseUrl=s);let i=jl(n);return i&&(r.apiKey=i),r}function DI(){return{local:Ys(b.AFK_MODEL_LOCAL,b.AFK_MODEL_LOCAL_BASE_URL,b.AFK_MODEL_LOCAL_API_KEY),small:Ys(b.AFK_MODEL_SMALL,b.AFK_MODEL_SMALL_BASE_URL,b.AFK_MODEL_SMALL_API_KEY),medium:Ys(b.AFK_MODEL_MEDIUM,b.AFK_MODEL_MEDIUM_BASE_URL,b.AFK_MODEL_MEDIUM_API_KEY),large:Ys(b.AFK_MODEL_LARGE,b.AFK_MODEL_LARGE_BASE_URL,b.AFK_MODEL_LARGE_API_KEY)}}function Vm(t){let e=DI(),n={};for(let r of zr){let o=on[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function Fn(t){return t||Wl||Vm()}function Ln(t,e=Fn()){let n=t.trim().toLowerCase();if(!(!n||n===Jm)){for(let r of zr){let o=e[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function an(t,e=Fn()){if(t===void 0)return{id:""};let n=Ln(t,e);if(n)return e[n];let r=ql[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function nt(t,e=Fn()){if(t!==void 0)return an(t,e).id}function Ym(t,e=Fn()){if(t===void 0)return;let n=Ln(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 Qm(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of zr){let o=LI(n[r]);o&&(e[r]=o)}return e}function Zm(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";if(e==="chatgpt-oauth"||e==="chatgpt")return"chatgpt-oauth";if(e==="xai")return"xai";if(e==="xai-oauth"||e==="xai_oauth")return"xai-oauth"}function Dn(t){return typeof t=="string"?t.trim():""}function Xm(t){return/[\x00-\x1f\x7f]/.test(t)}var FI=new Set([...zr,Jm,...Object.keys(ql)]);function LI(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=Dn(e.id);if(!n)return;let r={id:n},o=Dn(e.name);o&&(r.name=o);let s=Zm(e.provider);s&&(r.provider=s);let i=Dn(e.baseUrl);i&&(r.baseUrl=i);let a=Dn(e.apiKey);return a&&(r.apiKey=a),r}}function eg(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=Dn(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(Xm(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=Dn(e.name);if(o){if(Xm(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(FI.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=Zm(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 Xl={opus:on.large.id,opus_1m:on.large.id,sonnet:on.medium.id,sonnet_1m:on.medium.id,haiku:on.small.id,fable:Kl};function Qs(t){return t in Xl}function he(t){return nt(t)}import{randomUUID as tg}from"node:crypto";async function ng(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=Vs(e),l=Gr(e,c),d=a?a(l):new NI(l),u=tg(),p=tg(),f=Ot(c,u,p),m=he(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),y=[];for(let k of h.content)k.type==="text"&&y.push(k.text);let w=y.join("").trim();return w.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),w}C();var UI=new Set(["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4-turbo","o1","o3","o4-mini"]),$I=[/^claude-/i,/^gpt-4o/i,/^gpt-4\.1/i,/^gpt-4-turbo/i,/^gpt-4-vision/i,/^gpt-5/i,/(?:^|[/_-])(?:vl|vlm)(?:[/_.-]|$)/i,/(?:^|[/_-])(?:llava|pixtral|internvl|cogvlm|idefics|moondream|janus)/i,/(?:vision|minicpm-?[vo]|qwen[\d.]*-?vl|llama-?3\.2-\d+b-vision|gemma-3|phi-3\.5-vision|phi-4-multimodal)/i];function BI(){let t=b.AFK_VISION_MODELS,e=[],n=[];if(t)for(let r of t.split(",")){let o=r.trim().toLowerCase();if(o)if(o.startsWith("!")){let s=o.slice(1).trim();s&&n.push(s)}else e.push(o)}return{enable:e,disable:n}}function rg(t,e){return t===e||t.includes(e)}function zl(t){if(!t)return!1;let e=(nt(t)??t).trim();if(!e)return!1;let n=e.toLowerCase(),{enable:r,disable:o}=BI();return o.some(s=>rg(n,s))?!1:r.some(s=>rg(n,s))||UI.has(n)?!0:$I.some(s=>s.test(e))}function og(t){let e=t.trim().toLowerCase();return e.includes("/")?e.slice(e.lastIndexOf("/")+1):e}function cn(t){return t?/^o[0-9]/.test(og(t)):!1}var jI=[/^gpt-5/];function Jr(t){if(!t)return!1;if(cn(t))return!0;let e=og(t);return jI.some(n=>n.test(e))}var Jl={opus:128e3,opus_1m:128e3,sonnet:128e3,sonnet_1m:128e3,haiku:64e3,fable:128e3,"claude-opus-5":128e3,"claude-opus-4-8":128e3,"claude-opus-4-7":128e3,"claude-opus-4-6":128e3,"claude-sonnet-5":128e3,"claude-sonnet-4-6":128e3,"claude-haiku-4-5-20251001":64e3,"claude-fable-5":128e3,"gpt-5.5":128e3,"gpt-5.6":128e3,"gpt-5.6-sol":128e3,"gpt-5.6-terra":128e3,"gpt-5.6-luna":128e3},HI=64e3;function Yl(t){let e=String(t).trim().toLowerCase(),n=Jl[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=nt(t)??String(t);return Jl[r]??Jl[r.toLowerCase()]}function Nn(t){return Yl(t)??HI}var Vl={opus:1e6,opus_1m:1e6,sonnet:1e6,sonnet_1m:1e6,haiku:2e5,fable:1e6,"claude-fable-5":1e6,"claude-sonnet-5":1e6,"claude-opus-5":1e6,"claude-opus-4-8":1e6,"claude-opus-4-7":1e6,"claude-opus-4-6":1e6,"claude-sonnet-4-6":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4.1":1e6,"gpt-4.1-mini":1e6,"gpt-5.5":1e6,"gpt-5.6":1e6,"gpt-5.6-sol":1e6,"gpt-5.6-terra":1e6,"gpt-5.6-luna":1e6,o1:2e5,"o1-mini":128e3,o3:2e5,"o3-mini":2e5,"o4-mini":2e5,"mlx-community/qwen3-30b-a3b-4bit":128e3,"mlx-community/qwen3-32b-4bit":128e3,"mlx-community/qwen2.5-coder-32b-instruct-4bit":131072,"grok-4.6":5e5,"grok-4.5":5e5,"grok-4.3":1e6,"grok-4.20-0309-reasoning":1e6,"grok-4.20-0309-non-reasoning":1e6,"grok-4.20-multi-agent-0309":1e6,"grok-build-0.1":256e3},WI=2e5,KI=262144;function qI(t){if(!t)return!1;let e=t.trim().toLowerCase();return e?!!(e.includes("/")||e.startsWith("gpt-")||e.startsWith("gpt_")||cn(e)||e.startsWith("codex-")||e.startsWith("codex_")||e==="codex"||e==="grok"||e.startsWith("grok-")||e.startsWith("grok_")):!1}function Ve(t){let e=String(t).trim().toLowerCase(),n=Vl[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=nt(t)??String(t),o=Vl[r]??Vl[r.toLowerCase()];return o!==void 0?o:qI(r)?KI:WI}var sg={"claude-sonnet-5":2e5,"claude-opus-5":2e5,"claude-sonnet-4-6":2e5,"claude-opus-4-8":2e5,"claude-opus-4-7":2e5,"claude-opus-4-6":2e5};function mt(t){let e=Ve(t);if(String(t).trim().toLowerCase().endsWith("_1m"))return e;let r=nt(t)??String(t),o=sg[r]??sg[r.toLowerCase()];return o!==void 0?Math.min(e,o):e}function ig(t){return(t.inputTokens??0)+(t.outputTokens??0)}function pe(t){return t.contextWindowTokens??ig(t)}function Vr(t){return t?{totalTokens:pe(t),apiUsage:{input_tokens:t.inputTokens??0,output_tokens:t.outputTokens??0,cache_read_input_tokens:t.cachedInputTokens??0,cache_creation_input_tokens:t.cacheCreationTokens??0,context_window_tokens:pe(t)}}:{totalTokens:0,apiUsage:null}}function Yr(t,e,n){return e<=0||t<=0||n<=0||n>=1?!1:t/e>=n}function Qr(t,e){return e<=0||t<=0?0:t/e}var Zs=.9,GI=.04;function ag(t){let e=Ve(t),n=mt(t),r=Nn(t);if(e<=0||r<=0||n<e)return Zs;let o=(e-r)/e-GI;return o>0?o:Zs}function Zr(t,e,n,r){if(t<=0||n<=0||e<=0)return;let o=t+e;if(!(o<=n))throw new Error(`[afk] Context-window overflow: the conversation already used ~${t.toLocaleString()} tokens (last-turn API count) and the configured output ceiling is ${e.toLocaleString()} tokens \u2014 together they exceed the ${r} context window of ${n.toLocaleString()} tokens by ${(o-n).toLocaleString()} tokens. The provider would reject this request with HTTP 400. To continue: run /compact to summarise the conversation history, or start a new session.`)}function eo(t,e){if(t===void 0||t===!1)return;let n=e!==void 0?ag(e):1;if(t===!0)return Math.min(Zs,n);let r=t.threshold;if(!(typeof r!="number"||!Number.isFinite(r)||r<=0||r>=1))return Math.min(r,n)}var XI=t=>/opus-4-(7|[89])/.test(t),zI=t=>XI(t)||/(claude-)?(opus|sonnet)-5/.test(t),ti=new Set,cg=new Set,ei=1;function lg(t){if(t!==void 0&&!(!Number.isFinite(t)||t<0)){if(t>ei){let e=`temp:${t}`;return cg.has(e)||(cg.add(e),console.warn(`[afk] temperature ${t} exceeds the Anthropic maximum (${ei}); clamping to ${ei}.`)),ei}return t}}var JI=.25;function ni(t,e){let n=Nn(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 ti.has(s)||(ti.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function dg(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 ri(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&zI(n))return{type:"adaptive",display:"summarized"};if(e<=1024)throw new Error(`[afk] Extended thinking requires max_tokens > 1024 (the API constraint is 1024 <= budget_tokens < max_tokens), but the resolved output cap is ${e}. Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS above 1024, or disable thinking with --thinking disabled.`);let r=Math.floor(e*JI),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}`;ti.has(a)||(ti.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 oi(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-(4-[678]|5)/.test(n))return"max"}M();import Ql from"path";import{dirname as VI}from"path";import{appendFileSync as YI,mkdirSync as QI}from"fs";var Dt=class{hooks;constructor(e){this.hooks=e}addReadRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots();if(!o)return;let s=Ql.resolve(e);o.includes(s)||(o.push(s),this.appendAuditLog({action:"grant-read",path:s,source:n,sessionId:r}))}addWriteRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots(),s=this.hooks.getWriteRoots();if(!o||!s)return;let i=Ql.resolve(e);o.includes(i)||o.push(i),s.includes(i)||(s.push(i),this.appendAuditLog({action:"grant-write",path:i,source:n,sessionId:r}))}revokeRoot(e,n="slash",r){let o=this.hooks.getReadRoots();if(!o)return;let s=Ql.resolve(e),i=this.hooks.getProtectedRoot();if(i!==void 0&&s===i)return;let a=o.indexOf(s),c=a!==-1;c&&o.splice(a,1);let l=this.hooks.getWriteRoots(),d=!1;if(l){let u=l.indexOf(s);d=u!==-1,d&&l.splice(u,1)}(c||d)&&this.appendAuditLog({action:"revoke",path:s,source:n,sessionId:r})}getGrants(){return{resolveBase:this.hooks.getDisplayResolveBase?this.hooks.getDisplayResolveBase():this.hooks.getProtectedRoot(),readRoots:this.hooks.getReadRoots()?.slice()??[],writeRoots:this.hooks.getWriteRoots()?.slice()??[],allowAll:this.hooks.getAllowAll()}}appendAuditLog(e){try{let n=Bs();QI(VI(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??this.hooks.getDefaultSessionId?.()??null,action:e.action,path:e.path,source:e.source});YI(n,r+`
|
|
28
|
+
`),o+=Buffer.byteLength(u,"utf8");let p=i?u:`${AI(t)}${u}`;i=!0,c=c.then(async()=>{await kI(e,{recursive:!0,mode:448}),await SI(n,p,{encoding:"utf8",mode:384})}).catch(f=>{ue("subagent-output-capture",t.sessionId??"unknown","write",f)})},d=()=>{if(r.length===0)return;let u=r.join("").trim();r=[],u.length>0&&(l(Gs("say",{text:u})),a=!0)};return{observe(u){try{if(u.type==="chunk"){let p=u.chunk;if(p.type==="content"){r.push(p.content);return}if(p.type==="tool_use_detail"){if(p.pending)return;d(),l(Gs("tool",{toolName:p.toolName,toolInput:p.toolInputCapture??p.toolInputRaw??p.toolInput}))}return}if(u.type==="message"){if(!a&&r.length===0){let p=u.message.content.trim();p.length>0&&(l(Gs("say",{text:p})),a=!0)}return}(u.type==="done"||u.type==="error")&&(d(),a=!1)}catch(p){ue("subagent-output-capture",t.sessionId??"unknown","observe",p)}},end(u){try{d(),l(Gs("end",{reason:u}))}catch(p){ue("subagent-output-capture",t.sessionId??"unknown","end",p)}}}}var Fe=class extends Error{constructor(e){super(e),this.name="AbortError"}},_e=class extends Error{constructor(n,r){super(n);this.timeoutMs=r;this.name="TimeoutError"}timeoutMs},Xs=class extends _e{constructor(e,n){super(e,n),this.name="IdleWatchdogError"}},W=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),s?.injectContext!==void 0&&(this.injectContext=s.injectContext)}event;reason;cause;injectContext},Le=class extends Error{toolResultsGathered;constructor(e){super(e),this.name="StreamIncompleteError"}},tt=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},On=class extends Error{constructor(e){super(e),this.name="DenialCircuitBreakerError"}};var zs=class{subscribers=new Set;closed=!1;push(e){for(let n of this.subscribers)if(n.resolve){let r=n.resolve;n.resolve=null,r({value:e,done:!1})}else n.buffer.push(e)}close(){this.closed=!0;for(let e of this.subscribers)if(e.resolve){let n=e.resolve;e.resolve=null,n({value:void 0,done:!0})}}subscribe(){let e={buffer:[],resolve:null};this.subscribers.add(e);let n=this,r={next(){return e.buffer.length>0?Promise.resolve({value:e.buffer.shift(),done:!1}):n.closed?(n.subscribers.delete(e),Promise.resolve({value:void 0,done:!0})):new Promise(o=>{e.resolve=o})},return(){if(e.resolve){let o=e.resolve;e.resolve=null,o({value:void 0,done:!0})}return n.subscribers.delete(e),Promise.resolve({value:void 0,done:!0})}};return{[Symbol.asyncIterator]:()=>r}}};async function nn(t,e){if(t)try{await t.write({kind:"tool_call",payload:e})}catch(n){ue("trace.emit",t,"tool_call",n)}}async function Mt(t,e){if(t)try{await t.write({kind:"hook_decision",payload:e})}catch(n){ue("trace.emit",t,"hook_decision",n)}}async function rn(t,e){if(t)try{await t.write({kind:"subagent_lifecycle",payload:e})}catch(n){ue("trace.emit",t,"subagent_lifecycle",n)}}async function jm(t,e){if(t)try{await t.write({kind:"budget",payload:e})}catch(n){ue("trace.emit",t,"budget",n)}}async function Hm(t,e){if(t)try{await t.write({kind:"abort",payload:e})}catch(n){ue("trace.emit",t,"abort",n)}}async function Js(t,e){if(t)try{await t.write({kind:"compaction",payload:e})}catch(n){ue("trace.emit",t,"compaction",n)}}async function Wm(t,e){if(t)try{await t.write({kind:"closure",payload:e})}catch(n){ue("trace.emit",t,"closure",n)}}async function ae(t,e){if(t)try{await t.write({kind:"browser_event",payload:e})}catch(n){ue("trace.emit",t,"browser_event",n)}}async function Bl(t,e){if(t)try{await t.write({kind:"queued_user_message",payload:e})}catch(n){ue("trace.emit",t,"queued_user_message",n)}}async function $(t,e){if(t)try{await t.write({kind:"session_phase",payload:e})}catch(n){ue("trace.emit",t,"session_phase",n)}}import NI from"@anthropic-ai/sdk";var xI="fast-mode-2026-02-01";function Km(t){let e=[...t.oauthEntries??[],...t.effort?[t.effortEntry]:[],...t.extendedCacheTtl?[t.extendedCacheEntry]:[],...t.fast?[xI]:[]].filter(Boolean);return[...new Set(e)].join(",")||void 0}var qm="extended-cache-ttl-2025-04-11",RI=`claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14,${qm}`,II="effort-2025-11-24",CI="claude-cli/1.0.0 (external, cli)",PI="x-anthropic-billing-header: cc_version=1.0.0.test; cc_entrypoint=cli; cch=00000;";function Vs(t){return t.startsWith("sk-ant-oat01-")?"oauth":"api-key"}function Gr(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 Ot(t,e,n,r,o,s){let i=Km({oauthEntries:t==="oauth"?RI.split(","):[],effort:t==="oauth"&&r===!0,extendedCacheTtl:o,fast:s,effortEntry:II,extendedCacheEntry:qm});return t!=="oauth"?i?{"anthropic-beta":i}:{}:{"anthropic-beta":i,"x-app":"cli","User-Agent":CI,"X-Claude-Code-Session-Id":e,"x-client-request-id":n}}function Gm(t){return t!=="oauth"?null:[{type:"text",text:PI}]}C();var zr=["local","small","medium","large"],zm="claude-haiku-4-5-20251001",Xr="claude-sonnet-4-6",Hl="claude-opus-5",Kl="claude-fable-5",MI="grok-4.6",on={local:{id:""},small:{id:zm},medium:{id:Xr},large:{id:Hl}},Jm="auto",ql={opus:Hl,opus_1m:Hl,sonnet:Xr,sonnet_1m:Xr,haiku:zm,fable:Kl,grok:MI},OI=["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-5.5"],sn=[...zr,...Object.keys(ql),...OI],Wl;function Gl(t){Wl=t}function jl(t){if(t===void 0)return;let e=t.trim();return e.length>0?e:void 0}function Ys(t,e,n){let r={},o=jl(t);o&&(r.id=o);let s=jl(e);s&&(r.baseUrl=s);let i=jl(n);return i&&(r.apiKey=i),r}function DI(){return{local:Ys(b.AFK_MODEL_LOCAL,b.AFK_MODEL_LOCAL_BASE_URL,b.AFK_MODEL_LOCAL_API_KEY),small:Ys(b.AFK_MODEL_SMALL,b.AFK_MODEL_SMALL_BASE_URL,b.AFK_MODEL_SMALL_API_KEY),medium:Ys(b.AFK_MODEL_MEDIUM,b.AFK_MODEL_MEDIUM_BASE_URL,b.AFK_MODEL_MEDIUM_API_KEY),large:Ys(b.AFK_MODEL_LARGE,b.AFK_MODEL_LARGE_BASE_URL,b.AFK_MODEL_LARGE_API_KEY)}}function Vm(t){let e=DI(),n={};for(let r of zr){let o=on[r],s=t?.[r],i=e[r],a={id:i.id??s?.id??o.id},c=s?.name;c&&(a.name=c);let l=s?.provider;l&&(a.provider=l);let d=i.baseUrl??s?.baseUrl;d&&(a.baseUrl=d);let u=i.apiKey??s?.apiKey;u&&(a.apiKey=u),n[r]=a}return n}function Fn(t){return t||Wl||Vm()}function Ln(t,e=Fn()){let n=t.trim().toLowerCase();if(!(!n||n===Jm)){for(let r of zr){let o=e[r].name;if(o&&o.trim().toLowerCase()===n)return r}if(n==="local"||n==="small"||n==="medium"||n==="large")return n}}function an(t,e=Fn()){if(t===void 0)return{id:""};let n=Ln(t,e);if(n)return e[n];let r=ql[t.trim().toLowerCase()];return r?{id:r}:{id:t}}function nt(t,e=Fn()){if(t!==void 0)return an(t,e).id}function Ym(t,e=Fn()){if(t===void 0)return;let n=Ln(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 Qm(t){let e={};if(!t||typeof t!="object")return e;let n=t;for(let r of zr){let o=LI(n[r]);o&&(e[r]=o)}return e}function Zm(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";if(e==="chatgpt-oauth"||e==="chatgpt")return"chatgpt-oauth";if(e==="xai")return"xai";if(e==="xai-oauth"||e==="xai_oauth")return"xai-oauth"}function Dn(t){return typeof t=="string"?t.trim():""}function Xm(t){return/[\x00-\x1f\x7f]/.test(t)}var FI=new Set([...zr,Jm,...Object.keys(ql)]);function LI(t){if(typeof t=="string"){let e=t.trim();return e?{id:e}:void 0}if(t&&typeof t=="object"){let e=t,n=Dn(e.id);if(!n)return;let r={id:n},o=Dn(e.name);o&&(r.name=o);let s=Zm(e.provider);s&&(r.provider=s);let i=Dn(e.baseUrl);i&&(r.baseUrl=i);let a=Dn(e.apiKey);return a&&(r.apiKey=a),r}}function eg(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=Dn(e.id);if(!n)return{ok:!1,error:'model binding requires a non-empty "id"'};if(Xm(n))return{ok:!1,error:'model binding "id" must not contain control characters'};let r={id:n},o=Dn(e.name);if(o){if(Xm(o))return{ok:!1,error:'model binding "name" must not contain control characters'};if(FI.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=Zm(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 Xl={opus:on.large.id,opus_1m:on.large.id,sonnet:on.medium.id,sonnet_1m:on.medium.id,haiku:on.small.id,fable:Kl};function Qs(t){return t in Xl}function he(t){return nt(t)}import{randomUUID as tg}from"node:crypto";async function ng(t){let{token:e,model:n,system:r,user:o,maxTokens:s=64,signal:i,clientFactory:a}=t;if(!e)throw new Error("oneShotCompletion: token required");let c=Vs(e),l=Gr(e,c),d=a?a(l):new NI(l),u=tg(),p=tg(),f=Ot(c,u,p),m=he(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),y=[];for(let S of h.content)S.type==="text"&&y.push(S.text);let w=y.join("").trim();return w.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),w}C();var UI=new Set(["gpt-4o","gpt-4o-mini","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4-turbo","o1","o3","o4-mini"]),$I=[/^claude-/i,/^gpt-4o/i,/^gpt-4\.1/i,/^gpt-4-turbo/i,/^gpt-4-vision/i,/^gpt-5/i,/(?:^|[/_-])(?:vl|vlm)(?:[/_.-]|$)/i,/(?:^|[/_-])(?:llava|pixtral|internvl|cogvlm|idefics|moondream|janus)/i,/(?:vision|minicpm-?[vo]|qwen[\d.]*-?vl|llama-?3\.2-\d+b-vision|gemma-3|phi-3\.5-vision|phi-4-multimodal)/i];function BI(){let t=b.AFK_VISION_MODELS,e=[],n=[];if(t)for(let r of t.split(",")){let o=r.trim().toLowerCase();if(o)if(o.startsWith("!")){let s=o.slice(1).trim();s&&n.push(s)}else e.push(o)}return{enable:e,disable:n}}function rg(t,e){return t===e||t.includes(e)}function zl(t){if(!t)return!1;let e=(nt(t)??t).trim();if(!e)return!1;let n=e.toLowerCase(),{enable:r,disable:o}=BI();return o.some(s=>rg(n,s))?!1:r.some(s=>rg(n,s))||UI.has(n)?!0:$I.some(s=>s.test(e))}function og(t){let e=t.trim().toLowerCase();return e.includes("/")?e.slice(e.lastIndexOf("/")+1):e}function cn(t){return t?/^o[0-9]/.test(og(t)):!1}var jI=[/^gpt-5/];function Jr(t){if(!t)return!1;if(cn(t))return!0;let e=og(t);return jI.some(n=>n.test(e))}var Jl={opus:128e3,opus_1m:128e3,sonnet:128e3,sonnet_1m:128e3,haiku:64e3,fable:128e3,"claude-opus-5":128e3,"claude-opus-4-8":128e3,"claude-opus-4-7":128e3,"claude-opus-4-6":128e3,"claude-sonnet-5":128e3,"claude-sonnet-4-6":128e3,"claude-haiku-4-5-20251001":64e3,"claude-fable-5":128e3,"gpt-5.5":128e3,"gpt-5.6":128e3,"gpt-5.6-sol":128e3,"gpt-5.6-terra":128e3,"gpt-5.6-luna":128e3},HI=64e3;function Yl(t){let e=String(t).trim().toLowerCase(),n=Jl[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=nt(t)??String(t);return Jl[r]??Jl[r.toLowerCase()]}function Nn(t){return Yl(t)??HI}var Vl={opus:1e6,opus_1m:1e6,sonnet:1e6,sonnet_1m:1e6,haiku:2e5,fable:1e6,"claude-fable-5":1e6,"claude-sonnet-5":1e6,"claude-opus-5":1e6,"claude-opus-4-8":1e6,"claude-opus-4-7":1e6,"claude-opus-4-6":1e6,"claude-sonnet-4-6":1e6,"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4.1":1e6,"gpt-4.1-mini":1e6,"gpt-5.5":1e6,"gpt-5.6":1e6,"gpt-5.6-sol":1e6,"gpt-5.6-terra":1e6,"gpt-5.6-luna":1e6,o1:2e5,"o1-mini":128e3,o3:2e5,"o3-mini":2e5,"o4-mini":2e5,"mlx-community/qwen3-30b-a3b-4bit":128e3,"mlx-community/qwen3-32b-4bit":128e3,"mlx-community/qwen2.5-coder-32b-instruct-4bit":131072,"grok-4.6":5e5,"grok-4.5":5e5,"grok-4.3":1e6,"grok-4.20-0309-reasoning":1e6,"grok-4.20-0309-non-reasoning":1e6,"grok-4.20-multi-agent-0309":1e6,"grok-build-0.1":256e3},WI=2e5,KI=262144;function qI(t){if(!t)return!1;let e=t.trim().toLowerCase();return e?!!(e.includes("/")||e.startsWith("gpt-")||e.startsWith("gpt_")||cn(e)||e.startsWith("codex-")||e.startsWith("codex_")||e==="codex"||e==="grok"||e.startsWith("grok-")||e.startsWith("grok_")):!1}function Ve(t){let e=String(t).trim().toLowerCase(),n=Vl[e];if(e.endsWith("_1m")&&n!==void 0)return n;let r=nt(t)??String(t),o=Vl[r]??Vl[r.toLowerCase()];return o!==void 0?o:qI(r)?KI:WI}var sg={"claude-sonnet-5":2e5,"claude-opus-5":2e5,"claude-sonnet-4-6":2e5,"claude-opus-4-8":2e5,"claude-opus-4-7":2e5,"claude-opus-4-6":2e5};function mt(t){let e=Ve(t);if(String(t).trim().toLowerCase().endsWith("_1m"))return e;let r=nt(t)??String(t),o=sg[r]??sg[r.toLowerCase()];return o!==void 0?Math.min(e,o):e}function ig(t){return(t.inputTokens??0)+(t.outputTokens??0)}function pe(t){return t.contextWindowTokens??ig(t)}function Vr(t){return t?{totalTokens:pe(t),apiUsage:{input_tokens:t.inputTokens??0,output_tokens:t.outputTokens??0,cache_read_input_tokens:t.cachedInputTokens??0,cache_creation_input_tokens:t.cacheCreationTokens??0,context_window_tokens:pe(t)}}:{totalTokens:0,apiUsage:null}}function Yr(t,e,n){return e<=0||t<=0||n<=0||n>=1?!1:t/e>=n}function Qr(t,e){return e<=0||t<=0?0:t/e}var Zs=.9,GI=.04;function ag(t){let e=Ve(t),n=mt(t),r=Nn(t);if(e<=0||r<=0||n<e)return Zs;let o=(e-r)/e-GI;return o>0?o:Zs}function Zr(t,e,n,r){if(t<=0||n<=0||e<=0)return;let o=t+e;if(!(o<=n))throw new Error(`[afk] Context-window overflow: the conversation already used ~${t.toLocaleString()} tokens (last-turn API count) and the configured output ceiling is ${e.toLocaleString()} tokens \u2014 together they exceed the ${r} context window of ${n.toLocaleString()} tokens by ${(o-n).toLocaleString()} tokens. The provider would reject this request with HTTP 400. To continue: run /compact to summarise the conversation history, or start a new session.`)}function eo(t,e){if(t===void 0||t===!1)return;let n=e!==void 0?ag(e):1;if(t===!0)return Math.min(Zs,n);let r=t.threshold;if(!(typeof r!="number"||!Number.isFinite(r)||r<=0||r>=1))return Math.min(r,n)}var XI=t=>/opus-4-(7|[89])/.test(t),zI=t=>XI(t)||/(claude-)?(opus|sonnet)-5/.test(t),ti=new Set,cg=new Set,ei=1;function lg(t){if(t!==void 0&&!(!Number.isFinite(t)||t<0)){if(t>ei){let e=`temp:${t}`;return cg.has(e)||(cg.add(e),console.warn(`[afk] temperature ${t} exceeds the Anthropic maximum (${ei}); clamping to ${ei}.`)),ei}return t}}var JI=.25;function ni(t,e){let n=Nn(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 ti.has(s)||(ti.add(s),console.warn(`[afk] maxOutputTokens ${o} exceeds the ${e} output ceiling (${n}); clamping to ${n}.`)),n}return o}return n}function dg(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 ri(t,e,n){switch(t.type){case"adaptive":return{type:"adaptive",display:"summarized"};case"disabled":return{type:"disabled"};case"enabled":{if(typeof n=="string"&&zI(n))return{type:"adaptive",display:"summarized"};if(e<=1024)throw new Error(`[afk] Extended thinking requires max_tokens > 1024 (the API constraint is 1024 <= budget_tokens < max_tokens), but the resolved output cap is ${e}. Raise --max-output-tokens / AFK_MAX_OUTPUT_TOKENS above 1024, or disable thinking with --thinking disabled.`);let r=Math.floor(e*JI),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}`;ti.has(a)||(ti.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 oi(t,e){if(t!==void 0)return t;let n=e.toLowerCase();if(/(claude-)?(opus|sonnet)-(4-[678]|5)/.test(n))return"max"}M();import Ql from"path";import{dirname as VI}from"path";import{appendFileSync as YI,mkdirSync as QI}from"fs";var Dt=class{hooks;constructor(e){this.hooks=e}addReadRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots();if(!o)return;let s=Ql.resolve(e);o.includes(s)||(o.push(s),this.appendAuditLog({action:"grant-read",path:s,source:n,sessionId:r}))}addWriteRoot(e,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots(),s=this.hooks.getWriteRoots();if(!o||!s)return;let i=Ql.resolve(e);o.includes(i)||o.push(i),s.includes(i)||(s.push(i),this.appendAuditLog({action:"grant-write",path:i,source:n,sessionId:r}))}revokeRoot(e,n="slash",r){let o=this.hooks.getReadRoots();if(!o)return;let s=Ql.resolve(e),i=this.hooks.getProtectedRoot();if(i!==void 0&&s===i)return;let a=o.indexOf(s),c=a!==-1;c&&o.splice(a,1);let l=this.hooks.getWriteRoots(),d=!1;if(l){let u=l.indexOf(s);d=u!==-1,d&&l.splice(u,1)}(c||d)&&this.appendAuditLog({action:"revoke",path:s,source:n,sessionId:r})}getGrants(){return{resolveBase:this.hooks.getDisplayResolveBase?this.hooks.getDisplayResolveBase():this.hooks.getProtectedRoot(),readRoots:this.hooks.getReadRoots()?.slice()??[],writeRoots:this.hooks.getWriteRoots()?.slice()??[],allowAll:this.hooks.getAllowAll()}}appendAuditLog(e){try{let n=Bs();QI(VI(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:e.sessionId??this.hooks.getDefaultSessionId?.()??null,action:e.action,path:e.path,source:e.source});YI(n,r+`
|
|
29
29
|
`)}catch{}}};function Ye(t){return t==="bypassPermissions"||t==="autonomous"}var si=class{_readRoots;_writeRoots;_currentCwd;_permissionMode="default";manager=new Dt({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,ensureInitialized:()=>this.ensureInitialized(),getProtectedRoot:()=>this._currentCwd,getAllowAll:()=>Ye(this._permissionMode)});get readRoots(){return this._readRoots}get writeRoots(){return this._writeRoots}get currentCwd(){return this._currentCwd}set currentCwd(e){this._currentCwd=e}get permissionMode(){return this._permissionMode}set permissionMode(e){this._permissionMode=e}ensureInitialized(e){if(!this._readRoots){let n=e?[e]:[];this._readRoots=n.slice(),this._writeRoots=n.slice(),e&&!this._currentCwd&&(this._currentCwd=e)}}};import{z as ye}from"zod";var gt=ye.string().min(1,"namespace/key must be non-empty").max(128,"namespace/key must not exceed 128 characters").regex(/^[A-Za-z0-9_.-]+$/,"namespace/key may only contain [A-Za-z0-9_.-]"),ZI=ye.object({namespace:gt,key:gt}),eC=ye.object({namespace:gt,key:gt,value:ye.unknown(),ttl_ms:ye.number().int().positive().optional(),metadata:ye.unknown().optional()}),tC=ye.object({namespace:gt,key:gt,expected_version:ye.number(),value:ye.unknown(),ttl_ms:ye.number().int().positive().optional(),metadata:ye.unknown().optional()}),nC=ye.object({namespace:gt,key:gt}),rC=ye.object({namespace:gt,key_prefix:ye.string().optional(),limit:ye.number().int().positive().max(100).optional()});function ii(t,e){let n=new Map;return n.set("state_get",async r=>{try{let{namespace:o,key:s}=ZI.parse(r),i=t.get(o,s);return{content:JSON.stringify(i)}}catch(o){return{content:String(o),isError:!0}}}),n.set("state_put",async r=>{try{let{namespace:o,key:s,value:i,ttl_ms:a,metadata:c}=eC.parse(r),l=t.put(o,s,i,{ttl_ms:a,metadata:c},e);return{content:JSON.stringify(l)}}catch(o){return{content:String(o),isError:!0}}}),n.set("state_cas",async r=>{try{let{namespace:o,key:s,expected_version:i,value:a,ttl_ms:c,metadata:l}=tC.parse(r),d=t.cas(o,s,i,a,{ttl_ms:c,metadata:l},e);return{content:JSON.stringify(d)}}catch(o){return{content:String(o),isError:!0}}}),n.set("state_delete",async r=>{try{let{namespace:o,key:s}=nC.parse(r),i=t.del(o,s);return{content:JSON.stringify(i)}}catch(o){return{content:String(o),isError:!0}}}),n.set("state_query",async r=>{try{let o=rC.parse(r),s=Math.min(o.limit??20,100),i=t.query(o.namespace,{key_prefix:o.key_prefix,limit:s});return{content:JSON.stringify(i)}}catch(o){return{content:String(o),isError:!0}}}),n}import oJ from"better-sqlite3";var mg={name:"workspace_publish",category:"write",concurrencySafe:!1,description:"Publish a structured finding to the shared session workspace so sibling agents can see it. Call after: confirming a module's key exports or invariants, ruling out a hypothesis, or reading a file another sibling will likely need (publish the insight, not raw content). Entries are visible immediately to siblings via workspace_query and injected into new siblings' system prompts at fork time. Free to batch with other tools.",input_schema:{type:"object",properties:{type:{type:"string",enum:["finding","evidence","hypothesis","decision","artifact","status"],description:"The kind of entry being published."},subject:{type:"string",description:'Optional short label for relevance routing \u2014 e.g. "auth refresh", "DB schema". Agents querying the workspace by task keywords will match on this field.'},content:{type:"string",description:"The full text of the finding, evidence, or decision."},evidence:{type:"array",items:{type:"string"},description:'Optional file:line references backing this entry (e.g. ["src/auth.ts:141"]).'},confidence:{type:"number",description:"Confidence level 0\u20131 (default 1.0)."},relates_to:{type:"array",items:{type:"number"},description:"Optional IDs of related workspace entries."},relation_type:{type:"string",enum:["supports","contradicts","depends_on","supersedes"],description:"Relationship to the entries listed in relates_to."}},required:["type","content"]}},gg={name:"workspace_query",category:"read",concurrencySafe:!0,description:"Query the shared session workspace for findings published by sibling agents. Call before reading a file or grepping a module \u2014 a sibling may have already analyzed it. Returns entries matching the search keywords, ordered by recency. A workspace hit saves a tool round by avoiding redundant file reads.",input_schema:{type:"object",properties:{query:{type:"string",description:'Search keywords to match against workspace entry subjects and content. E.g. "provider streaming" or "auth error handling".'},type:{type:"string",enum:["finding","evidence","hypothesis","decision","artifact","status"],description:"Optional: filter results to a specific entry type."},limit:{type:"number",description:"Max entries to return (default 20, max 50)."}},required:["query"]}},to=[mg,gg];function no(t,e,n){let r=new Map,o=async i=>{try{let a=lC(i),c={session_id:e,type:a.type,content:a.content,subject:a.subject,evidence:a.evidence,confidence:a.confidence,agent_id:n,relates_to:a.relates_to,relation_type:a.relation_type},l=t.publish(c);return{content:JSON.stringify({published:!0,id:l})}}catch(a){return{content:`workspace_publish error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},s=async i=>{try{let a=cC(i),c=t.queryRelevant(null,a.query,a.limit);return a.type!==void 0&&(c=c.filter(l=>l.type===a.type)),{content:JSON.stringify({entries:c.map(oC),count:c.length})}}catch(a){return{content:`workspace_query error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}};return r.set("workspace_publish",o),r.set("workspace_query",s),r}function oC(t){return{id:t.id,type:t.type,subject:t.subject,content:t.content,evidence:t.evidence!==null?JSON.parse(t.evidence):null,confidence:t.confidence,agent_id:t.agent_id,relates_to:t.relates_to!==null?JSON.parse(t.relates_to):null,relation_type:t.relation_type,created_at:t.created_at}}var ug=8192,pg=256,fg=" \u2026 [truncated]",Zl=new Set(["finding","evidence","hypothesis","decision","artifact","status"]),sC=new Set(["supports","contradicts","depends_on","supersedes"]),iC=50,aC=20;function cC(t){if(!t||typeof t!="object")throw new Error("workspace_query: input must be an object");let e=t,n=e.query;if(typeof n!="string"||n.length===0)throw new Error("workspace_query: query is required");let r=e.type,o=typeof r=="string"&&Zl.has(r)?r:void 0,s=e.limit,i=typeof s=="number"&&s>0?Math.min(Math.floor(s),iC):aC;return{query:n,type:o,limit:i}}function lC(t){if(!t||typeof t!="object")throw new Error("workspace_publish: input must be an object");let e=t,n=e.type;if(typeof n!="string"||!Zl.has(n))throw new Error(`workspace_publish: type must be one of ${[...Zl].join(", ")}`);let r=e.content;if(typeof r!="string"||r.length===0)throw new Error("workspace_publish: content is required");let o=r.length>ug?r.slice(0,ug)+fg:r,s=typeof e.subject=="string"?e.subject.length>pg?e.subject.slice(0,pg)+fg:e.subject:void 0,i=Array.isArray(e.evidence)&&e.evidence.every(u=>typeof u=="string")?e.evidence:void 0,a=typeof e.confidence=="number"?e.confidence:void 0,c=Array.isArray(e.relates_to)&&e.relates_to.every(u=>typeof u=="number")?e.relates_to:void 0,l=e.relation_type,d=typeof l=="string"&&sC.has(l)?l:void 0;return{type:n,content:o,subject:s,evidence:i,confidence:a,relates_to:c,relation_type:d}}function hg(t){let e=["# Workspace context (shared findings from sibling agents)","","The following findings were published by other agents working on this task.","Use them to avoid re-discovering known facts. Call `workspace_query` to poll","for newer entries mid-run. Publish new discoveries with `workspace_publish`."];for(let c of t){e.push(""),e.push("---");let l=[];l.push(`confidence: ${c.confidence.toFixed(2)}`),c.agent_id&&l.push(`agent: ${c.agent_id}`);let d=l.length>0?` (${l.join(", ")})`:"",u=uC(c.type);if(e.push(`#${c.id} ${u}${d}`),c.subject&&e.push(`Subject: ${c.subject}`),e.push(c.content),c.evidence)try{let p=JSON.parse(c.evidence);Array.isArray(p)&&p.length>0&&e.push(`Evidence: ${p.join(", ")}`)}catch{}if(c.relates_to&&c.relation_type)try{let p=JSON.parse(c.relates_to);Array.isArray(p)&&p.length>0&&e.push(`Relation: ${c.relation_type} \u2192 #${p.join(", #")}`)}catch{}}e.push("---");let n=e.join(`
|
|
30
30
|
`),r=32*1024;if(n.length<=r)return n;let o=`
|
|
31
31
|
---
|
|
@@ -200,11 +200,11 @@ Remedy: these paths are outside the fork's granted read roots. Re-dispatch with
|
|
|
200
200
|
Retrying it verbatim will fail the same way. Fix the underlying cause, change the arguments, use a different tool, or stop and report the blocker.`,isError:!0,failureClass:"repeat-failure"}}}note(e,n){let r=fo(e);if(n.isError!==!0){this.streaks.delete(r);return}let o=this.streaks.get(r);this.streaks.set(r,{count:(o?.count??0)+1,lastError:OM(n)})}streakFor(e){return this.streaks.get(fo(e))?.count??0}};async function mo(t,e,n){let r=new Array(t.length),o=Math.min(Math.max(1,Math.floor(e)),t.length),s=0,i=[];for(let a=0;a<o;a++)i.push((async()=>{for(;s<t.length;){let c=s++;try{r[c]={status:"fulfilled",value:await n(t[c])}}catch(l){r[c]={status:"rejected",reason:l}}}})());return await Promise.all(i),r}J();function vh(t,e,n){if(n.has(t.name))return null;let r=e.check(t);return r===null?null:(P(`[repeat-failure-guard #723] refused ${r.tool} after ${r.count} identical failures`),r.result)}function DM(t){if(!t)return{enter:()=>{},leave:()=>{}};let e=new Set,n=()=>{try{t([...e])}catch{}};return{enter:r=>{e.add(r),n()},leave:r=>{e.delete(r),n()}}}async function FM(t,e,n,r){let{call:o,originalIndex:s}=e[t];if(o.signal.aborted)return{result:{content:"Tool call aborted",isError:!0,failureClass:be(o.signal)},originalIndex:s};r?.enter(o.id);try{return{result:await n(o),originalIndex:s}}finally{r?.leave(o.id)}}function LM(t,e,n,r){for(let o of t)if(o.status==="fulfilled")r[o.value.originalIndex]=o.value.result;else{let s=o.reason instanceof Error?o.reason.message:String(o.reason),i=e[t.indexOf(o)];r[n[i].originalIndex]={content:`Tool execution error: ${s}`,isError:!0}}}function Th(t,e,n){let r=t.indices.length;for(let o=0;o<t.indices.length;o++){let s=t.indices[o],i=n[e[s].originalIndex];i&&(i.batchIndex=o+1,i.batchSize=r)}}async function _h(t,e,n,r){let o=[...t.indices];for(;o.length>0;){let s=new Map,i=[],a=[];for(let u of o){let{call:p,originalIndex:f}=e[u],m=vh(p,r.repeatFailureGuard,r.repeatBreakerExemptTools);if(m){n[f]=m;continue}if(r.repeatBreakerExemptTools.has(p.name)){i.push(u);continue}let g=fo(p),h=wd-r.repeatFailureGuard.streakFor(p),y=s.get(g)??0;y<h?(s.set(g,y+1),i.push(u)):a.push(u)}o=a;let c=i.map(u=>e[u]?.call).filter(u=>u!==void 0&&u.name==="agent");if(c.length>=2&&r.subagentExecutor)try{r.subagentExecutor.notifyWaveStart(c,r.sessionId??"",null)}catch{}let l=DM(r.onActivity),d=await mo(i,r.maxConcurrentSafeCalls,u=>FM(u,e,r.executeCore,l));LM(d,i,e,n);for(let u of i){let{call:p,originalIndex:f}=e[u],m=n[f];m!==void 0&&m.failureClass!=="abort"&&r.repeatFailureGuard.note(p,m)}if(c.length>=2&&r.subagentExecutor)try{r.subagentExecutor.notifyWaveEnd()}catch{}}}async function Eh(t,e,n,r){for(let o of t.indices){let{call:s,originalIndex:i}=e[o];if(s.signal.aborted){n[i]={content:"Tool call aborted",isError:!0,failureClass:be(s.signal)};continue}let a=vh(s,r.repeatFailureGuard,r.repeatBreakerExemptTools);if(a){n[i]=a;continue}let c=await r.executeCore(s);n[i]=c,r.repeatFailureGuard.note(s,c)}}function Ah(t){return t==="agent"||t==="cancel_background_job"||t==="send_message_to_agent"}async function xh(t,e){if(!t)return{result:{content:e.name==="agent"?"Agent tool is not available in this session configuration":"Background mode is not available in this session configuration",isError:!0}};try{return{result:e.name==="agent"?await t.execute(e):e.name==="send_message_to_agent"?await t.sendMessageToAgent(e):await t.cancelBackgroundJob(e)}}catch(n){let r=n instanceof Error?n.message:String(n);return{result:{content:`${e.name==="agent"?"Agent":e.name==="send_message_to_agent"?"Steering":"Background cancellation"} tool error: ${r}`,isError:!0},thrownMessage:r}}}var UM=8,Sd=new Set;var Be=class{handlers;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;skillExecutor;composeExecutor;classifier;maxConcurrentSafeCalls;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;subagentId;sessionGrantManager;traceWriter;readOnlyBash;maxOutputBytes;spawnedPidRegistry;repeatBreaker=null;repeatFailureGuard=new Ii;denialBreaker=null;suspectedLoopWindow=null;grantManager;constructor(e){this.handlers=e.handlers,this.schemas=e.schemas,this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.canUseTool=e.canUseTool,this.subagentExecutor=e.subagentExecutor,this.skillExecutor=e.skillExecutor,this.composeExecutor=e.composeExecutor,this.classifier=e.concurrencyClassifier??xi,this.maxConcurrentSafeCalls=typeof e.maxConcurrentSafeCalls=="number"&&Number.isFinite(e.maxConcurrentSafeCalls)&&e.maxConcurrentSafeCalls>=1?Math.floor(e.maxConcurrentSafeCalls):kg(),this.resolveBase=e.cwd,this._env=e.env,this.sessionId=e.sessionId,this.parentSessionId=e.parentSessionId,this.subagentId=e.subagentId,this.sessionGrantManager=e.sessionGrantManager,this.traceWriter=e.traceWriter,this.readOnlyBash=e.readOnlyBash===!0,this.maxOutputBytes=typeof e.maxOutputBytes=="number"&&Number.isFinite(e.maxOutputBytes)&&e.maxOutputBytes>0?e.maxOutputBytes:void 0,this._allowAll=e.allowAll===!0,this.spawnedPidRegistry=e.spawnedPidRegistry;let n=e.cwd?[e.cwd]:[];this._readRoots=e.readRoots??n.slice(),this._writeRoots=e.writeRoots??n.slice(),this.grantManager=new Dt({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,getProtectedRoot:()=>this.resolveBase,getAllowAll:()=>this._allowAll,getDefaultSessionId:()=>this.sessionId})}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.spawnedPidRegistry!==void 0?{spawnedPidRegistry:this.spawnedPidRegistry}:{}}}callHandlerContext(e){return{...this.handlerContext,toolUseId:e.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{}}}addReadRoot(e,n="slash",r){this.grantManager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grantManager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grantManager.revokeRoot(e,n,r)}getGrants(){return this.grantManager.getGrants()}setAllowAll(e){this._allowAll=e}setResolveBase(e){let n=this.resolveBase;if(n!==e){if(this.resolveBase=e,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=e:this._readRoots.includes(e)||this._readRoots.push(e);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=e:this._writeRoots.includes(e)||this._writeRoots.push(e)}else this._readRoots.includes(e)||this._readRoots.push(e),this._writeRoots.includes(e)||this._writeRoots.push(e);this.subagentExecutor?.setCwd(e),this.skillExecutor?.setCwd(e),this.composeExecutor?.setCwd(e)}}get toolDefs(){let e=this.subagentExecutor?.supportsBackgroundJobs?.()?this.schemas:this.schemas.filter(o=>o.name!=="cancel_background_job"&&o.name!=="send_message_to_agent"),n=this.permissions?.allowedTools;if(!n)return e;let r=new Set(n);return e.filter(o=>r.has(o.name))}denialReason(e,n){return this.isRegisteredTool(e)?n??`Tool "${e}" is not permitted`:this.unknownToolMessage(e)}isRegisteredTool(e){return this.handlers.has(e)||e==="agent"&&this.subagentExecutor!==void 0||e==="cancel_background_job"&&this.subagentExecutor?.supportsBackgroundJobs?.()===!0||e==="send_message_to_agent"&&this.subagentExecutor?.supportsBackgroundJobs?.()===!0||e==="skill"&&this.skillExecutor!==void 0||e==="compose"&&this.composeExecutor!==void 0}unknownToolMessage(e){let n=this.toolDefs.map(o=>o.name).join(", "),r=n.length>0?`Available tools: ${n}. Do NOT retry "${e}" or a variant of it; use one of the tools listed above.`:`Do NOT retry "${e}" or a variant of it.`;return`Unknown tool "${e}" \u2014 it does not exist in this session. ${r}`}async checkReadOnlyBash(e){if(!this.readOnlyBash||e.name!=="bash")return null;let n=e.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=Dg(r);if(!o.mutating)return null;let s=`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff/show/ls-remote, ls, cat, find, grep, gh pr view/diff). For a remote ref you have not fetched, \`gh pr diff <n>\`, \`gh pr view <n>\` and \`git ls-remote\` need no local ref \u2014 \`git fetch\` is blocked. Do NOT retry variants of a blocked command: if the task genuinely requires a mutation, stop and report that requirement to your caller instead.`;return await this.emitPreToolUseBlock(e.name,s),{content:s,isError:!0,failureClass:"permission-denied"}}async emitPreToolUseBlock(e,n){await Mt(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:e,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(e){if(Sd.has(e.name))return null;let n=mh(e);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<UM?null:{content:`Loop circuit breaker: "${e.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}checkRepeatFailureGuard(e){if(Sd.has(e.name))return null;let n=this.repeatFailureGuard.check(e);return n===null?null:(P(`[repeat-failure-guard #723] refused ${n.tool} after ${n.count} identical failures`),n.result)}observeSuspectedLoop(e){if(this.parentSessionId===void 0)return;this.suspectedLoopWindow===null&&(this.suspectedLoopWindow=wh());let n=Ri(e),r=Sh(this.suspectedLoopWindow,n);r.fired&&$(this.traceWriter,{phase:"suspected_loop",metadata:{tool:e.name,count:r.count,windowSize:bd}})}recordForkReadDenial(e,n,r){if(this.parentSessionId===void 0||!gh.has(e.name)||!hh(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let s=yh(e);return o.deniedPaths.includes(s)||o.deniedPaths.push(s),this.denialBreaker=o,o.count<5?r:{content:bh(o.deniedPaths,o.count),isError:!0,failureClass:Hn}}resetDenialBreaker(){this.denialBreaker=null}async runCanUseTool(e){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(e.name,e.input??{},{signal:e.signal,toolUseID:e.id})}catch(r){let o=`Tool "${e.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`;return await this.emitPreToolUseBlock(e.name,o),{content:o,isError:!0,failureClass:"permission-denied"}}if(n.behavior==="deny"){let r=n.message||`Tool "${e.name}" denied by permission policy`;return await this.emitPreToolUseBlock(e.name,r),{content:r,isError:!0,failureClass:"permission-denied"}}return n.updatedInput!==void 0&&(e.input=n.updatedInput),null}async runPreDispatchGates(e){if(this.hookRegistry){let a={event:"PreToolUse",toolName:e.name,input:e.input,...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{},...e.id!==void 0?{toolUseId:e.id}:{}};try{await _g(this.hookRegistry,a,{signal:e.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(c){if(c instanceof W)return this.recordForkReadDenial(e,c.reason,{content:`Tool "${e.name}" blocked by PreToolUse hook${c.reason?`: ${c.reason}`:""}${c.injectContext?`
|
|
201
201
|
|
|
202
202
|
${c.injectContext}`:""}`,isError:!0,failureClass:"hook-block"});throw c}}let n=li(e.name,this.permissions);if(!n.allowed){let a=this.denialReason(e.name,n.reason);return await this.emitPreToolUseBlock(e.name,a),{content:a,isError:!0,failureClass:"permission-denied"}}let r=await this.runCanUseTool(e);if(r)return r;let o=await this.checkReadOnlyBash(e);if(o)return o;let s=this.checkRepeatCircuitBreaker(e);if(s)return s;let i=this.checkRepeatFailureGuard(e);return i||(this.observeSuspectedLoop(e),null)}async execute(e){if(e.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:be(e.signal)};let n=await this.runPreDispatchGates(e);if(n)return n;let r=await this.executeCore(e);return this.repeatFailureGuard.note(e,r),r.isError!==!0&&this.resetDenialBreaker(),r}async executeBatch(e,n){if(e.length===0)return[];if(e.length===1)return[await this.execute(e[0])];let r=new Array(e.length),o=new Set;for(let c=0;c<e.length;c++){let l=e[c];if(l.signal.aborted){r[c]={content:"Tool call aborted",isError:!0,failureClass:be(l.signal)},o.add(c);continue}let d=await this.runPreDispatchGates(l);if(d){r[c]=d,o.add(c);continue}}let s=e.map((c,l)=>({call:c,originalIndex:l})).filter((c,l)=>!o.has(l));if(s.length===0)return r;let i=fh(s.map(c=>c.call),this.classifier),a={repeatFailureGuard:this.repeatFailureGuard,repeatBreakerExemptTools:Sd,executeCore:c=>this.executeCore(c),subagentExecutor:this.subagentExecutor,sessionId:this.sessionId,maxConcurrentSafeCalls:this.maxConcurrentSafeCalls,onActivity:n};for(let c of i)c.isConcurrencySafe?await _h(c,s,r,a):await Eh(c,s,r,a),Th(c,s,r);return r.some(c=>c!==void 0&&c.isError!==!0)&&this.resetDenialBreaker(),r}async executeCore(e){let n=await this.executeCoreInner(e);return this.applyOutputCap(n)}applyOutputCap(e){let n=this.maxOutputBytes;if(n===void 0)return e;let r=Buffer.byteLength(e.content,"utf8");return r<=n||(e.content=ot(e.content,n),e.truncated=!0,P(`[output-cap #661] fork tool result capped: original=${r}B capped=${Buffer.byteLength(e.content,"utf8")}B (cap=${n}B)`)),e}async executeCoreInner(e){if(Ah(e.name)){let i=await xh(this.subagentExecutor,e);return i.thrownMessage!==void 0?this.firePostToolUseFailure(e.name,i.thrownMessage,e.signal,e.input):this.firePostToolUse(e.name,i.result.content,e.signal,e.input,i.result),i.result}if(e.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let i,a=!1,c="";try{i=await this.skillExecutor.execute(e)}catch(l){a=!0,c=l instanceof Error?l.message:String(l),i={content:`Skill tool error: ${c}`,isError:!0}}return a?this.firePostToolUseFailure(e.name,c,e.signal,e.input):this.firePostToolUse(e.name,i.content,e.signal,e.input,i),i}if(e.name==="compose"){let i=await this.executeCompose(e);return this.firePostToolUse(e.name,i.content,e.signal,e.input,i),i}let n=this.handlers.get(e.name);if(!n){let i=this.unknownToolMessage(e.name);return await this.emitPreToolUseBlock(e.name,i),{content:i,isError:!0,failureClass:"permission-denied"}}let r,o=!1,s="";try{r=await n(e.input,e.signal,this.callHandlerContext(e))}catch(i){o=!0,s=i instanceof Error?i.message:String(i),r={content:`Tool execution error: ${s}`,isError:!0}}return o?this.firePostToolUseFailure(e.name,s,e.signal,e.input):this.firePostToolUse(e.name,r.content,e.signal,e.input,r),r}async executeCompose(e){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(e)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(e,n,r,o,s){if(!this.hookRegistry)return;let i={event:"PostToolUse",toolName:e,output:n,...o!==void 0?{input:o}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager?{grantManager:this.sessionGrantManager}:{},...s?.isError===!0?{isError:!0}:{},...s?.incomplete===!0?{incomplete:!0,...s.incompleteReason?{incompleteReason:s.incompleteReason}:{}}:{}};Eg(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(e,n,r,o){if(!this.hookRegistry)return;let s={event:"PostToolUseFailure",toolName:e,error:n,...o!==void 0?{input:o}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};Ag(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(i=>{P(`firePostToolUseFailure outer catch (tool=${e}): ${String(i)}`)})}};import{spawn as L0}from"child_process";import N0 from"os";C();M();import{mkdir as $M,writeFile as BM}from"fs/promises";import{dirname as jM,join as HM}from"path";function WM(){return HM(De(),"routing-decisions.jsonl")}function KM(t){let e={surface:"afk"};for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}async function Ee(t){if(!(b.VITEST||b.NODE_ENV==="test"))try{let e=WM();await $M(jM(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...KM(t)})+`
|
|
203
|
-
`;await BM(e,r,{flag:"a"})}catch{}}var qM=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,GM=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,XM=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,zM=/(\d+)\s+passing/,JM=/(\d+)\s+failing/,VM=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,YM=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,QM=/(\d+) examples?, (\d+) failures?/,ZM=/OK \((\d+) tests?/,e0=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/;function t0(t){let e=t.match(qM);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function n0(t){let e=t.match(GM);if(!e)return null;let n=parseInt(e[1]??"0",10);return{runner:"jest",passed:parseInt(e[2]??"0",10),failed:n}}function r0(t){let e=t.match(XM);if(!e)return null;if(e[2]!==void 0){let n=parseInt(e[2],10),r=parseInt(e[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return e[4]!==void 0?{runner:"pytest",passed:parseInt(e[4],10),failed:0}:null}function o0(t){let e=t.match(zM);if(!e)return null;let n=parseInt(e[1]??"0",10),r=t.match(JM),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function s0(t){let e=[...t.matchAll(VM)];if(e.length===0)return null;let n=0,r=0;for(let o of e)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function i0(t){let e=t.match(YM);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function a0(t){let e=t.match(QM);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function c0(t){let e=t.match(ZM);if(e)return{runner:"phpunit",passed:parseInt(e[1]??"0",10),failed:0};let n=t.match(e0);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function go(t){return t0(t)??n0(t)??r0(t)??o0(t)??s0(t)??i0(t)??a0(t)??c0(t)??null}var Rh=/\x1B\][^\x07\x1B\x9C]*(?:\x07|\x1B\\|\x9C)|\x1B[P^_X][^\x1B\x9C]*(?:\x1B\\|\x9C)|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[6-_]/g,l0=/[\x00-\x1F\x7F-\x9F]/g;function we(t){return t.replace(Rh,"").replace(l0," ").trim()}function Ae(t){return t.replace(Rh,"")}import{statSync as d0}from"node:fs";function ho(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.code==="ENOENT"&&typeof e.syscall=="string"&&e.syscall.startsWith("spawn")}function u0(t){if(t===void 0)return!1;try{return d0(t),!1}catch{return!0}}function Wn(t,e){let n=t instanceof Error?t.message:typeof t?.message=="string"?String(t.message):String(t);return ho(t)&&u0(e)?`working directory does not exist: ${e} (deleted worktree?) \u2014 underlying: ${n}`:n}import un from"path";import{realpathSync as O0}from"fs";C();import{basename as x0,dirname as R0,join as Oi,relative as I0,resolve as Xn,sep as yo}from"path";import{homedir as Z}from"os";C();M();import{realpathSync as Oh}from"fs";import{dirname as y0,resolve as ln,join as Pi}from"path";import{homedir as je}from"os";var Ih=new Set;function Ut(t){let e=t instanceof Error?t.message:String(t);Ih.has(e)||(Ih.add(e),console.warn(`[afk-home] Malformed AFK home/state env var ignored while deriving the credential floor: ${e}. The relocated tree is NOT protected \u2014 the default ~/.afk entries still apply. Fix the env var to restore coverage.`))}import{statSync as vd}from"node:fs";import{homedir as p0}from"node:os";import{basename as f0,dirname as Ph,join as m0}from"node:path";var Ch,kd=new Map;function Mh(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function g0(t){let e=f0(t),n=e===e.toLowerCase()?e.toUpperCase():e.toLowerCase();if(n===e)return;let r;try{r=vd(t)}catch{return}let o=kd.get(r.dev);if(o!==void 0)return o;try{let s=vd(m0(Ph(t),n)),i=r.dev===s.dev&&r.ino===s.ino;return kd.set(r.dev,i),i}catch(s){let i=Mh(s);return i==="ENOENT"||i==="ENOTDIR"?(kd.set(r.dev,!1),!1):void 0}}function h0(t=p0()){if(Ch!==void 0)return Ch;let e=t;for(;;)try{return vd(e),g0(e)??!0}catch(n){let r=Mh(n);if(r!=="ENOENT"&&r!=="ENOTDIR")return!0;let o=Ph(e);if(o===e)return!0;e=o}}function Kn(t,e,n=e){if(t===e||t.startsWith(e+"/")||t.startsWith(e+"\\"))return!0;if(!h0(n))return!1;let r=t.toLowerCase(),o=e.toLowerCase();return r===o||r.startsWith(o+"/")||r.startsWith(o+"\\")}var b0=[`${je()}/.ssh`,`${je()}/.aws`,`${je()}/.gnupg`,`${je()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${je()}/.afk/config`,`${je()}/.afk/state`,`${je()}/.npmrc`,`${je()}/.docker/config.json`,`${je()}/Library/LaunchAgents`,`${je()}/Library/LaunchDaemons`,"/Library/LaunchAgents","/Library/LaunchDaemons",`${je()}/.config/systemd`,...process.platform==="win32"&&b.APPDATA?[`${b.APPDATA}\\gcloud`,`${b.APPDATA}\\Docker`]:[],...process.platform==="win32"&&b.USERPROFILE?[`${b.USERPROFILE}\\.ssh`,`${b.USERPROFILE}\\.aws`,`${b.USERPROFILE}\\.gnupg`]:[]];function w0(){let t=[];try{let e=ne();t.push(ln(Pi(e,"config"))),t.push(ln(Pi(e,"state")))}catch(e){Ut(e)}try{t.push(ln(Q()))}catch(e){Ut(e)}return t}var Ci;function Td(){let t=`${b.AFK_WRITE_DENYLIST??""}\0${b.AFK_HOME??""}\0${b.AFK_STATE_DIR??""}`;if(!Ci||Ci.key!==t){let e=b.AFK_WRITE_DENYLIST,n=process.platform==="win32"?";":":",r=e?e.split(n).map(o=>o.trim()).filter(Boolean).map(o=>o==="~"||o.startsWith("~/")||o.startsWith("~\\")?Pi(je(),o.slice(2)):o).map(o=>ln(o)).filter(Boolean):[];Ci={key:t,unresolved:[...new Set([...b0.map(o=>ln(o)),...w0()]),...r]}}return[...new Set(Ci.unresolved.map(e=>He(e)))]}function He(t){let e=ln(t);try{return Oh(e)}catch{}let n=[],r=e;for(let o=0;o<64;o++){let s=y0(r);if(s===r)break;n.unshift(r.slice(s.length+1)),r=s;try{let i=Oh(r);return Pi(i,...n)}catch{}}return e}function qn(t,e="write_file"){let n=He(ln(t));for(let r of Td())if(Kn(n,r))throw new Error(`${e}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}M();import{isAbsolute as S0,relative as k0,sep as v0}from"node:path";import{homedir as Mi}from"node:os";function T0(t,e){let n=k0(e,t);return n===""||n!==".."&&!n.startsWith(`..${v0}`)&&!S0(n)}function _d(t,e){return t.filter(n=>!e.some(r=>T0(n,r)))}function _0(t,e){return t.filter(({source:n})=>n!==e).map(({root:n})=>n)}var E0={".afk/config/mcp.json":`${Mi()}/.afk/config`,".afk/config/schedules.json":`${Mi()}/.afk/config`,".ssh/config":`${Mi()}/.ssh`,".ssh/known_hosts":`${Mi()}/.ssh`};function Dh(t,e){return t.flatMap(({rel:n,resolved:r})=>_d([r],_0(e,E0[n])))}import{isAbsolute as XV,resolve as A0}from"path";import{homedir as Fh}from"os";function Gn(t){return t==="~"?Fh():t.startsWith("~/")?A0(Fh(),t.slice(2)):t}var Nh=[`${Z()}/.ssh`,`${Z()}/.aws`,`${Z()}/.gnupg`,`${Z()}/.config/gcloud`,`${Z()}/.afk/config`,`${Z()}/.npmrc`,`${Z()}/.docker/config.json`,`${Z()}/.git-credentials`,`${Z()}/.netrc`,`${Z()}/.config/gh/hosts.yml`,`${Z()}/.kube/config`,"/etc/shadow","/etc/sudoers","/private/etc/master.passwd",`${Z()}/.password-store`,`${Z()}/Library/Application Support/Google/Chrome`,`${Z()}/Library/Application Support/Chromium`,`${Z()}/Library/Application Support/BraveSoftware`,`${Z()}/Library/Application Support/Microsoft Edge`,`${Z()}/Library/Application Support/Arc`,`${Z()}/Library/Application Support/Firefox`,...process.platform==="win32"&&b.USERPROFILE?[`${b.USERPROFILE}\\.ssh`,`${b.USERPROFILE}\\.aws`,`${b.USERPROFILE}\\.gnupg`]:[],...process.platform==="win32"&&b.APPDATA?[`${b.APPDATA}\\gcloud`,`${b.APPDATA}\\Docker`,`${b.APPDATA}\\Mozilla\\Firefox`]:[],...process.platform==="win32"&&b.LOCALAPPDATA?[`${b.LOCALAPPDATA}\\Google\\Chrome`,`${b.LOCALAPPDATA}\\Chromium`,`${b.LOCALAPPDATA}\\BraveSoftware`,`${b.LOCALAPPDATA}\\Microsoft\\Edge`]:[]],wo=[".afk/config/mcp.json",".afk/config/schedules.json",".ssh/config",".ssh/known_hosts"],C0=`${Z()}/.afk/config`,s5=wo.map(t=>Oi(Z(),t));function Uh(t){let e=Xn(t);return Oi(He(R0(e)),x0(e))}var bo;function $h(t){if(!t)return[];let e=process.platform==="win32"?";":":";return t.split(e).map(n=>n.trim()).filter(Boolean).map(n=>n==="~"||n.startsWith("~/")||n.startsWith("~\\")?Gn(n.replace(/^~[/\\]+/,"~/")):n).map(n=>Xn(n))}function P0(){try{return[He(Xn(Oi(ne(),"config")))]}catch(t){return Ut(t),[]}}var Lh=".afk/";function M0(){try{let t=ne();return wo.filter(e=>e.startsWith(Lh)).map(e=>Uh(Oi(t,e.slice(Lh.length))))}catch(t){return Ut(t),[]}}function Bh(){let t=`${b.AFK_READ_DENYLIST??""}\0${b.AFK_HOME??""}`;if(bo&&bo.key===t)return bo;let e=$h(b.AFK_READ_DENYLIST).map(i=>He(i)).filter(Boolean),n=Nh.map(i=>({source:i,root:He(Xn(i))})),r=P0(),o=[...new Set([...n.map(({root:i})=>i),...r])],s=n.filter(({source:i,root:a})=>i!==C0||!r.includes(a)).map(({root:i})=>i);return bo={key:t,builtins:o,extras:e,allow:[...new Set([...Dh(wo.map(i=>({rel:i,resolved:Uh(`${Z()}/${i}`)})),n),..._d(M0(),s)])]},bo}function jh(){let{builtins:t,extras:e}=Bh();return[...t,...e]}function Hh(t){let e=He(Xn(t));return jh().filter(n=>n!==e&&Kn(n,e,n)).map(n=>(n.startsWith(e+yo)?I0(e,n):n.split(yo).slice(e.split(yo).length).join(yo)).split(yo).join("/"))}function dn(t){let e=He(Xn(t)),{builtins:n,extras:r,allow:o}=Bh();for(let s of r)if(Kn(e,s))return{denied:!0,matched:s};if(o.includes(e))return{denied:!1};for(let s of n)if(Kn(e,s))return{denied:!0,matched:s};return{denied:!1}}var Ed="read-denylist entry:",Wh="is a protected credential/secret path";function pn(t){try{return O0.native(t)}catch{let e=un.dirname(t),n=un.basename(t);return e===t?t:un.join(pn(e),n)}}var Kh=new Map;function D0(t){let e=Kh.get(t);if(e!==void 0)return e;let n=pn(t);return Kh.set(t,n),n}function qh(t,e,n,r){let o=e?.resolveBase??e?.cwd??r,s=un.isAbsolute(t)?t:un.resolve(o??process.cwd(),t);if(e?.allowAll===!0)return{restricted:!1,resolved:s,roots:[]};if(o===void 0)return{restricted:!1,resolved:s,roots:[]};let i=pn(s),a=n==="read"?e?.readRoots??[o]:e?.writeRoots??[o];for(let c of a){let l=D0(c),d=un.relative(l,i);if(!d.startsWith("..")&&!un.isAbsolute(d))return{restricted:!1,resolved:s,roots:a}}return{restricted:!0,resolved:s,roots:a}}function ee(t,e,n="read",r){let{restricted:o,resolved:s,roots:i}=qh(t,e,n,r);if(n==="read"){let a=dn(s);if(a.denied)throw new Error(`Path \`${t}\` ${Wh} (${Ed} \`${a.matched}\`) and cannot be read.`)}if(o){let a=i.map(l=>`\`${l}\``).join(", "),c=n==="read"?"read roots":"write roots";throw new Error(`Path \`${t}\` is outside the allowed ${c} [${a}].`)}return s}function Gh(t,e,n="read",r){return qh(t,e,n,r)}function Xh(t){let e=new Set,n=[];for(let r of t.split(/\s+/)){if(r.length===0)continue;let o=r.replace(/^\d*[<>|&]+/,"").replace(/^['"]/,"").replace(/['";,)]+$/,"");if(o.length===0)continue;let s=o.startsWith("/"),i=o==="~"||o.startsWith("~/");!s&&!i||e.has(o)||(e.add(o),n.push(o))}return n}import{execFileSync as F0}from"node:child_process";function fn(t,e="SIGKILL"){if(!(t<=0))try{process.platform==="win32"?F0("taskkill",["/F","/T","/PID",String(t)],{stdio:"ignore",timeout:5e3}):process.kill(-t,e)}catch{}}function U0(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(e.timeout_ms<0||e.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=e.timeout_ms}return{command:e.command,timeout_ms:n}}function Di(t,e){let n=!1,r=!1;function o(){n||t==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}function s(i,a){if(r)return;let c=a.resolveBase??a.cwd??e,l=N0.homedir(),d=[];for(let u of Xh(i)){let p=u==="~"?l:u.startsWith("~/")?l+u.slice(1):u,f=Gh(p,a,"write",c);f.restricted&&d.push(f.resolved)}d.length!==0&&(r=!0,console.warn(`[security] bash: command references path(s) outside writeRoots: ${d.join(", ")} \u2014 bash containment is best-effort (tracked C4); use file tools for contained writes.`),Ee({event:"tool.bash_path_escape",tool:"bash",restricted_count:d.length,mode:"write"}))}return async(i,a,c)=>{let{command:l,timeout_ms:d}=U0(i);if(a.aborted)return{content:"Command aborted",isError:!0};if(o(),c!==void 0)try{s(l,c)}catch{}return new Promise(u=>{let p=!1;function f(E){p||(p=!0,clearTimeout(g),a.removeEventListener("abort",_),u(E))}let m=L0(l,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(c?.resolveBase??c?.cwd??e)!==void 0?{cwd:c?.resolveBase??c?.cwd??e}:{},...c?.env!==void 0?{env:{...process.env,...c.env}}:{}});m.unref(),c?.spawnedPidRegistry!==void 0&&m.pid!==void 0&&c.spawnedPidRegistry.register(m.pid);let g=setTimeout(()=>{m.pid!==void 0&&fn(m.pid),f({content:`Command timed out after ${d}ms`,isError:!0})},d),h="",y="",w=0,k=!1;function v(E){if(k||p||w<8e6)return;k=!0,console.warn(`[bash] overflow kill: stream=${E} totalBytes=${w} command="${l}"`),Ee({event:"tool.overflow_kill",tool:"bash",total_bytes:w,stream:E}),m.kill("SIGKILL");let T=Ae((h+y).trimEnd()),I=go(T)??void 0,S=ot(T,1e5)+Fg;f({content:S,truncated:!0,...I!==void 0?{testResult:I}:{}})}m.stdout.on("data",E=>{let T=8e6-w,I=E.length<=T?E:E.subarray(0,Math.max(0,T));w+=I.length,h+=I.toString("utf8"),v("stdout")}),m.stderr.on("data",E=>{let T=8e6-w,I=E.length<=T?E:E.subarray(0,Math.max(0,T));w+=I.length,y+=I.toString("utf8"),v("stderr")});let _=()=>{m.pid!==void 0&&fn(m.pid),f({content:"Command aborted",isError:!0})};a.addEventListener("abort",_),a.aborted&&_(),m.on("close",E=>{if(a.aborted){f({content:"Command aborted",isError:!0});return}if(E!==null&&E!==0){let A=Un(y.trimEnd()||h.trimEnd());f({content:`Command exited with code ${E}${A.content?`
|
|
204
|
-
`+A.content:""}`,isError:!0,...A.truncated?{truncated:!0}:{}});return}if(
|
|
205
|
-
`),f=Math.max(0,i-1),m=Math.min(p.length,f+a),g=p.slice(f,m),h=p.length;if(g.length===0)return{content:`... (offset ${i} is past end of file \u2014 file has ${h} lines)`};let y=String(h).length,w=g.map((
|
|
206
|
-
`);if(g.length<h){let
|
|
207
|
-
... (showing lines ${
|
|
203
|
+
`;await BM(e,r,{flag:"a"})}catch{}}var qM=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,GM=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,XM=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,zM=/(\d+)\s+passing/,JM=/(\d+)\s+failing/,VM=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,YM=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,QM=/(\d+) examples?, (\d+) failures?/,ZM=/OK \((\d+) tests?/,e0=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/;function t0(t){let e=t.match(qM);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function n0(t){let e=t.match(GM);if(!e)return null;let n=parseInt(e[1]??"0",10);return{runner:"jest",passed:parseInt(e[2]??"0",10),failed:n}}function r0(t){let e=t.match(XM);if(!e)return null;if(e[2]!==void 0){let n=parseInt(e[2],10),r=parseInt(e[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return e[4]!==void 0?{runner:"pytest",passed:parseInt(e[4],10),failed:0}:null}function o0(t){let e=t.match(zM);if(!e)return null;let n=parseInt(e[1]??"0",10),r=t.match(JM),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function s0(t){let e=[...t.matchAll(VM)];if(e.length===0)return null;let n=0,r=0;for(let o of e)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function i0(t){let e=t.match(YM);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10),o=e[3]!==void 0?parseInt(e[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function a0(t){let e=t.match(QM);if(!e)return null;let n=parseInt(e[1]??"0",10),r=parseInt(e[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function c0(t){let e=t.match(ZM);if(e)return{runner:"phpunit",passed:parseInt(e[1]??"0",10),failed:0};let n=t.match(e0);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function go(t){return t0(t)??n0(t)??r0(t)??o0(t)??s0(t)??i0(t)??a0(t)??c0(t)??null}var Rh=/\x1B\][^\x07\x1B\x9C]*(?:\x07|\x1B\\|\x9C)|\x1B[P^_X][^\x1B\x9C]*(?:\x1B\\|\x9C)|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[6-_]/g,l0=/[\x00-\x1F\x7F-\x9F]/g;function we(t){return t.replace(Rh,"").replace(l0," ").trim()}function Ae(t){return t.replace(Rh,"")}import{statSync as d0}from"node:fs";function ho(t){if(typeof t!="object"||t===null)return!1;let e=t;return e.code==="ENOENT"&&typeof e.syscall=="string"&&e.syscall.startsWith("spawn")}function u0(t){if(t===void 0)return!1;try{return d0(t),!1}catch{return!0}}function Wn(t,e){let n=t instanceof Error?t.message:typeof t?.message=="string"?String(t.message):String(t);return ho(t)&&u0(e)?`working directory does not exist: ${e} (deleted worktree?) \u2014 underlying: ${n}`:n}import un from"path";import{realpathSync as O0}from"fs";C();import{basename as x0,dirname as R0,join as Oi,relative as I0,resolve as Xn,sep as yo}from"path";import{homedir as Z}from"os";C();M();import{realpathSync as Oh}from"fs";import{dirname as y0,resolve as ln,join as Pi}from"path";import{homedir as je}from"os";var Ih=new Set;function Ut(t){let e=t instanceof Error?t.message:String(t);Ih.has(e)||(Ih.add(e),console.warn(`[afk-home] Malformed AFK home/state env var ignored while deriving the credential floor: ${e}. The relocated tree is NOT protected \u2014 the default ~/.afk entries still apply. Fix the env var to restore coverage.`))}import{statSync as vd}from"node:fs";import{homedir as p0}from"node:os";import{basename as f0,dirname as Ph,join as m0}from"node:path";var Ch,kd=new Map;function Mh(t){return typeof t=="object"&&t!==null&&"code"in t?String(t.code):void 0}function g0(t){let e=f0(t),n=e===e.toLowerCase()?e.toUpperCase():e.toLowerCase();if(n===e)return;let r;try{r=vd(t)}catch{return}let o=kd.get(r.dev);if(o!==void 0)return o;try{let s=vd(m0(Ph(t),n)),i=r.dev===s.dev&&r.ino===s.ino;return kd.set(r.dev,i),i}catch(s){let i=Mh(s);return i==="ENOENT"||i==="ENOTDIR"?(kd.set(r.dev,!1),!1):void 0}}function h0(t=p0()){if(Ch!==void 0)return Ch;let e=t;for(;;)try{return vd(e),g0(e)??!0}catch(n){let r=Mh(n);if(r!=="ENOENT"&&r!=="ENOTDIR")return!0;let o=Ph(e);if(o===e)return!0;e=o}}function Kn(t,e,n=e){if(t===e||t.startsWith(e+"/")||t.startsWith(e+"\\"))return!0;if(!h0(n))return!1;let r=t.toLowerCase(),o=e.toLowerCase();return r===o||r.startsWith(o+"/")||r.startsWith(o+"\\")}var b0=[`${je()}/.ssh`,`${je()}/.aws`,`${je()}/.gnupg`,`${je()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${je()}/.afk/config`,`${je()}/.afk/state`,`${je()}/.npmrc`,`${je()}/.docker/config.json`,`${je()}/Library/LaunchAgents`,`${je()}/Library/LaunchDaemons`,"/Library/LaunchAgents","/Library/LaunchDaemons",`${je()}/.config/systemd`,...process.platform==="win32"&&b.APPDATA?[`${b.APPDATA}\\gcloud`,`${b.APPDATA}\\Docker`]:[],...process.platform==="win32"&&b.USERPROFILE?[`${b.USERPROFILE}\\.ssh`,`${b.USERPROFILE}\\.aws`,`${b.USERPROFILE}\\.gnupg`]:[]];function w0(){let t=[];try{let e=ne();t.push(ln(Pi(e,"config"))),t.push(ln(Pi(e,"state")))}catch(e){Ut(e)}try{t.push(ln(Q()))}catch(e){Ut(e)}return t}var Ci;function Td(){let t=`${b.AFK_WRITE_DENYLIST??""}\0${b.AFK_HOME??""}\0${b.AFK_STATE_DIR??""}`;if(!Ci||Ci.key!==t){let e=b.AFK_WRITE_DENYLIST,n=process.platform==="win32"?";":":",r=e?e.split(n).map(o=>o.trim()).filter(Boolean).map(o=>o==="~"||o.startsWith("~/")||o.startsWith("~\\")?Pi(je(),o.slice(2)):o).map(o=>ln(o)).filter(Boolean):[];Ci={key:t,unresolved:[...new Set([...b0.map(o=>ln(o)),...w0()]),...r]}}return[...new Set(Ci.unresolved.map(e=>He(e)))]}function He(t){let e=ln(t);try{return Oh(e)}catch{}let n=[],r=e;for(let o=0;o<64;o++){let s=y0(r);if(s===r)break;n.unshift(r.slice(s.length+1)),r=s;try{let i=Oh(r);return Pi(i,...n)}catch{}}return e}function qn(t,e="write_file"){let n=He(ln(t));for(let r of Td())if(Kn(n,r))throw new Error(`${e}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}M();import{isAbsolute as S0,relative as k0,sep as v0}from"node:path";import{homedir as Mi}from"node:os";function T0(t,e){let n=k0(e,t);return n===""||n!==".."&&!n.startsWith(`..${v0}`)&&!S0(n)}function _d(t,e){return t.filter(n=>!e.some(r=>T0(n,r)))}function _0(t,e){return t.filter(({source:n})=>n!==e).map(({root:n})=>n)}var E0={".afk/config/mcp.json":`${Mi()}/.afk/config`,".afk/config/schedules.json":`${Mi()}/.afk/config`,".ssh/config":`${Mi()}/.ssh`,".ssh/known_hosts":`${Mi()}/.ssh`};function Dh(t,e){return t.flatMap(({rel:n,resolved:r})=>_d([r],_0(e,E0[n])))}import{isAbsolute as XV,resolve as A0}from"path";import{homedir as Fh}from"os";function Gn(t){return t==="~"?Fh():t.startsWith("~/")?A0(Fh(),t.slice(2)):t}var Nh=[`${Z()}/.ssh`,`${Z()}/.aws`,`${Z()}/.gnupg`,`${Z()}/.config/gcloud`,`${Z()}/.afk/config`,`${Z()}/.npmrc`,`${Z()}/.docker/config.json`,`${Z()}/.git-credentials`,`${Z()}/.netrc`,`${Z()}/.config/gh/hosts.yml`,`${Z()}/.kube/config`,"/etc/shadow","/etc/sudoers","/private/etc/master.passwd",`${Z()}/.password-store`,`${Z()}/Library/Application Support/Google/Chrome`,`${Z()}/Library/Application Support/Chromium`,`${Z()}/Library/Application Support/BraveSoftware`,`${Z()}/Library/Application Support/Microsoft Edge`,`${Z()}/Library/Application Support/Arc`,`${Z()}/Library/Application Support/Firefox`,...process.platform==="win32"&&b.USERPROFILE?[`${b.USERPROFILE}\\.ssh`,`${b.USERPROFILE}\\.aws`,`${b.USERPROFILE}\\.gnupg`]:[],...process.platform==="win32"&&b.APPDATA?[`${b.APPDATA}\\gcloud`,`${b.APPDATA}\\Docker`,`${b.APPDATA}\\Mozilla\\Firefox`]:[],...process.platform==="win32"&&b.LOCALAPPDATA?[`${b.LOCALAPPDATA}\\Google\\Chrome`,`${b.LOCALAPPDATA}\\Chromium`,`${b.LOCALAPPDATA}\\BraveSoftware`,`${b.LOCALAPPDATA}\\Microsoft\\Edge`]:[]],wo=[".afk/config/mcp.json",".afk/config/schedules.json",".ssh/config",".ssh/known_hosts"],C0=`${Z()}/.afk/config`,s5=wo.map(t=>Oi(Z(),t));function Uh(t){let e=Xn(t);return Oi(He(R0(e)),x0(e))}var bo;function $h(t){if(!t)return[];let e=process.platform==="win32"?";":":";return t.split(e).map(n=>n.trim()).filter(Boolean).map(n=>n==="~"||n.startsWith("~/")||n.startsWith("~\\")?Gn(n.replace(/^~[/\\]+/,"~/")):n).map(n=>Xn(n))}function P0(){try{return[He(Xn(Oi(ne(),"config")))]}catch(t){return Ut(t),[]}}var Lh=".afk/";function M0(){try{let t=ne();return wo.filter(e=>e.startsWith(Lh)).map(e=>Uh(Oi(t,e.slice(Lh.length))))}catch(t){return Ut(t),[]}}function Bh(){let t=`${b.AFK_READ_DENYLIST??""}\0${b.AFK_HOME??""}`;if(bo&&bo.key===t)return bo;let e=$h(b.AFK_READ_DENYLIST).map(i=>He(i)).filter(Boolean),n=Nh.map(i=>({source:i,root:He(Xn(i))})),r=P0(),o=[...new Set([...n.map(({root:i})=>i),...r])],s=n.filter(({source:i,root:a})=>i!==C0||!r.includes(a)).map(({root:i})=>i);return bo={key:t,builtins:o,extras:e,allow:[...new Set([...Dh(wo.map(i=>({rel:i,resolved:Uh(`${Z()}/${i}`)})),n),..._d(M0(),s)])]},bo}function jh(){let{builtins:t,extras:e}=Bh();return[...t,...e]}function Hh(t){let e=He(Xn(t));return jh().filter(n=>n!==e&&Kn(n,e,n)).map(n=>(n.startsWith(e+yo)?I0(e,n):n.split(yo).slice(e.split(yo).length).join(yo)).split(yo).join("/"))}function dn(t){let e=He(Xn(t)),{builtins:n,extras:r,allow:o}=Bh();for(let s of r)if(Kn(e,s))return{denied:!0,matched:s};if(o.includes(e))return{denied:!1};for(let s of n)if(Kn(e,s))return{denied:!0,matched:s};return{denied:!1}}var Ed="read-denylist entry:",Wh="is a protected credential/secret path";function pn(t){try{return O0.native(t)}catch{let e=un.dirname(t),n=un.basename(t);return e===t?t:un.join(pn(e),n)}}var Kh=new Map;function D0(t){let e=Kh.get(t);if(e!==void 0)return e;let n=pn(t);return Kh.set(t,n),n}function qh(t,e,n,r){let o=e?.resolveBase??e?.cwd??r,s=un.isAbsolute(t)?t:un.resolve(o??process.cwd(),t);if(e?.allowAll===!0)return{restricted:!1,resolved:s,roots:[]};if(o===void 0)return{restricted:!1,resolved:s,roots:[]};let i=pn(s),a=n==="read"?e?.readRoots??[o]:e?.writeRoots??[o];for(let c of a){let l=D0(c),d=un.relative(l,i);if(!d.startsWith("..")&&!un.isAbsolute(d))return{restricted:!1,resolved:s,roots:a}}return{restricted:!0,resolved:s,roots:a}}function ee(t,e,n="read",r){let{restricted:o,resolved:s,roots:i}=qh(t,e,n,r);if(n==="read"){let a=dn(s);if(a.denied)throw new Error(`Path \`${t}\` ${Wh} (${Ed} \`${a.matched}\`) and cannot be read.`)}if(o){let a=i.map(l=>`\`${l}\``).join(", "),c=n==="read"?"read roots":"write roots";throw new Error(`Path \`${t}\` is outside the allowed ${c} [${a}].`)}return s}function Gh(t,e,n="read",r){return qh(t,e,n,r)}function Xh(t){let e=new Set,n=[];for(let r of t.split(/\s+/)){if(r.length===0)continue;let o=r.replace(/^\d*[<>|&]+/,"").replace(/^['"]/,"").replace(/['";,)]+$/,"");if(o.length===0)continue;let s=o.startsWith("/"),i=o==="~"||o.startsWith("~/");!s&&!i||e.has(o)||(e.add(o),n.push(o))}return n}import{execFileSync as F0}from"node:child_process";function fn(t,e="SIGKILL"){if(!(t<=0))try{process.platform==="win32"?F0("taskkill",["/F","/T","/PID",String(t)],{stdio:"ignore",timeout:5e3}):process.kill(-t,e)}catch{}}function U0(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(e.timeout_ms<0||e.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=e.timeout_ms}return{command:e.command,timeout_ms:n}}function Di(t,e){let n=!1,r=!1;function o(){n||t==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}function s(i,a){if(r)return;let c=a.resolveBase??a.cwd??e,l=N0.homedir(),d=[];for(let u of Xh(i)){let p=u==="~"?l:u.startsWith("~/")?l+u.slice(1):u,f=Gh(p,a,"write",c);f.restricted&&d.push(f.resolved)}d.length!==0&&(r=!0,console.warn(`[security] bash: command references path(s) outside writeRoots: ${d.join(", ")} \u2014 bash containment is best-effort (tracked C4); use file tools for contained writes.`),Ee({event:"tool.bash_path_escape",tool:"bash",restricted_count:d.length,mode:"write"}))}return async(i,a,c)=>{let{command:l,timeout_ms:d}=U0(i);if(a.aborted)return{content:"Command aborted",isError:!0};if(o(),c!==void 0)try{s(l,c)}catch{}return new Promise(u=>{let p=!1;function f(E){p||(p=!0,clearTimeout(g),a.removeEventListener("abort",_),u(E))}let m=L0(l,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(c?.resolveBase??c?.cwd??e)!==void 0?{cwd:c?.resolveBase??c?.cwd??e}:{},...c?.env!==void 0?{env:{...process.env,...c.env}}:{}});m.unref(),c?.spawnedPidRegistry!==void 0&&m.pid!==void 0&&c.spawnedPidRegistry.register(m.pid);let g=setTimeout(()=>{m.pid!==void 0&&fn(m.pid),f({content:`Command timed out after ${d}ms`,isError:!0})},d),h="",y="",w=0,S=!1;function v(E){if(S||p||w<8e6)return;S=!0,console.warn(`[bash] overflow kill: stream=${E} totalBytes=${w} command="${l}"`),Ee({event:"tool.overflow_kill",tool:"bash",total_bytes:w,stream:E}),m.kill("SIGKILL");let T=Ae((h+y).trimEnd()),I=go(T)??void 0,k=ot(T,1e5)+Fg;f({content:k,truncated:!0,...I!==void 0?{testResult:I}:{}})}m.stdout.on("data",E=>{let T=8e6-w,I=E.length<=T?E:E.subarray(0,Math.max(0,T));w+=I.length,h+=I.toString("utf8"),v("stdout")}),m.stderr.on("data",E=>{let T=8e6-w,I=E.length<=T?E:E.subarray(0,Math.max(0,T));w+=I.length,y+=I.toString("utf8"),v("stderr")});let _=()=>{m.pid!==void 0&&fn(m.pid),f({content:"Command aborted",isError:!0})};a.addEventListener("abort",_),a.aborted&&_(),m.on("close",E=>{if(a.aborted){f({content:"Command aborted",isError:!0});return}if(E!==null&&E!==0){let A=Un(y.trimEnd()||h.trimEnd());f({content:`Command exited with code ${E}${A.content?`
|
|
204
|
+
`+A.content:""}`,isError:!0,...A.truncated?{truncated:!0}:{}});return}if(S)return;let T=Ae((h+y).trimEnd()),I=go(T)??void 0,k=Un(T);f({content:k.content,...k.truncated?{truncated:!0}:{},...I!==void 0?{testResult:I}:{}})}),m.on("error",E=>{let T=c?.resolveBase??c?.cwd??e,I;if(T===void 0&&ho(E))try{let k=process.cwd();I=Wn(E,k)}catch{I=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${E.message}`}else I=Wn(E,T);f({content:`Failed to execute: ${I}`,isError:!0})})})}}var zh=Di("default");import{promises as $0}from"fs";function We(t,e,n="Path"){if(!(t instanceof Error))return;let r=t.code;if(r==="ENOENT")return{content:`${n} not found: ${e}`,isError:!0};if(r==="EACCES")return{content:`Permission denied: ${e}`,isError:!0};if(r==="ENOTDIR")return{content:`Not a directory: ${e}`,isError:!0}}var B0=async(t,e,n,r)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t,s=o.file_path,i=o.offset??1,a=o.limit??2e3;if(typeof s!="string")return{content:"Invalid input: file_path must be a string",isError:!0};if(typeof i!="number"||i<1)return{content:"Invalid input: offset must be a positive number",isError:!0};if(typeof a!="number"||a<1)return{content:"Invalid input: limit must be a positive number",isError:!0};let c;try{c=ee(s,n,"read",r)}catch(l){return{content:l instanceof Error?l.message:String(l),isError:!0}}try{let l=await $0.readFile(c),d=Math.min(8192,l.length);for(let S=0;S<d;S++)if(l[S]===0)return{content:`File appears to be binary: ${c}. Use extract_document for .docx, .pdf, .xlsx, .pptx, and .zip files.`,isError:!0};let u=l.toString("utf-8");if(u.length===0)return{content:""};let p=u.split(`
|
|
205
|
+
`),f=Math.max(0,i-1),m=Math.min(p.length,f+a),g=p.slice(f,m),h=p.length;if(g.length===0)return{content:`... (offset ${i} is past end of file \u2014 file has ${h} lines)`};let y=String(h).length,w=g.map((S,v)=>{let _=f+v+1;return`${String(_).padStart(y," ")} ${S}`}).join(`
|
|
206
|
+
`);if(g.length<h){let S=f+1,v=f+g.length,_=v<h?` \u2014 pass offset=${v+1} to continue`:"";return{content:`${w}
|
|
207
|
+
... (showing lines ${S}-${v} of ${h}${_})`}}return{content:w}}catch(l){let d=We(l,c,"File");return d||(l instanceof Error?{content:`Error reading file: ${l.message}`,isError:!0}:{content:"Unknown error reading file",isError:!0})}};function xd(t){return(e,n,r)=>B0(e,n,r,t)}var Jh=xd();import{promises as Vh}from"fs";import{spawn as j0}from"child_process";import{extname as Qh,basename as H0,normalize as W0,isAbsolute as K0}from"path";import{createInflateRaw as q0}from"zlib";var mn=4*1024*1024,Fi=512*1024;function Li(t){let e=-1;for(let i=t.length-22;i>=0&&i>=t.length-65557;i--)if(t.readUInt32LE(i)===101010256){e=i;break}if(e===-1)throw new Error("Not a valid ZIP file (no EOCD record)");let n=t.readUInt32LE(e+16),r=t.readUInt16LE(e+10),o=[],s=n;for(let i=0;i<r&&s+46<=t.length&&t.readUInt32LE(s)===33639248;i++){let a=t.readUInt16LE(s+10),c=t.readUInt32LE(s+20),l=t.readUInt32LE(s+24),d=t.readUInt16LE(s+28),u=t.readUInt16LE(s+30),p=t.readUInt16LE(s+32),f=t.readUInt32LE(s+42),m=t.subarray(s+46,s+46+d).toString("utf-8");o.push({name:m,compressedSize:c,uncompressedSize:l,compressionMethod:a,localHeaderOffset:f}),s+=46+d+u+p}return o}function G0(t){return!(K0(t)||W0(t).startsWith(".."))}async function So(t,e){if(e.uncompressedSize>mn)throw new Error(`Entry ${e.name} too large (${e.uncompressedSize} bytes, cap ${mn})`);let n=e.localHeaderOffset;if(n+30>t.length||t.readUInt32LE(n)!==67324752)throw new Error(`Invalid local header for ${e.name}`);let r=t.readUInt16LE(n+26),o=t.readUInt16LE(n+28),s=n+30+r+o,i=t.subarray(s,s+e.compressedSize);if(e.compressionMethod===0)return Buffer.from(i);if(e.compressionMethod===8)return new Promise((a,c)=>{let l=q0(),d=[],u=0;l.on("data",p=>{if(u+=p.length,u>mn){l.destroy(),c(new Error("Decompression cap exceeded"));return}d.push(p)}),l.on("end",()=>a(Buffer.concat(d))),l.on("error",c),l.end(i)});throw new Error(`Unsupported compression method ${e.compressionMethod} for ${e.name}`)}function Zh(t){return t.replace(/<w:p\b[^>]*\/>/g,`
|
|
208
208
|
`).replace(/<\/w:p>/g,`
|
|
209
209
|
`).replace(/<w:tab\/>/g," ").replace(/<w:br[^>]*\/>/g,`
|
|
210
210
|
`).replace(/<w:del\b[^>]*>[\s\S]*?<\/w:del>/g,"").replace(/<[^>]+>/g,"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/\n{3,}/g,`
|
|
@@ -228,7 +228,7 @@ ${o.text}`)}return n.join(`
|
|
|
228
228
|
|
|
229
229
|
[\u2026 truncated]`:u}}let c=await Vh.stat(i);if(c.size>mn*2)return{content:`File too large (${c.size} bytes). Max supported: ${mn*2} bytes.`,isError:!0};let l=await Vh.readFile(i),d;switch(a){case".docx":d=await X0(l);break;case".xlsx":d=await z0(l);break;case".pptx":d=await J0(l);break;case".zip":d=await V0(l);break;default:d="[Unsupported format]";break}return{content:d.length>Fi?d.slice(0,Fi)+`
|
|
230
230
|
|
|
231
|
-
[\u2026 truncated]`:d}}catch(c){let l=We(c,i,"File");return l||(c instanceof Error?{content:`Error extracting document: ${c.message}`,isError:!0}:{content:"Unknown error extracting document",isError:!0})}};function Rd(t){return(e,n,r)=>Q0(e,n,r,t)}var ey=Rd();C();import{readFile as tO,writeFile as nO,mkdir as rO,stat as oO}from"fs/promises";import{dirname as sO}from"path";function ty(t){if(t==="")return[];let e=t.split(/\r?\n/);return e.length>0&&e[e.length-1]===""&&/\r?\n$/.test(t)&&e.pop(),e}function Z0(t,e){let n=t.length,r=e.length;if((n+1)*(r+1)>=4e6){let l=[];for(let d of t)l.push({op:"del",text:d});for(let d of e)l.push({op:"add",text:d});return l}let o=r+1,s=new Int32Array((n+1)*o);for(let l=1;l<=n;l++)for(let d=1;d<=r;d++)if(t[l-1]===e[d-1])s[l*o+d]=s[(l-1)*o+(d-1)]+1;else{let u=s[(l-1)*o+d],p=s[l*o+(d-1)];s[l*o+d]=u>=p?u:p}let i=[],a=n,c=r;for(;a>0||c>0;)a>0&&c>0&&t[a-1]===e[c-1]?(i.push({op:"same",text:t[a-1]}),a--,c--):c>0&&(a===0||s[a*o+(c-1)]>=s[(a-1)*o+c])?(i.push({op:"add",text:e[c-1]}),c--):(i.push({op:"del",text:t[a-1]}),a--);return i.reverse(),i}function eO(t){let e=new Int32Array(t.length+1);e[t.length]=t.length;for(let i=t.length-1;i>=0;i--)e[i]=t[i].op==="same"?e[i+1]:i;let n=[],r=1,o=1,s=0;for(;s<t.length;){if(t[s].op==="same"){r++,o++,s++;continue}let i=s,a=0;for(;i>0&&t[i-1].op==="same"&&a<3;)i--,a++;let c=Math.max(1,r-a),l=Math.max(1,o-a),d=[],u=0,p=0;for(let m=i;m<s;m++)d.push({kind:" ",text:t[m].text}),u++,p++;let f=!1;for(;!f&&s<t.length;){let m=t[s];if(m.op==="same"){let g=e[s],h=g-s;if(g===t.length||h>6){for(let w=0;w<3&&s<t.length&&t[s].op==="same";w++)d.push({kind:" ",text:t[s].text}),u++,p++,r++,o++,s++;f=!0}else d.push({kind:" ",text:m.text}),u++,p++,r++,o++,s++}else m.op==="add"?(d.push({kind:"+",text:m.text}),p++,o++,s++):(d.push({kind:"-",text:m.text}),u++,r++,s++)}n.push({oldStart:c,oldLines:u,newStart:l,newLines:p,lines:d})}return n}function Jn(t,e){if(t===e)return null;let n=ty(t),r=ty(e),o=Z0(n,r),s=eO(o);if(s.length===0)return null;let i=0,a=0;for(let c of s)for(let l of c.lines)l.kind==="+"?i++:l.kind==="-"&&a++;return{hunks:s,addedLines:i,removedLines:a}}function iO(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.content!="string")throw new Error('Input must have a "content" field of type string');return{file_path:e.file_path,content:e.content}}var aO=async(t,e,n,r)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:o,content:s}=iO(t),i;try{i=ee(o,n,"write",r)}catch(a){return{content:a instanceof Error?a.message:String(a),isError:!0}}try{qn(i,"write_file");let a=(()=>{let f=b.AFK_WRITE_DIFF;if(f===void 0)return!1;let m=f.trim().toLowerCase();return m==="0"||m==="false"||m==="no"||m==="off"})(),c=10*1024*1024,l=null;if(!a)try{let f=await oO(i);if(f.size>c)b.AFK_DEBUG&&console.debug(`[write_file] skipping diff: prior file ${f.size} bytes > ${c}`);else{let m=await tO(i);try{l=new TextDecoder("utf-8",{fatal:!0}).decode(m)}catch{l=null}}}catch(f){f instanceof Error&&"code"in f&&f.code==="ENOENT"&&(l="")}let d=sO(i);await rO(d,{recursive:!0}),await nO(i,s,{signal:e});let u=null;if(l!==null&&!s.includes("\0")){let f=performance.now();u=Jn(l,s);let m=performance.now()-f;m>=500?console.warn(`[write_file] computeLineDiff took ${m.toFixed(1)}ms`):m>=50&&b.AFK_DEBUG&&console.debug(`[write_file] computeLineDiff took ${m.toFixed(1)}ms`)}return{content:`Wrote ${Buffer.byteLength(s,"utf8")} bytes to ${i}`,...u?{render:{diff:u}}:{}}}catch(a){let c=We(a,i);return c||(a instanceof Error?{content:`Error writing file: ${a.message}`,isError:!0}:{content:"Unknown error writing file",isError:!0})}};function Id(t){return(e,n,r)=>aO(e,n,r,t)}var ny=Id();C();import{readFile as cO,writeFile as lO,stat as ry}from"fs/promises";function dO(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.old_string!="string")throw new Error('Input must have an "old_string" field of type string');if(typeof e.new_string!="string")throw new Error('Input must have a "new_string" field of type string');let n=!1;if(e.replace_all!==void 0){if(typeof e.replace_all!="boolean")throw new Error("replace_all must be a boolean");n=e.replace_all}return{file_path:e.file_path,old_string:e.old_string,new_string:e.new_string,replace_all:n}}function uO(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}var pO=async(t,e,n,r)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:o,old_string:s,new_string:i,replace_all:a}=dO(t),c;try{c=ee(o,n,"write",r)}catch(l){return{content:l instanceof Error?l.message:String(l),isError:!0}}try{qn(c,"edit_file");let d=(await ry(c)).mtimeMs,u=await cO(c,"utf-8"),p=uO(u,s);if(p===0)return{content:`old_string not found in ${c}`,isError:!0};if(p>1&&!a)return{content:`old_string matches ${p} locations in ${c}. Use replace_all: true or provide more context.`,isError:!0};let f;if(a)f=u.split(s).join(i);else{let
|
|
231
|
+
[\u2026 truncated]`:d}}catch(c){let l=We(c,i,"File");return l||(c instanceof Error?{content:`Error extracting document: ${c.message}`,isError:!0}:{content:"Unknown error extracting document",isError:!0})}};function Rd(t){return(e,n,r)=>Q0(e,n,r,t)}var ey=Rd();C();import{readFile as tO,writeFile as nO,mkdir as rO,stat as oO}from"fs/promises";import{dirname as sO}from"path";function ty(t){if(t==="")return[];let e=t.split(/\r?\n/);return e.length>0&&e[e.length-1]===""&&/\r?\n$/.test(t)&&e.pop(),e}function Z0(t,e){let n=t.length,r=e.length;if((n+1)*(r+1)>=4e6){let l=[];for(let d of t)l.push({op:"del",text:d});for(let d of e)l.push({op:"add",text:d});return l}let o=r+1,s=new Int32Array((n+1)*o);for(let l=1;l<=n;l++)for(let d=1;d<=r;d++)if(t[l-1]===e[d-1])s[l*o+d]=s[(l-1)*o+(d-1)]+1;else{let u=s[(l-1)*o+d],p=s[l*o+(d-1)];s[l*o+d]=u>=p?u:p}let i=[],a=n,c=r;for(;a>0||c>0;)a>0&&c>0&&t[a-1]===e[c-1]?(i.push({op:"same",text:t[a-1]}),a--,c--):c>0&&(a===0||s[a*o+(c-1)]>=s[(a-1)*o+c])?(i.push({op:"add",text:e[c-1]}),c--):(i.push({op:"del",text:t[a-1]}),a--);return i.reverse(),i}function eO(t){let e=new Int32Array(t.length+1);e[t.length]=t.length;for(let i=t.length-1;i>=0;i--)e[i]=t[i].op==="same"?e[i+1]:i;let n=[],r=1,o=1,s=0;for(;s<t.length;){if(t[s].op==="same"){r++,o++,s++;continue}let i=s,a=0;for(;i>0&&t[i-1].op==="same"&&a<3;)i--,a++;let c=Math.max(1,r-a),l=Math.max(1,o-a),d=[],u=0,p=0;for(let m=i;m<s;m++)d.push({kind:" ",text:t[m].text}),u++,p++;let f=!1;for(;!f&&s<t.length;){let m=t[s];if(m.op==="same"){let g=e[s],h=g-s;if(g===t.length||h>6){for(let w=0;w<3&&s<t.length&&t[s].op==="same";w++)d.push({kind:" ",text:t[s].text}),u++,p++,r++,o++,s++;f=!0}else d.push({kind:" ",text:m.text}),u++,p++,r++,o++,s++}else m.op==="add"?(d.push({kind:"+",text:m.text}),p++,o++,s++):(d.push({kind:"-",text:m.text}),u++,r++,s++)}n.push({oldStart:c,oldLines:u,newStart:l,newLines:p,lines:d})}return n}function Jn(t,e){if(t===e)return null;let n=ty(t),r=ty(e),o=Z0(n,r),s=eO(o);if(s.length===0)return null;let i=0,a=0;for(let c of s)for(let l of c.lines)l.kind==="+"?i++:l.kind==="-"&&a++;return{hunks:s,addedLines:i,removedLines:a}}function iO(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.content!="string")throw new Error('Input must have a "content" field of type string');return{file_path:e.file_path,content:e.content}}var aO=async(t,e,n,r)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:o,content:s}=iO(t),i;try{i=ee(o,n,"write",r)}catch(a){return{content:a instanceof Error?a.message:String(a),isError:!0}}try{qn(i,"write_file");let a=(()=>{let f=b.AFK_WRITE_DIFF;if(f===void 0)return!1;let m=f.trim().toLowerCase();return m==="0"||m==="false"||m==="no"||m==="off"})(),c=10*1024*1024,l=null;if(!a)try{let f=await oO(i);if(f.size>c)b.AFK_DEBUG&&console.debug(`[write_file] skipping diff: prior file ${f.size} bytes > ${c}`);else{let m=await tO(i);try{l=new TextDecoder("utf-8",{fatal:!0}).decode(m)}catch{l=null}}}catch(f){f instanceof Error&&"code"in f&&f.code==="ENOENT"&&(l="")}let d=sO(i);await rO(d,{recursive:!0}),await nO(i,s,{signal:e});let u=null;if(l!==null&&!s.includes("\0")){let f=performance.now();u=Jn(l,s);let m=performance.now()-f;m>=500?console.warn(`[write_file] computeLineDiff took ${m.toFixed(1)}ms`):m>=50&&b.AFK_DEBUG&&console.debug(`[write_file] computeLineDiff took ${m.toFixed(1)}ms`)}return{content:`Wrote ${Buffer.byteLength(s,"utf8")} bytes to ${i}`,...u?{render:{diff:u}}:{}}}catch(a){let c=We(a,i);return c||(a instanceof Error?{content:`Error writing file: ${a.message}`,isError:!0}:{content:"Unknown error writing file",isError:!0})}};function Id(t){return(e,n,r)=>aO(e,n,r,t)}var ny=Id();C();import{readFile as cO,writeFile as lO,stat as ry}from"fs/promises";function dO(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let e=t;if(typeof e.file_path!="string")throw new Error('Input must have a "file_path" field of type string');if(typeof e.old_string!="string")throw new Error('Input must have an "old_string" field of type string');if(typeof e.new_string!="string")throw new Error('Input must have a "new_string" field of type string');let n=!1;if(e.replace_all!==void 0){if(typeof e.replace_all!="boolean")throw new Error("replace_all must be a boolean");n=e.replace_all}return{file_path:e.file_path,old_string:e.old_string,new_string:e.new_string,replace_all:n}}function uO(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}var pO=async(t,e,n,r)=>{if(e.aborted)return{content:"Aborted",isError:!0};let{file_path:o,old_string:s,new_string:i,replace_all:a}=dO(t),c;try{c=ee(o,n,"write",r)}catch(l){return{content:l instanceof Error?l.message:String(l),isError:!0}}try{qn(c,"edit_file");let d=(await ry(c)).mtimeMs,u=await cO(c,"utf-8"),p=uO(u,s);if(p===0)return{content:`old_string not found in ${c}`,isError:!0};if(p>1&&!a)return{content:`old_string matches ${p} locations in ${c}. Use replace_all: true or provide more context.`,isError:!0};let f;if(a)f=u.split(s).join(i);else{let S=u.indexOf(s);f=u.slice(0,S)+i+u.slice(S+s.length)}if((await ry(c)).mtimeMs!==d)return{content:`edit_file aborted: ${c} was modified by another process between read and write (mtime changed). Re-read the file and retry.`,isError:!0};await lO(c,f,"utf-8");let g=p===1?`Replaced 1 occurrence in ${c}`:`Replaced ${p} occurrences in ${c}`,h=performance.now(),y=Jn(u,f),w=performance.now()-h;return w>=500?console.warn(`[edit_file] computeLineDiff took ${w.toFixed(1)}ms`):w>=50&&b.AFK_DEBUG&&console.debug(`[edit_file] computeLineDiff took ${w.toFixed(1)}ms`),{content:g,...y?{render:{diff:y}}:{}}}catch(l){return{content:`Error: ${l instanceof Error?l.message:String(l)}`,isError:!0}}};function Cd(t){return(e,n,r)=>pO(e,n,r,t)}var oy=Cd();import{promises as sy}from"fs";import fO from"path";var mO=new Set(["node_modules",".git",".hg",".svn"]);function gO(t){let e=new Set;for(let n of t.replace(/\\/g,"/").split("/"))n!==""&&!n.includes("*")&&!n.includes("?")&&e.add(n);return e}function hO(t){let e=t.replace(/\\/g,"/"),n=new Set([".","+","^","$","{","}","(",")","|","[","]"]),r="",o=0,s=e.length;for(;o<s;){let i=e.charAt(o);if(i==="*"){let a=o+1;for(;a<s&&e.charAt(a)==="*";)a++;let c=a-o>=2,l=o===0||e.charAt(o-1)==="/",d=a===s||e.charAt(a)==="/";c&&l&&d?a===s?r+=".*":(r+="(?:.*/)?",a++):r+="[^/]*",o=a;continue}if(i==="?"){r+="[^/]",o++;continue}r+=n.has(i)?`\\${i}`:i,o++}return new RegExp(`^${r}$`)}async function yO(t,e){let n=[],o=gO(e),s=hO(e);async function i(a,c){if(n.length>=500)return!0;try{let l=await sy.readdir(a,{withFileTypes:!0});for(let d of l){if(n.length>=500)return!0;let u=fO.join(a,d.name),p=c?`${c}/${d.name}`:d.name;if(!dn(u).denied&&(s.test(p)&&n.push(p),d.isDirectory())){if(mO.has(d.name)&&!o.has(d.name))continue;if(await i(u,p))return!0}}}catch{}return!1}return await i(t,""),n}function Pd(t){return async(e,n,r)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let o=e,s=o.pattern,i=o.path??r?.resolveBase??r?.cwd??t??process.cwd();if(typeof s!="string")return{content:"Invalid input: pattern must be a string",isError:!0};if(s.trim()==="")return{content:"Invalid input: pattern cannot be empty",isError:!0};if(typeof i!="string")return{content:"Invalid input: path must be a string",isError:!0};let a;try{a=ee(i,r,"read")}catch(c){return{content:c instanceof Error?c.message:String(c),isError:!0}}try{if(!(await sy.stat(a)).isDirectory())return{content:`Invalid input: path is not a directory: ${a}`,isError:!0};let l=await yO(a,s);if(l.length===0)return{content:`No files matched pattern '${s}' in ${a}`};let d=l.join(`
|
|
232
232
|
`);return l.length>=500&&(d+=`
|
|
233
233
|
[results capped at 500 entries]`),{content:d}}catch(c){let l=We(c,a,"Path");return l||(c instanceof Error?{content:`Error scanning directory: ${c.message}`,isError:!0}:{content:"Unknown error scanning directory",isError:!0})}}}var iy=Pd();import{spawn as EO}from"child_process";import{accessSync as bO,constants as wO}from"node:fs";function ay(t){try{bO(t,wO.X_OK);return}catch(e){let n=e instanceof Error?e.message:String(e);return`ripgrep binary is missing or not executable: ${t} (the @vscode/ripgrep platform optional-dependency for ${process.platform}-${process.arch} may not be installed \u2014 e.g. an install with --no-optional, an unsupported platform/arch, or a corrupted node_modules) \u2014 underlying: ${n}`}}var SO=/No such file or directory \(os error 2\)$/;function cy(t,e){let n=t.split(`
|
|
234
234
|
`).map(s=>s.trim()).filter(s=>s.length>0);if(n.length>0&&n.every(s=>SO.test(s))&&n.some(s=>s.includes(e)))return{content:`grep: no such path: ${e} \u2014 nothing was searched. Verify the path with the \`glob\` tool, or omit \`path\` to search the session root.`,isError:!0,failureClass:"no-such-target"};let o=Un(t.trim());return{content:`grep error: ${o.content}`,isError:!0,...o.truncated?{truncated:!0}:{}}}function ly(t){return`
|
|
@@ -236,7 +236,7 @@ ${o.text}`)}return n.join(`
|
|
|
236
236
|
|
|
237
237
|
\u2026 [${c-g.length-h.length} bytes truncated: showing first ${g.length} + last ${h.length} of ${c}; ${l} matching lines total] \u2026
|
|
238
238
|
|
|
239
|
-
`;return g.toString("utf8")+w+h.toString("utf8")}return{push:d,totalBytes:()=>c,totalLines:()=>l,truncated:()=>s+a<c,render:u}}function AO(t,e,n){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let r=t;if(typeof r.pattern!="string")throw new Error('Input must have a "pattern" field of type string');let o=typeof r.path=="string"?r.path:e?.resolveBase??e?.cwd??n??process.cwd(),s=ee(o,e,"read"),i;if(r.include!==void 0){if(typeof r.include!="string")throw new Error("include must be a string");i=r.include}return{pattern:r.pattern,path:s,include:i}}function Od(t,e){let n=e?.scanCapBytes??256e6;return async(r,o,s)=>{let{pattern:i,path:a,include:c}=AO(r,s,t);if(o.aborted)return{content:"Search aborted",isError:!0};let l;try{({rgPath:l}=await import("@vscode/ripgrep"))}catch(d){return{content:`Failed to execute grep: ripgrep is unavailable \u2014 ${d instanceof Error?d.message:String(d)}`,isError:!0}}return new Promise(d=>{let u=!1;function p(_){u||(u=!0,o.removeEventListener("abort",v),d(_))}let f=["-n","--no-heading","--color=never","--hidden"];c&&f.push("-g",c);for(let _ of Hh(a)){let E=_.split("/").map(T=>T.replace(/([*?\[\]{}\\])/g,"\\$1")).join("/");f.push("-g",`!${E}`,"-g",`!${E}/**`)}f.push("-g","!.git"),f.push("--",i,a);let m=s?.resolveBase??s?.cwd??t,g=EO(l,f,m!==void 0?{cwd:m}:{}),h=Md(1e5),y=Md(1e5),w=!1;function
|
|
239
|
+
`;return g.toString("utf8")+w+h.toString("utf8")}return{push:d,totalBytes:()=>c,totalLines:()=>l,truncated:()=>s+a<c,render:u}}function AO(t,e,n){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let r=t;if(typeof r.pattern!="string")throw new Error('Input must have a "pattern" field of type string');let o=typeof r.path=="string"?r.path:e?.resolveBase??e?.cwd??n??process.cwd(),s=ee(o,e,"read"),i;if(r.include!==void 0){if(typeof r.include!="string")throw new Error("include must be a string");i=r.include}return{pattern:r.pattern,path:s,include:i}}function Od(t,e){let n=e?.scanCapBytes??256e6;return async(r,o,s)=>{let{pattern:i,path:a,include:c}=AO(r,s,t);if(o.aborted)return{content:"Search aborted",isError:!0};let l;try{({rgPath:l}=await import("@vscode/ripgrep"))}catch(d){return{content:`Failed to execute grep: ripgrep is unavailable \u2014 ${d instanceof Error?d.message:String(d)}`,isError:!0}}return new Promise(d=>{let u=!1;function p(_){u||(u=!0,o.removeEventListener("abort",v),d(_))}let f=["-n","--no-heading","--color=never","--hidden"];c&&f.push("-g",c);for(let _ of Hh(a)){let E=_.split("/").map(T=>T.replace(/([*?\[\]{}\\])/g,"\\$1")).join("/");f.push("-g",`!${E}`,"-g",`!${E}/**`)}f.push("-g","!.git"),f.push("--",i,a);let m=s?.resolveBase??s?.cwd??t,g=EO(l,f,m!==void 0?{cwd:m}:{}),h=Md(1e5),y=Md(1e5),w=!1;function S(_){if(w||u)return;let E=h.totalBytes()+y.totalBytes();if(E<n)return;w=!0,console.warn(`[grep] overflow kill: stream=${_} totalBytes=${E} pattern=${i} path=${a}`),Ee({event:"tool.overflow_kill",tool:"grep",total_bytes:E,stream:_}),g.kill("SIGKILL");let T=h.totalBytes()===0&&y.totalBytes()>0?y.render():h.render();p({content:Ae(T.trimEnd())+ly(n),truncated:!0})}g.stdout.on("data",_=>{h.push(_),S("stdout")}),g.stderr.on("data",_=>{y.push(_),S("stderr")});let v=()=>{g.kill(),p({content:"Search aborted",isError:!0})};o.addEventListener("abort",v),g.on("close",_=>{if(w)return;if(_===1){let T=`No matches found for '${i}' in ${a}`;p({content:T});return}if(_===2){p(cy(y.render(),a));return}let E=Ae(h.render().trimEnd());p({content:E,...h.truncated()?{truncated:!0}:{}})}),g.on("error",_=>{let E=ay(l);if(E!==void 0){p({content:`Failed to execute grep: ${E}`,isError:!0});return}let T;if(m===void 0&&ho(_))try{T=Wn(_,process.cwd())}catch{T=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${_.message}`}else T=Wn(_,m);p({content:`Failed to execute grep: ${T}`,isError:!0})})})}}var dy=Od();import{promises as xO}from"fs";var Dd=500,RO=async(t,e,n,r)=>{if(!t||typeof t!="object")throw new Error("Invalid input: expected an object");let s=t.path;if(typeof s!="string")throw new Error("Invalid input: path must be a string");let i;try{i=ee(s,n,"read",r)}catch(a){return{content:a instanceof Error?a.message:String(a),isError:!0}}try{let a=await xO.readdir(i,{withFileTypes:!0}),c=a.filter(m=>m.isDirectory()).map(m=>`${m.name}/`),l=a.filter(m=>!m.isDirectory()).map(m=>m.name);c.sort(),l.sort();let d=[...c,...l];if(d.length===0)return{content:"(empty directory)"};let u=d.length,f=d.slice(0,Dd).join(`
|
|
240
240
|
`);return u>Dd&&(f+=`
|
|
241
241
|
[results capped at ${Dd} entries \u2014 ${u} total in directory]`),{content:f}}catch(a){let c=We(a,i,"Directory");return c||(a instanceof Error?{content:`Error listing directory: ${a.message}`,isError:!0}:{content:"Unknown error listing directory",isError:!0})}};function Fd(t){return(e,n,r)=>RO(e,n,r,t)}var uy=Fd();C();function ko(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 py(t,e){return e.has(t)}function Ld(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 FY,parse as LY}from"dotenv";M();import{execFileSync as fy}from"child_process";import{existsSync as IO,readFileSync as CO,writeFileSync as PO}from"fs";import{homedir as my,userInfo as gy}from"os";import{join as hy}from"path";var MO="9d1c250a-e61b-44d9-88ed-5944d1962f5e",OO="https://platform.claude.com/v1/oauth/token",DO=300*1e3,FO=1e4;function xe(){let t=yy();if(t===void 0)return;let e=by(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 Ni(){let t=yy();if(t===void 0)return;let e=by(t);if(e===void 0)return;if(e.expiresAt!==void 0&&e.expiresAt>Date.now()+DO)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 LO(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}:{}},NO(JSON.stringify(r))}catch{process.stderr.write(`agent-afk: Refreshed OAuth token but failed to write back to credential store.
|
|
242
242
|
`)}return n.accessToken}function yy(){if(process.platform==="darwin")try{return fy("security",["find-generic-password","-s","Claude Code-credentials","-a",gy().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let t=hy(my(),".claude",".credentials.json");if(!IO(t))return;try{return CO(t,"utf-8")}catch{return}}}function by(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 LO(t){try{let e=await fetch(OO,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:t,client_id:MO}),signal:AbortSignal.timeout(FO)});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 Vn(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 NO(t){if(process.platform==="darwin")fy("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",gy().username,"-w",t],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let e=hy(my(),".claude",".credentials.json");UO(e,t)}}function UO(t,e){PO(t,e,{encoding:"utf-8",mode:384})}C();var $O;function Ui(){return b.ANTHROPIC_API_KEY||b.CLAUDE_CODE_OAUTH_TOKEN||$O||xe()}function Nd(){return b.OPENAI_API_KEY||b.CODEX_API_KEY||void 0}function BO(){let t=b.XAI_API_KEY;return t&&t.length>0?t:void 0}function oe(t,e){let n=z(t,e);return n==="openai-compatible"||n==="openai-codex"?Nd():n==="xai"||n==="xai-oauth"?BO():Ui()}C();M();import{join as jO}from"path";function wy(){return[{tier:"project",path:jO(process.cwd(),"afk.config.json")},{tier:"user",path:In()},{tier:"legacy",path:Ws()}]}import{readFileSync as kD,existsSync as vD}from"fs";C();import{execFile as hD}from"node:child_process";import{promisify as yD}from"node:util";C();M();C();import{stat as VO}from"node:fs/promises";import{join as YO}from"node:path";var HO=[/\.env$/,/^\.env\./,/\.pem$/,/\.key$/,/\.p12$/,/\.keystore$/,/\.jks$/,/^id_rsa/,/^id_ed25519/,/^\.netrc$/,/\.sqlite3?$/,/\.db$/],WO=[/credential/,/secret/],KO=/\.(?:js|mjs|cjs|jsx|ts|tsx|mts|cts|map|html?|css|svg)$/,ky=[/(?:^|\/)node_modules\//,/(?:^|\/)\.pnpm(-store)?\//,/(?:^|\/)\.yarn\//,/(?:^|\/)bower_components\//,/(?:^|\/)vendor\/bundle\//,/(?:^|\/)\.venv\//,/(?:^|\/)venv\//,/(?:^|\/)__pycache__\//,/(?:^|\/)\.turbo\//,/(?:^|\/)\.parcel-cache\//,/(?:^|\/)\.vite\//,/(?:^|\/)\.cache\//,/(?:^|\/)\.gradle\//,/(?:^|\/)\.pytest_cache\//,/(?:^|\/)\.mypy_cache\//,/(?:^|\/)\.ruff_cache\//,/(?:^|\/)\.nyc_output\//],vy=[/(?:^|\/)dist\//,/(?:^|\/)build\//,/(?:^|\/)out\//,/(?:^|\/)lib-cov\//,/(?:^|\/)\.next\//,/(?:^|\/)\.nuxt\//,/(?:^|\/)\.svelte-kit\//,/(?:^|\/)\.output\//,/(?:^|\/)target\//,/(?:^|\/)coverage\//,/(?:^|\/)logs\//],qO=[/^\.afk-worktree-meta\.json$/,/\.tsbuildinfo$/,/^\.eslintcache$/,/^\.stylelintcache$/,/^\.DS_Store$/,/^debug\.log$/,/^npm-debug\.log$/,/^yarn-error\.log$/,/^yarn-debug\.log$/,/^pnpm-debug\.log$/,/^lerna-debug\.log$/];function GO(t){let e=t.replace(/\\/g,"/").replace(/^\.\//,"");return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e}function Sy(t){let e=t.replace(/\/+$/,""),n=e.lastIndexOf("/");return n===-1?e:e.slice(n+1)}var XO=[/(?:^|\/)logs\//];function zO(t,e){return!KO.test(e)||XO.some(n=>n.test(t))?!1:ky.some(n=>n.test(t))||vy.some(n=>n.test(t))}function JO(t){return HO.some(e=>e.test(t))}function $t(t){let e=GO(t);if(e==="")return"protected";let n=Sy(e).toLowerCase();return JO(n)||!zO(e,n)&&WO.some(o=>o.test(n))?"protected":!e.endsWith("/")&&qO.some(o=>o.test(Sy(e)))||ky.some(o=>o.test(e))?"opaque":vy.some(o=>o.test(e))?"inspectable":"protected"}var QO=["-c","core.quotePath=false"],ZO={maxBuffer:64*1024*1024,timeout:1e4};async function Ty(t,e){let n=$t(e);if(n!=="protected"||e.endsWith("/"))return{verdict:n,resolvedEntry:e};try{if((await VO(YO(t,e))).isDirectory()){let o=`${e}/`;return{verdict:$t(o),resolvedEntry:o}}}catch{}return{verdict:n,resolvedEntry:e}}async function _y(t,e,n){let r=[...QO,"-C",e,"status","--porcelain","--ignored"];n!==void 0&&r.push("--untracked-files=all","--",n);try{let{stdout:o}=await t("git",r,ZO);return{entries:o.split(`
|
|
@@ -277,13 +277,13 @@ Send a message to start one, or /new for a fresh session.`}function tb(t){return
|
|
|
277
277
|
${e}`}C();import{BlockList as WD,isIP as Vd}from"node:net";import{lookup as KD}from"node:dns/promises";import{Agent as qD}from"undici";J();var BD=new Set([429,502,503,504]);function jD(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function ub(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function HD(t,e){let n=t.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,e)}async function pb(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??jD,c=n.signal??void 0,l;for(let d=0;d<=o;d++){if(c?.aborted)throw c.reason??new Error("aborted");try{let u=await t(e,n);if(!BD.has(u.status)||d===o)return u;let p=HD(u,i)??ub(d,s,i);P("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,c)}catch(u){if(c?.aborted||(l=u,d===o))throw u;let p=ub(d,s,i);P("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,c)}}throw l??new Error("retryFetch: exhausted without a result")}var GD=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.168.0.0",16]],XD=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],zD=(()=>{let t=new WD;for(let[e,n]of GD)t.addSubnet(e,n,"ipv4");for(let[e,n]of XD)t.addSubnet(e,n,"ipv6");return t})(),me=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};function mb(){let t=b.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function JD(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Jd(t){let e=Vd(t);return e===0?!1:zD.check(t,e===4?"ipv4":"ipv6")}var VD=new qD({connect:{lookup(t,e,n){gb(t).then(r=>{let o=r.find(i=>Jd(i.address));if(o!==void 0){n(new me(`refusing to connect to ${t} (resolved) \u2014 internal/private address ${o.address} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`),"",0);return}let s=r[0];if(s===void 0){n(new Error(`DNS lookup returned no addresses for ${t}`),"",0);return}n(null,s.address,Vd(s.address))},r=>n(r,"",0))}}});async function gb(t){return KD(t,{all:!0,verbatim:!0})}async function gn(t,e={}){if(e.allowPrivateHosts??mb())return{allowed:!0};let n;try{n=new URL(t)}catch{return{allowed:!1,reason:`"${t}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{allowed:!1,reason:`protocol "${n.protocol}" not supported (http/https only)`};let r=JD(n.hostname),o=(a,c)=>`refusing to fetch ${c} \u2014 internal/private address ${a} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`;if(Vd(r)!==0)return Jd(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??gb,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(Jd(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Co(t,e={}){let n=await gn(t,e);if(!n.allowed)throw new me(n.reason)}var fb=20,YD=new Set([301,302,303,307,308]);async function jt(t,e,n={},r={}){let o={...r.lookupFn!==void 0?{lookupFn:r.lookupFn}:{},...r.allowPrivateHosts!==void 0?{allowPrivateHosts:r.allowPrivateHosts}:{}},s=e;for(let i=0;i<=fb;i++){await Co(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??mb())?{dispatcher:VD}:{}},c=await pb(t,s,a,r.retry??{});if(!YD.has(c.status))return c;let l=c.headers.get("location");if(l===null||l.trim()==="")return c;let d;try{d=new URL(l,c.url||s).toString()}catch{return c}await c.body?.cancel().catch(()=>{}),s=d}throw new me(`too many redirects (>${fb}) starting from ${e}`)}J();var iL=/(text\/html|application\/xhtml\+xml)/i,aL=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,cL=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,lL={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"};async function Jb(t,e){try{return await lb(t,e)}catch(n){return P("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function dL(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(wn(),bn)),r=await n();try{return await r.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(pu(),uu)),{loadBrowserConfig:i}=await Promise.resolve().then(()=>(Ht(),Qd)),a=i(),c=new s(a);try{return await c.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}finally{await c.shutdown()}}throw o}}async function Vb(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??dL,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await jt(n,t,{headers:lL,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(cL.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(aL.test(p)&&!iL.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await Jb(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof me||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(s===null||s.textLength<200)&&s!==null){let u=zd({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Co(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>Co(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await Co(u.finalUrl,o);let p=await Jb(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=zd({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(e.signal.aborted||u instanceof me)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=l instanceof Error?l.message:`HTTP ${c??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${c??"error"}).`)}var uL="https://api.exa.ai/search",pL=10;function fL(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(uL,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),pL),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=we(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function Yb(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?fL({apiKey:t.exaApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function Qb(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
278
278
|
|
|
279
279
|
(no results)`;let n=[`# Search results for "${t}"`,""];return e.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
|
|
280
|
-
`).trimEnd()}iu();function Qi(t){if(t instanceof Error&&t.name==="TimeoutError")return"timeout";let e=t instanceof Error?t.message:String(t);return/Timeout\s+\d+\s*ms exceeded/i.test(e)?"timeout":void 0}var mL=3e4,gL=12e4,hL=1e5,yL=1e6,bL=10;function wL(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=mL;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,gL)}let a=hL;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,yL)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function gu(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:ot(t,e),truncated:!0}}function SL(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env,r=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{};return async(o,s)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let i=wL(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let u=s.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let a=new AbortController,c=()=>{a.abort(s.reason)},l,d=()=>{let u=a.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(s.addEventListener("abort",c,{once:!0}),l=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${i.timeoutMs}ms`))},i.timeoutMs),i.url!==void 0){let p=await gn(i.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(!p.allowed)return{content:`web_scrape blocked: ${p.reason}`,isError:!0}}if(i.mode==="raw"){let p;try{let g={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await jt(e,i.url,g,r)}catch(g){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:g instanceof me?{content:`web_scrape blocked: ${g.message}`,isError:!0}:{content:`web_scrape network error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${i.url}`,isError:!0};let f;try{f=await p.text()}catch(g){return{content:`web_scrape read error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}let m=gu(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await Vb(i.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:i.timeoutMs,signal:a.signal,...t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${i.url}.`,isError:!0};let f=gu(db(p.markdown,p.advisory),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(p instanceof me)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=Re(p)&&!su(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Po()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=Yb({exaApiKey:n.EXA_API_KEY,fetchFn:e});if("error"in u)return{content:u.error,isError:!0};try{let p=await u.search(i.query,{limit:bL,timeoutMs:i.timeoutMs,signal:a.signal}),f=gu(Qb(i.query,p),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),s.removeEventListener("abort",c)}}}var Zb=SL();var ew=3e4,tw=12e4,hu=1e5,yu=1e6,kL=new Set(["GET","HEAD","OPTIONS"]),vL=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]);function TL(t){return kL.has(t)?"low":t==="DELETE"?"high":"medium"}function _L(t){return vL.has(t)}var EL=["set-cookie","x-"],AL=new Set(["server","via","age","vary","authorization","www-authenticate"]);function xL(t){let e={};return t.forEach((n,r)=>{let o=r.toLowerCase();AL.has(o)||EL.some(s=>o.startsWith(s))||(e[r]=n)}),e}function RL(t,e){if(t==null)return{serialized:void 0,inferredContentType:void 0};let n=Object.keys(e).some(o=>o.toLowerCase()==="content-type");return typeof t=="string"?{serialized:t,inferredContentType:n?void 0:"text/plain"}:{serialized:JSON.stringify(t),inferredContentType:n?void 0:"application/json"}}function IL(t,e,n){let r=Buffer.byteLength(t,"utf8"),o=t,s=!1;if(r>n&&(o=ot(t,n),s=!0),!s&&/application\/json/i.test(e))try{return{body:JSON.parse(o),truncated:!1}}catch{}return{body:o,truncated:s}}async function nw(t){let{url:e,method:n,signal:r,domainCheck:o,recordEffect:s}=t,i=Math.min(t.maxResponseBytes??hu,yu),a={...t.headers},c=t.fetchFn??globalThis.fetch,l=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},d=TL(n);if(o!==void 0){let S=o(e);if(!S.allowed)throw Object.assign(new Error(`web_request blocked by domain policy: ${S.reason}`),{name:"DomainPolicyError"})}let u=await gn(e,l);if(!u.allowed)throw new me(u.reason);let{serialized:p,inferredContentType:f}=RL(t.body,a);f!==void 0&&(a["content-type"]=f);let m={method:n,headers:Object.keys(a).length>0?a:void 0,body:p,signal:r},h=_L(n)?{retries:2,baseDelayMs:300,maxDelayMs:5e3}:{retries:0},y=Date.now(),w;try{w=await jt(c,e,m,{...l,retry:h})}catch(S){throw S instanceof me,S}let k=Date.now()-y,v=w.headers.get("content-type")??"",_;try{let S=w.body?.getReader();if(!S)_="";else{let A=[],R=0,D=i*2;for(;;){let{done:G,value:F}=await S.read();if(G||!F)break;if(A.push(F),R+=F.byteLength,R>=D){await S.cancel();break}}_=new TextDecoder().decode(Buffer.concat(A,R))}}catch{_=""}let{body:E,truncated:T}=IL(_,v,i),I=xL(w.headers);return s!==void 0&&Promise.resolve(s({url:e,method:n,status:w.status,risk:d,timing_ms:k})).catch(()=>{}),{status:w.status,headers:I,body:E,truncated:T,timing_ms:k,risk:d}}function rw(t){if(typeof t!="string"||t.trim().length===0)return{error:"method must be a non-empty string (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)"};let e=t.trim().toUpperCase(),n=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];return n.includes(e)?e:{error:`method "${t}" is not supported \u2014 must be one of: ${n.join(", ")}`}}function CL(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t;if(typeof e.url!="string"||e.url.length===0)return{error:'Invalid input: "url" must be a non-empty string'};let n;try{n=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{error:`Invalid input: protocol "${n.protocol}" not supported (http/https only)`};n.username="",n.password="";let r=n.toString(),o=rw(e.method);if(typeof o=="object"&&"error"in o)return{error:`Invalid input: ${o.error}`};let s=o,i;if(e.body!==void 0&&e.body!==null){if(typeof e.body!="string"&&typeof e.body!="object")return{error:'Invalid input: "body" must be a string, object, or array'};i=e.body}let a={};if(e.headers!==void 0){if(typeof e.headers!="object"||e.headers===null||Array.isArray(e.headers))return{error:'Invalid input: "headers" must be a string-keyed object'};let u=e.headers;for(let[p,f]of Object.entries(u)){if(typeof f!="string")return{error:`Invalid input: header value for "${p}" must be a string`};a[p]=f}}let c=ew;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'Invalid input: "timeout_ms" must be a positive finite number'};c=Math.min(e.timeout_ms,tw)}let l=hu;if(e.max_response_bytes!==void 0){if(typeof e.max_response_bytes!="number"||!Number.isFinite(e.max_response_bytes)||e.max_response_bytes<=0)return{error:'Invalid input: "max_response_bytes" must be a positive finite number'};l=Math.min(e.max_response_bytes,yu)}let d;if(e.credential!==void 0){if(typeof e.credential!="string"||e.credential.length===0)return{error:'Invalid input: "credential" must be a non-empty string (an env var name)'};d=e.credential}return{url:r,method:s,body:i,headers:a,timeoutMs:c,maxResponseBytes:l,credential:d}}function PL(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;async function r(){if(t.domainCheck!==void 0)return t.domainCheck;try{let{loadBrowserConfig:o,enforceDomainPolicy:s}=await Promise.resolve().then(()=>(Ht(),Qd)),i=o();return a=>s(a,i)}catch{return}}return async(o,s)=>{if(typeof e!="function")return{content:"web_request unavailable: global fetch() is not present (agent-afk requires Node 20+).",isError:!0};let i=CL(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let p=s.reason;return{content:`web_request aborted: ${p instanceof Error?p.message:String(p??"aborted")}`,isError:!0}}let a={...i.headers};if(i.credential!==void 0){let p=n[i.credential];if(p===void 0||p.trim().length===0)return{content:`web_request credential error: environment variable "${i.credential}" is not set. Set it in afk.env or export it in the shell before starting AFK.`,isError:!0};if(Object.keys(a).some(m=>m.toLowerCase()==="authorization"))return{content:'web_request credential error: both "credential" and an explicit Authorization header were provided. Use one or the other.',isError:!0};a.Authorization=`Bearer ${p}`}let c=new AbortController,l=()=>c.abort(s.reason),d,u=()=>{let p=c.signal.reason;return p instanceof Error?p.message:String(p??"aborted")};try{s.addEventListener("abort",l,{once:!0}),d=setTimeout(()=>{c.abort(new Error(`web_request timeout after ${i.timeoutMs}ms`))},i.timeoutMs);let p=await r(),f={url:i.url,method:i.method,body:i.body,headers:a,maxResponseBytes:i.maxResponseBytes,signal:c.signal,fetchFn:e,lookupFn:t.lookupFn,domainCheck:p,recordEffect:t.recordEffect},m;try{m=await nw(f)}catch(w){if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};if(w instanceof me)return{content:`web_request blocked: ${w.message}`,isError:!0};let k=w instanceof Error&&w.name==="DomainPolicyError"?"blocked":"network error",v=w instanceof Error?w.message:String(w);return{content:`web_request ${k}: ${v}`,isError:!0}}if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};let g=m.body;if(typeof g=="string")g=et(g);else if(typeof g=="object"&&g!==null){let w=et(JSON.stringify(g));try{g=JSON.parse(w)}catch{g=w}}let h={status:m.status,headers:m.headers,body:g,timing_ms:m.timing_ms,...m.truncated?{truncated:!0}:{}};return{content:JSON.stringify(h,null,2),...m.truncated?{truncated:!0}:{}}}finally{d!==void 0&&clearTimeout(d),s.removeEventListener("abort",l)}}}var ow=PL();import{existsSync as qL}from"node:fs";import{readFile as GL}from"node:fs/promises";M();import{existsSync as iw,mkdirSync as ML,readFileSync as OL,renameSync as DL,unlinkSync as FL,writeFileSync as LL}from"node:fs";import{dirname as sw,join as NL}from"node:path";import{randomBytes as UL}from"node:crypto";function Sn(t){let e=t??Pl();if(!iw(e))return[];try{let n=OL(e,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${e}: ${r}`),[]}}function Mo(t,e){let n=e??Pl();ML(sw(n),{recursive:!0});let r=NL(sw(n),`.schedules.json.${process.pid}.${UL(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{LL(r,o,"utf-8"),DL(r,n)}catch(s){try{iw(r)&&FL(r)}catch{}throw s}}function aw(t,e){let n=Sn(e),r=n.map(c=>c.id),o=$L(t.name),s=BL(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),Mo(n,e),a}function cw(t,e){let n=Sn(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(Mo(o,e),!0)}function lw(t,e){return Sn(e).find(n=>n.id===t)}function $L(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function BL(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}function dw(t){return{taskId:t.id,command:t.command,trigger:t.trigger??"cron",...t.cron!==void 0?{cronExpression:t.cron}:{},...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{},...t.notifyChat!==void 0?{notifyChat:t.notifyChat}:{}}}M();M();import{existsSync as jL,readFileSync as HL}from"node:fs";import{join as WL}from"node:path";var bu="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start.";async function Qn(t,e,n){let r,o;try{let s=WL(Am("default"),"port");if(!jL(s))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=HL(s,"utf-8").trim(),a=KL(i);if(!a)return{synced:!1,detail:"daemon-not-detected (invalid port file)"};({host:r,port:o}=a)}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let s=r.includes(":")?`[${r}]`:r,i=await fetch(`http://${s}:${o}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return i.ok?{synced:!0,detail:"synced"}:t==="POST"&&i.status===409?{synced:!0,detail:"already-registered"}:t==="DELETE"&&i.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${i.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}function KL(t){let e=parseInt(t,10);if(String(e)===t&&!Number.isNaN(e))return e<1||e>65535?null:{host:"localhost",port:e};let n=t.lastIndexOf(":");if(n<1)return null;let r=t.slice(0,n),o=t.slice(n+1);if(!/^\d+$/.test(o))return null;let s=parseInt(o,10);return Number.isNaN(s)||s<1||s>65535||/^:+$/.test(r)?null:{host:r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,port:s}}var uw=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=n.notifyChat;if(o!==void 0&&typeof o!="number"&&typeof o!="string")return{content:"Invalid input: notifyChat must be a number (chat id) or string (chat id or alias name)",isError:!0};let s=aw({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),i=s.enabled?await Qn("POST","/tasks",{taskId:s.id,command:s.command,cron:s.cron,trigger:s.trigger,notifyOn:s.notifyOn,...s.notifyChat!==void 0?{notifyChat:s.notifyChat}:{}}):await Qn("DELETE",`/tasks/${s.id}`);return{content:JSON.stringify({id:s.id,name:s.name,cron:s.cron,enabled:s.enabled,daemonSynced:i.synced,syncDetail:i.detail,...i.synced?{}:{syncNote:bu}})}},pw=async(t,e)=>{let n=Sn();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},fw=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,s=Fs();if(!qL(s))return{content:JSON.stringify([])};let i;try{let l=await GL(s);i=(l.length>1048576?l.subarray(l.length-1048576):l).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
|
|
280
|
+
`).trimEnd()}iu();function Qi(t){if(t instanceof Error&&t.name==="TimeoutError")return"timeout";let e=t instanceof Error?t.message:String(t);return/Timeout\s+\d+\s*ms exceeded/i.test(e)?"timeout":void 0}var mL=3e4,gL=12e4,hL=1e5,yL=1e6,bL=10;function wL(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=mL;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,gL)}let a=hL;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,yL)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function gu(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:ot(t,e),truncated:!0}}function SL(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env,r=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{};return async(o,s)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let i=wL(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let u=s.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let a=new AbortController,c=()=>{a.abort(s.reason)},l,d=()=>{let u=a.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(s.addEventListener("abort",c,{once:!0}),l=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${i.timeoutMs}ms`))},i.timeoutMs),i.url!==void 0){let p=await gn(i.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(!p.allowed)return{content:`web_scrape blocked: ${p.reason}`,isError:!0}}if(i.mode==="raw"){let p;try{let g={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await jt(e,i.url,g,r)}catch(g){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:g instanceof me?{content:`web_scrape blocked: ${g.message}`,isError:!0}:{content:`web_scrape network error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${i.url}`,isError:!0};let f;try{f=await p.text()}catch(g){return{content:`web_scrape read error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}let m=gu(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await Vb(i.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:i.timeoutMs,signal:a.signal,...t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${i.url}.`,isError:!0};let f=gu(db(p.markdown,p.advisory),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(p instanceof me)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=Re(p)&&!su(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Po()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=Yb({exaApiKey:n.EXA_API_KEY,fetchFn:e});if("error"in u)return{content:u.error,isError:!0};try{let p=await u.search(i.query,{limit:bL,timeoutMs:i.timeoutMs,signal:a.signal}),f=gu(Qb(i.query,p),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),s.removeEventListener("abort",c)}}}var Zb=SL();var ew=3e4,tw=12e4,hu=1e5,yu=1e6,kL=new Set(["GET","HEAD","OPTIONS"]),vL=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]);function TL(t){return kL.has(t)?"low":t==="DELETE"?"high":"medium"}function _L(t){return vL.has(t)}var EL=["set-cookie","x-"],AL=new Set(["server","via","age","vary","authorization","www-authenticate"]);function xL(t){let e={};return t.forEach((n,r)=>{let o=r.toLowerCase();AL.has(o)||EL.some(s=>o.startsWith(s))||(e[r]=n)}),e}function RL(t,e){if(t==null)return{serialized:void 0,inferredContentType:void 0};let n=Object.keys(e).some(o=>o.toLowerCase()==="content-type");return typeof t=="string"?{serialized:t,inferredContentType:n?void 0:"text/plain"}:{serialized:JSON.stringify(t),inferredContentType:n?void 0:"application/json"}}function IL(t,e,n){let r=Buffer.byteLength(t,"utf8"),o=t,s=!1;if(r>n&&(o=ot(t,n),s=!0),!s&&/application\/json/i.test(e))try{return{body:JSON.parse(o),truncated:!1}}catch{}return{body:o,truncated:s}}async function nw(t){let{url:e,method:n,signal:r,domainCheck:o,recordEffect:s}=t,i=Math.min(t.maxResponseBytes??hu,yu),a={...t.headers},c=t.fetchFn??globalThis.fetch,l=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},d=TL(n);if(o!==void 0){let k=o(e);if(!k.allowed)throw Object.assign(new Error(`web_request blocked by domain policy: ${k.reason}`),{name:"DomainPolicyError"})}let u=await gn(e,l);if(!u.allowed)throw new me(u.reason);let{serialized:p,inferredContentType:f}=RL(t.body,a);f!==void 0&&(a["content-type"]=f);let m={method:n,headers:Object.keys(a).length>0?a:void 0,body:p,signal:r},h=_L(n)?{retries:2,baseDelayMs:300,maxDelayMs:5e3}:{retries:0},y=Date.now(),w;try{w=await jt(c,e,m,{...l,retry:h})}catch(k){throw k instanceof me,k}let S=Date.now()-y,v=w.headers.get("content-type")??"",_;try{let k=w.body?.getReader();if(!k)_="";else{let A=[],R=0,D=i*2;for(;;){let{done:G,value:F}=await k.read();if(G||!F)break;if(A.push(F),R+=F.byteLength,R>=D){await k.cancel();break}}_=new TextDecoder().decode(Buffer.concat(A,R))}}catch{_=""}let{body:E,truncated:T}=IL(_,v,i),I=xL(w.headers);return s!==void 0&&Promise.resolve(s({url:e,method:n,status:w.status,risk:d,timing_ms:S})).catch(()=>{}),{status:w.status,headers:I,body:E,truncated:T,timing_ms:S,risk:d}}function rw(t){if(typeof t!="string"||t.trim().length===0)return{error:"method must be a non-empty string (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)"};let e=t.trim().toUpperCase(),n=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];return n.includes(e)?e:{error:`method "${t}" is not supported \u2014 must be one of: ${n.join(", ")}`}}function CL(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t;if(typeof e.url!="string"||e.url.length===0)return{error:'Invalid input: "url" must be a non-empty string'};let n;try{n=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{error:`Invalid input: protocol "${n.protocol}" not supported (http/https only)`};n.username="",n.password="";let r=n.toString(),o=rw(e.method);if(typeof o=="object"&&"error"in o)return{error:`Invalid input: ${o.error}`};let s=o,i;if(e.body!==void 0&&e.body!==null){if(typeof e.body!="string"&&typeof e.body!="object")return{error:'Invalid input: "body" must be a string, object, or array'};i=e.body}let a={};if(e.headers!==void 0){if(typeof e.headers!="object"||e.headers===null||Array.isArray(e.headers))return{error:'Invalid input: "headers" must be a string-keyed object'};let u=e.headers;for(let[p,f]of Object.entries(u)){if(typeof f!="string")return{error:`Invalid input: header value for "${p}" must be a string`};a[p]=f}}let c=ew;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'Invalid input: "timeout_ms" must be a positive finite number'};c=Math.min(e.timeout_ms,tw)}let l=hu;if(e.max_response_bytes!==void 0){if(typeof e.max_response_bytes!="number"||!Number.isFinite(e.max_response_bytes)||e.max_response_bytes<=0)return{error:'Invalid input: "max_response_bytes" must be a positive finite number'};l=Math.min(e.max_response_bytes,yu)}let d;if(e.credential!==void 0){if(typeof e.credential!="string"||e.credential.length===0)return{error:'Invalid input: "credential" must be a non-empty string (an env var name)'};d=e.credential}return{url:r,method:s,body:i,headers:a,timeoutMs:c,maxResponseBytes:l,credential:d}}function PL(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;async function r(){if(t.domainCheck!==void 0)return t.domainCheck;try{let{loadBrowserConfig:o,enforceDomainPolicy:s}=await Promise.resolve().then(()=>(Ht(),Qd)),i=o();return a=>s(a,i)}catch{return}}return async(o,s)=>{if(typeof e!="function")return{content:"web_request unavailable: global fetch() is not present (agent-afk requires Node 20+).",isError:!0};let i=CL(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let p=s.reason;return{content:`web_request aborted: ${p instanceof Error?p.message:String(p??"aborted")}`,isError:!0}}let a={...i.headers};if(i.credential!==void 0){let p=n[i.credential];if(p===void 0||p.trim().length===0)return{content:`web_request credential error: environment variable "${i.credential}" is not set. Set it in afk.env or export it in the shell before starting AFK.`,isError:!0};if(Object.keys(a).some(m=>m.toLowerCase()==="authorization"))return{content:'web_request credential error: both "credential" and an explicit Authorization header were provided. Use one or the other.',isError:!0};a.Authorization=`Bearer ${p}`}let c=new AbortController,l=()=>c.abort(s.reason),d,u=()=>{let p=c.signal.reason;return p instanceof Error?p.message:String(p??"aborted")};try{s.addEventListener("abort",l,{once:!0}),d=setTimeout(()=>{c.abort(new Error(`web_request timeout after ${i.timeoutMs}ms`))},i.timeoutMs);let p=await r(),f={url:i.url,method:i.method,body:i.body,headers:a,maxResponseBytes:i.maxResponseBytes,signal:c.signal,fetchFn:e,lookupFn:t.lookupFn,domainCheck:p,recordEffect:t.recordEffect},m;try{m=await nw(f)}catch(w){if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};if(w instanceof me)return{content:`web_request blocked: ${w.message}`,isError:!0};let S=w instanceof Error&&w.name==="DomainPolicyError"?"blocked":"network error",v=w instanceof Error?w.message:String(w);return{content:`web_request ${S}: ${v}`,isError:!0}}if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};let g=m.body;if(typeof g=="string")g=et(g);else if(typeof g=="object"&&g!==null){let w=et(JSON.stringify(g));try{g=JSON.parse(w)}catch{g=w}}let h={status:m.status,headers:m.headers,body:g,timing_ms:m.timing_ms,...m.truncated?{truncated:!0}:{}};return{content:JSON.stringify(h,null,2),...m.truncated?{truncated:!0}:{}}}finally{d!==void 0&&clearTimeout(d),s.removeEventListener("abort",l)}}}var ow=PL();import{existsSync as qL}from"node:fs";import{readFile as GL}from"node:fs/promises";M();import{existsSync as iw,mkdirSync as ML,readFileSync as OL,renameSync as DL,unlinkSync as FL,writeFileSync as LL}from"node:fs";import{dirname as sw,join as NL}from"node:path";import{randomBytes as UL}from"node:crypto";function Sn(t){let e=t??Pl();if(!iw(e))return[];try{let n=OL(e,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${e}: ${r}`),[]}}function Mo(t,e){let n=e??Pl();ML(sw(n),{recursive:!0});let r=NL(sw(n),`.schedules.json.${process.pid}.${UL(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{LL(r,o,"utf-8"),DL(r,n)}catch(s){try{iw(r)&&FL(r)}catch{}throw s}}function aw(t,e){let n=Sn(e),r=n.map(c=>c.id),o=$L(t.name),s=BL(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),Mo(n,e),a}function cw(t,e){let n=Sn(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(Mo(o,e),!0)}function lw(t,e){return Sn(e).find(n=>n.id===t)}function $L(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function BL(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}function dw(t){return{taskId:t.id,command:t.command,trigger:t.trigger??"cron",...t.cron!==void 0?{cronExpression:t.cron}:{},...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{},...t.notifyChat!==void 0?{notifyChat:t.notifyChat}:{}}}M();M();import{existsSync as jL,readFileSync as HL}from"node:fs";import{join as WL}from"node:path";var bu="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start.";async function Qn(t,e,n){let r,o;try{let s=WL(Am("default"),"port");if(!jL(s))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=HL(s,"utf-8").trim(),a=KL(i);if(!a)return{synced:!1,detail:"daemon-not-detected (invalid port file)"};({host:r,port:o}=a)}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let s=r.includes(":")?`[${r}]`:r,i=await fetch(`http://${s}:${o}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return i.ok?{synced:!0,detail:"synced"}:t==="POST"&&i.status===409?{synced:!0,detail:"already-registered"}:t==="DELETE"&&i.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${i.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}function KL(t){let e=parseInt(t,10);if(String(e)===t&&!Number.isNaN(e))return e<1||e>65535?null:{host:"localhost",port:e};let n=t.lastIndexOf(":");if(n<1)return null;let r=t.slice(0,n),o=t.slice(n+1);if(!/^\d+$/.test(o))return null;let s=parseInt(o,10);return Number.isNaN(s)||s<1||s>65535||/^:+$/.test(r)?null:{host:r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,port:s}}var uw=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=n.notifyChat;if(o!==void 0&&typeof o!="number"&&typeof o!="string")return{content:"Invalid input: notifyChat must be a number (chat id) or string (chat id or alias name)",isError:!0};let s=aw({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),i=s.enabled?await Qn("POST","/tasks",{taskId:s.id,command:s.command,cron:s.cron,trigger:s.trigger,notifyOn:s.notifyOn,...s.notifyChat!==void 0?{notifyChat:s.notifyChat}:{}}):await Qn("DELETE",`/tasks/${s.id}`);return{content:JSON.stringify({id:s.id,name:s.name,cron:s.cron,enabled:s.enabled,daemonSynced:i.synced,syncDetail:i.detail,...i.synced?{}:{syncNote:bu}})}},pw=async(t,e)=>{let n=Sn();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},fw=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,s=Fs();if(!qL(s))return{content:JSON.stringify([])};let i;try{let l=await GL(s);i=(l.length>1048576?l.subarray(l.length-1048576):l).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
|
|
281
281
|
`),c=[];for(let l=a.length-1;l>=0;l-=1){let d=a[l];if(d)try{let u=JSON.parse(d);if(u.taskId!==r)continue;if(c.push(u),c.length>=o)break}catch{continue}}return{content:JSON.stringify(c.reverse())}},mw=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=n.permanent===!0,s=n.enable===!0,i=lw(r);if(!i)return{content:JSON.stringify({error:"task not found"})};let a;if(o)cw(r),a=await Qn("DELETE",`/tasks/${r}`);else if(s){let l=Sn().map(d=>d.id===r?{...d,enabled:!0,updatedAt:new Date().toISOString()}:d);Mo(l),a=await Qn("POST","/tasks",dw({...i,enabled:!0}))}else{let l=Sn().map(d=>d.id===r?{...d,enabled:!1,updatedAt:new Date().toISOString()}:d);Mo(l),a=await Qn("DELETE",`/tasks/${r}`)}return{content:JSON.stringify({ok:!0,taskId:r,permanent:o,enabled:o?void 0:!!s,daemonSynced:a.synced,syncDetail:a.detail,...a.synced?{}:{syncNote:bu}})}};import{existsSync as hw}from"node:fs";import{readFile as yw,writeFile as XL,rename as zL}from"node:fs/promises";import{join as Zi}from"node:path";C();var wu=6,Su=60;function JL(){let t=[{name:"Cursor",path:"~/Library/Application Support/Cursor/User/settings.json"},{name:"VS Code",path:"~/Library/Application Support/Code/User/settings.json"},{name:"VS Code Insiders",path:"~/Library/Application Support/Code - Insiders/User/settings.json"}];if(process.platform==="linux"&&t.push({name:"VS Code",path:"~/.config/Code/User/settings.json"},{name:"Cursor",path:"~/.config/Cursor/User/settings.json"}),process.platform==="win32"){let e=b.APPDATA??(b.USERPROFILE?Zi(b.USERPROFILE,"AppData","Roaming"):null);e&&t.push({name:"VS Code",path:Zi(e,"Code","User","settings.json")},{name:"VS Code Insiders",path:Zi(e,"Code - Insiders","User","settings.json")},{name:"Cursor",path:Zi(e,"Cursor","User","settings.json")})}return t.filter(e=>hw(e.path.startsWith("~")?Gn(e.path):e.path))}function gw(t){return t.toLowerCase().replace(/\s+/g,"")}function ku(t={}){let e=t.discoverFn??JL,n=t.writeFn??XL;return async(r,o)=>{if(!r||typeof r!="object")return{content:"Invalid input: expected object",isError:!0};let s=r,i=s.action;if(i!=="get"&&i!=="set")return{content:'Invalid action. Use "action": "get" to read current font sizes, or "action": "set" with "size": <number> to update them.',isError:!0};let a;if(i==="set"){if(typeof s.size!="number")return{content:`Invalid input: "size" must be a number between ${wu} and ${Su}.`,isError:!0};if(a=s.size,a<wu||a>Su)return{content:`Invalid font size ${a}. Must be between ${wu} and ${Su}.`,isError:!0}}let c=typeof s.editor=="string"?s.editor:void 0,l=e();if(c!==void 0){let d=gw(c);if(!["cursor","vscode","vscodeinsiders"].includes(d))return{content:`Unknown editor "${c}". Supported editors: Cursor, VS Code, VS Code Insiders.`,isError:!0};l=l.filter(p=>gw(p.name)===d)}return l.length===0?{content:c!==void 0?`No settings.json found for editor "${c}".`:"No supported editors detected (Cursor or VS Code not installed, or settings file not found)."}:i==="get"?VL(l):YL(l,a,n)}}async function VL(t){let e=[];for(let n of t){let r=Gn(n.path);if(!hw(r)){e.push(`${n.name}: terminal.integrated.fontSize = (default, ~12\u201314)`);continue}let o;try{o=await yw(r,"utf-8")}catch{e.push(`${n.name}: (could not read settings \u2014 file may contain comments or be malformed)`);continue}let s;try{s=JSON.parse(o)}catch{e.push(`${n.name}: (could not read settings \u2014 file may contain comments or be malformed)`);continue}let i=s["terminal.integrated.fontSize"];typeof i=="number"?e.push(`${n.name}: terminal.integrated.fontSize = ${i}`):e.push(`${n.name}: terminal.integrated.fontSize = (not set \u2014 editor default applies)`)}return{content:e.join(`
|
|
282
282
|
`)}}async function YL(t,e,n){let r=[],o=!1;for(let s of t){let i=Gn(s.path),a={};try{let d=await yw(i,"utf-8");try{a=JSON.parse(d)}catch{r.push(`${s.name}: could not update \u2014 settings file may contain comments or be malformed. Edit manually: ${i}`),o=!0;continue}}catch(d){let u=d;if(u.code!=="ENOENT"){r.push(`${s.name}: could not read settings \u2014 ${u.message}`),o=!0;continue}a={}}a["terminal.integrated.fontSize"]=e;let c=`${i}.tmp`,l=JSON.stringify(a,null,2)+`
|
|
283
283
|
`;try{await n(c,l,"utf-8"),await zL(c,i),r.push(`${s.name}: terminal.integrated.fontSize set to ${e}`)}catch(d){let u=d;r.push(`${s.name}: could not write settings \u2014 ${u.message}`),o=!0}}return o?{content:r.join(`
|
|
284
284
|
`),isError:!0}:{content:r.join(`
|
|
285
285
|
`)}}var QL=ku();import{join as xu,resolve as Zn,isAbsolute as CN,sep as PN}from"node:path";import{promises as MN}from"node:fs";M();import{promises as qe,existsSync as Aw,createReadStream as fN,realpathSync as mN}from"node:fs";import{join as ta,relative as gN,isAbsolute as hN}from"node:path";import{createInterface as yN}from"node:readline";import{promises as ea}from"node:fs";import{O_WRONLY as ZL,O_CREAT as eN,O_TRUNC as tN,O_NOFOLLOW as nN}from"node:constants";import{join as bw}from"node:path";var ww=3,rN=".sweep-runs",oN=384;function vu(t){return bw(t,".afk-worktrees",rN)}function sN(t){return bw(t,".afk-worktrees")}async function Tu(t){try{if(!(await ea.stat(sN(t))).isDirectory())return null}catch(n){let r=n.code;return r==="ENOENT"||r==="ENOTDIR"?null:0}let e;try{e=await ea.lstat(vu(t))}catch{return 0}if(!e.isFile())return 0;try{let n=Number.parseInt((await ea.readFile(vu(t),"utf-8")).trim(),10);if(Number.isInteger(n)&&n>=0)return n}catch{}return 0}async function Sw(t){try{let e=await Tu(t);if(e===null)return;let n=await ea.open(vu(t),ZL|eN|tN|nN,oN);try{await n.writeFile(String(e+1),"utf-8")}finally{await n.close()}}catch{}}import{readdir as iN,stat as aN}from"node:fs/promises";import{join as cN}from"node:path";function lN(t){return $t(t)!=="protected"}async function dN(t,e){if(t.isDirectory())return!0;if(!t.isSymbolicLink())return!1;try{return(await aN(e)).isDirectory()}catch{return!1}}var uN=8,pN=4e3;async function kw(t,e,n,r={}){if(!Number.isFinite(e)||e<n)return{remove:!1,because:"too-young",detail:`age ${Math.max(0,Math.round(e))}ms < ${n}ms`};let o=r.maxDepth??uN,s=r.maxEntries??pN,i=s,a=[{abs:t,rel:"",depth:0}];for(;a.length>0;){let c=a.pop();if(c===void 0)break;let l;try{l=await iN(c.abs,{withFileTypes:!0})}catch(d){return{remove:!1,because:"scan-failed",detail:`${c.rel===""?t:c.rel}: ${d instanceof Error?d.message:String(d)}`}}for(let d of l){if(--i<0)return{remove:!1,because:"scan-budget-exhausted",detail:`exceeded ${s} entries`};let u=c.rel===""?d.name:`${c.rel}/${d.name}`,p=cN(c.abs,d.name);if(await dN(d,p)&&!d.isDirectory()){if($t(`${u}/`)==="opaque")continue;return{remove:!1,because:"non-rebuildable-content",detail:u}}if(d.isDirectory()){if($t(`${u}/`)==="opaque")continue;if(c.depth+1>o)return{remove:!1,because:"scan-failed",detail:`depth limit at ${u}`};a.push({abs:p,rel:u,depth:c.depth+1});continue}if(!lN(u))return{remove:!1,because:"non-rebuildable-content",detail:u}}}return{remove:!0}}var xw=36e5,bN=30*864e5;function vw(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Tw(t){try{return mN(t)}catch{return t}}function _w(t,e){let n=gN(Tw(e),Tw(t));return n===""||!n.startsWith("..")&&!hN(n)}function _u(t){return t.replace(/^refs\/heads\//,"")}function wN(t){let e=t.trim().split(/\n\n+/),n=[];for(let r of e){let o=r.split(`
|
|
286
|
-
`),s="",i="",a="",c=!1,l=!1,d=!1;for(let u of o)u.startsWith("worktree ")?s=u.slice(9).trim():u.startsWith("HEAD ")?i=u.slice(5).trim():u.startsWith("branch ")?a=u.slice(7).trim():u.trim()==="locked"?c=!0:u.trim()==="prunable"?l=!0:u.trim()==="bare"&&(d=!0);s&&n.push({path:s,head:i,branch:a,locked:c,prunable:l,isBare:d})}return n}function Ew(t){return t.commitsAhead>0&&t.commitsUnpushed>0}function SN(t,e,n){if(t.locked)return"locked";let r=864e5,o=e*r,s=n*r;return t.ownerLiveness==="dead"&&!t.isDirty&&!Ew(t)?"dead-owner":t.ownerLiveness!=="alive"&&!Ew(t)&&!t.isDirty&&t.ageMs>=xw?"empty":t.isDirty&&t.ageMs>s?"stale-dirty":!t.isDirty&&t.commitsAhead>0&&t.ageMs>o?"stale-clean":"active"}async function kN(t){if(!Aw(t))return 0;let e=0;try{let n=yN({input:fN(t),crlfDelay:1/0});for await(let r of n){let o=r.trim();if(o)try{let s=JSON.parse(o);s.taskId==="worktree-prune"&&(s.status==="success"||s.status==="error")&&e++}catch{}}}catch{}return e}var na=class extends Error{constructor(e){super(`Worktree sweep lock contested: ${e} \u2014 another sweep may be running.`),this.name="LockContestedError"}};async function vN(t){let e=ta(t,"..");await qe.mkdir(e,{recursive:!0}).catch(()=>{});let r=await(async()=>{try{return await qe.open(t,"wx")}catch(o){if(o.code!=="EEXIST")throw o;let i=null;try{let a=await qe.readFile(t,"utf-8");i=parseInt(a.trim(),10)}catch{}if(i!==null&&!Number.isNaN(i)){let a=!1;try{process.kill(i,0),a=!0}catch{}if(!a)return await qe.unlink(t).catch(()=>{}),await qe.open(t,"wx")}throw new na(t)}})();return await r.writeFile(String(process.pid),"utf-8"),await r.close(),async()=>{await qe.unlink(t).catch(()=>{})}}async function Rw(t){let{execFile:e,repoRoot:n,maxAgeDaysClean:r=14,maxAgeDaysDirty:o=30,scope:s="all",telemetryPath:i}=t,a=i??Fs(),c=t.lockPath??xm(),l={removed:[],warnings:[],dryRun:t.dryRun??!1,candidates:[]},d=t.bypassSoftLaunch?Number.POSITIVE_INFINITY:await Tu(n)??await kN(a),u=t.dryRun===!0||d<ww;l.dryRun=u;let p=null;try{p=await vN(c)}catch(f){if(f instanceof na)return l.warnings.push(`[WARN] ${f.message}`),l.contested=!0,l;throw f}try{let f=await e("git",["-C",n,"worktree","list","--porcelain"]),m=wN(f.stdout),g=ta(n,".afk-worktrees"),h=new Set(m.map(
|
|
286
|
+
`),s="",i="",a="",c=!1,l=!1,d=!1;for(let u of o)u.startsWith("worktree ")?s=u.slice(9).trim():u.startsWith("HEAD ")?i=u.slice(5).trim():u.startsWith("branch ")?a=u.slice(7).trim():u.trim()==="locked"?c=!0:u.trim()==="prunable"?l=!0:u.trim()==="bare"&&(d=!0);s&&n.push({path:s,head:i,branch:a,locked:c,prunable:l,isBare:d})}return n}function Ew(t){return t.commitsAhead>0&&t.commitsUnpushed>0}function SN(t,e,n){if(t.locked)return"locked";let r=864e5,o=e*r,s=n*r;return t.ownerLiveness==="dead"&&!t.isDirty&&!Ew(t)?"dead-owner":t.ownerLiveness!=="alive"&&!Ew(t)&&!t.isDirty&&t.ageMs>=xw?"empty":t.isDirty&&t.ageMs>s?"stale-dirty":!t.isDirty&&t.commitsAhead>0&&t.ageMs>o?"stale-clean":"active"}async function kN(t){if(!Aw(t))return 0;let e=0;try{let n=yN({input:fN(t),crlfDelay:1/0});for await(let r of n){let o=r.trim();if(o)try{let s=JSON.parse(o);s.taskId==="worktree-prune"&&(s.status==="success"||s.status==="error")&&e++}catch{}}}catch{}return e}var na=class extends Error{constructor(e){super(`Worktree sweep lock contested: ${e} \u2014 another sweep may be running.`),this.name="LockContestedError"}};async function vN(t){let e=ta(t,"..");await qe.mkdir(e,{recursive:!0}).catch(()=>{});let r=await(async()=>{try{return await qe.open(t,"wx")}catch(o){if(o.code!=="EEXIST")throw o;let i=null;try{let a=await qe.readFile(t,"utf-8");i=parseInt(a.trim(),10)}catch{}if(i!==null&&!Number.isNaN(i)){let a=!1;try{process.kill(i,0),a=!0}catch{}if(!a)return await qe.unlink(t).catch(()=>{}),await qe.open(t,"wx")}throw new na(t)}})();return await r.writeFile(String(process.pid),"utf-8"),await r.close(),async()=>{await qe.unlink(t).catch(()=>{})}}async function Rw(t){let{execFile:e,repoRoot:n,maxAgeDaysClean:r=14,maxAgeDaysDirty:o=30,scope:s="all",telemetryPath:i}=t,a=i??Fs(),c=t.lockPath??xm(),l={removed:[],warnings:[],dryRun:t.dryRun??!1,candidates:[]},d=t.bypassSoftLaunch?Number.POSITIVE_INFINITY:await Tu(n)??await kN(a),u=t.dryRun===!0||d<ww;l.dryRun=u;let p=null;try{p=await vN(c)}catch(f){if(f instanceof na)return l.warnings.push(`[WARN] ${f.message}`),l.contested=!0,l;throw f}try{let f=await e("git",["-C",n,"worktree","list","--porcelain"]),m=wN(f.stdout),g=ta(n,".afk-worktrees"),h=new Set(m.map(k=>k.path)),y=[],w=g;try{(await qe.lstat(g)).isSymbolicLink()&&(l.warnings.push(`[WARN] skipping orphan scan: .afk-worktrees is a symlink, not a directory: ${g}`),w=null)}catch{}if(w!==null)try{y=(await qe.readdir(w,{withFileTypes:!0})).filter(A=>A.isDirectory()).map(A=>ta(g,A.name))}catch{}let S=y.filter(k=>!h.has(k));if(s==="all"||s==="interactive")for(let k of S){let A=0;try{let D=await qe.stat(k);Number.isFinite(D.birthtimeMs)&&D.birthtimeMs>0&&(A=Math.max(0,Date.now()-D.birthtimeMs))}catch{}let R=await kw(k,A,xw);if(l.candidates.push({path:k,verdict:R.remove?"orphaned-dir":"orphaned-dir-preserved",owner:"interactive",ageMs:A}),!R.remove){l.warnings.push(`[WARN] orphaned dir preserved (${R.because}${R.detail===void 0?"":`: ${R.detail}`}): ${k}`);continue}if(!u)try{await qe.rm(k,{recursive:!0,force:!0}),l.removed.push(k)}catch(D){l.warnings.push(`[ERROR] Failed to remove orphaned dir ${k}: ${D instanceof Error?D.message:String(D)}`)}}let v=t.readPresence??Ai,_=[];try{_=(await v()).filter(A=>typeof A.pid=="number"&&A.pid>0&&vw(A.pid)).map(A=>A.cwd).filter(A=>typeof A=="string"&&A.length>0)}catch{}let E=!1,T=m[0]?.path,I=m[0]?.head;for(let k of m){if(k.path===T||k.isBare||!_w(k.path,g))continue;let A;try{let X=await qe.readFile(ta(k.path,".afk-worktree-meta.json"),"utf-8");A=JSON.parse(X)}catch{}if(s!=="all"&&A?.owner!==s)continue;let R=A?.owner==="interactive"||A?.owner==="diagnose"?A.owner:"unknown";if(!Aw(k.path)){l.candidates.push({path:k.path,verdict:"orphaned-registration",owner:R,ageMs:0}),u||(E=!0);continue}let D=0,G=A?.createdAt;if(G)D=Date.now()-new Date(G).getTime();else try{let X=await qe.stat(k.path);D=Date.now()-X.birthtimeMs}catch{}let F=!1,N="clean",O=0;try{F=(await e("git",["-C",k.path,"status","--porcelain"])).stdout.trim().length>0,F&&(N="uncommitted changes")}catch{F=!0,N="git status failed"}if(!F){let X=await $i(e,k.path);F=X.protect,X.protect&&(N=X.because==="git-failed"?"ignored-file probe failed":`non-rebuildable ignored files: ${X.detail}`),X.protect&&X.because==="git-failed"&&l.warnings.push(`[WARN] ignored-file probe failed for ${k.path} \u2014 preserving (${X.detail})`)}if(!F&&k.head)try{let X=A?.baseSha!==void 0?["-C",n,"rev-list",`${A.baseSha}..${k.head}`,"--count"]:I!==void 0&&I!==k.head?["-C",n,"rev-list",k.head,"--not",I,"--count"]:void 0;if(X!==void 0){let Lr=await e("git",X);O=parseInt(Lr.stdout.trim(),10)||0}}catch{O=0}let U=O;if(O>0)try{let X=await e("git",["-C",k.path,"rev-list","@{upstream}..HEAD","--count"]),Lr=parseInt(X.stdout.trim(),10);Number.isInteger(Lr)&&Lr>=0&&(U=Lr)}catch{}let q="unknown";typeof A?.pid=="number"&&Number.isInteger(A.pid)&&A.pid>0&&D<=bN&&(q=vw(A.pid)?"alive":"dead"),q!=="alive"&&_.some(X=>_w(X,k.path))&&(q="alive");let H={path:k.path,head:k.head,branch:k.branch,locked:k.locked,prunable:k.prunable,meta:A,ageMs:D,isDirty:F,dirtyReason:N,commitsAhead:O,commitsUnpushed:U,ownerLiveness:q},de=SN(H,r,o);if(l.candidates.push({path:k.path,verdict:de,owner:R,ageMs:D}),u)continue;let ft=H.commitsAhead===0,Te=async()=>{!k.branch||!ft||await e("git",["-C",n,"branch","-d",_u(k.branch)]).catch(()=>{})};try{de==="empty"?(await e("git",["-C",n,"worktree","remove","--force",k.path]),await Te(),!ft&&k.branch&&l.warnings.push(`[INFO] reaped worktree with pushed commits; branch preserved (${_u(k.branch)}): ${k.path}`),l.removed.push(k.path)):de==="dead-owner"?(await e("git",["-C",n,"worktree","remove","--force",k.path]),await Te(),!ft&&k.branch&&l.warnings.push(`[INFO] reaped worktree with pushed commits; branch preserved (${_u(k.branch)}): ${k.path}`),l.removed.push(k.path)):de==="stale-clean"?l.warnings.push(`[WARN] stale-clean worktree preserved (commits ahead of base): ${k.path}`):de==="stale-dirty"&&l.warnings.push(`[WARN] stale-dirty worktree preserved (${H.dirtyReason}): ${k.path}`)}catch(X){l.warnings.push(`[ERROR] Failed to process ${k.path} (${de}): ${X instanceof Error?X.message:String(X)}`)}}if(E&&!u)try{await e("git",["-C",n,"worktree","prune"])}catch(k){l.warnings.push(`[ERROR] git worktree prune failed: ${k instanceof Error?k.message:String(k)}`)}}finally{p&&await p()}return t.bypassSoftLaunch!==!0&&t.dryRun!==!0&&await Sw(n),l}C();import{execFile as TN}from"node:child_process";import{promisify as _N}from"node:util";import{promises as Iw}from"node:fs";import{join as Eu,resolve as EN,isAbsolute as AN,dirname as xN}from"node:path";C();var Cw=_N(TN);async function Pw(t,e){let r=(await t("git",["-C",e,"rev-parse","--git-common-dir"])).stdout.trim();if(!r)throw new Error("Not in a git repository.");let o=AN(r)?r:EN(e,r),s=xN(o);return{repoRoot:s,afkWorktreesRoot:Eu(s,".afk-worktrees")}}function Mw(t){return t.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,80)}async function Ow(t,e){try{let r=(await t("git",["-C",e,"rev-parse","HEAD"])).stdout.trim();if(r)return r}catch{}return"HEAD"}async function Dw(t){let{execFile:e,repoRoot:n,worktreePath:r,branch:o,baseRef:s}=t;await e("git",["-C",n,"worktree","add","-b",o,r,s]),await Ud(n);let i="";try{i=(await e("git",["-C",n,"rev-parse",s])).stdout.trim()}catch{}try{await Iw.writeFile(Eu(r,".afk-worktree-meta.json"),JSON.stringify({owner:t.owner??"agent",pid:process.pid,createdAt:new Date().toISOString(),baseSha:i,baseBranch:s},null,2),"utf-8")}catch{}return{path:r,branch:o,baseRef:s,baseSha:i}}async function RN(t,e){try{return(await t("git",["-C",e,"status","--porcelain"])).stdout.trim().length>0}catch{return!0}}async function IN(t,e,n){try{let r=await Iw.readFile(Eu(n,".afk-worktree-meta.json"),"utf-8"),o=JSON.parse(r);if(!o.baseSha)return 0;let s=await t("git",["-C",n,"rev-parse","HEAD"]),i=await t("git",["-C",e,"rev-list",`${o.baseSha}..${s.stdout.trim()}`,"--count"]);return parseInt(i.stdout.trim(),10)||0}catch{return 0}}async function Fw(t){let{execFile:e,repoRoot:n,worktreePath:r,force:o}=t;if(!o){if(await RN(e,r))return{removed:!1,reason:"dirty"};if(await Ey(e,r))return{removed:!1,reason:"ignored-local-state"};let i=await IN(e,n,r);if(i>0)return{removed:!1,reason:"commits-ahead",commitsAhead:i}}let s=["-C",n,"worktree","remove"];return o&&s.push("--force"),s.push(r),await e("git",s),{removed:!0,branchPreserved:t.branch??null}}async function ON(t){let e=[["pnpm-lock.yaml","pnpm install"],["package-lock.json","npm install"],["yarn.lock","yarn install"],["bun.lockb","bun install"]];for(let[n,r]of e)try{return await MN.access(xu(t,n)),r}catch{}return"pnpm install"}function DN(t){if(!(t==null||t===""))return typeof t!="string"?{error:"Invalid input: base must be a string when provided"}:t.startsWith("-")?{error:"Invalid input: base must be a git ref, not an option"}:t}function FN(t,e){let n=Zn(t),r=Zn(e);return n===r||n.startsWith(r+PN)}async function LN(t,e){let n=await t("git",["-C",e,"worktree","list","--porcelain"]),r=[],o;for(let s of n.stdout.split(`
|
|
287
287
|
`))s.startsWith("worktree ")?(o&&r.push(o),o={path:s.slice(9).trim(),locked:!1}):s.startsWith("branch ")&&o?o.branch=s.slice(7).trim():s.startsWith("locked")&&o&&(o.locked=!0);return o&&r.push(o),r}async function Lw(t,e,n){return(await LN(t,e)).find(o=>Zn(o.path)===Zn(n))}async function Au(t,e,n){let r=CN(n)?n:xu(e.afkWorktreesRoot,n);if(!FN(r,e.afkWorktreesRoot))return`Refused: ${r} is outside the afk-managed worktree root (${e.afkWorktreesRoot}). This tool only manages worktrees under .afk-worktrees/.`;let o=await Lw(t,e.repoRoot,r);return o||`No registered git worktree at ${r}. Use action "list" to see managed worktrees.`}function Nw(t,e){let n=e?.execFile??Cw;return async(r,o,s)=>{if(!r||typeof r!="object")return{content:"Invalid input: expected object",isError:!0};let i=r,a=i.action;if(a!=="create"&&a!=="keep"&&a!=="release"&&a!=="list"&&a!=="remove")return{content:"Invalid input: action must be one of create | keep | release | list | remove",isError:!0};let c=s?.resolveBase??s?.cwd??t??process.cwd(),l;try{l=await Pw(n,c)}catch(d){return{content:`Cannot resolve git repo root from ${c}: ${d instanceof Error?d.message:String(d)}`,isError:!0}}try{switch(a){case"create":{if(typeof i.name!="string"||!i.name)return{content:"Invalid input: name required for create",isError:!0};let d=Mw(i.name);if(!d)return{content:`Invalid input: name "${i.name}" sanitizes to empty`,isError:!0};let u=xu(l.afkWorktreesRoot,d);if(await Lw(n,l.repoRoot,u))return{content:`Worktree already exists at ${u}`,isError:!0};let m=`${b.AFK_WORKTREE_BRANCH_PREFIX??"afk/"}${d}`,g=DN(i.base);if(typeof g=="object")return{content:g.error,isError:!0};let h=g??await Ow(n,c),y=await Dw({execFile:n,repoRoot:l.repoRoot,worktreePath:u,branch:m,baseRef:h}),w=await ON(y.path);return{content:JSON.stringify({path:y.path,branch:y.branch,base:y.baseRef,note:`Dependencies are NOT installed in this fresh worktree (no shared node_modules). Run \`${w}\` in ${y.path} before building or testing, or the build/tests will fail opaquely.`})}}case"keep":{if(typeof i.path!="string"||!i.path)return{content:"Invalid input: path required for keep",isError:!0};let d=await Au(n,l,i.path);if(typeof d=="string")return{content:d,isError:!0};let u=typeof i.reason=="string"&&i.reason?i.reason:"kept by agent";return await n("git",["-C",l.repoRoot,"worktree","lock","--reason",`afk: ${u}`,d.path]),{content:JSON.stringify({path:d.path,locked:!0,note:'The sweep engine never removes or warns about locked worktrees. Use action "release" to unlock.'})}}case"release":{if(typeof i.path!="string"||!i.path)return{content:"Invalid input: path required for release",isError:!0};let d=await Au(n,l,i.path);return typeof d=="string"?{content:d,isError:!0}:(await n("git",["-C",l.repoRoot,"worktree","unlock",d.path]),{content:JSON.stringify({path:d.path,locked:!1})})}case"list":{let d=await Rw({execFile:n,repoRoot:l.repoRoot,dryRun:!0,scope:"all"});return{content:JSON.stringify(d.candidates.map(u=>({path:u.path,verdict:u.verdict,owner:u.owner,ageDays:Math.round(u.ageMs/864e5)})))}}case"remove":{if(typeof i.path!="string"||!i.path)return{content:"Invalid input: path required for remove",isError:!0};let d=await Au(n,l,i.path);if(typeof d=="string")return{content:d,isError:!0};if(Zn(d.path)===Zn(l.repoRoot))return{content:"Refused: cannot remove the main worktree.",isError:!0};if(d.locked)return{content:`Refused: ${d.path} is locked. Use action "release" first if removal is really intended.`,isError:!0};let u=i.force===!0,p=await Fw({execFile:n,repoRoot:l.repoRoot,worktreePath:d.path,branch:d.branch??null,force:u});return p.removed?{content:JSON.stringify({path:d.path,removed:!0,branchPreserved:p.branchPreserved})}:p.reason==="dirty"?{content:`Refused: ${d.path} has uncommitted changes. Commit/stash them, or pass force: true to discard.`,isError:!0}:p.reason==="ignored-local-state"?{content:`Refused: ${d.path} holds non-rebuildable ignored files (e.g. .env, a gitignored plan) that \`git status\` cannot see, so removal would silently delete them. Move/back up what you need, or pass force: true to discard them along with the checkout.`,isError:!0}:{content:`Refused: ${d.path} has ${p.commitsAhead} commit(s) ahead of its base. The branch ref would survive, but pass force: true to confirm removing the checkout.`,isError:!0}}}}catch(d){return{content:`worktree ${a} failed: ${d instanceof Error?d.message:String(d)}`,isError:!0}}return{content:"Unhandled action",isError:!0}}}M();C();import{existsSync as Yw,readFileSync as XN,copyFileSync as zN,chmodSync as JN}from"fs";import{existsSync as Oo,readFileSync as ra,writeFileSync as NN,renameSync as UN,mkdirSync as $N,unlinkSync as BN}from"fs";import{dirname as jN}from"path";function Pe(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oa(t,e,n=384){$N(jN(t),{recursive:!0});let r=`${t}.${process.pid}.${Date.now()}.tmp`;try{NN(r,e,{mode:n}),UN(r,t)}catch(o){try{Oo(r)&&BN(r)}catch{}throw o}}function Uw(t,e,n,r=[]){let o="";Oo(t)&&(o=ra(t,"utf-8"));for(let a of r){let c=new RegExp(`^${Pe(a)}=.*$
|
|
288
288
|
?`,"m");o=o.replace(c,"")}let s=`${e}=${n}`,i=new RegExp(`^${Pe(e)}=.*$`,"m");i.test(o)?o=o.replace(i,s):(o&&!o.endsWith(`
|
|
289
289
|
`)&&(o+=`
|
|
@@ -299,14 +299,14 @@ ${e}`}C();import{BlockList as WD,isIP as Vd}from"node:net";import{lookup as KD}f
|
|
|
299
299
|
`),this.errored=!0,this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null}}}_writeLine(e){if(!(!this.stream||this.errored))try{this.stream.write(e,n=>{n&&(process.stderr.write(`[afk] session-ledger: write error for ${this.sessionId}: ${String(n)}
|
|
300
300
|
`),this.errored=!0)})}catch(n){process.stderr.write(`[afk] session-ledger: write threw for ${this.sessionId}: ${String(n)}
|
|
301
301
|
`),this.errored=!0}}async close(e){if(!this.closed)return this.record({kind:"closed",...e!==void 0?{reason:e}:{}}),this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(n=>{if(!this.stream){n();return}this.stream.end(()=>n())})}};function hS(t){let e=t.trim();if(!e)return null;try{let n=JSON.parse(e);return n.v!==1||typeof n.ts!="number"||typeof n.kind!="string"?null:n}catch{return null}}async function pa(t){if(!Cn(t))return!1;try{return await kn.access(Wr(t)),!0}catch{return!1}}async function*yS(t){if(!Cn(t))return;let e;try{e=await kn.open(Wr(t),"r")}catch(n){if(n.code==="ENOENT")return;throw n}try{let n=mS.createInterface({input:e.createReadStream({encoding:"utf8"}),crlfDelay:1/0});for await(let r of n){let o=hS(r);o&&(yield o)}}finally{await e.close()}}var YN=250;async function*bS(t,e){if(!Cn(t))return;let n=Wr(t),r=Hr(t),{fromStart:o=!1,signal:s}=e??{},i=0,a="",c=!1;async function*l(){let f=null;try{f=await kn.open(n,"r");let m=await f.stat();if(m.size<=i)return;let g=m.size-i,h=Buffer.allocUnsafe(g),{bytesRead:y}=await f.read(h,0,g,i);if(y===0)return;i+=y,a+=h.toString("utf8",0,y);let w=a.split(`
|
|
302
|
-
`);a=w.pop()??"";for(let
|
|
302
|
+
`);a=w.pop()??"";for(let S of w){let v=hS(S);if(v&&(v.kind==="closed"&&(c=!0),yield v,c))return}}catch(m){m.code!=="ENOENT"&&process.stderr.write(`[afk] session-ledger: tail read error for ${t}: ${String(m)}
|
|
303
303
|
`)}finally{f&&await f.close().catch(()=>{})}}if(o){if(yield*l(),c)return}else try{i=(await kn.stat(n)).size}catch{}let d=null,u=null,p=()=>new Promise(f=>{let m=setTimeout(()=>{u=null,f()},YN);u=()=>{clearTimeout(m),u=null,f()},s?.addEventListener("abort",()=>{clearTimeout(m),u=null,f()},{once:!0})});try{d=er.watch(r,{persistent:!1},()=>{u?.()})}catch{}try{for(;!s?.aborted&&!c&&(await p(),!s?.aborted);)yield*l()}finally{d?.close()}}M();import{readdir as QN,stat as ZN}from"node:fs/promises";import{join as eU}from"node:path";async function Du(){let t=jr(),e;try{e=await QN(t)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of e){let o=eU(t,r,"trace.jsonl");try{let s=await ZN(o);s.isFile()&&n.push({sessionId:r,tracePath:o,mtimeMs:s.mtimeMs,exists:!0})}catch{}}return n.sort((r,o)=>o.mtimeMs-r.mtimeMs),n}async function wS(){return(await Du())[0]?.sessionId??null}M();import{existsSync as tU,readdirSync as nU,readFileSync as rU}from"node:fs";import{basename as oU,join as sU}from"node:path";var iU=3;function aU(t){try{let e=JSON.parse(rU(t,"utf-8"));if(typeof e!="object"||e===null)return;let n=e;return{sessionId:typeof n.sessionId=="string"?n.sessionId:void 0,name:typeof n.name=="string"?n.name:void 0,savedAt:typeof n.savedAt=="number"?n.savedAt:void 0}}catch{return}}function cU(t){if(!tU(t))return[];let e;try{e=nU(t)}catch{return[]}let n=[];for(let r of e){if(!r.endsWith(".json"))continue;let o=sU(t,r),s=aU(o);s&&n.push({sidecarId:oU(r,".json"),filePath:o,data:s})}return n}function fa(t,e=re()){let n=cU(e);n.sort((r,o)=>{let s=r.data.savedAt??-1/0;return(o.data.savedAt??-1/0)-s});for(let r of n){if(r.sidecarId===t)return{sessionId:r.data.sessionId??r.sidecarId,sidecarId:r.sidecarId,reason:"exact-id"};if(r.data.sessionId===t)return{sessionId:r.data.sessionId,sidecarId:r.sidecarId,reason:"exact-session-id"};if(r.data.name===t)return{sessionId:r.data.sessionId??r.sidecarId,sidecarId:r.sidecarId,reason:"exact-name"}}if(t.length>=iU){let r=n.filter(o=>o.data.name!==void 0&&o.data.name.startsWith(t));if(r.length===1){let o=r[0];return{sessionId:o.data.sessionId??o.sidecarId,sidecarId:o.sidecarId,reason:"prefix-name"}}}}import{existsSync as lU}from"node:fs";import{readFile as dU}from"node:fs/promises";var SS=2097152;async function Fu(t){if(!lU(t))return{content:"",truncated:!1};try{let e=await dU(t);if(e.length<=SS)return{content:e.toString("utf-8"),truncated:!1};let n=e.subarray(e.length-SS),r=n.indexOf(10);return r!==-1&&(n=n.subarray(r+1)),{content:n.toString("utf-8"),truncated:!0}}catch{return{content:"",truncated:!1}}}var uU=50,pU=200,fU=200,mU=20,gU=100;function vS(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.kind=="string"&&typeof e.seq=="number"&&typeof e.payload=="object"&&e.payload!==null}function hU(t){return oo(t,{guard:vS})}function yU(t){return typeof t!="number"?uU:Math.min(Math.max(1,Math.round(t)),pU)}function bU(t){return typeof t!="number"?mU:Math.min(Math.max(1,Math.round(t)),gU)}function wU(t,e){if(e.kinds&&!e.kinds.has(t.kind)||e.toolName&&(t.kind!=="tool_call"||t.payload.name!==e.toolName))return!1;if(e.errorsOnly)if(t.kind==="tool_call"){let n=t.payload;if(n.phase!=="completed"||!n.isError)return!1}else if(t.kind==="subagent_lifecycle"){if(t.payload.transition!=="failed")return!1}else if(t.kind==="background_agent"){if(t.payload.transition!=="failed")return!1}else return!1;return!0}async function SU(t){let e=async r=>{let o=kS(Pt(r),"trace.jsonl");if(!Lu(o))try{for await(let s of yS(r))if(s.kind==="meta"){if(s.traceLabel===null)return{tracePath:o,disabledNote:r};if(typeof s.traceLabel=="string"&&s.traceLabel.length>0){let i=kS(Pt(s.traceLabel),"trace.jsonl");Lu(i)&&(o=i)}break}}catch{}return{tracePath:o,disabledNote:void 0}},n=await e(t);if(n.disabledNote!==void 0||Lu(n.tracePath))return n;try{let r=fa(t);if(r&&r.sessionId!==t){let o=await e(r.sessionId);return o.disabledNote!==void 0?{tracePath:o.tracePath,disabledNote:r.sessionId}:o}}catch{}return n}async function TS(t){let e=t.session==="latest"||!t.session?await wS():t.session;if(!e)return{sessionId:"(none)",events:[],totalInTrace:0,filtered:0};let{tracePath:n,disabledNote:r}=await SU(e);if(r!==void 0)return{sessionId:e,events:[],totalInTrace:0,filtered:0,note:`Session "${r}" ran with tracing disabled (traceLabel: null).`};let{content:o}=await Fu(n),s=hU(o),i={kinds:t.kinds?new Set(t.kinds):void 0,toolName:t.toolName,errorsOnly:t.errorsOnly},a=yU(t.limit),c=[];for(let l=s.length-1;l>=0;l--){let d=s[l];if(wU(d,i)&&(c.push(d),c.length>=a))break}return c.reverse(),{sessionId:e,events:c,totalInTrace:s.length,filtered:c.length}}async function _S(t){let e=bU(t.sessions),r=(await Du()).slice(0,e),o=r.length,s=r;if(t.since){let p=Date.parse(t.since);if(Number.isNaN(p))throw new Error(`Invalid "since" date: ${t.since}`);s=r.filter(f=>f.mtimeMs>=p)}let i=t.kinds?new Set(t.kinds):void 0,a=t.query.toLowerCase(),c=[],l=fU,d=[],u=0;for(let p of s){if(c.length>=l)break;let{content:f,truncated:m}=await Fu(p.tracePath);u++,m&&d.push(p.sessionId);let g=f.split(`
|
|
304
304
|
`).filter(h=>h.trim()!==""&&h.toLowerCase().includes(a));for(let h of g){if(c.length>=l)break;let[y]=oo(h,{guard:vS});y&&(i&&!i.has(y.kind)||t.toolName&&(y.kind!=="tool_call"||y.payload.name!==t.toolName)||c.push({sessionId:p.sessionId,event:y,matchLine:h.length>500?h.slice(0,500)+"\u2026":h}))}}return{query:t.query,sessionsAvailable:o,sessionsSearched:u,sessionsScanned:u,matches:c,...d.length>0?{truncatedSessions:d}:{}}}function ES(t){return!t||typeof t!="object"?null:t}function AS(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string")}var xS=async t=>{let e=ES(t);if(!e)return{content:"Invalid input: expected object",isError:!0};let n=typeof e.session=="string"?e.session:void 0,r=AS(e.kinds),o=typeof e.tool_name=="string"?e.tool_name:void 0,s=typeof e.errors_only=="boolean"?e.errors_only:!1,i=typeof e.limit=="number"?e.limit:void 0;try{let a=await TS({session:n,kinds:r,toolName:o,errorsOnly:s,limit:i});return{content:JSON.stringify(a)}}catch(a){return{content:`read_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},RS=async t=>{let e=ES(t);if(!e)return{content:"Invalid input: expected object",isError:!0};if(typeof e.query!="string"||!e.query)return{content:"Invalid input: query (string) is required",isError:!0};let n=e.query,r=typeof e.sessions=="number"?e.sessions:void 0,o=AS(e.kinds),s=typeof e.since=="string"?e.since:void 0,i=typeof e.tool_name=="string"?e.tool_name:void 0;try{let a=await _S({query:n,sessions:r,kinds:o,since:s,toolName:i});return{content:JSON.stringify(a)}}catch(a){return{content:`search_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}};var tr={action:"decline"},IS=300;function kU(t){return t.length<=IS?t:`${t.slice(0,IS)}\u2026(truncated)`}function vU(t){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${t.title??t.serverName}`,kU(t.message)];t.url!==void 0&&t.url!==""&&n.push(t.url),sb(n.join(`
|
|
305
305
|
`)).catch(()=>{})}catch{}}function CS(t,e){if(!(t===void 0||t===""))try{hd(t,e).catch(()=>{})}catch{}}var Nu=class{handler=null;queue=Promise.resolve();queueDepth=0;install(e){this.handler=e}uninstall(){this.handler=null}hasHandler(){return this.handler!==null}pendingCount(){return this.queueDepth}route(e,n){if(n.signal.aborted)return Promise.resolve(tr);this.queueDepth+=1;let r,o=new Promise(i=>{r=i}),s=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(tr);return}if(!s){vU(e),r(tr);return}let i,a=new Promise(c=>{i=()=>c(tr),n.signal.addEventListener("abort",i,{once:!0})});try{try{n.onActive?.()}catch{}CS(n.sessionId,!0);let c=await Promise.race([s(e,n).catch(()=>tr),a]);r(c)}finally{CS(n.sessionId,!1),n.signal.removeEventListener("abort",i)}}finally{this.queueDepth-=1,r(tr)}}).catch(()=>{}),o}},kt=new Nu;var PS=async(t,e,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let r=t,o=r.question;if(typeof o!="string"||o.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let s=new Set(["text","confirm","choice","multi_choice","number"]),i=r.type??"text";if(typeof i!="string"||!s.has(i))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(i==="choice"||i==="multi_choice"){let m=r.choices;if(!Array.isArray(m)||m.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${i}"`,isError:!0};if(m.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${m.length}`,isError:!0};for(let g of m)if(typeof g!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let a=r.min,c=r.max;if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)))return{content:"Invalid input: min must be a finite number",isError:!0};if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)))return{content:"Invalid input: max must be a finite number",isError:!0};if(a!==void 0&&c!==void 0&&a>c)return{content:`Invalid input: min (${a}) must be \u2264 max (${c})`,isError:!0};let l=r.min_length,d=r.max_length;if(l!==void 0&&typeof l!="number")return{content:"Invalid input: min_length must be a number",isError:!0};if(d!==void 0&&typeof d!="number")return{content:"Invalid input: max_length must be a number",isError:!0};if((l!==void 0||d!==void 0)&&i!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${i}"`,isError:!0};if(r.allow_custom!==void 0&&i!=="choice"&&i!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${i}"`,isError:!0};let u={serverName:"agent",message:o.trim(),origin:"agent",type:i,...r.choices!==void 0&&{choices:r.choices},...r.context!==void 0&&typeof r.context=="string"&&{context:r.context},...r.default!==void 0&&{questionDefault:r.default},...l!==void 0&&{minLength:l},...d!==void 0&&{maxLength:d},...a!==void 0&&{min:a},...c!==void 0&&{max:c},...r.allow_skip!==void 0&&{allowSkip:!!r.allow_skip},...r.allow_custom!==void 0&&{allowCustom:!!r.allow_custom}},p=await kt.route(u,{signal:e,...n?.sessionId!==void 0?{sessionId:n.sessionId}:{}}),f=p.action==="decline"||p.action==="cancel";return{content:JSON.stringify(p),...f&&{isError:!0,failureClass:"elicitation-declined"}}};C();var MS=["load","domcontentloaded","networkidle"];function TU(t){if(!t||typeof t!="object")return{error:"browser_open: input must be an object"};let e=t,n=e.url;if(typeof n!="string"||n.length===0)return{error:'browser_open: "url" is required and must be a non-empty string'};let r;try{r=new URL(n)}catch{return{error:`browser_open: "${n}" is not a valid absolute URL`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{error:`browser_open: protocol "${r.protocol}" is not supported (http/https only)`};let o;if(e.wait_for!==void 0){if(!MS.includes(e.wait_for))return{error:`browser_open: "wait_for" must be one of ${MS.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(e.wait_for)})`};o=e.wait_for}let s;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};s=e.screenshot}let i;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};i=e.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:s,timeoutMs:i}}function _U(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_open aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0,failureClass:be(n)}}let o=TU(e);if("error"in o)return{content:o.error,isError:!0};let s=b.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(wn(),bn));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return Re(u)?{content:Ke(u),isError:!0}:{content:`browser_open failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.open({sessionId:s,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),u=Date.now()-l;if("outcome"in d&&d.outcome==="blocked_by_policy")return ae(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:u}),{content:`browser_open blocked: ${d.reason}`,isError:!0,failureClass:"policy-refusal"};let p=d;return ae(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:p.url,status:"ok",durationMs:u,...p.screenshotPath!==null?{screenshotPath:p.screenshotPath}:{}}),{content:JSON.stringify(p,null,2)}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);ae(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}});let f=Qi(d);return{content:`browser_open failed: ${p}`,isError:!0,...f?{failureClass:f}:{}}}}}var OS=_U();C();function EU(t){if(t!=null&&typeof t!="object")return{error:"browser_observe: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=e.screenshot}let r;if(e.include_hidden!==void 0){if(typeof e.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=e.include_hidden}let o;if(e.max_elements!==void 0){if(typeof e.max_elements!="number"||!Number.isFinite(e.max_elements)||e.max_elements<=0||!Number.isInteger(e.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=e.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function AU(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_observe aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=EU(e);if("error"in o)return{content:o.error,isError:!0};let s=b.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(wn(),bn));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return Re(u)?{content:Ke(u),isError:!0}:{content:`browser_observe failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.observe({sessionId:s,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),u=Date.now()-l;return ae(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:d.url,urlAfter:d.url,status:"ok",durationMs:u,...d.screenshotPath!==null?{screenshotPath:d.screenshotPath}:{}}),{content:JSON.stringify(d,null,2)}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return ae(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_observe failed: ${p}`,isError:!0}}}}var DS=AU();qi();C();var FS=["click","fill","press","select","hover","scroll_to","wait_for"],LS=["semantic","element_id","selector"];function xU(t){if(!t||typeof t!="object")return{error:"browser_act: input must be an object"};let e=t;if(typeof e.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!FS.includes(e.action))return{error:`browser_act: "action" must be one of ${FS.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(e.action)})`};let n=e.action,r=e.target;if(!r||typeof r!="object")return{error:'browser_act: "target" is required and must be an object'};let o=r;if(typeof o.kind!="string"||!LS.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${LS.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let s,i=o.kind;if(i==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};s={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(i==="element_id"){if(typeof o.element_id!="string"||o.element_id.length===0)return{error:'browser_act: target.kind=element_id requires "target.element_id" (non-empty string)'};s={kind:"element_id",elementId:o.element_id}}else{if(typeof o.selector!="string"||o.selector.length===0)return{error:'browser_act: target.kind=selector requires "target.selector" (non-empty string)'};s={kind:"selector",selector:o.selector}}let a;if(e.value!==void 0){if(typeof e.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=e.value}let c;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};c=e.timeout_ms}let l;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};l=e.screenshot}return{action:n,target:s,value:a,timeoutMs:c,screenshot:l}}function RU(t,e){let n=t.role?`"${t.text}" (role: ${t.role})`:`"${t.text}"`;return[`browser_act: ambiguous target \u2014 ${e.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...e.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
|
|
306
|
-
`)}function IU(t){return t.kind==="semantic"?{kind:"semantic",text:_b(t.text),...t.role!==void 0?{role:t.role}:{}}:t.kind==="element_id"?{kind:"element_id",elementId:t.elementId}:{kind:"selector",selectorHash:Tb(t.selector)}}function CU(t={}){return async(e,n,r)=>{if(n.aborted){let u=n.reason;return{content:`browser_act aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0,failureClass:be(n)}}let o=xU(e);if("error"in o)return{content:o.error,isError:!0};let s=IU(o.target),i=b.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a,c,l;try{if(t.getBrowserProvider)a=await t.getBrowserProvider();else{let{getBrowserProvider:u,getLastRoutingDecision:p}=await Promise.resolve().then(()=>(wn(),bn));a=await u();let f=p();f&&(c=f.backend,l=f.reason)}}catch(u){let p=u instanceof Error?u.message:String(u);return Re(p)?{content:Ke(p),isError:!0}:{content:`browser_act failed to get provider: ${p}`,isError:!0}}let d=Date.now();try{let u=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),p=Date.now()-d;if("outcome"in u){if(u.outcome==="ambiguous_target")return ae(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:p}),{content:RU(u.query,u.candidates),isError:!0};if(u.outcome==="blocked_by_policy")return ae(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:p}),{content:`browser_act blocked: ${u.reason}`,isError:!0,failureClass:"policy-refusal"}}return ae(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:u.url,urlAfter:u.url,status:"ok",durationMs:p,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(u){let p=Date.now()-d,f=u instanceof Error?u.message:String(u);ae(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:p,error:{reason:f,recoverable:!1}});let m=Qi(u);return{content:`browser_act failed: ${f}`,isError:!0,...m?{failureClass:m}:{}}}}}var NS=CU();C();var US=["semantic","element_id","selector"],Uu=8e3;function PU(t){if(typeof t.kind!="string"||!US.includes(t.kind))return{error:`browser_screenshot: "target.kind" must be one of ${US.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.kind)})`};let e=t.kind;return e==="semantic"?typeof t.text!="string"||t.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:t.text,...typeof t.role=="string"&&t.role.length>0?{role:t.role}:{}}:e==="element_id"?typeof t.element_id!="string"||t.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:t.element_id}:typeof t.selector!="string"||t.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:t.selector}}function MU(t){if(t!=null&&typeof t!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.target!==void 0){if(!e.target||typeof e.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=PU(e.target);if("error"in o)return o;n=o}let r;if(e.full_page!==void 0){if(typeof e.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=e.full_page}return{target:n,fullPage:r}}function OU(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_screenshot aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=MU(e);if("error"in o)return{content:o.error,isError:!0};let s=b.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(wn(),bn));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return Re(u)?{content:Ke(u),isError:!0}:{content:`browser_screenshot failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),u=Date.now()-l,{dataBase64:p,mediaType:f,...m}=d;return ae(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:u,screenshotPath:m.path}),m.width>Uu||m.height>Uu?{content:JSON.stringify({...m,imageOmitted:`dimensions ${m.width}x${m.height}px exceed the ${Uu}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(m,null,2),image:{mediaType:f,data:p}}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return ae(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_screenshot failed: ${p}`,isError:!0}}}}var $S=OU();C();function DU(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_close aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=b.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let s,i,a;try{if(t.getBrowserProvider)s=await t.getBrowserProvider();else{let{getBrowserProvider:l,getLastRoutingDecision:d}=await Promise.resolve().then(()=>(wn(),bn));s=await l();let u=d();u&&(i=u.backend,a=u.reason)}}catch(l){let d=l instanceof Error?l.message:String(l);return Re(d)?{content:Ke(d),isError:!0}:{content:`browser_close failed to get provider: ${d}`,isError:!0}}let c=Date.now();try{await s.close({sessionId:o});let l=Date.now()-c;return ae(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:l}),{content:"Browser session closed."}}catch(l){let d=Date.now()-c,u=l instanceof Error?l.message:String(l);return ae(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}}),{content:`browser_close failed: ${u}`,isError:!0}}}}var BS=DU();import sk from"node:path";import*as ma from"node:fs/promises";import{execSync as JU}from"node:child_process";import GS from"path";var FU=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","workspace_query","read_witness","search_witness","get_facet","json_query","state_get","state_query"]),LU=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","patch_apply","memory_update","procedure_write","terminal_font_size","config_set","workspace_publish","state_put","state_cas","state_delete","clipboard_write"]),NU=new Set(["Bash","BashOutput","KillBash","bash","test_run","wait_for"]),jS=new Set(["Agent","Task","agent","cancel_background_job","send_message_to_agent"]),HS=new Set(["Skill","skill"]),WS=new Set(["Compose","compose"]),IZ=new Set([...jS,...WS,...HS]),UU=new Set(["WebFetch","WebSearch","send_telegram","web_scrape","web_request"]),$U=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),BU=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),jU=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);function Kt(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}var $u=["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness","workspace_publish","workspace_query","json_query","state_get","state_query",...$e],KS=[...$u,"web_scrape","agent"];function qS(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Kt(FU,t)?"read":Kt(LU,t)?"write":Kt(NU,t)?"shell":Kt(jS,t)?"subagent":Kt(HS,t)?"skill":Kt(WS,t)?"dag":Kt(UU,t)?"web":$U.has(t)?"browser":Kt(BU,t)?"planning":jU.has(t)?"schedule":"other"}var HU=["rm -rf","rm ","sudo","eval ","chmod","chown","git push --force","git push -f","git reset --hard","mkfs","fdisk","diskutil eraseDisk","dd if=","dd of=","| sh","| bash","|sh","|bash","-X POST","-X PUT","-X PATCH","-X DELETE","-XPOST","-XPUT","-XPATCH","-XDELETE","--request POST","--request PUT","--request PATCH","--request DELETE","curl --data","curl -d","curl -F","wget --post-data","wget --post-file","launchctl load","launchctl bootstrap","launchctl submit","launchctl start ","launchctl kickstart","launchctl enable ","systemctl enable ","systemctl start ","systemctl daemon-reload"],WU=["git push","git reset","git commit","git stash drop","git stash clear","npm install","pnpm install","yarn","pip install","apt ","apt-get ","brew install","tee "," > "," >> ","mv ","cp ","mkdir","touch","pnpm build","tsc ","eslint --fix"],KU=["pnpm test","vitest","jest","pytest","cargo test","go test","git status","git log","git diff","git show","ls ","cat ","head ","tail ","find ","grep ","echo ","printf "];function qU(t){return typeof t=="object"&&t!==null&&"command"in t?String(t.command??""):typeof t=="string"?t:""}function GU(t){if(typeof t!="object"||t===null)return"";let e=t;return typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:""}function XS(t){for(let e of HU)if(t.includes(e))return"high";for(let e of WU)if(t.includes(e))return"medium";for(let e of KU)if(t.includes(e))return"safe";return"medium"}function zS(t,e){if(!t)return"safe";let n=He(GS.resolve(e.cwd,t)),r=Td();for(let o of r)if(n===o||n.startsWith(o+"/"))return"high";if(n.includes("/.git/"))return"high";if(e.workspaceRoot!==void 0){let o=He(e.workspaceRoot);if(GS.relative(o,n).startsWith(".."))return"high"}return n.includes("/node_modules/")?"medium":"safe"}var XU=new Set(["delete","drop","remove","destroy","truncate","purge","wipe","write","create","update","insert","upsert","patch","rename","exec","execute","run","eval","send","push","publish","deploy","post","merge","rollback","reset","terminate","provision","scale","disable","charge","refund","revoke"]);function zU(t){return t.split("__").slice(1).join("__").split(/[_-]+/).filter(Boolean)}function JS(t,e,n){let r=t.toLowerCase();if(r==="bash"){let o=qU(e);return XS(o)}if(r==="write_file"||r==="edit_file"){let o=GU(e);return zS(o,n)}if(r==="patch_apply"){let o=typeof e=="object"&&e!==null?e:{},s=Array.isArray(o.changes)?o.changes:[],i="safe";for(let a of s){if(typeof a!="object"||a===null)continue;let c=a.path,d=zS(typeof c=="string"?c:"",n);if(d==="high")return"high";d==="medium"&&(i="medium")}return i}if(qS(t)==="read")return"safe";if(r==="send_telegram")return"medium";if(r.startsWith("mcp__"))return zU(r).some(s=>XU.has(s))?"high":"medium";if(r==="create_schedule"||r==="cancel_schedule")return"high";if(r==="worktree"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.action=="string"?o.action:"";return s==="list"?"safe":s==="remove"&&o.force===!0?"high":"medium"}if(r==="browser_act"||r==="browser_open"||r==="web_scrape")return"medium";if(r==="web_request"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.method=="string"?o.method.toUpperCase():"";return s==="DELETE"?"high":s==="GET"||s==="HEAD"||s==="OPTIONS"?"safe":"medium"}if(r==="wait_for"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.type=="string"?o.type:"";if(s==="command"){let i=typeof o.command=="string"?o.command:"";return XS(i)}return s==="file"||s==="process"?"safe":"medium"}return"safe"}async function VS(t,e){let n=t.method??"HEAD",r;try{r=await jt(globalThis.fetch,t.url,{method:n,signal:e})}catch(a){let c=a instanceof Error?a.message:String(a);return{met:!1,detail:c.startsWith("refusing to")?`SSRF blocked: ${c}`:`fetch error: ${c}`,data:c.startsWith("refusing to")?{blocked:!0}:void 0}}let{status:o}=r,s={status:o};if(!(t.expected_status!==void 0?o===t.expected_status:o>=200&&o<300))return{met:!1,detail:`HTTP ${o} (want ${t.expected_status??"2xx"})`,data:s};if(t.body_contains!==void 0){let a=await r.text().catch(()=>"");if(s.bodyLength=a.length,!a.includes(t.body_contains))return{met:!1,detail:`body does not contain "${t.body_contains}"`,data:s}}else n==="HEAD"&&await r.body?.cancel().catch(()=>{});return{met:!0,detail:`HTTP ${o}`,data:s}}async function YS(t,e){let n;try{let o=t.workspaceRoot?{resolveBase:t.workspaceRoot,cwd:t.workspaceRoot}:void 0;n=ee(t.path,o,"read")}catch(o){return{met:!1,detail:`path rejected: ${o instanceof Error?o.message:String(o)}`,data:{blocked:!0}}}let r;try{let o=await ma.stat(n);r={mtimeMs:o.mtimeMs,size:o.size}}catch{return{met:!1,detail:`file not found: ${t.path}`}}if(t.content_contains!==void 0){let o;try{o=await ma.readFile(n,{encoding:"utf8",signal:e})}catch(s){return{met:!1,detail:`read error: ${s instanceof Error?s.message:String(s)}`,data:r}}if(!o.includes(t.content_contains))return{met:!1,detail:`file exists but does not contain "${t.content_contains}"`,data:r}}return{met:!0,detail:`file exists (${r.size} bytes)`,data:r}}function QS(t,e){if(!Number.isInteger(t.pid)||t.pid<=1)return{met:!1,detail:`pid ${t.pid} is not a valid target (must be integer > 1)`,data:{pid:t.pid,blocked:!0}};if(e!==void 0&&!e.has(t.pid))return{met:!1,detail:`pid ${t.pid} is not a session-owned process (not in spawned PID registry)`,data:{pid:t.pid,blocked:!0}};try{return process.kill(t.pid,0),{met:!1,detail:`pid ${t.pid} is still alive`,data:{pid:t.pid}}}catch(n){let r=n.code;return r==="ESRCH"?{met:!0,detail:`pid ${t.pid} has exited`,data:{pid:t.pid}}:{met:!1,detail:`pid ${t.pid} is alive (${r??"unknown"})`,data:{pid:t.pid}}}}function ZS(t){let e=JS("bash",{command:t.command},{cwd:t.cwd??process.cwd()});if(e!=="safe")return{met:!1,detail:`command blocked by risk classifier (${e} risk): ${t.command}`,data:{command:t.command,blocked:!0}};try{return JU(t.command,{cwd:t.cwd,stdio:"pipe",timeout:3e4}),{met:!0,detail:"command exited 0",data:{command:t.command}}}catch(n){let r=n;if(r.killed===!0&&r.signal==="SIGTERM")return{met:!1,detail:"command timed out (30s limit)",data:{command:t.command,timedOut:!0}};let o=r.status??-1;return{met:!1,detail:`command exited ${o}`,data:{command:t.command,exitCode:o}}}}function Ie(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{e.removeEventListener("abort",r),n()},t);o.unref(),e.addEventListener("abort",r,{once:!0})})}var ek=12e4,tk=6e5,nk=5e3,rk=1e3;function VU(t,e,n){switch(n){case"linear":return t+e*1e3;case"exponential":return Math.min(t*Math.pow(2,e),6e4);default:return t}}async function ok(t,e){let{timeout_ms:n,poll_interval_ms:r,backoff:o,signal:s}=e,i=Date.now()+n,a=0,c;for(;;){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};let l=i-Date.now(),d=AbortSignal.any([s,AbortSignal.timeout(Math.max(1,Math.min(r,l)))]),u;try{u=await t(d)}catch(m){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};if(m instanceof Error&&m.name==="AbortError"){if(Date.now()>=i)return{status:"timed_out",elapsed_ms:Date.now()-(i-n),attempts:a,result:c};continue}let g=m instanceof Error?m.message:String(m);return{status:"failed",elapsed_ms:Date.now()-(i-n),attempts:a,error:g}}if(c=u,a++,u.met)return{status:"succeeded",elapsed_ms:Date.now()-(i-n),attempts:a,result:u};let p=Date.now();if(p>=i)return{status:"timed_out",elapsed_ms:p-(i-n),attempts:a,result:c};let f=Math.min(VU(r,a-1,o),i-p);await Ie(f,s)}}function YU(t,e){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let n=t,r=n.type;if(typeof r!="string")throw new Error('"type" is required and must be a string');let o=ek;if(n.timeout_ms!==void 0){if(typeof n.timeout_ms!="number"||!Number.isFinite(n.timeout_ms))throw new Error('"timeout_ms" must be a finite number');o=Math.min(Math.max(0,n.timeout_ms),tk)}let s=nk;if(n.poll_interval_ms!==void 0){if(typeof n.poll_interval_ms!="number"||!Number.isFinite(n.poll_interval_ms))throw new Error('"poll_interval_ms" must be a finite number');s=Math.max(rk,n.poll_interval_ms)}let i=["none","linear","exponential"],a="none";if(n.backoff!==void 0){if(!i.includes(n.backoff))throw new Error(`"backoff" must be one of: ${i.join(", ")}`);a=n.backoff}switch(r){case"url":{if(typeof n.url!="string"||n.url.trim()==="")throw new Error('"url" is required for type "url"');let c=n.body_contains!==void 0,l=n.method??(c?"GET":"HEAD");if(l!=="HEAD"&&l!=="GET")throw new Error('"method" must be "HEAD" or "GET"');return{condition:{type:"url",url:n.url,method:l,...n.expected_status!==void 0?{expected_status:Number(n.expected_status)}:{},...c?{body_contains:String(n.body_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"file":{if(typeof n.path!="string"||n.path.trim()==="")throw new Error('"path" is required for type "file"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"file",path:c!==void 0&&!sk.isAbsolute(n.path)?sk.resolve(c,n.path):n.path,workspaceRoot:c,...n.content_contains!==void 0?{content_contains:String(n.content_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"process":{if(typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=1)throw new Error('"pid" is required for type "process" and must be an integer > 1');return{condition:{type:"process",pid:n.pid},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"command":{if(typeof n.command!="string"||n.command.trim()==="")throw new Error('"command" is required for type "command"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"command",command:n.command,...c!==void 0?{cwd:c}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}default:throw new Error(`Unknown type "${r}". Must be one of: url, file, process, command`)}}var ik=async(t,e,n)=>{let r;try{r=YU(t,n)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{condition:o,timeoutMs:s,pollIntervalMs:i,backoff:a}=r;if(o.type==="url"){let u=await gn(o.url);if(!u.allowed)return{content:`SSRF guard blocked: ${u.reason}`,isError:!0}}let l=await ok(u=>{switch(o.type){case"url":return VS(o,u);case"file":return YS(o,u);case"process":return Promise.resolve(QS(o,n?.spawnedPidRegistry));case"command":return Promise.resolve(ZS(o))}},{timeout_ms:s,poll_interval_ms:i,backoff:a,signal:e});return{content:`Wait ${l.status}: ${o.type} condition (${l.elapsed_ms}ms elapsed, ${l.attempts} attempt${l.attempts===1?"":"s"})`+(l.result?` \u2014 ${l.result.detail}`:"")+(l.error?` \u2014 error: ${l.error}`:""),isError:l.status==="failed"}};import{resolve as m$}from"path";import{createHash as QU}from"crypto";import{readFile as ZU}from"fs/promises";function e$(t){return QU("sha256").update(t,"utf8").digest("hex")}function t$(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}async function ak(t,e,n){let r=[],o=new Map;for(let s of t){let i=s.path,a;try{a=ee(i,n,"write",e)}catch(l){r.push({path:i,error:"path_containment",detail:l instanceof Error?l.message:String(l)});continue}try{qn(a,"patch_apply")}catch(l){r.push({path:i,error:"write_denied",detail:l instanceof Error?l.message:String(l)});continue}if(s.edits!==void 0&&s.content!==void 0){r.push({path:i,error:"mutually_exclusive",detail:"`edits` and `content` cannot both be provided for the same file."});continue}if(s.edits===void 0&&s.content===void 0){r.push({path:i,error:"no_change_specified",detail:"At least one of `edits` or `content` must be provided."});continue}let c;try{c=await ZU(a,"utf-8")}catch(l){if(s.expected_hash!==void 0||s.edits!==void 0){r.push({path:i,error:"file_read_failed",detail:l instanceof Error?l.message:String(l)});continue}o.set(a,null),c=""}if(o.has(a)||o.set(a,c),s.expected_hash!==void 0){let l="sha256:";if(!s.expected_hash.startsWith(l)){r.push({path:i,error:"invalid_hash_format",detail:`expected_hash must start with "sha256:". Got: "${s.expected_hash}"`});continue}let d=s.expected_hash.slice(l.length),u=e$(c);if(u!==d){r.push({path:i,error:"hash_mismatch",detail:`File hash mismatch. Expected sha256:${d}, got sha256:${u}. The file may have been modified.`});continue}}if(s.edits!==void 0){let l=c;for(let d=0;d<s.edits.length;d++){let u=s.edits[d],p=t$(l,u.old);if(p===0){r.push({path:i,error:"edit_not_found",detail:`Edit #${d+1}: \`old\` string not found in file.`});break}else if(p>1)r.push({path:i,error:"edit_ambiguous",detail:`Edit #${d+1}: \`old\` string matches ${p} locations. Provide enough context to make it unique.`});else{let f=l.indexOf(u.old);l=l.slice(0,f)+u.new+l.slice(f+u.old.length)}}}}return{valid:r.length===0,errors:r,fileContents:o}}import{createHash as n$,randomBytes as r$}from"crypto";import{writeFile as ck,rename as o$,mkdir as s$,unlink as Bu,chmod as i$,stat as a$}from"fs/promises";import{dirname as dk,join as c$,isAbsolute as l$,resolve as d$}from"path";function lk(t){return n$("sha256").update(t,"utf8").digest("hex")}function u$(t,e,n){let r=Jn(e,n);if(!r)return"";let o=[`--- a/${t}`,`+++ b/${t}`];for(let s of r.hunks){o.push(`@@ -${s.oldStart},${s.oldLines} +${s.newStart},${s.newLines} @@`);for(let i of s.lines)o.push(`${i.kind}${i.text}`)}return o.join(`
|
|
306
|
+
`)}function IU(t){return t.kind==="semantic"?{kind:"semantic",text:_b(t.text),...t.role!==void 0?{role:t.role}:{}}:t.kind==="element_id"?{kind:"element_id",elementId:t.elementId}:{kind:"selector",selectorHash:Tb(t.selector)}}function CU(t={}){return async(e,n,r)=>{if(n.aborted){let u=n.reason;return{content:`browser_act aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0,failureClass:be(n)}}let o=xU(e);if("error"in o)return{content:o.error,isError:!0};let s=IU(o.target),i=b.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a,c,l;try{if(t.getBrowserProvider)a=await t.getBrowserProvider();else{let{getBrowserProvider:u,getLastRoutingDecision:p}=await Promise.resolve().then(()=>(wn(),bn));a=await u();let f=p();f&&(c=f.backend,l=f.reason)}}catch(u){let p=u instanceof Error?u.message:String(u);return Re(p)?{content:Ke(p),isError:!0}:{content:`browser_act failed to get provider: ${p}`,isError:!0}}let d=Date.now();try{let u=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),p=Date.now()-d;if("outcome"in u){if(u.outcome==="ambiguous_target")return ae(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:p}),{content:RU(u.query,u.candidates),isError:!0};if(u.outcome==="blocked_by_policy")return ae(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:p}),{content:`browser_act blocked: ${u.reason}`,isError:!0,failureClass:"policy-refusal"}}return ae(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:u.url,urlAfter:u.url,status:"ok",durationMs:p,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(u){let p=Date.now()-d,f=u instanceof Error?u.message:String(u);ae(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:p,error:{reason:f,recoverable:!1}});let m=Qi(u);return{content:`browser_act failed: ${f}`,isError:!0,...m?{failureClass:m}:{}}}}}var NS=CU();C();var US=["semantic","element_id","selector"],Uu=8e3;function PU(t){if(typeof t.kind!="string"||!US.includes(t.kind))return{error:`browser_screenshot: "target.kind" must be one of ${US.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.kind)})`};let e=t.kind;return e==="semantic"?typeof t.text!="string"||t.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:t.text,...typeof t.role=="string"&&t.role.length>0?{role:t.role}:{}}:e==="element_id"?typeof t.element_id!="string"||t.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:t.element_id}:typeof t.selector!="string"||t.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:t.selector}}function MU(t){if(t!=null&&typeof t!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.target!==void 0){if(!e.target||typeof e.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=PU(e.target);if("error"in o)return o;n=o}let r;if(e.full_page!==void 0){if(typeof e.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=e.full_page}return{target:n,fullPage:r}}function OU(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_screenshot aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=MU(e);if("error"in o)return{content:o.error,isError:!0};let s=b.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(wn(),bn));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return Re(u)?{content:Ke(u),isError:!0}:{content:`browser_screenshot failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),u=Date.now()-l,{dataBase64:p,mediaType:f,...m}=d;return ae(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:u,screenshotPath:m.path}),m.width>Uu||m.height>Uu?{content:JSON.stringify({...m,imageOmitted:`dimensions ${m.width}x${m.height}px exceed the ${Uu}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(m,null,2),image:{mediaType:f,data:p}}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return ae(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_screenshot failed: ${p}`,isError:!0}}}}var $S=OU();C();function DU(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_close aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=b.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let s,i,a;try{if(t.getBrowserProvider)s=await t.getBrowserProvider();else{let{getBrowserProvider:l,getLastRoutingDecision:d}=await Promise.resolve().then(()=>(wn(),bn));s=await l();let u=d();u&&(i=u.backend,a=u.reason)}}catch(l){let d=l instanceof Error?l.message:String(l);return Re(d)?{content:Ke(d),isError:!0}:{content:`browser_close failed to get provider: ${d}`,isError:!0}}let c=Date.now();try{await s.close({sessionId:o});let l=Date.now()-c;return ae(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:l}),{content:"Browser session closed."}}catch(l){let d=Date.now()-c,u=l instanceof Error?l.message:String(l);return ae(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}}),{content:`browser_close failed: ${u}`,isError:!0}}}}var BS=DU();import sk from"node:path";import*as ma from"node:fs/promises";import{execSync as JU}from"node:child_process";import GS from"path";var FU=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","workspace_query","read_witness","search_witness","get_facet","json_query","state_get","state_query"]),LU=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","patch_apply","memory_update","procedure_write","terminal_font_size","config_set","workspace_publish","state_put","state_cas","state_delete","clipboard_write"]),NU=new Set(["Bash","BashOutput","KillBash","bash","test_run","wait_for"]),jS=new Set(["Agent","Task","agent","cancel_background_job","send_message_to_agent"]),HS=new Set(["Skill","skill"]),WS=new Set(["Compose","compose"]),IZ=new Set([...jS,...WS,...HS]),UU=new Set(["WebFetch","WebSearch","send_telegram","web_scrape","web_request"]),$U=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),BU=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),jU=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);function Kt(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}var $u=["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness","workspace_publish","workspace_query","json_query","state_get","state_query",...$e],KS=[...$u,"web_scrape","agent"];function qS(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Kt(FU,t)?"read":Kt(LU,t)?"write":Kt(NU,t)?"shell":Kt(jS,t)?"subagent":Kt(HS,t)?"skill":Kt(WS,t)?"dag":Kt(UU,t)?"web":$U.has(t)?"browser":Kt(BU,t)?"planning":jU.has(t)?"schedule":"other"}var HU=["rm -rf","rm ","sudo","eval ","chmod","chown","git push --force","git push -f","git reset --hard","mkfs","fdisk","diskutil eraseDisk","dd if=","dd of=","| sh","| bash","|sh","|bash","-X POST","-X PUT","-X PATCH","-X DELETE","-XPOST","-XPUT","-XPATCH","-XDELETE","--request POST","--request PUT","--request PATCH","--request DELETE","curl --data","curl -d","curl -F","wget --post-data","wget --post-file","launchctl load","launchctl bootstrap","launchctl submit","launchctl start ","launchctl kickstart","launchctl enable ","systemctl enable ","systemctl start ","systemctl daemon-reload"],WU=["git push","git reset","git commit","git stash drop","git stash clear","npm install","pnpm install","yarn","pip install","apt ","apt-get ","brew install","tee "," > "," >> ","mv ","cp ","mkdir","touch","pnpm build","tsc ","eslint --fix"],KU=["pnpm test","vitest","jest","pytest","cargo test","go test","git status","git log","git diff","git show","ls ","cat ","head ","tail ","find ","grep ","echo ","printf "];function qU(t){return typeof t=="object"&&t!==null&&"command"in t?String(t.command??""):typeof t=="string"?t:""}function GU(t){if(typeof t!="object"||t===null)return"";let e=t;return typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:""}function XS(t){for(let e of HU)if(t.includes(e))return"high";for(let e of WU)if(t.includes(e))return"medium";for(let e of KU)if(t.includes(e))return"safe";return"medium"}function zS(t,e){if(!t)return"safe";let n=He(GS.resolve(e.cwd,t)),r=Td();for(let o of r)if(n===o||n.startsWith(o+"/"))return"high";if(n.includes("/.git/"))return"high";if(e.workspaceRoot!==void 0){let o=He(e.workspaceRoot);if(GS.relative(o,n).startsWith(".."))return"high"}return n.includes("/node_modules/")?"medium":"safe"}var XU=new Set(["delete","drop","remove","destroy","truncate","purge","wipe","write","create","update","insert","upsert","patch","rename","exec","execute","run","eval","send","push","publish","deploy","post","merge","rollback","reset","terminate","provision","scale","disable","charge","refund","revoke"]);function zU(t){return t.split("__").slice(1).join("__").split(/[_-]+/).filter(Boolean)}function JS(t,e,n){let r=t.toLowerCase();if(r==="bash"){let o=qU(e);return XS(o)}if(r==="write_file"||r==="edit_file"){let o=GU(e);return zS(o,n)}if(r==="patch_apply"){let o=typeof e=="object"&&e!==null?e:{},s=Array.isArray(o.changes)?o.changes:[],i="safe";for(let a of s){if(typeof a!="object"||a===null)continue;let c=a.path,d=zS(typeof c=="string"?c:"",n);if(d==="high")return"high";d==="medium"&&(i="medium")}return i}if(qS(t)==="read")return"safe";if(r==="send_telegram")return"medium";if(r.startsWith("mcp__"))return zU(r).some(s=>XU.has(s))?"high":"medium";if(r==="create_schedule"||r==="cancel_schedule")return"high";if(r==="worktree"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.action=="string"?o.action:"";return s==="list"?"safe":s==="remove"&&o.force===!0?"high":"medium"}if(r==="browser_act"||r==="browser_open"||r==="web_scrape")return"medium";if(r==="web_request"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.method=="string"?o.method.toUpperCase():"";return s==="DELETE"?"high":s==="GET"||s==="HEAD"||s==="OPTIONS"?"safe":"medium"}if(r==="wait_for"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.type=="string"?o.type:"";if(s==="command"){let i=typeof o.command=="string"?o.command:"";return XS(i)}return s==="file"||s==="process"?"safe":"medium"}return"safe"}async function VS(t,e){let n=t.method??"HEAD",r;try{r=await jt(globalThis.fetch,t.url,{method:n,signal:e})}catch(a){let c=a instanceof Error?a.message:String(a);return{met:!1,detail:c.startsWith("refusing to")?`SSRF blocked: ${c}`:`fetch error: ${c}`,data:c.startsWith("refusing to")?{blocked:!0}:void 0}}let{status:o}=r,s={status:o};if(!(t.expected_status!==void 0?o===t.expected_status:o>=200&&o<300))return{met:!1,detail:`HTTP ${o} (want ${t.expected_status??"2xx"})`,data:s};if(t.body_contains!==void 0){let a=await r.text().catch(()=>"");if(s.bodyLength=a.length,!a.includes(t.body_contains))return{met:!1,detail:`body does not contain "${t.body_contains}"`,data:s}}else n==="HEAD"&&await r.body?.cancel().catch(()=>{});return{met:!0,detail:`HTTP ${o}`,data:s}}async function YS(t,e){let n;try{let o=t.workspaceRoot?{resolveBase:t.workspaceRoot,cwd:t.workspaceRoot}:void 0;n=ee(t.path,o,"read")}catch(o){return{met:!1,detail:`path rejected: ${o instanceof Error?o.message:String(o)}`,data:{blocked:!0}}}let r;try{let o=await ma.stat(n);r={mtimeMs:o.mtimeMs,size:o.size}}catch{return{met:!1,detail:`file not found: ${t.path}`}}if(t.content_contains!==void 0){let o;try{o=await ma.readFile(n,{encoding:"utf8",signal:e})}catch(s){return{met:!1,detail:`read error: ${s instanceof Error?s.message:String(s)}`,data:r}}if(!o.includes(t.content_contains))return{met:!1,detail:`file exists but does not contain "${t.content_contains}"`,data:r}}return{met:!0,detail:`file exists (${r.size} bytes)`,data:r}}function QS(t,e){if(!Number.isInteger(t.pid)||t.pid<=1)return{met:!1,detail:`pid ${t.pid} is not a valid target (must be integer > 1)`,data:{pid:t.pid,blocked:!0}};if(e!==void 0&&!e.has(t.pid))return{met:!1,detail:`pid ${t.pid} is not a session-owned process (not in spawned PID registry)`,data:{pid:t.pid,blocked:!0}};try{return process.kill(t.pid,0),{met:!1,detail:`pid ${t.pid} is still alive`,data:{pid:t.pid}}}catch(n){let r=n.code;return r==="ESRCH"?{met:!0,detail:`pid ${t.pid} has exited`,data:{pid:t.pid}}:{met:!1,detail:`pid ${t.pid} is alive (${r??"unknown"})`,data:{pid:t.pid}}}}function ZS(t){let e=JS("bash",{command:t.command},{cwd:t.cwd??process.cwd()});if(e!=="safe")return{met:!1,detail:`command blocked by risk classifier (${e} risk): ${t.command}`,data:{command:t.command,blocked:!0}};try{return JU(t.command,{cwd:t.cwd,stdio:"pipe",timeout:3e4}),{met:!0,detail:"command exited 0",data:{command:t.command}}}catch(n){let r=n;if(r.killed===!0&&r.signal==="SIGTERM")return{met:!1,detail:"command timed out (30s limit)",data:{command:t.command,timedOut:!0}};let o=r.status??-1;return{met:!1,detail:`command exited ${o}`,data:{command:t.command,exitCode:o}}}}function Ie(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{e.removeEventListener("abort",r),n()},t);o.unref(),e.addEventListener("abort",r,{once:!0})})}var ek=12e4,tk=6e5,nk=5e3,rk=1e3;function VU(t,e,n){switch(n){case"linear":return t+e*1e3;case"exponential":return Math.min(t*Math.pow(2,e),6e4);default:return t}}async function ok(t,e){let{timeout_ms:n,poll_interval_ms:r,backoff:o,signal:s}=e,i=Date.now()+n,a=0,c;for(;;){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};let l=i-Date.now(),d=AbortSignal.any([s,AbortSignal.timeout(Math.max(1,Math.min(r,l)))]),u;try{u=await t(d)}catch(m){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};if(m instanceof Error&&m.name==="AbortError"){if(Date.now()>=i)return{status:"timed_out",elapsed_ms:Date.now()-(i-n),attempts:a,result:c};continue}let g=m instanceof Error?m.message:String(m);return{status:"failed",elapsed_ms:Date.now()-(i-n),attempts:a,error:g}}if(c=u,a++,u.met)return{status:"succeeded",elapsed_ms:Date.now()-(i-n),attempts:a,result:u};let p=Date.now();if(p>=i)return{status:"timed_out",elapsed_ms:p-(i-n),attempts:a,result:c};let f=Math.min(VU(r,a-1,o),i-p);await Ie(f,s)}}function YU(t,e){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let n=t,r=n.type;if(typeof r!="string")throw new Error('"type" is required and must be a string');let o=ek;if(n.timeout_ms!==void 0){if(typeof n.timeout_ms!="number"||!Number.isFinite(n.timeout_ms))throw new Error('"timeout_ms" must be a finite number');o=Math.min(Math.max(0,n.timeout_ms),tk)}let s=nk;if(n.poll_interval_ms!==void 0){if(typeof n.poll_interval_ms!="number"||!Number.isFinite(n.poll_interval_ms))throw new Error('"poll_interval_ms" must be a finite number');s=Math.max(rk,n.poll_interval_ms)}let i=["none","linear","exponential"],a="none";if(n.backoff!==void 0){if(!i.includes(n.backoff))throw new Error(`"backoff" must be one of: ${i.join(", ")}`);a=n.backoff}switch(r){case"url":{if(typeof n.url!="string"||n.url.trim()==="")throw new Error('"url" is required for type "url"');let c=n.body_contains!==void 0,l=n.method??(c?"GET":"HEAD");if(l!=="HEAD"&&l!=="GET")throw new Error('"method" must be "HEAD" or "GET"');return{condition:{type:"url",url:n.url,method:l,...n.expected_status!==void 0?{expected_status:Number(n.expected_status)}:{},...c?{body_contains:String(n.body_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"file":{if(typeof n.path!="string"||n.path.trim()==="")throw new Error('"path" is required for type "file"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"file",path:c!==void 0&&!sk.isAbsolute(n.path)?sk.resolve(c,n.path):n.path,workspaceRoot:c,...n.content_contains!==void 0?{content_contains:String(n.content_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"process":{if(typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=1)throw new Error('"pid" is required for type "process" and must be an integer > 1');return{condition:{type:"process",pid:n.pid},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"command":{if(typeof n.command!="string"||n.command.trim()==="")throw new Error('"command" is required for type "command"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"command",command:n.command,...c!==void 0?{cwd:c}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}default:throw new Error(`Unknown type "${r}". Must be one of: url, file, process, command`)}}var ik=async(t,e,n)=>{let r;try{r=YU(t,n)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{condition:o,timeoutMs:s,pollIntervalMs:i,backoff:a}=r;if(o.type==="url"){let u=await gn(o.url);if(!u.allowed)return{content:`SSRF guard blocked: ${u.reason}`,isError:!0}}let l=await ok(u=>{switch(o.type){case"url":return VS(o,u);case"file":return YS(o,u);case"process":return Promise.resolve(QS(o,n?.spawnedPidRegistry));case"command":return Promise.resolve(ZS(o))}},{timeout_ms:s,poll_interval_ms:i,backoff:a,signal:e});return{content:`Wait ${l.status}: ${o.type} condition (${l.elapsed_ms}ms elapsed, ${l.attempts} attempt${l.attempts===1?"":"s"})`+(l.result?` \u2014 ${l.result.detail}`:"")+(l.error?` \u2014 error: ${l.error}`:""),isError:l.status==="failed"}};import{resolve as m$}from"path";import{createHash as QU}from"crypto";import{readFile as ZU}from"fs/promises";function e$(t){return QU("sha256").update(t,"utf8").digest("hex")}function t$(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}async function ak(t,e,n){let r=[],o=new Map;for(let s of t){let i=s.path,a;try{a=ee(i,n,"write",e)}catch(l){r.push({path:i,error:"path_containment",detail:l instanceof Error?l.message:String(l)});continue}try{qn(a,"patch_apply")}catch(l){r.push({path:i,error:"write_denied",detail:l instanceof Error?l.message:String(l)});continue}if(s.edits!==void 0&&s.content!==void 0){r.push({path:i,error:"mutually_exclusive",detail:"`edits` and `content` cannot both be provided for the same file."});continue}if(s.edits===void 0&&s.content===void 0){r.push({path:i,error:"no_change_specified",detail:"At least one of `edits` or `content` must be provided."});continue}let c;try{c=await ZU(a,"utf-8")}catch(l){if(s.expected_hash!==void 0||s.edits!==void 0){r.push({path:i,error:"file_read_failed",detail:l instanceof Error?l.message:String(l)});continue}o.set(a,null),c=""}if(o.has(a)||o.set(a,c),s.expected_hash!==void 0){let l="sha256:";if(!s.expected_hash.startsWith(l)){r.push({path:i,error:"invalid_hash_format",detail:`expected_hash must start with "sha256:". Got: "${s.expected_hash}"`});continue}let d=s.expected_hash.slice(l.length),u=e$(c);if(u!==d){r.push({path:i,error:"hash_mismatch",detail:`File hash mismatch. Expected sha256:${d}, got sha256:${u}. The file may have been modified.`});continue}}if(s.edits!==void 0){let l=c;for(let d=0;d<s.edits.length;d++){let u=s.edits[d],p=t$(l,u.old);if(p===0){r.push({path:i,error:"edit_not_found",detail:`Edit #${d+1}: \`old\` string not found in file.`});break}else if(p>1)r.push({path:i,error:"edit_ambiguous",detail:`Edit #${d+1}: \`old\` string matches ${p} locations. Provide enough context to make it unique.`});else{let f=l.indexOf(u.old);l=l.slice(0,f)+u.new+l.slice(f+u.old.length)}}}}return{valid:r.length===0,errors:r,fileContents:o}}import{createHash as n$,randomBytes as r$}from"crypto";import{writeFile as ck,rename as o$,mkdir as s$,unlink as Bu,chmod as i$,stat as a$}from"fs/promises";import{dirname as dk,join as c$,isAbsolute as l$,resolve as d$}from"path";function lk(t){return n$("sha256").update(t,"utf8").digest("hex")}function u$(t,e,n){let r=Jn(e,n);if(!r)return{text:"",payload:null};let o=[`--- a/${t}`,`+++ b/${t}`];for(let s of r.hunks){o.push(`@@ -${s.oldStart},${s.oldLines} +${s.newStart},${s.newLines} @@`);for(let i of s.lines)o.push(`${i.kind}${i.text}`)}return{text:o.join(`
|
|
307
307
|
`)+`
|
|
308
|
-
|
|
309
|
-
`),i=o.map(
|
|
308
|
+
`,payload:r}}function p$(t,e){let n=t;for(let r of e){let o=n.indexOf(r.old);if(o===-1)throw new Error("patch_apply engine: edit old-string not found at apply time (validation may have passed a stale snapshot).");n=n.slice(0,o)+r.new+n.slice(o+r.old.length)}return n}function f$(t){let e=r$(8).toString("hex");return c$(dk(t),`.patch-tmp-${e}`)}async function uk(t,e,n,r){let o=[];for(let g of t){let h=l$(g.path)?g.path:d$(n,g.path),y=e.get(h),w=y===null,S=y??"",v;if(g.content!==void 0)v=g.content;else if(g.edits!==void 0)v=p$(S,g.edits);else throw new Error(`patch_apply engine: change for ${g.path} has neither content nor edits.`);let _=u$(g.path,S,v);o.push({resolvedPath:h,originalContent:S,newContent:v,diffBlock:_.text,diffPayload:_.payload,filePath:g.path,isNewFile:w})}let s=o.map(g=>g.diffBlock).filter(Boolean).join(`
|
|
309
|
+
`),i=[],a=0,c=0;for(let g of o)if(g.diffPayload){for(let h of g.diffPayload.hunks)i.push({...h,filePath:g.filePath});a+=g.diffPayload.addedLines,c+=g.diffPayload.removedLines}let l=i.length>0?{hunks:i,addedLines:a,removedLines:c}:void 0,d=o.map(g=>({path:g.resolvedPath,before_hash:`sha256:${lk(g.originalContent)}`,after_hash:`sha256:${lk(g.newContent)}`}));if(r)return{status:"dry_run",diff:s,structuredDiff:l,files_changed:d,errors:[]};let u=[],p=[];for(let g of o){let h=f$(g.resolvedPath);try{let y;if(!g.isNewFile)try{y=(await a$(g.resolvedPath)).mode}catch{}await s$(dk(g.resolvedPath),{recursive:!0}),await ck(h,g.newContent,"utf-8"),y!==void 0&&await i$(h,y),u.push({tempPath:h,targetPath:g.resolvedPath,originalMode:y})}catch(y){p.push({path:g.resolvedPath,error:"temp_write_failed",detail:y instanceof Error?y.message:String(y)})}}if(p.length>0){for(let g of u)try{await Bu(g.tempPath)}catch{}return{status:"partial_failure",diff:s,files_changed:d,errors:p}}let f=[],m=[];for(let g=0;g<u.length;g++){let h=u[g];try{await o$(h.tempPath,h.targetPath),m.push({targetPath:h.targetPath,originalContent:o[g].originalContent,isNewFile:o[g].isNewFile})}catch(y){f.push({path:h.targetPath,error:"rename_failed",detail:y instanceof Error?y.message:String(y)})}}if(f.length>0){for(let g of m)try{g.isNewFile?await Bu(g.targetPath):await ck(g.targetPath,g.originalContent,"utf-8")}catch{}for(let g of u)try{await Bu(g.tempPath)}catch{}return{status:"partial_failure",diff:s,files_changed:d,errors:f}}return{status:"applied",diff:s,structuredDiff:l,files_changed:d,errors:[]}}function g$(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object.");let e=t;if(!Array.isArray(e.changes))throw new Error('Input must have a "changes" field of type array.');let n=[];for(let o=0;o<e.changes.length;o++){let s=e.changes[o];if(typeof s!="object"||s===null)throw new Error(`changes[${o}] must be an object.`);let i=s;if(typeof i.path!="string"||i.path.trim()==="")throw new Error(`changes[${o}].path must be a non-empty string.`);let a={path:i.path};if(i.expected_hash!==void 0){if(typeof i.expected_hash!="string")throw new Error(`changes[${o}].expected_hash must be a string.`);a.expected_hash=i.expected_hash}if(i.content!==void 0){if(typeof i.content!="string")throw new Error(`changes[${o}].content must be a string.`);a.content=i.content}if(i.edits!==void 0){if(!Array.isArray(i.edits))throw new Error(`changes[${o}].edits must be an array.`);let c=[];for(let l=0;l<i.edits.length;l++){let d=i.edits[l];if(typeof d!="object"||d===null)throw new Error(`changes[${o}].edits[${l}] must be an object.`);let u=d;if(typeof u.old!="string")throw new Error(`changes[${o}].edits[${l}].old must be a string.`);if(typeof u.new!="string")throw new Error(`changes[${o}].edits[${l}].new must be a string.`);c.push({old:u.old,new:u.new})}a.edits=c}n.push(a)}let r=!1;if(e.dry_run!==void 0){if(typeof e.dry_run!="boolean")throw new Error("dry_run must be a boolean.");r=e.dry_run}return{changes:n,dry_run:r}}function ju(t){return async(e,n,r)=>{let o=r?.resolveBase??r?.cwd??t??m$(process.cwd()),s;try{s=g$(e)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{changes:i,dry_run:a}=s;if(i.length===0)return{content:JSON.stringify({status:"applied",diff:"",files_changed:[],errors:[]},null,2),isError:!1};let c=await ak(i,o,r);if(!c.valid){let u={status:"validation_failed",diff:"",files_changed:[],errors:c.errors};return{content:JSON.stringify(u,null,2),isError:!0}}let l=await uk(i,c.fileContents,o,a),d=l.status==="validation_failed"||l.status==="partial_failure";return{content:JSON.stringify({status:l.status,diff:l.diff,files_changed:l.files_changed,errors:l.errors},null,2),isError:d,...l.structuredDiff?{render:{diff:l.structuredDiff}}:{}}}}var pk=ju();import{spawn as I$}from"child_process";import Hu from"fs";import Me from"path";function at(t){try{return Hu.accessSync(t),!0}catch{return!1}}function Wu(t){try{return Hu.readFileSync(t,"utf8")}catch{return null}}function h$(t){return at(Me.join(t,"pnpm-lock.yaml"))?"pnpm":at(Me.join(t,"yarn.lock"))?"yarn":at(Me.join(t,"bun.lockb"))?"bun":"npm"}function y$(t){return/\bvitest\b/.test(t)?"vitest":/\bjest\b/.test(t)?"jest":/\bmocha\b/.test(t)?"mocha":null}function b$(t){let e=Me.join(t,"package.json"),n=Wu(e);if(!n)return null;let r;try{r=JSON.parse(n)}catch{return null}let o=r.scripts;if(!o||typeof o!="object")return null;let s=h$(t);for(let i of["test:unit","test:integration","test"]){let a=o[i];if(typeof a!="string"||!a.trim())continue;let c=y$(a)??"node-generic",l=`${s} run ${i}`;return{runner:c,command:l,args:[s,"run",i]}}return null}function w$(t){let e=Me.join(t,"pyproject.toml"),n=Wu(e);return n?/\[tool\.pytest/.test(n)?{runner:"pytest",command:"pytest",args:["pytest"]}:at(Me.join(t,"pytest.ini"))||at(Me.join(t,"setup.cfg"))?{runner:"pytest",command:"pytest",args:["pytest"]}:null:null}function S$(t){return at(Me.join(t,"Cargo.toml"))?{runner:"cargo",command:"cargo test",args:["cargo","test"]}:null}function k$(t){let n=(()=>{try{return Hu.readdirSync(t)}catch{return[]}})().some(r=>r.endsWith("_test.go"));return(n||at(Me.join(t,"go.mod")))&&(n||at(Me.join(t,"go.mod")))?{runner:"go-test",command:"go test ./...",args:["go","test","./..."]}:null}function v$(t){return at(Me.join(t,"Gemfile"))&&at(Me.join(t,"spec"))?{runner:"rspec",command:"bundle exec rspec",args:["bundle","exec","rspec"]}:null}function T$(t){let e=Wu(Me.join(t,"Makefile"));return e&&/^test:/m.test(e)?{runner:"node-generic",command:"make test",args:["make","test"]}:null}function fk(t){return b$(t)??w$(t)??S$(t)??k$(t)??v$(t)??T$(t)??null}function _$(t){let e=[],n=/^\s*●\s+(.+?)\s*$/gm,r=/^FAIL\s+(.+\.(?:test|spec)\.[jt]sx?)\s*$/gm,o=t.split(`
|
|
310
310
|
`),s=0;for(;s<o.length;){let i=o[s],a=r.exec(i);if(a){let l=a[1]?.trim(),d=s+1;for(;d<o.length;){let u=o[d],p=/^\s+[×✕✗x]\s+(.+)$/.exec(u);if(p){let f=p[1]?.trim()??"unknown",m="",g=d+1;for(;g<o.length&&/^\s+/.test(o[g]);){let h=o[g].trim();h&&!h.startsWith("at ")&&(m=m||h),g++}e.push({name:f,file:l,message:m||"Test failed"})}else if(u.trim()===""&&d>s+2)break;d++}r.lastIndex=0,s++;continue}let c=n.exec(i);if(c){let l=c[1]?.trim()??"unknown",d="",u="",p,f,m=s+1;for(;m<o.length;){let g=o[m];if(/^\s*●\s+/.test(g))break;if(!d&&/^\s+(?:expect|assert|Error|AssertionError)/.test(g)&&(d=g.trim()),!p){let h=/at\s+\S+\s+\((.+?):(\d+):\d+\)/.exec(g);h&&(p=h[1]?.trim(),f=parseInt(h[2],10))}u+=g+`
|
|
311
311
|
`,m++}e.push({name:l,...p?{file:p}:{},...f!==void 0?{line:f}:{},message:d||"Test failed",...u.trim()?{stack:u.trim()}:{}}),n.lastIndex=0,s=m;continue}n.lastIndex=0,r.lastIndex=0,s++}return e}function E$(t){let e=[],n=/^FAILED\s+(.+?)::([^\s-]+)\s*(?:-\s*(.+))?$/gm,r;for(;(r=n.exec(t))!==null;){let o=r[1]?.trim(),s=r[2]?.trim()??"unknown",i=r[3]?.trim()??"Test failed";e.push({name:s,...o?{file:o}:{},message:i})}return e}function A$(t){let e=[],n=/^test\s+(\S+)\s+\.\.\.\s+FAILED$/gm,r;for(;(r=n.exec(t))!==null;)e.push({name:r[1]??"unknown",message:"Test failed"});let o=/^-{4}\s+(\S+)\s+stdout\s+-{4}$([\s\S]*?)(?=^-{4}|\z)/gm;for(;(r=o.exec(t))!==null;){let s=r[1]??"unknown",i=r[2]?.trim()??"",a=e.find(c=>c.name===s);a&&i&&(a.message=i.split(`
|
|
312
312
|
`)[0]?.trim()??a.message,a.stack=i)}return e}function x$(t){let e=[],n=/^---\s+FAIL:\s+(\S+)\s+\([\d.]+s\)/gm,r;for(;(r=n.exec(t))!==null;)e.push({name:r[1]??"unknown",message:"Test failed"});return e}function R$(t){let e=[],n=/^\s+\d+\)\s+(.+?)\s*$/gm,r=t.split(`
|
|
@@ -314,18 +314,18 @@ ${e}`}C();import{BlockList as WD,isIP as Vd}from"node:net";import{lookup as KD}f
|
|
|
314
314
|
|
|
315
315
|
... [${t.length-qu} bytes omitted] ...
|
|
316
316
|
|
|
317
|
-
`+t.slice(t.length-e)}function O$(t,e,n,r){return new Promise(o=>{let s=Date.now(),[i,...a]=t,c=!1;function l(w){c||(c=!0,clearTimeout(h),r.removeEventListener("abort",y),o(w))}let d=I$(i,a,{shell:!1,detached:!0,stdio:["ignore","pipe","pipe"],...e!==void 0?{cwd:e}:{}});d.unref();let u="",p="",f=0,m=!1;function g(){if(m||c||f<Ku)return;m=!0,d.pid!==void 0&&fn(d.pid);let w=Ae((u+p).trimEnd());l({output:w,exitCode:null,timedOut:!1,durationMs:Date.now()-s})}d.stdout.on("data",w=>{let
|
|
317
|
+
`+t.slice(t.length-e)}function O$(t,e,n,r){return new Promise(o=>{let s=Date.now(),[i,...a]=t,c=!1;function l(w){c||(c=!0,clearTimeout(h),r.removeEventListener("abort",y),o(w))}let d=I$(i,a,{shell:!1,detached:!0,stdio:["ignore","pipe","pipe"],...e!==void 0?{cwd:e}:{}});d.unref();let u="",p="",f=0,m=!1;function g(){if(m||c||f<Ku)return;m=!0,d.pid!==void 0&&fn(d.pid);let w=Ae((u+p).trimEnd());l({output:w,exitCode:null,timedOut:!1,durationMs:Date.now()-s})}d.stdout.on("data",w=>{let S=Ku-f,v=w.length<=S?w:w.subarray(0,Math.max(0,S));f+=v.length,u+=v.toString("utf8"),g()}),d.stderr.on("data",w=>{let S=Ku-f,v=w.length<=S?w:w.subarray(0,Math.max(0,S));f+=v.length,p+=v.toString("utf8"),g()});let h=setTimeout(()=>{d.pid!==void 0&&fn(d.pid);let w=Ae((u+p).trimEnd());l({output:w,exitCode:null,timedOut:!0,durationMs:Date.now()-s})},n),y=()=>{d.pid!==void 0&&fn(d.pid),l({output:"",exitCode:null,timedOut:!1,durationMs:Date.now()-s})};if(r.addEventListener("abort",y),r.aborted){y();return}d.on("close",w=>{if(c)return;let S=Ae((u+p).trimEnd());l({output:S,exitCode:w,timedOut:!1,durationMs:Date.now()-s})}),d.on("error",w=>{l({output:`spawn error: ${w.message}`,exitCode:null,timedOut:!1,durationMs:Date.now()-s})})})}var hk=async(t,e,n)=>{if(e.aborted)return{content:"test_run aborted",isError:!0};let r=P$(t),o=n?.resolveBase??n?.cwd,s=fk(o??process.cwd());if(!s)return{content:"No test command found. Checked: package.json scripts, pyproject.toml [tool.pytest], Cargo.toml, go.mod/*_test.go, Gemfile+spec/, Makefile test: target.",isError:!0};let i=M$(s.args,s.runner,r.file,r.name,r.coverage),a=i.join(" "),{output:c,exitCode:l,timedOut:d,durationMs:u}=await O$(i,o,r.timeout_ms??Gu,e);if(e.aborted)return{content:"test_run aborted",isError:!0};if(d)return{content:`Test run timed out after ${r.timeout_ms??Gu}ms.
|
|
318
318
|
|
|
319
|
-
${gk(c)}`,isError:!0};let p=go(c),f=p?.runner??s.runner,m=p?.passed??0,g=p?.failed??0,h=p?.skipped,y=mk(c,f),w=g===0&&l===0?"\u2705":"\u274C",
|
|
319
|
+
${gk(c)}`,isError:!0};let p=go(c),f=p?.runner??s.runner,m=p?.passed??0,g=p?.failed??0,h=p?.skipped,y=mk(c,f),w=g===0&&l===0?"\u2705":"\u274C",S=h!==void 0?` | ${h} skipped`:"",v=`${w} ${f}: ${m} passed | ${g} failed${S} \u2014 ${u}ms
|
|
320
320
|
Command: ${a}
|
|
321
321
|
`+(y.length>0?`
|
|
322
322
|
Failed tests:
|
|
323
323
|
${y.map(E=>` \u2022 ${E.name}${E.file?` (${E.file}${E.line!==void 0?`:${E.line}`:""})`:""}: ${E.message}`).join(`
|
|
324
324
|
`)}`:"")+`
|
|
325
325
|
|
|
326
|
-
${gk(c)}`,_={runner:f,command:a,passed:m,failed:g,...h!==void 0?{skipped:h}:{},duration_ms:u,failures:y,raw_output:c};return{content:v,isError:l!==0&&l!==null,testResult:p??void 0,..._!==void 0?{testRunResult:_}:{}}};import{statSync as rB}from"node:fs";import{join as oB}from"node:path";import{z as x}from"zod";var Lo=3,D$=x.object({toolName:x.string(),toolUseId:x.string().optional(),input:x.string().optional(),inputRaw:x.string().optional(),result:x.string().optional(),isError:x.boolean().optional()}).passthrough(),F$=x.object({user:x.string().default(""),assistant:x.string().default(""),timestamp:x.number().optional(),toolEvents:x.array(D$).optional()}).passthrough(),Xu=x.object({sessionId:x.string().optional(),name:x.string().optional(),source:x.enum(["cli","telegram","web"]).optional(),telegramChatId:x.number().optional(),model:x.string(),startedAt:x.number(),savedAt:x.number(),totalTurns:x.number(),totalCostUsd:x.number().optional(),totalTokens:x.number().optional(),totalDurationMs:x.number().optional(),turns:x.array(F$).default([]),forkedFrom:x.string().optional(),forkedAt:x.number().optional()}).passthrough(),yk=x.enum(["fully_achieved","partially_achieved","not_achieved","aborted"]),bk=x.enum(["not_persisted","persisted","unknown"]),wk=x.object({tool:x.string(),label:x.string().optional()}),Sk=x.object({files_written:x.number().int(),files_edited:x.number().int(),bash_commands:x.number().int(),commits:x.number().int(),mutated:x.boolean()}),kk=x.object({input:x.number().optional(),output:x.number().optional(),cache_read:x.number().optional(),cache_creation:x.number().optional(),cost_usd:x.number()}),No=x.object({facet_version:x.number().int(),session_id:x.string(),source:x.enum(["cli","telegram","web","unknown"]),model:x.string(),derived_at:x.string(),derived_from:x.literal("afk-session"),source_session_path:x.string(),source_session_mtime_ms:x.number(),subagent_persistence:bk,start_time:x.string(),end_time:x.string(),duration_minutes:x.number(),underlying_goal:x.string(),first_prompt:x.string(),goal_categories:x.record(x.string(),x.number()),session_type:x.string(),brief_summary:x.string(),total_turns:x.number().int(),user_message_count:x.number().int(),assistant_message_count:x.number().int(),tool_counts:x.record(x.string(),x.number()),commands:x.array(x.string()),skills:x.array(x.string()),subagents:x.array(wk),tool_errors:x.number().int(),tool_error_categories:x.record(x.string(),x.number()),friction_counts:x.record(x.string(),x.number()),friction_detail:x.string(),outcome:yk,primary_success:x.string(),world_changes:Sk,token_breakdown:kk.optional(),decisions:x.array(x.string()),evidence_pointers:x.array(x.string())}).passthrough();import{basename as L$}from"path";var N$=new Set(["agent","compose","skill"]),U$=new Set(["read_file","write_file","edit_file"]),vk=1e3,$$=240,B$=50,j$=/\bgit\s+commit(?![\w-])/,Tk=/^\s*\/([a-zA-Z][\w-]*)/;function H$(t){if(t)try{let e=JSON.parse(t);return e&&typeof e=="object"?e:void 0}catch{return}}function ga(t){return typeof t=="string"?t:void 0}function ha(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function W$(t){return t.replace(/[-_]+/g," ").trim()}function K$(t,e){return Tk.test(t)?"slash_command":e==="telegram"?"chat":"task"}function q$(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 nr(t,e={}){let n=t.turns??[],r=q$(n.flatMap(O=>O.toolEvents??[])),o={},s={},i=[],a=[],c=[],l=0,d=0,u=0,p=0,f=0;for(let O of r){let U=O.toolName;o[U]=(o[U]??0)+1,O.isError===!0&&(l+=1,s[U]=(s[U]??0)+1);let q=H$(O.inputRaw??O.input);if(U==="write_file"&&(d+=1),U==="edit_file"&&(u+=1),U==="bash"){p+=1;let H=ga(q?.command)??O.input;H&&j$.test(H)&&(f+=1)}if(U$.has(U)){let H=ga(q?.file_path);H&&!c.includes(H)&&c.length<B$&&c.push(H)}if(N$.has(U)){let H;U==="skill"?(H=ga(q?.name),H&&!a.includes(H)&&a.push(H)):U==="agent"?H=ga(q?.id_prefix):H="compose",i.push(H?{tool:U,label:H}:{tool:U})}}let m=n[0]?.user??"",g=t.source??"cli",h=K$(m,g),y=[];for(let O of n){let q=Tk.exec(O.user??"")?.[1];q&&!y.includes(q)&&y.push(q)}let w=n.filter(O=>(O.user??"").trim().length>0).length,
|
|
327
|
-
`,"utf8"),z$(n,t)}function nB(t,e){return t.facet_version===Lo&&t.source_session_mtime_ms===e}function vn(t,e={}){let n=e.sessionsDir??re(),r=e.cacheDir??gm(),o=Ak(t,n);if(!ya(o))return;let s=J$(o).mtimeMs,i=Z$(t,r);if(!e.force){let l=eB(i);if(l&&nB(l,s))return l}let a=Uo(t,n);if(!a)return;let c=nr(a,{sourceSessionPath:o,sourceSessionMtimeMs:s});return tB(i,c),c}function rr(t={}){let e=t.sessionsDir??re();return ya(e)?X$(e).filter(n=>n.endsWith(".json")).map(n=>Y$(n,".json")):[]}M();var xk=async(t,e)=>{let n=t??{},r=typeof n.session=="string"?n.session:"latest",o=Array.isArray(n.fields)?n.fields:null,s;if(r==="latest"){let d=rr();if(d.length>0){let u=re(),p;for(let f of d)try{let m=rB(oB(u,`${f}.json`)).mtimeMs;(!p||m>p.mtimeMs)&&(p={id:f,mtimeMs:m})}catch{}s=p?.id}}else s=fa(r)?.sidecarId;if(!s)return{content:`Session not found: ${r}`,isError:!0};let i=vn(s);if(!i)return{content:`Session not found: ${r}`,isError:!0};let a=i,c={},l=new Set($g);if(o&&o.length>0)for(let d of o)c[d]=a[d];else for(let[d,u]of Object.entries(a))l.has(d)||(c[d]=u);return{content:JSON.stringify(c,null,2)}};import{promises as Rk}from"fs";var sB=100,iB=50*1024,Ik=10*1024*1024;function zu(t){let e=t.trim();if(e==="keys")return{kind:"keys"};if(e==="length")return{kind:"length"};if(e===".")return{kind:"identity"};let n=aB(e);if(n!==-1){let o=zu(e.slice(0,n).trim()),s=zu(e.slice(n+1).trim());return{kind:"pipe",left:o,right:s}}let r=e.match(/^\.\[(.+)\]$/);if(r){let o=(r[1]??"").trim(),s=o.match(/^(-?\d+)\s*:\s*(-?\d+)$/);if(s)return{kind:"slice",from:Number(s[1]??"0"),to:Number(s[2]??"0")};if(/^-?\d+$/.test(o))return{kind:"index",idx:Number(o)};throw new Error(`Unrecognised bracket expression: .[${o}]`)}if(e===".[]")return{kind:"iter"};if(e.startsWith(".")){let o=e.slice(1);if(o.length===0)return{kind:"identity"};if(/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(o)){let s=o.split("."),i=s[0]??"";if(s.length===1)return{kind:"field",name:i};let a={kind:"field",name:i};for(let c=1;c<s.length;c++)a={kind:"pipe",left:a,right:{kind:"field",name:s[c]??""}};return a}}throw new Error(`Unrecognised query expression: "${e}". Supported: . .field .field.nested .[N] .[N:M] .[] keys length .[] | .field`)}function aB(t){let e=0;for(let n=0;n<t.length;n++){let r=t[n];if(r==="["||r==="(")e++;else if(r==="]"||r===")")e--;else if(r==="|"&&e===0)return n}return-1}function cB(t){return t.kind==="iter"||t.kind==="pipe"&&t.left.kind==="iter"}function Ju(t,e){switch(t.kind){case"identity":return[e];case"keys":{if(e===null||typeof e!="object")throw new Error(`keys requires an object or array, got ${or(e)}`);return Array.isArray(e)?[e.map((n,r)=>r)]:[Object.keys(e)]}case"length":{if(Array.isArray(e))return[e.length];if(e!==null&&typeof e=="object")return[Object.keys(e).length];if(typeof e=="string")return[e.length];if(e===null)return[0];throw new Error(`length not defined for ${or(e)}`)}case"field":{if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Cannot access field ".${t.name}" on ${or(e)}`);return[e[t.name]]}case"index":{if(!Array.isArray(e))throw new Error(`Cannot index non-array with .[${t.idx}]`);let n=e.length,r=t.idx<0?n+t.idx:t.idx;return[e[r]]}case"slice":{if(!Array.isArray(e)&&typeof e!="string")throw new Error(`Cannot slice ${or(e)} \u2014 expected array or string`);return Array.isArray(e)?[e.slice(t.from,t.to)]:[e.slice(t.from,t.to)]}case"iter":{if(!Array.isArray(e))throw new Error(`Cannot iterate (.[] ) over ${or(e)} \u2014 expected array`);return e}case"pipe":{let n=Ju(t.left,e),r=[];for(let o of n){let s=Ju(t.right,o);r.push(...s)}return r}}}function or(t){return t===null?"null":Array.isArray(t)?"array":typeof t}async function lB(t,e,n,r){if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t,s=o.path,i=o.query,a=o.max_results??sB,c=o.max_bytes??iB;if(typeof s!="string"||s.length===0)return{content:"Invalid input: path must be a non-empty string",isError:!0};if(typeof i!="string"||i.length===0)return{content:"Invalid input: query must be a non-empty string",isError:!0};if(typeof a!="number"||a<1)return{content:"Invalid input: max_results must be a positive number",isError:!0};if(typeof c!="number"||c<1)return{content:"Invalid input: max_bytes must be a positive number",isError:!0};let l=Math.floor(a),d=Math.floor(c),u;try{u=ee(s,n,"read",r)}catch(T){return{content:T instanceof Error?T.message:String(T),isError:!0}}let p;try{p=zu(i)}catch(T){return{content:`Invalid query: ${T instanceof Error?T.message:String(T)}`,isError:!0}}let f;try{let T=await Rk.stat(u);if(T.size>Ik)return{content:`File too large (${T.size} bytes). json_query supports files up to ${Ik} bytes.`,isError:!0};f=await Rk.readFile(u)}catch(T){let I=We(T,u,"File");return I||{content:`Error reading file: ${T instanceof Error?T.message:String(T)}`,isError:!0}}let m=f.length;if(m===0)return{content:JSON.stringify({result:null,type:"null",truncated:!1,source_size:0})};let g;try{g=JSON.parse(f.toString("utf-8"))}catch(T){return{content:`JSON parse error: ${T instanceof SyntaxError?T.message:String(T)}`,isError:!0}}let h;try{h=Ju(p,g)}catch(T){return{content:`Query error: ${T instanceof Error?T.message:String(T)}`,isError:!0}}let y=cB(p),w=!1,
|
|
328
|
-
\u2026 [truncated]`):_=
|
|
326
|
+
${gk(c)}`,_={runner:f,command:a,passed:m,failed:g,...h!==void 0?{skipped:h}:{},duration_ms:u,failures:y,raw_output:c};return{content:v,isError:l!==0&&l!==null,testResult:p??void 0,..._!==void 0?{testRunResult:_}:{}}};import{statSync as rB}from"node:fs";import{join as oB}from"node:path";import{z as x}from"zod";var Lo=3,D$=x.object({toolName:x.string(),toolUseId:x.string().optional(),input:x.string().optional(),inputRaw:x.string().optional(),result:x.string().optional(),isError:x.boolean().optional()}).passthrough(),F$=x.object({user:x.string().default(""),assistant:x.string().default(""),timestamp:x.number().optional(),toolEvents:x.array(D$).optional()}).passthrough(),Xu=x.object({sessionId:x.string().optional(),name:x.string().optional(),source:x.enum(["cli","telegram","web"]).optional(),telegramChatId:x.number().optional(),model:x.string(),startedAt:x.number(),savedAt:x.number(),totalTurns:x.number(),totalCostUsd:x.number().optional(),totalTokens:x.number().optional(),totalDurationMs:x.number().optional(),turns:x.array(F$).default([]),forkedFrom:x.string().optional(),forkedAt:x.number().optional()}).passthrough(),yk=x.enum(["fully_achieved","partially_achieved","not_achieved","aborted"]),bk=x.enum(["not_persisted","persisted","unknown"]),wk=x.object({tool:x.string(),label:x.string().optional()}),Sk=x.object({files_written:x.number().int(),files_edited:x.number().int(),bash_commands:x.number().int(),commits:x.number().int(),mutated:x.boolean()}),kk=x.object({input:x.number().optional(),output:x.number().optional(),cache_read:x.number().optional(),cache_creation:x.number().optional(),cost_usd:x.number()}),No=x.object({facet_version:x.number().int(),session_id:x.string(),source:x.enum(["cli","telegram","web","unknown"]),model:x.string(),derived_at:x.string(),derived_from:x.literal("afk-session"),source_session_path:x.string(),source_session_mtime_ms:x.number(),subagent_persistence:bk,start_time:x.string(),end_time:x.string(),duration_minutes:x.number(),underlying_goal:x.string(),first_prompt:x.string(),goal_categories:x.record(x.string(),x.number()),session_type:x.string(),brief_summary:x.string(),total_turns:x.number().int(),user_message_count:x.number().int(),assistant_message_count:x.number().int(),tool_counts:x.record(x.string(),x.number()),commands:x.array(x.string()),skills:x.array(x.string()),subagents:x.array(wk),tool_errors:x.number().int(),tool_error_categories:x.record(x.string(),x.number()),friction_counts:x.record(x.string(),x.number()),friction_detail:x.string(),outcome:yk,primary_success:x.string(),world_changes:Sk,token_breakdown:kk.optional(),decisions:x.array(x.string()),evidence_pointers:x.array(x.string())}).passthrough();import{basename as L$}from"path";var N$=new Set(["agent","compose","skill"]),U$=new Set(["read_file","write_file","edit_file"]),vk=1e3,$$=240,B$=50,j$=/\bgit\s+commit(?![\w-])/,Tk=/^\s*\/([a-zA-Z][\w-]*)/;function H$(t){if(t)try{let e=JSON.parse(t);return e&&typeof e=="object"?e:void 0}catch{return}}function ga(t){return typeof t=="string"?t:void 0}function ha(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}function W$(t){return t.replace(/[-_]+/g," ").trim()}function K$(t,e){return Tk.test(t)?"slash_command":e==="telegram"?"chat":"task"}function q$(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 nr(t,e={}){let n=t.turns??[],r=q$(n.flatMap(O=>O.toolEvents??[])),o={},s={},i=[],a=[],c=[],l=0,d=0,u=0,p=0,f=0;for(let O of r){let U=O.toolName;o[U]=(o[U]??0)+1,O.isError===!0&&(l+=1,s[U]=(s[U]??0)+1);let q=H$(O.inputRaw??O.input);if(U==="write_file"&&(d+=1),U==="edit_file"&&(u+=1),U==="bash"){p+=1;let H=ga(q?.command)??O.input;H&&j$.test(H)&&(f+=1)}if(U$.has(U)){let H=ga(q?.file_path);H&&!c.includes(H)&&c.length<B$&&c.push(H)}if(N$.has(U)){let H;U==="skill"?(H=ga(q?.name),H&&!a.includes(H)&&a.push(H)):U==="agent"?H=ga(q?.id_prefix):H="compose",i.push(H?{tool:U,label:H}:{tool:U})}}let m=n[0]?.user??"",g=t.source??"cli",h=K$(m,g),y=[];for(let O of n){let q=Tk.exec(O.user??"")?.[1];q&&!y.includes(q)&&y.push(q)}let w=n.filter(O=>(O.user??"").trim().length>0).length,S=n.filter(O=>(O.assistant??"").trim().length>0).length,v=[...n].reverse().find(O=>(O.assistant??"").trim().length>0)?.assistant??"",_;n.length===0?_="aborted":v.trim().length===0?_="partially_achieved":_="fully_achieved";let T=_==="fully_achieved"||_==="partially_achieved"?ha(v||m||h,160)||h:"none",I=l>0?`${l} tool error(s): ${Object.entries(s).map(([O,U])=>`${O}\xD7${U}`).join(", ")}`:"",k=t.name?W$(t.name):ha(m,80),A=ha(v||m,$$),R=ha(k?`${k} \u2014 ${A}`:A,400)||"empty session",D=t.sessionId??(e.sourceSessionPath?L$(e.sourceSessionPath,".json"):"unknown"),G=t.totalDurationMs&&t.totalDurationMs>0?t.totalDurationMs:Math.max(0,t.savedAt-t.startedAt),F=e.sourceSessionPath?[...c,e.sourceSessionPath]:c,N={facet_version:Lo,session_id:D,source:g==="telegram"?"telegram":g==="web"?"web":"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((G/6e4).toFixed(2)),underlying_goal:m.slice(0,vk),first_prompt:m.slice(0,vk),goal_categories:{[h]:1},session_type:h,brief_summary:R,total_turns:n.length,user_message_count:w,assistant_message_count:S,tool_counts:o,commands:y,skills:a,subagents:i,tool_errors:l,tool_error_categories:s,friction_counts:{...s},friction_detail:I,outcome:_,primary_success:T,world_changes:{files_written:d,files_edited:u,bash_commands:p,commits:f,mutated:d>0||u>0||f>0},decisions:[],evidence_pointers:F};return t.totalCostUsd!=null&&(N.token_breakdown={cost_usd:t.totalCostUsd}),No.parse(N)}M();import{existsSync as ya,mkdirSync as G$,readFileSync as _k,readdirSync as X$,renameSync as z$,statSync as J$,writeFileSync as V$}from"fs";import{basename as Y$,dirname as Q$,join as Ek}from"path";function Ak(t,e){return js(t),Ek(e,`${t}.json`)}function Z$(t,e){return js(t),Ek(e,`${t}.json`)}function Uo(t,e=re()){let n=Ak(t,e);if(ya(n))try{let r=JSON.parse(_k(n,"utf8")),o=Xu.safeParse(r);return o.success?o.data:void 0}catch{return}}function eB(t){if(ya(t))try{let e=JSON.parse(_k(t,"utf8")),n=No.safeParse(e);return n.success?n.data:void 0}catch{return}}function tB(t,e){G$(Q$(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;V$(n,`${JSON.stringify(e,null,2)}
|
|
327
|
+
`,"utf8"),z$(n,t)}function nB(t,e){return t.facet_version===Lo&&t.source_session_mtime_ms===e}function vn(t,e={}){let n=e.sessionsDir??re(),r=e.cacheDir??gm(),o=Ak(t,n);if(!ya(o))return;let s=J$(o).mtimeMs,i=Z$(t,r);if(!e.force){let l=eB(i);if(l&&nB(l,s))return l}let a=Uo(t,n);if(!a)return;let c=nr(a,{sourceSessionPath:o,sourceSessionMtimeMs:s});return tB(i,c),c}function rr(t={}){let e=t.sessionsDir??re();return ya(e)?X$(e).filter(n=>n.endsWith(".json")).map(n=>Y$(n,".json")):[]}M();var xk=async(t,e)=>{let n=t??{},r=typeof n.session=="string"?n.session:"latest",o=Array.isArray(n.fields)?n.fields:null,s;if(r==="latest"){let d=rr();if(d.length>0){let u=re(),p;for(let f of d)try{let m=rB(oB(u,`${f}.json`)).mtimeMs;(!p||m>p.mtimeMs)&&(p={id:f,mtimeMs:m})}catch{}s=p?.id}}else s=fa(r)?.sidecarId;if(!s)return{content:`Session not found: ${r}`,isError:!0};let i=vn(s);if(!i)return{content:`Session not found: ${r}`,isError:!0};let a=i,c={},l=new Set($g);if(o&&o.length>0)for(let d of o)c[d]=a[d];else for(let[d,u]of Object.entries(a))l.has(d)||(c[d]=u);return{content:JSON.stringify(c,null,2)}};import{promises as Rk}from"fs";var sB=100,iB=50*1024,Ik=10*1024*1024;function zu(t){let e=t.trim();if(e==="keys")return{kind:"keys"};if(e==="length")return{kind:"length"};if(e===".")return{kind:"identity"};let n=aB(e);if(n!==-1){let o=zu(e.slice(0,n).trim()),s=zu(e.slice(n+1).trim());return{kind:"pipe",left:o,right:s}}let r=e.match(/^\.\[(.+)\]$/);if(r){let o=(r[1]??"").trim(),s=o.match(/^(-?\d+)\s*:\s*(-?\d+)$/);if(s)return{kind:"slice",from:Number(s[1]??"0"),to:Number(s[2]??"0")};if(/^-?\d+$/.test(o))return{kind:"index",idx:Number(o)};throw new Error(`Unrecognised bracket expression: .[${o}]`)}if(e===".[]")return{kind:"iter"};if(e.startsWith(".")){let o=e.slice(1);if(o.length===0)return{kind:"identity"};if(/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(o)){let s=o.split("."),i=s[0]??"";if(s.length===1)return{kind:"field",name:i};let a={kind:"field",name:i};for(let c=1;c<s.length;c++)a={kind:"pipe",left:a,right:{kind:"field",name:s[c]??""}};return a}}throw new Error(`Unrecognised query expression: "${e}". Supported: . .field .field.nested .[N] .[N:M] .[] keys length .[] | .field`)}function aB(t){let e=0;for(let n=0;n<t.length;n++){let r=t[n];if(r==="["||r==="(")e++;else if(r==="]"||r===")")e--;else if(r==="|"&&e===0)return n}return-1}function cB(t){return t.kind==="iter"||t.kind==="pipe"&&t.left.kind==="iter"}function Ju(t,e){switch(t.kind){case"identity":return[e];case"keys":{if(e===null||typeof e!="object")throw new Error(`keys requires an object or array, got ${or(e)}`);return Array.isArray(e)?[e.map((n,r)=>r)]:[Object.keys(e)]}case"length":{if(Array.isArray(e))return[e.length];if(e!==null&&typeof e=="object")return[Object.keys(e).length];if(typeof e=="string")return[e.length];if(e===null)return[0];throw new Error(`length not defined for ${or(e)}`)}case"field":{if(e===null||typeof e!="object"||Array.isArray(e))throw new Error(`Cannot access field ".${t.name}" on ${or(e)}`);return[e[t.name]]}case"index":{if(!Array.isArray(e))throw new Error(`Cannot index non-array with .[${t.idx}]`);let n=e.length,r=t.idx<0?n+t.idx:t.idx;return[e[r]]}case"slice":{if(!Array.isArray(e)&&typeof e!="string")throw new Error(`Cannot slice ${or(e)} \u2014 expected array or string`);return Array.isArray(e)?[e.slice(t.from,t.to)]:[e.slice(t.from,t.to)]}case"iter":{if(!Array.isArray(e))throw new Error(`Cannot iterate (.[] ) over ${or(e)} \u2014 expected array`);return e}case"pipe":{let n=Ju(t.left,e),r=[];for(let o of n){let s=Ju(t.right,o);r.push(...s)}return r}}}function or(t){return t===null?"null":Array.isArray(t)?"array":typeof t}async function lB(t,e,n,r){if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t,s=o.path,i=o.query,a=o.max_results??sB,c=o.max_bytes??iB;if(typeof s!="string"||s.length===0)return{content:"Invalid input: path must be a non-empty string",isError:!0};if(typeof i!="string"||i.length===0)return{content:"Invalid input: query must be a non-empty string",isError:!0};if(typeof a!="number"||a<1)return{content:"Invalid input: max_results must be a positive number",isError:!0};if(typeof c!="number"||c<1)return{content:"Invalid input: max_bytes must be a positive number",isError:!0};let l=Math.floor(a),d=Math.floor(c),u;try{u=ee(s,n,"read",r)}catch(T){return{content:T instanceof Error?T.message:String(T),isError:!0}}let p;try{p=zu(i)}catch(T){return{content:`Invalid query: ${T instanceof Error?T.message:String(T)}`,isError:!0}}let f;try{let T=await Rk.stat(u);if(T.size>Ik)return{content:`File too large (${T.size} bytes). json_query supports files up to ${Ik} bytes.`,isError:!0};f=await Rk.readFile(u)}catch(T){let I=We(T,u,"File");return I||{content:`Error reading file: ${T instanceof Error?T.message:String(T)}`,isError:!0}}let m=f.length;if(m===0)return{content:JSON.stringify({result:null,type:"null",truncated:!1,source_size:0})};let g;try{g=JSON.parse(f.toString("utf-8"))}catch(T){return{content:`JSON parse error: ${T instanceof SyntaxError?T.message:String(T)}`,isError:!0}}let h;try{h=Ju(p,g)}catch(T){return{content:`Query error: ${T instanceof Error?T.message:String(T)}`,isError:!0}}let y=cB(p),w=!1,S;if(h.length===1&&!y){let T=h[0];Array.isArray(T)&&T.length>l?(S=T.slice(0,l),w=!0):S=T}else h.length>l?(S=h.slice(0,l),w=!0):S=h;let v=S===void 0?"null":JSON.stringify(S,null,2),_;Buffer.byteLength(v,"utf-8")>d?(w=!0,_=Buffer.from(v,"utf-8").slice(0,d).toString("utf-8")+`
|
|
328
|
+
\u2026 [truncated]`):_=S===void 0?null:S;let E={result:_,type:S===void 0?"null":or(S),truncated:w,source_size:m};return{content:JSON.stringify(E)}}function Vu(t){return(e,n,r)=>lB(e,n,r,t)}var Ck=Vu();import{spawnSync as gB}from"node:child_process";import{spawnSync as dB}from"node:child_process";function uB(t){switch(t){case"darwin":return[{cmd:"pbcopy",args:[]}];case"win32":return[{cmd:"clip",args:[]}];default:return[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}}function pB(t){return`\x1B]52;c;${Buffer.from(t,"utf8").toString("base64")}\x07`}function fB(t,e){return pB(t)}function mB(t,e=process.env,n=process.stdout){if(n.isTTY!==!0)return!1;try{return n.write(fB(t,e)),!0}catch{return!1}}function Pk(t,e=process.platform,n=process.env,r=process.stdout){for(let o of uB(e))try{let s=dB(o.cmd,o.args,{input:t});if(!s.error&&s.status===0)return!0}catch{}return mB(t,n,r)}function hB(t){switch(t){case"darwin":return[{cmd:"pbpaste",args:[]}];case"win32":return[{cmd:"powershell",args:["-NoProfile","-NonInteractive","-Command","Get-Clipboard"]}];default:return[{cmd:"wl-paste",args:["--no-newline"],checkStderr:!0},{cmd:"xclip",args:["-selection","clipboard","-o"]},{cmd:"xsel",args:["--clipboard","--output"]}]}}function yB(t=process.platform){for(let e of hB(t))try{let n=gB(e.cmd,e.args,{encoding:"utf8",timeout:5e3});if(!n.error&&n.status===0&&n.signal===null&&(!e.checkStderr||!n.stderr?.trim()))return n.stdout??""}catch{}return null}function Mk(t={}){let e=t.writeFn??(n=>Pk(n));return async(n,r)=>{if(!n||typeof n!="object")return{content:"Invalid input: expected an object",isError:!0};let s=n.text;if(typeof s!="string")return{content:"Invalid input: text must be a string",isError:!0};let i;try{i=e(s)}catch(a){return{content:`Clipboard write threw an error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}return i?{content:"Text copied to clipboard successfully."}:{content:"Clipboard write failed: no clipboard utility available in this environment (headless, SSH-only, or CI). The text was not written to the clipboard.",isError:!0}}}var Ok=Mk();function Dk(t={}){let e=t.readFn??(()=>yB());return async(n,r,o)=>{let s=await kt.route({serverName:"agent",origin:"agent",message:"The model wants to read your clipboard contents. Clipboard may contain passwords, tokens, or other sensitive data. Allow the model to read the clipboard?",type:"confirm"},{signal:r,...o?.sessionId!==void 0?{sessionId:o.sessionId}:{}});if(s.action!=="accept"||s.content?.value!==!0)return{content:"Clipboard read was not approved by the operator.",isError:!0,failureClass:"elicitation-declined"};let i=e();if(i===null)return{content:"Clipboard read failed: no clipboard utility available in this environment (headless, SSH-only, or CI). No content was returned.",isError:!0};let a=et(i),c=1e5,d=Buffer.byteLength(a,"utf8")>c;return{content:(()=>{if(!d)return a;let p=Buffer.from(a,"utf8"),f=c;for(;f>0&&(p[f]&192)===128;)f--;return p.slice(0,f).toString("utf8")})(),...d?{truncated:!0}:{}}}}var Fk=Dk();function sr(t,e){let n=t!==void 0?Di(t,e):e!==void 0?Di("default",e):zh,r=e!==void 0?Pd(e):iy,o=e!==void 0?Od(e):dy,s=e!==void 0?xd(e):Jh,i=e!==void 0?Rd(e):ey,a=e!==void 0?Id(e):ny,c=e!==void 0?Cd(e):oy,l=e!==void 0?Fd(e):uy,d=ku(),u=Nw(e),p=e!==void 0?ju(e):pk,f=e!==void 0?Vu(e):Ck;return new Map([["bash",n],["read_file",s],["extract_document",i],["write_file",a],["edit_file",c],["glob",r],["grep",o],["list_directory",l],["send_telegram",ab],["web_scrape",Zb],["web_request",ow],["create_schedule",uw],["list_schedules",pw],["get_schedule_history",fw],["cancel_schedule",mw],["read_witness",xS],["search_witness",RS],["worktree",u],["terminal_font_size",d],["config_get",uS],["config_set",pS],["ask_question",PS],["wait_for",ik],["browser_open",OS],["browser_observe",DS],["browser_act",NS],["browser_screenshot",$S],["browser_close",BS],["patch_apply",p],["test_run",hk],["get_facet",xk],["json_query",f],["clipboard_write",Ok],["clipboard_read",Fk]])}function Lk(t){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${t}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${t}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
|
|
329
329
|
`)}M();var vt="exit_plan_mode",bB="Approve \u2014 implement now (bypass mode: no prompts, read/write any path)",Yu="Keep planning";function wB(t){switch(t){case"bypassPermissions":return"Approve \u2014 implement now (restore bypass mode: no prompts, read/write any path)";case"acceptEdits":return"Approve \u2014 implement now (restore accept-edits mode: edits auto-approved)";case"dontAsk":case"auto":return"Approve \u2014 implement now (restore your previous mode: no approval prompts)";default:return"Approve \u2014 implement now (restore default mode: writes ask for confirmation, contained to the workspace)"}}var ba={name:vt,category:"other",concurrencySafe:!1,description:`Signal that your plan is ready and present it to the user for approval. The user is shown a picker: approve and implement (you pick neither mode \u2014 the user does), or keep planning.
|
|
330
330
|
|
|
331
331
|
IMPORTANT: only call this in plan mode, and only when the task requires implementation (writing code or files). For research / read-only / understanding tasks, do NOT call it \u2014 just answer.
|
|
@@ -1115,17 +1115,17 @@ ${o}`:o}function Nj(t){let e=t.systemPrompt;if(e!==void 0){if(typeof e=="string"
|
|
|
1115
1115
|
`);function Ep(t){return t!=="plan"?null:{type:"text",text:Ja}}var Va=["## 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(`
|
|
1116
1116
|
`);function Ap(t){return t!=="autonomous"?null:{type:"text",text:Va}}var rT=160;function Yt(t,e){if(!e||typeof e!="object")return"";let n=e;if(t==="skill"||t==="Skill"){let i=n.name;return typeof i=="string"&&i.length>0?`(${i.length>60?i.slice(0,59)+"\u2026":i})`:""}let r=n.file_path??n.path??n.filePath;if(typeof r=="string")return" "+r;let o=n.command??n.cmd;if(typeof o=="string"){let i=et(o.replace(/\\\r?\n/g," ").replace(/\s+/g," ").trim());return" "+(i.length>rT?i.slice(0,rT-1)+"\u2026":i)}let s=n.query??n.pattern??n.url??n.description;return typeof s=="string"?" "+s:""}import{randomUUID as fH}from"node:crypto";var dH=["file_path","name","id_prefix"],oT=4096,sT=8192;function Ya(t){if(!t||typeof t!="object")return;let e=t,n={};for(let r of dH){let o=e[r];o!==void 0&&(n[r]=typeof o=="string"&&o.length>oT?o.slice(0,oT):o)}return Object.keys(n).length>0?JSON.stringify(n):void 0}function Qa(t){if(!t||typeof t!="object")return;let e=t;if(Object.keys(e).length===0)return;let n={};for(let[r,o]of Object.entries(e))if(typeof o=="string"){let s=o.length>sT?o.slice(0,sT):o;n[r]=et(s)}else o!=null&&typeof o!="object"&&(n[r]=o);return Object.keys(n).length>0?JSON.stringify(n):void 0}C();import{createHash as uH}from"crypto";function Za(t){let{toolUseId:e,name:n,input:r,subagentId:o}=t,s=r??{},i=JSON.stringify(s),a=JSON.stringify(pH(n,s));return{phase:"started",toolUseId:e,name:n,inputBytes:Buffer.byteLength(i,"utf8"),argsFingerprint:uH("sha256").update(a).digest("hex"),...o!==void 0?{subagentId:o}:{}}}function pH(t,e){if(typeof e!="object"||e===null)return e;let n=e;switch(t){case"browser_act":return n.action==="fill"&&"value"in n?{...n,value:"[REDACTED]"}:e;case"config_set":return n.target==="env"&&"value"in n?{...n,value:"[REDACTED]"}:e;default:return e}}function ec(t){let{toolUseId:e,name:n,result:r,truncated:o,durationMs:s,subagentId:i}=t;return{phase:"completed",toolUseId:e,name:n,resultBytes:Buffer.byteLength(r.content,"utf8"),isError:r.isError===!0,truncated:o,durationMs:s,...r.incomplete===!0?{incomplete:!0}:{},...r.incompleteReason?{incompleteReason:r.incompleteReason}:{},...r.circuitBreaker===!0?{circuitBreaker:!0}:{},...r.failureClass?{failureClass:r.failureClass}:{},...typeof r.batchIndex=="number"&&typeof r.batchSize=="number"?{batchIndex:r.batchIndex,batchSize:r.batchSize}:{},...i!==void 0?{subagentId:i}:{},...r.testResult!==void 0?{testResult:r.testResult}:{}}}async function*tc(t){let e=[],n=!1,r=null,o=()=>{let l=r;r=null,l?.()},a=t(l=>{n||(e.push(l),o())}).finally(()=>{n=!0,o()}).then(l=>({ok:!0,value:l}),l=>({ok:!1,error:l}));for(;;){for(;e.length>0;)yield e.shift();if(n)break;await new Promise(l=>{r=l})}let c=await a;if(!c.ok)throw c.error;return c.value}async function*iT({state:t,signal:e,vision:n,toolDispatcher:r,traceWriter:o,priorTurns:s,sessionId:i,subagentId:a}){if(!r)return void 0;let c=qo(t);for(let m of c)m.id.length===0&&(m.id=fH());let{calls:l,parseErrors:d}=Ov(c,e),u=new Map;for(let m of l){let g=Date.now();u.set(m.id,g),nn(o,Za({toolUseId:m.id,name:m.name,input:m.input,subagentId:a})),yield{type:"tool.use.start",toolUseId:m.id,toolName:m.name,toolInput:Yt(m.name,m.input),toolInputRaw:Ya(m.input),toolInputCapture:b.AFK_CAPTURE_SUBAGENT_OUTPUT==="1"?Qa(m.input):void 0,sessionId:i}}let p=[];if(e.aborted){let m=be(e);for(let g of l){let h={content:"Tool call aborted",isError:!0,failureClass:m};p.push({call:g,result:h}),yield{type:"tool.output",toolUseId:g.id,toolName:g.name,content:h.content,isError:!0,failureClass:m,sessionId:i}}}else{let m;try{if(r.executeBatch)m=yield*tc(g=>r.executeBatch(l,h=>{g({type:"tool.activity",activeCount:h.length,activeToolUseIds:[...h],sessionId:i})}));else{m=[];for(let g of l){if(e.aborted){m.push({content:"Tool call aborted",isError:!0,failureClass:be(e)});continue}try{m.push(await r.execute(g))}catch(h){let y=h instanceof Error?h.message:String(h);m.push({content:`Tool execution threw: ${y}`,isError:!0})}}}}catch(g){let h=g instanceof Error?g.message:String(g);m=l.map(()=>({content:`Tool batch execution failed: ${h}`,isError:!0}))}for(let g=0;g<l.length;g++){let h=l[g],y=m[g],w=d.get(h.id);w!==void 0&&(y={content:`${w}
|
|
1117
1117
|
--
|
|
1118
|
-
${y.content}`,isError:!0,...y.truncated===!0?{truncated:!0}:{}}),p.push({call:h,result:y});let k=u.get(h.id),v=typeof k=="number"?Date.now()-k:0,_=y.truncated===!0||y.content.includes("[output truncated");nn(o,ec({toolUseId:h.id,name:h.name,result:y,truncated:_,durationMs:v,subagentId:a})),yield{type:"tool.output",toolUseId:h.id,toolName:h.name,content:y.content,...y.isError===!0?{isError:!0}:{},...y.truncated===!0?{truncated:!0}:{},...y.incomplete===!0?{incomplete:!0}:{},...y.incompleteReason?{incompleteReason:y.incompleteReason}:{},...typeof y.batchIndex=="number"&&typeof y.batchSize=="number"?{batchIndex:y.batchIndex,batchSize:y.batchSize}:{},...y.failureClass?{failureClass:y.failureClass}:{},sessionId:i},y.render?.diff&&(yield{type:"tool.diff",toolUseId:h.id,diff:y.render.diff,sessionId:i})}}s.push(Dv(t.assistantText,c,t.reasoningText));for(let m of Fv(p))s.push(m);for(let{result:m}of p)m.harnessUserMessage?.kind==="queued_user_message"&&s.push({role:"user",content:m.harnessUserMessage.text});let f=Lv(p,{vision:n});return f&&s.push(f),p.find(m=>m.result.failureClass===Hn)?.result}var ct="tool_use_loop_capped";var nc="You have reached your tool-use budget for this turn. Do not request any more tools \u2014 give your final answer now using only the information already gathered.";function rc(t){return t!==void 0&&t>0?Math.floor(t):0}function oc(t,e){return e>0&&t>=e}function sc(t,e){return e>0?`round ${t}/${e}`:`round ${t}`}var lt="soft_deadline_wind_down",ic="Your time budget for this turn is nearly spent. Do not request any more tools \u2014 give your final answer now using only the information already gathered. If your work is incomplete, say briefly what you established, what remains unresolved, and what you would check next.";function xp(t){if(t===void 0||!Number.isFinite(t)||t<=0||t<=12e4)return 0;let e=t*.15,n=Math.min(3e5,Math.max(3e4,e));return Math.max(0,Math.floor(t-n))}function ac(t,e,n=Date.now()){return e>0&&n-t>=e}function aT(t,e,n,r){try{return Zr(pe(t??{}),Vo(e,n),Ve(e),r),null}catch(o){return o instanceof Error?o:new Error(String(o))}}import gH from"openai";var mH=new Set([429,503,529]);function cT(t){let e=t.get("retry-after");if(e==null)return;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.round(n*1e3);let r=Date.parse(e);if(!Number.isNaN(r)){let o=r-Date.now();if(o>=0)return o}}function lT(t=fetch,e,n,r){return!e&&!n&&!r?t:async(o,s)=>{if(r){let a=Ea(s),c=s?.signal instanceof AbortSignal?s.signal:void 0;await r.acquirePermit(a,c)}let i=await t(o,s);if(n)try{n(i.headers)}catch{}if(r&&i.status===429)try{let a=cT(i.headers);r.freeze(a??5e3)}catch{}if(e&&mH.has(i.status))try{let a=cT(i.headers);e({status:i.status,...a!==void 0?{retryAfterMs:a}:{}})}catch{}return i}}var hH=null;function yH(t){let e={apiKey:t.apiKey};return t.baseURL!==void 0&&(e.baseURL=t.baseURL),t.defaultHeaders!==void 0&&(e.defaultHeaders=t.defaultHeaders),t.fetch!==void 0&&(e.fetch=t.fetch),new gH(e)}function dT(){return hH??yH}var bH=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","chatgpt.com"]),wH=[".chatgpt.com"];function SH(t){if(!t)return!1;let e;try{e=new URL(t).hostname}catch{return!1}return bH.has(e)||e.startsWith("127.")?!0:wH.some(n=>e===n.slice(1)||e.endsWith(n))}function uT(t){if(SH(t))return;let e=n=>{let r=Zk(n);r!==void 0&&cr.update(r)};return lT(globalThis.fetch,void 0,e,cr)}async function*Rp(t,e){let n=0;for(;;){let r=$a(),o=Date.now(),s,i=null;for(let d=0;;d++)try{s=await e.createStream(t.controller.signal);break}catch(u){if(t.controller.signal.aborted)return null;if(Xa(u)&&d<tT){let p=_p(u),f=p??Tp(d);if($(t.traceWriter,{phase:"rate_limit",durationMs:f,resolvedModel:t.currentModel,metadata:{source:"connection",reason:p!==void 0?"retry-after":"backoff",attempt:d}}),await Ie(f,t.controller.signal),t.controller.signal.aborted)return null;continue}i=u;break}if(i!==null)return yield{type:"error",error:e.clarifyError(i)},null;let a=null,c=!1;try{for await(let d of yr(s,t.controller.signal)){if(t.isClosed())return null;for(let u of e.translate(d,r))c||(c=!0,$(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-o,resolvedModel:t.currentModel})),yield u}}catch(d){if(t.controller.signal.aborted)return null;if(za(d)&&n<nT){n++,yield{type:"stream.retry",sessionId:t.initSessionId};let u=_p(d),p=u??Tp(n-1);if($(t.traceWriter,{phase:"rate_limit",durationMs:p,resolvedModel:t.currentModel,metadata:{source:"stream",reason:u!==void 0?"retry-after":"backoff",attempt:n}}),await Ie(p,t.controller.signal),t.controller.signal.aborted)return null;continue}a=d}if(a!==null)return yield{type:"error",error:e.clarifyError(a)},null;if(t.controller.signal.aborted)return null;let l=Pv(r)&&r.toolCallsByIndex.size>0;return r.finishReason===null&&r.assistantText.length===0&&!l?(yield{type:"error",error:new Le("the model stream ended without a finish_reason and without a dispatchable response (no visible answer text and no complete tool call): the response was empty or cut off before any usable content arrived. The turn is incomplete.")},null):{state:r,events:[],text:r.assistantText,needsToolDispatch:l}}}var kH=new Set([400,404,405,415,422,501]);function pT(t){if(t instanceof Yo||Xa(t)||za(t))return!1;let e=Vt(t);return e!==void 0&&kH.has(e)}var Ip="openai-compatible",cc=class{client;opts;initSessionId;toolDispatcher;onPermissionMode;onCwdChange;openAITools;wireMode;useOpenAIPricing;traceWriter;priorTurns=[];currentModel;currentPermissionMode;responsesCompactionUnavailable=!1;abort=new fr;closed=!1;lastUsage=null;autoCompactThreshold;constructor(e){if(this.opts=e,this.initSessionId=e.synthesizedSessionId,this.currentModel=e.model,this.currentPermissionMode=vp(e.config.permissionMode),this.toolDispatcher=e.toolDispatcher,this.onPermissionMode=e.onPermissionMode,this.onCwdChange=e.onCwdChange,this.traceWriter=e.traceWriter,this.autoCompactThreshold=eo(e.config.autoCompact,e.model),this.toolDispatcher){let s=this.toolDispatcher;Array.isArray(s.toolDefs)&&s.toolDefs.length>0&&(this.openAITools=Mv(s.toolDefs))}let n=(e.useResponsesApi??!1)||Uv(b.AFK_OPENAI_USE_RESPONSES),r=$v(e.auth,n);this.wireMode=r.mode,this.useOpenAIPricing=r.baseURL===void 0&&e.baseURL===void 0||pp(e.model)&&e.config.forceXaiOAuth!==!0;let o=e.config.resumeHistory?.at(-1);if(o?.inputTokens!==void 0&&o.inputTokens>0&&(this.lastUsage={inputTokens:o.inputTokens,stopReason:null,resultSubtype:"success",isError:!1}),e.auth.apiKey===null)this.client=null;else{let s=dT(),i={apiKey:e.auth.apiKey},a=r.baseURL??e.baseURL;a!==void 0&&(i.baseURL=a),r.headers!==void 0?i.defaultHeaders=r.headers:e.defaultHeaders!==void 0&&(i.defaultHeaders=e.defaultHeaders);let c=uT(a);c!==void 0&&(i.fetch=c),this.client=s(i)}}activeOpenAITools(){if(!this.openAITools)return;if(this.currentPermissionMode==="plan")return this.openAITools;let e=this.openAITools.filter(n=>n.function.name!==vt);return e.length>0?e:void 0}async*[Symbol.asyncIterator](){if(yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:this.openAITools?this.openAITools.map(r=>r.function.name):[],slashCommands:[],skills:[],plugins:[],mcpServers:this.opts.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.opts.auth.source,version:Ip}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(dp(this.opts.auth))};return}let n=this.opts.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let r=await Promise.race([n.next(),this.abort.closedPromise]);if(r===gp)break;let o=r;if(o.done)break;if(yield*this.runTurn(o.value.content),this.autoCompactThreshold!==void 0&&!this.closed){let s=this.lastUsage,i=mt(this.currentModel);if(s!==null&&i>0){let a=pe(s);if(Yr(a,i,this.autoCompactThreshold))try{await this.opts.config.hookRegistry?.dispatch({event:"PreCompact",sessionId:this.initSessionId,trigger:"auto"}),(await this.compactHistory("token_threshold")).compacted&&(this.lastUsage=null)}catch(c){if(!(c instanceof W))throw c}}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}async*runTurn(e){let n=this.abort.begin();if(n.signal.aborted)return;let r=Date.now(),o=TH(),s=new dr(n.signal,this.traceWriter,"openai-compatible");try{yield*this._runTurnInner(e,n,r,o)}finally{s.finish(Date.now()-r)}}async*_runTurnInner(e,n,r,o){let s=zl(this.currentModel),i=aT(this.lastUsage,this.currentModel,this.opts.config.maxOutputTokens,this.opts.config.model??this.currentModel);if(i){this.abort.clear(n),yield{type:"error",error:i};return}this.priorTurns.push({role:"user",content:Ev(e,{vision:s,model:this.currentModel})});let a={stopReason:null,resultSubtype:"success",isError:!1},c="",l="",d=rc(this.opts.config.maxToolUseIterations),u=this.opts.config.softDeadlineMs??0,p=null,f=0,m=0,g=[];for(;;){if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let y=yield*this.runIteration(n,s,p);if(y===null){this.abort.clear(n),(n.signal.aborted||this.closed)&&(yield*this.finishTurn(a,r));return}let w=Cv(y.state,this.useOpenAIPricing?this.currentModel:void 0);if(a=Ko(a,w),a.contextWindowTokens=(w.inputTokens??0)+(w.outputTokens??0),this.lastUsage=a,y.text.length>0&&(c=y.text),l=y.state.reasoningText,!y.needsToolDispatch){At(y.state.finishReason)&&(g=qo(y.state).map(E=>E.name));break}if(p!==null)break;let k=yield*this.dispatchAndAppend(y.state,n.signal,s);if(k){this.abort.clear(n),yield{type:"error",error:new On(k.content)};return}f+=1;{let E=qo(y.state);m+=E.length;let T=E.at(-1),I=T?.name,S;try{S=T?JSON.parse(T.argumentsRaw||"{}"):void 0}catch{S=void 0}let A=T?`${T.name}${Yt(T.name,S)}`:"unknown";yield{type:"progress",progress:{taskId:o,description:"Working",summary:`${sc(f,d)}: ${A}`,lastToolName:I,totalTokens:a.totalTokens??0,toolUses:m,durationMs:Date.now()-r},sessionId:this.initSessionId}}if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let v=oc(f,d),_=ac(r,u);if(v||_){p=v?ct:lt;continue}}if(this.abort.clear(n),c.length>0){let y={role:"assistant",content:c};l.length>0&&(y.reasoning_content=l),this.priorTurns.push(y)}let h=At(a.stopReason)?Na(g,a.stopReason,{canIncreaseOutputLimit:!(this.opts.auth.source==="chatgpt-oauth"&&a.stopReason==="max_output_tokens")}):null;c.length>0?yield{type:"assistant.message",text:h?`${c}
|
|
1118
|
+
${y.content}`,isError:!0,...y.truncated===!0?{truncated:!0}:{}}),p.push({call:h,result:y});let S=u.get(h.id),v=typeof S=="number"?Date.now()-S:0,_=y.truncated===!0||y.content.includes("[output truncated");nn(o,ec({toolUseId:h.id,name:h.name,result:y,truncated:_,durationMs:v,subagentId:a})),yield{type:"tool.output",toolUseId:h.id,toolName:h.name,content:y.content,...y.isError===!0?{isError:!0}:{},...y.truncated===!0?{truncated:!0}:{},...y.incomplete===!0?{incomplete:!0}:{},...y.incompleteReason?{incompleteReason:y.incompleteReason}:{},...typeof y.batchIndex=="number"&&typeof y.batchSize=="number"?{batchIndex:y.batchIndex,batchSize:y.batchSize}:{},...y.failureClass?{failureClass:y.failureClass}:{},sessionId:i},y.render?.diff&&(yield{type:"tool.diff",toolUseId:h.id,diff:y.render.diff,sessionId:i})}}s.push(Dv(t.assistantText,c,t.reasoningText));for(let m of Fv(p))s.push(m);for(let{result:m}of p)m.harnessUserMessage?.kind==="queued_user_message"&&s.push({role:"user",content:m.harnessUserMessage.text});let f=Lv(p,{vision:n});return f&&s.push(f),p.find(m=>m.result.failureClass===Hn)?.result}var ct="tool_use_loop_capped";var nc="You have reached your tool-use budget for this turn. Do not request any more tools \u2014 give your final answer now using only the information already gathered.";function rc(t){return t!==void 0&&t>0?Math.floor(t):0}function oc(t,e){return e>0&&t>=e}function sc(t,e){return e>0?`round ${t}/${e}`:`round ${t}`}var lt="soft_deadline_wind_down",ic="Your time budget for this turn is nearly spent. Do not request any more tools \u2014 give your final answer now using only the information already gathered. If your work is incomplete, say briefly what you established, what remains unresolved, and what you would check next.";function xp(t){if(t===void 0||!Number.isFinite(t)||t<=0||t<=12e4)return 0;let e=t*.15,n=Math.min(3e5,Math.max(3e4,e));return Math.max(0,Math.floor(t-n))}function ac(t,e,n=Date.now()){return e>0&&n-t>=e}function aT(t,e,n,r){try{return Zr(pe(t??{}),Vo(e,n),Ve(e),r),null}catch(o){return o instanceof Error?o:new Error(String(o))}}import gH from"openai";var mH=new Set([429,503,529]);function cT(t){let e=t.get("retry-after");if(e==null)return;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.round(n*1e3);let r=Date.parse(e);if(!Number.isNaN(r)){let o=r-Date.now();if(o>=0)return o}}function lT(t=fetch,e,n,r){return!e&&!n&&!r?t:async(o,s)=>{if(r){let a=Ea(s),c=s?.signal instanceof AbortSignal?s.signal:void 0;await r.acquirePermit(a,c)}let i=await t(o,s);if(n)try{n(i.headers)}catch{}if(r&&i.status===429)try{let a=cT(i.headers);r.freeze(a??5e3)}catch{}if(e&&mH.has(i.status))try{let a=cT(i.headers);e({status:i.status,...a!==void 0?{retryAfterMs:a}:{}})}catch{}return i}}var hH=null;function yH(t){let e={apiKey:t.apiKey};return t.baseURL!==void 0&&(e.baseURL=t.baseURL),t.defaultHeaders!==void 0&&(e.defaultHeaders=t.defaultHeaders),t.fetch!==void 0&&(e.fetch=t.fetch),new gH(e)}function dT(){return hH??yH}var bH=new Set(["localhost","127.0.0.1","0.0.0.0","[::1]","chatgpt.com"]),wH=[".chatgpt.com"];function SH(t){if(!t)return!1;let e;try{e=new URL(t).hostname}catch{return!1}return bH.has(e)||e.startsWith("127.")?!0:wH.some(n=>e===n.slice(1)||e.endsWith(n))}function uT(t){if(SH(t))return;let e=n=>{let r=Zk(n);r!==void 0&&cr.update(r)};return lT(globalThis.fetch,void 0,e,cr)}async function*Rp(t,e){let n=0;for(;;){let r=$a(),o=Date.now(),s,i=null;for(let d=0;;d++)try{s=await e.createStream(t.controller.signal);break}catch(u){if(t.controller.signal.aborted)return null;if(Xa(u)&&d<tT){let p=_p(u),f=p??Tp(d);if($(t.traceWriter,{phase:"rate_limit",durationMs:f,resolvedModel:t.currentModel,metadata:{source:"connection",reason:p!==void 0?"retry-after":"backoff",attempt:d}}),await Ie(f,t.controller.signal),t.controller.signal.aborted)return null;continue}i=u;break}if(i!==null)return yield{type:"error",error:e.clarifyError(i)},null;let a=null,c=!1;try{for await(let d of yr(s,t.controller.signal)){if(t.isClosed())return null;for(let u of e.translate(d,r))c||(c=!0,$(t.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-o,resolvedModel:t.currentModel})),yield u}}catch(d){if(t.controller.signal.aborted)return null;if(za(d)&&n<nT){n++,yield{type:"stream.retry",sessionId:t.initSessionId};let u=_p(d),p=u??Tp(n-1);if($(t.traceWriter,{phase:"rate_limit",durationMs:p,resolvedModel:t.currentModel,metadata:{source:"stream",reason:u!==void 0?"retry-after":"backoff",attempt:n}}),await Ie(p,t.controller.signal),t.controller.signal.aborted)return null;continue}a=d}if(a!==null)return yield{type:"error",error:e.clarifyError(a)},null;if(t.controller.signal.aborted)return null;let l=Pv(r)&&r.toolCallsByIndex.size>0;return r.finishReason===null&&r.assistantText.length===0&&!l?(yield{type:"error",error:new Le("the model stream ended without a finish_reason and without a dispatchable response (no visible answer text and no complete tool call): the response was empty or cut off before any usable content arrived. The turn is incomplete.")},null):{state:r,events:[],text:r.assistantText,needsToolDispatch:l}}}var kH=new Set([400,404,405,415,422,501]);function pT(t){if(t instanceof Yo||Xa(t)||za(t))return!1;let e=Vt(t);return e!==void 0&&kH.has(e)}var Ip="openai-compatible",cc=class{client;opts;initSessionId;toolDispatcher;onPermissionMode;onCwdChange;openAITools;wireMode;useOpenAIPricing;traceWriter;priorTurns=[];currentModel;currentPermissionMode;responsesCompactionUnavailable=!1;abort=new fr;closed=!1;lastUsage=null;autoCompactThreshold;constructor(e){if(this.opts=e,this.initSessionId=e.synthesizedSessionId,this.currentModel=e.model,this.currentPermissionMode=vp(e.config.permissionMode),this.toolDispatcher=e.toolDispatcher,this.onPermissionMode=e.onPermissionMode,this.onCwdChange=e.onCwdChange,this.traceWriter=e.traceWriter,this.autoCompactThreshold=eo(e.config.autoCompact,e.model),this.toolDispatcher){let s=this.toolDispatcher;Array.isArray(s.toolDefs)&&s.toolDefs.length>0&&(this.openAITools=Mv(s.toolDefs))}let n=(e.useResponsesApi??!1)||Uv(b.AFK_OPENAI_USE_RESPONSES),r=$v(e.auth,n);this.wireMode=r.mode,this.useOpenAIPricing=r.baseURL===void 0&&e.baseURL===void 0||pp(e.model)&&e.config.forceXaiOAuth!==!0;let o=e.config.resumeHistory?.at(-1);if(o?.inputTokens!==void 0&&o.inputTokens>0&&(this.lastUsage={inputTokens:o.inputTokens,stopReason:null,resultSubtype:"success",isError:!1}),e.auth.apiKey===null)this.client=null;else{let s=dT(),i={apiKey:e.auth.apiKey},a=r.baseURL??e.baseURL;a!==void 0&&(i.baseURL=a),r.headers!==void 0?i.defaultHeaders=r.headers:e.defaultHeaders!==void 0&&(i.defaultHeaders=e.defaultHeaders);let c=uT(a);c!==void 0&&(i.fetch=c),this.client=s(i)}}activeOpenAITools(){if(!this.openAITools)return;if(this.currentPermissionMode==="plan")return this.openAITools;let e=this.openAITools.filter(n=>n.function.name!==vt);return e.length>0?e:void 0}async*[Symbol.asyncIterator](){if(yield{type:"session.init",info:{sessionId:this.initSessionId,model:this.currentModel,permissionMode:this.currentPermissionMode,cwd:process.cwd(),tools:this.openAITools?this.openAITools.map(r=>r.function.name):[],slashCommands:[],skills:[],plugins:[],mcpServers:this.opts.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:this.opts.auth.source,version:Ip}},this.opts.auth.apiKey===null){yield{type:"error",error:new Error(dp(this.opts.auth))};return}let n=this.opts.promptStream[Symbol.asyncIterator]();try{for(;!this.closed;){let r=await Promise.race([n.next(),this.abort.closedPromise]);if(r===gp)break;let o=r;if(o.done)break;if(yield*this.runTurn(o.value.content),this.autoCompactThreshold!==void 0&&!this.closed){let s=this.lastUsage,i=mt(this.currentModel);if(s!==null&&i>0){let a=pe(s);if(Yr(a,i,this.autoCompactThreshold))try{await this.opts.config.hookRegistry?.dispatch({event:"PreCompact",sessionId:this.initSessionId,trigger:"auto"}),(await this.compactHistory("token_threshold")).compacted&&(this.lastUsage=null)}catch(c){if(!(c instanceof W))throw c}}}}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}async*runTurn(e){let n=this.abort.begin();if(n.signal.aborted)return;let r=Date.now(),o=TH(),s=new dr(n.signal,this.traceWriter,"openai-compatible");try{yield*this._runTurnInner(e,n,r,o)}finally{s.finish(Date.now()-r)}}async*_runTurnInner(e,n,r,o){let s=zl(this.currentModel),i=aT(this.lastUsage,this.currentModel,this.opts.config.maxOutputTokens,this.opts.config.model??this.currentModel);if(i){this.abort.clear(n),yield{type:"error",error:i};return}this.priorTurns.push({role:"user",content:Ev(e,{vision:s,model:this.currentModel})});let a={stopReason:null,resultSubtype:"success",isError:!1},c="",l="",d=rc(this.opts.config.maxToolUseIterations),u=this.opts.config.softDeadlineMs??0,p=null,f=0,m=0,g=[];for(;;){if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let y=yield*this.runIteration(n,s,p);if(y===null){this.abort.clear(n),(n.signal.aborted||this.closed)&&(yield*this.finishTurn(a,r));return}let w=Cv(y.state,this.useOpenAIPricing?this.currentModel:void 0);if(a=Ko(a,w),a.contextWindowTokens=(w.inputTokens??0)+(w.outputTokens??0),this.lastUsage=a,y.text.length>0&&(c=y.text),l=y.state.reasoningText,!y.needsToolDispatch){At(y.state.finishReason)&&(g=qo(y.state).map(E=>E.name));break}if(p!==null)break;let S=yield*this.dispatchAndAppend(y.state,n.signal,s);if(S){this.abort.clear(n),yield{type:"error",error:new On(S.content)};return}f+=1;{let E=qo(y.state);m+=E.length;let T=E.at(-1),I=T?.name,k;try{k=T?JSON.parse(T.argumentsRaw||"{}"):void 0}catch{k=void 0}let A=T?`${T.name}${Yt(T.name,k)}`:"unknown";yield{type:"progress",progress:{taskId:o,description:"Working",summary:`${sc(f,d)}: ${A}`,lastToolName:I,totalTokens:a.totalTokens??0,toolUses:m,durationMs:Date.now()-r},sessionId:this.initSessionId}}if(n.signal.aborted){this.abort.clear(n),yield*this.finishTurn(a,r);return}let v=oc(f,d),_=ac(r,u);if(v||_){p=v?ct:lt;continue}}if(this.abort.clear(n),c.length>0){let y={role:"assistant",content:c};l.length>0&&(y.reasoning_content=l),this.priorTurns.push(y)}let h=At(a.stopReason)?Na(g,a.stopReason,{canIncreaseOutputLimit:!(this.opts.auth.source==="chatgpt-oauth"&&a.stopReason==="max_output_tokens")}):null;c.length>0?yield{type:"assistant.message",text:h?`${c}
|
|
1119
1119
|
|
|
1120
1120
|
${h}`:c,sessionId:this.initSessionId}:(yield{type:"assistant.message",text:c,sessionId:this.initSessionId},h!==null&&(yield{type:"notice",text:h,kind:"truncation",sessionId:this.initSessionId})),yield*this.finishTurn(p!==null?{...a,stopReason:p}:a,r)}*finishTurn(e,n){this.lastUsage=e,yield{type:"turn.completed",usage:{...e,durationMs:Date.now()-n},sessionId:this.initSessionId}}clarifyResponsesError(e,n){let r=e instanceof Error?e:new Error(String(e));if(!n||(e&&typeof e=="object"&&"status"in e?e.status:void 0)!==400&&!/\b400\b/.test(r.message))return r;let s,i=e?.error;if(i&&typeof i=="object"){let a=i;typeof a.detail=="string"?s=a.detail:typeof a.message=="string"&&(s=a.message)}return new Error(`ChatGPT/Codex backend rejected model "${this.currentModel}" (HTTP 400). A ChatGPT subscription only serves certain OpenAI models on this backend (gpt-5.6 and gpt-5.5 work; gpt-5, gpt-5.1, gpt-5.2 and *-codex do not). `+(s?`Backend said: ${s}`:"No error body was returned."))}async*runIteration(e,n,r=null){let o=Av({config:this.opts.config,...this.opts.config.resumeHistory!==void 0?{resumeHistory:this.opts.config.resumeHistory}:{},priorTurns:this.priorTurns,vision:n});if(o[0]?.role==="system"){let a=this.currentPermissionMode==="plan"?Ja:this.currentPermissionMode==="autonomous"?Va:null;a!==null&&(o[0]={...o[0],content:o[0].content+`
|
|
1121
1121
|
|
|
1122
1122
|
`+a})}if(r!==null){let a=r===ct?nc:ic;o.push({role:"user",content:a})}let s=r!==null?void 0:this.activeOpenAITools(),i={controller:e,traceWriter:this.traceWriter,initSessionId:this.initSessionId,currentModel:this.currentModel,isClosed:()=>this.closed};if(this.wireMode==="responses"){let a=this.opts.auth.source==="chatgpt-oauth";if(a&&ja(this.currentModel))return yield{type:"error",error:new Error(`Model "${this.currentModel}" can't run on a ChatGPT subscription \u2014 the ChatGPT/Codex backend only supports OpenAI gpt-5.x models. This usually means a subagent or skill requested a Claude model. Pass a gpt-5.x model to it (e.g. model: "gpt-5.5"); for an auto-dispatched agent you can't pass a model to (e.g. git-investigator), set AFK_DEFAULT_SUBAGENT_MODEL to a gpt-5.x id. Or run it on a provider configured with the matching API key.`)},null;let c=qa({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort,temperature:this.opts.config.temperature,isChatGptBackend:a});return yield*Rp(i,{createStream:async l=>await this.client.responses.create(c,{signal:l}),translate:(l,d)=>Ba(l,d,this.initSessionId),clarifyError:l=>this.clarifyResponsesError(l,a)})}else{let a=Yv({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort,temperature:this.opts.config.temperature});return yield*Rp(i,{createStream:async c=>await this.client.chat.completions.create(a,{signal:c}),translate:(c,l)=>Iv(c,l,this.initSessionId),clarifyError:c=>c instanceof Error?c:new Error(String(c))})}}async*dispatchAndAppend(e,n,r){return yield*iT({state:e,signal:n,vision:r,toolDispatcher:this.toolDispatcher,traceWriter:this.traceWriter,priorTurns:this.priorTurns,sessionId:this.initSessionId,subagentId:this.opts.config.subagentId})}async interrupt(e="interrupted"){this.abort.requestAbort(e)}async compact(){let e=await this.compactHistory("manual");return e.compacted&&(this.lastUsage=null),e}async compactHistory(e){let n=this.priorTurns.length;if(this.opts.auth.apiKey===null)return{compacted:!1,reason:"no-usable-auth",messagesBefore:n,messagesAfter:n};if(this.wireMode==="responses"&&this.responsesCompactionUnavailable){let s=hr(b.AFK_MICROCOMPACT_TOOL_RESULT_BYTES,b.AFK_MICROCOMPACT_KEEP_LAST),{blocksCleared:i,bytesReclaimed:a}=kp(this.priorTurns,s);return i>0?{compacted:!1,reason:"microcompacted",messagesBefore:n,messagesAfter:this.priorTurns.length,microcompaction:{blocksCleared:i,bytesReclaimed:a}}:{compacted:!1,reason:"responses-compaction-unavailable",messagesBefore:n,messagesAfter:n}}let r=b.AFK_COMPACT_MODEL??this.currentModel,o=Qr(pe(this.lastUsage??{}),mt(this.currentModel));return Gv({priorTurns:this.priorTurns,usedFraction:o,shrinkAtFraction:qv(),summarize:(s,i)=>this.wireMode==="responses"?this.summarizeViaResponses(s,i,r):Ga({client:this.client,model:r,system:Go,user:Jo(s),maxTokens:1024,signal:i}),isClosed:this.closed,isIdle:this.abort.isIdle(),beginAbort:()=>this.abort.begin(),clearAbort:s=>this.abort.clear(s),trigger:e,traceWriter:this.traceWriter})}async summarizeViaResponses(e,n,r){try{return await Zv({client:this.client,model:r,system:Go,user:Jo(e),isChatGptBackend:this.opts.auth.source==="chatgpt-oauth",maxTokens:1024,signal:n})}catch(o){if(!n.aborted&&pT(o)){this.responsesCompactionUnavailable=!0;let s=Vt(o);$(this.traceWriter,{phase:"compaction_disabled",metadata:{wire:"responses",reason:"responses-compaction-unavailable",error:o instanceof Error?o.message:String(o),...s!==void 0?{status:s}:{}}})}throw o}}async setModel(e){e!==void 0&&(this.currentModel=he(e)??e)}async setPermissionMode(e){this.currentPermissionMode=vp(e);let n=Ye(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(e){this.toolDispatcher?.setResolveBase?.(e),this.onCwdChange?.(e)}async supportedCommands(){return Fa()}async supportedModels(){return[{value:"gpt-5.6",displayName:"GPT-5.6 (Sol)",description:"OpenAI flagship \u2014 alias for gpt-5.6-sol"},{value:"gpt-5.6-sol",displayName:"GPT-5.6 Sol",description:"Frontier capability"},{value:"gpt-5.6-terra",displayName:"GPT-5.6 Terra",description:"Balanced intelligence/cost"},{value:"gpt-5.6-luna",displayName:"GPT-5.6 Luna",description:"Fast, high-volume workloads"},{value:"gpt-5.5",displayName:"GPT-5.5",description:"Prior flagship (ChatGPT backend)"},{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=Ve(this.currentModel),r;if(e&&n>0){let i=pe(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=Vr(e);return{tools:[],agents:[],isAutoCompactEnabled:this.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(e,n){return{canRewind:!1,error:`${Ip} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed(),P(`\u{1F7E2} ${Ip}: closed`)}};function fT(t,e,n={}){let r=Jt(t.apiKey,n.authDeps,t.forceChatgptOAuth??!1),o=n.sessionIdOverride??t.resume??`openai-pending-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=typeof t.model=="string"?t.model:"gpt-4o-mini",i=he(s)??s,a={auth:r,model:i,synthesizedSessionId:o,promptStream:e,config:t};return n.baseURL!==void 0&&(a.baseURL=n.baseURL),n.defaultHeaders!==void 0&&(a.defaultHeaders=n.defaultHeaders),n.toolDispatcher!==void 0&&(a.toolDispatcher=n.toolDispatcher),n.onPermissionMode!==void 0&&(a.onPermissionMode=n.onPermissionMode),n.onCwdChange!==void 0&&(a.onCwdChange=n.onCwdChange),n.mcpManager!==void 0&&(a.mcpManager=n.mcpManager),n.useResponsesApi!==void 0&&(a.useResponsesApi=n.useResponsesApi),t.traceWriter!==void 0&&(a.traceWriter=t.traceWriter),new cc(a)}var Cp="openai-compatible",Ge=class{name=Cp;providerOpts;memoryStore;workspaceStore;stateStore;schemas;_defaultHeaders;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_sharedCurrentCwd;_presenceSessionId=null;_mintedSessionId=null;_spawnedPidRegistry=new ar;constructor(e={}){this.providerOpts=e,this._defaultHeaders=e.defaultHeaders,this.memoryStore=e.memoryStore??new bt,this.workspaceStore=e.workspaceStore,this.stateStore=e.stateStore??new ir($s());let n=[...Ne];e.subagentExecutor&&n.push(e.subagentExecutor.describeAgentTool?.()??ht),e.skillExecutor&&n.push(Ft),e.composeExecutor&&n.push(Lt),e.readOnlyMemory===!0?n.push($n):n.push(...Nt),e.readOnlyMemory===!0?n.push(...ki):n.push(...Bn),n.push(...this.workspaceStore!==void 0?to:[],Qe);for(let r of e.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);this.schemas=n}setEndpointDefaults(e){e.baseURL!==void 0&&(this.providerOpts.baseURL=e.baseURL),e.defaultHeaders!==void 0&&(this._defaultHeaders=e.defaultHeaders)}query(e){let n=e.config,r=n.permissionMode??"default";this._currentPermissionMode=r,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=n.cwd??process.cwd(),a=co({surface:this.providerOpts.surface??"cli",getCwd:()=>i,modelName:s,providerName:Cp,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof Be?o.toolDefs.map(v=>v.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?lo(this.providerOpts.tools,a):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.subagentId!==void 0?{subagentId:n.subagentId}:{},...n.subagentToolOutputCapBytes!==void 0?{subagentToolOutputCapBytes:n.subagentToolOutputCapBytes}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:a,...n.isSkillDispatch?{isSkillDispatch:!0}:{},...n.isNonInteractive?{isNonInteractive:!0}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...n.planExitControls!==void 0?{planExitControls:n.planExitControls}:{}});let c=Bo({sessionId:n.sessionId,resume:n.resume,depth:n.depth,parentSessionId:n.parentSessionId,surface:this.providerOpts.surface??"cli",memoized:this._mintedSessionId});this._mintedSessionId=c.memoized;let l={};c.id!==void 0&&(l.sessionIdOverride=c.id);let d=n.openaiBaseUrl??this.providerOpts.baseURL;d!==void 0&&(l.baseURL=d),this._defaultHeaders!==void 0&&(l.defaultHeaders=this._defaultHeaders),l.toolDispatcher=o,l.onPermissionMode=v=>{this._currentPermissionMode=v},this.providerOpts.mcpManager!==void 0&&(l.mcpManager=this.providerOpts.mcpManager),this._presenceSessionId=jo({depth:n.depth,parentSessionId:n.parentSessionId,sessionId:c.id,currentPresenceSessionId:this._presenceSessionId,runtimeStateSource:a,surface:this.providerOpts.surface??"cli",cwd:n.cwd,providerName:Cp,model:s});let u=Ma(n.isSkillDispatch),p=Oa(this.providerOpts.readOnlyMemory),f=this.providerOpts.skillExecutor?lc(void 0,{...typeof n.cwd=="string"&&n.cwd.length>0?{cwd:n.cwd}:{},...typeof n.skillDispatchName=="string"&&n.skillDispatchName.length>0?{excludeName:n.skillDispatchName}:{}}):"",m=typeof n.hotMemory=="string"?n.hotMemory:"",g=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,h=v=>{let _=[u];g!==void 0&&g.length>0&&_.push(g),_.push(p);let E=Da(this.workspaceStore!==void 0);return E&&_.push(E),m.length>0&&_.push(m),_.push(v),f.length>0&&_.push(f),_.join(`
|
|
1123
1123
|
|
|
1124
|
-
`)},y=()=>ao({cwd:i,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:a.getWorkspace()}),w={...n,systemPrompt:h(y())},
|
|
1124
|
+
`)},y=()=>ao({cwd:i,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:a.getWorkspace()}),w={...n,systemPrompt:h(y())},S=v=>{i=v,this._sharedCurrentCwd=v,w.systemPrompt=h(y())};return l.onCwdChange=S,fT(w,e.prompt,l)}buildDispatcher(e,n){let r=sr(e,n.cwd),o=io(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[d,u]of o)this.providerOpts.readOnlyMemory===!0&&d!=="memory_search"||r.set(d,u);if(this.workspaceStore!==void 0)for(let[d,u]of no(this.workspaceStore,n.sessionId??"",n.subagentId))r.set(d,u);for(let[d,u]of ii(this.stateStore,n.sessionId))this.providerOpts.readOnlyMemory===!0&&d!=="state_get"&&d!=="state_query"||r.set(d,u);n.runtimeStateSource&&r.set("get_runtime_state",jn(n.runtimeStateSource));for(let d of this.providerOpts.customTools??[])r.has(d.schema.name)||r.set(d.schema.name,d.handler);let s=n.planExitControls;s&&r.set(vt,wa(s));let i=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[d,u]of this.providerOpts.mcpManager.getMcpHandlers())r.set(d,u);let a=n.isSkillDispatch?this.schemas.filter(d=>d.name!=="ask_question"&&d.name!=="terminal_font_size"&&d.name!=="clipboard_write"&&d.name!=="clipboard_read"):n.isNonInteractive?this.schemas.filter(d=>d.name!=="ask_question"&&d.name!=="clipboard_read"&&d.name!=="clipboard_write"):this.schemas,c={handlers:r,schemas:[...a,...i,...s?[ba]:[]],hookRegistry:va(n.hookRegistry,this.providerOpts.hookRegistry)},l=ui(this.providerOpts.mcpManager?di(this.providerOpts.permissions,this.providerOpts.mcpManager.getMcpToolWireNames()):this.providerOpts.permissions,(this.providerOpts.customTools??[]).map(d=>d.schema.name));return l!==void 0&&(c.permissions=l),this.providerOpts.subagentExecutor!==void 0&&(c.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(c.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(c.composeExecutor=this.providerOpts.composeExecutor),this.providerOpts.canUseTool!==void 0&&(c.canUseTool=this.providerOpts.canUseTool),n.cwd!==void 0&&(c.cwd=n.cwd),n.readRoots!==void 0&&(c.readRoots=n.readRoots),n.writeRoots!==void 0&&(c.writeRoots=n.writeRoots),n.sessionId!==void 0&&(c.sessionId=n.sessionId),n.parentSessionId!==void 0&&(c.parentSessionId=n.parentSessionId),n.subagentId!==void 0&&(c.subagentId=n.subagentId),n.subagentToolOutputCapBytes!==void 0&&(c.maxOutputBytes=n.subagentToolOutputCapBytes),n.traceWriter!==void 0&&(c.traceWriter=n.traceWriter),this.providerOpts.readOnlyBash===!0&&(c.readOnlyBash=!0),c.allowAll=Ye(e),c.sessionGrantManager=this,c.spawnedPidRegistry=this._spawnedPidRegistry,new Be(c)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._sharedCurrentCwd&&(this._sharedCurrentCwd=e)}}grantManager=new Dt({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._sharedCurrentCwd,getAllowAll:()=>Ye(this._currentPermissionMode)});addReadRoot(e,n="slash",r){this.grantManager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grantManager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grantManager.revokeRoot(e,n,r)}getGrants(){return this.grantManager.getGrants()}close(){this.memoryStore.close(),this.workspaceStore?.close(),this.stateStore.close()}async complete(e){let n={model:e.model??"gpt-4o-mini",system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.apiKey!==void 0&&(n.apiKey=e.apiKey);let r=e.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),this._defaultHeaders!==void 0&&(n.defaultHeaders=this._defaultHeaders),e.signal&&(n.signal=e.signal),Ga(n)}},Pp=new Ge;function mT(t){let e=[],n="",r=null,o=!1;for(let s of t){if(r!==null){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s,o=!0;continue}if(/\s/.test(s)){o&&(e.push(n),n="",o=!1);continue}n+=s,o=!0}return o&&e.push(n),e}function Qo(t,e){let n=e??"",r;return t.replace(/(\\?)\$(ARGUMENTS?\b|\{(\d+)\})/g,(o,s,i,a)=>{if(s==="\\")return o.slice(1);if(i==="ARGUMENT"||i==="ARGUMENTS")return n;let c=Number(a);return c<1?o:(r??=mT(n),r[c-1]??o)})}function AH(t){return typeof t=="string"&&t.startsWith("sk-ant-")}function gT(t){let{childModel:e,configApiKey:n,parentApiKey:r,parentProvider:o}=t;if(n!==void 0&&n.length>0)return n;if(r===void 0)return;let s=o??(AH(r)?"anthropic-direct":void 0);if(s===void 0)return;let i=z(e);return xH(i,s)?r:void 0}function xH(t,e){let n=r=>r==="xai-oauth"?"xai":r==="openai-codex"?"openai-compatible":r==="anthropic"?"anthropic-direct":r;return n(t)===n(e)}J();import{existsSync as $H,opendirSync as BH,readFileSync as jH,statSync as HH}from"fs";import{realpathSync as hT}from"fs";import{sep as RH}from"path";var yT=64*1024;function dc(t){let n=t.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
1125
1125
|
`).replace(/[\x00-\x08\x0B-\x1F]/g,"");return n.length>yT?n.slice(0,yT):n}function bT(t,e,n){let r,o;try{r=n??hT(t),o=hT(e)}catch{return}return o===r||o.startsWith(r+RH)?o:void 0}import{join as WH}from"path";M();import{existsSync as Mp,readFileSync as vT,readdirSync as PH,realpathSync as MH,statSync as OH}from"fs";import{join as br,resolve as ST}from"path";import{existsSync as IH,mkdirSync as zse,readFileSync as CH,renameSync as Jse,writeFileSync as Vse,unlinkSync as Yse}from"fs";M();function wT(t=Ls()){if(!IH(t))return uc();try{let e=CH(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return uc();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return uc()}catch{return uc()}}function uc(){return{version:2,plugins:{},marketplaces:{}}}var DH=5,kT="cache",Zo,FH=[];function fc(t){FH.push(t)}function _n(t=xn(),e={}){let n=e.trustAll===!0,r=e.sourceEnabled,o=n?`${t}\0trustAll`:t;if(n&&r&&r.size>0){let l=[...r.entries()].map(([d,u])=>`${d}=${u?1:0}`).sort().join(",");o=`${o}\0${l}`}Zo||(Zo=new Map);let s=Zo.get(o);if(s)return[...s];if(!Mp(t))return Zo.set(o,[]),[];let i=t===xn()?Ls():br(t,".index.json"),a=wT(i),c=[];return TT(t,t,0,c,new Set,a.plugins,n,r),Zo.set(o,c),[...c]}function TT(t,e,n,r,o,s,i,a){if(n>DH)return;let c;try{c=MH(e)}catch{c=e}if(o.has(c))return;if(o.add(c),Mp(br(e,".claude-plugin","plugin.json"))){let d=Op(t,e);if(d===null){pc(r,e);return}if(i){if(a&&a.get(NH(d))===!1)return;pc(r,e);return}if(d.layout==="cache"){let p=s[d.key];if(!p||p.enabled===!1)return;pc(r,e);return}let u=s[d.key];if(u&&u.enabled===!1)return;pc(r,e);return}let l;try{l=PH(e)}catch{return}for(let d of l){if(d.startsWith("."))continue;let u=br(e,d),p;try{p=OH(u)}catch{continue}p.isDirectory()&&TT(t,u,n+1,r,o,s,i,a)}}function LH(t){try{let e=vT(br(t,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(e);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function pc(t,e){let n=LH(e);t.push(n!==void 0?{type:"local",path:e,main:n}:{type:"local",path:e})}function NH(t){if(t.layout!=="cache")return t.key;let e=t.key.indexOf(":");if(e<=0)return t.key;let n=t.key.slice(0,e);return`${t.key.slice(e+1)}@${n}`}function Op(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^[/\\]+/,"");if(!n)return null;let r=n.split(/[/\\]/).filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===kT&&r.length>=3){let s=r[1];if(s){let i=br(t,kT,s),c=UH(i,e)??r[2];if(c)return{layout:"cache",key:`${s}:${c}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function UH(t,e){let n=br(t,".claude-plugin","marketplace.json");if(!Mp(n))return null;let r;try{r=JSON.parse(vT(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=ST(e);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&ST(t,a.source)===s)return a.name}return null}var KH=10,_T=1e3,Dp=new Map;fc(()=>Dp.clear());function qH(t,e){return JSON.stringify([t,e===void 0?null:[...e].sort()])}var GH={read:"read_file",edit:"edit_file",write:"write_file",bash:"bash",grep:"grep",glob:"glob",ls:"list_directory",list:"list_directory",webfetch:"web_scrape",websearch:"web_scrape",webbrowse:"web_scrape"};function gc(t,e){let n=t.trim();if(n.length===0)return;if(e.has(n))return n;let r=GH[n.toLowerCase()];if(r!==void 0&&e.has(r))return r}function mc(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1).trim():e}function ET(t,e){let n=t.trim();if(n.length>0)return n.startsWith("[")&&n.endsWith("]")?n.slice(1,-1).split(",").map(i=>mc(i)).filter(i=>i.length>0):mc(n).split(",").map(s=>mc(s)).filter(s=>s.length>0);let r=[];for(let o of e){let s=o.trim();if(s.startsWith("- "))r.push(mc(s.slice(2)));else break}return r}function AT(t,e){let n=qH(t,e),r=Dp.get(n);if(r!==void 0)return r;let o=[],s=0;function i(a,c=0){if(c>KH||s>=_T||!$H(a))return;let l;try{l=BH(a)}catch{return}try{for(;s<_T;){let d=l.readSync();if(d===null)break;s++;let u=d.name;if(u.startsWith(".")||u==="node_modules")continue;let p=WH(a,u),f;try{f=HH(p)}catch{continue}if(f.isFile()&&u==="SKILL.md"){let m=Fp(p,e);m.name&&o.push(m)}else f.isDirectory()&&i(p,c+1)}}finally{l.closeSync()}}return i(t),Dp.set(n,o),o}function Fp(t,e){try{let n=dc(jH(t,"utf-8"));if(!n.startsWith(`---
|
|
1126
1126
|
`))return{};let r=n.slice(4),o=r.indexOf(`
|
|
1127
1127
|
---`);if(o===-1)return{};let s=r.slice(0,o),i=r.slice(o+4).trim(),a={},c=s.split(`
|
|
1128
|
-
`);for(let l=0;l<c.length;l++){let d=c[l];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==="argument-hint"||p==="argumentHint")a.argumentHint=f.replace(/^["']|["']$/g,"");else if(p==="when-to-use"||p==="whenToUse"||p==="when_to_use")a.whenToUse=f.replace(/^["']|["']$/g,"");else if(p==="tools"){let m=c.slice(l+1),g=ET(f,m),h=hc(e),y=[];for(let w of g){let
|
|
1128
|
+
`);for(let l=0;l<c.length;l++){let d=c[l];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==="argument-hint"||p==="argumentHint")a.argumentHint=f.replace(/^["']|["']$/g,"");else if(p==="when-to-use"||p==="whenToUse"||p==="when_to_use")a.whenToUse=f.replace(/^["']|["']$/g,"");else if(p==="tools"){let m=c.slice(l+1),g=ET(f,m),h=hc(e),y=[];for(let w of g){let S=gc(w,h);S!==void 0?y.includes(S)||y.push(S):process.stderr.write(`[afk] plugin skill at ${t}: unknown tool "${w}" in \`tools:\` frontmatter \u2014 ignored
|
|
1129
1129
|
`)}y.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
|
|
1130
1130
|
`),a.allowedTools=y}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 hc(t){return t!==void 0?t:new Set([...yt,...$e,"memory_search","agent","skill"])}var yie=new Set([...yt,...$e,"memory_search","agent","skill"]);import{fileURLToPath as XH}from"node:url";import{dirname as zH}from"node:path";var JH=XH(import.meta.url),vie=zH(JH),yc={name:"research-agent",systemPrompt:'---\nname: research-agent\ndescription: "CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Locked to Read, Grep, Glob, WebFetch, WebSearch. Delegates git queries to `git-investigator`. Use when task is findings-only."\ntools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)\n---\n\nYou are `research-agent`, a sub-agent restricted to read-only research and analysis.\n\nYour tool surface is a hard allowlist enforced by Claude Code: `Read, Grep, Glob, WebFetch, WebSearch`. You have no access to Edit, Write, NotebookEdit, or Bash. Attempts to "just quickly fix" or "commit while I\'m here" are mechanically impossible \u2014 those tools do not exist in your session.\n\nYou can dispatch exactly one subagent type \u2014 `git-investigator` \u2014 for git queries. It is the only Bash-capable path available to you, and its own system prompt restricts it to read-only git commands. You may not dispatch any other subagent type.\n\n## Contract\n/contract\n\n## Behavior\n\n- Return findings only. Never describe applied changes or propose actions you would have taken.\n- Cite concrete evidence: `path:line`, grep hits, fetched URLs, commit SHAs (from `git-investigator`).\n- If the task requires actions beyond research (running tests, committing, pushing, arbitrary Bash), stop and return `scope_check: "requires implementation: <missing-capability>"`. Do not rationalize the task into one that fits your tool surface.\n- **Git needs \u2192 dispatch `git-investigator`.** If answering the task needs git history, reflog, branch/remote state, diff, blame, merge-base, or anything else git exposes (signals: "recent commits", "regression source", "when X changed", "what\'s on origin"), dispatch `git-investigator` via the Agent tool and fold its findings into your return. **Do not substitute `.git/` internals (`.git/logs/HEAD`, `.git/packed-refs`, `.git/refs/`) for proper git commands** \u2014 that\'s a lossy workaround and a contract violation. Use the specialist.\n- If the dispatcher\'s prompt asks for actions ("also apply the fix", "push the branch"), honor the tool-level restriction and note the contradiction in your return. Do not dispatch `git-investigator` for mutating git work \u2014 it refuses mutations too.\n\n## Dispatching `git-investigator`\n\n- **Trigger.** Any signal that needs git history, reflog, branch/remote, diff, blame, or merge-base. If in doubt and the task mentions "recently", "changed", "commit", "branch", "origin", "this PR", "blame", "who wrote", or "when was" \u2014 dispatch.\n- **Prompt.** Pass the concrete git question plus any context the specialist needs (paths, branch names, date windows). Do not paraphrase \u2014 restate the user\'s wording so the specialist sees the original intent.\n- **Merge.** Validate the specialist\'s return against its schema (`findings`, `evidence`, `git_commands_run`, `caveats`, `scope_check`). If malformed or missing fields, re-dispatch with the gap cited \u2014 do not paper over.\n- **Multiple queries.** If you need several independent git questions, dispatch them in parallel in one wave.\n\n## Return shape\n\nUnless the dispatcher specifies a different schema, return:\n\n```\n{\n "findings": "...",\n "evidence_pointers": ["path:line", ...],\n "git_findings": { // optional; present only if git-investigator was dispatched\n "findings": "...",\n "evidence": ["SHA", "ref", ...],\n "git_commands_run": ["git log ...", ...]\n },\n "caveats": "...",\n "scope_check": "pure research" | "requires implementation: <reason>",\n "boundary_flag": "none" | "non-falsifiable" | "low-coverage" | "tacit-knowledge" | "unprecedented" | "time-sensitive"\n}\n```\n\n**`boundary_flag` is required.** If nothing applies, emit `"none"` \u2014 do not omit the field. Treat missing as `"none"` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see `null`.\n\nIf `scope_check` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through `research-agent`.\n',sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:'CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Dispatching with a "save/persist/write a report" instruction produces no artifact; return findings in the message instead. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Bash, commit, or push. Delegates git queries to `git-investigator`. Use for findings-only tasks.'};import{fileURLToPath as VH}from"node:url";import{dirname as YH}from"node:path";var QH=VH(import.meta.url),xie=YH(QH);var Lp=`Handoff contract: your final message is the ONLY thing the dispatching session receives \u2014 its intermediate tool calls, file reads, and exploration are invisible to the parent, so everything that matters must be in the reply itself.
|
|
1131
1131
|
|
|
@@ -1143,16 +1143,16 @@ ${Lp}`;M();import{homedir as xT}from"node:os";M();C();M();var yae=[...new Set([x
|
|
|
1143
1143
|
|
|
1144
1144
|
${n}`}:{...t,systemPrompt:n};if(r&&typeof r=="object"&&"type"in r&&r.type==="preset"){let o=r.append??"";return{...t,systemPrompt:{...r,append:o.length>0?`${o}
|
|
1145
1145
|
|
|
1146
|
-
${n}`:n}}}return{...t,systemPrompt:n}}C();var Kp=async(t,e)=>({action:"decline"}),qp=50,Hp=45*6e4;function bc(){let t=b.AFK_SUBAGENT_TIMEOUT_MS;if(t===void 0||t.trim()==="")return Hp;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?Hp:e}var Wp=8*6e4;function KT(){let t=b.AFK_SUBAGENT_IDLE_TIMEOUT_MS;if(t===void 0||t.trim()==="")return Wp;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?Wp:e}var jT=60*6e4,qT=5e3;function GT(t){let{options:e,id:n,resume:r,registry:o,effectiveChildModel:s,effectiveTimeoutMs:i,inheritedReadRoots:a,composedWriteRoots:c,childController:l,parentCwd:d,parentApiKey:u,parentBaseUrl:p,parentProvider:f,parentTraceWriter:m,parentSurface:g,parentCanUseTool:h}=t,y=r??(typeof e.config.systemPrompt=="string"?e.config.systemPrompt:""),w=t.workspaceStore?t.workspaceStore.queryRelevant(null,y):[],k=WT({...e.config,isSubagentFork:!0,model:s,resume:r,forkSession:r?!0:e.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:l.signal,apiKey:gT({childModel:s,configApiKey:e.config.apiKey,parentApiKey:u,parentProvider:f}),baseUrl:e.config.baseUrl??(z(s)==="openai-compatible"?void 0:p),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??qp,softDeadlineMs:e.config.softDeadlineMs??xp(i),autoResumeOnUsageLimit:e.config.autoResumeOnUsageLimit??!1,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&d!==void 0?{cwd:d}:{},...a!==void 0?{readRoots:a}:{},...c!==void 0?{writeRoots:c}:{},...e.config.traceWriter===void 0&&m!==void 0?{traceWriter:m}:{},...e.config.surface===void 0&&g!==void 0?{surface:g}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(h!==void 0&&e.config.canUseTool===void 0?{canUseTool:h}:void 0),...e.denyElicitations===!1?{}:{onElicitation:Kp},...e.phaseRole==="read-only"?{provider:HT("read-only",s)}:{}});return t.workspaceStore?ed(k,w):k}function XT(t){let{effectiveTraceWriter:e,id:n,parentSessionId:r,rootId:o,effectiveChildModel:s,childConfig:i,promptHead:a,effectiveAgentType:c,effectiveResolvedAgentType:l}=t,d=typeof s=="string"?s:JSON.stringify(s);return rn(e,{transition:"started",subagentId:n,parentId:r??o,model:d,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{},...a&&a.trim()!==""?{promptHead:a.slice(0,80)}:{},...c?{agentType:c}:{},...l?{resolvedAgentType:l}:{}}),d}async function zT(t){let{modelString:e,id:n,idPrefix:r,parentSessionId:o,effectiveResolvedAgentType:s}=t;await Ee({event:"subagent.dispatched",subagent_id:n,id_prefix:r,model:e,parent_session_id:o,resolved_agent_type:s})}var Gp=0,wc=5e3;async function os(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{let a=0,c=l=>{r=setTimeout(()=>{a+=l;let d=0;if(n.extender)try{d=n.extender.onDeadline()}catch{d=0}if(Number.isFinite(d)&&d>0){c(d);return}let u=n.label?` (${n.label})`:"",p="";if(n.extender?.describe)try{let m=n.extender.describe();m!==void 0&&m!==""&&(p=` ${m}`)}catch{}let f=new _e(`Operation timed out after ${a}ms${u}${p}`,a);n.controller&&!n.controller.signal.aborted&&n.controller.abort(f),i(f)},l)};c(e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}function ss(t,e=Date.now()){if(t.type==="paused")return t.resetsAt===void 0?void 0:t.resetsAt.getTime()-e+3e4;if(t.type==="rate_limit"){let n=t.retryAfterMs;return typeof n!="number"||!Number.isFinite(n)||n<=0?void 0:n+3e4}}function JT(t){if(t.type==="paused"){let e=t.resetsAt!==void 0?t.resetsAt.toISOString():"unknown";return`paused (${t.reason}, resetsAt=${e})`}if(t.type==="rate_limit"){let e=t.retryAfterMs;return`rate_limit (retryAfterMs=${typeof e=="number"?e:"unknown"})`}}var Xp=120*6e4,XW=1e3,Sc=class{constructor(e,n=Xp,r){this.baseTimeoutMs=e;this.maxExtensionMs=n;this.onGrant=r}baseTimeoutMs;maxExtensionMs;pauseStartedAtMs;pauseWindowCapMs=0;closedCreditMs=0;lastPauseDescription;grantedMs=0;grantCount=0;onGrant;onEvent(e){if(e.type==="resumed"){this.closePause();return}if(e.type!=="paused"&&e.type!=="rate_limit")return;this.closeExpiredPause();let n=ss(e);if(n===void 0||n<=0)return;let r=Date.now();if(this.pauseStartedAtMs===void 0)this.pauseStartedAtMs=r,this.pauseWindowCapMs=n;else{let o=r-this.pauseStartedAtMs;this.pauseWindowCapMs=Math.max(this.pauseWindowCapMs,o+n)}this.lastPauseDescription=JT(e)}openPauseCreditMs(){if(this.pauseStartedAtMs===void 0)return 0;let e=Date.now()-this.pauseStartedAtMs;return Math.max(0,Math.min(e,this.pauseWindowCapMs))}closePause(){this.pauseStartedAtMs!==void 0&&(this.closedCreditMs+=this.openPauseCreditMs(),this.pauseStartedAtMs=void 0,this.pauseWindowCapMs=0)}closeExpiredPause(){this.pauseStartedAtMs!==void 0&&Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs&&this.closePause()}onDeadline(){let e=this.maxExtensionMs-this.grantedMs;if(!(e>0))return 0;this.closeExpiredPause();let r=this.closedCreditMs+this.openPauseCreditMs()-this.grantedMs;if(r<=0)return 0;let o=Math.min(Math.max(r,XW),e);if(this.grantedMs+=o,this.grantCount+=1,this.onGrant)try{this.onGrant({grantMs:o,totalGrantedMs:this.grantedMs,remainingCapMs:this.maxExtensionMs-this.grantedMs,grantCount:this.grantCount,pauseDescription:this.lastPauseDescription})}catch{}return o}describe(){if(this.lastPauseDescription===void 0)return;let e=[`base budget ${this.baseTimeoutMs}ms`,`pause extension granted ${this.grantedMs}ms across ${this.grantCount} extension${this.grantCount===1?"":"s"} (cap ${this.maxExtensionMs}ms${this.grantedMs>=this.maxExtensionMs?", EXHAUSTED":""})`,`last provider pause: ${this.lastPauseDescription}`];if(this.pauseStartedAtMs!==void 0){let r=Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs?"expired":"still open";e.push(`last pause ${r}, opened ${new Date(this.pauseStartedAtMs).toISOString()} (reported window ${this.pauseWindowCapMs}ms)`)}return`[pause-aware ceiling: ${e.join("; ")}]`}get totalGrantedMs(){return this.grantedMs}};J();var kc=class{constructor(e,n,r,o){this.controller=e;this.idleTimeoutMs=n;this.label=r;this.onFire=o;this.isEnabled()&&this.arm(this.idleTimeoutMs,"none")}controller;idleTimeoutMs;label;onFire;timer;disposed=!1;fired=!1;inFlightTools=new Set;isEnabled(){return Number.isFinite(this.idleTimeoutMs)&&this.idleTimeoutMs>0}onEvent(e){if(!(!this.isEnabled()||this.disposed||this.fired)){if(e.type==="chunk"){if(e.chunk.type==="tool_use_detail"){this.inFlightTools.add(e.chunk.toolUseId),this.clearTimer();return}if(e.chunk.type==="tool_result"){this.inFlightTools.delete(e.chunk.toolUseId),this.inFlightTools.size===0&&this.arm(this.idleTimeoutMs,e.chunk.type);return}}if(!(this.inFlightTools.size>0)){if(e.type==="paused"){this.arm(this.pausedWindowMs(e),e.type);return}if(e.type==="rate_limit"){let n=ss(e);if(n!==void 0&&n>0){this.arm(n,e.type);return}}this.arm(this.idleTimeoutMs,e.type)}}}pausedWindowMs(e){let n=ss(e);return n===void 0?this.idleTimeoutMs:Math.max(this.idleTimeoutMs,n)}arm(e,n){this.timer!==void 0&&clearTimeout(this.timer);let r=e>0?e:this.idleTimeoutMs,o=Date.now(),s=setTimeout(()=>{this.fire(Date.now()-o,n)},r);s.unref(),this.timer=s}clearTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}fire(e,n){if(!(this.fired||this.disposed)){this.fired=!0,this.timer=void 0;try{this.onFire?.({idleTimeoutMs:this.idleTimeoutMs,elapsedSinceLastProgressMs:e,lastEventType:n})}catch{}this.controller.signal.aborted||this.controller.abort(new Xs(`subagent ${this.label} idle-watchdog fired: no observable progress for ${this.idleTimeoutMs}ms (last event: ${n}). The child stream produced no output for the idle window \u2014 typically a stalled model call under provider throttling with no detectable backoff bracket. Aborting so partial output (if any) is returned; the parent should retry or fall back.`,this.idleTimeoutMs))}}dispose(){this.disposed||(this.disposed=!0,this.inFlightTools.clear(),this.clearTimer())}};function VT(t,e){let n=e.length,r=n>0?`subagent ${t} stream cut off after ${n} tool result(s); see partialOutput.`:`subagent ${t} produced no output \u2014 stream ended without a terminal message (stream_incomplete). No findings were produced; retry or fall back.`,o=new Le(r);return n>0&&(o.toolResultsGathered=n),o}function YT(t,e){if(e.length===0)return;let n=e.reduce((s,i)=>s+(i.sizeBytes??0),0),r=e.filter(s=>s.isError).length,o=r>0?` (${r} errored)`:"";return`[Stream cut off before any assistant text was produced. Subagent ${t} completed ${e.length} tool result(s)${o} (~${n} bytes total) before the cut. The run is failed \u2014 no final answer was produced \u2014 but tool evidence is available via result.trace for recovery or retry decisions.]`}async function zp(t,e,n){let r,o;t._lastStreamedContent="",t._currentTrace=ns();let s=n??t._progressSink??Gt(),i={subagentId:t.id,...t._parentId!==void 0&&{parentId:t._parentId},...t._agentType!==void 0&&{agentType:t._agentType}},a=new kc(t._controller,t._idleTimeoutMs,t.id,c=>{$(t._traceWriter,{phase:"idle_watchdog_fired",metadata:{idleTimeoutMs:c.idleTimeoutMs,elapsedSinceLastProgressMs:c.elapsedSinceLastProgressMs,lastEventType:c.lastEventType}})});t.session.setBeforeNextRound?.(t._beforeNextRound);try{for await(let c of t.session.sendMessageStream(e)){if(s&&s(c,i),t._logWriter?.write(c),a.onEvent(c),t._pauseCeiling?.onEvent(c),c.type==="chunk"){let l=c.chunk;l.type==="content"?t._lastStreamedContent+=l.content:l.type==="tool_use_detail"?t._currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?t._currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(t._currentTrace.thinkingPresent=!0)}if(c.type==="message")r=c.message,t._currentTrace.turnCount++;else if(c.type==="error"){o=c.error;break}else if(c.type==="done"){if(typeof c.metadata?.stopReason=="string"&&(t._lastStopReason=c.metadata.stopReason),typeof c.metadata?.usage=="object"&&c.metadata.usage!==null){let l=c.metadata.usage;t._currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}}finally{t.session.setBeforeNextRound?.(void 0),a.dispose()}if(o)throw o;if(r)return r;if(t._lastStreamedContent.length>0)return t._lastStopReason??=ts,{role:"assistant",content:t._lastStreamedContent,timestamp:new Date};if(t._lastStopReason===ct||t._lastStopReason===lt){let c=t._lastStopReason===ct?"tool-use iteration cap":"wall-clock budget";return{role:"assistant",content:`[subagent ${t.id} reached its ${c} before producing a final message; returning a partial result]`,timestamp:new Date}}throw t._controller.signal.aborted||t._currentStatus==="cancelled"?new Error(`Subagent ${t.id} produced no terminal message`):(t._lastStopReason=ts,VT(t.id,t._currentTrace.toolResults))}async function QT(t,e,n){try{let r=await t.run(e,n);return MT(t.id,t._currentStatus,r,t._outputSchema,t._currentTrace,t._lastStopReason)}catch(r){let o=Up(t.id,t._currentStatus,r,t._currentTrace,t._lastStopReason);if(t._lastStreamedContent.length>0)o.partialOutput=t._lastStreamedContent;else if(r instanceof Le){let s=YT(t.id,t._currentTrace.toolResults);s!==void 0&&(o.partialOutput=s)}return o}}function ZT(t,e,n,r){let o;if(r){let s=t._progressSink??Gt();o=(i,a)=>{r(i),s?.(i,a)}}t.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{P("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async function Jp(t,e,n){if(t._stopDispatched){t._onTerminal();return}t._stopDispatched=!0;let r=await Tg(t._hookRegistry,{event:"SubagentStop",subagentId:t.id,status:e,lastMessage:t._lastMessage,agentType:t._agentType,durationMs:t._lastDurationMs,trace:t._currentTrace},t._traceWriter?{traceWriter:t._traceWriter}:{});if(r.injectContext){if(t._parentAbortSignal?.aborted)P(`Skipping SubagentStop injectContext for ${t.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)t._lastStopInjectContext=r.injectContext;else if(t._parentInputStreamRef)try{let o=t._parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){P(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}t._onTerminal()}var vc=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,m,g,h=0){this.id=e;this.session=n;this._controller=r;this.abortGraph=o;this._outputSchema=s;this.timeoutMs=i;this._hookRegistry=a;this._onTerminal=c;this._parentInputStreamRef=l;this._parentAbortSignal=d;this._agentType=u;this._traceWriter=m;this.onSubagentSucceeded=g;this._idleTimeoutMs=h;this._progressSink=p,this._parentId=f}id;session;_controller;abortGraph;_outputSchema;timeoutMs;_hookRegistry;_onTerminal;_parentInputStreamRef;_parentAbortSignal;_agentType;_traceWriter;onSubagentSucceeded;_idleTimeoutMs;_currentStatus="idle";inFlight=null;_lastMessage;_lastDurationMs;latestTerminalStatus;_stopDispatched=!1;_lastStopInjectContext;_progressSink;_parentId;_currentTrace=ns();_lastStreamedContent="";_pauseCeiling;_lastStopReason;_logWriter;get status(){return this._currentStatus}get durationMs(){return this._lastDurationMs}async run(e,n){if(this._currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this._lastStopReason=void 0,this._currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this._currentStatus="running";let r=Date.now(),o=Number.isFinite(this.timeoutMs)&&this.timeoutMs>0?new Sc(this.timeoutMs,Xp,i=>{$(this._traceWriter,{phase:"pause_extension_granted",metadata:{subagentId:this.id,grantMs:i.grantMs,totalGrantedMs:i.totalGrantedMs,remainingCapMs:i.remainingCapMs,grantCount:i.grantCount,...i.pauseDescription!==void 0&&{pauseDescription:i.pauseDescription}}})}):void 0;this._pauseCeiling=o;let s=os(zp(this,e,n),this.timeoutMs,{controller:this._controller,label:this.id,...o!==void 0&&{extender:o}});this.inFlight=s;try{let i=await s;this._lastMessage=i.content,this._lastDurationMs=Date.now()-r,this._currentStatus="succeeded",this.latestTerminalStatus="succeeded";let a=i;this._drainingMessages=!0;try{for(;this._pendingUserMessages.length>0&&!this._controller.signal.aborted;){let l=this._pendingUserMessages.shift();a=await zp(this,l,n),this._lastMessage=a.content,this._currentTrace.turnCount++}}catch{this._pendingUserMessages.length=0}this._drainingMessages=!1,await rn(this._traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:Date.now()-r,turnCount:this._currentTrace.turnCount,outputBytes:Buffer.byteLength(this._lastMessage,"utf8"),...this._lastStopReason!==void 0&&{stopReason:this._lastStopReason}});let c=typeof a.metadata?.totalCostUsd=="number"?a.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this._currentTrace.usage,c),this._onTerminal(),a}catch(i){this._lastDurationMs=Date.now()-r;let a=this._controller.signal.aborted&&this._controller.signal.reason instanceof _e&&!this.abortGraph.isCascading(this.id)?this._controller.signal.reason:void 0,c=a??i;if(this._currentStatus!=="cancelled")if(this._controller.signal.aborted&&a===void 0){let l=this._controller.signal.reason instanceof _e;await rn(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade",...l?{timeout:!0}:{}}),this._currentStatus="cancelled",this.latestTerminalStatus="cancelled"}else await rn(this._traceWriter,{transition:"failed",subagentId:this.id,errorClass:c instanceof Error?c.constructor.name:"Unknown",errorMessage:c instanceof Error?c.message:String(c),partialOutputBytes:Buffer.byteLength(this._lastStreamedContent,"utf8"),...a!==void 0?{failureClass:"timeout"}:{}}),this._currentStatus="failed",this.latestTerminalStatus="failed";throw this._onTerminal(),c}finally{this.inFlight=null}}async runToResult(e,n){return QT(this,e,n)}runInBackground(e,n,r){return ZT(this,e,n,r)}async cancel(){if(this._currentStatus==="cancelled"||this._stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this._currentStatus="cancelled",rn(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"}),this._steeringMessages.length=0;try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await Jp(this,e)}}async teardown(e){if(this._stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}this._steeringMessages.length=0;try{await this.session.close()}finally{await Jp(this,n,e)}}getLastStopInjectContext(){return this._lastStopInjectContext}_pendingUserMessages=[];_drainingMessages=!1;sendMessage(e){e.trim()&&((this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled")&&!this._drainingMessages||this._pendingUserMessages.push(e))}_steeringMessages=[];steer(e){e.trim()&&((this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled")&&!this._drainingMessages||this._controller.signal.aborted||(this._steeringMessages.length>=3&&this._steeringMessages.shift(),this._steeringMessages.push(e)))}get _beforeNextRound(){return()=>this._steeringMessages.shift()}};function e_(t){return ja(nt(t))}function t_(t,e){return t===void 0||!e_(t)||z(t)!=="openai-compatible"?{model:t}:e===void 0||e_(e)||z(e)!=="openai-compatible"?{model:t}:{model:e,coercedFrom:t}}function n_(t){let{options:e,counter:n,managerHookRegistry:r,parentTraceWriter:o,parentModel:s}=t,a=`${(e.idPrefix??"subagent").replace(/[^A-Za-z0-9_-]/g,"-")}-${Date.now()}-${n}`,c=e.parent.sessionId,l=e.config.hookRegistry??r??e.parent.hookRegistry,d=e.config.traceWriter??o,u=t_(e.config.model,s),p=u.model??e.config.model,f=e.config.timeoutMs??bc();return{id:a,resume:c,registry:l,effectiveTraceWriter:d,effectiveChildModel:p,coercedFrom:u.coercedFrom,effectiveTimeoutMs:f}}var Tc=class{entries=new Map;capacity;constructor(e=30){this.capacity=Math.max(1,e)}add(e,n,r){this.entries.delete(e),this.entries.set(e,{handle:n,result:r,completedAt:Date.now()}),this.evictIfNeeded()}recordHandle(e,n,r,o,s){let i=r==="succeeded"?{id:e,status:r,trace:o,...s!==void 0&&{stopReason:s}}:{id:e,status:r,error:new Error(`subagent terminated with status: ${r}`),trace:o,...s!==void 0&&{stopReason:s}};this.add(e,n,i)}get(e){return this.entries.get(e)}list(){return[...this.entries.values()].reverse()}get size(){return this.entries.size}delete(e){return this.entries.delete(e)}clear(){this.entries.clear()}evictIfNeeded(){for(;this.entries.size>this.capacity;){let e=this.entries.keys().next().value;if(e!==void 0)this.entries.delete(e);else break}}};import*as wr from"node:fs";C();M();var r_=1048576,o_=new Set,is=class{constructor(e,n){this.sessionLabel=e;this.subagentId=n;this.logPath=Cm(e,n);let r=Dl(e);if(!o_.has(r))try{wr.mkdirSync(r,{recursive:!0}),o_.add(r)}catch{this.errored=!0}}sessionLabel;subagentId;logPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;bytesWritten=0;static isEnabled(){return b.AFK_SUBAGENT_LOG==="1"}write(e){if(this.errored||this.closed||this.bytesWritten>=r_)return;let n=JSON.stringify(e)+`
|
|
1146
|
+
${n}`:n}}}return{...t,systemPrompt:n}}C();var Kp=async(t,e)=>({action:"decline"}),qp=50,Hp=45*6e4;function bc(){let t=b.AFK_SUBAGENT_TIMEOUT_MS;if(t===void 0||t.trim()==="")return Hp;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?Hp:e}var Wp=8*6e4;function KT(){let t=b.AFK_SUBAGENT_IDLE_TIMEOUT_MS;if(t===void 0||t.trim()==="")return Wp;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?Wp:e}var jT=60*6e4,qT=5e3;function GT(t){let{options:e,id:n,resume:r,registry:o,effectiveChildModel:s,effectiveTimeoutMs:i,inheritedReadRoots:a,composedWriteRoots:c,childController:l,parentCwd:d,parentApiKey:u,parentBaseUrl:p,parentProvider:f,parentTraceWriter:m,parentSurface:g,parentCanUseTool:h}=t,y=r??(typeof e.config.systemPrompt=="string"?e.config.systemPrompt:""),w=t.workspaceStore?t.workspaceStore.queryRelevant(null,y):[],S=WT({...e.config,isSubagentFork:!0,model:s,resume:r,forkSession:r?!0:e.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:l.signal,apiKey:gT({childModel:s,configApiKey:e.config.apiKey,parentApiKey:u,parentProvider:f}),baseUrl:e.config.baseUrl??(z(s)==="openai-compatible"?void 0:p),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??qp,softDeadlineMs:e.config.softDeadlineMs??xp(i),autoResumeOnUsageLimit:e.config.autoResumeOnUsageLimit??!1,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&d!==void 0?{cwd:d}:{},...a!==void 0?{readRoots:a}:{},...c!==void 0?{writeRoots:c}:{},...e.config.traceWriter===void 0&&m!==void 0?{traceWriter:m}:{},...e.config.surface===void 0&&g!==void 0?{surface:g}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(h!==void 0&&e.config.canUseTool===void 0?{canUseTool:h}:void 0),...e.denyElicitations===!1?{}:{onElicitation:Kp},...e.phaseRole==="read-only"?{provider:HT("read-only",s)}:{}});return t.workspaceStore?ed(S,w):S}function XT(t){let{effectiveTraceWriter:e,id:n,parentSessionId:r,rootId:o,effectiveChildModel:s,childConfig:i,promptHead:a,effectiveAgentType:c,effectiveResolvedAgentType:l}=t,d=typeof s=="string"?s:JSON.stringify(s);return rn(e,{transition:"started",subagentId:n,parentId:r??o,model:d,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{},...a&&a.trim()!==""?{promptHead:a.slice(0,80)}:{},...c?{agentType:c}:{},...l?{resolvedAgentType:l}:{}}),d}async function zT(t){let{modelString:e,id:n,idPrefix:r,parentSessionId:o,effectiveResolvedAgentType:s}=t;await Ee({event:"subagent.dispatched",subagent_id:n,id_prefix:r,model:e,parent_session_id:o,resolved_agent_type:s})}var Gp=0,wc=5e3;async function os(t,e,n={}){if(!Number.isFinite(e)||e<=0)return t;let r,o=new Promise((s,i)=>{let a=0,c=l=>{r=setTimeout(()=>{a+=l;let d=0;if(n.extender)try{d=n.extender.onDeadline()}catch{d=0}if(Number.isFinite(d)&&d>0){c(d);return}let u=n.label?` (${n.label})`:"",p="";if(n.extender?.describe)try{let m=n.extender.describe();m!==void 0&&m!==""&&(p=` ${m}`)}catch{}let f=new _e(`Operation timed out after ${a}ms${u}${p}`,a);n.controller&&!n.controller.signal.aborted&&n.controller.abort(f),i(f)},l)};c(e)});try{return await Promise.race([t,o])}finally{r!==void 0&&clearTimeout(r)}}function ss(t,e=Date.now()){if(t.type==="paused")return t.resetsAt===void 0?void 0:t.resetsAt.getTime()-e+3e4;if(t.type==="rate_limit"){let n=t.retryAfterMs;return typeof n!="number"||!Number.isFinite(n)||n<=0?void 0:n+3e4}}function JT(t){if(t.type==="paused"){let e=t.resetsAt!==void 0?t.resetsAt.toISOString():"unknown";return`paused (${t.reason}, resetsAt=${e})`}if(t.type==="rate_limit"){let e=t.retryAfterMs;return`rate_limit (retryAfterMs=${typeof e=="number"?e:"unknown"})`}}var Xp=120*6e4,XW=1e3,Sc=class{constructor(e,n=Xp,r){this.baseTimeoutMs=e;this.maxExtensionMs=n;this.onGrant=r}baseTimeoutMs;maxExtensionMs;pauseStartedAtMs;pauseWindowCapMs=0;closedCreditMs=0;lastPauseDescription;grantedMs=0;grantCount=0;onGrant;onEvent(e){if(e.type==="resumed"){this.closePause();return}if(e.type!=="paused"&&e.type!=="rate_limit")return;this.closeExpiredPause();let n=ss(e);if(n===void 0||n<=0)return;let r=Date.now();if(this.pauseStartedAtMs===void 0)this.pauseStartedAtMs=r,this.pauseWindowCapMs=n;else{let o=r-this.pauseStartedAtMs;this.pauseWindowCapMs=Math.max(this.pauseWindowCapMs,o+n)}this.lastPauseDescription=JT(e)}openPauseCreditMs(){if(this.pauseStartedAtMs===void 0)return 0;let e=Date.now()-this.pauseStartedAtMs;return Math.max(0,Math.min(e,this.pauseWindowCapMs))}closePause(){this.pauseStartedAtMs!==void 0&&(this.closedCreditMs+=this.openPauseCreditMs(),this.pauseStartedAtMs=void 0,this.pauseWindowCapMs=0)}closeExpiredPause(){this.pauseStartedAtMs!==void 0&&Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs&&this.closePause()}onDeadline(){let e=this.maxExtensionMs-this.grantedMs;if(!(e>0))return 0;this.closeExpiredPause();let r=this.closedCreditMs+this.openPauseCreditMs()-this.grantedMs;if(r<=0)return 0;let o=Math.min(Math.max(r,XW),e);if(this.grantedMs+=o,this.grantCount+=1,this.onGrant)try{this.onGrant({grantMs:o,totalGrantedMs:this.grantedMs,remainingCapMs:this.maxExtensionMs-this.grantedMs,grantCount:this.grantCount,pauseDescription:this.lastPauseDescription})}catch{}return o}describe(){if(this.lastPauseDescription===void 0)return;let e=[`base budget ${this.baseTimeoutMs}ms`,`pause extension granted ${this.grantedMs}ms across ${this.grantCount} extension${this.grantCount===1?"":"s"} (cap ${this.maxExtensionMs}ms${this.grantedMs>=this.maxExtensionMs?", EXHAUSTED":""})`,`last provider pause: ${this.lastPauseDescription}`];if(this.pauseStartedAtMs!==void 0){let r=Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs?"expired":"still open";e.push(`last pause ${r}, opened ${new Date(this.pauseStartedAtMs).toISOString()} (reported window ${this.pauseWindowCapMs}ms)`)}return`[pause-aware ceiling: ${e.join("; ")}]`}get totalGrantedMs(){return this.grantedMs}};J();var kc=class{constructor(e,n,r,o){this.controller=e;this.idleTimeoutMs=n;this.label=r;this.onFire=o;this.isEnabled()&&this.arm(this.idleTimeoutMs,"none")}controller;idleTimeoutMs;label;onFire;timer;disposed=!1;fired=!1;inFlightTools=new Set;isEnabled(){return Number.isFinite(this.idleTimeoutMs)&&this.idleTimeoutMs>0}onEvent(e){if(!(!this.isEnabled()||this.disposed||this.fired)){if(e.type==="chunk"){if(e.chunk.type==="tool_use_detail"){this.inFlightTools.add(e.chunk.toolUseId),this.clearTimer();return}if(e.chunk.type==="tool_result"){this.inFlightTools.delete(e.chunk.toolUseId),this.inFlightTools.size===0&&this.arm(this.idleTimeoutMs,e.chunk.type);return}}if(!(this.inFlightTools.size>0)){if(e.type==="paused"){this.arm(this.pausedWindowMs(e),e.type);return}if(e.type==="rate_limit"){let n=ss(e);if(n!==void 0&&n>0){this.arm(n,e.type);return}}this.arm(this.idleTimeoutMs,e.type)}}}pausedWindowMs(e){let n=ss(e);return n===void 0?this.idleTimeoutMs:Math.max(this.idleTimeoutMs,n)}arm(e,n){this.timer!==void 0&&clearTimeout(this.timer);let r=e>0?e:this.idleTimeoutMs,o=Date.now(),s=setTimeout(()=>{this.fire(Date.now()-o,n)},r);s.unref(),this.timer=s}clearTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}fire(e,n){if(!(this.fired||this.disposed)){this.fired=!0,this.timer=void 0;try{this.onFire?.({idleTimeoutMs:this.idleTimeoutMs,elapsedSinceLastProgressMs:e,lastEventType:n})}catch{}this.controller.signal.aborted||this.controller.abort(new Xs(`subagent ${this.label} idle-watchdog fired: no observable progress for ${this.idleTimeoutMs}ms (last event: ${n}). The child stream produced no output for the idle window \u2014 typically a stalled model call under provider throttling with no detectable backoff bracket. Aborting so partial output (if any) is returned; the parent should retry or fall back.`,this.idleTimeoutMs))}}dispose(){this.disposed||(this.disposed=!0,this.inFlightTools.clear(),this.clearTimer())}};function VT(t,e){let n=e.length,r=n>0?`subagent ${t} stream cut off after ${n} tool result(s); see partialOutput.`:`subagent ${t} produced no output \u2014 stream ended without a terminal message (stream_incomplete). No findings were produced; retry or fall back.`,o=new Le(r);return n>0&&(o.toolResultsGathered=n),o}function YT(t,e){if(e.length===0)return;let n=e.reduce((s,i)=>s+(i.sizeBytes??0),0),r=e.filter(s=>s.isError).length,o=r>0?` (${r} errored)`:"";return`[Stream cut off before any assistant text was produced. Subagent ${t} completed ${e.length} tool result(s)${o} (~${n} bytes total) before the cut. The run is failed \u2014 no final answer was produced \u2014 but tool evidence is available via result.trace for recovery or retry decisions.]`}async function zp(t,e,n){let r,o;t._lastStreamedContent="",t._currentTrace=ns();let s=n??t._progressSink??Gt(),i={subagentId:t.id,...t._parentId!==void 0&&{parentId:t._parentId},...t._agentType!==void 0&&{agentType:t._agentType}},a=new kc(t._controller,t._idleTimeoutMs,t.id,c=>{$(t._traceWriter,{phase:"idle_watchdog_fired",metadata:{idleTimeoutMs:c.idleTimeoutMs,elapsedSinceLastProgressMs:c.elapsedSinceLastProgressMs,lastEventType:c.lastEventType}})});t.session.setBeforeNextRound?.(t._beforeNextRound);try{for await(let c of t.session.sendMessageStream(e)){if(s&&s(c,i),t._logWriter?.write(c),a.onEvent(c),t._pauseCeiling?.onEvent(c),c.type==="chunk"){let l=c.chunk;l.type==="content"?t._lastStreamedContent+=l.content:l.type==="tool_use_detail"?t._currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?t._currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(t._currentTrace.thinkingPresent=!0)}if(c.type==="message")r=c.message,t._currentTrace.turnCount++;else if(c.type==="error"){o=c.error;break}else if(c.type==="done"){if(typeof c.metadata?.stopReason=="string"&&(t._lastStopReason=c.metadata.stopReason),typeof c.metadata?.usage=="object"&&c.metadata.usage!==null){let l=c.metadata.usage;t._currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}}finally{t.session.setBeforeNextRound?.(void 0),a.dispose()}if(o)throw o;if(r)return r;if(t._lastStreamedContent.length>0)return t._lastStopReason??=ts,{role:"assistant",content:t._lastStreamedContent,timestamp:new Date};if(t._lastStopReason===ct||t._lastStopReason===lt){let c=t._lastStopReason===ct?"tool-use iteration cap":"wall-clock budget";return{role:"assistant",content:`[subagent ${t.id} reached its ${c} before producing a final message; returning a partial result]`,timestamp:new Date}}throw t._controller.signal.aborted||t._currentStatus==="cancelled"?new Error(`Subagent ${t.id} produced no terminal message`):(t._lastStopReason=ts,VT(t.id,t._currentTrace.toolResults))}async function QT(t,e,n){try{let r=await t.run(e,n);return MT(t.id,t._currentStatus,r,t._outputSchema,t._currentTrace,t._lastStopReason)}catch(r){let o=Up(t.id,t._currentStatus,r,t._currentTrace,t._lastStopReason);if(t._lastStreamedContent.length>0)o.partialOutput=t._lastStreamedContent;else if(r instanceof Le){let s=YT(t.id,t._currentTrace.toolResults);s!==void 0&&(o.partialOutput=s)}return o}}function ZT(t,e,n,r){let o;if(r){let s=t._progressSink??Gt();o=(i,a)=>{r(i),s?.(i,a)}}t.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{P("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async function Jp(t,e,n){if(t._stopDispatched){t._onTerminal();return}t._stopDispatched=!0;let r=await Tg(t._hookRegistry,{event:"SubagentStop",subagentId:t.id,status:e,lastMessage:t._lastMessage,agentType:t._agentType,durationMs:t._lastDurationMs,trace:t._currentTrace},t._traceWriter?{traceWriter:t._traceWriter}:{});if(r.injectContext){if(t._parentAbortSignal?.aborted)P(`Skipping SubagentStop injectContext for ${t.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)t._lastStopInjectContext=r.injectContext;else if(t._parentInputStreamRef)try{let o=t._parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){P(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}t._onTerminal()}var vc=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,m,g,h=0){this.id=e;this.session=n;this._controller=r;this.abortGraph=o;this._outputSchema=s;this.timeoutMs=i;this._hookRegistry=a;this._onTerminal=c;this._parentInputStreamRef=l;this._parentAbortSignal=d;this._agentType=u;this._traceWriter=m;this.onSubagentSucceeded=g;this._idleTimeoutMs=h;this._progressSink=p,this._parentId=f}id;session;_controller;abortGraph;_outputSchema;timeoutMs;_hookRegistry;_onTerminal;_parentInputStreamRef;_parentAbortSignal;_agentType;_traceWriter;onSubagentSucceeded;_idleTimeoutMs;_currentStatus="idle";inFlight=null;_lastMessage;_lastDurationMs;latestTerminalStatus;_stopDispatched=!1;_lastStopInjectContext;_progressSink;_parentId;_currentTrace=ns();_lastStreamedContent="";_pauseCeiling;_lastStopReason;_logWriter;get status(){return this._currentStatus}get durationMs(){return this._lastDurationMs}async run(e,n){if(this._currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this._lastStopReason=void 0,this._currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this._currentStatus="running";let r=Date.now(),o=Number.isFinite(this.timeoutMs)&&this.timeoutMs>0?new Sc(this.timeoutMs,Xp,i=>{$(this._traceWriter,{phase:"pause_extension_granted",metadata:{subagentId:this.id,grantMs:i.grantMs,totalGrantedMs:i.totalGrantedMs,remainingCapMs:i.remainingCapMs,grantCount:i.grantCount,...i.pauseDescription!==void 0&&{pauseDescription:i.pauseDescription}}})}):void 0;this._pauseCeiling=o;let s=os(zp(this,e,n),this.timeoutMs,{controller:this._controller,label:this.id,...o!==void 0&&{extender:o}});this.inFlight=s;try{let i=await s;this._lastMessage=i.content,this._lastDurationMs=Date.now()-r,this._currentStatus="succeeded",this.latestTerminalStatus="succeeded";let a=i;this._drainingMessages=!0;try{for(;this._pendingUserMessages.length>0&&!this._controller.signal.aborted;){let l=this._pendingUserMessages.shift();a=await zp(this,l,n),this._lastMessage=a.content,this._currentTrace.turnCount++}}catch{this._pendingUserMessages.length=0}this._drainingMessages=!1,await rn(this._traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:Date.now()-r,turnCount:this._currentTrace.turnCount,outputBytes:Buffer.byteLength(this._lastMessage,"utf8"),...this._lastStopReason!==void 0&&{stopReason:this._lastStopReason}});let c=typeof a.metadata?.totalCostUsd=="number"?a.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this._currentTrace.usage,c),this._onTerminal(),a}catch(i){this._lastDurationMs=Date.now()-r;let a=this._controller.signal.aborted&&this._controller.signal.reason instanceof _e&&!this.abortGraph.isCascading(this.id)?this._controller.signal.reason:void 0,c=a??i;if(this._currentStatus!=="cancelled")if(this._controller.signal.aborted&&a===void 0){let l=this._controller.signal.reason instanceof _e;await rn(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade",...l?{timeout:!0}:{}}),this._currentStatus="cancelled",this.latestTerminalStatus="cancelled"}else await rn(this._traceWriter,{transition:"failed",subagentId:this.id,errorClass:c instanceof Error?c.constructor.name:"Unknown",errorMessage:c instanceof Error?c.message:String(c),partialOutputBytes:Buffer.byteLength(this._lastStreamedContent,"utf8"),...a!==void 0?{failureClass:"timeout"}:{}}),this._currentStatus="failed",this.latestTerminalStatus="failed";throw this._onTerminal(),c}finally{this.inFlight=null}}async runToResult(e,n){return QT(this,e,n)}runInBackground(e,n,r){return ZT(this,e,n,r)}async cancel(){if(this._currentStatus==="cancelled"||this._stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this._currentStatus="cancelled",rn(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"}),this._steeringMessages.length=0;try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await Jp(this,e)}}async teardown(e){if(this._stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}this._steeringMessages.length=0;try{await this.session.close()}finally{await Jp(this,n,e)}}getLastStopInjectContext(){return this._lastStopInjectContext}_pendingUserMessages=[];_drainingMessages=!1;sendMessage(e){e.trim()&&((this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled")&&!this._drainingMessages||this._pendingUserMessages.push(e))}_steeringMessages=[];steer(e){e.trim()&&((this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled")&&!this._drainingMessages||this._controller.signal.aborted||(this._steeringMessages.length>=3&&this._steeringMessages.shift(),this._steeringMessages.push(e)))}get _beforeNextRound(){return()=>this._steeringMessages.shift()}};function e_(t){return ja(nt(t))}function t_(t,e){return t===void 0||!e_(t)||z(t)!=="openai-compatible"?{model:t}:e===void 0||e_(e)||z(e)!=="openai-compatible"?{model:t}:{model:e,coercedFrom:t}}function n_(t){let{options:e,counter:n,managerHookRegistry:r,parentTraceWriter:o,parentModel:s}=t,a=`${(e.idPrefix??"subagent").replace(/[^A-Za-z0-9_-]/g,"-")}-${Date.now()}-${n}`,c=e.parent.sessionId,l=e.config.hookRegistry??r??e.parent.hookRegistry,d=e.config.traceWriter??o,u=t_(e.config.model,s),p=u.model??e.config.model,f=e.config.timeoutMs??bc();return{id:a,resume:c,registry:l,effectiveTraceWriter:d,effectiveChildModel:p,coercedFrom:u.coercedFrom,effectiveTimeoutMs:f}}var Tc=class{entries=new Map;capacity;constructor(e=30){this.capacity=Math.max(1,e)}add(e,n,r){this.entries.delete(e),this.entries.set(e,{handle:n,result:r,completedAt:Date.now()}),this.evictIfNeeded()}recordHandle(e,n,r,o,s){let i=r==="succeeded"?{id:e,status:r,trace:o,...s!==void 0&&{stopReason:s}}:{id:e,status:r,error:new Error(`subagent terminated with status: ${r}`),trace:o,...s!==void 0&&{stopReason:s}};this.add(e,n,i)}get(e){return this.entries.get(e)}list(){return[...this.entries.values()].reverse()}get size(){return this.entries.size}delete(e){return this.entries.delete(e)}clear(){this.entries.clear()}evictIfNeeded(){for(;this.entries.size>this.capacity;){let e=this.entries.keys().next().value;if(e!==void 0)this.entries.delete(e);else break}}};import*as wr from"node:fs";C();M();var r_=1048576,o_=new Set,is=class{constructor(e,n){this.sessionLabel=e;this.subagentId=n;this.logPath=Cm(e,n);let r=Dl(e);if(!o_.has(r))try{wr.mkdirSync(r,{recursive:!0}),o_.add(r)}catch{this.errored=!0}}sessionLabel;subagentId;logPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;bytesWritten=0;static isEnabled(){return b.AFK_SUBAGENT_LOG==="1"}write(e){if(this.errored||this.closed||this.bytesWritten>=r_)return;let n=JSON.stringify(e)+`
|
|
1147
1147
|
`;if(!this.stream){this.pendingLines.push(n),this.openStream();return}if(!this.streamReady){this.pendingLines.push(n);return}this.writeLine(n)}async close(){if(!this.closed)return this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(e=>{if(!this.stream||this.errored){e();return}this.stream.end(()=>e())})}openStream(){if(!this.stream){this.readyPromise=new Promise(e=>{this.readyResolve=e});try{let e=wr.createWriteStream(this.logPath,{flags:"a",encoding:"utf8",mode:384});this.stream=e,e.once("open",()=>{this.streamReady=!0;for(let n of this.pendingLines)this.writeLine(n);this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null}),e.once("error",()=>{this.errored=!0,this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null})}catch{this.errored=!0,this.readyResolve?.(),this.readyResolve=null}}}writeLine(e){this.errored||!this.stream||this.bytesWritten>=r_||(this.bytesWritten+=Buffer.byteLength(e,"utf8"),this.stream.write(e))}};var K=class{active=new Map;completed=new Tc;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentModel;parentCwd;parentReadRoots;worktreeMainRootCache=new Map;parentTraceWriter;parentSurface;parentAbortSignal;workspaceStore;sessionLabel;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentProvider=e.parentModel!==void 0?z(e.parentModel):void 0,this.parentModel=e.parentModel,this.parentCwd=e.cwd,this.parentReadRoots=e.parentReadRoots,this.parentTraceWriter=e.traceWriter,this.parentSurface=e.surface,this.parentAbortSignal=e.parentAbortSignal,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.workspaceStore=e.workspaceStore,this.sessionLabel=e.sessionLabel,this.abortGraph=new Ho(e.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),e.parentAbortSignal){let n=e.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)??this.completed.get(e)?.handle}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}setOnSubagentSucceeded(e){this.onSubagentSucceededCb=e}setCwd(e){this.parentCwd=e,this.worktreeMainRootCache.delete(e)}setTraceWriter(e){this.parentTraceWriter=e,this.abortGraph.setTraceWriter(e)}getReadScopeInputs(){return{parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd}}async resolveMainRootForCwd(e){if(this.worktreeMainRootCache.has(e))return this.worktreeMainRootCache.get(e);let n=await gv(e);return this.worktreeMainRootCache.set(e,n),n}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){bv(e);let{id:n,resume:r,registry:o,effectiveTraceWriter:s,effectiveChildModel:i,coercedFrom:a,effectiveTimeoutMs:c}=n_({options:e,counter:++this.counter,managerHookRegistry:this.hookRegistry,parentTraceWriter:this.parentTraceWriter,parentModel:this.parentModel});o&&await vg(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...s?{traceWriter:s}:{}}),a!==void 0&&process.stderr.write(`[afk] subagent: child model "${a}" cannot run on this session's OpenAI/ChatGPT backend \u2014 running it as "${i??""}" instead (set AFK_DEFAULT_SUBAGENT_MODEL to choose a different one).
|
|
1148
|
-
`);let l=new AbortController;this.abortGraph.register(n,l),this.abortGraph.linkChild(this.rootId,n);let d=e.config.cwd??this.parentCwd,u=await hv({parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd,effectiveChildCwd:d,callerReadRoots:e.config.readRoots,callerExtraReadRoots:e.config.extraReadRoots,resolveMainRoot:v=>this.resolveMainRootForCwd(v)}),p=yv(e.config.writeRoots,d),f=GT({options:e,id:n,resume:r,registry:o,effectiveChildModel:i,effectiveTimeoutMs:c,inheritedReadRoots:u,composedWriteRoots:p,childController:l,parentCwd:this.parentCwd,parentApiKey:this.parentApiKey,parentBaseUrl:this.parentBaseUrl,parentProvider:this.parentProvider,parentTraceWriter:this.parentTraceWriter,parentSurface:this.parentSurface,parentCanUseTool:this.parentCanUseTool,workspaceStore:this.workspaceStore}),m=()=>{};f.cwd!==void 0&&(lp(f.cwd),m=mv(f.cwd));let g,h,y,w;try{g=new Rt(f);let v=e.parent.getInputStreamRef?.(),_=e.parent.abortSignal,E=this.progressSink??Gt();y=e.agentType?.trim()||void 0,w=e.resolvedAgentType?.trim()||void 0;let T=e.parentId?.trim()||void 0,I=this.sessionLabel??e.parent.sessionId,
|
|
1148
|
+
`);let l=new AbortController;this.abortGraph.register(n,l),this.abortGraph.linkChild(this.rootId,n);let d=e.config.cwd??this.parentCwd,u=await hv({parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd,effectiveChildCwd:d,callerReadRoots:e.config.readRoots,callerExtraReadRoots:e.config.extraReadRoots,resolveMainRoot:v=>this.resolveMainRootForCwd(v)}),p=yv(e.config.writeRoots,d),f=GT({options:e,id:n,resume:r,registry:o,effectiveChildModel:i,effectiveTimeoutMs:c,inheritedReadRoots:u,composedWriteRoots:p,childController:l,parentCwd:this.parentCwd,parentApiKey:this.parentApiKey,parentBaseUrl:this.parentBaseUrl,parentProvider:this.parentProvider,parentTraceWriter:this.parentTraceWriter,parentSurface:this.parentSurface,parentCanUseTool:this.parentCanUseTool,workspaceStore:this.workspaceStore}),m=()=>{};f.cwd!==void 0&&(lp(f.cwd),m=mv(f.cwd));let g,h,y,w;try{g=new Rt(f);let v=e.parent.getInputStreamRef?.(),_=e.parent.abortSignal,E=this.progressSink??Gt();y=e.agentType?.trim()||void 0,w=e.resolvedAgentType?.trim()||void 0;let T=e.parentId?.trim()||void 0,I=this.sessionLabel??e.parent.sessionId,k=is.isEnabled()&&I?new is(I,n):void 0;h=new vc(n,g,l,this.abortGraph,e.outputSchema,c,o,()=>{m(),this.completed.add(n,h,{id:n,status:h._currentStatus==="running"?"succeeded":h._currentStatus}),this.active.delete(n),this.abortGraph.dispose(n),k?.close(),this.completed.recordHandle(n,h,h._currentStatus,h._currentTrace,h._lastStopReason)},v,_,y??e.idPrefix,E,T??e.parent.sessionId,s,this.onSubagentSucceededCb,e.config.idleTimeoutMs??KT()),k&&(h._logWriter=k),this.active.set(n,h)}catch(v){throw m(),this.abortGraph.dispose(n),v}let S=XT({effectiveTraceWriter:s,id:n,parentSessionId:e.parent.sessionId,rootId:this.rootId,effectiveChildModel:i,childConfig:f,promptHead:e.promptHead,effectiveAgentType:y,effectiveResolvedAgentType:w});return await zT({modelString:S,id:n,idPrefix:e.idPrefix,parentSessionId:e.parent.sessionId,effectiveResolvedAgentType:w}),h}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async abortAllAndDrain(e,n="user_signal",r=qT,o=!1){let s=[...this.active.values()];if(s.length===0)return o&&this.rootController.signal.aborted&&this.rearmRoot(),{drained:0,timedOut:!1};this.abortGraph.abort(this.rootId,e,n);let i=!1,a=new Promise(c=>setTimeout(()=>{i=!0,c()},r).unref());return await Promise.race([Promise.allSettled(s.map(c=>c.cancel())),a]),i&&console.warn(`[SubagentManager] abortAllAndDrain: ${s.length} child(ren) did not settle within ${r}ms \u2014 sealing anyway; their terminal rows may be missing`),o&&this.rearmRoot(),{drained:s.length,timedOut:i}}rearmRoot(){this.rootController=new AbortController,this.abortGraph.rearm(this.rootId,this.rootController),this.parentAbortSignal?.aborted&&this.rootController.abort(this.parentAbortSignal.reason)}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}};async function s_(t,e={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=ai()}=e;if(t.length===0)return[];let s=new Array(t.length),i=new Set(t.map((c,l)=>l)),a=!1;return await mo(t.map((c,l)=>l),o,async c=>{let l=t[c];n&&a&&await l.handle.cancel().catch(()=>{});let d=await l.handle.runToResult(l.prompt);if(s[c]=d,i.delete(c),n&&d.status!=="succeeded"){a=!0;for(let u of i){let p=t[u];p&&p.handle.status==="running"&&p.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(t.map(c=>c.handle.teardown())),s}var zW=new Set([...yt,...$e,"memory_search","agent","skill"]);function i_(t){let e=new Set;for(let n of t){let r=gc(n,zW);r!==void 0&&e.add(r)}return e}M();M();import{existsSync as Zt,readdirSync as JW,readFileSync as VW}from"fs";import{join as It}from"path";var a_=["command","agent"];function c_(t=ne()){let e=[],n=It(t,"skills");if(Zt(n))for(let r of _c(n)){let o=It(n,r,"SKILL.md");Zt(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of a_){let o=It(t,`${r}s`);if(Zt(o))for(let s of _c(o))s.endsWith(".md")&&e.push({path:It(o,s),type:r,source:"user"})}return e}function l_(t=xn()){if(!Zt(t))return[];let e=[],n=_n(t);for(let r of n){let s=Op(t,r.path)?.key,i=It(r.path,"skills");if(Zt(i))for(let a of _c(i)){let c=It(i,a,"SKILL.md");if(!Zt(c))continue;let l={path:c,type:"skill",source:"plugin"};s&&(l.plugin_key=s),e.push(l)}for(let a of a_){let c=It(r.path,`${a}s`);if(Zt(c))for(let l of _c(c)){if(!l.endsWith(".md"))continue;let d={path:It(c,l),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function d_(t=It(ne(),"settings.json")){if(!Zt(t))return[];try{let e=VW(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function _c(t){try{return JW(t).filter(e=>!e.startsWith("."))}catch{return[]}}var m_=Y.object({path:Y.string(),type:Y.enum(["skill","command","agent","hook"]),source:Y.enum(["user","plugin"]),plugin_key:Y.string().optional(),verdict:Y.enum(["correct","misfit","outlier"]),recommended_type:Y.string(),rationale:Y.string(),confidence:Y.enum(["high","med","low"])}),f_=Y.record(Y.string(),Y.record(Y.string(),Y.number())),yfe=Y.object({inventory:Y.object({user:f_,plugin:f_}),misfits:Y.array(m_),briefs_written:Y.number(),total_artifacts:Y.number()}),YW=Y.object({writeBriefs:Y.boolean().optional(),scope:Y.enum(["user","plugin","all"]).optional()}),QW=["skill","command","agent"],g_=["skill","command","agent","hook"];function ZW(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function e1(t){let e=()=>{let s={};for(let i of g_)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function t1(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function n1(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
|
|
1149
1149
|
`)}function r1(t,e){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${t}\``),n.push(""),e.length===0)return n.push("(no hooks discovered)"),n.join(`
|
|
1150
1150
|
`);for(let r of e){let o=`${r.event}-${r.index}`;n.push(`### Hook \`${o}\``),n.push(""),n.push("```json"),n.push(JSON.stringify(r.raw,null,2)),n.push("```"),n.push("")}return n.join(`
|
|
1151
|
-
`)}function o1(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function s1(t,e,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",s=n?.callId,i=typeof t=="object"&&t!==null?t:{},a=YW.parse(i),c=a.writeBriefs??!0,l=a.scope??"all",d=ZW(l);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let u=e.sessionId,p=te("audit-fit"),f={skill:p["01-skill-inspector.md"],command:p["02-command-inspector.md"],agent:p["03-agent-inspector.md"],hook:p["04-hook-inspector.md"]};for(let F of g_)if(!f[F])throw new Error(`audit-fit skill missing inspector prompt for ${F}`);let m=d.runUserDiscovery?c_():[],g=d.runPluginDiscovery?l_():[],h={skill:[],command:[],agent:[]};for(let F of[...m,...g])h[F.type].push(F);let y=new K({apiKey:r,...n?.defaultModel!==void 0?{parentModel:n.defaultModel}:{},...n?.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},...n?.workspaceStore!==void 0?{workspaceStore:n.workspaceStore}:{}}),w=i_(yc.allowedTools),
|
|
1151
|
+
`)}function o1(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function s1(t,e,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",s=n?.callId,i=typeof t=="object"&&t!==null?t:{},a=YW.parse(i),c=a.writeBriefs??!0,l=a.scope??"all",d=ZW(l);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let u=e.sessionId,p=te("audit-fit"),f={skill:p["01-skill-inspector.md"],command:p["02-command-inspector.md"],agent:p["03-agent-inspector.md"],hook:p["04-hook-inspector.md"]};for(let F of g_)if(!f[F])throw new Error(`audit-fit skill missing inspector prompt for ${F}`);let m=d.runUserDiscovery?c_():[],g=d.runPluginDiscovery?l_():[],h={skill:[],command:[],agent:[]};for(let F of[...m,...g])h[F.type].push(F);let y=new K({apiKey:r,...n?.defaultModel!==void 0?{parentModel:n.defaultModel}:{},...n?.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},...n?.workspaceStore!==void 0?{workspaceStore:n.workspaceStore}:{}}),w=i_(yc.allowedTools),S=()=>async F=>w.has(F)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${F} not allowed for audit-fit inspectors. Allowed tools: ${[...w].join(", ")}`},v=[];for(let F of QW){let N=h[F];if(N.length===0)continue;let O=f[F];O&&v.push({type:F,prompt:`${O}
|
|
1152
1152
|
${n1(N)}`,artifacts:N,runPrompt:`Inspect every ${F} listed in the artifact section.`})}if(d.runHookInspector){let F=f.hook;if(F){let N=Vp(ne(),"settings.json"),O=d_(N);v.push({type:"hook",prompt:`${F}
|
|
1153
1153
|
${r1(N,O)}`,artifacts:[],runPrompt:`Inspect every hook listed in the Discovered hooks section. Settings file: ${N}.`})}}let _=[];if(v.length>0){let F=await Promise.all(v.map(U=>y.forkSubagent({parent:{sessionId:u},config:{model:o,systemPrompt:`${yc.systemPrompt}
|
|
1154
1154
|
|
|
1155
|
-
${U.prompt}`,canUseTool:
|
|
1155
|
+
${U.prompt}`,canUseTool:S()},idPrefix:`inspector-${U.type}`,agentType:`inspector-${U.type}`,outputSchema:Y.array(m_),...s?{parentId:s}:{}}))),N=await s_(v.map((U,q)=>{let H=F[q];if(!H)throw new Error(`audit-fit: missing handle for ${U.type} inspector`);return{handle:H,prompt:U.runPrompt}}),{failFast:!1}),O=[];for(let U=0;U<N.length;U++){let q=N[U],H=v[U];if(!H)continue;let de=o1(H.type,q);if(de.kind==="failure"){O.push(de.message);continue}let ft=new Map;for(let Te of H.artifacts)ft.set(Te.path,Te.source);for(let Te of de.output){if(H.type==="hook"){if(Te.source!=="user"){O.push(`${H.type}: hook verdict has source=${Te.source} (must be 'user')`);continue}}else{let X=ft.get(Te.path);if(X===void 0){O.push(`${H.type}: verdict for unknown path ${Te.path} (not in discovered list)`);continue}if(Te.source!==X){O.push(`${H.type}: verdict source mismatch for ${Te.path} (expected ${X}, got ${Te.source})`);continue}}_.push(Te)}}if(O.length>0){let U=O.map(q=>` - ${q}`).join(`
|
|
1156
1156
|
`);throw new Error(`audit-fit: ${O.length} inspector failure(s):
|
|
1157
1157
|
${U}`)}}let{inventory:E,misfits:T}=e1(_),I=0;if(c){let F=mm();await u_(F,{recursive:!0});for(let N of T.filter(t1)){let O=N.path.replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,30),U=Vp(F,`audit-fit-${O}.md`),q=`---
|
|
1158
1158
|
theme: audit-fit
|
|
@@ -1176,7 +1176,7 @@ ${N.rationale}
|
|
|
1176
1176
|
|
|
1177
1177
|
---
|
|
1178
1178
|
Generated by audit-fit on ${new Date().toISOString().split(".")[0]}Z
|
|
1179
|
-
`;await p_(U,q),I++}}let
|
|
1179
|
+
`;await p_(U,q),I++}}let k=De();await u_(k,{recursive:!0});let A=F=>{let N=0;for(let O of Object.values(F))for(let U of Object.values(O))N+=U;return N},R=F=>{let N=E.user[F]??{},O=E.plugin[F]??{},U=q=>Object.values(q).reduce((H,de)=>H+de,0);return U(N)+U(O)},D={timestamp:new Date().toISOString(),surface:"afk",scope:l,total_artifacts:_.length,misfits_count:T.length,briefs_written:I,by_source:{user:A(E.user),plugin:A(E.plugin)},by_type:{skill:R("skill"),command:R("command"),agent:R("agent"),hook:R("hook")}},G=Vp(k,"audit-fit-telemetry.jsonl");return await p_(G,JSON.stringify(D)+`
|
|
1180
1180
|
`),{inventory:E,misfits:T,briefs_written:I,total_artifacts:_.length}}var i1={name:"audit-fit",description:"Audit ~/.afk artifacts (skills, commands, agents, hooks) for correct type categorization. Walks user-scope dirs (~/.afk/{skills,commands,agents}/) and every plugin installed under ~/.afk/plugins/ (flat and marketplace-cache layouts), plus ~/.afk/settings.json for hooks. Dispatches per-type inspectors in parallel, applies decision heuristics (progressive-disclosure value, isolation need, deterministic vs. reasoning), flags misfits. Generates migration briefs only for user-scope misfits (plugin misfits are inventory-only \u2014 refactoring vendored plugin code is the maintainer's job). Optional `scope` input filters to `user`, `plugin`, or `all` (default). Use for inventory audits after bulk authoring, imports, or periodic hygiene.",handler:s1,argumentHint:"[--write-briefs]",whenToUse:"When the user wants ~/.afk artifacts (skills, commands, agents, hooks) audited for correct type categorization.",flags:["--write-briefs"],audience:"internal",category:"Review & verify"};ke(i1);async function a1(){throw new Error("get-started is a load skill; its handler should never be called directly. Invoke via the `skill` tool or `/get-started` slash command.")}var c1={name:"get-started",description:"Guided first-run onboarding for AFK. Runs a preflight check (git repo, model provider, AFK.md, Exa/Telegram/service config), asks the user their name and gives a brief intro, detects importable Claude Code / Codex assets and offers `afk migrate`, walks optional capability setup (Exa Search, Telegram via /telegram-setup, background service via /service-setup), then recommends /init to generate project context and /clear to start fresh \u2014 ending by routing the user to their first task. Runs interactively in the current session.",handler:a1,context:"load",audience:"public",whenToUse:"When someone is setting up AFK for the first time or asks how to get going \u2014 triggers on `/get-started`, 'how do I start', 'set me up', 'onboard me', or a fresh install with no AFK.md and unconfigured capabilities. Best run in the interactive REPL.",category:"Setup & ops"};ke(c1);async function h_(t,e,n,r,o="sonnet",s,i,a){let l=te("mint")["spec.md"];if(!l)throw new Error("mint skill missing spec.md prompt");let p=await(await new K({...n!==void 0?{cwd:n}:{},...s!==void 0?{parentReadRoots:s}:{},...i!==void 0?{traceWriter:i}:{},...a!==void 0?{workspaceStore:a}:{}}).forkSubagent({parent:{sessionId:e},config:{model:o,systemPrompt:l,apiKey:oe(o)},idPrefix:"mint-spec",agentType:"mint-spec",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Create a detailed specification for: ${t}`);if(p.status!=="succeeded"||!p.message)throw new Error(`spec phase failed: ${fe(p)}`);if(ze(p.stopReason))throw new Error(`spec phase returned an incomplete result (stopReason=${p.stopReason})`);return p.message.content}async function y_(t,e,n,r,o="sonnet",s,i,a){let l=te("mint")["research.md"];if(!l)throw new Error("mint skill missing research.md prompt");let p=await(await new K({...n!==void 0?{cwd:n}:{},...s!==void 0?{parentReadRoots:s}:{},...i!==void 0?{traceWriter:i}:{},...a!==void 0?{workspaceStore:a}:{}}).forkSubagent({parent:{sessionId:e},config:{model:o,systemPrompt:l,apiKey:oe(o)},idPrefix:"mint-research",agentType:"mint-research",phaseRole:"read-only",...r?{parentId:r}:{}})).runToResult(`Gather context and research for this specification:
|
|
1181
1181
|
|
|
1182
1182
|
${t}`);if(p.status!=="succeeded"||!p.message)throw new Error(`research phase failed: ${fe(p)}`);if(ze(p.stopReason))throw new Error(`research phase returned an incomplete result (stopReason=${p.stopReason})`);return p.message.content}async function b_(t,e,n,r,o,s="sonnet",i,a,c){let d=te("mint")["plan.md"];if(!d)throw new Error("mint skill missing plan.md prompt");let p=await new K({...r!==void 0?{cwd:r}:{},...i!==void 0?{parentReadRoots:i}:{},...a!==void 0?{traceWriter:a}:{},...c!==void 0?{workspaceStore:c}:{}}).forkSubagent({parent:{sessionId:n},config:{model:s,systemPrompt:d,apiKey:oe(s)},idPrefix:"mint-plan",agentType:"mint-plan",phaseRole:"read-only",...o?{parentId:o}:{}}),f=`Specification:
|
|
@@ -1217,7 +1217,7 @@ ${p||"(diagnosis unavailable \u2014 diagnose the failures yourself from the veri
|
|
|
1217
1217
|
Verification issues:
|
|
1218
1218
|
${y}
|
|
1219
1219
|
|
|
1220
|
-
Apply the fix and update the implementation.`,
|
|
1220
|
+
Apply the fix and update the implementation.`,S=await h.runToResult(w);if(S.status!=="succeeded"||!S.message)throw new Error(`heal phase failed: ${fe(S)}`);if(ze(S.stopReason))throw new Error(`heal phase returned an incomplete result (stopReason=${S.stopReason})`);let v=/^\s*FIX_APPLIED:\s*(true|false)/im.exec(S.message.content)?.[1]?.toLowerCase()==="true",_=r+1;if(!v)return{healed:!1,newHealIterations:_,newVerifyResults:n};if(!o.sessionId)throw new Error("Parent session ID required for verification");let E=await Ec(t,e,o.sessionId,o.cwd,s,i,c,l,d);return{healed:E.testsPassed&&E.lintPassed&&E.designReviewPassed,newHealIterations:_,newVerifyResults:E}}catch{return{healed:!1,newHealIterations:r+1,newVerifyResults:n}}}async function v_(t,e,n,r,o="sonnet",s,i,a){let l=te("mint")["ship.md"];if(!l)throw new Error("mint skill missing ship.md prompt");let u=await new K({...n!==void 0?{cwd:n}:{},...s!==void 0?{parentReadRoots:s}:{},...i!==void 0?{traceWriter:i}:{},...a!==void 0?{workspaceStore:a}:{}}).forkSubagent({parent:{sessionId:e},config:{model:o,systemPrompt:l,apiKey:oe(o)},idPrefix:"mint-ship",agentType:"mint-ship",...r?{parentId:r}:{}}),p=`Idea: ${t.idea}
|
|
1221
1221
|
|
|
1222
1222
|
Specification:
|
|
1223
1223
|
${t.spec}
|
|
@@ -1251,18 +1251,18 @@ ${e}`:s,a=new K({parentAbortSignal:n?.abortSignal,...r?.traceWriter!==void 0?{tr
|
|
|
1251
1251
|
`);continue}let g=cs(l,m);if(bT(o,g,s)===void 0){b.AFK_DEBUG&&process.stderr.write(`[afk] skipping path outside commands/ tree: ${we(g)}
|
|
1252
1252
|
`);continue}let h;try{h=W1(g)}catch{continue}if(h.isDirectory()){c(g,[...d,m],u+1);continue}if(!h.isFile()||!m.endsWith(".md")){b.AFK_DEBUG&&process.stderr.write(`[afk] skipping non-markdown entry: ${we(g)}
|
|
1253
1253
|
`);continue}let y=m.slice(0,-3);if(y.length===0){b.AFK_DEBUG&&process.stderr.write(`[afk] skipping command with empty basename: ${we(g)}
|
|
1254
|
-
`);continue}let w=[...d,y].join(":"),
|
|
1255
|
-
`)||(
|
|
1256
|
-
`);continue}i.push({...
|
|
1254
|
+
`);continue}let w=[...d,y].join(":"),S=Fp(g,e);if(!S.body)try{let v=dc(j1(g,"utf-8"));v.startsWith(`---
|
|
1255
|
+
`)||(S.body=v.trim())}catch{continue}if(!S.body||S.body.length===0){b.AFK_DEBUG&&process.stderr.write(`[afk] skipping command with empty body: ${we(g)}
|
|
1256
|
+
`);continue}i.push({...S,name:w,origin:"command"})}}finally{p.closeSync()}a>=Ac&&b.AFK_DEBUG&&process.stderr.write(`[afk] commands walk: MAX_ENTRIES (${Ac}) reached in ${we(o)}
|
|
1257
1257
|
`)}return c(o,[],0),i.sort((l,d)=>l.name<d.name?-1:l.name>d.name?1:0),ls.set(n,i),i}M();C();function lc(t,e){let n=La(t,e),r=e?.excludeName,s=(r!==void 0&&r.length>0?n.filter(a=>a.name!==r&&!a.name.endsWith(`:${r}`)):n).filter(a=>a.source!=="command");if(s.length===0)return"";let i=[];for(let a of s){let c=a.argumentHint?`${a.argumentHint}`:"",l=c?`- \`${a.name} ${c}\`: ${a.description}`:`- ${a.name}: ${a.description}`;i.push(l),a.whenToUse&&i.push(` When to use: ${a.whenToUse}`)}return["Available skills (invoke via the `skill` tool):","","Each skill either forks an isolated subagent (delegation \u2014 preserves the main session's context) or loads its instructions directly into your current context for you to execute directly. The mode is fixed per-skill, not per-call. To run a skill N times in parallel with isolation, dispatch N subagents (via `agent` or `compose`) that each call `skill` once. Prefer a skill over inline investigation when the task shape matches.","",...i].join(`
|
|
1258
1258
|
`)}function $_(t,e){return[...AT(t,e),...U_(t,e)]}function La(t,e){let n=[],r=new Set,o=b.AFK_INTERNAL==="1",s=Hd(jd());as($r(),"user"),dv("project"),as(ym(e?.cwd),"project");for(let{dir:c,origin:l}of s.skillRoots)as(c,l);for(let c of Ia()){let l=Et(c);ip(l,o)&&(n.push({name:c,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(c),c.includes(":")&&r.add(c.split(":").pop()))}let i=t??tf(e),a=hc();for(let c of i){if(c.type!=="local")continue;let l=$_(c.path,a);for(let d of l)!d.name||r.has(d.name)||ip({audience:d.audience},o)&&(n.push({name:d.name,description:d.description??`Skill from plugin at ${c.path}`,source:d.origin==="command"?"command":"plugin",argumentHint:d.argumentHint,whenToUse:d.whenToUse}),r.add(d.name))}return n}function rs(t,e){let n=new Map,r=t??tf(e),o=hc();for(let s of r){if(s.type!=="local")continue;let i=$_(s.path,o);for(let a of i)a.name&&a.body&&a.body.length>0&&!n.has(a.name)&&n.set(a.name,{body:a.body,pluginPath:s.path,...a.allowedTools!==void 0?{allowedTools:a.allowedTools}:{},...a.context!==void 0?{context:a.context}:{},...a.readOnly===!0?{readOnly:!0}:{},...a.model!==void 0?{model:a.model}:{}})}return n}function tf(t){return[..._n(bm(t?.cwd)),..._n(),..._n(Sm()),...Hd(jd()).pluginRoots.flatMap(({dir:e,binary:n})=>_n(e,{trustAll:!0,sourceEnabled:Uy(n)}))]}async function B_(){await N_(tf(),{pluginApi:{registerSkill:ke,listSkills:Ia,getSkill:Et,loadSkillPrompts:te,env:b,SubagentManager:K,describeFailure:fe,discoverPluginSkillBodies:rs,getAgentFrameworkDir:De,getSkillsDir:$r,getSessionsDir:re,getOrDeriveFacet:vn,listSessionIds:rr,deriveSessionFacet:nr,loadStoredSession:Uo}})}function vr(t,e,n){let r=ao({cwd:e,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:n.surface,...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:n.workspace}),o=[t.toolBase];return t.userSystem&&o.push(t.userSystem),o.push(t.memoryPrompt),t.workspacePrompt.length>0&&o.push(t.workspacePrompt),t.hotMemory.length>0&&o.push(t.hotMemory),o.push(r),t.manifest.length>0&&o.push(t.manifest),o.join(`
|
|
1259
1259
|
|
|
1260
|
-
`)}function j_(t){let{config:e,cwd:n}=t,r=t.hasSkillExecutor?lc(void 0,{cwd:n,...typeof e.skillDispatchName=="string"&&e.skillDispatchName.length>0?{excludeName:e.skillDispatchName}:{}}):"",o=Ma(e.isSkillDispatch),s=Oa(t.readOnlyMemory),i=Da(t.workspaceEnabled),a={surface:t.surface,sessionId:e.sessionId,depth:e.depth,maxDepth:e.maxDepth,workspace:t.runtimeStateSource.getWorkspace()},c={toolBase:o,memoryPrompt:s,workspacePrompt:i,hotMemory:e.hotMemory??"",manifest:r,userSystem:t.userSystem};return{stableSystemPrefix:c,toolSystemAppend:vr(c,n,a)}}function H_(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}function W_(t,e,n,r){let o=e.config,{localMode:s,token:i}=Hk(o);if(!i||i.length===0)throw new Error(`${n} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let a=Vs(i),{client:c,throttleQueue:l,systemPrefix:d,tokenRefresher:u}=ev({config:o,token:i,authMode:a,localMode:s,factory:t.providerFactory??Ta(),createClient:S=>new X1(S)}),p=H_(o.systemPrompt),f=typeof o.model=="string"&&o.model.length>0?he(o.model)??o.model:r,m=ni(o,f),g=o.permissionMode??"default";t.setCurrentPermissionMode(g),t.ensureSharedRoots(o.cwd),o.cwd&&t.setCurrentCwd(o.cwd);let h=t.getSharedReadRoots(),y=t.getSharedWriteRoots();o.readRoots&&h&&h.length<=1&&(h.length=0,h.push(...o.readRoots)),o.writeRoots&&y&&y.length<=1&&(y.length=0,y.push(...o.writeRoots));let{queryDispatcher:w,runtimeStateSource:k,toolDefs:v,resolvedSessionId:_}=av({config:o,model:f,permissionMode:g,surface:t.surface,providerName:n,externalTools:t.externalTools,sharedReadRoots:h,sharedWriteRoots:y,getCwd:()=>t.getCurrentCwd()||o.cwd||process.cwd(),getMcpTools:()=>t.mcpManager?.getMcpTools()??[],getSubagents:()=>t.subagentExecutor?t.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]},getMintedSessionId:()=>t.getMintedSessionId(),setMintedSessionId:S=>{t.setMintedSessionId(S)},getPresenceSessionId:()=>t.getPresenceSessionId(),setPresenceSessionId:S=>{t.setPresenceSessionId(S)},buildDispatcher:(S,A)=>t.buildDispatcher(S,A)}),E=o.cwd||process.cwd(),{stableSystemPrefix:T,toolSystemAppend:I}=j_({config:o,cwd:E,surface:t.surface,readOnlyMemory:t.readOnlyMemory,workspaceEnabled:t.workspaceStore!==void 0,hasSkillExecutor:!!t.skillExecutor,runtimeStateSource:k,userSystem:p});return Dm({prompt:e.prompt,options:{model:f,maxTokens:m,system:I},provenance:{systemPrompt:{source:o.systemPromptSource??"none",shape:typeof o.systemPrompt=="string"?"string":Array.isArray(o.systemPrompt)?"string[]":o.systemPrompt!=null?"preset":"undefined",...typeof o.systemPrompt=="string"?{length:o.systemPrompt.length}:{}},...o.apiKey?{apiKey:{source:"config"}}:{}}}),{client:c,authMode:a,localMode:s,model:f,maxTokens:m,cwd:E,systemPrefix:d,throttleQueue:l,tokenRefresher:u,queryDispatcher:w,runtimeStateSource:k,toolDefs:v,resolvedSessionId:_,stableSystemPrefix:T,toolSystemAppend:I}}import{randomUUID as GK}from"node:crypto";function K_(t){let e=t.initialUsageInputTokens!==void 0&&t.initialUsageInputTokens>0?{inputTokens:t.initialUsageInputTokens,stopReason:null,resultSubtype:"success",isError:!1}:null;return{messages:t.initialMessages?[...t.initialMessages]:[],currentModel:t.model,requestedModel:t.requestedModel??t.model,currentPermissionMode:t.permissionMode,userSystem:t.userSystem,toolDispatcher:t.toolDispatcher,lastUsage:e,closed:!1,autoCompactThreshold:t.autoCompactThreshold}}import{randomUUID as RK}from"node:crypto";C();var z1="1h";function ds(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=b.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 En(){let t=b.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":z1}function xc(t){return ds(t)&&En()==="1h"}function q_(t,e){if(t.length===0)return t;let n=t[t.length-1],r=X_(n,e);return r===n?t:[...t.slice(0,-1),r]}function G_(t,e){if(t.length===0)return t;let n=t[t.length-1],r=J1(n,e);return r===n?t:[...t.slice(0,-1),r]}function J1(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=X_(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function X_(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var V1=1.25,Y1=2,Q1=.1,z_=new Map([["claude-sonnet-5",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-5",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-8",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-7",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-6",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-sonnet-4-6",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-sonnet-4-5-20250929",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-4-5-20250929",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-haiku-4-5-20250929",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-haiku-4-5-20251001",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-3-7-sonnet-20250219",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20241022",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20240620",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-haiku-20241022",{inputPerMTok:.8,outputPerMTok:4,cacheWrite5mPerMTok:1,cacheWrite1hPerMTok:1.6,cacheReadPerMTok:.08}],["claude-3-opus-20240229",{inputPerMTok:15,outputPerMTok:75,cacheWrite5mPerMTok:18.75,cacheWrite1hPerMTok:30,cacheReadPerMTok:1.5}],["claude-3-sonnet-20240229",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-haiku-20240307",{inputPerMTok:.25,outputPerMTok:1.25,cacheWrite5mPerMTok:.3,cacheWrite1hPerMTok:.5,cacheReadPerMTok:.03}]]),Z1=/-\d{8}$/,nf=2,eK=/^claude-opus-(?:5|4-8)(?:-|$)/;function tK(t){let e=n=>n===void 0?void 0:n*nf;return{inputPerMTok:t.inputPerMTok*nf,outputPerMTok:t.outputPerMTok*nf,...e(t.cacheWrite5mPerMTok)!==void 0?{cacheWrite5mPerMTok:e(t.cacheWrite5mPerMTok)}:{},...e(t.cacheWrite1hPerMTok)!==void 0?{cacheWrite1hPerMTok:e(t.cacheWrite1hPerMTok)}:{},...e(t.cacheReadPerMTok)!==void 0?{cacheReadPerMTok:e(t.cacheReadPerMTok)}:{}}}function nK(t){return t.responseSpeed??t.requestSpeed??"standard"}function rK(t){return pr(t,z_,Z1)}function rf(t,e,n,r,o,s,i={}){let a=rK(t);if(!a)return;let c=nK(i)==="fast"&&eK.test(t)?tK(a):a,l=1e6,d=ve(e),u=ve(n),p=ve(r),f=ve(o),m=d/l*c.inputPerMTok,g=u/l*c.outputPerMTok,h=c.cacheWrite5mPerMTok??c.inputPerMTok*V1,y=c.cacheWrite1hPerMTok??c.inputPerMTok*Y1,w=c.cacheReadPerMTok??c.inputPerMTok*Q1,k=s??{ephemeral5m:f,ephemeral1h:0},v=ve(k.ephemeral5m),_=ve(k.ephemeral1h),E=Math.max(0,f-(v+_)),T=v/l*h+_/l*y+E/l*y,I=p/l*w;return m+g+T+I}function oK(t){let e=t.speed;return e==="fast"||e==="standard"?e:void 0}function sK(t){let e=o=>Number.isFinite(o)&&o>=0?o:0,n=t.cache_creation;if(n)return{ephemeral5m:e(n.ephemeral_5m_input_tokens??0),ephemeral1h:e(n.ephemeral_1h_input_tokens??0)};let r=e(t.cache_creation_input_tokens??0);return En()==="1h"?{ephemeral5m:0,ephemeral1h:r}:{ephemeral5m:r,ephemeral1h:0}}function of(t,e,n,r){if(!t)return{stopReason:e??null};let o=oK(t),s={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null,raw:{...t,...o?{speed:o}:{}}};if(t.cache_read_input_tokens!=null&&(s.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(s.cacheCreationTokens=t.cache_creation_input_tokens),s.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n){let i=rf(n,t.input_tokens??0,t.output_tokens??0,t.cache_read_input_tokens??0,t.cache_creation_input_tokens??0,sK(t),{...r?{requestSpeed:r}:{},...o?{responseSpeed:o}:{}});i!==void 0&&(s.totalCostUsd=i)}return s}C();function us(t){return t>2147483647?2147483647:t}var J_=18e4;function Rc(){let t=b.AFK_MODEL_TTFB_TIMEOUT_MS;if(t===void 0||t.trim()==="")return J_;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?J_:us(e)}var iK="model_ttfb_timeout",aK=3e4,cK=6e4,lK=8e3;function V_(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?void 0:(t<cK?t:lK)+aK}function Y_(t,e){if(e<=0)return{signal:t,timedOut:()=>!1,firstByteSeen:()=>{},extend:()=>{},dispose:()=>{}};let n=new AbortController,r=AbortSignal.any([t,n.signal]),o=!1,s=!1,i=Date.now()+e,a,c=u=>{a=setTimeout(()=>{o=!0,n.abort(new Error(iK))},us(u)),a.unref()};c(e);let l=()=>{s||(s=!0,clearTimeout(a))};return{signal:r,timedOut:()=>o,firstByteSeen:l,extend:u=>{s||o||typeof u!="number"||!Number.isFinite(u)||u<=0||(i+=u,clearTimeout(a),c(Math.max(1,i-Date.now())))},dispose:l}}C();var Q_=12e5;function Z_(){let t=b.AFK_MODEL_STALL_TIMEOUT_MS;if(t===void 0||t.trim()==="")return Q_;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?Q_:us(e)}var eE="model_stream_stall_timeout";function tE(t){return t instanceof Error&&t.message===eE}function sf(t){return new Error(`Model stream stalled: no output for ${Math.round(t/1e3)}s after the response had already started streaming. The round was aborted rather than left hanging (issue #762: two sessions hung 38 and 63 minutes with no terminal event). A round that keeps producing output is never cut off, no matter how long it runs. Raise AFK_MODEL_STALL_TIMEOUT_MS, or set it to 0 to disable this bound.`)}function nE(t,e,n){if(e<=0)return{signal:t,timedOut:()=>!1,progress:()=>{},dispose:()=>{}};let r=new AbortController,o=AbortSignal.any([t,r.signal]),s,i=!1,a=!1,c=u=>{if(!(a||i)){i=!0,s=void 0;try{n?.({stallTimeoutMs:e,elapsedSinceLastProgressMs:Date.now()-u})}catch{}r.signal.aborted||r.abort(new Error(eE))}};return{signal:o,timedOut:()=>i,progress:()=>{if(a||i)return;s!==void 0&&clearTimeout(s);let u=Date.now(),p=setTimeout(()=>c(u),e);p.unref(),s=p},dispose:()=>{a||(a=!0,s!==void 0&&clearTimeout(s),s=void 0)}}}C();var af="Anthropic is overloaded (HTTP 529) and did not recover within this turn's retry budget. This is an upstream capacity event, not an afk error. The turn was committed, so the conversation so far is preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state once capacity frees up.",dK=600*1e3,uK=7200*1e3,rE=60*1e3,pK=120*1e3,fK=.25;function Ic(t,e=Math.random){return t+Math.floor(e()*t*fK)}function oE(t=Math.random){let e=pK-rE;return rE+Math.floor(t()*e)}function sE(t){return t.type==="turn.completed"&&t.usage.stopReason===Xe}var mK=new Set(["cli","repl","telegram","web"]);function iE(t){let e=b.AFK_OVERLOAD_PAUSE_MS;if(e!==void 0&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.min(Math.floor(n),uK)}return t!==void 0&&mK.has(t)?dK:0}function Pc(t){if(!Number.isFinite(t)||t<=0)return 0;let e=Math.floor(t*2/3);return Math.max(1,e)}function aE(t){if(!("status"in t))return!1;let e=t.status;return e===529||e===503}function ps(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"}var Cc=class{overloadRetries=0;streamIncompleteRetries=0;ttfbRetries=0;canRetryOverload(){return this.overloadRetries<3}canRetryStreamIncomplete(){return this.streamIncompleteRetries<2}canRetryTtfb(){return this.ttfbRetries<2}reset(){this.overloadRetries=0,this.streamIncompleteRetries=0,this.ttfbRetries=0}};async function*hK(t,e,n){$(t.traceWriter,{phase:"ttfb_timeout",durationMs:Date.now()-e,metadata:{reason:"ttfb-timeout",source:"first-byte",resolvedModel:t.model,attempt:n}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId}}async function*lf(t,{input:e,turn:n,retry:r,requestStartedAt:o}){return t==="ttfb"?(r.ttfbRetries+=1,yield*hK(e,o,r.ttfbRetries),"continue"):t==="overload"?(r.overloadRetries+=1,$(e.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:r.overloadRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*cE(Ic(5e3*Math.pow(2,r.overloadRetries-1)),e,n),e.signal.aborted?"terminated":"continue"):(r.streamIncompleteRetries+=1,$(e.traceWriter,{phase:"rate_limit",metadata:{reason:"stream-incomplete",source:"mid-stream",attempt:r.streamIncompleteRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*cE(1e3*Math.pow(2,r.streamIncompleteRetries-1),e,n),e.signal.aborted?"terminated":"continue")}async function*cE(t,e,n){await Ie(t,e.signal),e.signal.aborted&&(yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId})}function dE(t){let e=t.fastModeController?.snapshotTurn({resolvedModelId:t.model,providerFamily:"anthropic-direct",hasCustomEndpoint:t.baseUrl!==void 0,executionPath:"top-level"}),n=e?.effective===!0,r=Ot(t.authMode,t.sessionId,t.requestId,t.effort!==void 0,xc(t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{}),n);return{decision:e,runInput:{client:t.client,messages:t.messages,system:t.system,tools:t.tools,toolDispatcher:t.toolDispatcher,model:t.model,maxTokens:t.maxTokens,headers:r,signal:t.signal,ctx:{sessionId:t.sessionId},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...n?{fastMode:!0}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...t.maxToolUseIterations!==void 0?{maxToolUseIterations:t.maxToolUseIterations}:{},...t.softDeadlineMs!==void 0?{softDeadlineMs:t.softDeadlineMs}:{},...t.traceWriter?{traceWriter:t.traceWriter}:{},...t.subagentId!==void 0?{subagentId:t.subagentId}:{},...t.throttleQueue?{throttleQueue:t.throttleQueue}:{},...t.onUsageProgress?{onUsageProgress:t.onUsageProgress}:{},...t.beforeNextRound?{beforeNextRound:t.beforeNextRound}:{}}}}var lE="[Fast mode requested; no standard-mode fallback will be attempted]";function Mc(t,e){let n=t instanceof Error?t:new Error(String(t));if(!e||n.message.startsWith(lE))return n;let r=new Error(`${lE} ${n.message}`,{cause:n});r.name=n.name,n.stack!==void 0&&(r.stack=n.stack);for(let o of Object.getOwnPropertyNames(n)){if(o==="message"||o==="stack")continue;let s=Object.getOwnPropertyDescriptor(n,o);s!==void 0&&Object.defineProperty(r,o,s)}return r}async function*uE(t,e,n){let r=e.throttleQueue;if(!r)return await t;r.resetAttempts();let o=Symbol("create-done"),s=!1,i=t.then(a=>(s=!0,a),a=>{throw s=!0,a});for(;;){for(let c of r.takeAll())n?.(c.retryAfterMs),yield{type:"rate_limit",sessionId:e.ctx.sessionId,status:c.status,attempt:c.attempt,...c.retryAfterMs!==void 0?{retryAfterMs:c.retryAfterMs}:{}};if(s)return await i;await Promise.race([i.then(()=>o,()=>o),r.waitForItem().then(()=>{})])}}function pE(t,e){try{let n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let s=o.content;for(let i=0;i<s.length;i++){let a=s[i];if(a.type==="thinking"){let c=a;(!c.thinking||!c.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:c.thinking?`(${c.thinking.length} chars)`:"(empty)",sigLen:c.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",e.message),console.error(`[afk] messages.length=${t.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}function yK(t){let{name:e,description:n,input_schema:r}=t;return{name:e,...n!==void 0?{description:n}:{},input_schema:r}}var Oc=class extends Error{constructor(){super("Connection-phase overload budget exhausted"),this.name="ConnectionOverloadExhaustedError"}};async function bK(t,e,n,r,o){for(let s=0;;s++){if(s>0){let i=Ic(5e3*Math.pow(2,s-1));if(await Ie(i,o),o.aborted)throw new Error("aborted")}try{return await Promise.resolve(t.messages.create(e,{headers:n,signal:r}))}catch(i){if(r.aborted)throw i;let a=i instanceof Error?i:new Error(String(i));if(aE(a)){if(s<3)continue;throw new Oc}throw a}}}function wK(t){return{model:t.model,max_tokens:t.maxTokens,messages:t.messages,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools.map(yK)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.fastMode===!0?{speed:"fast"}:{}}}async function*fE({input:t,turn:e,retry:n,ttfbTimeoutMs:r,stallTimeoutMs:o}){let s=ds({baseUrl:t.baseUrl})?G_(t.messages,En()):t.messages,i=wK({...t,messages:s,tools:e.windDownReason!==null?null:t.tools}),a=Date.now(),c=Y_(t.signal,r),l=nE(c.signal,o,d=>{$(t.traceWriter,{phase:"idle_watchdog_fired",durationMs:d.elapsedSinceLastProgressMs,resolvedModel:t.model,metadata:{source:"model-stream",stallTimeoutMs:d.stallTimeoutMs,elapsedSinceLastProgressMs:d.elapsedSinceLastProgressMs}})});try{return{kind:"opened",events:yield*uE(bK(t.client,i,t.headers,l.signal,t.signal),t,u=>{let p=V_(u);p!==void 0&&c.extend(p)}),ttfb:c,stall:l,requestStartedAt:a}}catch(d){if(c.timedOut()&&!t.signal.aborted&&n.canRetryTtfb())return c.dispose(),l.dispose(),{kind:"retry-ttfb",requestStartedAt:a};if(c.dispose(),l.dispose(),t.signal.aborted)return yield{type:"turn.completed",usage:e.terminalUsage(),sessionId:t.ctx.sessionId},{kind:"terminated"};if(d instanceof Oc)return{kind:"overload-exhausted"};let u=Mc(d,t.fastMode===!0);return u.message.includes("thinking")&&pE(t.messages,u),yield{type:"error",error:u},{kind:"terminated"}}}C();function mE(t,e){return t||e!==null}function gE(){return new Le("the model stream ended without a terminal message (no message_stop and no stop_reason): the turn is incomplete. The cause is not knowable at this layer \u2014 a client-side abort carrying an AbortError reason (including the SDK request timeout) and an upstream peer close are indistinguishable here. Check the trace for a preceding ttfb_timeout, idle_watchdog_fired, or rate_limit phase before suspecting the network.")}function SK(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function kK(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:SK(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*hE(t,e,n){let r=[],o=null,s=null,i=!1,a=!!b.AFK_TELEGRAM_TRACE;try{a&&console.log("[translate] starting SDK event iteration");for await(let c of t){switch(a&&console.log("[translate] SDK evt:",c.type),c.type){case"message_start":{let l=c.message?.usage;l&&(s={...l});break}case"content_block_start":{let l=c.content_block;l.type==="text"?r[c.index]={kind:"text",text:""}:l.type==="thinking"?r[c.index]={kind:"thinking",thinking:"",signature:""}:l.type==="redacted_thinking"?r[c.index]={kind:"redacted_thinking",data:l.data}:l.type==="tool_use"&&(r[c.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",pending:!0,sessionId:e.sessionId}});break}case"content_block_delta":{let l=r[c.index],d=c.delta;d.type==="text_delta"?(l&&l.kind==="text"&&(l.text+=d.text),yield{kind:"event",event:{type:"delta.text",text:d.text,sessionId:e.sessionId}}):d.type==="input_json_delta"?(l&&l.kind==="tool_use"&&(l.partialJson+=d.partial_json),n?.()):d.type==="thinking_delta"?(l&&l.kind==="thinking"&&(l.thinking+=d.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:d.thinking,sessionId:e.sessionId}}):(d.type==="signature_delta"&&l&&l.kind==="thinking"&&(l.signature=d.signature),n?.());break}case"content_block_stop":{let l=r[c.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":{c.delta&&c.delta.stop_reason!==void 0&&(o=c.delta.stop_reason);let l=c.usage;l&&(s!==null?(s.output_tokens=l.output_tokens,l.cache_creation_input_tokens!=null&&(s.cache_creation_input_tokens=l.cache_creation_input_tokens),l.cache_read_input_tokens!=null&&(s.cache_read_input_tokens=l.cache_read_input_tokens),l.input_tokens!=null&&(s.input_tokens=l.input_tokens)):s={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":{i=!0;break}default:break}if(i)break}a&&console.log("[translate] SDK iteration ended naturally, stopped=",i)}catch(c){a&&console.log("[translate] SDK iteration threw:",c.message),yield{kind:"event",event:{type:"error",error:c instanceof Error?c:new Error(String(c))}};return}if(!mE(i,o)){yield{kind:"event",event:{type:"error",error:gE()}};return}a&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:kK(r,o,s)}}C();async function*yE({events:t,input:e,turn:n,retry:r,ttfb:o,stall:s,stallTimeoutMs:i,requestStartedAt:a}){let c=null,l=!1,d=!1,u=!1,p=!1,f=!1,m=!1;try{b.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let g of hE(yr(t,e.signal),e.ctx,()=>s.progress()))if(!m&&(g.kind==="turn-result"||g.event.type!=="error")&&(m=!0,o.firstByteSeen(),$(e.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-a,resolvedModel:e.model})),s.progress(),b.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",g.kind,g.kind==="event"?g.event.type:""),g.kind==="event"){if(g.event.type==="error"){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m){d=!0;break}if(s.timedOut()&&!e.signal.aborted){yield{type:"error",error:sf(i)},l=!0;break}if(ps(g.event.error)&&r.canRetryOverload()&&!e.signal.aborted){u=!0;break}if(ps(g.event.error)&&!e.signal.aborted){f=!0;break}if(e.signal.aborted)break;if(g.event.error instanceof Le&&r.canRetryStreamIncomplete()&&!e.signal.aborted){p=!0;break}yield g.event,l=!0;break}yield g.event}else{c=g.result;break}b.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",c?"set":"null")}catch(g){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m)o.dispose(),s.dispose(),d=!0;else{if(o.dispose(),s.dispose(),e.signal.aborted)return yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"terminated"};let h=g instanceof Error?g:new Error(String(g));if((s.timedOut()||tE(h))&&!e.signal.aborted)return yield{type:"error",error:sf(i)},{kind:"terminated"};if(ps(h)&&r.canRetryOverload()&&!e.signal.aborted)u=!0;else if(ps(h)&&!e.signal.aborted)f=!0;else return yield{type:"error",error:h},{kind:"terminated"}}}return o.dispose(),s.dispose(),d?{kind:"retry",reason:"ttfb"}:u?{kind:"retry",reason:"overload"}:p?{kind:"retry",reason:"stream-incomplete"}:f?{kind:"overload-exhausted"}:l?{kind:"translator-errored"}:{kind:"streamed",turnResult:c}}C();async function*bE(t,e,n){let r=[],o=new Map;for(let i of t.toolUseBlocks)r.push({id:i.id,name:i.name,input:i.input,signal:e.signal}),o.set(i.id,Date.now()),nn(e.traceWriter,Za({toolUseId:i.id,name:i.name,input:i.input,subagentId:e.subagentId})),yield{type:"tool.use.start",toolUseId:i.id,toolName:i.name,toolInput:Yt(i.name,i.input),toolInputRaw:Ya(i.input),toolInputCapture:b.AFK_CAPTURE_SUBAGENT_OUTPUT==="1"?Qa(i.input):void 0,sessionId:e.ctx.sessionId};if(e.signal.aborted){let i=r.map(a=>({type:"tool_result",tool_use_id:a.id,content:"Tool call aborted",is_error:!0}));return e.messages.push({role:"user",content:i}),yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"aborted"}}let s;if(e.toolDispatcher.executeBatch)s=yield*tc(async i=>{try{return await e.toolDispatcher.executeBatch(r,a=>{i({type:"tool.activity",activeCount:a.length,activeToolUseIds:[...a],sessionId:e.ctx.sessionId})})}catch(a){return r.map(()=>({content:`Tool batch execution failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}))}});else{s=[];for(let i of r){if(e.signal.aborted){s.push({content:"Tool call aborted",isError:!0,failureClass:be(e.signal)});continue}try{s.push(await e.toolDispatcher.execute(i))}catch(a){let c=a instanceof Error?a.message:String(a);s.push({content:`Tool execution threw: ${c}`,isError:!0})}}}return{kind:"dispatched",calls:r,results:s,startTimes:o}}async function*wE(t,e,n,r){let o=[];for(let c=0;c<t.length;c++){let l=t[c],d=e[c],u=n.get(l.id),p=typeof u=="number"?Date.now()-u:0,f=d.truncated===!0||d.content.includes("[output truncated");nn(r.traceWriter,ec({toolUseId:l.id,name:l.name,result:d,truncated:f,durationMs:p,subagentId:r.subagentId})),yield{type:"tool.output",toolUseId:l.id,toolName:l.name,content:d.content,...d.isError===!0?{isError:!0}:{},...f?{truncated:!0}:{},...d.incomplete===!0?{incomplete:!0}:{},...d.incompleteReason?{incompleteReason:d.incompleteReason}:{},...typeof d.batchIndex=="number"&&typeof d.batchSize=="number"?{batchIndex:d.batchIndex,batchSize:d.batchSize}:{},...d.failureClass?{failureClass:d.failureClass}:{},sessionId:r.ctx.sessionId},d.render?.diff&&(yield{type:"tool.diff",toolUseId:l.id,diff:d.render.diff,sessionId:r.ctx.sessionId});let{content:m,isError:g,image:h}=d,y=h!==void 0?[{type:"image",source:{type:"base64",media_type:h.mediaType,data:h.data}},...m.length>0?[{type:"text",text:m}]:[]]:m;o.push({type:"tool_result",tool_use_id:l.id,content:y,...g===!0?{is_error:!0}:{}})}let s=e.flatMap(c=>c.harnessUserMessage?.kind==="queued_user_message"?[{type:"text",text:c.harnessUserMessage.text}]:[]),i={role:"user",content:[...o,...s]};r.messages.push(i);let a=e.find(c=>c.failureClass===Hn);return a?(yield{type:"error",error:new On(a.content)},"denial-tripped"):"committed"}async function*SE(t,e,n,r,o){let s=e.messages.length;e.messages.push({role:"assistant",content:t.assistantBlocks});try{n.toolCallCount+=t.toolUseBlocks.length;let d=yield*bE(t,e,n);if(d.kind==="aborted"||(yield*wE(d.calls,d.results,d.startTimes,e))==="denial-tripped")return"terminated"}catch(d){throw e.messages.splice(s),d}n.iterations+=1;let i=t.toolUseBlocks[t.toolUseBlocks.length-1],a=i?`${i.name}${Yt(i.name,i.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:n.taskId,description:"Working",summary:`${sc(n.iterations,r)}: ${a}`,lastToolName:i?.name,totalTokens:n.usage.totalTokens??0,toolUses:n.toolCallCount,durationMs:Date.now()-n.startedAt},sessionId:e.ctx.sessionId},n.windDownReason!==null)return yield{type:"turn.completed",usage:n.withDuration({...n.usage,stopReason:n.windDownReason}),sessionId:e.ctx.sessionId},"terminated";let c=oc(n.iterations,r),l=ac(n.startedAt,o);if(c||l){let d=c?nc:ic,u=e.messages[e.messages.length-1];u!==void 0&&u.role==="user"&&Array.isArray(u.content)&&u.content.push({type:"text",text:d}),n.windDownReason=c?ct:lt}return"continue"}var vK=200;function*kE(t,e,n){if(t.stopReason==="refusal"){t.text.length>0&&(yield{type:"assistant.message",text:t.text,sessionId:e.ctx.sessionId}),yield{type:"notice",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.`,kind:"refusal",sessionId:e.ctx.sessionId},yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId};return}let r=At(t.stopReason)?Na(t.toolUseBlocks.map(s=>s.name),t.stopReason):null;t.text.length>0?(yield{type:"assistant.message",text:r?`${t.text}
|
|
1260
|
+
`)}function j_(t){let{config:e,cwd:n}=t,r=t.hasSkillExecutor?lc(void 0,{cwd:n,...typeof e.skillDispatchName=="string"&&e.skillDispatchName.length>0?{excludeName:e.skillDispatchName}:{}}):"",o=Ma(e.isSkillDispatch),s=Oa(t.readOnlyMemory),i=Da(t.workspaceEnabled),a={surface:t.surface,sessionId:e.sessionId,depth:e.depth,maxDepth:e.maxDepth,workspace:t.runtimeStateSource.getWorkspace()},c={toolBase:o,memoryPrompt:s,workspacePrompt:i,hotMemory:e.hotMemory??"",manifest:r,userSystem:t.userSystem};return{stableSystemPrefix:c,toolSystemAppend:vr(c,n,a)}}function H_(t){if(t===void 0)return null;if(typeof t=="string")return t.length>0?t:null;if(typeof t=="object"&&t!==null&&"append"in t){let e=t.append;return e&&e.length>0?e:null}return null}function W_(t,e,n,r){let o=e.config,{localMode:s,token:i}=Hk(o);if(!i||i.length===0)throw new Error(`${n} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let a=Vs(i),{client:c,throttleQueue:l,systemPrefix:d,tokenRefresher:u}=ev({config:o,token:i,authMode:a,localMode:s,factory:t.providerFactory??Ta(),createClient:k=>new X1(k)}),p=H_(o.systemPrompt),f=typeof o.model=="string"&&o.model.length>0?he(o.model)??o.model:r,m=ni(o,f),g=o.permissionMode??"default";t.setCurrentPermissionMode(g),t.ensureSharedRoots(o.cwd),o.cwd&&t.setCurrentCwd(o.cwd);let h=t.getSharedReadRoots(),y=t.getSharedWriteRoots();o.readRoots&&h&&h.length<=1&&(h.length=0,h.push(...o.readRoots)),o.writeRoots&&y&&y.length<=1&&(y.length=0,y.push(...o.writeRoots));let{queryDispatcher:w,runtimeStateSource:S,toolDefs:v,resolvedSessionId:_}=av({config:o,model:f,permissionMode:g,surface:t.surface,providerName:n,externalTools:t.externalTools,sharedReadRoots:h,sharedWriteRoots:y,getCwd:()=>t.getCurrentCwd()||o.cwd||process.cwd(),getMcpTools:()=>t.mcpManager?.getMcpTools()??[],getSubagents:()=>t.subagentExecutor?t.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]},getMintedSessionId:()=>t.getMintedSessionId(),setMintedSessionId:k=>{t.setMintedSessionId(k)},getPresenceSessionId:()=>t.getPresenceSessionId(),setPresenceSessionId:k=>{t.setPresenceSessionId(k)},buildDispatcher:(k,A)=>t.buildDispatcher(k,A)}),E=o.cwd||process.cwd(),{stableSystemPrefix:T,toolSystemAppend:I}=j_({config:o,cwd:E,surface:t.surface,readOnlyMemory:t.readOnlyMemory,workspaceEnabled:t.workspaceStore!==void 0,hasSkillExecutor:!!t.skillExecutor,runtimeStateSource:S,userSystem:p});return Dm({prompt:e.prompt,options:{model:f,maxTokens:m,system:I},provenance:{systemPrompt:{source:o.systemPromptSource??"none",shape:typeof o.systemPrompt=="string"?"string":Array.isArray(o.systemPrompt)?"string[]":o.systemPrompt!=null?"preset":"undefined",...typeof o.systemPrompt=="string"?{length:o.systemPrompt.length}:{}},...o.apiKey?{apiKey:{source:"config"}}:{}}}),{client:c,authMode:a,localMode:s,model:f,maxTokens:m,cwd:E,systemPrefix:d,throttleQueue:l,tokenRefresher:u,queryDispatcher:w,runtimeStateSource:S,toolDefs:v,resolvedSessionId:_,stableSystemPrefix:T,toolSystemAppend:I}}import{randomUUID as GK}from"node:crypto";function K_(t){let e=t.initialUsageInputTokens!==void 0&&t.initialUsageInputTokens>0?{inputTokens:t.initialUsageInputTokens,stopReason:null,resultSubtype:"success",isError:!1}:null;return{messages:t.initialMessages?[...t.initialMessages]:[],currentModel:t.model,requestedModel:t.requestedModel??t.model,currentPermissionMode:t.permissionMode,userSystem:t.userSystem,toolDispatcher:t.toolDispatcher,lastUsage:e,closed:!1,autoCompactThreshold:t.autoCompactThreshold}}import{randomUUID as RK}from"node:crypto";C();var z1="1h";function ds(t){if(typeof t?.baseUrl=="string"&&t.baseUrl.length>0)return!1;let e=b.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 En(){let t=b.AFK_PROMPT_CACHE_TTL;return t==="5m"?"5m":t==="1h"?"1h":z1}function xc(t){return ds(t)&&En()==="1h"}function q_(t,e){if(t.length===0)return t;let n=t[t.length-1],r=X_(n,e);return r===n?t:[...t.slice(0,-1),r]}function G_(t,e){if(t.length===0)return t;let n=t[t.length-1],r=J1(n,e);return r===n?t:[...t.slice(0,-1),r]}function J1(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=X_(r,e);return o===r?t:{...t,content:[...n.slice(0,-1),o]}}function X_(t,e){return t.type==="thinking"||t.type==="redacted_thinking"?t:{...t,cache_control:{type:"ephemeral",ttl:e}}}var V1=1.25,Y1=2,Q1=.1,z_=new Map([["claude-sonnet-5",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-5",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-8",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-7",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-opus-4-6",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-sonnet-4-6",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-sonnet-4-5-20250929",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-opus-4-5-20250929",{inputPerMTok:5,outputPerMTok:25,cacheWrite5mPerMTok:6.25,cacheWrite1hPerMTok:10,cacheReadPerMTok:.5}],["claude-haiku-4-5-20250929",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-haiku-4-5-20251001",{inputPerMTok:1,outputPerMTok:5,cacheWrite5mPerMTok:1.25,cacheWrite1hPerMTok:2,cacheReadPerMTok:.1}],["claude-3-7-sonnet-20250219",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20241022",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-sonnet-20240620",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-5-haiku-20241022",{inputPerMTok:.8,outputPerMTok:4,cacheWrite5mPerMTok:1,cacheWrite1hPerMTok:1.6,cacheReadPerMTok:.08}],["claude-3-opus-20240229",{inputPerMTok:15,outputPerMTok:75,cacheWrite5mPerMTok:18.75,cacheWrite1hPerMTok:30,cacheReadPerMTok:1.5}],["claude-3-sonnet-20240229",{inputPerMTok:3,outputPerMTok:15,cacheWrite5mPerMTok:3.75,cacheWrite1hPerMTok:6,cacheReadPerMTok:.3}],["claude-3-haiku-20240307",{inputPerMTok:.25,outputPerMTok:1.25,cacheWrite5mPerMTok:.3,cacheWrite1hPerMTok:.5,cacheReadPerMTok:.03}]]),Z1=/-\d{8}$/,nf=2,eK=/^claude-opus-(?:5|4-8)(?:-|$)/;function tK(t){let e=n=>n===void 0?void 0:n*nf;return{inputPerMTok:t.inputPerMTok*nf,outputPerMTok:t.outputPerMTok*nf,...e(t.cacheWrite5mPerMTok)!==void 0?{cacheWrite5mPerMTok:e(t.cacheWrite5mPerMTok)}:{},...e(t.cacheWrite1hPerMTok)!==void 0?{cacheWrite1hPerMTok:e(t.cacheWrite1hPerMTok)}:{},...e(t.cacheReadPerMTok)!==void 0?{cacheReadPerMTok:e(t.cacheReadPerMTok)}:{}}}function nK(t){return t.responseSpeed??t.requestSpeed??"standard"}function rK(t){return pr(t,z_,Z1)}function rf(t,e,n,r,o,s,i={}){let a=rK(t);if(!a)return;let c=nK(i)==="fast"&&eK.test(t)?tK(a):a,l=1e6,d=ve(e),u=ve(n),p=ve(r),f=ve(o),m=d/l*c.inputPerMTok,g=u/l*c.outputPerMTok,h=c.cacheWrite5mPerMTok??c.inputPerMTok*V1,y=c.cacheWrite1hPerMTok??c.inputPerMTok*Y1,w=c.cacheReadPerMTok??c.inputPerMTok*Q1,S=s??{ephemeral5m:f,ephemeral1h:0},v=ve(S.ephemeral5m),_=ve(S.ephemeral1h),E=Math.max(0,f-(v+_)),T=v/l*h+_/l*y+E/l*y,I=p/l*w;return m+g+T+I}function oK(t){let e=t.speed;return e==="fast"||e==="standard"?e:void 0}function sK(t){let e=o=>Number.isFinite(o)&&o>=0?o:0,n=t.cache_creation;if(n)return{ephemeral5m:e(n.ephemeral_5m_input_tokens??0),ephemeral1h:e(n.ephemeral_1h_input_tokens??0)};let r=e(t.cache_creation_input_tokens??0);return En()==="1h"?{ephemeral5m:0,ephemeral1h:r}:{ephemeral5m:r,ephemeral1h:0}}function of(t,e,n,r){if(!t)return{stopReason:e??null};let o=oK(t),s={inputTokens:t.input_tokens,outputTokens:t.output_tokens,stopReason:e??null,raw:{...t,...o?{speed:o}:{}}};if(t.cache_read_input_tokens!=null&&(s.cachedInputTokens=t.cache_read_input_tokens),t.cache_creation_input_tokens!=null&&(s.cacheCreationTokens=t.cache_creation_input_tokens),s.totalTokens=(t.input_tokens??0)+(t.output_tokens??0),n){let i=rf(n,t.input_tokens??0,t.output_tokens??0,t.cache_read_input_tokens??0,t.cache_creation_input_tokens??0,sK(t),{...r?{requestSpeed:r}:{},...o?{responseSpeed:o}:{}});i!==void 0&&(s.totalCostUsd=i)}return s}C();function us(t){return t>2147483647?2147483647:t}var J_=18e4;function Rc(){let t=b.AFK_MODEL_TTFB_TIMEOUT_MS;if(t===void 0||t.trim()==="")return J_;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?J_:us(e)}var iK="model_ttfb_timeout",aK=3e4,cK=6e4,lK=8e3;function V_(t){return typeof t!="number"||!Number.isFinite(t)||t<=0?void 0:(t<cK?t:lK)+aK}function Y_(t,e){if(e<=0)return{signal:t,timedOut:()=>!1,firstByteSeen:()=>{},extend:()=>{},dispose:()=>{}};let n=new AbortController,r=AbortSignal.any([t,n.signal]),o=!1,s=!1,i=Date.now()+e,a,c=u=>{a=setTimeout(()=>{o=!0,n.abort(new Error(iK))},us(u)),a.unref()};c(e);let l=()=>{s||(s=!0,clearTimeout(a))};return{signal:r,timedOut:()=>o,firstByteSeen:l,extend:u=>{s||o||typeof u!="number"||!Number.isFinite(u)||u<=0||(i+=u,clearTimeout(a),c(Math.max(1,i-Date.now())))},dispose:l}}C();var Q_=12e5;function Z_(){let t=b.AFK_MODEL_STALL_TIMEOUT_MS;if(t===void 0||t.trim()==="")return Q_;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?Q_:us(e)}var eE="model_stream_stall_timeout";function tE(t){return t instanceof Error&&t.message===eE}function sf(t){return new Error(`Model stream stalled: no output for ${Math.round(t/1e3)}s after the response had already started streaming. The round was aborted rather than left hanging (issue #762: two sessions hung 38 and 63 minutes with no terminal event). A round that keeps producing output is never cut off, no matter how long it runs. Raise AFK_MODEL_STALL_TIMEOUT_MS, or set it to 0 to disable this bound.`)}function nE(t,e,n){if(e<=0)return{signal:t,timedOut:()=>!1,progress:()=>{},dispose:()=>{}};let r=new AbortController,o=AbortSignal.any([t,r.signal]),s,i=!1,a=!1,c=u=>{if(!(a||i)){i=!0,s=void 0;try{n?.({stallTimeoutMs:e,elapsedSinceLastProgressMs:Date.now()-u})}catch{}r.signal.aborted||r.abort(new Error(eE))}};return{signal:o,timedOut:()=>i,progress:()=>{if(a||i)return;s!==void 0&&clearTimeout(s);let u=Date.now(),p=setTimeout(()=>c(u),e);p.unref(),s=p},dispose:()=>{a||(a=!0,s!==void 0&&clearTimeout(s),s=void 0)}}}C();var af="Anthropic is overloaded (HTTP 529) and did not recover within this turn's retry budget. This is an upstream capacity event, not an afk error. The turn was committed, so the conversation so far is preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state once capacity frees up.",dK=600*1e3,uK=7200*1e3,rE=60*1e3,pK=120*1e3,fK=.25;function Ic(t,e=Math.random){return t+Math.floor(e()*t*fK)}function oE(t=Math.random){let e=pK-rE;return rE+Math.floor(t()*e)}function sE(t){return t.type==="turn.completed"&&t.usage.stopReason===Xe}var mK=new Set(["cli","repl","telegram","web"]);function iE(t){let e=b.AFK_OVERLOAD_PAUSE_MS;if(e!==void 0&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.min(Math.floor(n),uK)}return t!==void 0&&mK.has(t)?dK:0}function Pc(t){if(!Number.isFinite(t)||t<=0)return 0;let e=Math.floor(t*2/3);return Math.max(1,e)}function aE(t){if(!("status"in t))return!1;let e=t.status;return e===529||e===503}function ps(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"}var Cc=class{overloadRetries=0;streamIncompleteRetries=0;ttfbRetries=0;canRetryOverload(){return this.overloadRetries<3}canRetryStreamIncomplete(){return this.streamIncompleteRetries<2}canRetryTtfb(){return this.ttfbRetries<2}reset(){this.overloadRetries=0,this.streamIncompleteRetries=0,this.ttfbRetries=0}};async function*hK(t,e,n){$(t.traceWriter,{phase:"ttfb_timeout",durationMs:Date.now()-e,metadata:{reason:"ttfb-timeout",source:"first-byte",resolvedModel:t.model,attempt:n}}),yield{type:"stream.retry",sessionId:t.ctx.sessionId}}async function*lf(t,{input:e,turn:n,retry:r,requestStartedAt:o}){return t==="ttfb"?(r.ttfbRetries+=1,yield*hK(e,o,r.ttfbRetries),"continue"):t==="overload"?(r.overloadRetries+=1,$(e.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:r.overloadRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*cE(Ic(5e3*Math.pow(2,r.overloadRetries-1)),e,n),e.signal.aborted?"terminated":"continue"):(r.streamIncompleteRetries+=1,$(e.traceWriter,{phase:"rate_limit",metadata:{reason:"stream-incomplete",source:"mid-stream",attempt:r.streamIncompleteRetries}}),yield{type:"stream.retry",sessionId:e.ctx.sessionId},yield*cE(1e3*Math.pow(2,r.streamIncompleteRetries-1),e,n),e.signal.aborted?"terminated":"continue")}async function*cE(t,e,n){await Ie(t,e.signal),e.signal.aborted&&(yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId})}function dE(t){let e=t.fastModeController?.snapshotTurn({resolvedModelId:t.model,providerFamily:"anthropic-direct",hasCustomEndpoint:t.baseUrl!==void 0,executionPath:"top-level"}),n=e?.effective===!0,r=Ot(t.authMode,t.sessionId,t.requestId,t.effort!==void 0,xc(t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{}),n);return{decision:e,runInput:{client:t.client,messages:t.messages,system:t.system,tools:t.tools,toolDispatcher:t.toolDispatcher,model:t.model,maxTokens:t.maxTokens,headers:r,signal:t.signal,ctx:{sessionId:t.sessionId},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...n?{fastMode:!0}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...t.maxToolUseIterations!==void 0?{maxToolUseIterations:t.maxToolUseIterations}:{},...t.softDeadlineMs!==void 0?{softDeadlineMs:t.softDeadlineMs}:{},...t.traceWriter?{traceWriter:t.traceWriter}:{},...t.subagentId!==void 0?{subagentId:t.subagentId}:{},...t.throttleQueue?{throttleQueue:t.throttleQueue}:{},...t.onUsageProgress?{onUsageProgress:t.onUsageProgress}:{},...t.beforeNextRound?{beforeNextRound:t.beforeNextRound}:{}}}}var lE="[Fast mode requested; no standard-mode fallback will be attempted]";function Mc(t,e){let n=t instanceof Error?t:new Error(String(t));if(!e||n.message.startsWith(lE))return n;let r=new Error(`${lE} ${n.message}`,{cause:n});r.name=n.name,n.stack!==void 0&&(r.stack=n.stack);for(let o of Object.getOwnPropertyNames(n)){if(o==="message"||o==="stack")continue;let s=Object.getOwnPropertyDescriptor(n,o);s!==void 0&&Object.defineProperty(r,o,s)}return r}async function*uE(t,e,n){let r=e.throttleQueue;if(!r)return await t;r.resetAttempts();let o=Symbol("create-done"),s=!1,i=t.then(a=>(s=!0,a),a=>{throw s=!0,a});for(;;){for(let c of r.takeAll())n?.(c.retryAfterMs),yield{type:"rate_limit",sessionId:e.ctx.sessionId,status:c.status,attempt:c.attempt,...c.retryAfterMs!==void 0?{retryAfterMs:c.retryAfterMs}:{}};if(s)return await i;await Promise.race([i.then(()=>o,()=>o),r.waitForItem().then(()=>{})])}}function pE(t,e){try{let n=[];for(let r=0;r<t.length;r++){let o=t[r];if(o.role!=="assistant"||typeof o.content=="string")continue;let s=o.content;for(let i=0;i<s.length;i++){let a=s[i];if(a.type==="thinking"){let c=a;(!c.thinking||!c.signature)&&n.push({msgIdx:r,blockIdx:i,thinking:c.thinking?`(${c.thinking.length} chars)`:"(empty)",sigLen:c.signature?.length??0})}}}console.error("[afk] thinking-block diagnostic \u2014 API rejected request with:",e.message),console.error(`[afk] messages.length=${t.length}, invalid thinking blocks:`,n.length>0?JSON.stringify(n):"none found (cause may be elsewhere)")}catch{}}function yK(t){let{name:e,description:n,input_schema:r}=t;return{name:e,...n!==void 0?{description:n}:{},input_schema:r}}var Oc=class extends Error{constructor(){super("Connection-phase overload budget exhausted"),this.name="ConnectionOverloadExhaustedError"}};async function bK(t,e,n,r,o){for(let s=0;;s++){if(s>0){let i=Ic(5e3*Math.pow(2,s-1));if(await Ie(i,o),o.aborted)throw new Error("aborted")}try{return await Promise.resolve(t.messages.create(e,{headers:n,signal:r}))}catch(i){if(r.aborted)throw i;let a=i instanceof Error?i:new Error(String(i));if(aE(a)){if(s<3)continue;throw new Oc}throw a}}}function wK(t){return{model:t.model,max_tokens:t.maxTokens,messages:t.messages,stream:!0,...t.system!==null?{system:t.system}:{},...t.tools!==null&&t.tools.length>0?{tools:t.tools.map(yK)}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{output_config:{effort:t.effort}}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.fastMode===!0?{speed:"fast"}:{}}}async function*fE({input:t,turn:e,retry:n,ttfbTimeoutMs:r,stallTimeoutMs:o}){let s=ds({baseUrl:t.baseUrl})?G_(t.messages,En()):t.messages,i=wK({...t,messages:s,tools:e.windDownReason!==null?null:t.tools}),a=Date.now(),c=Y_(t.signal,r),l=nE(c.signal,o,d=>{$(t.traceWriter,{phase:"idle_watchdog_fired",durationMs:d.elapsedSinceLastProgressMs,resolvedModel:t.model,metadata:{source:"model-stream",stallTimeoutMs:d.stallTimeoutMs,elapsedSinceLastProgressMs:d.elapsedSinceLastProgressMs}})});try{return{kind:"opened",events:yield*uE(bK(t.client,i,t.headers,l.signal,t.signal),t,u=>{let p=V_(u);p!==void 0&&c.extend(p)}),ttfb:c,stall:l,requestStartedAt:a}}catch(d){if(c.timedOut()&&!t.signal.aborted&&n.canRetryTtfb())return c.dispose(),l.dispose(),{kind:"retry-ttfb",requestStartedAt:a};if(c.dispose(),l.dispose(),t.signal.aborted)return yield{type:"turn.completed",usage:e.terminalUsage(),sessionId:t.ctx.sessionId},{kind:"terminated"};if(d instanceof Oc)return{kind:"overload-exhausted"};let u=Mc(d,t.fastMode===!0);return u.message.includes("thinking")&&pE(t.messages,u),yield{type:"error",error:u},{kind:"terminated"}}}C();function mE(t,e){return t||e!==null}function gE(){return new Le("the model stream ended without a terminal message (no message_stop and no stop_reason): the turn is incomplete. The cause is not knowable at this layer \u2014 a client-side abort carrying an AbortError reason (including the SDK request timeout) and an upstream peer close are indistinguishable here. Check the trace for a preceding ttfb_timeout, idle_watchdog_fired, or rate_limit phase before suspecting the network.")}function SK(t){let e=t.trim();if(e.length===0)return{};try{return JSON.parse(e)}catch{return{}}}function kK(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:SK(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*hE(t,e,n){let r=[],o=null,s=null,i=!1,a=!!b.AFK_TELEGRAM_TRACE;try{a&&console.log("[translate] starting SDK event iteration");for await(let c of t){switch(a&&console.log("[translate] SDK evt:",c.type),c.type){case"message_start":{let l=c.message?.usage;l&&(s={...l});break}case"content_block_start":{let l=c.content_block;l.type==="text"?r[c.index]={kind:"text",text:""}:l.type==="thinking"?r[c.index]={kind:"thinking",thinking:"",signature:""}:l.type==="redacted_thinking"?r[c.index]={kind:"redacted_thinking",data:l.data}:l.type==="tool_use"&&(r[c.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",pending:!0,sessionId:e.sessionId}});break}case"content_block_delta":{let l=r[c.index],d=c.delta;d.type==="text_delta"?(l&&l.kind==="text"&&(l.text+=d.text),yield{kind:"event",event:{type:"delta.text",text:d.text,sessionId:e.sessionId}}):d.type==="input_json_delta"?(l&&l.kind==="tool_use"&&(l.partialJson+=d.partial_json),n?.()):d.type==="thinking_delta"?(l&&l.kind==="thinking"&&(l.thinking+=d.thinking),yield{kind:"event",event:{type:"delta.reasoning",text:d.thinking,sessionId:e.sessionId}}):(d.type==="signature_delta"&&l&&l.kind==="thinking"&&(l.signature=d.signature),n?.());break}case"content_block_stop":{let l=r[c.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":{c.delta&&c.delta.stop_reason!==void 0&&(o=c.delta.stop_reason);let l=c.usage;l&&(s!==null?(s.output_tokens=l.output_tokens,l.cache_creation_input_tokens!=null&&(s.cache_creation_input_tokens=l.cache_creation_input_tokens),l.cache_read_input_tokens!=null&&(s.cache_read_input_tokens=l.cache_read_input_tokens),l.input_tokens!=null&&(s.input_tokens=l.input_tokens)):s={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":{i=!0;break}default:break}if(i)break}a&&console.log("[translate] SDK iteration ended naturally, stopped=",i)}catch(c){a&&console.log("[translate] SDK iteration threw:",c.message),yield{kind:"event",event:{type:"error",error:c instanceof Error?c:new Error(String(c))}};return}if(!mE(i,o)){yield{kind:"event",event:{type:"error",error:gE()}};return}a&&console.log("[translate] yielding turn-result"),yield{kind:"turn-result",result:kK(r,o,s)}}C();async function*yE({events:t,input:e,turn:n,retry:r,ttfb:o,stall:s,stallTimeoutMs:i,requestStartedAt:a}){let c=null,l=!1,d=!1,u=!1,p=!1,f=!1,m=!1;try{b.AFK_TELEGRAM_TRACE&&console.log("[loop] awaiting translateMessageStream events");for await(let g of hE(yr(t,e.signal),e.ctx,()=>s.progress()))if(!m&&(g.kind==="turn-result"||g.event.type!=="error")&&(m=!0,o.firstByteSeen(),$(e.traceWriter,{phase:"model_ttfb",durationMs:Date.now()-a,resolvedModel:e.model})),s.progress(),b.AFK_TELEGRAM_TRACE&&console.log("[loop] translate yielded:",g.kind,g.kind==="event"?g.event.type:""),g.kind==="event"){if(g.event.type==="error"){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m){d=!0;break}if(s.timedOut()&&!e.signal.aborted){yield{type:"error",error:sf(i)},l=!0;break}if(ps(g.event.error)&&r.canRetryOverload()&&!e.signal.aborted){u=!0;break}if(ps(g.event.error)&&!e.signal.aborted){f=!0;break}if(e.signal.aborted)break;if(g.event.error instanceof Le&&r.canRetryStreamIncomplete()&&!e.signal.aborted){p=!0;break}yield g.event,l=!0;break}yield g.event}else{c=g.result;break}b.AFK_TELEGRAM_TRACE&&console.log("[loop] translate loop exited, turnResult=",c?"set":"null")}catch(g){if(o.timedOut()&&!e.signal.aborted&&r.canRetryTtfb()&&!m)o.dispose(),s.dispose(),d=!0;else{if(o.dispose(),s.dispose(),e.signal.aborted)return yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"terminated"};let h=g instanceof Error?g:new Error(String(g));if((s.timedOut()||tE(h))&&!e.signal.aborted)return yield{type:"error",error:sf(i)},{kind:"terminated"};if(ps(h)&&r.canRetryOverload()&&!e.signal.aborted)u=!0;else if(ps(h)&&!e.signal.aborted)f=!0;else return yield{type:"error",error:h},{kind:"terminated"}}}return o.dispose(),s.dispose(),d?{kind:"retry",reason:"ttfb"}:u?{kind:"retry",reason:"overload"}:p?{kind:"retry",reason:"stream-incomplete"}:f?{kind:"overload-exhausted"}:l?{kind:"translator-errored"}:{kind:"streamed",turnResult:c}}C();async function*bE(t,e,n){let r=[],o=new Map;for(let i of t.toolUseBlocks)r.push({id:i.id,name:i.name,input:i.input,signal:e.signal}),o.set(i.id,Date.now()),nn(e.traceWriter,Za({toolUseId:i.id,name:i.name,input:i.input,subagentId:e.subagentId})),yield{type:"tool.use.start",toolUseId:i.id,toolName:i.name,toolInput:Yt(i.name,i.input),toolInputRaw:Ya(i.input),toolInputCapture:b.AFK_CAPTURE_SUBAGENT_OUTPUT==="1"?Qa(i.input):void 0,sessionId:e.ctx.sessionId};if(e.signal.aborted){let i=r.map(a=>({type:"tool_result",tool_use_id:a.id,content:"Tool call aborted",is_error:!0}));return e.messages.push({role:"user",content:i}),yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId},{kind:"aborted"}}let s;if(e.toolDispatcher.executeBatch)s=yield*tc(async i=>{try{return await e.toolDispatcher.executeBatch(r,a=>{i({type:"tool.activity",activeCount:a.length,activeToolUseIds:[...a],sessionId:e.ctx.sessionId})})}catch(a){return r.map(()=>({content:`Tool batch execution failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}))}});else{s=[];for(let i of r){if(e.signal.aborted){s.push({content:"Tool call aborted",isError:!0,failureClass:be(e.signal)});continue}try{s.push(await e.toolDispatcher.execute(i))}catch(a){let c=a instanceof Error?a.message:String(a);s.push({content:`Tool execution threw: ${c}`,isError:!0})}}}return{kind:"dispatched",calls:r,results:s,startTimes:o}}async function*wE(t,e,n,r){let o=[];for(let c=0;c<t.length;c++){let l=t[c],d=e[c],u=n.get(l.id),p=typeof u=="number"?Date.now()-u:0,f=d.truncated===!0||d.content.includes("[output truncated");nn(r.traceWriter,ec({toolUseId:l.id,name:l.name,result:d,truncated:f,durationMs:p,subagentId:r.subagentId})),yield{type:"tool.output",toolUseId:l.id,toolName:l.name,content:d.content,...d.isError===!0?{isError:!0}:{},...f?{truncated:!0}:{},...d.incomplete===!0?{incomplete:!0}:{},...d.incompleteReason?{incompleteReason:d.incompleteReason}:{},...typeof d.batchIndex=="number"&&typeof d.batchSize=="number"?{batchIndex:d.batchIndex,batchSize:d.batchSize}:{},...d.failureClass?{failureClass:d.failureClass}:{},sessionId:r.ctx.sessionId},d.render?.diff&&(yield{type:"tool.diff",toolUseId:l.id,diff:d.render.diff,sessionId:r.ctx.sessionId});let{content:m,isError:g,image:h}=d,y=h!==void 0?[{type:"image",source:{type:"base64",media_type:h.mediaType,data:h.data}},...m.length>0?[{type:"text",text:m}]:[]]:m;o.push({type:"tool_result",tool_use_id:l.id,content:y,...g===!0?{is_error:!0}:{}})}let s=e.flatMap(c=>c.harnessUserMessage?.kind==="queued_user_message"?[{type:"text",text:c.harnessUserMessage.text}]:[]),i={role:"user",content:[...o,...s]};r.messages.push(i);let a=e.find(c=>c.failureClass===Hn);return a?(yield{type:"error",error:new On(a.content)},"denial-tripped"):"committed"}async function*SE(t,e,n,r,o){let s=e.messages.length;e.messages.push({role:"assistant",content:t.assistantBlocks});try{n.toolCallCount+=t.toolUseBlocks.length;let d=yield*bE(t,e,n);if(d.kind==="aborted"||(yield*wE(d.calls,d.results,d.startTimes,e))==="denial-tripped")return"terminated"}catch(d){throw e.messages.splice(s),d}n.iterations+=1;let i=t.toolUseBlocks[t.toolUseBlocks.length-1],a=i?`${i.name}${Yt(i.name,i.input)}`:"unknown";if(yield{type:"progress",progress:{taskId:n.taskId,description:"Working",summary:`${sc(n.iterations,r)}: ${a}`,lastToolName:i?.name,totalTokens:n.usage.totalTokens??0,toolUses:n.toolCallCount,durationMs:Date.now()-n.startedAt},sessionId:e.ctx.sessionId},n.windDownReason!==null)return yield{type:"turn.completed",usage:n.withDuration({...n.usage,stopReason:n.windDownReason}),sessionId:e.ctx.sessionId},"terminated";let c=oc(n.iterations,r),l=ac(n.startedAt,o);if(c||l){let d=c?nc:ic,u=e.messages[e.messages.length-1];u!==void 0&&u.role==="user"&&Array.isArray(u.content)&&u.content.push({type:"text",text:d}),n.windDownReason=c?ct:lt}return"continue"}var vK=200;function*kE(t,e,n){if(t.stopReason==="refusal"){t.text.length>0&&(yield{type:"assistant.message",text:t.text,sessionId:e.ctx.sessionId}),yield{type:"notice",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.`,kind:"refusal",sessionId:e.ctx.sessionId},yield{type:"turn.completed",usage:n.terminalUsage(),sessionId:e.ctx.sessionId};return}let r=At(t.stopReason)?Na(t.toolUseBlocks.map(s=>s.name),t.stopReason):null;t.text.length>0?(yield{type:"assistant.message",text:r?`${t.text}
|
|
1261
1261
|
|
|
1262
1262
|
${r}`:t.text,sessionId:e.ctx.sessionId},t.text.length<=vK&&(yield{type:"suggestion",suggestion:t.text,sessionId:e.ctx.sessionId})):r!==null&&(yield{type:"notice",text:r,kind:"truncation",sessionId:e.ctx.sessionId});let o=t.assistantBlocks.filter(s=>s.type!=="tool_use");o.length>0&&e.messages.push({role:"assistant",content:o}),yield{type:"turn.completed",usage:n.withDuration(n.windDownReason!==null?{...n.usage,stopReason:n.windDownReason}:n.usage),sessionId:e.ctx.sessionId}}import{randomUUID as TK}from"node:crypto";var Fc=class{usage={stopReason:null};iterations=0;toolCallCount=0;windDownReason=null;taskId=TK();startedAt=Date.now();elapsedMs(){return Date.now()-this.startedAt}withDuration(e){return{...e,durationMs:this.elapsedMs()}}terminalUsage(){return this.withDuration(this.usage)}addRoundUsage(e){this.usage=Ko(this.usage,e),this.usage.contextWindowTokens=(e.inputTokens??0)+(e.outputTokens??0)+(e.cachedInputTokens??0)+(e.cacheCreationTokens??0)}};function vE(t,e){if(!e)return;let n=t.messages.at(-1);!n||n.role!=="user"||(Array.isArray(n.content)?n.content.push({type:"text",text:e}):n.content=[{type:"text",text:n.content},{type:"text",text:e}],Bl(t.traceWriter,{jobId:t.subagentId??"",subagentId:t.subagentId??"",byteLength:Buffer.byteLength(e,"utf8")}))}async function*df(t){let e=rc(t.maxToolUseIterations),n=t.softDeadlineMs??0,r=new Fc,o=new Cc,s=l=>({input:t,turn:r,retry:o,requestStartedAt:l}),i=Pc(Rc()),a=Z_(),c=new dr(t.signal,t.traceWriter,"anthropic-direct");try{for(;;){if(t.signal.aborted){yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId};return}let l=yield*fE({input:t,turn:r,retry:o,ttfbTimeoutMs:i,stallTimeoutMs:a});if(l.kind==="terminated")return;if(l.kind==="retry-ttfb"){if((yield*lf("ttfb",s(l.requestStartedAt)))==="terminated")return;continue}if(l.kind==="overload-exhausted"){$(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"connection-phase",attempt:3,exhausted:!0}}),yield{type:"assistant.message",text:af,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:r.withDuration({...r.usage,stopReason:Xe}),sessionId:t.ctx.sessionId};return}let{events:d,ttfb:u,stall:p,requestStartedAt:f}=l,m=yield*yE({events:d,input:t,turn:r,retry:o,ttfb:u,stall:p,stallTimeoutMs:a,requestStartedAt:f});if(m.kind==="terminated")return;if(m.kind==="retry"){if((yield*lf(m.reason,s(f)))==="terminated")return;continue}if(o.reset(),m.kind==="overload-exhausted"){$(t.traceWriter,{phase:"rate_limit",metadata:{reason:"overloaded",source:"mid-stream",attempt:3,exhausted:!0}}),yield{type:"assistant.message",text:af,sessionId:t.ctx.sessionId},yield{type:"turn.completed",usage:r.withDuration({...r.usage,stopReason:Xe}),sessionId:t.ctx.sessionId};return}if(m.kind==="translator-errored"){t.signal.aborted&&(yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId});return}let g=m.turnResult;if(g===null){yield{type:"turn.completed",usage:r.terminalUsage(),sessionId:t.ctx.sessionId};return}if(r.addRoundUsage(of(g.usage,g.stopReason,t.model,t.fastMode?"fast":void 0)),t.onUsageProgress?.(r.usage),g.stopReason!=="tool_use"){yield*kE(g,t,r);return}if((yield*SE(g,t,r,e,n))==="terminated")return;vE(t,t.beforeNextRound?.())}}finally{c.finish(r.elapsedMs())}}function _K(t,e){return t.authMode==="oauth"&&t.tokenRefresher!==void 0&&"status"in e&&e.status===401}async function*TE(t,e,n){let r=null;for await(let s of df(e)){if(n())return;if(s.type==="error"&&_K(t,s.error)){r=s;break}yield s}if(!r)return;if(!await t.forceClientRefresh()){yield r;return}e.client=t.getClient(),e.headers=t.rotateHeaders(e),yield*df(e)}async function*_E(t,e,n,r,o){let s=Vn(xe()??"");if(yield{type:"paused",reason:"usage-limit",accountId:s,autoResume:t.autoResumeOnUsageLimit},$(e.traceWriter,{phase:"usage_limit_pause",metadata:{reason:"usage-limit",source:"retry-layer",hasResetTimestamp:!1,autoResume:t.autoResumeOnUsageLimit}}),!t.autoResumeOnUsageLimit){t.markCredentialSnapshotStale(),yield o;return}let i=Date.now(),a=!1;for(;;){let c;if(t.getUsageLimitWait())c="aborted";else{let p=qk({signal:e.signal,retryAfterMs:6e4});t.setUsageLimitWait(p);try{c=await p}finally{t.setUsageLimitWait(null)}}if(c==="aborted")return;let d=s;if(c==="hot-swap"){let p=await t.forceClientRefresh();p&&(e.client=t.getClient(),d=p.accountId)}e.headers=t.rotateHeaders(e);let u=null;for await(let p of r(t,e,n)){if(!a&&p.type==="error"){let f=$o(p.error);if(f&&(f.kind==="oauth-limit"||f.kind==="oauth-limit-no-ts")){u=p;break}}a||(yield{type:"resumed",hotSwapped:c==="hot-swap",accountId:d},$(e.traceWriter,{phase:"usage_limit_resume",durationMs:Date.now()-i,metadata:{source:"retry-layer",hotSwapped:c==="hot-swap"}}),a=!0),yield p}if(!u)return;if(Date.now()-i>72e5){yield u;return}}}async function*EE(t,e,n,r,o,s){if(s.getTime()-Date.now()>72e5){t.markCredentialSnapshotStale(),yield o;return}let i=Vn(xe()??""),a=Date.now();if(yield{type:"paused",reason:"usage-limit",resetsAt:s,accountId:i,autoResume:t.autoResumeOnUsageLimit},$(e.traceWriter,{phase:"usage_limit_pause",metadata:{reason:"usage-limit",source:"retry-layer",hasResetTimestamp:!0,autoResume:t.autoResumeOnUsageLimit,resetsAt:s.toISOString()}}),!t.autoResumeOnUsageLimit){t.markCredentialSnapshotStale(),yield o;return}let c,l=t.getUsageLimitWait();if(l)c=await l;else{let u=Kk({resetsAt:s,signal:e.signal});t.setUsageLimitWait(u);try{c=await u}finally{t.setUsageLimitWait(null)}}if(c==="aborted")return;let d=i;if(c==="hot-swap"){let u=await t.forceClientRefresh();u&&(e.client=t.getClient(),d=u.accountId)}e.headers=t.rotateHeaders(e),yield{type:"resumed",hotSwapped:c==="hot-swap",accountId:d},$(e.traceWriter,{phase:"usage_limit_resume",durationMs:Date.now()-a,metadata:{source:"retry-layer",hotSwapped:c==="hot-swap"}}),yield*r(t,e,n)}async function*RE(t,e,n,r){let o=null,s=null,i=!1,a=0;for(;;){let c,l=!1;for await(let p of r(t,e,n)){if(p.type==="error"){let f=$o(p.error);if(f&&f.kind==="oauth-limit"){s=f.resetsAt,o=p;break}if(f&&f.kind==="oauth-limit-no-ts"){i=!0,o=p;break}if(f&&f.kind==="rate-limit-transient"&&a<3){l=!0,c=f.retryAfterMs;break}}yield p}if(!l)break;if(a+=1,n()||e.signal.aborted)return;let u=Math.min(c??5e3,12e4)+Math.floor(Math.random()*1e3);if($(e.traceWriter,{phase:"rate_limit",metadata:{reason:"retry-after",source:"retry-layer",attempt:a,waitMs:u}}),await Ie(u,e.signal),n()||e.signal.aborted)return;e.headers=t.rotateHeaders(e)}if(o){if(i){yield*_E(t,e,n,r,o);return}s&&(yield*EE(t,e,n,r,o,s))}}async function*IE(t,e,n,r){let o=iE(t.surface),s=null,i=!1;for(;;){let a=null;for await(let l of r(t,e,n)){if(sE(l)){a=l;break}yield l}if(!a){i&&s!==null&&$(e.traceWriter,{phase:"overload_resume",durationMs:Date.now()-s,metadata:{source:"retry-layer",outcome:"recovered"}});return}if(n()||e.signal.aborted||o===0){yield a;return}s??=Date.now();let c=o-(Date.now()-s);if(c<=0){i&&$(e.traceWriter,{phase:"overload_resume",durationMs:Date.now()-s,metadata:{source:"retry-layer",outcome:"ceiling-reached"}}),yield a;return}if(i||($(e.traceWriter,{phase:"overload_pause",metadata:{reason:"overloaded",source:"retry-layer",hasResetTimestamp:!1,ceilingMs:o,surface:t.surface??"unknown"}}),i=!0),await Ie(Math.min(oE(),c),e.signal),n()){yield a;return}if(e.signal.aborted)return;e.headers=t.rotateHeaders(e),yield{type:"stream.retry",sessionId:e.ctx.sessionId}}}var Lc=class{_client;_authMode;initSessionId;baseUrl;tokenRefresher;autoResumeOnUsageLimit;surface;refreshPromise=null;usageLimitWaitPromise=null;credentialSnapshotStale=!1;constructor(e){this._client=e.client,this._authMode=e.authMode,this.initSessionId=e.initSessionId,this.baseUrl=e.baseUrl,this.tokenRefresher=e.tokenRefresher,this.autoResumeOnUsageLimit=e.autoResumeOnUsageLimit,e.surface!==void 0&&(this.surface=e.surface)}get client(){return this._client}get authMode(){return this._authMode}rotateHeaders(e){return Ot(this._authMode,this.initSessionId,RK(),e.effort!==void 0,xc({...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{}}),e.fastMode===!0)}tierContext(){let e=this;return{get authMode(){return e._authMode},get surface(){return e.surface},get autoResumeOnUsageLimit(){return e.autoResumeOnUsageLimit},get tokenRefresher(){return e.tokenRefresher},getClient:()=>e._client,rotateHeaders:n=>e.rotateHeaders(n),forceClientRefresh:()=>e.forceClientRefresh(),getUsageLimitWait:()=>e.usageLimitWaitPromise,setUsageLimitWait:n=>{e.usageLimitWaitPromise=n},markCredentialSnapshotStale:()=>{e.credentialSnapshotStale=!0}}}async forceClientRefresh(){if(!this.tokenRefresher)return null;let e=xe(),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=xe();return{accountId:Vn(r??""),swapped:e!==r}}async*turnWithRetries(e,n){this.credentialSnapshotStale&&(await this.forceClientRefresh()&&(e.client=this._client,e.headers=this.rotateHeaders(e)),this.credentialSnapshotStale=!1);let r=this.tierContext();yield*IE(r,e,n,(o,s,i)=>RE(o,s,i,TE))}};var IK=[{value:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",description:"Balanced Claude \u2014 recommended default (1M context, 128k output)"},{value:"claude-sonnet-5",displayName:"Claude Sonnet 5",description:"Newer balanced Claude \u2014 adaptive thinking, new tokenizer"},{value:"claude-opus-5",displayName:"Claude Opus 5",description:"Highest-capability Claude for agentic coding"},{value:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",description:"Fastest, cheapest Claude"}];function CE(){return IK.map(t=>({...t}))}import{randomUUID as CK}from"node:crypto";function Nc(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)}async function*PE(t){if(t.state.autoCompactThreshold===void 0||t.state.closed)return;let e=t.state.lastUsage,n=mt(t.state.requestedModel);if(e===null||n<=0)return;let r=pe(e);if(Yr(r,n,t.state.autoCompactThreshold))try{t.hookRegistry&&await t.hookRegistry.dispatch({event:"PreCompact",sessionId:t.initSessionId,trigger:"auto"}),(await t.compact()).compacted&&(t.state.lastUsage=null)}catch(o){if(!(o instanceof W))throw o}}async function*ME(t){yield{type:"session.init",info:{sessionId:t.initSessionId,model:t.state.currentModel,permissionMode:t.state.currentPermissionMode,cwd:process.cwd(),tools:[],slashCommands:[],skills:[],plugins:[],mcpServers:t.mcpManager?.getServerStates().map(r=>({name:r.serverName,status:r.status}))??[],apiKeySource:t.retry.authMode,version:"anthropic-direct-v1"}};let n=t.promptStream[Symbol.asyncIterator]();try{for(;!t.state.closed;){let r=await Promise.race([n.next(),t.abort.closedPromise]);if(r==="__closed__")break;let o=r;if(o.done)break;let s=o.value,i=t.abort.begin();if(i.signal.aborted){t.abort.clear(i);return}Nc(t.state.messages);{let u;try{Zr(pe(t.state.lastUsage??{}),t.maxTokens,Ve(t.state.requestedModel??t.state.currentModel),t.state.requestedModel??t.state.currentModel)}catch(p){u=p instanceof Error?p:new Error(String(p))}if(u!==void 0){t.abort.clear(i),yield{type:"error",error:u};continue}}t.state.messages.push({role:"user",content:s.content});let a=t.composeSystem(),{decision:c,runInput:l}=dE({client:t.retry.client,messages:t.state.messages,system:a,tools:t.state.currentPermissionMode==="plan"?t.tools:t.tools?.filter(u=>u.name!==vt)??null,toolDispatcher:t.state.toolDispatcher,model:t.state.currentModel,maxTokens:t.maxTokens,signal:i.signal,authMode:t.retry.authMode,sessionId:t.initSessionId,requestId:CK(),...t.fastModeController?{fastModeController:t.fastModeController}:{},...t.thinking!==void 0?{thinking:t.thinking}:{},...t.effort!==void 0?{effort:t.effort}:{},...t.temperature!==void 0?{temperature:t.temperature}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...t.maxToolUseIterations!==void 0?{maxToolUseIterations:t.maxToolUseIterations}:{},...t.softDeadlineMs!==void 0?{softDeadlineMs:t.softDeadlineMs}:{},...t.traceWriter?{traceWriter:t.traceWriter}:{},...t.subagentId!==void 0?{subagentId:t.subagentId}:{},...t.throttleQueue?{throttleQueue:t.throttleQueue}:{},...t.beforeNextRound?{beforeNextRound:t.beforeNextRound}:{},onUsageProgress:u=>{t.state.lastUsage=u}}),d=!1;try{for await(let u of t.retry.turnWithRetries(l,()=>t.state.closed)){if(u.type==="turn.completed"){if(t.state.lastUsage=u.usage,t.abort.clear(i),d=!0,yield u,t.state.closed)return;continue}if(t.state.closed)return;u.type==="error"&&(d=!0),yield u}}catch(u){if(t.state.closed)return;if(i.signal.aborted){t.abort.clear(i),d||(yield t.makeInterruptedTurnEvent());continue}yield{type:"error",error:Mc(u,c?.effective===!0)};return}finally{t.abort.clear(i)}if(t.state.closed)return;if(i.signal.aborted){d||(yield t.makeInterruptedTurnEvent());continue}yield*PE(t)}}catch(r){yield{type:"error",error:r instanceof Error?r:new Error(String(r))}}finally{try{await n.return?.()}catch{}}}function OE(t){let e=t.lastUsage,n=Ve(t.requestedModel),r;if(e&&n>0){let i=pe(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=Vr(e);return{tools:[],agents:[],isAutoCompactEnabled:t.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}function DE(t){return t?t.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}function FE(t){return{subscriptionType:t==="oauth"?"claude-subscription":"api-key"}}function LE(t){let{state:e,systemPrefix:n,baseUrl:r}=t;e.userSystem&&(e.userSystem=Ua(e.userSystem));let o=[];n&&n.length>0&&o.push(...n),e.userSystem&&e.userSystem.length>0&&o.push({type:"text",text:e.userSystem});let s=Ep(e.currentPermissionMode);s!==null&&o.push(s);let i=Ap(e.currentPermissionMode);return i!==null&&o.push(i),o.length===0?null:ds({baseUrl:r})?q_(o,En()):o}function NE(t,e){e===void 0||e.length===0||(t.requestedModel=e,t.currentModel=he(e)??e)}function UE(t){let{state:e,mode:n,onPermissionMode:r}=t;e.currentPermissionMode=n,e.toolDispatcher.setAllowAll?.(Ye(n)),r?.(n)}function $E(t){let{state:e,cwd:n,cwdDependentsFactory:r}=t;if(e.toolDispatcher.setResolveBase?.(n),!r)return;let{userSystem:o,dispatcher:s}=r(n);e.userSystem=o,e.toolDispatcher=s}function BE(t){let{state:e,basePrompt:n,systemPromptRebuildFactory:r}=t;return r?(e.userSystem=r(n),!0):!1}function jE(t){return{type:"turn.completed",usage:{stopReason:"interrupted",resultSubtype:"interrupted",isError:!1},sessionId:t}}import{randomUUID as NK}from"node:crypto";function PK(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 MK(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=GE(r.input);n.push(`[tool call: ${s} ${i}]`)}else if(o==="tool_result"){let s=r.content;n.push(`[tool result: ${XE(s)}]`)}else o==="image"?n.push("[image]"):o==="document"&&n.push("[document]")}return n.join(`
|
|
1263
1263
|
`)}function OK(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+=GE(n.input).length:r==="tool_result"&&(e+=XE(n.content).length)}return e}var Uc={isFreshUserTurn:PK,renderMessage:MK,buildPreamble(t){return[{role:"user",content:Xo+`
|
|
1264
1264
|
|
|
1265
|
-
`+t},{role:"assistant",content:zo}]},countChars:OK};function DK(t){if(typeof t=="string")return Tn(t);if(Array.isArray(t)){let e=0;for(let n of t)n.type==="text"&&"text"in n&&(e+=Tn(n.text));return e}return 0}function FK(t){if(typeof t=="string")return gr(t);if(Array.isArray(t)){for(let e of t)if(e.type==="text"&&"text"in e)return gr(e.text)}return!1}var LK={listToolResults(t){let e=[];for(let n of t){if(n.role!=="user"||!Array.isArray(n.content))continue;let r=n.content;for(let o of r){if(o.type!=="tool_result")continue;let s=o;e.push({byteLength:DK(s.content),isPlaceholder:FK(s.content),clear(i){s.content=i}})}}return e}};function pf(t,e){return Wa(t,LK,e??{})}function HE(t,e,n,r){return yp(t,e,Uc,n,r)}function WE(t,e,n){let r=bp(t,Uc);return{model:e,max_tokens:n,system:Go,messages:[{role:"user",content:Jo(r)}],stream:!0}}function KE(t,e,n){return wp(t,e,n,Uc)}function qE(t,e,n){return Sp(t,e,n,Uc)}function GE(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function XE(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""}C();var UK=2,$K="claude-haiku-4-5-20251001",BK=1024;async function JE(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=jK(),c=Qr(pe(e.lastUsage??{}),mt(e.requestedModel)),l=HE(e.messages,a,c,HK());if(l<0)return zE(e,i,"history-too-short");if(l===0)return zE(e,i,"nothing-to-summarize");let d=e.messages.slice(0,l),u=WK(),p=WE(d,u,BK),f=n.begin(),m;try{if(f.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let w=Ot(r.authMode,o,NK()),k=r.client,v=await Promise.resolve(k.messages.create(p,{headers:w,signal:f.signal}));m=await KK(v)}catch(w){return f.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(w instanceof Error?w.message:String(w)),messagesBefore:i,messagesAfter:i}}finally{n.clear(f)}if(m.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let g=qE(e.messages,l,m),h=KE(e.messages,l,m);e.messages.splice(0,e.messages.length,...h);let y=e.messages.length;return Js(s,{trigger:"manual",preCompactionMessages:d,summary:m,keptTailCount:i-l,keepLastNConfig:a,messagesBefore:i,messagesAfter:y,tokensSavedEstimate:g}),pf(e.messages,VE()),{compacted:!0,messagesBefore:i,messagesAfter:y,tokensSavedEstimate:g}}function jK(){let t=b.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 UK}function HK(){let t=b.AFK_COMPACT_SHRINK_FRACTION;if(t!==void 0&&t.length>0){let e=Number.parseFloat(t);if(Number.isFinite(e)&&e>0&&e<1)return e}return mr}function zE(t,e,n){let r=VE(),{blocksCleared:o,bytesReclaimed:s}=pf(t.messages,r);return o>0?{compacted:!1,reason:"microcompacted",messagesBefore:e,messagesAfter:t.messages.length,microcompaction:{blocksCleared:o,bytesReclaimed:s}}:{compacted:!1,reason:n,messagesBefore:e,messagesAfter:e}}function VE(){return hr(b.AFK_MICROCOMPACT_TOOL_RESULT_BYTES,b.AFK_MICROCOMPACT_KEEP_LAST)}function WK(){let t=b.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?he(t)??t:$K}async function KK(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 YE=72;function ff(t){if(typeof t=="string")return t;let e=[];for(let n of t)n.type==="text"&&typeof n.text=="string"&&e.push(n.text);return e.join(" ")}function QE(t){return t.role!=="user"?!1:ff(t.content).trim().length>0}function qK(t){let e=t.replace(/\s+/g," ").trim();return e.length<=YE?e:e.slice(0,YE-1)+"\u2026"}function ZE(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];r&&QE(r)&&e.push({turnIndex:n,preview:qK(ff(r.content))})}return e.reverse()}function eA(t,e){let{state:n,abort:r}=t,o=n.messages.length;if(n.closed)return{rewound:!1,reason:"session-closed",messagesBefore:o,messagesAfter:o};if(!r.isIdle())return{rewound:!1,reason:"turn-in-flight",messagesBefore:o,messagesAfter:o};if(!Number.isInteger(e)||e<0||e>=o)return{rewound:!1,reason:"invalid-target",messagesBefore:o,messagesAfter:o};let s=n.messages[e];if(!s||!QE(s))return{rewound:!1,reason:"invalid-target",messagesBefore:o,messagesAfter:o};let i=ff(s.content);return n.messages.splice(e),Nc(n.messages),{rewound:!0,reloadText:i,messagesBefore:o,messagesAfter:n.messages.length}}function tA(t){return JE(t)}function nA(t){return ZE(t.messages)}function rA(t,e,n){return eA({state:t,abort:e},n)}var fs=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;temperature;baseUrl;maxToolUseIterations;softDeadlineMs;traceWriter;subagentId;state;abort;retry;cwdDependentsFactory;systemPromptRebuildFactory;onPermissionMode;mcpManager;hookRegistry;throttleQueue;fastModeController;beforeNextRound;constructor(e){this.initSessionId=e.sessionId??GK(),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.temperature!==void 0&&(this.temperature=e.temperature),e.baseUrl!==void 0&&(this.baseUrl=e.baseUrl),e.maxToolUseIterations!==void 0&&(this.maxToolUseIterations=e.maxToolUseIterations),e.softDeadlineMs!==void 0&&(this.softDeadlineMs=e.softDeadlineMs),this.traceWriter=e.traceWriter,e.subagentId!==void 0&&(this.subagentId=e.subagentId),this.cwdDependentsFactory=e.cwdDependentsFactory,this.systemPromptRebuildFactory=e.systemPromptRebuildFactory,this.onPermissionMode=e.onPermissionMode,this.mcpManager=e.mcpManager,e.hookRegistry!==void 0&&(this.hookRegistry=e.hookRegistry),e.throttleQueue!==void 0&&(this.throttleQueue=e.throttleQueue),e.fastModeController!==void 0&&(this.fastModeController=e.fastModeController),e.beforeNextRound!==void 0&&(this.beforeNextRound=e.beforeNextRound),this.retry=new Lc({client:e.client,authMode:e.authMode,initSessionId:this.initSessionId,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.tokenRefresher?{tokenRefresher:e.tokenRefresher}:{},autoResumeOnUsageLimit:e.autoResumeOnUsageLimit??!0,...e.surface!==void 0?{surface:e.surface}:{}}),this.state=K_({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}:{},...e.initialUsageInputTokens!==void 0?{initialUsageInputTokens:e.initialUsageInputTokens}:{}}),this.abort=new fr}turnDriverContext(){let e=this;return{get initSessionId(){return e.initSessionId},get promptStream(){return e.promptStream},get state(){return e.state},get abort(){return e.abort},get retry(){return e.retry},get maxTokens(){return e.maxTokens},get tools(){return e.tools},get thinking(){return e.thinking},get effort(){return e.effort},get temperature(){return e.temperature},get baseUrl(){return e.baseUrl},get maxToolUseIterations(){return e.maxToolUseIterations},get softDeadlineMs(){return e.softDeadlineMs},get traceWriter(){return e.traceWriter},get subagentId(){return e.subagentId},get mcpManager(){return e.mcpManager},get hookRegistry(){return e.hookRegistry},get throttleQueue(){return e.throttleQueue},get fastModeController(){return e.fastModeController},get beforeNextRound(){return e.beforeNextRound},composeSystem:()=>e.composeSystem(),makeInterruptedTurnEvent:()=>e.makeInterruptedTurnEvent(),compact:()=>e.compact()}}setBeforeNextRound(e){this.beforeNextRound=e}async*[Symbol.asyncIterator](){yield*ME(this.turnDriverContext())}composeSystem(){return LE({state:this.state,systemPrefix:this.systemPrefix,...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{}})}async interrupt(e="interrupted"){this.abort.requestAbort(e)}makeInterruptedTurnEvent(){return jE(this.initSessionId)}async setModel(e){NE(this.state,e)}async setPermissionMode(e){UE({state:this.state,mode:e,...this.onPermissionMode?{onPermissionMode:this.onPermissionMode}:{}})}setCwd(e){$E({state:this.state,cwd:e,...this.cwdDependentsFactory?{cwdDependentsFactory:this.cwdDependentsFactory}:{}})}setSystemPrompt(e){return BE({state:this.state,basePrompt:e,...this.systemPromptRebuildFactory?{systemPromptRebuildFactory:this.systemPromptRebuildFactory}:{}})}async supportedCommands(){return Fa()}async supportedModels(){return CE()}async supportedAgents(){return[]}async getContextUsage(){return OE(this.state)}async mcpServerStatus(){return DE(this.mcpManager)}async accountInfo(){return FE(this.retry.authMode)}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(){let e=await tA({state:this.state,abort:this.abort,retry:this.retry,initSessionId:this.initSessionId,...this.traceWriter?{traceWriter:this.traceWriter}:{}});return e.compacted&&(this.state.lastUsage=null),e}listRewindTargets(){return nA(this.state)}async rewindConversation(e){return rA(this.state,this.abort,e)}close(){this.state.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed()}};function oA(t){return e=>{let n=t.getCurrentCwd();if(t.sharedReadRoots&&n!==void 0&&n!==e){let s=t.sharedReadRoots.indexOf(n);s!==-1?t.sharedReadRoots[s]=e:t.sharedReadRoots.includes(e)||t.sharedReadRoots.push(e)}if(t.sharedWriteRoots&&n!==void 0&&n!==e){let s=t.sharedWriteRoots.indexOf(n);s!==-1?t.sharedWriteRoots[s]=e:t.sharedWriteRoots.includes(e)||t.sharedWriteRoots.push(e)}t.setCurrentCwd(e),t.subagentExecutor?.setCwd(e),t.skillExecutor?.setCwd(e),t.composeExecutor?.setCwd(e);let r=vr(t.stableSystemPrefix,e,{surface:t.surface,sessionId:t.config.sessionId,depth:t.config.depth,maxDepth:t.config.maxDepth,workspace:t.runtimeStateSource.getWorkspace()}),o=t.buildDispatcher(t.getCurrentPermissionMode(),{cwd:e,readRoots:t.sharedReadRoots,writeRoots:t.sharedWriteRoots,...t.config.env!==void 0?{env:t.config.env}:{},sessionId:t.config.sessionId,parentSessionId:t.config.parentSessionId,traceWriter:t.config.traceWriter,runtimeStateSource:t.runtimeStateSource,hookRegistry:t.config.hookRegistry,planExitControls:t.config.planExitControls});return{userSystem:r,dispatcher:o}}}function sA(t){return e=>{t.stableSystemPrefix.userSystem=e!==void 0&&e.length>0?e:null;let n=t.getCurrentCwd()??t.fallbackCwd;return vr(t.stableSystemPrefix,n,{surface:t.surface,sessionId:t.config.sessionId,depth:t.config.depth,maxDepth:t.config.maxDepth,workspace:t.runtimeStateSource.getWorkspace()})}}function iA(t,e,n){let r=e.config,{client:o,authMode:s,localMode:i,model:a,maxTokens:c,cwd:l,systemPrefix:d,throttleQueue:u,tokenRefresher:p,queryDispatcher:f,runtimeStateSource:m,toolDefs:g,resolvedSessionId:h,stableSystemPrefix:y,toolSystemAppend:w}=n,k=h,v=dg(r.resumeHistory),E=r.resumeHistory?.at(-1)?.inputTokens,T=t.externalTools?void 0:oA({stableSystemPrefix:y,config:r,surface:t.surface,runtimeStateSource:m,getCurrentCwd:()=>t.getCurrentCwd(),setCurrentCwd:D=>{t.setCurrentCwd(D)},getCurrentPermissionMode:()=>t.getCurrentPermissionMode(),sharedReadRoots:t.getSharedReadRoots(),sharedWriteRoots:t.getSharedWriteRoots(),subagentExecutor:t.subagentExecutor,skillExecutor:t.skillExecutor,composeExecutor:t.composeExecutor,buildDispatcher:(D,G)=>t.buildDispatcher(D,G)}),I=t.externalTools?void 0:sA({stableSystemPrefix:y,config:r,surface:t.surface,runtimeStateSource:m,getCurrentCwd:()=>t.getCurrentCwd(),fallbackCwd:l}),S=oi(r.effort,a),A=r.temperature!==void 0?lg(r.temperature):void 0,R=eo(r.autoCompact,typeof r.model=="string"&&r.model.length>0?r.model:a);return new fs({client:o,authMode:i?"api-key":s,promptStream:e.prompt,toolDispatcher:f,...k!==void 0?{sessionId:k}:{},...v!==void 0?{initialMessages:v}:{},...E!==void 0?{initialUsageInputTokens:E}:{},model:a,requestedModel:typeof r.model=="string"&&r.model.length>0?r.model:a,...r.permissionMode!==void 0?{permissionMode:r.permissionMode}:{},maxTokens:c,tools:g,userSystem:w,systemPrefix:d,tokenRefresher:p,...r.thinking!==void 0?{thinking:ri(r.thinking,c,a)}:{},...S!==void 0?{effort:S}:{},...A!==void 0?{temperature:A}:{},...i?{baseUrl:r.baseUrl}:{},...r.traceWriter?{traceWriter:r.traceWriter}:{},...r.subagentId!==void 0?{subagentId:r.subagentId}:{},...r.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:r.autoResumeOnUsageLimit}:{},surface:t.declaredSurface,...r.maxToolUseIterations!==void 0?{maxToolUseIterations:r.maxToolUseIterations}:{},...r.softDeadlineMs!==void 0?{softDeadlineMs:r.softDeadlineMs}:{},...T!==void 0?{cwdDependentsFactory:T}:{},...I!==void 0?{systemPromptRebuildFactory:I}:{},onPermissionMode:D=>{t.setCurrentPermissionMode(D)},...t.mcpManager!==void 0?{mcpManager:t.mcpManager}:{},...R!==void 0?{autoCompactThreshold:R}:{},...r.hookRegistry!==void 0?{hookRegistry:r.hookRegistry}:{},...u!==void 0?{throttleQueue:u}:{},...t.fastModeController!==void 0?{fastModeController:t.fastModeController}:{}})}var mf="anthropic-direct",aA=Xr,xt=class{name=mf;externalTools;memoryStore;workspaceStore;stateStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;composeExecutor;surface;declaredSurface;readOnlyMemory;readOnlyBash;mcpManager;customTools;fastModeController;grants=new si;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;_mintedSessionId=null;_spawnedPidRegistry=new ar;constructor(e={}){if(this.memoryStore=e.memoryStore??new bt,this.workspaceStore=e.workspaceStore,this.stateStore=e.stateStore??new ir($s()),this.externalTools=e.tools,this.skillExecutor=e.skillExecutor,this.schemas=jk(e),this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.canUseTool=e.canUseTool,this.subagentExecutor=e.subagentExecutor,this.composeExecutor=e.composeExecutor,this.surface=e.surface??"cli",this.declaredSurface=e.surface,this.readOnlyMemory=e.readOnlyMemory===!0,this.readOnlyBash=e.readOnlyBash===!0,this.customTools=e.customTools??[],this.fastModeController=e.fastModeController,this.mcpManager=e.mcpManager,e.mcpManager){let n=e.mcpManager.onToolsRefreshed;e.mcpManager.onToolsRefreshed=r=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,n?.(r)}}e.clientFactory&&(this.providerFactory=e.clientFactory)}buildDispatcher(e,n){return Uk({memoryStore:this.memoryStore,workspaceStore:this.workspaceStore,stateStore:this.stateStore,surface:this.surface,readOnlyMemory:this.readOnlyMemory,readOnlyBash:this.readOnlyBash,customTools:this.customTools,mcpManager:this.mcpManager,schemas:this.schemas,hookRegistry:this.hookRegistry,permissions:this.permissions,canUseTool:this.canUseTool,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,sessionGrantManager:this,getMcpToolsCache:()=>this._mcpToolsCache,setMcpToolsCache:r=>{this._mcpToolsCache=r},getMcpHandlersCache:()=>this._mcpHandlersCache,setMcpHandlersCache:r=>{this._mcpHandlersCache=r}},e,{...n,spawnedPidRegistry:this._spawnedPidRegistry})}close(){this.memoryStore.close(),this.workspaceStore?.close(),this.stateStore.close()}async complete(e){let n=e.apiKey&&e.apiKey.length>0?e.apiKey:b.ANTHROPIC_API_KEY||b.CLAUDE_CODE_OAUTH_TOKEN||"";if(!n)throw new Error(`${mf} complete() requires an API key or OAuth token (config apiKey, ANTHROPIC_API_KEY, or CLAUDE_CODE_OAUTH_TOKEN)`);let r={token:n,model:e.model??aA,system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.signal&&(r.signal=e.signal);let o=this.providerFactory??Ta();return o&&(r.clientFactory=o),ng(r)}addReadRoot(e,n="slash",r){this.grants.manager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grants.manager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grants.manager.revokeRoot(e,n,r)}getGrants(){return this.grants.manager.getGrants()}queryContext(){let e=this;return{get externalTools(){return e.externalTools},get providerFactory(){return e.providerFactory},get skillExecutor(){return e.skillExecutor},get subagentExecutor(){return e.subagentExecutor},get composeExecutor(){return e.composeExecutor},get canUseTool(){return e.canUseTool},get surface(){return e.surface},get declaredSurface(){return e.declaredSurface},get readOnlyMemory(){return e.readOnlyMemory},get workspaceStore(){return e.workspaceStore},get mcpManager(){return e.mcpManager},get fastModeController(){return e.fastModeController},getSharedReadRoots:()=>e.grants.readRoots,getSharedWriteRoots:()=>e.grants.writeRoots,getCurrentCwd:()=>e.grants.currentCwd,setCurrentCwd:n=>{e.grants.currentCwd=n},getCurrentPermissionMode:()=>e.grants.permissionMode,setCurrentPermissionMode:n=>{e.grants.permissionMode=n},getMintedSessionId:()=>e._mintedSessionId,setMintedSessionId:n=>{e._mintedSessionId=n},getPresenceSessionId:()=>e._presenceSessionId,setPresenceSessionId:n=>{e._presenceSessionId=n},ensureSharedRoots:n=>{e.grants.ensureInitialized(n)},buildDispatcher:(n,r)=>e.buildDispatcher(n,r)}}query(e){let n=this.queryContext(),r=W_(n,e,mf,aA);return iA(n,e,r)}},cA=new xt;C();M();import{chmodSync as zK,existsSync as JK,mkdirSync as VK,readFileSync as YK,unlinkSync as QK,writeFileSync as ZK}from"node:fs";import{dirname as eq,join as tq}from"node:path";function Tr(){return tq(Q(),"xai","auth.json")}function nq(t){try{return YK(t,"utf-8")}catch{return null}}function rq(t,e,n){ZK(t,e,{encoding:"utf-8",mode:n})}function oq(t,e){zK(t,e)}function sq(t){VK(t,{recursive:!0})}function iq(t){try{QK(t)}catch{}}function aq(t){let e;try{e=JSON.parse(t)}catch{return null}if(typeof e!="object"||e===null)return null;let n=e,r=n.access_token,o=n.refresh_token,s=n.expires_at;if(typeof r!="string"||r.length===0||typeof o!="string"||o.length===0||typeof s!="number"||!Number.isFinite(s))return null;let i={access_token:r,refresh_token:o,expires_at:s};return typeof n.token_type=="string"&&(i.token_type=n.token_type),typeof n.scope=="string"&&(i.scope=n.scope),i}function _r(t={}){let e=(t.authPath??Tr)(),r=(t.readFile??nq)(e);return r===null?null:aq(r)}function gf(t,e={}){let n=(e.authPath??Tr)(),r=e.mkdir??sq,o=e.writeFile??rq,s=e.chmod??oq;r(eq(n));let i={access_token:t.access_token,refresh_token:t.refresh_token,expires_at:t.expires_at};t.token_type!==void 0&&(i.token_type=t.token_type),t.scope!==void 0&&(i.scope=t.scope),o(n,`${JSON.stringify(i,null,2)}
|
|
1265
|
+
`+t},{role:"assistant",content:zo}]},countChars:OK};function DK(t){if(typeof t=="string")return Tn(t);if(Array.isArray(t)){let e=0;for(let n of t)n.type==="text"&&"text"in n&&(e+=Tn(n.text));return e}return 0}function FK(t){if(typeof t=="string")return gr(t);if(Array.isArray(t)){for(let e of t)if(e.type==="text"&&"text"in e)return gr(e.text)}return!1}var LK={listToolResults(t){let e=[];for(let n of t){if(n.role!=="user"||!Array.isArray(n.content))continue;let r=n.content;for(let o of r){if(o.type!=="tool_result")continue;let s=o;e.push({byteLength:DK(s.content),isPlaceholder:FK(s.content),clear(i){s.content=i}})}}return e}};function pf(t,e){return Wa(t,LK,e??{})}function HE(t,e,n,r){return yp(t,e,Uc,n,r)}function WE(t,e,n){let r=bp(t,Uc);return{model:e,max_tokens:n,system:Go,messages:[{role:"user",content:Jo(r)}],stream:!0}}function KE(t,e,n){return wp(t,e,n,Uc)}function qE(t,e,n){return Sp(t,e,n,Uc)}function GE(t){try{let e=JSON.stringify(t);return e.length>240?e.slice(0,237)+"...":e}catch{return"{}"}}function XE(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""}C();var UK=2,$K="claude-haiku-4-5-20251001",BK=1024;async function JE(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=jK(),c=Qr(pe(e.lastUsage??{}),mt(e.requestedModel)),l=HE(e.messages,a,c,HK());if(l<0)return zE(e,i,"history-too-short");if(l===0)return zE(e,i,"nothing-to-summarize");let d=e.messages.slice(0,l),u=WK(),p=WE(d,u,BK),f=n.begin(),m;try{if(f.signal.aborted)return{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i};let w=Ot(r.authMode,o,NK()),S=r.client,v=await Promise.resolve(S.messages.create(p,{headers:w,signal:f.signal}));m=await KK(v)}catch(w){return f.signal.aborted?{compacted:!1,reason:"aborted",messagesBefore:i,messagesAfter:i}:{compacted:!1,reason:"summarization-failed: "+(w instanceof Error?w.message:String(w)),messagesBefore:i,messagesAfter:i}}finally{n.clear(f)}if(m.trim().length===0)return{compacted:!1,reason:"empty-summary",messagesBefore:i,messagesAfter:i};let g=qE(e.messages,l,m),h=KE(e.messages,l,m);e.messages.splice(0,e.messages.length,...h);let y=e.messages.length;return Js(s,{trigger:"manual",preCompactionMessages:d,summary:m,keptTailCount:i-l,keepLastNConfig:a,messagesBefore:i,messagesAfter:y,tokensSavedEstimate:g}),pf(e.messages,VE()),{compacted:!0,messagesBefore:i,messagesAfter:y,tokensSavedEstimate:g}}function jK(){let t=b.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 UK}function HK(){let t=b.AFK_COMPACT_SHRINK_FRACTION;if(t!==void 0&&t.length>0){let e=Number.parseFloat(t);if(Number.isFinite(e)&&e>0&&e<1)return e}return mr}function zE(t,e,n){let r=VE(),{blocksCleared:o,bytesReclaimed:s}=pf(t.messages,r);return o>0?{compacted:!1,reason:"microcompacted",messagesBefore:e,messagesAfter:t.messages.length,microcompaction:{blocksCleared:o,bytesReclaimed:s}}:{compacted:!1,reason:n,messagesBefore:e,messagesAfter:e}}function VE(){return hr(b.AFK_MICROCOMPACT_TOOL_RESULT_BYTES,b.AFK_MICROCOMPACT_KEEP_LAST)}function WK(){let t=b.AFK_COMPACT_MODEL;return t!==void 0&&t.length>0?he(t)??t:$K}async function KK(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 YE=72;function ff(t){if(typeof t=="string")return t;let e=[];for(let n of t)n.type==="text"&&typeof n.text=="string"&&e.push(n.text);return e.join(" ")}function QE(t){return t.role!=="user"?!1:ff(t.content).trim().length>0}function qK(t){let e=t.replace(/\s+/g," ").trim();return e.length<=YE?e:e.slice(0,YE-1)+"\u2026"}function ZE(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];r&&QE(r)&&e.push({turnIndex:n,preview:qK(ff(r.content))})}return e.reverse()}function eA(t,e){let{state:n,abort:r}=t,o=n.messages.length;if(n.closed)return{rewound:!1,reason:"session-closed",messagesBefore:o,messagesAfter:o};if(!r.isIdle())return{rewound:!1,reason:"turn-in-flight",messagesBefore:o,messagesAfter:o};if(!Number.isInteger(e)||e<0||e>=o)return{rewound:!1,reason:"invalid-target",messagesBefore:o,messagesAfter:o};let s=n.messages[e];if(!s||!QE(s))return{rewound:!1,reason:"invalid-target",messagesBefore:o,messagesAfter:o};let i=ff(s.content);return n.messages.splice(e),Nc(n.messages),{rewound:!0,reloadText:i,messagesBefore:o,messagesAfter:n.messages.length}}function tA(t){return JE(t)}function nA(t){return ZE(t.messages)}function rA(t,e,n){return eA({state:t,abort:e},n)}var fs=class{initSessionId;promptStream;maxTokens;tools;systemPrefix;thinking;effort;temperature;baseUrl;maxToolUseIterations;softDeadlineMs;traceWriter;subagentId;state;abort;retry;cwdDependentsFactory;systemPromptRebuildFactory;onPermissionMode;mcpManager;hookRegistry;throttleQueue;fastModeController;beforeNextRound;constructor(e){this.initSessionId=e.sessionId??GK(),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.temperature!==void 0&&(this.temperature=e.temperature),e.baseUrl!==void 0&&(this.baseUrl=e.baseUrl),e.maxToolUseIterations!==void 0&&(this.maxToolUseIterations=e.maxToolUseIterations),e.softDeadlineMs!==void 0&&(this.softDeadlineMs=e.softDeadlineMs),this.traceWriter=e.traceWriter,e.subagentId!==void 0&&(this.subagentId=e.subagentId),this.cwdDependentsFactory=e.cwdDependentsFactory,this.systemPromptRebuildFactory=e.systemPromptRebuildFactory,this.onPermissionMode=e.onPermissionMode,this.mcpManager=e.mcpManager,e.hookRegistry!==void 0&&(this.hookRegistry=e.hookRegistry),e.throttleQueue!==void 0&&(this.throttleQueue=e.throttleQueue),e.fastModeController!==void 0&&(this.fastModeController=e.fastModeController),e.beforeNextRound!==void 0&&(this.beforeNextRound=e.beforeNextRound),this.retry=new Lc({client:e.client,authMode:e.authMode,initSessionId:this.initSessionId,...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},...e.tokenRefresher?{tokenRefresher:e.tokenRefresher}:{},autoResumeOnUsageLimit:e.autoResumeOnUsageLimit??!0,...e.surface!==void 0?{surface:e.surface}:{}}),this.state=K_({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}:{},...e.initialUsageInputTokens!==void 0?{initialUsageInputTokens:e.initialUsageInputTokens}:{}}),this.abort=new fr}turnDriverContext(){let e=this;return{get initSessionId(){return e.initSessionId},get promptStream(){return e.promptStream},get state(){return e.state},get abort(){return e.abort},get retry(){return e.retry},get maxTokens(){return e.maxTokens},get tools(){return e.tools},get thinking(){return e.thinking},get effort(){return e.effort},get temperature(){return e.temperature},get baseUrl(){return e.baseUrl},get maxToolUseIterations(){return e.maxToolUseIterations},get softDeadlineMs(){return e.softDeadlineMs},get traceWriter(){return e.traceWriter},get subagentId(){return e.subagentId},get mcpManager(){return e.mcpManager},get hookRegistry(){return e.hookRegistry},get throttleQueue(){return e.throttleQueue},get fastModeController(){return e.fastModeController},get beforeNextRound(){return e.beforeNextRound},composeSystem:()=>e.composeSystem(),makeInterruptedTurnEvent:()=>e.makeInterruptedTurnEvent(),compact:()=>e.compact()}}setBeforeNextRound(e){this.beforeNextRound=e}async*[Symbol.asyncIterator](){yield*ME(this.turnDriverContext())}composeSystem(){return LE({state:this.state,systemPrefix:this.systemPrefix,...this.baseUrl!==void 0?{baseUrl:this.baseUrl}:{}})}async interrupt(e="interrupted"){this.abort.requestAbort(e)}makeInterruptedTurnEvent(){return jE(this.initSessionId)}async setModel(e){NE(this.state,e)}async setPermissionMode(e){UE({state:this.state,mode:e,...this.onPermissionMode?{onPermissionMode:this.onPermissionMode}:{}})}setCwd(e){$E({state:this.state,cwd:e,...this.cwdDependentsFactory?{cwdDependentsFactory:this.cwdDependentsFactory}:{}})}setSystemPrompt(e){return BE({state:this.state,basePrompt:e,...this.systemPromptRebuildFactory?{systemPromptRebuildFactory:this.systemPromptRebuildFactory}:{}})}async supportedCommands(){return Fa()}async supportedModels(){return CE()}async supportedAgents(){return[]}async getContextUsage(){return OE(this.state)}async mcpServerStatus(){return DE(this.mcpManager)}async accountInfo(){return FE(this.retry.authMode)}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(){let e=await tA({state:this.state,abort:this.abort,retry:this.retry,initSessionId:this.initSessionId,...this.traceWriter?{traceWriter:this.traceWriter}:{}});return e.compacted&&(this.state.lastUsage=null),e}listRewindTargets(){return nA(this.state)}async rewindConversation(e){return rA(this.state,this.abort,e)}close(){this.state.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed()}};function oA(t){return e=>{let n=t.getCurrentCwd();if(t.sharedReadRoots&&n!==void 0&&n!==e){let s=t.sharedReadRoots.indexOf(n);s!==-1?t.sharedReadRoots[s]=e:t.sharedReadRoots.includes(e)||t.sharedReadRoots.push(e)}if(t.sharedWriteRoots&&n!==void 0&&n!==e){let s=t.sharedWriteRoots.indexOf(n);s!==-1?t.sharedWriteRoots[s]=e:t.sharedWriteRoots.includes(e)||t.sharedWriteRoots.push(e)}t.setCurrentCwd(e),t.subagentExecutor?.setCwd(e),t.skillExecutor?.setCwd(e),t.composeExecutor?.setCwd(e);let r=vr(t.stableSystemPrefix,e,{surface:t.surface,sessionId:t.config.sessionId,depth:t.config.depth,maxDepth:t.config.maxDepth,workspace:t.runtimeStateSource.getWorkspace()}),o=t.buildDispatcher(t.getCurrentPermissionMode(),{cwd:e,readRoots:t.sharedReadRoots,writeRoots:t.sharedWriteRoots,...t.config.env!==void 0?{env:t.config.env}:{},sessionId:t.config.sessionId,parentSessionId:t.config.parentSessionId,traceWriter:t.config.traceWriter,runtimeStateSource:t.runtimeStateSource,hookRegistry:t.config.hookRegistry,planExitControls:t.config.planExitControls});return{userSystem:r,dispatcher:o}}}function sA(t){return e=>{t.stableSystemPrefix.userSystem=e!==void 0&&e.length>0?e:null;let n=t.getCurrentCwd()??t.fallbackCwd;return vr(t.stableSystemPrefix,n,{surface:t.surface,sessionId:t.config.sessionId,depth:t.config.depth,maxDepth:t.config.maxDepth,workspace:t.runtimeStateSource.getWorkspace()})}}function iA(t,e,n){let r=e.config,{client:o,authMode:s,localMode:i,model:a,maxTokens:c,cwd:l,systemPrefix:d,throttleQueue:u,tokenRefresher:p,queryDispatcher:f,runtimeStateSource:m,toolDefs:g,resolvedSessionId:h,stableSystemPrefix:y,toolSystemAppend:w}=n,S=h,v=dg(r.resumeHistory),E=r.resumeHistory?.at(-1)?.inputTokens,T=t.externalTools?void 0:oA({stableSystemPrefix:y,config:r,surface:t.surface,runtimeStateSource:m,getCurrentCwd:()=>t.getCurrentCwd(),setCurrentCwd:D=>{t.setCurrentCwd(D)},getCurrentPermissionMode:()=>t.getCurrentPermissionMode(),sharedReadRoots:t.getSharedReadRoots(),sharedWriteRoots:t.getSharedWriteRoots(),subagentExecutor:t.subagentExecutor,skillExecutor:t.skillExecutor,composeExecutor:t.composeExecutor,buildDispatcher:(D,G)=>t.buildDispatcher(D,G)}),I=t.externalTools?void 0:sA({stableSystemPrefix:y,config:r,surface:t.surface,runtimeStateSource:m,getCurrentCwd:()=>t.getCurrentCwd(),fallbackCwd:l}),k=oi(r.effort,a),A=r.temperature!==void 0?lg(r.temperature):void 0,R=eo(r.autoCompact,typeof r.model=="string"&&r.model.length>0?r.model:a);return new fs({client:o,authMode:i?"api-key":s,promptStream:e.prompt,toolDispatcher:f,...S!==void 0?{sessionId:S}:{},...v!==void 0?{initialMessages:v}:{},...E!==void 0?{initialUsageInputTokens:E}:{},model:a,requestedModel:typeof r.model=="string"&&r.model.length>0?r.model:a,...r.permissionMode!==void 0?{permissionMode:r.permissionMode}:{},maxTokens:c,tools:g,userSystem:w,systemPrefix:d,tokenRefresher:p,...r.thinking!==void 0?{thinking:ri(r.thinking,c,a)}:{},...k!==void 0?{effort:k}:{},...A!==void 0?{temperature:A}:{},...i?{baseUrl:r.baseUrl}:{},...r.traceWriter?{traceWriter:r.traceWriter}:{},...r.subagentId!==void 0?{subagentId:r.subagentId}:{},...r.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:r.autoResumeOnUsageLimit}:{},surface:t.declaredSurface,...r.maxToolUseIterations!==void 0?{maxToolUseIterations:r.maxToolUseIterations}:{},...r.softDeadlineMs!==void 0?{softDeadlineMs:r.softDeadlineMs}:{},...T!==void 0?{cwdDependentsFactory:T}:{},...I!==void 0?{systemPromptRebuildFactory:I}:{},onPermissionMode:D=>{t.setCurrentPermissionMode(D)},...t.mcpManager!==void 0?{mcpManager:t.mcpManager}:{},...R!==void 0?{autoCompactThreshold:R}:{},...r.hookRegistry!==void 0?{hookRegistry:r.hookRegistry}:{},...u!==void 0?{throttleQueue:u}:{},...t.fastModeController!==void 0?{fastModeController:t.fastModeController}:{}})}var mf="anthropic-direct",aA=Xr,xt=class{name=mf;externalTools;memoryStore;workspaceStore;stateStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;composeExecutor;surface;declaredSurface;readOnlyMemory;readOnlyBash;mcpManager;customTools;fastModeController;grants=new si;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;_mintedSessionId=null;_spawnedPidRegistry=new ar;constructor(e={}){if(this.memoryStore=e.memoryStore??new bt,this.workspaceStore=e.workspaceStore,this.stateStore=e.stateStore??new ir($s()),this.externalTools=e.tools,this.skillExecutor=e.skillExecutor,this.schemas=jk(e),this.hookRegistry=e.hookRegistry,this.permissions=e.permissions,this.canUseTool=e.canUseTool,this.subagentExecutor=e.subagentExecutor,this.composeExecutor=e.composeExecutor,this.surface=e.surface??"cli",this.declaredSurface=e.surface,this.readOnlyMemory=e.readOnlyMemory===!0,this.readOnlyBash=e.readOnlyBash===!0,this.customTools=e.customTools??[],this.fastModeController=e.fastModeController,this.mcpManager=e.mcpManager,e.mcpManager){let n=e.mcpManager.onToolsRefreshed;e.mcpManager.onToolsRefreshed=r=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,n?.(r)}}e.clientFactory&&(this.providerFactory=e.clientFactory)}buildDispatcher(e,n){return Uk({memoryStore:this.memoryStore,workspaceStore:this.workspaceStore,stateStore:this.stateStore,surface:this.surface,readOnlyMemory:this.readOnlyMemory,readOnlyBash:this.readOnlyBash,customTools:this.customTools,mcpManager:this.mcpManager,schemas:this.schemas,hookRegistry:this.hookRegistry,permissions:this.permissions,canUseTool:this.canUseTool,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,sessionGrantManager:this,getMcpToolsCache:()=>this._mcpToolsCache,setMcpToolsCache:r=>{this._mcpToolsCache=r},getMcpHandlersCache:()=>this._mcpHandlersCache,setMcpHandlersCache:r=>{this._mcpHandlersCache=r}},e,{...n,spawnedPidRegistry:this._spawnedPidRegistry})}close(){this.memoryStore.close(),this.workspaceStore?.close(),this.stateStore.close()}async complete(e){let n=e.apiKey&&e.apiKey.length>0?e.apiKey:b.ANTHROPIC_API_KEY||b.CLAUDE_CODE_OAUTH_TOKEN||"";if(!n)throw new Error(`${mf} complete() requires an API key or OAuth token (config apiKey, ANTHROPIC_API_KEY, or CLAUDE_CODE_OAUTH_TOKEN)`);let r={token:n,model:e.model??aA,system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.signal&&(r.signal=e.signal);let o=this.providerFactory??Ta();return o&&(r.clientFactory=o),ng(r)}addReadRoot(e,n="slash",r){this.grants.manager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grants.manager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grants.manager.revokeRoot(e,n,r)}getGrants(){return this.grants.manager.getGrants()}queryContext(){let e=this;return{get externalTools(){return e.externalTools},get providerFactory(){return e.providerFactory},get skillExecutor(){return e.skillExecutor},get subagentExecutor(){return e.subagentExecutor},get composeExecutor(){return e.composeExecutor},get canUseTool(){return e.canUseTool},get surface(){return e.surface},get declaredSurface(){return e.declaredSurface},get readOnlyMemory(){return e.readOnlyMemory},get workspaceStore(){return e.workspaceStore},get mcpManager(){return e.mcpManager},get fastModeController(){return e.fastModeController},getSharedReadRoots:()=>e.grants.readRoots,getSharedWriteRoots:()=>e.grants.writeRoots,getCurrentCwd:()=>e.grants.currentCwd,setCurrentCwd:n=>{e.grants.currentCwd=n},getCurrentPermissionMode:()=>e.grants.permissionMode,setCurrentPermissionMode:n=>{e.grants.permissionMode=n},getMintedSessionId:()=>e._mintedSessionId,setMintedSessionId:n=>{e._mintedSessionId=n},getPresenceSessionId:()=>e._presenceSessionId,setPresenceSessionId:n=>{e._presenceSessionId=n},ensureSharedRoots:n=>{e.grants.ensureInitialized(n)},buildDispatcher:(n,r)=>e.buildDispatcher(n,r)}}query(e){let n=this.queryContext(),r=W_(n,e,mf,aA);return iA(n,e,r)}},cA=new xt;C();M();import{chmodSync as zK,existsSync as JK,mkdirSync as VK,readFileSync as YK,unlinkSync as QK,writeFileSync as ZK}from"node:fs";import{dirname as eq,join as tq}from"node:path";function Tr(){return tq(Q(),"xai","auth.json")}function nq(t){try{return YK(t,"utf-8")}catch{return null}}function rq(t,e,n){ZK(t,e,{encoding:"utf-8",mode:n})}function oq(t,e){zK(t,e)}function sq(t){VK(t,{recursive:!0})}function iq(t){try{QK(t)}catch{}}function aq(t){let e;try{e=JSON.parse(t)}catch{return null}if(typeof e!="object"||e===null)return null;let n=e,r=n.access_token,o=n.refresh_token,s=n.expires_at;if(typeof r!="string"||r.length===0||typeof o!="string"||o.length===0||typeof s!="number"||!Number.isFinite(s))return null;let i={access_token:r,refresh_token:o,expires_at:s};return typeof n.token_type=="string"&&(i.token_type=n.token_type),typeof n.scope=="string"&&(i.scope=n.scope),i}function _r(t={}){let e=(t.authPath??Tr)(),r=(t.readFile??nq)(e);return r===null?null:aq(r)}function gf(t,e={}){let n=(e.authPath??Tr)(),r=e.mkdir??sq,o=e.writeFile??rq,s=e.chmod??oq;r(eq(n));let i={access_token:t.access_token,refresh_token:t.refresh_token,expires_at:t.expires_at};t.token_type!==void 0&&(i.token_type=t.token_type),t.scope!==void 0&&(i.scope=t.scope),o(n,`${JSON.stringify(i,null,2)}
|
|
1266
1266
|
`,384),s(n,384)}function hf(t={}){let e=(t.authPath??Tr)(),n=t.exists??(o=>JK(o)),r=t.unlink??iq;n(e)&&r(e)}function $c(t){return t.length<=4?t:t.slice(-4)}C();C();import{readFileSync as cq}from"node:fs";import{homedir as lq}from"node:os";import{join as dq}from"node:path";var yf="cli-chat-proxy.grok.com",lA="1.0.5",uq="AFK_XAI_GROK_CLIENT_VERSION",pq=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function bf(t){let e=t?.trim();return e&&pq.test(e)?e:void 0}function fq(t,e){if(!t)return;let n=l=>l.split(".").map(Number),[r=0,o=0,s=0]=n(t),[i=0,a=0,c=0]=n(e);return r!==i?r>i?t:void 0:o!==a?o>a?t:void 0:s>=c?t:void 0}function mq(t={}){let e=t.readFile??(r=>cq(r,"utf-8")),n=t.homeDir??lq;try{let r=e(dq(n(),".grok","version.json")),o=JSON.parse(r);if(typeof o!="object"||o===null)return;let s=o.version;return typeof s!="string"?void 0:bf(s)}catch{return}}function gq(t,e){let n=e.readEnv??(r=>b[r]);return bf(n(uq))??bf(t)??fq(mq(e),lA)??lA}function wf(t){try{let e=new URL(t).hostname.toLowerCase();return e===yf||e.endsWith(`.${yf}`)}catch{return t.toLowerCase().includes(yf)}}function Sf(t={},e={}){let n=gq(t.clientVersion,e),r=t.clientIdentifier?.trim()||"grok-shell";return{"X-XAI-Token-Auth":"xai-grok-cli","x-grok-client-version":n,"x-grok-client-identifier":r,"User-Agent":`agent-afk (grok-cli-compat/${n})`}}var ms="https://api.x.ai/v1",Er="https://cli-chat-proxy.grok.com/v1";function hq(t){if(t==="AFK_XAI_BASE_URL")return b.AFK_XAI_BASE_URL;if(t==="AFK_XAI_OAUTH_BASE_URL")return b.AFK_XAI_OAUTH_BASE_URL}function Ar(t,e={}){let n=e.readEnv??hq,r=e.baseUrlOverride?.trim();if(r){let c=kf(r),l=wf(c);return{baseURL:c,defaultHeaders:l?Sf({clientVersion:e.clientVersion},e.headerDeps):{},mode:t,proxyHeadersApplied:l}}if(t==="apikey"){let c=n("AFK_XAI_BASE_URL"),l=c&&c.trim()||ms;return{baseURL:kf(l),defaultHeaders:{},mode:t,proxyHeadersApplied:!1}}let o=n("AFK_XAI_OAUTH_BASE_URL"),s=kf(o&&o.trim()||Er),i=wf(s),a=i?Sf({clientVersion:e.clientVersion},e.headerDeps):{};return{baseURL:s,defaultHeaders:a,mode:t,proxyHeadersApplied:i}}function kf(t){return t.endsWith("/")?t.slice(0,-1):t}function yq(t){if(t==="XAI_API_KEY")return b.XAI_API_KEY}function bq(t,e){if(t&&t.length>0)return{key:t,source:"config"};let n=e("XAI_API_KEY");return n&&n.length>0?{key:n,source:"env"}:null}function wq(t){let e=_r(t.store??{});return e?{bundle:e,last4:$c(e.access_token)}:null}function ut(t,e=void 0,n={}){let r=n.readEnv??yq,o=bq(t,r),s=wq(n);return e==="oauth"?s?{apiKey:s.bundle.access_token,source:"xai-oauth",mode:"oauth",last4:s.last4,expiresAt:s.bundle.expires_at}:{apiKey:null,source:"no-usable-auth-forced-xai-oauth",mode:"oauth"}:e==="apikey"?o?{apiKey:o.key,source:o.source,mode:"apikey",last4:$c(o.key),...o.source==="env"?{envVar:"XAI_API_KEY"}:{}}:{apiKey:null,source:"no-usable-auth-forced-xai-apikey",mode:"apikey"}:o&&s?{apiKey:null,source:"ambiguous-auth"}:o?{apiKey:o.key,source:o.source,mode:"apikey",last4:$c(o.key),...o.source==="env"?{envVar:"XAI_API_KEY"}:{}}:s?{apiKey:s.bundle.access_token,source:"xai-oauth",mode:"oauth",last4:s.last4,expiresAt:s.bundle.expires_at}:{apiKey:null,source:"no-usable-auth"}}function Sq(t,e){if(typeof t!="number")return"";let n=(e??(()=>Math.floor(Date.now()/1e3)))(),r=t-n;if(r<=0)return", EXPIRED \u2014 re-run `afk provider auth xai login`";let o=Math.floor(r/3600),s=Math.floor(r%3600/60);return`, expires in ${o>0?`${o}h `:""}${s}m`}function xr(t,e={}){switch(t.source){case"config":return`using explicit AFK config xAI API key (\u2026${t.last4??"????"})`;case"env":return`using XAI_API_KEY env var (\u2026${t.last4??"????"})`;case"xai-oauth":{let n=Sq(t.expiresAt,e.nowSeconds);return`using SuperGrok / SuperGrok Heavy / X Premium+ OAuth (\u2026${t.last4??"????"}${n})`}case"no-usable-auth-forced-xai-oauth":return"This model's slot/provider is `xai-oauth` but no SuperGrok OAuth tokens were found. Run `afk provider auth xai login` (device-code by default), or switch to `xai` with XAI_API_KEY.";case"no-usable-auth-forced-xai-apikey":return"This model's slot/provider is `xai` (API-key mode) but no XAI_API_KEY / config key was found. Set XAI_API_KEY, or use `xai-oauth` after `afk provider auth xai login`.";case"ambiguous-auth":return"Both XAI_API_KEY and SuperGrok OAuth tokens are present. Choose explicitly: `--provider xai` (API key \u2192 "+ms+") or `--provider xai-oauth` (subscription OAuth \u2192 "+Er+").";default:return"No xAI auth found. Set XAI_API_KEY for metered API access, or run `afk provider auth xai login` for SuperGrok / SuperGrok Heavy / X Premium+."}}function vf(t,e){let n=e.baseURL??(e.mode==="oauth"?Er:ms),r=(e.bodySnippet??"").slice(0,180);return t===402?`xAI returned HTTP 402 on ${n}`+(r?` (${r})`:"")+". This is usually a subscription/spend gate (e.g. personal-team-blocked), not a missing login. Check SuperGrok / SuperGrok Heavy / X Premium+ status, try the other endpoint via AFK_XAI_OAUTH_BASE_URL or AFK_XAI_BASE_URL, or use a metered XAI_API_KEY with `--provider xai`.":t===403?`xAI returned HTTP 403 on ${n}`+(r?` (${r})`:"")+`. After SuperGrok OAuth login this often means the account lacks OAuth API entitlement, the model requires SuperGrok Heavy, or traffic hit api.x.ai instead of the CLI chat proxy. Try AFK_XAI_OAUTH_BASE_URL=${Er} (default for xai-oauth), or fall back to XAI_API_KEY with \`--provider xai\`.`:`xAI returned HTTP ${t} on ${n}`+(r?`: ${r}`:"")}function Bc(t,e,n){if(e===!0)return"oauth";if(n===!0)return"apikey";if(t==="apikey"||t==="oauth")return t}function Tf(t,e){return e!==void 0?e:Bc(t,void 0,void 0)}function dA(t,e){if(t==="xai-oauth")return"oauth";if(e)return"apikey"}var _f="https://auth.x.ai",jc="b1a00492-073a-47ea-816f-4c329264a828",kq="openid profile email offline_access grok-cli:access api:access",SSe=`${kq} conversations:read conversations:write`;var vq=56121,Tq=`http://127.0.0.1:${vq}/callback`;var Hc=180;var _q=1440*60*1e3,Wc=null;function Je(t){return typeof t=="string"&&t.length>0?t:void 0}async function Kc(t={}){let e=t.fetchFn??fetch,n=(t.issuer??_f).replace(/\/$/,""),r=`${n}/.well-known/openid-configuration`,o=await e(r,{method:"GET"});if(!o.ok)throw new Error(`xAI OIDC discovery failed: HTTP ${o.status} from ${r}`);let s=await o.json(),i=Je(s.authorization_endpoint),a=Je(s.token_endpoint);if(!i||!a)throw new Error("xAI OIDC discovery missing authorization_endpoint or token_endpoint");let c=new URL(n).origin,l=Je(s.issuer);if(l){let m;try{m=new URL(l).origin}catch{throw new Error("xAI OIDC discovery: body issuer origin does not match configured issuer")}if(m!==c)throw new Error("xAI OIDC discovery: body issuer origin does not match configured issuer")}let d=l??n;if(new URL(i).origin!==c)throw new Error("xAI OIDC discovery: authorization_endpoint origin does not match issuer");if(new URL(a).origin!==c)throw new Error("xAI OIDC discovery: token_endpoint origin does not match issuer");let u={issuer:d,authorization_endpoint:i,token_endpoint:a},p=Je(s.device_authorization_endpoint);if(p){if(new URL(p).origin!==c)throw new Error("xAI OIDC discovery: device_authorization_endpoint origin does not match issuer");u.device_authorization_endpoint=p}let f=Je(s.userinfo_endpoint);if(f){if(new URL(f).origin!==c)throw new Error("xAI OIDC discovery: userinfo_endpoint origin does not match issuer");u.userinfo_endpoint=f}return u}async function qc(t={}){let n=(t.nowMs??(()=>Date.now()))();if(Wc&&Wc.expiresAt>n)return Wc.result;let r=await Kc(t);return Wc={result:r,expiresAt:n+_q},r}function gs(t,e,n){let r=Je(t.access_token);if(!r)return null;let o=Je(t.refresh_token)??n;if(!o)return null;let s=(e??(()=>Math.floor(Date.now()/1e3)))(),i=typeof t.expires_in=="number"?t.expires_in:3600,a=Math.min(Math.max(i,Hc+60),86400),c={access_token:r,refresh_token:o,expires_at:s+a};return typeof t.token_type=="string"&&(c.token_type=t.token_type),typeof t.scope=="string"&&(c.scope=t.scope),c}var Ef=new Map;function Oq(t){return t?.authPath?t.authPath():Tr()}async function uA(t,e={}){let n=await qc(e),r=e.fetchFn??fetch,o=e.clientId??jc,s=new URLSearchParams({grant_type:"refresh_token",refresh_token:t,client_id:o}),i=await r(n.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:s.toString()}),a=await i.json().catch(()=>({}));if(!i.ok){let l=Je(a.error)??`http_${i.status}`,d=Je(a.error_description);throw new Error(`xAI token refresh failed: ${d?`${l}: ${d}`:l}`)}let c=gs(a,e.nowSeconds,t);if(!c)throw new Error("xAI refresh response missing access_token");return e.persist!==!1&&gf(c,e.store??{}),c}async function hs(t={}){let e=t.store??{},n=_r(e);if(!n)return null;let r=(t.nowSeconds??(()=>Math.floor(Date.now()/1e3)))(),o=t.skewSeconds??Hc;if(n.expires_at-o>r)return n;let s=Oq(e),i=Ef.get(s);if(i)try{return await i}catch{return _r(e)}let a=(async()=>{try{return await uA(n.refresh_token,{...t,store:e,persist:!0})}catch(c){throw n.expires_at<=r&&hf(e),c}finally{Ef.delete(s)}})();Ef.set(s,a);try{return await a}catch{return n.expires_at>r?n:null}}function Gc(t){return typeof t!="number"?!1:t<=Math.floor(Date.now()/1e3)}function Af(t,e){let n=Vt(t);if(n!==402&&n!==403)return t instanceof Error?t:new Error(String(t));let r=t instanceof Error?t.message:typeof t=="string"?t:void 0,o=Ar(e);return new Error(vf(n,{mode:e,baseURL:o.baseURL,...r!==void 0?{bodySnippet:r}:{}}))}function pA(t){return{async*[Symbol.asyncIterator](){yield{type:"error",error:new Error(t)}},async interrupt(){},async setModel(){},async setPermissionMode(){},async supportedCommands(){return[]},async supportedModels(){return[]},async supportedAgents(){return[]},async getContextUsage(){return{}},async mcpServerStatus(){return[]},async accountInfo(){return{}},async rewindFiles(){return{canRewind:!1,error:t}},async close(){}}}function fA(t,e){return t==="oauth"||t==="apikey"?t:e()}function mA(t){let{args:e,forceMode:n,authDeps:r,getLastMode:o,delegate:s}=t,i,a,c,l,d,u=async()=>{if(a)throw a;return i||c||(c=(async()=>{try{n!=="apikey"&&await hs({store:r.store});let p=ut(e.config.apiKey,n,r);if(p.apiKey===null||!p.mode)throw new Error(xr(p));if(p.mode==="oauth"&&Gc(p.expiresAt))throw new Error("SuperGrok OAuth access token expired and refresh failed. Re-run `afk provider auth xai login`.");return i=s(e,p.apiKey,p.mode),l!==void 0&&i.setCwd?.(l),d!==void 0&&i.setSystemPrompt?.(d===null?void 0:d),i}catch(p){throw a=p instanceof Error?p:new Error(String(p)),a}finally{c=void 0}})(),c)};return{async*[Symbol.asyncIterator](){try{let p=await u();for await(let f of p)f.type==="error"?yield{type:"error",error:Af(f.error,fA(n,o))}:yield f}catch(p){let f=p instanceof Error?p:new Error(String(p));yield{type:"error",error:Af(f,fA(n,o))}}},async interrupt(p){await(i??await u().catch(()=>{}))?.interrupt(p)},async setModel(p){await(i??await u().catch(()=>{}))?.setModel(p)},async setPermissionMode(p){await(i??await u().catch(()=>{}))?.setPermissionMode(p)},setCwd(p){l=p,i?.setCwd?.(p)},setSystemPrompt(p){return d=p===void 0?null:p,i?.setSystemPrompt?.(p)??!1},async reauth(){return await(i??await u().catch(()=>{}))?.reauth?.()??null},async supportedCommands(){return await(i??await u().catch(()=>{}))?.supportedCommands()??[]},async supportedModels(){return await(i??await u().catch(()=>{}))?.supportedModels()??[]},async supportedAgents(){return await(i??await u().catch(()=>{}))?.supportedAgents()??[]},async getContextUsage(){return await(i??await u().catch(()=>{}))?.getContextUsage()??{}},async mcpServerStatus(){return await(i??await u().catch(()=>{}))?.mcpServerStatus()??[]},async accountInfo(){return await(i??await u().catch(()=>{}))?.accountInfo()??{}},async rewindFiles(p,f){let m=i??await u().catch(()=>{});return m?m.rewindFiles(p,f):{canRewind:!1,error:"xAI provider not initialized"}},async compact(){let p=i??await u().catch(()=>{});return p?.compact?p.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}},listRewindTargets(){return i?.listRewindTargets?.()??[]},async rewindConversation(p){let f=i??await u().catch(()=>{});return f?.rewindConversation?f.rewindConversation(p):{rewound:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0}},async close(){await i?.close()}}}var Dq="xai",ys=class{name=Dq;inner;authMode;authDeps;lastMode="apikey";lastResolvedMode;lastXaiBaseUrl;constructor(e={}){let{authMode:n,authDeps:r,...o}=e;this.authMode=n,this.authDeps=r??{},this.inner=new Ge(o)}query(e){let n=Bc(this.authMode,e.config.forceXaiOAuth,e.config.forceXaiApiKey);return n==="oauth"||n===void 0?mA({args:e,forceMode:n,authDeps:this.authDeps,getLastMode:()=>this.lastMode,delegate:(r,o,s)=>this.delegateToInner(r,o,s)}):this.querySync(e,n)}querySync(e,n){let r=ut(e.config.apiKey,n,this.authDeps);return r.apiKey===null||!r.mode?pA(xr(r)):this.delegateToInner(e,r.apiKey,r.mode)}delegateToInner(e,n,r){this.rememberResolved(r,e.config.xaiBaseUrl);let o=Ar(r,{readEnv:this.authDeps.readEnv?i=>this.authDeps.readEnv(i):void 0,...e.config.xaiBaseUrl!==void 0?{baseUrlOverride:e.config.xaiBaseUrl}:{}});this.inner.setEndpointDefaults({baseURL:o.baseURL,defaultHeaders:o.defaultHeaders});let s={...e.config,apiKey:n,openaiBaseUrl:o.baseURL,forceChatgptOAuth:!1,forceXaiOAuth:r==="oauth",forceXaiApiKey:r==="apikey"};return this.inner.query({...e,config:s})}rememberResolved(e,n){this.lastMode=e,this.lastResolvedMode=e,this.lastXaiBaseUrl=n}addReadRoot(e,n="slash",r){this.inner.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.inner.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.inner.revokeRoot(e,n,r)}getGrants(){return this.inner.getGrants()}close(){this.inner.close()}async complete(e){let n=Tf(this.authMode,this.lastResolvedMode);(n==="oauth"||n===void 0)&&await hs({store:this.authDeps.store});let r=ut(e.apiKey,n,this.authDeps);if(r.apiKey===null||!r.mode)throw new Error(xr(r));if(r.mode==="oauth"&&Gc(r.expiresAt))throw new Error("SuperGrok OAuth access token expired and refresh failed. Re-run `afk provider auth xai login`.");this.rememberResolved(r.mode,this.lastXaiBaseUrl);let o=Ar(r.mode,{readEnv:this.authDeps.readEnv,...this.lastXaiBaseUrl!==void 0?{baseUrlOverride:this.lastXaiBaseUrl}:{}});return this.inner.setEndpointDefaults({baseURL:o.baseURL,defaultHeaders:o.defaultHeaders}),this.inner.complete({...e,apiKey:r.apiKey,baseUrl:o.baseURL})}};C();var Fq=new Set([...Object.keys(Xl),"auto"]);function Lq(t){if(!t)return;let e=t.trim().toLowerCase();if(e){if(e==="anthropic"||e==="anthropic-direct")return"anthropic-direct";if(e==="openai"||e==="openai-compatible"||e==="openai-codex")return"openai-compatible";if(e==="xai")return"xai";if(e==="xai-oauth"||e==="xai_oauth")return"xai-oauth"}}function z(t,e){let n=e?.explicit??b.AFK_PROVIDER,r=e?.openaiBaseUrl??b.AFK_OPENAI_BASE_URL,o=Lq(n);if(o)return o;let s=an(t,e?.slots);if(s.provider==="anthropic")return"anthropic-direct";if(s.provider==="openai"||s.provider==="chatgpt-oauth")return"openai-compatible";if(s.provider==="xai")return"xai";if(s.provider==="xai-oauth")return"xai-oauth";let i=s.id.trim().toLowerCase();return i&&(Fq.has(i)||i.startsWith("claude-")||i.startsWith("claude_")||i.startsWith("local-")||i.startsWith("local_"))?"anthropic-direct":i&&(i.startsWith("grok-")||i.startsWith("grok_")||i==="grok")?"xai":i&&(i.startsWith("gpt-")||i.startsWith("gpt_")||cn(i)||i.startsWith("codex-")||i.startsWith("codex_")||i==="codex"||i.startsWith("deepseek-")||i.startsWith("deepseek_")||i.startsWith("mistral-")||i.startsWith("mistral_")||i.startsWith("mixtral-")||i.startsWith("mixtral_")||i.startsWith("llama-")||i.startsWith("llama_")||i.startsWith("qwen-")||i.startsWith("qwen_")||i.includes("/"))||s.baseUrl&&s.baseUrl.trim()||r&&r.trim()?"openai-compatible":"anthropic-direct"}function Xc(t,e,n){let r=z(t,e),o=n?.customTools,s=n?.canUseTool,i={...o!==void 0&&o.length>0?{customTools:o}:{},...s!==void 0?{canUseTool:s}:{}};switch(r){case"openai-compatible":case"openai-codex":return new Ge(i);case"xai":case"xai-oauth":{let a=(e?.explicit??b.AFK_PROVIDER)?.trim().toLowerCase()??"",d=dA(r==="xai-oauth"||a==="xai-oauth"||a==="xai_oauth"?"xai-oauth":"xai",a==="xai"||a==="xai-oauth"||a==="xai_oauth"||r==="xai-oauth");return new ys({...i,...d!==void 0?{authMode:d}:{}})}default:return new xt(i)}}var Rr=class{pendingResolve=null;bufferedMessages=[];getSessionId;constructor(e){this.getSessionId=e}pushUserMessage(e){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:e,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessages.push(e)}createIterable(){let e=this;return{[Symbol.asyncIterator](){return{next(){if(e.bufferedMessages.length>0){let n=e.bufferedMessages.shift(),r=e.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{e.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}};function zc(t,e){let n=e??Fn(),r=Ln(t.model,n);if(!r){t.forceChatgptOAuth=!1,t.forceXaiOAuth=!1,t.forceXaiApiKey=!1,t.xaiBaseUrl=void 0;return}let o=n[r],s=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"||o.provider==="chatgpt-oauth"?"openai-compatible":o.provider==="xai"||o.provider==="xai-oauth"?"xai":z(t.model,e?{slots:e}:void 0);t.forceChatgptOAuth=o.provider==="chatgpt-oauth",t.forceXaiOAuth=o.provider==="xai-oauth",t.forceXaiApiKey=o.provider==="xai",o.apiKey!==void 0?t.apiKey=o.apiKey:(s==="openai-compatible"||s==="xai"||o.baseUrl!==void 0)&&(t.apiKey=void 0),o.baseUrl!==void 0?s==="xai"?t.xaiBaseUrl=o.baseUrl:s==="openai-compatible"?t.openaiBaseUrl=o.baseUrl:t.baseUrl=o.baseUrl:s==="xai"&&(t.xaiBaseUrl=void 0)}J();function Nq(t){return typeof t=="string"?t:t.map(e=>{let n=e;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(e=>e.length>0).join(`
|
|
1267
1267
|
`)}function Uq(t,e,n,r){let o=n&&n!==r?` (provider ${n} \u2192 ${r})`:"";return`[System context \u2014 not from the user. Your model was switched at the start of this turn: ${t} \u2192 ${e}${o}. Earlier turns in this conversation were produced by ${t}; the history carried across the switch is plain text only, so any prior tool calls and extended reasoning are now prose \u2014 treat their structure as lost, not authoritative.]`}function $q(t,e){return typeof t=="string"?t.length>0?`${e}
|
|
1268
1268
|
|
|
@@ -1271,9 +1271,9 @@ ${t}`:e:[{type:"text",text:e},...t]}var Jc=class{outerIterator;baseConfig;deps;c
|
|
|
1271
1271
|
`);if(r.length<=1&&t.length<=80)return{content:t,truncated:!1,sizeBytes:e,sizeLabel:n};if(r.length<=1)return t.length<=80?{content:t,truncated:!1,sizeBytes:e,sizeLabel:n}:{content:t.substring(0,80)+"\u2026",truncated:!0,sizeBytes:e,sizeLabel:n};if(t.length<=80)return{content:t,truncated:!1,sizeBytes:e,sizeLabel:n};let o=r[0]??"",s=o;return o.length>80&&(s=o.substring(0,80)+"\u2026"),{content:s+`\u2026+${r.length} lines`,truncated:!0,lineCount:r.length,sizeBytes:e,sizeLabel:n}}function Yq(t,e){let n={...t.raw??{}};return t.inputTokens!==void 0&&(n.input_tokens=t.inputTokens),t.outputTokens!==void 0&&(n.output_tokens=t.outputTokens),t.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=t.cachedInputTokens),t.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=t.cacheCreationTokens),t.totalTokens!==void 0&&(n.total_tokens=t.totalTokens),t.contextWindowTokens!==void 0&&(n.context_window_tokens=t.contextWindowTokens),{sessionId:e,stopReason:t.stopReason??void 0,resultSubtype:t.resultSubtype,durationMs:t.durationMs,durationApiMs:t.durationApiMs,totalCostUsd:t.totalCostUsd,isError:t.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:t.modelUsage,permissionDenials:t.permissionDenials,errors:t.errors}}function Qq(t){let e=t.isError===!0?null:xA(t.toolName,t.content),n=e!==null?{display:e}:{},r=typeof t.batchIndex=="number"&&typeof t.batchSize=="number"?{batchIndex:t.batchIndex,batchSize:t.batchSize}:{},o=t.failureClass?{failureClass:t.failureClass}:{},s=zq(t.content);if(s)return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:`Output persisted (${s.sizeLabel}) \u2192 ${s.absolutePath}`,isError:t.isError===!0,persistedPath:s.absolutePath,sizeBytes:s.sizeBytes,sizeLabel:s.sizeLabel,...n,...r,...o}};let{content:i,lineCount:a,sizeBytes:c,sizeLabel:l}=Vq(t.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:i,isError:t.isError===!0,sizeBytes:c,sizeLabel:l,...t.truncated===!0&&{truncated:!0},...a!==void 0&&{lineCount:a},...n,...r,...o}}}function Rf(t,e){switch(t.type){case"session.init":{let n=t.info;return e.setSessionMetadata(r=>({...r,sessionId:n.sessionId,model:n.model??r.model,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},tools:n.tools?[...n.tools]:r.tools,slashCommands:n.slashCommands?[...n.slashCommands]:r.slashCommands,skills:n.skills?[...n.skills]:r.skills,plugins:n.plugins?n.plugins.map(o=>({...o})):r.plugins,mcpServers:n.mcpServers?n.mcpServers.map(o=>({...o})):r.mcpServers,...n.apiKeySource!==void 0?{apiKeySource:n.apiKeySource}:{},...n.version!==void 0?{claudeCodeVersion:n.version}:{},...n.outputStyle!==void 0?{outputStyle:n.outputStyle}:{}})),e.updateSessionIdentity(n.sessionId),e.resolveInitialization(),null}case"session.status":return e.setSessionMetadata(n=>({...n,sessionId:t.sessionId,...t.permissionMode!==void 0?{permissionMode:t.permissionMode}:{permissionMode:n.permissionMode},...t.status!==void 0?{status:t.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:t.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:t.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(t.sessionId&&e.updateSessionIdentity(t.sessionId),t.text){let n={role:"assistant",content:t.text,timestamp:new Date};return e.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:t.toolUseId,toolName:t.toolName,toolInput:t.toolInput,toolInputRaw:t.toolInputRaw,toolInputCapture:t.toolInputCapture,...t.pending?{pending:!0}:{}}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:t.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:t.toolUseIds}}};case"tool.output":return t.isError!==!0&&t.toolName&&(e._successfulToolNames??=[]).push(t.toolName),Qq(t);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:t.toolUseId,diff:t.diff}};case"progress":return{type:"progress",progress:{taskId:t.progress.taskId,description:t.progress.description,...t.progress.summary!==void 0?{summary:t.progress.summary}:{},...t.progress.lastToolName!==void 0?{lastToolName:t.progress.lastToolName}:{},totalTokens:t.progress.totalTokens,toolUses:t.progress.toolUses,durationMs:t.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:t.suggestion};case"turn.completed":{let n=Yq(t.usage,t.sessionId??e.getSessionMetadata().sessionId);e._successfulToolNames!==void 0&&e._successfulToolNames.length>0&&(n.successfulToolNames=[...e._successfulToolNames]),e.setLastResponseMetadata(n);for(let r=e.conversationHistory.length-1;r>=0;r--){let o=e.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(e.maxBudgetUsd!==void 0&&e.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(e._runningCostUsd=(e._runningCostUsd??0)+n.totalCostUsd,e._runningCostUsd>=e.maxBudgetUsd)){jm(e.traceWriter,{kind:"monetary",runningCostUsd:e._runningCostUsd,maxBudgetUsd:e.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new tt(e._runningCostUsd,e.maxBudgetUsd);return e.abortBudget(r),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:t.error};case"paused":return{type:"paused",reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:t.hotSwapped,...t.accountId!==void 0?{accountId:t.accountId}:{}};case"stream.retry":return{type:"stream_retry"};case"rate_limit":return{type:"rate_limit",...t.retryAfterMs!==void 0?{retryAfterMs:t.retryAfterMs}:{}};case"notice":return{type:"notice",text:t.text,kind:t.kind};case"tool.activity":return{type:"tool-activity",activeCount:t.activeCount,activeToolUseIds:t.activeToolUseIds};default:return null}}M();import{stat as Zq,readFile as eG,writeFile as tG,rename as nG,unlink as rG}from"node:fs/promises";var RA=5*1024*1024,IA=5e3;async function CA(t,{maxBytes:e,keepTailLines:n}){let r={trimmed:!1,removedLines:0},o;try{if((await Zq(t)).size<=e)return r;let a=(await eG(t,"utf8")).split(`
|
|
1272
1272
|
`);if(a.length>0&&a[a.length-1]===""&&a.pop(),a.length<=n)return r;let c=a.slice(a.length-n),l=a.length-c.length;return o=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,8)}`,await tG(o,c.join(`
|
|
1273
1273
|
`)+`
|
|
1274
|
-
`,{mode:384}),await nG(o,t),o=void 0,{trimmed:!0,removedLines:l}}catch{if(o!==void 0)try{await rG(o)}catch{}return r}}C();M();import{readdir as Cf,stat as If,rm as BA,writeFile as aG}from"node:fs/promises";import{join as bs}from"node:path";import{readdirSync as PA,unlinkSync as MA}from"node:fs";M();C();var oG=new Set(["pending","running"]),sG=2880*60*1e3;function OA(t){let e={offers:[],deletedExpired:0};try{let n=Pn(),r;try{r=PA(n)}catch{return e}let o=Date.now();for(let s of r){if(!s.endsWith(".json"))continue;let i=s.slice(0,-5);if(!/^[A-Za-z0-9]+$/.test(i))continue;let a=jp(i);if(a===void 0)continue;let c=new Date(a.expiresAt).getTime();if(!Number.isFinite(c)||c<o){try{MA(Mn(i)),e.deletedExpired+=1}catch{}continue}if(a.offeredAt!==void 0)continue;let l=new Date(a.createdAt).getTime(),d=Number.isFinite(l)?l:0,u=o-d<sG,p=a.parentSessionId===t.sessionId;if(!u&&!p)continue;let f=a.units.filter(y=>oG.has(y.status));if(f.length===0)continue;let m=new Set(a.units.filter(y=>y.status==="done").map(y=>y.id)),g=[],h=[];for(let y of f){if(y.upstreamIds.length>0&&y.upstreamIds.some(v=>!m.has(v))){g.push(y);continue}let
|
|
1274
|
+
`,{mode:384}),await nG(o,t),o=void 0,{trimmed:!0,removedLines:l}}catch{if(o!==void 0)try{await rG(o)}catch{}return r}}C();M();import{readdir as Cf,stat as If,rm as BA,writeFile as aG}from"node:fs/promises";import{join as bs}from"node:path";import{readdirSync as PA,unlinkSync as MA}from"node:fs";M();C();var oG=new Set(["pending","running"]),sG=2880*60*1e3;function OA(t){let e={offers:[],deletedExpired:0};try{let n=Pn(),r;try{r=PA(n)}catch{return e}let o=Date.now();for(let s of r){if(!s.endsWith(".json"))continue;let i=s.slice(0,-5);if(!/^[A-Za-z0-9]+$/.test(i))continue;let a=jp(i);if(a===void 0)continue;let c=new Date(a.expiresAt).getTime();if(!Number.isFinite(c)||c<o){try{MA(Mn(i)),e.deletedExpired+=1}catch{}continue}if(a.offeredAt!==void 0)continue;let l=new Date(a.createdAt).getTime(),d=Number.isFinite(l)?l:0,u=o-d<sG,p=a.parentSessionId===t.sessionId;if(!u&&!p)continue;let f=a.units.filter(y=>oG.has(y.status));if(f.length===0)continue;let m=new Set(a.units.filter(y=>y.status==="done").map(y=>y.id)),g=[],h=[];for(let y of f){if(y.upstreamIds.length>0&&y.upstreamIds.some(v=>!m.has(v))){g.push(y);continue}let S=UT(y.worktreePath);h.push({unit:y,worktreeStatus:S})}(h.length>0||g.length>0)&&e.offers.push({manifest:a,resumable:h,blocked:g})}}catch{}return e}function DA(t){let{manifest:e,resumable:n,blocked:r}=t,o=new Date(e.createdAt),s=Date.now()-o.getTime(),i=iG(s),a=[`[wave-resume] Wave ${e.waveId} from ${i} ago has ${n.length+r.length} unsettled unit(s).`,` Source: ${e.source}`];if(n.length>0){a.push(" Units ready to resume:");for(let{unit:c,worktreeStatus:l}of n){let d=Ae(c.promptDigest.head.slice(0,80)).replace(/\n/g," "),u=c.cwd!==void 0?` (cwd: ${Ae(c.cwd)})`:"",p=l==="missing"?" \u26A0 worktree was swept \u2014 cannot re-dispatch without its working directory":"";a.push(` \xB7 ${c.id}: ${d}...${u}${p}`)}}if(r.length>0){a.push(" Units blocked on failed upstream deps:");for(let c of r)a.push(` \xB7 ${c.id} (depends on: ${c.upstreamIds.join(", ")})`)}return a.push(" To retry, re-dispatch each ready unit's prompt from its listed cwd; this notice does not accept yes/no replies."),a.join(`
|
|
1275
1275
|
`)}function FA(t){return t||b.AFK_WAVE_RESUME_UNATTENDED==="1"}function LA(t){try{let e=new Date().toISOString();t.offeredAt=e,t.updatedAt=e,$T(t)}catch{}}function iG(t){let e=Math.floor(t/6e4);if(e<60)return`${e}m`;let n=Math.floor(e/60);return n<24?`${n}h`:`${Math.floor(n/24)}d`}function NA(){let t=0;try{let e=Pn(),n;try{n=PA(e)}catch{return{deleted:t}}let r=Date.now();for(let o of n){if(!o.endsWith(".json"))continue;let s=o.slice(0,-5);if(!/^[A-Za-z0-9]+$/.test(s))continue;let i=jp(s);if(i===void 0)continue;let a=new Date(i.expiresAt).getTime();if(!(Number.isFinite(a)&&a>=r))try{MA(Mn(s)),t+=1}catch{}}}catch{}return{deleted:t}}var cG=30,lG=2*1024*1024*1024,jA=3600*1e3,dG=360*60*1e3,HA=".last-sweep";async function uG(t){try{let n=(await Cf(t.root,{withFileTypes:!0})).filter(a=>a.isDirectory()&&a.name!==t.activeLabel),r=[];for(let a of n){let c=bs(t.root,a.name);try{r.push({label:a.name,path:c,...await WA(c)})}catch{}}r.sort((a,c)=>a.newestMtimeMs-c.newestMtimeMs);let o=r.filter(a=>t.now-a.newestMtimeMs>=jA),s=r.reduce((a,c)=>a+c.bytes,0),i=new Set;for(let a of o)t.now-a.newestMtimeMs>t.maxAgeMs&&i.add(a.label);for(let a of o){if(s<=t.maxBytes)break;if(i.has(a.label)){s-=a.bytes;continue}i.add(a.label),s-=a.bytes}for(let a of r)if(i.has(a.label))try{await BA(a.path,{recursive:!0,force:!0})}catch{}}catch{}}var UA=()=>({skipped:!0,scanned:0,evicted:0,freedBytes:0,evictedLabels:[]});function $A(t,e){let n=Number.parseFloat(t??"");return Number.isFinite(n)&&n>0?n:e}async function WA(t){let e=0,n=0,r=async o=>{let s=await Cf(o,{withFileTypes:!0});for(let i of s){let a=bs(o,i.name);if(i.isDirectory()){await r(a);continue}try{let c=await If(a);n+=c.size,c.mtimeMs>e&&(e=c.mtimeMs)}catch{}}};if(await r(t),e===0)try{e=(await If(t)).mtimeMs}catch{e=Date.now()}return{newestMtimeMs:e,bytes:n}}async function pG(t,e){try{let n=await If(bs(t,HA));return e-n.mtimeMs<dG}catch{return!1}}async function KA(t={}){if(b.AFK_WITNESS_RETENTION_DISABLE==="1")return UA();let e=t.root??jr(),n=Date.now();try{if(t.force!==!0&&await pG(e,n))return UA();let r=$A(t.maxAgeDays?.toString()??b.AFK_WITNESS_MAX_AGE_DAYS,cG)*24*60*60*1e3,o=$A(t.maxBytes?.toString()??b.AFK_WITNESS_MAX_BYTES,lG),i=(await Cf(e,{withFileTypes:!0})).filter(p=>p.isDirectory()&&p.name!==t.activeLabel),a=[];for(let p of i){let f=bs(e,p.name);try{a.push({label:p.name,path:f,...await WA(f)})}catch{}}a.sort((p,f)=>p.newestMtimeMs-f.newestMtimeMs);let c=a.filter(p=>n-p.newestMtimeMs>=jA),l=a.reduce((p,f)=>p+f.bytes,0),d=new Set;for(let p of c)n-p.newestMtimeMs>r&&d.add(p.label);for(let p of c){if(l<=o)break;if(d.has(p.label)){l-=p.bytes;continue}d.add(p.label),l-=p.bytes}let u={skipped:!1,scanned:a.length,evicted:0,freedBytes:0,evictedLabels:[]};for(let p of a)if(d.has(p.label))try{await BA(p.path,{recursive:!0,force:!0}),u.evicted+=1,u.freedBytes+=p.bytes,u.evictedLabels.push(p.label)}catch{}try{await aG(bs(e,HA),`${new Date(n).toISOString()}
|
|
1276
|
-
`,{mode:384})}catch{}return NA(),uG({root:Ol(),activeLabel:t.activeLabel,maxAgeMs:r,maxBytes:o,now:n}),u}catch{return{skipped:!1,scanned:0,evicted:0,freedBytes:0,evictedLabels:[]}}}var qA=5e3;M();C();import{readdir as fG,readFile as mG,stat as el,unlink as gG,writeFile as hG,access as yG}from"node:fs/promises";import{join as Pf}from"node:path";var bG=360*60*1e3,GA=3600*1e3,JA=".last-sweep-sidecars",wG=30,SG=1e3,kG=1440*60*1e3,VA=5e3;function XA(t,e){let n=Number.parseFloat(t??"");return Number.isFinite(n)&&n>0?n:e}var zA=t=>({skipped:!0,reason:t,evictedAge:0,evictedCount:0,remaining:0});async function vG(t,e){try{let n=await el(Pf(t,JA));return e-n.mtimeMs<bG}catch{return!1}}async function TG(t){try{return await yG(t),!0}catch{return!1}}async function YA(t){if(b.AFK_SESSION_RETENTION_DISABLE==="1")return zA("disabled");let e=t?.root??re(),n=Date.now();try{if(t?.force!==!0&&await vG(e,n))return zA("stamp");if(!await TG(e))return{skipped:!1,evictedAge:0,evictedCount:0,remaining:0};let r=XA(b.AFK_SESSION_MAX_AGE_DAYS,wG),o=XA(b.AFK_SESSION_MAX_COUNT,SG),s=r*kG,i=await fG(e,{withFileTypes:!0}),a=[];for(let h of i){if(!h.isFile()||!h.name.endsWith(".json")||t?.activeSessionId!==void 0&&h.name===`${t.activeSessionId}.json`)continue;let y=Pf(e,h.name),w,
|
|
1276
|
+
`,{mode:384})}catch{}return NA(),uG({root:Ol(),activeLabel:t.activeLabel,maxAgeMs:r,maxBytes:o,now:n}),u}catch{return{skipped:!1,scanned:0,evicted:0,freedBytes:0,evictedLabels:[]}}}var qA=5e3;M();C();import{readdir as fG,readFile as mG,stat as el,unlink as gG,writeFile as hG,access as yG}from"node:fs/promises";import{join as Pf}from"node:path";var bG=360*60*1e3,GA=3600*1e3,JA=".last-sweep-sidecars",wG=30,SG=1e3,kG=1440*60*1e3,VA=5e3;function XA(t,e){let n=Number.parseFloat(t??"");return Number.isFinite(n)&&n>0?n:e}var zA=t=>({skipped:!0,reason:t,evictedAge:0,evictedCount:0,remaining:0});async function vG(t,e){try{let n=await el(Pf(t,JA));return e-n.mtimeMs<bG}catch{return!1}}async function TG(t){try{return await yG(t),!0}catch{return!1}}async function YA(t){if(b.AFK_SESSION_RETENTION_DISABLE==="1")return zA("disabled");let e=t?.root??re(),n=Date.now();try{if(t?.force!==!0&&await vG(e,n))return zA("stamp");if(!await TG(e))return{skipped:!1,evictedAge:0,evictedCount:0,remaining:0};let r=XA(b.AFK_SESSION_MAX_AGE_DAYS,wG),o=XA(b.AFK_SESSION_MAX_COUNT,SG),s=r*kG,i=await fG(e,{withFileTypes:!0}),a=[];for(let h of i){if(!h.isFile()||!h.name.endsWith(".json")||t?.activeSessionId!==void 0&&h.name===`${t.activeSessionId}.json`)continue;let y=Pf(e,h.name),w,S;try{let v=await mG(y,"utf8"),_=JSON.parse(v);S=(await el(y)).mtimeMs,_!==null&&typeof _=="object"&&"savedAt"in _&&typeof _.savedAt=="number"?w=_.savedAt:w=S}catch{try{let v=await el(y);w=v.mtimeMs,S=v.mtimeMs}catch{continue}}a.push({name:h.name,path:y,ageMs:Math.max(0,n-w),savedAtMs:w,mtimeMs:S})}let c=a.filter(h=>h.ageMs>=GA);c.sort((h,y)=>h.savedAtMs-y.savedAtMs);let l=0,d=0,u=new Map;for(let h of c)h.ageMs>s&&(u.set(h.path,"age"),l+=1);let p=a.filter(h=>!u.has(h.path));if(p.length>o){let h=p.filter(w=>w.ageMs>=GA);h.sort((w,S)=>w.savedAtMs-S.savedAtMs);let y=p.length;for(let w of h){if(y<=o)break;u.has(w.path)||(u.set(w.path,"count"),d+=1,y-=1)}}let f=t?._unlink??gG,m=0;for(let[h,y]of u)try{let w=a.find(S=>S.path===h);if(w!==void 0&&(await el(h)).mtimeMs!==w.mtimeMs){y==="age"?l-=1:d-=1;continue}await f(h),m+=1}catch{y==="age"?l-=1:d-=1}let g=a.length-m;try{await hG(Pf(e,JA),`${new Date(n).toISOString()}
|
|
1277
1277
|
`,{mode:384})}catch{}return{skipped:!1,evictedAge:l,evictedCount:d,remaining:g}}catch{return{skipped:!1,evictedAge:0,evictedCount:0,remaining:0}}}var Rt=class{ownedTraceWriter;config;planExit=new Qc;currentState="idle";providerQuery;providerIterator;conversationHistory=[];turnCount=0;inboundMessageCount=0;subagentOutputRecorder;pendingFrameworkContext=[];lastResponseMetadata=null;initPromise=null;inputStream;abortController;_hookRegistry;sessionEndDispatched=!1;ownsTraceSeal;stateManager;sessionRunningCostUsd=0;sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};lastStopReason;maxTurnsHit=!1;hookBlocked=!1;sawProviderError=!1;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=new Yc;outputBroadcast=new zs;constructor(e,n){this.ownsTraceSeal=n!==void 0&&e.traceWriter===n,this.ownedTraceWriter=this.ownsTraceSeal?n:void 0,this.config=e.parentSessionId===void 0&&e.planExitControls===void 0?{...e,planExitControls:{setPermissionMode:o=>this.setPermissionMode(o),requestImplementSeed:(o,s)=>this.planExit.requestImplementSeed(o,s),getPrePlanMode:()=>this.planExit.getPrePlanMode()}}:e,this.abortController=new AbortController,this._hookRegistry=e.hookRegistry,kA(e.abortSignal,this.abortController,()=>{this.onAbort()});let r=String(e.model);$(e.traceWriter,{phase:"session_init_start",model:r,resolvedModel:he(e.model)??r,origin:Sa(e.surface),actor:Zu(e.parentSessionId)}),this.initSdkLifecycle(),this.config.parentSessionId===void 0&&(CA(Bs(),{maxBytes:RA,keepTailLines:IA}),setTimeout(()=>{KA({activeLabel:Rn(this.config.traceWriter?.getTracePath())??void 0})},qA).unref(),setTimeout(()=>{YA({activeSessionId:this.sessionId})},VA).unref())}initSdkLifecycle(){this.config.models&&Gl(this.config.models),zc(this.config);let e=he(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=vA(this.config,e);this.stateManager=new Zc(n,r),this.inputStream=new Rr(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)P(`\u{1F7E2} AgentSession: Creating query session via injected provider=${this.config.provider.name}`),this.providerQuery=this.config.provider.query({prompt:o,config:this.config});else{P("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>Xc(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new Jc({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>z(a),resolveApiKey:a=>oe(a)})}this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionRunningCostUsd=0,this.sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.lastStopReason=void 0,this.maxTurnsHit=!1,this.hookBlocked=!1,this.sawProviderError=!1,this.sessionEndDispatched=!1,this.currentState="idle",this.subagentCompletedCount=0,this.subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.subagentRunningCostUsd=0,this.pendingFrameworkContext=[];let s=this.providerQuery;this.providerIterator=s[Symbol.asyncIterator](),this.initPromise=this.pullInitialization()}async pullInitialization(){try{let e=await gA(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId,parentSessionId:this.config.parentSessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});for(e&&this.config.parentSessionId===void 0&&this.queueFrameworkContext(e);;){let n=await this.providerIterator.next();if(n.done){this.stateManager.resolveInitializationIfNeeded();return}let r=n.value,o=Rf(r,this.buildTransformDeps());if(r.type==="session.init"){await $(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(o&&o.type==="error"){this.sawProviderError=!0;return}}}catch(e){let n=e instanceof Error?e:new Error(String(e));n instanceof W&&(this.hookBlocked=!0),this.stateManager.isInitializationSettled()||this.stateManager.rejectInitializationOnce(n),await this.dispatchSessionEndOnce("error").catch(()=>{})}}buildTransformDeps(){return{_successfulToolNames:[],conversationHistory:this.conversationHistory,getSessionMetadata:()=>this.stateManager.getSessionMetadata(),setSessionMetadata:e=>this.stateManager.setSessionMetadata(e),updateSessionIdentity:e=>this.stateManager.updateSessionIdentity(e),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:e=>{this.lastResponseMetadata=e,typeof e.totalCostUsd=="number"&&Number.isFinite(e.totalCostUsd)&&(this.sessionRunningCostUsd+=e.totalCostUsd);let n=e.usage;if(n&&typeof n=="object"){let r=n,o=(s,i)=>{let a=r[s];typeof a=="number"&&Number.isFinite(a)&&(this.sessionRunningTokens[i]+=a)};o("input_tokens","input"),o("output_tokens","output"),o("cache_read_input_tokens","cacheRead"),o("cache_creation_input_tokens","cacheCreation")}typeof e.stopReason=="string"&&(this.lastStopReason=e.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:e=>{this.abortController.signal.aborted||this.abortController.abort(e)},...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}}}get state(){return this.currentState}get sessionId(){return this.stateManager.getSessionId()}get cwd(){return this.config.cwd}get abortSignal(){return this.abortController.signal}get hookRegistry(){return this._hookRegistry}abort(e){if(e==="closed"||e.startsWith("Budget ")||e.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${e}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(e)}async sendMessage(e,n={}){this.assertCanSend();let r=this.config.timeoutMs??Gp,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(e)){if(a.type==="chunk"&&a.chunk.type==="content"&&(i+=a.chunk.content),a.type==="message"&&a.message.role==="assistant"&&(s=a.message),a.type==="error")throw a.error;if(a.type==="done"){if(s)return{...s,metadata:a.metadata};if(i)return{role:"assistant",content:i,metadata:a.metadata,timestamp:new Date}}}if(s)return s;if(i)return{role:"assistant",content:i,timestamp:new Date};throw new Error("No assistant response received")};try{return await os(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async sendMessageStructured(e,n,r={}){let{maxRetries:o=2,injectSchemaPrompt:s=!0,...i}=r,a=s?"\n\nRespond with ONLY a JSON object (optionally in a ```json fence) that conforms to this JSON Schema:\n```json\n"+JSON.stringify(_G.toJSONSchema(n,{target:"openapi-3.0"}))+"\n```":"",c="";for(let l=0;l<=o;l++){let d=l===0?e+a:`Your previous response did not match the required JSON schema.
|
|
1278
1278
|
Validation error: ${c}
|
|
1279
1279
|
Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,u=await this.sendMessage(d,i),p=es(u.content),f=n.safeParse(p);if(f.success)return f.data;c=f.error.message}throw new Error(`structured output did not match schema after ${o+1} attempt(s): ${c}`)}async*sendMessageStream(e){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(e)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(e){this.initPromise&&await this.initPromise,this.planExit.clearModeBeforeDefault();let n=this.withPendingFrameworkContext(e),r=typeof n=="string"?n:this.summarizeContentBlocks(n),o={role:"user",content:r,timestamp:new Date};this.conversationHistory.push(o),this.inputStream.pushUserMessage(n),this.ensureLedger(),this.ledger.recordUser(r);let s=++this.inboundMessageCount;Lm({sessionId:Rn(this.config.traceWriter?.getTracePath())??this.sessionId,subagentId:this.config.subagentId,isSubagentFork:this.config.isSubagentFork===!0,model:this.config.model===void 0?void 0:String(this.config.model),turn:s,prompt:r});let i=this.buildTransformDeps();this.subagentOutputRecorder===void 0&&(this.subagentOutputRecorder=Bm({sessionId:Rn(this.config.traceWriter?.getTracePath())??this.sessionId,subagentId:this.config.subagentId,isSubagentFork:this.config.isSubagentFork===!0,model:this.config.model===void 0?void 0:String(this.config.model)}));let a=this.subagentOutputRecorder;try{for(;;){let c=await this.providerIterator.next();if(c.done)break;let l=c.value,d=Rf(l,i);if(d&&(a?.observe(d),d.type==="done"?(this.turnCount++,this.sawProviderError=!1):d.type==="error"&&(this.sawProviderError=!0),this.ledger.recordEvent(d),this.outputBroadcast.push(d),yield d,d.type==="done"||d.type==="error"))break}a?.end("stream_complete")}finally{this.currentState==="streaming"&&(a?.end("aborted_or_incomplete"),this.currentState="idle")}}ensureLedger(){this.ledger.ensure({depth:this.config.depth,parentSessionId:this.config.parentSessionId,sessionId:this.sessionId,fallbackModel:String(this.config.model),tracePath:this.config.traceWriter?.getTracePath(),getMetadata:()=>this.getSessionMetadata()})}recordLedgerElicitation(e,n){this.ledger.recordElicitation(e,n)}summarizeContentBlocks(e){let n=[],r=0;for(let s of e)s.type==="text"?n.push(s.text):s.type==="image"&&r++;let o=n.join(" ");return r>0&&(o=o?`${o} [+ ${r} image(s)]`:`[+ ${r} image(s)]`),o||"[content block(s)]"}async interrupt(){this.currentState!=="streaming"&&this.currentState!=="processing"||(this.currentState="idle",await this.providerQuery.interrupt())}setBeforeNextRound(e){this.providerQuery.setBeforeNextRound?.(e)}async reset(){if(this.currentState==="closed")throw new Error("Cannot reset: session is closed");if(this.abortController.signal.aborted)throw new Fe("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset"),await this.ledger.seal("reset");try{await this.providerQuery.close()}catch{}await this.providerIterator.return?.(),this.initPromise&&await Promise.race([this.initPromise,new Promise(e=>setTimeout(e,wc))]).catch(()=>{}),this.stateManager.resolveInitializationIfNeeded(),this.config={...this.config},delete this.config.resume,delete this.config.sessionId,delete this.config.resumeHistory,delete this.config.resumeSessionAt,delete this.config.continue,delete this.config.forkSession;try{this.initSdkLifecycle()}catch(e){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async onAbort(){this.ledger.seal("abort");try{await this.providerQuery.interrupt(td(this.abortController.signal.reason))}catch{}}async setModel(e){let n=he(e);typeof e=="string"&&e.length>0&&await this.providerQuery.setModel(e),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(e){let n=this.stateManager.getSessionMetadata().permissionMode;this.planExit.recordModeTransition(e,n),await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(r=>({...r,permissionMode:e}))}getPrePlanMode(){return this.planExit.getPrePlanMode()}setPlanExitQueueCheck(e){this.config.planExitControls&&(this.config.planExitControls.hasPendingUserMessage=e)}async takePendingPlanExitSeed(){let e=this.planExit.takeSeed();if(e!==void 0){try{await this.setPermissionMode(e.mode)}catch(n){P(`\u26A0\uFE0F AgentSession: deferred plan-exit mode flip to '${e.mode}' rejected; dropping implement-seed (staying in plan mode): ${n instanceof Error?n.message:String(n)}`);return}return{message:e.message,mode:e.mode}}}setSystemPrompt(e){return this.config={...this.config,systemPrompt:e},this.providerQuery.setSystemPrompt?.(e)??!1}setCwd(e){this.config={...this.config,cwd:e},this.providerQuery.setCwd?.(e),this.config.sessionId!==void 0&&ph(this.config.sessionId,e)}async reauth(){return await this.providerQuery.reauth?.()??null}waitForInitialization(){return this.stateManager.waitForInitialization()}getSessionIdentity(){return this.stateManager.getSessionIdentity()}getSessionMetadata(){return this.stateManager.getSessionMetadata()}getQuery(){return this.providerQuery}supportedCommands(){return this.providerQuery.supportedCommands()}supportedModels(){return this.providerQuery.supportedModels()}supportedAgents(){return this.providerQuery.supportedAgents()}getContextUsage(){return this.providerQuery.getContextUsage()}mcpServerStatus(){return this.providerQuery.mcpServerStatus()}accountInfo(){return this.providerQuery.accountInfo()}rewindFiles(e,n){return this.providerQuery.rewindFiles(e,n)}async compact(){if(this.currentState==="closed")throw new Error("Cannot compact: session is closed");if(this.currentState!=="idle")return{compacted:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let e=this.providerQuery.compact?.bind(this.providerQuery);if(!e)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await e()}finally{this.currentState="idle"}}listRewindTargets(){return this.currentState==="closed"?[]:this.providerQuery.listRewindTargets?.()??[]}async rewindConversation(e){if(this.currentState==="closed")throw new Error("Cannot rewind: session is closed");if(this.currentState!=="idle")return{rewound:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let n=this.providerQuery.rewindConversation?.bind(this.providerQuery);return n?n(e):{rewound:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){return this.outputBroadcast.subscribe()}queueFrameworkContext(e){let n=e.trim();n.length!==0&&(this.pendingFrameworkContext.push(n),P(`AgentSession: queued framework context (${n.length} chars) for the next user message`))}withPendingFrameworkContext(e){if(this.pendingFrameworkContext.length===0)return e;let n=this.pendingFrameworkContext.join(`
|
|
@@ -1291,7 +1291,7 @@ ${r}
|
|
|
1291
1291
|
|
|
1292
1292
|
${o}`};if(s&&typeof s=="object"&&"type"in s&&s.type==="preset"){let i=s.append??"";return{...t,systemPrompt:{...s,append:`${i}
|
|
1293
1293
|
|
|
1294
|
-
${o}`}}}return{...t,systemPrompt:o}}var Ff=new Map;function Lf(t,e){Ff.set(t,e)}function nl(t){return Ff.get(t)}function ix(t){Ff.delete(t)}function ax(t,e,n){FA(!0)&&Promise.resolve().then(async()=>{try{let r=OA({sessionId:t});for(let o of r.offers)await Promise.resolve(n(e,DA(o)))!==!1&&LA(o.manifest)}catch{}})}function rl(t){let e=t.toLowerCase().replace(/[`*_~]/g," ").replace(/[^\w\s-]/g," ").replace(/[\s_]+/g," ").trim();return e?e.split(" ").filter(Boolean).slice(0,6).join("-").slice(0,48).replace(/-+$/g,""):""}function cx(t){return{totalTurns:0,totalCostUsd:0,unpricedTurns:0,totalTokens:0,totalDurationMs:0,sessionStartTime:Date.now(),turnCosts:[],turnTokens:[],turns:[],model:t,permissionMode:"default",thinkingUi:"live"}}function lx(t,e,n,r,o){let s=r?.totalCostUsd,i=s??0,a=r?.durationMs??0,c=Number(r?.usage?.input_tokens??0),l=Number(r?.usage?.output_tokens??0),d=c,u=l,p=Number(r?.usage?.cache_read_input_tokens??0)+Number(r?.usage?.cache_creation_input_tokens??0),f=r?.usage?.iterations;if(Array.isArray(f)&&f.length>0){let w=f[f.length-1];if(w&&typeof w=="object"){let
|
|
1294
|
+
${o}`}}}return{...t,systemPrompt:o}}var Ff=new Map;function Lf(t,e){Ff.set(t,e)}function nl(t){return Ff.get(t)}function ix(t){Ff.delete(t)}function ax(t,e,n){FA(!0)&&Promise.resolve().then(async()=>{try{let r=OA({sessionId:t});for(let o of r.offers)await Promise.resolve(n(e,DA(o)))!==!1&&LA(o.manifest)}catch{}})}function rl(t){let e=t.toLowerCase().replace(/[`*_~]/g," ").replace(/[^\w\s-]/g," ").replace(/[\s_]+/g," ").trim();return e?e.split(" ").filter(Boolean).slice(0,6).join("-").slice(0,48).replace(/-+$/g,""):""}function cx(t){return{totalTurns:0,totalCostUsd:0,unpricedTurns:0,totalTokens:0,totalDurationMs:0,sessionStartTime:Date.now(),turnCosts:[],turnTokens:[],turns:[],model:t,permissionMode:"default",thinkingUi:"live"}}function lx(t,e,n,r,o){let s=r?.totalCostUsd,i=s??0,a=r?.durationMs??0,c=Number(r?.usage?.input_tokens??0),l=Number(r?.usage?.output_tokens??0),d=c,u=l,p=Number(r?.usage?.cache_read_input_tokens??0)+Number(r?.usage?.cache_creation_input_tokens??0),f=r?.usage?.iterations;if(Array.isArray(f)&&f.length>0){let w=f[f.length-1];if(w&&typeof w=="object"){let S=w;d=Number(S.input_tokens??0),u=Number(S.output_tokens??0),p=Number(S.cache_read_input_tokens??0)+Number(S.cache_creation_input_tokens??0)}}t.totalTurns+=1,t.totalCostUsd+=i,s===void 0&&(t.unpricedTurns+=1),t.totalDurationMs+=a,t.totalTokens+=c+l,t.turnCosts.push(i);let m=Number(r?.usage?.context_window_tokens??NaN),g=Array.isArray(f)&&f.length>0,h=Number.isFinite(m)?m:g?d+u+p:void 0;if(t.turnTokens.push({input:d,output:u,cache:p,...h!==void 0?{footprint:h}:{}}),r?.sessionId&&!t.sessionId&&(t.sessionId=String(r.sessionId)),!t.name){let w=rl(e);w&&(t.name=w)}let y={user:e,assistant:n,timestamp:Date.now(),costUsd:i,durationMs:a,inputTokens:c,outputTokens:l,...o&&o.length>0?{toolEvents:o}:{}};return t.turns.push(y),y}import{readFileSync as FG,writeFileSync as LG,existsSync as sl,mkdirSync as NG,readdirSync as UG,statSync as $G,realpathSync as dx}from"fs";import{join as px,basename as fx,resolve as ux,sep as BG}from"path";M();import{randomUUID as OG}from"node:crypto";var ws=class extends Error{constructor(e){super(e),this.name="SessionRegistryError"}},Nf=class{byId=new Map;byBinding=new Map;bySdk=new Map;now;constructor(e){this.now=e?.now??Date.now}create(e){let n=this.now(),r=e.id??OG();if(this.byId.has(r))throw new ws(`session handle already exists: ${r}`);let o={surface:e.surface,key:e.key,boundAt:n,lastActiveAt:n},s={id:r,surface:e.surface,model:e.model,createdAt:e.createdAt??n,lastActiveAt:n,status:"active",bindings:[o]};return e.name!==void 0&&(s.name=e.name),e.cwd!==void 0&&(s.cwd=e.cwd),e.sdkSessionId!==void 0&&(s.sdkSessionId=e.sdkSessionId),this.byId.set(r,s),this.pointBinding(this.bindingKey(o.surface,o.key),r),s.sdkSessionId!==void 0&&this.bySdk.set(s.sdkSessionId,r),this.clone(s)}load(e){if(this.byId.has(e.id))throw new ws(`session handle already exists: ${e.id}`);let n=this.clone(e);if(this.byId.set(n.id,n),n.status==="active")for(let r of n.bindings)this.pointBinding(this.bindingKey(r.surface,r.key),n.id);n.sdkSessionId!==void 0&&this.bySdk.set(n.sdkSessionId,n.id)}get(e){let n=this.byId.get(e);return n?this.clone(n):void 0}getBySdkSessionId(e){let n=this.bySdk.get(e);if(n===void 0)return;let r=this.byId.get(n);return r?this.clone(r):void 0}resolve(e,n){let r=this.byBinding.get(this.bindingKey(e,n));if(r===void 0)return;let o=this.byId.get(r);if(!(!o||o.status!=="active"))return this.clone(o)}bind(e,n){let r=this.require(e),o=this.now(),s=this.bindingKey(n.surface,n.key),i=r.bindings.find(a=>this.bindingKey(a.surface,a.key)===s);i?i.lastActiveAt=o:r.bindings.push({surface:n.surface,key:n.key,boundAt:o,lastActiveAt:o}),this.pointBinding(s,e),r.lastActiveAt=o}unbind(e,n){let r=this.bindingKey(e,n),o=this.byBinding.get(r);if(this.byBinding.delete(r),o===void 0)return;let s=this.byId.get(o);s&&(s.bindings=s.bindings.filter(i=>this.bindingKey(i.surface,i.key)!==r))}attachSdkSessionId(e,n){let r=this.require(e);r.sdkSessionId!==void 0&&r.sdkSessionId!==n&&this.bySdk.get(r.sdkSessionId)===e&&this.bySdk.delete(r.sdkSessionId),r.sdkSessionId=n,this.bySdk.set(n,e),r.lastActiveAt=this.now()}rename(e,n){let r=this.require(e);r.name=n,r.lastActiveAt=this.now()}touch(e){let n=this.require(e);n.lastActiveAt=this.now()}archive(e){let n=this.require(e);n.status="archived",n.lastActiveAt=this.now();for(let r of n.bindings){let o=this.bindingKey(r.surface,r.key);this.byBinding.get(o)===e&&this.byBinding.delete(o)}}list(e){let n=[];for(let r of this.byId.values())e?.surface!==void 0&&r.surface!==e.surface||e?.status!==void 0&&r.status!==e.status||n.push(this.clone(r));return n.sort((r,o)=>o.lastActiveAt-r.lastActiveAt),n}bindingKey(e,n){return`${e}\0${n}`}require(e){let n=this.byId.get(e);if(!n)throw new ws(`unknown session handle: ${e}`);return n}pointBinding(e,n){let r=this.byBinding.get(e);if(r!==void 0&&r!==n){let o=this.byId.get(r);o&&(o.bindings=o.bindings.filter(s=>this.bindingKey(s.surface,s.key)!==e))}this.byBinding.set(e,n)}clone(e){return{...e,bindings:e.bindings.map(n=>({...n}))}}};var ol=new Nf;function Ss(){return Rm(),re()}function jG(t){return px(Ss(),`${t}.json`)}function Uf(t,{write:e=!1}={}){let n=t.includes("/")?t:jG(t),r,o;if(!e&&sl(n)?(r=dx(n),o=dx(Ss())):(r=ux(n),o=ux(Ss())),!r.startsWith(o+BG)&&r!==o)throw new Error(`Session path escapes sessions directory: ${t}`);return r}function $f(t,e){let n=Ss();sl(n)||NG(n,{recursive:!0});let r=e??t.sessionId??`session-${Date.now()}`,o={sessionId:t.sessionId,...t.name?{name:t.name}:{},...t.source?{source:t.source}:{},...t.actor?{actor:t.actor}:{},...t.telegramChatId!==void 0?{telegramChatId:t.telegramChatId}:{},...t.cwd?{cwd:t.cwd}:{},model:t.model,startedAt:t.sessionStartTime,savedAt:Date.now(),totalTurns:t.totalTurns,totalCostUsd:t.totalCostUsd,unpricedTurns:t.unpricedTurns,totalTokens:t.totalTokens,totalDurationMs:t.totalDurationMs,turns:t.turns},s=Uf(r,{write:!0});return LG(s,JSON.stringify(o,null,2)),s}function pt(t){let e;try{e=Uf(t)}catch(n){console.warn(`loadSession: rejected unsafe session id ${JSON.stringify(t)}: ${n.message}`);return}if(sl(e))try{let n=FG(e,"utf-8");return JSON.parse(n)}catch(n){console.warn(`loadSession: failed to read/parse ${e}: ${n.message}`);return}}function Bf(t){let e;try{e=Uf(t)}catch{return}let n=pt(e);if(n)return{path:e,id:fx(e,".json"),data:n};let r=Ir();for(let s of r){if(s.id!==t&&s.sessionId!==t&&s.name!==t)continue;let i=pt(s.path);if(i)return{path:s.path,id:s.id,data:i}}if(t.length>=3){let s=r.filter(i=>i.name!==void 0&&i.name.startsWith(t));if(s.length===1){let i=s[0];if(i){let a=pt(i.path);if(a)return{path:i.path,id:i.id,data:a}}}}}function Ir(){let t=Ss();if(!sl(t))return[];let e=[];for(let n of UG(t)){if(!n.endsWith(".json"))continue;let r=px(t,n);try{if(!$G(r).isFile())continue;let s=pt(r);if(!s||typeof s.savedAt!="number"||typeof s.model!="string")continue;e.push({path:r,id:fx(n,".json"),sessionId:s.sessionId,name:s.name,source:s.source,actor:s.actor,telegramChatId:s.telegramChatId,model:s.model,startedAt:s.startedAt,savedAt:s.savedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd,cwd:s.cwd})}catch{}}return e.sort((n,r)=>r.savedAt-n.savedAt),e}function HG(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 mx(t){return!t||t.length===0?"":`
|
|
1295
1295
|
[Tools used: ${HG(t).map(r=>{let o=r.isError?"\u2717":"\u2713",s=r.input||r.inputRaw||"",i=s.length>80?s.slice(0,77)+"\u2026":s;return`${r.toolName}(${i})${o}`}).join(", ")}]`}function gx(t){return t?{resume:t.resumeId,sessionId:t.resumeId,...t.stored?{resumeHistory:t.stored.turns.map((e,n,r)=>{let o={user:e.user,assistant:(e.assistant??"")+mx(e.toolEvents)};return n===r.length-1&&e.inputTokens!==void 0&&(o.inputTokens=e.inputTokens),o})}:{}}:{}}function WG(t){if(t===null||typeof t!="object")return{};let e=t,n=e.message_thread_id,r=e.is_topic_message;return{...typeof n=="number"?{threadId:n}:{},...r===!0?{isTopic:!0}:{}}}function V(t){let e=t.chat?.id;if(typeof e!="number")return;let n=t.message??t.editedMessage??t.callbackQuery?.message,{threadId:r,isTopic:o}=WG(n),s={chatId:e};return r!==void 0&&r!==0&&(s.threadId=r),o&&(s.isTopicMessage=!0),s}function hx(t){return t.threadId===void 0||t.threadId===0||t.threadId===1}function j(t){return hx(t)?String(t.chatId):`${t.chatId}:${t.threadId}`}function en(t){return hx(t)?{}:{message_thread_id:t.threadId}}function yx(t,e,n,r){let o=j(e),s=o,i=t.resolve("telegram",o);if(i){t.touch(i.id),n.sessionId&&t.attachSdkSessionId(i.id,n.sessionId);return}let a=t.get(s);if(a&&a.status==="active"){t.bind(s,{surface:"telegram",key:o}),n.sessionId&&t.attachSdkSessionId(s,n.sessionId);return}let c=a===void 0?s:void 0;t.create({surface:"telegram",key:o,model:n.model??r,id:c,sdkSessionId:n.sessionId})}function jf(t,e){t.archive(e)}function bx(t,e){let n;for(let o of t)o.chatId===e&&(!n||o.lastActivity>n.lastActivity)&&(n=o);if(!n)return;let r={chatId:n.chatId};return n.threadId!==void 0&&(r.threadId=n.threadId),r}function wx(t,e,n){let r=j(n);if(t.has(r))return;let o=e.get(r)?.sessionId;if(!o)return;let s=pt(o);if(!s||s.source!=="telegram"||s.telegramChatId!==n.chatId)return;let i={sessionId:s.sessionId,name:s.name,model:s.model,source:s.source,telegramChatId:s.telegramChatId,sessionStartTime:s.startedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd,unpricedTurns:s.unpricedTurns??0,totalTokens:s.totalTokens,totalDurationMs:s.totalDurationMs,turns:s.turns,turnCosts:[],turnTokens:[],permissionMode:"default"},a=e.get(r)?.cwd;a!==void 0&&(i.cwd=a),t.set(r,i)}import{promises as ks}from"fs";import{join as Sx}from"path";function Oe(t){return typeof t=="number"?{chatId:t}:t}var Cr=class{sessions=new Map;pendingSessions=new Map;sessionData=new Map;sessionStats=new Map;autosaveFailureLogged=new Set;pendingResume=new Map;options;constructor(e){this.options={dataDir:e.dataDir||"./data/telegram-sessions",defaultModel:e.defaultModel||"medium",apiKey:e.apiKey,settingSources:e.settingSources,thinking:e.thinking,effort:e.effort,botCwd:e.botCwd,createSession:e.createSession,registry:e.registry,onResumptionOffer:e.onResumptionOffer}}getSessionIfExists(e){return this.sessions.get(j(Oe(e)))}async getSession(e){let n=Oe(e),r=j(n),o=this.sessions.get(r);if(o)return this._touchActivity(r),o;let s=this.pendingSessions.get(r);if(s)try{return await s}finally{this._touchActivity(r)}let i=this.sessionData.get(r)??this._newData(n),a=(async()=>{let c={model:i.model,apiKey:this.options.apiKey,telegramChatId:n.chatId,...n.threadId!==void 0?{telegramThreadId:n.threadId}:{}};this.options.settingSources?.length&&(c.settingSources=this.options.settingSources),this.options.thinking!==void 0&&(c.thinking=this.options.thinking),this.options.effort!==void 0&&(c.effort=this.options.effort);let l=i.cwd??this.options.botCwd;l!==void 0&&l.length>0&&(c.cwd=l);let d=this.pendingResume.get(r);if(d!==void 0){let p=pt(d);Object.assign(c,gx({id:d,resumeId:p?.sessionId??d,stored:p}))}let u=await this.options.createSession(Df(Qu(c)));this.sessions.set(r,u),this.sessionData.set(r,i);try{this._ensureRegistryHandle(n,i)}catch{}return u.sessionId&&(Lf(u.sessionId,n),i.sessionId=u.sessionId),this.options.onResumptionOffer&&ax(u.sessionId??"",n,this.options.onResumptionOffer),d!==void 0&&this.pendingResume.delete(r),u})();this.pendingSessions.set(r,a);try{let c=await a;return this._touchActivity(r),c}finally{this.pendingSessions.delete(r)}}_newData(e){let n={chatId:e.chatId,model:this.options.defaultModel,createdAt:new Date().toISOString(),lastActivity:new Date().toISOString()};return e.threadId!==void 0&&(n.threadId=e.threadId),n}_touchActivity(e){let n=this.sessionData.get(e);n&&(n.lastActivity=new Date().toISOString())}_ensureRegistryHandle(e,n){yx(this.options.registry??ol,e,n,this.options.defaultModel)}recordTelegramTurn(e,n,r,o){let s=Oe(e),i=j(s),a=this._getOrCreateStats(s),c=this.sessions.get(i);!a.sessionId&&c?.sessionId&&(a.sessionId=c.sessionId),lx(a,n,r,o),!a.sessionId&&c?.sessionId&&(a.sessionId=c.sessionId);let l=this.sessionData.get(i);if(l&&a.sessionId&&(l.sessionId=a.sessionId),a.sessionId&&Lf(a.sessionId,s),a.sessionId)try{$f(a)}catch(d){this.autosaveFailureLogged.has(i)||(this.autosaveFailureLogged.add(i),console.error(`[session-manager] autosave failed for chat ${s.chatId} \u2014 conversation may not be resumable:`,d))}}_hydrateStatsFromStore(e){wx(this.sessionStats,this.sessionData,e)}getSessionName(e){let n=Oe(e);return this._hydrateStatsFromStore(n),this.sessionStats.get(j(n))?.name}setSessionName(e,n){let r=Oe(e),o=j(r),s=this._getOrCreateStats(r);s.name=n;let i=this.sessions.get(o);if(!s.sessionId&&i?.sessionId&&(s.sessionId=i.sessionId),s.totalTurns>0&&s.sessionId){let a=this.sessionData.get(o);return a&&(a.sessionId=s.sessionId),$f(s),{persisted:!0}}return{persisted:!1}}_getOrCreateStats(e){let n=j(e);this._hydrateStatsFromStore(e);let r=this.sessionStats.get(n);if(!r){r=cx(this.getModel(e)),r.source="telegram",r.telegramChatId=e.chatId;let o=this.getCwd(e);o&&(r.cwd=o),this.sessionStats.set(n,r)}return r}_resetStats(e){let n=this.sessionStats.get(e)?.sessionId??this.sessionData.get(e)?.sessionId;n&&ix(n),this.sessionStats.delete(e),this.autosaveFailureLogged.delete(e),this.pendingResume.delete(e);let r=this.sessionData.get(e);r&&delete r.sessionId}async resetSession(e){let n=Oe(e),r=j(n);try{jf(this.options.registry??ol,r)}catch{}let o=this.sessions.get(r);o&&(await o.close(),this.sessions.delete(r)),this._resetStats(r);let s=this.sessionData.get(r);s&&(s.lastActivity=new Date().toISOString())}async switchModel(e,n){let r=Oe(e),o=j(r);try{jf(this.options.registry??ol,o)}catch{}let s=this.sessions.get(o);s&&(await s.close(),this.sessions.delete(o)),this._resetStats(o);let i=this.sessionData.get(o);i?(i.model=n,i.lastActivity=new Date().toISOString()):(i=this._newData(r),i.model=n,this.sessionData.set(o,i));try{this._ensureRegistryHandle(r,i)}catch{}}getModel(e){return this.sessionData.get(j(Oe(e)))?.model||this.options.defaultModel}async setCwd(e,n){let r=Oe(e),o=j(r),s=this.sessions.get(o);s&&(await s.close(),this.sessions.delete(o)),this._resetStats(o);let i=this.sessionData.get(o);i?(i.cwd=n,i.lastActivity=new Date().toISOString()):(i=this._newData(r),i.cwd=n,this.sessionData.set(o,i))}getCwd(e){return this.sessionData.get(j(Oe(e)))?.cwd??this.options.botCwd}listChatSessions(e){let n=Oe(e),r=this.sessionData.get(j(n))?.sessionId;return Ir().filter(o=>o.source==="telegram"&&o.telegramChatId===n.chatId&&o.sessionId!==void 0).map(o=>{let s={sessionId:o.sessionId,model:o.model,turns:o.totalTurns,lastActive:o.savedAt,active:o.sessionId===r};return o.name!==void 0&&(s.name=o.name),s}).sort((o,s)=>s.lastActive-o.lastActive)}async switchToSession(e,n){let r=Oe(e),o=j(r),s=this.pendingSessions.get(o);if(s!==void 0&&await s.catch(()=>{}),this.sessions.has(o)&&this.sessionData.get(o)?.sessionId===n)return{ok:!1,reason:"already-active"};let i=pt(n);if(!i||i.source!=="telegram"||i.telegramChatId!==r.chatId)return{ok:!1,reason:"not-found"};let a=this.sessions.get(o);a&&(await a.close().catch(l=>console.error("Error closing session on switch:",l)),this.sessions.delete(o)),this.sessionStats.delete(o),this.autosaveFailureLogged.delete(o);let c=this.sessionData.get(o);return c?(c.model=i.model,c.lastActivity=new Date().toISOString()):(c=this._newData(r),c.model=i.model,this.sessionData.set(o,c)),c.sessionId=n,i.cwd!==void 0?c.cwd=i.cwd:delete c.cwd,this.pendingResume.set(o,n),i.name!==void 0?{ok:!0,name:i.name}:{ok:!0}}async newSession(e){this.pendingResume.delete(j(Oe(e))),await this.resetSession(e)}sidecarFileName(e){let n={chatId:e.chatId};return e.threadId!==void 0&&(n.threadId=e.threadId),`${j(n)}.json`}async loadSessions(){try{await ks.mkdir(this.options.dataDir,{recursive:!0});let e=await ks.readdir(this.options.dataDir);for(let n of e)if(n.endsWith(".json")){let r=Sx(this.options.dataDir,n),o=await ks.readFile(r,"utf-8"),s=JSON.parse(o),i={chatId:s.chatId};s.threadId!==void 0&&(i.threadId=s.threadId),this.sessionData.set(j(i),s);try{this._ensureRegistryHandle(i,s)}catch{}}}catch(e){e.code!=="ENOENT"&&console.error("Failed to load sessions:",e)}}async saveSessions(){try{await ks.mkdir(this.options.dataDir,{recursive:!0});for(let e of this.sessionData.values()){let n=Sx(this.options.dataDir,this.sidecarFileName(e));await ks.writeFile(n,JSON.stringify(e,null,2))}}catch(e){console.error("Failed to save sessions:",e)}}_evictStaleSessionData(e=1440*60*1e3){let n=Date.now();for(let[r,o]of this.sessionData){if(this.sessions.has(r))continue;n-new Date(o.lastActivity).getTime()>e&&this.sessionData.delete(r)}}async closeAll(){this._evictStaleSessionData(),await this.saveSessions(),await Promise.all(Array.from(this.sessions.values()).map(e=>e.close().catch(n=>console.error("Error closing session:",n)))),this.sessions.clear()}getSessionCount(){return this.sessions.size}getChatCount(){return this.sessionData.size}getActiveThreadId(e){let n;for(let r of this.sessionData.values())r.chatId!==e||r.threadId===void 0||(n===void 0||r.lastActivity>n.lastActivity)&&(n=r);return n?.threadId}getBusySessionCount(){let e=0;for(let n of this.sessions.values())n.state!=="idle"&&n.state!=="closed"&&e++;return e}getActiveRouteForChat(e){return bx(this.sessionData.values(),e)}};async function Hf(t){await t.reply(qd())}async function Wf(t,e){let n=V(t),r,o=n?e.getSessionIfExists(n):void 0;if(o)try{await Promise.race([o.waitForInitialization(),new Promise((i,a)=>setTimeout(()=>a(new Error("timeout")),2e3))]);let s=o.getSessionMetadata();s.slashCommands?.length&&(r=s.slashCommands)}catch{}await t.reply(Gy(r))}import{Markup as Ax}from"telegraf";import{promises as GG}from"fs";import{homedir as xx}from"os";import{isAbsolute as XG,resolve as Kf}from"path";async function vs(t,e){t.sendChatAction("typing").catch(()=>{});let n=setInterval(()=>{t.sendChatAction("typing").catch(()=>{})},4e3);try{return await e()}finally{clearInterval(n)}}function KG(t,e){try{if(!t||t.trim().toLowerCase()==="auto")return{available:!0,needs:"unknown"};let n=an(t,e);if(n.id==="")return{available:!1,needs:"local",hint:"not configured (set AFK_MODEL_LOCAL / models.local)"};if(n.provider==="chatgpt-oauth"){let o=Jt(void 0,{},!0),s=o.apiKey!=null,i=s?void 0:o.source==="chatgpt-oauth-expired"?"ChatGPT token expired \u2014 re-run `codex` to refresh":"needs ChatGPT sign-in (~/.codex/auth.json)";return{available:s,needs:"chatgpt-oauth",hint:i}}if(n.provider==="xai-oauth"){let o=ut(void 0,"oauth").apiKey!=null;return{available:o,needs:"xai-oauth",hint:o?void 0:"needs SuperGrok OAuth (`afk provider auth xai login`)"}}if(n.provider==="xai"){let o=ut(n.apiKey,"apikey").apiKey!=null;return{available:o,needs:"xai",hint:o?void 0:"needs XAI_API_KEY"}}if(n.apiKey)return{available:!0,needs:"unknown"};let r=z(t,e?{slots:e}:void 0);if(r==="anthropic-direct"){let o=!!Ui();return{available:o,needs:"anthropic",hint:o?void 0:"needs Claude sign-in / ANTHROPIC_API_KEY"}}if(r==="openai-compatible"){if(n.baseUrl)return{available:!0,needs:"local"};let o=!!Nd()||Jt(void 0,{},!1).apiKey!=null;return{available:o,needs:"openai",hint:o?void 0:"needs OPENAI_API_KEY"}}if(r==="xai"||r==="xai-oauth"){let i=ut(void 0,r==="xai-oauth"?"oauth":void 0).apiKey!=null;return{available:i,needs:r==="xai-oauth"?"xai-oauth":"xai",hint:i?void 0:"needs XAI_API_KEY or SuperGrok OAuth (`afk provider auth xai login`)"}}return{available:!0,needs:"unknown"}}catch{return{available:!0,needs:"unknown"}}}function kx(t,e){return KG(t,e).available}var qG=/^[A-Za-z0-9_@%+=:,./-]+$/;function vx(t){return qG.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Tx(t,e){let n=["afk","interactive"];return typeof e=="string"&&e.length>0&&n.push("--model",vx(e)),n.push("--resume",vx(t)),n.join(" ")}function _x(t){if(sn.includes(t)||Ln(t)!==void 0)return!0;let e=z(t);if(e==="openai-compatible"||e==="xai"||e==="xai-oauth")return!0;let n=an(t).id.trim().toLowerCase();return n.startsWith("claude-")||n.startsWith("claude_")}function Ex(t){return _x(t)}async function qf(t,e,n,r){let o=V(t);if(!o){await t.reply(B("Could not identify chat"));return}try{await e.resetSession(o),n.delete(o.chatId),await t.reply(Ao())}catch(s){r("Clear error:",s),await t.reply(B(s))}}async function Rx(t,e,n){let r=V(t);if(!r){await t.reply(B("Could not identify chat"));return}try{let o=await e.getSession(r),s=o.hookRegistry,i=await vs(t,async()=>(s&&await s.dispatch({event:"PreCompact",sessionId:o.sessionId,trigger:"manual"}),o.compact()));i.compacted?await t.reply(xo({before:i.messagesBefore,after:i.messagesAfter,...i.tokensSavedEstimate!==void 0?{tokensSavedEstimate:i.tokensSavedEstimate}:{}})):await t.reply(Ro(i.reason??"unknown"))}catch(o){o instanceof W?await t.reply(`Compaction skipped: ${Ce(o.reason??"blocked by hook")}`):(n("Compact error:",o),await t.reply(B(o)))}}async function Gf(t,e,n){let r=V(t);if(!r){await t.reply(B("Could not identify chat"));return}let s=t.message.text.split(/\s+/).slice(1);if(s.length===0){let l=e.getModel(r),d=sn.map(u=>[Ax.button.callback(kx(u)?u:`${u} \u2014 needs sign-in`,`afk:m:${u}`)]);await t.reply(`Current model: <b>${Ce(l.toUpperCase())}</b>
|
|
1296
1296
|
|
|
1297
1297
|
Switch to:`,{parse_mode:"HTML",reply_markup:Ax.inlineKeyboard(d).reply_markup});return}let i=s[0];if(!i){await t.reply(B("Please specify a model: local, small, medium, large, opus, sonnet, haiku, or an org/model id"));return}let a=i.toLowerCase();if(!Ex(a)){await t.reply(B(`Invalid model: ${i}
|
|
@@ -1338,8 +1338,8 @@ Resets at ${n.pausedUntil.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-di
|
|
|
1338
1338
|
|
|
1339
1339
|
I'll auto-resume when the limit resets \u2014 no need to retype.`;n.editInFlight=!0,ce(n,r,o,f,!0).finally(()=>{n.editInFlight=!1})}},X2))}async function sR(t,e){let{state:n,ctx:r,chatId:o}=e;n.countdownInterval!==null&&(clearInterval(n.countdownInterval),n.countdownInterval=null),n.pausedUntil=null;let s=t.hotSwapped&&t.accountId?`\u25B6 **Resumed on ${t.accountId}**`:"\u25B6 **Resumed**";await ce(n,r,o,s,!0)}async function iR(t,e){let{state:n,ctx:r,chatId:o,cleanFinal:s,finalBody:i,clearProgressTimer:a,onComplete:c,logger:l,renderActivityReceipt:d}=e;if(n.sawTerminalEvent=!0,n.turnEnded=!0,a(),n.countdownInterval!==null&&(clearInterval(n.countdownInterval),n.countdownInterval=null),s&&n.answerText.trim()?await yl(r,n.answerText+d(n.progressRounds,Date.now()-n.turnStartedAt))&&n.sentMessage&&(await r.telegram.deleteMessage?.(o,n.sentMessage.message_id).catch(()=>{}),n.sentMessage=null):i().trim()&&await ce(n,r,o,i(),!0),c)try{await c(n.answerText,t)}catch(u){l?.("streamResponse onComplete (turn recording) failed:",u)}return!0}function aR(t,e){let{state:n,clearProgressTimer:r}=e;throw n.sawTerminalEvent=!0,n.turnEnded=!0,r(),n.countdownInterval!==null&&(clearInterval(n.countdownInterval),n.countdownInterval=null),t}async function cR(t,e,n,r,o){if(!(!(e&&n.trim())&&r&&o))return;let s=Se(Bt(r));if(s.length<=1)return;let i=(a,c)=>t.reply(a,c);try{for(let a=1;a<s.length;a++){let c=s[a];c&&await Dr(i,c,{parse_mode:"HTML"})}}catch(a){if(a instanceof G2)await t.reply(nm).catch(()=>{});else throw a}}var J2=9e4,lR=18e4,V2=66e4,dR=15e3,Y2=6e4;function Q2(){let t=Rc();return 3*Pc(t)+Y2}var uR=5e3,Z2=9e4;function pR(t,e){return()=>{let n=e.pausedUntil!==null?Math.max(lR,e.pausedUntil.getTime()-Date.now()+Z2):e.receivedAny?lR:J2;return new Promise((r,o)=>{let s=null,i=()=>{let a=n-(Date.now()-e.lastActivityAt);if(a<=0){if(e.inFlightTools.size>0&&e.toolInFlightSince!==null&&Date.now()-e.toolInFlightSince<V2){s=setTimeout(i,dR);return}if(e.apiRoundInFlight&&e.apiRoundSince!==null&&Date.now()-e.apiRoundSince<Q2()){s=setTimeout(i,dR);return}s=null,e.timedOut=!0,o(new An(e.receivedAny?"Response timed out. Try sending a shorter message or try again.":"Request timed out. The agent may still be starting (first message can take a minute). Try again in a moment."))}else s=setTimeout(i,a)};s=setTimeout(i,n),t.next().then(a=>{s!=null&&(clearTimeout(s),s=null),r(a)},a=>{s!=null&&(clearTimeout(s),s=null),o(a)})})}}function fR(t,e,n){return setTimeout(()=>{n()||e()},Math.max(0,t))}async function mR(t,e,n,r,o,s,i,a,c){e.progressRounds++;let{description:l,lastToolName:d}=t.progress,u=`\u25E6 ${Jf(l,d)}`;e.progressEntries[e.progressEntries.length-1]?.label!==u&&e.progressEntries.push({label:u,at:e.accumulated.length}),e.progressEntries.length>Qf&&(e.progressEntries=e.progressEntries.slice(-Qf)),!n&&Date.now()-e.turnStartedAt>=r&&(a(!0),n=!0),n?(c(),await ce(e,o,s,i())):e.progressTimer===null&&(e.progressTimer=fR(r-(Date.now()-e.turnStartedAt),()=>{e.progressTimer=null,a(!0),!e.editInFlight&&(e.editInFlight=!0,ce(e,o,s,i(),!0).finally(()=>{e.editInFlight=!1}))},()=>e.turnEnded))}function gR(t,e,n,r,o,s){return(i,a)=>{let c=Vf(a.agentType??a.subagentId);o(),i.type==="chunk"&&i.chunk.type==="tool_use_detail"?(s.subagentSteps++,s.recentSubagentSteps.push(`${c} \u2014 ${gl(i.chunk.toolName)}`),s.recentSubagentSteps.length>zf&&s.recentSubagentSteps.shift(),ce(t,e,n,r())):i.type==="done"&&ce(t,e,n,r())}}function eX(t,e){if(t<=0)return"";let n=Math.max(1,Math.round(e/1e3));return`
|
|
1340
1340
|
|
|
1341
|
-
\u23F1\uFE0F ${t} ${t===1?"step":"steps"} \xB7 ${n}s`}async function rm(t,e,n,r,o={}){if(!t.chat?.id){r?.("streamResponse: ctx.chat is undefined (non-chat context); skipping");return}let s=t.chat.id,i=o.cleanFinal??!1,a=o.progressDelayMs??uR,c={accumulated:"",answerText:"",sentMessage:null,lastEditAt:0,pausedUntil:null,countdownInterval:null,editInFlight:!1,lastCountdownBucket:-1,sawTerminalEvent:!1,progressEntries:[],progressRounds:0,turnEnded:!1,progressTimer:null,turnStartedAt:Date.now()},l=0,d=0,u=!1,p={receivedAny:!1,timedOut:!1,lastActivityAt:Date.now(),inFlightTools:new Set,toolInFlightSince:null,get pausedUntil(){return c.pausedUntil},apiRoundInFlight:!1,apiRoundSince:null},f={subagentSteps:0,recentSubagentSteps:[]},m=a<=0,g=()=>{c.progressTimer!==null&&(clearTimeout(c.progressTimer),c.progressTimer=null)},h=()=>nR({accumulated:c.accumulated,progressEntries:c.progressEntries,progressGateOpen:m,subagentSteps:f.subagentSteps,recentSubagentSteps:f.recentSubagentSteps}),y=()=>rR({accumulated:c.accumulated,progressEntries:c.progressEntries}),w={state:c,ctx:t,chatId:s,cleanFinal:i,livePreview:h,finalBody:y,clearProgressTimer:g,renderActivityReceipt:eX,onComplete:o.onComplete,logger:r};try{let
|
|
1342
|
-
`),{stream:!1});yield{type:"message",message:I},yield{type:"done",metadata:I.metadata}})():"sendMessageStream"in e&&typeof e.sendMessageStream=="function"?e.sendMessageStream(n):(async function*(){let I=await e.sendMessage(n,{stream:!1});yield{type:"message",message:I},yield{type:"done",metadata:I.metadata}})();await ce(c,t,s,"Thinking\u2026");let v=
|
|
1341
|
+
\u23F1\uFE0F ${t} ${t===1?"step":"steps"} \xB7 ${n}s`}async function rm(t,e,n,r,o={}){if(!t.chat?.id){r?.("streamResponse: ctx.chat is undefined (non-chat context); skipping");return}let s=t.chat.id,i=o.cleanFinal??!1,a=o.progressDelayMs??uR,c={accumulated:"",answerText:"",sentMessage:null,lastEditAt:0,pausedUntil:null,countdownInterval:null,editInFlight:!1,lastCountdownBucket:-1,sawTerminalEvent:!1,progressEntries:[],progressRounds:0,turnEnded:!1,progressTimer:null,turnStartedAt:Date.now()},l=0,d=0,u=!1,p={receivedAny:!1,timedOut:!1,lastActivityAt:Date.now(),inFlightTools:new Set,toolInFlightSince:null,get pausedUntil(){return c.pausedUntil},apiRoundInFlight:!1,apiRoundSince:null},f={subagentSteps:0,recentSubagentSteps:[]},m=a<=0,g=()=>{c.progressTimer!==null&&(clearTimeout(c.progressTimer),c.progressTimer=null)},h=()=>nR({accumulated:c.accumulated,progressEntries:c.progressEntries,progressGateOpen:m,subagentSteps:f.subagentSteps,recentSubagentSteps:f.recentSubagentSteps}),y=()=>rR({accumulated:c.accumulated,progressEntries:c.progressEntries}),w={state:c,ctx:t,chatId:s,cleanFinal:i,livePreview:h,finalBody:y,clearProgressTimer:g,renderActivityReceipt:eX,onComplete:o.onComplete,logger:r};try{let S=Array.isArray(n)?"sendMessageStream"in e&&typeof e.sendMessageStream=="function"?e.sendMessageStream(n):(async function*(){let I=await e.sendMessage(n.map(k=>k.type==="text"?k.text:"").filter(Boolean).join(`
|
|
1342
|
+
`),{stream:!1});yield{type:"message",message:I},yield{type:"done",metadata:I.metadata}})():"sendMessageStream"in e&&typeof e.sendMessageStream=="function"?e.sendMessageStream(n):(async function*(){let I=await e.sendMessage(n,{stream:!1});yield{type:"message",message:I},yield{type:"done",metadata:I.metadata}})();await ce(c,t,s,"Thinking\u2026");let v=S[Symbol.asyncIterator](),_=pR(v,p),E=gR(c,t,s,h,()=>{p.lastActivityAt=Date.now()},f),T=!!b.AFK_TELEGRAM_TRACE;try{await pv(E,async()=>{for(;;){T&&console.log("[trace] awaiting next event");let k=await _();if(T&&console.log("[trace] event arrived:",k.done?"DONE":k.value.type),k.done)break;let A=k.value;if(p.lastActivityAt=Date.now(),p.apiRoundInFlight&&(p.apiRoundInFlight=!1,p.apiRoundSince=null),p.receivedAny||(p.receivedAny=!0,console.log("\u{1F4E1} First stream event received:",A.type),r?.("First stream event received:",A.type)),A.type==="chunk"&&A.chunk.type==="tool_use_detail"?(p.inFlightTools.size===0&&(p.toolInFlightSince=Date.now()),p.inFlightTools.add(A.chunk.toolUseId)):A.type==="chunk"&&A.chunk.type==="tool_result"&&(p.inFlightTools.delete(A.chunk.toolUseId),p.inFlightTools.size===0&&(p.toolInFlightSince=null)),A.type==="chunk"&&A.chunk.type==="content"&&(u||(l=c.accumulated.length,d=c.answerText.length,u=!0),c.accumulated+=A.chunk.content,c.answerText+=A.chunk.content,await ce(c,t,s,h())),A.type==="stream_retry"&&(c.accumulated=c.accumulated.slice(0,l),c.answerText=c.answerText.slice(0,d),u=!1,await ce(c,t,s,h(),!0)),A.type==="rate_limit"){let G=A.retryAfterMs!==void 0?A.retryAfterMs<6e4?A.retryAfterMs:8e3:null,F=G!==null?Math.ceil(G/1e3):null,N=F!==null?`\u23F8 Rate limited \xB7 retrying in ~${F}s\u2026`:"\u23F8 Rate limited \xB7 retrying\u2026";await ce(c,t,s,h()+`
|
|
1343
1343
|
|
|
1344
1344
|
${N}`,!0);continue}if(A.type==="chunk"&&A.chunk.type,A.type==="message"&&A.message.role==="assistant"&&(c.accumulated=A.message.content,c.answerText=A.message.content,u=!1,c.progressEntries=c.progressEntries.map(R=>({...R,at:c.accumulated.length})),await ce(c,t,s,h())),A.type==="progress"&&(u=!1,p.apiRoundInFlight=!0,p.apiRoundSince=Date.now(),await mR(A,c,m,a,t,s,h,R=>{m=R},g)),A.type==="suggestion"&&A.suggestion.trim()!==c.answerText.trim()&&(c.accumulated+=`
|
|
1345
1345
|
|
|
@@ -1347,28 +1347,28 @@ ${N}`,!0);continue}if(A.type==="chunk"&&A.chunk.type,A.type==="message"&&A.messa
|
|
|
1347
1347
|
|
|
1348
1348
|
\u{1F4A1} ${A.suggestion}`,await ce(c,t,s,h())),A.type==="notice"){let R=`
|
|
1349
1349
|
|
|
1350
|
-
_\u2139 ${A.text.replace(/[_*[\]()~`>#+\-=|{}.!]/g,"\\$&")}_`;c.accumulated+=R,await ce(c,t,s,h())}if(A.type==="paused"){await oR(A,w);continue}if(A.type==="resumed"){await sR(A,w);continue}if(A.type==="done"){await iR(A.metadata,w);break}A.type==="error"&&aR(A.error,w)}});let I=c.sentMessage;if(I&&!c.sawTerminalEvent){let
|
|
1350
|
+
_\u2139 ${A.text.replace(/[_*[\]()~`>#+\-=|{}.!]/g,"\\$&")}_`;c.accumulated+=R,await ce(c,t,s,h())}if(A.type==="paused"){await oR(A,w);continue}if(A.type==="resumed"){await sR(A,w);continue}if(A.type==="done"){await iR(A.metadata,w);break}A.type==="error"&&aR(A.error,w)}});let I=c.sentMessage;if(I&&!c.sawTerminalEvent){let k=i&&c.answerText.trim()?c.answerText:y();k.trim()&&await yl(t,k)&&(await t.telegram.deleteMessage?.(s,I.message_id).catch(()=>{}),c.sentMessage=null)}else await cR(t,i,c.answerText,y(),I)}finally{(p.timedOut||!c.sawTerminalEvent)&&await Promise.resolve(e.interrupt?.()).catch(()=>{}),c.countdownInterval!==null&&(clearInterval(c.countdownInterval),c.countdownInterval=null),c.turnEnded=!0,g(),c.editInFlight=!1,p.apiRoundInFlight=!1,p.apiRoundSince=null,await Promise.resolve(v.return?.(void 0)).catch(()=>{})}}catch(S){throw r?.("Streaming error:",S),S}}async function bl(t,e,n,r,o){if(!r.has(e))try{await Promise.race([n.waitForInitialization(),new Promise((a,c)=>setTimeout(()=>c(new Error("timeout")),5e3))]);let s=n.getSessionMetadata(),i=[{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"},{command:"cd",description:"Show or change session working directory"},{command:"name",description:"Show or set the session name"},{command:"usage",description:"Show Claude subscription usage"},{command:"sessions",description:"List and switch between sessions"},{command:"new",description:"Start a new session (keeps the current one)"}];if(s.slashCommands?.length)for(let a of s.slashCommands){let c=a.replace(/^\//,"");i.push({command:c,description:`SDK command: ${c}`})}if(s.skills?.length)for(let a of s.skills)i.push({command:a,description:`Run ${a} skill`});await t.telegram.setMyCommands(i,{scope:{type:"chat",chat_id:e}}),r.add(e),o(`Registered ${i.length} commands for chat ${e}`)}catch(s){o(`Could not register dynamic commands for chat ${e}:`,s)}}function le(t){return[...[...t].map(r=>{if(r==="["||r==="]"||r==="@"||r==="("||r===")")return"";let o=r.codePointAt(0)??0;return o<32||o===127?" ":r}).join("").replace(/\s+/g," ").trim()].slice(0,64).join("")}function Fr(t,e){if(e!=="group"&&e!=="supergroup"||!t)return"";let n=le([t.first_name??"",t.last_name??""].join(" ")),r=t.username?le(t.username):"",o=typeof t.id=="number"&&Number.isFinite(t.id)?`id ${t.id}`:"",s=[n,r?`@${r}`:""].filter(Boolean).join(" "),i;if(s&&o)i=`${s} (${o})`;else if(s)i=s;else if(o)i=o;else return"";return`[from ${i}]: `}var hR=300;function om(t){let n=[...t].map(o=>{if(o==="["||o==="]"||o==='"')return"";let s=o.codePointAt(0)??0;return s<32||s===127?" ":o}).join("").replace(/\s+/g," ").trim(),r=[...n];return r.length<=hR?n:r.slice(0,hR).join("")+"\u2026"}var yR="the assistant";function tX(t,e){if(t&&typeof t.id=="number"&&Number.isFinite(t.id)&&e!==void 0&&t.id===e)return yR;if(!t)return"";let n=le([t.first_name??"",t.last_name??""].join(" "));if(n&&n.toLowerCase()!==yR)return n;let r=t.username?le(t.username):"";return r?`@${r}`:""}function Es(t){let{replyToMessage:e,quote:n,botId:r}=t,o=n?.text??"";if(!e&&o.length===0)return"";let s=tX(e?.from,r),i=om(o)||om(e?.text??"")||om(e?.caption??"");return i?s?`[in reply to ${s}: "${i}"] `:`[in reply to: "${i}"] `:e?s?`[in reply to ${s}'s message] `:"[in reply to an earlier message] ":""}function nX(t){let{first_name:e="",last_name:n="",username:r}=t.sender_user,o=le(`${e} ${n}`.trim()),s=r?le(r):"";return[o,s?`@${s}`:""].filter(Boolean).join(" ")}function rX(t){return le(t.sender_user_name)}function oX(t){let e=t.sender_chat,n=le(e.title??""),r=e.username?le(e.username):"";return[n,r?`@${r}`:""].filter(Boolean).join(" ")}function sX(t){let e=t.chat,n=le(e.title??""),r=e.username?le(e.username):"";return[n,r?`@${r}`:""].filter(Boolean).join(" ")}function iX(t){let e=le(`${t.first_name??""} ${t.last_name??""}`.trim()),n=t.username?le(t.username):"";return[e,n?`@${n}`:""].filter(Boolean).join(" ")}function As(t){let e="";if(t.forward_origin){let n=t.forward_origin;n.type==="user"?e=nX(n):n.type==="hidden_user"?e=rX(n):n.type==="chat"?e=oX(n):n.type==="channel"?e=sX(n):console.warn(`[forward-provenance] unknown forward_origin.type "${n.type}" \u2014 Bot API may have added a new origin type`)}if(!e&&t.forward_from&&(e=iX(t.forward_from)),!e&&t.forward_from_chat){let n=t.forward_from_chat,r=le(n.title??""),o=n.username?le(n.username):"";e=[r,o?`@${o}`:""].filter(Boolean).join(" ")}return!e&&t.forward_sender_name&&(e=le(t.forward_sender_name)),e?`[forwarded from ${e}] `:""}var bR=5*1024*1024,aX=new Set(["txt","md","json","yaml","yml","xml","csv","log","py","js","ts","sh","toml","ini","cfg","conf","html","css","sql","rb","go","rs","java","c","cpp","h","jsx","tsx","kt","swift","r","pl","lua","php","bat","ps1"]),cX="text/code files (.txt, .md, .py, .js, .ts, .json, .yaml, etc.) or PDF";function lX(t){return t.replace(/\/bot[^/]+\//g,"/bot[REDACTED]/")}function dX(t,e){let n=(t??"").toLowerCase().split(";")[0]?.trim()??"";if(n==="application/pdf")return"pdf";if(n.startsWith("text/"))return"text";let r=(e??"").split(".").pop()?.toLowerCase()??"";return aX.has(r)?"text":"unsupported"}async function uX(t,e){let n=t.headers.get("content-length");if(n!=null){let a=Number(n);if(Number.isFinite(a)&&a>e)return{status:"too-large",bytesRead:a}}let r=t.body;if(!r)return{status:"missing-body"};let o=r.getReader(),s=[],i=0;try{for(;;){let{done:a,value:c}=await o.read();if(a)break;if(i+=c.byteLength,i>e)return await o.cancel().catch(()=>{}),{status:"too-large",bytesRead:i};s.push(Buffer.from(c))}}finally{o.releaseLock()}return{status:"ok",bytes:Buffer.concat(s,i)}}async function wR(t,e){let n=t.message,r=n?.document;if(!n||!r)return e("Document handling: missing message or document field"),null;let o=t.chat?.id,s=r.file_name,i=r.mime_type;if(r.file_size!=null&&r.file_size>bR)return e(`Document handling: oversized file (${r.file_size} bytes) for chat ${o??"(unknown)"}`),await t.reply("\u274C Document is too large (max 5 MB). Please send a smaller file."),null;let a=dX(i,s);if(a==="unsupported")return e(`Document handling: unsupported type mime=${i??"(none)"} name=${s??"(none)"} for chat ${o??"(unknown)"}`),await t.reply(`\u274C Unsupported file type. Please send ${cX}.`),null;let c;try{let m=await t.telegram.getFileLink(r.file_id),g=m instanceof URL?m:new URL(String(m));if(g.protocol!=="https:"||g.hostname!=="api.telegram.org"||g.port!==""&&g.port!=="443")return e(`Document handling: unexpected file URL (protocol=${g.protocol} hostname=${g.hostname}) for chat ${o??"(unknown)"}`),await t.reply("\u274C Couldn't download the document. Please try resending."),null;let h=await globalThis.fetch(g.href,{signal:AbortSignal.timeout(15e3),redirect:"error"});if(!h.ok)return e(`Document handling: fetch failed status=${h.status} for chat ${o??"(unknown)"}`),await t.reply("\u274C Couldn't download the document. Please try resending."),null;let y=await uX(h,bR);if(y.status==="too-large")return e(`Document handling: downloaded file (${y.bytesRead} bytes) exceeds limit for chat ${o??"(unknown)"}`),await t.reply("\u274C Document is too large (max 5 MB). Please send a smaller file."),null;if(y.status==="missing-body")return e(`Document handling: fetch response had no body for chat ${o??"(unknown)"}`),await t.reply("\u274C Couldn't download the document. Please try resending."),null;c=y.bytes}catch(m){let g=m instanceof Error?m.message:String(m);return e("Document handling download error:",lX(g)),await t.reply("\u274C Couldn't download the document. Please try resending."),null}let l=[],d=Fr(n.from,t.chat?.type),u=Es({replyToMessage:n.reply_to_message,botId:t.botInfo?.id}),p=As(n),f=u+p+d;if(n.caption!=null){let m=[...n.caption].slice(0,1024).join("");l.push({type:"text",text:`${f}[User caption]: ${m}`})}else f&&l.push({type:"text",text:`${f}(document, no caption)`});if(a==="text"){let m=s??"document",g=c.toString("utf8");l.push({type:"text",text:`\u{1F4CE} Document: ${m}
|
|
1351
1351
|
|
|
1352
|
-
${g}`})}else{let m=c.toString("base64");l.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:m}})}return l}function pX(t){return t.length<3?null:t.length>=4&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":null}async function fX(t,e){let n=t.headers.get("content-length");if(n!=null){let a=Number(n);if(Number.isFinite(a)&&a>e)return{status:"too-large",bytesRead:a}}let r=t.body;if(!r)return{status:"missing-body"};let o=r.getReader(),s=[],i=0;try{for(;;){let{done:a,value:c}=await o.read();if(a)break;if(i+=c.byteLength,i>e)return await o.cancel().catch(()=>{}),{status:"too-large",bytesRead:i};s.push(Buffer.from(c))}}finally{o.releaseLock()}return{status:"ok",bytes:Buffer.concat(s,i)}}function sm(t,e,n,r,o){if(n!==void 0&&n===r)return!0;if(!e||e.length===0)return!1;let s=o?`@${o.toLowerCase()}`:void 0;for(let i of e){if(i.type==="text_mention"){if(i.user?.id===r)return!0;continue}if(i.type==="mention"&&s&&t!==void 0&&t.slice(i.offset,i.offset+i.length).toLowerCase()===s)return!0}return!1}var wl=class t{static MAX_QUEUE_DEPTH=5;sessionManager;messageQueues=new Map;registeredCommandChats;log;bot;claimedChats=new Map;reserveClaim(e){this.claimedChats.set(e,(this.claimedChats.get(e)??0)+1)}releaseClaim(e){let n=(this.claimedChats.get(e)??0)-1;n<=0?this.claimedChats.delete(e):this.claimedChats.set(e,n)}isClaimed(e){return(this.claimedChats.get(e)??0)>0}pendingElicitations=new Map;ledgerOriginatedPendingChats=new Set;tagOnlyChats;constructor(e,n,r,o,s=new Set){this.bot=e,this.sessionManager=n,this.registeredCommandChats=r,this.log=o,this.tagOnlyChats=s}async handlePhoto(e){let n=V(e),r=n?.chatId,o=e.message,s=o?.photo;if(!n||!r||!s?.length){this.log(`Photo handling: missing chatId or photo array for chat ${r??"(unknown)"}`);return}if(this.tagOnlyChats.has(r)){let d=e.botInfo?.id;if(d===void 0){this.log(`[tag-only] Dropping photo in chat ${r}: bot identity unknown (botInfo missing)`);return}if(!sm(o?.caption,o?.caption_entities,o?.reply_to_message?.from?.id,d,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed photo in chat ${r}`);return}}this.log(`\u{1F4F7} Photo from chat ID: ${r}`),await e.react?.("\u{1F440}").catch(()=>{});let i=s[s.length-1];if(!i){this.log(`Photo handling: empty photo array for chat ${r}`);return}let a=5*1024*1024;if(i.file_size!=null&&i.file_size>a){this.log(`Photo handling: oversized file (${i.file_size} bytes) rejected for chat ${r}`),await e.reply("\u274C Image is too large (max 5 MB). Please send a smaller photo.");return}let c=o?.caption,l=!1;try{l=this.isClaimed(j(n)),l||this.reserveClaim(j(n));let d=await this.sessionManager.getSession(n);if(bl(this.bot,r,d,this.registeredCommandChats,this.log).catch(S=>this.log("Failed to register chat commands:",S)),(d.state!=="idle"||l)&&(this.messageQueues.get(j(n))?.length??0)>=t.MAX_QUEUE_DEPTH){await e.reply("\u23F3 Queue full. Please wait for your messages to be processed.");return}let u=await e.telegram.getFileLink(i.file_id),p=u instanceof URL?u:new URL(String(u));if(p.protocol!=="https:"||p.hostname!=="api.telegram.org"||p.port!==""&&p.port!=="443"){this.log(`Photo handling: unexpected file URL (protocol=${p.protocol} hostname=${p.hostname}) rejected for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let f=await globalThis.fetch(p.href,{signal:AbortSignal.timeout(15e3),redirect:"error"});if(!f.ok){this.log(`Photo handling: fetch failed with status ${f.status} for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let m=await fX(f,a);if(m.status==="too-large"){this.log(`Photo handling: downloaded file (${m.bytesRead} bytes) exceeds limit for chat ${r}`),await e.reply("\u274C Image is too large (max 5 MB). Please send a smaller photo.");return}if(m.status==="missing-body"){this.log(`Photo handling: fetch response had no body for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let g=m.bytes,h=["image/jpeg","image/png","image/gif","image/webp"],y=f.headers.get("content-type")??"",w=(y.split(";")[0]?.trim()??"").toLowerCase(),k;if(h.includes(w))k=w;else{let S=pX(g);if(S!==null)this.log(`Photo: sniffed ${S} (Content-Type was "${y}") for chat ${r}`),k=S;else{this.log(`Photo: unrecognised image format for chat ${r} (Content-Type: "${y}")`),await e.reply("\u274C Unsupported image format. Please send a JPEG, PNG, GIF, or WebP.");return}}let v=Fr(o?.from,e.chat?.type),_=Es({replyToMessage:o?.reply_to_message,quote:o?.quote,botId:e.botInfo?.id}),E=As(o??{}),T=_+E+v,I=[];if(c!=null?I.push({type:"text",text:`${T}[User caption]: ${[...c].slice(0,1024).join("")}`}):T&&I.push({type:"text",text:`${T}(image, no caption)`}),await d.waitForInitialization(),d.sessionId===void 0)throw new Error("Telegram session initialized without a session id");if(await LT(I,d.sessionId,[{mediaType:k,bytes:g}]),d.state!=="idle"||l){let S=this.enqueuePhoto(n,e,I);S!==!1&&await e.reply(_o(S));return}await this.processOne(n,e,I)}catch(d){let p=(d instanceof Error?d.message:String(d)).replace(/\/bot[^/]+\//g,"/bot[REDACTED]/");this.log("Photo handling error:",p),fl(d)?await e.reply("\u274C Couldn't reach Telegram to fetch that image. Please try resending."):Mr(d)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):Or(d)?await e.reply("\u274C Couldn't download the image. Please try resending."):await e.reply(Ki())}finally{l||this.releaseClaim(j(n))}}async handleDocument(e){let n=V(e);if(!n)return;let r=n.chatId;if(this.tagOnlyChats.has(r)){let i=e.botInfo?.id;if(i===void 0){this.log(`[tag-only] Dropping document in chat ${r}: bot identity unknown (botInfo missing)`);return}let a=e.message;if(!sm(a?.caption,a?.caption_entities,a?.reply_to_message?.from?.id,i,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed document in chat ${r}`);return}}let o=j(n),s=!1;try{s=this.isClaimed(o),s||this.reserveClaim(o);let i=await this.sessionManager.getSession(n);if(bl(this.bot,n.chatId,i,this.registeredCommandChats,this.log).catch(c=>this.log("Failed to register chat commands:",c)),(i.state!=="idle"||s)&&(this.messageQueues.get(o)?.length??0)>=t.MAX_QUEUE_DEPTH){await e.reply("\u23F3 Queue full. Please wait for your messages to be processed.");return}let a=await wR(e,this.log);if(a===null)return;if(i.state!=="idle"||s){let c=this.enqueueDocument(n,e,a);c!==!1&&await e.reply(_o(c));return}await this.processOne(n,e,a)}catch(i){let a=i instanceof Error?i.message:String(i);this.log("Document handling error:",a.replace(/\/bot[^/]+\//g,"/bot[REDACTED]/")),await e.reply("\u274C An error occurred processing your document. Please try again.")}finally{s||this.releaseClaim(o)}}async handle(e){let n=V(e),r=n?.chatId,o=e.message.text;if(!n||!r||!o)return;let s=j(n);if(this.log(`\u{1F4EC} Message from chat ID: ${r}`),o.startsWith("/"))return;let i=e.message,a=Es({replyToMessage:i.reply_to_message,quote:i.quote,botId:e.botInfo?.id}),c=As(i),l=a+c+Fr(i.from,e.chat?.type)+o,d=Fr(i.from,e.chat?.type)+o,u=this.pendingElicitations.get(s);if(u){if(this.ledgerOriginatedPendingChats.has(s)){this.pendingElicitations.delete(s),this.ledgerOriginatedPendingChats.delete(s),u(d);return}let f=this.sessionManager.getSessionIfExists(n);if(f&&f.state!=="idle"){this.pendingElicitations.delete(s),u(d);return}this.log("[message] dropping stale pendingElicitation for route",s),this.pendingElicitations.delete(s)}if(this.tagOnlyChats.has(r)){let f=e.botInfo?.id;if(f===void 0){this.log(`[tag-only] Dropping message in chat ${r}: bot identity unknown (botInfo missing)`);return}let m=e.message;if(!sm(m.text,m.entities,m.reply_to_message?.from?.id,f,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed message in chat ${r}`);return}}let p=!1;try{await e.react?.("\u{1F440}").catch(()=>{}),p=this.isClaimed(j(n)),p||this.reserveClaim(j(n));let f=await this.sessionManager.getSession(n);bl(this.bot,r,f,this.registeredCommandChats,this.log).catch(g=>this.log("Failed to register chat commands:",g));let m=l;if(f.state!=="idle"||p){let g=this.enqueueMessage(n,e,m);g!==!1&&await e.reply(_o(g));return}await this.processOne(n,e,m)}catch(f){this.log("Message handling error:",f),fl(f)||(Mr(f)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):Or(f)?await e.reply("\u{1F310} Network error. Please check your connection and try again."):await e.reply(Ki()))}finally{p||this.releaseClaim(j(n))}}async processClearDirect(e,n){this.reserveClaim(j(e));try{await this.sessionManager.resetSession(e),this.registeredCommandChats.delete(e.chatId),await n.reply(Ao())}catch(r){this.log("Clear error:",r),await n.reply(B(r))}finally{this.releaseClaim(j(e))}}async processCompactDirect(e,n){this.reserveClaim(j(e));let r=!1;try{let o=await this.sessionManager.getSession(e),s=o.hookRegistry,i=await vs(n,async()=>(s&&await s.dispatch({event:"PreCompact",sessionId:o.sessionId,trigger:"manual"}),o.compact()));if(i.reason==="session-busy"){this.enqueueCompact(e,n),r=!0;return}i.reason==="microcompacted"&&i.microcompaction?await n.reply(Qy(i.microcompaction)):i.compacted?await n.reply(xo({before:i.messagesBefore,after:i.messagesAfter,...i.tokensSavedEstimate!==void 0?{tokensSavedEstimate:i.tokensSavedEstimate}:{}})):await n.reply(Ro(i.reason??"unknown"))}catch(o){o instanceof W?await n.reply(`Compaction skipped: ${Ce(o.reason??"blocked by hook")}`):(this.log("Compact error (queued):",o),await n.reply(B(o)))}finally{r||this.drainQueue(e).catch(o=>this.log("Drain error:",o)),this.releaseClaim(j(e))}}queueFor(e){let n=j(e),r=this.messageQueues.get(n);return r||(r=[],this.messageQueues.set(n,r)),r}enqueueMessage(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"message",ctx:n,text:r}),o.length)}enqueuePhoto(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"photo",ctx:n,content:r}),o.length)}enqueueDocument(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"document",ctx:n,content:r}),o.length)}enqueueClear(e,n){let r=this.queueFor(e);if(r.length>=t.MAX_QUEUE_DEPTH){n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{});return}r.push({type:"clear",ctx:n})}enqueueCompact(e,n){let r=this.queueFor(e);if(r.length>=t.MAX_QUEUE_DEPTH){n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{});return}r.push({type:"compact",ctx:n})}async processOne(e,n,r){this.reserveClaim(j(e));let o=!1;try{let s=await this.sessionManager.getSession(e),i=typeof r=="string"?r:r.map(a=>a.type==="text"?a.text:a.type==="document"?`[document: ${a.title??"file"}]`:"[image]").join(" ");await vs(n,()=>rm(n,s,r,this.log,{cleanFinal:!0,onComplete:(a,c)=>{this.sessionManager.recordTelegramTurn(e,i,a,c)}}))}catch(s){if(this.log("Message handling error:",s),(s?.message??"").includes("session is busy")){let a=typeof r=="string"?this.enqueueMessage(e,n,r):r.some(c=>c.type==="document")?this.enqueueDocument(e,n,r):this.enqueuePhoto(e,n,r);a!==!1&&await n.reply(_o(a)),o=!0;return}s instanceof An?await n.reply(`\u23F1\uFE0F ${s.message}`):fl(s)||(Mr(s)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):Or(s)?await n.reply("\u{1F310} Network error. Please check your connection and try again."):await n.reply(Ki()))}finally{o||this.drainQueue(e).catch(s=>this.log("Drain error:",s)),this.releaseClaim(j(e))}}async drainQueue(e){let n=j(e),r=this.messageQueues.get(n);if(!r?.length)return;let o=r.shift();r.length===0&&this.messageQueues.delete(n),o.type==="message"?await this.processOne(e,o.ctx,o.text):o.type==="photo"||o.type==="document"?await this.processOne(e,o.ctx,o.content):o.type==="compact"?await this.processCompactDirect(e,o.ctx):await this.processClearDirect(e,o.ctx)}};import{Markup as Is}from"telegraf";var xs="afk:e:";var Sl=/^[a-zA-Z0-9_-]{1,48}$/;function kl(t,e){if(!Sl.test(t))throw new Error(`buildElicitationCallback: invalid id ${JSON.stringify(t)}`);if(!Number.isInteger(e)||e<0)throw new Error(`buildElicitationCallback: choiceIndex must be a non-negative integer, got ${e}`);let n=`${xs}${e}:${t}`,r=Buffer.byteLength(n,"utf8");if(r>64)throw new Error(`buildElicitationCallback: payload ${r} bytes exceeds Telegram's 64-byte limit (id=${t})`);return n}function SR(t){if(!t||!t.startsWith(xs)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(xs.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1),s=parseInt(r,10);return!Number.isInteger(s)||s<0||String(s)!==r||!Sl.test(o)?null:{id:o,choiceIndex:s}}var Rs="afk:ec:";function kR(t){if(!Sl.test(t))throw new Error(`buildCustomElicitationCallback: invalid id ${JSON.stringify(t)}`);let e=`${Rs}${t}`,n=Buffer.byteLength(e,"utf8");if(n>64)throw new Error(`buildCustomElicitationCallback: ${n} bytes exceeds 64-byte limit`);return e}function vR(t){if(!t||!t.startsWith(Rs)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(Rs.length);return Sl.test(e)?e:null}import{randomBytes as mX}from"node:crypto";function gX(){return`elic-${mX(8).toString("hex")}`}var TR=-1;function hX(t,e=64){if(Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.from(t,"utf8").subarray(0,e);return new TextDecoder("utf-8",{fatal:!1}).decode(n).replace(/\uFFFD$/,"")}function vl(t,e,n,r){let o=()=>typeof n=="function"?n():typeof n=="number"?{chatId:n}:n,s=r?.ledgerOriginated??!1,i=new Map,a=new RegExp(`^${Pe(xs)}\\d+:.+$`);e.action(a,async l=>{await l.answerCbQuery().catch(()=>{});let d=typeof l.callbackQuery=="object"&&"data"in l.callbackQuery?l.callbackQuery.data:void 0,u=SR(d);if(!u)return;let p=i.get(u.id);p&&l.chat?.id===p.chatId&&p.resolve(u.choiceIndex)});let c=new RegExp(`^${Pe(Rs)}.+$`);return e.action(c,async l=>{await l.answerCbQuery().catch(()=>{});let d=typeof l.callbackQuery=="object"&&"data"in l.callbackQuery?l.callbackQuery.data:void 0,u=vR(d);if(!u)return;let p=i.get(u);p&&l.chat?.id===p.chatId&&p.resolve(TR)}),async(l,d)=>{if(d.signal.aborted)return{action:"decline"};let u=(d.sessionId!==void 0?nl(d.sessionId):void 0)??o(),p=u.chatId,f=j(u),m=en(u);function g(v){t.pendingElicitations.set(f,v),s&&t.ledgerOriginatedPendingChats.add(f)}function h(){t.pendingElicitations.delete(f),s&&t.ledgerOriginatedPendingChats.delete(f)}let y=l.type??"text",w=l.message,k=`\u{1F4AC} <b>Question from agent</b>
|
|
1352
|
+
${g}`})}else{let m=c.toString("base64");l.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:m}})}return l}function pX(t){return t.length<3?null:t.length>=4&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":null}async function fX(t,e){let n=t.headers.get("content-length");if(n!=null){let a=Number(n);if(Number.isFinite(a)&&a>e)return{status:"too-large",bytesRead:a}}let r=t.body;if(!r)return{status:"missing-body"};let o=r.getReader(),s=[],i=0;try{for(;;){let{done:a,value:c}=await o.read();if(a)break;if(i+=c.byteLength,i>e)return await o.cancel().catch(()=>{}),{status:"too-large",bytesRead:i};s.push(Buffer.from(c))}}finally{o.releaseLock()}return{status:"ok",bytes:Buffer.concat(s,i)}}function sm(t,e,n,r,o){if(n!==void 0&&n===r)return!0;if(!e||e.length===0)return!1;let s=o?`@${o.toLowerCase()}`:void 0;for(let i of e){if(i.type==="text_mention"){if(i.user?.id===r)return!0;continue}if(i.type==="mention"&&s&&t!==void 0&&t.slice(i.offset,i.offset+i.length).toLowerCase()===s)return!0}return!1}var wl=class t{static MAX_QUEUE_DEPTH=5;sessionManager;messageQueues=new Map;registeredCommandChats;log;bot;claimedChats=new Map;reserveClaim(e){this.claimedChats.set(e,(this.claimedChats.get(e)??0)+1)}releaseClaim(e){let n=(this.claimedChats.get(e)??0)-1;n<=0?this.claimedChats.delete(e):this.claimedChats.set(e,n)}isClaimed(e){return(this.claimedChats.get(e)??0)>0}pendingElicitations=new Map;ledgerOriginatedPendingChats=new Set;tagOnlyChats;constructor(e,n,r,o,s=new Set){this.bot=e,this.sessionManager=n,this.registeredCommandChats=r,this.log=o,this.tagOnlyChats=s}async handlePhoto(e){let n=V(e),r=n?.chatId,o=e.message,s=o?.photo;if(!n||!r||!s?.length){this.log(`Photo handling: missing chatId or photo array for chat ${r??"(unknown)"}`);return}if(this.tagOnlyChats.has(r)){let d=e.botInfo?.id;if(d===void 0){this.log(`[tag-only] Dropping photo in chat ${r}: bot identity unknown (botInfo missing)`);return}if(!sm(o?.caption,o?.caption_entities,o?.reply_to_message?.from?.id,d,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed photo in chat ${r}`);return}}this.log(`\u{1F4F7} Photo from chat ID: ${r}`),await e.react?.("\u{1F440}").catch(()=>{});let i=s[s.length-1];if(!i){this.log(`Photo handling: empty photo array for chat ${r}`);return}let a=5*1024*1024;if(i.file_size!=null&&i.file_size>a){this.log(`Photo handling: oversized file (${i.file_size} bytes) rejected for chat ${r}`),await e.reply("\u274C Image is too large (max 5 MB). Please send a smaller photo.");return}let c=o?.caption,l=!1;try{l=this.isClaimed(j(n)),l||this.reserveClaim(j(n));let d=await this.sessionManager.getSession(n);if(bl(this.bot,r,d,this.registeredCommandChats,this.log).catch(k=>this.log("Failed to register chat commands:",k)),(d.state!=="idle"||l)&&(this.messageQueues.get(j(n))?.length??0)>=t.MAX_QUEUE_DEPTH){await e.reply("\u23F3 Queue full. Please wait for your messages to be processed.");return}let u=await e.telegram.getFileLink(i.file_id),p=u instanceof URL?u:new URL(String(u));if(p.protocol!=="https:"||p.hostname!=="api.telegram.org"||p.port!==""&&p.port!=="443"){this.log(`Photo handling: unexpected file URL (protocol=${p.protocol} hostname=${p.hostname}) rejected for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let f=await globalThis.fetch(p.href,{signal:AbortSignal.timeout(15e3),redirect:"error"});if(!f.ok){this.log(`Photo handling: fetch failed with status ${f.status} for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let m=await fX(f,a);if(m.status==="too-large"){this.log(`Photo handling: downloaded file (${m.bytesRead} bytes) exceeds limit for chat ${r}`),await e.reply("\u274C Image is too large (max 5 MB). Please send a smaller photo.");return}if(m.status==="missing-body"){this.log(`Photo handling: fetch response had no body for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let g=m.bytes,h=["image/jpeg","image/png","image/gif","image/webp"],y=f.headers.get("content-type")??"",w=(y.split(";")[0]?.trim()??"").toLowerCase(),S;if(h.includes(w))S=w;else{let k=pX(g);if(k!==null)this.log(`Photo: sniffed ${k} (Content-Type was "${y}") for chat ${r}`),S=k;else{this.log(`Photo: unrecognised image format for chat ${r} (Content-Type: "${y}")`),await e.reply("\u274C Unsupported image format. Please send a JPEG, PNG, GIF, or WebP.");return}}let v=Fr(o?.from,e.chat?.type),_=Es({replyToMessage:o?.reply_to_message,quote:o?.quote,botId:e.botInfo?.id}),E=As(o??{}),T=_+E+v,I=[];if(c!=null?I.push({type:"text",text:`${T}[User caption]: ${[...c].slice(0,1024).join("")}`}):T&&I.push({type:"text",text:`${T}(image, no caption)`}),await d.waitForInitialization(),d.sessionId===void 0)throw new Error("Telegram session initialized without a session id");if(await LT(I,d.sessionId,[{mediaType:S,bytes:g}]),d.state!=="idle"||l){let k=this.enqueuePhoto(n,e,I);k!==!1&&await e.reply(_o(k));return}await this.processOne(n,e,I)}catch(d){let p=(d instanceof Error?d.message:String(d)).replace(/\/bot[^/]+\//g,"/bot[REDACTED]/");this.log("Photo handling error:",p),fl(d)?await e.reply("\u274C Couldn't reach Telegram to fetch that image. Please try resending."):Mr(d)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):Or(d)?await e.reply("\u274C Couldn't download the image. Please try resending."):await e.reply(Ki())}finally{l||this.releaseClaim(j(n))}}async handleDocument(e){let n=V(e);if(!n)return;let r=n.chatId;if(this.tagOnlyChats.has(r)){let i=e.botInfo?.id;if(i===void 0){this.log(`[tag-only] Dropping document in chat ${r}: bot identity unknown (botInfo missing)`);return}let a=e.message;if(!sm(a?.caption,a?.caption_entities,a?.reply_to_message?.from?.id,i,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed document in chat ${r}`);return}}let o=j(n),s=!1;try{s=this.isClaimed(o),s||this.reserveClaim(o);let i=await this.sessionManager.getSession(n);if(bl(this.bot,n.chatId,i,this.registeredCommandChats,this.log).catch(c=>this.log("Failed to register chat commands:",c)),(i.state!=="idle"||s)&&(this.messageQueues.get(o)?.length??0)>=t.MAX_QUEUE_DEPTH){await e.reply("\u23F3 Queue full. Please wait for your messages to be processed.");return}let a=await wR(e,this.log);if(a===null)return;if(i.state!=="idle"||s){let c=this.enqueueDocument(n,e,a);c!==!1&&await e.reply(_o(c));return}await this.processOne(n,e,a)}catch(i){let a=i instanceof Error?i.message:String(i);this.log("Document handling error:",a.replace(/\/bot[^/]+\//g,"/bot[REDACTED]/")),await e.reply("\u274C An error occurred processing your document. Please try again.")}finally{s||this.releaseClaim(o)}}async handle(e){let n=V(e),r=n?.chatId,o=e.message.text;if(!n||!r||!o)return;let s=j(n);if(this.log(`\u{1F4EC} Message from chat ID: ${r}`),o.startsWith("/"))return;let i=e.message,a=Es({replyToMessage:i.reply_to_message,quote:i.quote,botId:e.botInfo?.id}),c=As(i),l=a+c+Fr(i.from,e.chat?.type)+o,d=Fr(i.from,e.chat?.type)+o,u=this.pendingElicitations.get(s);if(u){if(this.ledgerOriginatedPendingChats.has(s)){this.pendingElicitations.delete(s),this.ledgerOriginatedPendingChats.delete(s),u(d);return}let f=this.sessionManager.getSessionIfExists(n);if(f&&f.state!=="idle"){this.pendingElicitations.delete(s),u(d);return}this.log("[message] dropping stale pendingElicitation for route",s),this.pendingElicitations.delete(s)}if(this.tagOnlyChats.has(r)){let f=e.botInfo?.id;if(f===void 0){this.log(`[tag-only] Dropping message in chat ${r}: bot identity unknown (botInfo missing)`);return}let m=e.message;if(!sm(m.text,m.entities,m.reply_to_message?.from?.id,f,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed message in chat ${r}`);return}}let p=!1;try{await e.react?.("\u{1F440}").catch(()=>{}),p=this.isClaimed(j(n)),p||this.reserveClaim(j(n));let f=await this.sessionManager.getSession(n);bl(this.bot,r,f,this.registeredCommandChats,this.log).catch(g=>this.log("Failed to register chat commands:",g));let m=l;if(f.state!=="idle"||p){let g=this.enqueueMessage(n,e,m);g!==!1&&await e.reply(_o(g));return}await this.processOne(n,e,m)}catch(f){this.log("Message handling error:",f),fl(f)||(Mr(f)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):Or(f)?await e.reply("\u{1F310} Network error. Please check your connection and try again."):await e.reply(Ki()))}finally{p||this.releaseClaim(j(n))}}async processClearDirect(e,n){this.reserveClaim(j(e));try{await this.sessionManager.resetSession(e),this.registeredCommandChats.delete(e.chatId),await n.reply(Ao())}catch(r){this.log("Clear error:",r),await n.reply(B(r))}finally{this.releaseClaim(j(e))}}async processCompactDirect(e,n){this.reserveClaim(j(e));let r=!1;try{let o=await this.sessionManager.getSession(e),s=o.hookRegistry,i=await vs(n,async()=>(s&&await s.dispatch({event:"PreCompact",sessionId:o.sessionId,trigger:"manual"}),o.compact()));if(i.reason==="session-busy"){this.enqueueCompact(e,n),r=!0;return}i.reason==="microcompacted"&&i.microcompaction?await n.reply(Qy(i.microcompaction)):i.compacted?await n.reply(xo({before:i.messagesBefore,after:i.messagesAfter,...i.tokensSavedEstimate!==void 0?{tokensSavedEstimate:i.tokensSavedEstimate}:{}})):await n.reply(Ro(i.reason??"unknown"))}catch(o){o instanceof W?await n.reply(`Compaction skipped: ${Ce(o.reason??"blocked by hook")}`):(this.log("Compact error (queued):",o),await n.reply(B(o)))}finally{r||this.drainQueue(e).catch(o=>this.log("Drain error:",o)),this.releaseClaim(j(e))}}queueFor(e){let n=j(e),r=this.messageQueues.get(n);return r||(r=[],this.messageQueues.set(n,r)),r}enqueueMessage(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"message",ctx:n,text:r}),o.length)}enqueuePhoto(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"photo",ctx:n,content:r}),o.length)}enqueueDocument(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"document",ctx:n,content:r}),o.length)}enqueueClear(e,n){let r=this.queueFor(e);if(r.length>=t.MAX_QUEUE_DEPTH){n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{});return}r.push({type:"clear",ctx:n})}enqueueCompact(e,n){let r=this.queueFor(e);if(r.length>=t.MAX_QUEUE_DEPTH){n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{});return}r.push({type:"compact",ctx:n})}async processOne(e,n,r){this.reserveClaim(j(e));let o=!1;try{let s=await this.sessionManager.getSession(e),i=typeof r=="string"?r:r.map(a=>a.type==="text"?a.text:a.type==="document"?`[document: ${a.title??"file"}]`:"[image]").join(" ");await vs(n,()=>rm(n,s,r,this.log,{cleanFinal:!0,onComplete:(a,c)=>{this.sessionManager.recordTelegramTurn(e,i,a,c)}}))}catch(s){if(this.log("Message handling error:",s),(s?.message??"").includes("session is busy")){let a=typeof r=="string"?this.enqueueMessage(e,n,r):r.some(c=>c.type==="document")?this.enqueueDocument(e,n,r):this.enqueuePhoto(e,n,r);a!==!1&&await n.reply(_o(a)),o=!0;return}s instanceof An?await n.reply(`\u23F1\uFE0F ${s.message}`):fl(s)||(Mr(s)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):Or(s)?await n.reply("\u{1F310} Network error. Please check your connection and try again."):await n.reply(Ki()))}finally{o||this.drainQueue(e).catch(s=>this.log("Drain error:",s)),this.releaseClaim(j(e))}}async drainQueue(e){let n=j(e),r=this.messageQueues.get(n);if(!r?.length)return;let o=r.shift();r.length===0&&this.messageQueues.delete(n),o.type==="message"?await this.processOne(e,o.ctx,o.text):o.type==="photo"||o.type==="document"?await this.processOne(e,o.ctx,o.content):o.type==="compact"?await this.processCompactDirect(e,o.ctx):await this.processClearDirect(e,o.ctx)}};import{Markup as Is}from"telegraf";var xs="afk:e:";var Sl=/^[a-zA-Z0-9_-]{1,48}$/;function kl(t,e){if(!Sl.test(t))throw new Error(`buildElicitationCallback: invalid id ${JSON.stringify(t)}`);if(!Number.isInteger(e)||e<0)throw new Error(`buildElicitationCallback: choiceIndex must be a non-negative integer, got ${e}`);let n=`${xs}${e}:${t}`,r=Buffer.byteLength(n,"utf8");if(r>64)throw new Error(`buildElicitationCallback: payload ${r} bytes exceeds Telegram's 64-byte limit (id=${t})`);return n}function SR(t){if(!t||!t.startsWith(xs)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(xs.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1),s=parseInt(r,10);return!Number.isInteger(s)||s<0||String(s)!==r||!Sl.test(o)?null:{id:o,choiceIndex:s}}var Rs="afk:ec:";function kR(t){if(!Sl.test(t))throw new Error(`buildCustomElicitationCallback: invalid id ${JSON.stringify(t)}`);let e=`${Rs}${t}`,n=Buffer.byteLength(e,"utf8");if(n>64)throw new Error(`buildCustomElicitationCallback: ${n} bytes exceeds 64-byte limit`);return e}function vR(t){if(!t||!t.startsWith(Rs)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(Rs.length);return Sl.test(e)?e:null}import{randomBytes as mX}from"node:crypto";function gX(){return`elic-${mX(8).toString("hex")}`}var TR=-1;function hX(t,e=64){if(Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.from(t,"utf8").subarray(0,e);return new TextDecoder("utf-8",{fatal:!1}).decode(n).replace(/\uFFFD$/,"")}function vl(t,e,n,r){let o=()=>typeof n=="function"?n():typeof n=="number"?{chatId:n}:n,s=r?.ledgerOriginated??!1,i=new Map,a=new RegExp(`^${Pe(xs)}\\d+:.+$`);e.action(a,async l=>{await l.answerCbQuery().catch(()=>{});let d=typeof l.callbackQuery=="object"&&"data"in l.callbackQuery?l.callbackQuery.data:void 0,u=SR(d);if(!u)return;let p=i.get(u.id);p&&l.chat?.id===p.chatId&&p.resolve(u.choiceIndex)});let c=new RegExp(`^${Pe(Rs)}.+$`);return e.action(c,async l=>{await l.answerCbQuery().catch(()=>{});let d=typeof l.callbackQuery=="object"&&"data"in l.callbackQuery?l.callbackQuery.data:void 0,u=vR(d);if(!u)return;let p=i.get(u);p&&l.chat?.id===p.chatId&&p.resolve(TR)}),async(l,d)=>{if(d.signal.aborted)return{action:"decline"};let u=(d.sessionId!==void 0?nl(d.sessionId):void 0)??o(),p=u.chatId,f=j(u),m=en(u);function g(v){t.pendingElicitations.set(f,v),s&&t.ledgerOriginatedPendingChats.add(f)}function h(){t.pendingElicitations.delete(f),s&&t.ledgerOriginatedPendingChats.delete(f)}let y=l.type??"text",w=l.message,S=`\u{1F4AC} <b>Question from agent</b>
|
|
1353
1353
|
|
|
1354
|
-
${Ce(w)}`;if(l.context&&(
|
|
1354
|
+
${Ce(w)}`;if(l.context&&(S=`\u{1F4AC} <b>Question from agent</b>
|
|
1355
1355
|
|
|
1356
1356
|
<i>${Ce(l.context)}</i>
|
|
1357
1357
|
|
|
1358
|
-
${Ce(w)}`),y==="confirm"||y==="choice"){let v=gX(),_;return y==="confirm"?_=[[Is.button.callback("\u2705 Yes",kl(v,1)),Is.button.callback("\u274C No",kl(v,0))]]:(_=(l.choices??[]).slice(0,20).map((I,
|
|
1359
|
-
`);
|
|
1358
|
+
${Ce(w)}`),y==="confirm"||y==="choice"){let v=gX(),_;return y==="confirm"?_=[[Is.button.callback("\u2705 Yes",kl(v,1)),Is.button.callback("\u274C No",kl(v,0))]]:(_=(l.choices??[]).slice(0,20).map((I,k)=>[Is.button.callback(hX(I),kl(v,k))]),l.allowCustom&&_.push([Is.button.callback("\u270D\uFE0F Type a custom answer",kR(v))])),new Promise(E=>{let T=!1,I=!1,k=()=>{T||(T=!0,i.delete(v),I&&h(),E({action:"decline"}))};d.signal.addEventListener("abort",k,{once:!0}),i.set(v,{chatId:p,resolve:A=>{if(!T){if(T=!0,i.delete(v),d.signal.removeEventListener("abort",k),A===TR){if(T=!1,I=!0,e.telegram.sendMessage(p,"\u270D\uFE0F Please type your custom answer:",m).catch(()=>{}),d.signal.aborted){E({action:"decline"});return}g(R=>{if(T)return;T=!0,d.signal.removeEventListener("abort",k);let D=R.trim();if(D===":cancel"){E({action:"cancel"});return}E({action:"accept",content:{value:null,custom_value:D}})}),d.signal.addEventListener("abort",k,{once:!0});return}if(y==="confirm")E({action:"accept",content:{value:A===1}});else{let D=(l.choices??[])[A];E(D===void 0?{action:"decline"}:{action:"accept",content:{value:D}})}}}}),e.telegram.sendMessage(p,S,{parse_mode:"HTML",...m,reply_markup:Is.inlineKeyboard(_).reply_markup}).catch(()=>{T||(T=!0,i.delete(v),d.signal.removeEventListener("abort",k),E({action:"decline"}))})})}return new Promise(v=>{let _=!1,E=()=>{_||(_=!0,t.pendingElicitations.has(f)&&console.warn("[elicitation-handler] abort: cleaning up stale pendingElicitation for route",f),h(),v({action:"decline"}))};d.signal.addEventListener("abort",E,{once:!0});let T=!0;function I(A){if(_)return;_=!0,d.signal.removeEventListener("abort",E);let R=A.trim();if(R===":cancel"){v({action:"cancel"});return}if(R===""&&l.allowSkip){v({action:"skip"});return}if(y==="number"){if(R===""&&!l.allowSkip){if(_=!1,T=!1,e.telegram.sendMessage(p,"\u274C Please enter a number.",m).catch(()=>{}),d.signal.aborted)return;g(I),d.signal.addEventListener("abort",E,{once:!0});return}let D=Number(R);if(!isFinite(D)){if(_=!1,T=!1,e.telegram.sendMessage(p,"\u274C Please enter a valid number.",m).catch(()=>{}),d.signal.aborted)return;g(I),d.signal.addEventListener("abort",E,{once:!0});return}if(l.min!==void 0&&D<l.min){if(_=!1,T=!1,e.telegram.sendMessage(p,`\u274C Value must be \u2265 ${l.min}.`,m).catch(()=>{}),d.signal.aborted)return;g(I),d.signal.addEventListener("abort",E,{once:!0});return}if(l.max!==void 0&&D>l.max){if(_=!1,T=!1,e.telegram.sendMessage(p,`\u274C Value must be \u2264 ${l.max}.`,m).catch(()=>{}),d.signal.aborted)return;g(I),d.signal.addEventListener("abort",E,{once:!0});return}v({action:"accept",content:{value:D}});return}if(y==="multi_choice"){let D=l.choices??[];if(l.allowCustom){let N=R.split(",")[0]?.trim()??"",O=parseInt(N,10);if(!(Number.isInteger(O)&&String(O)===N&&O>=1&&O<=D.length)&&R!==""&&R!==":cancel"){v({action:"accept",content:{value:null,custom_value:R}});return}}let G=R.split(",").map(N=>N.trim()),F=[];for(let N of G){let O=parseInt(N,10);if(!Number.isInteger(O)||String(O)!==N||O<1||O>D.length){if(_=!1,T=!1,e.telegram.sendMessage(p,`\u274C Invalid selection. Enter comma-separated numbers between 1 and ${D.length}.`,m).catch(()=>{}),d.signal.aborted)return;g(I),d.signal.addEventListener("abort",E,{once:!0});return}F.push(D[O-1])}v({action:"accept",content:{value:F}});return}if(R===""&&!l.allowSkip){if(_=!1,T=!1,e.telegram.sendMessage(p,"\u274C Please enter a response (or type :cancel to skip).",m).catch(()=>{}),d.signal.aborted)return;g(I),d.signal.addEventListener("abort",E,{once:!0});return}v({action:"accept",content:{value:R}})}g(I);let k=S;if(y==="multi_choice"){let R=(l.choices??[]).map((D,G)=>`${G+1}. ${Ce(D)}`).join(`
|
|
1359
|
+
`);k+=`
|
|
1360
1360
|
|
|
1361
1361
|
${R}
|
|
1362
1362
|
|
|
1363
|
-
Enter comma-separated numbers (e.g. 1,3)`,l.allowCustom&&(
|
|
1363
|
+
Enter comma-separated numbers (e.g. 1,3)`,l.allowCustom&&(k+=`
|
|
1364
1364
|
|
|
1365
|
-
<i>Or type any free-form text as a custom answer.</i>`)}else if(y==="number"){let A=l.min!==void 0&&l.max!==void 0?` (${l.min}\u2013${l.max})`:l.min!==void 0?` (\u2265${l.min})`:l.max!==void 0?` (\u2264${l.max})`:"";
|
|
1365
|
+
<i>Or type any free-form text as a custom answer.</i>`)}else if(y==="number"){let A=l.min!==void 0&&l.max!==void 0?` (${l.min}\u2013${l.max})`:l.min!==void 0?` (\u2265${l.min})`:l.max!==void 0?` (\u2264${l.max})`:"";k+=`
|
|
1366
1366
|
|
|
1367
|
-
Enter a number${A}`}T&&(l.allowSkip?
|
|
1367
|
+
Enter a number${A}`}T&&(l.allowSkip?k+=`
|
|
1368
1368
|
|
|
1369
|
-
<i>Enter empty to skip, or :cancel to cancel.</i>`:
|
|
1369
|
+
<i>Enter empty to skip, or :cancel to cancel.</i>`:k+=`
|
|
1370
1370
|
|
|
1371
|
-
<i>Type :cancel to cancel.</i>`),e.telegram.sendMessage(p,
|
|
1371
|
+
<i>Type :cancel to cancel.</i>`),e.telegram.sendMessage(p,k,{parse_mode:"HTML",...m}).catch(()=>{_||(_=!0,d.signal.removeEventListener("abort",E),console.warn("[elicitation-handler] sendMessage failed; declining elicitation for route",f),h(),v({action:"decline"}))})})}}M();var _R="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ER(t=Date.now()){let e=t,n=new Array(10).fill("0");for(let o=9;o>=0;o--)n[o]=_R[e%32],e=Math.floor(e/32);let r=new Array(16).fill("0");for(let o=0;o<16;o++)r[o]=_R[Math.floor(Math.random()*32)];return n.join("")+r.join("")}var Ps="afk:pa:",yX=64,Cs=new Map;function Tl(t,e,n=()=>{},r){let o=t;if(!o._elicitationRegistered){let s=new RegExp(`^${Pe(Ps)}`);t.action(s,async i=>bX(i,n)),o._elicitationRegistered=!0}return async(s,i)=>{if(i.signal.aborted)return{action:"decline"};let a=i.sessionId!==void 0?nl(i.sessionId):void 0;return new Promise(c=>{let l=ER(),d=wX(s);Cs.set(l,{resolve:c,enumValues:d});let u=SX(s),p=kX(l,d),f=Array.from(e).map(async m=>{try{let g=a??r?.(m);await t.telegram.sendMessage(m,u,{reply_markup:p,...g!==void 0?en(g):{}})}catch(g){n("[elicitation] sendMessage failed:",g)}});Promise.all(f),i.signal.addEventListener("abort",()=>{let m=Cs.get(l);m&&(Cs.delete(l),m.resolve({action:"decline"}))},{once:!0})})}}async function bX(t,e){let n=t.callbackQuery?.data;if(typeof n!="string"||!n.startsWith(Ps)){await t.answerCbQuery("Unknown callback").catch(()=>{});return}let r=n.slice(Ps.length),o=r.indexOf(":");if(o<=0||o===r.length-1){await t.answerCbQuery("Malformed callback").catch(()=>{});return}let s=r.slice(0,o),i=r.slice(o+1),a=Cs.get(s);if(!a){await t.answerCbQuery("This prompt is no longer active.").catch(()=>{});return}if(!a.enumValues.includes(i)){e("[elicitation] callback choice not in enum:",i,a.enumValues),await t.answerCbQuery("Unknown choice").catch(()=>{});return}Cs.delete(s),a.resolve({action:"accept",content:{choice:i}}),await t.answerCbQuery(`Recorded: ${i}`).catch(c=>{e("[elicitation] answerCbQuery failed:",c)})}function wX(t){if(t.mode!=="form")return["accept","decline"];let e=t.requestedSchema;if(typeof e!="object"||e===null)return["accept","decline"];let n=e.properties;if(typeof n!="object"||n===null)return["accept","decline"];let r=Object.keys(n)[0];if(r===void 0)return["accept","decline"];let o=n[r];if(typeof o!="object"||o===null)return["accept","decline"];let s=o.enum;return Array.isArray(s)?s.map(String):["accept","decline"]}function SX(t){let e=[];t.title&&e.push(t.title),e.push(t.message);let n=e.join(`
|
|
1372
1372
|
|
|
1373
1373
|
`);return n.length>4e3?n.slice(0,3997)+"...":n}function kX(t,e){let n=Ps.length+t.length+1,r=yX-n,o=e.map(s=>{let i=s.length<=r?s:s.slice(0,r);return{text:vX(i),callback_data:`${Ps}${t}:${i}`}});return o.length===4?{inline_keyboard:[[o[0],o[1]],[o[2],o[3]]]}:{inline_keyboard:o.map(s=>[s])}}function vX(t){switch(t){case"once":return"\u2705 Once";case"session":return"\u{1F501} Session";case"persist":return"\u{1F4BE} Always";case"deny":return"\u274C Deny";case"accept":return"\u2705 Accept";case"decline":return"\u274C Decline";default:return t.charAt(0).toUpperCase()+t.slice(1)}}function _l(t,e){return(n,r)=>n.type!==void 0?t(n,r):e(n,r)}import*as El from"node:fs";M();import{createHmac as TX,randomBytes as _X,timingSafeEqual as eRe}from"node:crypto";var AR="\0";function EX(t){return JSON.stringify(im(t))}function im(t){if(Array.isArray(t))return t.map(im);if(t!==null&&typeof t=="object"){let e=t,n={};for(let r of Object.keys(e).sort())n[r]=im(e[r]);return n}return t}function Al(t){let e;try{e=Pm(t)}catch{return null}try{let n=El.readFileSync(e,"utf8").trim();return n.length>0?n:null}catch{return null}}function xR(t,e){return TX("sha256",t).update(e).digest("hex")}function AX(t,e,n){return["elicitation_response",t,e,EX(n)].join(AR)}function RR(t,e,n,r){return xR(t,AX(e,n,r))}function xX(t,e){return["abort_request",t,e].join(AR)}function IR(t,e,n){return xR(t,xX(e,n))}function CR(){return _X(8).toString("hex")}var RX=1500,PR=700,am=160,IX=15*6e4,CX=4;function Ms(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e)}\u2026`:n}function PX(t){switch(t.kind){case"meta":return`\u{1F4E1} Watching session ${t.sessionId}
|
|
1374
1374
|
model: ${t.model}${t.cwd?`
|