agent-afk 5.89.0 → 5.89.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -738,7 +738,7 @@ Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${e}${r}
738
738
 
739
739
  `;return s.toString("utf8")+c+a.toString("utf8")}function uo(e){return Buffer.byteLength(e,"utf8")<=1e5?{content:e,truncated:!1}:{content:xr(e,1e5),truncated:!0}}var P5,_m,wi=T(()=>{"use strict";P5=160;_m=`
740
740
  [output truncated \u2014 command exceeded the 8000000-byte output cap and was terminated]`});import pv from"path";import{dirname as M5}from"path";import{appendFileSync as O5,mkdirSync as $5}from"fs";var po,Im=T(()=>{"use strict";q();po=class{hooks;constructor(t){this.hooks=t}addReadRoot(t,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots();if(!o)return;let i=pv.resolve(t);o.includes(i)||(o.push(i),this.appendAuditLog({action:"grant-read",path:i,source:n,sessionId:r}))}addWriteRoot(t,n="slash",r){this.hooks.ensureInitialized?.();let o=this.hooks.getReadRoots(),i=this.hooks.getWriteRoots();if(!o||!i)return;let s=pv.resolve(t);o.includes(s)||o.push(s),i.includes(s)||(i.push(s),this.appendAuditLog({action:"grant-write",path:s,source:n,sessionId:r}))}revokeRoot(t,n="slash",r){let o=this.hooks.getReadRoots();if(!o)return;let i=pv.resolve(t),s=this.hooks.getProtectedRoot();if(s!==void 0&&i===s)return;let a=o.indexOf(i);a!==-1&&o.splice(a,1);let l=this.hooks.getWriteRoots();if(l){let c=l.indexOf(i);c!==-1&&l.splice(c,1)}this.appendAuditLog({action:"revoke",path:i,source:n,sessionId:r})}getGrants(){return{resolveBase:this.hooks.getProtectedRoot(),readRoots:this.hooks.getReadRoots()?.slice()??[],writeRoots:this.hooks.getWriteRoots()?.slice()??[],allowAll:this.hooks.getAllowAll()}}appendAuditLog(t){try{let n=yp();$5(M5(n),{recursive:!0});let r=JSON.stringify({timestamp:new Date().toISOString(),sessionId:t.sessionId??this.hooks.getDefaultSessionId?.()??null,action:t.action,path:t.path,source:t.source});O5(n,r+`
741
- `)}catch{}}}});var D5,F5,L5,N5,B5,U5,j5,H5,W5,Wt,Si,vi,K5,G5,q5,z5,J5,V5,Y5,X5,Q5,Z5,e3,t3,n3,r3,Zn,Mt,xPe,Kt=T(()=>{"use strict";D5={name:"bash",category:"shell",concurrencySafe:!1,description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run in the user's default shell. Long-running commands should use timeout_ms. Output is capped 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"]}},F5={name:"read_file",category:"read",concurrencySafe:!0,description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},L5={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"]}},N5={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"]}},B5={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"]}},U5={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"]}},j5={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"]}},H5={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).',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)."}},required:["message"]}},W5={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:[]}},Wt={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.
741
+ `)}catch{}}}});var D5,F5,L5,N5,B5,U5,j5,H5,W5,Wt,Si,vi,K5,G5,q5,z5,J5,V5,Y5,X5,Q5,Z5,e3,t3,n3,r3,Zn,Mt,xPe,Kt=T(()=>{"use strict";D5={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"]}},F5={name:"read_file",category:"read",concurrencySafe:!0,description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},L5={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"]}},N5={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"]}},B5={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"]}},U5={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"]}},j5={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"]}},H5={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).',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)."}},required:["message"]}},W5={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:[]}},Wt={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.
742
742
 
743
743
  Parallelize: dispatch multiple \`agent\` calls in a single tool-use turn to run independent investigations concurrently.
744
744
 
@@ -880,7 +880,7 @@ ${n}
880
880
  Remedy: these paths are outside the fork's granted read roots. Re-dispatch with the needed paths inside the child's cwd/worktree, or pass explicit readRoots granting them. If this worker is deliberately confined (e.g. an \`afk farm\` branch worker), this failure is expected \u2014 the paths are outside its assigned scope; widen the scope or narrow the task.`}var da,TP,_3,Bm=T(()=>{"use strict";da="denial-breaker",TP=new Set(["read_file","list_directory","glob","grep"]),_3="Sub-agent path access denied:"});import{createHash as I3}from"node:crypto";function AP(){return{recent:[],firedFingerprints:new Set}}function Um(e){let t;try{t=M3(e.input)}catch{t=String(e.input)}return I3("sha256").update(e.name).update("\0").update(t).digest("hex")}function M3(e){return JSON.stringify(bv(e))??"null"}function bv(e){if(Array.isArray(e))return e.map(bv);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=bv(t[r]);return n}return e}function O3(e,t){let n=0;for(let r of e)r===t&&(n+=1);return n}function CP(e,t){e.recent.push(t),e.recent.length>wv&&e.recent.shift();let n=O3(e.recent,t);return n>=P3&&!e.firedFingerprints.has(t)?(e.firedFingerprints.add(t),{fired:!0,count:n}):{fired:!1,count:n}}var P3,wv,Sv=T(()=>{"use strict";P3=5,wv=20});function D3(e){if(e===null||typeof e!="object"||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))$3.has(n)||(t[n]=r);return t}function zc(e){return Um({...e,input:D3(e.input)})}function F3(e){let t=e.content.split(`
881
881
  `).find(n=>n.trim()!=="")?.trim()??"";return t.length<=_P?t:`${t.slice(0,_P)}\u2026`}var vv,$3,_P,jm,IP=T(()=>{"use strict";Sv();vv=3,$3=new Set(["timeout_ms","timeoutMs","timeout"]),_P=240;jm=class{streaks=new Map;check(t){let n=this.streaks.get(zc(t));return n===void 0||n.count<vv?null:{count:n.count,tool:t.name,result:{content:`Repeat-failure guard: "${t.name}" has already failed ${n.count} times in a row with the same arguments, so this call was NOT executed again. The last failure was: ${n.lastError}
882
882
 
883
- Retrying it verbatim will fail the same way. Fix the underlying cause, change the arguments, use a different tool, or stop and report the blocker.`,isError:!0,failureClass:"repeat-failure"}}}note(t,n){let r=zc(t);if(n.isError!==!0){this.streaks.delete(r);return}let o=this.streaks.get(r);this.streaks.set(r,{count:(o?.count??0)+1,lastError:F3(n)})}streakFor(t){return this.streaks.get(zc(t))?.count??0}}});var ua,kv,N3,Ot,pa=T(()=>{"use strict";ue();Fe();Rm();Sm();xm();uv();wi();Im();ye();yv();kP();Bm();Sv();IP();yv();ua=8,kv=new Set,N3=8,Ot=class{handlers;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;skillExecutor;composeExecutor;classifier;maxConcurrentSafeCalls;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;subagentId;sessionGrantManager;traceWriter;readOnlyBash;maxOutputBytes;repeatBreaker=null;repeatFailureGuard=new jm;denialBreaker=null;suspectedLoopWindow=null;grantManager;constructor(t){this.handlers=t.handlers,this.schemas=t.schemas,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,this.subagentExecutor=t.subagentExecutor,this.skillExecutor=t.skillExecutor,this.composeExecutor=t.composeExecutor,this.classifier=t.concurrencyClassifier??hv,this.maxConcurrentSafeCalls=typeof t.maxConcurrentSafeCalls=="number"&&Number.isFinite(t.maxConcurrentSafeCalls)&&t.maxConcurrentSafeCalls>=1?Math.floor(t.maxConcurrentSafeCalls):N3,this.resolveBase=t.cwd,this._env=t.env,this.sessionId=t.sessionId,this.parentSessionId=t.parentSessionId,this.subagentId=t.subagentId,this.sessionGrantManager=t.sessionGrantManager,this.traceWriter=t.traceWriter,this.readOnlyBash=t.readOnlyBash===!0,this.maxOutputBytes=typeof t.maxOutputBytes=="number"&&Number.isFinite(t.maxOutputBytes)&&t.maxOutputBytes>0?t.maxOutputBytes:void 0,this._allowAll=t.allowAll===!0;let n=t.cwd?[t.cwd]:[];this._readRoots=t.readRoots??n.slice(),this._writeRoots=t.writeRoots??n.slice(),this.grantManager=new po({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,getProtectedRoot:()=>this.resolveBase,getAllowAll:()=>this._allowAll,getDefaultSessionId:()=>this.sessionId})}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{}}}callHandlerContext(t){return{...this.handlerContext,toolUseId:t.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{}}}addReadRoot(t,n="slash"){this.grantManager.addReadRoot(t,n)}addWriteRoot(t,n="slash"){this.grantManager.addWriteRoot(t,n)}revokeRoot(t,n="slash"){this.grantManager.revokeRoot(t,n)}getGrants(){return this.grantManager.getGrants()}setAllowAll(t){this._allowAll=t}setResolveBase(t){let n=this.resolveBase;if(n!==t){if(this.resolveBase=t,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=t:this._readRoots.includes(t)||this._readRoots.push(t);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=t:this._writeRoots.includes(t)||this._writeRoots.push(t)}else this._readRoots.includes(t)||this._readRoots.push(t),this._writeRoots.includes(t)||this._writeRoots.push(t);this.subagentExecutor?.setCwd(t),this.skillExecutor?.setCwd(t),this.composeExecutor?.setCwd(t)}}get toolDefs(){let t=this.permissions?.allowedTools;if(!t)return this.schemas;let n=new Set(t);return this.schemas.filter(r=>n.has(r.name))}async checkReadOnlyBash(t){if(!this.readOnlyBash||t.name!=="bash")return null;let n=t.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=Cm(r);if(!o.mutating)return null;let i=`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff, ls, cat, find, grep).`;return await this.emitPreToolUseBlock(t.name,i),{content:i,isError:!0,failureClass:"permission-denied"}}async emitPreToolUseBlock(t,n){await Zt(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(t){if(kv.has(t.name))return null;let n=vP(t);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<ua?null:{content:`Loop circuit breaker: "${t.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}checkRepeatFailureGuard(t){if(kv.has(t.name))return null;let n=this.repeatFailureGuard.check(t);return n===null?null:(j(`[repeat-failure-guard #723] refused ${n.tool} after ${n.count} identical failures`),n.result)}observeSuspectedLoop(t){if(this.parentSessionId===void 0)return;this.suspectedLoopWindow===null&&(this.suspectedLoopWindow=AP());let n=Um(t),r=CP(this.suspectedLoopWindow,n);r.fired&&re(this.traceWriter,{phase:"suspected_loop",metadata:{tool:t.name,count:r.count,windowSize:wv}})}recordForkReadDenial(t,n,r){if(this.parentSessionId===void 0||!TP.has(t.name)||!EP(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let i=xP(t);return o.deniedPaths.includes(i)||o.deniedPaths.push(i),this.denialBreaker=o,o.count<5?r:{content:RP(o.deniedPaths,o.count),isError:!0,failureClass:da}}resetDenialBreaker(){this.denialBreaker=null}async runCanUseTool(t){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(t.name,t.input??{},{signal:t.signal,toolUseID:t.id})}catch(r){let o=`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`;return await this.emitPreToolUseBlock(t.name,o),{content:o,isError:!0,failureClass:"permission-denied"}}if(n.behavior==="deny"){let r=n.message||`Tool "${t.name}" denied by permission policy`;return await this.emitPreToolUseBlock(t.name,r),{content:r,isError:!0,failureClass:"permission-denied"}}return n.updatedInput!==void 0&&(t.input=n.updatedInput),null}async execute(t){if(t.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:"abort"};if(this.hookRegistry){let l={event:"PreToolUse",toolName:t.name,input:t.input,...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{}};try{await ov(this.hookRegistry,l,{signal:t.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(c){if(c instanceof Ee)return this.recordForkReadDenial(t,c.reason,{content:`Tool "${t.name}" blocked by PreToolUse hook: ${c.message}`,isError:!0,failureClass:"hook-block"});throw c}}let n=cv(t.name,this.permissions);if(!n.allowed){let l=n.reason??`Tool "${t.name}" is not permitted`;return await this.emitPreToolUseBlock(t.name,l),{content:l,isError:!0,failureClass:"permission-denied"}}let r=await this.runCanUseTool(t);if(r)return r;let o=await this.checkReadOnlyBash(t);if(o)return o;let i=this.checkRepeatCircuitBreaker(t);if(i)return i;let s=this.checkRepeatFailureGuard(t);if(s)return s;this.observeSuspectedLoop(t);let a=await this.executeCore(t);return this.repeatFailureGuard.note(t,a),a.isError!==!0&&this.resetDenialBreaker(),a}async executeBatch(t){if(t.length===0)return[];if(t.length===1)return[await this.execute(t[0])];let n=new Array(t.length),r=new Set;for(let s=0;s<t.length;s++){let a=t[s];if(a.signal.aborted){n[s]={content:"Tool call aborted",isError:!0,failureClass:"abort"},r.add(s);continue}if(this.hookRegistry){let f={event:"PreToolUse",toolName:a.name,input:a.input,...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{}};try{await ov(this.hookRegistry,f,{signal:a.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(g){if(g instanceof Ee){n[s]=this.recordForkReadDenial(a,g.reason,{content:`Tool "${a.name}" blocked by PreToolUse hook: ${g.message}`,isError:!0,failureClass:"hook-block"}),r.add(s);continue}throw g}}let l=cv(a.name,this.permissions);if(!l.allowed){let f=l.reason??`Tool "${a.name}" is not permitted`;await this.emitPreToolUseBlock(a.name,f),n[s]={content:f,isError:!0,failureClass:"permission-denied"},r.add(s);continue}let c=await this.runCanUseTool(a);if(c){n[s]=c,r.add(s);continue}let d=await this.checkReadOnlyBash(a);if(d){n[s]=d,r.add(s);continue}let u=this.checkRepeatCircuitBreaker(a);if(u){n[s]=u,r.add(s);continue}let m=this.checkRepeatFailureGuard(a);if(m){n[s]=m,r.add(s);continue}this.observeSuspectedLoop(a)}let o=t.map((s,a)=>({call:s,originalIndex:a})).filter((s,a)=>!r.has(a));if(o.length===0)return n;let i=SP(o.map(s=>s.call),this.classifier);for(let s of i){if(s.isConcurrencySafe){let l=[...s.indices];for(;l.length>0;){let c=new Map,d=[],u=[];for(let f of l){let{call:g,originalIndex:h}=o[f],y=this.checkRepeatFailureGuard(g);if(y){n[h]=y;continue}if(kv.has(g.name)){d.push(f);continue}let b=zc(g),w=vv-this.repeatFailureGuard.streakFor(g),S=c.get(b)??0;S<w?(c.set(b,S+1),d.push(f)):u.push(f)}l=u;let m=await la(d,this.maxConcurrentSafeCalls,async f=>{let{call:g,originalIndex:h}=o[f];return g.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:"abort"},originalIndex:h}:{result:await this.executeCore(g),originalIndex:h}});for(let f of m)if(f.status==="fulfilled")n[f.value.originalIndex]=f.value.result;else{let g=f.reason instanceof Error?f.reason.message:String(f.reason),h=d[m.indexOf(f)];n[o[h].originalIndex]={content:`Tool execution error: ${g}`,isError:!0}}for(let f of d){let{call:g,originalIndex:h}=o[f],y=n[h];y!==void 0&&y.failureClass!=="abort"&&this.repeatFailureGuard.note(g,y)}}}else for(let l of s.indices){let{call:c,originalIndex:d}=o[l];if(c.signal.aborted){n[d]={content:"Tool call aborted",isError:!0,failureClass:"abort"};continue}let u=this.checkRepeatFailureGuard(c);if(u){n[d]=u;continue}let m=await this.executeCore(c);n[d]=m,this.repeatFailureGuard.note(c,m)}let a=s.indices.length;s.indices.forEach((l,c)=>{let d=n[o[l].originalIndex];d&&(d.batchIndex=c+1,d.batchSize=a)})}return n.some(s=>s!==void 0&&s.isError!==!0)&&this.resetDenialBreaker(),n}async executeCore(t){let n=await this.executeCoreInner(t);return this.applyOutputCap(n)}applyOutputCap(t){let n=this.maxOutputBytes;if(n===void 0)return t;let r=Buffer.byteLength(t.content,"utf8");return r<=n||(t.content=xr(t.content,n),t.truncated=!0,j(`[output-cap #661] fork tool result capped: original=${r}B capped=${Buffer.byteLength(t.content,"utf8")}B (cap=${n}B)`)),t}async executeCoreInner(t){if(t.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.subagentExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Agent tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}if(t.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.skillExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Skill tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}if(t.name==="compose"){let s=await this.executeCompose(t);return this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}let n=this.handlers.get(t.name);if(!n)return{content:`Unknown tool "${t.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r,o=!1,i="";try{r=await n(t.input,t.signal,this.callHandlerContext(t))}catch(s){o=!0,i=s instanceof Error?s.message:String(s),r={content:`Tool execution error: ${i}`,isError:!0}}return o?this.firePostToolUseFailure(t.name,i,t.signal,t.input):this.firePostToolUse(t.name,r.content,t.signal,t.input,r),r}async executeCompose(t){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(t)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(t,n,r,o,i){if(!this.hookRegistry)return;let s={event:"PostToolUse",toolName:t,output:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{},...i?.incomplete===!0?{incomplete:!0}:{},...i?.incompleteReason?{incompleteReason:i.incompleteReason}:{}};KI(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(t,n,r,o){if(!this.hookRegistry)return;let i={event:"PostToolUseFailure",toolName:t,error:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};GI(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(s=>{j(`firePostToolUseFailure outer catch (tool=${t}): ${String(s)}`)})}}});function V3(e){let t=e.match(B3);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Y3(e){let t=e.match(U3);if(!t)return null;let n=parseInt(t[1]??"0",10);return{runner:"jest",passed:parseInt(t[2]??"0",10),failed:n}}function X3(e){let t=e.match(j3);if(!t)return null;if(t[2]!==void 0){let n=parseInt(t[2],10),r=parseInt(t[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return t[4]!==void 0?{runner:"pytest",passed:parseInt(t[4],10),failed:0}:null}function Q3(e){let t=e.match(H3);if(!t)return null;let n=parseInt(t[1]??"0",10),r=e.match(W3),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function Z3(e){let t=[...e.matchAll(K3)];if(t.length===0)return null;let n=0,r=0;for(let o of t)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function eX(e){let t=e.match(G3);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function tX(e){let t=e.match(q3);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function nX(e){let t=e.match(z3);if(t)return{runner:"phpunit",passed:parseInt(t[1]??"0",10),failed:0};let n=e.match(J3);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function Tv(e){return V3(e)??Y3(e)??X3(e)??Q3(e)??Z3(e)??eX(e)??tX(e)??nX(e)??null}var B3,U3,j3,H3,W3,K3,G3,q3,z3,J3,PP=T(()=>{"use strict";B3=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,U3=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,j3=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,H3=/(\d+)\s+passing/,W3=/(\d+)\s+failing/,K3=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,G3=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,q3=/(\d+) examples?, (\d+) failures?/,z3=/OK \((\d+) tests?/,J3=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/});function Rr(e){return e.replace(MP,"").replace(rX," ").trim()}function er(e){return e.replace(MP,"")}var MP,rX,fo=T(()=>{"use strict";MP=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,rX=/[\x00-\x1F\x7F-\x9F]/g});import{statSync as oX}from"node:fs";function Jc(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.code==="ENOENT"&&typeof t.syscall=="string"&&t.syscall.startsWith("spawn")}function iX(e){if(e===void 0)return!1;try{return oX(e),!1}catch{return!0}}function ma(e,t){let n=e instanceof Error?e.message:typeof e?.message=="string"?String(e.message):String(e);return Jc(e)&&iX(t)?`working directory does not exist: ${t} (deleted worktree?) \u2014 underlying: ${n}`:n}var Ev=T(()=>{"use strict"});function tr(e){if(OP)return;OP=!0;let t=e instanceof Error?e.message:String(e);console.warn(`[afk-home] Malformed AFK home/state env var ignored while deriving the credential floor: ${t}. The relocated tree is NOT protected \u2014 the default ~/.afk entries still apply. Fix the env var to restore coverage.`)}var OP,Vc=T(()=>{"use strict";OP=!1});import{statSync as Rv}from"node:fs";import{homedir as sX}from"node:os";import{basename as aX,dirname as DP,join as lX}from"node:path";function FP(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function cX(e){let t=aX(e),n=t===t.toLowerCase()?t.toUpperCase():t.toLowerCase();if(n===t)return;let r;try{r=Rv(e)}catch{return}let o=xv.get(r.dev);if(o!==void 0)return o;try{let i=Rv(lX(DP(e),n)),s=r.dev===i.dev&&r.ino===i.ino;return xv.set(r.dev,s),s}catch(i){let s=FP(i);return s==="ENOENT"||s==="ENOTDIR"?(xv.set(r.dev,!1),!1):void 0}}function LP(e=sX()){if($P!==void 0)return $P;let t=e;for(;;)try{return Rv(t),cX(t)??!0}catch(n){let r=FP(n);if(r!=="ENOENT"&&r!=="ENOTDIR")return!0;let o=DP(t);if(o===t)return!0;t=o}}function fa(e,t,n=t){if(e===t||e.startsWith(t+"/"))return!0;if(!LP(n))return!1;let r=e.toLowerCase(),o=t.toLowerCase();return r===o||r.startsWith(o+"/")}function Av(e,t){return e.includes(t)?!0:LP(t)?e.toLowerCase().includes(t.toLowerCase()):!1}var $P,xv,Hm=T(()=>{"use strict";xv=new Map});import{realpathSync as NP}from"fs";import{dirname as dX,resolve as Ti,join as Cv}from"path";import{homedir as go}from"os";function pX(){let e=[];try{let t=we();e.push(Be(Ti(Cv(t,"config")))),e.push(Be(Ti(Cv(t,"state"))))}catch(t){tr(t)}try{e.push(Be(Ti(me())))}catch(t){tr(t)}return e}function _v(){let e=k.AFK_WRITE_DENYLIST,t=e?e.split(":").map(r=>Be(Ti(r))).filter(Boolean):[];return[...[...new Set([...uX.map(r=>Be(Ti(r))),...pX()])],...t]}function Be(e){let t=Ti(e);try{return NP(t)}catch{}let n=[],r=t;for(let o=0;o<64;o++){let i=dX(r);if(i===r)break;n.unshift(r.slice(i.length+1)),r=i;try{let s=NP(r);return Cv(s,...n)}catch{}}return t}function Wm(e,t="write_file"){let n=Be(Ti(e));for(let r of _v())if(fa(n,r))throw new Error(`${t}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}var uX,Ei=T(()=>{"use strict";G();q();Vc();Hm();uX=[`${go()}/.ssh`,`${go()}/.aws`,`${go()}/.gnupg`,`${go()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${go()}/.afk/config`,`${go()}/.afk/state`,`${go()}/.npmrc`,`${go()}/.docker/config.json`]});import{basename as mX,dirname as fX,join as Km,relative as gX,resolve as ga,sep as Yc}from"path";import{homedir as qe}from"os";function UP(e){let t=ga(e);return Km(Be(fX(t)),mX(t))}function Pv(e){return e?e.split(":").map(t=>t.trim()).filter(Boolean).map(t=>t==="~"||t.startsWith("~/")?Km(qe(),t.slice(1)):t).map(t=>ga(t)):[]}function yX(){try{return[Be(ga(Km(we(),"config")))]}catch(e){return tr(e),[]}}function bX(){try{let e=we();return ho.filter(t=>t.startsWith(BP)).map(t=>UP(Km(e,t.slice(BP.length))))}catch(e){return tr(e),[]}}function jP(){let e=`${k.AFK_READ_DENYLIST??""}\0${k.AFK_HOME??""}`;if(Xc&&Xc.key===e)return Xc;let t=Pv(k.AFK_READ_DENYLIST).map(r=>Be(r)).filter(Boolean),n=[...new Set([...Iv.map(r=>Be(ga(r))),...yX()])];return Xc={key:e,builtins:n,extras:t,allow:[...new Set([...hX.map(UP),...bX()])]},Xc}function Mv(){let{builtins:e,extras:t}=jP();return[...e,...t]}function HP(e){let t=Be(ga(e));return Mv().filter(n=>n!==t&&fa(n,t,n)).map(n=>(n.startsWith(t+Yc)?gX(t,n):n.split(Yc).slice(t.split(Yc).length).join(Yc)).split(Yc).join("/"))}function $t(e){let t=Be(ga(e)),{builtins:n,extras:r,allow:o}=jP();for(let i of r)if(fa(t,i))return{denied:!0,matched:i};if(o.includes(t))return{denied:!1};for(let i of n)if(fa(t,i))return{denied:!0,matched:i};return{denied:!1}}var Iv,ho,hX,Xc,BP,Ar=T(()=>{"use strict";G();Ei();q();Vc();Hm();Iv=[`${qe()}/.ssh`,`${qe()}/.aws`,`${qe()}/.gnupg`,`${qe()}/.config/gcloud`,`${qe()}/.afk/config`,`${qe()}/.npmrc`,`${qe()}/.docker/config.json`,`${qe()}/.git-credentials`,`${qe()}/.netrc`,`${qe()}/.config/gh/hosts.yml`,`${qe()}/.kube/config`,"/etc/shadow","/etc/sudoers","/private/etc/master.passwd",`${qe()}/.password-store`,`${qe()}/Library/Application Support/Google/Chrome`,`${qe()}/Library/Application Support/Chromium`,`${qe()}/Library/Application Support/BraveSoftware`,`${qe()}/Library/Application Support/Microsoft Edge`,`${qe()}/Library/Application Support/Arc`,`${qe()}/Library/Application Support/Firefox`],ho=[".afk/config/mcp.json",".ssh/config",".ssh/known_hosts"],hX=ho.map(e=>`${qe()}/${e}`);BP=".afk/"});import xi from"path";import{realpathSync as wX}from"fs";function on(e){try{return wX.native(e)}catch{let t=xi.dirname(e),n=xi.basename(e);return t===e?e:xi.join(on(t),n)}}function SX(e){let t=WP.get(e);if(t!==void 0)return t;let n=on(e);return WP.set(e,n),n}function KP(e,t,n,r){let o=t?.resolveBase??t?.cwd??r,i=xi.isAbsolute(e)?e:xi.resolve(o??process.cwd(),e);if(t?.allowAll===!0)return{restricted:!1,resolved:i,roots:[]};if(o===void 0)return{restricted:!1,resolved:i,roots:[]};let s=on(i),a=n==="read"?t?.readRoots??[o]:t?.writeRoots??[o];for(let l of a){let c=SX(l),d=xi.relative(c,s);if(!d.startsWith("..")&&!xi.isAbsolute(d))return{restricted:!1,resolved:i,roots:a}}return{restricted:!0,resolved:i,roots:a}}function Dt(e,t,n="read",r){let{restricted:o,resolved:i,roots:s}=KP(e,t,n,r);if(n==="read"){let a=$t(i);if(a.denied)throw new Error(`Path \`${e}\` is a protected credential/secret path (read-denylist entry: \`${a.matched}\`) and cannot be read.`)}if(o){let a=s.map(c=>`\`${c}\``).join(", "),l=n==="read"?"read roots":"write roots";throw new Error(`Path \`${e}\` is outside the allowed ${l} [${a}].`)}return i}function Qc(e,t,n="read",r){return KP(e,t,n,r)}function GP(e){let t=new Set,n=[];for(let r of e.split(/\s+/)){if(r.length===0)continue;let o=r.replace(/^\d*[<>|&]+/,"").replace(/^['"]/,"").replace(/['";,)]+$/,"");if(o.length===0)continue;let i=o.startsWith("/"),s=o==="~"||o.startsWith("~/");!i&&!s||t.has(o)||(t.add(o),n.push(o))}return n}var WP,sn=T(()=>{"use strict";Ar();WP=new Map});import{spawn as vX}from"child_process";import kX from"os";function TX(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(t.timeout_ms<0||t.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=t.timeout_ms}return{command:t.command,timeout_ms:n}}function Gm(e,t){let n=!1,r=!1;function o(){n||e==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}function i(s,a){if(r)return;let l=a.resolveBase??a.cwd??t,c=kX.homedir(),d=[];for(let u of GP(s)){let m=u==="~"?c:u.startsWith("~/")?c+u.slice(1):u,f=Qc(m,a,"write",l);f.restricted&&d.push(f.resolved)}d.length!==0&&(r=!0,console.warn(`[security] bash: command references path(s) outside writeRoots: ${d.join(", ")} \u2014 bash containment is best-effort (tracked C4); use file tools for contained writes.`),Me({event:"tool.bash_path_escape",tool:"bash",restricted_count:d.length,mode:"write"}))}return async(s,a,l)=>{let{command:c,timeout_ms:d}=TX(s);if(a.aborted)return{content:"Command aborted",isError:!0};if(o(),l!==void 0)try{i(c,l)}catch{}return new Promise(u=>{let m=!1;function f(R){m||(m=!0,clearTimeout(h),a.removeEventListener("abort",E),u(R))}let g=vX(c,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(l?.resolveBase??l?.cwd??t)!==void 0?{cwd:l?.resolveBase??l?.cwd??t}:{},...l?.env!==void 0?{env:{...process.env,...l.env}}:{}});g.unref();let h=setTimeout(()=>{g.pid!==void 0&&process.kill(-g.pid,"SIGKILL"),f({content:`Command timed out after ${d}ms`,isError:!0})},d),y="",b="",w=0,S=!1;function v(R){if(S||m||w<8e6)return;S=!0,console.warn(`[bash] overflow kill: stream=${R} totalBytes=${w} command="${c}"`),Me({event:"tool.overflow_kill",tool:"bash",total_bytes:w,stream:R}),g.kill("SIGKILL");let D=er((y+b).trimEnd()),I=Tv(D)??void 0,A=xr(D,1e5)+_m;f({content:A,truncated:!0,...I!==void 0?{testResult:I}:{}})}g.stdout.on("data",R=>{let D=8e6-w,I=R.length<=D?R:R.subarray(0,Math.max(0,D));w+=I.length,y+=I.toString("utf8"),v("stdout")}),g.stderr.on("data",R=>{let D=8e6-w,I=R.length<=D?R:R.subarray(0,Math.max(0,D));w+=I.length,b+=I.toString("utf8"),v("stderr")});let E=()=>{g.pid!==void 0&&process.kill(-g.pid,"SIGKILL"),f({content:"Command aborted",isError:!0})};a.addEventListener("abort",E),a.aborted&&E(),g.on("close",R=>{if(a.aborted){f({content:"Command aborted",isError:!0});return}if(R!==null&&R!==0){let C=uo(b.trimEnd()||y.trimEnd());f({content:`Command exited with code ${R}${C.content?`
883
+ Retrying it verbatim will fail the same way. Fix the underlying cause, change the arguments, use a different tool, or stop and report the blocker.`,isError:!0,failureClass:"repeat-failure"}}}note(t,n){let r=zc(t);if(n.isError!==!0){this.streaks.delete(r);return}let o=this.streaks.get(r);this.streaks.set(r,{count:(o?.count??0)+1,lastError:F3(n)})}streakFor(t){return this.streaks.get(zc(t))?.count??0}}});var ua,kv,N3,Ot,pa=T(()=>{"use strict";ue();Fe();Rm();Sm();xm();uv();wi();Im();ye();yv();kP();Bm();Sv();IP();yv();ua=8,kv=new Set,N3=8,Ot=class{handlers;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;skillExecutor;composeExecutor;classifier;maxConcurrentSafeCalls;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;subagentId;sessionGrantManager;traceWriter;readOnlyBash;maxOutputBytes;repeatBreaker=null;repeatFailureGuard=new jm;denialBreaker=null;suspectedLoopWindow=null;grantManager;constructor(t){this.handlers=t.handlers,this.schemas=t.schemas,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,this.subagentExecutor=t.subagentExecutor,this.skillExecutor=t.skillExecutor,this.composeExecutor=t.composeExecutor,this.classifier=t.concurrencyClassifier??hv,this.maxConcurrentSafeCalls=typeof t.maxConcurrentSafeCalls=="number"&&Number.isFinite(t.maxConcurrentSafeCalls)&&t.maxConcurrentSafeCalls>=1?Math.floor(t.maxConcurrentSafeCalls):N3,this.resolveBase=t.cwd,this._env=t.env,this.sessionId=t.sessionId,this.parentSessionId=t.parentSessionId,this.subagentId=t.subagentId,this.sessionGrantManager=t.sessionGrantManager,this.traceWriter=t.traceWriter,this.readOnlyBash=t.readOnlyBash===!0,this.maxOutputBytes=typeof t.maxOutputBytes=="number"&&Number.isFinite(t.maxOutputBytes)&&t.maxOutputBytes>0?t.maxOutputBytes:void 0,this._allowAll=t.allowAll===!0;let n=t.cwd?[t.cwd]:[];this._readRoots=t.readRoots??n.slice(),this._writeRoots=t.writeRoots??n.slice(),this.grantManager=new po({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,getProtectedRoot:()=>this.resolveBase,getAllowAll:()=>this._allowAll,getDefaultSessionId:()=>this.sessionId})}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{},...this.sessionId!==void 0?{sessionId:this.sessionId}:{}}}callHandlerContext(t){return{...this.handlerContext,toolUseId:t.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{}}}addReadRoot(t,n="slash"){this.grantManager.addReadRoot(t,n)}addWriteRoot(t,n="slash"){this.grantManager.addWriteRoot(t,n)}revokeRoot(t,n="slash"){this.grantManager.revokeRoot(t,n)}getGrants(){return this.grantManager.getGrants()}setAllowAll(t){this._allowAll=t}setResolveBase(t){let n=this.resolveBase;if(n!==t){if(this.resolveBase=t,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=t:this._readRoots.includes(t)||this._readRoots.push(t);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=t:this._writeRoots.includes(t)||this._writeRoots.push(t)}else this._readRoots.includes(t)||this._readRoots.push(t),this._writeRoots.includes(t)||this._writeRoots.push(t);this.subagentExecutor?.setCwd(t),this.skillExecutor?.setCwd(t),this.composeExecutor?.setCwd(t)}}get toolDefs(){let t=this.permissions?.allowedTools;if(!t)return this.schemas;let n=new Set(t);return this.schemas.filter(r=>n.has(r.name))}async checkReadOnlyBash(t){if(!this.readOnlyBash||t.name!=="bash")return null;let n=t.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=Cm(r);if(!o.mutating)return null;let i=`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff/show/ls-remote, ls, cat, find, grep, gh pr view/diff). For a remote ref you have not fetched, \`gh pr diff <n>\`, \`gh pr view <n>\` and \`git ls-remote\` need no local ref \u2014 \`git fetch\` is blocked. Do NOT retry variants of a blocked command: if the task genuinely requires a mutation, stop and report that requirement to your caller instead.`;return await this.emitPreToolUseBlock(t.name,i),{content:i,isError:!0,failureClass:"permission-denied"}}async emitPreToolUseBlock(t,n){await Zt(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t,reason:n,...this.subagentId!==void 0?{subagentId:this.subagentId}:{}})}checkRepeatCircuitBreaker(t){if(kv.has(t.name))return null;let n=vP(t);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<ua?null:{content:`Loop circuit breaker: "${t.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}checkRepeatFailureGuard(t){if(kv.has(t.name))return null;let n=this.repeatFailureGuard.check(t);return n===null?null:(j(`[repeat-failure-guard #723] refused ${n.tool} after ${n.count} identical failures`),n.result)}observeSuspectedLoop(t){if(this.parentSessionId===void 0)return;this.suspectedLoopWindow===null&&(this.suspectedLoopWindow=AP());let n=Um(t),r=CP(this.suspectedLoopWindow,n);r.fired&&re(this.traceWriter,{phase:"suspected_loop",metadata:{tool:t.name,count:r.count,windowSize:wv}})}recordForkReadDenial(t,n,r){if(this.parentSessionId===void 0||!TP.has(t.name)||!EP(n))return r;let o=this.denialBreaker??{count:0,deniedPaths:[]};o.count+=1;let i=xP(t);return o.deniedPaths.includes(i)||o.deniedPaths.push(i),this.denialBreaker=o,o.count<5?r:{content:RP(o.deniedPaths,o.count),isError:!0,failureClass:da}}resetDenialBreaker(){this.denialBreaker=null}async runCanUseTool(t){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(t.name,t.input??{},{signal:t.signal,toolUseID:t.id})}catch(r){let o=`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`;return await this.emitPreToolUseBlock(t.name,o),{content:o,isError:!0,failureClass:"permission-denied"}}if(n.behavior==="deny"){let r=n.message||`Tool "${t.name}" denied by permission policy`;return await this.emitPreToolUseBlock(t.name,r),{content:r,isError:!0,failureClass:"permission-denied"}}return n.updatedInput!==void 0&&(t.input=n.updatedInput),null}async execute(t){if(t.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:"abort"};if(this.hookRegistry){let l={event:"PreToolUse",toolName:t.name,input:t.input,...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{}};try{await ov(this.hookRegistry,l,{signal:t.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(c){if(c instanceof Ee)return this.recordForkReadDenial(t,c.reason,{content:`Tool "${t.name}" blocked by PreToolUse hook: ${c.message}`,isError:!0,failureClass:"hook-block"});throw c}}let n=cv(t.name,this.permissions);if(!n.allowed){let l=n.reason??`Tool "${t.name}" is not permitted`;return await this.emitPreToolUseBlock(t.name,l),{content:l,isError:!0,failureClass:"permission-denied"}}let r=await this.runCanUseTool(t);if(r)return r;let o=await this.checkReadOnlyBash(t);if(o)return o;let i=this.checkRepeatCircuitBreaker(t);if(i)return i;let s=this.checkRepeatFailureGuard(t);if(s)return s;this.observeSuspectedLoop(t);let a=await this.executeCore(t);return this.repeatFailureGuard.note(t,a),a.isError!==!0&&this.resetDenialBreaker(),a}async executeBatch(t){if(t.length===0)return[];if(t.length===1)return[await this.execute(t[0])];let n=new Array(t.length),r=new Set;for(let s=0;s<t.length;s++){let a=t[s];if(a.signal.aborted){n[s]={content:"Tool call aborted",isError:!0,failureClass:"abort"},r.add(s);continue}if(this.hookRegistry){let f={event:"PreToolUse",toolName:a.name,input:a.input,...this.sessionId!==void 0?{sessionId:this.sessionId}:{},...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{}};try{await ov(this.hookRegistry,f,{signal:a.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(g){if(g instanceof Ee){n[s]=this.recordForkReadDenial(a,g.reason,{content:`Tool "${a.name}" blocked by PreToolUse hook: ${g.message}`,isError:!0,failureClass:"hook-block"}),r.add(s);continue}throw g}}let l=cv(a.name,this.permissions);if(!l.allowed){let f=l.reason??`Tool "${a.name}" is not permitted`;await this.emitPreToolUseBlock(a.name,f),n[s]={content:f,isError:!0,failureClass:"permission-denied"},r.add(s);continue}let c=await this.runCanUseTool(a);if(c){n[s]=c,r.add(s);continue}let d=await this.checkReadOnlyBash(a);if(d){n[s]=d,r.add(s);continue}let u=this.checkRepeatCircuitBreaker(a);if(u){n[s]=u,r.add(s);continue}let m=this.checkRepeatFailureGuard(a);if(m){n[s]=m,r.add(s);continue}this.observeSuspectedLoop(a)}let o=t.map((s,a)=>({call:s,originalIndex:a})).filter((s,a)=>!r.has(a));if(o.length===0)return n;let i=SP(o.map(s=>s.call),this.classifier);for(let s of i){if(s.isConcurrencySafe){let l=[...s.indices];for(;l.length>0;){let c=new Map,d=[],u=[];for(let f of l){let{call:g,originalIndex:h}=o[f],y=this.checkRepeatFailureGuard(g);if(y){n[h]=y;continue}if(kv.has(g.name)){d.push(f);continue}let b=zc(g),w=vv-this.repeatFailureGuard.streakFor(g),S=c.get(b)??0;S<w?(c.set(b,S+1),d.push(f)):u.push(f)}l=u;let m=await la(d,this.maxConcurrentSafeCalls,async f=>{let{call:g,originalIndex:h}=o[f];return g.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:"abort"},originalIndex:h}:{result:await this.executeCore(g),originalIndex:h}});for(let f of m)if(f.status==="fulfilled")n[f.value.originalIndex]=f.value.result;else{let g=f.reason instanceof Error?f.reason.message:String(f.reason),h=d[m.indexOf(f)];n[o[h].originalIndex]={content:`Tool execution error: ${g}`,isError:!0}}for(let f of d){let{call:g,originalIndex:h}=o[f],y=n[h];y!==void 0&&y.failureClass!=="abort"&&this.repeatFailureGuard.note(g,y)}}}else for(let l of s.indices){let{call:c,originalIndex:d}=o[l];if(c.signal.aborted){n[d]={content:"Tool call aborted",isError:!0,failureClass:"abort"};continue}let u=this.checkRepeatFailureGuard(c);if(u){n[d]=u;continue}let m=await this.executeCore(c);n[d]=m,this.repeatFailureGuard.note(c,m)}let a=s.indices.length;s.indices.forEach((l,c)=>{let d=n[o[l].originalIndex];d&&(d.batchIndex=c+1,d.batchSize=a)})}return n.some(s=>s!==void 0&&s.isError!==!0)&&this.resetDenialBreaker(),n}async executeCore(t){let n=await this.executeCoreInner(t);return this.applyOutputCap(n)}applyOutputCap(t){let n=this.maxOutputBytes;if(n===void 0)return t;let r=Buffer.byteLength(t.content,"utf8");return r<=n||(t.content=xr(t.content,n),t.truncated=!0,j(`[output-cap #661] fork tool result capped: original=${r}B capped=${Buffer.byteLength(t.content,"utf8")}B (cap=${n}B)`)),t}async executeCoreInner(t){if(t.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.subagentExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Agent tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}if(t.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.skillExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Skill tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}if(t.name==="compose"){let s=await this.executeCompose(t);return this.firePostToolUse(t.name,s.content,t.signal,t.input,s),s}let n=this.handlers.get(t.name);if(!n)return{content:`Unknown tool "${t.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r,o=!1,i="";try{r=await n(t.input,t.signal,this.callHandlerContext(t))}catch(s){o=!0,i=s instanceof Error?s.message:String(s),r={content:`Tool execution error: ${i}`,isError:!0}}return o?this.firePostToolUseFailure(t.name,i,t.signal,t.input):this.firePostToolUse(t.name,r.content,t.signal,t.input,r),r}async executeCompose(t){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(t)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(t,n,r,o,i){if(!this.hookRegistry)return;let s={event:"PostToolUse",toolName:t,output:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{},...i?.incomplete===!0?{incomplete:!0}:{},...i?.incompleteReason?{incompleteReason:i.incompleteReason}:{}};KI(this.hookRegistry,s,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(t,n,r,o){if(!this.hookRegistry)return;let i={event:"PostToolUseFailure",toolName:t,error:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};GI(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(s=>{j(`firePostToolUseFailure outer catch (tool=${t}): ${String(s)}`)})}}});function V3(e){let t=e.match(B3);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function Y3(e){let t=e.match(U3);if(!t)return null;let n=parseInt(t[1]??"0",10);return{runner:"jest",passed:parseInt(t[2]??"0",10),failed:n}}function X3(e){let t=e.match(j3);if(!t)return null;if(t[2]!==void 0){let n=parseInt(t[2],10),r=parseInt(t[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return t[4]!==void 0?{runner:"pytest",passed:parseInt(t[4],10),failed:0}:null}function Q3(e){let t=e.match(H3);if(!t)return null;let n=parseInt(t[1]??"0",10),r=e.match(W3),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function Z3(e){let t=[...e.matchAll(K3)];if(t.length===0)return null;let n=0,r=0;for(let o of t)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function eX(e){let t=e.match(G3);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function tX(e){let t=e.match(q3);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function nX(e){let t=e.match(z3);if(t)return{runner:"phpunit",passed:parseInt(t[1]??"0",10),failed:0};let n=e.match(J3);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function Tv(e){return V3(e)??Y3(e)??X3(e)??Q3(e)??Z3(e)??eX(e)??tX(e)??nX(e)??null}var B3,U3,j3,H3,W3,K3,G3,q3,z3,J3,PP=T(()=>{"use strict";B3=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,U3=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,j3=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,H3=/(\d+)\s+passing/,W3=/(\d+)\s+failing/,K3=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,G3=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,q3=/(\d+) examples?, (\d+) failures?/,z3=/OK \((\d+) tests?/,J3=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/});function Rr(e){return e.replace(MP,"").replace(rX," ").trim()}function er(e){return e.replace(MP,"")}var MP,rX,fo=T(()=>{"use strict";MP=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,rX=/[\x00-\x1F\x7F-\x9F]/g});import{statSync as oX}from"node:fs";function Jc(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.code==="ENOENT"&&typeof t.syscall=="string"&&t.syscall.startsWith("spawn")}function iX(e){if(e===void 0)return!1;try{return oX(e),!1}catch{return!0}}function ma(e,t){let n=e instanceof Error?e.message:typeof e?.message=="string"?String(e.message):String(e);return Jc(e)&&iX(t)?`working directory does not exist: ${t} (deleted worktree?) \u2014 underlying: ${n}`:n}var Ev=T(()=>{"use strict"});function tr(e){if(OP)return;OP=!0;let t=e instanceof Error?e.message:String(e);console.warn(`[afk-home] Malformed AFK home/state env var ignored while deriving the credential floor: ${t}. The relocated tree is NOT protected \u2014 the default ~/.afk entries still apply. Fix the env var to restore coverage.`)}var OP,Vc=T(()=>{"use strict";OP=!1});import{statSync as Rv}from"node:fs";import{homedir as sX}from"node:os";import{basename as aX,dirname as DP,join as lX}from"node:path";function FP(e){return typeof e=="object"&&e!==null&&"code"in e?String(e.code):void 0}function cX(e){let t=aX(e),n=t===t.toLowerCase()?t.toUpperCase():t.toLowerCase();if(n===t)return;let r;try{r=Rv(e)}catch{return}let o=xv.get(r.dev);if(o!==void 0)return o;try{let i=Rv(lX(DP(e),n)),s=r.dev===i.dev&&r.ino===i.ino;return xv.set(r.dev,s),s}catch(i){let s=FP(i);return s==="ENOENT"||s==="ENOTDIR"?(xv.set(r.dev,!1),!1):void 0}}function LP(e=sX()){if($P!==void 0)return $P;let t=e;for(;;)try{return Rv(t),cX(t)??!0}catch(n){let r=FP(n);if(r!=="ENOENT"&&r!=="ENOTDIR")return!0;let o=DP(t);if(o===t)return!0;t=o}}function fa(e,t,n=t){if(e===t||e.startsWith(t+"/"))return!0;if(!LP(n))return!1;let r=e.toLowerCase(),o=t.toLowerCase();return r===o||r.startsWith(o+"/")}function Av(e,t){return e.includes(t)?!0:LP(t)?e.toLowerCase().includes(t.toLowerCase()):!1}var $P,xv,Hm=T(()=>{"use strict";xv=new Map});import{realpathSync as NP}from"fs";import{dirname as dX,resolve as Ti,join as Cv}from"path";import{homedir as go}from"os";function pX(){let e=[];try{let t=we();e.push(Be(Ti(Cv(t,"config")))),e.push(Be(Ti(Cv(t,"state"))))}catch(t){tr(t)}try{e.push(Be(Ti(me())))}catch(t){tr(t)}return e}function _v(){let e=k.AFK_WRITE_DENYLIST,t=e?e.split(":").map(r=>Be(Ti(r))).filter(Boolean):[];return[...[...new Set([...uX.map(r=>Be(Ti(r))),...pX()])],...t]}function Be(e){let t=Ti(e);try{return NP(t)}catch{}let n=[],r=t;for(let o=0;o<64;o++){let i=dX(r);if(i===r)break;n.unshift(r.slice(i.length+1)),r=i;try{let s=NP(r);return Cv(s,...n)}catch{}}return t}function Wm(e,t="write_file"){let n=Be(Ti(e));for(let r of _v())if(fa(n,r))throw new Error(`${t}: refusing to write to protected path: ${n} (matches denylist entry: ${r})`)}var uX,Ei=T(()=>{"use strict";G();q();Vc();Hm();uX=[`${go()}/.ssh`,`${go()}/.aws`,`${go()}/.gnupg`,`${go()}/.config/gcloud`,"/etc","/System","/private/etc","/usr/local/etc",`${go()}/.afk/config`,`${go()}/.afk/state`,`${go()}/.npmrc`,`${go()}/.docker/config.json`]});import{basename as mX,dirname as fX,join as Km,relative as gX,resolve as ga,sep as Yc}from"path";import{homedir as qe}from"os";function UP(e){let t=ga(e);return Km(Be(fX(t)),mX(t))}function Pv(e){return e?e.split(":").map(t=>t.trim()).filter(Boolean).map(t=>t==="~"||t.startsWith("~/")?Km(qe(),t.slice(1)):t).map(t=>ga(t)):[]}function yX(){try{return[Be(ga(Km(we(),"config")))]}catch(e){return tr(e),[]}}function bX(){try{let e=we();return ho.filter(t=>t.startsWith(BP)).map(t=>UP(Km(e,t.slice(BP.length))))}catch(e){return tr(e),[]}}function jP(){let e=`${k.AFK_READ_DENYLIST??""}\0${k.AFK_HOME??""}`;if(Xc&&Xc.key===e)return Xc;let t=Pv(k.AFK_READ_DENYLIST).map(r=>Be(r)).filter(Boolean),n=[...new Set([...Iv.map(r=>Be(ga(r))),...yX()])];return Xc={key:e,builtins:n,extras:t,allow:[...new Set([...hX.map(UP),...bX()])]},Xc}function Mv(){let{builtins:e,extras:t}=jP();return[...e,...t]}function HP(e){let t=Be(ga(e));return Mv().filter(n=>n!==t&&fa(n,t,n)).map(n=>(n.startsWith(t+Yc)?gX(t,n):n.split(Yc).slice(t.split(Yc).length).join(Yc)).split(Yc).join("/"))}function $t(e){let t=Be(ga(e)),{builtins:n,extras:r,allow:o}=jP();for(let i of r)if(fa(t,i))return{denied:!0,matched:i};if(o.includes(t))return{denied:!1};for(let i of n)if(fa(t,i))return{denied:!0,matched:i};return{denied:!1}}var Iv,ho,hX,Xc,BP,Ar=T(()=>{"use strict";G();Ei();q();Vc();Hm();Iv=[`${qe()}/.ssh`,`${qe()}/.aws`,`${qe()}/.gnupg`,`${qe()}/.config/gcloud`,`${qe()}/.afk/config`,`${qe()}/.npmrc`,`${qe()}/.docker/config.json`,`${qe()}/.git-credentials`,`${qe()}/.netrc`,`${qe()}/.config/gh/hosts.yml`,`${qe()}/.kube/config`,"/etc/shadow","/etc/sudoers","/private/etc/master.passwd",`${qe()}/.password-store`,`${qe()}/Library/Application Support/Google/Chrome`,`${qe()}/Library/Application Support/Chromium`,`${qe()}/Library/Application Support/BraveSoftware`,`${qe()}/Library/Application Support/Microsoft Edge`,`${qe()}/Library/Application Support/Arc`,`${qe()}/Library/Application Support/Firefox`],ho=[".afk/config/mcp.json",".ssh/config",".ssh/known_hosts"],hX=ho.map(e=>`${qe()}/${e}`);BP=".afk/"});import xi from"path";import{realpathSync as wX}from"fs";function on(e){try{return wX.native(e)}catch{let t=xi.dirname(e),n=xi.basename(e);return t===e?e:xi.join(on(t),n)}}function SX(e){let t=WP.get(e);if(t!==void 0)return t;let n=on(e);return WP.set(e,n),n}function KP(e,t,n,r){let o=t?.resolveBase??t?.cwd??r,i=xi.isAbsolute(e)?e:xi.resolve(o??process.cwd(),e);if(t?.allowAll===!0)return{restricted:!1,resolved:i,roots:[]};if(o===void 0)return{restricted:!1,resolved:i,roots:[]};let s=on(i),a=n==="read"?t?.readRoots??[o]:t?.writeRoots??[o];for(let l of a){let c=SX(l),d=xi.relative(c,s);if(!d.startsWith("..")&&!xi.isAbsolute(d))return{restricted:!1,resolved:i,roots:a}}return{restricted:!0,resolved:i,roots:a}}function Dt(e,t,n="read",r){let{restricted:o,resolved:i,roots:s}=KP(e,t,n,r);if(n==="read"){let a=$t(i);if(a.denied)throw new Error(`Path \`${e}\` is a protected credential/secret path (read-denylist entry: \`${a.matched}\`) and cannot be read.`)}if(o){let a=s.map(c=>`\`${c}\``).join(", "),l=n==="read"?"read roots":"write roots";throw new Error(`Path \`${e}\` is outside the allowed ${l} [${a}].`)}return i}function Qc(e,t,n="read",r){return KP(e,t,n,r)}function GP(e){let t=new Set,n=[];for(let r of e.split(/\s+/)){if(r.length===0)continue;let o=r.replace(/^\d*[<>|&]+/,"").replace(/^['"]/,"").replace(/['";,)]+$/,"");if(o.length===0)continue;let i=o.startsWith("/"),s=o==="~"||o.startsWith("~/");!i&&!s||t.has(o)||(t.add(o),n.push(o))}return n}var WP,sn=T(()=>{"use strict";Ar();WP=new Map});import{spawn as vX}from"child_process";import kX from"os";function TX(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.command!="string")throw new Error('Input must have a "command" field of type string');let n=12e4;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number")throw new Error("timeout_ms must be a number");if(t.timeout_ms<0||t.timeout_ms>6e5)throw new Error("timeout_ms must be between 0 and 600000");n=t.timeout_ms}return{command:t.command,timeout_ms:n}}function Gm(e,t){let n=!1,r=!1;function o(){n||e==="bypassPermissions"&&(n=!0,console.warn("[security] bash handler: shell=true with bypassPermissions \u2014 all shell metacharacters are interpreted without confirmation. Migrate to execFile to eliminate this risk (tracked: C4)."))}function i(s,a){if(r)return;let l=a.resolveBase??a.cwd??t,c=kX.homedir(),d=[];for(let u of GP(s)){let m=u==="~"?c:u.startsWith("~/")?c+u.slice(1):u,f=Qc(m,a,"write",l);f.restricted&&d.push(f.resolved)}d.length!==0&&(r=!0,console.warn(`[security] bash: command references path(s) outside writeRoots: ${d.join(", ")} \u2014 bash containment is best-effort (tracked C4); use file tools for contained writes.`),Me({event:"tool.bash_path_escape",tool:"bash",restricted_count:d.length,mode:"write"}))}return async(s,a,l)=>{let{command:c,timeout_ms:d}=TX(s);if(a.aborted)return{content:"Command aborted",isError:!0};if(o(),l!==void 0)try{i(c,l)}catch{}return new Promise(u=>{let m=!1;function f(R){m||(m=!0,clearTimeout(h),a.removeEventListener("abort",E),u(R))}let g=vX(c,{shell:!0,detached:!0,stdio:["ignore","pipe","pipe"],...(l?.resolveBase??l?.cwd??t)!==void 0?{cwd:l?.resolveBase??l?.cwd??t}:{},...l?.env!==void 0?{env:{...process.env,...l.env}}:{}});g.unref();let h=setTimeout(()=>{g.pid!==void 0&&process.kill(-g.pid,"SIGKILL"),f({content:`Command timed out after ${d}ms`,isError:!0})},d),y="",b="",w=0,S=!1;function v(R){if(S||m||w<8e6)return;S=!0,console.warn(`[bash] overflow kill: stream=${R} totalBytes=${w} command="${c}"`),Me({event:"tool.overflow_kill",tool:"bash",total_bytes:w,stream:R}),g.kill("SIGKILL");let D=er((y+b).trimEnd()),I=Tv(D)??void 0,A=xr(D,1e5)+_m;f({content:A,truncated:!0,...I!==void 0?{testResult:I}:{}})}g.stdout.on("data",R=>{let D=8e6-w,I=R.length<=D?R:R.subarray(0,Math.max(0,D));w+=I.length,y+=I.toString("utf8"),v("stdout")}),g.stderr.on("data",R=>{let D=8e6-w,I=R.length<=D?R:R.subarray(0,Math.max(0,D));w+=I.length,b+=I.toString("utf8"),v("stderr")});let E=()=>{g.pid!==void 0&&process.kill(-g.pid,"SIGKILL"),f({content:"Command aborted",isError:!0})};a.addEventListener("abort",E),a.aborted&&E(),g.on("close",R=>{if(a.aborted){f({content:"Command aborted",isError:!0});return}if(R!==null&&R!==0){let C=uo(b.trimEnd()||y.trimEnd());f({content:`Command exited with code ${R}${C.content?`
884
884
  `+C.content:""}`,isError:!0,...C.truncated?{truncated:!0}:{}});return}if(S)return;let D=er((y+b).trimEnd()),I=Tv(D)??void 0,A=uo(D);f({content:A.content,...A.truncated?{truncated:!0}:{},...I!==void 0?{testResult:I}:{}})}),g.on("error",R=>{let D=l?.resolveBase??l?.cwd??t,I;if(D===void 0&&Jc(R))try{let A=process.cwd();I=ma(R,A)}catch{I=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${R.message}`}else I=ma(R,D);f({content:`Failed to execute: ${I}`,isError:!0})})})}}var qP,zP=T(()=>{"use strict";Cn();PP();fo();Ev();wi();sn();qP=Gm("default")});import{promises as EX}from"fs";function Ov(e){return(t,n,r)=>xX(t,n,r,e)}var xX,JP,VP=T(()=>{"use strict";sn();xX=async(e,t,n,r)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let o=e,i=o.file_path,s=o.offset??1,a=o.limit??2e3;if(typeof i!="string")return{content:"Invalid input: file_path must be a string",isError:!0};if(typeof s!="number"||s<1)return{content:"Invalid input: offset must be a positive number",isError:!0};if(typeof a!="number"||a<1)return{content:"Invalid input: limit must be a positive number",isError:!0};let l;try{l=Dt(i,n,"read",r)}catch(c){return{content:c instanceof Error?c.message:String(c),isError:!0}}try{let c=await EX.readFile(l),d=Math.min(8192,c.length);for(let S=0;S<d;S++)if(c[S]===0)return{content:`File appears to be binary: ${l}`,isError:!0};let u=c.toString("utf-8");if(u.length===0)return{content:""};let m=u.split(`
885
885
  `),f=Math.max(0,s-1),g=Math.min(m.length,f+a),h=m.slice(f,g),y=m.length;if(h.length===0)return{content:`... (offset ${s} is past end of file \u2014 file has ${y} lines)`};let b=String(y).length,w=h.map((S,v)=>{let E=f+v+1;return`${String(E).padStart(b," ")} ${S}`}).join(`
886
886
  `);if(h.length<y){let S=f+1,v=f+h.length,E=v<y?` \u2014 pass offset=${v+1} to continue`:"";return{content:`${w}
@@ -891,7 +891,7 @@ Retrying it verbatim will fail the same way. Fix the underlying cause, change th
891
891
 
892
892
  `).trim()}function e9(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}async function fM(e,t){let{JSDOM:n,Readability:r,turndown:o}=await ZX(),s=new n(e,{url:t}).window.document,a=(s.title??"").trim(),l=(()=>{try{let m=s.cloneNode(!0);return new r(m).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let m=mM(o.turndown(l.content)),f=(l.title??"").trim()||a,g=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:m,textLength:g,usedFallback:!1}}let c=s.body,d=c?.innerHTML??"",u=mM(o.turndown(d));return{title:a,markdown:u,textLength:e9(c),usedFallback:!0}}var Uv,gM=T(()=>{"use strict";Uv=null});function n9(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 hM(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function r9(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 yM(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??n9,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await e(t,n);if(!t9.has(u.status)||d===o)return u;let m=r9(u,s)??hM(d,i,s);j("[web/retryFetch] retrying",{url:t,attempt:d,status:u.status,waitMs:m}),await u.body?.cancel().catch(()=>{}),await a(m,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let m=hM(d,i,s);j("[web/retryFetch] retrying after error",{url:t,attempt:d,waitMs:m}),await a(m,l)}}throw c??new Error("retryFetch: exhausted without a result")}var t9,bM=T(()=>{"use strict";ue();t9=new Set([429,502,503,504])});import{BlockList as o9,isIP as Hv}from"node:net";import{lookup as i9}from"node:dns/promises";import{Agent as s9}from"undici";function SM(){let e=k.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return e==="1"||e==="true"}function d9(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function jv(e){let t=Hv(e);return t===0?!1:c9.check(e,t===4?"ipv4":"ipv6")}async function vM(e){return i9(e,{all:!0,verbatim:!0})}async function Wv(e,t={}){if(t.allowPrivateHosts??SM())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=d9(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(Hv(r)!==0)return jv(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let i=t.lookupFn??vM,s;try{s=await i(r)}catch{return{allowed:!0}}for(let a of s)if(jv(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function ed(e,t={}){let n=await Wv(e,t);if(!n.allowed)throw new In(n.reason)}async function zm(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<=wM;s++){await ed(i,o);let a={...n,redirect:"manual",...e===globalThis.fetch&&!(r.allowPrivateHosts??SM())?{dispatcher:u9}:{}},l=await yM(e,i,a,r.retry??{});if(!p9.has(l.status))return l;let c=l.headers.get("location");if(c===null||c.trim()==="")return l;let d;try{d=new URL(c,l.url||i).toString()}catch{return l}await l.body?.cancel().catch(()=>{}),i=d}throw new In(`too many redirects (>${wM}) starting from ${t}`)}var a9,l9,c9,In,u9,wM,p9,Kv=T(()=>{"use strict";G();bM();a9=[["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]],l9=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],c9=(()=>{let e=new o9;for(let[t,n]of a9)e.addSubnet(t,n,"ipv4");for(let[t,n]of l9)e.addSubnet(t,n,"ipv6");return e})(),In=class extends Error{constructor(t){super(t),this.name="EgressBlockedError"}};u9=new s9({connect:{lookup(e,t,n){vM(e).then(r=>{let o=r.find(s=>jv(s.address));if(o!==void 0){n(new In(`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,Hv(i.address))},r=>n(r,"",0))}}});wM=20,p9=new Set([301,302,303,307,308])});import{readFileSync as m9}from"node:fs";import{join as f9}from"path";function g9(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function kM(e,t){return g9(t).test(e)}function b9(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(h9.has(t))return!0;if(y9.has(t))return!1}return!1}function TM(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function w9(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 EM(e){let t=e===void 0||e.trim()===""?"default":e.trim();return gc(t),t}function S9(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function v9(e){try{return m9(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function k9(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=EM(t.defaultProfile)),n}function xM(e){let t=e?.env??k,n=e?.readFileSync??v9,r=e?.surface??t.AGENT_SURFACE,o=b9(t.AFK_BROWSER_HEADLESS,r),i=TM(t.AFK_BROWSER_ALLOWED_DOMAINS),s=TM(t.AFK_BROWSER_BLOCKED_DOMAINS),a=S9(t.AFK_BROWSER_DOM_SNAPSHOTS),l=w9(t.AFK_BROWSER_BACKEND),c=EM(t.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:i,blockedDomains:s,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=t.AFK_BROWSER_CONFIG,m=u!==void 0&&u.trim()!==""?u.trim():f9(Tn(),"browser.json"),f=n(m);if(f===void 0)return d;let g;try{g=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${m}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${m} must be a JSON object`);let h=k9(d,g);return h.configPath=m,h}function Jm(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(kM(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>kM(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var h9,y9,Vm=T(()=>{"use strict";G();q();h9=new Set(["daemon","subagent","telegram","afk"]),y9=new Set(["repl","interactive","cli"])});import{existsSync as T9,readFileSync as E9}from"node:fs";import{createRequire as x9}from"node:module";import{dirname as R9,join as A9}from"node:path";function CM(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<_9&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function Ft(e){let t=CM(e);return AM.some(n=>t.includes(n))}function I9(){try{let t=x9(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(E9(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=A9(R9(t),o);return T9(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function td(){return RM??=I9()??C9,RM}function Gv(e){return e.includes("install chromium")}function an(e,t){let n=CM(e),r=t?.latched===!0?` ${P9}`:"";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: ${td()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${td()}). Or pick a different tool.${r}`}function nd(e,t,n=!1){if(!Ft(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
893
893
 
894
- ${an(e,{headless:t,latched:n})}`,{cause:e})}var AM,C9,_9,RM,P9,Ym=T(()=>{"use strict";AM=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],C9="pnpm exec playwright install chromium",_9=4;P9="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 Ai from"node:fs";import Xm from"node:path";import{randomBytes as M9}from"node:crypto";import{chromium as O9}from"playwright";function $9(){try{return"5.89.0"}catch{}try{let e=Xm.resolve(import.meta.dirname,"../../../package.json"),t=Ai.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var D9,Qm,_M=T(()=>{"use strict";Ym();q();ue();D9=$9(),Qm=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=O9.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=nd(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(m){throw i??m}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let d=a.url(),u=l!==null?l.status():null;return{html:c,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){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/${D9}`}}loadStorageState(t){let n=hc(t);try{if(!Ai.existsSync(n))return;let r=JSON.parse(Ai.readFileSync(n,"utf8"));return j("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){j("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=hc(t);if(!Ai.existsSync(r))return;let o=await n.storageState(),i=Xm.join(Xm.dirname(r),`.${Xm.basename(r)}.${process.pid}.${M9(4).toString("hex")}.tmp`);Ai.writeFileSync(i,JSON.stringify(o),{mode:384}),Ai.chmodSync(i,384),Ai.renameSync(i,r),j("[browser/vault] saved session",{profile:t,file:r})}catch(r){j("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as F9}from"crypto";function IM(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&L9.test(e.label))}function PM(e){return F9("sha256").update(e,"utf8").digest("hex").slice(0,8)}function MM(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var L9,Zm=T(()=>{"use strict";L9=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as N9}from"node:crypto";function B9(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function U9(e,t,n){return`el_${N9("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function j9(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function OM(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function DM(e,t){let n=e.role??"",r=e.name??"";$M.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])DM(i,t)}async function H9(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 d=window.getComputedStyle(s);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},FM).catch(()=>[])}async function W9(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 d="value"in i?i.value:void 0,u=d!==void 0?String(d):void 0,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},FM).catch(()=>[])}function K9(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function ef(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=K9(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=H9(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,m,f,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],DM(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await W9(e)).filter($=>$M.has($.role??"")));let w=new Map;for(let _ of m){let $=OM(_.name),B=w.get($);(!B||B.bbox.w===0&&_.bbox.w>0)&&w.set($,_)}let S=y.map(_=>({ax:_,dom:w.get(OM(_.name??""))})),v=r?S:S.filter(_=>_.dom?_.dom.bbox.w>0||_.dom.bbox.h>0:!0);v.sort((_,$)=>{let B=_.dom?.bbox.y??0,L=$.dom?.bbox.y??0;if(B!==L)return B-L;let W=_.dom?.bbox.x??0,P=$.dom?.bbox.x??0;return W-P}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=v.slice(0,n).map((_,$)=>{let B=_.ax.role??"generic",L=_.ax.name??"",W=U9(B,L,$),P=_.dom?.bbox??{x:0,y:0,w:0,h:0},U=_.dom?.type??null,N=null;_.ax.value!==void 0&&_.ax.value!==null&&(N=String(_.ax.value)),_.ax.checked!==void 0&&(N=String(_.ax.checked)),IM({role:B,kind:U})&&(N="[redacted]");let M={disabled:_.ax.disabled??!1};_.ax.checked!==void 0&&(M.checked=_.ax.checked===!0||_.ax.checked==="mixed"),_.ax.selected!==void 0&&(M.selected=_.ax.selected),_.ax.expanded!==void 0&&(M.expanded=_.ax.expanded);let O;_.dom?.testId?O=`[data-testid="${_.dom.testId}"]`:_.dom?.id&&(O=`#${_.dom.id}`);let H={id:W,role:B,label:B9(L),kind:U,value:N,state:M,bbox:P};return O!==void 0&&(H.selector=O),H}),D="idle";try{let _=await e.evaluate(()=>document.readyState);_==="loading"?D="loading":_==="interactive"?D="navigating":D="idle"}catch{D="navigating"}D!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=j9(f),A=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:A,url:g,title:h,textSummary:I,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:D,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var $M,FM,LM=T(()=>{"use strict";Zm();$M=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);FM="a[href], button, input, select, textarea, [role], [tabindex], label"});async function NM(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")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${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 qv(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>NM(e,i)))).filter(o=>o!==null)}async function G9(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 zv(e,t,n){switch(t.kind){case"element_id":return q9(e,t,n);case"selector":return z9(e,t);case"semantic":return J9(e,t)}}async function q9(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 qv(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function z9(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 qv(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function J9(e,t){return t.role!==void 0?V9(e,t.text,t.role):Y9(e,t.text,t)}async function V9(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 qv(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function Y9(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 d=[];s>0&&d.push({loc:r,count:s}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:i,count:l});let u=await G9(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=u.slice(0,5),f=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await NM(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let v=0;v<w.length;v++)S=S*31+w.charCodeAt(v)>>>0;f.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var BM=T(()=>{"use strict"});async function Jv(e,t,n,r){let o=e.url();if(o===n)return null;let i=Jm(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 UM=T(()=>{"use strict";Vm()});import{randomBytes as X9}from"crypto";import{mkdir as Q9,stat as Z9,writeFile as e7}from"fs/promises";import{join as Vv}from"path";import{gzip as t7}from"zlib";import{promisify as n7}from"util";function r7(e){return Vv(Xr(e),"browser")}function o7(e){return Vv(r7(e),"screenshots")}function i7(){return new Date().toISOString().replace(/[:.]/g,"-")}function s7(){return X9(3).toString("hex")}async function Yv(e,t,n){if(t.length>jM)throw new Error(`writeScreenshotSidecar: buffer exceeds ${jM} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=o7(e);await Q9(r,{recursive:!0});let o=`${i7()}-${s7()}-${n}.png`,i=Vv(r,o);await e7(i,t);let{size:s}=await Z9(i);return{path:i,bytes:s}}var xOe,jM,HM=T(()=>{"use strict";q();Zm();xOe=n7(t7);jM=5*1024*1024});var KM={};dp(KM,{PlaywrightProvider:()=>Xv});function WM(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 Xv,GM=T(()=>{"use strict";_M();LM();BM();Vm();UM();HM();Xv=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Qm(t)}async open(t){let n=Jm(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(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Jv(o,this.config,t.url,()=>this.close({sessionId:r}));if(u!==null)return u}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let d=await ef(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,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}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 ef(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 zv(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${WM(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=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 d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){c=y}else c=h}let u=await Jv(r,this.config,i,()=>this.close({sessionId:n}));if(u!==null)return u;let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await ef(r,{observationCounter:o.observationCounter,screenshotPath:m,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 d=await zv(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${WM(t.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await d.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await Yv(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path: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 Yv(n,o,r);return i}catch{return null}}}});var _i={};dp(_i,{__resetBrowserRegistryForTests:()=>u7,browserProviderActive:()=>c7,closeBrowserProvider:()=>Qv,getBrowserProvider:()=>l7,peekBrowserProvider:()=>d7});function qM(){Promise.resolve(Qv()).then(()=>{process.exit(130)})}function zM(){Promise.resolve(Qv()).then(()=>{process.exit(143)})}function JM(){nr=null}function a7(){tf||(process.on("SIGINT",qM),process.on("SIGTERM",zM),process.on("exit",JM),tf=!0)}function VM(){tf&&(process.removeListener("SIGINT",qM),process.removeListener("SIGTERM",zM),process.removeListener("exit",JM),tf=!1)}async function l7(e){return nr!==null?nr:(Ci!==null||(Ci=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(GM(),KM)),n=xM(e),r=new t(n);return a7(),nr=r,Ci=null,r})()),Ci)}async function Qv(){if(nr===null)return;let e=nr;nr=null,Ci=null,VM(),await e.shutdown()}function c7(){return nr!==null}function d7(){return nr}function u7(){nr=null,Ci=null,VM()}var nr,Ci,tf,Ii=T(()=>{"use strict";Vm();nr=null,Ci=null,tf=!1});async function YM(e,t){try{return await fM(e,t)}catch(n){return j("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function y7(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Ii(),_i));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function XM(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??y7,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s=e,a=null,l=null;try{let d=await zm(n,e,{headers:h7,signal:t.signal},o);a=d.status,s=d.url||e;let u=d.headers.get("content-type")??"";if(d.ok){if(g7.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let m=await d.text();if(f7.test(u)&&!m7.test(u))return{title:"",markdown:m.trim(),finalUrl:s,usedRender:!1};if(i=await YM(m,s),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof In||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;l=d}if(!(i===null||i.textLength<200)&&i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};try{await ed(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:m=>ed(m,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await ed(d.finalUrl,o);let u=await YM(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||u.textLength>=i.textLength)return{title:u.title,markdown:u.markdown,finalUrl:d.finalUrl,usedRender:!0}}catch(d){if(t.signal.aborted||d instanceof In)throw d;if(i===null){let u=d instanceof Error?d.message:String(d),m=l instanceof Error?l.message:`HTTP ${a??"error"}`,f=new Error(`web_scrape could not retrieve ${e}: fetch failed (${m}) and render failed (${u}).`);throw f.cause=d,f}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${a??"error"}).`)}var m7,f7,g7,h7,QM=T(()=>{"use strict";gM();Kv();ue();m7=/(text\/html|application\/xhtml\+xml)/i,f7=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,g7=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,h7={"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 S7(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(b7,{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),w7),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Rr(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}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 ZM(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?S7({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 e0(e,t){if(t.length===0)return`# Search results for "${e}"
894
+ ${an(e,{headless:t,latched:n})}`,{cause:e})}var AM,C9,_9,RM,P9,Ym=T(()=>{"use strict";AM=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],C9="pnpm exec playwright install chromium",_9=4;P9="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 Ai from"node:fs";import Xm from"node:path";import{randomBytes as M9}from"node:crypto";import{chromium as O9}from"playwright";function $9(){try{return"5.89.1"}catch{}try{let e=Xm.resolve(import.meta.dirname,"../../../package.json"),t=Ai.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var D9,Qm,_M=T(()=>{"use strict";Ym();q();ue();D9=$9(),Qm=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=O9.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=nd(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(m){throw i??m}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let d=a.url(),u=l!==null?l.status():null;return{html:c,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){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/${D9}`}}loadStorageState(t){let n=hc(t);try{if(!Ai.existsSync(n))return;let r=JSON.parse(Ai.readFileSync(n,"utf8"));return j("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){j("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=hc(t);if(!Ai.existsSync(r))return;let o=await n.storageState(),i=Xm.join(Xm.dirname(r),`.${Xm.basename(r)}.${process.pid}.${M9(4).toString("hex")}.tmp`);Ai.writeFileSync(i,JSON.stringify(o),{mode:384}),Ai.chmodSync(i,384),Ai.renameSync(i,r),j("[browser/vault] saved session",{profile:t,file:r})}catch(r){j("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as F9}from"crypto";function IM(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&L9.test(e.label))}function PM(e){return F9("sha256").update(e,"utf8").digest("hex").slice(0,8)}function MM(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var L9,Zm=T(()=>{"use strict";L9=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as N9}from"node:crypto";function B9(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function U9(e,t,n){return`el_${N9("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function j9(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function OM(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function DM(e,t){let n=e.role??"",r=e.name??"";$M.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])DM(i,t)}async function H9(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 d=window.getComputedStyle(s);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},FM).catch(()=>[])}async function W9(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 d="value"in i?i.value:void 0,u=d!==void 0?String(d):void 0,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},FM).catch(()=>[])}function K9(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function ef(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=K9(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=H9(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,m,f,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],DM(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await W9(e)).filter($=>$M.has($.role??"")));let w=new Map;for(let _ of m){let $=OM(_.name),B=w.get($);(!B||B.bbox.w===0&&_.bbox.w>0)&&w.set($,_)}let S=y.map(_=>({ax:_,dom:w.get(OM(_.name??""))})),v=r?S:S.filter(_=>_.dom?_.dom.bbox.w>0||_.dom.bbox.h>0:!0);v.sort((_,$)=>{let B=_.dom?.bbox.y??0,L=$.dom?.bbox.y??0;if(B!==L)return B-L;let W=_.dom?.bbox.x??0,P=$.dom?.bbox.x??0;return W-P}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=v.slice(0,n).map((_,$)=>{let B=_.ax.role??"generic",L=_.ax.name??"",W=U9(B,L,$),P=_.dom?.bbox??{x:0,y:0,w:0,h:0},U=_.dom?.type??null,N=null;_.ax.value!==void 0&&_.ax.value!==null&&(N=String(_.ax.value)),_.ax.checked!==void 0&&(N=String(_.ax.checked)),IM({role:B,kind:U})&&(N="[redacted]");let M={disabled:_.ax.disabled??!1};_.ax.checked!==void 0&&(M.checked=_.ax.checked===!0||_.ax.checked==="mixed"),_.ax.selected!==void 0&&(M.selected=_.ax.selected),_.ax.expanded!==void 0&&(M.expanded=_.ax.expanded);let O;_.dom?.testId?O=`[data-testid="${_.dom.testId}"]`:_.dom?.id&&(O=`#${_.dom.id}`);let H={id:W,role:B,label:B9(L),kind:U,value:N,state:M,bbox:P};return O!==void 0&&(H.selector=O),H}),D="idle";try{let _=await e.evaluate(()=>document.readyState);_==="loading"?D="loading":_==="interactive"?D="navigating":D="idle"}catch{D="navigating"}D!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=j9(f),A=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:A,url:g,title:h,textSummary:I,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:D,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var $M,FM,LM=T(()=>{"use strict";Zm();$M=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);FM="a[href], button, input, select, textarea, [role], [tabindex], label"});async function NM(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")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${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 qv(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>NM(e,i)))).filter(o=>o!==null)}async function G9(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 zv(e,t,n){switch(t.kind){case"element_id":return q9(e,t,n);case"selector":return z9(e,t);case"semantic":return J9(e,t)}}async function q9(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 qv(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function z9(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 qv(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function J9(e,t){return t.role!==void 0?V9(e,t.text,t.role):Y9(e,t.text,t)}async function V9(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 qv(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function Y9(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 d=[];s>0&&d.push({loc:r,count:s}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:i,count:l});let u=await G9(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=u.slice(0,5),f=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await NM(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let v=0;v<w.length;v++)S=S*31+w.charCodeAt(v)>>>0;f.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var BM=T(()=>{"use strict"});async function Jv(e,t,n,r){let o=e.url();if(o===n)return null;let i=Jm(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 UM=T(()=>{"use strict";Vm()});import{randomBytes as X9}from"crypto";import{mkdir as Q9,stat as Z9,writeFile as e7}from"fs/promises";import{join as Vv}from"path";import{gzip as t7}from"zlib";import{promisify as n7}from"util";function r7(e){return Vv(Xr(e),"browser")}function o7(e){return Vv(r7(e),"screenshots")}function i7(){return new Date().toISOString().replace(/[:.]/g,"-")}function s7(){return X9(3).toString("hex")}async function Yv(e,t,n){if(t.length>jM)throw new Error(`writeScreenshotSidecar: buffer exceeds ${jM} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=o7(e);await Q9(r,{recursive:!0});let o=`${i7()}-${s7()}-${n}.png`,i=Vv(r,o);await e7(i,t);let{size:s}=await Z9(i);return{path:i,bytes:s}}var xOe,jM,HM=T(()=>{"use strict";q();Zm();xOe=n7(t7);jM=5*1024*1024});var KM={};dp(KM,{PlaywrightProvider:()=>Xv});function WM(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 Xv,GM=T(()=>{"use strict";_M();LM();BM();Vm();UM();HM();Xv=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Qm(t)}async open(t){let n=Jm(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(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Jv(o,this.config,t.url,()=>this.close({sessionId:r}));if(u!==null)return u}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let d=await ef(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,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}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 ef(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 zv(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${WM(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=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 d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){c=y}else c=h}let u=await Jv(r,this.config,i,()=>this.close({sessionId:n}));if(u!==null)return u;let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await ef(r,{observationCounter:o.observationCounter,screenshotPath:m,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 d=await zv(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${WM(t.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await d.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await Yv(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path: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 Yv(n,o,r);return i}catch{return null}}}});var _i={};dp(_i,{__resetBrowserRegistryForTests:()=>u7,browserProviderActive:()=>c7,closeBrowserProvider:()=>Qv,getBrowserProvider:()=>l7,peekBrowserProvider:()=>d7});function qM(){Promise.resolve(Qv()).then(()=>{process.exit(130)})}function zM(){Promise.resolve(Qv()).then(()=>{process.exit(143)})}function JM(){nr=null}function a7(){tf||(process.on("SIGINT",qM),process.on("SIGTERM",zM),process.on("exit",JM),tf=!0)}function VM(){tf&&(process.removeListener("SIGINT",qM),process.removeListener("SIGTERM",zM),process.removeListener("exit",JM),tf=!1)}async function l7(e){return nr!==null?nr:(Ci!==null||(Ci=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(GM(),KM)),n=xM(e),r=new t(n);return a7(),nr=r,Ci=null,r})()),Ci)}async function Qv(){if(nr===null)return;let e=nr;nr=null,Ci=null,VM(),await e.shutdown()}function c7(){return nr!==null}function d7(){return nr}function u7(){nr=null,Ci=null,VM()}var nr,Ci,tf,Ii=T(()=>{"use strict";Vm();nr=null,Ci=null,tf=!1});async function YM(e,t){try{return await fM(e,t)}catch(n){return j("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function y7(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Ii(),_i));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function XM(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??y7,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s=e,a=null,l=null;try{let d=await zm(n,e,{headers:h7,signal:t.signal},o);a=d.status,s=d.url||e;let u=d.headers.get("content-type")??"";if(d.ok){if(g7.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let m=await d.text();if(f7.test(u)&&!m7.test(u))return{title:"",markdown:m.trim(),finalUrl:s,usedRender:!1};if(i=await YM(m,s),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof In||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;l=d}if(!(i===null||i.textLength<200)&&i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};try{await ed(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:m=>ed(m,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await ed(d.finalUrl,o);let u=await YM(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||u.textLength>=i.textLength)return{title:u.title,markdown:u.markdown,finalUrl:d.finalUrl,usedRender:!0}}catch(d){if(t.signal.aborted||d instanceof In)throw d;if(i===null){let u=d instanceof Error?d.message:String(d),m=l instanceof Error?l.message:`HTTP ${a??"error"}`,f=new Error(`web_scrape could not retrieve ${e}: fetch failed (${m}) and render failed (${u}).`);throw f.cause=d,f}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${a??"error"}).`)}var m7,f7,g7,h7,QM=T(()=>{"use strict";gM();Kv();ue();m7=/(text\/html|application\/xhtml\+xml)/i,f7=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,g7=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,h7={"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 S7(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(b7,{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),w7),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Rr(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}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 ZM(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?S7({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 e0(e,t){if(t.length===0)return`# Search results for "${e}"
895
895
 
896
896
  (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(`
897
897
  `).trimEnd()}var b7,w7,t0=T(()=>{"use strict";fo();b7="https://api.exa.ai/search",w7=10});function nf(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 Pi=T(()=>{"use strict";Ym()});function R7(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=v7;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,k7)}let a=T7;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,E7)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function Zv(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:xr(e,t),truncated:!0}}function A7(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=R7(o);if("error"in s)return{content:s.error,isError:!0};if(i.aborted){let u=i.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let a=new AbortController,l=()=>{a.abort(i.reason)},c,d=()=>{let u=a.signal.reason;return u instanceof Error?u.message:String(u??"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 m=await Wv(s.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(!m.allowed)return{content:`web_scrape blocked: ${m.reason}`,isError:!0}}if(s.mode==="raw"){let m;try{let h={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};m=await zm(t,s.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:h instanceof In?{content:`web_scrape blocked: ${h.message}`,isError:!0}:{content:`web_scrape network error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}if(!m.ok)return{content:`web_scrape HTTP ${m.status} ${m.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let f;try{f=await m.text()}catch(h){return{content:`web_scrape read error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let g=Zv(f,s.maxBytes);return{content:g.content,...g.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let m=await XM(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:a.signal,...e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{}});if(m.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let f=Zv(m.markdown,s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(m){if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(m instanceof In)return{content:`web_scrape blocked: ${m.message}`,isError:!0};let f=m instanceof Error?m.message:String(m),g=Ft(m)&&!Gv(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${td()}\`)`:"";return{content:`web_scrape markdown error: ${f}${g}`,isError:!0}}let u=ZM({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in u)return{content:u.error,isError:!0};try{let m=await u.search(s.query,{limit:x7,timeoutMs:s.timeoutMs,signal:a.signal}),f=Zv(e0(s.query,m),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(m){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${m instanceof Error?m.message:String(m)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),i.removeEventListener("abort",l)}}}var v7,k7,T7,E7,x7,n0,r0=T(()=>{"use strict";QM();t0();Kv();wi();Pi();v7=3e4,k7=12e4,T7=1e5,E7=1e6,x7=10;n0=A7()});import{existsSync as i0,mkdirSync as C7,readFileSync as _7,renameSync as I7,unlinkSync as P7,writeFileSync as M7}from"node:fs";import{dirname as o0,join as O7}from"node:path";import{randomBytes as $7}from"node:crypto";function ln(e){let t=e??Fw();if(!i0(t))return[];try{let n=_7(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 Mi(e,t){let n=t??Fw();C7(o0(n),{recursive:!0});let r=O7(o0(n),`.schedules.json.${process.pid}.${$7(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{M7(r,o,"utf-8"),I7(r,n)}catch(i){try{i0(r)&&P7(r)}catch{}throw i}}function rf(e,t){let n=ln(t),r=n.map(l=>l.id),o=D7(e.name),i=F7(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),Mi(n,t),a}function of(e,t){let n=ln(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(Mi(o,t),!0)}function rd(e,t){return ln(t).find(n=>n.id===e)}function D7(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function F7(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function s0(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 sf=T(()=>{"use strict";q()});import{existsSync as L7,readFileSync as N7}from"node:fs";import{join as B7}from"node:path";async function Pn(e,t,n){let r;try{let o=B7(Sp("default"),"port");if(!L7(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=N7(o,"utf-8").trim();if(r=parseInt(i,10),Number.isNaN(r))return{synced:!1,detail:"daemon-not-detected (invalid port file)"}}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let o=await fetch(`http://localhost:${r}${t}`,{method:e,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return o.ok?{synced:!0,detail:"synced"}:e==="POST"&&o.status===409?{synced:!0,detail:"already-registered"}:e==="DELETE"&&o.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${o.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}var yo,ek=T(()=>{"use strict";q();yo="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 U7}from"node:fs";import{readFile as j7}from"node:fs/promises";var a0,l0,c0,d0,u0=T(()=>{"use strict";sf();q();ek();a0=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=rf({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 Pn("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 Pn("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:yo}})}},l0=async(e,t)=>{let n=ln();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})))}},c0=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=Kn();if(!U7(i))return{content:JSON.stringify([])};let s;try{let c=await j7(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
@@ -1784,7 +1784,7 @@ ${v}
1784
1784
  ${E}`})}return{fileBlocks:l,warnings:c}}async function x2(e,t,n,r,o="summary",i,s){let a=N1(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),hl(process.stdout,cu(process.cwd(),!0));let l="",c=0,d=!1,u=!1,m=!1,f=!1,g=!1,h,y=!1,b=!1,w={abort:null},S=0,v=3e3,E=[],R=new Map,D=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,I=()=>{let L=r.subagentControl;L?.hasPromotableForeground()&&L.promoteActiveForeground().then(W=>{for(let P of W)(i??{fn:console.log}).fn(p.dim(` \u2192 subagent backgrounded as ${P.jobId}: ${P.label}`))}).catch(()=>{})},A=r.getCompositor?r.getCompositor():null,C=()=>new Ml({out:Ol(i),thinkingMode:o,...D?{activeSkillName:D}:{},onCancel:()=>{t.interrupt().catch(L=>{Le()&&console.error(" "+p.error("session.interrupt() failed:"),L)})},...r.subagentControl?{onBackground:I}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...A?{compositor:A}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),_=C(),$=async()=>{if(!f){f=!0;try{await _.dispose()}catch{}}},B=async()=>{await _.arm();let L=_.getCompositor();if(i&&L){let W=L;i.fn=P=>W.commitAbove(P),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(L),r.setInterruptNotifier?.(W=>_.setInterrupting(W)),r.rearmStatus?.()};try{A?A.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{y=!0,_.setSoftStopping(!0),t.interrupt().catch(O=>{Le()&&console.error(" "+p.error("soft-stop session.interrupt() failed:"),O)});let M=r.subagentControl;M?.hasActiveForeground()&&M.cancelActiveForeground().catch(O=>{Le()&&console.error(" "+p.error("soft-stop cancelActiveForeground() failed:"),O)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{b=!0,t.interrupt().catch(M=>{Le()&&console.error(" "+p.error("pause-interrupt session.interrupt() failed:"),M)})}),await B(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(I);let{fileBlocks:L,warnings:W}=E2(e.text,{rootDir:process.cwd()});for(let M of W)(i??{fn:console.log}).fn(p.dim(` @-file: ${M}`));let P=L.length>0||e.attachments.length>0?T2(e.text,e.attachments,void 0,L):e.text,U=t.sendMessageStream(P);if(await sa((M,O)=>{_.process(M,O)},async()=>{for await(let M of U){if(y||b)break;if(M.type==="chunk"&&M.chunk.type==="content"?(l=d?v2(l,M.chunk.content):l+M.chunk.content,d=!1,u=!0):M.type==="message"&&!u&&(l=M.message.content),M.type==="stream_retry"&&(l=l.slice(0,c),d=l.length>0),M.type==="chunk"&&M.chunk.type==="tool_use_detail"){let O=M.chunk,H={toolName:O.toolName,toolUseId:O.toolUseId,input:O.toolInput,...O.toolInputRaw!==void 0&&{inputRaw:O.toolInputRaw}};R.set(O.toolUseId,H),E.push(H)}else if(M.type==="chunk"&&M.chunk.type==="tool_result"){let O=M.chunk;c=l.length,d=!0;let H=R.get(O.toolUseId);if(H&&(H.result=O.content,H.isError=O.isError,R.delete(O.toolUseId)),r.onContextProgress){let X=Date.now();if(X-S>=v){S=X;try{let K=r.onContextProgress();K instanceof Promise&&await K}catch(K){Le()&&console.error(" "+p.error("onContextProgress (status refresh) failed:"),K)}}}}if(M.type==="paused"){if(r.setPausedState?.(!0),await $(),A&&M.autoResume===!0){let O=new AbortController;w.abort=O;let H=M.resetsAt?M.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,X=H?`Keep waiting \u2014 auto-resumes at ${H}`:"Keep waiting \u2014 auto-resume in progress",K="Switch model / provider (type /model after)",Q="Stop waiting",ae=[p.warning(" \u23F3 Usage limit reached.")+(H?p.dim(` Auto-resumes at ${H}.`):""),p.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Sn(A,{header:ae,options:[X,K,Q],signal:O.signal,initialIndex:0}).then(z=>{if(w.abort=null,!z)return;let ee=z[0];ee===void 0||ee===X||(b=!0,ee===K&&(i??{fn:console.log}).fn(p.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(oe=>{Le()&&console.error(" "+p.error("picker pause-interrupt session.interrupt() failed:"),oe)}))}).catch(z=>{Le()&&console.error(" "+p.error("picker promise rejected:"),z)})}else(i??{fn:console.log}).fn(r_({reason:M.reason,...M.resetsAt!==void 0?{resetsAt:M.resetsAt}:{},...M.accountId!==void 0?{accountId:M.accountId}:{},...M.autoResume!==void 0?{autoResume:M.autoResume}:{}}));continue}if(M.type==="resumed"){r.setPausedState?.(!1),w.abort?.abort(),w.abort=null;let O=M.hotSwapped&&M.accountId?`\u25B6 Resumed on ${M.accountId}`:"\u25B6 Resumed";l="",c=0,d=!1,u=!1,E.length=0,R.clear(),g=!1,h=void 0,m=!1,_=C(),f=!1,await B(),(i??{fn:console.log}).fn(p.success(O));continue}if(M.type==="error"){await $(),Ws(Ls(M.error)),m=!0;continue}_.process(M),M.type==="done"&&(g=!0,h=M.metadata)}}),await $(),y){let M=i?i.fn:console.log,O=A?A.getPendingCount():0,H=O>0?` \xB7 ${O} queued`:"";M(p.warning(`\u23F8 Stopped${H} \u2014 work so far kept.`)+p.dim(" Send a message to continue.")),M("")}if(b){let M=i?i.fn:console.log;M(p.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),M("")}if(g&&!y&&!b){Qi(n,a,l,h,E),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),gl(process.stdout),Ij(process.stdout,"afk: turn complete");let M=H=>{i?i.fn(H):console.log(H)},O=Lb(l);if(O){M(k2(O)),M("");let H=sK(E);if(r.onTerminalState)try{r.onTerminalState(O,{doneHasCorroboratingEvidence:H})}catch{}if(n.permissionMode==="autonomous"){let X=O.kind==="done"&&Uc().verifyDone===!0&&!H;lK(O,void 0,{unverified:X})}}if($he(h,n,M),r.onAfterTurn){let H=r.onAfterTurn();H instanceof Promise&&await H.catch(()=>{})}}}catch(L){await $(),m||Ws(Ls(L))}finally{await $(),hl(process.stdout,cu(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),w.abort?.abort(),w.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function Ohe(e,t){let n=Math.round(e*100),r=ge(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${ge(o)} tok \u2014 model output may be silently truncated`}}return e>=.95?{tier:"near",text:` context ${n}% used of ${r} \u2014 near limit; output may soon truncate (consider /clear or a fresh session)`}:e>=.8?{tier:"caution",text:` context ${n}% used of ${r} \u2014 approaching limit`}:e>.5?{tier:"normal",text:` context ${n}% used of ${r}`}:{tier:"quiet",text:null}}function $he(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(Re(e.durationMs)),e.totalCostUsd!==void 0&&r.push(it(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(ge(o+i)+" tok"),r.length>0&&n(p.dim(" \u25E6 "+r.join(" \xB7 ")));let s=Zx(t),a=qt(t.model),l=Ohe(s,a);if(l.text!==null){let d=l.tier==="over"||l.tier==="near"?p.error:l.tier==="caution"?p.warning:p.dim;n(d(l.text))}let c=S2(Wy(sh()),new Date,{autoResume:PI()});if(c.text!==null){let d=c.tier==="over"||c.tier==="near"?p.error:c.tier==="caution"?p.warning:p.dim;n(d(c.text))}n("")}var Dhe=5e3,Fhe=3,Lhe="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function Nhe(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(p.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function R2(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,verdictLedger:d,shellPassthrough:u,bgResultNotifier:m}=s,f=null,g=[];e.session.current.waitForInitialization().then(async D=>{Le()&&(f=ib(D)),await Pu(e.session.current),Le()&&(g=Yx())}).catch(()=>{});let h=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,y,b=!1,w=!1,S,v,E,R=0;for(m.onInjectable=()=>{R>=Fhe||!o.isAwaitingInput()||!o.bufferIsEmpty()||(R++,gl(process.stdout),h={text:Lhe,attachments:[]},o.abortPendingRead())};;){if(f&&(e.replRenderer.writeLine(f),e.replRenderer.writeLine(""),f=null),g.length>0){for(let P of g)e.replRenderer.writeLine(P);e.replRenderer.writeLine(""),g=[]}let D=u.drainNotifications();for(let{job:P,result:U}of D){let N=U.errorReason===void 0?"\u2713":"\u2717",M=U.errorReason==="abort"?"killed":U.errorReason==="timeout"?"timed out":U.errorReason==="signal-killed"?"killed by signal":`exit ${U.exitCode??0}`,O=Math.max(0,Math.round(U.durationMs/100)/10);e.replRenderer.writeLine(p.dim(` ${N} [${P.id}] ${M} \xB7 ${O}s \xB7 `)+P.command)}let I=m.drainNotifications();for(let{job:P}of I){let U=P.status==="completed"?"\u2713":P.status==="failed"?"\u2717":"\u2298",N=P.endedAt!==void 0?Math.max(0,Math.round((P.endedAt-P.startedAt)/100)/10):0,M=P.label.length>60?`${P.label.slice(0,60)}\u2026`:P.label;e.replRenderer.writeLine(p.dim(` ${U} [${P.jobId}] subagent ${P.status} \xB7 ${N}s \xB7 `)+M)}let A=l.renderIfChanged(e.stats.sessionId);if(A.length>0){for(let P of A)e.replRenderer.writeLine(P);e.replRenderer.writeLine("")}let C,_;if(h===void 0){let P=await e.session.current.takePendingPlanExitSeed();P!==void 0&&(e.stats.permissionMode=P.mode,h={text:P.message,attachments:[]})}if(h!==void 0){let P=h;h=void 0;let U=Bl(e.stats.permissionMode),N=rs({buffer:P.text,promptText:U,isTTY:!!process.stdout.isTTY,attachmentSummary:Tl([...P.attachments])});e.replRenderer.writeLine(N),C=P.text.trim(),_=P.attachments}else{let P=y;y=void 0;let U=await o.readLine({promptFn:()=>Bl(e.stats.permissionMode),...P!==void 0?{initialBuffer:P}:{},onSigint:r,onShiftTab:()=>{Ob(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});C=U.text.trim(),_=U.attachments}if(!C&&_.length===0)continue;if(C.startsWith("!")){let P=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!P&&(b||(b=!0,e.replRenderer.writeLine(p.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await u.dispatch(C))){e.statusLine.rearm();continue}}let $=!1;if(C.startsWith("/")){let P=await Oj(C,e.slashCtx,_);if(P.handled){if(P.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if((C==="/clear"||C.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(p.dim(` transcript: ${t.path()}`)),d.reset(),S=void 0),P.result!==null&&typeof P.result=="object"&&"kind"in P.result&&P.result.kind==="submit"){h={text:P.result.message,attachments:_??[]},e.statusLine.rearm();continue}if(P.result!==null&&typeof P.result=="object"&&"kind"in P.result&&P.result.kind==="prefill"){y=P.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}$=!0}a.push(C),await Nhe(e,C);let B=C;if($){let P=cx(C);if(P){let U=P.name.replace(/^\//,"").split(":").pop()??"";if(U&&qx(U)){let N={skillName:U,rawArgs:P.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},M=e.session.current.sessionId,O=fs(M),H=Date.now();j(`[afk trace] preflight.start commandName=${U}`);let X=!1,K=await ms(N,{cwd:e.stats.cwd??process.cwd(),artifactDir:O},Q=>{Le()&&e.replRenderer.writeLine(p.warning(`\u26A0 preflight(${U}) failed: `)+(Q instanceof Error?Q.message:String(Q)))});X=K!==null,j(`[afk trace] preflight.end commandName=${U} durationMs=${Date.now()-H} success=${X}`),B=Jx(K?.manifestBlock,C)}}}let L=u.drainInjections();L.length>0&&(B=L+B);let W=m.drainInjections();if(W.length>0&&(B=W+B),S!==void 0&&(B=S+`
1785
1785
 
1786
1786
  `+B,S=void 0),e.hookRegistry)try{let P={event:"UserPromptSubmit",prompt:B,sessionId:e.stats.sessionId},U=await e.hookRegistry.dispatch(P);U.injectContext&&(B=U.injectContext+B)}catch(P){if(P instanceof Ee){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+(P.reason?p.dim(`: ${Rr(P.reason)}`):"")),e.statusLine.rearm();continue}if(P instanceof Xn){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+p.dim(`: handler timed out after ${P.timeoutMs}ms`)),e.statusLine.rearm();continue}throw P}if(v=void 0,E=void 0,await x2({text:B,attachments:_},e.session.current,e.stats,{setInFlight(P){n.turnInFlight=P},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(P){await t.appendUser(P)},async onTurnComplete(P,U){if(await t.appendTurn(P,U),e.stats.sessionId)try{Fo(e.stats)}catch(N){w||(w=!0,e.replRenderer.writeLine(p.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(N instanceof Error?N.message:String(N))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(P,U)=>{d?.push(P),v=P.kind,E=U?.doneHasCorroboratingEvidence},setActiveCompositor:P=>{n.activeCompositor=P},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(Un(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:P=>c.repaint(P)}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(Bl(e.stats.permissionMode))),e.hookRegistry)try{let P=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...v!==void 0?{terminalState:v}:{},...E!==void 0?{doneHasCorroboratingEvidence:E}:{}},void 0,Dhe);P.injectContext&&P.injectContext.trim().length>0&&(S=P.injectContext)}catch(P){if(P instanceof at)throw P;P instanceof Xn?(j("[stop hook] handler timed out"),e.completionWriter.fn(p.dim(" [stop hook] timed out"))):P instanceof Ee?e.completionWriter.fn(p.dim(` [stop hook] blocked: ${Rr(P.reason??"no reason given")}`)):j("[stop hook] unexpected error: "+String(P))}}}function Bhe(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 A2(e,t,n,r){let o=await r2(),i=new Mb({rl:e.rl,history:o,statusLine:e.statusLine}),s=Bhe(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await l2(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar});a=b2(e,n),await R2(e,t,n,r,i,l,a,o),await e.resolveWorktreeDisposition?.(!0)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.bgResultNotifier.dispose(),a?.loopStageBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await i.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}Dc();ha();import{execFile as Uhe}from"node:child_process";import{dirname as jhe,isAbsolute as Hhe,resolve as Whe}from"node:path";import{promisify as Khe}from"node:util";var C2=Khe(Uhe),Ghe=3e3,qhe=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function zhe(){let t=(await C2("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=Hhe(t)?t:Whe(process.cwd(),t);return jhe(n)}async function _2(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await zhe()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),Ghe)});try{let o=dn({execFile:C2,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=>qhe.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Hp();Dc();import{promises as Jhe}from"node:fs";import{dirname as Vhe,join as M2}from"node:path";import{randomBytes as Yhe}from"node:crypto";var Xhe=["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(`
1787
- `),I2=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,qR=30,Qhe=1024,Zhe=8e3,eye="haiku";async function tye(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=iye(n,Qhe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??Zhe),s=t.signal?sye([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await Js({token:t.token,model:t.model??eye,system:Xhe,user:r,maxTokens:32,signal:s})}catch(u){let m=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=nye(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=Vhe(t.worktreePath);return await rye(l,c)}function nye(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(I2.test(t)&&t.length<=qR)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>qR)break;o=s}return I2.test(o)?o:null}async function rye(e,t){if(!await oye(M2(t,e)))return e;let n=Yhe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,qR-5)}-${n}`}async function oye(e){try{return await Jhe.access(e),!0}catch{return!1}}function iye(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 sye(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 O2(e){let t,n,r=M2(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await tye(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=`${lm(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return P2(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 P2(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 P2(e,t){e&&e.setCwd(t),aye(t)}function aye(e){try{process.chdir(e)}catch{}}_t();q();import{spawn as D2}from"child_process";import{existsSync as F2,mkdirSync as pye,readFileSync as L2,unlinkSync as $2,writeFileSync as N2}from"fs";import{get as mye}from"https";import{join as B2}from"path";import{readFileSync as lye}from"fs";import{dirname as cye,join as dye}from"path";import{fileURLToPath as uye}from"url";function mr(){try{return"5.89.0"}catch{}try{let e=cye(uye(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(lye(dye(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}G();var fye=64*1024,gye=10800*1e3,hye=800,yye=3600*1e3,bye="update-check.json",wye="pending-update.json";function zR(){return B2($s(),bye)}function Hu(){return B2($s(),wye)}function JR(){let e=$s();F2(e)||pye(e,{recursive:!0})}function U2(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 j2(){try{let e=L2(zR(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function H2(){try{JR();let e=`
1787
+ `),I2=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,qR=30,Qhe=1024,Zhe=8e3,eye="haiku";async function tye(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=iye(n,Qhe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??Zhe),s=t.signal?sye([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await Js({token:t.token,model:t.model??eye,system:Xhe,user:r,maxTokens:32,signal:s})}catch(u){let m=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=nye(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=Vhe(t.worktreePath);return await rye(l,c)}function nye(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(I2.test(t)&&t.length<=qR)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>qR)break;o=s}return I2.test(o)?o:null}async function rye(e,t){if(!await oye(M2(t,e)))return e;let n=Yhe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,qR-5)}-${n}`}async function oye(e){try{return await Jhe.access(e),!0}catch{return!1}}function iye(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 sye(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 O2(e){let t,n,r=M2(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await tye(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=`${lm(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return P2(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 P2(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 P2(e,t){e&&e.setCwd(t),aye(t)}function aye(e){try{process.chdir(e)}catch{}}_t();q();import{spawn as D2}from"child_process";import{existsSync as F2,mkdirSync as pye,readFileSync as L2,unlinkSync as $2,writeFileSync as N2}from"fs";import{get as mye}from"https";import{join as B2}from"path";import{readFileSync as lye}from"fs";import{dirname as cye,join as dye}from"path";import{fileURLToPath as uye}from"url";function mr(){try{return"5.89.1"}catch{}try{let e=cye(uye(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(lye(dye(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}G();var fye=64*1024,gye=10800*1e3,hye=800,yye=3600*1e3,bye="update-check.json",wye="pending-update.json";function zR(){return B2($s(),bye)}function Hu(){return B2($s(),wye)}function JR(){let e=$s();F2(e)||pye(e,{recursive:!0})}function U2(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 j2(){try{let e=L2(zR(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function H2(){try{JR();let e=`
1788
1788
  const https = require('https');
1789
1789
  const fs = require('fs');
1790
1790
  const url = 'https://registry.npmjs.org/agent-afk/latest';