qlogicagent 2.14.8 → 2.14.9
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
|
@@ -424,7 +424,7 @@ ${n.stderr}`:""].filter(Boolean).join(`
|
|
|
424
424
|
${t}
|
|
425
425
|
${n.authorization??""}`,i=Ny.get(o);if(i&&Date.now()<i.expiresAt)return i.value;let s=Dy.get(o);if(s)return await s;let a=$C(r,t,n).then(c=>(Ny.set(o,{value:c,expiresAt:Date.now()+IC}),c)).finally(()=>{Dy.delete(o)});return Dy.set(o,a),a}async function MC(t,e){let r=Md(e),n=_C(e),o=`${r}
|
|
426
426
|
${t}
|
|
427
|
-
${n.authorization??""}`,i=await $C(r,t,n);return Ny.set(o,{value:i,expiresAt:Date.now()+IC}),i}async function $C(t,e,r){let n;try{n=await fetch(`${t}${e}`,{method:"GET",headers:r,signal:AbortSignal.timeout(1e4)})}catch{throw new zn}if(!n.ok)throw new zn;let o=await n.json().catch(()=>null),i=Array.isArray(o)?o:FC(o)&&Array.isArray(o.data)?o.data:null;if(!i)throw new zn;return i}function jy(t){let e=t.trim().replace(/\/+$/,"");return e.endsWith("/v1")?`${e}/models`:`${e}/v1/models`}async function FV(t,e){let r;try{r=await fetch(t,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`},signal:AbortSignal.timeout(1e4)})}catch{throw new zn}if(!r.ok)throw new zn;let n=await r.json().catch(()=>null),o=Array.isArray(n)?n:FC(n)&&Array.isArray(n.data)?n.data:null;if(!o)throw new zn;return o}async function oc(t,e={}){return e.force?MC("/ext/model-catalog/providers",t):EC("/ext/model-catalog/providers",t)}async function Ly(t,e={}){return e.force?MC("/ext/model-catalog/models",t):EC("/ext/model-catalog/models",t)}async function DC(t,e){return FV(jy(t),e)}function $d(t){let e={zhipu:"Zhipu GLM","zhipu-openai":"Zhipu GLM OpenAI","zhipu-coding":"Zhipu GLM Coding",qwen:"Alibaba Qwen (DashScope)","qwen-coding":"Alibaba Qwen (Coding Plan)",volcengine:"Doubao / Volcengine","volcengine-plan":"Doubao / Volcengine Plan"};return e[t.id]?e[t.id]:t.displayName??t.name??t.id}function bo(t){return t.baseUrl??t.base_url}async function Uy(t,e,r={}){return(await oc(e,r)).find(o=>o.id===t)??null}async function HV(t,e,r={}){let[n,o]=await Promise.all([oc(e,r),Ly(e,r)]);t.replaceCatalogProviders(n.map(LC));let i=o.flatMap(BV);return t.replaceCatalogModels(i),i}async function zV(t,e,r,n){let o=await DC(t,e);if(o.length===0)return[];let i=new Set(o.map(jC).filter(a=>!!a));return(await Ly(r,{force:n})).map(Fy).filter(a=>!!a&&i.has(a.model)).map(a=>({...a,baseUrl:t}))}async function fs(t,e,r={}){let n=new Set(t.getAllProviderStatus().filter(d=>d.keys.some(p=>p.enabled&&p.healthStatus!=="disabled")).map(d=>d.providerId));if(n.size===0)return HV(t,e,r);let o=t.getProviderStatus(ct)?.baseUrl??Md(e),[i,s]=await Promise.all([oc(e,{force:r.force}).catch(()=>[]),Ly(e,{force:r.force})]);t.replaceCatalogProviders(i.map(LC));let a=n.has(ct),c=null;if(a){let d=t.getKeyForProvider(ct);if(d)try{let p=(await DC(o,d)).map(jC).filter(m=>!!m);p.length>0&&(c=new Set(p))}catch{}}let l=[];for(let d of s){let p=OC(d);if(p&&p.provider!==ct&&n.has(p.provider)&&l.push(p),a){let m=Fy(d);m&&(c===null||c.has(m.model))&&l.push({...m,baseUrl:o})}}return t.replaceCatalogModels(l),l}async function NC(t,e){let r=await zV(e.baseUrl,e.apiKey,e.configPort,e.forceCatalog);return t.replaceProviderModels(ct,r),r}function ic(t,e=pr()){if(t.getBinding("textGeneration")||!e.get("QLOGIC_LLMROUTER_INFERENCE_KEY")?.trim())return!1;let n=t.listModels({purpose:"textGeneration",provider:ct,enabledOnly:!0}),i=n.find(s=>s.model.toLowerCase().includes("deepseek"))??n[0];return i?(t.setBinding("textGeneration",i.id),!0):!1}function BV(t){return[OC(t),Fy(t)].filter(e=>!!e)}function OC(t){let e=t.provider??t.owned_by,r=t.public_model??t.publicModel??t.id,n=t.native_model_id??t.nativeModelId??t.id;return!e||!r||!n?null:{id:`${e}:${r}`,provider:e,model:r,displayName:t.display_name??t.displayName??t.name??t.id,routeIntents:UC(t.route_intents,t.category),baseUrl:t.baseUrl??t.base_url,enabled:!0,nativeModelId:n,transport:t.provider_transport??t.providerTransport,contextWindow:t.context_window??t.contextWindow,maxOutput:t.max_output??t.maxOutput,streamRequired:t.stream_required??t.streamRequired,toolCall:t.tool_call??t.toolCall,mediaType:t.media_type!==void 0?t.media_type:t.mediaType,reasoningMode:t.reasoning_mode??t.reasoningMode,capabilityProfile:t.capability_profile,pricing:t.pricing}}function Fy(t){let e=t.public_model??t.publicModel??t.id;return e?{id:`${ct}:${e}`,provider:ct,model:e,displayName:t.display_name??t.displayName??t.name??t.id,routeIntents:UC(t.route_intents,t.category),enabled:!0,nativeModelId:e,transport:"openai-responses",contextWindow:t.context_window??t.contextWindow,maxOutput:t.max_output??t.maxOutput,streamRequired:t.stream_required??t.streamRequired,toolCall:t.tool_call??t.toolCall,mediaType:t.media_type!==void 0?t.media_type:t.mediaType,reasoningMode:t.reasoning_mode??t.reasoningMode,capabilityProfile:t.capability_profile,pricing:t.pricing}:null}function jC(t){return t.public_model??t.publicModel??t.id}function LC(t){return{id:t.id,name:$d(t),transport:t.transport??"",baseUrl:bo(t)??"",group:t.group,models:t.models?.flatMap(e=>e.id?[{id:e.id}]:[])??[]}}function UC(t,e){let r=[...t??[],e].filter(i=>!!i),n=new Set(["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"]),o=r.filter(i=>n.has(i));return[...new Set(o.length?o:["textGeneration"])]}function FC(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}import*as rI from"node:path";var fi="1.0.0",b={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030,REQUEST_DEADLINE_EXCEEDED:-32040,REQUEST_CANCELLED:-32041,REQUEST_DEDUPED:-32042,REQUEST_IDEMPOTENCY_REQUIRED:-32043};function Hy(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&e.method.length>0}import{randomUUID as qV}from"node:crypto";var WV=["settings.list","settings.get","settings.validate","provider.list","config.get","config.tunables","tools.list","todos.list","tasks.list","agents.list","agents.get","agents.processes","agents.scan","session.list","session.get","session.resolve","thread.list","project.list","files.list","files.gitStatus","instructions.list","instructions.read","skills.list","skills.stats","memory.atlas","memory.activity","memory.list","memory.read","memory.search","media.listModels","media.status","pet.status","agent.health","agent.metrics"],KV=new Set(["memory.dream","memory.propose","memory.consolidate","media.stt","pet.forge","pet.asset.import","solo.start","solo.evaluate","product.plan","product.create","product.message"]),GV=["memory.","pet.","usage."],VV=new Set(["memory.atlas","memory.activity","memory.list","memory.read","memory.search","memory.attachment.locate","memory.attachment.adopt","pet.status"]);function Dd(t){return KV.has(t)?{channel:"task",mutability:"write",defaultTimeoutMs:12e4}:WV.some(e=>t===e||t.startsWith(`${e}.`)||t.startsWith(e))?{channel:"query",mutability:"read",defaultTimeoutMs:1e4}:{channel:"task",mutability:"write",defaultTimeoutMs:3e4}}function HC(t){return VV.has(t)||Dd(t).mutability==="read"?!1:GV.some(e=>t.startsWith(e))}function zy(t,e={}){let r=e.now??Date.now(),n=Dd(t),o=e.timeoutMs??n.defaultTimeoutMs;return{requestId:e.requestId??qV(),createdAt:r,deadlineAt:r+o,channel:e.channel??n.channel,idempotencyKey:e.idempotencyKey,traceId:e.traceId}}function Nd(t,e=Date.now()){let r=t.meta;if(!r||typeof r!="object")return{ok:!1,error:{code:b.INVALID_REQUEST,message:"RPC request meta is required."}};if(typeof r.requestId!="string"||r.requestId.length===0)return{ok:!1,error:{code:b.INVALID_REQUEST,message:"RPC request meta.requestId is required."}};if(r.channel!=="query"&&r.channel!=="task")return{ok:!1,error:{code:b.INVALID_REQUEST,message:"RPC request meta.channel must be query or task."}};if(typeof r.createdAt!="number"||!Number.isFinite(r.createdAt))return{ok:!1,error:{code:b.INVALID_REQUEST,message:"RPC request meta.createdAt is required."}};if(typeof r.deadlineAt!="number"||!Number.isFinite(r.deadlineAt))return{ok:!1,error:{code:b.INVALID_REQUEST,message:"RPC request meta.deadlineAt is required."}};if(r.deadlineAt<=e)return{ok:!1,error:{code:b.REQUEST_DEADLINE_EXCEEDED,message:"RPC request deadline has already expired."}};let n=Dd(t.method).channel;return r.channel!==n?{ok:!1,error:{code:b.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${n}, got ${r.channel}.`}}:HC(t.method)&&(typeof r.idempotencyKey!="string"||r.idempotencyKey.length===0)?{ok:!1,error:{code:b.REQUEST_IDEMPOTENCY_REQUIRED,message:`RPC method ${t.method} requires meta.idempotencyKey.`}}:{ok:!0,meta:r}}var sc=class{now;active=new Map;idempotency=new Map;counters={completedRequests:0,cancelledRequests:0,deadlineExceededRequests:0,dedupedRequests:0,lateResponsesDropped:0,invalidRequests:0};constructor(e={}){this.now=e.now??(()=>Date.now())}begin(e,r){let n=Nd({method:e,meta:r},this.now());if(!n.ok)return this.counters.invalidRequests+=1,{status:"rejected",error:n.error};if(r.idempotencyKey){let o=this.idempotency.get(r.idempotencyKey);if(o)return this.counters.dedupedRequests+=1,o.error?{status:"deduped",error:o.error}:{status:"deduped",result:o.result}}return this.active.set(r.requestId,{method:e,meta:r,cancelled:!1,startedAt:this.now()}),{status:"started"}}cancel(e,r="cancelled"){let n=this.active.get(e);return!n||n.cancelled?!1:(n.cancelled=!0,n.cancelReason=r,this.counters.cancelledRequests+=1,!0)}expire(e){return this.active.get(e)?(this.active.delete(e),this.counters.deadlineExceededRequests+=1,!0):!1}settle(e,r,n){let o=this.active.get(e);return o?(this.active.delete(e),o.cancelled?(this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"cancelled"}):o.meta.deadlineAt<=this.now()?(this.counters.deadlineExceededRequests+=1,this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"deadline_exceeded"}):(this.counters.completedRequests+=1,o.meta.idempotencyKey&&this.idempotency.set(o.meta.idempotencyKey,{result:r,error:n,settledAt:this.now()}),{accepted:!0})):{accepted:!1,reason:"unknown"}}metrics(){return{activeRequests:this.active.size,...this.counters}}};var zC=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.media_usage","turn.media_capability_check","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated","skills.updated","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.asset.updated","system.activity","workflow.created","workflow.updated","workflow.deleted","workflow.runStarted","workflow.runCompleted","workflow.runFailed","workflow.nodeStatus","workflow.triggerDropped","workflow.alert","workflow.approvalRequested"],BC=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.budgetWarning","product.checkpointed","product.completed","product.dagTopology","plan.interrupted"],ZV=[...zC,...BC];var Gt={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_CLOSE:"session/close",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_LOAD:"session/load",SESSION_CANCEL:"session/cancel",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},Te={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",SOLO_SPEC_CHAT:"x/solo.specChat",SOLO_SPEC_JUDGE:"x/solo.specJudge",WORKFLOW_CHAT:"x/workflow.chat",WORKFLOW_MATCH_INTENT:"x/workflow.matchIntent",PRODUCT_SUBSCRIBE:"x/product.subscribe"},mn={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",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update"},gs={X_SKILL_INSTRUCTION:"x_skill_instruction",X_SESSION_INFO:"x_session_info",X_RELAY:"x_relay"};function ac(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&"id"in e}function cc(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&!("id"in e)}function By(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&"id"in e&&!("method"in e)}var qC="openai-codex";var iSe={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[qC]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};import{randomUUID as FE}from"node:crypto";import*as Zv from"node:path";import{readFile as Od,writeFile as Ky,stat as Wy,unlink as uZ,mkdir as Gy}from"node:fs/promises";import{join as ko,resolve as t_,isAbsolute as r_,normalize as n_}from"node:path";import{randomUUID as pZ}from"node:crypto";function KC(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function JV(t){return t.latestInputTokens+t.cumulativeOutputTokens}var XV=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),GC=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function YV(t){return{isSearch:XV.has(t)||void 0,isRead:GC.has(t)||void 0}}function QV(t,e){let r=e.file_path??e.path??e.filePath;if(typeof r=="string")return`${GC.has(t)?"Reading":t.includes("write")||t.includes("edit")?"Editing":"Using"} ${r}`;let n=e.command??e.cmd;if(typeof n=="string")return`Running: ${n.length>60?n.slice(0,60)+"\u2026":n}`;let o=e.query??e.pattern??e.search;if(typeof o=="string")return`Searching: ${o}`}function VC(t,e){t.latestInputTokens=(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0),t.cumulativeOutputTokens+=e.output_tokens??0}function ZC(t,e,r,n){t.toolUseCount++;let o=YV(e),i={toolName:e,input:r,activityDescription:n?.(e,r)??QV(e,r),isSearch:o.isSearch,isRead:o.isRead};for(t.recentActivities.push(i);t.recentActivities.length>5;)t.recentActivities.shift()}function qy(t){return{toolUseCount:t.toolUseCount,tokenCount:JV(t),lastActivity:t.recentActivities.length>0?t.recentActivities[t.recentActivities.length-1]:void 0,recentActivities:[...t.recentActivities]}}import{AsyncLocalStorage as eZ}from"node:async_hooks";var JC=new eZ;function lc(){return JC.getStore()?.depth??0}function XC(t,e){return JC.run({depth:t},e)}import{randomUUID as YC}from"node:crypto";function tZ(t){let e=new AbortController;return t&&(t.aborted?e.abort(t.reason):t.addEventListener("abort",()=>{e.abort(t.reason)},{once:!0})),e}async function Wr(t){let e=Date.now(),r=[],n={inputTokens:0,outputTokens:0},o=KC(),{promptMessages:i,systemPrompt:s,tools:a,canUseTool:c,transport:l,toolInvoker:d,createAgentRunner:p,apiKey:m,model:f,log:g,hooks:h,forkLabel:y,maxTurns:v,temperature:k,parentSignal:w,onEvent:S,onProgress:T,budgetTokens:M,parentDepth:_}=t,R=tZ(w),C=`fork-${y}-${YC().slice(0,8)}`,U=`fork-session-${YC().slice(0,8)}`,j=(_??lc())+1;g.info(`[fork:${y}] starting \u2014 ${i.length} initial messages, model=${f}, depth=${j}`);let W=c?{invoke:async(Ze,de,ht,J)=>{let I={};try{I=JSON.parse(ht)}catch{}let Je=c(de,I);return Je.allowed?d.invoke(Ze,de,ht,J):(g.info(`[fork:${y}] tool ${de} denied: ${Je.reason}`),{result:"",error:Je.reason})}}:d,Q=!0,Me;try{await XC(j,async()=>{let Ze=p({transport:l,apiKey:m,toolInvoker:W,log:g,hooks:h,maxRounds:v});for await(let de of Ze.run({turnId:C,sessionId:U,messages:i,tools:a,systemPrompt:s,config:{model:f,apiKey:m,temperature:k,maxOutputTokens:t.maxOutputTokens,parentDepth:j-1}},R.signal)){if(r.push(de),S?.(de),de.type==="end"&&de.usage&&(VC(o,{input_tokens:de.usage.inputTokens,output_tokens:de.usage.outputTokens}),n.inputTokens+=de.usage.inputTokens,n.outputTokens+=de.usage.outputTokens,de.usage.cacheRead&&(n.cacheRead=(n.cacheRead??0)+de.usage.cacheRead),de.usage.cacheWrite&&(n.cacheWrite=(n.cacheWrite??0)+de.usage.cacheWrite),M&&M>0)){let ht=n.inputTokens+n.outputTokens+(n.reasoningTokens??0);ht>=M&&(g.info(`[fork:${y}] budget exceeded (${ht} / ${M} tokens), aborting`),R.abort("budget_exceeded"))}if(de.type==="tool_call"){let ht={};try{ht=JSON.parse(de.arguments??"{}")}catch{}ZC(o,de.name,ht),T?.(qy(o))}de.type==="error"&&(Q=!1,Me=de.error)}})}catch(Ze){Q=!1,Me=Ze instanceof Error?Ze.message:String(Ze),g.warn(`[fork:${y}] error: ${Me}`)}finally{R.signal.aborted||R.abort("fork_complete")}let cr=Date.now()-e;return g.info(`[fork:${y}] finished in ${cr}ms \u2014 ${r.length} events, usage: prompt=${n.inputTokens} completion=${n.outputTokens}, ok=${Q}`),{events:r,totalUsage:n,progress:qy(o),durationMs:cr,ok:Q,error:Me}}import{readFile as rZ,readdir as nZ}from"node:fs/promises";import{existsSync as oZ}from"node:fs";import{join as iZ}from"node:path";var sZ={lesson:"lesson",debug:"lesson",gotcha:"lesson",fix:"lesson",preference:"preference",style:"preference",pattern:"pattern",convention:"pattern",practice:"pattern",fact:"fact",config:"fact",architecture:"fact",env:"fact",deploy:"fact",decision:"decision",choice:"decision",tradeoff:"decision",skill:"skill-learning",workflow:"skill-learning"},aZ={lesson:[/(?:原来|root cause|turns out|the issue was|问题出在|踩坑|gotcha|pitfall)/i,/(?:以后|下次|remember to|don't forget|务必|切记)/i],preference:[/(?:我(?:喜欢|偏好|习惯)|I (?:prefer|like|always))/i,/(?:请(?:用|使用)|please use|always use)/i],pattern:[/(?:每次|always|whenever|pattern|惯例|convention|best practice)/i],fact:[/(?:架构|architecture|port|version|部署|deployed|环境|配置|config)/i],decision:[/(?:决定|decided|选择|chosen|采用|因为|because|rationale|trade-?off)/i],"skill-learning":[/(?:skill|workflow|tool|command|命令|工具)/i]};function cZ(t){let e=t.replace(/\.md$/,"").toLowerCase();for(let[r,n]of Object.entries(sZ))if(e.startsWith(r+"-")||e.startsWith(r+"_")||e===r)return n;return null}function lZ(t){let e=t.slice(0,500),r=null,n=0;for(let[o,i]of Object.entries(aZ)){let s=i.filter(a=>a.test(e)).length;s>n&&(n=s,r=o)}return r}async function QC(t){let e={},r=0,n=0;if(!oZ(t))return{categories:e,totalFiles:0,uncategorizedCount:0};let o;try{o=await nZ(t)}catch{return{categories:e,totalFiles:0,uncategorizedCount:0}}let i=o.filter(s=>s.endsWith(".md")&&s!=="INDEX.md");for(let s of i){let a=iZ(t,s);try{let c=await rZ(a,"utf-8");r++;let l=cZ(s)??lZ(c)??"uncategorized";l==="uncategorized"&&n++;let d=c.split(`
|
|
427
|
+
${n.authorization??""}`,i=await $C(r,t,n);return Ny.set(o,{value:i,expiresAt:Date.now()+IC}),i}async function $C(t,e,r){let n;try{n=await fetch(`${t}${e}`,{method:"GET",headers:r,signal:AbortSignal.timeout(1e4)})}catch{throw new zn}if(!n.ok)throw new zn;let o=await n.json().catch(()=>null),i=Array.isArray(o)?o:FC(o)&&Array.isArray(o.data)?o.data:null;if(!i)throw new zn;return i}function jy(t){let e=t.trim().replace(/\/+$/,"");return e.endsWith("/v1")?`${e}/models`:`${e}/v1/models`}async function FV(t,e){let r;try{r=await fetch(t,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`},signal:AbortSignal.timeout(1e4)})}catch{throw new zn}if(!r.ok)throw new zn;let n=await r.json().catch(()=>null),o=Array.isArray(n)?n:FC(n)&&Array.isArray(n.data)?n.data:null;if(!o)throw new zn;return o}async function oc(t,e={}){return e.force?MC("/ext/model-catalog/providers",t):EC("/ext/model-catalog/providers",t)}async function Ly(t,e={}){return e.force?MC("/ext/model-catalog/models",t):EC("/ext/model-catalog/models",t)}async function DC(t,e){return FV(jy(t),e)}function $d(t){let e={zhipu:"Zhipu GLM","zhipu-openai":"Zhipu GLM OpenAI","zhipu-coding":"Zhipu GLM Coding",qwen:"Alibaba Qwen (DashScope)","qwen-coding":"Alibaba Qwen (Coding Plan)",volcengine:"Doubao / Volcengine","volcengine-plan":"Doubao / Volcengine Plan"};return e[t.id]?e[t.id]:t.displayName??t.name??t.id}function bo(t){return t.baseUrl??t.base_url}async function Uy(t,e,r={}){return(await oc(e,r)).find(o=>o.id===t)??null}async function HV(t,e,r={}){let[n,o]=await Promise.all([oc(e,r),Ly(e,r)]);t.replaceCatalogProviders(n.map(LC));let i=o.flatMap(BV);return t.replaceCatalogModels(i),i}async function zV(t,e,r,n){let o=await DC(t,e);if(o.length===0)return[];let i=new Set(o.map(jC).filter(a=>!!a));return(await Ly(r,{force:n})).map(Fy).filter(a=>!!a&&i.has(a.model)).map(a=>({...a,baseUrl:t}))}async function fs(t,e,r={}){let n=new Set(t.getAllProviderStatus().filter(d=>d.keys.some(p=>p.enabled&&p.healthStatus!=="disabled")).map(d=>d.providerId));if(n.size===0)return HV(t,e,r);let o=t.getProviderStatus(ct)?.baseUrl??Md(e),[i,s]=await Promise.all([oc(e,{force:r.force}).catch(()=>[]),Ly(e,{force:r.force})]);t.replaceCatalogProviders(i.map(LC));let a=n.has(ct),c=null;if(a){let d=t.getKeyForProvider(ct);if(d)try{let p=(await DC(o,d)).map(jC).filter(m=>!!m);p.length>0&&(c=new Set(p))}catch{}}let l=[];for(let d of s){let p=OC(d);if(p&&p.provider!==ct&&n.has(p.provider)&&l.push(p),a){let m=Fy(d);m&&(c===null||c.has(m.model))&&l.push({...m,baseUrl:o})}}return t.replaceCatalogModels(l),l}async function NC(t,e){let r=await zV(e.baseUrl,e.apiKey,e.configPort,e.forceCatalog);return t.replaceProviderModels(ct,r),r}function ic(t,e=pr()){if(t.getBinding("textGeneration")||!e.get("QLOGIC_LLMROUTER_INFERENCE_KEY")?.trim())return!1;let n=t.listModels({purpose:"textGeneration",provider:ct,enabledOnly:!0}),i=n.find(s=>s.model.toLowerCase().includes("deepseek"))??n[0];return i?(t.setBinding("textGeneration",i.id),!0):!1}function BV(t){return[OC(t),Fy(t)].filter(e=>!!e)}function OC(t){let e=t.provider??t.owned_by,r=t.public_model??t.publicModel??t.id,n=t.native_model_id??t.nativeModelId??t.id;return!e||!r||!n?null:{id:`${e}:${r}`,provider:e,model:r,displayName:t.display_name??t.displayName??t.name??t.id,routeIntents:UC(t.route_intents,t.category),baseUrl:t.baseUrl??t.base_url,enabled:!0,nativeModelId:n,transport:t.provider_transport??t.providerTransport,contextWindow:t.context_window??t.contextWindow,maxOutput:t.max_output??t.maxOutput,streamRequired:t.stream_required??t.streamRequired,toolCall:t.tool_call??t.toolCall,mediaType:t.media_type!==void 0?t.media_type:t.mediaType,reasoningMode:t.reasoning_mode??t.reasoningMode,capabilityProfile:t.capability_profile,pricing:t.pricing}}function Fy(t){let e=t.public_model??t.publicModel??t.id;return e?{id:`${ct}:${e}`,provider:ct,model:e,displayName:t.display_name??t.displayName??t.name??t.id,routeIntents:UC(t.route_intents,t.category),enabled:!0,nativeModelId:e,transport:"openai-chat",contextWindow:t.context_window??t.contextWindow,maxOutput:t.max_output??t.maxOutput,streamRequired:t.stream_required??t.streamRequired,toolCall:t.tool_call??t.toolCall,mediaType:t.media_type!==void 0?t.media_type:t.mediaType,reasoningMode:t.reasoning_mode??t.reasoningMode,capabilityProfile:t.capability_profile,pricing:t.pricing}:null}function jC(t){return t.public_model??t.publicModel??t.id}function LC(t){return{id:t.id,name:$d(t),transport:t.transport??"",baseUrl:bo(t)??"",group:t.group,models:t.models?.flatMap(e=>e.id?[{id:e.id}]:[])??[]}}function UC(t,e){let r=[...t??[],e].filter(i=>!!i),n=new Set(["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"]),o=r.filter(i=>n.has(i));return[...new Set(o.length?o:["textGeneration"])]}function FC(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}import*as rI from"node:path";var fi="1.0.0",b={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030,REQUEST_DEADLINE_EXCEEDED:-32040,REQUEST_CANCELLED:-32041,REQUEST_DEDUPED:-32042,REQUEST_IDEMPOTENCY_REQUIRED:-32043};function Hy(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&e.method.length>0}import{randomUUID as qV}from"node:crypto";var WV=["settings.list","settings.get","settings.validate","provider.list","config.get","config.tunables","tools.list","todos.list","tasks.list","agents.list","agents.get","agents.processes","agents.scan","session.list","session.get","session.resolve","thread.list","project.list","files.list","files.gitStatus","instructions.list","instructions.read","skills.list","skills.stats","memory.atlas","memory.activity","memory.list","memory.read","memory.search","media.listModels","media.status","pet.status","agent.health","agent.metrics"],KV=new Set(["memory.dream","memory.propose","memory.consolidate","media.stt","pet.forge","pet.asset.import","solo.start","solo.evaluate","product.plan","product.create","product.message"]),GV=["memory.","pet.","usage."],VV=new Set(["memory.atlas","memory.activity","memory.list","memory.read","memory.search","memory.attachment.locate","memory.attachment.adopt","pet.status"]);function Dd(t){return KV.has(t)?{channel:"task",mutability:"write",defaultTimeoutMs:12e4}:WV.some(e=>t===e||t.startsWith(`${e}.`)||t.startsWith(e))?{channel:"query",mutability:"read",defaultTimeoutMs:1e4}:{channel:"task",mutability:"write",defaultTimeoutMs:3e4}}function HC(t){return VV.has(t)||Dd(t).mutability==="read"?!1:GV.some(e=>t.startsWith(e))}function zy(t,e={}){let r=e.now??Date.now(),n=Dd(t),o=e.timeoutMs??n.defaultTimeoutMs;return{requestId:e.requestId??qV(),createdAt:r,deadlineAt:r+o,channel:e.channel??n.channel,idempotencyKey:e.idempotencyKey,traceId:e.traceId}}function Nd(t,e=Date.now()){let r=t.meta;if(!r||typeof r!="object")return{ok:!1,error:{code:b.INVALID_REQUEST,message:"RPC request meta is required."}};if(typeof r.requestId!="string"||r.requestId.length===0)return{ok:!1,error:{code:b.INVALID_REQUEST,message:"RPC request meta.requestId is required."}};if(r.channel!=="query"&&r.channel!=="task")return{ok:!1,error:{code:b.INVALID_REQUEST,message:"RPC request meta.channel must be query or task."}};if(typeof r.createdAt!="number"||!Number.isFinite(r.createdAt))return{ok:!1,error:{code:b.INVALID_REQUEST,message:"RPC request meta.createdAt is required."}};if(typeof r.deadlineAt!="number"||!Number.isFinite(r.deadlineAt))return{ok:!1,error:{code:b.INVALID_REQUEST,message:"RPC request meta.deadlineAt is required."}};if(r.deadlineAt<=e)return{ok:!1,error:{code:b.REQUEST_DEADLINE_EXCEEDED,message:"RPC request deadline has already expired."}};let n=Dd(t.method).channel;return r.channel!==n?{ok:!1,error:{code:b.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${n}, got ${r.channel}.`}}:HC(t.method)&&(typeof r.idempotencyKey!="string"||r.idempotencyKey.length===0)?{ok:!1,error:{code:b.REQUEST_IDEMPOTENCY_REQUIRED,message:`RPC method ${t.method} requires meta.idempotencyKey.`}}:{ok:!0,meta:r}}var sc=class{now;active=new Map;idempotency=new Map;counters={completedRequests:0,cancelledRequests:0,deadlineExceededRequests:0,dedupedRequests:0,lateResponsesDropped:0,invalidRequests:0};constructor(e={}){this.now=e.now??(()=>Date.now())}begin(e,r){let n=Nd({method:e,meta:r},this.now());if(!n.ok)return this.counters.invalidRequests+=1,{status:"rejected",error:n.error};if(r.idempotencyKey){let o=this.idempotency.get(r.idempotencyKey);if(o)return this.counters.dedupedRequests+=1,o.error?{status:"deduped",error:o.error}:{status:"deduped",result:o.result}}return this.active.set(r.requestId,{method:e,meta:r,cancelled:!1,startedAt:this.now()}),{status:"started"}}cancel(e,r="cancelled"){let n=this.active.get(e);return!n||n.cancelled?!1:(n.cancelled=!0,n.cancelReason=r,this.counters.cancelledRequests+=1,!0)}expire(e){return this.active.get(e)?(this.active.delete(e),this.counters.deadlineExceededRequests+=1,!0):!1}settle(e,r,n){let o=this.active.get(e);return o?(this.active.delete(e),o.cancelled?(this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"cancelled"}):o.meta.deadlineAt<=this.now()?(this.counters.deadlineExceededRequests+=1,this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"deadline_exceeded"}):(this.counters.completedRequests+=1,o.meta.idempotencyKey&&this.idempotency.set(o.meta.idempotencyKey,{result:r,error:n,settledAt:this.now()}),{accepted:!0})):{accepted:!1,reason:"unknown"}}metrics(){return{activeRequests:this.active.size,...this.counters}}};var zC=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.media_usage","turn.media_capability_check","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated","skills.updated","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.asset.updated","system.activity","workflow.created","workflow.updated","workflow.deleted","workflow.runStarted","workflow.runCompleted","workflow.runFailed","workflow.nodeStatus","workflow.triggerDropped","workflow.alert","workflow.approvalRequested"],BC=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.budgetWarning","product.checkpointed","product.completed","product.dagTopology","plan.interrupted"],ZV=[...zC,...BC];var Gt={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_CLOSE:"session/close",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_LOAD:"session/load",SESSION_CANCEL:"session/cancel",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},Te={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",SOLO_SPEC_CHAT:"x/solo.specChat",SOLO_SPEC_JUDGE:"x/solo.specJudge",WORKFLOW_CHAT:"x/workflow.chat",WORKFLOW_MATCH_INTENT:"x/workflow.matchIntent",PRODUCT_SUBSCRIBE:"x/product.subscribe"},mn={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",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update"},gs={X_SKILL_INSTRUCTION:"x_skill_instruction",X_SESSION_INFO:"x_session_info",X_RELAY:"x_relay"};function ac(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&"id"in e}function cc(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&!("id"in e)}function By(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&"id"in e&&!("method"in e)}var qC="openai-codex";var iSe={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[qC]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};import{randomUUID as FE}from"node:crypto";import*as Zv from"node:path";import{readFile as Od,writeFile as Ky,stat as Wy,unlink as uZ,mkdir as Gy}from"node:fs/promises";import{join as ko,resolve as t_,isAbsolute as r_,normalize as n_}from"node:path";import{randomUUID as pZ}from"node:crypto";function KC(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function JV(t){return t.latestInputTokens+t.cumulativeOutputTokens}var XV=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),GC=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function YV(t){return{isSearch:XV.has(t)||void 0,isRead:GC.has(t)||void 0}}function QV(t,e){let r=e.file_path??e.path??e.filePath;if(typeof r=="string")return`${GC.has(t)?"Reading":t.includes("write")||t.includes("edit")?"Editing":"Using"} ${r}`;let n=e.command??e.cmd;if(typeof n=="string")return`Running: ${n.length>60?n.slice(0,60)+"\u2026":n}`;let o=e.query??e.pattern??e.search;if(typeof o=="string")return`Searching: ${o}`}function VC(t,e){t.latestInputTokens=(e.input_tokens??0)+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0),t.cumulativeOutputTokens+=e.output_tokens??0}function ZC(t,e,r,n){t.toolUseCount++;let o=YV(e),i={toolName:e,input:r,activityDescription:n?.(e,r)??QV(e,r),isSearch:o.isSearch,isRead:o.isRead};for(t.recentActivities.push(i);t.recentActivities.length>5;)t.recentActivities.shift()}function qy(t){return{toolUseCount:t.toolUseCount,tokenCount:JV(t),lastActivity:t.recentActivities.length>0?t.recentActivities[t.recentActivities.length-1]:void 0,recentActivities:[...t.recentActivities]}}import{AsyncLocalStorage as eZ}from"node:async_hooks";var JC=new eZ;function lc(){return JC.getStore()?.depth??0}function XC(t,e){return JC.run({depth:t},e)}import{randomUUID as YC}from"node:crypto";function tZ(t){let e=new AbortController;return t&&(t.aborted?e.abort(t.reason):t.addEventListener("abort",()=>{e.abort(t.reason)},{once:!0})),e}async function Wr(t){let e=Date.now(),r=[],n={inputTokens:0,outputTokens:0},o=KC(),{promptMessages:i,systemPrompt:s,tools:a,canUseTool:c,transport:l,toolInvoker:d,createAgentRunner:p,apiKey:m,model:f,log:g,hooks:h,forkLabel:y,maxTurns:v,temperature:k,parentSignal:w,onEvent:S,onProgress:T,budgetTokens:M,parentDepth:_}=t,R=tZ(w),C=`fork-${y}-${YC().slice(0,8)}`,U=`fork-session-${YC().slice(0,8)}`,j=(_??lc())+1;g.info(`[fork:${y}] starting \u2014 ${i.length} initial messages, model=${f}, depth=${j}`);let W=c?{invoke:async(Ze,de,ht,J)=>{let I={};try{I=JSON.parse(ht)}catch{}let Je=c(de,I);return Je.allowed?d.invoke(Ze,de,ht,J):(g.info(`[fork:${y}] tool ${de} denied: ${Je.reason}`),{result:"",error:Je.reason})}}:d,Q=!0,Me;try{await XC(j,async()=>{let Ze=p({transport:l,apiKey:m,toolInvoker:W,log:g,hooks:h,maxRounds:v});for await(let de of Ze.run({turnId:C,sessionId:U,messages:i,tools:a,systemPrompt:s,config:{model:f,apiKey:m,temperature:k,maxOutputTokens:t.maxOutputTokens,parentDepth:j-1}},R.signal)){if(r.push(de),S?.(de),de.type==="end"&&de.usage&&(VC(o,{input_tokens:de.usage.inputTokens,output_tokens:de.usage.outputTokens}),n.inputTokens+=de.usage.inputTokens,n.outputTokens+=de.usage.outputTokens,de.usage.cacheRead&&(n.cacheRead=(n.cacheRead??0)+de.usage.cacheRead),de.usage.cacheWrite&&(n.cacheWrite=(n.cacheWrite??0)+de.usage.cacheWrite),M&&M>0)){let ht=n.inputTokens+n.outputTokens+(n.reasoningTokens??0);ht>=M&&(g.info(`[fork:${y}] budget exceeded (${ht} / ${M} tokens), aborting`),R.abort("budget_exceeded"))}if(de.type==="tool_call"){let ht={};try{ht=JSON.parse(de.arguments??"{}")}catch{}ZC(o,de.name,ht),T?.(qy(o))}de.type==="error"&&(Q=!1,Me=de.error)}})}catch(Ze){Q=!1,Me=Ze instanceof Error?Ze.message:String(Ze),g.warn(`[fork:${y}] error: ${Me}`)}finally{R.signal.aborted||R.abort("fork_complete")}let cr=Date.now()-e;return g.info(`[fork:${y}] finished in ${cr}ms \u2014 ${r.length} events, usage: prompt=${n.inputTokens} completion=${n.outputTokens}, ok=${Q}`),{events:r,totalUsage:n,progress:qy(o),durationMs:cr,ok:Q,error:Me}}import{readFile as rZ,readdir as nZ}from"node:fs/promises";import{existsSync as oZ}from"node:fs";import{join as iZ}from"node:path";var sZ={lesson:"lesson",debug:"lesson",gotcha:"lesson",fix:"lesson",preference:"preference",style:"preference",pattern:"pattern",convention:"pattern",practice:"pattern",fact:"fact",config:"fact",architecture:"fact",env:"fact",deploy:"fact",decision:"decision",choice:"decision",tradeoff:"decision",skill:"skill-learning",workflow:"skill-learning"},aZ={lesson:[/(?:原来|root cause|turns out|the issue was|问题出在|踩坑|gotcha|pitfall)/i,/(?:以后|下次|remember to|don't forget|务必|切记)/i],preference:[/(?:我(?:喜欢|偏好|习惯)|I (?:prefer|like|always))/i,/(?:请(?:用|使用)|please use|always use)/i],pattern:[/(?:每次|always|whenever|pattern|惯例|convention|best practice)/i],fact:[/(?:架构|architecture|port|version|部署|deployed|环境|配置|config)/i],decision:[/(?:决定|decided|选择|chosen|采用|因为|because|rationale|trade-?off)/i],"skill-learning":[/(?:skill|workflow|tool|command|命令|工具)/i]};function cZ(t){let e=t.replace(/\.md$/,"").toLowerCase();for(let[r,n]of Object.entries(sZ))if(e.startsWith(r+"-")||e.startsWith(r+"_")||e===r)return n;return null}function lZ(t){let e=t.slice(0,500),r=null,n=0;for(let[o,i]of Object.entries(aZ)){let s=i.filter(a=>a.test(e)).length;s>n&&(n=s,r=o)}return r}async function QC(t){let e={},r=0,n=0;if(!oZ(t))return{categories:e,totalFiles:0,uncategorizedCount:0};let o;try{o=await nZ(t)}catch{return{categories:e,totalFiles:0,uncategorizedCount:0}}let i=o.filter(s=>s.endsWith(".md")&&s!=="INDEX.md");for(let s of i){let a=iZ(t,s);try{let c=await rZ(a,"utf-8");r++;let l=cZ(s)??lZ(c)??"uncategorized";l==="uncategorized"&&n++;let d=c.split(`
|
|
428
428
|
`),p="";for(let f of d){let g=f.trim();if(!(!g||g.startsWith("#")||g.startsWith("---"))){p=g.slice(0,120);break}}let m=d.filter(f=>/^\s*[-*+]\s|^\s*\d+[.)]\s/.test(f)).length;e[l]||(e[l]=[]),e[l].push({filename:s,category:l,description:p,sizeBytes:Buffer.byteLength(c,"utf-8"),entryCount:m})}catch{}}return{categories:e,totalFiles:r,uncategorizedCount:n}}var dZ={fact:"SUPERSEDE: If a newer fact contradicts an older one (e.g. port changed, version updated), update the existing entry in-place. Do not keep both \u2014 stale facts cause confusion. Convert relative dates to absolute. Mark the update date.",lesson:"ACCUMULATE: Lessons learned are valuable even when old. Append new insights to existing lesson files. Only remove a lesson if it's provably wrong (not just outdated). Group related lessons under the same topic file.",preference:"OVERWRITE: User preferences evolve. If a newer statement contradicts an older preference, the newer one wins. Remove the old entry and write the current preference. Keep preferences concise (one line each).",pattern:"MERGE: If multiple entries describe the same pattern, merge them into one authoritative entry with examples. Remove redundant duplicates. A pattern that's been superseded by a better practice should be removed.",decision:"UPDATE: Decisions have context and rationale. When a decision changes, don't delete the old one \u2014 add an 'Updated (date):' section explaining what changed and why. This preserves the decision history.","skill-learning":"CONSOLIDATE: Group related skill entries by tool/workflow. Remove entries for skills that are now obvious or well-documented elsewhere. Keep the most actionable version of each skill note.",uncategorized:"CLASSIFY: Try to infer a category from the content. If it matches lesson/preference/pattern/fact/decision, rename the file with the appropriate prefix. If truly uncategorizable, leave as-is but ensure it has a clear description."};function e_(t){if(t.totalFiles===0)return"\n## Category Context\n\nNo existing memory files found. Create new files using the naming convention: `<category>-<topic>.md` (e.g. `lesson-docker.md`, `fact-ports.md`, `decision-framework.md`).\n";let e=[];e.push(`
|
|
429
429
|
## Category Context (${t.totalFiles} files)
|
|
430
430
|
`),e.push(`Use category-specific merge rules when updating files:
|
|
@@ -643,7 +643,7 @@ ${wE(m)}`)}return lt(e,"memory.after_recall",{sessionId:o,turnId:i,blockCount:l?
|
|
|
643
643
|
|
|
644
644
|
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 jo(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=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){n(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){n(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())n(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,r.def??r.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:Ws(e,"input",t.processors),output:Ws(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ut(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Ut(n.element,r);if(n.type==="set")return Ut(n.valueType,r);if(n.type==="lazy")return Ut(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Ut(n.innerType,r);if(n.type==="intersection")return Ut(n.left,r)||Ut(n.right,r);if(n.type==="record"||n.type==="map")return Ut(n.keyType,r)||Ut(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Ut(n.in,r)||Ut(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Ut(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Ut(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Ut(o,r))return!0;return!!(n.rest&&Ut(n.rest,r))}return!1}var oS=(t,e={})=>r=>{let n=No({...r,processors:e});return me(t,n),Oo(n,t),jo(n,t)},Ws=(t,e,r={})=>n=>{let{libraryOptions:o,target:i}=n??{},s=No({...o??{},target:i,io:e,processors:r});return me(t,s),Oo(s,t),jo(s,t)};var XX={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},iS=(t,e,r,n)=>{let o=r;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=XX[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}))])}},sS=(t,e,r,n)=>{let o=r,{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)},aS=(t,e,r,n)=>{r.type="boolean"},cS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},lS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},dS=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},uS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},pS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},mS=(t,e,r,n)=>{r.not={}},fS=(t,e,r,n)=>{},gS=(t,e,r,n)=>{},hS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},yS=(t,e,r,n)=>{let o=t._zod.def,i=kc(o.entries);i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},vS=(t,e,r,n)=>{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];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i},bS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},kS=(t,e,r,n)=>{let o=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},wS=(t,e,r,n)=>{let o=r,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)},SS=(t,e,r,n)=>{r.type="boolean"},xS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},RS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},TS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},PS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},AS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},IS=(t,e,r,n)=>{let o=r,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=me(i.element,e,{...n,path:[...n.path,"items"]})},CS=(t,e,r,n)=>{let o=r,i=t._zod.def;o.type="object",o.properties={};let s=i.shape;for(let l in s)o.properties[l]=me(s[l],e,{...n,path:[...n.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=me(i.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},rp=(t,e,r,n)=>{let o=t._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>me(a,e,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},_S=(t,e,r,n)=>{let o=t._zod.def,i=me(o.left,e,{...n,path:[...n.path,"allOf",0]}),s=me(o.right,e,{...n,path:[...n.path,"allOf",1]}),a=l=>"allOf"in l&&Object.keys(l).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c},ES=(t,e,r,n)=>{let o=r,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)=>me(m,e,{...n,path:[...n.path,s,f]})),l=i.rest?me(i.rest,e,{...n,path:[...n.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)},MS=(t,e,r,n)=>{let o=r,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=me(i.valueType,e,{...n,path:[...n.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=me(i.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=me(i.valueType,e,{...n,path:[...n.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)}},$S=(t,e,r,n)=>{let o=t._zod.def,i=me(o.innerType,e,n),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},DS=(t,e,r,n)=>{let o=t._zod.def;me(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},NS=(t,e,r,n)=>{let o=t._zod.def;me(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},OS=(t,e,r,n)=>{let o=t._zod.def;me(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},jS=(t,e,r,n)=>{let o=t._zod.def;me(o.innerType,e,n);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")}r.default=s},LS=(t,e,r,n)=>{let o=t._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?i?o.out:o.in:o.out;me(s,e,n);let a=e.seen.get(t);a.ref=s},US=(t,e,r,n)=>{let o=t._zod.def;me(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,r.readOnly=!0},FS=(t,e,r,n)=>{let o=t._zod.def;me(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},np=(t,e,r,n)=>{let o=t._zod.def;me(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},HS=(t,e,r,n)=>{let o=t._zod.innerType;me(o,e,n);let i=e.seen.get(t);i.ref=o},tp={string:iS,number:sS,boolean:aS,bigint:cS,symbol:lS,null:dS,undefined:uS,void:pS,never:mS,any:fS,unknown:gS,date:hS,enum:yS,literal:vS,nan:bS,template_literal:kS,file:wS,success:SS,custom:xS,function:RS,transform:TS,map:PS,set:AS,array:IS,object:CS,union:rp,intersection:_S,tuple:ES,record:MS,nullable:$S,nonoptional:DS,default:NS,prefault:OS,catch:jS,pipe:LS,readonly:US,promise:FS,optional:np,lazy:HS};function op(t,e){if("_idmap"in t){let n=t,o=No({...e,processors:tp}),i={};for(let c of n._idmap.entries()){let[l,d]=c;me(d,o)}let s={},a={registry:n,uri:e?.uri,defs:i};o.external=a;for(let c of n._idmap.entries()){let[l,d]=c;Oo(o,d),s[l]=jo(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 r=No({...e,processors:tp});return me(t,r),Oo(r,t),jo(r,t)}var ip=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 r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=No({processors:tp,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return me(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),Oo(this.ctx,e);let n=jo(this.ctx,e),{"~standard":o,...i}=n;return i}};var b$={};var Lc={};qt(Lc,{ZodAny:()=>ux,ZodArray:()=>gx,ZodBase64:()=>Pp,ZodBase64URL:()=>Ap,ZodBigInt:()=>Qs,ZodBigIntFormat:()=>_p,ZodBoolean:()=>Ys,ZodCIDRv4:()=>Rp,ZodCIDRv6:()=>Tp,ZodCUID:()=>yp,ZodCUID2:()=>vp,ZodCatch:()=>jx,ZodCodec:()=>Jc,ZodCustom:()=>Xc,ZodCustomStringFormat:()=>Js,ZodDate:()=>Wc,ZodDefault:()=>Ex,ZodDiscriminatedUnion:()=>yx,ZodE164:()=>Ip,ZodEmail:()=>fp,ZodEmoji:()=>gp,ZodEnum:()=>Vs,ZodExactOptional:()=>Ix,ZodFile:()=>Px,ZodFunction:()=>Gx,ZodGUID:()=>Fc,ZodIPv4:()=>Sp,ZodIPv6:()=>xp,ZodIntersection:()=>vx,ZodJWT:()=>Cp,ZodKSUID:()=>wp,ZodLazy:()=>qx,ZodLiteral:()=>Tx,ZodMAC:()=>ox,ZodMap:()=>xx,ZodNaN:()=>Ux,ZodNanoID:()=>hp,ZodNever:()=>mx,ZodNonOptional:()=>Op,ZodNull:()=>lx,ZodNullable:()=>_x,ZodNumber:()=>Xs,ZodNumberFormat:()=>_i,ZodObject:()=>Gc,ZodOptional:()=>Np,ZodPipe:()=>Zc,ZodPrefault:()=>$x,ZodPreprocess:()=>Fx,ZodPromise:()=>Kx,ZodReadonly:()=>Hx,ZodRecord:()=>Gs,ZodSet:()=>Rx,ZodString:()=>Zs,ZodStringFormat:()=>we,ZodSuccess:()=>Ox,ZodSymbol:()=>ax,ZodTemplateLiteral:()=>Bx,ZodTransform:()=>Ax,ZodTuple:()=>kx,ZodType:()=>ee,ZodULID:()=>bp,ZodURL:()=>qc,ZodUUID:()=>bn,ZodUndefined:()=>cx,ZodUnion:()=>Vc,ZodUnknown:()=>px,ZodVoid:()=>fx,ZodXID:()=>kp,ZodXor:()=>hx,_ZodString:()=>mp,_default:()=>Mx,_function:()=>ID,any:()=>iD,array:()=>Kc,base64:()=>z$,base64url:()=>B$,bigint:()=>eD,boolean:()=>sx,catch:()=>Lx,check:()=>CD,cidrv4:()=>F$,cidrv6:()=>H$,codec:()=>RD,cuid:()=>M$,cuid2:()=>$$,custom:()=>_D,date:()=>aD,describe:()=>ED,discriminatedUnion:()=>mD,e164:()=>q$,email:()=>S$,emoji:()=>_$,enum:()=>$p,exactOptional:()=>Cx,file:()=>kD,float32:()=>J$,float64:()=>X$,function:()=>ID,guid:()=>x$,hash:()=>Z$,hex:()=>V$,hostname:()=>G$,httpUrl:()=>C$,instanceof:()=>$D,int:()=>up,int32:()=>Y$,int64:()=>tD,intersection:()=>bx,invertCodec:()=>TD,ipv4:()=>j$,ipv6:()=>U$,json:()=>ND,jwt:()=>W$,keyof:()=>cD,ksuid:()=>O$,lazy:()=>Wx,literal:()=>bD,looseObject:()=>uD,looseRecord:()=>gD,mac:()=>L$,map:()=>hD,meta:()=>MD,nan:()=>xD,nanoid:()=>E$,nativeEnum:()=>vD,never:()=>Ep,nonoptional:()=>Nx,null:()=>dx,nullable:()=>zc,nullish:()=>wD,number:()=>ix,object:()=>lD,optional:()=>Hc,partialRecord:()=>fD,pipe:()=>pp,prefault:()=>Dx,preprocess:()=>OD,promise:()=>AD,readonly:()=>zx,record:()=>Sx,refine:()=>Vx,set:()=>yD,strictObject:()=>dD,string:()=>Uc,stringFormat:()=>K$,stringbool:()=>DD,success:()=>SD,superRefine:()=>Zx,symbol:()=>nD,templateLiteral:()=>PD,transform:()=>Dp,tuple:()=>wx,uint32:()=>Q$,uint64:()=>rD,ulid:()=>D$,undefined:()=>oD,union:()=>Mp,unknown:()=>Ci,url:()=>I$,uuid:()=>R$,uuidv4:()=>T$,uuidv6:()=>P$,uuidv7:()=>A$,void:()=>sD,xid:()=>N$,xor:()=>pD});var sp={};qt(sp,{endsWith:()=>js,gt:()=>yn,gte:()=>Lt,includes:()=>Ns,length:()=>Ii,lowercase:()=>$s,lt:()=>hn,lte:()=>fr,maxLength:()=>Ai,maxSize:()=>Do,mime:()=>Ls,minLength:()=>Wn,minSize:()=>vn,multipleOf:()=>$o,negative:()=>Xu,nonnegative:()=>Qu,nonpositive:()=>Yu,normalize:()=>Us,overwrite:()=>Vr,positive:()=>Ju,property:()=>ep,regex:()=>Ms,size:()=>Pi,slugify:()=>Bs,startsWith:()=>Os,toLowerCase:()=>Hs,toUpperCase:()=>zs,trim:()=>Fs,uppercase:()=>Ds});var Ks={};qt(Ks,{ZodISODate:()=>cp,ZodISODateTime:()=>ap,ZodISODuration:()=>dp,ZodISOTime:()=>lp,date:()=>BS,datetime:()=>zS,duration:()=>WS,time:()=>qS});var ap=x("ZodISODateTime",(t,e)=>{bk.init(t,e),we.init(t,e)});function zS(t){return xw(ap,t)}var cp=x("ZodISODate",(t,e)=>{kk.init(t,e),we.init(t,e)});function BS(t){return Rw(cp,t)}var lp=x("ZodISOTime",(t,e)=>{wk.init(t,e),we.init(t,e)});function qS(t){return Tw(lp,t)}var dp=x("ZodISODuration",(t,e)=>{Sk.init(t,e),we.init(t,e)});function WS(t){return Pw(dp,t)}var k$=(t,e)=>{Tc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Ac(t,r)},flatten:{value:r=>Pc(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,xs,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,xs,2)}},isEmpty:{get(){return t.issues.length===0}}})},QX=x("ZodError",k$),Jt=x("ZodError",k$,{Parent:Error});var KS=Ps(Jt),GS=As(Jt),VS=Is(Jt),ZS=Cs(Jt),JS=ou(Jt),XS=iu(Jt),YS=su(Jt),QS=au(Jt),ex=cu(Jt),tx=lu(Jt),rx=du(Jt),nx=uu(Jt);var w$=new WeakMap;function Bc(t,e,r){let n=Object.getPrototypeOf(t),o=w$.get(n);if(o||(o=new Set,w$.set(n,o)),!o.has(e)){o.add(e);for(let i in r){let s=r[i];Object.defineProperty(n,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 ee=x("ZodType",(t,e)=>(X.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:Ws(t,"input"),output:Ws(t,"output")}}),t.toJSONSchema=oS(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>KS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>VS(t,r,n),t.parseAsync=async(r,n)=>GS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>ZS(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>JS(t,r,n),t.decode=(r,n)=>XS(t,r,n),t.encodeAsync=async(r,n)=>YS(t,r,n),t.decodeAsync=async(r,n)=>QS(t,r,n),t.safeEncode=(r,n)=>ex(t,r,n),t.safeDecode=(r,n)=>tx(t,r,n),t.safeEncodeAsync=async(r,n)=>rx(t,r,n),t.safeDecodeAsync=async(r,n)=>nx(t,r,n),Bc(t,"ZodType",{check(...r){let n=this.def;return this.clone(N.mergeDefs(n,{checks:[...n.checks??[],...r.map(o=>typeof o=="function"?{_zod:{check:o,def:{check:"custom"},onattach:[]}}:o)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return Ot(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(Vx(r,n))},superRefine(r,n){return this.check(Zx(r,n))},overwrite(r){return this.check(Vr(r))},optional(){return Hc(this)},exactOptional(){return Cx(this)},nullable(){return zc(this)},nullish(){return Hc(zc(this))},nonoptional(r){return Nx(this,r)},array(){return Kc(this)},or(r){return Mp([this,r])},and(r){return bx(this,r)},transform(r){return pp(this,Dp(r))},default(r){return Mx(this,r)},prefault(r){return Dx(this,r)},catch(r){return Lx(this,r)},pipe(r){return pp(this,r)},readonly(){return zx(this)},describe(r){let n=this.clone();return bt.add(n,{description:r}),n},meta(...r){if(r.length===0)return bt.get(this);let n=this.clone();return bt.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return bt.get(t)?.description},configurable:!0}),t)),mp=x("_ZodString",(t,e)=>{Ti.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,o,i)=>iS(t,n,o,i);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,Bc(t,"_ZodString",{regex(...n){return this.check(Ms(...n))},includes(...n){return this.check(Ns(...n))},startsWith(...n){return this.check(Os(...n))},endsWith(...n){return this.check(js(...n))},min(...n){return this.check(Wn(...n))},max(...n){return this.check(Ai(...n))},length(...n){return this.check(Ii(...n))},nonempty(...n){return this.check(Wn(1,...n))},lowercase(n){return this.check($s(n))},uppercase(n){return this.check(Ds(n))},trim(){return this.check(Fs())},normalize(...n){return this.check(Us(...n))},toLowerCase(){return this.check(Hs())},toUpperCase(){return this.check(zs())},slugify(){return this.check(Bs())}})}),Zs=x("ZodString",(t,e)=>{Ti.init(t,e),mp.init(t,e),t.email=r=>t.check(_u(fp,r)),t.url=r=>t.check(jc(qc,r)),t.jwt=r=>t.check(Zu(Cp,r)),t.emoji=r=>t.check(Nu(gp,r)),t.guid=r=>t.check(Oc(Fc,r)),t.uuid=r=>t.check(Eu(bn,r)),t.uuidv4=r=>t.check(Mu(bn,r)),t.uuidv6=r=>t.check($u(bn,r)),t.uuidv7=r=>t.check(Du(bn,r)),t.nanoid=r=>t.check(Ou(hp,r)),t.guid=r=>t.check(Oc(Fc,r)),t.cuid=r=>t.check(ju(yp,r)),t.cuid2=r=>t.check(Lu(vp,r)),t.ulid=r=>t.check(Uu(bp,r)),t.base64=r=>t.check(Ku(Pp,r)),t.base64url=r=>t.check(Gu(Ap,r)),t.xid=r=>t.check(Fu(kp,r)),t.ksuid=r=>t.check(Hu(wp,r)),t.ipv4=r=>t.check(zu(Sp,r)),t.ipv6=r=>t.check(Bu(xp,r)),t.cidrv4=r=>t.check(qu(Rp,r)),t.cidrv6=r=>t.check(Wu(Tp,r)),t.e164=r=>t.check(Vu(Ip,r)),t.datetime=r=>t.check(zS(r)),t.date=r=>t.check(BS(r)),t.time=r=>t.check(qS(r)),t.duration=r=>t.check(WS(r))});function Uc(t){return bw(Zs,t)}var we=x("ZodStringFormat",(t,e)=>{ke.init(t,e),mp.init(t,e)}),fp=x("ZodEmail",(t,e)=>{dk.init(t,e),we.init(t,e)});function S$(t){return _u(fp,t)}var Fc=x("ZodGUID",(t,e)=>{ck.init(t,e),we.init(t,e)});function x$(t){return Oc(Fc,t)}var bn=x("ZodUUID",(t,e)=>{lk.init(t,e),we.init(t,e)});function R$(t){return Eu(bn,t)}function T$(t){return Mu(bn,t)}function P$(t){return $u(bn,t)}function A$(t){return Du(bn,t)}var qc=x("ZodURL",(t,e)=>{uk.init(t,e),we.init(t,e)});function I$(t){return jc(qc,t)}function C$(t){return jc(qc,{protocol:mr.httpProtocol,hostname:mr.domain,...N.normalizeParams(t)})}var gp=x("ZodEmoji",(t,e)=>{pk.init(t,e),we.init(t,e)});function _$(t){return Nu(gp,t)}var hp=x("ZodNanoID",(t,e)=>{mk.init(t,e),we.init(t,e)});function E$(t){return Ou(hp,t)}var yp=x("ZodCUID",(t,e)=>{fk.init(t,e),we.init(t,e)});function M$(t){return ju(yp,t)}var vp=x("ZodCUID2",(t,e)=>{gk.init(t,e),we.init(t,e)});function $$(t){return Lu(vp,t)}var bp=x("ZodULID",(t,e)=>{hk.init(t,e),we.init(t,e)});function D$(t){return Uu(bp,t)}var kp=x("ZodXID",(t,e)=>{yk.init(t,e),we.init(t,e)});function N$(t){return Fu(kp,t)}var wp=x("ZodKSUID",(t,e)=>{vk.init(t,e),we.init(t,e)});function O$(t){return Hu(wp,t)}var Sp=x("ZodIPv4",(t,e)=>{xk.init(t,e),we.init(t,e)});function j$(t){return zu(Sp,t)}var ox=x("ZodMAC",(t,e)=>{Tk.init(t,e),we.init(t,e)});function L$(t){return ww(ox,t)}var xp=x("ZodIPv6",(t,e)=>{Rk.init(t,e),we.init(t,e)});function U$(t){return Bu(xp,t)}var Rp=x("ZodCIDRv4",(t,e)=>{Pk.init(t,e),we.init(t,e)});function F$(t){return qu(Rp,t)}var Tp=x("ZodCIDRv6",(t,e)=>{Ak.init(t,e),we.init(t,e)});function H$(t){return Wu(Tp,t)}var Pp=x("ZodBase64",(t,e)=>{Ck.init(t,e),we.init(t,e)});function z$(t){return Ku(Pp,t)}var Ap=x("ZodBase64URL",(t,e)=>{_k.init(t,e),we.init(t,e)});function B$(t){return Gu(Ap,t)}var Ip=x("ZodE164",(t,e)=>{Ek.init(t,e),we.init(t,e)});function q$(t){return Vu(Ip,t)}var Cp=x("ZodJWT",(t,e)=>{Mk.init(t,e),we.init(t,e)});function W$(t){return Zu(Cp,t)}var Js=x("ZodCustomStringFormat",(t,e)=>{$k.init(t,e),we.init(t,e)});function K$(t,e,r={}){return qs(Js,t,e,r)}function G$(t){return qs(Js,"hostname",mr.hostname,t)}function V$(t){return qs(Js,"hex",mr.hex,t)}function Z$(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,o=mr[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return qs(Js,n,o,e)}var Xs=x("ZodNumber",(t,e)=>{ku.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,o,i)=>sS(t,n,o,i),Bc(t,"ZodNumber",{gt(n,o){return this.check(yn(n,o))},gte(n,o){return this.check(Lt(n,o))},min(n,o){return this.check(Lt(n,o))},lt(n,o){return this.check(hn(n,o))},lte(n,o){return this.check(fr(n,o))},max(n,o){return this.check(fr(n,o))},int(n){return this.check(up(n))},safe(n){return this.check(up(n))},positive(n){return this.check(yn(0,n))},nonnegative(n){return this.check(Lt(0,n))},negative(n){return this.check(hn(0,n))},nonpositive(n){return this.check(fr(0,n))},multipleOf(n,o){return this.check($o(n,o))},step(n,o){return this.check($o(n,o))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ix(t){return Aw(Xs,t)}var _i=x("ZodNumberFormat",(t,e)=>{Dk.init(t,e),Xs.init(t,e)});function up(t){return Cw(_i,t)}function J$(t){return _w(_i,t)}function X$(t){return Ew(_i,t)}function Y$(t){return Mw(_i,t)}function Q$(t){return $w(_i,t)}var Ys=x("ZodBoolean",(t,e)=>{Ec.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>aS(t,r,n,o)});function sx(t){return Dw(Ys,t)}var Qs=x("ZodBigInt",(t,e)=>{wu.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,o,i)=>cS(t,n,o,i),t.gte=(n,o)=>t.check(Lt(n,o)),t.min=(n,o)=>t.check(Lt(n,o)),t.gt=(n,o)=>t.check(yn(n,o)),t.gte=(n,o)=>t.check(Lt(n,o)),t.min=(n,o)=>t.check(Lt(n,o)),t.lt=(n,o)=>t.check(hn(n,o)),t.lte=(n,o)=>t.check(fr(n,o)),t.max=(n,o)=>t.check(fr(n,o)),t.positive=n=>t.check(yn(BigInt(0),n)),t.negative=n=>t.check(hn(BigInt(0),n)),t.nonpositive=n=>t.check(fr(BigInt(0),n)),t.nonnegative=n=>t.check(Lt(BigInt(0),n)),t.multipleOf=(n,o)=>t.check($o(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function eD(t){return Ow(Qs,t)}var _p=x("ZodBigIntFormat",(t,e)=>{Nk.init(t,e),Qs.init(t,e)});function tD(t){return Lw(_p,t)}function rD(t){return Uw(_p,t)}var ax=x("ZodSymbol",(t,e)=>{Ok.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>lS(t,r,n,o)});function nD(t){return Fw(ax,t)}var cx=x("ZodUndefined",(t,e)=>{jk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>uS(t,r,n,o)});function oD(t){return Hw(cx,t)}var lx=x("ZodNull",(t,e)=>{Lk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>dS(t,r,n,o)});function dx(t){return zw(lx,t)}var ux=x("ZodAny",(t,e)=>{Uk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>fS(t,r,n,o)});function iD(){return Bw(ux)}var px=x("ZodUnknown",(t,e)=>{Fk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>gS(t,r,n,o)});function Ci(){return qw(px)}var mx=x("ZodNever",(t,e)=>{Hk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>mS(t,r,n,o)});function Ep(t){return Ww(mx,t)}var fx=x("ZodVoid",(t,e)=>{zk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>pS(t,r,n,o)});function sD(t){return Kw(fx,t)}var Wc=x("ZodDate",(t,e)=>{Bk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,o,i)=>hS(t,n,o,i),t.min=(n,o)=>t.check(Lt(n,o)),t.max=(n,o)=>t.check(fr(n,o));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function aD(t){return Gw(Wc,t)}var gx=x("ZodArray",(t,e)=>{qk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>IS(t,r,n,o),t.element=e.element,Bc(t,"ZodArray",{min(r,n){return this.check(Wn(r,n))},nonempty(r){return this.check(Wn(1,r))},max(r,n){return this.check(Ai(r,n))},length(r,n){return this.check(Ii(r,n))},unwrap(){return this.element}})});function Kc(t,e){return Jw(gx,t,e)}function cD(t){let e=t._zod.def.shape;return $p(Object.keys(e))}var Gc=x("ZodObject",(t,e)=>{Wk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>CS(t,r,n,o),N.defineLazy(t,"shape",()=>e.shape),Bc(t,"ZodObject",{keyof(){return $p(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Ci()})},loose(){return this.clone({...this._zod.def,catchall:Ci()})},strict(){return this.clone({...this._zod.def,catchall:Ep()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return N.extend(this,r)},safeExtend(r){return N.safeExtend(this,r)},merge(r){return N.merge(this,r)},pick(r){return N.pick(this,r)},omit(r){return N.omit(this,r)},partial(...r){return N.partial(Np,this,r[0])},required(...r){return N.required(Op,this,r[0])}})});function lD(t,e){let r={type:"object",shape:t??{},...N.normalizeParams(e)};return new Gc(r)}function dD(t,e){return new Gc({type:"object",shape:t,catchall:Ep(),...N.normalizeParams(e)})}function uD(t,e){return new Gc({type:"object",shape:t,catchall:Ci(),...N.normalizeParams(e)})}var Vc=x("ZodUnion",(t,e)=>{Mc.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>rp(t,r,n,o),t.options=e.options});function Mp(t,e){return new Vc({type:"union",options:t,...N.normalizeParams(e)})}var hx=x("ZodXor",(t,e)=>{Vc.init(t,e),Kk.init(t,e),t._zod.processJSONSchema=(r,n,o)=>rp(t,r,n,o),t.options=e.options});function pD(t,e){return new hx({type:"union",options:t,inclusive:!1,...N.normalizeParams(e)})}var yx=x("ZodDiscriminatedUnion",(t,e)=>{Vc.init(t,e),Gk.init(t,e)});function mD(t,e,r){return new yx({type:"union",options:e,discriminator:t,...N.normalizeParams(r)})}var vx=x("ZodIntersection",(t,e)=>{Vk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>_S(t,r,n,o)});function bx(t,e){return new vx({type:"intersection",left:t,right:e})}var kx=x("ZodTuple",(t,e)=>{Su.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ES(t,r,n,o),t.rest=r=>t.clone({...t._zod.def,rest:r})});function wx(t,e,r){let n=e instanceof X,o=n?r:e,i=n?e:null;return new kx({type:"tuple",items:t,rest:i,...N.normalizeParams(o)})}var Gs=x("ZodRecord",(t,e)=>{Zk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>MS(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function Sx(t,e,r){return!e||!e._zod?new Gs({type:"record",keyType:Uc(),valueType:t,...N.normalizeParams(e)}):new Gs({type:"record",keyType:t,valueType:e,...N.normalizeParams(r)})}function fD(t,e,r){let n=Ot(t);return n._zod.values=void 0,new Gs({type:"record",keyType:n,valueType:e,...N.normalizeParams(r)})}function gD(t,e,r){return new Gs({type:"record",keyType:t,valueType:e,mode:"loose",...N.normalizeParams(r)})}var xx=x("ZodMap",(t,e)=>{Jk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>PS(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(vn(...r)),t.nonempty=r=>t.check(vn(1,r)),t.max=(...r)=>t.check(Do(...r)),t.size=(...r)=>t.check(Pi(...r))});function hD(t,e,r){return new xx({type:"map",keyType:t,valueType:e,...N.normalizeParams(r)})}var Rx=x("ZodSet",(t,e)=>{Xk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>AS(t,r,n,o),t.min=(...r)=>t.check(vn(...r)),t.nonempty=r=>t.check(vn(1,r)),t.max=(...r)=>t.check(Do(...r)),t.size=(...r)=>t.check(Pi(...r))});function yD(t,e){return new Rx({type:"set",valueType:t,...N.normalizeParams(e)})}var Vs=x("ZodEnum",(t,e)=>{Yk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,o,i)=>yS(t,n,o,i),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Vs({...e,checks:[],...N.normalizeParams(o),entries:i})},t.exclude=(n,o)=>{let i={...e.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Vs({...e,checks:[],...N.normalizeParams(o),entries:i})}});function $p(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Vs({type:"enum",entries:r,...N.normalizeParams(e)})}function vD(t,e){return new Vs({type:"enum",entries:t,...N.normalizeParams(e)})}var Tx=x("ZodLiteral",(t,e)=>{Qk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vS(t,r,n,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 bD(t,e){return new Tx({type:"literal",values:Array.isArray(t)?t:[t],...N.normalizeParams(e)})}var Px=x("ZodFile",(t,e)=>{ew.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>wS(t,r,n,o),t.min=(r,n)=>t.check(vn(r,n)),t.max=(r,n)=>t.check(Do(r,n)),t.mime=(r,n)=>t.check(Ls(Array.isArray(r)?r:[r],n))});function kD(t){return Xw(Px,t)}var Ax=x("ZodTransform",(t,e)=>{tw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>TS(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Io(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(N.issue(i,r.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=t),r.issues.push(N.issue(s))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r.fallback=!0,r)):(r.value=o,r.fallback=!0,r)}});function Dp(t){return new Ax({type:"transform",transform:t})}var Np=x("ZodOptional",(t,e)=>{xu.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>np(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Hc(t){return new Np({type:"optional",innerType:t})}var Ix=x("ZodExactOptional",(t,e)=>{rw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>np(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Cx(t){return new Ix({type:"optional",innerType:t})}var _x=x("ZodNullable",(t,e)=>{nw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>$S(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function zc(t){return new _x({type:"nullable",innerType:t})}function wD(t){return Hc(zc(t))}var Ex=x("ZodDefault",(t,e)=>{ow.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>NS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Mx(t,e){return new Ex({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():N.shallowClone(e)}})}var $x=x("ZodPrefault",(t,e)=>{iw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>OS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Dx(t,e){return new $x({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():N.shallowClone(e)}})}var Op=x("ZodNonOptional",(t,e)=>{sw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>DS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Nx(t,e){return new Op({type:"nonoptional",innerType:t,...N.normalizeParams(e)})}var Ox=x("ZodSuccess",(t,e)=>{aw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>SS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function SD(t){return new Ox({type:"success",innerType:t})}var jx=x("ZodCatch",(t,e)=>{cw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>jS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Lx(t,e){return new jx({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var Ux=x("ZodNaN",(t,e)=>{lw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>bS(t,r,n,o)});function xD(t){return Zw(Ux,t)}var Zc=x("ZodPipe",(t,e)=>{Ru.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>LS(t,r,n,o),t.in=e.in,t.out=e.out});function pp(t,e){return new Zc({type:"pipe",in:t,out:e})}var Jc=x("ZodCodec",(t,e)=>{Zc.init(t,e),$c.init(t,e)});function RD(t,e,r){return new Jc({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function TD(t){let e=t._zod.def;return new Jc({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var Fx=x("ZodPreprocess",(t,e)=>{Zc.init(t,e),dw.init(t,e)}),Hx=x("ZodReadonly",(t,e)=>{uw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>US(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function zx(t){return new Hx({type:"readonly",innerType:t})}var Bx=x("ZodTemplateLiteral",(t,e)=>{pw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>kS(t,r,n,o)});function PD(t,e){return new Bx({type:"template_literal",parts:t,...N.normalizeParams(e)})}var qx=x("ZodLazy",(t,e)=>{gw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>HS(t,r,n,o),t.unwrap=()=>t._zod.def.getter()});function Wx(t){return new qx({type:"lazy",getter:t})}var Kx=x("ZodPromise",(t,e)=>{fw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>FS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function AD(t){return new Kx({type:"promise",innerType:t})}var Gx=x("ZodFunction",(t,e)=>{mw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>RS(t,r,n,o)});function ID(t){return new Gx({type:"function",input:Array.isArray(t?.input)?wx(t?.input):t?.input??Kc(Ci()),output:t?.output??Ci()})}var Xc=x("ZodCustom",(t,e)=>{hw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>xS(t,r,n,o)});function CD(t){let e=new xe({check:"custom"});return e._zod.check=t,e}function _D(t,e){return Yw(Xc,t??(()=>!0),e)}function Vx(t,e={}){return Qw(Xc,t,e)}function Zx(t,e){return eS(t,e)}var ED=tS,MD=rS;function $D(t,e={}){let r=new Xc({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...N.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=n=>{n.value instanceof t||n.issues.push({code:"invalid_type",expected:t.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var DD=(...t)=>nS({Codec:Jc,Boolean:Ys,String:Zs},...t);function ND(t){let e=Wx(()=>Mp([Uc(t),ix(),sx(),dx(),Kc(e),Sx(Uc(),e)]));return e}function OD(t,e){return new Fx({type:"pipe",in:Dp(t),out:e})}var tY={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 rY(t){Fe({customError:t})}function nY(){return Fe().customError}var Jx;Jx||(Jx={});var H={...Lc,...sp,iso:Ks},oY=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 iY(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function sY(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let n=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===n){let o=r[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 jD(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return H.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 H.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=sY(o,e),s=It(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 H.null();if(o.length===0)return H.never();if(o.length===1)return H.literal(o[0]);if(o.every(s=>typeof s=="string"))return H.enum(o);let i=o.map(s=>H.literal(s));return i.length<2?i[0]:H.union([i[0],i[1],...i.slice(2)])}if(t.const!==void 0)return H.literal(t.const);let r=t.type;if(Array.isArray(r)){let o=r.map(i=>{let s={...t,type:i};return jD(s,e)});return o.length===0?H.never():o.length===1?o[0]:H.union(o)}if(!r)return H.any();let n;switch(r){case"string":{let o=H.string();if(t.format){let i=t.format;i==="email"?o=o.check(H.email()):i==="uri"||i==="uri-reference"?o=o.check(H.url()):i==="uuid"||i==="guid"?o=o.check(H.uuid()):i==="date-time"?o=o.check(H.iso.datetime()):i==="date"?o=o.check(H.iso.date()):i==="time"?o=o.check(H.iso.time()):i==="duration"?o=o.check(H.iso.duration()):i==="ipv4"?o=o.check(H.ipv4()):i==="ipv6"?o=o.check(H.ipv6()):i==="mac"?o=o.check(H.mac()):i==="cidr"?o=o.check(H.cidrv4()):i==="cidr-v6"?o=o.check(H.cidrv6()):i==="base64"?o=o.check(H.base64()):i==="base64url"?o=o.check(H.base64url()):i==="e164"?o=o.check(H.e164()):i==="jwt"?o=o.check(H.jwt()):i==="emoji"?o=o.check(H.emoji()):i==="nanoid"?o=o.check(H.nanoid()):i==="cuid"?o=o.check(H.cuid()):i==="cuid2"?o=o.check(H.cuid2()):i==="ulid"?o=o.check(H.ulid()):i==="xid"?o=o.check(H.xid()):i==="ksuid"&&(o=o.check(H.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))),n=o;break}case"number":case"integer":{let o=r==="integer"?H.number().int():H.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)),n=o;break}case"boolean":{n=H.boolean();break}case"null":{n=H.null();break}case"object":{let o={},i=t.properties||{},s=new Set(t.required||[]);for(let[c,l]of Object.entries(i)){let d=It(l,e);o[c]=s.has(c)?d:d.optional()}if(t.propertyNames){let c=It(t.propertyNames,e),l=t.additionalProperties&&typeof t.additionalProperties=="object"?It(t.additionalProperties,e):H.any();if(Object.keys(o).length===0){n=H.record(c,l);break}let d=H.object(o).passthrough(),p=H.looseRecord(c,l);n=H.intersection(d,p);break}if(t.patternProperties){let c=t.patternProperties,l=Object.keys(c),d=[];for(let m of l){let f=It(c[m],e),g=H.string().regex(new RegExp(m));d.push(H.looseRecord(g,f))}let p=[];if(Object.keys(o).length>0&&p.push(H.object(o).passthrough()),p.push(...d),p.length===0)n=H.object({}).passthrough();else if(p.length===1)n=p[0];else{let m=H.intersection(p[0],p[1]);for(let f=2;f<p.length;f++)m=H.intersection(m,p[f]);n=m}break}let a=H.object(o);t.additionalProperties===!1?n=a.strict():typeof t.additionalProperties=="object"?n=a.catchall(It(t.additionalProperties,e)):n=a.passthrough();break}case"array":{let o=t.prefixItems,i=t.items;if(o&&Array.isArray(o)){let s=o.map(c=>It(c,e)),a=i&&typeof i=="object"&&!Array.isArray(i)?It(i,e):void 0;a?n=H.tuple(s).rest(a):n=H.tuple(s),typeof t.minItems=="number"&&(n=n.check(H.minLength(t.minItems))),typeof t.maxItems=="number"&&(n=n.check(H.maxLength(t.maxItems)))}else if(Array.isArray(i)){let s=i.map(c=>It(c,e)),a=t.additionalItems&&typeof t.additionalItems=="object"?It(t.additionalItems,e):void 0;a?n=H.tuple(s).rest(a):n=H.tuple(s),typeof t.minItems=="number"&&(n=n.check(H.minLength(t.minItems))),typeof t.maxItems=="number"&&(n=n.check(H.maxLength(t.maxItems)))}else if(i!==void 0){let s=It(i,e),a=H.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),n=a}else n=H.array(H.any());break}default:throw new Error(`Unsupported type: ${r}`)}return n}function It(t,e){if(typeof t=="boolean")return t?H.any():H.never();let r=jD(t,e),n=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(l=>It(l,e)),c=H.union(a);r=n?H.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(l=>It(l,e)),c=H.xor(a);r=n?H.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=n?r:H.any();else{let a=n?r:It(t.allOf[0],e),c=n?0:1;for(let l=c;l<t.allOf.length;l++)a=H.intersection(a,It(t.allOf[l],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=H.nullable(r)),t.readOnly===!0&&(r=H.readonly(r)),t.default!==void 0&&(r=r.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))oY.has(a)||(o[a]=t[a]);return Object.keys(o).length>0&&e.registry.add(r,o),t.description&&(r=r.describe(t.description)),r}function LD(t,e){if(typeof t=="boolean")return t?H.any():H.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let n=iY(r,e?.defaultTarget),o=r.$defs||r.definitions||{},i={version:n,defs:o,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??bt};return It(r,i)}var Xx={};qt(Xx,{bigint:()=>dY,boolean:()=>lY,date:()=>uY,number:()=>cY,string:()=>aY});function aY(t){return kw(Zs,t)}function cY(t){return Iw(Xs,t)}function lY(t){return Nw(Ys,t)}function dY(t){return jw(Qs,t)}function uY(t){return Vw(Wc,t)}Fe(Tu());var Se={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"},Mr={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 UD=Symbol("skippedItem");function F(t,e){return t.catch(e)}function Zr(t,e){let r=t.catch(e);return u.unknown().transform((n,o)=>n!==void 0?r.parse(n):(o.addIssue({code:"custom",message:"Required value is missing"}),u.NEVER))}function ye(t){return u.array(t.catch(UD)).transform(e=>e.filter(r=>r!==UD))}var mY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminal:u.boolean().optional().default(!1)}),fY=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)}),gY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:u.string(),name:u.string()}),hY=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(fY)}),yY=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()}),vY=u.union([hY.and(u.object({type:u.literal("env_var")})),yY.and(u.object({type:u.literal("terminal")})),gY]),FD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),methodId:u.string()}),bY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),kY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),blob:u.string(),mimeType:u.string().nullish(),uri:u.string()}),wY=u.object({default:u.boolean().nullish(),description:u.string().nullish(),title:u.string().nullish()}),SY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),RY=u.object({amount:u.number(),currency:u.string()}),TY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),PY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),AY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),newText:u.string(),oldText:u.string().nullish(),path:u.string()}),HD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string()}),IY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),CY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),_Y=u.union([u.string(),u.number(),u.number(),u.boolean(),u.array(u.string())]),EY=u.object({content:u.record(u.string(),_Y).nullish()}),MY=u.intersection(u.union([EY.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()})),$Y=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),zD=u.string(),Qx=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),elicitationId:zD}),DY=u.literal("object"),NY=u.literal("string"),OY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),jY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),form:F($Y.nullish(),()=>{}),url:F(OY.nullish(),()=>{})}),BD=u.object({const:u.string(),title:u.string()}),qD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),LY=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"})]),WD=u.object({code:LY,data:u.unknown().optional(),message:u.string()}),KD=u.unknown(),GD=u.unknown(),VD=u.unknown(),UY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),readTextFile:u.boolean().optional().default(!1),writeTextFile:u.boolean().optional().default(!1)}),ZD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),JD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),title:u.string().nullish(),version:u.string()}),FY=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),HY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),XD=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),YD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cursor:u.string().nullish(),cwd:u.string().nullish()}),eR=u.union([u.literal("anthropic"),u.literal("openai"),u.literal("azure"),u.literal("vertex"),u.literal("bedrock"),u.string()]),zY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),BY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),logout:F(zY.nullish(),()=>{})}),QD=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),qY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),WY=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)}),jp=u.string(),KY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:jp}),GY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:jp}),e0=u.string(),VY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),acpId:e0}),ZY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:e0,name:u.string()}),JY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(ZD),name:u.string(),url:u.string()}),XY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(ZD),name:u.string(),url:u.string()}),YY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),args:u.array(u.string()),command:u.string(),env:u.array(qD),name:u.string()}),Lp=u.union([JY.and(u.object({type:u.literal("http")})),XY.and(u.object({type:u.literal("sse")})),ZY.and(u.object({type:u.literal("acp")})),YY]),QY=u.string(),t0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:jp,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),r0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:jp,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),n0=u.unknown(),e9=u.union([u.literal("error"),u.literal("warning"),u.literal("information"),u.literal("hint")]),t9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),r9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),n9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),o9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),i9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),s9=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()}),a9=u.object({diff:u.string(),uri:u.string()}),c9=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()}),l9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),d9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),u9=u.object({languageId:u.string(),text:u.string(),uri:u.string()}),p9=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()}),m9=u.union([u.literal("rejected"),u.literal("ignored"),u.literal("replaced"),u.literal("cancelled")]),f9=u.object({excerpts:u.array(c9),uri:u.string()}),g9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),h9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),y9=u.object({name:u.string(),owner:u.string(),remoteUrl:u.string()}),v9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),b9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),jump:F(l9.nullish(),()=>{}),rename:F(h9.nullish(),()=>{}),searchAndReplace:F(v9.nullish(),()=>{})}),k9=u.object({id:u.string(),isRegex:u.boolean().nullish(),replace:u.string(),search:u.string(),uri:u.string()}),w9=u.union([u.literal("automatic"),u.literal("diagnostic"),u.literal("manual")]),S9=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()}),x9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:F(t9.nullish(),()=>{}),editHistory:F(s9.nullish(),()=>{}),openFiles:F(d9.nullish(),()=>{}),recentFiles:F(p9.nullish(),()=>{}),relatedSnippets:F(g9.nullish(),()=>{}),userActions:F(S9.nullish(),()=>{})}),o0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(Lp)}),R9=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),i0=u.string(),T9=u.union([u.literal("allow_once"),u.literal("allow_always"),u.literal("reject_once"),u.literal("reject_always")]),P9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),kind:T9,name:u.string(),optionId:i0}),A9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),I9=u.union([u.literal("high"),u.literal("medium"),u.literal("low")]),C9=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed")]),s0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),priority:I9,status:C9}),_9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:Zr(ye(s0),()=>[])}),Up=u.string(),E9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:Up,uri:u.string()}),M9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:Zr(ye(s0),()=>[]),id:Up}),$9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),id:Up}),D9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:Up}),N9=u.union([M9.and(u.object({type:u.literal("items")})),E9.and(u.object({type:u.literal("file")})),$9.and(u.object({type:u.literal("markdown")}))]),O9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),plan:N9}),Lo=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"})}),j9=u.object({id:u.string(),position:Lo,uri:u.string()}),L9=u.object({id:u.string(),newName:u.string(),position:Lo,uri:u.string()}),U9=u.object({action:u.string(),position:Lo,timestampMs:u.number(),uri:u.string()}),a0=u.union([u.literal("utf-16"),u.literal("utf-32"),u.literal("utf-8")]),F9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:mY.optional().default({terminal:!1}),elicitation:F(jY.nullish(),()=>{}),fs:UY.optional().default({readTextFile:!1,writeTextFile:!1}),nes:F(b9.nullish(),()=>{}),plan:F(A9.nullish(),()=>{}),positionEncodings:F(ye(a0).optional(),()=>[]),terminal:u.boolean().optional().default(!1)}),H9=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)}),c0=u.number().int().gte(0).lte(65535),l0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),clientCapabilities:F9.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:F(JD.nullish(),()=>{}),protocolVersion:c0}),z9=u.object({apiType:eR,baseUrl:u.string()}),B9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),current:z9.nullish(),id:u.string(),required:u.boolean(),supported:Zr(ye(eR),()=>[])}),q9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),providers:Zr(ye(B9),()=>[])}),W9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),ea=u.object({end:Lo,start:Lo}),K9=u.object({message:u.string(),range:ea,severity:e9,uri:u.string()}),G9=u.object({languageId:u.string(),lastFocusedMs:F(u.number().nullish(),()=>{}),uri:u.string(),visibleRange:F(ea.nullish(),()=>{})}),V9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:F(ye(K9).nullish(),()=>{}),editHistory:F(ye(a9).nullish(),()=>{}),openFiles:F(ye(G9).nullish(),()=>{}),recentFiles:F(ye(u9).nullish(),()=>{}),relatedSnippets:F(ye(f9).nullish(),()=>{}),userActions:F(ye(U9).nullish(),()=>{})}),Z9=u.object({newText:u.string(),range:ea}),J9=u.object({cursorPosition:F(Lo.nullish(),()=>{}),edits:u.array(Z9),id:u.string(),uri:u.string()}),X9=u.union([J9.and(u.object({kind:u.literal("edit")})),j9.and(u.object({kind:u.literal("jump")})),L9.and(u.object({kind:u.literal("rename")})),k9.and(u.object({kind:u.literal("searchAndReplace")}))]),Y9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string()}),Q9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Uo=u.union([u.number(),u.string()]).nullable(),VCe=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),requestId:Uo}),d0=u.object({requestId:Uo}),eQ=u.enum(["assistant","user"]),Yc=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),audience:F(ye(eQ).nullish(),()=>{}),lastModified:u.string().nullish(),priority:u.number().nullish()}),tQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:F(Yc.nullish(),()=>{}),data:u.string(),mimeType:u.string()}),rQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:F(Yc.nullish(),()=>{}),data:u.string(),mimeType:u.string(),uri:u.string().nullish()}),nQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:F(Yc.nullish(),()=>{}),description:u.string().nullish(),mimeType:u.string().nullish(),name:u.string(),size:u.number().nullish(),title:u.string().nullish(),uri:u.string()}),oQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),optionId:i0}),iQ=u.union([u.object({outcome:u.literal("cancelled")}),oQ.and(u.object({outcome:u.literal("selected")}))]),sQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),outcome:iQ}),aQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),cQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),lQ=u.object({currentValue:u.boolean()}),dQ=u.string(),u0=u.string(),uQ=u.union([u.literal("mode"),u.literal("model"),u.literal("thought_level"),u.string()]),tR=u.string(),p0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),name:u.string(),value:tR}),pQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),group:dQ,name:u.string(),options:u.array(p0)}),mQ=u.union([u.array(p0),u.array(pQ)]),fQ=u.object({currentValue:tR,options:mQ}),ta=u.intersection(u.union([fQ.and(u.object({type:u.literal("select")})),lQ.and(u.object({type:u.literal("boolean")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),category:F(uQ.nullish(),()=>{}),description:u.string().nullish(),id:u0,name:u.string()})),gQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:Zr(ye(ta),()=>[])}),hQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),yQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),ue=u.string(),m0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),sessionId:ue}),f0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue}),g0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue}),h0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue}),rR=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(qD).optional(),outputByteLimit:u.number().nullish(),sessionId:ue}),y0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue}),v0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,uri:u.string()}),b0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),position:Lo,sessionId:ue,uri:u.string(),version:u.number(),visibleRange:ea}),k0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),languageId:u.string(),sessionId:ue,text:u.string(),uri:u.string(),version:u.number()}),w0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,uri:u.string()}),S0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(Lp).optional(),sessionId:ue}),nR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,terminalId:u.string()}),x0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(Lp),sessionId:ue}),oR=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:ue}),R0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),reason:F(m9.nullish(),()=>{}),sessionId:ue}),iR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,terminalId:u.string()}),T0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(Lp).optional(),sessionId:ue}),vQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),sessionId:ue,title:F(u.string().nullish(),()=>{}),updatedAt:F(u.string().nullish(),()=>{})}),bQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),nextCursor:u.string().nullish(),sessions:Zr(ye(vQ),()=>[])}),kQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),title:u.string().nullish(),updatedAt:u.string().nullish()}),wQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Fp=u.string(),SQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),currentModeId:Fp}),xQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:Fp,name:u.string()}),Hp=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableModes:Zr(ye(xQ),()=>[]),currentModeId:Fp}),RQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:F(ye(ta).nullish(),()=>{}),modes:F(Hp.nullish(),()=>{}),sessionId:ue}),TQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:F(ye(ta).nullish(),()=>{}),modes:F(Hp.nullish(),()=>{})}),PQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:F(ye(ta).nullish(),()=>{}),modes:F(Hp.nullish(),()=>{}),sessionId:ue}),AQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:F(ye(ta).nullish(),()=>{}),modes:F(Hp.nullish(),()=>{})}),IQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),CQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:F(aQ.nullish(),()=>{}),close:F(cQ.nullish(),()=>{}),delete:F(hQ.nullish(),()=>{}),fork:F(yQ.nullish(),()=>{}),list:F(wQ.nullish(),()=>{}),resume:F(IQ.nullish(),()=>{})}),P0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),apiType:eR,baseUrl:u.string(),headers:u.record(u.string(),u.string()).optional(),id:u.string()}),_Q=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),A0=u.intersection(u.union([u.object({type:u.literal("boolean"),value:u.boolean()}),u.object({value:tR})]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configId:u0,sessionId:ue})),EQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:Zr(ye(ta),()=>[])}),I0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),modeId:Fp,sessionId:ue}),MQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),$Q=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue}),DQ=u.union([u.literal("end_turn"),u.literal("max_tokens"),u.literal("max_turn_requests"),u.literal("refusal"),u.literal("cancelled")]),NQ=u.union([u.literal("email"),u.literal("uri"),u.literal("date"),u.literal("date-time")]),OQ=u.object({default:u.string().nullish(),description:u.string().nullish(),enum:u.array(u.string()).nullish(),format:NQ.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(BD).nullish(),pattern:u.string().nullish(),title:u.string().nullish()}),C0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:F(V9.nullish(),()=>{}),position:Lo,selection:F(ea.nullish(),()=>{}),sessionId:ue,triggerKind:w9,uri:u.string(),version:u.number()}),jQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),suggestions:Zr(ye(X9),()=>[])}),LQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),UQ=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()}),sR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,terminalId:u.string()}),FQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),exitStatus:UQ.nullish(),output:u.string(),truncated:u.boolean()}),HQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:F(Yc.nullish(),()=>{}),text:u.string()}),zQ=u.object({range:ea.nullish(),text:u.string()}),_0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),contentChanges:u.array(zQ),sessionId:ue,uri:u.string(),version:u.number()}),ZCe=u.object({method:u.string(),params:u.union([f0,k0,_0,v0,w0,b0,m0,R0,t0,KD]).nullish()}),BQ=u.union([u.literal("full"),u.literal("incremental")]),qQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),syncKind:BQ}),WQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),didChange:F(qQ.nullish(),()=>{}),didClose:F(r9.nullish(),()=>{}),didFocus:F(n9.nullish(),()=>{}),didOpen:F(o9.nullish(),()=>{}),didSave:F(i9.nullish(),()=>{})}),KQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),document:F(WQ.nullish(),()=>{})}),GQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:F(x9.nullish(),()=>{}),events:F(KQ.nullish(),()=>{})}),VQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:BY.optional().default({}),loadSession:u.boolean().optional().default(!1),mcpCapabilities:WY.optional().default({acp:!1,http:!1,sse:!1}),nes:F(GQ.nullish(),()=>{}),positionEncoding:F(a0.nullish(),()=>{}),promptCapabilities:H9.optional().default({audio:!1,embeddedContext:!1,image:!1}),providers:F(W9.nullish(),()=>{}),sessionCapabilities:CQ.optional().default({})}),ZQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),agentCapabilities:VQ.optional().default({auth:{},loadSession:!1,mcpCapabilities:{acp:!1,http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:F(JD.nullish(),()=>{}),authMethods:F(ye(vY).optional().default([]),()=>[]),protocolVersion:c0}),JQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),mimeType:u.string().nullish(),text:u.string(),uri:u.string()}),XQ=u.union([JQ,kY]),YQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:F(Yc.nullish(),()=>{}),resource:XQ}),aR=u.union([HQ.and(u.object({type:u.literal("text")})),rQ.and(u.object({type:u.literal("image")})),tQ.and(u.object({type:u.literal("audio")})),nQ.and(u.object({type:u.literal("resource_link")})),YQ.and(u.object({type:u.literal("resource")}))]),QQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:aR}),Yx=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:aR,messageId:QY.nullish()}),E0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),prompt:u.array(aR),sessionId:ue}),e7=u.object({anyOf:u.array(BD)}),M0=u.union([QQ.and(u.object({type:u.literal("content")})),AY.and(u.object({type:u.literal("diff")})),LQ.and(u.object({type:u.literal("terminal")}))]),cR=u.string(),$0=u.object({sessionId:ue,toolCallId:cR.nullish()}),t7=u.intersection(u.union([$0,d0]),u.object({elicitationId:zD,url:u.string().url()})),D0=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()}),N0=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed"),u.literal("failed")]),O0=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")]),r7=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:F(ye(M0).optional(),()=>[]),kind:O0.optional(),locations:F(ye(D0).optional(),()=>[]),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:N0.optional(),title:u.string(),toolCallId:cR}),j0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:F(ye(M0).nullish(),()=>{}),kind:F(O0.nullish(),()=>{}),locations:F(ye(D0).nullish(),()=>{}),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:F(N0.nullish(),()=>{}),title:u.string().nullish(),toolCallId:cR}),lR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),options:u.array(P9),sessionId:ue,toolCall:j0}),n7=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),hint:u.string()}),o7=n7,i7=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string(),input:F(o7.nullish(),()=>{}),name:u.string()}),s7=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableCommands:Zr(ye(i7),()=>[])}),a7=u.object({enum:u.array(u.string()),type:NY}),c7=u.union([a7,e7]),l7=u.object({default:u.array(u.string()).nullish(),description:u.string().nullish(),items:c7,maxItems:u.number().nullish(),minItems:u.number().nullish(),title:u.string().nullish()}),d7=u.union([OQ.and(u.object({type:u.literal("string")})),R9.and(u.object({type:u.literal("number")})),FY.and(u.object({type:u.literal("integer")})),wY.and(u.object({type:u.literal("boolean")})),l7.and(u.object({type:u.literal("array")}))]),u7=u.object({description:u.string().nullish(),properties:u.record(u.string(),d7).optional().default({}),required:u.array(u.string()).nullish(),title:u.string().nullish(),type:DY.optional().default("object")}),p7=u.intersection(u.union([$0,d0]),u.object({requestedSchema:u7})),dR=u.intersection(u.union([p7.and(u.object({mode:u.literal("form")})),t7.and(u.object({mode:u.literal("url")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),message:u.string()})),m7=u.object({cachedReadTokens:u.number().nullish(),cachedWriteTokens:u.number().nullish(),inputTokens:u.number(),outputTokens:u.number(),thoughtTokens:u.number().nullish(),totalTokens:u.number()}),f7=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),stopReason:DQ,usage:F(m7.nullish(),()=>{})}),JCe=u.union([u.object({id:Uo,result:u.union([ZQ,bY,q9,_Q,IY,qY,PQ,TQ,bQ,PY,RQ,AQ,xY,MQ,EQ,f7,$Q,jQ,SY,VD,n0])}),u.object({error:WD,id:Uo})]),g7=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cost:F(RY.nullish(),()=>{}),size:u.number(),used:u.number()}),h7=u.union([Yx.and(u.object({sessionUpdate:u.literal("user_message_chunk")})),Yx.and(u.object({sessionUpdate:u.literal("agent_message_chunk")})),Yx.and(u.object({sessionUpdate:u.literal("agent_thought_chunk")})),r7.and(u.object({sessionUpdate:u.literal("tool_call")})),j0.and(u.object({sessionUpdate:u.literal("tool_call_update")})),_9.and(u.object({sessionUpdate:u.literal("plan")})),O9.and(u.object({sessionUpdate:u.literal("plan_update")})),D9.and(u.object({sessionUpdate:u.literal("plan_removed")})),s7.and(u.object({sessionUpdate:u.literal("available_commands_update")})),SQ.and(u.object({sessionUpdate:u.literal("current_mode_update")})),gQ.and(u.object({sessionUpdate:u.literal("config_option_update")})),kQ.and(u.object({sessionUpdate:u.literal("session_info_update")})),g7.and(u.object({sessionUpdate:u.literal("usage_update")}))]),uR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,update:h7}),XCe=u.object({method:u.string(),params:u.union([uR,Qx,t0,KD]).nullish()}),pR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,terminalId:u.string()}),y7=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()}),v7=u.object({name:u.string(),uri:u.string()}),L0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),repository:F(y9.nullish(),()=>{}),workspaceFolders:F(ye(v7).nullish(),()=>{}),workspaceUri:u.string().nullish()}),YCe=u.object({id:Uo,method:u.string(),params:u.union([l0,FD,XD,P0,HD,QD,o0,x0,YD,y0,S0,T0,h0,I0,A0,E0,L0,C0,g0,r0,GD]).nullish()}),mR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),path:u.string(),sessionId:ue}),QCe=u.object({id:Uo,method:u.string(),params:u.union([mR,oR,lR,rR,sR,iR,pR,nR,dR,VY,r0,GY,GD]).nullish()}),b7=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),e_e=u.union([u.object({id:Uo,result:u.union([b7,Y9,sQ,TY,FQ,Q9,y7,HY,MY,KY,CY,VD,n0])}),u.object({error:WD,id:Uo})]);function U0(t,e){let r=new TextEncoder,n=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+=n.decode();break}if(!d)continue;a+=n.decode(d,{stream:!0});let m=a.split(`
|
|
645
645
|
`);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)+`
|
|
646
|
-
`,c=t.getWriter();try{await c.write(r.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function Fo(t){return t??{}}function F0(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var zp=class{connection;constructor(e,r){let n=e(this),o=async(s,a)=>{switch(s){case Mr.fs_write_text_file:{let c=mR.parse(a);return await n.writeTextFile?.(c)??{}}case Mr.fs_read_text_file:{let c=oR.parse(a);return n.readTextFile?.(c)}case Mr.session_request_permission:{let c=lR.parse(a);return n.requestPermission(c)}case Mr.terminal_create:{let c=rR.parse(a);return n.createTerminal?.(c)}case Mr.terminal_output:{let c=sR.parse(a);return n.terminalOutput?.(c)}case Mr.terminal_release:{let c=iR.parse(a);return await n.releaseTerminal?.(c)??{}}case Mr.terminal_wait_for_exit:{let c=pR.parse(a);return n.waitForTerminalExit?.(c)}case Mr.terminal_kill:{let c=nR.parse(a);return await n.killTerminal?.(c)??{}}case Mr.elicitation_create:{if(!n.unstable_createElicitation)throw Xt.methodNotFound(s);let c=dR.parse(a);return n.unstable_createElicitation(c)}default:if(n.extMethod)return n.extMethod(s,a);throw Xt.methodNotFound(s)}},i=async(s,a)=>{switch(s){case Mr.session_update:{let c=uR.parse(a);return n.sessionUpdate(c)}case Mr.elicitation_complete:{if(!n.unstable_completeElicitation)return;let c=Qx.parse(a);return n.unstable_completeElicitation(c)}default:if(n.extNotification)return n.extNotification(s,a);throw Xt.methodNotFound(s)}};this.connection=new fR(o,i,r)}initialize(e){return this.connection.sendRequest(Se.initialize,e)}newSession(e){return this.connection.sendRequest(Se.session_new,e)}loadSession(e){return this.connection.sendRequest(Se.session_load,e,Fo)}unstable_forkSession(e){return this.connection.sendRequest(Se.session_fork,e)}listSessions(e){return this.connection.sendRequest(Se.session_list,e)}deleteSession(e){return this.connection.sendRequest(Se.session_delete,e,Fo)}resumeSession(e){return this.connection.sendRequest(Se.session_resume,e)}closeSession(e){return this.connection.sendRequest(Se.session_close,e)}setSessionMode(e){return this.connection.sendRequest(Se.session_set_mode,e,Fo)}setSessionConfigOption(e){return this.connection.sendRequest(Se.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(Se.authenticate,e,Fo)}unstable_listProviders(e){return this.connection.sendRequest(Se.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(Se.providers_set,e,Fo)}unstable_disableProvider(e){return this.connection.sendRequest(Se.providers_disable,e,Fo)}logout(e){return this.connection.sendRequest(Se.logout,e,Fo)}prompt(e){return this.connection.sendRequest(Se.session_prompt,e)}cancel(e){return this.connection.sendNotification(Se.session_cancel,e)}unstable_startNes(e){return this.connection.sendRequest(Se.nes_start,e)}unstable_suggestNes(e){return this.connection.sendRequest(Se.nes_suggest,e)}unstable_closeNes(e){return this.connection.sendRequest(Se.nes_close,e,Fo)}unstable_didOpenDocument(e){return this.connection.sendNotification(Se.document_did_open,e)}unstable_didChangeDocument(e){return this.connection.sendNotification(Se.document_did_change,e)}unstable_didCloseDocument(e){return this.connection.sendNotification(Se.document_did_close,e)}unstable_didSaveDocument(e){return this.connection.sendNotification(Se.document_did_save,e)}unstable_didFocusDocument(e){return this.connection.sendNotification(Se.document_did_focus,e)}unstable_acceptNes(e){return this.connection.sendNotification(Se.nes_accept,e)}unstable_rejectNes(e){return this.connection.sendNotification(Se.nes_reject,e)}extMethod(e,r){return this.connection.sendRequest(e,r)}extNotification(e,r){return this.connection.sendNotification(e,r)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},fR=class{pendingResponses=new Map;nextRequestId=0;requestHandler;notificationHandler;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;constructor(e,r,n){this.requestHandler=e,this.notificationHandler=r,this.stream=n,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 r=this.stream.readable.getReader();try{for(;!this.abortController.signal.aborted;){let{value:n,done:o}=await r.read();if(o)break;if(n)try{this.processMessage(n)}catch(i){console.error("Unexpected error during message processing:",n,i),"id"in n&&n.id!==void 0&&this.sendMessage({jsonrpc:"2.0",id:n.id,error:{code:-32700,message:"Parse error"}})}}}finally{r.releaseLock()}}catch(r){e=r}finally{this.close(e)}}close(e){if(this.abortController.signal.aborted)return;let r=e??new Error("ACP connection closed");for(let n of this.pendingResponses.values())n.reject(r);this.pendingResponses.clear(),this.abortController.abort(r)}async processMessage(e){if("method"in e&&"id"in e){let r=await this.tryCallRequestHandler(e.method,e.params);"error"in r&&console.error("Error handling request",e,r.error),await this.sendMessage({jsonrpc:"2.0",id:e.id,...r})}else if("method"in e){let r=await this.tryCallNotificationHandler(e.method,e.params);"error"in r&&console.error("Error handling notification",e,r.error)}else"id"in e?this.handleResponse(e):console.error("Invalid message",{message:e})}async tryCallRequestHandler(e,r){try{return{result:await this.requestHandler(e,r)??null}}catch(n){if(n instanceof Xt)return n.toResult();if(n instanceof u.ZodError)return Xt.invalidParams(n.format()).toResult();let o;(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")&&(o=n.message);try{return Xt.internalError(o?JSON.parse(o):{}).toResult()}catch{return Xt.internalError({details:o}).toResult()}}}async tryCallNotificationHandler(e,r){try{return await this.notificationHandler(e,r),{result:null}}catch(n){if(n instanceof Xt)return n.toResult();if(n instanceof u.ZodError)return Xt.invalidParams(n.format()).toResult();let o;(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")&&(o=n.message);try{return Xt.internalError(o?JSON.parse(o):{}).toResult()}catch{return Xt.internalError({details:o}).toResult()}}}handleResponse(e){let r=this.pendingResponses.get(e.id);if(r){if("result"in e)r.resolve(e.result);else if("error"in e){let{code:n,message:o,data:i}=e.error;r.reject(new Xt(n,o,i))}this.pendingResponses.delete(e.id)}else console.error("Got response to unknown request",e.id)}sendRequest(e,r,n){if(this.abortController.signal.aborted)return F0(this.closedReason());let o=this.nextRequestId++,i=new Promise((s,a)=>{this.pendingResponses.set(o,{resolve:c=>{try{s(n?n(c):c)}catch(l){a(l)}},reject:a})});return i.catch(()=>{}),this.sendMessage({jsonrpc:"2.0",id:o,method:e,params:r}),i}sendNotification(e,r){return this.abortController.signal.aborted?F0(this.closedReason()):this.sendMessage({jsonrpc:"2.0",method:e,params:r})}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendMessage(e){return this.writeQueue=this.writeQueue.then(async()=>{let r=this.stream.writable.getWriter();try{await r.write(e)}finally{r.releaseLock()}}).catch(r=>{this.close(r)}),this.writeQueue}},Xt=class t extends Error{code;data;constructor(e,r,n){super(r),this.code=e,this.name="RequestError",this.data=n}static parseError(e,r){return new t(-32700,`Parse error${r?`: ${r}`:""}`,e)}static invalidRequest(e,r){return new t(-32600,`Invalid request${r?`: ${r}`:""}`,e)}static methodNotFound(e){return new t(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,r){return new t(-32602,`Invalid params${r?`: ${r}`:""}`,e)}static internalError(e,r){return new t(-32603,`Internal error${r?`: ${r}`:""}`,e)}static authRequired(e,r){return new t(-32e3,`Authentication required${r?`: ${r}`:""}`,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 x7=1,R7=2e4,H0=3e4,T7=3e5,Jr={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"},Qc=class extends Error{retryable=!1;authMethods;constructor(e,r){super(e),this.name="AcpAuthRequiredError",this.authMethods=r}};function el(t,e){if(t instanceof Qc)return t;let r=t,n=Array.isArray(r?.data?.authMethods)?r.data.authMethods:[];if(r?.code===-32e3||n.length>0||/auth(?:entication|orization)?\s+required/i.test(r?.message??"")){let i=n[0],s=i?.description||(i?.name?`Use "${i.name}".`:"");return new Qc(`Authentication required.${s?` ${s}`:""}`,n)}if(e&&e.length>0){let i=e[0],s=r?.data?.details||i?.description||(i?.name?`Authentication required. Use "${i.name}".`:r?.message||"Authentication required.");return new Qc(s,e)}return null}function P7(t){let e=t;if(!e||typeof e.message!="string")return t;let r=e.data,n=typeof r=="string"?r:typeof r?.details=="string"?r.details:typeof r?.error=="string"?r.error:typeof r?.message=="string"?r.message:"";if(!n||e.message.includes(n))return t;let o=new Error(`${e.message}: ${n}`);return o.name=t instanceof Error?t.name:"Error",Object.assign(o,{code:e.code,data:e.data}),o}var Ho=class{conn=null;child=null;onNotification=null;hostHandler=null;attach(e,r,n){if(this.child=e,this.onNotification=r??null,this.hostHandler=n??null,!e.stdin||!e.stdout)throw new Error("ACP adapter: child process has no stdio");let o=U0(S7.toWeb(e.stdin),w7.toWeb(e.stdout));this.conn=new zp(()=>this.buildClient(),o)}buildClient(){let e=()=>this.hostHandler,r=(n,o)=>this.onNotification?.(n,o);return{async sessionUpdate(n){r("session/update",n)},async requestPermission(n){let o=e(),s=(o?.requestPermission?await o.requestPermission(n):{optionId:"allow"})?.optionId;return s?{outcome:{outcome:"selected",optionId:s}}:{outcome:{outcome:"cancelled"}}},async readTextFile(n){return{content:(await e()?.readTextFile?.(n))?.content??""}},async writeTextFile(n){return await e()?.writeTextFile?.(n),{}},async createTerminal(n){return await e()?.createTerminal?.(n)??{terminalId:""}},async terminalOutput(n){return await e()?.terminalOutput?.(n)??{output:"",truncated:!1}},async releaseTerminal(n){return await e()?.releaseTerminal?.(n),{}},async waitForTerminalExit(n){return await e()?.waitForTerminalExit?.(n)??{}},async killTerminal(n){return await e()?.killTerminal?.(n),{}},async extMethod(n,o){return await e()?.extMethod?.(n,o)??{}},async extNotification(n,o){r(n,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,r,n,o){let i,s=new Promise((a,c)=>{i=setTimeout(()=>{try{o?.()}catch{}c(new Error(`ACP ${n} timeout (${r}ms)`))},r)});try{return await Promise.race([e,s])}finally{i&&clearTimeout(i)}}async initialize(e){let r={protocolVersion:x7,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}},clientInfo:{name:"qlogicagent",version:"1.0.0"}},n=await this.withTimeout(this.requireConn().initialize(r),R7,"initialize").catch(i=>{throw el(i)??i}),o=n?.agentCapabilities??{};return{protocolVersion:typeof n?.protocolVersion=="number"?n.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities,qlogicagent:o.qlogicagent},agentInfo:n?.agentInfo,authMethods:n?.authMethods}}async createSession(e,r){let n={cwd:r.cwd,mcpServers:r.mcpServers??[]};r.additionalDirectories?.length&&(n.additionalDirectories=r.additionalDirectories),r.systemPrompt&&(n._meta={qlogicagent:{systemPrompt:r.systemPrompt}});let o=await this.withTimeout(this.requireConn().newSession(n),H0,"session/new").catch(i=>{throw el(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,r,n,o=T7){let i=this.requireConn(),s=await this.withTimeout(i.prompt({sessionId:r,prompt:[{type:"text",text:n}]}),o,"session/prompt",()=>{i.cancel({sessionId:r}).catch(()=>{})}).catch(a=>{throw el(a)??P7(a)});return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:void 0}}async resumeSession(e,r,n){let o={sessionId:r,cwd:n?.cwd??process.cwd(),mcpServers:n?.mcpServers??[]},i=await this.withTimeout(this.requireConn().loadSession(o),H0,"session/load");return{sessionId:typeof i?.sessionId=="string"?i.sessionId:r}}static translateNotification(e,r){let n=r;if(e==="session/update"){if(!n)return null;let o=n.update;if(!o)return null;let i=o.sessionUpdate,s=n.sessionId;switch(i){case Jr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case Jr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case Jr.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 Jr.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 Jr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case Jr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case Jr.AVAILABLE_COMMANDS_UPDATE:case Jr.CURRENT_MODE_UPDATE:case Jr.CONFIG_OPTION_UPDATE:case Jr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case Jr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as A7}from"node:child_process";import{readFile as I7,writeFile as C7}from"node:fs/promises";import{isAbsolute as z0,normalize as _7,relative as E7,resolve as M7,sep as $7}from"node:path";function D7(t){let e=t.options;if(!Array.isArray(e)||e.length===0)return"allow";let r=e.filter(c=>!!c&&typeof c=="object"),n=c=>typeof c.optionId=="string"&&c.optionId.trim()?c.optionId:void 0;if(r.find(c=>n(c)==="allow"))return"allow";let i=r.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/allow/i.test(l)}),s=i?n(i):void 0;if(s)return s;let a=r.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/reject|deny|cancel/i.test(l)});return n(a??{})??n(r[0]??{})??"allow"}function gR(t){let e=new Map,r=0,n=i=>{let s=z0(i)?_7(i):M7(t.cwd,i),a=E7(t.cwd,s);if(a===".."||a.startsWith(`..${$7}`)||z0(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:D7(i)}},async readTextFile(i){return{content:await I7(n(i.path),"utf8")}},async writeTextFile(i){return await C7(n(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?n(String(l)):t.cwd,p=i.env,m={...process.env,...p&&typeof p=="object"?p:{}},f=A7(s,c,{cwd:d,env:m,stdio:["ignore","pipe","pipe"]}),g=`term-${++r}`,h={child:f,output:"",exitStatus:null,exit:new Promise(y=>{f.on("exit",(v,k)=>{let w={exitCode:v,signal:k};h.exitStatus=w,y(w)}),f.on("error",()=>{let v={exitCode:null,signal:null};h.exitStatus=v,y(v)})})};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 tl=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{execFile as N7,execFileSync as O7,execSync as K0}from"node:child_process";import{existsSync as Bp,mkdirSync as j7,readFileSync as yR,readdirSync as L7,writeFileSync as U7}from"node:fs";import{homedir as F7,platform as H7,tmpdir as z7}from"node:os";import{dirname as B7,join as Gn}from"node:path";import{promisify as q7}from"node:util";var W7=q7(N7),nl={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:!1,apiKeyEnvVar:"GEMINI_API_KEY"},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"},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"}},K7=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],B0={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"}},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"}},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"}},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",docsUrl:"https://docs.github.com/copilot/concepts/agents/about-copilot-cli"}},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",docsUrl:"https://cursor.com/cli"}},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"}},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",docsUrl:"https://github.com/MoonshotAI/kimi-cli"}},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"}},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"}},kiro:{brandId:"kiro",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{cliCommand:"kiro-cli",docsUrl:"https://kiro.dev/docs"}},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"}},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",docsUrl:"https://github.com/openclaw/openclaw"}},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",docsUrl:"https://github.com/NousResearch/hermes-agent"}}};function ra(t){let e=nl[t];if(e)return B0[t]?{...e,...B0[t]}:e}function vR(){return K7.map(t=>{let e=ra(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Ei=H7()==="win32",G7=5*6e4,rl,q0=new Map;function hR(t){try{let e=Ei?`where ${t}`:`which ${t}`;return K0(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function V7(t,e){let r=i=>{let s=i.match(/^(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},n=r(t),o=r(e);for(let i=0;i<3;i+=1)if(n[i]!==o[i])return o[i]-n[i];return e.localeCompare(t)}function Z7(){if(!Ei)return null;let t=[process.env.COPILOT_CACHE_HOME?Gn(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?Gn(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?Gn(process.env.COPILOT_HOME,"pkg","win32-x64"):null,Gn(F7(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let r=L7(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name).sort(V7);for(let n of r){let o=Gn(e,n,"npm-loader.js");if(Bp(o)&&Z0(o))return o}}catch{}return null}function J7(t){return t.id==="copilot"?Z7()??hR(t.cliCommand):hR(t.cliCommand)}function X7(t,e){return O7(Ei?"cmd.exe":"npm",Ei?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"]}).trim()}async function Y7(t,e){let{stdout:r}=await W7(Ei?"cmd.exe":"npm",Ei?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function Q7(t){let e=t.trim().replace(/^["']|["']$/g,"");if(!e||e.startsWith("-"))return null;if(e.startsWith("@")){let n=e.indexOf("@",1);return n>0?e.slice(0,n):e}let r=e.indexOf("@");return r>0?e.slice(0,r):e}function bR(t){if(!t)return null;let e=t.trim().split(/\s+/).filter(Boolean);if(e[0]!=="npm"&&e[0]!=="npm.cmd")return null;let r=e.findIndex(n=>n==="i"||n==="install"||n==="add");if(r<0)return null;for(let n=r+1;n<e.length;n+=1){let o=e[n];if(!(o==="-g"||o==="--global")){if(o.startsWith("--")&&!o.includes("=")){n+=1;continue}if(!o.startsWith("-"))return Q7(o)}}return null}function qp(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function eee(t,e){let r=i=>{let s=qp(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}},n=r(t),o=r(e);for(let i=0;i<3;i+=1)if(n.nums[i]!==o.nums[i])return n.nums[i]-o.nums[i];return n.pre===o.pre?0:n.pre?o.pre?n.pre.localeCompare(o.pre):-1:1}function tee(t,e){return!t||!e?!1:eee(t,e)>0}function ree(){if(rl!==void 0)return rl;try{rl=X7(["root","-g"],3e3)||null}catch{rl=null}return rl}function kR(t){if(!t)return null;let e=ree();if(!e)return null;let r=Gn(e,...t.split("/"),"package.json");try{let n=JSON.parse(yR(r,"utf8"));return typeof n.version=="string"?n.version:null}catch{return null}}function nee(t){let e=bR(t?.npm);return kR(e)}function G0(t,e){let r=bR(t.install?.npm),o=kR(r)??qp(e)??e??void 0;return{packageName:r??void 0,installedVersion:o,updateAvailable:!1}}async function oee(t){if(!t)return null;let e=q0.get(t);if(e&&Date.now()-e.timestamp<G7)return e.version;let r=null;try{let n=await Y7(["view",t,"version","--json"],12e3),o=n?JSON.parse(n):null;r=typeof o=="string"?o:qp(n)}catch{r=null}return q0.set(t,{timestamp:Date.now(),version:r}),r}async function V0(t){let e=t.map(async({id:n,entry:o,detectedVersion:i})=>{let s=bR(o.install?.npm),a=kR(s)??qp(i)??i??void 0;if(!s||!a)return null;let c=await oee(s)??void 0;return c?{id:n,packageName:s,installedVersion:a,latestVersion:c,updateAvailable:tee(c,a)}:null});return(await Promise.all(e)).filter(n=>n!==null)}function Z0(t){try{let e=t.endsWith("npm-loader.js")?`"${process.execPath}" "${t}" version`:`"${t}" version`;return K0(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}function iee(t,e){if(!Ei)return{cliPath:t,acpArgs:e};if(t.endsWith("npm-loader.js")){let n=e.includes("--no-auto-update");return{cliPath:process.execPath,acpArgs:[t,...e,...n?[]:["--no-auto-update"]]}}let r=see(t);return r?{cliPath:process.execPath,acpArgs:[r,...e]}:{cliPath:t,acpArgs:e}}function see(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),r=[`${e}.cmd`,`${e}.ps1`,e];for(let n of r){if(!Bp(n))continue;let o;try{o=yR(n,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=Gn(B7(e),s);if(Bp(a))return a}return null}var aee=6e4;function cee(t,e,r){let n={};return t?.env&&Object.assign(n,t.env),r&&Object.assign(n,r),t?.apiKeyEnvVar&&e?.apiKey&&(n[t.apiKeyEnvVar]=e.apiKey),t?.baseUrlEnvVar&&e?.baseUrl&&(n[t.baseUrlEnvVar]=e.baseUrl),e?.env&&Object.assign(n,e.env),Object.keys(n).length>0?n:void 0}var W0=new Set(["codex","qwen","opencode"]);function lee(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function dee(t){let e=Gn(z7(),"qlogicagent-codex-model-catalog");j7(e,{recursive:!0});let r=Gn(e,`${lee(t)}.json`),n=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(!Bp(r)||yR(r,"utf8")!==n)&&U7(r,n,"utf8"),r}function uee(t,e){let r={};if(!t||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:n,baseUrlEnvVar:o}=t;if(t.keySource==="llmrouter"){n&&e.llmrouterKey&&(r[n]=e.llmrouterKey);let i=e.getLlmrouterBaseUrl?.(t.id,t)??e.llmrouterBaseUrl;o&&i&&(r[o]=i),W0.has(t.id)&&e.llmrouterModel&&(r.OPENAI_MODEL=e.llmrouterModel)}else if(t.keySource==="direct"){let i=e.getDirectKey?.(t.id);n&&i&&(r[n]=i)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&W0.has(t.id)){let i=e.passthroughModel;r.OPENAI_API_KEY=i.apiKey,i.baseUrl&&(r.OPENAI_BASE_URL=i.baseUrl),i.model&&(r.OPENAI_MODEL=i.model)}return r}function pee(t,e,r,n){if(t?.id!=="codex"||t.keySource!=="llmrouter"||!r.OPENAI_API_KEY||e.some(s=>s.includes("model_provider")||s.includes("model_providers.")))return e;let o=r.OPENAI_BASE_URL,i=n.llmrouterModel||r.OPENAI_MODEL||"deepseek-v4-flash";return o?[...e,"-c","model_providers.llmrouter.name=llmrouter","-c",`model_providers.llmrouter.base_url=${o}`,"-c","model_providers.llmrouter.wire_api=responses","-c","model_providers.llmrouter.env_key=OPENAI_API_KEY","-c","model_provider=llmrouter","-c",`model=${i}`,"-c",`model_catalog_json=${dee(i)}`]:e}var na=class{cache=null;configStore=null;keySources={};setConfigStore(e){this.configStore=e}setKeySources(e){this.keySources=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<aee)return this.cache.agents;let r=[];for(let n of Object.values(nl))r.push(this.detectBackend(n));if(this.configStore?.customAgents)for(let n of Object.values(this.configStore.customAgents))r.push(this.detectCustomAgent(n));return this.cache={agents:r,timestamp:Date.now()},r}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let r=J7(e),n=this.hasAgentConfig(e.id);if(!r)return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}};let o=ra(e.id),i=Z0(r)??nee(o?.install);return e.id==="copilot"&&!i?{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:n,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:r,version:i??void 0,authRequired:e.authRequired,hasConfig:n,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}}}detectCustomAgent(e){let r=hR(e.cliCommand),n=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:r?"available":"not_installed",cliPath:r??void 0,authRequired:e.authRequired??!1,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let r=this.configStore.agents[e];return!!(r?.apiKey||r?.baseUrl||r?.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"],r={};for(let n of e){let o=process.env[n];o&&(r[n]=o)}return{id:"qlogicagent",cliPath:process.execPath,acpArgs:[process.argv[1]??""],env:Object.keys(r).length>0?r:void 0,protocol:"acp"}}buildExternalDescriptor(e){if(e==="qlogicagent")return this.buildSelfDescriptor();let r=this.list().find(d=>d.id===e);if(!r||r.protocol!=="acp"||r.status!=="available"||!r.cliPath)return null;let n=ra(e)??nl[e],o=this.configStore?.agents[e],i=this.configStore?.customAgents?.[e],s=o?.customArgs?.length?o.customArgs:i?.acpArgs??n?.acpArgs??[],a=o?.customCliPath?{cliPath:o.customCliPath,acpArgs:s}:iee(r.cliPath,s),c=uee(n,this.keySources),l=o?.customArgs?.length?a.acpArgs:pee(n,a.acpArgs,c,this.keySources);return{id:e,cliPath:a.cliPath,acpArgs:l,env:cee(n,o,c),protocol:"acp"}}isAgentReady(e){if(e==="qlogicagent")return!0;let r=this.buildExternalDescriptor(e);if(!r)return!1;let n=ra(e)??nl[e];return n?.apiKeyEnvVar&&n.authMode!=="oauth"?!!r.env?.[n.apiKeyEnvVar]:!0}};var SR="https://registry.npmmirror.com",oa="https://pypi.tuna.tsinghua.edu.cn/simple",wR="https://registry.npmmirror.com/-/binary";function mee(){return{npm_config_registry:SR,PIP_INDEX_URL:oa,UV_DEFAULT_INDEX:oa,UV_INDEX_URL:oa,UV_PYTHON_INSTALL_MIRROR:`${wR}/python-build-standalone`,NODEJS_ORG_MIRROR:`${wR}/node`,npm_config_disturl:`${wR}/node`}}var J0=Object.keys(mee());var wee=1;function See(t,e){return{jsonrpc:"2.0",id:wee++,method:t,params:e,meta:zy(t)}}var xee=["NODE_ENV","HOME","PATH","TERM","OPENAI_API_KEY","OPENAI_BASE_URL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","QLOGIC_LLMROUTER_BASE_URL","QLOGIC_LLMROUTER_ACCESS_TOKEN","QLOGIC_LLMROUTER_USER_ID","QLOGIC_LLMROUTER_INFERENCE_KEY","QLOGIC_LLMROUTER_EMBEDDING_MODEL","QLOGIC_LLMROUTER_EMBEDDING_DIMENSIONS","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy",...J0],Ree=["127.0.0.1","localhost","::1"];function Tee(t){let r=`${t.NO_PROXY??""},${t.no_proxy??""}`.split(",").map(i=>i.trim()).filter(Boolean),n=new Set(r.map(i=>i.toLowerCase()));for(let i of Ree)n.has(i.toLowerCase())||(r.push(i),n.add(i.toLowerCase()));let o=r.join(",");return t.NO_PROXY=o,t.no_proxy=o,t}function Pee(t){let e={};for(let r of xee)process.env[r]&&(e[r]=process.env[r]);return e.QLOGICAGENT_MEMBER_ID=t.memberId,e.QLOGICAGENT_MEMBER_NAME=t.name,t.agentType&&(e.QLOGICAGENT_AGENT_TYPE=t.agentType),t.env&&Object.assign(e,t.env),Tee(e)}function X0(t){return["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_MODEL","CODEX_API_KEY","NO_PROXY"].map(r=>{let n=t[r];return/API_KEY|TOKEN|SECRET|PASSWORD/i.test(r)?`${r}=${n?"<set>":"<unset>"}`:`${r}=${n||"<unset>"}`}).join(", ")}var RR=Gh,Aee=Vh,ia=Zh,Y0=Jh;function Iee(t){return new Promise(e=>setTimeout(e,t))}function Cee(t){return t.replace(/[<>:"/\\|?*\x00-\x1F]/g,"-")}function _ee(t,e){if(process.platform==="win32"&&typeof e=="number"&&e>0)try{fee("taskkill",["/PID",String(e),"/T","/F"],()=>{});return}catch{}try{t.kill("SIGTERM"),setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},1e4)}catch{}}var $r=class t{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let r=gee(ol(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=ol(r,"dist","cli.js"),this.mcpBridgeScriptPath=ol(r,"dist","runtime","infra","mcp-bridge-server.js")}slog(e,r,n,o){let s=`[${new Date().toISOString()}] [${e}] [agent:${r}] [${n}] ${o}`;e==="warn"?this.callbacks.log?.warn(s):this.callbacks.log?.info(s)}async spawn(e){if(this.processes.has(e.memberId))throw new Error(`Agent process "${e.memberId}" already spawned`);let r=this.callbacks.log,n=Pee(e),o={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()};if(e.external)return this.spawnAcpAgentWithRetry(e,o,n);let i=[this.cliBinaryPath];e.verbose&&i.push("--verbose"),this.slog("info",e.memberId,"spawn",`spawning ${e.name} in ${e.cwd}`);let s=xR(process.execPath,i,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});o.pid=s.pid??-1;let a=new Map;this.processes.set(e.memberId,{handle:o,child:s,pendingRpc:a}),Wp({input:s.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",l=>{let d=l.trim();if(d)try{let p=JSON.parse(d),m="id"in p,f="method"in p&&typeof p.method=="string";if(m&&f){this.handleChildHostRequest(e.memberId,p);return}if(m){let g=a.get(p.id);if(g){clearTimeout(g.timer),a.delete(p.id);let h=p;h.error?g.reject(new Error(h.error.message)):g.resolve(h.result)}return}if(f){let g=Ho.translateNotification(p.method,p.params),h=g?.method??p.method,y=g?.params??p.params;this.captureChildProgress(e.memberId,h,y),this.callbacks.onNotification?.(e.memberId,h,y)}}catch{this.slog("warn",e.memberId,"parse",`invalid JSON: ${d.slice(0,200)}`)}}),s.stderr&&Wp({input:s.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",d=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${d}`)}),s.on("exit",(l,d)=>{o.state!=="killed"&&(o.state=l===0?"completed":"failed"),o.endedAt=Date.now(),l!==0&&!o.error&&(o.error=`Process exited with code ${l} (signal: ${d})`);for(let[m,f]of a)clearTimeout(f.timer),f.reject(new Error(`Agent process exited (code=${l})`)),a.delete(m);this.callbacks.onStateChange?.(e.memberId,o.state),this.callbacks.onExit?.(e.memberId,l,d),this.slog("info",e.memberId,"exit",`exited (code=${l}, signal=${d})`)}),s.on("error",l=>{o.state="failed",o.error=l.message,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.slog("warn",e.memberId,"error",l.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{await this.sendRpc(e.memberId,"initialize",{protocolVersion:1,clientInfo:{name:"qlogicagent-team-leader",version:"1.0.0"},clientCapabilities:{qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}}},15e3);let l=hee(),d={sessionId:l,cwd:e.cwd,_meta:{permissions:{mode:"full_access"},...e.systemPrompt?{appendSystemPrompt:e.systemPrompt}:{}}};await this.sendRpc(e.memberId,"session/new",d,15e3),o.sessionId=l;let p=[["provider",e.provider],["model",e.model],["apiKey",e.apiKey],["baseUrl",e.baseUrl]];for(let[m,f]of p)f&&await this.sendRpc(e.memberId,"session/set_config_option",{sessionId:l,option:m,value:f},15e3);o.state="ready",this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`initialized (pid=${o.pid}, session=${l})`)}catch(l){throw o.state="failed",o.error=`Initialize handshake failed: ${l instanceof Error?l.message:String(l)}`,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.kill(e.memberId),new Error(o.error)}return o}async sendTask(e,r,n){let o=this.processes.get(e);if(!o)throw new Error(`No agent process: ${e}`);o.handle.resultText="",o.handle.acpUpdateTypes=[],o.handle.state="running",this.callbacks.onStateChange?.(e,"running");try{let i;if(o.acpAdapter){let s=o.handle.sessionId??"default",a=Date.now(),c;try{c=await o.acpAdapter.sendPrompt(o.child,s,r,n?.timeout??3e5)}finally{o.handle.acpLastPromptElapsedMs=Date.now()-a}let l=o.handle.resultText??"";c.usage&&o.usageTracker&&o.usageTracker.onPromptResponseUsage(c.usage),i={content:l,stopReason:c.stopReason,diagnostics:this.buildExternalPromptDiagnostics(o,c.stopReason)}}else{let s=n?.sessionId??o.handle.sessionId??"default",a=await this.sendRpc(e,"session/prompt",{sessionId:s,prompt:[{type:"text",text:r}]},n?.timeout??3e5),c=o.handle.resultText??"",l=a&&typeof a.stopReason=="string"?a.stopReason:void 0;i={content:c,stopReason:l}}return o.handle.state="completed",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"completed"),i}catch(i){throw o.handle.state="failed",o.handle.error=i instanceof Error?i.message:String(i),o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),i}}buildExternalPromptDiagnostics(e,r){return{stopReason:r,sessionId:e.handle.sessionId,updateTypes:e.handle.acpUpdateTypes??[],stderrLog:e.handle.stderrLogPath,launch:e.handle.acpLaunchDiagnostics,promptElapsedMs:e.handle.acpLastPromptElapsedMs}}async sendRpc(e,r,n,o=3e4){let i=this.processes.get(e);if(!i)throw new Error(`No agent process: ${e}`);let s=See(r,n);return new Promise((a,c)=>{let l=setTimeout(()=>{i.pendingRpc.delete(s.id),c(new Error(`RPC timeout: ${r} (${o}ms)`))},o);i.pendingRpc.set(s.id,{resolve:a,reject:c,timer:l});try{i.child.stdin.write(`${JSON.stringify(s)}
|
|
646
|
+
`,c=t.getWriter();try{await c.write(r.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function Fo(t){return t??{}}function F0(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var zp=class{connection;constructor(e,r){let n=e(this),o=async(s,a)=>{switch(s){case Mr.fs_write_text_file:{let c=mR.parse(a);return await n.writeTextFile?.(c)??{}}case Mr.fs_read_text_file:{let c=oR.parse(a);return n.readTextFile?.(c)}case Mr.session_request_permission:{let c=lR.parse(a);return n.requestPermission(c)}case Mr.terminal_create:{let c=rR.parse(a);return n.createTerminal?.(c)}case Mr.terminal_output:{let c=sR.parse(a);return n.terminalOutput?.(c)}case Mr.terminal_release:{let c=iR.parse(a);return await n.releaseTerminal?.(c)??{}}case Mr.terminal_wait_for_exit:{let c=pR.parse(a);return n.waitForTerminalExit?.(c)}case Mr.terminal_kill:{let c=nR.parse(a);return await n.killTerminal?.(c)??{}}case Mr.elicitation_create:{if(!n.unstable_createElicitation)throw Xt.methodNotFound(s);let c=dR.parse(a);return n.unstable_createElicitation(c)}default:if(n.extMethod)return n.extMethod(s,a);throw Xt.methodNotFound(s)}},i=async(s,a)=>{switch(s){case Mr.session_update:{let c=uR.parse(a);return n.sessionUpdate(c)}case Mr.elicitation_complete:{if(!n.unstable_completeElicitation)return;let c=Qx.parse(a);return n.unstable_completeElicitation(c)}default:if(n.extNotification)return n.extNotification(s,a);throw Xt.methodNotFound(s)}};this.connection=new fR(o,i,r)}initialize(e){return this.connection.sendRequest(Se.initialize,e)}newSession(e){return this.connection.sendRequest(Se.session_new,e)}loadSession(e){return this.connection.sendRequest(Se.session_load,e,Fo)}unstable_forkSession(e){return this.connection.sendRequest(Se.session_fork,e)}listSessions(e){return this.connection.sendRequest(Se.session_list,e)}deleteSession(e){return this.connection.sendRequest(Se.session_delete,e,Fo)}resumeSession(e){return this.connection.sendRequest(Se.session_resume,e)}closeSession(e){return this.connection.sendRequest(Se.session_close,e)}setSessionMode(e){return this.connection.sendRequest(Se.session_set_mode,e,Fo)}setSessionConfigOption(e){return this.connection.sendRequest(Se.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(Se.authenticate,e,Fo)}unstable_listProviders(e){return this.connection.sendRequest(Se.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(Se.providers_set,e,Fo)}unstable_disableProvider(e){return this.connection.sendRequest(Se.providers_disable,e,Fo)}logout(e){return this.connection.sendRequest(Se.logout,e,Fo)}prompt(e){return this.connection.sendRequest(Se.session_prompt,e)}cancel(e){return this.connection.sendNotification(Se.session_cancel,e)}unstable_startNes(e){return this.connection.sendRequest(Se.nes_start,e)}unstable_suggestNes(e){return this.connection.sendRequest(Se.nes_suggest,e)}unstable_closeNes(e){return this.connection.sendRequest(Se.nes_close,e,Fo)}unstable_didOpenDocument(e){return this.connection.sendNotification(Se.document_did_open,e)}unstable_didChangeDocument(e){return this.connection.sendNotification(Se.document_did_change,e)}unstable_didCloseDocument(e){return this.connection.sendNotification(Se.document_did_close,e)}unstable_didSaveDocument(e){return this.connection.sendNotification(Se.document_did_save,e)}unstable_didFocusDocument(e){return this.connection.sendNotification(Se.document_did_focus,e)}unstable_acceptNes(e){return this.connection.sendNotification(Se.nes_accept,e)}unstable_rejectNes(e){return this.connection.sendNotification(Se.nes_reject,e)}extMethod(e,r){return this.connection.sendRequest(e,r)}extNotification(e,r){return this.connection.sendNotification(e,r)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},fR=class{pendingResponses=new Map;nextRequestId=0;requestHandler;notificationHandler;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;constructor(e,r,n){this.requestHandler=e,this.notificationHandler=r,this.stream=n,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 r=this.stream.readable.getReader();try{for(;!this.abortController.signal.aborted;){let{value:n,done:o}=await r.read();if(o)break;if(n)try{this.processMessage(n)}catch(i){console.error("Unexpected error during message processing:",n,i),"id"in n&&n.id!==void 0&&this.sendMessage({jsonrpc:"2.0",id:n.id,error:{code:-32700,message:"Parse error"}})}}}finally{r.releaseLock()}}catch(r){e=r}finally{this.close(e)}}close(e){if(this.abortController.signal.aborted)return;let r=e??new Error("ACP connection closed");for(let n of this.pendingResponses.values())n.reject(r);this.pendingResponses.clear(),this.abortController.abort(r)}async processMessage(e){if("method"in e&&"id"in e){let r=await this.tryCallRequestHandler(e.method,e.params);"error"in r&&console.error("Error handling request",e,r.error),await this.sendMessage({jsonrpc:"2.0",id:e.id,...r})}else if("method"in e){let r=await this.tryCallNotificationHandler(e.method,e.params);"error"in r&&console.error("Error handling notification",e,r.error)}else"id"in e?this.handleResponse(e):console.error("Invalid message",{message:e})}async tryCallRequestHandler(e,r){try{return{result:await this.requestHandler(e,r)??null}}catch(n){if(n instanceof Xt)return n.toResult();if(n instanceof u.ZodError)return Xt.invalidParams(n.format()).toResult();let o;(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")&&(o=n.message);try{return Xt.internalError(o?JSON.parse(o):{}).toResult()}catch{return Xt.internalError({details:o}).toResult()}}}async tryCallNotificationHandler(e,r){try{return await this.notificationHandler(e,r),{result:null}}catch(n){if(n instanceof Xt)return n.toResult();if(n instanceof u.ZodError)return Xt.invalidParams(n.format()).toResult();let o;(n instanceof Error||typeof n=="object"&&n!=null&&"message"in n&&typeof n.message=="string")&&(o=n.message);try{return Xt.internalError(o?JSON.parse(o):{}).toResult()}catch{return Xt.internalError({details:o}).toResult()}}}handleResponse(e){let r=this.pendingResponses.get(e.id);if(r){if("result"in e)r.resolve(e.result);else if("error"in e){let{code:n,message:o,data:i}=e.error;r.reject(new Xt(n,o,i))}this.pendingResponses.delete(e.id)}else console.error("Got response to unknown request",e.id)}sendRequest(e,r,n){if(this.abortController.signal.aborted)return F0(this.closedReason());let o=this.nextRequestId++,i=new Promise((s,a)=>{this.pendingResponses.set(o,{resolve:c=>{try{s(n?n(c):c)}catch(l){a(l)}},reject:a})});return i.catch(()=>{}),this.sendMessage({jsonrpc:"2.0",id:o,method:e,params:r}),i}sendNotification(e,r){return this.abortController.signal.aborted?F0(this.closedReason()):this.sendMessage({jsonrpc:"2.0",method:e,params:r})}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendMessage(e){return this.writeQueue=this.writeQueue.then(async()=>{let r=this.stream.writable.getWriter();try{await r.write(e)}finally{r.releaseLock()}}).catch(r=>{this.close(r)}),this.writeQueue}},Xt=class t extends Error{code;data;constructor(e,r,n){super(r),this.code=e,this.name="RequestError",this.data=n}static parseError(e,r){return new t(-32700,`Parse error${r?`: ${r}`:""}`,e)}static invalidRequest(e,r){return new t(-32600,`Invalid request${r?`: ${r}`:""}`,e)}static methodNotFound(e){return new t(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,r){return new t(-32602,`Invalid params${r?`: ${r}`:""}`,e)}static internalError(e,r){return new t(-32603,`Internal error${r?`: ${r}`:""}`,e)}static authRequired(e,r){return new t(-32e3,`Authentication required${r?`: ${r}`:""}`,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 x7=1,R7=2e4,H0=3e4,T7=3e5,Jr={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"},Qc=class extends Error{retryable=!1;authMethods;constructor(e,r){super(e),this.name="AcpAuthRequiredError",this.authMethods=r}};function el(t,e){if(t instanceof Qc)return t;let r=t,n=Array.isArray(r?.data?.authMethods)?r.data.authMethods:[];if(r?.code===-32e3||n.length>0||/auth(?:entication|orization)?\s+required/i.test(r?.message??"")){let i=n[0],s=i?.description||(i?.name?`Use "${i.name}".`:"");return new Qc(`Authentication required.${s?` ${s}`:""}`,n)}if(e&&e.length>0){let i=e[0],s=r?.data?.details||i?.description||(i?.name?`Authentication required. Use "${i.name}".`:r?.message||"Authentication required.");return new Qc(s,e)}return null}function P7(t){let e=t;if(!e||typeof e.message!="string")return t;let r=e.data,n=typeof r=="string"?r:typeof r?.details=="string"?r.details:typeof r?.error=="string"?r.error:typeof r?.message=="string"?r.message:"";if(!n||e.message.includes(n))return t;let o=new Error(`${e.message}: ${n}`);return o.name=t instanceof Error?t.name:"Error",Object.assign(o,{code:e.code,data:e.data}),o}var Ho=class{conn=null;child=null;onNotification=null;hostHandler=null;attach(e,r,n){if(this.child=e,this.onNotification=r??null,this.hostHandler=n??null,!e.stdin||!e.stdout)throw new Error("ACP adapter: child process has no stdio");let o=U0(S7.toWeb(e.stdin),w7.toWeb(e.stdout));this.conn=new zp(()=>this.buildClient(),o)}buildClient(){let e=()=>this.hostHandler,r=(n,o)=>this.onNotification?.(n,o);return{async sessionUpdate(n){r("session/update",n)},async requestPermission(n){let o=e(),s=(o?.requestPermission?await o.requestPermission(n):{optionId:"allow"})?.optionId;return s?{outcome:{outcome:"selected",optionId:s}}:{outcome:{outcome:"cancelled"}}},async readTextFile(n){return{content:(await e()?.readTextFile?.(n))?.content??""}},async writeTextFile(n){return await e()?.writeTextFile?.(n),{}},async createTerminal(n){return await e()?.createTerminal?.(n)??{terminalId:""}},async terminalOutput(n){return await e()?.terminalOutput?.(n)??{output:"",truncated:!1}},async releaseTerminal(n){return await e()?.releaseTerminal?.(n),{}},async waitForTerminalExit(n){return await e()?.waitForTerminalExit?.(n)??{}},async killTerminal(n){return await e()?.killTerminal?.(n),{}},async extMethod(n,o){return await e()?.extMethod?.(n,o)??{}},async extNotification(n,o){r(n,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,r,n,o){let i,s=new Promise((a,c)=>{i=setTimeout(()=>{try{o?.()}catch{}c(new Error(`ACP ${n} timeout (${r}ms)`))},r)});try{return await Promise.race([e,s])}finally{i&&clearTimeout(i)}}async initialize(e){let r={protocolVersion:x7,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}},clientInfo:{name:"qlogicagent",version:"1.0.0"}},n=await this.withTimeout(this.requireConn().initialize(r),R7,"initialize").catch(i=>{throw el(i)??i}),o=n?.agentCapabilities??{};return{protocolVersion:typeof n?.protocolVersion=="number"?n.protocolVersion:0,agentCapabilities:{loadSession:o.loadSession===!0,mcpCapabilities:o.mcpCapabilities,promptCapabilities:o.promptCapabilities,sessionCapabilities:o.sessionCapabilities,qlogicagent:o.qlogicagent},agentInfo:n?.agentInfo,authMethods:n?.authMethods}}async createSession(e,r){let n={cwd:r.cwd,mcpServers:r.mcpServers??[]};r.additionalDirectories?.length&&(n.additionalDirectories=r.additionalDirectories),r.systemPrompt&&(n._meta={qlogicagent:{systemPrompt:r.systemPrompt}});let o=await this.withTimeout(this.requireConn().newSession(n),H0,"session/new").catch(i=>{throw el(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,r,n,o=T7){let i=this.requireConn(),s=await this.withTimeout(i.prompt({sessionId:r,prompt:[{type:"text",text:n}]}),o,"session/prompt",()=>{i.cancel({sessionId:r}).catch(()=>{})}).catch(a=>{throw el(a)??P7(a)});return{stopReason:s?.stopReason??"end_turn",usage:s?.usage,userMessageId:void 0}}async resumeSession(e,r,n){let o={sessionId:r,cwd:n?.cwd??process.cwd(),mcpServers:n?.mcpServers??[]},i=await this.withTimeout(this.requireConn().loadSession(o),H0,"session/load");return{sessionId:typeof i?.sessionId=="string"?i.sessionId:r}}static translateNotification(e,r){let n=r;if(e==="session/update"){if(!n)return null;let o=n.update;if(!o)return null;let i=o.sessionUpdate,s=n.sessionId;switch(i){case Jr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case Jr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case Jr.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 Jr.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 Jr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case Jr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case Jr.AVAILABLE_COMMANDS_UPDATE:case Jr.CURRENT_MODE_UPDATE:case Jr.CONFIG_OPTION_UPDATE:case Jr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case Jr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as A7}from"node:child_process";import{readFile as I7,writeFile as C7}from"node:fs/promises";import{isAbsolute as z0,normalize as _7,relative as E7,resolve as M7,sep as $7}from"node:path";function D7(t){let e=t.options;if(!Array.isArray(e)||e.length===0)return"allow";let r=e.filter(c=>!!c&&typeof c=="object"),n=c=>typeof c.optionId=="string"&&c.optionId.trim()?c.optionId:void 0;if(r.find(c=>n(c)==="allow"))return"allow";let i=r.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/allow/i.test(l)}),s=i?n(i):void 0;if(s)return s;let a=r.find(c=>{let l=[c.optionId,c.kind,c.name].filter(d=>typeof d=="string").join(" ");return/reject|deny|cancel/i.test(l)});return n(a??{})??n(r[0]??{})??"allow"}function gR(t){let e=new Map,r=0,n=i=>{let s=z0(i)?_7(i):M7(t.cwd,i),a=E7(t.cwd,s);if(a===".."||a.startsWith(`..${$7}`)||z0(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:D7(i)}},async readTextFile(i){return{content:await I7(n(i.path),"utf8")}},async writeTextFile(i){return await C7(n(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?n(String(l)):t.cwd,p=i.env,m={...process.env,...p&&typeof p=="object"?p:{}},f=A7(s,c,{cwd:d,env:m,stdio:["ignore","pipe","pipe"]}),g=`term-${++r}`,h={child:f,output:"",exitStatus:null,exit:new Promise(y=>{f.on("exit",(v,k)=>{let w={exitCode:v,signal:k};h.exitStatus=w,y(w)}),f.on("error",()=>{let v={exitCode:null,signal:null};h.exitStatus=v,y(v)})})};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 tl=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{execFile as N7,execFileSync as O7,execSync as K0}from"node:child_process";import{existsSync as Bp,mkdirSync as j7,readFileSync as yR,readdirSync as L7,writeFileSync as U7}from"node:fs";import{homedir as F7,platform as H7,tmpdir as z7}from"node:os";import{dirname as B7,join as Gn}from"node:path";import{promisify as q7}from"node:util";var W7=q7(N7),nl={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:!1,apiKeyEnvVar:"GEMINI_API_KEY"},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"},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"}},K7=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],B0={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"}},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"}},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"}},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",docsUrl:"https://docs.github.com/copilot/concepts/agents/about-copilot-cli"}},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",docsUrl:"https://cursor.com/cli"}},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"}},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",docsUrl:"https://github.com/MoonshotAI/kimi-cli"}},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"}},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"}},kiro:{brandId:"kiro",category:"coding",integration:"acp",keySource:"direct",authMode:"key",install:{cliCommand:"kiro-cli",docsUrl:"https://kiro.dev/docs"}},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"}},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",docsUrl:"https://github.com/openclaw/openclaw"}},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",docsUrl:"https://github.com/NousResearch/hermes-agent"}}};function ra(t){let e=nl[t];if(e)return B0[t]?{...e,...B0[t]}:e}function vR(){return K7.map(t=>{let e=ra(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Ei=H7()==="win32",G7=5*6e4,rl,q0=new Map;function hR(t){try{let e=Ei?`where ${t}`:`which ${t}`;return K0(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function V7(t,e){let r=i=>{let s=i.match(/^(\d+)\.(\d+)\.(\d+)/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:[0,0,0]},n=r(t),o=r(e);for(let i=0;i<3;i+=1)if(n[i]!==o[i])return o[i]-n[i];return e.localeCompare(t)}function Z7(){if(!Ei)return null;let t=[process.env.COPILOT_CACHE_HOME?Gn(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?Gn(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?Gn(process.env.COPILOT_HOME,"pkg","win32-x64"):null,Gn(F7(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let r=L7(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name).sort(V7);for(let n of r){let o=Gn(e,n,"npm-loader.js");if(Bp(o)&&Z0(o))return o}}catch{}return null}function J7(t){return t.id==="copilot"?Z7()??hR(t.cliCommand):hR(t.cliCommand)}function X7(t,e){return O7(Ei?"cmd.exe":"npm",Ei?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"]}).trim()}async function Y7(t,e){let{stdout:r}=await W7(Ei?"cmd.exe":"npm",Ei?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function Q7(t){let e=t.trim().replace(/^["']|["']$/g,"");if(!e||e.startsWith("-"))return null;if(e.startsWith("@")){let n=e.indexOf("@",1);return n>0?e.slice(0,n):e}let r=e.indexOf("@");return r>0?e.slice(0,r):e}function bR(t){if(!t)return null;let e=t.trim().split(/\s+/).filter(Boolean);if(e[0]!=="npm"&&e[0]!=="npm.cmd")return null;let r=e.findIndex(n=>n==="i"||n==="install"||n==="add");if(r<0)return null;for(let n=r+1;n<e.length;n+=1){let o=e[n];if(!(o==="-g"||o==="--global")){if(o.startsWith("--")&&!o.includes("=")){n+=1;continue}if(!o.startsWith("-"))return Q7(o)}}return null}function qp(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function eee(t,e){let r=i=>{let s=qp(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}},n=r(t),o=r(e);for(let i=0;i<3;i+=1)if(n.nums[i]!==o.nums[i])return n.nums[i]-o.nums[i];return n.pre===o.pre?0:n.pre?o.pre?n.pre.localeCompare(o.pre):-1:1}function tee(t,e){return!t||!e?!1:eee(t,e)>0}function ree(){if(rl!==void 0)return rl;try{rl=X7(["root","-g"],3e3)||null}catch{rl=null}return rl}function kR(t){if(!t)return null;let e=ree();if(!e)return null;let r=Gn(e,...t.split("/"),"package.json");try{let n=JSON.parse(yR(r,"utf8"));return typeof n.version=="string"?n.version:null}catch{return null}}function nee(t){let e=bR(t?.npm);return kR(e)}function G0(t,e){return kR(bR(t.install?.npm))??qp(e)??e??void 0}async function oee(t){if(!t)return null;let e=q0.get(t);if(e&&Date.now()-e.timestamp<G7)return e.version;let r=null;try{let n=await Y7(["view",t,"version","--json"],12e3),o=n?JSON.parse(n):null;r=typeof o=="string"?o:qp(n)}catch{r=null}return q0.set(t,{timestamp:Date.now(),version:r}),r}async function V0(t){let e=t.map(async({id:n,entry:o,detectedVersion:i})=>{let s=bR(o.install?.npm),a=kR(s)??qp(i)??i??void 0;if(!s||!a)return null;let c=await oee(s)??void 0;return c?{id:n,packageName:s,installedVersion:a,latestVersion:c,updateAvailable:tee(c,a)}:null});return(await Promise.all(e)).filter(n=>n!==null)}function Z0(t){try{let e=t.endsWith("npm-loader.js")?`"${process.execPath}" "${t}" version`:`"${t}" version`;return K0(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}function iee(t,e){if(!Ei)return{cliPath:t,acpArgs:e};if(t.endsWith("npm-loader.js")){let n=e.includes("--no-auto-update");return{cliPath:process.execPath,acpArgs:[t,...e,...n?[]:["--no-auto-update"]]}}let r=see(t);return r?{cliPath:process.execPath,acpArgs:[r,...e]}:{cliPath:t,acpArgs:e}}function see(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),r=[`${e}.cmd`,`${e}.ps1`,e];for(let n of r){if(!Bp(n))continue;let o;try{o=yR(n,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=Gn(B7(e),s);if(Bp(a))return a}return null}var aee=6e4;function cee(t,e,r){let n={};return t?.env&&Object.assign(n,t.env),r&&Object.assign(n,r),t?.apiKeyEnvVar&&e?.apiKey&&(n[t.apiKeyEnvVar]=e.apiKey),t?.baseUrlEnvVar&&e?.baseUrl&&(n[t.baseUrlEnvVar]=e.baseUrl),e?.env&&Object.assign(n,e.env),Object.keys(n).length>0?n:void 0}var W0=new Set(["codex","qwen","opencode"]);function lee(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function dee(t){let e=Gn(z7(),"qlogicagent-codex-model-catalog");j7(e,{recursive:!0});let r=Gn(e,`${lee(t)}.json`),n=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(!Bp(r)||yR(r,"utf8")!==n)&&U7(r,n,"utf8"),r}function uee(t,e){let r={};if(!t||t.authMode==="oauth"||t.keySource==="none")return r;let{apiKeyEnvVar:n,baseUrlEnvVar:o}=t;if(t.keySource==="llmrouter"){n&&e.llmrouterKey&&(r[n]=e.llmrouterKey);let i=e.getLlmrouterBaseUrl?.(t.id,t)??e.llmrouterBaseUrl;o&&i&&(r[o]=i),W0.has(t.id)&&e.llmrouterModel&&(r.OPENAI_MODEL=e.llmrouterModel)}else if(t.keySource==="direct"){let i=e.getDirectKey?.(t.id);n&&i&&(r[n]=i)}if(Object.keys(r).length===0&&e.passthroughModel?.apiKey&&W0.has(t.id)){let i=e.passthroughModel;r.OPENAI_API_KEY=i.apiKey,i.baseUrl&&(r.OPENAI_BASE_URL=i.baseUrl),i.model&&(r.OPENAI_MODEL=i.model)}return r}function pee(t,e,r,n){if(t?.id!=="codex"||t.keySource!=="llmrouter"||!r.OPENAI_API_KEY||e.some(s=>s.includes("model_provider")||s.includes("model_providers.")))return e;let o=r.OPENAI_BASE_URL,i=n.llmrouterModel||r.OPENAI_MODEL||"deepseek-v4-flash";return o?[...e,"-c","model_providers.llmrouter.name=llmrouter","-c",`model_providers.llmrouter.base_url=${o}`,"-c","model_providers.llmrouter.wire_api=responses","-c","model_providers.llmrouter.env_key=OPENAI_API_KEY","-c","model_provider=llmrouter","-c",`model=${i}`,"-c",`model_catalog_json=${dee(i)}`]:e}var na=class{cache=null;configStore=null;keySources={};setConfigStore(e){this.configStore=e}setKeySources(e){this.keySources=e}scan(e=!1){if(!e&&this.cache&&Date.now()-this.cache.timestamp<aee)return this.cache.agents;let r=[];for(let n of Object.values(nl))r.push(this.detectBackend(n));if(this.configStore?.customAgents)for(let n of Object.values(this.configStore.customAgents))r.push(this.detectCustomAgent(n));return this.cache={agents:r,timestamp:Date.now()},r}list(){return this.cache?this.cache.agents:this.scan()}clearCache(){this.cache=null}detectBackend(e){let r=J7(e),n=this.hasAgentConfig(e.id);if(!r)return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:e.id==="claude"||e.id==="codex",skillsDirs:e.skillsDirs}};let o=ra(e.id),i=Z0(r)??nee(o?.install);return e.id==="copilot"&&!i?{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:"not_installed",authRequired:e.authRequired,hasConfig:n,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:r,version:i??void 0,authRequired:e.authRequired,hasConfig:n,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}}}detectCustomAgent(e){let r=hR(e.cliCommand),n=this.hasAgentConfig(e.id);return{id:e.id,name:e.name,category:"teammate",protocol:"acp",status:r?"available":"not_installed",cliPath:r??void 0,authRequired:e.authRequired??!1,hasConfig:n,supportsBaseUrlOverride:e.supportsBaseUrlOverride??!1,capabilities:{supportsMcp:!0,supportsResume:!1,supportsUsageUpdate:!1,skillsDirs:e.skillsDirs}}}hasAgentConfig(e){if(!this.configStore)return!1;let r=this.configStore.agents[e];return!!(r?.apiKey||r?.baseUrl||r?.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"],r={};for(let n of e){let o=process.env[n];o&&(r[n]=o)}return{id:"qlogicagent",cliPath:process.execPath,acpArgs:[process.argv[1]??""],env:Object.keys(r).length>0?r:void 0,protocol:"acp"}}buildExternalDescriptor(e){if(e==="qlogicagent")return this.buildSelfDescriptor();let r=this.list().find(d=>d.id===e);if(!r||r.protocol!=="acp"||r.status!=="available"||!r.cliPath)return null;let n=ra(e)??nl[e],o=this.configStore?.agents[e],i=this.configStore?.customAgents?.[e],s=o?.customArgs?.length?o.customArgs:i?.acpArgs??n?.acpArgs??[],a=o?.customCliPath?{cliPath:o.customCliPath,acpArgs:s}:iee(r.cliPath,s),c=uee(n,this.keySources),l=o?.customArgs?.length?a.acpArgs:pee(n,a.acpArgs,c,this.keySources);return{id:e,cliPath:a.cliPath,acpArgs:l,env:cee(n,o,c),protocol:"acp"}}isAgentReady(e){if(e==="qlogicagent")return!0;let r=this.buildExternalDescriptor(e);if(!r)return!1;let n=ra(e)??nl[e];return n?.apiKeyEnvVar&&n.authMode!=="oauth"?!!r.env?.[n.apiKeyEnvVar]:!0}};var SR="https://registry.npmmirror.com",oa="https://pypi.tuna.tsinghua.edu.cn/simple",wR="https://registry.npmmirror.com/-/binary";function mee(){return{npm_config_registry:SR,PIP_INDEX_URL:oa,UV_DEFAULT_INDEX:oa,UV_INDEX_URL:oa,UV_PYTHON_INSTALL_MIRROR:`${wR}/python-build-standalone`,NODEJS_ORG_MIRROR:`${wR}/node`,npm_config_disturl:`${wR}/node`}}var J0=Object.keys(mee());var wee=1;function See(t,e){return{jsonrpc:"2.0",id:wee++,method:t,params:e,meta:zy(t)}}var xee=["NODE_ENV","HOME","PATH","TERM","OPENAI_API_KEY","OPENAI_BASE_URL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","QLOGIC_LLMROUTER_BASE_URL","QLOGIC_LLMROUTER_ACCESS_TOKEN","QLOGIC_LLMROUTER_USER_ID","QLOGIC_LLMROUTER_INFERENCE_KEY","QLOGIC_LLMROUTER_EMBEDDING_MODEL","QLOGIC_LLMROUTER_EMBEDDING_DIMENSIONS","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy",...J0],Ree=["127.0.0.1","localhost","::1"];function Tee(t){let r=`${t.NO_PROXY??""},${t.no_proxy??""}`.split(",").map(i=>i.trim()).filter(Boolean),n=new Set(r.map(i=>i.toLowerCase()));for(let i of Ree)n.has(i.toLowerCase())||(r.push(i),n.add(i.toLowerCase()));let o=r.join(",");return t.NO_PROXY=o,t.no_proxy=o,t}function Pee(t){let e={};for(let r of xee)process.env[r]&&(e[r]=process.env[r]);return e.QLOGICAGENT_MEMBER_ID=t.memberId,e.QLOGICAGENT_MEMBER_NAME=t.name,t.agentType&&(e.QLOGICAGENT_AGENT_TYPE=t.agentType),t.env&&Object.assign(e,t.env),Tee(e)}function X0(t){return["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_MODEL","CODEX_API_KEY","NO_PROXY"].map(r=>{let n=t[r];return/API_KEY|TOKEN|SECRET|PASSWORD/i.test(r)?`${r}=${n?"<set>":"<unset>"}`:`${r}=${n||"<unset>"}`}).join(", ")}var RR=Gh,Aee=Vh,ia=Zh,Y0=Jh;function Iee(t){return new Promise(e=>setTimeout(e,t))}function Cee(t){return t.replace(/[<>:"/\\|?*\x00-\x1F]/g,"-")}function _ee(t,e){if(process.platform==="win32"&&typeof e=="number"&&e>0)try{fee("taskkill",["/PID",String(e),"/T","/F"],()=>{});return}catch{}try{t.kill("SIGTERM"),setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},1e4)}catch{}}var $r=class t{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let r=gee(ol(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=ol(r,"dist","cli.js"),this.mcpBridgeScriptPath=ol(r,"dist","runtime","infra","mcp-bridge-server.js")}slog(e,r,n,o){let s=`[${new Date().toISOString()}] [${e}] [agent:${r}] [${n}] ${o}`;e==="warn"?this.callbacks.log?.warn(s):this.callbacks.log?.info(s)}async spawn(e){if(this.processes.has(e.memberId))throw new Error(`Agent process "${e.memberId}" already spawned`);let r=this.callbacks.log,n=Pee(e),o={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now()};if(e.external)return this.spawnAcpAgentWithRetry(e,o,n);let i=[this.cliBinaryPath];e.verbose&&i.push("--verbose"),this.slog("info",e.memberId,"spawn",`spawning ${e.name} in ${e.cwd}`);let s=xR(process.execPath,i,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});o.pid=s.pid??-1;let a=new Map;this.processes.set(e.memberId,{handle:o,child:s,pendingRpc:a}),Wp({input:s.stdout,crlfDelay:Number.POSITIVE_INFINITY}).on("line",l=>{let d=l.trim();if(d)try{let p=JSON.parse(d),m="id"in p,f="method"in p&&typeof p.method=="string";if(m&&f){this.handleChildHostRequest(e.memberId,p);return}if(m){let g=a.get(p.id);if(g){clearTimeout(g.timer),a.delete(p.id);let h=p;h.error?g.reject(new Error(h.error.message)):g.resolve(h.result)}return}if(f){let g=Ho.translateNotification(p.method,p.params),h=g?.method??p.method,y=g?.params??p.params;this.captureChildProgress(e.memberId,h,y),this.callbacks.onNotification?.(e.memberId,h,y)}}catch{this.slog("warn",e.memberId,"parse",`invalid JSON: ${d.slice(0,200)}`)}}),s.stderr&&Wp({input:s.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",d=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${d}`)}),s.on("exit",(l,d)=>{o.state!=="killed"&&(o.state=l===0?"completed":"failed"),o.endedAt=Date.now(),l!==0&&!o.error&&(o.error=`Process exited with code ${l} (signal: ${d})`);for(let[m,f]of a)clearTimeout(f.timer),f.reject(new Error(`Agent process exited (code=${l})`)),a.delete(m);this.callbacks.onStateChange?.(e.memberId,o.state),this.callbacks.onExit?.(e.memberId,l,d),this.slog("info",e.memberId,"exit",`exited (code=${l}, signal=${d})`)}),s.on("error",l=>{o.state="failed",o.error=l.message,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.slog("warn",e.memberId,"error",l.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{await this.sendRpc(e.memberId,"initialize",{protocolVersion:1,clientInfo:{name:"qlogicagent-team-leader",version:"1.0.0"},clientCapabilities:{qlogicagent:{version:1,events:!0,methods:!0,orchestration:!0}}},15e3);let l=hee(),d={sessionId:l,cwd:e.cwd,_meta:{permissions:{mode:"full_access"},...e.systemPrompt?{appendSystemPrompt:e.systemPrompt}:{}}};await this.sendRpc(e.memberId,"session/new",d,15e3),o.sessionId=l;let p=[["provider",e.provider],["model",e.model],["apiKey",e.apiKey],["baseUrl",e.baseUrl]];for(let[m,f]of p)f&&await this.sendRpc(e.memberId,"session/set_config_option",{sessionId:l,option:m,value:f},15e3);o.state="ready",this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`initialized (pid=${o.pid}, session=${l})`)}catch(l){throw o.state="failed",o.error=`Initialize handshake failed: ${l instanceof Error?l.message:String(l)}`,o.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.kill(e.memberId),new Error(o.error)}return o}async sendTask(e,r,n){let o=this.processes.get(e);if(!o)throw new Error(`No agent process: ${e}`);o.handle.resultText="",o.handle.acpUpdateTypes=[],o.handle.state="running",this.callbacks.onStateChange?.(e,"running");try{let i;if(o.acpAdapter){let s=o.handle.sessionId??"default",a=Date.now(),c;try{c=await o.acpAdapter.sendPrompt(o.child,s,r,n?.timeout??3e5)}finally{o.handle.acpLastPromptElapsedMs=Date.now()-a}let l=o.handle.resultText??"";c.usage&&o.usageTracker&&o.usageTracker.onPromptResponseUsage(c.usage),i={content:l,stopReason:c.stopReason,diagnostics:this.buildExternalPromptDiagnostics(o,c.stopReason)}}else{let s=n?.sessionId??o.handle.sessionId??"default",a=await this.sendRpc(e,"session/prompt",{sessionId:s,prompt:[{type:"text",text:r}]},n?.timeout??3e5),c=o.handle.resultText??"",l=a&&typeof a.stopReason=="string"?a.stopReason:void 0;i={content:c,stopReason:l}}return o.handle.state="completed",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"completed"),i}catch(i){throw o.handle.state="failed",o.handle.error=i instanceof Error?i.message:String(i),o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),i}}buildExternalPromptDiagnostics(e,r){return{stopReason:r,sessionId:e.handle.sessionId,updateTypes:e.handle.acpUpdateTypes??[],stderrLog:e.handle.stderrLogPath,launch:e.handle.acpLaunchDiagnostics,promptElapsedMs:e.handle.acpLastPromptElapsedMs}}async sendRpc(e,r,n,o=3e4){let i=this.processes.get(e);if(!i)throw new Error(`No agent process: ${e}`);let s=See(r,n);return new Promise((a,c)=>{let l=setTimeout(()=>{i.pendingRpc.delete(s.id),c(new Error(`RPC timeout: ${r} (${o}ms)`))},o);i.pendingRpc.set(s.id,{resolve:a,reject:c,timer:l});try{i.child.stdin.write(`${JSON.stringify(s)}
|
|
647
647
|
`)}catch(d){clearTimeout(l),i.pendingRpc.delete(s.id),c(d instanceof Error?d:new Error(String(d)))}})}async sendTaskAsync(e,r,n){let o=this.processes.get(e);if(!o)throw new Error(`No agent process: ${e}`);o.handle.state="running",this.callbacks.onStateChange?.(e,"running");let s={sessionId:n?.sessionId??o.handle.sessionId??"default",prompt:[{type:"text",text:r}]},a=n?.pingInterval??6e4,c=n?.pingTimeout??1e4,l=n?.timeout??0,d=Date.now(),p=l>0?l:1440*60*1e3,m=this.sendRpc(e,"session/prompt",s,p),f=setInterval(async()=>{if(l>0&&Date.now()-d>l){clearInterval(f),o.handle.state="failed",o.handle.error="Task timed out",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed");return}try{await this.sendRpc(e,"ping",void 0,c)}catch{this.slog("warn",o.handle.memberId,"heartbeat","ping failed")}},a);try{let g=await m;return clearInterval(f),o.handle.state="completed",o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"completed"),g}catch(g){throw clearInterval(f),o.handle.state="failed",o.handle.error=g instanceof Error?g.message:String(g),o.handle.endedAt=Date.now(),this.callbacks.onStateChange?.(e,"failed"),g}}async ping(e,r=5e3){let n=this.processes.get(e);if(!n)return!1;if(n.acpAdapter)return!n.child.killed&&n.child.exitCode===null&&n.child.signalCode===null;try{return await this.sendRpc(e,"ping",void 0,r),!0}catch{return!1}}getStatus(e){let r=this.processes.get(e);if(!r)return null;let{handle:n}=r,o=n.state==="starting"||n.state==="ready"||n.state==="running",i=o?Date.now()-n.startedAt:void 0,s=n.lastActivityAt&&o?Math.round((Date.now()-n.lastActivityAt)/1e3):void 0;return{alive:o,state:n.state,runningFor:i,resultText:n.resultText,error:n.error,mediaProgress:n.mediaProgress,lastToolCall:n.lastToolCall,idleFor:s}}handleChildHostRequest(e,r){let o=this.processes.get(e)?.child.stdin;if(!o?.writable)return;let i=s=>{try{o.write(`${JSON.stringify({jsonrpc:"2.0",id:r.id,...s})}
|
|
648
648
|
`)}catch{}};if(r.method==="session/request_permission"){i({result:{optionId:"allow"}});return}i({error:{code:-32601,message:`Method not found: ${r.method}`}})}captureChildProgress(e,r,n){let o=this.processes.get(e);if(!o)return;let{handle:i}=o;switch(i.lastActivityAt=Date.now(),r){case"turn.media_progress":{let s=n;s&&typeof s.taskId=="string"&&(i.mediaProgress={taskId:s.taskId,mediaType:s.mediaType??"unknown",percent:typeof s.percent=="number"?s.percent:0,status:s.status??"unknown",provider:s.provider,updatedAt:Date.now()});break}case"turn.tool_call":{let s=n;s&&typeof s.name=="string"&&(i.lastToolCall=s.name);break}case"turn.delta":{let s=n;if(s&&typeof s.text=="string"){let a=s.text;i.resultText=`${i.resultText??""}${a}`,i.lastDelta=a.slice(-200)}break}case"turn.tool_result":{n&&i.mediaProgress&&i.mediaProgress.percent>=100&&(i.mediaProgress=void 0);break}}}async spawnAcpAgentWithRetry(e,r,n){let o=null;for(let i=0;i<=RR;i++)try{if(i>0){this.processes.delete(e.memberId),r.state="starting",r.error=void 0,r.endedAt=void 0;let s=Aee*i;this.slog("info",e.memberId,"spawn",`retry ${i}/${RR} after ${s}ms`),await Iee(s)}return await this.spawnAcpAgent(e,r,n)}catch(s){if(o=s instanceof Error?s:new Error(String(s)),o.retryable===!1)throw r.state="failed",r.error=o.message,r.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),o;this.slog("warn",e.memberId,"spawn",`attempt ${i+1} failed: ${o.message}`)}throw r.state="failed",r.error=`ACP spawn failed after ${RR+1} attempts: ${o?.message}`,r.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),new Error(r.error)}async spawnAcpAgent(e,r,n){let o=this.callbacks.log,i=e.external;i.env&&Object.assign(n,i.env);let s=[...i.acpArgs];r.acpLaunchDiagnostics={cliPath:i.cliPath,acpArgs:s,cwd:e.cwd,env:X0(n)},this.slog("info",e.memberId,"spawn",`spawning ACP ${e.name} via ${i.cliPath} ${s.join(" ")} env: ${X0(n)}`);let a=xR(i.cliPath,s,{cwd:e.cwd,env:n,stdio:["pipe","pipe","pipe"],detached:!1});r.pid=a.pid??-1;let c=new Map,l=new Ho,d=new tl,{server:p,pipePath:m}=this.createMcpIpcServer(e.memberId);n.QLOGICAGENT_PARENT_RPC=m;let f;if(this.callbacks.sessionDir)try{bee(this.callbacks.sessionDir,{recursive:!0}),r.stderrLogPath=ol(this.callbacks.sessionDir,`${Cee(e.memberId)}.stderr.log`),f=vee(r.stderrLogPath,{flags:"a"})}catch{}let g=gR({cwd:e.cwd,requestPermission:this.callbacks.onPermissionRequest?h=>this.callbacks.onPermissionRequest(e.memberId,h):void 0});this.processes.set(e.memberId,{handle:r,child:a,pendingRpc:c,acpAdapter:l,usageTracker:d,ipcServer:p,ipcPath:m,stderrStream:f,hostHandler:g}),l.attach(a,(h,y)=>{if(h==="session/update"){let k=y?.update?.sessionUpdate;if(typeof k=="string"){let w=this.processes.get(e.memberId),S=w?.handle.acpUpdateTypes??[];w&&!S.includes(k)&&(w.handle.acpUpdateTypes=[...S,k])}}h==="usage_update"&&d.onUsageUpdate(y);let v=Ho.translateNotification(h,y);v?(this.captureChildProgress(e.memberId,v.method,v.params),this.callbacks.onNotification?.(e.memberId,v.method,v.params)):(this.captureChildProgress(e.memberId,h,y),this.callbacks.onNotification?.(e.memberId,h,y))},g),a.stderr&&Wp({input:a.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",y=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${y}`),f?.write(`${new Date().toISOString()} ${y}
|
|
649
649
|
`)}),a.on("exit",(h,y)=>{l.detach(),g.disposeAll();let v=r.state;if(v!=="killed"&&v!=="completed"&&h!==0){let w=this.processes.get(e.memberId)?.runtimeRestartCount??0;if(w<ia){let S=Y0*2**w;this.slog("warn",e.memberId,"crash",`crashed (code=${h}), restarting ${w+1}/${ia} after ${S}ms`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${h}, signal=${y}), restarting`,retriesLeft:ia-w-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,n,w+1).catch(T=>{this.slog("warn",e.memberId,"restart",`failed: ${T instanceof Error?T.message:String(T)}`)})},S);return}}v!=="killed"&&(r.state=h===0?"completed":"failed"),r.endedAt=Date.now(),h!==0&&!r.error&&(r.error=`ACP process exited with code ${h} (signal: ${y})`),this.callbacks.onStateChange?.(e.memberId,r.state),this.callbacks.onExit?.(e.memberId,h,y),this.slog("info",e.memberId,"exit",`ACP exited (code=${h}, signal=${y})`)}),a.on("error",h=>{l.detach(),g.disposeAll(),r.state="failed",r.error=h.message,r.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"spawn",error:h.message,retriesLeft:0}),this.slog("warn",e.memberId,"error",h.message)}),this.callbacks.onStateChange?.(e.memberId,"starting");try{let h=await l.initialize(a);r.state="ready",r.supportsResume=h.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"handshake",`ACP initialized (protocol=${h.protocolVersion}, loadSession=${r.supportsResume}, pid=${r.pid})`);try{let y={cwd:e.cwd},v=[...e.mcpServers??[]],k=this.processes.get(e.memberId),S=h.agentCapabilities.mcpCapabilities?.stdio===!0;k?.ipcPath&&S&&v.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:k.ipcPath,QLOGICAGENT_SESSION_ID:e.memberId}}),v.length>0&&(y.mcpServers=v),e.systemPrompt&&(y.systemPrompt=e.systemPrompt);let T=await l.createSession(a,y);r.sessionId=T.sessionId,this.slog("info",e.memberId,"session",`session created (id=${T.sessionId})`)}catch(y){let v=y instanceof Error?y:new Error(String(y)),k=h.authMethods??[],w=el(v,k);throw this.slog("warn",e.memberId,"session",`session creation failed: ${(w??v).message}`),w??v}this.startHeartbeat(e.memberId,y=>{this.slog("warn",y,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(y,"agents.error",{agentId:y,phase:"heartbeat",error:`Agent ${e.name} stopped responding (${t.MAX_MISSED_BEATS} missed heartbeats)`,retriesLeft:0}),this.kill(y)})}catch(h){let y=h instanceof Error?h:new Error(String(h)),v=y.retryable===!1,k=y.authMethods;throw r.state="failed",r.error=v?y.message:`ACP handshake failed: ${y.message}`,r.endedAt=Date.now(),l.detach(),g.disposeAll(),this.callbacks.onStateChange?.(e.memberId,"failed"),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"handshake",error:r.error,retriesLeft:0,...k?{authMethods:k}:{}}),this.kill(e.memberId),y}return r}kill(e){let r=this.processes.get(e);if(r){this.stopHeartbeat(e),r.handle.state="killed",r.handle.endedAt=Date.now(),r.acpAdapter?.detach(),r.hostHandler?.disposeAll();try{r.ipcServer?.close()}catch{}try{r.stderrStream?.end()}catch{}_ee(r.child,r.handle.pid),this.callbacks.onStateChange?.(e,"killed"),this.slog("info",e,"kill",`killed (pid=${r.handle.pid})`)}}killAll(){for(let e of this.processes.keys())this.kill(e)}getHandle(e){return this.processes.get(e)?.handle}getAllHandles(){return[...this.processes.values()].map(e=>e.handle)}isAlive(e){let r=this.processes.get(e);return!r||r.child.killed||r.child.exitCode!==null?!1:r.handle.state!=="killed"&&r.handle.state!=="failed"}getUsageTracker(e){return this.processes.get(e)?.usageTracker??null}createMcpIpcServer(e){let r=e.replace(/[^a-zA-Z0-9-]/g,"-"),n=process.platform==="win32"?`\\\\.\\pipe\\qlogicagent-mcp-${r}-${Date.now()}`:ol(kee(),`qlogicagent-mcp-${r}-${Date.now()}.sock`),o=yee(i=>{let s="";i.on("data",a=>{s+=a.toString();let c;for(;(c=s.indexOf(`
|
|
@@ -652,9 +652,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
652
652
|
`;try{n.write(c)}catch{}}).catch(a=>{let c=JSON.stringify({jsonrpc:"2.0",id:o.id,error:{code:-32603,message:a instanceof Error?a.message:String(a)}})+`
|
|
653
653
|
`;try{n.write(c)}catch{}})}else if(o.id!==void 0){let i=JSON.stringify({jsonrpc:"2.0",id:o.id,error:{code:-32601,message:`Unknown IPC method: ${o.method}`}})+`
|
|
654
654
|
`;try{n.write(i)}catch{}}}async attemptRuntimeRestart(e,r,n){let o=this.callbacks.log,i=this.processes.get(e.memberId),s=i?.ipcServer,a=i?.ipcPath,c=i?.stderrStream;this.processes.delete(e.memberId);try{let l={memberId:e.memberId,name:e.name,pid:-1,cwd:e.cwd,state:"starting",startedAt:Date.now(),stderrLogPath:i?.handle.stderrLogPath},d=e.external,p=[...d.acpArgs];a&&(r.QLOGICAGENT_PARENT_RPC=a);let m=xR(d.cliPath,p,{cwd:e.cwd,env:r,stdio:["pipe","pipe","pipe"],detached:!1});l.pid=m.pid??-1;let f=new Map,g=new Ho,h=new tl,y=gR({cwd:e.cwd,requestPermission:this.callbacks.onPermissionRequest?w=>this.callbacks.onPermissionRequest(e.memberId,w):void 0});this.processes.set(e.memberId,{handle:l,child:m,pendingRpc:f,acpAdapter:g,usageTracker:h,ipcServer:s,ipcPath:a,stderrStream:c,hostHandler:y,runtimeRestartCount:n}),g.attach(m,(w,S)=>{if(w==="session/update"){let M=S?.update?.sessionUpdate;if(typeof M=="string"){let _=this.processes.get(e.memberId),R=_?.handle.acpUpdateTypes??[];_&&!R.includes(M)&&(_.handle.acpUpdateTypes=[...R,M])}}w==="usage_update"&&h.onUsageUpdate(S);let T=Ho.translateNotification(w,S);T?(this.captureChildProgress(e.memberId,T.method,T.params),this.callbacks.onNotification?.(e.memberId,T.method,T.params)):(this.captureChildProgress(e.memberId,w,S),this.callbacks.onNotification?.(e.memberId,w,S))},y),m.stderr&&Wp({input:m.stderr,crlfDelay:Number.POSITIVE_INFINITY}).on("line",S=>{this.callbacks.log?.debug?.(`[${new Date().toISOString()}] [debug] [agent:${e.memberId}] [stderr] ${S}`),c?.write(`${new Date().toISOString()} ${S}
|
|
655
|
-
`)}),m.on("exit",(w,S)=>{g.detach(),y.disposeAll();let T=l.state;if(T!=="killed"&&T!=="completed"&&w!==0){let _=this.processes.get(e.memberId)?.runtimeRestartCount??n;if(_<ia){let R=Y0*2**_;this.slog("warn",e.memberId,"crash",`crashed again (code=${w}), restart ${_+1}/${ia}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${w}), restarting`,retriesLeft:ia-_-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,r,_+1).catch(C=>{this.slog("warn",e.memberId,"restart",`failed: ${C instanceof Error?C.message:String(C)}`)})},R);return}}T!=="killed"&&(l.state=w===0?"completed":"failed"),l.endedAt=Date.now(),w!==0&&!l.error&&(l.error=`ACP process exited with code ${w} (signal: ${S})`),this.callbacks.onStateChange?.(e.memberId,l.state),this.callbacks.onExit?.(e.memberId,w,S)}),m.on("error",w=>{g.detach(),y.disposeAll(),l.state="failed",l.error=w.message,l.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed")}),this.callbacks.onStateChange?.(e.memberId,"starting");let v=await g.initialize(m);l.state="ready",l.supportsResume=v.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"restart",`ACP restarted (attempt=${n}, protocol=${v.protocolVersion}, loadSession=${l.supportsResume}, pid=${l.pid})`);let k=[...e.mcpServers??[]];a&&k.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:a,QLOGICAGENT_SESSION_ID:e.memberId}});try{if(l.supportsResume&&l.sessionId){let w=await g.resumeSession(m,l.sessionId,{cwd:e.cwd,mcpServers:k.length>0?k:void 0});l.sessionId=w.sessionId,this.slog("info",e.memberId,"session",`session resumed (id=${l.sessionId})`)}else{let w={cwd:e.cwd};k.length>0&&(w.mcpServers=k),e.systemPrompt&&(w.systemPrompt=e.systemPrompt);let S=await g.createSession(m,w);l.sessionId=S.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,w=>{this.slog("warn",w,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(w,"agents.error",{agentId:w,phase:"heartbeat",error:`Agent ${e.name} stopped responding`,retriesLeft:0}),this.kill(w)})}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 ${n} 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,r){this.stopHeartbeat(e),this.missedBeats.set(e,0);let n=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),r?.(e))},t.HEARTBEAT_INTERVAL);this.heartbeatTimers.set(e,n)}stopHeartbeat(e){let r=this.heartbeatTimers.get(e);r&&(clearInterval(r),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 r=this.processes.get(e);r&&(this.stopHeartbeat(e),(r.handle.state==="running"||r.handle.state==="starting"||r.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 Q0}from"node:child_process";var tN=/[|&;><$`(){}]/;function Eee(t,e){let r=e==="win32",n=e==="darwin",o=n?[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=tN.test(i);if(!(s&&r)&&!(i.startsWith("brew ")&&!n))return{command:i,shell:s}}return null}function Mee(t,e){if(e!=="cn")return t;let r=t.trim();return/^npm\b/.test(r)&&!/(?:^|\s)--registry(?:\s|=)/.test(r)?`${r} --registry ${SR}`:/^uv\b/.test(r)&&!/(?:^|\s)--(?:default-)?index(?:-url)?(?:\s|=)/.test(r)?`${r} --default-index ${oa}`:/^(?:pipx|pip3?|python -m pip)\b/.test(r)&&!/(?:^|\s)--index-url(?:\s|=)/.test(r)?`${r} --index-url ${oa}`:r}function eN(t,e,r,n){return new Promise(o=>{let i;try{i=r(t,e)}catch(s){n({type:"log",stream:"stderr",chunk:s instanceof Error?s.message:String(s)}),o(1);return}i.stdout?.on("data",s=>n({type:"log",stream:"stdout",chunk:s.toString()})),i.stderr?.on("data",s=>n({type:"log",stream:"stderr",chunk:s.toString()})),i.on("error",s=>{n({type:"log",stream:"stderr",chunk:s.message}),o(1)}),i.on("close",s=>o(s))})}var $ee=(t,e)=>{if(e)return Q0(t,{shell:!0,stdio:["ignore","pipe","pipe"]});let r=t.split(/\s+/).filter(Boolean);return Q0(r[0],r.slice(1),{stdio:["ignore","pipe","pipe"]})};async function rN(t,e,r={}){let n=r.platform??process.platform,o=r.spawnImpl??$ee,i=Eee(t,n);if(!i){let d=`No install command available for ${n}`;return e({type:"state",state:"failed"}),e({type:"done",ok:!1,error:d}),{ok:!1,error:d}}let s=Mee(i.command,r.mirror);e({type:"state",state:"installing"});let a=await eN(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 eN(c,tN.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}}var kt=new Map,Dee=10*6e4,Nee=6e4,Oee=6,Mi=null;function Kp(t,e,r){return`${t}\0${e}\0${r??"default"}`}function il(t){try{t.manager.kill(t.memberId)}catch{}try{t.manager.dispose()}catch{}}function nN(t){let e=kt.get(t);if(e){if(!e.manager.isAlive(e.memberId)){kt.delete(t),il(e);return}return e}}function oN(t,e){let r=kt.get(t);r&&r!==e&&(kt.delete(t),il(r)),kt.set(t,e),jee(),Uee()}function iN(t,e){let r=kt.get(t);if(!r)return;if(!r.manager.isAlive(r.memberId)){kt.delete(t),il(r);return}kt.delete(t);let n=kt.get(e);return n&&n!==r&&(kt.delete(e),il(n)),kt.set(e,r),r.lastUsed=Date.now(),r}var Gp="__warm__";function sl(t){let e=kt.get(t);e&&(kt.delete(t),il(e))}function sN(){for(let t of[...kt.keys()])sl(t);Mi&&(clearInterval(Mi),Mi=null)}function jee(){for(;kt.size>Oee;){let t=null,e=Number.POSITIVE_INFINITY;for(let[r,n]of kt)n.holder.current||n.lastUsed<e&&(e=n.lastUsed,t=r);if(!t)break;sl(t)}}function Lee(t){for(let[e,r]of[...kt.entries()])r.holder.current||t-r.lastUsed>Dee&&sl(e)}function Uee(){Mi||(Mi=setInterval(()=>Lee(Date.now()),Nee),typeof Mi.unref=="function"&&Mi.unref())}import{randomUUID as Fee}from"node:crypto";var sa=new Map;function Hee(t,e){let r=sa.get(t);return r&&(clearTimeout(r.timer),r.resolve(null),sa.delete(t)),new Promise(n=>{let o=setTimeout(()=>{sa.delete(t),n(null)},e);typeof o.unref=="function"&&o.unref(),sa.set(t,{resolve:n,timer:o})})}function aN(t,e){let r=sa.get(t);return r?(clearTimeout(r.timer),sa.delete(t),r.resolve(e),!0):!1}function zee(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}async function cN(t,e){let r=e.turnContext(),n=t.toolCall&&typeof t.toolCall=="object"?t.toolCall:{},o=typeof t.permissionId=="string"&&t.permissionId?t.permissionId:Fee(),i=Array.isArray(t.options)?t.options:[];if(r?.turnId&&e.sendNotification){e.sendNotification("agents.prompt.approval",{agentId:e.agentId,sessionId:r.sessionId,turnId:r.turnId,requestId:r.requestId,approvalId:o,callId:typeof n.toolCallId=="string"?n.toolCallId:o,toolName:typeof n.title=="string"?n.title:typeof t.toolName=="string"?t.toolName:"operation",arguments:zee(n.rawInput),message:typeof t.message=="string"?t.message:void 0,category:typeof t.category=="string"?t.category:"destructive",options:i});let a=await Hee(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 qee(t){let e=t?.rawInput;if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}function Wee(t){let e=t?.content;if(Array.isArray(e)){let r=e.map(n=>{if(!n||typeof n!="object")return"";let o=n;return typeof o.text=="string"?o.text:typeof o.content=="string"?o.content:""}).join("");if(r)return r.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 dN(t){let e=t?.authMethods;return Array.isArray(e)&&e.length>0?e:void 0}function uN(t){return t instanceof Error?t.message:String(t)}async function Kee(t){let e=dN(t.error);if(!t.sessionId||!e)return;let r=uN(t.error);await qr(t.sessionId,{role:"user",content:t.prompt},t.projectRoot,t.turnId),await qr(t.sessionId,{role:"assistant",content:r,blocks:[{type:"auth_prompt",agentId:t.agentId,message:r,authMethods:e}]},t.projectRoot,t.turnId);let n=Nt(t.sessionId,t.projectRoot),o=await us(t.sessionId,t.projectRoot);await st(t.sessionId,{type:"personal",...t.projectId?{projectId:t.projectId}:{},...o!==null?{messageCount:o}:{},...n?.title?{}:{title:Ja(t.prompt,"External agent login required")},...n?.agentId?{}:{agentId:t.agentId}},t.projectRoot)}async function pN(t){let e=t.params,r=typeof e?.approvalId=="string"?e.approvalId:"",n=typeof e?.optionId=="string"?e.optionId:"",o=r&&n?aN(r,n):!1;t.id!==void 0&&this.sendResponse(t.id,{ok:o})}async function mN(t){try{let e=t.params,r=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(r.getData());let n=this.acpDetector.scan(e?.force);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function fN(t){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let r=this.acpDetector.list();t.id!==void 0&&this.sendResponse(t.id,r)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function gN(t){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let r=new Map(this.acpDetector.list().map(o=>[o.id,o])),n=vR().map(o=>{let i=r.get(o.id),s=G0(o,i?.version);return{id:o.id,name:o.name,brandId:o.brandId??o.id,category:o.category??"code",integration:o.integration??"acp",authMode:o.authMode??"key",note:o.note,status:i?.status??"not_installed",version:s.installedVersion??i?.version,latestVersion:s.latestVersion,updateAvailable:s.updateAvailable,updatePackageName:s.packageName,install:{docsUrl:o.install?.docsUrl,command:o.install?.npm??o.install?.pip??o.install?.brew??o.install?.curl}}});t.id!==void 0&&this.sendResponse(t.id,{catalog:n})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function hN(t){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let r=new Map(this.acpDetector.list().map(i=>[i.id,i])),n=vR().map(i=>({id:i.id,entry:i,detectedVersion:r.get(i.id)?.version})),o=await V0(n);t.id!==void 0&&this.sendResponse(t.id,{updates:o})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function yN(t){let e=t.params,r=typeof e?.agentId=="string"?e.agentId:void 0,n=typeof e?.mirror=="string"&&e.mirror?e.mirror:process.env.QLOGICAGENT_INSTALL_MIRROR;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId (string) required"});return}let o=ra(r);if(!o?.install){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:`Unknown or non-installable agent: ${r}`});return}try{let i=await rN(o.install,s=>{this.sendNotification?.("agent.install.progress",{agentId:r,event:s})},{mirror:n});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:b.INTERNAL_ERROR,message:i instanceof Error?i.message:String(i)})}}async function vN(t){try{let e=t.params;if(!e?.action||!e?.agent){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"action and agent are required."});return}let r=await this.ensureAgentConfigStore();switch(e.action){case"register":await r.registerCustomAgent(e.agent);break;case"unregister":await r.unregisterCustomAgent(e.agent.id);break;case"update":await r.registerCustomAgent(e.agent);break}this.acpDetector.setConfigStore(r.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:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function bN(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId is required."});return}let r=await this.ensureAgentConfigStore(),{agentId:n,...o}=e;await r.setAgentConfig(n,o),this.acpDetector.setConfigStore(r.getData()),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function kN(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId is required."});return}let n=(await this.ensureAgentConfigStore()).getAgentConfig(e.agentId);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function wN(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId is required."});return}let r=await this.ensureAgentConfigStore();await r.removeAgentConfig(e.agentId),this.acpDetector.setConfigStore(r.getData()),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function SN(t){try{let e=t.params;if(!e?.url){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.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:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function xN(t){try{let r=(await this.ensureAgentConfigStore()).getGatewayUrl();t.id!==void 0&&this.sendResponse(t.id,{url:r})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function RN(t){try{let r=(await this.ensureAgentConfigStore()).getData(),n=Object.entries(r.agents).map(([o,i])=>({agentId:o,hasApiKey:!!i.apiKey,hasBaseUrl:!!i.baseUrl,hasModel:!!i.model}));t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function TN(t){try{let e=[],r=(n,o)=>{if(n)for(let i of n.getAllHandles())e.push({memberId:i.memberId,name:i.name,pid:i.pid,state:i.state,startedAt:i.startedAt,endedAt:i.endedAt,source:o})};r(this.soloProcessManager,"solo"),r(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:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function PN(t){try{let e=t.params;if(!e?.memberId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"memberId is required."});return}let r=!1;for(let n of[this.soloProcessManager,this.productProcessManager])if(n?.getHandle(e.memberId)){n.kill(e.memberId),r=!0;break}t.id!==void 0&&this.sendResponse(t.id,{ok:r})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function AN(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId is required."});return}let r=Vp.join(pe(),"agent-logs"),n=Vp.join(r,`${e.agentId}.stderr.log`),o="";try{o=lN.readFileSync(n,"utf-8")}catch{}e.tail&&e.tail>0&&o&&(o=o.split(`
|
|
655
|
+
`)}),m.on("exit",(w,S)=>{g.detach(),y.disposeAll();let T=l.state;if(T!=="killed"&&T!=="completed"&&w!==0){let _=this.processes.get(e.memberId)?.runtimeRestartCount??n;if(_<ia){let R=Y0*2**_;this.slog("warn",e.memberId,"crash",`crashed again (code=${w}), restart ${_+1}/${ia}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${w}), restarting`,retriesLeft:ia-_-1}),setTimeout(()=>{this.attemptRuntimeRestart(e,r,_+1).catch(C=>{this.slog("warn",e.memberId,"restart",`failed: ${C instanceof Error?C.message:String(C)}`)})},R);return}}T!=="killed"&&(l.state=w===0?"completed":"failed"),l.endedAt=Date.now(),w!==0&&!l.error&&(l.error=`ACP process exited with code ${w} (signal: ${S})`),this.callbacks.onStateChange?.(e.memberId,l.state),this.callbacks.onExit?.(e.memberId,w,S)}),m.on("error",w=>{g.detach(),y.disposeAll(),l.state="failed",l.error=w.message,l.endedAt=Date.now(),this.callbacks.onStateChange?.(e.memberId,"failed")}),this.callbacks.onStateChange?.(e.memberId,"starting");let v=await g.initialize(m);l.state="ready",l.supportsResume=v.agentCapabilities.loadSession===!0,this.callbacks.onStateChange?.(e.memberId,"ready"),this.slog("info",e.memberId,"restart",`ACP restarted (attempt=${n}, protocol=${v.protocolVersion}, loadSession=${l.supportsResume}, pid=${l.pid})`);let k=[...e.mcpServers??[]];a&&k.push({name:"qlogicagent-tools",command:process.execPath,args:[this.mcpBridgeScriptPath],env:{QLOGICAGENT_PARENT_RPC:a,QLOGICAGENT_SESSION_ID:e.memberId}});try{if(l.supportsResume&&l.sessionId){let w=await g.resumeSession(m,l.sessionId,{cwd:e.cwd,mcpServers:k.length>0?k:void 0});l.sessionId=w.sessionId,this.slog("info",e.memberId,"session",`session resumed (id=${l.sessionId})`)}else{let w={cwd:e.cwd};k.length>0&&(w.mcpServers=k),e.systemPrompt&&(w.systemPrompt=e.systemPrompt);let S=await g.createSession(m,w);l.sessionId=S.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,w=>{this.slog("warn",w,"heartbeat","hang detected \u2014 force-killing"),this.callbacks.onNotification?.(w,"agents.error",{agentId:w,phase:"heartbeat",error:`Agent ${e.name} stopped responding`,retriesLeft:0}),this.kill(w)})}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 ${n} 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,r){this.stopHeartbeat(e),this.missedBeats.set(e,0);let n=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),r?.(e))},t.HEARTBEAT_INTERVAL);this.heartbeatTimers.set(e,n)}stopHeartbeat(e){let r=this.heartbeatTimers.get(e);r&&(clearInterval(r),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 r=this.processes.get(e);r&&(this.stopHeartbeat(e),(r.handle.state==="running"||r.handle.state==="starting"||r.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 Q0}from"node:child_process";var tN=/[|&;><$`(){}]/;function Eee(t,e){let r=e==="win32",n=e==="darwin",o=n?[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=tN.test(i);if(!(s&&r)&&!(i.startsWith("brew ")&&!n))return{command:i,shell:s}}return null}function Mee(t,e){if(e!=="cn")return t;let r=t.trim();return/^npm\b/.test(r)&&!/(?:^|\s)--registry(?:\s|=)/.test(r)?`${r} --registry ${SR}`:/^uv\b/.test(r)&&!/(?:^|\s)--(?:default-)?index(?:-url)?(?:\s|=)/.test(r)?`${r} --default-index ${oa}`:/^(?:pipx|pip3?|python -m pip)\b/.test(r)&&!/(?:^|\s)--index-url(?:\s|=)/.test(r)?`${r} --index-url ${oa}`:r}function eN(t,e,r,n){return new Promise(o=>{let i;try{i=r(t,e)}catch(s){n({type:"log",stream:"stderr",chunk:s instanceof Error?s.message:String(s)}),o(1);return}i.stdout?.on("data",s=>n({type:"log",stream:"stdout",chunk:s.toString()})),i.stderr?.on("data",s=>n({type:"log",stream:"stderr",chunk:s.toString()})),i.on("error",s=>{n({type:"log",stream:"stderr",chunk:s.message}),o(1)}),i.on("close",s=>o(s))})}var $ee=(t,e)=>{if(e)return Q0(t,{shell:!0,stdio:["ignore","pipe","pipe"]});let r=t.split(/\s+/).filter(Boolean);return Q0(r[0],r.slice(1),{stdio:["ignore","pipe","pipe"]})};async function rN(t,e,r={}){let n=r.platform??process.platform,o=r.spawnImpl??$ee,i=Eee(t,n);if(!i){let d=`No install command available for ${n}`;return e({type:"state",state:"failed"}),e({type:"done",ok:!1,error:d}),{ok:!1,error:d}}let s=Mee(i.command,r.mirror);e({type:"state",state:"installing"});let a=await eN(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 eN(c,tN.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}}var kt=new Map,Dee=10*6e4,Nee=6e4,Oee=6,Mi=null;function Kp(t,e,r){return`${t}\0${e}\0${r??"default"}`}function il(t){try{t.manager.kill(t.memberId)}catch{}try{t.manager.dispose()}catch{}}function nN(t){let e=kt.get(t);if(e){if(!e.manager.isAlive(e.memberId)){kt.delete(t),il(e);return}return e}}function oN(t,e){let r=kt.get(t);r&&r!==e&&(kt.delete(t),il(r)),kt.set(t,e),jee(),Uee()}function iN(t,e){let r=kt.get(t);if(!r)return;if(!r.manager.isAlive(r.memberId)){kt.delete(t),il(r);return}kt.delete(t);let n=kt.get(e);return n&&n!==r&&(kt.delete(e),il(n)),kt.set(e,r),r.lastUsed=Date.now(),r}var Gp="__warm__";function sl(t){let e=kt.get(t);e&&(kt.delete(t),il(e))}function sN(){for(let t of[...kt.keys()])sl(t);Mi&&(clearInterval(Mi),Mi=null)}function jee(){for(;kt.size>Oee;){let t=null,e=Number.POSITIVE_INFINITY;for(let[r,n]of kt)n.holder.current||n.lastUsed<e&&(e=n.lastUsed,t=r);if(!t)break;sl(t)}}function Lee(t){for(let[e,r]of[...kt.entries()])r.holder.current||t-r.lastUsed>Dee&&sl(e)}function Uee(){Mi||(Mi=setInterval(()=>Lee(Date.now()),Nee),typeof Mi.unref=="function"&&Mi.unref())}import{randomUUID as Fee}from"node:crypto";var sa=new Map;function Hee(t,e){let r=sa.get(t);return r&&(clearTimeout(r.timer),r.resolve(null),sa.delete(t)),new Promise(n=>{let o=setTimeout(()=>{sa.delete(t),n(null)},e);typeof o.unref=="function"&&o.unref(),sa.set(t,{resolve:n,timer:o})})}function aN(t,e){let r=sa.get(t);return r?(clearTimeout(r.timer),sa.delete(t),r.resolve(e),!0):!1}function zee(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}async function cN(t,e){let r=e.turnContext(),n=t.toolCall&&typeof t.toolCall=="object"?t.toolCall:{},o=typeof t.permissionId=="string"&&t.permissionId?t.permissionId:Fee(),i=Array.isArray(t.options)?t.options:[];if(r?.turnId&&e.sendNotification){e.sendNotification("agents.prompt.approval",{agentId:e.agentId,sessionId:r.sessionId,turnId:r.turnId,requestId:r.requestId,approvalId:o,callId:typeof n.toolCallId=="string"?n.toolCallId:o,toolName:typeof n.title=="string"?n.title:typeof t.toolName=="string"?t.toolName:"operation",arguments:zee(n.rawInput),message:typeof t.message=="string"?t.message:void 0,category:typeof t.category=="string"?t.category:"destructive",options:i});let a=await Hee(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 qee(t){let e=t?.rawInput;if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}function Wee(t){let e=t?.content;if(Array.isArray(e)){let r=e.map(n=>{if(!n||typeof n!="object")return"";let o=n;return typeof o.text=="string"?o.text:typeof o.content=="string"?o.content:""}).join("");if(r)return r.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 dN(t){let e=t?.authMethods;return Array.isArray(e)&&e.length>0?e:void 0}function uN(t){return t instanceof Error?t.message:String(t)}async function Kee(t){let e=dN(t.error);if(!t.sessionId||!e)return;let r=uN(t.error);await qr(t.sessionId,{role:"user",content:t.prompt},t.projectRoot,t.turnId),await qr(t.sessionId,{role:"assistant",content:r,blocks:[{type:"auth_prompt",agentId:t.agentId,message:r,authMethods:e}]},t.projectRoot,t.turnId);let n=Nt(t.sessionId,t.projectRoot),o=await us(t.sessionId,t.projectRoot);await st(t.sessionId,{type:"personal",...t.projectId?{projectId:t.projectId}:{},...o!==null?{messageCount:o}:{},...n?.title?{}:{title:Ja(t.prompt,"External agent login required")},...n?.agentId?{}:{agentId:t.agentId}},t.projectRoot)}async function pN(t){let e=t.params,r=typeof e?.approvalId=="string"?e.approvalId:"",n=typeof e?.optionId=="string"?e.optionId:"",o=r&&n?aN(r,n):!1;t.id!==void 0&&this.sendResponse(t.id,{ok:o})}async function mN(t){try{let e=t.params,r=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(r.getData());let n=this.acpDetector.scan(e?.force);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function fN(t){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let r=this.acpDetector.list();t.id!==void 0&&this.sendResponse(t.id,r)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function gN(t){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let r=new Map(this.acpDetector.list().map(o=>[o.id,o])),n=vR().map(o=>{let i=r.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",note:o.note,status:i?.status??"not_installed",version:G0(o,i?.version),install:{docsUrl:o.install?.docsUrl,command:o.install?.npm??o.install?.pip??o.install?.brew??o.install?.curl}}});t.id!==void 0&&this.sendResponse(t.id,{catalog:n})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function hN(t){try{let e=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(e.getData());let r=new Map(this.acpDetector.list().map(i=>[i.id,i])),n=vR().map(i=>({id:i.id,entry:i,detectedVersion:r.get(i.id)?.version})),o=await V0(n);t.id!==void 0&&this.sendResponse(t.id,{updates:o})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function yN(t){let e=t.params,r=typeof e?.agentId=="string"?e.agentId:void 0,n=typeof e?.mirror=="string"&&e.mirror?e.mirror:process.env.QLOGICAGENT_INSTALL_MIRROR;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId (string) required"});return}let o=ra(r);if(!o?.install){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:`Unknown or non-installable agent: ${r}`});return}try{let i=await rN(o.install,s=>{this.sendNotification?.("agent.install.progress",{agentId:r,event:s})},{mirror:n});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:b.INTERNAL_ERROR,message:i instanceof Error?i.message:String(i)})}}async function vN(t){try{let e=t.params;if(!e?.action||!e?.agent){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"action and agent are required."});return}let r=await this.ensureAgentConfigStore();switch(e.action){case"register":await r.registerCustomAgent(e.agent);break;case"unregister":await r.unregisterCustomAgent(e.agent.id);break;case"update":await r.registerCustomAgent(e.agent);break}this.acpDetector.setConfigStore(r.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:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function bN(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId is required."});return}let r=await this.ensureAgentConfigStore(),{agentId:n,...o}=e;await r.setAgentConfig(n,o),this.acpDetector.setConfigStore(r.getData()),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function kN(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId is required."});return}let n=(await this.ensureAgentConfigStore()).getAgentConfig(e.agentId);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function wN(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId is required."});return}let r=await this.ensureAgentConfigStore();await r.removeAgentConfig(e.agentId),this.acpDetector.setConfigStore(r.getData()),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function SN(t){try{let e=t.params;if(!e?.url){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.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:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function xN(t){try{let r=(await this.ensureAgentConfigStore()).getGatewayUrl();t.id!==void 0&&this.sendResponse(t.id,{url:r})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function RN(t){try{let r=(await this.ensureAgentConfigStore()).getData(),n=Object.entries(r.agents).map(([o,i])=>({agentId:o,hasApiKey:!!i.apiKey,hasBaseUrl:!!i.baseUrl,hasModel:!!i.model}));t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function TN(t){try{let e=[],r=(n,o)=>{if(n)for(let i of n.getAllHandles())e.push({memberId:i.memberId,name:i.name,pid:i.pid,state:i.state,startedAt:i.startedAt,endedAt:i.endedAt,source:o})};r(this.soloProcessManager,"solo"),r(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:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function PN(t){try{let e=t.params;if(!e?.memberId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"memberId is required."});return}let r=!1;for(let n of[this.soloProcessManager,this.productProcessManager])if(n?.getHandle(e.memberId)){n.kill(e.memberId),r=!0;break}t.id!==void 0&&this.sendResponse(t.id,{ok:r})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function AN(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId is required."});return}let r=Vp.join(pe(),"agent-logs"),n=Vp.join(r,`${e.agentId}.stderr.log`),o="";try{o=lN.readFileSync(n,"utf-8")}catch{}e.tail&&e.tail>0&&o&&(o=o.split(`
|
|
656
656
|
`).slice(-e.tail).join(`
|
|
657
|
-
`)),t.id!==void 0&&this.sendResponse(t.id,{log:o})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function IN(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId is required."});return}let r=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(r.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:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function CN(t,e,r,n,o,i){let s=Kp(e,n,o),a=nN(s);if(a)return a;if(o!==Gp){let f=iN(Kp(e,n,Gp),s);if(f)return f}let c=`chat-${e}-${Bee().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new $r({onNotification:(f,g,h)=>{let y=l.current;if(!y)return;let v=h;if(g==="turn.delta"){let w=typeof v?.text=="string"?v.text:"";if(!w)return;y.deltas.push(w),y.turnId&&d&&(d("agents.prompt.delta",{agentId:e,sessionId:y.sessionId,turnId:y.turnId,requestId:y.requestId,text:w}),y.streamedAny=!0);return}if(g==="turn.thought_delta"){let w=typeof v?.text=="string"?v.text:"";w&&y.turnId&&d&&d("agents.prompt.delta",{agentId:e,sessionId:y.sessionId,turnId:y.turnId,requestId:y.requestId,text:w,reasoning:!0});return}if(g==="turn.plan"){y.turnId&&d&&d("agents.prompt.plan",{agentId:e,sessionId:y.sessionId,turnId:y.turnId,requestId:y.requestId,steps:Array.isArray(v?.steps)?v.steps:[]});return}if(!y.turnId||!d)return;let k=typeof v?.callId=="string"?v.callId:String(v?.callId??"");g==="turn.tool_call"?d("agents.prompt.tool",{agentId:e,sessionId:y.sessionId,turnId:y.turnId,requestId:y.requestId,event:{kind:"call",callId:k,name:typeof v?.toolName=="string"?v.toolName:typeof v?.name=="string"?v.name:"tool",arguments:qee(v)}}):g==="turn.tool_result"&&d("agents.prompt.tool",{agentId:e,sessionId:y.sessionId,turnId:y.turnId,requestId:y.requestId,event:{kind:"result",callId:k,name:typeof v?.toolName=="string"?v.toolName:"tool",ok:v?.status!=="failed"&&v?.status!=="error",outputPreview:Wee(v)}})},onMcpToolCall:async(f,g,h)=>typeof t.handleMcpToolCall=="function"?t.handleMcpToolCall(f,g,h):{ok:!1,error:"MCP tool call unavailable"},onPermissionRequest:(f,g)=>cN(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:Vp.join(pe(),"agent-logs")});await p.spawn({memberId:c,name:`chat-${e}`,cwd:n,prompt:"",external:r,systemPrompt:i});let m={manager:p,memberId:c,holder:l,lastUsed:Date.now()};return oN(s,m),m}async function _N(t){try{let e=t.params??{},r=typeof e.agentId=="string"?e.agentId.trim():"";if(!r||r==="qlogicagent"){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}let n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData()),this.acpDetector.scan(!1);let o=this.acpDetector.buildExternalDescriptor(r);if(!o){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}let i=typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd();await CN(this,r,o,i,Gp),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 EN(t){try{let e=t.params??{},r=typeof e.agentId=="string"?e.agentId.trim():"",n=typeof e.prompt=="string"?e.prompt:"";if(!r||!n.trim()){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId and prompt are required."});return}let o=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(o.getData()),this.acpDetector.scan(!1);let i=this.acpDetector.buildExternalDescriptor(r);if(!i){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:`Agent ${r} is not available or not ACP-compatible.`});return}let s=typeof e.cwd=="string"&&e.cwd?e.cwd:typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd(),a=typeof e.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:3e5,c=typeof e.sessionId=="string"?e.sessionId:void 0,l=typeof e.turnId=="string"?e.turnId:void 0,d=typeof e.requestId=="string"?e.requestId:void 0,p=typeof e.projectId=="string"?e.projectId:void 0,m=Kp(r,s,c),f=await CN(this,r,i,s,c,typeof e.systemPrompt=="string"?e.systemPrompt:void 0),g={sessionId:c,turnId:l,requestId:d,deltas:[],streamedAny:!1};f.holder.current=g,f.lastUsed=Date.now();let h;try{h=await f.manager.sendTask(f.memberId,n,{timeout:a})}catch(k){throw await Kee({sessionId:c,projectRoot:s,turnId:l,projectId:p,agentId:r,prompt:n,error:k}),sl(m),k}finally{f.holder.current=null}let y=g.deltas.join("")||(typeof h?.content=="string"?h.content:""),v=f.manager.getUsageTracker(f.memberId)?.getUsage();if(c){qr(c,{role:"user",content:n},s,l),y&&qr(c,{role:"assistant",content:y},s,l);let k=Nt(c,s);st(c,{type:"personal",...p?{projectId:p}:{},...k?.title?{}:{title:Ja(n,"External agent session")},...k?.agentId?{}:{agentId:r}},s)}t.id!==void 0&&this.sendResponse(t.id,{ok:!0,agentId:r,content:y,streamed:g.streamedAny,stopReason:h?.stopReason,usage:v?{inputTokens:v.inputTokens,outputTokens:v.outputTokens,totalTokens:v.totalTokens,cacheRead:v.cachedReadTokens,thoughtTokens:v.thoughtTokens,cost:v.cost}:void 0})}catch(e){if(t.id!==void 0){let r=dN(e);this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:uN(e),...r?{data:{authMethods:r}}:{}})}}}ie();import*as ca from"node:fs/promises";import*as zO from"node:path";ms();var Gee=/^[a-z0-9][a-z0-9_.:-]{0,79}$/i,Vee=new Set(["journeyDay","count"]),Zee=new Set(["blocked"]),Jee=new Set(["R0","R1","R2","R3"]),Xee=new Set(["aix","android","darwin","freebsd","ios","linux","openbsd","sunos","win32"]),Yee={"community.journey.view":new Set(["surface","petState","journeyDay","platform"]),"community.share.generated":new Set(["surface","action","source","petState","journeyDay","platform"]),"community.sandbox.violation":new Set(["surface","action","source","ruleId","riskTier","platform","count","blocked"]),"community.desensitization.hit":new Set(["surface","action","source","ruleId","riskTier","platform","count","blocked"]),"registry.install_failed":new Set(["dimension","resourceType","platform"])};function Zp(t,e){if(!e||typeof e!="object"||Array.isArray(e))return;let r=Yee[t],n={};for(let[o,i]of Object.entries(e)){if(!r.has(o))continue;let s=Qee(o,i);s!==void 0&&(n[o]=s)}return Object.keys(n).length>0?n:void 0}function Qee(t,e){if(Vee.has(t))return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=1e5?e:void 0;if(Zee.has(t))return typeof e=="boolean"?e:void 0;if(t==="riskTier")return typeof e=="string"&&Jee.has(e)?e:void 0;if(t==="platform")return typeof e=="string"&&Xee.has(e)?e:void 0;if(typeof e!="string")return;let r=e.trim();return Gee.test(r)?r:void 0}var ete=new Set(["withdrawn","version-available","deprecated","version-yanked","frozen"]);function tte(t){let e=cte(t.baseUrl),r=lte(t.fetchFn??fetch,t.clientVersion),n=t.token.trim();return{async getConsent(){return $N(r,e,n,"GET")},async setConsent(o){return $N(r,e,n,"PUT",o)},async matchRegistry(o){let i=o.intent.trim();if(!i)throw new Error("intent is required.");let s=ute(o.topK),a=await Ne(r,_e(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:i,topK:s,prefer:o.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(Pe(a)&&Array.isArray(a.matches)?a.matches:[]).map(pte).filter(l=>!!l).slice(0,s)},async publishSkill(o){return TR(r,t.baseUrl,n,"skill",o)},async publishPet(o){return TR(r,t.baseUrl,n,"pet",o)},async publishWorkflow(o){return TR(r,t.baseUrl,n,"workflow",o)},async recordSignal(o){let i=encodeURIComponent(o.resourceId.trim());if(!i)throw new Error("resourceId is required.");let s=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${i}/signal`),n,"POST",{event:o.event,attribution:o.attribution?.trim()||void 0,metadata:o.metadata});if(Pe(s)&&s.accepted===!0)return{accepted:!0};throw new Error("Community hub returned an invalid signal response.")},async recordTelemetry(o){let i=Zp(o.event,o.metadata),s=await Ne(r,_e(t.baseUrl,"/api/v15/registry/telemetry"),n,"POST",{event:o.event,metadata:i});if(Pe(s)&&s.accepted===!0)return{accepted:!0};throw new Error("Community hub returned an invalid telemetry response.")},async listSharedResources(){let o=await Ne(r,_e(t.baseUrl,"/api/v15/registry/mine"),n,"GET");return(Pe(o)&&Array.isArray(o.resources)?o.resources:[]).map(Jp).filter(s=>!!s)},async withdrawSharedResource(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("resourceId is required.");let a=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${s}/withdraw`),n,"POST",{reason:i?.trim()||void 0}),c=Jp(a);if(!c)throw new Error("Community hub returned an invalid resource.");return c},async withdrawSharedResources(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/registry/community-consent/withdraw-shared"),n,"POST",{reason:o?.trim()||void 0});return(Pe(i)&&Array.isArray(i.resources)?i.resources:[]).map(Jp).filter(a=>!!a)},async listNotices(o={}){let i=o.includeRead?"?includeRead=true":"",s=await Ne(r,_e(t.baseUrl,`/api/v15/registry/notices${i}`),n,"GET");return(Pe(s)&&Array.isArray(s.notices)?s.notices:[]).map(DN).filter(c=>!!c)},async markNoticeRead(o){if(!Number.isSafeInteger(o)||o<1)throw new Error("noticeId is required.");let i=await Ne(r,_e(t.baseUrl,`/api/v15/registry/notices/${o}/read`),n,"POST"),s=DN(i);if(!s)throw new Error("Community hub returned an invalid notice.");return s},async resolveInstall(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("resourceId is required.");let a=i?.trim(),c=a?`?version=${encodeURIComponent(a)}`:"",l=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${s}/install${c}`),n,"GET"),d=jN(l);if(!d)throw new Error("Community hub returned an invalid install resolution.");return d},async listResourceVersions(o){let i=encodeURIComponent(o.trim());if(!i)throw new Error("resourceId is required.");let s=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${i}/versions`),n,"GET");return(Pe(s)&&Array.isArray(s.versions)?s.versions:[]).map(ote).filter(c=>!!c)},async rateResource(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("resourceId is required.");let a=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${s}/rate`),n,"POST",{stars:i});return MN(a)},async getRatingSummary(o){let i=encodeURIComponent(o.trim());if(!i)throw new Error("resourceId is required.");let s=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${i}/rating`),n,"GET");return MN(s)},async reportResource(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("resourceId is required.");await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${s}/report`),n,"POST",{reason:i?.trim()||void 0})},async listComments(o){let i=encodeURIComponent(o.trim());if(!i)throw new Error("resourceId is required.");let s=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${i}/comments`),n,"GET");return(Pe(s)&&Array.isArray(s.comments)?s.comments:[]).map(rte).filter(c=>!!c)},async postComment(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("resourceId is required.");let a=i?.trim()??"";if(!a)throw new Error("Comment body is required.");let c=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${s}/comments`),n,"POST",{body:a}),l=Pe(c)?c:{};return{id:typeof l.id=="number"?l.id:0,folded:l.folded===!0,createdAt:typeof l.createdAt=="string"?l.createdAt:""}},async emitActivity(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/community/activity"),n,"POST",{id:o.id,type:o.type,ts:o.ts,actorPetId:o.actorPetId,peerRef:o.peerRef,visibility:o.visibility,payload:o.payload});if(!(Pe(i)&&i.accepted===!0))throw new Error("Community hub returned an invalid activity response.")},async recordCommunityReview(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/community/reviews"),n,"POST",{id:o.id,resourceId:o.resourceId,actorPetId:o.actorPetId,experience:o.experience,outcome:o.outcome,contextCategory:o.contextCategory,ts:o.ts});if(!(Pe(i)&&i.accepted===!0))throw new Error("Community hub returned an invalid review response.")},async findReviewAnswers(o,i){let s=o.trim();if(!s)return[];let a=await Ne(r,_e(t.baseUrl,"/api/v15/community/reviews/search"),n,"POST",{query:s,limit:typeof i=="number"&&i>0?Math.min(Math.floor(i),20):void 0});return(Pe(a)&&Array.isArray(a.answers)?a.answers:[]).map(nte).filter(l=>!!l)},async recordCommunityAsk(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/community/asks"),n,"POST",{id:o.id,askerPetId:o.askerPetId,question:o.question,contextCategory:o.contextCategory,ts:o.ts});if(!(Pe(i)&&i.accepted===!0))throw new Error("Community hub returned an invalid ask response.")},async recordCommunityAnswer(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/community/answers"),n,"POST",{id:o.id,askId:o.askId,answererPetId:o.answererPetId,answer:o.answer,ts:o.ts});if(!(Pe(i)&&i.accepted===!0))throw new Error("Community hub returned an invalid answer response.")},async recordCommunityInteraction(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/community/interactions"),n,"POST",{id:o.id,kind:o.kind,actorPetId:o.actorPetId,peerPetId:o.peerPetId,payload:o.payload,ts:o.ts});if(!(Pe(i)&&i.accepted===!0))throw new Error("Community hub returned an invalid interaction response.")},async resolveRuntime(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("runtime id is required.");let a=encodeURIComponent(i.trim());if(!a)throw new Error("platform is required.");let c=await Ne(r,_e(t.baseUrl,`/api/v15/runtime/${s}/resolve?platform=${a}`),n,"GET"),l=ite(c);if(!l)throw new Error("Community hub returned an invalid runtime resolution.");return l}}}async function TR(t,e,r,n,o){let i=Jp(await Ne(t,_e(e,"/api/v15/registry/resources"),r,"POST",{id:o.id,type:n,title:o.title,summary:o.summary,visibility:o.visibility??"public",...o.category?{category:o.category}:{},tags:o.tags??[],manifest:o.manifest}));if(!i)throw new Error("Community hub returned an invalid resource.");if(o.version===void 0&&o.packageGzipBase64===void 0)return{resource:i};if(!o.version?.trim()||!o.packageGzipBase64?.trim())throw new Error("version and packageGzipBase64 must be provided together.");let s=encodeURIComponent(o.id.trim()),a=encodeURIComponent(o.version.trim()),c=mte(await dte(t,_e(e,`/api/v15/registry/resources/${s}/versions/${a}`),r,Buffer.from(o.packageGzipBase64,"base64")));if(!c)throw new Error("Community hub returned an invalid version.");return{resource:i,version:c}}function MN(t){return Pe(t)?{average:typeof t.average=="number"?t.average:0,count:typeof t.count=="number"?t.count:0}:{average:0,count:0}}function rte(t){return!Pe(t)||typeof t.id!="number"||typeof t.body!="string"?null:{id:t.id,body:t.body,folded:t.folded===!0,createdAt:typeof t.createdAt=="string"?t.createdAt:""}}function nte(t){if(!Pe(t))return null;let e=typeof t.id=="string"?t.id:"",r=typeof t.resourceId=="string"?t.resourceId:"",n=typeof t.experience=="string"?t.experience:"",o=t.outcome==="success"||t.outcome==="fail"||t.outcome==="neutral"?t.outcome:null;return!e||!r||!n||!o?null:{id:e,resourceId:r,actorPetId:typeof t.actorPetId=="string"?t.actorPetId:"",experience:n,outcome:o,contextCategory:typeof t.contextCategory=="string"?t.contextCategory:null,ts:typeof t.ts=="number"?t.ts:0}}function ote(t){return!Pe(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 ite(t){if(!Pe(t))return null;let e=typeof t.id=="string"?t.id:"",r=typeof t.version=="string"?t.version:"",n=typeof t.downloadUrl=="string"?t.downloadUrl:"",o=typeof t.checksum=="string"?t.checksum:"",i=typeof t.sizeBytes=="number"?t.sizeBytes:0;return!e||!r||!n||!/^[a-f0-9]{64}$/.test(o)||!Number.isSafeInteger(i)||i<=0?null:{id:e,version:r,downloadUrl:n,checksum:o,sizeBytes:i}}function dt(t=pr()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let r=ste(t);return tte({baseUrl:ate(t),token:e,clientVersion:r})}function ste(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.14.8"}function ate(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function cte(t){return _e(t,"/api/v15/registry/community-consent")}function _e(t,e){let r=t.trim().replace(/\/+$/,"");return r.endsWith("/v1")&&(r=r.slice(0,-3)),r.endsWith("/api")&&(r=r.slice(0,-4)),`${r}${e}`}function lte(t,e){let r=e?.trim();return r?(n,o)=>t(n,{...o,headers:{...o?.headers,"x-client-version":r}}):t}async function $N(t,e,r,n,o){return Xr(await Ne(t,e,r,n,o),!0)}async function Ne(t,e,r,n,o){let i,s=o!==void 0;try{i=await t(e,{method:n,headers:{accept:"application/json",authorization:`Bearer ${r}`,...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}`);return i.json().catch(()=>null)}async function dte(t,e,r,n){let o;try{o=await t(e,{method:"PUT",headers:{accept:"application/json",authorization:`Bearer ${r}`,"content-type":"application/gzip"},body:n,signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Community hub is unavailable.")}if(!o.ok)throw new Error(`Community hub rejected registry request: ${o.status}`);return o.json().catch(()=>null)}function Xr(t,e){let r=Pe(t)?t:{},n=r.enabled===!0;return{enabled:n,methodSharingEnabled:n&&r.methodSharingEnabled!==!1,signalsEnabled:n&&r.signalsEnabled!==!1,encounterEnabled:n&&r.encounterEnabled!==!1,remoteSynced:e}}function Pe(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Jp(t){return!Pe(t)||typeof t.id!="string"?null:{id:t.id,type:typeof t.type=="string"?t.type:"skill",title:typeof t.title=="string"?t.title:t.id,summary:typeof t.summary=="string"?t.summary:"",visibility:typeof t.visibility=="string"?t.visibility:"private",latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,withdrawn:t.withdrawn===!0,withdrawnAt:typeof t.withdrawnAt=="string"?t.withdrawnAt:null}}function ute(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 pte(t){if(!Pe(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=NN(t.sourceTier),r=ON(t.trustStage),n=Xp(t.resourceRiskTier),o=Xp(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.title!="string"||!e||!r||!n||!o)return null;let i=Array.isArray(t.capabilityTags)?t.capabilityTags:[];return{id:t.id,type:typeof t.type=="string"?t.type:"skill",title:PR(t.title,80),summary:PR(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=>PR(s,32)),sourceTier:e,trustStage:r,resourceRiskTier:n,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function PR(t,e){let r=t.replace(/\s+/g," ").trim();return r.length<=e?r:`${r.slice(0,Math.max(0,e-1))}\u2026`}function mte(t){return!Pe(t)||typeof t.version!="string"||typeof t.checksum!="string"?null:{version:t.version,checksum:t.checksum,sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0}}function DN(t){return!Pe(t)||typeof t.id!="number"||typeof t.resourceId!="string"?null:{id:t.id,resourceId:t.resourceId,resourceType:typeof t.resourceType=="string"?t.resourceType:"skill",title:typeof t.title=="string"?t.title:t.resourceId,event:ete.has(t.event)?t.event:"withdrawn",version:typeof t.version=="string"?t.version:null,reason:typeof t.reason=="string"?t.reason:null,read:t.read===!0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",readAt:typeof t.readAt=="string"?t.readAt:null}}var fte=new Set(["R0","R1","R2","R3"]),gte=new Set(["official","community"]),hte=new Set(["quarantine","trial","trusted"]),yte=new Set(["pending","approved","rejected"]);function Xp(t){return typeof t=="string"&&fte.has(t)?t:null}function NN(t){return typeof t=="string"&>e.has(t)?t:null}function ON(t){return typeof t=="string"&&hte.has(t)?t:null}function vte(t){return typeof t=="string"&&yte.has(t)?t:null}function jN(t){if(!Pe(t))return null;let e=NN(t.sourceTier),r=ON(t.trustStage),n=vte(t.reviewStatus),o=Xp(t.resourceRiskTier),i=Xp(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.type!="string"||typeof t.kind!="string"||!e||!r||!n||!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(jN);return c.some(l=>!l)?null:{id:t.id,type:t.type,kind:t.kind,sourceTier:e,trustStage:r,reviewStatus:n,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}}var bte=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|[A-Za-z]:\\|\/Users\/|\/home\/|secret|token|password|\+?\d[\d\s().-]{7,}\d)/i,kte=/\b(?:agent|tool|shell|execute|permission|memory|system prompt|developer message)\b/i;function wte(t){return Ste(t),{manifest:{schema_version:15,kind:"asset",name:t.name,summary:t.summary,persona:t.persona,traits:t.traits??[],assets:t.assets??[],tags:t.tags??[]}}}async function LN(t,e){let r=await t.getConsent();if(!r.enabled||!r.methodSharingEnabled)throw new Error("Community method-sharing consent is required before publishing pet assets.");let n=wte(e);return t.publishPet({id:e.id,title:e.name,summary:e.summary,visibility:e.visibility??"public",tags:e.tags??[],manifest:n.manifest})}function Ste(t){let e=[t.id,t.name,t.summary,t.persona,...t.traits??[],...t.tags??[]].join(`
|
|
657
|
+
`)),t.id!==void 0&&this.sendResponse(t.id,{log:o})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function IN(t){try{let e=t.params;if(!e?.agentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId is required."});return}let r=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(r.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:b.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function CN(t,e,r,n,o,i){let s=Kp(e,n,o),a=nN(s);if(a)return a;if(o!==Gp){let f=iN(Kp(e,n,Gp),s);if(f)return f}let c=`chat-${e}-${Bee().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new $r({onNotification:(f,g,h)=>{let y=l.current;if(!y)return;let v=h;if(g==="turn.delta"){let w=typeof v?.text=="string"?v.text:"";if(!w)return;y.deltas.push(w),y.turnId&&d&&(d("agents.prompt.delta",{agentId:e,sessionId:y.sessionId,turnId:y.turnId,requestId:y.requestId,text:w}),y.streamedAny=!0);return}if(g==="turn.thought_delta"){let w=typeof v?.text=="string"?v.text:"";w&&y.turnId&&d&&d("agents.prompt.delta",{agentId:e,sessionId:y.sessionId,turnId:y.turnId,requestId:y.requestId,text:w,reasoning:!0});return}if(g==="turn.plan"){y.turnId&&d&&d("agents.prompt.plan",{agentId:e,sessionId:y.sessionId,turnId:y.turnId,requestId:y.requestId,steps:Array.isArray(v?.steps)?v.steps:[]});return}if(!y.turnId||!d)return;let k=typeof v?.callId=="string"?v.callId:String(v?.callId??"");g==="turn.tool_call"?d("agents.prompt.tool",{agentId:e,sessionId:y.sessionId,turnId:y.turnId,requestId:y.requestId,event:{kind:"call",callId:k,name:typeof v?.toolName=="string"?v.toolName:typeof v?.name=="string"?v.name:"tool",arguments:qee(v)}}):g==="turn.tool_result"&&d("agents.prompt.tool",{agentId:e,sessionId:y.sessionId,turnId:y.turnId,requestId:y.requestId,event:{kind:"result",callId:k,name:typeof v?.toolName=="string"?v.toolName:"tool",ok:v?.status!=="failed"&&v?.status!=="error",outputPreview:Wee(v)}})},onMcpToolCall:async(f,g,h)=>typeof t.handleMcpToolCall=="function"?t.handleMcpToolCall(f,g,h):{ok:!1,error:"MCP tool call unavailable"},onPermissionRequest:(f,g)=>cN(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:Vp.join(pe(),"agent-logs")});await p.spawn({memberId:c,name:`chat-${e}`,cwd:n,prompt:"",external:r,systemPrompt:i});let m={manager:p,memberId:c,holder:l,lastUsed:Date.now()};return oN(s,m),m}async function _N(t){try{let e=t.params??{},r=typeof e.agentId=="string"?e.agentId.trim():"";if(!r||r==="qlogicagent"){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}let n=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(n.getData()),this.acpDetector.scan(!1);let o=this.acpDetector.buildExternalDescriptor(r);if(!o){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,warmed:!1});return}let i=typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd();await CN(this,r,o,i,Gp),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 EN(t){try{let e=t.params??{},r=typeof e.agentId=="string"?e.agentId.trim():"",n=typeof e.prompt=="string"?e.prompt:"";if(!r||!n.trim()){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:"agentId and prompt are required."});return}let o=await this.ensureAgentConfigStore();this.acpDetector.setConfigStore(o.getData()),this.acpDetector.scan(!1);let i=this.acpDetector.buildExternalDescriptor(r);if(!i){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:b.INVALID_PARAMS,message:`Agent ${r} is not available or not ACP-compatible.`});return}let s=typeof e.cwd=="string"&&e.cwd?e.cwd:typeof this.getActiveProjectRoot=="function"?this.getActiveProjectRoot():process.cwd(),a=typeof e.timeoutMs=="number"&&e.timeoutMs>0?e.timeoutMs:3e5,c=typeof e.sessionId=="string"?e.sessionId:void 0,l=typeof e.turnId=="string"?e.turnId:void 0,d=typeof e.requestId=="string"?e.requestId:void 0,p=typeof e.projectId=="string"?e.projectId:void 0,m=Kp(r,s,c),f=await CN(this,r,i,s,c,typeof e.systemPrompt=="string"?e.systemPrompt:void 0),g={sessionId:c,turnId:l,requestId:d,deltas:[],streamedAny:!1};f.holder.current=g,f.lastUsed=Date.now();let h;try{h=await f.manager.sendTask(f.memberId,n,{timeout:a})}catch(k){throw await Kee({sessionId:c,projectRoot:s,turnId:l,projectId:p,agentId:r,prompt:n,error:k}),sl(m),k}finally{f.holder.current=null}let y=g.deltas.join("")||(typeof h?.content=="string"?h.content:""),v=f.manager.getUsageTracker(f.memberId)?.getUsage();if(c){qr(c,{role:"user",content:n},s,l),y&&qr(c,{role:"assistant",content:y},s,l);let k=Nt(c,s);st(c,{type:"personal",...p?{projectId:p}:{},...k?.title?{}:{title:Ja(n,"External agent session")},...k?.agentId?{}:{agentId:r}},s)}t.id!==void 0&&this.sendResponse(t.id,{ok:!0,agentId:r,content:y,streamed:g.streamedAny,stopReason:h?.stopReason,usage:v?{inputTokens:v.inputTokens,outputTokens:v.outputTokens,totalTokens:v.totalTokens,cacheRead:v.cachedReadTokens,thoughtTokens:v.thoughtTokens,cost:v.cost}:void 0})}catch(e){if(t.id!==void 0){let r=dN(e);this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:uN(e),...r?{data:{authMethods:r}}:{}})}}}ie();import*as ca from"node:fs/promises";import*as zO from"node:path";ms();var Gee=/^[a-z0-9][a-z0-9_.:-]{0,79}$/i,Vee=new Set(["journeyDay","count"]),Zee=new Set(["blocked"]),Jee=new Set(["R0","R1","R2","R3"]),Xee=new Set(["aix","android","darwin","freebsd","ios","linux","openbsd","sunos","win32"]),Yee={"community.journey.view":new Set(["surface","petState","journeyDay","platform"]),"community.share.generated":new Set(["surface","action","source","petState","journeyDay","platform"]),"community.sandbox.violation":new Set(["surface","action","source","ruleId","riskTier","platform","count","blocked"]),"community.desensitization.hit":new Set(["surface","action","source","ruleId","riskTier","platform","count","blocked"]),"registry.install_failed":new Set(["dimension","resourceType","platform"])};function Zp(t,e){if(!e||typeof e!="object"||Array.isArray(e))return;let r=Yee[t],n={};for(let[o,i]of Object.entries(e)){if(!r.has(o))continue;let s=Qee(o,i);s!==void 0&&(n[o]=s)}return Object.keys(n).length>0?n:void 0}function Qee(t,e){if(Vee.has(t))return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=1e5?e:void 0;if(Zee.has(t))return typeof e=="boolean"?e:void 0;if(t==="riskTier")return typeof e=="string"&&Jee.has(e)?e:void 0;if(t==="platform")return typeof e=="string"&&Xee.has(e)?e:void 0;if(typeof e!="string")return;let r=e.trim();return Gee.test(r)?r:void 0}var ete=new Set(["withdrawn","version-available","deprecated","version-yanked","frozen"]);function tte(t){let e=cte(t.baseUrl),r=lte(t.fetchFn??fetch,t.clientVersion),n=t.token.trim();return{async getConsent(){return $N(r,e,n,"GET")},async setConsent(o){return $N(r,e,n,"PUT",o)},async matchRegistry(o){let i=o.intent.trim();if(!i)throw new Error("intent is required.");let s=ute(o.topK),a=await Ne(r,_e(t.baseUrl,"/api/v15/registry/match"),n,"POST",{intent:i,topK:s,prefer:o.preferOfficial===!1?"relevance":"official",canonicalOnly:!0});return(Pe(a)&&Array.isArray(a.matches)?a.matches:[]).map(pte).filter(l=>!!l).slice(0,s)},async publishSkill(o){return TR(r,t.baseUrl,n,"skill",o)},async publishPet(o){return TR(r,t.baseUrl,n,"pet",o)},async publishWorkflow(o){return TR(r,t.baseUrl,n,"workflow",o)},async recordSignal(o){let i=encodeURIComponent(o.resourceId.trim());if(!i)throw new Error("resourceId is required.");let s=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${i}/signal`),n,"POST",{event:o.event,attribution:o.attribution?.trim()||void 0,metadata:o.metadata});if(Pe(s)&&s.accepted===!0)return{accepted:!0};throw new Error("Community hub returned an invalid signal response.")},async recordTelemetry(o){let i=Zp(o.event,o.metadata),s=await Ne(r,_e(t.baseUrl,"/api/v15/registry/telemetry"),n,"POST",{event:o.event,metadata:i});if(Pe(s)&&s.accepted===!0)return{accepted:!0};throw new Error("Community hub returned an invalid telemetry response.")},async listSharedResources(){let o=await Ne(r,_e(t.baseUrl,"/api/v15/registry/mine"),n,"GET");return(Pe(o)&&Array.isArray(o.resources)?o.resources:[]).map(Jp).filter(s=>!!s)},async withdrawSharedResource(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("resourceId is required.");let a=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${s}/withdraw`),n,"POST",{reason:i?.trim()||void 0}),c=Jp(a);if(!c)throw new Error("Community hub returned an invalid resource.");return c},async withdrawSharedResources(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/registry/community-consent/withdraw-shared"),n,"POST",{reason:o?.trim()||void 0});return(Pe(i)&&Array.isArray(i.resources)?i.resources:[]).map(Jp).filter(a=>!!a)},async listNotices(o={}){let i=o.includeRead?"?includeRead=true":"",s=await Ne(r,_e(t.baseUrl,`/api/v15/registry/notices${i}`),n,"GET");return(Pe(s)&&Array.isArray(s.notices)?s.notices:[]).map(DN).filter(c=>!!c)},async markNoticeRead(o){if(!Number.isSafeInteger(o)||o<1)throw new Error("noticeId is required.");let i=await Ne(r,_e(t.baseUrl,`/api/v15/registry/notices/${o}/read`),n,"POST"),s=DN(i);if(!s)throw new Error("Community hub returned an invalid notice.");return s},async resolveInstall(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("resourceId is required.");let a=i?.trim(),c=a?`?version=${encodeURIComponent(a)}`:"",l=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${s}/install${c}`),n,"GET"),d=jN(l);if(!d)throw new Error("Community hub returned an invalid install resolution.");return d},async listResourceVersions(o){let i=encodeURIComponent(o.trim());if(!i)throw new Error("resourceId is required.");let s=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${i}/versions`),n,"GET");return(Pe(s)&&Array.isArray(s.versions)?s.versions:[]).map(ote).filter(c=>!!c)},async rateResource(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("resourceId is required.");let a=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${s}/rate`),n,"POST",{stars:i});return MN(a)},async getRatingSummary(o){let i=encodeURIComponent(o.trim());if(!i)throw new Error("resourceId is required.");let s=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${i}/rating`),n,"GET");return MN(s)},async reportResource(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("resourceId is required.");await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${s}/report`),n,"POST",{reason:i?.trim()||void 0})},async listComments(o){let i=encodeURIComponent(o.trim());if(!i)throw new Error("resourceId is required.");let s=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${i}/comments`),n,"GET");return(Pe(s)&&Array.isArray(s.comments)?s.comments:[]).map(rte).filter(c=>!!c)},async postComment(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("resourceId is required.");let a=i?.trim()??"";if(!a)throw new Error("Comment body is required.");let c=await Ne(r,_e(t.baseUrl,`/api/v15/registry/resources/${s}/comments`),n,"POST",{body:a}),l=Pe(c)?c:{};return{id:typeof l.id=="number"?l.id:0,folded:l.folded===!0,createdAt:typeof l.createdAt=="string"?l.createdAt:""}},async emitActivity(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/community/activity"),n,"POST",{id:o.id,type:o.type,ts:o.ts,actorPetId:o.actorPetId,peerRef:o.peerRef,visibility:o.visibility,payload:o.payload});if(!(Pe(i)&&i.accepted===!0))throw new Error("Community hub returned an invalid activity response.")},async recordCommunityReview(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/community/reviews"),n,"POST",{id:o.id,resourceId:o.resourceId,actorPetId:o.actorPetId,experience:o.experience,outcome:o.outcome,contextCategory:o.contextCategory,ts:o.ts});if(!(Pe(i)&&i.accepted===!0))throw new Error("Community hub returned an invalid review response.")},async findReviewAnswers(o,i){let s=o.trim();if(!s)return[];let a=await Ne(r,_e(t.baseUrl,"/api/v15/community/reviews/search"),n,"POST",{query:s,limit:typeof i=="number"&&i>0?Math.min(Math.floor(i),20):void 0});return(Pe(a)&&Array.isArray(a.answers)?a.answers:[]).map(nte).filter(l=>!!l)},async recordCommunityAsk(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/community/asks"),n,"POST",{id:o.id,askerPetId:o.askerPetId,question:o.question,contextCategory:o.contextCategory,ts:o.ts});if(!(Pe(i)&&i.accepted===!0))throw new Error("Community hub returned an invalid ask response.")},async recordCommunityAnswer(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/community/answers"),n,"POST",{id:o.id,askId:o.askId,answererPetId:o.answererPetId,answer:o.answer,ts:o.ts});if(!(Pe(i)&&i.accepted===!0))throw new Error("Community hub returned an invalid answer response.")},async recordCommunityInteraction(o){let i=await Ne(r,_e(t.baseUrl,"/api/v15/community/interactions"),n,"POST",{id:o.id,kind:o.kind,actorPetId:o.actorPetId,peerPetId:o.peerPetId,payload:o.payload,ts:o.ts});if(!(Pe(i)&&i.accepted===!0))throw new Error("Community hub returned an invalid interaction response.")},async resolveRuntime(o,i){let s=encodeURIComponent(o.trim());if(!s)throw new Error("runtime id is required.");let a=encodeURIComponent(i.trim());if(!a)throw new Error("platform is required.");let c=await Ne(r,_e(t.baseUrl,`/api/v15/runtime/${s}/resolve?platform=${a}`),n,"GET"),l=ite(c);if(!l)throw new Error("Community hub returned an invalid runtime resolution.");return l}}}async function TR(t,e,r,n,o){let i=Jp(await Ne(t,_e(e,"/api/v15/registry/resources"),r,"POST",{id:o.id,type:n,title:o.title,summary:o.summary,visibility:o.visibility??"public",...o.category?{category:o.category}:{},tags:o.tags??[],manifest:o.manifest}));if(!i)throw new Error("Community hub returned an invalid resource.");if(o.version===void 0&&o.packageGzipBase64===void 0)return{resource:i};if(!o.version?.trim()||!o.packageGzipBase64?.trim())throw new Error("version and packageGzipBase64 must be provided together.");let s=encodeURIComponent(o.id.trim()),a=encodeURIComponent(o.version.trim()),c=mte(await dte(t,_e(e,`/api/v15/registry/resources/${s}/versions/${a}`),r,Buffer.from(o.packageGzipBase64,"base64")));if(!c)throw new Error("Community hub returned an invalid version.");return{resource:i,version:c}}function MN(t){return Pe(t)?{average:typeof t.average=="number"?t.average:0,count:typeof t.count=="number"?t.count:0}:{average:0,count:0}}function rte(t){return!Pe(t)||typeof t.id!="number"||typeof t.body!="string"?null:{id:t.id,body:t.body,folded:t.folded===!0,createdAt:typeof t.createdAt=="string"?t.createdAt:""}}function nte(t){if(!Pe(t))return null;let e=typeof t.id=="string"?t.id:"",r=typeof t.resourceId=="string"?t.resourceId:"",n=typeof t.experience=="string"?t.experience:"",o=t.outcome==="success"||t.outcome==="fail"||t.outcome==="neutral"?t.outcome:null;return!e||!r||!n||!o?null:{id:e,resourceId:r,actorPetId:typeof t.actorPetId=="string"?t.actorPetId:"",experience:n,outcome:o,contextCategory:typeof t.contextCategory=="string"?t.contextCategory:null,ts:typeof t.ts=="number"?t.ts:0}}function ote(t){return!Pe(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 ite(t){if(!Pe(t))return null;let e=typeof t.id=="string"?t.id:"",r=typeof t.version=="string"?t.version:"",n=typeof t.downloadUrl=="string"?t.downloadUrl:"",o=typeof t.checksum=="string"?t.checksum:"",i=typeof t.sizeBytes=="number"?t.sizeBytes:0;return!e||!r||!n||!/^[a-f0-9]{64}$/.test(o)||!Number.isSafeInteger(i)||i<=0?null:{id:e,version:r,downloadUrl:n,checksum:o,sizeBytes:i}}function dt(t=pr()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let r=ste(t);return tte({baseUrl:ate(t),token:e,clientVersion:r})}function ste(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.14.9"}function ate(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function cte(t){return _e(t,"/api/v15/registry/community-consent")}function _e(t,e){let r=t.trim().replace(/\/+$/,"");return r.endsWith("/v1")&&(r=r.slice(0,-3)),r.endsWith("/api")&&(r=r.slice(0,-4)),`${r}${e}`}function lte(t,e){let r=e?.trim();return r?(n,o)=>t(n,{...o,headers:{...o?.headers,"x-client-version":r}}):t}async function $N(t,e,r,n,o){return Xr(await Ne(t,e,r,n,o),!0)}async function Ne(t,e,r,n,o){let i,s=o!==void 0;try{i=await t(e,{method:n,headers:{accept:"application/json",authorization:`Bearer ${r}`,...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}`);return i.json().catch(()=>null)}async function dte(t,e,r,n){let o;try{o=await t(e,{method:"PUT",headers:{accept:"application/json",authorization:`Bearer ${r}`,"content-type":"application/gzip"},body:n,signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Community hub is unavailable.")}if(!o.ok)throw new Error(`Community hub rejected registry request: ${o.status}`);return o.json().catch(()=>null)}function Xr(t,e){let r=Pe(t)?t:{},n=r.enabled===!0;return{enabled:n,methodSharingEnabled:n&&r.methodSharingEnabled!==!1,signalsEnabled:n&&r.signalsEnabled!==!1,encounterEnabled:n&&r.encounterEnabled!==!1,remoteSynced:e}}function Pe(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Jp(t){return!Pe(t)||typeof t.id!="string"?null:{id:t.id,type:typeof t.type=="string"?t.type:"skill",title:typeof t.title=="string"?t.title:t.id,summary:typeof t.summary=="string"?t.summary:"",visibility:typeof t.visibility=="string"?t.visibility:"private",latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,withdrawn:t.withdrawn===!0,withdrawnAt:typeof t.withdrawnAt=="string"?t.withdrawnAt:null}}function ute(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 pte(t){if(!Pe(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=NN(t.sourceTier),r=ON(t.trustStage),n=Xp(t.resourceRiskTier),o=Xp(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.title!="string"||!e||!r||!n||!o)return null;let i=Array.isArray(t.capabilityTags)?t.capabilityTags:[];return{id:t.id,type:typeof t.type=="string"?t.type:"skill",title:PR(t.title,80),summary:PR(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=>PR(s,32)),sourceTier:e,trustStage:r,resourceRiskTier:n,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function PR(t,e){let r=t.replace(/\s+/g," ").trim();return r.length<=e?r:`${r.slice(0,Math.max(0,e-1))}\u2026`}function mte(t){return!Pe(t)||typeof t.version!="string"||typeof t.checksum!="string"?null:{version:t.version,checksum:t.checksum,sizeBytes:typeof t.sizeBytes=="number"?t.sizeBytes:0}}function DN(t){return!Pe(t)||typeof t.id!="number"||typeof t.resourceId!="string"?null:{id:t.id,resourceId:t.resourceId,resourceType:typeof t.resourceType=="string"?t.resourceType:"skill",title:typeof t.title=="string"?t.title:t.resourceId,event:ete.has(t.event)?t.event:"withdrawn",version:typeof t.version=="string"?t.version:null,reason:typeof t.reason=="string"?t.reason:null,read:t.read===!0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",readAt:typeof t.readAt=="string"?t.readAt:null}}var fte=new Set(["R0","R1","R2","R3"]),gte=new Set(["official","community"]),hte=new Set(["quarantine","trial","trusted"]),yte=new Set(["pending","approved","rejected"]);function Xp(t){return typeof t=="string"&&fte.has(t)?t:null}function NN(t){return typeof t=="string"&>e.has(t)?t:null}function ON(t){return typeof t=="string"&&hte.has(t)?t:null}function vte(t){return typeof t=="string"&&yte.has(t)?t:null}function jN(t){if(!Pe(t))return null;let e=NN(t.sourceTier),r=ON(t.trustStage),n=vte(t.reviewStatus),o=Xp(t.resourceRiskTier),i=Xp(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.type!="string"||typeof t.kind!="string"||!e||!r||!n||!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(jN);return c.some(l=>!l)?null:{id:t.id,type:t.type,kind:t.kind,sourceTier:e,trustStage:r,reviewStatus:n,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}}var bte=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|[A-Za-z]:\\|\/Users\/|\/home\/|secret|token|password|\+?\d[\d\s().-]{7,}\d)/i,kte=/\b(?:agent|tool|shell|execute|permission|memory|system prompt|developer message)\b/i;function wte(t){return Ste(t),{manifest:{schema_version:15,kind:"asset",name:t.name,summary:t.summary,persona:t.persona,traits:t.traits??[],assets:t.assets??[],tags:t.tags??[]}}}async function LN(t,e){let r=await t.getConsent();if(!r.enabled||!r.methodSharingEnabled)throw new Error("Community method-sharing consent is required before publishing pet assets.");let n=wte(e);return t.publishPet({id:e.id,title:e.name,summary:e.summary,visibility:e.visibility??"public",tags:e.tags??[],manifest:n.manifest})}function Ste(t){let e=[t.id,t.name,t.summary,t.persona,...t.traits??[],...t.tags??[]].join(`
|
|
658
658
|
`);if(bte.test(e))throw new Error("Pet asset publish blocked: private email, path, secret, token, or phone-like text detected.");if(kte.test(e))throw new Error("Pet asset publish blocked: pets are display-only and cannot claim agent execution powers.");for(let r of t.assets??[])if(r.path.includes("..")||r.path.startsWith("/")||/^[A-Za-z]:\\/.test(r.path))throw new Error("Pet asset publish blocked: unsafe asset path.")}var AR={enabled:!0},xte=new Set(["R2","R3"]);function UN(t,e=AR){return xte.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"}}var FN=new Set(["installed","success","fail","error","kept","uninstalled","endorse"]),Rte=new Set(["acquire","ask","answer","encounter","review"]),Tte=new Set(["unlock","flaunt"]),Pte=new Set([...FN,...Rte,...Tte,"search"]),Ate=["x","y","z","lat","lng","lon","coord","coords","coordinate","coordinates","position","positionHint","pos"];function Yp(t){return FN.has(t)}function Ite(t){return typeof t=="string"&&Pte.has(t)}function Cte(t){if(t==null)return;if(typeof t!="object")throw new Error("ActivityEvent anchor \u5FC5\u987B\u662F\u5BF9\u8C61");for(let r of Object.keys(t))if(Ate.includes(r))throw new Error(`ActivityEvent anchor \u7981\u6743\u5A01\u5750\u6807\u952E: ${r}(DR12 \u7EA2\u7EBF:v1 \u4F4D\u7F6E client \u975E\u6743\u5A01)`);let e={};return typeof t.districtId=="string"&&t.districtId.length>0&&(e.districtId=t.districtId),typeof t.shopId=="string"&&t.shopId.length>0&&(e.shopId=t.shopId),e.districtId===void 0&&e.shopId===void 0?void 0:e}function HN(t){if(!t.id||typeof t.id!="string")throw new Error("ActivityEvent.id \u5FC5\u586B(\u5E42\u7B49\u952E)");if(!Ite(t.type))throw new Error(`ActivityEvent.type \u975E\u6CD5: ${String(t.type)}`);if(typeof t.ts!="number"||!Number.isFinite(t.ts)||t.ts<0)throw new Error("ActivityEvent.ts \u5FC5\u987B\u662F\u975E\u8D1F epoch ms");if(!t.actorPetId||typeof t.actorPetId!="string")throw new Error("ActivityEvent.actorPetId \u5FC5\u586B");let e=t.payload??{},r=Cte(e.anchor),n={...e};r?n.anchor=r:delete n.anchor;let o={id:t.id,type:t.type,ts:t.ts,actorPetId:t.actorPetId,payload:n,visibility:t.visibility??"owner"};return typeof t.peerRef=="string"&&t.peerRef.length>0&&(o.peerRef=t.peerRef),o}import{createHash as _te}from"node:crypto";var Ete="pk_",Mte=24;function Qp(t,e){let r=(t??"").trim(),n=(e??"").trim();if(!r||!n)throw new Error("derivePetKey: ownerUserId \u4E0E deviceId \u5747\u5FC5\u586B");let o=_te("sha256").update(r+"\0"+n).digest("hex");return`${Ete}${o.slice(0,Mte)}`}ms();function IR(t){return{async emit(e){if(!t.transport)return"disabled";let r=HN(e);if(r.visibility==="community"){if(!t.consent)return"consent-blocked";let n;try{n=await t.consent.getConsent()}catch{return"failed"}if(!n.enabled||!(Yp(r.type)?n.signalsEnabled:n.encounterEnabled))return"consent-blocked"}try{return await t.transport.emit(r),"emitted"}catch{return"failed"}}}}function CR(t){return{async emit(e){if(!t.emitActivity)throw new Error("emitActivity unavailable on client");await t.emitActivity(e)}}}function _R(){let t=dt(),e=t?.emitActivity?CR(t):null;return IR({transport:e,consent:t})}function ER(t=pr()){let e=t.get("QLOGIC_LLMROUTER_USER_ID")?.trim(),r=t.get("QLOGIC_LLMROUTER_DEVICE_ID")?.trim();if(!e||!r)return null;try{return Qp(e,r)}catch{return null}}import{randomUUID as BO}from"node:crypto";import{createPublicKey as $te,verify as Dte}from"node:crypto";function Nte(t){return`id=${t.id}
|
|
659
659
|
version=${t.version}
|
|
660
660
|
checksum=${t.checksum}
|