qlogicagent 2.20.4 → 2.20.5

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
@@ -225,7 +225,7 @@ ${t.slice(-n)}`}function Fc(t){return t.replaceAll("&","&amp;").replaceAll("<","
225
225
  ${t.slice(-r)}`}function bw(t){let e=bn(t),n=e.events.at(-1);return[n?Bc(n):"",e.cleanOutput].filter(Boolean).join(`
226
226
  `)}var qc=class{constructor(e,n){this.store=e;this.getCurrentSessionId=n}store;getCurrentSessionId;controllers=new Map;bashHandles=new Map;externalControls=new Map;deadlineTimers=new Map;lastProgressAt=new Map;idleReclaimMs=new Map;settledListeners=new Set;onTaskSettled(e){return this.settledListeners.add(e),()=>this.settledListeners.delete(e)}fireSettled(e){let n=this.store.getTask(e);if(n)for(let r of this.settledListeners)try{r(n)}catch{}}startAgentTask(e){let n={taskId:Vr("local_agent"),type:"local_agent",label:e.label,permissionRole:"worker",isolation:"shared",lifecycle:"running",depth:e.depth,maxTurns:e.maxTurns,tokenBudget:0,startedAt:Date.now(),parentTaskId:e.parentTaskId,launchSessionId:e.launchSessionId??this.getCurrentSessionId?.(),launchTurnId:e.launchTurnId,agentName:e.agentName,systemPrompt:"",allowedTools:[]};this.store.registerTask(n);let r=new AbortController;return this.controllers.set(n.taskId,r),this.armIdleReclaim(n.taskId,e.idleMs??pB),e.run(r.signal,n.taskId).then(o=>{this.settle(n.taskId,{lifecycle:o.ok?"completed":"failed",output:o.output?fm(o.output,uB):void 0,error:o.error})}).catch(o=>{this.settle(n.taskId,{lifecycle:"failed",error:o instanceof Error?o.message:String(o)})}).finally(()=>{this.controllers.delete(n.taskId)}),n}registerBashTask(e){let n={taskId:e.handle.taskOutput.taskId,type:"local_bash",label:e.label??e.command.slice(0,80),permissionRole:"worker",isolation:"shared",lifecycle:"running",depth:0,maxTurns:1,tokenBudget:0,startedAt:Date.now(),launchSessionId:e.launchSessionId??this.getCurrentSessionId?.(),launchTurnId:e.launchTurnId,command:e.command,cwd:e.cwd,pid:e.pid,outputPath:e.handle.taskOutput.path};return this.store.registerTask(n),this.bashHandles.set(n.taskId,e.handle),e.handle.result.then(r=>{let o=this.store.getTask(n.taskId);if(!o||pt(o.lifecycle))return;let i=[r.stdout,r.stderr?`[stderr]
227
227
  ${r.stderr}`:""].filter(Boolean).join(`
228
- `);this.store.updateTask(n.taskId,s=>({...s,lifecycle:r.code===0?"completed":"failed",exitCode:r.code,output:fm(bn(i).cleanOutput),error:r.code===0?void 0:`exit code ${r.code}`,endedAt:Date.now()})),this.fireSettled(n.taskId)}).catch(r=>{this.settle(n.taskId,{lifecycle:"failed",error:r instanceof Error?r.message:String(r)})}).finally(()=>{this.bashHandles.delete(n.taskId)}),n}registerExternalTask(e,n){this.store.registerTask(e),this.externalControls.set(e.taskId,n)}settleExternalTask(e,n,r){this.externalControls.delete(e);let o=this.store.getTask(e);!o||pt(o.lifecycle)||(this.store.updateTask(e,i=>({...i,lifecycle:n,...r!=null?{output:r}:{},endedAt:Date.now()})),this.fireSettled(e))}settle(e,n){this.clearDeadline(e);let r=this.store.getTask(e);!r||pt(r.lifecycle)||(this.store.updateTask(e,o=>({...o,...n,endedAt:Date.now()})),this.fireSettled(e))}getTask(e){return this.store.getTask(e)}listTasks(){return this.store.getAllTasks()}async readOutput(e){let n=this.store.getTask(e);if(!n)return null;let r=!pt(n.lifecycle);if(r&&n.type==="local_bash"&&n.outputPath){let o="";try{o=(await Hc(n.outputPath,kw)).output}catch{o=""}return{task:n,output:fm(bw(qn(o))),running:r}}if(r){let o=this.externalControls.get(e);if(o?.readStatus)return{task:n,output:bw(o.readStatus()),running:r}}return{task:n,output:n.output??"",running:r}}teardownExecutors(e){let n=this.bashHandles.get(e);if(n){try{n.kill()}catch{}this.bashHandles.delete(e)}let r=this.controllers.get(e);r&&(r.abort("cancelled"),this.controllers.delete(e));let o=this.externalControls.get(e);if(o){try{o.cancel()}catch{}this.externalControls.delete(e)}}armIdleReclaim(e,n){!Number.isFinite(n)||n<=0||(this.idleReclaimMs.set(e,n),this.lastProgressAt.set(e,Date.now()),this.scheduleIdleCheck(e))}markProgress(e){this.lastProgressAt.has(e)&&this.lastProgressAt.set(e,Date.now())}scheduleIdleCheck(e){let n=this.idleReclaimMs.get(e);if(n===void 0)return;let r=this.lastProgressAt.get(e)??Date.now(),o=Math.max(0,n-(Date.now()-r)),i=setTimeout(()=>this.onIdleCheck(e),o||n);i.unref?.(),this.deadlineTimers.set(e,i)}onIdleCheck(e){let n=this.idleReclaimMs.get(e);if(n===void 0)return;Date.now()-(this.lastProgressAt.get(e)??0)>=n?this.enforceIdleTimeout(e,n):this.scheduleIdleCheck(e)}clearDeadline(e){let n=this.deadlineTimers.get(e);n&&(clearTimeout(n),this.deadlineTimers.delete(e)),this.lastProgressAt.delete(e),this.idleReclaimMs.delete(e)}enforceIdleTimeout(e,n){this.clearDeadline(e);let r=this.store.getTask(e);!r||pt(r.lifecycle)||(this.teardownExecutors(e),this.store.updateTask(e,o=>({...o,lifecycle:"timeout",error:o.error??`background task reclaimed after ${Math.round(n/1e3)}s with no progress (no output or tool activity)`,endedAt:Date.now()})),this.fireSettled(e))}cancelTask(e){let n=this.store.getTask(e);return!n||pt(n.lifecycle)?!1:(this.clearDeadline(e),this.teardownExecutors(e),this.store.updateTask(e,r=>({...r,lifecycle:"cancelled",endedAt:Date.now()})),!0)}cancelTasksForSession(e,n){if(!e)return[];let r=[];for(let o of this.store.getAllTasks())o.launchSessionId===e&&(!n||o.launchTurnId===n)&&!pt(o.lifecycle)&&this.cancelTask(o.taskId)&&r.push(o.taskId);return r}cancelAllRunning(){let e=[];for(let n of this.store.getAllTasks())pt(n.lifecycle)||this.cancelTask(n.taskId)&&e.push(n.taskId);return e}};function Wc(){return Rt()?.type==="group"}var hm=new Set;function Wn(t){return hm.add(t),()=>{hm.delete(t)}}async function vw(){await Promise.all(Array.from(hm).map(t=>t()))}import{randomUUID as Ow}from"node:crypto";import{createHash as ooe}from"node:crypto";import{randomUUID as soe}from"node:crypto";import*as Ko from"node:fs";import*as zc from"node:path";function Gc(t){return zc.join(Mt(t),"feedback","events")}function Sw(t,e){return zc.join(Gc(t),`${encodeURIComponent(e)}.json`)}async function ym(t,e){try{return JSON.parse(await Ko.promises.readFile(Sw(t,e),"utf8"))}catch{return null}}async function bm(t){t.projectId&&(await Ko.promises.mkdir(Gc(t.projectId),{recursive:!0}),await Ko.promises.writeFile(Sw(t.projectId,t.turnId),JSON.stringify(t,null,2),"utf8"))}async function ww(t){let e;try{e=(await Ko.promises.readdir(Gc(t),{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".json")).map(r=>r.name)}catch{return[]}let n=[];for(let r of e)try{n.push(JSON.parse(await Ko.promises.readFile(zc.join(Gc(t),r),"utf8")))}catch{continue}return n}async function Tw(t){return(await ww(t)).filter(e=>e.upload?.eligible!==!1&&!e.upload?.uploadBatchId)}async function Rw(t,e,n){let r=await ym(t,e);r&&(r.upload={eligible:r.upload?.eligible??!0,uploadBatchId:n},await bm(r))}async function km(t,e,n,r){let o=await ym(t,e);o&&(o.upload={eligible:o.upload?.eligible??!0,uploadBatchId:n,uploadedAt:new Date().toISOString(),redactionVersion:r},await bm(o))}async function Pw(t){return(await ww(t)).filter(e=>e.state==="active")}async function xw(t,e,n){let r=await ym(t,e);r&&(r.distill={proposedAt:new Date().toISOString(),clusterKey:n.clusterKey,idempotencyKey:n.idempotencyKey},await bm(r))}import{createHash as gB}from"node:crypto";var Gn="feedback-redaction-v1",mB=500;function vm(t){return gB("sha256").update(t,"utf8").digest("hex")}var fB=[[/sk-[A-Za-z0-9_-]{8,}/g,"[redacted-key]"],[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,"[redacted-email]"],[/(?:[A-Za-z]:\\|\/)(?:Users|home|root|var|opt|etc|tmp)[\\/][^\s'"`)]+/gi,"[redacted-path]"]];function hB(t){let e=(t??"").slice(0,mB);for(let[n,r]of fB)e=e.replace(n,r);return e}function Cw(t,e=Gn){return{feedbackId:t.feedbackId,rating:t.rating,reason:t.reason,state:t.state,messageHash:t.messageHash,sessionIdHash:vm(t.sessionId),projectIdHash:t.projectId?vm(t.projectId):void 0,turnIdHash:vm(t.turnId),messagePreview:hB(t.messagePreview),model:t.model,provider:t.provider,agentMode:t.agentMode,sourceChannel:t.sourceChannel,usage:t.usage,toolSummary:t.toolSummary,fileContext:t.fileContext?{changedFileCount:t.fileContext.changedFileCount,hasTurnFileChanges:t.fileContext.hasTurnFileChanges,diffOpenState:t.fileContext.diffOpenState}:void 0,browserContext:t.browserContext?{hadToastError:t.browserContext.hadToastError,visiblePanel:t.browserContext.visiblePanel}:void 0,telemetryStatus:t.telemetryStatus,redactionVersion:e,createdAt:t.createdAt}}function Aw(t,e){let n={rollupId:e.rollupId,periodStart:e.periodStart,periodEnd:e.periodEnd,total:0,upCount:0,downCount:0,byReason:{},byModel:{},byAgentMode:{},telemetryStatusCounts:{complete:0,partial:0,missing:0},redactionVersion:e.redactionVersion??Gn,createdAt:new Date().toISOString()};for(let r of t){n.total+=1,r.rating==="up"?n.upCount+=1:n.downCount+=1,r.rating==="down"&&r.reason&&(n.byReason[r.reason]=(n.byReason[r.reason]??0)+1);let o=r.model??"unknown",i=n.byModel[o]??={up:0,down:0};i[r.rating]+=1;let s=r.agentMode??"unknown",a=n.byAgentMode[s]??={up:0,down:0};a[r.rating]+=1,n.telemetryStatusCounts[r.telemetryStatus]+=1}return n}import{randomUUID as yB}from"node:crypto";import*as Kc from"node:fs";import*as Vc from"node:path";var bB=6,kB=6e4,vB=30*6e4;function Iw(t){return Vc.join(Mt(t),"feedback","outbox.json")}async function Yc(t){try{let e=JSON.parse(await Kc.promises.readFile(Iw(t),"utf8"));return Array.isArray(e)?e:[]}catch{return[]}}async function Sm(t,e){let n=Iw(t);await Kc.promises.mkdir(Vc.dirname(n),{recursive:!0}),await Kc.promises.writeFile(n,JSON.stringify(e,null,2),"utf8")}function SB(t){return Math.min(kB*2**Math.max(0,t-1),vB)}async function Ew(t,e,n=new Date){let r=await Yc(t),o=r.find(a=>a.idempotencyKey===e.idempotencyKey);if(o)return o;let i=n.toISOString(),s={entryId:yB(),idempotencyKey:e.idempotencyKey,op:e.op,payload:e.payload,attempts:0,createdAt:i,nextAttemptAt:i};return r.push(s),await Sm(t,r),s}async function _w(t,e=new Date){return(await Yc(t)).filter(r=>r.attempts<bB&&Date.parse(r.nextAttemptAt)<=e.getTime())}async function Mw(t,e){let n=await Yc(t),r=n.filter(o=>o.entryId!==e);r.length!==n.length&&await Sm(t,r)}async function Dw(t,e,n,r=new Date){let o=await Yc(t),i=o.find(s=>s.entryId===e);i&&(i.attempts+=1,i.lastError=n,i.nextAttemptAt=new Date(r.getTime()+SB(i.attempts)).toISOString(),await Sm(t,o))}async function Xc(t,e={}){let n=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim();if(!n)throw new Error("QLOGIC_LLMROUTER_BASE_URL not configured");let r=e.fetchFn??fetch,o=e.signal??e.init?.signal??void 0,i=Object.fromEntries(new Headers(e.init?.headers).entries()),s=process.env.QLOGIC_LLMROUTER_ACCESS_TOKEN?.trim();return s&&(i.authorization=`Bearer ${s}`),{response:await r(`${n.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`,{...e.init,headers:i,signal:o}),refreshedToken:!1}}function wB(){return"2.20.4"}function TB(){let t=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim();if(t)return`${t.replace(/\/+$/,"")}/client/feedback`}async function wm(t,e){if(!TB())return{ok:!1,error:"QLOGIC_LLMROUTER_BASE_URL not configured"};if(t.events.length===0)return{ok:!0,accepted:0};let r=e??AbortSignal.timeout(3e4);try{let{response:o,refreshedToken:i}=await Xc("/client/feedback/uploadBatch",{signal:r,init:RB(t)});if(!o.ok){let a=await o.text().catch(()=>"");return{ok:!1,status:o.status,error:`HTTP ${o.status}${a?`: ${a.slice(0,200)}`:""}`}}return{ok:!0,accepted:(await o.json().catch(()=>({}))).accepted??t.events.length,status:o.status,refreshedToken:i}}catch(o){return{ok:!1,error:o instanceof Error?o.message:String(o)}}}function RB(t){return{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({batchId:t.batchId,events:t.events,rollups:t.rollups,redactionVersion:t.redactionVersion,clientBuild:t.clientBuild,runtimeVersion:t.runtimeVersion,qlogicagentVersion:t.qlogicagentVersion??wB(),uploadTarget:"llmrouter"})}}function PB(t){let e=t.map(r=>r.createdAt).sort(),n=new Date().toISOString();return{periodStart:e[0]??n,periodEnd:e[e.length-1]??n}}async function xB(t,e){let n=0;for(let r of await _w(t,e)){let o=r.payload,i=await wm({batchId:o.batchId,events:o.events,rollups:o.rollups??[],redactionVersion:o.redactionVersion??Gn});if(i.ok){for(let s of o.turnIds??[])await km(t,s,o.batchId,o.redactionVersion??Gn);await Mw(t,r.entryId),n+=1}else await Dw(t,r.entryId,i.error??"upload failed",e)}return n}async function Nw(t,e=new Date){let n=await xB(t,e),r=await Tw(t);if(r.length===0)return{uploaded:0,queued:0,retried:n};let o=Ow(),i=r.map(p=>Cw(p)),s=r.map(p=>p.turnId),{periodStart:a,periodEnd:c}=PB(r),l=Aw(r,{rollupId:Ow(),periodStart:a,periodEnd:c});if((await wm({batchId:o,events:i,rollups:[l],redactionVersion:Gn})).ok){for(let p of s)await km(t,p,o,Gn);return{uploaded:r.length,queued:0,retried:n}}for(let p of s)await Rw(t,p,o);return await Ew(t,{idempotencyKey:o,op:"uploadBatch",payload:{batchId:o,events:i,rollups:[l],turnIds:s,redactionVersion:Gn}},e),{uploaded:0,queued:r.length,retried:n}}import{createHash as CB}from"node:crypto";var AB=2;function IB(t){return t.rating==="down"?`dislike:${t.reason??"other"}`:"like"}var EB={"dislike:missed_requirement":"\u7528\u6237\u91CD\u89C6\u56DE\u7B54\u5B8C\u6574\u8986\u76D6\u5176\u9700\u6C42,\u4E0D\u8981\u9057\u6F0F\u660E\u786E\u63D0\u51FA\u7684\u8981\u6C42\u3002","dislike:incomplete":"\u7528\u6237\u91CD\u89C6\u4EA4\u4ED8\u7684\u5B8C\u6574\u6027,\u4E0D\u8981\u534A\u9014\u800C\u5E9F\u6216\u7559\u4E0B\u672A\u5B8C\u6210\u7684\u90E8\u5206\u3002","dislike:broken_file_link_or_panel":"\u7528\u6237\u91CD\u89C6\u6587\u4EF6\u94FE\u63A5\u3001\u53F3\u4FA7\u9762\u677F\u7B49\u4EA7\u7269\u771F\u5B9E\u53EF\u70B9\u51FB\u3001\u53EF\u6253\u5F00,\u4EA4\u4ED8\u524D\u5E94\u81EA\u884C\u9A8C\u8BC1\u3002","dislike:code_or_test_failed":"\u7528\u6237\u91CD\u89C6\u4EE3\u7801\u4E0E\u6D4B\u8BD5\u771F\u5B9E\u901A\u8FC7,\u4EA4\u4ED8\u524D\u5E94\u5B9E\u9645\u8FD0\u884C\u9A8C\u8BC1,\u800C\u975E\u4EC5\u58F0\u79F0\u5B8C\u6210\u3002","dislike:factually_wrong":"\u7528\u6237\u91CD\u89C6\u4E8B\u5B9E\u51C6\u786E\u6027,\u4E0D\u786E\u5B9A\u65F6\u5E94\u6838\u5B9E\u6765\u6E90\u800C\u975E\u81C6\u6D4B\u3002","dislike:too_verbose":"\u7528\u6237\u504F\u597D\u7B80\u6D01\u7684\u56DE\u7B54:\u76F4\u63A5\u7ED9\u7ED3\u8BBA\u548C\u5173\u952E\u8981\u70B9,\u907F\u514D\u5197\u957F\u94FA\u9648\u3002","dislike:too_short":"\u7528\u6237\u504F\u597D\u66F4\u5B8C\u6574\u3001\u6709\u4F9D\u636E\u7684\u56DE\u7B54,\u4E0D\u8981\u8FC7\u4E8E\u7B80\u7565\u3002","dislike:wrong_style":"\u7528\u6237\u5BF9\u56DE\u7B54\u98CE\u683C\u6709\u660E\u786E\u504F\u597D,\u5E94\u8D34\u5408\u5176\u671F\u671B\u7684\u8868\u8FBE\u98CE\u683C\u3002","dislike:other":"\u7528\u6237\u5BF9\u8FD9\u7C7B\u56DE\u7B54\u8868\u8FBE\u8FC7\u4E0D\u6EE1,\u9700\u7ED3\u5408\u4E0A\u4E0B\u6587\u6CE8\u610F\u6539\u8FDB\u3002",like:"\u7528\u6237\u8BA4\u53EF\u8FD9\u7C7B\u56DE\u7B54\u7684\u65B9\u5F0F\u4E0E\u8D28\u91CF,\u53EF\u7EE7\u7EED\u4FDD\u6301\u3002"};function _B(t){return EB[t]??"\u7528\u6237\u5BF9\u8FD9\u7C7B\u56DE\u7B54\u6709\u660E\u786E\u504F\u597D,\u5E94\u636E\u5176\u53CD\u9988\u8C03\u6574\u3002"}function MB(t,e){let n=.45+.12*Math.min(t,4)+(e?.08:0);return Math.max(.3,Math.min(.85,Number(n.toFixed(4))))}function DB(t){return Math.max(.3,Math.min(.9,Number((.4+.1*t).toFixed(4))))}function OB(t,e){return CB("sha256").update(`${t}
228
+ `);this.store.updateTask(n.taskId,s=>({...s,lifecycle:r.code===0?"completed":"failed",exitCode:r.code,output:fm(bn(i).cleanOutput),error:r.code===0?void 0:`exit code ${r.code}`,endedAt:Date.now()})),this.fireSettled(n.taskId)}).catch(r=>{this.settle(n.taskId,{lifecycle:"failed",error:r instanceof Error?r.message:String(r)})}).finally(()=>{this.bashHandles.delete(n.taskId)}),n}registerExternalTask(e,n){this.store.registerTask(e),this.externalControls.set(e.taskId,n)}settleExternalTask(e,n,r){this.externalControls.delete(e);let o=this.store.getTask(e);!o||pt(o.lifecycle)||(this.store.updateTask(e,i=>({...i,lifecycle:n,...r!=null?{output:r}:{},endedAt:Date.now()})),this.fireSettled(e))}settle(e,n){this.clearDeadline(e);let r=this.store.getTask(e);!r||pt(r.lifecycle)||(this.store.updateTask(e,o=>({...o,...n,endedAt:Date.now()})),this.fireSettled(e))}getTask(e){return this.store.getTask(e)}listTasks(){return this.store.getAllTasks()}async readOutput(e){let n=this.store.getTask(e);if(!n)return null;let r=!pt(n.lifecycle);if(r&&n.type==="local_bash"&&n.outputPath){let o="";try{o=(await Hc(n.outputPath,kw)).output}catch{o=""}return{task:n,output:fm(bw(qn(o))),running:r}}if(r){let o=this.externalControls.get(e);if(o?.readStatus)return{task:n,output:bw(o.readStatus()),running:r}}return{task:n,output:n.output??"",running:r}}teardownExecutors(e){let n=this.bashHandles.get(e);if(n){try{n.kill()}catch{}this.bashHandles.delete(e)}let r=this.controllers.get(e);r&&(r.abort("cancelled"),this.controllers.delete(e));let o=this.externalControls.get(e);if(o){try{o.cancel()}catch{}this.externalControls.delete(e)}}armIdleReclaim(e,n){!Number.isFinite(n)||n<=0||(this.idleReclaimMs.set(e,n),this.lastProgressAt.set(e,Date.now()),this.scheduleIdleCheck(e))}markProgress(e){this.lastProgressAt.has(e)&&this.lastProgressAt.set(e,Date.now())}scheduleIdleCheck(e){let n=this.idleReclaimMs.get(e);if(n===void 0)return;let r=this.lastProgressAt.get(e)??Date.now(),o=Math.max(0,n-(Date.now()-r)),i=setTimeout(()=>this.onIdleCheck(e),o||n);i.unref?.(),this.deadlineTimers.set(e,i)}onIdleCheck(e){let n=this.idleReclaimMs.get(e);if(n===void 0)return;Date.now()-(this.lastProgressAt.get(e)??0)>=n?this.enforceIdleTimeout(e,n):this.scheduleIdleCheck(e)}clearDeadline(e){let n=this.deadlineTimers.get(e);n&&(clearTimeout(n),this.deadlineTimers.delete(e)),this.lastProgressAt.delete(e),this.idleReclaimMs.delete(e)}enforceIdleTimeout(e,n){this.clearDeadline(e);let r=this.store.getTask(e);!r||pt(r.lifecycle)||(this.teardownExecutors(e),this.store.updateTask(e,o=>({...o,lifecycle:"timeout",error:o.error??`background task reclaimed after ${Math.round(n/1e3)}s with no progress (no output or tool activity)`,endedAt:Date.now()})),this.fireSettled(e))}cancelTask(e){let n=this.store.getTask(e);return!n||pt(n.lifecycle)?!1:(this.clearDeadline(e),this.teardownExecutors(e),this.store.updateTask(e,r=>({...r,lifecycle:"cancelled",endedAt:Date.now()})),!0)}cancelTasksForSession(e,n){if(!e)return[];let r=[];for(let o of this.store.getAllTasks())o.launchSessionId===e&&(!n||o.launchTurnId===n)&&!pt(o.lifecycle)&&this.cancelTask(o.taskId)&&r.push(o.taskId);return r}cancelAllRunning(){let e=[];for(let n of this.store.getAllTasks())pt(n.lifecycle)||this.cancelTask(n.taskId)&&e.push(n.taskId);return e}};function Wc(){return Rt()?.type==="group"}var hm=new Set;function Wn(t){return hm.add(t),()=>{hm.delete(t)}}async function vw(){await Promise.all(Array.from(hm).map(t=>t()))}import{randomUUID as Ow}from"node:crypto";import{createHash as ooe}from"node:crypto";import{randomUUID as soe}from"node:crypto";import*as Ko from"node:fs";import*as zc from"node:path";function Gc(t){return zc.join(Mt(t),"feedback","events")}function Sw(t,e){return zc.join(Gc(t),`${encodeURIComponent(e)}.json`)}async function ym(t,e){try{return JSON.parse(await Ko.promises.readFile(Sw(t,e),"utf8"))}catch{return null}}async function bm(t){t.projectId&&(await Ko.promises.mkdir(Gc(t.projectId),{recursive:!0}),await Ko.promises.writeFile(Sw(t.projectId,t.turnId),JSON.stringify(t,null,2),"utf8"))}async function ww(t){let e;try{e=(await Ko.promises.readdir(Gc(t),{withFileTypes:!0})).filter(r=>r.isFile()&&r.name.endsWith(".json")).map(r=>r.name)}catch{return[]}let n=[];for(let r of e)try{n.push(JSON.parse(await Ko.promises.readFile(zc.join(Gc(t),r),"utf8")))}catch{continue}return n}async function Tw(t){return(await ww(t)).filter(e=>e.upload?.eligible!==!1&&!e.upload?.uploadBatchId)}async function Rw(t,e,n){let r=await ym(t,e);r&&(r.upload={eligible:r.upload?.eligible??!0,uploadBatchId:n},await bm(r))}async function km(t,e,n,r){let o=await ym(t,e);o&&(o.upload={eligible:o.upload?.eligible??!0,uploadBatchId:n,uploadedAt:new Date().toISOString(),redactionVersion:r},await bm(o))}async function Pw(t){return(await ww(t)).filter(e=>e.state==="active")}async function xw(t,e,n){let r=await ym(t,e);r&&(r.distill={proposedAt:new Date().toISOString(),clusterKey:n.clusterKey,idempotencyKey:n.idempotencyKey},await bm(r))}import{createHash as gB}from"node:crypto";var Gn="feedback-redaction-v1",mB=500;function vm(t){return gB("sha256").update(t,"utf8").digest("hex")}var fB=[[/sk-[A-Za-z0-9_-]{8,}/g,"[redacted-key]"],[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,"[redacted-email]"],[/(?:[A-Za-z]:\\|\/)(?:Users|home|root|var|opt|etc|tmp)[\\/][^\s'"`)]+/gi,"[redacted-path]"]];function hB(t){let e=(t??"").slice(0,mB);for(let[n,r]of fB)e=e.replace(n,r);return e}function Cw(t,e=Gn){return{feedbackId:t.feedbackId,rating:t.rating,reason:t.reason,state:t.state,messageHash:t.messageHash,sessionIdHash:vm(t.sessionId),projectIdHash:t.projectId?vm(t.projectId):void 0,turnIdHash:vm(t.turnId),messagePreview:hB(t.messagePreview),model:t.model,provider:t.provider,agentMode:t.agentMode,sourceChannel:t.sourceChannel,usage:t.usage,toolSummary:t.toolSummary,fileContext:t.fileContext?{changedFileCount:t.fileContext.changedFileCount,hasTurnFileChanges:t.fileContext.hasTurnFileChanges,diffOpenState:t.fileContext.diffOpenState}:void 0,browserContext:t.browserContext?{hadToastError:t.browserContext.hadToastError,visiblePanel:t.browserContext.visiblePanel}:void 0,telemetryStatus:t.telemetryStatus,redactionVersion:e,createdAt:t.createdAt}}function Aw(t,e){let n={rollupId:e.rollupId,periodStart:e.periodStart,periodEnd:e.periodEnd,total:0,upCount:0,downCount:0,byReason:{},byModel:{},byAgentMode:{},telemetryStatusCounts:{complete:0,partial:0,missing:0},redactionVersion:e.redactionVersion??Gn,createdAt:new Date().toISOString()};for(let r of t){n.total+=1,r.rating==="up"?n.upCount+=1:n.downCount+=1,r.rating==="down"&&r.reason&&(n.byReason[r.reason]=(n.byReason[r.reason]??0)+1);let o=r.model??"unknown",i=n.byModel[o]??={up:0,down:0};i[r.rating]+=1;let s=r.agentMode??"unknown",a=n.byAgentMode[s]??={up:0,down:0};a[r.rating]+=1,n.telemetryStatusCounts[r.telemetryStatus]+=1}return n}import{randomUUID as yB}from"node:crypto";import*as Kc from"node:fs";import*as Vc from"node:path";var bB=6,kB=6e4,vB=30*6e4;function Iw(t){return Vc.join(Mt(t),"feedback","outbox.json")}async function Yc(t){try{let e=JSON.parse(await Kc.promises.readFile(Iw(t),"utf8"));return Array.isArray(e)?e:[]}catch{return[]}}async function Sm(t,e){let n=Iw(t);await Kc.promises.mkdir(Vc.dirname(n),{recursive:!0}),await Kc.promises.writeFile(n,JSON.stringify(e,null,2),"utf8")}function SB(t){return Math.min(kB*2**Math.max(0,t-1),vB)}async function Ew(t,e,n=new Date){let r=await Yc(t),o=r.find(a=>a.idempotencyKey===e.idempotencyKey);if(o)return o;let i=n.toISOString(),s={entryId:yB(),idempotencyKey:e.idempotencyKey,op:e.op,payload:e.payload,attempts:0,createdAt:i,nextAttemptAt:i};return r.push(s),await Sm(t,r),s}async function _w(t,e=new Date){return(await Yc(t)).filter(r=>r.attempts<bB&&Date.parse(r.nextAttemptAt)<=e.getTime())}async function Mw(t,e){let n=await Yc(t),r=n.filter(o=>o.entryId!==e);r.length!==n.length&&await Sm(t,r)}async function Dw(t,e,n,r=new Date){let o=await Yc(t),i=o.find(s=>s.entryId===e);i&&(i.attempts+=1,i.lastError=n,i.nextAttemptAt=new Date(r.getTime()+SB(i.attempts)).toISOString(),await Sm(t,o))}async function Xc(t,e={}){let n=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim();if(!n)throw new Error("QLOGIC_LLMROUTER_BASE_URL not configured");let r=e.fetchFn??fetch,o=e.signal??e.init?.signal??void 0,i=Object.fromEntries(new Headers(e.init?.headers).entries()),s=process.env.QLOGIC_LLMROUTER_ACCESS_TOKEN?.trim();return s&&(i.authorization=`Bearer ${s}`),r(`${n.replace(/\/+$/,"")}/${t.replace(/^\/+/,"")}`,{...e.init,headers:i,signal:o})}function wB(){return"2.20.5"}function TB(){let t=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim();if(t)return`${t.replace(/\/+$/,"")}/client/feedback`}async function wm(t,e){if(!TB())return{ok:!1,error:"QLOGIC_LLMROUTER_BASE_URL not configured"};if(t.events.length===0)return{ok:!0,accepted:0};let r=e??AbortSignal.timeout(3e4);try{let o=await Xc("/client/feedback/uploadBatch",{signal:r,init:RB(t)});if(!o.ok){let s=await o.text().catch(()=>"");return{ok:!1,status:o.status,error:`HTTP ${o.status}${s?`: ${s.slice(0,200)}`:""}`}}return{ok:!0,accepted:(await o.json().catch(()=>({}))).accepted??t.events.length,status:o.status}}catch(o){return{ok:!1,error:o instanceof Error?o.message:String(o)}}}function RB(t){return{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify({batchId:t.batchId,events:t.events,rollups:t.rollups,redactionVersion:t.redactionVersion,clientBuild:t.clientBuild,runtimeVersion:t.runtimeVersion,qlogicagentVersion:t.qlogicagentVersion??wB(),uploadTarget:"llmrouter"})}}function PB(t){let e=t.map(r=>r.createdAt).sort(),n=new Date().toISOString();return{periodStart:e[0]??n,periodEnd:e[e.length-1]??n}}async function xB(t,e){let n=0;for(let r of await _w(t,e)){let o=r.payload,i=await wm({batchId:o.batchId,events:o.events,rollups:o.rollups??[],redactionVersion:o.redactionVersion??Gn});if(i.ok){for(let s of o.turnIds??[])await km(t,s,o.batchId,o.redactionVersion??Gn);await Mw(t,r.entryId),n+=1}else await Dw(t,r.entryId,i.error??"upload failed",e)}return n}async function Nw(t,e=new Date){let n=await xB(t,e),r=await Tw(t);if(r.length===0)return{uploaded:0,queued:0,retried:n};let o=Ow(),i=r.map(p=>Cw(p)),s=r.map(p=>p.turnId),{periodStart:a,periodEnd:c}=PB(r),l=Aw(r,{rollupId:Ow(),periodStart:a,periodEnd:c});if((await wm({batchId:o,events:i,rollups:[l],redactionVersion:Gn})).ok){for(let p of s)await km(t,p,o,Gn);return{uploaded:r.length,queued:0,retried:n}}for(let p of s)await Rw(t,p,o);return await Ew(t,{idempotencyKey:o,op:"uploadBatch",payload:{batchId:o,events:i,rollups:[l],turnIds:s,redactionVersion:Gn}},e),{uploaded:0,queued:r.length,retried:n}}import{createHash as CB}from"node:crypto";var AB=2;function IB(t){return t.rating==="down"?`dislike:${t.reason??"other"}`:"like"}var EB={"dislike:missed_requirement":"\u7528\u6237\u91CD\u89C6\u56DE\u7B54\u5B8C\u6574\u8986\u76D6\u5176\u9700\u6C42,\u4E0D\u8981\u9057\u6F0F\u660E\u786E\u63D0\u51FA\u7684\u8981\u6C42\u3002","dislike:incomplete":"\u7528\u6237\u91CD\u89C6\u4EA4\u4ED8\u7684\u5B8C\u6574\u6027,\u4E0D\u8981\u534A\u9014\u800C\u5E9F\u6216\u7559\u4E0B\u672A\u5B8C\u6210\u7684\u90E8\u5206\u3002","dislike:broken_file_link_or_panel":"\u7528\u6237\u91CD\u89C6\u6587\u4EF6\u94FE\u63A5\u3001\u53F3\u4FA7\u9762\u677F\u7B49\u4EA7\u7269\u771F\u5B9E\u53EF\u70B9\u51FB\u3001\u53EF\u6253\u5F00,\u4EA4\u4ED8\u524D\u5E94\u81EA\u884C\u9A8C\u8BC1\u3002","dislike:code_or_test_failed":"\u7528\u6237\u91CD\u89C6\u4EE3\u7801\u4E0E\u6D4B\u8BD5\u771F\u5B9E\u901A\u8FC7,\u4EA4\u4ED8\u524D\u5E94\u5B9E\u9645\u8FD0\u884C\u9A8C\u8BC1,\u800C\u975E\u4EC5\u58F0\u79F0\u5B8C\u6210\u3002","dislike:factually_wrong":"\u7528\u6237\u91CD\u89C6\u4E8B\u5B9E\u51C6\u786E\u6027,\u4E0D\u786E\u5B9A\u65F6\u5E94\u6838\u5B9E\u6765\u6E90\u800C\u975E\u81C6\u6D4B\u3002","dislike:too_verbose":"\u7528\u6237\u504F\u597D\u7B80\u6D01\u7684\u56DE\u7B54:\u76F4\u63A5\u7ED9\u7ED3\u8BBA\u548C\u5173\u952E\u8981\u70B9,\u907F\u514D\u5197\u957F\u94FA\u9648\u3002","dislike:too_short":"\u7528\u6237\u504F\u597D\u66F4\u5B8C\u6574\u3001\u6709\u4F9D\u636E\u7684\u56DE\u7B54,\u4E0D\u8981\u8FC7\u4E8E\u7B80\u7565\u3002","dislike:wrong_style":"\u7528\u6237\u5BF9\u56DE\u7B54\u98CE\u683C\u6709\u660E\u786E\u504F\u597D,\u5E94\u8D34\u5408\u5176\u671F\u671B\u7684\u8868\u8FBE\u98CE\u683C\u3002","dislike:other":"\u7528\u6237\u5BF9\u8FD9\u7C7B\u56DE\u7B54\u8868\u8FBE\u8FC7\u4E0D\u6EE1,\u9700\u7ED3\u5408\u4E0A\u4E0B\u6587\u6CE8\u610F\u6539\u8FDB\u3002",like:"\u7528\u6237\u8BA4\u53EF\u8FD9\u7C7B\u56DE\u7B54\u7684\u65B9\u5F0F\u4E0E\u8D28\u91CF,\u53EF\u7EE7\u7EED\u4FDD\u6301\u3002"};function _B(t){return EB[t]??"\u7528\u6237\u5BF9\u8FD9\u7C7B\u56DE\u7B54\u6709\u660E\u786E\u504F\u597D,\u5E94\u636E\u5176\u53CD\u9988\u8C03\u6574\u3002"}function MB(t,e){let n=.45+.12*Math.min(t,4)+(e?.08:0);return Math.max(.3,Math.min(.85,Number(n.toFixed(4))))}function DB(t){return Math.max(.3,Math.min(.9,Number((.4+.1*t).toFixed(4))))}function OB(t,e){return CB("sha256").update(`${t}
229
229
  ${e.join(",")}`).digest("hex").slice(0,32)}function Lw(t){let e=new Map;for(let r of t){if(r.state!=="active")continue;let o=IB(r),i=e.get(o);i?i.push(r):e.set(o,[r])}let n=[];for(let[r,o]of e){if(o.length<AB)continue;let i=o.map(c=>c.feedbackId).sort(),s=[...new Set(o.map(c=>c.turnId))].sort(),a=new Set(o.map(c=>c.sessionId)).size>=2;n.push({clusterKey:r,text:_B(r),category:"preference",importance:DB(o.length),confidence:MB(o.length,a),evidence:{kind:"feedback",refs:[...i,...s.map(c=>`turn:${c}`)],idempotencyKey:OB(r,i)},stats:{evidence:o.length,crossSession:a,feedbackIds:i,turnIds:s}})}return n.sort((r,o)=>r.clusterKey.localeCompare(o.clusterKey)),n}var $w=()=>{};function jw(t){$w=t}function ps(){return $w()}async function Fw(t,e,n){if(!e.proposeExtracted)return{candidates:0,proposed:0};let r=ps(),o=r?await r.listDistillableFeedback(t):await Pw(t);if(o.length===0)return{candidates:0,proposed:0};let i=Lw(o),s=0;for(let a of i)try{let c=await e.proposeExtracted([{text:a.text,category:a.category,importance:a.importance,confidence:a.confidence,evidence:a.evidence}],n,{source:"feedback"});s+=c?.proposalsAdded??0;for(let l of a.stats.turnIds){let d={clusterKey:a.clusterKey,idempotencyKey:a.evidence.idempotencyKey};r?await r.markFeedbackDistilled(t,l,d):await xw(t,l,d)}}catch(c){console.error(`[feedback:distill] candidate skipped (cluster ${a.clusterKey}): ${c instanceof Error?c.message:String(c)}`)}return{candidates:i.length,proposed:s}}import*as Pt from"node:fs";import{MODEL_PURPOSES as vT}from"@xiaozhiclaw/module-sdk/model-access";function Uw(t){return t.baseUrl??t.base_url}function Hw(t){return{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"}[t.id]??t.displayName??t.name??t.id}function Gw(t,e){return t.kind===e.kind&&t.owner===e.owner&&t.name===e.name&&t.seq===e.seq}var Dt={request:"x/delegate",update:"x/delegate.update",respond:"x/delegate.respond",cancel:"x/delegate.cancel"},LB=["search","addText","embedText","ingestExtracted","proposeExtracted","consumePendingProposals","feedback","findRelatedEvents","synthesizeTimeline","getActivitySummary","getAllProfiles","setProfile","getAtlas","setMemoryArchived","triggerDecay","resolveConflicts","readProcedureUsage","writeProcedureUsage","readDistillCandidates","writeDistillCandidates","readPromotionProposals","writePromotionProposals","listActiveMemoriesByTag","readDistilledProcedure","promoteDistilledProcedure","demoteDistilledProcedure","recordInjectedAccess","recordRecallOutcome","enqueueExtractionTurn","claimPendingExtractionTurns","completeExtractionTurn","releaseExtractionTurn","recordExtractionTurnFailure"],$B=["initialize","getIndex","addToIndex","replaceInIndex","removeFromIndex","createFile","writeFile","readFile","deleteFile","listFiles","searchLocal"],jB=["getSkillSnapshot","readSkillFile","recordSkillInvocation","commitSkillMutation","applyCuratorPlan","prepareSkillInstall","finalizeSkillInstall"],FB=["loadForResume","appendTranscript","updateTitle","saveState","saveTaskSummary","groupSplit"],UB=["commitTurnTelemetry","listDistillableFeedback","markFeedbackDistilled","runUploadSweep"],HB=["getSnapshot","create","switch","update"],$oe=1024*1024,BB=["resolveInstall","listResourceVersions","resolveRuntime"],qB=["probeSession"],WB=["list","get","diagnose"],Qc=["navigate","snapshot","click","type","screenshot","console","network"];var GB=["open","openWithCheckpoint","recordEvent","checkpoint","get","list","delete","getCheckpoint","listCheckpoints","restoreCheckpoint"],zB=["getTunables","updateTunable","clearTunable","appendDirectoryAllowRule"],Pm={request:"x/host.request"},Tm=new Set(["memory","projectMemory","profile","preview","capability","session","feedback","project","runState","provider","community","cloudAuth"]),KB=new Set(LB),VB=new Set($B),YB=new Set(zB),XB=new Set(jB),JB=new Set(FB),QB=new Set(UB),ZB=new Set(HB),eq=new Set(GB),tq=new Set(WB),nq=new Set(BB),rq=new Set(qB),oq=new Set(Qc);function z(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gs(t){return Array.isArray(t)&&t.every(e=>typeof e=="string")}function zw(t,e){return e.every(n=>t[n]===void 0||typeof t[n]=="string")}function iq(t){return z(t)?typeof t.name=="string"&&t.name.length>0&&(t.state==="active"||t.state==="stale"||t.state==="archived")&&typeof t.createdAt=="string"&&typeof t.pinned=="boolean"&&typeof t.useCount=="number"&&Number.isFinite(t.useCount)&&(t.source==="learned"||t.source==="created"||t.source==="installed"||t.source==="promoted")&&zw(t,["lastUsedAt","lastViewedAt","lastPatchedAt","staleAt","archivedAt","resourceType","artifactDigest","registryResourceId","registryVersion","registryKeptSignalAt"])&&["launcherRequired","manualReviewRequired"].every(e=>t[e]===void 0||typeof t[e]=="boolean")&&["positiveCount","negativeCount"].every(e=>t[e]===void 0||typeof t[e]=="number"&&Number.isFinite(t[e]))&&["sourceTier","registrySourceTier"].every(e=>t[e]===void 0||t[e]==="official"||t[e]==="community")&&["riskTier","registryRiskTier","registryEffectiveRiskTier"].every(e=>t[e]===void 0||t[e]==="R0"||t[e]==="R1"||t[e]==="R2"||t[e]==="R3"):!1}function sq(t){return z(t)?O(t,["name","filePath","baseDir","fileRevision","globallyDisabled","projectDisabled","active","systemGenerated","description","version","category","author","requiredTools","environments","source","registryVersion"])&&typeof t.name=="string"&&t.name.length>0&&typeof t.filePath=="string"&&t.filePath.length>0&&typeof t.baseDir=="string"&&t.baseDir.length>0&&typeof t.fileRevision=="string"&&t.fileRevision.length>0&&typeof t.globallyDisabled=="boolean"&&typeof t.projectDisabled=="boolean"&&typeof t.active=="boolean"&&typeof t.systemGenerated=="boolean"&&zw(t,["description","version","category","author","registryVersion"])&&(t.source===void 0||t.source==="learned"||t.source==="created"||t.source==="installed"||t.source==="promoted")&&(t.requiredTools===void 0||gs(t.requiredTools))&&(t.environments===void 0||gs(t.environments)):!1}function aq(t){return z(t)&&O(t,["name","skills","filePath"])&&typeof t.name=="string"&&t.name.length>0&&gs(t.skills)&&typeof t.filePath=="string"&&t.filePath.length>0}function Kw(t){return!z(t)||typeof t.revision!="string"||t.revision.length===0?!1:t.notModified===!0?O(t,["revision","notModified"]):t.notModified!==!1||!O(t,["revision","notModified","skills","lifecycle","bundles"])?!1:Array.isArray(t.skills)&&t.skills.every(sq)&&Array.isArray(t.lifecycle)&&t.lifecycle.every(iq)&&Array.isArray(t.bundles)&&t.bundles.every(aq)}function Vw(t){return z(t)&&O(t,["name","relativePath","content","baseDir","revision"])&&typeof t.name=="string"&&t.name.length>0&&typeof t.relativePath=="string"&&t.relativePath.length>0&&typeof t.content=="string"&&typeof t.baseDir=="string"&&t.baseDir.length>0&&typeof t.revision=="string"&&t.revision.length>0}function Yw(t){return z(t)&&O(t,["name","lastUsedAt","useCount","positiveCount","negativeCount"])&&zn(t.name)&&typeof t.lastUsedAt=="string"&&t.lastUsedAt.length>0&&["useCount","positiveCount","negativeCount"].every(e=>typeof t[e]=="number"&&Number.isFinite(t[e])&&t[e]>=0)}function Xw(t){return!z(t)||!zn(t.name)||typeof t.kind!="string"?!1:t.kind==="create"||t.kind==="editContent"||t.kind==="editSupportingFile"?O(t,["kind","name","revision","changed"])&&typeof t.revision=="string"&&t.revision.length>0&&t.changed===!0:t.kind==="delete"?O(t,["kind","name","deleted"])&&t.deleted===!0:t.kind==="setGlobalDisabled"||t.kind==="setProjectDisabled"?O(t,["kind","name","disabled","changed"])&&typeof t.disabled=="boolean"&&typeof t.changed=="boolean":t.kind==="setPinned"?O(t,["kind","name","pinned","changed"])&&typeof t.pinned=="boolean"&&typeof t.changed=="boolean":t.kind==="promote"?O(t,["kind","name","promoted","changed"])&&t.promoted===!0&&typeof t.changed=="boolean":!1}function cq(t,e){return t==="active"&&e==="stale"||t==="stale"&&(e==="archived"||e==="active")||t==="archived"&&e==="active"}function Jw(t){return z(t)&&O(t,["name","from","to"])&&zn(t.name)&&cq(t.from,t.to)}function Qw(t){return z(t)&&O(t,["revision","changed","transitioned"])&&typeof t.revision=="string"&&t.revision.length>0&&typeof t.changed=="boolean"&&Array.isArray(t.transitioned)&&t.transitioned.every(Jw)}function Zw(t){return z(t)&&O(t,["installationId","artifactPath","contentDir","expiresAt"])&&["installationId","artifactPath","contentDir","expiresAt"].every(e=>typeof t[e]=="string"&&t[e].length>0)}function eT(t){return z(t)?t.action==="discard"?O(t,["action","discarded"])&&t.discarded===!0:t.action==="adopt"&&O(t,["action","resourceId","version","skillName","installDir","checksum","replaced"])&&zn(t.resourceId)&&t.skillName===t.resourceId&&typeof t.version=="string"&&t.version.length>0&&typeof t.installDir=="string"&&t.installDir.length>0&&typeof t.checksum=="string"&&/^[a-f0-9]{64}$/.test(t.checksum)&&typeof t.replaced=="boolean":!1}function O(t,e){let n=new Set(e);return Object.keys(t).every(r=>n.has(r))}function Vo(t,e){return t[e]===void 0||typeof t[e]=="string"}function Ze(t,e){return t[e]===void 0||typeof t[e]=="string"&&t[e].trim().length>0}function zn(t){return typeof t=="string"&&/^[A-Za-z0-9_.-]+$/.test(t)&&t!=="."&&t!==".."}function tT(t){return typeof t!="string"||t.trim()!==t||t.length===0||t.includes("\0")||/^(?:[A-Za-z]:[\\/]|[\\/])/.test(t)?!1:t.split(/[\\/]/).every(n=>n.length>0&&n!=="."&&n!=="..")}function Bw(t){return tT(t)&&t.toLowerCase()!=="skill.md"}function lq(t,e){if(!z(e))return!1;if(t==="getSkillSnapshot")return O(e,["projectId","knownRevision"])&&Ze(e,"projectId")&&Ze(e,"knownRevision");if(t==="readSkillFile")return O(e,["name","relativePath","expectedRevision"])&&zn(e.name)&&(e.relativePath===void 0||tT(e.relativePath))&&Ze(e,"expectedRevision");if(t==="commitSkillMutation"){if(!O(e,["mutation"])||!z(e.mutation))return!1;let n=e.mutation;return!zn(n.name)||typeof n.kind!="string"?!1:n.kind==="create"?!O(n,["kind","name","content","source","supportingFile"])||typeof n.content!="string"||n.source!==void 0&&n.source!=="created"&&n.source!=="learned"?!1:n.supportingFile===void 0?!0:z(n.supportingFile)&&O(n.supportingFile,["relativePath","content"])&&Bw(n.supportingFile.relativePath)&&typeof n.supportingFile.content=="string":n.kind==="editContent"?O(n,["kind","name","expectedRevision","content"])&&typeof n.expectedRevision=="string"&&n.expectedRevision.length>0&&typeof n.content=="string":n.kind==="editSupportingFile"?O(n,["kind","name","relativePath","expectedRevision","content"])&&Bw(n.relativePath)&&(n.expectedRevision===null||typeof n.expectedRevision=="string"&&n.expectedRevision.length>0)&&typeof n.content=="string":n.kind==="delete"?O(n,["kind","name"]):n.kind==="setGlobalDisabled"?O(n,["kind","name","disabled"])&&typeof n.disabled=="boolean":n.kind==="setProjectDisabled"?O(n,["kind","name","projectId","disabled"])&&typeof n.projectId=="string"&&n.projectId.length>0&&typeof n.disabled=="boolean":n.kind==="setPinned"?O(n,["kind","name","pinned"])&&typeof n.pinned=="boolean":n.kind==="promote"?O(n,["kind","name"]):!1}if(t==="applyCuratorPlan"){if(!O(e,["expectedRevision","transitions"])||typeof e.expectedRevision!="string"||e.expectedRevision.length===0||!Array.isArray(e.transitions)||e.transitions.length>500||!e.transitions.every(Jw))return!1;let n=e.transitions.map(r=>r.name);return new Set(n).size===n.length}if(t==="prepareSkillInstall"){if(!O(e,["name","version","checksum","sizeBytes","allowReplace","provenance"])||!zn(e.name)||typeof e.version!="string"||!e.version.trim()||typeof e.checksum!="string"||!/^[a-f0-9]{64}$/.test(e.checksum)||!Number.isSafeInteger(e.sizeBytes)||e.sizeBytes<=0||e.sizeBytes>20*1024*1024||typeof e.allowReplace!="boolean"||!z(e.provenance)||!O(e.provenance,["sourceTier","resourceRiskTier","effectiveRiskTier"]))return!1;let n=r=>r==="R0"||r==="R1"||r==="R2"||r==="R3";return(e.provenance.sourceTier==="official"||e.provenance.sourceTier==="community")&&n(e.provenance.resourceRiskTier)&&n(e.provenance.effectiveRiskTier)}return t==="finalizeSkillInstall"?O(e,["installationId","action"])&&typeof e.installationId=="string"&&e.installationId.trim().length>0&&(e.action==="adopt"||e.action==="discard"):O(e,["name","success"])&&zn(e.name)&&typeof e.success=="boolean"}function G(t){return typeof t=="string"&&t.trim()===t&&t.length>0&&t.length<=512&&!t.includes("\0")}function Ie(t){return Number.isSafeInteger(t)&&t>=0}function nT(t){return t==="installed"||t==="auth_required"||t==="ready"||t==="disabled"||t==="incompatible"||t==="unresponsive"||t==="failed"||t==="not_installed"}function dq(t){return nT(t)&&t!=="not_installed"}function xm(t){return!z(t)||!O(t,["providerId","state","stage","code","message","retryable","providerVersion","payloadVersion"])?!1:G(t.providerId)&&nT(t.state)&&["install","manifest","auth","launch","initialize","models","native_sessions","request"].includes(String(t.stage))&&G(t.code)&&typeof t.message=="string"&&typeof t.retryable=="boolean"&&Ze(t,"providerVersion")&&Ze(t,"payloadVersion")}function qw(t,e){return z(t)&&O(t,e)&&e.every(n=>typeof t[n]=="boolean")}function uq(t){return z(t)?t.kind==="provider"?O(t,["kind","enumeration"])&&(t.enumeration==="protocol"||t.enumeration==="implicit-default"):t.kind==="host"&&O(t,["kind","managedPurposes"])&&gs(t.managedPurposes):!1}function rT(t){if(!z(t)||!O(t,["providerId","displayName","version","state","capabilities","diagnostic"])||!G(t.providerId)||!G(t.displayName)||!G(t.version)||!dq(t.state)||t.diagnostic!==void 0&&!xm(t.diagnostic)||!z(t.capabilities)||!O(t.capabilities,["execution","auth","models","nativeSessions","diagnostics"]))return!1;let e=t.capabilities;return!qw(e.execution,["streaming","approvals","cancellation","resume"])||!z(e.auth)||!O(e.auth,["modes","terminal","logout"])||!Array.isArray(e.auth.modes)||!e.auth.modes.every(n=>n==="account"||n==="userKey"||n==="managed")||typeof e.auth.terminal!="boolean"||typeof e.auth.logout!="boolean"||!uq(e.models)||!qw(e.nativeSessions,["discover","transcript","resume"])?!1:z(e.diagnostics)&&O(e.diagnostics,["readiness","version","structuredErrors"])&&e.diagnostics.readiness===!0&&e.diagnostics.version===!0&&e.diagnostics.structuredErrors===!0}function oT(t){return z(t)&&O(t,["revision","providers"])&&Ie(t.revision)&&Array.isArray(t.providers)&&t.providers.every(rT)}function iT(t){return z(t)&&O(t,["revision","provider"])&&Ie(t.revision)&&(t.provider===null||rT(t.provider))}function Jc(t,e=0){return e>12?!1:t===null||typeof t=="string"||typeof t=="boolean"?!0:typeof t=="number"?Number.isFinite(t):Array.isArray(t)?t.length<=1e4&&t.every(n=>Jc(n,e+1)):!z(t)||Object.keys(t).length>1e3?!1:Object.values(t).every(n=>Jc(n,e+1))}function pq(t){return t===void 0||gs(t)}function sT(t){return z(t)&&O(t,["inputTokens","outputTokens","totalTokens"])&&["inputTokens","outputTokens","totalTokens"].every(e=>t[e]===void 0||Ie(t[e]))}function aT(t){if(!z(t)||!O(t,["role","content","tool_calls","tool_call_id","name","is_error","reasoning_content","toolReferences","thinkingBlocks","imageUrls","imageDetail","imagePixelLimit","videoUrls","videoFps","audioFormat","audioUrls","fileIds","blocks","attachmentEntries","timestamp","turnId","usage","displayMetadata"])||t.role!=="system"&&t.role!=="user"&&t.role!=="assistant"&&t.role!=="tool"||t.content!==null&&typeof t.content!="string"||!["tool_call_id","name","reasoning_content","timestamp","turnId"].every(e=>Vo(t,e))||t.is_error!==void 0&&typeof t.is_error!="boolean"||!["toolReferences","imageUrls","videoUrls","audioUrls"].every(e=>pq(t[e]))||t.imageDetail!==void 0&&t.imageDetail!=="auto"&&t.imageDetail!=="low"&&t.imageDetail!=="high"&&t.imageDetail!=="xhigh"||t.audioFormat!==void 0&&t.audioFormat!=="mp3"&&t.audioFormat!=="wav"&&t.audioFormat!=="aac"&&t.audioFormat!=="m4a"||t.videoFps!==void 0&&(typeof t.videoFps!="number"||!Number.isFinite(t.videoFps)||t.videoFps<.2||t.videoFps>5)||t.tool_calls!==void 0&&(!Array.isArray(t.tool_calls)||!t.tool_calls.every(e=>z(e)&&O(e,["id","type","function"])&&G(e.id)&&e.type==="function"&&z(e.function)&&O(e.function,["name","arguments"])&&G(e.function.name)&&typeof e.function.arguments=="string"))||t.thinkingBlocks!==void 0&&(!Array.isArray(t.thinkingBlocks)||!t.thinkingBlocks.every(e=>z(e)&&O(e,["thinking","signature"])&&typeof e.thinking=="string"&&typeof e.signature=="string")))return!1;if(t.imagePixelLimit!==void 0){if(!z(t.imagePixelLimit))return!1;let e=t.imagePixelLimit;if(!O(e,["minPixels","maxPixels"])||!["minPixels","maxPixels"].every(n=>e[n]===void 0||Ie(e[n])))return!1}return t.fileIds!==void 0&&(!Array.isArray(t.fileIds)||!t.fileIds.every(e=>z(e)&&O(e,["id","mimeType","size"])&&G(e.id)&&Vo(e,"mimeType")&&(e.size===void 0||Ie(e.size))))||t.usage!==void 0&&!sT(t.usage)?!1:["blocks","attachmentEntries","displayMetadata"].every(e=>t[e]===void 0||Jc(t[e]))}function gq(t,e){if(!z(e))return!1;if(t==="loadForResume")return O(e,["sessionId","projectId","includeMessages"])&&G(e.sessionId)&&Ze(e,"projectId")&&(e.includeMessages===void 0||typeof e.includeMessages=="boolean");if(t==="appendTranscript")return O(e,["sessionId","turnId","messageId","sequence","message","usage","displayMetadata"])&&G(e.sessionId)&&G(e.turnId)&&G(e.messageId)&&Ie(e.sequence)&&aT(e.message)&&(e.usage===void 0||sT(e.usage))&&(e.displayMetadata===void 0||Jc(e.displayMetadata));if(t==="updateTitle")return O(e,["sessionId","operationId","title"])&&G(e.sessionId)&&G(e.operationId)&&typeof e.title=="string"&&e.title.length<=2e3;if(t==="saveState"){if(!O(e,["sessionId","turnId","operationId","model","usage"])||!G(e.sessionId)||!G(e.turnId)||!G(e.operationId)||!Vo(e,"model")||!z(e.usage))return!1;let n=e.usage;return O(n,["turnCount","totalInputTokens","totalOutputTokens"])&&["turnCount","totalInputTokens","totalOutputTokens"].every(r=>Ie(n[r]))}return t==="saveTaskSummary"?O(e,["sessionId","operationId","summary","generatedAtTurn"])&&G(e.sessionId)&&G(e.operationId)&&typeof e.summary=="string"&&e.summary.length<=2e5&&Ie(e.generatedAtTurn):O(e,["sessionId","operationId","reason","expectedLastActiveAt","expectedTurnCount"])&&G(e.sessionId)&&G(e.operationId)&&(e.reason==="idle"||e.reason==="turn-limit")&&Vo(e,"expectedLastActiveAt")&&(e.expectedTurnCount===void 0||Ie(e.expectedTurnCount))}function cT(t){if(!z(t)||!O(t,["session"]))return!1;if(t.session===null)return!0;if(!z(t.session)||!O(t.session,["metadata","messages","corruptLines"])||!z(t.session.metadata))return!1;let e=t.session.metadata;return O(e,["sessionId","projectId","createdAt","lastActiveAt","turnCount","messageCount","type","title","agentId","model","taskSummary","carryoverSummary","previousSessionId","pinnedAt","archivedAt","sealedAt"])&&["sessionId","projectId","createdAt","lastActiveAt"].every(n=>G(e[n]))&&["turnCount","messageCount"].every(n=>Ie(e[n]))&&(e.type===void 0||e.type==="personal"||e.type==="group")&&["title","agentId","model","taskSummary","carryoverSummary","previousSessionId","pinnedAt","archivedAt","sealedAt"].every(n=>Vo(e,n))&&Array.isArray(t.session.messages)&&t.session.messages.every(aT)&&(t.session.corruptLines===void 0||Ie(t.session.corruptLines))}function lT(t){return z(t)&&O(t,["status","messageCount"])&&(t.status==="appended"||t.status==="duplicate"||t.status==="session-deleted")&&Ie(t.messageCount)}function dT(t){return z(t)&&O(t,["status"])&&(t.status==="updated"||t.status==="duplicate"||t.status==="session-deleted")}function uT(t){return z(t)&&O(t,["status","nextSessionId"])&&(t.status==="updated"||t.status==="duplicate"||t.status==="session-deleted")&&(t.nextSessionId===void 0||G(t.nextSessionId))}function mq(t,e){if(!z(e)||!Vo(e,"viewId")||!Ze(e,"sessionId"))return!1;switch(t){case"navigate":return O(e,["url","viewId","sessionId"])&&typeof e.url=="string";case"click":return O(e,["ref","viewId","sessionId"])&&typeof e.ref=="string";case"type":return O(e,["ref","text","submit","viewId","sessionId"])&&typeof e.ref=="string"&&typeof e.text=="string"&&(e.submit===void 0||typeof e.submit=="boolean");case"snapshot":case"screenshot":case"console":case"network":return O(e,["viewId","sessionId"])}}function Rm(t,e){return t[e]===void 0||Ie(t[e])}function fq(t){if(!z(t)||!O(t,["schemaVersion","launched","completed","failed","cancelled","backgroundCount","automaticDeliveryCount","byAgentType","decisionCounts","argumentCorrections","durationMs","tokenUsage"])||t.schemaVersion!==1)return!1;for(let e of["launched","completed","failed","cancelled","backgroundCount","automaticDeliveryCount"])if(!Ie(t[e]))return!1;return!z(t.byAgentType)||!O(t.byAgentType,["general","explore","plan","code","research","verify"])||!Object.values(t.byAgentType).every(Ie)||!z(t.decisionCounts)||!O(t.decisionCounts,["adopted","partiallyAdopted","rejected","unreported"])||!Object.values(t.decisionCounts).every(Ie)||!z(t.argumentCorrections)||!O(t.argumentCorrections,["roleAlias","promptAlias","backgroundAlias","agentValue","backgroundValue"])||!Object.values(t.argumentCorrections).every(Ie)||!z(t.durationMs)||!O(t.durationMs,["total","max"])||!Ie(t.durationMs.total)||!Ie(t.durationMs.max)?!1:z(t.tokenUsage)&&O(t.tokenUsage,["total"])&&Ie(t.tokenUsage.total)}function hq(t){if(!z(t)||!O(t,["model","provider","agentMode","sourceChannel","usage","toolSummary","fileContext","delegationSummary"]))return!1;for(let e of["model","provider","sourceChannel"])if(t[e]!==void 0&&!G(t[e]))return!1;if(t.agentMode!==void 0&&!["chat","solo","product","workflow","unknown"].includes(String(t.agentMode))||t.usage!==void 0&&(!z(t.usage)||!O(t.usage,["inputTokens","outputTokens","totalTokens"])||!["inputTokens","outputTokens","totalTokens"].every(e=>Rm(t.usage,e))))return!1;if(t.toolSummary!==void 0){if(!z(t.toolSummary)||!O(t.toolSummary,["calledTools","failedTools","blockedTools"]))return!1;for(let e of["calledTools","failedTools","blockedTools"]){let n=t.toolSummary[e];if(!Array.isArray(n)||!n.every(G))return!1}}return!(t.fileContext!==void 0&&(!z(t.fileContext)||!O(t.fileContext,["changedFileCount","changedPathsPreview","hasTurnFileChanges"])||!Rm(t.fileContext,"changedFileCount")||t.fileContext.changedPathsPreview!==void 0&&(!Array.isArray(t.fileContext.changedPathsPreview)||!t.fileContext.changedPathsPreview.every(G))||t.fileContext.hasTurnFileChanges!==void 0&&typeof t.fileContext.hasTurnFileChanges!="boolean")||t.delegationSummary!==void 0&&!fq(t.delegationSummary))}function yq(t,e){return z(e)?t==="commitTurnTelemetry"?O(e,["projectId","sessionId","turnId","telemetry"])&&G(e.projectId)&&G(e.sessionId)&&G(e.turnId)&&hq(e.telemetry):t==="listDistillableFeedback"||t==="runUploadSweep"?O(e,["projectId"])&&G(e.projectId):O(e,["projectId","turnId","clusterKey","idempotencyKey"])&&G(e.projectId)&&G(e.turnId)&&G(e.clusterKey)&&G(e.idempotencyKey):!1}function bq(t,e){if(!z(e))return!1;if(t==="getSnapshot")return Object.keys(e).length===0;if(t==="switch")return O(e,["projectIdOrQuery"])&&G(e.projectIdOrQuery);if(t==="create"){let n=e.workspaceDir!==void 0||typeof e.name=="string"&&e.name!=="."&&e.name!==".."&&!/[\\/]/.test(e.name);return O(e,["name","workspaceDir","type","groupId"])&&G(e.name)&&n&&Ze(e,"workspaceDir")&&Ze(e,"groupId")&&(e.type===void 0||["personal","group","solo","product","automation"].includes(String(e.type)))}return!O(e,["projectId","planStatus","planAgents","planWinnerId","leaderSessionId","primaryWorkflowId"])||!G(e.projectId)||e.planStatus!==void 0&&!["creating","running","completed","failed","cancelled"].includes(String(e.planStatus))||e.planAgents!==void 0&&(!Array.isArray(e.planAgents)||!e.planAgents.every(G))?!1:["planWinnerId","leaderSessionId","primaryWorkflowId"].every(n=>Ze(e,n))}function kq(t,e){return!z(e)||!G(e.sessionId)?!1:t==="open"?O(e,["runId","kind","projectId","sessionId"])&&G(e.runId)&&G(e.projectId)&&(e.kind==="solo"||e.kind==="product"||e.kind==="goal"):t==="openWithCheckpoint"?O(e,["runId","kind","projectId","snapshot","checkpointId","sessionId"])&&G(e.runId)&&G(e.projectId)&&(e.kind==="solo"||e.kind==="product"||e.kind==="goal")&&Ze(e,"checkpointId")&&Object.prototype.hasOwnProperty.call(e,"snapshot")&&e.snapshot!==void 0:t==="recordEvent"?!O(e,["runId","event","sessionId"])||!G(e.runId)||!z(e.event)?!1:O(e.event,["at","type","sequence","payload"])&&G(e.event.at)&&G(e.event.type)&&Rm(e.event,"sequence"):t==="checkpoint"?O(e,["runId","checkpointId","snapshot","sessionId"])&&G(e.runId)&&Ze(e,"checkpointId")&&Object.prototype.hasOwnProperty.call(e,"snapshot")&&e.snapshot!==void 0:t==="list"?O(e,["projectId","kind","sessionId"])&&G(e.projectId)&&(e.kind===void 0||e.kind==="solo"||e.kind==="product"||e.kind==="goal"):t==="getCheckpoint"||t==="restoreCheckpoint"?O(e,["runId","checkpointId","sessionId"])&&G(e.runId)&&G(e.checkpointId):t==="listCheckpoints"?O(e,["runId","sessionId"])&&G(e.runId):(t==="get"||t==="delete")&&O(e,["runId","sessionId"])&&G(e.runId)}function Ww(t){return typeof t=="string"&&/^[a-z0-9][a-z0-9._-]*\.md$/i.test(t)&&t!=="INDEX.md"&&!t.includes("..")&&!t.includes("/")&&!t.includes("\\")}function vq(t,e){return!z(e)||typeof e.sessionId!="string"||e.sessionId.trim().length===0?!1:t==="initialize"||t==="getIndex"||t==="listFiles"?O(e,["sessionId"]):t==="addToIndex"?O(e,["sessionId","content"])&&typeof e.content=="string"&&e.content.length>0:t==="replaceInIndex"?O(e,["sessionId","oldText","newText"])&&typeof e.oldText=="string"&&e.oldText.length>0&&typeof e.newText=="string"&&e.newText.length>0:t==="removeFromIndex"?O(e,["sessionId","oldText"])&&typeof e.oldText=="string"&&e.oldText.length>0:t==="createFile"||t==="writeFile"?O(e,["sessionId","name","content"])&&Ww(e.name)&&typeof e.content=="string":t==="readFile"||t==="deleteFile"?O(e,["sessionId","name"])&&Ww(e.name):t==="searchLocal"&&O(e,["sessionId","query"])&&typeof e.query=="string"&&e.query.length>0}function pT(t){if(!z(t)||!O(t,["service","method","params","sessionId"])||typeof t.service!="string"||!Tm.has(t.service)||typeof t.method!="string"||t.method.length===0)return!1;if(t.service==="memory")return KB.has(t.method)&&Array.isArray(t.params)&&(t.sessionId===void 0||G(t.sessionId));if(t.sessionId!==void 0)return!1;if(t.service==="projectMemory")return VB.has(t.method)&&vq(t.method,t.params);if(t.service==="profile"){if(!YB.has(t.method)||!Array.isArray(t.params))return!1;switch(t.method){case"getTunables":return t.params.length===0;case"updateTunable":return t.params.length===2&&typeof t.params[0]=="string"&&t.params[0].trim().length>0&&t.params[1]!==void 0;case"clearTunable":case"appendDirectoryAllowRule":return t.params.length===1&&typeof t.params[0]=="string"&&t.params[0].trim().length>0}}return t.service==="capability"?XB.has(t.method)&&lq(t.method,t.params):t.service==="session"?JB.has(t.method)&&gq(t.method,t.params):t.service==="feedback"?QB.has(t.method)&&yq(t.method,t.params):t.service==="project"?ZB.has(t.method)&&bq(t.method,t.params):t.service==="runState"?eq.has(t.method)&&kq(t.method,t.params):t.service==="provider"?!tq.has(t.method)||!Array.isArray(t.params)?!1:t.method==="list"?t.params.length===0:t.params.length===1&&G(t.params[0]):t.service==="community"?!nq.has(t.method)||!z(t.params)?!1:t.method==="resolveInstall"?O(t.params,["resourceId","version"])&&G(t.params.resourceId)&&Ze(t.params,"version"):t.method==="listResourceVersions"?O(t.params,["resourceId"])&&G(t.params.resourceId):O(t.params,["id","platform"])&&G(t.params.id)&&G(t.params.platform):t.service==="cloudAuth"?rq.has(t.method)&&t.method==="probeSession"&&z(t.params)&&Object.keys(t.params).length===0:oq.has(t.method)?mq(t.method,t.params):!1}function gT(t){return z(t)&&O(t,["ok"])&&t.ok===!0}function mT(t){return!z(t)||!O(t,["events"])||!Array.isArray(t.events)?!1:t.events.every(e=>z(e)&&O(e,["feedbackId","rating","reason","state","sessionId","turnId"])&&G(e.feedbackId)&&(e.rating==="up"||e.rating==="down")&&(e.reason===void 0||["missed_requirement","incomplete","broken_file_link_or_panel","code_or_test_failed","factually_wrong","too_verbose","too_short","wrong_style","other"].includes(String(e.reason)))&&e.state==="active"&&G(e.sessionId)&&G(e.turnId))}function fT(t){return z(t)&&O(t,["ok","updated"])&&t.ok===!0&&typeof t.updated=="boolean"}function hT(t){return z(t)&&O(t,["uploaded","queued","retried","exhausted"])&&["uploaded","queued","retried","exhausted"].every(e=>Ie(t[e]))}function yT(t){return!z(t)||!O(t,["id","name","workspaceDir","type","status","groupId","createdAt","updatedAt","planStatus","planAgents","planWinnerId","leaderSessionId","primaryWorkflowId"])||!G(t.id)||!G(t.name)||!G(t.workspaceDir)||!["default","personal","group","solo","product","automation"].includes(String(t.type))||t.status!=="active"&&t.status!=="archived"||!G(t.createdAt)||!G(t.updatedAt)||!["groupId","planWinnerId","leaderSessionId","primaryWorkflowId"].every(e=>Ze(t,e))||t.planStatus!==void 0&&!["creating","running","completed","failed","cancelled"].includes(String(t.planStatus))?!1:t.planAgents===void 0||Array.isArray(t.planAgents)&&t.planAgents.every(G)}function bT(t){return z(t)&&O(t,["activeProjectId","projects"])&&(t.activeProjectId===null||G(t.activeProjectId))&&Array.isArray(t.projects)&&t.projects.every(yT)}function kT(t){return z(t)&&O(t,["ok","project","deduplicated"])&&t.ok===!0&&yT(t.project)&&(t.deduplicated===void 0||typeof t.deduplicated=="boolean")}function Zc(t,e){return!z(t)||t.version!==1||!Array.isArray(t.services)||typeof e!="string"||!Tm.has(e)||!t.services.every(n=>typeof n=="string"&&Tm.has(n))?!1:t.services.includes(e)}var el=class{pools=new Map;runtimeStates=new Map;constructor(e){if(e)for(let n of e){this.pools.set(n.providerId,n);for(let r of n.keys)this.runtimeStates.set(r.id,this.createInitialState())}}acquireKey(e){let n=this.pools.get(e);if(!n||n.keys.length===0)return null;let r=Date.now(),o=this.getHealthyCandidates(n,r);if(o.length===0)return null;let i=this.selectByStrategy(o,n.strategy,r);if(!i)return null;let s=this.runtimeStates.get(i.id);s.inFlight++,s.totalRequests++,s.lastUsedAt=r,s.requestTimestamps.push(r);let a=!1;return{keyId:i.id,apiKey:i.key,providerId:e,release:c=>{a||(a=!0,this.releaseKey(i.id,c))}}}releaseKey(e,n){let r=this.runtimeStates.get(e);if(r)if(r.inFlight=Math.max(0,r.inFlight-1),n.success)r.consecutiveErrors=0,r.healthStatus="healthy",n.tokens&&(r.totalTokens+=n.tokens,r.tokenCounts.push({timestamp:Date.now(),tokens:n.tokens}));else if(r.consecutiveErrors++,r.lastErrorAt=Date.now(),n.errorCode===429){let o=n.retryAfter?n.retryAfter*1e3:3e4;r.cooldownUntil=Date.now()+o,r.healthStatus="cooldown"}else r.consecutiveErrors>=5?(r.cooldownUntil=Date.now()+6e4,r.healthStatus="cooldown"):r.consecutiveErrors>=3&&(r.healthStatus="degraded")}addProvider(e,n){this.pools.has(e)||this.pools.set(e,{providerId:e,baseUrl:n?.baseUrl,strategy:n?.strategy??"weighted-round-robin",keys:[],rateLimit:n?.rateLimit})}removeProvider(e){let n=this.pools.get(e);if(n){for(let r of n.keys)this.runtimeStates.delete(r.id);this.pools.delete(e)}}addKey(e,n,r){let o=this.pools.get(e);o||(o={providerId:e,strategy:"weighted-round-robin",keys:[]},this.pools.set(e,o));let i=r?.id??crypto.randomUUID(),s={id:i,key:n,label:r?.label,weight:r?.weight??1,enabled:r?.enabled??!0};return o.keys.push(s),this.runtimeStates.set(i,this.createInitialState()),i}removeKey(e){for(let[n,r]of this.pools){let o=r.keys.findIndex(i=>i.id===e);if(o!==-1)return r.keys.splice(o,1),r.keys.length===0&&this.pools.delete(n),this.runtimeStates.delete(e),!0}return!1}getKeyById(e){for(let n of this.pools.values()){let r=n.keys.find(o=>o.id===e);if(r)return r.key}return null}updateKey(e,n){for(let r of this.pools.values()){let o=r.keys.find(i=>i.id===e);if(o){if(n.label!==void 0&&(o.label=n.label),n.weight!==void 0&&(o.weight=n.weight),n.enabled!==void 0){o.enabled=n.enabled;let i=this.runtimeStates.get(e);i&&(i.healthStatus=n.enabled?"healthy":"disabled")}return!0}}return!1}setKeyHealth(e,n){let r=this.runtimeStates.get(e);r&&(r.healthStatus=n)}setStrategy(e,n){let r=this.pools.get(e);r&&(r.strategy=n)}setRateLimit(e,n){let r=this.pools.get(e);r&&(r.rateLimit=n)}getPoolStatus(e){let n=this.pools.get(e);return n?this.buildPoolStatus(n):null}getAllStatus(){return[...this.pools.values()].map(e=>this.buildPoolStatus(e))}getProviderIds(){return[...this.pools.keys()]}hasProvider(e){return this.pools.has(e)}hasAvailableKey(e){let n=this.pools.get(e);return n?this.getHealthyCandidates(n,Date.now()).length>0:!1}exportConfig(){return[...this.pools.values()]}reloadConfig(e){let n=new Set;for(let r of e){this.pools.set(r.providerId,r);for(let o of r.keys)n.add(o.id),this.runtimeStates.has(o.id)||this.runtimeStates.set(o.id,this.createInitialState())}for(let r of[...this.pools.keys()])e.some(o=>o.providerId===r)||this.pools.delete(r);for(let r of[...this.runtimeStates.keys()])n.has(r)||this.runtimeStates.delete(r)}createInitialState(){return{inFlight:0,totalRequests:0,totalTokens:0,lastUsedAt:0,lastErrorAt:0,consecutiveErrors:0,cooldownUntil:0,healthStatus:"healthy",requestTimestamps:[],tokenCounts:[]}}getHealthyCandidates(e,n){let r=[];for(let o of e.keys){if(!o.enabled)continue;let i=this.runtimeStates.get(o.id);if(i){if(i.healthStatus==="cooldown")if(n>=i.cooldownUntil)i.healthStatus="healthy",i.consecutiveErrors=0;else continue;i.healthStatus!=="disabled"&&(e.rateLimit?.rpm&&(this.pruneWindow(i.requestTimestamps,n),i.requestTimestamps.length>=e.rateLimit.rpm*.9)||e.rateLimit?.tpm&&(this.pruneTokenWindow(i.tokenCounts,n),i.tokenCounts.reduce((a,c)=>a+c.tokens,0)>=e.rateLimit.tpm*.9)||r.push(o))}}return r}selectByStrategy(e,n,r){if(e.length===0)return null;if(e.length===1)return e[0];switch(n){case"weighted-round-robin":return this.weightedRandom(e);case"least-busy":return this.leastBusy(e);case"random":return e[Math.floor(Math.random()*e.length)];default:return this.weightedRandom(e)}}weightedRandom(e){let n=e.reduce((o,i)=>o+i.weight,0),r=Math.random()*n;for(let o of e)if(r-=o.weight,r<=0)return o;return e[e.length-1]}leastBusy(e){let n=1/0,r=e[0];for(let o of e){let s=this.runtimeStates.get(o.id)?.inFlight??0;(s<n||s===n&&o.weight>r.weight)&&(n=s,r=o)}return r}pruneWindow(e,n){let r=n-6e4;for(;e.length>0&&e[0]<r;)e.shift()}pruneTokenWindow(e,n){let r=n-6e4;for(;e.length>0&&e[0].timestamp<r;)e.shift()}buildPoolStatus(e){return{providerId:e.providerId,baseUrl:e.baseUrl,strategy:e.strategy,rateLimit:e.rateLimit,keys:e.keys.map(n=>{let r=this.runtimeStates.get(n.id)??this.createInitialState();return{...n,inFlight:r.inFlight,totalRequests:r.totalRequests,totalTokens:r.totalTokens,lastUsedAt:r.lastUsedAt,lastErrorAt:r.lastErrorAt,consecutiveErrors:r.consecutiveErrors,cooldownUntil:r.cooldownUntil,healthStatus:n.enabled?r.healthStatus:"disabled"}})}}};var ST=[...vT];function ms(t){if(t==="llmrouter")return process.env.QLOGIC_LLMROUTER_INFERENCE_KEY?.trim()||void 0}var Yr="llmrouter-env";function Sq(t={}){if(t.removed)return null;let e=ms("llmrouter");if(!e)return null;let n=t.enabled!==!1;return{providerId:"llmrouter",strategy:"weighted-round-robin",keys:[{id:Yr,key:e,label:"Desktop LLMRouter",weight:1,enabled:n,inFlight:0,totalRequests:0,totalTokens:0,lastUsedAt:0,lastErrorAt:0,consecutiveErrors:0,cooldownUntil:0,healthStatus:n?"healthy":"disabled"}]}}var Cm=class{keyPool;catalogProviders=new Map;models=new Map;modelEnabledOverrides=new Map;modelPurposeDisabled=new Map;bindings={};injectedKeyStates={};settingsPath;changeListeners=[];hydratedFromUpstream=!1;constructor(e){this.settingsPath=Ho(),this.keyPool=new el(e?.providers),e?.models&&this.loadModelState(e.models),e?.bindings&&(this.bindings={...e.bindings}),e?.injectedKeys&&(this.injectedKeyStates={...e.injectedKeys})}isHydratedFromUpstream(){return this.hydratedFromUpstream}markHydratedFromUpstream(){this.hydratedFromUpstream=!0}getActiveModel(e){let n=this.bindings[e];if(!n)return null;let r=this.models.get(n);if(!r||!this.isEnabledForPurpose(n,e))return null;let o=this.resolveTechnicalVariant(r,e),i=o?.provider??r.provider,s=o?.nativeModelId??r.nativeModelId??r.model,a=this.acquireKeyForProviderVariant(i);if(!a)return null;let{keyHandle:c,keyProviderId:l}=a,d=this.getProviderBaseUrl(i),u=this.getProviderBaseUrl(l);return{provider:i,model:s,apiKey:c.apiKey,baseUrl:d??(r.provider===i?r.baseUrl:void 0)??u,keyHandle:c}}peekActiveModel(e){let n=this.bindings[e];return n?this.models.get(n)??null:null}acceptsInputModality(e,n="textGeneration"){let r=this.peekActiveModel(n)?.capabilityProfile?.input_modalities;return!r||r.length===0?!0:r.includes(e)}isAvailable(e){let n=this.peekActiveModel(e);return!!n&&this.isEnabledForPurpose(n.id,e)&&this.hasAvailableKeyForProviderVariant(n.provider)}isEnabledForPurpose(e,n){let r=this.models.get(e);return!r||!r.enabled?!1:!this.modelPurposeDisabled.get(e)?.has(n)}resolveModelForPurpose(e){let n=this.peekActiveModel(e);return n?n.model:null}addProvider(e,n){this.keyPool.addProvider(e,n),this.emitChange()}removeProvider(e){this.keyPool.removeProvider(e);for(let[n,r]of this.models)r.provider===e&&this.removeModel(n);this.emitChange()}addKey(e,n,r){let o=this.keyPool.addKey(e,n,r);return this.emitChange(),o}removeKey(e){if(e===Yr)return this.hasLlmrouterEnvKey()?(this.setInjectedKeyState(e,{removed:!0,enabled:!1}),!0):!1;let n=this.keyPool.removeKey(e);return n&&this.emitChange(),n}getKeyById(e){return e===Yr?this.getInjectedKeyState(e).removed?null:ms("llmrouter")??null:this.keyPool.getKeyById(e)}updateKey(e,n){if(e===Yr)return this.hasLlmrouterEnvKey()?(n.enabled!==void 0&&this.setInjectedKeyState(e,{enabled:n.enabled}),!0):!1;let r=this.keyPool.updateKey(e,n);return r&&this.emitChange(),r}setKeyHealth(e,n){this.keyPool.setKeyHealth(e,n),this.emitChange()}setStrategy(e,n){this.keyPool.setStrategy(e,n),this.emitChange()}addModel(e){let n=e.id??`${e.provider}:${e.model}`;return this.models.set(n,{...e,id:n,enabled:this.modelEnabledOverrides.get(n)??e.enabled,disabledPurposes:this.purposeDisabledArray(n)}),this.emitChange(),n}replaceCatalogProviders(e){this.catalogProviders=new Map(e.map(n=>[n.id,n]))}replaceCatalogModels(e){let n=new Map;for(let r of e)n.set(r.id,{...r,enabled:this.modelEnabledOverrides.get(r.id)??r.enabled,disabledPurposes:this.purposeDisabledArray(r.id)});for(let r of this.modelEnabledOverrides.keys())n.has(r)||this.modelEnabledOverrides.delete(r);for(let r of this.modelPurposeDisabled.keys())n.has(r)||this.modelPurposeDisabled.delete(r);this.models=n;for(let[r,o]of Object.entries(this.bindings))o&&!this.models.has(o)&&delete this.bindings[r];this.emitChange()}replaceProviderModels(e,n){let r=new Map;for(let[i,s]of this.models)s.provider!==e&&r.set(i,s);for(let i of n)i.provider===e&&r.set(i.id,{...i,enabled:this.modelEnabledOverrides.get(i.id)??i.enabled,disabledPurposes:this.purposeDisabledArray(i.id)});let o=`${e}:`;for(let i of this.modelEnabledOverrides.keys())i.startsWith(o)&&!r.has(i)&&this.modelEnabledOverrides.delete(i);for(let i of this.modelPurposeDisabled.keys())i.startsWith(o)&&!r.has(i)&&this.modelPurposeDisabled.delete(i);this.models=r;for(let[i,s]of Object.entries(this.bindings))s&&!this.models.has(s)&&delete this.bindings[i];this.emitChange()}removeModel(e){this.models.delete(e),this.modelEnabledOverrides.delete(e),this.modelPurposeDisabled.delete(e);for(let[n,r]of Object.entries(this.bindings))r===e&&delete this.bindings[n];this.emitChange()}enableModel(e,n){if(n){let r=new Set(this.modelPurposeDisabled.get(e)??[]);if(!this.isMasterEnabled(e)){let o=this.models.get(e);for(let i of o?.routeIntents??[])i!==n&&r.add(i)}r.delete(n),this.setPurposeDisabled(e,r),this.setMasterEnabled(e,!0)}else this.setPurposeDisabled(e,new Set),this.setMasterEnabled(e,!0);this.emitChange()}disableModel(e,n){if(n){let r=new Set(this.modelPurposeDisabled.get(e)??[]);r.add(n),this.setPurposeDisabled(e,r);let o=this.models.get(e),i=!!o&&o.routeIntents.length>0&&o.routeIntents.every(s=>r.has(s));this.setMasterEnabled(e,!i)}else this.setPurposeDisabled(e,new Set),this.setMasterEnabled(e,!1);this.emitChange()}isMasterEnabled(e){let n=this.models.get(e);return n?n.enabled:this.modelEnabledOverrides.get(e)??!0}setMasterEnabled(e,n){let r=this.models.get(e);r&&(r.enabled=n),this.modelEnabledOverrides.set(e,n)}setPurposeDisabled(e,n){n.size===0?this.modelPurposeDisabled.delete(e):this.modelPurposeDisabled.set(e,n);let r=this.models.get(e);r&&(r.disabledPurposes=n.size?[...n]:void 0)}purposeDisabledArray(e){let n=this.modelPurposeDisabled.get(e);return n&&n.size?[...n]:void 0}listModels(e){let n=[...this.models.values()];if(e?.purpose&&(n=n.filter(r=>r.routeIntents.includes(e.purpose))),e?.provider&&(n=n.filter(r=>r.provider===e.provider)),e?.enabledOnly){let r=e.purpose;n=r?n.filter(o=>this.isEnabledForPurpose(o.id,r)):n.filter(o=>o.enabled)}return n}getModel(e){return this.models.get(e)??null}setBinding(e,n){let r=this.models.get(n);if(!r)throw new Error(`Model "${n}" not found in pool.`);if(!r.routeIntents.includes(e))throw new Error(`Model "${n}" does not support purpose "${e}".`);this.bindings[e]=n,this.emitChange()}removeBinding(e){delete this.bindings[e],this.emitChange()}getBinding(e){let n=this.bindings[e];return n?this.models.get(n)??null:null}getAllBindings(){let e={};for(let n of ST){let r=this.bindings[n];e[n]=r?this.models.get(r)??null:null}return e}getProviderStatus(e){return this.keyPool.getPoolStatus(e)}getAllProviderStatus(){let e=this.keyPool.getAllStatus(),n=Sq(this.getInjectedKeyState(Yr));return n?e.find(o=>o.providerId===n.providerId)?e.map(o=>o.providerId===n.providerId?{...o,keys:[...o.keys,...n.keys]}:o):[...e,n]:e}save(){let e={};try{e=JSON.parse(Pt.readFileSync(this.settingsPath,"utf-8"))}catch(o){if(o.code!=="ENOENT")throw new Error(`[model-registry] settings.json at ${this.settingsPath} is unreadable or corrupted (${o instanceof Error?o.message:String(o)}); refusing to save model config over it. Fix or remove the file, then retry.`)}delete e.provider,delete e.apiKey,delete e.model,delete e.baseUrl;let n={...e,providers:this.keyPool.exportConfig(),models:this.exportModelState(),bindings:{...this.bindings},injectedKeys:this.exportInjectedKeyStates()},r=this.settingsPath.replace(/[/\\][^/\\]+$/,"");Pt.existsSync(r)||Pt.mkdirSync(r,{recursive:!0}),Pt.writeFileSync(this.settingsPath,JSON.stringify(n,null,2),"utf-8")}load(){try{if(!Pt.existsSync(this.settingsPath))return!1;let e=Pt.readFileSync(this.settingsPath,"utf-8"),n=JSON.parse(e);return n.providers&&this.keyPool.reloadConfig(n.providers),this.models.clear(),this.modelEnabledOverrides.clear(),this.modelPurposeDisabled.clear(),n.models&&this.loadModelState(n.models),this.bindings=n.bindings??{},this.injectedKeyStates=n.injectedKeys?{...n.injectedKeys}:{},this.emitChange(),!0}catch{return!1}}exportConfig(){return{providers:this.keyPool.exportConfig(),models:this.exportModelState(),bindings:{...this.bindings},injectedKeys:this.exportInjectedKeyStates()}}getTunable(e){try{if(!Pt.existsSync(this.settingsPath))return;let n=Pt.readFileSync(this.settingsPath,"utf-8");return JSON.parse(n).tunables?.[e]}catch{return}}getModelInfo(e,n){let r=this.listModels({provider:e}).find(o=>o.model===n);if(r)return{id:r.model,name:r.displayName,contextWindow:r.contextWindow,maxOutput:r.maxOutput,streamRequired:r.streamRequired}}getProviderDefaultModel(e){return this.listModels({provider:e,enabledOnly:!0})[0]?.model??this.listModels({provider:e})[0]?.model}hasConfiguredKeyForProviderVariant(e){return this.providerVariantKeyCandidates(e).some(n=>!!this.keyPool.getPoolStatus(n)?.keys.some(o=>o.enabled))||this.hasEnabledLlmrouterEnvKey(e)}hasAvailableKeyForProviderVariant(e){return this.providerVariantKeyCandidates(e).some(n=>this.keyPool.hasAvailableKey(n))||this.hasEnabledLlmrouterEnvKey(e)}listProviderDefs(){return this.keyPool.getAllStatus().map(e=>({id:e.providerId,name:e.providerId,transport:"",baseUrl:e.baseUrl??"",defaultModel:this.getProviderDefaultModel(e.providerId),models:this.listModels({provider:e.providerId}).map(n=>({id:n.model,name:n.displayName,contextWindow:n.contextWindow,maxOutput:n.maxOutput,streamRequired:n.streamRequired}))}))}getKnownProviderDef(e){return this.catalogProviders.get(e)??null}resolveProviderApiKey(e){return this.getKeyForProvider(e)??void 0}onChange(e){return this.changeListeners.push(e),()=>{let n=this.changeListeners.indexOf(e);n>=0&&this.changeListeners.splice(n,1)}}getKeyForProvider(e){let r=this.acquireKeyForProviderVariant(e)?.keyHandle;if(!r)return null;let o=r.apiKey;return r.release({success:!0}),o}snapshotProviderKeys(){let e={};for(let n of this.getAllProviderStatus()){let r=this.getKeyForProvider(n.providerId);r&&(e[n.providerId]=r)}return e}getProviderBaseUrl(e){return this.catalogProviders.get(e)?.baseUrl??this.keyPool.getPoolStatus(e)?.baseUrl}acquireKeyForProviderVariant(e){for(let r of this.providerVariantKeyCandidates(e)){let o=this.keyPool.acquireKey(r);if(o)return{keyHandle:o,keyProviderId:r}}let n=this.hasEnabledLlmrouterEnvKey(e)?ms(e):void 0;return n?{keyHandle:{keyId:"llmrouter-env",apiKey:n,providerId:e,release:()=>{}},keyProviderId:e}:null}resolveTechnicalVariant(e,n){return{provider:e.provider,nativeModelId:e.nativeModelId??e.model}}providerVariantKeyCandidates(e){return[e]}hasLlmrouterEnvKey(){return!this.getInjectedKeyState(Yr).removed&&!!ms("llmrouter")}hasEnabledLlmrouterEnvKey(e){if(e!=="llmrouter")return!1;let n=this.getInjectedKeyState(Yr);return!n.removed&&n.enabled!==!1&&!!ms(e)}getInjectedKeyState(e){return this.injectedKeyStates[e]??{}}setInjectedKeyState(e,n){this.injectedKeyStates={...this.injectedKeyStates,[e]:{...this.getInjectedKeyState(e),...n}},this.emitChange()}loadModelState(e){for(let n of e)if(!(typeof n.id!="string"||!n.id)&&(typeof n.enabled=="boolean"&&this.modelEnabledOverrides.set(n.id,n.enabled),Array.isArray(n.disabledPurposes))){let r=n.disabledPurposes.filter(o=>ST.includes(o));r.length&&this.modelPurposeDisabled.set(n.id,new Set(r))}}exportModelState(){let e=new Map;for(let[r,o]of this.modelEnabledOverrides)e.set(r,o);for(let r of this.models.values())e.set(r.id,r.enabled);return[...new Set([...e.keys(),...this.modelPurposeDisabled.keys()])].map(r=>{let o=this.modelPurposeDisabled.get(r),i={id:r,enabled:e.get(r)??!0};return o&&o.size&&(i.disabledPurposes=[...o]),i})}exportInjectedKeyStates(){return{...this.injectedKeyStates}}emitChange(){for(let e of this.changeListeners)try{e()}catch{}}},tl=null;function ce(){return tl||(tl=new Cm,tl.load()),tl}function Qt(t=process.env){return{get:e=>t[e]}}var wq="\u65E0\u6CD5\u8FDE\u63A5 llmrouter \u6A21\u578B\u76EE\u5F55",Xr="llmrouter";var wT=6e4,Im=new Map,Am=new Map,kn=class extends Error{constructor(e=wq){super(e),this.name="LlmrouterCatalogUnavailableError"}},nl=class extends Error{status;constructor(e,n="llmrouter inference key rejected (not active)"){super(n),this.name="LlmrouterAuthError",this.status=e}};function _m(t=Qt()){let e=t.get("QLOGIC_LLMROUTER_BASE_URL")?.trim().replace(/\/+$/,"");if(!e)throw new kn;return e}function TT(t=Qt()){let e={accept:"application/json"},n=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();return n&&(e.authorization=`Bearer ${n}`),e}async function RT(t,e){let n=_m(e),r=TT(e),o=`${n}
230
230
  ${t}
231
231
  ${r.authorization??""}`,i=Im.get(o);if(i&&Date.now()<i.expiresAt)return i.value;let s=Am.get(o);if(s)return await s;let a=xT(n,t,r).then(c=>(Im.set(o,{value:c,expiresAt:Date.now()+wT}),c)).finally(()=>{Am.delete(o)});return Am.set(o,a),a}async function PT(t,e){let n=_m(e),r=TT(e),o=`${n}
@@ -370,7 +370,7 @@ ${Gm(n)}`)}catch(s){return console.error(`[context-compression] LLM summarizatio
370
370
 
371
371
  ${Gm(n)}`}}}function Gm(t){let e=[],n=t.filter(i=>i.role==="user"),r=n.slice(0,20).map(i=>{let s=typeof i.content=="string"?i.content:JSON.stringify(i.content??"");return`- [user]: ${s.slice(0,300)}${s.length>300?"...":""}`});e.push(`## User Requests (${n.length} messages)`),e.push(...r);let o=t.filter(i=>i.role==="assistant");if(o.length>0){let i=o.slice(0,10).map(s=>{let a=typeof s.content=="string"?s.content:JSON.stringify(s.content??"");return`- [assistant]: ${a.slice(0,150)}${a.length>150?"...":""}`});e.push("",`## Assistant Responses (${o.length} total)`),e.push(...i)}return e.join(`
372
372
  `)}function J1(){return Yu(new Ar(Km),new Ln(20,eo),new Ro(eo))}function wR(t,e){let n=Xu(new Ar(Km),new Ln(20,eo),new Oi({protectedHeadExchanges:1,protectedTailMessages:8,summarize:t,estimateTokens:eo}),new Ro(eo));return new Ni({inner:n,estimateTokens:eo,onCacheInvalidated:e?.onCacheInvalidated})}var Vm=null;function vs(t,e){let n=e?.budget??Ya({modelContextWindow:TR(e?.model)}),o=(e?.pipeline??J1()).compress(t,n);if(o.droppedCount>0){let i=to(t),s=to(o.messages);RR.record({timestamp:Date.now(),strategy:o.strategy,tokensBefore:i,tokensAfter:s,droppedCount:o.droppedCount,latencyMs:o.metrics?.latencyMs??0,usedLlm:!1,cacheInvalidated:o.metrics?.cacheInvalidated??!1,tier:Fi(i,n)})}return o.droppedCount>0&&Vm?.(o.droppedCount,to(o.messages)),o}async function Q1(t,e,n){let r=n??Ya({modelContextWindow:TR(e.model)}),o=to(t),i=Fi(o,r),s;switch(i){case"none":s={messages:t,droppedCount:0,strategy:"none"};break;case"trim-only":s=new Ar(Km).compress(t,r);break;case"sliding-window":{s=await wR(e.summarize).compressAsync(t,r);break}case"llm-summarize":{let a=e.pipeline??wR(e.summarize);s=ji(a)?await a.compressAsync(t,r):a.compress(t,r);break}}return s.droppedCount>0&&(s={...s,messages:await Qu(s.messages,t,{maxFiles:5,maxTokenBudget:5e4,readFile:async a=>{try{return await K1(a,"utf-8")}catch{return null}}})}),Z1(t,s,r),s}function Z1(t,e,n){if(e.droppedCount>0||e.metrics?.usedLlm){let r=e.metrics?.tokensBefore||to(t),o=e.metrics?.tokensAfter||to(e.messages);RR.record({timestamp:Date.now(),strategy:e.strategy,tokensBefore:r,tokensAfter:o,droppedCount:e.droppedCount,latencyMs:e.metrics?.latencyMs??0,usedLlm:e.metrics?.usedLlm??!1,cacheInvalidated:e.metrics?.cacheInvalidated??!1,tier:Fi(r,n)})}if(e.droppedCount>0){let r=e.metrics?.tokensAfter||to(e.messages);Vm?.(e.droppedCount,r)}}function eW(t,e){let n=X1(t,e),r={id:"builtin-compressor",label:"4-Layer Compression Funnel (built-in)",async compressAsync(o,i,s){return Q1(o,{budget:i,model:s?.model,sessionId:s?.sessionId,summarize:n},i)}};zm.register(r),zm.activate(r.id),t.info(`[context-compression] registered context engine: ${r.id}`)}function xR(t,e,n){eW(e,n),t.register({point:"context.before_compact",priority:50,label:"context-compression-bridge",handler:(r,o)=>{let i=o.messageCount;return i&&i>0&&e.debug(`[context-compression] before_compact: ${i} messages entering compression`),{action:"continue"}}}),Vm=(r,o)=>{e.debug(`[context-compression] after_compact: removed ${r}, ${o} tokens remaining`),t.invoke("context.after_compact",{sessionId:"",turnId:"",removedCount:r,tokenCount:o}).catch(()=>{})}}function CR(t,e,n){let r=n-e;return`[Budget] ${Math.round(t)}% used (${e.toLocaleString()} / ${n.toLocaleString()} tokens). ${r.toLocaleString()} tokens remaining. `+(t>=90?"Wrap up your current taskyou are near the token limit.":"Continue workingdo not summarize prematurely.")}function Kn(t){return t?.riskLevel?t.riskLevel:t?.isDangerous?"system":t?.isReadOnly?"read":t?.isEgress?"external_egress":"write"}function tW(t,e){if(!e)return!1;for(let n of e)try{if(new RegExp(n,"i").test(t))return!0}catch(r){console.error(`[tool-eligibility] invalid dangerousPatterns regex ${JSON.stringify(n)} ignored: ${String(r instanceof Error?r.message:r)}`)}return!1}function nW(t,e){let n=Kn(t.meta);return n==="write"&&tW(t.function.name,e.dangerousPatterns)?"system":n}function rW(t){return`risk_${t}`}function oW(t,e){let n=t.function.name,r=nW(t,e),o=[];return e.blockedToolNames?.includes(n)?(o.push("policy_blocked"),{decision:"deny",riskLevel:r,reasonCodes:o}):(o.push(rW(r)),t.meta?.requiresApproval||r==="system"||r==="external_egress"?(t.meta?.requiresApproval&&o.unshift("requires_approval"),{decision:"ask",riskLevel:r,reasonCodes:o}):{decision:"allow",riskLevel:r,reasonCodes:o})}function iW(t){switch(t){case"allow":return"eligible";case"ask":return"approval-required";case"deny":return"blocked-by-policy"}}function AR(t,e={}){let n=new Map,r=[],o=[],i=[];for(let s of t){let a=s.function.name,{decision:c,riskLevel:l,reasonCodes:d}=oW(s,e),u=iW(c),p={toolName:a,status:u,decision:c,riskLevel:l,approvalRequired:c==="ask",reasonCodes:d};if(n.set(a,p),c==="deny"){o.push(p);continue}r.push(s),c==="ask"&&i.push(p)}return{eligibleTools:r,blockedTools:o,approvalRequiredTools:i,eligibilityByName:n}}function al(){return{resolveModelForPurpose:t=>ce().resolveModelForPurpose(t),toolLoop:{createContentReplacementState:pR,enforceToolResultBudget:bR,getActiveContextCompressionEngine:()=>PR().getActive()??null,compressMessages:vs,getBudgetContinuationMessage:CR,createStreamingToolExecutor:t=>new sl(t),resolveToolEligibility:(t,e)=>AR(t,e)}}}var vn=({transport:t,apiKey:e,toolInvoker:n,log:r,hooks:o,maxRounds:i})=>new Hr({llmTransport:t,apiKey:e,toolInvoker:n,log:r,hooks:o,maxRounds:i,runtimePorts:al()});async function Xo(t,e){let n=t.params??{},r=n.turnId??IR(),o=n.sessionId,i=n.config,s=e!==void 0,a=Me(),c=i?.memoryRoot||this.resolveMemoryRoot?.()||Ym.join(a,"memory"),l=i?.transcriptDir||this.resolveTranscriptDir?.()||Ym.join(a,"agent-logs"),d=i?.dreamSessionIds??[];t.id!==void 0&&this.sendResponse(t.id,{accepted:!0,turnId:r});let u=new AbortController,p=()=>u.abort(e?.reason);e?.aborted?p():e?.addEventListener("abort",p,{once:!0}),this.activeTurn=u,this.log(`dream ${r} starting (session: ${o}, sessions reviewing: ${d.length})`),s||this.sendNotification("system.activity",{category:"dream",level:"info",title:"\u68A6\u5883\u6574\u7406\u542F\u52A8",detail:`\u6B63\u5728\u56DE\u987E ${d.length} \u4E2A\u4F1A\u8BDD\u7684\u8BB0\u5FC6...`});let g={provider:i?.provider,model:i?.model,apiKey:i?.apiKey,baseUrl:i?.baseUrl,maxRounds:i?.maxRounds,temperature:i?.temperature,contextWindowTokens:i?.contextWindowTokens,maxOutputTokens:i?.maxOutputTokens,modelMaxOutputTokens:i?.modelMaxOutputTokens,reasoning:i?.reasoning,promptCacheKey:i?.promptCacheKey,promptCacheRetention:i?.promptCacheRetention,serviceTier:i?.serviceTier,openaiBuiltinTools:i?.openaiBuiltinTools,maxToolCalls:i?.maxToolCalls,parallelToolCalls:i?.parallelToolCalls,textVerbosity:i?.textVerbosity};{let f=g.provider??"",h=g.model??"";if(f&&h){let y=ce().getModelInfo(f,h);y?.streamRequired&&(g.streamRequired=!0),!g.contextWindowTokens&&y?.contextWindow&&(g.contextWindowTokens=y.contextWindow)}}if(!this.resolveAgent(g)||!this.currentTransport){s||(this.sendNotification("turn.start",{turnId:r}),this.sendNotification("turn.error",{turnId:r,error:{message:"No LLM provider configured for dream.",code:"NO_PROVIDER"}})),e?.removeEventListener("abort",p),this.activeTurn===u&&(this.activeTurn=null);return}s||this.sendNotification("turn.start",{turnId:r});try{let f={context:{memoryRoot:c,transcriptDir:l,currentSessionId:o,listSessionsSince:async()=>d,currentSessionTurnCount:i?.currentSessionTurnCount??0},triggerConfig:{force:i?.force!==!1},transport:this.currentTransport,toolInvoker:{invoke:async(y,b,P,w)=>{if(b.startsWith("$"))return{result:P};let C=this.toolCatalog.findTool(b);if(!C||typeof C.execute!="function")return{result:"",error:`Unknown tool: ${b}`};let A=`tc_${IR().slice(0,8)}`;try{let v=JSON.parse(P),x=await C.execute(A,v,w);return{result:x.content.map(M=>M.text??"").join(`
373
- `),error:x.details?.error}}catch(v){return{result:"",error:v instanceof Error?v.message:String(v)}}}},createAgentRunner:vn,tools:this.toolCatalog.getToolManifest(),taskStore:this.taskStore,apiKey:this.currentApiKey,model:g.model??this.currentModel,log:{info:y=>this.log(y),warn:y=>this.log(`[warn] ${y}`),error:y=>this.log(`[error] ${y}`),debug:y=>{this.verbose&&this.log(`[debug] ${y}`)}},hooks:this.currentHooks??void 0,parentSignal:u.signal,memoryProvider:this.memoryProvider??void 0,memoryUserId:this.memoryUserId||void 0},h=await sR(f);await sW(this,c),h.ok?s||(this.sendNotification("system.activity",{category:"dream",level:"success",title:"\u68A6\u5883\u6574\u7406\u5B8C\u6210",detail:`\u56DE\u987E ${h.sessionsReviewed} \u4E2A\u4F1A\u8BDD\uFF0C\u6574\u7406 ${h.filesTouched.length} \u4E2A\u8BB0\u5FC6\u6587\u4EF6\uFF0C\u8017\u65F6 ${h.durationMs}ms`}),this.sendNotification("memory.updated",{source:"dream",target:"consolidation",files:h.filesTouched}),this.sendNotification("turn.end",{turnId:r,content:`Dream consolidation completed. ${h.sessionsReviewed} sessions reviewed, ${h.filesTouched.length} files touched. Duration: ${h.durationMs}ms.`,usage:{inputTokens:0,outputTokens:0}})):s||(this.sendNotification("system.activity",{category:"dream",level:"error",title:"\u68A6\u5883\u6574\u7406\u5931\u8D25",detail:h.error??"\u672A\u77E5\u9519\u8BEF"}),this.sendNotification("turn.error",{turnId:r,error:{message:h.error??"Dream consolidation failed",code:"DREAM_FAILED"}})),this.log(`dream ${r} completed`)}catch(f){if(u.signal.aborted)s||(this.sendNotification("system.activity",{category:"dream",level:"warn",title:"\u68A6\u5883\u6574\u7406\u88AB\u4E2D\u65AD"}),this.sendNotification("turn.error",{turnId:r,error:{message:"Dream aborted",code:"ABORTED"}}));else{let h=f instanceof Error?f.message:String(f);s||(this.sendNotification("system.activity",{category:"dream",level:"error",title:"\u68A6\u5883\u6574\u7406\u5F02\u5E38",detail:h}),this.sendNotification("turn.error",{turnId:r,error:{message:h,code:"INTERNAL_ERROR"}}))}}finally{e?.removeEventListener("abort",p),this.activeTurn===u&&(this.activeTurn=null)}}async function sW(t,e){if(!(!t.memoryProvider||!t.memoryUserId)){try{let n=await lR({adapter:t.memoryProvider,userId:t.memoryUserId,memoryRoot:e,log:{info:r=>t.log(r),debug:r=>{t.verbose&&t.log(r)}}});n.ran&&t.log(`[decay] completed: decayed=${n.decayed} archived=${n.archived} duration=${n.durationMs}ms`)}catch(n){console.error(`[decay] post-dream decay error: ${n instanceof Error?n.message:String(n)}`)}try{let n=t.memoryProvider;if(typeof n.resolveConflicts=="function"){let r=await n.resolveConflicts(t.memoryUserId);(r.conflictsResolved>0||r.claimsPromoted>0)&&t.log(`[dream] resolved ${r.conflictsResolved} conflicts, promoted ${r.claimsPromoted} pending claims`)}}catch(n){console.error(`[consolidation] post-dream conflict resolution error: ${n instanceof Error?n.message:String(n)}`)}try{let n=t.memoryProvider;if(typeof n.consumePendingProposals=="function"){let r=await n.consumePendingProposals(t.memoryUserId);(r.committed>0||r.expiredIds.length>0)&&t.log(`[dream] proposal consumer: committed=${r.committed} merged=${r.merged} expired=${r.expiredIds.length} pending=${r.pendingLeft}`)}}catch(n){console.error(`[consolidation] post-dream proposal consume error: ${n instanceof Error?n.message:String(n)}`)}}}function aW(t){let e=dW(t.fetchFn??fetch,t.clientVersion),n=t.token.trim();return{async resolveInstall(r,o){let i=encodeURIComponent(r.trim());if(!i)throw new Error("resourceId is required.");let s=o?.trim(),a=s?`?version=${encodeURIComponent(s)}`:"",c=await Jm(e,Xm(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=Qm(c);if(!l)throw new Error("Community hub returned an invalid install resolution.");return l},async listResourceVersions(r){let o=encodeURIComponent(r.trim());if(!o)throw new Error("resourceId is required.");let i=await Jm(e,Xm(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(Ss(i)&&Array.isArray(i.versions)?i.versions:[]).map(OR).filter(a=>!!a)},async resolveRuntime(r,o){let i=r.trim(),s=encodeURIComponent(i);if(!s)throw new Error("runtime id is required.");let a=o.trim(),c=encodeURIComponent(a);if(!c)throw new Error("platform is required.");let l=await Jm(e,Xm(t.baseUrl,`/api/v15/runtime/${s}/resolve?platform=${c}`),n,"GET"),d=NR(l,i,a);if(!d)throw new Error("Community hub returned an invalid runtime resolution.");return d}}}function MR(t){return{async resolveInstall(e,n){let r=await t.resolveInstall(e,n),o=Qm(r);if(!o)throw new Error("Community hub returned an invalid install resolution.");return o},async listResourceVersions(e){let n=await t.listResourceVersions(e);return(Ss(n)&&Array.isArray(n.versions)?n.versions:[]).map(OR).filter(o=>!!o)},async resolveRuntime(e,n){let r=await t.resolveRuntime(e,n),o=NR(r,e,n);if(!o)throw new Error("Community hub returned an invalid runtime resolution.");return o}}}function DR(t=Qt()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=cW(t);return aW({baseUrl:lW(t),token:e,clientVersion:n})}function cW(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.20.4"}function lW(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Xm(t,e){let n=t.trim().replace(/\/+$/,"");return n.endsWith("/v1")&&(n=n.slice(0,-3)),n.endsWith("/api")&&(n=n.slice(0,-4)),`${n}${e}`}function dW(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function Jm(t,e,n,r,o){let i,s=o!==void 0;try{i=await t(e,{method:r,headers:{accept:"application/json",authorization:`Bearer ${n}`,...s?{"content-type":"application/json"}:{}},...s?{body:JSON.stringify(o)}:{},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Community hub is unavailable.")}if(!i.ok)throw new Error(`Community hub rejected registry request: ${i.status}${await uW(i)}`);return i.json().catch(()=>null)}async function uW(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function Ss(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function OR(t){return!Ss(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 NR(t,e,n){if(!Ss(t))return null;let r=typeof t.id=="string"?t.id:"",o=typeof t.platform=="string"?t.platform:"",i=typeof t.version=="string"?t.version:"",s=typeof t.downloadUrl=="string"?t.downloadUrl:"",a=typeof t.checksum=="string"?t.checksum:"",c=typeof t.sizeBytes=="number"?t.sizeBytes:0;if(!r||r!==e||o!==n||!i||!s||!/^[a-f0-9]{64}$/.test(a)||!Number.isSafeInteger(c)||c<=0)return null;let l=t.format,d=l===void 0&&r==="officecli"?"executable":l;if(d!=="executable"&&d!=="zip"&&d!=="tar.gz")return null;let u=typeof t.entrypoint=="string"?t.entrypoint:void 0;return(d==="zip"||d==="tar.gz")&&!ER(u)||u!==void 0&&!ER(u)?null:{id:r,platform:o,version:i,downloadUrl:s,checksum:a,sizeBytes:c,format:d,...u?{entrypoint:u}:{}}}function ER(t){return!t||t.includes("\\")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:t.split("/").every(n=>!!n&&n!=="."&&n!=="..")}var pW=new Set(["R0","R1","R2","R3"]),gW=new Set(["official","community"]),mW=new Set(["quarantine","trial","trusted"]),fW=new Set(["pending","approved","rejected"]);function _R(t){return typeof t=="string"&&pW.has(t)?t:null}function hW(t){return typeof t=="string"&&gW.has(t)?t:null}function yW(t){return typeof t=="string"&&mW.has(t)?t:null}function bW(t){return typeof t=="string"&&fW.has(t)?t:null}function Qm(t){if(!Ss(t))return null;let e=hW(t.sourceTier),n=yW(t.trustStage),r=bW(t.reviewStatus),o=_R(t.resourceRiskTier),i=_R(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.type!="string"||typeof t.kind!="string"||!e||!n||!r||!o||!i||typeof t.version!="string"||typeof t.checksum!="string"||typeof t.sizeBytes!="number"||typeof t.downloadUrl!="string")return null;let s=Array.isArray(t.requires)?t.requires:null,a=Array.isArray(t.dependencies)?t.dependencies:null;if(!s||!a||s.some(l=>typeof l!="string"))return null;let c=a.map(Qm);return c.some(l=>!l)?null:{id:t.id,type:t.type,kind:t.kind,sourceTier:e,trustStage:n,reviewStatus:r,resourceRiskTier:o,effectiveRiskTier:i,requires:s,dependencies:c,version:t.version,checksum:t.checksum,sizeBytes:t.sizeBytes,downloadUrl:t.downloadUrl,manifest:t.manifest,minClientVersion:typeof t.minClientVersion=="string"&&t.minClientVersion.trim()?t.minClientVersion.trim():void 0,signature:typeof t.signature=="string"&&t.signature.trim()?t.signature:null,signingKeyId:typeof t.signingKeyId=="string"&&t.signingKeyId.trim()?t.signingKeyId:null}}var Zm={enabled:!0},kW=new Set(["R2","R3"]);function LR(t,e=Zm){return kW.has(t.effectiveRiskTier)?{mode:"high-risk-ask",requiresInstallConsent:!0,requiresHighRiskConsent:!0,reason:`effectiveRiskTier=${t.effectiveRiskTier} \u9AD8\u5371,\u5FC5\u987B\u9AD8\u5371\u95EE\u4EBA`}:e.enabled?t.effectiveRiskTier==="R0"?{mode:"silent",requiresInstallConsent:!1,requiresHighRiskConsent:!1,reason:"R0 \u4F4E\u98CE\u9669 inert,\u81EA\u6CBB\u9759\u9ED8\u83B7\u53D6"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"R1 \u4F4E\u98CE\u9669\u4F46\u975E\u96F6,\u95EE\u4EBA\u4E00\u6B21"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"\u81EA\u6CBB\u9884\u7B97\u5173\u95ED,\u56DE\u9000\u663E\u5F0F\u540C\u610F"}}import{gunzipSync as qW}from"node:zlib";import{gunzipSync as RW}from"node:zlib";import*as ws from"node:fs/promises";import*as Zt from"node:path";import{createHash as UR}from"node:crypto";import{existsSync as vW}from"node:fs";import*as gt from"node:fs/promises";import*as cl from"node:path";import{Transform as nce}from"node:stream";import{pipeline as oce}from"node:stream/promises";var SW=4*1024*1024,wW=3;async function HR(t,e,n){let r=cl.join(Uo(),"cache","downloads",`${TW(e.downloadUrl)}.part`),o=0;if(vW(r)){let l=(await gt.stat(r)).size;o=l<e.sizeBytes?l:0,o===0&&await gt.rm(r,{force:!0})}let i=await jR(t,e.downloadUrl,o,$R(o,e.sizeBytes),n);if(i.whole)return await gt.rm(r,{force:!0}).catch(()=>{}),FR(i.bytes,e,n);await gt.mkdir(cl.dirname(r),{recursive:!0});let s=await gt.open(r,o>0?"r+":"w");try{if(i.bytes.length===0)throw new Error(`${n} download truncated.`);for(await s.write(i.bytes,0,i.bytes.length,o),o+=i.bytes.length;o<e.sizeBytes;){let l=await jR(t,e.downloadUrl,o,$R(o,e.sizeBytes),n);if(l.bytes.length===0)throw new Error(`${n} download truncated.`);await s.write(l.bytes,0,l.bytes.length,o),o+=l.bytes.length}}finally{await s.close()}let a=await gt.readFile(r),c=FR(a,e,n,r);return await gt.rm(r,{force:!0}).catch(()=>{}),c}function $R(t,e){return Math.min(t+SW,e)-1}function TW(t){return UR("sha256").update(t).digest("hex").slice(0,32)}async function jR(t,e,n,r,o){let i=0;for(let s=0;s<wW;s++)try{let a=await t(e,{method:"GET",headers:{range:`bytes=${n}-${r}`},signal:AbortSignal.timeout(3e4)});if(a.status===206)return{bytes:Buffer.from(await a.arrayBuffer()),whole:!1};if(a.ok)return{bytes:Buffer.from(await a.arrayBuffer()),whole:!0};i=a.status}catch{i=0}throw new Error(i?`${o} download failed: ${i}.`:`${o} download failed.`)}function FR(t,e,n,r){let o=i=>{throw r&&gt.rm(r,{force:!0}).catch(()=>{}),new Error(i)};return t.length!==e.sizeBytes&&o(`${n} size did not match registry metadata.`),UR("sha256").update(t).digest("hex")!==e.checksum&&o(`${n} checksum did not match registry metadata.`),t}var ef=64*1024*1024,tf=1024,PW=ef+tf*512+1024;async function dl(t,e,n){return HR(t,e,n)}async function BR(t,e,n){let r;try{r=RW(t,{maxOutputLength:PW})}catch(a){throw/larger than|output length|buffer too large/i.test(a instanceof Error?a.message:String(a))?new Error(`${n} expanded archive exceeds the extraction limit.`):new Error(`${n} must be a gzip-compressed tar archive.`)}let o=0,i=0,s=0;for(;o+512<=r.length;){let a=r.subarray(o,o+512);if(a.every(y=>y===0))return;let c=ll(a,0,100),l=ll(a,345,155),d=l?`${l}/${c}`:c,u=ll(a,124,12).trim(),p=Number.parseInt(u||"0",8);if(!Number.isFinite(p)||p<0)throw new Error(`${n} has an invalid tar entry size.`);let g=ll(a,156,1)||"0",m=o+512,f=m+p;if(f>r.length)throw new Error(`${n} tar entry is truncated.`);let h=xW(e,d,n);if(g==="5")await ws.mkdir(h,{recursive:!0});else if(g==="0"||g==="\0"){if(s+=1,i+=p,s>tf)throw new Error(`${n} exceeds the ${tf}-file extraction limit.`);if(i>ef)throw new Error(`${n} expanded file payload exceeds the ${ef}-byte limit.`);await ws.mkdir(Zt.dirname(h),{recursive:!0}),await ws.writeFile(h,r.subarray(m,f))}else throw new Error(`${n} may only contain regular files and directories.`);o=m+Math.ceil(p/512)*512}throw new Error(`${n} tar archive is missing an end marker.`)}function xW(t,e,n){let r=Zt.posix.normalize(e.replace(/\\/g,"/"));if(!r||r==="."||r.startsWith("../")||Zt.posix.isAbsolute(r))throw new Error(`${n} contains an unsafe path.`);let o=Zt.resolve(t,...r.split("/")),i=Zt.resolve(t);if(o!==i&&!o.startsWith(i+Zt.sep))throw new Error(`${n} contains an unsafe path.`);return o}function ll(t,e,n){let r=t.subarray(e,e+n),o=r.indexOf(0);return r.subarray(0,o===-1?r.length:o).toString("utf8")}import{createPublicKey as CW,verify as AW}from"node:crypto";function IW(t){return`id=${t.id}
373
+ `),error:x.details?.error}}catch(v){return{result:"",error:v instanceof Error?v.message:String(v)}}}},createAgentRunner:vn,tools:this.toolCatalog.getToolManifest(),taskStore:this.taskStore,apiKey:this.currentApiKey,model:g.model??this.currentModel,log:{info:y=>this.log(y),warn:y=>this.log(`[warn] ${y}`),error:y=>this.log(`[error] ${y}`),debug:y=>{this.verbose&&this.log(`[debug] ${y}`)}},hooks:this.currentHooks??void 0,parentSignal:u.signal,memoryProvider:this.memoryProvider??void 0,memoryUserId:this.memoryUserId||void 0},h=await sR(f);await sW(this,c),h.ok?s||(this.sendNotification("system.activity",{category:"dream",level:"success",title:"\u68A6\u5883\u6574\u7406\u5B8C\u6210",detail:`\u56DE\u987E ${h.sessionsReviewed} \u4E2A\u4F1A\u8BDD\uFF0C\u6574\u7406 ${h.filesTouched.length} \u4E2A\u8BB0\u5FC6\u6587\u4EF6\uFF0C\u8017\u65F6 ${h.durationMs}ms`}),this.sendNotification("memory.updated",{source:"dream",target:"consolidation",files:h.filesTouched}),this.sendNotification("turn.end",{turnId:r,content:`Dream consolidation completed. ${h.sessionsReviewed} sessions reviewed, ${h.filesTouched.length} files touched. Duration: ${h.durationMs}ms.`,usage:{inputTokens:0,outputTokens:0}})):s||(this.sendNotification("system.activity",{category:"dream",level:"error",title:"\u68A6\u5883\u6574\u7406\u5931\u8D25",detail:h.error??"\u672A\u77E5\u9519\u8BEF"}),this.sendNotification("turn.error",{turnId:r,error:{message:h.error??"Dream consolidation failed",code:"DREAM_FAILED"}})),this.log(`dream ${r} completed`)}catch(f){if(u.signal.aborted)s||(this.sendNotification("system.activity",{category:"dream",level:"warn",title:"\u68A6\u5883\u6574\u7406\u88AB\u4E2D\u65AD"}),this.sendNotification("turn.error",{turnId:r,error:{message:"Dream aborted",code:"ABORTED"}}));else{let h=f instanceof Error?f.message:String(f);s||(this.sendNotification("system.activity",{category:"dream",level:"error",title:"\u68A6\u5883\u6574\u7406\u5F02\u5E38",detail:h}),this.sendNotification("turn.error",{turnId:r,error:{message:h,code:"INTERNAL_ERROR"}}))}}finally{e?.removeEventListener("abort",p),this.activeTurn===u&&(this.activeTurn=null)}}async function sW(t,e){if(!(!t.memoryProvider||!t.memoryUserId)){try{let n=await lR({adapter:t.memoryProvider,userId:t.memoryUserId,memoryRoot:e,log:{info:r=>t.log(r),debug:r=>{t.verbose&&t.log(r)}}});n.ran&&t.log(`[decay] completed: decayed=${n.decayed} archived=${n.archived} duration=${n.durationMs}ms`)}catch(n){console.error(`[decay] post-dream decay error: ${n instanceof Error?n.message:String(n)}`)}try{let n=t.memoryProvider;if(typeof n.resolveConflicts=="function"){let r=await n.resolveConflicts(t.memoryUserId);(r.conflictsResolved>0||r.claimsPromoted>0)&&t.log(`[dream] resolved ${r.conflictsResolved} conflicts, promoted ${r.claimsPromoted} pending claims`)}}catch(n){console.error(`[consolidation] post-dream conflict resolution error: ${n instanceof Error?n.message:String(n)}`)}try{let n=t.memoryProvider;if(typeof n.consumePendingProposals=="function"){let r=await n.consumePendingProposals(t.memoryUserId);(r.committed>0||r.expiredIds.length>0)&&t.log(`[dream] proposal consumer: committed=${r.committed} merged=${r.merged} expired=${r.expiredIds.length} pending=${r.pendingLeft}`)}}catch(n){console.error(`[consolidation] post-dream proposal consume error: ${n instanceof Error?n.message:String(n)}`)}}}function aW(t){let e=dW(t.fetchFn??fetch,t.clientVersion),n=t.token.trim();return{async resolveInstall(r,o){let i=encodeURIComponent(r.trim());if(!i)throw new Error("resourceId is required.");let s=o?.trim(),a=s?`?version=${encodeURIComponent(s)}`:"",c=await Jm(e,Xm(t.baseUrl,`/api/v15/registry/resources/${i}/install${a}`),n,"GET"),l=Qm(c);if(!l)throw new Error("Community hub returned an invalid install resolution.");return l},async listResourceVersions(r){let o=encodeURIComponent(r.trim());if(!o)throw new Error("resourceId is required.");let i=await Jm(e,Xm(t.baseUrl,`/api/v15/registry/resources/${o}/versions`),n,"GET");return(Ss(i)&&Array.isArray(i.versions)?i.versions:[]).map(OR).filter(a=>!!a)},async resolveRuntime(r,o){let i=r.trim(),s=encodeURIComponent(i);if(!s)throw new Error("runtime id is required.");let a=o.trim(),c=encodeURIComponent(a);if(!c)throw new Error("platform is required.");let l=await Jm(e,Xm(t.baseUrl,`/api/v15/runtime/${s}/resolve?platform=${c}`),n,"GET"),d=NR(l,i,a);if(!d)throw new Error("Community hub returned an invalid runtime resolution.");return d}}}function MR(t){return{async resolveInstall(e,n){let r=await t.resolveInstall(e,n),o=Qm(r);if(!o)throw new Error("Community hub returned an invalid install resolution.");return o},async listResourceVersions(e){let n=await t.listResourceVersions(e);return(Ss(n)&&Array.isArray(n.versions)?n.versions:[]).map(OR).filter(o=>!!o)},async resolveRuntime(e,n){let r=await t.resolveRuntime(e,n),o=NR(r,e,n);if(!o)throw new Error("Community hub returned an invalid runtime resolution.");return o}}}function DR(t=Qt()){let e=t.get("QLOGIC_LLMROUTER_ACCESS_TOKEN")?.trim();if(!e)return null;let n=cW(t);return aW({baseUrl:lW(t),token:e,clientVersion:n})}function cW(t){let e=t.get("QLOGIC_AGENT_VERSION")?.trim();return e||"2.20.5"}function lW(t){return t.get("QLOGIC_HUB_BASE_URL")?.trim()||t.get("XIAOZHICLAW_HUB_URL")?.trim()||"https://xiaozhi.qlogicagent.com"}function Xm(t,e){let n=t.trim().replace(/\/+$/,"");return n.endsWith("/v1")&&(n=n.slice(0,-3)),n.endsWith("/api")&&(n=n.slice(0,-4)),`${n}${e}`}function dW(t,e){let n=e?.trim();return n?(r,o)=>t(r,{...o,headers:{...o?.headers,"x-client-version":n}}):t}async function Jm(t,e,n,r,o){let i,s=o!==void 0;try{i=await t(e,{method:r,headers:{accept:"application/json",authorization:`Bearer ${n}`,...s?{"content-type":"application/json"}:{}},...s?{body:JSON.stringify(o)}:{},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Community hub is unavailable.")}if(!i.ok)throw new Error(`Community hub rejected registry request: ${i.status}${await uW(i)}`);return i.json().catch(()=>null)}async function uW(t){try{let e=(await t.text()).trim();return e?` ${e.slice(0,500)}`:""}catch{return""}}function Ss(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function OR(t){return!Ss(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 NR(t,e,n){if(!Ss(t))return null;let r=typeof t.id=="string"?t.id:"",o=typeof t.platform=="string"?t.platform:"",i=typeof t.version=="string"?t.version:"",s=typeof t.downloadUrl=="string"?t.downloadUrl:"",a=typeof t.checksum=="string"?t.checksum:"",c=typeof t.sizeBytes=="number"?t.sizeBytes:0;if(!r||r!==e||o!==n||!i||!s||!/^[a-f0-9]{64}$/.test(a)||!Number.isSafeInteger(c)||c<=0)return null;let l=t.format,d=l===void 0&&r==="officecli"?"executable":l;if(d!=="executable"&&d!=="zip"&&d!=="tar.gz")return null;let u=typeof t.entrypoint=="string"?t.entrypoint:void 0;return(d==="zip"||d==="tar.gz")&&!ER(u)||u!==void 0&&!ER(u)?null:{id:r,platform:o,version:i,downloadUrl:s,checksum:a,sizeBytes:c,format:d,...u?{entrypoint:u}:{}}}function ER(t){return!t||t.includes("\\")||t.startsWith("/")||/^[a-zA-Z]:/.test(t)?!1:t.split("/").every(n=>!!n&&n!=="."&&n!=="..")}var pW=new Set(["R0","R1","R2","R3"]),gW=new Set(["official","community"]),mW=new Set(["quarantine","trial","trusted"]),fW=new Set(["pending","approved","rejected"]);function _R(t){return typeof t=="string"&&pW.has(t)?t:null}function hW(t){return typeof t=="string"&&gW.has(t)?t:null}function yW(t){return typeof t=="string"&&mW.has(t)?t:null}function bW(t){return typeof t=="string"&&fW.has(t)?t:null}function Qm(t){if(!Ss(t))return null;let e=hW(t.sourceTier),n=yW(t.trustStage),r=bW(t.reviewStatus),o=_R(t.resourceRiskTier),i=_R(t.effectiveRiskTier);if(typeof t.id!="string"||typeof t.type!="string"||typeof t.kind!="string"||!e||!n||!r||!o||!i||typeof t.version!="string"||typeof t.checksum!="string"||typeof t.sizeBytes!="number"||typeof t.downloadUrl!="string")return null;let s=Array.isArray(t.requires)?t.requires:null,a=Array.isArray(t.dependencies)?t.dependencies:null;if(!s||!a||s.some(l=>typeof l!="string"))return null;let c=a.map(Qm);return c.some(l=>!l)?null:{id:t.id,type:t.type,kind:t.kind,sourceTier:e,trustStage:n,reviewStatus:r,resourceRiskTier:o,effectiveRiskTier:i,requires:s,dependencies:c,version:t.version,checksum:t.checksum,sizeBytes:t.sizeBytes,downloadUrl:t.downloadUrl,manifest:t.manifest,minClientVersion:typeof t.minClientVersion=="string"&&t.minClientVersion.trim()?t.minClientVersion.trim():void 0,signature:typeof t.signature=="string"&&t.signature.trim()?t.signature:null,signingKeyId:typeof t.signingKeyId=="string"&&t.signingKeyId.trim()?t.signingKeyId:null}}var Zm={enabled:!0},kW=new Set(["R2","R3"]);function LR(t,e=Zm){return kW.has(t.effectiveRiskTier)?{mode:"high-risk-ask",requiresInstallConsent:!0,requiresHighRiskConsent:!0,reason:`effectiveRiskTier=${t.effectiveRiskTier} \u9AD8\u5371,\u5FC5\u987B\u9AD8\u5371\u95EE\u4EBA`}:e.enabled?t.effectiveRiskTier==="R0"?{mode:"silent",requiresInstallConsent:!1,requiresHighRiskConsent:!1,reason:"R0 \u4F4E\u98CE\u9669 inert,\u81EA\u6CBB\u9759\u9ED8\u83B7\u53D6"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"R1 \u4F4E\u98CE\u9669\u4F46\u975E\u96F6,\u95EE\u4EBA\u4E00\u6B21"}:{mode:"ask",requiresInstallConsent:!0,requiresHighRiskConsent:!1,reason:"\u81EA\u6CBB\u9884\u7B97\u5173\u95ED,\u56DE\u9000\u663E\u5F0F\u540C\u610F"}}import{gunzipSync as qW}from"node:zlib";import{gunzipSync as RW}from"node:zlib";import*as ws from"node:fs/promises";import*as Zt from"node:path";import{createHash as UR}from"node:crypto";import{existsSync as vW}from"node:fs";import*as gt from"node:fs/promises";import*as cl from"node:path";import{Transform as nce}from"node:stream";import{pipeline as oce}from"node:stream/promises";var SW=4*1024*1024,wW=3;async function HR(t,e,n){let r=cl.join(Uo(),"cache","downloads",`${TW(e.downloadUrl)}.part`),o=0;if(vW(r)){let l=(await gt.stat(r)).size;o=l<e.sizeBytes?l:0,o===0&&await gt.rm(r,{force:!0})}let i=await jR(t,e.downloadUrl,o,$R(o,e.sizeBytes),n);if(i.whole)return await gt.rm(r,{force:!0}).catch(()=>{}),FR(i.bytes,e,n);await gt.mkdir(cl.dirname(r),{recursive:!0});let s=await gt.open(r,o>0?"r+":"w");try{if(i.bytes.length===0)throw new Error(`${n} download truncated.`);for(await s.write(i.bytes,0,i.bytes.length,o),o+=i.bytes.length;o<e.sizeBytes;){let l=await jR(t,e.downloadUrl,o,$R(o,e.sizeBytes),n);if(l.bytes.length===0)throw new Error(`${n} download truncated.`);await s.write(l.bytes,0,l.bytes.length,o),o+=l.bytes.length}}finally{await s.close()}let a=await gt.readFile(r),c=FR(a,e,n,r);return await gt.rm(r,{force:!0}).catch(()=>{}),c}function $R(t,e){return Math.min(t+SW,e)-1}function TW(t){return UR("sha256").update(t).digest("hex").slice(0,32)}async function jR(t,e,n,r,o){let i=0;for(let s=0;s<wW;s++)try{let a=await t(e,{method:"GET",headers:{range:`bytes=${n}-${r}`},signal:AbortSignal.timeout(3e4)});if(a.status===206)return{bytes:Buffer.from(await a.arrayBuffer()),whole:!1};if(a.ok)return{bytes:Buffer.from(await a.arrayBuffer()),whole:!0};i=a.status}catch{i=0}throw new Error(i?`${o} download failed: ${i}.`:`${o} download failed.`)}function FR(t,e,n,r){let o=i=>{throw r&&gt.rm(r,{force:!0}).catch(()=>{}),new Error(i)};return t.length!==e.sizeBytes&&o(`${n} size did not match registry metadata.`),UR("sha256").update(t).digest("hex")!==e.checksum&&o(`${n} checksum did not match registry metadata.`),t}var ef=64*1024*1024,tf=1024,PW=ef+tf*512+1024;async function dl(t,e,n){return HR(t,e,n)}async function BR(t,e,n){let r;try{r=RW(t,{maxOutputLength:PW})}catch(a){throw/larger than|output length|buffer too large/i.test(a instanceof Error?a.message:String(a))?new Error(`${n} expanded archive exceeds the extraction limit.`):new Error(`${n} must be a gzip-compressed tar archive.`)}let o=0,i=0,s=0;for(;o+512<=r.length;){let a=r.subarray(o,o+512);if(a.every(y=>y===0))return;let c=ll(a,0,100),l=ll(a,345,155),d=l?`${l}/${c}`:c,u=ll(a,124,12).trim(),p=Number.parseInt(u||"0",8);if(!Number.isFinite(p)||p<0)throw new Error(`${n} has an invalid tar entry size.`);let g=ll(a,156,1)||"0",m=o+512,f=m+p;if(f>r.length)throw new Error(`${n} tar entry is truncated.`);let h=xW(e,d,n);if(g==="5")await ws.mkdir(h,{recursive:!0});else if(g==="0"||g==="\0"){if(s+=1,i+=p,s>tf)throw new Error(`${n} exceeds the ${tf}-file extraction limit.`);if(i>ef)throw new Error(`${n} expanded file payload exceeds the ${ef}-byte limit.`);await ws.mkdir(Zt.dirname(h),{recursive:!0}),await ws.writeFile(h,r.subarray(m,f))}else throw new Error(`${n} may only contain regular files and directories.`);o=m+Math.ceil(p/512)*512}throw new Error(`${n} tar archive is missing an end marker.`)}function xW(t,e,n){let r=Zt.posix.normalize(e.replace(/\\/g,"/"));if(!r||r==="."||r.startsWith("../")||Zt.posix.isAbsolute(r))throw new Error(`${n} contains an unsafe path.`);let o=Zt.resolve(t,...r.split("/")),i=Zt.resolve(t);if(o!==i&&!o.startsWith(i+Zt.sep))throw new Error(`${n} contains an unsafe path.`);return o}function ll(t,e,n){let r=t.subarray(e,e+n),o=r.indexOf(0);return r.subarray(0,o===-1?r.length:o).toString("utf8")}import{createPublicKey as CW,verify as AW}from"node:crypto";function IW(t){return`id=${t.id}
374
374
  version=${t.version}
375
375
  checksum=${t.checksum}
376
376
  sizeBytes=${t.sizeBytes}`}function EW(t){return t.includes("\\n")?t.replace(/\\n/g,`
@@ -390,7 +390,7 @@ ${t.slice(-r)}`}function cG(t,e){return e?.aborted?Promise.reject(e.reason??new
390
390
  ; `);return{commandString:_G+n+s,cwdFilePath:o}},getSpawnArgs(n){return MG(n)},async getEnvironmentOverrides(n){return{QLOGICAGENT:"1",PYTHONUTF8:"1",PYTHONIOENCODING:"utf-8"}}}}function uf(t){return/(?:^|[;&|])\s*sleep\s+\d/i.test(t)?"sleep command blocks execution \u2014 use run_in_background: true":/\bwhile\s+(?:true|:|\[\s*1\s*\])\b/.test(t)?"infinite loop \u2014 use run_in_background: true or monitor tool":null}var DG=[{pattern:/\bgit\s+reset\s+--hard\b/,warning:"Note: may discard uncommitted changes"},{pattern:/\bgit\s+push\b[^;&|\n]*[ \t](--force|--force-with-lease|-f)\b/,warning:"Note: may overwrite remote history"},{pattern:/\bgit\s+clean\b(?![^;&|\n]*(?:-[a-zA-Z]*n|--dry-run))[^;&|\n]*-[a-zA-Z]*f/,warning:"Note: may permanently delete untracked files"},{pattern:/\bgit\s+checkout\s+(--\s+)?\.[ \t]*($|[;&|\n])/,warning:"Note: may discard all working tree changes"},{pattern:/\bgit\s+restore\s+(--\s+)?\.[ \t]*($|[;&|\n])/,warning:"Note: may discard all working tree changes"},{pattern:/\bgit\s+stash[ \t]+(drop|clear)\b/,warning:"Note: may permanently remove stashed changes"},{pattern:/\bgit\s+branch\s+(-D[ \t]|--delete\s+--force|--force\s+--delete)\b/,warning:"Note: may force-delete a branch"},{pattern:/\bgit\s+(commit|push|merge)\b[^;&|\n]*--no-verify\b/,warning:"Note: may skip safety hooks"},{pattern:/\bgit\s+commit\b[^;&|\n]*--amend\b/,warning:"Note: may rewrite the last commit"},{pattern:/(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*[rR][a-zA-Z]*f|(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*f[a-zA-Z]*[rR]/,warning:"Note: may recursively force-remove files"},{pattern:/(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*[rR]/,warning:"Note: may recursively remove files"},{pattern:/(^|[;&|\n]\s*)rm\s+-[a-zA-Z]*f/,warning:"Note: may force-remove files"},{pattern:/\b(DROP|TRUNCATE)\s+(TABLE|DATABASE|SCHEMA)\b/i,warning:"Note: may drop or truncate database objects"},{pattern:/\bDELETE\s+FROM\s+\w+[ \t]*(;|"|'|\n|$)/i,warning:"Note: may delete all rows from a database table"},{pattern:/\bkubectl\s+delete\b/,warning:"Note: may delete Kubernetes resources"},{pattern:/\bterraform\s+destroy\b/,warning:"Note: may destroy Terraform infrastructure"}],OG=[{pattern:/(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Recurse\b[^|;&\n}]*-Force\b/i,warning:"Note: may recursively force-remove files"},{pattern:/(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Force\b[^|;&\n}]*-Recurse\b/i,warning:"Note: may recursively force-remove files"},{pattern:/(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Recurse\b/i,warning:"Note: may recursively remove files"},{pattern:/(?:^|[|;&\n({])\s*(Remove-Item|rm|del|rd|rmdir|ri)\b[^|;&\n}]*-Force\b/i,warning:"Note: may force-remove files"},{pattern:/\bClear-Content\b[^|;&\n]*\*/i,warning:"Note: may clear content of multiple files"},{pattern:/\bFormat-Volume\b/i,warning:"Note: may format a disk volume"},{pattern:/\bClear-Disk\b/i,warning:"Note: may clear a disk"},{pattern:/\bgit\s+reset\s+--hard\b/i,warning:"Note: may discard uncommitted changes"},{pattern:/\bgit\s+push\b[^|;&\n]*\s+(--force|--force-with-lease|-f)\b/i,warning:"Note: may overwrite remote history"},{pattern:/\bgit\s+clean\b(?![^|;&\n]*(?:-[a-zA-Z]*n|--dry-run))[^|;&\n]*-[a-zA-Z]*f/i,warning:"Note: may permanently delete untracked files"},{pattern:/\bgit\s+stash\s+(drop|clear)\b/i,warning:"Note: may permanently remove stashed changes"},{pattern:/\b(DROP|TRUNCATE)\s+(TABLE|DATABASE|SCHEMA)\b/i,warning:"Note: may drop or truncate database objects"},{pattern:/\bStop-Computer\b/i,warning:"Note: will shut down the computer"},{pattern:/\bRestart-Computer\b/i,warning:"Note: will restart the computer"},{pattern:/\bClear-RecycleBin\b/i,warning:"Note: permanently deletes recycled files"}];function Rs(t){for(let{pattern:e,warning:n}of DG)if(e.test(t))return n;return null}function Ps(t){for(let{pattern:e,warning:n}of OG)if(e.test(t))return n;return null}var NG=t=>({isError:t!==0,message:t!==0?`Command failed with exit code ${t}`:void 0}),LG=new Map([["grep",t=>({isError:t>=2,message:t===1?"No matches found":void 0})],["rg",t=>({isError:t>=2,message:t===1?"No matches found":void 0})],["egrep",t=>({isError:t>=2,message:t===1?"No matches found":void 0})],["fgrep",t=>({isError:t>=2,message:t===1?"No matches found":void 0})],["ag",t=>({isError:t>=2,message:t===1?"No matches found":void 0})],["find",t=>({isError:t>=2,message:t===1?"Some directories were inaccessible":void 0})],["diff",t=>({isError:t>=2,message:t===1?"Files differ":void 0})],["test",t=>({isError:t>=2,message:t===1?"Condition is false":void 0})],["[",t=>({isError:t>=2,message:t===1?"Condition is false":void 0})],["cmp",t=>({isError:t>=2,message:t===1?"Files differ":void 0})]]);function $G(t){let e=t.trim(),n=e.split(/\s*\|\s*/);return(n[n.length-1]??e).trim().split(/\s+/)[0]??""}function pf(t,e,n,r){let o=$G(t);return(LG.get(o)??NG)(e,n,r)}import{execFile as jG}from"node:child_process";var gf=137,mf=143,FG=2e3,UG=250,HG=5e3,ff=5*1024*1024*1024,yl=class{#e;#n;#o;#i=!1;constructor(e,n,r){this.#e=e,this.#n=n,this.#o=r,e.setEncoding("utf-8"),e.on("data",this.#t)}#t=e=>{let n=typeof e=="string"?e:e.toString();this.#o?this.#n.writeStderr(n):this.#n.writeStdout(n)};cleanup(){this.#i||(this.#i=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#n=null)}},hf=class t{#e="running";#n;#o;#i;#t;#s=null;#r=null;#u=!1;#v;#c;#p;#h;#S;#g=null;#m=null;#l=null;#f;#d=null;#y=!1;taskOutput;result;onTimeout;constructor(e,n,r,o,i=!1,s=ff){this.#t=e,this.#c=n,this.#h=r,this.#S=i,this.#v=s,this.taskOutput=o,this.#i=e.stderr?new yl(e.stderr,o,!0):null,this.#o=e.stdout?new yl(e.stdout,o,!1):null,i&&(this.onTimeout=a=>{this.#p=a}),this.result=this.#A()}get status(){return this.#e}static#T(e){e.#S&&e.#p?e.#p(e.background.bind(e)):e.#k(mf)}#R(){this.#c.reason!=="interrupt"&&this.kill()}#P(e,n){this.#y=!0;let r=this.#f??e??(n==="SIGTERM"?144:1);if(this.#d){this.#d.then(()=>this.#a(r));return}this.#a(r)}#x(e){if(e){let n=e.code==="ENOENT",r=n?`shell not found: ${e.path??"(unknown)"} \u2014 install the shell or set QLOGICAGENT_SHELL / QLOGICAGENT_POWERSHELL_PATH / QLOGICAGENT_BASH_PATH to a working interpreter`:`failed to start shell process: ${e.message}`;this.taskOutput.writeStderr(r),this.#a(n?127:1);return}this.#a(1)}#a(e){this.#m&&(this.#m(e),this.#m=null)}#b(){this.#w(),this.#s&&(clearTimeout(this.#s),this.#s=null),this.#l&&(this.#c.removeEventListener("abort",this.#l),this.#l=null)}#w(){this.#r&&(clearInterval(this.#r),this.#r=null)}#C(){this.#r=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(n=>{n.size>this.#v&&this.#e==="backgrounded"&&this.#r!==null&&(this.#u=!0,this.#w(),this.#k(gf))},()=>{}))},HG),this.#r.unref?.()}#A(){this.#l=this.#R.bind(this),this.#c.addEventListener("abort",this.#l,{once:!0}),this.#t.once("exit",this.#P.bind(this)),this.#t.once("error",this.#x.bind(this)),this.#s=setTimeout(t.#T,this.#h,this);let e=new Promise(n=>{this.#m=n});return new Promise(n=>{this.#g=n,e.then(this.#I.bind(this))})}async#I(e){this.#b(),(this.#e==="running"||this.#e==="backgrounded")&&(this.#e="completed");let n=await this.taskOutput.getStdout(),r={code:e,stdout:n,stderr:this.taskOutput.getStderr(),interrupted:e===gf||e===mf,backgroundTaskId:this.#n};this.taskOutput.stdoutToFile&&!this.#n&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(r.outputFilePath=this.taskOutput.path,r.outputFileSize=this.taskOutput.outputFileSize)),this.#u?r.stderr=`Background command killed: output file exceeded ${ff} bytes. ${r.stderr}`:e===mf&&(r.stderr=`Command timed out after ${this.#h}ms. ${r.stderr}`),this.#g&&(this.#g(r),this.#g=null)}#k(e){if(this.#e==="completed"||this.#d)return;this.#e="killed",this.#f=e??gf;let n=this.#t.pid;if(n)try{if(process.platform==="win32"){this.#d=this.#E(n),this.#d.then(()=>this.#a(this.#f));return}else try{process.kill(-n,"SIGKILL")}catch{try{process.kill(n,"SIGKILL")}catch{}}}catch{try{this.#t.kill("SIGKILL")}catch{}}this.#a(this.#f)}#E(e){return new Promise(r=>{let o=i=>{if(i)try{this.#t.kill("SIGKILL")}catch{}r()};try{jG("taskkill",["/PID",String(e),"/T","/F"],{windowsHide:!0,timeout:FG},i=>o(i))}catch(i){o(i instanceof Error?i:new Error(String(i)))}}).then(()=>this.#_())}#_(){return this.#y?Promise.resolve():new Promise(e=>{let n=!1,r=()=>{n||(n=!0,clearTimeout(i),this.#t.removeListener("exit",o),e())},o=()=>r(),i=setTimeout(r,UG);this.#t.once("exit",o),this.#y&&r()})}kill(){this.#k()}background(e){return this.#e==="running"?(this.#n=e,this.#e="backgrounded",this.#b(),this.taskOutput.stdoutToFile?this.#C():this.taskOutput.spillToDisk(),!0):!1}cleanup(){this.#o?.cleanup(),this.#i?.cleanup(),this.taskOutput.clear(),this.#b(),this.#t=null,this.#c=null,this.#p=void 0}};function yf(t,e,n,r,o=!1,i=ff){return new hf(t,e,n,r,o,i)}function bl(t,e){let n=new Vn(Vr("local_bash"));return{status:"killed",result:Promise.resolve({code:e?.code??145,stdout:"",stderr:e?.stderr??"Command aborted before execution",interrupted:!0,backgroundTaskId:t}),taskOutput:n,background:()=>!1,kill:()=>{},cleanup:()=>{}}}function bf(t){let e=new Vn(Vr("local_bash"));return{status:"completed",result:Promise.resolve({code:1,stdout:"",stderr:t,interrupted:!1,preSpawnError:t}),taskOutput:e,background:()=>!1,kill:()=>{},cleanup:()=>{}}}var BG=new Set(["API_KEY","ANTHROPIC_API_KEY","OPENAI_API_KEY","DEEPSEEK_API_KEY","DOUBAO_API_KEY","MINIMAX_API_KEY","GLM_API_KEY","KIMI_API_KEY","QWEN_API_KEY","MOONSHOT_API_KEY","ZHIPU_API_KEY","BAICHUAN_API_KEY","VOLCENGINE_API_KEY","QLOGIC_LLMROUTER_ACCESS_TOKEN","QLOGIC_LLMROUTER_REFRESH_TOKEN","QLOGIC_LLMROUTER_INFERENCE_KEY","XIAOZHICLAW_RUNTIME_SESSION_URL","XIAOZHICLAW_RUNTIME_SESSION_BEARER","XIAOZHICLAW_RUNTIME_CONVERSATION_ID","XIAOZHICLAW_RUNTIME_CREDENTIAL_SUBJECT","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","GOOGLE_APPLICATION_CREDENTIALS","AZURE_CLIENT_SECRET","AZURE_CLIENT_ID","AZURE_TENANT_ID","ACTIONS_ID_TOKEN_REQUEST_TOKEN","ACTIONS_RUNTIME_TOKEN","GITHUB_TOKEN","GH_TOKEN","GITLAB_TOKEN","CI_JOB_TOKEN","DATABASE_URL","REDIS_URL","REDIS_PASSWORD"]),qG=["_SECRET","_TOKEN","_PASSWORD","_CREDENTIAL","_API_KEY","SECRET_","TOKEN_","PASSWORD_","CREDENTIAL_","_AUTH_","PRIVATE_KEY"];function kf(t=process.env){let e={...t};for(let n of Object.keys(e))WG(n)&&delete e[n];return e}function WG(t){let e=t.toUpperCase();if(BG.has(e))return!0;for(let n of qG)if(e.includes(n))return!0;return!1}import{spawn as Ez}from"node:child_process";import{AsyncLocalStorage as _z}from"node:async_hooks";import{constants as wl,readFileSync as Mz,statSync as Dz,unlinkSync as Oz}from"node:fs";import{mkdir as xP,open as Nz,realpath as CP}from"node:fs/promises";import{delimiter as Lz,isAbsolute as $z,resolve as jz,win32 as Cf}from"node:path";function GG(t){return`"${t.replaceAll('"','\\"')}"`}function cP(t,e){let n=t.map(r=>` (subpath ${GG(r)})`).join(`
391
391
  `);return["(version 1)","(deny default)","(allow process-fork)","(allow process-exec*)","(allow signal (target self))","(allow sysctl-read)","(allow mach-lookup)","(allow file-read*)",'(allow file-write-data (literal "/dev/null") (literal "/dev/dtracehelper"))','(allow file-write* (subpath "/dev/tty"))','(allow file-write* (subpath "/private/tmp") (subpath "/private/var/tmp"))',t.length?`(allow file-write*
392
392
  ${n})`:"",e==="deny"?"(deny network*)":"(allow network*)",""].filter(Boolean).join(`
393
- `)}function lP(t,e,n,r,o){let i=[t];for(let s of e)i.push("--allow-write",s);return n==="deny"&&i.push("--deny-net"),i.push("--",r,...o),i}import{resolve as zG}from"node:path";function dP(t){let e=new Set,n=r=>{r&&r.trim()&&e.add(zG(r))};return n(t.workdir),t.allowedDirs.forEach(n),t.bookkeepingDirs.forEach(n),n(t.tmpDir),[...e]}function kl(t,e,n){return{wrapped:!1,bin:t,args:e,useSandbox:!1,reason:n}}function KG(t){let{platform:e,config:n,bin:r,args:o,writableRoots:i}=t;if(n.mode==="full_access")return kl(r,o,"full_access: sandbox off by design");if(e==="win32"||e==="other")return kl(r,o,`sandbox unsupported on ${e}; degrade to prompt-only`);if(e==="darwin")return n.sandboxExecAvailable?{wrapped:!0,bin:"sandbox-exec",args:["-p",cP(i,n.netPolicy),"--",r,...o],useSandbox:!0,sandboxTmpDir:n.tmpDir,reason:"macOS Seatbelt: read-all, write-scoped"}:kl(r,o,"sandbox-exec unavailable; degrade");if(!n.helperPath)return kl(r,o,"landlock helper missing; degrade to prompt-only");let s=lP(n.helperPath,i,n.netPolicy,r,o);return{wrapped:!0,bin:n.helperPath,args:s.slice(1),useSandbox:!0,sandboxTmpDir:n.tmpDir,reason:"Linux Landlock: read-all, write-scoped"}}function vf(t,e,n,r){let o=KG({platform:t,config:e,bin:n,args:r,writableRoots:dP(e)});return o.wrapped?{bin:o.bin,args:o.args,useSandbox:!0,sandboxTmpDir:o.sandboxTmpDir,reason:o.reason}:{bin:n,args:r,useSandbox:!1,reason:o.reason}}function Sf(){switch(process.platform){case"win32":return"win32";case"darwin":return"darwin";case"linux":return"linux";default:return"other"}}import*as wf from"node:path";var pP=/^[A-Za-z]:[\\/]/,gP=/^\/([A-Za-z])(?:\/|$)(.*)$/,mP=/^\/mnt\/([A-Za-z])(?:\/|$)(.*)$/;function uP(t,e){let n=e?e.replace(/\//g,"\\"):"";return wf.win32.normalize(`${t.toUpperCase()}:\\${n}`)}function en(t){let e=mP.exec(t);if(e)return uP(e[1],e[2]??"");let n=gP.exec(t);return n?uP(n[1],n[2]??""):pP.test(t)?wf.win32.normalize(t):t}function Yn(t){return pP.test(t)||gP.test(t)||mP.test(t)}import{randomBytes as SP,timingSafeEqual as ZG}from"node:crypto";import{createServer as ez}from"node:http";import{Readable as tz}from"node:stream";import{pipeline as nz}from"node:stream/promises";import{createHash as VG}from"node:crypto";var YG="QLOGIC_LLMROUTER_INFERENCE_KEY",XG="QLOGIC_LLMROUTER_BASE_URL";function hP(t,e){let n=bP(t);return n?VG("sha256").update(n).digest("hex"):e}async function yP(t,e={config:Qt(),fetch}){let n=JG(e.config),r=bP(e.config);if(!n||!r)return fP();let o={"accept-encoding":"identity",authorization:`Bearer ${r}`};t.contentType&&(o["content-type"]=t.contentType);let i=AbortSignal.any([t.signal,AbortSignal.timeout(QG(t))]),s={method:t.method,headers:o,signal:i};t.body&&(s.body=t.body,s.duplex="half");try{return await e.fetch(`${n}${t.path}`,s)}catch{if(t.signal.aborted)throw t.signal.reason??new DOMException("request aborted","AbortError");return fP()}}function bP(t){return t.get(YG)?.trim()||void 0}function JG(t){let e=t.get(XG)?.trim();if(e)try{let n=new URL(e);return n.username||n.password||n.search||n.hash||n.protocol!=="http:"&&n.protocol!=="https:"||process.env.NODE_ENV==="production"&&n.protocol!=="https:"?void 0:n.href.replace(/\/+$/,"")}catch{return}}function QG(t){return t.path==="/v1/cad/plan-grants"||t.path==="/v1/solidworks/plan-grants"?18e4:t.path==="/v1/files"&&t.method==="POST"?12e4:3e4}function fP(){return Response.json({error:{type:"runtime_proxy_error",code:"MANAGED_INFERENCE_UNAVAILABLE"}},{status:502,headers:{"cache-control":"no-store"}})}var kP=()=>{};function vP(t){kP=t}function Tf(){return kP()}var Pf="127.0.0.1",rz="/v1/runtime-session/check",wP=1,oz=16*1024,iz=5e3,sz=4*1024*1024,az=100*1024*1024,cz=["content-type","content-length","retry-after","x-request-id"],Xn=Cs({code:"HOST_SESSION_INVALID",exitCode:12,message:"\u684C\u9762\u4F1A\u8BDD\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u4ECE\u5C0F\u667AClaw\u91CD\u65B0\u6267\u884C",technicalMessage:"desktop runtime session bearer or endpoint is invalid",retryable:!1,retryMode:"restart_from_desktop"}),lz=Cs({code:"HOST_PROTOCOL_INCOMPATIBLE",exitCode:16,message:"\u684C\u9762\u4F1A\u8BDD\u534F\u8BAE\u4E0D\u517C\u5BB9\uFF0C\u8BF7\u66F4\u65B0\u5C0F\u667AClaw",technicalMessage:"desktop runtime session protocol is incompatible",retryable:!1,retryMode:"update_desktop"}),dz=Cs({code:"DESKTOP_SESSION_REQUIRED",exitCode:11,message:"\u8BF7\u4ECE\u5728\u7EBF\u7684\u5C0F\u667AClaw\u684C\u9762\u7AEF\u91CD\u65B0\u6267\u884C",technicalMessage:"desktop runtime session environment is missing",retryable:!1,retryMode:"restart_from_desktop"}),uz=Cs({code:"NETWORK_REQUIRED",exitCode:10,message:"\u9700\u8981\u8054\u7F51\u540E\u624D\u80FD\u4F7F\u7528\u6B64\u5DE5\u4E1A\u80FD\u529B",technicalMessage:"llmrouter network is unreachable",retryable:!0,retryMode:"after_network_restored"}),pz=Cs({code:"LLMROUTER_UNAVAILABLE",exitCode:15,message:"\u5728\u7EBF\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",technicalMessage:"llmrouter returned an unavailable response",retryable:!0,retryMode:"retry_later"}),Rf,vl;async function PP(t){if(gz())return Rf?Rf.childEnv(t):(vl||(vl=mz({configPort:Qt(),probeSession:async e=>{let n=Tf();if(n){if(e.aborted)throw new Error("desktop session probe aborted");let o=await n.probeSession();return new Response(null,{status:o.status})}let{response:r}=await Xc("/auth/me",{signal:e});return r}}).then(e=>(Rf=e,e)).finally(()=>{vl=void 0})),(await vl).childEnv(t))}function gz(){if(Tf())return!0;let t=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim(),e=process.env.QLOGIC_LLMROUTER_ACCESS_TOKEN?.trim();return!!(t&&e)}async function mz(t){let e=SP(32).toString("base64url"),n=SP(32).toString("hex"),r=ez((l,d)=>{hz(l,d,e,t).catch(()=>{!d.headersSent&&!d.destroyed?Ct(d,400,Xn):d.destroyed||d.destroy()})});await Iz(r);let o=r.address();if(!o||typeof o=="string")throw await RP(r),new Error("industrial runtime session server has no TCP address");let i,s=()=>{},a=()=>(i||(s(),s=()=>{},i=RP(r)),i);s=Wn(a);let c={XIAOZHICLAW_RUNTIME_SESSION_URL:`http://${Pf}:${o.port}`,XIAOZHICLAW_RUNTIME_SESSION_BEARER:e};return{childEnv:l=>({...c,...l?.trim()?{XIAOZHICLAW_RUNTIME_CONVERSATION_ID:l}:{},XIAOZHICLAW_RUNTIME_CREDENTIAL_SUBJECT:fz(t.configPort,n)}),stop:a}}function fz(t,e){return hP(t,e)}async function hz(t,e,n,r){if(!Pz(t)){t.resume(),Ct(e,404,Xn);return}if(!xz(t.headers.authorization,n)){t.resume(),Ct(e,401,Xn);return}if(t.url===rz){await yz(t,e,r.probeSession);return}let o=bz(t.url,t.method);if(!o){t.resume(),Ct(e,404,Xn);return}if(o.kind==="method-not-allowed"){t.resume(),e.setHeader("allow",o.allow),Ct(e,405,Xn);return}await kz(t,e,o.request,r)}async function yz(t,e,n){if(t.method!=="POST"){t.resume(),e.setHeader("allow","POST"),Ct(e,405,Xn);return}let r=await Cz(t);if(r.kind==="too-large"){Ct(e,413,Xn);return}let o=Az(r.value);if(!o){Ct(e,400,Xn);return}if(o.protocolVersion!==wP){Ct(e,409,lz);return}let i;try{i=await n(AbortSignal.timeout(iz))}catch{Ct(e,200,uz);return}if(i.ok){xf(e,200,{ok:!0,protocolVersion:wP});return}if(i.status===401||i.status===403){Ct(e,200,dz);return}Ct(e,503,pz)}function bz(t,e){if(t==="/v1/runtime-session/llmrouter/models")return e==="GET"?{kind:"request",request:{path:"/v1/models",method:e}}:{kind:"method-not-allowed",allow:"GET"};if(t==="/v1/runtime-session/llmrouter/files")return e==="GET"||e==="POST"?{kind:"request",request:{path:"/v1/files",method:e}}:{kind:"method-not-allowed",allow:"GET, POST"};if(t==="/v1/runtime-session/llmrouter/cad/plan-grants")return e==="POST"?{kind:"request",request:{path:"/v1/cad/plan-grants",method:e}}:{kind:"method-not-allowed",allow:"POST"};if(t==="/v1/runtime-session/llmrouter/solidworks/plan-grants")return e==="POST"?{kind:"request",request:{path:"/v1/solidworks/plan-grants",method:e}}:{kind:"method-not-allowed",allow:"POST"};let n="/v1/runtime-session/llmrouter/files/";if(!t?.startsWith(n))return;let r=t.slice(n.length);if(/^[A-Za-z0-9_-]{1,128}$/.test(r))return e==="GET"||e==="DELETE"?{kind:"request",request:{path:`/v1/files/${r}`,method:e}}:{kind:"method-not-allowed",allow:"GET, DELETE"}}async function kz(t,e,n,r){let o=new AbortController,i=()=>{o.signal.aborted||o.abort(new DOMException("client disconnected","AbortError"))},s=()=>{e.writableFinished||i()};t.once("aborted",i),e.once("close",s);try{let a=Sz(t),c=Rz(t.headers["content-length"]);if(n.method!=="POST"&&(t.headers["content-type"]!==void 0||t.headers["transfer-encoding"]!==void 0||c==="invalid"||typeof c=="number"&&c!==0)){t.resume(),xs(e,400,"REQUEST_BODY_NOT_ALLOWED");return}if(n.method==="POST"&&!wz(n.path,a)){t.resume(),xs(e,415,"UNSUPPORTED_MEDIA_TYPE");return}let l=n.path==="/v1/files"&&n.method==="POST"?az:sz;if(c==="invalid"||typeof c=="number"&&c>l){t.resume(),xs(e,413,"REQUEST_BODY_TOO_LARGE");return}let d=n.method==="POST",u=await yP({...n,...a?{contentType:a}:{},...d?{body:vz(t,l,o)}:{},signal:o.signal},{config:r.configPort,fetch:r.fetch??fetch});if(e.destroyed)return;e.statusCode=u.status;for(let m of cz){if(m==="content-length"&&u.headers.has("content-encoding"))continue;let f=u.headers.get(m);f!==null&&e.setHeader(m,f)}if(!u.body){e.end();return}let p=tz.fromWeb(u.body),g=()=>p.destroy(o.signal.reason);o.signal.addEventListener("abort",g,{once:!0});try{await nz(p,e)}finally{o.signal.removeEventListener("abort",g)}}catch(a){if(a instanceof Sl&&!e.headersSent){xs(e,413,"REQUEST_BODY_TOO_LARGE");return}if(o.signal.aborted||e.destroyed)return;e.headersSent?e.destroy():xs(e,502,"MANAGED_INFERENCE_UNAVAILABLE")}finally{t.off("aborted",i),e.off("close",s)}}var Sl=class extends Error{constructor(){super("runtime proxy request body exceeds its limit"),this.name="RequestBodyTooLargeError"}};async function*vz(t,e,n){let r=0;for await(let o of t){let i=Buffer.isBuffer(o)?o:Buffer.from(o);if(r+=i.length,r>e){let s=new Sl;throw n.abort(s),s}yield i}}function Sz(t){let e=t.headersDistinct["content-type"];return e?.length===1?e[0]:void 0}function wz(t,e){return e?t==="/v1/files"?Tz(e):t==="/v1/cad/plan-grants"||t==="/v1/solidworks/plan-grants"?/^application\/json(?:[\t ]*;[\t ]*charset[\t ]*=[\t ]*utf-8)?[\t ]*$/i.test(e):!1:!1}function Tz(t){let e=/^multipart\/form-data[\t ]*;[\t ]*boundary[\t ]*=[\t ]*(?:"([^"]*)"|([^\t ]+))[\t ]*$/i.exec(t);if(!e)return!1;let n=e[1]!==void 0,r=e[1]??e[2]??"";return r.length<1||r.length>70||!/^[ 0-9A-Za-z'()+_,./:=?-]+$/.test(r)||!/[0-9A-Za-z'()+_,./:=?-]$/.test(r)?!1:n||/^[0-9A-Za-z'+._-]+$/.test(r)}function Rz(t){if(t===void 0)return;if(!/^(0|[1-9][0-9]*)$/.test(t))return"invalid";let e=Number(t);return Number.isSafeInteger(e)?e:"invalid"}function xs(t,e,n){xf(t,e,{error:{type:"runtime_proxy_error",code:n}})}function Pz(t){let e=t.socket.localPort;return e!==void 0&&t.headers.host===`${Pf}:${e}`}function xz(t,e){if(!t?.startsWith("Bearer "))return!1;let n=Buffer.from(t.slice(7)),r=Buffer.from(e);return n.length===r.length&&ZG(n,r)}function Cz(t){return new Promise((e,n)=>{let r=[],o=0,i=!1;t.on("data",s=>{if(o+=s.length,o>oz){i=!0,r.length=0;return}i||r.push(s)}),t.on("end",()=>{e(i?{kind:"too-large"}:{kind:"body",value:Buffer.concat(r).toString("utf8")})}),t.on("error",n)})}function Az(t){let e;try{e=JSON.parse(t)}catch{return}if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,r=new Set(["protocolVersion","runtimeId","runtimeVersion","taskId","planSha256"]);if(!Object.keys(n).some(o=>!r.has(o))&&Number.isInteger(n.protocolVersion)&&!(typeof n.runtimeId!="string"||typeof n.runtimeVersion!="string")&&!(!TP(n.taskId)||!TP(n.planSha256)))return n}function TP(t){return t==null||typeof t=="string"}function Ct(t,e,n){xf(t,e,{ok:!1,error:n})}function xf(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json; charset=utf-8"),t.setHeader("cache-control","no-store"),t.end(JSON.stringify(n))}function Cs(t){return{type:"error",status:"failed",error:{code:t.code,exitCode:t.exitCode,message:t.message,technicalMessage:t.technicalMessage,stage:"desktop_session_check",retryable:t.retryable,safeToRetry:!0,retryMode:t.retryMode,action:t.message},completedSteps:[],pendingSteps:[],partialArtifacts:[]}}function Iz(t){return new Promise((e,n)=>{let r=i=>{t.off("listening",o),n(i)},o=()=>{t.off("error",r),e()};t.once("error",r),t.once("listening",o),t.listen(0,Pf)})}function RP(t){return new Promise((e,n)=>{t.close(r=>{if(r&&r.code!=="ERR_SERVER_NOT_RUNNING"){n(r);return}e()}),t.closeAllConnections()})}var Fz=1800*1e3,Tl=process.cwd(),AP=process.cwd(),As=new _z;function mt(){return As.getStore()?.cwd??Tl}function Af(t,e,n){let r=en(t),o=en(e||mt()),i=Yn(r)||Yn(o)?Cf.isAbsolute(r)?Cf.normalize(r):Cf.resolve(o,r):$z(r)?r:jz(o,r);if(n?.mustExist)try{if(!Dz(i).isDirectory())return!1}catch{return!1}let s=As.getStore();return s?s.cwd=i:Tl=i,!0}function Rl(){return As.getStore()?.originalCwd??AP}function Jo(t){let e=en(t);Tl=e,AP=Tl;let n=As.getStore();n&&(n.cwd=e,n.originalCwd=e)}function Ef(t,e){let n=en(t);return As.run({cwd:n,originalCwd:n},e)}var If=null;function Is(t){If={provider:t}}function _f(){if(!If)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return If.provider}function Mf(){let t;try{t=_f()}catch{return}return{type:t.type,shellPath:t.shellPath,...t.psEdition?{psEdition:t.psEdition}:{},...t.isGitBashOnWindows?{isGitBashOnWindows:!0}:{}}}async function Uz(t,e=async()=>[],n){let r=await PP(n),o=await e(),i=kf({...process.env,GIT_EDITOR:"true",QLOGICAGENT:"1",...t});return o.length>0&&(i.PATH=[...o,...i.PATH?[i.PATH]:[]].join(Lz)),{...i,...r}}async function Pl(t,e,n,r){let{timeout:o,preventCwdChanges:i,shouldAutoBackground:s,onStdout:a,cwd:c}=r??{},l=o||Fz,d=n??sf(),u=_f(),p=cf(),g=r?.sandbox,m=g?vf(Sf(),g,u.shellPath,[]):void 0,{commandString:f,cwdFilePath:h}=await u.buildExecCommand(t,{id:p,useSandbox:m?.useSandbox??!1,sandboxTmpDir:m?.useSandbox?m.sandboxTmpDir:void 0}),y=f,b=c??mt();try{await CP(b)}catch{let D=Rl();try{await CP(D),Af(D),b=D}catch{return bf(`Working directory "${b}" no longer exists.`)}}if(e.aborted)return bl();let P=u.shellPath,w=u.getSpawnArgs(y);if(g&&m?.useSandbox){let D=vf(Sf(),g,P,w);P=D.bin,w=D.args,D.sandboxTmpDir&&await xP(D.sandboxTmpDir,{recursive:!0})}let C=await u.getEnvironmentOverrides(t),A=await Uz(C,r?.resolveRuntimePathEntries,r?.sessionId),v=!!a,x=Vr("local_bash"),I=new Vn(x,!v);await xP(no(),{recursive:!0});let M;if(!v){let D=wl.O_NOFOLLOW??0;M=await Nz(I.path,process.platform==="win32"?"w":wl.O_WRONLY|wl.O_CREAT|wl.O_APPEND|D)}try{let D=Ez(P,w,{env:A,cwd:b,stdio:v?["pipe","pipe","pipe"]:["pipe",M?.fd,M?.fd],detached:u.detached,windowsHide:!0}),H=yf(D,e,l,I,s);if(M!==void 0)try{await M.close()}catch{}return D.stdout&&a&&D.stdout.on("data",K=>{a(typeof K=="string"?K:K.toString())}),h&&H.result.then(K=>{if(K&&!i&&!K.backgroundTaskId){try{let X=Mz(h,{encoding:"utf8"}).trim();X&&X.normalize("NFC")!==b&&Af(X,b,{mustExist:!0})}catch{}try{Oz(h)}catch{}}}),H}catch(D){if(M!==void 0)try{await M.close()}catch{}return I.clear(),bl(void 0,{code:126,stderr:D instanceof Error?D.message:String(D)})}}var Qo="image_generate",Df={type:"object",properties:{prompt:{type:"string",description:"Image generation prompt. Enrich vague requests with style, lighting, composition, color, mood details."},purpose:{type:"string",description:"Intended use: 'social-media', 'short-video-cover', 'phone-wallpaper', 'avatar', 'poster', etc."},style:{type:"string",description:"Visual art style: 'photorealistic', 'anime', 'watercolor', 'oil-painting', '3d-render', etc."},size:{type:"string",description:"Dimensions. Model-dependent: Seedream (doubao-seedream-*) accepts ONLY named '2K'/'4K' \u2014 never pixel sizes. Other models take pixels, e.g. '1024x1792' (portrait), '1792x1024' (landscape), '1024x1024' (square). Omit to use the model's default."},image_url:{type:"string",description:"Reference image URL for image-to-image generation (img2img). Character reference sheet or style transfer. MUST be a publicly accessible HTTP/HTTPS URL. Local file paths and data: URLs are NOT supported."},output_path:{type:"string",description:"Optional absolute or workspace-relative path where the generated image should be saved. Use only for a single generated image."},output_paths:{type:"array",items:{type:"string"},description:"Optional absolute or workspace-relative paths where generated images should be saved. Must match the number of generated images."},n:{type:"number",description:"Number of images to generate (1-4). Default: 1."},quality:{type:"string",description:"Image quality level: 'auto', 'high', 'low', 'hd'. Provider-specific."},seed:{type:"number",description:"Random seed for reproducible generation. Same seed + prompt = same result."}},required:["prompt"]};function IP(t){return{name:Qo,label:"Image Generate",description:"Generate images from a text prompt. You MUST enrich vague prompts with details about style, lighting, composition, color, and mood before calling. Supports img2img via image_url reference. All generated images are saved locally and can be viewed immediately. IMPORTANT: For ordinary creative requests, infer reasonable defaults for purpose, style, and size and call this tool directly. Use ask_user only when a missing detail is critical or the request is genuinely ambiguous (e.g. the user asks for a production ad with unspecified brand constraints). Infer image size automatically from purpose (e.g. 1024x1792 for phone wallpaper, 1792x1024 for landscape poster, 1024x1024 for avatar/social). Do NOT expose size as a raw number to the user. The generated image is ALREADY displayed to the user by the app from this tool's result \u2014 do NOT re-embed it, and NEVER write a Markdown image that points at a local filesystem path or saved file location (a local path renders as a broken image). Do NOT invent Markdown image URLs, placeholder attachment paths, or claim an image was generated without this tool returning mediaUrls. When the user asks for generated image files at specific workspace paths, pass output_path/output_paths so the files are actually saved there. ALL reference image URLs MUST be publicly accessible HTTP/HTTPS URLs. Use file_upload tool first if the user provides a local file. Local file paths and data: URIs are NOT supported by the generation API.",parameters:Df,isEgress:!0,egressCarriesData:!1,execute:async(e,n)=>{let r=await t.generateImage({prompt:n.prompt,purpose:n.purpose,style:n.style,size:n.size,imageUrl:n.image_url,n:n.n,quality:n.quality,seed:n.seed}),o=r.mediaUrls.length,i=Bz(n);if(i.length>0&&i.length!==o)return{content:[{type:"text",text:`Error: output_paths length (${i.length}) must match generated image count (${o}).`}],details:{type:"image_generate",model:r.model,size:r.size,durationMs:r.durationMs,mediaUrls:r.mediaUrls,error:"output_path_count_mismatch"}};let s=[],a=[];if(i.length>0){if(!t.saveGeneratedImages)return{content:[{type:"text",text:"Error: this host does not support saving generated images to explicit output paths."}],details:{type:"image_generate",model:r.model,size:r.size,durationMs:r.durationMs,mediaUrls:r.mediaUrls,error:"output_path_unsupported"}};a=await t.saveGeneratedImages({mediaUrls:r.mediaUrls,outputPaths:i}),s=a.map(u=>u.localPath)}let c=s.length===0?"":`
393
+ `)}function lP(t,e,n,r,o){let i=[t];for(let s of e)i.push("--allow-write",s);return n==="deny"&&i.push("--deny-net"),i.push("--",r,...o),i}import{resolve as zG}from"node:path";function dP(t){let e=new Set,n=r=>{r&&r.trim()&&e.add(zG(r))};return n(t.workdir),t.allowedDirs.forEach(n),t.bookkeepingDirs.forEach(n),n(t.tmpDir),[...e]}function kl(t,e,n){return{wrapped:!1,bin:t,args:e,useSandbox:!1,reason:n}}function KG(t){let{platform:e,config:n,bin:r,args:o,writableRoots:i}=t;if(n.mode==="full_access")return kl(r,o,"full_access: sandbox off by design");if(e==="win32"||e==="other")return kl(r,o,`sandbox unsupported on ${e}; degrade to prompt-only`);if(e==="darwin")return n.sandboxExecAvailable?{wrapped:!0,bin:"sandbox-exec",args:["-p",cP(i,n.netPolicy),"--",r,...o],useSandbox:!0,sandboxTmpDir:n.tmpDir,reason:"macOS Seatbelt: read-all, write-scoped"}:kl(r,o,"sandbox-exec unavailable; degrade");if(!n.helperPath)return kl(r,o,"landlock helper missing; degrade to prompt-only");let s=lP(n.helperPath,i,n.netPolicy,r,o);return{wrapped:!0,bin:n.helperPath,args:s.slice(1),useSandbox:!0,sandboxTmpDir:n.tmpDir,reason:"Linux Landlock: read-all, write-scoped"}}function vf(t,e,n,r){let o=KG({platform:t,config:e,bin:n,args:r,writableRoots:dP(e)});return o.wrapped?{bin:o.bin,args:o.args,useSandbox:!0,sandboxTmpDir:o.sandboxTmpDir,reason:o.reason}:{bin:n,args:r,useSandbox:!1,reason:o.reason}}function Sf(){switch(process.platform){case"win32":return"win32";case"darwin":return"darwin";case"linux":return"linux";default:return"other"}}import*as wf from"node:path";var pP=/^[A-Za-z]:[\\/]/,gP=/^\/([A-Za-z])(?:\/|$)(.*)$/,mP=/^\/mnt\/([A-Za-z])(?:\/|$)(.*)$/;function uP(t,e){let n=e?e.replace(/\//g,"\\"):"";return wf.win32.normalize(`${t.toUpperCase()}:\\${n}`)}function en(t){let e=mP.exec(t);if(e)return uP(e[1],e[2]??"");let n=gP.exec(t);return n?uP(n[1],n[2]??""):pP.test(t)?wf.win32.normalize(t):t}function Yn(t){return pP.test(t)||gP.test(t)||mP.test(t)}import{randomBytes as SP,timingSafeEqual as ZG}from"node:crypto";import{createServer as ez}from"node:http";import{Readable as tz}from"node:stream";import{pipeline as nz}from"node:stream/promises";import{createHash as VG}from"node:crypto";var YG="QLOGIC_LLMROUTER_INFERENCE_KEY",XG="QLOGIC_LLMROUTER_BASE_URL";function hP(t,e){let n=bP(t);return n?VG("sha256").update(n).digest("hex"):e}async function yP(t,e={config:Qt(),fetch}){let n=JG(e.config),r=bP(e.config);if(!n||!r)return fP();let o={"accept-encoding":"identity",authorization:`Bearer ${r}`};t.contentType&&(o["content-type"]=t.contentType);let i=AbortSignal.any([t.signal,AbortSignal.timeout(QG(t))]),s={method:t.method,headers:o,signal:i};t.body&&(s.body=t.body,s.duplex="half");try{return await e.fetch(`${n}${t.path}`,s)}catch{if(t.signal.aborted)throw t.signal.reason??new DOMException("request aborted","AbortError");return fP()}}function bP(t){return t.get(YG)?.trim()||void 0}function JG(t){let e=t.get(XG)?.trim();if(e)try{let n=new URL(e);return n.username||n.password||n.search||n.hash||n.protocol!=="http:"&&n.protocol!=="https:"||process.env.NODE_ENV==="production"&&n.protocol!=="https:"?void 0:n.href.replace(/\/+$/,"")}catch{return}}function QG(t){return t.path==="/v1/cad/plan-grants"||t.path==="/v1/solidworks/plan-grants"?18e4:t.path==="/v1/files"&&t.method==="POST"?12e4:3e4}function fP(){return Response.json({error:{type:"runtime_proxy_error",code:"MANAGED_INFERENCE_UNAVAILABLE"}},{status:502,headers:{"cache-control":"no-store"}})}var kP=()=>{};function vP(t){kP=t}function Tf(){return kP()}var Pf="127.0.0.1",rz="/v1/runtime-session/check",wP=1,oz=16*1024,iz=5e3,sz=4*1024*1024,az=100*1024*1024,cz=["content-type","content-length","retry-after","x-request-id"],Xn=Cs({code:"HOST_SESSION_INVALID",exitCode:12,message:"\u684C\u9762\u4F1A\u8BDD\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u4ECE\u5C0F\u667AClaw\u91CD\u65B0\u6267\u884C",technicalMessage:"desktop runtime session bearer or endpoint is invalid",retryable:!1,retryMode:"restart_from_desktop"}),lz=Cs({code:"HOST_PROTOCOL_INCOMPATIBLE",exitCode:16,message:"\u684C\u9762\u4F1A\u8BDD\u534F\u8BAE\u4E0D\u517C\u5BB9\uFF0C\u8BF7\u66F4\u65B0\u5C0F\u667AClaw",technicalMessage:"desktop runtime session protocol is incompatible",retryable:!1,retryMode:"update_desktop"}),dz=Cs({code:"DESKTOP_SESSION_REQUIRED",exitCode:11,message:"\u8BF7\u4ECE\u5728\u7EBF\u7684\u5C0F\u667AClaw\u684C\u9762\u7AEF\u91CD\u65B0\u6267\u884C",technicalMessage:"desktop runtime session environment is missing",retryable:!1,retryMode:"restart_from_desktop"}),uz=Cs({code:"NETWORK_REQUIRED",exitCode:10,message:"\u9700\u8981\u8054\u7F51\u540E\u624D\u80FD\u4F7F\u7528\u6B64\u5DE5\u4E1A\u80FD\u529B",technicalMessage:"llmrouter network is unreachable",retryable:!0,retryMode:"after_network_restored"}),pz=Cs({code:"LLMROUTER_UNAVAILABLE",exitCode:15,message:"\u5728\u7EBF\u670D\u52A1\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",technicalMessage:"llmrouter returned an unavailable response",retryable:!0,retryMode:"retry_later"}),Rf,vl;async function PP(t){if(gz())return Rf?Rf.childEnv(t):(vl||(vl=mz({configPort:Qt(),probeSession:async e=>{let n=Tf();if(n){if(e.aborted)throw new Error("desktop session probe aborted");let o=await n.probeSession();return new Response(null,{status:o.status})}return await Xc("/auth/me",{signal:e})}}).then(e=>(Rf=e,e)).finally(()=>{vl=void 0})),(await vl).childEnv(t))}function gz(){if(Tf())return!0;let t=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim(),e=process.env.QLOGIC_LLMROUTER_ACCESS_TOKEN?.trim();return!!(t&&e)}async function mz(t){let e=SP(32).toString("base64url"),n=SP(32).toString("hex"),r=ez((l,d)=>{hz(l,d,e,t).catch(()=>{!d.headersSent&&!d.destroyed?Ct(d,400,Xn):d.destroyed||d.destroy()})});await Iz(r);let o=r.address();if(!o||typeof o=="string")throw await RP(r),new Error("industrial runtime session server has no TCP address");let i,s=()=>{},a=()=>(i||(s(),s=()=>{},i=RP(r)),i);s=Wn(a);let c={XIAOZHICLAW_RUNTIME_SESSION_URL:`http://${Pf}:${o.port}`,XIAOZHICLAW_RUNTIME_SESSION_BEARER:e};return{childEnv:l=>({...c,...l?.trim()?{XIAOZHICLAW_RUNTIME_CONVERSATION_ID:l}:{},XIAOZHICLAW_RUNTIME_CREDENTIAL_SUBJECT:fz(t.configPort,n)}),stop:a}}function fz(t,e){return hP(t,e)}async function hz(t,e,n,r){if(!Pz(t)){t.resume(),Ct(e,404,Xn);return}if(!xz(t.headers.authorization,n)){t.resume(),Ct(e,401,Xn);return}if(t.url===rz){await yz(t,e,r.probeSession);return}let o=bz(t.url,t.method);if(!o){t.resume(),Ct(e,404,Xn);return}if(o.kind==="method-not-allowed"){t.resume(),e.setHeader("allow",o.allow),Ct(e,405,Xn);return}await kz(t,e,o.request,r)}async function yz(t,e,n){if(t.method!=="POST"){t.resume(),e.setHeader("allow","POST"),Ct(e,405,Xn);return}let r=await Cz(t);if(r.kind==="too-large"){Ct(e,413,Xn);return}let o=Az(r.value);if(!o){Ct(e,400,Xn);return}if(o.protocolVersion!==wP){Ct(e,409,lz);return}let i;try{i=await n(AbortSignal.timeout(iz))}catch{Ct(e,200,uz);return}if(i.ok){xf(e,200,{ok:!0,protocolVersion:wP});return}if(i.status===401||i.status===403){Ct(e,200,dz);return}Ct(e,503,pz)}function bz(t,e){if(t==="/v1/runtime-session/llmrouter/models")return e==="GET"?{kind:"request",request:{path:"/v1/models",method:e}}:{kind:"method-not-allowed",allow:"GET"};if(t==="/v1/runtime-session/llmrouter/files")return e==="GET"||e==="POST"?{kind:"request",request:{path:"/v1/files",method:e}}:{kind:"method-not-allowed",allow:"GET, POST"};if(t==="/v1/runtime-session/llmrouter/cad/plan-grants")return e==="POST"?{kind:"request",request:{path:"/v1/cad/plan-grants",method:e}}:{kind:"method-not-allowed",allow:"POST"};if(t==="/v1/runtime-session/llmrouter/solidworks/plan-grants")return e==="POST"?{kind:"request",request:{path:"/v1/solidworks/plan-grants",method:e}}:{kind:"method-not-allowed",allow:"POST"};let n="/v1/runtime-session/llmrouter/files/";if(!t?.startsWith(n))return;let r=t.slice(n.length);if(/^[A-Za-z0-9_-]{1,128}$/.test(r))return e==="GET"||e==="DELETE"?{kind:"request",request:{path:`/v1/files/${r}`,method:e}}:{kind:"method-not-allowed",allow:"GET, DELETE"}}async function kz(t,e,n,r){let o=new AbortController,i=()=>{o.signal.aborted||o.abort(new DOMException("client disconnected","AbortError"))},s=()=>{e.writableFinished||i()};t.once("aborted",i),e.once("close",s);try{let a=Sz(t),c=Rz(t.headers["content-length"]);if(n.method!=="POST"&&(t.headers["content-type"]!==void 0||t.headers["transfer-encoding"]!==void 0||c==="invalid"||typeof c=="number"&&c!==0)){t.resume(),xs(e,400,"REQUEST_BODY_NOT_ALLOWED");return}if(n.method==="POST"&&!wz(n.path,a)){t.resume(),xs(e,415,"UNSUPPORTED_MEDIA_TYPE");return}let l=n.path==="/v1/files"&&n.method==="POST"?az:sz;if(c==="invalid"||typeof c=="number"&&c>l){t.resume(),xs(e,413,"REQUEST_BODY_TOO_LARGE");return}let d=n.method==="POST",u=await yP({...n,...a?{contentType:a}:{},...d?{body:vz(t,l,o)}:{},signal:o.signal},{config:r.configPort,fetch:r.fetch??fetch});if(e.destroyed)return;e.statusCode=u.status;for(let m of cz){if(m==="content-length"&&u.headers.has("content-encoding"))continue;let f=u.headers.get(m);f!==null&&e.setHeader(m,f)}if(!u.body){e.end();return}let p=tz.fromWeb(u.body),g=()=>p.destroy(o.signal.reason);o.signal.addEventListener("abort",g,{once:!0});try{await nz(p,e)}finally{o.signal.removeEventListener("abort",g)}}catch(a){if(a instanceof Sl&&!e.headersSent){xs(e,413,"REQUEST_BODY_TOO_LARGE");return}if(o.signal.aborted||e.destroyed)return;e.headersSent?e.destroy():xs(e,502,"MANAGED_INFERENCE_UNAVAILABLE")}finally{t.off("aborted",i),e.off("close",s)}}var Sl=class extends Error{constructor(){super("runtime proxy request body exceeds its limit"),this.name="RequestBodyTooLargeError"}};async function*vz(t,e,n){let r=0;for await(let o of t){let i=Buffer.isBuffer(o)?o:Buffer.from(o);if(r+=i.length,r>e){let s=new Sl;throw n.abort(s),s}yield i}}function Sz(t){let e=t.headersDistinct["content-type"];return e?.length===1?e[0]:void 0}function wz(t,e){return e?t==="/v1/files"?Tz(e):t==="/v1/cad/plan-grants"||t==="/v1/solidworks/plan-grants"?/^application\/json(?:[\t ]*;[\t ]*charset[\t ]*=[\t ]*utf-8)?[\t ]*$/i.test(e):!1:!1}function Tz(t){let e=/^multipart\/form-data[\t ]*;[\t ]*boundary[\t ]*=[\t ]*(?:"([^"]*)"|([^\t ]+))[\t ]*$/i.exec(t);if(!e)return!1;let n=e[1]!==void 0,r=e[1]??e[2]??"";return r.length<1||r.length>70||!/^[ 0-9A-Za-z'()+_,./:=?-]+$/.test(r)||!/[0-9A-Za-z'()+_,./:=?-]$/.test(r)?!1:n||/^[0-9A-Za-z'+._-]+$/.test(r)}function Rz(t){if(t===void 0)return;if(!/^(0|[1-9][0-9]*)$/.test(t))return"invalid";let e=Number(t);return Number.isSafeInteger(e)?e:"invalid"}function xs(t,e,n){xf(t,e,{error:{type:"runtime_proxy_error",code:n}})}function Pz(t){let e=t.socket.localPort;return e!==void 0&&t.headers.host===`${Pf}:${e}`}function xz(t,e){if(!t?.startsWith("Bearer "))return!1;let n=Buffer.from(t.slice(7)),r=Buffer.from(e);return n.length===r.length&&ZG(n,r)}function Cz(t){return new Promise((e,n)=>{let r=[],o=0,i=!1;t.on("data",s=>{if(o+=s.length,o>oz){i=!0,r.length=0;return}i||r.push(s)}),t.on("end",()=>{e(i?{kind:"too-large"}:{kind:"body",value:Buffer.concat(r).toString("utf8")})}),t.on("error",n)})}function Az(t){let e;try{e=JSON.parse(t)}catch{return}if(!e||typeof e!="object"||Array.isArray(e))return;let n=e,r=new Set(["protocolVersion","runtimeId","runtimeVersion","taskId","planSha256"]);if(!Object.keys(n).some(o=>!r.has(o))&&Number.isInteger(n.protocolVersion)&&!(typeof n.runtimeId!="string"||typeof n.runtimeVersion!="string")&&!(!TP(n.taskId)||!TP(n.planSha256)))return n}function TP(t){return t==null||typeof t=="string"}function Ct(t,e,n){xf(t,e,{ok:!1,error:n})}function xf(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json; charset=utf-8"),t.setHeader("cache-control","no-store"),t.end(JSON.stringify(n))}function Cs(t){return{type:"error",status:"failed",error:{code:t.code,exitCode:t.exitCode,message:t.message,technicalMessage:t.technicalMessage,stage:"desktop_session_check",retryable:t.retryable,safeToRetry:!0,retryMode:t.retryMode,action:t.message},completedSteps:[],pendingSteps:[],partialArtifacts:[]}}function Iz(t){return new Promise((e,n)=>{let r=i=>{t.off("listening",o),n(i)},o=()=>{t.off("error",r),e()};t.once("error",r),t.once("listening",o),t.listen(0,Pf)})}function RP(t){return new Promise((e,n)=>{t.close(r=>{if(r&&r.code!=="ERR_SERVER_NOT_RUNNING"){n(r);return}e()}),t.closeAllConnections()})}var Fz=1800*1e3,Tl=process.cwd(),AP=process.cwd(),As=new _z;function mt(){return As.getStore()?.cwd??Tl}function Af(t,e,n){let r=en(t),o=en(e||mt()),i=Yn(r)||Yn(o)?Cf.isAbsolute(r)?Cf.normalize(r):Cf.resolve(o,r):$z(r)?r:jz(o,r);if(n?.mustExist)try{if(!Dz(i).isDirectory())return!1}catch{return!1}let s=As.getStore();return s?s.cwd=i:Tl=i,!0}function Rl(){return As.getStore()?.originalCwd??AP}function Jo(t){let e=en(t);Tl=e,AP=Tl;let n=As.getStore();n&&(n.cwd=e,n.originalCwd=e)}function Ef(t,e){let n=en(t);return As.run({cwd:n,originalCwd:n},e)}var If=null;function Is(t){If={provider:t}}function _f(){if(!If)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return If.provider}function Mf(){let t;try{t=_f()}catch{return}return{type:t.type,shellPath:t.shellPath,...t.psEdition?{psEdition:t.psEdition}:{},...t.isGitBashOnWindows?{isGitBashOnWindows:!0}:{}}}async function Uz(t,e=async()=>[],n){let r=await PP(n),o=await e(),i=kf({...process.env,GIT_EDITOR:"true",QLOGICAGENT:"1",...t});return o.length>0&&(i.PATH=[...o,...i.PATH?[i.PATH]:[]].join(Lz)),{...i,...r}}async function Pl(t,e,n,r){let{timeout:o,preventCwdChanges:i,shouldAutoBackground:s,onStdout:a,cwd:c}=r??{},l=o||Fz,d=n??sf(),u=_f(),p=cf(),g=r?.sandbox,m=g?vf(Sf(),g,u.shellPath,[]):void 0,{commandString:f,cwdFilePath:h}=await u.buildExecCommand(t,{id:p,useSandbox:m?.useSandbox??!1,sandboxTmpDir:m?.useSandbox?m.sandboxTmpDir:void 0}),y=f,b=c??mt();try{await CP(b)}catch{let D=Rl();try{await CP(D),Af(D),b=D}catch{return bf(`Working directory "${b}" no longer exists.`)}}if(e.aborted)return bl();let P=u.shellPath,w=u.getSpawnArgs(y);if(g&&m?.useSandbox){let D=vf(Sf(),g,P,w);P=D.bin,w=D.args,D.sandboxTmpDir&&await xP(D.sandboxTmpDir,{recursive:!0})}let C=await u.getEnvironmentOverrides(t),A=await Uz(C,r?.resolveRuntimePathEntries,r?.sessionId),v=!!a,x=Vr("local_bash"),I=new Vn(x,!v);await xP(no(),{recursive:!0});let M;if(!v){let D=wl.O_NOFOLLOW??0;M=await Nz(I.path,process.platform==="win32"?"w":wl.O_WRONLY|wl.O_CREAT|wl.O_APPEND|D)}try{let D=Ez(P,w,{env:A,cwd:b,stdio:v?["pipe","pipe","pipe"]:["pipe",M?.fd,M?.fd],detached:u.detached,windowsHide:!0}),H=yf(D,e,l,I,s);if(M!==void 0)try{await M.close()}catch{}return D.stdout&&a&&D.stdout.on("data",K=>{a(typeof K=="string"?K:K.toString())}),h&&H.result.then(K=>{if(K&&!i&&!K.backgroundTaskId){try{let X=Mz(h,{encoding:"utf8"}).trim();X&&X.normalize("NFC")!==b&&Af(X,b,{mustExist:!0})}catch{}try{Oz(h)}catch{}}}),H}catch(D){if(M!==void 0)try{await M.close()}catch{}return I.clear(),bl(void 0,{code:126,stderr:D instanceof Error?D.message:String(D)})}}var Qo="image_generate",Df={type:"object",properties:{prompt:{type:"string",description:"Image generation prompt. Enrich vague requests with style, lighting, composition, color, mood details."},purpose:{type:"string",description:"Intended use: 'social-media', 'short-video-cover', 'phone-wallpaper', 'avatar', 'poster', etc."},style:{type:"string",description:"Visual art style: 'photorealistic', 'anime', 'watercolor', 'oil-painting', '3d-render', etc."},size:{type:"string",description:"Dimensions. Model-dependent: Seedream (doubao-seedream-*) accepts ONLY named '2K'/'4K' \u2014 never pixel sizes. Other models take pixels, e.g. '1024x1792' (portrait), '1792x1024' (landscape), '1024x1024' (square). Omit to use the model's default."},image_url:{type:"string",description:"Reference image URL for image-to-image generation (img2img). Character reference sheet or style transfer. MUST be a publicly accessible HTTP/HTTPS URL. Local file paths and data: URLs are NOT supported."},output_path:{type:"string",description:"Optional absolute or workspace-relative path where the generated image should be saved. Use only for a single generated image."},output_paths:{type:"array",items:{type:"string"},description:"Optional absolute or workspace-relative paths where generated images should be saved. Must match the number of generated images."},n:{type:"number",description:"Number of images to generate (1-4). Default: 1."},quality:{type:"string",description:"Image quality level: 'auto', 'high', 'low', 'hd'. Provider-specific."},seed:{type:"number",description:"Random seed for reproducible generation. Same seed + prompt = same result."}},required:["prompt"]};function IP(t){return{name:Qo,label:"Image Generate",description:"Generate images from a text prompt. You MUST enrich vague prompts with details about style, lighting, composition, color, and mood before calling. Supports img2img via image_url reference. All generated images are saved locally and can be viewed immediately. IMPORTANT: For ordinary creative requests, infer reasonable defaults for purpose, style, and size and call this tool directly. Use ask_user only when a missing detail is critical or the request is genuinely ambiguous (e.g. the user asks for a production ad with unspecified brand constraints). Infer image size automatically from purpose (e.g. 1024x1792 for phone wallpaper, 1792x1024 for landscape poster, 1024x1024 for avatar/social). Do NOT expose size as a raw number to the user. The generated image is ALREADY displayed to the user by the app from this tool's result \u2014 do NOT re-embed it, and NEVER write a Markdown image that points at a local filesystem path or saved file location (a local path renders as a broken image). Do NOT invent Markdown image URLs, placeholder attachment paths, or claim an image was generated without this tool returning mediaUrls. When the user asks for generated image files at specific workspace paths, pass output_path/output_paths so the files are actually saved there. ALL reference image URLs MUST be publicly accessible HTTP/HTTPS URLs. Use file_upload tool first if the user provides a local file. Local file paths and data: URIs are NOT supported by the generation API.",parameters:Df,isEgress:!0,egressCarriesData:!1,execute:async(e,n)=>{let r=await t.generateImage({prompt:n.prompt,purpose:n.purpose,style:n.style,size:n.size,imageUrl:n.image_url,n:n.n,quality:n.quality,seed:n.seed}),o=r.mediaUrls.length,i=Bz(n);if(i.length>0&&i.length!==o)return{content:[{type:"text",text:`Error: output_paths length (${i.length}) must match generated image count (${o}).`}],details:{type:"image_generate",model:r.model,size:r.size,durationMs:r.durationMs,mediaUrls:r.mediaUrls,error:"output_path_count_mismatch"}};let s=[],a=[];if(i.length>0){if(!t.saveGeneratedImages)return{content:[{type:"text",text:"Error: this host does not support saving generated images to explicit output paths."}],details:{type:"image_generate",model:r.model,size:r.size,durationMs:r.durationMs,mediaUrls:r.mediaUrls,error:"output_path_unsupported"}};a=await t.saveGeneratedImages({mediaUrls:r.mediaUrls,outputPaths:i}),s=a.map(u=>u.localPath)}let c=s.length===0?"":`
394
394
  Saved ${s.length} image${s.length>1?"s":""} to ${s.join(", ")}${Hz(a)}`;return{content:[{type:"text",text:`Generated ${o} image${o>1?"s":""}${r.model?` (model: ${r.model})`:""}${c}
395
395
  The generated image is already displayed to the user; the saved path above (if any) is a file location for reading only \u2014 do NOT re-embed the image as Markdown or reference a local filesystem path as an image URL.`}],details:{type:"image_generate",model:r.model,size:r.size,durationMs:r.durationMs,mediaUrls:r.mediaUrls,...s.length>0?{savedPaths:s}:{},...a.length>0?{savedFiles:a}:{}}}}}}function Hz(t){return t.length===0?"":`
396
396
  Saved file evidence: ${t.map(n=>{let r=[`bytes: ${n.bytes}`,`mimeType: ${n.mimeType}`];return n.headerHex&&r.push(`header: ${n.headerHex}`),`${n.localPath} (${r.join(", ")})`}).join("; ")}`}function Bz(t){let e=[];if(typeof t.output_path=="string"&&t.output_path.trim()&&e.push(t.output_path.trim()),Array.isArray(t.output_paths))for(let n of t.output_paths)typeof n=="string"&&n.trim()&&e.push(n.trim());return e}var Of={type:"object",properties:{text:{type:"string",description:"Text to convert to speech."},channel:{type:"string",description:"Optional channel id to pick output format (e.g. telegram)."},voice:{type:"string",description:"Voice name for TTS. Available voices depend on the provider. Common options: alloy, ash, ballad, coral, echo, fable, nova, onyx, sage, shimmer."},speed:{type:"number",description:"Speech speed multiplier (0.25-4.0). Default is 1.0."}},required:["text"]};function EP(t){return{name:"tts",label:"TTS",searchHint:"tts text-to-speech speak voice narration read-aloud audio voiceover dub spoken mp3 \u8BED\u97F3 \u914D\u97F3 \u6717\u8BFB \u6587\u5B57\u8F6C\u8BED\u97F3 \u8BED\u97F3\u5408\u6210 \u5FF5\u51FA\u6765 \u751F\u6210\u8BED\u97F3 \u8F6C\u6210\u8BED\u97F3",description:"Convert text to speech (TTS) \u2014 read text aloud as spoken audio. Use for narration, voice messages, or any spoken-word output. DO NOT use for music, songs, or melodies \u2014 use music_generate instead.",parameters:Of,execute:async(e,n)=>{let r=await t.textToSpeech({text:n.text,channel:n.channel,voice:n.voice,speed:n.speed});return{content:[{type:"text",text:"\u5DF2\u6210\u529F\u751F\u6210\u8BED\u97F3\u3002"}],details:{type:"tts",audioPath:r.audioPath,provider:r.provider,voiceCompatible:r.voiceCompatible,mediaUrls:r.mediaUrls}}}}}var Zo="video_generate",Nf={type:"object",properties:{prompt:{type:"string",description:"Video generation prompt. MUST be in English. Include scene, movement, camera motion, lighting, style."},purpose:{type:"string",description:"Intended use: 'social-media', 'short-video', 'presentation', etc."},style:{type:"string",description:"Visual style: 'cinematic', 'anime', 'watercolor', etc."},image_url:{type:"string",description:"Reference image URL for image-to-video generation (first frame, style reference, or character reference). MUST be a publicly accessible HTTP/HTTPS URL. Local file paths and data: URLs are NOT supported. If the user provides a local file, use a file hosting service or the image_generate tool first."},reference_videos:{type:"array",items:{type:"string"},maxItems:3,description:"Reference video URLs for video-to-video or multimodal generation (Seedance 2.0). Max 3 videos, total duration \u226415s. Use for: (a) video-to-video: provide source video to restyle/transform with prompt guidance; (b) multimodal reference: combine with image_url and/or reference_audios for style/motion/audio-guided generation. Each URL MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},reference_audios:{type:"array",items:{type:"string"},maxItems:3,description:"Reference audio URLs for audio-guided video generation (Seedance 2.0). Max 3 audio clips, total duration \u226415s. CANNOT be used alone \u2014 must be combined with at least one image_url or reference_video. Each URL MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},generate_audio:{type:"boolean",description:"Generate synchronized audio track for the video (Seedance 2.0/1.5 pro). When true, the output video includes AI-generated sound effects matching the visual content."},aspect_ratio:{type:"string",description:"Video aspect ratio: '9:16' (vertical), '16:9' (horizontal), '1:1' (square). Default: '16:9'."},duration:{type:"number",minimum:3,maximum:15,description:"Video duration in seconds. Seedance 2.0: 4-15s per shot. Seedance 1.0/1.5: 3-10s. For longer videos (>15s), use multi-shot storyboard workflow (generate + extend/merge). Must be confirmed by user before generation."},resolution:{type:"string",description:"Output resolution: '480p', '720p', '1080p'. Default: '720p'."},fps:{type:"number",description:"Frame rate: 24 or 30 fps. Default: provider-specific."},seed:{type:"number",description:"Random seed for reproducible generation."},camera_fixed:{type:"boolean",description:"Lock camera position (Seedance 1.0/1.5 only, not supported for img2video)."},return_last_frame:{type:"boolean",description:"Return last frame URL for chaining continuous video segments."},draft:{type:"boolean",description:"Draft mode: low-cost preview (Seedance 1.5 pro only)."},service_tier:{type:"string",enum:["default","flex"],description:"'default' (online, fast) or 'flex' (offline, ~50% cost). Not all models support flex."},callback_url:{type:"string",description:"Webhook URL for async task completion notification."},safety_identifier:{type:"string",description:"End-user safety identifier for content moderation tracking."},execution_expires_after:{type:"number",description:"Task expiration in seconds (for offline/flex scheduling)."},video_tools:{type:"array",items:{type:"string"},description:"Video-level builtin tools, e.g. ['web_search'] (Seedance 2.0 online search)."}},required:["prompt"]};function _P(t){return{name:Zo,label:"Video Generate",searchHint:"video generate text-to-video image-to-video photo-to-video animate-image animate-photo still-to-motion bring-image-to-life clip movie \u89C6\u9891 \u751F\u6210\u89C6\u9891 \u6587\u751F\u89C6\u9891 \u56FE\u751F\u89C6\u9891 \u7167\u7247\u53D8\u89C6\u9891 \u8BA9\u56FE\u7247\u52A8\u8D77\u6765 \u56FE\u7247\u52A8\u753B \u77ED\u89C6\u9891 \u505A\u89C6\u9891",description:"Generate a short video clip from a text prompt, reference image, source video, or multimodal references. Prompt MUST be in English. Include scene, movement, camera motion, lighting details. Single-shot: 3\u201310s. For longer videos (>10s), use multi-shot storyboard workflow. MODES: (1) text-to-video: prompt only. (2) image-to-video: prompt + image_url. (3) video-to-video: prompt + reference_videos \u2014 restyle/transform an existing video with prompt guidance. (4) multimodal reference: prompt + any combination of image_url / reference_videos / reference_audios for style/motion/audio-guided generation. (5) generate_audio=true for synchronized sound effects. ALL image/video/audio URLs MUST be publicly accessible HTTP/HTTPS URLs. Local file paths and data: URIs are NOT supported by the generation API. If the user provides a local file, use the file_upload tool FIRST to get a public URL. IMPORTANT: If the user has not specified aspect ratio or duration, use ask_user to clarify (e.g. aspect: 16:9 for landscape / 9:16 for vertical / 1:1 for square; duration: 3-10s). Auto-set aspect_ratio based on stated purpose (e.g. 9:16 for short-video / Douyin, 16:9 for presentation).",parameters:Nf,execute:async(e,n)=>{let r=await t.generateVideo({prompt:n.prompt,purpose:n.purpose,style:n.style,imageUrl:n.image_url,referenceVideos:n.reference_videos,referenceAudios:n.reference_audios,generateAudio:n.generate_audio,aspectRatio:n.aspect_ratio,duration:n.duration,resolution:n.resolution,fps:n.fps,seed:n.seed,cameraFixed:n.camera_fixed,returnLastFrame:n.return_last_frame,draft:n.draft,serviceTier:n.service_tier,callbackUrl:n.callback_url,safetyIdentifier:n.safety_identifier,executionExpiresAfterSeconds:n.execution_expires_after,videoTools:n.video_tools}),o=r.mediaUrls.length,i=[`Generated ${o} video${o>1?"s":""}`];return r.model&&i.push(`model: ${r.model}`),r.lastFrameUrl&&i.push(`last_frame: ${r.lastFrameUrl}`),r.taskId&&i.push(`task_id: ${r.taskId}`),{content:[{type:"text",text:i.length>1?`${i[0]} (${i.slice(1).join(", ")})`:i[0]}],details:{type:"video_generate",model:r.model,durationMs:r.durationMs,mediaUrls:r.mediaUrls,...r.taskId?{taskId:r.taskId}:{}}}}}}var ei="music_generate",Lf={type:"object",properties:{prompt:{type:"string",description:"Music generation prompt. MUST be in English. Include genre, mood, tempo, instruments, and atmosphere details."},purpose:{type:"string",description:"Intended use: 'background-music', 'ringtone', 'short-video-bgm', 'full-song', 'notification-sound', etc."},style:{type:"string",description:"Musical style/genre: 'lo-fi', 'pop', 'rock', 'jazz', 'classical', 'electronic', 'ambient', etc."},lyrics:{type:"string",description:"Optional lyrics for vocal music. Structure with [verse], [chorus], [bridge] tags if desired."},duration:{type:"number",description:"Duration in seconds (5-300). Infer from purpose: ringtone 15-30s, BGM 30-60s, full song 120-180s."},is_instrumental:{type:"boolean",description:"Set true for pure instrumental music without vocals. Defaults to true when no lyrics are provided."},cover_audio_url:{type:"string",description:"URL of an existing audio track to use as base for cover/remix. When provided, generates a cover version. MUST be a publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},audio_format:{type:"string",enum:["mp3","wav","flac"],description:"Output audio format. Defaults to mp3."}},required:["prompt"]};function MP(t){return{name:ei,label:"Music Generate",searchHint:"music song melody bgm compose lyrics \u97F3\u4E50 \u6B4C\u66F2 \u4F5C\u66F2 \u5199\u6B4C \u80CC\u666F\u97F3\u4E50 \u65CB\u5F8B",description:"Generate music, songs, or melodies from text descriptions. Prompt MUST be in English. Supports lyrics for vocal songs. DO NOT use for spoken-word audio or TTS \u2014 use tts tool instead. IMPORTANT: If the user has not specified genre/style or duration, use ask_user to clarify (e.g. style: lo-fi / pop / rock / jazz; duration inferred from purpose: 30s for ringtone, 60-90s for BGM, 180-240s for full song). Auto-infer duration from purpose when possible.",parameters:Lf,isEgress:!0,egressCarriesData:!1,execute:async(e,n)=>{let r=n.lyrics,o;if(!r&&!n.is_instrumental&&t.generateLyrics){try{r=await t.generateLyrics(n.prompt),r||(o="empty lyrics returned")}catch(l){o=l instanceof Error?l.message:String(l)}o&&console.error(`[music-generate] lyrics generation failed: ${o}; falling back to instrumental`)}let i=await t.generateMusic({prompt:n.prompt,purpose:n.purpose,style:n.style,lyrics:r,duration:n.duration,isInstrumental:o?!0:n.is_instrumental,audioUrl:n.cover_audio_url,audioFormat:n.audio_format}),s=i.mediaUrls.length,a=o?` (lyrics generation failed: ${o} \u2014 generated as instrumental)`:"";return{content:[{type:"text",text:`Generated ${s} audio track${s>1?"s":""}${i.model?` (model: ${i.model})`:""}${a}`}],details:{type:"music_generate",model:i.model,durationMs:i.durationMs,mediaUrls:i.mediaUrls,...o?{lyricsFailed:!0}:{}}}}}}var $f=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow","subagent_decision"]),DP=new Set([...$f,"agent"]);function jf(t,e){let n=e?$f:DP;return t.filter(r=>r.function.name.startsWith("mcp__")?!0:!n.has(r.function.name))}var Es=class{toolPool=new Map;setTools(e){this.toolPool.clear();for(let n of e)this.toolPool.set(n.name,n)}addTool(e){this.toolPool.set(e.name,e)}addTools(e){for(let n of e)this.addTool(n)}removeTool(e){return this.toolPool.delete(e)}findTool(e){return this.toolPool.get(e)}hasTool(e){return this.toolPool.has(e)}getToolNames(){return Array.from(this.toolPool.keys())}getToolCount(){return this.toolPool.size}async executeTool(e,n,r,o){let i=this.toolPool.get(e);if(!i)throw new Error(`Tool not found: ${e}`);return i.execute(n,r,o)}getTools(){return Array.from(this.toolPool.values()).filter(e=>e.isEnabled?.()!==!1)}getToolManifest(){let e=[];for(let n of this.toolPool.values()){if(n.isEnabled?.()===!1)continue;let r=Kn(n);e.push({type:"function",function:{name:n.name,description:n.description,parameters:n.parameters},meta:{category:n.category??"other",displayName:n.displayName??{key:`capability.tool.${n.name}.name`,fallback:n.label},displayDescription:n.displayDescription??{key:`capability.tool.${n.name}.description`,fallback:""},parallelSafe:n.isConcurrencySafe??!1,riskLevel:r,isReadOnly:r==="read",isDangerous:r==="system",isDelete:n.isDelete??!1,isEgress:n.isEgress??r==="external_egress",egressCarriesData:n.egressCarriesData??!1,...n.executionTimeoutMs!==void 0?{executionTimeoutMs:n.executionTimeoutMs}:{}}})}return e}},xl=new Es;function OP(){return xl}function NP(t){xl.addTool(t)}function LP(t){xl.addTools(t)}function Cl(t){return xl.removeTool(t)}function tn(t=OP()){return{findTool:e=>t.findTool(e),getToolManifest:()=>t.getToolManifest(),getToolNames:()=>t.getToolNames(),setTools:e=>t.setTools(e),addTool:e=>t.addTool(e),addTools:e=>t.addTools(e),removeTool:e=>t.removeTool(e)}}function $P(){return tn(new Es)}import*as se from"node:fs";import*as nt from"node:path";import{spawn as H2}from"node:child_process";import{StringDecoder as B2}from"node:string_decoder";var ti="ask_user";var qz={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:4,description:"1-4 clarifying questions to ask the user.",items:{type:"object",properties:{question:{type:"string",description:"The question text. Should end with '?'."},header:{type:"string",description:"Short identifier/tag for this question (max 50 chars)."},options:{type:"array",minItems:2,maxItems:8,description:"2-8 options for the user to choose from. Omit for free text.",items:{type:"object",properties:{label:{type:"string",description:"Display label (1-5 words)."},description:{type:"string",description:"Brief explanation of this option."}},required:["label"]}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false (single exclusive choice). Set true whenever the question accepts more than one answer \u2014 e.g. the wording is plural (\u4E2D\u6587 '\u54EA\u4E9B/\u54EA\u51E0\u9879/\u6709\u54EA\u4E9B', English 'which \u2026 (plural)/select all that apply'), or you are collecting a set of features/preferences rather than one mutually-exclusive pick."}},required:["question","header"]}}},required:["questions"]};function jP(t){return{name:ti,label:"Ask User",description:"Ask the user clarifying questions when you need more information to proceed. Supports free text questions and multiple-choice options. Set multiSelect:true on a question that accepts multiple answers (plural wording like \u4E2D\u6587 '\u54EA\u4E9B/\u54EA\u51E0\u9879' or English 'which \u2026 (plural)', or collecting a set of preferences); leave it off for a single exclusive choice. Use this when the user's intent is ambiguous or you need confirmation.",parameters:qz,execute:async(e,n)=>{if(!n.questions||n.questions.length===0)return{content:[{type:"text",text:"Error: at least one question is required."}],details:{type:"ask_user",error:"no_questions"}};if(n.questions.length>4)return{content:[{type:"text",text:"Error: maximum 4 questions allowed."}],details:{type:"ask_user",error:"too_many_questions"}};for(let s of n.questions)if(!s.question?.trim()||!s.header?.trim())return{content:[{type:"text",text:"Error: every question must have a non-empty 'question' and 'header'."}],details:{type:"ask_user",error:"empty_question_or_header"}};let r=n.questions.map(s=>s.question);if(new Set(r).size!==r.length)return{content:[{type:"text",text:"Error: all questions must have unique text."}],details:{type:"ask_user",error:"duplicate_questions"}};for(let s of n.questions){if(Array.isArray(s.options)&&s.options.length===0&&(s.options=void 0),s.options&&(s.options.length<2||s.options.length>8))return{content:[{type:"text",text:`Error: question "${s.header}" must have 2-8 options (got ${s.options.length}).`}],details:{type:"ask_user",error:"invalid_option_count"}};if(s.options){let a=s.options.map(c=>c.label);if(new Set(a).size!==a.length)return{content:[{type:"text",text:`Error: question "${s.header}" has duplicate option labels.`}],details:{type:"ask_user",error:"duplicate_option_labels"}}}}let o=await t.askUser(n.questions);if(o===null)return{content:[{type:"text",text:"User declined to answer questions."}],details:{type:"ask_user",declined:!0}};let i=["User answered:"];for(let s of n.questions){let a=o[s.question]??"(no answer)";i.push(`- ${s.header}: ${a}`)}return{content:[{type:"text",text:i.join(`
@@ -24,14 +24,14 @@ requires: []
24
24
  如果找不到工具或 Prompt:
25
25
 
26
26
  1. 引导用户在桌面端“插件 → 连接器”安装并启用官方 **Astra Search**。
27
- 2. 优先建议 OAuth:在 Astra Search 设置中选择 OAuth 并点击“授权”。Runtime 会
28
- 打开 llmrouter 的授权页面;不要索取、显示或保存 OAuth token。
29
- 3. 如果用户选择 API Key:
27
+ 2. Xiaozhi Runtime 会在正常 llmrouter 握手后自动注入本机托管 API Key,不应再让
28
+ 用户选择认证模式或重复填写密钥;如果托管 Key 尚不可用,引导用户先完成桌面账号登录。
29
+ 3. 第三方 MCP Host 只支持用户自行配置普通 llmrouter API Key:
30
30
  - 未注册时打开或给出 <https://www.qlogicagent.com/signup>;
31
31
  - 登录后打开或给出 <https://www.qlogicagent.com/keys> 创建或重置密钥;
32
- - 让用户返回 Astra Search 设置,选择 API Key 并把密钥填入凭证框。
32
+ - 让用户返回 Astra Search 设置,把密钥填入 API Key 凭证框。
33
33
  4. 当前 Host 能安全打开外部链接时可以导航到上述页面;否则提供可点击链接。
34
34
  **不要把 API Key 发到聊天、写入项目文件、日志、记忆或 Skill。**
35
35
 
36
- 完成安装、授权、启用和连接测试后,重新发现 MCP 清单并读取 Prompt。不得改用旧
36
+ 完成安装、绑定、启用和连接测试后,重新发现 MCP 清单并读取 Prompt。不得改用旧
37
37
  REST 搜索、本地 provider 或其它隐藏 fallback。
@@ -24,7 +24,6 @@ export interface UploadBatchResult {
24
24
  accepted?: number;
25
25
  status?: number;
26
26
  error?: string;
27
- refreshedToken?: boolean;
28
27
  }
29
28
  /**
30
29
  * Resolve the feedback ingest base, derived from the llmrouter base already injected into the agent
@@ -4,9 +4,4 @@ export interface LlmrouterFetchOptions {
4
4
  init?: RequestInit;
5
5
  signal?: AbortSignal;
6
6
  }
7
- export interface LlmrouterFetchResult {
8
- response: Response;
9
- refreshedToken: boolean;
10
- }
11
- export declare function isJwtExpiredOrNearExpiry(token: string | undefined, skewSeconds?: number): boolean;
12
- export declare function fetchWithLlmrouterAccess(path: string, options?: LlmrouterFetchOptions): Promise<LlmrouterFetchResult>;
7
+ export declare function fetchWithLlmrouterAccess(path: string, options?: LlmrouterFetchOptions): Promise<Response>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qlogicagent",
3
- "version": "2.20.4",
3
+ "version": "2.20.5",
4
4
  "description": "XiaozhiClaw Agent CLI — subprocess architecture (JSON-RPC over stdio)",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",