agent-afk 4.21.0 → 4.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +5 -5
- package/dist/index.mjs +2 -2
- package/dist/telegram.mjs +4 -4
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1073,7 +1073,7 @@ ${o}`;return s.includes("already checked out")||s.includes("is already used by w
|
|
|
1073
1073
|
Effective base URL: ${r}`)),r}return t}function aU(){if(Hf!==void 0)return Hf;if(!Yv){let o=[ua(process.cwd(),".env"),at(),Kw()];for(let s of o)Kf(s)&&sU({path:s,override:!1});Yv=!0}let e={},t=k.AFK_MODEL??k.CLAUDE_MODEL;if(t){let o=t.toLowerCase();e.model=Zm(o)?o:t}if(oe(t)==="anthropic-direct"){let o=Wf();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=iU(k.AFK_OPENAI_BASE_URL)),Hf=e,e}function Qv(){if(Cs!==void 0)return Cs;let e=[ua(process.cwd(),"afk.config.json"),_t(),Hl()];for(let t of e)if(Kf(t))try{let n=Zv(t,"utf-8"),r=JSON.parse(n),o={},s=RS(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=Zm(i)?i: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),r.autoRouting&&typeof r.autoRouting=="object"){let i={};typeof r.autoRouting.interactive=="boolean"&&(i.interactive=r.autoRouting.interactive),typeof r.autoRouting.chat=="boolean"&&(i.chat=r.autoRouting.chat),typeof r.autoRouting.telegram=="boolean"&&(i.telegram=r.autoRouting.telegram),typeof r.autoRouting.daemon=="boolean"&&(i.daemon=r.autoRouting.daemon),o.autoRouting=i}if(r.daemon&&typeof r.daemon=="object"){let i={};typeof r.daemon.task=="string"&&(i.task=r.daemon.task),typeof r.daemon.taskId=="string"&&(i.taskId=r.daemon.taskId);let a=r.daemon.worktreePrune;a&&typeof a=="object"&&(i.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=i}if(r.telegram&&typeof r.telegram=="object"){let i={},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(u=>typeof u=="number"&&Number.isFinite(u));c.length>0&&(l.targets=c)}i.notify=l}o.telegram=i}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!==ua(process.cwd(),"afk.config.json")){let i=la(r.importFrom);i!==void 0&&(o.importFrom=i)}if(r.interactive&&typeof r.interactive=="object"){let i={};typeof r.interactive.worktreeAutoname=="boolean"&&(i.worktreeAutoname=r.interactive.worktreeAutoname),typeof r.interactive.worktreeBranchPrefix=="string"&&(i.worktreeBranchPrefix=Nf(r.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(Bf(r.interactive.worktreeBase,`${t}#/interactive/worktreeBase`),i.worktreeBase=r.interactive.worktreeBase),typeof r.interactive.suggestGhost=="boolean"&&(i.suggestGhost=r.interactive.suggestGhost),Object.keys(i).length>0&&(o.interactive=i)}return Cs={config:o,sourcePath:t,modelsPartial:s},Cs}catch(n){console.error(`Warning: Failed to parse ${t}:`,n)}return Cs={config:{},sourcePath:void 0,modelsPartial:{}},Cs}function lU(){if(_s!==void 0)return _s.value;let e=[ua(process.cwd(),"AFK.md"),ua(_e(),"AFK.md")];for(let t of e)if(Kf(t))try{let n=Zv(t,"utf-8").trim();if(n.length>0)return _s={value:{content:n,path:t}},_s.value}catch{}return _s={value:null},_s.value}function ek(){return Qv().config.telegram??{}}function bt(e){let t=aU(),{config:n,sourcePath:r,modelsPartial:o}=Qv(),s={...ca,...t,...n,...e},i;if(t.systemPrompt!==void 0)i="env:AFK_SYSTEM_PROMPT";else if(n.systemPrompt!==void 0&&r!==void 0)i=`file:${r}`;else if(s.systemPrompt===void 0){let c=lU();c!==null&&(s.systemPrompt=c.content,i=`afk-md:${c.path}`)}let a={model:s.model??ca.model,maxTokens:s.maxTokens??ca.maxTokens,temperature:s.temperature??ca.temperature,updatePolicy:s.updatePolicy??ca.updatePolicy,...s.apiKey!==void 0?{apiKey:s.apiKey}:{},...s.baseUrl!==void 0?{baseUrl:s.baseUrl}:{},...s.openaiBaseUrl!==void 0?{openaiBaseUrl:s.openaiBaseUrl}:{},...s.systemPrompt!==void 0?{systemPrompt:s.systemPrompt}:{},...i!==void 0?{systemPromptSource:i}:{},...s.autoRouting!==void 0?{autoRouting:s.autoRouting}:{},...s.daemon!==void 0?{daemon:s.daemon}:{},...s.telegram!==void 0?{telegram:s.telegram}:{},...s.bgSummaries!==void 0?{bgSummaries:s.bgSummaries}:{},...s.maxSummaryCallsPerSession!==void 0?{maxSummaryCallsPerSession:s.maxSummaryCallsPerSession}:{},...s.interactive!==void 0?{interactive:s.interactive}:{},...s.hooks!==void 0?{hooks:s.hooks}:{},...s.enableShellHooks!==void 0?{enableShellHooks:s.enableShellHooks}:{},...s.importFrom!==void 0?{importFrom:s.importFrom}:{}},l=e?.models??Vm(o);if(rc(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 ca,Yv,Hf,Xv,Cs,_s,qn=C(()=>{"use strict";$n();zt();Je();W();Rs();aa();G();uo();ca={model:"sonnet",maxTokens:4096,temperature:1,updatePolicy:"notify"},Yv=!1;Xv=new Set});function cU(e,t){return t!==void 0&&Number.isFinite(t)&&t!==0?t:e.find(r=>r>0)??e[0]}function uU(e,t={}){let n=[...e],r=t.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let s=(t.targets??[]).filter(i=>typeof i=="number"&&Number.isFinite(i)&&i!==0);if(s.length>0)return[...new Set(s)]}let o=cU(n,t.primaryChatId);return o!==void 0?[o]:[]}function dU(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 pU(e){if(!e)return;let t=e.trim().toLowerCase();return t==="primary"||t==="broadcast"||t==="custom"?t:void 0}function mU(){let e=ek().notify??{},t=e.mode??pU(k.AFK_TELEGRAM_NOTIFY_MODE),n=e.primaryChatId??dU(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 Is(){let e=Mv(k.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return uU(e,mU())}var Nc=C(()=>{"use strict";Ov();qn();G()});function tk(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,s=r.lastIndexOf(`
|
|
1074
1074
|
`,t);if(s>t-500&&s>0)o=s+1;else{let i=r.slice(0,t).match(/[.!?]\s+(?=[A-Z])/g);if(i&&i.length>0){let a=i[i.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}var nk=C(()=>{"use strict"});var Gf={};$l(Gf,{push:()=>Bc,pushIfConfigured:()=>Sr});async function Bc(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??fU}/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 s=new AbortController,i=setTimeout(()=>s.abort(),1e4);try{let a=await t(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:s.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(i)}}async function Sr(e,t={}){let n=k.TELEGRAM_BOT_TOKEN;if(!n)return null;let r=Is();if(r.length===0)return null;let o=tk(e),s=[];for(let i of r)for(let a=0;a<o.length;a++)s.push(await Bc({token:n,chatId:i,text:o[a]??"",...t.parseMode!==void 0?{parseMode:t.parseMode}:{},...t.replyMarkup!==void 0&&a===0?{replyMarkup:t.replyMarkup}:{},...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}}));return s}var fU,po=C(()=>{"use strict";Nc();nk();G();fU="https://api.telegram.org"});function gU(e=Bc){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>rk)return{content:`Invalid input: message exceeds Telegram's ${rk}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=k.TELEGRAM_BOT_TOKEN;if(!s)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 i=Is();if(i.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 i){let c=await e({token:s,chatId:l,text:o});c.ok||a.push(`chat ${l}: ${c.errorMessage??`HTTP ${c.status}`}`)}return a.length===i.length?{content:`Failed to send Telegram message to any chat. ${a.join("; ")}`,isError:!0}:a.length>0?{content:`Sent Telegram message to ${i.length-a.length}/${i.length} chat(s); ${a.length} failed: ${a.join("; ")}`}:{content:i.length===1?`Sent Telegram message to chat ${i[0]}.`:`Sent Telegram message to ${i.length} chats.`}}}var rk,ok,sk=C(()=>{"use strict";G();po();Nc();rk=4096;ok=gU()});import{JSDOM as hU}from"jsdom";import{Readability as yU}from"@mozilla/readability";import bU from"turndown";function ik(e){return e.replace(/\n{3,}/g,`
|
|
1075
1075
|
|
|
1076
|
-
`).trim()}function wU(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function lk(e,t){let r=new hU(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new yU(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=ik(zf.turndown(s.content)),u=(s.title??"").trim()||o,d=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:u,markdown:c,textLength:d,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",l=ik(zf.turndown(a));return{title:o,markdown:l,textLength:wU(i),usedFallback:!0}}var ak,zf,ck=C(()=>{"use strict";ak=200,zf=new bU({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});zf.remove(["script","style","noscript","iframe"])});import{readFileSync as SU}from"node:fs";import{join as vU}from"path";function kU(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function uk(e,t){return kU(t).test(e)}function TU(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(EU.has(t))return!0;if(xU.has(t))return!1}return!1}function dk(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function RU(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 AU(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function CU(e){try{return SU(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function _U(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 n}function pk(e){let t=e?.env??k,n=e?.readFileSync??CU,r=e?.surface??t.AGENT_SURFACE,o=TU(t.AFK_BROWSER_HEADLESS,r),s=dk(t.AFK_BROWSER_ALLOWED_DOMAINS),i=dk(t.AFK_BROWSER_BLOCKED_DOMAINS),a=AU(t.AFK_BROWSER_DOM_SNAPSHOTS),l=RU(t.AFK_BROWSER_BACKEND),c={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null},u=t.AFK_BROWSER_CONFIG,d=u!==void 0&&u.trim()!==""?u.trim():vU(Gt(),"browser.json"),p=n(d);if(p===void 0)return c;let f;try{f=JSON.parse(p)}catch(h){throw new Error(`Failed to parse browser config at ${d}: ${String(h)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${d} must be a JSON object`);let g=_U(c,f);return g.configPath=d,g}function qf(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(uk(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>uk(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var EU,xU,Jf=C(()=>{"use strict";G();W();EU=new Set(["daemon","subagent","telegram","afk"]),xU=new Set(["repl","interactive","cli"])});import IU from"node:fs";import PU from"node:path";import{chromium as MU}from"playwright";function OU(){try{return"4.21.0"}catch{}try{let e=PU.resolve(import.meta.dirname,"../../../package.json"),t=IU.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var $U,jc,mk=C(()=>{"use strict";$U=OU(),jc=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=MU.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 o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),o}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",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),u=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),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/${$U}`}}}});import{createHash as DU}from"crypto";function Vf(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of LU)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function fk(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&FU.test(e.label))}function gk(e){return DU("sha256").update(e,"utf8").digest("hex").slice(0,8)}function hk(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var LU,FU,da=C(()=>{"use strict";LU=[{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}];FU=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as NU}from"node:crypto";function BU(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function jU(e,t,n){return`el_${NU("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function UU(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function yk(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function wk(e,t){let n=e.role??"",r=e.name??"";bk.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])wk(s,t)}async function HU(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let u=window.getComputedStyle(i);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Sk).catch(()=>[])}async function KU(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 s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in s?s.value:void 0,d=u!==void 0?String(u):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},Sk).catch(()=>[])}function WU(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Uc(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=WU(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=HU(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([i,a,l,c,u]),b,y=!1;d!==null?(b=[],wk(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await KU(e)).filter(O=>bk.has(O.role??"")));let S=new Map;for(let $ of p){let O=yk($.name),D=S.get(O);(!D||D.bbox.w===0&&$.bbox.w>0)&&S.set(O,$)}let w=b.map($=>({ax:$,dom:S.get(yk($.name??""))})),R=r?w:w.filter($=>$.dom?$.dom.bbox.w>0||$.dom.bbox.h>0:!0);R.sort(($,O)=>{let D=$.dom?.bbox.y??0,N=O.dom?.bbox.y??0;if(D!==N)return D-N;let B=$.dom?.bbox.x??0,U=O.dom?.bbox.x??0;return B-U}),R.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=R.slice(0,n).map(($,O)=>{let D=$.ax.role??"generic",N=$.ax.name??"",B=jU(D,N,O),U=$.dom?.bbox??{x:0,y:0,w:0,h:0},j=$.dom?.type??null,F=null;$.ax.value!==void 0&&$.ax.value!==null&&(F=String($.ax.value)),$.ax.checked!==void 0&&(F=String($.ax.checked)),fk({role:D,kind:j})&&(F="[redacted]");let L={disabled:$.ax.disabled??!1};$.ax.checked!==void 0&&(L.checked=$.ax.checked===!0||$.ax.checked==="mixed"),$.ax.selected!==void 0&&(L.selected=$.ax.selected),$.ax.expanded!==void 0&&(L.expanded=$.ax.expanded);let M;$.dom?.testId?M=`[data-testid="${$.dom.testId}"]`:$.dom?.id&&(M=`#${$.dom.id}`);let z={id:B,role:D,label:BU(N),kind:j,value:F,state:L,bbox:U};return M!==void 0&&(z.selector=M),z}),T="idle";try{let $=await e.evaluate(()=>document.readyState);$==="loading"?T="loading":$==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let v=UU(f),_=`obs_${t.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:_,url:g,title:h,textSummary:v,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:T,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:I}}var bk,Sk,vk=C(()=>{"use strict";da();bk=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Sk="a[href], button, input, select, textarea, [role], [tabindex], label"});async function kk(e,t){try{let n=await e.nth(t).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Yf(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>kk(e,s)))).filter(o=>o!==null)}async function GU(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(i)||(t.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Xf(e,t,n){switch(t.kind){case"element_id":return zU(e,t,n);case"selector":return qU(e,t);case"semantic":return JU(e,t)}}async function zU(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}),s=await o.count();if(s===0)return{outcome:"not_found",query:t};if(s===1)return{outcome:"resolved",locator:o};let i=await Yf(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function qU(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 Yf(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function JU(e,t){return t.role!==void 0?VU(e,t.text,t.role):YU(e,t.text,t)}async function VU(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 s=await Yf(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function YU(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),s=e.getByLabel(t,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let u=[];i>0&&u.push({loc:r,count:i}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:s,count:l});let d=await GU(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let y=await kk(b.locator,b.index);if(y!==null){let S=`${y.role}:${y.label}:${h}`,w=0;for(let R=0;R<S.length;R++)w=w*31+S.charCodeAt(R)>>>0;f.push({...y,id:`el_${w.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var Ek=C(()=>{"use strict"});import{randomBytes as XU}from"crypto";import{mkdir as ZU,stat as QU,writeFile as e1}from"fs/promises";import{join as Zf}from"path";import{gzip as t1}from"zlib";import{promisify as n1}from"util";function r1(e){return Zf(is(e),"browser")}function o1(e){return Zf(r1(e),"screenshots")}function s1(){return new Date().toISOString().replace(/[:.]/g,"-")}function i1(){return XU(3).toString("hex")}async function Qf(e,t,n){if(t.length>xk)throw new Error(`writeScreenshotSidecar: buffer exceeds ${xk} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=o1(e);await ZU(r,{recursive:!0});let o=`${s1()}-${i1()}-${n}.png`,s=Zf(r,o);await e1(s,t);let{size:i}=await QU(s);return{path:s,bytes:i}}var bae,xk,Tk=C(()=>{"use strict";W();da();bae=n1(t1);xk=5*1024*1024});var Ak={};$l(Ak,{PlaywrightProvider:()=>eg});function Rk(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 eg,Ck=C(()=>{"use strict";mk();vk();Ek();Jf();da();Tk();eg=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new jc(t)}async open(t){let n=qf(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),s=this.ensureSessionState(r),i=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)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await Uc(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,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),s=null;t.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Uc(r,{observationCounter:o.observationCounter,screenshotPath:s,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,i.interactive,i.url,i.title,"browser_observe"),i}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),s=r.url(),i=t.timeoutMs??3e4,a=await Xf(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Rk(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:i});break;case"fill":{let h=Vf(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:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=r.url();if(d!==s){let h=qf(d,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:d,reason:h.reason}}let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Uc(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}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),s;if(t.target!==void 0){let u=await Xf(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Rk(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await u.locator.screenshot()}else s=await r.screenshot({fullPage:t.fullPage??!1});let{path:i,bytes:a}=await Qf(n,s,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.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,s){t.knownElements=new Map(n.map(i=>[i.id,i])),t.currentUrl=r,t.currentTitle=o,t.lastAction=s,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:s}=await Qf(n,o,r);return s}catch{return null}}}});var fo={};$l(fo,{__resetBrowserRegistryForTests:()=>d1,browserProviderActive:()=>c1,closeBrowserProvider:()=>tg,getBrowserProvider:()=>l1,peekBrowserProvider:()=>u1});function _k(){Promise.resolve(tg()).then(()=>{process.exit(130)})}function Ik(){Promise.resolve(tg()).then(()=>{process.exit(143)})}function Pk(){un=null}function a1(){Hc||(process.on("SIGINT",_k),process.on("SIGTERM",Ik),process.on("exit",Pk),Hc=!0)}function Mk(){Hc&&(process.removeListener("SIGINT",_k),process.removeListener("SIGTERM",Ik),process.removeListener("exit",Pk),Hc=!1)}async function l1(e){return un!==null?un:(mo!==null||(mo=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(Ck(),Ak)),n=pk(e),r=new t(n);return a1(),un=r,mo=null,r})()),mo)}async function tg(){if(un===null)return;let e=un;un=null,mo=null,Mk(),await e.shutdown()}function c1(){return un!==null}function u1(){return un}function d1(){un=null,mo=null,Mk()}var un,mo,Hc,go=C(()=>{"use strict";Jf();un=null,mo=null,Hc=!1});function Ok(e,t){try{return lk(e,t)}catch(n){return V("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function h1(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(go(),fo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function $k(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??h1,o=null,s=e,i=null,a=null;try{let c=await n(e,{headers:g1,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(f1.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let d=await c.text();if(m1.test(u)&&!p1.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=Ok(d,s)}}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<ak)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),u=Ok(c.html,c.finalUrl);if(o===null||u.textLength>=o.textLength)return{title:u.title,markdown:u.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let u=c instanceof Error?c.message:String(c),d=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${e}: fetch failed (${d}) and render failed (${u}).`);throw p.cause=c,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${i??"error"}).`)}var p1,m1,f1,g1,Dk=C(()=>{"use strict";ck();Pe();p1=/(text\/html|application\/xhtml\+xml)/i,m1=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,f1=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,g1={"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 w1(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(y1,{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),b1),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=_c(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.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 Lk(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?w1({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 Fk(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
1076
|
+
`).trim()}function wU(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function lk(e,t){let r=new hU(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new yU(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=ik(zf.turndown(s.content)),u=(s.title??"").trim()||o,d=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:u,markdown:c,textLength:d,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",l=ik(zf.turndown(a));return{title:o,markdown:l,textLength:wU(i),usedFallback:!0}}var ak,zf,ck=C(()=>{"use strict";ak=200,zf=new bU({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});zf.remove(["script","style","noscript","iframe"])});import{readFileSync as SU}from"node:fs";import{join as vU}from"path";function kU(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function uk(e,t){return kU(t).test(e)}function TU(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(EU.has(t))return!0;if(xU.has(t))return!1}return!1}function dk(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function RU(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 AU(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function CU(e){try{return SU(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function _U(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 n}function pk(e){let t=e?.env??k,n=e?.readFileSync??CU,r=e?.surface??t.AGENT_SURFACE,o=TU(t.AFK_BROWSER_HEADLESS,r),s=dk(t.AFK_BROWSER_ALLOWED_DOMAINS),i=dk(t.AFK_BROWSER_BLOCKED_DOMAINS),a=AU(t.AFK_BROWSER_DOM_SNAPSHOTS),l=RU(t.AFK_BROWSER_BACKEND),c={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null},u=t.AFK_BROWSER_CONFIG,d=u!==void 0&&u.trim()!==""?u.trim():vU(Gt(),"browser.json"),p=n(d);if(p===void 0)return c;let f;try{f=JSON.parse(p)}catch(h){throw new Error(`Failed to parse browser config at ${d}: ${String(h)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${d} must be a JSON object`);let g=_U(c,f);return g.configPath=d,g}function qf(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(uk(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>uk(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var EU,xU,Jf=C(()=>{"use strict";G();W();EU=new Set(["daemon","subagent","telegram","afk"]),xU=new Set(["repl","interactive","cli"])});import IU from"node:fs";import PU from"node:path";import{chromium as MU}from"playwright";function OU(){try{return"4.21.1"}catch{}try{let e=PU.resolve(import.meta.dirname,"../../../package.json"),t=IU.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var $U,jc,mk=C(()=>{"use strict";$U=OU(),jc=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=MU.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 o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),o}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",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),u=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),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/${$U}`}}}});import{createHash as DU}from"crypto";function Vf(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of LU)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function fk(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&FU.test(e.label))}function gk(e){return DU("sha256").update(e,"utf8").digest("hex").slice(0,8)}function hk(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var LU,FU,da=C(()=>{"use strict";LU=[{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}];FU=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as NU}from"node:crypto";function BU(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function jU(e,t,n){return`el_${NU("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function UU(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function yk(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function wk(e,t){let n=e.role??"",r=e.name??"";bk.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])wk(s,t)}async function HU(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let u=window.getComputedStyle(i);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Sk).catch(()=>[])}async function KU(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 s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in s?s.value:void 0,d=u!==void 0?String(u):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},Sk).catch(()=>[])}function WU(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Uc(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=WU(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=HU(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([i,a,l,c,u]),b,y=!1;d!==null?(b=[],wk(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await KU(e)).filter(O=>bk.has(O.role??"")));let S=new Map;for(let $ of p){let O=yk($.name),D=S.get(O);(!D||D.bbox.w===0&&$.bbox.w>0)&&S.set(O,$)}let w=b.map($=>({ax:$,dom:S.get(yk($.name??""))})),R=r?w:w.filter($=>$.dom?$.dom.bbox.w>0||$.dom.bbox.h>0:!0);R.sort(($,O)=>{let D=$.dom?.bbox.y??0,N=O.dom?.bbox.y??0;if(D!==N)return D-N;let B=$.dom?.bbox.x??0,U=O.dom?.bbox.x??0;return B-U}),R.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=R.slice(0,n).map(($,O)=>{let D=$.ax.role??"generic",N=$.ax.name??"",B=jU(D,N,O),U=$.dom?.bbox??{x:0,y:0,w:0,h:0},j=$.dom?.type??null,F=null;$.ax.value!==void 0&&$.ax.value!==null&&(F=String($.ax.value)),$.ax.checked!==void 0&&(F=String($.ax.checked)),fk({role:D,kind:j})&&(F="[redacted]");let L={disabled:$.ax.disabled??!1};$.ax.checked!==void 0&&(L.checked=$.ax.checked===!0||$.ax.checked==="mixed"),$.ax.selected!==void 0&&(L.selected=$.ax.selected),$.ax.expanded!==void 0&&(L.expanded=$.ax.expanded);let M;$.dom?.testId?M=`[data-testid="${$.dom.testId}"]`:$.dom?.id&&(M=`#${$.dom.id}`);let z={id:B,role:D,label:BU(N),kind:j,value:F,state:L,bbox:U};return M!==void 0&&(z.selector=M),z}),T="idle";try{let $=await e.evaluate(()=>document.readyState);$==="loading"?T="loading":$==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let v=UU(f),_=`obs_${t.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:_,url:g,title:h,textSummary:v,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:T,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:I}}var bk,Sk,vk=C(()=>{"use strict";da();bk=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Sk="a[href], button, input, select, textarea, [role], [tabindex], label"});async function kk(e,t){try{let n=await e.nth(t).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Yf(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>kk(e,s)))).filter(o=>o!==null)}async function GU(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(i)||(t.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Xf(e,t,n){switch(t.kind){case"element_id":return zU(e,t,n);case"selector":return qU(e,t);case"semantic":return JU(e,t)}}async function zU(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}),s=await o.count();if(s===0)return{outcome:"not_found",query:t};if(s===1)return{outcome:"resolved",locator:o};let i=await Yf(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function qU(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 Yf(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function JU(e,t){return t.role!==void 0?VU(e,t.text,t.role):YU(e,t.text,t)}async function VU(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 s=await Yf(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function YU(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),s=e.getByLabel(t,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let u=[];i>0&&u.push({loc:r,count:i}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:s,count:l});let d=await GU(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let y=await kk(b.locator,b.index);if(y!==null){let S=`${y.role}:${y.label}:${h}`,w=0;for(let R=0;R<S.length;R++)w=w*31+S.charCodeAt(R)>>>0;f.push({...y,id:`el_${w.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var Ek=C(()=>{"use strict"});import{randomBytes as XU}from"crypto";import{mkdir as ZU,stat as QU,writeFile as e1}from"fs/promises";import{join as Zf}from"path";import{gzip as t1}from"zlib";import{promisify as n1}from"util";function r1(e){return Zf(is(e),"browser")}function o1(e){return Zf(r1(e),"screenshots")}function s1(){return new Date().toISOString().replace(/[:.]/g,"-")}function i1(){return XU(3).toString("hex")}async function Qf(e,t,n){if(t.length>xk)throw new Error(`writeScreenshotSidecar: buffer exceeds ${xk} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=o1(e);await ZU(r,{recursive:!0});let o=`${s1()}-${i1()}-${n}.png`,s=Zf(r,o);await e1(s,t);let{size:i}=await QU(s);return{path:s,bytes:i}}var bae,xk,Tk=C(()=>{"use strict";W();da();bae=n1(t1);xk=5*1024*1024});var Ak={};$l(Ak,{PlaywrightProvider:()=>eg});function Rk(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 eg,Ck=C(()=>{"use strict";mk();vk();Ek();Jf();da();Tk();eg=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new jc(t)}async open(t){let n=qf(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),s=this.ensureSessionState(r),i=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)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await Uc(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,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),s=null;t.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Uc(r,{observationCounter:o.observationCounter,screenshotPath:s,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,i.interactive,i.url,i.title,"browser_observe"),i}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),s=r.url(),i=t.timeoutMs??3e4,a=await Xf(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Rk(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:i});break;case"fill":{let h=Vf(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:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=r.url();if(d!==s){let h=qf(d,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:d,reason:h.reason}}let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Uc(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}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),s;if(t.target!==void 0){let u=await Xf(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Rk(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await u.locator.screenshot()}else s=await r.screenshot({fullPage:t.fullPage??!1});let{path:i,bytes:a}=await Qf(n,s,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.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,s){t.knownElements=new Map(n.map(i=>[i.id,i])),t.currentUrl=r,t.currentTitle=o,t.lastAction=s,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:s}=await Qf(n,o,r);return s}catch{return null}}}});var fo={};$l(fo,{__resetBrowserRegistryForTests:()=>d1,browserProviderActive:()=>c1,closeBrowserProvider:()=>tg,getBrowserProvider:()=>l1,peekBrowserProvider:()=>u1});function _k(){Promise.resolve(tg()).then(()=>{process.exit(130)})}function Ik(){Promise.resolve(tg()).then(()=>{process.exit(143)})}function Pk(){un=null}function a1(){Hc||(process.on("SIGINT",_k),process.on("SIGTERM",Ik),process.on("exit",Pk),Hc=!0)}function Mk(){Hc&&(process.removeListener("SIGINT",_k),process.removeListener("SIGTERM",Ik),process.removeListener("exit",Pk),Hc=!1)}async function l1(e){return un!==null?un:(mo!==null||(mo=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(Ck(),Ak)),n=pk(e),r=new t(n);return a1(),un=r,mo=null,r})()),mo)}async function tg(){if(un===null)return;let e=un;un=null,mo=null,Mk(),await e.shutdown()}function c1(){return un!==null}function u1(){return un}function d1(){un=null,mo=null,Mk()}var un,mo,Hc,go=C(()=>{"use strict";Jf();un=null,mo=null,Hc=!1});function Ok(e,t){try{return lk(e,t)}catch(n){return V("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function h1(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(go(),fo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function $k(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??h1,o=null,s=e,i=null,a=null;try{let c=await n(e,{headers:g1,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(f1.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let d=await c.text();if(m1.test(u)&&!p1.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=Ok(d,s)}}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<ak)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),u=Ok(c.html,c.finalUrl);if(o===null||u.textLength>=o.textLength)return{title:u.title,markdown:u.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let u=c instanceof Error?c.message:String(c),d=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${e}: fetch failed (${d}) and render failed (${u}).`);throw p.cause=c,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${i??"error"}).`)}var p1,m1,f1,g1,Dk=C(()=>{"use strict";ck();Pe();p1=/(text\/html|application\/xhtml\+xml)/i,m1=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,f1=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,g1={"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 w1(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(y1,{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),b1),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=_c(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.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 Lk(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?w1({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 Fk(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
1077
1077
|
|
|
1078
1078
|
(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(`
|
|
1079
1079
|
`).trimEnd()}var y1,b1,Nk=C(()=>{"use strict";xs();y1="https://api.exa.ai/search",b1=10});function A1(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,s;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=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 i=S1;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"};i=Math.min(t.timeout_ms,v1)}let a=k1;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,E1)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function ng(e,t){let n=Buffer.from(e,"utf8");return n.byteLength<=t?e:n.subarray(0,t).toString("utf8")+x1}function C1(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 R1.some(o=>r.includes(o))}function _1(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 s=A1(r);if("error"in s)return{content:s.error,isError:!0};if(o.aborted){let u=o.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let i=new AbortController,a=()=>{i.abort(o.reason)},l,c=()=>{let u=i.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),l=setTimeout(()=>{i.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.mode==="raw"){let d;try{d=await t(s.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:i.signal})}catch(f){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape network error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}if(!d.ok)return{content:`web_scrape HTTP ${d.status} ${d.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let p;try{p=await d.text()}catch(f){return{content:`web_scrape read error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}return{content:ng(p,s.maxBytes)}}if(s.mode==="markdown")try{let d=await $k(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:i.signal});return d.markdown.trim().length===0?{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0}:{content:ng(d.markdown,s.maxBytes)}}catch(d){if(i.signal.aborted)return{content:`web_scrape aborted: ${c()}`,isError:!0};let p=d instanceof Error?d.message:String(d),f=C1(d)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${p}${f}`,isError:!0}}let u=Lk({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in u)return{content:u.error,isError:!0};try{let d=await u.search(s.query,{limit:T1,timeoutMs:s.timeoutMs,signal:i.signal});return{content:ng(Fk(s.query,d),s.maxBytes)}}catch(d){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${d instanceof Error?d.message:String(d)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),o.removeEventListener("abort",a)}}}var S1,v1,k1,E1,x1,T1,R1,Bk,jk=C(()=>{"use strict";Dk();Nk();S1=3e4,v1=12e4,k1=1e6,E1=1e7,x1=`
|
|
@@ -1127,7 +1127,7 @@ ${u}`:u};return wx(p,t.prompt,a)}buildDispatcher(t,n){let r=uu(t,n.cwd),o=na(thi
|
|
|
1127
1127
|
`)}finally{h&&await h.close().catch(()=>{})}}async function d(){let h=await e.readMeta(t);if(!h||!(h.status!=="running"))return!1;try{let y=await Ve.stat(r);return i>=y.size}catch{return!0}}if(o)yield*u();else try{i=(await Ve.stat(r)).size}catch{}if(await d())return;let p=null,f=null,g=()=>new Promise(h=>{f=h;let b=setTimeout(()=>{f=null,h()},c);p=()=>{clearTimeout(b),f=null,h()}});try{l=Ns.watch(s,{persistent:!1},()=>{p?.(),p=null})}catch{}try{for(;await g(),yield*u(),!await d(););}finally{f?.(),l?.close()}}}});import{EventEmitter as kK}from"node:events";import*as Rr from"node:fs/promises";import*as Px from"node:path";import{createHash as EK}from"node:crypto";function $g(e){De(e).catch(()=>{})}var xK,_x,Ix,TK,Ra,vu,Dg=C(()=>{"use strict";Bt();Pe();wt();Su();W();Ln();xK=300*1e3,_x=4096;Ix=5e3,TK=10,Ra=class extends Error{constructor(t,n){super(`Background job cap reached (${t}/${n} running). Wait for existing jobs to finish or cancel them before spawning more.`),this.name="BackgroundJobCapError"}},vu=class extends kK{jobs=new Map;counter=Math.floor(Math.random()*65536);traceWriter;maxConcurrentJobs;constructor(t={}){super(),this.traceWriter=t.traceWriter,this.maxConcurrentJobs=t.maxConcurrentJobs??TK,setTimeout(()=>this._sweepOldJobs().catch(r=>process.stderr.write(`[afk] bg sweep error: ${String(r)}
|
|
1128
1128
|
`)),5e3).unref()}register(t){let{job:n,jobId:r,writer:o,metaRecord:s}=this.createJobEntry(t);return t.handle.runInBackground(t.prompt,i=>{this.markTerminal(r,i,o,s)},i=>{o.write(i),i.type==="chunk"&&i.chunk.type==="content"&&this.appendTranscript(r,i.chunk.content)}),this.snapshot(n)}adoptRunning(t){let{job:n,jobId:r,writer:o,metaRecord:s}=this.createJobEntry(t);return t.runPromise.then(i=>{this.markTerminal(r,i,o,s)}).catch(i=>{V("adoptRunning: unexpected rejection from in-flight runPromise",i),this.markTerminal(r,bu(t.handle.id,"failed",i,Ta()),o,s)}),this.snapshot(n)}createJobEntry(t){let n=[...this.jobs.values()].filter(d=>d.status==="running").length;if(n>=this.maxConcurrentJobs)throw new Ra(n,this.maxConcurrentJobs);let r=this.nextJobId(),o=t.prompt.trim().slice(0,80),s=Date.now(),i,a=new Promise(d=>{i=d}),l={jobId:r,subagentId:t.handle.id,label:o,model:t.model,startedAt:s,status:"running",handle:t.handle,joiners:[],terminalSettled:a,settle:i,transcriptTail:"",parentSessionId:t.parentSessionId};this.jobs.set(r,l),ms(this.traceWriter,{transition:"started",jobId:r,subagentId:t.handle.id,label:o,model:t.model}),this.emit("started",this.snapshot(l));let c=new wu(r),u={jobId:r,subagentId:t.handle.id,label:o,promptHash:EK("sha256").update(t.prompt).digest("hex"),model:t.model,startedAt:s,status:"running",...t.parentSessionId!==void 0?{parentSessionId:t.parentSessionId}:{},schemaVersion:1};return c.writeMeta(u),{job:l,jobId:r,writer:c,metaRecord:u}}get(t){let n=this.jobs.get(t);return n?this.snapshot(n):void 0}list(){return[...this.jobs.values()].map(t=>this.snapshot(t))}async join(t){let n=this.jobs.get(t);if(!n)throw new Error(`Background job not found: "${t}". Completed and cancelled jobs are evicted from the registry ~5 minutes after they settle. If the jobId looks correct, the job may have already been evicted.`);let r=await n.terminalSettled;return ms(this.traceWriter,{transition:"joined",jobId:t,subagentId:n.subagentId,jobStatus:n.status}),this.emit("joined",this.snapshot(n)),r}async cancelJob(t){let n=this.jobs.get(t);return!n||n.status!=="running"?!1:(n.cancelSource="explicit",await n.handle.cancel(),!0)}async cancelAll(){let t=[...this.jobs.values()].filter(n=>n.status==="running");for(let n of t)n.cancelSource="cascade";await Promise.allSettled(t.map(n=>n.handle.cancel())),await Promise.allSettled(t.map(n=>{let r=new Promise(o=>setTimeout(()=>{console.warn(`[BackgroundAgentRegistry] cancelAll: job ${n.jobId} did not settle within ${Ix}ms \u2014 continuing teardown`),o()},Ix).unref());return Promise.race([n.terminalSettled,r])}))}appendTranscript(t,n){let r=this.jobs.get(t);if(!r)return;let o=r.transcriptTail+n;o.length<=_x?r.transcriptTail=o:r.transcriptTail=o.slice(o.length-_x)}getTranscript(t){return this.jobs.get(t)?.transcriptTail}nextJobId(){return this.counter+=1,`bg-${Date.now().toString(36)}-${this.counter}`}markTerminal(t,n,r,o){let s=this.jobs.get(t);if(!s||s.status!=="running")return;s.result=n,s.endedAt=Date.now();let i=s.endedAt-s.startedAt;if(s.status=this.statusFromResult(n.status),s.status==="completed"){let l=n.message?.content,c=typeof l=="string"?l:l!==void 0?JSON.stringify(l):"";ms(this.traceWriter,{transition:"completed",jobId:t,subagentId:s.subagentId,durationMs:i,outputBytes:Buffer.byteLength(c,"utf8")}),$g({event:"subagent.completed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,content_chars:c.length}),this.emit("settled",this.snapshot(s))}else if(s.status==="failed"){let l=n.error;ms(this.traceWriter,{transition:"failed",jobId:t,subagentId:s.subagentId,durationMs:i,errorClass:l?.name??"Error",errorMessage:l?.message??"unknown"}),$g({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i,error_message:l?.message}),this.emit("settled",this.snapshot(s))}else ms(this.traceWriter,{transition:"cancelled",jobId:t,subagentId:s.subagentId,source:s.cancelSource??"explicit"}),$g({event:"subagent.failed",subagent_id:s.subagentId,parent_session_id:s.parentSessionId,status:n.status,duration_ms:i}),this.emit("settled",this.snapshot(s));if(s.settle(n),r&&o){let l=s.status,c=s.endedAt;r.writeMeta({...o,status:l,...c!==void 0?{endedAt:c}:{}}).then(()=>r.close())}setTimeout(()=>{this.jobs.delete(t)},xK).unref()}async _sweepOldJobs(){let n=Ji(),r;try{r=await Rr.readdir(n)}catch{return}for(let o of r){let s=Zr(o),i=Px.join(s,"meta.json");try{if(!(await Rr.lstat(s)).isDirectory()){process.stderr.write(`[afk] bg sweep: skipping non-directory entry ${o}
|
|
1129
1129
|
`);continue}let l=await Rr.readFile(i,"utf8"),c=JSON.parse(l);if(c.status==="running"||c.endedAt===void 0||Date.now()-c.endedAt<6048e5)continue;await Rr.rm(s,{recursive:!0,force:!0})}catch(a){if(a.code==="ENOENT")continue;process.stderr.write(`[afk] bg sweep: error evicting ${o}: ${String(a)}
|
|
1130
|
-
`)}}}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}:{}}}}});function RK(e){return typeof e=="string"&&e.startsWith("sk-ant-")}function Aa(e){let{childModel:t,resolved:n,parentApiKey:r}=e;return n!==void 0&&n.length>0||oe(t)==="openai-compatible"?n:RK(r)?r:n}var Lg=C(()=>{"use strict";Je()});import{isAbsolute as AK}from"node:path";function CK(e){if(typeof e!="object"||e===null)throw new Error("Agent tool input must be an object");let t=e,n=t.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=t.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=t.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let a="agent-tool",l=t.id_prefix;if(l!==void 0){if(typeof l!="string")throw new Error("Agent tool id_prefix must be a string");a=l}let c="foreground",u=t.mode;if(u!==void 0){if(u!=="foreground"&&u!=="background")throw new Error(`Agent tool mode must be "foreground" or "background", got: ${JSON.stringify(u)}`);c=u}let d,p=t.cwd;if(p!==void 0){if(typeof p!="string")throw new Error(`Agent tool cwd must be a string, got: ${JSON.stringify(p)}`);if(p.length===0)throw new Error("Agent tool cwd must be a non-empty string");if(!AK(p))throw new Error(`Agent tool cwd must be an absolute path, got: ${JSON.stringify(p)}`);if(p.split(/[/\\]/).includes(".."))throw new Error(`Agent tool cwd must not contain '..' segments, got: ${JSON.stringify(p)}`);d=p}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:c,...d!==void 0?{cwd:d}:{}}}function ku(e){try{return De(e).catch(()=>{})}catch{return Promise.resolve()}}function Bs(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function Ox(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}function IK(e){if(e==null)return;let t=Ox(e);return t!==void 0&&t>_K?{truncated:!0,chars:t}:e}function PK(e){let t={status:e.status,error:Bs(e.errorMessage,Mx),subagent_id:e.subagentId};e.schemaErrorMessage&&(t.schemaError=Bs(e.schemaErrorMessage,Mx));let n=IK(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var _K,Mx,gn,Ca=C(()=>{"use strict";Ge();Dg();Je();Lg();Rs();Ar();Ln();Pe();xs();yo();Ar();_K=4096,Mx=1024;gn=class e{constructor(t){this.ctx=t}ctx;promotionTriggers=new Map;hasPromotableForeground(){return this.ctx.backgroundRegistry!==void 0&&this.promotionTriggers.size>0}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=CK(t.input)}catch(A){return{content:`Agent tool input validation failed: ${A instanceof Error?A.message:String(A)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??js,s,i=this.ctx.surface!==void 0?{origin:Ds(this.ctx.surface),actor:Er(r)}:{},a=n.model??this.ctx.defaultSubagentModel??"sonnet",l=oe(a)==="openai-compatible",c=Aa({childModel:a,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(a):Wn(a),parentApiKey:this.ctx.defaultConfig.apiKey}),u={model:a,apiKey:l?void 0:c,systemPrompt:this.ctx.defaultConfig.systemPrompt,baseUrl:l?void 0:this.ctx.defaultConfig.baseUrl,maxTurns:n.max_turns,depth:r+1,maxDepth:o,...n.cwd!==void 0?{cwd:n.cwd}:{}},d;if(this.ctx.childProviderFactory&&r<o){s=new se({parentAbortSignal:t.signal,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),d=So(t.signal);let A=new e({subagentManager:s,parentSession:d,defaultConfig:this.ctx.defaultConfig,...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:r+1,maxDepth:o,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}}),T=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,t.signal):void 0;u.provider=this.ctx.childProviderFactory({childExecutor:A,...T!==void 0?{childSkillExecutor:T}:{},...u.model!==void 0?{model:u.model}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}})}let p;try{p=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:t.id,config:u,idPrefix:n.id_prefix,agentType:n.id_prefix&&n.id_prefix!=="agent-tool"?Un(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":Un(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:n.mode==="background"}),d!==void 0&&(d.sessionId=p.id)}catch(A){let T=A instanceof Error?A.message:String(A);return ku({...i,event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:Bs(T),depth:r}),{content:`Failed to fork subagent: ${T}`,isError:!0}}if(n.mode==="background"){let A=this.ctx.backgroundRegistry;if(!A)return await p.teardown().catch(_=>V("subagent-executor: handle teardown failed: "+(_ instanceof Error?_.message:String(_)))),{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 T;try{T=A.register({handle:p,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(_){if(_ instanceof Ra)return await p.teardown().catch(I=>V("subagent-executor: handle teardown failed after cap error: "+(I instanceof Error?I.message:String(I)))),{content:_.message,isError:!0};throw _}let v={status:"running",jobId:T.jobId,subagentId:T.subagentId,label:T.label,message:`Background subagent started (jobId=${T.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${T.jobId} or ask the user to join.`};return{content:JSON.stringify(v)}}let f=()=>{p.cancel()};t.signal.addEventListener("abort",f,{once:!0});let g=Date.now(),h=this.ctx.parentSession.sessionId,b=!1,y,S=new Promise(A=>{y=A}),w,R=new Promise(A=>{w=A});this.promotionTriggers.set(p.id,{fire:y,ready:R});let x=p.runToResult(n.prompt);try{let A=await Promise.race([x.then($=>({kind:"result",result:$})),S.then(()=>({kind:"promote"}))]);if(A.kind==="promote"){let $=this.ctx.backgroundRegistry;if($)try{let O=$.adoptRunning({handle:p,runPromise:x,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:h});return b=!0,t.signal.removeEventListener("abort",f),w({jobId:O.jobId,label:O.label}),{content:JSON.stringify({status:"running",jobId:O.jobId,subagentId:O.subagentId,label:O.label,message:`Subagent backgrounded by user (jobId=${O.jobId}). It keeps running detached and its result will NOT auto-inject into this context. Retrieve it via /bgsub:join ${O.jobId}.`})}}catch(O){V("subagent-executor: promotion failed, staying foreground: "+(O instanceof Error?O.message:String(O))),w(null)}else w(null)}let T=A.kind==="result"?A.result:await x;if(T.status==="succeeded"&&T.message){let $=T.message.content,O=typeof $=="string"?$:JSON.stringify($),D=T.trace;return ku({...i,event:"subagent.completed",subagent_id:p.id,parent_session_id:h,status:T.status,duration_ms:Date.now()-g,content_chars:O.length,depth:r,tool_call_count:D?.toolCalls.length,thinking_present:D?.thinkingPresent,tool_names:D?.toolCalls.length?JSON.stringify([...new Set(D.toolCalls.map(N=>N.name))]):void 0}),{content:O}}let v=T.error?.message??"Subagent failed with no output",_=T.trace;ku({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:h,status:T.status,duration_ms:Date.now()-g,error_message:Bs(v),schema_error:T.schemaError?Bs(T.schemaError.message):void 0,partial_output_chars:Ox(T.partialOutput),depth:r,tool_call_count:_?.toolCalls.length,thinking_present:_?.thinkingPresent,tool_names:_?.toolCalls.length?JSON.stringify([...new Set(_.toolCalls.map($=>$.name))]):void 0});let I=PK({status:T.status,errorMessage:v,schemaErrorMessage:T.schemaError?.message,partialOutput:T.partialOutput,subagentId:p.id});return{content:JSON.stringify(I),isError:!0}}catch(A){let T=A instanceof Error?A.message:String(A);throw ku({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:h,status:"failed",duration_ms:Date.now()-g,error_message:Bs(T),depth:r}),A}finally{this.promotionTriggers.delete(p.id),w(null),b||(t.signal.removeEventListener("abort",f),await s?.teardownAll(),await p.teardown())}}}});function Eu(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${Us}`}var Us,Fg=C(()=>{"use strict";Us="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});import{appendFileSync as MK,mkdirSync as OK}from"fs";import{join as $K}from"path";function DK(e){return{ts:new Date().toISOString(),surface:"afk",event:"skill_invocation",skill_name:e.skillName,source:"native-runtime",...e.sessionId!==void 0?{session_id:e.sessionId}:{},...e.traceId!==void 0?{trace_id:e.traceId}:{},...e.cwd!==void 0?{cwd:e.cwd}:{},...e.model!==void 0?{model:e.model}:{},...e.command!==void 0?{command:e.command}:{},...e.origin!==void 0?{origin:e.origin}:{},...e.actor!==void 0?{actor:e.actor}:{}}}function LK(e,t){try{OK(e,{recursive:!0}),MK($K(e,"skill-invocations.jsonl"),JSON.stringify(t)+`
|
|
1130
|
+
`)}}}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}:{}}}}});function RK(e){return typeof e=="string"&&e.startsWith("sk-ant-")}function Aa(e){let{childModel:t,resolved:n,parentApiKey:r}=e;return n!==void 0&&n.length>0||oe(t)==="openai-compatible"?n:RK(r)?r:n}var Lg=C(()=>{"use strict";Je()});import{isAbsolute as AK}from"node:path";function CK(e){if(typeof e!="object"||e===null)throw new Error("Agent tool input must be an object");let t=e,n=t.prompt;if(typeof n!="string")throw new Error('Agent tool input must have a "prompt" field of type string');if(n.trim().length===0)throw new Error("Agent tool prompt cannot be empty");let r,o=t.model;if(o!==void 0){if(typeof o!="string")throw new Error("Agent tool model must be a string");r=o}let s=10,i=t.max_turns;if(i!==void 0){if(typeof i!="number")throw new Error("Agent tool max_turns must be a number");s=Math.max(1,Math.min(50,Math.floor(i)))}let a="agent-tool",l=t.id_prefix;if(l!==void 0){if(typeof l!="string")throw new Error("Agent tool id_prefix must be a string");a=l}let c="foreground",u=t.mode;if(u!==void 0){if(u!=="foreground"&&u!=="background")throw new Error(`Agent tool mode must be "foreground" or "background", got: ${JSON.stringify(u)}`);c=u}let d,p=t.cwd;if(p!==void 0){if(typeof p!="string")throw new Error(`Agent tool cwd must be a string, got: ${JSON.stringify(p)}`);if(p.length===0)throw new Error("Agent tool cwd must be a non-empty string");if(!AK(p))throw new Error(`Agent tool cwd must be an absolute path, got: ${JSON.stringify(p)}`);if(p.split(/[/\\]/).includes(".."))throw new Error(`Agent tool cwd must not contain '..' segments, got: ${JSON.stringify(p)}`);d=p}return{prompt:n,model:r,max_turns:s,id_prefix:a,mode:c,...d!==void 0?{cwd:d}:{}}}function ku(e){try{return De(e).catch(()=>{})}catch{return Promise.resolve()}}function Bs(e,t=240){return e.length<=t?e:e.slice(0,t)+"\u2026"}function Ox(e){if(e!=null){if(typeof e=="string")return e.length;try{return JSON.stringify(e).length}catch{return}}}function IK(e){if(e==null)return;let t=Ox(e);return t!==void 0&&t>_K?{truncated:!0,chars:t}:e}function PK(e){let t={status:e.status,error:Bs(e.errorMessage,Mx),subagent_id:e.subagentId};e.schemaErrorMessage&&(t.schemaError=Bs(e.schemaErrorMessage,Mx));let n=IK(e.partialOutput);return n!==void 0&&(t.partialOutput=n),t}var _K,Mx,gn,Ca=C(()=>{"use strict";Ge();Dg();Je();Lg();Rs();Ar();Ln();Pe();xs();yo();Ar();_K=4096,Mx=1024;gn=class e{constructor(t){this.ctx=t}ctx;promotionTriggers=new Map;hasPromotableForeground(){return this.ctx.backgroundRegistry!==void 0&&this.promotionTriggers.size>0}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=CK(t.input)}catch(A){return{content:`Agent tool input validation failed: ${A instanceof Error?A.message:String(A)}`,isError:!0}}let r=this.ctx.depth,o=this.ctx.maxDepth??js,s,i=this.ctx.surface!==void 0?{origin:Ds(this.ctx.surface),actor:Er(r)}:{},a=n.model??this.ctx.defaultSubagentModel??"sonnet",l=oe(a)==="openai-compatible",c=Aa({childModel:a,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(a):Wn(a),parentApiKey:this.ctx.defaultConfig.apiKey}),u={model:a,apiKey:l?void 0:c,systemPrompt:this.ctx.defaultConfig.systemPrompt,baseUrl:l?void 0:this.ctx.defaultConfig.baseUrl,maxTurns:n.max_turns,depth:r+1,maxDepth:o,...n.cwd!==void 0?{cwd:n.cwd}:{}},d;if(this.ctx.childProviderFactory&&r<o){s=new se({parentAbortSignal:t.signal,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),d=So(t.signal);let A=new e({subagentManager:s,parentSession:d,defaultConfig:this.ctx.defaultConfig,...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:r+1,maxDepth:o,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}}),T=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(r+1,o,t.signal):void 0;u.provider=this.ctx.childProviderFactory({childExecutor:A,...T!==void 0?{childSkillExecutor:T}:{},...u.model!==void 0?{model:u.model}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash?{readOnlyBash:!0}:{}})}let p;try{p=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:t.id,config:u,idPrefix:n.id_prefix,agentType:n.id_prefix&&n.id_prefix!=="agent-tool"?Un(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":Un(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",denyElicitations:!0}),d!==void 0&&(d.sessionId=p.id)}catch(A){let T=A instanceof Error?A.message:String(A);return ku({...i,event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:Bs(T),depth:r}),{content:`Failed to fork subagent: ${T}`,isError:!0}}if(n.mode==="background"){let A=this.ctx.backgroundRegistry;if(!A)return await p.teardown().catch(_=>V("subagent-executor: handle teardown failed: "+(_ instanceof Error?_.message:String(_)))),{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 T;try{T=A.register({handle:p,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:this.ctx.parentSession.sessionId})}catch(_){if(_ instanceof Ra)return await p.teardown().catch(I=>V("subagent-executor: handle teardown failed after cap error: "+(I instanceof Error?I.message:String(I)))),{content:_.message,isError:!0};throw _}let v={status:"running",jobId:T.jobId,subagentId:T.subagentId,label:T.label,message:`Background subagent started (jobId=${T.jobId}). It is running detached and its result will NOT auto-inject into this context. Retrieve it later via /bgsub:join ${T.jobId} or ask the user to join.`};return{content:JSON.stringify(v)}}let f=()=>{p.cancel()};t.signal.addEventListener("abort",f,{once:!0});let g=Date.now(),h=this.ctx.parentSession.sessionId,b=!1,y,S=new Promise(A=>{y=A}),w,R=new Promise(A=>{w=A});this.promotionTriggers.set(p.id,{fire:y,ready:R});let x=p.runToResult(n.prompt);try{let A=await Promise.race([x.then($=>({kind:"result",result:$})),S.then(()=>({kind:"promote"}))]);if(A.kind==="promote"){let $=this.ctx.backgroundRegistry;if($)try{let O=$.adoptRunning({handle:p,runPromise:x,prompt:n.prompt,model:u.model??"sonnet",parentSessionId:h});return b=!0,t.signal.removeEventListener("abort",f),w({jobId:O.jobId,label:O.label}),{content:JSON.stringify({status:"running",jobId:O.jobId,subagentId:O.subagentId,label:O.label,message:`Subagent backgrounded by user (jobId=${O.jobId}). It keeps running detached and its result will NOT auto-inject into this context. Retrieve it via /bgsub:join ${O.jobId}.`})}}catch(O){V("subagent-executor: promotion failed, staying foreground: "+(O instanceof Error?O.message:String(O))),w(null)}else w(null)}let T=A.kind==="result"?A.result:await x;if(T.status==="succeeded"&&T.message){let $=T.message.content,O=typeof $=="string"?$:JSON.stringify($),D=T.trace;return ku({...i,event:"subagent.completed",subagent_id:p.id,parent_session_id:h,status:T.status,duration_ms:Date.now()-g,content_chars:O.length,depth:r,tool_call_count:D?.toolCalls.length,thinking_present:D?.thinkingPresent,tool_names:D?.toolCalls.length?JSON.stringify([...new Set(D.toolCalls.map(N=>N.name))]):void 0}),{content:O}}let v=T.error?.message??"Subagent failed with no output",_=T.trace;ku({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:h,status:T.status,duration_ms:Date.now()-g,error_message:Bs(v),schema_error:T.schemaError?Bs(T.schemaError.message):void 0,partial_output_chars:Ox(T.partialOutput),depth:r,tool_call_count:_?.toolCalls.length,thinking_present:_?.thinkingPresent,tool_names:_?.toolCalls.length?JSON.stringify([...new Set(_.toolCalls.map($=>$.name))]):void 0});let I=PK({status:T.status,errorMessage:v,schemaErrorMessage:T.schemaError?.message,partialOutput:T.partialOutput,subagentId:p.id});return{content:JSON.stringify(I),isError:!0}}catch(A){let T=A instanceof Error?A.message:String(A);throw ku({...i,event:"subagent.failed",subagent_id:p.id,id_prefix:n.id_prefix,parent_session_id:h,status:"failed",duration_ms:Date.now()-g,error_message:Bs(T),depth:r}),A}finally{this.promotionTriggers.delete(p.id),w(null),b||(t.signal.removeEventListener("abort",f),await s?.teardownAll(),await p.teardown())}}}});function Eu(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${Us}`}var Us,Fg=C(()=>{"use strict";Us="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});import{appendFileSync as MK,mkdirSync as OK}from"fs";import{join as $K}from"path";function DK(e){return{ts:new Date().toISOString(),surface:"afk",event:"skill_invocation",skill_name:e.skillName,source:"native-runtime",...e.sessionId!==void 0?{session_id:e.sessionId}:{},...e.traceId!==void 0?{trace_id:e.traceId}:{},...e.cwd!==void 0?{cwd:e.cwd}:{},...e.model!==void 0?{model:e.model}:{},...e.command!==void 0?{command:e.command}:{},...e.origin!==void 0?{origin:e.origin}:{},...e.actor!==void 0?{actor:e.actor}:{}}}function LK(e,t){try{OK(e,{recursive:!0}),MK($K(e,"skill-invocations.jsonl"),JSON.stringify(t)+`
|
|
1131
1131
|
`)}catch{}}function xu(e){k.VITEST||k.NODE_ENV==="test"||LK(Ct(),DK(e))}var $x=C(()=>{"use strict";G();W()});function Lx(e){Dx.add(e)}function Fx(e){return Dx.has(e)}var Dx,Ng=C(()=>{"use strict";Dx=new Set});function Nx(e){Bg.add(e)}function Bx(e){Bg.delete(e)}function jx(e){jg.add(e)}function Ux(e){jg.delete(e)}function Hx(e){for(let t of Bg)t(e)}function Kx(e){for(let t of jg)t(e)}var Bg,jg,Ug=C(()=>{"use strict";Bg=new Set,jg=new Set});function NK(e,t=FK){return e.length<=t?e:e.slice(0,t)+"\u2026"}function BK(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 jK(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 FK,hn,_a=C(()=>{"use strict";ut();Ge();wo();Ar();Ca();Fg();Lg();Rs();Fn();qt();Ln();$x();Ng();Ug();Pe();yo();FK=240;hn=class{constructor(t){this.ctx=t}ctx;pluginBodies=null;sessionIdentity(){return this.ctx.surface!==void 0?{origin:Ds(this.ctx.surface),actor:Er(this.ctx.depth)}:{}}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??js;if(n>=r){let l=BK(t.input);return De({...this.sessionIdentity(),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:l}).catch(()=>{}),{content:Eu(n,r),isError:!0}}let o;try{o=jK(t.input)}catch(l){return{content:`Skill tool input validation failed: ${l instanceof Error?l.message:String(l)}`,isError:!0}}try{let l=Be(o.name);return await this.executeRegistrySkill(l,o.arguments,t)}catch{}let s=this.getPluginSkillBody(o.name);if(s){if(s.context==="fork"){let c=s.readOnly===!0||Hg.has(o.name);return await this.executePluginSkill(o.name,s.body,s.pluginPath,o.arguments,t,c,s.allowedTools)}let l=s.body.replace(/\$\{?PLUGIN_ROOT\}?/g,()=>s.pluginPath);return this.executeLoadedPluginSkill(o.name,l,o.arguments,t)}let a=Yn(this.ctx.pluginConfigs).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 this.executeForkedRegistrySkill(t,n,r);if(t.context==="load")return this.executeLoadedRegistrySkill(t,n,r);let o=Fx(t.name);o&&Kx(t.name);let s=this.ctx.depth??0;xu({skillName:t.name,sessionId:this.ctx.parentSession.sessionId,cwd:this.ctx.cwd,model:t.model??this.ctx.defaultModel,...this.sessionIdentity()}),De({...this.sessionIdentity(),event:"skill.dispatched",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...t.model!==void 0?{model:t.model}:{}}).catch(()=>{});let i=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)})}catch(u){a=u}finally{let u=Date.now()-i;o&&Hx({skillName:t.name,durationMs:u,...a!==void 0?{isError:!0}:{}});let d=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof l=="string"?l.length:l!=null?JSON.stringify(l).length:0:void 0;De({...this.sessionIdentity(),event:"skill.completed",requested_name:t.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:u,depth:s,...p!==void 0?{content_chars:p}:{},...d!==void 0?{error_message:NK(d)}:{},...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."}}buildForkedChildConfig(t,n,r=!1,o){let s=this.ctx.depth??0,i=this.ctx.maxDepth??js,a={...t},l=r&&o!==void 0?o.filter(f=>Tu.includes(f)):r?[...Tu]:o,c=r;if(!this.ctx.childProviderFactory||s>=i)return r?a.provider=Wx(a.model):l!==void 0&&(a.provider=Gx(l,a.model)),{childConfig:a,childManager:void 0};let u=new se({parentAbortSignal:n,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),d=new gn({subagentManager:u,parentSession:So(n),defaultConfig:{model:a.model,apiKey:this.ctx.apiKey,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{}},...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,childProviderFactory:this.ctx.childProviderFactory,childSkillExecutorFactory:this.ctx.childSkillExecutorFactory,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},depth:s+1,maxDepth:i,...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{},...this.ctx.backgroundRegistry!==void 0?{backgroundRegistry:this.ctx.backgroundRegistry}:{},...l!==void 0?{allowedTools:l}:{},...c?{readOnlyBash:!0}:{}}),p=this.ctx.childSkillExecutorFactory?this.ctx.childSkillExecutorFactory(s+1,i,n):void 0;return a.provider=this.ctx.childProviderFactory({childExecutor:d,...p!==void 0?{childSkillExecutor:p}:{},...a.model!==void 0?{model:a.model}:{},...l!==void 0?{allowedTools:l}:{},...c?{readOnlyBash:!0}:{}}),{childConfig:a,childManager:u}}async executeForkedRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=t.readOnly===!0||Hg.has(t.name),s;try{if(s=Fe(t.name)["system.md"],!s)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 i=t.model??this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",a=Aa({childModel:i,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(i):Wn(i),parentApiKey:this.ctx.apiKey});xu({skillName:t.name,sessionId:this.ctx.parentSession.sessionId,cwd:this.ctx.cwd,model:typeof i=="string"?i:void 0,...this.sessionIdentity()});let l=new se({parentAbortSignal:r.signal,apiKey:a,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:$t(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),{childConfig:c,childManager:u}=this.buildForkedChildConfig({model:i,systemPrompt:s,isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},r.signal,o),d;try{d=await l.forkSubagent({parent:this.ctx.parentSession,config:c,idPrefix:`skill-fork-${t.name}`,parentId:r.id,agentType:t.name});let p=n&&n.length>0?n:`Run the ${t.name} skill now, following the instructions in your system prompt.`,f=await d.runToResult(p);return f.status==="succeeded"&&f.message?{content:f.message.content}:f.status==="cancelled"&&typeof f.partialOutput=="string"&&f.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
|
|
1132
1132
|
|
|
1133
1133
|
${f.partialOutput}`}:{content:f.error?.message??"Forked skill failed with no output",isError:!0}}catch(p){return{content:`Forked skill execution error: ${p instanceof Error?p.message:String(p)}`,isError:!0}}finally{d&&await d.teardown().catch(V),await u?.teardownAll(),await l.teardownAll()}}formatLoadedSkillResult(t,n,r){let o=r&&r.trim().length>0?r.trim():"(none)";return{content:`${`[Skill "${t}" loaded into your current context \u2014 act on it now]
|
|
@@ -1138,7 +1138,7 @@ Arguments: ${o}`}
|
|
|
1138
1138
|
|
|
1139
1139
|
${n}`}}emitLoadTelemetry(t,n,r,o){let s=this.ctx.depth??0,i={...this.sessionIdentity(),requested_name:t,parent_session_id:this.ctx.parentSession.sessionId,depth:s,mode:"load",...o!==void 0?{model:o}:{}};De({event:"skill.dispatched",...i}).catch(()=>{}),De({event:"skill.completed",status:"succeeded",duration_ms:r,content_chars:n,...i}).catch(()=>{})}executeLoadedRegistrySkill(t,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=Date.now(),s;if(t.loadBody!==void 0)s=t.loadBody;else try{let l=Fe(t.name)["system.md"];if(!l)return{content:`Skill "${t.name}" has context: "load" but no prompts/system.md found`,isError:!0};s=l}catch(a){return{content:`Failed to load skill prompts: ${a instanceof Error?a.message:String(a)}`,isError:!0}}let i=this.substituteSkillArgs(s,n);return this.emitLoadTelemetry(t.name,i.length,Date.now()-o,t.model),this.formatLoadedSkillResult(t.name,i,n)}executeLoadedPluginSkill(t,n,r,o){if(o.signal.aborted)return{content:"Skill call aborted",isError:!0};let s=Date.now(),i=this.substituteSkillArgs(n,r);return this.emitLoadTelemetry(t,i.length,Date.now()-s,void 0),this.formatLoadedSkillResult(t,i,r)}substituteSkillArgs(t,n){let r=n??"";return t.replace(/\$ARGUMENTS?\b/g,()=>r)}async executePluginSkill(t,n,r,o,s,i=!1,a){if(s.signal.aborted)return{content:"Skill call aborted",isError:!0};let l=this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",c=Aa({childModel:l,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(l):Wn(l),parentApiKey:this.ctx.apiKey});xu({skillName:t,sessionId:this.ctx.parentSession.sessionId,cwd:this.ctx.cwd,model:typeof l=="string"?l:void 0,...this.sessionIdentity()});let u=new se({parentAbortSignal:s.signal,apiKey:c,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:$t(),...this.ctx.cwd!==void 0?{cwd:this.ctx.cwd}:{}}),d={model:l,systemPrompt:this.substituteSkillArgs(n,o),env:{PLUGIN_ROOT:r},isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},{childConfig:p,childManager:f}=this.buildForkedChildConfig(d,s.signal,i,a),g;try{g=await u.forkSubagent({parent:this.ctx.parentSession,config:p,idPrefix:`skill-${t}`,parentId:s.id,agentType:t});let h=o&&o.length>0?o:`Run the ${t} skill now, following the instructions in your system prompt.`,b=await g.runToResult(h);return b.status==="succeeded"&&b.message?{content:b.message.content}:b.status==="cancelled"&&typeof b.partialOutput=="string"&&b.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
|
|
1140
1140
|
|
|
1141
|
-
${b.partialOutput}`}:{content:b.error?.message??"Plugin skill failed with no output",isError:!0}}catch(h){return{content:`Plugin skill execution error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}finally{g&&await g.teardown().catch(V),await f?.teardownAll(),await u.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=Ru(this.ctx.pluginConfigs)),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},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}}});function So(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}function Hs(e={}){return({childExecutor:t,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??UK},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return oe(typeof r=="string"?r:void 0)==="openai-compatible"?new Et({...i,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new je({...i,readOnlyMemory:!0})}}function Wx(e){let t={allowedTools:[...Tu]};return oe(typeof e=="string"?e:void 0)==="openai-compatible"?new Et({permissions:t,readOnlyBash:!0,readOnlyMemory:!0}):new je({permissions:t,readOnlyBash:!0,readOnlyMemory:!0})}function Ks(e,t,n,r,o,s,i,a){let l=(c,u,d)=>new hn({parentSession:So(d),defaultModel:e,apiKey:t,...r!==void 0?{baseUrl:r}:{},depth:c,maxDepth:u,childProviderFactory:n,childSkillExecutorFactory:l,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...i!==void 0?{cwd:i}:{},...a!==void 0?{resolveApiKeyForModel:a}:{}});return l}function Gx(e,t){let n={allowedTools:[...e]};return oe(typeof t=="string"?t:void 0)==="openai-compatible"?new Et({permissions:n}):new je({permissions:n})}function zx(e,t){let n={allowedTools:[...kx]};return oe(typeof t=="string"?t:void 0)==="openai-compatible"?new Et({permissions:n}):new je({permissions:n})}var js,UK,Tu,Hg,Ar=C(()=>{"use strict";vo();va();Je();an();cn();xa();_a();js=3;UK=[...Dt,...rt,"memory_search","agent","skill"],Tu=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...rt,"memory_search","agent","skill"],Hg=new Set(["ground-state"])});var Au,qx=C(()=>{"use strict";Pe();dc();Fn();mc();wt();Bt();Au=class{constructor(t,n,r,o,s,i,a,l,c,u,d,p,f,g,h){this.id=t;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=u;this.agentType=d;this.traceWriter=g;this.onSubagentSucceeded=h;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;currentTrace=Ta();lastStreamedContent="";get status(){return this.currentStatus}async run(t,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=uc(this.streamToFinalMessage(t,n),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=o;try{let s=await o;this.lastMessage=s.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",to(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8")});let i=typeof s.metadata?.totalCostUsd=="number"?s.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,i),this.onTerminal(),s}catch(s){throw this.lastDurationMs=Date.now()-r,this.currentStatus!=="cancelled"&&(this.controller.signal.aborted?(to(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(to(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:s instanceof Error?s.constructor.name:"Unknown",errorMessage:s instanceof Error?s.message:String(s),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8")}),this.currentStatus="failed",this.latestTerminalStatus="failed")),this.onTerminal(),s}finally{this.inFlight=null}}async streamToFinalMessage(t,n){let r,o;this.lastStreamedContent="",this.currentTrace=Ta();let s=n??this.progressSink??$t(),i={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(s&&s(a,i),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?.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{role:"assistant",content:this.lastStreamedContent,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 Rx(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=bu(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(t,n,r){let o;if(r){let s=this.progressSink??$t();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(t,o).then(s=>{n?.(s)}).catch(s=>{V("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",to(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(){if(this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(t)}}async dispatchStopAndRelease(t){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await KS(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(n.injectContext&&this.parentInputStreamRef)if(this.parentAbortSignal?.aborted)V(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){V(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}}});var HK,se,Ge=C(()=>{"use strict";jS();Ws();dc();mc();wt();Ln();Fn();Ar();qx();HK=async(e,t)=>({action:"decline"}),se=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentCwd;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.parentCwd=t.cwd,this.onSubagentSucceededCb=t.onSubagentSucceeded,this.abortGraph=new lc(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}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;o&&await HS(o,{event:"SubagentStart",subagentId:n,parentSessionId:t.parent.sessionId},{signal:this.rootController.signal,...t.config.traceWriter?{traceWriter:t.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...t.config,resume:r,forkSession:r?!0:t.config.forkSession,abortSignal:s.signal,apiKey:t.config.apiKey||this.parentApiKey,baseUrl:t.config.baseUrl??this.parentBaseUrl,...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}:{},hookRegistry:o,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!0?{onElicitation:HK}:{},...t.phaseRole==="read-only"?{provider:zx("read-only",t.config.model)}:{}},a;try{a=new dt(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??$t(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,f=new Au(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??cc,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},l,c,d??t.idPrefix,u,p??t.parent.sessionId,t.config.traceWriter,this.onSubagentSucceededCb);this.active.set(n,f);let g=typeof t.config.model=="string"?t.config.model:JSON.stringify(t.config.model);return to(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await De({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:g,parent_session_id:t.parent.sessionId}),f}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 Cu(e,t={}){let{failFast:n=!0,teardown:r=!0}=t;if(e.length===0)return[];let o=new Array(e.length),s=new Set(e.map((a,l)=>l)),i=e.map((a,l)=>a.handle.runToResult(a.prompt).then(c=>{if(o[l]=c,s.delete(l),n&&c.status!=="succeeded")for(let u of s){let d=e[u];d&&d.handle.status==="running"&&d.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(e.map(a=>a.handle.teardown())),o}var Kg=C(()=>{"use strict"});import{fileURLToPath as KK}from"node:url";import{dirname as WK}from"node:path";var GK,Yde,jt,Wg=C(()=>{"use strict";GK=KK(import.meta.url),Yde=WK(GK),jt={name:"research-agent",systemPrompt:`---
|
|
1141
|
+
${b.partialOutput}`}:{content:b.error?.message??"Plugin skill failed with no output",isError:!0}}catch(h){return{content:`Plugin skill execution error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}finally{g&&await g.teardown().catch(V),await f?.teardownAll(),await u.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=Ru(this.ctx.pluginConfigs)),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},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}}});function So(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}function Hs(e={}){return({childExecutor:t,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??UK},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return oe(typeof r=="string"?r:void 0)==="openai-compatible"?new Et({...i,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new je({...i,readOnlyMemory:!0})}}function Wx(e){let t={allowedTools:[...Tu]};return oe(typeof e=="string"?e:void 0)==="openai-compatible"?new Et({permissions:t,readOnlyBash:!0,readOnlyMemory:!0}):new je({permissions:t,readOnlyBash:!0,readOnlyMemory:!0})}function Ks(e,t,n,r,o,s,i,a){let l=(c,u,d)=>new hn({parentSession:So(d),defaultModel:e,apiKey:t,...r!==void 0?{baseUrl:r}:{},depth:c,maxDepth:u,childProviderFactory:n,childSkillExecutorFactory:l,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...i!==void 0?{cwd:i}:{},...a!==void 0?{resolveApiKeyForModel:a}:{}});return l}function Gx(e,t){let n={allowedTools:[...e]};return oe(typeof t=="string"?t:void 0)==="openai-compatible"?new Et({permissions:n}):new je({permissions:n})}function zx(e,t){let n={allowedTools:[...kx]};return oe(typeof t=="string"?t:void 0)==="openai-compatible"?new Et({permissions:n}):new je({permissions:n})}var js,UK,Tu,Hg,Ar=C(()=>{"use strict";vo();va();Je();an();cn();xa();_a();js=3;UK=[...Dt,...rt,"memory_search","agent","skill"],Tu=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...rt,"memory_search","agent","skill"],Hg=new Set(["ground-state"])});var Au,qx=C(()=>{"use strict";Pe();dc();Fn();mc();wt();Bt();Au=class{constructor(t,n,r,o,s,i,a,l,c,u,d,p,f,g,h){this.id=t;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=u;this.agentType=d;this.traceWriter=g;this.onSubagentSucceeded=h;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;currentTrace=Ta();lastStreamedContent="";get status(){return this.currentStatus}async run(t,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=uc(this.streamToFinalMessage(t,n),this.timeoutMs,{controller:this.controller,label:this.id});this.inFlight=o;try{let s=await o;this.lastMessage=s.content,this.lastDurationMs=Date.now()-r,this.currentStatus="succeeded",this.latestTerminalStatus="succeeded",to(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8")});let i=typeof s.metadata?.totalCostUsd=="number"?s.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,i),this.onTerminal(),s}catch(s){throw this.lastDurationMs=Date.now()-r,this.currentStatus!=="cancelled"&&(this.controller.signal.aborted?(to(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(to(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:s instanceof Error?s.constructor.name:"Unknown",errorMessage:s instanceof Error?s.message:String(s),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8")}),this.currentStatus="failed",this.latestTerminalStatus="failed")),this.onTerminal(),s}finally{this.inFlight=null}}async streamToFinalMessage(t,n){let r,o;this.lastStreamedContent="",this.currentTrace=Ta();let s=n??this.progressSink??$t(),i={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(s&&s(a,i),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?.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{role:"assistant",content:this.lastStreamedContent,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 Rx(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=bu(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(t,n,r){let o;if(r){let s=this.progressSink??$t();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(t,o).then(s=>{n?.(s)}).catch(s=>{V("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",to(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(){if(this.stopDispatched)return;let t=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(t)}}async dispatchStopAndRelease(t){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await KS(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(n.injectContext&&this.parentInputStreamRef)if(this.parentAbortSignal?.aborted)V(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){V(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}}});var HK,se,Ge=C(()=>{"use strict";jS();Ws();dc();mc();wt();Ln();Fn();Ar();qx();HK=async(e,t)=>({action:"decline"}),se=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentCwd;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.parentCwd=t.cwd,this.onSubagentSucceededCb=t.onSubagentSucceeded,this.abortGraph=new lc(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}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;o&&await HS(o,{event:"SubagentStart",subagentId:n,parentSessionId:t.parent.sessionId},{signal:this.rootController.signal,...t.config.traceWriter?{traceWriter:t.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...t.config,resume:r,forkSession:r?!0:t.config.forkSession,abortSignal:s.signal,apiKey:t.config.apiKey||this.parentApiKey,baseUrl:t.config.baseUrl??this.parentBaseUrl,isNonInteractive:t.config.isNonInteractive??!0,...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}:{},hookRegistry:o,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!1?{}:{onElicitation:HK},...t.phaseRole==="read-only"?{provider:zx("read-only",t.config.model)}:{}},a;try{a=new dt(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??$t(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,f=new Au(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??cc,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},l,c,d??t.idPrefix,u,p??t.parent.sessionId,t.config.traceWriter,this.onSubagentSucceededCb);this.active.set(n,f);let g=typeof t.config.model=="string"?t.config.model:JSON.stringify(t.config.model);return to(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await De({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:g,parent_session_id:t.parent.sessionId}),f}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 Cu(e,t={}){let{failFast:n=!0,teardown:r=!0}=t;if(e.length===0)return[];let o=new Array(e.length),s=new Set(e.map((a,l)=>l)),i=e.map((a,l)=>a.handle.runToResult(a.prompt).then(c=>{if(o[l]=c,s.delete(l),n&&c.status!=="succeeded")for(let u of s){let d=e[u];d&&d.handle.status==="running"&&d.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(e.map(a=>a.handle.teardown())),o}var Kg=C(()=>{"use strict"});import{fileURLToPath as KK}from"node:url";import{dirname as WK}from"node:path";var GK,Yde,jt,Wg=C(()=>{"use strict";GK=KK(import.meta.url),Yde=WK(GK),jt={name:"research-agent",systemPrompt:`---
|
|
1142
1142
|
name: research-agent
|
|
1143
1143
|
description: Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to \`git-investigator\`. Use when the dispatched task is findings-only.
|
|
1144
1144
|
model: sonnet
|
|
@@ -1673,7 +1673,7 @@ ${w.map(T=>`> - ${T}`).join(`
|
|
|
1673
1673
|
`)}
|
|
1674
1674
|
|
|
1675
1675
|
`:"")+b,A=g.failed.length>0;return{content:x,isError:A}}catch(d){let p=d instanceof Error?d.message:String(d);return De({event:"compose.failed",parent_session_id:this.ctx.parentSession.sessionId,error_message:p.slice(0,240),duration_ms:Date.now()-u}).catch(()=>{}),{content:`Compose execution error: ${p}`,isError:!0}}finally{await l.teardownAll()}}};G();Os();yr();W();import{existsSync as Z2,mkdirSync as Q2,readFileSync as ez,renameSync as tz,writeFileSync as nz}from"fs";import{dirname as rz,isAbsolute as oz}from"path";import{randomUUID as sz}from"node:crypto";var jh={version:1,grants:[]},IA="0123456789ABCDEFGHJKMNPQRSTVWXYZ";function iz(e=Date.now()){let t=e,n=new Array(10).fill("0");for(let o=9;o>=0;o--)n[o]=IA[t%32],t=Math.floor(t/32);let r=new Array(16).fill("0");for(let o=0;o<16;o++)r[o]=IA[Math.floor(Math.random()*32)];return n.join("")+r.join("")}function MA(e=qi()){if(!Z2(e))return jh;try{let t=ez(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)?jh:{version:1,grants:n.grants.filter(az)}}catch(t){return console.warn(`[permissions] could not parse ${e} \u2014 treating as empty (persisted grants reset): `+(t instanceof Error?t.message:String(t))),jh}}function az(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.path=="string"&&oz(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 OA(e,t=qi()){let n=MA(t),r={id:iz(),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 lz(t,o),r}function PA(e,t=qi()){let n=MA(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 s=Date.parse(o.expiresAt);return Number.isFinite(s)?s>r:!0}).map(o=>o.path)}function $A(e,t=qi()){for(let n of PA("read",t))e.addReadRoot(n,"tool");for(let n of PA("write",t))e.addWriteRoot(n,"tool")}function lz(e,t){Q2(rz(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${sz()}`;nz(n,JSON.stringify(t,null,2)+`
|
|
1676
|
-
`,{encoding:"utf8",mode:384}),tz(n,e)}var DA=new Set(["read_file","write_file","edit_file","list_directory","glob","grep"]),LA=new Set(["write_file","edit_file"]);function Uh(e,t){return`${e}:${t}`}function FA(e){let t={sessionApproved:new Set,onceApproved:new Map,inFlight:new Map};return{preToolUse:async(s,i)=>cz(e,t,s,i),postToolUse:s=>uz(e,t,s),sessionEnd:s=>dz(e,t,s)}}async function cz(e,t,n,r){if(n.event!=="PreToolUse")return{};if(!DA.has(n.toolName))return{};let o=n.input;if(!o)return{};let s=NA(n.toolName,o);if(s===void 0)return{};let i=LA.has(n.toolName)?"write":"read",a=e.getGrantManager();if(!a)return{};let l=a.getGrants(),c=e.getCwd(),u=Af(s,{cwd:c,resolveBase:l.resolveBase??c,readRoots:l.readRoots,writeRoots:l.writeRoots},i);if(!u.restricted)return{};let d=Uh(i,u.resolved);if(t.sessionApproved.has(d))return{};let p=t.inFlight.get(d);if(p)return p;let f=pz({toolName:n.toolName,resolvedPath:u.resolved,capturedCwd:c,mode:i,grantManager:a,state:t,surface:e.surface,...r!==void 0?{signal:r}:{}});t.inFlight.set(d,f);try{return await f}finally{t.inFlight.delete(d)}}function uz(e,t,n){if(n.event!=="PostToolUse")return{};if(!DA.has(n.toolName))return{};let r=n.input;if(!r)return{};let o=NA(n.toolName,r);if(o===void 0)return{};let s=LA.has(n.toolName)?"write":"read",i=e.getGrantManager();if(!i)return{};let a=i.getGrants(),l,c;for(let[u,d]of t.onceApproved){if(d.mode!==s)continue;let{resolved:p}=Af(o,{cwd:d.capturedCwd,resolveBase:a.resolveBase??d.capturedCwd,readRoots:a.readRoots,writeRoots:a.writeRoots},s);if(Uh(s,p)===u){l=d,c=u;break}}return!l||c===void 0?{}:(i.revokeRoot(l.resolvedPath,"tool"),t.onceApproved.delete(c),{})}function dz(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 NA(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 pz(e){let{toolName:t,resolvedPath:n,capturedCwd:r,mode:o,grantManager:s,state:i,surface:a,signal:l}=e,c=Ts(n),u=c!==n?`
|
|
1676
|
+
`,{encoding:"utf8",mode:384}),tz(n,e)}var DA=new Set(["read_file","write_file","edit_file","list_directory","glob","grep"]),LA=new Set(["write_file","edit_file"]);function Uh(e,t){return`${e}:${t}`}function FA(e){let t={sessionApproved:new Set,onceApproved:new Map,inFlight:new Map};return{preToolUse:async(s,i)=>cz(e,t,s,i),postToolUse:s=>uz(e,t,s),sessionEnd:s=>dz(e,t,s)}}async function cz(e,t,n,r){if(n.event!=="PreToolUse")return{};if(!DA.has(n.toolName))return{};let o=n.input;if(!o)return{};let s=NA(n.toolName,o);if(s===void 0)return{};let i=LA.has(n.toolName)?"write":"read",a=e.getGrantManager();if(!a)return{};let l=a.getGrants(),c=e.getCwd(),u=Af(s,{cwd:c,resolveBase:l.resolveBase??c,readRoots:l.readRoots,writeRoots:l.writeRoots},i);if(!u.restricted)return{};if(n.parentSessionId!==void 0)return console.error(`[path-approval] surface=${e.surface} tool=${n.toolName} path=${u.resolved} outcome=subagent-autodeny`),{decision:"block",reason:`Sub-agents cannot access paths outside the session's granted roots (${u.resolved}). Report this path requirement to the parent session, which owns the operator surface and can grant access.`};let d=Uh(i,u.resolved);if(t.sessionApproved.has(d))return{};let p=t.inFlight.get(d);if(p)return p;let f=pz({toolName:n.toolName,resolvedPath:u.resolved,capturedCwd:c,mode:i,grantManager:a,state:t,surface:e.surface,...r!==void 0?{signal:r}:{}});t.inFlight.set(d,f);try{return await f}finally{t.inFlight.delete(d)}}function uz(e,t,n){if(n.event!=="PostToolUse")return{};if(!DA.has(n.toolName))return{};let r=n.input;if(!r)return{};let o=NA(n.toolName,r);if(o===void 0)return{};let s=LA.has(n.toolName)?"write":"read",i=e.getGrantManager();if(!i)return{};let a=i.getGrants(),l,c;for(let[u,d]of t.onceApproved){if(d.mode!==s)continue;let{resolved:p}=Af(o,{cwd:d.capturedCwd,resolveBase:a.resolveBase??d.capturedCwd,readRoots:a.readRoots,writeRoots:a.writeRoots},s);if(Uh(s,p)===u){l=d,c=u;break}}return!l||c===void 0?{}:(i.revokeRoot(l.resolvedPath,"tool"),t.onceApproved.delete(c),{})}function dz(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 NA(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 pz(e){let{toolName:t,resolvedPath:n,capturedCwd:r,mode:o,grantManager:s,state:i,surface:a,signal:l}=e,c=Ts(n),u=c!==n?`
|
|
1677
1677
|
(resolves to: ${c})`:"",d=`Tool \`${t}\` wants to ${o==="write"?"WRITE to":"read"} a path outside this session's granted roots:
|
|
1678
1678
|
|
|
1679
1679
|
${n}${u}
|
|
@@ -1990,7 +1990,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
1990
1990
|
${R}${S}
|
|
1991
1991
|
${w}
|
|
1992
1992
|
${R}`})}return{fileBlocks:a,warnings:l}}async function z0(e,t,n,r,o="summary",s,i){let a=II(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0);let l="",c=0,u=!1,d=!1,p=!1,f=!1,g,h=!1,b=!1,y={abort:null},S=0,w=15e3,R=[],x=new Map,A=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,T=()=>{let D=r.subagentControl;D?.hasPromotableForeground()&&D.promoteActiveForeground().then(N=>{for(let B of N)(s??{fn:console.log}).fn(m.dim(` \u2192 subagent backgrounded as ${B.jobId}: ${B.label}`))}).catch(()=>{})},v=r.getCompositor?r.getCompositor():null,_=()=>new Ti({out:Ri(s),thinkingMode:o,...A?{activeSkillName:A}:{},onCancel:()=>{t.interrupt().catch(D=>{Ne()&&console.error(" "+m.error("session.interrupt() failed:"),D)})},...r.subagentControl?{onBackground:T}:{},...i?.history?{history:i.history}:{},...i?.autocompleteState?{autocompleteState:i.autocompleteState}:{},...i?.promptText!==void 0?{promptText:i.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...v?{compositor:v}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),I=_(),$=async()=>{if(!p){p=!0;try{await I.dispose()}catch{}}},O=async()=>{await I.arm();let D=I.getCompositor();if(s&&D){let N=D;s.fn=B=>N.commitAbove(B)}r.setActiveCompositor?.(D),r.setInterruptNotifier?.(N=>I.setInterrupting(N)),r.rearmStatus?.()};try{v?v.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{h=!0,t.interrupt().catch(F=>{Ne()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),F)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{b=!0,t.interrupt().catch(F=>{Ne()&&console.error(" "+m.error("pause-interrupt session.interrupt() failed:"),F)})}),await O(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(T);let{fileBlocks:D,warnings:N}=G0(e.text,{rootDir:process.cwd()});for(let F of N)(s??{fn:console.log}).fn(m.dim(` @-file: ${F}`));let B=D.length>0||e.attachments.length>0?K0(e.text,e.attachments,void 0,D):e.text,U=t.sendMessageStream(B);if(await Ss((F,L)=>{I.process(F,L)},async()=>{for await(let F of U){if(h||b)break;if(F.type==="chunk"&&F.chunk.type==="content"?(l+=F.chunk.content,u=!0):F.type==="message"&&!u&&(l=F.message.content),F.type==="stream_retry"&&(l=l.slice(0,c)),F.type==="chunk"&&F.chunk.type==="tool_use_detail"){let L=F.chunk,M={toolName:L.toolName,toolUseId:L.toolUseId,input:L.toolInput,...L.toolInputRaw!==void 0&&{inputRaw:L.toolInputRaw}};x.set(L.toolUseId,M),R.push(M)}else if(F.type==="chunk"&&F.chunk.type==="tool_result"){let L=F.chunk;c=l.length;let M=x.get(L.toolUseId);if(M&&(M.result=L.content,M.isError=L.isError,x.delete(L.toolUseId)),r.onContextProgress){let z=Date.now();if(z-S>=w){S=z;try{let Y=r.onContextProgress();Y instanceof Promise&&await Y}catch(Y){Ne()&&console.error(" "+m.error("onContextProgress (status refresh) failed:"),Y)}}}}if(F.type==="paused"){if(r.setPausedState?.(!0),await $(),v&&F.autoResume===!0){let L=new AbortController;y.abort=L;let M=F.resetsAt?F.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,z=M?`Keep waiting \u2014 auto-resumes at ${M}`:"Keep waiting \u2014 auto-resume in progress",Y="Switch model / provider (type /model after)",re="Stop waiting",X=[m.warning(" \u23F3 Usage limit reached.")+(M?m.dim(` Auto-resumes at ${M}.`):""),m.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Fp(v,{header:X,options:[z,Y,re],signal:L.signal,initialIndex:0}).then(H=>{if(y.abort=null,!H)return;let ee=H[0];ee===void 0||ee===z||(b=!0,ee===Y&&(s??{fn:console.log}).fn(m.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(ce=>{Ne()&&console.error(" "+m.error("picker pause-interrupt session.interrupt() failed:"),ce)}))}).catch(H=>{Ne()&&console.error(" "+m.error("picker promise rejected:"),H)})}else(s??{fn:console.log}).fn(mS({reason:F.reason,...F.resetsAt!==void 0?{resetsAt:F.resetsAt}:{},...F.accountId!==void 0?{accountId:F.accountId}:{},...F.autoResume!==void 0?{autoResume:F.autoResume}:{}}));continue}if(F.type==="resumed"){r.setPausedState?.(!1),y.abort?.abort(),y.abort=null;let L=F.hotSwapped&&F.accountId?`\u25B6 Resumed on ${F.accountId}`:"\u25B6 Resumed";l="",c=0,u=!1,R.length=0,x.clear(),f=!1,g=void 0,d=!1,I=_(),p=!1,await O(),(s??{fn:console.log}).fn(m.success(L));continue}if(F.type==="error"){await $(),ds(as(F.error)),d=!0;continue}I.process(F),F.type==="done"&&(f=!0,g=F.metadata)}}),await $(),h){let F=s?s.fn:console.log;F(m.warning("\u23F8 Stopped \u2014 work so far kept.")+m.dim(" Send a message to continue.")),F("")}if(b){let F=s?s.fn:console.log;F(m.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),F("")}if(f&&!h&&!b){ko(n,a,l,g,R),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),fd(process.stdout);let F=M=>{s?s.fn(M):console.log(M)},L=U0(l);if(L){if(F(H0(L)),F(""),r.onTerminalState)try{r.onTerminalState(L)}catch{}n.permissionMode==="autonomous"&&s_(L)}if(R6(g,n,F),r.onAfterTurn){let M=r.onAfterTurn();M instanceof Promise&&await M.catch(()=>{})}}}catch(D){await $(),d||ds(as(D))}finally{await $(),s&&(s.fn=s.idleFn),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),y.abort?.abort(),y.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function R6(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(fe(e.durationMs)),e.totalCostUsd!==void 0&&r.push(Ye(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),s=Number(e.usage?.output_tokens??0);o+s>0&&r.push(ae(o+s)+" tok"),r.length>0&&n(m.dim(" \u25E6 "+r.join(" \xB7 ")));let i=qh(t),a=kt(t.model);if(i>=1){let l=Math.round((i-1)*a),c=Math.round(a/1e3);console.log(m.error(` context OVER ${c}k tok by ~${ae(l)} tok \u2014 model output may be silently truncated`))}else if(i>.5){let l=i>.8?m.error:m.warning;n(l(` context ${Math.round(i*100)}% used of ${ae(a)}`))}n("")}async function A6(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function q0(e,t,n,r,o,s,i,a){let{contextPane:l,loopStageBar:c,verdictLedger:u,shellPassthrough:d}=i,p=null,f=[];e.session.current.waitForInitialization().then(async y=>{Ne()&&(p=kd(y)),await mp(e.session.current),Ne()&&(f=PM())}).catch(()=>{});let g,h=!1,b=!1;for(;;){if(p&&(e.replRenderer.writeLine(p),e.replRenderer.writeLine(""),p=null),f.length>0){for(let v of f)e.replRenderer.writeLine(v);e.replRenderer.writeLine(""),f=[]}let y=d.drainNotifications();for(let{job:v,result:_}of y){let I=_.errorReason===void 0?"\u2713":"\u2717",$=_.errorReason==="abort"?"killed":_.errorReason==="timeout"?"timed out":_.errorReason==="signal-killed"?"killed by signal":`exit ${_.exitCode??0}`,O=Math.max(0,Math.round(_.durationMs/100)/10);e.replRenderer.writeLine(m.dim(` ${I} [${v.id}] ${$} \xB7 ${O}s \xB7 `)+v.command)}let S=l.renderIfChanged(e.stats.sessionId);if(S.length>0){for(let v of S)e.replRenderer.writeLine(v);e.replRenderer.writeLine("")}let w,R;if(g!==void 0){let v=g;g=void 0;let _=Mi(e.stats.model,e.stats.permissionMode),I=Co({buffer:v.text,promptText:_,isTTY:!!process.stdout.isTTY,attachmentSummary:bi([...v.attachments])});e.replRenderer.writeLine(I),w=v.text.trim(),R=v.attachments}else{let v=await o.readLine({promptFn:()=>Mi(e.stats.model,e.stats.permissionMode),onSigint:r,onShiftTab:()=>{rr(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});w=v.text.trim(),R=v.attachments}if(!w&&R.length===0)continue;if(w.startsWith("!")){let v=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!v&&(h||(h=!0,e.replRenderer.writeLine(m.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await d.dispatch(w))){e.statusLine.rearm();continue}}let x=!1;if(w.startsWith("/")){let v=await HC(w,e.slashCtx,R);if(v.handled){if(v.result==="exit"){e.rl.close();return}if((w==="/clear"||w.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),u.reset()),v.result!==null&&typeof v.result=="object"&&"kind"in v.result&&v.result.kind==="submit"){g={text:v.result.message,attachments:R??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}x=!0}a.push(w),await A6(e,w);let A=w;if(x){let v=zh(w);if(v){let _=v.name.replace(/^\//,"").split(":").pop()??"";if(_&&nb(_)){let I={skillName:_,rawArgs:v.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},$=e.session.current.sessionId,O=Fo($),D=Date.now();V(`[afk trace] preflight.start commandName=${_}`);let N=!1,B=await Lo(I,{cwd:e.stats.cwd??process.cwd(),artifactDir:O},U=>{Ne()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${_}) failed: `)+(U instanceof Error?U.message:String(U)))});N=B!==null,V(`[afk trace] preflight.end commandName=${_} durationMs=${Date.now()-D} success=${N}`),A=ob(B?.manifestBlock,w)}}}let T=d.drainInjections();T.length>0&&(A=T+A),await z0({text:A,attachments:R},e.session.current,e.stats,{setInFlight(v){n.turnInFlight=v},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(v){await t.appendUser(v)},async onTurnComplete(v,_){if(await t.appendTurn(v,_),e.stats.sessionId)try{bn(e.stats)}catch(I){b||(b=!0,e.replRenderer.writeLine(m.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(I instanceof Error?I.message:String(I))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:v=>u?.push(v),setActiveCompositor:v=>{n.activeCompositor=v},setInterruptNotifier:v=>{n.notifyInterrupting=v},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:v=>o.setBackgroundHandler(v),setSoftStopHandler:s,setPausedState:v=>o.setPausedState(v),setPauseInterruptHandler:v=>o.setPauseInterruptHandler(v),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(nr(e.stats,e.contextSampler))},...c?{onStageChange:v=>c.repaint(v)}:{}},e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(Mi(e.stats.model,e.stats.permissionMode)))}}function C6(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 J0(e,t,n,r){let o=await T0(),s=new Lp({rl:e.rl,history:o,statusLine:e.statusLine}),i=C6(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await P0(e,s,n,t,r,i,{getLoopStageBar:()=>a?.loopStageBar});a=j0(e,n),await q0(e,t,n,r,s,l,a,o)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),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 s.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}aa();import{execFile as _6}from"node:child_process";import{dirname as I6,isAbsolute as P6,resolve as M6}from"node:path";import{promisify as O6}from"node:util";var V0=O6(_6),$6=3e3,D6=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function L6(){let t=(await V0("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=P6(t)?t:M6(process.cwd(),t);return I6(n)}async function Y0(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await L6()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),$6)});try{let o=kn({execFile:V0,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),s=await Promise.race([o,r]);if(s==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let i=s;return i.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:i.candidates.filter(c=>D6.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}oc();aa();import{promises as F6}from"node:fs";import{dirname as N6,join as Q0}from"node:path";import{randomBytes as B6}from"node:crypto";var j6=["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(`
|
|
1993
|
-
`),X0=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Pb=30,U6=1024,H6=8e3,K6="haiku";async function W6(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=J6(n,U6),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??H6),i=t.signal?V6([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await bs({token:t.token,model:t.model??K6,system:j6,user:r,maxTokens:32,signal:i})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=G6(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=N6(t.worktreePath);return await z6(l,c)}function G6(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(X0.test(t)&&t.length<=Pb)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>Pb)break;o=i}return X0.test(o)?o:null}async function z6(e,t){if(!await q6(Q0(t,e)))return e;let n=B6(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Pb-5)}-${n}`}async function q6(e){try{return await F6.access(e),!0}catch{return!1}}function J6(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 V6(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 eO(e){let t,n,r=Q0(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await W6(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}}),s=t??"unknown",i=n;if(o!==null){let l=`${$c(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return Z0(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return Z0(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function Z0(e,t){e&&e.setCwd(t),Y6(t)}function Y6(e){try{process.chdir(e)}catch{}}He();qn();W();import{spawn as nO}from"child_process";import{existsSync as rO,mkdirSync as tX,readFileSync as oO,unlinkSync as tO,writeFileSync as nX}from"fs";import{get as rX}from"https";import{join as sO}from"path";import{readFileSync as X6}from"fs";import{dirname as Z6,join as Q6}from"path";import{fileURLToPath as eX}from"url";function cr(){try{return"4.21.
|
|
1993
|
+
`),X0=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Pb=30,U6=1024,H6=8e3,K6="haiku";async function W6(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=J6(n,U6),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??H6),i=t.signal?V6([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await bs({token:t.token,model:t.model??K6,system:j6,user:r,maxTokens:32,signal:i})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=G6(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=N6(t.worktreePath);return await z6(l,c)}function G6(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(X0.test(t)&&t.length<=Pb)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>Pb)break;o=i}return X0.test(o)?o:null}async function z6(e,t){if(!await q6(Q0(t,e)))return e;let n=B6(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Pb-5)}-${n}`}async function q6(e){try{return await F6.access(e),!0}catch{return!1}}function J6(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 V6(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 eO(e){let t,n,r=Q0(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await W6(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}}),s=t??"unknown",i=n;if(o!==null){let l=`${$c(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return Z0(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return Z0(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function Z0(e,t){e&&e.setCwd(t),Y6(t)}function Y6(e){try{process.chdir(e)}catch{}}He();qn();W();import{spawn as nO}from"child_process";import{existsSync as rO,mkdirSync as tX,readFileSync as oO,unlinkSync as tO,writeFileSync as nX}from"fs";import{get as rX}from"https";import{join as sO}from"path";import{readFileSync as X6}from"fs";import{dirname as Z6,join as Q6}from"path";import{fileURLToPath as eX}from"url";function cr(){try{return"4.21.1"}catch{}try{let e=Z6(eX(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(X6(Q6(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}G();var oX=64*1024,sX=1440*60*1e3,iX=3600*1e3,aX="update-check.json",lX="pending-update.json";function iO(){return sO(Nl(),aX)}function Sl(){return sO(Nl(),lX)}function aO(){let e=Nl();rO(e)||tX(e,{recursive:!0})}function cX(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),s=n(t).split(".").map(Number),i=Math.max(o.length,s.length);for(let a=0;a<i;a++){let l=o[a]??0,c=s[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function uX(){try{let e=oO(iO(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function dX(){try{aO();let e=`
|
|
1994
1994
|
const https = require('https');
|
|
1995
1995
|
const fs = require('fs');
|
|
1996
1996
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|