agent-afk 5.33.0 → 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.
@@ -843,7 +843,7 @@ ${Uy}
843
843
  `,"utf-8")}catch(r){W("WAL append failed (non-fatal):",String(r))}}};jG=/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;HG=new Set(["fact","session_start","session_end","supersede"]),WG=new Set(["preference","convention","decision","learning"])});function Zx(e){return GG.has(e)}function Mu(){return k.AFK_MEMORY_EVIDENCE_GATE==="1"}function jy(e){return Zx(e)}function Ou(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Qx(e,t){return Zx(e)?Ou(t)?"verified":"unverified":"not-applicable"}function eR(e,t){return t!=="unverified"||e.startsWith(Xx)?e:`${Xx} ${e}`}var GG,Xx,tR=R(()=>{"use strict";q();GG=new Set(["convention"]),Xx="[unverified]"});function zG(e,t){return t?e.map(n=>{if(n.type!=="fact"||!n.category)return{...n,verification:"not-applicable"};let r=Qx(n.category,n.evidence);return{...n,verification:r,content:eR(n.content,r)}}):e.map(n=>{let r={...n};return delete r.evidence,delete r.verification,r})}function El(e,t,n){let r=async s=>{try{let a=JG(s),l=e.search(a.query,{category:a.category,since:a.since,limit:a.limit??10});return{content:JSON.stringify(zG(l,Mu()))}}catch(a){return{content:`memory_search error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},o=async s=>{try{let a=VG(s);if(a.target==="hot"){if(a.action!=="set")return{content:'Hot memory only supports action: "set". Use supersede/remove only for facts.',isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let l=e.saveHot(a.content),c={saved:!0,target:"hot",usage:{tokens:l.tokens,maxTokens:l.maxTokens,pct:l.pct}};return l.truncated?(c.truncated=!0,c.note='Hot memory exceeded the ~1,500-token cap and was truncated from the end (lowest-priority lines dropped; a sentinel marks the cut). Keep hot memory to a few durable essentials \u2014 move detail to the fact archive with target:"fact".'):l.pct>=Vx*100&&(c.warning=`Hot memory is at ${l.pct}% of the ~1,500-token cap. Move non-essential lines to the fact archive (target:"fact") before it truncates.`),{content:JSON.stringify(c)}}if(a.action==="set"){if(!a.category)return{content:"category is required for fact storage",isError:!0};if(!a.content)return{content:'content is required for action: "set"',isError:!0};let l=a.category,c=Ou(a.evidence),u={id:e.storeFact({session_id:t,category:l,content:a.content,source_surface:n??"cli",evidence:c}),action:"set",target:"fact"};return Mu()&&jy(l)&&!c&&(u.warning=nR),{content:JSON.stringify(u)}}if(a.action==="supersede"){if(!a.supersedes)return{content:'supersedes (fact ID) is required for action: "supersede"',isError:!0};if(!a.content)return{content:'content is required for action: "supersede"',isError:!0};let l=e.getFact(a.supersedes),c=a.evidence===void 0?void 0:Ou(a.evidence),u={id:e.supersedeFact(a.supersedes,a.content,a.category??void 0,c),action:"supersede",target:"fact",supersedes:a.supersedes};if(Mu()){let m=a.category??l?.category;m&&jy(m)&&((c===void 0?l?.evidence??null:c)?c===void 0&&(u.warning=qG):u.warning=nR)}return{content:JSON.stringify(u)}}if(a.action==="remove"){if(!a.id)return{content:'id (fact ID) is required for action: "remove"',isError:!0};let l=e.removeFact(a.id);return{content:JSON.stringify({removed:l,action:"remove",target:"fact"})}}return{content:`Unknown action: ${a.action}`,isError:!0}}catch(a){return{content:`memory_update error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},i=async s=>{try{let a=YG(s);return e.writeProcedure(a.name,a.content,t),{content:JSON.stringify({name:a.name,written:!0})}}catch(a){return{content:`procedure_write error: ${a instanceof Error?a.message:String(a)}`,isError:!0}}};return new Map([["memory_search",r],["memory_update",o],["procedure_write",i]])}function JG(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.query!="string")throw new Error("query (string) is required");let n={query:t.query};if(t.category!==void 0){if(typeof t.category!="string")throw new Error("category must be a string");let r=["preference","convention","decision","learning"];if(!r.includes(t.category))throw new Error(`category must be one of: ${r.join(", ")}`);n.category=t.category}if(t.since!==void 0){if(typeof t.since!="string")throw new Error("since must be a string (ISO date)");n.since=t.since}if(t.limit!==void 0){if(typeof t.limit!="number"||t.limit<=0)throw new Error("limit must be a positive number");n.limit=t.limit}return n}function VG(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e,n=["hot","fact"];if(typeof t.target!="string"||!n.includes(t.target))throw new Error(`target must be one of: ${n.join(", ")}`);let r=["set","supersede","remove"];if(typeof t.action!="string"||!r.includes(t.action))throw new Error(`action must be one of: ${r.join(", ")}`);let o={target:t.target,action:t.action};if(t.content!==void 0){if(typeof t.content!="string")throw new Error("content must be a string");o.content=t.content}if(t.category!==void 0){if(typeof t.category!="string")throw new Error("category must be a string");let i=["preference","convention","decision","learning"];if(!i.includes(t.category))throw new Error(`category must be one of: ${i.join(", ")}`);o.category=t.category}if(t.evidence!==void 0){if(typeof t.evidence!="string")throw new Error("evidence must be a string");o.evidence=t.evidence}if(t.supersedes!==void 0){if(typeof t.supersedes!="number"||t.supersedes<=0)throw new Error("supersedes must be a positive fact ID");o.supersedes=t.supersedes}if(t.id!==void 0){if(typeof t.id!="number"||t.id<=0)throw new Error("id must be a positive fact ID");o.id=t.id}return o}function YG(e){if(typeof e!="object"||e===null)throw new Error("Input must be an object");let t=e;if(typeof t.name!="string")throw new Error("name (string) is required");if(typeof t.content!="string")throw new Error("content (string) is required");return{name:t.name,content:t.content}}var ms,rR,oR,Gr,Go,nR,qG,Hy=R(()=>{"use strict";Pu();tR();ms={name:"memory_search",category:"read",concurrencySafe:!0,description:'Search cross-session memory for facts and procedures. Returns results ranked by relevance. Use this to recall information from prior sessions. Supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*',input_schema:{type:"object",properties:{query:{type:"string",description:'Search query (supports FTS5 match syntax: AND, OR, NOT, "exact phrase", prefix*)'},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Optional: filter by fact category"},since:{type:"string",description:"Optional: ISO date \u2014 only return facts created after this date"},limit:{type:"number",description:"Max results (default 10)"}},required:["query"]}},rR={name:"memory_update",category:"write",concurrencySafe:!1,description:'Store a fact in cross-session memory or update hot memory. Hot memory (target: "hot") persists in the system prompt across all future sessions. Facts (target: "fact") are stored in the searchable archive.',input_schema:{type:"object",properties:{target:{type:"string",enum:["hot","fact"],description:'"hot" writes to HOT.md (system prompt), "fact" writes to the searchable archive'},action:{type:"string",enum:["set","supersede","remove"],description:"Operation: set (create/overwrite), supersede (replace while keeping history), remove (delete)"},content:{type:"string",description:"The content to store (for set/supersede)"},category:{type:"string",enum:["preference","convention","decision","learning"],description:"Required for fact target"},evidence:{type:"string",description:'Optional provenance citation backing a codebase fact \u2014 a file:line, commit SHA, or trace-event id. When the evidence gate is enabled, a "convention" fact stored without it is recalled as [unverified]; preferences and reflections never need it.'},supersedes:{type:"number",description:"Fact ID being superseded (for supersede action)"},id:{type:"number",description:"Fact ID to remove (for remove action)"}},required:["target","action"]}},oR={name:"procedure_write",category:"write",concurrencySafe:!1,description:"Write a reusable procedure to memory. Procedures are markdown files describing how to perform recurring tasks. They persist across sessions and are searchable via memory_search.",input_schema:{type:"object",properties:{name:{type:"string",description:"Procedure name (kebab-case, becomes the filename)"},content:{type:"string",description:"Procedure content (markdown)"}},required:["name","content"]}},Gr=[ms,rR,oR],Go=Gr.map(e=>e.name),nR='Stored without evidence \u2014 this codebase fact (category "convention") will be recalled as [unverified]. Supply `evidence` (a file:line, commit SHA, or trace-event id) so future sessions can trust it as ground truth rather than an unverified agent claim.',qG='Superseded without fresh evidence \u2014 the prior citation is carried forward and this codebase fact (category "convention") is still recalled as verified against the OLD evidence, which may not back the changed content. Re-supply `evidence` if the claim changed (or pass an empty string to clear it and recall as [unverified]).'});function Wy(e,t="all"){switch(t){case"self":return{self:e.getSelf()};case"tools":return{tools:e.getTools()};case"subagents":return{subagents:e.getSubagents()};case"workspace":return{workspace:e.getWorkspace()};default:return{self:e.getSelf(),tools:e.getTools(),subagents:e.getSubagents(),workspace:e.getWorkspace()}}}function Ky(e){return e==="self"||e==="tools"||e==="subagents"||e==="workspace"||e==="all"?e:"all"}function Tl(e){let n=[`- Working directory: ${e.cwd.replace(/[\r\n]/g," ")}`];n.push(`- Date: ${XG(e.now??new Date,e.timeZone)}`);let r=typeof e.sessionId=="string"&&e.sessionId.length>0?e.sessionId.slice(0,8):null,o=e.surface&&e.surface!=="unknown"?e.surface:null,i=typeof e.depth=="number"?typeof e.maxDepth=="number"?`depth ${e.depth}/${e.maxDepth}`:`depth ${e.depth}`:null,s=[o,i].filter(a=>typeof a=="string");if(r!==null||s.length>0){let a=["- Session:"];r!==null&&a.push(r),s.length>0&&a.push(`(${s.join(", ")})`),n.push(a.join(" "))}if(e.workspace!==void 0&&e.workspace!==null){let a=e.workspace;if(a.branch!==null||a.headSha!==null){let l=a.branch??"(detached)",c=a.headSha!==null?` @ ${a.headSha}`:"",d;a.dirty===null?d="":a.dirty?d=` (${a.dirtyCount!==null?a.dirtyCount:"?"} dirty)`:d=" (clean)",n.push(`- Workspace: ${l}${c}${d}`)}}return`# Environment
844
844
  ${n.join(`
845
845
  `)}`}function XG(e,t){try{let n=t??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",r=new Intl.DateTimeFormat("en-CA",{timeZone:n,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),o=s=>r.find(a=>a.type===s)?.value??"";return`${new Intl.DateTimeFormat("en-US",{timeZone:n,weekday:"long"}).format(e)}, ${o("year")}-${o("month")}-${o("day")} (${n})`}catch{return e.toISOString().slice(0,10)}}var Gy=R(()=>{"use strict"});import{spawnSync as ZG}from"child_process";function $u(e,t,n=!1){try{let r=ZG("git",t,{cwd:e,encoding:"utf8",maxBuffer:4096,shell:!1});if(r.status!==0||r.signal!==null||r.error!==void 0)return null;let o=typeof r.stdout=="string"?r.stdout.trim():null;return o===null?null:o.length>0||n?o:null}catch{return null}}function qy(e){let t=$u(e,["rev-parse","--short","HEAD"]);if(t===null)return{...QG};let n=$u(e,["symbolic-ref","--short","HEAD"]),r=$u(e,["status","--porcelain"],!0),o=!1,i=0;if(r!==null){let a=r.split(`
846
- `).filter(l=>l.trim().length>0);o=a.length>0,i=a.length}else o=null,i=null;let s=$u(e,["remote","get-url","origin"]);return{branch:n,headSha:t,dirty:o,dirtyCount:i,remoteUrl:s}}var QG,zy=R(()=>{"use strict";QG={branch:null,headSha:null,dirty:null,dirtyCount:null,remoteUrl:null}});function xl(e){return{getSelf(){return{sessionId:e.sessionId??null,surface:t2(e.surface),parentSessionId:e.parentSessionId??null,depth:e.depth??null,maxDepth:e.maxDepth??null,phaseRole:e.phaseRole??null,cwd:e.cwd,model:{provider:e.providerName,name:e.modelName},permissionMode:e2(e.permissionMode)}},getTools(){return{enabled:e.getEnabledToolNames(),mcpServers:n2(e.getMcpTools())}},getSubagents(){return e.getSubagents()},getWorkspace(){return qy(e.cwd)}}}function e2(e){switch(e){case"bypassPermissions":case"acceptEdits":case"dontAsk":case"auto":return"elevated";default:return"default"}}function t2(e){switch(e){case"cli":case"repl":case"daemon":case"telegram":case"subagent":return e;default:return"unknown"}}function n2(e){let t=new Map;for(let n of e){if(!n.name.startsWith("mcp__"))continue;let r=n.name.split("__");if(r.length<3)continue;let o=r[1];typeof o!="string"||o.length===0||t.set(o,(t.get(o)??0)+1)}return[...t.entries()].map(([n,r])=>({name:n,toolCount:r})).sort((n,r)=>n.name.localeCompare(r.name))}var iR=R(()=>{"use strict";zy()});function fs(e){return async(t,n)=>{let r=t&&typeof t=="object"?Ky(t.view):"all",o=Wy(e,r);return{content:JSON.stringify(o)}}}function Rl(e,t){let n=fs(t),r=e,o=Array.isArray(r.toolDefs)?r.toolDefs:null,i={async execute(s){return s.name==="get_runtime_state"?n(s.input,s.signal):e.execute(s)}};if(o!==null){let s=o.some(a=>a.name==="get_runtime_state");i.toolDefs=s?o:[...o,Un]}return i}var Un,st,Du=R(()=>{"use strict";Gy();Un={name:"get_runtime_state",category:"other",concurrencySafe:!0,description:"Inspect what the runtime knows about this session: identity (sessionId, surface, depth, parent), tool affordances (currently-enabled tool names and MCP server summary), delegation state (active subagent handles, background jobs), and git workspace state (branch, HEAD SHA, dirty count, remote URL). Returns a compact JSON snapshot.\n\nUse when uncertain about: your current nesting depth, whether a tool you want is actually available right now, what MCP servers are wired, whether earlier subagents you dispatched are still running, or what git branch / commit the session started on.\n\nViews:\n- `self` \u2014 identity + model + permissions + cwd only\n- `tools` \u2014 enabled tool names + MCP server summary only\n- `subagents` \u2014 active subagent handles + background jobs only\n- `workspace` \u2014 git state (branch, headSha, dirty, dirtyCount, remoteUrl)\n- `all` \u2014 union of the four above (default)\n\nThis is a read-only, in-memory inspection. It does not probe the file system or network. Fields the runtime does not know (e.g. depth for a top-level session) come back as `null` rather than synthesised defaults.",input_schema:{type:"object",properties:{view:{type:"string",enum:["self","tools","subagents","workspace","all"],description:'Which slice of state to return. Defaults to "all". Use a narrower view when only one slice is needed to keep the response compact.'}},required:[]}},st=[Un.name]});import{mkdir as r2,writeFile as Jy,unlink as Oge,readdir as o2,readFile as Vy}from"fs/promises";import{unlinkSync as i2,existsSync as s2}from"fs";import{join as sR}from"path";function Fu(e){return sR(Ad(),`${e}.json`)}async function a2(){try{return await r2(Ad(),{recursive:!0}),!0}catch{return!1}}async function Cl(e){try{if(!await a2())return;let n=Fu(e.sessionId);await Jy(n,JSON.stringify(e,null,2),"utf8")}catch{}}async function Yy(e,t){try{let n=Fu(e),r=await Vy(n,"utf8"),o=JSON.parse(r);o.afk=t,await Jy(n,JSON.stringify(o,null,2),"utf8")}catch{}}async function aR(e,t){try{let n=Fu(e),r=await Vy(n,"utf8"),o=JSON.parse(r);o.cwd=t,await Jy(n,JSON.stringify(o,null,2),"utf8")}catch{}}function hr(e){try{let t=Fu(e);s2(t)&&i2(t)}catch{}}async function Xy(){let e=Ad(),t;try{t=await o2(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".json"))continue;let o=sR(e,r);try{let i=await Vy(o,"utf8"),s=JSON.parse(i);s!==null&&typeof s=="object"&&"sessionId"in s&&typeof s.sessionId=="string"&&n.push({...s,path:o})}catch{}}return n}var Al=R(()=>{"use strict";G()});var dn=R(()=>{"use strict";Gy();iR();Du();zy();Al()});function Zy(e){return l2.has(e)}function lR(e,t){return e.reduce((n,r,o)=>{let i=t(r.name,r.input),s=n[n.length-1];return s&&i&&s.isConcurrencySafe?s.indices.push(o):n.push({isConcurrencySafe:i,indices:[o]}),n},[])}var l2,Qy=R(()=>{"use strict";ln();Hy();dn();l2=new Set([...gr,Wt,Wo,Ko,...Gr,Un].filter(e=>e.concurrencySafe===!0).map(e=>e.name))});import{createHash as c2}from"node:crypto";function cR(e){let t;try{t=JSON.stringify(e.input)??"null"}catch{t=String(e.input)}return c2("sha256").update(e.name).update("\0").update(t).digest("hex")}var dR=R(()=>{"use strict"});var gs,d2,u2,Kt,_l=R(()=>{"use strict";ve();pt();ku();hu();vu();Ny();xu();xe();Qy();dR();Qy();gs=8,d2=new Set,u2=8,Kt=class{handlers;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;skillExecutor;composeExecutor;classifier;maxConcurrentSafeCalls;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;traceWriter;readOnlyBash;repeatBreaker=null;grantManager;constructor(t){this.handlers=t.handlers,this.schemas=t.schemas,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,this.subagentExecutor=t.subagentExecutor,this.skillExecutor=t.skillExecutor,this.composeExecutor=t.composeExecutor,this.classifier=t.concurrencyClassifier??Zy,this.maxConcurrentSafeCalls=typeof t.maxConcurrentSafeCalls=="number"&&Number.isFinite(t.maxConcurrentSafeCalls)&&t.maxConcurrentSafeCalls>=1?Math.floor(t.maxConcurrentSafeCalls):u2,this.resolveBase=t.cwd,this._env=t.env,this.sessionId=t.sessionId,this.parentSessionId=t.parentSessionId,this.traceWriter=t.traceWriter,this.readOnlyBash=t.readOnlyBash===!0,this._allowAll=t.allowAll===!0;let n=t.cwd?[t.cwd]:[];this._readRoots=t.readRoots??n.slice(),this._writeRoots=t.writeRoots??n.slice(),this.grantManager=new Kr({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,getProtectedRoot:()=>this.resolveBase,getAllowAll:()=>this._allowAll,getDefaultSessionId:()=>this.sessionId})}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{}}}callHandlerContext(t){return{...this.handlerContext,toolUseId:t.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{}}}addReadRoot(t,n="slash"){this.grantManager.addReadRoot(t,n)}addWriteRoot(t,n="slash"){this.grantManager.addWriteRoot(t,n)}revokeRoot(t,n="slash"){this.grantManager.revokeRoot(t,n)}getGrants(){return this.grantManager.getGrants()}setAllowAll(t){this._allowAll=t}setResolveBase(t){let n=this.resolveBase;if(n!==t){if(this.resolveBase=t,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=t:this._readRoots.includes(t)||this._readRoots.push(t);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=t:this._writeRoots.includes(t)||this._writeRoots.push(t)}else this._readRoots.includes(t)||this._readRoots.push(t),this._writeRoots.includes(t)||this._writeRoots.push(t);this.subagentExecutor?.setCwd(t),this.skillExecutor?.setCwd(t),this.composeExecutor?.setCwd(t)}}get toolDefs(){let t=this.permissions?.allowedTools;if(!t)return this.schemas;let n=new Set(t);return this.schemas.filter(r=>n.has(r.name))}checkReadOnlyBash(t){if(!this.readOnlyBash||t.name!=="bash")return null;let n=t.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=Tu(r);return o.mutating?{content:`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff, ls, cat, find, grep).`,isError:!0,failureClass:"permission-denied"}:null}checkRepeatCircuitBreaker(t){if(d2.has(t.name))return null;let n=cR(t);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<gs?null:{content:`Loop circuit breaker: "${t.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}async runCanUseTool(t){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(t.name,t.input??{},{signal:t.signal,toolUseID:t.id})}catch(r){return await wn(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t.name,reason:`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`}),{content:`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`,isError:!0,failureClass:"permission-denied"}}return n.behavior==="deny"?(await wn(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t.name,reason:n.message||`Tool "${t.name}" denied by permission policy`}),{content:n.message||`Tool "${t.name}" denied by permission policy`,isError:!0,failureClass:"permission-denied"}):(n.updatedInput!==void 0&&(t.input=n.updatedInput),null)}async execute(t){if(t.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:"abort"};if(this.hookRegistry){let s={event:"PreToolUse",toolName:t.name,input:t.input,...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};try{await Oy(this.hookRegistry,s,{signal:t.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(a){if(a instanceof me)return{content:`Tool "${t.name}" blocked by PreToolUse hook: ${a.message}`,isError:!0,failureClass:"hook-block"};throw a}}let n=Ly(t.name,this.permissions);if(!n.allowed)return{content:n.reason??`Tool "${t.name}" is not permitted`,isError:!0,failureClass:"permission-denied"};let r=await this.runCanUseTool(t);if(r)return r;let o=this.checkReadOnlyBash(t);if(o)return o;let i=this.checkRepeatCircuitBreaker(t);return i||this.executeCore(t)}async executeBatch(t){if(t.length===0)return[];if(t.length===1)return[await this.execute(t[0])];let n=new Array(t.length),r=new Set;for(let s=0;s<t.length;s++){let a=t[s];if(a.signal.aborted){n[s]={content:"Tool call aborted",isError:!0,failureClass:"abort"},r.add(s);continue}if(this.hookRegistry){let m={event:"PreToolUse",toolName:a.name,input:a.input,...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};try{await Oy(this.hookRegistry,m,{signal:a.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(p){if(p instanceof me){n[s]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${p.message}`,isError:!0,failureClass:"hook-block"},r.add(s);continue}throw p}}let l=Ly(a.name,this.permissions);if(!l.allowed){n[s]={content:l.reason??`Tool "${a.name}" is not permitted`,isError:!0,failureClass:"permission-denied"},r.add(s);continue}let c=await this.runCanUseTool(a);if(c){n[s]=c,r.add(s);continue}let d=this.checkReadOnlyBash(a);if(d){n[s]=d,r.add(s);continue}let u=this.checkRepeatCircuitBreaker(a);if(u){n[s]=u,r.add(s);continue}}let o=t.map((s,a)=>({call:s,originalIndex:a})).filter((s,a)=>!r.has(a));if(o.length===0)return n;let i=lR(o.map(s=>s.call),this.classifier);for(let s of i){if(s.isConcurrencySafe){let l=await ps(s.indices,this.maxConcurrentSafeCalls,async c=>{let{call:d,originalIndex:u}=o[c];return d.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:"abort"},originalIndex:u}:{result:await this.executeCore(d),originalIndex:u}});for(let c of l)if(c.status==="fulfilled")n[c.value.originalIndex]=c.value.result;else{let d=c.reason instanceof Error?c.reason.message:String(c.reason),u=s.indices[l.indexOf(c)];n[o[u].originalIndex]={content:`Tool execution error: ${d}`,isError:!0}}}else for(let l of s.indices){let{call:c,originalIndex:d}=o[l];if(c.signal.aborted){n[d]={content:"Tool call aborted",isError:!0,failureClass:"abort"};continue}n[d]=await this.executeCore(c)}let a=s.indices.length;s.indices.forEach((l,c)=>{let d=n[o[l].originalIndex];d&&(d.batchIndex=c+1,d.batchSize=a)})}return n}async executeCore(t){if(t.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.subagentExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Agent tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input),s}if(t.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.skillExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Skill tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input),s}if(t.name==="compose"){let s=await this.executeCompose(t);return this.firePostToolUse(t.name,s.content,t.signal,t.input),s}let n=this.handlers.get(t.name);if(!n)return{content:`Unknown tool "${t.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r,o=!1,i="";try{r=await n(t.input,t.signal,this.callHandlerContext(t))}catch(s){o=!0,i=s instanceof Error?s.message:String(s),r={content:`Tool execution error: ${i}`,isError:!0}}return o?this.firePostToolUseFailure(t.name,i,t.signal,t.input):this.firePostToolUse(t.name,r.content,t.signal,t.input),r}async executeCompose(t){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(t)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(t,n,r,o){if(!this.hookRegistry)return;let i={event:"PostToolUse",toolName:t,output:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};Px(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(t,n,r,o){if(!this.hookRegistry)return;let i={event:"PostToolUseFailure",toolName:t,error:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};Mx(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(s=>{W(`firePostToolUseFailure outer catch (tool=${t}): ${String(s)}`)})}}});function k2(e){let t=e.match(p2);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function E2(e){let t=e.match(m2);if(!t)return null;let n=parseInt(t[1]??"0",10);return{runner:"jest",passed:parseInt(t[2]??"0",10),failed:n}}function T2(e){let t=e.match(f2);if(!t)return null;if(t[2]!==void 0){let n=parseInt(t[2],10),r=parseInt(t[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return t[4]!==void 0?{runner:"pytest",passed:parseInt(t[4],10),failed:0}:null}function x2(e){let t=e.match(g2);if(!t)return null;let n=parseInt(t[1]??"0",10),r=e.match(h2),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function R2(e){let t=[...e.matchAll(y2)];if(t.length===0)return null;let n=0,r=0;for(let o of t)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function C2(e){let t=e.match(b2);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function A2(e){let t=e.match(w2);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function _2(e){let t=e.match(S2);if(t)return{runner:"phpunit",passed:parseInt(t[1]??"0",10),failed:0};let n=e.match(v2);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function eb(e){return k2(e)??E2(e)??T2(e)??x2(e)??R2(e)??C2(e)??A2(e)??_2(e)??null}var p2,m2,f2,g2,h2,y2,b2,w2,S2,v2,uR=R(()=>{"use strict";p2=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,m2=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,f2=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,g2=/(\d+)\s+passing/,h2=/(\d+)\s+failing/,y2=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,b2=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,w2=/(\d+) examples?, (\d+) failures?/,S2=/OK \((\d+) tests?/,v2=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/});function qo(e){return e.replace(pR,"").replace(I2," ").trim()}function yr(e){return e.replace(pR,"")}var pR,I2,zo=R(()=>{"use strict";pR=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,I2=/[\x00-\x1F\x7F-\x9F]/g});import{statSync as P2}from"node:fs";function Il(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.code==="ENOENT"&&typeof t.syscall=="string"&&t.syscall.startsWith("spawn")}function M2(e){if(e===void 0)return!1;try{return P2(e),!1}catch{return!0}}function hs(e,t){let n=e instanceof Error?e.message:typeof e?.message=="string"?String(e.message):String(e);return Il(e)&&M2(t)?`working directory does not exist: ${t} (deleted worktree?) \u2014 underlying: ${n}`:n}var tb=R(()=>{"use strict"});function O2(e,t){if(e.length<=t)return e;let n=t;for(;n>0&&(e[n]&192)===128;)n--;return e.subarray(0,n)}function $2(e,t){if(e.length<=t)return e;let n=e.length-t;for(;n<e.length&&(e[n]&192)===128;)n++;return e.subarray(n)}function Pl(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=Math.max(0,t-D2),o=Math.ceil(r/2),i=r-o,s=O2(n,o),a=$2(n,i),c=`
846
+ `).filter(l=>l.trim().length>0);o=a.length>0,i=a.length}else o=null,i=null;let s=$u(e,["remote","get-url","origin"]);return{branch:n,headSha:t,dirty:o,dirtyCount:i,remoteUrl:s}}var QG,zy=R(()=>{"use strict";QG={branch:null,headSha:null,dirty:null,dirtyCount:null,remoteUrl:null}});function xl(e){return{getSelf(){return{sessionId:e.sessionId??null,surface:t2(e.surface),parentSessionId:e.parentSessionId??null,depth:e.depth??null,maxDepth:e.maxDepth??null,phaseRole:e.phaseRole??null,cwd:e.cwd,model:{provider:e.providerName,name:e.modelName},permissionMode:e2(e.permissionMode)}},getTools(){return{enabled:e.getEnabledToolNames(),mcpServers:n2(e.getMcpTools())}},getSubagents(){return e.getSubagents()},getWorkspace(){return qy(e.cwd)}}}function e2(e){switch(e){case"bypassPermissions":case"acceptEdits":case"dontAsk":case"auto":return"elevated";default:return"default"}}function t2(e){switch(e){case"cli":case"repl":case"daemon":case"telegram":case"subagent":return e;default:return"unknown"}}function n2(e){let t=new Map;for(let n of e){if(!n.name.startsWith("mcp__"))continue;let r=n.name.split("__");if(r.length<3)continue;let o=r[1];typeof o!="string"||o.length===0||t.set(o,(t.get(o)??0)+1)}return[...t.entries()].map(([n,r])=>({name:n,toolCount:r})).sort((n,r)=>n.name.localeCompare(r.name))}var iR=R(()=>{"use strict";zy()});function fs(e){return async(t,n)=>{let r=t&&typeof t=="object"?Ky(t.view):"all",o=Wy(e,r);return{content:JSON.stringify(o)}}}function Rl(e,t){let n=fs(t),r=e,o=Array.isArray(r.toolDefs)?r.toolDefs:null,i={async execute(s){return s.name==="get_runtime_state"?n(s.input,s.signal):e.execute(s)}};if(o!==null){let s=o.some(a=>a.name==="get_runtime_state");i.toolDefs=s?o:[...o,Un]}return i}var Un,st,Du=R(()=>{"use strict";Gy();Un={name:"get_runtime_state",category:"other",concurrencySafe:!0,description:"Inspect what the runtime knows about this session: identity (sessionId, surface, depth, parent), tool affordances (currently-enabled tool names and MCP server summary), delegation state (active subagent handles, background jobs), and git workspace state (branch, HEAD SHA, dirty count, remote URL). Returns a compact JSON snapshot.\n\nUse when uncertain about: your current nesting depth, whether a tool you want is actually available right now, what MCP servers are wired, whether earlier subagents you dispatched are still running, or what git branch / commit the session started on.\n\nViews:\n- `self` \u2014 identity + model + permissions + cwd only\n- `tools` \u2014 enabled tool names + MCP server summary only\n- `subagents` \u2014 active subagent handles + background jobs only\n- `workspace` \u2014 git state (branch, headSha, dirty, dirtyCount, remoteUrl)\n- `all` \u2014 union of the four above (default)\n\nThis is a read-only, in-memory inspection. It does not probe the file system or network. Fields the runtime does not know (e.g. depth for a top-level session) come back as `null` rather than synthesised defaults.",input_schema:{type:"object",properties:{view:{type:"string",enum:["self","tools","subagents","workspace","all"],description:'Which slice of state to return. Defaults to "all". Use a narrower view when only one slice is needed to keep the response compact.'}},required:[]}},st=[Un.name]});import{mkdir as r2,writeFile as Jy,unlink as Oge,readdir as o2,readFile as Vy}from"fs/promises";import{unlinkSync as i2,existsSync as s2}from"fs";import{join as sR}from"path";function Fu(e){return sR(Ad(),`${e}.json`)}async function a2(){try{return await r2(Ad(),{recursive:!0}),!0}catch{return!1}}async function Cl(e){try{if(!await a2())return;let n=Fu(e.sessionId);await Jy(n,JSON.stringify(e,null,2),"utf8")}catch{}}async function Yy(e,t){try{let n=Fu(e),r=await Vy(n,"utf8"),o=JSON.parse(r);o.afk=t,await Jy(n,JSON.stringify(o,null,2),"utf8")}catch{}}async function aR(e,t){try{let n=Fu(e),r=await Vy(n,"utf8"),o=JSON.parse(r);o.cwd=t,await Jy(n,JSON.stringify(o,null,2),"utf8")}catch{}}function hr(e){try{let t=Fu(e);s2(t)&&i2(t)}catch{}}async function Xy(){let e=Ad(),t;try{t=await o2(e)}catch{return[]}let n=[];for(let r of t){if(!r.endsWith(".json"))continue;let o=sR(e,r);try{let i=await Vy(o,"utf8"),s=JSON.parse(i);s!==null&&typeof s=="object"&&"sessionId"in s&&typeof s.sessionId=="string"&&n.push({...s,path:o})}catch{}}return n}var Al=R(()=>{"use strict";G()});var dn=R(()=>{"use strict";Gy();iR();Du();zy();Al()});function Zy(e){return l2.has(e)}function lR(e,t){return e.reduce((n,r,o)=>{let i=t(r.name,r.input),s=n[n.length-1];return s&&i&&s.isConcurrencySafe?s.indices.push(o):n.push({isConcurrencySafe:i,indices:[o]}),n},[])}var l2,Qy=R(()=>{"use strict";ln();Hy();dn();l2=new Set([...gr,Wt,Wo,Ko,...Gr,Un].filter(e=>e.concurrencySafe===!0).map(e=>e.name))});import{createHash as c2}from"node:crypto";function cR(e){let t;try{t=JSON.stringify(e.input)??"null"}catch{t=String(e.input)}return c2("sha256").update(e.name).update("\0").update(t).digest("hex")}var dR=R(()=>{"use strict"});var gs,d2,u2,Kt,_l=R(()=>{"use strict";ve();pt();ku();hu();vu();Ny();xu();xe();Qy();dR();Qy();gs=8,d2=new Set,u2=8,Kt=class{handlers;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;skillExecutor;composeExecutor;classifier;maxConcurrentSafeCalls;resolveBase;_readRoots;_writeRoots;_allowAll;_env;sessionId;parentSessionId;sessionGrantManager;traceWriter;readOnlyBash;repeatBreaker=null;grantManager;constructor(t){this.handlers=t.handlers,this.schemas=t.schemas,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,this.subagentExecutor=t.subagentExecutor,this.skillExecutor=t.skillExecutor,this.composeExecutor=t.composeExecutor,this.classifier=t.concurrencyClassifier??Zy,this.maxConcurrentSafeCalls=typeof t.maxConcurrentSafeCalls=="number"&&Number.isFinite(t.maxConcurrentSafeCalls)&&t.maxConcurrentSafeCalls>=1?Math.floor(t.maxConcurrentSafeCalls):u2,this.resolveBase=t.cwd,this._env=t.env,this.sessionId=t.sessionId,this.parentSessionId=t.parentSessionId,this.sessionGrantManager=t.sessionGrantManager,this.traceWriter=t.traceWriter,this.readOnlyBash=t.readOnlyBash===!0,this._allowAll=t.allowAll===!0;let n=t.cwd?[t.cwd]:[];this._readRoots=t.readRoots??n.slice(),this._writeRoots=t.writeRoots??n.slice(),this.grantManager=new Kr({getReadRoots:()=>this._readRoots,getWriteRoots:()=>this._writeRoots,getProtectedRoot:()=>this.resolveBase,getAllowAll:()=>this._allowAll,getDefaultSessionId:()=>this.sessionId})}get handlerContext(){return{cwd:this.resolveBase,resolveBase:this.resolveBase,readRoots:this._readRoots.slice(),writeRoots:this._writeRoots.slice(),...this._allowAll?{allowAll:!0}:{},...this._env!==void 0?{env:this._env}:{}}}callHandlerContext(t){return{...this.handlerContext,toolUseId:t.id,...this.traceWriter!==void 0?{traceWriter:this.traceWriter}:{}}}addReadRoot(t,n="slash"){this.grantManager.addReadRoot(t,n)}addWriteRoot(t,n="slash"){this.grantManager.addWriteRoot(t,n)}revokeRoot(t,n="slash"){this.grantManager.revokeRoot(t,n)}getGrants(){return this.grantManager.getGrants()}setAllowAll(t){this._allowAll=t}setResolveBase(t){let n=this.resolveBase;if(n!==t){if(this.resolveBase=t,n!==void 0){let r=this._readRoots.indexOf(n);r!==-1?this._readRoots[r]=t:this._readRoots.includes(t)||this._readRoots.push(t);let o=this._writeRoots.indexOf(n);o!==-1?this._writeRoots[o]=t:this._writeRoots.includes(t)||this._writeRoots.push(t)}else this._readRoots.includes(t)||this._readRoots.push(t),this._writeRoots.includes(t)||this._writeRoots.push(t);this.subagentExecutor?.setCwd(t),this.skillExecutor?.setCwd(t),this.composeExecutor?.setCwd(t)}}get toolDefs(){let t=this.permissions?.allowedTools;if(!t)return this.schemas;let n=new Set(t);return this.schemas.filter(r=>n.has(r.name))}checkReadOnlyBash(t){if(!this.readOnlyBash||t.name!=="bash")return null;let n=t.input,r=typeof n=="object"&&n!==null?n.command:void 0;if(typeof r!="string")return null;let o=Tu(r);return o.mutating?{content:`Bash command blocked: read-only skill may not run mutating commands (${o.reason??"mutation detected"}). Allowed: read-only recon (git status/log/diff, ls, cat, find, grep).`,isError:!0,failureClass:"permission-denied"}:null}checkRepeatCircuitBreaker(t){if(d2.has(t.name))return null;let n=cR(t);return this.repeatBreaker!==null&&this.repeatBreaker.fingerprint===n?this.repeatBreaker.count+=1:this.repeatBreaker={fingerprint:n,count:1},this.repeatBreaker.count<gs?null:{content:`Loop circuit breaker: "${t.name}" has been called ${this.repeatBreaker.count} times in a row with byte-identical input. The result will not change. Stop repeating this call \u2014 reuse the previous result, change the input, try a different tool, or end the turn.`,isError:!0,circuitBreaker:!0}}async runCanUseTool(t){if(!this.canUseTool)return null;let n;try{n=await this.canUseTool(t.name,t.input??{},{signal:t.signal,toolUseID:t.id})}catch(r){return await wn(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t.name,reason:`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`}),{content:`Tool "${t.name}" denied by canUseTool (threw): ${r instanceof Error?r.message:String(r)}`,isError:!0,failureClass:"permission-denied"}}return n.behavior==="deny"?(await wn(this.traceWriter,{hookEvent:"PreToolUse",decision:"block",blockedTool:t.name,reason:n.message||`Tool "${t.name}" denied by permission policy`}),{content:n.message||`Tool "${t.name}" denied by permission policy`,isError:!0,failureClass:"permission-denied"}):(n.updatedInput!==void 0&&(t.input=n.updatedInput),null)}async execute(t){if(t.signal.aborted)return{content:"Tool call aborted",isError:!0,failureClass:"abort"};if(this.hookRegistry){let s={event:"PreToolUse",toolName:t.name,input:t.input,...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{}};try{await Oy(this.hookRegistry,s,{signal:t.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(a){if(a instanceof me)return{content:`Tool "${t.name}" blocked by PreToolUse hook: ${a.message}`,isError:!0,failureClass:"hook-block"};throw a}}let n=Ly(t.name,this.permissions);if(!n.allowed)return{content:n.reason??`Tool "${t.name}" is not permitted`,isError:!0,failureClass:"permission-denied"};let r=await this.runCanUseTool(t);if(r)return r;let o=this.checkReadOnlyBash(t);if(o)return o;let i=this.checkRepeatCircuitBreaker(t);return i||this.executeCore(t)}async executeBatch(t){if(t.length===0)return[];if(t.length===1)return[await this.execute(t[0])];let n=new Array(t.length),r=new Set;for(let s=0;s<t.length;s++){let a=t[s];if(a.signal.aborted){n[s]={content:"Tool call aborted",isError:!0,failureClass:"abort"},r.add(s);continue}if(this.hookRegistry){let m={event:"PreToolUse",toolName:a.name,input:a.input,...this.resolveBase!==void 0?{cwd:this.resolveBase}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{}};try{await Oy(this.hookRegistry,m,{signal:a.signal,...this.traceWriter?{traceWriter:this.traceWriter}:{}})}catch(p){if(p instanceof me){n[s]={content:`Tool "${a.name}" blocked by PreToolUse hook: ${p.message}`,isError:!0,failureClass:"hook-block"},r.add(s);continue}throw p}}let l=Ly(a.name,this.permissions);if(!l.allowed){n[s]={content:l.reason??`Tool "${a.name}" is not permitted`,isError:!0,failureClass:"permission-denied"},r.add(s);continue}let c=await this.runCanUseTool(a);if(c){n[s]=c,r.add(s);continue}let d=this.checkReadOnlyBash(a);if(d){n[s]=d,r.add(s);continue}let u=this.checkRepeatCircuitBreaker(a);if(u){n[s]=u,r.add(s);continue}}let o=t.map((s,a)=>({call:s,originalIndex:a})).filter((s,a)=>!r.has(a));if(o.length===0)return n;let i=lR(o.map(s=>s.call),this.classifier);for(let s of i){if(s.isConcurrencySafe){let l=await ps(s.indices,this.maxConcurrentSafeCalls,async c=>{let{call:d,originalIndex:u}=o[c];return d.signal.aborted?{result:{content:"Tool call aborted",isError:!0,failureClass:"abort"},originalIndex:u}:{result:await this.executeCore(d),originalIndex:u}});for(let c of l)if(c.status==="fulfilled")n[c.value.originalIndex]=c.value.result;else{let d=c.reason instanceof Error?c.reason.message:String(c.reason),u=s.indices[l.indexOf(c)];n[o[u].originalIndex]={content:`Tool execution error: ${d}`,isError:!0}}}else for(let l of s.indices){let{call:c,originalIndex:d}=o[l];if(c.signal.aborted){n[d]={content:"Tool call aborted",isError:!0,failureClass:"abort"};continue}n[d]=await this.executeCore(c)}let a=s.indices.length;s.indices.forEach((l,c)=>{let d=n[o[l].originalIndex];d&&(d.batchIndex=c+1,d.batchSize=a)})}return n}async executeCore(t){if(t.name==="agent"){if(!this.subagentExecutor)return{content:"Agent tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.subagentExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Agent tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input),s}if(t.name==="skill"){if(!this.skillExecutor)return{content:"Skill tool is not available in this session configuration",isError:!0};let s,a=!1,l="";try{s=await this.skillExecutor.execute(t)}catch(c){a=!0,l=c instanceof Error?c.message:String(c),s={content:`Skill tool error: ${l}`,isError:!0}}return a?this.firePostToolUseFailure(t.name,l,t.signal,t.input):this.firePostToolUse(t.name,s.content,t.signal,t.input),s}if(t.name==="compose"){let s=await this.executeCompose(t);return this.firePostToolUse(t.name,s.content,t.signal,t.input),s}let n=this.handlers.get(t.name);if(!n)return{content:`Unknown tool "${t.name}". Available tools: ${[...this.handlers.keys()].join(", ")}`,isError:!0};let r,o=!1,i="";try{r=await n(t.input,t.signal,this.callHandlerContext(t))}catch(s){o=!0,i=s instanceof Error?s.message:String(s),r={content:`Tool execution error: ${i}`,isError:!0}}return o?this.firePostToolUseFailure(t.name,i,t.signal,t.input):this.firePostToolUse(t.name,r.content,t.signal,t.input),r}async executeCompose(t){if(!this.composeExecutor)return{content:"Compose tool is not available in this session configuration",isError:!0};try{return await this.composeExecutor.execute(t)}catch(n){return{content:`Compose tool error: ${n instanceof Error?n.message:String(n)}`,isError:!0}}}firePostToolUse(t,n,r,o){if(!this.hookRegistry)return;let i={event:"PostToolUse",toolName:t,output:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{},...this.sessionGrantManager!==void 0?{grantManager:this.sessionGrantManager}:{}};Px(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(()=>{})}firePostToolUseFailure(t,n,r,o){if(!this.hookRegistry)return;let i={event:"PostToolUseFailure",toolName:t,error:n,...o!==void 0?{input:o}:{},...this.parentSessionId!==void 0?{parentSessionId:this.parentSessionId}:{}};Mx(this.hookRegistry,i,{signal:r,...this.traceWriter?{traceWriter:this.traceWriter}:{}}).catch(s=>{W(`firePostToolUseFailure outer catch (tool=${t}): ${String(s)}`)})}}});function k2(e){let t=e.match(p2);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"vitest",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function E2(e){let t=e.match(m2);if(!t)return null;let n=parseInt(t[1]??"0",10);return{runner:"jest",passed:parseInt(t[2]??"0",10),failed:n}}function T2(e){let t=e.match(f2);if(!t)return null;if(t[2]!==void 0){let n=parseInt(t[2],10),r=parseInt(t[1]??"0",10);return{runner:"pytest",passed:n,failed:r}}return t[4]!==void 0?{runner:"pytest",passed:parseInt(t[4],10),failed:0}:null}function x2(e){let t=e.match(g2);if(!t)return null;let n=parseInt(t[1]??"0",10),r=e.match(h2),o=r?parseInt(r[1]??"0",10):0;return{runner:"mocha",passed:n,failed:o}}function R2(e){let t=[...e.matchAll(y2)];if(t.length===0)return null;let n=0,r=0;for(let o of t)o[1]==="ok"?n++:o[1]==="FAIL"&&r++;return{runner:"go-test",passed:n,failed:r}}function C2(e){let t=e.match(b2);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10),o=t[3]!==void 0?parseInt(t[3],10):void 0;return{runner:"cargo",passed:n,failed:r,...o!==void 0?{skipped:o}:{}}}function A2(e){let t=e.match(w2);if(!t)return null;let n=parseInt(t[1]??"0",10),r=parseInt(t[2]??"0",10);return{runner:"rspec",passed:n-r,failed:r}}function _2(e){let t=e.match(S2);if(t)return{runner:"phpunit",passed:parseInt(t[1]??"0",10),failed:0};let n=e.match(v2);if(n){let r=parseInt(n[1]??"0",10),o=parseInt(n[2]??"0",10);return{runner:"phpunit",passed:r-o,failed:o}}return null}function eb(e){return k2(e)??E2(e)??T2(e)??x2(e)??R2(e)??C2(e)??A2(e)??_2(e)??null}var p2,m2,f2,g2,h2,y2,b2,w2,S2,v2,uR=R(()=>{"use strict";p2=/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/,m2=/Tests:\s+(?:(\d+)\s+failed,\s*)?(\d+)\s+passed,\s*\d+\s+total/,f2=/={3,}\s*(?:(\d+)\s+failed,\s*)?(\d+)\s+passed(?:,\s*(\d+)\s+warning)?.*in\s+[\d.]+s\s*={3,}|={3,}\s*(\d+)\s+passed.*in\s+[\d.]+s\s*={3,}/,g2=/(\d+)\s+passing/,h2=/(\d+)\s+failing/,y2=/^(ok|FAIL)\s+\S+\s+[\d.]+s/gm,b2=/test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed(?:; (\d+) ignored)?/,w2=/(\d+) examples?, (\d+) failures?/,S2=/OK \((\d+) tests?/,v2=/Tests:\s*(\d+)[^]*?Failures:\s*(\d+)/});function qo(e){return e.replace(pR,"").replace(I2," ").trim()}function yr(e){return e.replace(pR,"")}var pR,I2,zo=R(()=>{"use strict";pR=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,I2=/[\x00-\x1F\x7F-\x9F]/g});import{statSync as P2}from"node:fs";function Il(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.code==="ENOENT"&&typeof t.syscall=="string"&&t.syscall.startsWith("spawn")}function M2(e){if(e===void 0)return!1;try{return P2(e),!1}catch{return!0}}function hs(e,t){let n=e instanceof Error?e.message:typeof e?.message=="string"?String(e.message):String(e);return Il(e)&&M2(t)?`working directory does not exist: ${t} (deleted worktree?) \u2014 underlying: ${n}`:n}var tb=R(()=>{"use strict"});function O2(e,t){if(e.length<=t)return e;let n=t;for(;n>0&&(e[n]&192)===128;)n--;return e.subarray(0,n)}function $2(e,t){if(e.length<=t)return e;let n=e.length-t;for(;n<e.length&&(e[n]&192)===128;)n++;return e.subarray(n)}function Pl(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=Math.max(0,t-D2),o=Math.ceil(r/2),i=r-o,s=O2(n,o),a=$2(n,i),c=`
847
847
 
848
848
  \u2026 [${n.length-s.length-a.length} bytes truncated: showing first ${s.length} + last ${a.length} of ${n.length}] \u2026
849
849
 
@@ -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.0"}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=`
@@ -964,7 +964,7 @@ ${y.content}`,isError:!0,...y.truncated===!0?{truncated:!0}:{}}),u.push({call:h,
964
964
 
965
965
  `+a})}r&&o.push({role:"user",content:Fp});let i=r?void 0:this.activeOpenAITools(),s={controller:t,traceWriter:this.traceWriter,initSessionId:this.initSessionId,currentModel:this.currentModel,isClosed:()=>this.closed};if(this.wireMode==="responses"){let a=this.opts.auth.source==="chatgpt-oauth";if(a&&qA(this.currentModel))return yield{type:"error",error:new Error(`Model "${this.currentModel}" can't run on a ChatGPT subscription \u2014 the ChatGPT/Codex backend only supports OpenAI gpt-5.x models. This usually means a subagent or skill requested a Claude model. Pass a gpt-5.x model to it (e.g. model: "gpt-5.5"), or run it on a provider configured with the matching API key.`)},null;let l=g_({model:this.currentModel,messages:o,activeTools:i,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort,isChatGptBackend:a});return yield*pw(s,{createStream:async c=>await this.client.responses.create(l,{signal:c}),translate:(c,d)=>WA(c,d,this.initSessionId),clarifyError:c=>this.clarifyResponsesError(c,a)})}else{let a=h_({model:this.currentModel,messages:o,activeTools:i,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort});return yield*pw(s,{createStream:async l=>await this.client.chat.completions.create(a,{signal:l}),translate:(l,c)=>DA(l,c,this.initSessionId),clarifyError:l=>l instanceof Error?l:new Error(String(l))})}}async*dispatchAndAppend(t,n,r){yield*t_({state:t,signal:n,vision:r,toolDispatcher:this.toolDispatcher,traceWriter:this.traceWriter,priorTurns:this.priorTurns,sessionId:this.initSessionId})}async interrupt(){let t=this.abortController;if(t&&!t.signal.aborted){t.abort("interrupted");return}this.pendingAbortReason="interrupted"}async compact(){return this.compactHistory("manual")}async compactHistory(t){let n=this.priorTurns.length;if(this.opts.auth.apiKey===null)return{compacted:!1,reason:"no-usable-auth",messagesBefore:n,messagesAfter:n};if(this.wireMode==="responses")return{compacted:!1,reason:"unsupported-wire-mode",messagesBefore:n,messagesAfter:n};let r=k.AFK_COMPACT_MODEL??this.currentModel;return ZA({priorTurns:this.priorTurns,summarize:(o,i)=>Mp({client:this.client,model:r,system:_p,user:Ip(o),maxTokens:1024,signal:i}),isClosed:this.closed,isIdle:this.abortController===null,beginAbort:()=>{let o=new AbortController;return this.abortController=o,o},clearAbort:o=>{this.abortController===o&&(this.abortController=null)},trigger:t,traceWriter:this.traceWriter})}async setModel(t){t!==void 0&&(this.currentModel=Et(t)??t)}async setPermissionMode(t){this.currentPermissionMode=lw(t);let n=Dn(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(t){this.toolDispatcher?.setResolveBase?.(t)}async supportedCommands(){return Wp()}async supportedModels(){return[{value:"gpt-5.6",displayName:"GPT-5.6 (Sol)",description:"OpenAI flagship \u2014 alias for gpt-5.6-sol"},{value:"gpt-5.6-sol",displayName:"GPT-5.6 Sol",description:"Frontier capability"},{value:"gpt-5.6-terra",displayName:"GPT-5.6 Terra",description:"Balanced intelligence/cost"},{value:"gpt-5.6-luna",displayName:"GPT-5.6 Luna",description:"Fast, high-volume workloads"},{value:"gpt-5.5",displayName:"GPT-5.5",description:"Prior flagship (ChatGPT backend)"},{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let t=this.lastUsage,n=Gt(this.currentModel),r;if(t&&n>0){let s=Zr(t);r=Math.min(100,Math.max(0,s/n*100))}let{totalTokens:o,apiUsage:i}=Wl(t);return{tools:[],agents:[],isAutoCompactEnabled:this.autoCompactThreshold!==void 0,apiUsage:i,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(t=>({name:t.serverName,status:t.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(t,n){return{canRewind:!1,error:`${mw} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0;let t=this.abortController;t&&!t.signal.aborted?t.abort("closed"):this.pendingAbortReason="closed",this.closeResolve?.(),W(`\u{1F7E2} ${mw}: closed`)}}});var hw,qt,VV,Jl=R(()=>{"use strict";bu();vu();_l();xu();hl();zb();jo();ln();Rn();Vb();Gn();fw();ow();dn();Xr();Hl();fw();hw="openai-compatible",qt=class{name=hw;providerOpts;memoryStore;schemas;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_presenceSessionId=null;constructor(t={}){this.providerOpts=t,this.memoryStore=t.memoryStore??new mt;let n=[...gr];t.subagentExecutor&&n.push(t.subagentExecutor.describeAgentTool?.()??Wt),t.skillExecutor&&n.push(Wo),t.composeExecutor&&n.push(Ko),t.readOnlyMemory===!0?n.push(ms):n.push(...Gr),n.push(Un);for(let r of t.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);this.schemas=n}query(t){let n=t.config,r=n.permissionMode??"default";this._currentPermissionMode=r,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,i=typeof n.model=="string"?n.model:String(n.model),s=xl({surface:this.providerOpts.surface??"cli",cwd:n.cwd??process.cwd(),modelName:i,providerName:hw,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof Kt?o.toolDefs.map(b=>b.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?Rl(this.providerOpts.tools,s):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:s,...n.isSkillDispatch?{isSkillDispatch:!0}:{},...n.isNonInteractive?{isNonInteractive:!0}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...n.planExitControls!==void 0?{planExitControls:n.planExitControls}:{}});let a={},l=n.openaiBaseUrl??this.providerOpts.baseURL;if(l!==void 0&&(a.baseURL=l),a.toolDispatcher=o,a.onPermissionMode=b=>{this._currentPermissionMode=b},this.providerOpts.mcpManager!==void 0&&(a.mcpManager=this.providerOpts.mcpManager),(n.depth===void 0||n.depth===0)&&n.parentSessionId===void 0&&n.sessionId!==void 0&&this._presenceSessionId===null){this._presenceSessionId=n.sessionId;let b=n.sessionId,w=s.getWorkspace();Cl({sessionId:b,surface:this.providerOpts.surface??"cli",actor:Kn(n.depth),cwd:n.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:hw,name:i},workspace:w,pid:process.pid}),process.once("exit",()=>{hr(b)}),process.once("SIGINT",()=>{hr(b),process.exit(130)}),process.once("SIGTERM",()=>{hr(b),process.exit(143)})}let d=Tl({cwd:n.cwd??process.cwd(),...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:s.getWorkspace()}),u=vp(n.isSkillDispatch),m=kp(this.providerOpts.readOnlyMemory),p=this.providerOpts.skillExecutor?Kp():"",g=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,h=[u,m,d];p.length>0&&h.push(p),g!==void 0&&g.length>0&&h.push(g);let y={...n,systemPrompt:h.join(`
966
966
 
967
- `)};return b_(y,t.prompt,a)}buildDispatcher(t,n){let r=wp(t,n.cwd),o=El(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[d,u]of o)this.providerOpts.readOnlyMemory===!0&&d!=="memory_search"||r.set(d,u);n.runtimeStateSource&&r.set("get_runtime_state",fs(n.runtimeStateSource));for(let d of this.providerOpts.customTools??[])r.has(d.schema.name)||r.set(d.schema.name,d.handler);let i=n.planExitControls;i&&r.set(Ht,fu(i));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[d,u]of this.providerOpts.mcpManager.getMcpHandlers())r.set(d,u);let a=n.isSkillDispatch?this.schemas.filter(d=>d.name!=="ask_question"&&d.name!=="terminal_font_size"):n.isNonInteractive?this.schemas.filter(d=>d.name!=="ask_question"):this.schemas,l={handlers:r,schemas:[...a,...s,...i?[mu]:[]],hookRegistry:yu(n.hookRegistry,this.providerOpts.hookRegistry)},c=Su(this.providerOpts.mcpManager?wu(this.providerOpts.permissions,this.providerOpts.mcpManager.getMcpToolWireNames()):this.providerOpts.permissions,(this.providerOpts.customTools??[]).map(d=>d.schema.name));return c!==void 0&&(l.permissions=c),this.providerOpts.subagentExecutor!==void 0&&(l.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(l.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(l.composeExecutor=this.providerOpts.composeExecutor),this.providerOpts.canUseTool!==void 0&&(l.canUseTool=this.providerOpts.canUseTool),n.cwd!==void 0&&(l.cwd=n.cwd),n.readRoots!==void 0&&(l.readRoots=n.readRoots),n.writeRoots!==void 0&&(l.writeRoots=n.writeRoots),n.sessionId!==void 0&&(l.sessionId=n.sessionId),n.parentSessionId!==void 0&&(l.parentSessionId=n.parentSessionId),n.traceWriter!==void 0&&(l.traceWriter=n.traceWriter),this.providerOpts.readOnlyBash===!0&&(l.readOnlyBash=!0),l.allowAll=Dn(t),new Kt(l)}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t)}}grantManager=new Kr({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Dn(this._currentPermissionMode)});addReadRoot(t,n="slash",r){this.grantManager.addReadRoot(t,n,r)}addWriteRoot(t,n="slash",r){this.grantManager.addWriteRoot(t,n,r)}revokeRoot(t,n="slash",r){this.grantManager.revokeRoot(t,n,r)}getGrants(){return this.grantManager.getGrants()}close(){this.memoryStore.close()}async complete(t){let n={model:t.model??"gpt-4o-mini",system:t.system,user:t.user,maxTokens:t.maxTokens??64};t.apiKey!==void 0&&(n.apiKey=t.apiKey);let r=t.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),t.signal&&(n.signal=t.signal),Mp(n)}},VV=new qt});function to(e,t){if(e.has(t))return!0;let n=t.charAt(0).toUpperCase()+t.slice(1);return n!==t&&e.has(n)}function qn(e){return e.startsWith("mcp__")||e.startsWith("MCP__")?"mcp":to(YV,e)?"read":to(XV,e)?"write":to(ZV,e)?"shell":to(no,e)?"subagent":to(Vl,e)?"skill":to(Yl,e)?"dag":to(QV,e)?"web":eY.has(e)?"browser":to(tY,e)?"planning":nY.has(e)?"schedule":"other"}function yw(e){return rY[e]}var YV,XV,ZV,no,Vl,Yl,Ye,QV,eY,tY,nY,w_,rY,Xl=R(()=>{"use strict";Du();YV=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search"]),XV=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size","config_set"]),ZV=new Set(["Bash","BashOutput","KillBash","bash"]),no=new Set(["Agent","Task","agent"]),Vl=new Set(["Skill","skill"]),Yl=new Set(["Compose","compose"]),Ye=new Set([...no,...Yl,...Vl]),QV=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),eY=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),tY=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),nY=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);w_=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search",...st];rY={subagent:"subagent",skill:"skill",dag:"dag"}});function Gp(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${Cs}`}var Cs,bw=R(()=>{"use strict";Cs="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function v_(e){S_.add(e)}function k_(e){return S_.has(e)}var S_,ww=R(()=>{"use strict";S_=new Set});function E_(e){Sw.add(e)}function T_(e){Sw.delete(e)}function x_(e){vw.add(e)}function R_(e){vw.delete(e)}function C_(e){for(let t of Sw)t(e)}function A_(e){for(let t of vw)t(e)}var Sw,vw,kw=R(()=>{"use strict";Sw=new Set,vw=new Set});function qp(e){return oY.has(e)}function __(e,t=iY){return e.length<=t?e:e.slice(0,t)+"\u2026"}function As(e){return e.surface!==void 0?{origin:Yr(e.surface),actor:Kn(e.depth)}:{}}var oY,iY,Ew=R(()=>{"use strict";Xr();oY=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","intent-lock","long-bash-gate","exploration-gate","irreversible-action-gate","safe-destruct","plan-probe"]);iY=240});function I_(e,t,n){let r=n&&n.trim().length>0?n.trim():"(none)";return{content:`${`[Skill "${e}" loaded into your current context \u2014 act on it now]
967
+ `)};return b_(y,t.prompt,a)}buildDispatcher(t,n){let r=wp(t,n.cwd),o=El(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[d,u]of o)this.providerOpts.readOnlyMemory===!0&&d!=="memory_search"||r.set(d,u);n.runtimeStateSource&&r.set("get_runtime_state",fs(n.runtimeStateSource));for(let d of this.providerOpts.customTools??[])r.has(d.schema.name)||r.set(d.schema.name,d.handler);let i=n.planExitControls;i&&r.set(Ht,fu(i));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[d,u]of this.providerOpts.mcpManager.getMcpHandlers())r.set(d,u);let a=n.isSkillDispatch?this.schemas.filter(d=>d.name!=="ask_question"&&d.name!=="terminal_font_size"):n.isNonInteractive?this.schemas.filter(d=>d.name!=="ask_question"):this.schemas,l={handlers:r,schemas:[...a,...s,...i?[mu]:[]],hookRegistry:yu(n.hookRegistry,this.providerOpts.hookRegistry)},c=Su(this.providerOpts.mcpManager?wu(this.providerOpts.permissions,this.providerOpts.mcpManager.getMcpToolWireNames()):this.providerOpts.permissions,(this.providerOpts.customTools??[]).map(d=>d.schema.name));return c!==void 0&&(l.permissions=c),this.providerOpts.subagentExecutor!==void 0&&(l.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(l.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(l.composeExecutor=this.providerOpts.composeExecutor),this.providerOpts.canUseTool!==void 0&&(l.canUseTool=this.providerOpts.canUseTool),n.cwd!==void 0&&(l.cwd=n.cwd),n.readRoots!==void 0&&(l.readRoots=n.readRoots),n.writeRoots!==void 0&&(l.writeRoots=n.writeRoots),n.sessionId!==void 0&&(l.sessionId=n.sessionId),n.parentSessionId!==void 0&&(l.parentSessionId=n.parentSessionId),n.traceWriter!==void 0&&(l.traceWriter=n.traceWriter),this.providerOpts.readOnlyBash===!0&&(l.readOnlyBash=!0),l.allowAll=Dn(t),l.sessionGrantManager=this,new Kt(l)}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t)}}grantManager=new Kr({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Dn(this._currentPermissionMode)});addReadRoot(t,n="slash",r){this.grantManager.addReadRoot(t,n,r)}addWriteRoot(t,n="slash",r){this.grantManager.addWriteRoot(t,n,r)}revokeRoot(t,n="slash",r){this.grantManager.revokeRoot(t,n,r)}getGrants(){return this.grantManager.getGrants()}close(){this.memoryStore.close()}async complete(t){let n={model:t.model??"gpt-4o-mini",system:t.system,user:t.user,maxTokens:t.maxTokens??64};t.apiKey!==void 0&&(n.apiKey=t.apiKey);let r=t.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),t.signal&&(n.signal=t.signal),Mp(n)}},VV=new qt});function to(e,t){if(e.has(t))return!0;let n=t.charAt(0).toUpperCase()+t.slice(1);return n!==t&&e.has(n)}function qn(e){return e.startsWith("mcp__")||e.startsWith("MCP__")?"mcp":to(YV,e)?"read":to(XV,e)?"write":to(ZV,e)?"shell":to(no,e)?"subagent":to(Vl,e)?"skill":to(Yl,e)?"dag":to(QV,e)?"web":eY.has(e)?"browser":to(tY,e)?"planning":nY.has(e)?"schedule":"other"}function yw(e){return rY[e]}var YV,XV,ZV,no,Vl,Yl,Ye,QV,eY,tY,nY,w_,rY,Xl=R(()=>{"use strict";Du();YV=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search"]),XV=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size","config_set"]),ZV=new Set(["Bash","BashOutput","KillBash","bash"]),no=new Set(["Agent","Task","agent"]),Vl=new Set(["Skill","skill"]),Yl=new Set(["Compose","compose"]),Ye=new Set([...no,...Yl,...Vl]),QV=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),eY=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),tY=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),nY=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);w_=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search",...st];rY={subagent:"subagent",skill:"skill",dag:"dag"}});function Gp(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${Cs}`}var Cs,bw=R(()=>{"use strict";Cs="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function v_(e){S_.add(e)}function k_(e){return S_.has(e)}var S_,ww=R(()=>{"use strict";S_=new Set});function E_(e){Sw.add(e)}function T_(e){Sw.delete(e)}function x_(e){vw.add(e)}function R_(e){vw.delete(e)}function C_(e){for(let t of Sw)t(e)}function A_(e){for(let t of vw)t(e)}var Sw,vw,kw=R(()=>{"use strict";Sw=new Set,vw=new Set});function qp(e){return oY.has(e)}function __(e,t=iY){return e.length<=t?e:e.slice(0,t)+"\u2026"}function As(e){return e.surface!==void 0?{origin:Yr(e.surface),actor:Kn(e.depth)}:{}}var oY,iY,Ew=R(()=>{"use strict";Xr();oY=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","intent-lock","long-bash-gate","exploration-gate","irreversible-action-gate","safe-destruct","plan-probe"]);iY=240});function I_(e,t,n){let r=n&&n.trim().length>0?n.trim():"(none)";return{content:`${`[Skill "${e}" loaded into your current context \u2014 act on it now]
968
968
  The instructions below are your operating procedure for THIS task. Execute them immediately, in this session, using the tools you already have. This is an instruction set, not reference material: follow it directly \u2014 do not merely summarize or describe it. No sub-agent was forked; you are the one carrying it out.
969
969
  Arguments: ${r}`}
970
970
 
@@ -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}
@@ -1335,7 +1335,7 @@ ${t.body}`)}var Z4,nS=R(()=>{"use strict";Z4=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
1335
1335
  `;process.stderr.write(c)}}var y5,b5,w5,Ys=R(()=>{"use strict";q();y5=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
1336
1336
  `,b5=/key|token|secret|password|credential|auth/i,w5=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,e=>`<REDACTED sk-ant length=${e[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,e=>`<REDACTED sk- length=${e[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,e=>`<REDACTED Bearer length=${e[0].length}>`],[/AKIA[A-Z0-9]{16}/g,e=>`<REDACTED AKIA length=${e[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,e=>`<REDACTED xox token length=${e[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,e=>`<REDACTED Telegram token length=${e[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,e=>`${e[1]}=<REDACTED length=${e[2].length}>`],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,e=>`${e[1]}=<REDACTED length=${e[2].length}>`]]});function pM(e){let t=typeof e.baseUrl=="string"&&e.baseUrl.length>0,n=t?e.apiKey&&e.apiKey.length>0?e.apiKey:k.AFK_LOCAL_API_KEY||"local":e.apiKey&&e.apiKey.length>0?e.apiKey:k.ANTHROPIC_API_KEY||k.CLAUDE_CODE_OAUTH_TOKEN||"";return{localMode:t,token:n}}var mM=R(()=>{"use strict";q()});function fM(e){if((e.depth===void 0||e.depth===0)&&e.parentSessionId===void 0&&e.sessionId!==void 0&&e.currentPresenceSessionId===null){let n=e.sessionId,r=e.runtimeStateSource.getWorkspace();return Cl({sessionId:n,surface:e.surface,actor:Kn(e.depth),cwd:e.cwd??process.cwd(),startedAt:new Date().toISOString(),model:{provider:e.providerName,name:e.model},workspace:r,pid:process.pid}),process.once("exit",()=>{hr(n)}),process.once("SIGINT",()=>{hr(n),process.exit(130)}),process.once("SIGTERM",()=>{hr(n),process.exit(143)}),n}return e.currentPresenceSessionId}var gM=R(()=>{"use strict";dn();Xr()});function hM(e){let t=[e.toolBase,e.memoryPrompt];return e.manifest.length>0&&t.push(e.manifest),e.userSystem&&t.push(e.userSystem),t}function _m(e,t,n){return[e[0],e[1],Tl({cwd:t,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:n.surface,...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:n.workspace}),...e.slice(2)].join(`
1337
1337
 
1338
- `)}var yS=R(()=>{"use strict";dn()});function yM(e){return t=>{let n=e.getCurrentCwd();if(e.sharedReadRoots&&n!==void 0&&n!==t){let i=e.sharedReadRoots.indexOf(n);i!==-1?e.sharedReadRoots[i]=t:e.sharedReadRoots.includes(t)||e.sharedReadRoots.push(t)}if(e.sharedWriteRoots&&n!==void 0&&n!==t){let i=e.sharedWriteRoots.indexOf(n);i!==-1?e.sharedWriteRoots[i]=t:e.sharedWriteRoots.includes(t)||e.sharedWriteRoots.push(t)}e.setCurrentCwd(t),e.subagentExecutor?.setCwd(t),e.skillExecutor?.setCwd(t),e.composeExecutor?.setCwd(t);let r=_m(e.stableSystemPrefix,t,{surface:e.surface,sessionId:e.config.sessionId,depth:e.config.depth,maxDepth:e.config.maxDepth,workspace:e.runtimeStateSource.getWorkspace()}),o=e.buildDispatcher(e.getCurrentPermissionMode(),{cwd:t,readRoots:e.sharedReadRoots,writeRoots:e.sharedWriteRoots,...e.config.env!==void 0?{env:e.config.env}:{},sessionId:e.config.sessionId,parentSessionId:e.config.parentSessionId,traceWriter:e.config.traceWriter,runtimeStateSource:e.runtimeStateSource,hookRegistry:e.config.hookRegistry,planExitControls:e.config.planExitControls});return{userSystem:r,dispatcher:o}}}var bM=R(()=>{"use strict";yS()});import wM from"@anthropic-ai/sdk";function k5(e){if(e===void 0)return null;if(typeof e=="string")return e.length>0?e:null;if(typeof e=="object"&&e!==null&&"append"in e){let t=e.append;return t&&t.length>0?t:null}return null}var fc,SM,bS,tt,E5,li=R(()=>{"use strict";Vi();Xd();HT();ts();cM();hl();gS();gS();_l();xu();zb();jo();ln();Vb();vu();bu();vn();Gn();Rn();Ys();q();mM();dn();gM();bM();yS();fc="anthropic-direct",SM="claude-sonnet-5",bS=null,tt=class{name=fc;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;composeExecutor;surface;readOnlyMemory;readOnlyBash;mcpManager;customTools;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;constructor(t={}){let n=[...gr];t.subagentExecutor&&n.push(t.subagentExecutor.describeAgentTool?.()??Wt),t.skillExecutor&&n.push(Wo),t.composeExecutor&&n.push(Ko),t.readOnlyMemory===!0?n.push(ms):n.push(...Gr),n.push(Un);for(let r of t.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);if(this.memoryStore=t.memoryStore??new mt,this.externalTools=t.tools,this.skillExecutor=t.skillExecutor,this.schemas=n,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,this.subagentExecutor=t.subagentExecutor,this.composeExecutor=t.composeExecutor,this.surface=t.surface??"cli",this.readOnlyMemory=t.readOnlyMemory===!0,this.readOnlyBash=t.readOnlyBash===!0,this.customTools=t.customTools??[],this.mcpManager=t.mcpManager,t.mcpManager){let r=t.mcpManager.onToolsRefreshed;t.mcpManager.onToolsRefreshed=o=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,r?.(o)}}t.clientFactory&&(this.providerFactory=t.clientFactory)}buildDispatcher(t,n){let r=wp(t,n?.cwd),o=El(this.memoryStore,void 0,this.surface);for(let[a,l]of o)this.readOnlyMemory&&a!=="memory_search"||r.set(a,l);n?.runtimeStateSource&&r.set("get_runtime_state",fs(n.runtimeStateSource));for(let a of this.customTools)r.has(a.schema.name)||r.set(a.schema.name,a.handler);if(this.mcpManager){this._mcpToolsCache||(this._mcpToolsCache=this.mcpManager.getMcpTools()),this._mcpHandlersCache||(this._mcpHandlersCache=this.mcpManager.getMcpHandlers());for(let[a,l]of this._mcpHandlersCache)r.set(a,l)}let i=this._mcpToolsCache??[],s=n?.planExitControls;return s&&r.set(Ht,fu(s)),new Kt({handlers:r,allowAll:Dn(t),schemas:[...this.schemas,...i,...s?[mu]:[]],hookRegistry:yu(n?.hookRegistry,this.hookRegistry),permissions:Su(this.mcpManager?wu(this.permissions,this.mcpManager.getMcpToolWireNames()):this.permissions,this.customTools.map(a=>a.schema.name)),subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,...this.canUseTool!==void 0?{canUseTool:this.canUseTool}:{},cwd:n?.cwd,readRoots:n?.readRoots,writeRoots:n?.writeRoots,...n?.env!==void 0?{env:n.env}:{},sessionId:n?.sessionId,parentSessionId:n?.parentSessionId,...n?.traceWriter?{traceWriter:n.traceWriter}:{},readOnlyBash:this.readOnlyBash})}close(){this.memoryStore.close()}async complete(t){let n=t.apiKey&&t.apiKey.length>0?t.apiKey:k.ANTHROPIC_API_KEY||k.CLAUDE_CODE_OAUTH_TOKEN||"";if(!n)throw new Error(`${fc} complete() requires an API key or OAuth token (config apiKey, ANTHROPIC_API_KEY, or CLAUDE_CODE_OAUTH_TOKEN)`);let r={token:n,model:t.model??SM,system:t.system,user:t.user,maxTokens:t.maxTokens??64};t.signal&&(r.signal=t.signal);let o=this.providerFactory??bS;return o&&(r.clientFactory=o),es(r)}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t),t&&!this._currentCwd&&(this._currentCwd=t)}}grantManager=new Kr({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Dn(this._currentPermissionMode)});addReadRoot(t,n="slash",r){this.grantManager.addReadRoot(t,n,r)}addWriteRoot(t,n="slash",r){this.grantManager.addWriteRoot(t,n,r)}revokeRoot(t,n="slash",r){this.grantManager.revokeRoot(t,n,r)}getGrants(){return this.grantManager.getGrants()}query(t){let n=t.config,{localMode:r,token:o}=pM(n);if(!o||o.length===0)throw new Error(`${fc} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let i=zd(o),s=fl(o,i,n.baseUrl,!r&&n.traceWriter?sy(n.traceWriter):void 0),a=this.providerFactory??bS,l=a?a(s):new wM(s),c=r?null:TT(i),d=k5(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?Et(n.model)??n.model:SM,m=pS(n,u),p=n.permissionMode??"default";this._currentPermissionMode=p,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let g,h=xl({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:u,providerName:fc,permissionMode:p,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>g instanceof Kt?g.toolDefs.map(F=>F.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});this._presenceSessionId=fM({depth:n.depth,parentSessionId:n.parentSessionId,sessionId:n.sessionId,currentPresenceSessionId:this._presenceSessionId,runtimeStateSource:h,surface:this.surface,cwd:n.cwd,providerName:fc,model:u}),g=this.externalTools?Rl(this.externalTools,h):this.buildDispatcher(p,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:h,hookRegistry:n.hookRegistry,planExitControls:n.planExitControls});let y=g instanceof Kt?[...g.toolDefs]:[...gr,Un],b=n.isSkillDispatch?y.filter(F=>F.name!=="ask_question"&&F.name!=="terminal_font_size"):n.isNonInteractive?y.filter(F=>F.name!=="ask_question"):y,w=n.cwd||process.cwd(),v=this.skillExecutor?Kp(void 0,{cwd:w}):"",S=vp(n.isSkillDispatch),E=kp(this.readOnlyMemory),x={surface:this.surface,sessionId:n.sessionId,depth:n.depth,maxDepth:n.maxDepth,workspace:h.getWorkspace()},C=hM({toolBase:S,memoryPrompt:E,manifest:v,userSystem:d}),A=_m(C,w,x);uM({prompt:t.prompt,options:{model:u,maxTokens:m,system:A},provenance:{systemPrompt:{source:n.systemPromptSource??"none",shape:typeof n.systemPrompt=="string"?"string":Array.isArray(n.systemPrompt)?"string[]":n.systemPrompt!=null?"preset":"undefined",...typeof n.systemPrompt=="string"?{length:n.systemPrompt.length}:{}},...n.apiKey?{apiKey:{source:"config"}}:{}}});let N;if(i==="oauth"&&!r){let F=this.providerFactory??bS;N=async()=>{let U=await ry();if(!U)return null;let H=fl(U,"oauth",n.baseUrl,n.traceWriter?sy(n.traceWriter):void 0);return F?F(H):new wM(H)}}let $=n.sessionId??n.resume,I=dM(n.resumeHistory),_=this.externalTools?void 0:yM({stableSystemPrefix:C,config:n,surface:this.surface,runtimeStateSource:h,getCurrentCwd:()=>this._currentCwd,setCurrentCwd:F=>{this._currentCwd=F},getCurrentPermissionMode:()=>this._currentPermissionMode,sharedReadRoots:this._sharedReadRoots,sharedWriteRoots:this._sharedWriteRoots,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,buildDispatcher:(F,U)=>this.buildDispatcher(F,U)}),D=fS(n.effort,u);return new Cm({client:l,authMode:r?"api-key":i,promptStream:t.prompt,toolDispatcher:g,...$!==void 0?{sessionId:$}:{},...I!==void 0?{initialMessages:I}:{},model:u,requestedModel:typeof n.model=="string"&&n.model.length>0?n.model:u,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:m,tools:b,userSystem:A,systemPrefix:c,tokenRefresher:N,...n.thinking!==void 0?{thinking:mS(n.thinking,m,u)}:{},...D!==void 0?{effort:D}:{},...r?{baseUrl:n.baseUrl}:{},...n.traceWriter?{traceWriter:n.traceWriter}:{},...n.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:n.autoResumeOnUsageLimit}:{},...n.maxToolUseIterations!==void 0?{maxToolUseIterations:n.maxToolUseIterations}:{},..._!==void 0?{cwdDependentsFactory:_}:{},onPermissionMode:F=>{this._currentPermissionMode=F},...this.mcpManager!==void 0?{mcpManager:this.mcpManager}:{},...Rs(n.autoCompact)!==void 0?{autoCompactThreshold:Rs(n.autoCompact)}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{}})}};E5=new tt});function x5(e){if(!e)return;let t=e.trim().toLowerCase();if(t){if(t==="anthropic"||t==="anthropic-direct")return"anthropic-direct";if(t==="openai"||t==="openai-compatible"||t==="openai-codex")return"openai-compatible"}}function re(e,t){let n=t?.explicit??k.AFK_PROVIDER,r=t?.openaiBaseUrl??k.AFK_OPENAI_BASE_URL,o=x5(n);if(o)return o;let i=ty(e,t?.slots);if(i.provider==="anthropic")return"anthropic-direct";if(i.provider==="openai")return"openai-compatible";let s=i.id.trim().toLowerCase();return s&&(T5.has(s)||s.startsWith("claude-")||s.startsWith("claude_")||s.startsWith("local-")||s.startsWith("local_"))?"anthropic-direct":s&&(s.startsWith("gpt-")||s.startsWith("gpt_")||ei(s)||s.startsWith("codex-")||s.startsWith("codex_")||s==="codex"||s.startsWith("deepseek-")||s.startsWith("deepseek_")||s.startsWith("mistral-")||s.startsWith("mistral_")||s.startsWith("mixtral-")||s.startsWith("mixtral_")||s.startsWith("llama-")||s.startsWith("llama_")||s.startsWith("qwen-")||s.startsWith("qwen_")||s.includes("/"))||i.baseUrl&&i.baseUrl.trim()||r&&r.trim()?"openai-compatible":"anthropic-direct"}function Im(e,t,n){let r=re(e,t),o=n?.customTools,i=n?.canUseTool,s={...o!==void 0&&o.length>0?{customTools:o}:{},...i!==void 0?{canUseTool:i}:{}};switch(r){case"openai-compatible":case"openai-codex":return new qt(s);default:return new tt(s)}}var T5,Je=R(()=>{"use strict";li();Jl();vn();Lt();Es();q();li();Jl();T5=new Set([...Object.keys(ny),"auto"])});var Xs,wS=R(()=>{"use strict";Xs=class{pendingResolve=null;bufferedMessages=[];getSessionId;constructor(t){this.getSessionId=t}pushUserMessage(t){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:t,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessages.push(t)}createIterable(){let t=this;return{[Symbol.asyncIterator](){return{next(){if(t.bufferedMessages.length>0){let n=t.bufferedMessages.shift(),r=t.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{t.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}}});function Pm(e,t){let n=t??Xi(),r=Zi(e.model,n);if(!r)return;let o=n[r],i=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"?"openai-compatible":re(e.model,t?{slots:t}:void 0);o.apiKey!==void 0?e.apiKey=o.apiKey:(i==="openai-compatible"||o.baseUrl!==void 0)&&(e.apiKey=void 0),o.baseUrl!==void 0&&(i==="openai-compatible"?e.openaiBaseUrl=o.baseUrl:e.baseUrl=o.baseUrl)}var SS=R(()=>{"use strict";Je();Lt()});function R5(e){return typeof e=="string"?e:e.map(t=>{let n=t;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(t=>t.length>0).join(`
1338
+ `)}var yS=R(()=>{"use strict";dn()});function yM(e){return t=>{let n=e.getCurrentCwd();if(e.sharedReadRoots&&n!==void 0&&n!==t){let i=e.sharedReadRoots.indexOf(n);i!==-1?e.sharedReadRoots[i]=t:e.sharedReadRoots.includes(t)||e.sharedReadRoots.push(t)}if(e.sharedWriteRoots&&n!==void 0&&n!==t){let i=e.sharedWriteRoots.indexOf(n);i!==-1?e.sharedWriteRoots[i]=t:e.sharedWriteRoots.includes(t)||e.sharedWriteRoots.push(t)}e.setCurrentCwd(t),e.subagentExecutor?.setCwd(t),e.skillExecutor?.setCwd(t),e.composeExecutor?.setCwd(t);let r=_m(e.stableSystemPrefix,t,{surface:e.surface,sessionId:e.config.sessionId,depth:e.config.depth,maxDepth:e.config.maxDepth,workspace:e.runtimeStateSource.getWorkspace()}),o=e.buildDispatcher(e.getCurrentPermissionMode(),{cwd:t,readRoots:e.sharedReadRoots,writeRoots:e.sharedWriteRoots,...e.config.env!==void 0?{env:e.config.env}:{},sessionId:e.config.sessionId,parentSessionId:e.config.parentSessionId,traceWriter:e.config.traceWriter,runtimeStateSource:e.runtimeStateSource,hookRegistry:e.config.hookRegistry,planExitControls:e.config.planExitControls});return{userSystem:r,dispatcher:o}}}var bM=R(()=>{"use strict";yS()});import wM from"@anthropic-ai/sdk";function k5(e){if(e===void 0)return null;if(typeof e=="string")return e.length>0?e:null;if(typeof e=="object"&&e!==null&&"append"in e){let t=e.append;return t&&t.length>0?t:null}return null}var fc,SM,bS,tt,E5,li=R(()=>{"use strict";Vi();Xd();HT();ts();cM();hl();gS();gS();_l();xu();zb();jo();ln();Vb();vu();bu();vn();Gn();Rn();Ys();q();mM();dn();gM();bM();yS();fc="anthropic-direct",SM="claude-sonnet-5",bS=null,tt=class{name=fc;externalTools;memoryStore;providerFactory;skillExecutor;schemas;hookRegistry;permissions;canUseTool;subagentExecutor;composeExecutor;surface;readOnlyMemory;readOnlyBash;mcpManager;customTools;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_currentCwd;_mcpToolsCache=null;_mcpHandlersCache=null;_presenceSessionId=null;constructor(t={}){let n=[...gr];t.subagentExecutor&&n.push(t.subagentExecutor.describeAgentTool?.()??Wt),t.skillExecutor&&n.push(Wo),t.composeExecutor&&n.push(Ko),t.readOnlyMemory===!0?n.push(ms):n.push(...Gr),n.push(Un);for(let r of t.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);if(this.memoryStore=t.memoryStore??new mt,this.externalTools=t.tools,this.skillExecutor=t.skillExecutor,this.schemas=n,this.hookRegistry=t.hookRegistry,this.permissions=t.permissions,this.canUseTool=t.canUseTool,this.subagentExecutor=t.subagentExecutor,this.composeExecutor=t.composeExecutor,this.surface=t.surface??"cli",this.readOnlyMemory=t.readOnlyMemory===!0,this.readOnlyBash=t.readOnlyBash===!0,this.customTools=t.customTools??[],this.mcpManager=t.mcpManager,t.mcpManager){let r=t.mcpManager.onToolsRefreshed;t.mcpManager.onToolsRefreshed=o=>{this._mcpToolsCache=null,this._mcpHandlersCache=null,r?.(o)}}t.clientFactory&&(this.providerFactory=t.clientFactory)}buildDispatcher(t,n){let r=wp(t,n?.cwd),o=El(this.memoryStore,void 0,this.surface);for(let[a,l]of o)this.readOnlyMemory&&a!=="memory_search"||r.set(a,l);n?.runtimeStateSource&&r.set("get_runtime_state",fs(n.runtimeStateSource));for(let a of this.customTools)r.has(a.schema.name)||r.set(a.schema.name,a.handler);if(this.mcpManager){this._mcpToolsCache||(this._mcpToolsCache=this.mcpManager.getMcpTools()),this._mcpHandlersCache||(this._mcpHandlersCache=this.mcpManager.getMcpHandlers());for(let[a,l]of this._mcpHandlersCache)r.set(a,l)}let i=this._mcpToolsCache??[],s=n?.planExitControls;return s&&r.set(Ht,fu(s)),new Kt({handlers:r,sessionGrantManager:this,allowAll:Dn(t),schemas:[...this.schemas,...i,...s?[mu]:[]],hookRegistry:yu(n?.hookRegistry,this.hookRegistry),permissions:Su(this.mcpManager?wu(this.permissions,this.mcpManager.getMcpToolWireNames()):this.permissions,this.customTools.map(a=>a.schema.name)),subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,...this.canUseTool!==void 0?{canUseTool:this.canUseTool}:{},cwd:n?.cwd,readRoots:n?.readRoots,writeRoots:n?.writeRoots,...n?.env!==void 0?{env:n.env}:{},sessionId:n?.sessionId,parentSessionId:n?.parentSessionId,...n?.traceWriter?{traceWriter:n.traceWriter}:{},readOnlyBash:this.readOnlyBash})}close(){this.memoryStore.close()}async complete(t){let n=t.apiKey&&t.apiKey.length>0?t.apiKey:k.ANTHROPIC_API_KEY||k.CLAUDE_CODE_OAUTH_TOKEN||"";if(!n)throw new Error(`${fc} complete() requires an API key or OAuth token (config apiKey, ANTHROPIC_API_KEY, or CLAUDE_CODE_OAUTH_TOKEN)`);let r={token:n,model:t.model??SM,system:t.system,user:t.user,maxTokens:t.maxTokens??64};t.signal&&(r.signal=t.signal);let o=this.providerFactory??bS;return o&&(r.clientFactory=o),es(r)}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t),t&&!this._currentCwd&&(this._currentCwd=t)}}grantManager=new Kr({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Dn(this._currentPermissionMode)});addReadRoot(t,n="slash",r){this.grantManager.addReadRoot(t,n,r)}addWriteRoot(t,n="slash",r){this.grantManager.addWriteRoot(t,n,r)}revokeRoot(t,n="slash",r){this.grantManager.revokeRoot(t,n,r)}getGrants(){return this.grantManager.getGrants()}query(t){let n=t.config,{localMode:r,token:o}=pM(n);if(!o||o.length===0)throw new Error(`${fc} provider requires config.apiKey (resolved from ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN)`);let i=zd(o),s=fl(o,i,n.baseUrl,!r&&n.traceWriter?sy(n.traceWriter):void 0),a=this.providerFactory??bS,l=a?a(s):new wM(s),c=r?null:TT(i),d=k5(n.systemPrompt),u=typeof n.model=="string"&&n.model.length>0?Et(n.model)??n.model:SM,m=pS(n,u),p=n.permissionMode??"default";this._currentPermissionMode=p,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let g,h=xl({surface:this.surface,cwd:n.cwd??process.cwd(),modelName:u,providerName:fc,permissionMode:p,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>g instanceof Kt?g.toolDefs.map(F=>F.name):[],getMcpTools:()=>this.mcpManager?.getMcpTools()??[],getSubagents:()=>this.subagentExecutor?this.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});this._presenceSessionId=fM({depth:n.depth,parentSessionId:n.parentSessionId,sessionId:n.sessionId,currentPresenceSessionId:this._presenceSessionId,runtimeStateSource:h,surface:this.surface,cwd:n.cwd,providerName:fc,model:u}),g=this.externalTools?Rl(this.externalTools,h):this.buildDispatcher(p,{cwd:n.cwd,readRoots:this._sharedReadRoots,writeRoots:this._sharedWriteRoots,...n.env!==void 0?{env:n.env}:{},sessionId:n.sessionId,parentSessionId:n.parentSessionId,traceWriter:n.traceWriter,runtimeStateSource:h,hookRegistry:n.hookRegistry,planExitControls:n.planExitControls});let y=g instanceof Kt?[...g.toolDefs]:[...gr,Un],b=n.isSkillDispatch?y.filter(F=>F.name!=="ask_question"&&F.name!=="terminal_font_size"):n.isNonInteractive?y.filter(F=>F.name!=="ask_question"):y,w=n.cwd||process.cwd(),v=this.skillExecutor?Kp(void 0,{cwd:w}):"",S=vp(n.isSkillDispatch),E=kp(this.readOnlyMemory),x={surface:this.surface,sessionId:n.sessionId,depth:n.depth,maxDepth:n.maxDepth,workspace:h.getWorkspace()},C=hM({toolBase:S,memoryPrompt:E,manifest:v,userSystem:d}),A=_m(C,w,x);uM({prompt:t.prompt,options:{model:u,maxTokens:m,system:A},provenance:{systemPrompt:{source:n.systemPromptSource??"none",shape:typeof n.systemPrompt=="string"?"string":Array.isArray(n.systemPrompt)?"string[]":n.systemPrompt!=null?"preset":"undefined",...typeof n.systemPrompt=="string"?{length:n.systemPrompt.length}:{}},...n.apiKey?{apiKey:{source:"config"}}:{}}});let N;if(i==="oauth"&&!r){let F=this.providerFactory??bS;N=async()=>{let U=await ry();if(!U)return null;let H=fl(U,"oauth",n.baseUrl,n.traceWriter?sy(n.traceWriter):void 0);return F?F(H):new wM(H)}}let $=n.sessionId??n.resume,I=dM(n.resumeHistory),_=this.externalTools?void 0:yM({stableSystemPrefix:C,config:n,surface:this.surface,runtimeStateSource:h,getCurrentCwd:()=>this._currentCwd,setCurrentCwd:F=>{this._currentCwd=F},getCurrentPermissionMode:()=>this._currentPermissionMode,sharedReadRoots:this._sharedReadRoots,sharedWriteRoots:this._sharedWriteRoots,subagentExecutor:this.subagentExecutor,skillExecutor:this.skillExecutor,composeExecutor:this.composeExecutor,buildDispatcher:(F,U)=>this.buildDispatcher(F,U)}),D=fS(n.effort,u);return new Cm({client:l,authMode:r?"api-key":i,promptStream:t.prompt,toolDispatcher:g,...$!==void 0?{sessionId:$}:{},...I!==void 0?{initialMessages:I}:{},model:u,requestedModel:typeof n.model=="string"&&n.model.length>0?n.model:u,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},maxTokens:m,tools:b,userSystem:A,systemPrefix:c,tokenRefresher:N,...n.thinking!==void 0?{thinking:mS(n.thinking,m,u)}:{},...D!==void 0?{effort:D}:{},...r?{baseUrl:n.baseUrl}:{},...n.traceWriter?{traceWriter:n.traceWriter}:{},...n.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:n.autoResumeOnUsageLimit}:{},...n.maxToolUseIterations!==void 0?{maxToolUseIterations:n.maxToolUseIterations}:{},..._!==void 0?{cwdDependentsFactory:_}:{},onPermissionMode:F=>{this._currentPermissionMode=F},...this.mcpManager!==void 0?{mcpManager:this.mcpManager}:{},...Rs(n.autoCompact)!==void 0?{autoCompactThreshold:Rs(n.autoCompact)}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{}})}};E5=new tt});function x5(e){if(!e)return;let t=e.trim().toLowerCase();if(t){if(t==="anthropic"||t==="anthropic-direct")return"anthropic-direct";if(t==="openai"||t==="openai-compatible"||t==="openai-codex")return"openai-compatible"}}function re(e,t){let n=t?.explicit??k.AFK_PROVIDER,r=t?.openaiBaseUrl??k.AFK_OPENAI_BASE_URL,o=x5(n);if(o)return o;let i=ty(e,t?.slots);if(i.provider==="anthropic")return"anthropic-direct";if(i.provider==="openai")return"openai-compatible";let s=i.id.trim().toLowerCase();return s&&(T5.has(s)||s.startsWith("claude-")||s.startsWith("claude_")||s.startsWith("local-")||s.startsWith("local_"))?"anthropic-direct":s&&(s.startsWith("gpt-")||s.startsWith("gpt_")||ei(s)||s.startsWith("codex-")||s.startsWith("codex_")||s==="codex"||s.startsWith("deepseek-")||s.startsWith("deepseek_")||s.startsWith("mistral-")||s.startsWith("mistral_")||s.startsWith("mixtral-")||s.startsWith("mixtral_")||s.startsWith("llama-")||s.startsWith("llama_")||s.startsWith("qwen-")||s.startsWith("qwen_")||s.includes("/"))||i.baseUrl&&i.baseUrl.trim()||r&&r.trim()?"openai-compatible":"anthropic-direct"}function Im(e,t,n){let r=re(e,t),o=n?.customTools,i=n?.canUseTool,s={...o!==void 0&&o.length>0?{customTools:o}:{},...i!==void 0?{canUseTool:i}:{}};switch(r){case"openai-compatible":case"openai-codex":return new qt(s);default:return new tt(s)}}var T5,Je=R(()=>{"use strict";li();Jl();vn();Lt();Es();q();li();Jl();T5=new Set([...Object.keys(ny),"auto"])});var Xs,wS=R(()=>{"use strict";Xs=class{pendingResolve=null;bufferedMessages=[];getSessionId;constructor(t){this.getSessionId=t}pushUserMessage(t){if(this.pendingResolve){let n=this.pendingResolve;this.pendingResolve=null;let r=this.getSessionId();n({content:t,...r!==void 0?{sessionId:r}:{}});return}this.bufferedMessages.push(t)}createIterable(){let t=this;return{[Symbol.asyncIterator](){return{next(){if(t.bufferedMessages.length>0){let n=t.bufferedMessages.shift(),r=t.getSessionId();return Promise.resolve({value:{content:n,...r!==void 0?{sessionId:r}:{}},done:!1})}return new Promise(n=>{t.pendingResolve=r=>n({value:r,done:!1})})},return(){return Promise.resolve({value:void 0,done:!0})}}}}}}});function Pm(e,t){let n=t??Xi(),r=Zi(e.model,n);if(!r)return;let o=n[r],i=o.provider==="anthropic"?"anthropic-direct":o.provider==="openai"?"openai-compatible":re(e.model,t?{slots:t}:void 0);o.apiKey!==void 0?e.apiKey=o.apiKey:(i==="openai-compatible"||o.baseUrl!==void 0)&&(e.apiKey=void 0),o.baseUrl!==void 0&&(i==="openai-compatible"?e.openaiBaseUrl=o.baseUrl:e.baseUrl=o.baseUrl)}var SS=R(()=>{"use strict";Je();Lt()});function R5(e){return typeof e=="string"?e:e.map(t=>{let n=t;return n.type==="text"&&typeof n.text=="string"?n.text:""}).filter(t=>t.length>0).join(`
1339
1339
  `)}var Mm,vM=R(()=>{"use strict";wS();SS();ve();Mm=class{outerIterator;baseConfig;deps;currentModel;currentPermissionMode;currentCwd;startupFamily;active;activeModel;closed=!1;shadowHistory;pendingUserText;pendingAssistantText="";lastSessionId;constructor(t,n){this.outerIterator=t.prompt[Symbol.asyncIterator](),this.baseConfig=t.config,this.deps=n,this.currentModel=typeof t.config.model=="string"?t.config.model:void 0,this.currentPermissionMode=t.config.permissionMode,this.currentCwd=t.config.cwd,this.startupFamily=n.providerNameForModel(this.currentModel),this.shadowHistory=[...t.config.resumeHistory??[]]}resolveInner(t){let n=this.deps.resolveProvider(t),r={...this.baseConfig};r.model=t??this.baseConfig.model;let o=n.name===this.startupFamily&&this.baseConfig.apiKey!==void 0?this.baseConfig.apiKey:this.deps.resolveApiKey(t);o!==void 0?r.apiKey=o:delete r.apiKey,Pm(r);let i=[n.name,r.baseUrl??"",r.openaiBaseUrl??"",r.apiKey??""].join("\0");return{provider:n,innerConfig:r,signature:i}}buildInner(t,n){let{provider:r,innerConfig:o,signature:i}=this.resolveInner(t),s=new Xs(()=>this.lastSessionId);this.currentPermissionMode!==void 0&&(o.permissionMode=this.currentPermissionMode),this.currentCwd!==void 0&&(o.cwd=this.currentCwd),n&&(o.resumeHistory=[...this.shadowHistory]);let a=r.query({prompt:s.createIterable(),config:o});return{family:r.name,signature:i,query:a,iterator:a[Symbol.asyncIterator](),input:s}}async closeActive(){let t=this.active;if(t){this.active=void 0;try{await t.iterator.return?.(void 0)}catch{}try{await t.query.close()}catch{}}}observeEvent(t){t.type==="assistant.message"&&(this.pendingAssistantText+=(this.pendingAssistantText?`
1340
1340
  `:"")+t.text)}commitShadowTurn(){this.pendingUserText!==void 0&&(this.shadowHistory.push({user:this.pendingUserText,assistant:this.pendingAssistantText}),this.pendingUserText=void 0,this.pendingAssistantText="")}async*[Symbol.asyncIterator](){try{for(this.active=this.buildInner(this.currentModel,!1),this.activeModel=this.currentModel,yield*this.driveUntilInit(!1);!this.closed;){let t=await this.outerIterator.next();if(t.done)break;let n=t.value;this.lastSessionId=n.sessionId;let r=this.currentModel!==this.activeModel,o=!this.active||r&&this.resolveInner(this.currentModel).signature!==this.active.signature;if(this.activeModel=this.currentModel,o&&(await this.closeActive(),this.active=this.buildInner(this.currentModel,!0),W(`\u{1F500} ProviderRouter: switched inner provider \u2192 ${this.active.family} (model=${this.currentModel})`),yield*this.driveUntilInit(!0)))break;for(this.pendingUserText=R5(n.content),this.pendingAssistantText="",this.active.input.pushUserMessage(n.content);;){let i=await this.active.iterator.next();if(i.done){this.closed=!0;break}let s=i.value;if(this.observeEvent(s),yield s,s.type==="turn.completed"){this.commitShadowTurn();break}if(s.type==="error"){this.commitShadowTurn();break}}}}finally{await this.closeActive()}}async*driveUntilInit(t){for(;;){let n=await this.active.iterator.next();if(n.done)return yield{type:"error",error:new Error("provider ended before initialization")},this.closed=!0,!0;let r=n.value;if(r.type==="session.init")return t||(yield r),!1;if(r.type==="error")return yield r,this.closed=!0,!0;yield r}}async interrupt(){await this.active?.query.interrupt()}async setModel(t){typeof t=="string"&&t.length>0&&(this.currentModel=t,this.active&&this.resolveInner(t).signature===this.active.signature&&await this.active.query.setModel(t))}async setPermissionMode(t){this.currentPermissionMode=t,await this.active?.query.setPermissionMode(t)}setCwd(t){this.currentCwd=t,this.active?.query.setCwd?.(t)}async reauth(){return await this.active?.query.reauth?.()??null}async supportedCommands(){return await this.active?.query.supportedCommands()??[]}async supportedModels(){return await this.active?.query.supportedModels()??[]}async supportedAgents(){return await this.active?.query.supportedAgents()??[]}async getContextUsage(){return await this.active?.query.getContextUsage()??{}}async mcpServerStatus(){return await this.active?.query.mcpServerStatus()??[]}async accountInfo(){return await this.active?.query.accountInfo()??{}}async rewindFiles(t,n){let r=this.active;return r?r.query.rewindFiles(t,n):{canRewind:!1,error:"no active provider"}}async compact(){let t=this.active;return t?.query.compact?t.query.compact():{compacted:!1,reason:"provider does not support compaction",messagesBefore:0,messagesAfter:0}}async reloadPlugins(...t){let n=this.active?.query;if(n&&typeof n.reloadPlugins=="function")return n.reloadPlugins(...t)}async close(){this.closed=!0,await this.closeActive()}}});async function Om(e,t,n){if(!e)return;if(n.kind==="blocked"){await wn(e,{hookEvent:t,decision:"block",...n.err.reason!==void 0?{reason:n.err.reason}:{}});return}let r=n.decision;await wn(e,{hookEvent:t,decision:r.decision,...r.reason!==void 0?{reason:r.reason}:{},...r.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(r.injectContext,"utf8")}:{}})}async function kM(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Om(n.traceWriter,"SessionStart",{kind:"decision",decision:r})}catch(r){throw r instanceof me&&await Om(n.traceWriter,"SessionStart",{kind:"blocked",err:r}),r}}async function EM(e,t,n={}){if(e)try{let r=await e.dispatch(t,n.signal);await Om(n.traceWriter,"SessionEnd",{kind:"decision",decision:r})}catch(r){if(r instanceof me&&await Om(n.traceWriter,"SessionEnd",{kind:"blocked",err:r}),r instanceof me||r instanceof ut){W(`SessionEnd hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}W(`SessionEnd hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var TM=R(()=>{"use strict";ve();pt();xe()});function ci(e){return e==="abort"?vS:null}var vS,$m=R(()=>{"use strict";vS="Session ended via abort before reaching a terminal state. The transcript and witness trace are preserved \u2014 resume with `afk --resume <sessionId>` to continue from saved state, or re-run the task if the interruption was intentional."});function C5(e){return e==="max_tokens"||e==="length"}function xM(e){return e.maxTurnsHit?"max_turns_exceeded":e.hookBlocked?"hook_blocked":e.dispatchReason==="error"?"abort":e.abort!==null?e.abort:e.sawProviderError?"abort":e.lastStopReason==="tool_use_loop_capped"?"iteration_cap":C5(e.lastStopReason)?"truncated":"model_end_turn"}var RM=R(()=>{"use strict"});function A5(e){let t=null,n=e.signal;if(n.aborted&&n.reason!=="closed"){let r=n.reason;r instanceof Lr?t="budget_exceeded":r instanceof tn?t="timeout":typeof r=="string"&&r.startsWith("Budget ")?t="budget_exceeded":typeof r=="string"&&r.includes("timed out")?t="timeout":t="abort"}return xM({dispatchReason:e.dispatchReason,maxTurnsHit:e.maxTurnsHit,hookBlocked:e.hookBlocked,abort:t,lastStopReason:e.lastStopReason,sawProviderError:e.sawProviderError})}function _5(e){if(e.dispatchReason==="error")return"failed";let t=e.signal;return t.aborted&&t.reason!=="closed"?"cancelled":e.sawProviderError?"failed":"succeeded"}async function CM(e,t){if(!e)return;let n=A5(t),r={},o=t.runningTokens;o.input>0&&(r.input=o.input),o.output>0&&(r.output=o.output),o.cacheRead>0&&(r.cacheRead=o.cacheRead),o.cacheCreation>0&&(r.cacheCreation=o.cacheCreation);let i=ci(n);await kT(e,{reason:n,finalTurnCount:t.finalTurnCount,finalCostUsd:t.finalCostUsd,finalTokens:r,...t.lastStopReason!==void 0?{lastStopReason:t.lastStopReason}:{},...i!==null?{guidance:i}:{}})}async function AM(e,t){if(!e)return;let n=_5(t),r=t.subagentCompletedCount>0?t.subagentCompletedCount:void 0,o=t.subagentRunningTokens,s=o.input>0||o.output>0||o.cacheRead>0||o.cacheCreation>0?{...o.input>0?{input:o.input}:{},...o.output>0?{output:o.output}:{},...o.cacheRead>0?{cacheRead:o.cacheRead}:{},...o.cacheCreation>0?{cacheCreation:o.cacheCreation}:{}}:void 0,a=t.subagentRunningCostUsd>0?t.subagentRunningCostUsd:void 0;await e.seal({status:n,finalCostUsd:t.finalCostUsd,finalTurnCount:t.finalTurnCount,closedAt:new Date().toISOString(),...r!==void 0?{subagentCount:r}:{},...s!==void 0?{subagentTokens:s}:{},...a!==void 0?{subagentCostUsd:a}:{}})}var _M=R(()=>{"use strict";pt();xe();$m();RM()});import*as Zs from"node:fs";import*as Qs from"node:fs/promises";import*as PM from"node:readline";function Dm(e,t){return e.length>t?`${e.slice(0,t)}\u2026 [truncated]`:e}function I5(e){switch(e.type){case"message":return e.message.role!=="assistant"||!e.message.content?null:{kind:"assistant",text:Dm(e.message.content,MM)};case"chunk":{let t=e.chunk;return t.type==="tool_use_detail"?{kind:"tool",toolName:t.toolName,input:Dm(t.toolInput,IM)}:t.type==="tool_result"&&t.isError===!0?{kind:"tool_error",content:Dm(t.content,IM)}:null}case"done":{let t=e.metadata?.totalCostUsd,n=e.metadata?.durationMs;return{kind:"done",...typeof t=="number"?{costUsd:t}:{},...typeof n=="number"?{durationMs:n}:{}}}case"error":return{kind:"error",message:e.error.message};case"paused":return{kind:"paused",...e.resetsAt?{resetsAt:e.resetsAt.toISOString()}:{}};case"resumed":return{kind:"resumed"};default:return null}}function OM(e){let t=e.trim();if(!t)return null;try{let n=JSON.parse(t);return n.v!==1||typeof n.ts!="number"||typeof n.kind!="string"?null:n}catch{return null}}async function*$M(e){if(!ll(e))return;let t;try{t=await Qs.open(Dd(e),"r")}catch(n){if(n.code==="ENOENT")return;throw n}try{let n=PM.createInterface({input:t.createReadStream({encoding:"utf8"}),crlfDelay:1/0});for await(let r of n){let o=OM(r);o&&(yield o)}}finally{await t.close()}}async function*kS(e,t){if(!ll(e))return;let n=Dd(e),r=cl(e),{fromStart:o=!1,signal:i}=t??{},s=0,a="",l=!1;async function*c(){let p=null;try{p=await Qs.open(n,"r");let g=await p.stat();if(g.size<=s)return;let h=g.size-s,y=Buffer.allocUnsafe(h),{bytesRead:b}=await p.read(y,0,h,s);if(b===0)return;s+=b,a+=y.toString("utf8",0,b);let w=a.split(`
1341
1341
  `);a=w.pop()??"";for(let v of w){let S=OM(v);if(S&&(S.kind==="closed"&&(l=!0),yield S,l))return}}catch(g){g.code!=="ENOENT"&&process.stderr.write(`[afk] session-ledger: tail read error for ${e}: ${String(g)}
@@ -1443,12 +1443,12 @@ ${S.map(A=>`> - ${A}`).join(`
1443
1443
  `)){let r=n.trim();if(r!=="")try{let o=JSON.parse(r);BX(o)&&t.push(o)}catch{}}return t}function BX(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&typeof t.ts=="string"&&"payload"in t}function CS(e){let t=OX($X(e)),n=Oh();return{label:t,jsonPath:w0(n,`${t}.json`),mdPath:w0(n,`${t}.md`)}}function UX(e,t){let n={},r={},o={},i=[],s=0,a=0,l=0,c=0,d={started:0,succeeded:0,failed:0,cancelled:0},u,m,p,g,h,y,b,w,v,S,E=!1;for(let B of e)switch(n[B.kind]=(n[B.kind]??0)+1,B.kind){case"tool_call":{let P=B.payload;if(P.phase!=="completed")break;if(P.circuitBreaker===!0){c++;break}s++;let M=r[P.name]??{total:0,errored:0};if(M.total++,P.isError===!0){l++,M.errored++;let O=P.failureClass,j=O??"unclassified";o[j]=(o[j]??0)+1,i.push({toolUseId:P.toolUseId,name:P.name,...O!==void 0?{failureClass:O}:{},durationMs:P.durationMs,ts:B.ts,truncated:P.truncated===!0,exempt:O!==void 0&&FX.has(O),...P.subagentId!==void 0?{subagentId:P.subagentId}:{}})}else a++;r[P.name]=M;break}case"subagent_lifecycle":{let P=B.payload.transition;P==="started"?d.started++:P==="succeeded"?d.succeeded++:P==="failed"?d.failed++:P==="cancelled"&&d.cancelled++;break}case"closure":{let P=B.payload;u=P.reason,m=P.lastStopReason,p=P.guidance,h=P.finalCostUsd,y=P.finalTurnCount,P.finalTokens!==void 0&&(g=P.finalTokens);break}case"session_sealed":{let P=B.payload;b=P.status,w=P.finalCostUsd,v=P.finalTurnCount,S=P.closedAt,P.incomplete===!0&&(E=!0);break}default:break}let x=i.filter(B=>!B.exempt).length,C=LX.reduce((B,P)=>B+(o[P]??0),0),A=b??"unknown",N=e[0]?.ts,$=S??(e.length>0?e[e.length-1]?.ts:void 0),I;if(N!==void 0&&$!==void 0){let B=Date.parse($)-Date.parse(N);Number.isFinite(B)&&B>=0&&(I=B)}let _=w??h,D=v??y,F=[];A==="failed"?F.push('Session sealed with status "failed".'):A==="cancelled"?F.push("Session was cancelled."):A==="unknown"&&F.push("No terminal session_sealed record found \u2014 the trace may be truncated or was read before the session sealed."),E&&F.push("Trace was sealed by the process-exit backstop, indicating an abnormal exit (crash, early EOF, or process.exit())."),u!==void 0&&u!=="model_end_turn"&&F.push(`Closure reason "${u}" is not a clean completion.`),x>0&&F.push(`${x} tool call(s) returned an error (excluding expected policy/permission refusals).`),c>0&&F.push(`Repeat-loop circuit breaker fired ${c} time(s).`),d.failed>0&&F.push(`${d.failed} subagent(s) failed.`);let U=["Sourced from witness-trace metadata only: raw tool output (stdout/stderr, file contents, error messages) is NOT recorded in the trace and is therefore absent here.","Failure entries list tool name, failure class, duration, and timestamp; inspect the trace at the path above for full per-call detail."];A==="unknown"&&U.push("No session_sealed record was present when this receipt was generated.");let H={..._!==void 0?{finalCostUsd:_}:{},...D!==void 0?{turnCount:D}:{},...g!==void 0?{tokens:g}:{}};return{schemaVersion:DX,generatedAt:(t.now??new Date).toISOString(),witnessLabel:t.witnessLabel,tracePath:t.tracePath,...t.sessionId!==void 0?{sessionId:t.sessionId}:{},...t.endReason!==void 0?{endReason:t.endReason}:{},status:A,...u!==void 0?{closureReason:u}:{},...m!==void 0?{lastStopReason:m}:{},...p!==void 0?{guidance:p}:{},incomplete:E,...N!==void 0?{startedAt:N}:{},...$!==void 0?{endedAt:$}:{},...I!==void 0?{durationMs:I}:{},toolCalls:{total:s,succeeded:a,errored:l,erroredNotable:x,refused:C,circuitBreakerHits:c,byTool:r,byFailureClass:o},events:{total:e.length,byKind:n},subagents:d,cost:H,failures:i,humanReviewRequired:F.length>0,humanReviewReasons:F,limitations:U}}function jX(e){if(e<1e3)return`${e}ms`;let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=Math.round(t%60);return`${n}m${r}s`}function HX(e){let t=[];t.push(`# Run receipt \u2014 ${e.witnessLabel}`),t.push(""),t.push(`**Status:** ${e.status} \xB7 **Review required:** ${e.humanReviewRequired?"\u26A0\uFE0F YES":"\u2713 no"}`);let n=[];if(e.sessionId!==void 0&&n.push(`**Session:** ${e.sessionId}`),e.endedAt!==void 0&&n.push(`**Ended:** ${e.endedAt}`),e.durationMs!==void 0&&n.push(`**Duration:** ${jX(e.durationMs)}`),n.length>0&&t.push(n.join(" \xB7 ")),t.push(`**Trace:** \`${e.tracePath}\``),t.push(""),e.humanReviewRequired){t.push("## Why review is required");for(let o of e.humanReviewReasons)t.push(`- ${o}`);t.push("")}if(t.push("## Summary"),t.push(""),t.push("| Metric | Value |"),t.push("| --- | --- |"),t.push(`| Tool calls | ${e.toolCalls.total} |`),t.push(`| Errored | ${e.toolCalls.errored} (${e.toolCalls.erroredNotable} notable) |`),e.toolCalls.refused>0){let o=e.toolCalls.total>0?(e.toolCalls.refused/e.toolCalls.total*100).toFixed(1):"0.0";t.push(`| Refused (denylisted) | ${e.toolCalls.refused} (${o}% of calls) |`)}e.toolCalls.circuitBreakerHits>0&&t.push(`| Circuit-breaker hits | ${e.toolCalls.circuitBreakerHits} |`),e.cost.turnCount!==void 0&&t.push(`| Turns | ${e.cost.turnCount} |`),e.cost.finalCostUsd!==void 0&&t.push(`| Cost (USD) | ${e.cost.finalCostUsd.toFixed(4)} |`),e.subagents.started>0&&t.push(`| Subagents | ${e.subagents.started} started \xB7 ${e.subagents.succeeded} ok \xB7 ${e.subagents.failed} failed \xB7 ${e.subagents.cancelled} cancelled |`),e.closureReason!==void 0&&t.push(`| Closure | ${e.closureReason} |`),t.push("");let r=Object.keys(e.toolCalls.byTool).sort();if(r.length>0){t.push("## Tool calls by name"),t.push(""),t.push("| Tool | Calls | Errored |"),t.push("| --- | --- | --- |");for(let o of r){let i=e.toolCalls.byTool[o];i!==void 0&&t.push(`| ${o} | ${i.total} | ${i.errored} |`)}t.push("")}if(e.failures.length>0){t.push("## Failures"),t.push(""),t.push("| Tool | Class | Duration | When | Exempt |"),t.push("| --- | --- | --- | --- | --- |");for(let o of e.failures)t.push(`| ${o.name} | ${o.failureClass??"unclassified"} | ${o.durationMs}ms | ${o.ts} | ${o.exempt?"yes":"no"} |`);t.push("")}else t.push("No tool failures recorded."),t.push("");t.push("## Limitations"),t.push("");for(let o of e.limitations)t.push(`- ${o}`);return t.push(""),t.push("---"),t.push(`_Generated ${e.generatedAt} by the AFK run-receipt writer (read-only; no agent behavior was modified)._`),t.push(""),t.join(`
1444
1444
  `)}async function WX(e){let t;try{t=await MX(e.tracePath,"utf8")}catch{return null}let n=NX(t);if(n.length===0)return null;let r=CS(e.tracePath),o=UX(n,{tracePath:e.tracePath,witnessLabel:r.label,...e.sessionId!==void 0?{sessionId:e.sessionId}:{},...e.reason!==void 0?{endReason:e.reason}:{},...e.now!==void 0?{now:e.now}:{}});return await PX(Oh(),{recursive:!0}),await b0(r.jsonPath,JSON.stringify(o,null,2)+`
1445
1445
  `,"utf8"),await b0(r.mdPath,HX(o),"utf8"),r}var S0=async e=>{if(e.event!=="SessionEnd")return{};if(e.parentSessionId!==void 0)return{};if(k.AFK_RUN_RECEIPT_DISABLED==="1")return{};if(e.tracePath===void 0)return{};try{await WX({tracePath:e.tracePath,...e.sessionId!==void 0?{sessionId:e.sessionId}:{},...e.reason!==void 0?{reason:e.reason}:{}})}catch{}return{}};q();mr();qr();G();import{existsSync as KX,mkdirSync as GX,readFileSync as qX,renameSync as zX,writeFileSync as JX}from"fs";import{dirname as VX,isAbsolute as YX}from"path";import{randomUUID as XX}from"node:crypto";var AS={version:1,grants:[]},v0="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function ZX(e=Date.now()){let t=e,n=new Array(10).fill("0");for(let o=9;o>=0;o--)n[o]=v0[t%32],t=Math.floor(t/32);let r=new Array(16).fill("0");for(let o=0;o<16;o++)r[o]=v0[Math.floor(Math.random()*32)];return n.join("")+r.join("")}function E0(e=ol()){if(!KX(e))return AS;try{let t=qX(e,"utf8"),n=JSON.parse(t);return typeof n!="object"||n===null||!("version"in n)||n.version!==1||!("grants"in n)||!Array.isArray(n.grants)?AS:{version:1,grants:n.grants.filter(QX)}}catch(t){return console.warn(`[permissions] could not parse ${e} \u2014 treating as empty (persisted grants reset): `+(t instanceof Error?t.message:String(t))),AS}}function QX(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.path=="string"&&YX(t.path)&&(t.mode==="read"||t.mode==="write")&&(t.decision==="allow"||t.decision==="deny")&&typeof t.grantedAt=="string"&&(t.source==="elicit:repl"||t.source==="elicit:telegram"||t.source==="elicit:unknown"||t.source==="manual")}function T0(e,t=ol()){let n=E0(t),r={id:ZX(),grantedAt:e.grantedAt??new Date().toISOString(),path:e.path,mode:e.mode,decision:e.decision,source:e.source,...e.reason!==void 0?{reason:e.reason}:{},...e.expiresAt!==void 0?{expiresAt:e.expiresAt}:{}},o={version:1,grants:[...n.grants,r]};return e6(t,o),r}function k0(e,t=ol()){let n=E0(t),r=Date.now();return n.grants.filter(o=>o.decision==="allow").filter(o=>o.mode===e||e==="read"&&o.mode==="write").filter(o=>{if(o.expiresAt===void 0)return!0;let i=Date.parse(o.expiresAt);return Number.isFinite(i)?i>r:!0}).map(o=>o.path)}function x0(e,t=ol()){for(let n of k0("read",t))e.addReadRoot(n,"tool");for(let n of k0("write",t))e.addWriteRoot(n,"tool")}function e6(e,t){GX(VX(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${XX()}`;JX(n,JSON.stringify(t,null,2)+`
1446
- `,{encoding:"utf8",mode:384}),zX(n,e)}var R0=new Set(["read_file","write_file","edit_file","list_directory","glob","grep"]),C0=new Set(["write_file","edit_file"]);function _S(e,t){return`${e}:${t}`}function A0(e){let t={sessionApproved:new Set,onceApproved:new Map,inFlight:new Map};return{preToolUse:async(i,s)=>t6(e,t,i,s),postToolUse:i=>n6(e,t,i),sessionEnd:i=>r6(e,t,i)}}async function t6(e,t,n,r){if(n.event!=="PreToolUse")return{};if(!R0.has(n.toolName))return{};let o=n.input;if(!o)return{};let i=_0(n.toolName,o);if(i===void 0)return{};let s=C0.has(n.toolName)?"write":"read",a=e.getGrantManager();if(!a)return{};let l=a.getGrants(),c=e.getCwd(),d=ob(i,{cwd:c,resolveBase:l.resolveBase??c,readRoots:l.readRoots,writeRoots:l.writeRoots,...l.allowAll===!0?{allowAll:!0}:{}},s);if(!d.restricted)return{};if(n.parentSessionId!==void 0){console.error(`[path-approval] surface=${e.surface} tool=${n.toolName} path=${d.resolved} outcome=subagent-autodeny`);let g=s==="write"?`Writes are confined to this fork's granted write roots by design (worktree isolation). To allow it, the parent must re-dispatch you via the \`agent\` tool with \`writeRoots: [${JSON.stringify(d.resolved)}]\`, or perform the write itself. Return this exact path requirement to your parent.`:"Reads are confined to this fork's granted read roots. Return this exact path requirement to your parent, which owns the operator surface and can grant access (widen readRoots or re-dispatch with the path inside cwd).";return{decision:"block",reason:`Sub-agent path access denied: ${d.resolved} is outside the session's granted ${s} roots. ${g}`}}let u=_S(s,d.resolved);if(t.sessionApproved.has(u))return{};let m=t.inFlight.get(u);if(m)return m;let p=o6({toolName:n.toolName,resolvedPath:d.resolved,capturedCwd:c,mode:s,grantManager:a,state:t,surface:e.surface,...r!==void 0?{signal:r}:{}});t.inFlight.set(u,p);try{return await p}finally{t.inFlight.delete(u)}}function n6(e,t,n){if(n.event!=="PostToolUse")return{};if(!R0.has(n.toolName))return{};let r=n.input;if(!r)return{};let o=_0(n.toolName,r);if(o===void 0)return{};let i=C0.has(n.toolName)?"write":"read",s=e.getGrantManager();if(!s)return{};let a=s.getGrants(),l,c;for(let[d,u]of t.onceApproved){if(u.mode!==i)continue;let{resolved:m}=ob(o,{cwd:u.capturedCwd,resolveBase:a.resolveBase??u.capturedCwd,readRoots:a.readRoots,writeRoots:a.writeRoots},i);if(_S(i,m)===d){l=u,c=d;break}}return!l||c===void 0?{}:(s.revokeRoot(l.resolvedPath,"tool"),t.onceApproved.delete(c),{})}function r6(e,t,n){if(n.event!=="SessionEnd")return{};let r=e.getGrantManager();if(r)for(let{resolvedPath:o}of t.onceApproved.values())r.revokeRoot(o,"tool");return t.onceApproved.clear(),{}}function _0(e,t){if(e==="read_file"||e==="write_file"||e==="edit_file"){let n=t.file_path;return typeof n=="string"?n:void 0}if(e==="list_directory"){let n=t.path;return typeof n=="string"?n:void 0}if(e==="glob"||e==="grep"){let n=t.path;return typeof n=="string"?n:void 0}}async function o6(e){let{toolName:t,resolvedPath:n,capturedCwd:r,mode:o,grantManager:i,state:s,surface:a,signal:l}=e,c=bs(n),d=c!==n?`
1446
+ `,{encoding:"utf8",mode:384}),zX(n,e)}var R0=new Set(["read_file","write_file","edit_file","list_directory","glob","grep"]),C0=new Set(["write_file","edit_file"]);function _S(e,t){return`${e}:${t}`}function A0(e){let t={sessionApproved:new Set,onceApproved:new Map,inFlight:new Map};return{preToolUse:async(i,s)=>t6(e,t,i,s),postToolUse:i=>n6(e,t,i),sessionEnd:i=>r6(e,t,i)}}async function t6(e,t,n,r){if(n.event!=="PreToolUse")return{};if(!R0.has(n.toolName))return{};let o=n.input;if(!o)return{};let i=_0(n.toolName,o);if(i===void 0)return{};let s=C0.has(n.toolName)?"write":"read",a=n.grantManager??e.getGrantManager();if(!a)return{};let l=a.getGrants(),c=e.getCwd(),d=ob(i,{cwd:c,resolveBase:l.resolveBase??c,readRoots:l.readRoots,writeRoots:l.writeRoots,...l.allowAll===!0?{allowAll:!0}:{}},s);if(!d.restricted)return{};if(n.parentSessionId!==void 0){console.error(`[path-approval] surface=${e.surface} tool=${n.toolName} path=${d.resolved} outcome=subagent-autodeny`);let g=s==="write"?`Writes are confined to this fork's granted write roots by design (worktree isolation). To allow it, the parent must re-dispatch you via the \`agent\` tool with \`writeRoots: [${JSON.stringify(d.resolved)}]\`, or perform the write itself. Return this exact path requirement to your parent.`:"Reads are confined to this fork's granted read roots. Return this exact path requirement to your parent, which owns the operator surface and can grant access (widen readRoots or re-dispatch with the path inside cwd).";return{decision:"block",reason:`Sub-agent path access denied: ${d.resolved} is outside the session's granted ${s} roots. ${g}`}}let u=_S(s,d.resolved);if(t.sessionApproved.has(u))return{};let m=t.inFlight.get(u);if(m)return m;let p=o6({toolName:n.toolName,resolvedPath:d.resolved,capturedCwd:c,mode:s,grantManager:a,state:t,surface:e.surface,...r!==void 0?{signal:r}:{}});t.inFlight.set(u,p);try{return await p}finally{t.inFlight.delete(u)}}function n6(e,t,n){if(n.event!=="PostToolUse")return{};if(!R0.has(n.toolName))return{};let r=n.input;if(!r)return{};let o=_0(n.toolName,r);if(o===void 0)return{};let i=C0.has(n.toolName)?"write":"read",s=n.grantManager??e.getGrantManager();if(!s)return{};let a=s.getGrants(),l,c;for(let[d,u]of t.onceApproved){if(u.mode!==i)continue;let{resolved:m}=ob(o,{cwd:u.capturedCwd,resolveBase:a.resolveBase??u.capturedCwd,readRoots:a.readRoots,writeRoots:a.writeRoots},i);if(_S(i,m)===d){l=u,c=d;break}}return!l||c===void 0?{}:(s.revokeRoot(l.resolvedPath,"tool"),t.onceApproved.delete(c),{})}function r6(e,t,n){if(n.event!=="SessionEnd")return{};let r=e.getGrantManager();if(r)for(let{resolvedPath:o}of t.onceApproved.values())r.revokeRoot(o,"tool");return t.onceApproved.clear(),{}}function _0(e,t){if(e==="read_file"||e==="write_file"||e==="edit_file"){let n=t.file_path;return typeof n=="string"?n:void 0}if(e==="list_directory"){let n=t.path;return typeof n=="string"?n:void 0}if(e==="glob"||e==="grep"){let n=t.path;return typeof n=="string"?n:void 0}}async function o6(e){let{toolName:t,resolvedPath:n,capturedCwd:r,mode:o,grantManager:i,state:s,surface:a,signal:l}=e,c=bs(n),d=c!==n?`
1447
1447
  (resolves to: ${c})`:"",u=`Tool \`${t}\` wants to ${o==="write"?"WRITE to":"read"} a path outside this session's granted roots:
1448
1448
 
1449
1449
  ${n}${d}
1450
1450
 
1451
- Choose how to handle this and future requests for this path.`,m=await et.route({serverName:"agent-afk",message:u,mode:"form",title:"Path access approval",requestedSchema:{type:"object",properties:{choice:{type:"string",title:"Choose one",enum:["once","session","persist","deny"],description:"'once' allows this single call only. 'session' allows this path until the session ends. 'persist' writes a grant to ~/.afk/config/permissions.json so future sessions inherit it. 'deny' blocks this call and returns an error to the model."}},required:["choice"]}},{signal:l??new AbortController().signal});if(m.action!=="accept"){let h=m.action==="cancel"?"cancel":"block";return console.error(`[path-approval] surface=${a} tool=${t} path=${n} outcome=${h}`),{decision:"block",reason:m.action==="cancel"?`User cancelled the access prompt for ${n}`:`User denied access to ${n}`}}let p=String(m.content?.choice??"").toLowerCase(),g=_S(o,n);switch(p){case"once":return o==="write"?i.addWriteRoot(n,"tool"):i.addReadRoot(n,"tool"),s.onceApproved.set(g,{resolvedPath:n,mode:o,capturedCwd:r}),console.error(`[path-approval] surface=${a} tool=${t} path=${n} outcome=once`),{};case"session":return o==="write"?i.addWriteRoot(n,"tool"):i.addReadRoot(n,"tool"),s.sessionApproved.add(g),console.error(`[path-approval] surface=${a} tool=${t} path=${n} outcome=session`),{};case"persist":o==="write"?i.addWriteRoot(n,"tool"):i.addReadRoot(n,"tool"),s.sessionApproved.add(g),console.error(`[path-approval] surface=${a} tool=${t} path=${n} outcome=persist`);try{T0({path:n,mode:o,decision:"allow",source:a==="telegram"?"elicit:telegram":a==="repl"?"elicit:repl":"elicit:unknown",reason:`Approved via ${a} prompt for ${t}`})}catch(h){console.error(`path-approval: failed to persist grant for ${n}:`,h instanceof Error?h.message:String(h))}return{};default:return console.error(`[path-approval] surface=${a} tool=${t} path=${n} outcome=deny`),{decision:"block",reason:`User denied access to ${n}`}}}import{homedir as I0}from"os";import go from"path";var i6=/\b(python|python3|node|ruby|perl|osascript|sh|bash|zsh|fish|lua)\s+-[cCeE](\s|$)/,s6=/\.ssh\b|\bid_rsa\b|\bid_ed25519\b|\.gnupg\b|\.aws\b|\.config\/gh\b|\.netrc\b|\.password-store\b|Library\/Application Support\b|\/etc\/shadow\b|\/etc\/sudoers\b/i;function P0(e){return t=>{if(t.event!=="PreToolUse")return{};if(t.toolName!=="bash")return{};let n=t.input,r=typeof n?.command=="string"?n.command:"";if(!r)return{};let o=e.getGrantManager(),i=o!==void 0,s=I0(),a=a6(r,s),l=o?c6(o.getGrants()):[];if(!e.disableInterpreterGuard&&(i||e.forceInterpreterGuard===!0)&&i6.test(r)&&l6(a,r,l))return{decision:"block",reason:"Interpreter one-liner (python -c, node -e, sh -c, ...) referencing a sensitive path (SSH keys, cloud credentials, GPG, /etc/shadow, ...) is blocked by the path-approval policy \u2014 an interpreter can assemble a path the shell-substring check cannot see. Use the typed file tools (read_file, write_file, edit_file), which support per-call user approval, or ask the user to run the script themselves. To lift this block \u2014 e.g. headless automation that legitimately reads such paths \u2014 set AFK_DISABLE_BASH_INTERPRETER_GUARD=1, or disable all of path-approval with AFK_DISABLE_PATH_APPROVAL=1."};if(!o)return{};if(l.length===0)return{};for(let d of l)if(a.includes(d))return{decision:"block",reason:`Bash command references a restricted path (${d}). For sensitive paths, use read_file / write_file / edit_file \u2014 those tools support per-call user approval via an inline prompt. If you genuinely need a shell command for this path, ask the user to grant it via \`/allow-dir <path>\` first.`};return{}}}function a6(e,t){return e.replace(/\$HOME/g,t).replace(/(^|[\s/=:])~(?=$|[/\s])/g,`$1${t}`)}function l6(e,t,n){return n.some(r=>e.includes(r))?!0:s6.test(t)}function c6(e){let t=I0(),n=[go.join(t,".ssh"),go.join(t,".gnupg"),go.join(t,".aws"),go.join(t,".config","gh"),go.join(t,".netrc"),go.join(t,"Library","Application Support"),go.join(t,".password-store"),"/etc/shadow","/etc/sudoers","/private/etc/sudoers"],r=new Set([...e.resolveBase!==void 0?[e.resolveBase]:[],...e.readRoots,...e.writeRoots]);return n.filter(o=>{for(let i of r){let s=go.relative(i,o);if(s===""||!s.startsWith(".."))return!1}return!0})}G();wl();import{existsSync as $0,readFileSync as d6}from"node:fs";import{join as M0}from"node:path";var u6=3e4;function D0(e){if(e===void 0||e==="*")return()=>!0;let t=/^\/(.+)\/([gimsuy]*)$/.exec(e);if(t!==null){let n=t[1],r=t[2];try{let o=r.replace(/[gy]/g,""),i=new RegExp(n,o);return s=>i.test(s)}catch{}}return n=>n===e}function p6(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.type!=="command"||typeof t.command!="string"||t.command.length===0)return null;let n=typeof t.timeout_ms=="number"&&t.timeout_ms>0?t.timeout_ms:u6,r=Math.min(n,Ho);return{type:"command",command:t.command,timeoutMs:r}}function O0(e,t){let n=[],r=[],o={};if(!$0(e))return{hooks:o,enableShellHooks:!1,allowProjectHooks:!1,sources:r,warnings:n};r.push(e);let i;try{i=JSON.parse(d6(e,"utf-8"))}catch(m){let p=m instanceof Error?m.message:String(m);return n.push(`hooks config at ${e}: parse error \u2014 ${p}`),{hooks:o,enableShellHooks:!1,allowProjectHooks:!1,sources:r,warnings:n}}if(i===null||typeof i!="object"||Array.isArray(i))return n.push(`hooks config at ${e}: top-level must be an object`),{hooks:o,enableShellHooks:!1,allowProjectHooks:!1,sources:r,warnings:n};let s=i,a=s.enableShellHooks===!0,l=s.allowProjectHooks===!0,c=s.hooks;if(c==null)return{hooks:o,enableShellHooks:a,allowProjectHooks:l,sources:r,warnings:n};if(typeof c!="object"||Array.isArray(c))return n.push(`hooks config at ${e}: "hooks" must be an object`),{hooks:o,enableShellHooks:a,allowProjectHooks:l,sources:r,warnings:n};let d=c,u=["SessionStart","SessionEnd","SubagentStart","SubagentStop","PreToolUse","PostToolUse","PreCompact","PostToolUseFailure","Stop","UserPromptSubmit"];for(let m of u){let p=d[m];if(p===void 0)continue;if(!Array.isArray(p)){n.push(`hooks config at ${e}: hooks.${m} must be an array`);continue}let g=[];for(let h=0;h<p.length;h++){let y=p[h];if(y===null||typeof y!="object"||Array.isArray(y)){n.push(`hooks config at ${e}: hooks.${m}[${h}] must be an object \u2014 skipping`);continue}let b=y,w=typeof b.matcher=="string"?b.matcher:void 0;if(!Array.isArray(b.hooks)){n.push(`hooks config at ${e}: hooks.${m}[${h}].hooks must be an array \u2014 skipping`);continue}let v=b.hooks,S=[];for(let E=0;E<v.length;E++){let x=p6(v[E]);if(x===null){n.push(`hooks config at ${e}: hooks.${m}[${h}].hooks[${E}] is malformed (must have type="command" and non-empty command) \u2014 skipping`);continue}S.push(x)}S.length>0&&g.push({...w!==void 0?{matcher:w}:{},hooks:S,tier:t})}g.length>0&&(o[m]=g)}return{hooks:o,enableShellHooks:a,allowProjectHooks:l,sources:r,warnings:n}}function ta(e={}){let t=e.cwd??process.cwd(),n=[],r=[],o={},i=!1,s=!1,a=[{path:en(),tier:"user-global"},{path:$h(),tier:"user-global"},{path:M0(t,"afk.config.json"),tier:"project-local"},{path:WE(t),tier:"project-local"}],l=new Set,c=a.filter(u=>l.has(u.path)?!1:(l.add(u.path),!0));try{let u=M0(_e(),"settings.json");!l.has(u)&&$0(u)&&r.push(`found ${u} but AFK does not read settings from the AFK-home root; user-global hooks/settings belong in ${$h()} \u2014 the root file is ignored`)}catch{}for(let u of c){if(u.tier!=="user-global")continue;let m=O0(u.path,u.tier);m.enableShellHooks&&(i=!0),m.allowProjectHooks&&(s=!0)}let d=["SessionStart","SessionEnd","SubagentStart","SubagentStop","PreToolUse","PostToolUse","PreCompact","PostToolUseFailure","Stop","UserPromptSubmit"];for(let u of c){let m=O0(u.path,u.tier);for(let p of m.sources)n.includes(p)||n.push(p);for(let p of m.warnings)r.push(p);if(!(u.tier==="project-local"&&!s))for(let p of d){let g=m.hooks[p];if(g===void 0||g.length===0)continue;let h=o[p];h===void 0?o[p]=[...g]:o[p]=[...h,...g]}}return{hooks:o,userGlobalEnabled:i,allowProjectHooks:s,sources:n,warnings:r}}import{spawn as m6}from"node:child_process";import{homedir as f6}from"node:os";import{StringDecoder as F0}from"node:string_decoder";async function L0(e){let{context:t,agentCwd:n,sessionId:r,timeoutMs:o}=e,i=e.command.replace(/^~\//,f6()+"/"),s={session_id:r,hook_event_name:t.event,cwd:n};(t.event==="PreToolUse"||t.event==="PostToolUse"||t.event==="PostToolUseFailure")&&(s.tool_name=t.toolName),t.event==="PreToolUse"&&(s.tool_input=t.input),t.event==="PostToolUse"&&t.output!==void 0&&(s.tool_output=typeof t.output=="string"?t.output:JSON.stringify(t.output)),t.event==="PostToolUseFailure"&&(s.error=t.error),t.event==="PreCompact"&&(s.trigger=t.trigger??null),t.event==="UserPromptSubmit"&&(s.prompt=t.prompt),s.transcript_path=null;let a=JSON.stringify(s),l=t.event==="PreToolUse"||t.event==="PostToolUse"||t.event==="PostToolUseFailure"?t.toolName:"",c=["PATH","HOME","SHELL","LANG","TERM","TMPDIR","TMP","TEMP","USER","LOGNAME"],d={};for(let m of c){let p=process.env[m];p!==void 0&&(d[m]=p)}let u=/_(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|CREDENTIALS)$/i;for(let[m,p]of Object.entries(process.env))!m.startsWith("AFK_")||p===void 0||u.test(m)||(d[m]=p);return d.AFK_PROJECT_DIR=n,d.AFK_SESSION_ID=r??"",d.AFK_HOOK_EVENT=t.event,d.AFK_TOOL_NAME=l,new Promise(m=>{let p=!1;function g(A){p||(p=!0,m(A))}let h=m6("sh",["-c",i],{stdio:["pipe","pipe","pipe"],cwd:n,env:d,detached:!0});h.unref();let y=64e3,b="",w="",v=0,S=0,E=new F0("utf8"),x=new F0("utf8");h.stdout.on("data",A=>{if(v>=y)return;let N=y-v,$=A.length<=N?A:A.subarray(0,N);v+=$.length,b+=E.write($)}),h.stderr.on("data",A=>{if(S>=y)return;let N=y-S,$=A.length<=N?A:A.subarray(0,N);S+=$.length,w+=x.write($)});let C=setTimeout(()=>{if(!p){if(h.pid!==void 0)try{process.kill(-h.pid,"SIGKILL")}catch{}console.warn(`[hooks] command timed out after ${o}ms: ${i}`),g({decision:{}})}},o);C.unref(),h.stdin.on("error",()=>{});try{h.stdin.write(a),h.stdin.end()}catch{}h.on("close",A=>{if(!p){if(clearTimeout(C),b+=E.end(),w+=x.end(),A===0){let N=g6(b);g({decision:N});return}if(A===2){let N=w.trim().slice(0,500)||"hook blocked operation";g({decision:{decision:"block",reason:N}});return}console.warn(`[hooks] command exited with code ${String(A)}: ${i}${w.trim()?`
1451
+ Choose how to handle this and future requests for this path.`,m=await et.route({serverName:"agent-afk",message:u,mode:"form",title:"Path access approval",requestedSchema:{type:"object",properties:{choice:{type:"string",title:"Choose one",enum:["once","session","persist","deny"],description:"'once' allows this single call only. 'session' allows this path until the session ends. 'persist' writes a grant to ~/.afk/config/permissions.json so future sessions inherit it. 'deny' blocks this call and returns an error to the model."}},required:["choice"]}},{signal:l??new AbortController().signal});if(m.action!=="accept"){let h=m.action==="cancel"?"cancel":"block";return console.error(`[path-approval] surface=${a} tool=${t} path=${n} outcome=${h}`),{decision:"block",reason:m.action==="cancel"?`User cancelled the access prompt for ${n}`:`User denied access to ${n}`}}let p=String(m.content?.choice??"").toLowerCase(),g=_S(o,n);switch(p){case"once":return o==="write"?i.addWriteRoot(n,"tool"):i.addReadRoot(n,"tool"),s.onceApproved.set(g,{resolvedPath:n,mode:o,capturedCwd:r}),console.error(`[path-approval] surface=${a} tool=${t} path=${n} outcome=once`),{};case"session":return o==="write"?i.addWriteRoot(n,"tool"):i.addReadRoot(n,"tool"),s.sessionApproved.add(g),console.error(`[path-approval] surface=${a} tool=${t} path=${n} outcome=session`),{};case"persist":o==="write"?i.addWriteRoot(n,"tool"):i.addReadRoot(n,"tool"),s.sessionApproved.add(g),console.error(`[path-approval] surface=${a} tool=${t} path=${n} outcome=persist`);try{T0({path:n,mode:o,decision:"allow",source:a==="telegram"?"elicit:telegram":a==="repl"?"elicit:repl":"elicit:unknown",reason:`Approved via ${a} prompt for ${t}`})}catch(h){console.error(`path-approval: failed to persist grant for ${n}:`,h instanceof Error?h.message:String(h))}return{};default:return console.error(`[path-approval] surface=${a} tool=${t} path=${n} outcome=deny`),{decision:"block",reason:`User denied access to ${n}`}}}import{homedir as I0}from"os";import go from"path";var i6=/\b(python|python3|node|ruby|perl|osascript|sh|bash|zsh|fish|lua)\s+-[cCeE](\s|$)/,s6=/\.ssh\b|\bid_rsa\b|\bid_ed25519\b|\.gnupg\b|\.aws\b|\.config\/gh\b|\.netrc\b|\.password-store\b|Library\/Application Support\b|\/etc\/shadow\b|\/etc\/sudoers\b/i;function P0(e){return t=>{if(t.event!=="PreToolUse")return{};if(t.toolName!=="bash")return{};let n=t.input,r=typeof n?.command=="string"?n.command:"";if(!r)return{};let o=t.grantManager??e.getGrantManager(),i=o!==void 0,s=I0(),a=a6(r,s),l=o?c6(o.getGrants()):[];if(!e.disableInterpreterGuard&&(i||e.forceInterpreterGuard===!0)&&i6.test(r)&&l6(a,r,l))return{decision:"block",reason:"Interpreter one-liner (python -c, node -e, sh -c, ...) referencing a sensitive path (SSH keys, cloud credentials, GPG, /etc/shadow, ...) is blocked by the path-approval policy \u2014 an interpreter can assemble a path the shell-substring check cannot see. Use the typed file tools (read_file, write_file, edit_file), which support per-call user approval, or ask the user to run the script themselves. To lift this block \u2014 e.g. headless automation that legitimately reads such paths \u2014 set AFK_DISABLE_BASH_INTERPRETER_GUARD=1, or disable all of path-approval with AFK_DISABLE_PATH_APPROVAL=1."};if(!o)return{};if(l.length===0)return{};for(let d of l)if(a.includes(d))return{decision:"block",reason:`Bash command references a restricted path (${d}). For sensitive paths, use read_file / write_file / edit_file \u2014 those tools support per-call user approval via an inline prompt. If you genuinely need a shell command for this path, ask the user to grant it via \`/allow-dir <path>\` first.`};return{}}}function a6(e,t){return e.replace(/\$HOME/g,t).replace(/(^|[\s/=:])~(?=$|[/\s])/g,`$1${t}`)}function l6(e,t,n){return n.some(r=>e.includes(r))?!0:s6.test(t)}function c6(e){let t=I0(),n=[go.join(t,".ssh"),go.join(t,".gnupg"),go.join(t,".aws"),go.join(t,".config","gh"),go.join(t,".netrc"),go.join(t,"Library","Application Support"),go.join(t,".password-store"),"/etc/shadow","/etc/sudoers","/private/etc/sudoers"],r=new Set([...e.resolveBase!==void 0?[e.resolveBase]:[],...e.readRoots,...e.writeRoots]);return n.filter(o=>{for(let i of r){let s=go.relative(i,o);if(s===""||!s.startsWith(".."))return!1}return!0})}G();wl();import{existsSync as $0,readFileSync as d6}from"node:fs";import{join as M0}from"node:path";var u6=3e4;function D0(e){if(e===void 0||e==="*")return()=>!0;let t=/^\/(.+)\/([gimsuy]*)$/.exec(e);if(t!==null){let n=t[1],r=t[2];try{let o=r.replace(/[gy]/g,""),i=new RegExp(n,o);return s=>i.test(s)}catch{}}return n=>n===e}function p6(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.type!=="command"||typeof t.command!="string"||t.command.length===0)return null;let n=typeof t.timeout_ms=="number"&&t.timeout_ms>0?t.timeout_ms:u6,r=Math.min(n,Ho);return{type:"command",command:t.command,timeoutMs:r}}function O0(e,t){let n=[],r=[],o={};if(!$0(e))return{hooks:o,enableShellHooks:!1,allowProjectHooks:!1,sources:r,warnings:n};r.push(e);let i;try{i=JSON.parse(d6(e,"utf-8"))}catch(m){let p=m instanceof Error?m.message:String(m);return n.push(`hooks config at ${e}: parse error \u2014 ${p}`),{hooks:o,enableShellHooks:!1,allowProjectHooks:!1,sources:r,warnings:n}}if(i===null||typeof i!="object"||Array.isArray(i))return n.push(`hooks config at ${e}: top-level must be an object`),{hooks:o,enableShellHooks:!1,allowProjectHooks:!1,sources:r,warnings:n};let s=i,a=s.enableShellHooks===!0,l=s.allowProjectHooks===!0,c=s.hooks;if(c==null)return{hooks:o,enableShellHooks:a,allowProjectHooks:l,sources:r,warnings:n};if(typeof c!="object"||Array.isArray(c))return n.push(`hooks config at ${e}: "hooks" must be an object`),{hooks:o,enableShellHooks:a,allowProjectHooks:l,sources:r,warnings:n};let d=c,u=["SessionStart","SessionEnd","SubagentStart","SubagentStop","PreToolUse","PostToolUse","PreCompact","PostToolUseFailure","Stop","UserPromptSubmit"];for(let m of u){let p=d[m];if(p===void 0)continue;if(!Array.isArray(p)){n.push(`hooks config at ${e}: hooks.${m} must be an array`);continue}let g=[];for(let h=0;h<p.length;h++){let y=p[h];if(y===null||typeof y!="object"||Array.isArray(y)){n.push(`hooks config at ${e}: hooks.${m}[${h}] must be an object \u2014 skipping`);continue}let b=y,w=typeof b.matcher=="string"?b.matcher:void 0;if(!Array.isArray(b.hooks)){n.push(`hooks config at ${e}: hooks.${m}[${h}].hooks must be an array \u2014 skipping`);continue}let v=b.hooks,S=[];for(let E=0;E<v.length;E++){let x=p6(v[E]);if(x===null){n.push(`hooks config at ${e}: hooks.${m}[${h}].hooks[${E}] is malformed (must have type="command" and non-empty command) \u2014 skipping`);continue}S.push(x)}S.length>0&&g.push({...w!==void 0?{matcher:w}:{},hooks:S,tier:t})}g.length>0&&(o[m]=g)}return{hooks:o,enableShellHooks:a,allowProjectHooks:l,sources:r,warnings:n}}function ta(e={}){let t=e.cwd??process.cwd(),n=[],r=[],o={},i=!1,s=!1,a=[{path:en(),tier:"user-global"},{path:$h(),tier:"user-global"},{path:M0(t,"afk.config.json"),tier:"project-local"},{path:WE(t),tier:"project-local"}],l=new Set,c=a.filter(u=>l.has(u.path)?!1:(l.add(u.path),!0));try{let u=M0(_e(),"settings.json");!l.has(u)&&$0(u)&&r.push(`found ${u} but AFK does not read settings from the AFK-home root; user-global hooks/settings belong in ${$h()} \u2014 the root file is ignored`)}catch{}for(let u of c){if(u.tier!=="user-global")continue;let m=O0(u.path,u.tier);m.enableShellHooks&&(i=!0),m.allowProjectHooks&&(s=!0)}let d=["SessionStart","SessionEnd","SubagentStart","SubagentStop","PreToolUse","PostToolUse","PreCompact","PostToolUseFailure","Stop","UserPromptSubmit"];for(let u of c){let m=O0(u.path,u.tier);for(let p of m.sources)n.includes(p)||n.push(p);for(let p of m.warnings)r.push(p);if(!(u.tier==="project-local"&&!s))for(let p of d){let g=m.hooks[p];if(g===void 0||g.length===0)continue;let h=o[p];h===void 0?o[p]=[...g]:o[p]=[...h,...g]}}return{hooks:o,userGlobalEnabled:i,allowProjectHooks:s,sources:n,warnings:r}}import{spawn as m6}from"node:child_process";import{homedir as f6}from"node:os";import{StringDecoder as F0}from"node:string_decoder";async function L0(e){let{context:t,agentCwd:n,sessionId:r,timeoutMs:o}=e,i=e.command.replace(/^~\//,f6()+"/"),s={session_id:r,hook_event_name:t.event,cwd:n};(t.event==="PreToolUse"||t.event==="PostToolUse"||t.event==="PostToolUseFailure")&&(s.tool_name=t.toolName),t.event==="PreToolUse"&&(s.tool_input=t.input),t.event==="PostToolUse"&&t.output!==void 0&&(s.tool_output=typeof t.output=="string"?t.output:JSON.stringify(t.output)),t.event==="PostToolUseFailure"&&(s.error=t.error),t.event==="PreCompact"&&(s.trigger=t.trigger??null),t.event==="UserPromptSubmit"&&(s.prompt=t.prompt),s.transcript_path=null;let a=JSON.stringify(s),l=t.event==="PreToolUse"||t.event==="PostToolUse"||t.event==="PostToolUseFailure"?t.toolName:"",c=["PATH","HOME","SHELL","LANG","TERM","TMPDIR","TMP","TEMP","USER","LOGNAME"],d={};for(let m of c){let p=process.env[m];p!==void 0&&(d[m]=p)}let u=/_(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|CREDENTIALS)$/i;for(let[m,p]of Object.entries(process.env))!m.startsWith("AFK_")||p===void 0||u.test(m)||(d[m]=p);return d.AFK_PROJECT_DIR=n,d.AFK_SESSION_ID=r??"",d.AFK_HOOK_EVENT=t.event,d.AFK_TOOL_NAME=l,new Promise(m=>{let p=!1;function g(A){p||(p=!0,m(A))}let h=m6("sh",["-c",i],{stdio:["pipe","pipe","pipe"],cwd:n,env:d,detached:!0});h.unref();let y=64e3,b="",w="",v=0,S=0,E=new F0("utf8"),x=new F0("utf8");h.stdout.on("data",A=>{if(v>=y)return;let N=y-v,$=A.length<=N?A:A.subarray(0,N);v+=$.length,b+=E.write($)}),h.stderr.on("data",A=>{if(S>=y)return;let N=y-S,$=A.length<=N?A:A.subarray(0,N);S+=$.length,w+=x.write($)});let C=setTimeout(()=>{if(!p){if(h.pid!==void 0)try{process.kill(-h.pid,"SIGKILL")}catch{}console.warn(`[hooks] command timed out after ${o}ms: ${i}`),g({decision:{}})}},o);C.unref(),h.stdin.on("error",()=>{});try{h.stdin.write(a),h.stdin.end()}catch{}h.on("close",A=>{if(!p){if(clearTimeout(C),b+=E.end(),w+=x.end(),A===0){let N=g6(b);g({decision:N});return}if(A===2){let N=w.trim().slice(0,500)||"hook blocked operation";g({decision:{decision:"block",reason:N}});return}console.warn(`[hooks] command exited with code ${String(A)}: ${i}${w.trim()?`
1452
1452
  ${w.trim()}`:""}`),g({decision:{}})}}),h.on("error",A=>{p||(clearTimeout(C),console.warn(`[hooks] command error: ${i} \u2014 ${A.message}`),g({decision:{}}))})})}function g6(e){let t=e.trim();if(!t)return{};let n;try{n=JSON.parse(t)}catch{return{}}if(n===null||typeof n!="object"||Array.isArray(n))return{};let r=n,o={};r.continue===!1&&(o.continue=!1),r.decision==="block"?o.decision="block":r.decision==="approve"&&(o.decision="approve"),typeof r.reason=="string"&&(o.reason=r.reason);let i=r.hookSpecificOutput;if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let s=i;typeof s.additionalContext=="string"&&(o.injectContext=s.additionalContext)}return o}function N0(e,t,n){if(!t.userGlobalEnabled){let s=[];for(let a of Object.keys(t.hooks)){let l=t.hooks[a];if(l!==void 0)for(let c of l)for(let d of c.hooks)s.push(`${a}: ${d.command}`)}s.length>0&&console.warn(`[hooks] shell hooks are disabled (enableShellHooks not set in user-global config).
1453
1453
  Skipped ${s.length} hook(s):
1454
1454
  `+s.map(a=>` - ${a}`).join(`
@@ -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.0"}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';