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.
package/dist/telegram.mjs CHANGED
@@ -1011,9 +1011,13 @@ Available skills: ${n.join(", ")}`:"";throw new Error(`Skill not found: ${t}${r}
1011
1011
  `),this.errored=!0,this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null}}}_writeLine(e){if(!(!this.stream||this.errored))try{this.stream.write(e,n=>{n&&(process.stderr.write(`[afk] session-ledger: write error for ${this.sessionId}: ${String(n)}
1012
1012
  `),this.errored=!0)})}catch(n){process.stderr.write(`[afk] session-ledger: write threw for ${this.sessionId}: ${String(n)}
1013
1013
  `),this.errored=!0}}async close(e){if(!this.closed)return this.record({kind:"closed",...e!==void 0?{reason:e}:{}}),this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(n=>{if(!this.stream){n();return}this.stream.end(()=>n())})}};Ok=250});import{mkdir as Dk,writeFile as gp,unlink as $L,readdir as Fk,readFile as hp}from"fs/promises";import{unlinkSync as Lk,existsSync as Nk}from"fs";import{join as yp}from"path";function Ia(t){return yp(Zr(),`${t}.json`)}async function $k(){try{return await Dk(Zr(),{recursive:!0}),!0}catch{return!1}}async function Yn(t){try{if(!await $k())return;let n=Ia(t.sessionId);await gp(n,JSON.stringify(t,null,2),"utf8")}catch{}}async function bp(t,e){try{let n=Ia(t),r=await hp(n,"utf8"),o=JSON.parse(r);o.cwd=e,await gp(n,JSON.stringify(o,null,2),"utf8")}catch{}}function tt(t){try{let e=Ia(t);Nk(e)&&Lk(e)}catch{}}async function Xn(){let t=Zr(),e;try{e=await Fk(t)}catch{return[]}let n=[];for(let r of e){if(!r.endsWith(".json"))continue;let o=yp(t,r);try{let s=await hp(o,"utf8"),i=JSON.parse(s);i!==null&&typeof i=="object"&&"sessionId"in i&&typeof i.sessionId=="string"&&n.push({...i,path:o})}catch{}}return n}var Qn=y(()=>{"use strict";W()});function wp(t,e,n){t&&(t.aborted?e.abort(t.reason):t.addEventListener("abort",()=>{e.signal.aborted||e.abort(t.reason)},{once:!0})),e.signal.addEventListener("abort",n,{once:!0})}function Sp(t,e){let n=t.permissionMode??"default",r=t.persistSession??!0,o={sessionId:t.sessionId,configuredSessionId:t.sessionId,resume:t.resume,resumeSessionAt:t.resumeSessionAt,continue:t.continue,forkSession:t.forkSession,persistSession:r},s={sessionId:t.sessionId,model:e,permissionMode:n};return{sessionIdentity:o,metadata:s}}var vp=y(()=>{"use strict"});var Wo,kp=y(()=>{"use strict";Wo=class{initializationPromise;resolveInitialization;rejectInitialization;initializationSettled=!1;sessionMetadata;sessionIdentity;constructor(e,n){this.sessionIdentity=e,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(e){e&&(this.sessionIdentity={...this.sessionIdentity,sessionId:e},this.sessionMetadata={...this.sessionMetadata,sessionId:e})}setSessionMetadata(e){this.sessionMetadata=e(this.sessionMetadata)}resolveInitializationIfNeeded(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}resolveInitializationOnce(){this.initializationSettled||(this.initializationSettled=!0,this.resolveInitialization(this.getSessionMetadata()))}rejectInitializationOnce(e){this.initializationSettled||(this.initializationSettled=!0,this.rejectInitialization(e))}isInitializationSettled(){return this.initializationSettled}}});function _p(t){try{let e=JSON.parse(t);if(!Array.isArray(e))return null;let n=e.length;if(n===0)return"no results";let r=0,o=0;for(let a of e)if(a&&typeof a=="object"){let c=a.type;c==="fact"?r++:c==="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 Ep(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;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 Ap(t){try{let e=JSON.parse(t);if(!e||typeof e!="object")return null;let n=e;return typeof n.name=="string"&&n.written===!0?`wrote procedure '${n.name}'`:null}catch{return null}}var Tp=y(()=>{"use strict"});function Ca(t){let e=t.trim();if(e.length===0)return null;let n=e[0];if(n!=="{"&&n!=="[")return null;let r=e[e.length-1];if(n==="{"&&r!=="}"||n==="["&&r!=="]")return null;let o;try{o=JSON.parse(e)}catch{return null}return Array.isArray(o)?xp(Uk(o)):o!==null&&typeof o=="object"?xp(Bk(o)):null}function Uk(t){return t.length===0?"[empty array]":t.length===1?"[1 item]":`[${t.length} items]`}function Bk(t){let e=Object.keys(t);if(e.length===0)return"{empty object}";let n=e.slice(0,4),r=e.length>4?", \u2026":"";return`{${n.join(", ")}${r}}`}function xp(t){return t.length<=80?t:t.slice(0,79)+"\u2026"}var Rp=y(()=>{"use strict"});function Go(t){return t.replace(Pp,"").replace(jk," ").trim()}function nt(t){return t.replace(Pp,"")}var Pp,jk,pn=y(()=>{"use strict";Pp=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B[P^_X][^\x1B]*\x1B\\|\x1B\[[0-?]*[ -/]*[@-~]|\x9B[0-?]*[ -/]*[@-~]|\x1B[@-_]/g,jk=/[\x00-\x1F\x7F-\x9F]/g});function Ip(t,e){if(!t)return null;let n=Hk.get(t);if(!n)return null;try{let r=n(e);if(r===null)return null;let o=Go(r);return o.length>0?o:null}catch{return null}}var Hk,Cp=y(()=>{"use strict";Tp();Rp();pn();Hk=new Map([["memory_search",_p],["memory_update",Ep],["procedure_write",Ap],["bash",Ca],["Bash",Ca]])});function Kk(t){let e=/Output too large \((\d+(?:\.\d+)?)\s*(B|KB|MB|GB)\)\.\s*Full output saved to:\s*(\/[^\n]+)/,n=t.match(e);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 c=r;return i%1===0&&(c=String(Math.floor(i))),c+=o,{sizeLabel:c,sizeBytes:Math.round(a),absolutePath:s.trim()}}function Wk(t){if(t<1024)return`${t}B`;let e=t/1024;if(e<1024)return e%1===0?`${Math.floor(e)}KB`:`${e.toFixed(1)}KB`;let n=e/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 Gk(t){let e=Buffer.byteLength(t,"utf8"),n=Wk(e),r=t.split(`
1014
- `);if(r.length<=1&&t.length<=80)return{content:t,truncated:!1,sizeBytes:e,sizeLabel:n};if(r.length<=1)return t.length<=80?{content:t,truncated:!1,sizeBytes:e,sizeLabel:n}:{content:t.substring(0,80)+"\u2026",truncated:!0,sizeBytes:e,sizeLabel:n};if(t.length<=80)return{content:t,truncated:!1,sizeBytes:e,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:e,sizeLabel:n}}function qk(t,e){let n={...t.raw??{}};return t.inputTokens!==void 0&&(n.input_tokens=t.inputTokens),t.outputTokens!==void 0&&(n.output_tokens=t.outputTokens),t.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=t.cachedInputTokens),t.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=t.cacheCreationTokens),t.totalTokens!==void 0&&(n.total_tokens=t.totalTokens),t.contextWindowTokens!==void 0&&(n.context_window_tokens=t.contextWindowTokens),{sessionId:e,stopReason:t.stopReason??void 0,resultSubtype:t.resultSubtype,durationMs:t.durationMs,durationApiMs:t.durationApiMs,totalCostUsd:t.totalCostUsd,isError:t.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:t.modelUsage,permissionDenials:t.permissionDenials,errors:t.errors}}function zk(t){let e=t.isError===!0?null:Ip(t.toolName,t.content),n=e!==null?{display:e}:{},r=Kk(t.content);if(r)return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:`Output persisted (${r.sizeLabel}) \u2192 ${r.absolutePath}`,isError:t.isError===!0,persistedPath:r.absolutePath,sizeBytes:r.sizeBytes,sizeLabel:r.sizeLabel,...n}};let{content:o,lineCount:s,sizeBytes:i,sizeLabel:a}=Gk(t.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:o,isError:t.isError===!0,sizeBytes:i,sizeLabel:a,...t.truncated===!0&&{truncated:!0},...s!==void 0&&{lineCount:s},...n}}}function Ma(t,e){switch(t.type){case"session.init":{let n=t.info;return e.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}:{}})),e.updateSessionIdentity(n.sessionId),e.resolveInitialization(),null}case"session.status":return e.setSessionMetadata(n=>({...n,sessionId:t.sessionId,...t.permissionMode!==void 0?{permissionMode:t.permissionMode}:{permissionMode:n.permissionMode},...t.status!==void 0?{status:t.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:t.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:t.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(t.sessionId&&e.updateSessionIdentity(t.sessionId),t.text){let n={role:"assistant",content:t.text,timestamp:new Date};return e.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:t.toolUseId,toolName:t.toolName,toolInput:t.toolInput,toolInputRaw:t.toolInputRaw}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:t.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:t.toolUseIds}}};case"tool.output":return zk(t);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:t.toolUseId,diff:t.diff}};case"progress":return{type:"progress",progress:{taskId:t.progress.taskId,description:t.progress.description,...t.progress.summary!==void 0?{summary:t.progress.summary}:{},...t.progress.lastToolName!==void 0?{lastToolName:t.progress.lastToolName}:{},totalTokens:t.progress.totalTokens,toolUses:t.progress.toolUses,durationMs:t.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:t.suggestion};case"turn.completed":{let n=qk(t.usage,t.sessionId??e.getSessionMetadata().sessionId);e.setLastResponseMetadata(n);for(let r=e.conversationHistory.length-1;r>=0;r--){let o=e.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(e.maxBudgetUsd!==void 0&&e.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(e._runningCostUsd=(e._runningCostUsd??0)+n.totalCostUsd,e._runningCostUsd>=e.maxBudgetUsd)){Xu(e.traceWriter,{kind:"monetary",runningCostUsd:e._runningCostUsd,maxBudgetUsd:e.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new tn(e._runningCostUsd,e.maxBudgetUsd);return e.abortBudget(r.message),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:t.error};case"paused":return{type:"paused",reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:t.hotSwapped,...t.accountId!==void 0?{accountId:t.accountId}:{}};case"stream.retry":return{type:"stream_retry"};default:return null}}var Mp=y(()=>{"use strict";ge();ne();Cp()});import{z as Vk}from"zod";var Nt,Op=y(()=>{"use strict";de();ge();ne();Se();np();ln();$o();ip();ge();cp();dp();Pa();Aa();Ko();H();Be();gt();Qn();Qe();Ta();vp();kp();Mp();Nt=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(e){this.config=e.parentSessionId===void 0&&e.planExitControls===void 0?{...e,planExitControls:{setPermissionMode:r=>this.setPermissionMode(r),requestImplementSeed:(r,o)=>{this._pendingPlanExitSeed={message:r,mode:o}},getPrePlanMode:()=>this._prePlanPermissionMode}}:e,this.abortController=new AbortController,this._hookRegistry=e.hookRegistry,wp(e.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(e.model);ae(e.traceWriter,{phase:"session_init_start",model:n,resolvedModel:ce(e.model)??n,origin:mt(e.surface),actor:fo(e.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&Ro(this.config.models),Do(this.config);let e=ce(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=Sp(this.config,e);this.stateManager=new Wo(n,r),this.inputStream=new cn(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)B(`\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{B("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>Dp(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new Fo({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>V(a),resolveApiKey:a=>et(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 op(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});;){let e=await this.providerIterator.next();if(e.done){this.stateManager.resolveInitializationIfNeeded();return}let n=e.value,r=Ma(n,this.buildTransformDeps());if(n.type==="session.init"){await ae(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(r&&r.type==="error"){this.sawProviderError=!0;return}}}catch(e){let n=e instanceof Error?e:new Error(String(e));n instanceof X&&(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:e=>this.stateManager.setSessionMetadata(e),updateSessionIdentity:e=>this.stateManager.updateSessionIdentity(e),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:e=>{this.lastResponseMetadata=e,typeof e.totalCostUsd=="number"&&Number.isFinite(e.totalCostUsd)&&(this.sessionRunningCostUsd+=e.totalCostUsd);let n=e.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 e.stopReason=="string"&&(this.lastStopReason=e.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:e=>{this.abortController.signal.aborted||this.abortController.abort(e)},...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(e){if(e==="closed"||e.startsWith("Budget ")||e.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${e}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(e)}async sendMessage(e,n={}){this.assertCanSend();let r=this.config.timeoutMs??Lo,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(e)){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 No(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async sendMessageStructured(e,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(Vk.toJSONSchema(n,{target:"openapi-3.0"}))+"\n```":"",c="";for(let l=0;l<=o;l++){let d=l===0?e+a:`Your previous response did not match the required JSON schema.
1014
+ `);if(r.length<=1&&t.length<=80)return{content:t,truncated:!1,sizeBytes:e,sizeLabel:n};if(r.length<=1)return t.length<=80?{content:t,truncated:!1,sizeBytes:e,sizeLabel:n}:{content:t.substring(0,80)+"\u2026",truncated:!0,sizeBytes:e,sizeLabel:n};if(t.length<=80)return{content:t,truncated:!1,sizeBytes:e,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:e,sizeLabel:n}}function qk(t,e){let n={...t.raw??{}};return t.inputTokens!==void 0&&(n.input_tokens=t.inputTokens),t.outputTokens!==void 0&&(n.output_tokens=t.outputTokens),t.cachedInputTokens!==void 0&&(n.cache_read_input_tokens=t.cachedInputTokens),t.cacheCreationTokens!==void 0&&(n.cache_creation_input_tokens=t.cacheCreationTokens),t.totalTokens!==void 0&&(n.total_tokens=t.totalTokens),t.contextWindowTokens!==void 0&&(n.context_window_tokens=t.contextWindowTokens),{sessionId:e,stopReason:t.stopReason??void 0,resultSubtype:t.resultSubtype,durationMs:t.durationMs,durationApiMs:t.durationApiMs,totalCostUsd:t.totalCostUsd,isError:t.isError,usage:Object.keys(n).length>0?n:void 0,modelUsage:t.modelUsage,permissionDenials:t.permissionDenials,errors:t.errors}}function zk(t){let e=t.isError===!0?null:Ip(t.toolName,t.content),n=e!==null?{display:e}:{},r=Kk(t.content);if(r)return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:`Output persisted (${r.sizeLabel}) \u2192 ${r.absolutePath}`,isError:t.isError===!0,persistedPath:r.absolutePath,sizeBytes:r.sizeBytes,sizeLabel:r.sizeLabel,...n}};let{content:o,lineCount:s,sizeBytes:i,sizeLabel:a}=Gk(t.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:o,isError:t.isError===!0,sizeBytes:i,sizeLabel:a,...t.truncated===!0&&{truncated:!0},...s!==void 0&&{lineCount:s},...n}}}function Ma(t,e){switch(t.type){case"session.init":{let n=t.info;return e.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}:{}})),e.updateSessionIdentity(n.sessionId),e.resolveInitialization(),null}case"session.status":return e.setSessionMetadata(n=>({...n,sessionId:t.sessionId,...t.permissionMode!==void 0?{permissionMode:t.permissionMode}:{permissionMode:n.permissionMode},...t.status!==void 0?{status:t.status}:{}})),null;case"delta.text":return{type:"chunk",chunk:{type:"content",content:t.text,metadata:{eventType:"delta",deltaType:"text_delta"}}};case"delta.reasoning":return{type:"chunk",chunk:{type:"thinking",content:t.text,metadata:{eventType:"delta",deltaType:"thinking_delta"}}};case"assistant.message":if(t.sessionId&&e.updateSessionIdentity(t.sessionId),t.text){let n={role:"assistant",content:t.text,timestamp:new Date};return e.conversationHistory.push(n),{type:"message",message:n}}return null;case"tool.use.start":return{type:"chunk",chunk:{type:"tool_use_detail",toolUseId:t.toolUseId,toolName:t.toolName,toolInput:t.toolInput,toolInputRaw:t.toolInputRaw}};case"tool.use":return{type:"chunk",chunk:{type:"tool_use",content:t.summary,metadata:{eventType:"tool_use_summary",precedingToolUseIds:t.toolUseIds}}};case"tool.output":return zk(t);case"tool.diff":return{type:"chunk",chunk:{type:"tool_diff",toolUseId:t.toolUseId,diff:t.diff}};case"progress":return{type:"progress",progress:{taskId:t.progress.taskId,description:t.progress.description,...t.progress.summary!==void 0?{summary:t.progress.summary}:{},...t.progress.lastToolName!==void 0?{lastToolName:t.progress.lastToolName}:{},totalTokens:t.progress.totalTokens,toolUses:t.progress.toolUses,durationMs:t.progress.durationMs}};case"suggestion":return{type:"suggestion",suggestion:t.suggestion};case"turn.completed":{let n=qk(t.usage,t.sessionId??e.getSessionMetadata().sessionId);e.setLastResponseMetadata(n);for(let r=e.conversationHistory.length-1;r>=0;r--){let o=e.conversationHistory[r];if(o?.role==="assistant"){o.metadata=n;break}}if(e.maxBudgetUsd!==void 0&&e.abortBudget!==void 0&&typeof n.totalCostUsd=="number"&&(e._runningCostUsd=(e._runningCostUsd??0)+n.totalCostUsd,e._runningCostUsd>=e.maxBudgetUsd)){Xu(e.traceWriter,{kind:"monetary",runningCostUsd:e._runningCostUsd,maxBudgetUsd:e.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new tn(e._runningCostUsd,e.maxBudgetUsd);return e.abortBudget(r.message),{type:"error",error:r}}return{type:"done",metadata:n}}case"error":return{type:"error",error:t.error};case"paused":return{type:"paused",reason:t.reason,...t.resetsAt!==void 0?{resetsAt:t.resetsAt}:{},...t.accountId!==void 0?{accountId:t.accountId}:{},...t.autoResume!==void 0?{autoResume:t.autoResume}:{}};case"resumed":return{type:"resumed",hotSwapped:t.hotSwapped,...t.accountId!==void 0?{accountId:t.accountId}:{}};case"stream.retry":return{type:"stream_retry"};default:return null}}var Mp=y(()=>{"use strict";ge();ne();Cp()});import{z as Vk}from"zod";var Nt,Op=y(()=>{"use strict";de();ge();ne();Se();np();ln();$o();ip();ge();cp();dp();Pa();Aa();Ko();H();Be();gt();Qn();Qe();Ta();vp();kp();Mp();Nt=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(e){this.config=e.parentSessionId===void 0&&e.planExitControls===void 0?{...e,planExitControls:{setPermissionMode:r=>this.setPermissionMode(r),requestImplementSeed:(r,o)=>{this._pendingPlanExitSeed={message:r,mode:o}},getPrePlanMode:()=>this._prePlanPermissionMode}}:e,this.abortController=new AbortController,this._hookRegistry=e.hookRegistry,wp(e.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(e.model);ae(e.traceWriter,{phase:"session_init_start",model:n,resolvedModel:ce(e.model)??n,origin:mt(e.surface),actor:fo(e.parentSessionId)}),this.initSdkLifecycle()}initSdkLifecycle(){this.config.models&&Ro(this.config.models),Do(this.config);let e=ce(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=Sp(this.config,e);this.stateManager=new Wo(n,r),this.inputStream=new cn(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)B(`\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{B("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>Dp(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new Fo({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>V(a),resolveApiKey:a=>et(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 op(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});;){let e=await this.providerIterator.next();if(e.done){this.stateManager.resolveInitializationIfNeeded();return}let n=e.value,r=Ma(n,this.buildTransformDeps());if(n.type==="session.init"){await ae(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(r&&r.type==="error"){this.sawProviderError=!0;return}}}catch(e){let n=e instanceof Error?e:new Error(String(e));n instanceof X&&(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:e=>this.stateManager.setSessionMetadata(e),updateSessionIdentity:e=>this.stateManager.updateSessionIdentity(e),resolveInitialization:()=>this.stateManager.resolveInitializationOnce(),setLastResponseMetadata:e=>{this.lastResponseMetadata=e,typeof e.totalCostUsd=="number"&&Number.isFinite(e.totalCostUsd)&&(this.sessionRunningCostUsd+=e.totalCostUsd);let n=e.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 e.stopReason=="string"&&(this.lastStopReason=e.stopReason)},maxBudgetUsd:this.config.maxBudgetUsd,abortBudget:e=>{this.abortController.signal.aborted||this.abortController.abort(e)},...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(e){if(e==="closed"||e.startsWith("Budget ")||e.includes("timed out"))throw new Error(`AgentSession.abort: reserved reason "${e}" (use a caller-specific string like 'sigint')`);this.abortController.signal.aborted||this.abortController.abort(e)}async sendMessage(e,n={}){this.assertCanSend();let r=this.config.timeoutMs??Lo,o=async()=>{let s=null,i="";this.currentState=n.stream?"streaming":"processing";for await(let a of this.sendMessageStreamInternal(e)){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 No(o(),r,{controller:this.abortController,label:this.sessionId??"session"})}finally{this.currentState==="processing"&&(this.currentState="idle")}}async sendMessageStructured(e,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(Vk.toJSONSchema(n,{target:"openapi-3.0"}))+"\n```":"",c="";for(let l=0;l<=o;l++){let d=l===0?e+a:`Your previous response did not match the required JSON schema.
1015
1015
  Validation error: ${c}
1016
- Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,u=await this.sendMessage(d,i),p=Bo(u.content),f=n.safeParse(p);if(f.success)return f.data;c=f.error.message}throw new Error(`structured output did not match schema after ${o+1} attempt(s): ${c}`)}async*sendMessageStream(e){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(e)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(e){this.initPromise&&await this.initPromise;let n=typeof e=="string"?e:this.summarizeContentBlocks(e),r={role:"user",content:n,timestamp:new Date};this.conversationHistory.push(r),this.inputStream.pushUserMessage(e),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=Ma(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)||k.AFK_SESSION_LEDGER_DISABLED==="1")return;let e=this.sessionId;if(!e)return;let n=new bt(e);if(!n.active)return;this.ledger=n;let r=this.getSessionMetadata();n.record({kind:"meta",sessionId:e,model:r.model??String(this.config.model),...r.cwd!==void 0?{cwd:r.cwd}:{}})}sealLedger(e){let n=this.ledger;return n?(this.ledger=null,this.ledgerInitAttempted=!1,n.close(e)):Promise.resolve()}recordLedgerElicitation(e,n){this.ledger?.record({kind:"elicitation",reqId:e,request:n})}summarizeContentBlocks(e){let n=[],r=0;for(let s of e)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 we("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(e=>setTimeout(e,Ra))]).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(e){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async onAbort(){this.sealLedger("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(e){let n=ce(e);typeof e=="string"&&e.length>0&&await this.providerQuery.setModel(e),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(e){if(e==="plan"){let n=this.stateManager.getSessionMetadata().permissionMode;n!=="plan"&&(this._prePlanPermissionMode=n==="autonomous"?void 0:n)}await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:e}))}getPrePlanMode(){return this._prePlanPermissionMode}async takePendingPlanExitSeed(){let e=this._pendingPlanExitSeed;if(this._pendingPlanExitSeed=void 0,e!==void 0){try{await this.setPermissionMode(e.mode)}catch(n){B(`\u26A0\uFE0F AgentSession: deferred plan-exit mode flip to '${e.mode}' rejected; dropping implement-seed (staying in plan mode): ${n instanceof Error?n.message:String(n)}`);return}return e.message}}setCwd(e){this.config={...this.config,cwd:e},this.providerQuery.setCwd?.(e),this.config.sessionId!==void 0&&bp(this.config.sessionId,e)}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(e,n){return this.providerQuery.rewindFiles(e,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 e=this.providerQuery.compact?.bind(this.providerQuery);if(!e)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await e()}finally{this.currentState="idle"}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){throw new Error("getOutputStream() is not supported \u2014 use sendMessageStream() instead")}getInputStreamRef(){return{pushUserMessage:e=>this.inputStream.pushUserMessage(e)}}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(e=>setTimeout(e,Ra))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(e).catch(()=>{}),await this.sealTraceWriter(e).catch(()=>{}),await sp(this._hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:e,parentSessionId:this.config.parentSessionId,...this.config.traceWriter?{tracePath:this.config.traceWriter.getTracePath()}:{}},this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}))}async emitClosure(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveClosureReason(e),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=lp(r);await ep(n,{reason:r,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,finalTokens:o,...this.lastStopReason!==void 0?{lastStopReason:this.lastStopReason}:{},...s!==null?{guidance:s}:{}})}deriveClosureReason(e){let n=null,r=this.abortController.signal;if(r.aborted&&r.reason!=="closed"){let o=r.reason;o instanceof tn?n="budget_exceeded":o instanceof $e?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return ap({dispatchReason:e,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,abort:n,lastStopReason:this.lastStopReason,sawProviderError:this.sawProviderError})}async sealTraceWriter(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveSealStatus(e),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,c=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}:{},...c!==void 0?{subagentCostUsd:c}:{}})}recordSubagentCompletion(e,n){if(this.subagentCompletedCount++,e){let r=(o,s)=>{typeof o=="number"&&Number.isFinite(o)&&o>0&&(this.subagentRunningTokens[s]+=o)};r(e.inputTokens,"input"),r(e.outputTokens,"output"),r(e.cacheReadTokens,"cacheRead"),r(e.cacheCreationTokens,"cacheCreation")}typeof n=="number"&&Number.isFinite(n)&&n>0&&(this.subagentRunningCostUsd+=n)}deriveSealStatus(e){if(e==="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 we("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 Oa=y(()=>{"use strict";Op()});function Jk(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new $t(n,e)))},e);i.unref(),Promise.resolve(t).then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}function Yk(t){return t.continue===!1||t.decision==="block"}function Da(t,e){if(t?.aborted){let n=t.reason,r=`aborted during ${e}${n?`: ${String(n)}`:""}`;throw new we(r)}}function Fp(){return new Fa}var Ut,$t,Fa,qo=y(()=>{"use strict";ge();Ut=3e4;$t=class extends Error{constructor(n,r){super(`hook handler timed out after ${r}ms during ${n}`);this.hookEvent=n;this.timeoutMs=r;this.name="HookHandlerTimeoutError"}hookEvent;timeoutMs;code="HOOK_HANDLER_TIMEOUT"},Fa=class{handlers=new Map;register(e,n,r={}){let o=this.handlers.get(e);o||(o=[],this.handlers.set(e,o));let s={handler:n,options:r};return o.push(s),()=>{let i=this.handlers.get(e);if(!i)return;let a=i.indexOf(s);a>=0&&i.splice(a,1)}}count(e){return this.handlers.get(e)?.length??0}async dispatch(e,n,r=Ut){Da(n,e.event);let o=this.handlers.get(e.event);if(!o||o.length===0)return{};let s=o.slice(),i={};for(let a of s){Da(n,e.event);let c;try{let d=a.handler(e,n);c=!a.options.longRunning&&r>0&&Number.isFinite(r)?await Jk(d,r,e.event):await d}catch(d){throw d instanceof $t?d:new X(`hook handler threw during ${e.event}`,e.event,d instanceof Error?d.message:String(d),{cause:d})}if(Da(n,e.event),Yk(c))throw new X(`hook handler blocked ${e.event}${c.reason?`: ${c.reason}`:""}`,e.event,c.reason);let l=[i.injectContext,c.injectContext].filter(d=>typeof d=="string"&&d.length>0).join(`
1016
+ Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,u=await this.sendMessage(d,i),p=Bo(u.content),f=n.safeParse(p);if(f.success)return f.data;c=f.error.message}throw new Error(`structured output did not match schema after ${o+1} attempt(s): ${c}`)}async*sendMessageStream(e){this.assertCanSend(),this.currentState="streaming";try{yield*this.sendMessageStreamInternal(e)}finally{this.currentState==="streaming"&&(this.currentState="idle")}}async*sendMessageStreamInternal(e){this.initPromise&&await this.initPromise;let n=this.withPendingFrameworkContext(e),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,c=Ma(a,s);if(c&&(c.type==="done"?(this.turnCount++,this.sawProviderError=!1):c.type==="error"&&(this.sawProviderError=!0),this.ledger?.recordEvent(c),yield c,c.type==="done"||c.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)||k.AFK_SESSION_LEDGER_DISABLED==="1")return;let e=this.sessionId;if(!e)return;let n=new bt(e);if(!n.active)return;this.ledger=n;let r=this.getSessionMetadata();n.record({kind:"meta",sessionId:e,model:r.model??String(this.config.model),...r.cwd!==void 0?{cwd:r.cwd}:{}})}sealLedger(e){let n=this.ledger;return n?(this.ledger=null,this.ledgerInitAttempted=!1,n.close(e)):Promise.resolve()}recordLedgerElicitation(e,n){this.ledger?.record({kind:"elicitation",reqId:e,request:n})}summarizeContentBlocks(e){let n=[],r=0;for(let s of e)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 we("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(e=>setTimeout(e,Ra))]).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(e){throw this.currentState="closed",new Error(`Session reset failed during lifecycle rebuild: ${e instanceof Error?e.message:String(e)}`,{cause:e})}}async onAbort(){this.sealLedger("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(e){let n=ce(e);typeof e=="string"&&e.length>0&&await this.providerQuery.setModel(e),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(e){if(e==="plan"){let n=this.stateManager.getSessionMetadata().permissionMode;n!=="plan"&&(this._prePlanPermissionMode=n==="autonomous"?void 0:n)}await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(n=>({...n,permissionMode:e}))}getPrePlanMode(){return this._prePlanPermissionMode}async takePendingPlanExitSeed(){let e=this._pendingPlanExitSeed;if(this._pendingPlanExitSeed=void 0,e!==void 0){try{await this.setPermissionMode(e.mode)}catch(n){B(`\u26A0\uFE0F AgentSession: deferred plan-exit mode flip to '${e.mode}' rejected; dropping implement-seed (staying in plan mode): ${n instanceof Error?n.message:String(n)}`);return}return e.message}}setCwd(e){this.config={...this.config,cwd:e},this.providerQuery.setCwd?.(e),this.config.sessionId!==void 0&&bp(this.config.sessionId,e)}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(e,n){return this.providerQuery.rewindFiles(e,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 e=this.providerQuery.compact?.bind(this.providerQuery);if(!e)return{compacted:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0};this.currentState="compacting";try{return await e()}finally{this.currentState="idle"}}getLastResponseMetadata(){return this.lastResponseMetadata}getOutputStream(){throw new Error("getOutputStream() is not supported \u2014 use sendMessageStream() instead")}queueFrameworkContext(e){let n=e.trim();n.length!==0&&(this.pendingFrameworkContext.push(n),B(`AgentSession: queued framework context (${n.length} chars) for the next user message`))}withPendingFrameworkContext(e){if(this.pendingFrameworkContext.length===0)return e;let n=this.pendingFrameworkContext.join(`
1017
+
1018
+ `);return this.pendingFrameworkContext=[],typeof e=="string"?`${n}
1019
+
1020
+ ${e}`:[{type:"text",text:n},...e]}getInputStreamRef(){return{pushUserMessage:e=>this.inputStream.pushUserMessage(e),queueFrameworkContext:e=>this.queueFrameworkContext(e)}}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(e=>setTimeout(e,Ra))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){this.sessionEndDispatched||(this.sessionEndDispatched=!0,await this.emitClosure(e).catch(()=>{}),await this.sealTraceWriter(e).catch(()=>{}),await sp(this._hookRegistry,{event:"SessionEnd",sessionId:this.sessionId,reason:e,parentSessionId:this.config.parentSessionId,...this.config.traceWriter?{tracePath:this.config.traceWriter.getTracePath()}:{}},this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}))}async emitClosure(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveClosureReason(e),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=lp(r);await ep(n,{reason:r,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,finalTokens:o,...this.lastStopReason!==void 0?{lastStopReason:this.lastStopReason}:{},...s!==null?{guidance:s}:{}})}deriveClosureReason(e){let n=null,r=this.abortController.signal;if(r.aborted&&r.reason!=="closed"){let o=r.reason;o instanceof tn?n="budget_exceeded":o instanceof $e?n="timeout":typeof o=="string"&&o.startsWith("Budget ")?n="budget_exceeded":typeof o=="string"&&o.includes("timed out")?n="timeout":n="abort"}return ap({dispatchReason:e,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,abort:n,lastStopReason:this.lastStopReason,sawProviderError:this.sawProviderError})}async sealTraceWriter(e){let n=this.config.traceWriter;if(!n)return;let r=this.deriveSealStatus(e),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,c=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}:{},...c!==void 0?{subagentCostUsd:c}:{}})}recordSubagentCompletion(e,n){if(this.subagentCompletedCount++,e){let r=(o,s)=>{typeof o=="number"&&Number.isFinite(o)&&o>0&&(this.subagentRunningTokens[s]+=o)};r(e.inputTokens,"input"),r(e.outputTokens,"output"),r(e.cacheReadTokens,"cacheRead"),r(e.cacheCreationTokens,"cacheCreation")}typeof n=="number"&&Number.isFinite(n)&&n>0&&(this.subagentRunningCostUsd+=n)}deriveSealStatus(e){if(e==="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 we("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 Oa=y(()=>{"use strict";Op()});function Jk(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new $t(n,e)))},e);i.unref(),Promise.resolve(t).then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}function Yk(t){return t.continue===!1||t.decision==="block"}function Da(t,e){if(t?.aborted){let n=t.reason,r=`aborted during ${e}${n?`: ${String(n)}`:""}`;throw new we(r)}}function Fp(){return new Fa}var Ut,$t,Fa,qo=y(()=>{"use strict";ge();Ut=3e4;$t=class extends Error{constructor(n,r){super(`hook handler timed out after ${r}ms during ${n}`);this.hookEvent=n;this.timeoutMs=r;this.name="HookHandlerTimeoutError"}hookEvent;timeoutMs;code="HOOK_HANDLER_TIMEOUT"},Fa=class{handlers=new Map;register(e,n,r={}){let o=this.handlers.get(e);o||(o=[],this.handlers.set(e,o));let s={handler:n,options:r};return o.push(s),()=>{let i=this.handlers.get(e);if(!i)return;let a=i.indexOf(s);a>=0&&i.splice(a,1)}}count(e){return this.handlers.get(e)?.length??0}async dispatch(e,n,r=Ut){Da(n,e.event);let o=this.handlers.get(e.event);if(!o||o.length===0)return{};let s=o.slice(),i={};for(let a of s){Da(n,e.event);let c;try{let d=a.handler(e,n);c=!a.options.longRunning&&r>0&&Number.isFinite(r)?await Jk(d,r,e.event):await d}catch(d){throw d instanceof $t?d:new X(`hook handler threw during ${e.event}`,e.event,d instanceof Error?d.message:String(d),{cause:d})}if(Da(n,e.event),Yk(c))throw new X(`hook handler blocked ${e.event}${c.reason?`: ${c.reason}`:""}`,e.event,c.reason);let l=[i.injectContext,c.injectContext].filter(d=>typeof d=="string"&&d.length>0).join(`
1017
1021
  `);i={...i,...c,...l.length>0?{injectContext:l}:{}}}return i}}});async function He(t,e,n,r){if(!t)return;if(r.kind==="blocked"){await Me(t,{hookEvent:e,decision:"block",...r.err.reason!==void 0?{reason:r.err.reason}:{},...e==="PreToolUse"&&n.toolName!==void 0?{blockedTool:n.toolName}:{}});return}let o=r.decision;await Me(t,{hookEvent:e,decision:o.decision,...o.reason!==void 0?{reason:o.reason}:{},...o.injectContext!==void 0?{injectedContextBytes:Buffer.byteLength(o.injectContext,"utf8")}:{}})}async function Lp(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await He(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof X&&await He(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function Xk(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new $t(n,e)))},e);i.unref(),t.then(a=>{s||(s=!0,clearTimeout(i),r(a))},a=>{s||(s=!0,clearTimeout(i),o(a))})})}async function Np(t,e,n={}){if(!t)return{};try{let r=await Xk(t.dispatch(e,n.signal,Ut),Ut,"SubagentStop");return await He(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof $t?(console.warn(`[afk] SubagentStop hook timed out after ${Ut}ms (subagentId=${e.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof X&&await He(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof X||r instanceof we?(B(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(B(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function La(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await He(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){throw r instanceof X&&await He(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r}}async function $p(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await He(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof X&&await He(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof X||r instanceof we){B(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}B(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}async function Up(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await He(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof X&&await He(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof X||r instanceof we){B(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}B(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var zo=y(()=>{"use strict";de();ge();qo();ne()});import{mkdir as Qk,writeFile as Zk}from"fs/promises";import{dirname as e_,join as t_}from"path";function n_(){return t_(Ye(),"routing-decisions.jsonl")}function r_(t){let e={surface:"afk"};for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}async function re(t){if(!(k.VITEST||k.NODE_ENV==="test"))try{let e=n_();await Qk(e_(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...r_(t)})+`
1018
1022
  `;await Zk(e,r,{flag:"a"})}catch{}}var rt=y(()=>{"use strict";H();W()});import{AsyncLocalStorage as o_}from"node:async_hooks";function jp(t,e){return Bp.run(t,e)}function Re(){return Bp.getStore()}var Bp,Bt=y(()=>{"use strict";Bp=new o_});function Hp(){return Fp()}function Vo(t,e){return t??e}var Jo=y(()=>{"use strict";qo()});function Na(t,e){return e?.allowedTools?e.allowedTools.includes(t)?{allowed:!0}:{allowed:!1,reason:`Tool "${t}" is not in the configured allowlist`}:{allowed:!0}}function Yo(t,e){return Kp(t,e)}function Xo(t,e){return Kp(t,e)}function Kp(t,e){if(!t?.allowedTools||e.length===0)return t;let n=new Set(t.allowedTools),r=!1;for(let o of e)n.has(o)||(n.add(o),r=!0);return r?{...t,allowedTools:[...n]}:t}var Qo=y(()=>{"use strict"});function j_(t){return t.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,e=>/\$\(|`/.test(e)?e:" ")}function fn(t){if(typeof t!="string"||t.trim().length===0)return{mutating:!1};let e=t.replace(u_," ");for(let s of U_)if(s.re.test(e))return{mutating:!0,reason:s.reason};let n=t.match(I_)?.[1];if(n&&C_.test(n))return{mutating:!0,reason:"interpreter one-liner file write (`-c`/`-e`)"};let r=j_(t);for(let s of B_)if(s.re.test(r))return{mutating:!0,reason:s.reason};let o=r.replace(N_," ").replace(L_," ").replace(/&(>>?)/g,"$1");return $_.test(o)?{mutating:!0,reason:"output redirection to a file (`>`/`>>`)"}:{mutating:!1}}var s_,i_,a_,c_,l_,d_,u_,p_,f_,m_,g_,h_,y_,b_,w_,S_,v_,Zo,k_,__,E_,A_,T_,x_,R_,P_,I_,C_,M_,O_,D_,F_,L_,N_,$_,U_,B_,es=y(()=>{"use strict";s_=/\bgit\b[^|;&]*\s(commit|push|pull|merge|rebase|reset|checkout|switch|restore|cherry-pick|revert|am|apply|clean|add|rm|mv|init)\b/i,i_=/\bgit\b[^|;&]*\s+tag\s+-/i,a_=/\bgit\b[^|;&]*\s+branch\s+-[dDmM]\b/i,c_=/\bgit\b[^|;&]*\s+remote\s+(add|remove|rm|set-url|rename)\b/i,l_=/\bgit\b[^|;&]*\s+worktree\s+(remove|prune|move|lock|unlock)\b/i,d_=/\bgit\b[^|;&]*\s+stash\b(?!\s+(list|show)\b)/i,u_=/\bstash@\{[^}]*\}/gi,p_=/\bgit\s+config\b[^|;&]*\s(--add|--unset|--unset-all|--replace-all|--rename-section|--remove-section|--edit|-e)\b/i,f_=/\bgit\s+config\s+(?:--(?:global|system|local|worktree)\s+|(?:--file|-f)\s+\S+\s+)*[\w][\w.-]*\s+\S/i,m_=/\bgh\s+\w[\w-]*\s+(create|merge|close|edit|delete|comment|review|reopen|sync|fork|clone|ready)\b/i,g_=/\bgh\s+api\b.*(-X|--method)\s+(POST|PUT|PATCH|DELETE)\b/i,h_=/\bgh\s+api\b.*(\s-f\b|\s-F\b|--field\b)/i,y_=/\bgh\s+(secret|variable|workflow|release|run|cache|ssh-key|gpg-key)\s+(set|run|rerun|cancel|upload|delete|enable|disable)\b/i,b_=/\|\s*(sh|bash|zsh|dash)\b/i,w_=/\b(rm|rmdir|unlink|mv|cp|mkdir|touch|dd|truncate|tee|sponge|ln|chmod|chown|chgrp|shred|rsync)\b/i,S_=/\bfind\b[^|;&]*\s-delete\b/i,v_=/\bfind\b[^|;&]*\s-exec\s+['"]?\s*(rm|rmdir|unlink|mv|cp|dd|truncate|shred|tee|chmod|chown|chgrp|install|patch)\b/i,Zo=String.raw`(?:^|[\n;|&(]|\$\()\s*`,k_=new RegExp(Zo+String.raw`patch\b`,"i"),__=new RegExp(Zo+String.raw`install\b`,"i"),E_=new RegExp(Zo+String.raw`(?:source\b|\.\s+\S)`,"i"),A_=/\btar\s+-?[a-zA-Z]*[cxruA][a-zA-Z]*\b/i,T_=new RegExp(Zo+String.raw`unzip\b`,"i"),x_=/\bcpio\b[^|;&]*\s-[a-zA-Z]*i\b/i,R_=/\bsed\b[^|;&]*\s-[a-zA-Z]*i\b/i,P_=/\bperl\b[^|;&]*\s-[a-zA-Z]*i\b/i,I_=/\b(?:python3?|nodejs|node|bun|ruby|perl|php)\b[^|;&]*?\s-(?:c|e)\b\s*("(?:[^"\\]|\\.)*"|'[^']*'|`[^`]*`)/i,C_=/open\s*\([^)]*,\s*['"][wax]|writeFileSync|writeFile\b|appendFileSync|appendFile\b|createWriteStream|File\.(?:write|delete)\b|IO\.write\b|FileUtils\.|\bBun\.write\b|os\.remove\b|shutil\.\w|\.write_text\b|\.write_bytes\b/i,M_=/\b(npm|pnpm|yarn|pip|pip3|brew|cargo|go|apt|apt-get|gem|poetry|bundle|composer)\s+(install|add|remove|uninstall|i|ci|up|update|upgrade|dlx|get|require)\b/i,O_=/\b(curl|wget)\b[^|;&]*\s(-o\b|-O\b|--output\b)/i,D_=/\bcurl\b[^|;&]*\s-X\s+(POST|PUT|PATCH|DELETE)\b/i,F_=/\bcurl\b[^|;&]*\s(-d\b|--data\b|-F\b|--form\b)/i,L_=/(\d*&?>>?\s*\/dev\/null|\d*>&\d+|&>\s*\/dev\/null|&>>\s*\/dev\/null)/gi,N_=/\$\(\(.*?\)\)/g,$_=/(?<![=<>-])>>?(?!&)/,U_=[{re:s_,reason:"git repository mutation"},{re:i_,reason:"git tag create/delete"},{re:a_,reason:"git branch delete/rename"},{re:c_,reason:"git remote mutation"},{re:d_,reason:"git stash mutation (only `stash list`/`stash show` allowed)"},{re:p_,reason:"git config write flag (only reads allowed)"},{re:f_,reason:"git config set (`<key> <value>`; only reads allowed)"},{re:m_,reason:"gh write operation"},{re:g_,reason:"gh api write method (POST/PUT/PATCH/DELETE)"},{re:h_,reason:"gh api field payload (-f/-F/--field)"},{re:y_,reason:"gh extended write operation (secret/variable/workflow/run/cache)"},{re:l_,reason:"git worktree mutation (remove/prune/move)"},{re:R_,reason:"sed in-place edit (-i)"},{re:P_,reason:"perl in-place edit (-i)"},{re:M_,reason:"package install/modify"},{re:O_,reason:"curl/wget output-to-file"},{re:D_,reason:"curl write method (POST/PUT/PATCH/DELETE)"},{re:F_,reason:"curl data/form payload"},{re:v_,reason:"find -exec with mutating verb"}],B_=[{re:b_,reason:"pipe-to-shell (RCE via piped interpreter)"},{re:w_,reason:"filesystem mutation"},{re:S_,reason:"find -delete (file removal)"},{re:k_,reason:"patch (applies a diff to files)"},{re:__,reason:"install (writes files)"},{re:E_,reason:"source/dot-source executes a script"},{re:A_,reason:"tar create/extract/append/update (writes files/archive)"},{re:T_,reason:"unzip (writes files)"},{re:x_,reason:"cpio extract (-i mode writes files)"}]});var H_,K_,W_,G_,q_,z_,V_,J_,Y_,jt,Ht,Kt,X_,Q_,Z_,eE,tE,nE,rE,oE,sE,iE,aE,cE,lE,ot,st,zN,it=y(()=>{"use strict";H_={name:"bash",category:"shell",concurrencySafe:!1,description:"Execute a shell command and return its stdout and stderr. Use for running programs, installing packages, git operations, and any task that requires a shell. Commands run in the user's default shell. Long-running commands should use timeout_ms. Output is capped at ~100KB; excess is truncated with a notice.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute."},timeout_ms:{type:"number",description:"Optional timeout in milliseconds (default 120000, max 600000). The command is killed if it exceeds this duration."}},required:["command"]}},K_={name:"read_file",category:"read",concurrencySafe:!0,description:"Read a file from the filesystem. Returns the file content with line numbers. Use offset and limit to read specific sections of large files. When the read returns a partial view, the response ends with a `... (showing lines X-Y of Z [\u2014 pass offset=N to continue])` annotation indicating the full file size and how to continue. Binary files are detected and rejected. Missing files return an error.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to read."},offset:{type:"number",description:"Line number to start reading from (1-based). Defaults to 1."},limit:{type:"number",description:"Maximum number of lines to read. Defaults to 2000."}},required:["file_path"]}},W_={name:"write_file",category:"write",concurrencySafe:!1,description:"Write content to a file, creating it if it does not exist or overwriting if it does. Parent directories are created automatically. Prefer edit_file for modifying existing files \u2014 use write_file only for new files or complete rewrites.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to write."},content:{type:"string",description:"The full content to write to the file."}},required:["file_path","content"]}},G_={name:"edit_file",category:"write",concurrencySafe:!1,description:"Perform an exact string replacement in a file. Finds old_string and replaces it with new_string. The edit fails if old_string is not found or matches multiple locations (unless replace_all is true). Always use read_file first to verify the exact content before editing.",input_schema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to the file to edit."},old_string:{type:"string",description:"The exact string to find and replace. Must match file content exactly."},new_string:{type:"string",description:"The replacement string."},replace_all:{type:"boolean",description:"If true, replace all occurrences. If false (default), fail when multiple matches exist."}},required:["file_path","old_string","new_string"]}},q_={name:"glob",category:"read",concurrencySafe:!0,description:'Find files matching a glob pattern. Returns matching file paths, capped at 500 results. Use for discovering files before reading them. Patterns follow standard glob syntax (e.g., "src/**/*.ts", "*.json").',input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match (e.g., "src/**/*.ts").'},path:{type:"string",description:"Base directory to search from. Defaults to the current working directory."}},required:["pattern"]}},z_={name:"grep",category:"read",concurrencySafe:!0,description:"Search file contents for lines matching a pattern. Returns matches in file:line:content format. Runs `grep -rn` in basic-regex (BRE) mode by default, where `|` is a LITERAL pipe \u2014 not alternation; set extended: true for extended-regex (ERE) alternation. A no-match result on a pattern containing `|` is often a false negative \u2014 re-read the returned hint. Output is capped to prevent overflow. Use for finding symbols, strings, or patterns across the codebase.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Search pattern. Basic regex (BRE) by default: `|` `+` `?` `(` `)` `{` `}` are LITERAL characters. Set extended: true for extended regex (ERE) where `|` means alternation."},path:{type:"string",description:"Directory or file to search. Defaults to current working directory."},include:{type:"string",description:'File glob to restrict search (e.g., "*.ts"). Passed as --include to grep.'},extended:{type:"boolean",description:"Use extended regex (ERE, `grep -E`) so `|` is alternation and `+ ? ( ) { }` are metacharacters. Default false (BRE \u2014 those characters match literally)."}},required:["pattern"]}},V_={name:"list_directory",category:"read",concurrencySafe:!0,description:"List the contents of a directory. Returns file and subdirectory names with type annotations (directories end with /). Use for exploring project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the directory to list."}},required:["path"]}},J_={name:"send_telegram",category:"web",concurrencySafe:!1,riskClass:"caution",description:"Send a Telegram message to the operator. Use to surface terminal-state notifications, blocking questions, or important status updates when the user is away from keyboard (AFK). The message is delivered through the same Telegram bot the operator uses to drive this session. By default the message goes to your primary chat (the first private chat in `AFK_TELEGRAM_ALLOWED_CHAT_IDS`, or `AFK_TELEGRAM_PRIMARY_CHAT_ID` if set); set `telegram.notify` in afk.config.json to broadcast to all allowed chats or target a custom set.\n\nPlain text only \u2014 Telegram's 4096-character limit per message is enforced. Returns an error if Telegram is not configured (missing `TELEGRAM_BOT_TOKEN` or empty allowlist) so the tool is safe to attempt unconditionally.\n\nUse sparingly: this is a real push notification to a human. Reserve for terminal states (Done/Blocked/Asking) and material progress, not running commentary. When running inside the Telegram bot, prefer replying normally \u2014 your response already reaches the operator through the bot. Use this tool only from CLI or daemon sessions.",input_schema:{type:"object",properties:{message:{type:"string",description:"Plain-text message body to send to the operator. Max 4096 characters (Telegram API limit). Must be non-empty."}},required:["message"]}},Y_={name:"web_scrape",category:"web",concurrencySafe:!0,description:'Scrape a web page or run a web search and return text content suitable for reasoning over. Three modes:\n\n- `markdown` (default): fetches the URL and extracts the main content as clean markdown (Readability + Turndown). Handles JS-rendered pages: if the plain fetch yields thin content, it escalates to a headless-browser render and re-extracts. Use this for articles, docs, blog posts, and most "I want to read this page" cases. No API key required (the render fallback needs the Playwright chromium binary \u2014 `pnpm exec playwright install chromium`).\n- `raw`: GETs the URL directly with no transformation. Use for JSON APIs, robots.txt, RSS, plain-text endpoints, or when you need the literal bytes. No API key required.\n- `search`: runs a web search and returns ranked markdown results. Use when you need to FIND a URL, not read one. Provide `query` instead of `url`. Requires `EXA_API_KEY` (free tier at https://exa.ai); the handler returns a clear error if it is unset.\n\nOutputs are capped at `max_bytes` UTF-8 bytes (default 1MB, ceiling 10MB) and the request is aborted after `timeout_ms` (default 30000, ceiling 120000).',input_schema:{type:"object",properties:{mode:{type:"string",enum:["markdown","raw","search"],description:'Fetch mode. Defaults to "markdown".'},url:{type:"string",description:"Absolute http(s) URL. Required for markdown and raw modes. Ignored in search mode."},query:{type:"string",description:"Search query string. Required for search mode. Ignored otherwise."},timeout_ms:{type:"number",description:"Request timeout in milliseconds (default 30000, clamped to 120000)."},max_bytes:{type:"number",description:"Maximum UTF-8 bytes returned. Content beyond this is truncated with a marker. Default 1000000, clamped to 10000000."}},required:[]}},jt={name:"agent",category:"subagent",concurrencySafe:!0,description:`Dispatch an independent subagent with its own context window and tool access. Use for tasks that protect the main session's context: codebase exploration, multi-file inspection, repo search, verification, debugging, failing-test investigation, PR review, parallel hypothesis testing, independent re-derivation of a claim, audit work, stale-path detection, feature-wiring checks, and any research-shaped investigation.
1019
1023
 
@@ -1053,7 +1057,7 @@ Note: this search ran in basic-regex (BRE) mode, where '|' is a literal pipe \u2
1053
1057
  `)}}catch(i){if(i instanceof Error){let a=i;return a.code==="ENOENT"?{content:`Directory not found: ${s}`,isError:!0}:a.code==="ENOTDIR"?{content:`Not a directory: ${s}`,isError:!0}:a.code==="EACCES"?{content:`Permission denied: ${s}`,isError:!0}:{content:`Error listing directory: ${i.message}`,isError:!0}}return{content:"Unknown error listing directory",isError:!0}}}});function cs(t,e=()=>{}){let n=new Set;if(!t)return n;for(let r of t.split(",")){let o=r.trim();if(o){if(!/^-?\d+$/.test(o)){e("[allowlist] Ignoring non-numeric chat ID:",o);continue}n.add(Number(o))}}return n}function ff(t,e=()=>{}){return async(n,r)=>{let o=n.chat?.id;if(o===void 0||!t.has(o)){e("[allowlist] Rejecting update from chat:",o??"<unknown>");return}await r()}}var ls=y(()=>{"use strict"});var Xa=y(()=>{"use strict";H();W()});var mf=y(()=>{"use strict";H();Xa()});import{execFile as bA}from"node:child_process";import{promisify as wA}from"node:util";function hf(t,e){if(t.length>gf)throw new Error(`Invalid branch prefix from ${e}: length ${t.length} exceeds ${gf}.`);if(!SA.test(t))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 only [A-Za-z0-9_-./] are allowed.`);if(t.startsWith("-"))throw new Error(`Invalid branch prefix from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);return t}function yf(t,e){if(t.trim().length===0)throw new Error(`Invalid worktree base ref from ${e}: '' \u2014 base ref cannot be empty.`);if(t.startsWith("-"))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not start with '-' (would be parsed by git as a flag).`);if(t.includes("\0"))throw new Error(`Invalid worktree base ref from ${e}: contains a NUL byte.`);if(/\s/.test(t))throw new Error(`Invalid worktree base ref from ${e}: '${t}' \u2014 must not contain whitespace.`)}var PU,SA,gf,bf=y(()=>{"use strict";H();Xa();mf();PU=wA(bA),SA=/^[A-Za-z0-9_\-./]*$/,gf=64});import{existsSync as ds,readdirSync as MU,readFileSync as vA,realpathSync as OU,statSync as DU}from"fs";import{homedir as kA}from"os";import{join as kt}from"path";function Za(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e={};for(let n of wf){let r=t[n];if(r!==void 0){if(r===!0){e[n]={plugins:!0,skills:!0,mcp:!0};continue}if(r!==!1&&typeof r=="object"&&r!==null&&!Array.isArray(r)){let o=r;e[n]={plugins:o.plugins===!0,skills:o.skills===!0,mcp:o.mcp===!0}}}}return Object.keys(e).length>0?e:void 0}function _A(){return[ft(),ro()]}function tr(t=_A()){for(let e of t)if(ds(e))try{let n=JSON.parse(vA(e,"utf-8")),r=Za(n.importFrom);if(r!==void 0)return r}catch{}}function nr(t,e=kA()){let n={pluginRoots:[],skillRoots:[],mcpConfigs:[]};if(!t)return n;for(let r of wf){let o=t[r];if(!o)continue;let s=Qa[r];if(o.plugins)for(let i of s.pluginRoots(e))ds(i)&&n.pluginRoots.push(i);if(o.skills){let i=`imported:${r}`;for(let a of s.skillRoots(e))ds(a)&&n.skillRoots.push({dir:a,origin:i})}if(o.mcp){let i=EA(s.mcpConfigCandidates(e));i&&n.mcpConfigs.push({source:i,format:s.mcpFormat})}}return n}function EA(t){for(let e of t)if(ds(e))return e;return null}var wf,Qa,$U,us=y(()=>{"use strict";W();wf=["claude-code","codex"],Qa={"claude-code":{label:"Claude Code",pluginRoots:t=>[kt(t,".claude","plugins")],skillRoots:t=>[kt(t,".claude","skills")],mcpConfigCandidates:t=>[kt(t,".claude","mcp.json"),kt(t,".claude",".mcp.json"),kt(t,".claude","claude-code","mcp.json")],mcpFormat:"json"},codex:{label:"Codex",pluginRoots:t=>[kt(t,".codex","plugins")],skillRoots:t=>[kt(t,".codex","skills")],mcpConfigCandidates:t=>[kt(t,".codex","config.toml")],mcpFormat:"toml"}},$U={"claude-code":Qa["claude-code"].label,codex:Qa.codex.label}});import{readFileSync as kf,existsSync as tc}from"fs";import{join as or}from"path";import{config as AA}from"dotenv";function nc(){return xa()}function xA(t){let e=t.trim();if(!e)return e;let n="/chat/completions";if(e.endsWith(n)){let r=e.slice(0,-n.length);return vf.has(e)||(vf.add(e),console.warn(`[afk] AFK_OPENAI_BASE_URL: stripped trailing "/chat/completions" \u2014 the OpenAI SDK appends it automatically.
1054
1058
  Effective base URL: ${r}`)),r}return e}function RA(){if(ec!==void 0)return ec;if(!Sf){let o=[or(process.cwd(),".env"),Ct(),Gd()];for(let s of o)tc(s)&&AA({path:s,override:!1});Sf=!0}let t={},e=k.AFK_MODEL??k.CLAUDE_MODEL;if(e){let o=e.toLowerCase();t.model=ha(o)?o:e}if(V(e)==="anthropic-direct"){let o=nc();o!==void 0&&(t.apiKey=o)}let r=k.AFK_LOCAL_BASE_URL;if(r&&r.length>0&&(t.baseUrl=r,t.apiKey=k.AFK_LOCAL_API_KEY||"local"),k.AFK_MAX_TOKENS&&(t.maxTokens=parseInt(k.AFK_MAX_TOKENS,10)),k.AFK_TEMPERATURE&&(t.temperature=parseFloat(k.AFK_TEMPERATURE)),k.AFK_SYSTEM_PROMPT&&(t.systemPrompt=k.AFK_SYSTEM_PROMPT),k.AFK_AUTO_ROUTING){let o=k.AFK_AUTO_ROUTING.toLowerCase()==="true";t.autoRouting={interactive:o,chat:o,telegram:o,daemon:o}}return k.AFK_OPENAI_BASE_URL&&(t.openaiBaseUrl=xA(k.AFK_OPENAI_BASE_URL)),ec=t,t}function _f(){if(bn!==void 0)return bn;let t=[or(process.cwd(),"afk.config.json"),ft(),ro()];for(let e of t)if(tc(e))try{let n=kf(e,"utf-8"),r=JSON.parse(n),o={},s=Du(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=ha(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 c={};if((a.mode==="primary"||a.mode==="broadcast"||a.mode==="custom")&&(c.mode=a.mode),typeof a.primaryChatId=="number"&&Number.isFinite(a.primaryChatId)&&(c.primaryChatId=a.primaryChatId),Array.isArray(a.targets)){let l=a.targets.filter(d=>typeof d=="number"&&Number.isFinite(d));l.length>0&&(c.targets=l)}i.notify=c}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),e!==or(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=hf(r.interactive.worktreeBranchPrefix,`${e}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(yf(r.interactive.worktreeBase,`${e}#/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 bn={config:o,sourcePath:e,modelsPartial:s},bn}catch(n){console.error(`Warning: Failed to parse ${e}:`,n)}return bn={config:{},sourcePath:void 0,modelsPartial:{}},bn}function PA(){if(wn!==void 0)return wn.value;let t=[or(process.cwd(),"AFK.md"),or(me(),"AFK.md")];for(let e of t)if(tc(e))try{let n=kf(e,"utf-8").trim();if(n.length>0)return wn={value:{content:n,path:e}},wn.value}catch{}return wn={value:null},wn.value}function Ef(){return _f().config.telegram??{}}function rc(t){let e=RA(),{config:n,sourcePath:r,modelsPartial:o}=_f(),s={...rr,...e,...n,...t},i;if(e.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 l=PA();l!==null&&(s.systemPrompt=l.content,i=`afk-md:${l.path}`)}let a={model:s.model??rr.model,maxTokens:s.maxTokens??rr.maxTokens,temperature:s.temperature??rr.temperature,updatePolicy:s.updatePolicy??rr.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??TA,...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}:{}},c=t?.models??fa(o);if(Ro(c),a.models=c,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 rr,TA,Sf,ec,vf,bn,wn,ps=y(()=>{"use strict";Be();Qe();Se();W();ln();bf();H();us();rr={model:"sonnet",maxTokens:4096,temperature:1,updatePolicy:"notify"},TA="bypassPermissions",Sf=!1;vf=new Set});function IA(t,e){return e!==void 0&&Number.isFinite(e)&&e!==0?e:t.find(r=>r>0)??t[0]}function CA(t,e={}){let n=[...t],r=e.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let s=(e.targets??[]).filter(i=>typeof i=="number"&&Number.isFinite(i)&&i!==0);if(s.length>0)return[...new Set(s)]}let o=IA(n,e.primaryChatId);return o!==void 0?[o]:[]}function MA(t){if(!t)return;let e=t.trim();if(!/^-?\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)&&n!==0?n:void 0}function OA(t){if(!t)return;let e=t.trim().toLowerCase();return e==="primary"||e==="broadcast"||e==="custom"?e:void 0}function DA(){let t=Ef().notify??{},e=t.mode??OA(k.AFK_TELEGRAM_NOTIFY_MODE),n=t.primaryChatId??MA(k.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...e!==void 0?{mode:e}:{},...n!==void 0?{primaryChatId:n}:{},...t.targets!==void 0?{targets:t.targets}:{}}}function fs(){let t=cs(k.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return CA(t,DA())}var oc=y(()=>{"use strict";ls();ps();H()});var Tf={};Gi(Tf,{push:()=>Sn,pushIfConfigured:()=>sc,pushMarkdown:()=>Af});async function Sn(t){if(!t.token)throw new Error("push: token is required");if(t.chatId===""||t.chatId==null||t.chatId===0)throw new Error("push: chatId is required");let e=t.fetchImpl??fetch,r=`${t.apiBase??FA}/bot${t.token}/sendMessage`,o={chat_id:t.chatId,text:t.text.slice(0,4096)};t.parseMode&&(o.parse_mode=t.parseMode),t.replyMarkup&&(o.reply_markup=t.replyMarkup);let s=new AbortController,i=setTimeout(()=>s.abort(),1e4);try{let a=await e(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 c;try{c=(await a.json()).description}catch{c=`HTTP ${a.status}`}return{ok:!1,status:a.status,...c!==void 0?{errorMessage:c}:{}}}catch(a){return{ok:!1,status:0,errorMessage:a instanceof Error?a.message:String(a)}}finally{clearTimeout(i)}}async function Af(t){let e=Mt(t.text),n=Ae(e),r={ok:!0,status:200};for(let o of n)if(r=await Sn({...t,text:o,parseMode:"HTML"}),!r.ok)return r.status===400&&/can't parse entities/i.test(r.errorMessage??"")?Sn({...t}):r;return r}async function sc(t,e={}){let n=k.TELEGRAM_BOT_TOKEN;if(!n)return null;let r=fs();if(r.length===0)return null;let o=Ae(t),s=[];for(let i of r)for(let a=0;a<o.length;a++){let c={token:n,chatId:i,text:o[a]??"",...e.replyMarkup!==void 0&&a===0?{replyMarkup:e.replyMarkup}:{},...e.fetchImpl!==void 0?{fetchImpl:e.fetchImpl}:{}};s.push(e.markdown?await Af(c):await Sn({...c,...e.parseMode!==void 0?{parseMode:e.parseMode}:{}}))}return s}var FA,ms=y(()=>{"use strict";oc();Ne();H();FA="https://api.telegram.org"});function LA(t=Sn){return async(e,n)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let o=e.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>xf)return{content:`Invalid input: message exceeds Telegram's ${xf}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=k.TELEGRAM_BOT_TOKEN;if(!s)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let i=fs();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 c of i){let l=await t({token:s,chatId:c,text:o});l.ok||a.push(`chat ${c}: ${l.errorMessage??`HTTP ${l.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 xf,Rf,Pf=y(()=>{"use strict";H();ms();oc();xf=4096;Rf=LA()});import{JSDOM as NA}from"jsdom";import{Readability as $A}from"@mozilla/readability";import UA from"turndown";function If(t){return t.replace(/\n{3,}/g,`
1055
1059
 
1056
- `).trim()}function BA(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}function Mf(t,e){let r=new NA(t,{url:e}).window.document,o=(r.title??"").trim(),s=null;try{let l=r.cloneNode(!0);s=new $A(l).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let l=If(ic.turndown(s.content)),d=(s.title??"").trim()||o,u=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:d,markdown:l,textLength:u,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",c=If(ic.turndown(a));return{title:o,markdown:c,textLength:BA(i),usedFallback:!0}}var Cf,ic,Of=y(()=>{"use strict";Cf=200,ic=new UA({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});ic.remove(["script","style","noscript","iframe"])});function HA(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function Df(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function KA(t,e){let n=t.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,e)}async function gs(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??HA,c=n.signal??void 0,l;for(let d=0;d<=o;d++){if(c?.aborted)throw c.reason??new Error("aborted");try{let u=await t(e,n);if(!jA.has(u.status)||d===o)return u;let p=KA(u,i)??Df(d,s,i);B("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,c)}catch(u){if(c?.aborted||(l=u,d===o))throw u;let p=Df(d,s,i);B("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,c)}}throw l??new Error("retryFetch: exhausted without a result")}var jA,ac=y(()=>{"use strict";de();jA=new Set([429,502,503,504])});import{readFileSync as WA}from"node:fs";import{join as GA}from"path";function qA(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Ff(t,e){return qA(e).test(t)}function JA(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(zA.has(e))return!0;if(VA.has(e))return!1}return!1}function Lf(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function YA(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Nf(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Yi(e),e}function XA(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function QA(t){try{return WA(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function ZA(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Nf(e.defaultProfile)),n}function $f(t){let e=t?.env??k,n=t?.readFileSync??QA,r=t?.surface??e.AGENT_SURFACE,o=JA(e.AFK_BROWSER_HEADLESS,r),s=Lf(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Lf(e.AFK_BROWSER_BLOCKED_DOMAINS),a=XA(e.AFK_BROWSER_DOM_SNAPSHOTS),c=YA(e.AFK_BROWSER_BACKEND),l=Nf(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():GA(Xe(),"browser.json"),f=n(p);if(f===void 0)return d;let h;try{h=JSON.parse(f)}catch(w){throw new Error(`Failed to parse browser config at ${p}: ${String(w)}`)}if(typeof h!="object"||h===null||Array.isArray(h))throw new Error(`Browser config at ${p} must be a JSON object`);let g=ZA(d,h);return g.configPath=p,g}function cc(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(Ff(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Ff(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var zA,VA,lc=y(()=>{"use strict";H();W();zA=new Set(["daemon","subagent","telegram","afk"]),VA=new Set(["repl","interactive","cli"])});import Wt from"node:fs";import hs from"node:path";import{randomBytes as eT}from"node:crypto";import{chromium as tT}from"playwright";function nT(){try{return"5.15.12"}catch{}try{let t=hs.resolve(import.meta.dirname,"../../../package.json"),e=Wt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var rT,ys,Uf=y(()=>{"use strict";W();de();rT=nT(),ys=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(e){this.config=e}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=tT.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,e}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);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(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);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(e){return this.sessions.get(e)?.page}async renderHtml(e,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(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),c=await i.content(),l=i.url(),d=a!==null?a.status():null;return{html:c,finalUrl:l,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);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(e){let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),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 e=[...this.sessions.keys()];if(await Promise.all(e.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/${rT}`}}loadStorageState(e){let n=Xi(e);try{if(!Wt.existsSync(n))return;let r=JSON.parse(Wt.readFileSync(n,"utf8"));return B("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){B("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Xi(e);if(!Wt.existsSync(r))return;let o=await n.storageState(),s=hs.join(hs.dirname(r),`.${hs.basename(r)}.${process.pid}.${eT(4).toString("hex")}.tmp`);Wt.writeFileSync(s,JSON.stringify(o),{mode:384}),Wt.chmodSync(s,384),Wt.renameSync(s,r),B("[browser/vault] saved session",{profile:e,file:r})}catch(r){B("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as oT}from"crypto";function dc(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of sT)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Bf(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&iT.test(t.label))}function jf(t){return oT("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Hf(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var sT,iT,sr=y(()=>{"use strict";sT=[{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}];iT=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as aT}from"node:crypto";function cT(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function lT(t,e,n){return`el_${aT("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function dT(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Kf(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Gf(t,e){let n=t.role??"",r=t.name??"";Wf.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Gf(s,e)}async function uT(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,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},qf).catch(()=>[])}async function pT(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,h={role:l,name:c,disabled:p};u!==void 0&&(h.value=u),f!==void 0&&(h.checked=f),o.push(h)}return o},qf).catch(()=>[])}function fT(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function bs(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=fT(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=uT(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,h,g]=await Promise.all([i,a,c,l,d]),w,b=!1;u!==null?(w=[],Gf(u,w)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,w=(await pT(t)).filter($=>Wf.has($.role??"")));let _=new Map;for(let I of p){let $=Kf(I.name),j=_.get($);(!j||j.bbox.w===0&&I.bbox.w>0)&&_.set($,I)}let S=w.map(I=>({ax:I,dom:_.get(Kf(I.name??""))})),v=r?S:S.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);v.sort((I,$)=>{let j=I.dom?.bbox.y??0,M=$.dom?.bbox.y??0;if(j!==M)return j-M;let R=I.dom?.bbox.x??0,U=$.dom?.bbox.x??0;return R-U}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=v.slice(0,n).map((I,$)=>{let j=I.ax.role??"generic",M=I.ax.name??"",R=lT(j,M,$),U=I.dom?.bbox??{x:0,y:0,w:0,h:0},C=I.dom?.type??null,N=null;I.ax.value!==void 0&&I.ax.value!==null&&(N=String(I.ax.value)),I.ax.checked!==void 0&&(N=String(I.ax.checked)),Bf({role:j,kind:C})&&(N="[redacted]");let O={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(O.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(O.selected=I.ax.selected),I.ax.expanded!==void 0&&(O.expanded=I.ax.expanded);let F;I.dom?.testId?F=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(F=`#${I.dom.id}`);let z={id:R,role:j,label:cT(M),kind:C,value:N,state:O,bbox:U};return F!==void 0&&(z.selector=F),z}),T="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?T="loading":I==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let P=dT(f),x=`obs_${e.observationCounter.toString(36)}`,L=new Date().toISOString();return{observationId:x,url:h,title:g,textSummary:P,interactive:A,status:{httpStatus:e.httpStatus??null,loadingState:T,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:L}}var Wf,qf,zf=y(()=>{"use strict";sr();Wf=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);qf="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Vf(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,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 uc(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Vf(t,s)))).filter(o=>o!==null)}async function mT(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function pc(t,e,n){switch(e.kind){case"element_id":return gT(t,e,n);case"selector":return hT(t,e);case"semantic":return yT(t,e)}}async function gT(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await uc(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function hT(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await uc(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function yT(t,e){return e.role!==void 0?bT(t,e.text,e.role):wT(t,e.text,e)}async function bT(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await uc(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function wT(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await mT(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let w=p[g];if(w===void 0)continue;let b=await Vf(w.locator,w.index);if(b!==null){let _=`${b.role}:${b.label}:${g}`,S=0;for(let v=0;v<_.length;v++)S=S*31+_.charCodeAt(v)>>>0;f.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Jf=y(()=>{"use strict"});import{randomBytes as ST}from"crypto";import{mkdir as vT,stat as kT,writeFile as _T}from"fs/promises";import{join as fc}from"path";import{gzip as ET}from"zlib";import{promisify as AT}from"util";function TT(t){return fc(no(t),"browser")}function xT(t){return fc(TT(t),"screenshots")}function RT(){return new Date().toISOString().replace(/[:.]/g,"-")}function PT(){return ST(3).toString("hex")}async function mc(t,e,n){if(e.length>Yf)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Yf} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=xT(t);await vT(r,{recursive:!0});let o=`${RT()}-${PT()}-${n}.png`,s=fc(r,o);await _T(s,e);let{size:i}=await kT(s);return{path:s,bytes:i}}var jB,Yf,Xf=y(()=>{"use strict";W();sr();jB=AT(ET);Yf=5*1024*1024});var Zf={};Gi(Zf,{PlaywrightProvider:()=>gc});function Qf(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var gc,em=y(()=>{"use strict";Uf();zf();Jf();lc();sr();Xf();gc=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new ys(e)}async open(e){let n=cc(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(l){a=l}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let c=await bs(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,c.interactive,c.url,c.title,"browser_open"),a!==null)throw a;return c}async observe(e){let{sessionId:n}=e,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;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await bs(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,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=e.timeoutMs??3e4,a=await pc(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Qf(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":{let g=dc(e.value??"");await c.fill(e.value??"");break}case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(w){l=w}else l=g}let u=r.url();if(u!==s){let g=cc(u,this.config);if(!g.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:g.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await bs(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),h=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,h),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,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(e.target!==void 0){let d=await pc(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Qf(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await mc(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);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(e){let n=this.sessions.get(e);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(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await mc(n,o,r);return s}catch{return null}}}});var qt={};Gi(qt,{__resetBrowserRegistryForTests:()=>DT,browserProviderActive:()=>MT,closeBrowserProvider:()=>hc,getBrowserProvider:()=>CT,peekBrowserProvider:()=>OT});function tm(){Promise.resolve(hc()).then(()=>{process.exit(130)})}function nm(){Promise.resolve(hc()).then(()=>{process.exit(143)})}function rm(){We=null}function IT(){ws||(process.on("SIGINT",tm),process.on("SIGTERM",nm),process.on("exit",rm),ws=!0)}function om(){ws&&(process.removeListener("SIGINT",tm),process.removeListener("SIGTERM",nm),process.removeListener("exit",rm),ws=!1)}async function CT(t){return We!==null?We:(Gt!==null||(Gt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(em(),Zf)),n=$f(t),r=new e(n);return IT(),We=r,Gt=null,r})()),Gt)}async function hc(){if(We===null)return;let t=We;We=null,Gt=null,om(),await t.shutdown()}function MT(){return We!==null}function OT(){return We}function DT(){We=null,Gt=null,om()}var We,Gt,ws,zt=y(()=>{"use strict";lc();We=null,Gt=null,ws=!1});function sm(t,e){try{return Mf(t,e)}catch(n){return B("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function UT(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(zt(),qt));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function im(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??UT,o=null,s=t,i=null,a=null;try{let l=await gs(n,t,{headers:$T,redirect:"follow",signal:e.signal});i=l.status,s=l.url||t;let d=l.headers.get("content-type")??"";if(l.ok){if(NT.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await l.text();if(LT.test(d)&&!FT.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};o=sm(u,s)}}catch(l){if(e.signal.aborted||l instanceof Error&&l.message.startsWith("web_scrape markdown mode received binary"))throw l;a=l}if(!(o===null||o.textLength<Cf)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let l=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=sm(l.html,l.finalUrl);if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:l.finalUrl,usedRender:!0}}catch(l){if(e.signal.aborted)throw l;if(o===null){let d=l instanceof Error?l.message:String(l),u=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${t}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=l,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 ${t} (HTTP ${i??"error"}).`)}var FT,LT,NT,$T,am=y(()=>{"use strict";Of();ac();de();FT=/(text\/html|application\/xhtml\+xml)/i,LT=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,NT=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,$T={"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 HT(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(BT,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),jT),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=Go(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function cm(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?HT({apiKey:t.exaApiKey,fetchFn:t.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 lm(t,e){if(e.length===0)return`# Search results for "${t}"
1060
+ `).trim()}function BA(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}function Mf(t,e){let r=new NA(t,{url:e}).window.document,o=(r.title??"").trim(),s=null;try{let l=r.cloneNode(!0);s=new $A(l).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let l=If(ic.turndown(s.content)),d=(s.title??"").trim()||o,u=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:d,markdown:l,textLength:u,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",c=If(ic.turndown(a));return{title:o,markdown:c,textLength:BA(i),usedFallback:!0}}var Cf,ic,Of=y(()=>{"use strict";Cf=200,ic=new UA({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});ic.remove(["script","style","noscript","iframe"])});function HA(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function Df(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function KA(t,e){let n=t.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,e)}async function gs(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??HA,c=n.signal??void 0,l;for(let d=0;d<=o;d++){if(c?.aborted)throw c.reason??new Error("aborted");try{let u=await t(e,n);if(!jA.has(u.status)||d===o)return u;let p=KA(u,i)??Df(d,s,i);B("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,c)}catch(u){if(c?.aborted||(l=u,d===o))throw u;let p=Df(d,s,i);B("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,c)}}throw l??new Error("retryFetch: exhausted without a result")}var jA,ac=y(()=>{"use strict";de();jA=new Set([429,502,503,504])});import{readFileSync as WA}from"node:fs";import{join as GA}from"path";function qA(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Ff(t,e){return qA(e).test(t)}function JA(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(zA.has(e))return!0;if(VA.has(e))return!1}return!1}function Lf(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function YA(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Nf(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Yi(e),e}function XA(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function QA(t){try{return WA(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function ZA(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Nf(e.defaultProfile)),n}function $f(t){let e=t?.env??k,n=t?.readFileSync??QA,r=t?.surface??e.AGENT_SURFACE,o=JA(e.AFK_BROWSER_HEADLESS,r),s=Lf(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Lf(e.AFK_BROWSER_BLOCKED_DOMAINS),a=XA(e.AFK_BROWSER_DOM_SNAPSHOTS),c=YA(e.AFK_BROWSER_BACKEND),l=Nf(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():GA(Xe(),"browser.json"),f=n(p);if(f===void 0)return d;let h;try{h=JSON.parse(f)}catch(w){throw new Error(`Failed to parse browser config at ${p}: ${String(w)}`)}if(typeof h!="object"||h===null||Array.isArray(h))throw new Error(`Browser config at ${p} must be a JSON object`);let g=ZA(d,h);return g.configPath=p,g}function cc(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(Ff(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Ff(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var zA,VA,lc=y(()=>{"use strict";H();W();zA=new Set(["daemon","subagent","telegram","afk"]),VA=new Set(["repl","interactive","cli"])});import Wt from"node:fs";import hs from"node:path";import{randomBytes as eT}from"node:crypto";import{chromium as tT}from"playwright";function nT(){try{return"5.15.13"}catch{}try{let t=hs.resolve(import.meta.dirname,"../../../package.json"),e=Wt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var rT,ys,Uf=y(()=>{"use strict";W();de();rT=nT(),ys=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(e){this.config=e}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=tT.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,e}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);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(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);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(e){return this.sessions.get(e)?.page}async renderHtml(e,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(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),c=await i.content(),l=i.url(),d=a!==null?a.status():null;return{html:c,finalUrl:l,httpStatus:d}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);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(e){let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),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 e=[...this.sessions.keys()];if(await Promise.all(e.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/${rT}`}}loadStorageState(e){let n=Xi(e);try{if(!Wt.existsSync(n))return;let r=JSON.parse(Wt.readFileSync(n,"utf8"));return B("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){B("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Xi(e);if(!Wt.existsSync(r))return;let o=await n.storageState(),s=hs.join(hs.dirname(r),`.${hs.basename(r)}.${process.pid}.${eT(4).toString("hex")}.tmp`);Wt.writeFileSync(s,JSON.stringify(o),{mode:384}),Wt.chmodSync(s,384),Wt.renameSync(s,r),B("[browser/vault] saved session",{profile:e,file:r})}catch(r){B("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as oT}from"crypto";function dc(t){if(t.length===0)return t;let e=t;for(let{regex:n,name:r}of sT)r==="form-password"?e=e.replace(n,"password=[redacted]"):e=e.replace(n,"[redacted]");return e}function Bf(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&iT.test(t.label))}function jf(t){return oT("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Hf(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var sT,iT,sr=y(()=>{"use strict";sT=[{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}];iT=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as aT}from"node:crypto";function cT(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function lT(t,e,n){return`el_${aT("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function dT(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Kf(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Gf(t,e){let n=t.role??"",r=t.name??"";Wf.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Gf(s,e)}async function uT(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,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},qf).catch(()=>[])}async function pT(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,h={role:l,name:c,disabled:p};u!==void 0&&(h.value=u),f!==void 0&&(h.checked=f),o.push(h)}return o},qf).catch(()=>[])}function fT(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function bs(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=fT(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=uT(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,h,g]=await Promise.all([i,a,c,l,d]),w,b=!1;u!==null?(w=[],Gf(u,w)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,w=(await pT(t)).filter($=>Wf.has($.role??"")));let _=new Map;for(let I of p){let $=Kf(I.name),j=_.get($);(!j||j.bbox.w===0&&I.bbox.w>0)&&_.set($,I)}let S=w.map(I=>({ax:I,dom:_.get(Kf(I.name??""))})),v=r?S:S.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);v.sort((I,$)=>{let j=I.dom?.bbox.y??0,M=$.dom?.bbox.y??0;if(j!==M)return j-M;let R=I.dom?.bbox.x??0,U=$.dom?.bbox.x??0;return R-U}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=v.slice(0,n).map((I,$)=>{let j=I.ax.role??"generic",M=I.ax.name??"",R=lT(j,M,$),U=I.dom?.bbox??{x:0,y:0,w:0,h:0},C=I.dom?.type??null,N=null;I.ax.value!==void 0&&I.ax.value!==null&&(N=String(I.ax.value)),I.ax.checked!==void 0&&(N=String(I.ax.checked)),Bf({role:j,kind:C})&&(N="[redacted]");let O={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(O.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(O.selected=I.ax.selected),I.ax.expanded!==void 0&&(O.expanded=I.ax.expanded);let F;I.dom?.testId?F=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(F=`#${I.dom.id}`);let z={id:R,role:j,label:cT(M),kind:C,value:N,state:O,bbox:U};return F!==void 0&&(z.selector=F),z}),T="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?T="loading":I==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let P=dT(f),x=`obs_${e.observationCounter.toString(36)}`,L=new Date().toISOString();return{observationId:x,url:h,title:g,textSummary:P,interactive:A,status:{httpStatus:e.httpStatus??null,loadingState:T,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:L}}var Wf,qf,zf=y(()=>{"use strict";sr();Wf=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);qf="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Vf(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,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 uc(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Vf(t,s)))).filter(o=>o!==null)}async function mT(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function pc(t,e,n){switch(e.kind){case"element_id":return gT(t,e,n);case"selector":return hT(t,e);case"semantic":return yT(t,e)}}async function gT(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await uc(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function hT(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await uc(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function yT(t,e){return e.role!==void 0?bT(t,e.text,e.role):wT(t,e.text,e)}async function bT(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await uc(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function wT(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await mT(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let w=p[g];if(w===void 0)continue;let b=await Vf(w.locator,w.index);if(b!==null){let _=`${b.role}:${b.label}:${g}`,S=0;for(let v=0;v<_.length;v++)S=S*31+_.charCodeAt(v)>>>0;f.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Jf=y(()=>{"use strict"});import{randomBytes as ST}from"crypto";import{mkdir as vT,stat as kT,writeFile as _T}from"fs/promises";import{join as fc}from"path";import{gzip as ET}from"zlib";import{promisify as AT}from"util";function TT(t){return fc(no(t),"browser")}function xT(t){return fc(TT(t),"screenshots")}function RT(){return new Date().toISOString().replace(/[:.]/g,"-")}function PT(){return ST(3).toString("hex")}async function mc(t,e,n){if(e.length>Yf)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Yf} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=xT(t);await vT(r,{recursive:!0});let o=`${RT()}-${PT()}-${n}.png`,s=fc(r,o);await _T(s,e);let{size:i}=await kT(s);return{path:s,bytes:i}}var jB,Yf,Xf=y(()=>{"use strict";W();sr();jB=AT(ET);Yf=5*1024*1024});var Zf={};Gi(Zf,{PlaywrightProvider:()=>gc});function Qf(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var gc,em=y(()=>{"use strict";Uf();zf();Jf();lc();sr();Xf();gc=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new ys(e)}async open(e){let n=cc(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(l){a=l}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let c=await bs(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,c.interactive,c.url,c.title,"browser_open"),a!==null)throw a;return c}async observe(e){let{sessionId:n}=e,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;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await bs(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,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=e.timeoutMs??3e4,a=await pc(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Qf(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":{let g=dc(e.value??"");await c.fill(e.value??"");break}case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(w){l=w}else l=g}let u=r.url();if(u!==s){let g=cc(u,this.config);if(!g.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:u,reason:g.reason}}let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await bs(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),h=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,h),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal})}async screenshot(e){let{sessionId:n}=e,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(e.target!==void 0){let d=await pc(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Qf(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await mc(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);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(e){let n=this.sessions.get(e);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(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await mc(n,o,r);return s}catch{return null}}}});var qt={};Gi(qt,{__resetBrowserRegistryForTests:()=>DT,browserProviderActive:()=>MT,closeBrowserProvider:()=>hc,getBrowserProvider:()=>CT,peekBrowserProvider:()=>OT});function tm(){Promise.resolve(hc()).then(()=>{process.exit(130)})}function nm(){Promise.resolve(hc()).then(()=>{process.exit(143)})}function rm(){We=null}function IT(){ws||(process.on("SIGINT",tm),process.on("SIGTERM",nm),process.on("exit",rm),ws=!0)}function om(){ws&&(process.removeListener("SIGINT",tm),process.removeListener("SIGTERM",nm),process.removeListener("exit",rm),ws=!1)}async function CT(t){return We!==null?We:(Gt!==null||(Gt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(em(),Zf)),n=$f(t),r=new e(n);return IT(),We=r,Gt=null,r})()),Gt)}async function hc(){if(We===null)return;let t=We;We=null,Gt=null,om(),await t.shutdown()}function MT(){return We!==null}function OT(){return We}function DT(){We=null,Gt=null,om()}var We,Gt,ws,zt=y(()=>{"use strict";lc();We=null,Gt=null,ws=!1});function sm(t,e){try{return Mf(t,e)}catch(n){return B("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function UT(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(zt(),qt));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function im(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??UT,o=null,s=t,i=null,a=null;try{let l=await gs(n,t,{headers:$T,redirect:"follow",signal:e.signal});i=l.status,s=l.url||t;let d=l.headers.get("content-type")??"";if(l.ok){if(NT.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await l.text();if(LT.test(d)&&!FT.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};o=sm(u,s)}}catch(l){if(e.signal.aborted||l instanceof Error&&l.message.startsWith("web_scrape markdown mode received binary"))throw l;a=l}if(!(o===null||o.textLength<Cf)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let l=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=sm(l.html,l.finalUrl);if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:l.finalUrl,usedRender:!0}}catch(l){if(e.signal.aborted)throw l;if(o===null){let d=l instanceof Error?l.message:String(l),u=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${t}: fetch failed (${u}) and render failed (${d}).`);throw p.cause=l,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 ${t} (HTTP ${i??"error"}).`)}var FT,LT,NT,$T,am=y(()=>{"use strict";Of();ac();de();FT=/(text\/html|application\/xhtml\+xml)/i,LT=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,NT=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,$T={"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 HT(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(BT,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),jT),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=Go(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function cm(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?HT({apiKey:t.exaApiKey,fetchFn:t.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 lm(t,e){if(e.length===0)return`# Search results for "${t}"
1057
1061
 
1058
1062
  (no results)`;let n=[`# Search results for "${t}"`,""];return e.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(`
1059
1063
  `).trimEnd()}var BT,jT,dm=y(()=>{"use strict";pn();BT="https://api.exa.ai/search",jT=10});function YT(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.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 e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=KT;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,WT)}let a=GT;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,qT)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function yc(t,e){let n=Buffer.from(t,"utf8");return n.byteLength<=e?t:n.subarray(0,e).toString("utf8")+zT}function XT(t){let e=[],n=t;for(let o=0;o<4&&n instanceof Error;o++)e.push(n.message),n=n.cause;let r=e.join(" | ");return JT.some(o=>r.includes(o))}function QT(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;return async(r,o)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=YT(r);if("error"in s)return{content:s.error,isError:!0};if(o.aborted){let d=o.reason;return{content:`web_scrape aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let i=new AbortController,a=()=>{i.abort(o.reason)},c,l=()=>{let d=i.signal.reason;return d instanceof Error?d.message:String(d??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),c=setTimeout(()=>{i.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.mode==="raw"){let u;try{u=await gs(e,s.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:i.signal})}catch(f){return i.signal.aborted?{content:`web_scrape aborted: ${l()}`,isError:!0}:{content:`web_scrape network error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}if(!u.ok)return{content:`web_scrape HTTP ${u.status} ${u.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let p;try{p=await u.text()}catch(f){return{content:`web_scrape read error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}return{content:yc(p,s.maxBytes)}}if(s.mode==="markdown")try{let u=await im(s.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:s.timeoutMs,signal:i.signal});return u.markdown.trim().length===0?{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0}:{content:yc(u.markdown,s.maxBytes)}}catch(u){if(i.signal.aborted)return{content:`web_scrape aborted: ${l()}`,isError:!0};let p=u instanceof Error?u.message:String(u),f=XT(u)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${p}${f}`,isError:!0}}let d=cm({exaApiKey:n.EXA_API_KEY,fetchFn:e});if("error"in d)return{content:d.error,isError:!0};try{let u=await d.search(s.query,{limit:VT,timeoutMs:s.timeoutMs,signal:i.signal});return{content:yc(lm(s.query,u),s.maxBytes)}}catch(u){return i.signal.aborted?{content:`web_scrape aborted: ${l()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${u instanceof Error?u.message:String(u)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),o.removeEventListener("abort",a)}}}var KT,WT,GT,qT,zT,VT,JT,um,pm=y(()=>{"use strict";am();dm();ac();KT=3e4,WT=12e4,GT=1e6,qT=1e7,zT=`
@@ -1161,7 +1165,7 @@ Arguments: ${o}`}
1161
1165
 
1162
1166
  ${n}`}}emitLoadTelemetry(e,n,r,o){let s=this.ctx.depth??0,i={...this.sessionIdentity(),requested_name:e,parent_session_id:this.ctx.parentSession.sessionId,depth:s,mode:"load",...o!==void 0?{model:o}:{}};re({event:"skill.dispatched",...i,...Dh(e)?{is_gate:!0}:{}}).catch(()=>{}),re({event:"skill.completed",status:"succeeded",duration_ms:r,content_chars:n,...i}).catch(()=>{})}executeLoadedRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let o=Date.now(),s;if(e.loadBody!==void 0)s=e.loadBody;else try{let c=ee(e.name)["system.md"];if(!c)return{content:`Skill "${e.name}" has context: "load" but no prompts/system.md found`,isError:!0};s=c}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(e.name,i.length,Date.now()-o,e.model),this.formatLoadedSkillResult(e.name,i,n)}executeLoadedPluginSkill(e,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(e,i.length,Date.now()-s,void 0),this.formatLoadedSkillResult(e,i,r)}substituteSkillArgs(e,n){let r=n??"";return e.replace(/\$ARGUMENTS?\b/g,()=>r)}async executePluginSkill(e,n,r,o,s,i=!1,a){if(s.signal.aborted)return{content:"Skill call aborted",isError:!0};let c=this.ctx.defaultSubagentModel??this.ctx.defaultModel??"sonnet",l=yr({childModel:c,resolved:this.ctx.resolveApiKeyForModel?this.ctx.resolveApiKeyForModel(c):et(c),parentApiKey:this.ctx.apiKey}),d=new q({parentAbortSignal:s.signal,apiKey:l,parentModel:c,...this.ctx.baseUrl!==void 0?{baseUrl:this.ctx.baseUrl}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},progressSink:Re(),...this.currentCwd!==void 0?{cwd:this.currentCwd}:{}}),u={model:c,systemPrompt:this.substituteSkillArgs(n,o),env:{PLUGIN_ROOT:r},isSkillDispatch:!0,...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{}},{childConfig:p,childManager:f}=this.buildForkedChildConfig(u,s.signal,i,a),h;try{h=await d.forkSubagent({parent:this.ctx.parentSession,config:p,idPrefix:`skill-${e}`,parentId:s.id,agentType:e});let g=o&&o.length>0?o:`Run the ${e} skill now, following the instructions in your system prompt.`,w=await h.runToResult(g);return w.status==="succeeded"&&w.message?{content:w.message.content}:w.status==="cancelled"&&typeof w.partialOutput=="string"&&w.partialOutput.length>0?{content:`[skill cancelled mid-flight \u2014 partial output preserved below]
1163
1167
 
1164
- ${w.partialOutput}`}:{content:w.error?.message??"Plugin skill failed with no output",isError:!0}}catch(g){return{content:`Plugin skill execution error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}finally{h&&await h.teardown().catch(B),await f?.teardownAll(),await d.teardownAll()}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=Sr(this.ctx.pluginConfigs)),this.pluginBodies.get(e)}createDispatchSkillCallback(e){return async(n,r)=>{let o={id:`${e.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:e.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}}});function br(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}function Nh(t={}){return({childExecutor:e,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??mP},subagentExecutor:e,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return V(typeof r=="string"?r:void 0)==="openai-compatible"?new he({...i,...t.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{},readOnlyMemory:!0}):new ye({...i,readOnlyMemory:!0})}}function Fh(t){let e={allowedTools:[...Xs]};return V(typeof t=="string"?t:void 0)==="openai-compatible"?new he({permissions:e,readOnlyBash:!0,readOnlyMemory:!0}):new ye({permissions:e,readOnlyBash:!0,readOnlyMemory:!0})}function $h(t,e,n,r,o,s,i,a,c,l){let d=(u,p,f)=>new Pn({parentSession:br(f),defaultModel:t,...l!==void 0?{defaultSubagentModel:l}:{},apiKey:e,...r!==void 0?{baseUrl:r}:{},depth:u,maxDepth:p,childProviderFactory:n,childSkillExecutorFactory:d,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...i!==void 0?{cwd:i}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...c!==void 0?{surface:c}:{}});return d}function Lh(t,e){let n={allowedTools:[...t]};return V(typeof e=="string"?e:void 0)==="openai-compatible"?new he({permissions:n}):new ye({permissions:n})}function Uh(t,e){let n={allowedTools:[...mh]};return V(typeof e=="string"?e:void 0)==="openai-compatible"?new he({permissions:n}):new ye({permissions:n})}var xn,mP,Xs,nl,Rn=y(()=>{"use strict";Qs();hr();Se();it();wt();qs();rl();xn=3;mP=[...st,...ve,"memory_search","agent","skill"],Xs=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...ve,"memory_search","agent","skill"],nl=new Set(["ground-state"])});var Zs,Bh=y(()=>{"use strict";de();$o();Bt();zo();ne();ke();Zs=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,h,g){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=c;this.parentInputStreamRef=l;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=h;this.onSubagentSucceeded=g;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;currentTrace=zs();lastStreamedContent="";get status(){return this.currentStatus}async run(e,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=No(this.streamToFinalMessage(e,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",Lt(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?(Lt(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(Lt(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(e,n){let r,o;this.lastStreamedContent="",this.currentTrace=zs();let s=n??this.progressSink??Re(),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(e)){if(s&&s(a,i),a.type==="chunk"){let c=a.chunk;c.type==="content"?this.lastStreamedContent+=c.content:c.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:c.toolUseId,name:c.toolName,inputBytes:Buffer.byteLength(c.toolInput,"utf8")}):c.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:c.toolUseId,isError:c.isError,truncated:c.truncated,sizeBytes:c.sizeBytes}):c.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 c=a.metadata.usage;this.currentTrace.usage={inputTokens:typeof c.input_tokens=="number"?c.input_tokens:void 0,outputTokens:typeof c.output_tokens=="number"?c.output_tokens:void 0,cacheReadTokens:typeof c.cache_read_input_tokens=="number"?c.cache_read_input_tokens:void 0,cacheCreationTokens:typeof c.cache_creation_input_tokens=="number"?c.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(e,n){try{let r=await this.run(e,n);return wh(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=el(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(e,n,r){let o;if(r){let s=this.progressSink??Re();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{B("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",Lt(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(e)}}async teardown(){if(this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async dispatchStopAndRelease(e){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await Np(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,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)B(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else try{this.parentInputStreamRef.pushUserMessage(n.injectContext)}catch(r){B(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}}});var gP,q,le=y(()=>{"use strict";tp();Oa();$o();zo();ne();rt();Bt();Rn();Js();Se();Bh();gP=async(t,e)=>({action:"decline"}),q=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentCwd;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentProvider=e.parentModel!==void 0?V(e.parentModel):void 0,this.parentCwd=e.cwd,this.parentTraceWriter=e.traceWriter,this.parentSurface=e.surface,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.abortGraph=new Oo(e.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),e.parentAbortSignal){let n=e.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(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}setOnSubagentSucceeded(e){this.onSubagentSucceededCb=e}setCwd(e){this.parentCwd=e}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){if(e.phaseRole!==void 0&&e.phaseRole!=="read-write"&&e.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${e.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=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry??e.parent.hookRegistry;o&&await Lp(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...e.config.traceWriter?{traceWriter:e.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...e.config,resume:r,forkSession:r?!0:e.config.forkSession,abortSignal:s.signal,apiKey:Eh({childModel:e.config.model,configApiKey:e.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:e.config.baseUrl??(V(e.config.model)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:e.config.isNonInteractive??!0,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...e.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...e.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...e.denyElicitations===!1?{}:{onElicitation:gP},...e.phaseRole==="read-only"?{provider:Uh("read-only",e.config.model)}:{}},a;try{a=new Nt(i)}catch(g){throw this.abortGraph.dispose(n),g}let c=e.parent.getInputStreamRef?.(),l=e.parent.abortSignal,d=this.progressSink??Re(),u=e.agentType?.trim()||void 0,p=e.parentId?.trim()||void 0,f=new Zs(n,a,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??Lo,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},c,l,u??e.idPrefix,d,p??e.parent.sessionId,e.config.traceWriter,this.onSubagentSucceededCb);this.active.set(n,f);let h=typeof e.config.model=="string"?e.config.model:JSON.stringify(e.config.model);return Lt(e.config.traceWriter,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:h,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await re({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,model:h,parent_session_id:e.parent.sessionId}),f}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}}});async function ei(t,e={}){let{failFast:n=!0,teardown:r=!0}=e;if(t.length===0)return[];let o=new Array(t.length),s=new Set(t.map((a,c)=>c)),i=t.map((a,c)=>a.handle.runToResult(a.prompt).then(l=>{if(o[c]=l,s.delete(c),n&&l.status!=="succeeded")for(let d of s){let u=t[d];u&&u.handle.status==="running"&&u.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(t.map(a=>a.handle.teardown())),o}var ol=y(()=>{"use strict"});import{fileURLToPath as hP}from"node:url";import{dirname as yP}from"node:path";var bP,M1,Yt,sl=y(()=>{"use strict";bP=hP(import.meta.url),M1=yP(bP),Yt={name:"research-agent",systemPrompt:`---
1168
+ ${w.partialOutput}`}:{content:w.error?.message??"Plugin skill failed with no output",isError:!0}}catch(g){return{content:`Plugin skill execution error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}finally{h&&await h.teardown().catch(B),await f?.teardownAll(),await d.teardownAll()}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=Sr(this.ctx.pluginConfigs)),this.pluginBodies.get(e)}createDispatchSkillCallback(e){return async(n,r)=>{let o={id:`${e.id}-dispatch-${n}`,name:"skill",input:{name:n,...r!==void 0?{arguments:r}:{}},signal:e.signal},s=await this.execute(o);if(s.isError)throw new Error(s.content);return s.content}}}});function br(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}function Nh(t={}){return({childExecutor:e,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??mP},subagentExecutor:e,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return V(typeof r=="string"?r:void 0)==="openai-compatible"?new he({...i,...t.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{},readOnlyMemory:!0}):new ye({...i,readOnlyMemory:!0})}}function Fh(t){let e={allowedTools:[...Xs]};return V(typeof t=="string"?t:void 0)==="openai-compatible"?new he({permissions:e,readOnlyBash:!0,readOnlyMemory:!0}):new ye({permissions:e,readOnlyBash:!0,readOnlyMemory:!0})}function $h(t,e,n,r,o,s,i,a,c,l){let d=(u,p,f)=>new Pn({parentSession:br(f),defaultModel:t,...l!==void 0?{defaultSubagentModel:l}:{},apiKey:e,...r!==void 0?{baseUrl:r}:{},depth:u,maxDepth:p,childProviderFactory:n,childSkillExecutorFactory:d,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...i!==void 0?{cwd:i}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...c!==void 0?{surface:c}:{}});return d}function Lh(t,e){let n={allowedTools:[...t]};return V(typeof e=="string"?e:void 0)==="openai-compatible"?new he({permissions:n}):new ye({permissions:n})}function Uh(t,e){let n={allowedTools:[...mh]};return V(typeof e=="string"?e:void 0)==="openai-compatible"?new he({permissions:n}):new ye({permissions:n})}var xn,mP,Xs,nl,Rn=y(()=>{"use strict";Qs();hr();Se();it();wt();qs();rl();xn=3;mP=[...st,...ve,"memory_search","agent","skill"],Xs=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...ve,"memory_search","agent","skill"],nl=new Set(["ground-state"])});var Zs,Bh=y(()=>{"use strict";de();$o();Bt();zo();ne();ke();Zs=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,h,g){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=c;this.parentInputStreamRef=l;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=h;this.onSubagentSucceeded=g;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;progressSink;parentId;currentTrace=zs();lastStreamedContent="";get status(){return this.currentStatus}async run(e,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=No(this.streamToFinalMessage(e,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",Lt(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?(Lt(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade"}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"):(Lt(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(e,n){let r,o;this.lastStreamedContent="",this.currentTrace=zs();let s=n??this.progressSink??Re(),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(e)){if(s&&s(a,i),a.type==="chunk"){let c=a.chunk;c.type==="content"?this.lastStreamedContent+=c.content:c.type==="tool_use_detail"?this.currentTrace.toolCalls.push({id:c.toolUseId,name:c.toolName,inputBytes:Buffer.byteLength(c.toolInput,"utf8")}):c.type==="tool_result"?this.currentTrace.toolResults.push({toolUseId:c.toolUseId,isError:c.isError,truncated:c.truncated,sizeBytes:c.sizeBytes}):c.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 c=a.metadata.usage;this.currentTrace.usage={inputTokens:typeof c.input_tokens=="number"?c.input_tokens:void 0,outputTokens:typeof c.output_tokens=="number"?c.output_tokens:void 0,cacheReadTokens:typeof c.cache_read_input_tokens=="number"?c.cache_read_input_tokens:void 0,cacheCreationTokens:typeof c.cache_creation_input_tokens=="number"?c.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(e,n){try{let r=await this.run(e,n);return wh(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace)}catch(r){let o=el(this.id,this.currentStatus,r,this.currentTrace);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(e,n,r){let o;if(r){let s=this.progressSink??Re();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{B("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async cancel(){if(this.currentStatus==="cancelled"||this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this.currentStatus="cancelled",Lt(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(e)}}async teardown(){if(this.stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(e)}}async dispatchStopAndRelease(e){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let n=await Np(this.hookRegistry,{event:"SubagentStop",subagentId:this.id,status:e,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)B(`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){B(`Failed to inject context from SubagentStop handler: ${String(r)}`)}this.onTerminal()}}});var gP,q,le=y(()=>{"use strict";tp();Oa();$o();zo();ne();rt();Bt();Rn();Js();Se();Bh();gP=async(t,e)=>({action:"decline"}),q=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentCwd;parentTraceWriter;parentSurface;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentProvider=e.parentModel!==void 0?V(e.parentModel):void 0,this.parentCwd=e.cwd,this.parentTraceWriter=e.traceWriter,this.parentSurface=e.surface,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.abortGraph=new Oo(e.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),e.parentAbortSignal){let n=e.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(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}setOnSubagentSucceeded(e){this.onSubagentSucceededCb=e}setCwd(e){this.parentCwd=e}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){if(e.phaseRole!==void 0&&e.phaseRole!=="read-write"&&e.config.provider!==void 0)throw new Error(`SubagentManager.forkSubagent: phaseRole "${e.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=`${e.idPrefix??"subagent"}-${Date.now()}-${++this.counter}`,r=e.parent.sessionId,o=e.config.hookRegistry??this.hookRegistry??e.parent.hookRegistry;o&&await Lp(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...e.config.traceWriter?{traceWriter:e.config.traceWriter}:{}});let s=new AbortController;this.abortGraph.register(n,s),this.abortGraph.linkChild(this.rootId,n);let i={...e.config,resume:r,forkSession:r?!0:e.config.forkSession,abortSignal:s.signal,apiKey:Eh({childModel:e.config.model,configApiKey:e.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:e.config.baseUrl??(V(e.config.model)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:e.config.isNonInteractive??!0,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&this.parentCwd!==void 0?{cwd:this.parentCwd}:{},...e.config.traceWriter===void 0&&this.parentTraceWriter!==void 0?{traceWriter:this.parentTraceWriter}:{},...e.config.surface===void 0&&this.parentSurface!==void 0?{surface:this.parentSurface}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(this.parentCanUseTool!==void 0&&e.config.canUseTool===void 0?{canUseTool:this.parentCanUseTool}:void 0),...e.denyElicitations===!1?{}:{onElicitation:gP},...e.phaseRole==="read-only"?{provider:Uh("read-only",e.config.model)}:{}},a;try{a=new Nt(i)}catch(g){throw this.abortGraph.dispose(n),g}let c=e.parent.getInputStreamRef?.(),l=e.parent.abortSignal,d=this.progressSink??Re(),u=e.agentType?.trim()||void 0,p=e.parentId?.trim()||void 0,f=new Zs(n,a,s,this.abortGraph,e.outputSchema,e.config.timeoutMs??Lo,o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},c,l,u??e.idPrefix,d,p??e.parent.sessionId,e.config.traceWriter,this.onSubagentSucceededCb);this.active.set(n,f);let h=typeof e.config.model=="string"?e.config.model:JSON.stringify(e.config.model);return Lt(e.config.traceWriter,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:h,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{}}),await re({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,model:h,parent_session_id:e.parent.sessionId}),f}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}}});async function ei(t,e={}){let{failFast:n=!0,teardown:r=!0}=e;if(t.length===0)return[];let o=new Array(t.length),s=new Set(t.map((a,c)=>c)),i=t.map((a,c)=>a.handle.runToResult(a.prompt).then(l=>{if(o[c]=l,s.delete(c),n&&l.status!=="succeeded")for(let d of s){let u=t[d];u&&u.handle.status==="running"&&u.handle.cancel().catch(()=>{})}}));return await Promise.all(i),r&&await Promise.allSettled(t.map(a=>a.handle.teardown())),o}var ol=y(()=>{"use strict"});import{fileURLToPath as hP}from"node:url";import{dirname as yP}from"node:path";var bP,M1,Yt,sl=y(()=>{"use strict";bP=hP(import.meta.url),M1=yP(bP),Yt={name:"research-agent",systemPrompt:`---
1165
1169
  name: research-agent
1166
1170
  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.
1167
1171
  model: sonnet
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-afk",
3
- "version": "5.15.12",
3
+ "version": "5.15.13",
4
4
  "description": "Open-source coding-agent harness you can actually change — own the loop (prompts, gates, routing, skills, terminal states), use any model, run long tasks while you're away.",
5
5
  "main": "dist/index.mjs",
6
6
  "types": "dist/index.d.ts",