agent-afk 5.33.1 → 5.33.2

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
@@ -4,7 +4,7 @@ var D1=Object.defineProperty;var R=(e,t)=>()=>(e&&(t=e(e=0)),t);var kd=(e,t)=>{f
4
4
  `)}return n.accessToken}function LT(){if(process.platform==="darwin")try{return OT("security",["find-generic-password","-s","Claude Code-credentials","-a",DT().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()}catch{return}if(process.platform==="linux"){let e=FT($T(),".claude",".credentials.json");if(!qH(e))return;try{return zH(e,"utf-8")}catch{return}}}function NT(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t!="object"||t===null)return;let n=t.claudeAiOauth;if(typeof n!="object"||n===null)return;let r=n,o=r.accessToken;if(typeof o!="string"||o.length===0)return;let i={accessToken:o},s=r.refreshToken;typeof s=="string"&&s.length>0&&(i.refreshToken=s);let a=r.expiresAt;return typeof a=="number"&&(i.expiresAt=a),i}async function ZH(e){try{let t=await fetch(YH,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:e,client_id:VH})});if(!t.ok)return;let n=await t.json(),r=n.access_token,o=n.expires_in;if(typeof r!="string"||typeof o!="number")return;let i=n.refresh_token;return{accessToken:r,expiresAt:Date.now()+o*1e3,...typeof i=="string"&&i.length>0?{refreshToken:i}:{}}}catch{return}}function Hr(e){if(!e||e.length<3)return"token:(unknown)";try{let n=e.split(".");if(n.length<2)throw new Error("not a JWT");let r=Buffer.from(n[1],"base64url").toString("utf-8"),o=JSON.parse(r),i=typeof o.email=="string"&&o.email||typeof o.sub=="string"&&o.sub||typeof o.account_id=="string"&&o.account_id||typeof o.preferred_username=="string"&&o.preferred_username;if(i)return i}catch{}return`token:${e.length>=8?e.slice(-8):e}`}function QH(e){if(process.platform==="darwin")OT("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",DT().username,"-w",e],{stdio:["ignore","ignore","ignore"]});else if(process.platform==="linux"){let t=FT($T(),".claude",".credentials.json");eW(t,e)}}function eW(e,t){JH(e,t,{encoding:"utf-8",mode:384})}var VH,YH,XH,ts=R(()=>{"use strict";VH="9d1c250a-e61b-44d9-88ed-5944d1962f5e",YH="https://platform.claude.com/v1/oauth/token",XH=300*1e3});function xt(e,t){if(e===null||typeof e!="object")return;let n=e.headers;if(n==null)return;if(typeof n.get=="function")return n.get(t)??void 0;if(typeof n=="object"){let o=n,i=o[t]??o[t.toUpperCase()];return typeof i=="string"?i:void 0}}function Zd(e){let t=xt(e,"retry-after-ms");if(t!==void 0){let r=Number(t);if(Number.isFinite(r)&&r>=0)return r}let n=xt(e,"retry-after");if(n!==void 0){let r=Number(n);if(Number.isFinite(r)&&r>=0)return Math.round(r*1e3);let o=Date.parse(n);if(!Number.isNaN(o)){let i=o-Date.now();if(i>=0)return i}}}function BT(e){if(!Number.isFinite(e)||e<=0)return;let t=e*1e3;if(!(t>nW))return new Date(t)}function oy(e){if(!("status"in e))return null;let t=e.status;if(t===429){let n=e.message.split("|");if(n.length>=2){let l=BT(parseInt(n[1].trim(),10));if(l!==void 0)return{kind:"oauth-limit",resetsAt:l}}let r=xt(e,"anthropic-ratelimit-unified-representative-claim"),o=xt(e,"anthropic-ratelimit-unified-overage-status"),i=xt(e,"anthropic-ratelimit-unified-status");if(r!==void 0||o!==void 0||i==="rejected"){let l=xt(e,"anthropic-ratelimit-unified-reset");if(l!==void 0){let c=BT(Number(l));if(c!==void 0)return{kind:"oauth-limit",resetsAt:c}}return{kind:"oauth-limit-no-ts"}}if(xt(e,"anthropic-ratelimit-requests-remaining")!==void 0||xt(e,"anthropic-ratelimit-requests-limit")!==void 0||xt(e,"anthropic-ratelimit-requests-reset")!==void 0||xt(e,"anthropic-ratelimit-input-tokens-remaining")!==void 0||xt(e,"anthropic-ratelimit-input-tokens-limit")!==void 0||xt(e,"anthropic-ratelimit-input-tokens-reset")!==void 0||xt(e,"anthropic-ratelimit-output-tokens-remaining")!==void 0||xt(e,"anthropic-ratelimit-output-tokens-limit")!==void 0||xt(e,"anthropic-ratelimit-output-tokens-reset")!==void 0)return{kind:"rate-limit-transient",retryAfterMs:Zd(e)};let a=Zd(e);return a!==void 0&&a<=tW?{kind:"rate-limit-transient",retryAfterMs:a}:{kind:"oauth-limit-no-ts"}}return t===400&&e.message.includes("invalid_request_error")&&e.message.includes("credit balance")?{kind:"credit-exhausted"}:null}async function UT(e){let{resetsAt:t,signal:n,readToken:r=Tt}=e,o=r(),i=t.getTime()+3e4;return new Promise(s=>{let a,l=!1,c=m=>{l||(l=!0,a!==void 0&&clearInterval(a),n.removeEventListener("abort",d),s(m))},d=()=>{c("aborted")},u=()=>n.aborted?(c("aborted"),!0):Date.now()>=i?(c("timer"),!0):r()!==o?(c("hot-swap"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),n.addEventListener("abort",d,{once:!0}))})}async function jT(e){let{signal:t,readToken:n=Tt,retryAfterMs:r}=e,o=n(),i=r!==void 0?Date.now()+r:void 0;return new Promise(s=>{let a,l=!1,c=m=>{l||(l=!0,a!==void 0&&clearInterval(a),t.removeEventListener("abort",d),s(m))},d=()=>{c("aborted")},u=()=>t.aborted?(c("aborted"),!0):n()!==o?(c("hot-swap"),!0):i!==void 0&&Date.now()>=i?(c("timer"),!0):!1;u()||(a=setInterval(()=>{u()},3e4),a.unref(),t.addEventListener("abort",d,{once:!0}))})}var tW,nW,iy=R(()=>{"use strict";ts();tW=300*1e3;nW=864e13});function sy(e,t=fetch){return e?async(n,r)=>{let o=await t(n,r);if(rW.has(o.status)){let i=Zd({headers:o.headers}),s={status:o.status,reason:o.status===429?"rate-limit":"overloaded",source:"sdk-fetch"};i!==void 0&&(s.retryAfterMs=i),ye(e,{phase:"rate_limit",...i!==void 0?{durationMs:i}:{},metadata:s})}return o}:t}var rW,HT=R(()=>{"use strict";xe();iy();rW=new Set([429,503,529])});function Dn(e){return e==="bypassPermissions"||e==="autonomous"}var hl=R(()=>{"use strict"});function Qd(e){if(typeof e?.baseUrl=="string"&&e.baseUrl.length>0)return!1;let t=k.AFK_DISABLE_PROMPT_CACHE;if(t===void 0||t.length===0)return!0;let n=t.toLowerCase();return!(n==="1"||n==="true"||n==="yes"||n==="on")}function eu(){let e=k.AFK_PROMPT_CACHE_TTL;return e==="5m"?"5m":e==="1h"?"1h":oW}function WT(e,t){if(e.length===0)return e;let n=e[e.length-1],r=GT(n,t);return r===n?e:[...e.slice(0,-1),r]}function KT(e,t){if(e.length===0)return e;let n=e[e.length-1],r=iW(n,t);return r===n?e:[...e.slice(0,-1),r]}function iW(e,t){let n=e.content;if(typeof n=="string")return n.length===0?e:{...e,content:[{type:"text",text:n,cache_control:{type:"ephemeral",ttl:t}}]};if(!Array.isArray(n)||n.length===0)return e;let r=n[n.length-1],o=GT(r,t);return o===r?e:{...e,content:[...n.slice(0,-1),o]}}function GT(e,t){return e.type==="thinking"||e.type==="redacted_thinking"?e:{...e,cache_control:{type:"ephemeral",ttl:t}}}var oW,ay=R(()=>{"use strict";q();oW="1h"});function ly(e){return e!=="plan"?null:{type:"text",text:tu}}var tu,cy=R(()=>{"use strict";tu=["## Plan mode is active","","File and memory write tools (`write_file`, `edit_file`, `memory_update`, `procedure_write`) are refused at the hook layer.","`bash` runs for read-only investigation (git status/log/diff, ls, cat, grep, find \u2014 chained or not); state-mutating bash (file writes, rm, installs, commits, pushes) is refused while planning. The user has asked you to plan, not yet to act \u2014 exit plan mode to make changes.","Treat this turn as planning work.","","Traverse the shape that matches the work \u2014 skip steps the terrain already covers, do not skip steps the terrain hides:",""," unknown field \u2192 ground the current terrain \u2192 gather missing codebase context \u2192"," research missing external context \u2192 reveal chaos / constraints / risks \u2192"," name the failure geometry \u2192 form a candidate plan \u2192 apply adversarial pressure \u2192 embody the final plan","","Reach for these skills (invoke via the `skill` tool) when the cost of skipping exceeds the cost of dispatching:"," - `ground-state` \u2014 survey git, infra, memory before non-trivial work"," - `gather` \u2014 parallel context-gathering for a code area"," - `research` \u2014 parallel external + local context for the current task"," - `devils-advocate` \u2014 generate alternatives and rank them before committing"," - `shadow-verify` \u2014 independently re-derive load-bearing claims","","Do not declare readiness silently. When the plan is ready, state: chosen approach, risks named, and alternatives considered.","","Then, IF the task requires implementation (writing code or files), call the `exit_plan_mode` tool to present your plan. The user picks how to proceed (approve and implement, or keep planning). After calling it, END YOUR TURN \u2014 on approval you will receive a separate instruction to save the plan to a file and implement it. Do NOT use `ask_question` to ask whether the plan is OK; that is exactly what `exit_plan_mode` does \u2014 use `ask_question` only to resolve open requirement questions first. For research / read-only tasks that need no code changes, do NOT call `exit_plan_mode` \u2014 just answer.","","Manual fallbacks remain: the user can exit with `/plan off` (same save-and-implement handoff), and Shift+Tab advances the permission-mode ring without saving or implementing. Keep the plan concrete and complete enough to act on directly."].join(`
5
5
  `)});var qT=R(()=>{"use strict";cy()});function dy(e){return e!=="autonomous"?null:{type:"text",text:nu}}var nu,uy=R(()=>{"use strict";nu=["## AFK mode is active","","The operator is away from keyboard. Your channel to them is Telegram via the `send_telegram` tool \u2014 not this transcript, which no one is watching live. At the end of each turn, push your terminal state (Done / Blocked / Asking) to Telegram so the operator can review asynchronously.","","Posture \u2014 bounded autonomy, not unchecked action:"," - Proceed autonomously on reversible work. Do not stop to confirm actions you are already authorized to take and can undo (edits, reads, tests, local commits, non-force pushes, installs)."," - At a one-way door \u2014 anything irreversible, externally visible, credential- or payment-touching, or where multiple readings lead to materially different work \u2014 do NOT guess. Push a concise Asking summary to Telegram naming the decision and your recommended default, then stop and end the turn in the Asking state."," - A mechanical gate refuses high-risk and irreversible operations at the hook layer regardless of this text. Treat a gate refusal as a signal to surface the decision to the operator, not an obstacle to work around.","","Communication discipline:"," - Batch updates. Send a Telegram message at terminal state (and at a genuinely blocking fork), not a play-by-play \u2014 the operator gets a push notification for every message."," - Keep pushes short and scannable: what happened, what changed, what (if anything) you need. Never paste raw tool output, logs, secrets, or full file contents into a push.","","Exit: the operator returns and runs `/afk off` (or Shift+Tab) to restore default permissions and terminal-channel interaction."].join(`
6
6
  `)});var zT=R(()=>{"use strict";uy()});function JT(e,t=()=>{}){let n=new Set;if(!e)return n;for(let r of e.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){t("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}var VT=R(()=>{"use strict"});var ns,ru,py=R(()=>{"use strict";ns={model:"sonnet",maxTokens:4096,temperature:1,updatePolicy:"notify"},ru="bypassPermissions"});function my(){return k.ANTHROPIC_API_KEY||k.CLAUDE_CODE_OAUTH_TOKEN||Tt()}function fy(){return k.OPENAI_API_KEY||k.CODEX_API_KEY||void 0}function Le(e){let t=re(e);return t==="openai-compatible"||t==="openai-codex"?fy():my()}var Nt=R(()=>{"use strict";Je();ts();q()});import{existsSync as sW}from"fs";import{join as aW}from"path";import{config as lW}from"dotenv";function ou(){return my()}function ZT(e){let t=e.trim();if(!t)return t;let n="/chat/completions";if(t.endsWith(n)){let r=t.slice(0,-n.length);return XT.has(t)||(XT.add(t),console.warn(`[afk] AFK_OPENAI_BASE_URL: stripped trailing "/chat/completions" \u2014 the OpenAI SDK appends it automatically.
7
- Effective base URL: ${r}`)),r}return t}function QT(){if(gy!==void 0)return gy;if(!YT){let o=[aW(process.cwd(),".env"),kt(),KE()];for(let i of o)sW(i)&&lW({path:i,override:!1});YT=!0}let e={},t=k.AFK_MODEL??k.CLAUDE_MODEL;if(t){let o=t.toLowerCase();e.model=gl(o)?o:t}if(re(t)==="anthropic-direct"){let o=ou();o!==void 0&&(e.apiKey=o)}let r=k.AFK_LOCAL_BASE_URL;if(r&&r.length>0&&(e.baseUrl=r,e.apiKey=k.AFK_LOCAL_API_KEY||"local"),k.AFK_MAX_TOKENS&&(e.maxTokens=parseInt(k.AFK_MAX_TOKENS,10)),k.AFK_TEMPERATURE&&(e.temperature=parseFloat(k.AFK_TEMPERATURE)),k.AFK_SYSTEM_PROMPT&&(e.systemPrompt=k.AFK_SYSTEM_PROMPT),k.AFK_AUTO_ROUTING){let o=k.AFK_AUTO_ROUTING.toLowerCase()==="true";e.autoRouting={interactive:o,chat:o,telegram:o,daemon:o}}return k.AFK_OPENAI_BASE_URL&&(e.openaiBaseUrl=ZT(k.AFK_OPENAI_BASE_URL)),gy=e,e}var YT,gy,XT,hy=R(()=>{"use strict";vn();Je();G();Nt();q();YT=!1;XT=new Set});import{basename as ex}from"node:path";function cW(e){return`# >>> afk shell-init >>>
7
+ Effective base URL: ${r}`)),r}return t}function QT(){if(gy!==void 0)return gy;if(!YT){let o=[aW(process.cwd(),".env"),kt(),KE()];for(let i of o)sW(i)&&lW({path:i,override:!1});YT=!0}let e={},t=k.AFK_MODEL??k.CLAUDE_MODEL;if(t){let o=t.toLowerCase();e.model=gl(o)?o:t}if(re(t)==="anthropic-direct"){let o=ou();o!==void 0&&(e.apiKey=o)}let r=k.AFK_LOCAL_BASE_URL;if(r&&r.length>0&&(e.baseUrl=r,e.apiKey=k.AFK_LOCAL_API_KEY||"local"),k.AFK_MAX_TOKENS){let o=Number(k.AFK_MAX_TOKENS);Number.isInteger(o)&&(e.maxTokens=o)}if(k.AFK_TEMPERATURE){let o=Number(k.AFK_TEMPERATURE);Number.isFinite(o)&&(e.temperature=o)}if(k.AFK_SYSTEM_PROMPT&&(e.systemPrompt=k.AFK_SYSTEM_PROMPT),k.AFK_AUTO_ROUTING){let o=k.AFK_AUTO_ROUTING.toLowerCase()==="true";e.autoRouting={interactive:o,chat:o,telegram:o,daemon:o}}return k.AFK_OPENAI_BASE_URL&&(e.openaiBaseUrl=ZT(k.AFK_OPENAI_BASE_URL)),gy=e,e}var YT,gy,XT,hy=R(()=>{"use strict";vn();Je();G();Nt();q();YT=!1;XT=new Set});import{basename as ex}from"node:path";function cW(e){return`# >>> afk shell-init >>>
8
8
  # Auto-cd into a preserved worktree after \`afk\` exits.
9
9
  # REQUIRES: bash or zsh. Uses \`local\` (also works in dash/ash but
10
10
  # breaks in ksh93). For fish, use \`afk shell-init fish | source\`.
@@ -70,7 +70,7 @@ end
70
70
  `,await wy.writeFile(t,i,"utf8")}function EW(e,t,n){if(!Wr(e))return new Error(`git worktree add failed: ${String(e)}`);let r=e.stderr??"",o=e.message??"",i=`${r}
71
71
  ${o}`;return i.includes("already checked out")||i.includes("is already used by worktree")?new Error(`Branch '${t}' is already checked out in another worktree. Pick a different name.`):i.includes("already exists")?new Error(`Worktree path '${n}' already exists. Remove it or pick a different branch name.`):new Error(o||r||"git worktree add failed")}async function su(e,t){let n=t?.execFile??rx,r=iu(t?.branchPrefix),o=await ox(n);return await ix(o),dx(o,e,{execFile:n,prefix:r,baseRef:t?.baseRef})}async function sx(e){let t=e?.execFile??rx,n=iu(e?.branchPrefix),r=await ox(t);await ix(r);let o=await ax(r,e?.baseRef,t),i;return{repoRoot:r,handle:()=>i,async create(s){return i===void 0&&(i=await dx(r,s,{execFile:t,prefix:n,preResolvedBase:o})),i}}}async function ax(e,t,n){let r=TW(t);if(r!==void 0)return ky(r,"worktree base ref"),await lx(e,r,n),{ref:r,sha:await cx(e,r,n)}}function ky(e,t){if(e.trim().length===0)throw new Error(`Invalid worktree base ref from ${t}: '' \u2014 base ref cannot be empty.`);if(e.startsWith("-"))throw new Error(`Invalid worktree base ref from ${t}: '${e}' \u2014 must not start with '-' (would be parsed by git as a flag).`);if(e.includes("\0"))throw new Error(`Invalid worktree base ref from ${t}: contains a NUL byte.`);if(/\s/.test(e))throw new Error(`Invalid worktree base ref from ${t}: '${e}' \u2014 must not contain whitespace.`)}function TW(e){let t=e??k.AFK_WORKTREE_BASE;if(!(t===void 0||t.length===0))return t}async function lx(e,t,n){let r=t.indexOf("/");if(r<=0)return;let o=t.slice(0,r),i;try{let{stdout:a}=await n("git",["-C",e,"remote"]);i=a.split(`
72
72
  `).map(l=>l.trim()).filter(l=>l.length>0)}catch{return}if(!i.includes(o))return;let s=t.slice(r+1).replace(/[~^@:].*$/,"");if(s.length!==0)try{await n("git",["-C",e,"fetch","--no-tags",o,s])}catch(a){let l=Wr(a)?a.message||a.stderr||"":String(a);console.warn(`Worktree base: could not fetch '${o}/${s}' (${l.trim()}). Using the local copy of '${t}', which may be stale.`)}}async function cx(e,t,n){try{let{stdout:r}=await n("git",["-C",e,"rev-parse","--verify",`${t}^{commit}`]),o=r.trim();if(o.length===0)throw new Error("empty rev-parse output");return o}catch(r){let o=Wr(r)?r.message||r.stderr||"":String(r);throw new Error(`Cannot resolve worktree base ref '${t}': ${o.trim()} \u2014 check the ref exists (for a remote branch, make sure the remote is reachable so it can be fetched).`)}}async function xW(e,t){try{let{stdout:n}=await t("git",["-C",e,"symbolic-ref","--short","--quiet","refs/remotes/origin/HEAD"]),r=n.trim();if(r.length>0)return r}catch{}for(let n of["origin/main","origin/master"])try{let{stdout:r}=await t("git",["-C",e,"rev-parse","--verify","--quiet",`${n}^{commit}`]);if(r.trim().length>0)return n}catch{}}async function RW(e,t,n){try{return await cx(e,t,n)}catch{return}}async function dx(e,t,n){let{execFile:r,prefix:o}=n,i=t===!0?vW(o):t;kW(i);let s=i.replaceAll("/","-"),a=Sy(e,".afk-worktrees",s),l,c,d=n.preResolvedBase??await ax(e,n.baseRef,r);if(d!==void 0)c=d.sha,l=d.ref;else{let p=await xW(e,r);if(p!==void 0){await lx(e,p,r);let g=await RW(e,p,r);g!==void 0&&(c=g,l=p)}}let u=["-C",e,"worktree","add","-b",i,a];c!==void 0&&u.push(c);try{await r("git",u)}catch(p){throw EW(p,i,a)}let m={path:a,branch:i,cleanup:async p=>{let g=m.path,h=m.branch;if(p?.force===!0){console.log(`Worktree removed (zero turns \u2014 no work done): ${g}`);try{await r("git",["-C",e,"worktree","remove","--force",g])}catch(b){let w=Wr(b)?b.message||b.stderr||"":String(b);console.warn(`Worktree cleanup: 'git worktree remove --force ${g}' failed (${w}). Manual removal may be needed.`);return}try{await r("git",["-C",e,"branch","-d",h])}catch(b){let w=Wr(b)?b.message||b.stderr||"":String(b);console.warn(`Could not delete branch '${h}': ${w}`)}return}let y;try{y=await r("git",["-C",g,"status","--porcelain"])}catch(b){let w=Wr(b)?b.message||b.stderr||"":String(b);console.warn(`Worktree cleanup: could not check status at ${g} (${w}). Skipping removal \u2014 manual cleanup may be needed.`);return}if(y.stdout.trim().length>0){if(console.log(`Worktree preserved at ${g} (branch: ${h}) \u2014 uncommitted changes.`),YE(g),!XE()){let w=yy(k.SHELL)==="fish"?"afk shell-init fish | source (add to ~/.config/fish/config.fish)":'eval "$(afk shell-init)" (add to ~/.zshrc or ~/.bashrc)';console.log(` \u2192 cd ${g}
73
- \u2192 Or install one-time: ${w}`)}return}try{await r("git",["-C",e,"worktree","remove","--force",g])}catch(b){let w=Wr(b)?b.message||b.stderr||"":String(b);console.warn(`Worktree cleanup: 'git worktree remove --force ${g}' failed (${w}). Manual removal may be needed.`);return}try{await r("git",["-C",e,"branch","-d",h])}catch(b){let w=Wr(b)?b.message||b.stderr||"":String(b);console.warn(`Could not delete branch '${h}': ${w}`)}}};try{let p=c??"",g=l??"";if(c===void 0){try{p=(await r("git",["-C",e,"rev-parse","HEAD"])).stdout.trim()}catch{}try{g=(await r("git",["-C",e,"symbolic-ref","--short","HEAD"])).stdout.trim()}catch{}}let h={owner:"interactive",pid:process.pid,createdAt:new Date().toISOString(),baseSha:p,baseBranch:g};await wy.writeFile(Sy(a,".afk-worktree-meta.json"),JSON.stringify(h,null,2),"utf-8")}catch{}return m}var rx,bW,wW,nx,yl=R(()=>{"use strict";q();Ld();by();rx=mW(pW),bW="afk/",wW=/^[A-Za-z0-9_\-./]*$/,nx=64});import{existsSync as dr,readdirSync as px,readFileSync as Ty,realpathSync as CW,statSync as AW}from"fs";import{homedir as mx}from"os";import{join as Bt}from"path";function bl(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of rs){let r=e[n];if(r!==void 0){if(r===!0){t[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;t[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(t).length>0?t:void 0}function IW(){return[en(),Od()]}function Ut(e=IW()){for(let t of e)if(dr(t))try{let n=JSON.parse(Ty(t,"utf-8")),r=bl(n.importFrom);if(r!==void 0)return r}catch{}}function kn(e,t=mx()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!e)return n;for(let r of rs){let o=e[r];if(!o)continue;let i=au[r];if(o.plugins)for(let s of i.pluginRoots(t))dr(s)&&n.pluginRoots.push(s);if(o.skills){let s=`imported:${r}`;for(let a of i.skillRoots(t))dr(a)&&n.skillRoots.push({dir:a,origin:s})}if(o.mcp){let s=fx(i.mcpConfigCandidates(t));s&&n.mcpConfigs.push({source:s,format:i.mcpFormat})}}return n}function lu(e=mx()){return rs.map(t=>PW(t,e))}function PW(e,t){let n=au[e],r=[];for(let l of n.pluginRoots(t))r.push(...OW(l));let o=[];for(let l of n.skillRoots(t))o.push(...$W(l));let i=fx(n.mcpConfigCandidates(t)),s=i?DW(i,n.mcpFormat):[],a=r.length>0||o.length>0||i!==null||n.pluginRoots(t).some(dr)||n.skillRoots(t).some(dr);return{binary:e,label:n.label,present:a,plugins:r,skills:o,mcpServers:s,mcpConfigPath:i,mcpFormat:n.mcpFormat}}function fx(e){for(let t of e)if(dr(t))return t;return null}function MW(e){try{let t=JSON.parse(Ty(Bt(e,".claude-plugin","plugin.json"),"utf-8"));return typeof t.name=="string"&&t.name.length>0?t.name:null}catch{return null}}function OW(e){if(!dr(e))return[];let t=[];return gx(e,0,t,new Set),t}function gx(e,t,n,r){let o;try{o=CW(e)}catch{o=e}if(t>_W||r.has(o))return;if(r.add(o),dr(Bt(e,".claude-plugin","plugin.json"))){let s=MW(e)??e.split("/").filter(Boolean).pop()??e;n.push({name:s,path:e});return}let i;try{i=px(e)}catch{return}for(let s of i){if(s.startsWith("."))continue;let a=Bt(e,s);try{AW(a).isDirectory()&&gx(a,t+1,n,r)}catch{}}}function $W(e){let t;try{t=px(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t)!r.isDirectory()||r.name.startsWith("_")||r.name.startsWith(".")||dr(Bt(e,r.name,"SKILL.md"))&&n.push({name:r.name,path:Bt(e,r.name)});return n}function DW(e,t){let n;try{n=Ty(e,"utf-8")}catch{return[]}return t==="json"?FW(n):LW(n)}function FW(e){let t;try{t=JSON.parse(e)}catch{return[]}if(t===null||typeof t!="object")return[];let n=t.mcpServers;if(n===null||typeof n!="object"||Array.isArray(n))return[];let r=[];for(let[o,i]of Object.entries(n))r.push({name:o,command:BW(i)});return r}function LW(e){let t=[],n=e.split(/\r?\n/),r=!1,o=null,i=null,s=null,a=[],l=()=>{if(r&&o){let d;s!==null?d=s:i!==null?d=a.length>0?[i,...a].join(" "):i:d="(no command)",t.push({name:o,command:d})}o=null,i=null,s=null,a=[]},c=/^\[mcp_servers\.([^\]]+)\]\s*$/;for(let d of n){let u=d.trim();if(u===""||u.startsWith("#"))continue;let m=c.exec(u);if(m){l(),r=!0,o=m[1]??null;continue}if(u.startsWith("[")){l(),r=!1;continue}if(!r)continue;let p=u.indexOf("=");if(p===-1)continue;let g=u.slice(0,p).trim(),h=u.slice(p+1).trim();g==="command"?i=Ey(ux(h)):g==="url"?s=Ey(ux(h)):g==="args"&&(a=NW(h))}return l(),t}function ux(e){if(e.startsWith('"')||e.startsWith("'"))return e;let t=e.indexOf(" #");return t===-1?e:e.slice(0,t).trimEnd()}function NW(e){let t=e.trim();if(!t.startsWith("["))return[];let n=t.slice(1,t.lastIndexOf("]"));if(!n.trim())return[];try{return n.split(",").map(r=>Ey(r.trim())).filter(r=>r.length>0)}catch{return[]}}function Ey(e){let t=e.match(/^"([^"]*)"$/)??e.match(/^'([^']*)'$/);return t&&t[1]!==void 0?t[1]:e.startsWith('"')||e.startsWith("'")?e.slice(1):e.endsWith('"')||e.endsWith("'")?e.slice(0,-1):e}function BW(e){if(e===null||typeof e!="object")return"(invalid)";let t=e;if(typeof t.url=="string")return t.url;if(typeof t.command=="string"){let n=Array.isArray(t.args)?t.args.filter(r=>typeof r=="string"):[];return[t.command,...n].join(" ")}return"(no command)"}var rs,au,Bme,_W,ur=R(()=>{"use strict";G();rs=["claude-code","codex"],au={"claude-code":{label:"Claude Code",pluginRoots:e=>[Bt(e,".claude","plugins")],skillRoots:e=>[Bt(e,".claude","skills")],mcpConfigCandidates:e=>[Bt(e,".claude","mcp.json"),Bt(e,".claude",".mcp.json"),Bt(e,".claude","claude-code","mcp.json")],mcpFormat:"json"},codex:{label:"Codex",pluginRoots:e=>[Bt(e,".codex","plugins")],skillRoots:e=>[Bt(e,".codex","skills")],mcpConfigCandidates:e=>[Bt(e,".codex","config.toml")],mcpFormat:"toml"}},Bme={"claude-code":au["claude-code"].label,codex:au.codex.label},_W=5});import{readFileSync as UW,existsSync as jW}from"fs";import{join as hx}from"path";function cu(){if(os!==void 0)return os;let e=[hx(process.cwd(),"afk.config.json"),en(),Od()];for(let t of e)if(jW(t))try{let n=UW(t,"utf-8"),r=JSON.parse(n),o={},i=_T(r.models);if(typeof r.model=="string"&&r.model.length>0){let s=r.model.toLowerCase();o.model=gl(s)?s:r.model}if(typeof r.maxTokens=="number"&&(o.maxTokens=r.maxTokens),typeof r.temperature=="number"&&(o.temperature=r.temperature),r.systemPrompt&&(o.systemPrompt=r.systemPrompt),typeof r.permissionMode=="string"){let s=r.permissionMode;(s==="default"||s==="plan"||s==="autonomous"||s==="bypassPermissions")&&(o.permissionMode=s)}if(r.autoRouting&&typeof r.autoRouting=="object"){let s={};typeof r.autoRouting.interactive=="boolean"&&(s.interactive=r.autoRouting.interactive),typeof r.autoRouting.chat=="boolean"&&(s.chat=r.autoRouting.chat),typeof r.autoRouting.telegram=="boolean"&&(s.telegram=r.autoRouting.telegram),typeof r.autoRouting.daemon=="boolean"&&(s.daemon=r.autoRouting.daemon),o.autoRouting=s}if(r.daemon&&typeof r.daemon=="object"){let s={};typeof r.daemon.task=="string"&&(s.task=r.daemon.task),typeof r.daemon.taskId=="string"&&(s.taskId=r.daemon.taskId);let a=r.daemon.worktreePrune;a&&typeof a=="object"&&(s.worktreePrune={enabled:typeof a.enabled=="boolean"?a.enabled:!0,cron:typeof a.cron=="string"?a.cron:"0 4 * * *",maxAgeDaysClean:typeof a.maxAgeDaysClean=="number"?a.maxAgeDaysClean:14,maxAgeDaysDirty:typeof a.maxAgeDaysDirty=="number"?a.maxAgeDaysDirty:30,scope:typeof a.scope=="string"?a.scope:"all"}),o.daemon=s}if(r.telegram&&typeof r.telegram=="object"){let s={},a=r.telegram.notify;if(a&&typeof a=="object"){let l={};if((a.mode==="primary"||a.mode==="broadcast"||a.mode==="custom")&&(l.mode=a.mode),typeof a.primaryChatId=="number"&&Number.isFinite(a.primaryChatId)&&(l.primaryChatId=a.primaryChatId),Array.isArray(a.targets)){let c=a.targets.filter(d=>typeof d=="number"&&Number.isFinite(d));c.length>0&&(l.targets=c)}s.notify=l}typeof r.telegram.verifyDone=="boolean"&&(s.verifyDone=r.telegram.verifyDone),o.telegram=s}if(r.updatePolicy&&["notify","auto","off"].includes(r.updatePolicy)&&(o.updatePolicy=r.updatePolicy),typeof r.autoResumeOnUsageLimit=="boolean"&&(o.autoResumeOnUsageLimit=r.autoResumeOnUsageLimit),typeof r.bgSummaries=="boolean"&&(o.bgSummaries=r.bgSummaries),typeof r.maxSummaryCallsPerSession=="number"&&(o.maxSummaryCallsPerSession=Math.min(500,Math.max(1,r.maxSummaryCallsPerSession))),r.hooks!==null&&typeof r.hooks=="object"&&!Array.isArray(r.hooks)&&(o.hooks=r.hooks),typeof r.enableShellHooks=="boolean"&&(o.enableShellHooks=r.enableShellHooks),t!==hx(process.cwd(),"afk.config.json")){let s=bl(r.importFrom);s!==void 0&&(o.importFrom=s)}if(r.interactive&&typeof r.interactive=="object"){let s={};typeof r.interactive.worktreeAutoname=="boolean"&&(s.worktreeAutoname=r.interactive.worktreeAutoname),typeof r.interactive.worktreeBranchPrefix=="string"&&(s.worktreeBranchPrefix=vy(r.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(ky(r.interactive.worktreeBase,`${t}#/interactive/worktreeBase`),s.worktreeBase=r.interactive.worktreeBase),typeof r.interactive.suggestGhost=="boolean"&&(s.suggestGhost=r.interactive.suggestGhost),(r.interactive.thinkingUi==="summary"||r.interactive.thinkingUi==="live"||r.interactive.thinkingUi==="digest"||r.interactive.thinkingUi==="off")&&(s.thinkingUi=r.interactive.thinkingUi),Object.keys(s).length>0&&(o.interactive=s)}return os={config:o,sourcePath:t,modelsPartial:i},os}catch(n){console.error(`Warning: Failed to parse ${t}:`,n)}return os={config:{},sourcePath:void 0,modelsPartial:{}},os}var os,yx=R(()=>{"use strict";vn();Lt();G();yl();ur()});import{readFileSync as HW,existsSync as WW}from"fs";import{join as bx}from"path";function wx(){if(is!==void 0)return is.value;let e=[bx(process.cwd(),"AFK.md"),bx(_e(),"AFK.md")];for(let t of e)if(WW(t))try{let n=HW(t,"utf-8").trim();if(n.length>0)return is={value:{content:n,path:t}},is.value}catch{}return is={value:null},is.value}var is,Sx=R(()=>{"use strict";G()});function du(){return cu().config.telegram??{}}function ss(){return cu().config.permissionMode??ru}function Pt(e){let t=QT(),{config:n,sourcePath:r,modelsPartial:o}=cu(),i={...ns,...t,...n,...e},s;if(t.systemPrompt!==void 0)s="env:AFK_SYSTEM_PROMPT";else if(n.systemPrompt!==void 0&&r!==void 0)s=`file:${r}`;else if(i.systemPrompt===void 0){let c=wx();c!==null&&(i.systemPrompt=c.content,s=`afk-md:${c.path}`)}let a={model:i.model??ns.model,maxTokens:i.maxTokens??ns.maxTokens,temperature:i.temperature??ns.temperature,updatePolicy:i.updatePolicy??ns.updatePolicy,...i.apiKey!==void 0?{apiKey:i.apiKey}:{},...i.baseUrl!==void 0?{baseUrl:i.baseUrl}:{},...i.openaiBaseUrl!==void 0?{openaiBaseUrl:i.openaiBaseUrl}:{},...i.systemPrompt!==void 0?{systemPrompt:i.systemPrompt}:{},...s!==void 0?{systemPromptSource:s}:{},permissionMode:i.permissionMode??ru,...i.autoRouting!==void 0?{autoRouting:i.autoRouting}:{},...i.daemon!==void 0?{daemon:i.daemon}:{},...i.telegram!==void 0?{telegram:i.telegram}:{},...i.bgSummaries!==void 0?{bgSummaries:i.bgSummaries}:{},...i.maxSummaryCallsPerSession!==void 0?{maxSummaryCallsPerSession:i.maxSummaryCallsPerSession}:{},...i.interactive!==void 0?{interactive:i.interactive}:{},...i.hooks!==void 0?{hooks:i.hooks}:{},...i.enableShellHooks!==void 0?{enableShellHooks:i.enableShellHooks}:{},...i.importFrom!==void 0?{importFrom:i.importFrom}:{}},l=e?.models??ey(o);if(Yd(l),a.models=l,typeof a.model=="string"&&a.model.toLowerCase().startsWith("local-")&&(a.baseUrl===void 0||a.baseUrl.length===0))throw new Error(`Model '${a.model}' requires AFK_LOCAL_BASE_URL to be set (e.g. AFK_LOCAL_BASE_URL=http://127.0.0.1:8080). Point it at your local Anthropic-Messages-compatible server.`);return a}var jt=R(()=>{"use strict";vn();Lt();Je();py();hy();yx();Sx();py();hy()});function KW(e,t){return t!==void 0&&Number.isFinite(t)&&t!==0?t:e.find(r=>r>0)??e[0]}function GW(e,t={}){let n=[...e],r=t.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let i=(t.targets??[]).filter(s=>typeof s=="number"&&Number.isFinite(s)&&s!==0);if(i.length>0)return[...new Set(i)]}let o=KW(n,t.primaryChatId);return o!==void 0?[o]:[]}function qW(e){if(!e)return;let t=e.trim();if(!/^-?\d+$/.test(t))return;let n=Number(t);return Number.isFinite(n)&&n!==0?n:void 0}function zW(e){if(!e)return;let t=e.trim().toLowerCase();return t==="primary"||t==="broadcast"||t==="custom"?t:void 0}function JW(){let e=du().notify??{},t=e.mode??zW(k.AFK_TELEGRAM_NOTIFY_MODE),n=e.primaryChatId??qW(k.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...t!==void 0?{mode:t}:{},...n!==void 0?{primaryChatId:n}:{},...e.targets!==void 0?{targets:e.targets}:{}}}function as(){let e=JT(k.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return GW(e,JW())}var uu=R(()=>{"use strict";VT();jt();q()});function xy(e,t=4096){if(e.length<=t)return[e];let n=[],r=e;for(;r.length>0;){if(r.length<=t){n.push(r);break}let o=t,i=r.lastIndexOf(`
73
+ \u2192 Or install one-time: ${w}`)}return}try{await r("git",["-C",e,"worktree","remove","--force",g])}catch(b){let w=Wr(b)?b.message||b.stderr||"":String(b);console.warn(`Worktree cleanup: 'git worktree remove --force ${g}' failed (${w}). Manual removal may be needed.`);return}try{await r("git",["-C",e,"branch","-d",h])}catch(b){let w=Wr(b)?b.message||b.stderr||"":String(b);console.warn(`Could not delete branch '${h}': ${w}`)}}};try{let p=c??"",g=l??"";if(c===void 0){try{p=(await r("git",["-C",e,"rev-parse","HEAD"])).stdout.trim()}catch{}try{g=(await r("git",["-C",e,"symbolic-ref","--short","HEAD"])).stdout.trim()}catch{}}let h={owner:"interactive",pid:process.pid,createdAt:new Date().toISOString(),baseSha:p,baseBranch:g};await wy.writeFile(Sy(a,".afk-worktree-meta.json"),JSON.stringify(h,null,2),"utf-8")}catch{}return m}var rx,bW,wW,nx,yl=R(()=>{"use strict";q();Ld();by();rx=mW(pW),bW="afk/",wW=/^[A-Za-z0-9_\-./]*$/,nx=64});import{existsSync as dr,readdirSync as px,readFileSync as Ty,realpathSync as CW,statSync as AW}from"fs";import{homedir as mx}from"os";import{join as Bt}from"path";function bl(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t={};for(let n of rs){let r=e[n];if(r!==void 0){if(r===!0){t[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;t[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(t).length>0?t:void 0}function IW(){return[en(),Od()]}function Ut(e=IW()){for(let t of e)if(dr(t))try{let n=JSON.parse(Ty(t,"utf-8")),r=bl(n.importFrom);if(r!==void 0)return r}catch{}}function kn(e,t=mx()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!e)return n;for(let r of rs){let o=e[r];if(!o)continue;let i=au[r];if(o.plugins)for(let s of i.pluginRoots(t))dr(s)&&n.pluginRoots.push(s);if(o.skills){let s=`imported:${r}`;for(let a of i.skillRoots(t))dr(a)&&n.skillRoots.push({dir:a,origin:s})}if(o.mcp){let s=fx(i.mcpConfigCandidates(t));s&&n.mcpConfigs.push({source:s,format:i.mcpFormat})}}return n}function lu(e=mx()){return rs.map(t=>PW(t,e))}function PW(e,t){let n=au[e],r=[];for(let l of n.pluginRoots(t))r.push(...OW(l));let o=[];for(let l of n.skillRoots(t))o.push(...$W(l));let i=fx(n.mcpConfigCandidates(t)),s=i?DW(i,n.mcpFormat):[],a=r.length>0||o.length>0||i!==null||n.pluginRoots(t).some(dr)||n.skillRoots(t).some(dr);return{binary:e,label:n.label,present:a,plugins:r,skills:o,mcpServers:s,mcpConfigPath:i,mcpFormat:n.mcpFormat}}function fx(e){for(let t of e)if(dr(t))return t;return null}function MW(e){try{let t=JSON.parse(Ty(Bt(e,".claude-plugin","plugin.json"),"utf-8"));return typeof t.name=="string"&&t.name.length>0?t.name:null}catch{return null}}function OW(e){if(!dr(e))return[];let t=[];return gx(e,0,t,new Set),t}function gx(e,t,n,r){let o;try{o=CW(e)}catch{o=e}if(t>_W||r.has(o))return;if(r.add(o),dr(Bt(e,".claude-plugin","plugin.json"))){let s=MW(e)??e.split("/").filter(Boolean).pop()??e;n.push({name:s,path:e});return}let i;try{i=px(e)}catch{return}for(let s of i){if(s.startsWith("."))continue;let a=Bt(e,s);try{AW(a).isDirectory()&&gx(a,t+1,n,r)}catch{}}}function $W(e){let t;try{t=px(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t)!r.isDirectory()||r.name.startsWith("_")||r.name.startsWith(".")||dr(Bt(e,r.name,"SKILL.md"))&&n.push({name:r.name,path:Bt(e,r.name)});return n}function DW(e,t){let n;try{n=Ty(e,"utf-8")}catch{return[]}return t==="json"?FW(n):LW(n)}function FW(e){let t;try{t=JSON.parse(e)}catch{return[]}if(t===null||typeof t!="object")return[];let n=t.mcpServers;if(n===null||typeof n!="object"||Array.isArray(n))return[];let r=[];for(let[o,i]of Object.entries(n))r.push({name:o,command:BW(i)});return r}function LW(e){let t=[],n=e.split(/\r?\n/),r=!1,o=null,i=null,s=null,a=[],l=()=>{if(r&&o){let d;s!==null?d=s:i!==null?d=a.length>0?[i,...a].join(" "):i:d="(no command)",t.push({name:o,command:d})}o=null,i=null,s=null,a=[]},c=/^\[mcp_servers\.([^\]]+)\]\s*$/;for(let d of n){let u=d.trim();if(u===""||u.startsWith("#"))continue;let m=c.exec(u);if(m){l(),r=!0,o=m[1]??null;continue}if(u.startsWith("[")){l(),r=!1;continue}if(!r)continue;let p=u.indexOf("=");if(p===-1)continue;let g=u.slice(0,p).trim(),h=u.slice(p+1).trim();g==="command"?i=Ey(ux(h)):g==="url"?s=Ey(ux(h)):g==="args"&&(a=NW(h))}return l(),t}function ux(e){if(e.startsWith('"')||e.startsWith("'"))return e;let t=e.indexOf(" #");return t===-1?e:e.slice(0,t).trimEnd()}function NW(e){let t=e.trim();if(!t.startsWith("["))return[];let n=t.slice(1,t.lastIndexOf("]"));if(!n.trim())return[];try{return n.split(",").map(r=>Ey(r.trim())).filter(r=>r.length>0)}catch{return[]}}function Ey(e){let t=e.match(/^"([^"]*)"$/)??e.match(/^'([^']*)'$/);return t&&t[1]!==void 0?t[1]:e.startsWith('"')||e.startsWith("'")?e.slice(1):e.endsWith('"')||e.endsWith("'")?e.slice(0,-1):e}function BW(e){if(e===null||typeof e!="object")return"(invalid)";let t=e;if(typeof t.url=="string")return t.url;if(typeof t.command=="string"){let n=Array.isArray(t.args)?t.args.filter(r=>typeof r=="string"):[];return[t.command,...n].join(" ")}return"(no command)"}var rs,au,Bme,_W,ur=R(()=>{"use strict";G();rs=["claude-code","codex"],au={"claude-code":{label:"Claude Code",pluginRoots:e=>[Bt(e,".claude","plugins")],skillRoots:e=>[Bt(e,".claude","skills")],mcpConfigCandidates:e=>[Bt(e,".claude","mcp.json"),Bt(e,".claude",".mcp.json"),Bt(e,".claude","claude-code","mcp.json")],mcpFormat:"json"},codex:{label:"Codex",pluginRoots:e=>[Bt(e,".codex","plugins")],skillRoots:e=>[Bt(e,".codex","skills")],mcpConfigCandidates:e=>[Bt(e,".codex","config.toml")],mcpFormat:"toml"}},Bme={"claude-code":au["claude-code"].label,codex:au.codex.label},_W=5});import{readFileSync as UW,existsSync as jW}from"fs";import{join as hx}from"path";function cu(){if(os!==void 0)return os;let e=[hx(process.cwd(),"afk.config.json"),en(),Od()];for(let t of e)if(jW(t))try{let n=UW(t,"utf-8"),r=JSON.parse(n),o={},i=_T(r.models);if(typeof r.model=="string"&&r.model.length>0){let s=r.model.toLowerCase();o.model=gl(s)?s:r.model}if(typeof r.maxTokens=="number"&&(o.maxTokens=r.maxTokens),typeof r.temperature=="number"&&(o.temperature=r.temperature),typeof r.systemPrompt=="string"&&r.systemPrompt.length>0&&(o.systemPrompt=r.systemPrompt),typeof r.permissionMode=="string"){let s=r.permissionMode;(s==="default"||s==="plan"||s==="autonomous"||s==="bypassPermissions")&&(o.permissionMode=s)}if(r.autoRouting&&typeof r.autoRouting=="object"){let s={};typeof r.autoRouting.interactive=="boolean"&&(s.interactive=r.autoRouting.interactive),typeof r.autoRouting.chat=="boolean"&&(s.chat=r.autoRouting.chat),typeof r.autoRouting.telegram=="boolean"&&(s.telegram=r.autoRouting.telegram),typeof r.autoRouting.daemon=="boolean"&&(s.daemon=r.autoRouting.daemon),o.autoRouting=s}if(r.daemon&&typeof r.daemon=="object"){let s={};typeof r.daemon.task=="string"&&(s.task=r.daemon.task),typeof r.daemon.taskId=="string"&&(s.taskId=r.daemon.taskId);let a=r.daemon.worktreePrune;a&&typeof a=="object"&&(s.worktreePrune={enabled:typeof a.enabled=="boolean"?a.enabled:!0,cron:typeof a.cron=="string"?a.cron:"0 4 * * *",maxAgeDaysClean:typeof a.maxAgeDaysClean=="number"?a.maxAgeDaysClean:14,maxAgeDaysDirty:typeof a.maxAgeDaysDirty=="number"?a.maxAgeDaysDirty:30,scope:typeof a.scope=="string"?a.scope:"all"}),o.daemon=s}if(r.telegram&&typeof r.telegram=="object"){let s={},a=r.telegram.notify;if(a&&typeof a=="object"){let l={};if((a.mode==="primary"||a.mode==="broadcast"||a.mode==="custom")&&(l.mode=a.mode),typeof a.primaryChatId=="number"&&Number.isFinite(a.primaryChatId)&&(l.primaryChatId=a.primaryChatId),Array.isArray(a.targets)){let c=a.targets.filter(d=>typeof d=="number"&&Number.isFinite(d));c.length>0&&(l.targets=c)}s.notify=l}typeof r.telegram.verifyDone=="boolean"&&(s.verifyDone=r.telegram.verifyDone),o.telegram=s}if(r.updatePolicy&&["notify","auto","off"].includes(r.updatePolicy)&&(o.updatePolicy=r.updatePolicy),typeof r.autoResumeOnUsageLimit=="boolean"&&(o.autoResumeOnUsageLimit=r.autoResumeOnUsageLimit),typeof r.bgSummaries=="boolean"&&(o.bgSummaries=r.bgSummaries),typeof r.maxSummaryCallsPerSession=="number"&&(o.maxSummaryCallsPerSession=Math.min(500,Math.max(1,r.maxSummaryCallsPerSession))),r.hooks!==null&&typeof r.hooks=="object"&&!Array.isArray(r.hooks)&&(o.hooks=r.hooks),typeof r.enableShellHooks=="boolean"&&(o.enableShellHooks=r.enableShellHooks),t!==hx(process.cwd(),"afk.config.json")){let s=bl(r.importFrom);s!==void 0&&(o.importFrom=s)}if(r.interactive&&typeof r.interactive=="object"){let s={};typeof r.interactive.worktreeAutoname=="boolean"&&(s.worktreeAutoname=r.interactive.worktreeAutoname),typeof r.interactive.worktreeBranchPrefix=="string"&&(s.worktreeBranchPrefix=vy(r.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(ky(r.interactive.worktreeBase,`${t}#/interactive/worktreeBase`),s.worktreeBase=r.interactive.worktreeBase),typeof r.interactive.suggestGhost=="boolean"&&(s.suggestGhost=r.interactive.suggestGhost),(r.interactive.thinkingUi==="summary"||r.interactive.thinkingUi==="live"||r.interactive.thinkingUi==="digest"||r.interactive.thinkingUi==="off")&&(s.thinkingUi=r.interactive.thinkingUi),Object.keys(s).length>0&&(o.interactive=s)}return os={config:o,sourcePath:t,modelsPartial:i},os}catch(n){console.error(`Warning: Failed to parse ${t}:`,n)}return os={config:{},sourcePath:void 0,modelsPartial:{}},os}var os,yx=R(()=>{"use strict";vn();Lt();G();yl();ur()});import{readFileSync as HW,existsSync as WW}from"fs";import{join as bx}from"path";function wx(){if(is!==void 0)return is.value;let e=[bx(process.cwd(),"AFK.md"),bx(_e(),"AFK.md")];for(let t of e)if(WW(t))try{let n=HW(t,"utf-8").trim();if(n.length>0)return is={value:{content:n,path:t}},is.value}catch{}return is={value:null},is.value}var is,Sx=R(()=>{"use strict";G()});function du(){return cu().config.telegram??{}}function ss(){return cu().config.permissionMode??ru}function Pt(e){let t=QT(),{config:n,sourcePath:r,modelsPartial:o}=cu(),i={...ns,...t,...n,...e},s;if(t.systemPrompt!==void 0)s="env:AFK_SYSTEM_PROMPT";else if(n.systemPrompt!==void 0&&r!==void 0)s=`file:${r}`;else if(i.systemPrompt===void 0){let c=wx();c!==null&&(i.systemPrompt=c.content,s=`afk-md:${c.path}`)}let a={model:i.model??ns.model,maxTokens:i.maxTokens??ns.maxTokens,temperature:i.temperature??ns.temperature,updatePolicy:i.updatePolicy??ns.updatePolicy,...i.apiKey!==void 0?{apiKey:i.apiKey}:{},...i.baseUrl!==void 0?{baseUrl:i.baseUrl}:{},...i.openaiBaseUrl!==void 0?{openaiBaseUrl:i.openaiBaseUrl}:{},...i.systemPrompt!==void 0?{systemPrompt:i.systemPrompt}:{},...s!==void 0?{systemPromptSource:s}:{},permissionMode:i.permissionMode??ru,...i.autoRouting!==void 0?{autoRouting:i.autoRouting}:{},...i.daemon!==void 0?{daemon:i.daemon}:{},...i.telegram!==void 0?{telegram:i.telegram}:{},...i.bgSummaries!==void 0?{bgSummaries:i.bgSummaries}:{},...i.maxSummaryCallsPerSession!==void 0?{maxSummaryCallsPerSession:i.maxSummaryCallsPerSession}:{},...i.interactive!==void 0?{interactive:i.interactive}:{},...i.hooks!==void 0?{hooks:i.hooks}:{},...i.enableShellHooks!==void 0?{enableShellHooks:i.enableShellHooks}:{},...i.importFrom!==void 0?{importFrom:i.importFrom}:{}},l=e?.models??ey(o);if(Yd(l),a.models=l,typeof a.model=="string"&&a.model.toLowerCase().startsWith("local-")&&(a.baseUrl===void 0||a.baseUrl.length===0))throw new Error(`Model '${a.model}' requires AFK_LOCAL_BASE_URL to be set (e.g. AFK_LOCAL_BASE_URL=http://127.0.0.1:8080). Point it at your local Anthropic-Messages-compatible server.`);return a}var jt=R(()=>{"use strict";vn();Lt();Je();py();hy();yx();Sx();py();hy()});function KW(e,t){return t!==void 0&&Number.isFinite(t)&&t!==0?t:e.find(r=>r>0)??e[0]}function GW(e,t={}){let n=[...e],r=t.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let i=(t.targets??[]).filter(s=>typeof s=="number"&&Number.isFinite(s)&&s!==0);if(i.length>0)return[...new Set(i)]}let o=KW(n,t.primaryChatId);return o!==void 0?[o]:[]}function qW(e){if(!e)return;let t=e.trim();if(!/^-?\d+$/.test(t))return;let n=Number(t);return Number.isFinite(n)&&n!==0?n:void 0}function zW(e){if(!e)return;let t=e.trim().toLowerCase();return t==="primary"||t==="broadcast"||t==="custom"?t:void 0}function JW(){let e=du().notify??{},t=e.mode??zW(k.AFK_TELEGRAM_NOTIFY_MODE),n=e.primaryChatId??qW(k.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...t!==void 0?{mode:t}:{},...n!==void 0?{primaryChatId:n}:{},...e.targets!==void 0?{targets:e.targets}:{}}}function as(){let e=JT(k.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return GW(e,JW())}var uu=R(()=>{"use strict";VT();jt();q()});function xy(e,t=4096){if(e.length<=t)return[e];let n=[],r=e;for(;r.length>0;){if(r.length<=t){n.push(r);break}let o=t,i=r.lastIndexOf(`
74
74
  `,t);if(i>t-500&&i>0)o=i+1;else{let s=r.slice(0,t).match(/[.!?]\s+(?=[A-Z])/g);if(s&&s.length>0){let a=s[s.length-1];if(a){let l=r.lastIndexOf(a,t);l>t-200&&l>0&&(o=l+2)}}else{let a=r.lastIndexOf(" ",t);a>t-100&&a>0&&(o=a+1)}}n.push(r.slice(0,o).trim()),r=r.slice(o).trim()}return n}function vx(e){e=e.replace(/[\x02\x03]/g,"");let t=e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),n=[];t=t.replace(/^ {0,3}```([\w]*)\n([\s\S]*?)```/gm,(o,i,s)=>{let a=n.length;if(s.trim()===""){let l=i?`(empty ${i} block)`:"(empty code block)";n.push(`<i>${l}</i>`)}else n.push(`<pre>${s}</pre>`);return`FENCED${a}`});let r=[];return t=t.replace(/`([^`]+)`/g,(o,i)=>{let s=r.length;return r.push(`<code>${i}</code>`),`CODE${s}`}),t=t.replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>"),t=t.replace(/__([^_]+)__/g,"<b>$1</b>"),t=t.replace(/\*([^*]+)\*/g,"<i>$1</i>"),t=t.replace(/(^|[^\w])_([^_\n]+?)_(?!\w)/gm,"$1<i>$2</i>"),t=t.replace(/~~([^~]+)~~/g,"<s>$1</s>"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(o,i,s)=>'<a href="'+s.replace(/"/g,"&quot;")+'">'+i+"</a>"),t=t.replace(/^#{1,6}\s+/gm,""),VW(t)||(t=t.replace(/<\/?[bis]>/g,"")),t=t.replace(/\x02CODE(\d+)\x03/g,(o,i)=>r[Number(i)]??o),t=t.replace(/\x02FENCED(\d+)\x03/g,(o,i)=>n[Number(i)]??o),t}function VW(e){let t=[],n=/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g,r;for(;(r=n.exec(e))!==null;){let o=(r[2]??"").toLowerCase();if(r[1]==="/"){if(t.pop()!==o)return!1}else t.push(o)}return t.length===0}var kx=R(()=>{"use strict"});var Ry={};kd(Ry,{push:()=>ls,pushIfConfigured:()=>rn,pushMarkdown:()=>Ex});async function ls(e){if(!e.token)throw new Error("push: token is required");if(e.chatId===""||e.chatId==null||e.chatId===0)throw new Error("push: chatId is required");let t=e.fetchImpl??fetch,r=`${e.apiBase??YW}/bot${e.token}/sendMessage`,o={chat_id:e.chatId,text:e.text.slice(0,4096)};e.parseMode&&(o.parse_mode=e.parseMode),e.replyMarkup&&(o.reply_markup=e.replyMarkup);let i=new AbortController,s=setTimeout(()=>i.abort(),1e4);try{let a=await t(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:i.signal});if(a.ok)return{ok:!0,status:a.status};let l;try{l=(await a.json()).description}catch{l=`HTTP ${a.status}`}return{ok:!1,status:a.status,...l!==void 0?{errorMessage:l}:{}}}catch(a){return{ok:!1,status:0,errorMessage:a instanceof Error?a.message:String(a)}}finally{clearTimeout(s)}}async function Ex(e){let t=vx(e.text),n=xy(t),r={ok:!0,status:200};for(let o of n)if(r=await ls({...e,text:o,parseMode:"HTML"}),!r.ok)return r.status===400&&/can't parse entities/i.test(r.errorMessage??"")?ls({...e}):r;return r}async function rn(e,t={}){let n=k.TELEGRAM_BOT_TOKEN;if(!n)return null;let r=as();if(r.length===0)return null;let o=xy(e),i=[];for(let s of r)for(let a=0;a<o.length;a++){let l={token:n,chatId:s,text:o[a]??"",...t.replyMarkup!==void 0&&a===0?{replyMarkup:t.replyMarkup}:{},...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}};i.push(t.markdown?await Ex(l):await ls({...l,...t.parseMode!==void 0?{parseMode:t.parseMode}:{}}))}return i}var YW,pr=R(()=>{"use strict";uu();kx();q();YW="https://api.telegram.org"});function XW(e){return e.length<=Tx?e:`${e.slice(0,Tx)}\u2026(truncated)`}function ZW(e){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${e.title??e.serverName}`,XW(e.message)];e.url!==void 0&&e.url!==""&&n.push(e.url),rn(n.join(`
75
75
  `)).catch(()=>{})}catch{}}var cs,Tx,Cy,et,mr=R(()=>{"use strict";pr();cs={action:"decline"},Tx=300;Cy=class{handler=null;queue=Promise.resolve();queueDepth=0;install(t){this.handler=t}uninstall(){this.handler=null}hasHandler(){return this.handler!==null}pendingCount(){return this.queueDepth}route(t,n){if(n.signal.aborted)return Promise.resolve(cs);this.queueDepth+=1;let r,o=new Promise(s=>{r=s}),i=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(cs);return}if(!i){ZW(t),r(cs);return}let s,a=new Promise(l=>{s=()=>l(cs),n.signal.addEventListener("abort",s,{once:!0})});try{try{n.onActive?.()}catch{}let l=await Promise.race([i(t,n).catch(()=>cs),a]);r(l)}finally{n.signal.removeEventListener("abort",s)}}finally{this.queueDepth-=1,r(cs)}}).catch(()=>{}),o}},et=new Cy});function pu(e){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${e}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${e}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
76
76
  `)}var Ay=R(()=>{"use strict"});function eK(e){switch(e){case"bypassPermissions":return"Approve \u2014 implement now (restore bypass mode: no prompts, read/write any path)";case"acceptEdits":return"Approve \u2014 implement now (restore accept-edits mode: edits auto-approved)";case"dontAsk":case"auto":return"Approve \u2014 implement now (restore your previous mode: no approval prompts)";default:return"Approve \u2014 implement now (restore default mode: writes ask for confirmation, contained to the workspace)"}}function fu(e){return async(t,n,r)=>{let o=e.getPrePlanMode()??"default",i=eK(o),a={serverName:"agent",origin:"agent",type:"choice",message:"Plan ready. How do you want to proceed? (Your plan is in the conversation above.)",choices:o==="bypassPermissions"?[i,_y]:[i,QW,_y]},l=await et.route(a,{signal:n});if(l.action!=="accept")return{content:"Plan exit not confirmed (the user did not approve). Stay in plan mode \u2014 keep refining the plan; do not implement. Call exit_plan_mode again when ready."};let c=typeof l.content?.value=="string"?l.content.value:"";if(c.startsWith("Keep")||c===_y)return{content:"User chose to keep planning. Stay in plan mode and refine the plan; do not implement. Call exit_plan_mode again when ready."};let d=c.includes("bypass")?"bypassPermissions":o,u=Rd(r?.resolveBase??r?.cwd??process.cwd());return e.requestImplementSeed(pu(u),d),{content:`Plan approved (mode=${d}). The implementation instruction will follow as a new message \u2014 end your turn now.`}}}var Ht,QW,_y,mu,jo=R(()=>{"use strict";mr();Ay();G();Ht="exit_plan_mode",QW="Approve \u2014 implement now (bypass mode: no prompts, read/write any path)",_y="Keep planning";mu={name:Ht,category:"other",concurrencySafe:!1,description:`Signal that your plan is ready and present it to the user for approval. The user is shown a picker: approve and implement (you pick neither mode \u2014 the user does), or keep planning.
@@ -859,7 +859,7 @@ ${n.join(`
859
859
  Note: this search ran in basic-regex (BRE) mode, where '|' is a literal pipe \u2014 not alternation. If you intended "A or B", retry with extended: true (extended regex / ERE). If you meant the literal character '|', this empty result stands.`),d({content:C});return}if(S===2){let C=ys(h.trim());d({content:`grep error: ${C.content}`,isError:!0,...C.truncated?{truncated:!0}:{}});return}let E=yr(g.trimEnd()),x=ys(E);d({content:x.content,...x.truncated?{truncated:!0}:{}})}),p.on("error",S=>{let E;if(m===void 0&&Il(S))try{E=hs(S,process.cwd())}catch{E=`working directory does not exist (process cwd deleted \u2014 deleted worktree?) \u2014 underlying: ${S.message}`}else E=hs(S,m);d({content:`Failed to execute grep: ${E}`,isError:!0})})})}}var _R,IR=R(()=>{"use strict";Bn();qr();zo();tb();nb();_R=ub()});import{promises as pq}from"fs";function pb(e){return(t,n,r)=>mq(t,n,r,e)}var mq,PR,MR=R(()=>{"use strict";qr();mq=async(e,t,n,r)=>{if(!e||typeof e!="object")throw new Error("Invalid input: expected an object");let i=e.path;if(typeof i!="string")throw new Error("Invalid input: path must be a string");let s;try{s=un(i,n,"read",r)}catch(a){return{content:a instanceof Error?a.message:String(a),isError:!0}}try{let a=await pq.readdir(s,{withFileTypes:!0}),l=a.filter(m=>m.isDirectory()).map(m=>`${m.name}/`),c=a.filter(m=>!m.isDirectory()).map(m=>m.name);l.sort(),c.sort();let d=[...l,...c];return d.length===0?{content:"(empty directory)"}:{content:d.join(`
860
860
  `)}}catch(a){if(a instanceof Error){let l=a;return l.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:l.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:l.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${a.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}};PR=pb()});function fq(e=ls){return async(t,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t.message;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>OR)return{content:`Invalid input: message exceeds Telegram's ${OR}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let i=k.TELEGRAM_BOT_TOKEN;if(!i)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let s=as();if(s.length===0)return{content:"Telegram is not configured: AFK_TELEGRAM_ALLOWED_CHAT_IDS is empty or unset. Add the operator chat ID(s) before using send_telegram.",isError:!0};let a=[];for(let l of s){let c=await e({token:i,chatId:l,text:o});c.ok||a.push(`chat ${l}: ${c.errorMessage??`HTTP ${c.status}`}`)}return a.length===s.length?{content:`Failed to send Telegram message to any chat. ${a.join("; ")}`,isError:!0}:a.length>0?{content:`Sent Telegram message to ${s.length-a.length}/${s.length} chat(s); ${a.length} failed: ${a.join("; ")}`}:{content:s.length===1?`Sent Telegram message to chat ${s[0]}.`:`Sent Telegram message to ${s.length} chats.`}}}var OR,$R,DR=R(()=>{"use strict";q();pr();uu();OR=4096;$R=fq()});import{JSDOM as gq}from"jsdom";import{Readability as hq}from"@mozilla/readability";import yq from"turndown";function FR(e){return e.replace(/\n{3,}/g,`
861
861
 
862
- `).trim()}function bq(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function NR(e,t){let r=new gq(e,{url:t}).window.document,o=(r.title??"").trim(),i=null;try{let c=r.cloneNode(!0);i=new hq(c).parse()}catch{i=null}if(i&&typeof i.content=="string"&&i.content.trim().length>0){let c=FR(mb.turndown(i.content)),d=(i.title??"").trim()||o,u=typeof i.length=="number"&&i.length>0?i.length:(i.textContent??"").replace(/\s+/g," ").trim().length;return{title:d,markdown:c,textLength:u,usedFallback:!1}}let s=r.body,a=s?.innerHTML??"",l=FR(mb.turndown(a));return{title:o,markdown:l,textLength:bq(s),usedFallback:!0}}var LR,mb,BR=R(()=>{"use strict";LR=200,mb=new yq({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});mb.remove(["script","style","noscript","iframe"])});function Sq(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 UR(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function vq(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 Hu(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??Sq,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(!wq.has(u.status)||d===o)return u;let m=vq(u,s)??UR(d,i,s);W("[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=UR(d,i,s);W("[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 wq,fb=R(()=>{"use strict";ve();wq=new Set([429,502,503,504])});import{readFileSync as kq}from"node:fs";import{join as Eq}from"path";function Tq(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function jR(e,t){return Tq(t).test(e)}function Cq(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(xq.has(t))return!0;if(Rq.has(t))return!1}return!1}function HR(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function Aq(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 WR(e){let t=e===void 0||e.trim()===""?"default":e.trim();return sl(t),t}function _q(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function Iq(e){try{return kq(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function Pq(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=WR(t.defaultProfile)),n}function KR(e){let t=e?.env??k,n=e?.readFileSync??Iq,r=e?.surface??t.AGENT_SURFACE,o=Cq(t.AFK_BROWSER_HEADLESS,r),i=HR(t.AFK_BROWSER_ALLOWED_DOMAINS),s=HR(t.AFK_BROWSER_BLOCKED_DOMAINS),a=_q(t.AFK_BROWSER_DOM_SNAPSHOTS),l=Aq(t.AFK_BROWSER_BACKEND),c=WR(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():Eq(bn(),"browser.json"),p=n(m);if(p===void 0)return d;let g;try{g=JSON.parse(p)}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=Pq(d,g);return h.configPath=m,h}function gb(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(jR(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>jR(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var xq,Rq,hb=R(()=>{"use strict";q();G();xq=new Set(["daemon","subagent","telegram","afk"]),Rq=new Set(["repl","interactive","cli"])});import Vo from"node:fs";import Wu from"node:path";import{randomBytes as Mq}from"node:crypto";import{chromium as Oq}from"playwright";function $q(){try{return"5.33.1"}catch{}try{let e=Wu.resolve(import.meta.dirname,"../../../package.json"),t=Vo.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Dq,Ku,GR=R(()=>{"use strict";G();ve();Dq=$q(),Ku=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=Oq.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),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=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let s=await o.newPage(),a=await s.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await s.content(),c=s.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),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){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.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/${Dq}`}}loadStorageState(t){let n=al(t);try{if(!Vo.existsSync(n))return;let r=JSON.parse(Vo.readFileSync(n,"utf8"));return W("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){W("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=al(t);if(!Vo.existsSync(r))return;let o=await n.storageState(),i=Wu.join(Wu.dirname(r),`.${Wu.basename(r)}.${process.pid}.${Mq(4).toString("hex")}.tmp`);Vo.writeFileSync(i,JSON.stringify(o),{mode:384}),Vo.chmodSync(i,384),Vo.renameSync(i,r),W("[browser/vault] saved session",{profile:t,file:r})}catch(r){W("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as Fq}from"crypto";function yb(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of Lq)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function qR(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&Nq.test(e.label))}function zR(e){return Fq("sha256").update(e,"utf8").digest("hex").slice(0,8)}function JR(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var Lq,Nq,Ol=R(()=>{"use strict";Lq=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];Nq=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Bq}from"node:crypto";function Uq(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function jq(e,t,n){return`el_${Bq("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function Hq(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function VR(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function XR(e,t){let n=e.role??"",r=e.name??"";YR.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])XR(i,t)}async function Wq(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},ZR).catch(()=>[])}async function Kq(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,p=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};u!==void 0&&(g.value=u),p!==void 0&&(g.checked=p),o.push(g)}return o},ZR).catch(()=>[])}function Gq(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Gu(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=Gq(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Wq(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,m,p,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],XR(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await Kq(e)).filter(_=>YR.has(_.role??"")));let w=new Map;for(let I of m){let _=VR(I.name),D=w.get(_);(!D||D.bbox.w===0&&I.bbox.w>0)&&w.set(_,I)}let v=y.map(I=>({ax:I,dom:w.get(VR(I.name??""))})),S=r?v:v.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);S.sort((I,_)=>{let D=I.dom?.bbox.y??0,F=_.dom?.bbox.y??0;if(D!==F)return D-F;let U=I.dom?.bbox.x??0,H=_.dom?.bbox.x??0;return U-H}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=S.slice(0,n).map((I,_)=>{let D=I.ax.role??"generic",F=I.ax.name??"",U=jq(D,F,_),H=I.dom?.bbox??{x:0,y:0,w:0,h:0},B=I.dom?.type??null,P=null;I.ax.value!==void 0&&I.ax.value!==null&&(P=String(I.ax.value)),I.ax.checked!==void 0&&(P=String(I.ax.checked)),qR({role:D,kind:B})&&(P="[redacted]");let M={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(M.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(M.selected=I.ax.selected),I.ax.expanded!==void 0&&(M.expanded=I.ax.expanded);let O;I.dom?.testId?O=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(O=`#${I.dom.id}`);let j={id:U,role:D,label:Uq(F),kind:B,value:P,state:M,bbox:H};return O!==void 0&&(j.selector=O),j}),C="idle";try{let I=await e.evaluate(()=>document.readyState);I==="loading"?C="loading":I==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="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 A=Hq(p),N=`obs_${t.observationCounter.toString(36)}`,$=new Date().toISOString();return{observationId:N,url:g,title:h,textSummary:A,interactive:x,status:{httpStatus:t.httpStatus??null,loadingState:C,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:$}}var YR,ZR,QR=R(()=>{"use strict";Ol();YR=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);ZR="a[href], button, input, select, textarea, [role], [tabindex], label"});async function eC(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 bb(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>eC(e,i)))).filter(o=>o!==null)}async function qq(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 wb(e,t,n){switch(t.kind){case"element_id":return zq(e,t,n);case"selector":return Jq(e,t);case"semantic":return Vq(e,t)}}async function zq(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 bb(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function Jq(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 bb(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function Vq(e,t){return t.role!==void 0?Yq(e,t.text,t.role):Xq(e,t.text,t)}async function Yq(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 bb(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function Xq(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 qq(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),p=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await eC(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,v=0;for(let S=0;S<w.length;S++)v=v*31+w.charCodeAt(S)>>>0;p.push({...b,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:p}}var tC=R(()=>{"use strict"});import{randomBytes as Zq}from"crypto";import{mkdir as Qq,stat as ez,writeFile as tz}from"fs/promises";import{join as Sb}from"path";import{gzip as nz}from"zlib";import{promisify as rz}from"util";function oz(e){return Sb($o(e),"browser")}function iz(e){return Sb(oz(e),"screenshots")}function sz(){return new Date().toISOString().replace(/[:.]/g,"-")}function az(){return Zq(3).toString("hex")}async function vb(e,t,n){if(t.length>nC)throw new Error(`writeScreenshotSidecar: buffer exceeds ${nC} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=iz(e);await Qq(r,{recursive:!0});let o=`${sz()}-${az()}-${n}.png`,i=Sb(r,o);await tz(i,t);let{size:s}=await ez(i);return{path:i,bytes:s}}var jye,nC,rC=R(()=>{"use strict";G();Ol();jye=rz(nz);nC=5*1024*1024});var iC={};kd(iC,{PlaywrightProvider:()=>kb});function oC(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 kb,sC=R(()=>{"use strict";GR();QR();tC();hb();Ol();rC();kb=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Ku(t)}async open(t){let n=gb(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(c){a=c}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let l=await Gu(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}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 Gu(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 wb(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${oC(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":{let h=yb(t.value??"");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=r.url();if(u!==i){let h=gb(u,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:h.reason}}let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let p=await Gu(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,p.interactive,p.url,p.title,g),c!==null)throw c;return p}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}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 wb(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${oC(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 vb(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 vb(n,o,r);return i}catch{return null}}}});var Xo={};kd(Xo,{__resetBrowserRegistryForTests:()=>pz,browserProviderActive:()=>dz,closeBrowserProvider:()=>Eb,getBrowserProvider:()=>cz,peekBrowserProvider:()=>uz});function aC(){Promise.resolve(Eb()).then(()=>{process.exit(130)})}function lC(){Promise.resolve(Eb()).then(()=>{process.exit(143)})}function cC(){jn=null}function lz(){qu||(process.on("SIGINT",aC),process.on("SIGTERM",lC),process.on("exit",cC),qu=!0)}function dC(){qu&&(process.removeListener("SIGINT",aC),process.removeListener("SIGTERM",lC),process.removeListener("exit",cC),qu=!1)}async function cz(e){return jn!==null?jn:(Yo!==null||(Yo=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(sC(),iC)),n=KR(e),r=new t(n);return lz(),jn=r,Yo=null,r})()),Yo)}async function Eb(){if(jn===null)return;let e=jn;jn=null,Yo=null,dC(),await e.shutdown()}function dz(){return jn!==null}function uz(){return jn}function pz(){jn=null,Yo=null,dC()}var jn,Yo,qu,Zo=R(()=>{"use strict";hb();jn=null,Yo=null,qu=!1});function uC(e,t){try{return NR(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function yz(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Zo(),Xo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function pC(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??yz,o=null,i=e,s=null,a=null;try{let c=await Hu(n,e,{headers:hz,redirect:"follow",signal:t.signal});s=c.status,i=c.url||e;let d=c.headers.get("content-type")??"";if(c.ok){if(gz.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await c.text();if(fz.test(d)&&!mz.test(d))return{title:"",markdown:u.trim(),finalUrl:i,usedRender:!1};o=uC(u,i)}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<LR)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),d=uC(c.html,c.finalUrl);if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),u=a instanceof Error?a.message:`HTTP ${s??"error"}`,m=new Error(`web_scrape could not retrieve ${e}: fetch failed (${u}) and render failed (${d}).`);throw m.cause=c,m}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${s??"error"}).`)}var mz,fz,gz,hz,mC=R(()=>{"use strict";BR();fb();ve();mz=/(text\/html|application\/xhtml\+xml)/i,fz=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,gz=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,hz={"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 Sz(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(bz,{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),wz),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=qo(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 fC(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Sz({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 gC(e,t){if(t.length===0)return`# Search results for "${e}"
862
+ `).trim()}function bq(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function NR(e,t){let r=new gq(e,{url:t}).window.document,o=(r.title??"").trim(),i=null;try{let c=r.cloneNode(!0);i=new hq(c).parse()}catch{i=null}if(i&&typeof i.content=="string"&&i.content.trim().length>0){let c=FR(mb.turndown(i.content)),d=(i.title??"").trim()||o,u=typeof i.length=="number"&&i.length>0?i.length:(i.textContent??"").replace(/\s+/g," ").trim().length;return{title:d,markdown:c,textLength:u,usedFallback:!1}}let s=r.body,a=s?.innerHTML??"",l=FR(mb.turndown(a));return{title:o,markdown:l,textLength:bq(s),usedFallback:!0}}var LR,mb,BR=R(()=>{"use strict";LR=200,mb=new yq({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});mb.remove(["script","style","noscript","iframe"])});function Sq(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 UR(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function vq(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 Hu(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??Sq,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(!wq.has(u.status)||d===o)return u;let m=vq(u,s)??UR(d,i,s);W("[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=UR(d,i,s);W("[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 wq,fb=R(()=>{"use strict";ve();wq=new Set([429,502,503,504])});import{readFileSync as kq}from"node:fs";import{join as Eq}from"path";function Tq(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function jR(e,t){return Tq(t).test(e)}function Cq(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(xq.has(t))return!0;if(Rq.has(t))return!1}return!1}function HR(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function Aq(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 WR(e){let t=e===void 0||e.trim()===""?"default":e.trim();return sl(t),t}function _q(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function Iq(e){try{return kq(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function Pq(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=WR(t.defaultProfile)),n}function KR(e){let t=e?.env??k,n=e?.readFileSync??Iq,r=e?.surface??t.AGENT_SURFACE,o=Cq(t.AFK_BROWSER_HEADLESS,r),i=HR(t.AFK_BROWSER_ALLOWED_DOMAINS),s=HR(t.AFK_BROWSER_BLOCKED_DOMAINS),a=_q(t.AFK_BROWSER_DOM_SNAPSHOTS),l=Aq(t.AFK_BROWSER_BACKEND),c=WR(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():Eq(bn(),"browser.json"),p=n(m);if(p===void 0)return d;let g;try{g=JSON.parse(p)}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=Pq(d,g);return h.configPath=m,h}function gb(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(jR(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>jR(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var xq,Rq,hb=R(()=>{"use strict";q();G();xq=new Set(["daemon","subagent","telegram","afk"]),Rq=new Set(["repl","interactive","cli"])});import Vo from"node:fs";import Wu from"node:path";import{randomBytes as Mq}from"node:crypto";import{chromium as Oq}from"playwright";function $q(){try{return"5.33.2"}catch{}try{let e=Wu.resolve(import.meta.dirname,"../../../package.json"),t=Vo.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Dq,Ku,GR=R(()=>{"use strict";G();ve();Dq=$q(),Ku=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=Oq.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),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=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let s=await o.newPage(),a=await s.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await s.content(),c=s.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),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){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.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/${Dq}`}}loadStorageState(t){let n=al(t);try{if(!Vo.existsSync(n))return;let r=JSON.parse(Vo.readFileSync(n,"utf8"));return W("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){W("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=al(t);if(!Vo.existsSync(r))return;let o=await n.storageState(),i=Wu.join(Wu.dirname(r),`.${Wu.basename(r)}.${process.pid}.${Mq(4).toString("hex")}.tmp`);Vo.writeFileSync(i,JSON.stringify(o),{mode:384}),Vo.chmodSync(i,384),Vo.renameSync(i,r),W("[browser/vault] saved session",{profile:t,file:r})}catch(r){W("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as Fq}from"crypto";function yb(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of Lq)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function qR(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&Nq.test(e.label))}function zR(e){return Fq("sha256").update(e,"utf8").digest("hex").slice(0,8)}function JR(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var Lq,Nq,Ol=R(()=>{"use strict";Lq=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];Nq=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Bq}from"node:crypto";function Uq(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function jq(e,t,n){return`el_${Bq("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function Hq(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function VR(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function XR(e,t){let n=e.role??"",r=e.name??"";YR.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])XR(i,t)}async function Wq(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},ZR).catch(()=>[])}async function Kq(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,p=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};u!==void 0&&(g.value=u),p!==void 0&&(g.checked=p),o.push(g)}return o},ZR).catch(()=>[])}function Gq(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Gu(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=Gq(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Wq(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,m,p,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],XR(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await Kq(e)).filter(_=>YR.has(_.role??"")));let w=new Map;for(let I of m){let _=VR(I.name),D=w.get(_);(!D||D.bbox.w===0&&I.bbox.w>0)&&w.set(_,I)}let v=y.map(I=>({ax:I,dom:w.get(VR(I.name??""))})),S=r?v:v.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);S.sort((I,_)=>{let D=I.dom?.bbox.y??0,F=_.dom?.bbox.y??0;if(D!==F)return D-F;let U=I.dom?.bbox.x??0,H=_.dom?.bbox.x??0;return U-H}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=S.slice(0,n).map((I,_)=>{let D=I.ax.role??"generic",F=I.ax.name??"",U=jq(D,F,_),H=I.dom?.bbox??{x:0,y:0,w:0,h:0},B=I.dom?.type??null,P=null;I.ax.value!==void 0&&I.ax.value!==null&&(P=String(I.ax.value)),I.ax.checked!==void 0&&(P=String(I.ax.checked)),qR({role:D,kind:B})&&(P="[redacted]");let M={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(M.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(M.selected=I.ax.selected),I.ax.expanded!==void 0&&(M.expanded=I.ax.expanded);let O;I.dom?.testId?O=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(O=`#${I.dom.id}`);let j={id:U,role:D,label:Uq(F),kind:B,value:P,state:M,bbox:H};return O!==void 0&&(j.selector=O),j}),C="idle";try{let I=await e.evaluate(()=>document.readyState);I==="loading"?C="loading":I==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="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 A=Hq(p),N=`obs_${t.observationCounter.toString(36)}`,$=new Date().toISOString();return{observationId:N,url:g,title:h,textSummary:A,interactive:x,status:{httpStatus:t.httpStatus??null,loadingState:C,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:$}}var YR,ZR,QR=R(()=>{"use strict";Ol();YR=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);ZR="a[href], button, input, select, textarea, [role], [tabindex], label"});async function eC(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 bb(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>eC(e,i)))).filter(o=>o!==null)}async function qq(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 wb(e,t,n){switch(t.kind){case"element_id":return zq(e,t,n);case"selector":return Jq(e,t);case"semantic":return Vq(e,t)}}async function zq(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 bb(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function Jq(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 bb(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function Vq(e,t){return t.role!==void 0?Yq(e,t.text,t.role):Xq(e,t.text,t)}async function Yq(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 bb(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function Xq(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 qq(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),p=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await eC(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,v=0;for(let S=0;S<w.length;S++)v=v*31+w.charCodeAt(S)>>>0;p.push({...b,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:p}}var tC=R(()=>{"use strict"});import{randomBytes as Zq}from"crypto";import{mkdir as Qq,stat as ez,writeFile as tz}from"fs/promises";import{join as Sb}from"path";import{gzip as nz}from"zlib";import{promisify as rz}from"util";function oz(e){return Sb($o(e),"browser")}function iz(e){return Sb(oz(e),"screenshots")}function sz(){return new Date().toISOString().replace(/[:.]/g,"-")}function az(){return Zq(3).toString("hex")}async function vb(e,t,n){if(t.length>nC)throw new Error(`writeScreenshotSidecar: buffer exceeds ${nC} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=iz(e);await Qq(r,{recursive:!0});let o=`${sz()}-${az()}-${n}.png`,i=Sb(r,o);await tz(i,t);let{size:s}=await ez(i);return{path:i,bytes:s}}var jye,nC,rC=R(()=>{"use strict";G();Ol();jye=rz(nz);nC=5*1024*1024});var iC={};kd(iC,{PlaywrightProvider:()=>kb});function oC(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 kb,sC=R(()=>{"use strict";GR();QR();tC();hb();Ol();rC();kb=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Ku(t)}async open(t){let n=gb(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(c){a=c}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let l=await Gu(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}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 Gu(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 wb(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${oC(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":{let h=yb(t.value??"");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=r.url();if(u!==i){let h=gb(u,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:h.reason}}let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let p=await Gu(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,p.interactive,p.url,p.title,g),c!==null)throw c;return p}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}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 wb(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${oC(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 vb(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 vb(n,o,r);return i}catch{return null}}}});var Xo={};kd(Xo,{__resetBrowserRegistryForTests:()=>pz,browserProviderActive:()=>dz,closeBrowserProvider:()=>Eb,getBrowserProvider:()=>cz,peekBrowserProvider:()=>uz});function aC(){Promise.resolve(Eb()).then(()=>{process.exit(130)})}function lC(){Promise.resolve(Eb()).then(()=>{process.exit(143)})}function cC(){jn=null}function lz(){qu||(process.on("SIGINT",aC),process.on("SIGTERM",lC),process.on("exit",cC),qu=!0)}function dC(){qu&&(process.removeListener("SIGINT",aC),process.removeListener("SIGTERM",lC),process.removeListener("exit",cC),qu=!1)}async function cz(e){return jn!==null?jn:(Yo!==null||(Yo=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(sC(),iC)),n=KR(e),r=new t(n);return lz(),jn=r,Yo=null,r})()),Yo)}async function Eb(){if(jn===null)return;let e=jn;jn=null,Yo=null,dC(),await e.shutdown()}function dz(){return jn!==null}function uz(){return jn}function pz(){jn=null,Yo=null,dC()}var jn,Yo,qu,Zo=R(()=>{"use strict";hb();jn=null,Yo=null,qu=!1});function uC(e,t){try{return NR(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function yz(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Zo(),Xo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function pC(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??yz,o=null,i=e,s=null,a=null;try{let c=await Hu(n,e,{headers:hz,redirect:"follow",signal:t.signal});s=c.status,i=c.url||e;let d=c.headers.get("content-type")??"";if(c.ok){if(gz.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await c.text();if(fz.test(d)&&!mz.test(d))return{title:"",markdown:u.trim(),finalUrl:i,usedRender:!1};o=uC(u,i)}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<LR)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),d=uC(c.html,c.finalUrl);if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),u=a instanceof Error?a.message:`HTTP ${s??"error"}`,m=new Error(`web_scrape could not retrieve ${e}: fetch failed (${u}) and render failed (${d}).`);throw m.cause=c,m}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:i,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${s??"error"}).`)}var mz,fz,gz,hz,mC=R(()=>{"use strict";BR();fb();ve();mz=/(text\/html|application\/xhtml\+xml)/i,fz=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,gz=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,hz={"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 Sz(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(bz,{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),wz),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=qo(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 fC(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Sz({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 gC(e,t){if(t.length===0)return`# Search results for "${e}"
863
863
 
864
864
  (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(`
865
865
  `).trimEnd()}var bz,wz,hC=R(()=>{"use strict";zo();bz="https://api.exa.ai/search",wz=10});function Az(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=vz;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,kz)}let a=Ez;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,Tz)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function Tb(e,t){let n=Buffer.from(e,"utf8");return n.byteLength<=t?e:n.subarray(0,t).toString("utf8")+xz}function _z(e){let t=[],n=e;for(let o=0;o<4&&n instanceof Error;o++)t.push(n.message),n=n.cause;let r=t.join(" | ");return Cz.some(o=>r.includes(o))}function Iz(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env;return async(r,o)=>{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 i=Az(r);if("error"in i)return{content:i.error,isError:!0};if(o.aborted){let d=o.reason;return{content:`web_scrape aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let s=new AbortController,a=()=>{s.abort(o.reason)},l,c=()=>{let d=s.signal.reason;return d instanceof Error?d.message:String(d??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),l=setTimeout(()=>{s.abort(new Error(`web_scrape timeout after ${i.timeoutMs}ms`))},i.timeoutMs),i.mode==="raw"){let u;try{u=await Hu(t,i.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:s.signal})}catch(p){return s.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape network error: ${p instanceof Error?p.message:String(p)}`,isError:!0}}if(!u.ok)return{content:`web_scrape HTTP ${u.status} ${u.statusText||""}`.trimEnd()+` for ${i.url}`,isError:!0};let m;try{m=await u.text()}catch(p){return{content:`web_scrape read error: ${p instanceof Error?p.message:String(p)}`,isError:!0}}return{content:Tb(m,i.maxBytes)}}if(i.mode==="markdown")try{let u=await pC(i.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:i.timeoutMs,signal:s.signal});return u.markdown.trim().length===0?{content:`web_scrape extracted no readable content from ${i.url}.`,isError:!0}:{content:Tb(u.markdown,i.maxBytes)}}catch(u){if(s.signal.aborted)return{content:`web_scrape aborted: ${c()}`,isError:!0};let m=u instanceof Error?u.message:String(u),p=_z(u)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${m}${p}`,isError:!0}}let d=fC({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in d)return{content:d.error,isError:!0};try{let u=await d.search(i.query,{limit:Rz,timeoutMs:i.timeoutMs,signal:s.signal});return{content:Tb(gC(i.query,u),i.maxBytes)}}catch(u){return s.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${u instanceof Error?u.message:String(u)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),o.removeEventListener("abort",a)}}}var vz,kz,Ez,Tz,xz,Rz,Cz,yC,bC=R(()=>{"use strict";mC();hC();fb();vz=3e4,kz=12e4,Ez=1e6,Tz=1e7,xz=`
@@ -1068,7 +1068,7 @@ Available agent types (pass via \`agent_type\`):
1068
1068
  `);continue}let l=await ao.readFile(s,"utf8"),c=JSON.parse(l);if(c.status==="running"||c.endedAt===void 0||Date.now()-c.endedAt<6048e5)continue;await ao.rm(i,{recursive:!0,force:!0})}catch(a){if(a.code==="ENOENT")continue;process.stderr.write(`[afk] bg sweep: error evicting ${o}: ${String(a)}
1069
1069
  `)}}}statusFromResult(t){return t==="succeeded"?"completed":t==="failed"?"failed":t==="cancelled"?"cancelled":"failed"}snapshot(t){return{jobId:t.jobId,subagentId:t.subagentId,label:t.label,model:t.model,startedAt:t.startedAt,status:t.status,...t.result!==void 0?{result:t.result}:{},...t.endedAt!==void 0?{endedAt:t.endedAt}:{}}}}});async function sI(e){let{handle:t,registry:n,prompt:r,model:o,parentSessionId:i}=e;if(!n)return await t.teardown().catch(l=>W("subagent-executor: handle teardown failed: "+(l instanceof Error?l.message:String(l)))),{content:'Background mode is not available in this session \u2014 no BackgroundAgentRegistry is wired. Re-issue the call with mode="foreground" or run inside `afk interactive`.',isError:!0};let s;try{s=n.register({handle:t,prompt:r,model:o??"sonnet",parentSessionId:i})}catch(l){if(l instanceof rc)return await t.teardown().catch(c=>W("subagent-executor: handle teardown failed after cap error: "+(c instanceof Error?c.message:String(c)))),{content:l.message,isError:!0};throw l}let a={status:"running",jobId:s.jobId,subagentId:s.subagentId,label:s.label,message:`Background subagent started (jobId=${s.jobId}). It is running detached; its result will be delivered into this context automatically with the next user message once it finishes. /bgsub:join ${s.jobId} remains available for manual replay.`};return{content:JSON.stringify(a)}}var aI=R(()=>{"use strict";Bw();ve()});async function lI(e){let{handle:t,signal:n,prompt:r,idPrefix:o,model:i,childManager:s,identity:a,depth:l,parentSessionId:c,registry:d,promotionTriggers:u,activeForegroundHandles:m}=e,p=()=>{t.cancel()};n.addEventListener("abort",p,{once:!0});let g=Date.now(),h=!1,y,b=new Promise(x=>{y=x}),w,v=new Promise(x=>{w=x});u.set(t.id,{fire:y,ready:v}),m.set(t.id,t);let S,E=t.runToResult(r);try{let x=await Promise.race([E.then(I=>({kind:"result",result:I})),b.then(()=>({kind:"promote"}))]);if(x.kind==="promote")if(d)try{let I=d.adoptRunning({handle:t,runPromise:E,prompt:r,model:i??"sonnet",parentSessionId:c});return h=!0,n.removeEventListener("abort",p),w({jobId:I.jobId,label:I.label}),{content:JSON.stringify({status:"running",jobId:I.jobId,subagentId:I.subagentId,label:I.label,message:`Subagent backgrounded by user (jobId=${I.jobId}). It keeps running detached; its result will be delivered into this context automatically with the next user message once it finishes. /bgsub:join ${I.jobId} remains available for manual replay.`})}}catch(I){W("subagent-executor: promotion failed, staying foreground: "+(I instanceof Error?I.message:String(I))),w(null)}else w(null);let C=x.kind==="result"?x.result:await E;if(C.status==="succeeded"&&C.message){let I=C.message.content,_=typeof I=="string"?I:JSON.stringify(I),D=C.trace;return Ms({...a,event:"subagent.completed",subagent_id:t.id,parent_session_id:c,status:C.status,duration_ms:Date.now()-g,content_chars:_.length,depth:l,tool_call_count:D?.toolCalls.length,thinking_present:D?.thinkingPresent,tool_names:D?.toolCalls.length?JSON.stringify([...new Set(D.toolCalls.map(F=>F.name))]):void 0}),S={content:oo(_,C.stopReason)},S}let A=C.error?.message??"Subagent failed with no output",N=C.trace;Ms({...a,event:"subagent.failed",subagent_id:t.id,id_prefix:o,parent_session_id:c,status:C.status,duration_ms:Date.now()-g,error_message:so(A),schema_error:C.schemaError?so(C.schemaError.message):void 0,partial_output_chars:Fw(C.partialOutput),depth:l,tool_call_count:N?.toolCalls.length,thinking_present:N?.thinkingPresent,tool_names:N?.toolCalls.length?JSON.stringify([...new Set(N.toolCalls.map(I=>I.name))]):void 0});let $=Q_({status:C.status,errorMessage:A,schemaErrorMessage:C.schemaError?.message,partialOutput:C.partialOutput,subagentId:t.id});return S={content:JSON.stringify($),isError:!0},S}catch(x){let C=x instanceof Error?x.message:String(x);throw Ms({...a,event:"subagent.failed",subagent_id:t.id,id_prefix:o,parent_session_id:c,status:"failed",duration_ms:Date.now()-g,error_message:so(C),depth:l}),x}finally{if(u.delete(t.id),m.delete(t.id),w(null),!h){n.removeEventListener("abort",p),await s?.teardownAll(),await t.teardown({deferInjectContextToCaller:!0});let x=t.getLastStopInjectContext?.();if(Yp(S,x),e.isolationTeardown){let{repoRoot:C,worktreePath:A}=e.isolationTeardown,N=await FC({repoRoot:C,worktreePath:A});N.preserved&&W(`[isolation] preserved worktree ${A} (${N.reason}) \u2014 locked so the sweep will not reap it; recover via the worktree tool`)}}}}var cI=R(()=>{"use strict";Rt();ve();Lw();Cw();ep()});var Jn,oc=R(()=>{"use strict";Ke();Cn();Ps();zo();Xr();X_();Lw();tI();aI();cI();ep();ve();Cn();Jn=class e{constructor(t){this.ctx=t;this.currentCwd=t.cwd}ctx;currentCwd;isolationCounter=0;setCwd(t){this.currentCwd=t,this.ctx.subagentManager.setCwd(t)}describeAgentTool(){return Dw(this.ctx.agentRegistry)}promotionTriggers=new Map;activeForegroundHandles=new Map;hasPromotableForeground(){return this.ctx.backgroundRegistry!==void 0&&this.promotionTriggers.size>0}hasActiveForeground(){return this.activeForegroundHandles.size>0}async cancelActiveForeground(){let t=[...this.activeForegroundHandles.values()];return t.length===0?0:(await Promise.all(t.map(n=>n.cancel().catch(()=>{}))),t.length)}async promoteActiveForeground(){let t=[...this.promotionTriggers.values()];return t.forEach(r=>r.fire()),(await Promise.all(t.map(r=>r.ready))).filter(r=>r!==null)}getSubagentsLite(){let t=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:t,backgroundJobs:n}}async execute(t){if(t.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=Y_(t.input)}catch(g){return{content:`Agent tool input validation failed: ${g instanceof Error?g.message:String(g)}`,isError:!0}}let r;if(n.agent_type!==void 0&&(r=this.ctx.agentRegistry?.get(n.agent_type),r===void 0)){let g=[...this.ctx.agentRegistry?.keys()??[]].sort().join(", ");return{content:`Agent type "${n.agent_type}" not found. Available agent types: ${g.length>0?g:"(none)"}`,isError:!0}}let o=this.ctx.nestedAgentAllowlist;if(o!==void 0){let g=n.agent_type;if(g===void 0||!o.includes(g))return{content:o.length===0?"This agent is not permitted to dispatch any nested agents (its definition granted the dispatch tool but named zero allowed types, e.g. `Agent()`). Complete the task with your own tools.":`This agent may only dispatch the following agent type(s): ${o.join(", ")}. `+(g===void 0?"A bare dispatch with no agent_type is not permitted here \u2014 set agent_type to one of the allowed types, or complete the task with your own tools.":`agent_type "${g}" is out of scope.`),isError:!0}}let i=this.ctx.depth,s=this.ctx.maxDepth??si,a=this.ctx.surface!==void 0?{origin:Yr(this.ctx.surface),actor:Kn(i)}:{},{childConfig:l,childParentSession:c,childManager:d,childWriteCapable:u}=eI({parsed:n,namedAgent:r,depth:i,maxDepth:s,currentCwd:this.currentCwd,signal:t.signal,defaultConfig:this.ctx.defaultConfig,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,...this.ctx.childProviderFactory!==void 0?{childProviderFactory:this.ctx.childProviderFactory}:{},...this.ctx.childSkillExecutorFactory!==void 0?{childSkillExecutorFactory:this.ctx.childSkillExecutorFactory}:{},...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash!==void 0?{readOnlyBash:this.ctx.readOnlyBash}:{},...this.ctx.agentRegistry!==void 0?{agentRegistry:this.ctx.agentRegistry}:{},...this.ctx.parentModel!==void 0?{parentModel:this.ctx.parentModel}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},createChildExecutor:g=>new e(g)}),m;if(n.isolation==="worktree")if(!u)W(`[isolation] skipped worktree for read-only dispatch (agent_type=${n.agent_type??"generic"}) \u2014 nothing to isolate`);else{let g=this.currentCwd??process.cwd();try{let h=await DC({cwd:g,slugHint:`iso-${n.id_prefix}-${++this.isolationCounter}-${Math.random().toString(36).slice(2,8)}`});l.cwd=h.path,m={repoRoot:h.repoRoot,worktreePath:h.path}}catch(h){return{content:`Failed to create isolated worktree for the subagent: ${h instanceof Error?h.message:String(h)}. isolation:"worktree" requires the dispatching session to run inside a git repository.`,isError:!0}}}n.mode==="background"&&l.timeoutMs===void 0&&(l.timeoutMs=dI);let p;try{p=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:t.id,config:l,idPrefix:n.id_prefix,agentType:r!==void 0?r.name:n.id_prefix&&n.id_prefix!=="agent-tool"?yr(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":yr(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:!0}),c!==void 0&&(c.sessionId=p.id)}catch(g){let h=g instanceof Error?g.message:String(g);return Ms({...a,event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:so(h),depth:i}),{content:`Failed to fork subagent: ${h}`,isError:!0}}return n.mode==="background"?sI({handle:p,registry:this.ctx.backgroundRegistry,prompt:n.prompt,model:l.model,parentSessionId:this.ctx.parentSession.sessionId}):lI({handle:p,signal:t.signal,prompt:n.prompt,idPrefix:n.id_prefix,model:l.model,childManager:d,identity:a,depth:i,parentSessionId:this.ctx.parentSession.sessionId,registry:this.ctx.backgroundRegistry,promotionTriggers:this.promotionTriggers,activeForegroundHandles:this.activeForegroundHandles,...m!==void 0?{isolationTeardown:m}:{}})}}});function Uw(e,t,n,r=!1,o){let{ctx:i,currentCwd:s}=e,a=i.depth??0,l=i.maxDepth??si,c={...t},d=r&&o!==void 0?o.filter(h=>am.includes(h)):r?[...am]:o,u=r;if(!i.childProviderFactory||a>=l)return r?c.provider=pI(c.model,i.openaiBaseUrl):d!==void 0&&(c.provider=rm(d,c.model,u,i.openaiBaseUrl)),{childConfig:c,childManager:void 0};let m=new ie({parentAbortSignal:n,...i.traceWriter!==void 0?{traceWriter:i.traceWriter}:{},...s!==void 0?{cwd:s}:{}}),p=new Jn({subagentManager:m,parentSession:ii(n),defaultConfig:{model:c.model,apiKey:i.apiKey,...i.baseUrl!==void 0?{baseUrl:i.baseUrl}:{},...i.openaiBaseUrl!==void 0?{openaiBaseUrl:i.openaiBaseUrl}:{}},...i.surface!==void 0?{surface:i.surface}:{},defaultSubagentModel:i.defaultSubagentModel,childProviderFactory:i.childProviderFactory,childSkillExecutorFactory:i.childSkillExecutorFactory,...i.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:i.resolveApiKeyForModel}:{},depth:a+1,maxDepth:l,...s!==void 0?{cwd:s}:{},...i.traceWriter!==void 0?{traceWriter:i.traceWriter}:{},...i.backgroundRegistry!==void 0?{backgroundRegistry:i.backgroundRegistry}:{},...d!==void 0?{allowedTools:d}:{},...u?{readOnlyBash:!0}:{},...i.agentRegistry!==void 0?{agentRegistry:i.agentRegistry}:{},...c.model!==void 0?{parentModel:c.model}:{}}),g=i.childSkillExecutorFactory?i.childSkillExecutorFactory(a+1,l,n,s):void 0;return c.provider=i.childProviderFactory({childExecutor:p,...g!==void 0?{childSkillExecutor:g}:{},...c.model!==void 0?{model:c.model}:{},...d!==void 0?{allowedTools:d}:{},...u?{readOnlyBash:!0}:{}}),{childConfig:c,childManager:m}}var uI=R(()=>{"use strict";Ke();Cn();oc()});async function mI(e,t,n,r){let{ctx:o,currentCwd:i}=e;if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let s=t.readOnly===!0||lm.has(t.name),a;try{if(a=je(t.name)["system.md"],!a)return{content:`Skill "${t.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(p){return{content:`Failed to load skill prompts: ${p instanceof Error?p.message:String(p)}`,isError:!0}}let l=t.model??o.defaultSubagentModel??o.defaultModel??"sonnet",c=Ql({childModel:l,resolved:o.resolveApiKeyForModel?o.resolveApiKeyForModel(l):Le(l),parentApiKey:o.apiKey}),d=new ie({parentAbortSignal:r.signal,apiKey:c,parentModel:l,...o.baseUrl!==void 0?{baseUrl:o.baseUrl}:{},...o.traceWriter!==void 0?{traceWriter:o.traceWriter}:{},progressSink:an(),...i!==void 0?{cwd:i}:{}}),{childConfig:u,childManager:m}=Uw(e,{model:l,systemPrompt:a,isSkillDispatch:!0,...o.traceWriter!==void 0?{traceWriter:o.traceWriter}:{}},r.signal,s);return gI(e,{manager:d,childManager:m,childConfig:u,label:t.name,idPrefix:`skill-fork-${t.name}`,parentId:r.id,args:n,noOutputError:"Forked skill failed with no output",errorPrefix:"Forked skill execution error"})}async function fI(e,t,n,r,o,i,s=!1,a){let{ctx:l,currentCwd:c}=e;if(i.signal.aborted)return{content:"Skill call aborted",isError:!0};let d=l.defaultSubagentModel??l.defaultModel??"sonnet",u=Ql({childModel:d,resolved:l.resolveApiKeyForModel?l.resolveApiKeyForModel(d):Le(d),parentApiKey:l.apiKey}),m=new ie({parentAbortSignal:i.signal,apiKey:u,parentModel:d,...l.baseUrl!==void 0?{baseUrl:l.baseUrl}:{},...l.traceWriter!==void 0?{traceWriter:l.traceWriter}:{},progressSink:an(),...c!==void 0?{cwd:c}:{}}),p={model:d,systemPrompt:zp(n,o),env:{PLUGIN_ROOT:r},isSkillDispatch:!0,...l.traceWriter!==void 0?{traceWriter:l.traceWriter}:{}},{childConfig:g,childManager:h}=Uw(e,p,i.signal,s,a);return gI(e,{manager:m,childManager:h,childConfig:g,label:t,idPrefix:`skill-${t}`,parentId:i.id,args:o,noOutputError:"Plugin skill failed with no output",errorPrefix:"Plugin skill execution error"})}async function gI(e,t){let{manager:n,childManager:r,childConfig:o,label:i,idPrefix:s,parentId:a,args:l,noOutputError:c,errorPrefix:d}=t,u,m;try{u=await n.forkSubagent({parent:e.ctx.parentSession,config:o,idPrefix:s,parentId:a,agentType:i});let p=l&&l.length>0?l:`Run the ${i} skill now, following the instructions in your system prompt.`,g=await u.runToResult(p);return g.status==="succeeded"&&g.message?(m={content:oo(g.message.content,g.stopReason)},m):g.status==="cancelled"&&typeof g.partialOutput=="string"&&g.partialOutput.length>0?(m={content:`[skill cancelled mid-flight \u2014 partial output preserved below]
1070
1070
 
1071
- ${g.partialOutput}`},m):(m={content:g.error?.message??c,isError:!0},m)}catch(p){let g=p instanceof Error?p.message:String(p);return{content:`${d}: ${g}`,isError:!0}}finally{u&&await u.teardown({deferInjectContextToCaller:!0}).catch(W);let p=u?.getLastStopInjectContext?.();Yp(m,p),await r?.teardownAll(),await n.teardownAll()}}var hI=R(()=>{"use strict";Ke();Rt();Cw();Cn();Xp();Nt();fr();on();ve();uI();Tw()});function YY(e){if(typeof e!="object"||e===null)return;let t=e.name;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}function XY(e){if(typeof e!="object"||e===null)throw new Error("Skill tool input must be an object");let t=e,n=t.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=t.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var Vn,ic=R(()=>{"use strict";Ot();Gn();Cn();bw();Bn();ww();kw();Ew();Tw();hI();Vn=class{constructor(t){this.ctx=t;this.currentCwd=t.cwd}ctx;pluginBodies=null;currentCwd;setCwd(t){this.currentCwd=t,this.pluginBodies=null}internals(){return{ctx:this.ctx,currentCwd:this.currentCwd}}async execute(t){if(t.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??si;if(n>=r){let l=YY(t.input);return Ne({...As(this.ctx),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:Gp(n,r),isError:!0}}let o;try{o=XY(t.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=Ve(o.name);return await this.executeRegistrySkill(l,o.arguments,t)}catch{}let i=this.getPluginSkillBody(o.name);if(i){if(i.context==="fork"){let c=i.readOnly===!0||lm.has(o.name);return await fI(this.internals(),o.name,i.body,i.pluginPath,o.arguments,t,c,i.allowedTools)}let l=i.body.replace(/\$\{PLUGIN_ROOT(?::-(?:[^{}]|\$\{[^{}]*\})*)?\}|\$PLUGIN_ROOT\b/g,()=>i.pluginPath);return O_(this.internals(),o.name,l,o.arguments,t)}let a=ai(this.ctx.pluginConfigs,this.currentCwd!==void 0?{cwd:this.currentCwd}:void 0).map(l=>l.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${a||"(none)"}`,isError:!0}}async executeRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(t.context==="fork")return mI(this.internals(),t,n,r);if(t.context==="load")return M_(this.internals(),t,n,r);let o=k_(t.name);o&&A_(t.name);let i=this.ctx.depth??0;Ne({...As(this.ctx),event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:i,...qp(t.name)?{is_gate:!0}:{},...t.model!==void 0?{model:t.model}:{}}).catch(()=>{});let s=Date.now(),a,l;try{l=await t.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r),...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}})}catch(d){a=d}finally{let d=Date.now()-s;o&&C_({skillName:t.name,durationMs:d,...a!==void 0?{isError:!0}:{}});let u=a!==void 0?a instanceof Error?a.message:String(a):void 0,m=a===void 0?typeof l=="string"?l.length:l!=null?JSON.stringify(l).length:0:void 0;Ne({...As(this.ctx),event:"skill.completed",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:d,depth:i,...m!==void 0?{content_chars:m}:{},...u!==void 0?{error_message:__(u)}:{},...t.model!==void 0?{model:t.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof l=="string"?l:l!=null?JSON.stringify(l):"Skill completed successfully."}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=sc(this.ctx.pluginConfigs,this.currentCwd!==void 0?{cwd:this.currentCwd}:void 0)),this.pluginBodies.get(t)}createDispatchSkillCallback(t){return async(n,r)=>{let o={id:`${t.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:t.signal},i=await this.execute(o);if(i.isError)throw new Error(i.content);return i.content}}}});function ii(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}function $s(e={}){return({childExecutor:t,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:i})=>{let s={permissions:{allowedTools:o??nm},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...i===!0?{readOnlyBash:!0}:{}};return re(typeof r=="string"?r:void 0)==="openai-compatible"?new qt({...s,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new tt({...s,readOnlyMemory:!0})}}function pI(e,t){let n={allowedTools:[...am]};return re(typeof e=="string"?e:void 0)==="openai-compatible"?new qt({permissions:n,readOnlyBash:!0,readOnlyMemory:!0,...t!==void 0?{baseURL:t}:{}}):new tt({permissions:n,readOnlyBash:!0,readOnlyMemory:!0})}function Ds(e,t,n,r,o,i,s,a,l,c,d,u){let m=(p,g,h,y)=>{let b=y??s;return new Vn({parentSession:ii(h),defaultModel:e,...c!==void 0?{defaultSubagentModel:c}:{},apiKey:t,...r!==void 0?{baseUrl:r}:{},...u!==void 0?{openaiBaseUrl:u}:{},depth:p,maxDepth:g,childProviderFactory:n,childSkillExecutorFactory:m,...o!==void 0?{traceWriter:o}:{},...i!==void 0?{backgroundRegistry:i}:{},...b!==void 0?{cwd:b}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...l!==void 0?{surface:l}:{},...d!==void 0?{agentRegistry:d}:{}})};return m}function rm(e,t,n=!1,r){let o={allowedTools:[...e]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new qt({permissions:o,...n?{readOnlyBash:!0}:{},...r!==void 0?{baseURL:r}:{}}):new tt({permissions:o,...n?{readOnlyBash:!0}:{}})}function yI(e,t){let n={allowedTools:[...w_]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new qt({permissions:n}):new tt({permissions:n})}var si,nm,am,lm,Cn=R(()=>{"use strict";li();Jl();Je();ln();dn();Xl();ic();si=3;nm=[...$t,...st,"memory_search","agent","skill"],am=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...st,"memory_search","agent","skill"],lm=new Set(["ground-state"])});async function cm(e,t,n={}){if(!Number.isFinite(t)||t<=0)return e;let r,o=new Promise((i,s)=>{r=setTimeout(()=>{let a=n.label?` (${n.label})`:"",l=new tn(`Operation timed out after ${t}ms${a}`,t);n.controller&&!n.controller.signal.aborted&&n.controller.abort(l),s(l)},t)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}var bI,jw,Hw=R(()=>{"use strict";pt();bI=0,jw=5e3});var dm,wI=R(()=>{"use strict";ve();Hw();fr();hu();xe();Rt();dm=class{constructor(t,n,r,o,i,s,a,l,c,d,u,m,p,g,h){this.id=t;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=i;this.timeoutMs=s;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=g;this.onSubagentSucceeded=h;this.progressSink=m,this.parentId=p}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;lastStopInjectContext;progressSink;parentId;currentTrace=Zl();lastStreamedContent="";lastStopReason;get status(){return this.currentStatus}async run(t,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.lastStopReason=void 0,this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=cm(this.streamToFinalMessage(t,n),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=o;try{let i=await o;this.lastMessage=i.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",await No(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8"),...this.lastStopReason!==void 0&&{stopReason:this.lastStopReason}});let s=typeof i.metadata?.totalCostUsd=="number"?i.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,s),this.onTerminal(),i}catch(i){throw this.lastDurationMs=Date.now()-r,this.currentStatus!=="cancelled"&&(this.controller.signal.aborted?(await No(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(await No(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:i instanceof Error?i.constructor.name:"Unknown",errorMessage:i instanceof Error?i.message:String(i),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8")}),this.currentStatus="failed",this.latestTerminalStatus="failed")),this.onTerminal(),i}finally{this.inFlight=null}}async streamToFinalMessage(t,n){let r,o;this.lastStreamedContent="",this.currentTrace=Zl();let i=n??this.progressSink??an(),s={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let a of this.session.sendMessageStream(t)){if(i&&i(a,s),a.type==="chunk"){let l=a.chunk;l.type==="content"?this.lastStreamedContent+=l.content:l.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(this.currentTrace.thinkingPresent=!0)}if(a.type==="message")r=a.message,this.currentTrace.turnCount++;else if(a.type==="error"){o=a.error;break}else if(a.type==="done"){if(typeof a.metadata?.stopReason=="string"&&(this.lastStopReason=a.metadata.stopReason),typeof a.metadata?.usage=="object"&&a.metadata.usage!==null){let l=a.metadata.usage;this.currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}if(o)throw o;if(r)return r;if(this.lastStreamedContent.length>0)return this.lastStopReason??=Rw,{role:"assistant",content:this.lastStreamedContent,timestamp:new Date};if(this.lastStopReason==="tool_use_loop_capped")return{role:"assistant",content:`[subagent ${this.id} reached its tool-use iteration cap before producing a final message; returning a capped partial result]`,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(t,n){try{let r=await this.run(t,n);return B_(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace,this.lastStopReason)}catch(r){let o=Vp(this.id,this.currentStatus,r,this.currentTrace,this.lastStopReason);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(t,n,r){let o;if(r){let i=this.progressSink??an();o=(s,a)=>{r(s),i?.(s,a)}}this.runToResult(t,o).then(i=>{n?.(i)}).catch(i=>{W("runInBackground: unexpected rejection after runToResult",i),console.error("Subagent runInBackground failed unexpectedly:",i)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",No(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(t)}}async teardown(t){if(this.stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(n,t)}}getLastStopInjectContext(){return this.lastStopInjectContext}async dispatchStopAndRelease(t,n){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let r=await Ix(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:t,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs,trace:this.currentTrace},this.traceWriter?{traceWriter:this.traceWriter}:{});if(r.injectContext){if(this.parentAbortSignal?.aborted)W(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)this.lastStopInjectContext=r.injectContext;else if(this.parentInputStreamRef)try{let o=this.parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){W(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}this.onTerminal()}}});var ZY,QY,e4,dI,ie,Ke=R(()=>{"use strict";Cx();Fs();hu();xe();Bn();fr();Fy();Lx();Cn();Xp();Je();wI();ZY=async(e,t)=>({action:"decline"}),QY=50,e4=20*6e4,dI=60*6e4,ie=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentCwd;worktreeMainRootCache=new Map;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(t={}){if(this.parentCanUseTool=t.canUseTool,this.hookRegistry=t.hookRegistry,this.progressSink=t.progressSink,this.parentApiKey=t.apiKey,this.parentBaseUrl=t.baseUrl,this.parentProvider=t.parentModel!==void 0?re(t.parentModel):void 0,this.parentCwd=t.cwd,this.parentTraceWriter=t.traceWriter,this.parentSurface=t.surface,this.onSubagentSucceededCb=t.onSubagentSucceeded,this.abortGraph=new gu(t.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),t.parentAbortSignal){let n=t.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(t=>({id:t.id,status:t.status}))}get(t){return this.active.get(t)}onChildAborted(t){return this.abortGraph.onChildAborted(this.rootId,t)}setOnSubagentSucceeded(t){this.onSubagentSucceededCb=t}setCwd(t){this.parentCwd=t,this.worktreeMainRootCache.delete(t)}async resolveMainRootForCwd(t){if(this.worktreeMainRootCache.has(t))return this.worktreeMainRootCache.get(t);let n=await Fx(t);return this.worktreeMainRootCache.set(t,n),n}abortAll(t,n="user_signal"){this.abortGraph.abort(this.rootId,t,n)}async forkSubagent(t){if(t.phaseRole!==void 0&&t.phaseRole!=="read-write"&&t.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${t.phaseRole}" is mutually exclusive with config.provider. Remove one \u2014 either let the manager construct the phase-restricted provider, or use config.provider with phaseRole: "read-write" (default).`);let n=`${t.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=t.parent.sessionId,o=t.config.hookRegistry??this.hookRegistry??t.parent.hookRegistry,i=t.config.traceWriter??this.parentTraceWriter;o&&await _x(o,{event:"SubagentStart",subagentId:n,parentSessionId:t.parent.sessionId},{signal:this.rootController.signal,...i?{traceWriter:i}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let a=t.config.cwd??this.parentCwd,l;if(t.config.readRoots===void 0&&a!==void 0){let v=await this.resolveMainRootForCwd(a);v!==void 0&&v!==a&&(l=[a,v])}let c;if(t.config.writeRoots!==void 0&&t.config.writeRoots.length>0){let v=a!==void 0?[a]:[];c=[...new Set([...v,...t.config.writeRoots])]}let d={...t.config,resume:r,forkSession:r?!0:t.config.forkSession,abortSignal:s.signal,apiKey:H_({childModel:t.config.model,configApiKey:t.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:t.config.baseUrl??(re(t.config.model)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:t.config.isNonInteractive??!0,maxToolUseIterations:t.config.maxToolUseIterations??QY,autoResumeOnUsageLimit:t.config.autoResumeOnUsageLimit??!1,...t.config.parentSessionId===void 0&&t.parent.sessionId!==void 0?{parentSessionId:t.parent.sessionId}:{},...t.config.phaseRole===void 0&&t.phaseRole!==void 0?{phaseRole:t.phaseRole}:{},...t.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...l!==void 0?{readRoots:l}:{},...c!==void 0?{writeRoots:c}:{},...t.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...t.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!1?{}:{onElicitation:ZY},...t.phaseRole==="read-only"?{provider:yI("read-only",t.config.model)}:{}};d.cwd!==void 0&&Dx(d.cwd);let u;try{u=new Ct(d)}catch(v){throw this.abortGraph.dispose(n),v}let m=t.parent.getInputStreamRef?.(),p=t.parent.abortSignal,g=this.progressSink??an(),h=t.agentType?.trim()||void 0,y=t.parentId?.trim()||void 0,b=new dm(n,u,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??e4,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},m,p,h??t.idPrefix,g,y??t.parent.sessionId,i,this.onSubagentSucceededCb);this.active.set(n,b);let w=typeof t.config.model=="string"?t.config.model:JSON.stringify(t.config.model);return No(i,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:w,...d.tools?.allowedTools?{allowedTools:[...d.tools.allowedTools]}:{}}),await Ne({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:w,parent_session_id:t.parent.sessionId}),b}async kill(t){let n=this.active.get(t);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(t=>t.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(t=>t.teardown()))}}});async function SI(e,t={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=8}=t;if(e.length===0)return[];let i=new Array(e.length),s=new Set(e.map((l,c)=>c)),a=!1;return await ps(e.map((l,c)=>c),o,async l=>{let c=e[l];n&&a&&await c.handle.cancel().catch(()=>{});let d=await c.handle.runToResult(c.prompt);if(i[l]=d,s.delete(l),n&&d.status!=="succeeded"){a=!0;for(let u of s){let m=e[u];m&&m.handle.status==="running"&&m.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(e.map(l=>l.handle.teardown())),i}var vI=R(()=>{"use strict";ku()});function kI(e){let t=new Set;for(let n of e){let r=ec(n,t4);r!==void 0&&t.add(r)}return t}var t4,EI=R(()=>{"use strict";tc();ln();Du();t4=new Set([...$t,...st,"memory_search","agent","skill"])});import{existsSync as xI,mkdirSync as n4,readFileSync as r4,renameSync as o4,writeFileSync as i4,unlinkSync as s4}from"fs";import{dirname as TI,join as a4}from"path";import{randomBytes as l4}from"crypto";function Ae(e=pe()){if(!xI(e))return um();try{let t=r4(e,"utf8"),n=JSON.parse(t);if(!n||typeof n!="object")return um();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let i=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:i}}return um()}catch{return um()}}function ac(e,t=pe()){n4(TI(t),{recursive:!0});let n=a4(TI(t),`.index.json.${process.pid}.${l4(4).toString("hex")}.tmp`),r=JSON.stringify(e,null,2);try{i4(n,r,"utf8"),o4(n,t)}catch(o){try{xI(n)&&s4(n)}catch{}throw o}}function lo(e,t,n=pe()){let r=Ae(n);return r.plugins[e]=t,ac(r,n),r}function RI(e,t=pe()){let n=Ae(t);return e in n.plugins&&(delete n.plugins[e],ac(n,t)),n}function Kw(e,t,n=pe()){let r=Ae(n),o=r.plugins[e];if(!o)throw new Error(`plugin "${e}" is not in the index`);return o.enabled=t,o.updatedAt=new Date().toISOString(),ac(r,n),r}function lc(e,t,n=pe()){let r=Ae(n);return r.marketplaces[e]=t,ac(r,n),r}function CI(e,t=pe()){let n=Ae(t),r=!1;e in n.marketplaces&&(delete n.marketplaces[e],r=!0);for(let[o,i]of Object.entries(n.plugins))i.marketplace===e&&(delete n.plugins[o],r=!0);return r&&ac(n,t),n}function um(){return{version:2,plugins:{},marketplaces:{}}}var zt=R(()=>{"use strict";G()});import{existsSync as qw,readFileSync as II,readdirSync as c4,realpathSync as d4,statSync as u4}from"fs";import{join as Ns,resolve as AI}from"path";function kr(){Ls=void 0}function Er(e=Qe(),t={}){let n=t.trustAll===!0,r=n?`${e}\0trustAll`:e;Ls||(Ls=new Map);let o=Ls.get(r);if(o)return[...o];if(!qw(e))return Ls.set(r,[]),[];let i=e===Qe()?pe():Ns(e,".index.json"),s=Ae(i),a=[];return PI(e,e,0,a,new Set,s.plugins,n),Ls.set(r,a),[...a]}function PI(e,t,n,r,o,i,s){if(n>p4)return;let a;try{a=d4(t)}catch{a=t}if(o.has(a))return;if(o.add(a),qw(Ns(t,".claude-plugin","plugin.json"))){let c=zw(e,t);if(c===null){Gw(r,t);return}if(c.layout==="cache"){if(!s){let u=i[c.key];if(!u||u.enabled===!1)return}Gw(r,t);return}let d=i[c.key];if(d&&d.enabled===!1)return;Gw(r,t);return}let l;try{l=c4(t)}catch{return}for(let c of l){if(c.startsWith("."))continue;let d=Ns(t,c),u;try{u=u4(d)}catch{continue}u.isDirectory()&&PI(e,d,n+1,r,o,i,s)}}function m4(e){try{let t=II(Ns(e,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(t);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function Gw(e,t){let n=m4(t);e.push(n!==void 0?{type:"local",path:t,main:n}:{type:"local",path:t})}function zw(e,t){if(!t.startsWith(e))return null;let n=t.slice(e.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(i=>i.length>0);if(r.length===0)return null;if(r[0]===_I&&r.length>=3){let i=r[1];if(i){let s=Ns(e,_I,i),l=f4(s,t)??r[2];if(l)return{layout:"cache",key:`${i}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function f4(e,t){let n=Ns(e,".claude-plugin","marketplace.json");if(!qw(n))return null;let r;try{r=JSON.parse(II(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let i=AI(t);for(let s of o){if(!s||typeof s!="object")continue;let a=s;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&AI(e,a.source)===i)return a.name}return null}var p4,_I,Ls,co=R(()=>{"use strict";G();zt();p4=5,_I="cache"});import{existsSync as uo,readdirSync as g4,readFileSync as h4}from"fs";import{join as Tr}from"path";function OI(e=_e()){let t=[],n=Tr(e,"skills");if(uo(n))for(let r of pm(n)){let o=Tr(n,r,"SKILL.md");uo(o)&&t.push({path:o,type:"skill",source:"user"})}for(let r of MI){let o=Tr(e,`${r}s`);if(uo(o))for(let i of pm(o))i.endsWith(".md")&&t.push({path:Tr(o,i),type:r,source:"user"})}return t}function $I(e=Qe()){if(!uo(e))return[];let t=[],n=Er(e);for(let r of n){let i=zw(e,r.path)?.key,s=Tr(r.path,"skills");if(uo(s))for(let a of pm(s)){let l=Tr(s,a,"SKILL.md");if(!uo(l))continue;let c={path:l,type:"skill",source:"plugin"};i&&(c.plugin_key=i),t.push(c)}for(let a of MI){let l=Tr(r.path,`${a}s`);if(uo(l))for(let c of pm(l)){if(!c.endsWith(".md"))continue;let d={path:Tr(l,c),type:a,source:"plugin"};i&&(d.plugin_key=i),t.push(d)}}}return t}function DI(e=Tr(_e(),"settings.json")){if(!uo(e))return[];try{let t=h4(e,"utf8"),r=JSON.parse(t).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[i,s]of Object.entries(r))if(Array.isArray(s))for(let a=0;a<s.length;a++)o.push({event:i,index:a,raw:s[a]});return o}catch{return[]}}function pm(e){try{return g4(e).filter(t=>!t.startsWith("."))}catch{return[]}}var MI,FI=R(()=>{"use strict";G();co();MI=["command","agent"]});import{z as Be}from"zod";import{mkdir as LI,appendFile as NI}from"fs/promises";import{join as Jw}from"path";function w4(e){return{runUserDiscovery:e!=="plugin",runPluginDiscovery:e!=="user",runHookInspector:e!=="plugin"}}function S4(e){let t=()=>{let i={};for(let s of jI)i[s]={correct:0,misfit:0,outlier:0};return i},n={user:t(),plugin:t()};for(let i of e)n[i.source][i.type][i.verdict]+=1;let r={high:0,med:1,low:2},o=e.filter(i=>i.verdict==="misfit").slice().sort((i,s)=>r[i.confidence]-r[s.confidence]);return{inventory:n,misfits:o}}function v4(e){return e.verdict==="misfit"&&e.confidence==="high"&&e.source==="user"}function k4(e){let t=e.filter(o=>o.source==="user"),n=e.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),t.length===0)r.push("(none discovered)");else for(let o of t)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let i=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${i})`)}return r.join(`
1071
+ ${g.partialOutput}`},m):(m={content:g.error?.message??c,isError:!0},m)}catch(p){let g=p instanceof Error?p.message:String(p);return{content:`${d}: ${g}`,isError:!0}}finally{u&&await u.teardown({deferInjectContextToCaller:!0}).catch(W);let p=u?.getLastStopInjectContext?.();Yp(m,p),await r?.teardownAll(),await n.teardownAll()}}var hI=R(()=>{"use strict";Ke();Rt();Cw();Cn();Xp();Nt();fr();on();ve();uI();Tw()});function YY(e){if(typeof e!="object"||e===null)return;let t=e.name;if(typeof t!="string")return;let n=t.trim();return n.length>0?n:void 0}function XY(e){if(typeof e!="object"||e===null)throw new Error("Skill tool input must be an object");let t=e,n=t.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=t.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var Vn,ic=R(()=>{"use strict";Ot();Gn();Cn();bw();Bn();ww();kw();Ew();Tw();hI();Vn=class{constructor(t){this.ctx=t;this.currentCwd=t.cwd}ctx;pluginBodies=null;currentCwd;setCwd(t){this.currentCwd=t,this.pluginBodies=null}internals(){return{ctx:this.ctx,currentCwd:this.currentCwd}}async execute(t){if(t.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??si;if(n>=r){let c=YY(t.input);return Ne({...As(this.ctx),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:c}).catch(()=>{}),{content:Gp(n,r),isError:!0}}let o;try{o=XY(t.input)}catch(c){return{content:`Skill tool input validation failed: ${c instanceof Error?c.message:String(c)}`,isError:!0}}let i;try{i=Ve(o.name)}catch{}if(i)return await this.executeRegistrySkill(i,o.arguments,t);let s=this.getPluginSkillBody(o.name);if(s){if(s.context==="fork"){let d=s.readOnly===!0||lm.has(o.name);return await fI(this.internals(),o.name,s.body,s.pluginPath,o.arguments,t,d,s.allowedTools)}let c=s.body.replace(/\$\{PLUGIN_ROOT(?::-(?:[^{}]|\$\{[^{}]*\})*)?\}|\$PLUGIN_ROOT\b/g,()=>s.pluginPath);return O_(this.internals(),o.name,c,o.arguments,t)}let l=ai(this.ctx.pluginConfigs,this.currentCwd!==void 0?{cwd:this.currentCwd}:void 0).map(c=>c.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${l||"(none)"}`,isError:!0}}async executeRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(t.context==="fork")return mI(this.internals(),t,n,r);if(t.context==="load")return M_(this.internals(),t,n,r);let o=k_(t.name);o&&A_(t.name);let i=this.ctx.depth??0;Ne({...As(this.ctx),event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:i,...qp(t.name)?{is_gate:!0}:{},...t.model!==void 0?{model:t.model}:{}}).catch(()=>{});let s=Date.now(),a,l;try{l=await t.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r),...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}})}catch(d){a=d}finally{let d=Date.now()-s;o&&C_({skillName:t.name,durationMs:d,...a!==void 0?{isError:!0}:{}});let u=a!==void 0?a instanceof Error?a.message:String(a):void 0,m=a===void 0?typeof l=="string"?l.length:l!=null?JSON.stringify(l).length:0:void 0;Ne({...As(this.ctx),event:"skill.completed",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:d,depth:i,...m!==void 0?{content_chars:m}:{},...u!==void 0?{error_message:__(u)}:{},...t.model!==void 0?{model:t.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof l=="string"?l:l!=null?JSON.stringify(l):"Skill completed successfully."}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=sc(this.ctx.pluginConfigs,this.currentCwd!==void 0?{cwd:this.currentCwd}:void 0)),this.pluginBodies.get(t)}createDispatchSkillCallback(t){return async(n,r)=>{let o={id:`${t.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:t.signal},i=await this.execute(o);if(i.isError)throw new Error(i.content);return i.content}}}});function ii(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}function $s(e={}){return({childExecutor:t,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:i})=>{let s={permissions:{allowedTools:o??nm},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...i===!0?{readOnlyBash:!0}:{}};return re(typeof r=="string"?r:void 0)==="openai-compatible"?new qt({...s,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new tt({...s,readOnlyMemory:!0})}}function pI(e,t){let n={allowedTools:[...am]};return re(typeof e=="string"?e:void 0)==="openai-compatible"?new qt({permissions:n,readOnlyBash:!0,readOnlyMemory:!0,...t!==void 0?{baseURL:t}:{}}):new tt({permissions:n,readOnlyBash:!0,readOnlyMemory:!0})}function Ds(e,t,n,r,o,i,s,a,l,c,d,u){let m=(p,g,h,y)=>{let b=y??s;return new Vn({parentSession:ii(h),defaultModel:e,...c!==void 0?{defaultSubagentModel:c}:{},apiKey:t,...r!==void 0?{baseUrl:r}:{},...u!==void 0?{openaiBaseUrl:u}:{},depth:p,maxDepth:g,childProviderFactory:n,childSkillExecutorFactory:m,...o!==void 0?{traceWriter:o}:{},...i!==void 0?{backgroundRegistry:i}:{},...b!==void 0?{cwd:b}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...l!==void 0?{surface:l}:{},...d!==void 0?{agentRegistry:d}:{}})};return m}function rm(e,t,n=!1,r){let o={allowedTools:[...e]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new qt({permissions:o,...n?{readOnlyBash:!0}:{},...r!==void 0?{baseURL:r}:{}}):new tt({permissions:o,...n?{readOnlyBash:!0}:{}})}function yI(e,t){let n={allowedTools:[...w_]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new qt({permissions:n}):new tt({permissions:n})}var si,nm,am,lm,Cn=R(()=>{"use strict";li();Jl();Je();ln();dn();Xl();ic();si=3;nm=[...$t,...st,"memory_search","agent","skill"],am=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...st,"memory_search","agent","skill"],lm=new Set(["ground-state"])});async function cm(e,t,n={}){if(!Number.isFinite(t)||t<=0)return e;let r,o=new Promise((i,s)=>{r=setTimeout(()=>{let a=n.label?` (${n.label})`:"",l=new tn(`Operation timed out after ${t}ms${a}`,t);n.controller&&!n.controller.signal.aborted&&n.controller.abort(l),s(l)},t)});try{return await Promise.race([e,o])}finally{r!==void 0&&clearTimeout(r)}}var bI,jw,Hw=R(()=>{"use strict";pt();bI=0,jw=5e3});var dm,wI=R(()=>{"use strict";ve();Hw();fr();hu();xe();Rt();dm=class{constructor(t,n,r,o,i,s,a,l,c,d,u,m,p,g,h){this.id=t;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=i;this.timeoutMs=s;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=g;this.onSubagentSucceeded=h;this.progressSink=m,this.parentId=p}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;lastStopInjectContext;progressSink;parentId;currentTrace=Zl();lastStreamedContent="";lastStopReason;get status(){return this.currentStatus}async run(t,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.lastStopReason=void 0,this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=cm(this.streamToFinalMessage(t,n),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=o;try{let i=await o;this.lastMessage=i.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",await No(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8"),...this.lastStopReason!==void 0&&{stopReason:this.lastStopReason}});let s=typeof i.metadata?.totalCostUsd=="number"?i.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,s),this.onTerminal(),i}catch(i){throw this.lastDurationMs=Date.now()-r,this.currentStatus!=="cancelled"&&(this.controller.signal.aborted?(await No(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(await No(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:i instanceof Error?i.constructor.name:"Unknown",errorMessage:i instanceof Error?i.message:String(i),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8")}),this.currentStatus="failed",this.latestTerminalStatus="failed")),this.onTerminal(),i}finally{this.inFlight=null}}async streamToFinalMessage(t,n){let r,o;this.lastStreamedContent="",this.currentTrace=Zl();let i=n??this.progressSink??an(),s={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}};for await(let a of this.session.sendMessageStream(t)){if(i&&i(a,s),a.type==="chunk"){let l=a.chunk;l.type==="content"?this.lastStreamedContent+=l.content:l.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(this.currentTrace.thinkingPresent=!0)}if(a.type==="message")r=a.message,this.currentTrace.turnCount++;else if(a.type==="error"){o=a.error;break}else if(a.type==="done"){if(typeof a.metadata?.stopReason=="string"&&(this.lastStopReason=a.metadata.stopReason),typeof a.metadata?.usage=="object"&&a.metadata.usage!==null){let l=a.metadata.usage;this.currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}if(o)throw o;if(r)return r;if(this.lastStreamedContent.length>0)return this.lastStopReason??=Rw,{role:"assistant",content:this.lastStreamedContent,timestamp:new Date};if(this.lastStopReason==="tool_use_loop_capped")return{role:"assistant",content:`[subagent ${this.id} reached its tool-use iteration cap before producing a final message; returning a capped partial result]`,timestamp:new Date};throw new Error(`Subagent ${this.id} produced no terminal message`)}async runToResult(t,n){try{let r=await this.run(t,n);return B_(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace,this.lastStopReason)}catch(r){let o=Vp(this.id,this.currentStatus,r,this.currentTrace,this.lastStopReason);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(t,n,r){let o;if(r){let i=this.progressSink??an();o=(s,a)=>{r(s),i?.(s,a)}}this.runToResult(t,o).then(i=>{n?.(i)}).catch(i=>{W("runInBackground: unexpected rejection after runToResult",i),console.error("Subagent runInBackground failed unexpectedly:",i)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",No(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(t)}}async teardown(t){if(this.stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(n,t)}}getLastStopInjectContext(){return this.lastStopInjectContext}async dispatchStopAndRelease(t,n){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let r=await Ix(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:t,lastMessage:this.lastMessage,agentType:this.agentType,durationMs:this.lastDurationMs,trace:this.currentTrace},this.traceWriter?{traceWriter:this.traceWriter}:{});if(r.injectContext){if(this.parentAbortSignal?.aborted)W(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)this.lastStopInjectContext=r.injectContext;else if(this.parentInputStreamRef)try{let o=this.parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){W(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}this.onTerminal()}}});var ZY,QY,e4,dI,ie,Ke=R(()=>{"use strict";Cx();Fs();hu();xe();Bn();fr();Fy();Lx();Cn();Xp();Je();wI();ZY=async(e,t)=>({action:"decline"}),QY=50,e4=20*6e4,dI=60*6e4,ie=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentCwd;worktreeMainRootCache=new Map;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(t={}){if(this.parentCanUseTool=t.canUseTool,this.hookRegistry=t.hookRegistry,this.progressSink=t.progressSink,this.parentApiKey=t.apiKey,this.parentBaseUrl=t.baseUrl,this.parentProvider=t.parentModel!==void 0?re(t.parentModel):void 0,this.parentCwd=t.cwd,this.parentTraceWriter=t.traceWriter,this.parentSurface=t.surface,this.onSubagentSucceededCb=t.onSubagentSucceeded,this.abortGraph=new gu(t.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),t.parentAbortSignal){let n=t.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(t=>({id:t.id,status:t.status}))}get(t){return this.active.get(t)}onChildAborted(t){return this.abortGraph.onChildAborted(this.rootId,t)}setOnSubagentSucceeded(t){this.onSubagentSucceededCb=t}setCwd(t){this.parentCwd=t,this.worktreeMainRootCache.delete(t)}async resolveMainRootForCwd(t){if(this.worktreeMainRootCache.has(t))return this.worktreeMainRootCache.get(t);let n=await Fx(t);return this.worktreeMainRootCache.set(t,n),n}abortAll(t,n="user_signal"){this.abortGraph.abort(this.rootId,t,n)}async forkSubagent(t){if(t.phaseRole!==void 0&&t.phaseRole!=="read-write"&&t.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${t.phaseRole}" is mutually exclusive with config.provider. Remove one \u2014 either let the manager construct the phase-restricted provider, or use config.provider with phaseRole: "read-write" (default).`);let n=`${t.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=t.parent.sessionId,o=t.config.hookRegistry??this.hookRegistry??t.parent.hookRegistry,i=t.config.traceWriter??this.parentTraceWriter;o&&await _x(o,{event:"SubagentStart",subagentId:n,parentSessionId:t.parent.sessionId},{signal:this.rootController.signal,...i?{traceWriter:i}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let a=t.config.cwd??this.parentCwd,l;if(t.config.readRoots===void 0&&a!==void 0){let v=await this.resolveMainRootForCwd(a);v!==void 0&&v!==a&&(l=[a,v])}let c;if(t.config.writeRoots!==void 0&&t.config.writeRoots.length>0){let v=a!==void 0?[a]:[];c=[...new Set([...v,...t.config.writeRoots])]}let d={...t.config,resume:r,forkSession:r?!0:t.config.forkSession,abortSignal:s.signal,apiKey:H_({childModel:t.config.model,configApiKey:t.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:t.config.baseUrl??(re(t.config.model)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:t.config.isNonInteractive??!0,maxToolUseIterations:t.config.maxToolUseIterations??QY,autoResumeOnUsageLimit:t.config.autoResumeOnUsageLimit??!1,...t.config.parentSessionId===void 0&&t.parent.sessionId!==void 0?{parentSessionId:t.parent.sessionId}:{},...t.config.phaseRole===void 0&&t.phaseRole!==void 0?{phaseRole:t.phaseRole}:{},...t.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...l!==void 0?{readRoots:l}:{},...c!==void 0?{writeRoots:c}:{},...t.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...t.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!1?{}:{onElicitation:ZY},...t.phaseRole==="read-only"?{provider:yI("read-only",t.config.model)}:{}};d.cwd!==void 0&&Dx(d.cwd);let u;try{u=new Ct(d)}catch(v){throw this.abortGraph.dispose(n),v}let m=t.parent.getInputStreamRef?.(),p=t.parent.abortSignal,g=this.progressSink??an(),h=t.agentType?.trim()||void 0,y=t.parentId?.trim()||void 0,b=new dm(n,u,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??e4,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},m,p,h??t.idPrefix,g,y??t.parent.sessionId,i,this.onSubagentSucceededCb);this.active.set(n,b);let w=typeof t.config.model=="string"?t.config.model:JSON.stringify(t.config.model);return No(i,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:w,...d.tools?.allowedTools?{allowedTools:[...d.tools.allowedTools]}:{}}),await Ne({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:w,parent_session_id:t.parent.sessionId}),b}async kill(t){let n=this.active.get(t);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(t=>t.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(t=>t.teardown()))}}});async function SI(e,t={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=8}=t;if(e.length===0)return[];let i=new Array(e.length),s=new Set(e.map((l,c)=>c)),a=!1;return await ps(e.map((l,c)=>c),o,async l=>{let c=e[l];n&&a&&await c.handle.cancel().catch(()=>{});let d=await c.handle.runToResult(c.prompt);if(i[l]=d,s.delete(l),n&&d.status!=="succeeded"){a=!0;for(let u of s){let m=e[u];m&&m.handle.status==="running"&&m.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(e.map(l=>l.handle.teardown())),i}var vI=R(()=>{"use strict";ku()});function kI(e){let t=new Set;for(let n of e){let r=ec(n,t4);r!==void 0&&t.add(r)}return t}var t4,EI=R(()=>{"use strict";tc();ln();Du();t4=new Set([...$t,...st,"memory_search","agent","skill"])});import{existsSync as xI,mkdirSync as n4,readFileSync as r4,renameSync as o4,writeFileSync as i4,unlinkSync as s4}from"fs";import{dirname as TI,join as a4}from"path";import{randomBytes as l4}from"crypto";function Ae(e=pe()){if(!xI(e))return um();try{let t=r4(e,"utf8"),n=JSON.parse(t);if(!n||typeof n!="object")return um();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let i=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:i}}return um()}catch{return um()}}function ac(e,t=pe()){n4(TI(t),{recursive:!0});let n=a4(TI(t),`.index.json.${process.pid}.${l4(4).toString("hex")}.tmp`),r=JSON.stringify(e,null,2);try{i4(n,r,"utf8"),o4(n,t)}catch(o){try{xI(n)&&s4(n)}catch{}throw o}}function lo(e,t,n=pe()){let r=Ae(n);return r.plugins[e]=t,ac(r,n),r}function RI(e,t=pe()){let n=Ae(t);return e in n.plugins&&(delete n.plugins[e],ac(n,t)),n}function Kw(e,t,n=pe()){let r=Ae(n),o=r.plugins[e];if(!o)throw new Error(`plugin "${e}" is not in the index`);return o.enabled=t,o.updatedAt=new Date().toISOString(),ac(r,n),r}function lc(e,t,n=pe()){let r=Ae(n);return r.marketplaces[e]=t,ac(r,n),r}function CI(e,t=pe()){let n=Ae(t),r=!1;e in n.marketplaces&&(delete n.marketplaces[e],r=!0);for(let[o,i]of Object.entries(n.plugins))i.marketplace===e&&(delete n.plugins[o],r=!0);return r&&ac(n,t),n}function um(){return{version:2,plugins:{},marketplaces:{}}}var zt=R(()=>{"use strict";G()});import{existsSync as qw,readFileSync as II,readdirSync as c4,realpathSync as d4,statSync as u4}from"fs";import{join as Ns,resolve as AI}from"path";function kr(){Ls=void 0}function Er(e=Qe(),t={}){let n=t.trustAll===!0,r=n?`${e}\0trustAll`:e;Ls||(Ls=new Map);let o=Ls.get(r);if(o)return[...o];if(!qw(e))return Ls.set(r,[]),[];let i=e===Qe()?pe():Ns(e,".index.json"),s=Ae(i),a=[];return PI(e,e,0,a,new Set,s.plugins,n),Ls.set(r,a),[...a]}function PI(e,t,n,r,o,i,s){if(n>p4)return;let a;try{a=d4(t)}catch{a=t}if(o.has(a))return;if(o.add(a),qw(Ns(t,".claude-plugin","plugin.json"))){let c=zw(e,t);if(c===null){Gw(r,t);return}if(c.layout==="cache"){if(!s){let u=i[c.key];if(!u||u.enabled===!1)return}Gw(r,t);return}let d=i[c.key];if(d&&d.enabled===!1)return;Gw(r,t);return}let l;try{l=c4(t)}catch{return}for(let c of l){if(c.startsWith("."))continue;let d=Ns(t,c),u;try{u=u4(d)}catch{continue}u.isDirectory()&&PI(e,d,n+1,r,o,i,s)}}function m4(e){try{let t=II(Ns(e,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(t);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function Gw(e,t){let n=m4(t);e.push(n!==void 0?{type:"local",path:t,main:n}:{type:"local",path:t})}function zw(e,t){if(!t.startsWith(e))return null;let n=t.slice(e.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(i=>i.length>0);if(r.length===0)return null;if(r[0]===_I&&r.length>=3){let i=r[1];if(i){let s=Ns(e,_I,i),l=f4(s,t)??r[2];if(l)return{layout:"cache",key:`${i}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function f4(e,t){let n=Ns(e,".claude-plugin","marketplace.json");if(!qw(n))return null;let r;try{r=JSON.parse(II(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let i=AI(t);for(let s of o){if(!s||typeof s!="object")continue;let a=s;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&AI(e,a.source)===i)return a.name}return null}var p4,_I,Ls,co=R(()=>{"use strict";G();zt();p4=5,_I="cache"});import{existsSync as uo,readdirSync as g4,readFileSync as h4}from"fs";import{join as Tr}from"path";function OI(e=_e()){let t=[],n=Tr(e,"skills");if(uo(n))for(let r of pm(n)){let o=Tr(n,r,"SKILL.md");uo(o)&&t.push({path:o,type:"skill",source:"user"})}for(let r of MI){let o=Tr(e,`${r}s`);if(uo(o))for(let i of pm(o))i.endsWith(".md")&&t.push({path:Tr(o,i),type:r,source:"user"})}return t}function $I(e=Qe()){if(!uo(e))return[];let t=[],n=Er(e);for(let r of n){let i=zw(e,r.path)?.key,s=Tr(r.path,"skills");if(uo(s))for(let a of pm(s)){let l=Tr(s,a,"SKILL.md");if(!uo(l))continue;let c={path:l,type:"skill",source:"plugin"};i&&(c.plugin_key=i),t.push(c)}for(let a of MI){let l=Tr(r.path,`${a}s`);if(uo(l))for(let c of pm(l)){if(!c.endsWith(".md"))continue;let d={path:Tr(l,c),type:a,source:"plugin"};i&&(d.plugin_key=i),t.push(d)}}}return t}function DI(e=Tr(_e(),"settings.json")){if(!uo(e))return[];try{let t=h4(e,"utf8"),r=JSON.parse(t).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[i,s]of Object.entries(r))if(Array.isArray(s))for(let a=0;a<s.length;a++)o.push({event:i,index:a,raw:s[a]});return o}catch{return[]}}function pm(e){try{return g4(e).filter(t=>!t.startsWith("."))}catch{return[]}}var MI,FI=R(()=>{"use strict";G();co();MI=["command","agent"]});import{z as Be}from"zod";import{mkdir as LI,appendFile as NI}from"fs/promises";import{join as Jw}from"path";function w4(e){return{runUserDiscovery:e!=="plugin",runPluginDiscovery:e!=="user",runHookInspector:e!=="plugin"}}function S4(e){let t=()=>{let i={};for(let s of jI)i[s]={correct:0,misfit:0,outlier:0};return i},n={user:t(),plugin:t()};for(let i of e)n[i.source][i.type][i.verdict]+=1;let r={high:0,med:1,low:2},o=e.filter(i=>i.verdict==="misfit").slice().sort((i,s)=>r[i.confidence]-r[s.confidence]);return{inventory:n,misfits:o}}function v4(e){return e.verdict==="misfit"&&e.confidence==="high"&&e.source==="user"}function k4(e){let t=e.filter(o=>o.source==="user"),n=e.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),t.length===0)r.push("(none discovered)");else for(let o of t)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let i=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${i})`)}return r.join(`
1072
1072
  `)}function E4(e,t){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${e}\``),n.push(""),t.length===0)return n.push("(no hooks discovered)"),n.join(`
1073
1073
  `);for(let r of t){let o=`${r.event}-${r.index}`;n.push(`### Hook \`${o}\``),n.push(""),n.push("```json"),n.push(JSON.stringify(r.raw,null,2)),n.push("```"),n.push("")}return n.join(`
1074
1074
  `)}function T4(e,t){if(!t)return{kind:"failure",message:`${e}: no result`};if(t.schemaError)return{kind:"failure",message:`${e}: schema mismatch \u2014 ${t.schemaError.message}`};if(t.status!=="succeeded"){let n=t.error?` \u2014 ${t.error.message}`:"";return{kind:"failure",message:`${e}: ${t.status}${n}`}}return t.output?{kind:"success",output:t.output}:{kind:"failure",message:`${e}: no output`}}async function x4(e,t,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",i=n?.callId,s=typeof e=="object"&&e!==null?e:{},a=y4.parse(s),l=a.writeBriefs??!0,c=a.scope??"all",d=w4(c);if(!t?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let u=t.sessionId,m=je("audit-fit"),p={skill:m["01-skill-inspector.md"],command:m["02-command-inspector.md"],agent:m["03-agent-inspector.md"],hook:m["04-hook-inspector.md"]};for(let F of jI)if(!p[F])throw new Error(`audit-fit skill missing inspector prompt for ${F}`);let g=d.runUserDiscovery?OI():[],h=d.runPluginDiscovery?$I():[],y={skill:[],command:[],agent:[]};for(let F of[...g,...h])y[F.type].push(F);let b=new ie({apiKey:r,...n?.defaultModel!==void 0?{parentModel:n.defaultModel}:{},...n?.traceWriter!==void 0?{traceWriter:n.traceWriter}:{}}),w=kI(io.allowedTools),v=()=>async F=>w.has(F)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${F} not allowed for audit-fit inspectors. Allowed tools: ${[...w].join(", ")}`},S=[];for(let F of b4){let U=y[F];if(U.length===0)continue;let H=p[F];H&&S.push({type:F,prompt:`${H}
@@ -1769,7 +1769,7 @@ ${t.partialOutput}`:"";return`Subagent failed \u2014 ${r}${o}`}let n=t.message?.
1769
1769
  ${S}${w}
1770
1770
  ${v}
1771
1771
  ${S}`})}return{fileBlocks:a,warnings:l}}async function VN(e,t,n,r,o="summary",i,s){let a=WD(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0);let l="",c=0,d=!1,u=!1,m=!1,p=!1,g,h=!1,y=!1,b={abort:null},w=0,v=3e3,S=[],E=new Map,x=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,C=()=>{let D=r.subagentControl;D?.hasPromotableForeground()&&D.promoteActiveForeground().then(F=>{for(let U of F)(i??{fn:console.log}).fn(f.dim(` \u2192 subagent backgrounded as ${U.jobId}: ${U.label}`))}).catch(()=>{})},A=r.getCompositor?r.getCompositor():null,N=()=>new Ia({out:Pa(i),thinkingMode:o,...x?{activeSkillName:x}:{},onCancel:()=>{t.interrupt().catch(D=>{We()&&console.error(" "+f.error("session.interrupt() failed:"),D)})},...r.subagentControl?{onBackground:C}:{},...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}:{}}),$=N(),I=async()=>{if(!m){m=!0;try{await $.dispose()}catch{}}},_=async()=>{await $.arm();let D=$.getCompositor();if(i&&D){let F=D;i.fn=U=>F.commitAbove(U),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(D),r.setInterruptNotifier?.(F=>$.setInterrupting(F)),r.rearmStatus?.()};try{A?A.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{h=!0,t.interrupt().catch(M=>{We()&&console.error(" "+f.error("soft-stop session.interrupt() failed:"),M)});let P=r.subagentControl;P?.hasActiveForeground()&&P.cancelActiveForeground().catch(M=>{We()&&console.error(" "+f.error("soft-stop cancelActiveForeground() failed:"),M)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{y=!0,t.interrupt().catch(P=>{We()&&console.error(" "+f.error("pause-interrupt session.interrupt() failed:"),P)})}),await _(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(C);let{fileBlocks:D,warnings:F}=JN(e.text,{rootDir:process.cwd()});for(let P of F)(i??{fn:console.log}).fn(f.dim(` @-file: ${P}`));let U=D.length>0||e.attachments.length>0?qN(e.text,e.attachments,void 0,D):e.text,H=t.sendMessageStream(U);if(await us((P,M)=>{$.process(P,M)},async()=>{for await(let P of H){if(h||y)break;if(P.type==="chunk"&&P.chunk.type==="content"?(l+=P.chunk.content,d=!0):P.type==="message"&&!d&&(l=P.message.content),P.type==="stream_retry"&&(l=l.slice(0,c)),P.type==="chunk"&&P.chunk.type==="tool_use_detail"){let M=P.chunk,O={toolName:M.toolName,toolUseId:M.toolUseId,input:M.toolInput,...M.toolInputRaw!==void 0&&{inputRaw:M.toolInputRaw}};E.set(M.toolUseId,O),S.push(O)}else if(P.type==="chunk"&&P.chunk.type==="tool_result"){let M=P.chunk;c=l.length;let O=E.get(M.toolUseId);if(O&&(O.result=M.content,O.isError=M.isError,E.delete(M.toolUseId)),r.onContextProgress){let j=Date.now();if(j-w>=v){w=j;try{let X=r.onContextProgress();X instanceof Promise&&await X}catch(X){We()&&console.error(" "+f.error("onContextProgress (status refresh) failed:"),X)}}}}if(P.type==="paused"){if(r.setPausedState?.(!0),await I(),A&&P.autoResume===!0){let M=new AbortController;b.abort=M;let O=P.resetsAt?P.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,j=O?`Keep waiting \u2014 auto-resumes at ${O}`:"Keep waiting \u2014 auto-resume in progress",X="Switch model / provider (type /model after)",ee="Stop waiting",te=[f.warning(" \u23F3 Usage limit reached.")+(O?f.dim(` Auto-resumes at ${O}.`):""),f.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];$g(A,{header:te,options:[j,X,ee],signal:M.signal,initialIndex:0}).then(ce=>{if(b.abort=null,!ce)return;let K=ce[0];K===void 0||K===j||(y=!0,K===X&&(i??{fn:console.log}).fn(f.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(Se=>{We()&&console.error(" "+f.error("picker pause-interrupt session.interrupt() failed:"),Se)}))}).catch(ce=>{We()&&console.error(" "+f.error("picker promise rejected:"),ce)})}else(i??{fn:console.log}).fn(mT({reason:P.reason,...P.resetsAt!==void 0?{resetsAt:P.resetsAt}:{},...P.accountId!==void 0?{accountId:P.accountId}:{},...P.autoResume!==void 0?{autoResume:P.autoResume}:{}}));continue}if(P.type==="resumed"){r.setPausedState?.(!1),b.abort?.abort(),b.abort=null;let M=P.hotSwapped&&P.accountId?`\u25B6 Resumed on ${P.accountId}`:"\u25B6 Resumed";l="",c=0,d=!1,S.length=0,E.clear(),p=!1,g=void 0,u=!1,$=N(),m=!1,await _(),(i??{fn:console.log}).fn(f.success(M));continue}if(P.type==="error"){await I(),zi(Wi(P.error)),u=!0;continue}$.process(P),P.type==="done"&&(p=!0,g=P.metadata)}}),await I(),h){let P=i?i.fn:console.log;P(f.warning("\u23F8 Stopped \u2014 work so far kept.")+f.dim(" Send a message to continue.")),P("")}if(y){let P=i?i.fn:console.log;P(f.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),P("")}if(p&&!h&&!y){di(n,a,l,g,S),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),fa(process.stdout);let P=O=>{i?i.fn(O):console.log(O)},M=KN(l);if(M){if(P(GN(M)),P(""),r.onTerminalState)try{r.onTerminalState(M)}catch{}if(n.permissionMode==="autonomous"){let O=M.kind==="done"&&du().verifyDone===!0&&!g$(S);y$(M,void 0,{unverified:O})}}if(sre(g,n,P),r.onAfterTurn){let O=r.onAfterTurn();O instanceof Promise&&await O.catch(()=>{})}}}catch(D){await I(),u||zi(Wi(D))}finally{await I(),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),b.abort?.abort(),b.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function sre(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(ge(e.durationMs)),e.totalCostUsd!==void 0&&r.push(lt(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(se(o+i)+" tok"),r.length>0&&n(f.dim(" \u25E6 "+r.join(" \xB7 ")));let s=GS(t),a=Gt(t.model);if(s>=1){let l=Math.round((s-1)*a),c=Math.round(a/1e3);n(f.error(` context OVER ${c}k tok by ~${se(l)} tok \u2014 model output may be silently truncated`))}else if(s>.5){let l=s>.8?f.error:f.warning;n(l(` context ${Math.round(s*100)}% used of ${se(a)}`))}n("")}var are=5e3,lre=3,cre="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function dre(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(f.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function YN(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,verdictLedger:d,shellPassthrough:u,bgResultNotifier:m}=s,p=null,g=[];e.session.current.waitForInitialization().then(async v=>{We()&&(p=Ef(v)),await Zc(e.session.current),We()&&(g=ek())}).catch(()=>{});let h=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,y=!1,b=!1,w=0;for(m.onInjectable=()=>{w>=lre||!o.isAwaitingInput()||!o.bufferIsEmpty()||(w++,fa(process.stdout),h={text:cre,attachments:[]},o.abortPendingRead())};;){if(p&&(e.replRenderer.writeLine(p),e.replRenderer.writeLine(""),p=null),g.length>0){for(let _ of g)e.replRenderer.writeLine(_);e.replRenderer.writeLine(""),g=[]}let v=u.drainNotifications();for(let{job:_,result:D}of v){let F=D.errorReason===void 0?"\u2713":"\u2717",U=D.errorReason==="abort"?"killed":D.errorReason==="timeout"?"timed out":D.errorReason==="signal-killed"?"killed by signal":`exit ${D.exitCode??0}`,H=Math.max(0,Math.round(D.durationMs/100)/10);e.replRenderer.writeLine(f.dim(` ${F} [${_.id}] ${U} \xB7 ${H}s \xB7 `)+_.command)}let S=m.drainNotifications();for(let{job:_}of S){let D=_.status==="completed"?"\u2713":_.status==="failed"?"\u2717":"\u2298",F=_.endedAt!==void 0?Math.max(0,Math.round((_.endedAt-_.startedAt)/100)/10):0,U=_.label.length>60?`${_.label.slice(0,60)}\u2026`:_.label;e.replRenderer.writeLine(f.dim(` ${D} [${_.jobId}] subagent ${_.status} \xB7 ${F}s \xB7 `)+U)}let E=l.renderIfChanged(e.stats.sessionId);if(E.length>0){for(let _ of E)e.replRenderer.writeLine(_);e.replRenderer.writeLine("")}let x,C;if(h===void 0){let _=await e.session.current.takePendingPlanExitSeed();_!==void 0&&(e.stats.permissionMode=_.mode,h={text:_.message,attachments:[]})}if(h!==void 0){let _=h;h=void 0;let D=Da(e.stats.permissionMode),F=bi({buffer:_.text,promptText:D,isTTY:!!process.stdout.isTTY,attachmentSummary:va([..._.attachments])});e.replRenderer.writeLine(F),x=_.text.trim(),C=_.attachments}else{let _=await o.readLine({promptFn:()=>Da(e.stats.permissionMode),onSigint:r,onShiftTab:()=>{Dg(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});x=_.text.trim(),C=_.attachments}if(!x&&C.length===0)continue;if(x.startsWith("!")){let _=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!_&&(y||(y=!0,e.replRenderer.writeLine(f.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(x))){e.statusLine.rearm();continue}}let A=!1;if(x.startsWith("/")){let _=await s$(x,e.slashCtx,C);if(_.handled){if(_.result==="exit"){e.rl.close();return}if((x==="/clear"||x.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(f.dim(` transcript: ${t.path()}`)),d.reset()),_.result!==null&&typeof _.result=="object"&&"kind"in _.result&&_.result.kind==="submit"){h={text:_.result.message,attachments:C??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}A=!0}a.push(x),await dre(e,x);let N=x;if(A){let _=KS(x);if(_){let D=_.name.replace(/^\//,"").split(":").pop()??"";if(D&&Yv(D)){let F={skillName:D,rawArgs:_.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},U=e.session.current.sessionId,H=Ri(U),B=Date.now();W(`[afk trace] preflight.start commandName=${D}`);let P=!1,M=await xi(F,{cwd:e.stats.cwd??process.cwd(),artifactDir:H},O=>{We()&&e.replRenderer.writeLine(f.warning(`\u26A0 preflight(${D}) failed: `)+(O instanceof Error?O.message:String(O)))});P=M!==null,W(`[afk trace] preflight.end commandName=${D} durationMs=${Date.now()-B} success=${P}`),N=Zv(M?.manifestBlock,x)}}}let $=u.drainInjections();$.length>0&&(N=$+N);let I=m.drainInjections();if(I.length>0&&(N=I+N),e.hookRegistry)try{let _={event:"UserPromptSubmit",prompt:N,sessionId:e.stats.sessionId},D=await e.hookRegistry.dispatch(_);D.injectContext&&(N=D.injectContext+N)}catch(_){if(_ instanceof me){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+(_.reason?f.dim(`: ${qo(_.reason)}`):"")),e.statusLine.rearm();continue}if(_ instanceof Ln){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+f.dim(`: handler timed out after ${_.timeoutMs}ms`)),e.statusLine.rearm();continue}throw _}if(await VN({text:N,attachments:C},e.session.current,e.stats,{setInFlight(_){n.turnInFlight=_},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(_){await t.appendUser(_)},async onTurnComplete(_,D){if(await t.appendTurn(_,D),e.stats.sessionId)try{Xn(e.stats)}catch(F){b||(b=!0,e.replRenderer.writeLine(f.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(F instanceof Error?F.message:String(F))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:_=>d?.push(_),setActiveCompositor:_=>{n.activeCompositor=_},setInterruptNotifier:_=>{n.notifyInterrupting=_},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:_=>o.setBackgroundHandler(_),setSoftStopHandler:i,setPausedState:_=>o.setPausedState(_),setPauseInterruptHandler:_=>o.setPauseInterruptHandler(_),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(er(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:_=>c.repaint(_)}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(Da(e.stats.permissionMode))),e.hookRegistry)try{await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId},void 0,are)}catch(_){if(_ instanceof ut)throw _;_ instanceof Ln?(W("[stop hook] handler timed out"),e.completionWriter.fn(f.dim(" [stop hook] timed out"))):_ instanceof me?e.completionWriter.fn(f.dim(` [stop hook] blocked: ${qo(_.reason??"no reason given")}`)):W("[stop hook] unexpected error: "+String(_))}}}function ure(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 XN(e,t,n,r){let o=await CN(),i=new Og({rl:e.rl,history:o,statusLine:e.statusLine}),s=ure(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await ON(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar});a=WN(e,n),await YN(e,t,n,r,i,l,a,o)}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)}}yl();ws();import{execFile as pre}from"node:child_process";import{dirname as mre,isAbsolute as fre,resolve as gre}from"node:path";import{promisify as hre}from"node:util";var ZN=hre(pre),yre=3e3,bre=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function wre(){let t=(await ZN("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=fre(t)?t:gre(process.cwd(),t);return mre(n)}async function QN(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await wre()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),yre)});try{let o=mn({execFile:ZN,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=>bre.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Xd();yl();import{promises as Sre}from"node:fs";import{dirname as vre,join as nB}from"node:path";import{randomBytes as kre}from"node:crypto";var Ere=["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(`
1772
- `),eB=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,kk=30,Tre=1024,xre=8e3,Rre="haiku";async function Cre(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=Pre(n,Tre),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??xre),s=t.signal?Mre([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await es({token:t.token,model:t.model??Rre,system:Ere,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=Are(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=vre(t.worktreePath);return await _re(l,c)}function Are(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(eB.test(t)&&t.length<=kk)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>kk)break;o=s}return eB.test(o)?o:null}async function _re(e,t){if(!await Ire(nB(t,e)))return e;let n=kre(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,kk-5)}-${n}`}async function Ire(e){try{return await Sre.access(e),!0}catch{return!1}}function Pre(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 Mre(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 rB(e){let t,n,r=nB(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Cre(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=`${iu(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return tB(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 tB(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 tB(e,t){e&&e.setCwd(t),Ore(t)}function Ore(e){try{process.chdir(e)}catch{}}Jt();jt();G();import{spawn as iB}from"child_process";import{existsSync as sB,mkdirSync as Nre,readFileSync as aB,unlinkSync as oB,writeFileSync as lB}from"fs";import{get as Bre}from"https";import{join as cB}from"path";import{readFileSync as $re}from"fs";import{dirname as Dre,join as Fre}from"path";import{fileURLToPath as Lre}from"url";function ir(){try{return"5.33.1"}catch{}try{let e=Dre(Lre(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse($re(Fre(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}q();var Ure=64*1024,jre=10800*1e3,Hre=800,Wre=3600*1e3,Kre="update-check.json",Gre="pending-update.json";function Ek(){return cB(Cd(),Kre)}function od(){return cB(Cd(),Gre)}function Tk(){let e=Cd();sB(e)||Nre(e,{recursive:!0})}function dB(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 uB(){try{let e=aB(Ek(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function pB(){try{Tk();let e=`
1772
+ `),eB=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,kk=30,Tre=1024,xre=8e3,Rre="haiku";async function Cre(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=Pre(n,Tre),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??xre),s=t.signal?Mre([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await es({token:t.token,model:t.model??Rre,system:Ere,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=Are(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=vre(t.worktreePath);return await _re(l,c)}function Are(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(eB.test(t)&&t.length<=kk)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>kk)break;o=s}return eB.test(o)?o:null}async function _re(e,t){if(!await Ire(nB(t,e)))return e;let n=kre(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,kk-5)}-${n}`}async function Ire(e){try{return await Sre.access(e),!0}catch{return!1}}function Pre(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 Mre(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 rB(e){let t,n,r=nB(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Cre(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=`${iu(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return tB(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 tB(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 tB(e,t){e&&e.setCwd(t),Ore(t)}function Ore(e){try{process.chdir(e)}catch{}}Jt();jt();G();import{spawn as iB}from"child_process";import{existsSync as sB,mkdirSync as Nre,readFileSync as aB,unlinkSync as oB,writeFileSync as lB}from"fs";import{get as Bre}from"https";import{join as cB}from"path";import{readFileSync as $re}from"fs";import{dirname as Dre,join as Fre}from"path";import{fileURLToPath as Lre}from"url";function ir(){try{return"5.33.2"}catch{}try{let e=Dre(Lre(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse($re(Fre(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}q();var Ure=64*1024,jre=10800*1e3,Hre=800,Wre=3600*1e3,Kre="update-check.json",Gre="pending-update.json";function Ek(){return cB(Cd(),Kre)}function od(){return cB(Cd(),Gre)}function Tk(){let e=Cd();sB(e)||Nre(e,{recursive:!0})}function dB(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 uB(){try{let e=aB(Ek(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function pB(){try{Tk();let e=`
1773
1773
  const https = require('https');
1774
1774
  const fs = require('fs');
1775
1775
  const url = 'https://registry.npmjs.org/agent-afk/latest';