agent-afk 5.81.4 → 5.81.6

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
@@ -805,13 +805,13 @@ ${t}`:e:[{type:"text",text:e},...t]}var Oi,Oh=b(()=>{"use strict";Pd();Md();fe()
805
805
  `);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 FC(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 LC(t){let e=t.isError===!0?null:ly(t.toolName,t.content),n=e!==null?{display:e}:{},r=typeof t.batchIndex=="number"&&typeof t.batchSize=="number"?{batchIndex:t.batchIndex,batchSize:t.batchSize}:{},o=MC(t.content);if(o)return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:`Output persisted (${o.sizeLabel}) \u2192 ${o.absolutePath}`,isError:t.isError===!0,persistedPath:o.absolutePath,sizeBytes:o.sizeBytes,sizeLabel:o.sizeLabel,...n,...r}};let{content:s,lineCount:i,sizeBytes:a,sizeLabel:l}=DC(t.content);return{type:"chunk",chunk:{type:"tool_result",toolUseId:t.toolUseId,content:s,isError:t.isError===!0,sizeBytes:a,sizeLabel:l,...t.truncated===!0&&{truncated:!0},...i!==void 0&&{lineCount:i},...n,...r}}}function Nd(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 t.isError!==!0&&t.toolName&&(e._successfulToolNames??=[]).push(t.toolName),LC(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=FC(t.usage,t.sessionId??e.getSessionMetadata().sessionId);e._successfulToolNames!==void 0&&e._successfulToolNames.length>0&&(n.successfulToolNames=[...e._successfulToolNames]),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)){xg(e.traceWriter,{kind:"monetary",runningCostUsd:e._runningCostUsd,maxBudgetUsd:e.maxBudgetUsd,lastTurnCostUsd:n.totalCostUsd});let r=new Wn(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"};case"rate_limit":return{type:"rate_limit",...t.retryAfterMs!==void 0?{retryAfterMs:t.retryAfterMs}:{}};default:return null}}var dy=b(()=>{"use strict";le();ne();cy()});import{stat as NC,readFile as $C,writeFile as UC,rename as BC,unlink as HC}from"node:fs/promises";async function fy(t,{maxBytes:e,keepTailLines:n}){let r={trimmed:!1,removedLines:0},o;try{if((await NC(t)).size<=e)return r;let a=(await $C(t,"utf8")).split(`
806
806
  `);if(a.length>0&&a[a.length-1]===""&&a.pop(),a.length<=n)return r;let l=a.slice(a.length-n),c=a.length-l.length;return o=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,8)}`,await UC(o,l.join(`
807
807
  `)+`
808
- `,{mode:384}),await BC(o,t),o=void 0,{trimmed:!0,removedLines:c}}catch{if(o!==void 0)try{await HC(o)}catch{}return r}}var uy,py,my=b(()=>{"use strict";uy=5*1024*1024,py=5e3});import{z as jC}from"zod";var bn,gy=b(()=>{"use strict";fe();le();ne();Se();Oh();_e();Dd();Nh();le();Kh();Fd();Pd();Vh();Yh();Ke();$t();mn();We();Md();Zh();ey();dy();z();my();bn=class{config;planExit=new Hi;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=new Bi;constructor(e){this.config=e.parentSessionId===void 0&&e.planExitControls===void 0?{...e,planExitControls:{setPermissionMode:r=>this.setPermissionMode(r),requestImplementSeed:(r,o)=>this.planExit.requestImplementSeed(r,o),getPrePlanMode:()=>this.planExit.getPrePlanMode()}}:e,this.abortController=new AbortController,this._hookRegistry=e.hookRegistry,Xh(e.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(e.model);Y(e.traceWriter,{phase:"session_init_start",model:n,resolvedModel:be(e.model)??n,origin:Nt(e.surface),actor:zs(e.parentSessionId)}),this.initSdkLifecycle(),this.config.parentSessionId===void 0&&fy(Fs(),{maxBytes:uy,keepTailLines:py})}initSdkLifecycle(){this.config.models&&ci(this.config.models),Mi(this.config);let e=be(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=Qh(this.config,e);this.stateManager=new ji(n,r),this.inputStream=new rr(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)U(`\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{U("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>hy(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new Oi({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>X(a),resolveApiKey:a=>oe(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{let e=await Fh(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId,parentSessionId:this.config.parentSessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});for(e&&this.config.parentSessionId===void 0&&this.queueFrameworkContext(e);;){let n=await this.providerIterator.next();if(n.done){this.stateManager.resolveInitializationIfNeeded();return}let r=n.value,o=Nd(r,this.buildTransformDeps());if(r.type==="session.init"){await Y(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(o&&o.type==="error"){this.sawProviderError=!0;return}}}catch(e){let n=e instanceof Error?e:new Error(String(e));n instanceof Z&&(this.hookBlocked=!0),this.stateManager.isInitializationSettled()||this.stateManager.rejectInitializationOnce(n),await this.dispatchSessionEndOnce("error").catch(()=>{})}}buildTransformDeps(){return{_successfulToolNames:[],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??Dh,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 Di(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(jC.toJSONSchema(n,{target:"openapi-3.0"}))+"\n```":"",l="";for(let c=0;c<=o;c++){let d=c===0?e+a:`Your previous response did not match the required JSON schema.
808
+ `,{mode:384}),await BC(o,t),o=void 0,{trimmed:!0,removedLines:c}}catch{if(o!==void 0)try{await HC(o)}catch{}return r}}var uy,py,my=b(()=>{"use strict";uy=5*1024*1024,py=5e3});import{z as jC}from"zod";var bn,gy=b(()=>{"use strict";fe();le();ne();Se();Oh();_e();Dd();Nh();le();Kh();Fd();Pd();Vh();Yh();Ke();$t();mn();We();Md();Zh();ey();dy();z();my();bn=class t{static claimedTraceWriters=new WeakSet;config;planExit=new Hi;currentState="idle";providerQuery;providerIterator;conversationHistory=[];turnCount=0;pendingFrameworkContext=[];lastResponseMetadata=null;initPromise=null;inputStream;abortController;_hookRegistry;sessionEndDispatched=!1;ownsTraceSeal;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=new Bi;constructor(e){this.ownsTraceSeal=e.traceWriter!==void 0&&e.isSubagentFork!==!0&&!t.claimedTraceWriters.has(e.traceWriter),this.ownsTraceSeal&&t.claimedTraceWriters.add(e.traceWriter),this.config=e.parentSessionId===void 0&&e.planExitControls===void 0?{...e,planExitControls:{setPermissionMode:r=>this.setPermissionMode(r),requestImplementSeed:(r,o)=>this.planExit.requestImplementSeed(r,o),getPrePlanMode:()=>this.planExit.getPrePlanMode()}}:e,this.abortController=new AbortController,this._hookRegistry=e.hookRegistry,Xh(e.abortSignal,this.abortController,()=>{this.onAbort()});let n=String(e.model);Y(e.traceWriter,{phase:"session_init_start",model:n,resolvedModel:be(e.model)??n,origin:Nt(e.surface),actor:zs(e.parentSessionId)}),this.initSdkLifecycle(),this.config.parentSessionId===void 0&&fy(Fs(),{maxBytes:uy,keepTailLines:py})}initSdkLifecycle(){this.config.models&&ci(this.config.models),Mi(this.config);let e=be(this.config.model)??this.config.model,{sessionIdentity:n,metadata:r}=Qh(this.config,e);this.stateManager=new ji(n,r),this.inputStream=new rr(()=>this.sessionId);let o=this.inputStream.createIterable();if(this.config.provider)U(`\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{U("\u{1F7E2} AgentSession: Creating query session via ProviderRouter");let i=this.config.providerFactory?this.config.providerFactory:a=>hy(a,void 0,{customTools:this.config.customTools,canUseTool:this.config.canUseTool});this.providerQuery=new Oi({prompt:o,config:this.config},{resolveProvider:i,providerNameForModel:a=>X(a),resolveApiKey:a=>oe(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{let e=await Fh(this._hookRegistry,{event:"SessionStart",sessionId:this.sessionId,parentSessionId:this.config.parentSessionId},{signal:this.abortController.signal,...this.config.traceWriter?{traceWriter:this.config.traceWriter}:{}});for(e&&this.config.parentSessionId===void 0&&this.queueFrameworkContext(e);;){let n=await this.providerIterator.next();if(n.done){this.stateManager.resolveInitializationIfNeeded();return}let r=n.value,o=Nd(r,this.buildTransformDeps());if(r.type==="session.init"){await Y(this.config.traceWriter,{phase:"session_init_done",durationMs:Date.now()-this.sessionStartedAt});return}if(o&&o.type==="error"){this.sawProviderError=!0;return}}}catch(e){let n=e instanceof Error?e:new Error(String(e));n instanceof Z&&(this.hookBlocked=!0),this.stateManager.isInitializationSettled()||this.stateManager.rejectInitializationOnce(n),await this.dispatchSessionEndOnce("error").catch(()=>{})}}buildTransformDeps(){return{_successfulToolNames:[],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??Dh,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 Di(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(jC.toJSONSchema(n,{target:"openapi-3.0"}))+"\n```":"",l="";for(let c=0;c<=o;c++){let d=c===0?e+a:`Your previous response did not match the required JSON schema.
809
809
  Validation error: ${l}
810
810
  Respond again with ONLY a JSON object (optionally in a \`\`\`json fence) that satisfies the schema.`+a,u=await this.sendMessage(d,i),p=Li(u.content),f=n.safeParse(p);if(f.success)return f.data;l=f.error.message}throw new Error(`structured output did not match schema after ${o+1} attempt(s): ${l}`)}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,this.planExit.clearModeBeforeDefault();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,l=Nd(a,s);if(l&&(l.type==="done"?(this.turnCount++,this.sawProviderError=!1):l.type==="error"&&(this.sawProviderError=!0),this.ledger.recordEvent(l),yield l,l.type==="done"||l.type==="error"))break}}finally{this.currentState==="streaming"&&(this.currentState="idle")}}ensureLedger(){this.ledger.ensure({depth:this.config.depth,parentSessionId:this.config.parentSessionId,sessionId:this.sessionId,fallbackModel:String(this.config.model),tracePath:this.config.traceWriter?.getTracePath(),getMetadata:()=>this.getSessionMetadata()})}recordLedgerElicitation(e,n){this.ledger.recordElicitation(e,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 Ne("Cannot reset: session aborted");if(this.currentState==="processing"||this.currentState==="streaming")try{await this.providerQuery.interrupt()}catch{}await this.dispatchSessionEndOnce("reset"),await this.ledger.seal("reset");try{await this.providerQuery.close()}catch{}await this.providerIterator.return?.(),this.initPromise&&await Promise.race([this.initPromise,new Promise(e=>setTimeout(e,Od))]).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.ledger.seal("abort");try{await this.providerQuery.interrupt()}catch{}}async setModel(e){let n=be(e);typeof e=="string"&&e.length>0&&await this.providerQuery.setModel(e),n&&this.stateManager.setSessionMetadata(r=>({...r,model:n}))}async setPermissionMode(e){let n=this.stateManager.getSessionMetadata().permissionMode;this.planExit.recordModeTransition(e,n),await this.providerQuery.setPermissionMode(e),this.stateManager.setSessionMetadata(r=>({...r,permissionMode:e}))}getPrePlanMode(){return this.planExit.getPrePlanMode()}async takePendingPlanExitSeed(){let e=this.planExit.takeSeed();if(e!==void 0){try{await this.setPermissionMode(e.mode)}catch(n){U(`\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{message:e.message,mode:e.mode}}}setCwd(e){this.config={...this.config,cwd:e},this.providerQuery.setCwd?.(e),this.config.sessionId!==void 0&&Eh(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"}}listRewindTargets(){return this.currentState==="closed"?[]:this.providerQuery.listRewindTargets?.()??[]}async rewindConversation(e){if(this.currentState==="closed")throw new Error("Cannot rewind: session is closed");if(this.currentState!=="idle")return{rewound:!1,reason:"session-busy",messagesBefore:0,messagesAfter:0};let n=this.providerQuery.rewindConversation?.bind(this.providerQuery);return n?n(e):{rewound:!1,reason:"not-supported",messagesBefore:0,messagesAfter:0}}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),U(`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(`
811
811
 
812
812
  `);return this.pendingFrameworkContext=[],typeof e=="string"?`${n}
813
813
 
814
- ${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.ledger.seal("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,Od))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){if(this.sessionEndDispatched)return;this.sessionEndDispatched=!0;let n=this.closureSignals(e);await jh(this.config.traceWriter,{...n,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,runningTokens:this.sessionRunningTokens}).catch(()=>{}),this.config.subagentToolOutputCapBytes===void 0&&await Wh(this.config.traceWriter,{...n,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,subagentCompletedCount:this.subagentCompletedCount,subagentRunningTokens:this.subagentRunningTokens,subagentRunningCostUsd:this.subagentRunningCostUsd}).catch(()=>{}),await Lh(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}:{})}closureSignals(e){return{dispatchReason:e,signal:this.abortController.signal,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,lastStopReason:this.lastStopReason,sawProviderError:this.sawProviderError}}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)}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new Ne("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 $d=b(()=>{"use strict";gy()});function WC(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new wn(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 KC(t){return t.continue===!1||t.decision==="block"}function Ud(t,e){if(t?.aborted){let n=t.reason,r=`aborted during ${e}${n?`: ${String(n)}`:""}`;throw new Ne(r)}}function yy(){return new Bd}var Sn,wn,Bd,Wi=b(()=>{"use strict";le();Sn=3e4;wn=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"},Bd=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=Sn){Ud(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){Ud(n,e.event);let l;try{let d=a.handler(e,n);l=!a.options.longRunning&&r>0&&Number.isFinite(r)?await WC(d,r,e.event):await d}catch(d){throw d instanceof wn?d:new Z(`hook handler threw during ${e.event}`,e.event,d instanceof Error?d.message:String(d),{cause:d})}if(Ud(n,e.event),KC(l))throw new Z(`hook handler blocked ${e.event}${l.reason?`: ${l.reason}`:""}`,e.event,l.reason);let c=[i.injectContext,l.injectContext].filter(d=>typeof d=="string"&&d.length>0).join(`
814
+ ${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.ledger.seal("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,Od))])}catch{}await this.dispatchSessionEndOnce("close")}}async dispatchSessionEndOnce(e){if(this.sessionEndDispatched)return;this.sessionEndDispatched=!0;let n=this.closureSignals(e);await jh(this.config.traceWriter,{...n,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,runningTokens:this.sessionRunningTokens}).catch(()=>{}),this.ownsTraceSeal&&await Wh(this.config.traceWriter,{...n,finalTurnCount:this.turnCount,finalCostUsd:this.sessionRunningCostUsd,subagentCompletedCount:this.subagentCompletedCount,subagentRunningTokens:this.subagentRunningTokens,subagentRunningCostUsd:this.subagentRunningCostUsd}).catch(()=>{}),await Lh(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}:{})}closureSignals(e){return{dispatchReason:e,signal:this.abortController.signal,maxTurnsHit:this.maxTurnsHit,hookBlocked:this.hookBlocked,lastStopReason:this.lastStopReason,sawProviderError:this.sawProviderError}}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)}assertCanSend(){if(this.currentState==="closed")throw new Error("Cannot send message: session is closed");if(this.abortController.signal.aborted)throw new Ne("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 $d=b(()=>{"use strict";gy()});function WC(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new wn(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 KC(t){return t.continue===!1||t.decision==="block"}function Ud(t,e){if(t?.aborted){let n=t.reason,r=`aborted during ${e}${n?`: ${String(n)}`:""}`;throw new Ne(r)}}function yy(){return new Bd}var Sn,wn,Bd,Wi=b(()=>{"use strict";le();Sn=3e4;wn=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"},Bd=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=Sn){Ud(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){Ud(n,e.event);let l;try{let d=a.handler(e,n);l=!a.options.longRunning&&r>0&&Number.isFinite(r)?await WC(d,r,e.event):await d}catch(d){throw d instanceof wn?d:new Z(`hook handler threw during ${e.event}`,e.event,d instanceof Error?d.message:String(d),{cause:d})}if(Ud(n,e.event),KC(l))throw new Z(`hook handler blocked ${e.event}${l.reason?`: ${l.reason}`:""}`,e.event,l.reason);let c=[i.injectContext,l.injectContext].filter(d=>typeof d=="string"&&d.length>0).join(`
815
815
  `);i={...i,...l,...c.length>0?{injectContext:c}:{}}}return i}}});async function pt(t,e,n,r){if(!t)return;if(r.kind==="blocked"){await Xe(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 Xe(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 by(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await pt(n.traceWriter,"SubagentStart",{},{kind:"decision",decision:r})}catch(r){throw r instanceof Z&&await pt(n.traceWriter,"SubagentStart",{},{kind:"blocked",err:r}),r}}function GC(t,e,n){return new Promise((r,o)=>{let s=!1,i=setTimeout(()=>{s||(s=!0,o(new wn(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 wy(t,e,n={}){if(!t)return{};try{let r=await GC(t.dispatch(e,n.signal,Sn),Sn,"SubagentStop");return await pt(n.traceWriter,"SubagentStop",{},{kind:"decision",decision:r}),r}catch(r){return r instanceof wn?(console.warn(`[afk] SubagentStop hook timed out after ${Sn}ms (subagentId=${e.subagentId}): ${r.message}`),n.onError?.(r),{}):(r instanceof Z&&await pt(n.traceWriter,"SubagentStop",{},{kind:"blocked",err:r}),r instanceof Z||r instanceof Ne?(U(`SubagentStop hook swallowed ${r.name}: ${r.message}`),n.onError?.(r),{}):(U(`SubagentStop hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r))),{}))}}async function Hd(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await pt(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){throw r instanceof Z&&await pt(n.traceWriter,"PreToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r}}async function Sy(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await pt(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof Z&&await pt(n.traceWriter,"PostToolUse",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof Z||r instanceof Ne){U(`PostToolUse hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}U(`PostToolUse hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}async function vy(t,e,n={}){if(t)try{let r=await t.dispatch(e,n.signal);await pt(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"decision",decision:r})}catch(r){if(r instanceof Z&&await pt(n.traceWriter,"PostToolUseFailure",{toolName:e.toolName},{kind:"blocked",err:r}),r instanceof Z||r instanceof Ne){U(`PostToolUseFailure hook swallowed ${r.name}: ${r.message}`),n.onError?.(r);return}U(`PostToolUseFailure hook unexpected error: ${String(r)}`),n.onError?.(r instanceof Error?r:new Error(String(r)))}}var Ki=b(()=>{"use strict";fe();le();Wi();ne()});import{mkdir as qC,writeFile as zC}from"fs/promises";import{dirname as JC,join as VC}from"path";function YC(){return VC(wt(),"routing-decisions.jsonl")}function XC(t){let e={surface:"afk"};for(let[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}async function ie(t){if(!(_.VITEST||_.NODE_ENV==="test"))try{let e=YC();await qC(JC(e),{recursive:!0});let n=new Date().toISOString().split(".")[0]+"Z",r=JSON.stringify({ts:n,...XC(t)})+`
816
816
  `;await zC(e,r,{flag:"a"})}catch{}}var ft=b(()=>{"use strict";K();z()});import{AsyncLocalStorage as QC}from"node:async_hooks";function _y(t,e){return ky.run(t,e)}function Qe(){return ky.getStore()}var ky,vn=b(()=>{"use strict";ky=new QC});import{promises as Ay}from"node:fs";import{join as ZC,resolve as eI,sep as Wd}from"node:path";function fo(t){let e=eI(t),n=e.indexOf(jd);if(n===-1)return;let o=e.slice(n+jd.length).split(Wd)[0];if(o)return e.slice(0,n+jd.length)+o}async function Ey(t){let e=fo(t);if(e===void 0)return;let n=ZC(e,tI);try{let r={};try{r=JSON.parse(await Ay.readFile(n,"utf-8"))}catch{r={owner:"agent"}}r.pid=process.pid,r.createdAt=new Date().toISOString(),await Ay.writeFile(n,JSON.stringify(r,null,2),"utf-8")}catch{}}var tI,jd,Kd=b(()=>{"use strict";tI=".afk-worktree-meta.json",jd=`${Wd}.afk-worktrees${Wd}`});import{execFile as nI}from"node:child_process";import{promisify as rI}from"node:util";import Wt from"node:path";function iI(t){let e=Wt.resolve(t),n=`${Wt.sep}.afk-worktrees${Wt.sep}`,r=e.indexOf(n);if(!(r<=0))return e.slice(0,r)}async function Ty(t,e=sI){if(!(t===void 0||t===""))try{let{stdout:n}=await e("git",["-C",t,"rev-parse","--git-common-dir","--show-toplevel"]),r=n.split(`
817
817
  `).map(c=>c.trim()),o=r[0],s=r[1];if(!o||!s)return;let i=Wt.isAbsolute(o)?o:Wt.resolve(t,o),a=Wt.resolve(Wt.dirname(i)),l=Wt.resolve(s);return a===l?void 0:a}catch(n){let r=iI(t);if(r!==void 0)return U(`[worktree-read-root] git rev-parse failed for cwd=${t}; recovered main root lexically as ${r} (afk worktree layout) \u2014 ${n instanceof Error?n.message:String(n)}`),r;U(`[worktree-read-root] git rev-parse failed for cwd=${t}; child confined to worktree only \u2014 ${n instanceof Error?n.message:String(n)}`);return}}var oI,sI,xy=b(()=>{"use strict";fe();oI=rI(nI),sI=(t,e)=>oI(t,e)});import kn from"path";function aI(t){let e=kn.resolve(t??process.cwd());return kn.parse(e).root||kn.sep}function Kt(t,e){if(t!==void 0)return mo({parentReadRoots:t.parentReadRoots,parentCwd:t.parentCwd,childCwd:e})}function mo(t){let{parentReadRoots:e,parentCwd:n,childCwd:r,worktreeMainRoot:o,afkStateRoot:s}=t,i=r!==void 0&&r!==""?kn.resolve(r):void 0;if(e===void 0&&n===void 0)return i!==void 0?[aI(i)]:void 0;let a=e??(n!==void 0?[n]:[]),l=new Set;i!==void 0&&l.add(i);for(let c of a)c!==void 0&&c!==""&&l.add(kn.resolve(c));if(o!==void 0&&o!==""&&l.add(kn.resolve(o)),s!==void 0&&s!==""&&l.add(kn.resolve(s)),l.size!==0&&!(l.size===1&&i!==void 0&&l.has(i)))return[...l]}var _n=b(()=>{"use strict"});function Ry(){return yy()}function Gi(t,e){return t??e}var qi=b(()=>{"use strict";Wi()});function Gd(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 zi(t,e){return Cy(t,e)}function Ji(t,e){return Cy(t,e)}function Cy(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 Vi=b(()=>{"use strict"});async function ar(t,e,n){let r=new Array(t.length),o=Math.min(Math.max(1,Math.floor(e)),t.length),s=0,i=[];for(let a=0;a<o;a++)i.push((async()=>{for(;s<t.length;){let l=s++;try{r[l]={status:"fulfilled",value:await n(t[l])}}catch(c){r[l]={status:"rejected",reason:c}}}})());return await Promise.all(i),r}var Yi=b(()=>{"use strict"});function NI(t){return t.replace(/'[^']*'/g," ").replace(/"(?:[^"\\]|\\.)*"/g,e=>/\$\(|`/.test(e)?e:" ")}function qd(t){return(t.split("/").pop()??t).replace(/^\\+/,"")}function Py(t){let e=[],n=[],r=[],o="",s=!1,i=()=>{s&&(r.push(o),o="",s=!1)},a=()=>{i(),r.length>0&&(e.push(r),r=[])},l=u=>{let p=u,f=1,m="";for(;p<t.length&&f>0;){let g=t[p];if(g==="(")f++;else if(g===")"&&(f--,f===0)){p++;break}m+=g,p++}return n.push(m),p},c=0,d=t.length;for(;c<d;){let u=t[c];if(u==="'"){for(s=!0,c++;c<d&&t[c]!=="'";)o+=t[c],c++;c++;continue}if(u==='"'){for(s=!0,c++;c<d&&t[c]!=='"';)if(t[c]==="$"&&t[c+1]==="(")c=l(c+2);else if(t[c]==="`"){c++;let p="";for(;c<d&&t[c]!=="`";)p+=t[c],c++;c++,n.push(p)}else o+=t[c],c++;c++;continue}if(u==="`"){i(),c++;let p="";for(;c<d&&t[c]!=="`";)p+=t[c],c++;c++,n.push(p);continue}if(u==="$"&&t[c+1]==="("){i(),c=l(c+2);continue}if(u===";"||u===`
@@ -857,7 +857,7 @@ Remedy: these paths are outside the fork's granted read roots. Re-dispatch with
857
857
 
858
858
  `).trim()}function QM(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}async function bb(t,e){let{JSDOM:n,Readability:r,turndown:o}=await XM(),i=new n(t,{url:e}).window.document,a=(i.title??"").trim(),l=(()=>{try{let p=i.cloneNode(!0);return new r(p).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let p=yb(o.turndown(l.content)),f=(l.title??"").trim()||a,m=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:p,textLength:m,usedFallback:!1}}let c=i.body,d=c?.innerHTML??"",u=yb(o.turndown(d));return{title:a,markdown:u,textLength:QM(c),usedFallback:!0}}var gu,wb=b(()=>{"use strict";gu=null});function eO(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 Sb(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function tO(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 da(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??eO,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await t(e,n);if(!ZM.has(u.status)||d===o)return u;let p=tO(u,i)??Sb(d,s,i);U("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let p=Sb(d,s,i);U("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var ZM,hu=b(()=>{"use strict";fe();ZM=new Set([429,502,503,504])});import{readFileSync as nO}from"node:fs";import{join as rO}from"path";function oO(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function vb(t,e){return oO(e).test(t)}function aO(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(sO.has(e))return!0;if(iO.has(e))return!1}return!1}function kb(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function lO(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 _b(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Mc(e),e}function cO(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function dO(t){try{return nO(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function uO(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=_b(e.defaultProfile)),n}function Ab(t){let e=t?.env??_,n=t?.readFileSync??dO,r=t?.surface??e.AGENT_SURFACE,o=aO(e.AFK_BROWSER_HEADLESS,r),s=kb(e.AFK_BROWSER_ALLOWED_DOMAINS),i=kb(e.AFK_BROWSER_BLOCKED_DOMAINS),a=cO(e.AFK_BROWSER_DOM_SNAPSHOTS),l=lO(e.AFK_BROWSER_BACKEND),c=_b(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():rO(St(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=uO(d,m);return g.configPath=p,g}function yu(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(vb(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>vb(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var sO,iO,bu=b(()=>{"use strict";K();z();sO=new Set(["daemon","subagent","telegram","afk"]),iO=new Set(["repl","interactive","cli"])});import{existsSync as pO,readFileSync as fO}from"node:fs";import{createRequire as mO}from"node:module";import{dirname as gO,join as hO}from"node:path";function xb(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<bO&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function Ce(t){let e=xb(t);return Tb.some(n=>e.includes(n))}function wO(){try{let e=mO(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(fO(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=hO(gO(e),o);return pO(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function _o(){return Eb??=wO()??yO,Eb}function wu(t){return t.includes("install chromium")}function Ve(t,e){if(xb(t).includes("Executable doesn't exist")){let r="";return e?.headless===!0?r=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(r=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${_o()}.${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${_o()}). Or pick a different tool.`}function Su(t,e){if(!Ce(t))return t;let n=t instanceof Error?t.message:String(t);return new Error(`${n}
859
859
 
860
- ${Ve(t,{headless:e})}`,{cause:t})}var Tb,yO,bO,Eb,vu=b(()=>{"use strict";Tb=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],yO="pnpm exec playwright install chromium",bO=4});import Rn from"node:fs";import ua from"node:path";import{randomBytes as SO}from"node:crypto";import{chromium as vO}from"playwright";function kO(){try{return"5.81.4"}catch{}try{let t=ua.resolve(import.meta.dirname,"../../../package.json"),e=Rn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var _O,pa,Rb=b(()=>{"use strict";vu();z();fe();_O=kO(),pa=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=vO.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,Su(e,this.config.headless)}),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}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,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/${_O}`}}loadStorageState(e){let n=Oc(e);try{if(!Rn.existsSync(n))return;let r=JSON.parse(Rn.readFileSync(n,"utf8"));return U("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){U("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Oc(e);if(!Rn.existsSync(r))return;let o=await n.storageState(),s=ua.join(ua.dirname(r),`.${ua.basename(r)}.${process.pid}.${SO(4).toString("hex")}.tmp`);Rn.writeFileSync(s,JSON.stringify(o),{mode:384}),Rn.chmodSync(s,384),Rn.renameSync(s,r),U("[browser/vault] saved session",{profile:e,file:r})}catch(r){U("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as AO}from"crypto";function Cb(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&EO.test(t.label))}function Ib(t){return AO("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Pb(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var EO,fa=b(()=>{"use strict";EO=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as TO}from"node:crypto";function xO(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function RO(t,e,n){return`el_${TO("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function CO(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Mb(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Db(t,e){let n=t.role??"",r=t.name??"";Ob.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Db(s,e)}async function IO(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Fb).catch(()=>[])}async function PO(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},Fb).catch(()=>[])}function MO(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function ma(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=MO(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=IO(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,w=!1;u!==null?(h=[],Db(u,h)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,h=(await PO(t)).filter(N=>Ob.has(N.role??"")));let v=new Map;for(let I of p){let N=Mb(I.name),j=v.get(N);(!j||j.bbox.w===0&&I.bbox.w>0)&&v.set(N,I)}let E=h.map(I=>({ax:I,dom:v.get(Mb(I.name??""))})),k=r?E:E.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,N)=>{let j=I.dom?.bbox.y??0,C=N.dom?.bbox.y??0;if(j!==C)return j-C;let $=I.dom?.bbox.x??0,O=N.dom?.bbox.x??0;return $-O}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,N)=>{let j=I.ax.role??"generic",C=I.ax.name??"",$=RO(j,C,N),O=I.dom?.bbox??{x:0,y:0,w:0,h:0},M=I.dom?.type??null,D=null;I.ax.value!==void 0&&I.ax.value!==null&&(D=String(I.ax.value)),I.ax.checked!==void 0&&(D=String(I.ax.checked)),Cb({role:j,kind:M})&&(D="[redacted]");let H={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(H.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(H.selected=I.ax.selected),I.ax.expanded!==void 0&&(H.expanded=I.ax.expanded);let L;I.dom?.testId?L=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(L=`#${I.dom.id}`);let B={id:$,role:j,label:xO(C),kind:M,value:D,state:H,bbox:O};return L!==void 0&&(B.selector=L),B}),R="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?R="loading":I==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let S=CO(f),x=`obs_${e.observationCounter.toString(36)}`,P=new Date().toISOString();return{observationId:x,url:m,title:g,textSummary:S,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:P}}var Ob,Fb,Lb=b(()=>{"use strict";fa();Ob=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Fb="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Nb(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${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 ku(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Nb(t,s)))).filter(o=>o!==null)}async function OO(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function _u(t,e,n){switch(e.kind){case"element_id":return DO(t,e,n);case"selector":return FO(t,e);case"semantic":return LO(t,e)}}async function DO(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 ku(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function FO(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 ku(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function LO(t,e){return e.role!==void 0?NO(t,e.text,e.role):$O(t,e.text,e)}async function NO(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 ku(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function $O(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await OO(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 h=p[g];if(h===void 0)continue;let w=await Nb(h.locator,h.index);if(w!==null){let v=`${w.role}:${w.label}:${g}`,E=0;for(let k=0;k<v.length;k++)E=E*31+v.charCodeAt(k)>>>0;f.push({...w,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var $b=b(()=>{"use strict"});import{randomBytes as UO}from"crypto";import{mkdir as BO,stat as HO,writeFile as jO}from"fs/promises";import{join as Au}from"path";import{gzip as WO}from"zlib";import{promisify as KO}from"util";function GO(t){return Au(Ns(t),"browser")}function qO(t){return Au(GO(t),"screenshots")}function zO(){return new Date().toISOString().replace(/[:.]/g,"-")}function JO(){return UO(3).toString("hex")}async function Eu(t,e,n){if(e.length>Ub)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Ub} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=qO(t);await BO(r,{recursive:!0});let o=`${zO()}-${JO()}-${n}.png`,s=Au(r,o);await jO(s,e);let{size:i}=await HO(s);return{path:s,bytes:i}}var cY,Ub,Bb=b(()=>{"use strict";z();fa();cY=KO(WO);Ub=5*1024*1024});var jb={};Ec(jb,{PlaywrightProvider:()=>Tu});function Hb(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 Tu,Wb=b(()=>{"use strict";Rb();Lb();$b();bu();Bb();Tu=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new pa(e)}async open(e){let n=yu(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(c){a=c}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await ma(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(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 ma(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 _u(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Hb(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=r.url();if(u!==s){let g=yu(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||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await ma(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;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 _u(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Hb(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 Eu(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 Eu(n,o,r);return s}catch{return null}}}});var In={};Ec(In,{__resetBrowserRegistryForTests:()=>ZO,browserProviderActive:()=>XO,closeBrowserProvider:()=>xu,getBrowserProvider:()=>YO,peekBrowserProvider:()=>QO});function Kb(){Promise.resolve(xu()).then(()=>{process.exit(130)})}function Gb(){Promise.resolve(xu()).then(()=>{process.exit(143)})}function qb(){ht=null}function VO(){ga||(process.on("SIGINT",Kb),process.on("SIGTERM",Gb),process.on("exit",qb),ga=!0)}function zb(){ga&&(process.removeListener("SIGINT",Kb),process.removeListener("SIGTERM",Gb),process.removeListener("exit",qb),ga=!1)}async function YO(t){return ht!==null?ht:(Cn!==null||(Cn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Wb(),jb)),n=Ab(t),r=new e(n);return VO(),ht=r,Cn=null,r})()),Cn)}async function xu(){if(ht===null)return;let t=ht;ht=null,Cn=null,zb(),await t.shutdown()}function XO(){return ht!==null}function QO(){return ht}function ZO(){ht=null,Cn=null,zb()}var ht,Cn,ga,Pn=b(()=>{"use strict";bu();ht=null,Cn=null,ga=!1});async function Jb(t,e){try{return await bb(t,e)}catch(n){return U("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function s0(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Pn(),In));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function Vb(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??s0,o=null,s=t,i=null,a=null;try{let c=await da(n,t,{headers:o0,redirect:"follow",signal:e.signal});i=c.status,s=c.url||t;let d=c.headers.get("content-type")??"";if(c.ok){if(r0.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await c.text();if(n0.test(d)&&!t0.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};if(o=await Jb(u,s),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(c){if(e.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<200)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=await Jb(c.html,c.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(e.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),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=c,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${i??"error"}).`)}var t0,n0,r0,o0,Yb=b(()=>{"use strict";wb();hu();fe();t0=/(text\/html|application\/xhtml\+xml)/i,n0=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,r0=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,o0={"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 l0(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(i0,{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),a0),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=ir(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function Xb(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?l0({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 Qb(t,e){if(e.length===0)return`# Search results for "${t}"
860
+ ${Ve(t,{headless:e})}`,{cause:t})}var Tb,yO,bO,Eb,vu=b(()=>{"use strict";Tb=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],yO="pnpm exec playwright install chromium",bO=4});import Rn from"node:fs";import ua from"node:path";import{randomBytes as SO}from"node:crypto";import{chromium as vO}from"playwright";function kO(){try{return"5.81.6"}catch{}try{let t=ua.resolve(import.meta.dirname,"../../../package.json"),e=Rn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var _O,pa,Rb=b(()=>{"use strict";vu();z();fe();_O=kO(),pa=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=vO.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,e)).catch(e=>{throw this.launchPromise=void 0,Su(e,this.config.headless)}),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}),l=await i.content(),c=i.url(),d=a!==null?a.status():null;return{html:l,finalUrl:c,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/${_O}`}}loadStorageState(e){let n=Oc(e);try{if(!Rn.existsSync(n))return;let r=JSON.parse(Rn.readFileSync(n,"utf8"));return U("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){U("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Oc(e);if(!Rn.existsSync(r))return;let o=await n.storageState(),s=ua.join(ua.dirname(r),`.${ua.basename(r)}.${process.pid}.${SO(4).toString("hex")}.tmp`);Rn.writeFileSync(s,JSON.stringify(o),{mode:384}),Rn.chmodSync(s,384),Rn.renameSync(s,r),U("[browser/vault] saved session",{profile:e,file:r})}catch(r){U("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as AO}from"crypto";function Cb(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&EO.test(t.label))}function Ib(t){return AO("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Pb(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var EO,fa=b(()=>{"use strict";EO=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as TO}from"node:crypto";function xO(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function RO(t,e,n){return`el_${TO("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function CO(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Mb(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Db(t,e){let n=t.role??"",r=t.name??"";Ob.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Db(s,e)}async function IO(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},Fb).catch(()=>[])}async function PO(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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,m={role:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},Fb).catch(()=>[])}function MO(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function ma(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=MO(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=IO(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,w=!1;u!==null?(h=[],Db(u,h)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,h=(await PO(t)).filter(N=>Ob.has(N.role??"")));let v=new Map;for(let I of p){let N=Mb(I.name),j=v.get(N);(!j||j.bbox.w===0&&I.bbox.w>0)&&v.set(N,I)}let E=h.map(I=>({ax:I,dom:v.get(Mb(I.name??""))})),k=r?E:E.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,N)=>{let j=I.dom?.bbox.y??0,C=N.dom?.bbox.y??0;if(j!==C)return j-C;let $=I.dom?.bbox.x??0,O=N.dom?.bbox.x??0;return $-O}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,N)=>{let j=I.ax.role??"generic",C=I.ax.name??"",$=RO(j,C,N),O=I.dom?.bbox??{x:0,y:0,w:0,h:0},M=I.dom?.type??null,D=null;I.ax.value!==void 0&&I.ax.value!==null&&(D=String(I.ax.value)),I.ax.checked!==void 0&&(D=String(I.ax.checked)),Cb({role:j,kind:M})&&(D="[redacted]");let H={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(H.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(H.selected=I.ax.selected),I.ax.expanded!==void 0&&(H.expanded=I.ax.expanded);let L;I.dom?.testId?L=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(L=`#${I.dom.id}`);let B={id:$,role:j,label:xO(C),kind:M,value:D,state:H,bbox:O};return L!==void 0&&(B.selector=L),B}),R="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?R="loading":I==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let S=CO(f),x=`obs_${e.observationCounter.toString(36)}`,P=new Date().toISOString();return{observationId:x,url:m,title:g,textSummary:S,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:P}}var Ob,Fb,Lb=b(()=>{"use strict";fa();Ob=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);Fb="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Nb(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${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 ku(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Nb(t,s)))).filter(o=>o!==null)}async function OO(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function _u(t,e,n){switch(e.kind){case"element_id":return DO(t,e,n);case"selector":return FO(t,e);case"semantic":return LO(t,e)}}async function DO(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 ku(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function FO(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 ku(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function LO(t,e){return e.role!==void 0?NO(t,e.text,e.role):$O(t,e.text,e)}async function NO(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 ku(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function $O(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:s,count:l});let u=await OO(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 h=p[g];if(h===void 0)continue;let w=await Nb(h.locator,h.index);if(w!==null){let v=`${w.role}:${w.label}:${g}`,E=0;for(let k=0;k<v.length;k++)E=E*31+v.charCodeAt(k)>>>0;f.push({...w,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var $b=b(()=>{"use strict"});import{randomBytes as UO}from"crypto";import{mkdir as BO,stat as HO,writeFile as jO}from"fs/promises";import{join as Au}from"path";import{gzip as WO}from"zlib";import{promisify as KO}from"util";function GO(t){return Au(Ns(t),"browser")}function qO(t){return Au(GO(t),"screenshots")}function zO(){return new Date().toISOString().replace(/[:.]/g,"-")}function JO(){return UO(3).toString("hex")}async function Eu(t,e,n){if(e.length>Ub)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Ub} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=qO(t);await BO(r,{recursive:!0});let o=`${zO()}-${JO()}-${n}.png`,s=Au(r,o);await jO(s,e);let{size:i}=await HO(s);return{path:s,bytes:i}}var cY,Ub,Bb=b(()=>{"use strict";z();fa();cY=KO(WO);Ub=5*1024*1024});var jb={};Ec(jb,{PlaywrightProvider:()=>Tu});function Hb(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 Tu,Wb=b(()=>{"use strict";Rb();Lb();$b();bu();Bb();Tu=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new pa(e)}async open(e){let n=yu(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(c){a=c}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await ma(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(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 ma(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 _u(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Hb(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(h){c=h}else c=g}let u=r.url();if(u!==s){let g=yu(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||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await ma(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;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 _u(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Hb(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 Eu(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 Eu(n,o,r);return s}catch{return null}}}});var In={};Ec(In,{__resetBrowserRegistryForTests:()=>ZO,browserProviderActive:()=>XO,closeBrowserProvider:()=>xu,getBrowserProvider:()=>YO,peekBrowserProvider:()=>QO});function Kb(){Promise.resolve(xu()).then(()=>{process.exit(130)})}function Gb(){Promise.resolve(xu()).then(()=>{process.exit(143)})}function qb(){ht=null}function VO(){ga||(process.on("SIGINT",Kb),process.on("SIGTERM",Gb),process.on("exit",qb),ga=!0)}function zb(){ga&&(process.removeListener("SIGINT",Kb),process.removeListener("SIGTERM",Gb),process.removeListener("exit",qb),ga=!1)}async function YO(t){return ht!==null?ht:(Cn!==null||(Cn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Wb(),jb)),n=Ab(t),r=new e(n);return VO(),ht=r,Cn=null,r})()),Cn)}async function xu(){if(ht===null)return;let t=ht;ht=null,Cn=null,zb(),await t.shutdown()}function XO(){return ht!==null}function QO(){return ht}function ZO(){ht=null,Cn=null,zb()}var ht,Cn,ga,Pn=b(()=>{"use strict";bu();ht=null,Cn=null,ga=!1});async function Jb(t,e){try{return await bb(t,e)}catch(n){return U("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function s0(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Pn(),In));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal})}async function Vb(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??s0,o=null,s=t,i=null,a=null;try{let c=await da(n,t,{headers:o0,redirect:"follow",signal:e.signal});i=c.status,s=c.url||t;let d=c.headers.get("content-type")??"";if(c.ok){if(r0.test(d))throw new Error(`web_scrape markdown mode received binary content (${d.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let u=await c.text();if(n0.test(d)&&!t0.test(d))return{title:"",markdown:u.trim(),finalUrl:s,usedRender:!1};if(o=await Jb(u,s),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(c){if(e.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<200)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal}),d=await Jb(c.html,c.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(o===null||d.textLength>=o.textLength)return{title:d.title,markdown:d.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(e.signal.aborted)throw c;if(o===null){let d=c instanceof Error?c.message:String(c),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=c,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${i??"error"}).`)}var t0,n0,r0,o0,Yb=b(()=>{"use strict";wb();hu();fe();t0=/(text\/html|application\/xhtml\+xml)/i,n0=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,r0=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,o0={"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 l0(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(i0,{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),a0),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=ir(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function Xb(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?l0({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 Qb(t,e){if(e.length===0)return`# Search results for "${t}"
861
861
 
862
862
  (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(`
863
863
  `).trimEnd()}var i0,a0,Zb=b(()=>{"use strict";yn();i0="https://api.exa.ai/search",a0=10});function ha(t){if(t instanceof Error&&t.name==="TimeoutError")return"timeout";let e=t instanceof Error?t.message:String(t);return/Timeout\s+\d+\s*ms exceeded/i.test(e)?"timeout":void 0}var Mn=b(()=>{"use strict";vu()});function m0(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 l;try{l=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let i=c0;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,d0)}let a=u0;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,p0)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Ru(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:xt(t,e),truncated:!0}}function g0(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=m0(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)},l,c=()=>{let d=i.signal.reason;return d instanceof Error?d.message:String(d??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),l=setTimeout(()=>{i.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.mode==="raw"){let u;try{u=await da(e,s.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:i.signal})}catch(m){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape network error: ${m instanceof Error?m.message:String(m)}`,isError:!0}}if(!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(m){return{content:`web_scrape read error: ${m instanceof Error?m.message:String(m)}`,isError:!0}}let f=Ru(p,s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let u=await Vb(s.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:s.timeoutMs,signal:i.signal});if(u.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let p=Ru(u.markdown,s.maxBytes);return{content:p.content,...p.truncated?{truncated:!0}:{}}}catch(u){if(i.signal.aborted)return{content:`web_scrape aborted: ${c()}`,isError:!0};let p=u instanceof Error?u.message:String(u),f=Ce(u)&&!wu(p)?` (the render fallback needs the optional Playwright browser \u2014 run \`${_o()}\`)`:"";return{content:`web_scrape markdown error: ${p}${f}`,isError:!0}}let d=Xb({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:f0,timeoutMs:s.timeoutMs,signal:i.signal}),p=Ru(Qb(s.query,u),s.maxBytes);return{content:p.content,...p.truncated?{truncated:!0}:{}}}catch(u){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${u instanceof Error?u.message:String(u)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),o.removeEventListener("abort",a)}}}var c0,d0,u0,p0,f0,ew,tw=b(()=>{"use strict";Yb();Zb();hu();cr();Mn();c0=3e4,d0=12e4,u0=1e5,p0=1e6,f0=10;ew=g0()});import{existsSync as rw,mkdirSync as h0,readFileSync as y0,renameSync as b0,unlinkSync as w0,writeFileSync as S0}from"node:fs";import{dirname as nw,join as v0}from"node:path";import{randomBytes as k0}from"node:crypto";function mr(t){let e=t??Cc();if(!rw(e))return[];try{let n=y0(e,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${e}: ${r}`),[]}}function ya(t,e){let n=e??Cc();h0(nw(n),{recursive:!0});let r=v0(nw(n),`.schedules.json.${process.pid}.${k0(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{S0(r,o,"utf-8"),b0(r,n)}catch(s){try{rw(r)&&w0(r)}catch{}throw s}}function ow(t,e){let n=mr(e),r=n.map(l=>l.id),o=_0(t.name),s=A0(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),ya(n,e),a}function sw(t,e){let n=mr(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(ya(o,e),!0)}function iw(t,e){return mr(e).find(n=>n.id===t)}function _0(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function A0(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}var aw=b(()=>{"use strict";z()});import{existsSync as E0,readFileSync as T0}from"node:fs";import{join as x0}from"node:path";async function Ao(t,e,n){let r;try{let o=x0(gm("default"),"port");if(!E0(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let s=T0(o,"utf-8").trim();if(r=parseInt(s,10),Number.isNaN(r))return{synced:!1,detail:"daemon-not-detected (invalid port file)"}}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let o=await fetch(`http://localhost:${r}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return o.ok?{synced:!0,detail:"synced"}:t==="POST"&&o.status===409?{synced:!0,detail:"already-registered"}:t==="DELETE"&&o.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${o.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}var Cu,lw=b(()=>{"use strict";z();Cu="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start."});import{existsSync as R0}from"node:fs";import{readFile as C0}from"node:fs/promises";var cw,dw,uw,pw,fw=b(()=>{"use strict";aw();z();lw();cw=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=n.notifyChat;if(o!==void 0&&typeof o!="number"&&typeof o!="string")return{content:"Invalid input: notifyChat must be a number (chat id) or string (chat id or alias name)",isError:!0};let s=ow({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),i=s.enabled?await Ao("POST","/tasks",{taskId:s.id,command:s.command,cron:s.cron,trigger:s.trigger,notifyOn:s.notifyOn,...s.notifyChat!==void 0?{notifyChat:s.notifyChat}:{}}):await Ao("DELETE",`/tasks/${s.id}`);return{content:JSON.stringify({id:s.id,name:s.name,cron:s.cron,enabled:s.enabled,daemonSynced:i.synced,syncDetail:i.detail,...i.synced?{}:{syncNote:Cu}})}},dw=async(t,e)=>{let n=mr();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},uw=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,s=Is();if(!R0(s))return{content:JSON.stringify([])};let i;try{let c=await C0(s);i=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
@@ -1003,7 +1003,7 @@ ${Xo}`:Xo,baseUrl:u?void 0:a.baseUrl,maxTurns:v,maxToolUseIterations:E,depth:r+1
1003
1003
  ${t}`}async function rk(t){let{handle:e,signal:n,prompt:r,idPrefix:o,model:s,parentModel:i,childManager:a,identity:l,depth:c,parentSessionId:d,registry:u,promotionTriggers:p,activeForegroundHandles:f}=t,m=()=>{e.cancel()};n.addEventListener("abort",m,{once:!0});let g=Date.now(),h=!1,w,v=new Promise(R=>{w=R}),E,k=new Promise(R=>{E=R});p.set(e.id,{fire:w,ready:k}),f.set(e.id,e);let A,T=e.runToResult(r);try{let R=await Promise.race([T.then(N=>({kind:"result",result:N})),v.then(()=>({kind:"promote"}))]);if(R.kind==="promote")if(u)try{let N=u.adoptRunning({handle:e,runPromise:T,prompt:r,model:s??"sonnet",parentSessionId:d});return h=!0,n.removeEventListener("abort",m),E({jobId:N.jobId,label:N.label}),{content:JSON.stringify({status:"running",jobId:N.jobId,subagentId:N.subagentId,label:N.label,message:`Subagent backgrounded by user (jobId=${N.jobId}). It keeps running detached; its result will be delivered into this context automatically with the next user message once it finishes. /bgsub:join ${N.jobId} remains available for manual replay.`})}}catch(N){U("subagent-executor: promotion failed, staying foreground: "+(N instanceof Error?N.message:String(N))),E(null)}else E(null);let S=R.kind==="result"?R.result:await T;if(S.status==="succeeded"&&S.message){let N=S.message.content,j=typeof N=="string"?N:JSON.stringify(N),C=S.trace;return Cr({...l,event:"subagent.completed",subagent_id:e.id,parent_session_id:d,status:S.status,duration_ms:Date.now()-g,content_chars:j.length,stop_reason:S.stopReason!==void 0?st(S.stopReason,64):void 0,depth:c,tool_call_count:C?.toolCalls.length,thinking_present:C?.thinkingPresent,tool_names:C?.toolCalls.length?JSON.stringify([...new Set(C.toolCalls.map($=>$.name))]):void 0}),A={content:BL(Tr(j,S.stopReason),s,i),...Nn(S.stopReason)},A}let x=S.error?.message??"Subagent failed with no output",P=S.trace;Cr({...l,event:"subagent.failed",subagent_id:e.id,id_prefix:o,parent_session_id:d,status:S.status,duration_ms:Date.now()-g,error_message:st(x),schema_error:S.schemaError?st(S.schemaError.message):void 0,partial_output_chars:jp(S.partialOutput),stop_reason:S.stopReason!==void 0?st(S.stopReason,64):void 0,depth:c,tool_call_count:P?.toolCalls.length,thinking_present:P?.thinkingPresent,tool_names:P?.toolCalls.length?JSON.stringify([...new Set(P.toolCalls.map(N=>N.name))]):void 0});let I=Yv({status:S.status,errorMessage:x,schemaErrorMessage:S.schemaError?.message,partialOutput:S.partialOutput,subagentId:e.id});return A={content:JSON.stringify(I),isError:!0,...Nn(S.stopReason)},A}catch(R){let S=R instanceof Error?R.message:String(R);throw Cr({...l,event:"subagent.failed",subagent_id:e.id,id_prefix:o,parent_session_id:d,status:"failed",duration_ms:Date.now()-g,error_message:st(S),depth:c}),R}finally{if(p.delete(e.id),f.delete(e.id),E(null),!h){n.removeEventListener("abort",m),await a?.teardownAll(),await e.teardown({deferInjectContextToCaller:!0});let R=e.getLastStopInjectContext?.();if(fl(A,R),t.isolationTeardown){let{repoRoot:S,worktreePath:x}=t.isolationTeardown,P=await Tw({repoRoot:S,worktreePath:x});P.preserved&&U(`[isolation] preserved worktree ${x} (${P.reason}) \u2014 locked so the sweep will not reap it; recover via the worktree tool`)}}}}var ok=b(()=>{"use strict";Ee();fe();vl();Ip();ka()});var Ir,Wp=b(()=>{"use strict";ye();_n();Mt();wl();yn();$t();Jv();vl();Qv();nk();ok();ka();fe();Mt();Ir=class t{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;currentCwd;isolationCounter=0;setCwd(e){this.currentCwd=e,this.ctx.subagentManager.setCwd(e)}describeAgentTool(){return Hp(this.ctx.agentRegistry)}promotionTriggers=new Map;activeForegroundHandles=new Map;hasPromotableForeground(){return this.ctx.backgroundRegistry!==void 0&&this.promotionTriggers.size>0}hasActiveForeground(){return this.activeForegroundHandles.size>0}async cancelActiveForeground(){let e=[...this.activeForegroundHandles.values()];return e.length===0?0:(await Promise.all(e.map(n=>n.cancel().catch(()=>{}))),e.length)}async promoteActiveForeground(){let e=[...this.promotionTriggers.values()];return e.forEach(r=>r.fire()),(await Promise.all(e.map(r=>r.ready))).filter(r=>r!==null)}getSubagentsLite(){let e=this.ctx.subagentManager.list().map(r=>({id:r.id,status:r.status})),n=this.ctx.backgroundRegistry?this.ctx.backgroundRegistry.list().map(r=>({jobId:r.jobId,status:r.status,startedAt:new Date(r.startedAt).toISOString(),label:r.label.length>0?r.label:null})):[];return{active:e,backgroundJobs:n}}async execute(e){if(e.signal.aborted)return{content:"Agent tool call aborted",isError:!0};let n;try{n=zv(e.input)}catch(h){return{content:`Agent tool input validation failed: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let r;if(n.agent_type!==void 0&&(r=this.ctx.agentRegistry?.get(n.agent_type),r===void 0)){let h=[...this.ctx.agentRegistry?.keys()??[]].sort().join(", ");return{content:`Agent type "${n.agent_type}" not found. Available agent types: ${h.length>0?h:"(none)"}`,isError:!0}}let o=this.ctx.nestedAgentAllowlist;if(o!==void 0){let h=n.agent_type;if(h===void 0||!o.includes(h))return{content:o.length===0?"This agent is not permitted to dispatch any nested agents (its definition granted the dispatch tool but named zero allowed types, e.g. `Agent()`). Complete the task with your own tools.":`This agent may only dispatch the following agent type(s): ${o.join(", ")}. `+(h===void 0?"A bare dispatch with no agent_type is not permitted here \u2014 set agent_type to one of the allowed types, or complete the task with your own tools.":`agent_type "${h}" is out of scope.`),isError:!0}}let s=this.ctx.depth,i=this.ctx.maxDepth??Un,a=this.ctx.surface!==void 0?{origin:Nt(this.ctx.surface),actor:at(s)}:{},l=this.ctx.subagentManager.getReadScopeInputs?.()??{parentReadRoots:void 0,parentCwd:void 0},c=mo({parentReadRoots:l.parentReadRoots,parentCwd:l.parentCwd,childCwd:n.cwd??this.currentCwd}),{childConfig:d,childParentSession:u,childManager:p,childWriteCapable:f}=Xv({parsed:n,namedAgent:r,depth:s,maxDepth:i,currentCwd:this.currentCwd,...c!==void 0?{childInheritedReadRoots:c}:{},signal:e.signal,defaultConfig:this.ctx.defaultConfig,...this.ctx.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:this.ctx.resolveApiKeyForModel}:{},defaultSubagentModel:this.ctx.defaultSubagentModel,...this.ctx.childProviderFactory!==void 0?{childProviderFactory:this.ctx.childProviderFactory}:{},...this.ctx.childSkillExecutorFactory!==void 0?{childSkillExecutorFactory:this.ctx.childSkillExecutorFactory}:{},...this.ctx.surface!==void 0?{surface:this.ctx.surface}:{},...this.ctx.allowedTools!==void 0?{allowedTools:this.ctx.allowedTools}:{},...this.ctx.readOnlyBash!==void 0?{readOnlyBash:this.ctx.readOnlyBash}:{},...this.ctx.agentRegistry!==void 0?{agentRegistry:this.ctx.agentRegistry}:{},...this.ctx.parentModel!==void 0?{parentModel:this.ctx.parentModel}:{},...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},createChildExecutor:h=>new t(h)}),m;if(n.isolation==="worktree")if(!f)U(`[isolation] skipped worktree for read-only dispatch (agent_type=${n.agent_type??"generic"}) \u2014 nothing to isolate`);else{let h=this.currentCwd??process.cwd();try{let w=await Ew({cwd:h,slugHint:`iso-${n.id_prefix}-${++this.isolationCounter}-${Math.random().toString(36).slice(2,8)}`});d.cwd=w.path,m={repoRoot:w.repoRoot,worktreePath:w.path}}catch(w){return{content:`Failed to create isolated worktree for the subagent: ${w instanceof Error?w.message:String(w)}. isolation:"worktree" requires the dispatching session to run inside a git repository.`,isError:!0}}}n.mode==="background"&&d.timeoutMs===void 0&&(d.timeoutMs=sk);let g;try{g=await this.ctx.subagentManager.forkSubagent({parent:this.ctx.parentSession,parentId:e.id,config:d,idPrefix:n.id_prefix,agentType:r!==void 0?r.name:n.id_prefix&&n.id_prefix!=="agent-tool"?ut(n.id_prefix).replace(/[\r\n]+/g," ").trim()||"agent":ut(n.prompt).replace(/[\r\n]+/g," ").slice(0,40).trim()||"agent",...r!==void 0?{resolvedAgentType:r.name}:{},promptHead:ut(n.prompt).replace(/[\r\n]+/g," ").slice(0,80).trim(),denyElicitations:!0}),u!==void 0&&(u.sessionId=g.id)}catch(h){let w=h instanceof Error?h.message:String(h);return Cr({...a,event:"subagent.failed",subagent_id:"unknown",id_prefix:n.id_prefix,parent_session_id:this.ctx.parentSession.sessionId,status:"failed",error_message:st(w),depth:s}),{content:`Failed to fork subagent: ${w}`,isError:!0}}return n.mode==="background"?tk({handle:g,registry:this.ctx.backgroundRegistry,prompt:n.prompt,model:d.model,parentSessionId:this.ctx.parentSession.sessionId}):rk({handle:g,signal:e.signal,prompt:n.prompt,idPrefix:n.id_prefix,model:d.model,...this.ctx.parentModel!==void 0?{parentModel:this.ctx.parentModel}:{},childManager:p,identity:a,depth:s,parentSessionId:this.ctx.parentSession.sessionId,registry:this.ctx.backgroundRegistry,promotionTriggers:this.promotionTriggers,activeForegroundHandles:this.activeForegroundHandles,...m!==void 0?{isolationTeardown:m}:{}})}}});function Kp(t,e,n,r=!1,o){let{ctx:s,currentCwd:i}=t,a=s.depth??0,l=s.maxDepth??Un,c={...e},d=r&&o!==void 0?o.filter(h=>El.includes(h)):r?[...El]:o,u=r;if(!s.childProviderFactory||a>=l)return r?c.provider=ak(c.model,s.openaiBaseUrl,d):d!==void 0&&(c.provider=_l(d,c.model,u,s.openaiBaseUrl)),{childConfig:c,childManager:void 0};let p=Kt(s.getReadScopeInputs?.(),i),f=new Q({parentAbortSignal:n,...s.traceWriter!==void 0?{traceWriter:s.traceWriter}:{},...s.surface!==void 0?{surface:s.surface}:{},...i!==void 0?{cwd:i}:{},...p!==void 0?{parentReadRoots:p}:{}}),m=new Ir({subagentManager:f,parentSession:Qo(n),defaultConfig:{model:c.model,apiKey:s.apiKey,...s.baseUrl!==void 0?{baseUrl:s.baseUrl}:{},...s.openaiBaseUrl!==void 0?{openaiBaseUrl:s.openaiBaseUrl}:{}},...s.surface!==void 0?{surface:s.surface}:{},defaultSubagentModel:s.defaultSubagentModel,childProviderFactory:s.childProviderFactory,childSkillExecutorFactory:s.childSkillExecutorFactory,...s.resolveApiKeyForModel!==void 0?{resolveApiKeyForModel:s.resolveApiKeyForModel}:{},depth:a+1,maxDepth:l,...i!==void 0?{cwd:i}:{},...s.traceWriter!==void 0?{traceWriter:s.traceWriter}:{},...s.backgroundRegistry!==void 0?{backgroundRegistry:s.backgroundRegistry}:{},...d!==void 0?{allowedTools:d}:{},...u?{readOnlyBash:!0}:{},...s.agentRegistry!==void 0?{agentRegistry:s.agentRegistry}:{},...c.model!==void 0?{parentModel:c.model}:{}}),g=s.childSkillExecutorFactory?s.childSkillExecutorFactory(a+1,l,n,i,{parentReadRoots:p,parentCwd:i}):void 0;return c.provider=s.childProviderFactory({childExecutor:m,...g!==void 0?{childSkillExecutor:g}:{},...c.model!==void 0?{model:c.model}:{},...d!==void 0?{allowedTools:d}:{},...u?{readOnlyBash:!0}:{}}),{childConfig:c,childManager:f}}var ik=b(()=>{"use strict";ye();_n();Mt();Wp()});function lk(t,e){let{ctx:n,currentCwd:r}=t,o=Kt(n.getReadScopeInputs?.(),r);return new Q({parentAbortSignal:e.parentAbortSignal,apiKey:e.apiKey,parentModel:e.parentModel,...n.baseUrl!==void 0?{baseUrl:n.baseUrl}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},...n.surface!==void 0?{surface:n.surface}:{},progressSink:Qe(),...r!==void 0?{cwd:r}:{},...o!==void 0?{parentReadRoots:o}:{}})}async function ck(t,e,n,r){let{ctx:o}=t;if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};let s=e.readOnly===!0||Tl.has(e.name),i;try{if(i=ce(e.name)["system.md"],!i)return{content:`Skill "${e.name}" has context: "fork" but no prompts/system.md found`,isError:!0}}catch(p){return{content:`Failed to load skill prompts: ${p instanceof Error?p.message:String(p)}`,isError:!0}}let a=e.model??o.defaultSubagentModel??o.defaultModel??"sonnet",l=zo({childModel:a,resolved:o.resolveApiKeyForModel?o.resolveApiKeyForModel(a):oe(a),parentApiKey:o.apiKey}),c=lk(t,{apiKey:l,parentModel:a,parentAbortSignal:r.signal}),{childConfig:d,childManager:u}=Kp(t,{model:a,systemPrompt:i,isSkillDispatch:!0,...o.traceWriter!==void 0?{traceWriter:o.traceWriter}:{}},r.signal,s);return uk(t,{manager:c,childManager:u,childConfig:d,label:e.name,idPrefix:`skill-fork-${e.name}`,parentId:r.id,args:n,noOutputError:"Forked skill failed with no output",errorPrefix:"Forked skill execution error"})}async function dk(t,e,n,r,o,s,i=!1,a,l){let{ctx:c}=t;if(s.signal.aborted)return{content:"Skill call aborted",isError:!0};let d=l??c.defaultSubagentModel??c.defaultModel??"sonnet",u=zo({childModel:d,resolved:c.resolveApiKeyForModel?c.resolveApiKeyForModel(d):oe(d),parentApiKey:c.apiKey}),p=lk(t,{apiKey:u,parentModel:d,parentAbortSignal:s.signal}),f={model:d,systemPrompt:dl(n,o),env:{PLUGIN_ROOT:r},isSkillDispatch:!0,...c.traceWriter!==void 0?{traceWriter:c.traceWriter}:{}},{childConfig:m,childManager:g}=Kp(t,f,s.signal,i,a);return uk(t,{manager:p,childManager:g,childConfig:m,label:e,idPrefix:`skill-${e}`,parentId:s.id,args:o,noOutputError:"Plugin skill failed with no output",errorPrefix:"Plugin skill execution error"})}async function uk(t,e){let{manager:n,childManager:r,childConfig:o,label:s,idPrefix:i,parentId:a,args:l,noOutputError:c,errorPrefix:d}=e,u,p;try{u=await n.forkSubagent({parent:t.ctx.parentSession,config:o,idPrefix:i,parentId:a,agentType:s});let f=l&&l.length>0?l:`Run the ${s} skill now, following the instructions in your system prompt.`,m=await u.runToResult(f);return m.status==="succeeded"&&m.message?(p={content:Tr(m.message.content,m.stopReason),...Nn(m.stopReason)},p):m.status==="cancelled"&&typeof m.partialOutput=="string"&&m.partialOutput.length>0?(p={content:`[skill cancelled mid-flight \u2014 partial output preserved below]
1004
1004
 
1005
1005
  ${m.partialOutput}`,...Nn(m.stopReason)},p):(p={content:m.error?.message??c,isError:!0,...Nn(m.stopReason)},p)}catch(f){let m=f instanceof Error?f.message:String(f);return{content:`${d}: ${m}`,isError:!0}}finally{u&&await u.teardown({deferInjectContextToCaller:!0}).catch(U);let f=u?.getLastStopInjectContext?.();fl(p,f),await r?.teardownAll(),await n.teardownAll()}}var pk=b(()=>{"use strict";ye();_n();Ee();Ip();Mt();ml();_e();vn();qe();fe();ik();Rp()});function HL(t){if(typeof t!="object"||t===null)return;let e=t.name;if(typeof e!="string")return;let n=e.trim();return n.length>0?n:void 0}function jL(t){if(typeof t!="object"||t===null)throw new Error("Skill tool input must be an object");let e=t,n=e.name;if(typeof n!="string"||n.trim().length===0)throw new Error('Skill tool input must have a non-empty "name" field');let r,o=e.arguments;if(o!==void 0){if(typeof o!="string")throw new Error('Skill tool "arguments" must be a string');r=o}return{name:n.trim(),arguments:r}}var Pr,Gp=b(()=>{"use strict";dt();Yt();Mt();kv();ft();Av();xv();xp();Rp();pk();Pr=class{constructor(e){this.ctx=e;this.currentCwd=e.cwd}ctx;pluginBodies=null;currentCwd;setCwd(e){this.currentCwd=e,this.pluginBodies=null}internals(){return{ctx:this.ctx,currentCwd:this.currentCwd}}async execute(e){if(e.signal.aborted)return{content:"Skill tool call aborted",isError:!0};let n=this.ctx.depth??0,r=this.ctx.maxDepth??Un;if(n>=r){let c=HL(e.input);return ie({...Er(this.ctx),event:"delegation.skipped",parent_session_id:this.ctx.parentSession.sessionId,reason:"max_depth",depth:n,requested_name:c}).catch(()=>{}),{content:vv(n,r),isError:!0}}let o;try{o=jL(e.input)}catch(c){return{content:`Skill tool input validation failed: ${c instanceof Error?c.message:String(c)}`,isError:!0}}let s;try{s=Tt(o.name)}catch{}if(s)return await this.executeRegistrySkill(s,o.arguments,e);let i=this.getPluginSkillBody(o.name);if(i){if(i.context==="fork"){let d=i.readOnly===!0||Tl.has(o.name);return await dk(this.internals(),o.name,i.body,i.pluginPath,o.arguments,e,d,i.allowedTools,i.model)}let c=i.body.replace(/\$\{PLUGIN_ROOT(?::-(?:[^{}]|\$\{[^{}]*\})*)?\}|\$PLUGIN_ROOT\b/g,()=>i.pluginPath);return Mv(this.internals(),o.name,c,o.arguments,e)}let l=Zo(this.ctx.pluginConfigs,this.currentCwd!==void 0?{cwd:this.currentCwd}:void 0).map(c=>c.name).join(", ");return{content:`Skill "${o.name}" not found. Available skills: ${l||"(none)"}`,isError:!0}}async executeRegistrySkill(e,n,r){if(r.signal.aborted)return{content:"Skill call aborted",isError:!0};if(e.context==="fork")return ck(this.internals(),e,n,r);if(e.context==="load")return Pv(this.internals(),e,n,r);let o=_v(e.name);o&&Tv(e.name);let s=this.ctx.depth??0;ie({...Er(this.ctx),event:"skill.dispatched",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,depth:s,...cl(e.name)?{is_gate:!0}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{});let i=Date.now(),a,l;try{l=await e.handler(n&&n.length>0?n:void 0,this.ctx.parentSession,{apiKey:this.ctx.apiKey,defaultModel:this.ctx.defaultModel,defaultSubagentModel:this.ctx.defaultSubagentModel,callId:r.id,dispatchSkill:this.createDispatchSkillCallback(r),...this.ctx.traceWriter!==void 0?{traceWriter:this.ctx.traceWriter}:{},...this.ctx.getReadScopeInputs!==void 0?{getReadScopeInputs:this.ctx.getReadScopeInputs}:{}})}catch(d){a=d}finally{let d=Date.now()-i;o&&Ev({skillName:e.name,durationMs:d,...a!==void 0?{isError:!0}:{}});let u=a!==void 0?a instanceof Error?a.message:String(a):void 0,p=a===void 0?typeof l=="string"?l.length:l!=null?JSON.stringify(l).length:0:void 0;ie({...Er(this.ctx),event:"skill.completed",requested_name:e.name,parent_session_id:this.ctx.parentSession.sessionId,status:a!==void 0?"failed":"succeeded",duration_ms:d,depth:s,...p!==void 0?{content_chars:p}:{},...u!==void 0?{error_message:Rv(u)}:{},...e.model!==void 0?{model:e.model}:{}}).catch(()=>{})}return a!==void 0?{content:`Skill execution error: ${a instanceof Error?a.message:String(a)}`,isError:!0}:{content:typeof l=="string"?l:l!=null?JSON.stringify(l):"Skill completed successfully."}}getPluginSkillBody(e){return this.pluginBodies||(this.pluginBodies=es(this.ctx.pluginConfigs,this.currentCwd!==void 0?{cwd:this.currentCwd}:void 0)),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 Qo(t){return{sessionId:void 0,getInputStreamRef:()=>({pushUserMessage:()=>{}}),abortSignal:t}}function fk(t={}){return({childExecutor:e,childSkillExecutor:n,model:r,allowedTools:o,readOnlyBash:s})=>{let i={permissions:{allowedTools:o??kl},subagentExecutor:e,...n!==void 0?{skillExecutor:n}:{},...s===!0?{readOnlyBash:!0}:{}};return X(typeof r=="string"?r:void 0)==="openai-compatible"?new Ie({...i,...t.openaiBaseUrl!==void 0?{baseURL:t.openaiBaseUrl}:{},readOnlyMemory:!0}):new Me({...i,readOnlyMemory:!0})}}function ak(t,e,n){let r={allowedTools:[...n??El]};return X(typeof t=="string"?t:void 0)==="openai-compatible"?new Ie({permissions:r,readOnlyBash:!0,readOnlyMemory:!0,...e!==void 0?{baseURL:e}:{}}):new Me({permissions:r,readOnlyBash:!0,readOnlyMemory:!0})}function mk(t,e,n,r,o,s,i,a,l,c,d,u){let p=(f,m,g,h,w)=>{let v=h??i;return new Pr({parentSession:Qo(g),defaultModel:t,...c!==void 0?{defaultSubagentModel:c}:{},apiKey:e,...r!==void 0?{baseUrl:r}:{},...u!==void 0?{openaiBaseUrl:u}:{},depth:f,maxDepth:m,childProviderFactory:n,childSkillExecutorFactory:p,...o!==void 0?{traceWriter:o}:{},...s!==void 0?{backgroundRegistry:s}:{},...v!==void 0?{cwd:v}:{},...a!==void 0?{resolveApiKeyForModel:a}:{},...l!==void 0?{surface:l}:{},...d!==void 0?{agentRegistry:d}:{},...w!==void 0?{getReadScopeInputs:()=>w}:{}})};return p}function _l(t,e,n=!1,r){let o={allowedTools:[...t]};return X(typeof e=="string"?e:void 0)==="openai-compatible"?new Ie({permissions:o,...n?{readOnlyBash:!0}:{},...r!==void 0?{baseURL:r}:{}}):new Me({permissions:o,...n?{readOnlyBash:!0}:{}})}function gk(t,e){let n={allowedTools:[...Sv]};return X(typeof e=="string"?e:void 0)==="openai-compatible"?new Ie({permissions:n}):new Me({permissions:n})}var Un,kl,El,Tl,Mt=b(()=>{"use strict";xl();qo();Se();et();tt();ll();Gp();Un=3;kl=[...Ze,...Ae,"memory_search","agent","skill"],El=["read_file","glob","grep","list_directory","config_get","bash","web_scrape",...Ae,"memory_search","agent","skill"],Tl=new Set(["ground-state"])});var hk,Rl,yk=b(()=>{"use strict";le();hk=3e4,Rl=class{constructor(e,n,r,o){this.controller=e;this.idleTimeoutMs=n;this.label=r;this.onFire=o;this.isEnabled()&&this.arm(this.idleTimeoutMs,"none")}controller;idleTimeoutMs;label;onFire;timer;disposed=!1;fired=!1;inFlightTools=new Set;isEnabled(){return Number.isFinite(this.idleTimeoutMs)&&this.idleTimeoutMs>0}onEvent(e){if(!(!this.isEnabled()||this.disposed||this.fired)){if(e.type==="chunk"){if(e.chunk.type==="tool_use_detail"){this.inFlightTools.add(e.chunk.toolUseId),this.clearTimer();return}if(e.chunk.type==="tool_result"){this.inFlightTools.delete(e.chunk.toolUseId),this.inFlightTools.size===0&&this.arm(this.idleTimeoutMs,e.chunk.type);return}}if(!(this.inFlightTools.size>0)){if(e.type==="paused"){this.arm(this.pausedWindowMs(e.resetsAt),e.type);return}if(e.type==="rate_limit"&&typeof e.retryAfterMs=="number"&&e.retryAfterMs>0){this.arm(e.retryAfterMs+hk,e.type);return}this.arm(this.idleTimeoutMs,e.type)}}}pausedWindowMs(e){if(e===void 0)return this.idleTimeoutMs;let n=e.getTime()-Date.now();return Math.max(this.idleTimeoutMs,n+hk)}arm(e,n){this.timer!==void 0&&clearTimeout(this.timer);let r=e>0?e:this.idleTimeoutMs,o=Date.now(),s=setTimeout(()=>{this.fire(Date.now()-o,n)},r);s.unref(),this.timer=s}clearTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}fire(e,n){if(!(this.fired||this.disposed)){this.fired=!0,this.timer=void 0;try{this.onFire?.({idleTimeoutMs:this.idleTimeoutMs,elapsedSinceLastProgressMs:e,lastEventType:n})}catch{}this.controller.signal.aborted||this.controller.abort(new ai(`subagent ${this.label} idle-watchdog fired: no observable progress for ${this.idleTimeoutMs}ms (last event: ${n}). The child stream produced no output for the idle window \u2014 typically a stalled model call under provider throttling with no detectable backoff bracket. Aborting so partial output (if any) is returned; the parent should retry or fall back.`,this.idleTimeoutMs))}}dispose(){this.disposed||(this.disposed=!0,this.inFlightTools.clear(),this.clearTimer())}}});var Cl,bk=b(()=>{"use strict";fe();le();Dd();vn();Ki();ne();yk();Ee();Cl=class{constructor(e,n,r,o,s,i,a,l,c,d,u,p,f,m,g,h=0){this.id=e;this.session=n;this.controller=r;this.abortGraph=o;this.outputSchema=s;this.timeoutMs=i;this.hookRegistry=a;this.onTerminal=l;this.parentInputStreamRef=c;this.parentAbortSignal=d;this.agentType=u;this.traceWriter=m;this.onSubagentSucceeded=g;this.idleTimeoutMs=h;this.progressSink=p,this.parentId=f}id;session;controller;abortGraph;outputSchema;timeoutMs;hookRegistry;onTerminal;parentInputStreamRef;parentAbortSignal;agentType;traceWriter;onSubagentSucceeded;idleTimeoutMs;currentStatus="idle";inFlight=null;lastMessage;lastDurationMs;latestTerminalStatus;stopDispatched=!1;lastStopInjectContext;progressSink;parentId;currentTrace=pl();lastStreamedContent="";lastStopReason;get status(){return this.currentStatus}async run(e,n){if(this.currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this.lastStopReason=void 0,this.currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this.currentStatus="running";let r=Date.now(),o=Di(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",await un(this.traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:this.lastDurationMs,turnCount:this.currentTrace.turnCount,outputBytes:Buffer.byteLength(this.lastMessage,"utf8"),...this.lastStopReason!==void 0&&{stopReason:this.lastStopReason}});let i=typeof s.metadata?.totalCostUsd=="number"?s.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this.currentTrace.usage,i),this.onTerminal(),s}catch(s){this.lastDurationMs=Date.now()-r;let i=this.controller.signal.aborted&&this.controller.signal.reason instanceof xe&&!this.abortGraph.isCascading(this.id)?this.controller.signal.reason:void 0,a=i??s;if(this.currentStatus!=="cancelled")if(this.controller.signal.aborted&&i===void 0){let l=this.controller.signal.reason instanceof xe;await un(this.traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade",...l?{timeout:!0}:{}}),this.currentStatus="cancelled",this.latestTerminalStatus="cancelled"}else await un(this.traceWriter,{transition:"failed",subagentId:this.id,errorClass:a instanceof Error?a.constructor.name:"Unknown",errorMessage:a instanceof Error?a.message:String(a),partialOutputBytes:Buffer.byteLength(this.lastStreamedContent,"utf8"),...i!==void 0?{failureClass:"timeout"}:{}}),this.currentStatus="failed",this.latestTerminalStatus="failed";throw this.onTerminal(),a}finally{this.inFlight=null}}async streamToFinalMessage(e,n){let r,o;this.lastStreamedContent="",this.currentTrace=pl();let s=n??this.progressSink??Qe(),i={subagentId:this.id,...this.parentId!==void 0&&{parentId:this.parentId},...this.agentType!==void 0&&{agentType:this.agentType}},a=new Rl(this.controller,this.idleTimeoutMs,this.id,l=>{Y(this.traceWriter,{phase:"idle_watchdog_fired",metadata:{idleTimeoutMs:l.idleTimeoutMs,elapsedSinceLastProgressMs:l.elapsedSinceLastProgressMs,lastEventType:l.lastEventType}})});try{for await(let l of this.session.sendMessageStream(e)){if(s&&s(l,i),a.onEvent(l),l.type==="chunk"){let c=l.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(l.type==="message")r=l.message,this.currentTrace.turnCount++;else if(l.type==="error"){o=l.error;break}else if(l.type==="done"){if(typeof l.metadata?.stopReason=="string"&&(this.lastStopReason=l.metadata.stopReason),typeof l.metadata?.usage=="object"&&l.metadata.usage!==null){let c=l.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}}}finally{a.dispose()}if(o)throw o;if(r)return r;if(this.lastStreamedContent.length>0)return this.lastStopReason??=ul,{role:"assistant",content:this.lastStreamedContent,timestamp:new Date};if(this.lastStopReason==="tool_use_loop_capped")return{role:"assistant",content:`[subagent ${this.id} reached its tool-use iteration cap before producing a final message; returning a capped partial result]`,timestamp:new Date};throw this.controller.signal.aborted||this.currentStatus==="cancelled"?new Error(`Subagent ${this.id} produced no terminal message`):(this.lastStopReason=ul,new lt(`subagent ${this.id} produced no output \u2014 its model stream ended without a terminal message (stream_incomplete), and no partial text was streamed. This is typically a first-token timeout while the provider was overloaded (the connection was aborted mid retry-backoff). No findings were produced; the parent should retry or fall back.`))}async runToResult(e,n){try{let r=await this.run(e,n);return Nv(this.id,this.currentStatus,r,this.outputSchema,this.currentTrace,this.lastStopReason)}catch(r){let o=Cp(this.id,this.currentStatus,r,this.currentTrace,this.lastStopReason);return this.lastStreamedContent.length>0&&(o.partialOutput=this.lastStreamedContent),o}}runInBackground(e,n,r){let o;if(r){let s=this.progressSink??Qe();o=(i,a)=>{r(i),s?.(i,a)}}this.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{U("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",un(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(e){if(this.stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await this.dispatchStopAndRelease(n,e)}}getLastStopInjectContext(){return this.lastStopInjectContext}async dispatchStopAndRelease(e,n){if(this.stopDispatched){this.onTerminal();return}this.stopDispatched=!0;let r=await wy(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(r.injectContext){if(this.parentAbortSignal?.aborted)U(`Skipping SubagentStop injectContext for ${this.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)this.lastStopInjectContext=r.injectContext;else if(this.parentInputStreamRef)try{let o=this.parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){U(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}this.onTerminal()}}});function wk(t,e){return t===void 0||!Oo(t)||X(t)!=="openai-compatible"?{model:t}:e===void 0||Oo(e)||X(e)!=="openai-compatible"?{model:t}:{model:e,coercedFrom:t}}var Sk=b(()=>{"use strict";Se();Ua()});import WL from"path";function qL(){let t=_.AFK_SUBAGENT_TIMEOUT_MS;if(t===void 0||t.trim()==="")return vk;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?vk:e}function zL(){let t=_.AFK_SUBAGENT_IDLE_TIMEOUT_MS;if(t===void 0||t.trim()==="")return kk;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?kk:e}var KL,GL,vk,kk,sk,Q,ye=b(()=>{"use strict";Mh();$d();Ki();ne();ft();vn();Kd();xy();_n();z();K();Mt();cr();ml();Se();bk();Sk();KL=async(t,e)=>({action:"decline"}),GL=50,vk=45*6e4;kk=8*6e4;sk=60*6e4,Q=class{active=new Map;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentModel;parentCwd;parentReadRoots;worktreeMainRootCache=new Map;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?X(e.parentModel):void 0,this.parentModel=e.parentModel,this.parentCwd=e.cwd,this.parentReadRoots=e.parentReadRoots,this.parentTraceWriter=e.traceWriter,this.parentSurface=e.surface,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.abortGraph=new Pi(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,this.worktreeMainRootCache.delete(e)}getReadScopeInputs(){return{parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd}}async resolveMainRootForCwd(e){if(this.worktreeMainRootCache.has(e))return this.worktreeMainRootCache.get(e);let n=await Ty(e);return this.worktreeMainRootCache.set(e,n),n}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,s=e.config.traceWriter??this.parentTraceWriter;o&&await by(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...s?{traceWriter:s}:{}});let i=new AbortController;this.abortGraph.register(n,i),this.abortGraph.linkChild(this.rootId,n);let a=e.config.cwd??this.parentCwd,l;if(e.config.readRoots===void 0){let T=this.parentReadRoots===void 0&&this.parentCwd===void 0,R;!T&&a!==void 0&&(R=await this.resolveMainRootForCwd(a),R===void 0&&this.parentCwd!==void 0&&this.parentCwd!==a&&(R=await this.resolveMainRootForCwd(this.parentCwd))),l=mo({parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd,childCwd:a,worktreeMainRoot:R,...T?{}:{afkStateRoot:Oe()}})}if(e.config.readRoots===void 0&&e.config.extraReadRoots!==void 0&&e.config.extraReadRoots.length>0&&(l!==void 0||a!==void 0)){let R=l??(a!==void 0?[a]:[]);l=[...new Set([...R,...e.config.extraReadRoots.map(S=>WL.resolve(S))])]}let c;if(e.config.writeRoots!==void 0&&e.config.writeRoots.length>0){let T=a!==void 0?[a]:[];c=[...new Set([...T,...e.config.writeRoots])]}let d=wk(e.config.model,this.parentModel),u=d.model??e.config.model;d.coercedFrom!==void 0&&process.stderr.write(`[afk] subagent: child model "${d.coercedFrom}" cannot run on this session's OpenAI/ChatGPT backend \u2014 running it as "${u??""}" instead (set AFK_DEFAULT_SUBAGENT_MODEL to choose a different one).
1006
- `);let p={...e.config,model:u,resume:r,forkSession:r?!0:e.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:i.signal,apiKey:Bv({childModel:u,configApiKey:e.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:e.config.baseUrl??(X(u)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??GL,autoResumeOnUsageLimit:e.config.autoResumeOnUsageLimit??!1,...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}:{},...l!==void 0?{readRoots:l}:{},...c!==void 0?{writeRoots:c}:{},...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:KL},...e.phaseRole==="read-only"?{provider:gk("read-only",u)}:{}};p.cwd!==void 0&&Ey(p.cwd);let f;try{f=new bn(p)}catch(T){throw this.abortGraph.dispose(n),T}let m=e.parent.getInputStreamRef?.(),g=e.parent.abortSignal,h=this.progressSink??Qe(),w=e.agentType?.trim()||void 0,v=e.resolvedAgentType?.trim()||void 0,E=e.parentId?.trim()||void 0,k=new Cl(n,f,i,this.abortGraph,e.outputSchema,e.config.timeoutMs??qL(),o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},m,g,w??e.idPrefix,h,E??e.parent.sessionId,s,this.onSubagentSucceededCb,e.config.idleTimeoutMs??zL());this.active.set(n,k);let A=typeof u=="string"?u:JSON.stringify(u);return un(s,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:A,...p.tools?.allowedTools?{allowedTools:[...p.tools.allowedTools]}:{},...e.promptHead&&e.promptHead.trim()!==""?{promptHead:e.promptHead.slice(0,80)}:{},...w?{agentType:w}:{},...v?{resolvedAgentType:v}:{}}),await ie({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,model:A,parent_session_id:e.parent.sessionId,resolved_agent_type:v}),k}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 _k(t,e={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=8}=e;if(t.length===0)return[];let s=new Array(t.length),i=new Set(t.map((l,c)=>c)),a=!1;return await ar(t.map((l,c)=>c),o,async l=>{let c=t[l];n&&a&&await c.handle.cancel().catch(()=>{});let d=await c.handle.runToResult(c.prompt);if(s[l]=d,i.delete(l),n&&d.status!=="succeeded"){a=!0;for(let u of i){let p=t[u];p&&p.handle.status==="running"&&p.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(t.map(l=>l.handle.teardown())),s}var Ak=b(()=>{"use strict";Yi()});function Ek(t){let e=new Set;for(let n of t){let r=Jo(n,JL);r!==void 0&&e.add(r)}return e}var JL,Tk=b(()=>{"use strict";Vo();et();na();JL=new Set([...Ze,...Ae,"memory_search","agent","skill"])});import{existsSync as VL,mkdirSync as f9,readFileSync as YL,renameSync as m9,writeFileSync as g9,unlinkSync as h9}from"fs";function xk(t=Ms()){if(!VL(t))return Il();try{let e=YL(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Il();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Il()}catch{return Il()}}function Il(){return{version:2,plugins:{},marketplaces:{}}}var Rk=b(()=>{"use strict";z()});import{existsSync as zp,readFileSync as Pk,readdirSync as XL,realpathSync as QL,statSync as ZL}from"fs";import{join as Mr,resolve as Ck}from"path";function Ot(t=it(),e={}){let n=e.trustAll===!0,r=e.sourceEnabled,o=n?`${t}\0trustAll`:t;if(n&&r&&r.size>0){let c=[...r.entries()].map(([d,u])=>`${d}=${u?1:0}`).sort().join(",");o=`${o}\0${c}`}ts||(ts=new Map);let s=ts.get(o);if(s)return[...s];if(!zp(t))return ts.set(o,[]),[];let i=t===it()?Ms():Mr(t,".index.json"),a=xk(i),l=[];return Mk(t,t,0,l,new Set,a.plugins,n,r),ts.set(o,l),[...l]}function Mk(t,e,n,r,o,s,i,a){if(n>eN)return;let l;try{l=QL(e)}catch{l=e}if(o.has(l))return;if(o.add(l),zp(Mr(e,".claude-plugin","plugin.json"))){let d=Jp(t,e);if(d===null){Pl(r,e);return}if(i){if(a&&a.get(nN(d))===!1)return;Pl(r,e);return}if(d.layout==="cache"){let p=s[d.key];if(!p||p.enabled===!1)return;Pl(r,e);return}let u=s[d.key];if(u&&u.enabled===!1)return;Pl(r,e);return}let c;try{c=XL(e)}catch{return}for(let d of c){if(d.startsWith("."))continue;let u=Mr(e,d),p;try{p=ZL(u)}catch{continue}p.isDirectory()&&Mk(t,u,n+1,r,o,s,i,a)}}function tN(t){try{let e=Pk(Mr(t,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(e);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function Pl(t,e){let n=tN(e);t.push(n!==void 0?{type:"local",path:e,main:n}:{type:"local",path:e})}function nN(t){if(t.layout!=="cache")return t.key;let e=t.key.indexOf(":");if(e<=0)return t.key;let n=t.key.slice(0,e);return`${t.key.slice(e+1)}@${n}`}function Jp(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===Ik&&r.length>=3){let s=r[1];if(s){let i=Mr(t,Ik,s),l=rN(i,e)??r[2];if(l)return{layout:"cache",key:`${s}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function rN(t,e){let n=Mr(t,".claude-plugin","marketplace.json");if(!zp(n))return null;let r;try{r=JSON.parse(Pk(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=Ck(e);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&Ck(t,a.source)===s)return a.name}return null}var eN,Ik,ts,Ml=b(()=>{"use strict";z();Rk();eN=5,Ik="cache"});import{existsSync as en,readdirSync as oN,readFileSync as sN}from"fs";import{join as Dt}from"path";function Dk(t=ge()){let e=[],n=Dt(t,"skills");if(en(n))for(let r of Ol(n)){let o=Dt(n,r,"SKILL.md");en(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of Ok){let o=Dt(t,`${r}s`);if(en(o))for(let s of Ol(o))s.endsWith(".md")&&e.push({path:Dt(o,s),type:r,source:"user"})}return e}function Fk(t=it()){if(!en(t))return[];let e=[],n=Ot(t);for(let r of n){let s=Jp(t,r.path)?.key,i=Dt(r.path,"skills");if(en(i))for(let a of Ol(i)){let l=Dt(i,a,"SKILL.md");if(!en(l))continue;let c={path:l,type:"skill",source:"plugin"};s&&(c.plugin_key=s),e.push(c)}for(let a of Ok){let l=Dt(r.path,`${a}s`);if(en(l))for(let c of Ol(l)){if(!c.endsWith(".md"))continue;let d={path:Dt(l,c),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function Lk(t=Dt(ge(),"settings.json")){if(!en(t))return[];try{let e=sN(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function Ol(t){try{return oN(t).filter(e=>!e.startsWith("."))}catch{return[]}}var Ok,Nk=b(()=>{"use strict";z();Ml();Ok=["command","agent"]});import{z as ae}from"zod";import{mkdir as $k,appendFile as Uk}from"fs/promises";import{join as Vp}from"path";function lN(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function cN(t){let e=()=>{let s={};for(let i of jk)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function dN(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function uN(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
1006
+ `);let p={...e.config,isSubagentFork:!0,model:u,resume:r,forkSession:r?!0:e.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:i.signal,apiKey:Bv({childModel:u,configApiKey:e.config.apiKey,parentApiKey:this.parentApiKey,parentProvider:this.parentProvider}),baseUrl:e.config.baseUrl??(X(u)==="openai-compatible"?void 0:this.parentBaseUrl),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??GL,autoResumeOnUsageLimit:e.config.autoResumeOnUsageLimit??!1,...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}:{},...l!==void 0?{readRoots:l}:{},...c!==void 0?{writeRoots:c}:{},...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:KL},...e.phaseRole==="read-only"?{provider:gk("read-only",u)}:{}};p.cwd!==void 0&&Ey(p.cwd);let f;try{f=new bn(p)}catch(T){throw this.abortGraph.dispose(n),T}let m=e.parent.getInputStreamRef?.(),g=e.parent.abortSignal,h=this.progressSink??Qe(),w=e.agentType?.trim()||void 0,v=e.resolvedAgentType?.trim()||void 0,E=e.parentId?.trim()||void 0,k=new Cl(n,f,i,this.abortGraph,e.outputSchema,e.config.timeoutMs??qL(),o,()=>{this.active.delete(n),this.abortGraph.dispose(n)},m,g,w??e.idPrefix,h,E??e.parent.sessionId,s,this.onSubagentSucceededCb,e.config.idleTimeoutMs??zL());this.active.set(n,k);let A=typeof u=="string"?u:JSON.stringify(u);return un(s,{transition:"started",subagentId:n,parentId:e.parent.sessionId??this.rootId,model:A,...p.tools?.allowedTools?{allowedTools:[...p.tools.allowedTools]}:{},...e.promptHead&&e.promptHead.trim()!==""?{promptHead:e.promptHead.slice(0,80)}:{},...w?{agentType:w}:{},...v?{resolvedAgentType:v}:{}}),await ie({event:"subagent.dispatched",subagent_id:n,id_prefix:e.idPrefix,model:A,parent_session_id:e.parent.sessionId,resolved_agent_type:v}),k}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 _k(t,e={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=8}=e;if(t.length===0)return[];let s=new Array(t.length),i=new Set(t.map((l,c)=>c)),a=!1;return await ar(t.map((l,c)=>c),o,async l=>{let c=t[l];n&&a&&await c.handle.cancel().catch(()=>{});let d=await c.handle.runToResult(c.prompt);if(s[l]=d,i.delete(l),n&&d.status!=="succeeded"){a=!0;for(let u of i){let p=t[u];p&&p.handle.status==="running"&&p.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(t.map(l=>l.handle.teardown())),s}var Ak=b(()=>{"use strict";Yi()});function Ek(t){let e=new Set;for(let n of t){let r=Jo(n,JL);r!==void 0&&e.add(r)}return e}var JL,Tk=b(()=>{"use strict";Vo();et();na();JL=new Set([...Ze,...Ae,"memory_search","agent","skill"])});import{existsSync as VL,mkdirSync as f9,readFileSync as YL,renameSync as m9,writeFileSync as g9,unlinkSync as h9}from"fs";function xk(t=Ms()){if(!VL(t))return Il();try{let e=YL(t,"utf8"),n=JSON.parse(e);if(!n||typeof n!="object")return Il();let r=n,o=r.plugins&&typeof r.plugins=="object"?r.plugins:{};if(r.version===1)return{version:2,plugins:o,marketplaces:{}};if(r.version===2){let s=r.marketplaces&&typeof r.marketplaces=="object"?r.marketplaces:{};return{version:2,plugins:o,marketplaces:s}}return Il()}catch{return Il()}}function Il(){return{version:2,plugins:{},marketplaces:{}}}var Rk=b(()=>{"use strict";z()});import{existsSync as zp,readFileSync as Pk,readdirSync as XL,realpathSync as QL,statSync as ZL}from"fs";import{join as Mr,resolve as Ck}from"path";function Ot(t=it(),e={}){let n=e.trustAll===!0,r=e.sourceEnabled,o=n?`${t}\0trustAll`:t;if(n&&r&&r.size>0){let c=[...r.entries()].map(([d,u])=>`${d}=${u?1:0}`).sort().join(",");o=`${o}\0${c}`}ts||(ts=new Map);let s=ts.get(o);if(s)return[...s];if(!zp(t))return ts.set(o,[]),[];let i=t===it()?Ms():Mr(t,".index.json"),a=xk(i),l=[];return Mk(t,t,0,l,new Set,a.plugins,n,r),ts.set(o,l),[...l]}function Mk(t,e,n,r,o,s,i,a){if(n>eN)return;let l;try{l=QL(e)}catch{l=e}if(o.has(l))return;if(o.add(l),zp(Mr(e,".claude-plugin","plugin.json"))){let d=Jp(t,e);if(d===null){Pl(r,e);return}if(i){if(a&&a.get(nN(d))===!1)return;Pl(r,e);return}if(d.layout==="cache"){let p=s[d.key];if(!p||p.enabled===!1)return;Pl(r,e);return}let u=s[d.key];if(u&&u.enabled===!1)return;Pl(r,e);return}let c;try{c=XL(e)}catch{return}for(let d of c){if(d.startsWith("."))continue;let u=Mr(e,d),p;try{p=ZL(u)}catch{continue}p.isDirectory()&&Mk(t,u,n+1,r,o,s,i,a)}}function tN(t){try{let e=Pk(Mr(t,".claude-plugin","plugin.json"),"utf8"),n=JSON.parse(e);if(n!==null&&typeof n=="object"&&"main"in n){let r=n.main;if(typeof r=="string"&&r.trim()!=="")return r}}catch{}}function Pl(t,e){let n=tN(e);t.push(n!==void 0?{type:"local",path:e,main:n}:{type:"local",path:e})}function nN(t){if(t.layout!=="cache")return t.key;let e=t.key.indexOf(":");if(e<=0)return t.key;let n=t.key.slice(0,e);return`${t.key.slice(e+1)}@${n}`}function Jp(t,e){if(!e.startsWith(t))return null;let n=e.slice(t.length).replace(/^\/+/,"");if(!n)return null;let r=n.split("/").filter(s=>s.length>0);if(r.length===0)return null;if(r[0]===Ik&&r.length>=3){let s=r[1];if(s){let i=Mr(t,Ik,s),l=rN(i,e)??r[2];if(l)return{layout:"cache",key:`${s}:${l}`}}}let o=r[0];return o?{layout:"flat",key:o}:null}function rN(t,e){let n=Mr(t,".claude-plugin","marketplace.json");if(!zp(n))return null;let r;try{r=JSON.parse(Pk(n,"utf8"))}catch{return null}if(!r||typeof r!="object")return null;let o=r.plugins;if(!Array.isArray(o))return null;let s=Ck(e);for(let i of o){if(!i||typeof i!="object")continue;let a=i;if(!(typeof a.name!="string"||typeof a.source!="string")&&!(!a.source.startsWith("./")&&!a.source.startsWith("../"))&&Ck(t,a.source)===s)return a.name}return null}var eN,Ik,ts,Ml=b(()=>{"use strict";z();Rk();eN=5,Ik="cache"});import{existsSync as en,readdirSync as oN,readFileSync as sN}from"fs";import{join as Dt}from"path";function Dk(t=ge()){let e=[],n=Dt(t,"skills");if(en(n))for(let r of Ol(n)){let o=Dt(n,r,"SKILL.md");en(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of Ok){let o=Dt(t,`${r}s`);if(en(o))for(let s of Ol(o))s.endsWith(".md")&&e.push({path:Dt(o,s),type:r,source:"user"})}return e}function Fk(t=it()){if(!en(t))return[];let e=[],n=Ot(t);for(let r of n){let s=Jp(t,r.path)?.key,i=Dt(r.path,"skills");if(en(i))for(let a of Ol(i)){let l=Dt(i,a,"SKILL.md");if(!en(l))continue;let c={path:l,type:"skill",source:"plugin"};s&&(c.plugin_key=s),e.push(c)}for(let a of Ok){let l=Dt(r.path,`${a}s`);if(en(l))for(let c of Ol(l)){if(!c.endsWith(".md"))continue;let d={path:Dt(l,c),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function Lk(t=Dt(ge(),"settings.json")){if(!en(t))return[];try{let e=sN(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function Ol(t){try{return oN(t).filter(e=>!e.startsWith("."))}catch{return[]}}var Ok,Nk=b(()=>{"use strict";z();Ml();Ok=["command","agent"]});import{z as ae}from"zod";import{mkdir as $k,appendFile as Uk}from"fs/promises";import{join as Vp}from"path";function lN(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function cN(t){let e=()=>{let s={};for(let i of jk)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function dN(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function uN(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
1007
1007
  `)}function pN(t,e){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${t}\``),n.push(""),e.length===0)return n.push("(no hooks discovered)"),n.join(`
1008
1008
  `);for(let r of e){let o=`${r.event}-${r.index}`;n.push(`### Hook \`${o}\``),n.push(""),n.push("```json"),n.push(JSON.stringify(r.raw,null,2)),n.push("```"),n.push("")}return n.join(`
1009
1009
  `)}function fN(t,e){if(!e)return{kind:"failure",message:`${t}: no result`};if(e.schemaError)return{kind:"failure",message:`${t}: schema mismatch \u2014 ${e.schemaError.message}`};if(e.status!=="succeeded"){let n=e.error?` \u2014 ${e.error.message}`:"";return{kind:"failure",message:`${t}: ${e.status}${n}`}}return e.output?{kind:"success",output:e.output}:{kind:"failure",message:`${t}: no output`}}async function mN(t,e,n){let r=n?.apiKey,o=n?.defaultSubagentModel??n?.defaultModel??"sonnet",s=n?.callId,i=typeof t=="object"&&t!==null?t:{},a=iN.parse(i),l=a.writeBriefs??!0,c=a.scope??"all",d=lN(c);if(!e?.sessionId)throw new Error("audit-fit requires a parent session with sessionId");let u=e.sessionId,p=ce("audit-fit"),f={skill:p["01-skill-inspector.md"],command:p["02-command-inspector.md"],agent:p["03-agent-inspector.md"],hook:p["04-hook-inspector.md"]};for(let C of jk)if(!f[C])throw new Error(`audit-fit skill missing inspector prompt for ${C}`);let m=d.runUserDiscovery?Dk():[],g=d.runPluginDiscovery?Fk():[],h={skill:[],command:[],agent:[]};for(let C of[...m,...g])h[C.type].push(C);let w=new Q({apiKey:r,...n?.defaultModel!==void 0?{parentModel:n.defaultModel}:{},...n?.traceWriter!==void 0?{traceWriter:n.traceWriter}:{}}),v=Ek(Zt.allowedTools),E=()=>async C=>v.has(C)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${C} not allowed for audit-fit inspectors. Allowed tools: ${[...v].join(", ")}`},k=[];for(let C of aN){let $=h[C];if($.length===0)continue;let O=f[C];O&&k.push({type:C,prompt:`${O}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-afk",
3
- "version": "5.81.4",
3
+ "version": "5.81.6",
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",