zcode-app-cli 4.0.0-49 → 4.0.0-51

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/vendor/zcode.cjs CHANGED
@@ -14348,14 +14348,14 @@ ${HBn}`,...v===void 0?{}:{causalityGraph:v}};let I=KGo(n,b?.path),R=await x.subm
14348
14348
  `)}function Qtc(e){let t=Fse.safeParse(e);if(!t.success||t.data.script===void 0)return{gate:"ask"};let n=uJo(t.data.run_id,t.data.hole_id,t.data.script);if(n===void 0)return{gate:"ask"};let o=yS(n.effectiveScript);if(!o.ok||!Nue(o,n.modelBindings))return{gate:"proceed"};let i=Bz(o,JN);return{gate:"ask",...i?{display:i}:{}}}function enc(e){let t=dyn.safeParse(e);return t.success?t.data.response:"FillWorkflowHole returned an invalid result."}var fJo,ZBn,yRt,Xtc,mJo,hJo=V(()=>{"use strict";fJo=bi(require("node:path"),1);vn();mRt();XGo();KBn();UTe();tAt();DX();Z6();_V();Lue();BW();_Ie();KBn();ZBn=15e3,yRt=24e3;r(Gtc,"fillUnavailableFailure");r(Jtc,"fillRefusalFor");r(Ktc,"writeFillFile");r(Ztc,"formatFillDiagnosticLines");r(pJo,"fillBlock");r(Ytc,"compileFailureResponse");Xtc=r(async(e,t)=>{let n=Fse.parse(e),o=t.dynamicWorkflowRunPort;if(o===void 0||typeof o.fillHole!="function")return Gtc();let i=n.script;if(i===void 0)return{result:!1,errorCode:Y6.BODY_UNAVAILABLE,message:"workflow_fill_body_unavailable: the call reached the handler without a resolved body. Pass `script` or `path`. Nothing was filled."};let a=t.workingDirectory,c;if(n.path===void 0){let k=await Ktc(n,i,o,a);k!==void 0&&(c={kind:"draft",described:ow(k,a??"")},await zTe(t,{path:k,source:i,toolName:"FillWorkflowHole"}))}else c={kind:"path",described:ow(n.path,a??"")};let u=await o.fillHole({runId:n.run_id,holeId:n.hole_id,body:i,parentSessionId:t.sessionId,toolCallId:t.toolCallId,trace:e7e(t)});if(!u.ok){if(u.reason!=="compile_failed")return Jtc(u.reason,u.message,n.run_id);lJo(t.sessionId,n.run_id,n.hole_id,i);let k=u.diagnostics??[];return{fill:pJo(n),diagnostics:k.map(x=>({code:x.code,column:x.column,line:x.line,message:x.message})),ok:!1,response:Ytc(n,k,c,a)}}let p=yS(u.scriptText),h=W6(p),_=n.hole?.name??n.hole_id,v=u.phasesAdded.length===0?"It added no phases.":`It added the phase${u.phasesAdded.length===1?"":"s"} ${u.phasesAdded.join(", ")}.`,b=u.scriptPath===void 0?"The run has no draft file, so a later revision must pass the whole script to AmendWorkflow.":`The run's draft ${ow(u.scriptPath,a??"")} now holds the effective script: edit that file and pass \`path\` to AmendWorkflow for any later revision.`;return{fill:pJo(n),diagnostics:[],ok:!0,response:`The fill joined run ${n.run_id} at hole "${_}" (${n.hole_id}); the branch parked there has resumed and the run keeps going in the background. ${v} ${b} Do not wait for the run or poll it with TaskOutput; you will be notified when it completes.`,...h===void 0?{}:{causalityGraph:h}}},"fillWorkflowHoleHandler");r(Qtc,"prepareFillWorkflowHoleApproval");mJo={capability:"Supply the body of a hole a running dynamic-workflow run is waiting at, so the parked branch resumes",metadata:{shouldDefer:!0,name:JN,description:YGo,readOnly:!1,destructive:!1,concurrentSafe:!0,timeoutMs:ZBn,maxOutputBytes:yRt,sideEffectScope:"none",riskLevel:"low",needsApproval:!0},handler:Xtc,validateInput:r(e=>sJo(e),"validateInput"),resolveInput:r(async(e,t)=>{let n=Vz(t,JN);return n||dJo(e,t)},"resolveInput"),prepareApproval:Qtc,inputSchema:r9r,outputSchema:o9r,runtimeInputSchema:Fse,runtimeOutputSchema:dyn,formatModelContent:enc,permission:{permission:"createWorkflow",reason:"fillWorkflowHole.runConfirmation: user must confirm the body that joins the running script",riskLevel:"low",sideEffectScope:"none",needsApproval:!0,patternSources:["toolName"],alwaysAllowPatternSources:["toolName"],denyPriority:"beforeAsk",alwaysAsk:!0,askOptions:{allowAlways:"session"}},resultBudget:{maxInlineBytes:yRt,maxModelBytes:yRt,strategy:"truncate",preview:{maxBytes:yRt,direction:"head"}},timeout:{defaultMs:ZBn,maxMs:ZBn,allowCallOverride:!1},cancellation:{supported:!1,cleanup:"none",userVisibleMessage:"FillWorkflowHole compiles the effective script synchronously and cannot be cancelled"},trace:{required:!0,propagateToAdapters:!0,recordInput:"summary",recordOutput:"summary"}};r(enc,"formatFillWorkflowHoleModelContent")});async function yJo(e,t,n){let o=await t.executionPort?.getBackgroundTask?.(e.taskId),i=o?await tnc(o,e,t,n):await nnc(e.outputFile,n);return{task_id:e.taskId,task_type:e.type,status:e.status,description:e.description,output:i.output,exitCode:o?.result?.exitCode??e.exitCode??null,...i.outputFile?{outputFile:i.outputFile}:{}}}async function tnc(e,t,n,o){let i=e.outputPath??t.outputFile??e.stdoutPersistedOutputPath??e.result?.stdout.artifactPath,a=e.stderrPersistedOutputPath??e.result?.stderr.artifactPath,c=t.status==="running"?v=>rnc(v,n,o.runningOutputPrefixBytes):o.readOutputFile,u=await gJo(i,e.result?.stdout.text??e.stdoutTail??"",c),p=a&&a===u.path?{content:"",path:a}:await gJo(a,e.result?.stderr.text??e.stderrTail??"",c),h=[u.content,p.content].filter(v=>v.length>0).join(`
14349
14349
  `),_=u.path&&(!p.content||p.path===u.path)?u.path:!u.content&&p.path?p.path:void 0;return{output:h,..._?{outputFile:_}:{}}}async function gJo(e,t,n){let o=await n(e);return o.available?{content:o.content,...e?{path:e}:{}}:{content:t}}async function nnc(e,t){let n=await t.readOutputFile(e);return{output:n.content,...e&&n.available?{outputFile:e}:{}}}async function rnc(e,t,n){if(!e)return{available:!1,content:"",truncated:!1};try{YBn(t.abortSignal);let o=await(0,_Jo.open)(e,"r");try{let i=await o.stat(),a=Math.min(i.size,n);if(a===0)return{available:!0,content:"",truncated:!1};let c=Buffer.allocUnsafe(a),u=0;for(;u<a;){let p=await o.read(c,u,a-u,u);if(p.bytesRead===0)break;u+=p.bytesRead}return YBn(t.abortSignal),{available:!0,content:c.subarray(0,u).toString("utf8"),truncated:i.size>u}}finally{await o.close()}}catch(o){if(t.abortSignal.aborted&&YBn(t.abortSignal),o instanceof Error&&o.name==="AbortError")throw o;return{available:!1,content:"",truncated:!1}}}function YBn(e){if(e.aborted)throw new DOMException("Task output wait aborted","AbortError")}var _Jo,vJo=V(()=>{"use strict";_Jo=require("node:fs/promises");r(yJo,"projectBashTask");r(tnc,"projectBashSnapshot");r(gJo,"readBashOutputPart");r(nnc,"projectFallbackTaskFile");r(rnc,"readRunningBashOutputFile");r(YBn,"throwIfAborted")});function SJo(e){let t=e/1024;if(t<1)return`${e} bytes`;if(t<1024)return`${XBn(t)}KB`;let n=t/1024;return n<1024?`${XBn(n)}MB`:`${XBn(n/1024)}GB`}function XBn(e){return e.toFixed(1).replace(/\.0$/,"")}async function n7e(e,t){if(e.type==="local_bash")return yJo(e,t,{readOutputFile:r(o=>wJo(o,t),"readOutputFile"),runningOutputPrefixBytes:inc});if(e.type==="local_agent")return anc(e,t);if(e.type==="local_dynamic_workflow")return snc(e,t);let n=await QBn(e.outputFile,t);return{task_id:e.taskId,task_type:e.type,status:e.status,description:e.description,output:n,...e.outputFile?{outputFile:e.outputFile}:{}}}async function snc(e,t){let n=e.outputFile,o=e.resultText??await QBn(n,t);return{task_id:e.taskId,task_type:e.type,status:e.status,description:e.description,output:o,...n?{outputFile:n}:{},...e.resultText===void 0?{}:{result:e.resultText},...e.error?{error:e.error}:{}}}async function anc(e,t){let n=e.outputFile,o=await QBn(n,t),c=(e.output?.status==="completed"?e.output:void 0)?.content.map(u=>u.text).join(`
14350
14350
  `)||o;return{task_id:e.taskId,task_type:e.type,status:e.status,description:e.description,output:c,...n?{outputFile:n}:{},...e.prompt?{prompt:e.prompt}:{},...c?{result:c}:{},...e.error?{error:e.error}:{},...e.status==="running"?{activity:cnc(e)}:{}}}function cnc(e){let t=Date.now(),n=e.activity?.lastProgressAt??e.startedAt.getTime();return{last_progress_at:new Date(n).toISOString(),no_progress_for_ms:Math.max(0,t-n),running_tools:(e.activity?.runningTools??[]).map(o=>({tool_name:o.toolName,running_for_ms:Math.max(0,t-o.startedAt),...o.summary?{summary:o.summary}:{}})),waiting_for_permission:e.activity?.waitingForPermission??!1}}async function QBn(e,t){return(await wJo(e,t)).content}async function wJo(e,t){if(!e)return{available:!1,content:"",truncated:!1};try{Fue(t.abortSignal);let n=await(0,bJo.open)(e,"r");try{let o=await n.stat(),i=Math.min(o.size,onc);if(i===0)return{available:!0,content:"",truncated:!1};let a=Buffer.allocUnsafe(i),c=o.size-i,u=0;for(;u<i;){let _=await n.read(a,u,i-u,c+u);if(_.bytesRead===0)break;u+=_.bytesRead}Fue(t.abortSignal);let p=o.size-u,h=a.subarray(0,u).toString("utf8");return{available:!0,content:p>0?`[${Math.round(p/1024)}KB of earlier output omitted]
14351
- ${h}`:h,truncated:p>0}}finally{await n.close()}}catch(n){if(t.abortSignal.aborted&&Fue(t.abortSignal),n instanceof Error&&n.name==="AbortError")throw n;return{available:!1,content:"",truncated:!1}}}function Fue(e){if(e.aborted)throw new DOMException("Task output wait aborted","AbortError")}var bJo,onc,inc,kJo=V(()=>{"use strict";bJo=require("node:fs/promises");vJo();onc=8*1024*1024,inc=3e4;r(SJo,"formatCompactFileSize");r(XBn,"trimSingleDecimal");r(n7e,"projectTask");r(snc,"projectDynamicWorkflowTask");r(anc,"projectAgentTask");r(cnc,"projectAgentActivity");r(QBn,"readTaskOutputFile");r(wJo,"readTaskOutputFileSnapshot");r(Fue,"throwIfAborted")});function t3n(e,t){return{result:!1,errorCode:e,message:t}}function mnc(e,t){let n=ije.parse(e);return CJo(n,t.runtimeTaskRegistry)??{result:!0}}function CJo(e,t){if(!e.task_id)return t3n(e3n.TASK_ID_REQUIRED,"Task ID is required");if(t&&!t.get(e.task_id))return t3n(e3n.TASK_NOT_FOUND,`No task found with ID: ${e.task_id}`)}function hnc(e){let t=Tve.parse(e),n=[`<retrieval_status>${t.retrieval_status}</retrieval_status>`],o=t.task;if(o){if(n.push(`<task_id>${o.task_id}</task_id>`),n.push(`<task_type>${o.task_type}</task_type>`),n.push(`<status>${o.status}</status>`),o.exitCode!==void 0&&o.exitCode!==null&&n.push(`<exit_code>${o.exitCode}</exit_code>`),o.output.trim()){let i=(o.outputFile?_nc(o.output,o.outputFile):o.output).trimEnd();n.push(`<output>
14351
+ ${h}`:h,truncated:p>0}}finally{await n.close()}}catch(n){if(t.abortSignal.aborted&&Fue(t.abortSignal),n instanceof Error&&n.name==="AbortError")throw n;return{available:!1,content:"",truncated:!1}}}function Fue(e){if(e.aborted)throw new DOMException("Task output wait aborted","AbortError")}var bJo,onc,inc,kJo=V(()=>{"use strict";bJo=require("node:fs/promises");vJo();onc=8*1024*1024,inc=3e4;r(SJo,"formatCompactFileSize");r(XBn,"trimSingleDecimal");r(n7e,"projectTask");r(snc,"projectDynamicWorkflowTask");r(anc,"projectAgentTask");r(cnc,"projectAgentActivity");r(QBn,"readTaskOutputFile");r(wJo,"readTaskOutputFileSnapshot");r(Fue,"throwIfAborted")});function t3n(e,t){return{result:!1,errorCode:e,message:t}}function mnc(e,t){let n=ije.parse(e);return CJo(n,t.runtimeTaskRegistry)??{result:!0}}function CJo(e,t){if(!e.task_id)return t3n(e3n.TASK_ID_REQUIRED,"Task ID is required");if(t&&!t.get(e.task_id)&&!require(require("node:path").join(__dirname,"cli-config.cjs")).historicalTaskOutput(t,e.task_id))return t3n(e3n.TASK_NOT_FOUND,`No task found with ID: ${e.task_id}`)}function hnc(e){let t=Tve.parse(e),n=[`<retrieval_status>${t.retrieval_status}</retrieval_status>`],o=t.task;if(o){if(n.push(`<task_id>${o.task_id}</task_id>`),n.push(`<task_type>${o.task_type}</task_type>`),n.push(`<status>${o.status}</status>`),o.exitCode!==void 0&&o.exitCode!==null&&n.push(`<exit_code>${o.exitCode}</exit_code>`),o.output.trim()){let i=(o.outputFile?_nc(o.output,o.outputFile):o.output).trimEnd();n.push(`<output>
14352
14352
  ${i}
14353
14353
  </output>`)}o.error&&n.push(`<error>${o.error}</error>`),o.activity&&n.push(gnc(o.activity))}return n.join(`
14354
14354
 
14355
14355
  `)}function gnc(e){let t=["<activity>",`<last_progress_at>${e.last_progress_at}</last_progress_at>`,`<no_progress_for_ms>${Math.floor(e.no_progress_for_ms)}</no_progress_for_ms>`];e.waiting_for_permission&&t.push("<waiting_for_permission>true</waiting_for_permission>");for(let n of e.running_tools)t.push(`<running_tool name="${Bs(n.tool_name)}" running_for_ms="${Math.floor(n.running_for_ms)}">${Bs(n.summary??"")}</running_tool>`);return t.push("</activity>"),t.join(`
14356
14356
  `)}function _nc(e,t,n=process.env.TASK_MAX_OUTPUT_LENGTH){let o=ync(n);if(e.length<=o)return e;let i=`[Truncated. Full output: ${t}]
14357
14357
 
14358
- `,a=o-i.length;return i+e.slice(-a)}function ync(e=process.env.TASK_MAX_OUTPUT_LENGTH){if(!e)return xJo;let t=Number.parseInt(e,10);return Number.isNaN(t)||t<=0?xJo:Math.min(t,lnc)}function vnc(e){return kTt({content:e.content,formatBytes:SJo,originalBytes:e.content.length,persistedPath:e.persistedPath,previewChars:dnc})}async function bnc(e,t,n){let o=Date.now();for(;Date.now()-o<t;){Fue(n.abortSignal);let i=n.runtimeTaskRegistry?.get(e);if(!i)return;if(!n3n(i.status))return i;await Snc(pnc)}return n.runtimeTaskRegistry?.get(e)}function Snc(e){return new Promise(t=>{setTimeout(t,e)})}function TJo(e,t){t.runtimeTaskRegistry?.update(e.taskId,n=>n.notified?n:{...n,notified:!0})}async function wnc(e){e.emitEvent&&await e.emitEvent({id:crypto.randomUUID(),sessionId:e.sessionId,turnId:e.turnId,type:Je.ToolCallProgress,timestamp:new Date,traceId:e.traceId,sequenceNumber:0,payload:{toolCallId:e.toolCallId,toolName:xve,elapsedMs:0}})}function r7e(e,t){return{retrieval_status:e,task:t}}function knc(e){let t=e.runtimeTaskRegistry;if(t)return t;throw Mr(qn.ConfigurationError,"Runtime task registry is not configured for TaskOutput",{context:{toolCallId:e.toolCallId,toolName:xve},recoverable:!1})}var xJo,lnc,unc,vRt,dnc,pnc,e3n,fnc,IJo,n3n,EJo=V(()=>{"use strict";vn();WL();Cle();kJo();xJo=32e3,lnc=16e4,unc=1e5,vRt=4e5,dnc=2e3,pnc=100,e3n={TASK_ID_REQUIRED:1,TASK_NOT_FOUND:2},fnc=r(async(e,t)=>{let n=ije.parse(e),o=CJo(n,t.runtimeTaskRegistry);if(o)return o;let a=knc(t).get(n.task_id);if(!a)return t3n(e3n.TASK_NOT_FOUND,`No task found with ID: ${n.task_id}`);if(!n.block){if(n3n(a.status))return r7e("not_ready",await n7e(a,t));let p=await n7e(a,t);return Fue(t.abortSignal),TJo(a,t),r7e("success",p)}await wnc(t);let c=await bnc(n.task_id,n.timeout,t);if(!c)return r7e("timeout",null);if(n3n(c.status))return r7e("timeout",await n7e(c,t));let u=await n7e(c,t);return Fue(t.abortSignal),TJo(c,t),r7e("success",u)},"taskOutputHandler"),IJo={aliases:U7r,capability:"read output/logs from a background task",maxModelChars:unc,metadata:{shouldDefer:!0,name:xve,searchHint:"read output/logs from a background task",description:z7r,readOnly:!0,destructive:!1,concurrentSafe:!0,maxOutputBytes:vRt,sideEffectScope:"none",riskLevel:"low",needsApproval:!1},handler:fnc,validateInput:mnc,formatModelContent:hnc,formatPersistedModelContent:vnc,inputSchema:$7r,outputSchema:q7r,runtimeInputSchema:ije,runtimeOutputSchema:Tve,permission:{permission:"taskOutput",reason:"TaskOutput reads a background task from the current runtime",riskLevel:"low",sideEffectScope:"none",needsApproval:!1,patternSources:["toolName","input"],alwaysAllowPatternSources:["toolName"],denyPriority:"beforeAsk"},resultBudget:{maxInlineBytes:vRt,maxModelBytes:vRt,strategy:"artifact",preview:{maxBytes:vRt,direction:"head"},artifact:{enabled:!0,retention:"session"}},resultArtifactContentType:"text/plain",timeout:{kind:"none"},cancellation:{supported:!0,cleanup:"none",userVisibleMessage:"TaskOutput was cancelled while waiting for the task"},trace:{required:!0,propagateToAdapters:!1,recordInput:"summary",recordOutput:"summary"}};r(t3n,"taskOutputFailure");r(mnc,"validateTaskOutputInput");r(CJo,"getTaskOutputInputFailure");r(hnc,"formatTaskOutputModelContent");r(gnc,"formatTaskActivity");r(_nc,"truncateTaskOutput");r(ync,"resolveTaskOutputLength");r(vnc,"formatPersistedTaskOutputModelContent");r(bnc,"waitForTask");r(Snc,"delay");n3n=r(e=>e==="running"||e==="pending","isTaskActive");r(TJo,"markTaskNotified");r(wnc,"emitWaitingProgress");r(r7e,"taskOutputResult");r(knc,"requireRuntimeTaskRegistry")});function Cnc(e){return JSON.stringify(Cve.parse(e))}function r3n(e,t){return{result:!1,errorCode:e,message:t}}function Enc(e,t,n){return Mr(qn.ToolExecutionFailed,e,{context:{...n,code:t,toolName:Ive},recoverable:!0})}var bRt,xnc,Tnc,Inc,AJo,RJo=V(()=>{"use strict";vn();bRt=1e5,xnc="This lookup failure does not mean the task has completed or stopped; use the full task_id returned when the task started to stop it.",Tnc=["","- Stops a running background task by its ID","- Takes a task_id parameter identifying the task to stop","- Returns a success or failure status","- Use this tool when you need to terminate a long-running task",""].join(`
14358
+ `,a=o-i.length;return i+e.slice(-a)}function ync(e=process.env.TASK_MAX_OUTPUT_LENGTH){if(!e)return xJo;let t=Number.parseInt(e,10);return Number.isNaN(t)||t<=0?xJo:Math.min(t,lnc)}function vnc(e){return kTt({content:e.content,formatBytes:SJo,originalBytes:e.content.length,persistedPath:e.persistedPath,previewChars:dnc})}async function bnc(e,t,n){let o=Date.now();for(;Date.now()-o<t;){Fue(n.abortSignal);let i=n.runtimeTaskRegistry?.get(e);if(!i)return;if(!n3n(i.status))return i;await Snc(pnc)}return n.runtimeTaskRegistry?.get(e)}function Snc(e){return new Promise(t=>{setTimeout(t,e)})}function TJo(e,t){t.runtimeTaskRegistry?.update(e.taskId,n=>n.notified?n:{...n,notified:!0})}async function wnc(e){e.emitEvent&&await e.emitEvent({id:crypto.randomUUID(),sessionId:e.sessionId,turnId:e.turnId,type:Je.ToolCallProgress,timestamp:new Date,traceId:e.traceId,sequenceNumber:0,payload:{toolCallId:e.toolCallId,toolName:xve,elapsedMs:0}})}function r7e(e,t){return{retrieval_status:e,task:t}}function knc(e){let t=e.runtimeTaskRegistry;if(t)return t;throw Mr(qn.ConfigurationError,"Runtime task registry is not configured for TaskOutput",{context:{toolCallId:e.toolCallId,toolName:xve},recoverable:!1})}var xJo,lnc,unc,vRt,dnc,pnc,e3n,fnc,IJo,n3n,EJo=V(()=>{"use strict";vn();WL();Cle();kJo();xJo=32e3,lnc=16e4,unc=1e5,vRt=4e5,dnc=2e3,pnc=100,e3n={TASK_ID_REQUIRED:1,TASK_NOT_FOUND:2},fnc=r(async(e,t)=>{let n=ije.parse(e),o=CJo(n,t.runtimeTaskRegistry);if(o)return o;let $zHistory=require(require("node:path").join(__dirname,"cli-config.cjs")).historicalTaskOutput(knc(t),n.task_id),a=knc(t).get(n.task_id)??$zHistory;if(!a)return t3n(e3n.TASK_NOT_FOUND,`No task found with ID: ${n.task_id}`);if(!n.block||a===$zHistory){if(n3n(a.status))return r7e("not_ready",await n7e(a,t));let p=await n7e(a,t);return Fue(t.abortSignal),a!==$zHistory&&TJo(a,t),r7e("success",p)}await wnc(t);let c=await bnc(n.task_id,n.timeout,t);if(!c)return r7e("timeout",null);if(n3n(c.status))return r7e("timeout",await n7e(c,t));let u=await n7e(c,t);return Fue(t.abortSignal),TJo(c,t),r7e("success",u)},"taskOutputHandler"),IJo={aliases:U7r,capability:"read output/logs from a background task",maxModelChars:unc,metadata:{shouldDefer:!0,name:xve,searchHint:"read output/logs from a background task",description:z7r,readOnly:!0,destructive:!1,concurrentSafe:!0,maxOutputBytes:vRt,sideEffectScope:"none",riskLevel:"low",needsApproval:!1},handler:fnc,validateInput:mnc,formatModelContent:hnc,formatPersistedModelContent:vnc,inputSchema:$7r,outputSchema:q7r,runtimeInputSchema:ije,runtimeOutputSchema:Tve,permission:{permission:"taskOutput",reason:"TaskOutput reads a background task from the current runtime",riskLevel:"low",sideEffectScope:"none",needsApproval:!1,patternSources:["toolName","input"],alwaysAllowPatternSources:["toolName"],denyPriority:"beforeAsk"},resultBudget:{maxInlineBytes:vRt,maxModelBytes:vRt,strategy:"artifact",preview:{maxBytes:vRt,direction:"head"},artifact:{enabled:!0,retention:"session"}},resultArtifactContentType:"text/plain",timeout:{kind:"none"},cancellation:{supported:!0,cleanup:"none",userVisibleMessage:"TaskOutput was cancelled while waiting for the task"},trace:{required:!0,propagateToAdapters:!1,recordInput:"summary",recordOutput:"summary"}};r(t3n,"taskOutputFailure");r(mnc,"validateTaskOutputInput");r(CJo,"getTaskOutputInputFailure");r(hnc,"formatTaskOutputModelContent");r(gnc,"formatTaskActivity");r(_nc,"truncateTaskOutput");r(ync,"resolveTaskOutputLength");r(vnc,"formatPersistedTaskOutputModelContent");r(bnc,"waitForTask");r(Snc,"delay");n3n=r(e=>e==="running"||e==="pending","isTaskActive");r(TJo,"markTaskNotified");r(wnc,"emitWaitingProgress");r(r7e,"taskOutputResult");r(knc,"requireRuntimeTaskRegistry")});function Cnc(e){return JSON.stringify(Cve.parse(e))}function r3n(e,t){return{result:!1,errorCode:e,message:t}}function Enc(e,t,n){return Mr(qn.ToolExecutionFailed,e,{context:{...n,code:t,toolName:Ive},recoverable:!0})}var bRt,xnc,Tnc,Inc,AJo,RJo=V(()=>{"use strict";vn();bRt=1e5,xnc="This lookup failure does not mean the task has completed or stopped; use the full task_id returned when the task started to stop it.",Tnc=["","- Stops a running background task by its ID","- Takes a task_id parameter identifying the task to stop","- Returns a success or failure status","- Use this tool when you need to terminate a long-running task",""].join(`
14359
14359
  `),Inc=r(async(e,t)=>{let n=nft.parse(e),o=n.task_id??n.shell_id;if(!o)return r3n(1,"Missing required parameter: task_id");if(!t.backgroundTaskControlPort)throw Mr(qn.ConfigurationError,"Background task control is not configured for TaskStop",{context:{toolCallId:t.toolCallId,toolName:Ive},recoverable:!1});let i=await t.backgroundTaskControlPort.stopBackgroundTask(o,{initiator:"model",strict:!0,traceContext:t.traceContext});if(!i.ok){if(i.reason==="background_task_not_running")return r3n(3,`Task ${o} is not running (status: ${i.status??"unknown"})`);if(i.reason==="background_task_cancel_not_supported")throw Enc(`Task ${o} cannot be stopped`,1,{reason:i.reason,status:i.status,taskId:o,taskType:i.type,toolCallId:t.toolCallId});return r3n(1,`No task found with ID: ${o}. ${xnc}`)}let a=i.type??"background_task";return{message:`Successfully stopped task: ${i.taskId} (${i.command??a})`,task_id:i.taskId,task_type:a,...i.command?{command:i.command}:{}}},"taskStopHandler"),AJo={aliases:["KillShell","KillBash"],capability:"Stop a running background task by ID",metadata:{shouldDefer:!0,name:Ive,searchHint:"kill a running background task",description:Tnc,readOnly:!1,destructive:!1,concurrentSafe:!0,timeoutMs:1e4,maxOutputBytes:bRt,sideEffectScope:"session",riskLevel:"low",needsApproval:!1},handler:Inc,formatModelContent:Cnc,inputSchema:V7r,outputSchema:H7r,runtimeInputSchema:nft,runtimeOutputSchema:Cve,permission:{permission:"backgroundTask.stop",reason:"TaskStop stops a running background task in the current runtime",riskLevel:"low",sideEffectScope:"session",needsApproval:!1,patternSources:["toolName","input"],alwaysAllowPatternSources:["toolName"],denyPriority:"beforeAsk"},resultBudget:{maxInlineBytes:bRt,maxModelBytes:bRt,strategy:"truncate",preview:{maxBytes:bRt,direction:"head"}},timeout:{defaultMs:1e4,maxMs:1e4,allowCallOverride:!1},cancellation:{supported:!0,cleanup:"none",userVisibleMessage:"TaskStop was cancelled before the stop request completed"},trace:{required:!0,propagateToAdapters:!1,recordInput:"summary",recordOutput:"summary"}};r(Cnc,"formatTaskStopModelContent");r(r3n,"taskStopFailure");r(Enc,"taskStopError")});var o7e,SRt,PJo,o3n,OJo,i3n=V(()=>{"use strict";io();o7e="ReadTopicResource",SRt=d.object({inputId:d.string().min(1).max(256).optional().describe("Snapshot inputId from the topic history file; selects only an admitted input in this task."),messageId:d.string().min(1).max(256).describe("Message id of the resource in the topic history file resource index."),index:d.number().int().nonnegative().optional().describe("Resource position inside that message, starting at zero. Defaults to 0.")}).strict(),PJo=d.toJSONSchema(SRt),o3n=d.object({status:d.literal("success"),path:d.string().min(1),fileName:d.string(),mime:d.string(),bytes:d.number().int().nonnegative(),messageId:d.string(),index:d.number().int().nonnegative()}).strict(),OJo=d.toJSONSchema(o3n)});async function DJo(e,t,n){n.abortSignal.throwIfAborted();let o=e.filter(({info:x})=>x.role==="user"&&!x.synthetic),i;for(let{info:x}of o.toReversed()){let I=x.metadata,R=I&&Object.hasOwn(I,"conversationInputIntent")?I.conversationInputIntent:I?.inputIntent;if(R===void 0)continue;let O=Anc.safeParse(R);if(O.success){if(t.inputId&&O.data.sourceCommandId!==t.inputId)continue;i=O.data;break}if(R&&typeof R=="object"&&Reflect.has(R,"botGroupSource")||I&&Object.hasOwn(I,"conversationInputIntent")&&I.inputIntent)break}if(!i)throw new Error("No admitted topic authorization is available for this input");let a=t.index??0;if(t.inputId){let x=i.botGroupSource;if(!(x.topicHistory?x.topicHistory.resourceMessages.some(R=>R.messageId===t.messageId&&a<R.count):!!x.topicContext?.messages.find(R=>R.id===t.messageId)?.attachments?.[a]))throw new Error("Resource is not indexed in the selected history snapshot")}let c=n.topicResourcePort,u=n.artifactStore;if(!c||!u?.writeToolResultBinaryArtifact)throw new Error("Topic attachment retrieval is unavailable on this runtime");let p={signal:n.abortSignal,trace:n.traceContext},h=await c.read({taskId:n.sessionId,inputId:i.sourceCommandId,authorizationId:i.botGroupSource.authorizationId,messageId:t.messageId,resourceIndex:a},p);if(n.abortSignal.throwIfAborted(),!Number.isSafeInteger(h.bytes)||h.bytes<0||h.bytes>qa.attachmentMaxBytes)throw new Error("Invalid topic attachment size");let _=await u.readToolResultArtifact({uri:h.ref,trace:p.trace},p),v=Rnc.exec(_.content);if(!v||v[1]!==h.mime||v[2].length>Math.ceil(qa.attachmentMaxBytes/3)*4)throw new Error("Invalid topic attachment artifact");let b=Buffer.from(v[2],"base64");if(b.length!==h.bytes||b.toString("base64")!==v[2])throw new Error("Topic attachment size or encoding mismatch");n.abortSignal.throwIfAborted();let k=await u.writeToolResultBinaryArtifact({sessionId:n.sessionId,toolCallId:n.toolCallId,toolName:o7e,content:b,contentType:h.mime,retention:"session",trace:p.trace,extension:Pnc.exec(h.fileName)?.[1]?.toLowerCase()??"bin"},p);if(n.abortSignal.throwIfAborted(),!k.path)throw new Error("Topic attachment could not be materialized");return{status:"success",path:k.path,fileName:h.fileName,mime:h.mime,bytes:h.bytes,messageId:t.messageId,index:a}}var Anc,Rnc,Pnc,MJo=V(()=>{"use strict";io();Rd();i3n();Anc=d.object({sourceCommandId:d.string().min(1),botGroupSource:d.object({botId:d.string().min(1),chatId:d.string().min(1),threadId:d.string().min(1),authorizationId:d.string().min(1),topicHistory:d.object({resourceMessages:d.array(d.object({messageId:d.string(),count:d.number().int().positive()}))}).optional(),topicContext:d.object({messages:d.array(d.object({id:d.string(),attachments:d.array(d.unknown()).optional()}))}).optional()})}),Rnc=/^data:([^;,]+);base64,([A-Za-z0-9+/]*={0,2})$/,Pnc=/\.([a-zA-Z0-9]{1,12})$/;r(DJo,"readTopicResourceFromSession")});var s3n,wRt,Onc,a3n,NJo=V(()=>{"use strict";vn();i3n();MJo();s3n=3e5,wRt=4096,Onc=r(async(e,t)=>{let n=SRt.parse(e);if(!t.sessionStore)throw Mr(qn.ConfigurationError,"SessionStorePort is not configured for ReadTopicResource",{context:{toolCallId:t.toolCallId,toolName:o7e},recoverable:!1});let o=await t.sessionStore.messages({sessionID:t.sessionId});return DJo(o,n,t)},"readTopicResourceHandler"),a3n={capability:"Materialize an authorized resource from the current task's archived topic",metadata:{shouldDefer:!0,name:o7e,description:"Download a file or image listed in the current task's topic history resource index to a managed local file.",modelInstructions:["Use only for a resource listed in the topic history file resource index (A1, A2\u2026). Pass its inputId, messageId and index.","The result gives a managed local file path. Read that file with an appropriate tool.","The tool reads only the current task's admitted topic. Missing host capability or authorization is an error, not permission to fetch another URL."],readOnly:!1,destructive:!1,concurrentSafe:!0,timeoutMs:s3n,maxOutputBytes:wRt,sideEffectScope:"session",riskLevel:"low",needsApproval:!1},handler:Onc,inputSchema:PJo,outputSchema:OJo,runtimeInputSchema:SRt,runtimeOutputSchema:o3n,permission:{permission:"session.topic_resource.read",reason:"Download an authorized resource from the current task's topic",riskLevel:"low",sideEffectScope:"session",needsApproval:!1,patternSources:["toolName","input"],alwaysAllowPatternSources:["toolName"],denyPriority:"beforeAsk"},resultBudget:{maxInlineBytes:wRt,maxModelBytes:wRt,strategy:"truncate",preview:{maxBytes:wRt,direction:"head"}},timeout:{defaultMs:s3n,maxMs:s3n,allowCallOverride:!1},cancellation:{supported:!0,cleanup:"none",userVisibleMessage:"ReadTopicResource was cancelled before the resource was saved"},trace:{required:!0,propagateToAdapters:!0,recordInput:"summary",recordOutput:"summary"}}});var LJo,FJo=V(()=>{"use strict";vn();LJo=["Amend an existing dynamic-workflow run with a revised script or revised settings. Starts a NEW run that supersedes the old one and imports its finished work as a cache, so only what you changed is paid for again. Works on ANY run of this project: completed, errored, stopped \u2014 or still running.","","When to use:","- The run errored, or completed but needs one more stage: fix or extend the script and amend. Never rewrite the workflow from scratch with CreateWorkflow.","- The run is STILL RUNNING and is visibly going wrong: amend it NOW, in one call. Do not TaskStop it first and do not wait for it to finish \u2014 this tool stops the running predecessor and starts the revision; the earlier you amend, the less is re-paid.","- The user wants the same workflow with fewer subagents at once, its subagents on another model, or another name: amend with only that field and neither `path` nor `script`.","- To continue a stopped run unchanged, use ResumeWorkflowRun instead.","",`Load the \`${c_}\` skill with the Skill tool before revising a script: it carries the cache rules, what each omitted field keeps, and the confirmation rule. A call that passes \`path\` or \`script\` is refused until that skill has been loaded in this session; a settings-only call is not. Pass \`path\` (the run's script file, edited in place \u2014 the usual form) or \`script\` (the whole revised script inline), never both.`].join(`
14360
14360
  `)});function c3n(e){let t=xj.safeParse(e);return t.success?t.data.script!==void 0&&t.data.path!==void 0?{result:!1,errorCode:Dnc,message:Sqr}:{result:!0}:{result:!0}}function i7e(e,t){let n=t==="record"?`run ${e} has no stored script to keep (it predates script persistence)`:`this host cannot read run ${e}'s stored script`;return{result:!1,errorCode:e1.SCRIPT_UNAVAILABLE,message:`workflow_amend_script_unavailable: ${n}, so the script cannot be omitted here \u2014 pass the whole script as \`script\`, or its file as \`path\`. Nothing was stopped or created.`}}function jue(e,t){if(e===null)return{};let n=e??t;return n===void 0?{}:{max_concurrency:MX(n)}}function kRt(e,t){let n=e.runStatus??"running";return{...e.name===void 0?{}:{name:e.name},status:n,...e.stopReason===void 0?{}:{stop_reason:e.stopReason},owned_by_this_session:t!==void 0&&e.parentSessionId!==void 0&&e.parentSessionId===t}}async function s7e(e){let{model:t,cwd:n,port:o}=e;if(t.path!==void 0){let c=await lV({cwd:n,inputPath:t.path});return c.ok?{result:!0,inherited:!1,described:c.file.described,fields:{script:c.file.script,path:c.file.path,...c.file.bodyLineOffset===0?{}:{script_line_offset:c.file.bodyLineOffset}}}:{result:!1,errorCode:e1.SCRIPT_FILE,message:`workflow_script_file_unreadable: ${c.message} Nothing was stopped or created.`}}if(t.script!==void 0)return{result:!0,inherited:!1,fields:{script:t.script}};if(o===void 0||typeof o.getScript!="function")return i7e(t.run_id,"host");let i=await o.getScript(t.run_id);if(i===void 0||i.length===0)return i7e(t.run_id,"record");let a=await l3n({cwd:n,scriptPath:e.predecessorScriptPath,script:i});return{result:!0,inherited:!0,...a===void 0?{}:{described:a.described},fields:{script:i,...a===void 0?{}:{path:a.path,...a.lineOffset===0?{}:{script_line_offset:a.lineOffset}}}}}async function l3n(e){if(e.scriptPath===void 0)return;let t=await lV({cwd:e.cwd,inputPath:e.scriptPath});if(!(!t.ok||t.file.script!==e.script))return{path:t.file.path,described:t.file.described,lineOffset:t.file.bodyLineOffset}}async function jJo(e){let{port:t,model:n,resolvedScript:o,described:i}=e;if(n.path===void 0||n.max_concurrency!==void 0||n.subagent_model!==void 0||typeof t.getScript!="function")return;let a=await t.getScript(n.run_id);if(!(a===void 0||a!==o))return{result:!1,errorCode:e1.SCRIPT_UNCHANGED,message:`workflow_script_unchanged: ${i??n.path} is byte-for-byte the script run ${n.run_id} was started with, so amending it would repeat that run exactly. Edit the file first, then call AmendWorkflow again with the same \`path\`; to change only the settings, pass them and omit \`path\`; to continue a stopped run under the same script, use ResumeWorkflowRun. Nothing was stopped or created.`}}var e1,Dnc,a7e=V(()=>{"use strict";vn();DTe();OTe();e1={AMEND_UNAVAILABLE:21,MISSING_BOUNDARIES:22,SUBAGENT_MODEL:23,SCRIPT_UNCHANGED:24,SCRIPT_FILE:25,SCRIPT_UNAVAILABLE:26,RETUNE_UNCHANGED:27,RUN_SETTLED:28,NOT_RETUNABLE:29,HELD_ELSEWHERE:30},Dnc=400;r(c3n,"validateAmendWorkflowSource");r(i7e,"scriptUnavailableFailure");r(jue,"resolveAmendMaxConcurrency");r(kRt,"describePredecessor");r(s7e,"resolveAmendScript");r(l3n,"resolveKeptScriptFile");r(jJo,"refuseUnchangedScript")});function u3n(e){return e.max_concurrency!==void 0&&e.script===void 0&&e.path===void 0&&e.subagent_model===void 0&&e.name===void 0}function BJo(e){let{model:t,port:n,predecessor:o}=e;if(!u3n(t)||o.status!=="pending"&&o.status!=="running"||typeof n.retuneConcurrency!="function")return;let i=t.max_concurrency??null,a=n.defaultConcurrency?.(),c=Mnc(t.run_id,i,e.inherited,a);return c!==void 0?c:{result:!0,input:{run_id:t.run_id,max_concurrency:i,predecessor:o}}}function Mnc(e,t,n,o){let i=n??o,a=t===null?o:MX(t);if(!(i===void 0||a===void 0||i!==a))return $Jo(e,i,o)}async function UJo(e,t){let n=t.dynamicWorkflowRunPort;if(n===void 0||typeof n.retuneConcurrency!="function")return;let o=await n.retuneConcurrency({runId:e.run_id,maxConcurrency:e.max_concurrency??null});if(o.ok)return{diagnostics:[],ok:!0,response:Bnc(e.run_id,o),retuned:{runId:e.run_id,maxConcurrency:o.maxConcurrency,previous:o.previous,defaultConcurrency:o.defaultConcurrency}};if(o.reason==="unchanged")return $Jo(e.run_id,o.current,n.defaultConcurrency?.())}async function zJo(e,t){let n=t.dynamicWorkflowRunPort,o=n===void 0?void 0:await n.getTask(e.run_id);if(o===void 0)return Nnc(e.run_id);let i=kRt(o,t.sessionId);if(!gft(i))return i.status==="pending"||i.status==="running"?jnc(e.run_id):Fnc(e.run_id);let a=await s7e({model:e,cwd:t.workingDirectory,port:n,predecessorScriptPath:o.scriptPath});return a.result?{result:!0,input:xj.parse({run_id:e.run_id,...a.fields,...jue(e.max_concurrency,void 0),predecessor:{...i,...a.inherited?{script_inherited:!0}:{}}})}:a}function Nnc(e){let t=aF(e);return{...t,message:`${t.message} Nothing was stopped or created: \`run_id\` pointed at a run that does not exist \u2014 pass an existing run's ID (see ListWorkflowRuns), or start a fresh run with CreateWorkflow.`}}function Lnc(e,t){return e===void 0||e===t?t===void 0?"already runs at the default parallelism":`already runs at the default parallelism (at most ${t} subagents at once)`:e===1?"already runs at most 1 subagent at once":`already runs at most ${e} subagents at once`}function $Jo(e,t,n){return{result:!1,errorCode:e1.RETUNE_UNCHANGED,message:`workflow_retune_unchanged: run ${e} ${Lnc(t,n)}, so there is nothing to change. Nothing was stopped, created or changed \u2014 pass a different \`max_concurrency\`, or a revised script if you meant to amend the run.`}}function Fnc(e){return{result:!1,errorCode:e1.RUN_SETTLED,message:`workflow_run_settled: run ${e} settled before the new parallelism limit could take hold, so there is nothing running to retune. Nothing was stopped, created or changed \u2014 call AmendWorkflow again if you want a new run of it under that limit.`}}function jnc(e){return{result:!1,errorCode:e1.NOT_RETUNABLE,message:`workflow_run_not_retunable: run ${e} is not being executed by this agent, so its parallelism cannot be changed in place. Nothing was stopped, created or changed \u2014 call AmendWorkflow again if you want a new run of it under that limit.`}}function Bnc(e,t){let n=t.maxConcurrency===1?"at most 1 subagent runs at once":`at most ${t.maxConcurrency} subagents run at once`,o=t.maxConcurrency===t.defaultConcurrency?`${n} (the default)`:n;return`Applied to the running run ${e}; ${o}. Run ${e} keeps running under it: nothing was stopped and no new run was started.`}var d3n=V(()=>{"use strict";vn();a7e();DTe();Z6();r(u3n,"isConcurrencyOnlyAmend");r(BJo,"resolveConcurrencyRetuneRoute");r(Mnc,"refuseUnchangedBound");r(UJo,"runConcurrencyRetune");r(zJo,"resolveRetuneFallbackAmend");r(Nnc,"predecessorNotFoundFailure");r(Lnc,"describeBoundInForce");r($Jo,"retuneUnchangedFailure");r(Fnc,"runSettledFailure");r(jnc,"notRetunableFailure");r(Bnc,"retuneResponse")});function p3n(e){let t=aF(e);return{...t,message:`${t.message} Nothing was stopped or created: \`run_id\` pointed at a run that does not exist \u2014 pass an existing run's ID (see ListWorkflowRuns), or start a fresh run with CreateWorkflow.`}}function znc(e){return{result:!1,errorCode:e1.HELD_ELSEWHERE,message:`workflow_run_held_elsewhere: run ${e} is running in another session's process, so this session cannot stop it to start a revision. Nothing was stopped or created. Amend it from the session that started it, or amend it from here once it has ended.`}}async function VJo(e,t){let n=xj.safeParse(e);if(!n.success)return{result:!0,input:e};let o=t.workingDirectory??".",i=t.dynamicWorkflowRunPort;if(i===void 0){let{predecessor:L,max_concurrency:$,subagent_model:z,script_line_offset:q,...W}=n.data,Q=WJo(n.data.subagent_model,void 0,t.modelCatalogPort);if(!Q.result)return Q;let ne=await s7e({model:n.data,cwd:o,port:i,predecessorScriptPath:void 0});return ne.result?{result:!0,input:sRt({...W,...ne.fields,...typeof $=="number"?{max_concurrency:$}:{},...Q.field},t.modelCatalogPort)}:ne}let a=await i.getTask(n.data.run_id);if(a===void 0)return p3n(n.data.run_id);let c=kRt(a,t.sessionId),u=BJo({model:n.data,port:i,predecessor:c,inherited:a.maxConcurrency});if(u!==void 0)return u;if(a.status==="running"&&a.liveInThisProcess===!1)return znc(n.data.run_id);let p=WJo(n.data.subagent_model,a.subagentModel,t.modelCatalogPort);if(!p.result)return p;let h=await s7e({model:n.data,cwd:o,port:i,predecessorScriptPath:a.scriptPath});if(!h.result)return h;let _=await jJo({port:i,model:n.data,resolvedScript:h.fields.script,described:h.described});if(_!==void 0)return _;let{predecessor:v,max_concurrency:b,subagent_model:k,script_line_offset:x,...I}=n.data,R={...I,...h.fields,...jue(n.data.max_concurrency,a.maxConcurrency),...p.field,predecessor:{...c,...h.inherited?{script_inherited:!0}:{}}},O=sRt(R,t.modelCatalogPort,a.modelBindings),j=$nc(O,a,t.modelCatalogPort);return{result:!0,input:j.length===0?O:{...O,predecessor:{...R.predecessor,introduces_providers:j}}}}function $nc(e,t,n){let o=new Set,i=n?.listModels().find(p=>p.current)?.providerId;i!==void 0&&o.add(i);for(let p of[t.subagentModel,...Object.values(t.modelBindings??{})]){let h=qJo(p);h!==void 0&&o.add(h)}let a=e.model_bindings,c=[e.subagent_model,...typeof a=="object"&&a!==null?Object.values(a):[]],u=new Set;for(let p of c){let h=qJo(p);h!==void 0&&!o.has(h)&&u.add(h)}return[...u].sort()}function qJo(e){if(typeof e!="string")return;let t=e.indexOf(Unc);return t>0?e.slice(0,t):void 0}function WJo(e,t,n){let o=f3n(e,t,n);return o.ok?{result:!0,field:o.canonical===void 0?{}:{subagent_model:o.canonical}}:qnc(o.inherited?`This amend inherited the predecessor run's subagent model (\`${o.text}\`), which is no longer usable. ${o.message}
14361
14361
 
@@ -14641,14 +14641,14 @@ ${xZo}
14641
14641
  ${TZo()}`}),...e.totalTokensReminder===!0?[s8n({name:"Total Tokens",source:"total_tokens",cacheHint:"stable",content:`
14642
14642
 
14643
14643
  ${WRt}`})]:[],...kxt(e.envInfo,e.model));let o=qRt({userInstructions:e.userInstructions});o&&t.push(o);let i=zue(e.currentDate);return i&&t.push(i),t}function Yic(e){return[...e.filter(t=>t.injectionTarget==="system"),...e.filter(t=>t.injectionTarget==="meta_user")]}function s8n(e){return{...e,injectionTarget:"system",chars:e.content.length,tokens:hf(e.content),preview:e.content.slice(0,100)}}function Xic(e){return{workingDirectory:e.envInfo.cwd,envInfo:e.envInfo,model:e.model,currentDate:e.currentDate}}var Kic,a8n,IZo=V(()=>{"use strict";Z3n();NRt();v7e();WY();y7e();S7e();sI();i8n();Kic={type:"ephemeral"},a8n=class extends w7e{static{r(this,"SubagentContextBuilder")}subagentConfig;constructor(t){super(Xic(t)),this.subagentConfig=t}setEnvInfo(t){return this.subagentConfig={...this.subagentConfig,envInfo:t},this}build(){let t=Zic(this.subagentConfig),n=Yic(t),o=n.reduce((u,p)=>u+p.chars,0),i=n.reduce((u,p)=>u+p.tokens,0),a=n.filter(u=>u.injectionTarget==="system"),c=[a.filter(u=>u.source==="cli_prefix"),a.filter(u=>u.source!=="cli_prefix")].filter(u=>u.length>0).map(u=>({role:"system",content:u.map(p=>p.content).join(""),cacheControl:Kic}));return{sections:n,totalChars:o,totalTokens:i,systemMessages:c,metaUserAttachments:J3n(n)}}};r(c8n,"createSubagentContextBuilder");r(Zic,"buildSubagentContextSections");r(Yic,"orderSubagentSections");r(s8n,"createSubagentSection");r(Xic,"toBaseContextBuilderConfig")});function u8n(){return["You are an agent for ZCode CLI. Given the user's message, you should use the tools available to complete the task. Complete the task fully\u2014don't gold-plate, but don't leave it half-done. When you complete the task, respond with a concise report covering what was done and any key findings \u2014 the caller will relay this to the user, so it only needs the essentials.","","Your strengths:","- Searching for code, configurations, and patterns across large codebases","- Analyzing multiple files to understand system architecture","- Investigating complex questions that require exploring many files","- Performing multi-step research tasks","","Guidelines:","- For file searches: search broadly when you don't know where something lives. Use Read when you know the specific file path.","- For analysis: Start broad and narrow down. Use multiple search strategies if the first doesn't yield results.","- Be thorough: Check multiple locations, consider different naming conventions, look for related files.","- NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one.","- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested."].join(`
14644
- `)}var l8n,d8n=V(()=>{"use strict";l8n="general-purpose";r(u8n,"buildGeneralPurposeSystemPrompt")});function p8n(e){return[...Qic,...e??[]]}function Wue(e,t){return O6o(e,p8n(t))}var Qic,cPt=V(()=>{"use strict";vn();Xxe();Qic=[p9,a_];r(p8n,"buildSubagentChildDisallowRules");r(Wue,"filterSubagentChildToolNames")});function esc(e={}){return{name:vV,description:`Read-only search agent for broad fan-out searches \u2014 when answering means sweeping many files, directories, or naming conventions and you only need the conclusion, not the file dumps. It reads excerpts rather than whole files, so it locates code; it doesn't review or audit it. Specify search breadth: "medium" for moderate exploration, "very thorough" for multiple locations and naming conventions.`,color:"cyan",injectAgentsMd:!1,...e.modelSelection?{modelSelection:e.modelSelection}:{},source:"built-in",systemPrompt:"",tools:["Bash","Glob","Grep","Read","WebFetch","WebSearch","TodoWrite"]}}function T7e(e){return e.name===vV&&e.source==="built-in"}function EIe(e,t={}){let n=t.builtInModelSelectionOverrides??{},o=new Map;o.set(lPt,tsc({modelSelection:n[lPt]})),o.set(vV,esc({modelSelection:n[vV]}));for(let i of e)o.set(i.name,i);return Array.from(o.values())}function tsc(e={}){return{name:lPt,description:"General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",color:"blue",injectAgentsMd:!0,...e.modelSelection?{modelSelection:e.modelSelection}:{},source:"built-in",systemPrompt:u8n(),tools:["*"]}}function CZo(e,t={}){let n=T7e(e)?R6o(t):e.tools?Wue(e.tools,e.disallowedTools):void 0,o=typeof n=="string"?n:n?.join(", ");return`- ${e.name}: ${e.description}${o?` (Tools: ${o})`:""}`}var lPt,AIe=V(()=>{"use strict";d8n();aPt();Xze();cPt();To();lPt=l8n;r(esc,"createBuiltInExploreAgentProfile");r(T7e,"isBuiltInExploreAgentProfile");r(EIe,"normalizeAgentProfiles");r(tsc,"createBuiltInGeneralPurposeAgentProfile");r(CZo,"formatAgentProfileForPrompt")});function uPt(e){return yze({agentId:e.agentId,description:e.description,outputFile:e.outputFile,result:e.result,status:e.status,summary:`Agent "${e.description}" ${osc(e)}`,taskId:e.agentId,taskType:"local_agent",toolUseId:e.parentToolCallId,usage:e.status==="completed"?{durationMs:e.totalDurationMs,modelUsage:e.usage,toolUseCount:e.totalToolUseCount,totalTokens:e.totalTokens}:void 0})}function AZo(e){return e.status==="failed"?{status:"failed",error:rsc(RZo(e.error))}:{status:e.status}}function rsc(e){return e.length<=EZo?e:`${VN(e.slice(0,EZo-1))}\u2026`}function RZo(e){return e?.trim()?e:nsc}function osc(e){return e.status==="completed"?"finished":e.status==="failed"?`failed: ${RZo(e.error)}`:e.stoppedBy==="model"?"was stopped by ZCode":e.stoppedBy==="user"?"was stopped by user":"was stopped"}var nsc,EZo,f8n=V(()=>{"use strict";vn();WL();nsc="Unknown error",EZo=2e3;r(uPt,"formatLocalAgentTaskNotification");r(AZo,"localAgentSubagentResult");r(rsc,"boundStructuredError");r(RZo,"failureReason");r(osc,"formatLocalAgentOutcome")});function b8n(e){let t=new Set,n=[],o=new AbortController,i=!1,a,c=r((O,j=!1)=>(t.add(O),O.then(()=>t.delete(O),L=>{t.delete(O),j&&n.push(L)}),O),"track"),u=e.runExploreAgent,p=new Map;e={...e,runExploreAgent:r((O,j)=>{let L=u(O,{...j,signal:j?.signal?AbortSignal.any([j.signal,o.signal]):o.signal});p.set(O.sessionId,L);let $=r(()=>{p.get(O.sessionId)===L&&p.delete(O.sessionId)},"release");return L.then($,$),c(L)},"runExploreAgent")};let h=e.runtimeTaskRegistry??new wxe,_=new Map,v=new Set,b=EIe(e.profiles??[],{builtInModelSelectionOverrides:e.builtInModelSelectionOverrides}),k=r(()=>e.getAgentDefinitions?.().activeAgents??b,"getProfiles"),x=isc(e.autoBackgroundMs),I={async launch(O,j){let{profile:L,request:$}=m8n(k(),O),z=csc($),q=r(()=>I.start(z,{signal:j?.signal,...j?.model?{model:j.model}:{},...j?.modelOverride?{modelOverride:j.modelOverride}:{},...j?.onChildSessionReady?{onChildSessionReady:j.onChildSessionReady}:{}}),"startBackground");if(O.alwaysBackground===!0)return j?.modelOverride?.background==="deny"?I.run(z,j):q();if(O.runInBackground===!0||L.background===!0){if(j?.modelOverride?.background==="deny")throw Mr(qn.ToolExecutionFailed,"Idle-time tasks do not support background agents. Run this agent in the foreground.",{context:{code:d9.BACKGROUND_UNAVAILABLE,agentType:O.agentType,parentToolCallId:O.parentToolCallId},recoverable:!0});return q()}return I.run(z,j)},async run(O,j){let{profile:L,request:$}=m8n(k(),O),z=OZo(e,$,L),q=new Date(z.startedAt);h.register(_8n({isBackgrounded:!1,lifecycle:z,request:$,startedAt:q,status:"running"}));try{await E7e(z,$,"running")}catch(We){throw h.remove(z.agentId),We}let W=j?.modelOverride?.background==="deny",Q=!1,ne=r(()=>Q?h.get(z.agentId)?.isBackgrounded===!0?"wait":h.requestBackground(z.agentId)?(e.logger?.info("Foreground subagent moved to background",{...ia(z.runTraceContext),agentId:z.agentId,event:"subagent.foreground.backgrounded",module:"core.subagent",parentToolCallId:$.parentToolCallId,trigger:ypt}),"wait"):"cancel":"cancel","decideInputPreemption");j?.inputPreemption?.register(ne);let ge=h8n(_,z.agentId,j?.signal,j?.inputPreemption?ne:void 0);W&&v.add(z.agentId);let ie=gsc({abort:ge.abort,lifecycle:z,logger:e.logger,request:$,signal:ge.signal,timeoutMs:e.inactivityTimeoutMs??GK}),ke=g8n(),De=[],Ee;ie.start();let lt=jZo(e,$,z,h,{signal:ge.signal,...j?.model?{model:j.model}:{},...j?.modelOverride?{modelOverride:j.modelOverride}:{}},{reportActivity:ie.reportActivity,onEvent:KZo(z,De)},{onSessionReady:r(async()=>{let We=h.get(z.agentId);if(We?.executionId!==z.executionId||Sh(We))throw ge.signal.throwIfAborted(),new Error(`${vsc}: ${z.agentId}`);Ee=rQ(e,Je.SubagentSpawned,$,z.runTraceContext,{agentId:z.agentId,taskId:z.agentId,executionId:z.executionId,agentType:$.agentType,childSessionId:z.childSessionId,description:$.description,prompt:$.prompt,parentToolCallId:$.parentToolCallId,status:"running",allowedTools:[...y8n(L,e)],model:L.modelSelection?`${L.modelSelection.providerId}/${L.modelSelection.modelId}`:void 0}),await Ee,j?.onChildSessionReady?.({agentId:z.agentId,childSessionId:z.childSessionId,outputFile:z.outputFile}),ge.signal.throwIfAborted(),ke.resolve()},"onSessionReady")});lt.catch(We=>ke.reject(We));try{await DZo(ke.promise,$,z,ge.signal)}catch(We){ie.stop(),ge.abort(We),ge.dispose(),v.delete(z.agentId);let Re=h.get(z.agentId),Me=Re?.executionId===z.executionId;if(Me&&Re.status==="killed")throw dPt(z,$);if(Me&&h.remove(z.agentId),Ee){let Te=Date.now()-z.startedAt,ct=We instanceof Error?Ixe(We):String(We);c(Ee.then(()=>NZo(e,$,z,Te,ct),()=>{}).catch(Ve=>{e.logger?.warn("Startup-stopped subagent terminal event failed",{...ia(z.runTraceContext),agentId:z.agentId,errorMessage:Ve instanceof Error?Ve.message:String(Ve),event:"subagent.startup_stop.terminal_event_failed",module:"core.subagent",parentToolCallId:$.parentToolCallId})}))}throw We}e.logger?.info("Explore subagent spawned",{...ia(z.runTraceContext),agentId:z.agentId,agentType:$.agentType,event:"subagent.spawned",module:"core.subagent",parentToolCallId:$.parentToolCallId,status:"started"});let St=DZo(lt,$,z,ge.signal),Le;try{Le=!W&&x!==void 0?ssc(h,z.agentId,x,ge.signal):void 0;let We=W?void 0:h.waitForBackgroundRequest(z.agentId,{signal:ge.signal}).then(qe=>({kind:qe?"backgrounded":"ignored"}));Q=!W;let Re=Promise.race([St.then(qe=>({completed:qe,kind:"completed"})),...We?[We]:[],...Le?[Le.promise]:[]]),Me;try{Me=await Re}catch(qe){Me={error:qe,kind:"failed"}}if(Q=!1,Me.kind==="backgrounded"||!W&&h.get(z.agentId)?.isBackgrounded===!0){ge.detachParent(),ie.stop();let qe=Me.kind==="failed"?Promise.reject(Me.error):lt;return c(qe.then(ut=>UZo(e,$,z,h,ut)).catch(ut=>zZo(e,$,z,h,ut,De)).finally(ge.dispose),!0),MZo($,z)}if(Me.kind==="failed")throw Me.error;let ct=Me.kind==="completed"?Me.completed:await St;if(h.get(z.agentId)?.executionId===z.executionId&&h.get(z.agentId)?.status==="killed")throw dPt(z,$);Le?.cancel(),ie.stop(),ge.dispose(),v.delete(z.agentId);let Ve=!1;if(h.update(z.agentId,qe=>qe.executionId!==z.executionId||Sh(qe)?qe:(Ve=!0,{...C7e(qe),status:"completed",completedAt:new Date,output:ct.output,usage:{durationMs:ct.output.totalDurationMs,modelUsage:ct.output.usage,toolUseCount:ct.output.totalToolUseCount,totalTokens:ct.output.totalTokens}})),!Ve)throw dPt(z,$);return await qZo(z,$,ct.output),await rQ(e,Je.SubagentStopped,$,z.runTraceContext,{agentId:z.agentId,executionId:z.executionId,agentType:$.agentType,childSessionId:z.childSessionId,parentToolCallId:$.parentToolCallId,status:"completed",totalDurationMs:ct.output.totalDurationMs,totalToolUseCount:ct.output.totalToolUseCount,totalTokens:ct.output.totalTokens}),e.logger?.info("Explore subagent completed",{...ia(z.runTraceContext),agentId:z.agentId,durationMs:ct.output.totalDurationMs,event:"subagent.completed",module:"core.subagent",status:"completed",totalToolUseCount:ct.output.totalToolUseCount,totalTokens:ct.output.totalTokens}),ct.output}catch(We){if(ie.stop(),ge.dispose(),v.delete(z.agentId),h.get(z.agentId)?.executionId===z.executionId&&h.get(z.agentId)?.status==="killed")throw dPt(z,$);if(h.get(z.agentId)?.executionId===z.executionId&&Sh(h.get(z.agentId)))throw We;let Re=Date.now()-z.startedAt,Me=We instanceof Error?Ixe(We):String(We),Te=!1;if(h.update(z.agentId,qe=>qe.executionId!==z.executionId||Sh(qe)?qe:(Te=!0,{...C7e(qe),status:"failed",completedAt:new Date,error:Me,usage:{durationMs:Re}})),!Te)throw We;await WZo(z,$,Me),await NZo(e,$,z,Re,Me);let ct=GZo(De),Ve={agentId:z.agentId,report:k8n(De),totalDurationMs:Math.max(0,Re),totalToolUseCount:Asc(De),...ct?.totalTokens===void 0?{}:{totalTokens:ct.totalTokens}};throw Lp(We)?E_n(We,Ve):E_n(Mr(qn.ToolExecutionFailed,"Explore subagent failed",{cause:We instanceof Error?We:void 0,context:wTt({code:d9.CHILD_RUNTIME_FAILED,agentId:z.agentId,agentType:$.agentType,parentToolCallId:$.parentToolCallId},Ile.Wrapper),recoverable:!0}),Ve)}finally{ie.stop(),Le?.cancel()}},async start(O,j){let{profile:L,request:$}=m8n(k(),O),z=OZo(e,$,L),q=new Date(z.startedAt),W=MZo($,z);h.register(_8n({isBackgrounded:!0,lifecycle:z,request:$,startedAt:q,status:"running"}));try{await E7e(z,$,"running")}catch(ge){throw h.remove(z.agentId),ge}let Q=h8n(_,z.agentId);j?.signal?.aborted&&Q.abort(j.signal.reason);let ne=g8n();c(BZo(e,$,z,h,{signal:Q.signal,...j?.model?{model:j.model}:{},...j?.modelOverride?{modelOverride:j.modelOverride}:{}},{onSessionReady:r(async()=>{await rQ(e,Je.SubagentSpawned,$,z.runTraceContext,{agentId:z.agentId,taskId:z.agentId,executionId:z.executionId,agentType:$.agentType,background:!0,childSessionId:z.childSessionId,description:$.description,prompt:$.prompt,parentToolCallId:$.parentToolCallId,status:"running",allowedTools:[...y8n(L,e)],outputFile:z.outputFile,model:L.modelSelection?`${L.modelSelection.providerId}/${L.modelSelection.modelId}`:void 0}),j?.onChildSessionReady?.({agentId:z.agentId,childSessionId:z.childSessionId,outputFile:z.outputFile}),ne.resolve()},"onSessionReady"),onSessionStartFailed:ne.reject},Q.dispose),!0);try{await ne.promise}catch(ge){throw Q.abort(ge),h.remove(z.agentId),ge}return e.logger?.info("Explore subagent background task started",{...ia(z.runTraceContext),agentId:z.agentId,agentType:$.agentType,event:"subagent.background.started",module:"core.subagent",parentToolCallId:$.parentToolCallId,status:"started"}),W},async getTask(O){return h.get(O)},async backgroundTask(O){return v.has(O)||h.requestBackground(O),h.get(O)},async waitForTask(O,j){return h.waitForTerminal(O,{signal:j?.signal})},async stopTask(O,j){if(j?.signal?.aborted)throw j.signal.reason??new Error("Subagent stop aborted");let L=h.get(O);if(!L||L.type!=="local_agent"||j?.expectedExecutionId!==void 0&&L.executionId!==j.expectedExecutionId||Sh(L))return;let $=bsc(h,L,j?.initiator);if(!$)return;let z=_.get(O),q=!1;if(h.update(O,Q=>Q!==$.previousTask||Sh(Q)?Q:(q=!0,$.task)),!q)return;let W=r(()=>{z?.abort(new Error(`${bV.message}: ${O}`)),_.get(O)===z&&_.delete(O)},"abortTask");try{return await Ssc(e,h,$,W)}finally{W()}},async sendMessage(O,j){return usc(e,k,h,_,O,j,c,L=>p.has(L))}},R=r(O=>(...j)=>i?Promise.reject(new Error("Subagent owner is closed")):c(O(...j)),"admit");return{...I,launch:R(I.launch),run:R(I.run),start:R(I.start),sendMessage:R(I.sendMessage),close:r(()=>(i=!0,a??=(async()=>{let O=await Promise.allSettled(Object.values(h.all()).filter(L=>L.type==="local_agent"&&!Sh(L)).map(L=>I.stopTask(L.taskId)));o.abort(new Error("Session runtime closed"));for(let L of _.values())L.abort(o.signal.reason);for(;t.size>0;)await Promise.allSettled(t);let j=[...n];try{await e.closeOwnedRuntimes?.()}catch(L){j.push(L)}for(let L of O)L.status==="rejected"&&j.push(L.reason);if(j.length>0)throw new AggregateError(j,"Subagent cleanup failed")})().catch(O=>{throw a=void 0,O}),a),"close")}}function h8n(e,t,n,o){let i=new AbortController;e.set(t,i);let a=r(()=>{let p=n?.reason;vpt(p)&&o?.()==="wait"||i.abort(p??new Error(`Subagent task aborted: ${t}`))},"onParentAbort");n?.aborted?a():n?.addEventListener("abort",a,{once:!0});let c=r(()=>{n?.removeEventListener("abort",a)},"detachParent");return{abort:r(p=>i.abort(p),"abort"),detachParent:c,dispose:r(()=>{c(),e.get(t)===i&&e.delete(t)},"dispose"),signal:i.signal}}function isc(e){if(!(typeof e!="number"||!Number.isFinite(e)||e<=0))return Math.trunc(e)}function ssc(e,t,n,o){let i=!1,a,c,u=r(_=>{i||(i=!0,a&&clearTimeout(a),o?.removeEventListener("abort",p),c(_))},"complete"),p=r(()=>{u({kind:"ignored"})},"onAbort"),h=new Promise(_=>{if(c=_,o?.aborted){u({kind:"ignored"});return}a=setTimeout(()=>{u({kind:e.requestBackground(t)?"backgrounded":"ignored"})},n),o?.addEventListener("abort",p,{once:!0})});return{cancel:r(()=>u({kind:"ignored"}),"cancel"),promise:h}}function m8n(e,t){let n=asc(e,t.agentType);if(n.kind==="matched"){let{profile:o}=n;return{profile:o,request:o.name===t.agentType?t:{...t,agentType:o.name}}}throw n.kind==="ambiguous"?Mr(qn.ToolExecutionFailed,[`Agent type '${t.agentType}' is ambiguous`,`matches ${n.matches.join(", ")}`,`Use the exact name: ${n.matches.join(" or ")}`].join(" \u2014 "),{context:{code:d9.UNKNOWN_AGENT_TYPE,agentType:t.agentType,matches:n.matches,parentToolCallId:t.parentToolCallId},recoverable:!0}):Mr(qn.ToolExecutionFailed,`Agent type '${t.agentType}' not found. Available agents: ${n.availableAgentTypes.join(", ")}`,{context:{code:d9.UNKNOWN_AGENT_TYPE,agentType:t.agentType,availableAgentTypes:n.availableAgentTypes,parentToolCallId:t.parentToolCallId},recoverable:!0})}function asc(e,t){let n=e.find(c=>c.name===t);if(n)return{kind:"matched",profile:n};let o=e.map(c=>c.name),i=PZo(t);if(!i)return{availableAgentTypes:o,kind:"not_found"};let a=e.filter(c=>PZo(c.name)===i);return a.length===1?{kind:"matched",profile:a[0]}:a.length>1?{availableAgentTypes:o,kind:"ambiguous",matches:a.map(c=>c.name)}:{availableAgentTypes:o,kind:"not_found"}}function PZo(e){let t=e.trim().normalize("NFKC").toLowerCase().replace(/[\p{White_Space}\p{Pd}_]+/gu,"");return t.length>0?t:void 0}function csc(e){let{alwaysBackground:t,runInBackground:n,...o}=e;return o}function OZo(e,t,n){let o=e.createAgentId?.()??`agent_${crypto.randomUUID()}`,i=h0(`subagent_${o}`),a=Date.now(),c=(0,vS.join)(w8n(e.outputRootDir),t.sessionId,o),u=(0,vS.join)(c,"metadata.json"),p=(0,vS.join)(c,"output.txt"),h=(0,vS.join)(c,"task.output"),_=ik(t.trace,{sessionId:t.sessionId,turnId:t.turnId,attributes:{agentId:o,agentType:t.agentType,parentToolCallId:t.parentToolCallId}}),v=ik(_,{sessionId:i,rootSessionId:_.rootSessionId??t.sessionId,turnId:t.turnId,attributes:{agentId:o,agentType:t.agentType,parentSessionId:t.sessionId,parentToolCallId:t.parentToolCallId}});return{agentId:o,executionId:crypto.randomUUID(),childSessionId:i,metadataFile:u,outputFile:p,taskOutputFile:h,profile:n,startedAt:a,runTraceContext:_,childTraceContext:v}}function lsc(e,t,n,o){if(!o.childSessionId)return;let i=o.agentId,a=o.childSessionId,c=Date.now(),u=o.outputFile?(0,vS.dirname)(o.outputFile):(0,vS.join)(w8n(e.outputRootDir),t.sessionId,i),p=(0,vS.join)(u,"metadata.json"),h=(0,vS.join)(u,"output.txt"),_=(0,vS.join)(u,"task.output"),v=ik(t.trace,{sessionId:t.sessionId,turnId:t.turnId,attributes:{agentId:i,agentType:t.agentType,parentToolCallId:t.parentToolCallId,resumed:!0}}),b=ik(v,{sessionId:a,rootSessionId:v.rootSessionId??t.sessionId,turnId:t.turnId,attributes:{agentId:i,agentType:t.agentType,parentSessionId:t.sessionId,parentToolCallId:t.parentToolCallId,resumed:!0}});return{agentId:i,executionId:crypto.randomUUID(),childSessionId:a,metadataFile:p,outputFile:h,taskOutputFile:_,profile:n,startedAt:c,runTraceContext:v,childTraceContext:b}}async function usc(e,t,n,o,i,a,c,u){if(a?.signal?.aborted)return I7e(i,`SendMessage was aborted for ${i.to}.`);let p=n.get(i.to);if(!p){let _=await fsc(e,i);p=n.get(i.to)??_}if(!p||p.type!=="local_agent")return I7e(i,`No agent named '${i.to}' is reachable.
14645
- Use the agentId returned in the Agent result to message a local agent.`);let h=hsc(i);return Sh(p)?p.childSessionId!==void 0&&u(p.childSessionId)?(e.logger?.info("Refused to resume a local agent whose previous run is still stopping",{...ia(i.trace),agentId:p.agentId,childSessionId:p.childSessionId,event:"subagent.send_message.resume_refused",module:"core.subagent",parentToolCallId:i.parentToolCallId,reason:"previous_run_stopping"}),I7e(i,`Cannot resume local agent ${p.agentId}: its previous run is still stopping. Wait a moment, then send the message again. If this keeps failing, start a new Agent instead.`)):psc(e,t(),n,o,p,i,h,a,c):dsc(n,p,h)}async function dsc(e,t,n){if(t.messageSink)try{let o=await t.messageSink.send(n);return fPt(t,n,o)}catch{return e.queueMessage(t.taskId,n),fPt(t,n,"queued")}return e.queueMessage(t.taskId,n),fPt(t,n,"queued")}async function psc(e,t,n,o,i,a,c,u,p){let h=t.find(R=>R.name===i.agentType);if(!h)return I7e(a,`Cannot resume local agent ${i.agentId}: profile ${i.agentType} is unavailable.`);let _={sessionId:a.sessionId,turnId:a.turnId,parentToolCallId:a.parentToolCallId,agentType:i.agentType,description:i.description,prompt:a.message,workingDirectory:a.workingDirectory,workspaceRoot:a.workspaceRoot,trace:a.trace},v=lsc(e,_,h,i);if(!v)return I7e(a,`Cannot resume local agent ${i.agentId}: missing child session id.`);let b=new Date(v.startedAt),k=i;n.register(_8n({isBackgrounded:!0,lifecycle:v,request:_,startedAt:b,status:"running"}));try{await E7e(v,_,"running",{resumedAt:new Date().toISOString(),resumedFromMessageId:c.id})}catch(R){throw n.register(k),R}let x=h8n(o,v.agentId),I=g8n();p(BZo(e,_,v,n,{signal:x.signal,model:u?.model,modelOverride:u?.modelOverride},{resumeFromStore:!0,onSessionReady:r(async()=>{await rQ(e,Je.SubagentSpawned,_,v.runTraceContext,{agentId:v.agentId,taskId:v.agentId,executionId:v.executionId,agentType:_.agentType,background:!0,childSessionId:v.childSessionId,description:_.description,outputFile:v.outputFile,parentToolCallId:_.parentToolCallId,prompt:_.prompt,resumed:!0,status:"running"}),I.resolve()},"onSessionReady"),onSessionStartFailed:I.reject},x.dispose),!0);try{await I.promise}catch(R){throw x.abort(R),n.register(k),R}return fPt({...i,outputFile:v.outputFile},c,"resumed_background")}async function fsc(e,t){let n=r((u,p={})=>e.logger?.info("Local agent cold restore from run metadata",{...ia(t.trace),agentId:t.to,event:"subagent.send_message.cold_restore",module:"core.subagent",outcome:u,parentToolCallId:t.parentToolCallId,...p}),"log"),o=e.findTranscriptAgentOutputFile?.(t.to);if(!o){n("not_in_transcript");return}let i=await R7e({agentId:t.to,outputFile:o});if(!i){n("no_metadata");return}if(!i.childSessionId||!i.profileId||i.parentSessionId!==t.sessionId){let u=Object.entries({childSessionId:!i.childSessionId,parentSessionId:i.parentSessionId!==t.sessionId,profileId:!i.profileId}).flatMap(([p,h])=>h?[p]:[]);n("metadata_mismatch",{mismatch:u});return}let a=await e.readChildSessionUpdatedAt?.(i.childSessionId);if(e.readChildSessionUpdatedAt&&a===void 0){n("child_session_missing",{childSessionId:i.childSessionId});return}let c=msc(i.status,a);if(!c){n("may_be_running_elsewhere",{childSessionId:i.childSessionId,childUpdatedAt:a});return}return n("snapshot_rebuilt",{childSessionId:i.childSessionId,metadataStatus:i.status,restoredStatus:c}),{taskId:t.to,agentId:t.to,agentType:i.profileId,childSessionId:i.childSessionId,description:i.description??"",isBackgrounded:!0,notified:!0,outputFile:o,parentSessionId:t.sessionId,startedAt:new Date,status:c,taskType:"local_agent",type:"local_agent"}}function msc(e,t){switch(e){case"completed":return"completed";case"failed":return"failed";case"stopped":return"killed";case"running":return t!==void 0&&t<performance.timeOrigin?"failed":void 0}}function hsc(e){return{id:`msg_${crypto.randomUUID()}`,isMeta:!0,message:e.message,origin:{kind:"coordinator",toolCallId:String(e.parentToolCallId)},queuedAt:new Date,summary:e.summary,traceContext:e.trace}}function fPt(e,t,n){let o=n==="queued"?`Message queued for delivery to ${e.agentId} at its next tool round.`:n==="resumed_background"?`Agent "${e.agentId}" was stopped (${e.status}); resumed it in the background with your message. You'll be notified when it finishes. Output: ${e.outputFile}`:`Message ${t.id} was sent to its active turn for local agent ${e.agentId}.`;return{status:"success",messageId:t.id,delivery:n,agentId:e.agentId,taskId:e.taskId,outputFile:e.outputFile,message:o}}function I7e(e,t){return{status:"failed",messageId:`msg_${crypto.randomUUID()}`,agentId:e.to,error:t,message:t}}async function jZo(e,t,n,o,i,a={},c={}){let u=!1,p=r(async()=>{u||(await c.onSessionReady?.(),u=!0)},"notifySessionReady"),h=await e.runExploreAgent({agentId:n.agentId,executionId:n.executionId,agentType:t.agentType,allowedTools:y8n(n.profile,e),get background(){return o.get(n.agentId)?.isBackgrounded===!0},disallowedTools:n.profile.disallowedTools,sessionId:n.childSessionId,description:t.description,maxTurns:n.profile.maxTurns,onEvent:a.onEvent,onSessionReady:p,permissionMode:n.profile.permissionMode,prompt:t.prompt,profile:n.profile,registerMessageSink:_sc(e,n,o),reportActivity:a.reportActivity,resumeFromStore:c.resumeFromStore,systemPrompt:n.profile.systemPrompt,workingDirectory:t.workingDirectory,workspaceRoot:t.workspaceRoot,traceContext:n.childTraceContext},i);await p();let _=GZo(h.events),v=_?.totalTokens,b=Csc(h.events),k=Date.now()-n.startedAt,x={status:"completed",agentId:n.agentId,agentType:t.agentType,description:t.description,prompt:t.prompt,content:[{type:"text",text:Esc(h)}],totalToolUseCount:b,totalDurationMs:k,...v===void 0?{}:{totalTokens:v},..._===void 0?{}:{usage:_}};return{events:h.events,output:x}}function gsc(e){if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)return{reportActivity:r(()=>{},"reportActivity"),start:r(()=>{},"start"),stop:r(()=>{},"stop")};let t=Date.now(),n,o=!1,i=r(()=>{n&&(clearTimeout(n),n=void 0)},"clear"),a=r(()=>{o=!0,i()},"stop"),c=r(()=>{i(),!(o||e.signal.aborted)&&(n=setTimeout(()=>{let p=Date.now()-t,h=Mr(qn.ToolTimeout,`Subagent was inactive for ${e.timeoutMs}ms`,{context:{code:d9.CHILD_RUNTIME_FAILED,agentId:e.lifecycle.agentId,agentType:e.request.agentType,idleMs:p,parentToolCallId:e.request.parentToolCallId,timeoutMs:e.timeoutMs},recoverable:!0,retryable:!0});e.logger?.warn("Explore subagent activity watchdog fired",{...ia(e.lifecycle.runTraceContext),agentId:e.lifecycle.agentId,agentType:e.request.agentType,event:"subagent.activity_timeout",idleMs:p,module:"core.subagent",parentToolCallId:e.request.parentToolCallId,status:"failed",timeoutMs:e.timeoutMs}),e.abort(h)},e.timeoutMs))},"schedule"),u=r(()=>{t=Date.now(),c()},"reportActivity");return{reportActivity:u,start:u,stop:a}}function DZo(e,t,n,o){return o?new Promise((i,a)=>{let c=!1,u=r(h=>{c||(c=!0,o.removeEventListener("abort",p),h())},"settle"),p=r(()=>{if(Lp(o.reason)){u(()=>a(o.reason));return}u(()=>a(Mr(qn.ToolCancelled,"Agent was cancelled before the subagent returned findings or background launch completed",{cause:o.reason instanceof Error?o.reason:void 0,context:{code:d9.CHILD_RUNTIME_FAILED,agentId:n.agentId,taskId:n.agentId,executionId:n.executionId,agentType:t.agentType,parentToolCallId:t.parentToolCallId},recoverable:!0})))},"abortHandler");if(e.then(h=>u(()=>i(h)),h=>u(()=>a(h))),o.aborted){p();return}o.addEventListener("abort",p,{once:!0})}):e}async function BZo(e,t,n,o,i,a={},c){let u=!1,p=[];try{if(Sh(o.get(n.agentId)??{status:"lost"})){a.onSessionStartFailed?.(new Error("Subagent stopped during startup"));return}i?.signal?.throwIfAborted();let h=await jZo(e,t,n,o,i,{onEvent:KZo(n,p)},{...a,onSessionReady:r(async()=>{await a.onSessionReady?.(),u=!0},"onSessionReady")});await UZo(e,t,n,o,h)}catch(h){if(!u){a.onSessionStartFailed?.(h);return}await zZo(e,t,n,o,h,p)}finally{c?.()}}function g8n(){let e,t,n=new Promise((i,a)=>{e=i,t=a}),o=!1;return{promise:n,reject:r(i=>{o||(o=!0,t(i))},"reject"),resolve:r(()=>{o||(o=!0,e())},"resolve")}}function _sc(e,t,n){return o=>{n.update(t.agentId,i=>({...i,messageSink:o})),ysc(e,t,n,o)}}async function ysc(e,t,n,o){let i=n.drainMessages(t.agentId);for(let a=0;a<i.length;a++){let c=i[a];if(c)try{await o.send(c)}catch(u){for(let p of i.slice(a))n.queueMessage(t.agentId,p);e.logger?.warn("Failed to flush pending subagent message",{...ia(t.runTraceContext),agentId:t.agentId,errorMessage:u instanceof Error?u.message:String(u),event:"subagent.message.flush.failed",module:"core.subagent",status:"failed"});return}}}function _8n(e){return{taskId:e.lifecycle.agentId,executionId:e.lifecycle.executionId,agentId:e.lifecycle.agentId,agentType:e.request.agentType,childSessionId:e.lifecycle.childSessionId,description:e.request.description,isBackgrounded:e.isBackgrounded,outputFile:e.lifecycle.outputFile,parentToolCallId:e.request.parentToolCallId,parentSessionId:e.request.sessionId,prompt:e.request.prompt,startedAt:e.startedAt,status:e.status,taskType:"local_agent",traceContext:e.lifecycle.runTraceContext,type:"local_agent",turnId:e.request.turnId}}function C7e(e){let{messageSink:t,pendingMessages:n,...o}=e;return o}function MZo(e,t){return{status:"async_launched",isAsync:!0,agentId:t.agentId,agentType:e.agentType,description:e.description,prompt:e.prompt,childSessionId:t.childSessionId,backgroundTaskId:t.agentId,outputFile:t.outputFile,canReadOutputFile:e.callerCanReadOutputFile===!0}}async function UZo(e,t,n,o,i){let a=o.get(n.agentId);if(!a||a.executionId!==n.executionId||Sh(a))return;await qZo(n,t,i.output);let c={agentId:i.output.agentId,description:i.output.description,outputFile:n.outputFile,parentToolCallId:String(t.parentToolCallId),result:i.output.content.map(_=>_.text).join(`
14644
+ `)}var l8n,d8n=V(()=>{"use strict";l8n="general-purpose";r(u8n,"buildGeneralPurposeSystemPrompt")});function p8n(e){return[...Qic,...e??[]]}function Wue(e,t){return O6o(e,p8n(t))}var Qic,cPt=V(()=>{"use strict";vn();Xxe();Qic=[p9,a_];r(p8n,"buildSubagentChildDisallowRules");r(Wue,"filterSubagentChildToolNames")});function esc(e={}){return{name:vV,description:`Read-only search agent for broad fan-out searches \u2014 when answering means sweeping many files, directories, or naming conventions and you only need the conclusion, not the file dumps. It reads excerpts rather than whole files, so it locates code; it doesn't review or audit it. Specify search breadth: "medium" for moderate exploration, "very thorough" for multiple locations and naming conventions.`,color:"cyan",injectAgentsMd:!1,...e.modelSelection?{modelSelection:e.modelSelection}:{},source:"built-in",systemPrompt:"",tools:["Bash","Glob","Grep","Read","WebFetch","WebSearch","TodoWrite"]}}function T7e(e){return e.name===vV&&e.source==="built-in"}function EIe(e,t={}){let n=t.builtInModelSelectionOverrides??{},o=new Map;o.set(lPt,tsc({modelSelection:n[lPt]})),o.set(vV,esc({modelSelection:n[vV]}));for(let i of e)o.set(i.name,i);return Array.from(o.values())}function tsc(e={}){return{name:lPt,description:"General-purpose agent for researching complex questions, searching for code, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you.",color:"blue",injectAgentsMd:!0,...e.modelSelection?{modelSelection:e.modelSelection}:{},source:"built-in",systemPrompt:u8n(),tools:["*"]}}function CZo(e,t={}){let n=T7e(e)?R6o(t):e.tools?Wue(e.tools,e.disallowedTools):void 0,o=typeof n=="string"?n:n?.join(", ");return`- ${e.name}: ${e.description}${o?` (Tools: ${o})`:""}`}var lPt,AIe=V(()=>{"use strict";d8n();aPt();Xze();cPt();To();lPt=l8n;r(esc,"createBuiltInExploreAgentProfile");r(T7e,"isBuiltInExploreAgentProfile");r(EIe,"normalizeAgentProfiles");r(tsc,"createBuiltInGeneralPurposeAgentProfile");r(CZo,"formatAgentProfileForPrompt")});function uPt(e){return yze({agentId:e.agentId,description:e.description,outputFile:e.outputFile,result:e.result,status:e.status,summary:`Agent "${e.description}" ${osc(e)}`,taskId:e.agentId,taskType:"local_agent",toolUseId:e.parentToolCallId,usage:e.status==="completed"?{durationMs:e.totalDurationMs,modelUsage:e.usage,toolUseCount:e.totalToolUseCount,totalTokens:e.totalTokens}:void 0})}function AZo(e){return e.status==="failed"?{status:"failed",error:rsc(RZo(e.error))}:{status:e.status}}function rsc(e){return e.length<=EZo?e:`${VN(e.slice(0,EZo-1))}\u2026`}function RZo(e){return e?.trim()?e:nsc}function osc(e){return e.status==="completed"?"finished":e.status==="failed"?`failed: ${RZo(e.error)}`:e.stoppedBy==="model"?"was stopped by ZCode":e.stoppedBy==="user"?"was stopped by user":"was stopped"}var nsc,EZo,f8n=V(()=>{"use strict";vn();WL();nsc="Unknown error",EZo=2e3;r(uPt,"formatLocalAgentTaskNotification");r(AZo,"localAgentSubagentResult");r(rsc,"boundStructuredError");r(RZo,"failureReason");r(osc,"formatLocalAgentOutcome")});function b8n(e){let t=new Set,n=[],o=new AbortController,i=!1,a,c=r((O,j=!1)=>(require(require("node:path").join(__dirname,"cli-config.cjs")).trackSubagentExecution(O),t.add(O),O.then(()=>t.delete(O),L=>{t.delete(O),j&&n.push(L)}),O),"track"),u=e.runExploreAgent,p=new Map;e={...e,runExploreAgent:r((O,j)=>{let L=u(O,{...j,signal:j?.signal?AbortSignal.any([j.signal,o.signal]):o.signal});p.set(O.sessionId,L);let $=r(()=>{p.get(O.sessionId)===L&&p.delete(O.sessionId)},"release");return L.then($,$),c(L)},"runExploreAgent")};let h=e.runtimeTaskRegistry??new wxe,_=new Map,v=new Set,b=EIe(e.profiles??[],{builtInModelSelectionOverrides:e.builtInModelSelectionOverrides}),k=r(()=>e.getAgentDefinitions?.().activeAgents??b,"getProfiles"),x=isc(e.autoBackgroundMs),I={async launch(O,j){let{profile:L,request:$}=m8n(k(),O),z=csc($),q=r(()=>I.start(z,{signal:j?.signal,...j?.model?{model:j.model}:{},...j?.modelOverride?{modelOverride:j.modelOverride}:{},...j?.onChildSessionReady?{onChildSessionReady:j.onChildSessionReady}:{}}),"startBackground");if(O.alwaysBackground===!0)return j?.modelOverride?.background==="deny"?I.run(z,j):q();if(O.runInBackground===!0||L.background===!0){if(j?.modelOverride?.background==="deny")throw Mr(qn.ToolExecutionFailed,"Idle-time tasks do not support background agents. Run this agent in the foreground.",{context:{code:d9.BACKGROUND_UNAVAILABLE,agentType:O.agentType,parentToolCallId:O.parentToolCallId},recoverable:!0});return q()}return I.run(z,j)},async run(O,j){let{profile:L,request:$}=m8n(k(),O),z=OZo(e,$,L),q=new Date(z.startedAt);return require(require("node:path").join(__dirname,"cli-config.cjs")).withSubagentExecution(z,false,async()=>{h.register(_8n({isBackgrounded:!1,lifecycle:z,request:$,startedAt:q,status:"running"}));try{await E7e(z,$,"running")}catch(We){throw h.remove(z.agentId),We}let W=j?.modelOverride?.background==="deny",Q=!1,ne=r(()=>Q?h.get(z.agentId)?.isBackgrounded===!0?"wait":h.requestBackground(z.agentId)?(e.logger?.info("Foreground subagent moved to background",{...ia(z.runTraceContext),agentId:z.agentId,event:"subagent.foreground.backgrounded",module:"core.subagent",parentToolCallId:$.parentToolCallId,trigger:ypt}),"wait"):"cancel":"cancel","decideInputPreemption");j?.inputPreemption?.register(ne);let ge=h8n(_,z.agentId,j?.signal,j?.inputPreemption?ne:void 0);W&&v.add(z.agentId);let ie=gsc({abort:ge.abort,lifecycle:z,logger:e.logger,request:$,signal:ge.signal,timeoutMs:e.inactivityTimeoutMs??GK}),ke=g8n(),De=[],Ee;ie.start();let lt=jZo(e,$,z,h,{signal:ge.signal,...j?.model?{model:j.model}:{},...j?.modelOverride?{modelOverride:j.modelOverride}:{}},{reportActivity:ie.reportActivity,onEvent:KZo(z,De)},{onSessionReady:r(async()=>{let We=h.get(z.agentId);if(We?.executionId!==z.executionId||Sh(We))throw ge.signal.throwIfAborted(),new Error(`${vsc}: ${z.agentId}`);Ee=rQ(e,Je.SubagentSpawned,$,z.runTraceContext,{agentId:z.agentId,taskId:z.agentId,executionId:z.executionId,agentType:$.agentType,childSessionId:z.childSessionId,description:$.description,prompt:$.prompt,parentToolCallId:$.parentToolCallId,status:"running",allowedTools:[...y8n(L,e)],model:L.modelSelection?`${L.modelSelection.providerId}/${L.modelSelection.modelId}`:void 0}),await Ee,j?.onChildSessionReady?.({agentId:z.agentId,childSessionId:z.childSessionId,outputFile:z.outputFile}),ge.signal.throwIfAborted(),ke.resolve()},"onSessionReady")});lt.catch(We=>ke.reject(We));try{await DZo(ke.promise,$,z,ge.signal)}catch(We){ie.stop(),ge.abort(We),ge.dispose(),v.delete(z.agentId);let Re=h.get(z.agentId),Me=Re?.executionId===z.executionId;if(Me&&Re.status==="killed")throw dPt(z,$);if(Me&&h.remove(z.agentId),Ee){let Te=Date.now()-z.startedAt,ct=We instanceof Error?Ixe(We):String(We);c(Ee.then(()=>NZo(e,$,z,Te,ct),()=>{}).catch(Ve=>{e.logger?.warn("Startup-stopped subagent terminal event failed",{...ia(z.runTraceContext),agentId:z.agentId,errorMessage:Ve instanceof Error?Ve.message:String(Ve),event:"subagent.startup_stop.terminal_event_failed",module:"core.subagent",parentToolCallId:$.parentToolCallId})}))}throw We}e.logger?.info("Explore subagent spawned",{...ia(z.runTraceContext),agentId:z.agentId,agentType:$.agentType,event:"subagent.spawned",module:"core.subagent",parentToolCallId:$.parentToolCallId,status:"started"});let St=DZo(lt,$,z,ge.signal),Le;try{Le=!W&&x!==void 0?ssc(h,z.agentId,x,ge.signal):void 0;let We=W?void 0:h.waitForBackgroundRequest(z.agentId,{signal:ge.signal}).then(qe=>({kind:qe?"backgrounded":"ignored"}));Q=!W;let Re=Promise.race([St.then(qe=>({completed:qe,kind:"completed"})),...We?[We]:[],...Le?[Le.promise]:[]]),Me;try{Me=await Re}catch(qe){Me={error:qe,kind:"failed"}}if(Q=!1,Me.kind==="backgrounded"||!W&&h.get(z.agentId)?.isBackgrounded===!0){ge.detachParent(),ie.stop();let qe=Me.kind==="failed"?Promise.reject(Me.error):lt;return c(qe.then(ut=>UZo(e,$,z,h,ut)).catch(ut=>zZo(e,$,z,h,ut,De)).finally(ge.dispose),!0),MZo($,z)}if(Me.kind==="failed")throw Me.error;let ct=Me.kind==="completed"?Me.completed:await St;if(h.get(z.agentId)?.executionId===z.executionId&&h.get(z.agentId)?.status==="killed")throw dPt(z,$);Le?.cancel(),ie.stop(),ge.dispose(),v.delete(z.agentId);let Ve=!1;if(h.update(z.agentId,qe=>qe.executionId!==z.executionId||Sh(qe)?qe:(Ve=!0,{...C7e(qe),status:"completed",completedAt:new Date,output:ct.output,usage:{durationMs:ct.output.totalDurationMs,modelUsage:ct.output.usage,toolUseCount:ct.output.totalToolUseCount,totalTokens:ct.output.totalTokens}})),!Ve)throw dPt(z,$);return await qZo(z,$,ct.output),await rQ(e,Je.SubagentStopped,$,z.runTraceContext,{agentId:z.agentId,executionId:z.executionId,agentType:$.agentType,childSessionId:z.childSessionId,parentToolCallId:$.parentToolCallId,status:"completed",totalDurationMs:ct.output.totalDurationMs,totalToolUseCount:ct.output.totalToolUseCount,totalTokens:ct.output.totalTokens}),e.logger?.info("Explore subagent completed",{...ia(z.runTraceContext),agentId:z.agentId,durationMs:ct.output.totalDurationMs,event:"subagent.completed",module:"core.subagent",status:"completed",totalToolUseCount:ct.output.totalToolUseCount,totalTokens:ct.output.totalTokens}),ct.output}catch(We){if(ie.stop(),ge.dispose(),v.delete(z.agentId),h.get(z.agentId)?.executionId===z.executionId&&h.get(z.agentId)?.status==="killed")throw dPt(z,$);if(h.get(z.agentId)?.executionId===z.executionId&&Sh(h.get(z.agentId)))throw We;let Re=Date.now()-z.startedAt,Me=We instanceof Error?Ixe(We):String(We),Te=!1;if(h.update(z.agentId,qe=>qe.executionId!==z.executionId||Sh(qe)?qe:(Te=!0,{...C7e(qe),status:"failed",completedAt:new Date,error:Me,usage:{durationMs:Re}})),!Te)throw We;await WZo(z,$,Me),await NZo(e,$,z,Re,Me);let ct=GZo(De),Ve={agentId:z.agentId,report:k8n(De),totalDurationMs:Math.max(0,Re),totalToolUseCount:Asc(De),...ct?.totalTokens===void 0?{}:{totalTokens:ct.totalTokens}};throw Lp(We)?E_n(We,Ve):E_n(Mr(qn.ToolExecutionFailed,"Explore subagent failed",{cause:We instanceof Error?We:void 0,context:wTt({code:d9.CHILD_RUNTIME_FAILED,agentId:z.agentId,agentType:$.agentType,parentToolCallId:$.parentToolCallId},Ile.Wrapper),recoverable:!0}),Ve)}finally{ie.stop(),Le?.cancel()}})},async start(O,j){let{profile:L,request:$}=m8n(k(),O),z=OZo(e,$,L),q=new Date(z.startedAt),W=MZo($,z);return require(require("node:path").join(__dirname,"cli-config.cjs")).withSubagentExecution(z,false,async()=>{h.register(_8n({isBackgrounded:!0,lifecycle:z,request:$,startedAt:q,status:"running"}));try{await E7e(z,$,"running")}catch(ge){throw h.remove(z.agentId),ge}let Q=h8n(_,z.agentId);j?.signal?.aborted&&Q.abort(j.signal.reason);let ne=g8n();c(BZo(e,$,z,h,{signal:Q.signal,...j?.model?{model:j.model}:{},...j?.modelOverride?{modelOverride:j.modelOverride}:{}},{onSessionReady:r(async()=>{await rQ(e,Je.SubagentSpawned,$,z.runTraceContext,{agentId:z.agentId,taskId:z.agentId,executionId:z.executionId,agentType:$.agentType,background:!0,childSessionId:z.childSessionId,description:$.description,prompt:$.prompt,parentToolCallId:$.parentToolCallId,status:"running",allowedTools:[...y8n(L,e)],outputFile:z.outputFile,model:L.modelSelection?`${L.modelSelection.providerId}/${L.modelSelection.modelId}`:void 0}),j?.onChildSessionReady?.({agentId:z.agentId,childSessionId:z.childSessionId,outputFile:z.outputFile}),ne.resolve()},"onSessionReady"),onSessionStartFailed:ne.reject},Q.dispose),!0);try{await ne.promise}catch(ge){throw Q.abort(ge),h.remove(z.agentId),ge}return e.logger?.info("Explore subagent background task started",{...ia(z.runTraceContext),agentId:z.agentId,agentType:$.agentType,event:"subagent.background.started",module:"core.subagent",parentToolCallId:$.parentToolCallId,status:"started"}),W})},async getTask(O){return h.get(O)},async backgroundTask(O){return v.has(O)||h.requestBackground(O),h.get(O)},async waitForTask(O,j){return h.waitForTerminal(O,{signal:j?.signal})},async stopTask(O,j){if(j?.signal?.aborted)throw j.signal.reason??new Error("Subagent stop aborted");let L=h.get(O);if(!L||L.type!=="local_agent"||j?.expectedExecutionId!==void 0&&L.executionId!==j.expectedExecutionId||Sh(L))return;let $=bsc(h,L,j?.initiator);if(!$)return;let z=_.get(O),q=!1;if(h.update(O,Q=>Q!==$.previousTask||Sh(Q)?Q:(q=!0,$.task)),!q)return;let W=r(()=>{z?.abort(new Error(`${bV.message}: ${O}`)),_.get(O)===z&&_.delete(O)},"abortTask");try{return await Ssc(e,h,$,W)}finally{W()}},async sendMessage(O,j){return usc(e,k,h,_,O,j,c,L=>p.has(L))}},R=r(O=>(...j)=>i?Promise.reject(new Error("Subagent owner is closed")):c(O(...j)),"admit");return{...I,launch:R(I.launch),run:R(I.run),start:R(I.start),sendMessage:R(I.sendMessage),close:r(()=>(i=!0,a??=(async()=>{let O=await Promise.allSettled(Object.values(h.all()).filter(L=>L.type==="local_agent"&&!Sh(L)).map(L=>I.stopTask(L.taskId)));o.abort(new Error("Session runtime closed"));for(let L of _.values())L.abort(o.signal.reason);for(;t.size>0;)await Promise.allSettled(t);let j=[...n];try{await e.closeOwnedRuntimes?.()}catch(L){j.push(L)}for(let L of O)L.status==="rejected"&&j.push(L.reason);if(j.length>0)throw new AggregateError(j,"Subagent cleanup failed")})().catch(O=>{throw a=void 0,O}),a),"close")}}function h8n(e,t,n,o){let i=new AbortController;e.set(t,i);let a=r(()=>{let p=n?.reason;vpt(p)&&o?.()==="wait"||i.abort(p??new Error(`Subagent task aborted: ${t}`))},"onParentAbort");n?.aborted?a():n?.addEventListener("abort",a,{once:!0});let c=r(()=>{n?.removeEventListener("abort",a)},"detachParent");return{abort:r(p=>i.abort(p),"abort"),detachParent:c,dispose:r(()=>{c(),e.get(t)===i&&e.delete(t)},"dispose"),signal:i.signal}}function isc(e){if(!(typeof e!="number"||!Number.isFinite(e)||e<=0))return Math.trunc(e)}function ssc(e,t,n,o){let i=!1,a,c,u=r(_=>{i||(i=!0,a&&clearTimeout(a),o?.removeEventListener("abort",p),c(_))},"complete"),p=r(()=>{u({kind:"ignored"})},"onAbort"),h=new Promise(_=>{if(c=_,o?.aborted){u({kind:"ignored"});return}a=setTimeout(()=>{u({kind:e.requestBackground(t)?"backgrounded":"ignored"})},n),o?.addEventListener("abort",p,{once:!0})});return{cancel:r(()=>u({kind:"ignored"}),"cancel"),promise:h}}function m8n(e,t){let n=asc(e,t.agentType);if(n.kind==="matched"){let{profile:o}=n;return{profile:o,request:o.name===t.agentType?t:{...t,agentType:o.name}}}throw n.kind==="ambiguous"?Mr(qn.ToolExecutionFailed,[`Agent type '${t.agentType}' is ambiguous`,`matches ${n.matches.join(", ")}`,`Use the exact name: ${n.matches.join(" or ")}`].join(" \u2014 "),{context:{code:d9.UNKNOWN_AGENT_TYPE,agentType:t.agentType,matches:n.matches,parentToolCallId:t.parentToolCallId},recoverable:!0}):Mr(qn.ToolExecutionFailed,`Agent type '${t.agentType}' not found. Available agents: ${n.availableAgentTypes.join(", ")}`,{context:{code:d9.UNKNOWN_AGENT_TYPE,agentType:t.agentType,availableAgentTypes:n.availableAgentTypes,parentToolCallId:t.parentToolCallId},recoverable:!0})}function asc(e,t){let n=e.find(c=>c.name===t);if(n)return{kind:"matched",profile:n};let o=e.map(c=>c.name),i=PZo(t);if(!i)return{availableAgentTypes:o,kind:"not_found"};let a=e.filter(c=>PZo(c.name)===i);return a.length===1?{kind:"matched",profile:a[0]}:a.length>1?{availableAgentTypes:o,kind:"ambiguous",matches:a.map(c=>c.name)}:{availableAgentTypes:o,kind:"not_found"}}function PZo(e){let t=e.trim().normalize("NFKC").toLowerCase().replace(/[\p{White_Space}\p{Pd}_]+/gu,"");return t.length>0?t:void 0}function csc(e){let{alwaysBackground:t,runInBackground:n,...o}=e;return o}function OZo(e,t,n){let o=e.createAgentId?.()??`agent_${crypto.randomUUID()}`,i=h0(`subagent_${o}`),a=Date.now(),c=(0,vS.join)(w8n(e.outputRootDir),t.sessionId,o),u=(0,vS.join)(c,"metadata.json"),p=(0,vS.join)(c,"output.txt"),h=(0,vS.join)(c,"task.output"),_=ik(t.trace,{sessionId:t.sessionId,turnId:t.turnId,attributes:{agentId:o,agentType:t.agentType,parentToolCallId:t.parentToolCallId}}),v=ik(_,{sessionId:i,rootSessionId:_.rootSessionId??t.sessionId,turnId:t.turnId,attributes:{agentId:o,agentType:t.agentType,parentSessionId:t.sessionId,parentToolCallId:t.parentToolCallId}});return{agentId:o,executionId:crypto.randomUUID(),childSessionId:i,metadataFile:u,outputFile:p,taskOutputFile:h,profile:n,startedAt:a,runTraceContext:_,childTraceContext:v}}function lsc(e,t,n,o){if(!o.childSessionId)return;let i=o.agentId,a=o.childSessionId,c=Date.now(),u=o.outputFile?(0,vS.dirname)(o.outputFile):(0,vS.join)(w8n(e.outputRootDir),t.sessionId,i),p=(0,vS.join)(u,"metadata.json"),h=(0,vS.join)(u,"output.txt"),_=(0,vS.join)(u,"task.output"),v=ik(t.trace,{sessionId:t.sessionId,turnId:t.turnId,attributes:{agentId:i,agentType:t.agentType,parentToolCallId:t.parentToolCallId,resumed:!0}}),b=ik(v,{sessionId:a,rootSessionId:v.rootSessionId??t.sessionId,turnId:t.turnId,attributes:{agentId:i,agentType:t.agentType,parentSessionId:t.sessionId,parentToolCallId:t.parentToolCallId,resumed:!0}});return{agentId:i,executionId:crypto.randomUUID(),childSessionId:a,metadataFile:p,outputFile:h,taskOutputFile:_,profile:n,startedAt:c,runTraceContext:v,childTraceContext:b}}async function usc(e,t,n,o,i,a,c,u){if(a?.signal?.aborted)return I7e(i,`SendMessage was aborted for ${i.to}.`);let p=n.get(i.to);if(!p){let _=await fsc(e,i);p=n.get(i.to)??_}if(!p||p.type!=="local_agent")return I7e(i,`No agent named '${i.to}' is reachable.
14645
+ Use the agentId returned in the Agent result to message a local agent.`);let h=hsc(i);return Sh(p)?p.childSessionId!==void 0&&u(p.childSessionId)?(e.logger?.info("Refused to resume a local agent whose previous run is still stopping",{...ia(i.trace),agentId:p.agentId,childSessionId:p.childSessionId,event:"subagent.send_message.resume_refused",module:"core.subagent",parentToolCallId:i.parentToolCallId,reason:"previous_run_stopping"}),I7e(i,`Cannot resume local agent ${p.agentId}: its previous run is still stopping. Wait a moment, then send the message again. If this keeps failing, start a new Agent instead.`)):psc(e,t(),n,o,p,i,h,a,c):dsc(n,p,h)}async function dsc(e,t,n){if(t.messageSink)try{let o=await t.messageSink.send(n);return fPt(t,n,o)}catch{return e.queueMessage(t.taskId,n),fPt(t,n,"queued")}return e.queueMessage(t.taskId,n),fPt(t,n,"queued")}async function psc(e,t,n,o,i,a,c,u,p){let h=t.find(R=>R.name===i.agentType);if(!h)return I7e(a,`Cannot resume local agent ${i.agentId}: profile ${i.agentType} is unavailable.`);let _={sessionId:a.sessionId,turnId:a.turnId,parentToolCallId:a.parentToolCallId,agentType:i.agentType,description:i.description,prompt:a.message,workingDirectory:a.workingDirectory,workspaceRoot:a.workspaceRoot,trace:a.trace},v=lsc(e,_,h,i);if(!v)return I7e(a,`Cannot resume local agent ${i.agentId}: missing child session id.`);let b=new Date(v.startedAt),k=i;return require(require("node:path").join(__dirname,"cli-config.cjs")).withSubagentExecution(v,true,async()=>{n.register(_8n({isBackgrounded:!0,lifecycle:v,request:_,startedAt:b,status:"running"}));try{await E7e(v,_,"running",{resumedAt:new Date().toISOString(),resumedFromMessageId:c.id})}catch(R){throw n.register(k),R}let x=h8n(o,v.agentId),I=g8n();p(BZo(e,_,v,n,{signal:x.signal,model:u?.model,modelOverride:u?.modelOverride},{resumeFromStore:!0,onSessionReady:r(async()=>{await rQ(e,Je.SubagentSpawned,_,v.runTraceContext,{agentId:v.agentId,taskId:v.agentId,executionId:v.executionId,agentType:_.agentType,background:!0,childSessionId:v.childSessionId,description:_.description,outputFile:v.outputFile,parentToolCallId:_.parentToolCallId,prompt:_.prompt,resumed:!0,status:"running"}),I.resolve()},"onSessionReady"),onSessionStartFailed:I.reject},x.dispose),!0);try{await I.promise}catch(R){throw x.abort(R),n.register(k),R}return fPt({...i,outputFile:v.outputFile},c,"resumed_background")})}async function fsc(e,t){let n=r((u,p={})=>e.logger?.info("Local agent cold restore from run metadata",{...ia(t.trace),agentId:t.to,event:"subagent.send_message.cold_restore",module:"core.subagent",outcome:u,parentToolCallId:t.parentToolCallId,...p}),"log"),o=e.findTranscriptAgentOutputFile?.(t.to);if(!o){n("not_in_transcript");return}let i=await R7e({agentId:t.to,outputFile:o});if(!i){n("no_metadata");return}if(!i.childSessionId||!i.profileId||i.parentSessionId!==t.sessionId){let u=Object.entries({childSessionId:!i.childSessionId,parentSessionId:i.parentSessionId!==t.sessionId,profileId:!i.profileId}).flatMap(([p,h])=>h?[p]:[]);n("metadata_mismatch",{mismatch:u});return}let a=await e.readChildSessionUpdatedAt?.(i.childSessionId);if(e.readChildSessionUpdatedAt&&a===void 0){n("child_session_missing",{childSessionId:i.childSessionId});return}let c=i.status==="running"?(require(require("node:path").join(__dirname,"cli-config.cjs")).subagentExecutionState(o,i.childSessionId)==="released"?"failed":void 0):msc(i.status,a);if(!c){n("may_be_running_elsewhere",{childSessionId:i.childSessionId,childUpdatedAt:a});return}return n("snapshot_rebuilt",{childSessionId:i.childSessionId,metadataStatus:i.status,restoredStatus:c}),{taskId:t.to,agentId:t.to,agentType:i.profileId,childSessionId:i.childSessionId,description:i.description??"",isBackgrounded:!0,notified:!0,outputFile:o,parentSessionId:t.sessionId,startedAt:new Date,status:c,taskType:"local_agent",type:"local_agent"}}function msc(e,t){switch(e){case"completed":return"completed";case"failed":return"failed";case"stopped":return"killed";case"running":return t!==void 0&&t<performance.timeOrigin?"failed":void 0}}function hsc(e){return{id:`msg_${crypto.randomUUID()}`,isMeta:!0,message:e.message,origin:{kind:"coordinator",toolCallId:String(e.parentToolCallId)},queuedAt:new Date,summary:e.summary,traceContext:e.trace}}function fPt(e,t,n){let o=n==="queued"?`Message queued for delivery to ${e.agentId} at its next tool round.`:n==="resumed_background"?`Agent "${e.agentId}" was stopped (${e.status}); resumed it in the background with your message. You'll be notified when it finishes. Output: ${e.outputFile}`:`Message ${t.id} was sent to its active turn for local agent ${e.agentId}.`;return{status:"success",messageId:t.id,delivery:n,agentId:e.agentId,taskId:e.taskId,outputFile:e.outputFile,message:o}}function I7e(e,t){return{status:"failed",messageId:`msg_${crypto.randomUUID()}`,agentId:e.to,error:t,message:t}}async function jZo(e,t,n,o,i,a={},c={}){let u=!1,p=r(async()=>{u||(await c.onSessionReady?.(),u=!0)},"notifySessionReady"),h=await e.runExploreAgent({agentId:n.agentId,executionId:n.executionId,agentType:t.agentType,allowedTools:y8n(n.profile,e),get background(){return o.get(n.agentId)?.isBackgrounded===!0},disallowedTools:n.profile.disallowedTools,sessionId:n.childSessionId,description:t.description,maxTurns:n.profile.maxTurns,onEvent:a.onEvent,onSessionReady:p,permissionMode:n.profile.permissionMode,prompt:t.prompt,profile:n.profile,registerMessageSink:_sc(e,n,o),reportActivity:a.reportActivity,resumeFromStore:c.resumeFromStore,systemPrompt:n.profile.systemPrompt,workingDirectory:t.workingDirectory,workspaceRoot:t.workspaceRoot,traceContext:n.childTraceContext},i);await p();let _=GZo(h.events),v=_?.totalTokens,b=Csc(h.events),k=Date.now()-n.startedAt,x={status:"completed",agentId:n.agentId,agentType:t.agentType,description:t.description,prompt:t.prompt,content:[{type:"text",text:Esc(h)}],totalToolUseCount:b,totalDurationMs:k,...v===void 0?{}:{totalTokens:v},..._===void 0?{}:{usage:_}};return{events:h.events,output:x}}function gsc(e){if(!Number.isFinite(e.timeoutMs)||e.timeoutMs<=0)return{reportActivity:r(()=>{},"reportActivity"),start:r(()=>{},"start"),stop:r(()=>{},"stop")};let t=Date.now(),n,o=!1,i=r(()=>{n&&(clearTimeout(n),n=void 0)},"clear"),a=r(()=>{o=!0,i()},"stop"),c=r(()=>{i(),!(o||e.signal.aborted)&&(n=setTimeout(()=>{let p=Date.now()-t,h=Mr(qn.ToolTimeout,`Subagent was inactive for ${e.timeoutMs}ms`,{context:{code:d9.CHILD_RUNTIME_FAILED,agentId:e.lifecycle.agentId,agentType:e.request.agentType,idleMs:p,parentToolCallId:e.request.parentToolCallId,timeoutMs:e.timeoutMs},recoverable:!0,retryable:!0});e.logger?.warn("Explore subagent activity watchdog fired",{...ia(e.lifecycle.runTraceContext),agentId:e.lifecycle.agentId,agentType:e.request.agentType,event:"subagent.activity_timeout",idleMs:p,module:"core.subagent",parentToolCallId:e.request.parentToolCallId,status:"failed",timeoutMs:e.timeoutMs}),e.abort(h)},e.timeoutMs))},"schedule"),u=r(()=>{t=Date.now(),c()},"reportActivity");return{reportActivity:u,start:u,stop:a}}function DZo(e,t,n,o){return o?new Promise((i,a)=>{let c=!1,u=r(h=>{c||(c=!0,o.removeEventListener("abort",p),h())},"settle"),p=r(()=>{if(Lp(o.reason)){u(()=>a(o.reason));return}u(()=>a(Mr(qn.ToolCancelled,"Agent was cancelled before the subagent returned findings or background launch completed",{cause:o.reason instanceof Error?o.reason:void 0,context:{code:d9.CHILD_RUNTIME_FAILED,agentId:n.agentId,taskId:n.agentId,executionId:n.executionId,agentType:t.agentType,parentToolCallId:t.parentToolCallId},recoverable:!0})))},"abortHandler");if(e.then(h=>u(()=>i(h)),h=>u(()=>a(h))),o.aborted){p();return}o.addEventListener("abort",p,{once:!0})}):e}async function BZo(e,t,n,o,i,a={},c){let u=!1,p=[];try{if(Sh(o.get(n.agentId)??{status:"lost"})){a.onSessionStartFailed?.(new Error("Subagent stopped during startup"));return}i?.signal?.throwIfAborted();let h=await jZo(e,t,n,o,i,{onEvent:KZo(n,p)},{...a,onSessionReady:r(async()=>{await a.onSessionReady?.(),u=!0},"onSessionReady")});await UZo(e,t,n,o,h)}catch(h){if(!u){a.onSessionStartFailed?.(h);return}await zZo(e,t,n,o,h,p)}finally{c?.()}}function g8n(){let e,t,n=new Promise((i,a)=>{e=i,t=a}),o=!1;return{promise:n,reject:r(i=>{o||(o=!0,t(i))},"reject"),resolve:r(()=>{o||(o=!0,e())},"resolve")}}function _sc(e,t,n){return o=>{n.update(t.agentId,i=>({...i,messageSink:o})),ysc(e,t,n,o)}}async function ysc(e,t,n,o){let i=n.drainMessages(t.agentId);for(let a=0;a<i.length;a++){let c=i[a];if(c)try{await o.send(c)}catch(u){for(let p of i.slice(a))n.queueMessage(t.agentId,p);e.logger?.warn("Failed to flush pending subagent message",{...ia(t.runTraceContext),agentId:t.agentId,errorMessage:u instanceof Error?u.message:String(u),event:"subagent.message.flush.failed",module:"core.subagent",status:"failed"});return}}}function _8n(e){return{taskId:e.lifecycle.agentId,executionId:e.lifecycle.executionId,agentId:e.lifecycle.agentId,agentType:e.request.agentType,childSessionId:e.lifecycle.childSessionId,description:e.request.description,isBackgrounded:e.isBackgrounded,outputFile:e.lifecycle.outputFile,parentToolCallId:e.request.parentToolCallId,parentSessionId:e.request.sessionId,prompt:e.request.prompt,startedAt:e.startedAt,status:e.status,taskType:"local_agent",traceContext:e.lifecycle.runTraceContext,type:"local_agent",turnId:e.request.turnId}}function C7e(e){let{messageSink:t,pendingMessages:n,...o}=e;return o}function MZo(e,t){return{status:"async_launched",isAsync:!0,agentId:t.agentId,agentType:e.agentType,description:e.description,prompt:e.prompt,childSessionId:t.childSessionId,backgroundTaskId:t.agentId,outputFile:t.outputFile,canReadOutputFile:e.callerCanReadOutputFile===!0}}async function UZo(e,t,n,o,i){let a=o.get(n.agentId);if(!a||a.executionId!==n.executionId||Sh(a))return;await qZo(n,t,i.output);let c={agentId:i.output.agentId,description:i.output.description,outputFile:n.outputFile,parentToolCallId:String(t.parentToolCallId),result:i.output.content.map(_=>_.text).join(`
14646
14646
 
14647
14647
  `),status:"completed",totalDurationMs:i.output.totalDurationMs,totalTokens:i.output.totalTokens,totalToolUseCount:i.output.totalToolUseCount,usage:i.output.usage},u=new Date,p=!1,h=o.update(n.agentId,_=>_.executionId!==n.executionId||Sh(_)?_:(p=!0,{...C7e(_),status:"completed",completedAt:u,output:i.output,usage:{durationMs:i.output.totalDurationMs,modelUsage:i.output.usage,toolUseCount:i.output.totalToolUseCount,totalTokens:i.output.totalTokens}}));p&&(S8n(e,o,n.agentId,c,n.runTraceContext),h&&await $Zo(e,t,n.runTraceContext,h),await rQ(e,Je.SubagentStopped,t,n.runTraceContext,{agentId:n.agentId,executionId:n.executionId,agentType:t.agentType,background:!0,childSessionId:n.childSessionId,parentToolCallId:t.parentToolCallId,status:"completed",outputFile:n.outputFile,totalDurationMs:i.output.totalDurationMs,totalToolUseCount:i.output.totalToolUseCount,totalTokens:i.output.totalTokens}),e.logger?.info("Subagent background task completed",{...ia(n.runTraceContext),agentId:n.agentId,durationMs:i.output.totalDurationMs,event:"subagent.background.completed",module:"core.subagent",status:"completed",totalToolUseCount:i.output.totalToolUseCount,totalTokens:i.output.totalTokens}))}async function zZo(e,t,n,o,i,a){let c=o.get(n.agentId);if(!c||c.executionId!==n.executionId||Sh(c))return;let u=i instanceof Error?Ixe(i):String(i),p=new Date,h=Date.now()-n.startedAt;await WZo(n,t,u);let _={agentId:n.agentId,description:t.description,error:u,outputFile:n.outputFile,parentToolCallId:String(t.parentToolCallId),result:k8n(a),status:"failed",totalDurationMs:h},v=!1,b=o.update(n.agentId,k=>k.executionId!==n.executionId||Sh(k)?k:(v=!0,{...C7e(k),status:"failed",completedAt:p,error:u,usage:{durationMs:h}}));v&&(S8n(e,o,n.agentId,_,n.runTraceContext),b&&await $Zo(e,t,n.runTraceContext,b),await rQ(e,Je.SubagentStopped,t,n.runTraceContext,{agentId:n.agentId,executionId:n.executionId,agentType:t.agentType,background:!0,childSessionId:n.childSessionId,parentToolCallId:t.parentToolCallId,status:"failed",outputFile:n.outputFile,totalDurationMs:h,error:u}),e.logger?.warn("Subagent background task failed",{...ia(n.runTraceContext),agentId:n.agentId,errorMessage:u,event:"subagent.background.failed",module:"core.subagent",status:"failed"}))}function bsc(e,t,n){let o=e.get(t.taskId);if(!o||Sh(o))return;let i=new Date,a=Math.max(0,i.getTime()-o.startedAt.getTime()),c={...C7e(o),status:bV.registryStatus,completedAt:i,error:bV.message,usage:{durationMs:a}},u=xsc(c);return{initiator:n,previousTask:o,task:c,totalDurationMs:a,traceContext:u}}async function Ssc(e,t,n,o){let i={agentId:n.task.agentId,description:n.task.description,outputFile:n.task.outputFile??"",parentToolCallId:String(n.task.parentToolCallId??n.task.taskId),status:bV.notificationStatus,stoppedBy:n.initiator,totalDurationMs:n.totalDurationMs},a=!1,c;try{await Tsc(n.task)}catch(p){c={error:p},e.logger?.warn("Failed to write stopped subagent artifacts",{...ia(n.traceContext),event:"subagent.stop.artifacts.failed",module:"core.subagent",taskId:n.task.taskId,errorMessage:p instanceof Error?p.message:String(p)})}n.previousTask.isBackgrounded&&(o(),a=!S8n(e,t,n.task.taskId,i,n.traceContext));let u=t.get(n.task.taskId);if(!u||u.executionId!==n.task.executionId||u.status!=="killed"){if(c)throw c.error;return n.task}if(n.previousTask.isBackgrounded&&await wsc(e,u,n.traceContext),await ksc(e,u,n.traceContext,n.totalDurationMs),e.logger?.info("Subagent background task stopped",{...ia(n.traceContext),agentId:n.task.agentId,event:"subagent.background.stopped",module:"core.subagent",status:bV.backgroundEventStatus}),c)throw c.error;if(a)throw new Error(`Background agent task stopped notification was not enqueued: ${n.task.taskId}`);return u}async function $Zo(e,t,n,o){Sh(o)&&await rQ(e,Je.BackgroundTaskCompleted,t,n,{taskId:o.taskId,toolCallId:String(t.parentToolCallId),toolName:"Agent",taskKind:"subagent",childSessionId:o.childSessionId,cancellable:!1,description:o.description,status:o.status,startedAt:o.startedAt,completedAt:o.completedAt??new Date,outputPath:o.outputFile,terminalId:o.taskId})}async function wsc(e,t,n){if(!t.parentSessionId)return;let o=xf(Je.BackgroundTaskCompleted,t.parentSessionId,{taskId:t.taskId,toolCallId:String(t.parentToolCallId??t.taskId),toolName:"Agent",taskKind:"subagent",childSessionId:t.childSessionId,cancellable:!1,description:t.description,status:bV.backgroundEventStatus,startedAt:t.startedAt,completedAt:t.completedAt??new Date,outputPath:t.outputFile,terminalId:t.taskId},{turnId:t.turnId,traceId:n.traceId});await e.emitParentEvent(o,n)}async function ksc(e,t,n,o){if(!t.parentSessionId)return;let i=xf(Je.SubagentStopped,t.parentSessionId,{agentId:t.agentId,executionId:t.executionId,agentType:t.agentType,background:t.isBackgrounded===!0,childSessionId:t.childSessionId,parentToolCallId:t.parentToolCallId,status:bV.subagentEventStatus,outputFile:t.outputFile,totalDurationMs:o,error:t.error},{turnId:t.turnId,traceId:n.traceId});await e.emitParentEvent(i,n)}function S8n(e,t,n,o,i){if(!e.enqueueParentTaskNotification)return e.logger?.warn("Skipped subagent background notification without parent queue",{...ia(i),event:"subagent.background.notification.skipped",module:"core.subagent",taskId:n}),!1;let a=t.get(n);if(!a||a.notified)return e.logger?.debug("Skipped duplicate subagent background notification",{...ia(i),event:"subagent.background.notification.duplicate",module:"core.subagent",reason:a?"already_notified":"task_missing",taskId:n}),!1;try{e.enqueueParentTaskNotification({originMeta:{backgroundSource:"subagent",title:a.description.trim()||n,workId:n,subagentResult:AZo(o)},taskId:n,text:uPt(o),traceContext:i})}catch(c){return e.logger?.warn("Failed to enqueue subagent background notification",{...ia(i),errorMessage:c instanceof Error?c.message:String(c),event:"subagent.background.notification.failed",module:"core.subagent",taskId:n}),!1}return t.update(n,c=>c.notified?c:{...c,notified:!0}),e.logger?.info?.("Subagent background notification enqueued",{...ia(i),event:"subagent.background.notification.enqueued",module:"core.subagent",taskId:n}),!0}function xsc(e){return e.traceContext??{traceId:LK(),spanId:`span_${e.taskId}`,sessionId:e.parentSessionId,turnId:e.turnId}}async function rQ(e,t,n,o,i){let a=xf(t,n.sessionId,i,{turnId:n.turnId,traceId:o.traceId});await e.emitParentEvent(a,o)}function NZo(e,t,n,o,i){return rQ(e,Je.SubagentStopped,t,n.runTraceContext,{agentId:n.agentId,executionId:n.executionId,agentType:t.agentType,childSessionId:n.childSessionId,parentToolCallId:t.parentToolCallId,status:"failed",totalDurationMs:o,error:i})}function dPt(e,t){return Mr(qn.ToolCancelled,"Subagent was stopped by user",{context:{agentId:e.agentId,parentToolCallId:t.parentToolCallId},recoverable:!0})}async function qZo(e,t,n){let o=n.content.map(i=>i.text).join(`
14648
14648
 
14649
14649
  `);await VZo(e,o),await E7e(e,t,"completed",{completedAt:new Date().toISOString(),totalDurationMs:n.totalDurationMs,totalTokens:n.totalTokens,totalToolUseCount:n.totalToolUseCount,usage:n.usage})}async function WZo(e,t,n){await VZo(e,n),await E7e(e,t,"failed",{completedAt:new Date().toISOString(),error:n})}async function Tsc(e){if(!e.outputFile)return;let t=(0,vS.dirname)(e.outputFile),n=`${bV.message}
14650
- `;await PIe(e.outputFile,n),await PIe((0,vS.join)(t,"task.output"),n),await PIe((0,vS.join)(t,"metadata.json"),`${JSON.stringify({agentId:e.agentId,childSessionId:e.childSessionId,completedAt:new Date().toISOString(),description:e.description,outputFile:e.outputFile,parentSessionId:e.parentSessionId,parentToolUseId:e.parentToolCallId,profileId:e.agentType,prompt:e.prompt,status:bV.subagentEventStatus,taskOutputFile:(0,vS.join)(t,"task.output"),updatedAt:new Date().toISOString()},null,2)}
14651
- `)}async function VZo(e,t){await PIe(e.outputFile,t),await PIe(e.taskOutputFile,t)}function w8n(e){return e??(0,vS.join)((0,FZo.tmpdir)(),"zcode-agents")}function mPt(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.agentId=="string"&&typeof t.childSessionId=="string"&&typeof t.outputFile=="string"}async function R7e(e){return HZo((0,vS.dirname)(e.outputFile),e.agentId)}async function hPt(e){let t=(0,vS.join)(w8n(e.outputRootDir),e.parentSessionId,e.agentId),n=e.outputFile?[(0,vS.dirname)(e.outputFile),t]:[t];for(let o of new Set(n)){let i=await HZo(o,e.agentId);if(i)return i}}async function HZo(e,t){try{let n=JSON.parse(await(0,OIe.readFile)((0,vS.join)(e,"metadata.json"),"utf8"));if(n.agentId!==t||typeof n.status!="string"||!Isc.has(n.status))return;let o=LZo(n.resumedAt),i=LZo(n.completedAt),a=pPt(n.childSessionId),c=pPt(n.description),u=pPt(n.parentSessionId),p=pPt(n.profileId);return{status:n.status,...o!==void 0?{resumedAt:o}:{},...i!==void 0?{completedAt:i}:{},...a?{childSessionId:a}:{},...c?{description:c}:{},...u?{parentSessionId:u}:{},...p?{profileId:p}:{}}}catch{return}}function pPt(e){return typeof e=="string"&&e.length>0?e:void 0}function LZo(e){if(typeof e!="string")return;let t=Date.parse(e);return Number.isNaN(t)?void 0:t}async function E7e(e,t,n,o={}){await PIe(e.metadataFile,`${JSON.stringify({agentId:e.agentId,childSessionId:e.childSessionId,createdAt:new Date(e.startedAt).toISOString(),cwd:t.workingDirectory,description:t.description,metadataFile:e.metadataFile,outputFile:e.outputFile,parentSessionId:t.sessionId,parentToolUseId:t.parentToolCallId,profileId:t.agentType,profileSnapshot:e.profile,prompt:t.prompt,status:n,taskOutputFile:e.taskOutputFile,updatedAt:new Date().toISOString(),workspaceRoot:t.workspaceRoot,...o},null,2)}
14650
+ `;await PIe(e.outputFile,n),await PIe((0,vS.join)(t,"task.output"),n),await PIe((0,vS.join)(t,"metadata.json"),`${JSON.stringify({agentId:e.agentId,childSessionId:e.childSessionId,executionId:e.executionId,completedAt:new Date().toISOString(),description:e.description,outputFile:e.outputFile,parentSessionId:e.parentSessionId,parentToolUseId:e.parentToolCallId,profileId:e.agentType,prompt:e.prompt,status:bV.subagentEventStatus,taskOutputFile:(0,vS.join)(t,"task.output"),updatedAt:new Date().toISOString()},null,2)}
14651
+ `)}async function VZo(e,t){await PIe(e.outputFile,t),await PIe(e.taskOutputFile,t)}function w8n(e){return e??(0,vS.join)((0,FZo.tmpdir)(),"zcode-agents")}function mPt(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.agentId=="string"&&typeof t.childSessionId=="string"&&typeof t.outputFile=="string"}async function R7e(e){return HZo((0,vS.dirname)(e.outputFile),e.agentId)}async function hPt(e){let t=(0,vS.join)(w8n(e.outputRootDir),e.parentSessionId,e.agentId),n=e.outputFile?[(0,vS.dirname)(e.outputFile),t]:[t];for(let o of new Set(n)){let i=await HZo(o,e.agentId);if(i)return i}}async function HZo(e,t){try{let n=JSON.parse(await(0,OIe.readFile)((0,vS.join)(e,"metadata.json"),"utf8"));if(n.agentId!==t||typeof n.status!="string"||!Isc.has(n.status))return;let o=LZo(n.resumedAt),i=LZo(n.completedAt),a=pPt(n.childSessionId),c=pPt(n.description),u=pPt(n.parentSessionId),p=pPt(n.profileId);return{status:n.status,...o!==void 0?{resumedAt:o}:{},...i!==void 0?{completedAt:i}:{},...a?{childSessionId:a}:{},...c?{description:c}:{},...u?{parentSessionId:u}:{},...p?{profileId:p}:{}}}catch{return}}function pPt(e){return typeof e=="string"&&e.length>0?e:void 0}function LZo(e){if(typeof e!="string")return;let t=Date.parse(e);return Number.isNaN(t)?void 0:t}async function E7e(e,t,n,o={}){await PIe(e.metadataFile,`${JSON.stringify({agentId:e.agentId,childSessionId:e.childSessionId,executionId:e.executionId,createdAt:new Date(e.startedAt).toISOString(),cwd:t.workingDirectory,description:t.description,metadataFile:e.metadataFile,outputFile:e.outputFile,parentSessionId:t.sessionId,parentToolUseId:t.parentToolCallId,profileId:t.agentType,profileSnapshot:e.profile,prompt:t.prompt,status:n,taskOutputFile:e.taskOutputFile,updatedAt:new Date().toISOString(),workspaceRoot:t.workspaceRoot,...o},null,2)}
14652
14652
  `)}function GZo(e){let t;for(let n of e){if(!JZo(n))continue;let o=n.payload;if(!A7e(o)||!A7e(o.usage))continue;let i=o.usage;Qgn(i)&&(t??={},Rsc(t,i))}return t}function JZo(e){return e.type===Je.ModelComplete||e.type===Je.ModelNetworkStatus&&A7e(e.payload)&&e.payload.type==="model_request_failed"}function KZo(e,t){return n=>{n.sessionId===e.childSessionId&&JZo(n)&&t.push(n)}}function Csc(e){let t=0,n=!1;for(let o of e){if(o.type!==Je.TurnComplete||!A7e(o.payload))continue;let i=o.payload.toolCallCount;typeof i!="number"||!Number.isFinite(i)||(n=!0,t+=i)}return n?t:e.filter(o=>o.type===Je.ToolCallResult||o.type===Je.ToolCallError).length}function Esc(e){return e.response.trim().length>0?e.response:k8n(e.events)??e.response}function k8n(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n||!ZZo(n))continue;let o=n.payload.content;if(typeof o=="string"&&o.trim().length>0)return o}}function Asc(e){let t=0;for(let n of e){if(!ZZo(n))continue;let o=n.payload.toolCallCount;typeof o=="number"&&Number.isFinite(o)&&(t+=o)}return t}function ZZo(e){return e.type===Je.ModelComplete&&A7e(e.payload)&&e.payload.querySource===v8n}function Rsc(e,t){RIe(e,"inputTokens",t.inputTokens),RIe(e,"outputTokens",t.outputTokens),RIe(e,"totalTokens",Psc(t)),RIe(e,"cacheReadTokens",t.cacheReadTokens),RIe(e,"cacheWriteTokens",t.cacheWriteTokens),RIe(e,"reasoningTokens",t.reasoningTokens);let n=t.serverToolUse?.webSearchRequests??0,o=t.serverToolUse?.webFetchRequests??0;(n>0||o>0)&&(e.serverToolUse??={},e.serverToolUse.webSearchRequests=(e.serverToolUse.webSearchRequests??0)+n,e.serverToolUse.webFetchRequests=(e.serverToolUse.webFetchRequests??0)+o)}function RIe(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function Psc(e){if(e.totalTokens!==void 0)return e.totalTokens;if(!(e.inputTokens===void 0&&e.outputTokens===void 0&&e.cacheReadTokens===void 0&&e.cacheWriteTokens===void 0))return $K(e)}function A7e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function y8n(e,t){let o=[...(T7e(e)?t.getAllowedTools?.(e)??Vle:e.tools)??[]],i=new Set(e.disallowedTools??[]);return e.skills&&e.skills.length>0&&!i.has("Skill")&&o.push("Skill"),Wue(o,e.disallowedTools)}async function PIe(e,t){await(0,OIe.mkdir)((0,vS.dirname)(e),{recursive:!0}),await(0,OIe.writeFile)(e,t,"utf8")}var OIe,FZo,vS,v8n,bV,vsc,Isc,gPt=V(()=>{"use strict";vn();OIe=require("node:fs/promises"),FZo=require("node:os"),vS=require("node:path");AIe();Xze();f8n();cPt();Tze();bz();v8n="subagent";r(b8n,"createExploreSubagentPort");r(h8n,"createSubagentTaskAbortController");r(isc,"normalizeAutoBackgroundMs");r(ssc,"createAutoBackgroundTimer");r(m8n,"resolveAgentProfileForRequest");r(asc,"resolveAgentProfileByType");r(PZo,"normalizeAgentTypeForMatch");r(csc,"toSubagentExecutionRequest");r(OZo,"createSubagentLifecycle");r(lsc,"createSubagentLifecycleFromTask");r(usc,"sendMessageToLocalAgent");r(dsc,"deliverMessageToRunningAgent");r(psc,"resumeTerminalAgentInBackground");r(fsc,"restoreLocalAgentTaskFromRunMetadata");r(msc,"restoredTaskStatus");r(hsc,"createRuntimeTaskPendingMessage");r(fPt,"createSendMessageSuccess");r(I7e,"createSendMessageFailure");r(jZo,"runAgentToCompletion");r(gsc,"createSubagentActivityWatchdog");r(DZo,"guardSubagentPromiseWithAbort");r(BZo,"runBackgroundAgent");r(g8n,"createSubagentSessionReadyGate");r(_sc,"createMessageSinkRegistration");r(ysc,"flushPendingMessages");r(_8n,"createRuntimeTaskSnapshot");r(C7e,"withoutRuntimeMessageState");r(MZo,"createAgentBackgroundedOutput");r(UZo,"finalizeBackgroundCompletion");r(zZo,"finalizeBackgroundFailure");bV={backgroundEventStatus:"cancelled",message:"Background agent task stopped.",notificationStatus:"killed",registryStatus:"killed",subagentEventStatus:"stopped"},vsc="Subagent stopped before its session was ready";r(bsc,"createBackgroundStoppedTask");r(Ssc,"finalizeBackgroundStopped");r($Zo,"emitBackgroundTaskCompletedEvent");r(wsc,"emitRuntimeTaskBackgroundCompletedEvent");r(ksc,"emitRuntimeTaskSubagentStoppedEvent");r(S8n,"enqueueBackgroundNotification");r(xsc,"traceContextFromRuntimeTask");r(rQ,"emitSubagentEvent");r(NZo,"emitForegroundSubagentFailed");r(dPt,"createSubagentStoppedByUserError");r(qZo,"writeCompletedAgentArtifacts");r(WZo,"writeFailedAgentArtifacts");r(Tsc,"writeStoppedAgentArtifacts");r(VZo,"writeAgentOutputFiles");r(w8n,"resolveAgentOutputRootDir");Isc=new Set(["running","completed","failed","stopped"]);r(mPt,"hasStructuredSubagentFacts");r(R7e,"readSubagentRunMetadata");r(hPt,"readLegacySubagentRunMetadata");r(HZo,"readMetadataIn");r(pPt,"nonEmptyString");r(LZo,"isoTimeMs");r(E7e,"writeAgentMetadataFile");r(GZo,"aggregateModelUsage");r(JZo,"isModelUsageEvent");r(KZo,"collectRunModelEvents");r(Csc,"resolveSubagentToolUseCount");r(Esc,"resolveSubagentReport");r(k8n,"findLatestSubagentStepText");r(Asc,"countSubagentStepToolCalls");r(ZZo,"isSubagentModelStep");r(Rsc,"addUsage");r(RIe,"addOptionalUsageNumber");r(Psc,"resolveTotalTokens");r(A7e,"isRecord");r(y8n,"resolveAllowedTools");r(PIe,"writeTextFile")});var YZo=V(()=>{"use strict";bz()});var x8n=V(()=>{"use strict";aPt();IZo();i8n();d8n();AIe();Xze();gPt();YZo()});function I8n(e,t){let n=e.readOnlyHint===!0,o=e.destructiveHint===!0,i=!n,a=o?"high":n?"low":"medium",c=`the ${e.serverName} app page`,u=[e.title&&e.title!==e.toolName?e.title:void 0,e.description,`(Tool provided by ${c}; available only while the app is open.)`].filter(h=>!!h).join(`
14653
14653
 
14654
14654
  `),p={serverName:e.serverName,toolName:e.toolName,name:e.modelName,inputSchema:e.inputSchema};return{retainExecution:e.retainExecution,capability:`App tool ${e.toolName} provided by ${c}`,inputSchema:Osc(e.inputSchema),outputSchema:C8n,metadata:{concurrentSafe:n||e.idempotentHint===!0,destructive:o,description:u,name:e.modelName,mcpPresentation:{serverName:e.serverName,toolName:e.toolName,...e.description?{description:e.description}:{},pluginId:e.pluginId},needsApproval:i,readOnly:n,riskLevel:a,sideEffectScope:"network",timeoutMs:T8n},permission:{permission:"mcp",reason:`App tool "${e.toolName}" provided by ${c}`,riskLevel:a,sideEffectScope:"network",needsApproval:i,patternSources:["toolName","input"],denyPriority:"beforeAsk",askOptions:{allowAlways:"session"}},resultBudget:{maxInlineBytes:1e5,maxModelBytes:5e4,strategy:"truncate",preview:{direction:"head"}},timeout:{defaultMs:T8n,allowCallOverride:!1},cancellation:{supported:!0,cleanup:"bestEffort",userVisibleMessage:`App tool ${e.modelName} was cancelled`},trace:{required:!0,propagateToAdapters:!1,recordInput:"summary",recordOutput:"summary"},handler:r(async(h,_)=>{let v=h&&typeof h=="object"&&!Array.isArray(h)?h:{},b=await t({definition:e,arguments:v,toolCallId:_.toolCallId},{signal:_.abortSignal});return _It({compressOversizedImages:!1,context:_,descriptor:p,result:b,toolName:e.modelName})},"handler"),formatModelContent:r(h=>E8n(h),"formatModelContent")}}function Osc(e){return{...e,type:"object",properties:e.properties&&typeof e.properties=="object"&&!Array.isArray(e.properties)?e.properties:{}}}var T8n,XZo=V(()=>{"use strict";DD();Uxe();Vue();T8n=ult+WFe+5e3;r(I8n,"createMcpAppProvidedToolEntry");r(Osc,"normalizeObjectSchema")});function A8n(e,t){return`MCP tool is unavailable in the current session: ${e}${t?`. ${t}`:""}`}function QZo(e,t){return new Error(A8n(e,t))}function _Pt(e,t,n,o={}){let i=[];for(let{name:a,descriptor:c,officialCuaAuthorityVerified:u}of D7e(n,o))e.register(yPt(a,c,t,u,{pluginId:o.pluginIdByServerName?.get(c.serverName)},o.resolveLiveDescriptor)),i.push(a);return i}function*D7e(e,t={}){let n=t.allowedTools?new Set(t.allowedTools):void 0,o=Yxe(t.disallowedTools);for(let i of e){let a=t.officialCuaServerNames?.has(i.serverName)===!0,c=pS(i),u=tYo(i,a);n&&!n.has(u)&&!n.has(c)||o?.has(u)||o?.has(c)||(yield{name:u,descriptor:i,officialCuaAuthorityVerified:a,aliases:nYo(u,i,a)})}}function tYo(e,t){return t&&e.serverName===PN?`${O7e}${mk(e.toolName)}`:pS(e)}function yPt(e,t,n,o,i={},a,c){let u=t.annotations?.readOnlyHint===!0,p=t.catalogOnly===!0||t.annotations?.destructiveHint===!0,h=t9(t).includes("model"),_=t.serverName==="node_repl"&&t.toolName==="js",v=zsc(t),b=_?"system":"network",k=_||p?"high":u?"low":"medium",x=!0,I=t.timeoutMs??Dsc,R=o?{maxInlineBytes:256*1024,maxModelBytes:256*1024,strategy:"truncate",preview:{direction:"head"}}:_?{maxInlineBytes:1e6,maxModelBytes:64*1024,strategy:"artifact",preview:{direction:"tail",maxBytes:64*1024},artifact:{enabled:!0,retention:"session"}}:{maxInlineBytes:1e5,maxModelBytes:5e4,strategy:"truncate",preview:{direction:"head"}},O={aliases:nYo(e,t,o),capability:`MCP tool exposed by ${t.serverName}: ${t.toolName}`,...o?{permissionCapabilityGroup:Msc,modelContentProtection:PL}:{},inputSchema:Usc(t,v),outputSchema:C8n,metadata:{shouldDefer:!0,alwaysLoad:t.alwaysLoad,searchHint:t.searchHint,concurrentSafe:u||t.annotations?.idempotentHint===!0,destructive:p,description:t.description,name:e,mcpPresentation:{serverName:t.serverName,toolName:t.toolName,...t.description?{description:t.description}:{},...t.official?{official:!0}:{},...i.pluginId?{pluginId:i.pluginId}:{},...t.ui?{ui:t.ui}:{}},needsApproval:x,...h?{}:{providerVisible:!1},readOnly:u,riskLevel:k,sideEffectScope:b,timeoutMs:I},permission:{permission:"mcp",reason:`MCP tool ${t.serverName}/${t.toolName} executes through an external server`,riskLevel:k,sideEffectScope:b,needsApproval:x,patternSources:["toolName","input","network"],denyPriority:"beforeAsk"},resultBudget:R,timeout:{defaultMs:I,allowCallOverride:!1},cancellation:{supported:!0,cleanup:"bestEffort",userVisibleMessage:`MCP tool ${e} was cancelled`},trace:{required:!0,propagateToAdapters:!0,recordInput:"summary",recordOutput:"summary"},handler:r(async(j,L)=>{if(t.catalogOnly)throw new Error(`MCP tool is unavailable: ${e}`);let $=c?.checkTarget();if($)throw QZo(e,$);let z=Date.now(),q=await n.callTool({serverName:t.serverName,toolName:t.toolName,arguments:Gsc(j,v),trace:{traceId:L.traceId,spanId:L.spanId,parentSpanId:L.parentSpanId,sessionId:L.sessionId,turnId:L.turnId},runtimeScope:L.runtimeScope??"main",workspacePath:L.workingDirectory,...L.remoteSessionId?{remoteSessionId:L.remoteSessionId}:{},...L.workspaceIdentity?.trim()?{workspaceIdentity:L.workspaceIdentity.trim()}:{},workspaceKey:L.workspaceKey??(L.workspaceIdentity?.trim()||L.workingDirectory),...L.turnId?{turnId:L.turnId}:{},clientMode:L.clientMode??"desktop-continuous",deliveryKind:L.deliveryKind??"desktop-continuous"},{signal:L.abortSignal,timeoutMs:I,...L.emitEvent?{onProgress:r(W=>{L.emitEvent?.(jsc(L,e,z,W))},"onProgress")}:{}}).catch(W=>{let Q=L.abortSignal?.aborted?void 0:c?.authorizationReason();throw Q?QZo(e,Q):W});return _It({compressOversizedImages:_,context:L,descriptor:t,preserveOfficialCuaFrames:o,result:q,toolName:e})},"handler"),formatModelContent:r(j=>E8n(j),"formatModelContent")};return a&&(O.resolveForExecution=async({signal:j})=>{let L=await a(t,j);if(L&&"unavailableReason"in L)return{status:"unavailable",message:A8n(e,L.unavailableReason)};let $=L?.descriptor;if(!$||tYo($,o)!==e)return{status:"unavailable",message:A8n(e)};let z=yPt(e,$,n,o,i,void 0,L),q=Fsc(O,z);return q?{status:"unavailable",message:`MCP tool ${e} now has a stricter live ${q} constraint than its registered definition; it was not called. Call it again in the next request.`}:{status:"ready",entry:z}}),O}function Fsc(e,t){if(e.metadata.readOnly&&!t.metadata.readOnly)return"readOnly";if(e.metadata.concurrentSafe&&!t.metadata.concurrentSafe)return"concurrency";if(!e.metadata.destructive&&t.metadata.destructive)return"destructive";if(e.metadata.providerVisible!==!1&&t.metadata.providerVisible===!1)return"visibility"}function jsc(e,t,n,o){let i={toolCallId:e.toolCallId,toolName:t,elapsedMs:Math.max(0,Date.now()-n),progress:o.progress,...o.total!==void 0?{total:o.total}:{},...o.message!==void 0?{message:o.message}:{}};return{id:(0,eYo.randomUUID)(),sessionId:e.sessionId,turnId:e.turnId,type:Je.ToolCallProgress,timestamp:new Date,traceId:e.traceId,sequenceNumber:0,payload:i}}function nYo(e,t,n){if(!n||t.serverName!==PN||!e.startsWith(O7e))return;let o=e.slice(O7e.length);return o.length>0?[`${Lsc}${o}`]:void 0}function Bsc(e){return!e||typeof e!="object"?{type:"object",properties:{},additionalProperties:!0}:{...e,type:"object",properties:e.properties&&typeof e.properties=="object"&&!Array.isArray(e.properties)?e.properties:{}}}function Usc(e,t){let n=Bsc(e.inputSchema);if(!t)return n;let o=n.properties,i=Array.isArray(n.required)?n.required.filter(a=>typeof a=="string"):[];return{...n,properties:{...o,title:Nsc},required:[...new Set([...i,"title"])]}}function zsc(e){if(e.toolName.trim().toLowerCase().replace(/-/g,"_")!=="get_app_state")return!1;let t=e.serverName.trim().toLowerCase().replace(/_/g,"-");return e.serverName===PN||t==="zcode-cua"||t==="computer-use"||t.includes("zcode-cua")&&t.includes("computer-use")}function E8n(e){if(!Vsc(e))return P7e(e);let t=e.content.flatMap($sc);t.length===0&&e.structuredContent!==void 0&&t.push({type:"text",text:`Structured content:
@@ -14824,7 +14824,7 @@ ${xoi}
14824
14824
  `)};let a=yS(o.script),c=a.ok?cRt(a,this.modelCatalogPort):void 0,u=[...a.diagnostics,...c?.unbound??[]];if(!a.ok||u.length>0)return{ok:!1,reason:"compile_failed",message:eDt(`The saved workflow '${o.name}' has errors:`,u)};let p=c?.selections,h=this.dynamicWorkflowRunPort;if(h===void 0)return{ok:!1,reason:"start_failed",message:"dynamic workflow port unavailable"};await this.ensureContextInitialized(t),await this.ensureSessionPersisted(o.name,t),await ZW.call(this,{source:"run_control",traceContext:t});let _=`launch-${(0,Noi.randomUUID)()}`,v=Object.keys(i.args).length>0,b=Zq(),k=W6(a),x=Q8(k),I=x===void 0?void 0:oZ(k),R=await _A({cwd:n,name:o.name,source:o.source}),O;try{O=(await h.submit({scriptText:o.script,cwd:n,name:o.name,...v?{args:i.args}:{},parentSessionId:this.sessionId,toolCallId:_,launchInputId:b,...x===void 0?{}:{phaseNames:x},...I===void 0?{}:{phaseAlongside:I},...p===void 0?{}:{modelBindings:p},...R===void 0?{}:{scriptPath:R.path},trace:t})).runId}catch(z){return{ok:!1,reason:"start_failed",message:Mpc(z)}}let j=Dpc(o.name,o.scope,O,i.args),L=Bz(a),$=M4e({runId:O,toolCallId:_,name:o.name,scope:o.scope,path:o.path,...v?{args:i.args}:{},description:o.meta.description,...L?.kind==="create_workflow"?{display:L}:{},script:o.script});try{let z=Fl();await XOt.call(this,{messageId:z,titleInput:o.name,historyText:j,turnInput:j,traceContext:t,inputId:b,inputSource:"workflow_launch",workflowLaunch:$,persistMessage:r(()=>qzn.call(this,{messageID:z,text:j,meta:$,traceContext:t}),"persistMessage")});let q={id:_,name:U0,input:{name:o.name,saved:{name:o.name,scope:o.scope,...v?{args:i.args}:{}}}};await this.executor.trackExternalBackgroundTask(q,{backgroundTaskId:O,status:"backgrounded"},t,void 0)}catch(z){this.logger?.error("Saved workflow launched but post-submit bookkeeping failed",z instanceof Error?z:new Error(String(z)),{...lr(t),event:"dynamic_workflow.launch.post_submit_failed",module:"core.runtime",runId:O,toolCallId:_})}return{ok:!0,runId:O,toolCallId:_}}function Dpc(e,t,n,o){let i=[`Started the saved workflow "${e}" (${t}) from the workflows hub as run ${n}.`];return Object.keys(o).length>0&&i.push("","Arguments:","```json",JSON.stringify(o,null,2),"```"),i.push("","Progress and results arrive as background notifications; do not start it again."),i.join(`
14825
14825
  `)}function eDt(e,t){let n=[e,...t.map(o=>`L${o.line}:C${o.column} ${o.message}`)].join(`
14826
14826
  `);return n.length>Moi?`${n.slice(0,Moi-1)}\u2026`:n}function Mpc(e){return e instanceof Error?e.message:String(e)}var Noi,Moi,Wzn=V(()=>{"use strict";Noi=require("node:crypto");vn();hue();UTe();DX();_V();Lue();To();Ns();QOt();YW();Moi=2e3;r(Loi,"startSavedWorkflowRun");r(Dpc,"buildLaunchMessageText");r(eDt,"boundedCompileDiagnostics");r(Mpc,"describeError")});function LP(){return Foi+=1,`runtime_command_${Foi}`}function joi(){let e=[],t=new Set,n=r(o=>{let i=-1,a=Number.POSITIVE_INFINITY,c=o===void 0?Number.POSITIVE_INFINITY:tDt[o];for(let[u,p]of e.entries()){let h=tDt[p.priority];h>c||h<a&&(i=u,a=h)}return i},"selectNextIndex");return{clearCancelPending(o){t.delete(o)},consumeCancelPending(o){return t.delete(o)},dequeue(){let o=n();if(o===-1)return;let[i]=e.splice(o,1);return i},dequeueNextBatch(){let o=n();if(o===-1)return Object.freeze([]);let i=e[o];if(i?.mode!=="task-notification"){let[c]=e.splice(o,1);return Object.freeze(c?[c]:[])}let a=e.filter(c=>c.mode==="task-notification"&&c.priority===i.priority&&c.offPeakExecutionId===i.offPeakExecutionId);for(let c=e.length-1;c>=0;c-=1){let u=e[c];u?.mode==="task-notification"&&u.priority===i.priority&&u.offPeakExecutionId===i.offPeakExecutionId&&e.splice(c,1)}return Object.freeze(a)},enqueue(o){e.push(o)},getByMaxPriority(o){let i=tDt[o];return Object.freeze(e.filter(a=>tDt[a.priority]<=i))},hasPending(){return e.length>0},markCancelPending(o){t.add(o)},removeById(o){let i=e.findIndex(c=>c.id===o);if(i===-1)return;let[a]=e.splice(i,1);return a},size(){return e.length},snapshot(){return Object.freeze([...e])}}}var tDt,Foi,EV=V(()=>{"use strict";tDt={now:0,next:1,later:2},Foi=0;r(LP,"createRuntimeCommandId");r(joi,"createRuntimeCommandQueue")});function Vzn(e){this.enqueueRuntimeCommand({branchGeneration:this.branchGeneration,createdAt:new Date,id:LP(),inputId:Zq(),mode:"control-only-turn",priority:"next",text:e.text,titleInput:e.titleInput,traceContext:e.traceContext,workflowLaunch:e.meta})}function nDt(e,t){return{...e===void 0?{}:{from:e},...t===void 0?{}:{to:t}}}function rDt(e){let t=e.amend.predecessorRunId===void 0,n=`Changed the settings of workflow run ${e.previous}${e.name===void 0?"":` ("${e.name}")`} from the GUI: ${Npc(e.amend,t).join("; ")}.`,o="Progress and results arrive as background notifications; do not amend, resume or restart it.";if(t){let a=e.amend.maxConcurrency?.to===void 0?`Run ${e.previous} keeps running with no limit`:`Run ${e.previous} keeps running under the new limit`;return[n,`${a}; nothing was stopped and no new run was started.`,o].join(" ")}let i=e.superseded?"supersedes":"takes over from";return[n,`The same script continues as run ${e.runId}, which ${i} run ${e.previous} and imports everything run ${e.previous} finished as cache.`,o].join(" ")}function Npc(e,t){let n=[],o=e.subagentModel;o!==void 0&&n.push(o.to===void 0?"its subagents are back on the session model":`its subagents now run on ${o.to}`);let i=e.maxConcurrency;return i!==void 0&&n.push(i.to===void 0?"the limit on subagents at once is back to the default":t?`at most ${i.to} of its subagents run at once`:`at most ${i.to} of them run at once`),n}function Boi(e){return{...e.subagentModel===void 0?{}:{subagentModel:e.subagentModel},...e.maxConcurrency===void 0?{}:{maxConcurrency:e.maxConcurrency}}}var Hzn=V(()=>{"use strict";To();EV();r(Vzn,"enqueueSettingsTurn");r(nDt,"fromTo");r(rDt,"buildSettingsMessageText");r(Npc,"settingsChangeClauses");r(Boi,"runSettingsOfSnapshot")});async function zoi(e){let t=e.traceContext??this.rootTraceContext,n=this.dynamicWorkflowRunPort;if(n===void 0||typeof n.amend!="function")return{ok:!1,reason:"start_failed",message:"dynamic workflow amend unavailable"};let o=await n.getTask(e.runId);if(o===void 0||o.parentSessionId!==this.sessionId)return{ok:!1,reason:"not_found"};if(o.runStatus==="completed"||o.supersededBy!==void 0)return{ok:!1,reason:"not_configurable"};let i=Boi(o),a=f3n(e.subagentModel,i.subagentModel,this.modelCatalogPort);if(!a.ok)return{ok:!1,reason:"model_unavailable",...this.modelCatalogPort===void 0?{}:{message:a.message}};let c=n.defaultConcurrency?.(),u=jue(e.maxConcurrency,i.maxConcurrency),p=u.max_concurrency===void 0||u.max_concurrency===c?void 0:u.max_concurrency,h={...a.canonical===void 0?{}:{subagentModel:a.canonical},...p===void 0?{}:{maxConcurrency:p}},_=h.subagentModel!==i.subagentModel,v=h.maxConcurrency!==i.maxConcurrency;if(!_&&!v)return{ok:!1,reason:"unchanged"};if(v&&!_&&typeof n.retuneConcurrency=="function"){let ge=await n.retuneConcurrency({runId:e.runId,maxConcurrency:e.maxConcurrency??null});if(ge.ok)return await ZW.call(this,{source:"run_control",traceContext:t}),Lpc.call(this,{answer:ge,name:Uoi(o),runId:e.runId,traceContext:t});if(ge.reason==="unchanged")return{ok:!1,reason:"unchanged"}}let b=typeof n.getScript=="function"?await n.getScript(e.runId):void 0;if(b===void 0||b.length===0)return{ok:!1,reason:"script_missing"};let k=yS(b);if(!k.ok||k.diagnostics.length>0)return{ok:!1,reason:"compile_failed",message:eDt(`The stored script of run ${e.runId} has errors:`,k.diagnostics)};let x=cRt(k,this.modelCatalogPort,o.modelBindings);if(x.unbound.length>0)return{ok:!1,reason:"model_unavailable",message:eDt(`The models named in the script of run ${e.runId} cannot be used now:`,x.unbound)};let I=x.selections,R=W6(k),j=(await l3n({cwd:this.workingDirectory,scriptPath:o.scriptPath,script:b}))?.path??(await _A({cwd:this.workingDirectory,name:PTe(o.name,R),source:b}))?.path,L=`settings-${(0,Gzn.randomUUID)()}`,$=Q8(R),z=$===void 0?void 0:oZ(R),q=ITe(h.subagentModel),W;try{W=await n.amend({scriptText:b,cwd:this.workingDirectory,predecessorRunId:e.runId,parentSessionId:this.sessionId,toolCallId:L,...$===void 0?{}:{phaseNames:$},...z===void 0?{}:{phaseAlongside:z},...h.maxConcurrency===void 0?{}:{maxConcurrency:h.maxConcurrency},...q===void 0?{}:{subagentModel:q},...I===void 0?{}:{modelBindings:I},...j===void 0?{}:{scriptPath:j},inheritArgs:!0,trace:t})}catch(ge){return{ok:!1,reason:"start_failed",message:ge instanceof Error?ge.message:String(ge)}}if(!W.ok)return{ok:!1,reason:W.reason==="run_not_found"?"not_found":"missing_boundaries"};let Q=Uoi(o),ne={predecessorRunId:e.runId,..._?{subagentModel:nDt(i.subagentModel,h.subagentModel)}:{},...v?{maxConcurrency:nDt(i.maxConcurrency,h.maxConcurrency)}:{},...c===void 0?{}:{ceiling:c}};try{let ge={id:L,name:l_,input:{run_id:e.runId,...Q===void 0?{}:{name:Q}}};await this.executor.trackExternalBackgroundTask(ge,{backgroundTaskId:W.runId,status:"backgrounded"},t,void 0),await ZW.call(this,{source:"run_control",traceContext:t}),Vzn.call(this,{text:rDt({...Q===void 0?{}:{name:Q},previous:e.runId,runId:W.runId,superseded:W.supersededRunId!==void 0,amend:ne}),meta:M4e({runId:W.runId,toolCallId:L,...Q===void 0?{}:{name:Q},...(()=>{let ie=Bz(k);return ie?.kind==="create_workflow"?{display:ie}:{}})(),amend:ne}),titleInput:Q??e.runId,traceContext:t})}catch(ge){this.logger?.error("Workflow settings amended but post-amend bookkeeping failed",ge instanceof Error?ge:new Error(String(ge)),{...lr(t),event:"dynamic_workflow.settings.post_amend_failed",module:"core.runtime",runId:W.runId,toolCallId:L})}return{ok:!0,runId:W.runId,toolCallId:L,...W.supersededRunId===void 0?{}:{supersededRunId:W.supersededRunId}}}function Lpc(e){let{answer:t,name:n,runId:o,traceContext:i}=e,a=`settings-${(0,Gzn.randomUUID)()}`,c={maxConcurrency:nDt(t.previous===t.defaultConcurrency?void 0:t.previous,t.maxConcurrency===t.defaultConcurrency?void 0:t.maxConcurrency),ceiling:t.defaultConcurrency};try{Vzn.call(this,{text:rDt({...n===void 0?{}:{name:n},previous:o,runId:o,superseded:!1,amend:c}),meta:M4e({runId:o,toolCallId:a,...n===void 0?{}:{name:n},amend:c}),titleInput:n??o,traceContext:i})}catch(u){this.logger?.error("Workflow run retuned but the settings turn could not be queued",u instanceof Error?u:new Error(String(u)),{...lr(i),event:"dynamic_workflow.settings.post_retune_failed",module:"core.runtime",runId:o,toolCallId:a})}return{ok:!0,runId:o,toolCallId:a}}function Uoi(e){let t=e.name?.trim();return t===void 0||t.length===0?void 0:t}var Gzn,$oi=V(()=>{"use strict";Gzn=require("node:crypto");vn();m3n();a7e();cV();UTe();DX();_V();Lue();Ns();Wzn();YW();Hzn();Hzn();r(zoi,"amendWorkflowRunSettings");r(Lpc,"retunedSettings");r(Uoi,"displayNameOfSnapshot")});function Voi(e){return e.input.trim().length>0||!!e.attachments?.length||!!e.intent?.conversationQuotes?.length}async function Hoi(e){let t=typeof e=="string"?{input:e}:e,n=this.activeTurn,o=iQ(t.input),i=NIe(t.input);if(!Voi(t))return await this.rejectTurnSteer("empty_input",{activeTurn:n,expectedTurnId:t.expectedTurnId,inputPreview:i,inputSize:o,traceContext:t.traceContext});if(o>O8n)return await this.rejectTurnSteer("input_too_large",{activeTurn:n,expectedTurnId:t.expectedTurnId,inputPreview:i,inputSize:o,traceContext:t.traceContext});if(!n)return await this.rejectTurnSteer("no_active_turn",{expectedTurnId:t.expectedTurnId,inputPreview:i,inputSize:o,traceContext:t.traceContext});if(t.expectedTurnId!==void 0&&t.expectedTurnId!==n.turnId)return await this.rejectTurnSteer("expected_turn_mismatch",{activeTurn:n,expectedTurnId:t.expectedTurnId,inputPreview:i,inputSize:o,traceContext:t.traceContext});if(!n.steerable)return await this.rejectTurnSteer("turn_not_steerable",{activeTurn:n,expectedTurnId:t.expectedTurnId,inputPreview:i,inputSize:o,traceContext:t.traceContext});let a=t.queryId??t.inputId??Hue(),c=t.commandKind,u=t.source,p=t.delivery,h=t.automationId,_=t.toolDisallowlist,v=n.pendingInputs.length,b=t.intent?{...t.intent,admittedDelivery:t.delivery??t.intent.admittedDelivery,queuePosition:v}:void 0,k={id:t.pendingInputId??t.intent?.queueItemId??this.createPendingInputId(n.turnId),input:t.input,queuedAt:new Date,traceId:n.traceContext.traceId,queryId:a,...c?{commandKind:c}:{},...u?{source:u}:{},...t.inputPresentation?{inputPresentation:t.inputPresentation}:{},...p?{delivery:p}:{},...b?{intent:b}:{},...t.attachments?{attachments:t.attachments}:{},...h?{automationId:h}:{},..._?{toolDisallowlist:_}:{},turnId:n.turnId},x=SQ(this,b,n.traceContext,t.modelSelectionScope?{selectionScope:t.modelSelectionScope,highspeedFallbackSelection:t.highspeedFallbackSelection}:void 0);n.pendingInputs.push(k),nii(t)&&this.workflowBlockedReminder?.userSpoke();let I=n.pendingInputs.length,R=xf(Je.TurnSteerQueued,this.sessionId,{inputId:t.inputId,queryId:a,pendingInputId:k.id,input:k.input,inputPreview:i,inputSize:o,...c?{commandKind:c}:{},...u?{source:u}:{},...t.inputPresentation?{inputPresentation:t.inputPresentation}:{},...p?{delivery:p}:{},...b?{intent:b}:{},...h?{automationId:h}:{},..._?{toolDisallowlist:_}:{},targetTurnId:n.turnId,queueLength:I},{traceId:n.traceContext.traceId,turnId:n.turnId});return await this.appendEvent(R,n.traceContext),await x,this.logger?.debug("Turn steer queued",{...lr(n.traceContext),activeTurnKind:n.kind,activeTurnSteerable:n.steerable,inputId:t.inputId,queryId:a,event:"turn.steer.queued",expectedTurnId:t.expectedTurnId,inputPreview:i,inputSize:o,module:"core.runtime",pendingInputId:k.id,queueLength:I,...u?{source:u}:{},...t.inputPresentation?{inputPresentation:t.inputPresentation}:{},status:"waiting",targetTurnId:n.turnId}),{kind:"queued",pendingInputId:k.id,queueLength:I,turnId:n.turnId}}async function Goi(e){let t=typeof e=="string"?{input:e}:e,n=iQ(t.input),o=NIe(t.input),i=t.traceContext??this.rootTraceContext;if(!Voi(t))return await this.rejectTurnSteer("empty_input",{inputPreview:o,inputSize:n,traceContext:i});if(n>O8n)return await this.rejectTurnSteer("input_too_large",{inputPreview:o,inputSize:n,traceContext:i});let a=this.activeTurn?.turnId??this.latestAssistantTurnId??i.turnId??"deferred",c=t.queryId??t.inputId??Hue(),u=t.commandKind,p=t.source,h=t.delivery??"queue",_=t.automationId,v=t.toolDisallowlist,b=t.pendingInputId??t.intent?.queueItemId??this.createPendingInputId(a),x=(await this.rebuildProjection()).pendingSteerInputs.length+1,I=t.intent?{...t.intent,admittedDelivery:h,queuePosition:x-1}:void 0,R=xf(Je.TurnSteerQueued,this.sessionId,{...t.inputId?{inputId:t.inputId}:{},queryId:c,pendingInputId:b,input:t.input,inputPreview:o,inputSize:n,...u?{commandKind:u}:{},...p?{source:p}:{},...t.inputPresentation?{inputPresentation:t.inputPresentation}:{},delivery:h,...I?{intent:I}:{},..._?{automationId:_}:{},...v?{toolDisallowlist:v}:{},targetTurnId:a,queueLength:x},{traceId:i.traceId,turnId:a});return await this.appendEvent(R,i),await SQ(this,I,i,t.modelSelectionScope?{selectionScope:t.modelSelectionScope,highspeedFallbackSelection:t.highspeedFallbackSelection}:void 0),this.logger?.debug("Deferred input queued",{...lr(i),delivery:h,event:"turn.deferred_input.queued",inputId:t.inputId,inputPreview:o,inputSize:n,module:"core.runtime",pendingInputId:b,queueLength:x,status:"waiting",targetTurnId:a}),{kind:"queued",pendingInputId:b,queueLength:x,turnId:a}}function Joi(e,t,n,o,i){if(this.activeTurn)throw oDt(n,this.activeTurn.turnId,e);let a=this.activeTurnStartReservation;if(a&&a.turnId!==e)throw oDt(n,a.turnId,e);let c={goalStateChangeReminderDeferralOpen:!1,kind:n,pendingInputs:[],steerable:o,traceContext:t,turnId:e,...i?.inputId===void 0?{}:{inputId:i.inputId}};return this.activeTurnStartReservation=void 0,this.activeTurn=c,c}function Koi(e,t,n){if(this.activeTurn)throw oDt(n,this.activeTurn.turnId,e);if(this.activeTurnStartReservation)throw oDt(n,this.activeTurnStartReservation.turnId,e);this.activeTurnStartReservation={kind:n,traceContext:t,turnId:e}}function Zoi(e){this.activeTurnStartReservation?.turnId===e&&(this.activeTurnStartReservation=void 0)}function Yoi(e){e!==void 0&&this.activeTurn===e&&(this.activeTurn=void 0)}function Xoi(e){return this.pendingInputSequence+=1,`pending_${e}_${this.pendingInputSequence}`}function oDt(e,t,n){return Mr(qn.TurnInProgress,`Cannot start ${e} turn while another turn is active`,{context:{activeTurnId:t,nextTurnId:n},recoverable:!0})}async function Qoi(e,t){let n=t.activeTurn?.traceContext??t.traceContext??this.rootTraceContext,o=xf(Je.TurnSteerRejected,this.sessionId,{activeTurnId:t.activeTurn?.turnId,expectedTurnId:t.expectedTurnId,inputPreview:t.inputPreview,inputSize:t.inputSize,reason:e},{traceId:n.traceId,turnId:t.activeTurn?.turnId});return await this.appendEvent(o,n),this.logger?.debug("Turn steer rejected",{...lr(n),activeQueueLength:t.activeTurn?.pendingInputs.length,activeTurnId:t.activeTurn?.turnId,activeTurnKind:t.activeTurn?.kind,activeTurnSteerable:t.activeTurn?.steerable,event:"turn.steer.rejected",expectedTurnId:t.expectedTurnId,inputPreview:t.inputPreview,inputSize:t.inputSize,module:"core.runtime",reason:e,status:"completed"}),{activeTurnId:t.activeTurn?.turnId,kind:"rejected",reason:e}}function eii(e){return this.activeTurn===e&&e.pendingInputs.length>0}function Jzn(e){return(e?.delivery??e?.intent?.admittedDelivery)==="guide"?"guide":"queue"}function tii(e){return e.commandKind!=="sendGoalCommand"&&e.commandKind!=="compact"&&Jzn(e)==="guide"}function nii(e){return e.inputPresentation==="user_steer"}function Fpc(e){return e.pendingInputs.findIndex(tii)}function jpc(e,t){return t?{...e,queryId:t}:e}function rii(e){let t=Fpc(e),n=t>=0?e.pendingInputs[t]:void 0;return this.activeTurn===e&&!this.permissionFullAccessPending&&!this.queueExternalDrainActive&&!this.pendingInputReservations.has(n?.id??"")&&n?.commandKind!=="sendGoalCommand"&&n?.commandKind!=="compact"&&Jzn(n)==="guide"}async function oii(e){if(this.activeTurn!==e.activeTurn)return 0;let t=0;for(let n of e.activeTurn.pendingInputs){if(Jzn(n)!=="guide")continue;let o=n.intent?{...n.intent,admittedDelivery:"queue",fallbackReasonCode:e.reasonCode}:void 0,i=this.createEvent(Je.TurnSteerDeliveryChanged,{admittedDelivery:"queue",fallbackReasonCode:e.reasonCode,...o?{intent:o}:{},pendingInputId:n.id,requestedDelivery:"guide",targetTurnId:e.activeTurn.turnId},e.traceContext);await this.appendEvent(i,e.traceContext),e.events?.push(i),n.delivery="queue",o&&(n.intent=o),t+=1,this.logger?.debug("Guide input fell back to ordinary queue",{...lr(e.traceContext),event:"turn.guide.fell_back",fallbackReasonCode:e.reasonCode,module:"core.runtime",pendingInputId:n.id,status:"completed",targetTurnId:e.activeTurn.turnId})}return t}async function Pqe(e,t){let n=e.activeTurn?.pendingInputs.find(i=>i.id===t);return n?n.turnId:(await e.rebuildProjection()).pendingSteerInputs.find(i=>i.pendingInputId===t)?.targetTurnId}async function Kzn(e,t){let n=xf(Je.TurnSteerDispatchChanged,e.sessionId,{pendingInputId:t.pendingInputId,...t.reservationId?{reservationId:t.reservationId}:{},state:t.state,targetTurnId:t.targetTurnId},{traceId:t.traceContext.traceId,turnId:t.targetTurnId});await e.appendEvent(n,t.traceContext)}async function iDt(e,t,n){n==="user_removed"&&await e.sessionStore?.settleSessionInput?.({id:t,sessionID:e.sessionId,status:"cancelled",reason:"user_removed"})}async function sDt(e,t){await e.sessionStore?.updateSessionInputs?.({sessionID:e.sessionId,updates:t})}async function iii(e){if(this.permissionFullAccessPending||this.pendingInputReservations.has(e.pendingInputId)||this.pendingInputEditLocks.has(e.pendingInputId))return!1;e5.has(this)&&await ade(this);let t=await Pqe(this,e.pendingInputId);if(!t||this.permissionFullAccessPending||this.pendingInputReservations.has(e.pendingInputId)||this.pendingInputEditLocks.has(e.pendingInputId))return!1;this.pendingInputReservations.set(e.pendingInputId,e.reservationId);try{return await Kzn(this,{...e,state:"reserved",targetTurnId:t}),!0}catch(n){throw this.pendingInputReservations.delete(e.pendingInputId),n}}async function sii(e){if(this.pendingInputReservations.get(e.pendingInputId)!==e.reservationId)return!1;let t=await Pqe(this,e.pendingInputId);return t?(await Kzn(this,{...e,state:"promoting",targetTurnId:t}),!0):!1}async function aii(e){if(this.pendingInputReservations.get(e.pendingInputId)!==e.reservationId)return!1;let t=await Pqe(this,e.pendingInputId);if(this.pendingInputReservations.delete(e.pendingInputId),!t)return!0;try{await Kzn(this,{pendingInputId:e.pendingInputId,state:"queued",targetTurnId:t,traceContext:e.traceContext})}catch(n){throw this.pendingInputReservations.set(e.pendingInputId,e.reservationId),n}return!0}async function cii(e){let t=this.pendingInputReservations.get(e.pendingInputId);if(t&&t!==e.reservationId||this.pendingInputEditLocks.has(e.pendingInputId))return!1;let n=this.activeTurn,o=n?.pendingInputs.findIndex(a=>a.id===e.pendingInputId)??-1;if(!n||o<0)return this.discardHeldPendingInputById(e.pendingInputId,e.traceContext,e.reservationId,e.reason);await iDt(this,e.pendingInputId,e.reason),n.pendingInputs.splice(o,1);let i=xf(Je.TurnSteerDiscarded,this.sessionId,{pendingInputIds:[e.pendingInputId],reason:e.reason,targetTurnId:n.turnId},{traceId:n.traceContext.traceId,turnId:n.turnId});return await this.appendEvent(i,e.traceContext),this.pendingInputReservations.delete(e.pendingInputId),this.logger?.debug("Turn steer item removed",{...lr(e.traceContext),event:"turn.steer.removed",module:"core.runtime",pendingInputId:e.pendingInputId,status:"completed",targetTurnId:n.turnId}),!0}async function lii(e,t,n,o="user_removed"){let i=this.pendingInputReservations.get(e);if(i&&i!==n)return!1;let c=(await this.rebuildProjection()).pendingSteerInputs.find(p=>p.pendingInputId===e);if(!c)return!1;await iDt(this,e,o);let u=xf(Je.TurnSteerDiscarded,this.sessionId,{pendingInputIds:[e],reason:o,targetTurnId:c.targetTurnId},{traceId:t.traceId,turnId:c.targetTurnId});return await this.appendEvent(u,t),this.pendingInputReservations.delete(e),this.logger?.debug("Turn steer item removed",{...lr(t),event:"turn.steer.removed",module:"core.runtime",pendingInputId:e,status:"completed",targetTurnId:c.targetTurnId}),!0}async function uii(e){let t=0,n=r(c=>{for(let u of c)this.pendingInputEditLocks.delete(u)},"releaseLocks"),o=this.activeTurn;if(o&&o.pendingInputs.length>0){for(let p of o.pendingInputs)await iDt(this,p.id,"user_removed");let c=o.pendingInputs.splice(0);t+=c.length;let u=xf(Je.TurnSteerDiscarded,this.sessionId,{pendingInputIds:c.map(p=>p.id),reason:"user_removed",targetTurnId:o.turnId},{traceId:o.traceContext.traceId,turnId:o.turnId});await this.appendEvent(u,e),n(c.map(p=>p.id))}let i=await this.rebuildProjection(),a=new Map;for(let c of i.pendingSteerInputs){let u=a.get(c.targetTurnId)??[];u.push(c),a.set(c.targetTurnId,u)}for(let[c,u]of a){for(let h of u)await iDt(this,h.pendingInputId,"user_removed");t+=u.length;let p=xf(Je.TurnSteerDiscarded,this.sessionId,{pendingInputIds:u.map(h=>h.pendingInputId),reason:"user_removed",targetTurnId:c},{traceId:e.traceId,turnId:c});await this.appendEvent(p,e),n(u.map(h=>h.pendingInputId))}return t}function qoi(e,t){if(!e)return;let n={...e,...t.newText!==void 0?{text:t.newText}:{},...t.attachmentRefs?{attachmentRefs:t.attachmentRefs}:{},...t.conversationQuotes?{conversationQuotes:t.conversationQuotes}:{},...t.modelSelection?{modelSelection:kg(t.modelSelection)}:{},...t.mode?{mode:t.mode}:{},...t.planEnabled!==void 0?{planEnabled:t.planEnabled}:{}};return t.dropHighspeed&&delete n.highspeed,n}function Bpc(e,t){let n=e.pendingInputEditLocks.get(t.pendingInputId);return t.editorId!==void 0?n?.editorId===t.editorId?"ok":"lockLost":n?"editLocked":"ok"}async function dii(e){let t=Bpc(this,e);if(t!=="ok")return t;let n=this.activeTurn,o=n?.pendingInputs.find(a=>a.id===e.pendingInputId);if(!n||!o){let a=await this.rebuildProjection(),c=a.pendingSteerInputs.find(_=>_.pendingInputId===e.pendingInputId);if(!c)return"missing";let u=e.newText??c.input;e.newText!==void 0&&await sDt(this,[{id:c.pendingInputId,text:u}]);let p=qoi(c.intent,e),h=xf(Je.TurnSteerQueued,this.sessionId,{pendingInputId:c.pendingInputId,input:u,inputPreview:NIe(u),inputSize:iQ(u),...c.commandKind?{commandKind:c.commandKind}:{},...p?{intent:p}:{},...c.automationId?{automationId:c.automationId}:{},...c.toolDisallowlist?{toolDisallowlist:c.toolDisallowlist}:{},queueLength:a.pendingSteerInputs.length,targetTurnId:c.targetTurnId},{traceId:e.traceContext.traceId,turnId:c.targetTurnId});return await this.appendEvent(h,e.traceContext),await Woi(this,c.pendingInputId,c.targetTurnId,e),"edited"}e.newText!==void 0&&(await sDt(this,[{id:o.id,text:e.newText}]),o.input=e.newText),o.intent=qoi(o.intent,e),e.attachments&&(o.attachments=e.attachments);let i=xf(Je.TurnSteerQueued,this.sessionId,{pendingInputId:o.id,queryId:o.queryId,input:o.input,inputPreview:NIe(o.input),inputSize:iQ(o.input),...o.commandKind?{commandKind:o.commandKind}:{},...o.delivery?{delivery:o.delivery}:{},...o.inputPresentation?{inputPresentation:o.inputPresentation}:{},...o.intent?{intent:o.intent}:{},...o.automationId?{automationId:o.automationId}:{},...o.toolDisallowlist?{toolDisallowlist:o.toolDisallowlist}:{},queueLength:n.pendingInputs.length,targetTurnId:n.turnId},{traceId:n.traceContext.traceId,turnId:n.turnId});return await this.appendEvent(i,e.traceContext),await Woi(this,o.id,n.turnId,e),"edited"}async function Woi(e,t,n,o){let i=e.pendingInputEditLocks.get(t);!i||o.editorId===void 0||i.editorId!==o.editorId||await pii(e,t,n,o.traceContext)}async function pii(e,t,n,o){await fii(e,{pendingInputId:t,targetTurnId:n,traceContext:o}),e.pendingInputEditLocks.delete(t)}async function fii(e,t){let n=xf(Je.TurnSteerEditLockChanged,e.sessionId,{pendingInputId:t.pendingInputId,targetTurnId:t.targetTurnId,...t.editLock?{editLock:{...t.editLock}}:{}},{traceId:t.traceContext.traceId,turnId:t.targetTurnId});await e.appendEvent(n,t.traceContext)}async function mii(e){let t=r(()=>{if(this.pendingInputReservations.has(e.pendingInputId))return"reserved";let a=this.pendingInputEditLocks.get(e.pendingInputId);if(a)return a.editorId===e.editLock.editorId?"locked":"lockedByOther"},"decide"),n=t();if(n)return n;let o=await Pqe(this,e.pendingInputId);if(!o)return"missing";let i=t();if(i)return i;this.pendingInputEditLocks.set(e.pendingInputId,{...e.editLock});try{await fii(this,{pendingInputId:e.pendingInputId,editLock:e.editLock,targetTurnId:o,traceContext:e.traceContext})}catch(a){throw this.pendingInputEditLocks.delete(e.pendingInputId),a}return"locked"}async function hii(e){if(!this.pendingInputEditLocks.has(e.pendingInputId))return!1;let t=await Pqe(this,e.pendingInputId);return t?(await pii(this,e.pendingInputId,t,e.traceContext),!0):(this.pendingInputEditLocks.delete(e.pendingInputId),!0)}function gii(e){let t=this.pendingInputEditLocks.get(e);return t?{...t}:void 0}async function _ii(e){if(this.pendingInputEditLocks.has(e.pendingInputId))return!1;let t=this.activeTurn,n=t?.pendingInputs.findIndex(p=>p.id===e.pendingInputId)??-1;if(!t||n<0){let p=await this.rebuildProjection(),h=p.pendingSteerInputs.map(k=>k.pendingInputId),_=h.indexOf(e.pendingInputId);if(_<0)return!1;if(h.splice(_,1),e.beforePendingInputId===null)h.push(e.pendingInputId);else{let k=h.indexOf(e.beforePendingInputId);k<0?h.push(e.pendingInputId):h.splice(k,0,e.pendingInputId)}await sDt(this,h.map((k,x)=>({id:k,queuePosition:x})));let v=p.pendingSteerInputs.find(k=>k.pendingInputId===e.pendingInputId)?.targetTurnId??p.pendingSteerInputs[0].targetTurnId,b=xf(Je.TurnSteerReordered,this.sessionId,{orderedPendingInputIds:h,targetTurnId:v},{traceId:e.traceContext.traceId,turnId:v});return await this.appendEvent(b,e.traceContext),!0}let o=[...t.pendingInputs],i=o.findIndex(p=>p.id===e.pendingInputId);if(i<0)return!1;let[a]=o.splice(i,1);if(!a)return!1;if(e.beforePendingInputId===null)o.push(a);else{let p=o.findIndex(h=>h.id===e.beforePendingInputId);p<0?o.push(a):o.splice(p,0,a)}let c=o.map((p,h)=>p.intent?{...p,intent:{...p.intent,queuePosition:h}}:p);await sDt(this,c.map((p,h)=>({id:p.id,queuePosition:h}))),t.pendingInputs.splice(0,t.pendingInputs.length,...c);let u=xf(Je.TurnSteerReordered,this.sessionId,{orderedPendingInputIds:c.map(p=>p.id),targetTurnId:t.turnId},{traceId:t.traceContext.traceId,turnId:t.turnId});return await this.appendEvent(u,e.traceContext),!0}async function yii(e){e.autoDrain&&!this.queueAutoDrain?this.queueExternalDrainActive=!0:e.autoDrain||(this.queueExternalDrainActive=!1),this.queueAutoDrain=e.autoDrain;let t=xf(Je.QueueAutoDrainChanged,this.sessionId,{autoDrain:e.autoDrain},{traceId:e.traceContext.traceId});await this.appendEvent(t,e.traceContext)}function vii(){this.queueExternalDrainActive=!1}async function bii(e){let t=xf(Je.FollowupModeChanged,this.sessionId,{mode:e.mode},{traceId:e.traceContext.traceId});await this.appendEvent(t,e.traceContext)}async function Sii(e){let t=e.model??yk(this,{selection:e.modelSelection}),n=xf(Je.ModelSelected,this.sessionId,{contextWindow:t.properties.contextWindow,modelSelection:kg(e.modelSelection),...e.effectiveReasoningLevel?{effectiveReasoningLevel:e.effectiveReasoningLevel}:{},...e.previousModelSelection!==void 0?{previousModelSelection:e.previousModelSelection?kg(e.previousModelSelection):null}:{},...e.origin?{origin:e.origin}:{},...e.supportedThoughtLevels?{supportedThoughtLevels:[...e.supportedThoughtLevels]}:{}},{traceId:e.traceContext.traceId});await this.appendEvent(n,e.traceContext),Lti(this,e.modelSelection)}async function wii(e){let t=xf(Je.SessionModeChanged,this.sessionId,{mode:this.getMode(),planEnabled:this.getPlanEnabled(),previousMode:e.previousMode,source:"command"},{traceId:e.traceContext.traceId});await this.appendEvent(t,e.traceContext)}async function kii(e){if(!(this.permissionFullAccessPending||this.activeTurn!==e.activeTurn)&&(e5.has(this)&&await ade(this),!(this.permissionFullAccessPending||this.activeTurn!==e.activeTurn))){this.pendingInputDrains=(this.pendingInputDrains??0)+1;try{return await Upc.call(this,e)}finally{this.pendingInputDrains-=1}}}async function Upc(e){let t=[];for(let _ of e.activeTurn.pendingInputs)if(tii(_)){if(this.pendingInputReservations.has(_.id))break;t.push(_)}if(t.length===0)return;for(let _ of t)e.activeTurn.pendingInputs.splice(e.activeTurn.pendingInputs.indexOf(_),1);let n=t.flatMap(_=>_.queryId?[_.queryId]:[]),o=n.length>0?n:void 0,i=Date.now(),a=[],c=[];for(let _ of t){let v=Fl(),b=_.delivery??"queue",k=jpc(e.traceContext,_.queryId),x=await GPt(_.attachments,{artifactStore:this.artifactStore,fileSystemPort:this.fileSystemPort,imageProcessorPort:this.imageProcessorPort,sessionId:this.sessionId,traceContext:k,turnId:e.activeTurn.turnId,workingDirectory:this.workingDirectory}),I=b==="guide"&&!_.source&&!_.attachments?.length?VK(_.inputPresentation):void 0,R=ZUe(LIe(ZIe(_.input,_.intent?.conversationQuotes,_.intent?.botGroupSource),x),VC(I)??hz());await this.persistUserPrompt(v,_.input,x,k,{steerDelivery:b,inputPresentation:I,sessionInputId:_.id,sourceCommandId:_.intent?.sourceCommandId??String(_.queryId??_.id),clientId:_.intent?.clientId,intent:_.intent});let O={...uxe(R,_.intent?.genUiContext),time:this.now().getTime()};this.messageHistory.addEntries([O]),c.push(O),this.mcpTrustAdmissionRead&&VC(_.inputPresentation)?.source!=="legacy_synthetic"&&await gqe(this,k),a.push(v);let j=this.createEvent(Je.TurnSteerDrained,{injectedMessageIds:[v],pendingInputIds:[_.id],drainedInputs:[{pendingInputId:_.id,messageId:v,text:_.input,delivery:b,..._.intent?{intent:_.intent}:{},..._.toolDisallowlist?{toolDisallowlist:_.toolDisallowlist}:{}}],..._.queryId?{queryIds:[_.queryId]}:{},targetTurnId:e.activeTurn.turnId},k);await this.appendEvent(j,k),e.events.push(j),this.logger?.debug("Turn steer drained",{...lr(k),drainedCount:1,event:"turn.steer.drained",injectedMessageIds:[v],inputPreviews:[NIe(_.input)],inputSizes:[iQ(_.input)],module:"core.runtime",pendingInputIds:[_.id],queryIds:_.queryId?[_.queryId]:void 0,queuedDurationsMs:[i-_.queuedAt.getTime()],status:"completed",targetTurnId:e.activeTurn.turnId})}let u=t.map(_=>_.id),p=[...new Set(t.flatMap(_=>_.toolDisallowlist??[]))],h=t.findLast(_=>_.intent)?.intent;return{injectedMessageIds:a,...h?{intent:h}:{},pluginDiscoveryUi:t.every(_=>_.intent?.[use]===!0),latestMessageId:a.at(-1),pendingInputIds:u,queryIds:o,runtimeEntries:c,...p.length>0?{toolDisallowlist:p}:{},userSteered:t.some(nii)}}async function xii(e){if(this.activeTurn!==e.activeTurn)return;let t=e.activeTurn.pendingInputs.splice(0);if(t.length===0)return;let n=t.map(i=>i.id),o=xf(Je.TurnSteerDiscarded,this.sessionId,{pendingInputIds:n,reason:e.reason,targetTurnId:e.activeTurn.turnId},{traceId:e.activeTurn.traceContext.traceId,turnId:e.activeTurn.turnId});await this.appendEvent(o,e.traceContext),e.events?.push(o),this.logger?.debug("Turn steer discarded",{...lr(e.traceContext),discardedCount:t.length,event:"turn.steer.discarded",module:"core.runtime",pendingInputIds:n,reason:e.reason,status:"completed",targetTurnId:e.activeTurn.turnId})}async function Tii(e){try{let i=await this.sessionStore?.listSessionInputs?.({sessionID:this.sessionId,status:"admitted"})??[];for(let a of i)await this.sessionStore?.settleSessionInput?.({id:a.id,sessionID:this.sessionId,status:"discarded",reason:"session_resumed"})}catch(i){this.logger?.warn("Failed to sweep admitted session inputs on resume",{...lr(e),errorMessage:i instanceof Error?i.message:String(i),event:"session_input.resume_sweep_failed",module:"core.runtime",status:"failed"})}let n=(await this.rebuildProjection()).pendingSteerInputs;if(n.length===0)return 0;let o=new Map;for(let i of n){let a=o.get(i.targetTurnId)??[];a.push(i),o.set(i.targetTurnId,a)}for(let[i,a]of o){let c=a.map(p=>p.pendingInputId),u=xf(Je.TurnSteerDiscarded,this.sessionId,{pendingInputIds:c,reason:"session_resumed",targetTurnId:i},{traceId:e.traceId,turnId:i});await this.appendEvent(u,e),this.logger?.debug("Turn steer discarded",{...lr(e),discardedCount:a.length,event:"turn.steer.discarded",module:"core.runtime",pendingInputIds:c,reason:"session_resumed",status:"completed",targetTurnId:i})}return n.length}var kA=V(()=>{"use strict";vn();vn();COt();ble();CV();oOt();Ns();n5();IV();ZL();tp();Bd();r(Voi,"hasSteerInput");r(Hoi,"steerTurn");r(Goi,"enqueueDeferredInput");r(Joi,"beginActiveTurn");r(Koi,"reserveTurnStart");r(Zoi,"releaseTurnStart");r(Yoi,"finishActiveTurn");r(Xoi,"createPendingInputId");r(oDt,"createTurnInProgressError");r(Qoi,"rejectTurnSteer");r(eii,"hasPendingInput");r(Jzn,"pendingInputDelivery");r(tii,"isInlineGuide");r(nii,"isUserSteer");r(Fpc,"firstInlineGuideIndex");r(jpc,"withQueryId");r(rii,"hasInlineGuidePendingInput");r(oii,"fallbackPendingGuidesToQueue");r(Pqe,"pendingInputTargetTurnId");r(Kzn,"appendPendingInputDispatch");r(iDt,"settleRemovedSessionInput");r(sDt,"persistSessionInputUpdates");r(iii,"reservePendingInputById");r(sii,"markPendingInputPromoting");r(aii,"releasePendingInputReservation");r(cii,"removePendingInputById");r(lii,"discardHeldPendingInputById");r(uii,"clearAllPendingInputs");r(qoi,"editedIntent");r(Bpc,"editLockVerdict");r(dii,"editPendingInputById");r(Woi,"releaseEditLockAfterEdit");r(pii,"commitEditLockRelease");r(fii,"appendPendingInputEditLock");r(mii,"lockPendingInputEdit");r(hii,"releasePendingInputEdit");r(gii,"getPendingInputEditLock");r(_ii,"reorderPendingInput");r(yii,"setQueueAutoDrain");r(vii,"completeExternalQueueDrain");r(bii,"setFollowupMode");r(Sii,"emitModelSelected");r(wii,"emitModeChanged");r(kii,"drainPendingInput");r(Upc,"drainPendingInputUnlocked");r(xii,"discardPendingInput");r(Tii,"discardPersistedPendingSteerInputs")});function zpc(e){return e?.taskType??e?.type}function aDt(e){return!e.isSubagentChildRuntime||!e.notificationSealed?!1:e.toolName==="Bash"||zpc(e.registryTask)==="local_bash"}var Zzn=V(()=>{"use strict";r(zpc,"runtimeTaskTypeOf");r(aDt,"shouldSuppressSealedSubagentBashNotification")});function Eii(e,t,n,o=Date.now(),i){let a=Jpc(n);if(!a)return;let c=r(p=>p.type==="local_agent"&&p.status==="running"&&(i===void 0||p.executionId===void 0||p.executionId===i),"belongs"),u=e.get(t);!u||!c(u)||e.update(t,p=>{if(!c(p))return p;let h=p.activity??{lastProgressAt:o,runningTools:[],waitingForPermission:!1,pendingPermissionToolCallIds:[]};return{...p,activity:a(h,o)}})}function Jpc(e){let t=e.payload??{},n=typeof t.toolCallId=="string"?t.toolCallId:void 0,o=typeof t.requestId=="string"?t.requestId:void 0;switch(e.type){case Je.ModelRequest:case Je.ModelComplete:return(i,a)=>({...i,lastProgressAt:a});case Je.ToolCallScheduled:case Je.ToolCallStarted:{if(!n)return;let i=typeof t.toolName=="string"?t.toolName:void 0,a=e.type===Je.ToolCallScheduled?Ypc(t.input):void 0;return(c,u)=>{let p=c.runningTools.find(v=>v.toolCallId===n),h=e.type===Je.ToolCallStarted,_={toolCallId:n,toolName:i??p?.toolName??"tool",startedAt:h?u:p?.startedAt??u,...a??p?.summary?{summary:a??p?.summary}:{}};return{...c,lastProgressAt:h?u:c.lastProgressAt,runningTools:[...c.runningTools.filter(v=>v.toolCallId!==n),_]}}}case Je.ToolCallResult:case Je.ToolCallError:return n?(i,a)=>({...Iii(Yzn(i,n,!1),{toolCallId:n}),lastProgressAt:a,runningTools:i.runningTools.filter(c=>c.toolCallId!==n)}):void 0;case Je.PermissionRequested:return n?i=>Zpc(i,n,o)?i:Yzn(i,n,!0):i=>({...i,waitingForPermission:!0});case Je.PermissionResolved:case Je.PermissionDenied:return n?(i,a)=>({...Iii(Yzn(i,n,!1),{...o?{requestId:o}:{toolCallId:n},...e.type===Je.PermissionDenied?{toolCallId:n}:{}}),lastProgressAt:a}):(i,a)=>({...i,lastProgressAt:a,waitingForPermission:!1});default:return}}function Zpc(e,t,n){return(e.endedToolCallIds??[]).includes(t)||n!==void 0&&(e.endedPermissionRequestIds??[]).includes(n)}function Iii(e,t){let n=r((a,c)=>c===void 0?a:[...(a??[]).filter(u=>u!==c),c].slice(-Kpc),"remember"),o=n(e.endedPermissionRequestIds,t.requestId),i=n(e.endedToolCallIds,t.toolCallId);return{...e,...o?{endedPermissionRequestIds:o}:{},...i?{endedToolCallIds:i}:{}}}function Yzn(e,t,n){let o=(e.pendingPermissionToolCallIds??[]).filter(a=>a!==t),i=n?[...o,t]:o;return{...e,pendingPermissionToolCallIds:i,waitingForPermission:i.length>0}}function Ypc(e){if(e===null||typeof e!="object")return;let t=e,n=["command","description","file_path","path","pattern","url","prompt"].map(o=>t[o]).find(o=>typeof o=="string"&&o.trim()!=="");if(n)return Aii(n,Wpc)}function Aii(e,t){let n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Qzn(e){return Aii(e,Vpc)||"Subagent"}function Xzn(e){return e.activity?.lastProgressAt??e.startedAt.getTime()}function Rii(e,t){return!(!e||e.type!=="local_agent"||e.status!=="running"||e.activity?.waitingForPermission||t.executionId!==void 0&&e.executionId!==t.executionId||t.lastProgressAt!==void 0&&Xzn(e)!==t.lastProgressAt)}function Cii(e,t){return e!==void 0&&Number.isFinite(e)&&e>0?e:t}function Pii(e){let t=Bs(Qzn(e.description)),n=Bs(e.agentId),o=[...e.runningTools].sort((u,p)=>p.runningForMs-u.runningForMs),i=o.slice(0,Hpc),a=[...Xpc,"<background-agent-stall>",` <task-id>${n}</task-id>`,` <description>${t}</description>`,` <running-for-ms>${Math.floor(e.runningForMs)}</running-for-ms>`,` <no-progress-for-ms>${Math.floor(e.noProgressForMs)}</no-progress-for-ms>`,` <last-progress-at>${new Date(e.lastProgressAt).toISOString()}</last-progress-at>`];for(let u of i)a.push(` <running-tool name="${Bs(u.toolName)}" running-for-ms="${Math.floor(u.runningForMs)}">${Bs(u.summary??"")}</running-tool>`);o.length>i.length&&a.push(` <more-running-tools>${o.length-i.length}</more-running-tools>`),a.push(` <next-report-in-ms>${Math.floor(e.nextReportInMs)}</next-report-in-ms>`,"</background-agent-stall>","",`Background agent "${t}" (${n}) has been running for ${cDt(e.runningForMs)} and has made no progress for ${cDt(e.noProgressForMs)}: no new model request and no tool call has finished.`);let[c]=o;return c&&a.push(`It is inside ${Bs(c.toolName)}, which has been running for ${cDt(c.runningForMs)}${c.summary?`: ${Bs(c.summary)}`:""}.`),a.push("This is a status report, not a failure. Test suites, builds, simulations and polling loops with sleep often run this long or longer.",`If that fits what the agent is doing, do nothing and end your turn; if it is still quiet, the next report comes in about ${cDt(e.nextReportInMs)}.`,"Stop it with TaskStop only if you have a concrete reason to think it is stuck (for example, it waits for input that will never arrive). TaskOutput with block=false shows its current activity. Tell the user if they are waiting on it."),vz(a.join(`
14827
- `))}function cDt(e){let t=Math.max(1,Math.round(e/6e4));return t<120?`${t} minute${t===1?"":"s"}`:`${Math.round(t/60*10)/10} hours`}var $pc,qpc,Wpc,Vpc,Hpc,Gpc,Kpc,lDt,Xpc,uDt=V(()=>{"use strict";vn();WL();$pc=15*6e4,qpc=240*6e4,Wpc=200,Vpc=200,Hpc=5,Gpc=2147483647;r(Eii,"noteSubagentActivity");r(Jpc,"activityChange");Kpc=64;r(Zpc,"permissionAlreadyEnded");r(Iii,"withEnded");r(Yzn,"withPendingPermission");r(Ypc,"toolInputSummary");r(Aii,"singleLine");r(Qzn,"backgroundSubagentStallDescription");lDt=class{static{r(this,"BackgroundSubagentStallClock")}host;firstAfterMs;maxIntervalMs;states=new Map;cancelTimer;constructor(t,n={}){this.host=t,this.firstAfterMs=Cii(n.firstAfterMs,$pc),this.maxIntervalMs=Math.max(this.firstAfterMs,Cii(n.maxIntervalMs,qpc))}reconcile(){let t=new Map(this.host.liveAgents().map(n=>[n.taskId,n]));for(let n of this.states.keys())t.has(n)||this.states.delete(n);for(let n of t.values()){let o=Xzn(n),i=this.states.get(n.taskId);(!i||o>i.progressAt)&&this.states.set(n.taskId,{reminders:0,progressAt:o})}this.schedule(t)}dispose(){this.cancelTimer?.(),this.cancelTimer=void 0,this.states.clear()}intervalAfter(t){return Math.min(this.firstAfterMs*2**t,this.maxIntervalMs)}dueAt(t){return t.lastReminderAt===void 0?t.progressAt+this.firstAfterMs:t.lastReminderAt+this.intervalAfter(t.reminders)}schedule(t){this.cancelTimer?.(),this.cancelTimer=void 0;let n;for(let[i,a]of this.states){if(t.get(i)?.activity?.waitingForPermission)continue;let c=this.dueAt(a);n=n===void 0?c:Math.min(n,c)}if(n===void 0)return;let o=Math.min(Gpc,Math.max(0,n-this.host.now()));this.cancelTimer=this.host.setTimer(()=>this.fire(),o)}fire(){this.cancelTimer=void 0;let t=this.host.now(),n=new Map(this.host.liveAgents().map(o=>[o.taskId,o]));for(let[o,i]of this.states){let a=n.get(o);if(!a||a.activity?.waitingForPermission||this.dueAt(i)>t)continue;i.reminders+=1,i.lastReminderAt=t;let c=Xzn(a);this.host.remind({agentId:o,...a.executionId?{executionId:a.executionId}:{},description:a.description,...a.parentToolCallId?{parentToolCallId:String(a.parentToolCallId)}:{},runningForMs:Math.max(0,t-a.startedAt.getTime()),noProgressForMs:Math.max(0,t-c),lastProgressAt:c,runningTools:(a.activity?.runningTools??[]).map(u=>({...u,runningForMs:Math.max(0,t-u.startedAt)})),nextReportInMs:this.intervalAfter(i.reminders),ordinal:i.reminders})}this.schedule(n)}};r(Xzn,"progressTime");r(Rii,"isBackgroundSubagentStallReminderCurrent");r(Cii,"positiveOr");Xpc=["[SYSTEM NOTIFICATION - NOT USER INPUT]","This is an automated status report about a background agent, NOT a message from the user.","Do NOT interpret this as user acknowledgement, confirmation, or response to any pending question.",""];r(Pii,"formatBackgroundSubagentStallNotification");r(cDt,"minutes")});function Dii(e){if(this.shuttingDown){this.logger?.info?.("Dropped background task notification during runtime shutdown",{...lr(e.traceContext),event:"runtime.background_task_notification.shutdown_dropped",module:"core.runtime",taskId:e.taskId,toolName:e.toolName});return}let n=(e.taskId?this.runtimeTaskRegistry.get(e.taskId):void 0)?.branchGeneration??this.branchGeneration;if(n!==this.branchGeneration){this.logger?.debug("Dropped stale-branch background task notification",{...lr(e.traceContext),branchGeneration:n,currentBranchGeneration:this.branchGeneration,event:"runtime.background_task_notification.stale_branch_dropped",module:"core.runtime",taskId:e.taskId});return}let o=LP();this.enqueueRuntimeCommand({branchGeneration:n,createdAt:new Date,id:o,mode:"task-notification",priority:"next",source:"background_task",originMeta:e.originMeta,taskId:e.taskId,text:e.text,toolName:e.toolName,traceContext:e.traceContext});let i=this.sessionStore?.saveSessionInput?.({id:String(o),sessionID:this.sessionId,kind:"backgroundNotification",delivery:"queue",payload:{text:e.text,...e.taskId?{taskId:e.taskId}:{},...e.originMeta?{originMeta:e.originMeta}:{}}});i&&(ofc(this,String(o),i),this.trackResidencyBlockingWork(i).catch(a=>{this.logger?.warn("Failed to admit background notification to ledger",{...lr(e.traceContext),errorMessage:a instanceof Error?a.message:String(a),event:"session_input.admit_failed",module:"core.runtime",status:"failed"})}))}function Mii(e){this.config.taskType==="subagent_child"&&(this.backgroundTaskNotificationsSealed=!0,this.backgroundTaskNotificationSealReason=e.reason,this.logger?.info?.("Subagent runtime background task notifications sealed",{...lr(e.traceContext??this.rootTraceContext),event:"runtime.background_task_notifications.sealed",module:"core.runtime",reason:e.reason}))}async function Nii(e){return(await t5n.call(this,[e],!0)).messageId}function efc(e){let t=e.filter(o=>o.originMeta?.subagentStall===void 0),n=t[0]?.originMeta?.backgroundSource;if(!(!n||t.some(o=>o.originMeta?.backgroundSource!==n)))return n}function tfc(e){if(e.length===1)return e[0].originMeta;let t=[];for(let c of e){let u=c.originMeta;if(!u?.workId.trim()||!u.title.trim())return;t.push(u)}let n=t[0];if(!n)return;let o=t.slice(0,Qpc).map(c=>c.title.trim()),i=t.length-o.length,a=[...o,...i>0?[`+${i}`]:[]].join(" \xB7 ");return{backgroundSource:n.backgroundSource,title:a,workId:n.workId}}function rfc(e){let t=r(n=>n.text.trimStart().startsWith(nfc),"isNotification");return[...e.filter(t),...e.filter(n=>!t(n))]}async function t5n(e,t=!1){let n=e[0],o=efc(e),i=rfc(e),a=tfc(i),c=i.map(v=>v.text),u=dTt(c),p=!t&&c.length>1?c:void 0;await this.ensureContextInitialized(n.traceContext);let h=Fl(),_=t?"task_notification_steer":"task_notification";this.messageHistory.addUser(p?p.map(v=>({type:"text",text:v})):u,VC(_)),await this.persistSyntheticUserNoticeForSession({messageID:h,metadata:{inputPresentation:_,...a?{originMeta:a}:{},visibility:"model-only"},sessionId:this.sessionId,source:"background_task",text:p??u,traceContext:n.traceContext,visibility:"model-only"});for(let v of e)await this.sessionStore?.markSessionInputPromoted?.({id:String(v.id),sessionID:this.sessionId,promotedMessageID:h}).catch(b=>{this.logger?.warn("Failed to mark background notification promoted",{...lr(v.traceContext),commandId:v.id,errorMessage:b instanceof Error?b.message:String(b),event:"session_input.promote_mark_failed",module:"core.runtime",status:"failed"})});return{...o?{backgroundSource:o}:{},messageId:h,...a?{originMeta:a}:{},text:u}}function ofc(e,t,n){let o=e5n.get(e);o||(o=new Map,e5n.set(e,o));let i=n.catch(()=>{});o.set(t,i),i.then(()=>{o.get(t)===i&&o.delete(t)})}function Oii(e,t,n){let o=e.sessionStore?.settleSessionInput;if(!o)return;let i=String(t.id),a=(async()=>{await Promise.resolve(),await e5n.get(e)?.get(i),await o.call(e.sessionStore,{id:i,sessionID:e.sessionId,status:"discarded",reason:n})})();(e.trackResidencyBlockingWork?.(a)??a).catch(u=>{e.logger?.warn("Failed to settle dropped background notification",{...lr(t.traceContext),commandId:i,errorMessage:u instanceof Error?u.message:String(u),event:"session_input.settle_failed",module:"core.runtime",reason:n,status:"failed"})})}function dDt(e){let t=e.taskId?this.runtimeTaskRegistry.get(e.taskId):void 0,n=e.originMeta?.subagentStall;return n!==void 0&&!Rii(t,n)?(this.logger?.info?.("Dropped stale background subagent stall reminder",{...lr(e.traceContext),commandId:e.id,event:"runtime.background_task_notification.stall_reminder_stale",module:"core.runtime",taskId:e.taskId,taskStatus:t?.status}),Oii(this,e,"subagent_stall_reminder_stale"),!0):aDt({isSubagentChildRuntime:this.config.taskType==="subagent_child",notificationSealed:this.backgroundTaskNotificationsSealed,registryTask:t,toolName:e.toolName})?(this.logger?.info?.("Suppressed sealed subagent background Bash notification",{...lr(e.traceContext),commandId:e.id,event:"runtime.background_task_notification.suppressed",module:"core.runtime",reason:this.backgroundTaskNotificationSealReason,taskId:e.taskId,toolName:e.toolName}),Oii(this,e,"subagent_notifications_sealed"),!0):!1}function cfc(e,t,n){if(mPt(e)){if(e.background!==!0)return;let{agentId:p,childSessionId:h,outputFile:_}=e;return{agentId:p,childSessionId:h,outputFile:_,readRun:r(()=>R7e({agentId:p,outputFile:_}),"readRun")}}let o=t.output;if(typeof o!="string"||!o.startsWith(sfc))return;let i=o.match(/(?:^|\n)agentId:\s*([^\s(]+)/)?.[1];if(!i)return;let a=o.match(/(?:^|\n)output_file:[ \t]*([^\r\n]+)/)?.[1]?.trim(),c={...e,...t.metadata},u=typeof c.childSessionId=="string"?c.childSessionId:h0(`subagent_${i}`);return{agentId:i,childSessionId:u,outputFile:a,readRun:r(()=>hPt({agentId:i,outputFile:a,...n}),"readRun")}}async function Lii(e,t=performance.timeOrigin){if(!this.sessionStore)return;let n=new Map;for(let i of e)for(let a of i.parts)if(a.type==="text")for(let c of a.text.matchAll(afc)){let u=c[1]?.trim();u&&n.set(u,Math.max(n.get(u)??0,i.info.time.created))}let o=[];for(let i of e)if(i.info.role==="assistant")for(let a of i.parts){if(a.type!=="tool"||!kP(a.tool)||a.state.status!=="completed")continue;let c=cfc(a.metadata,a.state,{outputRootDir:this.config.subagents?.outputRootDir,parentSessionId:this.sessionId});if(!c||a.state.time.start>=t)continue;let{agentId:u,childSessionId:p,outputFile:h}=c;if(this.runtimeTaskRegistry.get(u))continue;let _=await c.readRun(),v=n.get(u);if(v!==void 0&&(_?.resumedAt===void 0||v>=_.resumedAt)||_!==void 0&&_.status!=="running")continue;let b=await this.sessionStore.getSession(p);if(!b||b.time.updated>=t||lfc(await this.sessionStore.messages({sessionID:b.id})))continue;let k=a.state.input;o.push(uPt({agentId:u,description:typeof k.description=="string"&&k.description.trim()?k.description:"Subagent",error:ifc,outputFile:h??"",parentToolCallId:a.callID,status:"failed"}))}if(o.length!==0)return["The previous ZCode runtime process for this workspace exited unexpectedly (for example, because the system ran out of memory).",`${o.length===1?"This background agent was":"These background agents were"} still running and stopped with it. ${o.length===1?"It":"They"} will not report back.`,"Before relaunching, check what each agent already changed, then decide whether the work still needs to run. Tell the user if they are waiting on it.","",...o].join(`
14827
+ `))}function cDt(e){let t=Math.max(1,Math.round(e/6e4));return t<120?`${t} minute${t===1?"":"s"}`:`${Math.round(t/60*10)/10} hours`}var $pc,qpc,Wpc,Vpc,Hpc,Gpc,Kpc,lDt,Xpc,uDt=V(()=>{"use strict";vn();WL();$pc=15*6e4,qpc=240*6e4,Wpc=200,Vpc=200,Hpc=5,Gpc=2147483647;r(Eii,"noteSubagentActivity");r(Jpc,"activityChange");Kpc=64;r(Zpc,"permissionAlreadyEnded");r(Iii,"withEnded");r(Yzn,"withPendingPermission");r(Ypc,"toolInputSummary");r(Aii,"singleLine");r(Qzn,"backgroundSubagentStallDescription");lDt=class{static{r(this,"BackgroundSubagentStallClock")}host;firstAfterMs;maxIntervalMs;states=new Map;cancelTimer;constructor(t,n={}){this.host=t,this.firstAfterMs=Cii(n.firstAfterMs,$pc),this.maxIntervalMs=Math.max(this.firstAfterMs,Cii(n.maxIntervalMs,qpc))}reconcile(){let t=new Map(this.host.liveAgents().map(n=>[n.taskId,n]));for(let n of this.states.keys())t.has(n)||this.states.delete(n);for(let n of t.values()){let o=Xzn(n),i=this.states.get(n.taskId);(!i||o>i.progressAt)&&this.states.set(n.taskId,{reminders:0,progressAt:o})}this.schedule(t)}dispose(){this.cancelTimer?.(),this.cancelTimer=void 0,this.states.clear()}intervalAfter(t){return Math.min(this.firstAfterMs*2**t,this.maxIntervalMs)}dueAt(t){return t.lastReminderAt===void 0?t.progressAt+this.firstAfterMs:t.lastReminderAt+this.intervalAfter(t.reminders)}schedule(t){this.cancelTimer?.(),this.cancelTimer=void 0;let n;for(let[i,a]of this.states){if(t.get(i)?.activity?.waitingForPermission)continue;let c=this.dueAt(a);n=n===void 0?c:Math.min(n,c)}if(n===void 0)return;let o=Math.min(Gpc,Math.max(0,n-this.host.now()));this.cancelTimer=this.host.setTimer(()=>this.fire(),o)}fire(){this.cancelTimer=void 0;let t=this.host.now(),n=new Map(this.host.liveAgents().map(o=>[o.taskId,o]));for(let[o,i]of this.states){let a=n.get(o);if(!a||a.activity?.waitingForPermission||this.dueAt(i)>t)continue;i.reminders+=1,i.lastReminderAt=t;let c=Xzn(a);this.host.remind({agentId:o,...a.executionId?{executionId:a.executionId}:{},description:a.description,...a.parentToolCallId?{parentToolCallId:String(a.parentToolCallId)}:{},runningForMs:Math.max(0,t-a.startedAt.getTime()),noProgressForMs:Math.max(0,t-c),lastProgressAt:c,runningTools:(a.activity?.runningTools??[]).map(u=>({...u,runningForMs:Math.max(0,t-u.startedAt)})),nextReportInMs:this.intervalAfter(i.reminders),ordinal:i.reminders})}this.schedule(n)}};r(Xzn,"progressTime");r(Rii,"isBackgroundSubagentStallReminderCurrent");r(Cii,"positiveOr");Xpc=["[SYSTEM NOTIFICATION - NOT USER INPUT]","This is an automated status report about a background agent, NOT a message from the user.","Do NOT interpret this as user acknowledgement, confirmation, or response to any pending question.",""];r(Pii,"formatBackgroundSubagentStallNotification");r(cDt,"minutes")});function Dii(e){if(this.shuttingDown){this.logger?.info?.("Dropped background task notification during runtime shutdown",{...lr(e.traceContext),event:"runtime.background_task_notification.shutdown_dropped",module:"core.runtime",taskId:e.taskId,toolName:e.toolName});return}let n=(e.taskId?this.runtimeTaskRegistry.get(e.taskId):void 0)?.branchGeneration??this.branchGeneration;if(n!==this.branchGeneration){this.logger?.debug("Dropped stale-branch background task notification",{...lr(e.traceContext),branchGeneration:n,currentBranchGeneration:this.branchGeneration,event:"runtime.background_task_notification.stale_branch_dropped",module:"core.runtime",taskId:e.taskId});return}let o=LP();this.enqueueRuntimeCommand({branchGeneration:n,createdAt:new Date,id:o,mode:"task-notification",priority:"next",source:"background_task",originMeta:e.originMeta,taskId:e.taskId,text:e.text,toolName:e.toolName,traceContext:e.traceContext});let i=this.sessionStore?.saveSessionInput?.({id:String(o),sessionID:this.sessionId,kind:"backgroundNotification",delivery:"queue",payload:{text:e.text,...e.taskId?{taskId:e.taskId}:{},...e.originMeta?{originMeta:e.originMeta}:{}}});i&&(ofc(this,String(o),i),this.trackResidencyBlockingWork(i).catch(a=>{this.logger?.warn("Failed to admit background notification to ledger",{...lr(e.traceContext),errorMessage:a instanceof Error?a.message:String(a),event:"session_input.admit_failed",module:"core.runtime",status:"failed"})}))}function Mii(e){this.config.taskType==="subagent_child"&&(this.backgroundTaskNotificationsSealed=!0,this.backgroundTaskNotificationSealReason=e.reason,this.logger?.info?.("Subagent runtime background task notifications sealed",{...lr(e.traceContext??this.rootTraceContext),event:"runtime.background_task_notifications.sealed",module:"core.runtime",reason:e.reason}))}async function Nii(e){return(await t5n.call(this,[e],!0)).messageId}function efc(e){let t=e.filter(o=>o.originMeta?.subagentStall===void 0),n=t[0]?.originMeta?.backgroundSource;if(!(!n||t.some(o=>o.originMeta?.backgroundSource!==n)))return n}function tfc(e){if(e.length===1)return e[0].originMeta;let t=[];for(let c of e){let u=c.originMeta;if(!u?.workId.trim()||!u.title.trim())return;t.push(u)}let n=t[0];if(!n)return;let o=t.slice(0,Qpc).map(c=>c.title.trim()),i=t.length-o.length,a=[...o,...i>0?[`+${i}`]:[]].join(" \xB7 ");return{backgroundSource:n.backgroundSource,title:a,workId:n.workId}}function rfc(e){let t=r(n=>n.text.trimStart().startsWith(nfc),"isNotification");return[...e.filter(t),...e.filter(n=>!t(n))]}async function t5n(e,t=!1){let n=e[0],o=efc(e),i=rfc(e),a=tfc(i),c=i.map(v=>v.text),u=dTt(c),p=!t&&c.length>1?c:void 0;await this.ensureContextInitialized(n.traceContext);let h=Fl(),_=t?"task_notification_steer":"task_notification";this.messageHistory.addUser(p?p.map(v=>({type:"text",text:v})):u,VC(_)),await this.persistSyntheticUserNoticeForSession({messageID:h,metadata:{inputPresentation:_,...a?{originMeta:a}:{},visibility:"model-only"},sessionId:this.sessionId,source:"background_task",text:p??u,traceContext:n.traceContext,visibility:"model-only"});for(let v of e)await this.sessionStore?.markSessionInputPromoted?.({id:String(v.id),sessionID:this.sessionId,promotedMessageID:h}).catch(b=>{this.logger?.warn("Failed to mark background notification promoted",{...lr(v.traceContext),commandId:v.id,errorMessage:b instanceof Error?b.message:String(b),event:"session_input.promote_mark_failed",module:"core.runtime",status:"failed"})});return{...o?{backgroundSource:o}:{},messageId:h,...a?{originMeta:a}:{},text:u}}function ofc(e,t,n){let o=e5n.get(e);o||(o=new Map,e5n.set(e,o));let i=n.catch(()=>{});o.set(t,i),i.then(()=>{o.get(t)===i&&o.delete(t)})}function Oii(e,t,n){let o=e.sessionStore?.settleSessionInput;if(!o)return;let i=String(t.id),a=(async()=>{await Promise.resolve(),await e5n.get(e)?.get(i),await o.call(e.sessionStore,{id:i,sessionID:e.sessionId,status:"discarded",reason:n})})();(e.trackResidencyBlockingWork?.(a)??a).catch(u=>{e.logger?.warn("Failed to settle dropped background notification",{...lr(t.traceContext),commandId:i,errorMessage:u instanceof Error?u.message:String(u),event:"session_input.settle_failed",module:"core.runtime",reason:n,status:"failed"})})}function dDt(e){let t=e.taskId?this.runtimeTaskRegistry.get(e.taskId):void 0,n=e.originMeta?.subagentStall;return n!==void 0&&!Rii(t,n)?(this.logger?.info?.("Dropped stale background subagent stall reminder",{...lr(e.traceContext),commandId:e.id,event:"runtime.background_task_notification.stall_reminder_stale",module:"core.runtime",taskId:e.taskId,taskStatus:t?.status}),Oii(this,e,"subagent_stall_reminder_stale"),!0):aDt({isSubagentChildRuntime:this.config.taskType==="subagent_child",notificationSealed:this.backgroundTaskNotificationsSealed,registryTask:t,toolName:e.toolName})?(this.logger?.info?.("Suppressed sealed subagent background Bash notification",{...lr(e.traceContext),commandId:e.id,event:"runtime.background_task_notification.suppressed",module:"core.runtime",reason:this.backgroundTaskNotificationSealReason,taskId:e.taskId,toolName:e.toolName}),Oii(this,e,"subagent_notifications_sealed"),!0):!1}function cfc(e,t,n){if(mPt(e)){if(e.background!==!0)return;let{agentId:p,childSessionId:h,outputFile:_}=e;return{agentId:p,childSessionId:h,outputFile:_,readRun:r(()=>R7e({agentId:p,outputFile:_}),"readRun")}}let o=t.output;if(typeof o!="string"||!o.startsWith(sfc))return;let i=o.match(/(?:^|\n)agentId:\s*([^\s(]+)/)?.[1];if(!i)return;let a=o.match(/(?:^|\n)output_file:[ \t]*([^\r\n]+)/)?.[1]?.trim(),c={...e,...t.metadata},u=typeof c.childSessionId=="string"?c.childSessionId:h0(`subagent_${i}`);return{agentId:i,childSessionId:u,outputFile:a,readRun:r(()=>hPt({agentId:i,outputFile:a,...n}),"readRun")}}async function Lii(e,t=performance.timeOrigin){if(!this.sessionStore)return;let n=new Map;for(let i of e)for(let a of i.parts)if(a.type==="text")for(let c of a.text.matchAll(afc)){let u=c[1]?.trim();u&&n.set(u,Math.max(n.get(u)??0,i.info.time.created))}let o=[];for(let i of e)if(i.info.role==="assistant")for(let a of i.parts){if(a.type!=="tool"||!kP(a.tool)||a.state.status!=="completed")continue;let c=cfc(a.metadata,a.state,{outputRootDir:this.config.subagents?.outputRootDir,parentSessionId:this.sessionId});if(!c||a.state.time.start>=t)continue;let{agentId:u,childSessionId:p,outputFile:h}=c;if(require(require("node:path").join(__dirname,"cli-config.cjs")).subagentExecutionState(h,p)!=="released")continue;if(this.runtimeTaskRegistry.get(u))continue;let _=await c.readRun(),v=n.get(u);if(v!==void 0&&(_?.resumedAt===void 0||v>=_.resumedAt)||_!==void 0&&_.status!=="running")continue;let b=await this.sessionStore.getSession(p);if(!b||b.time.updated>=t||lfc(await this.sessionStore.messages({sessionID:b.id})))continue;let k=a.state.input;o.push(uPt({agentId:u,description:typeof k.description=="string"&&k.description.trim()?k.description:"Subagent",error:ifc,outputFile:h??"",parentToolCallId:a.callID,status:"failed"}))}if(o.length!==0)return["The previous ZCode runtime process for this workspace exited unexpectedly (for example, because the system ran out of memory).",`${o.length===1?"This background agent was":"These background agents were"} still running and stopped with it. ${o.length===1?"It":"They"} will not report back.`,"Before relaunching, check what each agent already changed, then decide whether the work still needs to run. Tell the user if they are waiting on it.","",...o].join(`
14828
14828
  `)}function lfc(e){let t=e.findLast(n=>n.info.role==="assistant");return!t||t.info.role!=="assistant"?!1:t.info.error?t.info.error.name!==ED:t.parts.some(n=>n.type==="tool")?!1:!!(t.info.time.completed||t.info.finish)}var Qpc,nfc,e5n,ifc,sfc,afc,Oqe=V(()=>{"use strict";Ns();EV();ble();Zzn();WL();f8n();gPt();QY();uDt();r(Dii,"enqueueBackgroundTaskNotification");r(Mii,"sealBackgroundTaskNotifications");r(Nii,"persistBackgroundTaskNotificationCommand");Qpc=3;r(efc,"resolveBackgroundTaskNotificationSource");r(tfc,"resolveBackgroundTaskNotificationOriginMeta");nfc="<task-notification>";r(rfc,"orderTaskNotificationsForParsing");r(t5n,"persistBackgroundTaskNotificationBatch");e5n=new WeakMap;r(ofc,"rememberBackgroundNotificationAdmission");r(Oii,"settleDroppedBackgroundNotification");r(dDt,"shouldSuppressTaskNotificationRuntimeCommand");ifc="the ZCode runtime process exited before it finished",sfc="Async agent launched successfully.",afc=/<task-notification>(?:(?!<\/task-notification>)[\s\S])*?<task-id>([^<]+)<\/task-id>/g;r(cfc,"previousRuntimeBackgroundLaunch");r(Lii,"collectPreviousRuntimeAgentInterruptions");r(lfc,"childHasTerminalOutcome")});function ufc(e){return["<subagent-message>",`<agent-id>${Bs(e.agentId)}</agent-id>`,`<agent-type>${Bs(e.agentType)}</agent-type>`,`<summary>${Bs(e.summary)}</summary>`,`<message>${Bs(e.message)}</message>`,"</subagent-message>"].join(`
14829
14829
  `)}function Fii(e){let t=this.runtimeTaskRegistry.get(e.agentId)?.branchGeneration??this.branchGeneration;if(t!==this.branchGeneration){this.logger?.debug("Dropped stale-branch subagent response",{...lr(e.traceContext),agentId:e.agentId,branchGeneration:t,currentBranchGeneration:this.branchGeneration,event:"subagent.response.stale_branch_dropped",module:"core.runtime",responseId:e.responseId});return}let n={branchGeneration:t,responseId:e.responseId,agentId:e.agentId,agentType:e.agentType,childSessionId:e.childSessionId,childToolCallId:e.childToolCallId,...e.parentToolCallId?{parentToolCallId:e.parentToolCallId}:{},summary:e.summary,messageLength:e.message.length,traceContext:e.traceContext,createdAt:new Date,id:LP(),mode:"subagent-message",priority:"next",source:"subagent_message",text:ufc(e)};this.logger?.debug("Subagent response enqueued into runtime command queue",{...lr(n.traceContext),agentId:n.agentId,commandId:n.id,event:"subagent.response.runtime_enqueued",messageLength:n.messageLength,module:"core.runtime",queueSize:this.runtimeCommandQueue.size()+1,responseId:n.responseId,summary:n.summary.slice(0,200)}),this.enqueueRuntimeCommand(n)}async function pDt(e,t=!1){await this.ensureContextInitialized(e.traceContext);let n=Fl(),o=t?"subagent_reply_steer":"subagent_reply";return this.messageHistory.addUser(e.text,VC(o)),await this.persistSyntheticUserNoticeForSession({messageID:n,sessionId:this.sessionId,source:"subagent_message",text:e.text,traceContext:e.traceContext,visibility:"model-only",metadata:{inputPresentation:o,subagentMessage:{responseId:e.responseId,agentId:e.agentId,agentType:e.agentType,childSessionId:e.childSessionId,childToolCallId:e.childToolCallId,...e.parentToolCallId?{parentToolCallId:e.parentToolCallId}:{}}}}),n}var fDt=V(()=>{"use strict";Ns();EV();ble();WL();r(ufc,"formatSubagentMessage");r(Fii,"enqueueSubagentMessage");r(pDt,"persistSubagentMessageCommand")});function Dqe(e,t){return t.mode!=="task-notification"&&t.mode!=="subagent-message"&&t.mode!=="control-only-turn"||t.branchGeneration===e.branchGeneration?!1:(e.logger?.debug("Dropped queued stale-branch runtime command",{...lr(t.traceContext),branchGeneration:t.branchGeneration,commandId:t.id,currentBranchGeneration:e.branchGeneration,event:"runtime.command.stale_branch_dropped",mode:t.mode,module:"core.runtime"}),!0)}function mDt(e,t){if(t.type!==Je.BackgroundTaskUpdated&&t.type!==Je.BackgroundTaskCompleted&&t.type!==Je.SubagentMessage&&t.type!==Je.SubagentStopped)return!1;let n=t.payload&&typeof t.payload=="object"&&!Array.isArray(t.payload)?t.payload:{},o=typeof n.taskId=="string"?n.taskId:typeof n.agentId=="string"?n.agentId:void 0;if(!o)return!1;let i=e.runtimeTaskRegistry.get(o);return!i||i.branchGeneration===e.branchGeneration?!1:(e.logger?.debug("Dropped stale-branch runtime task event",{branchGeneration:i.branchGeneration,currentBranchGeneration:e.branchGeneration,event:"runtime.task_event.stale_branch_dropped",eventType:t.type,module:"core.runtime",taskId:o}),!0)}var Mqe=V(()=>{"use strict";Ns();r(Dqe,"isStaleBranchRuntimeCommand");r(mDt,"isStaleBranchRuntimeTaskEvent")});async function jii(){let e=this.runtimeCommandQueue.getByMaxPriority("next"),t=[],n=!1,o=!1,i=[],a=[];for(let c of e){if(c.mode==="control-only-turn")break;if(c.mode!=="task-notification"&&c.mode!=="subagent-message")continue;let u=this.runtimeCommandQueue.removeById(c.id);if(!u||Dqe(this,u))continue;let p;if(u.mode==="task-notification"){if(dDt.call(this,u))continue;p=await Nii.call(this,u)}else if(u.mode==="subagent-message")p=await pDt.call(this,u,!0);else continue;t.push(u.id),u.mode==="task-notification"&&u.originMeta?.backgroundSource==="subagent"&&u.originMeta.subagentStall===void 0&&(n=!0),u.mode==="task-notification"&&u.originMeta?.backgroundSource==="workflow"&&(o=!0),i.push(p),a.push(ZUe(u.text,VC(u.mode==="task-notification"?"task_notification_steer":"subagent_reply_steer")))}return{backgroundSubagentResultConsumed:n,workflowResultConsumed:o,consumedCommandIds:t,drained:t.length,messageIds:i,runtimeEntries:a}}var Bii=V(()=>{"use strict";ble();Oqe();fDt();Mqe();Bd();r(jii,"drainPendingRuntimeCommandsForActiveLoop")});function qii(e){return e.streamRecoveryRetryCount<Uii}function Nqe(e){for(let t of hDt(e)){let n=jqe(t.context),o=dw(t.providerCode)??dw(n?.providerCode)??dw(t.code)??dw(n?.code);if(o&&zii.has(o))return!0}return!1}function Wii(e){let t=_fc(e)??"3010",n=new Error(ffc,{cause:e instanceof Error?e:void 0});return n.name="StartPlanBusyAutoRetryExhaustedError",n.code="model_rate_limited",n.context={providerCode:t,reason:"rate_limited",retryable:!1,startPlanBusyAutoRetryExhausted:!0},n}function n5n(e){return e.streamRecoveryRetryCount+=1,{retryNumber:e.streamRecoveryRetryCount,maxRetries:Uii}}function Vii(e){return e.streamRecoveryRetryCount+=1,{retryNumber:e.streamRecoveryRetryCount,maxRetries:$ii.length}}function Hii(e){if(!(e.turnNumber<=0)&&pfc.has(e.providerId)&&Nqe(e.error))return $ii[e.state.streamRecoveryRetryCount]}async function Lqe(e,t,n,o,i){let a={attemptId:uQ(n.assistantMessageId),assistantMessageId:n.assistantMessageId,failureKind:vfc(o),message:o instanceof Error?o.message:String(o),retryNumber:i.retryNumber,maxRetries:i.maxRetries,...n.failedRequestId?{failedRequestId:n.failedRequestId}:{}},c=e.createEvent(Je.StreamRecoveryStarted,a,n.traceContext);await e.appendEvent(c,n.traceContext),t.events.push(c)}async function Fqe(e,t,n,o){let i=o.toolCallIds.at(-1),a=i?G7e(n.assistantMessageId,i):gfc(n.assistantMessageId),c=[e.createEvent(Je.StreamRecoveryAnchorSelected,{attemptId:uQ(n.assistantMessageId),anchorId:a,reason:o.reason,committedToolCallIds:o.toolCallIds},n.traceContext),e.createEvent(Je.StreamRecoveryTailDiscarded,{attemptId:uQ(n.assistantMessageId),anchorId:a,assistantMessageId:n.assistantMessageId,discardedReasoningBytes:o.discardedReasoningBytes,discardedTextBytes:o.discardedTextBytes,discardedToolCallIds:[]},n.traceContext),e.createEvent(Je.StreamRecoveryRetryStarted,{attemptId:uQ(n.assistantMessageId),anchorId:a,retryNumber:o.retryNumber,maxRetries:o.maxRetries,streamMode:"sse",...n.failedRequestId?{failedRequestId:n.failedRequestId}:{}},n.traceContext)];for(let u of c)await e.appendEvent(u,n.traceContext),t.events.push(u);t.pendingStreamRecoveryRequest={attemptId:uQ(n.assistantMessageId),anchorId:a,maxRetries:o.maxRetries,retryNumber:o.retryNumber,...n.failedRequestId?{recoveredFromRequestId:n.failedRequestId}:{}}}async function Gii(e){if(e.discardedReasoningBytes+e.discardedTextBytes<=0||!yfc(e.error))return!1;e.abortController.abort();let t=n5n(e.state);return await Lqe(e.runtime,e.state,e.options,e.error,t),await e.runtime.persistAssistantMessage(e.options.assistantMessageId,e.state.currentUserMessageId,e.assistantCreatedAt,{completed:Date.now(),error:{name:ED,data:{message:"Partial assistant output was discarded before a streaming retry.",retryNumber:t.retryNumber}},finish:N4e},e.options.traceContext,e.options.model),e.state.modelResponse="",e.state.modelStepCount+=1,wA(e.state),e.state.turnMachine=new Hf(e.state.turnMachine.receiveModelResponse("")),e.state.turnMachine=new Hf(e.state.turnMachine.aggregateResults()),await Fqe(e.runtime,e.state,e.options,{...t,discardedReasoningBytes:e.discardedReasoningBytes,discardedTextBytes:e.discardedTextBytes,reason:"no_tool_committed",toolCallIds:[]}),e.state.turnAbortSignal.removeEventListener("abort",e.turnAbortListener),!0}function gfc(e){return`${e}:${dfc}`}function _fc(e){for(let t of hDt(e)){let n=jqe(t.context),i=[dw(t.providerCode),dw(n?.providerCode),dw(t.code),dw(n?.code)].filter(a=>a!==void 0).find(a=>zii.has(a));if(i)return i}}function yfc(e){for(let t of hDt(e)){if(t.retryable===!0)return!0;let n=jqe(t.context);if(n?.retryable===!0)return!0;let o=dw(t.code)??dw(n?.code);if(o&&mfc.has(o))return!0;let i=dw(t.reason)??dw(n?.reason);if(i&&hfc.has(i)||dw(t.name)==="ModelStreamIdleTimeoutError")return!0;let c=dw(t.message);if(c&&bfc(c))return!0}return!1}function vfc(e){for(let t of hDt(e)){let n=jqe(t.context),o=dw(t.reason)??dw(n?.reason),i=dw(t.code)??dw(n?.code),a=dw(t.name),c=dw(t.message);if(o==="stream_idle_timeout"||i==="model_request_timeout"||i==="MODEL_REQUEST_TIMEOUT"||a==="ModelStreamIdleTimeoutError"||c!==void 0&&/\btimeout|timed out|stalled\b/i.test(c))return"provider_timeout";if(o==="network_error"||i==="model_network_error"||i==="MODEL_NETWORK_ERROR"||c!==void 0&&/\bECONNRESET|EPIPE|ETIMEDOUT\b/i.test(c))return"provider_network_error"}return e instanceof Error?"provider_stream_error":"unknown"}function bfc(e){return/\b(stream idle|stream stalled|timeout|timed out|ECONNRESET|EPIPE|ETIMEDOUT)\b/i.test(e)}function*hDt(e){let t=e,n=new WeakSet;for(let o=0;o<=6;o+=1){let i=jqe(t);if(!i||n.has(i))return;n.add(i),yield i,t=i.cause}}function jqe(e){if(!(e===null||typeof e!="object"))return e}function dw(e){return typeof e=="string"&&e.length>0?e:void 0}var Uii,dfc,zii,pfc,$ii,ffc,mfc,hfc,gDt=V(()=>{"use strict";Ns();tp();r5();Uii=10,dfc="previous-message-anchor",zii=new Set(["3008","3009","3010"]),pfc=new Set(["account:bigmodel-start-plan","account:zai-start-plan"]),$ii=[1e3,2e3],ffc="Start Plan is busy and automatic model stream recovery reached the maximum retry count.",mfc=new Set(["model_request_timeout","model_rate_limited","model_server_error","model_network_error","MODEL_REQUEST_TIMEOUT","MODEL_RATE_LIMITED","MODEL_SERVER_ERROR","MODEL_NETWORK_ERROR"]),hfc=new Set(["stream_idle_timeout","rate_limited","server_error","network_error","timeout"]);r(qii,"hasStreamRecoveryBudget");r(Nqe,"isStartPlanBusyStreamRecoveryFailure");r(Wii,"createStartPlanBusyAutoRetryExhaustedError");r(n5n,"beginStreamRecoveryAttempt");r(Vii,"beginStartPlanBusyAdmissionRetryAttempt");r(Hii,"getStartPlanBusyAdmissionRetryDelayMs");r(Lqe,"emitStreamRecoveryStarted");r(Fqe,"emitStreamRecoveryRetryEvents");r(Gii,"recoverPartialAssistantOutputFailure");r(gfc,"createPreviousMessageRecoveryAnchorId");r(_fc,"findStartPlanBusyProviderCode");r(yfc,"isRetryableStreamRecoveryFailure");r(vfc,"classifyStreamRecoveryFailure");r(bfc,"isTransientMessage");r(hDt,"walkErrorRecords");r(jqe,"asRecord");r(dw,"stringValue")});async function Jii(e,t,n){let o=e.agentTelemetry.detached({executionKind:"foreground",operation:"goal_completion_verification",targetKind:"goal",trigger:"turn",traceContext:t.traceContext});return o.run(async()=>{try{let i=await n();return o.setResultType("boolean"),o.finishCompleted(),i}catch(i){throw bg(i,t.abortSignal)?o.finishCancelled("abort_signal"):o.finishFailed("execute","unknown",i),i}})}var Kii=V(()=>{"use strict";Wle();r(Jii,"runTargetCompletionVerificationWithTelemetry")});async function Yii(e){return this.config.targetCompletionVerification?.enabled===!1||!this.sessionStore||e.target.status!=="active"?null:Jii(this,e,r(async()=>{let n=[],o=await xfc.call(this,{abortSignal:e.abortSignal,events:n,target:e.target,traceContext:e.traceContext});if(!o.passed)return{target:e.target,verification:o};let i=await this.readSessionTargetForContext(e.traceContext),a=await this.sessionStore.updateTargetStatus({sessionID:this.sessionId,status:"complete"})??e.target;return await this.recordTargetChanged({action:"status_updated",previousTarget:i,source:"runtime",target:a,traceContext:e.traceContext}),{target:a,verification:o}},"execute"))}async function xfc(e){let t=this.getSessionModelSelection(),n=yk(this,{selection:t}),o=bS(e.traceContext,{attributes:{model:`${n.providerId}/${n.modelId}`,querySource:r9,targetId:e.target.targetID}}),i=o.spanId??o.traceId,a=this.activeForegroundExecution?.foregroundExecutionId,c=await Efc.call(this,e.target.targetID),u=Tfc.call(this,e.traceContext);await this.appendEvent(this.createEvent(Je.TargetCompletionVerification,{...u,...a?{foregroundExecutionId:a}:{},goalIteration:c,status:"started",targetId:e.target.targetID,verificationId:i},o),o),Hx(this,{model:n});let p=Gz(this,{entries:Afc(this.messageHistory.borrowReadOnlyRuntimeEntries()),prompt:H0n(e.target),tools:[],applyCacheControl:!0,model:n}),h=HIe(p.request.messages,n.properties.inputFormat).messages,_=this.createEvent(Je.ModelRequest,{messages:h,providerId:String(n.providerId),modelId:String(n.modelId),querySource:r9,toolCount:0},o);await this.appendEvent(_,o),e.events.push(_);let v=Date.now(),b=e.events.length;try{let k=await Ifc.call(this,{abortSignal:e.abortSignal,events:e.events,request:{...p.request,messages:h},model:n,traceContext:o});pu(e.abortSignal);let x=this.extractToolCallsFromResult(k),I=this.createEvent(Je.ModelComplete,{content:k.text,querySource:r9,stopReason:k.finishReason,toolCallCount:x.length,usage:k.usage},o);await this.appendEvent(I,o),e.events.push(I),await t1(this,{events:e.events,model:n,networkEventStartIndex:b,querySource:r9,result:k,startedAt:v,status:"completed",toolCallCount:x.length,traceContext:o});let R=x.length>0?U4e("The completion verifier attempted to call tools instead of returning a verification result."):j4e(k.text);return await this.appendEvent(this.createEvent(Je.TargetCompletionVerification,{...u,...a?{foregroundExecutionId:a}:{},goalIteration:c,status:"completed",targetId:e.target.targetID,verification:R,verificationId:i},o),o),R}catch(k){if(await t1(this,{error:k,events:e.events,model:n,networkEventStartIndex:b,querySource:r9,startedAt:v,status:e.abortSignal?.aborted?"cancelled":"error",traceContext:o}),e.abortSignal?.aborted){let I=this.activeForegroundExecution?.preserveQueueAutoDrainOnCancel===!0;throw await this.appendEvent(this.createEvent(Je.TargetCompletionVerification,{...u,...a?{foregroundExecutionId:a}:{},goalIteration:c,status:"cancelled",targetId:e.target.targetID,...I?{preserveQueueAutoDrainOnCancel:!0}:{},verification:B4e("Completion verifier request was cancelled."),verificationId:i},o),o),await this.pauseActiveTargetForCancellation(o),k}this.logger?.warn("Goal completion verification failed open",{...lr(o),errorMessage:k instanceof Error?k.message:String(k),event:"target.completion_verification.failed_open",module:"core.runtime",status:"failed",targetId:e.target.targetID});let x=U4e(k instanceof Error?`Completion verifier request failed: ${k.message}`:"The completion verifier could not confirm that every goal requirement is complete.");return await this.appendEvent(this.createEvent(Je.TargetCompletionVerification,{...u,...a?{foregroundExecutionId:a}:{},goalIteration:c,status:"failed_closed",targetId:e.target.targetID,verification:x,verificationId:i},o),o),x}}function Tfc(e){let t=this.latestAssistantMessageId,n=this.latestAssistantTurnId??e.turnId;return{...t?{anchorAssistantMessageId:t}:{},...n?{anchorTurnId:n}:{}}}async function Ifc(e){let t=Zii.length+1;for(let n=1;n<=t;n+=1)try{let o={stack:[],error:void 0,hasError:!1};try{let i=Sfc(o,this.createModelStatusSink(e.traceContext,e.events),!1),a={metadata:lr(e.traceContext),modelCall:{operation:"goal_completion_verification"},statusSink:i,traceContext:e.traceContext,refreshRuntimeHeadersBeforeAttempt:Tk(this,{abortSignal:e.abortSignal,model:e.model,traceContext:e.traceContext})};return await xy(a,()=>e.model.generateText({abortSignal:e.abortSignal,...e.request,options:{maxOutputTokens:e.model.optionSpecs.maxOutputTokens.max}}))}catch(i){o.error=i,o.hasError=!0}finally{wfc(o)}}catch(o){let i=Zii[n-1];if(e.abortSignal?.aborted||i===void 0||!Cfc(o,e.model.providerId))throw o;this.logger?.warn("Goal completion verification retrying after Start Plan busy",{...lr(e.traceContext),attempt:n,event:"target.completion_verification.retry_start_plan_busy",maxAttempts:t,module:"core.runtime",retryDelayMs:i,status:"waiting"}),await new Promise(a=>setTimeout(a,i)),pu(e.abortSignal)}throw new Error("Goal completion verification retry loop exhausted unexpectedly.")}function Cfc(e,t){return kfc.has(t)&&Nqe(e)}async function Efc(e){return(await this.rebuildProjection()).targetCompletionVerificationTimeline.filter(i=>i.targetId===e).reduce((i,a,c)=>Math.max(i,a.goalIteration??c+1),0)+1}function Afc(e){let t=e.at(-1);return!t||xu(t)||t?.message.role!=="assistant"||!t.message.toolCalls||t.message.toolCalls.length===0?e:e.slice(0,-1)}var Sfc,wfc,Zii,kfc,Xii=V(()=>{"use strict";Ns();tp();YPt();Bd();Xz();ZL();gI();gDt();rB();Kii();Sfc=function(e,t,n){if(t!=null){if(typeof t!="object"&&typeof t!="function")throw new TypeError("Object expected.");var o,i;if(n){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");o=t[Symbol.asyncDispose]}if(o===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");o=t[Symbol.dispose],n&&(i=o)}if(typeof o!="function")throw new TypeError("Object not disposable.");i&&(o=r(function(){try{i.call(this)}catch(a){return Promise.reject(a)}},"dispose")),e.stack.push({value:t,dispose:o,async:n})}else n&&e.stack.push({async:!0});return t},wfc=(function(e){return function(t){function n(c){t.error=t.hasError?new e(c,t.error,"An error was suppressed during disposal."):c,t.hasError=!0}r(n,"fail");var o,i=0;function a(){for(;o=t.stack.pop();)try{if(!o.async&&i===1)return i=0,t.stack.push(o),Promise.resolve().then(a);if(o.dispose){var c=o.dispose.call(o.value);if(o.async)return i|=2,Promise.resolve(c).then(a,function(u){return n(u),a()})}else i|=1}catch(u){n(u)}if(i===1)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}return r(a,"next"),a()}})(typeof SuppressedError=="function"?SuppressedError:function(e,t,n){var o=new Error(n);return o.name="SuppressedError",o.error=e,o.suppressed=t,o}),Zii=[1e3,2e3],kfc=new Set(["account:bigmodel-start-plan","account:zai-start-plan"]);r(Yii,"verifyActiveTargetCompletionForContinuation");r(xfc,"verifyTargetCompletion");r(Tfc,"targetCompletionVerificationAnchor");r(Ifc,"generateTargetCompletionVerificationText");r(Cfc,"isTargetVerifierStartPlanBusyFailure");r(Efc,"getNextTargetCompletionVerificationIteration");r(Afc,"withoutTrailingPendingAssistantToolCallEntries")});function EQ(e,t){return new Promise((n,o)=>{let i=!1,a=t.abortSignal,c=r(()=>{a?.removeEventListener("abort",_)},"cleanup"),u=r(v=>{i||(i=!0,c(),n(v))},"resolveCommand"),p=r(v=>{i||(i=!0,c(),o(v))},"rejectCommand"),h=t.createCommand({reject:p,resolve:u});function _(){if(i)return;if(e.runtimeCommandQueue.removeById(h.id)){t.onCommandCancelled?.(),p(fA(a?.reason));return}e.runtimeCommandQueue.markCancelPending(h.id)}if(r(_,"abortQueuedCommand"),a?.aborted){t.onCommandCancelled?.(),p(fA(a.reason));return}a?.addEventListener("abort",_,{once:!0});try{t.onCommandAccepted?.()}catch(v){t.onCommandCancelled?.(),p(v);return}e.enqueueRuntimeCommand(h)})}var Bqe=V(()=>{"use strict";tp();r(EQ,"enqueueCancellableRuntimeCommand")});async function Qii(e){let{traceContext:t,...n}=e,o=this.createEvent(Je.TargetChanged,n,t);await this.appendEvent(o,t)}async function esi(e){let t=e?.traceContext??this.rootTraceContext;return await EQ(this,{abortSignal:e?.abortSignal,createCommand:r(({reject:n,resolve:o})=>{let i={...e?.abortSignal?{abortSignal:e.abortSignal}:{},...e?.inputId!==void 0?{inputId:e.inputId}:{},...e?.intent?{intent:e.intent}:{},traceContext:t,...e?.verifyBeforeContinue!==void 0?{verifyBeforeContinue:e.verifyBeforeContinue}:{}};return{createdAt:new Date,id:LP(),mode:"target-continuation",options:i,priority:"next",reject:n,resolve:o,traceContext:t}},"createCommand")})}async function _Dt(e){let t=e.traceContext,n=await nsi.call(this,t);if(!n)return null;if(e.verifyBeforeContinue===!0&&await Rfc.call(this))return this.logger?.info("Goal continuation deferred while background tasks are running",{...lr(t),event:"target.continuation.deferred_background_running",module:"core.runtime",status:"waiting",targetId:n.targetID}),null;let o=e.verifyBeforeContinue?await Yii.call(this,{abortSignal:e.abortSignal,target:n,traceContext:t}):null;if(o?.verification.passed)return this.logger?.info("Goal continuation skipped after completion verifier passed",{...lr(t),event:"target.continuation.skipped_complete",module:"core.runtime",status:"completed",targetId:o.target.targetID}),null;if(o&&!o.verification.nextAction?.trim())return this.logger?.warn("Goal continuation skipped after verifier failed without next action",{...lr(t),event:"target.continuation.skipped_no_next_action",module:"core.runtime",reason:o.verification.reason,targetId:o.target.targetID}),null;let i=await this.readSessionTargetForContext(t);if(!i||i.status!=="active"||i.targetID!==n.targetID)return this.logger?.info("Goal continuation skipped after target changed during verification",{...lr(t),currentStatus:i?.status??"missing",currentTargetId:i?.targetID,event:"target.continuation.skipped_inactive_after_verification",module:"core.runtime",targetId:n.targetID}),null;let a=i,c=WC("target_continuation",V0n(a,o?.verification)),u=bS(t,{sessionId:this.sessionId,attributes:{targetId:a.targetID,targetContinuation:!0}});return this.logger?.info("Goal continuation started",{...lr(u),event:"target.continuation.started",module:"core.runtime",status:"started",targetId:a.targetID}),await this.executeTurnCommand(c,void 0,{abortSignal:e.abortSignal,inputId:e.inputId,intent:e.intent,inputSource:"goal-continuation",inputVisibility:"model-only",targetId:a.targetID,traceContext:u})}async function tsi(e){return this.hasActiveOrQueuedTurnWork()?null:await nsi.call(this,e)}async function nsi(e){if(!this.sessionStore||this.getPlanEnabled()||this.activeTurn||this.activeTurnStartReservation||!this.sessionPersisted)return null;let t=await this.readSessionTargetForContext(e);return!t||t.status!=="active"?null:t}async function Rfc(){return pTt(this.runtimeTaskRegistry)}async function rsi(e){let t=e.startedTarget;if(!t||!this.sessionStore||t.status!=="active")return;let n=e.usage?.totalTokens??0,o=Date.now();try{let i=await this.readSessionTargetForContext(e.traceContext),a=this.sessionStore.finishTargetRun?await this.sessionStore.finishTargetRun({endedAtMs:o,inputID:e.inputID,sessionID:this.sessionId,targetID:t.targetID,tokensUsedDelta:n}):await this.sessionStore.accountTargetUsage({sessionID:this.sessionId,targetID:t.targetID,tokensUsedDelta:n,timeUsedSecondsDelta:Math.max(0,Math.ceil((o-e.startedAtMs)/1e3))});a?.targetID===t.targetID&&await this.recordTargetChanged({action:this.sessionStore.finishTargetRun?"run_finished":"usage_accounted",previousTarget:i,source:"runtime",target:a,traceContext:e.traceContext})}catch(i){this.logger?.warn("Failed to account goal turn completion",{...lr(e.traceContext),errorMessage:i instanceof Error?i.message:String(i),event:"target.account.failed",module:"core.runtime",status:"failed",targetId:t.targetID})}}async function osi(e){let t=e.startedTarget;if(!t||!this.sessionStore?.startTargetRun||t.status!=="active")return t;try{let n=await this.sessionStore.startTargetRun({inputID:e.inputID,sessionID:this.sessionId,startedAtMs:e.startedAtMs,targetID:t.targetID});return n?.targetID===t.targetID?(await this.recordTargetChanged({action:"run_started",previousTarget:t,source:"runtime",target:n,traceContext:e.traceContext}),n):t}catch(n){return this.logger?.warn("Failed to start goal active run accounting",{...lr(e.traceContext),errorMessage:n instanceof Error?n.message:String(n),event:"target.run_start.failed",module:"core.runtime",status:"failed",targetId:t.targetID}),t}}async function isi(e){let t=e.startedTarget;if(!(!t||!this.sessionStore?.heartbeatTargetRun)&&t.status==="active")try{await this.sessionStore.heartbeatTargetRun({inputID:e.inputID,seenAtMs:e.seenAtMs,sessionID:this.sessionId,targetID:t.targetID})}catch(n){this.logger?.debug("Failed to heartbeat goal active run accounting",{...lr(e.traceContext),errorMessage:n instanceof Error?n.message:String(n),event:"target.run_heartbeat.failed",module:"core.runtime",status:"failed",targetId:t.targetID})}}async function ssi(e){let t=e.startedTarget;if(!t||!this.sessionStore?.finishTargetRun||t.status!=="active")return t;try{let n=await this.readSessionTargetForContext(e.traceContext),o=await this.sessionStore.finishTargetRun({endedAtMs:e.endedAtMs,inputID:e.inputID,sessionID:this.sessionId,status:e.status,targetID:t.targetID});return o?.targetID===t.targetID?(await this.recordTargetChanged({action:"run_finished",previousTarget:n,source:"runtime",target:o,traceContext:e.traceContext}),o):t}catch(n){return this.logger?.warn("Failed to finish goal active run accounting",{...lr(e.traceContext),errorMessage:n instanceof Error?n.message:String(n),event:"target.run_finish.failed",module:"core.runtime",status:"failed",targetId:t.targetID}),t}}async function asi(e){if(!this.sessionStore)return;let t=await this.readSessionTargetForContext(e);if(!(!t||t.status!=="active"))try{let n=await this.sessionStore.updateTargetStatus({sessionID:this.sessionId,status:"paused"});n&&await this.recordTargetChanged({action:"status_updated",previousTarget:t,source:"runtime",target:n,traceContext:e})}catch(n){throw Mr(qn.InvalidStateTransition,"Failed to pause active goal after turn cancellation",{cause:n instanceof Error?n:new Error(String(n)),context:{sessionId:this.sessionId,targetId:t.targetID},recoverable:!0})}}async function csi(e){return!this.sessionStore||this.getPlanEnabled()?null:await this.readSessionTargetForContext(e)}var uF=V(()=>{"use strict";Ns();EV();bz();I6();Xii();Bqe();r(Qii,"recordTargetChanged");r(esi,"continueActiveTargetIfIdle");r(_Dt,"executeTargetContinuationCommand");r(tsi,"targetContinuationCandidate");r(nsi,"targetContinuationCandidateForCommand");r(Rfc,"hasRunningBackgroundTaskForGoalContinuation");r(rsi,"accountTargetTurnCompletion");r(osi,"startTargetTurnAccounting");r(isi,"heartbeatTargetTurnAccounting");r(ssi,"finishTargetTurnAccounting");r(asi,"pauseActiveTargetForCancellation");r(csi,"activatePausedTargetAfterResume")});async function lsi(e){let t=e.traceContext??this.rootTraceContext;return await EQ(this,{abortSignal:e.abortSignal,createCommand:r(({reject:n,resolve:o})=>({createdAt:new Date,id:LP(),mode:"target-continuation-loop",options:{...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.inputId!==void 0?{inputId:e.inputId}:{},...e.intent?{intent:e.intent}:{},traceContext:t,trigger:e.trigger,...e.verifyBeforeFirstContinue!==void 0?{verifyBeforeFirstContinue:e.verifyBeforeFirstContinue}:{}},priority:"next",reject:n,resolve:o,traceContext:t}),"createCommand")})}async function yDt(e){let t=e.traceContext??this.rootTraceContext,n=ode(e.intent,t.attributes),o=n?{...t,attributes:{...t.attributes,[pQ]:n}}:t,i=e.verifyBeforeFirstContinue===!0,a=null,c=e.yieldBeforeFirstContinue!==!1,u=e.intent;for(;!e.abortSignal?.aborted;){if(c&&this.runtimeCommandQueue.hasPending()||e.trigger==="task-notification"&&i&&this.config.targetCompletionVerification?.enabled===!1)return a;let p=await _Dt.call(this,{...e.abortSignal?{abortSignal:e.abortSignal}:{},...e.inputId!==void 0?{inputId:e.inputId}:{},...u?{intent:u}:{},traceContext:o,verifyBeforeContinue:i});if(!p)return a;a=p,u=void 0,i=!0,c=!0}return a}var r5n=V(()=>{"use strict";YIe();EV();uF();Bqe();r(lsi,"continueActiveTargetLoop");r(yDt,"runActiveTargetContinuationLoop")});function usi(e){let t=e.mode==="task-notification"?e.taskId:e.mode==="subagent-message"?e.agentId:void 0;if(t&&this.runtimeTaskRegistry.get(t)?.offPeakCancelled)return;let n=t&&this.runtimeTaskRegistry.get(t)?.offPeakExecutionId;n&&(e={...e,offPeakExecutionId:n}),this.runtimeCommandQueue.enqueue(e),e.mode==="task-notification"&&this.logger?.info?.("Background task notification enqueued into runtime command queue",{...lr(e.traceContext),commandId:e.id,event:"background_task.notification.runtime_enqueued",module:"core.runtime",queueSize:this.runtimeCommandQueue.size()}),this.drainRuntimeCommandQueue()}async function dsi(){if(!this.runtimeCommandDrainActive){this.runtimeCommandDrainActive=!0;try{let e;for(;(e=Pfc.call(this)).length>0;){let t=e[0];if(t){if(loi(this,t),t.mode==="task-notification"){let n=e.filter(o=>o.mode==="task-notification");if(n.length!==e.length)throw new Error("Runtime command queue returned a mixed task-notification batch");await hsi.call(this,n);continue}if(e.length!==1)throw new Error(`Runtime command queue returned an unsupported ${t.mode} batch`);await Dfc.call(this,t)}}}finally{this.runtimeCommandDrainActive=!1,wti(this)}if(this.runtimeCommandQueue.hasPending()&&this.foregroundPromotionLease===void 0){await this.drainRuntimeCommandQueue();return}o5n.call(this)||this.workflowBlockedReminder?.sessionIdle()}}function Pfc(){let e=this.foregroundPromotionLease;if(!e)return this.runtimeCommandQueue.dequeueNextBatch();let t=this.runtimeCommandQueue.snapshot().find(o=>Ofc(o)===e.promotedInputId);if(!t)return Object.freeze([]);let n=this.runtimeCommandQueue.removeById(t.id);return n?(this.foregroundPromotionLease=void 0,Object.freeze([n])):Object.freeze([])}function Ofc(e){if(e.mode==="prompt"||e.mode==="target-continuation"||e.mode==="target-continuation-loop")return e.options?.inputId}function o5n(){return this.foregroundPromotionLease!==void 0||this.activeForegroundExecution!==void 0||this.runtimeCommandDrainActive||this.runtimeCommandQueue.hasPending()||this.activeTurn!==void 0||this.activeTurnStartReservation!==void 0}function psi(e){let t=this.foregroundPromotionLease;return t?t.leaseId===e.leaseId?{kind:"acquired",leaseId:t.leaseId}:{kind:"conflict",leaseId:t.leaseId}:e.mode==="idle-only"&&(this.activeForegroundExecution!==void 0||this.runtimeCommandDrainActive||this.runtimeCommandQueue.hasPending()||this.activeTurn!==void 0||this.activeTurnStartReservation!==void 0)?{kind:"busy"}:(this.foregroundPromotionLease={leaseId:e.leaseId,promotedInputId:e.promotedInputId},{kind:"acquired",leaseId:e.leaseId})}function fsi(e){return this.foregroundPromotionLease?.leaseId!==e?!1:(this.foregroundPromotionLease=void 0,this.drainRuntimeCommandQueue(),!0)}async function msi(e,t){if(e.mode==="prompt"&&e.options?.continueActiveTargetAfterTurn===!0){let n=e.options.traceContext??e.traceContext,o=ode(e.options.intent,n.attributes);return await yDt.call(this,{abortSignal:t,inputId:e.options.inputId,traceContext:o?{...n,attributes:{...n.attributes,[pQ]:o}}:n,trigger:"user-prompt",verifyBeforeFirstContinue:!0})}if(e.mode==="task-notification")try{return await yDt.call(this,{abortSignal:t,traceContext:e.traceContext,trigger:"task-notification",verifyBeforeFirstContinue:!0})}catch(n){this.logger?.warn("Post-command goal continuation failed",{...lr(e.traceContext),errorMessage:n instanceof Error?n.message:String(n),event:"target.continuation.after_command_failed",module:"core.runtime"})}return null}async function Dfc(e){if(e.mode==="task-notification"){await hsi.call(this,[e]);return}if(Dqe(this,e))return;let t=gsi.call(this,e);try{if(e.mode==="prompt"){if(this.runtimeCommandQueue.consumeCancelPending(e.id)){e.startReservation&&this.releaseTurnStart(e.startReservation.turnId),e.reject(fA(e.options?.abortSignal?.reason));return}try{let n=await this.executeTurnCommand(e.input,e.attachments,{...e.options,abortSignal:t.controller.signal},e.startReservation),o=await msi.call(this,e,t.controller.signal);e.resolve(o??n)}finally{this.runtimeCommandQueue.clearCancelPending(e.id)}return}if(e.mode==="target-continuation"){if(this.runtimeCommandQueue.consumeCancelPending(e.id)){e.reject(fA(e.options.abortSignal?.reason));return}try{let n=await _Dt.call(this,{...e.options,abortSignal:t.controller.signal});e.resolve(n)}finally{this.runtimeCommandQueue.clearCancelPending(e.id)}return}if(e.mode==="target-continuation-loop"){if(this.runtimeCommandQueue.consumeCancelPending(e.id)){e.reject(fA(e.options.abortSignal?.reason));return}try{let n=await yDt.call(this,{...e.options,abortSignal:t.controller.signal,yieldBeforeFirstContinue:!1});e.resolve(n)}finally{this.runtimeCommandQueue.clearCancelPending(e.id)}return}if(e.mode==="subagent-message"){this.logger?.debug("Subagent response command started",{...lr(e.traceContext),agentId:e.agentId,commandId:e.id,event:"subagent.response.command_started",messageLength:e.messageLength,module:"core.runtime",queueSize:this.runtimeCommandQueue.size(),responseId:e.responseId,summary:e.summary.slice(0,200)});let n=await pDt.call(this,e);await this.executeTurnCommand(e.text,void 0,{offPeakExecutionId:e.offPeakExecutionId,abortSignal:t.controller.signal,inputSource:"subagent_message",inputVisibility:"model-only",recordedInputMessageId:n,skipInputRecord:!0,skipUserPromptSubmitHooks:!0,traceContext:e.traceContext}),this.logger?.debug("Subagent response command completed",{...lr(e.traceContext),agentId:e.agentId,commandId:e.id,event:"subagent.response.command_completed",messageId:n,module:"core.runtime",queueSize:this.runtimeCommandQueue.size(),responseId:e.responseId});return}if(e.mode==="control-only-turn"){await Ooi.call(this,e);return}}catch(n){if(e.mode==="prompt"||e.mode==="target-continuation"||e.mode==="target-continuation-loop"){e.reject(n);return}this.logger?.warn("Runtime command failed",{...lr(e.traceContext),commandMode:e.mode,errorMessage:n instanceof Error?n.message:String(n),event:"runtime_command.failed",module:"core.runtime"})}finally{_si.call(this,t)}}async function hsi(e){let t=e.filter(c=>!Dqe(this,c)&&!dDt.call(this,c)),n=t[0];if(!n)return;let o={...n.traceContext,attributes:gQo(t.map(c=>c.traceContext))},i=gsi.call(this,n),a=t.map(c=>c.id);try{let c=await t5n.call(this,t);this.logger?.info?.("Background task notification batch started",{...lr(n.traceContext),batchSize:t.length,commandId:n.id,commandIds:a,event:"background_task.notification.batch_started",messageId:c.messageId,module:"core.runtime"}),await this.executeTurnCommand(c.text,void 0,{offPeakExecutionId:n.offPeakExecutionId,inputId:Zq(),abortSignal:i.controller.signal,backgroundSubagentResultConsumed:t.some(u=>u.originMeta?.backgroundSource==="subagent"&&u.originMeta.subagentStall===void 0),workflowResultConsumed:t.some(u=>u.originMeta?.backgroundSource==="workflow"),...c.backgroundSource?{backgroundSource:c.backgroundSource}:{},inputSource:"background_task",inputVisibility:"model-only",...c.originMeta?{originMeta:c.originMeta}:{},recordedInputMessageId:c.messageId,skipInputRecord:!0,skipUserPromptSubmitHooks:!0,traceContext:o}),await msi.call(this,{...n,traceContext:o},i.controller.signal),this.logger?.info?.("Background task notification batch completed",{...lr(n.traceContext),batchSize:t.length,commandId:n.id,commandIds:a,event:"background_task.notification.batch_completed",messageId:c.messageId,module:"core.runtime"})}catch(c){this.logger?.warn("Background task notification batch failed",{...lr(n.traceContext),batchSize:t.length,commandId:n.id,commandIds:a,errorMessage:c instanceof Error?c.message:String(c),event:"background_task.notification.batch_failed",module:"core.runtime"})}finally{_si.call(this,i)}}function gsi(e){let t=new AbortController,n=Mfc(e),o=r(()=>{t.abort(n?.reason)},"abortFromParent");n?.aborted?o():n?.addEventListener("abort",o,{once:!0});let i={controller:t,disposeParentAbort:r(()=>{n?.removeEventListener("abort",o)},"disposeParentAbort"),foregroundExecutionId:String(e.id),preserveQueueAutoDrainOnCancel:!1};return this.activeForegroundExecution=i,i}function _si(e){e.disposeParentAbort(),this.activeForegroundExecution===e&&(this.activeForegroundExecution=void 0)}function Mfc(e){if(e.mode==="prompt"||e.mode==="target-continuation"||e.mode==="target-continuation-loop")return e.options?.abortSignal}function ysi(e={}){let t=this.activeForegroundExecution;if(!t||t.controller.signal.aborted)return{kind:"idle"};if(e.expectedForegroundExecutionId!==void 0&&e.expectedForegroundExecutionId!==t.foregroundExecutionId)return{kind:"mismatch",activeForegroundExecutionId:t.foregroundExecutionId};t.preserveQueueAutoDrainOnCancel=e.preserveQueueAutoDrainOnCancel===!0;let n=e.reason??"foreground execution stopped";return t.controller.abort(t.preserveQueueAutoDrainOnCancel?v5r(n):new Error(n)),{kind:"stopped",foregroundExecutionId:t.foregroundExecutionId}}function vsi(){return this.activeForegroundExecution?.foregroundExecutionId}var bsi=V(()=>{"use strict";vn();YIe();Ns();wV();To();Oqe();fDt();QOt();tp();uF();r5n();Mqe();GOt();r(usi,"enqueueRuntimeCommand");r(dsi,"drainRuntimeCommandQueue");r(Pfc,"dequeueNextRunnableBatch");r(Ofc,"runtimeCommandInputId");r(o5n,"hasActiveOrQueuedTurnWork");r(psi,"acquireForegroundPromotionLease");r(fsi,"releaseForegroundPromotionLease");r(msi,"runPostCommandActiveTargetLoop");r(Dfc,"runRuntimeCommand");r(hsi,"runTaskNotificationBatch");r(gsi,"beginForegroundExecution");r(_si,"finishForegroundExecution");r(Mfc,"runtimeCommandAbortSignal");r(ysi,"stopActiveForegroundExecution");r(vsi,"getActiveForegroundExecutionId")});function Ssi(e){return this.residencyBlockingWork.add(e),this.residencyBlockingWorkCount=this.residencyBlockingWork.size,e.finally(()=>{this.residencyBlockingWork.delete(e),this.residencyBlockingWorkCount=this.residencyBlockingWork.size;for(let t of this.workChanged)t()})}function wsi(){return bQ(this)?.lifecycle.terminal===!1||this.hasActiveOrQueuedTurnWork()||this.hasRunningBackgroundTasks()||this.residencyBlockingWorkCount>0||(this.memoryExtractionScheduler?.hasPendingWork()??!1)||this.memoryRecallPrefetch!==void 0&&!this.memoryRecallPrefetch.settled}var ksi=V(()=>{"use strict";wV();r(Ssi,"trackResidencyBlockingWork");r(wsi,"hasResidencyBlockingWork")});function xsi(e){let t=e.profileSelection,n=e.overrideSelection?{effectiveSelection:e.overrideSelection}:t?e.resolveSelection?e.resolveSelection(kg(t)):{effectiveSelection:t}:{effectiveSelection:e.parentSelection??null};if(!n.effectiveSelection||n.selectionIssue){let o=n.selectionIssue??"selection-missing",i=e.overrideSelection??t??e.parentSelection,a=i?`; selection=${i.providerId}/${i.modelId}`:"";throw Mr(qn.ConfigurationError,`Cannot start subagent: ${Nfc[o]} [reason=${o}${a}]`,{recoverable:!0,context:{selectionIssue:o,reason:o,...n.effectiveSelection?{providerId:n.effectiveSelection.providerId,modelId:n.effectiveSelection.modelId}:{}}})}return{hasConcreteModel:t!=null,selection:kg(n.effectiveSelection)}}var Nfc,Tsi=V(()=>{"use strict";Ns();n5();Nfc={"selection-missing":"No model selected / \u672A\u9009\u62E9\u6A21\u578B","account-connection-unavailable":"Account connection unavailable / \u5F53\u524D\u8D26\u53F7\u8FDE\u63A5\u4E0D\u53EF\u7528","provider-not-found":"Provider unavailable / \u4F9B\u5E94\u5546\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528","model-not-found":"Model unavailable / \u6A21\u578B\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528","reasoning-level-missing":"No reasoning level selected / \u672A\u9009\u62E9\u601D\u8003\u6863\u4F4D","reasoning-level-not-supported":"Reasoning level unsupported / \u4E0D\u652F\u6301\u6240\u9009\u601D\u8003\u6863\u4F4D"};r(xsi,"resolveSubagentSelection")});function Isi(e,t){return{async send(n){let o=await Lfc(e,t,n);if(o.kind==="rejected")throw new Error(`Subagent message rejected: ${o.reason}`);return"steered"}}}async function Lfc(e,t,n){let o=n.message;for(let i=0;i<20;i++){let a=await e.steerTurn({delivery:"guide",inputPresentation:"coordinator_steer",input:o,inputId:n.id,traceContext:n.traceContext??t.traceContext});if(a.kind!=="rejected"||a.reason!=="no_active_turn")return a;await Ffc(10)}return e.steerTurn({delivery:"guide",inputPresentation:"coordinator_steer",input:o,inputId:n.id,traceContext:n.traceContext??t.traceContext})}function Ffc(e){return new Promise(t=>setTimeout(t,e))}var Csi=V(()=>{"use strict";r(Isi,"createSubagentMessageSink");r(Lfc,"steerSubagentMessage");r(Ffc,"sleep")});function Esi(e,t){if(e==="*")return Object.values(t).some(o=>o.status==="connected");let n=e.toLowerCase();return Object.entries(t).some(([o,i])=>i.status==="connected"&&mMo(n,o))}function i5n(e){let t=new Set;for(let n of e){let o=jfc(n);o&&t.add(o)}return[...t]}function Asi(e,t){let n=new Set(i5n(e).filter(o=>o!=="*").map(o=>o.toLowerCase()));return n.size===0?[]:t.filter(o=>n.has(o.trim().toLowerCase())||n.has(mk(o).toLowerCase()))}function jfc(e){let t=e.trim();if(t==="mcp__*"||t==="mcp")return"*";if(!t.startsWith("mcp__"))return;let[,n]=t.split("__");return n&&n.length>0?n:void 0}var Rsi=V(()=>{"use strict";$L();r(Esi,"matchesRequiredMcpServer");r(i5n,"extractRequiredMcpServerNames");r(Asi,"resolveReferencedMcpServerNames");r(jfc,"extractRequiredMcpServerName")});function Osi(e){return{respond(t){let n=e.createResponseId?.()??`response_${(0,Psi.randomUUID)()}`;try{return e.enqueue({responseId:n,agentId:e.agentId,agentType:e.agentType,childSessionId:e.childSessionId,childToolCallId:String(t.childToolCallId),...e.parentToolCallId?{parentToolCallId:e.parentToolCallId}:{},summary:t.summary,message:t.message,traceContext:t.trace}),{status:"success",responseId:n,message:"Response was queued for the coordinator."}}catch(o){return{status:"failed",responseId:n,message:"Response could not be queued for the coordinator.",error:o instanceof Error?o.message:String(o)}}}}}var Psi,Dsi=V(()=>{"use strict";Psi=require("node:crypto");r(Osi,"createCoordinatorResponsePort")});function Msi(e){let t=e.rootDir.endsWith(s5n.sep)?e.rootDir:`${e.rootDir}${s5n.sep}`,n=W3n(e.indexContent);return[Bfc.replace("<MEMORY_ROOT>/",t).replace("<SCOPE_GUIDANCE>",Ufc[e.scope]),"","## MEMORY.md","",n||"Your MEMORY.md is currently empty. When you save new memories, they will appear here."].join(`
14830
14830
  `)}var s5n,Bfc,Ufc,Nsi=V(()=>{"use strict";s5n=require("node:path");kIe();Bfc=["# Persistent Agent Memory","","You have a persistent, file-based memory system at `<MEMORY_ROOT>/`. This directory already exists \u2014 write to it directly with the Write tool (do not run mkdir or check for its existence).","","You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.","","If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.","","## Types of memory","","There are several discrete types of memory that you can store in your memory system:","","<types>","<type>"," <name>user</name>"," <description>Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together.</description>"," <when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>"," <how_to_use>When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have.</how_to_use>"," <examples>"," user: I'm a data scientist investigating what logging we have in place"," assistant: [saves user memory: user is a data scientist, currently focused on observability/logging]",""," user: I've been writing Go for ten years but this is my first time touching the React side of this repo"," assistant: [saves user memory: deep Go expertise, new to React and this project's frontend \u2014 frame frontend explanations in terms of backend analogues]"," </examples>","</type>","<type>"," <name>feedback</name>"," <description>Guidance the user has given you about how to approach work \u2014 both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious.</description>",` <when_to_save>Any time the user corrects your approach ("no not that", "don't", "stop doing X") OR confirms a non-obvious approach worked ("yes exactly", "perfect, keep doing that", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter \u2014 watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later.</when_to_save>`," <how_to_use>Let these memories guide your behavior so that the user does not need to offer the same guidance twice.</how_to_use>"," <body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave \u2014 often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>"," <examples>"," user: don't mock the database in these tests \u2014 we got burned last quarter when mocked tests passed but the prod migration failed"," assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration]",""," user: stop summarizing what you just did at the end of every response, I can read the diff"," assistant: [saves feedback memory: this user wants terse responses with no trailing summaries]",""," user: yeah the single bundled PR was the right call here, splitting this one would've just been churn"," assistant: [saves feedback memory: for refactors in this area, user prefers one bundled PR over many small ones. Confirmed after I chose this approach \u2014 a validated judgment call, not a correction]"," </examples>","</type>","<type>"," <name>project</name>"," <description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory.</description>",' <when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" \u2192 "2026-03-05"), so the memory remains interpretable after time passes.</when_to_save>'," <how_to_use>Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions.</how_to_use>"," <body_structure>Lead with the fact or decision, then a **Why:** line (the motivation \u2014 often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>"," <examples>"," user: we're freezing all non-critical merges after Thursday \u2014 mobile team is cutting a release branch"," assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]",""," user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements"," assistant: [saves project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup \u2014 scope decisions should favor compliance over ergonomics]"," </examples>","</type>","<type>"," <name>reference</name>"," <description>Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory.</description>"," <when_to_save>When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel.</when_to_save>"," <how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>"," <examples>",` user: check the Linear project "INGEST" if you want context on these tickets, that's where we track all pipeline bugs`,' assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"]',""," user: the Grafana board at grafana.internal/d/api-latency is what oncall watches \u2014 if you're touching request handling, that's the thing that'll page someone"," assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard \u2014 check it when editing request-path code]"," </examples>","</type>","</types>","","## What NOT to save in memory","","- Code patterns, conventions, architecture, file paths, or project structure \u2014 these can be derived by reading the current project state.","- Git history, recent changes, or who-changed-what \u2014 `git log` / `git blame` are authoritative.","- Debugging solutions or fix recipes \u2014 the fix is in the code; the commit message has the context.","- Anything already documented in AGENTS.md files.","- Ephemeral task details: in-progress work, temporary state, current conversation context.","","These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it \u2014 that is the part worth keeping.","","## How to save memories","","Saving a memory is a two-step process:","","**Step 1** \u2014 write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:","","```markdown","---","name: {{short-kebab-case-slug}}","description: {{one-line summary \u2014 used to decide relevance in future conversations, so be specific}}","metadata:"," type: {{user, feedback, project, reference}}","---","","{{memory content \u2014 for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines. Link related memories with [[their-name]].}}","```","","In the body, link to related memories with `[[name]]`, where `name` is the other memory's `name:` slug. Link liberally \u2014 a `[[name]]` that doesn't match an existing memory yet is fine; it marks something worth writing later, not an error.","","**Step 2** \u2014 add a pointer to that file in `MEMORY.md`. `MEMORY.md` is an index, not a memory \u2014 each entry should be one line, under ~150 characters: `- [Title](file.md) \u2014 one-line hook`. It has no frontmatter. Never write memory content directly into `MEMORY.md`.","","- `MEMORY.md` is always loaded into your conversation context \u2014 lines after 200 will be truncated, so keep the index concise","- Keep the name, description, and type fields in memory files up-to-date with the content","- Organize memory semantically by topic, not chronologically","- Update or remove memories that turn out to be wrong or outdated","- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.","","## When to access memories","- When memories seem relevant, or the user references prior-conversation work.","- You MUST access memory when the user explicitly asks you to check, recall, or remember.","- If the user says to *ignore* or *not use* memory: Do not apply remembered facts, cite, compare against, or mention memory content.","- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now \u2014 and update or remove the stale memory rather than acting on it.","","## Before recommending from memory","","A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it:","","- If the memory names a file path: check the file exists.","- If the memory names a function or flag: grep for it.","- If the user is about to act on your recommendation (not just asking about history), verify first.","",'"The memory says X exists" is not the same as "X exists now."',"","A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot.","","## Memory and other forms of persistence","Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.","- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.","- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.","","<SCOPE_GUIDANCE>"].join(`
@@ -15876,7 +15876,7 @@ Commands:
15876
15876
  marketplace remove <name> Remove a configured marketplace
15877
15877
  marketplace update [name] Refresh one marketplace, or all when omitted
15878
15878
 
15879
- Scopes: user (default), project. \`zcode plugin\` is an alias of \`zcode plugins\`.`;r(U3i,"runPluginsCommand");r(OJc,"runPluginsListCommand");r(DJc,"runPluginsInstallCommand");r(MJc,"runPluginsUpdateCommand");r(NJc,"reportInstallOutcome");r(z3i,"runPluginsSetCommand");r(LJc,"runPluginsDisableCommand");r(FJc,"runPluginsUninstallCommand");r(jJc,"runPluginsValidateCommand")});function UJc(e=process.env){let t=e.ZCODE_STORAGE_DIR?.trim()||(0,gpe.join)((0,W3i.homedir)(),".zcode");return(0,gpe.join)(t,"clipboard")}function V3i(e={}){let t=e.platform??process.platform,n=e.maxBytes??BJc,o=e.runCommand??WJc,i=e.tempDirectory??UJc(e.processEnv);return async(a={})=>t==="darwin"?await zJc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:i}):t==="linux"?await $Jc({maxBytes:n,runCommand:o,signal:a.abortSignal}):t==="win32"?await qJc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:i}):null}async function zJc(e){await(0,kB.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,kB.mkdtemp)((0,gpe.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,gpe.join)(t,"clipboard.png");try{return(await e.runCommand("osascript",["-e","set png_data to (the clipboard as \xABclass PNGf\xBB)","-e",`set fp to open for access POSIX file ${VJc(n)} with write permission`,"-e","write png_data to fp","-e","close access fp"],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await H3i(n,"image/png",e.maxBytes)}finally{await(0,kB.rm)(t,{force:!0,recursive:!0})}}async function $Jc(e){let t=[{args:["--type","image/png"],file:"wl-paste",mediaType:"image/png"},{args:["--type","image/jpeg"],file:"wl-paste",mediaType:"image/jpeg"},{args:["--type","image/gif"],file:"wl-paste",mediaType:"image/gif"},{args:["--type","image/webp"],file:"wl-paste",mediaType:"image/webp"},{args:["-selection","clipboard","-t","image/png","-o"],file:"xclip",mediaType:"image/png"},{args:["-selection","clipboard","-t","image/jpeg","-o"],file:"xclip",mediaType:"image/jpeg"},{args:["-selection","clipboard","-t","image/gif","-o"],file:"xclip",mediaType:"image/gif"},{args:["-selection","clipboard","-t","image/webp","-o"],file:"xclip",mediaType:"image/webp"}];for(let n of t){let o=await e.runCommand(n.file,n.args,{maxBytes:e.maxBytes,signal:e.signal}),i=G3i(o.stdout,n.mediaType,e.maxBytes);if(o.exitCode===0&&i)return i}return null}async function qJc(e){await(0,kB.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,kB.mkdtemp)((0,gpe.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,gpe.join)(t,"clipboard.png"),o=["Add-Type -AssemblyName System.Windows.Forms;","$img = Get-Clipboard -Format Image;","if ($null -eq $img) { exit 2 }",`$img.Save(${HJc(n)}, [System.Drawing.Imaging.ImageFormat]::Png);`].join(" ");try{return(await e.runCommand("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await H3i(n,"image/png",e.maxBytes)}finally{await(0,kB.rm)(t,{force:!0,recursive:!0})}}async function H3i(e,t,n){let o=await(0,kB.readFile)(e);return G3i(o,t,n)}function G3i(e,t,n){return e.byteLength===0||e.byteLength>n?null:{dataUrl:`data:${t};base64,${e.toString("base64")}`,mediaType:t,sizeBytes:e.byteLength}}async function WJc(e,t,n){return await new Promise(o=>{let i;try{i=(0,q3i.spawn)(e,t,{signal:n.signal,stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:Buffer.alloc(0)});return}let a=[],c=0,u=!1,p=r(h=>{u||(u=!0,o(h))},"finish");i.stdout?.on("data",h=>{if(c+=h.byteLength,c>n.maxBytes){i.kill();return}a.push(h)}),i.on("error",()=>p({exitCode:-1,stdout:Buffer.alloc(0)})),i.on("close",(h,_)=>{p({exitCode:h,signal:_,stdout:Buffer.concat(a)})})})}function VJc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function HJc(e){return`'${e.replace(/'/g,"''")}'`}var q3i,kB,W3i,gpe,BJc,J3i=V(()=>{"use strict";q3i=require("node:child_process"),kB=require("node:fs/promises"),W3i=require("node:os"),gpe=require("node:path"),BJc=20*1024*1024;r(UJc,"resolveDefaultClipboardDirectory");r(V3i,"createNodeClipboardImageReader");r(zJc,"readMacClipboardImage");r($Jc,"readLinuxClipboardImage");r(qJc,"readWindowsClipboardImage");r(H3i,"readImageFile");r(G3i,"bufferToClipboardImage");r(WJc,"runCommandBuffer");r(VJc,"appleScriptString");r(HJc,"powershellString")});function Z3i(e={}){let t=e.maxBytes??GJc,n=e.platform??process.platform,o=e.runCommand??nKc;return async i=>{let a=tKc(i,t);if(a.byteLength===0)return;let c=XJc(e.stdout,a),u=await QJc({input:i,platform:n,runCommand:o});if(!c&&!u)throw new Error("No text clipboard target accepted the selected text.")}}function XJc(e,t){if(!e)return!1;try{return e.write(`${KJc}${JJc};${t.toString("base64")}${ZJc}`),!0}catch{return!1}}async function QJc(e){for(let t of eKc(e.platform))if((await e.runCommand(t.file,t.args,{input:e.input})).exitCode===0)return!0;return!1}function eKc(e){return e==="darwin"?[{args:[],file:"pbcopy"}]:e==="linux"?[{args:[],file:"wl-copy"},{args:["-selection","clipboard"],file:"xclip"},{args:["--clipboard","--input"],file:"xsel"}]:e==="win32"?[{args:["-NoProfile","-NonInteractive","-Command",YJc],file:"powershell.exe"}]:[]}function tKc(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength>t)throw new Error(`Clipboard text exceeds ${t} bytes.`);return n}async function nKc(e,t,n){return await new Promise(o=>{let i;try{i=(0,K3i.spawn)(e,t,{stdio:["pipe","ignore","ignore"],windowsHide:!0})}catch{o({exitCode:-1});return}let a=!1,c=r(u=>{a||(a=!0,o(u))},"finish");i.stdin?.on("error",()=>{}),i.stdin?.end(n.input),i.on("error",()=>c({exitCode:-1})),i.on("close",(u,p)=>c({exitCode:u,signal:p}))})}var K3i,GJc,JJc,KJc,ZJc,YJc,Y3i=V(()=>{"use strict";K3i=require("node:child_process"),GJc=1024*1024,JJc="c",KJc="\x1B]52;",ZJc="\x07",YJc="Set-Clipboard -Value ([Console]::In.ReadToEnd())";r(Z3i,"createNodeClipboardTextWriter");r(XJc,"writeOsc52");r(QJc,"writeNativeClipboardText");r(eKc,"nativeClipboardCommands");r(tKc,"assertClipboardTextSize");r(nKc,"runCommandText")});async function IBt(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return e.listCustomCommands?await e.listCustomCommands({env:t,logger:e.logger,workingDirectory:n}):await(await $y()).listZCodeCustomCommands({env:t,logger:e.logger,workingDirectory:n})}async function X3i(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)();return e.loadCustomCommand?await e.loadCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o}):await(await $y()).loadZCodeCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o})}async function Q3i(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return await(e.listSkills??(await $y()).listZCodeSkills)({env:t,logger:e.logger,workingDirectory:n})}async function e8i(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return(await(e.listSessions??(await $y()).listZCodeSessions)({directory:n,env:t,limit:50})).map(a=>({directory:a.directory,id:a.id,parentId:a.parentID,title:a.title,updatedAt:a.time.updated}))}async function t8i(e){try{return await e.getSessionMetadata?.()??{}}catch(t){if(rKc(t))throw t;return{}}}function rKc(e){return e instanceof Error?e.name==="SqliteSessionMigrationError":!1}var xZn=V(()=>{"use strict";Bee();r(IBt,"listCustomCommandsForTui");r(X3i,"loadCustomCommandForTui");r(Q3i,"listSkillsForTui");r(e8i,"listSessionsForTui");r(t8i,"loadInitialTuiSessionMetadata");r(rKc,"isStartupGateError")});function n8i(e){let t=new Set,n,o=r(()=>{n?.(),n=void 0},"detach"),i=r(()=>{if(o(),t.size===0)return;n=e.readSubscriber(e.currentRuntime())?.({onSessionEvent:r(c=>{for(let u of t)u(c)},"onSessionEvent")})},"reattach");return{addSink:r(a=>(t.add(a),t.size===1&&i(),()=>{t.delete(a),t.size===0&&o()}),"addSink"),reattach:i,detach:o,isAttached:r(()=>n!==void 0,"isAttached")}}var r8i=V(()=>{"use strict";r(n8i,"createTuiSessionEventRelay")});async function TZn(e){let t=await e.listModels?.()??[];return{locale:e.getLocale?.(),model:e.getModel?.(),theme:e.getTheme?.(),thoughtLevel:e.getThoughtLevel?.(),modelOptions:t,effortOptions:await dEe(e)??[],loginRequired:!t.some(n=>!n.disabledReason)}}var o8i,i8i=V(()=>{"use strict";pBt();r(TZn,"readTuiSessionMetadata");o8i=r((e,t)=>{const $zTuiBridge=e,$zTuiGetApp=t;e.readSubagents=async n=>(await t()).readSubagents?.(n)??{revision:0,childSessionIds:[],running:[],ended:{total:0,items:[]}},e.readSubagentTranscript=async n=>{let o=await t();if(!o.readSubagentTranscript)throw new Error("Subagent transcript is unavailable.");return o.readSubagentTranscript(n)},$zTuiBridge.createManagedWorktree=async $zDirectory=>await require(require("node:path").join(__dirname,"cli-config.cjs")).createManagedWorktree($zDirectory),$zTuiBridge.listManagedWorktrees=async $zDirectory=>await require(require("node:path").join(__dirname,"cli-config.cjs")).listManagedWorktrees($zDirectory),$zTuiBridge.restartTuiAtDirectory=$zDirectory=>require(require("node:path").join(__dirname,"cli-config.cjs")).restartTuiAtDirectory($zDirectory),$zTuiBridge.loadSessionTranscript=async()=>await(await $zTuiGetApp()).loadSessionTranscript?.()??[],$zTuiBridge.loadSessionContextMessages=async()=>await(await $zTuiGetApp()).loadSessionContextMessages?.()??[],$zTuiBridge.readGoal=async()=>await(await $zTuiGetApp()).readTarget?.()??null,$zTuiBridge.readTodos=async()=>await(await $zTuiGetApp()).readTodos?.()??[],$zTuiBridge.readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await $zTuiGetApp();return await require(require("node:path").join(__dirname,"cli-config.cjs")).readTuiRuntimeProjection($zRuntimeProjectionBridge,$zTuiBridge)},$zTuiBridge.$zRestorePersistedBackgroundTasks=async $zApp=>await require(require("node:path").join(__dirname,"cli-config.cjs")).restoreTuiBackgroundTasks($zApp,(ZWn(),c5r(),{collectChildSessionIds:HFt,projectSubagents:JFt,projectChildEvents:e=>new o9().reduce(e)})),$zTuiBridge.readSessionUsage=async()=>await(await $zTuiGetApp()).readSessionUsage?.()??null,$zTuiBridge.cancelBackgroundTask=async e=>await(await $zTuiGetApp()).cancelBackgroundTask?.(e)??null,$zTuiBridge.previewFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.previewWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.applyFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.applyWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.setCustomSessionTitle=async e=>{let t=await $zTuiGetApp();let r=t.runtime?.setCustomSessionTitle?.bind(t.runtime)??t.setCustomSessionTitle?.bind(t);if(!r)throw new Error("Session renaming is unavailable in this runtime.");return await r({title:e.title,traceContext:e.traceContext??t.runtime?.rootTraceContext})},$zTuiBridge.readCustomSessionTitle=async()=>{let t=await $zTuiGetApp(),o=t.sessionStore??t.runtime?.sessionStore,r=await o?.getSession?.(t.sessionId);return r?.titleSource==="custom"&&typeof r.title==="string"?r.title:void 0},$zTuiBridge.readSessionResumeTarget=async()=>await(await $zTuiGetApp()).readSessionResumeTarget?.(),$zTuiBridge.readSessionDatabasePath=async()=>await(await $zTuiGetApp()).readSessionDatabasePath?.(),$zTuiBridge.listWorkspacePathSuggestions=async $zWorkspaceRequest=>{let $zWorkspaceApp=await $zTuiGetApp();await $zWorkspaceApp.readExecutionState();let $zWorkspaceDirectory=$zWorkspaceApp.runtime?.workingDirectory;return $zWorkspaceDirectory?await A8i({workspaceDirectory:$zWorkspaceDirectory})($zWorkspaceRequest):{items:[],truncated:!1}},$zTuiBridge.setMode=async e=>{return await(await $zTuiGetApp()).setMode(e)},$zTuiBridge.readExecutionState=async()=>await(await $zTuiGetApp()).readExecutionState(),$zTuiBridge.setPlanEnabled=async e=>await(await $zTuiGetApp()).setPlanEnabled(e),$zTuiBridge.setTransientModel=async e=>{if(e==="main"){e=await $zTuiBridge.readDefaultModel();if(!e)throw new Error("No default model is configured.")}let t=await $zTuiGetApp(),r=await t.setModel(e);return{...r,thoughtLevel:t.getThoughtLevel(),effortOptions:t.listThoughtLevels()}},$zTuiBridge.readSessionModel=async()=>{let $zSessionModelApp=await $zTuiGetApp(),s=await $zSessionModelApp.readSessionModelState();if(s?.selection&&!s.issue)await $zSessionModelApp.setModel(s.selection,{transient:!0});return s},$zTuiBridge.sendBackgroundTaskMessage=async e=>await require(require("node:path").join(__dirname,"cli-config.cjs")).sendTuiBackgroundTaskMessage(await $zTuiGetApp(),$zTuiBridge,e),$zTuiBridge.interruptTurn=async e=>{let t=await $zTuiGetApp(),r=e?.reservationId??"tui-steer-interrupt",o=(Array.isArray(e?.pendingInputIds)?e.pendingInputIds:[]).filter(Boolean),n=[],i=async()=>{for(let a of n)await t.releaseQueueItemReservation?.(a,r);n=[]};try{if(t.reserveQueueItem&&t.releaseQueueItemReservation)for(let a of o)if(await t.reserveQueueItem(a,r))n.push(a);else{await i();break}let a=t.runtime?.stopActiveForegroundExecution?.({preserveQueueAutoDrainOnCancel:o.length>0&&n.length===o.length,reason:e?.reason??"TUI steer interrupt"})??{kind:"unsupported"};if(a.kind==="stopped"&&e?.waitForIdle===!0&&t.runtime?.getActiveForegroundExecutionId){let u=Date.now()+5e3;for(;t.runtime.getActiveForegroundExecutionId()!==void 0;){if(Date.now()>=u)throw new Error("Timed out waiting for background result processing to stop.");await new Promise(l=>setTimeout(l,25))}}return a.kind!=="stopped"&&await i(),a}catch(a){await i();throw a}},$zTuiBridge.promoteQueuedInput=async(e,t,r)=>{let o=await $zTuiGetApp(),n=r?.pendingInputReservationId??r?.queryId??r?.inputId??"tui-promotion",i=(Array.isArray(t)?t:[t]).filter(Boolean);if(i.length===0||!o.reserveQueueItem||!o.markQueueItemPromoting||!o.releaseQueueItemReservation||!o.removeQueueItem)return $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});let a=[],u=!1;try{for(let l of i){if(await o.markQueueItemPromoting(l,n)){a.push(l);continue}if(!await o.reserveQueueItem(l,n))throw new Error("TUI queued input is already reserved: "+l);a.push(l);if(!await o.markQueueItemPromoting(l,n))throw new Error("TUI queued input promotion failed: "+l)}let c=await $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});if(c?.kind==="rejected")return c;u=!0;for(let l of a)if(!await o.removeQueueItem(l,{reason:"promoted",reservationId:n}))throw new Error("TUI queued input promotion commit failed: "+l);return c}finally{if(!u)for(let l of a)await o.releaseQueueItemReservation(l,n)}},$zTuiBridge.$zSendInputWithoutBackgroundRestore=$zTuiBridge.sendInput,$zTuiBridge.sendInput=async(...$zArgs)=>{let $zApp=await $zTuiGetApp();await $zTuiBridge.$zRestorePersistedBackgroundTasks?.($zApp);return await $zTuiBridge.$zSendInputWithoutBackgroundRestore.apply($zTuiBridge,$zArgs)},e.recallPreviousInput=async n=>await(await t()).recallPreviousInputHistory?.(n)??null,e.getSessionMetadata=async()=>{let n=await t();return TZn(n)},e.reloadModelOptions=async()=>await(await t()).reloadModels(),e.readDefaultModel=async()=>{await t();let $zSelection=await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.read();return $zSelection?$zSelection.providerId+"/"+$zSelection.modelId:void 0},e.setDefaultModel=async $zModel=>{let $zApp=await t(),$zIndex=$zModel.indexOf("/"),$zSelection={providerId:$zModel.slice(0,$zIndex),modelId:$zModel.slice($zIndex+1)};if($zIndex<=0||!$zApp.getModelOption($zSelection))throw new Error("Unknown default model: "+$zModel);await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.saveConfiguredDefault($zSelection);return await e.setTransientModel($zModel)},e.listModelOptions=async()=>(await t()).listModels?.()??[],e.listEffortOptions=async()=>{let n=await t();return await dEe(n)??[]},e.listMcpServers=async()=>await(await t()).listMcpServers?.()??{},e.listWorkflowRuns=async()=>await(await t()).listDynamicWorkflowRuns?.({})??[],e.retuneWorkflowConcurrency=async $zInput=>{let $zApp=await t();if(typeof $zApp.retuneWorkflowConcurrency!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.retuneWorkflowConcurrency($zInput)},e.listSavedWorkflows=async $zInput=>{let $zApp=await t();if(typeof $zApp.listSavedWorkflows!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.listSavedWorkflows($zInput)},e.readSavedWorkflow=async $zInput=>{let $zApp=await t();if(typeof $zApp.readSavedWorkflow!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.readSavedWorkflow($zInput)},e.saveWorkflowRun=async $zInput=>{let $zApp=await t();if(typeof $zApp.saveWorkflowRun!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.saveWorkflowRun($zInput)},e.startSavedWorkflow=async $zInput=>require(require("node:path").join(__dirname,"cli-config.cjs")).startTuiSavedWorkflow(await t(),$zInput),e.replayWorkflowRuns=async n=>await(await t()).replayDynamicWorkflowRuns?.(n)??[]},"attachTuiAppQueries")});async function a8i(e,t,n,o){let i=e.env??process.env,a=(e.cwd??process.cwd)(),c=(e.loadDotenv??FR)({cwd:a,env:i});if(c.error)throw new Error(`Failed to load environment file: ${c.path}`,{cause:c.error});let u=await bBt(n,a,i,e),p=e.createZCodeApp?void 0:await $y(),h=e.createZCodeApp??p?.createZCodeApp;if(!h)throw new Error("ZCode app factory is unavailable.");let _=e.prepareZCodeTelemetryEnv??p?.prepareZCodeTelemetryEnv;_&&(o.shutdownTelemetry=e.shutdownZCodeTelemetry??p?.shutdownZCodeTelemetry);let v=_?await _(i,{cliVersion:t,productVersion:i.ZCODE_APP_VERSION}):i,b=e.startProcessProviderRegistryRuntime??p?.startProcessProviderRegistryRuntime;if(!b)throw new Error("Provider Registry runtime is unavailable.");o.providerRegistryRuntimePromise??=b(v,e.skipUserConfig?{}:{standalone:{...b4e(),...e.userConfigPath?{legacyCliUserConfigFilePath:e.userConfigPath}:{}}});let k=await o.providerRegistryRuntimePromise,x=k?.modelSelectionConfigRepository?await k.modelSelectionConfigRepository.read():k?.configuredDefaultModelSelection,I=e.createProviderEndpointRoutingPort??p?.createDefaultProviderEndpointRoutingPort;return o.providerEndpointRoutingPort??=I?.({appVersion:t,env:i,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:a}),{appEnv:v,configuredDefaultModelSelection:x,createAppFactory:h,providerRegistryRuntime:k,sessionId:u,workingDirectory:a}}var s8i,c8i=V(()=>{"use strict";Bee();Xoe();Cdt();hZn();s8i=r(()=>({providerEndpointRoutingPort:void 0,providerRegistryRuntimePromise:void 0,shutdownTelemetry:void 0}),"createTuiProcessRuntimeState");r(a8i,"prepareTuiAppRuntime")});async function l8i(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),i=(e.loadDotenv??FR)({cwd:o,env:n});if(i.error)throw new Error(`Failed to load environment file: ${i.path}`,{cause:i.error});return await(e.loginZCodeCli??(await $y()).loginZCodeCli)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function u8i(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),i=(e.loadDotenv??FR)({cwd:o,env:n});if(i.error)throw new Error(`Failed to load environment file: ${i.path}`,{cause:i.error});return await(e.loginBigmodelCodingPlan??(await $y()).loginBigmodelCodingPlan)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function d8i(e,t){return await(e.configureCodingPlanApiKey??(await $y()).configureCodingPlanApiKey)({apiKey:t.apiKey,env:e.env??process.env,providerId:t.providerId})}async function p8i(e){let t=e.env??process.env,n=(e.cwd??process.cwd)(),o=(e.loadDotenv??FR)({cwd:n,env:t});if(o.error)throw new Error(`Failed to load environment file: ${o.path}`,{cause:o.error});return await(e.logoutZCodeCli??(await $y()).logoutZCodeCli)({env:t})}var f8i=V(()=>{"use strict";Bee();Xoe();r(l8i,"loginForTui");r(u8i,"loginBigmodelForTui");r(d8i,"configureApiKeyForTui");r(p8i,"logoutForTui")});function mEe(e,t){return e.runtime?.getPlanEnabled?.()?"plan":e.getMode?.()??t}var m8i,h8i,sH,IZn=V(()=>{"use strict";m8i={},h8i=r(e=>({current:e,override:e}),"createCliModeState"),sH=r(e=>e.current??e.override??"build","currentCliMode");r(mEe,"readTuiMode")});function CZn(e,t,n){return{kind:"started_turn",result:{...e,locale:e.locale??t.getLocale?.(),mode:n,model:e.model??t.getModel?.(),theme:e.theme??t.getTheme?.(),thoughtLevel:e.thoughtLevel??t.getThoughtLevel?.()}}}var g8i=V(()=>{"use strict";r(CZn,"withTuiMetadata")});function _8i(e,t,n,o={continueSession:!1},i,a,c=e2t,u,p=!1,h="off",_,v,b=Uee,k=!1,x=!0,I){let R,O=i,j=s8i(),L,$=new WeakMap,z=new WeakMap,q,W=Math.max(1,Math.trunc(e.shutdownCleanupTimeoutMs??lst)),Q={requestPermission:r(async(Re,Me)=>{let Te=q;return Te?await Te(Re,Me):{decision:"deny",reason:`No interactive approval handler configured for ${Re.toolName}`,resolvedAt:new Date}},"requestPermission")},ne=r(async(Re=R)=>{if(!Re)return;let Me=Re,Te=$.get(Me);Te||(Te=(async()=>{await oj(async()=>Re.close?.(),W),await oj(async()=>z.get(Me)?.close(),W)})(),$.set(Me,Te)),await Te},"closeApp"),ge=n8i({currentRuntime:r(()=>R?.runtime,"currentRuntime"),readSubscriber:yBt}),ie=r(async Re=>{let Me=R,Te=await Re();try{await Te.readExecutionState()}catch($zResumeCandidateError){await ne(Te);throw $zResumeCandidateError}return R=Te,Me&&Me!==Te&&await ne(Me),ge.reattach(),t.current=mEe(R,sH(t)),R},"replaceApp"),ke=r(async Re=>{if(L)throw new Error("TUI prompt handler is closed");let{appEnv:Me,configuredDefaultModelSelection:Te,createAppFactory:ct,providerRegistryRuntime:Ve,sessionId:qe,workingDirectory:ut}=await a8i(e,n,Re,j),ht=j.providerEndpointRoutingPort,Ut=gBt({browserExecutable:v,browserState:I,browserUse:_},e),sn;try{sn=await ct({modelSelectionMode:"cli-default",standaloneSessionControl:!0,mcpStartupPolicy:"background",browserControlPort:Ut?.browserControlPort,env:Me,projectConfigPath:e.projectConfigPath,...ht?{providerEndpointRoutingPort:ht}:{},providerRegistry:Ve.runtime.registryService,configuredDefaultModelSelection:Te,...Ve.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:Ve.providerRuntimeHeadersPort}:{},resume:qe!==void 0,runtimeConfig:{...t.override?{mode:t.override}:{},...u?{toolDisallowlist:u}:{},toolSearch:{mode:h},totalTokensReminder:{enabled:k},subagents:{alwaysBackground:x},...p?{midConversationSystem:{mode:"force"}}:{},...dBt(b),modelStreaming:"on",titleGeneration:m8i,workingDirectory:ut},permissionBroker:Q,sessionId:qe,skipUserConfig:e.skipUserConfig,uiDetectedLocale:a,uiLocale:O,userConfigPath:e.userConfigPath,version:n})}catch(bn){throw await oj(async()=>Ut?.close(),W),bn}if(Ut&&z.set(sn,Ut),L)throw await ne(sn),new Error("TUI prompt handler is closed");let $zTuiCliDefaultPromptModel=true;let $zCliDefaultPromptModel=process.env.ZCODE_CLI_PROMPT_MODEL;let $zCliDefaultPromptEffort=process.env.ZCODE_CLI_PROMPT_EFFORT;if($zCliDefaultPromptEffort&&$zCliDefaultPromptEffort.toLowerCase()==="auto")$zCliDefaultPromptEffort=void 0;if($zCliDefaultPromptModel&&!$zCliDefaultPromptEffort){await sn.setModel($zCliDefaultPromptModel,{transient:true,cliDefault:true});}else if($zCliDefaultPromptEffort){let $zPromptSelection,$zPromptCurrent;if($zCliDefaultPromptModel){let $zPromptSlash=$zCliDefaultPromptModel.indexOf("/");if($zPromptSlash<=0||$zPromptSlash===$zCliDefaultPromptModel.length-1)throw new Error("Invalid prompt model selection.");$zPromptSelection={providerId:$zCliDefaultPromptModel.slice(0,$zPromptSlash),modelId:$zCliDefaultPromptModel.slice($zPromptSlash+1)};}else{await sn.readExecutionState?.();$zPromptCurrent=sn.getCurrentModelOption?.();if(!$zPromptCurrent?.ref)throw new Error("Cannot apply --effort without a current model. Pass --model or select a model first.");$zPromptSelection={...$zPromptCurrent.ref};}let $zPromptOption=sn.getModelOption?.($zPromptSelection);let $zPromptLevels=($zPromptOption?.reasoning?.levels??[]).map($zLevel=>$zLevel.value);if($zPromptOption&&$zPromptLevels.length===0)throw new Error("Model "+$zPromptSelection.providerId+"/"+$zPromptSelection.modelId+" does not support reasoning effort.");let $zPromptLevel=$zPromptLevels.find($zLevel=>$zLevel===$zCliDefaultPromptEffort)??$zPromptLevels.find($zLevel=>$zLevel.toLowerCase()===$zCliDefaultPromptEffort.toLowerCase());if($zPromptLevels.length>0&&!$zPromptLevel)throw new Error("Unsupported reasoning effort: "+$zCliDefaultPromptEffort+". Available: "+$zPromptLevels.join(", ")+".");await sn.setModel({...$zPromptSelection,options:{...$zPromptSelection.options,reasoningLevel:$zPromptLevel??$zCliDefaultPromptEffort}},{transient:true,cliDefault:true});}return sn},"createApp"),De=r(async()=>(R??=await ke(o),t.current=mEe(R,sH(t)),R),"getApp"),Ee=r(async Re=>await ie(async()=>await ke(Re?{continueSession:!1,resumeSessionId:Re}:{continueSession:!0})),"resumeApp"),lt=r(async()=>await ie(async()=>await ke({continueSession:!1})),"newApp"),St=r(async Re=>{if(t.override=Re,R){let Me=R;if(Me.setMode){let Te=await Me.setMode(Re);return t.current=mEe(Me,Te.mode),t.current}Me.runtime.updateConfig({mode:Re})}return t.current=R?mEe(R,Re):Re,t.current},"setCliMode"),Le=OVe({forkApp:r(async Re=>{let Te=await(await De()).forkFromCheckpoint?.({targetCheckpointId:Re});if(!Te)throw new Error("Forking is not available in this client.");return await ie(async()=>await ke({continueSession:!1,resumeSessionId:Te.forkedSessionId})),{copiedMessageCount:Te.copiedMessageCount,forkedSessionId:Te.forkedSessionId,response:`${Te.response}
15879
+ Scopes: user (default), project. \`zcode plugin\` is an alias of \`zcode plugins\`.`;r(U3i,"runPluginsCommand");r(OJc,"runPluginsListCommand");r(DJc,"runPluginsInstallCommand");r(MJc,"runPluginsUpdateCommand");r(NJc,"reportInstallOutcome");r(z3i,"runPluginsSetCommand");r(LJc,"runPluginsDisableCommand");r(FJc,"runPluginsUninstallCommand");r(jJc,"runPluginsValidateCommand")});function UJc(e=process.env){let t=e.ZCODE_STORAGE_DIR?.trim()||(0,gpe.join)((0,W3i.homedir)(),".zcode");return(0,gpe.join)(t,"clipboard")}function V3i(e={}){let t=e.platform??process.platform,n=e.maxBytes??BJc,o=e.runCommand??WJc,i=e.tempDirectory??UJc(e.processEnv);return async(a={})=>t==="darwin"?await zJc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:i}):t==="linux"?await $Jc({maxBytes:n,runCommand:o,signal:a.abortSignal}):t==="win32"?await qJc({maxBytes:n,runCommand:o,signal:a.abortSignal,tempDirectory:i}):null}async function zJc(e){await(0,kB.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,kB.mkdtemp)((0,gpe.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,gpe.join)(t,"clipboard.png");try{return(await e.runCommand("osascript",["-e","set png_data to (the clipboard as \xABclass PNGf\xBB)","-e",`set fp to open for access POSIX file ${VJc(n)} with write permission`,"-e","write png_data to fp","-e","close access fp"],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await H3i(n,"image/png",e.maxBytes)}finally{await(0,kB.rm)(t,{force:!0,recursive:!0})}}async function $Jc(e){let t=[{args:["--type","image/png"],file:"wl-paste",mediaType:"image/png"},{args:["--type","image/jpeg"],file:"wl-paste",mediaType:"image/jpeg"},{args:["--type","image/gif"],file:"wl-paste",mediaType:"image/gif"},{args:["--type","image/webp"],file:"wl-paste",mediaType:"image/webp"},{args:["-selection","clipboard","-t","image/png","-o"],file:"xclip",mediaType:"image/png"},{args:["-selection","clipboard","-t","image/jpeg","-o"],file:"xclip",mediaType:"image/jpeg"},{args:["-selection","clipboard","-t","image/gif","-o"],file:"xclip",mediaType:"image/gif"},{args:["-selection","clipboard","-t","image/webp","-o"],file:"xclip",mediaType:"image/webp"}];for(let n of t){let o=await e.runCommand(n.file,n.args,{maxBytes:e.maxBytes,signal:e.signal}),i=G3i(o.stdout,n.mediaType,e.maxBytes);if(o.exitCode===0&&i)return i}return null}async function qJc(e){await(0,kB.mkdir)(e.tempDirectory,{recursive:!0});let t=await(0,kB.mkdtemp)((0,gpe.join)(e.tempDirectory,"zcode-clipboard-")),n=(0,gpe.join)(t,"clipboard.png"),o=["Add-Type -AssemblyName System.Windows.Forms;","$img = Get-Clipboard -Format Image;","if ($null -eq $img) { exit 2 }",`$img.Save(${HJc(n)}, [System.Drawing.Imaging.ImageFormat]::Png);`].join(" ");try{return(await e.runCommand("powershell.exe",["-NoProfile","-NonInteractive","-Command",o],{maxBytes:e.maxBytes,signal:e.signal})).exitCode!==0?null:await H3i(n,"image/png",e.maxBytes)}finally{await(0,kB.rm)(t,{force:!0,recursive:!0})}}async function H3i(e,t,n){let o=await(0,kB.readFile)(e);return G3i(o,t,n)}function G3i(e,t,n){return e.byteLength===0||e.byteLength>n?null:{dataUrl:`data:${t};base64,${e.toString("base64")}`,mediaType:t,sizeBytes:e.byteLength}}async function WJc(e,t,n){return await new Promise(o=>{let i;try{i=(0,q3i.spawn)(e,t,{signal:n.signal,stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:Buffer.alloc(0)});return}let a=[],c=0,u=!1,p=r(h=>{u||(u=!0,o(h))},"finish");i.stdout?.on("data",h=>{if(c+=h.byteLength,c>n.maxBytes){i.kill();return}a.push(h)}),i.on("error",()=>p({exitCode:-1,stdout:Buffer.alloc(0)})),i.on("close",(h,_)=>{p({exitCode:h,signal:_,stdout:Buffer.concat(a)})})})}function VJc(e){return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function HJc(e){return`'${e.replace(/'/g,"''")}'`}var q3i,kB,W3i,gpe,BJc,J3i=V(()=>{"use strict";q3i=require("node:child_process"),kB=require("node:fs/promises"),W3i=require("node:os"),gpe=require("node:path"),BJc=20*1024*1024;r(UJc,"resolveDefaultClipboardDirectory");r(V3i,"createNodeClipboardImageReader");r(zJc,"readMacClipboardImage");r($Jc,"readLinuxClipboardImage");r(qJc,"readWindowsClipboardImage");r(H3i,"readImageFile");r(G3i,"bufferToClipboardImage");r(WJc,"runCommandBuffer");r(VJc,"appleScriptString");r(HJc,"powershellString")});function Z3i(e={}){let t=e.maxBytes??GJc,n=e.platform??process.platform,o=e.runCommand??nKc;return async i=>{let a=tKc(i,t);if(a.byteLength===0)return;let c=XJc(e.stdout,a),u=await QJc({input:i,platform:n,runCommand:o});if(!c&&!u)throw new Error("No text clipboard target accepted the selected text.")}}function XJc(e,t){if(!e)return!1;try{return e.write(`${KJc}${JJc};${t.toString("base64")}${ZJc}`),!0}catch{return!1}}async function QJc(e){for(let t of eKc(e.platform))if((await e.runCommand(t.file,t.args,{input:e.input})).exitCode===0)return!0;return!1}function eKc(e){return e==="darwin"?[{args:[],file:"pbcopy"}]:e==="linux"?[{args:[],file:"wl-copy"},{args:["-selection","clipboard"],file:"xclip"},{args:["--clipboard","--input"],file:"xsel"}]:e==="win32"?[{args:["-NoProfile","-NonInteractive","-Command",YJc],file:"powershell.exe"}]:[]}function tKc(e,t){let n=Buffer.from(e,"utf8");if(n.byteLength>t)throw new Error(`Clipboard text exceeds ${t} bytes.`);return n}async function nKc(e,t,n){return await new Promise(o=>{let i;try{i=(0,K3i.spawn)(e,t,{stdio:["pipe","ignore","ignore"],windowsHide:!0})}catch{o({exitCode:-1});return}let a=!1,c=r(u=>{a||(a=!0,o(u))},"finish");i.stdin?.on("error",()=>{}),i.stdin?.end(n.input),i.on("error",()=>c({exitCode:-1})),i.on("close",(u,p)=>c({exitCode:u,signal:p}))})}var K3i,GJc,JJc,KJc,ZJc,YJc,Y3i=V(()=>{"use strict";K3i=require("node:child_process"),GJc=1024*1024,JJc="c",KJc="\x1B]52;",ZJc="\x07",YJc="Set-Clipboard -Value ([Console]::In.ReadToEnd())";r(Z3i,"createNodeClipboardTextWriter");r(XJc,"writeOsc52");r(QJc,"writeNativeClipboardText");r(eKc,"nativeClipboardCommands");r(tKc,"assertClipboardTextSize");r(nKc,"runCommandText")});async function IBt(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return e.listCustomCommands?await e.listCustomCommands({env:t,logger:e.logger,workingDirectory:n}):await(await $y()).listZCodeCustomCommands({env:t,logger:e.logger,workingDirectory:n})}async function X3i(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)();return e.loadCustomCommand?await e.loadCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o}):await(await $y()).loadZCodeCustomCommand({env:n,logger:e.logger,name:t,workingDirectory:o})}async function Q3i(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return await(e.listSkills??(await $y()).listZCodeSkills)({env:t,logger:e.logger,workingDirectory:n})}async function e8i(e){let t=e.env??process.env,n=(e.cwd??process.cwd)();return(await(e.listSessions??(await $y()).listZCodeSessions)({directory:n,env:t,limit:50})).map(a=>({directory:a.directory,id:a.id,parentId:a.parentID,title:a.title,updatedAt:a.time.updated}))}async function t8i(e){try{return await e.getSessionMetadata?.()??{}}catch(t){if(rKc(t))throw t;return{}}}function rKc(e){return e instanceof Error?e.name==="SqliteSessionMigrationError":!1}var xZn=V(()=>{"use strict";Bee();r(IBt,"listCustomCommandsForTui");r(X3i,"loadCustomCommandForTui");r(Q3i,"listSkillsForTui");r(e8i,"listSessionsForTui");r(t8i,"loadInitialTuiSessionMetadata");r(rKc,"isStartupGateError")});function n8i(e){let t=new Set,n,o=r(()=>{n?.(),n=void 0},"detach"),i=r(()=>{if(o(),t.size===0)return;n=e.readSubscriber(e.currentRuntime())?.({onSessionEvent:r(c=>{for(let u of t)u(c)},"onSessionEvent")})},"reattach");return{addSink:r(a=>(t.add(a),t.size===1&&i(),()=>{t.delete(a),t.size===0&&o()}),"addSink"),reattach:i,detach:o,isAttached:r(()=>n!==void 0,"isAttached")}}var r8i=V(()=>{"use strict";r(n8i,"createTuiSessionEventRelay")});async function TZn(e){let t=await e.listModels?.()??[];return{locale:e.getLocale?.(),model:e.getModel?.(),theme:e.getTheme?.(),thoughtLevel:e.getThoughtLevel?.(),modelOptions:t,effortOptions:await dEe(e)??[],loginRequired:!t.some(n=>!n.disabledReason)}}var o8i,i8i=V(()=>{"use strict";pBt();r(TZn,"readTuiSessionMetadata");o8i=r((e,t)=>{const $zTuiBridge=e,$zTuiGetApp=t;e.readSubagents=async n=>(await t()).readSubagents?.(n)??{revision:0,childSessionIds:[],running:[],ended:{total:0,items:[]}},e.readSubagentTranscript=async n=>{let o=await t();if(!o.readSubagentTranscript)throw new Error("Subagent transcript is unavailable.");return o.readSubagentTranscript(n)},$zTuiBridge.createManagedWorktree=async $zDirectory=>await require(require("node:path").join(__dirname,"cli-config.cjs")).createManagedWorktree($zDirectory),$zTuiBridge.listManagedWorktrees=async $zDirectory=>await require(require("node:path").join(__dirname,"cli-config.cjs")).listManagedWorktrees($zDirectory),$zTuiBridge.restartTuiAtDirectory=$zDirectory=>require(require("node:path").join(__dirname,"cli-config.cjs")).restartTuiAtDirectory($zDirectory),$zTuiBridge.loadSessionTranscript=async()=>await(await $zTuiGetApp()).loadSessionTranscript?.()??[],$zTuiBridge.loadSessionContextMessages=async()=>await(await $zTuiGetApp()).loadSessionContextMessages?.()??[],$zTuiBridge.readGoal=async()=>await(await $zTuiGetApp()).readTarget?.()??null,$zTuiBridge.readTodos=async()=>await(await $zTuiGetApp()).readTodos?.()??[],$zTuiBridge.readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await $zTuiGetApp();return await require(require("node:path").join(__dirname,"cli-config.cjs")).readTuiRuntimeProjection($zRuntimeProjectionBridge,$zTuiBridge)},$zTuiBridge.$zRestorePersistedBackgroundTasks=async $zApp=>await require(require("node:path").join(__dirname,"cli-config.cjs")).restoreTuiBackgroundTasks($zApp),$zTuiBridge.readSessionUsage=async()=>await(await $zTuiGetApp()).readSessionUsage?.()??null,$zTuiBridge.cancelBackgroundTask=async(e,id)=>await require(require("node:path").join(__dirname,"cli-config.cjs")).stopTuiBackgroundTask(await $zTuiGetApp(),e,id),$zTuiBridge.previewFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.previewWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.applyFileRewind=async e=>{let t=await $zTuiGetApp();return await t.runtime?.applyWorkspaceFileRewind?.({targetMessageIds:e})??null},$zTuiBridge.setCustomSessionTitle=async e=>{let t=await $zTuiGetApp();let r=t.runtime?.setCustomSessionTitle?.bind(t.runtime)??t.setCustomSessionTitle?.bind(t);if(!r)throw new Error("Session renaming is unavailable in this runtime.");return await r({title:e.title,traceContext:e.traceContext??t.runtime?.rootTraceContext})},$zTuiBridge.readCustomSessionTitle=async()=>{let t=await $zTuiGetApp(),o=t.sessionStore??t.runtime?.sessionStore,r=await o?.getSession?.(t.sessionId);return r?.titleSource==="custom"&&typeof r.title==="string"?r.title:void 0},$zTuiBridge.readSessionResumeTarget=async()=>await(await $zTuiGetApp()).readSessionResumeTarget?.(),$zTuiBridge.readSessionDatabasePath=async()=>await(await $zTuiGetApp()).readSessionDatabasePath?.(),$zTuiBridge.listWorkspacePathSuggestions=async $zWorkspaceRequest=>{let $zWorkspaceApp=await $zTuiGetApp();await $zWorkspaceApp.readExecutionState();let $zWorkspaceDirectory=$zWorkspaceApp.runtime?.workingDirectory;return $zWorkspaceDirectory?await A8i({workspaceDirectory:$zWorkspaceDirectory})($zWorkspaceRequest):{items:[],truncated:!1}},$zTuiBridge.setMode=async e=>{return await(await $zTuiGetApp()).setMode(e)},$zTuiBridge.readExecutionState=async()=>await(await $zTuiGetApp()).readExecutionState(),$zTuiBridge.setPlanEnabled=async e=>await(await $zTuiGetApp()).setPlanEnabled(e),$zTuiBridge.setTransientModel=async e=>{if(e==="main"){e=await $zTuiBridge.readDefaultModel();if(!e)throw new Error("No default model is configured.")}let t=await $zTuiGetApp(),r=await t.setModel(e);return{...r,thoughtLevel:t.getThoughtLevel(),effortOptions:t.listThoughtLevels()}},$zTuiBridge.readSessionModel=async()=>{let $zSessionModelApp=await $zTuiGetApp(),s=await $zSessionModelApp.readSessionModelState();if(s?.selection&&!s.issue)await $zSessionModelApp.setModel(s.selection,{transient:!0});return s},$zTuiBridge.sendBackgroundTaskMessage=async e=>await require(require("node:path").join(__dirname,"cli-config.cjs")).sendTuiBackgroundTaskMessage(await $zTuiGetApp(),$zTuiBridge,e),$zTuiBridge.interruptTurn=async e=>{let t=await $zTuiGetApp(),r=e?.reservationId??"tui-steer-interrupt",o=(Array.isArray(e?.pendingInputIds)?e.pendingInputIds:[]).filter(Boolean),n=[],i=async()=>{for(let a of n)await t.releaseQueueItemReservation?.(a,r);n=[]};try{if(t.reserveQueueItem&&t.releaseQueueItemReservation)for(let a of o)if(await t.reserveQueueItem(a,r))n.push(a);else{await i();break}let a=t.runtime?.stopActiveForegroundExecution?.({preserveQueueAutoDrainOnCancel:o.length>0&&n.length===o.length,reason:e?.reason??"TUI steer interrupt"})??{kind:"unsupported"};if(a.kind==="stopped"&&e?.waitForIdle===!0&&t.runtime?.getActiveForegroundExecutionId){let u=Date.now()+5e3;for(;t.runtime.getActiveForegroundExecutionId()!==void 0;){if(Date.now()>=u)throw new Error("Timed out waiting for background result processing to stop.");await new Promise(l=>setTimeout(l,25))}}return a.kind!=="stopped"&&await i(),a}catch(a){await i();throw a}},$zTuiBridge.promoteQueuedInput=async(e,t,r)=>{let o=await $zTuiGetApp(),n=r?.pendingInputReservationId??r?.queryId??r?.inputId??"tui-promotion",i=(Array.isArray(t)?t:[t]).filter(Boolean);if(i.length===0||!o.reserveQueueItem||!o.markQueueItemPromoting||!o.releaseQueueItemReservation||!o.removeQueueItem)return $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});let a=[],u=!1;try{for(let l of i){if(await o.markQueueItemPromoting(l,n)){a.push(l);continue}if(!await o.reserveQueueItem(l,n))throw new Error("TUI queued input is already reserved: "+l);a.push(l);if(!await o.markQueueItemPromoting(l,n))throw new Error("TUI queued input promotion failed: "+l)}let c=await $zTuiBridge.sendInput(e,{...r,delivery:"start_turn"});if(c?.kind==="rejected")return c;u=!0;for(let l of a)if(!await o.removeQueueItem(l,{reason:"promoted",reservationId:n}))throw new Error("TUI queued input promotion commit failed: "+l);return c}finally{if(!u)for(let l of a)await o.releaseQueueItemReservation(l,n)}},$zTuiBridge.$zSendInputWithoutBackgroundRestore=$zTuiBridge.sendInput,$zTuiBridge.sendInput=async(...$zArgs)=>{let $zApp=await $zTuiGetApp();await $zTuiBridge.$zRestorePersistedBackgroundTasks?.($zApp);return await $zTuiBridge.$zSendInputWithoutBackgroundRestore.apply($zTuiBridge,$zArgs)},e.recallPreviousInput=async n=>await(await t()).recallPreviousInputHistory?.(n)??null,e.getSessionMetadata=async()=>{let n=await t();return TZn(n)},e.reloadModelOptions=async()=>await(await t()).reloadModels(),e.readDefaultModel=async()=>{await t();let $zSelection=await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.read();return $zSelection?$zSelection.providerId+"/"+$zSelection.modelId:void 0},e.setDefaultModel=async $zModel=>{let $zApp=await t(),$zIndex=$zModel.indexOf("/"),$zSelection={providerId:$zModel.slice(0,$zIndex),modelId:$zModel.slice($zIndex+1)};if($zIndex<=0||!$zApp.getModelOption($zSelection))throw new Error("Unknown default model: "+$zModel);await(await e.$zReadProviderRegistryRuntime()).modelSelectionConfigRepository.saveConfiguredDefault($zSelection);return await e.setTransientModel($zModel)},e.listModelOptions=async()=>(await t()).listModels?.()??[],e.listEffortOptions=async()=>{let n=await t();return await dEe(n)??[]},e.listMcpServers=async()=>await(await t()).listMcpServers?.()??{},e.listWorkflowRuns=async()=>await(await t()).listDynamicWorkflowRuns?.({})??[],e.retuneWorkflowConcurrency=async $zInput=>{let $zApp=await t();if(typeof $zApp.retuneWorkflowConcurrency!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.retuneWorkflowConcurrency($zInput)},e.listSavedWorkflows=async $zInput=>{let $zApp=await t();if(typeof $zApp.listSavedWorkflows!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.listSavedWorkflows($zInput)},e.readSavedWorkflow=async $zInput=>{let $zApp=await t();if(typeof $zApp.readSavedWorkflow!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.readSavedWorkflow($zInput)},e.saveWorkflowRun=async $zInput=>{let $zApp=await t();if(typeof $zApp.saveWorkflowRun!=="function")throw new Error("Workflow management is unavailable in this runtime.");return await $zApp.saveWorkflowRun($zInput)},e.startSavedWorkflow=async $zInput=>require(require("node:path").join(__dirname,"cli-config.cjs")).startTuiSavedWorkflow(await t(),$zInput),e.replayWorkflowRuns=async n=>await(await t()).replayDynamicWorkflowRuns?.(n)??[]},"attachTuiAppQueries")});async function a8i(e,t,n,o){let i=e.env??process.env,a=(e.cwd??process.cwd)(),c=(e.loadDotenv??FR)({cwd:a,env:i});if(c.error)throw new Error(`Failed to load environment file: ${c.path}`,{cause:c.error});let u=await bBt(n,a,i,e),p=e.createZCodeApp?void 0:await $y(),h=e.createZCodeApp??p?.createZCodeApp;if(!h)throw new Error("ZCode app factory is unavailable.");let _=e.prepareZCodeTelemetryEnv??p?.prepareZCodeTelemetryEnv;_&&(o.shutdownTelemetry=e.shutdownZCodeTelemetry??p?.shutdownZCodeTelemetry);let v=_?await _(i,{cliVersion:t,productVersion:i.ZCODE_APP_VERSION}):i,b=e.startProcessProviderRegistryRuntime??p?.startProcessProviderRegistryRuntime;if(!b)throw new Error("Provider Registry runtime is unavailable.");o.providerRegistryRuntimePromise??=b(v,e.skipUserConfig?{}:{standalone:{...b4e(),...e.userConfigPath?{legacyCliUserConfigFilePath:e.userConfigPath}:{}}});let k=await o.providerRegistryRuntimePromise,x=k?.modelSelectionConfigRepository?await k.modelSelectionConfigRepository.read():k?.configuredDefaultModelSelection,I=e.createProviderEndpointRoutingPort??p?.createDefaultProviderEndpointRoutingPort;return o.providerEndpointRoutingPort??=I?.({appVersion:t,env:i,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:a}),{appEnv:v,configuredDefaultModelSelection:x,createAppFactory:h,providerRegistryRuntime:k,sessionId:u,workingDirectory:a}}var s8i,c8i=V(()=>{"use strict";Bee();Xoe();Cdt();hZn();s8i=r(()=>({providerEndpointRoutingPort:void 0,providerRegistryRuntimePromise:void 0,shutdownTelemetry:void 0}),"createTuiProcessRuntimeState");r(a8i,"prepareTuiAppRuntime")});async function l8i(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),i=(e.loadDotenv??FR)({cwd:o,env:n});if(i.error)throw new Error(`Failed to load environment file: ${i.path}`,{cause:i.error});return await(e.loginZCodeCli??(await $y()).loginZCodeCli)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function u8i(e,t){let n=e.env??process.env,o=(e.cwd??process.cwd)(),i=(e.loadDotenv??FR)({cwd:o,env:n});if(i.error)throw new Error(`Failed to load environment file: ${i.path}`,{cause:i.error});return await(e.loginBigmodelCodingPlan??(await $y()).loginBigmodelCodingPlan)({abortSignal:t?.abortSignal,env:n,onAuthorizeUrl:t?.onAuthorizeUrl})}async function d8i(e,t){return await(e.configureCodingPlanApiKey??(await $y()).configureCodingPlanApiKey)({apiKey:t.apiKey,env:e.env??process.env,providerId:t.providerId})}async function p8i(e){let t=e.env??process.env,n=(e.cwd??process.cwd)(),o=(e.loadDotenv??FR)({cwd:n,env:t});if(o.error)throw new Error(`Failed to load environment file: ${o.path}`,{cause:o.error});return await(e.logoutZCodeCli??(await $y()).logoutZCodeCli)({env:t})}var f8i=V(()=>{"use strict";Bee();Xoe();r(l8i,"loginForTui");r(u8i,"loginBigmodelForTui");r(d8i,"configureApiKeyForTui");r(p8i,"logoutForTui")});function mEe(e,t){return e.runtime?.getPlanEnabled?.()?"plan":e.getMode?.()??t}var m8i,h8i,sH,IZn=V(()=>{"use strict";m8i={},h8i=r(e=>({current:e,override:e}),"createCliModeState"),sH=r(e=>e.current??e.override??"build","currentCliMode");r(mEe,"readTuiMode")});function CZn(e,t,n){return{kind:"started_turn",result:{...e,locale:e.locale??t.getLocale?.(),mode:n,model:e.model??t.getModel?.(),theme:e.theme??t.getTheme?.(),thoughtLevel:e.thoughtLevel??t.getThoughtLevel?.()}}}var g8i=V(()=>{"use strict";r(CZn,"withTuiMetadata")});function _8i(e,t,n,o={continueSession:!1},i,a,c=e2t,u,p=!1,h="off",_,v,b=Uee,k=!1,x=!0,I){let R,O=i,j=s8i(),L,$=new WeakMap,z=new WeakMap,q,W=Math.max(1,Math.trunc(e.shutdownCleanupTimeoutMs??lst)),Q={requestPermission:r(async(Re,Me)=>{let Te=q;return Te?await Te(Re,Me):{decision:"deny",reason:`No interactive approval handler configured for ${Re.toolName}`,resolvedAt:new Date}},"requestPermission")},ne=r(async(Re=R)=>{if(!Re)return;let Me=Re,Te=$.get(Me);Te||(Te=(async()=>{await oj(async()=>Re.close?.(),W),await oj(async()=>z.get(Me)?.close(),W)})(),$.set(Me,Te)),await Te},"closeApp"),ge=n8i({currentRuntime:r(()=>R?.runtime,"currentRuntime"),readSubscriber:yBt}),ie=r(async Re=>{let Me=R,Te=await Re();try{await Te.readExecutionState()}catch($zResumeCandidateError){await ne(Te);throw $zResumeCandidateError}return R=Te,Me&&Me!==Te&&await ne(Me),ge.reattach(),t.current=mEe(R,sH(t)),R},"replaceApp"),ke=r(async Re=>{if(L)throw new Error("TUI prompt handler is closed");let{appEnv:Me,configuredDefaultModelSelection:Te,createAppFactory:ct,providerRegistryRuntime:Ve,sessionId:qe,workingDirectory:ut}=await a8i(e,n,Re,j),ht=j.providerEndpointRoutingPort,Ut=gBt({browserExecutable:v,browserState:I,browserUse:_},e),sn;try{sn=await ct({modelSelectionMode:"cli-default",standaloneSessionControl:!0,mcpStartupPolicy:"background",browserControlPort:Ut?.browserControlPort,env:Me,projectConfigPath:e.projectConfigPath,...ht?{providerEndpointRoutingPort:ht}:{},providerRegistry:Ve.runtime.registryService,configuredDefaultModelSelection:Te,...Ve.providerRuntimeHeadersPort?{providerRuntimeHeadersPort:Ve.providerRuntimeHeadersPort}:{},resume:qe!==void 0,runtimeConfig:{...t.override?{mode:t.override}:{},...u?{toolDisallowlist:u}:{},toolSearch:{mode:h},totalTokensReminder:{enabled:k},subagents:{alwaysBackground:x},...p?{midConversationSystem:{mode:"force"}}:{},...dBt(b),modelStreaming:"on",titleGeneration:m8i,workingDirectory:ut},permissionBroker:Q,sessionId:qe,skipUserConfig:e.skipUserConfig,uiDetectedLocale:a,uiLocale:O,userConfigPath:e.userConfigPath,version:n})}catch(bn){throw await oj(async()=>Ut?.close(),W),bn}if(Ut&&z.set(sn,Ut),L)throw await ne(sn),new Error("TUI prompt handler is closed");let $zTuiCliDefaultPromptModel=true;let $zCliDefaultPromptModel=process.env.ZCODE_CLI_PROMPT_MODEL;let $zCliDefaultPromptEffort=process.env.ZCODE_CLI_PROMPT_EFFORT;if($zCliDefaultPromptEffort&&$zCliDefaultPromptEffort.toLowerCase()==="auto")$zCliDefaultPromptEffort=void 0;if($zCliDefaultPromptModel&&!$zCliDefaultPromptEffort){await sn.setModel($zCliDefaultPromptModel,{transient:true,cliDefault:true});}else if($zCliDefaultPromptEffort){let $zPromptSelection,$zPromptCurrent;if($zCliDefaultPromptModel){let $zPromptSlash=$zCliDefaultPromptModel.indexOf("/");if($zPromptSlash<=0||$zPromptSlash===$zCliDefaultPromptModel.length-1)throw new Error("Invalid prompt model selection.");$zPromptSelection={providerId:$zCliDefaultPromptModel.slice(0,$zPromptSlash),modelId:$zCliDefaultPromptModel.slice($zPromptSlash+1)};}else{await sn.readExecutionState?.();$zPromptCurrent=sn.getCurrentModelOption?.();if(!$zPromptCurrent?.ref)throw new Error("Cannot apply --effort without a current model. Pass --model or select a model first.");$zPromptSelection={...$zPromptCurrent.ref};}let $zPromptOption=sn.getModelOption?.($zPromptSelection);let $zPromptLevels=($zPromptOption?.reasoning?.levels??[]).map($zLevel=>$zLevel.value);if($zPromptOption&&$zPromptLevels.length===0)throw new Error("Model "+$zPromptSelection.providerId+"/"+$zPromptSelection.modelId+" does not support reasoning effort.");let $zPromptLevel=$zPromptLevels.find($zLevel=>$zLevel===$zCliDefaultPromptEffort)??$zPromptLevels.find($zLevel=>$zLevel.toLowerCase()===$zCliDefaultPromptEffort.toLowerCase());if($zPromptLevels.length>0&&!$zPromptLevel)throw new Error("Unsupported reasoning effort: "+$zCliDefaultPromptEffort+". Available: "+$zPromptLevels.join(", ")+".");await sn.setModel({...$zPromptSelection,options:{...$zPromptSelection.options,reasoningLevel:$zPromptLevel??$zCliDefaultPromptEffort}},{transient:true,cliDefault:true});}return sn},"createApp"),De=r(async()=>(R??=await ke(o),t.current=mEe(R,sH(t)),R),"getApp"),Ee=r(async Re=>await ie(async()=>await ke(Re?{continueSession:!1,resumeSessionId:Re}:{continueSession:!0})),"resumeApp"),lt=r(async()=>await ie(async()=>await ke({continueSession:!1})),"newApp"),St=r(async Re=>{if(t.override=Re,R){let Me=R;if(Me.setMode){let Te=await Me.setMode(Re);return t.current=mEe(Me,Te.mode),t.current}Me.runtime.updateConfig({mode:Re})}return t.current=R?mEe(R,Re):Re,t.current},"setCliMode"),Le=OVe({forkApp:r(async Re=>{let Te=await(await De()).forkFromCheckpoint?.({targetCheckpointId:Re});if(!Te)throw new Error("Forking is not available in this client.");return await ie(async()=>await ke({continueSession:!1,resumeSessionId:Te.forkedSessionId})),{copiedMessageCount:Te.copiedMessageCount,forkedSessionId:Te.forkedSessionId,response:`${Te.response}
15880
15880
  Switched to forked session ${Te.forkedSessionId}.`,restoredFileCount:Te.restoredFileCount??Te.restoredFiles?.length??0}},"forkApp"),getApp:De,getMode:r(()=>sH(t),"getMode"),getLocale:r(()=>R?.getLocale?.()??MKn(O,a)??c,"getLocale"),hasSelectableModels:o3i(De),listCustomCommands:r(()=>IBt(e),"listCustomCommands"),listSessions:r(()=>e8i(e),"listSessions"),listSkills:r(()=>Q3i(e),"listSkills"),configureApiKey:r(Re=>d8i(e,Re),"configureApiKey"),login:r(Re=>l8i(e,Re),"login"),loginBigmodel:r(Re=>u8i(e,Re),"loginBigmodel"),loadCustomCommand:r(Re=>X3i(e,Re),"loadCustomCommand"),newApp:lt,recordInputHistory:r(async(Re,Me)=>{await R?.recordInputHistory?.(Re,Me)},"recordInputHistory"),resumeApp:Ee,saveDefaultModelSelection:r(async Re=>{let Me=await j.providerRegistryRuntimePromise;if(!Me?.modelSelectionConfigRepository)throw new Error("Default model configuration storage is unavailable.");await Me.modelSelectionConfigRepository.saveConfiguredDefault(Re)},"saveDefaultModelSelection"),logout:r(()=>p8i(e),"logout"),setLocale:r(async Re=>{if(R?.setLocale){let Te=await R.setLocale(Re);return O=Re,Te}return O=Re,{configPath:(await Gwe(e.userConfigPath??c6(),Re)).path,locale:MKn(Re,a)??"en-US",requestedLocale:Re}},"setLocale"),setMode:St,workflowMode:b}),We=r(async(Re,Me)=>{let Te=await Le(Re,Me);return R?{...Te,...await TZn(await De())}:Te},"submitPrompt");return We.setMode=async Re=>({mode:await St(Re)}),We.registerPermissionRequester=Re=>(q=Re,()=>{q===Re&&(q=void 0)}),We.sendInput=async(Re,Me)=>{let Te=mpe(typeof Re=="string"?Re:Re.text);if(Te?.type==="known"&&(Te.name==="model"||Te.name==="effort"))return{kind:"command_result",result:await We(Re,{...Me,abortSignal:Me?.abortSignal??new AbortController().signal})};let ct=await De();if(ct.sendInput){let Ve=await ct.sendInput(Re,Me);return Ve.kind!=="started_turn"?Ve:CZn(await(Ve.result??Ve.completion),ct,sH(t))}return CZn(await ct.submitPrompt(Re,Me),ct,sH(t))},We.listSkills=async()=>await Q3i(e),We.$zReadProviderRegistryRuntime=()=>j.providerRegistryRuntimePromise,o8i(We,De),We.subscribeSessionEvents=Re=>{let Me=ge.addSink(Re);return De().then(()=>ge.reattach(),()=>{}),Me},We.getMainSessionId=()=>{let Me=R?.runtime?.getSessionId?.();return typeof Me=="string"&&Me.length>0?Me:void 0},We.close=async()=>{L??=(async()=>{await ne(),await oj(async()=>j.shutdownTelemetry?.(),W),(await j.providerRegistryRuntimePromise)?.dispose()})(),await L},We}var y8i=V(()=>{"use strict";km();dF();hBt();NKn();dZn();vBt();r8i();i8i();c8i();y_e();f8i();xZn();IZn();cZn();g8i();$ee();r(_8i,"createTuiSubmitPrompt")});var v8i,b8i,m1,Hee,JP,S8i,w8i,oKc,iKc,k8i,x8i,sKc,aKc,cKc,lKc,uKc,dKc,T8i=V(()=>{"use strict";v8i=require("node:crypto"),b8i=require("node:fs"),m1=require("node:fs/promises"),Hee=require("node:os"),JP=require("node:path"),S8i=require("node:url"),w8i="zcode-tui-runtime/",oKc=`${w8i}manifest.json`,iKc="node_modules/@zcode/tui/dist/index.js",k8i="manifest.json",x8i=r(async()=>{let e=await import("node:sea");if(!e.isSea())return await import("@zcode/tui");let t=await sKc(e);return await import((0,S8i.pathToFileURL)((0,JP.join)(t,iKc)).href)},"loadTuiRuntime"),sKc=r(async e=>{let t=aKc(e),n=(0,JP.join)(lKc(),"0.18.0",t.target,t.hash),o=(0,JP.join)(n,k8i);if(await cKc(o,t))return n;let i=`${n}.tmp-${process.pid}-${Date.now()}`;await(0,m1.rm)(i,{force:!0,recursive:!0}),await(0,m1.mkdir)(i,{recursive:!0});for(let a of t.files){let c=e.getRawAsset(`${w8i}${a.path}`),u=Buffer.from(c);if((0,v8i.createHash)("sha256").update(u).digest("hex")!==a.sha256)throw new Error(`SEA TUI asset hash mismatch for ${a.path}`);let h=(0,JP.join)(i,a.path);await(0,m1.mkdir)((0,JP.dirname)(h),{recursive:!0}),await(0,m1.writeFile)(h,u),await(0,m1.chmod)(h,a.mode??dKc(a.path))}return await(0,m1.writeFile)(uKc(i),JSON.stringify(t,null,2)),await(0,m1.rm)(n,{force:!0,recursive:!0}),await(0,m1.mkdir)((0,JP.dirname)(n),{recursive:!0}),await(0,m1.rename)(i,n),n},"ensureSeaTuiRuntime"),aKc=r(e=>{let t=e.getAsset(oKc,"utf8"),n=JSON.parse(t);if(n.version!==1||!n.hash||!Array.isArray(n.files))throw new Error("Invalid SEA TUI runtime manifest.");return n},"readManifest"),cKc=r(async(e,t)=>{if(!(0,b8i.existsSync)(e))return!1;try{let n=JSON.parse(await(0,m1.readFile)(e,"utf8"));return n.hash===t.hash&&n.target===t.target}catch{return!1}},"isCacheCurrent"),lKc=r(()=>{let e=(0,Hee.homedir)();return(0,Hee.platform)()==="darwin"&&e?(0,JP.join)(e,"Library","Caches","zcode","sea-assets"):(0,Hee.platform)()==="win32"?(0,JP.join)(process.env.LOCALAPPDATA??(0,JP.join)(e||(0,Hee.tmpdir)(),"AppData","Local"),"zcode","Cache","sea-assets"):(0,JP.join)(process.env.XDG_CACHE_HOME??(0,JP.join)(e||(0,Hee.tmpdir)(),".cache"),"zcode","sea-assets")},"cacheBaseDirectory"),uKc=r(e=>(0,JP.join)(e,k8i),"markerPathForDirectory"),dKc=r(e=>/\.(?:dll|dylib|node|so)$/i.test(e)?493:420,"modeForPath")});function I8i({deps:e,options:t,workingDirectory:n}){let o=Vh({cliOverrides:pKc(t.locale),env:e.env??process.env,projectConfigPath:e.projectConfigPath,skipUserConfig:e.skipUserConfig,userConfigPath:e.userConfigPath,workingDirectory:n});return o5(o.config.ui.locale,t.detectedLocale)}var pKc,C8i=V(()=>{"use strict";km();dF();pKc=r(e=>e?{ui:{locale:e}}:void 0,"localeCliOverrides");r(I8i,"resolveTuiStartupLocale")});function A8i(e){let t=e.fileSystemPort??mZ(),n=(0,CF.resolve)(e.workspaceDirectory);return require(require("node:path").join(__dirname,"cli-config.cjs")).withRecursiveWorkspacePathSuggestions(async o=>{let i=_Kc(o.token);if(!i)return{items:[],truncated:!1};let a=(0,CF.resolve)(n,i.directoryToken);if(!SKc(n,a))return{items:[],truncated:!1};try{let u=(await t.listDirectory({path:a},{signal:o.abortSignal})).entries.flatMap(h=>{if(h.kind!=="directory"&&h.kind!=="file")return[];if(h.kind==="directory"&&gKc.has(h.name))return[];if(!i.query.startsWith(".")&&h.name.startsWith("."))return[];if(!yKc(h.name,i.query))return[];let _=bKc(n,h.path);return _?[{kind:h.kind,path:h.kind==="directory"?`${_}/`:_}]:[]}).sort((h,_)=>vKc(h,_,i.query)),p=Math.max(1,Math.floor(o.limit??fKc));return{items:u.slice(0,p),truncated:u.length>p}}catch{return{items:[],truncated:!1}}},{workspaceDirectory:n,fileSystemPort:t,excludedDirectories:gKc})}function _Kc(e){let t=e.replace(/^@/u,"");if(t.startsWith("/")||t.startsWith("\\")||(0,CF.isAbsolute)(t)||hKc.test(t))return;let n=t.replace(mKc,"/");if(n.split("/").some(i=>i===".."))return;let o=n.lastIndexOf("/");return o<0?{directoryToken:"",query:n}:{directoryToken:n.slice(0,o+1),query:n.slice(o+1)}}function yKc(e,t){return t.length===0?!0:e.toLowerCase().includes(t.toLowerCase())}function vKc(e,t,n){if(e.kind!==t.kind)return e.kind==="directory"?-1:1;let o=E8i(e.path),i=E8i(t.path),a=n.toLowerCase(),c=o.toLowerCase().startsWith(a),u=i.toLowerCase().startsWith(a);return c!==u?c?-1:1:e.path.localeCompare(t.path)}function E8i(e){let t=e.endsWith("/")?e.slice(0,-1):e,n=t.lastIndexOf("/");return n<0?t:t.slice(n+1)}function bKc(e,t){let n=(0,CF.relative)(e,t);if(!(!n||n.startsWith("..")||(0,CF.isAbsolute)(n)))return n.split(CF.sep).join("/")}function SKc(e,t){let n=(0,CF.relative)(e,t);return n===""||!n.startsWith("..")&&!(0,CF.isAbsolute)(n)}var CF,fKc,mKc,hKc,gKc,R8i=V(()=>{"use strict";Xve();CF=require("node:path"),fKc=50,mKc=/[\\/]+/gu,hKc=/^[a-zA-Z]:[\\/]/u,gKc=new Set([".bzr",".git",".hg",".jj",".sl",".svn","node_modules"]);r(A8i,"createWorkspacePathSuggestionProvider");r(_Kc,"parseWorkspacePathToken");r(yKc,"matchesPathQuery");r(vKc,"compareWorkspacePathSuggestion");r(E8i,"basenameFromSuggestion");r(bKc,"toWorkspaceRelativePath");r(SKc,"isPathInside")});async function O8i(e){let t=e.maxOutputBytes??TKc,n=e.timeoutMs??xKc,i=await(e.runCommand??CKc)(wKc,["-C",e.workspaceDirectory,...kKc],{maxOutputBytes:t,timeoutMs:n}).catch(()=>({exitCode:-1,stdout:""}));if(i.exitCode!==0)return;let a=i.stdout.trim().split(/\r?\n/,1)[0]?.trim();if(!(!a||a===IKc))return a}async function CKc(e,t,n){return await new Promise(o=>{let i;try{i=(0,P8i.spawn)(e,t,{stdio:["ignore","pipe","ignore"],windowsHide:!0})}catch{o({exitCode:-1,stdout:""});return}let a="",c=!1,u=setTimeout(()=>{i.kill(),p({exitCode:-1,stdout:a})},n.timeoutMs),p=r(h=>{c||(c=!0,clearTimeout(u),o(h))},"finish");i.stdout?.on("data",h=>{a+=h.toString("utf8"),Buffer.byteLength(a,"utf8")>n.maxOutputBytes&&(i.kill(),p({exitCode:-1,stdout:a}))}),i.on("error",()=>p({exitCode:-1,stdout:a})),i.on("close",h=>p({exitCode:h,stdout:a}))})}var P8i,wKc,kKc,xKc,TKc,IKc,D8i=V(()=>{"use strict";P8i=require("node:child_process"),wKc="git",kKc=["symbolic-ref","--quiet","--short","HEAD"],xKc=750,TKc=512,IKc="HEAD";r(O8i,"resolveWorkspaceGitBranch");r(CKc,"runGitCommand")});var M8i,N8i=V(()=>{"use strict";To();J3i();Y3i();hBt();y_e();xZn();y8i();T8i();C8i();R8i();D8i();IZn();$ee();M8i=r(async(e,t,n,o,i,a,c,u=!1,p="off",h=Uee,_=!1,v=!0)=>{try{let b=h8i(i),k=n.runTui??(await x8i()).runTui,x=(n.cwd??process.cwd)(),I=n.env??process.env,R=XNe(I)==="development",O=I8i({deps:n,options:t,workingDirectory:x}),j=_8i(n,b,o,a,t.locale,t.detectedLocale,O,c,u,p,t.browserUse,t.browserExecutable,h,_,v,t.browserState),L=ust({cleanup:r(async()=>{await j.close?.()},"cleanup"),cleanupTimeoutMs:n.shutdownCleanupTimeoutMs,exitProcess:n.exitProcess,process:n.shutdownProcess});try{let $zTuiResumeOptions=a,$zTuiResumeReady=($zTuiResumeOptions.resumeSessionId||$zTuiResumeOptions.continueSession)?await j.readExecutionState?.():void 0;return await k({loadStartupOptions:r(async()=>{let[$,z,q]=await Promise.all([t8i(j),IBt(n).catch(()=>{}),(n.resolveWorkspaceGitBranch??O8i)({workspaceDirectory:x}).catch(()=>{})]);return{initialMode:sH(b),initialModel:$.model,initialThoughtLevel:$.thoughtLevel,loginRequired:$.loginRequired,locale:$.locale??O,theme:$.theme??"auto",modelOptions:$.modelOptions,effortOptions:$.effortOptions,slashCommands:oZn(z,{workflowMode:h}),workspaceGitBranch:q}},"loadStartupOptions"),locale:O,developerMode:R,version:o,workspaceDirectory:x,noColor:t.noColor,readClipboardImage:n.readClipboardImage??V3i(),readDefaultModel:j.readDefaultModel,setDefaultModel:j.setDefaultModel,reloadModelOptions:j.reloadModelOptions,listModelOptions:j.listModelOptions,listWorkspacePathSuggestions:j.listWorkspacePathSuggestions,listMcpServers:j.listMcpServers,readSubagents:j.readSubagents,readSubagentTranscript:j.readSubagentTranscript,listWorkflowRuns:j.listWorkflowRuns,replayWorkflowRuns:j.replayWorkflowRuns,reduceWorkflowRuns:($zState,$zEvent)=>{C8r();return Qdt($zState,$zEvent)},retuneWorkflowConcurrency:j.retuneWorkflowConcurrency,listSavedWorkflows:j.listSavedWorkflows,readSavedWorkflow:j.readSavedWorkflow,saveWorkflowRun:j.saveWorkflowRun,startSavedWorkflow:j.startSavedWorkflow,getMainSessionId:j.getMainSessionId,registerPermissionRequester:j.registerPermissionRequester,writeClipboardText:n.writeClipboardText??Z3i({stdout:e.stdout}),stderr:e.stderr,stdin:e.stdin,stdout:e.stdout,showReasoning:require(require("node:path").join(__dirname,"cli-config.cjs")).readTuiShowReasoning(process.env),loadSessionTranscript:j.loadSessionTranscript,loadSessionContextMessages:j.loadSessionContextMessages,readGoal:j.readGoal,readTodos:j.readTodos,readRuntimeProjection:j.readRuntimeProjection,readSessionUsage:j.readSessionUsage,cancelBackgroundTask:j.cancelBackgroundTask,previewFileRewind:j.previewFileRewind,applyFileRewind:j.applyFileRewind,setCustomSessionTitle:j.setCustomSessionTitle,readCustomSessionTitle:j.readCustomSessionTitle,readSessionResumeTarget:j.readSessionResumeTarget,readSessionDatabasePath:j.readSessionDatabasePath,createManagedWorktree:j.createManagedWorktree,listManagedWorktrees:j.listManagedWorktrees,restartTuiAtDirectory:j.restartTuiAtDirectory,interruptTurn:j.interruptTurn,promoteQueuedInput:j.promoteQueuedInput,listSkills:j.listSkills,readExecutionState:j.readExecutionState,setPlanEnabled:j.setPlanEnabled,setTransientModel:j.setTransientModel,readSessionModel:j.readSessionModel,sendBackgroundTaskMessage:j.sendBackgroundTaskMessage,recallPreviousInput:j.recallPreviousInput,sendInput:j.sendInput,setMode:j.setMode,submitPrompt:j,subscribeSessionEvents:j.subscribeSessionEvents})}finally{L(),await j.close?.()}}catch(b){let k=b instanceof Error?b.message:String(b);return e.stderr.write(`Error: ${k}
15881
15881
  `),t.verbose&&b instanceof Error&&b.stack&&e.stderr.write(`${b.stack}
15882
15882
  `),1}},"runTuiCommand")});function j8i(e){if((e.explicitPath!==void 0||e.disabled)&&e.browserUse!=="headless")return EKc;if(e.explicitPath!==void 0&&e.disabled)return AKc}async function B8i(e){if(e.disabled)return{ok:!0,notices:[]};let t=e.explicitPath===void 0?{source:"default",path:IPn(e.env,e.platform)}:{source:"explicit",path:(0,L8i.resolve)(e.launchCwd,e.explicitPath)},n;try{n=await A8e(t.path,{platform:e.platform})}catch(i){if(!(i instanceof jL))throw i;return t.source==="default"&&i.code==="missing"?{ok:!0,notices:[]}:{ok:!1,error:DKc(i,t.source)}}let o=n.looseMode===void 0?void 0:n.looseMode.toString(PKc).padStart(OKc,"0");return{ok:!0,selection:t,notices:MKc(t,n.unknownFields,o),logFields:{source:t.source,...n.summary,unknownFieldCount:n.unknownFields.length,...o===void 0?{}:{looseMode:o}}}}function DKc(e,t){let n=e.code==="invalid_schema"&&e.issues.length>0?` (fields: ${e.issues.join(F8i)})`:"",o=t==="default"?` ${RKc}`:"";return`${e.message}: ${e.path}${n}.${o}`}function MKc(e,t,n){let o=[];return e.source==="default"&&o.push(`Loaded default browser state from ${e.path}. Pass --no-browser-state to skip it.`),t.length>0&&o.push(`Browser state file has fields that will be ignored: ${t.join(F8i)}.`),n!==void 0&&o.push(`Browser state file is readable by other users (mode ${n}). Run: chmod 600 ${e.path}`),o}var L8i,EKc,AKc,RKc,F8i,PKc,OKc,U8i=V(()=>{"use strict";L8i=require("node:path");xSt();EKc="--browser-state and --no-browser-state require --browser-use=headless.",AKc="--browser-state cannot be used with --no-browser-state.",RKc="Fix the file or pass --no-browser-state.",F8i=", ",PKc=8,OKc=4;r(j8i,"validateBrowserStateFlags");r(B8i,"resolveBrowserStateSelection");r(DKc,"formatFileError");r(MKc,"buildNotices")});var $8i={};f0($8i,{run:()=>aZc});var aH,NKc,LKc,FKc,jKc,BKc,UKc,zKc,$Kc,qKc,WKc,VKc,HKc,GKc,JKc,KKc,EBt,EZn,ZKc,YKc,z8i,XKc,QKc,eZc,tZc,nZc,rZc,oZc,CBt,iZc,sZc,aZc,q8i=V(()=>{"use strict";vn();d_e();est();$Ue();ef();ef();dF();Xoe();Bdi();DKn();NKn();Bee();j6i();H6i();Z6i();BKn();man();Can();nBi();E3i();$3i();gZn();N8i();U8i();$ee();aH="0.18.0",NKc="--target requires non-empty text.",LKc="yolo",FKc="--force-mcs can only be used with --prompt, --target, or tui.",jKc="--toolsearch-mode can only be used with --prompt, --target, or tui.",BKc="--total-tokens-reminder can only be used with --prompt, --target, or tui.",UKc="--total-tokens-reminder must be one of on, off.",zKc="--agent-always-background can only be used with --prompt, --target, or tui.",$Kc="--agent-always-background must be one of on, off.",qKc="--target-replace requires --target.",WKc='--target cannot be used with --prompt. Use either --target <objective> or --prompt "/goal <objective>".',VKc="--browser-executable requires --browser-use=headless.",HKc="--browser-use=headless can only be used with --prompt, --target, or tui.",GKc="--surface can only be used with --prompt, --target, app-server, or agent-server.",JKc="--memory-bench can only be used with -p/--prompt.",KKc=r(e=>({...e.all===!0?{all:!0}:{},...e.available===!0?{available:!0}:{},...e["keep-data"]===!0?{keepData:!0}:{},...typeof e.scope=="string"?{scope:e.scope}:{},...Array.isArray(e.sparse)?{sparse:e.sparse}:{}}),"pluginsCommandFlags"),EBt=r(e=>e[0]??"tui","commandName"),EZn=r(e=>typeof e.prompt=="string"||e.targetRequest!==void 0||EBt(e.positionals)==="tui","isForceMcsSupportedInvocation"),ZKc=r(e=>{let t=EBt(e.positionals);return typeof e.prompt=="string"||e.targetRequest!==void 0||t==="app-server"||t==="agent-server"},"isPresentationSurfaceSupportedInvocation"),YKc=r((e,t,n,o,i,a)=>({browserExecutable:i,browserUse:o,detectedLocale:n,force:e.force===!0,json:e.json===!0,locale:t,...e["memory-bench"]===!0?{memoryBench:!0}:{},noColor:e["no-color"]===!0,...a?{outputFormat:a}:{},verbose:e.verbose===!0}),"globalOptions"),z8i=["text","json","stream-json"],XKc=r(e=>{if(e!==void 0){if(z8i.includes(e))return e;throw new Error(`--output-format must be one of ${z8i.join(", ")} (received: ${e}).`)}},"normalizeOutputFormat"),QKc=r(e=>{if(e!==void 0){if(l9e(e))return e;throw new Error(sB().cli.errors.localeUnsupported(e))}},"normalizeLocaleOption"),eZc=r(e=>{if(e===void 0)return;let t=e.toLowerCase();if(t==="build"||t==="edit"||t==="yolo"||t==="guarded")return t;throw new Error(`Unsupported --mode value: ${e}. Supported modes: build, edit, guarded, yolo. Use /plan in the TUI to toggle planning.`)},"normalizePromptMode"),tZc=r(e=>{if(e!==void 0){if(e.toLowerCase()==="headless")return"headless";throw new Error(`Unsupported --browser-use value: ${e}. Supported value: headless.`)}},"normalizeBrowserUse"),nZc=r(e=>{if(e===void 0||e.toLowerCase()==="terminal")return"terminal";if(e.toLowerCase()==="desktop")return"zcode_desktop";throw new Error(`Unsupported --surface value: ${e}. Supported surfaces: terminal, desktop.`)},"normalizePresentationSurface"),rZc=r(e=>{let t=e.target,n=e["target-replace"]===!0;if(t===void 0){if(n)throw new Error(qKc);return}let o=t.trim();if(o.length===0)throw new Error(NKc);return{objective:o,replaceExisting:n}},"normalizeTargetRequest"),oZc=r(e=>e.replaceExisting?`/goal replace ${e.objective}`:`/goal ${e.objective}`,"buildHeadlessTargetCommand"),CBt=r((e,t,n)=>{e.write(jdi(aH,t,n))},"writeHelp"),iZc=r((e,t,n)=>{let o=d$n(),i={cli:{name:kTr,processName:fan,version:aH},runtime:{arch:o.arch,cwd:n,execPath:o.execPath,node:o.node,platform:o.platform,processTitle:process.title,sea:o.sea},packaging:{default:"node-bundle",sea:"optional"},configuration:require(require("node:path").join(__dirname,"cli-config.cjs")).inspectRuntimeConfiguration(n,$zOptions=>{Dxo();return Vh($zOptions)})};if(t.json)return e.stdout.write(xg(i)),i.configuration.ok?0:1;let a=l$n(e.stdout,t.noColor);return e.stdout.write(`${u$n.bold("zcode doctor",a)}