agent-afk 5.15.12 → 5.15.13
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.
|
@@ -13,6 +13,7 @@ export declare class AgentSession implements IAgentSession {
|
|
|
13
13
|
private providerIterator;
|
|
14
14
|
private conversationHistory;
|
|
15
15
|
private turnCount;
|
|
16
|
+
private pendingFrameworkContext;
|
|
16
17
|
private lastResponseMetadata;
|
|
17
18
|
private initPromise;
|
|
18
19
|
private inputStream;
|
|
@@ -78,7 +79,9 @@ export declare class AgentSession implements IAgentSession {
|
|
|
78
79
|
compact(): Promise<ProviderCompactResult>;
|
|
79
80
|
getLastResponseMetadata(): ResponseMetadata | null;
|
|
80
81
|
getOutputStream(): AsyncIterable<OutputEvent>;
|
|
81
|
-
|
|
82
|
+
queueFrameworkContext(text: string): void;
|
|
83
|
+
private withPendingFrameworkContext;
|
|
84
|
+
getInputStreamRef(): Pick<InputStreamRef, 'pushUserMessage' | 'queueFrameworkContext'>;
|
|
82
85
|
getHistory(): readonly Message[];
|
|
83
86
|
getTurnCount(): number;
|
|
84
87
|
close(): Promise<void>;
|
|
@@ -119,7 +119,7 @@ export interface IAgentSession {
|
|
|
119
119
|
getQuery(): ProviderQuery;
|
|
120
120
|
getLastResponseMetadata(): ResponseMetadata | null;
|
|
121
121
|
getOutputStream(): AsyncIterable<OutputEvent>;
|
|
122
|
-
getInputStreamRef(): Pick<InputStreamRef, 'pushUserMessage'>;
|
|
122
|
+
getInputStreamRef(): Pick<InputStreamRef, 'pushUserMessage' | 'queueFrameworkContext'>;
|
|
123
123
|
supportedCommands(): Promise<SlashCommand[]>;
|
|
124
124
|
supportedModels(): Promise<ModelInfo[]>;
|
|
125
125
|
supportedAgents(): Promise<AgentInfo[]>;
|
package/dist/cli.mjs
CHANGED
|
@@ -1079,7 +1079,7 @@ ${o}`;return s.includes("already checked out")||s.includes("is already used by w
|
|
|
1079
1079
|
Effective base URL: ${r}`)),r}return t}function iW(){if(gh!==void 0)return gh;if(!aT){let o=[Va(process.cwd(),".env"),Et(),qv()];for(let s of o)hh(s)&&oW({path:s,override:!1});aT=!0}let e={},t=E.AFK_MODEL??E.CLAUDE_MODEL;if(t){let o=t.toLowerCase();e.model=Cg(o)?o:t}if(re(t)==="anthropic-direct"){let o=yh();o!==void 0&&(e.apiKey=o)}let r=E.AFK_LOCAL_BASE_URL;if(r&&r.length>0&&(e.baseUrl=r,e.apiKey=E.AFK_LOCAL_API_KEY||"local"),E.AFK_MAX_TOKENS&&(e.maxTokens=parseInt(E.AFK_MAX_TOKENS,10)),E.AFK_TEMPERATURE&&(e.temperature=parseFloat(E.AFK_TEMPERATURE)),E.AFK_SYSTEM_PROMPT&&(e.systemPrompt=E.AFK_SYSTEM_PROMPT),E.AFK_AUTO_ROUTING){let o=E.AFK_AUTO_ROUTING.toLowerCase()==="true";e.autoRouting={interactive:o,chat:o,telegram:o,daemon:o}}return E.AFK_OPENAI_BASE_URL&&(e.openaiBaseUrl=sW(E.AFK_OPENAI_BASE_URL)),gh=e,e}function bh(){if(Xs!==void 0)return Xs;let e=[Va(process.cwd(),"afk.config.json"),Gt(),Nc()];for(let t of e)if(hh(t))try{let n=cT(t,"utf-8"),r=JSON.parse(n),o={},s=_k(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=Cg(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),typeof r.permissionMode=="string"){let i=r.permissionMode;(i==="default"||i==="plan"||i==="autonomous"||i==="bypassPermissions")&&(o.permissionMode=i)}if(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}typeof r.telegram.verifyDone=="boolean"&&(i.verifyDone=r.telegram.verifyDone),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!==Va(process.cwd(),"afk.config.json")){let i=za(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=dh(r.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(ph(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 Xs={config:o,sourcePath:t,modelsPartial:s},Xs}catch(n){console.error(`Warning: Failed to parse ${t}:`,n)}return Xs={config:{},sourcePath:void 0,modelsPartial:{}},Xs}function aW(){if(Zs!==void 0)return Zs.value;let e=[Va(process.cwd(),"AFK.md"),Va(Le(),"AFK.md")];for(let t of e)if(hh(t))try{let n=cT(t,"utf-8").trim();if(n.length>0)return Zs={value:{content:n,path:t}},Zs.value}catch{}return Zs={value:null},Zs.value}function Lu(){return bh().config.telegram??{}}function Qs(){return bh().config.permissionMode??uT}function Mt(e){let t=iW(),{config:n,sourcePath:r,modelsPartial:o}=bh(),s={...Ja,...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=aW();c!==null&&(s.systemPrompt=c.content,i=`afk-md:${c.path}`)}let a={model:s.model??Ja.model,maxTokens:s.maxTokens??Ja.maxTokens,temperature:s.temperature??Ja.temperature,updatePolicy:s.updatePolicy??Ja.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}:{},permissionMode:s.permissionMode??uT,...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??Tg(o);if(eu(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 Ja,uT,aT,gh,lT,Xs,Zs,Lt=I(()=>{"use strict";Qn();sn();et();q();Vs();qa();V();ur();Ja={model:"sonnet",maxTokens:4096,temperature:1,updatePolicy:"notify"},uT="bypassPermissions",aT=!1;lT=new Set});function lW(e,t){return t!==void 0&&Number.isFinite(t)&&t!==0?t:e.find(r=>r>0)??e[0]}function cW(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=lW(n,t.primaryChatId);return o!==void 0?[o]:[]}function uW(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 dW(e){if(!e)return;let t=e.trim().toLowerCase();return t==="primary"||t==="broadcast"||t==="custom"?t:void 0}function pW(){let e=Lu().notify??{},t=e.mode??dW(E.AFK_TELEGRAM_NOTIFY_MODE),n=e.primaryChatId??uW(E.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...t!==void 0?{mode:t}:{},...n!==void 0?{primaryChatId:n}:{},...e.targets!==void 0?{targets:e.targets}:{}}}function ei(){let e=WE(E.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return cW(e,pW())}var Nu=I(()=>{"use strict";KE();Lt();V()});function wh(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(`
|
|
1080
1080
|
`,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}function dT(e){e=e.replace(/[\x02\x03]/g,"");let t=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),n=[];t=t.replace(/^ {0,3}```([\w]*)\n([\s\S]*?)```/gm,(o,s,i)=>{let a=n.length;if(i.trim()===""){let l=s?`(empty ${s} block)`:"(empty code block)";n.push(`<i>${l}</i>`)}else n.push(`<pre>${i}</pre>`);return`FENCED${a}`});let r=[];return t=t.replace(/`([^`]+)`/g,(o,s)=>{let i=r.length;return r.push(`<code>${s}</code>`),`CODE${i}`}),t=t.replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>"),t=t.replace(/__([^_]+)__/g,"<b>$1</b>"),t=t.replace(/\*([^*]+)\*/g,"<i>$1</i>"),t=t.replace(/(^|[^\w])_([^_\n]+?)_(?!\w)/gm,"$1<i>$2</i>"),t=t.replace(/~~([^~]+)~~/g,"<s>$1</s>"),t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(o,s,i)=>'<a href="'+i.replace(/"/g,""")+'">'+s+"</a>"),t=t.replace(/^#{1,6}\s+/gm,""),t=t.replace(/\x02CODE(\d+)\x03/g,(o,s)=>r[Number(s)]??o),t=t.replace(/\x02FENCED(\d+)\x03/g,(o,s)=>n[Number(s)]??o),mW(t)||(t=t.replace(/<\/?[bis]>/g,"")),t}function mW(e){let t=[],n=/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g,r;for(;(r=n.exec(e))!==null;){let o=(r[2]??"").toLowerCase();if(r[1]==="/"){if(t.pop()!==o)return!1}else t.push(o)}return t.length===0}var pT=I(()=>{"use strict"});var Sh={};Ac(Sh,{push:()=>ti,pushIfConfigured:()=>An,pushMarkdown:()=>mT});async function ti(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??fW}/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 mT(e){let t=dT(e.text),n=wh(t),r={ok:!0,status:200};for(let o of n)if(r=await ti({...e,text:o,parseMode:"HTML"}),!r.ok)return r.status===400&&/can't parse entities/i.test(r.errorMessage??"")?ti({...e}):r;return r}async function An(e,t={}){let n=E.TELEGRAM_BOT_TOKEN;if(!n)return null;let r=ei();if(r.length===0)return null;let o=wh(e),s=[];for(let i of r)for(let a=0;a<o.length;a++){let l={token:n,chatId:i,text:o[a]??"",...t.replyMarkup!==void 0&&a===0?{replyMarkup:t.replyMarkup}:{},...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}};s.push(t.markdown?await mT(l):await ti({...l,...t.parseMode!==void 0?{parseMode:t.parseMode}:{}}))}return s}var fW,Lr=I(()=>{"use strict";Nu();pT();V();fW="https://api.telegram.org"});function gW(e=ti){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>fT)return{content:`Invalid input: message exceeds Telegram's ${fT}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=E.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=ei();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 fT,gT,hT=I(()=>{"use strict";V();Lr();Nu();fT=4096;gT=gW()});import{JSDOM as hW}from"jsdom";import{Readability as yW}from"@mozilla/readability";import bW from"turndown";function yT(e){return e.replace(/\n{3,}/g,`
|
|
1081
1081
|
|
|
1082
|
-
`).trim()}function wW(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function wT(e,t){let r=new hW(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new yW(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=yT(vh.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=yT(vh.turndown(a));return{title:o,markdown:l,textLength:wW(i),usedFallback:!0}}var bT,vh,ST=I(()=>{"use strict";bT=200,vh=new bW({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});vh.remove(["script","style","noscript","iframe"])});function vW(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(t?.reason??new Error("aborted"))},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function vT(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function kW(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function Bu(e,t,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??vW,l=n.signal??void 0,c;for(let u=0;u<=o;u++){if(l?.aborted)throw l.reason??new Error("aborted");try{let d=await e(t,n);if(!SW.has(d.status)||u===o)return d;let p=kW(d,i)??vT(u,s,i);W("[web/retryFetch] retrying",{url:t,attempt:u,status:d.status,waitMs:p}),await d.body?.cancel().catch(()=>{}),await a(p,l)}catch(d){if(l?.aborted||(c=d,u===o))throw d;let p=vT(u,s,i);W("[web/retryFetch] retrying after error",{url:t,attempt:u,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var SW,kh=I(()=>{"use strict";Ie();SW=new Set([429,502,503,504])});import{readFileSync as EW}from"node:fs";import{join as TW}from"path";function xW(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function kT(e,t){return xW(t).test(e)}function AW(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(RW.has(t))return!0;if(CW.has(t))return!1}return!1}function ET(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function _W(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 TT(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Aa(t),t}function IW(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function PW(e){try{return EW(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function MW(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=TT(t.defaultProfile)),n}function xT(e){let t=e?.env??E,n=e?.readFileSync??PW,r=e?.surface??t.AGENT_SURFACE,o=AW(t.AFK_BROWSER_HEADLESS,r),s=ET(t.AFK_BROWSER_ALLOWED_DOMAINS),i=ET(t.AFK_BROWSER_BLOCKED_DOMAINS),a=IW(t.AFK_BROWSER_DOM_SNAPSHOTS),l=_W(t.AFK_BROWSER_BACKEND),c=TT(t.AFK_BROWSER_DEFAULT_PROFILE),u={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},d=t.AFK_BROWSER_CONFIG,p=d!==void 0&&d.trim()!==""?d.trim():TW(rn(),"browser.json"),m=n(p);if(m===void 0)return u;let g;try{g=JSON.parse(m)}catch(b){throw new Error(`Failed to parse browser config at ${p}: ${String(b)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=MW(u,g);return h.configPath=p,h}function Eh(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(kT(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>kT(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var RW,CW,Th=I(()=>{"use strict";V();q();RW=new Set(["daemon","subagent","telegram","afk"]),CW=new Set(["repl","interactive","cli"])});import $o from"node:fs";import Uu from"node:path";import{randomBytes as OW}from"node:crypto";import{chromium as $W}from"playwright";function DW(){try{return"5.15.12"}catch{}try{let e=Uu.resolve(import.meta.dirname,"../../../package.json"),t=$o.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var FW,ju,RT=I(()=>{"use strict";q();Ie();FW=DW(),ju=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=$W.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,i),s}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),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${FW}`}}loadStorageState(t){let n=_a(t);try{if(!$o.existsSync(n))return;let r=JSON.parse($o.readFileSync(n,"utf8"));return W("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){W("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=_a(t);if(!$o.existsSync(r))return;let o=await n.storageState(),s=Uu.join(Uu.dirname(r),`.${Uu.basename(r)}.${process.pid}.${OW(4).toString("hex")}.tmp`);$o.writeFileSync(s,JSON.stringify(o),{mode:384}),$o.chmodSync(s,384),$o.renameSync(s,r),W("[browser/vault] saved session",{profile:t,file:r})}catch(r){W("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as LW}from"crypto";function xh(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of NW)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function CT(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&BW.test(e.label))}function AT(e){return LW("sha256").update(e,"utf8").digest("hex").slice(0,8)}function _T(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var NW,BW,Ya=I(()=>{"use strict";NW=[{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}];BW=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as UW}from"node:crypto";function jW(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function HW(e,t,n){return`el_${UW("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function WW(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function IT(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function MT(e,t){let n=e.role??"",r=e.name??"";PT.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])MT(s,t)}async function KW(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},OT).catch(()=>[])}async function GW(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,m=i==="input"?s.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),m!==void 0&&(g.checked=m),o.push(g)}return o},OT).catch(()=>[])}function qW(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Hu(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=qW(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=KW(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,m,g,h]=await Promise.all([i,a,l,c,u]),b,y=!1;d!==null?(b=[],MT(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await GW(e)).filter(M=>PT.has(M.role??"")));let w=new Map;for(let x of p){let M=IT(x.name),U=w.get(M);(!U||U.bbox.w===0&&x.bbox.w>0)&&w.set(M,x)}let S=b.map(x=>({ax:x,dom:w.get(IT(x.name??""))})),v=r?S:S.filter(x=>x.dom?x.dom.bbox.w>0||x.dom.bbox.h>0:!0);v.sort((x,M)=>{let U=x.dom?.bbox.y??0,$=M.dom?.bbox.y??0;if(U!==$)return U-$;let B=x.dom?.bbox.x??0,H=M.dom?.bbox.x??0;return B-H}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=v.slice(0,n).map((x,M)=>{let U=x.ax.role??"generic",$=x.ax.name??"",B=HW(U,$,M),H=x.dom?.bbox??{x:0,y:0,w:0,h:0},O=x.dom?.type??null,C=null;x.ax.value!==void 0&&x.ax.value!==null&&(C=String(x.ax.value)),x.ax.checked!==void 0&&(C=String(x.ax.checked)),CT({role:U,kind:O})&&(C="[redacted]");let L={disabled:x.ax.disabled??!1};x.ax.checked!==void 0&&(L.checked=x.ax.checked===!0||x.ax.checked==="mixed"),x.ax.selected!==void 0&&(L.selected=x.ax.selected),x.ax.expanded!==void 0&&(L.expanded=x.ax.expanded);let D;x.dom?.testId?D=`[data-testid="${x.dom.testId}"]`:x.dom?.id&&(D=`#${x.dom.id}`);let j={id:B,role:U,label:jW($),kind:O,value:C,state:L,bbox:H};return D!==void 0&&(j.selector=D),j}),_="idle";try{let x=await e.evaluate(()=>document.readyState);x==="loading"?_="loading":x==="interactive"?_="navigating":_="idle"}catch{_="navigating"}_!=="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 A=WW(m),N=`obs_${t.observationCounter.toString(36)}`,P=new Date().toISOString();return{observationId:N,url:g,title:h,textSummary:A,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:_,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:P}}var PT,OT,$T=I(()=>{"use strict";Ya();PT=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);OT="a[href], button, input, select, textarea, [role], [tabindex], label"});async function DT(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 Rh(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>DT(e,s)))).filter(o=>o!==null)}async function zW(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 Ch(e,t,n){switch(t.kind){case"element_id":return JW(e,t,n);case"selector":return VW(e,t);case"semantic":return YW(e,t)}}async function JW(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 Rh(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function VW(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 Rh(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function YW(e,t){return t.role!==void 0?XW(e,t.text,t.role):ZW(e,t.text,t)}async function XW(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 Rh(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function ZW(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 zW(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),m=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let y=await DT(b.locator,b.index);if(y!==null){let w=`${y.role}:${y.label}:${h}`,S=0;for(let v=0;v<w.length;v++)S=S*31+w.charCodeAt(v)>>>0;m.push({...y,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:m}}var FT=I(()=>{"use strict"});import{randomBytes as QW}from"crypto";import{mkdir as eK,stat as tK,writeFile as nK}from"fs/promises";import{join as Ah}from"path";import{gzip as rK}from"zlib";import{promisify as oK}from"util";function sK(e){return Ah(As(e),"browser")}function iK(e){return Ah(sK(e),"screenshots")}function aK(){return new Date().toISOString().replace(/[:.]/g,"-")}function lK(){return QW(3).toString("hex")}async function _h(e,t,n){if(t.length>LT)throw new Error(`writeScreenshotSidecar: buffer exceeds ${LT} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=iK(e);await eK(r,{recursive:!0});let o=`${aK()}-${lK()}-${n}.png`,s=Ah(r,o);await nK(s,t);let{size:i}=await tK(s);return{path:s,bytes:i}}var bpe,LT,NT=I(()=>{"use strict";q();Ya();bpe=oK(rK);LT=5*1024*1024});var UT={};Ac(UT,{PlaywrightProvider:()=>Ih});function BT(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 Ih,jT=I(()=>{"use strict";RT();$T();FT();Th();Ya();NT();Ih=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new ju(t)}async open(t){let n=Eh(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 Hu(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 Hu(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 Ch(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${BT(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=xh(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=Eh(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 m=await Hu(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,m.interactive,m.url,m.title,g),c!==null)throw c;return m}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 Ch(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${BT(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 _h(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 _h(n,o,r);return s}catch{return null}}}});var Fo={};Ac(Fo,{__resetBrowserRegistryForTests:()=>mK,browserProviderActive:()=>dK,closeBrowserProvider:()=>Ph,getBrowserProvider:()=>uK,peekBrowserProvider:()=>pK});function HT(){Promise.resolve(Ph()).then(()=>{process.exit(130)})}function WT(){Promise.resolve(Ph()).then(()=>{process.exit(143)})}function KT(){_n=null}function cK(){Wu||(process.on("SIGINT",HT),process.on("SIGTERM",WT),process.on("exit",KT),Wu=!0)}function GT(){Wu&&(process.removeListener("SIGINT",HT),process.removeListener("SIGTERM",WT),process.removeListener("exit",KT),Wu=!1)}async function uK(e){return _n!==null?_n:(Do!==null||(Do=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(jT(),UT)),n=xT(e),r=new t(n);return cK(),_n=r,Do=null,r})()),Do)}async function Ph(){if(_n===null)return;let e=_n;_n=null,Do=null,GT(),await e.shutdown()}function dK(){return _n!==null}function pK(){return _n}function mK(){_n=null,Do=null,GT()}var _n,Do,Wu,Lo=I(()=>{"use strict";Th();_n=null,Do=null,Wu=!1});function qT(e,t){try{return wT(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function bK(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Lo(),Fo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function zT(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??bK,o=null,s=e,i=null,a=null;try{let c=await Bu(n,e,{headers:yK,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(hK.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(gK.test(u)&&!fK.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=qT(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<bT)&&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=qT(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 fK,gK,hK,yK,JT=I(()=>{"use strict";ST();kh();Ie();fK=/(text\/html|application\/xhtml\+xml)/i,gK=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,hK=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,yK={"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 vK(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(wK,{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),SK),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=Mo(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 VT(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?vK({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 YT(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
1082
|
+
`).trim()}function wW(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function wT(e,t){let r=new hW(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new yW(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=yT(vh.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=yT(vh.turndown(a));return{title:o,markdown:l,textLength:wW(i),usedFallback:!0}}var bT,vh,ST=I(()=>{"use strict";bT=200,vh=new bW({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});vh.remove(["script","style","noscript","iframe"])});function vW(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(t?.reason??new Error("aborted"))},s=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function vT(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function kW(e,t){let n=e.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,t)}async function Bu(e,t,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??vW,l=n.signal??void 0,c;for(let u=0;u<=o;u++){if(l?.aborted)throw l.reason??new Error("aborted");try{let d=await e(t,n);if(!SW.has(d.status)||u===o)return d;let p=kW(d,i)??vT(u,s,i);W("[web/retryFetch] retrying",{url:t,attempt:u,status:d.status,waitMs:p}),await d.body?.cancel().catch(()=>{}),await a(p,l)}catch(d){if(l?.aborted||(c=d,u===o))throw d;let p=vT(u,s,i);W("[web/retryFetch] retrying after error",{url:t,attempt:u,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var SW,kh=I(()=>{"use strict";Ie();SW=new Set([429,502,503,504])});import{readFileSync as EW}from"node:fs";import{join as TW}from"path";function xW(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function kT(e,t){return xW(t).test(e)}function AW(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(RW.has(t))return!0;if(CW.has(t))return!1}return!1}function ET(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function _W(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 TT(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Aa(t),t}function IW(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function PW(e){try{return EW(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function MW(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=TT(t.defaultProfile)),n}function xT(e){let t=e?.env??E,n=e?.readFileSync??PW,r=e?.surface??t.AGENT_SURFACE,o=AW(t.AFK_BROWSER_HEADLESS,r),s=ET(t.AFK_BROWSER_ALLOWED_DOMAINS),i=ET(t.AFK_BROWSER_BLOCKED_DOMAINS),a=IW(t.AFK_BROWSER_DOM_SNAPSHOTS),l=_W(t.AFK_BROWSER_BACKEND),c=TT(t.AFK_BROWSER_DEFAULT_PROFILE),u={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},d=t.AFK_BROWSER_CONFIG,p=d!==void 0&&d.trim()!==""?d.trim():TW(rn(),"browser.json"),m=n(p);if(m===void 0)return u;let g;try{g=JSON.parse(m)}catch(b){throw new Error(`Failed to parse browser config at ${p}: ${String(b)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=MW(u,g);return h.configPath=p,h}function Eh(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(kT(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>kT(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var RW,CW,Th=I(()=>{"use strict";V();q();RW=new Set(["daemon","subagent","telegram","afk"]),CW=new Set(["repl","interactive","cli"])});import $o from"node:fs";import Uu from"node:path";import{randomBytes as OW}from"node:crypto";import{chromium as $W}from"playwright";function DW(){try{return"5.15.13"}catch{}try{let e=Uu.resolve(import.meta.dirname,"../../../package.json"),t=$o.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var FW,ju,RT=I(()=>{"use strict";q();Ie();FW=DW(),ju=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=$W.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,i),s}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),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${FW}`}}loadStorageState(t){let n=_a(t);try{if(!$o.existsSync(n))return;let r=JSON.parse($o.readFileSync(n,"utf8"));return W("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){W("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=_a(t);if(!$o.existsSync(r))return;let o=await n.storageState(),s=Uu.join(Uu.dirname(r),`.${Uu.basename(r)}.${process.pid}.${OW(4).toString("hex")}.tmp`);$o.writeFileSync(s,JSON.stringify(o),{mode:384}),$o.chmodSync(s,384),$o.renameSync(s,r),W("[browser/vault] saved session",{profile:t,file:r})}catch(r){W("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as LW}from"crypto";function xh(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of NW)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function CT(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&BW.test(e.label))}function AT(e){return LW("sha256").update(e,"utf8").digest("hex").slice(0,8)}function _T(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var NW,BW,Ya=I(()=>{"use strict";NW=[{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}];BW=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as UW}from"node:crypto";function jW(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function HW(e,t,n){return`el_${UW("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function WW(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function IT(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function MT(e,t){let n=e.role??"",r=e.name??"";PT.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])MT(s,t)}async function KW(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},OT).catch(()=>[])}async function GW(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,m=i==="input"?s.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),m!==void 0&&(g.checked=m),o.push(g)}return o},OT).catch(()=>[])}function qW(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Hu(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=qW(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=KW(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,m,g,h]=await Promise.all([i,a,l,c,u]),b,y=!1;d!==null?(b=[],MT(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await GW(e)).filter(M=>PT.has(M.role??"")));let w=new Map;for(let x of p){let M=IT(x.name),U=w.get(M);(!U||U.bbox.w===0&&x.bbox.w>0)&&w.set(M,x)}let S=b.map(x=>({ax:x,dom:w.get(IT(x.name??""))})),v=r?S:S.filter(x=>x.dom?x.dom.bbox.w>0||x.dom.bbox.h>0:!0);v.sort((x,M)=>{let U=x.dom?.bbox.y??0,$=M.dom?.bbox.y??0;if(U!==$)return U-$;let B=x.dom?.bbox.x??0,H=M.dom?.bbox.x??0;return B-H}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let R=v.slice(0,n).map((x,M)=>{let U=x.ax.role??"generic",$=x.ax.name??"",B=HW(U,$,M),H=x.dom?.bbox??{x:0,y:0,w:0,h:0},O=x.dom?.type??null,C=null;x.ax.value!==void 0&&x.ax.value!==null&&(C=String(x.ax.value)),x.ax.checked!==void 0&&(C=String(x.ax.checked)),CT({role:U,kind:O})&&(C="[redacted]");let L={disabled:x.ax.disabled??!1};x.ax.checked!==void 0&&(L.checked=x.ax.checked===!0||x.ax.checked==="mixed"),x.ax.selected!==void 0&&(L.selected=x.ax.selected),x.ax.expanded!==void 0&&(L.expanded=x.ax.expanded);let D;x.dom?.testId?D=`[data-testid="${x.dom.testId}"]`:x.dom?.id&&(D=`#${x.dom.id}`);let j={id:B,role:U,label:jW($),kind:O,value:C,state:L,bbox:H};return D!==void 0&&(j.selector=D),j}),_="idle";try{let x=await e.evaluate(()=>document.readyState);x==="loading"?_="loading":x==="interactive"?_="navigating":_="idle"}catch{_="navigating"}_!=="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 A=WW(m),N=`obs_${t.observationCounter.toString(36)}`,P=new Date().toISOString();return{observationId:N,url:g,title:h,textSummary:A,interactive:R,status:{httpStatus:t.httpStatus??null,loadingState:_,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:P}}var PT,OT,$T=I(()=>{"use strict";Ya();PT=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);OT="a[href], button, input, select, textarea, [role], [tabindex], label"});async function DT(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 Rh(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>DT(e,s)))).filter(o=>o!==null)}async function zW(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 Ch(e,t,n){switch(t.kind){case"element_id":return JW(e,t,n);case"selector":return VW(e,t);case"semantic":return YW(e,t)}}async function JW(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 Rh(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function VW(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 Rh(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function YW(e,t){return t.role!==void 0?XW(e,t.text,t.role):ZW(e,t.text,t)}async function XW(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 Rh(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function ZW(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 zW(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),m=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let y=await DT(b.locator,b.index);if(y!==null){let w=`${y.role}:${y.label}:${h}`,S=0;for(let v=0;v<w.length;v++)S=S*31+w.charCodeAt(v)>>>0;m.push({...y,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:m}}var FT=I(()=>{"use strict"});import{randomBytes as QW}from"crypto";import{mkdir as eK,stat as tK,writeFile as nK}from"fs/promises";import{join as Ah}from"path";import{gzip as rK}from"zlib";import{promisify as oK}from"util";function sK(e){return Ah(As(e),"browser")}function iK(e){return Ah(sK(e),"screenshots")}function aK(){return new Date().toISOString().replace(/[:.]/g,"-")}function lK(){return QW(3).toString("hex")}async function _h(e,t,n){if(t.length>LT)throw new Error(`writeScreenshotSidecar: buffer exceeds ${LT} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=iK(e);await eK(r,{recursive:!0});let o=`${aK()}-${lK()}-${n}.png`,s=Ah(r,o);await nK(s,t);let{size:i}=await tK(s);return{path:s,bytes:i}}var bpe,LT,NT=I(()=>{"use strict";q();Ya();bpe=oK(rK);LT=5*1024*1024});var UT={};Ac(UT,{PlaywrightProvider:()=>Ih});function BT(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 Ih,jT=I(()=>{"use strict";RT();$T();FT();Th();Ya();NT();Ih=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new ju(t)}async open(t){let n=Eh(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 Hu(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 Hu(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 Ch(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${BT(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=xh(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=Eh(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 m=await Hu(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,m.interactive,m.url,m.title,g),c!==null)throw c;return m}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 Ch(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${BT(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 _h(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 _h(n,o,r);return s}catch{return null}}}});var Fo={};Ac(Fo,{__resetBrowserRegistryForTests:()=>mK,browserProviderActive:()=>dK,closeBrowserProvider:()=>Ph,getBrowserProvider:()=>uK,peekBrowserProvider:()=>pK});function HT(){Promise.resolve(Ph()).then(()=>{process.exit(130)})}function WT(){Promise.resolve(Ph()).then(()=>{process.exit(143)})}function KT(){_n=null}function cK(){Wu||(process.on("SIGINT",HT),process.on("SIGTERM",WT),process.on("exit",KT),Wu=!0)}function GT(){Wu&&(process.removeListener("SIGINT",HT),process.removeListener("SIGTERM",WT),process.removeListener("exit",KT),Wu=!1)}async function uK(e){return _n!==null?_n:(Do!==null||(Do=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(jT(),UT)),n=xT(e),r=new t(n);return cK(),_n=r,Do=null,r})()),Do)}async function Ph(){if(_n===null)return;let e=_n;_n=null,Do=null,GT(),await e.shutdown()}function dK(){return _n!==null}function pK(){return _n}function mK(){_n=null,Do=null,GT()}var _n,Do,Wu,Lo=I(()=>{"use strict";Th();_n=null,Do=null,Wu=!1});function qT(e,t){try{return wT(e,t)}catch(n){return W("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function bK(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Lo(),Fo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function zT(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??bK,o=null,s=e,i=null,a=null;try{let c=await Bu(n,e,{headers:yK,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(hK.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(gK.test(u)&&!fK.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=qT(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<bT)&&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=qT(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 fK,gK,hK,yK,JT=I(()=>{"use strict";ST();kh();Ie();fK=/(text\/html|application\/xhtml\+xml)/i,gK=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,hK=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,yK={"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 vK(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(wK,{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),SK),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=Mo(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 VT(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?vK({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 YT(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
1083
1083
|
|
|
1084
1084
|
(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(`
|
|
1085
1085
|
`).trimEnd()}var wK,SK,XT=I(()=>{"use strict";Oo();wK="https://api.exa.ai/search",SK=10});function _K(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=kK;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,EK)}let a=TK;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,xK)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Mh(e,t){let n=Buffer.from(e,"utf8");return n.byteLength<=t?e:n.subarray(0,t).toString("utf8")+RK}function IK(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 AK.some(o=>r.includes(o))}function PK(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=_K(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 Bu(t,s.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:i.signal})}catch(m){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape network error: ${m instanceof Error?m.message:String(m)}`,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(m){return{content:`web_scrape read error: ${m instanceof Error?m.message:String(m)}`,isError:!0}}return{content:Mh(p,s.maxBytes)}}if(s.mode==="markdown")try{let d=await zT(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:Mh(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),m=IK(d)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${p}${m}`,isError:!0}}let u=VT({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:CK,timeoutMs:s.timeoutMs,signal:i.signal});return{content:Mh(YT(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 kK,EK,TK,xK,RK,CK,AK,ZT,QT=I(()=>{"use strict";JT();XT();kh();kK=3e4,EK=12e4,TK=1e6,xK=1e7,RK=`
|
|
@@ -1206,7 +1206,7 @@ Arguments: ${o}`}
|
|
|
1206
1206
|
|
|
1207
1207
|
${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}:{}};We({event:"skill.dispatched",...i,...cC(t)?{is_gate:!0}:{}}).catch(()=>{}),We({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=Be(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=fl({childModel:l,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(l):lr(l),parentApiKey:this.ctx.apiKey}),u=new ie({parentAbortSignal:s.signal,apiKey:c,parentModel:l,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:Vt(),...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),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:m}=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]
|
|
1208
1208
|
|
|
1209
|
-
${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(W),await m?.teardownAll(),await u.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=yl(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 jo(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}function ui(e={}){return({childExecutor:t,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??Z2},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return re(typeof r=="string"?r:void 0)==="openai-compatible"?new Bt({...i,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new rt({...i,readOnlyMemory:!0})}}function uC(e){let t={allowedTools:[...Od]};return re(typeof e=="string"?e:void 0)==="openai-compatible"?new Bt({permissions:t,readOnlyBash:!0,readOnlyMemory:!0}):new rt({permissions:t,readOnlyBash:!0,readOnlyMemory:!0})}function di(e,t,n,r,o,s,i,a,l,c){let u=(d,p,m)=>new Ln({parentSession:jo(m),defaultModel:e,...c!==void 0?{defaultSubagentModel:c}:{},apiKey:t,...r!==void 0?{baseUrl:r}:{},depth:d,maxDepth:p,childProviderFactory:n,childSkillExecutorFactory:u,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...i!==void 0?{cwd:i}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...l!==void 0?{surface:l}:{}});return u}function dC(e,t){let n={allowedTools:[...e]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new Bt({permissions:n}):new rt({permissions:n})}function pC(e,t){let n={allowedTools:[...NR]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new Bt({permissions:n}):new rt({permissions:n})}var li,Z2,Od,xy,Jr=I(()=>{"use strict";Wo();ll();et();Rn();or();dl();hl();li=3;Z2=[...Yt,...bt,"memory_search","agent","skill"],Od=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...bt,"memory_search","agent","skill"],xy=new Set(["ground-state"])});var $d,mC=I(()=>{"use strict";Ie();cu();tr();uu();Ne();Ut();$d=class{constructor(t,n,r,o,s,i,a,l,c,u,d,p,m,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=m}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=pl();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=lu(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",Eo(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?(Eo(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(Eo(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=pl();let s=n??this.progressSink??Vt(),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 KR(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=Rd(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??Vt();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(t,o).then(s=>{n?.(s)}).catch(s=>{W("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",Eo(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 zk(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)W(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){W(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}}});var Q2,ie,ze=I(()=>{"use strict";Kk();pi();cu();uu();Ne();er();tr();Jr();Id();et();mC();Q2=async(e,t)=>({action:"decline"}),ie=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentCwd;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(t={}){if(this.parentCanUseTool=t.canUseTool,this.hookRegistry=t.hookRegistry,this.progressSink=t.progressSink,this.parentApiKey=t.apiKey,this.parentBaseUrl=t.baseUrl,this.parentProvider=t.parentModel!==void 0?re(t.parentModel):void 0,this.parentCwd=t.cwd,this.parentTraceWriter=t.traceWriter,this.parentSurface=t.surface,this.onSubagentSucceededCb=t.onSubagentSucceeded,this.abortGraph=new iu(t.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),t.parentAbortSignal){let n=t.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(t=>({id:t.id,status:t.status}))}get(t){return this.active.get(t)}onChildAborted(t){return this.abortGraph.onChildAborted(this.rootId,t)}setOnSubagentSucceeded(t){this.onSubagentSucceededCb=t}setCwd(t){this.parentCwd=t}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 qk(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:XR({childModel:t.config.model,configApiKey:t.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:t.config.baseUrl??(re(t.config.model)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:t.config.isNonInteractive??!0,...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}:{},...t.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...t.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!1?{}:{onElicitation:Q2},...t.phaseRole==="read-only"?{provider:pC("read-only",t.config.model)}:{}},a;try{a=new At(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??Vt(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,m=new $d(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??au,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,m);let g=typeof t.config.model=="string"?t.config.model:JSON.stringify(t.config.model);return Eo(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await We({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:g,parent_session_id:t.parent.sessionId}),m}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 Dd(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 Ry=I(()=>{"use strict"});import{fileURLToPath as eq}from"node:url";import{dirname as tq}from"node:path";var nq,wye,Ko,Cy=I(()=>{"use strict";nq=eq(import.meta.url),wye=tq(nq),Ko={name:"research-agent",systemPrompt:`---
|
|
1209
|
+
${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(W),await m?.teardownAll(),await u.teardownAll()}}getPluginSkillBody(t){return this.pluginBodies||(this.pluginBodies=yl(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 jo(e){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:e}}function ui(e={}){return({childExecutor:t,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??Z2},subagentExecutor:t,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return re(typeof r=="string"?r:void 0)==="openai-compatible"?new Bt({...i,...e.openaiBaseUrl!==void 0?{baseURL:e.openaiBaseUrl}:{},readOnlyMemory:!0}):new rt({...i,readOnlyMemory:!0})}}function uC(e){let t={allowedTools:[...Od]};return re(typeof e=="string"?e:void 0)==="openai-compatible"?new Bt({permissions:t,readOnlyBash:!0,readOnlyMemory:!0}):new rt({permissions:t,readOnlyBash:!0,readOnlyMemory:!0})}function di(e,t,n,r,o,s,i,a,l,c){let u=(d,p,m)=>new Ln({parentSession:jo(m),defaultModel:e,...c!==void 0?{defaultSubagentModel:c}:{},apiKey:t,...r!==void 0?{baseUrl:r}:{},depth:d,maxDepth:p,childProviderFactory:n,childSkillExecutorFactory:u,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...i!==void 0?{cwd:i}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...l!==void 0?{surface:l}:{}});return u}function dC(e,t){let n={allowedTools:[...e]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new Bt({permissions:n}):new rt({permissions:n})}function pC(e,t){let n={allowedTools:[...NR]};return re(typeof t=="string"?t:void 0)==="openai-compatible"?new Bt({permissions:n}):new rt({permissions:n})}var li,Z2,Od,xy,Jr=I(()=>{"use strict";Wo();ll();et();Rn();or();dl();hl();li=3;Z2=[...Yt,...bt,"memory_search","agent","skill"],Od=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...bt,"memory_search","agent","skill"],xy=new Set(["ground-state"])});var $d,mC=I(()=>{"use strict";Ie();cu();tr();uu();Ne();Ut();$d=class{constructor(t,n,r,o,s,i,a,l,c,u,d,p,m,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=m}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=pl();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=lu(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",Eo(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?(Eo(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(Eo(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=pl();let s=n??this.progressSink??Vt(),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 KR(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=Rd(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??Vt();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(t,o).then(s=>{n?.(s)}).catch(s=>{W("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",Eo(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 zk(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)W(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{let r=this.parentInputStreamRef;r.queueFrameworkContext?r.queueFrameworkContext(n.injectContext):r.pushUserMessage(n.injectContext)}catch(r){W(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}}});var Q2,ie,ze=I(()=>{"use strict";Kk();pi();cu();uu();Ne();er();tr();Jr();Id();et();mC();Q2=async(e,t)=>({action:"decline"}),ie=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentCwd;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(t={}){if(this.parentCanUseTool=t.canUseTool,this.hookRegistry=t.hookRegistry,this.progressSink=t.progressSink,this.parentApiKey=t.apiKey,this.parentBaseUrl=t.baseUrl,this.parentProvider=t.parentModel!==void 0?re(t.parentModel):void 0,this.parentCwd=t.cwd,this.parentTraceWriter=t.traceWriter,this.parentSurface=t.surface,this.onSubagentSucceededCb=t.onSubagentSucceeded,this.abortGraph=new iu(t.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),t.parentAbortSignal){let n=t.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(t=>({id:t.id,status:t.status}))}get(t){return this.active.get(t)}onChildAborted(t){return this.abortGraph.onChildAborted(this.rootId,t)}setOnSubagentSucceeded(t){this.onSubagentSucceededCb=t}setCwd(t){this.parentCwd=t}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 qk(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:XR({childModel:t.config.model,configApiKey:t.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:t.config.baseUrl??(re(t.config.model)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:t.config.isNonInteractive??!0,...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}:{},...t.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...t.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:t.config.permissionBubbler??(this.parentCanUseTool!==void 0&&t.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...t.denyElicitations===!1?{}:{onElicitation:Q2},...t.phaseRole==="read-only"?{provider:pC("read-only",t.config.model)}:{}},a;try{a=new At(i)}catch(h){throw this.abortGraph.dispose(n),h}let l=t.parent.getInputStreamRef?.(),c=t.parent.abortSignal,u=this.progressSink??Vt(),d=t.agentType?.trim()||void 0,p=t.parentId?.trim()||void 0,m=new $d(n,a,s,this.abortGraph,t.outputSchema,t.config.timeoutMs??au,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,m);let g=typeof t.config.model=="string"?t.config.model:JSON.stringify(t.config.model);return Eo(t.config.traceWriter,{transition:"started",subagentId:n,parentId:t.parent.sessionId??this.rootId,model:g,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await We({event:"subagent.dispatched",subagent_id:n,id_prefix:t.idPrefix,model:g,parent_session_id:t.parent.sessionId}),m}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 Dd(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 Ry=I(()=>{"use strict"});import{fileURLToPath as eq}from"node:url";import{dirname as tq}from"node:path";var nq,wye,Ko,Cy=I(()=>{"use strict";nq=eq(import.meta.url),wye=tq(nq),Ko={name:"research-agent",systemPrompt:`---
|
|
1210
1210
|
name: research-agent
|
|
1211
1211
|
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.
|
|
1212
1212
|
model: sonnet
|
|
@@ -1597,9 +1597,13 @@ ${t.body}`)}var Tz,tb=I(()=>{"use strict";Tz=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9
|
|
|
1597
1597
|
`),this.errored=!0,this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null}}}_writeLine(t){if(!(!this.stream||this.errored))try{this.stream.write(t,n=>{n&&(process.stderr.write(`[afk] session-ledger: write error for ${this.sessionId}: ${String(n)}
|
|
1598
1598
|
`),this.errored=!0)})}catch(n){process.stderr.write(`[afk] session-ledger: write threw for ${this.sessionId}: ${String(n)}
|
|
1599
1599
|
`),this.errored=!0}}async close(t){if(!this.closed)return this.record({kind:"closed",...t!==void 0?{reason:t}:{}}),this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(n=>{if(!this.stream){n();return}this.stream.end(()=>n())})}};QJ=250});function O_(e,t,n){e&&(e.aborted?t.abort(e.reason):e.addEventListener("abort",()=>{t.signal.aborted||t.abort(e.reason)},{once:!0})),t.signal.addEventListener("abort",n,{once:!0})}function $_(e,t){let n=e.permissionMode??"default",r=e.persistSession??!0,o={sessionId:e.sessionId,configuredSessionId:e.sessionId,resume:e.resume,resumeSessionAt:e.resumeSessionAt,continue:e.continue,forkSession:e.forkSession,persistSession:r},s={sessionId:e.sessionId,model:t,permissionMode:n};return{sessionIdentity:o,metadata:s}}var D_=I(()=>{"use strict"});var dp,F_=I(()=>{"use strict";dp=class{initializationPromise;resolveInitialization;rejectInitialization;initializationSettled=!1;sessionMetadata;sessionIdentity;constructor(t,n){this.sessionIdentity=t,this.sessionMetadata=n,this.initializationPromise=new Promise((r,o)=>{this.resolveInitialization=r,this.rejectInitialization=o})}waitForInitialization(){return this.initializationPromise}getSessionIdentity(){return{...this.sessionIdentity,sessionId:this.getSessionId()}}getSessionMetadata(){return{...this.sessionMetadata,sessionId:this.getSessionId()}}getSessionId(){return this.sessionMetadata.sessionId??this.sessionIdentity.sessionId}updateSessionIdentity(t){t&&(this.sessionIdentity={...this.sessionIdentity,sessionId:t},this.sessionMetadata={...this.sessionMetadata,sessionId:t})}setSessionMetadata(t){this.sessionMetadata=t(this.sessionMetadata)}resolveInitializationIfNeeded(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}resolveInitializationOnce(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}rejectInitializationOnce(t){this.initializationSettled||(this.initializationSettled=!0,this.rejectInitialization(t))}isInitializationSettled(){return this.initializationSettled}}});function L_(e){try{let t=JSON.parse(e);if(!Array.isArray(t))return null;let n=t.length;if(n===0)return"no results";let r=0,o=0;for(let a of t)if(a&&typeof a=="object"){let l=a.type;l==="fact"?r++:l==="procedure"&&o++}let s=`${n} result${n===1?"":"s"}`;if(r+o!==n)return s;let i=[];return r>0&&i.push(`${r} fact${r===1?"":"s"}`),o>0&&i.push(`${o} procedure${o===1?"":"s"}`),i.length===0?s:`${s} (${i.join(", ")})`}catch{return null}}function N_(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;if(n.target==="hot"&&n.saved===!0){if(n.truncated===!0)return"hot memory saved (truncated to fit cap)";let r=n.usage;if(r&&typeof r=="object"){let o=r.pct;if(typeof o=="number")return`hot memory saved (${o}% of cap)`}return"hot memory saved"}if(n.target==="fact"){if(n.action==="remove")return n.removed===!0?"fact removed":"fact not found";if(n.action==="set"&&typeof n.id=="number")return`fact #${n.id} set`;if(n.action==="supersede"&&typeof n.id=="number"&&typeof n.supersedes=="number")return`fact #${n.id} supersedes #${n.supersedes}`}return null}catch{return null}}function B_(e){try{let t=JSON.parse(e);if(!t||typeof t!="object")return null;let n=t;return typeof n.name=="string"&&n.written===!0?`wrote procedure '${n.name}'`:null}catch{return null}}var U_=I(()=>{"use strict"});function Cb(e){let t=e.trim();if(t.length===0)return null;let n=t[0];if(n!=="{"&&n!=="[")return null;let r=t[t.length-1];if(n==="{"&&r!=="}"||n==="["&&r!=="]")return null;let o;try{o=JSON.parse(t)}catch{return null}return Array.isArray(o)?j_(eV(o)):o!==null&&typeof o=="object"?j_(tV(o)):null}function eV(e){return e.length===0?"[empty array]":e.length===1?"[1 item]":`[${e.length} items]`}function tV(e){let t=Object.keys(e);if(t.length===0)return"{empty object}";let n=t.slice(0,4),r=t.length>4?", \u2026":"";return`{${n.join(", ")}${r}}`}function j_(e){return e.length<=80?e:e.slice(0,79)+"\u2026"}var H_=I(()=>{"use strict"});function W_(e,t){if(!e)return null;let n=nV.get(e);if(!n)return null;try{let r=n(t);if(r===null)return null;let o=Mo(r);return o.length>0?o:null}catch{return null}}var nV,K_=I(()=>{"use strict";U_();H_();Oo();nV=new Map([["memory_search",L_],["memory_update",N_],["procedure_write",B_],["bash",Cb],["Bash",Cb]])});function rV(e){let t=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=e.match(t);if(!n||!n[1]||!n[2]||!n[3])return null;let r=n[1],o=n[2],s=n[3],i=parseFloat(r),a=i;o==="KB"?a=i*1024:o==="MB"?a=i*1024*1024:o==="GB"&&(a=i*1024*1024*1024);let l=r;return i%1===0&&(l=String(Math.floor(i))),l+=o,{sizeLabel:l,sizeBytes:Math.round(a),absolutePath:s.trim()}}function oV(e){if(e<1024)return`${e}B`;let t=e/1024;if(t<1024)return t%1===0?`${Math.floor(t)}KB`:`${t.toFixed(1)}KB`;let n=t/1024;if(n<1024)return n%1===0?`${Math.floor(n)}MB`:`${n.toFixed(1)}MB`;let r=n/1024;return r%1===0?`${Math.floor(r)}GB`:`${r.toFixed(1)}GB`}function sV(e){let t=Buffer.byteLength(e,"utf8"),n=oV(t),r=e.split(`
|
|
1600
|
-
`);if(r.length<=1&&e.length<=80)return{content:e,truncated:!1,sizeBytes:t,sizeLabel:n};if(r.length<=1)return e.length<=80?{content:e,truncated:!1,sizeBytes:t,sizeLabel:n}:{content:e.substring(0,80)+"\u2026",truncated:!0,sizeBytes:t,sizeLabel:n};if(e.length<=80)return{content:e,truncated:!1,sizeBytes:t,sizeLabel:n};let o=r[0]??"",s=o;return o.length>80&&(s=o.substring(0,80)+"\u2026"),{content:s+`\u2026+${r.length} lines`,truncated:!0,lineCount:r.length,sizeBytes:t,sizeLabel:n}}function iV(e,t){let n={...e.raw??{}};return e.inputTokens!==void 0&&(n.input_tokens=e.inputTokens),e.outputTokens!==void 0&&(n.output_tokens=e.outputTokens),e.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=e.cachedInputTokens),e.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=e.cacheCreationTokens),e.totalTokens!==void 0&&(n.total_tokens=e.totalTokens),e.contextWindowTokens!==void 0&&(n.context_window_tokens=e.contextWindowTokens),{sessionId:t,stopReason:e.stopReason??void 0,resultSubtype:e.resultSubtype,durationMs:e.durationMs,durationApiMs:e.durationApiMs,totalCostUsd:e.totalCostUsd,isError:e.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:e.modelUsage,permissionDenials:e.permissionDenials,errors:e.errors}}function aV(e){let t=e.isError===!0?null:W_(e.toolName,e.content),n=t!==null?{display:t}:{},r=rV(e.content);if(r)return{type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:`Output persisted (${r.sizeLabel}) \u2192 ${r.absolutePath}`,isError:e.isError===!0,persistedPath:r.absolutePath,sizeBytes:r.sizeBytes,sizeLabel:r.sizeLabel,...n}};let{content:o,lineCount:s,sizeBytes:i,sizeLabel:a}=sV(e.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:o,isError:e.isError===!0,sizeBytes:i,sizeLabel:a,...e.truncated===!0&&{truncated:!0},...s!==void 0&&{lineCount:s},...n}}}function Ab(e,t){switch(e.type){case"session.init":{let n=e.info;return t.setSessionMetadata(r=>({...r,sessionId:n.sessionId,model:n.model??r.model,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},tools:n.tools?[...n.tools]:r.tools,slashCommands:n.slashCommands?[...n.slashCommands]:r.slashCommands,skills:n.skills?[...n.skills]:r.skills,plugins:n.plugins?n.plugins.map(o=>({...o})):r.plugins,mcpServers:n.mcpServers?n.mcpServers.map(o=>({...o})):r.mcpServers,...n.apiKeySource!==void 0?{apiKeySource:n.apiKeySource}:{},...n.version!==void 0?{claudeCodeVersion:n.version}:{},...n.outputStyle!==void 0?{outputStyle:n.outputStyle}:{}})),t.updateSessionIdentity(n.sessionId),t.resolveInitialization(),null}case"session.status":return t.setSessionMetadata(n=>({...n,sessionId:e.sessionId,...e.permissionMode!==void 0?{permissionMode:e.permissionMode}:{permissionMode:n.permissionMode},...e.status!==void 0?{status:e.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:e.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:e.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(e.sessionId&&t.updateSessionIdentity(e.sessionId),e.text){let n={role:"assistant",content:e.text,timestamp:new Date};return t.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:e.toolUseId,toolName:e.toolName,toolInput:e.toolInput,toolInputRaw:e.toolInputRaw}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:e.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:e.toolUseIds}}};case"tool.output":return aV(e);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:e.toolUseId,diff:e.diff}};case"progress":return{type:"progress",progress:{taskId:e.progress.taskId,description:e.progress.description,...e.progress.summary!==void 0?{summary:e.progress.summary}:{},...e.progress.lastToolName!==void 0?{lastToolName:e.progress.lastToolName}:{},totalTokens:e.progress.totalTokens,toolUses:e.progress.toolUses,durationMs:e.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:e.suggestion};case"turn.completed":{let n=iV(e.usage,e.sessionId??t.getSessionMetadata().sessionId);t.setLastResponseMetadata(n);for(let r=t.conversationHistory.length-1;r>=0;r--){let o=t.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(t.maxBudgetUsd!==void 0&&t.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(t._runningCostUsd=(t._runningCostUsd??0)+n.totalCostUsd,t._runningCostUsd>=t.maxBudgetUsd)){Ek(t.traceWriter,{kind:"monetary",runningCostUsd:t._runningCostUsd,maxBudgetUsd:t.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new _r(t._runningCostUsd,t.maxBudgetUsd);return t.abortBudget(r.message),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:e.error};case"paused":return{type:"paused",reason:e.reason,...e.resetsAt!==void 0?{resetsAt:e.resetsAt}:{},...e.accountId!==void 0?{accountId:e.accountId}:{},...e.autoResume!==void 0?{autoResume:e.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:e.hotSwapped,...e.accountId!==void 0?{accountId:e.accountId}:{}};case"stream.retry":return{type:"stream_retry"};default:return null}}var G_=I(()=>{"use strict";Tt();Ne();K_()});import{z as lV}from"zod";var At,_b=I(()=>{"use strict";Ie();Tt();Ne();et();x_();Vs();cu();A_();Tt();I_();lp();yy();kb();Rb();V();Qn();Hr();Wa();sn();Eb();D_();F_();G_();At=class{config;_pendingPlanExitSeed;_prePlanPermissionMode;currentState="idle";providerQuery;providerIterator;conversationHistory=[];turnCount=0;lastResponseMetadata=null;initPromise=null;inputStream;abortController;_hookRegistry;sessionEndDispatched=!1;stateManager;sessionRunningCostUsd=0;sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};lastStopReason;maxTurnsHit=!1;hookBlocked=!1;sawProviderError=!1;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=null;ledgerInitAttempted=!1;constructor(t){this.config=t.parentSessionId===void 0&&t.planExitControls===void 0?{...t,planExitControls:{setPermissionMode:r=>this.setPermissionMode(r),requestImplementSeed:(r,o)=>{this._pendingPlanExitSeed={message:r,mode:o}},getPrePlanMode:()=>this._prePlanPermissionMode}}:t,this.abortController=new AbortController,this._hookRegistry=t.hookRegistry,O_(t.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(t.model);Oe(t.traceWriter,{phase:"session_init_start",model:n,resolvedModel:xt(t.model)??n,origin:jr(t.surface),actor:gd(t.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&eu(this.config.models),sp(this.config);let t=xt(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=$_(this.config,t);this.stateManager=new dp(n,r),this.inputStream=new xi(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)W(`\u{1F7E2} AgentSession: Creating query session via injected provider=${this.config.provider.name}`),this.providerQuery=this.config.provider.query({prompt:o,config:this.config});else{W("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>op(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new ip({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>re(a),resolveApiKey:a=>lr(a)})}this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionRunningCostUsd=0,this.sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.lastStopReason=void 0,this.maxTurnsHit=!1,this.hookBlocked=!1,this.sawProviderError=!1,this.sessionEndDispatched=!1,this.currentState="idle",this.subagentCompletedCount=0,this.subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.subagentRunningCostUsd=0;let s=this.providerQuery;this.providerIterator=s[Symbol.asyncIterator](),this.initPromise=this.pullInitialization()}async pullInitialization(){try{for(await R_(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});;){let t=await this.providerIterator.next();if(t.done){this.stateManager.resolveInitializationIfNeeded();return}let n=t.value,r=Ab(n,this.buildTransformDeps());if(n.type==="session.init"){await Oe(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(r&&r.type==="error"){this.sawProviderError=!0;return}}}catch(t){let n=t instanceof Error?t:new Error(String(t));n instanceof ge&&(this.hookBlocked=!0),this.stateManager.isInitializationSettled()||this.stateManager.rejectInitializationOnce(n),await this.dispatchSessionEndOnce("error").catch(()=>{})}}buildTransformDeps(){return{conversationHistory:this.conversationHistory,getSessionMetadata:()=>this.stateManager.getSessionMetadata(),setSessionMetadata:t=>this.stateManager.setSessionMetadata(t),updateSessionIdentity:t=>this.stateManager.updateSessionIdentity(t),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:t=>{this.lastResponseMetadata=t,typeof t.totalCostUsd=="number"&&Number.isFinite(t.totalCostUsd)&&(this.sessionRunningCostUsd+=t.totalCostUsd);let n=t.usage;if(n&&typeof n=="object"){let r=n,o=(s,i)=>{let a=r[s];typeof a=="number"&&Number.isFinite(a)&&(this.sessionRunningTokens[i]+=a)};o("input_tokens","input"),o("output_tokens","output"),o("cache_read_input_tokens","cacheRead"),o("cache_creation_input_tokens","cacheCreation")}typeof t.stopReason=="string"&&(this.lastStopReason=t.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:t=>{this.abortController.signal.aborted||this.abortController.abort(t)},...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}}}get state(){return this.currentState}get sessionId(){return this.stateManager.getSessionId()}get cwd(){return this.config.cwd}get abortSignal(){return this.abortController.signal}get hookRegistry(){return this._hookRegistry}abort(t){if(t==="closed"||t.startsWith("Budget ")||t.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${t}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(t)}async sendMessage(t,n={}){this.assertCanSend();let r=this.config.timeoutMs??au,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(t)){if(a.type==="chunk"&&a.chunk.type==="content"&&(i+=a.chunk.content),a.type==="message"&&a.message.role==="assistant"&&(s=a.message),a.type==="error")throw a.error;if(a.type==="done"){if(s)return{...s,metadata:a.metadata};if(i)return{role:"assistant",content:i,metadata:a.metadata,timestamp:new Date}}}if(s)return s;if(i)return{role:"assistant",content:i,timestamp:new Date};throw new Error("No assistant response received")};try{return await lu(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async sendMessageStructured(t,n,r={}){let{maxRetries:o=2,injectSchemaPrompt:s=!0,...i}=r,a=s?"\n\nRespond with ONLY a JSON object (optionally in a ```json fence) that conforms to this JSON Schema:\n```json\n"+JSON.stringify(lV.toJSONSchema(n,{target:"openapi-3.0"}))+"\n```":"",l="";for(let c=0;c<=o;c++){let u=c===0?t+a:`Your previous response did not match the required JSON schema.
|
|
1600
|
+
`);if(r.length<=1&&e.length<=80)return{content:e,truncated:!1,sizeBytes:t,sizeLabel:n};if(r.length<=1)return e.length<=80?{content:e,truncated:!1,sizeBytes:t,sizeLabel:n}:{content:e.substring(0,80)+"\u2026",truncated:!0,sizeBytes:t,sizeLabel:n};if(e.length<=80)return{content:e,truncated:!1,sizeBytes:t,sizeLabel:n};let o=r[0]??"",s=o;return o.length>80&&(s=o.substring(0,80)+"\u2026"),{content:s+`\u2026+${r.length} lines`,truncated:!0,lineCount:r.length,sizeBytes:t,sizeLabel:n}}function iV(e,t){let n={...e.raw??{}};return e.inputTokens!==void 0&&(n.input_tokens=e.inputTokens),e.outputTokens!==void 0&&(n.output_tokens=e.outputTokens),e.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=e.cachedInputTokens),e.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=e.cacheCreationTokens),e.totalTokens!==void 0&&(n.total_tokens=e.totalTokens),e.contextWindowTokens!==void 0&&(n.context_window_tokens=e.contextWindowTokens),{sessionId:t,stopReason:e.stopReason??void 0,resultSubtype:e.resultSubtype,durationMs:e.durationMs,durationApiMs:e.durationApiMs,totalCostUsd:e.totalCostUsd,isError:e.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:e.modelUsage,permissionDenials:e.permissionDenials,errors:e.errors}}function aV(e){let t=e.isError===!0?null:W_(e.toolName,e.content),n=t!==null?{display:t}:{},r=rV(e.content);if(r)return{type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:`Output persisted (${r.sizeLabel}) \u2192 ${r.absolutePath}`,isError:e.isError===!0,persistedPath:r.absolutePath,sizeBytes:r.sizeBytes,sizeLabel:r.sizeLabel,...n}};let{content:o,lineCount:s,sizeBytes:i,sizeLabel:a}=sV(e.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:e.toolUseId,content:o,isError:e.isError===!0,sizeBytes:i,sizeLabel:a,...e.truncated===!0&&{truncated:!0},...s!==void 0&&{lineCount:s},...n}}}function Ab(e,t){switch(e.type){case"session.init":{let n=e.info;return t.setSessionMetadata(r=>({...r,sessionId:n.sessionId,model:n.model??r.model,...n.permissionMode!==void 0?{permissionMode:n.permissionMode}:{},...n.cwd!==void 0?{cwd:n.cwd}:{},tools:n.tools?[...n.tools]:r.tools,slashCommands:n.slashCommands?[...n.slashCommands]:r.slashCommands,skills:n.skills?[...n.skills]:r.skills,plugins:n.plugins?n.plugins.map(o=>({...o})):r.plugins,mcpServers:n.mcpServers?n.mcpServers.map(o=>({...o})):r.mcpServers,...n.apiKeySource!==void 0?{apiKeySource:n.apiKeySource}:{},...n.version!==void 0?{claudeCodeVersion:n.version}:{},...n.outputStyle!==void 0?{outputStyle:n.outputStyle}:{}})),t.updateSessionIdentity(n.sessionId),t.resolveInitialization(),null}case"session.status":return t.setSessionMetadata(n=>({...n,sessionId:e.sessionId,...e.permissionMode!==void 0?{permissionMode:e.permissionMode}:{permissionMode:n.permissionMode},...e.status!==void 0?{status:e.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:e.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:e.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(e.sessionId&&t.updateSessionIdentity(e.sessionId),e.text){let n={role:"assistant",content:e.text,timestamp:new Date};return t.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:e.toolUseId,toolName:e.toolName,toolInput:e.toolInput,toolInputRaw:e.toolInputRaw}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:e.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:e.toolUseIds}}};case"tool.output":return aV(e);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:e.toolUseId,diff:e.diff}};case"progress":return{type:"progress",progress:{taskId:e.progress.taskId,description:e.progress.description,...e.progress.summary!==void 0?{summary:e.progress.summary}:{},...e.progress.lastToolName!==void 0?{lastToolName:e.progress.lastToolName}:{},totalTokens:e.progress.totalTokens,toolUses:e.progress.toolUses,durationMs:e.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:e.suggestion};case"turn.completed":{let n=iV(e.usage,e.sessionId??t.getSessionMetadata().sessionId);t.setLastResponseMetadata(n);for(let r=t.conversationHistory.length-1;r>=0;r--){let o=t.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(t.maxBudgetUsd!==void 0&&t.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(t._runningCostUsd=(t._runningCostUsd??0)+n.totalCostUsd,t._runningCostUsd>=t.maxBudgetUsd)){Ek(t.traceWriter,{kind:"monetary",runningCostUsd:t._runningCostUsd,maxBudgetUsd:t.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new _r(t._runningCostUsd,t.maxBudgetUsd);return t.abortBudget(r.message),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:e.error};case"paused":return{type:"paused",reason:e.reason,...e.resetsAt!==void 0?{resetsAt:e.resetsAt}:{},...e.accountId!==void 0?{accountId:e.accountId}:{},...e.autoResume!==void 0?{autoResume:e.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:e.hotSwapped,...e.accountId!==void 0?{accountId:e.accountId}:{}};case"stream.retry":return{type:"stream_retry"};default:return null}}var G_=I(()=>{"use strict";Tt();Ne();K_()});import{z as lV}from"zod";var At,_b=I(()=>{"use strict";Ie();Tt();Ne();et();x_();Vs();cu();A_();Tt();I_();lp();yy();kb();Rb();V();Qn();Hr();Wa();sn();Eb();D_();F_();G_();At=class{config;_pendingPlanExitSeed;_prePlanPermissionMode;currentState="idle";providerQuery;providerIterator;conversationHistory=[];turnCount=0;pendingFrameworkContext=[];lastResponseMetadata=null;initPromise=null;inputStream;abortController;_hookRegistry;sessionEndDispatched=!1;stateManager;sessionRunningCostUsd=0;sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};lastStopReason;maxTurnsHit=!1;hookBlocked=!1;sawProviderError=!1;sessionStartedAt=Date.now();subagentCompletedCount=0;subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0};subagentRunningCostUsd=0;ledger=null;ledgerInitAttempted=!1;constructor(t){this.config=t.parentSessionId===void 0&&t.planExitControls===void 0?{...t,planExitControls:{setPermissionMode:r=>this.setPermissionMode(r),requestImplementSeed:(r,o)=>{this._pendingPlanExitSeed={message:r,mode:o}},getPrePlanMode:()=>this._prePlanPermissionMode}}:t,this.abortController=new AbortController,this._hookRegistry=t.hookRegistry,O_(t.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(t.model);Oe(t.traceWriter,{phase:"session_init_start",model:n,resolvedModel:xt(t.model)??n,origin:jr(t.surface),actor:gd(t.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&eu(this.config.models),sp(this.config);let t=xt(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=$_(this.config,t);this.stateManager=new dp(n,r),this.inputStream=new xi(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)W(`\u{1F7E2} AgentSession: Creating query session via injected provider=${this.config.provider.name}`),this.providerQuery=this.config.provider.query({prompt:o,config:this.config});else{W("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>op(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new ip({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>re(a),resolveApiKey:a=>lr(a)})}this.conversationHistory=[],this.turnCount=0,this.lastResponseMetadata=null,this.sessionRunningCostUsd=0,this.sessionRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.lastStopReason=void 0,this.maxTurnsHit=!1,this.hookBlocked=!1,this.sawProviderError=!1,this.sessionEndDispatched=!1,this.currentState="idle",this.subagentCompletedCount=0,this.subagentRunningTokens={input:0,output:0,cacheRead:0,cacheCreation:0},this.subagentRunningCostUsd=0,this.pendingFrameworkContext=[];let s=this.providerQuery;this.providerIterator=s[Symbol.asyncIterator](),this.initPromise=this.pullInitialization()}async pullInitialization(){try{for(await R_(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});;){let t=await this.providerIterator.next();if(t.done){this.stateManager.resolveInitializationIfNeeded();return}let n=t.value,r=Ab(n,this.buildTransformDeps());if(n.type==="session.init"){await Oe(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(r&&r.type==="error"){this.sawProviderError=!0;return}}}catch(t){let n=t instanceof Error?t:new Error(String(t));n instanceof ge&&(this.hookBlocked=!0),this.stateManager.isInitializationSettled()||this.stateManager.rejectInitializationOnce(n),await this.dispatchSessionEndOnce("error").catch(()=>{})}}buildTransformDeps(){return{conversationHistory:this.conversationHistory,getSessionMetadata:()=>this.stateManager.getSessionMetadata(),setSessionMetadata:t=>this.stateManager.setSessionMetadata(t),updateSessionIdentity:t=>this.stateManager.updateSessionIdentity(t),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:t=>{this.lastResponseMetadata=t,typeof t.totalCostUsd=="number"&&Number.isFinite(t.totalCostUsd)&&(this.sessionRunningCostUsd+=t.totalCostUsd);let n=t.usage;if(n&&typeof n=="object"){let r=n,o=(s,i)=>{let a=r[s];typeof a=="number"&&Number.isFinite(a)&&(this.sessionRunningTokens[i]+=a)};o("input_tokens","input"),o("output_tokens","output"),o("cache_read_input_tokens","cacheRead"),o("cache_creation_input_tokens","cacheCreation")}typeof t.stopReason=="string"&&(this.lastStopReason=t.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:t=>{this.abortController.signal.aborted||this.abortController.abort(t)},...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}}}get state(){return this.currentState}get sessionId(){return this.stateManager.getSessionId()}get cwd(){return this.config.cwd}get abortSignal(){return this.abortController.signal}get hookRegistry(){return this._hookRegistry}abort(t){if(t==="closed"||t.startsWith("Budget ")||t.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${t}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(t)}async sendMessage(t,n={}){this.assertCanSend();let r=this.config.timeoutMs??au,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(t)){if(a.type==="chunk"&&a.chunk.type==="content"&&(i+=a.chunk.content),a.type==="message"&&a.message.role==="assistant"&&(s=a.message),a.type==="error")throw a.error;if(a.type==="done"){if(s)return{...s,metadata:a.metadata};if(i)return{role:"assistant",content:i,metadata:a.metadata,timestamp:new Date}}}if(s)return s;if(i)return{role:"assistant",content:i,timestamp:new Date};throw new Error("No assistant response received")};try{return await lu(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async sendMessageStructured(t,n,r={}){let{maxRetries:o=2,injectSchemaPrompt:s=!0,...i}=r,a=s?"\n\nRespond with ONLY a JSON object (optionally in a ```json fence) that conforms to this JSON Schema:\n```json\n"+JSON.stringify(lV.toJSONSchema(n,{target:"openapi-3.0"}))+"\n```":"",l="";for(let c=0;c<=o;c++){let u=c===0?t+a:`Your previous response did not match the required JSON schema.
|
|
1601
1601
|
Validation error: ${l}
|
|
1602
|
-
Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,d=await this.sendMessage(u,i),p=xd(d.content),m=n.safeParse(p);if(m.success)return m.data;l=m.error.message}throw new Error(`structured output did not match schema after ${o+1} attempt(s): ${l}`)}async*sendMessageStream(t){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(t)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(t){this.initPromise&&await this.initPromise;let n=typeof t=="string"?t:this.summarizeContentBlocks(t),r={role:"user",content:n,timestamp:new Date};this.conversationHistory.push(r),this.inputStream.pushUserMessage(t),this.ensureLedger(),this.ledger?.recordUser(n);let o=this.buildTransformDeps();try{for(;;){let s=await this.providerIterator.next();if(s.done)break;let i=s.value,a=Ab(i,o);if(a&&(a.type==="done"?(this.turnCount++,this.sawProviderError=!1):a.type==="error"&&(this.sawProviderError=!0),this.ledger?.recordEvent(a),yield a,a.type==="done"||a.type==="error"))break}}finally{this.currentState==="streaming"&&(this.currentState="idle")}}ensureLedger(){if(this.ledgerInitAttempted||(this.ledgerInitAttempted=!0,this.config.depth!==void 0||this.config.parentSessionId!==void 0)||E.AFK_SESSION_LEDGER_DISABLED==="1")return;let t=this.sessionId;if(!t)return;let n=new up(t);if(!n.active)return;this.ledger=n;let r=this.getSessionMetadata();n.record({kind:"meta",sessionId:t,model:r.model??String(this.config.model),...r.cwd!==void 0?{cwd:r.cwd}:{}})}sealLedger(t){let n=this.ledger;return n?(this.ledger=null,this.ledgerInitAttempted=!1,n.close(t)):Promise.resolve()}recordLedgerElicitation(t,n){this.ledger?.record({kind:"elicitation",reqId:t,request:n})}summarizeContentBlocks(t){let n=[],r=0;for(let s of t)s.type==="text"?n.push(s.text):s.type==="image"&&r++;let o=n.join(" ");return r>0&&(o=o?`${o} [+ ${r} image(s)]`:`[+ ${r} image(s)]`),o||"[content block(s)]"}async interrupt(){this.currentState!=="streaming"&&this.currentState!=="processing"||(this.currentState="idle",await this.providerQuery.interrupt())}async reset(){if(this.currentState==="closed")throw new Error("Cannot reset: session is closed");if(this.abortController.signal.aborted)throw new dt("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset"),await this.sealLedger("reset");try{await this.providerQuery.close()}catch{}await this.providerIterator.return?.(),this.initPromise&&await Promise.race([this.initPromise,new Promise(t=>setTimeout(t,Dg))]).catch(()=>{}),this.stateManager.resolveInitializationIfNeeded(),this.config={...this.config},delete this.config.resume,delete this.config.sessionId,delete this.config.resumeHistory,delete this.config.resumeSessionAt,delete this.config.continue,delete this.config.forkSession;try{this.initSdkLifecycle()}catch(t){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async onAbort(){this.sealLedger("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(t){let n=xt(t);typeof t=="string"&&t.length>0&&await this.providerQuery.setModel(t),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(t){if(t==="plan"){let n=this.stateManager.getSessionMetadata().permissionMode;n!=="plan"&&(this._prePlanPermissionMode=n==="autonomous"?void 0:n)}await this.providerQuery.setPermissionMode(t),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:t}))}getPrePlanMode(){return this._prePlanPermissionMode}async takePendingPlanExitSeed(){let t=this._pendingPlanExitSeed;if(this._pendingPlanExitSeed=void 0,t!==void 0){try{await this.setPermissionMode(t.mode)}catch(n){W(`\u26A0\uFE0F AgentSession: deferred plan-exit mode flip to '${t.mode}' rejected; dropping implement-seed (staying in plan mode): ${n instanceof Error?n.message:String(n)}`);return}return t.message}}setCwd(t){this.config={...this.config,cwd:t},this.providerQuery.setCwd?.(t),this.config.sessionId!==void 0&&SE(this.config.sessionId,t)}async reauth(){return await this.providerQuery.reauth?.()??null}waitForInitialization(){return this.stateManager.waitForInitialization()}getSessionIdentity(){return this.stateManager.getSessionIdentity()}getSessionMetadata(){return this.stateManager.getSessionMetadata()}getQuery(){return this.providerQuery}supportedCommands(){return this.providerQuery.supportedCommands()}supportedModels(){return this.providerQuery.supportedModels()}supportedAgents(){return this.providerQuery.supportedAgents()}getContextUsage(){return this.providerQuery.getContextUsage()}mcpServerStatus(){return this.providerQuery.mcpServerStatus()}accountInfo(){return this.providerQuery.accountInfo()}rewindFiles(t,n){return this.providerQuery.rewindFiles(t,n)}async compact(){if(this.currentState==="closed")throw new Error("Cannot compact: session is closed");if(this.currentState!=="idle")return{compacted:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let t=this.providerQuery.compact?.bind(this.providerQuery);if(!t)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await t()}finally{this.currentState="idle"}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){throw new Error("getOutputStream() is not supported \u2014 use sendMessageStream() instead")}getInputStreamRef(){return{pushUserMessage:t=>this.inputStream.pushUserMessage(t)}}getHistory(){return[...this.conversationHistory]}getTurnCount(){return this.turnCount}async close(){if(this.currentState!=="closed"){this.currentState="closed",await this.sealLedger("close"),this.abortController.signal.aborted||this.abortController.abort("closed"),this.stateManager.resolveInitializationIfNeeded();try{await this.providerQuery.close()}catch{}if(await this.providerIterator.return?.(),this.initPromise)try{await Promise.race([this.initPromise,new Promise(t=>setTimeout(t,Dg))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(t){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(t).catch(()=>{}),await this.sealTraceWriter(t).catch(()=>{}),await C_(this._hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:t,parentSessionId:this.config.parentSessionId,...this.config.traceWriter?{tracePath:this.config.traceWriter.getTracePath()}:{}},this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}))}async emitClosure(t){let n=this.config.traceWriter;if(!n)return;let r=this.deriveClosureReason(t),o={};this.sessionRunningTokens.input>0&&(o.input=this.sessionRunningTokens.input),this.sessionRunningTokens.output>0&&(o.output=this.sessionRunningTokens.output),this.sessionRunningTokens.cacheRead>0&&(o.cacheRead=this.sessionRunningTokens.cacheRead),this.sessionRunningTokens.cacheCreation>0&&(o.cacheCreation=this.sessionRunningTokens.cacheCreation);let s=Go(r);await Rk(n,{reason:r,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,finalTokens:o,...this.lastStopReason!==void 0?{lastStopReason:this.lastStopReason}:{},...s!==null?{guidance:s}:{}})}deriveClosureReason(t){let n=null,r=this.abortController.signal;if(r.aborted&&r.reason!=="closed"){let o=r.reason;o instanceof _r?n="budget_exceeded":o instanceof qt?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return __({dispatchReason:t,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,abort:n,lastStopReason:this.lastStopReason,sawProviderError:this.sawProviderError})}async sealTraceWriter(t){let n=this.config.traceWriter;if(!n)return;let r=this.deriveSealStatus(t),o=this.subagentCompletedCount>0?this.subagentCompletedCount:void 0,s=this.subagentRunningTokens,a=s.input>0||s.output>0||s.cacheRead>0||s.cacheCreation>0?{...s.input>0?{input:s.input}:{},...s.output>0?{output:s.output}:{},...s.cacheRead>0?{cacheRead:s.cacheRead}:{},...s.cacheCreation>0?{cacheCreation:s.cacheCreation}:{}}:void 0,l=this.subagentRunningCostUsd>0?this.subagentRunningCostUsd:void 0;await n.seal({status:r,finalCostUsd:this.sessionRunningCostUsd,finalTurnCount:this.turnCount,closedAt:new Date().toISOString(),...o!==void 0?{subagentCount:o}:{},...a!==void 0?{subagentTokens:a}:{},...l!==void 0?{subagentCostUsd:l}:{}})}recordSubagentCompletion(t,n){if(this.subagentCompletedCount++,t){let r=(o,s)=>{typeof o=="number"&&Number.isFinite(o)&&o>0&&(this.subagentRunningTokens[s]+=o)};r(t.inputTokens,"input"),r(t.outputTokens,"output"),r(t.cacheReadTokens,"cacheRead"),r(t.cacheCreationTokens,"cacheCreation")}typeof n=="number"&&Number.isFinite(n)&&n>0&&(this.subagentRunningCostUsd+=n)}deriveSealStatus(t){if(t==="error")return"failed";let n=this.abortController.signal;return n.aborted&&n.reason!=="closed"?"cancelled":this.sawProviderError?"failed":"succeeded"}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new dt("Cannot send message: session aborted");if(this.currentState==="processing"||this.currentState==="streaming"||this.currentState==="compacting")throw new Error("Cannot send message: session is busy");if(this.config.maxTurns&&this.turnCount>=this.config.maxTurns)throw this.maxTurnsHit=!0,new Error(`Maximum turns (${this.config.maxTurns}) exceeded`)}}});var pi=I(()=>{"use strict";_b()});var pP={};Ac(pP,{KeychainOAuthProvider:()=>Fi,clearOauthPending:()=>Nb,readOauthPending:()=>dP});import{existsSync as Ap,mkdirSync as cP,readFileSync as _p,writeFileSync as Lb}from"node:fs";import{execFileSync as sP}from"node:child_process";import{randomUUID as O4}from"node:crypto";import{homedir as iP,userInfo as aP}from"node:os";import{join as lP,dirname as uP}from"node:path";function D4(){let e=process.platform==="darwin",t=process.platform==="linux";return{read(){if(e)try{return sP("security",["find-generic-password","-s","Claude Code-credentials","-a",aP().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()||void 0}catch{return}if(t){let n=lP(iP(),".claude",".credentials.json");if(!Ap(n))return;try{return _p(n,"utf-8")}catch{return}}},write(n){if(e)sP("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",aP().username,"-w",n],{stdio:["ignore","ignore","ignore"]});else if(t){let r=lP(iP(),".claude",".credentials.json");cP(uP(r),{recursive:!0}),Lb(r,n,{encoding:"utf-8",mode:384})}}}}function dP(){let e=Pa();if(!Ap(e))return{};let t;try{t=JSON.parse(_p(e,"utf-8"))}catch{return{}}if(t===null||typeof t!="object")return{};let n={};for(let[r,o]of Object.entries(t)){if(o===null||typeof o!="object")continue;let s=o;s.status==="oauth_pending"&&typeof s.authorizationUrl=="string"&&typeof s.timestamp=="number"&&Date.now()-s.timestamp<=$4&&(n[r]={status:"oauth_pending",authorizationUrl:s.authorizationUrl,timestamp:s.timestamp})}return n}function Nb(e){let t=Pa();if(!Ap(t))return;let n;try{n=JSON.parse(_p(t,"utf-8"))}catch{return}e in n&&(delete n[e],Lb(t,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}))}function F4(e,t){let n=Pa();cP(uP(n),{recursive:!0});let r={};if(Ap(n))try{r=JSON.parse(_p(n,"utf-8"))}catch{}let o=new URL(t),s=o.origin+o.pathname;r[e]={status:"oauth_pending",authorizationUrl:s,timestamp:Date.now()},Lb(n,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}var $4,Fi,Ip=I(()=>{"use strict";q();$4=600*1e3;Fi=class{serverName;backend;constructor(t,n=D4()){this.serverName=t,this.backend=n}get redirectUrl(){return"http://localhost:3000/oauth/callback"}get clientMetadata(){return{redirect_uris:[this.redirectUrl],client_name:"agent-afk",grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}clientInformation(){return this._readSlot().clientInfo}saveClientInformation(t){this._updateSlot(n=>({...n,clientInfo:t}))}tokens(){return this._readSlot().tokens}saveTokens(t){this._updateSlot(n=>({...n,tokens:t}));try{Nb(this.serverName)}catch{}}saveCodeVerifier(t){this._updateSlot(n=>({...n,codeVerifier:t}))}codeVerifier(){let t=this._readSlot().codeVerifier;if(!t)throw new Error(`[mcp:${this.serverName}] no PKCE code verifier stored`);return t}state(){let t=this._readSlot().state;if(t)return t;let n=O4();return this._updateSlot(r=>({...r,state:n})),n}saveDiscoveryState(t){this._updateSlot(n=>({...n,discoveryState:t}))}discoveryState(){return this._readSlot().discoveryState}invalidateCredentials(t){this._updateSlot(n=>{if(t==="all")return{};let r={...n};return t==="client"&&delete r.clientInfo,t==="tokens"&&delete r.tokens,t==="verifier"&&(delete r.codeVerifier,delete r.state),t==="discovery"&&delete r.discoveryState,r})}async redirectToAuthorization(t){let n=t.toString(),r=`\u{1F510} MCP server "${this.serverName}" requires authorization.
|
|
1602
|
+
Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,d=await this.sendMessage(u,i),p=xd(d.content),m=n.safeParse(p);if(m.success)return m.data;l=m.error.message}throw new Error(`structured output did not match schema after ${o+1} attempt(s): ${l}`)}async*sendMessageStream(t){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(t)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(t){this.initPromise&&await this.initPromise;let n=this.withPendingFrameworkContext(t),r=typeof n=="string"?n:this.summarizeContentBlocks(n),o={role:"user",content:r,timestamp:new Date};this.conversationHistory.push(o),this.inputStream.pushUserMessage(n),this.ensureLedger(),this.ledger?.recordUser(r);let s=this.buildTransformDeps();try{for(;;){let i=await this.providerIterator.next();if(i.done)break;let a=i.value,l=Ab(a,s);if(l&&(l.type==="done"?(this.turnCount++,this.sawProviderError=!1):l.type==="error"&&(this.sawProviderError=!0),this.ledger?.recordEvent(l),yield l,l.type==="done"||l.type==="error"))break}}finally{this.currentState==="streaming"&&(this.currentState="idle")}}ensureLedger(){if(this.ledgerInitAttempted||(this.ledgerInitAttempted=!0,this.config.depth!==void 0||this.config.parentSessionId!==void 0)||E.AFK_SESSION_LEDGER_DISABLED==="1")return;let t=this.sessionId;if(!t)return;let n=new up(t);if(!n.active)return;this.ledger=n;let r=this.getSessionMetadata();n.record({kind:"meta",sessionId:t,model:r.model??String(this.config.model),...r.cwd!==void 0?{cwd:r.cwd}:{}})}sealLedger(t){let n=this.ledger;return n?(this.ledger=null,this.ledgerInitAttempted=!1,n.close(t)):Promise.resolve()}recordLedgerElicitation(t,n){this.ledger?.record({kind:"elicitation",reqId:t,request:n})}summarizeContentBlocks(t){let n=[],r=0;for(let s of t)s.type==="text"?n.push(s.text):s.type==="image"&&r++;let o=n.join(" ");return r>0&&(o=o?`${o} [+ ${r} image(s)]`:`[+ ${r} image(s)]`),o||"[content block(s)]"}async interrupt(){this.currentState!=="streaming"&&this.currentState!=="processing"||(this.currentState="idle",await this.providerQuery.interrupt())}async reset(){if(this.currentState==="closed")throw new Error("Cannot reset: session is closed");if(this.abortController.signal.aborted)throw new dt("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset"),await this.sealLedger("reset");try{await this.providerQuery.close()}catch{}await this.providerIterator.return?.(),this.initPromise&&await Promise.race([this.initPromise,new Promise(t=>setTimeout(t,Dg))]).catch(()=>{}),this.stateManager.resolveInitializationIfNeeded(),this.config={...this.config},delete this.config.resume,delete this.config.sessionId,delete this.config.resumeHistory,delete this.config.resumeSessionAt,delete this.config.continue,delete this.config.forkSession;try{this.initSdkLifecycle()}catch(t){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${t instanceof Error?t.message:String(t)}`,{cause:t})}}async onAbort(){this.sealLedger("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(t){let n=xt(t);typeof t=="string"&&t.length>0&&await this.providerQuery.setModel(t),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(t){if(t==="plan"){let n=this.stateManager.getSessionMetadata().permissionMode;n!=="plan"&&(this._prePlanPermissionMode=n==="autonomous"?void 0:n)}await this.providerQuery.setPermissionMode(t),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:t}))}getPrePlanMode(){return this._prePlanPermissionMode}async takePendingPlanExitSeed(){let t=this._pendingPlanExitSeed;if(this._pendingPlanExitSeed=void 0,t!==void 0){try{await this.setPermissionMode(t.mode)}catch(n){W(`\u26A0\uFE0F AgentSession: deferred plan-exit mode flip to '${t.mode}' rejected; dropping implement-seed (staying in plan mode): ${n instanceof Error?n.message:String(n)}`);return}return t.message}}setCwd(t){this.config={...this.config,cwd:t},this.providerQuery.setCwd?.(t),this.config.sessionId!==void 0&&SE(this.config.sessionId,t)}async reauth(){return await this.providerQuery.reauth?.()??null}waitForInitialization(){return this.stateManager.waitForInitialization()}getSessionIdentity(){return this.stateManager.getSessionIdentity()}getSessionMetadata(){return this.stateManager.getSessionMetadata()}getQuery(){return this.providerQuery}supportedCommands(){return this.providerQuery.supportedCommands()}supportedModels(){return this.providerQuery.supportedModels()}supportedAgents(){return this.providerQuery.supportedAgents()}getContextUsage(){return this.providerQuery.getContextUsage()}mcpServerStatus(){return this.providerQuery.mcpServerStatus()}accountInfo(){return this.providerQuery.accountInfo()}rewindFiles(t,n){return this.providerQuery.rewindFiles(t,n)}async compact(){if(this.currentState==="closed")throw new Error("Cannot compact: session is closed");if(this.currentState!=="idle")return{compacted:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let t=this.providerQuery.compact?.bind(this.providerQuery);if(!t)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await t()}finally{this.currentState="idle"}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){throw new Error("getOutputStream() is not supported \u2014 use sendMessageStream() instead")}queueFrameworkContext(t){let n=t.trim();n.length!==0&&(this.pendingFrameworkContext.push(n),W(`AgentSession: queued framework context (${n.length} chars) for the next user message`))}withPendingFrameworkContext(t){if(this.pendingFrameworkContext.length===0)return t;let n=this.pendingFrameworkContext.join(`
|
|
1603
|
+
|
|
1604
|
+
`);return this.pendingFrameworkContext=[],typeof t=="string"?`${n}
|
|
1605
|
+
|
|
1606
|
+
${t}`:[{type:"text",text:n},...t]}getInputStreamRef(){return{pushUserMessage:t=>this.inputStream.pushUserMessage(t),queueFrameworkContext:t=>this.queueFrameworkContext(t)}}getHistory(){return[...this.conversationHistory]}getTurnCount(){return this.turnCount}async close(){if(this.currentState!=="closed"){this.currentState="closed",await this.sealLedger("close"),this.abortController.signal.aborted||this.abortController.abort("closed"),this.stateManager.resolveInitializationIfNeeded();try{await this.providerQuery.close()}catch{}if(await this.providerIterator.return?.(),this.initPromise)try{await Promise.race([this.initPromise,new Promise(t=>setTimeout(t,Dg))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(t){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(t).catch(()=>{}),await this.sealTraceWriter(t).catch(()=>{}),await C_(this._hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:t,parentSessionId:this.config.parentSessionId,...this.config.traceWriter?{tracePath:this.config.traceWriter.getTracePath()}:{}},this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}))}async emitClosure(t){let n=this.config.traceWriter;if(!n)return;let r=this.deriveClosureReason(t),o={};this.sessionRunningTokens.input>0&&(o.input=this.sessionRunningTokens.input),this.sessionRunningTokens.output>0&&(o.output=this.sessionRunningTokens.output),this.sessionRunningTokens.cacheRead>0&&(o.cacheRead=this.sessionRunningTokens.cacheRead),this.sessionRunningTokens.cacheCreation>0&&(o.cacheCreation=this.sessionRunningTokens.cacheCreation);let s=Go(r);await Rk(n,{reason:r,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,finalTokens:o,...this.lastStopReason!==void 0?{lastStopReason:this.lastStopReason}:{},...s!==null?{guidance:s}:{}})}deriveClosureReason(t){let n=null,r=this.abortController.signal;if(r.aborted&&r.reason!=="closed"){let o=r.reason;o instanceof _r?n="budget_exceeded":o instanceof qt?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return __({dispatchReason:t,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,abort:n,lastStopReason:this.lastStopReason,sawProviderError:this.sawProviderError})}async sealTraceWriter(t){let n=this.config.traceWriter;if(!n)return;let r=this.deriveSealStatus(t),o=this.subagentCompletedCount>0?this.subagentCompletedCount:void 0,s=this.subagentRunningTokens,a=s.input>0||s.output>0||s.cacheRead>0||s.cacheCreation>0?{...s.input>0?{input:s.input}:{},...s.output>0?{output:s.output}:{},...s.cacheRead>0?{cacheRead:s.cacheRead}:{},...s.cacheCreation>0?{cacheCreation:s.cacheCreation}:{}}:void 0,l=this.subagentRunningCostUsd>0?this.subagentRunningCostUsd:void 0;await n.seal({status:r,finalCostUsd:this.sessionRunningCostUsd,finalTurnCount:this.turnCount,closedAt:new Date().toISOString(),...o!==void 0?{subagentCount:o}:{},...a!==void 0?{subagentTokens:a}:{},...l!==void 0?{subagentCostUsd:l}:{}})}recordSubagentCompletion(t,n){if(this.subagentCompletedCount++,t){let r=(o,s)=>{typeof o=="number"&&Number.isFinite(o)&&o>0&&(this.subagentRunningTokens[s]+=o)};r(t.inputTokens,"input"),r(t.outputTokens,"output"),r(t.cacheReadTokens,"cacheRead"),r(t.cacheCreationTokens,"cacheCreation")}typeof n=="number"&&Number.isFinite(n)&&n>0&&(this.subagentRunningCostUsd+=n)}deriveSealStatus(t){if(t==="error")return"failed";let n=this.abortController.signal;return n.aborted&&n.reason!=="closed"?"cancelled":this.sawProviderError?"failed":"succeeded"}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new dt("Cannot send message: session aborted");if(this.currentState==="processing"||this.currentState==="streaming"||this.currentState==="compacting")throw new Error("Cannot send message: session is busy");if(this.config.maxTurns&&this.turnCount>=this.config.maxTurns)throw this.maxTurnsHit=!0,new Error(`Maximum turns (${this.config.maxTurns}) exceeded`)}}});var pi=I(()=>{"use strict";_b()});var pP={};Ac(pP,{KeychainOAuthProvider:()=>Fi,clearOauthPending:()=>Nb,readOauthPending:()=>dP});import{existsSync as Ap,mkdirSync as cP,readFileSync as _p,writeFileSync as Lb}from"node:fs";import{execFileSync as sP}from"node:child_process";import{randomUUID as O4}from"node:crypto";import{homedir as iP,userInfo as aP}from"node:os";import{join as lP,dirname as uP}from"node:path";function D4(){let e=process.platform==="darwin",t=process.platform==="linux";return{read(){if(e)try{return sP("security",["find-generic-password","-s","Claude Code-credentials","-a",aP().username,"-w"],{stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim()||void 0}catch{return}if(t){let n=lP(iP(),".claude",".credentials.json");if(!Ap(n))return;try{return _p(n,"utf-8")}catch{return}}},write(n){if(e)sP("security",["add-generic-password","-U","-s","Claude Code-credentials","-a",aP().username,"-w",n],{stdio:["ignore","ignore","ignore"]});else if(t){let r=lP(iP(),".claude",".credentials.json");cP(uP(r),{recursive:!0}),Lb(r,n,{encoding:"utf-8",mode:384})}}}}function dP(){let e=Pa();if(!Ap(e))return{};let t;try{t=JSON.parse(_p(e,"utf-8"))}catch{return{}}if(t===null||typeof t!="object")return{};let n={};for(let[r,o]of Object.entries(t)){if(o===null||typeof o!="object")continue;let s=o;s.status==="oauth_pending"&&typeof s.authorizationUrl=="string"&&typeof s.timestamp=="number"&&Date.now()-s.timestamp<=$4&&(n[r]={status:"oauth_pending",authorizationUrl:s.authorizationUrl,timestamp:s.timestamp})}return n}function Nb(e){let t=Pa();if(!Ap(t))return;let n;try{n=JSON.parse(_p(t,"utf-8"))}catch{return}e in n&&(delete n[e],Lb(t,JSON.stringify(n,null,2),{encoding:"utf-8",mode:384}))}function F4(e,t){let n=Pa();cP(uP(n),{recursive:!0});let r={};if(Ap(n))try{r=JSON.parse(_p(n,"utf-8"))}catch{}let o=new URL(t),s=o.origin+o.pathname;r[e]={status:"oauth_pending",authorizationUrl:s,timestamp:Date.now()},Lb(n,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}var $4,Fi,Ip=I(()=>{"use strict";q();$4=600*1e3;Fi=class{serverName;backend;constructor(t,n=D4()){this.serverName=t,this.backend=n}get redirectUrl(){return"http://localhost:3000/oauth/callback"}get clientMetadata(){return{redirect_uris:[this.redirectUrl],client_name:"agent-afk",grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}clientInformation(){return this._readSlot().clientInfo}saveClientInformation(t){this._updateSlot(n=>({...n,clientInfo:t}))}tokens(){return this._readSlot().tokens}saveTokens(t){this._updateSlot(n=>({...n,tokens:t}));try{Nb(this.serverName)}catch{}}saveCodeVerifier(t){this._updateSlot(n=>({...n,codeVerifier:t}))}codeVerifier(){let t=this._readSlot().codeVerifier;if(!t)throw new Error(`[mcp:${this.serverName}] no PKCE code verifier stored`);return t}state(){let t=this._readSlot().state;if(t)return t;let n=O4();return this._updateSlot(r=>({...r,state:n})),n}saveDiscoveryState(t){this._updateSlot(n=>({...n,discoveryState:t}))}discoveryState(){return this._readSlot().discoveryState}invalidateCredentials(t){this._updateSlot(n=>{if(t==="all")return{};let r={...n};return t==="client"&&delete r.clientInfo,t==="tokens"&&delete r.tokens,t==="verifier"&&(delete r.codeVerifier,delete r.state),t==="discovery"&&delete r.discoveryState,r})}async redirectToAuthorization(t){let n=t.toString(),r=`\u{1F510} MCP server "${this.serverName}" requires authorization.
|
|
1603
1607
|
|
|
1604
1608
|
Open this URL to authorize:
|
|
1605
1609
|
${n}`;F4(this.serverName,n);let o=!1;try{let{pushIfConfigured:s}=await Promise.resolve().then(()=>(Lr(),Sh));o=await s(r)!==null}catch{}o||process.stderr.write(`[mcp:${this.serverName}] OAuth authorization required.
|
|
@@ -2013,7 +2017,7 @@ ${t.partialOutput}`:"";return`Subagent failed \u2014 ${r}${o}`}let n=t.message?.
|
|
|
2013
2017
|
${v}${w}
|
|
2014
2018
|
${S}
|
|
2015
2019
|
${v}`})}return{fileBlocks:a,warnings:l}}async function TD(e,t,n,r,o="summary",s,i){let a=w0(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,m=!1,g,h=!1,b=!1,y={abort:null},w=0,S=3e3,v=[],k=new Map,R=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,_=()=>{let U=r.subagentControl;U?.hasPromotableForeground()&&U.promoteActiveForeground().then($=>{for(let B of $)(s??{fn:console.log}).fn(f.dim(` \u2192 subagent backgrounded as ${B.jobId}: ${B.label}`))}).catch(()=>{})},A=r.getCompositor?r.getCompositor():null,N=()=>new Qi({out:ea(s),thinkingMode:o,...R?{activeSkillName:R}:{},onCancel:()=>{t.interrupt().catch(U=>{qe()&&console.error(" "+f.error("session.interrupt() failed:"),U)})},...r.subagentControl?{onBackground:_}:{},...i?.history?{history:i.history}:{},...i?.autocompleteState?{autocompleteState:i.autocompleteState}:{},...i?.promptText!==void 0?{promptText:i.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...A?{compositor:A}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),P=N(),x=async()=>{if(!p){p=!0;try{await P.dispose()}catch{}}},M=async()=>{await P.arm();let U=P.getCompositor();if(s&&U){let $=U;s.fn=B=>$.commitAbove(B)}r.setActiveCompositor?.(U),r.setInterruptNotifier?.($=>P.setInterrupting($)),r.rearmStatus?.()};try{A?A.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{h=!0,t.interrupt().catch(C=>{qe()&&console.error(" "+f.error("soft-stop session.interrupt() failed:"),C)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{b=!0,t.interrupt().catch(C=>{qe()&&console.error(" "+f.error("pause-interrupt session.interrupt() failed:"),C)})}),await M(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(_);let{fileBlocks:U,warnings:$}=ED(e.text,{rootDir:process.cwd()});for(let C of $)(s??{fn:console.log}).fn(f.dim(` @-file: ${C}`));let B=U.length>0||e.attachments.length>0?vD(e.text,e.attachments,void 0,U):e.text,H=t.sendMessageStream(B);if(await Hs((C,L)=>{P.process(C,L)},async()=>{for await(let C of H){if(h||b)break;if(C.type==="chunk"&&C.chunk.type==="content"?(l+=C.chunk.content,u=!0):C.type==="message"&&!u&&(l=C.message.content),C.type==="stream_retry"&&(l=l.slice(0,c)),C.type==="chunk"&&C.chunk.type==="tool_use_detail"){let L=C.chunk,D={toolName:L.toolName,toolUseId:L.toolUseId,input:L.toolInput,...L.toolInputRaw!==void 0&&{inputRaw:L.toolInputRaw}};k.set(L.toolUseId,D),v.push(D)}else if(C.type==="chunk"&&C.chunk.type==="tool_result"){let L=C.chunk;c=l.length;let D=k.get(L.toolUseId);if(D&&(D.result=L.content,D.isError=L.isError,k.delete(L.toolUseId)),r.onContextProgress){let j=Date.now();if(j-w>=S){w=j;try{let Y=r.onContextProgress();Y instanceof Promise&&await Y}catch(Y){qe()&&console.error(" "+f.error("onContextProgress (status refresh) failed:"),Y)}}}}if(C.type==="paused"){if(r.setPausedState?.(!0),await x(),A&&C.autoResume===!0){let L=new AbortController;y.abort=L;let D=C.resetsAt?C.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,j=D?`Keep waiting \u2014 auto-resumes at ${D}`:"Keep waiting \u2014 auto-resume in progress",Y="Switch model / provider (type /model after)",ne="Stop waiting",te=[f.warning(" \u23F3 Usage limit reached.")+(D?f.dim(` Auto-resumes at ${D}.`):""),f.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];of(A,{header:te,options:[j,Y,ne],signal:L.signal,initialIndex:0}).then(Q=>{if(y.abort=null,!Q)return;let J=Q[0];J===void 0||J===j||(b=!0,J===Y&&(s??{fn:console.log}).fn(f.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(ke=>{qe()&&console.error(" "+f.error("picker pause-interrupt session.interrupt() failed:"),ke)}))}).catch(Q=>{qe()&&console.error(" "+f.error("picker promise rejected:"),Q)})}else(s??{fn:console.log}).fn(hk({reason:C.reason,...C.resetsAt!==void 0?{resetsAt:C.resetsAt}:{},...C.accountId!==void 0?{accountId:C.accountId}:{},...C.autoResume!==void 0?{autoResume:C.autoResume}:{}}));continue}if(C.type==="resumed"){r.setPausedState?.(!1),y.abort?.abort(),y.abort=null;let L=C.hotSwapped&&C.accountId?`\u25B6 Resumed on ${C.accountId}`:"\u25B6 Resumed";l="",c=0,u=!1,v.length=0,k.clear(),m=!1,g=void 0,d=!1,P=N(),p=!1,await M(),(s??{fn:console.log}).fn(f.success(L));continue}if(C.type==="error"){await x(),Os(_s(C.error)),d=!0;continue}P.process(C),C.type==="done"&&(m=!0,g=C.metadata)}}),await x(),h){let C=s?s.fn:console.log;C(f.warning("\u23F8 Stopped \u2014 work so far kept.")+f.dim(" Send a message to continue.")),C("")}if(b){let C=s?s.fn:console.log;C(f.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),C("")}if(m&&!h&&!b){qo(n,a,l,g,v),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),Lp(process.stdout);let C=D=>{s?s.fn(D):console.log(D)},L=wD(l);if(L){if(C(SD(L)),C(""),r.onTerminalState)try{r.onTerminalState(L)}catch{}if(n.permissionMode==="autonomous"){let D=L.kind==="done"&&Lu().verifyDone===!0&&!GP(v);zP(L,void 0,{unverified:D})}}if(NZ(g,n,C),r.onAfterTurn){let D=r.onAfterTurn();D instanceof Promise&&await D.catch(()=>{})}}}catch(U){await x(),d||Os(_s(U))}finally{await x(),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 NZ(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(fe(e.durationMs)),e.totalCostUsd!==void 0&&r.push(ct(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),s=Number(e.usage?.output_tokens??0);o+s>0&&r.push(le(o+s)+" tok"),r.length>0&&n(f.dim(" \u25E6 "+r.join(" \xB7 ")));let i=qb(t),a=Nt(t.model);if(i>=1){let l=Math.round((i-1)*a),c=Math.round(a/1e3);n(f.error(` context OVER ${c}k tok by ~${le(l)} tok \u2014 model output may be silently truncated`))}else if(i>.5){let l=i>.8?f.error:f.warning;n(l(` context ${Math.round(i*100)}% used of ${le(a)}`))}n("")}var BZ=5e3;async function UZ(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(f.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function xD(e,t,n,r,o,s,i,a){let{contextPane:l,loopStageBar:c,verdictLedger:u,shellPassthrough:d,bgResultNotifier:p}=i,m=null,g=[];e.session.current.waitForInitialization().then(async w=>{qe()&&(m=qp(w)),await Nm(e.session.current),qe()&&(g=b$())}).catch(()=>{});let h,b=!1,y=!1;for(;;){if(m&&(e.replRenderer.writeLine(m),e.replRenderer.writeLine(""),m=null),g.length>0){for(let x of g)e.replRenderer.writeLine(x);e.replRenderer.writeLine(""),g=[]}let w=d.drainNotifications();for(let{job:x,result:M}of w){let U=M.errorReason===void 0?"\u2713":"\u2717",$=M.errorReason==="abort"?"killed":M.errorReason==="timeout"?"timed out":M.errorReason==="signal-killed"?"killed by signal":`exit ${M.exitCode??0}`,B=Math.max(0,Math.round(M.durationMs/100)/10);e.replRenderer.writeLine(f.dim(` ${U} [${x.id}] ${$} \xB7 ${B}s \xB7 `)+x.command)}let S=p.drainNotifications();for(let{job:x}of S){let M=x.status==="completed"?"\u2713":x.status==="failed"?"\u2717":"\u2298",U=x.endedAt!==void 0?Math.max(0,Math.round((x.endedAt-x.startedAt)/100)/10):0,$=x.label.length>60?`${x.label.slice(0,60)}\u2026`:x.label;e.replRenderer.writeLine(f.dim(` ${M} [${x.jobId}] subagent ${x.status} \xB7 ${U}s \xB7 `)+$)}let v=l.renderIfChanged(e.stats.sessionId);if(v.length>0){for(let x of v)e.replRenderer.writeLine(x);e.replRenderer.writeLine("")}let k,R;if(h===void 0){let x=await e.session.current.takePendingPlanExitSeed();x!==void 0&&(h={text:x,attachments:[]})}if(h!==void 0){let x=h;h=void 0;let M=oa(e.stats.permissionMode),U=es({buffer:x.text,promptText:M,isTTY:!!process.stdout.isTTY,attachmentSummary:Gi([...x.attachments])});e.replRenderer.writeLine(U),k=x.text.trim(),R=x.attachments}else{let x=await o.readLine({promptFn:()=>oa(e.stats.permissionMode),onSigint:r,onShiftTab:()=>{sf(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});k=x.text.trim(),R=x.attachments}if(!k&&R.length===0)continue;if(k.startsWith("!")){let x=/^(0|false|off|no)$/i.test(E.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!x&&(b||(b=!0,e.replRenderer.writeLine(f.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await d.dispatch(k))){e.statusLine.rearm();continue}}let _=!1;if(k.startsWith("/")){let x=await FP(k,e.slashCtx,R);if(x.handled){if(x.result==="exit"){e.rl.close();return}if((k==="/clear"||k.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(f.dim(` transcript: ${t.path()}`)),u.reset()),x.result!==null&&typeof x.result=="object"&&"kind"in x.result&&x.result.kind==="submit"){h={text:x.result.message,attachments:R??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}_=!0}a.push(k),await UZ(e,k);let A=k;if(_){let x=Gb(k);if(x){let M=x.name.replace(/^\//,"").split(":").pop()??"";if(M&&Xw(M)){let U={skillName:M,rawArgs:x.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},$=e.session.current.sessionId,B=cs($),H=Date.now();W(`[afk trace] preflight.start commandName=${M}`);let O=!1,C=await ls(U,{cwd:e.stats.cwd??process.cwd(),artifactDir:B},L=>{qe()&&e.replRenderer.writeLine(f.warning(`\u26A0 preflight(${M}) failed: `)+(L instanceof Error?L.message:String(L)))});O=C!==null,W(`[afk trace] preflight.end commandName=${M} durationMs=${Date.now()-H} success=${O}`),A=Qw(C?.manifestBlock,k)}}}let N=d.drainInjections();N.length>0&&(A=N+A);let P=p.drainInjections();if(P.length>0&&(A=P+A),e.hookRegistry)try{let x={event:"UserPromptSubmit",prompt:A,sessionId:e.stats.sessionId},M=await e.hookRegistry.dispatch(x);M.injectContext&&(A=M.injectContext+A)}catch(x){if(x instanceof ge){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+(x.reason?f.dim(`: ${Mo(x.reason)}`):"")),e.statusLine.rearm();continue}if(x instanceof Tn){e.replRenderer.writeLine(f.warning("\u2298 Turn blocked by hook")+f.dim(`: handler timed out after ${x.timeoutMs}ms`)),e.statusLine.rearm();continue}throw x}if(await TD({text:A,attachments:R},e.session.current,e.stats,{setInFlight(x){n.turnInFlight=x},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(x){await t.appendUser(x)},async onTurnComplete(x,M){if(await t.appendTurn(x,M),e.stats.sessionId)try{Bn(e.stats)}catch(U){y||(y=!0,e.replRenderer.writeLine(f.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(U instanceof Error?U.message:String(U))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:x=>u?.push(x),setActiveCompositor:x=>{n.activeCompositor=x},setInterruptNotifier:x=>{n.notifyInterrupting=x},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:x=>o.setBackgroundHandler(x),setSoftStopHandler:s,setPausedState:x=>o.setPausedState(x),setPauseInterruptHandler:x=>o.setPauseInterruptHandler(x),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(Hn(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:x=>c.repaint(x)}:{}},e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(oa(e.stats.permissionMode))),e.hookRegistry)try{await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId},void 0,BZ)}catch(x){if(x instanceof dt)throw x;x instanceof Tn?(W("[stop hook] handler timed out"),e.completionWriter.fn(f.dim(" [stop hook] timed out"))):x instanceof ge?e.completionWriter.fn(f.dim(` [stop hook] blocked: ${Mo(x.reason??"no reason given")}`)):W("[stop hook] unexpected error: "+String(x))}}}function jZ(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 RD(e,t,n,r){let o=await nD(),s=new rf({rl:e.rl,history:o,statusLine:e.statusLine}),i=jZ(E.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await lD(e,s,n,t,r,i,{getLoopStageBar:()=>a?.loopStageBar});a=bD(e,n),await xD(e,t,n,r,s,l,a,o)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.bgResultNotifier.dispose(),a?.loopStageBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await s.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}qa();import{execFile as HZ}from"node:child_process";import{dirname as WZ,isAbsolute as KZ,resolve as GZ}from"node:path";import{promisify as qZ}from"node:util";var CD=qZ(HZ),zZ=3e3,JZ=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function VZ(){let t=(await CD("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=KZ(t)?t:GZ(process.cwd(),t);return WZ(n)}async function AD(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await VZ()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),zZ)});try{let o=Kn({execFile:CD,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=>JZ.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}tu();qa();import{promises as YZ}from"node:fs";import{dirname as XZ,join as PD}from"node:path";import{randomBytes as ZZ}from"node:crypto";var QZ=["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(`
|
|
2016
|
-
`),_D=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,kS=30,eQ=1024,tQ=8e3,nQ="haiku";async function rQ(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=aQ(n,eQ),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??tQ),i=t.signal?lQ([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??nQ,system:QZ,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=oQ(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=XZ(t.worktreePath);return await sQ(l,c)}function oQ(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(_D.test(t)&&t.length<=kS)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>kS)break;o=i}return _D.test(o)?o:null}async function sQ(e,t){if(!await iQ(PD(t,e)))return e;let n=ZZ(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,kS-5)}-${n}`}async function iQ(e){try{return await YZ.access(e),!0}catch{return!1}}function aQ(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 lQ(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 MD(e){let t,n,r=PD(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await rQ(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=`${Ou(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return ID(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 ID(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 ID(e,t){e&&e.setCwd(t),cQ(t)}function cQ(e){try{process.chdir(e)}catch{}}Ye();Lt();q();import{spawn as $D}from"child_process";import{existsSync as DD,mkdirSync as fQ,readFileSync as FD,unlinkSync as OD,writeFileSync as gQ}from"fs";import{get as hQ}from"https";import{join as LD}from"path";import{readFileSync as uQ}from"fs";import{dirname as dQ,join as pQ}from"path";import{fileURLToPath as mQ}from"url";function Rr(){try{return"5.15.
|
|
2020
|
+
`),_D=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,kS=30,eQ=1024,tQ=8e3,nQ="haiku";async function rQ(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=aQ(n,eQ),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??tQ),i=t.signal?lQ([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??nQ,system:QZ,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=oQ(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=XZ(t.worktreePath);return await sQ(l,c)}function oQ(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(_D.test(t)&&t.length<=kS)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>kS)break;o=i}return _D.test(o)?o:null}async function sQ(e,t){if(!await iQ(PD(t,e)))return e;let n=ZZ(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,kS-5)}-${n}`}async function iQ(e){try{return await YZ.access(e),!0}catch{return!1}}function aQ(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 lQ(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 MD(e){let t,n,r=PD(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await rQ(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=`${Ou(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return ID(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 ID(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 ID(e,t){e&&e.setCwd(t),cQ(t)}function cQ(e){try{process.chdir(e)}catch{}}Ye();Lt();q();import{spawn as $D}from"child_process";import{existsSync as DD,mkdirSync as fQ,readFileSync as FD,unlinkSync as OD,writeFileSync as gQ}from"fs";import{get as hQ}from"https";import{join as LD}from"path";import{readFileSync as uQ}from"fs";import{dirname as dQ,join as pQ}from"path";import{fileURLToPath as mQ}from"url";function Rr(){try{return"5.15.13"}catch{}try{let e=dQ(mQ(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(uQ(pQ(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}V();var yQ=64*1024,bQ=1440*60*1e3,wQ=3600*1e3,SQ="update-check.json",vQ="pending-update.json";function ND(){return LD(Oc(),SQ)}function dc(){return LD(Oc(),vQ)}function BD(){let e=Oc();DD(e)||fQ(e,{recursive:!0})}function kQ(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 EQ(){try{let e=FD(ND(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function TQ(){try{BD();let e=`
|
|
2017
2021
|
const https = require('https');
|
|
2018
2022
|
const fs = require('fs');
|
|
2019
2023
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|