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 CHANGED
@@ -405,10 +405,10 @@ ${i}`,action:n}}if(n==="search"){let o=t.query?.trim();if(!o)return{ok:!1,messag
405
405
  `)},content:{type:"string",description:["Content for add/replace/create_file/write_file.","For INDEX.md notes: write concise, factual statements.","For topic files: can be longer (up to 8KB), use markdown formatting."].join(`
406
406
  `)},old_text:{type:"string",description:"For 'replace'/'remove': the exact text to find in INDEX.md."},new_text:{type:"string",description:"For 'replace': the replacement text."},file:{type:"string",description:"Filename for file operations (e.g. 'project-notes.md', 'lesson-esbuild.md'). Must be kebab-case .md."},query:{type:"string",description:"For 'search'/'temporal': natural language query to find relevant memories."},days:{type:"number",description:"For 'temporal': look back N days from today (default: 7)."},memory_ids:{type:"array",items:{type:"string"},description:"For 'feedback': IDs of memories to give feedback on."},signal:{type:"string",enum:["useful","irrelevant","outdated","wrong"],description:"For 'feedback': the feedback signal to apply."},category:{type:"string",enum:["preference","personal_fact","lesson","pattern","decision","context"],description:"For 'remember': categorize the memory (helps with future recall precision)."}},required:["action"]},yW=["Manage persistent memory across sessions. Two distinct systems with clear roles:","","## Project memory (INDEX.md + topic files)","Scope: current project / workspace. Visible every turn.","Use for: architecture decisions, file conventions, build commands, known issues, task logs.","Actions: add, replace, remove, create_file, write_file, read_file, delete_file, list_files.","","## Long-term memory (QMemory)","Scope: user-level, persists across all projects. Searched on demand.","Use for: user preferences, personal facts, recurring lessons, communication style, past insights.","Actions: remember, search, temporal, feedback.","","## When to store (guidelines):","- User explicitly says 'remember this' or 'note that' -> submit a high-priority memory candidate","- User states a preference (style, format, tools, habits) -> remember (long-term)","- Project-specific decision or fact -> add/create_file (project memory)","- A debugging lesson or insight that applies broadly -> remember (long-term)","- DO NOT store: trivial/obvious info, one-off questions, transient state","- DO NOT store: information the user did not share or confirm","","## When to recall:","- Use 'search' when you suspect relevant past context exists for the current task","- Use 'temporal' to find what happened in a specific time period","- Memory is auto-recalled each turn - manual search is for deeper queries"].join(`
407
407
  `),Cbe=[/ignore\s+(previous|all|above|prior)\s+instructions/i,/you\s+are\s+now\s+/i,/do\s+not\s+tell\s+the\s+user/i,/system\s+prompt\s+override/i]});var wW={};sn(wW,{ensureLocalMemoryProvider:()=>Kh,registerMemoryRuntimeHooks:()=>C_,registerMemoryTool:()=>E_});function kW(t,e){return{recallProvider:t,runtimeHookProvider:t,learningSink:t,toolProvider:t,handlerProvider:t,dreamProvider:t,userId:e}}function Kh(t){try{let e=I_(),n=P_(e);if(n.provider)return kW(n.provider,e.ownerUserId||t)}catch{}return kW(null,t)}function C_(t){let e=Kh(t.currentUserId);return!e.recallProvider||!e.runtimeHookProvider||!e.userId||(LM(t.hooks,{memoryProvider:e.recallProvider,localMemoryProvider:e.runtimeHookProvider,userId:e.userId,log:{debug:n=>t.log.debug(n),warn:n=>t.log.warn(n)},getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,llmExtract:async n=>{let r=t.resolveSmallModelClient();if(!r)return null;try{let o="";for await(let i of r.transport.stream({model:r.model,messages:[{role:"user",content:n}],tools:[],maxTokens:512},r.apiKey))i.type==="delta"&&(o+=i.text);return o.trim()||null}catch{return null}}},t.prefetchState),t.log.info("[memory] local provider initialized")),e}function Mbe(t,e,n){if(n.ok)switch(n.action){case"add":case"replace":case"remove":t.sendNotification?.("memory.updated",{source:"agent-memdir",target:"index"});break;case"create_file":case"write_file":case"delete_file":t.sendNotification?.("memory.updated",{source:"agent-memdir",target:typeof e.file=="string"&&e.file.trim()?e.file.trim():"topic-file"});break;case"remember":t.sendNotification?.("memory.updated",{source:"agent-remember",target:"atlas"});break;case"feedback":t.sendNotification?.("memory.updated",{source:"agent-feedback",target:"atlas"});break}}function E_(t){t.toolCatalog.addTool({name:fW,label:gW,category:"memory",description:yW,parameters:hW,execute:async(e,n)=>{let r=t.memoryUserId?t.memoryProvider??void 0:void 0,o=t.getMemdir?.()??t.memdir,i=await vW(n,{memdir:o,provider:r,localProvider:r,userId:t.memoryUserId});return Mbe(t,n,i),{content:[{type:"text",text:i.message}],details:{type:"memory",action:i.action,ok:i.ok}}}})}var Vh=je(()=>{"use strict";__();bW();ni()});import{createRequire as nDe}from"node:module";import{createInterface as WX}from"node:readline";var wa=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)}
408
- `)}start(){process.stdin.on("data",n=>{process.stderr.write(`[transport] raw stdin data (${n.length} bytes): ${n.toString().slice(0,300)}
409
- `)});let e=WX({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",n=>{let r=n.trim();if(r){process.stderr.write(`[transport] line: ${r.slice(0,300)}
410
- `);try{let o=JSON.parse(r);this.messageHandler?.(o)}catch{process.stderr.write(`[transport] invalid JSON on stdin: ${r.slice(0,200)}
411
- `)}}}),e.on("close",()=>{this.closeHandler?.()})}close(){}log(e){this.verbose&&process.stderr.write(`[transport] ${e}
408
+ `)}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)}
409
+ `)});let n=WX({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)}
410
+ `);try{let i=JSON.parse(o);this.messageHandler?.(i)}catch{process.stderr.write(`[transport] invalid JSON on stdin: ${o.slice(0,200)}
411
+ `)}}}),n.on("close",()=>{this.closeHandler?.()})}close(){}log(e){this.verbose&&process.stderr.write(`[transport] ${e}
412
412
  `)}};ni();import*as Op from"node:fs";import*as wD from"node:path";Ke();import*as mD from"node:fs";import*as Il from"node:path";var vk="transcript.jsonl",wo="metadata.json";function iY(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}function ms(t){return ee().getProjectSessionDataRoot(t)}function Ur(t,e){return Il.join(ms(e),iY(t))}function bk(t,e){return Il.join(Ur(t,e),wo)}function $p(t,e){return Il.join(Ur(t,e),vk)}function kk(t,e){let n=Ur(t,e);if(mD.existsSync(Il.join(n,wo)))return n}import*as So from"node:fs";import*as _l from"node:path";var fD=".deleted";function wk(t,e){return _l.join(ms(e),fD,encodeURIComponent(t)+".json")}async function gD(t,e){let n=wk(t,e);await So.promises.mkdir(_l.dirname(n),{recursive:!0}),await So.promises.writeFile(n,JSON.stringify({sessionId:t,deletedAt:new Date().toISOString()},null,2),"utf8")}async function Cl(t,e){try{return await So.promises.access(wk(t,e),So.constants.F_OK),!0}catch{return!1}}function hD(t,e){return So.existsSync(wk(t,e))}async function yD(t){let e=_l.join(ms(t),fD),n;try{n=await So.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 Sk=0,vD=[],El=new Map;function sY(){return Sk<4?(Sk++,Promise.resolve()):new Promise(t=>vD.push(t))}function aY(){let t=vD.shift();t?t():Sk--}async function Np(t){await sY();try{return await t()}finally{aY()}}async function bD(t,e){let n=El.get(t)??Promise.resolve(),r,o=new Promise(s=>{r=s}),i=n.catch(()=>{}).then(()=>o);El.set(t,i),await n.catch(()=>{});try{return await e()}finally{r(),El.get(t)===i&&El.delete(t)}}async function kD(t){for(;;){let e=El.get(t);if(!e)return;await e.catch(()=>{})}}function SD(t,e){return`${e}\0${t}`}async function yr(t,e,n,r,o){let i=SD(t,n);return bD(i,async()=>{if(await Cl(t,n))return!1;let s=Ur(t,n);try{return await Op.promises.mkdir(s,{recursive:!0}),await Op.promises.appendFile(wD.join(s,vk),JSON.stringify(cY(e,r,o))+`
413
413
  `,"utf8"),!0}catch(a){return console.error(`[session-persistence] appendMessage failed for ${t}: ${a.message}`),!1}})}async function Ta(t,e){await kD(SD(t,e));let n=await xk(t,e);return n?n.messages.length:null}async function xk(t,e,n={}){let r;try{r=await Op.promises.readFile($p(t,e),"utf8")}catch{return null}let o=[],i=0;for(let s of r.split(`
414
414
  `))if(s.trim())try{o.push(lY(JSON.parse(s),n))}catch{i++}return{messages:o,corruptLines:i}}function cY(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 lY(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 Lt from"node:fs";import*as fs from"node:path";function xo(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 Tk(t){return t?.schemaVersion!==1||t.type==null}async function jp(t,e){let n=t+".tmp";await Lt.promises.writeFile(n,JSON.stringify(e,null,2),"utf8"),await Lt.promises.rename(n,t)}function dY(t,e){let n=t+".tmp";Lt.writeFileSync(n,JSON.stringify(e,null,2),"utf8"),Lt.renameSync(n,t)}function Kt(t,e){let n=kk(t,e);if(!n)return null;let r=fs.join(n,wo);try{let o=Lt.readFileSync(r,"utf8"),i=JSON.parse(o),s=xo(t,i);return Tk(i)&&dY(r,s),s}catch{return null}}async function Lp(t,e,n={}){let r=bk(t,e),o=null;try{o=JSON.parse(await Lt.promises.readFile(r,"utf8"))}catch{o=null}let i=xo(t,o,n);return(!o||Tk(o))&&(await Lt.promises.mkdir(fs.dirname(r),{recursive:!0}),await jp(r,i)),i}async function Ak(t,e,n,r){await Np(async()=>{if(await Cl(t,r))return;let o=Ur(t,r);await Lt.promises.mkdir(o,{recursive:!0});let i={};try{let l=await Lt.promises.readFile(fs.join(o,wo),"utf8");i=JSON.parse(l)}catch{i={}}let s=await Ta(t,r),a=new Date().toISOString(),c=xo(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 jp(fs.join(o,wo),c)})}async function vt(t,e,n){return Np(async()=>{if(await Cl(t,n))return null;let o=kk(t,n)??Ur(t,n),i=fs.join(o,wo),s=new Date().toISOString(),a;try{let l=await Lt.promises.readFile(i,"utf8");a=xo(t,JSON.parse(l))}catch{await Lt.promises.mkdir(o,{recursive:!0}),a=xo(t,{projectId:e.projectId??"",createdAt:s,lastActiveAt:s,turnCount:0,messageCount:0})}let c=uY(a,e);return c.lastActiveAt=s,await Lt.promises.mkdir(o,{recursive:!0}),await jp(i,c),c})}async function xD(t,e,n,r){await Np(async()=>{let o=await Lp(t,e);await jp(bk(t,e),{...o,taskSummary:n,taskSummaryGeneratedAt:r})})}function uY(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 xo(String(n.sessionId??t.sessionId),n)}import*as Up from"node:fs";async function Fr(t,e,n={}){try{await Up.promises.access(e,Up.constants.R_OK)}catch{return console.error(`[session-persistence] loadSessionForResume: projectRoot not accessible: ${e}`),null}let r=await xk(t,e,n);return r?(r.corruptLines>0&&console.warn(`[session-persistence] ${r.corruptLines} corrupt line(s) skipped in ${$p(t,e)}`),r.messages.length===0&&r.corruptLines>0?(console.error(`[session-persistence] Transcript fully corrupt for session ${t}`),null):{metadata:await Lp(t,e,{messageCount:r.messages.length}),messages:pY(r.messages,n.includeDisplayMetadata===!0)}):null}function pY(t,e){return t.filter(n=>n.role!=="system").map(n=>e?n:mY(n))}function mY(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 Aa from"node:fs";import*as RD from"node:path";an();async function cn(t=Hb,e){let n;try{n=await Aa.promises.readdir(ms(e))}catch{return[]}let r=[];for(let o of n){let i=RD.join(ms(e),o,wo);try{let s=await Aa.promises.readFile(i,"utf8"),a=xo(o,JSON.parse(s)),c=await Ta(o,e);r.push(fY({...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 Fp(t,e){await gD(t,e),await Promise.all([Aa.promises.rm(Ur(t,e),{recursive:!0,force:!0}),Aa.promises.rm(Mp(e,t),{recursive:!0,force:!0}),Aa.promises.rm(Dp(e,t),{recursive:!0,force:!0})])}function fY(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 gY=/[\u951f\ufffd]|[\uFFFD]|\u9225|\u20ac|\u9366|\u93b4|\u9428|\u7487|\u95b8|\u7ed7|\u710b|\u890e|\u5a4a|\u72b3|\u5f84|\u9368|\u7b91|\u6fb6\u682d|\u5134|\u6d7c\u6c33|\u763d/,hY=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/;function yY(t){return gY.test(t)||hY.test(t)}function Ml(t,e={}){let n=e.maxLength??40,r=t?.replace(/\s+/g," ").trim();if(r&&!yY(r))return r.slice(0,n)}function Dl(t,e,n={}){let r=n.maxLength??40,o=n.ellipsis??"...",i=Ml(t,{maxLength:r});return i?t.replace(/\s+/g," ").trim().length>r?`${i}${o}`:i:e}function TD(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 vY="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 AD(t){return t.turnCount<zb?!1:t.taskSummaryGeneratedAt?t.turnCount-(t.taskSummaryGeneratedAt??0)>=Bb:!0}async function Pk(t,e){if(!t.trim())return null;let n=TD(t);if(n)return n;try{let r=e.transport.stream({model:e.model,messages:[{role:"system",content:vY},{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,""),Ml(o,{maxLength:40})??null}catch{return null}}async function Ik(t,e,n,r,o){if(!AD(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(`
@@ -684,7 +684,7 @@ ${e}
684
684
  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 Ri(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:sc(e,"input",t.processors),output:sc(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 vT=(t,e={})=>n=>{let r=Si({...n,processors:e});return Pe(t,r),xi(r,t),Ri(r,t)},sc=(t,e,n={})=>r=>{let{libraryOptions:o,target:i}=r??{},s=Si({...o??{},target:i,io:e,processors:n});return Pe(t,s),xi(s,t),Ri(s,t)};var kse={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},bT=(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=kse[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}))])}},kT=(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)},wT=(t,e,n,r)=>{n.type="boolean"},ST=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},xT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},RT=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},TT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},AT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},PT=(t,e,n,r)=>{n.not={}},IT=(t,e,n,r)=>{},_T=(t,e,n,r)=>{},CT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},ET=(t,e,n,r)=>{let o=t._zod.def,i=cd(o.entries);i.every(s=>typeof s=="number")&&(n.type="number"),i.every(s=>typeof s=="string")&&(n.type="string"),n.enum=i},MT=(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},DT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},$T=(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},NT=(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)},OT=(t,e,n,r)=>{n.type="boolean"},jT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},LT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},UT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},FT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},HT=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},zT=(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"]})},BT=(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)},Hf=(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},qT=(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},WT=(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)},GT=(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)}},KT=(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"}]},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},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,n.default=JSON.parse(JSON.stringify(o.defaultValue))},ZT=(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)))},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;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=s},YT=(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},QT=(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},eA=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},zf=(t,e,n,r)=>{let o=t._zod.def;Pe(o.innerType,e,r);let i=e.seen.get(t);i.ref=o.innerType},tA=(t,e,n,r)=>{let o=t._zod.innerType;Pe(o,e,r);let i=e.seen.get(t);i.ref=o},Ff={string:bT,number:kT,boolean:wT,bigint:ST,symbol:xT,null:RT,undefined:TT,void:AT,never:PT,any:IT,unknown:_T,date:CT,enum:ET,literal:MT,nan:DT,template_literal:$T,file:NT,success:OT,custom:jT,function:LT,transform:UT,map:FT,set:HT,array:zT,object:BT,union:Hf,intersection:qT,tuple:WT,record:GT,nullable:KT,nonoptional:VT,default:JT,prefault:ZT,catch:XT,pipe:YT,readonly:QT,promise:eA,optional:zf,lazy:tA};function Bf(t,e){if("_idmap"in t){let r=t,o=Si({...e,processors:Ff}),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;xi(o,d),s[l]=Ri(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=Si({...e,processors:Ff});return Pe(t,n),xi(n,t),Ri(n,t)}var qf=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=Si({processors:Ff,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)),xi(this.ctx,e);let r=Ri(this.ctx,e),{"~standard":o,...i}=r;return i}};var qj={};var Ad={};sn(Ad,{ZodAny:()=>TA,ZodArray:()=>_A,ZodBase64:()=>ug,ZodBase64URL:()=>pg,ZodBigInt:()=>fc,ZodBigIntFormat:()=>gg,ZodBoolean:()=>mc,ZodCIDRv4:()=>lg,ZodCIDRv6:()=>dg,ZodCUID:()=>ng,ZodCUID2:()=>rg,ZodCatch:()=>XA,ZodCodec:()=>Ld,ZodCustom:()=>Ud,ZodCustomStringFormat:()=>uc,ZodDate:()=>Dd,ZodDefault:()=>WA,ZodDiscriminatedUnion:()=>EA,ZodE164:()=>mg,ZodEmail:()=>Qf,ZodEmoji:()=>eg,ZodEnum:()=>lc,ZodExactOptional:()=>zA,ZodFile:()=>FA,ZodFunction:()=>aP,ZodGUID:()=>Id,ZodIPv4:()=>ag,ZodIPv6:()=>cg,ZodIntersection:()=>MA,ZodJWT:()=>fg,ZodKSUID:()=>sg,ZodLazy:()=>oP,ZodLiteral:()=>UA,ZodMAC:()=>vA,ZodMap:()=>jA,ZodNaN:()=>QA,ZodNanoID:()=>tg,ZodNever:()=>PA,ZodNonOptional:()=>wg,ZodNull:()=>xA,ZodNullable:()=>qA,ZodNumber:()=>pc,ZodNumberFormat:()=>Fs,ZodObject:()=>Nd,ZodOptional:()=>kg,ZodPipe:()=>jd,ZodPrefault:()=>KA,ZodPreprocess:()=>eP,ZodPromise:()=>sP,ZodReadonly:()=>tP,ZodRecord:()=>cc,ZodSet:()=>LA,ZodString:()=>dc,ZodStringFormat:()=>$e,ZodSuccess:()=>ZA,ZodSymbol:()=>wA,ZodTemplateLiteral:()=>rP,ZodTransform:()=>HA,ZodTuple:()=>$A,ZodType:()=>ue,ZodULID:()=>og,ZodURL:()=>Md,ZodUUID:()=>Vr,ZodUndefined:()=>SA,ZodUnion:()=>Od,ZodUnknown:()=>AA,ZodVoid:()=>IA,ZodXID:()=>ig,ZodXor:()=>CA,_ZodString:()=>Yf,_default:()=>GA,_function:()=>QL,any:()=>CL,array:()=>$d,base64:()=>mL,base64url:()=>fL,bigint:()=>TL,boolean:()=>kA,catch:()=>YA,check:()=>eU,cidrv4:()=>uL,cidrv6:()=>pL,codec:()=>JL,cuid:()=>rL,cuid2:()=>oL,custom:()=>tU,date:()=>ML,describe:()=>nU,discriminatedUnion:()=>LL,e164:()=>gL,email:()=>Kj,emoji:()=>tL,enum:()=>vg,exactOptional:()=>BA,file:()=>WL,float32:()=>wL,float64:()=>SL,function:()=>QL,guid:()=>Vj,hash:()=>kL,hex:()=>bL,hostname:()=>vL,httpUrl:()=>eL,instanceof:()=>oU,int:()=>Zf,int32:()=>xL,int64:()=>AL,intersection:()=>DA,invertCodec:()=>ZL,ipv4:()=>cL,ipv6:()=>dL,json:()=>sU,jwt:()=>hL,keyof:()=>DL,ksuid:()=>aL,lazy:()=>iP,literal:()=>qL,looseObject:()=>OL,looseRecord:()=>FL,mac:()=>lL,map:()=>HL,meta:()=>rU,nan:()=>VL,nanoid:()=>nL,nativeEnum:()=>BL,never:()=>hg,nonoptional:()=>JA,null:()=>RA,nullable:()=>Cd,nullish:()=>GL,number:()=>bA,object:()=>$L,optional:()=>_d,partialRecord:()=>UL,pipe:()=>Xf,prefault:()=>VA,preprocess:()=>aU,promise:()=>YL,readonly:()=>nP,record:()=>OA,refine:()=>cP,set:()=>zL,strictObject:()=>NL,string:()=>Pd,stringFormat:()=>yL,stringbool:()=>iU,success:()=>KL,superRefine:()=>lP,symbol:()=>IL,templateLiteral:()=>XL,transform:()=>bg,tuple:()=>NA,uint32:()=>RL,uint64:()=>PL,ulid:()=>iL,undefined:()=>_L,union:()=>yg,unknown:()=>Us,url:()=>Qj,uuid:()=>Jj,uuidv4:()=>Zj,uuidv6:()=>Xj,uuidv7:()=>Yj,void:()=>EL,xid:()=>sL,xor:()=>jL});var Wf={};sn(Wf,{endsWith:()=>Ya,gt:()=>Gr,gte:()=>Xt,includes:()=>Za,length:()=>Ls,lowercase:()=>Va,lt:()=>Wr,lte:()=>jn,maxLength:()=>js,maxSize:()=>wi,mime:()=>Qa,minLength:()=>Co,minSize:()=>Kr,multipleOf:()=>ki,negative:()=>Of,nonnegative:()=>Lf,nonpositive:()=>jf,normalize:()=>ec,overwrite:()=>kr,positive:()=>Nf,property:()=>Uf,regex:()=>Ka,size:()=>Os,slugify:()=>oc,startsWith:()=>Xa,toLowerCase:()=>nc,toUpperCase:()=>rc,trim:()=>tc,uppercase:()=>Ja});var ac={};sn(ac,{ZodISODate:()=>Kf,ZodISODateTime:()=>Gf,ZodISODuration:()=>Jf,ZodISOTime:()=>Vf,date:()=>rA,datetime:()=>nA,duration:()=>iA,time:()=>oA});var Gf=I("ZodISODateTime",(t,e)=>{Dx.init(t,e),$e.init(t,e)});function nA(t){return jR(Gf,t)}var Kf=I("ZodISODate",(t,e)=>{$x.init(t,e),$e.init(t,e)});function rA(t){return LR(Kf,t)}var Vf=I("ZodISOTime",(t,e)=>{Nx.init(t,e),$e.init(t,e)});function oA(t){return UR(Vf,t)}var Jf=I("ZodISODuration",(t,e)=>{Ox.init(t,e),$e.init(t,e)});function iA(t){return FR(Jf,t)}var Wj=(t,e)=>{md.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>gd(t,n)},flatten:{value:n=>fd(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,La,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,La,2)}},isEmpty:{get(){return t.issues.length===0}}})},Sse=I("ZodError",Wj),mn=I("ZodError",Wj,{Parent:Error});var sA=Ha(mn),aA=za(mn),cA=Ba(mn),lA=qa(mn),dA=zm(mn),uA=Bm(mn),pA=qm(mn),mA=Wm(mn),fA=Gm(mn),gA=Km(mn),hA=Vm(mn),yA=Jm(mn);var Gj=new WeakMap;function Ed(t,e,n){let r=Object.getPrototypeOf(t),o=Gj.get(r);if(o||(o=new Set,Gj.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:sc(t,"input"),output:sc(t,"output")}}),t.toJSONSchema=vT(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>sA(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>cA(t,n,r),t.parseAsync=async(n,r)=>aA(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>lA(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>dA(t,n,r),t.decode=(n,r)=>uA(t,n,r),t.encodeAsync=async(n,r)=>pA(t,n,r),t.decodeAsync=async(n,r)=>mA(t,n,r),t.safeEncode=(n,r)=>fA(t,n,r),t.safeDecode=(n,r)=>gA(t,n,r),t.safeEncodeAsync=async(n,r)=>hA(t,n,r),t.safeDecodeAsync=async(n,r)=>yA(t,n,r),Ed(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(cP(n,r))},superRefine(n,r){return this.check(lP(n,r))},overwrite(n){return this.check(kr(n))},optional(){return _d(this)},exactOptional(){return BA(this)},nullable(){return Cd(this)},nullish(){return _d(Cd(this))},nonoptional(n){return JA(this,n)},array(){return $d(this)},or(n){return yg([this,n])},and(n){return DA(this,n)},transform(n){return Xf(this,bg(n))},default(n){return GA(this,n)},prefault(n){return VA(this,n)},catch(n){return YA(this,n)},pipe(n){return Xf(this,n)},readonly(){return nP(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)),Yf=I("_ZodString",(t,e)=>{Ns.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>bT(t,r,o,i);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,Ed(t,"_ZodString",{regex(...r){return this.check(Ka(...r))},includes(...r){return this.check(Za(...r))},startsWith(...r){return this.check(Xa(...r))},endsWith(...r){return this.check(Ya(...r))},min(...r){return this.check(Co(...r))},max(...r){return this.check(js(...r))},length(...r){return this.check(Ls(...r))},nonempty(...r){return this.check(Co(1,...r))},lowercase(r){return this.check(Va(r))},uppercase(r){return this.check(Ja(r))},trim(){return this.check(tc())},normalize(...r){return this.check(ec(...r))},toLowerCase(){return this.check(nc())},toUpperCase(){return this.check(rc())},slugify(){return this.check(oc())}})}),dc=I("ZodString",(t,e)=>{Ns.init(t,e),Yf.init(t,e),t.email=n=>t.check(gf(Qf,n)),t.url=n=>t.check(Td(Md,n)),t.jwt=n=>t.check($f(fg,n)),t.emoji=n=>t.check(kf(eg,n)),t.guid=n=>t.check(Rd(Id,n)),t.uuid=n=>t.check(hf(Vr,n)),t.uuidv4=n=>t.check(yf(Vr,n)),t.uuidv6=n=>t.check(vf(Vr,n)),t.uuidv7=n=>t.check(bf(Vr,n)),t.nanoid=n=>t.check(wf(tg,n)),t.guid=n=>t.check(Rd(Id,n)),t.cuid=n=>t.check(Sf(ng,n)),t.cuid2=n=>t.check(xf(rg,n)),t.ulid=n=>t.check(Rf(og,n)),t.base64=n=>t.check(Ef(ug,n)),t.base64url=n=>t.check(Mf(pg,n)),t.xid=n=>t.check(Tf(ig,n)),t.ksuid=n=>t.check(Af(sg,n)),t.ipv4=n=>t.check(Pf(ag,n)),t.ipv6=n=>t.check(If(cg,n)),t.cidrv4=n=>t.check(_f(lg,n)),t.cidrv6=n=>t.check(Cf(dg,n)),t.e164=n=>t.check(Df(mg,n)),t.datetime=n=>t.check(nA(n)),t.date=n=>t.check(rA(n)),t.time=n=>t.check(oA(n)),t.duration=n=>t.check(iA(n))});function Pd(t){return DR(dc,t)}var $e=I("ZodStringFormat",(t,e)=>{De.init(t,e),Yf.init(t,e)}),Qf=I("ZodEmail",(t,e)=>{Rx.init(t,e),$e.init(t,e)});function Kj(t){return gf(Qf,t)}var Id=I("ZodGUID",(t,e)=>{Sx.init(t,e),$e.init(t,e)});function Vj(t){return Rd(Id,t)}var Vr=I("ZodUUID",(t,e)=>{xx.init(t,e),$e.init(t,e)});function Jj(t){return hf(Vr,t)}function Zj(t){return yf(Vr,t)}function Xj(t){return vf(Vr,t)}function Yj(t){return bf(Vr,t)}var Md=I("ZodURL",(t,e)=>{Tx.init(t,e),$e.init(t,e)});function Qj(t){return Td(Md,t)}function eL(t){return Td(Md,{protocol:On.httpProtocol,hostname:On.domain,...F.normalizeParams(t)})}var eg=I("ZodEmoji",(t,e)=>{Ax.init(t,e),$e.init(t,e)});function tL(t){return kf(eg,t)}var tg=I("ZodNanoID",(t,e)=>{Px.init(t,e),$e.init(t,e)});function nL(t){return wf(tg,t)}var ng=I("ZodCUID",(t,e)=>{Ix.init(t,e),$e.init(t,e)});function rL(t){return Sf(ng,t)}var rg=I("ZodCUID2",(t,e)=>{_x.init(t,e),$e.init(t,e)});function oL(t){return xf(rg,t)}var og=I("ZodULID",(t,e)=>{Cx.init(t,e),$e.init(t,e)});function iL(t){return Rf(og,t)}var ig=I("ZodXID",(t,e)=>{Ex.init(t,e),$e.init(t,e)});function sL(t){return Tf(ig,t)}var sg=I("ZodKSUID",(t,e)=>{Mx.init(t,e),$e.init(t,e)});function aL(t){return Af(sg,t)}var ag=I("ZodIPv4",(t,e)=>{jx.init(t,e),$e.init(t,e)});function cL(t){return Pf(ag,t)}var vA=I("ZodMAC",(t,e)=>{Ux.init(t,e),$e.init(t,e)});function lL(t){return NR(vA,t)}var cg=I("ZodIPv6",(t,e)=>{Lx.init(t,e),$e.init(t,e)});function dL(t){return If(cg,t)}var lg=I("ZodCIDRv4",(t,e)=>{Fx.init(t,e),$e.init(t,e)});function uL(t){return _f(lg,t)}var dg=I("ZodCIDRv6",(t,e)=>{Hx.init(t,e),$e.init(t,e)});function pL(t){return Cf(dg,t)}var ug=I("ZodBase64",(t,e)=>{Bx.init(t,e),$e.init(t,e)});function mL(t){return Ef(ug,t)}var pg=I("ZodBase64URL",(t,e)=>{qx.init(t,e),$e.init(t,e)});function fL(t){return Mf(pg,t)}var mg=I("ZodE164",(t,e)=>{Wx.init(t,e),$e.init(t,e)});function gL(t){return Df(mg,t)}var fg=I("ZodJWT",(t,e)=>{Gx.init(t,e),$e.init(t,e)});function hL(t){return $f(fg,t)}var uc=I("ZodCustomStringFormat",(t,e)=>{Kx.init(t,e),$e.init(t,e)});function yL(t,e,n={}){return ic(uc,t,e,n)}function vL(t){return ic(uc,"hostname",On.hostname,t)}function bL(t){return ic(uc,"hex",On.hex,t)}function kL(t,e){let n=e?.enc??"hex",r=`${t}_${n}`,o=On[r];if(!o)throw new Error(`Unrecognized hash format: ${r}`);return ic(uc,r,o,e)}var pc=I("ZodNumber",(t,e)=>{of.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>kT(t,r,o,i),Ed(t,"ZodNumber",{gt(r,o){return this.check(Gr(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(Wr(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(Zf(r))},safe(r){return this.check(Zf(r))},positive(r){return this.check(Gr(0,r))},nonnegative(r){return this.check(Xt(0,r))},negative(r){return this.check(Wr(0,r))},nonpositive(r){return this.check(jn(0,r))},multipleOf(r,o){return this.check(ki(r,o))},step(r,o){return this.check(ki(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 bA(t){return HR(pc,t)}var Fs=I("ZodNumberFormat",(t,e)=>{Vx.init(t,e),pc.init(t,e)});function Zf(t){return BR(Fs,t)}function wL(t){return qR(Fs,t)}function SL(t){return WR(Fs,t)}function xL(t){return GR(Fs,t)}function RL(t){return KR(Fs,t)}var mc=I("ZodBoolean",(t,e)=>{bd.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>wT(t,n,r,o)});function kA(t){return VR(mc,t)}var fc=I("ZodBigInt",(t,e)=>{sf.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>ST(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(Gr(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(Wr(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(Gr(BigInt(0),r)),t.negative=r=>t.check(Wr(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(ki(r,o));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});function TL(t){return ZR(fc,t)}var gg=I("ZodBigIntFormat",(t,e)=>{Jx.init(t,e),fc.init(t,e)});function AL(t){return YR(gg,t)}function PL(t){return QR(gg,t)}var wA=I("ZodSymbol",(t,e)=>{Zx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>xT(t,n,r,o)});function IL(t){return eT(wA,t)}var SA=I("ZodUndefined",(t,e)=>{Xx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>TT(t,n,r,o)});function _L(t){return tT(SA,t)}var xA=I("ZodNull",(t,e)=>{Yx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>RT(t,n,r,o)});function RA(t){return nT(xA,t)}var TA=I("ZodAny",(t,e)=>{Qx.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>IT(t,n,r,o)});function CL(){return rT(TA)}var AA=I("ZodUnknown",(t,e)=>{eR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>_T(t,n,r,o)});function Us(){return oT(AA)}var PA=I("ZodNever",(t,e)=>{tR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>PT(t,n,r,o)});function hg(t){return iT(PA,t)}var IA=I("ZodVoid",(t,e)=>{nR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>AT(t,n,r,o)});function EL(t){return sT(IA,t)}var Dd=I("ZodDate",(t,e)=>{rR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>CT(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 ML(t){return aT(Dd,t)}var _A=I("ZodArray",(t,e)=>{oR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>zT(t,n,r,o),t.element=e.element,Ed(t,"ZodArray",{min(n,r){return this.check(Co(n,r))},nonempty(n){return this.check(Co(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 $d(t,e){return dT(_A,t,e)}function DL(t){let e=t._zod.def.shape;return vg(Object.keys(e))}var Nd=I("ZodObject",(t,e)=>{iR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>BT(t,n,r,o),F.defineLazy(t,"shape",()=>e.shape),Ed(t,"ZodObject",{keyof(){return vg(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:hg()})},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(kg,this,n[0])},required(...n){return F.required(wg,this,n[0])}})});function $L(t,e){let n={type:"object",shape:t??{},...F.normalizeParams(e)};return new Nd(n)}function NL(t,e){return new Nd({type:"object",shape:t,catchall:hg(),...F.normalizeParams(e)})}function OL(t,e){return new Nd({type:"object",shape:t,catchall:Us(),...F.normalizeParams(e)})}var Od=I("ZodUnion",(t,e)=>{kd.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Hf(t,n,r,o),t.options=e.options});function yg(t,e){return new Od({type:"union",options:t,...F.normalizeParams(e)})}var CA=I("ZodXor",(t,e)=>{Od.init(t,e),sR.init(t,e),t._zod.processJSONSchema=(n,r,o)=>Hf(t,n,r,o),t.options=e.options});function jL(t,e){return new CA({type:"union",options:t,inclusive:!1,...F.normalizeParams(e)})}var EA=I("ZodDiscriminatedUnion",(t,e)=>{Od.init(t,e),aR.init(t,e)});function LL(t,e,n){return new EA({type:"union",options:e,discriminator:t,...F.normalizeParams(n)})}var MA=I("ZodIntersection",(t,e)=>{cR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>qT(t,n,r,o)});function DA(t,e){return new MA({type:"intersection",left:t,right:e})}var $A=I("ZodTuple",(t,e)=>{af.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>WT(t,n,r,o),t.rest=n=>t.clone({...t._zod.def,rest:n})});function NA(t,e,n){let r=e instanceof ie,o=r?n:e,i=r?e:null;return new $A({type:"tuple",items:t,rest:i,...F.normalizeParams(o)})}var cc=I("ZodRecord",(t,e)=>{lR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>GT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType});function OA(t,e,n){return!e||!e._zod?new cc({type:"record",keyType:Pd(),valueType:t,...F.normalizeParams(e)}):new cc({type:"record",keyType:t,valueType:e,...F.normalizeParams(n)})}function UL(t,e,n){let r=Jt(t);return r._zod.values=void 0,new cc({type:"record",keyType:r,valueType:e,...F.normalizeParams(n)})}function FL(t,e,n){return new cc({type:"record",keyType:t,valueType:e,mode:"loose",...F.normalizeParams(n)})}var jA=I("ZodMap",(t,e)=>{dR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>FT(t,n,r,o),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...n)=>t.check(Kr(...n)),t.nonempty=n=>t.check(Kr(1,n)),t.max=(...n)=>t.check(wi(...n)),t.size=(...n)=>t.check(Os(...n))});function HL(t,e,n){return new jA({type:"map",keyType:t,valueType:e,...F.normalizeParams(n)})}var LA=I("ZodSet",(t,e)=>{uR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>HT(t,n,r,o),t.min=(...n)=>t.check(Kr(...n)),t.nonempty=n=>t.check(Kr(1,n)),t.max=(...n)=>t.check(wi(...n)),t.size=(...n)=>t.check(Os(...n))});function zL(t,e){return new LA({type:"set",valueType:t,...F.normalizeParams(e)})}var lc=I("ZodEnum",(t,e)=>{pR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(r,o,i)=>ET(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 lc({...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 lc({...e,checks:[],...F.normalizeParams(o),entries:i})}});function vg(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new lc({type:"enum",entries:n,...F.normalizeParams(e)})}function BL(t,e){return new lc({type:"enum",entries:t,...F.normalizeParams(e)})}var UA=I("ZodLiteral",(t,e)=>{mR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>MT(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 qL(t,e){return new UA({type:"literal",values:Array.isArray(t)?t:[t],...F.normalizeParams(e)})}var FA=I("ZodFile",(t,e)=>{fR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>NT(t,n,r,o),t.min=(n,r)=>t.check(Kr(n,r)),t.max=(n,r)=>t.check(wi(n,r)),t.mime=(n,r)=>t.check(Qa(Array.isArray(n)?n:[n],r))});function WL(t){return uT(FA,t)}var HA=I("ZodTransform",(t,e)=>{gR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>UT(t,n,r,o),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gi(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 bg(t){return new HA({type:"transform",transform:t})}var kg=I("ZodOptional",(t,e)=>{cf.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>zf(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function _d(t){return new kg({type:"optional",innerType:t})}var zA=I("ZodExactOptional",(t,e)=>{hR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>zf(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function BA(t){return new zA({type:"optional",innerType:t})}var qA=I("ZodNullable",(t,e)=>{yR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>KT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function Cd(t){return new qA({type:"nullable",innerType:t})}function GL(t){return _d(Cd(t))}var WA=I("ZodDefault",(t,e)=>{vR.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.removeDefault=t.unwrap});function GA(t,e){return new WA({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var KA=I("ZodPrefault",(t,e)=>{bR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>ZT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function VA(t,e){return new KA({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():F.shallowClone(e)}})}var wg=I("ZodNonOptional",(t,e)=>{kR.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 JA(t,e){return new wg({type:"nonoptional",innerType:t,...F.normalizeParams(e)})}var ZA=I("ZodSuccess",(t,e)=>{wR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>OT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function KL(t){return new ZA({type:"success",innerType:t})}var XA=I("ZodCatch",(t,e)=>{SR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>XT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function YA(t,e){return new XA({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var QA=I("ZodNaN",(t,e)=>{xR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>DT(t,n,r,o)});function VL(t){return lT(QA,t)}var jd=I("ZodPipe",(t,e)=>{lf.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>YT(t,n,r,o),t.in=e.in,t.out=e.out});function Xf(t,e){return new jd({type:"pipe",in:t,out:e})}var Ld=I("ZodCodec",(t,e)=>{jd.init(t,e),wd.init(t,e)});function JL(t,e,n){return new Ld({type:"pipe",in:t,out:e,transform:n.decode,reverseTransform:n.encode})}function ZL(t){let e=t._zod.def;return new Ld({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var eP=I("ZodPreprocess",(t,e)=>{jd.init(t,e),RR.init(t,e)}),tP=I("ZodReadonly",(t,e)=>{TR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>QT(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function nP(t){return new tP({type:"readonly",innerType:t})}var rP=I("ZodTemplateLiteral",(t,e)=>{AR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>$T(t,n,r,o)});function XL(t,e){return new rP({type:"template_literal",parts:t,...F.normalizeParams(e)})}var oP=I("ZodLazy",(t,e)=>{_R.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>tA(t,n,r,o),t.unwrap=()=>t._zod.def.getter()});function iP(t){return new oP({type:"lazy",getter:t})}var sP=I("ZodPromise",(t,e)=>{IR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>eA(t,n,r,o),t.unwrap=()=>t._zod.def.innerType});function YL(t){return new sP({type:"promise",innerType:t})}var aP=I("ZodFunction",(t,e)=>{PR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>LT(t,n,r,o)});function QL(t){return new aP({type:"function",input:Array.isArray(t?.input)?NA(t?.input):t?.input??$d(Us()),output:t?.output??Us()})}var Ud=I("ZodCustom",(t,e)=>{CR.init(t,e),ue.init(t,e),t._zod.processJSONSchema=(n,r,o)=>jT(t,n,r,o)});function eU(t){let e=new Le({check:"custom"});return e._zod.check=t,e}function tU(t,e){return pT(Ud,t??(()=>!0),e)}function cP(t,e={}){return mT(Ud,t,e)}function lP(t,e){return fT(t,e)}var nU=gT,rU=hT;function oU(t,e={}){let n=new Ud({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 iU=(...t)=>yT({Codec:Ld,Boolean:mc,String:dc},...t);function sU(t){let e=iP(()=>yg([Pd(t),bA(),kA(),RA(),$d(e),OA(Pd(),e)]));return e}function aU(t,e){return new eP({type:"pipe",in:bg(t),out:e})}var Rse={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 Tse(t){Ye({customError:t})}function Ase(){return Ye().customError}var dP;dP||(dP={});var G={...Ad,...Wf,iso:ac},Pse=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 Ise(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 _se(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 cU(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=_se(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 cU(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=cU(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))Pse.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 lU(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=Ise(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 uP={};sn(uP,{bigint:()=>Dse,boolean:()=>Mse,date:()=>$se,number:()=>Ese,string:()=>Cse});function Cse(t){return $R(dc,t)}function Ese(t){return zR(pc,t)}function Mse(t){return JR(mc,t)}function Dse(t){return XR(fc,t)}function $se(t){return cT(Dd,t)}Ye(df());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"},cr={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 dU=Symbol("skippedItem");function W(t,e){return t.catch(e)}function wr(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(dU)).transform(e=>e.filter(n=>n!==dU))}var Ose=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminal:u.boolean().optional().default(!1)}),jse=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)}),Lse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:u.string(),name:u.string()}),Use=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(jse)}),Fse=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()}),Hse=u.union([Use.and(u.object({type:u.literal("env_var")})),Fse.and(u.object({type:u.literal("terminal")})),Lse]),uU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),methodId:u.string()}),zse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Bse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),blob:u.string(),mimeType:u.string().nullish(),uri:u.string()}),qse=u.object({default:u.boolean().nullish(),description:u.string().nullish(),title:u.string().nullish()}),Wse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Gse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Kse=u.object({amount:u.number(),currency:u.string()}),Vse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),Jse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Zse=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),newText:u.string(),oldText:u.string().nullish(),path:u.string()}),pU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string()}),Xse=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Yse=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())]),eae=u.object({content:u.record(u.string(),Qse).nullish()}),tae=u.intersection(u.union([eae.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()})),nae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),mU=u.string(),mP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),elicitationId:mU}),rae=u.literal("object"),oae=u.literal("string"),iae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),sae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),form:W(nae.nullish(),()=>{}),url:W(iae.nullish(),()=>{})}),fU=u.object({const:u.string(),title:u.string()}),gU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),aae=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"})]),hU=u.object({code:aae,data:u.unknown().optional(),message:u.string()}),yU=u.unknown(),vU=u.unknown(),bU=u.unknown(),cae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),readTextFile:u.boolean().optional().default(!1),writeTextFile:u.boolean().optional().default(!1)}),kU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),wU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),title:u.string().nullish(),version:u.string()}),lae=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),dae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),SU=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cursor:u.string().nullish(),cwd:u.string().nullish()}),fP=u.union([u.literal("anthropic"),u.literal("openai"),u.literal("azure"),u.literal("vertex"),u.literal("bedrock"),u.string()]),uae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),pae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),logout:W(uae.nullish(),()=>{})}),RU=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),mae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),fae=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)}),Sg=u.string(),gae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:Sg}),hae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:Sg}),TU=u.string(),yae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),acpId:TU}),vae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:TU,name:u.string()}),bae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(kU),name:u.string(),url:u.string()}),kae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(kU),name:u.string(),url:u.string()}),wae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),args:u.array(u.string()),command:u.string(),env:u.array(gU),name:u.string()}),xg=u.union([bae.and(u.object({type:u.literal("http")})),kae.and(u.object({type:u.literal("sse")})),vae.and(u.object({type:u.literal("acp")})),wae]),Sae=u.string(),AU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:Sg,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),PU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:Sg,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),IU=u.unknown(),xae=u.union([u.literal("error"),u.literal("warning"),u.literal("information"),u.literal("hint")]),Rae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Tae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Aae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Pae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Iae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),_ae=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()}),Cae=u.object({diff:u.string(),uri:u.string()}),Eae=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()}),Mae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Dae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),$ae=u.object({languageId:u.string(),text:u.string(),uri:u.string()}),Nae=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()}),Oae=u.union([u.literal("rejected"),u.literal("ignored"),u.literal("replaced"),u.literal("cancelled")]),jae=u.object({excerpts:u.array(Eae),uri:u.string()}),Lae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Uae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Fae=u.object({name:u.string(),owner:u.string(),remoteUrl:u.string()}),Hae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),zae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),jump:W(Mae.nullish(),()=>{}),rename:W(Uae.nullish(),()=>{}),searchAndReplace:W(Hae.nullish(),()=>{})}),Bae=u.object({id:u.string(),isRegex:u.boolean().nullish(),replace:u.string(),search:u.string(),uri:u.string()}),qae=u.union([u.literal("automatic"),u.literal("diagnostic"),u.literal("manual")]),Wae=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()}),Gae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:W(Rae.nullish(),()=>{}),editHistory:W(_ae.nullish(),()=>{}),openFiles:W(Dae.nullish(),()=>{}),recentFiles:W(Nae.nullish(),()=>{}),relatedSnippets:W(Lae.nullish(),()=>{}),userActions:W(Wae.nullish(),()=>{})}),_U=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(xg)}),Kae=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),CU=u.string(),Vae=u.union([u.literal("allow_once"),u.literal("allow_always"),u.literal("reject_once"),u.literal("reject_always")]),Jae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),kind:Vae,name:u.string(),optionId:CU}),Zae=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Xae=u.union([u.literal("high"),u.literal("medium"),u.literal("low")]),Yae=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed")]),EU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),priority:Xae,status:Yae}),Qae=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:wr(Ce(EU),()=>[])}),Rg=u.string(),ece=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:Rg,uri:u.string()}),tce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:wr(Ce(EU),()=>[]),id:Rg}),nce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),id:Rg}),rce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:Rg}),oce=u.union([tce.and(u.object({type:u.literal("items")})),ece.and(u.object({type:u.literal("file")})),nce.and(u.object({type:u.literal("markdown")}))]),ice=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),plan:oce}),Ti=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"})}),sce=u.object({id:u.string(),position:Ti,uri:u.string()}),ace=u.object({id:u.string(),newName:u.string(),position:Ti,uri:u.string()}),cce=u.object({action:u.string(),position:Ti,timestampMs:u.number(),uri:u.string()}),MU=u.union([u.literal("utf-16"),u.literal("utf-32"),u.literal("utf-8")]),lce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:Ose.optional().default({terminal:!1}),elicitation:W(sae.nullish(),()=>{}),fs:cae.optional().default({readTextFile:!1,writeTextFile:!1}),nes:W(zae.nullish(),()=>{}),plan:W(Zae.nullish(),()=>{}),positionEncodings:W(Ce(MU).optional(),()=>[]),terminal:u.boolean().optional().default(!1)}),dce=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)}),DU=u.number().int().gte(0).lte(65535),$U=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),clientCapabilities:lce.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:W(wU.nullish(),()=>{}),protocolVersion:DU}),uce=u.object({apiType:fP,baseUrl:u.string()}),pce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),current:uce.nullish(),id:u.string(),required:u.boolean(),supported:wr(Ce(fP),()=>[])}),mce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),providers:wr(Ce(pce),()=>[])}),fce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),gc=u.object({end:Ti,start:Ti}),gce=u.object({message:u.string(),range:gc,severity:xae,uri:u.string()}),hce=u.object({languageId:u.string(),lastFocusedMs:W(u.number().nullish(),()=>{}),uri:u.string(),visibleRange:W(gc.nullish(),()=>{})}),yce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:W(Ce(gce).nullish(),()=>{}),editHistory:W(Ce(Cae).nullish(),()=>{}),openFiles:W(Ce(hce).nullish(),()=>{}),recentFiles:W(Ce($ae).nullish(),()=>{}),relatedSnippets:W(Ce(jae).nullish(),()=>{}),userActions:W(Ce(cce).nullish(),()=>{})}),vce=u.object({newText:u.string(),range:gc}),bce=u.object({cursorPosition:W(Ti.nullish(),()=>{}),edits:u.array(vce),id:u.string(),uri:u.string()}),kce=u.union([bce.and(u.object({kind:u.literal("edit")})),sce.and(u.object({kind:u.literal("jump")})),ace.and(u.object({kind:u.literal("rename")})),Bae.and(u.object({kind:u.literal("searchAndReplace")}))]),wce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string()}),Sce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Ai=u.union([u.number(),u.string()]).nullable(),Hze=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),requestId:Ai}),NU=u.object({requestId:Ai}),xce=u.enum(["assistant","user"]),Fd=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),audience:W(Ce(xce).nullish(),()=>{}),lastModified:u.string().nullish(),priority:u.number().nullish()}),Rce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(Fd.nullish(),()=>{}),data:u.string(),mimeType:u.string()}),Tce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(Fd.nullish(),()=>{}),data:u.string(),mimeType:u.string(),uri:u.string().nullish()}),Ace=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(Fd.nullish(),()=>{}),description:u.string().nullish(),mimeType:u.string().nullish(),name:u.string(),size:u.number().nullish(),title:u.string().nullish(),uri:u.string()}),Pce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),optionId:CU}),Ice=u.union([u.object({outcome:u.literal("cancelled")}),Pce.and(u.object({outcome:u.literal("selected")}))]),_ce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),outcome:Ice}),Cce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Ece=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Mce=u.object({currentValue:u.boolean()}),Dce=u.string(),OU=u.string(),$ce=u.union([u.literal("mode"),u.literal("model"),u.literal("thought_level"),u.string()]),gP=u.string(),jU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),name:u.string(),value:gP}),Nce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),group:Dce,name:u.string(),options:u.array(jU)}),Oce=u.union([u.array(jU),u.array(Nce)]),jce=u.object({currentValue:gP,options:Oce}),hc=u.intersection(u.union([jce.and(u.object({type:u.literal("select")})),Mce.and(u.object({type:u.literal("boolean")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),category:W($ce.nullish(),()=>{}),description:u.string().nullish(),id:OU,name:u.string()})),Lce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:wr(Ce(hc),()=>[])}),Uce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Fce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xe=u.string(),LU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),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}),HU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),hP=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(gU).optional(),outputByteLimit:u.number().nullish(),sessionId:xe}),zU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),BU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,uri:u.string()}),qU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),position:Ti,sessionId:xe,uri:u.string(),version:u.number(),visibleRange:gc}),WU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),languageId:u.string(),sessionId:xe,text:u.string(),uri:u.string(),version:u.number()}),GU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,uri: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(xg).optional(),sessionId:xe}),yP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),VU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(xg),sessionId:xe}),vP=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}),JU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),reason:W(Oae.nullish(),()=>{}),sessionId:xe}),bP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),ZU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(xg).optional(),sessionId:xe}),Hce=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(),()=>{})}),zce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),nextCursor:u.string().nullish(),sessions:wr(Ce(Hce),()=>[])}),Bce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),title:u.string().nullish(),updatedAt:u.string().nullish()}),qce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Tg=u.string(),Wce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),currentModeId:Tg}),Gce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:Tg,name:u.string()}),Ag=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableModes:wr(Ce(Gce),()=>[]),currentModeId:Tg}),Kce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(hc).nullish(),()=>{}),modes:W(Ag.nullish(),()=>{}),sessionId:xe}),Vce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(hc).nullish(),()=>{}),modes:W(Ag.nullish(),()=>{})}),Jce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(hc).nullish(),()=>{}),modes:W(Ag.nullish(),()=>{}),sessionId:xe}),Zce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:W(Ce(hc).nullish(),()=>{}),modes:W(Ag.nullish(),()=>{})}),Xce=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Yce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:W(Cce.nullish(),()=>{}),close:W(Ece.nullish(),()=>{}),delete:W(Uce.nullish(),()=>{}),fork:W(Fce.nullish(),()=>{}),list:W(qce.nullish(),()=>{}),resume:W(Xce.nullish(),()=>{})}),XU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),apiType:fP,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()}),YU=u.intersection(u.union([u.object({type:u.literal("boolean"),value:u.boolean()}),u.object({value:gP})]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configId:OU,sessionId:xe})),ele=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:wr(Ce(hc),()=>[])}),QU=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),modeId:Tg,sessionId:xe}),tle=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),nle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe}),rle=u.union([u.literal("end_turn"),u.literal("max_tokens"),u.literal("max_turn_requests"),u.literal("refusal"),u.literal("cancelled")]),ole=u.union([u.literal("email"),u.literal("uri"),u.literal("date"),u.literal("date-time")]),ile=u.object({default:u.string().nullish(),description:u.string().nullish(),enum:u.array(u.string()).nullish(),format:ole.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(fU).nullish(),pattern:u.string().nullish(),title:u.string().nullish()}),eF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:W(yce.nullish(),()=>{}),position:Ti,selection:W(gc.nullish(),()=>{}),sessionId:xe,triggerKind:qae,uri:u.string(),version:u.number()}),sle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),suggestions:wr(Ce(kce),()=>[])}),ale=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),cle=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()}),kP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),lle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),exitStatus:cle.nullish(),output:u.string(),truncated:u.boolean()}),dle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(Fd.nullish(),()=>{}),text:u.string()}),ule=u.object({range:gc.nullish(),text:u.string()}),tF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),contentChanges:u.array(ule),sessionId:xe,uri:u.string(),version:u.number()}),zze=u.object({method:u.string(),params:u.union([UU,WU,tF,BU,GU,qU,LU,JU,AU,yU]).nullish()}),ple=u.union([u.literal("full"),u.literal("incremental")]),mle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),syncKind:ple}),fle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),didChange:W(mle.nullish(),()=>{}),didClose:W(Tae.nullish(),()=>{}),didFocus:W(Aae.nullish(),()=>{}),didOpen:W(Pae.nullish(),()=>{}),didSave:W(Iae.nullish(),()=>{})}),gle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),document:W(fle.nullish(),()=>{})}),hle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:W(Gae.nullish(),()=>{}),events:W(gle.nullish(),()=>{})}),yle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:pae.optional().default({}),loadSession:u.boolean().optional().default(!1),mcpCapabilities:fae.optional().default({acp:!1,http:!1,sse:!1}),nes:W(hle.nullish(),()=>{}),positionEncoding:W(MU.nullish(),()=>{}),promptCapabilities:dce.optional().default({audio:!1,embeddedContext:!1,image:!1}),providers:W(fce.nullish(),()=>{}),sessionCapabilities:Yce.optional().default({})}),vle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),agentCapabilities:yle.optional().default({auth:{},loadSession:!1,mcpCapabilities:{acp:!1,http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:W(wU.nullish(),()=>{}),authMethods:W(Ce(Hse).optional().default([]),()=>[]),protocolVersion:DU}),ble=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),mimeType:u.string().nullish(),text:u.string(),uri:u.string()}),kle=u.union([ble,Bse]),wle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:W(Fd.nullish(),()=>{}),resource:kle}),wP=u.union([dle.and(u.object({type:u.literal("text")})),Tce.and(u.object({type:u.literal("image")})),Rce.and(u.object({type:u.literal("audio")})),Ace.and(u.object({type:u.literal("resource_link")})),wle.and(u.object({type:u.literal("resource")}))]),Sle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:wP}),pP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:wP,messageId:Sae.nullish()}),nF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),prompt:u.array(wP),sessionId:xe}),xle=u.object({anyOf:u.array(fU)}),rF=u.union([Sle.and(u.object({type:u.literal("content")})),Zse.and(u.object({type:u.literal("diff")})),ale.and(u.object({type:u.literal("terminal")}))]),SP=u.string(),oF=u.object({sessionId:xe,toolCallId:SP.nullish()}),Rle=u.intersection(u.union([oF,NU]),u.object({elicitationId:mU,url:u.string().url()})),iF=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()}),sF=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed"),u.literal("failed")]),aF=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")]),Tle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:W(Ce(rF).optional(),()=>[]),kind:aF.optional(),locations:W(Ce(iF).optional(),()=>[]),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:sF.optional(),title:u.string(),toolCallId:SP}),cF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:W(Ce(rF).nullish(),()=>{}),kind:W(aF.nullish(),()=>{}),locations:W(Ce(iF).nullish(),()=>{}),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:W(sF.nullish(),()=>{}),title:u.string().nullish(),toolCallId:SP}),xP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),options:u.array(Jae),sessionId:xe,toolCall:cF}),Ale=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),hint:u.string()}),Ple=Ale,Ile=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string(),input:W(Ple.nullish(),()=>{}),name:u.string()}),_le=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableCommands:wr(Ce(Ile),()=>[])}),Cle=u.object({enum:u.array(u.string()),type:oae}),Ele=u.union([Cle,xle]),Mle=u.object({default:u.array(u.string()).nullish(),description:u.string().nullish(),items:Ele,maxItems:u.number().nullish(),minItems:u.number().nullish(),title:u.string().nullish()}),Dle=u.union([ile.and(u.object({type:u.literal("string")})),Kae.and(u.object({type:u.literal("number")})),lae.and(u.object({type:u.literal("integer")})),qse.and(u.object({type:u.literal("boolean")})),Mle.and(u.object({type:u.literal("array")}))]),$le=u.object({description:u.string().nullish(),properties:u.record(u.string(),Dle).optional().default({}),required:u.array(u.string()).nullish(),title:u.string().nullish(),type:rae.optional().default("object")}),Nle=u.intersection(u.union([oF,NU]),u.object({requestedSchema:$le})),RP=u.intersection(u.union([Nle.and(u.object({mode:u.literal("form")})),Rle.and(u.object({mode:u.literal("url")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),message:u.string()})),Ole=u.object({cachedReadTokens:u.number().nullish(),cachedWriteTokens:u.number().nullish(),inputTokens:u.number(),outputTokens:u.number(),thoughtTokens:u.number().nullish(),totalTokens:u.number()}),jle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),stopReason:rle,usage:W(Ole.nullish(),()=>{})}),Bze=u.union([u.object({id:Ai,result:u.union([vle,zse,mce,Qce,Xse,mae,Jce,Vce,zce,Jse,Kce,Zce,Gse,tle,ele,jle,nle,sle,Wse,bU,IU])}),u.object({error:hU,id:Ai})]),Lle=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cost:W(Kse.nullish(),()=>{}),size:u.number(),used:u.number()}),Ule=u.union([pP.and(u.object({sessionUpdate:u.literal("user_message_chunk")})),pP.and(u.object({sessionUpdate:u.literal("agent_message_chunk")})),pP.and(u.object({sessionUpdate:u.literal("agent_thought_chunk")})),Tle.and(u.object({sessionUpdate:u.literal("tool_call")})),cF.and(u.object({sessionUpdate:u.literal("tool_call_update")})),Qae.and(u.object({sessionUpdate:u.literal("plan")})),ice.and(u.object({sessionUpdate:u.literal("plan_update")})),rce.and(u.object({sessionUpdate:u.literal("plan_removed")})),_le.and(u.object({sessionUpdate:u.literal("available_commands_update")})),Wce.and(u.object({sessionUpdate:u.literal("current_mode_update")})),Lce.and(u.object({sessionUpdate:u.literal("config_option_update")})),Bce.and(u.object({sessionUpdate:u.literal("session_info_update")})),Lle.and(u.object({sessionUpdate:u.literal("usage_update")}))]),TP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,update:Ule}),qze=u.object({method:u.string(),params:u.union([TP,mP,AU,yU]).nullish()}),AP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:xe,terminalId:u.string()}),Fle=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()}),Hle=u.object({name:u.string(),uri:u.string()}),lF=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),repository:W(Fae.nullish(),()=>{}),workspaceFolders:W(Ce(Hle).nullish(),()=>{}),workspaceUri:u.string().nullish()}),Wze=u.object({id:Ai,method:u.string(),params:u.union([$U,uU,SU,XU,pU,RU,_U,VU,xU,zU,KU,ZU,HU,QU,YU,nF,lF,eF,FU,PU,vU]).nullish()}),PP=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),path:u.string(),sessionId:xe}),Gze=u.object({id:Ai,method:u.string(),params:u.union([PP,vP,xP,hP,kP,bP,AP,yP,RP,yae,PU,hae,vU]).nullish()}),zle=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Kze=u.union([u.object({id:Ai,result:u.union([zle,wce,_ce,Vse,lle,Sce,Fle,dae,tae,gae,Yse,bU,IU])}),u.object({error:hU,id:Ai})]);function dF(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(`
685
685
  `);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)+`
686
686
  `,c=t.getWriter();try{await c.write(n.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function Pi(t){return t??{}}function uF(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var Pg=class{connection;constructor(e,n){let r=e(this),o=async(s,a)=>{switch(s){case cr.fs_write_text_file:{let c=PP.parse(a);return await r.writeTextFile?.(c)??{}}case cr.fs_read_text_file:{let c=vP.parse(a);return r.readTextFile?.(c)}case cr.session_request_permission:{let c=xP.parse(a);return r.requestPermission(c)}case cr.terminal_create:{let c=hP.parse(a);return r.createTerminal?.(c)}case cr.terminal_output:{let c=kP.parse(a);return r.terminalOutput?.(c)}case cr.terminal_release:{let c=bP.parse(a);return await r.releaseTerminal?.(c)??{}}case cr.terminal_wait_for_exit:{let c=AP.parse(a);return r.waitForTerminalExit?.(c)}case cr.terminal_kill:{let c=yP.parse(a);return await r.killTerminal?.(c)??{}}case cr.elicitation_create:{if(!r.unstable_createElicitation)throw fn.methodNotFound(s);let c=RP.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 cr.session_update:{let c=TP.parse(a);return r.sessionUpdate(c)}case cr.elicitation_complete:{if(!r.unstable_completeElicitation)return;let c=mP.parse(a);return r.unstable_completeElicitation(c)}default:if(r.extNotification)return r.extNotification(s,a);throw fn.methodNotFound(s)}};this.connection=new IP(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,Pi)}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,Pi)}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,Pi)}setSessionConfigOption(e){return this.connection.sendRequest(Ne.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(Ne.authenticate,e,Pi)}unstable_listProviders(e){return this.connection.sendRequest(Ne.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(Ne.providers_set,e,Pi)}unstable_disableProvider(e){return this.connection.sendRequest(Ne.providers_disable,e,Pi)}logout(e){return this.connection.sendRequest(Ne.logout,e,Pi)}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,Pi)}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}},IP=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 uF(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?uF(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 Gle=1,Kle=2e4,pF=3e4,Vle=3e5,Sr={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 Hd=class extends Error{retryable=!1;authMethods;constructor(e,n){super(e),this.name="AcpAuthRequiredError",this.authMethods=n}};function zd(t,e){if(t instanceof Hd)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 Hd(`Authentication required.${s?` ${s}`:""}`,r)}if(e&&e.length>0&&Jle(n)){let i=e[0],s=n?.data?.details||i?.description||(i?.name?`Authentication required. Use "${i.name}".`:n?.message||"Authentication required.");return new Hd(s,e)}return null}function Jle(t){let e=`${t?.message??""}
687
- ${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 Zle(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 Ii=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=dF(Wle.toWeb(e.stdin),qle.toWeb(e.stdout)),i=o.readable.pipeThrough(new TransformStream({transform:(s,a)=>{this.consumeExtensionNotification(s)||a.enqueue(s)}}));this.conn=new Pg(()=>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:Gle,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),Kle,"initialize").catch(i=>{throw zd(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),pF,"session/new").catch(i=>{throw zd(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=Vle){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 zd(a)??Zle(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),pF,"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 Sr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case Sr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case Sr.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 Sr.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 Sr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case Sr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case Sr.AVAILABLE_COMMANDS_UPDATE:case Sr.CURRENT_MODE_UPDATE:case Sr.CONFIG_OPTION_UPDATE:case Sr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case Sr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as Xle}from"node:child_process";import{readFile as Yle,writeFile as Qle}from"node:fs/promises";import{isAbsolute as mF,normalize as ede,relative as tde,resolve as nde,sep as rde}from"node:path";function ode(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 _P(t){let e=new Map,n=0,r=i=>{let s=mF(i)?ede(i):nde(t.cwd,i),a=tde(t.cwd,s);if(a===".."||a.startsWith(`..${rde}`)||mF(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:ode(i)}},async readTextFile(i){return{content:await Yle(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=Xle(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 Bd=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 sde,execFile as ade,execFileSync as fF,execSync as PF}from"node:child_process";import{existsSync as Mi,mkdirSync as IF,readFileSync as bc,readdirSync as _F,writeFileSync as CF}from"node:fs";import{homedir as jP,platform as cde,tmpdir as lde}from"node:os";import{dirname as qd,join as kt}from"node:path";import{promisify as EF}from"node:util";function _i(){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 Ci(t){let e={...process.env,ELECTRON_RUN_AS_NODE:"1"};return t.prefix&&(e.npm_config_prefix=t.prefix),e}function CP(t){let e=t.trim().split(/\s+/)[0];return e==="npm"||e==="npm.cmd"}var ide=/^(?:pip3?|pipx|uv|uvx|python3?|curl|wget|brew|sh|bash)\b/;function EP(t){return ide.test(t.trim())}function MP(){let t={...process.env};return delete t.ELECTRON_RUN_AS_NODE,t}var gF=EF(ade),MF=EF(sde),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"}},dde=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],hF={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 Mo(t){let e=Hs[t];if(e)return hF[t]?{...e,...hF[t]}:e}function Wd(){return dde.map(t=>{let e=Mo(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Do=cde()==="win32",DF=5*6e4,ude=2e4,Ei,yc=new Map,DP=kt(process.env.QLOGICAGENT_HOME||kt(jP(),".qlogicagent"),"agent-update-cache.json"),yF=!1;function $F(){if(!yF){yF=!0;try{let t=JSON.parse(bc(DP,"utf8"));for(let[e,n]of Object.entries(t))n&&typeof n.timestamp=="number"&&!yc.has(e)&&yc.set(e,n)}catch{}}}var Ig=null;function pde(){Ig||(Ig=setTimeout(()=>{Ig=null;try{let t={};for(let[e,n]of yc)t[e]=n;IF(qd(DP),{recursive:!0}),CF(DP,JSON.stringify(t),"utf8")}catch{}},1e3),Ig.unref?.())}function $P(t){try{let e=Do?`where ${t}`:`which ${t}`;return PF(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}async function NP(t){try{let e=Do?`where ${t}`:`which ${t}`,{stdout:n}=await MF(e,{encoding:"utf8",timeout:5e3,windowsHide:!0});return String(n).split(/\r?\n/)[0]?.trim()||null}catch{return null}}function NF(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 mde(){if(!Do)return null;let t=[process.env.COPILOT_CACHE_HOME?kt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?kt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?kt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,kt(jP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=_F(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(NF);for(let r of n){let o=kt(e,r,"npm-loader.js");if(Mi(o)&&HF(o))return o}}catch{}return null}function fde(t){return t.id==="copilot"?mde()??$P(t.cliCommand):$P(t.cliCommand)}async function gde(){if(!Do)return null;let t=[process.env.COPILOT_CACHE_HOME?kt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?kt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?kt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,kt(jP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=_F(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(NF);for(let r of n){let o=kt(e,r,"npm-loader.js");if(Mi(o)&&await zF(o))return o}}catch{}return null}async function hde(t){return t.id==="copilot"?await gde()??await NP(t.cliCommand):NP(t.cliCommand)}function yde(t,e){let n=_i();return n?fF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],env:Ci(n),windowsHide:!0}).trim():fF(Do?"cmd.exe":"npm",Do?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()}async function OF(t,e){let n=_i();if(n){let{stdout:o}=await gF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,env:Ci(n)});return o.trim()}let{stdout:r}=await gF(Do?"cmd.exe":"npm",Do?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function vde(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 Dg(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 vde(o)}}return null}function Gd(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function bde(t,e){let n=i=>{let s=Gd(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 jF(t,e){return!t||!e?!1:bde(t,e)>0}function kde(){if(Ei!==void 0)return Ei;try{Ei=yde(["root","-g"],3e3)||null}catch{Ei=null}return Ei}async function wde(){if(Ei===void 0)try{Ei=await OF(["root","-g"],3e3)||null}catch{Ei=null}}function $g(t){if(!t)return null;let e=kde();if(!e)return null;let n=kt(e,...t.split("/"),"package.json");try{let r=JSON.parse(bc(n,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}function vF(t){let e=Dg(t?.npm);return $g(e)}function LF(t,e){return $g(Dg(t.install?.npm))??Gd(e)??e??void 0}async function Sde(t,e){if(!t)return null;$F();let n=e?`${t}\0${e}`:t,r=yc.get(n);if(r){let i=r.version?DF:ude;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 OF(i,12e3),a=s?JSON.parse(s):null;o=typeof a=="string"?a:Gd(s)}catch{o=null}return yc.set(n,{timestamp:Date.now(),version:o}),pde(),o}async function UF(t,e){let n=t.map(async({id:o,entry:i,detectedVersion:s})=>{let a=Dg(i.install?.npm),c=$g(a)??Gd(s)??s??void 0;if(!a||!c)return null;let l=await Sde(a,e)??void 0;return l?{id:o,packageName:a,installedVersion:c,latestVersion:l,updateAvailable:jF(l,c)}:null});return(await Promise.all(n)).filter(o=>o!==null)}function FF(t,e){$F();let n=[],r=!1;for(let{id:o,entry:i,detectedVersion:s}of t){let a=Dg(i.install?.npm),c=$g(a)??Gd(s)??s??void 0;if(!a||!c)continue;let l=e?`${a} ${e}`:a,d=yc.get(l);d?.version&&Date.now()-d.timestamp<DF||(r=!0),d?.version&&n.push({id:o,packageName:a,installedVersion:c,latestVersion:d.version,updateAvailable:jF(d.version,c)})}return{updates:n,stale:r}}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}`,i=PF(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 zF(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 MF(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 xde(t,e){if(!Do)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=BF(t);if(n)return{cliPath:process.execPath,acpArgs:[n,...e]};let r=Rde(t);return r?{cliPath:r,acpArgs:e}:{cliPath:t,acpArgs:e}}function BF(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Mi(r))continue;let o;try{o=bc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=kt(qd(e),s);if(Mi(a))return a}return null}function Rde(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Mi(r))continue;let o;try{o=bc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.exe)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=kt(qd(e),s);if(Mi(a))return a}return null}function bF(t){let e=BF(t);if(!e)return null;let n=qd(e);for(let r=0;r<6;r+=1){let o=kt(n,"package.json");try{if(Mi(o)){let s=JSON.parse(bc(o,"utf8"));if(typeof s.version=="string"&&s.version)return s.version}}catch{}let i=qd(n);if(i===n)break;n=i}return null}var kF=6e4;function Tde(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 qF=new Set(["codex","qwen","opencode"]),Cg=new Set(["qwen","opencode"]),Eg=new Set(["gemini"]),OP=new Set(["glm"]),wF={claude:"anthropic",codex:"openai"};function Ade(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function Pde(t){let e=kt(lde(),"qlogicagent-codex-model-catalog");IF(e,{recursive:!0});let n=kt(e,`${Ade(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(!Mi(n)||bc(n,"utf8")!==r)&&CF(n,r,"utf8"),n}function LP(t){return t.id!=="claude"}function Mg(t,e){return e==="account"&&!LP(t)?"auto":e}function WF(t){if(t.authMode==="oauth"||t.keySource==="none")return["account"];let e=[];return t.keySource==="llmrouter"&&LP(t)&&e.push("account"),e.push("userKey"),(t.keySource==="llmrouter"||Cg.has(t.id)||Eg.has(t.id)||OP.has(t.id))&&e.push("managed"),e}function UP(t,e,n){let r=Mg(t,e);return!!(r==="account"||r==="auto"&&LP(t)&&n?.hasSubscription?.(t.id)===!0)}var GF={claude:"ANTHROPIC_MODEL",codex:"OPENAI_MODEL",glm:"ACP_GLM_MODEL"},Ide={glm:"ACP_GLM_AVAILABLE_MODELS"};function _g(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=GF[t.id];s&&e.llmrouterModel&&(n[s]=e.llmrouterModel);let a=Ide[t.id];a&&e.llmrouterModel&&(n[a]=e.llmrouterModel)}function SF(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 xF=["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_GEMINI_API_KEY","GEMINI_API_KEY"];function RF(t,e){return t?(e.apiKeyEnvVar?[e.apiKeyEnvVar,...xF]:xF).some(r=>typeof t[r]=="string"&&t[r].trim().length>0):!1}function TF(t){return!!t.apiKeyEnvVar||Cg.has(t.id)||Eg.has(t.id)}function AF(t,e,n="auto"){let r={};if(!t)return r;let o=Mg(t,n);if(o==="account"||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:i,baseUrlEnvVar:s}=t;if(o==="userKey"){let a=wF[t.id]??t.id,c=e.getDirectKey?.(a);return i&&c&&(r[i]=c),r}if(o==="managed")return t.keySource==="llmrouter"||Eg.has(t.id)||OP.has(t.id)?_g(t,e,r):Cg.has(t.id)&&SF(t,e,r),r;if(UP(t,"auto",e))return r;if(t.keySource==="llmrouter"){let a=wF[t.id],c=a?e.getDirectKey?.(a):void 0;i&&c?r[i]=c:_g(t,e,r)}else if(t.keySource==="direct"){let a=e.getDirectKey?.(t.id);i&&a?r[i]=a:Cg.has(t.id)?SF(t,e,r):(Eg.has(t.id)||OP.has(t.id))&&_g(t,e,r)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&qF.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 _de(t,e,n){if(!t||!UP(t,e,n))return[];let r=[];return t.apiKeyEnvVar&&r.push(t.apiKeyEnvVar),t.baseUrlEnvVar&&r.push(t.baseUrlEnvVar),qF.has(t.id)&&r.push("OPENAI_MODEL"),r}function Cde(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(UP(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=${Pde(s)}`]:e}var vc=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<kF)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<kF?this.cache.agents:this.scanInFlight?this.scanInFlight:(this.scanInFlight=this.runScanAsync().finally(()=>{this.scanInFlight=null}),this.scanInFlight)}async runScanAsync(){await wde();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=fde(e),r=n?HF(n)??bF(n)??vF(Mo(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}async detectBackendAsync(e){let n=await hde(e),r=n?await zF(n)??bF(n)??vF(Mo(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,$P(e.cliCommand))}async detectCustomAgentAsync(e){return this.assembleCustomAgentDescriptor(e,await NP(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=Mo(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}:xde(n.cliPath,s),c=o?.authPreference??"auto",l=AF(r,this.keySources,c),d=o?.customArgs?.length?a.acpArgs:Cde(r,a.acpArgs,l,this.keySources,c),p=r?_de(r,c,this.keySources):[];return{id:e,cliPath:a.cliPath,acpArgs:d,env:Tde(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=Mo(e)??Hs[e],o=this.configStore?.agents[e]?.authPreference??"auto";return(r?Mg(r,o):o)==="account"||r?.authMode==="oauth"||r?.keySource==="none"?this.keySources.hasSubscription?.(e)!==!1:r&&TF(r)?RF(n.env,r):!0}resolveCredentialError(e){if(e==="qlogicagent")return null;let n=Mo(e)??Hs[e];if(!n)return null;let r=this.configStore?.agents[e]?.authPreference??"auto",o=Mg(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(!TF(n)||RF(AF(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 KF(t,e){if(e!=="qlogicagent")try{let n=t.buildExternalDescriptor(e),r=GF[e]??"OPENAI_MODEL";return n?.env?.[r]??n?.env?.OPENAI_MODEL}catch{return}}var Kd="https://registry.npmmirror.com",kc="https://pypi.tuna.tsinghua.edu.cn/simple",FP="https://registry.npmmirror.com/-/binary";function Ede(){return{npm_config_registry:Kd,PIP_INDEX_URL:kc,UV_DEFAULT_INDEX:kc,UV_INDEX_URL:kc,UV_PYTHON_INSTALL_MIRROR:`${FP}/python-build-standalone`,NODEJS_ORG_MIRROR:`${FP}/node`,npm_config_disturl:`${FP}/node`}}var VF=Object.keys(Ede());import{readFileSync as Hde}from"node:fs";import{randomUUID as zde}from"node:crypto";le();xa();import{readdirSync as Mde,readFileSync as Dde,statSync as HP,writeFileSync as $de}from"node:fs";import{join as Vd}from"node:path";var Nde=["auto-skill-","test-skill-"],Ode=".skills_prompt_snapshot.json";function jde(t){return Nde.some(e=>t.startsWith(e))}function Lde(t){let e=t.replace(/\r\n/g,`
687
+ ${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 Zle(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 Ii=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=dF(Wle.toWeb(e.stdin),qle.toWeb(e.stdout)),i=o.readable.pipeThrough(new TransformStream({transform:(s,a)=>{this.consumeExtensionNotification(s)||a.enqueue(s)}}));this.conn=new Pg(()=>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:Gle,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),Kle,"initialize").catch(i=>{throw zd(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),pF,"session/new").catch(i=>{throw zd(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=Vle){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 zd(a)??Zle(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),pF,"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 Sr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case Sr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case Sr.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 Sr.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 Sr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case Sr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case Sr.AVAILABLE_COMMANDS_UPDATE:case Sr.CURRENT_MODE_UPDATE:case Sr.CONFIG_OPTION_UPDATE:case Sr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case Sr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as Xle}from"node:child_process";import{readFile as Yle,writeFile as Qle}from"node:fs/promises";import{isAbsolute as mF,normalize as ede,relative as tde,resolve as nde,sep as rde}from"node:path";function ode(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 _P(t){let e=new Map,n=0,r=i=>{let s=mF(i)?ede(i):nde(t.cwd,i),a=tde(t.cwd,s);if(a===".."||a.startsWith(`..${rde}`)||mF(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:ode(i)}},async readTextFile(i){return{content:await Yle(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=Xle(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 Bd=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 sde,execFile as ade,execFileSync as fF,execSync as PF}from"node:child_process";import{existsSync as Mi,mkdirSync as IF,readFileSync as bc,readdirSync as _F,writeFileSync as CF}from"node:fs";import{homedir as jP,platform as cde,tmpdir as lde}from"node:os";import{dirname as qd,join as kt}from"node:path";import{promisify as EF}from"node:util";function _i(){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 Ci(t){let e={...process.env,ELECTRON_RUN_AS_NODE:"1"};return t.prefix&&(e.npm_config_prefix=t.prefix),e}function CP(t){let e=t.trim().split(/\s+/)[0];return e==="npm"||e==="npm.cmd"}var ide=/^(?:pip3?|pipx|uv|uvx|python3?|curl|wget|brew|sh|bash)\b/;function EP(t){return ide.test(t.trim())}function MP(){let t={...process.env};return delete t.ELECTRON_RUN_AS_NODE,t}var gF=EF(ade),MF=EF(sde),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"}},dde=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],hF={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 Mo(t){let e=Hs[t];if(e)return hF[t]?{...e,...hF[t]}:e}function Wd(){return dde.map(t=>{let e=Mo(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Do=cde()==="win32",DF=5*6e4,ude=2e4,Ei,yc=new Map,DP=kt(process.env.QLOGICAGENT_HOME||kt(jP(),".qlogicagent"),"agent-update-cache.json"),yF=!1;function $F(){if(!yF){yF=!0;try{let t=JSON.parse(bc(DP,"utf8"));for(let[e,n]of Object.entries(t))n&&typeof n.timestamp=="number"&&!yc.has(e)&&yc.set(e,n)}catch{}}}var Ig=null;function pde(){Ig||(Ig=setTimeout(()=>{Ig=null;try{let t={};for(let[e,n]of yc)t[e]=n;IF(qd(DP),{recursive:!0}),CF(DP,JSON.stringify(t),"utf8")}catch{}},1e3),Ig.unref?.())}function $P(t){try{let e=Do?`where ${t}`:`which ${t}`;return PF(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"],windowsHide:!0}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}async function NP(t){try{let e=Do?`where ${t}`:`which ${t}`,{stdout:n}=await MF(e,{encoding:"utf8",timeout:5e3,windowsHide:!0});return String(n).split(/\r?\n/)[0]?.trim()||null}catch{return null}}function NF(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 mde(){if(!Do)return null;let t=[process.env.COPILOT_CACHE_HOME?kt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?kt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?kt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,kt(jP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=_F(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(NF);for(let r of n){let o=kt(e,r,"npm-loader.js");if(Mi(o)&&HF(o))return o}}catch{}return null}function fde(t){return t.id==="copilot"?mde()??$P(t.cliCommand):$P(t.cliCommand)}async function gde(){if(!Do)return null;let t=[process.env.COPILOT_CACHE_HOME?kt(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?kt(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?kt(process.env.COPILOT_HOME,"pkg","win32-x64"):null,kt(jP(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let n=_F(e,{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort(NF);for(let r of n){let o=kt(e,r,"npm-loader.js");if(Mi(o)&&await zF(o))return o}}catch{}return null}async function hde(t){return t.id==="copilot"?await gde()??await NP(t.cliCommand):NP(t.cliCommand)}function yde(t,e){let n=_i();return n?fF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],env:Ci(n),windowsHide:!0}).trim():fF(Do?"cmd.exe":"npm",Do?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"],windowsHide:!0}).trim()}async function OF(t,e){let n=_i();if(n){let{stdout:o}=await gF(n.nodeExe,[n.npmCli,...t],{encoding:"utf8",timeout:e,env:Ci(n)});return o.trim()}let{stdout:r}=await gF(Do?"cmd.exe":"npm",Do?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function vde(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 Dg(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 vde(o)}}return null}function Gd(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function bde(t,e){let n=i=>{let s=Gd(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 jF(t,e){return!t||!e?!1:bde(t,e)>0}function kde(){if(Ei!==void 0)return Ei;try{Ei=yde(["root","-g"],3e3)||null}catch{Ei=null}return Ei}async function wde(){if(Ei===void 0)try{Ei=await OF(["root","-g"],3e3)||null}catch{Ei=null}}function $g(t){if(!t)return null;let e=kde();if(!e)return null;let n=kt(e,...t.split("/"),"package.json");try{let r=JSON.parse(bc(n,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}function vF(t){let e=Dg(t?.npm);return $g(e)}function LF(t,e){return $g(Dg(t.install?.npm))??Gd(e)??e??void 0}async function Sde(t,e){if(!t)return null;$F();let n=e?`${t}\0${e}`:t,r=yc.get(n);if(r){let i=r.version?DF:ude;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 OF(i,12e3),a=s?JSON.parse(s):null;o=typeof a=="string"?a:Gd(s)}catch{o=null}return yc.set(n,{timestamp:Date.now(),version:o}),pde(),o}async function UF(t,e){let n=t.map(async({id:o,entry:i,detectedVersion:s})=>{let a=Dg(i.install?.npm),c=$g(a)??Gd(s)??s??void 0;if(!a||!c)return null;let l=await Sde(a,e)??void 0;return l?{id:o,packageName:a,installedVersion:c,latestVersion:l,updateAvailable:jF(l,c)}:null});return(await Promise.all(n)).filter(o=>o!==null)}function FF(t,e){$F();let n=[],r=!1;for(let{id:o,entry:i,detectedVersion:s}of t){let a=Dg(i.install?.npm),c=$g(a)??Gd(s)??s??void 0;if(!a||!c)continue;let l=e?`${a} ${e}`:a,d=yc.get(l);d?.version&&Date.now()-d.timestamp<DF||(r=!0),d?.version&&n.push({id:o,packageName:a,installedVersion:c,latestVersion:d.version,updateAvailable:jF(d.version,c)})}return{updates:n,stale:r}}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}`,i=PF(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 zF(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 MF(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 xde(t,e){if(!Do)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=BF(t);if(n)return{cliPath:process.execPath,acpArgs:[n,...e]};let r=Rde(t);return r?{cliPath:r,acpArgs:e}:{cliPath:t,acpArgs:e}}function BF(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Mi(r))continue;let o;try{o=bc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=kt(qd(e),s);if(Mi(a))return a}return null}function Rde(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),n=[`${e}.cmd`,`${e}.ps1`,e];for(let r of n){if(!Mi(r))continue;let o;try{o=bc(r,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.exe)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=kt(qd(e),s);if(Mi(a))return a}return null}function bF(t){let e=BF(t);if(!e)return null;let n=qd(e);for(let r=0;r<6;r+=1){let o=kt(n,"package.json");try{if(Mi(o)){let s=JSON.parse(bc(o,"utf8"));if(typeof s.version=="string"&&s.version)return s.version}}catch{}let i=qd(n);if(i===n)break;n=i}return null}var kF=6e4;function Tde(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 qF=new Set(["codex","qwen","opencode"]),Cg=new Set(["qwen","opencode"]),Eg=new Set(["gemini"]),OP=new Set(["glm"]),wF={claude:"anthropic",codex:"openai"};function Ade(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function Pde(t){let e=kt(lde(),"qlogicagent-codex-model-catalog");IF(e,{recursive:!0});let n=kt(e,`${Ade(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(!Mi(n)||bc(n,"utf8")!==r)&&CF(n,r,"utf8"),n}function LP(t){return t.id!=="claude"}function Mg(t,e){return e==="account"&&!LP(t)?"auto":e}function WF(t){if(t.authMode==="oauth"||t.keySource==="none")return["account"];let e=[];return t.keySource==="llmrouter"&&LP(t)&&e.push("account"),e.push("userKey"),(t.keySource==="llmrouter"||Cg.has(t.id)||Eg.has(t.id)||OP.has(t.id))&&e.push("managed"),e}function UP(t,e,n){let r=Mg(t,e);return!!(r==="account"||r==="auto"&&LP(t)&&n?.hasSubscription?.(t.id)===!0)}var GF={claude:"ANTHROPIC_MODEL",codex:"OPENAI_MODEL",glm:"ACP_GLM_MODEL"},Ide={glm:"ACP_GLM_AVAILABLE_MODELS"};function _g(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=GF[t.id];s&&e.llmrouterModel&&(n[s]=e.llmrouterModel);let a=Ide[t.id];a&&e.llmrouterModel&&(n[a]=e.llmrouterModel)}function SF(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 xF=["OPENAI_API_KEY","ANTHROPIC_API_KEY","GOOGLE_GEMINI_API_KEY","GEMINI_API_KEY"];function RF(t,e){return t?(e.apiKeyEnvVar?[e.apiKeyEnvVar,...xF]:xF).some(r=>typeof t[r]=="string"&&t[r].trim().length>0):!1}function TF(t){return!!t.apiKeyEnvVar||Cg.has(t.id)||Eg.has(t.id)}function AF(t,e,n="auto"){let r={};if(!t)return r;let o=Mg(t,n);if(o==="account"||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:i,baseUrlEnvVar:s}=t;if(o==="userKey"){let a=wF[t.id]??t.id,c=e.getDirectKey?.(a);return i&&c&&(r[i]=c),r}if(o==="managed")return t.keySource==="llmrouter"||Eg.has(t.id)||OP.has(t.id)?_g(t,e,r):Cg.has(t.id)&&SF(t,e,r),r;if(UP(t,"auto",e))return r;if(t.keySource==="llmrouter"){let a=wF[t.id],c=a?e.getDirectKey?.(a):void 0;i&&c?r[i]=c:_g(t,e,r)}else if(t.keySource==="direct"){let a=e.getDirectKey?.(t.id);i&&a?r[i]=a:Cg.has(t.id)?SF(t,e,r):(Eg.has(t.id)||OP.has(t.id))&&_g(t,e,r)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&qF.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 _de(t,e,n){if(!t||!UP(t,e,n))return[];let r=[];return t.apiKeyEnvVar&&r.push(t.apiKeyEnvVar),t.baseUrlEnvVar&&r.push(t.baseUrlEnvVar),qF.has(t.id)&&r.push("OPENAI_MODEL"),r}function Cde(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(UP(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=${Pde(s)}`]:e}var vc=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<kF)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<kF?this.cache.agents:this.scanInFlight?this.scanInFlight:(this.scanInFlight=this.runScanAsync().finally(()=>{this.scanInFlight=null}),this.scanInFlight)}async runScanAsync(){await wde();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=fde(e),r=n?HF(n)??bF(n)??vF(Mo(e.id)?.install):null;return this.assembleBackendDescriptor(e,n,r)}async detectBackendAsync(e){let n=await hde(e),r=n?await zF(n)??bF(n)??vF(Mo(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,$P(e.cliCommand))}async detectCustomAgentAsync(e){return this.assembleCustomAgentDescriptor(e,await NP(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=Mo(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}:xde(n.cliPath,s),c=o?.authPreference??"auto",l=AF(r,this.keySources,c),d=o?.customArgs?.length?a.acpArgs:Cde(r,a.acpArgs,l,this.keySources,c),p=r?_de(r,c,this.keySources):[];return{id:e,cliPath:a.cliPath,acpArgs:d,env:Tde(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=Mo(e)??Hs[e],o=this.configStore?.agents[e]?.authPreference??"auto";return(r?Mg(r,o):o)==="account"||r?.authMode==="oauth"||r?.keySource==="none"?this.keySources.hasSubscription?.(e)!==!1:r&&TF(r)?RF(n.env,r):!0}resolveCredentialError(e){if(e==="qlogicagent")return null;let n=Mo(e)??Hs[e];if(!n)return null;let r=this.configStore?.agents[e]?.authPreference??"auto",o=Mg(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(!TF(n)||RF(AF(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 KF(t,e){if(e!=="qlogicagent")try{let n=t.buildExternalDescriptor(e),r=GF[e]??"OPENAI_MODEL";return n?.env?.[r]??n?.env?.OPENAI_MODEL}catch{return}}var Kd="https://registry.npmmirror.com",kc="https://pypi.tuna.tsinghua.edu.cn/simple",FP="https://registry.npmmirror.com/-/binary";function Ede(){return{npm_config_registry:Kd,PIP_INDEX_URL:kc,UV_DEFAULT_INDEX:kc,UV_INDEX_URL:kc,UV_PYTHON_INSTALL_MIRROR:`${FP}/python-build-standalone`,NODEJS_ORG_MIRROR:`${FP}/node`,npm_config_disturl:`${FP}/node`}}var VF=Object.keys(Ede());import{readFileSync as Hde}from"node:fs";import{randomUUID as zde}from"node:crypto";le();xa();import{readdirSync as Mde,readFileSync as Dde,statSync as HP,writeFileSync as $de}from"node:fs";import{join as Vd}from"node:path";var Nde=["auto-skill-","test-skill-"],Ode=".skills_prompt_snapshot.json";function jde(t){return Nde.some(e=>t.startsWith(e))}function Lde(t){let e=t.replace(/\r\n/g,`
688
688
  `),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:JF(s?.[1]),environments:JF(a?.[1])}}function Jd(t,e){let n=Pn(),r=KM(),o=t?VM(t):new Set,i=[],s;try{s=Mde(n,{withFileTypes:!0})}catch{s=[]}for(let a of s){if(!a.isDirectory()||a.name.startsWith("."))continue;let c=Vd(n,a.name),l=Vd(c,"SKILL.md"),d;try{if(!HP(l).isFile())continue;d=Dde(l,"utf8")}catch{continue}let p=r.has(a.name),m=o.has(a.name),f=Lde(d),g=!Ude(f,e);i.push({name:a.name,filePath:l,baseDir:c,globallyDisabled:p,projectDisabled:m,active:!p&&!m&&!g,systemGenerated:jde(a.name),description:f.description,version:f.version,category:f.category,author:f.author,requiredTools:f.requiredTools,environments:f.environments})}return Fde(n,i),i}function $o(t,e){return Jd(t,e).filter(n=>n.active)}function Ln(t){let e=Pn(),n=Vd(e,t),r=Vd(n,"SKILL.md");try{if(HP(r).isFile())return{baseDir:n,filePath:r}}catch{}return null}function JF(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 Ude(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 Fde(t,e){try{let r={version:1,entries:e.map(o=>{let i=HP(o.filePath);return{name:o.name,size:i.size,mtimeMs:i.mtimeMs,description:o.description,version:o.version,requiredTools:o.requiredTools,environments:o.environments}})};$de(Vd(t,Ode),JSON.stringify(r,null,2),"utf8")}catch{}}var Bde="astraclaw_capabilities",xr=[Bde,"astraclaw"];function Ng(t){let e=$o(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(`
689
689
  `)}function ZF(t){let e=Ng(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(`
690
690
  `)}async function Og(t){if(t.tool==="skills_list")return{handled:!0,result:{skills:$o(t.projectRoot,{availableToolNames:t.availableToolNames,currentEnvironment:t.currentEnvironment??process.platform}).map(qde)}};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:Hde(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:Gde(n.function.name),name:Kde(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=Wde(t.args.args),o=`astraclaw_mcp_${zde().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 qde(t){return{name:t.name,description:t.description,version:t.version,category:t.category,requiredTools:t.requiredTools,environments:t.environments}}function Wde(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function Gde(t){let e=t.split("__");return e.length>=3?e[1]??"":""}function Kde(t){let e=t.split("__");return e.length>=3?e.slice(2).join("__"):t}import{existsSync as Zd,mkdirSync as Xd,readFileSync as zs,writeFileSync as Yd}from"node:fs";import{homedir as Vde}from"node:os";import{dirname as Qd,join as lr}from"node:path";le();var Jde={qwen:[".qwen","settings.json"],gemini:[".gemini","settings.json"]},jg="# BEGIN ASTRACLAW MANAGED MCP",qP="# END ASTRACLAW MANAGED MCP",XF=" # BEGIN ASTRACLAW MANAGED MCP",YF=" # END ASTRACLAW MANAGED MCP";function QF(t){let e=t.agentId.trim().toLowerCase(),n=t.homeDir||Vde(),r=Zde(t),o=Jde[e];if(o){let i=lr(n,...o);return eue({agentId:e,configPath:i,server:r})}if(e==="codex"){let i=lr(t.codexHome||process.env.CODEX_HOME?.trim()||lr(n,".codex"),"config.toml");return oue({agentId:e,configPath:i,server:r})}if(e==="kimi"){let i=lr(n,".kimi","mcp.json");return tue({agentId:e,configPath:i,server:r})}if(e==="hermes"){let i=lr(Xde(n),"config.yaml");return iue({agentId:e,configPath:i,server:r})}if(e==="opencode"){let i=lr(Yde(n,t.homeDir!==void 0),"opencode.jsonc");return sue({agentId:e,configPath:i,server:r})}return{agentId:e,status:"unsupported",reason:`No native MCP config adapter for agent "${e}"`}}function Zde(t){return{command:t.nodePath||process.execPath,args:[t.serverScriptPath],env:Qde({ASTRACLAW_PROJECT_ROOT:t.projectRoot,ASTRACLAW_MANAGED:"1",ASTRACLAW_MCP_CONFIG_PATH:Tl(),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 Xde(t){let e=process.env.HERMES_HOME?.trim();if(e)return e;let n=process.env.LOCALAPPDATA?.trim();return process.platform==="win32"&&n?lr(n,"hermes"):lr(t,".hermes")}function Yde(t,e=!1){if(e)return lr(t,"opencode");let n=process.env.XDG_CONFIG_HOME?.trim();if(n)return lr(n,"opencode");let r=process.env.APPDATA?.trim();return process.platform==="win32"&&r?lr(r,"opencode"):lr(t,".config","opencode")}function Qde(t){return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"&&e[1].length>0))}function eue(t){let e=eH(t.configPath),n={...e,mcpServers:{...eu(e.mcpServers)?e.mcpServers:{}}},r=n.mcpServers;for(let s of xr)r[s]=t.server;let o=`${JSON.stringify(n,null,2)}
@@ -725,7 +725,7 @@ ${n}
725
725
  `);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 Di}from"node:child_process";var cH=/[|&;><$`(){}]/;function lH(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=cH.test(i);if(!(s&&n)&&!(i.startsWith("brew ")&&!r))return{command:i,shell:s}}return null}function dH(t,e){if(e!=="cn")return t;let n=t.trim();return/^npm\b/.test(n)&&!/(?:^|\s)--registry(?:\s|=)/.test(n)?`${n} --registry ${Kd}`:/^uv\b/.test(n)&&!/(?:^|\s)--(?:default-)?index(?:-url)?(?:\s|=)/.test(n)?`${n} --default-index ${kc}`:/^(?:pipx|pip3?|python -m pip)\b/.test(n)&&!/(?:^|\s)--index-url(?:\s|=)/.test(n)?`${n} --index-url ${kc}`:n}function aH(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 Lue=(t,e)=>{let n=_i();if(n&&CP(t)){let i=t.trim().split(/\s+/).slice(1);return Di(n.nodeExe,[n.npmCli,...i],{env:Ci(n),stdio:["ignore","pipe","pipe"],windowsHide:!0})}let r=EP(t)?MP():void 0;if(e||process.platform==="win32")return Di(t,{shell:!0,...r?{env:r}:{},stdio:["ignore","pipe","pipe"],windowsHide:!0});let o=t.split(/\s+/).filter(Boolean);return Di(o[0],o.slice(1),{...r?{env:r}:{},stdio:["ignore","pipe","pipe"]})};async function uH(t,e,n={}){let r=n.platform??process.platform,o=n.spawnImpl??Lue,i=lH(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=dH(i.command,n.mirror);e({type:"state",state:"installing"});let a=await aH(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 aH(c,cH.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 pH(t,e=process.platform){try{return e==="win32"?Di("cmd.exe",["/c","start","","cmd","/k",t],{detached:!0,stdio:"ignore",windowsHide:!1}).unref():e==="darwin"?Di("osascript",["-e",`tell application "Terminal" to do script ${JSON.stringify(t)}`,"-e",'tell application "Terminal" to activate'],{detached:!0,stdio:"ignore"}).unref():Di("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 mH(t,e={}){let n=e.platform??process.platform,r=lH(t,n);if(!r)return{ok:!1,error:`No install command available for ${n}`};let o=dH(r.command,e.mirror);try{let i=_i(),s;if(i&&CP(o)){let a=o.trim().split(/\s+/).slice(1);s=Di(i.nodeExe,[i.npmCli,...a],{env:Ci(i),detached:!0,stdio:"ignore",windowsHide:!0})}else{let a=EP(o)?MP():void 0;s=Di(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 mt=new Map,Uue=10*6e4,Fue=6e4,Hue=6,Bs=null;function Ug(t,e,n){return`${t}\0${e}\0${n??"default"}`}function tu(t){try{t.manager.kill(t.memberId)}catch{}try{t.manager.dispose()}catch{}}function fH(t){let e=mt.get(t);if(e){if(!e.manager.isAlive(e.memberId)){mt.delete(t),tu(e);return}return e}}function gH(t,e){let n=mt.get(t);n&&n!==e&&(mt.delete(t),tu(n)),mt.set(t,e),zue(),que()}function hH(t,e){let n=mt.get(t);if(!n)return;if(!n.manager.isAlive(n.memberId)){mt.delete(t),tu(n);return}mt.delete(t);let r=mt.get(e);return r&&r!==n&&(mt.delete(e),tu(r)),mt.set(e,n),n.lastUsed=Date.now(),n}var Fg="__warm__";function qs(t){let e=mt.get(t);e&&(mt.delete(t),tu(e))}function nu(t){let e=`${t}\0`,n=0,r=0;for(let[o,i]of[...mt.entries()])o.startsWith(e)&&(i.holder.current?(i.pendingRecredential=!0,r+=1):(qs(o),n+=1));return{evicted:n,deferred:r}}function yH(t){mt.get(t)?.pendingRecredential&&qs(t)}function vH(){for(let t of[...mt.keys()])qs(t);Bs&&(clearInterval(Bs),Bs=null)}function zue(){for(;mt.size>Hue;){let t=null,e=Number.POSITIVE_INFINITY;for(let[n,r]of mt)r.holder.current||r.lastUsed<e&&(e=r.lastUsed,t=n);if(!t)break;qs(t)}}function Bue(t){for(let[e,n]of[...mt.entries()])n.holder.current||t-n.lastUsed>Uue&&qs(e)}function que(){Bs||(Bs=setInterval(()=>Bue(Date.now()),Fue),typeof Bs.unref=="function"&&Bs.unref())}import{randomUUID as Wue}from"node:crypto";var xc=new Map;function Gue(t,e){let n=xc.get(t);return n&&(clearTimeout(n.timer),n.resolve(null),xc.delete(t)),new Promise(r=>{let o=setTimeout(()=>{xc.delete(t),r(null)},e);typeof o.unref=="function"&&o.unref(),xc.set(t,{resolve:r,timer:o})})}function bH(t,e){let n=xc.get(t);return n?(clearTimeout(n.timer),xc.delete(t),n.resolve(e),!0):!1}function Kue(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}function Vue(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 KP(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)KP(n,e);return e}for(let n of Object.values(t))KP(n,e);return e}function Jue(t){let e=KP(t).join(`
726
726
  `);return/astraclaw/i.test(e)&&/\b(?:skills_list|skill_view|mcp_connectors_list|mcp_tool_call)\b/.test(e)}async function kH(t,e){let n=e.turnContext(),r=t.toolCall&&typeof t.toolCall=="object"?t.toolCall:{},o=typeof t.permissionId=="string"&&t.permissionId?t.permissionId:Wue(),i=Array.isArray(t.options)?t.options:[];if(Jue(t))return{optionId:Vue(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:Kue(r.rawInput),message:typeof t.message=="string"?t.message:void 0,category:typeof t.category=="string"?t.category:"destructive",options:i});let a=await Gue(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 Xue(t){let e=t?.rawInput;if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}function Yue(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 Que(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:Xue(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:Yue(s)}})}function SH(t){let e=t?.authMethods;return Array.isArray(e)&&e.length>0?e:void 0}function xH(t){return t instanceof Error?t.message:String(t)}async function epe(t){let e=SH(t.error);if(!t.sessionId||!e)return;let n=xH(t.error);await yr(t.sessionId,{role:"user",content:t.prompt},t.projectRoot,t.turnId),await yr(t.sessionId,{role:"assistant",content:n,blocks:[{type:"auth_prompt",agentId:t.agentId,message:n,authMethods:e}]},t.projectRoot,t.turnId);let r=Kt(t.sessionId,t.projectRoot),o=await Ta(t.sessionId,t.projectRoot);await vt(t.sessionId,{type:"personal",...t.projectId?{projectId:t.projectId}:{},...o!==null?{messageCount:o}:{},...r?.title?{}:{title:Dl(t.prompt,"External agent login required")},...t.lockSessionOwner===!1||r?.agentId?{}:{agentId:t.agentId}},t.projectRoot)}async function RH(t){let e=t.params,n=typeof e?.approvalId=="string"?e.approvalId:"",r=typeof e?.optionId=="string"?e.optionId:"",o=n&&r?bH(n,r):!1;t.id!==void 0&&this.sendResponse(t.id,{ok:o})}async function TH(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 AH(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 PH(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=Wd().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:WF(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:LF(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 VP=new Set;async function IH(t){try{let e=t.params,r=(typeof e?.mirror=="string"&&e.mirror?e.mirror:process.env.QLOGICAGENT_INSTALL_MIRROR)==="cn"?Kd:void 0,o=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(o.getData());let i=new Map(this.acpDetector.list().map(l=>[l.id,l])),s=Wd().map(l=>({id:l.id,entry:l,detectedVersion:i.get(l.id)?.version})),{updates:a,stale:c}=FF(s,r);if(t.id!==void 0&&this.sendResponse(t.id,{updates:a,refreshing:c}),c){let l=r??"";VP.has(l)||(VP.add(l),UF(s,r).catch(()=>{}).finally(()=>VP.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 _H(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=Mo(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=mH(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 uH(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 CH(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=Mo(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=pH(o);t.id!==void 0&&this.sendResponse(t.id,{ok:i.ok,error:i.error,command:o})}async function EH(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 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(),{agentId:r,...o}=e;await n.setAgentConfig(r,o),this.acpDetector.setConfigStore(n.getData());let{deferred:i}=nu(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 DH(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 $H(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 tpe(t){let e=wH.homedir();if(t==="codex"){let n=process.env.CODEX_HOME?.trim()||Rc.join(e,".codex");return[Rc.join(n,"auth.json")]}return[]}async function NH(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 tpe(n))try{Tc.existsSync(o)&&(Tc.rmSync(o,{force:!0}),r=!0)}catch{}nu(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 OH(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 jH(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 LH(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 UH(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 FH(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 HH(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=Rc.join(_e(),"agent-logs"),r=Rc.join(n,`${e.agentId}.stderr.log`),o="";try{o=Tc.readFileSync(r,"utf-8")}catch{}e.tail&&e.tail>0&&o&&(o=o.split(`
727
727
  `).slice(-e.tail).join(`
728
- `)),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 zH(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 BH(t,e,n,r,o,i){let s=Ug(e,r,o),a=fH(s);if(a)return a;if(o!==Fg){let f=hH(Ug(e,r,Fg),s);if(f)return f}let c=`chat-${e}-${Zue().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Jr({onNotification:(f,g,h)=>{Que({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 Og({tool:g,args:h,projectRoot:r});return y.handled?y.result:{ok:!1,error:"MCP tool call unavailable"}},onPermissionRequest:(f,g)=>kH(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:Rc.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 gH(s,m),m}async function qH(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 BH(this,n,o,i,Fg),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 WH(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=Ug(n,a,l),h=await BH(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 epe({sessionId:l,projectRoot:a,turnId:d,projectId:m,agentId:n,prompt:r,error:S,lockSessionOwner:f}),qs(g),S}finally{h.holder.current=null,yH(g)}let v=y.deltas.join("")||(typeof b?.content=="string"?b.content:""),k=h.manager.getUsageTracker(h.memberId)?.getUsage();if(l){yr(l,{role:"user",content:r},a,d),v&&yr(l,{role:"assistant",content:v},a,d);let S=Kt(l,a);vt(l,{type:"personal",...m?{projectId:m}:{},...S?.title?{}:{title:Dl(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=SH(e);this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:xH(e),...n?{data:{authMethods:n}}:{}})}}}em();function npe(t){let e=ipe(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=ape(r.topK),s=await zg(e,Hg(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:o,topK:i,prefer:r.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(Ac(s)&&Array.isArray(s.matches)?s.matches:[]).map(cpe).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 zg(e,Hg(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=VH(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 zg(e,Hg(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(Ac(i)&&Array.isArray(i.versions)?i.versions:[]).map(lpe).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 zg(e,Hg(t.baseUrl,`/api/v15/runtime/${i}/resolve?platform=${s}`),n,"GET"),c=dpe(a);if(!c)throw new Error("Community hub returned an invalid runtime resolution.");return c}}}function Pc(t=ii()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=rpe(t);return npe({baseUrl:ope(t),token:e,clientVersion:n})}function rpe(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.17.5"}function ope(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Hg(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 ipe(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function zg(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 spe(i)}`);return i.json().catch(()=>null)}async function spe(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function Ac(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function ape(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 cpe(t){if(!Ac(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=GH(t.sourceTier),n=KH(t.trustStage),r=Bg(t.resourceRiskTier),o=Bg(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:JP(t.title,80),summary:JP(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=>JP(s,32)),sourceTier:e,trustStage:n,resourceRiskTier:r,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function JP(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}\u2026`}function lpe(t){return!Ac(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 dpe(t){if(!Ac(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 upe=new Set(["R0","R1","R2","R3"]),ppe=new Set(["official","community"]),mpe=new Set(["quarantine","trial","trusted"]),fpe=new Set(["pending","approved","rejected"]);function Bg(t){return typeof t=="string"&&upe.has(t)?t:null}function GH(t){return typeof t=="string"&&ppe.has(t)?t:null}function KH(t){return typeof t=="string"&&mpe.has(t)?t:null}function gpe(t){return typeof t=="string"&&fpe.has(t)?t:null}function VH(t){if(!Ac(t))return null;let e=GH(t.sourceTier),n=KH(t.trustStage),r=gpe(t.reviewStatus),o=Bg(t.resourceRiskTier),i=Bg(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(VH);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}}le();var ZP={enabled:!0},hpe=new Set(["R2","R3"]);function JH(t,e=ZP){return hpe.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 ype,verify as vpe}from"node:crypto";function bpe(t){return`id=${t.id}
728
+ `)),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 zH(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 BH(t,e,n,r,o,i){let s=Ug(e,r,o),a=fH(s);if(a)return a;if(o!==Fg){let f=hH(Ug(e,r,Fg),s);if(f)return f}let c=`chat-${e}-${Zue().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Jr({onNotification:(f,g,h)=>{Que({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 Og({tool:g,args:h,projectRoot:r});return y.handled?y.result:{ok:!1,error:"MCP tool call unavailable"}},onPermissionRequest:(f,g)=>kH(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:Rc.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 gH(s,m),m}async function qH(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 BH(this,n,o,i,Fg),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 WH(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=Ug(n,a,l),h=await BH(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 epe({sessionId:l,projectRoot:a,turnId:d,projectId:m,agentId:n,prompt:r,error:S,lockSessionOwner:f}),qs(g),S}finally{h.holder.current=null,yH(g)}let v=y.deltas.join("")||(typeof b?.content=="string"?b.content:""),k=h.manager.getUsageTracker(h.memberId)?.getUsage();if(l){yr(l,{role:"user",content:r},a,d),v&&yr(l,{role:"assistant",content:v},a,d);let S=Kt(l,a);vt(l,{type:"personal",...m?{projectId:m}:{},...S?.title?{}:{title:Dl(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=SH(e);this.sendResponse(t.id,void 0,{code:w.INTERNAL_ERROR,message:xH(e),...n?{data:{authMethods:n}}:{}})}}}em();function npe(t){let e=ipe(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=ape(r.topK),s=await zg(e,Hg(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:o,topK:i,prefer:r.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(Ac(s)&&Array.isArray(s.matches)?s.matches:[]).map(cpe).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 zg(e,Hg(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=VH(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 zg(e,Hg(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(Ac(i)&&Array.isArray(i.versions)?i.versions:[]).map(lpe).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 zg(e,Hg(t.baseUrl,`/api/v15/runtime/${i}/resolve?platform=${s}`),n,"GET"),c=dpe(a);if(!c)throw new Error("Community hub returned an invalid runtime resolution.");return c}}}function Pc(t=ii()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=rpe(t);return npe({baseUrl:ope(t),token:e,clientVersion:n})}function rpe(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.17.6"}function ope(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Hg(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 ipe(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function zg(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 spe(i)}`);return i.json().catch(()=>null)}async function spe(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function Ac(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function ape(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 cpe(t){if(!Ac(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=GH(t.sourceTier),n=KH(t.trustStage),r=Bg(t.resourceRiskTier),o=Bg(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:JP(t.title,80),summary:JP(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=>JP(s,32)),sourceTier:e,trustStage:n,resourceRiskTier:r,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function JP(t,e){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,Math.max(0,e-1))}\u2026`}function lpe(t){return!Ac(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 dpe(t){if(!Ac(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 upe=new Set(["R0","R1","R2","R3"]),ppe=new Set(["official","community"]),mpe=new Set(["quarantine","trial","trusted"]),fpe=new Set(["pending","approved","rejected"]);function Bg(t){return typeof t=="string"&&upe.has(t)?t:null}function GH(t){return typeof t=="string"&&ppe.has(t)?t:null}function KH(t){return typeof t=="string"&&mpe.has(t)?t:null}function gpe(t){return typeof t=="string"&&fpe.has(t)?t:null}function VH(t){if(!Ac(t))return null;let e=GH(t.sourceTier),n=KH(t.trustStage),r=gpe(t.reviewStatus),o=Bg(t.resourceRiskTier),i=Bg(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(VH);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}}le();var ZP={enabled:!0},hpe=new Set(["R2","R3"]);function JH(t,e=ZP){return hpe.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 ype,verify as vpe}from"node:crypto";function bpe(t){return`id=${t.id}
729
729
  version=${t.version}
730
730
  checksum=${t.checksum}
731
731
  sizeBytes=${t.sizeBytes}`}function kpe(t){return t.includes("\\n")?t.replace(/\\n/g,`