qlogicagent 2.17.5 → 2.17.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +6 -6
- package/dist/index.js +6 -6
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -462,10 +462,10 @@ attribution: ${o}`}function vo(t){return t&&typeof t=="object"&&!Array.isArray(t
|
|
|
462
462
|
${x.result.content}`,K=Wt(T.id,{ok:!0,payload:q,imageUrls:x.result.imageUrls,toolReferences:x.result.toolReferences});j.push(K),qt.push(T.id),_.add(T.function.name),$++,yield{type:"tool_result",turnId:o,callId:T.id,name:T.function.name,ok:!0,outputPreview:q.slice(0,2e3),durationMs:0,details:{type:T.function.name,reusedIdenticalCall:!0,repeatCount:x.repeatCount}}}if(kl.some(x=>x.call.function.name==="exec"&&u0(x.call.function.arguments))){let x=Y(D);j.push({role:"user",content:pQ(R.artifactContract)}),yield{type:"tool_selection_policy",turnId:o,policyId:"browser_verification_after_preparation_required",intent:"verification",reason:"repeated-browser-preparation-command",availableToolNames:Y(a??c),enabledToolNamesBefore:x,enabledToolNamesAfter:x,suppressedToolNames:[],nextAction:"run-browser-verification-script-not-playwright-install"},yield we("browser_verification_after_preparation_required","reused successful browser preparation command")}for(let x of go){k.push({name:x.function.name,reason:"identical-repeat-policy"});let T=fp.get(`${x.function.name}::${x.function.arguments}`),q=Op(j,x.function.name),K=oQ(q),N=aM.has(x.id)?eee(T,x):K?`This exact tool call has been attempted ${T} times. Last error: ${K}. Do not retry. Report this error to the user.`:`This exact tool call has been attempted ${T} times and keeps failing. Do not retry it. Report the issue to the user or try a completely different approach.`,me=Wt(x.id,{ok:!1,error:N});j.push(me),qt.push(x.id),_.add(x.function.name),$++,yield{type:"tool_result",turnId:o,callId:x.id,name:x.function.name,ok:!1,error:N}}if(go.length>0&&bl.length===0&&kl.length===0&&go.every(x=>aM.has(x.id))&&R.existingFileUpdateRecoveryCount<2){let x=Y(D);D=s0(v,se);let T=Y(D);B=!0,Ue=!0;let q=[...new Set(go.map(K=>Xp(K.function.arguments)).filter(K=>!!K))];j.push({role:"user",content:`Existing-file maintenance recovery: the same write call was repeatedly attempted for an existing file. Do not use write for these existing path(s): ${q.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:o,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"repeated-existing-file-write",availableToolNames:Y(a??c),enabledToolNamesBefore:x,enabledToolNamesAfter:T,suppressedToolNames:Kk(x,T),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield we("existing_file_update_recovery",q.join(",")||"unknown"),R={...R,messages:j,existingFileUpdateRecoveryCount:R.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}if(go.length>0){let x=Op(j,go[0].function.name),T={role:"user",content:"Tool calls were blocked because you repeated them with identical arguments too many times. "+(x?`The error was: "${x}". Tell the user about this error. `:"The operation is not working. ")+"Stop retrying and report the result to the user."};j.push(T)}let IX=E>=3&&R.repeatedToolFailureRecoveryCount<1;if(go.length>0&&bl.length===0&&kl.length===0&&!IX){let x=p0(Nk(j,1),{availableToolNames:Y(a??c),enabledToolNames:gt(),toolCallNames:[..._].sort(),blockedToolCalls:Wp(k)});yield*Z(x);return}let cM=[],sb=[];for(let x of bl){let T=sD({toolName:x.function.name,rawArguments:x.function.arguments});T?sb.push({call:x,...T}):cM.push(x)}for(let x of sb){let T=x.call;k.push({name:T.function.name,reason:"read-only-context-pack"}),j.push(Wt(T.id,{ok:!1,error:x.error})),qt.push(T.id),_.add(T.function.name),$++,yield{type:"tool_result",turnId:o,callId:T.id,name:T.function.name,ok:!1,error:x.error},r.warn(`read-only context-pack blocked: ${T.function.name} ${x.path}`)}sb.length>0&&j.push({role:"user",content:"A write was blocked because context-pack is read-only evidence. Continue by writing compact indexes, checkpoints, and maintenance updates under benchmark-state; do not retry writes into context-pack."});let _X=new Set(D.map(x=>x.function.name)),lM=[],gp=[];for(let x of cM){let T=T0(x.function.name,x.function.arguments,_X);T?gp.push({call:x,...T}):lM.push(x)}for(let x of gp){let T=x.call;k.push({name:T.function.name,reason:"existing-file-update-tool-required"}),j.push(Wt(T.id,{ok:!1,error:x.error})),qt.push(T.id),_.add(T.function.name),$++,yield{type:"tool_result",turnId:o,callId:T.id,name:T.function.name,ok:!1,error:x.error},r.info(`existing file update blocked: ${T.function.name} ${x.path}`)}if(gp.length>0){let x=Y(D);D=s0(v,se);let T=Y(D);B=!0,Ue=!0;let q=[...new Set(gp.map(K=>K.path))];j.push({role:"user",content:`Existing-file maintenance recovery: a write was blocked because the target file already exists and edit/patch are enabled. Do not use write for these existing path(s): ${q.join(", ")||"(unknown)"}. Do not delete, remove, or recreate an existing file to make write succeed; that is artifact path drift, not maintenance. Use read only if you need the current contents, then use edit or patch for the smallest valid change. After the edit/patch succeeds, continue build/browser verification normally.`}),yield{type:"tool_selection_policy",turnId:o,policyId:"existing_file_update_recovery",intent:"tool_recovery",reason:"existing-file-write-blocked",availableToolNames:Y(a??c),enabledToolNamesBefore:x,enabledToolNamesAfter:T,suppressedToolNames:Kk(x,T),nextAction:"use-read-edit-or-patch-for-existing-file-update"},yield we("existing_file_update_recovery",q.join(",")||"unknown"),R={...R,messages:j,existingFileUpdateRecoveryCount:R.existingFileUpdateRecoveryCount+1,transition:{reason:"next_turn"}};continue}let dM=[],ab=[];for(let x of lM){let T=iD({state:R.artifactContract,inputMessages:s,toolName:x.function.name,rawArguments:x.function.arguments});T?ab.push({call:x,...T}):dM.push(x)}for(let x of ab){let T=x.call;k.push({name:T.function.name,reason:"artifact-root-contract"}),Ik(R.artifactContract,{path:x.path,artifactRoot:x.artifactRoot,toolName:T.function.name}),j.push(Wt(T.id,{ok:!1,error:x.error})),qt.push(T.id),_.add(T.function.name),$++,yield{type:"tool_result",turnId:o,callId:T.id,name:T.function.name,ok:!1,error:x.error},mo()&&(yield lt()),r.warn(`artifact root contract blocked: ${T.function.name}`)}ab.length>0&&j.push({role:"user",content:"A write was blocked by the artifactRoot contract. Continue inside the declared artifactRoot, or stop with an honest final status that lists the root drift as Not done."});let uM=[],cb=[];for(let x of dM){let T=HD({inputMessages:s,messages:j,toolCall:x});T?cb.push({call:x,error:T}):uM.push(x)}for(let x of cb){let T=x.call;k.push({name:T.function.name,reason:"premature-completion-artifact"}),j.push(Wt(T.id,{ok:!1,error:x.error})),qt.push(T.id),_.add(T.function.name),$++,yield{type:"tool_result",turnId:o,callId:T.id,name:T.function.name,ok:!1,error:x.error},r.info(`premature completion artifact blocked: ${T.function.name}`)}cb.length>0&&j.push({role:"user",content:"A tool attempted to write a completion artifact before all explicitly requested output files had evidence. Do not write final DONE markers or success reports into artifacts until the missing files are created or verified. If you cannot complete them, respond with the requested FAIL marker and the real reason."});let CX=new Set(D.map(x=>x.function.name)),pM=[],hp=[];for(let x of uM)CX.has(x.function.name)?pM.push(x):hp.push(x);for(let x of hp){let T=`Tool "${x.function.name}" was not offered for this turn and will not be executed. Use only the tools listed in the current request.`;k.push({name:x.function.name,reason:"not-offered"}),j.push(Wt(x.id,{ok:!1,error:T})),qt.push(x.id),_.add(x.function.name),r.warn(`unoffered tool call suppressed: ${x.function.name}`)}if(hp.length>0&&R.notOfferedToolRecoveryCount<1){let x=[...new Set(hp.map(me=>me.function.name))].sort(),T=B&&x.includes("write"),q=x.filter(me=>se.has(me)),N=(a??c).filter(me=>x.includes(me.function.name));if(q.length>0)R.notOfferedToolRecoveryCount+=1,Ue=!0,j.push({role:"user",content:`You retried ${q.map(me=>`\`${me}\``).join(", ")} after it was disabled by this turn's tool-selection policy. Do not retry policy-suppressed tools in this turn. Continue using only the currently enabled tools, or stop with a clear blocker.`}),yield{type:"tool_selection_policy",turnId:o,policyId:"policy_suppressed_tool_retry_blocked",intent:"tool_recovery",reason:"requested-tool-disabled-by-turn-policy",availableToolNames:Y(a??c),enabledToolNamesBefore:Y(D),enabledToolNamesAfter:Y(D),suppressedToolNames:q,nextAction:"continue-with-currently-enabled-tools-or-report-blocker"},yield we("policy_suppressed_tool_retry_blocked",q.join(","));else if(!T&&N.length>0){let me=Y(D),Ot=new Map(D.map(Q=>[Q.function.name,Q]));for(let Q of N)Ot.set(Q.function.name,Q);D=xa([...Ot.values()]),R.notOfferedToolRecoveryCount+=1,Ue=!0,yield{type:"tool_selection_policy",turnId:o,policyId:"available_tool_reenabled_after_not_offered_call",intent:"tool_recovery",reason:"requested-tool-available-but-disabled",availableToolNames:Y(a??c),enabledToolNamesBefore:me,enabledToolNamesAfter:Y(D),suppressedToolNames:[],nextAction:"retry-with-reenabled-requested-tool"},j.push({role:"user",content:`You called ${x.map(Q=>`\`${Q}\``).join(", ")} but it was not enabled for that round even though it is available. The requested available tool has now been re-enabled. Use the re-enabled tool once with valid arguments; do not repeat a disabled-tool call.`}),yield we("available_tool_reenabled_after_not_offered_call",x.join(","))}}let mM=[],lb=[];for(let x of pM){let T=D.find(K=>K.function.name===x.function.name),q=hQ(T,x.function.arguments);q?lb.push({call:x,error:q}):mM.push(x)}for(let x of lb){let T=x.call;k.push({name:T.function.name,reason:"invalid-arguments"}),j.push(Wt(T.id,{ok:!1,error:x.error})),qt.push(T.id),_.add(T.function.name),$++,yield{type:"tool_result",turnId:o,callId:T.id,name:T.function.name,ok:!1,error:x.error,details:{type:T.function.name,error:"invalid_arguments"}},r.info(`invalid tool arguments blocked: ${T.function.name}`)}lb.length>0&&j.push({role:"user",content:"Some tool calls were blocked before execution because they did not match the tool schema. Do not retry the same tool with substituted fields. Use the required field names exactly, switch to the correct tool, or stop and report the invalid tool input."});let yp=[],db=[];for(let x of mM){if(x.function.name!=="exec"){yp.push(x);continue}let T=a0(x.function.arguments);if(!T){yp.push(x);continue}let q=Ml(T);Bp(q)&&i0(v)?db.push({call:x,error:gQ(q)}):yp.push(x)}for(let x of db){let T=x.call;k.push({name:T.function.name,reason:"dedicated-tool-required"});let q=Y(D),K=D.filter(N=>["read","search"].includes(N.function.name));K.length>0&&(D=K,te=!0,Ue=!0),j.push(Wt(T.id,{ok:!1,error:x.error})),qt.push(T.id),_.add(T.function.name),$++,yield{type:"tool_result",turnId:o,callId:T.id,name:T.function.name,ok:!1,error:x.error,details:{type:T.function.name,error:"dedicated_tool_required",dedicatedTool:"read/search"}},r.info(`dedicated file tool preflight blocked: ${T.function.name}`),yield{type:"tool_selection_policy",turnId:o,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:Y(a??c),enabledToolNamesBefore:q,enabledToolNamesAfter:Y(D),suppressedToolNames:q.filter(N=>!["read","search"].includes(N)),nextAction:"use-read-search-for-file-inspection-then-resume-build-run-verify-tools"}}db.length>0&&j.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for the next local file inspection step. After that, resume exec only for non-inspection commands such as installs, builds, dev servers, and verification scripts."});let vp=[],ub=[],fM=[],gM=[];for(let x of yp){if(x.function.name!=="exec"){vp.push(x);continue}let T=x,q=a0(T.function.arguments),K=q?aQ(q):null;K&&(T={...T,function:{...T.function,arguments:l0(T.function.arguments,K)}},gM.push({originalCommand:q??"",rewrittenCommand:K}),q=K);let N=q?cQ(q):null;if(N?.action==="block")ub.push({call:T,error:N.error});else if(N?.action==="rewrite"){let me={...T,function:{...T.function,arguments:l0(T.function.arguments,N.command)}};fM.push({call:me,originalCommand:q??"",rewrittenCommand:N.command}),vp.push(me)}else vp.push(T)}for(let x of gM)yield{type:"tool_selection_policy",turnId:o,policyId:"exec_sleep_prefix_guard",intent:"verification",reason:"sleep-prefix-removed",availableToolNames:Y(a??c),enabledToolNamesBefore:Y(D),enabledToolNamesAfter:Y(D),suppressedToolNames:[],nextAction:"execute-command-without-blocking-sleep-prefix"},r.info(`blocking sleep prefix removed before exec: ${x.originalCommand} -> ${x.rewrittenCommand}`);for(let x of fM){let T=Y(D);yield{type:"tool_selection_policy",turnId:o,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"vite-strict-port-normalized",availableToolNames:Y(a??c),enabledToolNamesBefore:T,enabledToolNamesAfter:Y(D),suppressedToolNames:[],nextAction:"execute-normalized-vite-dev-server-command-with-strict-port"},r.info(`vite strict port normalized before exec: ${x.originalCommand} -> ${x.rewrittenCommand}`)}for(let x of ub){let T=x.call;k.push({name:T.function.name,reason:"reserved-frontend-port"});let q=Y(D);j.push(Wt(T.id,{ok:!1,error:x.error})),qt.push(T.id),_.add(T.function.name),$++,yield{type:"tool_result",turnId:o,callId:T.id,name:T.function.name,ok:!1,error:x.error,details:{type:T.function.name,error:"reserved_frontend_port",reservedPort:Vp}},r.info(`reserved frontend port preflight blocked: ${T.function.name}`),yield{type:"tool_selection_policy",turnId:o,policyId:"reserved_frontend_port_guard",intent:"verification",reason:"reserved-frontend-port",availableToolNames:Y(a??c),enabledToolNamesBefore:q,enabledToolNamesAfter:Y(D),suppressedToolNames:[],nextAction:"restart-generated-dev-server-on-explicit-non-5174-port-with-strict-port"}}ub.length>0&&j.push({role:"user",content:"A dev server command was blocked because it could occupy or fallback onto port 5174, which is reserved for the Xiaozhi Claw frontend. Retry with an explicit generated-app port other than 5174 and use --strictPort for Vite so browser evidence cannot be polluted."});let bp=[],ya=[];for(let x of vp){if(x.function.name!=="read"){bp.push(x);continue}let T=Xk(x.function.arguments);if(!T){bp.push(x);continue}let q=Lt(T),K=w0(q);(R.fileReadCounts.get(q)??0)>=K?ya.push({call:x,filePath:q,maxReads:K}):bp.push(x)}for(let x of ya){let T=x.call,q=`Read cycle policy blocked another read of "${x.filePath}" after ${x.maxReads} successful reads in this turn. Stop rereading the same large document. ${Vk(x.filePath)}`;k.push({name:T.function.name,reason:"read-cycle-policy"}),R.fileReadCycleBlockedPaths.add(x.filePath),j.push(Wt(T.id,{ok:!1,error:q})),qt.push(T.id),_.add(T.function.name),$++,yield{type:"tool_result",turnId:o,callId:T.id,name:T.function.name,ok:!1,error:q},r.info(`read cycle blocked: ${x.filePath}`)}if(ya.length>0){let x=[...new Set(ya.map(K=>`${K.filePath} (max ${K.maxReads})`))].join(", "),T=[...new Set(ya.map(K=>Vk(K.filePath)))].join(" ");if(j.push({role:"user",content:`Further reads were blocked because these large/context documents already reached their per-turn read limit: ${x}. Do not retry the read with a different path spelling. ${T} Continue from maintained requirements/defects/decisions/acceptance evidence and report any truly missing section explicitly.`}),D.some(K=>m0(K.function.name))&&(R.persistedBenchmarkStateRecovered||ya.some(K=>tw(K.filePath)))){let K=Y(D),N=K.filter(me=>NQ.has(me)).sort();yield{type:"tool_selection_policy",turnId:o,policyId:"long_horizon_benchmark_state_maintenance",intent:"benchmark_state_maintenance",reason:"read-cycle-guard-retains-evidence-tools",availableToolNames:Y(a??c),enabledToolNamesBefore:K,enabledToolNamesAfter:Y(D),suppressedToolNames:[],nextAction:"maintenance-or-final-answer"},j.push({role:"user",content:`Do not reread the blocked large/context document paths again. Evidence tools still enabled: ${N.join(", ")||"none"}. Use read/search only for targeted verification of generated artifacts, file names, and missing sections; use edit/patch/write only if benchmark-state maintenance needs an update; otherwise stop tool use and answer from the maintained benchmark-state evidence. Classify any unused edit/patch/write tools as not needed, not missing.`}),yield we("benchmark_state_maintenance_tool_bias","retaining targeted evidence tools after long-horizon read-cycle guard")}if(HQ(k,R.fileReadCycleBlockedPaths,R.persistedBenchmarkStateRecovered,R.maintainedDocuments)){yield*Z("Stopped repeated long-horizon context-pack rereads after the read-cycle guard blocked every maintained source document. Continue from benchmark-state/document-index.json, decision-state-table.json, and context-pack-evidence.json; do not reread or rewrite context-pack source documents.",{forcedStop:!0});return}}let pb=KD(bp,R.toolFailureCounts),mb=pb.allowed;if(C&&mb.length>Math.max(0,P-$)){let x=jk({currentToolBudget:P,currentRoundBudget:S,toolHardCap:100,roundHardCap:100,continuationCount:le,successfulSinceLastCheck:X-ct,fileReadCounts:R.fileReadCounts,windowTools:ho,windowRounds:25});x&&(P=x.nextToolBudget,S=x.nextRoundBudget,le=x.continuationCount,ct=X,r.info(`tool budget continuation #${x.continuationCount}: tools\u2192${P}, rounds\u2192${S} (progress detected)`))}let hM=Math.max(0,P-$),Xo=hM>0?mb.slice(0,hM):[],fb=mb.slice(Xo.length),EX=fb.length>0;if(pb.blocked.length>0){for(let x of pb.blocked){let T=x.call;k.push({name:T.function.name,reason:"variant-failure-policy"});let q=Wt(T.id,{ok:!1,error:x.error});j.push(q),qt.push(T.id),_.add(T.function.name),$++,yield{type:"tool_result",turnId:o,callId:T.id,name:T.function.name,ok:!1,error:x.error},r.info(`variant tool blocked: ${T.function.name} failed ${x.failCount}x with different args`)}j.push(VD())}if(fb.length>0){let x=`Tool call budget exhausted (${P}) for this turn. Stop requesting more tools and report what remains incomplete.`;for(let T of fb){k.push({name:T.function.name,reason:"tool-call-budget"});let q=Wt(T.id,{ok:!1,error:x});j.push(q),qt.push(T.id),_.add(T.function.name),$++,yield{type:"tool_result",turnId:o,callId:T.id,name:T.function.name,ok:!1,error:x}}j.push({role:"user",content:`${x} You reached this turn's tool budget after ${le} extension(s). Do NOT claim the task is complete or that all files were created if it is not. Be honest in your reply: (1) state plainly the turn stopped before finishing; (2) list concretely what is DONE vs what is still UNFINISHED; (3) tell the user to reply "\u7EE7\u7EED" to finish the rest. If explicitly requested output files are still missing, respond with the requested FAIL marker and the real reason.`})}for(let x of Xo){let T=x.function.arguments,q=D.find(K=>K.function.name===x.function.name);if(q?.backfillObservableInput)try{let K=JSON.parse(x.function.arguments),N={...K};q.backfillObservableInput(N),Object.keys(N).some(Ot=>!(Ot in K))&&(T=JSON.stringify(N))}catch{}yield{type:"tool_call",turnId:o,callId:x.id,name:x.function.name,arguments:T,inputSummary:Ok(T)},O.add(x.function.name),J++}let MX=new Map(R.toolFailureCounts),kp=null;try{let x=t.runtimePorts.createStreamingToolExecutor({toolInvoker:n,hooks:m,sessionId:i,turnId:o,log:r,signal:f,maxConcurrentTools:t?.maxConcurrentTools,maxExecutionMs:Pb});for(let N of Xo)x.addTool(N);let T=!1;for await(let N of x.getRemainingResults()){let me=nQ(N);if(me){if(k.push({name:N.toolName,reason:me}),N.toolName==="exec"&&me==="dedicated-tool-required"&&i0(v)){let oe=Y(D);j.push({role:"user",content:"Exec was blocked because it attempted local file reading/searching/listing. Use read/search for local file inspection. Exec remains available only for non-inspection commands such as installs, builds, dev servers, and verification scripts."}),yield{type:"tool_selection_policy",turnId:o,policyId:"dedicated_file_tool_required",intent:"fresh_evidence",reason:"exec-file-read-search-list-blocked",availableToolNames:Y(a??c),enabledToolNamesBefore:oe,enabledToolNamesAfter:Y(D),suppressedToolNames:[],nextAction:"use-read-search-for-file-inspection-or-exec-for-build-run-verify"}}if(N.toolName==="exec"&&me==="confirmation-timeout"){let oe=Y(D);se.add("exec");let Ae=ri(v,se);Ae.length>0&&(D=xa(Ae),Ue=!0),j.push({role:"user",content:"Exec confirmation timed out, so exec is disabled for the rest of this turn. Do not retry exec. Use read/search for inspection, edit/patch/write for file updates, ask_user only for missing user input, or stop with a clear blocker if no non-exec tool can complete the request."}),yield{type:"tool_selection_policy",turnId:o,policyId:"exec_confirmation_timeout_recovery",intent:"tool_recovery",reason:"exec-confirmation-timeout",availableToolNames:Y(a??c),enabledToolNamesBefore:oe,enabledToolNamesAfter:Y(D),suppressedToolNames:Kk(oe,Y(D)),nextAction:"continue-with-non-exec-tools-or-report-confirmation-blocker"}}if(N.toolName==="exec"&&me==="global-process-kill-blocked"){let oe=Y(D);j.push({role:"user",content:"Exec was blocked because it attempted to terminate every node process. Do not retry taskkill/killall/pkill/Stop-Process by process name. If a generated app server conflicts with another process, start the generated app on a new explicit non-5174 port with strict port behavior, or stop only an owned background task by its task id. Continue by verifying the app on the reachable generated-app URL."}),yield{type:"tool_selection_policy",turnId:o,policyId:"global_process_kill_recovery",intent:"verification",reason:"global-node-process-kill-blocked",availableToolNames:Y(a??c),enabledToolNamesBefore:oe,enabledToolNamesAfter:Y(D),suppressedToolNames:[],nextAction:"use-owned-task-cancel-or-new-explicit-port"}}}N.blocked&&(yield{type:"tool_blocked",turnId:o,callId:N.callId,name:N.toolName,reason:N.blockReason??"blocked"}),j.push(N.message),qt.push(N.callId),_.add(N.toolName);let Ot=SQ(N,R);Ot||$++;let Q=N.ok&&Dk(N);if(N.ok&&!Q&&!Ot&&(X+=1),Ot||JD({toolFailureCounts:R.toolFailureCounts,toolName:N.toolName,toolArguments:Xo.find(oe=>oe.id===N.callId)?.function.arguments,ok:N.ok,softEmpty:Q}),N.ok&&IQ.has(N.toolName)&&dee(R),N.ok&&m0(N.toolName)){let oe=Xo.find(rt=>rt.id===N.callId),Ae=oe?Xp(oe.function.arguments):void 0;if(Ae){let rt=Lt(Ae);if(R.benchmarkStateMaintenanceRequiredFiles.has(rt)){let Or=rw(R.maintainedDocuments,rt,oe?.function.arguments??"");Or.ok?R.benchmarkStateMaintenanceWrittenFiles.add(rt):(k.push({name:N.toolName,reason:"benchmark-state-invalid-content"}),j.push({role:"user",content:`Benchmark-state maintenance write for ${rt} is incomplete: ${Or.reason}. Rewrite or patch the file using the document evidence already provided; do not reread context-pack source documents.`}))}}}if(N.ok&&!Q&&(Jk.has(N.toolName)||N.toolName==="exec"&&N.details?.type==="exec_background"||N.toolName==="exec"&&u0(Xo.find(oe=>oe.id===N.callId)?.function.arguments??""))){let oe=Xo.find(rt=>rt.id===N.callId),Ae=typeof N.message?.content=="string"?N.message.content:"";if(oe&&Ae){let rt=Array.isArray(N.message.imageUrls)?N.message.imageUrls.filter(Qo=>typeof Qo=="string"):void 0,Or=Array.isArray(N.message.toolReferences)?N.message.toolReferences.filter(Qo=>typeof Qo=="string"):void 0;R.identicalSuccessfulToolResults.set(`${oe.function.name}::${oe.function.arguments}`,{content:Ae,imageUrls:rt,toolReferences:Or})}}if(N.toolName==="agent"){let oe=bs(N.details,"agentId"),Ae=bs(N.details,"status"),rt=Kp(N.details,"background");N.ok&&oe&&rt===!0&&Ae==="running"&&oi(R).add(oe)}if(N.toolName==="task"){let oe=PQ(N.details);oe&&(R.lastTaskList=oe);let Ae=bs(N.details,"taskId"),rt=Kp(N.details,"running"),Or=bs(N.details,"lifecycle"),Qo=bs(N.details,"action");if(Ae&&(Qo==="cancel"||rt===!1||Or&&Or!=="running"&&Or!=="pending"))oi(R).delete(Ae),R.backgroundAgentNoOutputPollCounts.delete(Ae),R.stalledBackgroundAgentTasks.delete(Ae);else if(Ae&&Qo==="output"&&rt===!0&&oi(R).has(Ae)){let bM=typeof N.message?.content=="string"?N.message.content:"",kM=Kp(N.details,"hasOutput");if(kM!==void 0?kM===!1:TQ(bM)){let gb=(R.backgroundAgentNoOutputPollCounts.get(Ae)??0)+1;R.backgroundAgentNoOutputPollCounts.set(Ae,gb);let Sp=vQ(N.details,"elapsedSeconds")??AQ(bM);(Sp!==void 0&&Sp>=xQ||Sp===void 0&&gb>=RQ)&&R.stalledBackgroundAgentTasks.set(Ae,`no output after ${Sp??"unknown"}s across ${gb} poll(s)`)}else R.backgroundAgentNoOutputPollCounts.delete(Ae),R.stalledBackgroundAgentTasks.delete(Ae)}}if(N.ok&&N.toolName==="read"){let oe=Xo.find(Ae=>Ae.id===N.callId);if(oe){let Ae=Xk(oe.function.arguments);if(Ae){let rt=Lt(Ae),Or=R.fileReadCounts.get(rt)??0;R.fileReadCounts.set(rt,Or+1);let Qo=typeof N.message?.content=="string"?N.message.content:"";T=YQ(R,Ae,Qo,R.turnCount,N.details)||T}}}yield GM(o,N);for(let oe of KM(o,N))yield oe;for(let oe of VM({turnId:o,result:N,toolCalls:mr}))yield oe;let fr=mr.find(oe=>oe.id===N.callId),Yo=typeof N.message?.content=="string"?N.message.content:"";if(fr){aD({state:R.artifactContract,inputMessages:s,toolName:N.toolName,rawArguments:fr.function.arguments,ok:N.ok,content:Yo}),mo()&&(yield lt());let oe=uQ(N.toolName,fr.function.arguments);if(oe){let Ae=(nt.get(oe)??0)+1;if(nt.set(oe,Ae),Ae===dQ){let rt=oe.startsWith("exec:")?"exec":"edit";R.recoveryTrace.set(`no_progress_observed:${rt}`,(R.recoveryTrace.get(`no_progress_observed:${rt}`)??0)+1)}}}!kp&&Pt&&N.toolName==="stt"&&N.ok&&(kp=W7(s,N))}if(B&&(D=ri(v,se),B=!1),te&&(D=ri(v,se),te=!1),T){let N=VQ(o,R.maintainedDocuments,R.fileReadCounts,R.turnCount);N&&(yield N);for(let Q of XQ(o,R.maintainedDocuments))yield Q;let me=jQ(R.maintainedDocuments,R.turnCount),Ot=D.some(Q=>Zk.has(Q.function.name));if(me&&Ot){R.benchmarkStateMaintenanceRequiredFiles=new Set(R0(R.maintainedDocuments).map(Lt));for(let Q of D)Zk.has(Q.function.name)||se.add(Q.function.name);D=ri(D,se),Ue=!0,j.push({role:"user",content:me}),yield we("benchmark_state_maintenance_required","forcing write/edit/patch after long-horizon document index")}}let q=oi(R);if(q.size>0){let N=(a??c).find(me=>me.function.name==="task");if(N){let me=Y(D),Ot=[...q].filter(Q=>R.stalledBackgroundAgentTasks.has(Q)).sort();if(Ot.length>0){D=[N],Ue=!0;let Q=Ot.map(Ge=>`${Ge}: ${R.stalledBackgroundAgentTasks.get(Ge)}`).join("; ");j.push({role:"user",content:kQ(Ot,{reason:Q})}),yield{type:"tool_selection_policy",turnId:o,policyId:"background_agent_no_output_watchdog_cancel_required",intent:"lifecycle_reconciliation",reason:"background-agent-no-output-watchdog",availableToolNames:Y(a??c),enabledToolNamesBefore:me,enabledToolNamesAfter:Y(D),suppressedToolNames:me.filter(Ge=>Ge!=="task"),nextAction:"cancel-stalled-background-task"},yield we("background_agent_no_output_watchdog_cancel_required",Q);continue}D=[N],Ue=!0,j.push({role:"user",content:bQ(q)}),yield{type:"tool_selection_policy",turnId:o,policyId:"background_agent_lifecycle_poll_required",intent:"lifecycle_reconciliation",reason:"background-agent-task-unresolved",availableToolNames:Y(a??c),enabledToolNamesBefore:me,enabledToolNamesAfter:Y(D),suppressedToolNames:me.filter(Q=>Q!=="task"),nextAction:"poll-existing-background-task-output"},yield we("background_agent_lifecycle_poll_required",[...q].sort().join(","));continue}}else D.length===1&&D[0]?.function.name==="task"&&(D=ri(v,se));if(yo(s)&&!R.artifactContract.browserVerified&&Jp(R.artifactContract).length>0&&D.some(N=>N.function.name==="exec")&&R.browserAcceptanceRecoveryCount<4){let N=d0(R.artifactContract);R={...R,browserAcceptanceRecoveryCount:R.browserAcceptanceRecoveryCount+1,messages:[...j,{role:"user",content:N}],transition:{reason:"next_turn"}},Ue=!0,yield we("browser_acceptance_required","forcing browser automation after localhost app URL was observed");continue}let K=FQ(R.maintainedDocuments);if(K.length>0&&R.benchmarkStateIntegrityRecoveryCount<$Q){let N=K.map(me=>`${ii(me.path)}: ${me.reason}`).join("; ");R={...R,benchmarkStateIntegrityRecoveryCount:R.benchmarkStateIntegrityRecoveryCount+1,messages:[...j,{role:"user",content:"Your maintained benchmark-state hash files no longer match the tool-derived ground truth: "+N+". The context-pack inputs are read-only and immutable \u2014 the source did NOT change. Restore the exact recorded contentHash/fileSizeBytes; do NOT flip any acceptance verdict on this phantom drift."}],transition:{reason:"next_turn"}},Ue=!0,yield we("benchmark_state_integrity_required","on-disk benchmark-state hash file contradicts tool-derived ground truth; forcing a correction before completion");continue}if(LQ(R)){yield*Z("Maintained benchmark-state files after indexing the context pack. Stopping this turn now because the required document-index.json, decision-state-table.json, and context-pack-evidence.json writes are complete; do not continue into extra writes, context-pack modifications, or repeated reads.");return}}catch(x){let T=x instanceof Error?x.message:String(x);yield{type:"error",turnId:o,error:T,code:"TOOL_EXECUTION_ERROR",usage:R.totalUsage};return}if(kp){yield*Z(kp);return}let yM=Y7(s,j);if(yM){yield*Te(yM);return}let vM=eQ(s,j);if(vM){yield*Te(vM);return}if(j.push(...ZD({toolFailureCounts:R.toolFailureCounts,snapshot:MX})),EX){let x=vs({inputMessages:s,messages:j,reason:`tool call budget exhausted (${P}) before completing all required files`});if(x){yield*Z(x,{forcedStop:!0});return}}Yn=Cp(Yn,{replayMessages:j,completedToolCallIds:[...Yn.completedToolCallIds,...qt],lastStopReason:"tool_calls"}),t.toolChoice==="required"&&mr.length>0&&(Re=!0);let DX=mr.length>0&&mr.every(x=>{let T=j.find(K=>K?.role==="tool"&&K?.tool_call_id===x.id);if(!T)return!0;let q=T.content;return typeof q=="string"&&q.startsWith("Error: ")}),ls=R.consecutiveFailedRounds;if(DX){if(ls+=1,ls>=Ib){if(E>=3&&R.repeatedToolFailureRecoveryCount<1){let K=qk({inputMessages:s,messages:j,finalText:R.finalText,thinkingBlocks:[],stopHookActive:R.stopHookActive,totalToolCallCount:$,distinctToolNames:_,log:r});if(K?.reason==="explicit_required_file_verification"||K?.reason==="explicit_extra_file_verification"){yield we("repeated_tool_failure_artifact_recovery","one recovery nudge before ending a complex explicit artifact turn after repeated tool failures"),R={...R,messages:K.messages,stopHookActive:K.stopHookActive,transition:K.transition,consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:R.repeatedToolFailureRecoveryCount+1};continue}}if(R.repeatedToolFailureRecoveryCount<1){let K=xD(j);if(K){yield we("repeated_tool_failure_self_correction","one help-guided self-correction round before ending on repeated tool failures"),R={...R,messages:[...j,K],consecutiveFailedRounds:0,repeatedToolFailureRecoveryCount:R.repeatedToolFailureRecoveryCount+1};continue}}let x=`repeated tool failures (${ls} rounds in a row)`,T=vs({inputMessages:s,messages:j,reason:`${x} before all required files were produced`})??(R.finalText.trim()?R.finalText:Nk(j,ls)),q=p0(T,{availableToolNames:Y(a??c),enabledToolNames:gt(),toolCallNames:[..._].sort(),blockedToolCalls:Wp(k)});r.info(`early exit: ${ls} consecutive failed rounds, returning ${R.finalText?"partial":"fallback"} response`),yield*Z(q,{forcedStop:!0});return}}else ls=0;let wp=[...R.fileReadCycleBlockedPaths].filter(x=>!R.fileReadCycleNudgedPaths.has(x));if(wp.length>0){let x=wp.join(", "),T=[...new Set(wp.map(Vk))].join(" ");r.info(`AP5: file read cycle detected on ${x}, injecting nudge`);let q={role:"user",content:`Read-cycle guard blocked repeated reads for: ${x}. ${T} Stop reading these source files this turn; summarize from maintained evidence and explain any remaining uncertainty.`};j.push(q);for(let K of wp)R.fileReadCycleNudgedPaths.add(K)}let va=Nr+1;if(h>0&&va>h){if(r.info(`max turns reached (${h}), completing`),m){let q=await m.invoke("stop",{sessionId:i,reason:"max_turns"});if(q.action==="abort"){let K=q.reason??"Stop hook requested continuation after max_turns",N={role:"assistant",content:R.finalText,...fo.length>0&&{thinkingBlocks:[...fo]}};R={...R,messages:[...j,N,{role:"user",content:K}],stopHookActive:!0,transition:{reason:"stop_hook_blocking"}};continue}}let x=vs({inputMessages:s,messages:j,reason:`tool loop max turns reached (${h}) before completing all required files`});if(x){yield*Z(x,{forcedStop:!0});return}let T=dp(j,`tool loop max turns reached (${h}) before completing the final status contract`);yield*Z(T);return}if(C&&oi(R).size>0&&va>S&&S<100&&(S=Math.min(100,va+25),r.info(`background task lifecycle wait extended round budget to ${S}`)),C&&va>S){let x=jk({currentToolBudget:P,currentRoundBudget:S,toolHardCap:100,roundHardCap:100,continuationCount:le,successfulSinceLastCheck:X-ct,fileReadCounts:R.fileReadCounts,windowTools:ho,windowRounds:25});x&&(S=x.nextRoundBudget,P=x.nextToolBudget,le=x.continuationCount,ct=X,r.info(`round budget continuation #${x.continuationCount}: rounds\u2192${S}, tools\u2192${P} (progress detected)`))}if(va>S){r.info(`tool loop budget exhausted (${S} rounds), returning`);let x=Wk({totalToolCallCount:$,distinctToolNames:_,projectRoot:t.projectRoot});x&&(yield{type:"skill_instruction",turnId:o,instruction:x});let T=vs({inputMessages:s,messages:j,reason:`tool budget exhausted (${S} rounds) before completing all required files`});if(T){yield*Z(T,{forcedStop:!0});return}let q=dp(j,`tool budget exhausted (${S} rounds) before completing the final status contract`);yield*Z(q);return}R={messages:j,maxOutputTokensRecoveryCount:0,hasAttemptedReactiveCompact:!1,maxOutputTokensOverride:void 0,turnCount:va,transition:{reason:"next_turn"},guardState:ht,reactiveCompactState:Xn,toolLoopState:Yn,consecutiveFailedRounds:ls,finalText:R.finalText,totalUsage:R.totalUsage,collapseStore:ob,currentModel:R.currentModel,consecutive529Errors:0,consecutiveApiRetries:0,stopHookActive:R.stopHookActive,lastResponseId:R.lastResponseId,snipRemovedIds:R.snipRemovedIds,contentReplacementState:R.contentReplacementState,budgetContinuationCount:R.budgetContinuationCount,repeatedToolFailureRecoveryCount:R.repeatedToolFailureRecoveryCount,lastBudgetDeltaTokens:R.lastBudgetDeltaTokens,lastBudgetGlobalTokens:R.lastBudgetGlobalTokens,identicalCallCounts:fp,identicalSuccessfulToolResults:R.identicalSuccessfulToolResults,artifactContract:R.artifactContract,toolFailureCounts:R.toolFailureCounts,fileReadCounts:R.fileReadCounts,fileReadCycleBlockedPaths:R.fileReadCycleBlockedPaths,fileReadCycleNudgedPaths:R.fileReadCycleNudgedPaths,maintainedDocuments:R.maintainedDocuments,persistedBenchmarkStateRecovered:R.persistedBenchmarkStateRecovered,benchmarkStateMaintenanceRequiredFiles:R.benchmarkStateMaintenanceRequiredFiles,benchmarkStateMaintenanceWrittenFiles:R.benchmarkStateMaintenanceWrittenFiles,recoveryTrace:R.recoveryTrace,browserAcceptanceRecoveryCount:R.browserAcceptanceRecoveryCount,buildVerificationRecoveryCount:R.buildVerificationRecoveryCount,benchmarkStateIntegrityRecoveryCount:R.benchmarkStateIntegrityRecoveryCount,backgroundAgentTaskIds:oi(R),backgroundAgentNoOutputPollCounts:R.backgroundAgentNoOutputPollCounts,stalledBackgroundAgentTasks:R.stalledBackgroundAgentTasks,notOfferedToolRecoveryCount:R.notOfferedToolRecoveryCount,existingFileUpdateRecoveryCount:R.existingFileUpdateRecoveryCount,taskListReconciliationCount:R.taskListReconciliationCount,lastTaskList:R.lastTaskList}}}var uee=["\u63A5\u5355\u91D1\u989D","\u5408\u540C\u91D1\u989D","\u62A5\u4EF7","\u9884\u7B97","\u91D1\u989D","price","amount","contract amount"];function C0(t){let e=pee(t),n=["[Recalled memories]","- L1 project MD is project-scoped working memory.","- L2 long-term memory is cross-project canonical memory.","- If L1 and L2 conflict on the same entity/fact, do not silently merge or choose. Surface the conflict and ask the user to confirm. For current-project operational tasks, use L1 only as a project-scoped clue until confirmed into L2."];if(e.length>0){n.push("[Memory conflict detected]");for(let r of e)n.push(`- entity: ${r.entity}; fact: ${r.predicate}; L1 project MD says: ${_0(r.l1Amount)}; L2 long-term says: ${_0(r.l2Amount)}; action: ask the user which value is current before using it.`)}for(let r of t){let o=gee(r);n.push(`- [${o}] ${r.text}`)}return n.join(`
|
|
463
463
|
`)}function pee(t){let e=t.filter(o=>o.source==="l1-project-md").flatMap(o=>I0(o.text)),n=t.filter(o=>o.source==="l2-long-term").flatMap(o=>I0(o.text)),r=[];for(let o of e)for(let i of n)o.entity===i.entity&&o.predicate===i.predicate&&o.amount!==i.amount&&r.push({entity:o.entity,predicate:o.predicate,l1Amount:o.amount,l2Amount:i.amount,l1Text:o.text,l2Text:i.text});return hee(r)}function I0(t){let e=[];for(let n of t.split(/\r?\n/)){let r=n.trim();if(r)for(let o of uee){if(o==="\u91D1\u989D"&&/(接单金额|合同金额)/u.test(r))continue;let i=new RegExp(`${yee(o)}[^0-9.\u4E07kK,]{0,12}([0-9][0-9.,]*\\s*(?:\u4E07|k|K)?)`,"gi");for(let s of r.matchAll(i)){let a=fee(s[1]);a!==null&&e.push({entity:mee(r,o),predicate:o,amount:a,text:r})}}}return e}function mee(t,e){if(/Galaxy\s+Tech/i.test(t))return"Galaxy Tech";if(t.includes("\u7528\u6237"))return"\u7528\u6237";let n=t.toLowerCase().indexOf(e.toLowerCase()),o=(n>=0?t.slice(0,n):"").replace(/[#*`:\-,。;;,.]/g," ").trim().split(/\s+/).filter(Boolean);return o[o.length-1]??"unknown"}function fee(t){let e=t.replace(/,/g,"").replace(/\s+/g,"").trim(),n=e.endsWith("\u4E07")?1e4:/k$/i.test(e)?1e3:1,r=Number(e.replace(/[万kK]$/u,""));return Number.isFinite(r)?r*n:null}function gee(t){if(t.label)return t.label;switch(t.source){case"l1-project-md":return"L1 project MD";case"l2-long-term":return"L2 long-term";case"skill":return"Skill";case"system":return"System";default:return"Memory"}}function _0(t){return Number.isInteger(t)?String(t):String(Number(t.toFixed(4)))}function hee(t){let e=new Set;return t.filter(n=>{let r=`${n.entity}\0${n.predicate}\0${n.l1Amount}\0${n.l2Amount}`;return e.has(r)?!1:(e.add(r),!0)})}function yee(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var vee=8192;async function E0(t){let{hooks:e,detectRecallCategories:n,log:r,sessionId:o,turnId:i,query:s}=t;try{let a=n(s),l=(await e.invoke("memory.before_recall",{sessionId:o,turnId:i,query:s,preferredCategories:a.preferred.length>0?a.preferred:void 0,deprioritizedCategories:a.deprioritized.length>0?a.deprioritized:void 0}))?.context?.recalledMemories,d=null;if(l&&l.length>0){let p=0,m=[];for(let f of l){let g=(f.text?.length??0)*2;if(p+g>vee)break;m.push(f),p+=g}m.length>0&&(d=`[Recalled memories \u2014 context priority: project-specific facts override general user preferences when they conflict]
|
|
464
464
|
${C0(m)}`)}return dt(e,"memory.after_recall",{sessionId:o,turnId:i,blockCount:l?.length??0},r),d}catch{return null}}var ws=class{transport;apiKey;toolInvoker;log;hooks;maxRounds;configuredMaxRounds;projectRoot;runtimePorts;constructor(e){this.transport=e.llmTransport,this.apiKey=e.apiKey,this.toolInvoker=e.toolInvoker,this.log=e.log,this.hooks=e.hooks,this.projectRoot=e.projectRoot,this.runtimePorts=e.runtimePorts,this.configuredMaxRounds=typeof e.maxRounds=="number"&&Number.isFinite(e.maxRounds)?Math.min(e.maxRounds,100):void 0,this.maxRounds=Math.min(this.configuredMaxRounds??25,100)}async*run(e,n){let{turnId:r,messages:o,availableTools:i,tools:s,systemPrompt:a,config:c}=e,l={sessionId:e.sessionId,turnId:r};yield{type:"start",turnId:r},dt(this.hooks,"turn.submitted",{...l,prompt:o[o.length-1]?.content??void 0},this.log);let d=uk(o),p=[];if(a&&p.push({role:"system",content:a}),p.push(...d),this.hooks){let h=d.filter(b=>b.role==="user").pop(),y=typeof h?.content=="string"?h.content.slice(0,500):void 0;if(y){let b=await E0({hooks:this.hooks,detectRecallCategories:v=>this.runtimePorts.detectRecallCategories(v),log:this.log,sessionId:e.sessionId,turnId:r,query:y});b&&p.splice(a?1:0,0,{role:"system",content:b})}}let m=c?.model??"",f=typeof c?.maxRounds=="number"&&Number.isFinite(c.maxRounds)?c.maxRounds:this.configuredMaxRounds,g=f===void 0?void 0:Math.min(f,100);try{let h=c?.reasoning;c?.reasoning?.effort==="auto"&&(h={...c?.reasoning,effort:"medium"});let y={turnId:r,sessionId:e.sessionId,messages:p,availableTools:i,tools:s,refreshTools:e.refreshTools,model:m,apiKey:c?.apiKey??this.apiKey,temperature:c?.temperature,maxRounds:g,contextWindowTokens:c?.contextWindowTokens,maxOutputTokens:c?.maxOutputTokens,modelMaxOutputTokens:c?.modelMaxOutputTokens,toolChoice:c?.toolChoice,parentDepth:c?.parentDepth,hooks:this.hooks,fallbackModel:c?.fallbackModel,maxTurns:c?.maxTurns,tokenBudget:c?.tokenBudget,maxConcurrentTools:c?.maxConcurrentTools,streamRequired:c?.streamRequired,reasoning:h,promptCacheKey:c?.promptCacheKey,promptCacheRetention:c?.promptCacheRetention,serviceTier:c?.serviceTier,openaiBuiltinTools:c?.openaiBuiltinTools,maxToolCalls:c?.maxToolCalls,parallelToolCalls:c?.parallelToolCalls,textVerbosity:c?.textVerbosity,projectRoot:this.projectRoot,runtimePorts:this.runtimePorts.toolLoop,signal:n},b;for await(let v of P0(y,this.transport,this.toolInvoker,this.log))b=v,yield v;b?.type==="end"?dt(this.hooks,"turn.completed",{...l},this.log):b?.type==="error"&&dt(this.hooks,"turn.failed",{...l,code:b.code,error:b.error},this.log)}catch(h){if(n?.aborted)dt(this.hooks,"turn.failed",{...l,code:"ABORTED",error:"Turn aborted"},this.log),yield{type:"error",turnId:r,error:"Turn aborted",code:"ABORTED"};else{let y=h instanceof Error?h.message:String(h),b=typeof h?.status=="number"?h.status:void 0,v=ba(b,y);this.log.error(`turn ${r} error [${v}, retryable=${vb(v)}]: ${y}`),dt(this.hooks,"turn.failed",{...l,code:v,error:y},this.log),yield{type:"error",turnId:r,error:y,code:v}}}}};function bee(t){let e={verbose:!1};for(let n of t.slice(2))(n==="--verbose"||n==="-v")&&(e.verbose=!0);return e}import{createInterface as kee}from"node:readline";var $l=class{messageHandler=null;closeHandler=null;verbose;constructor(e){this.verbose=e?.verbose??!1}onMessage(e){this.messageHandler=e}onClose(e){this.closeHandler=e}send(e){process.stdout.write(`${JSON.stringify(e)}
|
|
465
|
-
`)}start(){process.stdin.on("data",
|
|
466
|
-
`)});let
|
|
467
|
-
`);try{let
|
|
468
|
-
`)}}}),
|
|
465
|
+
`)}start(){let e=process.env.XIAOZHICLAW_TRANSPORT_DEBUG==="1";e&&process.stdin.on("data",r=>{process.stderr.write(`[transport] raw stdin data (${r.length} bytes): ${r.toString().slice(0,300)}
|
|
466
|
+
`)});let n=kee({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});n.on("line",r=>{let o=r.trim();if(o){e&&process.stderr.write(`[transport] line: ${o.slice(0,300)}
|
|
467
|
+
`);try{let i=JSON.parse(o);this.messageHandler?.(i)}catch{process.stderr.write(`[transport] invalid JSON on stdin: ${o.slice(0,200)}
|
|
468
|
+
`)}}}),n.on("close",()=>{this.closeHandler?.()})}close(){}log(e){this.verbose&&process.stderr.write(`[transport] ${e}
|
|
469
469
|
`)}};import{createRequire as GMe}from"node:module";si();import*as sm from"node:fs";import*as A$ from"node:path";Ke();import*as v$ from"node:fs";import*as Ll from"node:path";var Aw="transcript.jsonl",xo="metadata.json";function gte(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}function Rs(t){return ee().getProjectSessionDataRoot(t)}function Fr(t,e){return Ll.join(Rs(e),gte(t))}function Pw(t,e){return Ll.join(Fr(t,e),xo)}function om(t,e){return Ll.join(Fr(t,e),Aw)}function Iw(t,e){let n=Fr(t,e);if(v$.existsSync(Ll.join(n,xo)))return n}import*as Ro from"node:fs";import*as Ul from"node:path";var b$=".deleted";function _w(t,e){return Ul.join(Rs(e),b$,encodeURIComponent(t)+".json")}async function k$(t,e){let n=_w(t,e);await Ro.promises.mkdir(Ul.dirname(n),{recursive:!0}),await Ro.promises.writeFile(n,JSON.stringify({sessionId:t,deletedAt:new Date().toISOString()},null,2),"utf8")}async function Fl(t,e){try{return await Ro.promises.access(_w(t,e),Ro.constants.F_OK),!0}catch{return!1}}function w$(t,e){return Ro.existsSync(_w(t,e))}async function S$(t){let e=Ul.join(Rs(t),b$),n;try{n=await Ro.promises.readdir(e)}catch{return[]}return n.filter(r=>r.endsWith(".json")).map(r=>{try{return decodeURIComponent(r.slice(0,-5))}catch{return r.slice(0,-5)}})}var Cw=0,x$=[],Hl=new Map;function hte(){return Cw<4?(Cw++,Promise.resolve()):new Promise(t=>x$.push(t))}function yte(){let t=x$.shift();t?t():Cw--}async function im(t){await hte();try{return await t()}finally{yte()}}async function R$(t,e){let n=Hl.get(t)??Promise.resolve(),r,o=new Promise(s=>{r=s}),i=n.catch(()=>{}).then(()=>o);Hl.set(t,i),await n.catch(()=>{});try{return await e()}finally{r(),Hl.get(t)===i&&Hl.delete(t)}}async function T$(t){for(;;){let e=Hl.get(t);if(!e)return;await e.catch(()=>{})}}function P$(t,e){return`${e}\0${t}`}async function hr(t,e,n,r,o){let i=P$(t,n);return R$(i,async()=>{if(await Fl(t,n))return!1;let s=Fr(t,n);try{return await sm.promises.mkdir(s,{recursive:!0}),await sm.promises.appendFile(A$.join(s,Aw),JSON.stringify(vte(e,r,o))+`
|
|
470
470
|
`,"utf8"),!0}catch(a){return console.error(`[session-persistence] appendMessage failed for ${t}: ${a.message}`),!1}})}async function _a(t,e){await T$(P$(t,e));let n=await Ew(t,e);return n?n.messages.length:null}async function Ew(t,e,n={}){let r;try{r=await sm.promises.readFile(om(t,e),"utf8")}catch{return null}let o=[],i=0;for(let s of r.split(`
|
|
471
471
|
`))if(s.trim())try{o.push(bte(JSON.parse(s),n))}catch{i++}return{messages:o,corruptLines:i}}function vte(t,e,n){let r={role:t.role,content:t.content,ts:Date.now()};return e&&(r.turnId=e),n?.usage&&(r.usage=n.usage),n?.displayMetadata&&(r.displayMetadata=n.displayMetadata),t.tool_calls&&(r.tool_calls=t.tool_calls),t.tool_call_id&&(r.tool_call_id=t.tool_call_id),t.name&&(r.name=t.name),t.thinkingBlocks&&(r.thinkingBlocks=t.thinkingBlocks),t.imageUrls&&(r.imageUrls=t.imageUrls),t.videoUrls&&(r.videoUrls=t.videoUrls),t.audioUrls&&(r.audioUrls=t.audioUrls),t.fileIds&&(r.fileIds=t.fileIds),t.imageDetail&&(r.imageDetail=t.imageDetail),t.blocks&&(r.blocks=t.blocks),t.attachmentEntries&&(r.attachmentEntries=t.attachmentEntries),r}function bte(t,e){let n={role:t.role,content:t.content??null};return t.tool_calls&&(n.tool_calls=t.tool_calls),t.tool_call_id&&(n.tool_call_id=t.tool_call_id),t.name&&(n.name=t.name),t.thinkingBlocks&&(n.thinkingBlocks=t.thinkingBlocks),t.imageUrls&&(n.imageUrls=t.imageUrls),t.videoUrls&&(n.videoUrls=t.videoUrls),t.audioUrls&&(n.audioUrls=t.audioUrls),t.fileIds&&(n.fileIds=t.fileIds),t.imageDetail&&(n.imageDetail=t.imageDetail),t.blocks&&(n.blocks=t.blocks),t.attachmentEntries&&(n.attachmentEntries=t.attachmentEntries),e.includeDisplayMetadata&&(t.turnId&&(n.turnId=t.turnId),t.usage&&(n.usage=t.usage),t.displayMetadata&&typeof t.displayMetadata=="object"&&(n.displayMetadata=t.displayMetadata),typeof t.ts=="number"&&(n.timestamp=new Date(t.ts).toISOString())),n}import*as Ut from"node:fs";import*as Ts from"node:path";function To(t,e,n={}){let r=new Date().toISOString();return{schemaVersion:1,sessionId:e?.sessionId??t,projectId:e?.projectId??n.projectId??"",createdAt:e?.createdAt??n.createdAt??r,lastActiveAt:e?.lastActiveAt??n.lastActiveAt??r,model:e?.model,agentId:e?.agentId,cwd:e?.cwd,turnCount:e?.turnCount??n.turnCount??0,messageCount:e?.messageCount??n.messageCount??0,title:e?.title,taskSummary:e?.taskSummary,taskSummaryGeneratedAt:e?.taskSummaryGeneratedAt,pinnedAt:e?.pinnedAt,archivedAt:e?.archivedAt,sealedAt:e?.sealedAt,previousSessionId:e?.previousSessionId,carryoverSummary:e?.carryoverSummary,type:e?.type??"personal",ownerPlatform:e?.ownerPlatform,ownerId:e?.ownerId,groupKey:e?.groupKey,groupName:e?.groupName,groupPlatform:e?.groupPlatform,totalInputTokens:e?.totalInputTokens,totalOutputTokens:e?.totalOutputTokens}}function Dw(t){return t?.schemaVersion!==1||t.type==null}async function am(t,e){let n=t+".tmp";await Ut.promises.writeFile(n,JSON.stringify(e,null,2),"utf8"),await Ut.promises.rename(n,t)}function kte(t,e){let n=t+".tmp";Ut.writeFileSync(n,JSON.stringify(e,null,2),"utf8"),Ut.renameSync(n,t)}function Vt(t,e){let n=Iw(t,e);if(!n)return null;let r=Ts.join(n,xo);try{let o=Ut.readFileSync(r,"utf8"),i=JSON.parse(o),s=To(t,i);return Dw(i)&&kte(r,s),s}catch{return null}}async function cm(t,e,n={}){let r=Pw(t,e),o=null;try{o=JSON.parse(await Ut.promises.readFile(r,"utf8"))}catch{o=null}let i=To(t,o,n);return(!o||Dw(o))&&(await Ut.promises.mkdir(Ts.dirname(r),{recursive:!0}),await am(r,i)),i}async function $w(t,e,n,r){await im(async()=>{if(await Fl(t,r))return;let o=Fr(t,r);await Ut.promises.mkdir(o,{recursive:!0});let i={};try{let l=await Ut.promises.readFile(Ts.join(o,xo),"utf8");i=JSON.parse(l)}catch{i={}}let s=await _a(t,r),a=new Date().toISOString(),c=To(t,{sessionId:t,projectId:n.projectId??i.projectId??"",createdAt:n.createdAt??i.createdAt??a,lastActiveAt:a,model:n.model??i.model,agentId:n.agentId??i.agentId,cwd:n.cwd??i.cwd,turnCount:e.turnCount,messageCount:s??n.messageCount??i.messageCount??0,title:n.title??i.title,taskSummary:n.taskSummary??i.taskSummary,taskSummaryGeneratedAt:n.taskSummaryGeneratedAt??i.taskSummaryGeneratedAt,pinnedAt:n.pinnedAt!==void 0?n.pinnedAt:i.pinnedAt,archivedAt:n.archivedAt!==void 0?n.archivedAt:i.archivedAt,sealedAt:n.sealedAt??i.sealedAt,previousSessionId:n.previousSessionId??i.previousSessionId,carryoverSummary:n.carryoverSummary??i.carryoverSummary,type:n.type??i.type,ownerPlatform:n.ownerPlatform??i.ownerPlatform,ownerId:n.ownerId??i.ownerId,groupKey:n.groupKey??i.groupKey,groupName:n.groupName??i.groupName,groupPlatform:n.groupPlatform??i.groupPlatform,totalInputTokens:e.totalInputTokens,totalOutputTokens:e.totalOutputTokens});await am(Ts.join(o,xo),c)})}async function yt(t,e,n){return im(async()=>{if(await Fl(t,n))return null;let o=Iw(t,n)??Fr(t,n),i=Ts.join(o,xo),s=new Date().toISOString(),a;try{let l=await Ut.promises.readFile(i,"utf8");a=To(t,JSON.parse(l))}catch{await Ut.promises.mkdir(o,{recursive:!0}),a=To(t,{projectId:e.projectId??"",createdAt:s,lastActiveAt:s,turnCount:0,messageCount:0})}let c=wte(a,e);return c.lastActiveAt=s,await Ut.promises.mkdir(o,{recursive:!0}),await am(i,c),c})}async function I$(t,e,n,r){await im(async()=>{let o=await cm(t,e);await am(Pw(t,e),{...o,taskSummary:n,taskSummaryGeneratedAt:r})})}function wte(t,e){let n={...t};for(let[r,o]of Object.entries(e))o!==void 0&&(o===null?delete n[r]:n[r]=o);return To(String(n.sessionId??t.sessionId),n)}import*as lm from"node:fs";async function Hr(t,e,n={}){try{await lm.promises.access(e,lm.constants.R_OK)}catch{return console.error(`[session-persistence] loadSessionForResume: projectRoot not accessible: ${e}`),null}let r=await Ew(t,e,n);return r?(r.corruptLines>0&&console.warn(`[session-persistence] ${r.corruptLines} corrupt line(s) skipped in ${om(t,e)}`),r.messages.length===0&&r.corruptLines>0?(console.error(`[session-persistence] Transcript fully corrupt for session ${t}`),null):{metadata:await cm(t,e,{messageCount:r.messages.length}),messages:Ste(r.messages,n.includeDisplayMetadata===!0)}):null}function Ste(t,e){return t.filter(n=>n.role!=="system").map(n=>e?n:xte(n))}function xte(t){let e={role:t.role,content:t.content};return t.tool_calls&&(e.tool_calls=t.tool_calls),t.tool_call_id&&(e.tool_call_id=t.tool_call_id),t.name&&(e.name=t.name),t.thinkingBlocks&&(e.thinkingBlocks=t.thinkingBlocks),t.imageUrls&&(e.imageUrls=t.imageUrls),t.videoUrls&&(e.videoUrls=t.videoUrls),t.audioUrls&&(e.audioUrls=t.audioUrls),t.fileIds&&(e.fileIds=t.fileIds),t.imageDetail&&(e.imageDetail=t.imageDetail),e}jt();import*as Ca from"node:fs";import*as _$ from"node:path";cn();async function ln(t=Gb,e){let n;try{n=await Ca.promises.readdir(Rs(e))}catch{return[]}let r=[];for(let o of n){let i=_$.join(Rs(e),o,xo);try{let s=await Ca.promises.readFile(i,"utf8"),a=To(o,JSON.parse(s)),c=await _a(o,e);r.push(Rte({...a,messageCount:c??a.messageCount}))}catch{}}return r.sort((o,i)=>o.lastActiveAt>i.lastActiveAt?-1:o.lastActiveAt<i.lastActiveAt?1:0),r.slice(0,t)}async function dm(t,e){await k$(t,e),await Promise.all([Ca.promises.rm(Fr(t,e),{recursive:!0,force:!0}),Ca.promises.rm(nm(e,t),{recursive:!0,force:!0}),Ca.promises.rm(rm(e,t),{recursive:!0,force:!0})])}function Rte(t){return{sessionId:t.sessionId,title:t.title,lastActiveAt:t.lastActiveAt,messageCount:t.messageCount,model:t.model,agentId:t.agentId,pinnedAt:t.pinnedAt,archivedAt:t.archivedAt,sealedAt:t.sealedAt,projectId:t.projectId,type:t.type??"personal",createdAt:t.createdAt,groupKey:t.groupKey,previousSessionId:t.previousSessionId,carryoverSummary:t.carryoverSummary??null}}jt();var Tte=/[\u951f\ufffd]|[\uFFFD]|\u9225|\u20ac|\u9366|\u93b4|\u9428|\u7487|\u95b8|\u7ed7|\u710b|\u890e|\u5a4a|\u72b3|\u5f84|\u9368|\u7b91|\u6fb6\u682d|\u5134|\u6d7c\u6c33|\u763d/,Ate=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/;function Pte(t){return Tte.test(t)||Ate.test(t)}function zl(t,e={}){let n=e.maxLength??40,r=t?.replace(/\s+/g," ").trim();if(r&&!Pte(r))return r.slice(0,n)}function Bl(t,e,n={}){let r=n.maxLength??40,o=n.ellipsis??"...",i=zl(t,{maxLength:r});return i?t.replace(/\s+/g," ").trim().length>r?`${i}${o}`:i:e}function C$(t){let e=t.replace(/\s+/g," ").trim().toLowerCase();return e&&(e.includes("reply with exactly")||e.includes("exactly this single line")||e.includes("nothing else")||e.includes("only reply")||e.includes("\u53EA\u56DE\u590D")||e.includes("\u4E0D\u8981\u89E3\u91CA"))?"Exact reply":null}var Ite="Based on the user's message below, generate a very short session title (2-8 Chinese characters or 3-6 English words). The title should capture the main topic or intent. Reply with ONLY the title text, no quotes, no punctuation.";function E$(t){return t.turnCount<Kb?!1:t.taskSummaryGeneratedAt?t.turnCount-(t.taskSummaryGeneratedAt??0)>=Vb:!0}async function Nw(t,e){if(!t.trim())return null;let n=C$(t);if(n)return n;try{let r=e.transport.stream({model:e.model,messages:[{role:"system",content:Ite},{role:"user",content:t.slice(0,500)}],tools:[],maxTokens:30},e.apiKey),o="";for await(let i of r)i.type==="delta"&&(o+=i.text);return o=o.trim().replace(/^["'""'']+|["'""'']+$/g,""),zl(o,{maxLength:40})??null}catch{return null}}async function Ow(t,e,n,r,o){if(!E$(e))return null;try{let s=n.slice(-20).map(l=>`[${l.role}]: ${typeof l.content=="string"?l.content.slice(0,500):JSON.stringify(l.content).slice(0,500)}`).join(`
|
|
@@ -683,7 +683,7 @@ ${e}
|
|
|
683
683
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){i(s);continue}if(t.external){let l=t.external.registry.get(s[0])?.id;if(e!==s[0]&&l){i(s);continue}}if(t.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1&&t.reused==="ref"){i(s);continue}}}function xi(t,e){let n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");let r=a=>{let c=t.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,d={...l},p=c.ref;if(c.ref=null,p){r(p);let f=t.seen.get(p),g=f.schema;if(g.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(g)):Object.assign(l,g),Object.assign(l,d),a._zod.parent===p)for(let y in l)y==="$ref"||y==="allOf"||y in d||delete l[y];if(g.$ref&&f.def)for(let y in l)y==="$ref"||y==="allOf"||y in f.def&&JSON.stringify(l[y])===JSON.stringify(f.def[y])&&delete l[y]}let m=a._zod.parent;if(m&&m!==p){r(m);let f=t.seen.get(m);if(f?.schema.$ref&&(l.$ref=f.schema.$ref,f.def))for(let g in l)g==="$ref"||g==="allOf"||g in f.def&&JSON.stringify(l[g])===JSON.stringify(f.def[g])&&delete l[g]}t.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())r(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,n.def??n.schema);let i=t.metadataRegistry.get(e)?.id;i!==void 0&&o.id===i&&delete o.id;let s=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,s[c.defId]=c.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:nc(e,"input",t.processors),output:nc(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Yt(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Yt(r.element,n);if(r.type==="set")return Yt(r.valueType,n);if(r.type==="lazy")return Yt(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Yt(r.innerType,n);if(r.type==="intersection")return Yt(r.left,n)||Yt(r.right,n);if(r.type==="record"||r.type==="map")return Yt(r.keyType,n)||Yt(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Yt(r.in,n)||Yt(r.out,n);if(r.type==="object"){for(let o in r.shape)if(Yt(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(Yt(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(Yt(o,n))return!0;return!!(r.rest&&Yt(r.rest,n))}return!1}var hT=(t,e={})=>n=>{let r=wi({...n,processors:e});return Pe(t,r),Si(r,t),xi(r,t)},nc=(t,e,n={})=>r=>{let{libraryOptions:o,target:i}=r??{},s=wi({...o??{},target:i,io:e,processors:n});return Pe(t,s),Si(s,t),xi(s,t)};var use={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},yT=(t,e,n,r)=>{let o=n;o.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:l}=t._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),a&&(o.format=use[a]??a,o.format===""&&delete o.format,a==="time"&&delete o.format),l&&(o.contentEncoding=l),c&&c.size>0){let d=[...c];d.length===1?o.pattern=d[0].source:d.length>1&&(o.allOf=[...d.map(p=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},vT=(t,e,n,r)=>{let o=n,{minimum:i,maximum:s,format:a,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:d}=t._zod.bag;typeof a=="string"&&a.includes("int")?o.type="integer":o.type="number";let p=typeof d=="number"&&d>=(i??Number.NEGATIVE_INFINITY),m=typeof l=="number"&&l<=(s??Number.POSITIVE_INFINITY),f=e.target==="draft-04"||e.target==="openapi-3.0";p?f?(o.minimum=d,o.exclusiveMinimum=!0):o.exclusiveMinimum=d:typeof i=="number"&&(o.minimum=i),m?f?(o.maximum=l,o.exclusiveMaximum=!0):o.exclusiveMaximum=l:typeof s=="number"&&(o.maximum=s),typeof c=="number"&&(o.multipleOf=c)},bT=(t,e,n,r)=>{n.type="boolean"},kT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},wT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},ST=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},xT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},RT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},TT=(t,e,n,r)=>{n.not={}},AT=(t,e,n,r)=>{},PT=(t,e,n,r)=>{},IT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},_T=(t,e,n,r)=>{let o=t._zod.def,i=id(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},CT=(t,e,n,r)=>{let o=t._zod.def,i=[];for(let s of o.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];n.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[s]:n.const=s}else i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),i.every(s=>typeof s=="boolean")&&(n.type="boolean"),i.every(s=>s===null)&&(n.type="null"),n.enum=i},ET=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},MT=(t,e,n,r)=>{let o=n,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},DT=(t,e,n,r)=>{let o=n,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:c}=t._zod.bag;s!==void 0&&(i.minLength=s),a!==void 0&&(i.maxLength=a),c?c.length===1?(i.contentMediaType=c[0],Object.assign(o,i)):(Object.assign(o,i),o.anyOf=c.map(l=>({contentMediaType:l}))):Object.assign(o,i)},$T=(t,e,n,r)=>{n.type="boolean"},NT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},OT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},jT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},LT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},UT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},FT=(t,e,n,r)=>{let o=n,i=t._zod.def,{minimum:s,maximum:a}=t._zod.bag;typeof s=="number"&&(o.minItems=s),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=Pe(i.element,e,{...r,path:[...r.path,"items"]})},HT=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="object",o.properties={};let s=i.shape;for(let l in s)o.properties[l]=Pe(s[l],e,{...r,path:[...r.path,"properties",l]});let a=new Set(Object.keys(s)),c=new Set([...a].filter(l=>{let d=i.shape[l]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));c.size>0&&(o.required=Array.from(c)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=Pe(i.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},Uf=(t,e,n,r)=>{let o=t._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>Pe(a,e,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=s:n.anyOf=s},zT=(t,e,n,r)=>{let o=t._zod.def,i=Pe(o.left,e,{...r,path:[...r.path,"allOf",0]}),s=Pe(o.right,e,{...r,path:[...r.path,"allOf",1]}),a=l=>"allOf"in l&&Object.keys(l).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=c},BT=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((m,f)=>Pe(m,e,{...r,path:[...r.path,s,f]})),l=i.rest?Pe(i.rest,e,{...r,path:[...r.path,a,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null;e.target==="draft-2020-12"?(o.prefixItems=c,l&&(o.items=l)):e.target==="openapi-3.0"?(o.items={anyOf:c},l&&o.items.anyOf.push(l),o.minItems=c.length,l||(o.maxItems=c.length)):(o.items=c,l&&(o.additionalItems=l));let{minimum:d,maximum:p}=t._zod.bag;typeof d=="number"&&(o.minItems=d),typeof p=="number"&&(o.maxItems=p)},qT=(t,e,n,r)=>{let o=n,i=t._zod.def;o.type="object";let s=i.keyType,c=s._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let d=Pe(i.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let p of c)o.patternProperties[p.source]=d}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=Pe(i.keyType,e,{...r,path:[...r.path,"propertyNames"]})),o.additionalProperties=Pe(i.valueType,e,{...r,path:[...r.path,"additionalProperties"]});let l=s._zod.values;if(l){let d=[...l].filter(p=>typeof p=="string"||typeof p=="number");d.length>0&&(o.required=d)}},WT=(t,e,n,r)=>{let o=t._zod.def,i=Pe(o.innerType,e,r),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=o.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},GT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},KT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,n.default=JSON.parse(JSON.stringify(o.defaultValue))},VT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},JT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},ZT=(t,e,n,r)=>{let o=t._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?o.out:o.in:o.out;Pe(s,e,r);let a=e.seen.get(t);a.ref=s},XT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType,n.readOnly=!0},YT=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},Ff=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},QT=(t,e,n,r)=>{let o=t._zod.innerType;Pe(o,e,r);let i=e.seen.get(t);i.ref=o},Lf={string:yT,number:vT,boolean:bT,bigint:kT,symbol:wT,null:ST,undefined:xT,void:RT,never:TT,any:AT,unknown:PT,date:IT,enum:_T,literal:CT,nan:ET,template_literal:MT,file:DT,success:$T,custom:NT,function:OT,transform:jT,map:LT,set:UT,array:FT,object:HT,union:Uf,intersection:zT,tuple:BT,record:qT,nullable:WT,nonoptional:GT,default:KT,prefault:VT,catch:JT,pipe:ZT,readonly:XT,promise:YT,optional:Ff,lazy:QT};function Hf(t,e){if("_idmap"in t){let r=t,o=wi({...e,processors:Lf}),i={};for(let c of r._idmap.entries()){let[l,d]=c;Pe(d,o)}let s={},a={registry:r,uri:e?.uri,defs:i};o.external=a;for(let c of r._idmap.entries()){let[l,d]=c;Si(o,d),s[l]=xi(o,d)}if(Object.keys(i).length>0){let c=o.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:i}}return{schemas:s}}let n=wi({...e,processors:Lf});return Pe(t,n),Si(n,t),xi(n,t)}var zf=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let n=e?.target??"draft-2020-12";n==="draft-4"&&(n="draft-04"),n==="draft-7"&&(n="draft-07"),this.ctx=wi({processors:Lf,target:n,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,n={path:[],schemaPath:[]}){return Pe(e,this.ctx,n)}emit(e,n){n&&(n.cycles&&(this.ctx.cycles=n.cycles),n.reused&&(this.ctx.reused=n.reused),n.external&&(this.ctx.external=n.external)),Si(this.ctx,e);let r=xi(this.ctx,e),{"~standard":o,...i}=r;return i}};var Bj={};var xd={};sn(xd,{ZodAny:()=>xA,ZodArray:()=>PA,ZodBase64:()=>lg,ZodBase64URL:()=>dg,ZodBigInt:()=>dc,ZodBigIntFormat:()=>mg,ZodBoolean:()=>lc,ZodCIDRv4:()=>ag,ZodCIDRv6:()=>cg,ZodCUID:()=>eg,ZodCUID2:()=>tg,ZodCatch:()=>JA,ZodCodec:()=>Nd,ZodCustom:()=>Od,ZodCustomStringFormat:()=>ac,ZodDate:()=>Cd,ZodDefault:()=>BA,ZodDiscriminatedUnion:()=>_A,ZodE164:()=>ug,ZodEmail:()=>Xf,ZodEmoji:()=>Yf,ZodEnum:()=>ic,ZodExactOptional:()=>FA,ZodFile:()=>LA,ZodFunction:()=>iP,ZodGUID:()=>Td,ZodIPv4:()=>ig,ZodIPv6:()=>sg,ZodIntersection:()=>CA,ZodJWT:()=>pg,ZodKSUID:()=>og,ZodLazy:()=>nP,ZodLiteral:()=>jA,ZodMAC:()=>hA,ZodMap:()=>NA,ZodNaN:()=>XA,ZodNanoID:()=>Qf,ZodNever:()=>TA,ZodNonOptional:()=>bg,ZodNull:()=>wA,ZodNullable:()=>zA,ZodNumber:()=>cc,ZodNumberFormat:()=>Fs,ZodObject:()=>Md,ZodOptional:()=>vg,ZodPipe:()=>$d,ZodPrefault:()=>WA,ZodPreprocess:()=>YA,ZodPromise:()=>oP,ZodReadonly:()=>QA,ZodRecord:()=>oc,ZodSet:()=>OA,ZodString:()=>sc,ZodStringFormat:()=>$e,ZodSuccess:()=>VA,ZodSymbol:()=>bA,ZodTemplateLiteral:()=>tP,ZodTransform:()=>UA,ZodTuple:()=>MA,ZodType:()=>ue,ZodULID:()=>ng,ZodURL:()=>_d,ZodUUID:()=>Kr,ZodUndefined:()=>kA,ZodUnion:()=>Dd,ZodUnknown:()=>RA,ZodVoid:()=>AA,ZodXID:()=>rg,ZodXor:()=>IA,_ZodString:()=>Zf,_default:()=>qA,_function:()=>YL,any:()=>_L,array:()=>Ed,base64:()=>pL,base64url:()=>mL,bigint:()=>RL,boolean:()=>vA,catch:()=>ZA,check:()=>QL,cidrv4:()=>dL,cidrv6:()=>uL,codec:()=>VL,cuid:()=>nL,cuid2:()=>rL,custom:()=>eU,date:()=>EL,describe:()=>tU,discriminatedUnion:()=>jL,e164:()=>fL,email:()=>Gj,emoji:()=>eL,enum:()=>hg,exactOptional:()=>HA,file:()=>qL,float32:()=>kL,float64:()=>wL,function:()=>YL,guid:()=>Kj,hash:()=>bL,hex:()=>vL,hostname:()=>yL,httpUrl:()=>Qj,instanceof:()=>rU,int:()=>Vf,int32:()=>SL,int64:()=>TL,intersection:()=>EA,invertCodec:()=>JL,ipv4:()=>aL,ipv6:()=>lL,json:()=>iU,jwt:()=>gL,keyof:()=>ML,ksuid:()=>sL,lazy:()=>rP,literal:()=>BL,looseObject:()=>NL,looseRecord:()=>UL,mac:()=>cL,map:()=>FL,meta:()=>nU,nan:()=>KL,nanoid:()=>tL,nativeEnum:()=>zL,never:()=>fg,nonoptional:()=>KA,null:()=>SA,nullable:()=>Pd,nullish:()=>WL,number:()=>yA,object:()=>DL,optional:()=>Ad,partialRecord:()=>LL,pipe:()=>Jf,prefault:()=>GA,preprocess:()=>sU,promise:()=>XL,readonly:()=>eP,record:()=>$A,refine:()=>sP,set:()=>HL,strictObject:()=>$L,string:()=>Rd,stringFormat:()=>hL,stringbool:()=>oU,success:()=>GL,superRefine:()=>aP,symbol:()=>PL,templateLiteral:()=>ZL,transform:()=>yg,tuple:()=>DA,uint32:()=>xL,uint64:()=>AL,ulid:()=>oL,undefined:()=>IL,union:()=>gg,unknown:()=>Us,url:()=>Yj,uuid:()=>Vj,uuidv4:()=>Jj,uuidv6:()=>Zj,uuidv7:()=>Xj,void:()=>CL,xid:()=>iL,xor:()=>OL});var Bf={};sn(Bf,{endsWith:()=>Va,gt:()=>Wr,gte:()=>Xt,includes:()=>Ga,length:()=>Ls,lowercase:()=>qa,lt:()=>qr,lte:()=>jn,maxLength:()=>js,maxSize:()=>ki,mime:()=>Ja,minLength:()=>_o,minSize:()=>Gr,multipleOf:()=>bi,negative:()=>$f,nonnegative:()=>Of,nonpositive:()=>Nf,normalize:()=>Za,overwrite:()=>br,positive:()=>Df,property:()=>jf,regex:()=>Ba,size:()=>Os,slugify:()=>ec,startsWith:()=>Ka,toLowerCase:()=>Ya,toUpperCase:()=>Qa,trim:()=>Xa,uppercase:()=>Wa});var rc={};sn(rc,{ZodISODate:()=>Wf,ZodISODateTime:()=>qf,ZodISODuration:()=>Kf,ZodISOTime:()=>Gf,date:()=>tA,datetime:()=>eA,duration:()=>rA,time:()=>nA});var qf=I("ZodISODateTime",(t,e)=>{Ex.init(t,e),$e.init(t,e)});function eA(t){return NR(qf,t)}var Wf=I("ZodISODate",(t,e)=>{Mx.init(t,e),$e.init(t,e)});function tA(t){return OR(Wf,t)}var Gf=I("ZodISOTime",(t,e)=>{Dx.init(t,e),$e.init(t,e)});function nA(t){return jR(Gf,t)}var Kf=I("ZodISODuration",(t,e)=>{$x.init(t,e),$e.init(t,e)});function rA(t){return LR(Kf,t)}var qj=(t,e)=>{dd.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>pd(t,n)},flatten:{value:n=>ud(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,$a,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,$a,2)}},isEmpty:{get(){return t.issues.length===0}}})},mse=I("ZodError",qj),mn=I("ZodError",qj,{Parent:Error});var oA=ja(mn),iA=La(mn),sA=Ua(mn),aA=Fa(mn),cA=Fm(mn),lA=Hm(mn),dA=zm(mn),uA=Bm(mn),pA=qm(mn),mA=Wm(mn),fA=Gm(mn),gA=Km(mn);var Wj=new WeakMap;function Id(t,e,n){let r=Object.getPrototypeOf(t),o=Wj.get(r);if(o||(o=new Set,Wj.set(r,o)),!o.has(e)){o.add(e);for(let i in n){let s=n[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}var ue=I("ZodType",(t,e)=>(ie.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:nc(t,"input"),output:nc(t,"output")}}),t.toJSONSchema=hT(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>oA(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>sA(t,n,r),t.parseAsync=async(n,r)=>iA(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>aA(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>cA(t,n,r),t.decode=(n,r)=>lA(t,n,r),t.encodeAsync=async(n,r)=>dA(t,n,r),t.decodeAsync=async(n,r)=>uA(t,n,r),t.safeEncode=(n,r)=>pA(t,n,r),t.safeDecode=(n,r)=>mA(t,n,r),t.safeEncodeAsync=async(n,r)=>fA(t,n,r),t.safeDecodeAsync=async(n,r)=>gA(t,n,r),Id(t,"ZodType",{check(...n){let r=this.def;return this.clone(F.mergeDefs(r,{checks:[...r.checks??[],...n.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Jt(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(sP(n,r))},superRefine(n,r){return this.check(aP(n,r))},overwrite(n){return this.check(br(n))},optional(){return Ad(this)},exactOptional(){return HA(this)},nullable(){return Pd(this)},nullish(){return Ad(Pd(this))},nonoptional(n){return KA(this,n)},array(){return Ed(this)},or(n){return gg([this,n])},and(n){return EA(this,n)},transform(n){return Jf(this,yg(n))},default(n){return qA(this,n)},prefault(n){return GA(this,n)},catch(n){return ZA(this,n)},pipe(n){return Jf(this,n)},readonly(){return eP(this)},describe(n){let r=this.clone();return It.add(r,{description:n}),r},meta(...n){if(n.length===0)return It.get(this);let r=this.clone();return It.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){return It.get(t)?.description},configurable:!0}),t)),Zf=I("_ZodString",(t,e)=>{Ns.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>yT(t,r,o,i);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,Id(t,"_ZodString",{regex(...r){return this.check(Ba(...r))},includes(...r){return this.check(Ga(...r))},startsWith(...r){return this.check(Ka(...r))},endsWith(...r){return this.check(Va(...r))},min(...r){return this.check(_o(...r))},max(...r){return this.check(js(...r))},length(...r){return this.check(Ls(...r))},nonempty(...r){return this.check(_o(1,...r))},lowercase(r){return this.check(qa(r))},uppercase(r){return this.check(Wa(r))},trim(){return this.check(Xa())},normalize(...r){return this.check(Za(...r))},toLowerCase(){return this.check(Ya())},toUpperCase(){return this.check(Qa())},slugify(){return this.check(ec())}})}),sc=I("ZodString",(t,e)=>{Ns.init(t,e),Zf.init(t,e),t.email=n=>t.check(mf(Xf,n)),t.url=n=>t.check(Sd(_d,n)),t.jwt=n=>t.check(Mf(pg,n)),t.emoji=n=>t.check(vf(Yf,n)),t.guid=n=>t.check(wd(Td,n)),t.uuid=n=>t.check(ff(Kr,n)),t.uuidv4=n=>t.check(gf(Kr,n)),t.uuidv6=n=>t.check(hf(Kr,n)),t.uuidv7=n=>t.check(yf(Kr,n)),t.nanoid=n=>t.check(bf(Qf,n)),t.guid=n=>t.check(wd(Td,n)),t.cuid=n=>t.check(kf(eg,n)),t.cuid2=n=>t.check(wf(tg,n)),t.ulid=n=>t.check(Sf(ng,n)),t.base64=n=>t.check(_f(lg,n)),t.base64url=n=>t.check(Cf(dg,n)),t.xid=n=>t.check(xf(rg,n)),t.ksuid=n=>t.check(Rf(og,n)),t.ipv4=n=>t.check(Tf(ig,n)),t.ipv6=n=>t.check(Af(sg,n)),t.cidrv4=n=>t.check(Pf(ag,n)),t.cidrv6=n=>t.check(If(cg,n)),t.e164=n=>t.check(Ef(ug,n)),t.datetime=n=>t.check(eA(n)),t.date=n=>t.check(tA(n)),t.time=n=>t.check(nA(n)),t.duration=n=>t.check(rA(n))});function Rd(t){return ER(sc,t)}var $e=I("ZodStringFormat",(t,e)=>{De.init(t,e),Zf.init(t,e)}),Xf=I("ZodEmail",(t,e)=>{Sx.init(t,e),$e.init(t,e)});function Gj(t){return mf(Xf,t)}var Td=I("ZodGUID",(t,e)=>{kx.init(t,e),$e.init(t,e)});function Kj(t){return wd(Td,t)}var Kr=I("ZodUUID",(t,e)=>{wx.init(t,e),$e.init(t,e)});function Vj(t){return ff(Kr,t)}function Jj(t){return gf(Kr,t)}function Zj(t){return hf(Kr,t)}function Xj(t){return yf(Kr,t)}var _d=I("ZodURL",(t,e)=>{xx.init(t,e),$e.init(t,e)});function Yj(t){return Sd(_d,t)}function Qj(t){return Sd(_d,{protocol:On.httpProtocol,hostname:On.domain,...F.normalizeParams(t)})}var Yf=I("ZodEmoji",(t,e)=>{Rx.init(t,e),$e.init(t,e)});function eL(t){return vf(Yf,t)}var Qf=I("ZodNanoID",(t,e)=>{Tx.init(t,e),$e.init(t,e)});function tL(t){return bf(Qf,t)}var eg=I("ZodCUID",(t,e)=>{Ax.init(t,e),$e.init(t,e)});function nL(t){return kf(eg,t)}var tg=I("ZodCUID2",(t,e)=>{Px.init(t,e),$e.init(t,e)});function rL(t){return wf(tg,t)}var ng=I("ZodULID",(t,e)=>{Ix.init(t,e),$e.init(t,e)});function oL(t){return Sf(ng,t)}var rg=I("ZodXID",(t,e)=>{_x.init(t,e),$e.init(t,e)});function iL(t){return xf(rg,t)}var og=I("ZodKSUID",(t,e)=>{Cx.init(t,e),$e.init(t,e)});function sL(t){return Rf(og,t)}var ig=I("ZodIPv4",(t,e)=>{Nx.init(t,e),$e.init(t,e)});function aL(t){return Tf(ig,t)}var hA=I("ZodMAC",(t,e)=>{jx.init(t,e),$e.init(t,e)});function cL(t){return DR(hA,t)}var sg=I("ZodIPv6",(t,e)=>{Ox.init(t,e),$e.init(t,e)});function lL(t){return Af(sg,t)}var ag=I("ZodCIDRv4",(t,e)=>{Lx.init(t,e),$e.init(t,e)});function dL(t){return Pf(ag,t)}var cg=I("ZodCIDRv6",(t,e)=>{Ux.init(t,e),$e.init(t,e)});function uL(t){return If(cg,t)}var lg=I("ZodBase64",(t,e)=>{Hx.init(t,e),$e.init(t,e)});function pL(t){return _f(lg,t)}var dg=I("ZodBase64URL",(t,e)=>{zx.init(t,e),$e.init(t,e)});function mL(t){return Cf(dg,t)}var ug=I("ZodE164",(t,e)=>{Bx.init(t,e),$e.init(t,e)});function fL(t){return Ef(ug,t)}var pg=I("ZodJWT",(t,e)=>{qx.init(t,e),$e.init(t,e)});function gL(t){return Mf(pg,t)}var ac=I("ZodCustomStringFormat",(t,e)=>{Wx.init(t,e),$e.init(t,e)});function hL(t,e,n={}){return tc(ac,t,e,n)}function yL(t){return tc(ac,"hostname",On.hostname,t)}function vL(t){return tc(ac,"hex",On.hex,t)}function bL(t,e){let n=e?.enc??"hex",r=`${t}_${n}`,o=On[r];if(!o)throw new Error(`Unrecognized hash format: ${r}`);return tc(ac,r,o,e)}var cc=I("ZodNumber",(t,e)=>{nf.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>vT(t,r,o,i),Id(t,"ZodNumber",{gt(r,o){return this.check(Wr(r,o))},gte(r,o){return this.check(Xt(r,o))},min(r,o){return this.check(Xt(r,o))},lt(r,o){return this.check(qr(r,o))},lte(r,o){return this.check(jn(r,o))},max(r,o){return this.check(jn(r,o))},int(r){return this.check(Vf(r))},safe(r){return this.check(Vf(r))},positive(r){return this.check(Wr(0,r))},nonnegative(r){return this.check(Xt(0,r))},negative(r){return this.check(qr(0,r))},nonpositive(r){return this.check(jn(0,r))},multipleOf(r,o){return this.check(bi(r,o))},step(r,o){return this.check(bi(r,o))},finite(){return this}});let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function yA(t){return UR(cc,t)}var Fs=I("ZodNumberFormat",(t,e)=>{Gx.init(t,e),cc.init(t,e)});function Vf(t){return HR(Fs,t)}function kL(t){return zR(Fs,t)}function wL(t){return BR(Fs,t)}function SL(t){return qR(Fs,t)}function xL(t){return WR(Fs,t)}var lc=I("ZodBoolean",(t,e)=>{hd.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>bT(t,n,r,o)});function vA(t){return GR(lc,t)}var dc=I("ZodBigInt",(t,e)=>{rf.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>kT(t,r,o,i),t.gte=(r,o)=>t.check(Xt(r,o)),t.min=(r,o)=>t.check(Xt(r,o)),t.gt=(r,o)=>t.check(Wr(r,o)),t.gte=(r,o)=>t.check(Xt(r,o)),t.min=(r,o)=>t.check(Xt(r,o)),t.lt=(r,o)=>t.check(qr(r,o)),t.lte=(r,o)=>t.check(jn(r,o)),t.max=(r,o)=>t.check(jn(r,o)),t.positive=r=>t.check(Wr(BigInt(0),r)),t.negative=r=>t.check(qr(BigInt(0),r)),t.nonpositive=r=>t.check(jn(BigInt(0),r)),t.nonnegative=r=>t.check(Xt(BigInt(0),r)),t.multipleOf=(r,o)=>t.check(bi(r,o));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});function RL(t){return VR(dc,t)}var mg=I("ZodBigIntFormat",(t,e)=>{Kx.init(t,e),dc.init(t,e)});function TL(t){return ZR(mg,t)}function AL(t){return XR(mg,t)}var bA=I("ZodSymbol",(t,e)=>{Vx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wT(t,n,r,o)});function PL(t){return YR(bA,t)}var kA=I("ZodUndefined",(t,e)=>{Jx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>xT(t,n,r,o)});function IL(t){return QR(kA,t)}var wA=I("ZodNull",(t,e)=>{Zx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ST(t,n,r,o)});function SA(t){return eT(wA,t)}var xA=I("ZodAny",(t,e)=>{Xx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>AT(t,n,r,o)});function _L(){return tT(xA)}var RA=I("ZodUnknown",(t,e)=>{Yx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>PT(t,n,r,o)});function Us(){return nT(RA)}var TA=I("ZodNever",(t,e)=>{Qx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>TT(t,n,r,o)});function fg(t){return rT(TA,t)}var AA=I("ZodVoid",(t,e)=>{eR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>RT(t,n,r,o)});function CL(t){return oT(AA,t)}var Cd=I("ZodDate",(t,e)=>{tR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>IT(t,r,o,i),t.min=(r,o)=>t.check(Xt(r,o)),t.max=(r,o)=>t.check(jn(r,o));let n=t._zod.bag;t.minDate=n.minimum?new Date(n.minimum):null,t.maxDate=n.maximum?new Date(n.maximum):null});function EL(t){return iT(Cd,t)}var PA=I("ZodArray",(t,e)=>{nR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>FT(t,n,r,o),t.element=e.element,Id(t,"ZodArray",{min(n,r){return this.check(_o(n,r))},nonempty(n){return this.check(_o(1,n))},max(n,r){return this.check(js(n,r))},length(n,r){return this.check(Ls(n,r))},unwrap(){return this.element}})});function Ed(t,e){return cT(PA,t,e)}function ML(t){let e=t._zod.def.shape;return hg(Object.keys(e))}var Md=I("ZodObject",(t,e)=>{rR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>HT(t,n,r,o),F.defineLazy(t,"shape",()=>e.shape),Id(t,"ZodObject",{keyof(){return hg(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Us()})},loose(){return this.clone({...this._zod.def,catchall:Us()})},strict(){return this.clone({...this._zod.def,catchall:fg()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return F.extend(this,n)},safeExtend(n){return F.safeExtend(this,n)},merge(n){return F.merge(this,n)},pick(n){return F.pick(this,n)},omit(n){return F.omit(this,n)},partial(...n){return F.partial(vg,this,n[0])},required(...n){return F.required(bg,this,n[0])}})});function DL(t,e){let n={type:"object",shape:t??{},...F.normalizeParams(e)};return new Md(n)}function $L(t,e){return new Md({type:"object",shape:t,catchall:fg(),...F.normalizeParams(e)})}function NL(t,e){return new Md({type:"object",shape:t,catchall:Us(),...F.normalizeParams(e)})}var Dd=I("ZodUnion",(t,e)=>{yd.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Uf(t,n,r,o),t.options=e.options});function gg(t,e){return new Dd({type:"union",options:t,...F.normalizeParams(e)})}var IA=I("ZodXor",(t,e)=>{Dd.init(t,e),oR.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Uf(t,n,r,o),t.options=e.options});function OL(t,e){return new IA({type:"union",options:t,inclusive:!1,...F.normalizeParams(e)})}var _A=I("ZodDiscriminatedUnion",(t,e)=>{Dd.init(t,e),iR.init(t,e)});function jL(t,e,n){return new _A({type:"union",options:e,discriminator:t,...F.normalizeParams(n)})}var CA=I("ZodIntersection",(t,e)=>{sR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>zT(t,n,r,o)});function EA(t,e){return new CA({type:"intersection",left:t,right:e})}var MA=I("ZodTuple",(t,e)=>{of.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>BT(t,n,r,o),t.rest=n=>t.clone({...t._zod.def,rest:n})});function DA(t,e,n){let r=e instanceof ie,o=r?n:e,i=r?e:null;return new MA({type:"tuple",items:t,rest:i,...F.normalizeParams(o)})}var oc=I("ZodRecord",(t,e)=>{aR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function $A(t,e,n){return!e||!e._zod?new oc({type:"record",keyType:Rd(),valueType:t,...F.normalizeParams(e)}):new oc({type:"record",keyType:t,valueType:e,...F.normalizeParams(n)})}function LL(t,e,n){let r=Jt(t);return r._zod.values=void 0,new oc({type:"record",keyType:r,valueType:e,...F.normalizeParams(n)})}function UL(t,e,n){return new oc({type:"record",keyType:t,valueType:e,mode:"loose",...F.normalizeParams(n)})}var NA=I("ZodMap",(t,e)=>{cR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>LT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...n)=>t.check(Gr(...n)),t.nonempty=n=>t.check(Gr(1,n)),t.max=(...n)=>t.check(ki(...n)),t.size=(...n)=>t.check(Os(...n))});function FL(t,e,n){return new NA({type:"map",keyType:t,valueType:e,...F.normalizeParams(n)})}var OA=I("ZodSet",(t,e)=>{lR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>UT(t,n,r,o),t.min=(...n)=>t.check(Gr(...n)),t.nonempty=n=>t.check(Gr(1,n)),t.max=(...n)=>t.check(ki(...n)),t.size=(...n)=>t.check(Os(...n))});function HL(t,e){return new OA({type:"set",valueType:t,...F.normalizeParams(e)})}var ic=I("ZodEnum",(t,e)=>{dR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>_T(t,r,o,i),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let i={};for(let s of r)if(n.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new ic({...e,checks:[],...F.normalizeParams(o),entries:i})},t.exclude=(r,o)=>{let i={...e.entries};for(let s of r)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new ic({...e,checks:[],...F.normalizeParams(o),entries:i})}});function hg(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new ic({type:"enum",entries:n,...F.normalizeParams(e)})}function zL(t,e){return new ic({type:"enum",entries:t,...F.normalizeParams(e)})}var jA=I("ZodLiteral",(t,e)=>{uR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>CT(t,n,r,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function BL(t,e){return new jA({type:"literal",values:Array.isArray(t)?t:[t],...F.normalizeParams(e)})}var LA=I("ZodFile",(t,e)=>{pR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>DT(t,n,r,o),t.min=(n,r)=>t.check(Gr(n,r)),t.max=(n,r)=>t.check(ki(n,r)),t.mime=(n,r)=>t.check(Ja(Array.isArray(n)?n:[n],r))});function qL(t){return lT(LA,t)}var UA=I("ZodTransform",(t,e)=>{mR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>jT(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new fi(t.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(F.issue(i,n.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),n.issues.push(F.issue(s))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=o,n.fallback=!0,n)}});function yg(t){return new UA({type:"transform",transform:t})}var vg=I("ZodOptional",(t,e)=>{sf.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Ff(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Ad(t){return new vg({type:"optional",innerType:t})}var FA=I("ZodExactOptional",(t,e)=>{fR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Ff(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function HA(t){return new FA({type:"optional",innerType:t})}var zA=I("ZodNullable",(t,e)=>{gR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>WT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Pd(t){return new zA({type:"nullable",innerType:t})}function WL(t){return Ad(Pd(t))}var BA=I("ZodDefault",(t,e)=>{hR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>KT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function qA(t,e){return new BA({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var WA=I("ZodPrefault",(t,e)=>{yR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>VT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function GA(t,e){return new WA({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var bg=I("ZodNonOptional",(t,e)=>{vR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>GT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function KA(t,e){return new bg({type:"nonoptional",innerType:t,...F.normalizeParams(e)})}var VA=I("ZodSuccess",(t,e)=>{bR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>$T(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function GL(t){return new VA({type:"success",innerType:t})}var JA=I("ZodCatch",(t,e)=>{kR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>JT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function ZA(t,e){return new JA({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var XA=I("ZodNaN",(t,e)=>{wR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ET(t,n,r,o)});function KL(t){return aT(XA,t)}var $d=I("ZodPipe",(t,e)=>{af.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ZT(t,n,r,o),t.in=e.in,t.out=e.out});function Jf(t,e){return new $d({type:"pipe",in:t,out:e})}var Nd=I("ZodCodec",(t,e)=>{$d.init(t,e),vd.init(t,e)});function VL(t,e,n){return new Nd({type:"pipe",in:t,out:e,transform:n.decode,reverseTransform:n.encode})}function JL(t){let e=t._zod.def;return new Nd({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var YA=I("ZodPreprocess",(t,e)=>{$d.init(t,e),SR.init(t,e)}),QA=I("ZodReadonly",(t,e)=>{xR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>XT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function eP(t){return new QA({type:"readonly",innerType:t})}var tP=I("ZodTemplateLiteral",(t,e)=>{RR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>MT(t,n,r,o)});function ZL(t,e){return new tP({type:"template_literal",parts:t,...F.normalizeParams(e)})}var nP=I("ZodLazy",(t,e)=>{PR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>QT(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function rP(t){return new nP({type:"lazy",getter:t})}var oP=I("ZodPromise",(t,e)=>{AR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>YT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function XL(t){return new oP({type:"promise",innerType:t})}var iP=I("ZodFunction",(t,e)=>{TR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>OT(t,n,r,o)});function YL(t){return new iP({type:"function",input:Array.isArray(t?.input)?DA(t?.input):t?.input??Ed(Us()),output:t?.output??Us()})}var Od=I("ZodCustom",(t,e)=>{IR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>NT(t,n,r,o)});function QL(t){let e=new Le({check:"custom"});return e._zod.check=t,e}function eU(t,e){return dT(Od,t??(()=>!0),e)}function sP(t,e={}){return uT(Od,t,e)}function aP(t,e){return pT(t,e)}var tU=mT,nU=fT;function rU(t,e={}){let n=new Od({type:"custom",check:"custom",fn:r=>r instanceof t,abort:!0,...F.normalizeParams(e)});return n._zod.bag.Class=t,n._zod.check=r=>{r.value instanceof t||r.issues.push({code:"invalid_type",expected:t.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}var oU=(...t)=>gT({Codec:Nd,Boolean:lc,String:sc},...t);function iU(t){let e=rP(()=>gg([Rd(t),yA(),vA(),SA(),Ed(e),$A(Rd(),e)]));return e}function sU(t,e){return new YA({type:"pipe",in:yg(t),out:e})}var gse={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};function hse(t){Ye({customError:t})}function yse(){return Ye().customError}var cP;cP||(cP={});var G={...xd,...Bf,iso:rc},vse=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function bse(t,e){let n=t.$schema;return n==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":n==="http://json-schema.org/draft-07/schema#"?"draft-7":n==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function kse(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let n=t.slice(1).split("/").filter(Boolean);if(n.length===0)return e.rootSchema;let r=e.version==="draft-2020-12"?"$defs":"definitions";if(n[0]===r){let o=n[1];if(!o||!e.defs[o])throw new Error(`Reference not found: ${t}`);return e.defs[o]}throw new Error(`Reference not found: ${t}`)}function aU(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return G.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let o=t.$ref;if(e.refs.has(o))return e.refs.get(o);if(e.processing.has(o))return G.lazy(()=>{if(!e.refs.has(o))throw new Error(`Circular reference not resolved: ${o}`);return e.refs.get(o)});e.processing.add(o);let i=kse(o,e),s=Ft(i,e);return e.refs.set(o,s),e.processing.delete(o),s}if(t.enum!==void 0){let o=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&o.length===1&&o[0]===null)return G.null();if(o.length===0)return G.never();if(o.length===1)return G.literal(o[0]);if(o.every(s=>typeof s=="string"))return G.enum(o);let i=o.map(s=>G.literal(s));return i.length<2?i[0]:G.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return G.literal(t.const);let n=t.type;if(Array.isArray(n)){let o=n.map(i=>{let s={...t,type:i};return aU(s,e)});return o.length===0?G.never():o.length===1?o[0]:G.union(o)}if(!n)return G.any();let r;switch(n){case"string":{let o=G.string();if(t.format){let i=t.format;i==="email"?o=o.check(G.email()):i==="uri"||i==="uri-reference"?o=o.check(G.url()):i==="uuid"||i==="guid"?o=o.check(G.uuid()):i==="date-time"?o=o.check(G.iso.datetime()):i==="date"?o=o.check(G.iso.date()):i==="time"?o=o.check(G.iso.time()):i==="duration"?o=o.check(G.iso.duration()):i==="ipv4"?o=o.check(G.ipv4()):i==="ipv6"?o=o.check(G.ipv6()):i==="mac"?o=o.check(G.mac()):i==="cidr"?o=o.check(G.cidrv4()):i==="cidr-v6"?o=o.check(G.cidrv6()):i==="base64"?o=o.check(G.base64()):i==="base64url"?o=o.check(G.base64url()):i==="e164"?o=o.check(G.e164()):i==="jwt"?o=o.check(G.jwt()):i==="emoji"?o=o.check(G.emoji()):i==="nanoid"?o=o.check(G.nanoid()):i==="cuid"?o=o.check(G.cuid()):i==="cuid2"?o=o.check(G.cuid2()):i==="ulid"?o=o.check(G.ulid()):i==="xid"?o=o.check(G.xid()):i==="ksuid"&&(o=o.check(G.ksuid()))}typeof t.minLength=="number"&&(o=o.min(t.minLength)),typeof t.maxLength=="number"&&(o=o.max(t.maxLength)),t.pattern&&(o=o.regex(new RegExp(t.pattern))),r=o;break}case"number":case"integer":{let o=n==="integer"?G.number().int():G.number();typeof t.minimum=="number"&&(o=o.min(t.minimum)),typeof t.maximum=="number"&&(o=o.max(t.maximum)),typeof t.exclusiveMinimum=="number"?o=o.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(o=o.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?o=o.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(o=o.lt(t.maximum)),typeof t.multipleOf=="number"&&(o=o.multipleOf(t.multipleOf)),r=o;break}case"boolean":{r=G.boolean();break}case"null":{r=G.null();break}case"object":{let o={},i=t.properties||{},s=new Set(t.required||[]);for(let[c,l]of Object.entries(i)){let d=Ft(l,e);o[c]=s.has(c)?d:d.optional()}if(t.propertyNames){let c=Ft(t.propertyNames,e),l=t.additionalProperties&&typeof t.additionalProperties=="object"?Ft(t.additionalProperties,e):G.any();if(Object.keys(o).length===0){r=G.record(c,l);break}let d=G.object(o).passthrough(),p=G.looseRecord(c,l);r=G.intersection(d,p);break}if(t.patternProperties){let c=t.patternProperties,l=Object.keys(c),d=[];for(let m of l){let f=Ft(c[m],e),g=G.string().regex(new RegExp(m));d.push(G.looseRecord(g,f))}let p=[];if(Object.keys(o).length>0&&p.push(G.object(o).passthrough()),p.push(...d),p.length===0)r=G.object({}).passthrough();else if(p.length===1)r=p[0];else{let m=G.intersection(p[0],p[1]);for(let f=2;f<p.length;f++)m=G.intersection(m,p[f]);r=m}break}let a=G.object(o);t.additionalProperties===!1?r=a.strict():typeof t.additionalProperties=="object"?r=a.catchall(Ft(t.additionalProperties,e)):r=a.passthrough();break}case"array":{let o=t.prefixItems,i=t.items;if(o&&Array.isArray(o)){let s=o.map(c=>Ft(c,e)),a=i&&typeof i=="object"&&!Array.isArray(i)?Ft(i,e):void 0;a?r=G.tuple(s).rest(a):r=G.tuple(s),typeof t.minItems=="number"&&(r=r.check(G.minLength(t.minItems))),typeof t.maxItems=="number"&&(r=r.check(G.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=i.map(c=>Ft(c,e)),a=t.additionalItems&&typeof t.additionalItems=="object"?Ft(t.additionalItems,e):void 0;a?r=G.tuple(s).rest(a):r=G.tuple(s),typeof t.minItems=="number"&&(r=r.check(G.minLength(t.minItems))),typeof t.maxItems=="number"&&(r=r.check(G.maxLength(t.maxItems)))}else if(i!==void 0){let s=Ft(i,e),a=G.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),r=a}else r=G.array(G.any());break}default:throw new Error(`Unsupported type: ${n}`)}return r}function Ft(t,e){if(typeof t=="boolean")return t?G.any():G.never();let n=aU(t,e),r=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(l=>Ft(l,e)),c=G.union(a);n=r?G.intersection(n,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(l=>Ft(l,e)),c=G.xor(a);n=r?G.intersection(n,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)n=r?n:G.any();else{let a=r?n:Ft(t.allOf[0],e),c=r?0:1;for(let l=c;l<t.allOf.length;l++)a=G.intersection(a,Ft(t.allOf[l],e));n=a}t.nullable===!0&&e.version==="openapi-3.0"&&(n=G.nullable(n)),t.readOnly===!0&&(n=G.readonly(n)),t.default!==void 0&&(n=n.default(t.default));let o={},i=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of i)a in t&&(o[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(o[a]=t[a]);for(let a of Object.keys(t))vse.has(a)||(o[a]=t[a]);return Object.keys(o).length>0&&e.registry.add(n,o),t.description&&(n=n.describe(t.description)),n}function cU(t,e){if(typeof t=="boolean")return t?G.any():G.never();let n;try{n=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let r=bse(n,e?.defaultTarget),o=n.$defs||n.definitions||{},i={version:r,defs:o,refs:new Map,processing:new Set,rootSchema:n,registry:e?.registry??It};return Ft(n,i)}var lP={};sn(lP,{bigint:()=>Rse,boolean:()=>xse,date:()=>Tse,number:()=>Sse,string:()=>wse});function wse(t){return MR(sc,t)}function Sse(t){return FR(cc,t)}function xse(t){return KR(lc,t)}function Rse(t){return JR(dc,t)}function Tse(t){return sT(Cd,t)}Ye(cf());var Ne={authenticate:"authenticate",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_focus:"document/didFocus",document_did_open:"document/didOpen",document_did_save:"document/didSave",initialize:"initialize",logout:"logout",mcp_message:"mcp/message",nes_accept:"nes/accept",nes_close:"nes/close",nes_reject:"nes/reject",nes_start:"nes/start",nes_suggest:"nes/suggest",providers_disable:"providers/disable",providers_list:"providers/list",providers_set:"providers/set",session_cancel:"session/cancel",session_close:"session/close",session_delete:"session/delete",session_fork:"session/fork",session_list:"session/list",session_load:"session/load",session_new:"session/new",session_prompt:"session/prompt",session_resume:"session/resume",session_set_config_option:"session/set_config_option",session_set_mode:"session/set_mode"},ar={elicitation_complete:"elicitation/complete",elicitation_create:"elicitation/create",fs_read_text_file:"fs/read_text_file",fs_write_text_file:"fs/write_text_file",mcp_connect:"mcp/connect",mcp_disconnect:"mcp/disconnect",mcp_message:"mcp/message",session_request_permission:"session/request_permission",session_update:"session/update",terminal_create:"terminal/create",terminal_kill:"terminal/kill",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit"};var lU=Symbol("skippedItem");function W(t,e){return t.catch(e)}function kr(t,e){let n=t.catch(e);return u.unknown().transform((r,o)=>r!==void 0?n.parse(r):(o.addIssue({code:"custom",message:"Required value is missing"}),u.NEVER))}function Ce(t){return u.array(t.catch(lU)).transform(e=>e.filter(n=>n!==lU))}var Pse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminal:u.boolean().optional().default(!1)}),Ise=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),label:u.string().nullish(),name:u.string(),optional:u.boolean().optional().default(!1),secret:u.boolean().optional().default(!0)}),_se=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:u.string(),name:u.string()}),Cse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:u.string(),link:u.string().nullish(),name:u.string(),vars:u.array(Ise)}),Ese=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),args:u.array(u.string()).optional(),description:u.string().nullish(),env:u.record(u.string(),u.string()).optional(),id:u.string(),name:u.string()}),Mse=u.union([Cse.and(u.object({type:u.literal("env_var")})),Ese.and(u.object({type:u.literal("terminal")})),_se]),dU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),methodId:u.string()}),Dse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),$se=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),blob:u.string(),mimeType:u.string().nullish(),uri:u.string()}),Nse=u.object({default:u.boolean().nullish(),description:u.string().nullish(),title:u.string().nullish()}),Ose=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),jse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Lse=u.object({amount:u.number(),currency:u.string()}),Use=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),Fse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Hse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),newText:u.string(),oldText:u.string().nullish(),path:u.string()}),uU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string()}),zse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Bse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),qse=u.union([u.string(),u.number(),u.number(),u.boolean(),u.array(u.string())]),Wse=u.object({content:u.record(u.string(),qse).nullish()}),Gse=u.intersection(u.union([Wse.and(u.object({action:u.literal("accept")})),u.object({action:u.literal("decline")}),u.object({action:u.literal("cancel")})]),u.object({_meta:u.record(u.string(),u.unknown()).nullish()})),Kse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),pU=u.string(),uP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),elicitationId:pU}),Vse=u.literal("object"),Jse=u.literal("string"),Zse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Xse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),form:W(Kse.nullish(),()=>{}),url:W(Zse.nullish(),()=>{})}),mU=u.object({const:u.string(),title:u.string()}),fU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),Yse=u.union([u.literal(-32700),u.literal(-32600),u.literal(-32601),u.literal(-32602),u.literal(-32603),u.literal(-32800),u.literal(-32e3),u.literal(-32002),u.literal(-32042),u.number().int().min(-2147483648,{message:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{message:"Invalid value: Expected int32 to be <= 2147483647"})]),gU=u.object({code:Yse,data:u.unknown().optional(),message:u.string()}),hU=u.unknown(),yU=u.unknown(),vU=u.unknown(),Qse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),readTextFile:u.boolean().optional().default(!1),writeTextFile:u.boolean().optional().default(!1)}),bU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),kU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),title:u.string().nullish(),version:u.string()}),eae=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),tae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),wU=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),SU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cursor:u.string().nullish(),cwd:u.string().nullish()}),pP=u.union([u.literal("anthropic"),u.literal("openai"),u.literal("azure"),u.literal("vertex"),u.literal("bedrock"),u.string()]),nae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),rae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),logout:W(nae.nullish(),()=>{})}),xU=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),oae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),iae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),acp:u.boolean().optional().default(!1),http:u.boolean().optional().default(!1),sse:u.boolean().optional().default(!1)}),kg=u.string(),sae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:kg}),aae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:kg}),RU=u.string(),cae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),acpId:RU}),lae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:RU,name:u.string()}),dae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(bU),name:u.string(),url:u.string()}),uae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(bU),name:u.string(),url:u.string()}),pae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),args:u.array(u.string()),command:u.string(),env:u.array(fU),name:u.string()}),wg=u.union([dae.and(u.object({type:u.literal("http")})),uae.and(u.object({type:u.literal("sse")})),lae.and(u.object({type:u.literal("acp")})),pae]),mae=u.string(),TU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:kg,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),AU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:kg,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),PU=u.unknown(),fae=u.union([u.literal("error"),u.literal("warning"),u.literal("information"),u.literal("hint")]),gae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),hae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),yae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),vae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),bae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),kae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),maxCount:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),wae=u.object({diff:u.string(),uri:u.string()}),Sae=u.object({endLine:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),startLine:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),text:u.string()}),xae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Rae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Tae=u.object({languageId:u.string(),text:u.string(),uri:u.string()}),Aae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),maxCount:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),Pae=u.union([u.literal("rejected"),u.literal("ignored"),u.literal("replaced"),u.literal("cancelled")]),Iae=u.object({excerpts:u.array(Sae),uri:u.string()}),_ae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Cae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Eae=u.object({name:u.string(),owner:u.string(),remoteUrl:u.string()}),Mae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Dae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),jump:W(xae.nullish(),()=>{}),rename:W(Cae.nullish(),()=>{}),searchAndReplace:W(Mae.nullish(),()=>{})}),$ae=u.object({id:u.string(),isRegex:u.boolean().nullish(),replace:u.string(),search:u.string(),uri:u.string()}),Nae=u.union([u.literal("automatic"),u.literal("diagnostic"),u.literal("manual")]),Oae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),maxCount:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish()}),jae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:W(gae.nullish(),()=>{}),editHistory:W(kae.nullish(),()=>{}),openFiles:W(Rae.nullish(),()=>{}),recentFiles:W(Aae.nullish(),()=>{}),relatedSnippets:W(_ae.nullish(),()=>{}),userActions:W(Oae.nullish(),()=>{})}),IU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(wg)}),Lae=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),_U=u.string(),Uae=u.union([u.literal("allow_once"),u.literal("allow_always"),u.literal("reject_once"),u.literal("reject_always")]),Fae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),kind:Uae,name:u.string(),optionId:_U}),Hae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),zae=u.union([u.literal("high"),u.literal("medium"),u.literal("low")]),Bae=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed")]),CU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),priority:zae,status:Bae}),qae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:kr(Ce(CU),()=>[])}),Sg=u.string(),Wae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:Sg,uri:u.string()}),Gae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:kr(Ce(CU),()=>[]),id:Sg}),Kae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),id:Sg}),Vae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:Sg}),Jae=u.union([Gae.and(u.object({type:u.literal("items")})),Wae.and(u.object({type:u.literal("file")})),Kae.and(u.object({type:u.literal("markdown")}))]),Zae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),plan:Jae}),Ri=u.object({character:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}),line:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"})}),Xae=u.object({id:u.string(),position:Ri,uri:u.string()}),Yae=u.object({id:u.string(),newName:u.string(),position:Ri,uri:u.string()}),Qae=u.object({action:u.string(),position:Ri,timestampMs:u.number(),uri:u.string()}),EU=u.union([u.literal("utf-16"),u.literal("utf-32"),u.literal("utf-8")]),ece=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:Pse.optional().default({terminal:!1}),elicitation:W(Xse.nullish(),()=>{}),fs:Qse.optional().default({readTextFile:!1,writeTextFile:!1}),nes:W(Dae.nullish(),()=>{}),plan:W(Hae.nullish(),()=>{}),positionEncodings:W(Ce(EU).optional(),()=>[]),terminal:u.boolean().optional().default(!1)}),tce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),audio:u.boolean().optional().default(!1),embeddedContext:u.boolean().optional().default(!1),image:u.boolean().optional().default(!1)}),MU=u.number().int().gte(0).lte(65535),DU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),clientCapabilities:ece.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:W(kU.nullish(),()=>{}),protocolVersion:MU}),nce=u.object({apiType:pP,baseUrl:u.string()}),rce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),current:nce.nullish(),id:u.string(),required:u.boolean(),supported:kr(Ce(pP),()=>[])}),oce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),providers:kr(Ce(rce),()=>[])}),ice=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),uc=u.object({end:Ri,start:Ri}),sce=u.object({message:u.string(),range:uc,severity:fae,uri:u.string()}),ace=u.object({languageId:u.string(),lastFocusedMs:W(u.number().nullish(),()=>{}),uri:u.string(),visibleRange:W(uc.nullish(),()=>{})}),cce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:W(Ce(sce).nullish(),()=>{}),editHistory:W(Ce(wae).nullish(),()=>{}),openFiles:W(Ce(ace).nullish(),()=>{}),recentFiles:W(Ce(Tae).nullish(),()=>{}),relatedSnippets:W(Ce(Iae).nullish(),()=>{}),userActions:W(Ce(Qae).nullish(),()=>{})}),lce=u.object({newText:u.string(),range:uc}),dce=u.object({cursorPosition:W(Ri.nullish(),()=>{}),edits:u.array(lce),id:u.string(),uri:u.string()}),uce=u.union([dce.and(u.object({kind:u.literal("edit")})),Xae.and(u.object({kind:u.literal("jump")})),Yae.and(u.object({kind:u.literal("rename")})),$ae.and(u.object({kind:u.literal("searchAndReplace")}))]),pce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string()}),mce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Ti=u.union([u.number(),u.string()]).nullable(),Pze=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),requestId:Ti}),$U=u.object({requestId:Ti}),fce=u.enum(["assistant","user"]),jd=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),audience:W(Ce(fce).nullish(),()=>{}),lastModified:u.string().nullish(),priority:u.number().nullish()}),gce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),data:u.string(),mimeType:u.string()}),hce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),data:u.string(),mimeType:u.string(),uri:u.string().nullish()}),yce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),description:u.string().nullish(),mimeType:u.string().nullish(),name:u.string(),size:u.number().nullish(),title:u.string().nullish(),uri:u.string()}),vce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),optionId:_U}),bce=u.union([u.object({outcome:u.literal("cancelled")}),vce.and(u.object({outcome:u.literal("selected")}))]),kce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),outcome:bce}),wce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Sce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xce=u.object({currentValue:u.boolean()}),Rce=u.string(),NU=u.string(),Tce=u.union([u.literal("mode"),u.literal("model"),u.literal("thought_level"),u.string()]),mP=u.string(),OU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),name:u.string(),value:mP}),Ace=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),group:Rce,name:u.string(),options:u.array(OU)}),Pce=u.union([u.array(OU),u.array(Ace)]),Ice=u.object({currentValue:mP,options:Pce}),pc=u.intersection(u.union([Ice.and(u.object({type:u.literal("select")})),xce.and(u.object({type:u.literal("boolean")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),category:W(Tce.nullish(),()=>{}),description:u.string().nullish(),id:NU,name:u.string()})),_ce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:kr(Ce(pc),()=>[])}),Cce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Ece=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xe=u.string(),jU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),sessionId:xe}),LU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),UU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),FU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),fP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),args:u.array(u.string()).optional(),command:u.string(),cwd:u.string().nullish(),env:u.array(fU).optional(),outputByteLimit:u.number().nullish(),sessionId:xe}),HU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),zU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,uri:u.string()}),BU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),position:Ri,sessionId:xe,uri:u.string(),version:u.number(),visibleRange:uc}),qU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),languageId:u.string(),sessionId:xe,text:u.string(),uri:u.string(),version:u.number()}),WU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,uri:u.string()}),GU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(wg).optional(),sessionId:xe}),gP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),KU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(wg),sessionId:xe}),hP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),limit:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),line:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:u.string(),sessionId:xe}),VU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),reason:W(Pae.nullish(),()=>{}),sessionId:xe}),yP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),JU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(wg).optional(),sessionId:xe}),Mce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),sessionId:xe,title:W(u.string().nullish(),()=>{}),updatedAt:W(u.string().nullish(),()=>{})}),Dce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),nextCursor:u.string().nullish(),sessions:kr(Ce(Mce),()=>[])}),$ce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),title:u.string().nullish(),updatedAt:u.string().nullish()}),Nce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xg=u.string(),Oce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),currentModeId:xg}),jce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:xg,name:u.string()}),Rg=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableModes:kr(Ce(jce),()=>[]),currentModeId:xg}),Lce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(pc).nullish(),()=>{}),modes:W(Rg.nullish(),()=>{}),sessionId:xe}),Uce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(pc).nullish(),()=>{}),modes:W(Rg.nullish(),()=>{})}),Fce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(pc).nullish(),()=>{}),modes:W(Rg.nullish(),()=>{}),sessionId:xe}),Hce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(pc).nullish(),()=>{}),modes:W(Rg.nullish(),()=>{})}),zce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Bce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:W(wce.nullish(),()=>{}),close:W(Sce.nullish(),()=>{}),delete:W(Cce.nullish(),()=>{}),fork:W(Ece.nullish(),()=>{}),list:W(Nce.nullish(),()=>{}),resume:W(zce.nullish(),()=>{})}),ZU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),apiType:pP,baseUrl:u.string(),headers:u.record(u.string(),u.string()).optional(),id:u.string()}),qce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),XU=u.intersection(u.union([u.object({type:u.literal("boolean"),value:u.boolean()}),u.object({value:mP})]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configId:NU,sessionId:xe})),Wce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:kr(Ce(pc),()=>[])}),YU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),modeId:xg,sessionId:xe}),Gce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Kce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),Vce=u.union([u.literal("end_turn"),u.literal("max_tokens"),u.literal("max_turn_requests"),u.literal("refusal"),u.literal("cancelled")]),Jce=u.union([u.literal("email"),u.literal("uri"),u.literal("date"),u.literal("date-time")]),Zce=u.object({default:u.string().nullish(),description:u.string().nullish(),enum:u.array(u.string()).nullish(),format:Jce.nullish(),maxLength:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),minLength:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),oneOf:u.array(mU).nullish(),pattern:u.string().nullish(),title:u.string().nullish()}),QU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:W(cce.nullish(),()=>{}),position:Ri,selection:W(uc.nullish(),()=>{}),sessionId:xe,triggerKind:Nae,uri:u.string(),version:u.number()}),Xce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),suggestions:kr(Ce(uce),()=>[])}),Yce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),Qce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),exitCode:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:u.string().nullish()}),vP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),ele=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),exitStatus:Qce.nullish(),output:u.string(),truncated:u.boolean()}),tle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),text:u.string()}),nle=u.object({range:uc.nullish(),text:u.string()}),eF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),contentChanges:u.array(nle),sessionId:xe,uri:u.string(),version:u.number()}),Ize=u.object({method:u.string(),params:u.union([LU,qU,eF,zU,WU,BU,jU,VU,TU,hU]).nullish()}),rle=u.union([u.literal("full"),u.literal("incremental")]),ole=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),syncKind:rle}),ile=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),didChange:W(ole.nullish(),()=>{}),didClose:W(hae.nullish(),()=>{}),didFocus:W(yae.nullish(),()=>{}),didOpen:W(vae.nullish(),()=>{}),didSave:W(bae.nullish(),()=>{})}),sle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),document:W(ile.nullish(),()=>{})}),ale=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:W(jae.nullish(),()=>{}),events:W(sle.nullish(),()=>{})}),cle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:rae.optional().default({}),loadSession:u.boolean().optional().default(!1),mcpCapabilities:iae.optional().default({acp:!1,http:!1,sse:!1}),nes:W(ale.nullish(),()=>{}),positionEncoding:W(EU.nullish(),()=>{}),promptCapabilities:tce.optional().default({audio:!1,embeddedContext:!1,image:!1}),providers:W(ice.nullish(),()=>{}),sessionCapabilities:Bce.optional().default({})}),lle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),agentCapabilities:cle.optional().default({auth:{},loadSession:!1,mcpCapabilities:{acp:!1,http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:W(kU.nullish(),()=>{}),authMethods:W(Ce(Mse).optional().default([]),()=>[]),protocolVersion:MU}),dle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),mimeType:u.string().nullish(),text:u.string(),uri:u.string()}),ule=u.union([dle,$se]),ple=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(jd.nullish(),()=>{}),resource:ule}),bP=u.union([tle.and(u.object({type:u.literal("text")})),hce.and(u.object({type:u.literal("image")})),gce.and(u.object({type:u.literal("audio")})),yce.and(u.object({type:u.literal("resource_link")})),ple.and(u.object({type:u.literal("resource")}))]),mle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:bP}),dP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:bP,messageId:mae.nullish()}),tF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),prompt:u.array(bP),sessionId:xe}),fle=u.object({anyOf:u.array(mU)}),nF=u.union([mle.and(u.object({type:u.literal("content")})),Hse.and(u.object({type:u.literal("diff")})),Yce.and(u.object({type:u.literal("terminal")}))]),kP=u.string(),rF=u.object({sessionId:xe,toolCallId:kP.nullish()}),gle=u.intersection(u.union([rF,$U]),u.object({elicitationId:pU,url:u.string().url()})),oF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),line:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),path:u.string()}),iF=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed"),u.literal("failed")]),sF=u.union([u.literal("read"),u.literal("edit"),u.literal("delete"),u.literal("move"),u.literal("search"),u.literal("execute"),u.literal("think"),u.literal("fetch"),u.literal("switch_mode"),u.literal("other")]),hle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:W(Ce(nF).optional(),()=>[]),kind:sF.optional(),locations:W(Ce(oF).optional(),()=>[]),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:iF.optional(),title:u.string(),toolCallId:kP}),aF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:W(Ce(nF).nullish(),()=>{}),kind:W(sF.nullish(),()=>{}),locations:W(Ce(oF).nullish(),()=>{}),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:W(iF.nullish(),()=>{}),title:u.string().nullish(),toolCallId:kP}),wP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),options:u.array(Fae),sessionId:xe,toolCall:aF}),yle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),hint:u.string()}),vle=yle,ble=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string(),input:W(vle.nullish(),()=>{}),name:u.string()}),kle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableCommands:kr(Ce(ble),()=>[])}),wle=u.object({enum:u.array(u.string()),type:Jse}),Sle=u.union([wle,fle]),xle=u.object({default:u.array(u.string()).nullish(),description:u.string().nullish(),items:Sle,maxItems:u.number().nullish(),minItems:u.number().nullish(),title:u.string().nullish()}),Rle=u.union([Zce.and(u.object({type:u.literal("string")})),Lae.and(u.object({type:u.literal("number")})),eae.and(u.object({type:u.literal("integer")})),Nse.and(u.object({type:u.literal("boolean")})),xle.and(u.object({type:u.literal("array")}))]),Tle=u.object({description:u.string().nullish(),properties:u.record(u.string(),Rle).optional().default({}),required:u.array(u.string()).nullish(),title:u.string().nullish(),type:Vse.optional().default("object")}),Ale=u.intersection(u.union([rF,$U]),u.object({requestedSchema:Tle})),SP=u.intersection(u.union([Ale.and(u.object({mode:u.literal("form")})),gle.and(u.object({mode:u.literal("url")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),message:u.string()})),Ple=u.object({cachedReadTokens:u.number().nullish(),cachedWriteTokens:u.number().nullish(),inputTokens:u.number(),outputTokens:u.number(),thoughtTokens:u.number().nullish(),totalTokens:u.number()}),Ile=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),stopReason:Vce,usage:W(Ple.nullish(),()=>{})}),_ze=u.union([u.object({id:Ti,result:u.union([lle,Dse,oce,qce,zse,oae,Fce,Uce,Dce,Fse,Lce,Hce,jse,Gce,Wce,Ile,Kce,Xce,Ose,vU,PU])}),u.object({error:gU,id:Ti})]),_le=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cost:W(Lse.nullish(),()=>{}),size:u.number(),used:u.number()}),Cle=u.union([dP.and(u.object({sessionUpdate:u.literal("user_message_chunk")})),dP.and(u.object({sessionUpdate:u.literal("agent_message_chunk")})),dP.and(u.object({sessionUpdate:u.literal("agent_thought_chunk")})),hle.and(u.object({sessionUpdate:u.literal("tool_call")})),aF.and(u.object({sessionUpdate:u.literal("tool_call_update")})),qae.and(u.object({sessionUpdate:u.literal("plan")})),Zae.and(u.object({sessionUpdate:u.literal("plan_update")})),Vae.and(u.object({sessionUpdate:u.literal("plan_removed")})),kle.and(u.object({sessionUpdate:u.literal("available_commands_update")})),Oce.and(u.object({sessionUpdate:u.literal("current_mode_update")})),_ce.and(u.object({sessionUpdate:u.literal("config_option_update")})),$ce.and(u.object({sessionUpdate:u.literal("session_info_update")})),_le.and(u.object({sessionUpdate:u.literal("usage_update")}))]),xP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,update:Cle}),Cze=u.object({method:u.string(),params:u.union([xP,uP,TU,hU]).nullish()}),RP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),Ele=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),exitCode:u.number().int().gte(0).max(4294967295,{message:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),signal:u.string().nullish()}),Mle=u.object({name:u.string(),uri:u.string()}),cF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),repository:W(Eae.nullish(),()=>{}),workspaceFolders:W(Ce(Mle).nullish(),()=>{}),workspaceUri:u.string().nullish()}),Eze=u.object({id:Ti,method:u.string(),params:u.union([DU,dU,wU,ZU,uU,xU,IU,KU,SU,HU,GU,JU,FU,YU,XU,tF,cF,QU,UU,AU,yU]).nullish()}),TP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),path:u.string(),sessionId:xe}),Mze=u.object({id:Ti,method:u.string(),params:u.union([TP,hP,wP,fP,vP,yP,RP,gP,SP,cae,AU,aae,yU]).nullish()}),Dle=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Dze=u.union([u.object({id:Ti,result:u.union([Dle,pce,kce,Use,ele,mce,Ele,tae,Gse,sae,Bse,vU,PU])}),u.object({error:gU,id:Ti})]);function lF(t,e){let n=new TextEncoder,r=new TextDecoder,o=new ReadableStream({async start(s){let a="",c=e.getReader();try{for(;;){let{value:d,done:p}=await c.read();if(p){a+=r.decode();break}if(!d)continue;a+=r.decode(d,{stream:!0});let m=a.split(`
|
|
684
684
|
`);a=m.pop()||"";for(let f of m){let g=f.trim();if(g)try{let h=JSON.parse(g);s.enqueue(h)}catch(h){console.error("Failed to parse JSON message:",g,h)}}}let l=a.trim();if(l)try{let d=JSON.parse(l);s.enqueue(d)}catch(d){console.error("Failed to parse JSON message:",l,d)}}catch(l){s.error(l);return}finally{c.releaseLock()}s.close()}}),i=new WritableStream({async write(s){let a=JSON.stringify(s)+`
|
|
685
685
|
`,c=t.getWriter();try{await c.write(n.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function Ai(t){return t??{}}function dF(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var Tg=class{connection;constructor(e,n){let r=e(this),o=async(s,a)=>{switch(s){case ar.fs_write_text_file:{let c=TP.parse(a);return await r.writeTextFile?.(c)??{}}case ar.fs_read_text_file:{let c=hP.parse(a);return r.readTextFile?.(c)}case ar.session_request_permission:{let c=wP.parse(a);return r.requestPermission(c)}case ar.terminal_create:{let c=fP.parse(a);return r.createTerminal?.(c)}case ar.terminal_output:{let c=vP.parse(a);return r.terminalOutput?.(c)}case ar.terminal_release:{let c=yP.parse(a);return await r.releaseTerminal?.(c)??{}}case ar.terminal_wait_for_exit:{let c=RP.parse(a);return r.waitForTerminalExit?.(c)}case ar.terminal_kill:{let c=gP.parse(a);return await r.killTerminal?.(c)??{}}case ar.elicitation_create:{if(!r.unstable_createElicitation)throw fn.methodNotFound(s);let c=SP.parse(a);return r.unstable_createElicitation(c)}default:if(r.extMethod)return r.extMethod(s,a);throw fn.methodNotFound(s)}},i=async(s,a)=>{switch(s){case ar.session_update:{let c=xP.parse(a);return r.sessionUpdate(c)}case ar.elicitation_complete:{if(!r.unstable_completeElicitation)return;let c=uP.parse(a);return r.unstable_completeElicitation(c)}default:if(r.extNotification)return r.extNotification(s,a);throw fn.methodNotFound(s)}};this.connection=new AP(o,i,n)}initialize(e){return this.connection.sendRequest(Ne.initialize,e)}newSession(e){return this.connection.sendRequest(Ne.session_new,e)}loadSession(e){return this.connection.sendRequest(Ne.session_load,e,Ai)}unstable_forkSession(e){return this.connection.sendRequest(Ne.session_fork,e)}listSessions(e){return this.connection.sendRequest(Ne.session_list,e)}deleteSession(e){return this.connection.sendRequest(Ne.session_delete,e,Ai)}resumeSession(e){return this.connection.sendRequest(Ne.session_resume,e)}closeSession(e){return this.connection.sendRequest(Ne.session_close,e)}setSessionMode(e){return this.connection.sendRequest(Ne.session_set_mode,e,Ai)}setSessionConfigOption(e){return this.connection.sendRequest(Ne.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(Ne.authenticate,e,Ai)}unstable_listProviders(e){return this.connection.sendRequest(Ne.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(Ne.providers_set,e,Ai)}unstable_disableProvider(e){return this.connection.sendRequest(Ne.providers_disable,e,Ai)}logout(e){return this.connection.sendRequest(Ne.logout,e,Ai)}prompt(e){return this.connection.sendRequest(Ne.session_prompt,e)}cancel(e){return this.connection.sendNotification(Ne.session_cancel,e)}unstable_startNes(e){return this.connection.sendRequest(Ne.nes_start,e)}unstable_suggestNes(e){return this.connection.sendRequest(Ne.nes_suggest,e)}unstable_closeNes(e){return this.connection.sendRequest(Ne.nes_close,e,Ai)}unstable_didOpenDocument(e){return this.connection.sendNotification(Ne.document_did_open,e)}unstable_didChangeDocument(e){return this.connection.sendNotification(Ne.document_did_change,e)}unstable_didCloseDocument(e){return this.connection.sendNotification(Ne.document_did_close,e)}unstable_didSaveDocument(e){return this.connection.sendNotification(Ne.document_did_save,e)}unstable_didFocusDocument(e){return this.connection.sendNotification(Ne.document_did_focus,e)}unstable_acceptNes(e){return this.connection.sendNotification(Ne.nes_accept,e)}unstable_rejectNes(e){return this.connection.sendNotification(Ne.nes_reject,e)}extMethod(e,n){return this.connection.sendRequest(e,n)}extNotification(e,n){return this.connection.sendNotification(e,n)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},AP=class{pendingResponses=new Map;nextRequestId=0;requestHandler;notificationHandler;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;constructor(e,n,r){this.requestHandler=e,this.notificationHandler=n,this.stream=r,this.closedPromise=new Promise(o=>{this.abortController.signal.addEventListener("abort",()=>o())}),this.receive()}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}async receive(){let e;try{let n=this.stream.readable.getReader();try{for(;!this.abortController.signal.aborted;){let{value:r,done:o}=await n.read();if(o)break;if(r)try{this.processMessage(r)}catch(i){console.error("Unexpected error during message processing:",r,i),"id"in r&&r.id!==void 0&&this.sendMessage({jsonrpc:"2.0",id:r.id,error:{code:-32700,message:"Parse error"}})}}}finally{n.releaseLock()}}catch(n){e=n}finally{this.close(e)}}close(e){if(this.abortController.signal.aborted)return;let n=e??new Error("ACP connection closed");for(let r of this.pendingResponses.values())r.reject(n);this.pendingResponses.clear(),this.abortController.abort(n)}async processMessage(e){if("method"in e&&"id"in e){let n=await this.tryCallRequestHandler(e.method,e.params);"error"in n&&console.error("Error handling request",e,n.error),await this.sendMessage({jsonrpc:"2.0",id:e.id,...n})}else if("method"in e){let n=await this.tryCallNotificationHandler(e.method,e.params);"error"in n&&console.error("Error handling notification",e,n.error)}else"id"in e?this.handleResponse(e):console.error("Invalid message",{message:e})}async tryCallRequestHandler(e,n){try{return{result:await this.requestHandler(e,n)??null}}catch(r){if(r instanceof fn)return r.toResult();if(r instanceof u.ZodError)return fn.invalidParams(r.format()).toResult();let o;(r instanceof Error||typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")&&(o=r.message);try{return fn.internalError(o?JSON.parse(o):{}).toResult()}catch{return fn.internalError({details:o}).toResult()}}}async tryCallNotificationHandler(e,n){try{return await this.notificationHandler(e,n),{result:null}}catch(r){if(r instanceof fn)return r.toResult();if(r instanceof u.ZodError)return fn.invalidParams(r.format()).toResult();let o;(r instanceof Error||typeof r=="object"&&r!=null&&"message"in r&&typeof r.message=="string")&&(o=r.message);try{return fn.internalError(o?JSON.parse(o):{}).toResult()}catch{return fn.internalError({details:o}).toResult()}}}handleResponse(e){let n=this.pendingResponses.get(e.id);if(n){if("result"in e)n.resolve(e.result);else if("error"in e){let{code:r,message:o,data:i}=e.error;n.reject(new fn(r,o,i))}this.pendingResponses.delete(e.id)}else console.error("Got response to unknown request",e.id)}sendRequest(e,n,r){if(this.abortController.signal.aborted)return dF(this.closedReason());let o=this.nextRequestId++,i=new Promise((s,a)=>{this.pendingResponses.set(o,{resolve:c=>{try{s(r?r(c):c)}catch(l){a(l)}},reject:a})});return i.catch(()=>{}),this.sendMessage({jsonrpc:"2.0",id:o,method:e,params:n}),i}sendNotification(e,n){return this.abortController.signal.aborted?dF(this.closedReason()):this.sendMessage({jsonrpc:"2.0",method:e,params:n})}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendMessage(e){return this.writeQueue=this.writeQueue.then(async()=>{let n=this.stream.writable.getWriter();try{await n.write(e)}finally{n.releaseLock()}}).catch(n=>{this.close(n)}),this.writeQueue}},fn=class t extends Error{code;data;constructor(e,n,r){super(n),this.code=e,this.name="RequestError",this.data=r}static parseError(e,n){return new t(-32700,`Parse error${n?`: ${n}`:""}`,e)}static invalidRequest(e,n){return new t(-32600,`Invalid request${n?`: ${n}`:""}`,e)}static methodNotFound(e){return new t(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,n){return new t(-32602,`Invalid params${n?`: ${n}`:""}`,e)}static internalError(e,n){return new t(-32603,`Internal error${n?`: ${n}`:""}`,e)}static authRequired(e,n){return new t(-32e3,`Authentication required${n?`: ${n}`:""}`,e)}static resourceNotFound(e){return new t(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};var jle=1,Lle=2e4,uF=3e4,Ule=3e5,wr={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",USAGE_UPDATE:"usage_update"};var Ld=class extends Error{retryable=!1;authMethods;constructor(e,n){super(e),this.name="AcpAuthRequiredError",this.authMethods=n}};function Ud(t,e){if(t instanceof Ld)return t;let n=t,r=Array.isArray(n?.data?.authMethods)?n.data.authMethods:[];if(n?.code===-32e3||r.length>0||/auth(?:entication|orization)?\s+required/i.test(n?.message??"")){let i=r[0],s=i?.description||(i?.name?`Use "${i.name}".`:"");return new Ld(`Authentication required.${s?` ${s}`:""}`,r)}if(e&&e.length>0&&Fle(n)){let i=e[0],s=n?.data?.details||i?.description||(i?.name?`Authentication required. Use "${i.name}".`:n?.message||"Authentication required.");return new Ld(s,e)}return null}function Fle(t){let e=`${t?.message??""}
|
|
686
|
-
${t?.data?.details??""}`;return/\b(auth(?:entication|orization)?|login|log in|api key|apikey|token|credential|provider|configured|configuration|setup|sign in)\b/i.test(e)}function Hle(t){let e=t;if(!e||typeof e.message!="string")return t;let n=e.data,r=typeof n=="string"?n:typeof n?.details=="string"?n.details:typeof n?.error=="string"?n.error:typeof n?.message=="string"?n.message:"";if(!r||e.message.includes(r))return t;let o=new Error(`${e.message}: ${r}`);return o.name=t instanceof Error?t.name:"Error",Object.assign(o,{code:e.code,data:e.data}),o}var Pi=class{conn=null;child=null;onNotification=null;hostHandler=null;attach(e,n,r){if(this.child=e,this.onNotification=n??null,this.hostHandler=r??null,!e.stdin||!e.stdout)throw new Error("ACP adapter: child process has no stdio");let o=lF(Ole.toWeb(e.stdin),Nle.toWeb(e.stdout)),i=o.readable.pipeThrough(new TransformStream({transform:(s,a)=>{this.consumeExtensionNotification(s)||a.enqueue(s)}}));this.conn=new Tg(()=>this.buildClient(),{readable:i,writable:o.writable})}consumeExtensionNotification(e){let n=e;if(!n||n.method!=="session/update"||n.id!==void 0)return!1;let r=n.params?.update?.sessionUpdate;if(typeof r!="string"||!r.startsWith("x_"))return!1;try{this.onNotification?.("session/update",n.params)}catch{}return!0}buildClient(){let e=()=>this.hostHandler,n=(r,o)=>this.onNotification?.(r,o);return{async sessionUpdate(r){n("session/update",r)},async requestPermission(r){let o=e(),s=(o?.requestPermission?await o.requestPermission(r):{optionId:"allow"})?.optionId;return s?{outcome:{outcome:"selected",optionId:s}}:{outcome:{outcome:"cancelled"}}},async readTextFile(r){return{content:(await e()?.readTextFile?.(r))?.content??""}},async writeTextFile(r){return await e()?.writeTextFile?.(r),{}},async createTerminal(r){return await e()?.createTerminal?.(r)??{terminalId:""}},async terminalOutput(r){return await e()?.terminalOutput?.(r)??{output:"",truncated:!1}},async releaseTerminal(r){return await e()?.releaseTerminal?.(r),{}},async waitForTerminalExit(r){return await e()?.waitForTerminalExit?.(r)??{}},async killTerminal(r){return await e()?.killTerminal?.(r),{}},async extMethod(r,o){return await e()?.extMethod?.(r,o)??{}},async extNotification(r,o){n(r,o)}}}detach(){this.conn=null,this.hostHandler=null,this.onNotification=null,this.child=null}requireConn(){if(!this.conn)throw new Error("ACP adapter not attached");return this.conn}async withTimeout(e,n,r,o){let i,s=new Promise((a,c)=>{i=setTimeout(()=>{try{o?.()}catch{}c(new Error(`ACP ${r} timeout (${n}ms)`))},n)});try{return await Promise.race([e,s])}finally{i&&clearTimeout(i)}}async initialize(e){let n={protocolVersion:jle,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}},clientInfo:{name:"qlogicagent",version:"1.0.0"}},r=await this.withTimeout(this.requireConn().initialize(n),Lle,"initialize").catch(i=>{throw Ud(i)??i}),o=r?.agentCapabilities??{};return{protocolVersion:typeof r?.protocolVersion=="number"?r.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities,qlogicagent:o.qlogicagent},agentInfo:r?.agentInfo,authMethods:r?.authMethods}}async createSession(e,n){let r={cwd:n.cwd,mcpServers:n.mcpServers??[]};n.additionalDirectories?.length&&(r.additionalDirectories=n.additionalDirectories),n.systemPrompt&&(r._meta={qlogicagent:{systemPrompt:n.systemPrompt}});let o=await this.withTimeout(this.requireConn().newSession(r),uF,"session/new").catch(i=>{throw Ud(i)??i});if(typeof o?.sessionId!="string")throw new Error("ACP session/new: agent did not return sessionId");return{sessionId:o.sessionId}}async sendPrompt(e,n,r,o=Ule){let i=this.requireConn(),s=await this.withTimeout(i.prompt({sessionId:n,prompt:[{type:"text",text:r}]}),o,"session/prompt",()=>{i.cancel({sessionId:n}).catch(()=>{})}).catch(a=>{throw Ud(a)??Hle(a)});return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:void 0}}async resumeSession(e,n,r){let o={sessionId:n,cwd:r?.cwd??process.cwd(),mcpServers:r?.mcpServers??[]},i=await this.withTimeout(this.requireConn().loadSession(o),uF,"session/load");return{sessionId:typeof i?.sessionId=="string"?i.sessionId:n}}static translateNotification(e,n){let r=n;if(e==="session/update"){if(!r)return null;let o=r.update;if(!o)return null;let i=o.sessionUpdate,s=r.sessionId;switch(i){case wr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case wr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case wr.TOOL_CALL:return{method:"turn.tool_call",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"running",content:o.content,kind:o.kind,rawInput:o.rawInput,sessionId:s}};case wr.TOOL_CALL_UPDATE:return{method:"turn.tool_result",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"completed",content:o.content,rawOutput:o.rawOutput,sessionId:s}};case wr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case wr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case wr.AVAILABLE_COMMANDS_UPDATE:case wr.CURRENT_MODE_UPDATE:case wr.CONFIG_OPTION_UPDATE:case wr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case wr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as zle}from"node:child_process";import{readFile as Ble,writeFile as qle}from"node:fs/promises";import{isAbsolute as pF,normalize as Wle,relative as Gle,resolve as Kle,sep as Vle}from"node:path";function Jle(t){let e=t.options;if(!Array.isArray(e)||e.length===0)return"allow";let n=e.filter(c=>!!c&&typeof c=="object"),r=c=>typeof c.optionId=="string"&&c.optionId.trim()?c.optionId:void 0;if(n.find(c=>r(c)==="allow"))return"allow";let i=n.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/allow/i.test(l)}),s=i?r(i):void 0;if(s)return s;let a=n.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/reject|deny|cancel/i.test(l)});return r(a??{})??r(n[0]??{})??"allow"}function PP(t){let e=new Map,n=0,r=i=>{let s=pF(i)?Wle(i):Kle(t.cwd,i),a=Gle(t.cwd,s);if(a===".."||a.startsWith(`..${Vle}`)||pF(a))throw new Error(`path escapes cwd: ${i}`);return s},o=i=>String(i.terminalId??"");return{async requestPermission(i){return t.requestPermission?t.requestPermission(i):{optionId:Jle(i)}},async readTextFile(i){return{content:await Ble(r(i.path),"utf8")}},async writeTextFile(i){return await qle(r(i.path),i.content,"utf8"),{}},async createTerminal(i){let s=String(i.command??""),a=i.args,c=Array.isArray(a)?a.map(String):[],l=i.cwd,d=l?r(String(l)):t.cwd,p=i.env,m={...process.env,...p&&typeof p=="object"?p:{}},f=zle(s,c,{cwd:d,env:m,stdio:["ignore","pipe","pipe"]}),g=`term-${++n}`,h={child:f,output:"",exitStatus:null,exit:new Promise(y=>{f.on("exit",(b,v)=>{let k={exitCode:b,signal:v};h.exitStatus=k,y(k)}),f.on("error",()=>{let b={exitCode:null,signal:null};h.exitStatus=b,y(b)})})};return f.stdout?.on("data",y=>{h.output+=y.toString()}),f.stderr?.on("data",y=>{h.output+=y.toString()}),e.set(g,h),{terminalId:g}},async terminalOutput(i){let s=e.get(o(i));return s?{output:s.output,truncated:!1,exitStatus:s.exitStatus}:{output:"",truncated:!1,exitStatus:null}},async waitForTerminalExit(i){let s=e.get(o(i));return s?s.exit:{exitCode:null,signal:null}},async releaseTerminal(i){let s=o(i),a=e.get(s);if(a&&a.child.exitCode===null&&a.child.signalCode===null)try{a.child.kill()}catch{}return e.delete(s),{}},async killTerminal(i){let s=e.get(o(i));if(s)try{s.child.kill("SIGKILL")}catch{}return{}},disposeAll(){for(let i of e.values())try{i.child.kill("SIGKILL")}catch{}e.clear()}}}var Fd=class{usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0};onUsageUpdate(e){this.usage.hasTier1=!0,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cost=="number"&&(this.usage.cost+=e.cost)}onPromptResponseUsage(e){e&&(this.usage.hasTier1||(this.usage.turnCount++,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cachedReadTokens=="number"&&(this.usage.cachedReadTokens+=e.cachedReadTokens),typeof e.thoughtTokens=="number"&&(this.usage.thoughtTokens+=e.thoughtTokens)))}getUsage(){return{...this.usage}}reset(){this.usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0}}hasData(){return this.usage.hasTier1||this.usage.turnCount>0}};import{exec as Xle,execFile as Yle,execFileSync as mF,execSync as AF}from"node:child_process";import{existsSync as Ei,mkdirSync as PF,readFileSync as gc,readdirSync as IF,writeFileSync as _F}from"node:fs";import{homedir as NP,platform as Qle,tmpdir as ede}from"node:os";import{dirname as Hd,join as bt}from"node:path";import{promisify as CF}from"node:util";function Ii(){let t=process.env.XIAOZHICLAW_NODE_EXE,e=process.env.XIAOZHICLAW_NPM_CLI;return!t||!e?null:{nodeExe:t,npmCli:e,prefix:process.env.XIAOZHICLAW_NPM_GLOBAL_PREFIX||void 0}}function _i(t){let e={...process.env,ELECTRON_RUN_AS_NODE:"1"};return t.prefix&&(e.npm_config_prefix=t.prefix),e}function IP(t){let e=t.trim().split(/\s+/)[0];return e==="npm"||e==="npm.cmd"}var Zle=/^(?:pip3?|pipx|uv|uvx|python3?|curl|wget|brew|sh|bash)\b/;function _P(t){return Zle.test(t.trim())}function CP(){let t={...process.env};return delete t.ELECTRON_RUN_AS_NODE,t}var fF=CF(Yle),EF=CF(Xle),Hs={claude:{id:"claude",name:"Claude Code",cliCommand:"claude-agent-acp",acpArgs:[],authRequired:!0,skillsDirs:[".claude/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},codex:{id:"codex",name:"OpenAI Codex CLI",cliCommand:"codex-acp",acpArgs:["-c","sandbox_mode=danger-full-access","-c","approval_policy=untrusted"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENAI_API_KEY",baseUrlEnvVar:"OPENAI_BASE_URL"},qwen:{id:"qwen",name:"Qwen Code",cliCommand:"qwen",acpArgs:["--acp","--experimental-skills"],defaultCliPath:"npx @qwen-code/qwen-code",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"DASHSCOPE_API_KEY"},kimi:{id:"kimi",name:"Kimi CLI",cliCommand:"kimi",acpArgs:["acp"],authRequired:!0,skillsDirs:[".kimi/skills"],supportsBaseUrlOverride:!1},opencode:{id:"opencode",name:"OpenCode",cliCommand:"opencode",acpArgs:["acp"],authRequired:!1,skillsDirs:[".opencode/skills"],supportsBaseUrlOverride:!0},cursor:{id:"cursor",name:"Cursor Agent",cliCommand:"cursor-agent",acpArgs:["acp"],authRequired:!0,skillsDirs:[".cursor/skills"],supportsBaseUrlOverride:!1},hermes:{id:"hermes",name:"Hermes Agent",cliCommand:"hermes",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},copilot:{id:"copilot",name:"GitHub Copilot",cliCommand:"copilot",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},kiro:{id:"kiro",name:"Kiro CLI",cliCommand:"kiro-cli",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},snow:{id:"snow",name:"Snow",cliCommand:"snow",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},gemini:{id:"gemini",name:"Gemini CLI",cliCommand:"gemini",acpArgs:["--experimental-acp"],defaultCliPath:"npx @google/gemini-cli",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"GEMINI_API_KEY",baseUrlEnvVar:"GOOGLE_GEMINI_BASE_URL"},glm:{id:"glm",name:"GLM Agent",cliCommand:"glm-acp-agent",acpArgs:[],defaultCliPath:"npx glm-acp-agent",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"Z_AI_API_KEY",baseUrlEnvVar:"ACP_GLM_BASE_URL"},cline:{id:"cline",name:"Cline",cliCommand:"cline",acpArgs:["--acp"],defaultCliPath:"npx cline",authRequired:!0,supportsBaseUrlOverride:!0},nova:{id:"nova",name:"Nova",cliCommand:"nova",acpArgs:["acp"],defaultCliPath:"npx @compass-ai/nova",authRequired:!0,supportsBaseUrlOverride:!0},openclaw:{id:"openclaw",name:"OpenClaw",cliCommand:"openclaw",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENCLAW_API_KEY",baseUrlEnvVar:"OPENCLAW_BASE_URL"}},tde=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],gF={claude:{brandId:"claude",category:"coding",integration:"acp",keySource:"llmrouter",authMode:"key",install:{npm:"npm i -g @agentclientprotocol/claude-agent-acp",cliCommand:"claude-agent-acp",docsUrl:"https://github.com/agentclientprotocol/claude-agent-acp"},strengths:"\u590D\u6742\u63A8\u7406\u3001\u91CD\u6784\u3001\u957F\u94FE\u8DEF\u5B9E\u73B0"},codex:{brandId:"codex",category:"coding",integration:"acp",keySource:"llmrouter",authMode:"key",install:{npm:"npm i -g @zed-industries/codex-acp",cliCommand:"codex-acp",verifyCmd:"codex-acp --help",docsUrl:"https://github.com/zed-industries/codex-acp"},strengths:"\u4EE3\u7801\u751F\u6210\u3001\u8C03\u8BD5\u3001shell/\u5DE5\u5177\u94FE"},gemini:{brandId:"gemini",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @google/gemini-cli",cliCommand:"gemini",docsUrl:"https://github.com/google-gemini/gemini-cli"},strengths:"\u591A\u6A21\u6001\u3001\u957F\u4E0A\u4E0B\u6587\u3001\u7EFC\u5408\u5B9E\u73B0"},copilot:{brandId:"copilot",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9ED8\u8BA4\u9700 GitHub \u8D26\u53F7(\u4E5F\u652F\u6301 BYOK \u81EA\u5E26 key,\u540E\u7EED\u53EF\u63A5\u5165\u514D\u767B\u5F55\u6CE8\u5165)",install:{npm:"npm i -g @github/copilot",cliCommand:"copilot",setupCommand:"copilot",docsUrl:"https://docs.github.com/copilot/concepts/agents/about-copilot-cli"},strengths:"\u901A\u7528\u7F16\u7801\u3001GitHub \u751F\u6001"},cursor:{brandId:"cursor",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9700 Cursor \u8D26\u53F7",install:{curl:"curl https://cursor.com/install -fsS | bash",cliCommand:"cursor-agent",setupCommand:"cursor-agent login",docsUrl:"https://cursor.com/cli"},strengths:"\u901A\u7528\u7F16\u7801\u3001IDE \u96C6\u6210"},qwen:{brandId:"qwen",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @qwen-code/qwen-code",cliCommand:"qwen",docsUrl:"https://github.com/QwenLM/qwen-code"},strengths:"\u524D\u7AEF/UI\u3001\u4EA4\u4E92\u5B9E\u73B0\u3001\u901A\u7528\u7F16\u7801"},kimi:{brandId:"kimi",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9700 Kimi \u8D26\u53F7(\u5728\u7EC8\u7AEF\u8FD0\u884C kimi login \u767B\u5F55)",install:{pip:"uv tool install kimi-cli",cliCommand:"kimi",setupCommand:"kimi login",docsUrl:"https://github.com/MoonshotAI/kimi-cli"},strengths:"\u957F\u4E0A\u4E0B\u6587\u3001\u4E2D\u6587\u573A\u666F"},glm:{brandId:"glm",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g glm-acp-agent",cliCommand:"glm-acp-agent",docsUrl:"https://github.com/stefandevo/glm-acp-agent"},strengths:"\u901A\u7528\u7F16\u7801\u3001\u4E2D\u6587\u573A\u666F"},opencode:{brandId:"opencode",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g opencode-ai",cliCommand:"opencode",docsUrl:"https://opencode.ai/docs"},strengths:"\u7B97\u6CD5\u3001\u6570\u636E\u7ED3\u6784\u3001\u590D\u6742\u903B\u8F91"},kiro:{brandId:"kiro",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{cliCommand:"kiro-cli",docsUrl:"https://kiro.dev/docs"},strengths:"\u901A\u7528\u7F16\u7801"},qoder:{brandId:"qoder",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @qoder-ai/qodercli",cliCommand:"qodercli",docsUrl:"https://docs.qoder.com/cli/acp"},strengths:"\u901A\u7528\u7F16\u7801"},openclaw:{brandId:"openclaw",category:"assistant",integration:"acp",keySource:"direct",authMode:"key",note:"\u9AD8\u7EA7:\u9700\u81EA\u5907\u8FD0\u884C\u4E2D\u7684 openclaw Gateway + \u6709\u6548 ~/.openclaw \u914D\u7F6E(openclaw acp = \u6302\u5728 Gateway \u4E0A\u7684 ACP \u6865)",install:{npm:"npm i -g openclaw",cliCommand:"openclaw",setupCommand:"openclaw onboard",docsUrl:"https://github.com/openclaw/openclaw"},strengths:"\u52A9\u7406/\u7F16\u6392\u3001\u901A\u7528"},hermes:{brandId:"hermes",category:"assistant",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9996\u6B21\u9700\u5728\u7EC8\u7AEF\u8FD0\u884C hermes acp --setup \u914D\u7F6E provider/model",install:{pip:"uv tool install hermes-agent[acp] --python 3.13",cliCommand:"hermes",setupCommand:"hermes acp --setup",docsUrl:"https://github.com/NousResearch/hermes-agent"},strengths:"\u52A9\u7406\u3001\u901A\u7528"}};function Eo(t){let e=Hs[t];if(e)return gF[t]?{...e,...gF[t]}:e}function zd(){return tde.map(t=>{let e=Eo(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Mo=Qle()==="win32",MF=5*6e4,nde=2e4,Ci,mc=new Map,EP=bt(process.env.QLOGICAGENT_HOME||bt(NP(),".qlogicagent"),"agent-update-cache.json"),hF=!1;function DF(){if(!hF){hF=!0;try{let t=JSON.parse(gc(EP,"utf8"));for(let[e,n]of Object.entries(t))n&&typeof n.timestamp=="number"&&!mc.has(e)&&mc.set(e,n)}catch{}}}var Ag=null;function rde(){Ag||(Ag=setTimeout(()=>{Ag=null;try{let t={};for(let[e,n]of mc)t[e]=n;PF(Hd(EP),{recursive:!0}),_F(EP,JSON.stringify(t),"utf8")}catch{}},1e3),Ag.unref?.())}function MP(t){try{let e=Mo?`where ${t}`:`which ${t}`;return AF(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}async function DP(t){try{let e=Mo?`where ${t}`:`which ${t}`,{stdout:n}=await EF(e,{encoding:"utf8",timeout:5e3,windowsHide:!0});return String(n).split(/\r?\n/)[0]?.trim()||null}catch{return null}}function $F(t,e){let n=i=>{let s=i.match(/^(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r[i]!==o[i])return o[i]-r[i];return e.localeCompare(t)}function ode(){if(!Mo)return null;let t=[process.env.COPILOT_CACHE_HOME?bt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?bt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?bt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,bt(NP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=IF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort($F);for(let r of n){let o=bt(e,r,"npm-loader.js");if(Ei(o)&&FF(o))return o}}catch{}return null}function ide(t){return t.id==="copilot"?ode()??MP(t.cliCommand):MP(t.cliCommand)}async function sde(){if(!Mo)return null;let t=[process.env.COPILOT_CACHE_HOME?bt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?bt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?bt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,bt(NP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=IF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort($F);for(let r of n){let o=bt(e,r,"npm-loader.js");if(Ei(o)&&await HF(o))return o}}catch{}return null}async function ade(t){return t.id==="copilot"?await sde()??await DP(t.cliCommand):DP(t.cliCommand)}function cde(t,e){let n=Ii();return n?mF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],env:_i(n),windowsHide:!0}).trim():mF(Mo?"cmd.exe":"npm",Mo?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()}async function NF(t,e){let n=Ii();if(n){let{stdout:o}=await fF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,env:_i(n)});return o.trim()}let{stdout:r}=await fF(Mo?"cmd.exe":"npm",Mo?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function lde(t){let e=t.trim().replace(/^["']|["']$/g,"");if(!e||e.startsWith("-"))return null;if(e.startsWith("@")){let r=e.indexOf("@",1);return r>0?e.slice(0,r):e}let n=e.indexOf("@");return n>0?e.slice(0,n):e}function Eg(t){if(!t)return null;let e=t.trim().split(/\s+/).filter(Boolean);if(e[0]!=="npm"&&e[0]!=="npm.cmd")return null;let n=e.findIndex(r=>r==="i"||r==="install"||r==="add");if(n<0)return null;for(let r=n+1;r<e.length;r+=1){let o=e[r];if(!(o==="-g"||o==="--global")){if(o.startsWith("--")&&!o.includes("=")){r+=1;continue}if(!o.startsWith("-"))return lde(o)}}return null}function Bd(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function dde(t,e){let n=i=>{let s=Bd(i)??i,[a,c=""]=s.replace(/^v/,"").split("-",2),l=a.split(".").map(d=>Number.parseInt(d,10)||0);for(;l.length<3;)l.push(0);return{nums:l,pre:c}},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r.nums[i]!==o.nums[i])return r.nums[i]-o.nums[i];return r.pre===o.pre?0:r.pre?o.pre?r.pre.localeCompare(o.pre):-1:1}function OF(t,e){return!t||!e?!1:dde(t,e)>0}function ude(){if(Ci!==void 0)return Ci;try{Ci=cde(["root","-g"],3e3)||null}catch{Ci=null}return Ci}async function pde(){if(Ci===void 0)try{Ci=await NF(["root","-g"],3e3)||null}catch{Ci=null}}function Mg(t){if(!t)return null;let e=ude();if(!e)return null;let n=bt(e,...t.split("/"),"package.json");try{let r=JSON.parse(gc(n,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}function yF(t){let e=Eg(t?.npm);return Mg(e)}function jF(t,e){return Mg(Eg(t.install?.npm))??Bd(e)??e??void 0}async function mde(t,e){if(!t)return null;DF();let n=e?`${t}\0${e}`:t,r=mc.get(n);if(r){let i=r.version?MF:nde;if(Date.now()-r.timestamp<i)return r.version}let o=null;try{let i=["view",t,"version","--json"];e&&i.push("--registry",e);let s=await NF(i,12e3),a=s?JSON.parse(s):null;o=typeof a=="string"?a:Bd(s)}catch{o=null}return mc.set(n,{timestamp:Date.now(),version:o}),rde(),o}async function LF(t,e){let n=t.map(async({id:o,entry:i,detectedVersion:s})=>{let a=Eg(i.install?.npm),c=Mg(a)??Bd(s)??s??void 0;if(!a||!c)return null;let l=await mde(a,e)??void 0;return l?{id:o,packageName:a,installedVersion:c,latestVersion:l,updateAvailable:OF(l,c)}:null});return(await Promise.all(n)).filter(o=>o!==null)}function UF(t,e){DF();let n=[],r=!1;for(let{id:o,entry:i,detectedVersion:s}of t){let a=Eg(i.install?.npm),c=Mg(a)??Bd(s)??s??void 0;if(!a||!c)continue;let l=e?`${a} ${e}`:a,d=mc.get(l);d?.version&&Date.now()-d.timestamp<MF||(r=!0),d?.version&&n.push({id:o,packageName:a,installedVersion:c,latestVersion:d.version,updateAvailable:OF(d.version,c)})}return{updates:n,stale:r}}function FF(t){let e=t.endsWith("npm-loader.js");for(let n of["--version","version","-v"])try{let r=e?`"${process.execPath}" "${t}" ${n}`:`"${t}" ${n}`,i=AF(r,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().match(/(\d+\.\d+(?:\.\d+)?[\w.-]*)/);if(i?.[1])return i[1]}catch{}return null}async function HF(t){let e=t.endsWith("npm-loader.js");for(let n of["--version","version","-v"])try{let r=e?`"${process.execPath}" "${t}" ${n}`:`"${t}" ${n}`,{stdout:o}=await EF(r,{encoding:"utf8",timeout:5e3,windowsHide:!0}),i=String(o).trim().match(/(\d+\.\d+(?:\.\d+)?[\w.-]*)/);if(i?.[1])return i[1]}catch{}return null}function fde(t,e){if(!Mo)return{cliPath:t,acpArgs:e};if(t.endsWith("npm-loader.js")){let o=e.includes("--no-auto-update");return{cliPath:process.execPath,acpArgs:[t,...e,...o?[]:["--no-auto-update"]]}}let n=zF(t);if(n)return{cliPath:process.execPath,acpArgs:[n,...e]};let r=gde(t);return r?{cliPath:r,acpArgs:e}:{cliPath:t,acpArgs:e}}function zF(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ei(r))continue;let o;try{o=gc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=bt(Hd(e),s);if(Ei(a))return a}return null}function gde(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ei(r))continue;let o;try{o=gc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.exe)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=bt(Hd(e),s);if(Ei(a))return a}return null}function vF(t){let e=zF(t);if(!e)return null;let n=Hd(e);for(let r=0;r<6;r+=1){let o=bt(n,"package.json");try{if(Ei(o)){let s=JSON.parse(gc(o,"utf8"));if(typeof s.version=="string"&&s.version)return s.version}}catch{}let i=Hd(n);if(i===n)break;n=i}return null}var bF=6e4;function hde(t,e,n){let r={};return t?.env&&Object.assign(r,t.env),n&&Object.assign(r,n),t?.apiKeyEnvVar&&e?.apiKey&&(r[t.apiKeyEnvVar]=e.apiKey),t?.baseUrlEnvVar&&e?.baseUrl&&(r[t.baseUrlEnvVar]=e.baseUrl),e?.env&&Object.assign(r,e.env),Object.keys(r).length>0?r:void 0}var BF=new Set(["codex","qwen","opencode"]),Ig=new Set(["qwen","opencode"]),_g=new Set(["gemini"]),$P=new Set(["glm"]),kF={claude:"anthropic",codex:"openai"};function yde(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function vde(t){let e=bt(ede(),"qlogicagent-codex-model-catalog");PF(e,{recursive:!0});let n=bt(e,`${yde(t)}.json`),r=JSON.stringify({models:[{slug:t,display_name:t,supported_reasoning_levels:[],shell_type:"shell_command",visibility:"list",priority:0,base_instructions:"You are Codex, a coding agent. Follow the user's instructions and use tools only when needed.",supports_reasoning_summaries:!1,support_verbosity:!1,truncation_policy:{mode:"tokens",limit:1e6},supports_parallel_tool_calls:!1,experimental_supported_tools:[],supported_in_api:!0}]});return(!Ei(n)||gc(n,"utf8")!==r)&&_F(n,r,"utf8"),n}function OP(t){return t.id!=="claude"}function Cg(t,e){return e==="account"&&!OP(t)?"auto":e}function qF(t){if(t.authMode==="oauth"||t.keySource==="none")return["account"];let e=[];return t.keySource==="llmrouter"&&OP(t)&&e.push("account"),e.push("userKey"),(t.keySource==="llmrouter"||Ig.has(t.id)||_g.has(t.id)||$P.has(t.id))&&e.push("managed"),e}function jP(t,e,n){let r=Cg(t,e);return!!(r==="account"||r==="auto"&&OP(t)&&n?.hasSubscription?.(t.id)===!0)}var WF={claude:"ANTHROPIC_MODEL",codex:"OPENAI_MODEL",glm:"ACP_GLM_MODEL"},bde={glm:"ACP_GLM_AVAILABLE_MODELS"};function Pg(t,e,n){let{apiKeyEnvVar:r,baseUrlEnvVar:o}=t;r&&e.llmrouterKey&&(n[r]=e.llmrouterKey);let i=e.getLlmrouterBaseUrl?.(t.id,t)??e.llmrouterBaseUrl;o&&i&&(n[o]=i);let s=WF[t.id];s&&e.llmrouterModel&&(n[s]=e.llmrouterModel);let a=bde[t.id];a&&e.llmrouterModel&&(n[a]=e.llmrouterModel)}function wF(t,e,n){e.llmrouterKey&&(n.OPENAI_API_KEY=e.llmrouterKey);let r=e.getLlmrouterBaseUrl?.(t.id,t)??e.llmrouterBaseUrl;r&&(n.OPENAI_BASE_URL=r),e.llmrouterModel&&(n.OPENAI_MODEL=e.llmrouterModel)}var SF=["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_GEMINI_API_KEY","GEMINI_API_KEY"];function xF(t,e){return t?(e.apiKeyEnvVar?[e.apiKeyEnvVar,...SF]:SF).some(r=>typeof t[r]=="string"&&t[r].trim().length>0):!1}function RF(t){return!!t.apiKeyEnvVar||Ig.has(t.id)||_g.has(t.id)}function TF(t,e,n="auto"){let r={};if(!t)return r;let o=Cg(t,n);if(o==="account"||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:i,baseUrlEnvVar:s}=t;if(o==="userKey"){let a=kF[t.id]??t.id,c=e.getDirectKey?.(a);return i&&c&&(r[i]=c),r}if(o==="managed")return t.keySource==="llmrouter"||_g.has(t.id)||$P.has(t.id)?Pg(t,e,r):Ig.has(t.id)&&wF(t,e,r),r;if(jP(t,"auto",e))return r;if(t.keySource==="llmrouter"){let a=kF[t.id],c=a?e.getDirectKey?.(a):void 0;i&&c?r[i]=c:Pg(t,e,r)}else if(t.keySource==="direct"){let a=e.getDirectKey?.(t.id);i&&a?r[i]=a:Ig.has(t.id)?wF(t,e,r):(_g.has(t.id)||$P.has(t.id))&&Pg(t,e,r)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&BF.has(t.id)){let a=e.passthroughModel;r.OPENAI_API_KEY=a.apiKey,a.baseUrl&&(r.OPENAI_BASE_URL=a.baseUrl),a.model&&(r.OPENAI_MODEL=a.model)}return r}function kde(t,e,n){if(!t||!jP(t,e,n))return[];let r=[];return t.apiKeyEnvVar&&r.push(t.apiKeyEnvVar),t.baseUrlEnvVar&&r.push(t.baseUrlEnvVar),BF.has(t.id)&&r.push("OPENAI_MODEL"),r}function wde(t,e,n,r,o="auto"){if(!t)return e;if(t.id==="qwen")return!n.OPENAI_API_KEY||e.some(a=>a==="--auth-type"||a.startsWith("--auth-type="))?e:[...e,"--auth-type=openai"];if(t.id==="gemini"){let a=r.llmrouterModel;return!n.GEMINI_API_KEY||!a||e.some(c=>c==="-m"||c==="--model"||c.startsWith("--model="))?e:[...e,"--model",a]}if(t.id!=="codex")return e;if(jP(t,o,r))return e.some(a=>a.includes("preferred_auth_method"))?e:[...e,"-c","preferred_auth_method=chatgpt"];if(t.keySource!=="llmrouter"||!n.OPENAI_API_KEY||e.some(a=>a.includes("model_provider")||a.includes("model_providers.")))return e;let i=n.OPENAI_BASE_URL,s=r.llmrouterModel||n.OPENAI_MODEL||"deepseek-v4-flash";return i?[...e,"-c","model_providers.llmrouter.name=llmrouter","-c",`model_providers.llmrouter.base_url=${i}`,"-c","model_providers.llmrouter.wire_api=responses","-c","model_providers.llmrouter.env_key=OPENAI_API_KEY","-c","model_provider=llmrouter","-c",`model=${s}`,"-c",`model_catalog_json=${vde(s)}`]:e}var fc=class{cache=null;configStore=null;keySources={};scanInFlight=null;setConfigStore(e){this.configStore=e}setKeySources(e){this.keySources=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<bF)return this.cache.agents;let n=[];for(let r of Object.values(Hs))n.push(this.detectBackend(r));if(this.configStore?.customAgents)for(let r of Object.values(this.configStore.customAgents))n.push(this.detectCustomAgent(r));return this.cache={agents:n,timestamp:Date.now()},n}async scanAsync(e=!1){return!e&&this.cache&&Date.now()-this.cache.timestamp<bF?this.cache.agents:this.scanInFlight?this.scanInFlight:(this.scanInFlight=this.runScanAsync().finally(()=>{this.scanInFlight=null}),this.scanInFlight)}async runScanAsync(){await pde();let n=[...await Promise.all(Object.values(Hs).map(r=>this.detectBackendAsync(r)))];if(this.configStore?.customAgents){let r=await Promise.all(Object.values(this.configStore.customAgents).map(o=>this.detectCustomAgentAsync(o)));n.push(...r)}return this.cache={agents:n,timestamp:Date.now()},n}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let n=ide(e),r=n?FF(n)??vF(n)??yF(Eo(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}async detectBackendAsync(e){let n=await ade(e),r=n?await HF(n)??vF(n)??yF(Eo(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}assembleBackendDescriptor(e,n,r){let o=this.hasAgentConfig(e.id);return n?e.id==="copilot"&&!r?{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}:{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"available",cliPath:n,version:r??void 0,authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:e.id==="claude"||e.id==="goose"||e.id==="copilot",supportsUsageUpdate:e.id==="claude"||e.id==="codex"||e.id==="copilot",skillsDirs:e.skillsDirs}}:{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}}}detectCustomAgent(e){return this.assembleCustomAgentDescriptor(e,MP(e.cliCommand))}async detectCustomAgentAsync(e){return this.assembleCustomAgentDescriptor(e,await DP(e.cliCommand))}assembleCustomAgentDescriptor(e,n){let r=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:n?"available":"not_installed",cliPath:n??void 0,authRequired:e.authRequired??!1,hasConfig:r,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let n=this.configStore.agents[e];return!!(n?.apiKey||n?.baseUrl||n?.customCliPath)}buildSelfDescriptor(){let e=["QLOGIC_LLMROUTER_USER_ID","QLOGIC_IMPLICIT_OWNER_ID","QLOGIC_DEVICE_ID","QLOGICAGENT_HOME","QLOGIC_LLMROUTER_BASE_URL","QLOGIC_LLMROUTER_ACCESS_TOKEN"],n={};for(let r of e){let o=process.env[r];o&&(n[r]=o)}return{id:"qlogicagent",cliPath:process.execPath,acpArgs:[process.argv[1]??""],env:Object.keys(n).length>0?n:void 0,protocol:"acp"}}buildExternalDescriptor(e){if(e==="qlogicagent")return this.buildSelfDescriptor();let n=this.list().find(m=>m.id===e);if(!n||n.protocol!=="acp"||n.status!=="available"||!n.cliPath)return null;let r=Eo(e)??Hs[e],o=this.configStore?.agents[e],i=this.configStore?.customAgents?.[e],s=o?.customArgs?.length?o.customArgs:i?.acpArgs??r?.acpArgs??[],a=o?.customCliPath?{cliPath:o.customCliPath,acpArgs:s}:fde(n.cliPath,s),c=o?.authPreference??"auto",l=TF(r,this.keySources,c),d=o?.customArgs?.length?a.acpArgs:wde(r,a.acpArgs,l,this.keySources,c),p=r?kde(r,c,this.keySources):[];return{id:e,cliPath:a.cliPath,acpArgs:d,env:hde(r,o,l),suppressEnvKeys:p.length>0?p:void 0,protocol:"acp"}}getNativeLoginState(e){if(e!=="qlogicagent")return this.keySources.hasSubscription?.(e)}isAgentReady(e){if(e==="qlogicagent")return!0;let n=this.buildExternalDescriptor(e);if(!n)return!1;let r=Eo(e)??Hs[e],o=this.configStore?.agents[e]?.authPreference??"auto";return(r?Cg(r,o):o)==="account"||r?.authMode==="oauth"||r?.keySource==="none"?this.keySources.hasSubscription?.(e)!==!1:r&&RF(r)?xF(n.env,r):!0}resolveCredentialError(e){if(e==="qlogicagent")return null;let n=Eo(e)??Hs[e];if(!n)return null;let r=this.configStore?.agents[e]?.authPreference??"auto",o=Cg(n,r);if(o==="account"||n.authMode==="oauth"||n.keySource==="none"){if(this.keySources.hasSubscription?.(e)===!1){let s=n.name??e,a=n.install?.setupCommand;return a?`${s} \u9700\u8981\u5148\u5B8C\u6210\u767B\u5F55/\u8BBE\u7F6E: \u8BF7\u8FD0\u884C ${a}\u3002`:`${s} \u9700\u8981\u5148\u5B8C\u6210\u767B\u5F55/\u8BBE\u7F6E\u3002`}return null}if(!RF(n)||xF(TF(n,this.keySources,r),n))return null;let i=n.name??e;return o==="managed"?`${i} \u7684\u300C\u5E73\u53F0\u989D\u5EA6\u300D\u6682\u4E0D\u53EF\u7528:\u672A\u83B7\u53D6\u5230\u5E73\u53F0\u63A8\u7406\u5BC6\u94A5(\u8BF7\u786E\u8BA4\u8D26\u53F7\u5DF2\u767B\u5F55;\u79BB\u7EBF\u65F6\u5E73\u53F0\u989D\u5EA6\u4E0D\u53EF\u7528)\u3002`:`${i} \u7F3A\u5C11\u53EF\u7528\u7684 API Key:\u8BF7\u5728\u300C\u53C2\u6570\u914D\u7F6E \u2192 \u51ED\u636E\u6765\u6E90\u300D\u586B\u5165\u5B98\u65B9 Key,\u6216\u5207\u6362\u5230\u300C\u5E73\u53F0\u989D\u5EA6\u300D\u3002`}};function GF(t,e){if(e!=="qlogicagent")try{let n=t.buildExternalDescriptor(e),r=WF[e]??"OPENAI_MODEL";return n?.env?.[r]??n?.env?.OPENAI_MODEL}catch{return}}var qd="https://registry.npmmirror.com",hc="https://pypi.tuna.tsinghua.edu.cn/simple",LP="https://registry.npmmirror.com/-/binary";function KF(){return{npm_config_registry:qd,PIP_INDEX_URL:hc,UV_DEFAULT_INDEX:hc,UV_INDEX_URL:hc,UV_PYTHON_INSTALL_MIRROR:`${LP}/python-build-standalone`,NODEJS_ORG_MIRROR:`${LP}/node`,npm_config_disturl:`${LP}/node`}}var UP=Object.keys(KF());import{readFileSync as Ede}from"node:fs";import{randomUUID as Mde}from"node:crypto";de();Pa();import{readdirSync as Sde,readFileSync as xde,statSync as FP,writeFileSync as Rde}from"node:fs";import{join as Wd}from"node:path";var Tde=["auto-skill-","test-skill-"],Ade=".skills_prompt_snapshot.json";function Pde(t){return Tde.some(e=>t.startsWith(e))}function Ide(t){let e=t.replace(/\r\n/g,`
|
|
686
|
+
${t?.data?.details??""}`;return/\b(auth(?:entication|orization)?|login|log in|api key|apikey|token|credential|provider|configured|configuration|setup|sign in)\b/i.test(e)}function Hle(t){let e=t;if(!e||typeof e.message!="string")return t;let n=e.data,r=typeof n=="string"?n:typeof n?.details=="string"?n.details:typeof n?.error=="string"?n.error:typeof n?.message=="string"?n.message:"";if(!r||e.message.includes(r))return t;let o=new Error(`${e.message}: ${r}`);return o.name=t instanceof Error?t.name:"Error",Object.assign(o,{code:e.code,data:e.data}),o}var Pi=class{conn=null;child=null;onNotification=null;hostHandler=null;attach(e,n,r){if(this.child=e,this.onNotification=n??null,this.hostHandler=r??null,!e.stdin||!e.stdout)throw new Error("ACP adapter: child process has no stdio");let o=lF(Ole.toWeb(e.stdin),Nle.toWeb(e.stdout)),i=o.readable.pipeThrough(new TransformStream({transform:(s,a)=>{this.consumeExtensionNotification(s)||a.enqueue(s)}}));this.conn=new Tg(()=>this.buildClient(),{readable:i,writable:o.writable})}consumeExtensionNotification(e){let n=e;if(!n||n.method!=="session/update"||n.id!==void 0)return!1;let r=n.params?.update?.sessionUpdate;if(typeof r!="string"||!r.startsWith("x_"))return!1;try{this.onNotification?.("session/update",n.params)}catch{}return!0}buildClient(){let e=()=>this.hostHandler,n=(r,o)=>this.onNotification?.(r,o);return{async sessionUpdate(r){n("session/update",r)},async requestPermission(r){let o=e(),s=(o?.requestPermission?await o.requestPermission(r):{optionId:"allow"})?.optionId;return s?{outcome:{outcome:"selected",optionId:s}}:{outcome:{outcome:"cancelled"}}},async readTextFile(r){return{content:(await e()?.readTextFile?.(r))?.content??""}},async writeTextFile(r){return await e()?.writeTextFile?.(r),{}},async createTerminal(r){return await e()?.createTerminal?.(r)??{terminalId:""}},async terminalOutput(r){return await e()?.terminalOutput?.(r)??{output:"",truncated:!1}},async releaseTerminal(r){return await e()?.releaseTerminal?.(r),{}},async waitForTerminalExit(r){return await e()?.waitForTerminalExit?.(r)??{}},async killTerminal(r){return await e()?.killTerminal?.(r),{}},async extMethod(r,o){return await e()?.extMethod?.(r,o)??{}},async extNotification(r,o){n(r,o)}}}detach(){this.conn=null,this.hostHandler=null,this.onNotification=null,this.child=null}requireConn(){if(!this.conn)throw new Error("ACP adapter not attached");return this.conn}async withTimeout(e,n,r,o){let i,s=new Promise((a,c)=>{i=setTimeout(()=>{try{o?.()}catch{}c(new Error(`ACP ${r} timeout (${n}ms)`))},n)});try{return await Promise.race([e,s])}finally{i&&clearTimeout(i)}}async initialize(e){let n={protocolVersion:jle,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}},clientInfo:{name:"qlogicagent",version:"1.0.0"}},r=await this.withTimeout(this.requireConn().initialize(n),Lle,"initialize").catch(i=>{throw Ud(i)??i}),o=r?.agentCapabilities??{};return{protocolVersion:typeof r?.protocolVersion=="number"?r.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities,qlogicagent:o.qlogicagent},agentInfo:r?.agentInfo,authMethods:r?.authMethods}}async createSession(e,n){let r={cwd:n.cwd,mcpServers:n.mcpServers??[]};n.additionalDirectories?.length&&(r.additionalDirectories=n.additionalDirectories),n.systemPrompt&&(r._meta={qlogicagent:{systemPrompt:n.systemPrompt}});let o=await this.withTimeout(this.requireConn().newSession(r),uF,"session/new").catch(i=>{throw Ud(i)??i});if(typeof o?.sessionId!="string")throw new Error("ACP session/new: agent did not return sessionId");return{sessionId:o.sessionId}}async sendPrompt(e,n,r,o=Ule){let i=this.requireConn(),s=await this.withTimeout(i.prompt({sessionId:n,prompt:[{type:"text",text:r}]}),o,"session/prompt",()=>{i.cancel({sessionId:n}).catch(()=>{})}).catch(a=>{throw Ud(a)??Hle(a)});return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:void 0}}async resumeSession(e,n,r){let o={sessionId:n,cwd:r?.cwd??process.cwd(),mcpServers:r?.mcpServers??[]},i=await this.withTimeout(this.requireConn().loadSession(o),uF,"session/load");return{sessionId:typeof i?.sessionId=="string"?i.sessionId:n}}static translateNotification(e,n){let r=n;if(e==="session/update"){if(!r)return null;let o=r.update;if(!o)return null;let i=o.sessionUpdate,s=r.sessionId;switch(i){case wr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case wr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case wr.TOOL_CALL:return{method:"turn.tool_call",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"running",content:o.content,kind:o.kind,rawInput:o.rawInput,sessionId:s}};case wr.TOOL_CALL_UPDATE:return{method:"turn.tool_result",params:{callId:o.toolCallId,toolName:o.title,status:o.status??"completed",content:o.content,rawOutput:o.rawOutput,sessionId:s}};case wr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case wr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case wr.AVAILABLE_COMMANDS_UPDATE:case wr.CURRENT_MODE_UPDATE:case wr.CONFIG_OPTION_UPDATE:case wr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case wr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as zle}from"node:child_process";import{readFile as Ble,writeFile as qle}from"node:fs/promises";import{isAbsolute as pF,normalize as Wle,relative as Gle,resolve as Kle,sep as Vle}from"node:path";function Jle(t){let e=t.options;if(!Array.isArray(e)||e.length===0)return"allow";let n=e.filter(c=>!!c&&typeof c=="object"),r=c=>typeof c.optionId=="string"&&c.optionId.trim()?c.optionId:void 0;if(n.find(c=>r(c)==="allow"))return"allow";let i=n.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/allow/i.test(l)}),s=i?r(i):void 0;if(s)return s;let a=n.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/reject|deny|cancel/i.test(l)});return r(a??{})??r(n[0]??{})??"allow"}function PP(t){let e=new Map,n=0,r=i=>{let s=pF(i)?Wle(i):Kle(t.cwd,i),a=Gle(t.cwd,s);if(a===".."||a.startsWith(`..${Vle}`)||pF(a))throw new Error(`path escapes cwd: ${i}`);return s},o=i=>String(i.terminalId??"");return{async requestPermission(i){return t.requestPermission?t.requestPermission(i):{optionId:Jle(i)}},async readTextFile(i){return{content:await Ble(r(i.path),"utf8")}},async writeTextFile(i){return await qle(r(i.path),i.content,"utf8"),{}},async createTerminal(i){let s=String(i.command??""),a=i.args,c=Array.isArray(a)?a.map(String):[],l=i.cwd,d=l?r(String(l)):t.cwd,p=i.env,m={...process.env,...p&&typeof p=="object"?p:{}},f=zle(s,c,{cwd:d,env:m,stdio:["ignore","pipe","pipe"],windowsHide:!0}),g=`term-${++n}`,h={child:f,output:"",exitStatus:null,exit:new Promise(y=>{f.on("exit",(b,v)=>{let k={exitCode:b,signal:v};h.exitStatus=k,y(k)}),f.on("error",()=>{let b={exitCode:null,signal:null};h.exitStatus=b,y(b)})})};return f.stdout?.on("data",y=>{h.output+=y.toString()}),f.stderr?.on("data",y=>{h.output+=y.toString()}),e.set(g,h),{terminalId:g}},async terminalOutput(i){let s=e.get(o(i));return s?{output:s.output,truncated:!1,exitStatus:s.exitStatus}:{output:"",truncated:!1,exitStatus:null}},async waitForTerminalExit(i){let s=e.get(o(i));return s?s.exit:{exitCode:null,signal:null}},async releaseTerminal(i){let s=o(i),a=e.get(s);if(a&&a.child.exitCode===null&&a.child.signalCode===null)try{a.child.kill()}catch{}return e.delete(s),{}},async killTerminal(i){let s=e.get(o(i));if(s)try{s.child.kill("SIGKILL")}catch{}return{}},disposeAll(){for(let i of e.values())try{i.child.kill("SIGKILL")}catch{}e.clear()}}}var Fd=class{usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0};onUsageUpdate(e){this.usage.hasTier1=!0,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cost=="number"&&(this.usage.cost+=e.cost)}onPromptResponseUsage(e){e&&(this.usage.hasTier1||(this.usage.turnCount++,typeof e.inputTokens=="number"&&(this.usage.inputTokens+=e.inputTokens),typeof e.outputTokens=="number"&&(this.usage.outputTokens+=e.outputTokens),typeof e.totalTokens=="number"&&(this.usage.totalTokens+=e.totalTokens),typeof e.cachedReadTokens=="number"&&(this.usage.cachedReadTokens+=e.cachedReadTokens),typeof e.thoughtTokens=="number"&&(this.usage.thoughtTokens+=e.thoughtTokens)))}getUsage(){return{...this.usage}}reset(){this.usage={inputTokens:0,outputTokens:0,totalTokens:0,cachedReadTokens:0,thoughtTokens:0,cost:0,hasTier1:!1,turnCount:0}}hasData(){return this.usage.hasTier1||this.usage.turnCount>0}};import{exec as Xle,execFile as Yle,execFileSync as mF,execSync as AF}from"node:child_process";import{existsSync as Ei,mkdirSync as PF,readFileSync as gc,readdirSync as IF,writeFileSync as _F}from"node:fs";import{homedir as NP,platform as Qle,tmpdir as ede}from"node:os";import{dirname as Hd,join as bt}from"node:path";import{promisify as CF}from"node:util";function Ii(){let t=process.env.XIAOZHICLAW_NODE_EXE,e=process.env.XIAOZHICLAW_NPM_CLI;return!t||!e?null:{nodeExe:t,npmCli:e,prefix:process.env.XIAOZHICLAW_NPM_GLOBAL_PREFIX||void 0}}function _i(t){let e={...process.env,ELECTRON_RUN_AS_NODE:"1"};return t.prefix&&(e.npm_config_prefix=t.prefix),e}function IP(t){let e=t.trim().split(/\s+/)[0];return e==="npm"||e==="npm.cmd"}var Zle=/^(?:pip3?|pipx|uv|uvx|python3?|curl|wget|brew|sh|bash)\b/;function _P(t){return Zle.test(t.trim())}function CP(){let t={...process.env};return delete t.ELECTRON_RUN_AS_NODE,t}var fF=CF(Yle),EF=CF(Xle),Hs={claude:{id:"claude",name:"Claude Code",cliCommand:"claude-agent-acp",acpArgs:[],authRequired:!0,skillsDirs:[".claude/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"ANTHROPIC_API_KEY",baseUrlEnvVar:"ANTHROPIC_BASE_URL"},codex:{id:"codex",name:"OpenAI Codex CLI",cliCommand:"codex-acp",acpArgs:["-c","sandbox_mode=danger-full-access","-c","approval_policy=untrusted"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENAI_API_KEY",baseUrlEnvVar:"OPENAI_BASE_URL"},qwen:{id:"qwen",name:"Qwen Code",cliCommand:"qwen",acpArgs:["--acp","--experimental-skills"],defaultCliPath:"npx @qwen-code/qwen-code",authRequired:!0,skillsDirs:[".qwen/skills"],supportsBaseUrlOverride:!0,apiKeyEnvVar:"DASHSCOPE_API_KEY"},kimi:{id:"kimi",name:"Kimi CLI",cliCommand:"kimi",acpArgs:["acp"],authRequired:!0,skillsDirs:[".kimi/skills"],supportsBaseUrlOverride:!1},opencode:{id:"opencode",name:"OpenCode",cliCommand:"opencode",acpArgs:["acp"],authRequired:!1,skillsDirs:[".opencode/skills"],supportsBaseUrlOverride:!0},cursor:{id:"cursor",name:"Cursor Agent",cliCommand:"cursor-agent",acpArgs:["acp"],authRequired:!0,skillsDirs:[".cursor/skills"],supportsBaseUrlOverride:!1},hermes:{id:"hermes",name:"Hermes Agent",cliCommand:"hermes",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},copilot:{id:"copilot",name:"GitHub Copilot",cliCommand:"copilot",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!1},codebuddy:{id:"codebuddy",name:"CodeBuddy",cliCommand:"codebuddy",acpArgs:["--acp"],authRequired:!0,skillsDirs:[".codebuddy/skills"],supportsBaseUrlOverride:!0},kiro:{id:"kiro",name:"Kiro CLI",cliCommand:"kiro-cli",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0},snow:{id:"snow",name:"Snow",cliCommand:"snow",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},qoder:{id:"qoder",name:"Qoder",cliCommand:"qodercli",acpArgs:["--acp"],authRequired:!0,supportsBaseUrlOverride:!0},gemini:{id:"gemini",name:"Gemini CLI",cliCommand:"gemini",acpArgs:["--experimental-acp"],defaultCliPath:"npx @google/gemini-cli",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"GEMINI_API_KEY",baseUrlEnvVar:"GOOGLE_GEMINI_BASE_URL"},glm:{id:"glm",name:"GLM Agent",cliCommand:"glm-acp-agent",acpArgs:[],defaultCliPath:"npx glm-acp-agent",authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"Z_AI_API_KEY",baseUrlEnvVar:"ACP_GLM_BASE_URL"},cline:{id:"cline",name:"Cline",cliCommand:"cline",acpArgs:["--acp"],defaultCliPath:"npx cline",authRequired:!0,supportsBaseUrlOverride:!0},nova:{id:"nova",name:"Nova",cliCommand:"nova",acpArgs:["acp"],defaultCliPath:"npx @compass-ai/nova",authRequired:!0,supportsBaseUrlOverride:!0},openclaw:{id:"openclaw",name:"OpenClaw",cliCommand:"openclaw",acpArgs:["acp"],authRequired:!0,supportsBaseUrlOverride:!0,apiKeyEnvVar:"OPENCLAW_API_KEY",baseUrlEnvVar:"OPENCLAW_BASE_URL"}},tde=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],gF={claude:{brandId:"claude",category:"coding",integration:"acp",keySource:"llmrouter",authMode:"key",install:{npm:"npm i -g @agentclientprotocol/claude-agent-acp",cliCommand:"claude-agent-acp",docsUrl:"https://github.com/agentclientprotocol/claude-agent-acp"},strengths:"\u590D\u6742\u63A8\u7406\u3001\u91CD\u6784\u3001\u957F\u94FE\u8DEF\u5B9E\u73B0"},codex:{brandId:"codex",category:"coding",integration:"acp",keySource:"llmrouter",authMode:"key",install:{npm:"npm i -g @zed-industries/codex-acp",cliCommand:"codex-acp",verifyCmd:"codex-acp --help",docsUrl:"https://github.com/zed-industries/codex-acp"},strengths:"\u4EE3\u7801\u751F\u6210\u3001\u8C03\u8BD5\u3001shell/\u5DE5\u5177\u94FE"},gemini:{brandId:"gemini",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @google/gemini-cli",cliCommand:"gemini",docsUrl:"https://github.com/google-gemini/gemini-cli"},strengths:"\u591A\u6A21\u6001\u3001\u957F\u4E0A\u4E0B\u6587\u3001\u7EFC\u5408\u5B9E\u73B0"},copilot:{brandId:"copilot",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9ED8\u8BA4\u9700 GitHub \u8D26\u53F7(\u4E5F\u652F\u6301 BYOK \u81EA\u5E26 key,\u540E\u7EED\u53EF\u63A5\u5165\u514D\u767B\u5F55\u6CE8\u5165)",install:{npm:"npm i -g @github/copilot",cliCommand:"copilot",setupCommand:"copilot",docsUrl:"https://docs.github.com/copilot/concepts/agents/about-copilot-cli"},strengths:"\u901A\u7528\u7F16\u7801\u3001GitHub \u751F\u6001"},cursor:{brandId:"cursor",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9700 Cursor \u8D26\u53F7",install:{curl:"curl https://cursor.com/install -fsS | bash",cliCommand:"cursor-agent",setupCommand:"cursor-agent login",docsUrl:"https://cursor.com/cli"},strengths:"\u901A\u7528\u7F16\u7801\u3001IDE \u96C6\u6210"},qwen:{brandId:"qwen",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @qwen-code/qwen-code",cliCommand:"qwen",docsUrl:"https://github.com/QwenLM/qwen-code"},strengths:"\u524D\u7AEF/UI\u3001\u4EA4\u4E92\u5B9E\u73B0\u3001\u901A\u7528\u7F16\u7801"},kimi:{brandId:"kimi",category:"coding",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9700 Kimi \u8D26\u53F7(\u5728\u7EC8\u7AEF\u8FD0\u884C kimi login \u767B\u5F55)",install:{pip:"uv tool install kimi-cli",cliCommand:"kimi",setupCommand:"kimi login",docsUrl:"https://github.com/MoonshotAI/kimi-cli"},strengths:"\u957F\u4E0A\u4E0B\u6587\u3001\u4E2D\u6587\u573A\u666F"},glm:{brandId:"glm",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g glm-acp-agent",cliCommand:"glm-acp-agent",docsUrl:"https://github.com/stefandevo/glm-acp-agent"},strengths:"\u901A\u7528\u7F16\u7801\u3001\u4E2D\u6587\u573A\u666F"},opencode:{brandId:"opencode",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g opencode-ai",cliCommand:"opencode",docsUrl:"https://opencode.ai/docs"},strengths:"\u7B97\u6CD5\u3001\u6570\u636E\u7ED3\u6784\u3001\u590D\u6742\u903B\u8F91"},kiro:{brandId:"kiro",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{cliCommand:"kiro-cli",docsUrl:"https://kiro.dev/docs"},strengths:"\u901A\u7528\u7F16\u7801"},qoder:{brandId:"qoder",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{npm:"npm i -g @qoder-ai/qodercli",cliCommand:"qodercli",docsUrl:"https://docs.qoder.com/cli/acp"},strengths:"\u901A\u7528\u7F16\u7801"},openclaw:{brandId:"openclaw",category:"assistant",integration:"acp",keySource:"direct",authMode:"key",note:"\u9AD8\u7EA7:\u9700\u81EA\u5907\u8FD0\u884C\u4E2D\u7684 openclaw Gateway + \u6709\u6548 ~/.openclaw \u914D\u7F6E(openclaw acp = \u6302\u5728 Gateway \u4E0A\u7684 ACP \u6865)",install:{npm:"npm i -g openclaw",cliCommand:"openclaw",setupCommand:"openclaw onboard",docsUrl:"https://github.com/openclaw/openclaw"},strengths:"\u52A9\u7406/\u7F16\u6392\u3001\u901A\u7528"},hermes:{brandId:"hermes",category:"assistant",integration:"acp",keySource:"none",authMode:"oauth",note:"\u9996\u6B21\u9700\u5728\u7EC8\u7AEF\u8FD0\u884C hermes acp --setup \u914D\u7F6E provider/model",install:{pip:"uv tool install hermes-agent[acp] --python 3.13",cliCommand:"hermes",setupCommand:"hermes acp --setup",docsUrl:"https://github.com/NousResearch/hermes-agent"},strengths:"\u52A9\u7406\u3001\u901A\u7528"}};function Eo(t){let e=Hs[t];if(e)return gF[t]?{...e,...gF[t]}:e}function zd(){return tde.map(t=>{let e=Eo(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Mo=Qle()==="win32",MF=5*6e4,nde=2e4,Ci,mc=new Map,EP=bt(process.env.QLOGICAGENT_HOME||bt(NP(),".qlogicagent"),"agent-update-cache.json"),hF=!1;function DF(){if(!hF){hF=!0;try{let t=JSON.parse(gc(EP,"utf8"));for(let[e,n]of Object.entries(t))n&&typeof n.timestamp=="number"&&!mc.has(e)&&mc.set(e,n)}catch{}}}var Ag=null;function rde(){Ag||(Ag=setTimeout(()=>{Ag=null;try{let t={};for(let[e,n]of mc)t[e]=n;PF(Hd(EP),{recursive:!0}),_F(EP,JSON.stringify(t),"utf8")}catch{}},1e3),Ag.unref?.())}function MP(t){try{let e=Mo?`where ${t}`:`which ${t}`;return AF(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}async function DP(t){try{let e=Mo?`where ${t}`:`which ${t}`,{stdout:n}=await EF(e,{encoding:"utf8",timeout:5e3,windowsHide:!0});return String(n).split(/\r?\n/)[0]?.trim()||null}catch{return null}}function $F(t,e){let n=i=>{let s=i.match(/^(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r[i]!==o[i])return o[i]-r[i];return e.localeCompare(t)}function ode(){if(!Mo)return null;let t=[process.env.COPILOT_CACHE_HOME?bt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?bt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?bt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,bt(NP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=IF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort($F);for(let r of n){let o=bt(e,r,"npm-loader.js");if(Ei(o)&&FF(o))return o}}catch{}return null}function ide(t){return t.id==="copilot"?ode()??MP(t.cliCommand):MP(t.cliCommand)}async function sde(){if(!Mo)return null;let t=[process.env.COPILOT_CACHE_HOME?bt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?bt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?bt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,bt(NP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=IF(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort($F);for(let r of n){let o=bt(e,r,"npm-loader.js");if(Ei(o)&&await HF(o))return o}}catch{}return null}async function ade(t){return t.id==="copilot"?await sde()??await DP(t.cliCommand):DP(t.cliCommand)}function cde(t,e){let n=Ii();return n?mF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],env:_i(n),windowsHide:!0}).trim():mF(Mo?"cmd.exe":"npm",Mo?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()}async function NF(t,e){let n=Ii();if(n){let{stdout:o}=await fF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,env:_i(n)});return o.trim()}let{stdout:r}=await fF(Mo?"cmd.exe":"npm",Mo?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function lde(t){let e=t.trim().replace(/^["']|["']$/g,"");if(!e||e.startsWith("-"))return null;if(e.startsWith("@")){let r=e.indexOf("@",1);return r>0?e.slice(0,r):e}let n=e.indexOf("@");return n>0?e.slice(0,n):e}function Eg(t){if(!t)return null;let e=t.trim().split(/\s+/).filter(Boolean);if(e[0]!=="npm"&&e[0]!=="npm.cmd")return null;let n=e.findIndex(r=>r==="i"||r==="install"||r==="add");if(n<0)return null;for(let r=n+1;r<e.length;r+=1){let o=e[r];if(!(o==="-g"||o==="--global")){if(o.startsWith("--")&&!o.includes("=")){r+=1;continue}if(!o.startsWith("-"))return lde(o)}}return null}function Bd(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function dde(t,e){let n=i=>{let s=Bd(i)??i,[a,c=""]=s.replace(/^v/,"").split("-",2),l=a.split(".").map(d=>Number.parseInt(d,10)||0);for(;l.length<3;)l.push(0);return{nums:l,pre:c}},r=n(t),o=n(e);for(let i=0;i<3;i+=1)if(r.nums[i]!==o.nums[i])return r.nums[i]-o.nums[i];return r.pre===o.pre?0:r.pre?o.pre?r.pre.localeCompare(o.pre):-1:1}function OF(t,e){return!t||!e?!1:dde(t,e)>0}function ude(){if(Ci!==void 0)return Ci;try{Ci=cde(["root","-g"],3e3)||null}catch{Ci=null}return Ci}async function pde(){if(Ci===void 0)try{Ci=await NF(["root","-g"],3e3)||null}catch{Ci=null}}function Mg(t){if(!t)return null;let e=ude();if(!e)return null;let n=bt(e,...t.split("/"),"package.json");try{let r=JSON.parse(gc(n,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}function yF(t){let e=Eg(t?.npm);return Mg(e)}function jF(t,e){return Mg(Eg(t.install?.npm))??Bd(e)??e??void 0}async function mde(t,e){if(!t)return null;DF();let n=e?`${t}\0${e}`:t,r=mc.get(n);if(r){let i=r.version?MF:nde;if(Date.now()-r.timestamp<i)return r.version}let o=null;try{let i=["view",t,"version","--json"];e&&i.push("--registry",e);let s=await NF(i,12e3),a=s?JSON.parse(s):null;o=typeof a=="string"?a:Bd(s)}catch{o=null}return mc.set(n,{timestamp:Date.now(),version:o}),rde(),o}async function LF(t,e){let n=t.map(async({id:o,entry:i,detectedVersion:s})=>{let a=Eg(i.install?.npm),c=Mg(a)??Bd(s)??s??void 0;if(!a||!c)return null;let l=await mde(a,e)??void 0;return l?{id:o,packageName:a,installedVersion:c,latestVersion:l,updateAvailable:OF(l,c)}:null});return(await Promise.all(n)).filter(o=>o!==null)}function UF(t,e){DF();let n=[],r=!1;for(let{id:o,entry:i,detectedVersion:s}of t){let a=Eg(i.install?.npm),c=Mg(a)??Bd(s)??s??void 0;if(!a||!c)continue;let l=e?`${a} ${e}`:a,d=mc.get(l);d?.version&&Date.now()-d.timestamp<MF||(r=!0),d?.version&&n.push({id:o,packageName:a,installedVersion:c,latestVersion:d.version,updateAvailable:OF(d.version,c)})}return{updates:n,stale:r}}function FF(t){let e=t.endsWith("npm-loader.js");for(let n of["--version","version","-v"])try{let r=e?`"${process.execPath}" "${t}" ${n}`:`"${t}" ${n}`,i=AF(r,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().match(/(\d+\.\d+(?:\.\d+)?[\w.-]*)/);if(i?.[1])return i[1]}catch{}return null}async function HF(t){let e=t.endsWith("npm-loader.js");for(let n of["--version","version","-v"])try{let r=e?`"${process.execPath}" "${t}" ${n}`:`"${t}" ${n}`,{stdout:o}=await EF(r,{encoding:"utf8",timeout:5e3,windowsHide:!0}),i=String(o).trim().match(/(\d+\.\d+(?:\.\d+)?[\w.-]*)/);if(i?.[1])return i[1]}catch{}return null}function fde(t,e){if(!Mo)return{cliPath:t,acpArgs:e};if(t.endsWith("npm-loader.js")){let o=e.includes("--no-auto-update");return{cliPath:process.execPath,acpArgs:[t,...e,...o?[]:["--no-auto-update"]]}}let n=zF(t);if(n)return{cliPath:process.execPath,acpArgs:[n,...e]};let r=gde(t);return r?{cliPath:r,acpArgs:e}:{cliPath:t,acpArgs:e}}function zF(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ei(r))continue;let o;try{o=gc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=bt(Hd(e),s);if(Ei(a))return a}return null}function gde(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Ei(r))continue;let o;try{o=gc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.exe)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=bt(Hd(e),s);if(Ei(a))return a}return null}function vF(t){let e=zF(t);if(!e)return null;let n=Hd(e);for(let r=0;r<6;r+=1){let o=bt(n,"package.json");try{if(Ei(o)){let s=JSON.parse(gc(o,"utf8"));if(typeof s.version=="string"&&s.version)return s.version}}catch{}let i=Hd(n);if(i===n)break;n=i}return null}var bF=6e4;function hde(t,e,n){let r={};return t?.env&&Object.assign(r,t.env),n&&Object.assign(r,n),t?.apiKeyEnvVar&&e?.apiKey&&(r[t.apiKeyEnvVar]=e.apiKey),t?.baseUrlEnvVar&&e?.baseUrl&&(r[t.baseUrlEnvVar]=e.baseUrl),e?.env&&Object.assign(r,e.env),Object.keys(r).length>0?r:void 0}var BF=new Set(["codex","qwen","opencode"]),Ig=new Set(["qwen","opencode"]),_g=new Set(["gemini"]),$P=new Set(["glm"]),kF={claude:"anthropic",codex:"openai"};function yde(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function vde(t){let e=bt(ede(),"qlogicagent-codex-model-catalog");PF(e,{recursive:!0});let n=bt(e,`${yde(t)}.json`),r=JSON.stringify({models:[{slug:t,display_name:t,supported_reasoning_levels:[],shell_type:"shell_command",visibility:"list",priority:0,base_instructions:"You are Codex, a coding agent. Follow the user's instructions and use tools only when needed.",supports_reasoning_summaries:!1,support_verbosity:!1,truncation_policy:{mode:"tokens",limit:1e6},supports_parallel_tool_calls:!1,experimental_supported_tools:[],supported_in_api:!0}]});return(!Ei(n)||gc(n,"utf8")!==r)&&_F(n,r,"utf8"),n}function OP(t){return t.id!=="claude"}function Cg(t,e){return e==="account"&&!OP(t)?"auto":e}function qF(t){if(t.authMode==="oauth"||t.keySource==="none")return["account"];let e=[];return t.keySource==="llmrouter"&&OP(t)&&e.push("account"),e.push("userKey"),(t.keySource==="llmrouter"||Ig.has(t.id)||_g.has(t.id)||$P.has(t.id))&&e.push("managed"),e}function jP(t,e,n){let r=Cg(t,e);return!!(r==="account"||r==="auto"&&OP(t)&&n?.hasSubscription?.(t.id)===!0)}var WF={claude:"ANTHROPIC_MODEL",codex:"OPENAI_MODEL",glm:"ACP_GLM_MODEL"},bde={glm:"ACP_GLM_AVAILABLE_MODELS"};function Pg(t,e,n){let{apiKeyEnvVar:r,baseUrlEnvVar:o}=t;r&&e.llmrouterKey&&(n[r]=e.llmrouterKey);let i=e.getLlmrouterBaseUrl?.(t.id,t)??e.llmrouterBaseUrl;o&&i&&(n[o]=i);let s=WF[t.id];s&&e.llmrouterModel&&(n[s]=e.llmrouterModel);let a=bde[t.id];a&&e.llmrouterModel&&(n[a]=e.llmrouterModel)}function wF(t,e,n){e.llmrouterKey&&(n.OPENAI_API_KEY=e.llmrouterKey);let r=e.getLlmrouterBaseUrl?.(t.id,t)??e.llmrouterBaseUrl;r&&(n.OPENAI_BASE_URL=r),e.llmrouterModel&&(n.OPENAI_MODEL=e.llmrouterModel)}var SF=["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_GEMINI_API_KEY","GEMINI_API_KEY"];function xF(t,e){return t?(e.apiKeyEnvVar?[e.apiKeyEnvVar,...SF]:SF).some(r=>typeof t[r]=="string"&&t[r].trim().length>0):!1}function RF(t){return!!t.apiKeyEnvVar||Ig.has(t.id)||_g.has(t.id)}function TF(t,e,n="auto"){let r={};if(!t)return r;let o=Cg(t,n);if(o==="account"||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:i,baseUrlEnvVar:s}=t;if(o==="userKey"){let a=kF[t.id]??t.id,c=e.getDirectKey?.(a);return i&&c&&(r[i]=c),r}if(o==="managed")return t.keySource==="llmrouter"||_g.has(t.id)||$P.has(t.id)?Pg(t,e,r):Ig.has(t.id)&&wF(t,e,r),r;if(jP(t,"auto",e))return r;if(t.keySource==="llmrouter"){let a=kF[t.id],c=a?e.getDirectKey?.(a):void 0;i&&c?r[i]=c:Pg(t,e,r)}else if(t.keySource==="direct"){let a=e.getDirectKey?.(t.id);i&&a?r[i]=a:Ig.has(t.id)?wF(t,e,r):(_g.has(t.id)||$P.has(t.id))&&Pg(t,e,r)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&BF.has(t.id)){let a=e.passthroughModel;r.OPENAI_API_KEY=a.apiKey,a.baseUrl&&(r.OPENAI_BASE_URL=a.baseUrl),a.model&&(r.OPENAI_MODEL=a.model)}return r}function kde(t,e,n){if(!t||!jP(t,e,n))return[];let r=[];return t.apiKeyEnvVar&&r.push(t.apiKeyEnvVar),t.baseUrlEnvVar&&r.push(t.baseUrlEnvVar),BF.has(t.id)&&r.push("OPENAI_MODEL"),r}function wde(t,e,n,r,o="auto"){if(!t)return e;if(t.id==="qwen")return!n.OPENAI_API_KEY||e.some(a=>a==="--auth-type"||a.startsWith("--auth-type="))?e:[...e,"--auth-type=openai"];if(t.id==="gemini"){let a=r.llmrouterModel;return!n.GEMINI_API_KEY||!a||e.some(c=>c==="-m"||c==="--model"||c.startsWith("--model="))?e:[...e,"--model",a]}if(t.id!=="codex")return e;if(jP(t,o,r))return e.some(a=>a.includes("preferred_auth_method"))?e:[...e,"-c","preferred_auth_method=chatgpt"];if(t.keySource!=="llmrouter"||!n.OPENAI_API_KEY||e.some(a=>a.includes("model_provider")||a.includes("model_providers.")))return e;let i=n.OPENAI_BASE_URL,s=r.llmrouterModel||n.OPENAI_MODEL||"deepseek-v4-flash";return i?[...e,"-c","model_providers.llmrouter.name=llmrouter","-c",`model_providers.llmrouter.base_url=${i}`,"-c","model_providers.llmrouter.wire_api=responses","-c","model_providers.llmrouter.env_key=OPENAI_API_KEY","-c","model_provider=llmrouter","-c",`model=${s}`,"-c",`model_catalog_json=${vde(s)}`]:e}var fc=class{cache=null;configStore=null;keySources={};scanInFlight=null;setConfigStore(e){this.configStore=e}setKeySources(e){this.keySources=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<bF)return this.cache.agents;let n=[];for(let r of Object.values(Hs))n.push(this.detectBackend(r));if(this.configStore?.customAgents)for(let r of Object.values(this.configStore.customAgents))n.push(this.detectCustomAgent(r));return this.cache={agents:n,timestamp:Date.now()},n}async scanAsync(e=!1){return!e&&this.cache&&Date.now()-this.cache.timestamp<bF?this.cache.agents:this.scanInFlight?this.scanInFlight:(this.scanInFlight=this.runScanAsync().finally(()=>{this.scanInFlight=null}),this.scanInFlight)}async runScanAsync(){await pde();let n=[...await Promise.all(Object.values(Hs).map(r=>this.detectBackendAsync(r)))];if(this.configStore?.customAgents){let r=await Promise.all(Object.values(this.configStore.customAgents).map(o=>this.detectCustomAgentAsync(o)));n.push(...r)}return this.cache={agents:n,timestamp:Date.now()},n}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let n=ide(e),r=n?FF(n)??vF(n)??yF(Eo(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}async detectBackendAsync(e){let n=await ade(e),r=n?await HF(n)??vF(n)??yF(Eo(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}assembleBackendDescriptor(e,n,r){let o=this.hasAgentConfig(e.id);return n?e.id==="copilot"&&!r?{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}:{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"available",cliPath:n,version:r??void 0,authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:e.id==="claude"||e.id==="goose"||e.id==="copilot",supportsUsageUpdate:e.id==="claude"||e.id==="codex"||e.id==="copilot",skillsDirs:e.skillsDirs}}:{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:o,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}}}detectCustomAgent(e){return this.assembleCustomAgentDescriptor(e,MP(e.cliCommand))}async detectCustomAgentAsync(e){return this.assembleCustomAgentDescriptor(e,await DP(e.cliCommand))}assembleCustomAgentDescriptor(e,n){let r=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:n?"available":"not_installed",cliPath:n??void 0,authRequired:e.authRequired??!1,hasConfig:r,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let n=this.configStore.agents[e];return!!(n?.apiKey||n?.baseUrl||n?.customCliPath)}buildSelfDescriptor(){let e=["QLOGIC_LLMROUTER_USER_ID","QLOGIC_IMPLICIT_OWNER_ID","QLOGIC_DEVICE_ID","QLOGICAGENT_HOME","QLOGIC_LLMROUTER_BASE_URL","QLOGIC_LLMROUTER_ACCESS_TOKEN"],n={};for(let r of e){let o=process.env[r];o&&(n[r]=o)}return{id:"qlogicagent",cliPath:process.execPath,acpArgs:[process.argv[1]??""],env:Object.keys(n).length>0?n:void 0,protocol:"acp"}}buildExternalDescriptor(e){if(e==="qlogicagent")return this.buildSelfDescriptor();let n=this.list().find(m=>m.id===e);if(!n||n.protocol!=="acp"||n.status!=="available"||!n.cliPath)return null;let r=Eo(e)??Hs[e],o=this.configStore?.agents[e],i=this.configStore?.customAgents?.[e],s=o?.customArgs?.length?o.customArgs:i?.acpArgs??r?.acpArgs??[],a=o?.customCliPath?{cliPath:o.customCliPath,acpArgs:s}:fde(n.cliPath,s),c=o?.authPreference??"auto",l=TF(r,this.keySources,c),d=o?.customArgs?.length?a.acpArgs:wde(r,a.acpArgs,l,this.keySources,c),p=r?kde(r,c,this.keySources):[];return{id:e,cliPath:a.cliPath,acpArgs:d,env:hde(r,o,l),suppressEnvKeys:p.length>0?p:void 0,protocol:"acp"}}getNativeLoginState(e){if(e!=="qlogicagent")return this.keySources.hasSubscription?.(e)}isAgentReady(e){if(e==="qlogicagent")return!0;let n=this.buildExternalDescriptor(e);if(!n)return!1;let r=Eo(e)??Hs[e],o=this.configStore?.agents[e]?.authPreference??"auto";return(r?Cg(r,o):o)==="account"||r?.authMode==="oauth"||r?.keySource==="none"?this.keySources.hasSubscription?.(e)!==!1:r&&RF(r)?xF(n.env,r):!0}resolveCredentialError(e){if(e==="qlogicagent")return null;let n=Eo(e)??Hs[e];if(!n)return null;let r=this.configStore?.agents[e]?.authPreference??"auto",o=Cg(n,r);if(o==="account"||n.authMode==="oauth"||n.keySource==="none"){if(this.keySources.hasSubscription?.(e)===!1){let s=n.name??e,a=n.install?.setupCommand;return a?`${s} \u9700\u8981\u5148\u5B8C\u6210\u767B\u5F55/\u8BBE\u7F6E: \u8BF7\u8FD0\u884C ${a}\u3002`:`${s} \u9700\u8981\u5148\u5B8C\u6210\u767B\u5F55/\u8BBE\u7F6E\u3002`}return null}if(!RF(n)||xF(TF(n,this.keySources,r),n))return null;let i=n.name??e;return o==="managed"?`${i} \u7684\u300C\u5E73\u53F0\u989D\u5EA6\u300D\u6682\u4E0D\u53EF\u7528:\u672A\u83B7\u53D6\u5230\u5E73\u53F0\u63A8\u7406\u5BC6\u94A5(\u8BF7\u786E\u8BA4\u8D26\u53F7\u5DF2\u767B\u5F55;\u79BB\u7EBF\u65F6\u5E73\u53F0\u989D\u5EA6\u4E0D\u53EF\u7528)\u3002`:`${i} \u7F3A\u5C11\u53EF\u7528\u7684 API Key:\u8BF7\u5728\u300C\u53C2\u6570\u914D\u7F6E \u2192 \u51ED\u636E\u6765\u6E90\u300D\u586B\u5165\u5B98\u65B9 Key,\u6216\u5207\u6362\u5230\u300C\u5E73\u53F0\u989D\u5EA6\u300D\u3002`}};function GF(t,e){if(e!=="qlogicagent")try{let n=t.buildExternalDescriptor(e),r=WF[e]??"OPENAI_MODEL";return n?.env?.[r]??n?.env?.OPENAI_MODEL}catch{return}}var qd="https://registry.npmmirror.com",hc="https://pypi.tuna.tsinghua.edu.cn/simple",LP="https://registry.npmmirror.com/-/binary";function KF(){return{npm_config_registry:qd,PIP_INDEX_URL:hc,UV_DEFAULT_INDEX:hc,UV_INDEX_URL:hc,UV_PYTHON_INSTALL_MIRROR:`${LP}/python-build-standalone`,NODEJS_ORG_MIRROR:`${LP}/node`,npm_config_disturl:`${LP}/node`}}var UP=Object.keys(KF());import{readFileSync as Ede}from"node:fs";import{randomUUID as Mde}from"node:crypto";de();Pa();import{readdirSync as Sde,readFileSync as xde,statSync as FP,writeFileSync as Rde}from"node:fs";import{join as Wd}from"node:path";var Tde=["auto-skill-","test-skill-"],Ade=".skills_prompt_snapshot.json";function Pde(t){return Tde.some(e=>t.startsWith(e))}function Ide(t){let e=t.replace(/\r\n/g,`
|
|
687
687
|
`),n=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),r=e.match(/^---\n[\s\S]*?^description:\s*(.+)/m),o=e.match(/^---\n[\s\S]*?^category:\s*(.+)/m),i=e.match(/^---\n[\s\S]*?^author:\s*(.+)/m),s=e.match(/^---\n[\s\S]*?^requires:\s*(.+)/m),a=e.match(/^---\n[\s\S]*?^environments:\s*(.+)/m);return{version:n?.[1],description:r?.[1]?.trim(),category:o?.[1]?.trim()||void 0,author:i?.[1]?.trim()||void 0,requiredTools:VF(s?.[1]),environments:VF(a?.[1])}}function Gd(t,e){let n=_n(),r=Y0(),o=t?Q0(t):new Set,i=[],s;try{s=Sde(n,{withFileTypes:!0})}catch{s=[]}for(let a of s){if(!a.isDirectory()||a.name.startsWith("."))continue;let c=Wd(n,a.name),l=Wd(c,"SKILL.md"),d;try{if(!FP(l).isFile())continue;d=xde(l,"utf8")}catch{continue}let p=r.has(a.name),m=o.has(a.name),f=Ide(d),g=!_de(f,e);i.push({name:a.name,filePath:l,baseDir:c,globallyDisabled:p,projectDisabled:m,active:!p&&!m&&!g,systemGenerated:Pde(a.name),description:f.description,version:f.version,category:f.category,author:f.author,requiredTools:f.requiredTools,environments:f.environments})}return Cde(n,i),i}function Do(t,e){return Gd(t,e).filter(n=>n.active)}function Ln(t){let e=_n(),n=Wd(e,t),r=Wd(n,"SKILL.md");try{if(FP(r).isFile())return{baseDir:n,filePath:r}}catch{}return null}function VF(t){if(!t)return;let e=t.replace(/^\[|\]$/g,"").split(/[,\s]+/).map(n=>n.replace(/^["']|["']$/g,"").trim()).filter(Boolean);return e.length>0?e:void 0}function _de(t,e){if(t.environments&&e?.currentEnvironment&&!t.environments.includes(e.currentEnvironment))return!1;if(t.requiredTools){if(!e?.availableToolNames)return!1;let n=new Set(e.availableToolNames);return t.requiredTools.every(r=>n.has(r))}return!0}function Cde(t,e){try{let r={version:1,entries:e.map(o=>{let i=FP(o.filePath);return{name:o.name,size:i.size,mtimeMs:i.mtimeMs,description:o.description,version:o.version,requiredTools:o.requiredTools,environments:o.environments}})};Rde(Wd(t,Ade),JSON.stringify(r,null,2),"utf8")}catch{}}var Dde="astraclaw_capabilities",Sr=[Dde,"astraclaw"];function Dg(t){let e=Do(t.projectRoot,{availableToolNames:t.availableToolNames,currentEnvironment:t.currentEnvironment??process.platform}).filter(r=>!r.systemGenerated);if(e.length===0&&!t.mcpAvailable)return;let n=["# AstraClaw shared skills","AstraClaw shares the user's installed skills with this external agent for the current workspace."];if(t.mcpAvailable?n.push("The injected MCP server is named `astraclaw_capabilities`; some ACP clients display it as `astraclaw`.","When you need the live list, use the MCP tool `skills_list` (also shown by some clients as `astraclaw:acp://skills_list` or `astraclaw_capabilities.skills_list`).","When you need the full workflow for one skill, use `skill_view` with its `name` (also shown by some clients as `astraclaw:acp://skill_view` or `astraclaw_capabilities.skill_view`).","When you need connectors installed from AstraClaw's Plugins page, use `mcp_connectors_list` to discover shared MCP tools, then call one through `mcp_tool_call` with its `toolName` and `args`.","Do not look for a separate qlogicagent MCP server or local `mcp` CLI; these tools are injected into this ACP session by AstraClaw."):n.push("This ACP session did not accept direct AstraClaw MCP injection. If this agent exposes AstraClaw through its native MCP config, prefer those live tools (`skills_list`, `skill_view`, `mcp_connectors_list`, `mcp_tool_call`); otherwise use the catalog below as read-only shared skill context."),e.length>0){n.push("","Active shared skills:");for(let r of e.slice(0,40))n.push(`- ${r.name}${r.description?`: ${r.description}`:""}`);e.length>40&&n.push(`- ...and ${e.length-40} more`)}return n.join(`
|
|
688
688
|
`)}function JF(t){let e=Dg(t);if(e)return["<astraclaw_capabilities>","Host-provided context from AstraClaw. This is not the user's request; use it only to discover shared skills available in the current workspace.",e,"</astraclaw_capabilities>","","<user_request>"].join(`
|
|
689
689
|
`)}async function $g(t){if(t.tool==="skills_list")return{handled:!0,result:{skills:Do(t.projectRoot,{availableToolNames:t.availableToolNames,currentEnvironment:t.currentEnvironment??process.platform}).map($de)}};if(t.tool==="skill_view"){let e=typeof t.args.name=="string"?t.args.name.trim():"";if(!e)throw new Error("skill_view requires a skill name");let n=Ln(e);if(!n)throw new Error(`Skill not found: ${e}`);return{handled:!0,result:{name:e,content:Ede(n.filePath,"utf8")}}}if(t.tool==="mcp_connectors_list"){if(!t.toolCatalog)return{handled:!0,result:{tools:[],note:"AstraClaw MCP connector catalog is not attached to this capability server instance."}};let e=t.toolCatalog.getToolManifest().filter(n=>n.function.name.startsWith("mcp__")).map(n=>({toolName:n.function.name,server:Ode(n.function.name),name:jde(n.function.name),description:n.function.description,inputSchema:n.function.parameters}));return{handled:!0,result:{tools:e,count:e.length}}}if(t.tool==="mcp_tool_call"){if(!t.toolCatalog)throw new Error("AstraClaw MCP connector catalog is not attached");let e=typeof t.args.toolName=="string"?t.args.toolName.trim():"";if(!e.startsWith("mcp__"))throw new Error("mcp_tool_call requires a connector toolName returned by mcp_connectors_list");let n=t.toolCatalog.findTool(e);if(!n?.execute)throw new Error(`MCP connector tool not found or not executable: ${e}`);let r=Nde(t.args.args),o=`astraclaw_mcp_${Mde().slice(0,8)}`,i=await n.execute(o,r);return{handled:!0,result:{toolName:e,content:i.content,details:i.details,imageUrls:i.imageUrls}}}return{handled:!1}}function $de(t){return{name:t.name,description:t.description,version:t.version,category:t.category,requiredTools:t.requiredTools,environments:t.environments}}function Nde(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function Ode(t){let e=t.split("__");return e.length>=3?e[1]??"":""}function jde(t){let e=t.split("__");return e.length>=3?e.slice(2).join("__"):t}import{existsSync as Kd,mkdirSync as Vd,readFileSync as zs,writeFileSync as Jd}from"node:fs";import{homedir as Lde}from"node:os";import{dirname as Zd,join as cr}from"node:path";de();var Ude={qwen:[".qwen","settings.json"],gemini:[".gemini","settings.json"]},Ng="# BEGIN ASTRACLAW MANAGED MCP",BP="# END ASTRACLAW MANAGED MCP",ZF=" # BEGIN ASTRACLAW MANAGED MCP",XF=" # END ASTRACLAW MANAGED MCP";function YF(t){let e=t.agentId.trim().toLowerCase(),n=t.homeDir||Lde(),r=Fde(t),o=Ude[e];if(o){let i=cr(n,...o);return qde({agentId:e,configPath:i,server:r})}if(e==="codex"){let i=cr(t.codexHome||process.env.CODEX_HOME?.trim()||cr(n,".codex"),"config.toml");return Vde({agentId:e,configPath:i,server:r})}if(e==="kimi"){let i=cr(n,".kimi","mcp.json");return Wde({agentId:e,configPath:i,server:r})}if(e==="hermes"){let i=cr(Hde(n),"config.yaml");return Jde({agentId:e,configPath:i,server:r})}if(e==="opencode"){let i=cr(zde(n,t.homeDir!==void 0),"opencode.jsonc");return Zde({agentId:e,configPath:i,server:r})}return{agentId:e,status:"unsupported",reason:`No native MCP config adapter for agent "${e}"`}}function Fde(t){return{command:t.nodePath||process.execPath,args:[t.serverScriptPath],env:Bde({ASTRACLAW_PROJECT_ROOT:t.projectRoot,ASTRACLAW_MANAGED:"1",ASTRACLAW_MCP_CONFIG_PATH:Nl(),QLOGICAGENT_HOME:process.env.QLOGICAGENT_HOME,QLOGIC_LLMROUTER_USER_ID:process.env.QLOGIC_LLMROUTER_USER_ID,QLOGIC_IMPLICIT_OWNER_ID:process.env.QLOGIC_IMPLICIT_OWNER_ID,QLOGIC_DEVICE_ID:process.env.QLOGIC_DEVICE_ID})}}function Hde(t){let e=process.env.HERMES_HOME?.trim();if(e)return e;let n=process.env.LOCALAPPDATA?.trim();return process.platform==="win32"&&n?cr(n,"hermes"):cr(t,".hermes")}function zde(t,e=!1){if(e)return cr(t,"opencode");let n=process.env.XDG_CONFIG_HOME?.trim();if(n)return cr(n,"opencode");let r=process.env.APPDATA?.trim();return process.platform==="win32"&&r?cr(r,"opencode"):cr(t,".config","opencode")}function Bde(t){return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"&&e[1].length>0))}function qde(t){let e=QF(t.configPath),n={...e,mcpServers:{...Xd(e.mcpServers)?e.mcpServers:{}}},r=n.mcpServers;for(let s of Sr)r[s]=t.server;let o=`${JSON.stringify(n,null,2)}
|
|
@@ -724,7 +724,7 @@ ${n}
|
|
|
724
724
|
`);A&&(C.systemPrompt=A);let _=await h.createSession(f,C);l.sessionId=_.sessionId,this.slog("info",e.memberId,"session",`new session on restart (id=${l.sessionId})`)}}catch{this.slog("warn",e.memberId,"session","session re-creation failed on restart")}this.startHeartbeat(e.memberId,C=>{this.slog("warn",C,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(C,"agents.error",{agentId:C,phase:"heartbeat",error:`Agent ${e.name} stopped responding`,retriesLeft:0}),this.kill(C)})}catch(l){let d=this.processes.get(e.memberId);d&&(d.handle.state="failed",d.handle.error=`Runtime restart failed: ${l instanceof Error?l.message:String(l)}`,d.handle.endedAt=Date.now()),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Restart failed after ${r} attempts: ${l instanceof Error?l.message:String(l)}`,retriesLeft:0})}}getMcpIpcPath(e){return this.processes.get(e)?.ipcPath}heartbeatTimers=new Map;missedBeats=new Map;static HEARTBEAT_INTERVAL=3e4;static MAX_MISSED_BEATS=3;startHeartbeat(e,n){this.stopHeartbeat(e),this.missedBeats.set(e,0);let r=setInterval(async()=>{let o=this.processes.get(e);if(!o||o.handle.state==="completed"||o.handle.state==="failed"||o.handle.state==="killed"){this.stopHeartbeat(e);return}if(await this.ping(e,1e4)){this.missedBeats.set(e,0);return}let s=(this.missedBeats.get(e)??0)+1;this.missedBeats.set(e,s),this.slog("warn",e,"heartbeat",`missed (${s}/${t.MAX_MISSED_BEATS})`),s>=t.MAX_MISSED_BEATS&&(this.slog("warn",e,"heartbeat","hang detected, force-killing"),this.stopHeartbeat(e),o.handle.error=`Hang detected: ${s} consecutive heartbeat failures`,this.kill(e),n?.(e))},t.HEARTBEAT_INTERVAL);this.heartbeatTimers.set(e,r)}stopHeartbeat(e){let n=this.heartbeatTimers.get(e);n&&(clearInterval(n),this.heartbeatTimers.delete(e)),this.missedBeats.delete(e)}getMissedBeats(e){return this.missedBeats.get(e)??0}activeCount(){return[...this.processes.values()].filter(e=>e.handle.state==="starting"||e.handle.state==="ready"||e.handle.state==="running").length}remove(e){let n=this.processes.get(e);n&&(this.stopHeartbeat(e),(n.handle.state==="running"||n.handle.state==="starting"||n.handle.state==="ready")&&this.kill(e),this.processes.delete(e))}dispose(){for(let e of this.heartbeatTimers.keys())this.stopHeartbeat(e);for(let e of this.processes.values()){try{e.ipcServer?.close()}catch{}try{e.stderrStream?.end()}catch{}}this.killAll(),this.processes.clear()}};import{spawn as Mi}from"node:child_process";var aH=/[|&;><$`(){}]/;function cH(t,e){let n=e==="win32",r=e==="darwin",o=r?[t.brew,t.npm,t.pip,t.curl]:[t.npm,t.pip,t.brew,t.curl];for(let i of o){if(!i)continue;let s=aH.test(i);if(!(s&&n)&&!(i.startsWith("brew ")&&!r))return{command:i,shell:s}}return null}function lH(t,e){if(e!=="cn")return t;let n=t.trim();return/^npm\b/.test(n)&&!/(?:^|\s)--registry(?:\s|=)/.test(n)?`${n} --registry ${qd}`:/^uv\b/.test(n)&&!/(?:^|\s)--(?:default-)?index(?:-url)?(?:\s|=)/.test(n)?`${n} --default-index ${hc}`:/^(?:pipx|pip3?|python -m pip)\b/.test(n)&&!/(?:^|\s)--index-url(?:\s|=)/.test(n)?`${n} --index-url ${hc}`:n}function sH(t,e,n,r){return new Promise(o=>{let i;try{i=n(t,e)}catch(s){r({type:"log",stream:"stderr",chunk:s instanceof Error?s.message:String(s)}),o(1);return}i.stdout?.on("data",s=>r({type:"log",stream:"stdout",chunk:s.toString()})),i.stderr?.on("data",s=>r({type:"log",stream:"stderr",chunk:s.toString()})),i.on("error",s=>{r({type:"log",stream:"stderr",chunk:s.message}),o(1)}),i.on("close",s=>o(s))})}var Iue=(t,e)=>{let n=Ii();if(n&&IP(t)){let i=t.trim().split(/\s+/).slice(1);return Mi(n.nodeExe,[n.npmCli,...i],{env:_i(n),stdio:["ignore","pipe","pipe"],windowsHide:!0})}let r=_P(t)?CP():void 0;if(e||process.platform==="win32")return Mi(t,{shell:!0,...r?{env:r}:{},stdio:["ignore","pipe","pipe"],windowsHide:!0});let o=t.split(/\s+/).filter(Boolean);return Mi(o[0],o.slice(1),{...r?{env:r}:{},stdio:["ignore","pipe","pipe"]})};async function dH(t,e,n={}){let r=n.platform??process.platform,o=n.spawnImpl??Iue,i=cH(t,r);if(!i){let d=`No install command available for ${r}`;return e({type:"state",state:"failed"}),e({type:"done",ok:!1,error:d}),{ok:!1,error:d}}let s=lH(i.command,n.mirror);e({type:"state",state:"installing"});let a=await sH(s,i.shell,o,e);if(a!==0){let d=`Install command exited with code ${a}`;return e({type:"state",state:"failed"}),e({type:"done",ok:!1,error:d}),{ok:!1,error:d}}let c=t.verifyCmd??`${t.cliCommand} --version`;if(e({type:"state",state:"verifying"}),await sH(c,aH.test(c),o,e)!==0){let d=`Installed but verification failed (${t.cliCommand})`;return e({type:"state",state:"failed"}),e({type:"done",ok:!1,error:d}),{ok:!1,error:d}}return e({type:"state",state:"installed"}),e({type:"done",ok:!0}),{ok:!0}}function uH(t,e=process.platform){try{return e==="win32"?Mi("cmd.exe",["/c","start","","cmd","/k",t],{detached:!0,stdio:"ignore",windowsHide:!1}).unref():e==="darwin"?Mi("osascript",["-e",`tell application "Terminal" to do script ${JSON.stringify(t)}`,"-e",'tell application "Terminal" to activate'],{detached:!0,stdio:"ignore"}).unref():Mi("x-terminal-emulator",["-e","bash","-lc",`${t}; exec bash`],{detached:!0,stdio:"ignore"}).unref(),{ok:!0}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}}function pH(t,e={}){let n=e.platform??process.platform,r=cH(t,n);if(!r)return{ok:!1,error:`No install command available for ${n}`};let o=lH(r.command,e.mirror);try{let i=Ii(),s;if(i&&IP(o)){let a=o.trim().split(/\s+/).slice(1);s=Mi(i.nodeExe,[i.npmCli,...a],{env:_i(i),detached:!0,stdio:"ignore",windowsHide:!0})}else{let a=_P(o)?CP():void 0;s=Mi(o,{shell:!0,...a?{env:a}:{},detached:!0,stdio:"ignore",windowsHide:!0})}return s.unref(),{ok:!0}}catch(i){return{ok:!1,error:i instanceof Error?i.message:String(i)}}}var kt=new Map,_ue=10*6e4,Cue=6e4,Eue=6,jg=null;function Lg(t,e,n){return`${t}\0${e}\0${n??"default"}`}function Yd(t){try{t.manager.kill(t.memberId)}catch{}try{t.manager.dispose()}catch{}}function mH(t){let e=kt.get(t);if(e){if(!e.manager.isAlive(e.memberId)){kt.delete(t),Yd(e);return}return e}}function fH(t,e){let n=kt.get(t);n&&n!==e&&(kt.delete(t),Yd(n)),kt.set(t,e),Mue(),$ue()}function gH(t,e){let n=kt.get(t);if(!n)return;if(!n.manager.isAlive(n.memberId)){kt.delete(t),Yd(n);return}kt.delete(t);let r=kt.get(e);return r&&r!==n&&(kt.delete(e),Yd(r)),kt.set(e,n),n.lastUsed=Date.now(),n}var Ug="__warm__";function bc(t){let e=kt.get(t);e&&(kt.delete(t),Yd(e))}function Qd(t){let e=`${t}\0`,n=0,r=0;for(let[o,i]of[...kt.entries()])o.startsWith(e)&&(i.holder.current?(i.pendingRecredential=!0,r+=1):(bc(o),n+=1));return{evicted:n,deferred:r}}function hH(t){kt.get(t)?.pendingRecredential&&bc(t)}function Mue(){for(;kt.size>Eue;){let t=null,e=Number.POSITIVE_INFINITY;for(let[n,r]of kt)r.holder.current||r.lastUsed<e&&(e=r.lastUsed,t=n);if(!t)break;bc(t)}}function Due(t){for(let[e,n]of[...kt.entries()])n.holder.current||t-n.lastUsed>_ue&&bc(e)}function $ue(){jg||(jg=setInterval(()=>Due(Date.now()),Cue),typeof jg.unref=="function"&&jg.unref())}import{randomUUID as Nue}from"node:crypto";var kc=new Map;function Oue(t,e){let n=kc.get(t);return n&&(clearTimeout(n.timer),n.resolve(null),kc.delete(t)),new Promise(r=>{let o=setTimeout(()=>{kc.delete(t),r(null)},e);typeof o.unref=="function"&&o.unref(),kc.set(t,{resolve:r,timer:o})})}function yH(t,e){let n=kc.get(t);return n?(clearTimeout(n.timer),kc.delete(t),n.resolve(e),!0):!1}function jue(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}function Lue(t){let e=o=>typeof o?.optionId=="string"&&o.optionId.trim()?o.optionId:void 0;if(t.find(o=>e(o)==="allow"))return"allow";let r=t.find(o=>/allow/i.test([o.optionId,o.kind,o.name].filter(i=>typeof i=="string").join(" ")));return e(r)??e(t[0])??"allow"}function GP(t,e=[]){if(typeof t=="string")return e.push(t),e;if(!t||typeof t!="object")return e;if(Array.isArray(t)){for(let n of t)GP(n,e);return e}for(let n of Object.values(t))GP(n,e);return e}function Uue(t){let e=GP(t).join(`
|
|
725
725
|
`);return/astraclaw/i.test(e)&&/\b(?:skills_list|skill_view|mcp_connectors_list|mcp_tool_call)\b/.test(e)}async function vH(t,e){let n=e.turnContext(),r=t.toolCall&&typeof t.toolCall=="object"?t.toolCall:{},o=typeof t.permissionId=="string"&&t.permissionId?t.permissionId:Nue(),i=Array.isArray(t.options)?t.options:[];if(Uue(t))return{optionId:Lue(i)};if(n?.turnId&&e.sendNotification){e.sendNotification("agents.prompt.approval",{agentId:e.agentId,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,approvalId:o,callId:typeof r.toolCallId=="string"?r.toolCallId:o,toolName:typeof r.title=="string"?r.title:typeof t.toolName=="string"?t.toolName:"operation",arguments:jue(r.rawInput),message:typeof t.message=="string"?t.message:void 0,category:typeof t.category=="string"?t.category:"destructive",options:i});let a=await Oue(o,e.timeoutMs??5*6e4);if(a)return{optionId:a}}return{optionId:i.find(a=>a?.kind==="reject_once"||a?.kind==="reject"||/reject|deny|no|cancel/i.test(String(a?.optionId??a?.name??"")))?.optionId??i[0]?.optionId??"reject"}}function Hue(t){let e=t?.rawInput;if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}function zue(t){let e=t?.content;if(Array.isArray(e)){let n=e.map(r=>{if(!r||typeof r!="object")return"";let o=r;return typeof o.text=="string"?o.text:typeof o.content=="string"?o.content:""}).join("");if(n)return n.slice(0,2e3)}if(typeof e=="string")return e.slice(0,2e3);if(t?.rawOutput!==void 0)try{return JSON.stringify(t.rawOutput).slice(0,2e3)}catch{return}}function Bue(t){let{agentId:e,turn:n,method:r,payload:o,sendNotification:i}=t;if(!n||!i)return;let s=o;if(r==="turn.delta"){let c=typeof s?.text=="string"?s.text:"";if(!c)return;n.deltas.push(c),n.turnId&&(i("agents.prompt.delta",{agentId:e,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,text:c}),n.streamedAny=!0);return}if(r==="turn.thought_delta"){let c=typeof s?.text=="string"?s.text:"";c&&n.turnId&&i("agents.prompt.delta",{agentId:e,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,text:c,reasoning:!0});return}if(r==="turn.plan"){n.turnId&&i("agents.prompt.plan",{agentId:e,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,steps:Array.isArray(s?.steps)?s.steps:[]});return}if(r==="turn.tool_use_summary"){if(!n.turnId||!Array.isArray(s?.availableToolNames)||!Array.isArray(s?.enabledToolNames)||!Array.isArray(s?.toolCallNames)||!Array.isArray(s?.blockedToolCalls))return;i("turn.tool_use_summary",{...s,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId});return}if(r==="turn.tool_selection_policy"){if(!n.turnId||!Array.isArray(s?.availableToolNames)||!Array.isArray(s?.enabledToolNamesBefore)||!Array.isArray(s?.enabledToolNamesAfter)||!Array.isArray(s?.suppressedToolNames))return;i("turn.tool_selection_policy",{...s,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId});return}if(!n.turnId)return;let a=typeof s?.callId=="string"?s.callId:String(s?.callId??"");r==="turn.tool_call"?i("agents.prompt.tool",{agentId:e,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,event:{kind:"call",callId:a,name:typeof s?.toolName=="string"?s.toolName:typeof s?.name=="string"?s.name:"tool",arguments:Hue(s)}}):r==="turn.tool_result"&&i("agents.prompt.tool",{agentId:e,sessionId:n.sessionId,turnId:n.turnId,requestId:n.requestId,event:{kind:"result",callId:a,name:typeof s?.toolName=="string"?s.toolName:"tool",ok:s?.status!=="failed"&&s?.status!=="error",outputPreview:zue(s)}})}function kH(t){let e=t?.authMethods;return Array.isArray(e)&&e.length>0?e:void 0}function wH(t){return t instanceof Error?t.message:String(t)}async function que(t){let e=kH(t.error);if(!t.sessionId||!e)return;let n=wH(t.error);await hr(t.sessionId,{role:"user",content:t.prompt},t.projectRoot,t.turnId),await hr(t.sessionId,{role:"assistant",content:n,blocks:[{type:"auth_prompt",agentId:t.agentId,message:n,authMethods:e}]},t.projectRoot,t.turnId);let r=Vt(t.sessionId,t.projectRoot),o=await _a(t.sessionId,t.projectRoot);await yt(t.sessionId,{type:"personal",...t.projectId?{projectId:t.projectId}:{},...o!==null?{messageCount:o}:{},...r?.title?{}:{title:Bl(t.prompt,"External agent login required")},...t.lockSessionOwner===!1||r?.agentId?{}:{agentId:t.agentId}},t.projectRoot)}async function SH(t){let e=t.params,n=typeof e?.approvalId=="string"?e.approvalId:"",r=typeof e?.optionId=="string"?e.optionId:"",o=n&&r?yH(n,r):!1;t.id!==void 0&&this.sendResponse(t.id,{ok:o})}async function xH(t){try{let e=t.params,n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData());let r=await this.acpDetector.scanAsync(e?.force);t.id!==void 0&&this.sendResponse(t.id,r)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function RH(t){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let n=await this.acpDetector.scanAsync(!1);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function TH(t){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let n=new Map(this.acpDetector.list().map(o=>[o.id,o])),r=zd().map(o=>{let i=n.get(o.id);return{id:o.id,name:o.name,brandId:o.brandId??o.id,category:o.category??"code",integration:o.integration??"acp",authMode:o.authMode??"key",keySource:o.keySource??"none",note:o.note,availableModes:qF(o),authPreference:e.getAgentConfig(o.id)?.authPreference??"auto",credentialReady:i?.status==="available"?this.acpDetector.isAgentReady(o.id):!1,accountConnected:i?.status==="available"?this.acpDetector.getNativeLoginState(o.id):void 0,status:i?.status??"not_installed",version:jF(o,i?.version),install:{docsUrl:o.install?.docsUrl,command:o.install?.npm??o.install?.pip??o.install?.brew??o.install?.curl,setupCommand:o.install?.setupCommand}}});t.id!==void 0&&this.sendResponse(t.id,{catalog:r})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}var KP=new Set;async function AH(t){try{let e=t.params,r=(typeof e?.mirror=="string"&&e.mirror?e.mirror:process.env.QLOGICAGENT_INSTALL_MIRROR)==="cn"?qd:void 0,o=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(o.getData());let i=new Map(this.acpDetector.list().map(l=>[l.id,l])),s=zd().map(l=>({id:l.id,entry:l,detectedVersion:i.get(l.id)?.version})),{updates:a,stale:c}=UF(s,r);if(t.id!==void 0&&this.sendResponse(t.id,{updates:a,refreshing:c}),c){let l=r??"";KP.has(l)||(KP.add(l),LF(s,r).catch(()=>{}).finally(()=>KP.delete(l)))}}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function PH(t){let e=t.params,n=typeof e?.agentId=="string"?e.agentId:void 0,r=typeof e?.mirror=="string"&&e.mirror?e.mirror:process.env.QLOGICAGENT_INSTALL_MIRROR;if(!n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId (string) required"});return}let o=Eo(n);if(!o?.install){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:`Unknown or non-installable agent: ${n}`});return}if(o.install.deferUpdate){let i=pH(o.install,{mirror:r});t.id!==void 0&&this.sendResponse(t.id,{ok:i.ok,error:i.error,deferred:i.ok});return}try{let i=await dH(o.install,s=>{this.sendNotification?.("agent.install.progress",{agentId:n,event:s})},{mirror:r});this.acpDetector.clearCache(),t.id!==void 0&&this.sendResponse(t.id,{ok:i.ok,error:i.error})}catch(i){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:i instanceof Error?i.message:String(i)})}}async function IH(t){let e=t.params,n=typeof e?.agentId=="string"?e.agentId:void 0;if(!n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId (string) required"});return}let o=Eo(n)?.install?.setupCommand;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:`No terminal setup command for agent: ${n}`});return}let i=uH(o);t.id!==void 0&&this.sendResponse(t.id,{ok:i.ok,error:i.error,command:o})}async function _H(t){try{let e=t.params;if(!e?.action||!e?.agent){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"action and agent are required."});return}let n=await this.ensureAgentConfigStore();switch(e.action){case"register":await n.registerCustomAgent(e.agent);break;case"unregister":await n.unregisterCustomAgent(e.agent.id);break;case"update":await n.registerCustomAgent(e.agent);break}this.acpDetector.setConfigStore(n.getData()),this.acpDetector.clearCache(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function CH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore(),{agentId:r,...o}=e;await n.setAgentConfig(r,o),this.acpDetector.setConfigStore(n.getData());let{deferred:i}=Qd(r);t.id!==void 0&&this.sendResponse(t.id,{ok:!0,pendingTurn:i>0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function EH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let r=(await this.ensureAgentConfigStore()).getAgentConfig(e.agentId);t.id!==void 0&&this.sendResponse(t.id,r)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function MH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore();await n.removeAgentConfig(e.agentId),this.acpDetector.setConfigStore(n.getData()),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function Wue(t){let e=bH.homedir();if(t==="codex"){let n=process.env.CODEX_HOME?.trim()||wc.join(e,".codex");return[wc.join(n,"auth.json")]}return[]}async function DH(t){try{let e=t.params,n=typeof e?.agentId=="string"?e.agentId.trim():"";if(!n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let r=!1;for(let o of Wue(n))try{Sc.existsSync(o)&&(Sc.rmSync(o,{force:!0}),r=!0)}catch{}Qd(n),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,cleared:r,hint:r?void 0:`\u5728\u7EC8\u7AEF\u8FD0\u884C \`${n} logout\` \u9000\u51FA\u8BE5 Agent \u7684\u8D26\u53F7`})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function $H(t){try{let e=t.params;if(!e?.url){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"url is required."});return}await(await this.ensureAgentConfigStore()).setGatewayUrl(e.url),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function NH(t){try{let n=(await this.ensureAgentConfigStore()).getGatewayUrl();t.id!==void 0&&this.sendResponse(t.id,{url:n})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function OH(t){try{let n=(await this.ensureAgentConfigStore()).getData(),r=Object.entries(n.agents).map(([o,i])=>({agentId:o,hasApiKey:!!i.apiKey,hasBaseUrl:!!i.baseUrl,hasModel:!!i.model}));t.id!==void 0&&this.sendResponse(t.id,r)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function jH(t){try{let e=[],n=(r,o)=>{if(r)for(let i of r.getAllHandles())e.push({memberId:i.memberId,name:i.name,pid:i.pid,state:i.state,startedAt:i.startedAt,endedAt:i.endedAt,source:o})};n(this.soloProcessManager,"solo"),n(this.productProcessManager,"product"),t.id!==void 0&&this.sendResponse(t.id,e)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function LH(t){try{let e=t.params;if(!e?.memberId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"memberId is required."});return}let n=!1;for(let r of[this.soloProcessManager,this.productProcessManager])if(r?.getHandle(e.memberId)){r.kill(e.memberId),n=!0;break}t.id!==void 0&&this.sendResponse(t.id,{ok:n})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function UH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let n=wc.join(_e(),"agent-logs"),r=wc.join(n,`${e.agentId}.stderr.log`),o="";try{o=Sc.readFileSync(r,"utf-8")}catch{}e.tail&&e.tail>0&&o&&(o=o.split(`
|
|
726
726
|
`).slice(-e.tail).join(`
|
|
727
|
-
`)),t.id!==void 0&&this.sendResponse(t.id,{log:o})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function FH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData());let o=this.acpDetector.list().find(s=>s.id===e.agentId);if(!o){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:`Agent ${e.agentId} not found`,durationMs:0});return}if(o.status==="not_installed"){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:`Agent ${e.agentId} is not installed`,durationMs:0});return}let i=Date.now();t.id!==void 0&&this.sendResponse(t.id,{ok:o.status==="available",version:o.version,capabilities:o.capabilities,error:o.status!=="available"?`Agent status: ${o.status}`:void 0,durationMs:Date.now()-i})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function HH(t,e,n,r,o,i){let s=Lg(e,r,o),a=mH(s);if(a)return a;if(o!==Ug){let f=gH(Lg(e,r,Ug),s);if(f)return f}let c=`chat-${e}-${Fue().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Vr({onNotification:(f,g,h)=>{Bue({agentId:e,turn:l.current,method:g,payload:h,sendNotification:d})},onMcpToolCall:async(f,g,h)=>{if(typeof t.handleMcpToolCall=="function")return t.handleMcpToolCall(f,g,h);let y=await $g({tool:g,args:h,projectRoot:r});return y.handled?y.result:{ok:!1,error:"MCP tool call unavailable"}},onPermissionRequest:(f,g)=>vH(g,{agentId:e,turnContext:()=>l.current,sendNotification:d}),log:{info:f=>t.log?.(`[agents.prompt] ${f}`),warn:f=>t.log?.(`[agents.prompt] WARN: ${f}`),debug:f=>t.log?.(`[agents.prompt] ${f}`)},sessionDir:wc.join(_e(),"agent-logs")});await p.spawn({memberId:c,name:`chat-${e}`,cwd:r,prompt:"",external:n,systemPrompt:i});let m={manager:p,memberId:c,holder:l,lastUsed:Date.now()};return fH(s,m),m}async function zH(t){try{let e=t.params??{},n=typeof e.agentId=="string"?e.agentId.trim():"";if(!n||n==="qlogicagent"){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}let r=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(r.getData()),await this.acpDetector.scanAsync(!1);let o=this.acpDetector.buildExternalDescriptor(n);if(!o){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}if(this.acpDetector.resolveCredentialError(n)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,warmed:!1});return}let i=typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd();await HH(this,n,o,i,Ug),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,warmed:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1,error:e instanceof Error?e.message:String(e)})}}async function BH(t){try{let e=t.params??{},n=typeof e.agentId=="string"?e.agentId.trim():"",r=typeof e.prompt=="string"?e.prompt:"";if(!n||!r.trim()){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId and prompt are required."});return}let o=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(o.getData()),await this.acpDetector.scanAsync(!1);let i=this.acpDetector.buildExternalDescriptor(n);if(!i){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:`Agent ${n} is not available or not ACP-compatible.`});return}let s=this.acpDetector.resolveCredentialError(n);if(s){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:s});return}let a=typeof e.cwd=="string"&&e.cwd?e.cwd:typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd(),c=typeof e.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:3e5,l=typeof e.sessionId=="string"?e.sessionId:void 0,d=typeof e.turnId=="string"?e.turnId:void 0,p=typeof e.requestId=="string"?e.requestId:void 0,m=typeof e.projectId=="string"?e.projectId:void 0,f=e.lockSessionOwner!==!1,g=Lg(n,a,l),h=await HH(this,n,i,a,l,typeof e.systemPrompt=="string"?e.systemPrompt:void 0),y={sessionId:l,turnId:d,requestId:p,deltas:[],streamedAny:!1};h.holder.current=y,h.lastUsed=Date.now();let b;try{b=await h.manager.sendTask(h.memberId,r,{timeout:c})}catch(S){throw await que({sessionId:l,projectRoot:a,turnId:d,projectId:m,agentId:n,prompt:r,error:S,lockSessionOwner:f}),bc(g),S}finally{h.holder.current=null,hH(g)}let v=y.deltas.join("")||(typeof b?.content=="string"?b.content:""),k=h.manager.getUsageTracker(h.memberId)?.getUsage();if(l){hr(l,{role:"user",content:r},a,d),v&&hr(l,{role:"assistant",content:v},a,d);let S=Vt(l,a);yt(l,{type:"personal",...m?{projectId:m}:{},...S?.title?{}:{title:Bl(r,"External agent session")},...f&&!S?.agentId?{agentId:n}:{}},a)}t.id!==void 0&&this.sendResponse(t.id,{ok:!0,agentId:n,content:v,streamed:y.streamedAny,stopReason:b?.stopReason,usage:k?{inputTokens:k.inputTokens,outputTokens:k.outputTokens,totalTokens:k.totalTokens,cacheRead:k.cachedReadTokens,thoughtTokens:k.thoughtTokens,cost:k.cost}:void 0})}catch(e){if(t.id!==void 0){let n=kH(e);this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:wH(e),...n?{data:{authMethods:n}}:{}})}}}Rm();function Gue(t){let e=Jue(t.fetchFn??fetch,t.clientVersion),n=t.token.trim();return{async matchRegistry(r){let o=r.intent.trim();if(!o)throw new Error("intent is required.");let i=Xue(r.topK),s=await Hg(e,Fg(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:o,topK:i,prefer:r.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(xc(s)&&Array.isArray(s.matches)?s.matches:[]).map(Yue).filter(c=>!!c).slice(0,i)},async resolveInstall(r,o){let i=encodeURIComponent(r.trim());if(!i)throw new Error("resourceId is required.");let s=o?.trim(),a=s?`?version=${encodeURIComponent(s)}`:"",c=await Hg(e,Fg(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=GH(c);if(!l)throw new Error("Community hub returned an invalid install resolution.");return l},async listResourceVersions(r){let o=encodeURIComponent(r.trim());if(!o)throw new Error("resourceId is required.");let i=await Hg(e,Fg(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(xc(i)&&Array.isArray(i.versions)?i.versions:[]).map(Que).filter(a=>!!a)},async resolveRuntime(r,o){let i=encodeURIComponent(r.trim());if(!i)throw new Error("runtime id is required.");let s=encodeURIComponent(o.trim());if(!s)throw new Error("platform is required.");let a=await Hg(e,Fg(t.baseUrl,`/api/v15/runtime/${i}/resolve?platform=${s}`),n,"GET"),c=epe(a);if(!c)throw new Error("Community hub returned an invalid runtime resolution.");return c}}}function Rc(t=li()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=Kue(t);return Gue({baseUrl:Vue(t),token:e,clientVersion:n})}function Kue(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.17.5"}function Vue(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Fg(t,e){let n=t.trim().replace(/\/+$/,"");return n.endsWith("/v1")&&(n=n.slice(0,-3)),n.endsWith("/api")&&(n=n.slice(0,-4)),`${n}${e}`}function Jue(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function Hg(t,e,n,r,o){let i,s=o!==void 0;try{i=await t(e,{method:r,headers:{accept:"application/json",authorization:`Bearer ${n}`,...s?{"content-type":"application/json"}:{}},...s?{body:JSON.stringify(o)}:{},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Community hub is unavailable.")}if(!i.ok)throw new Error(`Community hub rejected registry request: ${i.status}${await Zue(i)}`);return i.json().catch(()=>null)}async function Zue(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function xc(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Xue(t){if(t===void 0)return 3;if(typeof t!="number"||!Number.isSafeInteger(t)||t<1||t>3)throw new Error("registry match topK must be an integer between 1 and 3.");return t}function Yue(t){if(!xc(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=qH(t.sourceTier),n=WH(t.trustStage),r=zg(t.resourceRiskTier),o=zg(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.title!="string"||!e||!n||!r||!o)return null;let i=Array.isArray(t.capabilityTags)?t.capabilityTags:[];return{id:t.id,type:typeof t.type=="string"?t.type:"skill",title:VP(t.title,80),summary:VP(typeof t.summary=="string"?t.summary:"",160),category:typeof t.category=="string"?t.category:null,capabilityTags:i.filter(s=>typeof s=="string"&&s.trim().length>0).slice(0,6).map(s=>VP(s,32)),sourceTier:e,trustStage:n,resourceRiskTier:r,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function VP(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}\u2026`}function Que(t){return!xc(t)||typeof t.version!="string"||!t.version?null:{version:t.version,createdAt:typeof t.createdAt=="string"?t.createdAt:"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,yanked:t.yanked===!0}}function epe(t){if(!xc(t))return null;let e=typeof t.id=="string"?t.id:"",n=typeof t.version=="string"?t.version:"",r=typeof t.downloadUrl=="string"?t.downloadUrl:"",o=typeof t.checksum=="string"?t.checksum:"",i=typeof t.sizeBytes=="number"?t.sizeBytes:0;return!e||!n||!r||!/^[a-f0-9]{64}$/.test(o)||!Number.isSafeInteger(i)||i<=0?null:{id:e,version:n,downloadUrl:r,checksum:o,sizeBytes:i}}var tpe=new Set(["R0","R1","R2","R3"]),npe=new Set(["official","community"]),rpe=new Set(["quarantine","trial","trusted"]),ope=new Set(["pending","approved","rejected"]);function zg(t){return typeof t=="string"&&tpe.has(t)?t:null}function qH(t){return typeof t=="string"&&npe.has(t)?t:null}function WH(t){return typeof t=="string"&&rpe.has(t)?t:null}function ipe(t){return typeof t=="string"&&ope.has(t)?t:null}function GH(t){if(!xc(t))return null;let e=qH(t.sourceTier),n=WH(t.trustStage),r=ipe(t.reviewStatus),o=zg(t.resourceRiskTier),i=zg(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.type!="string"||typeof t.kind!="string"||!e||!n||!r||!o||!i||typeof t.version!="string"||typeof t.checksum!="string"||typeof t.sizeBytes!="number"||typeof t.downloadUrl!="string")return null;let s=Array.isArray(t.requires)?t.requires:null,a=Array.isArray(t.dependencies)?t.dependencies:null;if(!s||!a||s.some(l=>typeof l!="string"))return null;let c=a.map(GH);return c.some(l=>!l)?null:{id:t.id,type:t.type,kind:t.kind,sourceTier:e,trustStage:n,reviewStatus:r,resourceRiskTier:o,effectiveRiskTier:i,requires:s,dependencies:c,version:t.version,checksum:t.checksum,sizeBytes:t.sizeBytes,downloadUrl:t.downloadUrl,manifest:t.manifest,minClientVersion:typeof t.minClientVersion=="string"&&t.minClientVersion.trim()?t.minClientVersion.trim():void 0,signature:typeof t.signature=="string"&&t.signature.trim()?t.signature:null,signingKeyId:typeof t.signingKeyId=="string"&&t.signingKeyId.trim()?t.signingKeyId:null}}de();var JP={enabled:!0},spe=new Set(["R2","R3"]);function KH(t,e=JP){return spe.has(t.effectiveRiskTier)?{mode:"high-risk-ask",requiresInstallConsent:!0,requiresHighRiskConsent:!0,reason:`effectiveRiskTier=${t.effectiveRiskTier} \u9AD8\u5371,\u5FC5\u987B\u9AD8\u5371\u95EE\u4EBA`}:e.enabled?t.effectiveRiskTier==="R0"?{mode:"silent",requiresInstallConsent:!1,requiresHighRiskConsent:!1,reason:"R0 \u4F4E\u98CE\u9669 inert,\u81EA\u6CBB\u9759\u9ED8\u83B7\u53D6"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"R1 \u4F4E\u98CE\u9669\u4F46\u975E\u96F6,\u95EE\u4EBA\u4E00\u6B21"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"\u81EA\u6CBB\u9884\u7B97\u5173\u95ED,\u56DE\u9000\u663E\u5F0F\u540C\u610F"}}import{createPublicKey as ape,verify as cpe}from"node:crypto";function lpe(t){return`id=${t.id}
|
|
727
|
+
`)),t.id!==void 0&&this.sendResponse(t.id,{log:o})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function FH(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId is required."});return}let n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData());let o=this.acpDetector.list().find(s=>s.id===e.agentId);if(!o){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:`Agent ${e.agentId} not found`,durationMs:0});return}if(o.status==="not_installed"){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:`Agent ${e.agentId} is not installed`,durationMs:0});return}let i=Date.now();t.id!==void 0&&this.sendResponse(t.id,{ok:o.status==="available",version:o.version,capabilities:o.capabilities,error:o.status!=="available"?`Agent status: ${o.status}`:void 0,durationMs:Date.now()-i})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function HH(t,e,n,r,o,i){let s=Lg(e,r,o),a=mH(s);if(a)return a;if(o!==Ug){let f=gH(Lg(e,r,Ug),s);if(f)return f}let c=`chat-${e}-${Fue().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Vr({onNotification:(f,g,h)=>{Bue({agentId:e,turn:l.current,method:g,payload:h,sendNotification:d})},onMcpToolCall:async(f,g,h)=>{if(typeof t.handleMcpToolCall=="function")return t.handleMcpToolCall(f,g,h);let y=await $g({tool:g,args:h,projectRoot:r});return y.handled?y.result:{ok:!1,error:"MCP tool call unavailable"}},onPermissionRequest:(f,g)=>vH(g,{agentId:e,turnContext:()=>l.current,sendNotification:d}),log:{info:f=>t.log?.(`[agents.prompt] ${f}`),warn:f=>t.log?.(`[agents.prompt] WARN: ${f}`),debug:f=>t.log?.(`[agents.prompt] ${f}`)},sessionDir:wc.join(_e(),"agent-logs")});await p.spawn({memberId:c,name:`chat-${e}`,cwd:r,prompt:"",external:n,systemPrompt:i});let m={manager:p,memberId:c,holder:l,lastUsed:Date.now()};return fH(s,m),m}async function zH(t){try{let e=t.params??{},n=typeof e.agentId=="string"?e.agentId.trim():"";if(!n||n==="qlogicagent"){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}let r=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(r.getData()),await this.acpDetector.scanAsync(!1);let o=this.acpDetector.buildExternalDescriptor(n);if(!o){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}if(this.acpDetector.resolveCredentialError(n)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,warmed:!1});return}let i=typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd();await HH(this,n,o,i,Ug),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,warmed:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1,error:e instanceof Error?e.message:String(e)})}}async function BH(t){try{let e=t.params??{},n=typeof e.agentId=="string"?e.agentId.trim():"",r=typeof e.prompt=="string"?e.prompt:"";if(!n||!r.trim()){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:"agentId and prompt are required."});return}let o=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(o.getData()),await this.acpDetector.scanAsync(!1);let i=this.acpDetector.buildExternalDescriptor(n);if(!i){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:`Agent ${n} is not available or not ACP-compatible.`});return}let s=this.acpDetector.resolveCredentialError(n);if(s){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:w.INVALID_PARAMS,message:s});return}let a=typeof e.cwd=="string"&&e.cwd?e.cwd:typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd(),c=typeof e.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:3e5,l=typeof e.sessionId=="string"?e.sessionId:void 0,d=typeof e.turnId=="string"?e.turnId:void 0,p=typeof e.requestId=="string"?e.requestId:void 0,m=typeof e.projectId=="string"?e.projectId:void 0,f=e.lockSessionOwner!==!1,g=Lg(n,a,l),h=await HH(this,n,i,a,l,typeof e.systemPrompt=="string"?e.systemPrompt:void 0),y={sessionId:l,turnId:d,requestId:p,deltas:[],streamedAny:!1};h.holder.current=y,h.lastUsed=Date.now();let b;try{b=await h.manager.sendTask(h.memberId,r,{timeout:c})}catch(S){throw await que({sessionId:l,projectRoot:a,turnId:d,projectId:m,agentId:n,prompt:r,error:S,lockSessionOwner:f}),bc(g),S}finally{h.holder.current=null,hH(g)}let v=y.deltas.join("")||(typeof b?.content=="string"?b.content:""),k=h.manager.getUsageTracker(h.memberId)?.getUsage();if(l){hr(l,{role:"user",content:r},a,d),v&&hr(l,{role:"assistant",content:v},a,d);let S=Vt(l,a);yt(l,{type:"personal",...m?{projectId:m}:{},...S?.title?{}:{title:Bl(r,"External agent session")},...f&&!S?.agentId?{agentId:n}:{}},a)}t.id!==void 0&&this.sendResponse(t.id,{ok:!0,agentId:n,content:v,streamed:y.streamedAny,stopReason:b?.stopReason,usage:k?{inputTokens:k.inputTokens,outputTokens:k.outputTokens,totalTokens:k.totalTokens,cacheRead:k.cachedReadTokens,thoughtTokens:k.thoughtTokens,cost:k.cost}:void 0})}catch(e){if(t.id!==void 0){let n=kH(e);this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:wH(e),...n?{data:{authMethods:n}}:{}})}}}Rm();function Gue(t){let e=Jue(t.fetchFn??fetch,t.clientVersion),n=t.token.trim();return{async matchRegistry(r){let o=r.intent.trim();if(!o)throw new Error("intent is required.");let i=Xue(r.topK),s=await Hg(e,Fg(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:o,topK:i,prefer:r.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(xc(s)&&Array.isArray(s.matches)?s.matches:[]).map(Yue).filter(c=>!!c).slice(0,i)},async resolveInstall(r,o){let i=encodeURIComponent(r.trim());if(!i)throw new Error("resourceId is required.");let s=o?.trim(),a=s?`?version=${encodeURIComponent(s)}`:"",c=await Hg(e,Fg(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=GH(c);if(!l)throw new Error("Community hub returned an invalid install resolution.");return l},async listResourceVersions(r){let o=encodeURIComponent(r.trim());if(!o)throw new Error("resourceId is required.");let i=await Hg(e,Fg(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(xc(i)&&Array.isArray(i.versions)?i.versions:[]).map(Que).filter(a=>!!a)},async resolveRuntime(r,o){let i=encodeURIComponent(r.trim());if(!i)throw new Error("runtime id is required.");let s=encodeURIComponent(o.trim());if(!s)throw new Error("platform is required.");let a=await Hg(e,Fg(t.baseUrl,`/api/v15/runtime/${i}/resolve?platform=${s}`),n,"GET"),c=epe(a);if(!c)throw new Error("Community hub returned an invalid runtime resolution.");return c}}}function Rc(t=li()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=Kue(t);return Gue({baseUrl:Vue(t),token:e,clientVersion:n})}function Kue(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.17.6"}function Vue(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Fg(t,e){let n=t.trim().replace(/\/+$/,"");return n.endsWith("/v1")&&(n=n.slice(0,-3)),n.endsWith("/api")&&(n=n.slice(0,-4)),`${n}${e}`}function Jue(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function Hg(t,e,n,r,o){let i,s=o!==void 0;try{i=await t(e,{method:r,headers:{accept:"application/json",authorization:`Bearer ${n}`,...s?{"content-type":"application/json"}:{}},...s?{body:JSON.stringify(o)}:{},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Community hub is unavailable.")}if(!i.ok)throw new Error(`Community hub rejected registry request: ${i.status}${await Zue(i)}`);return i.json().catch(()=>null)}async function Zue(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function xc(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Xue(t){if(t===void 0)return 3;if(typeof t!="number"||!Number.isSafeInteger(t)||t<1||t>3)throw new Error("registry match topK must be an integer between 1 and 3.");return t}function Yue(t){if(!xc(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=qH(t.sourceTier),n=WH(t.trustStage),r=zg(t.resourceRiskTier),o=zg(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.title!="string"||!e||!n||!r||!o)return null;let i=Array.isArray(t.capabilityTags)?t.capabilityTags:[];return{id:t.id,type:typeof t.type=="string"?t.type:"skill",title:VP(t.title,80),summary:VP(typeof t.summary=="string"?t.summary:"",160),category:typeof t.category=="string"?t.category:null,capabilityTags:i.filter(s=>typeof s=="string"&&s.trim().length>0).slice(0,6).map(s=>VP(s,32)),sourceTier:e,trustStage:n,resourceRiskTier:r,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function VP(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}\u2026`}function Que(t){return!xc(t)||typeof t.version!="string"||!t.version?null:{version:t.version,createdAt:typeof t.createdAt=="string"?t.createdAt:"",sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0,yanked:t.yanked===!0}}function epe(t){if(!xc(t))return null;let e=typeof t.id=="string"?t.id:"",n=typeof t.version=="string"?t.version:"",r=typeof t.downloadUrl=="string"?t.downloadUrl:"",o=typeof t.checksum=="string"?t.checksum:"",i=typeof t.sizeBytes=="number"?t.sizeBytes:0;return!e||!n||!r||!/^[a-f0-9]{64}$/.test(o)||!Number.isSafeInteger(i)||i<=0?null:{id:e,version:n,downloadUrl:r,checksum:o,sizeBytes:i}}var tpe=new Set(["R0","R1","R2","R3"]),npe=new Set(["official","community"]),rpe=new Set(["quarantine","trial","trusted"]),ope=new Set(["pending","approved","rejected"]);function zg(t){return typeof t=="string"&&tpe.has(t)?t:null}function qH(t){return typeof t=="string"&&npe.has(t)?t:null}function WH(t){return typeof t=="string"&&rpe.has(t)?t:null}function ipe(t){return typeof t=="string"&&ope.has(t)?t:null}function GH(t){if(!xc(t))return null;let e=qH(t.sourceTier),n=WH(t.trustStage),r=ipe(t.reviewStatus),o=zg(t.resourceRiskTier),i=zg(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.type!="string"||typeof t.kind!="string"||!e||!n||!r||!o||!i||typeof t.version!="string"||typeof t.checksum!="string"||typeof t.sizeBytes!="number"||typeof t.downloadUrl!="string")return null;let s=Array.isArray(t.requires)?t.requires:null,a=Array.isArray(t.dependencies)?t.dependencies:null;if(!s||!a||s.some(l=>typeof l!="string"))return null;let c=a.map(GH);return c.some(l=>!l)?null:{id:t.id,type:t.type,kind:t.kind,sourceTier:e,trustStage:n,reviewStatus:r,resourceRiskTier:o,effectiveRiskTier:i,requires:s,dependencies:c,version:t.version,checksum:t.checksum,sizeBytes:t.sizeBytes,downloadUrl:t.downloadUrl,manifest:t.manifest,minClientVersion:typeof t.minClientVersion=="string"&&t.minClientVersion.trim()?t.minClientVersion.trim():void 0,signature:typeof t.signature=="string"&&t.signature.trim()?t.signature:null,signingKeyId:typeof t.signingKeyId=="string"&&t.signingKeyId.trim()?t.signingKeyId:null}}de();var JP={enabled:!0},spe=new Set(["R2","R3"]);function KH(t,e=JP){return spe.has(t.effectiveRiskTier)?{mode:"high-risk-ask",requiresInstallConsent:!0,requiresHighRiskConsent:!0,reason:`effectiveRiskTier=${t.effectiveRiskTier} \u9AD8\u5371,\u5FC5\u987B\u9AD8\u5371\u95EE\u4EBA`}:e.enabled?t.effectiveRiskTier==="R0"?{mode:"silent",requiresInstallConsent:!1,requiresHighRiskConsent:!1,reason:"R0 \u4F4E\u98CE\u9669 inert,\u81EA\u6CBB\u9759\u9ED8\u83B7\u53D6"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"R1 \u4F4E\u98CE\u9669\u4F46\u975E\u96F6,\u95EE\u4EBA\u4E00\u6B21"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"\u81EA\u6CBB\u9884\u7B97\u5173\u95ED,\u56DE\u9000\u663E\u5F0F\u540C\u610F"}}import{createPublicKey as ape,verify as cpe}from"node:crypto";function lpe(t){return`id=${t.id}
|
|
728
728
|
version=${t.version}
|
|
729
729
|
checksum=${t.checksum}
|
|
730
730
|
sizeBytes=${t.sizeBytes}`}function dpe(t){return t.includes("\\n")?t.replace(/\\n/g,`
|