agent-afk 5.155.0 → 5.156.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs
CHANGED
|
@@ -116,7 +116,7 @@ ${n}`:n}}}return{...e,systemPrompt:n}}function sce(e){return e.length===0?e:(e[0
|
|
|
116
116
|
\u2026 [${n.length-s.length-a.length} bytes truncated: showing first ${s.length} + last ${a.length} of ${n.length}] \u2026
|
|
117
117
|
|
|
118
118
|
`;return s.toString("utf8")+c+a.toString("utf8")}function Ns(e){return Buffer.byteLength(e,"utf8")<=1e5?{content:e,truncated:!1}:{content:Ls(e,1e5),truncated:!0}}var iue,yN,ui=y(()=>{"use strict";iue=160;yN=`
|
|
119
|
-
[output truncated \u2014 command exceeded the 8000000-byte output cap and was terminated]`});var bN,SN,wN=y(()=>{"use strict";bN={name:"read_witness",category:"read",concurrencySafe:!0,description:"Read and filter events from a session's witness trace (the durable record of everything the agent did). Returns structured trace events in chronological order. Use to inspect tool calls, errors, subagent lifecycles, costs, and session phases from a specific session. Defaults to the most recent session.",input_schema:{type:"object",properties:{session:{type:"string",description:'Session ID to read, or "latest" (default). Use search_witness to find session IDs.'},kinds:{type:"array",items:{type:"string"},description:"Filter by event kind(s). Values: tool_call, subagent_lifecycle, session_phase, closure, abort, budget, hook_decision, browser_event, claim, compaction, background_agent, queued_user_message, session_sealed."},tool_name:{type:"string",description:'Filter tool_call events to only this tool name (e.g. "bash", "edit_file").'},errors_only:{type:"boolean",description:"When true, show only error events: failed tool calls and failed subagents. Default: false."},limit:{type:"number",description:"Max events to return (default: 50, max: 200). Returns the N most recent matching events."}},required:[]}},SN={name:"search_witness",category:"read",concurrencySafe:!0,description:"Search across multiple sessions' witness traces for a text pattern. Returns matching trace events grouped by session. Use to find patterns across sessions \u2014 recurring errors, specific tool usage, cost spikes, or any text that appears in trace event payloads. Scans the N most recent sessions (default 20). Results are capped at 200 total matches across all scanned sessions.",input_schema:{type:"object",properties:{query:{type:"string",description:"Text pattern to search for (case-insensitive substring match)."},sessions:{type:"number",description:'Number of recent sessions to scan (default: 20, max: 100). The result includes sessionsAvailable (sessions in this window before any since filter) and sessionsSearched (sessions actually read after the since filter) so you can distinguish "few sessions exist" from "the date filter excluded most of them".'},kinds:{type:"array",items:{type:"string"},description:"Filter results to specific event kinds (same values as read_witness)."},since:{type:"string",description:"ISO date string \u2014 only search sessions modified after this date."}},required:["query"]}}});var hx,vN=y(()=>{"use strict";hx={name:"cancel_background_job",category:"subagent",concurrencySafe:!1,description:'Cancel a running background subagent job that this model created with the agent tool in mode="background". Use when new context makes an in-flight model-dispatched job obsolete or harmful to continue. Do not use for jobs backgrounded by the user with Ctrl+B: those are user-owned and this tool will refuse; ask the user to run /bgsub:cancel instead. A concrete reason is required and is recorded in the witness trace. Completed, failed, or already-cancelled jobs return an informative non-error result.',input_schema:{type:"object",properties:{jobId:{type:"string",description:"The background job id returned by an earlier agent call in background mode."},reason:{type:"string",description:"Required explanation of why the running job is now obsolete or should stop."}},required:["jobId","reason"]}}});var kN=y(()=>{"use strict";vN()});var sue,aue,lue,cue,uue,due,pue,mue,fue,gue,vn,Bs,Us,hue,yue,bue,Sue,wue,vue,kue,Tue,Eue,Rue,xue,Aue,Cue,_ue,$r,sn,DJe,kn=y(()=>{"use strict";wN();kN();sue={name:"bash",category:"shell",concurrencySafe:!1,description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run through /bin/sh (Node spawn with shell:true) \u2014 NOT bash and NOT your $SHELL; /bin/sh is bash-in-POSIX-mode on macOS but dash on Debian/Ubuntu. Only process substitution <(...) reliably fails closed (exit 2, nothing runs). Other bashisms are nonportable and are NOT dependable refusals: [[ ]] runs on macOS but is a not-found command on dash while the rest of the line still executes; {a,b} expands on macOS but passes through literally on dash (silently wrong argument); arrays run on macOS but are a syntax error on dash. So never assume a bashism-containing command was side-effect-free \u2014 prefer a temp file or a POSIX equivalent. Long-running commands should use timeout_ms. Output is capped to a ~100KB head+tail view (the start and end are kept, the middle elided with a notice), so the command still runs to completion and you keep the real exit code and the tail (test/build summaries, final errors). For the full body of a verbose command, filter it (`| tail -n`, `--quiet`, narrower flags) or redirect to a file and read slices. Commands emitting extreme output (>8MB) are terminated. For reading or writing files \u2014 especially anything sensitive \u2014 prefer the typed file tools (read_file, write_file, edit_file): they support per-call user approval, and interpreter one-liners (python -c, node -e, sh -c, ...) that reference credential paths (SSH keys, cloud credentials, /etc/shadow) are blocked by the path-approval policy on interactive surfaces.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds (default 120000, max 600000). The command is killed if it exceeds this duration."}},required:["command"]}},aue={name:"read_file",category:"read",concurrencySafe:!0,description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected \u2014 use extract_document for .docx, .pdf, .xlsx, .pptx, and .zip files. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},lue={name:"extract_document",category:"read",concurrencySafe:!0,description:'Extract text from binary document formats that read_file rejects. Supports .docx, .xlsx, .pptx (Office/OOXML \u2014 zero external dependencies), .pdf (requires pdftotext from poppler-utils; emits install instructions if missing), and .zip (lists members and extracts text-file contents). Use this when read_file reports "File appears to be binary" on a document you need to read. Returns plain text extracted from the document. Security: 4 MB decompression cap, zip-slip path containment, no shell execution. Output is capped at 512 KB of text; larger documents are truncated with a marker.',input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the document file to extract text from."}},required:["file_path"]}},cue={name:"write_file",category:"write",concurrencySafe:!1,description:"Write content to a file, creating it if it does not exist or overwriting if it does. Parent directories are created automatically. Prefer edit_file for modifying existing files \u2014 use write_file only for new files or complete rewrites.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"The full content to write to the file."}},required:["file_path","content"]}},uue={name:"edit_file",category:"write",concurrencySafe:!1,description:"Perform an exact string replacement in a file. Finds old_string and replaces it with new_string. The edit fails if old_string is not found or matches multiple locations (unless replace_all is true). Always use read_file first to verify the exact content before editing.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit."},old_string:{type:"string",description:"The exact string to find and replace. Must match file content exactly."},new_string:{type:"string",description:"The replacement string."},replace_all:{type:"boolean",description:"If true, replace all occurrences. If false (default), fail when multiple matches exist."}},required:["file_path","old_string","new_string"]}},due={name:"glob",category:"read",concurrencySafe:!0,description:'Find files matching a glob pattern. Returns matching file paths, capped at 500 results. Use for discovering files before reading them. Patterns follow standard glob syntax (e.g., "src/**/*.ts", "*.json"). Skips node_modules/.git/.hg/.svn by default; name such a directory literally in the pattern (e.g. "node_modules/**/*.js") to search it.',input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "src/**/*.ts").'},path:{type:"string",description:"Base directory to search from. Defaults to the current working directory."}},required:["pattern"]}},pue={name:"grep",category:"read",concurrencySafe:!0,description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Runs on ripgrep: `|` `+` `?` `(` `)` `{` `}` are regex metacharacters by default (e.g. `foo|bar` alternates, matching either branch) \u2014 escape with a backslash for the literal character. Honors .gitignore (so build/dependency dirs like node_modules are skipped) but DOES search hidden files/dirs like .github and .env; the .git directory and binary files are skipped. Output is capped to a ~100KB head+tail view; if a search is truncated, narrow it (a more specific pattern, an `include` glob, or a subdirectory `path`) rather than re-running the same broad query. Use for finding symbols, strings, or patterns across the codebase.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Search pattern (ripgrep regex syntax). `|` `+` `?` `(` `)` `{` `}` are metacharacters \u2014 e.g. `foo|bar` matches either "foo" or "bar". Escape with a backslash (e.g. `\\|`) to match the literal character.'},path:{type:"string",description:"Directory or file to search. Defaults to current working directory."},include:{type:"string",description:'File glob to restrict search (e.g., "*.ts"). Passed as -g to ripgrep.'}},required:["pattern"]}},mue={name:"list_directory",category:"read",concurrencySafe:!0,description:"List the contents of a directory. Returns file and subdirectory names with type annotations (directories end with /). Use for exploring project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the directory to list."}},required:["path"]}},fue={name:"send_telegram",category:"web",concurrencySafe:!1,riskClass:"caution",description:'Send a Telegram message to the operator. Use to surface terminal-state notifications, blocking questions, or important status updates when the user is away from keyboard (AFK). The message is delivered through the same Telegram bot the operator uses to drive this session. By default the message goes to your primary chat (the first private chat in `AFK_TELEGRAM_ALLOWED_CHAT_IDS`, or `AFK_TELEGRAM_PRIMARY_CHAT_ID` if set); set `telegram.notify` in afk.config.json to broadcast to all allowed chats or target a custom set.\n\nPlain text only \u2014 Telegram\'s 4096-character limit per message is enforced. Returns an error if Telegram is not configured (missing `TELEGRAM_BOT_TOKEN` or empty allowlist) so the tool is safe to attempt unconditionally.\n\nUse sparingly: this is a real push notification to a human. Reserve for terminal states (Done/Blocked/Asking) and material progress, not running commentary. When running inside the Telegram bot, prefer replying normally \u2014 your response already reaches the operator through the bot. Use this tool only from CLI or daemon sessions.\n\nOptionally set `chat` to route to a SPECIFIC chat instead of the default primary target: pass a numeric chat id (e.g. -1001234567890 for a group) or a chat alias name defined in afk.config.json `telegram.chatAliases` (e.g. "ops"). An explicitly-targeted chat must be in the inbound allowlist (AFK_TELEGRAM_ALLOWED_CHAT_IDS) \u2014 a non-allowlisted target is rejected (fail-closed). Omit `chat` for the default behavior (unchanged).\n\nFor supergroups with topics enabled, set `thread_id` alongside `chat` to send to a specific topic thread.',input_schema:{type:"object",properties:{message:{type:"string",description:"Plain-text message body to send to the operator. Max 4096 characters (Telegram API limit). Must be non-empty."},chat:{type:["number","string"],description:"Optional. Target a specific chat instead of the default primary target. A number (or numeric string) is a raw Telegram chat id; a non-numeric string is looked up as a name in afk.config.json `telegram.chatAliases`. The resolved chat must be allowlisted (AFK_TELEGRAM_ALLOWED_CHAT_IDS) or the send is rejected. Omit to send to the configured default (primary DM chat / notify targets)."},thread_id:{type:"number",description:"Optional. Telegram message_thread_id for sending to a specific topic in a supergroup with topics enabled. Pass the numeric thread/topic ID. Ignored when the target chat is not a supergroup with topics. Requires `chat` to be set explicitly (thread targeting without a chat target is ambiguous)."}},required:["message"]}},gue={name:"web_scrape",category:"web",concurrencySafe:!0,description:'Scrape a web page or run a web search and return text content suitable for reasoning over. Three modes:\n\n- `markdown` (default): fetches the URL and extracts the main content as clean markdown (Readability + Turndown). Handles JS-rendered pages: if the plain fetch yields thin content, it escalates to a headless-browser render and re-extracts. Use this for articles, docs, blog posts, and most "I want to read this page" cases. No API key required (the render fallback needs the Playwright chromium binary; if it is absent the error names the exact install command for this installation).\n- `raw`: GETs the URL directly and returns the response body as decoded text, with no markdown transformation. Use for JSON APIs, robots.txt, RSS, or plain-text endpoints. Not byte-preserving \u2014 binary payloads are decoded as text, so do not rely on this for exact bytes. No API key required.\n- `search`: runs a web search and returns ranked markdown results. Use when you need to FIND a URL, not read one. Provide `query` instead of `url`. Requires `EXA_API_KEY` (free tier at https://exa.ai); the handler returns a clear error if it is unset.\n\nOutputs are capped at `max_bytes` UTF-8 bytes (default 100KB, ceiling 1MB); content over the cap is reduced to head+tail with a `\u2026 [N bytes truncated: \u2026] \u2026` marker so both ends survive. The request is aborted after `timeout_ms` (default 30000, ceiling 120000).',input_schema:{type:"object",properties:{mode:{type:"string",enum:["markdown","raw","search"],description:'Fetch mode. Defaults to "markdown".'},url:{type:"string",description:"Absolute http(s) URL. Required for markdown and raw modes. Ignored in search mode."},query:{type:"string",description:"Search query string. Required for search mode. Ignored otherwise."},timeout_ms:{type:"number",description:"Request timeout in milliseconds (default 30000, clamped to 120000)."},max_bytes:{type:"number",description:"Maximum UTF-8 bytes returned. Content beyond this is reduced to head+tail with a truncation marker (both ends preserved). Default 100000, clamped to 1000000."}},required:[]}},vn={name:"agent",category:"subagent",concurrencySafe:!0,description:`Dispatch an independent subagent with its own context window and tool access. Use for tasks that protect the main session's context: codebase exploration, multi-file inspection, repo search, verification, debugging, failing-test investigation, PR review, parallel hypothesis testing, independent re-derivation of a claim, audit work, stale-path detection, feature-wiring checks, and any research-shaped investigation.
|
|
119
|
+
[output truncated \u2014 command exceeded the 8000000-byte output cap and was terminated]`});var bN,SN,wN=y(()=>{"use strict";bN={name:"read_witness",category:"read",concurrencySafe:!0,description:"Read and filter events from a session's witness trace (the durable record of everything the agent did). Returns structured trace events in chronological order. Use to inspect tool calls, errors, subagent lifecycles, costs, and session phases from a specific session. Defaults to the most recent session.",input_schema:{type:"object",properties:{session:{type:"string",description:'Session ID to read, or "latest" (default). Use search_witness to find session IDs.'},kinds:{type:"array",items:{type:"string"},description:"Filter by event kind(s). Values: tool_call, subagent_lifecycle, session_phase, closure, abort, budget, hook_decision, browser_event, claim, compaction, background_agent, queued_user_message, session_sealed."},tool_name:{type:"string",description:'Filter tool_call events to only this tool name (e.g. "bash", "edit_file").'},errors_only:{type:"boolean",description:"When true, show only error events: failed tool calls and failed subagents. Default: false."},limit:{type:"number",description:"Max events to return (default: 50, max: 200). Returns the N most recent matching events."}},required:[]}},SN={name:"search_witness",category:"read",concurrencySafe:!0,description:"Search across multiple sessions' witness traces for a text pattern. Returns matching trace events grouped by session. Use to find patterns across sessions \u2014 recurring errors, specific tool usage, cost spikes, or any text that appears in trace event payloads. Scans the N most recent sessions (default 20). Results are capped at 200 total matches across all scanned sessions.",input_schema:{type:"object",properties:{query:{type:"string",description:"Text pattern to search for (case-insensitive substring match)."},sessions:{type:"number",description:'Number of recent sessions to scan (default: 20, max: 100). The result includes sessionsAvailable (sessions in this window before any since filter) and sessionsSearched (sessions actually read after the since filter) so you can distinguish "few sessions exist" from "the date filter excluded most of them".'},kinds:{type:"array",items:{type:"string"},description:"Filter results to specific event kinds (same values as read_witness)."},since:{type:"string",description:"ISO date string \u2014 only search sessions modified after this date."},tool_name:{type:"string",description:'Filter tool_call events to only this tool name (e.g. "bash", "edit_file"). Non-tool_call events are excluded when set.'}},required:["query"]}}});var hx,vN=y(()=>{"use strict";hx={name:"cancel_background_job",category:"subagent",concurrencySafe:!1,description:'Cancel a running background subagent job that this model created with the agent tool in mode="background". Use when new context makes an in-flight model-dispatched job obsolete or harmful to continue. Do not use for jobs backgrounded by the user with Ctrl+B: those are user-owned and this tool will refuse; ask the user to run /bgsub:cancel instead. A concrete reason is required and is recorded in the witness trace. Completed, failed, or already-cancelled jobs return an informative non-error result.',input_schema:{type:"object",properties:{jobId:{type:"string",description:"The background job id returned by an earlier agent call in background mode."},reason:{type:"string",description:"Required explanation of why the running job is now obsolete or should stop."}},required:["jobId","reason"]}}});var kN=y(()=>{"use strict";vN()});var sue,aue,lue,cue,uue,due,pue,mue,fue,gue,vn,Bs,Us,hue,yue,bue,Sue,wue,vue,kue,Tue,Eue,Rue,xue,Aue,Cue,_ue,$r,sn,DJe,kn=y(()=>{"use strict";wN();kN();sue={name:"bash",category:"shell",concurrencySafe:!1,description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run through /bin/sh (Node spawn with shell:true) \u2014 NOT bash and NOT your $SHELL; /bin/sh is bash-in-POSIX-mode on macOS but dash on Debian/Ubuntu. Only process substitution <(...) reliably fails closed (exit 2, nothing runs). Other bashisms are nonportable and are NOT dependable refusals: [[ ]] runs on macOS but is a not-found command on dash while the rest of the line still executes; {a,b} expands on macOS but passes through literally on dash (silently wrong argument); arrays run on macOS but are a syntax error on dash. So never assume a bashism-containing command was side-effect-free \u2014 prefer a temp file or a POSIX equivalent. Long-running commands should use timeout_ms. Output is capped to a ~100KB head+tail view (the start and end are kept, the middle elided with a notice), so the command still runs to completion and you keep the real exit code and the tail (test/build summaries, final errors). For the full body of a verbose command, filter it (`| tail -n`, `--quiet`, narrower flags) or redirect to a file and read slices. Commands emitting extreme output (>8MB) are terminated. For reading or writing files \u2014 especially anything sensitive \u2014 prefer the typed file tools (read_file, write_file, edit_file): they support per-call user approval, and interpreter one-liners (python -c, node -e, sh -c, ...) that reference credential paths (SSH keys, cloud credentials, /etc/shadow) are blocked by the path-approval policy on interactive surfaces.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds (default 120000, max 600000). The command is killed if it exceeds this duration."}},required:["command"]}},aue={name:"read_file",category:"read",concurrencySafe:!0,description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected \u2014 use extract_document for .docx, .pdf, .xlsx, .pptx, and .zip files. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},lue={name:"extract_document",category:"read",concurrencySafe:!0,description:'Extract text from binary document formats that read_file rejects. Supports .docx, .xlsx, .pptx (Office/OOXML \u2014 zero external dependencies), .pdf (requires pdftotext from poppler-utils; emits install instructions if missing), and .zip (lists members and extracts text-file contents). Use this when read_file reports "File appears to be binary" on a document you need to read. Returns plain text extracted from the document. Security: 4 MB decompression cap, zip-slip path containment, no shell execution. Output is capped at 512 KB of text; larger documents are truncated with a marker.',input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the document file to extract text from."}},required:["file_path"]}},cue={name:"write_file",category:"write",concurrencySafe:!1,description:"Write content to a file, creating it if it does not exist or overwriting if it does. Parent directories are created automatically. Prefer edit_file for modifying existing files \u2014 use write_file only for new files or complete rewrites.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"The full content to write to the file."}},required:["file_path","content"]}},uue={name:"edit_file",category:"write",concurrencySafe:!1,description:"Perform an exact string replacement in a file. Finds old_string and replaces it with new_string. The edit fails if old_string is not found or matches multiple locations (unless replace_all is true). Always use read_file first to verify the exact content before editing.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit."},old_string:{type:"string",description:"The exact string to find and replace. Must match file content exactly."},new_string:{type:"string",description:"The replacement string."},replace_all:{type:"boolean",description:"If true, replace all occurrences. If false (default), fail when multiple matches exist."}},required:["file_path","old_string","new_string"]}},due={name:"glob",category:"read",concurrencySafe:!0,description:'Find files matching a glob pattern. Returns matching file paths, capped at 500 results. Use for discovering files before reading them. Patterns follow standard glob syntax (e.g., "src/**/*.ts", "*.json"). Skips node_modules/.git/.hg/.svn by default; name such a directory literally in the pattern (e.g. "node_modules/**/*.js") to search it.',input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "src/**/*.ts").'},path:{type:"string",description:"Base directory to search from. Defaults to the current working directory."}},required:["pattern"]}},pue={name:"grep",category:"read",concurrencySafe:!0,description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Runs on ripgrep: `|` `+` `?` `(` `)` `{` `}` are regex metacharacters by default (e.g. `foo|bar` alternates, matching either branch) \u2014 escape with a backslash for the literal character. Honors .gitignore (so build/dependency dirs like node_modules are skipped) but DOES search hidden files/dirs like .github and .env; the .git directory and binary files are skipped. Output is capped to a ~100KB head+tail view; if a search is truncated, narrow it (a more specific pattern, an `include` glob, or a subdirectory `path`) rather than re-running the same broad query. Use for finding symbols, strings, or patterns across the codebase.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Search pattern (ripgrep regex syntax). `|` `+` `?` `(` `)` `{` `}` are metacharacters \u2014 e.g. `foo|bar` matches either "foo" or "bar". Escape with a backslash (e.g. `\\|`) to match the literal character.'},path:{type:"string",description:"Directory or file to search. Defaults to current working directory."},include:{type:"string",description:'File glob to restrict search (e.g., "*.ts"). Passed as -g to ripgrep.'}},required:["pattern"]}},mue={name:"list_directory",category:"read",concurrencySafe:!0,description:"List the contents of a directory. Returns file and subdirectory names with type annotations (directories end with /). Use for exploring project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the directory to list."}},required:["path"]}},fue={name:"send_telegram",category:"web",concurrencySafe:!1,riskClass:"caution",description:'Send a Telegram message to the operator. Use to surface terminal-state notifications, blocking questions, or important status updates when the user is away from keyboard (AFK). The message is delivered through the same Telegram bot the operator uses to drive this session. By default the message goes to your primary chat (the first private chat in `AFK_TELEGRAM_ALLOWED_CHAT_IDS`, or `AFK_TELEGRAM_PRIMARY_CHAT_ID` if set); set `telegram.notify` in afk.config.json to broadcast to all allowed chats or target a custom set.\n\nPlain text only \u2014 Telegram\'s 4096-character limit per message is enforced. Returns an error if Telegram is not configured (missing `TELEGRAM_BOT_TOKEN` or empty allowlist) so the tool is safe to attempt unconditionally.\n\nUse sparingly: this is a real push notification to a human. Reserve for terminal states (Done/Blocked/Asking) and material progress, not running commentary. When running inside the Telegram bot, prefer replying normally \u2014 your response already reaches the operator through the bot. Use this tool only from CLI or daemon sessions.\n\nOptionally set `chat` to route to a SPECIFIC chat instead of the default primary target: pass a numeric chat id (e.g. -1001234567890 for a group) or a chat alias name defined in afk.config.json `telegram.chatAliases` (e.g. "ops"). An explicitly-targeted chat must be in the inbound allowlist (AFK_TELEGRAM_ALLOWED_CHAT_IDS) \u2014 a non-allowlisted target is rejected (fail-closed). Omit `chat` for the default behavior (unchanged).\n\nFor supergroups with topics enabled, set `thread_id` alongside `chat` to send to a specific topic thread.',input_schema:{type:"object",properties:{message:{type:"string",description:"Plain-text message body to send to the operator. Max 4096 characters (Telegram API limit). Must be non-empty."},chat:{type:["number","string"],description:"Optional. Target a specific chat instead of the default primary target. A number (or numeric string) is a raw Telegram chat id; a non-numeric string is looked up as a name in afk.config.json `telegram.chatAliases`. The resolved chat must be allowlisted (AFK_TELEGRAM_ALLOWED_CHAT_IDS) or the send is rejected. Omit to send to the configured default (primary DM chat / notify targets)."},thread_id:{type:"number",description:"Optional. Telegram message_thread_id for sending to a specific topic in a supergroup with topics enabled. Pass the numeric thread/topic ID. Ignored when the target chat is not a supergroup with topics. Requires `chat` to be set explicitly (thread targeting without a chat target is ambiguous)."}},required:["message"]}},gue={name:"web_scrape",category:"web",concurrencySafe:!0,description:'Scrape a web page or run a web search and return text content suitable for reasoning over. Three modes:\n\n- `markdown` (default): fetches the URL and extracts the main content as clean markdown (Readability + Turndown). Handles JS-rendered pages: if the plain fetch yields thin content, it escalates to a headless-browser render and re-extracts. Use this for articles, docs, blog posts, and most "I want to read this page" cases. No API key required (the render fallback needs the Playwright chromium binary; if it is absent the error names the exact install command for this installation).\n- `raw`: GETs the URL directly and returns the response body as decoded text, with no markdown transformation. Use for JSON APIs, robots.txt, RSS, or plain-text endpoints. Not byte-preserving \u2014 binary payloads are decoded as text, so do not rely on this for exact bytes. No API key required.\n- `search`: runs a web search and returns ranked markdown results. Use when you need to FIND a URL, not read one. Provide `query` instead of `url`. Requires `EXA_API_KEY` (free tier at https://exa.ai); the handler returns a clear error if it is unset.\n\nOutputs are capped at `max_bytes` UTF-8 bytes (default 100KB, ceiling 1MB); content over the cap is reduced to head+tail with a `\u2026 [N bytes truncated: \u2026] \u2026` marker so both ends survive. The request is aborted after `timeout_ms` (default 30000, ceiling 120000).',input_schema:{type:"object",properties:{mode:{type:"string",enum:["markdown","raw","search"],description:'Fetch mode. Defaults to "markdown".'},url:{type:"string",description:"Absolute http(s) URL. Required for markdown and raw modes. Ignored in search mode."},query:{type:"string",description:"Search query string. Required for search mode. Ignored otherwise."},timeout_ms:{type:"number",description:"Request timeout in milliseconds (default 30000, clamped to 120000)."},max_bytes:{type:"number",description:"Maximum UTF-8 bytes returned. Content beyond this is reduced to head+tail with a truncation marker (both ends preserved). Default 100000, clamped to 1000000."}},required:[]}},vn={name:"agent",category:"subagent",concurrencySafe:!0,description:`Dispatch an independent subagent with its own context window and tool access. Use for tasks that protect the main session's context: codebase exploration, multi-file inspection, repo search, verification, debugging, failing-test investigation, PR review, parallel hypothesis testing, independent re-derivation of a claim, audit work, stale-path detection, feature-wiring checks, and any research-shaped investigation.
|
|
120
120
|
|
|
121
121
|
Parallelize: dispatch multiple \`agent\` calls in a single tool-use turn to run independent investigations concurrently.
|
|
122
122
|
|
|
@@ -385,7 +385,7 @@ ${o}`,paths:[t,n]}:o!==null?i={content:o,paths:[n]}:r!==null?i={content:r,paths:
|
|
|
385
385
|
|
|
386
386
|
${t}`}var rge,xA=y(()=>{"use strict";rge=new Set(["script","style","noscript","template","svg"])});function sge(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(i),r(t?.reason??new Error("aborted"))},i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function Sj(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function age(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function wj(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??sge,l=n.signal??void 0,c;for(let u=0;u<=o;u++){if(l?.aborted)throw l.reason??new Error("aborted");try{let d=await e(t,n);if(!ige.has(d.status)||u===o)return d;let p=age(d,s)??Sj(u,i,s);N("[web/retryFetch] retrying",{url:t,attempt:u,status:d.status,waitMs:p}),await d.body?.cancel().catch(()=>{}),await a(p,l)}catch(d){if(l?.aborted||(c=d,u===o))throw d;let p=Sj(u,i,s);N("[web/retryFetch] retrying after error",{url:t,attempt:u,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var ige,vj=y(()=>{"use strict";ce();ige=new Set([429,502,503,504])});import{BlockList as lge,isIP as CA}from"node:net";import{lookup as cge}from"node:dns/promises";import{Agent as uge}from"undici";function Tj(){let e=v.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return e==="1"||e==="true"}function fge(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function AA(e){let t=CA(e);return t===0?!1:mge.check(e,t===4?"ipv4":"ipv6")}async function Ej(e){return cge(e,{all:!0,verbatim:!0})}async function _A(e,t={}){if(t.allowPrivateHosts??Tj())return{allowed:!0};let n;try{n=new URL(e)}catch{return{allowed:!1,reason:`"${e}" 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=fge(n.hostname),o=(a,l)=>`refusing to fetch ${l} \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(CA(r)!==0)return AA(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let i=t.lookupFn??Ej,s;try{s=await i(r)}catch{return{allowed:!0}}for(let a of s)if(AA(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Gp(e,t={}){let n=await _A(e,t);if(!n.allowed)throw new ur(n.reason)}async function By(e,t,n={},r={}){let o={...r.lookupFn!==void 0?{lookupFn:r.lookupFn}:{},...r.allowPrivateHosts!==void 0?{allowPrivateHosts:r.allowPrivateHosts}:{}},i=t;for(let s=0;s<=kj;s++){await Gp(i,o);let a={...n,redirect:"manual",...e===globalThis.fetch&&!(r.allowPrivateHosts??Tj())?{dispatcher:gge}:{}},l=await wj(e,i,a,r.retry??{});if(!hge.has(l.status))return l;let c=l.headers.get("location");if(c===null||c.trim()==="")return l;let u;try{u=new URL(c,l.url||i).toString()}catch{return l}await l.body?.cancel().catch(()=>{}),i=u}throw new ur(`too many redirects (>${kj}) starting from ${t}`)}var dge,pge,mge,ur,gge,kj,hge,IA=y(()=>{"use strict";L();vj();dge=[["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]],pge=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],mge=(()=>{let e=new lge;for(let[t,n]of dge)e.addSubnet(t,n,"ipv4");for(let[t,n]of pge)e.addSubnet(t,n,"ipv6");return e})(),ur=class extends Error{constructor(t){super(t),this.name="EgressBlockedError"}};gge=new uge({connect:{lookup(e,t,n){Ej(e).then(r=>{let o=r.find(s=>AA(s.address));if(o!==void 0){n(new ur(`refusing to connect to ${e} (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 i=r[0];if(i===void 0){n(new Error(`DNS lookup returned no addresses for ${e}`),"",0);return}n(null,i.address,CA(i.address))},r=>n(r,"",0))}}});kj=20,hge=new Set([301,302,303,307,308])});import{readFileSync as yge}from"node:fs";import{join as bge}from"path";function Sge(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Rj(e,t){return Sge(t).test(e)}function kge(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(wge.has(t))return!0;if(vge.has(t))return!1}return!1}function xj(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function Tge(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function Aj(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Kd(t),t}function Ege(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function Rge(e){try{return yge(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function xge(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=Aj(t.defaultProfile)),n}function Cj(e){let t=e?.env??v,n=e?.readFileSync??Rge,r=e?.surface??t.AGENT_SURFACE,o=kge(t.AFK_BROWSER_HEADLESS,r),i=xj(t.AFK_BROWSER_ALLOWED_DOMAINS),s=xj(t.AFK_BROWSER_BLOCKED_DOMAINS),a=Ege(t.AFK_BROWSER_DOM_SNAPSHOTS),l=Tge(t.AFK_BROWSER_BACKEND),c=Aj(t.AFK_BROWSER_DEFAULT_PROFILE),u={headless:o,allowedDomains:i,blockedDomains:s,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},d=t.AFK_BROWSER_CONFIG,p=d!==void 0&&d.trim()!==""?d.trim():bge(nr(),"browser.json"),f=n(p);if(f===void 0)return u;let g;try{g=JSON.parse(f)}catch(b){throw new Error(`Failed to parse browser config at ${p}: ${String(b)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=xge(u,g);return h.configPath=p,h}function Uy(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(Rj(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>Rj(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var wge,vge,jy=y(()=>{"use strict";L();H();wge=new Set(["daemon","subagent","telegram","afk"]),vge=new Set(["repl","interactive","cli"])});import{existsSync as Age,readFileSync as Cge}from"node:fs";import{createRequire as _ge}from"node:module";import{dirname as Ige,join as Pge}from"node:path";function Pj(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<Oge&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function dn(e){let t=Pj(e);return Ij.some(n=>t.includes(n))}function Dge(){try{let t=_ge(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(Cge(t,"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 i=Pge(Ige(t),o);return Age(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function qp(){return _j??=Dge()??Mge,_j}function PA(e){return e.includes("install chromium")}function jn(e,t){let n=Pj(e),r=t?.latched===!0?` ${$ge}`:"";if(n.includes("Executable doesn't exist")){let o="";return t?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":t?.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: ${qp()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${qp()}). Or pick a different tool.${r}`}function zp(e,t,n=!1){if(!dn(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
|
|
387
387
|
|
|
388
|
-
${jn(e,{headless:t,latched:n})}`,{cause:e})}var Ij,Mge,Oge,_j,$ge,Hy=y(()=>{"use strict";Ij=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],Mge="pnpm exec playwright install chromium",Oge=4;$ge="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 Js from"node:fs";import Wy from"node:path";import{randomBytes as Fge}from"node:crypto";import{chromium as Lge}from"playwright";function Nge(){try{return"5.155.0"}catch{}try{let e=Wy.resolve(import.meta.dirname,"../../../package.json"),t=Js.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Bge,Ky,Mj=y(()=>{"use strict";Hy();H();ce();Bge=Nge(),Ky=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}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=Lge.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=zp(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let u=a.url(),d=l!==null?l.status():null;return{html:c,finalUrl:u,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){this.clearLaunchFailure();let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${Bge}`}}loadStorageState(t){let n=Gd(t);try{if(!Js.existsSync(n))return;let r=JSON.parse(Js.readFileSync(n,"utf8"));return N("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){N("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Gd(t);if(!Js.existsSync(r))return;let o=await n.storageState(),i=Wy.join(Wy.dirname(r),`.${Wy.basename(r)}.${process.pid}.${Fge(4).toString("hex")}.tmp`);Js.writeFileSync(i,JSON.stringify(o),{mode:384}),Js.chmodSync(i,384),Js.renameSync(i,r),N("[browser/vault] saved session",{profile:t,file:r})}catch(r){N("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as Uge}from"crypto";function Oj(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&jge.test(e.label))}function Dj(e){return Uge("sha256").update(e,"utf8").digest("hex").slice(0,8)}function $j(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var jge,Gy=y(()=>{"use strict";jge=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Hge}from"node:crypto";function Wge(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function Kge(e,t,n){return`el_${Hge("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function Gge(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function Fj(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Nj(e,t){let n=e.role??"",r=e.name??"";Lj.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])Nj(i,t)}async function qge(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let u=window.getComputedStyle(s);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},Bj).catch(()=>[])}async function zge(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in i?i.value:void 0,d=u!==void 0?String(u):void 0,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},Bj).catch(()=>[])}function Vge(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function qy(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=Vge(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=qge(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([s,a,l,c,u]),b,S=!1;d!==null?(b=[],Nj(d,b)):(o.push("observation skipped accessibility tree (returned null)"),S=!0,b=(await zge(e)).filter(D=>Lj.has(D.role??"")));let w=new Map;for(let M of p){let D=Fj(M.name),$=w.get(D);(!$||$.bbox.w===0&&M.bbox.w>0)&&w.set(D,M)}let k=b.map(M=>({ax:M,dom:w.get(Fj(M.name??""))})),E=r?k:k.filter(M=>M.dom?M.dom.bbox.w>0||M.dom.bbox.h>0:!0);E.sort((M,D)=>{let $=M.dom?.bbox.y??0,U=D.dom?.bbox.y??0;if($!==U)return $-U;let W=M.dom?.bbox.x??0,G=D.dom?.bbox.x??0;return W-G}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=E.slice(0,n).map((M,D)=>{let $=M.ax.role??"generic",U=M.ax.name??"",W=Kge($,U,D),G=M.dom?.bbox??{x:0,y:0,w:0,h:0},j=M.dom?.type??null,K=null;M.ax.value!==void 0&&M.ax.value!==null&&(K=String(M.ax.value)),M.ax.checked!==void 0&&(K=String(M.ax.checked)),Oj({role:$,kind:j})&&(K="[redacted]");let Q={disabled:M.ax.disabled??!1};M.ax.checked!==void 0&&(Q.checked=M.ax.checked===!0||M.ax.checked==="mixed"),M.ax.selected!==void 0&&(Q.selected=M.ax.selected),M.ax.expanded!==void 0&&(Q.expanded=M.ax.expanded);let P;M.dom?.testId?P=`[data-testid="${M.dom.testId}"]`:M.dom?.id&&(P=`#${M.dom.id}`);let F={id:W,role:$,label:Wge(U),kind:j,value:K,state:Q,bbox:G};return P!==void 0&&(F.selector=P),F}),I="idle";try{let M=await e.evaluate(()=>document.readyState);M==="loading"?I="loading":M==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),S&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=Gge(f),x=`obs_${t.observationCounter.toString(36)}`,_=new Date().toISOString();return{observationId:x,url:g,title:h,textSummary:C,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:I,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:_}}var Lj,Bj,Uj=y(()=>{"use strict";Gy();Lj=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Bj="a[href], button, input, select, textarea, [role], [tabindex], label"});async function jj(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>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 MA(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>jj(e,i)))).filter(o=>o!==null)}async function Yge(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function OA(e,t,n){switch(t.kind){case"element_id":return Jge(e,t,n);case"selector":return Xge(e,t);case"semantic":return Qge(e,t)}}async function Jge(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await MA(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function Xge(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await MA(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function Qge(e,t){return t.role!==void 0?Zge(e,t.text,t.role):ehe(e,t.text,t)}async function Zge(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await MA(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function ehe(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let u=[];s>0&&u.push({loc:r,count:s}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:i,count:l});let d=await Yge(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let S=await jj(b.locator,b.index);if(S!==null){let w=`${S.role}:${S.label}:${h}`,k=0;for(let E=0;E<w.length;E++)k=k*31+w.charCodeAt(E)>>>0;f.push({...S,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var Hj=y(()=>{"use strict"});async function DA(e,t,n,r){let o=e.url();if(o===n)return null;let i=Uy(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var Wj=y(()=>{"use strict";jy()});import{randomBytes as the}from"crypto";import{mkdir as nhe,stat as rhe,writeFile as ohe}from"fs/promises";import{join as $A}from"path";import{gzip as ihe}from"zlib";import{promisify as she}from"util";function ahe(e){return $A(Sn(e),"browser")}function lhe(e){return $A(ahe(e),"screenshots")}function che(){return new Date().toISOString().replace(/[:.]/g,"-")}function uhe(){return the(3).toString("hex")}async function FA(e,t,n){if(t.length>Kj)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Kj} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=lhe(e);await nhe(r,{recursive:!0});let o=`${che()}-${uhe()}-${n}.png`,i=$A(r,o);await ohe(i,t);let{size:s}=await rhe(i);return{path:i,bytes:s}}var G3e,Kj,Gj=y(()=>{"use strict";H();Gy();G3e=she(ihe);Kj=5*1024*1024});var zj={};uo(zj,{PlaywrightProvider:()=>LA});function qj(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var LA,Vj=y(()=>{"use strict";Mj();Uj();Hj();jy();Wj();Gj();LA=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Ky(t)}async open(t){let n=Uy(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(d){a=d}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let d=await DA(o,this.config,t.url,()=>this.close({sessionId:r}));if(d!==null)return d}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let u=await qy(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,u.interactive,u.url,u.title,"browser_open"),a!==null)throw a;return u}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await qy(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),i=r.url(),s=t.timeoutMs??3e4,a=await OA(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${qj(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":await l.fill(t.value??"");break;case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=await DA(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await qy(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),i;if(t.target!==void 0){let u=await OA(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${qj(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await u.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await FA(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await FA(n,o,r);return i}catch{return null}}}});var Qs={};uo(Qs,{__resetBrowserRegistryForTests:()=>ghe,browserProviderActive:()=>mhe,closeBrowserProvider:()=>NA,getBrowserProvider:()=>phe,peekBrowserProvider:()=>fhe});function Yj(){Promise.resolve(NA()).then(()=>{process.exit(130)})}function Jj(){Promise.resolve(NA()).then(()=>{process.exit(143)})}function Xj(){jr=null}function dhe(){zy||(process.on("SIGINT",Yj),process.on("SIGTERM",Jj),process.on("exit",Xj),zy=!0)}function Qj(){zy&&(process.removeListener("SIGINT",Yj),process.removeListener("SIGTERM",Jj),process.removeListener("exit",Xj),zy=!1)}async function phe(e){return jr!==null?jr:(Xs!==null||(Xs=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(Vj(),zj)),n=Cj(e),r=new t(n);return dhe(),jr=r,Xs=null,r})()),Xs)}async function NA(){if(jr===null)return;let e=jr;jr=null,Xs=null,Qj(),await e.shutdown()}function mhe(){return jr!==null}function fhe(){return jr}function ghe(){jr=null,Xs=null,Qj()}var jr,Xs,zy,Zs=y(()=>{"use strict";jy();jr=null,Xs=null,zy=!1});async function Zj(e,t){try{return await hj(e,t)}catch(n){return N("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function vhe(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Zs(),Qs));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function e1(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??vhe,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await By(n,e,{headers:whe,signal:t.signal},o);l=d.status,a=d.url||e;let p=d.headers.get("content-type")??"";if(d.ok){if(She.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 d.text();if(bhe.test(p)&&!yhe.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await Zj(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof ur||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;c=d}if(!(i===null||i.textLength<200)&&i!==null){let d=RA({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await Gp(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>Gp(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await Gp(d.finalUrl,o);let p=await Zj(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=RA({html:d.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:d.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(d){if(t.signal.aborted||d instanceof ur)throw d;if(i===null){let p=d instanceof Error?d.message:String(d),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${p}).`);throw g.cause=d,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var yhe,bhe,She,whe,t1=y(()=>{"use strict";yj();xA();IA();ce();yhe=/(text\/html|application\/xhtml\+xml)/i,bhe=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,She=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,whe={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function Ehe(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(khe,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),The),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=ae(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function n1(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Ehe({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function r1(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
388
|
+
${jn(e,{headless:t,latched:n})}`,{cause:e})}var Ij,Mge,Oge,_j,$ge,Hy=y(()=>{"use strict";Ij=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],Mge="pnpm exec playwright install chromium",Oge=4;$ge="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 Js from"node:fs";import Wy from"node:path";import{randomBytes as Fge}from"node:crypto";import{chromium as Lge}from"playwright";function Nge(){try{return"5.156.0"}catch{}try{let e=Wy.resolve(import.meta.dirname,"../../../package.json"),t=Js.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Bge,Ky,Mj=y(()=>{"use strict";Hy();H();ce();Bge=Nge(),Ky=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}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=Lge.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=zp(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let u=a.url(),d=l!==null?l.status():null;return{html:c,finalUrl:u,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){this.clearLaunchFailure();let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${Bge}`}}loadStorageState(t){let n=Gd(t);try{if(!Js.existsSync(n))return;let r=JSON.parse(Js.readFileSync(n,"utf8"));return N("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){N("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Gd(t);if(!Js.existsSync(r))return;let o=await n.storageState(),i=Wy.join(Wy.dirname(r),`.${Wy.basename(r)}.${process.pid}.${Fge(4).toString("hex")}.tmp`);Js.writeFileSync(i,JSON.stringify(o),{mode:384}),Js.chmodSync(i,384),Js.renameSync(i,r),N("[browser/vault] saved session",{profile:t,file:r})}catch(r){N("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as Uge}from"crypto";function Oj(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&jge.test(e.label))}function Dj(e){return Uge("sha256").update(e,"utf8").digest("hex").slice(0,8)}function $j(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var jge,Gy=y(()=>{"use strict";jge=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Hge}from"node:crypto";function Wge(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function Kge(e,t,n){return`el_${Hge("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function Gge(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function Fj(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Nj(e,t){let n=e.role??"",r=e.name??"";Lj.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])Nj(i,t)}async function qge(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let u=window.getComputedStyle(s);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},Bj).catch(()=>[])}async function zge(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in i?i.value:void 0,d=u!==void 0?String(u):void 0,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},Bj).catch(()=>[])}function Vge(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function qy(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=Vge(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=qge(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([s,a,l,c,u]),b,S=!1;d!==null?(b=[],Nj(d,b)):(o.push("observation skipped accessibility tree (returned null)"),S=!0,b=(await zge(e)).filter(D=>Lj.has(D.role??"")));let w=new Map;for(let M of p){let D=Fj(M.name),$=w.get(D);(!$||$.bbox.w===0&&M.bbox.w>0)&&w.set(D,M)}let k=b.map(M=>({ax:M,dom:w.get(Fj(M.name??""))})),E=r?k:k.filter(M=>M.dom?M.dom.bbox.w>0||M.dom.bbox.h>0:!0);E.sort((M,D)=>{let $=M.dom?.bbox.y??0,U=D.dom?.bbox.y??0;if($!==U)return $-U;let W=M.dom?.bbox.x??0,G=D.dom?.bbox.x??0;return W-G}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=E.slice(0,n).map((M,D)=>{let $=M.ax.role??"generic",U=M.ax.name??"",W=Kge($,U,D),G=M.dom?.bbox??{x:0,y:0,w:0,h:0},j=M.dom?.type??null,K=null;M.ax.value!==void 0&&M.ax.value!==null&&(K=String(M.ax.value)),M.ax.checked!==void 0&&(K=String(M.ax.checked)),Oj({role:$,kind:j})&&(K="[redacted]");let Q={disabled:M.ax.disabled??!1};M.ax.checked!==void 0&&(Q.checked=M.ax.checked===!0||M.ax.checked==="mixed"),M.ax.selected!==void 0&&(Q.selected=M.ax.selected),M.ax.expanded!==void 0&&(Q.expanded=M.ax.expanded);let P;M.dom?.testId?P=`[data-testid="${M.dom.testId}"]`:M.dom?.id&&(P=`#${M.dom.id}`);let F={id:W,role:$,label:Wge(U),kind:j,value:K,state:Q,bbox:G};return P!==void 0&&(F.selector=P),F}),I="idle";try{let M=await e.evaluate(()=>document.readyState);M==="loading"?I="loading":M==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),S&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let C=Gge(f),x=`obs_${t.observationCounter.toString(36)}`,_=new Date().toISOString();return{observationId:x,url:g,title:h,textSummary:C,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:I,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:_}}var Lj,Bj,Uj=y(()=>{"use strict";Gy();Lj=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Bj="a[href], button, input, select, textarea, [role], [tabindex], label"});async function jj(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>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 MA(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>jj(e,i)))).filter(o=>o!==null)}async function Yge(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function OA(e,t,n){switch(t.kind){case"element_id":return Jge(e,t,n);case"selector":return Xge(e,t);case"semantic":return Qge(e,t)}}async function Jge(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await MA(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function Xge(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await MA(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function Qge(e,t){return t.role!==void 0?Zge(e,t.text,t.role):ehe(e,t.text,t)}async function Zge(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await MA(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function ehe(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let u=[];s>0&&u.push({loc:r,count:s}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:i,count:l});let d=await Yge(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let S=await jj(b.locator,b.index);if(S!==null){let w=`${S.role}:${S.label}:${h}`,k=0;for(let E=0;E<w.length;E++)k=k*31+w.charCodeAt(E)>>>0;f.push({...S,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var Hj=y(()=>{"use strict"});async function DA(e,t,n,r){let o=e.url();if(o===n)return null;let i=Uy(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var Wj=y(()=>{"use strict";jy()});import{randomBytes as the}from"crypto";import{mkdir as nhe,stat as rhe,writeFile as ohe}from"fs/promises";import{join as $A}from"path";import{gzip as ihe}from"zlib";import{promisify as she}from"util";function ahe(e){return $A(Sn(e),"browser")}function lhe(e){return $A(ahe(e),"screenshots")}function che(){return new Date().toISOString().replace(/[:.]/g,"-")}function uhe(){return the(3).toString("hex")}async function FA(e,t,n){if(t.length>Kj)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Kj} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=lhe(e);await nhe(r,{recursive:!0});let o=`${che()}-${uhe()}-${n}.png`,i=$A(r,o);await ohe(i,t);let{size:s}=await rhe(i);return{path:i,bytes:s}}var G3e,Kj,Gj=y(()=>{"use strict";H();Gy();G3e=she(ihe);Kj=5*1024*1024});var zj={};uo(zj,{PlaywrightProvider:()=>LA});function qj(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var LA,Vj=y(()=>{"use strict";Mj();Uj();Hj();jy();Wj();Gj();LA=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Ky(t)}async open(t){let n=Uy(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(d){a=d}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let d=await DA(o,this.config,t.url,()=>this.close({sessionId:r}));if(d!==null)return d}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let u=await qy(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,u.interactive,u.url,u.title,"browser_open"),a!==null)throw a;return u}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await qy(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),i=r.url(),s=t.timeoutMs??3e4,a=await OA(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${qj(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":await l.fill(t.value??"");break;case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=await DA(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await qy(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),i;if(t.target!==void 0){let u=await OA(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${qj(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await u.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await FA(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await FA(n,o,r);return i}catch{return null}}}});var Qs={};uo(Qs,{__resetBrowserRegistryForTests:()=>ghe,browserProviderActive:()=>mhe,closeBrowserProvider:()=>NA,getBrowserProvider:()=>phe,peekBrowserProvider:()=>fhe});function Yj(){Promise.resolve(NA()).then(()=>{process.exit(130)})}function Jj(){Promise.resolve(NA()).then(()=>{process.exit(143)})}function Xj(){jr=null}function dhe(){zy||(process.on("SIGINT",Yj),process.on("SIGTERM",Jj),process.on("exit",Xj),zy=!0)}function Qj(){zy&&(process.removeListener("SIGINT",Yj),process.removeListener("SIGTERM",Jj),process.removeListener("exit",Xj),zy=!1)}async function phe(e){return jr!==null?jr:(Xs!==null||(Xs=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(Vj(),zj)),n=Cj(e),r=new t(n);return dhe(),jr=r,Xs=null,r})()),Xs)}async function NA(){if(jr===null)return;let e=jr;jr=null,Xs=null,Qj(),await e.shutdown()}function mhe(){return jr!==null}function fhe(){return jr}function ghe(){jr=null,Xs=null,Qj()}var jr,Xs,zy,Zs=y(()=>{"use strict";jy();jr=null,Xs=null,zy=!1});async function Zj(e,t){try{return await hj(e,t)}catch(n){return N("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function vhe(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Zs(),Qs));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function e1(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??vhe,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await By(n,e,{headers:whe,signal:t.signal},o);l=d.status,a=d.url||e;let p=d.headers.get("content-type")??"";if(d.ok){if(She.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 d.text();if(bhe.test(p)&&!yhe.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await Zj(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof ur||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;c=d}if(!(i===null||i.textLength<200)&&i!==null){let d=RA({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await Gp(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>Gp(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await Gp(d.finalUrl,o);let p=await Zj(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=RA({html:d.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:d.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(d){if(t.signal.aborted||d instanceof ur)throw d;if(i===null){let p=d instanceof Error?d.message:String(d),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${p}).`);throw g.cause=d,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var yhe,bhe,She,whe,t1=y(()=>{"use strict";yj();xA();IA();ce();yhe=/(text\/html|application\/xhtml\+xml)/i,bhe=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,She=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,whe={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function Ehe(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(khe,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),The),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=ae(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function n1(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Ehe({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function r1(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
389
389
|
|
|
390
390
|
(no results)`;let n=[`# Search results for "${e}"`,""];return t.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
|
|
391
391
|
`).trimEnd()}var khe,The,o1=y(()=>{"use strict";ut();khe="https://api.exa.ai/search",The=10});function Vy(e){if(e instanceof Error&&e.name==="TimeoutError")return"timeout";let t=e instanceof Error?e.message:String(e);return/Timeout\s+\d+\s*ms exceeded/i.test(t)?"timeout":void 0}var ea=y(()=>{"use strict";Hy()});function Ihe(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,i;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};i=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let s=Rhe;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};s=Math.min(t.timeout_ms,xhe)}let a=Ahe;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(t.max_bytes,Che)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function BA(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:Ls(e,t),truncated:!0}}function Phe(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env,r=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{};return async(o,i)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=Ihe(o);if("error"in s)return{content:s.error,isError:!0};if(i.aborted){let d=i.reason;return{content:`web_scrape aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let a=new AbortController,l=()=>{a.abort(i.reason)},c,u=()=>{let d=a.signal.reason;return d instanceof Error?d.message:String(d??"aborted")};try{if(i.addEventListener("abort",l,{once:!0}),c=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.url!==void 0){let p=await _A(s.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,isError:!0};if(!p.allowed)return{content:`web_scrape blocked: ${p.reason}`,isError:!0}}if(s.mode==="raw"){let p;try{let h={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await By(t,s.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:h instanceof ur?{content:`web_scrape blocked: ${h.message}`,isError:!0}:{content:`web_scrape network error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let f;try{f=await p.text()}catch(h){return{content:`web_scrape read error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let g=BA(f,s.maxBytes);return{content:g.content,...g.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let p=await e1(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:a.signal,...e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let f=BA(bj(p.markdown,p.advisory),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,isError:!0};if(p instanceof ur)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),g=dn(p)&&!PA(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${qp()}\`)`:"";return{content:`web_scrape markdown error: ${f}${g}`,isError:!0}}let d=n1({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in d)return{content:d.error,isError:!0};try{let p=await d.search(s.query,{limit:_he,timeoutMs:s.timeoutMs,signal:a.signal}),f=BA(r1(s.query,p),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),i.removeEventListener("abort",l)}}}var Rhe,xhe,Ahe,Che,_he,i1,s1=y(()=>{"use strict";t1();o1();IA();ui();xA();ea();Rhe=3e4,xhe=12e4,Ahe=1e5,Che=1e6,_he=10;i1=Phe()});import{existsSync as l1,mkdirSync as Mhe,readFileSync as Ohe,renameSync as Dhe,unlinkSync as $he,writeFileSync as Fhe}from"node:fs";import{dirname as a1,join as Lhe}from"node:path";import{randomBytes as Nhe}from"node:crypto";function En(e){let t=e??kR();if(!l1(t))return[];try{let n=Ohe(t,"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 ${t}: ${r}`),[]}}function gi(e,t){let n=t??kR();Mhe(a1(n),{recursive:!0});let r=Lhe(a1(n),`.schedules.json.${process.pid}.${Nhe(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{Fhe(r,o,"utf-8"),Dhe(r,n)}catch(i){try{l1(r)&&$he(r)}catch{}throw i}}function Yy(e,t){let n=En(t),r=n.map(l=>l.id),o=Bhe(e.name),i=Uhe(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),gi(n,t),a}function Jy(e,t){let n=En(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(gi(o,t),!0)}function Vp(e,t){return En(t).find(n=>n.id===e)}function Bhe(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function Uhe(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function Xy(e){return{taskId:e.id,command:e.command,trigger:e.trigger??"cron",...e.cron!==void 0?{cronExpression:e.cron}:{},...e.notifyOn!==void 0?{notifyOn:e.notifyOn}:{},...e.notifyChat!==void 0?{notifyChat:e.notifyChat}:{}}}var Qy=y(()=>{"use strict";H()});import{existsSync as jhe,readFileSync as Hhe}from"node:fs";import{join as Whe}from"node:path";async function Hn(e,t,n){let r,o;try{let i=Whe(Qg("default"),"port");if(!jhe(i))return{synced:!1,detail:"daemon-not-detected (no port file)"};let s=Hhe(i,"utf-8").trim(),a=Khe(s);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 i=r.includes(":")?`[${r}]`:r,s=await fetch(`http://${i}:${o}${t}`,{method:e,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return s.ok?{synced:!0,detail:"synced"}:e==="POST"&&s.status===409?{synced:!0,detail:"already-registered"}:e==="DELETE"&&s.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${s.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}function Khe(e){let t=parseInt(e,10);if(String(t)===e&&!Number.isNaN(t))return t<1||t>65535?null:{host:"localhost",port:t};let n=e.lastIndexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1);if(!/^\d+$/.test(o))return null;let i=parseInt(o,10);return Number.isNaN(i)||i<1||i>65535||/^:+$/.test(r)?null:{host:r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,port:i}}var hi,UA=y(()=>{"use strict";H();hi="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."});import{existsSync as Ghe}from"node:fs";import{readFile as qhe}from"node:fs/promises";var c1,u1,d1,p1,m1=y(()=>{"use strict";Qy();H();UA();c1=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;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 i=Yy({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}),s=i.enabled?await Hn("POST","/tasks",{taskId:i.id,command:i.command,cron:i.cron,trigger:i.trigger,notifyOn:i.notifyOn,...i.notifyChat!==void 0?{notifyChat:i.notifyChat}:{}}):await Hn("DELETE",`/tasks/${i.id}`);return{content:JSON.stringify({id:i.id,name:i.name,cron:i.cron,enabled:i.enabled,daemonSynced:s.synced,syncDetail:s.detail,...s.synced?{}:{syncNote:hi}})}},u1=async(e,t)=>{let n=En();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})))}},d1=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;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,i=xr();if(!Ghe(i))return{content:JSON.stringify([])};let s;try{let c=await qhe(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
|
|
@@ -412,7 +412,7 @@ ${jn(e,{headless:t,latched:n})}`,{cause:e})}var Ij,Mge,Oge,_j,$ge,Hy=y(()=>{"use
|
|
|
412
412
|
`),this.errored=!0,this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null}}}_writeLine(t){if(!(!this.stream||this.errored))try{this.stream.write(t,n=>{n&&(process.stderr.write(`[afk] session-ledger: write error for ${this.sessionId}: ${String(n)}
|
|
413
413
|
`),this.errored=!0)})}catch(n){process.stderr.write(`[afk] session-ledger: write threw for ${this.sessionId}: ${String(n)}
|
|
414
414
|
`),this.errored=!0}}async close(t){if(!this.closed)return this.record({kind:"closed",...t!==void 0?{reason:t}:{}}),this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(n=>{if(!this.stream){n();return}this.stream.end(()=>n())})}};Yye=250});import{readdir as Jye,stat as Xye}from"node:fs/promises";import{join as Qye}from"node:path";async function tm(){let e=rr(),t;try{t=await Jye(e)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t){let o=Qye(e,r,"trace.jsonl");try{let i=await Xye(o);i.isFile()&&n.push({sessionId:r,tracePath:o,mtimeMs:i.mtimeMs,exists:!0})}catch{}}return n.sort((r,o)=>o.mtimeMs-r.mtimeMs),n}async function Tb(){return(await tm())[0]?.sessionId??null}var cC=y(()=>{"use strict";H()});import{existsSync as Zye,readdirSync as ebe,readFileSync as tbe}from"node:fs";import{basename as nbe,join as rbe}from"node:path";function ibe(e){try{let t=JSON.parse(tbe(e,"utf-8"));if(typeof t!="object"||t===null)return;let n=t;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 sbe(e){if(!Zye(e))return[];let t;try{t=ebe(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".json"))continue;let o=rbe(e,r),i=ibe(o);i&&n.push({sidecarId:nbe(r,".json"),filePath:o,data:i})}return n}function nH(e,t=Ge()){let n=sbe(t);n.sort((r,o)=>{let i=r.data.savedAt??-1/0;return(o.data.savedAt??-1/0)-i});for(let r of n){if(r.sidecarId===e)return{sessionId:r.data.sessionId??r.sidecarId,sidecarId:r.sidecarId,reason:"exact-id"};if(r.data.sessionId===e)return{sessionId:r.data.sessionId,sidecarId:r.sidecarId,reason:"exact-session-id"};if(r.data.name===e)return{sessionId:r.data.sessionId??r.sidecarId,sidecarId:r.sidecarId,reason:"exact-name"}}if(e.length>=obe){let r=n.filter(o=>o.data.name!==void 0&&o.data.name.startsWith(e));if(r.length===1){let o=r[0];return{sessionId:o.data.sessionId??o.sidecarId,sidecarId:o.sidecarId,reason:"prefix-name"}}}}var obe,rH=y(()=>{"use strict";H();obe=3});import{existsSync as abe}from"node:fs";import{readFile as lbe}from"node:fs/promises";async function uC(e){if(!abe(e))return{content:"",truncated:!1};try{let t=await lbe(e);if(t.length<=oH)return{content:t.toString("utf-8"),truncated:!1};let n=t.subarray(t.length-oH),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 oH,iH=y(()=>{"use strict";oH=2097152});import{existsSync as dC}from"node:fs";import{join as sH}from"node:path";function aH(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&typeof t.seq=="number"&&typeof t.payload=="object"&&t.payload!==null}function fbe(e){return kt(e,{guard:aH})}function gbe(e){return typeof e!="number"?cbe:Math.min(Math.max(1,Math.round(e)),ube)}function hbe(e){return typeof e!="number"?pbe:Math.min(Math.max(1,Math.round(e)),mbe)}function ybe(e,t){if(t.kinds&&!t.kinds.has(e.kind)||t.toolName&&(e.kind!=="tool_call"||e.payload.name!==t.toolName))return!1;if(t.errorsOnly)if(e.kind==="tool_call"){let n=e.payload;if(n.phase!=="completed"||!n.isError)return!1}else if(e.kind==="subagent_lifecycle"){if(e.payload.transition!=="failed")return!1}else if(e.kind==="background_agent"){if(e.payload.transition!=="failed")return!1}else return!1;return!0}async function bbe(e){let t=async r=>{let o=sH(Sn(r),"trace.jsonl");if(!dC(o))try{for await(let i of bi(r))if(i.kind==="meta"){if(i.traceLabel===null)return{tracePath:o,disabledNote:r};if(typeof i.traceLabel=="string"&&i.traceLabel.length>0){let s=sH(Sn(i.traceLabel),"trace.jsonl");dC(s)&&(o=s)}break}}catch{}return{tracePath:o,disabledNote:void 0}},n=await t(e);if(n.disabledNote!==void 0||dC(n.tracePath))return n;try{let r=nH(e);if(r&&r.sessionId!==e){let o=await t(r.sessionId);return o.disabledNote!==void 0?{tracePath:o.tracePath,disabledNote:r.sessionId}:o}}catch{}return n}async function Eb(e){let t=e.session==="latest"||!e.session?await Tb():e.session;if(!t)return{sessionId:"(none)",events:[],totalInTrace:0,filtered:0};let{tracePath:n,disabledNote:r}=await bbe(t);if(r!==void 0)return{sessionId:t,events:[],totalInTrace:0,filtered:0,note:`Session "${r}" ran with tracing disabled (traceLabel: null).`};let{content:o}=await uC(n),i=fbe(o),s={kinds:e.kinds?new Set(e.kinds):void 0,toolName:e.toolName,errorsOnly:e.errorsOnly},a=gbe(e.limit),l=[];for(let c=i.length-1;c>=0;c--){let u=i[c];if(ybe(u,s)&&(l.push(u),l.length>=a))break}return l.reverse(),{sessionId:t,events:l,totalInTrace:i.length,filtered:l.length}}async function Rb(e){let t=hbe(e.sessions),r=(await tm()).slice(0,t),o=r.length,i=r;if(e.since){let p=Date.parse(e.since);if(Number.isNaN(p))throw new Error(`Invalid "since" date: ${e.since}`);i=r.filter(f=>f.mtimeMs>=p)}let s=e.kinds?new Set(e.kinds):void 0,a=e.query.toLowerCase(),l=[],c=dbe,u=[],d=0;for(let p of i){if(l.length>=c)break;let{content:f,truncated:g}=await uC(p.tracePath);d++,g&&u.push(p.sessionId);let h=f.split(`
|
|
415
|
-
`).filter(b=>b.trim()!==""&&b.toLowerCase().includes(a));for(let b of h){if(l.length>=c)break;let[S]=kt(b,{guard:aH});S&&(s&&!s.has(S.kind)||l.push({sessionId:p.sessionId,event:S,matchLine:b.length>500?b.slice(0,500)+"\u2026":b}))}}return{query:e.query,sessionsAvailable:o,sessionsSearched:d,sessionsScanned:d,matches:l,...u.length>0?{truncatedSessions:u}:{}}}var cbe,ube,dbe,pbe,mbe,pC=y(()=>{"use strict";H();na();cC();rH();iH();yo();cbe=50,ube=200,dbe=200,pbe=20,mbe=100});function lH(e){return!e||typeof e!="object"?null:e}function cH(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}var uH,dH,pH=y(()=>{"use strict";pC();uH=async e=>{let t=lH(e);if(!t)return{content:"Invalid input: expected object",isError:!0};let n=typeof t.session=="string"?t.session:void 0,r=cH(t.kinds),o=typeof t.tool_name=="string"?t.tool_name:void 0,i=typeof t.errors_only=="boolean"?t.errors_only:!1,s=typeof t.limit=="number"?t.limit:void 0;try{let a=await Eb({session:n,kinds:r,toolName:o,errorsOnly:i,limit:s});return{content:JSON.stringify(a)}}catch(a){return{content:`read_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},dH=async e=>{let t=lH(e);if(!t)return{content:"Invalid input: expected object",isError:!0};if(typeof t.query!="string"||!t.query)return{content:"Invalid input: query (string) is required",isError:!0};let n=t.query,r=typeof t.sessions=="number"?t.sessions:void 0,o=cH(t.kinds),i=typeof t.since=="string"?t.since:void 0;try{let
|
|
415
|
+
`).filter(b=>b.trim()!==""&&b.toLowerCase().includes(a));for(let b of h){if(l.length>=c)break;let[S]=kt(b,{guard:aH});S&&(s&&!s.has(S.kind)||e.toolName&&(S.kind!=="tool_call"||S.payload.name!==e.toolName)||l.push({sessionId:p.sessionId,event:S,matchLine:b.length>500?b.slice(0,500)+"\u2026":b}))}}return{query:e.query,sessionsAvailable:o,sessionsSearched:d,sessionsScanned:d,matches:l,...u.length>0?{truncatedSessions:u}:{}}}var cbe,ube,dbe,pbe,mbe,pC=y(()=>{"use strict";H();na();cC();rH();iH();yo();cbe=50,ube=200,dbe=200,pbe=20,mbe=100});function lH(e){return!e||typeof e!="object"?null:e}function cH(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}var uH,dH,pH=y(()=>{"use strict";pC();uH=async e=>{let t=lH(e);if(!t)return{content:"Invalid input: expected object",isError:!0};let n=typeof t.session=="string"?t.session:void 0,r=cH(t.kinds),o=typeof t.tool_name=="string"?t.tool_name:void 0,i=typeof t.errors_only=="boolean"?t.errors_only:!1,s=typeof t.limit=="number"?t.limit:void 0;try{let a=await Eb({session:n,kinds:r,toolName:o,errorsOnly:i,limit:s});return{content:JSON.stringify(a)}}catch(a){return{content:`read_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},dH=async e=>{let t=lH(e);if(!t)return{content:"Invalid input: expected object",isError:!0};if(typeof t.query!="string"||!t.query)return{content:"Invalid input: query (string) is required",isError:!0};let n=t.query,r=typeof t.sessions=="number"?t.sessions:void 0,o=cH(t.kinds),i=typeof t.since=="string"?t.since:void 0,s=typeof t.tool_name=="string"?t.tool_name:void 0;try{let a=await Rb({query:n,sessions:r,kinds:o,since:i,toolName:s});return{content:JSON.stringify(a)}}catch(a){return{content:`search_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}}});function Sbe(e){return e.length<=mH?e:`${e.slice(0,mH)}\u2026(truncated)`}function wbe(e){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${e.title??e.serverName}`,Sbe(e.message)];e.url!==void 0&&e.url!==""&&n.push(e.url),Un(n.join(`
|
|
416
416
|
`)).catch(()=>{})}catch{}}function fH(e,t){if(!(e===void 0||e===""))try{Px(e,t).catch(()=>{})}catch{}}var bc,mH,mC,Xe,Wr=y(()=>{"use strict";Eo();Ws();bc={action:"decline"},mH=300;mC=class{handler=null;queue=Promise.resolve();queueDepth=0;install(t){this.handler=t}uninstall(){this.handler=null}hasHandler(){return this.handler!==null}pendingCount(){return this.queueDepth}route(t,n){if(n.signal.aborted)return Promise.resolve(bc);this.queueDepth+=1;let r,o=new Promise(s=>{r=s}),i=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(bc);return}if(!i){wbe(t),r(bc);return}let s,a=new Promise(l=>{s=()=>l(bc),n.signal.addEventListener("abort",s,{once:!0})});try{try{n.onActive?.()}catch{}fH(n.sessionId,!0);let l=await Promise.race([i(t,n).catch(()=>bc),a]);r(l)}finally{fH(n.sessionId,!1),n.signal.removeEventListener("abort",s)}}finally{this.queueDepth-=1,r(bc)}}).catch(()=>{}),o}},Xe=new mC});var gH,hH=y(()=>{"use strict";Wr();gH=async(e,t,n)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let r=e,o=r.question;if(typeof o!="string"||o.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let i=new Set(["text","confirm","choice","multi_choice","number"]),s=r.type??"text";if(typeof s!="string"||!i.has(s))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(s==="choice"||s==="multi_choice"){let g=r.choices;if(!Array.isArray(g)||g.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${s}"`,isError:!0};if(g.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${g.length}`,isError:!0};for(let h of g)if(typeof h!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let a=r.min,l=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(l!==void 0&&(typeof l!="number"||!Number.isFinite(l)))return{content:"Invalid input: max must be a finite number",isError:!0};if(a!==void 0&&l!==void 0&&a>l)return{content:`Invalid input: min (${a}) must be \u2264 max (${l})`,isError:!0};let c=r.min_length,u=r.max_length;if(c!==void 0&&typeof c!="number")return{content:"Invalid input: min_length must be a number",isError:!0};if(u!==void 0&&typeof u!="number")return{content:"Invalid input: max_length must be a number",isError:!0};if((c!==void 0||u!==void 0)&&s!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${s}"`,isError:!0};if(r.allow_custom!==void 0&&s!=="choice"&&s!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${s}"`,isError:!0};let d={serverName:"agent",message:o.trim(),origin:"agent",type:s,...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},...c!==void 0&&{minLength:c},...u!==void 0&&{maxLength:u},...a!==void 0&&{min:a},...l!==void 0&&{max:l},...r.allow_skip!==void 0&&{allowSkip:!!r.allow_skip},...r.allow_custom!==void 0&&{allowCustom:!!r.allow_custom}},p=await Xe.route(d,{signal:t,...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"}}}});function vbe(e){if(!e||typeof e!="object")return{error:"browser_open: input must be an object"};let t=e,n=t.url;if(typeof n!="string"||n.length===0)return{error:'browser_open: "url" is required and must be a non-empty string'};let r;try{r=new URL(n)}catch{return{error:`browser_open: "${n}" is not a valid absolute URL`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{error:`browser_open: protocol "${r.protocol}" is not supported (http/https only)`};let o;if(t.wait_for!==void 0){if(!yH.includes(t.wait_for))return{error:`browser_open: "wait_for" must be one of ${yH.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(t.wait_for)})`};o=t.wait_for}let i;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};i=t.screenshot}let s;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};s=t.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:i,timeoutMs:s}}function kbe(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_open aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0,failureClass:Zt(n)}}let o=vbe(t);if("error"in o)return{content:o.error,isError:!0};let i=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let s;try{if(e.getBrowserProvider)s=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(Zs(),Qs));s=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return dn(c)?{content:jn(c),isError:!0}:{content:`browser_open failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await s.open({sessionId:i,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),c=Date.now()-a;if("outcome"in l&&l.outcome==="blocked_by_policy")return vt(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:c}),{content:`browser_open blocked: ${l.reason}`,isError:!0,failureClass:"policy-refusal"};let u=l;return vt(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:u.url,status:"ok",durationMs:c,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(l){let c=Date.now()-a,u=l instanceof Error?l.message:String(l);vt(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:u,recoverable:!1}});let d=Vy(l);return{content:`browser_open failed: ${u}`,isError:!0,...d?{failureClass:d}:{}}}}}var yH,bH,SH=y(()=>{"use strict";L();ci();pe();ea();yH=["load","domcontentloaded","networkidle"];bH=kbe()});function Tbe(e){if(e!=null&&typeof e!="object")return{error:"browser_observe: input must be an object or omitted"};if(!e)return{};let t=e,n;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=t.screenshot}let r;if(t.include_hidden!==void 0){if(typeof t.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=t.include_hidden}let o;if(t.max_elements!==void 0){if(typeof t.max_elements!="number"||!Number.isFinite(t.max_elements)||t.max_elements<=0||!Number.isInteger(t.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=t.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function Ebe(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_observe aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=Tbe(t);if("error"in o)return{content:o.error,isError:!0};let i=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let s;try{if(e.getBrowserProvider)s=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(Zs(),Qs));s=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return dn(c)?{content:jn(c),isError:!0}:{content:`browser_observe failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await s.observe({sessionId:i,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),c=Date.now()-a;return vt(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:l.url,urlAfter:l.url,status:"ok",durationMs:c,...l.screenshotPath!==null?{screenshotPath:l.screenshotPath}:{}}),{content:JSON.stringify(l,null,2)}}catch(l){let c=Date.now()-a,u=l instanceof Error?l.message:String(l);return vt(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:u,recoverable:!1}}),{content:`browser_observe failed: ${u}`,isError:!0}}}}var wH,vH=y(()=>{"use strict";L();pe();ea();wH=Ebe()});function Rbe(e){if(!e||typeof e!="object")return{error:"browser_act: input must be an object"};let t=e;if(typeof t.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!kH.includes(t.action))return{error:`browser_act: "action" must be one of ${kH.map(u=>`"${u}"`).join(", ")} (got ${JSON.stringify(t.action)})`};let n=t.action,r=t.target;if(!r||typeof r!="object")return{error:'browser_act: "target" is required and must be an object'};let o=r;if(typeof o.kind!="string"||!TH.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${TH.map(u=>`"${u}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let i,s=o.kind;if(s==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};i={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(s==="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)'};i={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)'};i={kind:"selector",selector:o.selector}}let a;if(t.value!==void 0){if(typeof t.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=t.value}let l;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};l=t.timeout_ms}let c;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};c=t.screenshot}return{action:n,target:i,value:a,timeoutMs:l,screenshot:c}}function xbe(e,t){let n=e.role?`"${e.text}" (role: ${e.role})`:`"${e.text}"`;return[`browser_act: ambiguous target \u2014 ${t.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...t.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
|
|
417
417
|
`)}function Abe(e){return e.kind==="semantic"?{kind:"semantic",text:$j(e.text),...e.role!==void 0?{role:e.role}:{}}:e.kind==="element_id"?{kind:"element_id",elementId:e.elementId}:{kind:"selector",selectorHash:Dj(e.selector)}}function Cbe(e={}){return async(t,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_act aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0,failureClass:Zt(n)}}let o=Rbe(t);if("error"in o)return{content:o.error,isError:!0};let i=Abe(o.target),s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let a;try{if(e.getBrowserProvider)a=await e.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(Zs(),Qs));a=await c()}}catch(c){let u=c instanceof Error?c.message:String(c);return dn(u)?{content:jn(u),isError:!0}:{content:`browser_act failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let c=await a.act({sessionId:s,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),u=Date.now()-l;if("outcome"in c){if(c.outcome==="ambiguous_target")return vt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:u}),{content:xbe(c.query,c.candidates),isError:!0};if(c.outcome==="blocked_by_policy")return vt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:u}),{content:`browser_act blocked: ${c.reason}`,isError:!0,failureClass:"policy-refusal"}}return vt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:c.url,urlAfter:c.url,status:"ok",durationMs:u,...c.screenshotPath!==null?{screenshotPath:c.screenshotPath}:{}}),{content:JSON.stringify(c,null,2)}}catch(c){let u=Date.now()-l,d=c instanceof Error?c.message:String(c);vt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:d,recoverable:!1}});let p=Vy(c);return{content:`browser_act failed: ${d}`,isError:!0,...p?{failureClass:p}:{}}}}}var kH,TH,EH,RH=y(()=>{"use strict";Gy();L();ci();pe();ea();kH=["click","fill","press","select","hover","scroll_to","wait_for"],TH=["semantic","element_id","selector"];EH=Cbe()});function _be(e){if(typeof e.kind!="string"||!xH.includes(e.kind))return{error:`browser_screenshot: "target.kind" must be one of ${xH.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e.kind)})`};let t=e.kind;return t==="semantic"?typeof e.text!="string"||e.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:e.text,...typeof e.role=="string"&&e.role.length>0?{role:e.role}:{}}:t==="element_id"?typeof e.element_id!="string"||e.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:e.element_id}:typeof e.selector!="string"||e.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:e.selector}}function Ibe(e){if(e!=null&&typeof e!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!e)return{};let t=e,n;if(t.target!==void 0){if(!t.target||typeof t.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=_be(t.target);if("error"in o)return o;n=o}let r;if(t.full_page!==void 0){if(typeof t.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=t.full_page}return{target:n,fullPage:r}}function Pbe(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_screenshot aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=Ibe(t);if("error"in o)return{content:o.error,isError:!0};let i=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let s;try{if(e.getBrowserProvider)s=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(Zs(),Qs));s=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return dn(c)?{content:jn(c),isError:!0}:{content:`browser_screenshot failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await s.screenshot({sessionId:i,target:o.target,fullPage:o.fullPage}),c=Date.now()-a,{dataBase64:u,mediaType:d,...p}=l;return vt(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:c,screenshotPath:p.path}),p.width>fC||p.height>fC?{content:JSON.stringify({...p,imageOmitted:`dimensions ${p.width}x${p.height}px exceed the ${fC}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(p,null,2),image:{mediaType:d,data:u}}}catch(l){let c=Date.now()-a,u=l instanceof Error?l.message:String(l);return vt(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:u,recoverable:!1}}),{content:`browser_screenshot failed: ${u}`,isError:!0}}}}var xH,fC,AH,CH=y(()=>{"use strict";L();pe();ea();xH=["semantic","element_id","selector"],fC=8e3;AH=Pbe()});function Mbe(e={}){return async(t,n,r)=>{if(n.aborted){let a=n.reason;return{content:`browser_close aborted: ${a instanceof Error?a.message:String(a??"aborted")}`,isError:!0}}let o=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let i;try{if(e.getBrowserProvider)i=await e.getBrowserProvider();else{let{getBrowserProvider:a}=await Promise.resolve().then(()=>(Zs(),Qs));i=await a()}}catch(a){let l=a instanceof Error?a.message:String(a);return dn(l)?{content:jn(l),isError:!0}:{content:`browser_close failed to get provider: ${l}`,isError:!0}}let s=Date.now();try{await i.close({sessionId:o});let a=Date.now()-s;return vt(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:a}),{content:"Browser session closed."}}catch(a){let l=Date.now()-s,c=a instanceof Error?a.message:String(a);return vt(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:c,recoverable:!1}}),{content:`browser_close failed: ${c}`,isError:!0}}}}var _H,IH=y(()=>{"use strict";L();pe();ea();_H=Mbe()});function xb(e,t){let n=e!==void 0?gy(e,t):t!==void 0?gy("default",t):PB,r=t!==void 0?nA(t):VB,o=t!==void 0?oA(t):nU,i=t!==void 0?Qx(t):OB,s=t!==void 0?Zx(t):BB,a=t!==void 0?eA(t):HB,l=t!==void 0?tA(t):GB,c=t!==void 0?sA(t):oU,u=WA(),d=M1(t);return new Map([["bash",n],["read_file",i],["extract_document",s],["write_file",a],["edit_file",l],["glob",r],["grep",o],["list_directory",c],["send_telegram",mj],["web_scrape",i1],["create_schedule",c1],["list_schedules",u1],["get_schedule_history",d1],["cancel_schedule",p1],["read_witness",uH],["search_witness",dH],["worktree",d],["terminal_font_size",u],["config_get",Y1],["config_set",J1],["ask_question",gH],["browser_open",bH],["browser_observe",wH],["browser_act",EH],["browser_screenshot",AH],["browser_close",_H]])}var gC=y(()=>{"use strict";MB();DB();UB();WB();qB();YB();rU();iU();fj();s1();m1();GA();O1();X1();pH();hH();SH();vH();RH();CH();IH()});function Ab(e){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${e}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${e}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
|
|
418
418
|
`)}var hC=y(()=>{"use strict"});function Dbe(e){switch(e){case"bypassPermissions":return"Approve \u2014 implement now (restore bypass mode: no prompts, read/write any path)";case"acceptEdits":return"Approve \u2014 implement now (restore accept-edits mode: edits auto-approved)";case"dontAsk":case"auto":return"Approve \u2014 implement now (restore your previous mode: no approval prompts)";default:return"Approve \u2014 implement now (restore default mode: writes ask for confirmation, contained to the workspace)"}}function _b(e){return async(t,n,r)=>{let o=e.getPrePlanMode()??"default",i=Dbe(o),a={serverName:"agent",origin:"agent",type:"choice",message:"Plan ready. How do you want to proceed? (Your plan is in the conversation above.)",choices:o==="bypassPermissions"?[i,yC]:[i,Obe,yC]},l=await Xe.route(a,{signal:n,...r?.sessionId!==void 0?{sessionId:r.sessionId}:{}});if(l.action!=="accept")return{content:"Plan exit not confirmed (the user did not approve). Stay in plan mode \u2014 keep refining the plan; do not implement. Call exit_plan_mode again when ready."};let c=typeof l.content?.value=="string"?l.content.value:"";if(c.startsWith("Keep")||c===yC)return{content:"User chose to keep planning. Stay in plan mode and refine the plan; do not implement. Call exit_plan_mode again when ready."};let u=c.includes("bypass")?"bypassPermissions":o,d=zg(r?.resolveBase??r?.cwd??process.cwd());return e.requestImplementSeed(Ab(d),u),{content:`Plan approved (mode=${u}). The implementation instruction will follow as a new message \u2014 end your turn now.`}}}var Rn,Obe,yC,Cb,ra=y(()=>{"use strict";Wr();hC();H();Rn="exit_plan_mode",Obe="Approve \u2014 implement now (bypass mode: no prompts, read/write any path)",yC="Keep planning";Cb={name:Rn,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.
|
|
@@ -1978,7 +1978,7 @@ ${E}
|
|
|
1978
1978
|
${T}`})}return{fileBlocks:l,warnings:c}}function rte(e){let t=e.replace(/\s+/g," ").trim();return t.length<=60?t:`${t.slice(0,59)}\u2026`}async function ote(e,t,n){let r=t?.peekQueuedText(),o=r!==void 0?{text:r.text,claimed:!1}:void 0;r!==void 0&&t?.reserveQueued?.(r);let i;try{i=await e.promoteActiveForeground(o)}catch(s){throw r!==void 0&&t?.releaseQueued?.(r),s}if(o?.claimed===!0&&t!==null&&r!==void 0){try{await n?.(o.text)}catch{}return t.dropQueued(r),{jobs:i,flushedText:o.text,flushedPreview:r.preview}}return r!==void 0&&t?.releaseQueued?.(r),{jobs:i}}L();B();L();st();B();Ea();function ite(){return{toolStartTimes:new Map,subagentStartTimes:new Map,subagentLabels:new Map}}function ste(e,t){Fe()&&(t.pending||e.toolStartTimes.has(t.toolUseId)||e.toolStartTimes.set(t.toolUseId,Date.now()))}function ate(e,t,n,r){if(!Fe())return;let o=e.toolStartTimes.get(t.toolUseId),i=o!==void 0?Date.now()-o:void 0;e.toolStartTimes.delete(t.toolUseId);let s=Me(n??"tool"),a=t.isError?m.error("err"):m.success("ok"),l=i!==void 0?` \xB7 ${we(i)}`:"";r.fn(m.dim(` \u25E6 ${s}${l} \xB7 `)+a)}function lte(e,t,n,r){if(!Fe())return;let{subagentId:o,agentType:i}=n,s=Me(i??o);if(e.subagentStartTimes.has(o)||(e.subagentStartTimes.set(o,Date.now()),e.subagentLabels.set(o,s),r.fn(m.dim(` \u25E6 worker ${s} started`))),t.type==="done"||t.type==="error"){let l=e.subagentStartTimes.get(o),c=l!==void 0?Date.now()-l:void 0;e.subagentStartTimes.delete(o),e.subagentLabels.delete(o);let u=c!==void 0?` \xB7 ${we(c)}`:"",d=t.type==="error"?m.error("failed"):m.success("done");r.fn(m.dim(` \u25E6 worker ${s}${u} \xB7 `)+d)}}var yE=class{state;writer;ttfb;constructor(t,n){this.state=ite(),this.writer=t,this.ttfb=n}onToolStart(t){ste(this.state,t)}onToolResult(t,n){ate(this.state,t,n,this.writer)}onSubagentEvent(t,n){lte(this.state,t,n,this.writer)}onFirstContent(t){this.ttfb.waitingLineEmitted&&(this.ttfb.waitingLineEmitted=!1,t.write("\r\x1B[2K"))}};function cte(e){return{startedAt:e,received:!1,waitingLineEmitted:!1}}function ute(e){return e.received?{}:{turnStartedAt:e.startedAt}}function dte(e,t,n){let r=t.type==="chunk"&&t.chunk.type==="content"&&!n;return r&&(e.received=!0),r}function pte(e,t=process.stdout,n){if(!Fe()||!t.isTTY)return;(e?.fn??console.log)(m.dim(" \u25E6 waiting for response\u2026")),n&&(n.waitingLineEmitted=!0,e&&(n.plainHooks=new yE(e,n)))}ce();B();var mBe=3e3;async function mte(e,t){if(!e)return t;let n=Date.now();if(n-t<mBe)return t;try{let r=e();r instanceof Promise&&await r}catch(r){Be()&&console.error(" "+m.error("onContextProgress (status refresh) failed:"),r)}return n}B();ce();St();as();var fBe="Keep waiting \u2014 auto-resume in progress",fte="Switch model / provider (type /model after)",gBe="Stop waiting";async function gte(e){let{event:t,session:n,borrowedCompositor:r,pickerRef:o,completionWriter:i,disposeRendererOnce:s,setPausedState:a,onPauseInterrupt:l}=e;if(a?.(!0),await s(),r&&t.autoResume===!0){let c=new AbortController;o.abort=c;let u=t.resetsAt?t.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,d=u?`Keep waiting \u2014 auto-resumes at ${u}`:fBe,p=[m.warning(" \u23F3 Usage limit reached.")+(u?m.dim(` Auto-resumes at ${u}.`):""),m.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];hn(r,{header:p,options:[d,fte,gBe],signal:c.signal,initialIndex:0}).then(f=>{if(o.abort=null,!f)return;let g=f[0];g===void 0||g===d||(l(),g===fte&&(i??{fn:console.log}).fn(m.dim(" Hint: type /model <name> to switch, then send your message again.")),n.interrupt().catch(h=>{Be()&&console.error(" "+m.error("picker pause-interrupt session.interrupt() failed:"),h)}))}).catch(f=>{Be()&&console.error(" "+m.error("picker promise rejected:"),f)})}else(i??{fn:console.log}).fn(UF({reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}}))}Ik();async function hte(e,t,n,r,o="summary",i,s){let a=q5(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0);let l=Date.now(),c=cte(l);pte(i,process.stdout,c),Mu(process.stdout,wf(process.cwd(),!0));let u="",d=0,p=!1,f=!1,g=!1,h=!1,b=!1,S,w=!1,k=!1,E={abort:null},T=0,R=[],I=new Map,C=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,x=()=>{let W=r.subagentControl;W?.hasPromotableForeground()&&ote(W,_,r.onQueuedUserMessage).then(({jobs:G,flushedText:j,flushedPreview:K})=>{let Q=(i??{fn:console.log}).fn;for(let P of G)Q(m.dim(` \u2192 subagent backgrounded as ${P.jobId}: ${P.label}`));j!==void 0&&Q(m.dim(` \u2192 queued message sent to this turn: ${rte(K??j)}`))}).catch(()=>{})},_=r.getCompositor?r.getCompositor():null,M=()=>new od({out:id(i),thinkingMode:o,...C?{activeSkillName:C}:{},onCancel:()=>{t.interrupt().catch(W=>{Be()&&console.error(" "+m.error("session.interrupt() failed:"),W)})},...r.subagentControl?{onBackground:x}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},..._?{compositor:_}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{},...ute(c)}),D=M(),$=async()=>{if(!h){h=!0;try{await D.dispose()}catch{}}},U=async()=>{await D.arm();let W=D.getCompositor();if(i&&W){let G=W;i.fn=j=>G.commitAbove(j),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(W),r.setInterruptNotifier?.(G=>D.setInterrupting(G)),r.rearmStatus?.()};try{_?_.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{w=!0,D.setSoftStopping(!0),t.interrupt().catch(F=>{Be()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),F)});let P=r.subagentControl;P?.hasActiveForeground()&&P.cancelActiveForeground().catch(F=>{Be()&&console.error(" "+m.error("soft-stop cancelActiveForeground() failed:"),F)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{k=!0,t.interrupt().catch(P=>{Be()&&console.error(" "+m.error("pause-interrupt session.interrupt() failed:"),P)})}),await U(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(x);let{fileBlocks:W,warnings:G}=nte(e.text,{rootDir:process.cwd()});for(let P of G)(i??{fn:console.log}).fn(m.dim(` @-file: ${P}`));if(e.attachments.length>0&&(await t.waitForInitialization(),t.sessionId===void 0))throw new Error("CLI session initialized without a session id");let j=W.length>0||e.attachments.length>0?await tte(e.text,e.attachments,void 0,W,t.sessionId):e.text,K=t.sendMessageStream(j);if(await kc((P,F)=>{D.process(P,F),F&&c.plainHooks?.onSubagentEvent(P,F)},async()=>{for await(let P of K){if(w||k)break;let F=dte(c,P,f);if(P.type==="chunk"&&P.chunk.type==="content"?(u=p?Jee(u,P.chunk.content):u+P.chunk.content,p=!1,f=!0):P.type==="message"&&!f&&(u=P.message.content),P.type==="stream_retry"&&(u=u.slice(0,d),p=u.length>0),P.type==="chunk"&&P.chunk.type==="tool_use_detail"){let V=P.chunk,ee={toolName:V.toolName,toolUseId:V.toolUseId,input:V.toolInput,...V.toolInputRaw!==void 0&&{inputRaw:V.toolInputRaw}};I.set(V.toolUseId,ee),R.push(ee),c.plainHooks?.onToolStart(V)}else if(P.type==="chunk"&&P.chunk.type==="tool_result"){let V=P.chunk;d=u.length,p=!0;let ee=I.get(V.toolUseId);ee&&(ee.result=V.content,ee.isError=V.isError,I.delete(V.toolUseId)),c.plainHooks?.onToolResult(V,ee?.toolName),T=await mte(r.onContextProgress,T)}if(P.type==="paused"){await gte({event:P,session:t,borrowedCompositor:_,pickerRef:E,completionWriter:i,disposeRendererOnce:$,setPausedState:r.setPausedState,onPauseInterrupt:()=>{k=!0}});continue}if(P.type==="resumed"){r.setPausedState?.(!1),E.abort?.abort(),E.abort=null;let V=P.hotSwapped&&P.accountId?`\u25B6 Resumed on ${P.accountId}`:"\u25B6 Resumed";u="",d=0,p=!1,f=!1,R.length=0,I.clear(),b=!1,S=void 0,g=!1,D=M(),h=!1,await U(),(i??{fn:console.log}).fn(m.success(V));continue}if(P.type==="error"){await $(),Dl(xl(P.error)),g=!0;continue}D.process(P),F&&(c.plainHooks?.onFirstContent(process.stdout),D.notifyFirstContent()),P.type==="done"&&(b=!0,S=P.metadata)}}),await $(),w){let P=i?i.fn:console.log,F=_?_.getPendingCount():0,V=F>0?` \xB7 ${F} queued`:"";P(m.warning(`\u23F8 Stopped${V} \u2014 work so far kept.`)+m.dim(" Send a message to continue.")),P("")}if(k){let P=i?i.fn:console.log;P(m.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),P("")}if(b&&!w&&!k){_a(n,a,u,S,R),r.onTurnComplete&&await r.onTurnComplete(a,u).catch(()=>{}),Pu(process.stdout),ZX(process.stdout,"afk: turn complete");let P=V=>{i?i.fn(V):console.log(V)},F=hE(u);if(F){P(Xee(F,{durationMs:S?.durationMs,totalCostUsd:S?.totalCostUsd,toolCount:R.length})),P("");let V=dQ(R);if(r.onTerminalState)try{r.onTerminalState(F,{doneHasCorroboratingEvidence:V})}catch{}if(n.permissionMode==="autonomous"){let ee=F.kind==="done"&&Wp().verifyDone===!0&&!V;mQ(F,void 0,{unverified:ee})}}if(mD(S,n,P),r.onAfterTurn){let V=r.onAfterTurn();V instanceof Promise&&await V.catch(()=>{})}}}catch(W){await $(),g||Dl(xl(W))}finally{await $(),Mu(process.stdout,wf(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),E.abort?.abort(),E.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}Vi();Xd();var hBe=5e3,yBe=3,bBe="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function SBe(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function yte(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,mascotBar:u,healthRail:d,verdictLedger:p,shellPassthrough:f,bgResultNotifier:g}=s,h=null,b=[];e.session.current.waitForInitialization().then(async _=>{Be()&&(h=RT(_)),await Vf(e.session.current),Be()&&(b=O0())}).catch(()=>{});let S=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,w,k=!1,E=!1,T,R,I,C=(()=>{let _=parseInt(e.options.maxTurns,10);return _>0?_:void 0})(),x=0;g.onInjectable=()=>{x>=yBe||!o.isAwaitingInput()||!o.bufferIsEmpty()||n.pendingSteerRead||(x++,Pu(process.stdout),S={text:bBe,attachments:[]},o.abortPendingRead())};try{for(n.steerReadLine=async _=>{let M=()=>o.abortPendingRead({clearBuffer:!0});if(_?.addEventListener("abort",M,{once:!0}),_?.aborted)return"";try{return(await o.readLine({promptFn:()=>"Steer the agent \u2192 ",onEscape:M})).text}finally{_?.removeEventListener("abort",M)}};;){if(h&&(e.replRenderer.writeLine(h),e.replRenderer.writeLine(""),h=null),b.length>0){for(let P of b)e.replRenderer.writeLine(P);e.replRenderer.writeLine(""),b=[]}let _=f.drainNotifications();for(let{job:P,result:F}of _){let V=F.errorReason===void 0?"\u2713":"\u2717",ee=F.errorReason==="abort"?"killed":F.errorReason==="timeout"?"timed out":F.errorReason==="signal-killed"?"killed by signal":`exit ${F.exitCode??0}`,Pe=Math.max(0,Math.round(F.durationMs/100)/10);e.replRenderer.writeLine(m.dim(` ${V} [${P.id}] ${ee} \xB7 ${Pe}s \xB7 `)+P.command)}let M=g.drainNotifications();for(let{job:P}of M){let F=P.status==="completed"?"\u2713":P.status==="failed"?"\u2717":"\u2298",V=P.endedAt!==void 0?Math.max(0,Math.round((P.endedAt-P.startedAt)/100)/10):0,ee=ie(P.label,60);e.replRenderer.writeLine(m.dim(` ${F} [${P.jobId}] subagent ${P.status} \xB7 ${V}s \xB7 `)+ee)}let D=l.renderIfChanged(e.stats.sessionId);if(D.length>0){for(let P of D)e.replRenderer.writeLine(P);e.replRenderer.writeLine("")}let $,U,W=n.pendingSteerRead;if(W){let P=await W;n.pendingSteerRead===W&&(n.pendingSteerRead=null),P?.trim()&&(n.pendingSteerText=P)}if(n.pendingSteerText&&(S={text:n.pendingSteerText,attachments:[]},n.pendingSteerText=null),S===void 0){let P=await e.session.current.takePendingPlanExitSeed();P!==void 0&&(e.stats.permissionMode=P.mode,S={text:P.message,attachments:[]})}if(S!==void 0){let P=S;S=void 0;let F=gd(e.stats.permissionMode),V=Da({buffer:P.text,promptText:F,isTTY:!!process.stdout.isTTY,attachmentSummary:Ku([...P.attachments])});e.replRenderer.writeLine(V),$=P.text.trim(),U=P.attachments}else{let P=w;w=void 0;let F=await o.readLine({promptFn:()=>gd(e.stats.permissionMode),...P!==void 0?{initialBuffer:P}:{},primePromptSuggestion:!0,onSigint:r,onShiftTab:()=>{uE(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});$=F.text.trim(),U=F.attachments}if(!$&&U.length===0)continue;if($.startsWith("!")){let P=/^(0|false|off|no)$/i.test(v.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!P&&(k||(k=!0,e.replRenderer.writeLine(m.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await f.dispatch($))){e.statusLine.rearm();continue}}let G=!1;if($.startsWith("/")){let P=await n6($,e.slashCtx,U);if(P.handled){if(P.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if(($==="/clear"||$.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),p.reset(),T=void 0),P.result!==null&&typeof P.result=="object"&&"kind"in P.result&&P.result.kind==="submit"){S={text:P.result.message,attachments:U??[]},e.statusLine.rearm();continue}if(P.result!==null&&typeof P.result=="object"&&"kind"in P.result&&P.result.kind==="prefill"){w=P.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}G=!0}a.push($),await SBe(e,$);let j=$;if(G){let P=aM($);if(P){let F=P.name.replace(/^\//,"").split(":").pop()??"";if(F&&C0(F)){let V={skillName:F,rawArgs:P.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},ee=e.session.current.sessionId,Pe=Va(ee),oe=Date.now();N(`[afk trace] preflight.start commandName=${F}`);let ke=!1,Ke=await za(V,{cwd:e.stats.cwd??process.cwd(),artifactDir:Pe},On=>{Be()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${F}) failed: `)+(On instanceof Error?On.message:String(On)))});ke=Ke!==null,N(`[afk trace] preflight.end commandName=${F} durationMs=${Date.now()-oe} success=${ke}`),j=P0(Ke?.manifestBlock,$)}}}let K=f.drainInjections();K.length>0&&(j=K+j);let Q=g.drainInjections();if(Q.length>0&&(j=Q+j),T!==void 0&&(j=T+`
|
|
1979
1979
|
|
|
1980
1980
|
`+j,T=void 0),e.hookRegistry)try{let P={event:"UserPromptSubmit",prompt:j,sessionId:e.stats.sessionId},F=await e.hookRegistry.dispatch(P);F.injectContext&&(j=F.injectContext+j)}catch(P){if(P instanceof xe){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+(P.reason?m.dim(`: ${ae(P.reason)}`):"")),e.statusLine.rearm();continue}if(P instanceof Or){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+m.dim(`: handler timed out after ${P.timeoutMs}ms`)),e.statusLine.rearm();continue}throw P}if(R=void 0,I=void 0,zF(),XF(),await hte({text:j,attachments:U},e.session.current,e.stats,{setInFlight(P){n.turnInFlight=P},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(P){await t.appendUser(P)},async onQueuedUserMessage(P){await t.appendQueuedUser(P)},async onTurnComplete(P,F){if(await t.appendTurn(P,F),e.stats.sessionId)try{zi(e.stats)}catch(V){E||(E=!0,e.replRenderer.writeLine(m.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(V instanceof Error?V.message:String(V))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.repaint(Xn(e.stats,e.contextSampler,e.gitStatusSampler,C)),e.statusLine.rearm(),c?.repaint("observing"),d?.update(e.stats)},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(P,F)=>{p?.push(P),R=P.kind,I=F?.doneHasCorroboratingEvidence},setActiveCompositor:P=>{n.activeCompositor=P,P===null&&n.interruptPickerAbort&&(n.interruptPickerAbort.abort(),n.interruptPickerAbort=null)},setInterruptNotifier:P=>{n.notifyInterrupting=P},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:P=>o.setBackgroundHandler(P),setSoftStopHandler:i,setPausedState:P=>o.setPausedState(P),setPauseInterruptHandler:P=>o.setPauseInterruptHandler(P),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(Xn(e.stats,e.contextSampler,e.gitStatusSampler,C)),d?.update(e.stats,e.contextSampler.getRatio())},...c?{onStageChange:(P,F)=>{c.repaint(P),u?.onStage(P,F)}}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(gd(e.stats.permissionMode))),e.hookRegistry)try{let P=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...R!==void 0?{terminalState:R}:{},...I!==void 0?{doneHasCorroboratingEvidence:I}:{}},void 0,hBe);P.injectContext&&P.injectContext.trim().length>0&&(T=P.injectContext)}catch(P){if(P instanceof _t)throw P;P instanceof Or?(N("[stop hook] handler timed out"),e.completionWriter.fn(m.dim(" [stop hook] timed out"))):P instanceof xe?e.completionWriter.fn(m.dim(` [stop hook] blocked: ${ae(P.reason??"no reason given")}`)):N("[stop hook] unexpected error: "+String(P))}}}finally{n.steerReadLine=null,n.pendingSteerRead=null,n.pendingSteerText=null}}function wBe(e,t){if(e!==void 0){let n=e.toLowerCase();return!(n==="0"||n==="false"||n==="off"||n==="no")}return typeof t=="boolean"?t:!0}async function bte(e,t,n,r){let o=await uee(),i=new cE({rl:e.rl,history:o,statusLine:e.statusLine}),s=wBe(v.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await Mee(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar,getMascotBar:()=>a?.mascotBar});a=Yee(e,n);let c=a;e.slashCtx.suspendFooter=()=>{c.bgStatusBar.stop(),c.mascotBar.stop(),c.healthRail.stop(),e.statusLine.stop()},e.slashCtx.resumeFooter=()=>{e.statusLine.start(),c.healthRail.start(),c.mascotBar.start(),c.bgStatusBar.start(),c.bgStatusBar.redraw()},await yte(e,t,n,r,i,l,a,o),await e.resolveWorktreeDisposition?.(!0)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.bgResultNotifier.dispose(),a?.healthRail.stop(),a?.loopStageBar.stop(),a?.mascotBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await i.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}$p();dc();import{execFile as vBe}from"node:child_process";import{dirname as kBe,isAbsolute as TBe,resolve as EBe}from"node:path";import{promisify as RBe}from"node:util";var Ste=RBe(vBe),xBe=3e3,ABe=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function CBe(){let t=(await Ste("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=TBe(t)?t:EBe(process.cwd(),t);return kBe(n)}async function wte(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await CBe()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),xBe)});try{let o=Kn({execFile:Ste,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),i=await Promise.race([o,r]);if(i==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let s=i;return s.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:s.candidates.filter(c=>ABe.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Rh();$p();import{promises as _Be}from"node:fs";import{dirname as IBe,join as Tte}from"node:path";import{randomBytes as PBe}from"node:crypto";var MBe=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
|
|
1981
|
-
`),vte=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,gD=30,OBe=1024,DBe=8e3,$Be="haiku";async function FBe(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=UBe(n,OBe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??DBe),s=t.signal?jBe([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await Ul({token:t.token,model:t.model??$Be,system:MBe,user:r,maxTokens:32,signal:s})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=LBe(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=IBe(t.worktreePath);return await NBe(l,c)}function LBe(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(vte.test(t)&&t.length<=gD)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>gD)break;o=s}return vte.test(o)?o:null}async function NBe(e,t){if(!await BBe(Tte(t,e)))return e;let n=PBe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,gD-5)}-${n}`}async function BBe(e){try{return await _Be.access(e),!0}catch{return!1}}function UBe(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function jBe(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function Ete(e){let t,n,r=Tte(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await FBe(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${Py(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return kte(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return kte(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function kte(e,t){e&&e.setCwd(t),HBe(t)}function HBe(e){try{process.chdir(e)}catch{}}ht();Rt();El();ro();H();import{spawn as xte}from"child_process";import{existsSync as Ate,mkdirSync as zBe,readFileSync as Cte,unlinkSync as Rte,writeFileSync as _te}from"fs";import{get as VBe}from"https";import{join as Ite}from"path";import{readFileSync as WBe}from"fs";import{dirname as KBe,join as GBe}from"path";import{fileURLToPath as qBe}from"url";function so(){try{return"5.
|
|
1981
|
+
`),vte=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,gD=30,OBe=1024,DBe=8e3,$Be="haiku";async function FBe(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=UBe(n,OBe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??DBe),s=t.signal?jBe([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await Ul({token:t.token,model:t.model??$Be,system:MBe,user:r,maxTokens:32,signal:s})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=LBe(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=IBe(t.worktreePath);return await NBe(l,c)}function LBe(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(vte.test(t)&&t.length<=gD)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>gD)break;o=s}return vte.test(o)?o:null}async function NBe(e,t){if(!await BBe(Tte(t,e)))return e;let n=PBe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,gD-5)}-${n}`}async function BBe(e){try{return await _Be.access(e),!0}catch{return!1}}function UBe(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function jBe(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function Ete(e){let t,n,r=Tte(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await FBe(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${Py(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return kte(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return kte(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function kte(e,t){e&&e.setCwd(t),HBe(t)}function HBe(e){try{process.chdir(e)}catch{}}ht();Rt();El();ro();H();import{spawn as xte}from"child_process";import{existsSync as Ate,mkdirSync as zBe,readFileSync as Cte,unlinkSync as Rte,writeFileSync as _te}from"fs";import{get as VBe}from"https";import{join as Ite}from"path";import{readFileSync as WBe}from"fs";import{dirname as KBe,join as GBe}from"path";import{fileURLToPath as qBe}from"url";function so(){try{return"5.156.0"}catch{}try{let e=KBe(qBe(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(WBe(GBe(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}B();L();var YBe=64*1024,JBe=10800*1e3,XBe=800,QBe=3600*1e3,ZBe="update-check.json",eUe="pending-update.json";function hD(){return Ite(Sl(),ZBe)}function fg(){return Ite(Sl(),eUe)}function yD(){let e=Sl();Ate(e)||zBe(e,{recursive:!0})}function Pte(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),i=n(t).split(".").map(Number),s=Math.max(o.length,i.length);for(let a=0;a<s;a++){let l=o[a]??0,c=i[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function Mte(){try{let e=Cte(hD(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function Ote(){try{yD();let e=`
|
|
1982
1982
|
const https = require('https');
|
|
1983
1983
|
const fs = require('fs');
|
|
1984
1984
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|