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/index.js
CHANGED
|
@@ -446,7 +446,7 @@ ${n.stderr}`:""].filter(Boolean).join(`
|
|
|
446
446
|
${t}
|
|
447
447
|
${n.authorization??""}`,i=Iv.get(o);if(i&&Date.now()<i.expiresAt)return i.value;let s=Av.get(o);if(s)return await s;let a=L_(r,t,n).then(c=>(Iv.set(o,{value:c,expiresAt:Date.now()+$_}),c)).finally(()=>{Av.delete(o)});return Av.set(o,a),a}async function j_(t,e){let r=Bd(e),n=N_(e),o=`${r}
|
|
448
448
|
${t}
|
|
449
|
-
${n.authorization??""}`,i=await L_(r,t,n);return Iv.set(o,{value:i,expiresAt:Date.now()+$_}),i}async function L_(t,e,r){let n;try{n=await fetch(`${t}${e}`,{method:"GET",headers:r,signal:AbortSignal.timeout(1e4)})}catch{throw new Hn}if(!n.ok)throw new Hn;let o=await n.json().catch(()=>null),i=Array.isArray(o)?o:W_(o)&&Array.isArray(o.data)?o.data:null;if(!i)throw new Hn;return i}function _v(t){let e=t.trim().replace(/\/+$/,"");return e.endsWith("/v1")?`${e}/models`:`${e}/v1/models`}async function W3(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 Hn}if(!r.ok)throw new Hn;let n=await r.json().catch(()=>null),o=Array.isArray(n)?n:W_(n)&&Array.isArray(n.data)?n.data:null;if(!o)throw new Hn;return o}async function uc(t,e={}){return e.force?j_("/ext/model-catalog/providers",t):O_("/ext/model-catalog/providers",t)}async function Ev(t,e={}){return e.force?j_("/ext/model-catalog/models",t):O_("/ext/model-catalog/models",t)}async function U_(t,e){return W3(_v(t),e)}function qd(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 Ro(t){return t.baseUrl??t.base_url}async function Mv(t,e,r={}){return(await uc(e,r)).find(o=>o.id===t)??null}async function K3(t,e,r={}){let[n,o]=await Promise.all([uc(e,r),Ev(e,r)]);t.replaceCatalogProviders(n.map(B_));let i=o.flatMap(V3);return t.replaceCatalogModels(i),i}async function G3(t,e,r,n){let o=await U_(t,e);if(o.length===0)return[];let i=new Set(o.map(z_).filter(a=>!!a));return(await Ev(r,{force:n})).map($v).filter(a=>!!a&&i.has(a.model)).map(a=>({...a,baseUrl:t}))}async function ys(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 K3(t,e,r);let o=t.getProviderStatus(lt)?.baseUrl??Bd(e),[i,s]=await Promise.all([uc(e,{force:r.force}).catch(()=>[]),Ev(e,{force:r.force})]);t.replaceCatalogProviders(i.map(B_));let a=n.has(lt),c=null;if(a){let d=t.getKeyForProvider(lt);if(d)try{let p=(await U_(o,d)).map(z_).filter(m=>!!m);p.length>0&&(c=new Set(p))}catch{}}let l=[];for(let d of s){let p=H_(d);if(p&&p.provider!==lt&&n.has(p.provider)&&l.push(p),a){let m=$v(d);m&&(c===null||c.has(m.model))&&l.push({...m,baseUrl:o})}}return t.replaceCatalogModels(l),l}async function F_(t,e){let r=await G3(e.baseUrl,e.apiKey,e.configPort,e.forceCatalog);return t.replaceProviderModels(lt,r),r}function pc(t,e=pr()){if(t.getBinding("textGeneration")||!e.get("QLOGIC_LLMROUTER_INFERENCE_KEY")?.trim())return!1;let n=t.listModels({purpose:"textGeneration",provider:lt,enabledOnly:!0}),i=n.find(s=>s.model.toLowerCase().includes("deepseek"))??n[0];return i?(t.setBinding("textGeneration",i.id),!0):!1}function V3(t){return[H_(t),$v(t)].filter(e=>!!e)}function H_(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:q_(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 $v(t){let e=t.public_model??t.publicModel??t.id;return e?{id:`${lt}:${e}`,provider:lt,model:e,displayName:t.display_name??t.displayName??t.name??t.id,routeIntents:q_(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 z_(t){return t.public_model??t.publicModel??t.id}function B_(t){return{id:t.id,name:qd(t),transport:t.transport??"",baseUrl:Ro(t)??"",group:t.group,models:t.models?.flatMap(e=>e.id?[{id:e.id}]:[])??[]}}function q_(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 W_(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}import*as rI from"node:path";var bi="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 Dv(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 Z3}from"node:crypto";var J3=["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"],X3=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"]),Y3=["memory.","pet.","usage."],Q3=new Set(["memory.atlas","memory.activity","memory.list","memory.read","memory.search","memory.attachment.locate","memory.attachment.adopt","pet.status"]);function Wd(t){return X3.has(t)?{channel:"task",mutability:"write",defaultTimeoutMs:12e4}:J3.some(e=>t===e||t.startsWith(`${e}.`)||t.startsWith(e))?{channel:"query",mutability:"read",defaultTimeoutMs:1e4}:{channel:"task",mutability:"write",defaultTimeoutMs:3e4}}function K_(t){return Q3.has(t)||Wd(t).mutability==="read"?!1:Y3.some(e=>t.startsWith(e))}function Nv(t,e={}){let r=e.now??Date.now(),n=Wd(t),o=e.timeoutMs??n.defaultTimeoutMs;return{requestId:e.requestId??Z3(),createdAt:r,deadlineAt:r+o,channel:e.channel??n.channel,idempotencyKey:e.idempotencyKey,traceId:e.traceId}}function Kd(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=Wd(t.method).channel;return r.channel!==n?{ok:!1,error:{code:b.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${n}, got ${r.channel}.`}}:K_(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 mc=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=Kd({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 G_=["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"],V_=["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"],eJ=[...G_,...V_];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"},fn={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"},vs={X_SKILL_INSTRUCTION:"x_skill_instruction",X_SESSION_INFO:"x_session_info",X_RELAY:"x_relay"};function fc(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&"id"in e}function gc(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&!("id"in e)}function Ov(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&"id"in e&&!("method"in e)}var Z_="openai-codex";var nRe={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"},[Z_]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};import{randomUUID as LE}from"node:crypto";import*as Gv from"node:path";import{readFile as Gd,writeFile as Uv,stat as Lv,unlink as hJ,mkdir as Fv}from"node:fs/promises";import{join as To,resolve as sE,isAbsolute as aE,normalize as cE}from"node:path";import{randomUUID as yJ}from"node:crypto";function X_(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function tJ(t){return t.latestInputTokens+t.cumulativeOutputTokens}var rJ=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),Y_=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function nJ(t){return{isSearch:rJ.has(t)||void 0,isRead:Y_.has(t)||void 0}}function oJ(t,e){let r=e.file_path??e.path??e.filePath;if(typeof r=="string")return`${Y_.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 Q_(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 eE(t,e,r,n){t.toolUseCount++;let o=nJ(e),i={toolName:e,input:r,activityDescription:n?.(e,r)??oJ(e,r),isSearch:o.isSearch,isRead:o.isRead};for(t.recentActivities.push(i);t.recentActivities.length>5;)t.recentActivities.shift()}function jv(t){return{toolUseCount:t.toolUseCount,tokenCount:tJ(t),lastActivity:t.recentActivities.length>0?t.recentActivities[t.recentActivities.length-1]:void 0,recentActivities:[...t.recentActivities]}}import{AsyncLocalStorage as iJ}from"node:async_hooks";var tE=new iJ;function hc(){return tE.getStore()?.depth??0}function rE(t,e){return tE.run({depth:t},e)}import{randomUUID as nE}from"node:crypto";function sJ(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=X_(),{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=sJ(w),C=`fork-${y}-${nE().slice(0,8)}`,U=`fork-session-${nE().slice(0,8)}`,j=(_??hc())+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 rE(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&&(Q_(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{}eE(o,de.name,ht),T?.(jv(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:jv(o),durationMs:cr,ok:Q,error:Me}}import{readFile as aJ,readdir as cJ}from"node:fs/promises";import{existsSync as lJ}from"node:fs";import{join as dJ}from"node:path";var uJ={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"},pJ={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 mJ(t){let e=t.replace(/\.md$/,"").toLowerCase();for(let[r,n]of Object.entries(uJ))if(e.startsWith(r+"-")||e.startsWith(r+"_")||e===r)return n;return null}function fJ(t){let e=t.slice(0,500),r=null,n=0;for(let[o,i]of Object.entries(pJ)){let s=i.filter(a=>a.test(e)).length;s>n&&(n=s,r=o)}return r}async function oE(t){let e={},r=0,n=0;if(!lJ(t))return{categories:e,totalFiles:0,uncategorizedCount:0};let o;try{o=await cJ(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=dJ(t,s);try{let c=await aJ(a,"utf-8");r++;let l=mJ(s)??fJ(c)??"uncategorized";l==="uncategorized"&&n++;let d=c.split(`
|
|
449
|
+
${n.authorization??""}`,i=await L_(r,t,n);return Iv.set(o,{value:i,expiresAt:Date.now()+$_}),i}async function L_(t,e,r){let n;try{n=await fetch(`${t}${e}`,{method:"GET",headers:r,signal:AbortSignal.timeout(1e4)})}catch{throw new Hn}if(!n.ok)throw new Hn;let o=await n.json().catch(()=>null),i=Array.isArray(o)?o:W_(o)&&Array.isArray(o.data)?o.data:null;if(!i)throw new Hn;return i}function _v(t){let e=t.trim().replace(/\/+$/,"");return e.endsWith("/v1")?`${e}/models`:`${e}/v1/models`}async function W3(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 Hn}if(!r.ok)throw new Hn;let n=await r.json().catch(()=>null),o=Array.isArray(n)?n:W_(n)&&Array.isArray(n.data)?n.data:null;if(!o)throw new Hn;return o}async function uc(t,e={}){return e.force?j_("/ext/model-catalog/providers",t):O_("/ext/model-catalog/providers",t)}async function Ev(t,e={}){return e.force?j_("/ext/model-catalog/models",t):O_("/ext/model-catalog/models",t)}async function U_(t,e){return W3(_v(t),e)}function qd(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 Ro(t){return t.baseUrl??t.base_url}async function Mv(t,e,r={}){return(await uc(e,r)).find(o=>o.id===t)??null}async function K3(t,e,r={}){let[n,o]=await Promise.all([uc(e,r),Ev(e,r)]);t.replaceCatalogProviders(n.map(B_));let i=o.flatMap(V3);return t.replaceCatalogModels(i),i}async function G3(t,e,r,n){let o=await U_(t,e);if(o.length===0)return[];let i=new Set(o.map(z_).filter(a=>!!a));return(await Ev(r,{force:n})).map($v).filter(a=>!!a&&i.has(a.model)).map(a=>({...a,baseUrl:t}))}async function ys(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 K3(t,e,r);let o=t.getProviderStatus(lt)?.baseUrl??Bd(e),[i,s]=await Promise.all([uc(e,{force:r.force}).catch(()=>[]),Ev(e,{force:r.force})]);t.replaceCatalogProviders(i.map(B_));let a=n.has(lt),c=null;if(a){let d=t.getKeyForProvider(lt);if(d)try{let p=(await U_(o,d)).map(z_).filter(m=>!!m);p.length>0&&(c=new Set(p))}catch{}}let l=[];for(let d of s){let p=H_(d);if(p&&p.provider!==lt&&n.has(p.provider)&&l.push(p),a){let m=$v(d);m&&(c===null||c.has(m.model))&&l.push({...m,baseUrl:o})}}return t.replaceCatalogModels(l),l}async function F_(t,e){let r=await G3(e.baseUrl,e.apiKey,e.configPort,e.forceCatalog);return t.replaceProviderModels(lt,r),r}function pc(t,e=pr()){if(t.getBinding("textGeneration")||!e.get("QLOGIC_LLMROUTER_INFERENCE_KEY")?.trim())return!1;let n=t.listModels({purpose:"textGeneration",provider:lt,enabledOnly:!0}),i=n.find(s=>s.model.toLowerCase().includes("deepseek"))??n[0];return i?(t.setBinding("textGeneration",i.id),!0):!1}function V3(t){return[H_(t),$v(t)].filter(e=>!!e)}function H_(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:q_(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 $v(t){let e=t.public_model??t.publicModel??t.id;return e?{id:`${lt}:${e}`,provider:lt,model:e,displayName:t.display_name??t.displayName??t.name??t.id,routeIntents:q_(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 z_(t){return t.public_model??t.publicModel??t.id}function B_(t){return{id:t.id,name:qd(t),transport:t.transport??"",baseUrl:Ro(t)??"",group:t.group,models:t.models?.flatMap(e=>e.id?[{id:e.id}]:[])??[]}}function q_(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 W_(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}import*as rI from"node:path";var bi="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 Dv(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 Z3}from"node:crypto";var J3=["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"],X3=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"]),Y3=["memory.","pet.","usage."],Q3=new Set(["memory.atlas","memory.activity","memory.list","memory.read","memory.search","memory.attachment.locate","memory.attachment.adopt","pet.status"]);function Wd(t){return X3.has(t)?{channel:"task",mutability:"write",defaultTimeoutMs:12e4}:J3.some(e=>t===e||t.startsWith(`${e}.`)||t.startsWith(e))?{channel:"query",mutability:"read",defaultTimeoutMs:1e4}:{channel:"task",mutability:"write",defaultTimeoutMs:3e4}}function K_(t){return Q3.has(t)||Wd(t).mutability==="read"?!1:Y3.some(e=>t.startsWith(e))}function Nv(t,e={}){let r=e.now??Date.now(),n=Wd(t),o=e.timeoutMs??n.defaultTimeoutMs;return{requestId:e.requestId??Z3(),createdAt:r,deadlineAt:r+o,channel:e.channel??n.channel,idempotencyKey:e.idempotencyKey,traceId:e.traceId}}function Kd(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=Wd(t.method).channel;return r.channel!==n?{ok:!1,error:{code:b.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${n}, got ${r.channel}.`}}:K_(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 mc=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=Kd({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 G_=["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"],V_=["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"],eJ=[...G_,...V_];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"},fn={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"},vs={X_SKILL_INSTRUCTION:"x_skill_instruction",X_SESSION_INFO:"x_session_info",X_RELAY:"x_relay"};function fc(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&"id"in e}function gc(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&!("id"in e)}function Ov(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&"id"in e&&!("method"in e)}var Z_="openai-codex";var nRe={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"},[Z_]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};import{randomUUID as LE}from"node:crypto";import*as Gv from"node:path";import{readFile as Gd,writeFile as Uv,stat as Lv,unlink as hJ,mkdir as Fv}from"node:fs/promises";import{join as To,resolve as sE,isAbsolute as aE,normalize as cE}from"node:path";import{randomUUID as yJ}from"node:crypto";function X_(){return{toolUseCount:0,latestInputTokens:0,cumulativeOutputTokens:0,recentActivities:[]}}function tJ(t){return t.latestInputTokens+t.cumulativeOutputTokens}var rJ=new Set(["grep","glob","search","Grep","Glob","list_dir","find_files"]),Y_=new Set(["read_file","file_read","cat","head","tail","FileRead"]);function nJ(t){return{isSearch:rJ.has(t)||void 0,isRead:Y_.has(t)||void 0}}function oJ(t,e){let r=e.file_path??e.path??e.filePath;if(typeof r=="string")return`${Y_.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 Q_(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 eE(t,e,r,n){t.toolUseCount++;let o=nJ(e),i={toolName:e,input:r,activityDescription:n?.(e,r)??oJ(e,r),isSearch:o.isSearch,isRead:o.isRead};for(t.recentActivities.push(i);t.recentActivities.length>5;)t.recentActivities.shift()}function jv(t){return{toolUseCount:t.toolUseCount,tokenCount:tJ(t),lastActivity:t.recentActivities.length>0?t.recentActivities[t.recentActivities.length-1]:void 0,recentActivities:[...t.recentActivities]}}import{AsyncLocalStorage as iJ}from"node:async_hooks";var tE=new iJ;function hc(){return tE.getStore()?.depth??0}function rE(t,e){return tE.run({depth:t},e)}import{randomUUID as nE}from"node:crypto";function sJ(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=X_(),{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=sJ(w),C=`fork-${y}-${nE().slice(0,8)}`,U=`fork-session-${nE().slice(0,8)}`,j=(_??hc())+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 rE(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&&(Q_(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{}eE(o,de.name,ht),T?.(jv(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:jv(o),durationMs:cr,ok:Q,error:Me}}import{readFile as aJ,readdir as cJ}from"node:fs/promises";import{existsSync as lJ}from"node:fs";import{join as dJ}from"node:path";var uJ={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"},pJ={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 mJ(t){let e=t.replace(/\.md$/,"").toLowerCase();for(let[r,n]of Object.entries(uJ))if(e.startsWith(r+"-")||e.startsWith(r+"_")||e===r)return n;return null}function fJ(t){let e=t.slice(0,500),r=null,n=0;for(let[o,i]of Object.entries(pJ)){let s=i.filter(a=>a.test(e)).length;s>n&&(n=s,r=o)}return r}async function oE(t){let e={},r=0,n=0;if(!lJ(t))return{categories:e,totalFiles:0,uncategorizedCount:0};let o;try{o=await cJ(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=dJ(t,s);try{let c=await aJ(a,"utf-8");r++;let l=mJ(s)??fJ(c)??"uncategorized";l==="uncategorized"&&n++;let d=c.split(`
|
|
450
450
|
`),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 gJ={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 iE(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(`
|
|
451
451
|
## Category Context (${t.totalFiles} files)
|
|
452
452
|
`),e.push(`Use category-specific merge rules when updating files:
|
|
@@ -642,7 +642,7 @@ Return a brief summary of what you consolidated, updated, or pruned. If nothing
|
|
|
642
642
|
|
|
643
643
|
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 Oo(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:zs(e,"input",t.processors),output:zs(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 rS=(t,e={})=>r=>{let n=Do({...r,processors:e});return me(t,n),No(n,t),Oo(n,t)},zs=(t,e,r={})=>n=>{let{libraryOptions:o,target:i}=n??{},s=Do({...o??{},target:i,io:e,processors:r});return me(t,s),No(s,t),Oo(s,t)};var HX={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},nS=(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=HX[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}))])}},oS=(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)},iS=(t,e,r,n)=>{r.type="boolean"},sS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},aS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},cS=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},lS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},dS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},uS=(t,e,r,n)=>{r.not={}},pS=(t,e,r,n)=>{},mS=(t,e,r,n)=>{},fS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},gS=(t,e,r,n)=>{let o=t._zod.def,i=vc(o.entries);i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},hS=(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},yS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},vS=(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},bS=(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)},kS=(t,e,r,n)=>{r.type="boolean"},wS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},SS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},xS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},RS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},TS=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},PS=(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"]})},AS=(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)},ep=(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},IS=(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},CS=(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)},_S=(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)}},ES=(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"}]},MS=(t,e,r,n)=>{let o=t._zod.def;me(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},$S=(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))},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,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},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;let s;try{s=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=s},OS=(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},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,r.readOnly=!0},LS=(t,e,r,n)=>{let o=t._zod.def;me(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},tp=(t,e,r,n)=>{let o=t._zod.def;me(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},US=(t,e,r,n)=>{let o=t._zod.innerType;me(o,e,n);let i=e.seen.get(t);i.ref=o},Qu={string:nS,number:oS,boolean:iS,bigint:sS,symbol:aS,null:cS,undefined:lS,void:dS,never:uS,any:pS,unknown:mS,date:fS,enum:gS,literal:hS,nan:yS,template_literal:vS,file:bS,success:kS,custom:wS,function:SS,transform:xS,map:RS,set:TS,array:PS,object:AS,union:ep,intersection:IS,tuple:CS,record:_S,nullable:ES,nonoptional:MS,default:$S,prefault:DS,catch:NS,pipe:OS,readonly:jS,promise:LS,optional:tp,lazy:US};function rp(t,e){if("_idmap"in t){let n=t,o=Do({...e,processors:Qu}),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;No(o,d),s[l]=Oo(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=Do({...e,processors:Qu});return me(t,r),No(r,t),Oo(r,t)}var np=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=Do({processors:Qu,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)),No(this.ctx,e);let n=Oo(this.ctx,e),{"~standard":o,...i}=n;return i}};var y$={};var Oc={};qt(Oc,{ZodAny:()=>lx,ZodArray:()=>mx,ZodBase64:()=>Rp,ZodBase64URL:()=>Tp,ZodBigInt:()=>Js,ZodBigIntFormat:()=>Ip,ZodBoolean:()=>Zs,ZodCIDRv4:()=>Sp,ZodCIDRv6:()=>xp,ZodCUID:()=>gp,ZodCUID2:()=>hp,ZodCatch:()=>Nx,ZodCodec:()=>Vc,ZodCustom:()=>Zc,ZodCustomStringFormat:()=>Gs,ZodDate:()=>Bc,ZodDefault:()=>Cx,ZodDiscriminatedUnion:()=>gx,ZodE164:()=>Pp,ZodEmail:()=>pp,ZodEmoji:()=>mp,ZodEnum:()=>Ws,ZodExactOptional:()=>Px,ZodFile:()=>Rx,ZodFunction:()=>Wx,ZodGUID:()=>Lc,ZodIPv4:()=>kp,ZodIPv6:()=>wp,ZodIntersection:()=>hx,ZodJWT:()=>Ap,ZodKSUID:()=>bp,ZodLazy:()=>zx,ZodLiteral:()=>xx,ZodMAC:()=>rx,ZodMap:()=>wx,ZodNaN:()=>jx,ZodNanoID:()=>fp,ZodNever:()=>ux,ZodNonOptional:()=>Dp,ZodNull:()=>ax,ZodNullable:()=>Ix,ZodNumber:()=>Vs,ZodNumberFormat:()=>_i,ZodObject:()=>Wc,ZodOptional:()=>$p,ZodPipe:()=>Gc,ZodPrefault:()=>Ex,ZodPreprocess:()=>Lx,ZodPromise:()=>qx,ZodReadonly:()=>Ux,ZodRecord:()=>qs,ZodSet:()=>Sx,ZodString:()=>Ks,ZodStringFormat:()=>we,ZodSuccess:()=>Dx,ZodSymbol:()=>ix,ZodTemplateLiteral:()=>Hx,ZodTransform:()=>Tx,ZodTuple:()=>vx,ZodType:()=>ee,ZodULID:()=>yp,ZodURL:()=>zc,ZodUUID:()=>vn,ZodUndefined:()=>sx,ZodUnion:()=>Kc,ZodUnknown:()=>dx,ZodVoid:()=>px,ZodXID:()=>vp,ZodXor:()=>fx,_ZodString:()=>up,_default:()=>_x,_function:()=>PD,any:()=>nD,array:()=>qc,base64:()=>F$,base64url:()=>H$,bigint:()=>Y$,boolean:()=>ox,catch:()=>Ox,check:()=>AD,cidrv4:()=>L$,cidrv6:()=>U$,codec:()=>SD,cuid:()=>_$,cuid2:()=>E$,custom:()=>ID,date:()=>iD,describe:()=>CD,discriminatedUnion:()=>uD,e164:()=>z$,email:()=>k$,emoji:()=>I$,enum:()=>Ep,exactOptional:()=>Ax,file:()=>vD,float32:()=>V$,float64:()=>Z$,function:()=>PD,guid:()=>w$,hash:()=>G$,hex:()=>K$,hostname:()=>W$,httpUrl:()=>A$,instanceof:()=>ED,int:()=>lp,int32:()=>J$,int64:()=>Q$,intersection:()=>yx,invertCodec:()=>xD,ipv4:()=>N$,ipv6:()=>j$,json:()=>$D,jwt:()=>B$,keyof:()=>sD,ksuid:()=>D$,lazy:()=>Bx,literal:()=>yD,looseObject:()=>lD,looseRecord:()=>mD,mac:()=>O$,map:()=>fD,meta:()=>_D,nan:()=>wD,nanoid:()=>C$,nativeEnum:()=>hD,never:()=>Cp,nonoptional:()=>$x,null:()=>cx,nullable:()=>Fc,nullish:()=>bD,number:()=>nx,object:()=>aD,optional:()=>Uc,partialRecord:()=>pD,pipe:()=>dp,prefault:()=>Mx,preprocess:()=>DD,promise:()=>TD,readonly:()=>Fx,record:()=>kx,refine:()=>Kx,set:()=>gD,strictObject:()=>cD,string:()=>jc,stringFormat:()=>q$,stringbool:()=>MD,success:()=>kD,superRefine:()=>Gx,symbol:()=>tD,templateLiteral:()=>RD,transform:()=>Mp,tuple:()=>bx,uint32:()=>X$,uint64:()=>eD,ulid:()=>M$,undefined:()=>rD,union:()=>_p,unknown:()=>Ci,url:()=>P$,uuid:()=>S$,uuidv4:()=>x$,uuidv6:()=>R$,uuidv7:()=>T$,void:()=>oD,xid:()=>$$,xor:()=>dD});var op={};qt(op,{endsWith:()=>Ds,gt:()=>hn,gte:()=>Lt,includes:()=>Ms,length:()=>Ii,lowercase:()=>_s,lt:()=>gn,lte:()=>fr,maxLength:()=>Ai,maxSize:()=>$o,mime:()=>Ns,minLength:()=>qn,minSize:()=>yn,multipleOf:()=>Mo,negative:()=>Zu,nonnegative:()=>Xu,nonpositive:()=>Ju,normalize:()=>Os,overwrite:()=>Gr,positive:()=>Vu,property:()=>Yu,regex:()=>Cs,size:()=>Pi,slugify:()=>Fs,startsWith:()=>$s,toLowerCase:()=>Ls,toUpperCase:()=>Us,trim:()=>js,uppercase:()=>Es});var Bs={};qt(Bs,{ZodISODate:()=>sp,ZodISODateTime:()=>ip,ZodISODuration:()=>cp,ZodISOTime:()=>ap,date:()=>HS,datetime:()=>FS,duration:()=>BS,time:()=>zS});var ip=x("ZodISODateTime",(t,e)=>{yk.init(t,e),we.init(t,e)});function FS(t){return ww(ip,t)}var sp=x("ZodISODate",(t,e)=>{vk.init(t,e),we.init(t,e)});function HS(t){return Sw(sp,t)}var ap=x("ZodISOTime",(t,e)=>{bk.init(t,e),we.init(t,e)});function zS(t){return xw(ap,t)}var cp=x("ZodISODuration",(t,e)=>{kk.init(t,e),we.init(t,e)});function BS(t){return Rw(cp,t)}var v$=(t,e)=>{xc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Tc(t,r)},flatten:{value:r=>Rc(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,ks,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,ks,2)}},isEmpty:{get(){return t.issues.length===0}}})},BX=x("ZodError",v$),Jt=x("ZodError",v$,{Parent:Error});var qS=xs(Jt),WS=Rs(Jt),KS=Ts(Jt),GS=Ps(Jt),VS=ru(Jt),ZS=nu(Jt),JS=ou(Jt),XS=iu(Jt),YS=su(Jt),QS=au(Jt),ex=cu(Jt),tx=lu(Jt);var b$=new WeakMap;function Hc(t,e,r){let n=Object.getPrototypeOf(t),o=b$.get(n);if(o||(o=new Set,b$.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:zs(t,"input"),output:zs(t,"output")}}),t.toJSONSchema=rS(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>qS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>KS(t,r,n),t.parseAsync=async(r,n)=>WS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>GS(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>VS(t,r,n),t.decode=(r,n)=>ZS(t,r,n),t.encodeAsync=async(r,n)=>JS(t,r,n),t.decodeAsync=async(r,n)=>XS(t,r,n),t.safeEncode=(r,n)=>YS(t,r,n),t.safeDecode=(r,n)=>QS(t,r,n),t.safeEncodeAsync=async(r,n)=>ex(t,r,n),t.safeDecodeAsync=async(r,n)=>tx(t,r,n),Hc(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(Kx(r,n))},superRefine(r,n){return this.check(Gx(r,n))},overwrite(r){return this.check(Gr(r))},optional(){return Uc(this)},exactOptional(){return Ax(this)},nullable(){return Fc(this)},nullish(){return Uc(Fc(this))},nonoptional(r){return $x(this,r)},array(){return qc(this)},or(r){return _p([this,r])},and(r){return yx(this,r)},transform(r){return dp(this,Mp(r))},default(r){return _x(this,r)},prefault(r){return Mx(this,r)},catch(r){return Ox(this,r)},pipe(r){return dp(this,r)},readonly(){return Fx(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)),up=x("_ZodString",(t,e)=>{Ti.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,o,i)=>nS(t,n,o,i);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,Hc(t,"_ZodString",{regex(...n){return this.check(Cs(...n))},includes(...n){return this.check(Ms(...n))},startsWith(...n){return this.check($s(...n))},endsWith(...n){return this.check(Ds(...n))},min(...n){return this.check(qn(...n))},max(...n){return this.check(Ai(...n))},length(...n){return this.check(Ii(...n))},nonempty(...n){return this.check(qn(1,...n))},lowercase(n){return this.check(_s(n))},uppercase(n){return this.check(Es(n))},trim(){return this.check(js())},normalize(...n){return this.check(Os(...n))},toLowerCase(){return this.check(Ls())},toUpperCase(){return this.check(Us())},slugify(){return this.check(Fs())}})}),Ks=x("ZodString",(t,e)=>{Ti.init(t,e),up.init(t,e),t.email=r=>t.check(Iu(pp,r)),t.url=r=>t.check(Nc(zc,r)),t.jwt=r=>t.check(Gu(Ap,r)),t.emoji=r=>t.check($u(mp,r)),t.guid=r=>t.check(Dc(Lc,r)),t.uuid=r=>t.check(Cu(vn,r)),t.uuidv4=r=>t.check(_u(vn,r)),t.uuidv6=r=>t.check(Eu(vn,r)),t.uuidv7=r=>t.check(Mu(vn,r)),t.nanoid=r=>t.check(Du(fp,r)),t.guid=r=>t.check(Dc(Lc,r)),t.cuid=r=>t.check(Nu(gp,r)),t.cuid2=r=>t.check(Ou(hp,r)),t.ulid=r=>t.check(ju(yp,r)),t.base64=r=>t.check(qu(Rp,r)),t.base64url=r=>t.check(Wu(Tp,r)),t.xid=r=>t.check(Lu(vp,r)),t.ksuid=r=>t.check(Uu(bp,r)),t.ipv4=r=>t.check(Fu(kp,r)),t.ipv6=r=>t.check(Hu(wp,r)),t.cidrv4=r=>t.check(zu(Sp,r)),t.cidrv6=r=>t.check(Bu(xp,r)),t.e164=r=>t.check(Ku(Pp,r)),t.datetime=r=>t.check(FS(r)),t.date=r=>t.check(HS(r)),t.time=r=>t.check(zS(r)),t.duration=r=>t.check(BS(r))});function jc(t){return yw(Ks,t)}var we=x("ZodStringFormat",(t,e)=>{ke.init(t,e),up.init(t,e)}),pp=x("ZodEmail",(t,e)=>{ck.init(t,e),we.init(t,e)});function k$(t){return Iu(pp,t)}var Lc=x("ZodGUID",(t,e)=>{sk.init(t,e),we.init(t,e)});function w$(t){return Dc(Lc,t)}var vn=x("ZodUUID",(t,e)=>{ak.init(t,e),we.init(t,e)});function S$(t){return Cu(vn,t)}function x$(t){return _u(vn,t)}function R$(t){return Eu(vn,t)}function T$(t){return Mu(vn,t)}var zc=x("ZodURL",(t,e)=>{lk.init(t,e),we.init(t,e)});function P$(t){return Nc(zc,t)}function A$(t){return Nc(zc,{protocol:mr.httpProtocol,hostname:mr.domain,...N.normalizeParams(t)})}var mp=x("ZodEmoji",(t,e)=>{dk.init(t,e),we.init(t,e)});function I$(t){return $u(mp,t)}var fp=x("ZodNanoID",(t,e)=>{uk.init(t,e),we.init(t,e)});function C$(t){return Du(fp,t)}var gp=x("ZodCUID",(t,e)=>{pk.init(t,e),we.init(t,e)});function _$(t){return Nu(gp,t)}var hp=x("ZodCUID2",(t,e)=>{mk.init(t,e),we.init(t,e)});function E$(t){return Ou(hp,t)}var yp=x("ZodULID",(t,e)=>{fk.init(t,e),we.init(t,e)});function M$(t){return ju(yp,t)}var vp=x("ZodXID",(t,e)=>{gk.init(t,e),we.init(t,e)});function $$(t){return Lu(vp,t)}var bp=x("ZodKSUID",(t,e)=>{hk.init(t,e),we.init(t,e)});function D$(t){return Uu(bp,t)}var kp=x("ZodIPv4",(t,e)=>{wk.init(t,e),we.init(t,e)});function N$(t){return Fu(kp,t)}var rx=x("ZodMAC",(t,e)=>{xk.init(t,e),we.init(t,e)});function O$(t){return bw(rx,t)}var wp=x("ZodIPv6",(t,e)=>{Sk.init(t,e),we.init(t,e)});function j$(t){return Hu(wp,t)}var Sp=x("ZodCIDRv4",(t,e)=>{Rk.init(t,e),we.init(t,e)});function L$(t){return zu(Sp,t)}var xp=x("ZodCIDRv6",(t,e)=>{Tk.init(t,e),we.init(t,e)});function U$(t){return Bu(xp,t)}var Rp=x("ZodBase64",(t,e)=>{Ak.init(t,e),we.init(t,e)});function F$(t){return qu(Rp,t)}var Tp=x("ZodBase64URL",(t,e)=>{Ik.init(t,e),we.init(t,e)});function H$(t){return Wu(Tp,t)}var Pp=x("ZodE164",(t,e)=>{Ck.init(t,e),we.init(t,e)});function z$(t){return Ku(Pp,t)}var Ap=x("ZodJWT",(t,e)=>{_k.init(t,e),we.init(t,e)});function B$(t){return Gu(Ap,t)}var Gs=x("ZodCustomStringFormat",(t,e)=>{Ek.init(t,e),we.init(t,e)});function q$(t,e,r={}){return Hs(Gs,t,e,r)}function W$(t){return Hs(Gs,"hostname",mr.hostname,t)}function K$(t){return Hs(Gs,"hex",mr.hex,t)}function G$(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,o=mr[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return Hs(Gs,n,o,e)}var Vs=x("ZodNumber",(t,e)=>{vu.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,o,i)=>oS(t,n,o,i),Hc(t,"ZodNumber",{gt(n,o){return this.check(hn(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(gn(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(lp(n))},safe(n){return this.check(lp(n))},positive(n){return this.check(hn(0,n))},nonnegative(n){return this.check(Lt(0,n))},negative(n){return this.check(gn(0,n))},nonpositive(n){return this.check(fr(0,n))},multipleOf(n,o){return this.check(Mo(n,o))},step(n,o){return this.check(Mo(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 nx(t){return Tw(Vs,t)}var _i=x("ZodNumberFormat",(t,e)=>{Mk.init(t,e),Vs.init(t,e)});function lp(t){return Aw(_i,t)}function V$(t){return Iw(_i,t)}function Z$(t){return Cw(_i,t)}function J$(t){return _w(_i,t)}function X$(t){return Ew(_i,t)}var Zs=x("ZodBoolean",(t,e)=>{Cc.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>iS(t,r,n,o)});function ox(t){return Mw(Zs,t)}var Js=x("ZodBigInt",(t,e)=>{bu.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,o,i)=>sS(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(hn(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(gn(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(hn(BigInt(0),n)),t.negative=n=>t.check(gn(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(Mo(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function Y$(t){return Dw(Js,t)}var Ip=x("ZodBigIntFormat",(t,e)=>{$k.init(t,e),Js.init(t,e)});function Q$(t){return Ow(Ip,t)}function eD(t){return jw(Ip,t)}var ix=x("ZodSymbol",(t,e)=>{Dk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>aS(t,r,n,o)});function tD(t){return Lw(ix,t)}var sx=x("ZodUndefined",(t,e)=>{Nk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>lS(t,r,n,o)});function rD(t){return Uw(sx,t)}var ax=x("ZodNull",(t,e)=>{Ok.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>cS(t,r,n,o)});function cx(t){return Fw(ax,t)}var lx=x("ZodAny",(t,e)=>{jk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>pS(t,r,n,o)});function nD(){return Hw(lx)}var dx=x("ZodUnknown",(t,e)=>{Lk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>mS(t,r,n,o)});function Ci(){return zw(dx)}var ux=x("ZodNever",(t,e)=>{Uk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>uS(t,r,n,o)});function Cp(t){return Bw(ux,t)}var px=x("ZodVoid",(t,e)=>{Fk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>dS(t,r,n,o)});function oD(t){return qw(px,t)}var Bc=x("ZodDate",(t,e)=>{Hk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,o,i)=>fS(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 iD(t){return Ww(Bc,t)}var mx=x("ZodArray",(t,e)=>{zk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>PS(t,r,n,o),t.element=e.element,Hc(t,"ZodArray",{min(r,n){return this.check(qn(r,n))},nonempty(r){return this.check(qn(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 qc(t,e){return Vw(mx,t,e)}function sD(t){let e=t._zod.def.shape;return Ep(Object.keys(e))}var Wc=x("ZodObject",(t,e)=>{Bk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>AS(t,r,n,o),N.defineLazy(t,"shape",()=>e.shape),Hc(t,"ZodObject",{keyof(){return Ep(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:Cp()})},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($p,this,r[0])},required(...r){return N.required(Dp,this,r[0])}})});function aD(t,e){let r={type:"object",shape:t??{},...N.normalizeParams(e)};return new Wc(r)}function cD(t,e){return new Wc({type:"object",shape:t,catchall:Cp(),...N.normalizeParams(e)})}function lD(t,e){return new Wc({type:"object",shape:t,catchall:Ci(),...N.normalizeParams(e)})}var Kc=x("ZodUnion",(t,e)=>{_c.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ep(t,r,n,o),t.options=e.options});function _p(t,e){return new Kc({type:"union",options:t,...N.normalizeParams(e)})}var fx=x("ZodXor",(t,e)=>{Kc.init(t,e),qk.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ep(t,r,n,o),t.options=e.options});function dD(t,e){return new fx({type:"union",options:t,inclusive:!1,...N.normalizeParams(e)})}var gx=x("ZodDiscriminatedUnion",(t,e)=>{Kc.init(t,e),Wk.init(t,e)});function uD(t,e,r){return new gx({type:"union",options:e,discriminator:t,...N.normalizeParams(r)})}var hx=x("ZodIntersection",(t,e)=>{Kk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>IS(t,r,n,o)});function yx(t,e){return new hx({type:"intersection",left:t,right:e})}var vx=x("ZodTuple",(t,e)=>{ku.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>CS(t,r,n,o),t.rest=r=>t.clone({...t._zod.def,rest:r})});function bx(t,e,r){let n=e instanceof X,o=n?r:e,i=n?e:null;return new vx({type:"tuple",items:t,rest:i,...N.normalizeParams(o)})}var qs=x("ZodRecord",(t,e)=>{Gk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>_S(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function kx(t,e,r){return!e||!e._zod?new qs({type:"record",keyType:jc(),valueType:t,...N.normalizeParams(e)}):new qs({type:"record",keyType:t,valueType:e,...N.normalizeParams(r)})}function pD(t,e,r){let n=Ot(t);return n._zod.values=void 0,new qs({type:"record",keyType:n,valueType:e,...N.normalizeParams(r)})}function mD(t,e,r){return new qs({type:"record",keyType:t,valueType:e,mode:"loose",...N.normalizeParams(r)})}var wx=x("ZodMap",(t,e)=>{Vk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>RS(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(yn(...r)),t.nonempty=r=>t.check(yn(1,r)),t.max=(...r)=>t.check($o(...r)),t.size=(...r)=>t.check(Pi(...r))});function fD(t,e,r){return new wx({type:"map",keyType:t,valueType:e,...N.normalizeParams(r)})}var Sx=x("ZodSet",(t,e)=>{Zk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>TS(t,r,n,o),t.min=(...r)=>t.check(yn(...r)),t.nonempty=r=>t.check(yn(1,r)),t.max=(...r)=>t.check($o(...r)),t.size=(...r)=>t.check(Pi(...r))});function gD(t,e){return new Sx({type:"set",valueType:t,...N.normalizeParams(e)})}var Ws=x("ZodEnum",(t,e)=>{Jk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(n,o,i)=>gS(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 Ws({...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 Ws({...e,checks:[],...N.normalizeParams(o),entries:i})}});function Ep(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Ws({type:"enum",entries:r,...N.normalizeParams(e)})}function hD(t,e){return new Ws({type:"enum",entries:t,...N.normalizeParams(e)})}var xx=x("ZodLiteral",(t,e)=>{Xk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>hS(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 yD(t,e){return new xx({type:"literal",values:Array.isArray(t)?t:[t],...N.normalizeParams(e)})}var Rx=x("ZodFile",(t,e)=>{Yk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>bS(t,r,n,o),t.min=(r,n)=>t.check(yn(r,n)),t.max=(r,n)=>t.check($o(r,n)),t.mime=(r,n)=>t.check(Ns(Array.isArray(r)?r:[r],n))});function vD(t){return Zw(Rx,t)}var Tx=x("ZodTransform",(t,e)=>{Qk.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>xS(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Ao(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 Mp(t){return new Tx({type:"transform",transform:t})}var $p=x("ZodOptional",(t,e)=>{wu.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>tp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Uc(t){return new $p({type:"optional",innerType:t})}var Px=x("ZodExactOptional",(t,e)=>{ew.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>tp(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Ax(t){return new Px({type:"optional",innerType:t})}var Ix=x("ZodNullable",(t,e)=>{tw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ES(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Fc(t){return new Ix({type:"nullable",innerType:t})}function bD(t){return Uc(Fc(t))}var Cx=x("ZodDefault",(t,e)=>{rw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>$S(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function _x(t,e){return new Cx({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():N.shallowClone(e)}})}var Ex=x("ZodPrefault",(t,e)=>{nw.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 Mx(t,e){return new Ex({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():N.shallowClone(e)}})}var Dp=x("ZodNonOptional",(t,e)=>{ow.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>MS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function $x(t,e){return new Dp({type:"nonoptional",innerType:t,...N.normalizeParams(e)})}var Dx=x("ZodSuccess",(t,e)=>{iw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>kS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function kD(t){return new Dx({type:"success",innerType:t})}var Nx=x("ZodCatch",(t,e)=>{sw.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.removeCatch=t.unwrap});function Ox(t,e){return new Nx({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var jx=x("ZodNaN",(t,e)=>{aw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>yS(t,r,n,o)});function wD(t){return Gw(jx,t)}var Gc=x("ZodPipe",(t,e)=>{Su.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>OS(t,r,n,o),t.in=e.in,t.out=e.out});function dp(t,e){return new Gc({type:"pipe",in:t,out:e})}var Vc=x("ZodCodec",(t,e)=>{Gc.init(t,e),Ec.init(t,e)});function SD(t,e,r){return new Vc({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function xD(t){let e=t._zod.def;return new Vc({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}var Lx=x("ZodPreprocess",(t,e)=>{Gc.init(t,e),cw.init(t,e)}),Ux=x("ZodReadonly",(t,e)=>{lw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>jS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Fx(t){return new Ux({type:"readonly",innerType:t})}var Hx=x("ZodTemplateLiteral",(t,e)=>{dw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vS(t,r,n,o)});function RD(t,e){return new Hx({type:"template_literal",parts:t,...N.normalizeParams(e)})}var zx=x("ZodLazy",(t,e)=>{mw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>US(t,r,n,o),t.unwrap=()=>t._zod.def.getter()});function Bx(t){return new zx({type:"lazy",getter:t})}var qx=x("ZodPromise",(t,e)=>{pw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>LS(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function TD(t){return new qx({type:"promise",innerType:t})}var Wx=x("ZodFunction",(t,e)=>{uw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>SS(t,r,n,o)});function PD(t){return new Wx({type:"function",input:Array.isArray(t?.input)?bx(t?.input):t?.input??qc(Ci()),output:t?.output??Ci()})}var Zc=x("ZodCustom",(t,e)=>{fw.init(t,e),ee.init(t,e),t._zod.processJSONSchema=(r,n,o)=>wS(t,r,n,o)});function AD(t){let e=new xe({check:"custom"});return e._zod.check=t,e}function ID(t,e){return Jw(Zc,t??(()=>!0),e)}function Kx(t,e={}){return Xw(Zc,t,e)}function Gx(t,e){return Yw(t,e)}var CD=Qw,_D=eS;function ED(t,e={}){let r=new Zc({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 MD=(...t)=>tS({Codec:Vc,Boolean:Zs,String:Ks},...t);function $D(t){let e=Bx(()=>_p([jc(t),nx(),ox(),cx(),qc(e),kx(jc(),e)]));return e}function DD(t,e){return new Lx({type:"pipe",in:Mp(t),out:e})}var WX={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 KX(t){Fe({customError:t})}function GX(){return Fe().customError}var Vx;Vx||(Vx={});var H={...Oc,...op,iso:Bs},VX=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 ZX(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 JX(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 ND(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=JX(o,e),s=At(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 ND(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=At(l,e);o[c]=s.has(c)?d:d.optional()}if(t.propertyNames){let c=At(t.propertyNames,e),l=t.additionalProperties&&typeof t.additionalProperties=="object"?At(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=At(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(At(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=>At(c,e)),a=i&&typeof i=="object"&&!Array.isArray(i)?At(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=>At(c,e)),a=t.additionalItems&&typeof t.additionalItems=="object"?At(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=At(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 At(t,e){if(typeof t=="boolean")return t?H.any():H.never();let r=ND(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=>At(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=>At(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:At(t.allOf[0],e),c=n?0:1;for(let l=c;l<t.allOf.length;l++)a=H.intersection(a,At(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))VX.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 OD(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=ZX(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 At(r,i)}var Zx={};qt(Zx,{bigint:()=>eY,boolean:()=>QX,date:()=>tY,number:()=>YX,string:()=>XX});function XX(t){return vw(Ks,t)}function YX(t){return Pw(Vs,t)}function QX(t){return $w(Zs,t)}function eY(t){return Nw(Js,t)}function tY(t){return Kw(Bc,t)}Fe(xu());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"},Er={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 jD=Symbol("skippedItem");function F(t,e){return t.catch(e)}function Vr(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(jD)).transform(e=>e.filter(r=>r!==jD))}var nY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminal:u.boolean().optional().default(!1)}),oY=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)}),iY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:u.string(),name:u.string()}),sY=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(oY)}),aY=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()}),cY=u.union([sY.and(u.object({type:u.literal("env_var")})),aY.and(u.object({type:u.literal("terminal")})),iY]),LD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),methodId:u.string()}),lY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),dY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),blob:u.string(),mimeType:u.string().nullish(),uri:u.string()}),uY=u.object({default:u.boolean().nullish(),description:u.string().nullish(),title:u.string().nullish()}),pY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),mY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),fY=u.object({amount:u.number(),currency:u.string()}),gY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),hY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),yY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),newText:u.string(),oldText:u.string().nullish(),path:u.string()}),UD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string()}),vY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),bY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),kY=u.union([u.string(),u.number(),u.number(),u.boolean(),u.array(u.string())]),wY=u.object({content:u.record(u.string(),kY).nullish()}),SY=u.intersection(u.union([wY.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()})),xY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),FD=u.string(),Xx=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),elicitationId:FD}),RY=u.literal("object"),TY=u.literal("string"),PY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),AY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),form:F(xY.nullish(),()=>{}),url:F(PY.nullish(),()=>{})}),HD=u.object({const:u.string(),title:u.string()}),zD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),IY=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"})]),BD=u.object({code:IY,data:u.unknown().optional(),message:u.string()}),qD=u.unknown(),WD=u.unknown(),KD=u.unknown(),CY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),readTextFile:u.boolean().optional().default(!1),writeTextFile:u.boolean().optional().default(!1)}),GD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),value:u.string()}),VD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),name:u.string(),title:u.string().nullish(),version:u.string()}),_Y=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),EY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),ZD=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),JD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cursor:u.string().nullish(),cwd:u.string().nullish()}),Yx=u.union([u.literal("anthropic"),u.literal("openai"),u.literal("azure"),u.literal("vertex"),u.literal("bedrock"),u.string()]),MY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),$Y=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),logout:F(MY.nullish(),()=>{})}),XD=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),DY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),NY=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)}),Np=u.string(),OY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:Np}),jY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:Np}),YD=u.string(),LY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),acpId:YD}),UY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:YD,name:u.string()}),FY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(GD),name:u.string(),url:u.string()}),HY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),headers:u.array(GD),name:u.string(),url:u.string()}),zY=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),args:u.array(u.string()),command:u.string(),env:u.array(zD),name:u.string()}),Op=u.union([FY.and(u.object({type:u.literal("http")})),HY.and(u.object({type:u.literal("sse")})),UY.and(u.object({type:u.literal("acp")})),zY]),BY=u.string(),QD=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:Np,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),e0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),connectionId:Np,method:u.string(),params:u.record(u.string(),u.unknown()).nullish()}),t0=u.unknown(),qY=u.union([u.literal("error"),u.literal("warning"),u.literal("information"),u.literal("hint")]),WY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),KY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),GY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),VY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),ZY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),JY=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()}),XY=u.object({diff:u.string(),uri:u.string()}),YY=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()}),QY=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),e9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),t9=u.object({languageId:u.string(),text:u.string(),uri:u.string()}),r9=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()}),n9=u.union([u.literal("rejected"),u.literal("ignored"),u.literal("replaced"),u.literal("cancelled")]),o9=u.object({excerpts:u.array(YY),uri:u.string()}),i9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),s9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),a9=u.object({name:u.string(),owner:u.string(),remoteUrl:u.string()}),c9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),l9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),jump:F(QY.nullish(),()=>{}),rename:F(s9.nullish(),()=>{}),searchAndReplace:F(c9.nullish(),()=>{})}),d9=u.object({id:u.string(),isRegex:u.boolean().nullish(),replace:u.string(),search:u.string(),uri:u.string()}),u9=u.union([u.literal("automatic"),u.literal("diagnostic"),u.literal("manual")]),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.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:F(WY.nullish(),()=>{}),editHistory:F(JY.nullish(),()=>{}),openFiles:F(e9.nullish(),()=>{}),recentFiles:F(r9.nullish(),()=>{}),relatedSnippets:F(i9.nullish(),()=>{}),userActions:F(p9.nullish(),()=>{})}),r0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(Op)}),f9=u.object({default:u.number().nullish(),description:u.string().nullish(),maximum:u.number().nullish(),minimum:u.number().nullish(),title:u.string().nullish()}),n0=u.string(),g9=u.union([u.literal("allow_once"),u.literal("allow_always"),u.literal("reject_once"),u.literal("reject_always")]),h9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),kind:g9,name:u.string(),optionId:n0}),y9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),v9=u.union([u.literal("high"),u.literal("medium"),u.literal("low")]),b9=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed")]),o0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),priority:v9,status:b9}),k9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:Vr(ye(o0),()=>[])}),jp=u.string(),w9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:jp,uri:u.string()}),S9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),entries:Vr(ye(o0),()=>[]),id:jp}),x9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),id:jp}),R9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:jp}),T9=u.union([S9.and(u.object({type:u.literal("items")})),w9.and(u.object({type:u.literal("file")})),x9.and(u.object({type:u.literal("markdown")}))]),P9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),plan:T9}),jo=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"})}),A9=u.object({id:u.string(),position:jo,uri:u.string()}),I9=u.object({id:u.string(),newName:u.string(),position:jo,uri:u.string()}),C9=u.object({action:u.string(),position:jo,timestampMs:u.number(),uri:u.string()}),i0=u.union([u.literal("utf-16"),u.literal("utf-32"),u.literal("utf-8")]),_9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:nY.optional().default({terminal:!1}),elicitation:F(AY.nullish(),()=>{}),fs:CY.optional().default({readTextFile:!1,writeTextFile:!1}),nes:F(l9.nullish(),()=>{}),plan:F(y9.nullish(),()=>{}),positionEncodings:F(ye(i0).optional(),()=>[]),terminal:u.boolean().optional().default(!1)}),E9=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)}),s0=u.number().int().gte(0).lte(65535),a0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),clientCapabilities:_9.optional().default({auth:{terminal:!1},fs:{readTextFile:!1,writeTextFile:!1},terminal:!1}),clientInfo:F(VD.nullish(),()=>{}),protocolVersion:s0}),M9=u.object({apiType:Yx,baseUrl:u.string()}),$9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),current:M9.nullish(),id:u.string(),required:u.boolean(),supported:Vr(ye(Yx),()=>[])}),D9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),providers:Vr(ye($9),()=>[])}),N9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Xs=u.object({end:jo,start:jo}),O9=u.object({message:u.string(),range:Xs,severity:qY,uri:u.string()}),j9=u.object({languageId:u.string(),lastFocusedMs:F(u.number().nullish(),()=>{}),uri:u.string(),visibleRange:F(Xs.nullish(),()=>{})}),L9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),diagnostics:F(ye(O9).nullish(),()=>{}),editHistory:F(ye(XY).nullish(),()=>{}),openFiles:F(ye(j9).nullish(),()=>{}),recentFiles:F(ye(t9).nullish(),()=>{}),relatedSnippets:F(ye(o9).nullish(),()=>{}),userActions:F(ye(C9).nullish(),()=>{})}),U9=u.object({newText:u.string(),range:Xs}),F9=u.object({cursorPosition:F(jo.nullish(),()=>{}),edits:u.array(U9),id:u.string(),uri:u.string()}),H9=u.union([F9.and(u.object({kind:u.literal("edit")})),A9.and(u.object({kind:u.literal("jump")})),I9.and(u.object({kind:u.literal("rename")})),d9.and(u.object({kind:u.literal("searchAndReplace")}))]),z9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string()}),B9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Lo=u.union([u.number(),u.string()]).nullable(),$Ce=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),requestId:Lo}),c0=u.object({requestId:Lo}),q9=u.enum(["assistant","user"]),Jc=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),audience:F(ye(q9).nullish(),()=>{}),lastModified:u.string().nullish(),priority:u.number().nullish()}),W9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:F(Jc.nullish(),()=>{}),data:u.string(),mimeType:u.string()}),K9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:F(Jc.nullish(),()=>{}),data:u.string(),mimeType:u.string(),uri:u.string().nullish()}),G9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:F(Jc.nullish(),()=>{}),description:u.string().nullish(),mimeType:u.string().nullish(),name:u.string(),size:u.number().nullish(),title:u.string().nullish(),uri:u.string()}),V9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),optionId:n0}),Z9=u.union([u.object({outcome:u.literal("cancelled")}),V9.and(u.object({outcome:u.literal("selected")}))]),J9=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),outcome:Z9}),X9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Y9=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Q9=u.object({currentValue:u.boolean()}),eQ=u.string(),l0=u.string(),tQ=u.union([u.literal("mode"),u.literal("model"),u.literal("thought_level"),u.string()]),Qx=u.string(),d0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),name:u.string(),value:Qx}),rQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),group:eQ,name:u.string(),options:u.array(d0)}),nQ=u.union([u.array(d0),u.array(rQ)]),oQ=u.object({currentValue:Qx,options:nQ}),Ys=u.intersection(u.union([oQ.and(u.object({type:u.literal("select")})),Q9.and(u.object({type:u.literal("boolean")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),category:F(tQ.nullish(),()=>{}),description:u.string().nullish(),id:l0,name:u.string()})),iQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:Vr(ye(Ys),()=>[])}),sQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),aQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),ue=u.string(),u0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),sessionId:ue}),p0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue}),m0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue}),f0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue}),eR=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(zD).optional(),outputByteLimit:u.number().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,uri:u.string()}),y0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),position:jo,sessionId:ue,uri:u.string(),version:u.number(),visibleRange:Xs}),v0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),languageId:u.string(),sessionId:ue,text:u.string(),uri:u.string(),version:u.number()}),b0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,uri:u.string()}),k0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(Op).optional(),sessionId:ue}),tR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,terminalId:u.string()}),w0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:u.array(u.string()).optional(),cwd:u.string(),mcpServers:u.array(Op),sessionId:ue}),rR=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}),S0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),id:u.string(),reason:F(n9.nullish(),()=>{}),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(Op).optional(),sessionId:ue}),cQ=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(),()=>{})}),lQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),nextCursor:u.string().nullish(),sessions:Vr(ye(cQ),()=>[])}),dQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),title:u.string().nullish(),updatedAt:u.string().nullish()}),uQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),Lp=u.string(),pQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),currentModeId:Lp}),mQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string().nullish(),id:Lp,name:u.string()}),Up=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableModes:Vr(ye(mQ),()=>[]),currentModeId:Lp}),fQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:F(ye(Ys).nullish(),()=>{}),modes:F(Up.nullish(),()=>{}),sessionId:ue}),gQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:F(ye(Ys).nullish(),()=>{}),modes:F(Up.nullish(),()=>{})}),hQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:F(ye(Ys).nullish(),()=>{}),modes:F(Up.nullish(),()=>{}),sessionId:ue}),yQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:F(ye(Ys).nullish(),()=>{}),modes:F(Up.nullish(),()=>{})}),vQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),bQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),additionalDirectories:F(X9.nullish(),()=>{}),close:F(Y9.nullish(),()=>{}),delete:F(sQ.nullish(),()=>{}),fork:F(aQ.nullish(),()=>{}),list:F(uQ.nullish(),()=>{}),resume:F(vQ.nullish(),()=>{})}),R0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),apiType:Yx,baseUrl:u.string(),headers:u.record(u.string(),u.string()).optional(),id:u.string()}),kQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),T0=u.intersection(u.union([u.object({type:u.literal("boolean"),value:u.boolean()}),u.object({value:Qx})]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configId:l0,sessionId:ue})),wQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),configOptions:Vr(ye(Ys),()=>[])}),P0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),modeId:Lp,sessionId:ue}),SQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),xQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue}),RQ=u.union([u.literal("end_turn"),u.literal("max_tokens"),u.literal("max_turn_requests"),u.literal("refusal"),u.literal("cancelled")]),TQ=u.union([u.literal("email"),u.literal("uri"),u.literal("date"),u.literal("date-time")]),PQ=u.object({default:u.string().nullish(),description:u.string().nullish(),enum:u.array(u.string()).nullish(),format:TQ.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(HD).nullish(),pattern:u.string().nullish(),title:u.string().nullish()}),A0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:F(L9.nullish(),()=>{}),position:jo,selection:F(Xs.nullish(),()=>{}),sessionId:ue,triggerKind:u9,uri:u.string(),version:u.number()}),AQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),suggestions:Vr(ye(H9),()=>[])}),IQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),terminalId:u.string()}),CQ=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()}),oR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,terminalId:u.string()}),_Q=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),exitStatus:CQ.nullish(),output:u.string(),truncated:u.boolean()}),EQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:F(Jc.nullish(),()=>{}),text:u.string()}),MQ=u.object({range:Xs.nullish(),text:u.string()}),I0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),contentChanges:u.array(MQ),sessionId:ue,uri:u.string(),version:u.number()}),DCe=u.object({method:u.string(),params:u.union([p0,v0,I0,h0,b0,y0,u0,S0,QD,qD]).nullish()}),$Q=u.union([u.literal("full"),u.literal("incremental")]),DQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),syncKind:$Q}),NQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),didChange:F(DQ.nullish(),()=>{}),didClose:F(KY.nullish(),()=>{}),didFocus:F(GY.nullish(),()=>{}),didOpen:F(VY.nullish(),()=>{}),didSave:F(ZY.nullish(),()=>{})}),OQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),document:F(NQ.nullish(),()=>{})}),jQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),context:F(m9.nullish(),()=>{}),events:F(OQ.nullish(),()=>{})}),LQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),auth:$Y.optional().default({}),loadSession:u.boolean().optional().default(!1),mcpCapabilities:NY.optional().default({acp:!1,http:!1,sse:!1}),nes:F(jQ.nullish(),()=>{}),positionEncoding:F(i0.nullish(),()=>{}),promptCapabilities:E9.optional().default({audio:!1,embeddedContext:!1,image:!1}),providers:F(N9.nullish(),()=>{}),sessionCapabilities:bQ.optional().default({})}),UQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),agentCapabilities:LQ.optional().default({auth:{},loadSession:!1,mcpCapabilities:{acp:!1,http:!1,sse:!1},promptCapabilities:{audio:!1,embeddedContext:!1,image:!1},sessionCapabilities:{}}),agentInfo:F(VD.nullish(),()=>{}),authMethods:F(ye(cY).optional().default([]),()=>[]),protocolVersion:s0}),FQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),mimeType:u.string().nullish(),text:u.string(),uri:u.string()}),HQ=u.union([FQ,dY]),zQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),annotations:F(Jc.nullish(),()=>{}),resource:HQ}),iR=u.union([EQ.and(u.object({type:u.literal("text")})),K9.and(u.object({type:u.literal("image")})),W9.and(u.object({type:u.literal("audio")})),G9.and(u.object({type:u.literal("resource_link")})),zQ.and(u.object({type:u.literal("resource")}))]),BQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:iR}),Jx=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:iR,messageId:BY.nullish()}),C0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),prompt:u.array(iR),sessionId:ue}),qQ=u.object({anyOf:u.array(HD)}),_0=u.union([BQ.and(u.object({type:u.literal("content")})),yY.and(u.object({type:u.literal("diff")})),IQ.and(u.object({type:u.literal("terminal")}))]),sR=u.string(),E0=u.object({sessionId:ue,toolCallId:sR.nullish()}),WQ=u.intersection(u.union([E0,c0]),u.object({elicitationId:FD,url:u.string().url()})),M0=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()}),$0=u.union([u.literal("pending"),u.literal("in_progress"),u.literal("completed"),u.literal("failed")]),D0=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")]),KQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:F(ye(_0).optional(),()=>[]),kind:D0.optional(),locations:F(ye(M0).optional(),()=>[]),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:$0.optional(),title:u.string(),toolCallId:sR}),N0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:F(ye(_0).nullish(),()=>{}),kind:F(D0.nullish(),()=>{}),locations:F(ye(M0).nullish(),()=>{}),rawInput:u.unknown().optional(),rawOutput:u.unknown().optional(),status:F($0.nullish(),()=>{}),title:u.string().nullish(),toolCallId:sR}),aR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),options:u.array(h9),sessionId:ue,toolCall:N0}),GQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),hint:u.string()}),VQ=GQ,ZQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),description:u.string(),input:F(VQ.nullish(),()=>{}),name:u.string()}),JQ=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),availableCommands:Vr(ye(ZQ),()=>[])}),XQ=u.object({enum:u.array(u.string()),type:TY}),YQ=u.union([XQ,qQ]),QQ=u.object({default:u.array(u.string()).nullish(),description:u.string().nullish(),items:YQ,maxItems:u.number().nullish(),minItems:u.number().nullish(),title:u.string().nullish()}),e7=u.union([PQ.and(u.object({type:u.literal("string")})),f9.and(u.object({type:u.literal("number")})),_Y.and(u.object({type:u.literal("integer")})),uY.and(u.object({type:u.literal("boolean")})),QQ.and(u.object({type:u.literal("array")}))]),t7=u.object({description:u.string().nullish(),properties:u.record(u.string(),e7).optional().default({}),required:u.array(u.string()).nullish(),title:u.string().nullish(),type:RY.optional().default("object")}),r7=u.intersection(u.union([E0,c0]),u.object({requestedSchema:t7})),cR=u.intersection(u.union([r7.and(u.object({mode:u.literal("form")})),WQ.and(u.object({mode:u.literal("url")}))]),u.object({_meta:u.record(u.string(),u.unknown()).nullish(),message:u.string()})),n7=u.object({cachedReadTokens:u.number().nullish(),cachedWriteTokens:u.number().nullish(),inputTokens:u.number(),outputTokens:u.number(),thoughtTokens:u.number().nullish(),totalTokens:u.number()}),o7=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),stopReason:RQ,usage:F(n7.nullish(),()=>{})}),NCe=u.union([u.object({id:Lo,result:u.union([UQ,lY,D9,kQ,vY,DY,hQ,gQ,lQ,hY,fQ,yQ,mY,SQ,wQ,o7,xQ,AQ,pY,KD,t0])}),u.object({error:BD,id:Lo})]),i7=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),cost:F(fY.nullish(),()=>{}),size:u.number(),used:u.number()}),s7=u.union([Jx.and(u.object({sessionUpdate:u.literal("user_message_chunk")})),Jx.and(u.object({sessionUpdate:u.literal("agent_message_chunk")})),Jx.and(u.object({sessionUpdate:u.literal("agent_thought_chunk")})),KQ.and(u.object({sessionUpdate:u.literal("tool_call")})),N0.and(u.object({sessionUpdate:u.literal("tool_call_update")})),k9.and(u.object({sessionUpdate:u.literal("plan")})),P9.and(u.object({sessionUpdate:u.literal("plan_update")})),R9.and(u.object({sessionUpdate:u.literal("plan_removed")})),JQ.and(u.object({sessionUpdate:u.literal("available_commands_update")})),pQ.and(u.object({sessionUpdate:u.literal("current_mode_update")})),iQ.and(u.object({sessionUpdate:u.literal("config_option_update")})),dQ.and(u.object({sessionUpdate:u.literal("session_info_update")})),i7.and(u.object({sessionUpdate:u.literal("usage_update")}))]),lR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,update:s7}),OCe=u.object({method:u.string(),params:u.union([lR,Xx,QD,qD]).nullish()}),dR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),sessionId:ue,terminalId:u.string()}),a7=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()}),c7=u.object({name:u.string(),uri:u.string()}),O0=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),repository:F(a9.nullish(),()=>{}),workspaceFolders:F(ye(c7).nullish(),()=>{}),workspaceUri:u.string().nullish()}),jCe=u.object({id:Lo,method:u.string(),params:u.union([a0,LD,ZD,R0,UD,XD,r0,w0,JD,g0,k0,x0,f0,P0,T0,C0,O0,A0,m0,e0,WD]).nullish()}),uR=u.object({_meta:u.record(u.string(),u.unknown()).nullish(),content:u.string(),path:u.string(),sessionId:ue}),LCe=u.object({id:Lo,method:u.string(),params:u.union([uR,rR,aR,eR,oR,nR,dR,tR,cR,LY,e0,jY,WD]).nullish()}),l7=u.object({_meta:u.record(u.string(),u.unknown()).nullish()}),UCe=u.union([u.object({id:Lo,result:u.union([l7,z9,J9,gY,_Q,B9,a7,EY,SY,OY,bY,KD,t0])}),u.object({error:BD,id:Lo})]);function j0(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(`
|
|
644
644
|
`);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)+`
|
|
645
|
-
`,c=t.getWriter();try{await c.write(r.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function Uo(t){return t??{}}function L0(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var Fp=class{connection;constructor(e,r){let n=e(this),o=async(s,a)=>{switch(s){case Er.fs_write_text_file:{let c=uR.parse(a);return await n.writeTextFile?.(c)??{}}case Er.fs_read_text_file:{let c=rR.parse(a);return n.readTextFile?.(c)}case Er.session_request_permission:{let c=aR.parse(a);return n.requestPermission(c)}case Er.terminal_create:{let c=eR.parse(a);return n.createTerminal?.(c)}case Er.terminal_output:{let c=oR.parse(a);return n.terminalOutput?.(c)}case Er.terminal_release:{let c=nR.parse(a);return await n.releaseTerminal?.(c)??{}}case Er.terminal_wait_for_exit:{let c=dR.parse(a);return n.waitForTerminalExit?.(c)}case Er.terminal_kill:{let c=tR.parse(a);return await n.killTerminal?.(c)??{}}case Er.elicitation_create:{if(!n.unstable_createElicitation)throw Xt.methodNotFound(s);let c=cR.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 Er.session_update:{let c=lR.parse(a);return n.sessionUpdate(c)}case Er.elicitation_complete:{if(!n.unstable_completeElicitation)return;let c=Xx.parse(a);return n.unstable_completeElicitation(c)}default:if(n.extNotification)return n.extNotification(s,a);throw Xt.methodNotFound(s)}};this.connection=new pR(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,Uo)}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,Uo)}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,Uo)}setSessionConfigOption(e){return this.connection.sendRequest(Se.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(Se.authenticate,e,Uo)}unstable_listProviders(e){return this.connection.sendRequest(Se.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(Se.providers_set,e,Uo)}unstable_disableProvider(e){return this.connection.sendRequest(Se.providers_disable,e,Uo)}logout(e){return this.connection.sendRequest(Se.logout,e,Uo)}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,Uo)}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}},pR=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 L0(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?L0(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 m7=1,f7=2e4,U0=3e4,g7=3e5,Zr={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"},Xc=class extends Error{retryable=!1;authMethods;constructor(e,r){super(e),this.name="AcpAuthRequiredError",this.authMethods=r}};function Yc(t,e){if(t instanceof Xc)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 Xc(`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 Xc(s,e)}return null}function h7(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 Fo=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=j0(p7.toWeb(e.stdin),u7.toWeb(e.stdout));this.conn=new Fp(()=>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:m7,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),f7,"initialize").catch(i=>{throw Yc(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),U0,"session/new").catch(i=>{throw Yc(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=g7){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 Yc(a)??h7(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),U0,"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 Zr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case Zr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case Zr.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 Zr.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 Zr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case Zr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case Zr.AVAILABLE_COMMANDS_UPDATE:case Zr.CURRENT_MODE_UPDATE:case Zr.CONFIG_OPTION_UPDATE:case Zr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case Zr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as y7}from"node:child_process";import{readFile as v7,writeFile as b7}from"node:fs/promises";import{isAbsolute as F0,normalize as k7,relative as w7,resolve as S7,sep as x7}from"node:path";function R7(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 mR(t){let e=new Map,r=0,n=i=>{let s=F0(i)?k7(i):S7(t.cwd,i),a=w7(t.cwd,s);if(a===".."||a.startsWith(`..${x7}`)||F0(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:R7(i)}},async readTextFile(i){return{content:await v7(n(i.path),"utf8")}},async writeTextFile(i){return await b7(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=y7(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 Qc=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 T7,execFileSync as P7,execSync as q0}from"node:child_process";import{existsSync as Hp,mkdirSync as A7,readFileSync as gR,readdirSync as I7,writeFileSync as C7}from"node:fs";import{homedir as _7,platform as E7,tmpdir as M7}from"node:os";import{dirname as $7,join as Kn}from"node:path";import{promisify as D7}from"node:util";var N7=D7(T7),tl={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"}},O7=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],H0={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 Qs(t){let e=tl[t];if(e)return H0[t]?{...e,...H0[t]}:e}function hR(){return O7.map(t=>{let e=Qs(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Ei=E7()==="win32",j7=5*6e4,el,z0=new Map;function fR(t){try{let e=Ei?`where ${t}`:`which ${t}`;return q0(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function L7(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 U7(){if(!Ei)return null;let t=[process.env.COPILOT_CACHE_HOME?Kn(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?Kn(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?Kn(process.env.COPILOT_HOME,"pkg","win32-x64"):null,Kn(_7(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let r=I7(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name).sort(L7);for(let n of r){let o=Kn(e,n,"npm-loader.js");if(Hp(o)&&G0(o))return o}}catch{}return null}function F7(t){return t.id==="copilot"?U7()??fR(t.cliCommand):fR(t.cliCommand)}function H7(t,e){return P7(Ei?"cmd.exe":"npm",Ei?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"]}).trim()}async function z7(t,e){let{stdout:r}=await N7(Ei?"cmd.exe":"npm",Ei?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function B7(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 yR(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 B7(o)}}return null}function zp(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function q7(t,e){let r=i=>{let s=zp(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 W7(t,e){return!t||!e?!1:q7(t,e)>0}function K7(){if(el!==void 0)return el;try{el=H7(["root","-g"],3e3)||null}catch{el=null}return el}function vR(t){if(!t)return null;let e=K7();if(!e)return null;let r=Kn(e,...t.split("/"),"package.json");try{let n=JSON.parse(gR(r,"utf8"));return typeof n.version=="string"?n.version:null}catch{return null}}function G7(t){let e=yR(t?.npm);return vR(e)}function W0(t,e){let r=yR(t.install?.npm),o=vR(r)??zp(e)??e??void 0;return{packageName:r??void 0,installedVersion:o,updateAvailable:!1}}async function V7(t){if(!t)return null;let e=z0.get(t);if(e&&Date.now()-e.timestamp<j7)return e.version;let r=null;try{let n=await z7(["view",t,"version","--json"],12e3),o=n?JSON.parse(n):null;r=typeof o=="string"?o:zp(n)}catch{r=null}return z0.set(t,{timestamp:Date.now(),version:r}),r}async function K0(t){let e=t.map(async({id:n,entry:o,detectedVersion:i})=>{let s=yR(o.install?.npm),a=vR(s)??zp(i)??i??void 0;if(!s||!a)return null;let c=await V7(s)??void 0;return c?{id:n,packageName:s,installedVersion:a,latestVersion:c,updateAvailable:W7(c,a)}:null});return(await Promise.all(e)).filter(n=>n!==null)}function G0(t){try{let e=t.endsWith("npm-loader.js")?`"${process.execPath}" "${t}" version`:`"${t}" version`;return q0(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}function Z7(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=J7(t);return r?{cliPath:process.execPath,acpArgs:[r,...e]}:{cliPath:t,acpArgs:e}}function J7(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),r=[`${e}.cmd`,`${e}.ps1`,e];for(let n of r){if(!Hp(n))continue;let o;try{o=gR(n,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=Kn($7(e),s);if(Hp(a))return a}return null}var X7=6e4;function Y7(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 B0=new Set(["codex","qwen","opencode"]);function Q7(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function eee(t){let e=Kn(M7(),"qlogicagent-codex-model-catalog");A7(e,{recursive:!0});let r=Kn(e,`${Q7(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(!Hp(r)||gR(r,"utf8")!==n)&&C7(r,n,"utf8"),r}function tee(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),B0.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&&B0.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 ree(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=${eee(i)}`]:e}var ea=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<X7)return this.cache.agents;let r=[];for(let n of Object.values(tl))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=F7(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=Qs(e.id),i=G0(r)??G7(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=fR(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=Qs(e)??tl[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}:Z7(r.cliPath,s),c=tee(n,this.keySources),l=o?.customArgs?.length?a.acpArgs:ree(n,a.acpArgs,c,this.keySources);return{id:e,cliPath:a.cliPath,acpArgs:l,env:Y7(n,o,c),protocol:"acp"}}isAgentReady(e){if(e==="qlogicagent")return!0;let r=this.buildExternalDescriptor(e);if(!r)return!1;let n=Qs(e)??tl[e];return n?.apiKeyEnvVar&&n.authMode!=="oauth"?!!r.env?.[n.apiKeyEnvVar]:!0}};var kR="https://registry.npmmirror.com",ta="https://pypi.tuna.tsinghua.edu.cn/simple",bR="https://registry.npmmirror.com/-/binary";function V0(){return{npm_config_registry:kR,PIP_INDEX_URL:ta,UV_DEFAULT_INDEX:ta,UV_INDEX_URL:ta,UV_PYTHON_INSTALL_MIRROR:`${bR}/python-build-standalone`,NODEJS_ORG_MIRROR:`${bR}/node`,npm_config_disturl:`${bR}/node`}}var wR=Object.keys(V0());var dee=1;function uee(t,e){return{jsonrpc:"2.0",id:dee++,method:t,params:e,meta:Nv(t)}}var pee=["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",...wR],mee=["127.0.0.1","localhost","::1"];function fee(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 mee)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 gee(t){let e={};for(let r of pee)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),fee(e)}function Z0(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 xR=Qh,hee=ey,ra=ty,J0=ry;function yee(t){return new Promise(e=>setTimeout(e,t))}function vee(t){return t.replace(/[<>:"/\\|?*\x00-\x1F]/g,"-")}function bee(t,e){if(process.platform==="win32"&&typeof e=="number"&&e>0)try{nee("taskkill",["/PID",String(e),"/T","/F"],()=>{});return}catch{}try{t.kill("SIGTERM"),setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},1e4)}catch{}}var Mr=class t{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let r=oee(rl(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=rl(r,"dist","cli.js"),this.mcpBridgeScriptPath=rl(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=gee(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=SR(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}),Bp({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=Fo.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&&Bp({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=iee(),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=uee(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)}
|
|
645
|
+
`,c=t.getWriter();try{await c.write(r.encode(a))}finally{c.releaseLock()}}});return{readable:o,writable:i}}function Uo(t){return t??{}}function L0(t){let e=Promise.reject(t);return e.catch(()=>{}),e}var Fp=class{connection;constructor(e,r){let n=e(this),o=async(s,a)=>{switch(s){case Er.fs_write_text_file:{let c=uR.parse(a);return await n.writeTextFile?.(c)??{}}case Er.fs_read_text_file:{let c=rR.parse(a);return n.readTextFile?.(c)}case Er.session_request_permission:{let c=aR.parse(a);return n.requestPermission(c)}case Er.terminal_create:{let c=eR.parse(a);return n.createTerminal?.(c)}case Er.terminal_output:{let c=oR.parse(a);return n.terminalOutput?.(c)}case Er.terminal_release:{let c=nR.parse(a);return await n.releaseTerminal?.(c)??{}}case Er.terminal_wait_for_exit:{let c=dR.parse(a);return n.waitForTerminalExit?.(c)}case Er.terminal_kill:{let c=tR.parse(a);return await n.killTerminal?.(c)??{}}case Er.elicitation_create:{if(!n.unstable_createElicitation)throw Xt.methodNotFound(s);let c=cR.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 Er.session_update:{let c=lR.parse(a);return n.sessionUpdate(c)}case Er.elicitation_complete:{if(!n.unstable_completeElicitation)return;let c=Xx.parse(a);return n.unstable_completeElicitation(c)}default:if(n.extNotification)return n.extNotification(s,a);throw Xt.methodNotFound(s)}};this.connection=new pR(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,Uo)}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,Uo)}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,Uo)}setSessionConfigOption(e){return this.connection.sendRequest(Se.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(Se.authenticate,e,Uo)}unstable_listProviders(e){return this.connection.sendRequest(Se.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(Se.providers_set,e,Uo)}unstable_disableProvider(e){return this.connection.sendRequest(Se.providers_disable,e,Uo)}logout(e){return this.connection.sendRequest(Se.logout,e,Uo)}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,Uo)}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}},pR=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 L0(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?L0(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 m7=1,f7=2e4,U0=3e4,g7=3e5,Zr={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"},Xc=class extends Error{retryable=!1;authMethods;constructor(e,r){super(e),this.name="AcpAuthRequiredError",this.authMethods=r}};function Yc(t,e){if(t instanceof Xc)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 Xc(`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 Xc(s,e)}return null}function h7(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 Fo=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=j0(p7.toWeb(e.stdin),u7.toWeb(e.stdout));this.conn=new Fp(()=>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:m7,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),f7,"initialize").catch(i=>{throw Yc(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),U0,"session/new").catch(i=>{throw Yc(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=g7){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 Yc(a)??h7(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),U0,"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 Zr.AGENT_MESSAGE_CHUNK:{let a=o.content;return{method:"turn.delta",params:{text:a?.text??a?.content??"",sessionId:s,messageId:o.messageId}}}case Zr.AGENT_THOUGHT_CHUNK:return{method:"turn.thought_delta",params:{text:o.content?.text??"",sessionId:s}};case Zr.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 Zr.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 Zr.USAGE_UPDATE:return{method:"turn.usage_update",params:o??{}};case Zr.PLAN:return{method:"turn.plan",params:{steps:o.steps,sessionId:s}};case Zr.AVAILABLE_COMMANDS_UPDATE:case Zr.CURRENT_MODE_UPDATE:case Zr.CONFIG_OPTION_UPDATE:case Zr.SESSION_INFO_UPDATE:return{method:"turn.session_info",params:{type:i,...o,sessionId:s}};case Zr.USER_MESSAGE_CHUNK:return null;default:return{method:`turn.${i??"unknown"}`,params:{...o,sessionId:s}}}}return null}};import{spawn as y7}from"node:child_process";import{readFile as v7,writeFile as b7}from"node:fs/promises";import{isAbsolute as F0,normalize as k7,relative as w7,resolve as S7,sep as x7}from"node:path";function R7(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 mR(t){let e=new Map,r=0,n=i=>{let s=F0(i)?k7(i):S7(t.cwd,i),a=w7(t.cwd,s);if(a===".."||a.startsWith(`..${x7}`)||F0(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:R7(i)}},async readTextFile(i){return{content:await v7(n(i.path),"utf8")}},async writeTextFile(i){return await b7(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=y7(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 Qc=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 T7,execFileSync as P7,execSync as q0}from"node:child_process";import{existsSync as Hp,mkdirSync as A7,readFileSync as gR,readdirSync as I7,writeFileSync as C7}from"node:fs";import{homedir as _7,platform as E7,tmpdir as M7}from"node:os";import{dirname as $7,join as Kn}from"node:path";import{promisify as D7}from"node:util";var N7=D7(T7),tl={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"}},O7=["claude","codex","gemini","copilot","cursor","qwen","kimi","glm","opencode","kiro","qoder","openclaw","hermes"],H0={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 Qs(t){let e=tl[t];if(e)return H0[t]?{...e,...H0[t]}:e}function hR(){return O7.map(t=>{let e=Qs(t);if(!e)throw new Error(`Agent catalog entry "${t}" has no backend definition`);return e})}var Ei=E7()==="win32",j7=5*6e4,el,z0=new Map;function fR(t){try{let e=Ei?`where ${t}`:`which ${t}`;return q0(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().split(/\r?\n/)[0]?.trim()||null}catch{return null}}function L7(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 U7(){if(!Ei)return null;let t=[process.env.COPILOT_CACHE_HOME?Kn(process.env.COPILOT_CACHE_HOME,"pkg","win32-x64"):null,process.env.LOCALAPPDATA?Kn(process.env.LOCALAPPDATA,"copilot","pkg","win32-x64"):null,process.env.COPILOT_HOME?Kn(process.env.COPILOT_HOME,"pkg","win32-x64"):null,Kn(_7(),".copilot","pkg","win32-x64")].filter(e=>!!e);for(let e of t)try{let r=I7(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name).sort(L7);for(let n of r){let o=Kn(e,n,"npm-loader.js");if(Hp(o)&&G0(o))return o}}catch{}return null}function F7(t){return t.id==="copilot"?U7()??fR(t.cliCommand):fR(t.cliCommand)}function H7(t,e){return P7(Ei?"cmd.exe":"npm",Ei?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e,stdio:["ignore","pipe","ignore"]}).trim()}async function z7(t,e){let{stdout:r}=await N7(Ei?"cmd.exe":"npm",Ei?["/d","/s","/c","npm",...t]:t,{encoding:"utf8",timeout:e});return r.trim()}function B7(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 yR(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 B7(o)}}return null}function zp(t){return t?t.trim().match(/v?(\d+\.\d+\.\d+(?:[-+][\w.-]+)?|\d+\.\d+(?:[-+][\w.-]+)?)/)?.[1]??null:null}function q7(t,e){let r=i=>{let s=zp(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 W7(t,e){return!t||!e?!1:q7(t,e)>0}function K7(){if(el!==void 0)return el;try{el=H7(["root","-g"],3e3)||null}catch{el=null}return el}function vR(t){if(!t)return null;let e=K7();if(!e)return null;let r=Kn(e,...t.split("/"),"package.json");try{let n=JSON.parse(gR(r,"utf8"));return typeof n.version=="string"?n.version:null}catch{return null}}function G7(t){let e=yR(t?.npm);return vR(e)}function W0(t,e){return vR(yR(t.install?.npm))??zp(e)??e??void 0}async function V7(t){if(!t)return null;let e=z0.get(t);if(e&&Date.now()-e.timestamp<j7)return e.version;let r=null;try{let n=await z7(["view",t,"version","--json"],12e3),o=n?JSON.parse(n):null;r=typeof o=="string"?o:zp(n)}catch{r=null}return z0.set(t,{timestamp:Date.now(),version:r}),r}async function K0(t){let e=t.map(async({id:n,entry:o,detectedVersion:i})=>{let s=yR(o.install?.npm),a=vR(s)??zp(i)??i??void 0;if(!s||!a)return null;let c=await V7(s)??void 0;return c?{id:n,packageName:s,installedVersion:a,latestVersion:c,updateAvailable:W7(c,a)}:null});return(await Promise.all(e)).filter(n=>n!==null)}function G0(t){try{let e=t.endsWith("npm-loader.js")?`"${process.execPath}" "${t}" version`:`"${t}" version`;return q0(e,{encoding:"utf8",timeout:5e3,stdio:["pipe","pipe","pipe"]}).trim().match(/(\d+\.\d+[\w.-]*)/)?.[1]??null}catch{return null}}function Z7(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=J7(t);return r?{cliPath:process.execPath,acpArgs:[r,...e]}:{cliPath:t,acpArgs:e}}function J7(t){let e=t.replace(/\.(cmd|ps1|exe)$/i,""),r=[`${e}.cmd`,`${e}.ps1`,e];for(let n of r){if(!Hp(n))continue;let o;try{o=gR(n,"utf8")}catch{continue}let i=o.match(/["']?[^"'\s]*?(node_modules[\\/][^"'\s]*?\.js)["']?/i);if(!i)continue;let s=i[1].replace(/\\/g,"/"),a=Kn($7(e),s);if(Hp(a))return a}return null}var X7=6e4;function Y7(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 B0=new Set(["codex","qwen","opencode"]);function Q7(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"model"}function eee(t){let e=Kn(M7(),"qlogicagent-codex-model-catalog");A7(e,{recursive:!0});let r=Kn(e,`${Q7(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(!Hp(r)||gR(r,"utf8")!==n)&&C7(r,n,"utf8"),r}function tee(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),B0.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&&B0.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 ree(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=${eee(i)}`]:e}var ea=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<X7)return this.cache.agents;let r=[];for(let n of Object.values(tl))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=F7(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=Qs(e.id),i=G0(r)??G7(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=fR(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=Qs(e)??tl[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}:Z7(r.cliPath,s),c=tee(n,this.keySources),l=o?.customArgs?.length?a.acpArgs:ree(n,a.acpArgs,c,this.keySources);return{id:e,cliPath:a.cliPath,acpArgs:l,env:Y7(n,o,c),protocol:"acp"}}isAgentReady(e){if(e==="qlogicagent")return!0;let r=this.buildExternalDescriptor(e);if(!r)return!1;let n=Qs(e)??tl[e];return n?.apiKeyEnvVar&&n.authMode!=="oauth"?!!r.env?.[n.apiKeyEnvVar]:!0}};var kR="https://registry.npmmirror.com",ta="https://pypi.tuna.tsinghua.edu.cn/simple",bR="https://registry.npmmirror.com/-/binary";function V0(){return{npm_config_registry:kR,PIP_INDEX_URL:ta,UV_DEFAULT_INDEX:ta,UV_INDEX_URL:ta,UV_PYTHON_INSTALL_MIRROR:`${bR}/python-build-standalone`,NODEJS_ORG_MIRROR:`${bR}/node`,npm_config_disturl:`${bR}/node`}}var wR=Object.keys(V0());var dee=1;function uee(t,e){return{jsonrpc:"2.0",id:dee++,method:t,params:e,meta:Nv(t)}}var pee=["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",...wR],mee=["127.0.0.1","localhost","::1"];function fee(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 mee)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 gee(t){let e={};for(let r of pee)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),fee(e)}function Z0(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 xR=Qh,hee=ey,ra=ty,J0=ry;function yee(t){return new Promise(e=>setTimeout(e,t))}function vee(t){return t.replace(/[<>:"/\\|?*\x00-\x1F]/g,"-")}function bee(t,e){if(process.platform==="win32"&&typeof e=="number"&&e>0)try{nee("taskkill",["/PID",String(e),"/T","/F"],()=>{});return}catch{}try{t.kill("SIGTERM"),setTimeout(()=>{try{t.kill("SIGKILL")}catch{}},1e4)}catch{}}var Mr=class t{processes=new Map;callbacks;cliBinaryPath;mcpBridgeScriptPath;constructor(e={}){this.callbacks=e;let r=oee(rl(import.meta.url.startsWith("file://")?new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/,"$1"):process.cwd(),"..",".."));this.cliBinaryPath=rl(r,"dist","cli.js"),this.mcpBridgeScriptPath=rl(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=gee(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=SR(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}),Bp({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=Fo.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&&Bp({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=iee(),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=uee(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
646
|
`)}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})}
|
|
647
647
|
`)}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<=xR;i++)try{if(i>0){this.processes.delete(e.memberId),r.state="starting",r.error=void 0,r.endedAt=void 0;let s=hee*i;this.slog("info",e.memberId,"spawn",`retry ${i}/${xR} after ${s}ms`),await yee(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 ${xR+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:Z0(n)},this.slog("info",e.memberId,"spawn",`spawning ACP ${e.name} via ${i.cliPath} ${s.join(" ")} env: ${Z0(n)}`);let a=SR(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 Fo,d=new Qc,{server:p,pipePath:m}=this.createMcpIpcServer(e.memberId);n.QLOGICAGENT_PARENT_RPC=m;let f;if(this.callbacks.sessionDir)try{cee(this.callbacks.sessionDir,{recursive:!0}),r.stderrLogPath=rl(this.callbacks.sessionDir,`${vee(e.memberId)}.stderr.log`),f=aee(r.stderrLogPath,{flags:"a"})}catch{}let g=mR({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=Fo.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&&Bp({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}
|
|
648
648
|
`)}),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<ra){let S=J0*2**w;this.slog("warn",e.memberId,"crash",`crashed (code=${h}), restarting ${w+1}/${ra} after ${S}ms`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${h}, signal=${y}), restarting`,retriesLeft:ra-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=Yc(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{}bee(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()}`:rl(lee(),`qlogicagent-mcp-${r}-${Date.now()}.sock`),o=see(i=>{let s="";i.on("data",a=>{s+=a.toString();let c;for(;(c=s.indexOf(`
|
|
@@ -651,9 +651,9 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
651
651
|
`;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)}})+`
|
|
652
652
|
`;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}`}})+`
|
|
653
653
|
`;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=SR(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 Fo,h=new Qc,y=mR({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=Fo.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&&Bp({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}
|
|
654
|
-
`)}),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(_<ra){let R=J0*2**_;this.slog("warn",e.memberId,"crash",`crashed again (code=${w}), restart ${_+1}/${ra}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${w}), restarting`,retriesLeft:ra-_-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 X0}from"node:child_process";var Q0=/[|&;><$`(){}]/;function kee(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=Q0.test(i);if(!(s&&r)&&!(i.startsWith("brew ")&&!n))return{command:i,shell:s}}return null}function wee(t,e){if(e!=="cn")return t;let r=t.trim();return/^npm\b/.test(r)&&!/(?:^|\s)--registry(?:\s|=)/.test(r)?`${r} --registry ${kR}`:/^uv\b/.test(r)&&!/(?:^|\s)--(?:default-)?index(?:-url)?(?:\s|=)/.test(r)?`${r} --default-index ${ta}`:/^(?:pipx|pip3?|python -m pip)\b/.test(r)&&!/(?:^|\s)--index-url(?:\s|=)/.test(r)?`${r} --index-url ${ta}`:r}function Y0(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 See=(t,e)=>{if(e)return X0(t,{shell:!0,stdio:["ignore","pipe","pipe"]});let r=t.split(/\s+/).filter(Boolean);return X0(r[0],r.slice(1),{stdio:["ignore","pipe","pipe"]})};async function eN(t,e,r={}){let n=r.platform??process.platform,o=r.spawnImpl??See,i=kee(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=wee(i.command,r.mirror);e({type:"state",state:"installing"});let a=await Y0(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 Y0(c,Q0.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 It=new Map,xee=10*6e4,Ree=6e4,Tee=6,qp=null;function Wp(t,e,r){return`${t}\0${e}\0${r??"default"}`}function nl(t){try{t.manager.kill(t.memberId)}catch{}try{t.manager.dispose()}catch{}}function tN(t){let e=It.get(t);if(e){if(!e.manager.isAlive(e.memberId)){It.delete(t),nl(e);return}return e}}function rN(t,e){let r=It.get(t);r&&r!==e&&(It.delete(t),nl(r)),It.set(t,e),Pee(),Iee()}function nN(t,e){let r=It.get(t);if(!r)return;if(!r.manager.isAlive(r.memberId)){It.delete(t),nl(r);return}It.delete(t);let n=It.get(e);return n&&n!==r&&(It.delete(e),nl(n)),It.set(e,r),r.lastUsed=Date.now(),r}var Kp="__warm__";function Gp(t){let e=It.get(t);e&&(It.delete(t),nl(e))}function Pee(){for(;It.size>Tee;){let t=null,e=Number.POSITIVE_INFINITY;for(let[r,n]of It)n.holder.current||n.lastUsed<e&&(e=n.lastUsed,t=r);if(!t)break;Gp(t)}}function Aee(t){for(let[e,r]of[...It.entries()])r.holder.current||t-r.lastUsed>xee&&Gp(e)}function Iee(){qp||(qp=setInterval(()=>Aee(Date.now()),Ree),typeof qp.unref=="function"&&qp.unref())}import{randomUUID as Cee}from"node:crypto";var na=new Map;function _ee(t,e){let r=na.get(t);return r&&(clearTimeout(r.timer),r.resolve(null),na.delete(t)),new Promise(n=>{let o=setTimeout(()=>{na.delete(t),n(null)},e);typeof o.unref=="function"&&o.unref(),na.set(t,{resolve:n,timer:o})})}function oN(t,e){let r=na.get(t);return r?(clearTimeout(r.timer),na.delete(t),r.resolve(e),!0):!1}function Eee(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}async function iN(t,e){let r=e.turnContext(),n=t.toolCall&&typeof t.toolCall=="object"?t.toolCall:{},o=typeof t.permissionId=="string"&&t.permissionId?t.permissionId:Cee(),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:Eee(n.rawInput),message:typeof t.message=="string"?t.message:void 0,category:typeof t.category=="string"?t.category:"destructive",options:i});let a=await _ee(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 $ee(t){let e=t?.rawInput;if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}function Dee(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 aN(t){let e=t?.authMethods;return Array.isArray(e)&&e.length>0?e:void 0}function cN(t){return t instanceof Error?t.message:String(t)}async function Nee(t){let e=aN(t.error);if(!t.sessionId||!e)return;let r=cN(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 fs(t.sessionId,t.projectRoot);await at(t.sessionId,{type:"personal",...t.projectId?{projectId:t.projectId}:{},...o!==null?{messageCount:o}:{},...n?.title?{}:{title:nc(t.prompt,"External agent login required")},...n?.agentId?{}:{agentId:t.agentId}},t.projectRoot)}async function lN(t){let e=t.params,r=typeof e?.approvalId=="string"?e.approvalId:"",n=typeof e?.optionId=="string"?e.optionId:"",o=r&&n?oN(r,n):!1;t.id!==void 0&&this.sendResponse(t.id,{ok:o})}async function dN(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 uN(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 pN(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=hR().map(o=>{let i=r.get(o.id),s=W0(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 mN(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=hR().map(i=>({id:i.id,entry:i,detectedVersion:r.get(i.id)?.version})),o=await K0(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 fN(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=Qs(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 eN(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 gN(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 hN(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 yN(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 vN(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 bN(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 kN(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 wN(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 SN(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 xN(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 RN(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=sN.readFileSync(n,"utf-8")}catch{}e.tail&&e.tail>0&&o&&(o=o.split(`
|
|
654
|
+
`)}),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(_<ra){let R=J0*2**_;this.slog("warn",e.memberId,"crash",`crashed again (code=${w}), restart ${_+1}/${ra}`),this.callbacks.onNotification?.(e.memberId,"agents.error",{agentId:e.memberId,phase:"runtime",error:`Process crashed (code=${w}), restarting`,retriesLeft:ra-_-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 X0}from"node:child_process";var Q0=/[|&;><$`(){}]/;function kee(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=Q0.test(i);if(!(s&&r)&&!(i.startsWith("brew ")&&!n))return{command:i,shell:s}}return null}function wee(t,e){if(e!=="cn")return t;let r=t.trim();return/^npm\b/.test(r)&&!/(?:^|\s)--registry(?:\s|=)/.test(r)?`${r} --registry ${kR}`:/^uv\b/.test(r)&&!/(?:^|\s)--(?:default-)?index(?:-url)?(?:\s|=)/.test(r)?`${r} --default-index ${ta}`:/^(?:pipx|pip3?|python -m pip)\b/.test(r)&&!/(?:^|\s)--index-url(?:\s|=)/.test(r)?`${r} --index-url ${ta}`:r}function Y0(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 See=(t,e)=>{if(e)return X0(t,{shell:!0,stdio:["ignore","pipe","pipe"]});let r=t.split(/\s+/).filter(Boolean);return X0(r[0],r.slice(1),{stdio:["ignore","pipe","pipe"]})};async function eN(t,e,r={}){let n=r.platform??process.platform,o=r.spawnImpl??See,i=kee(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=wee(i.command,r.mirror);e({type:"state",state:"installing"});let a=await Y0(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 Y0(c,Q0.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 It=new Map,xee=10*6e4,Ree=6e4,Tee=6,qp=null;function Wp(t,e,r){return`${t}\0${e}\0${r??"default"}`}function nl(t){try{t.manager.kill(t.memberId)}catch{}try{t.manager.dispose()}catch{}}function tN(t){let e=It.get(t);if(e){if(!e.manager.isAlive(e.memberId)){It.delete(t),nl(e);return}return e}}function rN(t,e){let r=It.get(t);r&&r!==e&&(It.delete(t),nl(r)),It.set(t,e),Pee(),Iee()}function nN(t,e){let r=It.get(t);if(!r)return;if(!r.manager.isAlive(r.memberId)){It.delete(t),nl(r);return}It.delete(t);let n=It.get(e);return n&&n!==r&&(It.delete(e),nl(n)),It.set(e,r),r.lastUsed=Date.now(),r}var Kp="__warm__";function Gp(t){let e=It.get(t);e&&(It.delete(t),nl(e))}function Pee(){for(;It.size>Tee;){let t=null,e=Number.POSITIVE_INFINITY;for(let[r,n]of It)n.holder.current||n.lastUsed<e&&(e=n.lastUsed,t=r);if(!t)break;Gp(t)}}function Aee(t){for(let[e,r]of[...It.entries()])r.holder.current||t-r.lastUsed>xee&&Gp(e)}function Iee(){qp||(qp=setInterval(()=>Aee(Date.now()),Ree),typeof qp.unref=="function"&&qp.unref())}import{randomUUID as Cee}from"node:crypto";var na=new Map;function _ee(t,e){let r=na.get(t);return r&&(clearTimeout(r.timer),r.resolve(null),na.delete(t)),new Promise(n=>{let o=setTimeout(()=>{na.delete(t),n(null)},e);typeof o.unref=="function"&&o.unref(),na.set(t,{resolve:n,timer:o})})}function oN(t,e){let r=na.get(t);return r?(clearTimeout(r.timer),na.delete(t),r.resolve(e),!0):!1}function Eee(t){if(t==null)return"";if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return""}}async function iN(t,e){let r=e.turnContext(),n=t.toolCall&&typeof t.toolCall=="object"?t.toolCall:{},o=typeof t.permissionId=="string"&&t.permissionId?t.permissionId:Cee(),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:Eee(n.rawInput),message:typeof t.message=="string"?t.message:void 0,category:typeof t.category=="string"?t.category:"destructive",options:i});let a=await _ee(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 $ee(t){let e=t?.rawInput;if(e!=null){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return}}}function Dee(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 aN(t){let e=t?.authMethods;return Array.isArray(e)&&e.length>0?e:void 0}function cN(t){return t instanceof Error?t.message:String(t)}async function Nee(t){let e=aN(t.error);if(!t.sessionId||!e)return;let r=cN(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 fs(t.sessionId,t.projectRoot);await at(t.sessionId,{type:"personal",...t.projectId?{projectId:t.projectId}:{},...o!==null?{messageCount:o}:{},...n?.title?{}:{title:nc(t.prompt,"External agent login required")},...n?.agentId?{}:{agentId:t.agentId}},t.projectRoot)}async function lN(t){let e=t.params,r=typeof e?.approvalId=="string"?e.approvalId:"",n=typeof e?.optionId=="string"?e.optionId:"",o=r&&n?oN(r,n):!1;t.id!==void 0&&this.sendResponse(t.id,{ok:o})}async function dN(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 uN(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 pN(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=hR().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:W0(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 mN(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=hR().map(i=>({id:i.id,entry:i,detectedVersion:r.get(i.id)?.version})),o=await K0(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 fN(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=Qs(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 eN(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 gN(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 hN(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 yN(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 vN(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 bN(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 kN(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 wN(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 SN(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 xN(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 RN(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=sN.readFileSync(n,"utf-8")}catch{}e.tail&&e.tail>0&&o&&(o=o.split(`
|
|
655
655
|
`).slice(-e.tail).join(`
|
|
656
|
-
`)),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 TN(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 PN(t,e,r,n,o,i){let s=Wp(e,n,o),a=tN(s);if(a)return a;if(o!==Kp){let f=nN(Wp(e,n,Kp),s);if(f)return f}let c=`chat-${e}-${Mee().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Mr({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:$ee(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:Dee(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)=>iN(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 rN(s,m),m}async function AN(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 PN(this,r,o,i,Kp),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 IN(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=Wp(r,s,c),f=await PN(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 Nee({sessionId:c,projectRoot:s,turnId:l,projectId:p,agentId:r,prompt:n,error:k}),Gp(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);at(c,{type:"personal",...p?{projectId:p}:{},...k?.title?{}:{title:nc(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=aN(e);this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:cN(e),...r?{data:{authMethods:r}}:{}})}}}ie();import*as ia from"node:fs/promises";import*as UO from"node:path";hs();var Oee=/^[a-z0-9][a-z0-9_.:-]{0,79}$/i,jee=new Set(["journeyDay","count"]),Lee=new Set(["blocked"]),Uee=new Set(["R0","R1","R2","R3"]),Fee=new Set(["aix","android","darwin","freebsd","ios","linux","openbsd","sunos","win32"]),Hee={"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=Hee[t],n={};for(let[o,i]of Object.entries(e)){if(!r.has(o))continue;let s=zee(o,i);s!==void 0&&(n[o]=s)}return Object.keys(n).length>0?n:void 0}function zee(t,e){if(jee.has(t))return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=1e5?e:void 0;if(Lee.has(t))return typeof e=="boolean"?e:void 0;if(t==="riskTier")return typeof e=="string"&&Uee.has(e)?e:void 0;if(t==="platform")return typeof e=="string"&&Fee.has(e)?e:void 0;if(typeof e!="string")return;let r=e.trim();return Oee.test(r)?r:void 0}var Bee=new Set(["withdrawn","version-available","deprecated","version-yanked","frozen"]);function qee(t){let e=Xee(t.baseUrl),r=Yee(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=ete(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(tte).filter(l=>!!l).slice(0,s)},async publishSkill(o){return RR(r,t.baseUrl,n,"skill",o)},async publishPet(o){return RR(r,t.baseUrl,n,"pet",o)},async publishWorkflow(o){return RR(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(EN).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=EN(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=DN(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(Gee).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 CN(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 CN(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(Wee).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(Kee).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=Vee(c);if(!l)throw new Error("Community hub returned an invalid runtime resolution.");return l}}}async function RR(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=rte(await Qee(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 CN(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 Wee(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 Kee(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 Gee(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 Vee(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=Zee(t);return qee({baseUrl:Jee(t),token:e,clientVersion:r})}function Zee(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.14.8"}function Jee(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Xee(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 Yee(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 Jr(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 Qee(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 Jr(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 ete(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 tte(t){if(!Pe(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=MN(t.sourceTier),r=$N(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:TR(t.title,80),summary:TR(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=>TR(s,32)),sourceTier:e,trustStage:r,resourceRiskTier:n,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function TR(t,e){let r=t.replace(/\s+/g," ").trim();return r.length<=e?r:`${r.slice(0,Math.max(0,e-1))}\u2026`}function rte(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 EN(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:Bee.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 nte=new Set(["R0","R1","R2","R3"]),ote=new Set(["official","community"]),ite=new Set(["quarantine","trial","trusted"]),ste=new Set(["pending","approved","rejected"]);function Xp(t){return typeof t=="string"&&nte.has(t)?t:null}function MN(t){return typeof t=="string"&&ote.has(t)?t:null}function $N(t){return typeof t=="string"&&ite.has(t)?t:null}function ate(t){return typeof t=="string"&&ste.has(t)?t:null}function DN(t){if(!Pe(t))return null;let e=MN(t.sourceTier),r=$N(t.trustStage),n=ate(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(DN);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 cte=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|[A-Za-z]:\\|\/Users\/|\/home\/|secret|token|password|\+?\d[\d\s().-]{7,}\d)/i,lte=/\b(?:agent|tool|shell|execute|permission|memory|system prompt|developer message)\b/i;function dte(t){return ute(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 NN(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=dte(e);return t.publishPet({id:e.id,title:e.name,summary:e.summary,visibility:e.visibility??"public",tags:e.tags??[],manifest:n.manifest})}function ute(t){let e=[t.id,t.name,t.summary,t.persona,...t.traits??[],...t.tags??[]].join(`
|
|
656
|
+
`)),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 TN(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 PN(t,e,r,n,o,i){let s=Wp(e,n,o),a=tN(s);if(a)return a;if(o!==Kp){let f=nN(Wp(e,n,Kp),s);if(f)return f}let c=`chat-${e}-${Mee().slice(0,8)}`,l={current:null},d=typeof t.sendNotification=="function"?t.sendNotification.bind(t):void 0,p=new Mr({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:$ee(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:Dee(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)=>iN(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 rN(s,m),m}async function AN(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 PN(this,r,o,i,Kp),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 IN(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=Wp(r,s,c),f=await PN(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 Nee({sessionId:c,projectRoot:s,turnId:l,projectId:p,agentId:r,prompt:n,error:k}),Gp(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);at(c,{type:"personal",...p?{projectId:p}:{},...k?.title?{}:{title:nc(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=aN(e);this.sendResponse(t.id,void 0,{code:b.INTERNAL_ERROR,message:cN(e),...r?{data:{authMethods:r}}:{}})}}}ie();import*as ia from"node:fs/promises";import*as UO from"node:path";hs();var Oee=/^[a-z0-9][a-z0-9_.:-]{0,79}$/i,jee=new Set(["journeyDay","count"]),Lee=new Set(["blocked"]),Uee=new Set(["R0","R1","R2","R3"]),Fee=new Set(["aix","android","darwin","freebsd","ios","linux","openbsd","sunos","win32"]),Hee={"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=Hee[t],n={};for(let[o,i]of Object.entries(e)){if(!r.has(o))continue;let s=zee(o,i);s!==void 0&&(n[o]=s)}return Object.keys(n).length>0?n:void 0}function zee(t,e){if(jee.has(t))return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=1e5?e:void 0;if(Lee.has(t))return typeof e=="boolean"?e:void 0;if(t==="riskTier")return typeof e=="string"&&Uee.has(e)?e:void 0;if(t==="platform")return typeof e=="string"&&Fee.has(e)?e:void 0;if(typeof e!="string")return;let r=e.trim();return Oee.test(r)?r:void 0}var Bee=new Set(["withdrawn","version-available","deprecated","version-yanked","frozen"]);function qee(t){let e=Xee(t.baseUrl),r=Yee(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=ete(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(tte).filter(l=>!!l).slice(0,s)},async publishSkill(o){return RR(r,t.baseUrl,n,"skill",o)},async publishPet(o){return RR(r,t.baseUrl,n,"pet",o)},async publishWorkflow(o){return RR(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(EN).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=EN(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=DN(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(Gee).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 CN(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 CN(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(Wee).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(Kee).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=Vee(c);if(!l)throw new Error("Community hub returned an invalid runtime resolution.");return l}}}async function RR(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=rte(await Qee(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 CN(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 Wee(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 Kee(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 Gee(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 Vee(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=Zee(t);return qee({baseUrl:Jee(t),token:e,clientVersion:r})}function Zee(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.14.9"}function Jee(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Xee(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 Yee(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 Jr(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 Qee(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 Jr(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 ete(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 tte(t){if(!Pe(t)||t.canonical!==!0&&t.isCanonical!==!0)return null;let e=MN(t.sourceTier),r=$N(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:TR(t.title,80),summary:TR(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=>TR(s,32)),sourceTier:e,trustStage:r,resourceRiskTier:n,effectiveRiskTier:o,latestVersion:typeof t.latestVersion=="string"?t.latestVersion:null,canonical:!0}}function TR(t,e){let r=t.replace(/\s+/g," ").trim();return r.length<=e?r:`${r.slice(0,Math.max(0,e-1))}\u2026`}function rte(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 EN(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:Bee.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 nte=new Set(["R0","R1","R2","R3"]),ote=new Set(["official","community"]),ite=new Set(["quarantine","trial","trusted"]),ste=new Set(["pending","approved","rejected"]);function Xp(t){return typeof t=="string"&&nte.has(t)?t:null}function MN(t){return typeof t=="string"&&ote.has(t)?t:null}function $N(t){return typeof t=="string"&&ite.has(t)?t:null}function ate(t){return typeof t=="string"&&ste.has(t)?t:null}function DN(t){if(!Pe(t))return null;let e=MN(t.sourceTier),r=$N(t.trustStage),n=ate(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(DN);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 cte=/(?:[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|[A-Za-z]:\\|\/Users\/|\/home\/|secret|token|password|\+?\d[\d\s().-]{7,}\d)/i,lte=/\b(?:agent|tool|shell|execute|permission|memory|system prompt|developer message)\b/i;function dte(t){return ute(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 NN(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=dte(e);return t.publishPet({id:e.id,title:e.name,summary:e.summary,visibility:e.visibility??"public",tags:e.tags??[],manifest:n.manifest})}function ute(t){let e=[t.id,t.name,t.summary,t.persona,...t.traits??[],...t.tags??[]].join(`
|
|
657
657
|
`);if(cte.test(e))throw new Error("Pet asset publish blocked: private email, path, secret, token, or phone-like text detected.");if(lte.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 PR={enabled:!0},pte=new Set(["R2","R3"]);function ON(t,e=PR){return pte.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 jN=new Set(["installed","success","fail","error","kept","uninstalled","endorse"]),mte=new Set(["acquire","ask","answer","encounter","review"]),fte=new Set(["unlock","flaunt"]),gte=new Set([...jN,...mte,...fte,"search"]),hte=["x","y","z","lat","lng","lon","coord","coords","coordinate","coordinates","position","positionHint","pos"];function Yp(t){return jN.has(t)}function yte(t){return typeof t=="string"&>e.has(t)}function vte(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(hte.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 LN(t){if(!t.id||typeof t.id!="string")throw new Error("ActivityEvent.id \u5FC5\u586B(\u5E42\u7B49\u952E)");if(!yte(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=vte(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 bte}from"node:crypto";var kte="pk_",wte=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=bte("sha256").update(r+"\0"+n).digest("hex");return`${kte}${o.slice(0,wte)}`}hs();function AR(t){return{async emit(e){if(!t.transport)return"disabled";let r=LN(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 IR(t){return{async emit(e){if(!t.emitActivity)throw new Error("emitActivity unavailable on client");await t.emitActivity(e)}}}function CR(){let t=dt(),e=t?.emitActivity?IR(t):null;return AR({transport:e,consent:t})}function _R(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 FO}from"node:crypto";import{createPublicKey as Ste,verify as xte}from"node:crypto";function Rte(t){return`id=${t.id}
|
|
658
658
|
version=${t.version}
|
|
659
659
|
checksum=${t.checksum}
|