qlogicagent 2.10.31 → 2.10.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +91 -90
- package/dist/index.js +178 -177
- package/dist/types/runtime/prompt/fresh-workspace-evidence.d.ts +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var yT=Object.defineProperty;var Mo=(t,e)=>()=>(t&&(e=t(t=0)),e);var ku=(t,e)=>{for(var r in e)yT(t,r,{get:e[r],enumerable:!0})};import{homedir as uA}from"node:os";import{join as te}from"node:path";import{existsSync as pA}from"node:fs";function F(){return process.env.QLOGICAGENT_HOME||te(uA(),je)}function qu(){return te(F(),"settings.json")}function Wu(){return te(F(),"memory","memories.db")}function Br(){let t=process.env.QLOGIC_LLMROUTER_USER_ID?.trim();if(t)return t;let e=process.env.QLOGIC_IMPLICIT_OWNER_ID?.trim();if(e)return e;let r=process.env.QLOGIC_DEVICE_ID?.trim();return r?`oc_${r}`:"oc_local"}function mA(t){let e=t.trim();if(!e)throw new Error("ownerUserId is required for profile-scoped storage");return encodeURIComponent(e).replace(/\./g,"%2E")}function W(t=Br()){return te(F(),"profiles",mA(t))}function Gu(t=Br()){return te(W(t),"memory")}function Ku(){return te(W(),"plugins")}function yt(){return te(W(),"skills")}function de(){return te(W(),"settings.json")}function zu(){return te(F(),"cache")}function Vu(){return te(W(),"plugin-cache")}function Xu(){return te(W(),"mcp.json")}function Yu(){return te(W(),"marketplace.json")}function Ju(){return te(W(),"rules")}function re(t){if(!t)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return te(t,je)}function _t(t){return te(re(t),"skills")}function vr(t){return te(re(t),"INSTRUCTIONS.md")}function ir(t){return te(re(t),"rules")}function Mt(t){return te(re(t),"sessions")}function Qu(t,e){let r=te(re(t),"checkpoints");return e?te(r,e):r}function Zu(t){return te(t,je,"hooks")}function ep(t,e){return t.filter(r=>r!==e&&pA(te(r,je,"skills")))}var je,D=Mo(()=>{"use strict";je=".qlogicagent"});var Fo,lp=Mo(()=>{"use strict";Fo=class{pools=new Map;runtimeStates=new Map;constructor(e){if(e)for(let r of e){this.pools.set(r.providerId,r);for(let n of r.keys)this.runtimeStates.set(n.id,this.createInitialState())}}acquireKey(e){let r=this.pools.get(e);if(!r||r.keys.length===0)return null;let n=Date.now(),o=this.getHealthyCandidates(r,n);if(o.length===0)return null;let s=this.selectByStrategy(o,r.strategy,n);if(!s)return null;let i=this.runtimeStates.get(s.id);return i.inFlight++,i.totalRequests++,i.lastUsedAt=n,i.requestTimestamps.push(n),{keyId:s.id,apiKey:s.key,providerId:e,release:a=>this.releaseKey(s.id,a)}}releaseKey(e,r){let n=this.runtimeStates.get(e);if(n)if(n.inFlight=Math.max(0,n.inFlight-1),r.success)n.consecutiveErrors=0,n.healthStatus="healthy",r.tokens&&(n.totalTokens+=r.tokens,n.tokenCounts.push(r.tokens));else if(n.consecutiveErrors++,n.lastErrorAt=Date.now(),r.errorCode===429){let o=r.retryAfter?r.retryAfter*1e3:3e4;n.cooldownUntil=Date.now()+o,n.healthStatus="cooldown"}else n.consecutiveErrors>=5?(n.cooldownUntil=Date.now()+6e4,n.healthStatus="cooldown"):n.consecutiveErrors>=3&&(n.healthStatus="degraded")}addProvider(e,r){this.pools.has(e)||this.pools.set(e,{providerId:e,baseUrl:r?.baseUrl,strategy:r?.strategy??"weighted-round-robin",keys:[],rateLimit:r?.rateLimit})}removeProvider(e){let r=this.pools.get(e);if(r){for(let n of r.keys)this.runtimeStates.delete(n.id);this.pools.delete(e)}}addKey(e,r,n){let o=this.pools.get(e);o||(o={providerId:e,strategy:"weighted-round-robin",keys:[]},this.pools.set(e,o));let s=n?.id??crypto.randomUUID(),i={id:s,key:r,label:n?.label,weight:n?.weight??1,enabled:n?.enabled??!0};return o.keys.push(i),this.runtimeStates.set(s,this.createInitialState()),s}removeKey(e){for(let r of this.pools.values()){let n=r.keys.findIndex(o=>o.id===e);if(n!==-1){r.keys.splice(n,1),this.runtimeStates.delete(e);return}}}updateKey(e,r){for(let n of this.pools.values()){let o=n.keys.find(s=>s.id===e);if(o){if(r.label!==void 0&&(o.label=r.label),r.weight!==void 0&&(o.weight=r.weight),r.enabled!==void 0){o.enabled=r.enabled;let s=this.runtimeStates.get(e);s&&(s.healthStatus=r.enabled?"healthy":"disabled")}return}}}setKeyHealth(e,r){let n=this.runtimeStates.get(e);n&&(n.healthStatus=r)}setStrategy(e,r){let n=this.pools.get(e);n&&(n.strategy=r)}setRateLimit(e,r){let n=this.pools.get(e);n&&(n.rateLimit=r)}getPoolStatus(e){let r=this.pools.get(e);return r?this.buildPoolStatus(r):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 r=this.pools.get(e);return r?this.getHealthyCandidates(r,Date.now()).length>0:!1}exportConfig(){return[...this.pools.values()]}reloadConfig(e){let r=new Set;for(let n of e){this.pools.set(n.providerId,n);for(let o of n.keys)r.add(o.id),this.runtimeStates.has(o.id)||this.runtimeStates.set(o.id,this.createInitialState())}for(let n of[...this.pools.keys()])e.some(o=>o.providerId===n)||this.pools.delete(n);for(let n of[...this.runtimeStates.keys()])r.has(n)||this.runtimeStates.delete(n)}createInitialState(){return{inFlight:0,totalRequests:0,totalTokens:0,lastUsedAt:0,lastErrorAt:0,consecutiveErrors:0,cooldownUntil:0,healthStatus:"healthy",requestTimestamps:[],tokenCounts:[]}}getHealthyCandidates(e,r){let n=[];for(let o of e.keys){if(!o.enabled)continue;let s=this.runtimeStates.get(o.id);if(s){if(s.healthStatus==="cooldown")if(r>=s.cooldownUntil)s.healthStatus="healthy",s.consecutiveErrors=0;else continue;s.healthStatus!=="disabled"&&(e.rateLimit?.rpm&&(this.pruneWindow(s.requestTimestamps,r),s.requestTimestamps.length>=e.rateLimit.rpm*.9)||e.rateLimit?.tpm&&(this.pruneWindow(s.tokenCounts,r),s.tokenCounts.reduce((a,c)=>a+c,0)>=e.rateLimit.tpm*.9)||n.push(o))}}return n}selectByStrategy(e,r,n){if(e.length===0)return null;if(e.length===1)return e[0];switch(r){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 r=e.reduce((o,s)=>o+s.weight,0),n=Math.random()*r;for(let o of e)if(n-=o.weight,n<=0)return o;return e[e.length-1]}leastBusy(e){let r=1/0,n=e[0];for(let o of e){let i=this.runtimeStates.get(o.id)?.inFlight??0;(i<r||i===r&&o.weight>n.weight)&&(r=i,n=o)}return n}pruneWindow(e,r){let n=r-6e4;for(;e.length>0&&e[0]<n;)e.shift()}buildPoolStatus(e){return{providerId:e.providerId,baseUrl:e.baseUrl,strategy:e.strategy,rateLimit:e.rateLimit,keys:e.keys.map(r=>{let n=this.runtimeStates.get(r.id)??this.createInitialState();return{...r,inFlight:n.inFlight,totalRequests:n.totalRequests,totalTokens:n.totalTokens,lastUsedAt:n.lastUsedAt,lastErrorAt:n.lastErrorAt,consecutiveErrors:n.consecutiveErrors,cooldownUntil:n.cooldownUntil,healthStatus:r.enabled?n.healthStatus:"disabled"}})}}}});var mp={};ku(mp,{ALL_PURPOSES:()=>Pn,ModelRegistry:()=>Ho,deriveModelPurposes:()=>pp,getModelRegistry:()=>M,resetModelRegistry:()=>RA});import*as he from"node:fs";import{ProviderRegistry as vA,ProviderVariantResolver as kA}from"@xiaozhiclaw/provider-core";function M(){return xn||(xn=new Ho,xn.load()),xn}function RA(){xn=null}function SA(t){let e=qu();if(t===e||!he.existsSync(e))return;let r=dp(e);if(!up(r))return;let n=dp(t);if(up(n))return;let o={...r,...n,providers:r.providers,models:r.models??n.models,bindings:wA(n)?n.bindings:r.bindings,migrations:{...Va(r.migrations)?r.migrations:{},...Va(n.migrations)?n.migrations:{},legacyGlobalSettingsImportedAt:new Date().toISOString()}},s=t.replace(/[/\\][^/\\]+$/,"");he.existsSync(s)||he.mkdirSync(s,{recursive:!0}),he.writeFileSync(t,JSON.stringify(o,null,2),"utf-8")}function dp(t){try{return JSON.parse(he.readFileSync(t,"utf-8"))}catch{return{}}}function up(t){return Array.isArray(t.providers)&&t.providers.length>0}function wA(t){return Va(t.bindings)&&Object.keys(t.bindings).length>0}function Va(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function pp(t){let e=[];switch((!t.mediaType||t.mediaType==="image_understanding"||t.mediaType==="video_understanding")&&e.push("textGeneration"),(t.vision||t.mediaType==="image_understanding")&&e.push("imageUnderstanding"),t.mediaType==="video_understanding"&&e.push("videoUnderstanding"),t.mediaType){case"image":e.push("imageGeneration");break;case"video":e.push("videoGeneration");break;case"tts":e.push("tts");break;case"stt":e.push("stt");break;case"music":case"music_realtime":e.push("musicGeneration");break;case"voice_clone":e.push("voiceClone");break;case"embedding":e.push("embedding");break;case"3d":e.push("threeDGeneration");break;case"realtime_audio":e.push("realtimeAudio");break}return e.includes("textGeneration")&&e.push("smallModel"),[...new Set(e.length>0?e:["textGeneration"])]}function TA(t){switch(t){case"openai-chat":case"openai-responses":case"anthropic-messages":case"volcengine-responses":return t;default:return}}function AA(t,e){switch(t){case"imageUnderstanding":case"videoUnderstanding":case"imageGeneration":case"videoGeneration":case"threeDGeneration":case"stt":case"tts":case"voiceClone":case"musicGeneration":case"realtimeAudio":case"realtimeVideo":case"embedding":return;default:return TA(e)}}function xA(t){switch(t){case"imageUnderstanding":case"videoUnderstanding":return["vision"];case"imageGeneration":case"videoGeneration":case"threeDGeneration":case"stt":case"tts":case"voiceClone":case"musicGeneration":case"realtimeAudio":case"realtimeVideo":case"embedding":return["media"];default:return[]}}var Pn,Ho,xn,We=Mo(()=>{"use strict";D();lp();Pn=["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"],Ho=class{keyPool;coreProviderRegistry=new vA;providerVariantResolver=new kA(this.coreProviderRegistry);models=new Map;modelEnabledOverrides=new Map;bindings={};settingsPath;changeListeners=[];constructor(e){this.settingsPath=de(),this.keyPool=new Fo(e?.providers),e?.models&&this.loadModelState(e.models),e?.bindings&&(this.bindings={...e.bindings}),this.hydrateCatalogModels()}getActiveModel(e){let r=this.bindings[e];if(!r)return null;let n=this.models.get(r);if(!n||!n.enabled)return null;let o=this.resolveTechnicalVariant(n,e),s=o?.provider??n.provider,i=o?.nativeModelId??n.nativeModelId??n.model,a=this.acquireKeyForProviderVariant(s);if(!a)return null;let{keyHandle:c,keyProviderId:l}=a,d=this.getProviderBaseUrl(s),u=this.getProviderBaseUrl(l);return{provider:s,model:i,apiKey:c.apiKey,baseUrl:d??(n.provider===s?n.baseUrl:void 0)??u,keyHandle:c}}peekActiveModel(e){let r=this.bindings[e];return r?this.models.get(r)??null:null}isAvailable(e){let r=this.peekActiveModel(e);return!!r?.enabled&&this.hasAvailableKeyForProviderVariant(r.provider)}resolveModelForPurpose(e){let r=this.peekActiveModel(e);return r?r.model:null}addProvider(e,r){this.keyPool.addProvider(e,r),this.emitChange()}removeProvider(e){this.keyPool.removeProvider(e);for(let[r,n]of this.models)n.provider===e&&this.removeModel(r);this.emitChange()}addKey(e,r,n){let o=this.keyPool.addKey(e,r,n);return this.emitChange(),o}removeKey(e){this.keyPool.removeKey(e),this.emitChange()}updateKey(e,r){this.keyPool.updateKey(e,r),this.emitChange()}setKeyHealth(e,r){this.keyPool.setKeyHealth(e,r),this.emitChange()}setStrategy(e,r){this.keyPool.setStrategy(e,r),this.emitChange()}addModel(e){let r=e.id??`${e.provider}:${e.model}`;return this.models.set(r,{...e,id:r,enabled:this.modelEnabledOverrides.get(r)??e.enabled}),this.emitChange(),r}replaceCatalogModels(e){let r=new Map;for(let n of e)r.set(n.id,{...n,enabled:this.modelEnabledOverrides.get(n.id)??n.enabled});for(let n of this.modelEnabledOverrides.keys())r.has(n)||this.modelEnabledOverrides.delete(n);this.models=r;for(let[n,o]of Object.entries(this.bindings))o&&!this.models.has(o)&&delete this.bindings[n];this.emitChange()}replaceProviderModels(e,r){let n=new Map;for(let[s,i]of this.models)i.provider!==e&&n.set(s,i);for(let s of r)s.provider===e&&n.set(s.id,{...s,enabled:this.modelEnabledOverrides.get(s.id)??s.enabled});let o=`${e}:`;for(let s of this.modelEnabledOverrides.keys())s.startsWith(o)&&!n.has(s)&&this.modelEnabledOverrides.delete(s);this.models=n;for(let[s,i]of Object.entries(this.bindings))i&&!this.models.has(i)&&delete this.bindings[s];this.emitChange()}migrateModelIds(e){for(let[r,n]of e){let o=this.modelEnabledOverrides.get(r);o!==void 0&&!this.modelEnabledOverrides.has(n)&&this.modelEnabledOverrides.set(n,o),this.modelEnabledOverrides.delete(r);for(let[s,i]of Object.entries(this.bindings))i===r&&(this.bindings[s]=n)}this.emitChange()}removeModel(e){this.models.delete(e),this.modelEnabledOverrides.delete(e);for(let[r,n]of Object.entries(this.bindings))n===e&&delete this.bindings[r];this.emitChange()}enableModel(e){let r=this.models.get(e);r&&(r.enabled=!0),this.modelEnabledOverrides.set(e,!0),this.emitChange()}disableModel(e){let r=this.models.get(e);r&&(r.enabled=!1),this.modelEnabledOverrides.set(e,!1),this.emitChange()}listModels(e){let r=[...this.models.values()];return e?.purpose&&(r=r.filter(n=>n.purposes.includes(e.purpose))),e?.provider&&(r=r.filter(n=>n.provider===e.provider)),e?.enabledOnly&&(r=r.filter(n=>n.enabled)),r}getModel(e){return this.models.get(e)??null}setBinding(e,r){let n=this.models.get(r);if(!n)throw new Error(`Model "${r}" not found in pool.`);if(!n.purposes.includes(e))throw new Error(`Model "${r}" does not support purpose "${e}".`);this.bindings[e]=r,this.emitChange()}removeBinding(e){delete this.bindings[e],this.emitChange()}getBinding(e){let r=this.bindings[e];return r?this.models.get(r)??null:null}getAllBindings(){let e={};for(let r of Pn){let n=this.bindings[r];e[r]=n?this.models.get(n)??null:null}return e}getProviderStatus(e){return this.keyPool.getPoolStatus(e)}getAllProviderStatus(){return this.keyPool.getAllStatus()}save(){let e={};try{he.existsSync(this.settingsPath)&&(e=JSON.parse(he.readFileSync(this.settingsPath,"utf-8")))}catch{e={}}delete e.provider,delete e.apiKey,delete e.model,delete e.baseUrl;let r={...e,providers:this.keyPool.exportConfig(),models:this.exportModelState(),bindings:{...this.bindings}},n=this.settingsPath.replace(/[/\\][^/\\]+$/,"");he.existsSync(n)||he.mkdirSync(n,{recursive:!0}),he.writeFileSync(this.settingsPath,JSON.stringify(r,null,2),"utf-8")}load(){try{if(SA(this.settingsPath),!he.existsSync(this.settingsPath))return!1;let e=he.readFileSync(this.settingsPath,"utf-8"),r=JSON.parse(e);return r.providers&&this.keyPool.reloadConfig(r.providers),this.models.clear(),this.modelEnabledOverrides.clear(),r.models&&this.loadModelState(r.models),this.hydrateCatalogModels(),this.bindings=r.bindings??{},this.emitChange(),!0}catch{return!1}}exportConfig(){return{providers:this.keyPool.exportConfig(),models:this.exportModelState(),bindings:{...this.bindings}}}getTunable(e){try{if(!he.existsSync(this.settingsPath))return;let r=he.readFileSync(this.settingsPath,"utf-8");return JSON.parse(r).tunables?.[e]}catch{return}}getModelInfo(e,r){let n=this.listModels({provider:e}).find(o=>o.model===r);if(n)return{id:n.model,name:n.displayName,contextWindow:n.contextWindow,maxOutput:n.maxOutput,streamRequired:n.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(r=>!!this.keyPool.getPoolStatus(r)?.keys.some(o=>o.enabled))}hasAvailableKeyForProviderVariant(e){return this.providerVariantKeyCandidates(e).some(r=>this.keyPool.hasAvailableKey(r))}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(r=>({id:r.model,name:r.displayName,contextWindow:r.contextWindow,maxOutput:r.maxOutput,streamRequired:r.streamRequired}))}))}getKnownProviderDef(e){let r=this.coreProviderRegistry.getProvider(e);return r?{id:r.id,name:r.name,transport:r.transport,baseUrl:r.baseUrl,defaultModel:r.defaultModel,group:r.group,models:this.coreProviderRegistry.listModels(r.id).map(n=>({id:n.aliases?.[0]??n.id,name:n.name,contextWindow:n.contextWindow,maxOutput:n.maxOutput,streamRequired:n.streamRequired,vision:n.vision,mediaType:n.mediaType}))}:null}resolveProviderApiKey(e){return this.getKeyForProvider(e)??void 0}onChange(e){return this.changeListeners.push(e),()=>{let r=this.changeListeners.indexOf(e);r>=0&&this.changeListeners.splice(r,1)}}getKeyForProvider(e){let n=this.acquireKeyForProviderVariant(e)?.keyHandle;if(!n)return null;let o=n.apiKey;return n.release({success:!0}),o}snapshotProviderKeys(){let e={};for(let r of this.keyPool.getAllStatus()){let n=this.getKeyForProvider(r.providerId);n&&(e[r.providerId]=n)}return e}getProviderBaseUrl(e){return this.coreProviderRegistry.getProvider(e)?.baseUrl??this.keyPool.getPoolStatus(e)?.baseUrl}acquireKeyForProviderVariant(e){for(let r of this.providerVariantKeyCandidates(e)){let n=this.keyPool.acquireKey(r);if(n)return{keyHandle:n,keyProviderId:r}}return null}resolveTechnicalVariant(e,r){let n=this.providerVariantKeyCandidates(e.provider).filter(s=>this.hasConfiguredKeyForProviderVariant(s));if(n.length===0)return;let o=this.providerVariantResolver.resolveBest({publicModel:e.model,requestedProtocol:AA(r,e.transport),capabilities:xA(r),purpose:r,userPreference:{providerIds:n}});if(o)return{provider:o.provider,nativeModelId:o.nativeModelId}}providerVariantKeyCandidates(e){let r=[e],n=this.coreProviderRegistry.getProvider(e),o=n?.group??n?.id??e;for(let s of this.coreProviderRegistry.listProviders())(s.group??s.id)===o&&r.push(s.id);return o!==e&&r.push(o),[...new Set(r)]}loadModelState(e){for(let r of e)typeof r.id!="string"||!r.id||typeof r.enabled=="boolean"&&this.modelEnabledOverrides.set(r.id,r.enabled)}hydrateCatalogModels(){let e=[];for(let n of this.coreProviderRegistry.listProviders())for(let o of this.coreProviderRegistry.listModels(n.id)){let s=o.aliases?.[0]??o.id,i=`${n.id}:${s}`;e.push({id:i,provider:n.id,model:s,displayName:o.name,purposes:pp(o),baseUrl:n.baseUrl,enabled:this.modelEnabledOverrides.get(i)??!1,nativeModelId:o.id,transport:n.transport,contextWindow:o.contextWindow,maxOutput:o.maxOutput,streamRequired:o.streamRequired,capabilities:[...o.toolCall?["toolCall"]:[],...o.reasoning?["reasoning"]:[],...o.vision?["vision"]:[],...o.mediaType?[o.mediaType]:[]],pricing:{inputPer1M:o.costInput,outputPer1M:o.costOutput,cacheReadPer1M:o.costCacheRead,cacheWritePer1M:o.costCacheWrite}})}let r=new Map;for(let n of e)r.set(n.id,n);this.models=r}exportModelState(){let e=new Map;for(let[r,n]of this.modelEnabledOverrides)e.set(r,n);for(let r of this.models.values())e.set(r.id,r.enabled);return[...e.entries()].map(([r,n])=>({id:r,enabled:n}))}emitChange(){for(let e of this.changeListeners)try{e()}catch{}}},xn=null});var Um={};ku(Um,{resolveToolEligibility:()=>hC});function mC(t,e){if(pC.some(r=>r.test(t)))return!0;if(e)for(let r of e)try{if(new RegExp(r,"i").test(t))return!0}catch{}return!1}function gC(t,e){let r=t.function.name,n=t.meta,o=[];return e.blockedToolNames?.includes(r)?(o.push("policy_blocked"),{level:5,reasons:o}):n?.isReadOnly?(o.push("always_allowed"),{level:1,reasons:o}):n?.requiresApproval?(o.push("approval_required"),{level:4,reasons:o}):n?.isDangerous||mC(r,e.dangerousPatterns)?(o.push("dangerous_tool"),{level:3,reasons:o}):{level:2,reasons:o}}function fC(t){switch(t){case 1:return"eligible";case 2:return"eligible";case 3:return"dangerous-notify";case 4:return"approval-required";case 5:return"blocked-by-policy"}}function hC(t,e={}){let r=new Map,n=[],o=[],s=[];for(let i of t){let a=i.function.name,{level:c,reasons:l}=gC(i,e),d=fC(c),u={toolName:a,status:d,permissionLevel:c,approvalRequired:c===4,reasonCodes:l};r.set(a,u),c===5?o.push(u):(n.push(i),c===4&&s.push(u))}return{eligibleTools:n,blockedTools:o,approvalRequiredTools:s,eligibilityByName:r}}var pC,Fm=Mo(()=>{"use strict";pC=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});import{createRequire as lU}from"node:module";import{createInterface as bT}from"node:readline";var Ur=class{messageHandler=null;closeHandler=null;verbose;constructor(e){this.verbose=e?.verbose??!1}onMessage(e){this.messageHandler=e}onClose(e){this.closeHandler=e}send(e){process.stdout.write(`${JSON.stringify(e)}
|
|
2
|
+
var yT=Object.defineProperty;var Mo=(t,e)=>()=>(t&&(e=t(t=0)),e);var ku=(t,e)=>{for(var r in e)yT(t,r,{get:e[r],enumerable:!0})};import{homedir as uA}from"node:os";import{join as te}from"node:path";import{existsSync as pA}from"node:fs";function F(){return process.env.QLOGICAGENT_HOME||te(uA(),je)}function qu(){return te(F(),"settings.json")}function Wu(){return te(F(),"memory","memories.db")}function Br(){let t=process.env.QLOGIC_LLMROUTER_USER_ID?.trim();if(t)return t;let e=process.env.QLOGIC_IMPLICIT_OWNER_ID?.trim();if(e)return e;let r=process.env.QLOGIC_DEVICE_ID?.trim();return r?`oc_${r}`:"oc_local"}function mA(t){let e=t.trim();if(!e)throw new Error("ownerUserId is required for profile-scoped storage");return encodeURIComponent(e).replace(/\./g,"%2E")}function W(t=Br()){return te(F(),"profiles",mA(t))}function Gu(t=Br()){return te(W(t),"memory")}function Ku(){return te(W(),"plugins")}function yt(){return te(W(),"skills")}function de(){return te(W(),"settings.json")}function zu(){return te(F(),"cache")}function Vu(){return te(W(),"plugin-cache")}function Xu(){return te(W(),"mcp.json")}function Yu(){return te(W(),"marketplace.json")}function Ju(){return te(W(),"rules")}function re(t){if(!t)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return te(t,je)}function _t(t){return te(re(t),"skills")}function vr(t){return te(re(t),"INSTRUCTIONS.md")}function ir(t){return te(re(t),"rules")}function Mt(t){return te(re(t),"sessions")}function Qu(t,e){let r=te(re(t),"checkpoints");return e?te(r,e):r}function Zu(t){return te(t,je,"hooks")}function ep(t,e){return t.filter(r=>r!==e&&pA(te(r,je,"skills")))}var je,D=Mo(()=>{"use strict";je=".qlogicagent"});var Fo,lp=Mo(()=>{"use strict";Fo=class{pools=new Map;runtimeStates=new Map;constructor(e){if(e)for(let r of e){this.pools.set(r.providerId,r);for(let n of r.keys)this.runtimeStates.set(n.id,this.createInitialState())}}acquireKey(e){let r=this.pools.get(e);if(!r||r.keys.length===0)return null;let n=Date.now(),o=this.getHealthyCandidates(r,n);if(o.length===0)return null;let s=this.selectByStrategy(o,r.strategy,n);if(!s)return null;let i=this.runtimeStates.get(s.id);return i.inFlight++,i.totalRequests++,i.lastUsedAt=n,i.requestTimestamps.push(n),{keyId:s.id,apiKey:s.key,providerId:e,release:a=>this.releaseKey(s.id,a)}}releaseKey(e,r){let n=this.runtimeStates.get(e);if(n)if(n.inFlight=Math.max(0,n.inFlight-1),r.success)n.consecutiveErrors=0,n.healthStatus="healthy",r.tokens&&(n.totalTokens+=r.tokens,n.tokenCounts.push(r.tokens));else if(n.consecutiveErrors++,n.lastErrorAt=Date.now(),r.errorCode===429){let o=r.retryAfter?r.retryAfter*1e3:3e4;n.cooldownUntil=Date.now()+o,n.healthStatus="cooldown"}else n.consecutiveErrors>=5?(n.cooldownUntil=Date.now()+6e4,n.healthStatus="cooldown"):n.consecutiveErrors>=3&&(n.healthStatus="degraded")}addProvider(e,r){this.pools.has(e)||this.pools.set(e,{providerId:e,baseUrl:r?.baseUrl,strategy:r?.strategy??"weighted-round-robin",keys:[],rateLimit:r?.rateLimit})}removeProvider(e){let r=this.pools.get(e);if(r){for(let n of r.keys)this.runtimeStates.delete(n.id);this.pools.delete(e)}}addKey(e,r,n){let o=this.pools.get(e);o||(o={providerId:e,strategy:"weighted-round-robin",keys:[]},this.pools.set(e,o));let s=n?.id??crypto.randomUUID(),i={id:s,key:r,label:n?.label,weight:n?.weight??1,enabled:n?.enabled??!0};return o.keys.push(i),this.runtimeStates.set(s,this.createInitialState()),s}removeKey(e){for(let r of this.pools.values()){let n=r.keys.findIndex(o=>o.id===e);if(n!==-1){r.keys.splice(n,1),this.runtimeStates.delete(e);return}}}updateKey(e,r){for(let n of this.pools.values()){let o=n.keys.find(s=>s.id===e);if(o){if(r.label!==void 0&&(o.label=r.label),r.weight!==void 0&&(o.weight=r.weight),r.enabled!==void 0){o.enabled=r.enabled;let s=this.runtimeStates.get(e);s&&(s.healthStatus=r.enabled?"healthy":"disabled")}return}}}setKeyHealth(e,r){let n=this.runtimeStates.get(e);n&&(n.healthStatus=r)}setStrategy(e,r){let n=this.pools.get(e);n&&(n.strategy=r)}setRateLimit(e,r){let n=this.pools.get(e);n&&(n.rateLimit=r)}getPoolStatus(e){let r=this.pools.get(e);return r?this.buildPoolStatus(r):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 r=this.pools.get(e);return r?this.getHealthyCandidates(r,Date.now()).length>0:!1}exportConfig(){return[...this.pools.values()]}reloadConfig(e){let r=new Set;for(let n of e){this.pools.set(n.providerId,n);for(let o of n.keys)r.add(o.id),this.runtimeStates.has(o.id)||this.runtimeStates.set(o.id,this.createInitialState())}for(let n of[...this.pools.keys()])e.some(o=>o.providerId===n)||this.pools.delete(n);for(let n of[...this.runtimeStates.keys()])r.has(n)||this.runtimeStates.delete(n)}createInitialState(){return{inFlight:0,totalRequests:0,totalTokens:0,lastUsedAt:0,lastErrorAt:0,consecutiveErrors:0,cooldownUntil:0,healthStatus:"healthy",requestTimestamps:[],tokenCounts:[]}}getHealthyCandidates(e,r){let n=[];for(let o of e.keys){if(!o.enabled)continue;let s=this.runtimeStates.get(o.id);if(s){if(s.healthStatus==="cooldown")if(r>=s.cooldownUntil)s.healthStatus="healthy",s.consecutiveErrors=0;else continue;s.healthStatus!=="disabled"&&(e.rateLimit?.rpm&&(this.pruneWindow(s.requestTimestamps,r),s.requestTimestamps.length>=e.rateLimit.rpm*.9)||e.rateLimit?.tpm&&(this.pruneWindow(s.tokenCounts,r),s.tokenCounts.reduce((a,c)=>a+c,0)>=e.rateLimit.tpm*.9)||n.push(o))}}return n}selectByStrategy(e,r,n){if(e.length===0)return null;if(e.length===1)return e[0];switch(r){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 r=e.reduce((o,s)=>o+s.weight,0),n=Math.random()*r;for(let o of e)if(n-=o.weight,n<=0)return o;return e[e.length-1]}leastBusy(e){let r=1/0,n=e[0];for(let o of e){let i=this.runtimeStates.get(o.id)?.inFlight??0;(i<r||i===r&&o.weight>n.weight)&&(r=i,n=o)}return n}pruneWindow(e,r){let n=r-6e4;for(;e.length>0&&e[0]<n;)e.shift()}buildPoolStatus(e){return{providerId:e.providerId,baseUrl:e.baseUrl,strategy:e.strategy,rateLimit:e.rateLimit,keys:e.keys.map(r=>{let n=this.runtimeStates.get(r.id)??this.createInitialState();return{...r,inFlight:n.inFlight,totalRequests:n.totalRequests,totalTokens:n.totalTokens,lastUsedAt:n.lastUsedAt,lastErrorAt:n.lastErrorAt,consecutiveErrors:n.consecutiveErrors,cooldownUntil:n.cooldownUntil,healthStatus:r.enabled?n.healthStatus:"disabled"}})}}}});var mp={};ku(mp,{ALL_PURPOSES:()=>Pn,ModelRegistry:()=>Ho,deriveModelPurposes:()=>pp,getModelRegistry:()=>M,resetModelRegistry:()=>RA});import*as he from"node:fs";import{ProviderRegistry as vA,ProviderVariantResolver as kA}from"@xiaozhiclaw/provider-core";function M(){return xn||(xn=new Ho,xn.load()),xn}function RA(){xn=null}function SA(t){let e=qu();if(t===e||!he.existsSync(e))return;let r=dp(e);if(!up(r))return;let n=dp(t);if(up(n))return;let o={...r,...n,providers:r.providers,models:r.models??n.models,bindings:wA(n)?n.bindings:r.bindings,migrations:{...Va(r.migrations)?r.migrations:{},...Va(n.migrations)?n.migrations:{},legacyGlobalSettingsImportedAt:new Date().toISOString()}},s=t.replace(/[/\\][^/\\]+$/,"");he.existsSync(s)||he.mkdirSync(s,{recursive:!0}),he.writeFileSync(t,JSON.stringify(o,null,2),"utf-8")}function dp(t){try{return JSON.parse(he.readFileSync(t,"utf-8"))}catch{return{}}}function up(t){return Array.isArray(t.providers)&&t.providers.length>0}function wA(t){return Va(t.bindings)&&Object.keys(t.bindings).length>0}function Va(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function pp(t){let e=[];switch((!t.mediaType||t.mediaType==="image_understanding"||t.mediaType==="video_understanding")&&e.push("textGeneration"),(t.vision||t.mediaType==="image_understanding")&&e.push("imageUnderstanding"),t.mediaType==="video_understanding"&&e.push("videoUnderstanding"),t.mediaType){case"image":e.push("imageGeneration");break;case"video":e.push("videoGeneration");break;case"tts":e.push("tts");break;case"stt":e.push("stt");break;case"music":case"music_realtime":e.push("musicGeneration");break;case"voice_clone":e.push("voiceClone");break;case"embedding":e.push("embedding");break;case"3d":e.push("threeDGeneration");break;case"realtime_audio":e.push("realtimeAudio");break}return e.includes("textGeneration")&&e.push("smallModel"),[...new Set(e.length>0?e:["textGeneration"])]}function TA(t){switch(t){case"openai-chat":case"openai-responses":case"anthropic-messages":case"volcengine-responses":return t;default:return}}function AA(t,e){switch(t){case"imageUnderstanding":case"videoUnderstanding":case"imageGeneration":case"videoGeneration":case"threeDGeneration":case"stt":case"tts":case"voiceClone":case"musicGeneration":case"realtimeAudio":case"realtimeVideo":case"embedding":return;default:return TA(e)}}function xA(t){switch(t){case"imageUnderstanding":case"videoUnderstanding":return["vision"];case"imageGeneration":case"videoGeneration":case"threeDGeneration":case"stt":case"tts":case"voiceClone":case"musicGeneration":case"realtimeAudio":case"realtimeVideo":case"embedding":return["media"];default:return[]}}var Pn,Ho,xn,We=Mo(()=>{"use strict";D();lp();Pn=["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"],Ho=class{keyPool;coreProviderRegistry=new vA;providerVariantResolver=new kA(this.coreProviderRegistry);models=new Map;modelEnabledOverrides=new Map;bindings={};settingsPath;changeListeners=[];constructor(e){this.settingsPath=de(),this.keyPool=new Fo(e?.providers),e?.models&&this.loadModelState(e.models),e?.bindings&&(this.bindings={...e.bindings}),this.hydrateCatalogModels()}getActiveModel(e){let r=this.bindings[e];if(!r)return null;let n=this.models.get(r);if(!n||!n.enabled)return null;let o=this.resolveTechnicalVariant(n,e),s=o?.provider??n.provider,i=o?.nativeModelId??n.nativeModelId??n.model,a=this.acquireKeyForProviderVariant(s);if(!a)return null;let{keyHandle:c,keyProviderId:l}=a,d=this.getProviderBaseUrl(s),u=this.getProviderBaseUrl(l);return{provider:s,model:i,apiKey:c.apiKey,baseUrl:d??(n.provider===s?n.baseUrl:void 0)??u,keyHandle:c}}peekActiveModel(e){let r=this.bindings[e];return r?this.models.get(r)??null:null}isAvailable(e){let r=this.peekActiveModel(e);return!!r?.enabled&&this.hasAvailableKeyForProviderVariant(r.provider)}resolveModelForPurpose(e){let r=this.peekActiveModel(e);return r?r.model:null}addProvider(e,r){this.keyPool.addProvider(e,r),this.emitChange()}removeProvider(e){this.keyPool.removeProvider(e);for(let[r,n]of this.models)n.provider===e&&this.removeModel(r);this.emitChange()}addKey(e,r,n){let o=this.keyPool.addKey(e,r,n);return this.emitChange(),o}removeKey(e){this.keyPool.removeKey(e),this.emitChange()}updateKey(e,r){this.keyPool.updateKey(e,r),this.emitChange()}setKeyHealth(e,r){this.keyPool.setKeyHealth(e,r),this.emitChange()}setStrategy(e,r){this.keyPool.setStrategy(e,r),this.emitChange()}addModel(e){let r=e.id??`${e.provider}:${e.model}`;return this.models.set(r,{...e,id:r,enabled:this.modelEnabledOverrides.get(r)??e.enabled}),this.emitChange(),r}replaceCatalogModels(e){let r=new Map;for(let n of e)r.set(n.id,{...n,enabled:this.modelEnabledOverrides.get(n.id)??n.enabled});for(let n of this.modelEnabledOverrides.keys())r.has(n)||this.modelEnabledOverrides.delete(n);this.models=r;for(let[n,o]of Object.entries(this.bindings))o&&!this.models.has(o)&&delete this.bindings[n];this.emitChange()}replaceProviderModels(e,r){let n=new Map;for(let[s,i]of this.models)i.provider!==e&&n.set(s,i);for(let s of r)s.provider===e&&n.set(s.id,{...s,enabled:this.modelEnabledOverrides.get(s.id)??s.enabled});let o=`${e}:`;for(let s of this.modelEnabledOverrides.keys())s.startsWith(o)&&!n.has(s)&&this.modelEnabledOverrides.delete(s);this.models=n;for(let[s,i]of Object.entries(this.bindings))i&&!this.models.has(i)&&delete this.bindings[s];this.emitChange()}migrateModelIds(e){for(let[r,n]of e){let o=this.modelEnabledOverrides.get(r);o!==void 0&&!this.modelEnabledOverrides.has(n)&&this.modelEnabledOverrides.set(n,o),this.modelEnabledOverrides.delete(r);for(let[s,i]of Object.entries(this.bindings))i===r&&(this.bindings[s]=n)}this.emitChange()}removeModel(e){this.models.delete(e),this.modelEnabledOverrides.delete(e);for(let[r,n]of Object.entries(this.bindings))n===e&&delete this.bindings[r];this.emitChange()}enableModel(e){let r=this.models.get(e);r&&(r.enabled=!0),this.modelEnabledOverrides.set(e,!0),this.emitChange()}disableModel(e){let r=this.models.get(e);r&&(r.enabled=!1),this.modelEnabledOverrides.set(e,!1),this.emitChange()}listModels(e){let r=[...this.models.values()];return e?.purpose&&(r=r.filter(n=>n.purposes.includes(e.purpose))),e?.provider&&(r=r.filter(n=>n.provider===e.provider)),e?.enabledOnly&&(r=r.filter(n=>n.enabled)),r}getModel(e){return this.models.get(e)??null}setBinding(e,r){let n=this.models.get(r);if(!n)throw new Error(`Model "${r}" not found in pool.`);if(!n.purposes.includes(e))throw new Error(`Model "${r}" does not support purpose "${e}".`);this.bindings[e]=r,this.emitChange()}removeBinding(e){delete this.bindings[e],this.emitChange()}getBinding(e){let r=this.bindings[e];return r?this.models.get(r)??null:null}getAllBindings(){let e={};for(let r of Pn){let n=this.bindings[r];e[r]=n?this.models.get(n)??null:null}return e}getProviderStatus(e){return this.keyPool.getPoolStatus(e)}getAllProviderStatus(){return this.keyPool.getAllStatus()}save(){let e={};try{he.existsSync(this.settingsPath)&&(e=JSON.parse(he.readFileSync(this.settingsPath,"utf-8")))}catch{e={}}delete e.provider,delete e.apiKey,delete e.model,delete e.baseUrl;let r={...e,providers:this.keyPool.exportConfig(),models:this.exportModelState(),bindings:{...this.bindings}},n=this.settingsPath.replace(/[/\\][^/\\]+$/,"");he.existsSync(n)||he.mkdirSync(n,{recursive:!0}),he.writeFileSync(this.settingsPath,JSON.stringify(r,null,2),"utf-8")}load(){try{if(SA(this.settingsPath),!he.existsSync(this.settingsPath))return!1;let e=he.readFileSync(this.settingsPath,"utf-8"),r=JSON.parse(e);return r.providers&&this.keyPool.reloadConfig(r.providers),this.models.clear(),this.modelEnabledOverrides.clear(),r.models&&this.loadModelState(r.models),this.hydrateCatalogModels(),this.bindings=r.bindings??{},this.emitChange(),!0}catch{return!1}}exportConfig(){return{providers:this.keyPool.exportConfig(),models:this.exportModelState(),bindings:{...this.bindings}}}getTunable(e){try{if(!he.existsSync(this.settingsPath))return;let r=he.readFileSync(this.settingsPath,"utf-8");return JSON.parse(r).tunables?.[e]}catch{return}}getModelInfo(e,r){let n=this.listModels({provider:e}).find(o=>o.model===r);if(n)return{id:n.model,name:n.displayName,contextWindow:n.contextWindow,maxOutput:n.maxOutput,streamRequired:n.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(r=>!!this.keyPool.getPoolStatus(r)?.keys.some(o=>o.enabled))}hasAvailableKeyForProviderVariant(e){return this.providerVariantKeyCandidates(e).some(r=>this.keyPool.hasAvailableKey(r))}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(r=>({id:r.model,name:r.displayName,contextWindow:r.contextWindow,maxOutput:r.maxOutput,streamRequired:r.streamRequired}))}))}getKnownProviderDef(e){let r=this.coreProviderRegistry.getProvider(e);return r?{id:r.id,name:r.name,transport:r.transport,baseUrl:r.baseUrl,defaultModel:r.defaultModel,group:r.group,models:this.coreProviderRegistry.listModels(r.id).map(n=>({id:n.aliases?.[0]??n.id,name:n.name,contextWindow:n.contextWindow,maxOutput:n.maxOutput,streamRequired:n.streamRequired,vision:n.vision,mediaType:n.mediaType}))}:null}resolveProviderApiKey(e){return this.getKeyForProvider(e)??void 0}onChange(e){return this.changeListeners.push(e),()=>{let r=this.changeListeners.indexOf(e);r>=0&&this.changeListeners.splice(r,1)}}getKeyForProvider(e){let n=this.acquireKeyForProviderVariant(e)?.keyHandle;if(!n)return null;let o=n.apiKey;return n.release({success:!0}),o}snapshotProviderKeys(){let e={};for(let r of this.keyPool.getAllStatus()){let n=this.getKeyForProvider(r.providerId);n&&(e[r.providerId]=n)}return e}getProviderBaseUrl(e){return this.coreProviderRegistry.getProvider(e)?.baseUrl??this.keyPool.getPoolStatus(e)?.baseUrl}acquireKeyForProviderVariant(e){for(let r of this.providerVariantKeyCandidates(e)){let n=this.keyPool.acquireKey(r);if(n)return{keyHandle:n,keyProviderId:r}}return null}resolveTechnicalVariant(e,r){let n=this.providerVariantKeyCandidates(e.provider).filter(s=>this.hasConfiguredKeyForProviderVariant(s));if(n.length===0)return;let o=this.providerVariantResolver.resolveBest({publicModel:e.model,requestedProtocol:AA(r,e.transport),capabilities:xA(r),purpose:r,userPreference:{providerIds:n}});if(o)return{provider:o.provider,nativeModelId:o.nativeModelId}}providerVariantKeyCandidates(e){let r=[e],n=this.coreProviderRegistry.getProvider(e),o=n?.group??n?.id??e;for(let s of this.coreProviderRegistry.listProviders())(s.group??s.id)===o&&r.push(s.id);return o!==e&&r.push(o),[...new Set(r)]}loadModelState(e){for(let r of e)typeof r.id!="string"||!r.id||typeof r.enabled=="boolean"&&this.modelEnabledOverrides.set(r.id,r.enabled)}hydrateCatalogModels(){let e=[];for(let n of this.coreProviderRegistry.listProviders())for(let o of this.coreProviderRegistry.listModels(n.id)){let s=o.aliases?.[0]??o.id,i=`${n.id}:${s}`;e.push({id:i,provider:n.id,model:s,displayName:o.name,purposes:pp(o),baseUrl:n.baseUrl,enabled:this.modelEnabledOverrides.get(i)??!1,nativeModelId:o.id,transport:n.transport,contextWindow:o.contextWindow,maxOutput:o.maxOutput,streamRequired:o.streamRequired,capabilities:[...o.toolCall?["toolCall"]:[],...o.reasoning?["reasoning"]:[],...o.vision?["vision"]:[],...o.mediaType?[o.mediaType]:[]],pricing:{inputPer1M:o.costInput,outputPer1M:o.costOutput,cacheReadPer1M:o.costCacheRead,cacheWritePer1M:o.costCacheWrite}})}let r=new Map;for(let n of e)r.set(n.id,n);this.models=r}exportModelState(){let e=new Map;for(let[r,n]of this.modelEnabledOverrides)e.set(r,n);for(let r of this.models.values())e.set(r.id,r.enabled);return[...e.entries()].map(([r,n])=>({id:r,enabled:n}))}emitChange(){for(let e of this.changeListeners)try{e()}catch{}}},xn=null});var Um={};ku(Um,{resolveToolEligibility:()=>hC});function mC(t,e){if(pC.some(r=>r.test(t)))return!0;if(e)for(let r of e)try{if(new RegExp(r,"i").test(t))return!0}catch{}return!1}function gC(t,e){let r=t.function.name,n=t.meta,o=[];return e.blockedToolNames?.includes(r)?(o.push("policy_blocked"),{level:5,reasons:o}):n?.isReadOnly?(o.push("always_allowed"),{level:1,reasons:o}):n?.requiresApproval?(o.push("approval_required"),{level:4,reasons:o}):n?.isDangerous||mC(r,e.dangerousPatterns)?(o.push("dangerous_tool"),{level:3,reasons:o}):{level:2,reasons:o}}function fC(t){switch(t){case 1:return"eligible";case 2:return"eligible";case 3:return"dangerous-notify";case 4:return"approval-required";case 5:return"blocked-by-policy"}}function hC(t,e={}){let r=new Map,n=[],o=[],s=[];for(let i of t){let a=i.function.name,{level:c,reasons:l}=gC(i,e),d=fC(c),u={toolName:a,status:d,permissionLevel:c,approvalRequired:c===4,reasonCodes:l};r.set(a,u),c===5?o.push(u):(n.push(i),c===4&&s.push(u))}return{eligibleTools:n,blockedTools:o,approvalRequiredTools:s,eligibilityByName:r}}var pC,Fm=Mo(()=>{"use strict";pC=[/^(?:bash|shell|exec|terminal|run_command)$/i,/^(?:write_file|delete_file|move_file|create_directory)$/i,/^(?:git_push|git_reset|git_force)$/i]});import{createRequire as dU}from"node:module";import{createInterface as bT}from"node:readline";var Ur=class{messageHandler=null;closeHandler=null;verbose;constructor(e){this.verbose=e?.verbose??!1}onMessage(e){this.messageHandler=e}onClose(e){this.closeHandler=e}send(e){process.stdout.write(`${JSON.stringify(e)}
|
|
3
3
|
`)}start(){process.stdin.on("data",r=>{process.stderr.write(`[transport] raw stdin data (${r.length} bytes): ${r.toString().slice(0,300)}
|
|
4
4
|
`)});let e=bT({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});e.on("line",r=>{let n=r.trim();if(n){process.stderr.write(`[transport] line: ${n.slice(0,300)}
|
|
5
5
|
`);try{let o=JSON.parse(n);this.messageHandler?.(o)}catch{this.log(`invalid JSON on stdin: ${n.slice(0,200)}`)}}}),e.on("close",()=>{this.closeHandler?.()})}close(){}log(e){this.verbose&&process.stderr.write(`[transport] ${e}
|
|
@@ -32,10 +32,10 @@ Assistant response:
|
|
|
32
32
|
Today's date: {today}
|
|
33
33
|
|
|
34
34
|
Respond ONLY with a JSON array (or empty array [] if nothing worth extracting):
|
|
35
|
-
[{"text": "...", "category": "personal_fact|preference|event|lesson", "importance": 0.5-0.9, "eventDate": "YYYY-MM-DD or null"}]`;async function HT(t,e,r){let n=FT.replace("{user_message}",t.userMessage.slice(0,1e3)).replace("{assistant_message}",t.assistantMessage.slice(0,500)).replace("{today}",r);try{let o=await e(n);if(!o)return[];let s=o.replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"").trim(),i=JSON.parse(s);return Array.isArray(i)?i.filter(a=>a.text&&typeof a.text=="string"&&a.text.length>=5&&a.text.length<=500&&a.category).map(a=>({text:a.text.trim(),category:BT(a.category),importance:Math.min(.9,Math.max(.3,Number(a.importance)||.5)),eventDate:typeof a.eventDate=="string"?a.eventDate:void 0})).slice(0,3):[]}catch{return[]}}function BT(t){return new Set(["personal_fact","preference","event","lesson","pattern","decision"]).has(t)?t:"personal_fact"}async function Nu(t,e){if(!oa(t.userMessage))return 0;if(e.log.debug(`implicit-extract: signal detected in user message (${t.userMessage.slice(0,50)}...)`),!e.llmExtract)return e.log.debug("implicit-extract: no LLM extractor configured, skipping Layer 2"),0;let r=new Date().toISOString().slice(0,10),n=await HT(t,e.llmExtract,r);if(n.length===0)return e.log.debug("implicit-extract: LLM returned no facts"),0;let o=0;for(let s of n)try{if(!e.localProvider.proposeExtracted)continue;if(((await e.localProvider.proposeExtracted([{text:s.text,category:s.category,importance:s.importance}],e.userId,{source:"implicit-extract"})).proposalsAdded??0)>0){if(o++,e.log.debug(`implicit-extract: proposed "${s.text.slice(0,60)}..." [${s.category}]`),s.category==="event")try{let a=e.localProvider.findRelatedEvents?await e.localProvider.findRelatedEvents(s.text,e.userId):[];for(let c of a)e.localProvider.feedback?.([c.id],"useful").catch(()=>{});a.length>0&&e.log.debug(`implicit-extract: linked to ${a.length} related events`)}catch{}}else e.log.debug(`implicit-extract: dedup skipped "${s.text.slice(0,40)}..."`)}catch{}return o}var sa=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),ia=3,aa=2,Lo=2,ca=128e3,la=13e3,da=16384,ua=65536,pa=3,ma=65536,Oo=500,ga=3,fa=5e4,ha=2e5,jo=2e3,ya=3e4,ba=3,Fr=2,qT=3e5,WT=216e5,GT=.75,KT=16e3,zT=12e4,VT=3,XT=4,YT=50,va=20,Lu=50,ka=3,Ra=2,Sa=300*1e3,Ou=3,ju=720*60*60*1e3,JT=4e3,QT=5,wa=3,Ta=800,Aa=300*1e3,xa=4,Pa=0,Ca=50,Ia=50,Ea=30,$u=3600*1e3,Uu=200,_a=5,ZT=4e4,Ma=50*1024,Da=500*1024,Na=500*1024*1024,eA=50*1024*1024,La=3e5,Oa=2,ja=3e3,$a=3,Ua=5e3,tA=1e3,rA=3e3,nA=3e4,Fa=60*1024,Ha=10,Ba=100,oA=24,sA=5,iA=6e5,aA=30,cA=144e5,lA=3e5;function qa(){return{maxRoundsLimit:100,defaultMaxRounds:25,defaultTemperature:0,maxToolBudgetCap:100,defaultToolBudget:sa,maxConsecutiveFailures:ia,maxIdenticalCallRepeats:aa,defaultContextWindowTokens:ca,responseBufferTokens:la,defaultMaxOutputTokens:da,defaultModelMaxOutputTokens:ua,maxOutputTokensRecoveryLimit:pa,escalatedMaxOutputTokens:ma,diminishingReturnsThreshold:Oo,diminishingReturnsMinContinuations:ga,defaultMaxResultSizeChars:fa,maxToolResultsPerMessageChars:ha,toolResultPreviewBytes:jo,heartbeatIntervalMs:ya,max529Retries:ba,maxApiRetries:Fr,persistentRetryMaxBackoffMs:qT,persistentRetryResetCapMs:WT,compressionTargetUsageRatio:GT,compressionMinBudget:KT,compressionMaxBudget:zT,reactiveCompactMaxFailures:VT,reactiveCompactMinMessages:XT,reactiveCompactTargetPercent:YT,maxSkillsPerProject:va,maxSkillsGlobal:Lu,minToolCallsForSkill:ka,minDistinctToolsForSkill:Ra,skillCreationCooldownMs:Sa,skillInjectionMaxChars:JT,skillInjectionMaxCount:QT,skillRecallMaxSkills:wa,skillRecallMaxContentChars:Ta,skillRecallCacheTtlMs:Aa,maxForkDepth:xa,maxSessions:Ca,taskSummaryTurnThreshold:Ia,taskSummaryRegenInterval:Ea,maxIncludeDepth:_a,maxInstructionChars:ZT,instructionsMaxFileSize:Ma,instructionsMaxDirSize:Da,mediaMaxDownloadSize:Na,mediaMaxUploadSize:eA,mediaDownloadTimeoutMs:La,acpMaxSpawnRetries:Oa,acpRetryBackoffBase:ja,acpRuntimeRestartMax:$a,acpRuntimeRestartBackoffBase:Ua,taskPollIntervalMs:tA,taskStoppedDisplayMs:rA,taskPanelGraceMs:nA,memoryPrefetchMaxSessionBytes:Fa,memoryPrefetchLimitPerRecall:Ha,memoryMaxSurfacedEntries:Ba,dreamMinIntervalHours:oA,dreamMinSessions:sA,dreamScanIntervalMs:iA,idleDreamMinutes:aA,dreamCooldownMs:cA,dreamMaxDurationMs:lA,teamBudgetTokens:Pa}}var Hr={MAX_SESSION_BYTES:Fa,LIMIT_PER_RECALL:Ha,MAX_SURFACED_ENTRIES:Ba};function ht(){return{surfacedPaths:new Set,sessionBytes:0}}function Hu(t,e,r){let n=[],o=r??ht(),s,i=[];return n.push(t.register({point:"memory.before_recall",priority:50,label:"qmemory-prefetch",handler:async(a,c)=>{if(!e.memoryProvider||!c.query)return{action:"continue",context:c};if(o.sessionBytes>=Hr.MAX_SESSION_BYTES)return e.log.debug("memory.before_recall: session byte budget exhausted, skipping"),{action:"continue",context:c};try{let l=await e.memoryProvider.search(c.query,e.userId,{limit:Hr.LIMIT_PER_RECALL}),d=l.filter(m=>{let g=m,f=g.path??g.id??"";if(!f)return!0;if(o.surfacedPaths.has(f))return!1;let h=(g.content?.length??0)*2;if(o.sessionBytes+h>Hr.MAX_SESSION_BYTES)return!1;if(o.surfacedPaths.add(f),o.sessionBytes+=h,o.surfacedPaths.size>Hr.MAX_SURFACED_ENTRIES){let v=o.surfacedPaths.values().next().value;v!==void 0&&o.surfacedPaths.delete(v)}return!0});s=c.turnId,i=d,e.log.debug(`memory.before_recall: prefetched ${l.length} \u922B?${d.length} after dedup (${o.sessionBytes} bytes used)`);let u=d.map(m=>{let g=m;return{text:g.text??g.content??"",score:g.score,category:g.metadata?.category??null,source:"l2-long-term",label:"L2 long-term"}}).filter(m=>m.text);if(c.preferredCategories?.length||c.deprioritizedCategories?.length){let m={scenario:"general",preferred:c.preferredCategories??[],deprioritized:c.deprioritizedCategories??[],confidence:1};u=u.map(g=>({...g,score:na(g.score??.5,g.category,m)})).sort((g,f)=>(f.score??0)-(g.score??0))}let p=.15;return u=u.filter(m=>(m.score??0)>=p),{action:"continue",context:{...c,recalledMemories:[...c.recalledMemories??[],...u]}}}catch(l){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${l instanceof Error?l.message:String(l)}`),i=[]}return{action:"continue",context:c}}})),n.push(t.register({point:"memory.after_recall",priority:50,label:"qmemory-recall-log",handler:(a,c)=>{let l=s===c.turnId?i.length:0;return e.log.debug(`memory.after_recall: ${c.blockCount??0} blocks assembled, ${l} qmemory results (session: ${o.sessionBytes} bytes)`),{action:"continue",context:c}}})),e.localMemoryProvider&&(n.push(t.register({point:"turn.completed",priority:90,label:"memory-auto-extract",handler:async(a,c)=>{let l=e.getLastUserMessage?.();if(!l)return{action:"continue",context:c};let d=Fu(l);if(d.length===0)return{action:"continue",context:c};for(let u of d)try{await e.localMemoryProvider.addText(u.text,e.userId,{source:"auto-extract",category:u.category,importance:.6}),e.log.debug(`memory-auto-extract: stored "${u.text.slice(0,50)}..." (${u.category})`)}catch{}return{action:"continue",context:c}}})),n.push(t.register({point:"turn.completed",priority:95,label:"memory-implicit-extract",handler:async(a,c)=>{let l=e.getLastUserMessage?.();if(!l)return{action:"continue",context:c};if(Fu(l).length>0)return{action:"continue",context:c};if(!oa(l))return{action:"continue",context:c};let u=e.getLastAssistantMessage?.();return!u||!e.llmExtract?{action:"continue",context:c}:(Nu({userMessage:l,assistantMessage:u},{localProvider:e.localMemoryProvider,userId:e.userId,log:e.log,llmExtract:e.llmExtract}).catch(()=>{}),{action:"continue",context:c})}}))),()=>{for(let a of n)a();i=[]}}function Bu(t,e,r){let n=r??ht();return t.register({point:"memory.before_recall",priority:40,label:"memdir-cross-file-recall",handler:async(s,i)=>{let a=e.getMemorySource();if(!a||!i.query)return{action:"continue",context:i};if(n.sessionBytes>=Hr.MAX_SESSION_BYTES)return e.log.debug("memdir-recall: session byte budget exhausted, skipping"),{action:"continue",context:i};try{let c=a.getRootPath(),l=await Eu(i.query,c,n.surfacedPaths);if(l.length===0)return{action:"continue",context:i};if(i.preferredCategories?.length||i.deprioritizedCategories?.length){let g={scenario:"general",preferred:i.preferredCategories??[],deprioritized:i.deprioritizedCategories??[],confidence:1};l=l.map(f=>({...f,score:na(f.score,Du(f.filename),g)})).sort((f,h)=>h.score-f.score)}let d=l.filter(g=>{let f=Buffer.byteLength(g.content,"utf-8");return n.sessionBytes+f>Hr.MAX_SESSION_BYTES?!1:(n.surfacedPaths.add(g.filePath),n.sessionBytes+=f,!0)});if(d.length===0)return{action:"continue",context:i};e.log.debug(`memdir-recall: found ${l.length} \u922B?accepted ${d.length} files (${n.sessionBytes} bytes used)`);let u=_u(d),p=i.recalledMemories??[];return{action:"continue",context:{...i,recalledMemories:[...[{text:u,score:.9,category:"project",source:"l1-project-md",label:"L1 project MD"}],...p]}}}catch(c){e.log.warn(`memdir-recall: cross-file recall failed: ${c instanceof Error?c.message:String(c)}`)}return{action:"continue",context:i}}})}var dA=[{pattern:/(?:请|帮我)?记住[::]\s*(.+)/i,category:"personal_fact",extractor:t=>t[1]?.trim()||null},{pattern:/(?:请|帮我)?记住(.{10,120})/i,category:"personal_fact",extractor:t=>t[1]?.trim()||null},{pattern:/我的偏好[是为::]\s*(.+)/i,category:"preference",extractor:t=>t[1]?.trim()||null},{pattern:/我(?:喜欢|偏好|习惯)(.{5,100})/i,category:"preference",extractor:t=>`\u7528\u6237\u504F\u597D: ${t[1]?.trim()}`},{pattern:/以后(?:都|请|要)(.{5,100})/i,category:"preference",extractor:t=>`\u7528\u6237\u8981\u6C42: ${t[1]?.trim()}`},{pattern:/remember(?:\s+that)?[::]\s*(.+)/i,category:"personal_fact",extractor:t=>t[1]?.trim()||null},{pattern:/(?:note|memo)[::]\s*(.+)/i,category:"lesson",extractor:t=>t[1]?.trim()||null},{pattern:/my preference is[::]?\s*(.+)/i,category:"preference",extractor:t=>t[1]?.trim()||null},{pattern:/i (?:always|prefer|like to|want you to)\s+(.{10,120})/i,category:"preference",extractor:t=>`User preference: ${t[1]?.trim()}`}];function Fu(t){let e=[],r=t.slice(0,500);for(let{pattern:n,category:o,extractor:s}of dA){let i=r.match(n);if(i){let a=s(i,r);if(a&&a.length>=5&&a.length<=300){e.push({text:a,category:o});break}}}return e}D();import*as G from"node:fs";import*as Ce from"node:path";var np="transcript.jsonl",Gt="metadata.json",tp="state.json";function gA(t){return Mt(t)}function qr(t,e){let r=t.replace(/[^a-zA-Z0-9_-]/g,"_");return Ce.join(gA(e),r)}function rp(t){if(!t)return Date.now();let e=Date.parse(t);return Number.isFinite(e)?e:Date.now()}async function fA(t,e,r){let n={metadata:{sessionId:e.sessionId,createdAt:rp(e.createdAt),lastActiveAt:rp(e.lastActiveAt),model:e.model,cwd:e.cwd,turnCount:e.turnCount,messageCount:e.messageCount,title:e.title},costSnapshot:r},o=Ce.join(t,tp+".tmp");await G.promises.writeFile(o,JSON.stringify(n,null,2),"utf8"),await G.promises.rename(o,Ce.join(t,tp))}function op(t,e){let r=t.replace(/[^a-zA-Z0-9_-]/g,"_"),n=Ce.join(Mt(e),r),o=Ce.join(n,Gt);if(G.existsSync(o))return n}function Kt(t,e){let r=op(t,e);if(!r)return null;try{let n=G.readFileSync(Ce.join(r,Gt),"utf8");return JSON.parse(n)}catch{return null}}async function Wa(t,e,r,n){let o=qr(t,r);try{await G.promises.mkdir(o,{recursive:!0});let s={role:e.role,content:e.content,ts:Date.now()};n&&(s.turnId=n);let i=JSON.stringify(s)+`
|
|
36
|
-
`;return await G.promises.appendFile(Ce.join(o,np),i,"utf8"),!0}catch(s){return console.error(`[session-persistence] appendMessage failed for ${t}: ${s.message}`),!1}}async function sp(t,e,r,n){let o=qr(t,n);await G.promises.mkdir(o,{recursive:!0});let s={};try{let l=await G.promises.readFile(Ce.join(o,
|
|
37
|
-
`))if(u.trim())try{let p=JSON.parse(u);s.push({role:p.role,content:p.content??null})}catch{i++}i>0&&console.warn(`[session-persistence] ${i} corrupt line(s) skipped in ${n}`)}catch{return null}if(s.length===0&&i>0)return console.error(`[session-persistence] Transcript fully corrupt for session ${t}`),null;let a=new Date().toISOString(),c={sessionId:t,projectId:"",createdAt:a,lastActiveAt:a,turnCount:0,messageCount:s.length};try{let d=await G.promises.readFile(o,"utf8");c=JSON.parse(d)}catch{}let l=s.filter(d=>d.role!=="system");return{metadata:c,messages:l}}async function Dt(t=Ca,e){let r=Mt(e),n;try{n=await G.promises.readdir(r)}catch{return[]}let o=[];for(let s of n){let i=Ce.join(r,s,
|
|
38
|
-
`),a=n.transport.stream({model:n.model,messages:[{role:"system",content:"Generate a concise task summary (~100 words) of what the user is working on in this session. Focus on the goal, key decisions, and current progress. Reply with ONLY the summary."},{role:"user",content:i}],tools:[],maxTokens:200},n.apiKey),c="";for await(let u of a)u.type==="delta"&&(c+=u.text);if(c=c.trim(),!c)return null;let l=qr(t,o),d=Ce.join(l,Gt);try{let u=await G.promises.readFile(d,"utf8"),p=JSON.parse(u);p.taskSummary=c,p.taskSummaryGeneratedAt=e.turnCount;let m=d+".tmp";await G.promises.writeFile(m,JSON.stringify(p,null,2),"utf8"),await G.promises.rename(m,d)}catch{}return c}catch{return null}}import{randomUUID as zU}from"node:crypto";var bA=3e4;var Uo=class{tasks=new Map;listeners=new Set;hooks=null;sessionId="";setHooks(e,r){this.hooks=e,this.sessionId=r}onTaskChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(e,r){for(let n of this.listeners)try{n(e,r)}catch{}}registerTask(e){this.tasks.set(e.taskId,e),this.notify(e.taskId,e),this.hooks?.invoke("task.created",{sessionId:this.sessionId,taskId:e.taskId,taskType:e.type,label:e.label}).catch(()=>{})}updateTask(e,r){let n=this.tasks.get(e);if(!n)return;let o=r(n);o!==n&&(this.tasks.set(e,o),this.notify(e,o),!$o(n.lifecycle)&&$o(o.lifecycle)&&this.hooks?.invoke("task.completed",{sessionId:this.sessionId,taskId:o.taskId,taskType:o.type,label:o.label}).catch(()=>{}))}getTask(e){return this.tasks.get(e)}getRunningTasks(){return[...this.tasks.values()].filter(e=>e.lifecycle==="running")}getAllTasks(){return[...this.tasks.values()]}evictTask(e){let r=this.tasks.get(e);r&&$o(r.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=bA){let r=Date.now();for(let[n,o]of this.tasks)$o(o.lifecycle)&&o.endedAt&&r-o.endedAt>e&&(this.tasks.delete(n),this.notify(n,null))}};function $o(t){return t==="completed"||t==="failed"||t==="cancelled"||t==="timeout"}var za=new Set;function zt(t){return za.add(t),()=>{za.delete(t)}}async function cp(){await Promise.all(Array.from(za).map(t=>t()))}D();We();var Bo="\u65E0\u6CD5\u8FDE\u63A5 llmrouter \u6A21\u578B\u76EE\u5F55",ne="llmrouter",Xa="LLMRouter",Vt=class extends Error{constructor(e=Bo){super(e),this.name="LlmrouterCatalogUnavailableError"}};function gp(){let t=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim().replace(/\/+$/,"");if(!t)throw new Vt;return t}function fp(){return gp()}function PA(){let t={accept:"application/json"},e=process.env.QLOGIC_LLMROUTER_ACCESS_TOKEN?.trim();return e&&(t.authorization=`Bearer ${e}`),t}async function hp(t){let e=gp(),r;try{r=await fetch(`${e}${t}`,{method:"GET",headers:PA(),signal:AbortSignal.timeout(1e4)})}catch{throw new Vt}if(!r.ok)throw new Vt;let n=await r.json().catch(()=>null),o=Array.isArray(n)?n:Sp(n)&&Array.isArray(n.data)?n.data:null;if(!o)throw new Vt;return o}function Ya(t){let e=t.trim().replace(/\/+$/,"");return e.endsWith("/v1")?`${e}/models`:`${e}/v1/models`}async function CA(t,e){let r;try{r=await fetch(t,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`},signal:AbortSignal.timeout(1e4)})}catch{throw new Vt}if(!r.ok)throw new Vt;let n=await r.json().catch(()=>null),o=Array.isArray(n)?n:Sp(n)&&Array.isArray(n.data)?n.data:null;if(!o)throw new Vt;return o}async function Ja(){return hp("/ext/model-catalog/providers")}async function IA(){return hp("/ext/model-catalog/models")}async function EA(t,e){return CA(Ya(t),e)}function yp(t){let e={zhipu:"Zhipu GLM","zhipu-openai":"Zhipu GLM OpenAI","zhipu-coding":"Zhipu GLM Coding",volcengine:"Doubao / Volcengine"};return e[t.id]?e[t.id]:t.displayName??t.name??t.id}function Qa(t){return t.baseUrl??t.base_url}async function bp(t){return(await Ja()).find(r=>r.id===t)??null}async function Cn(t){let e=await IA();t.migrateModelIds(vp(e));let r=e.flatMap(kp);return t.replaceCatalogModels(r),r}async function Za(t,e){let r=await EA(e.baseUrl,e.apiKey);if(r.length===0)return[];t.migrateModelIds(vp(r));let n=r.flatMap(kp).filter(o=>o.provider===ne).map(o=>({...o,baseUrl:e.baseUrl}));return t.replaceProviderModels(ne,n),n}function vp(t){let e=new Map;for(let r of t){let n=r.provider??r.owned_by,o=r.public_model??r.publicModel??r.id,s=r.native_model_id??r.nativeModelId??r.id;if(!o)continue;let i=`${ne}:${o}`;if(n){let a=`${n}:${o}`;for(let c of[o,s,r.id]){if(!c)continue;let l=`${n}:${c}`;l!==a&&e.set(l,a)}}for(let a of[s,r.id]){if(!a)continue;let c=`${ne}:${a}`;c!==i&&e.set(c,i)}}return e}function kp(t){return[_A(t),MA(t)].filter(e=>!!e)}function _A(t){let e=t.provider??t.owned_by,r=t.public_model??t.publicModel??t.id,n=t.native_model_id??t.nativeModelId??t.id;return!e||!r||!n?null:{id:`${e}:${r}`,provider:e,model:r,displayName:t.display_name??t.displayName??t.name??t.id,purposes:Rp(t.purposes,t.category),baseUrl:t.baseUrl??t.base_url,enabled:!0,nativeModelId:n,transport:t.provider_transport??t.providerTransport,contextWindow:t.context_window??t.contextWindow,maxOutput:t.max_output??t.maxOutput,streamRequired:t.stream_required??t.streamRequired,capabilities:t.capabilities,pricing:t.pricing}}function MA(t){let e=t.public_model??t.publicModel??t.id;return e?{id:`${ne}:${e}`,provider:ne,model:e,displayName:t.display_name??t.displayName??t.name??t.id,purposes:Rp(t.purposes,t.category),enabled:!0,nativeModelId:e,transport:"openai-responses",contextWindow:t.context_window??t.contextWindow,maxOutput:t.max_output??t.maxOutput,streamRequired:t.stream_required??t.streamRequired,capabilities:t.capabilities,pricing:t.pricing}:null}function Rp(t,e){let r=[...t??[],e].filter(s=>!!s),n=new Set(["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"]),o=r.filter(s=>n.has(s));return[...new Set(o.length?o:["textGeneration"])]}function Sp(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}import{join as ec}from"node:path";import{mkdirSync as DA,existsSync as NA,createWriteStream as LA}from"node:fs";import{pipeline as OA}from"node:stream/promises";import{Readable as jA}from"node:stream";var $A=Na,UA=La,wp={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/svg+xml":".svg","image/avif":".avif","video/mp4":".mp4","video/webm":".webm","video/quicktime":".mov","audio/mpeg":".mp3","audio/wav":".wav","audio/ogg":".ogg","audio/aac":".aac","audio/mp4":".m4a","audio/flac":".flac","application/pdf":".pdf","model/gltf-binary":".glb","model/gltf+json":".gltf"},qo=class{projectDir;maxFileSize;timeoutMs;constructor(e){this.projectDir=e?.projectDir??null,this.maxFileSize=e?.maxFileSize??$A,this.timeoutMs=e?.timeoutMs??UA}setProjectDir(e){this.projectDir=e}resolveMediaDir(e){if(!this.projectDir)throw new Error("MediaPersistence requires projectDir \u2014 call setProjectDir() first");if(!e)return ec(this.projectDir,".qlogicagent","media",FA());let r=e.replace(/[^a-zA-Z0-9_-]/g,"_");return r!==e&&r.length>0&&[...e].filter(o=>!/[a-zA-Z0-9_-]/.test(o)).length>e.length/2&&console.warn(`[media-persistence] sessionId heavily sanitized: "${e}" \u2192 "${r}" \u2014 potential collision risk`),ec(this.projectDir,".qlogicagent","sessions",r,"media")}async download(e,r){let n=this.resolveMediaDir(r?.sessionId);if(n.length+60>255)throw new Error(`Media path too long (${n.length} chars) \u2014 would exceed OS limit. Use a shorter project path or session ID.`);NA(n)||DA(n,{recursive:!0});let o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs),i="";try{let a=await fetch(e,{signal:o.signal});if(!a.ok)throw new Error(`Download failed: ${a.status} ${a.statusText}`);let c=parseInt(a.headers.get("content-length")??"0",10);if(c>this.maxFileSize)throw new Error(`File too large: ${c} bytes (max: ${this.maxFileSize})`);let l=a.headers.get("content-type")?.split(";")[0].trim()||"application/octet-stream",d=BA(e,l),u=HA(r?.type??qA(l),d);i=ec(n,u);let p=a.body;if(!p)throw new Error("No response body");let m=LA(i);await OA(jA.fromWeb(p),m);let{size:g}=await import("node:fs/promises").then(f=>f.stat(i));if(g===0)throw await import("node:fs/promises").then(f=>f.unlink(i).catch(()=>{})),new Error("Download produced empty file (connection dropped)");return{remoteUrl:e,localPath:i,bytes:g,mimeType:l}}catch(a){if(i)try{let{unlink:c}=await import("node:fs/promises");await c(i)}catch{}throw a}finally{clearTimeout(s)}}async downloadAll(e,r,n){let o=[];for(let s of e)try{let i=await this.download(s,r);o.push(i)}catch(i){n?.warn(`media-persistence: failed to download ${s}: ${i.message}`)}return o}getMediaDir(e){return this.resolveMediaDir(e)}getProjectDir(){return this.projectDir}};function FA(){let t=new Date;return`${t.getFullYear()}${String(t.getMonth()+1).padStart(2,"0")}${String(t.getDate()).padStart(2,"0")}`}function HA(t,e){let r=new Date,n=`${r.getFullYear()}${String(r.getMonth()+1).padStart(2,"0")}${String(r.getDate()).padStart(2,"0")}_${String(r.getHours()).padStart(2,"0")}${String(r.getMinutes()).padStart(2,"0")}${String(r.getSeconds()).padStart(2,"0")}`,o=Math.random().toString(36).slice(2,6);return`${t}_${n}_${o}${e}`}function BA(t,e){if(wp[e])return wp[e];try{let r=new URL(t).pathname,n=r.lastIndexOf(".");if(n>0){let o=r.slice(n).toLowerCase().split("?")[0];if(o.length<=5)return o}}catch{}return".bin"}function qA(t){return t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":t.startsWith("model/")?"3d":"file"}var kr="1.0.0",y={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030,REQUEST_DEADLINE_EXCEEDED:-32040,REQUEST_CANCELLED:-32041,REQUEST_DEDUPED:-32042,REQUEST_IDEMPOTENCY_REQUIRED:-32043};function tc(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&e.method.length>0}import{randomUUID as WA}from"node:crypto";var GA=["settings.list","settings.get","settings.validate","provider.list","config.get","config.tunables","tools.list","todos.list","tasks.list","agents.list","agents.get","agents.processes","agents.scan","session.list","session.get","session.resolve","thread.list","project.list","files.list","files.gitStatus","instructions.list","instructions.read","skills.list","skills.stats","memory.atlas","memory.activity","memory.list","memory.read","memory.search","media.listModels","media.status","pet.status","agent.health","agent.metrics"],KA=new Set(["thread.turn","memory.dream","memory.propose","memory.consolidate","media.stt","pet.forge","solo.start","solo.evaluate","product.plan","product.create","product.message"]),zA=["memory.","pet.","usage."],VA=new Set(["memory.atlas","memory.activity","memory.list","memory.read","memory.search","pet.status"]);function Wo(t){return KA.has(t)?{channel:"task",mutability:"write",defaultTimeoutMs:t==="thread.turn"?3e5:12e4}:GA.some(e=>t===e||t.startsWith(`${e}.`)||t.startsWith(e))?{channel:"query",mutability:"read",defaultTimeoutMs:1e4}:{channel:"task",mutability:"write",defaultTimeoutMs:3e4}}function Tp(t){return VA.has(t)||Wo(t).mutability==="read"?!1:zA.some(e=>t.startsWith(e))}function rc(t,e={}){let r=e.now??Date.now(),n=Wo(t),o=e.timeoutMs??n.defaultTimeoutMs;return{requestId:e.requestId??WA(),createdAt:r,deadlineAt:r+o,channel:e.channel??n.channel,idempotencyKey:e.idempotencyKey,traceId:e.traceId}}function Go(t,e=Date.now()){let r=t.meta;if(!r||typeof r!="object")return{ok:!1,error:{code:y.INVALID_REQUEST,message:"RPC request meta is required."}};if(typeof r.requestId!="string"||r.requestId.length===0)return{ok:!1,error:{code:y.INVALID_REQUEST,message:"RPC request meta.requestId is required."}};if(r.channel!=="query"&&r.channel!=="task")return{ok:!1,error:{code:y.INVALID_REQUEST,message:"RPC request meta.channel must be query or task."}};if(typeof r.createdAt!="number"||!Number.isFinite(r.createdAt))return{ok:!1,error:{code:y.INVALID_REQUEST,message:"RPC request meta.createdAt is required."}};if(typeof r.deadlineAt!="number"||!Number.isFinite(r.deadlineAt))return{ok:!1,error:{code:y.INVALID_REQUEST,message:"RPC request meta.deadlineAt is required."}};if(r.deadlineAt<=e)return{ok:!1,error:{code:y.REQUEST_DEADLINE_EXCEEDED,message:"RPC request deadline has already expired."}};let n=Wo(t.method).channel;return r.channel!==n?{ok:!1,error:{code:y.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${n}, got ${r.channel}.`}}:Tp(t.method)&&(typeof r.idempotencyKey!="string"||r.idempotencyKey.length===0)?{ok:!1,error:{code:y.REQUEST_IDEMPOTENCY_REQUIRED,message:`RPC method ${t.method} requires meta.idempotencyKey.`}}:{ok:!0,meta:r}}var In=class{now;active=new Map;idempotency=new Map;counters={completedRequests:0,cancelledRequests:0,deadlineExceededRequests:0,dedupedRequests:0,lateResponsesDropped:0,invalidRequests:0};constructor(e={}){this.now=e.now??(()=>Date.now())}begin(e,r){let n=Go({method:e,meta:r},this.now());if(!n.ok)return this.counters.invalidRequests+=1,{status:"rejected",error:n.error};if(r.idempotencyKey){let o=this.idempotency.get(r.idempotencyKey);if(o)return this.counters.dedupedRequests+=1,o.error?{status:"deduped",error:o.error}:{status:"deduped",result:o.result}}return this.active.set(r.requestId,{method:e,meta:r,cancelled:!1,startedAt:this.now()}),{status:"started"}}cancel(e,r="cancelled"){let n=this.active.get(e);return!n||n.cancelled?!1:(n.cancelled=!0,n.cancelReason=r,this.counters.cancelledRequests+=1,!0)}expire(e){return this.active.get(e)?(this.active.delete(e),this.counters.deadlineExceededRequests+=1,!0):!1}settle(e,r,n){let o=this.active.get(e);return o?(this.active.delete(e),o.cancelled?(this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"cancelled"}):o.meta.deadlineAt<=this.now()?(this.counters.deadlineExceededRequests+=1,this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"deadline_exceeded"}):(this.counters.completedRequests+=1,o.meta.idempotencyKey&&this.idempotency.set(o.meta.idempotencyKey,{result:r,error:n,settledAt:this.now()}),{accepted:!0})):{accepted:!1,reason:"unknown"}}metrics(){return{activeRequests:this.active.size,...this.counters}}};var Ap=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated","skills.updated","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.forged","system.activity"],xp=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.checkpointed","product.dagTopology","plan.interrupted"],XA=[...Ap,...xp];var bt={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_END:"session/end",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},Z={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",PRODUCT_SUBSCRIBE:"x/product.subscribe",TEAM_DELEGATE:"x/team.delegate"},vt={AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update"},ue={X_SUBAGENT_STARTED:"x_subagent_started",X_SUBAGENT_DELTA:"x_subagent_delta",X_SUBAGENT_ENDED:"x_subagent_ended",X_MEDIA_RESULT:"x_media_result",X_MEDIA_PROGRESS:"x_media_progress",X_SKILL_INSTRUCTION:"x_skill_instruction",X_RECOVERY:"x_recovery",X_SIDECHAIN_STARTED:"x_sidechain_started",X_SIDECHAIN_COMPLETED:"x_sidechain_completed",X_SUGGESTIONS:"x_suggestions",X_ASK_USER:"x_ask_user",X_SESSION_INFO:"x_session_info",X_MEMORY_UPDATED:"x_memory_updated",X_TEAM_MEMBER_UPDATE:"x_team_member_update",X_SOLO_STARTED:"x_solo_started",X_SOLO_AGENT_FINISHED:"x_solo_agent_finished",X_SOLO_SELECTED:"x_solo_selected",X_PRODUCT_TASK_STARTED:"x_product_task_started",X_PRODUCT_TASK_COMPLETED:"x_product_task_completed",X_PRODUCT_CHECKPOINT:"x_product_checkpoint"};function En(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&"id"in e}function _n(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&!("id"in e)}function nc(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&"id"in e&&!("method"in e)}var Pp="openai-codex";var kF={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[Pp]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};import{randomUUID as YA}from"node:crypto";var Ko={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,PROTOCOL_MISMATCH:-32001,SESSION_NOT_FOUND:-32002,AGENT_BUSY:-32003},zo=class{transport;handler;verbose;hostCapabilities={};hostSupportsExtendedEvents=!1;hostSupportsExtendedMethods=!1;activeSessionId=null;pendingPermissions=new Map;outboundRequestMap=new Map;constructor(e,r,n){this.transport=e,this.handler=r,this.verbose=n?.verbose??!1}dispatchMessage(e){if(this.isJsonRpcResponse(e))return this.handleResponse(e),!0;if(En(e)){let r=e;return process.stderr.write(`[acp-server] \u922B?recv id=${String(r.id)} method=${r.method}
|
|
35
|
+
[{"text": "...", "category": "personal_fact|preference|event|lesson", "importance": 0.5-0.9, "eventDate": "YYYY-MM-DD or null"}]`;async function HT(t,e,r){let n=FT.replace("{user_message}",t.userMessage.slice(0,1e3)).replace("{assistant_message}",t.assistantMessage.slice(0,500)).replace("{today}",r);try{let o=await e(n);if(!o)return[];let s=o.replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"").trim(),i=JSON.parse(s);return Array.isArray(i)?i.filter(a=>a.text&&typeof a.text=="string"&&a.text.length>=5&&a.text.length<=500&&a.category).map(a=>({text:a.text.trim(),category:BT(a.category),importance:Math.min(.9,Math.max(.3,Number(a.importance)||.5)),eventDate:typeof a.eventDate=="string"?a.eventDate:void 0})).slice(0,3):[]}catch{return[]}}function BT(t){return new Set(["personal_fact","preference","event","lesson","pattern","decision"]).has(t)?t:"personal_fact"}async function Nu(t,e){if(!oa(t.userMessage))return 0;if(e.log.debug(`implicit-extract: signal detected in user message (${t.userMessage.slice(0,50)}...)`),!e.llmExtract)return e.log.debug("implicit-extract: no LLM extractor configured, skipping Layer 2"),0;let r=new Date().toISOString().slice(0,10),n=await HT(t,e.llmExtract,r);if(n.length===0)return e.log.debug("implicit-extract: LLM returned no facts"),0;let o=0;for(let s of n)try{if(!e.localProvider.proposeExtracted)continue;if(((await e.localProvider.proposeExtracted([{text:s.text,category:s.category,importance:s.importance}],e.userId,{source:"implicit-extract"})).proposalsAdded??0)>0){if(o++,e.log.debug(`implicit-extract: proposed "${s.text.slice(0,60)}..." [${s.category}]`),s.category==="event")try{let a=e.localProvider.findRelatedEvents?await e.localProvider.findRelatedEvents(s.text,e.userId):[];for(let c of a)e.localProvider.feedback?.([c.id],"useful").catch(()=>{});a.length>0&&e.log.debug(`implicit-extract: linked to ${a.length} related events`)}catch{}}else e.log.debug(`implicit-extract: dedup skipped "${s.text.slice(0,40)}..."`)}catch{}return o}var sa=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),ia=3,aa=2,Lo=2,ca=128e3,la=13e3,da=16384,ua=65536,pa=3,ma=65536,Oo=500,ga=3,fa=5e4,ha=2e5,jo=2e3,ya=3e4,ba=3,Fr=2,qT=3e5,WT=216e5,GT=.75,KT=16e3,zT=12e4,VT=3,XT=4,YT=50,va=20,Lu=50,ka=3,Ra=2,Sa=300*1e3,Ou=3,ju=720*60*60*1e3,JT=4e3,QT=5,wa=3,Ta=800,Aa=300*1e3,xa=4,Pa=0,Ca=50,Ia=50,Ea=30,$u=3600*1e3,Uu=200,_a=5,ZT=4e4,Ma=50*1024,Da=500*1024,Na=500*1024*1024,eA=50*1024*1024,La=3e5,Oa=2,ja=3e3,$a=3,Ua=5e3,tA=1e3,rA=3e3,nA=3e4,Fa=60*1024,Ha=10,Ba=100,oA=24,sA=5,iA=6e5,aA=30,cA=144e5,lA=3e5;function qa(){return{maxRoundsLimit:100,defaultMaxRounds:25,defaultTemperature:0,maxToolBudgetCap:100,defaultToolBudget:sa,maxConsecutiveFailures:ia,maxIdenticalCallRepeats:aa,defaultContextWindowTokens:ca,responseBufferTokens:la,defaultMaxOutputTokens:da,defaultModelMaxOutputTokens:ua,maxOutputTokensRecoveryLimit:pa,escalatedMaxOutputTokens:ma,diminishingReturnsThreshold:Oo,diminishingReturnsMinContinuations:ga,defaultMaxResultSizeChars:fa,maxToolResultsPerMessageChars:ha,toolResultPreviewBytes:jo,heartbeatIntervalMs:ya,max529Retries:ba,maxApiRetries:Fr,persistentRetryMaxBackoffMs:qT,persistentRetryResetCapMs:WT,compressionTargetUsageRatio:GT,compressionMinBudget:KT,compressionMaxBudget:zT,reactiveCompactMaxFailures:VT,reactiveCompactMinMessages:XT,reactiveCompactTargetPercent:YT,maxSkillsPerProject:va,maxSkillsGlobal:Lu,minToolCallsForSkill:ka,minDistinctToolsForSkill:Ra,skillCreationCooldownMs:Sa,skillInjectionMaxChars:JT,skillInjectionMaxCount:QT,skillRecallMaxSkills:wa,skillRecallMaxContentChars:Ta,skillRecallCacheTtlMs:Aa,maxForkDepth:xa,maxSessions:Ca,taskSummaryTurnThreshold:Ia,taskSummaryRegenInterval:Ea,maxIncludeDepth:_a,maxInstructionChars:ZT,instructionsMaxFileSize:Ma,instructionsMaxDirSize:Da,mediaMaxDownloadSize:Na,mediaMaxUploadSize:eA,mediaDownloadTimeoutMs:La,acpMaxSpawnRetries:Oa,acpRetryBackoffBase:ja,acpRuntimeRestartMax:$a,acpRuntimeRestartBackoffBase:Ua,taskPollIntervalMs:tA,taskStoppedDisplayMs:rA,taskPanelGraceMs:nA,memoryPrefetchMaxSessionBytes:Fa,memoryPrefetchLimitPerRecall:Ha,memoryMaxSurfacedEntries:Ba,dreamMinIntervalHours:oA,dreamMinSessions:sA,dreamScanIntervalMs:iA,idleDreamMinutes:aA,dreamCooldownMs:cA,dreamMaxDurationMs:lA,teamBudgetTokens:Pa}}var Hr={MAX_SESSION_BYTES:Fa,LIMIT_PER_RECALL:Ha,MAX_SURFACED_ENTRIES:Ba};function ht(){return{surfacedPaths:new Set,sessionBytes:0}}function Hu(t,e,r){let n=[],o=r??ht(),s,i=[];return n.push(t.register({point:"memory.before_recall",priority:50,label:"qmemory-prefetch",handler:async(a,c)=>{if(!e.memoryProvider||!c.query)return{action:"continue",context:c};if(o.sessionBytes>=Hr.MAX_SESSION_BYTES)return e.log.debug("memory.before_recall: session byte budget exhausted, skipping"),{action:"continue",context:c};try{let l=await e.memoryProvider.search(c.query,e.userId,{limit:Hr.LIMIT_PER_RECALL}),d=l.filter(m=>{let g=m,f=g.path??g.id??"";if(!f)return!0;if(o.surfacedPaths.has(f))return!1;let h=(g.content?.length??0)*2;if(o.sessionBytes+h>Hr.MAX_SESSION_BYTES)return!1;if(o.surfacedPaths.add(f),o.sessionBytes+=h,o.surfacedPaths.size>Hr.MAX_SURFACED_ENTRIES){let v=o.surfacedPaths.values().next().value;v!==void 0&&o.surfacedPaths.delete(v)}return!0});s=c.turnId,i=d,e.log.debug(`memory.before_recall: prefetched ${l.length} \u922B?${d.length} after dedup (${o.sessionBytes} bytes used)`);let u=d.map(m=>{let g=m;return{text:g.text??g.content??"",score:g.score,category:g.metadata?.category??null,source:"l2-long-term",label:"L2 long-term"}}).filter(m=>m.text);if(c.preferredCategories?.length||c.deprioritizedCategories?.length){let m={scenario:"general",preferred:c.preferredCategories??[],deprioritized:c.deprioritizedCategories??[],confidence:1};u=u.map(g=>({...g,score:na(g.score??.5,g.category,m)})).sort((g,f)=>(f.score??0)-(g.score??0))}let p=.15;return u=u.filter(m=>(m.score??0)>=p),{action:"continue",context:{...c,recalledMemories:[...c.recalledMemories??[],...u]}}}catch(l){e.log.warn(`memory.before_recall: qmemory prefetch failed: ${l instanceof Error?l.message:String(l)}`),i=[]}return{action:"continue",context:c}}})),n.push(t.register({point:"memory.after_recall",priority:50,label:"qmemory-recall-log",handler:(a,c)=>{let l=s===c.turnId?i.length:0;return e.log.debug(`memory.after_recall: ${c.blockCount??0} blocks assembled, ${l} qmemory results (session: ${o.sessionBytes} bytes)`),{action:"continue",context:c}}})),e.localMemoryProvider&&(n.push(t.register({point:"turn.completed",priority:90,label:"memory-auto-extract",handler:async(a,c)=>{let l=e.getLastUserMessage?.();if(!l)return{action:"continue",context:c};let d=Fu(l);if(d.length===0)return{action:"continue",context:c};for(let u of d)try{await e.localMemoryProvider.addText(u.text,e.userId,{source:"auto-extract",category:u.category,importance:.6}),e.log.debug(`memory-auto-extract: stored "${u.text.slice(0,50)}..." (${u.category})`)}catch{}return{action:"continue",context:c}}})),n.push(t.register({point:"turn.completed",priority:95,label:"memory-implicit-extract",handler:async(a,c)=>{let l=e.getLastUserMessage?.();if(!l)return{action:"continue",context:c};if(Fu(l).length>0)return{action:"continue",context:c};if(!oa(l))return{action:"continue",context:c};let u=e.getLastAssistantMessage?.();return!u||!e.llmExtract?{action:"continue",context:c}:(Nu({userMessage:l,assistantMessage:u},{localProvider:e.localMemoryProvider,userId:e.userId,log:e.log,llmExtract:e.llmExtract}).catch(()=>{}),{action:"continue",context:c})}}))),()=>{for(let a of n)a();i=[]}}function Bu(t,e,r){let n=r??ht();return t.register({point:"memory.before_recall",priority:40,label:"memdir-cross-file-recall",handler:async(s,i)=>{let a=e.getMemorySource();if(!a||!i.query)return{action:"continue",context:i};if(n.sessionBytes>=Hr.MAX_SESSION_BYTES)return e.log.debug("memdir-recall: session byte budget exhausted, skipping"),{action:"continue",context:i};try{let c=a.getRootPath(),l=await Eu(i.query,c,n.surfacedPaths);if(l.length===0)return{action:"continue",context:i};if(i.preferredCategories?.length||i.deprioritizedCategories?.length){let g={scenario:"general",preferred:i.preferredCategories??[],deprioritized:i.deprioritizedCategories??[],confidence:1};l=l.map(f=>({...f,score:na(f.score,Du(f.filename),g)})).sort((f,h)=>h.score-f.score)}let d=l.filter(g=>{let f=Buffer.byteLength(g.content,"utf-8");return n.sessionBytes+f>Hr.MAX_SESSION_BYTES?!1:(n.surfacedPaths.add(g.filePath),n.sessionBytes+=f,!0)});if(d.length===0)return{action:"continue",context:i};e.log.debug(`memdir-recall: found ${l.length} \u922B?accepted ${d.length} files (${n.sessionBytes} bytes used)`);let u=_u(d),p=i.recalledMemories??[];return{action:"continue",context:{...i,recalledMemories:[...[{text:u,score:.9,category:"project",source:"l1-project-md",label:"L1 project MD"}],...p]}}}catch(c){e.log.warn(`memdir-recall: cross-file recall failed: ${c instanceof Error?c.message:String(c)}`)}return{action:"continue",context:i}}})}var dA=[{pattern:/(?:请|帮我)?记住[::]\s*(.+)/i,category:"personal_fact",extractor:t=>t[1]?.trim()||null},{pattern:/(?:请|帮我)?记住(.{10,120})/i,category:"personal_fact",extractor:t=>t[1]?.trim()||null},{pattern:/我的偏好[是为::]\s*(.+)/i,category:"preference",extractor:t=>t[1]?.trim()||null},{pattern:/我(?:喜欢|偏好|习惯)(.{5,100})/i,category:"preference",extractor:t=>`\u7528\u6237\u504F\u597D: ${t[1]?.trim()}`},{pattern:/以后(?:都|请|要)(.{5,100})/i,category:"preference",extractor:t=>`\u7528\u6237\u8981\u6C42: ${t[1]?.trim()}`},{pattern:/remember(?:\s+that)?[::]\s*(.+)/i,category:"personal_fact",extractor:t=>t[1]?.trim()||null},{pattern:/(?:note|memo)[::]\s*(.+)/i,category:"lesson",extractor:t=>t[1]?.trim()||null},{pattern:/my preference is[::]?\s*(.+)/i,category:"preference",extractor:t=>t[1]?.trim()||null},{pattern:/i (?:always|prefer|like to|want you to)\s+(.{10,120})/i,category:"preference",extractor:t=>`User preference: ${t[1]?.trim()}`}];function Fu(t){let e=[],r=t.slice(0,500);for(let{pattern:n,category:o,extractor:s}of dA){let i=r.match(n);if(i){let a=s(i,r);if(a&&a.length>=5&&a.length<=300){e.push({text:a,category:o});break}}}return e}D();import*as G from"node:fs";import*as Ce from"node:path";var np="transcript.jsonl",Kt="metadata.json",tp="state.json";function gA(t){return Mt(t)}function qr(t,e){let r=t.replace(/[^a-zA-Z0-9_-]/g,"_");return Ce.join(gA(e),r)}function rp(t){if(!t)return Date.now();let e=Date.parse(t);return Number.isFinite(e)?e:Date.now()}async function fA(t,e,r){let n={metadata:{sessionId:e.sessionId,createdAt:rp(e.createdAt),lastActiveAt:rp(e.lastActiveAt),model:e.model,cwd:e.cwd,turnCount:e.turnCount,messageCount:e.messageCount,title:e.title},costSnapshot:r},o=Ce.join(t,tp+".tmp");await G.promises.writeFile(o,JSON.stringify(n,null,2),"utf8"),await G.promises.rename(o,Ce.join(t,tp))}function op(t,e){let r=t.replace(/[^a-zA-Z0-9_-]/g,"_"),n=Ce.join(Mt(e),r),o=Ce.join(n,Kt);if(G.existsSync(o))return n}function zt(t,e){let r=op(t,e);if(!r)return null;try{let n=G.readFileSync(Ce.join(r,Kt),"utf8");return JSON.parse(n)}catch{return null}}async function Wa(t,e,r,n){let o=qr(t,r);try{await G.promises.mkdir(o,{recursive:!0});let s={role:e.role,content:e.content,ts:Date.now()};n&&(s.turnId=n);let i=JSON.stringify(s)+`
|
|
36
|
+
`;return await G.promises.appendFile(Ce.join(o,np),i,"utf8"),!0}catch(s){return console.error(`[session-persistence] appendMessage failed for ${t}: ${s.message}`),!1}}async function sp(t,e,r,n){let o=qr(t,n);await G.promises.mkdir(o,{recursive:!0});let s={};try{let l=await G.promises.readFile(Ce.join(o,Kt),"utf8");s=JSON.parse(l)}catch{}let i=new Date().toISOString(),a={sessionId:t,projectId:r.projectId??s.projectId??"",createdAt:r.createdAt??s.createdAt??i,lastActiveAt:i,model:r.model??s.model,cwd:r.cwd??s.cwd,turnCount:e.turnCount,messageCount:r.messageCount??s.messageCount??0,title:r.title??s.title,pinnedAt:r.pinnedAt!==void 0?r.pinnedAt:s.pinnedAt,archivedAt:r.archivedAt!==void 0?r.archivedAt:s.archivedAt,type:r.type??s.type,ownerId:r.ownerId??s.ownerId,groupKey:r.groupKey??s.groupKey,groupName:r.groupName??s.groupName,groupPlatform:r.groupPlatform??s.groupPlatform,sealedAt:r.sealedAt??s.sealedAt,previousSessionId:r.previousSessionId??s.previousSessionId,carryoverSummary:r.carryoverSummary??s.carryoverSummary,totalInputTokens:e.totalInputTokens,totalOutputTokens:e.totalOutputTokens},c=Ce.join(o,Kt+".tmp");await G.promises.writeFile(c,JSON.stringify(a,null,2),"utf8"),await G.promises.rename(c,Ce.join(o,Kt)),await fA(o,a,e)}async function Qe(t,e,r){let o=op(t,r)??qr(t,r),s=Ce.join(o,Kt),i=new Date().toISOString(),a;try{let d=await G.promises.readFile(s,"utf8");a=JSON.parse(d)}catch{await G.promises.mkdir(o,{recursive:!0}),a={sessionId:t,projectId:e.projectId??"",createdAt:i,lastActiveAt:i,turnCount:0,messageCount:0,...e};let d=s+".tmp";return await G.promises.writeFile(d,JSON.stringify(a,null,2),"utf8"),await G.promises.rename(d,s),a}let c={...a};e.title!==void 0&&(c.title=e.title??void 0),e.pinnedAt!==void 0&&(c.pinnedAt=e.pinnedAt??void 0),e.archivedAt!==void 0&&(c.archivedAt=e.archivedAt??void 0),e.sealedAt!==void 0&&(c.sealedAt=e.sealedAt??void 0),e.previousSessionId!==void 0&&(c.previousSessionId=e.previousSessionId??void 0),e.carryoverSummary!==void 0&&(c.carryoverSummary=e.carryoverSummary??void 0),e.projectId!==void 0&&(c.projectId=e.projectId??c.projectId),e.type!==void 0&&(c.type=e.type??void 0),e.ownerId!==void 0&&(c.ownerId=e.ownerId??void 0),e.groupKey!==void 0&&(c.groupKey=e.groupKey??void 0),e.groupName!==void 0&&(c.groupName=e.groupName??void 0),e.groupPlatform!==void 0&&(c.groupPlatform=e.groupPlatform??void 0),c.lastActiveAt=i;let l=s+".tmp";return await G.promises.writeFile(l,JSON.stringify(c,null,2),"utf8"),await G.promises.rename(l,s),c}async function Ga(t,e){try{await G.promises.access(e,G.constants.R_OK)}catch{return console.error(`[session-persistence] loadSessionForResume: projectRoot not accessible: ${e}`),null}let r=qr(t,e),n=Ce.join(r,np),o=Ce.join(r,Kt),s=[],i=0;try{let d=await G.promises.readFile(n,"utf8");for(let u of d.split(`
|
|
37
|
+
`))if(u.trim())try{let p=JSON.parse(u);s.push({role:p.role,content:p.content??null})}catch{i++}i>0&&console.warn(`[session-persistence] ${i} corrupt line(s) skipped in ${n}`)}catch{return null}if(s.length===0&&i>0)return console.error(`[session-persistence] Transcript fully corrupt for session ${t}`),null;let a=new Date().toISOString(),c={sessionId:t,projectId:"",createdAt:a,lastActiveAt:a,turnCount:0,messageCount:s.length};try{let d=await G.promises.readFile(o,"utf8");c=JSON.parse(d)}catch{}let l=s.filter(d=>d.role!=="system");return{metadata:c,messages:l}}async function Dt(t=Ca,e){let r=Mt(e),n;try{n=await G.promises.readdir(r)}catch{return[]}let o=[];for(let s of n){let i=Ce.join(r,s,Kt);try{let a=await G.promises.readFile(i,"utf8"),c=JSON.parse(a);o.push({sessionId:c.sessionId,title:c.title,lastActiveAt:c.lastActiveAt,messageCount:c.messageCount,model:c.model,pinnedAt:c.pinnedAt,archivedAt:c.archivedAt,sealedAt:c.sealedAt,projectId:c.projectId,type:c.type??"personal",createdAt:c.createdAt,groupKey:c.groupKey,previousSessionId:c.previousSessionId,carryoverSummary:c.carryoverSummary??null})}catch{}}return o.sort((s,i)=>s.lastActiveAt>i.lastActiveAt?-1:s.lastActiveAt<i.lastActiveAt?1:0),o.slice(0,t)}async function Ka(t,e){let r=qr(t,e);await G.promises.rm(r,{recursive:!0,force:!0})}function hA(t){return t.turnCount<Ia?!1:t.taskSummaryGeneratedAt?t.turnCount-(t.taskSummaryGeneratedAt??0)>=Ea:!0}var yA="Based on the user's message below, generate a very short session title (2-8 Chinese characters or 3-6 English words). The title should capture the main topic or intent. Reply with ONLY the title text, no quotes, no punctuation.";async function ip(t,e){if(!t.trim())return null;try{let r=e.transport.stream({model:e.model,messages:[{role:"system",content:yA},{role:"user",content:t.slice(0,500)}],tools:[],maxTokens:30},e.apiKey),n="";for await(let o of r)o.type==="delta"&&(n+=o.text);return n=n.trim().replace(/^["'""'']+|["'""'']+$/g,""),n||null}catch{return null}}async function ap(t,e,r,n,o){if(!hA(e))return null;try{let i=r.slice(-20).map(u=>`[${u.role}]: ${typeof u.content=="string"?u.content.slice(0,500):JSON.stringify(u.content).slice(0,500)}`).join(`
|
|
38
|
+
`),a=n.transport.stream({model:n.model,messages:[{role:"system",content:"Generate a concise task summary (~100 words) of what the user is working on in this session. Focus on the goal, key decisions, and current progress. Reply with ONLY the summary."},{role:"user",content:i}],tools:[],maxTokens:200},n.apiKey),c="";for await(let u of a)u.type==="delta"&&(c+=u.text);if(c=c.trim(),!c)return null;let l=qr(t,o),d=Ce.join(l,Kt);try{let u=await G.promises.readFile(d,"utf8"),p=JSON.parse(u);p.taskSummary=c,p.taskSummaryGeneratedAt=e.turnCount;let m=d+".tmp";await G.promises.writeFile(m,JSON.stringify(p,null,2),"utf8"),await G.promises.rename(m,d)}catch{}return c}catch{return null}}import{randomUUID as VU}from"node:crypto";var bA=3e4;var Uo=class{tasks=new Map;listeners=new Set;hooks=null;sessionId="";setHooks(e,r){this.hooks=e,this.sessionId=r}onTaskChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(e,r){for(let n of this.listeners)try{n(e,r)}catch{}}registerTask(e){this.tasks.set(e.taskId,e),this.notify(e.taskId,e),this.hooks?.invoke("task.created",{sessionId:this.sessionId,taskId:e.taskId,taskType:e.type,label:e.label}).catch(()=>{})}updateTask(e,r){let n=this.tasks.get(e);if(!n)return;let o=r(n);o!==n&&(this.tasks.set(e,o),this.notify(e,o),!$o(n.lifecycle)&&$o(o.lifecycle)&&this.hooks?.invoke("task.completed",{sessionId:this.sessionId,taskId:o.taskId,taskType:o.type,label:o.label}).catch(()=>{}))}getTask(e){return this.tasks.get(e)}getRunningTasks(){return[...this.tasks.values()].filter(e=>e.lifecycle==="running")}getAllTasks(){return[...this.tasks.values()]}evictTask(e){let r=this.tasks.get(e);r&&$o(r.lifecycle)&&(this.tasks.delete(e),this.notify(e,null))}evictStaleTasks(e=bA){let r=Date.now();for(let[n,o]of this.tasks)$o(o.lifecycle)&&o.endedAt&&r-o.endedAt>e&&(this.tasks.delete(n),this.notify(n,null))}};function $o(t){return t==="completed"||t==="failed"||t==="cancelled"||t==="timeout"}var za=new Set;function Vt(t){return za.add(t),()=>{za.delete(t)}}async function cp(){await Promise.all(Array.from(za).map(t=>t()))}D();We();var Bo="\u65E0\u6CD5\u8FDE\u63A5 llmrouter \u6A21\u578B\u76EE\u5F55",ne="llmrouter",Xa="LLMRouter",Xt=class extends Error{constructor(e=Bo){super(e),this.name="LlmrouterCatalogUnavailableError"}};function gp(){let t=process.env.QLOGIC_LLMROUTER_BASE_URL?.trim().replace(/\/+$/,"");if(!t)throw new Xt;return t}function fp(){return gp()}function PA(){let t={accept:"application/json"},e=process.env.QLOGIC_LLMROUTER_ACCESS_TOKEN?.trim();return e&&(t.authorization=`Bearer ${e}`),t}async function hp(t){let e=gp(),r;try{r=await fetch(`${e}${t}`,{method:"GET",headers:PA(),signal:AbortSignal.timeout(1e4)})}catch{throw new Xt}if(!r.ok)throw new Xt;let n=await r.json().catch(()=>null),o=Array.isArray(n)?n:Sp(n)&&Array.isArray(n.data)?n.data:null;if(!o)throw new Xt;return o}function Ya(t){let e=t.trim().replace(/\/+$/,"");return e.endsWith("/v1")?`${e}/models`:`${e}/v1/models`}async function CA(t,e){let r;try{r=await fetch(t,{method:"GET",headers:{accept:"application/json",authorization:`Bearer ${e}`},signal:AbortSignal.timeout(1e4)})}catch{throw new Xt}if(!r.ok)throw new Xt;let n=await r.json().catch(()=>null),o=Array.isArray(n)?n:Sp(n)&&Array.isArray(n.data)?n.data:null;if(!o)throw new Xt;return o}async function Ja(){return hp("/ext/model-catalog/providers")}async function IA(){return hp("/ext/model-catalog/models")}async function EA(t,e){return CA(Ya(t),e)}function yp(t){let e={zhipu:"Zhipu GLM","zhipu-openai":"Zhipu GLM OpenAI","zhipu-coding":"Zhipu GLM Coding",volcengine:"Doubao / Volcengine"};return e[t.id]?e[t.id]:t.displayName??t.name??t.id}function Qa(t){return t.baseUrl??t.base_url}async function bp(t){return(await Ja()).find(r=>r.id===t)??null}async function Cn(t){let e=await IA();t.migrateModelIds(vp(e));let r=e.flatMap(kp);return t.replaceCatalogModels(r),r}async function Za(t,e){let r=await EA(e.baseUrl,e.apiKey);if(r.length===0)return[];t.migrateModelIds(vp(r));let n=r.flatMap(kp).filter(o=>o.provider===ne).map(o=>({...o,baseUrl:e.baseUrl}));return t.replaceProviderModels(ne,n),n}function vp(t){let e=new Map;for(let r of t){let n=r.provider??r.owned_by,o=r.public_model??r.publicModel??r.id,s=r.native_model_id??r.nativeModelId??r.id;if(!o)continue;let i=`${ne}:${o}`;if(n){let a=`${n}:${o}`;for(let c of[o,s,r.id]){if(!c)continue;let l=`${n}:${c}`;l!==a&&e.set(l,a)}}for(let a of[s,r.id]){if(!a)continue;let c=`${ne}:${a}`;c!==i&&e.set(c,i)}}return e}function kp(t){return[_A(t),MA(t)].filter(e=>!!e)}function _A(t){let e=t.provider??t.owned_by,r=t.public_model??t.publicModel??t.id,n=t.native_model_id??t.nativeModelId??t.id;return!e||!r||!n?null:{id:`${e}:${r}`,provider:e,model:r,displayName:t.display_name??t.displayName??t.name??t.id,purposes:Rp(t.purposes,t.category),baseUrl:t.baseUrl??t.base_url,enabled:!0,nativeModelId:n,transport:t.provider_transport??t.providerTransport,contextWindow:t.context_window??t.contextWindow,maxOutput:t.max_output??t.maxOutput,streamRequired:t.stream_required??t.streamRequired,capabilities:t.capabilities,pricing:t.pricing}}function MA(t){let e=t.public_model??t.publicModel??t.id;return e?{id:`${ne}:${e}`,provider:ne,model:e,displayName:t.display_name??t.displayName??t.name??t.id,purposes:Rp(t.purposes,t.category),enabled:!0,nativeModelId:e,transport:"openai-responses",contextWindow:t.context_window??t.contextWindow,maxOutput:t.max_output??t.maxOutput,streamRequired:t.stream_required??t.streamRequired,capabilities:t.capabilities,pricing:t.pricing}:null}function Rp(t,e){let r=[...t??[],e].filter(s=>!!s),n=new Set(["textGeneration","smallModel","stt","tts","imageGeneration","imageUnderstanding","videoGeneration","videoUnderstanding","threeDGeneration","embedding","voiceClone","musicGeneration","realtimeAudio","realtimeVideo"]),o=r.filter(s=>n.has(s));return[...new Set(o.length?o:["textGeneration"])]}function Sp(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}import{join as ec}from"node:path";import{mkdirSync as DA,existsSync as NA,createWriteStream as LA}from"node:fs";import{pipeline as OA}from"node:stream/promises";import{Readable as jA}from"node:stream";var $A=Na,UA=La,wp={"image/png":".png","image/jpeg":".jpg","image/gif":".gif","image/webp":".webp","image/svg+xml":".svg","image/avif":".avif","video/mp4":".mp4","video/webm":".webm","video/quicktime":".mov","audio/mpeg":".mp3","audio/wav":".wav","audio/ogg":".ogg","audio/aac":".aac","audio/mp4":".m4a","audio/flac":".flac","application/pdf":".pdf","model/gltf-binary":".glb","model/gltf+json":".gltf"},qo=class{projectDir;maxFileSize;timeoutMs;constructor(e){this.projectDir=e?.projectDir??null,this.maxFileSize=e?.maxFileSize??$A,this.timeoutMs=e?.timeoutMs??UA}setProjectDir(e){this.projectDir=e}resolveMediaDir(e){if(!this.projectDir)throw new Error("MediaPersistence requires projectDir \u2014 call setProjectDir() first");if(!e)return ec(this.projectDir,".qlogicagent","media",FA());let r=e.replace(/[^a-zA-Z0-9_-]/g,"_");return r!==e&&r.length>0&&[...e].filter(o=>!/[a-zA-Z0-9_-]/.test(o)).length>e.length/2&&console.warn(`[media-persistence] sessionId heavily sanitized: "${e}" \u2192 "${r}" \u2014 potential collision risk`),ec(this.projectDir,".qlogicagent","sessions",r,"media")}async download(e,r){let n=this.resolveMediaDir(r?.sessionId);if(n.length+60>255)throw new Error(`Media path too long (${n.length} chars) \u2014 would exceed OS limit. Use a shorter project path or session ID.`);NA(n)||DA(n,{recursive:!0});let o=new AbortController,s=setTimeout(()=>o.abort(),this.timeoutMs),i="";try{let a=await fetch(e,{signal:o.signal});if(!a.ok)throw new Error(`Download failed: ${a.status} ${a.statusText}`);let c=parseInt(a.headers.get("content-length")??"0",10);if(c>this.maxFileSize)throw new Error(`File too large: ${c} bytes (max: ${this.maxFileSize})`);let l=a.headers.get("content-type")?.split(";")[0].trim()||"application/octet-stream",d=BA(e,l),u=HA(r?.type??qA(l),d);i=ec(n,u);let p=a.body;if(!p)throw new Error("No response body");let m=LA(i);await OA(jA.fromWeb(p),m);let{size:g}=await import("node:fs/promises").then(f=>f.stat(i));if(g===0)throw await import("node:fs/promises").then(f=>f.unlink(i).catch(()=>{})),new Error("Download produced empty file (connection dropped)");return{remoteUrl:e,localPath:i,bytes:g,mimeType:l}}catch(a){if(i)try{let{unlink:c}=await import("node:fs/promises");await c(i)}catch{}throw a}finally{clearTimeout(s)}}async downloadAll(e,r,n){let o=[];for(let s of e)try{let i=await this.download(s,r);o.push(i)}catch(i){n?.warn(`media-persistence: failed to download ${s}: ${i.message}`)}return o}getMediaDir(e){return this.resolveMediaDir(e)}getProjectDir(){return this.projectDir}};function FA(){let t=new Date;return`${t.getFullYear()}${String(t.getMonth()+1).padStart(2,"0")}${String(t.getDate()).padStart(2,"0")}`}function HA(t,e){let r=new Date,n=`${r.getFullYear()}${String(r.getMonth()+1).padStart(2,"0")}${String(r.getDate()).padStart(2,"0")}_${String(r.getHours()).padStart(2,"0")}${String(r.getMinutes()).padStart(2,"0")}${String(r.getSeconds()).padStart(2,"0")}`,o=Math.random().toString(36).slice(2,6);return`${t}_${n}_${o}${e}`}function BA(t,e){if(wp[e])return wp[e];try{let r=new URL(t).pathname,n=r.lastIndexOf(".");if(n>0){let o=r.slice(n).toLowerCase().split("?")[0];if(o.length<=5)return o}}catch{}return".bin"}function qA(t){return t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":t.startsWith("model/")?"3d":"file"}var kr="1.0.0",y={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030,REQUEST_DEADLINE_EXCEEDED:-32040,REQUEST_CANCELLED:-32041,REQUEST_DEDUPED:-32042,REQUEST_IDEMPOTENCY_REQUIRED:-32043};function tc(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&e.method.length>0}import{randomUUID as WA}from"node:crypto";var GA=["settings.list","settings.get","settings.validate","provider.list","config.get","config.tunables","tools.list","todos.list","tasks.list","agents.list","agents.get","agents.processes","agents.scan","session.list","session.get","session.resolve","thread.list","project.list","files.list","files.gitStatus","instructions.list","instructions.read","skills.list","skills.stats","memory.atlas","memory.activity","memory.list","memory.read","memory.search","media.listModels","media.status","pet.status","agent.health","agent.metrics"],KA=new Set(["thread.turn","memory.dream","memory.propose","memory.consolidate","media.stt","pet.forge","solo.start","solo.evaluate","product.plan","product.create","product.message"]),zA=["memory.","pet.","usage."],VA=new Set(["memory.atlas","memory.activity","memory.list","memory.read","memory.search","pet.status"]);function Wo(t){return KA.has(t)?{channel:"task",mutability:"write",defaultTimeoutMs:t==="thread.turn"?3e5:12e4}:GA.some(e=>t===e||t.startsWith(`${e}.`)||t.startsWith(e))?{channel:"query",mutability:"read",defaultTimeoutMs:1e4}:{channel:"task",mutability:"write",defaultTimeoutMs:3e4}}function Tp(t){return VA.has(t)||Wo(t).mutability==="read"?!1:zA.some(e=>t.startsWith(e))}function rc(t,e={}){let r=e.now??Date.now(),n=Wo(t),o=e.timeoutMs??n.defaultTimeoutMs;return{requestId:e.requestId??WA(),createdAt:r,deadlineAt:r+o,channel:e.channel??n.channel,idempotencyKey:e.idempotencyKey,traceId:e.traceId}}function Go(t,e=Date.now()){let r=t.meta;if(!r||typeof r!="object")return{ok:!1,error:{code:y.INVALID_REQUEST,message:"RPC request meta is required."}};if(typeof r.requestId!="string"||r.requestId.length===0)return{ok:!1,error:{code:y.INVALID_REQUEST,message:"RPC request meta.requestId is required."}};if(r.channel!=="query"&&r.channel!=="task")return{ok:!1,error:{code:y.INVALID_REQUEST,message:"RPC request meta.channel must be query or task."}};if(typeof r.createdAt!="number"||!Number.isFinite(r.createdAt))return{ok:!1,error:{code:y.INVALID_REQUEST,message:"RPC request meta.createdAt is required."}};if(typeof r.deadlineAt!="number"||!Number.isFinite(r.deadlineAt))return{ok:!1,error:{code:y.INVALID_REQUEST,message:"RPC request meta.deadlineAt is required."}};if(r.deadlineAt<=e)return{ok:!1,error:{code:y.REQUEST_DEADLINE_EXCEEDED,message:"RPC request deadline has already expired."}};let n=Wo(t.method).channel;return r.channel!==n?{ok:!1,error:{code:y.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${n}, got ${r.channel}.`}}:Tp(t.method)&&(typeof r.idempotencyKey!="string"||r.idempotencyKey.length===0)?{ok:!1,error:{code:y.REQUEST_IDEMPOTENCY_REQUIRED,message:`RPC method ${t.method} requires meta.idempotencyKey.`}}:{ok:!0,meta:r}}var In=class{now;active=new Map;idempotency=new Map;counters={completedRequests:0,cancelledRequests:0,deadlineExceededRequests:0,dedupedRequests:0,lateResponsesDropped:0,invalidRequests:0};constructor(e={}){this.now=e.now??(()=>Date.now())}begin(e,r){let n=Go({method:e,meta:r},this.now());if(!n.ok)return this.counters.invalidRequests+=1,{status:"rejected",error:n.error};if(r.idempotencyKey){let o=this.idempotency.get(r.idempotencyKey);if(o)return this.counters.dedupedRequests+=1,o.error?{status:"deduped",error:o.error}:{status:"deduped",result:o.result}}return this.active.set(r.requestId,{method:e,meta:r,cancelled:!1,startedAt:this.now()}),{status:"started"}}cancel(e,r="cancelled"){let n=this.active.get(e);return!n||n.cancelled?!1:(n.cancelled=!0,n.cancelReason=r,this.counters.cancelledRequests+=1,!0)}expire(e){return this.active.get(e)?(this.active.delete(e),this.counters.deadlineExceededRequests+=1,!0):!1}settle(e,r,n){let o=this.active.get(e);return o?(this.active.delete(e),o.cancelled?(this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"cancelled"}):o.meta.deadlineAt<=this.now()?(this.counters.deadlineExceededRequests+=1,this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"deadline_exceeded"}):(this.counters.completedRequests+=1,o.meta.idempotencyKey&&this.idempotency.set(o.meta.idempotencyKey,{result:r,error:n,settledAt:this.now()}),{accepted:!0})):{accepted:!1,reason:"unknown"}}metrics(){return{activeRequests:this.active.size,...this.counters}}};var Ap=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated","skills.updated","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.forged","system.activity"],xp=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.checkpointed","product.dagTopology","plan.interrupted"],XA=[...Ap,...xp];var bt={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_END:"session/end",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},Z={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",PRODUCT_SUBSCRIBE:"x/product.subscribe",TEAM_DELEGATE:"x/team.delegate"},vt={AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update"},ue={X_SUBAGENT_STARTED:"x_subagent_started",X_SUBAGENT_DELTA:"x_subagent_delta",X_SUBAGENT_ENDED:"x_subagent_ended",X_MEDIA_RESULT:"x_media_result",X_MEDIA_PROGRESS:"x_media_progress",X_SKILL_INSTRUCTION:"x_skill_instruction",X_RECOVERY:"x_recovery",X_SIDECHAIN_STARTED:"x_sidechain_started",X_SIDECHAIN_COMPLETED:"x_sidechain_completed",X_SUGGESTIONS:"x_suggestions",X_ASK_USER:"x_ask_user",X_SESSION_INFO:"x_session_info",X_MEMORY_UPDATED:"x_memory_updated",X_TEAM_MEMBER_UPDATE:"x_team_member_update",X_SOLO_STARTED:"x_solo_started",X_SOLO_AGENT_FINISHED:"x_solo_agent_finished",X_SOLO_SELECTED:"x_solo_selected",X_PRODUCT_TASK_STARTED:"x_product_task_started",X_PRODUCT_TASK_COMPLETED:"x_product_task_completed",X_PRODUCT_CHECKPOINT:"x_product_checkpoint"};function En(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&"id"in e}function _n(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&typeof e.method=="string"&&!("id"in e)}function nc(t){if(!t||typeof t!="object")return!1;let e=t;return e.jsonrpc==="2.0"&&"id"in e&&!("method"in e)}var Pp="openai-codex";var RF={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[Pp]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};import{randomUUID as YA}from"node:crypto";var Ko={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,PROTOCOL_MISMATCH:-32001,SESSION_NOT_FOUND:-32002,AGENT_BUSY:-32003},zo=class{transport;handler;verbose;hostCapabilities={};hostSupportsExtendedEvents=!1;hostSupportsExtendedMethods=!1;activeSessionId=null;pendingPermissions=new Map;outboundRequestMap=new Map;constructor(e,r,n){this.transport=e,this.handler=r,this.verbose=n?.verbose??!1}dispatchMessage(e){if(this.isJsonRpcResponse(e))return this.handleResponse(e),!0;if(En(e)){let r=e;return process.stderr.write(`[acp-server] \u922B?recv id=${String(r.id)} method=${r.method}
|
|
39
39
|
`),this.handleRequest(r),!0}return _n(e)?(this.handleNotification(e),!0):!1}emitSessionUpdate(e,r,n){if(r.startsWith("x_")&&!this.hostSupportsExtendedEvents)return;let o={jsonrpc:"2.0",method:bt.SESSION_UPDATE,params:{sessionId:e,update:{sessionUpdate:r,...n}}};this.transport.send(o)}async requestPermission(e){let r=`perm-${YA().slice(0,8)}`,n={jsonrpc:"2.0",method:bt.SESSION_REQUEST_PERMISSION,params:e,id:r};return new Promise(o=>{this.outboundRequestMap.set(r,e.permissionId),this.pendingPermissions.set(e.permissionId,{resolve:s=>o({optionId:s})}),this.transport.send(n)})}get supportsExtendedEvents(){return this.hostSupportsExtendedEvents}get supportsExtendedMethods(){return this.hostSupportsExtendedMethods}get sessionId(){return this.activeSessionId}async handleRequest(e){let{method:r,params:n,id:o}=e,s=n??{};try{switch(r){case bt.INITIALIZE:await this.onInitialize(o,s);break;case bt.SESSION_NEW:await this.onSessionNew(o,s);break;case bt.SESSION_PROMPT:await this.onSessionPrompt(o,s);break;case bt.SESSION_END:await this.onSessionEnd(o,s);break;case bt.SESSION_SET_CONFIG:await this.onSessionSetConfig(o,s);break;case bt.SESSION_SET_MODEL:await this.handler.handleAcpSessionSetModel(s.sessionId??this.activeSessionId??"",s.modelId??s.model??""),this.sendResult(o,{});break;case bt.SESSION_SET_MODE:await this.handler.handleAcpSessionSetMode(s.sessionId??this.activeSessionId??"",s.modeId??s.mode??""),this.sendResult(o,{});break;case Z.ABORT:await this.onAbort(o,s);break;case Z.DREAM:await this.onDream(o,s);break;case Z.AGENTS_LIST:{let i=await this.handler.handleAcpAgentsList();this.sendResult(o,i);break}case Z.SOLO_START:{let i=await this.handler.handleAcpSoloStart(s);this.sendResult(o,i);break}case Z.SOLO_STATUS:{let i=await this.handler.handleAcpSoloStatus(s);this.sendResult(o,i);break}case Z.SOLO_SELECT:{let i=await this.handler.handleAcpSoloSelect(s);this.sendResult(o,i);break}case Z.SOLO_CANCEL:{let i=await this.handler.handleAcpSoloCancel(s);this.sendResult(o,i);break}case Z.SOLO_SUBSCRIBE:{let i=await this.handler.handleAcpSoloSubscribe(s);this.sendResult(o,i);break}case Z.SOLO_MESSAGE:{let i=await this.handler.handleAcpSoloMessage(s);this.sendResult(o,i);break}case Z.SOLO_EVALUATE:{let i=await this.handler.handleAcpSoloEvaluate(s);this.sendResult(o,i);break}case Z.PRODUCT_CREATE:{let i=await this.handler.handleAcpProductCreate(s);this.sendResult(o,i);break}case Z.PRODUCT_PLAN:{let i=await this.handler.handleAcpProductPlan(s);this.sendResult(o,i);break}case Z.PRODUCT_CONFIRM:{let i=await this.handler.handleAcpProductConfirm(s);this.sendResult(o,i);break}case Z.PRODUCT_MESSAGE:{let i=await this.handler.handleAcpProductMessage(s);this.sendResult(o,i);break}case Z.PRODUCT_PAUSE:{let i=await this.handler.handleAcpProductPause(s);this.sendResult(o,i);break}case Z.PRODUCT_RESUME:{let i=await this.handler.handleAcpProductResume(s);this.sendResult(o,i);break}case Z.PRODUCT_CANCEL:{let i=await this.handler.handleAcpProductCancel(s);this.sendResult(o,i);break}case Z.PRODUCT_ROLLBACK:{let i=await this.handler.handleAcpProductRollback(s);this.sendResult(o,i);break}case Z.PRODUCT_STATUS:{let i=await this.handler.handleAcpProductStatus(s);this.sendResult(o,i);break}case Z.PRODUCT_SUBSCRIBE:{let i=await this.handler.handleAcpProductSubscribe(s);this.sendResult(o,i);break}case Z.TEAM_DELEGATE:{let i=await this.handler.handleAcpTeamDelegate(s);this.sendResult(o,i);break}default:this.sendError(o,Ko.METHOD_NOT_FOUND,`Unknown method: ${r}`)}}catch(i){this.sendError(o,Ko.INTERNAL_ERROR,i.message)}}handleNotification(e){this.log(`received notification: ${e.method}`)}handleResponse(e){let r=this.outboundRequestMap.get(e.id);if(r){this.outboundRequestMap.delete(e.id);let n=this.pendingPermissions.get(r);if(n){this.pendingPermissions.delete(r);let o=e.result;n.resolve(o?.optionId??"deny")}}else this.log(`received response for id=${String(e.id)} (no matching outbound request)`)}async onInitialize(e,r){this.hostCapabilities=r.clientCapabilities??{},this.hostSupportsExtendedEvents=this.hostCapabilities.extendedEvents??!1,this.hostSupportsExtendedMethods=this.hostCapabilities.extendedMethods??!1;let n=r.clientInfo?.name??"unknown",o=r.clientInfo?.version??"unknown";this.log(`initialize: host=${n} v=${o}, proto=${String(r.protocolVersion)}, extendedEvents=${this.hostSupportsExtendedEvents}, extendedMethods=${this.hostSupportsExtendedMethods}`);let s=await this.handler.handleAcpInitialize(r);this.sendResult(e,s)}async onSessionNew(e,r){let n=await this.handler.handleAcpSessionNew(r);this.activeSessionId=n.sessionId,this.sendResult(e,n)}async onSessionPrompt(e,r){if(!this.activeSessionId||this.activeSessionId!==r.sessionId){this.sendError(e,Ko.SESSION_NOT_FOUND,`No active session with id: ${r.sessionId}`);return}let n=await this.handler.handleAcpSessionPrompt(r);this.sendResult(e,n)}async onSessionEnd(e,r){await this.handler.handleAcpSessionEnd(r),this.activeSessionId===r.sessionId&&(this.activeSessionId=null),this.sendResult(e,{})}async onSessionSetConfig(e,r){if(this.activeSessionId!==r.sessionId){this.sendError(e,Ko.SESSION_NOT_FOUND,`No active session with id: ${r.sessionId}`);return}await this.handler.handleAcpSessionSetConfig(r),this.sendResult(e,{})}async onAbort(e,r){await this.handler.handleAcpAbort(r),this.sendResult(e,{aborted:!0})}async onDream(e,r){let n=await this.handler.handleAcpDream(r);this.sendResult(e,n)}sendResult(e,r){process.stderr.write(`[acp-server] \u922B?send id=${String(e)} result
|
|
40
40
|
`);let n={jsonrpc:"2.0",id:e,result:r};this.transport.send(n)}sendError(e,r,n,o){process.stderr.write(`[acp-server] \u922B?send id=${String(e)} error=${n}
|
|
41
41
|
`);let s={jsonrpc:"2.0",id:e,error:{code:r,message:n,...o!==void 0?{data:o}:{}}};this.transport.send(s)}isJsonRpcResponse(e){if(!e||typeof e!="object")return!1;let r=e;return r.jsonrpc==="2.0"&&"id"in r&&("result"in r||"error"in r)&&!("method"in r)}log(e){this.verbose&&process.stderr.write(`[acp-server] ${e}
|
|
@@ -147,7 +147,7 @@ Return a brief summary of what you consolidated, updated, or pruned. If nothing
|
|
|
147
147
|
`}}catch{}let c="";if(i&&t.memoryProvider?.getAllProfiles)try{let h=t.memoryProvider.getAllProfiles(t.memoryUserId),v=Object.entries(h);if(v.length>0){let b=["## Known User Profile"];b.push("");for(let[S,T]of v.slice(0,20))b.push(`- **${S}**: ${T}`);c=`
|
|
148
148
|
`+b.join(`
|
|
149
149
|
`)+`
|
|
150
|
-
`}}catch{}let l=zp(t.context.memoryRoot,t.context.transcriptDir,o,{hasQMemory:i,categoryContext:s||void 0,temporalContext:a||void 0,profileContext:c||void 0});t.log.info(`[dream] starting consolidation \u2014 ${o.length} sessions, memoryRoot=${t.context.memoryRoot}`+(i?", memory=enabled":"")),t.hooks?.invoke("subagent.started",{sessionId:t.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream"}).catch(()=>{});let d=(h,v)=>wx(t.context.memoryRoot,{toolName:h,input:v}),u=i?[{type:"function",function:{name:"qmemory_search",description:"Search the user's long-term memory (QMemory). Returns relevant memories sorted by relevance.",parameters:{type:"object",properties:{query:{type:"string",description:"Semantic search query"},limit:{type:"number",description:"Max results (default: 10)"}},required:["query"]}}},{type:"function",function:{name:"qmemory_store",description:"Submit a low-priority candidate to the memory consolidation pipeline. Use for user preferences, facts, and cross-project knowledge; it may merge, conflict, or wait for confirmation.",parameters:{type:"object",properties:{text:{type:"string",description:"The candidate memory text to submit"},source:{type:"string",description:"Source label (e.g. 'dream-consolidation')"}},required:["text"]}}},{type:"function",function:{name:"qmemory_feedback",description:"Submit feedback on recalled memories (e.g. mark as outdated or wrong).",parameters:{type:"object",properties:{memoryIds:{type:"array",items:{type:"string"},description:"IDs of memories to give feedback on"},signal:{type:"string",enum:["useful","irrelevant","outdated","wrong"],description:"Feedback signal"}},required:["memoryIds","signal"]}}},{type:"function",function:{name:"qmemory_temporal",description:"Query memories by time range. Use for temporal synthesis ('what happened last week', 'recent decisions').",parameters:{type:"object",properties:{days:{type:"number",description:"Look back N days from today (default: 7)"},category:{type:"string",description:"Filter by category (optional)"}}}}},{type:"function",function:{name:"qmemory_profile",description:"Read or write user profile entries. Use 'get' to read all, 'set' to update a key.",parameters:{type:"object",properties:{action:{type:"string",enum:["get","set"],description:"Action to perform"},key:{type:"string",description:"Profile key (required for 'set')"},value:{type:"string",description:"Profile value (required for 'set')"}},required:["action"]}}}]:[],p=i?{invoke:async(h,v,b,S)=>{let T=t.memoryProvider,R=t.memoryUserId;if(v==="qmemory_search"){let{query:P,limit:I}=JSON.parse(b),E=await T.search(P,R,{limit:I??10});return{result:JSON.stringify(E)}}if(v==="qmemory_store"){if(!T.proposeExtracted)return{result:"",error:"memory proposals are not supported"};let{text:P,source:I}=JSON.parse(b),E=await T.proposeExtracted([{text:P,category:"insight",importance:.45}],R,{sessionId:t.context.currentSessionId,source:I??"dream-consolidation"});return{result:JSON.stringify(E)}}if(v==="qmemory_feedback"){if(!T.feedback)return{result:"Feedback noted (no handler)."};let{memoryIds:P,signal:I}=JSON.parse(b);return{result:`Feedback applied to ${(await T.feedback(P,I)).affected} memories.`}}if(v==="qmemory_temporal"){if(!T.synthesizeTimeline)return{result:"Temporal synthesis not available."};let{days:P,category:I}=JSON.parse(b),E=P??7,N=Date.now()-E*864e5;return{result:T.synthesizeTimeline(R,N,Date.now())}}if(v==="qmemory_profile"){let{action:P,key:I,value:E}=JSON.parse(b);if(P==="get"){if(!T.getAllProfiles)return{result:"{}"};let N=T.getAllProfiles(R);return{result:JSON.stringify(N)}}return P==="set"&&I&&E?T.setProfile?(T.setProfile(R,I,E),{result:`Profile updated: ${I} = ${E}`}):{result:"Profile write not available."}:{result:"Invalid profile action. Use 'get' or 'set' with key/value."}}return t.toolInvoker.invoke(h,v,b,S)}}:t.toolInvoker,m=new Set(["read","write","edit","patch","exec","search","qmemory_search","qmemory_store","qmemory_feedback","qmemory_temporal","qmemory_profile"]),f=[...t.tools.filter(h=>m.has(h.function.name)),...u];try{let h=await Wr({promptMessages:[{role:"user",content:"Begin memory consolidation."}],systemPrompt:l,tools:f,canUseTool:d,transport:t.transport,toolInvoker:p,createAgentRunner:t.createAgentRunner,apiKey:t.apiKey,model:t.model,log:t.log,hooks:void 0,forkLabel:"dream-consolidation",maxTurns:15,parentSignal:t.parentSignal,skipTranscript:!0}),v=[];for(let b of h.events)if(b.type==="tool_call")try{let S=JSON.parse(b.arguments),T=S.file_path??S.path??S.filePath;T&&Kp(T,t.context.memoryRoot)&&v.push(T)}catch{}return h.ok?(await Px(t.context.memoryRoot),t.log.info(`[dream] consolidation complete \u2014 ${v.length} files touched, ${h.durationMs}ms`)):(await qp(t.context.memoryRoot,n.priorLockMtime),t.log.warn(`[dream] consolidation failed: ${h.error}`)),t.hooks?.invoke("subagent.stopped",{sessionId:t.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:h.ok?"normal":"error",error:h.error}).catch(()=>{}),{ok:h.ok,sessionsReviewed:o.length,filesTouched:[...new Set(v)],turns:[],durationMs:Date.now()-e,error:h.error}}catch(h){await qp(t.context.memoryRoot,n.priorLockMtime).catch(()=>{});let v=h instanceof Error?h.message:String(h);return t.log.warn(`[dream] consolidation error: ${v}`),t.hooks?.invoke("subagent.stopped",{sessionId:t.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:"error",error:v}).catch(()=>{}),{ok:!1,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e,error:v}}}import*as Yo from"node:fs/promises";import*as ic from"node:path";var Yp={minIntervalHours:24,temporalExpiry:!0,stalenessDecay:!0,noiseArchival:!0},Jp=".last-decay";async function Ex(t,e={}){let r=(e.minIntervalHours??Yp.minIntervalHours)*36e5,n=ic.join(t,Jp);try{let o=await Yo.readFile(n,"utf-8"),s=parseInt(o.trim(),10);return isNaN(s)?!0:Date.now()-s>=r}catch{return!0}}async function _x(t){let e=ic.join(t,Jp);await Yo.writeFile(e,String(Date.now()),"utf-8")}async function Qp(t){let e=Date.now(),r={...Yp,...t.config};if(!await Ex(t.memoryRoot,r))return t.log?.debug?.("[decay] Skipped \u2014 cooldown not elapsed"),{ran:!1,decayed:0,archived:0,durationMs:Date.now()-e};t.log?.info("[decay] Starting importance decay cycle");try{let o=await t.adapter.triggerDecay(t.userId);await _x(t.memoryRoot);let s=Date.now()-e;return t.log?.info(`[decay] Completed \u2014 decayed=${o.decayed}, ${s}ms`),{ran:!0,decayed:o.decayed,archived:0,durationMs:s}}catch(o){let s=Date.now()-e;return t.log?.info(`[decay] Failed \u2014 ${o instanceof Error?o.message:String(o)}`),{ran:!1,decayed:0,archived:0,durationMs:s}}}We();var ac=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),Zp=new Set([...ac,"agent"]);function cc(t,e){let r=e?ac:Zp;return t.filter(n=>n.function.name.startsWith("mcp__")?!0:!r.has(n.function.name))}var Xt=new Map,lc=new Set;function em(t){Xt.clear(),lc.clear();for(let e of t)Xt.set(e.name,e)}function K(t){Xt.set(t.name,t)}function dc(t){for(let e of t)Xt.set(e.name,e)}function Jo(t){return Xt.delete(t)}function ve(t){return Xt.get(t)}function Yt(){return Array.from(Xt.keys())}function tm(t){let e=Xt.get(t);return!e||e.isEnabled?.()===!1?!1:(lc.add(t),!0)}function Ie(t=!1){let e=[];for(let r of Xt.values())r.isEnabled?.()!==!1&&(!t&&r.shouldDefer&&!lc.has(r.name)||e.push({type:"function",function:{name:r.name,description:r.description,parameters:r.parameters},meta:{category:r.category??"other",displayName:r.displayName??{key:`capability.tool.${r.name}.name`,fallback:r.label},displayDescription:r.displayDescription??{key:`capability.tool.${r.name}.description`,fallback:""},parallelSafe:r.isConcurrencySafe??!1,isReadOnly:r.isReadOnly??!1,isDangerous:!(r.isReadOnly??!1)&&!(r.isConcurrencySafe??!1)}}));return e}import{cleanSchemaForGemini as TB}from"@xiaozhiclaw/provider-core/gemini-schema-utils";function uc(t,e,r,n){return{role:"assistant",content:e||null,tool_calls:t,...r&&r.length>0?{thinkingBlocks:r}:{},...n?{reasoning_content:n}:{}}}function Qo(t,e){let r=e.ok?typeof e.payload=="string"?e.payload:JSON.stringify(e.payload??""):`Error: ${e.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:t,content:r,...!e.ok&&{is_error:!0},...e.toolReferences?.length?{toolReferences:e.toolReferences}:{},...e.imageUrls?.length?{imageUrls:e.imageUrls}:{}}}var Mx=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Sr={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Dx=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Nx=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Lx=512,Ox=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var jx=new Set([500,502,503,504,521,522,523,524,529]),$x=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ux=["upgrade your plan","upgrade plan","current plan","subscription"],Fx=["daily","weekly","monthly"],Hx=["try again","retry","temporary","cooldown"],Bx=["usage limit","rate limit","organization usage"],qx=["organization","workspace"],Wx=["billing period","exceeded","reached","exhausted"],Gx=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Kx=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function wr(t,e){if(!t)return!1;let r=t.toLowerCase();return e.some(n=>n instanceof RegExp?n.test(r):r.includes(n))}function zx(t){return wr(t,Sr.format)}function rm(t){return wr(t,Sr.rateLimit)}function Vx(t){return wr(t,Sr.timeout)}function Xx(t){return Mx.test(t)}function pc(t){let e=t.toLowerCase();return e?t.length>Lx?Nx.test(e):wr(e,Sr.billing)?!0:Dx.test(t)?e.includes("upgrade")||e.includes("credits")||e.includes("payment")||e.includes("plan"):!1:!1}function nm(t){return wr(t,Sr.authPermanent)}function Yx(t){return wr(t,Sr.auth)}function om(t){return wr(t,Sr.overloaded)}function Rr(t,e){return e.some(r=>t.includes(r))}function Jx(t){return Rr(t,$x)||Rr(t,Ux)&&t.includes("limit")||t.includes("billing hard limit")||t.includes("hard limit reached")||t.includes("maximum allowed")&&t.includes("limit")}function Qx(t){let e=Rr(t,Fx),r=t.includes("spend limit")||t.includes("spending limit"),n=Rr(t,qx);return Rr(t,Hx)&&Rr(t,Bx)||e&&(t.includes("usage limit")||r)||e&&t.includes("limit")&&t.includes("reset")||n&&t.includes("limit")&&(r||Rr(t,Wx))}function Zx(t){return t.trim().toLowerCase().replace(Kx,"").trim()}function sm(t){let e=Zx(t);return!e||Jx(e)?"billing":rm(e)||Qx(e)?"rate_limit":"billing"}function eP(t){return Gx.test(t)?sm(t):null}function im(t){let e=t.match(Ox);if(!e)return null;let r=Number(e[1]);return Number.isFinite(r)?{code:r,rest:(e[2]??"").trim()}:null}function tP(t){if(!t)return!1;let e=t.toLowerCase();return e.includes('"type":"api_error"')&&e.includes("internal server error")}function rP(t){let e=t.trim();if(!e)return!1;let r=im(e);return r?jx.has(r.code):!1}function am(t,e){return typeof t!="number"||!Number.isFinite(t)?null:t===402?e?sm(e):"billing":t===429?"rate_limit":t===401||t===403?e&&nm(e)?"auth_permanent":"auth":t===408?"timeout":t===503?e&&om(e)?"overloaded":"timeout":t===502||t===504?"timeout":t===529?"overloaded":t===400?e&&pc(e)?"billing":"format":null}function nP(t){if(!t)return!1;let e=t.toLowerCase();return!!(e.includes("unknown model")||e.includes("model not found")||e.includes("model_not_found")||e.includes("not_found_error")||e.includes("does not exist")&&e.includes("model")||e.includes("invalid model")&&!e.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(t)||/\b404\b/.test(t)&&/not[-_ ]?found/i.test(t))}function oP(t){if(!t)return!1;let e=t.toLowerCase();return e.includes("session not found")||e.includes("session does not exist")||e.includes("session expired")||e.includes("session invalid")||e.includes("conversation not found")||e.includes("conversation does not exist")||e.includes("conversation expired")||e.includes("conversation invalid")||e.includes("no such session")||e.includes("invalid session")||e.includes("session id not found")||e.includes("conversation id not found")}function cm(t){if(oP(t))return"session_expired";if(nP(t))return"model_not_found";let e=eP(t);return e||(Xx(t)?pc(t)?"billing":"rate_limit":rm(t)?"rate_limit":om(t)?"overloaded":rP(t)?im(t.trim())?.code===529?"overloaded":"timeout":tP(t)?"timeout":zx(t)?"format":pc(t)?"billing":Vx(t)?"timeout":nm(t)?"auth_permanent":Yx(t)?"auth":null)}var sP={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"},iP=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Gr(t,e){let r=am(t,e)??(e?cm(e):null);return r?sP[r]:typeof t=="number"&&t>=400&&t<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function mc(t){return iP.has(t)}function On(t){return typeof t.compressAsync=="function"}var lm=4,Kr=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,r){let n=[],o=[];for(let d of e)d.role==="system"?n.push(d):o.push(d);let s=r;for(let d of n)s-=this.estimateTokens(d);let i;for(let d of o)if(d.role==="user"){i=d;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...n,i]:n,droppedCount:o.length-(i?1:0),strategy:"sliding-window"};let a=[],c=0;for(let d=o.length-1;d>=0;d--){let u=o[d];if(u===i)continue;let p=this.estimateTokens(u);if(s-p<0&&c>=lm)break;if(s-p<0&&c<lm){a.unshift(u),c++;continue}s-=p,a.unshift(u),c++}let l=[...n];return i&&!a.includes(i)&&l.push(i),l.push(...a),{messages:l,droppedCount:o.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}};var Tr=class{constructor(e=8e3){this.maxToolResultChars=e}maxToolResultChars;compress(e,r){let n=0;return{messages:e.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(n++,{...s,content:aP(s.content,this.maxToolResultChars)})),droppedCount:n,strategy:"tool-result-trim"}}};function aP(t,e){if(t.length<=e)return t;let r=t.slice(0,e);if(t.trimStart().startsWith("{")||t.trimStart().startsWith("[")){let s=Math.max(r.lastIndexOf("},"),r.lastIndexOf("],"),r.lastIndexOf(`}
|
|
150
|
+
`}}catch{}let l=zp(t.context.memoryRoot,t.context.transcriptDir,o,{hasQMemory:i,categoryContext:s||void 0,temporalContext:a||void 0,profileContext:c||void 0});t.log.info(`[dream] starting consolidation \u2014 ${o.length} sessions, memoryRoot=${t.context.memoryRoot}`+(i?", memory=enabled":"")),t.hooks?.invoke("subagent.started",{sessionId:t.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream"}).catch(()=>{});let d=(h,v)=>wx(t.context.memoryRoot,{toolName:h,input:v}),u=i?[{type:"function",function:{name:"qmemory_search",description:"Search the user's long-term memory (QMemory). Returns relevant memories sorted by relevance.",parameters:{type:"object",properties:{query:{type:"string",description:"Semantic search query"},limit:{type:"number",description:"Max results (default: 10)"}},required:["query"]}}},{type:"function",function:{name:"qmemory_store",description:"Submit a low-priority candidate to the memory consolidation pipeline. Use for user preferences, facts, and cross-project knowledge; it may merge, conflict, or wait for confirmation.",parameters:{type:"object",properties:{text:{type:"string",description:"The candidate memory text to submit"},source:{type:"string",description:"Source label (e.g. 'dream-consolidation')"}},required:["text"]}}},{type:"function",function:{name:"qmemory_feedback",description:"Submit feedback on recalled memories (e.g. mark as outdated or wrong).",parameters:{type:"object",properties:{memoryIds:{type:"array",items:{type:"string"},description:"IDs of memories to give feedback on"},signal:{type:"string",enum:["useful","irrelevant","outdated","wrong"],description:"Feedback signal"}},required:["memoryIds","signal"]}}},{type:"function",function:{name:"qmemory_temporal",description:"Query memories by time range. Use for temporal synthesis ('what happened last week', 'recent decisions').",parameters:{type:"object",properties:{days:{type:"number",description:"Look back N days from today (default: 7)"},category:{type:"string",description:"Filter by category (optional)"}}}}},{type:"function",function:{name:"qmemory_profile",description:"Read or write user profile entries. Use 'get' to read all, 'set' to update a key.",parameters:{type:"object",properties:{action:{type:"string",enum:["get","set"],description:"Action to perform"},key:{type:"string",description:"Profile key (required for 'set')"},value:{type:"string",description:"Profile value (required for 'set')"}},required:["action"]}}}]:[],p=i?{invoke:async(h,v,b,S)=>{let T=t.memoryProvider,R=t.memoryUserId;if(v==="qmemory_search"){let{query:P,limit:I}=JSON.parse(b),E=await T.search(P,R,{limit:I??10});return{result:JSON.stringify(E)}}if(v==="qmemory_store"){if(!T.proposeExtracted)return{result:"",error:"memory proposals are not supported"};let{text:P,source:I}=JSON.parse(b),E=await T.proposeExtracted([{text:P,category:"insight",importance:.45}],R,{sessionId:t.context.currentSessionId,source:I??"dream-consolidation"});return{result:JSON.stringify(E)}}if(v==="qmemory_feedback"){if(!T.feedback)return{result:"Feedback noted (no handler)."};let{memoryIds:P,signal:I}=JSON.parse(b);return{result:`Feedback applied to ${(await T.feedback(P,I)).affected} memories.`}}if(v==="qmemory_temporal"){if(!T.synthesizeTimeline)return{result:"Temporal synthesis not available."};let{days:P,category:I}=JSON.parse(b),E=P??7,N=Date.now()-E*864e5;return{result:T.synthesizeTimeline(R,N,Date.now())}}if(v==="qmemory_profile"){let{action:P,key:I,value:E}=JSON.parse(b);if(P==="get"){if(!T.getAllProfiles)return{result:"{}"};let N=T.getAllProfiles(R);return{result:JSON.stringify(N)}}return P==="set"&&I&&E?T.setProfile?(T.setProfile(R,I,E),{result:`Profile updated: ${I} = ${E}`}):{result:"Profile write not available."}:{result:"Invalid profile action. Use 'get' or 'set' with key/value."}}return t.toolInvoker.invoke(h,v,b,S)}}:t.toolInvoker,m=new Set(["read","write","edit","patch","exec","search","qmemory_search","qmemory_store","qmemory_feedback","qmemory_temporal","qmemory_profile"]),f=[...t.tools.filter(h=>m.has(h.function.name)),...u];try{let h=await Wr({promptMessages:[{role:"user",content:"Begin memory consolidation."}],systemPrompt:l,tools:f,canUseTool:d,transport:t.transport,toolInvoker:p,createAgentRunner:t.createAgentRunner,apiKey:t.apiKey,model:t.model,log:t.log,hooks:void 0,forkLabel:"dream-consolidation",maxTurns:15,parentSignal:t.parentSignal,skipTranscript:!0}),v=[];for(let b of h.events)if(b.type==="tool_call")try{let S=JSON.parse(b.arguments),T=S.file_path??S.path??S.filePath;T&&Kp(T,t.context.memoryRoot)&&v.push(T)}catch{}return h.ok?(await Px(t.context.memoryRoot),t.log.info(`[dream] consolidation complete \u2014 ${v.length} files touched, ${h.durationMs}ms`)):(await qp(t.context.memoryRoot,n.priorLockMtime),t.log.warn(`[dream] consolidation failed: ${h.error}`)),t.hooks?.invoke("subagent.stopped",{sessionId:t.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:h.ok?"normal":"error",error:h.error}).catch(()=>{}),{ok:h.ok,sessionsReviewed:o.length,filesTouched:[...new Set(v)],turns:[],durationMs:Date.now()-e,error:h.error}}catch(h){await qp(t.context.memoryRoot,n.priorLockMtime).catch(()=>{});let v=h instanceof Error?h.message:String(h);return t.log.warn(`[dream] consolidation error: ${v}`),t.hooks?.invoke("subagent.stopped",{sessionId:t.context.currentSessionId,turnId:n.taskId,subagentId:n.taskId,agentType:"dream",reason:"error",error:v}).catch(()=>{}),{ok:!1,sessionsReviewed:0,filesTouched:[],turns:[],durationMs:Date.now()-e,error:v}}}import*as Yo from"node:fs/promises";import*as ic from"node:path";var Yp={minIntervalHours:24,temporalExpiry:!0,stalenessDecay:!0,noiseArchival:!0},Jp=".last-decay";async function Ex(t,e={}){let r=(e.minIntervalHours??Yp.minIntervalHours)*36e5,n=ic.join(t,Jp);try{let o=await Yo.readFile(n,"utf-8"),s=parseInt(o.trim(),10);return isNaN(s)?!0:Date.now()-s>=r}catch{return!0}}async function _x(t){let e=ic.join(t,Jp);await Yo.writeFile(e,String(Date.now()),"utf-8")}async function Qp(t){let e=Date.now(),r={...Yp,...t.config};if(!await Ex(t.memoryRoot,r))return t.log?.debug?.("[decay] Skipped \u2014 cooldown not elapsed"),{ran:!1,decayed:0,archived:0,durationMs:Date.now()-e};t.log?.info("[decay] Starting importance decay cycle");try{let o=await t.adapter.triggerDecay(t.userId);await _x(t.memoryRoot);let s=Date.now()-e;return t.log?.info(`[decay] Completed \u2014 decayed=${o.decayed}, ${s}ms`),{ran:!0,decayed:o.decayed,archived:0,durationMs:s}}catch(o){let s=Date.now()-e;return t.log?.info(`[decay] Failed \u2014 ${o instanceof Error?o.message:String(o)}`),{ran:!1,decayed:0,archived:0,durationMs:s}}}We();var ac=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),Zp=new Set([...ac,"agent"]);function cc(t,e){let r=e?ac:Zp;return t.filter(n=>n.function.name.startsWith("mcp__")?!0:!r.has(n.function.name))}var Yt=new Map,lc=new Set;function em(t){Yt.clear(),lc.clear();for(let e of t)Yt.set(e.name,e)}function K(t){Yt.set(t.name,t)}function dc(t){for(let e of t)Yt.set(e.name,e)}function Jo(t){return Yt.delete(t)}function ve(t){return Yt.get(t)}function Jt(){return Array.from(Yt.keys())}function tm(t){let e=Yt.get(t);return!e||e.isEnabled?.()===!1?!1:(lc.add(t),!0)}function Ie(t=!1){let e=[];for(let r of Yt.values())r.isEnabled?.()!==!1&&(!t&&r.shouldDefer&&!lc.has(r.name)||e.push({type:"function",function:{name:r.name,description:r.description,parameters:r.parameters},meta:{category:r.category??"other",displayName:r.displayName??{key:`capability.tool.${r.name}.name`,fallback:r.label},displayDescription:r.displayDescription??{key:`capability.tool.${r.name}.description`,fallback:""},parallelSafe:r.isConcurrencySafe??!1,isReadOnly:r.isReadOnly??!1,isDangerous:!(r.isReadOnly??!1)&&!(r.isConcurrencySafe??!1)}}));return e}import{cleanSchemaForGemini as AB}from"@xiaozhiclaw/provider-core/gemini-schema-utils";function uc(t,e,r,n){return{role:"assistant",content:e||null,tool_calls:t,...r&&r.length>0?{thinkingBlocks:r}:{},...n?{reasoning_content:n}:{}}}function Qo(t,e){let r=e.ok?typeof e.payload=="string"?e.payload:JSON.stringify(e.payload??""):`Error: ${e.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:t,content:r,...!e.ok&&{is_error:!0},...e.toolReferences?.length?{toolReferences:e.toolReferences}:{},...e.imageUrls?.length?{imageUrls:e.imageUrls}:{}}}var Mx=/\b(?:daily|weekly|monthly)(?:\/(?:daily|weekly|monthly))* (?:usage )?limit(?:s)?(?: (?:exhausted|reached|exceeded))?\b/i,Sr={rateLimit:[/rate[_ ]limit|too many requests|429/,"model_cooldown","exceeded your current quota","resource has been exhausted","quota exceeded","resource_exhausted","usage limit",/\btpm\b/i,"tokens per minute","tokens per day"],overloaded:[/overloaded_error|"type"\s*:\s*"overloaded_error"/i,"overloaded",/service[_ ]unavailable.*(?:overload|capacity|high[_ ]demand)|(?:overload|capacity|high[_ ]demand).*service[_ ]unavailable/i,"high demand"],timeout:["timeout","timed out","service unavailable","deadline exceeded","context deadline exceeded","connection error","network error","network request failed","fetch failed","socket hang up",/\beconn(?:refused|reset|aborted)\b/i,/\benotfound\b/i,/\beai_again\b/i,/without sending (?:any )?chunks?/i,/\bstop reason:\s*(?:abort|error|network_error)\b/i,/\breason:\s*(?:abort|error|network_error)\b/i,/\bunhandled stop reason:\s*(?:abort|error|network_error)\b/i],billing:[/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment/i,"payment required","insufficient credits",/insufficient[_ ]quota/i,"credit balance","plans & billing","insufficient balance"],authPermanent:[/api[_ ]?key[_ ]?(?:revoked|invalid|deactivated|deleted)/i,"invalid_api_key","key has been disabled","key has been revoked","account has been deactivated",/could not (?:authenticate|validate).*(?:api[_ ]?key|credentials)/i,"permission_error","not allowed for this organization"],auth:[/invalid[_ ]?api[_ ]?key/,"incorrect api key","invalid token","authentication","re-authenticate","oauth token refresh failed","unauthorized","forbidden","access denied","insufficient permissions","insufficient permission",/missing scopes?:/i,"expired","token has expired",/\b401\b/,/\b403\b/,"no credentials found","no api key found"],format:["string should match pattern","tool_use.id","tool_use_id","messages.1.content.1.tool_use.id","invalid request format",/tool call id was.*must be/i]},Dx=/^(?:error[:\s-]+)?billing(?:\s+error)?(?:[:\s-]+|$)|^(?:error[:\s-]+)?(?:credit balance|insufficient credits?|payment required|http\s*402\b)/i,Nx=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|^\s*402\s+payment/i,Lx=512,Ox=/^(?:http\s*)?(\d{3})(?:\s+([\s\S]+))?$/i;var jx=new Set([500,502,503,504,521,522,523,524,529]),$x=["insufficient credits","insufficient quota","credit balance","insufficient balance","plans & billing","add more credits","top up"],Ux=["upgrade your plan","upgrade plan","current plan","subscription"],Fx=["daily","weekly","monthly"],Hx=["try again","retry","temporary","cooldown"],Bx=["usage limit","rate limit","organization usage"],qx=["organization","workspace"],Wx=["billing period","exceeded","reached","exhausted"],Gx=/["']?(?:status|code)["']?\s*[:=]\s*402\b|\bhttp\s*402\b|\berror(?:\s+code)?\s*[:=]?\s*402\b|\b(?:got|returned|received)\s+(?:a\s+)?402\b|^\s*402\s+payment required\b/i,Kx=/^(?:error[:\s-]+)?(?:(?:http\s*)?402(?:\s+payment required)?|payment required)(?:[:\s-]+|$)/i;function wr(t,e){if(!t)return!1;let r=t.toLowerCase();return e.some(n=>n instanceof RegExp?n.test(r):r.includes(n))}function zx(t){return wr(t,Sr.format)}function rm(t){return wr(t,Sr.rateLimit)}function Vx(t){return wr(t,Sr.timeout)}function Xx(t){return Mx.test(t)}function pc(t){let e=t.toLowerCase();return e?t.length>Lx?Nx.test(e):wr(e,Sr.billing)?!0:Dx.test(t)?e.includes("upgrade")||e.includes("credits")||e.includes("payment")||e.includes("plan"):!1:!1}function nm(t){return wr(t,Sr.authPermanent)}function Yx(t){return wr(t,Sr.auth)}function om(t){return wr(t,Sr.overloaded)}function Rr(t,e){return e.some(r=>t.includes(r))}function Jx(t){return Rr(t,$x)||Rr(t,Ux)&&t.includes("limit")||t.includes("billing hard limit")||t.includes("hard limit reached")||t.includes("maximum allowed")&&t.includes("limit")}function Qx(t){let e=Rr(t,Fx),r=t.includes("spend limit")||t.includes("spending limit"),n=Rr(t,qx);return Rr(t,Hx)&&Rr(t,Bx)||e&&(t.includes("usage limit")||r)||e&&t.includes("limit")&&t.includes("reset")||n&&t.includes("limit")&&(r||Rr(t,Wx))}function Zx(t){return t.trim().toLowerCase().replace(Kx,"").trim()}function sm(t){let e=Zx(t);return!e||Jx(e)?"billing":rm(e)||Qx(e)?"rate_limit":"billing"}function eP(t){return Gx.test(t)?sm(t):null}function im(t){let e=t.match(Ox);if(!e)return null;let r=Number(e[1]);return Number.isFinite(r)?{code:r,rest:(e[2]??"").trim()}:null}function tP(t){if(!t)return!1;let e=t.toLowerCase();return e.includes('"type":"api_error"')&&e.includes("internal server error")}function rP(t){let e=t.trim();if(!e)return!1;let r=im(e);return r?jx.has(r.code):!1}function am(t,e){return typeof t!="number"||!Number.isFinite(t)?null:t===402?e?sm(e):"billing":t===429?"rate_limit":t===401||t===403?e&&nm(e)?"auth_permanent":"auth":t===408?"timeout":t===503?e&&om(e)?"overloaded":"timeout":t===502||t===504?"timeout":t===529?"overloaded":t===400?e&&pc(e)?"billing":"format":null}function nP(t){if(!t)return!1;let e=t.toLowerCase();return!!(e.includes("unknown model")||e.includes("model not found")||e.includes("model_not_found")||e.includes("not_found_error")||e.includes("does not exist")&&e.includes("model")||e.includes("invalid model")&&!e.includes("invalid model reference")||/models\/[^\s]+ is not found/i.test(t)||/\b404\b/.test(t)&&/not[-_ ]?found/i.test(t))}function oP(t){if(!t)return!1;let e=t.toLowerCase();return e.includes("session not found")||e.includes("session does not exist")||e.includes("session expired")||e.includes("session invalid")||e.includes("conversation not found")||e.includes("conversation does not exist")||e.includes("conversation expired")||e.includes("conversation invalid")||e.includes("no such session")||e.includes("invalid session")||e.includes("session id not found")||e.includes("conversation id not found")}function cm(t){if(oP(t))return"session_expired";if(nP(t))return"model_not_found";let e=eP(t);return e||(Xx(t)?pc(t)?"billing":"rate_limit":rm(t)?"rate_limit":om(t)?"overloaded":rP(t)?im(t.trim())?.code===529?"overloaded":"timeout":tP(t)?"timeout":zx(t)?"format":pc(t)?"billing":Vx(t)?"timeout":nm(t)?"auth_permanent":Yx(t)?"auth":null)}var sP={timeout:"RETRYABLE_TRANSIENT",overloaded:"RETRYABLE_TRANSIENT",rate_limit:"RETRYABLE_DEGRADED",auth:"NON_RETRYABLE_AUTH",auth_permanent:"NON_RETRYABLE_AUTH",billing:"NON_RETRYABLE_QUOTA",format:"NON_RETRYABLE_CONTENT",model_not_found:"NON_RETRYABLE_CONTENT",session_expired:"NON_RETRYABLE_CONTENT",unknown:"RETRYABLE_TRANSIENT"},iP=new Set(["RETRYABLE_TRANSIENT","RETRYABLE_DEGRADED","TOOL_EXECUTION_FAILED"]);function Gr(t,e){let r=am(t,e)??(e?cm(e):null);return r?sP[r]:typeof t=="number"&&t>=400&&t<500?"NON_RETRYABLE_CONTENT":"RETRYABLE_TRANSIENT"}function mc(t){return iP.has(t)}function On(t){return typeof t.compressAsync=="function"}var lm=4,Kr=class{constructor(e){this.estimateTokens=e}estimateTokens;compress(e,r){let n=[],o=[];for(let d of e)d.role==="system"?n.push(d):o.push(d);let s=r;for(let d of n)s-=this.estimateTokens(d);let i;for(let d of o)if(d.role==="user"){i=d;break}if(i&&(s-=this.estimateTokens(i)),s<=0)return{messages:i?[...n,i]:n,droppedCount:o.length-(i?1:0),strategy:"sliding-window"};let a=[],c=0;for(let d=o.length-1;d>=0;d--){let u=o[d];if(u===i)continue;let p=this.estimateTokens(u);if(s-p<0&&c>=lm)break;if(s-p<0&&c<lm){a.unshift(u),c++;continue}s-=p,a.unshift(u),c++}let l=[...n];return i&&!a.includes(i)&&l.push(i),l.push(...a),{messages:l,droppedCount:o.length-(a.length+(i&&!a.includes(i)?1:0)),strategy:"sliding-window"}}};var Tr=class{constructor(e=8e3){this.maxToolResultChars=e}maxToolResultChars;compress(e,r){let n=0;return{messages:e.map(s=>s.role!=="tool"||typeof s.content!="string"||s.content.length<=this.maxToolResultChars?s:(n++,{...s,content:aP(s.content,this.maxToolResultChars)})),droppedCount:n,strategy:"tool-result-trim"}}};function aP(t,e){if(t.length<=e)return t;let r=t.slice(0,e);if(t.trimStart().startsWith("{")||t.trimStart().startsWith("[")){let s=Math.max(r.lastIndexOf("},"),r.lastIndexOf("],"),r.lastIndexOf(`}
|
|
151
151
|
`),r.lastIndexOf(`]
|
|
152
152
|
`));if(s>e*.5)return r.slice(0,s+1)+`
|
|
153
153
|
[...truncated: ${t.length-s-1} chars omitted]`}let o=r.lastIndexOf(`
|
|
@@ -160,7 +160,7 @@ ${f}`},v=[...o,...u,h,...m],b=Date.now()-n,S=v.reduce((T,R)=>T+this.config.estim
|
|
|
160
160
|
`),i=o.filter(p=>!s.includes(p));if(i.length===0)return t;let a=r.maxTokenBudget,c=[],l=0;for(let p of i){if(l>=r.maxFiles||a<=0)break;let m=await r.readFile(p);if(!m)continue;let g=n(m);g>a||(a-=g,l++,c.push({role:"system",content:`[Post-compact file recovery: ${p}]
|
|
161
161
|
|
|
162
162
|
${m}`}))}if(c.length===0)return t;let d=[...t],u=-1;for(let p=0;p<d.length;p++)d[p].role==="system"&&(u=p);return d.splice(u+1,0,...c),d}function bc(t,e,r=hc){if(e.size===0)return{messages:t,tokensFreed:0,removedCount:0};let n=0,o=0,s=[];for(let a of t){let c=a.tool_call_id??"";if(c&&e.has(c)){n+=r(a),o++,e.delete(c);continue}s.push(a)}let i=o>0?{role:"system",content:`[${o} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:n,removedCount:o,boundaryMessage:i}}function vc(){return{stages:[]}}function kc(t,e,r){let n=r?.thresholdMessages??40;if(t.filter(a=>a.role!=="system").length<=n)return{messages:t,stagedCount:0};let s=pm(t,e),i=uP(s,e,n);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)e.stages.push(a);return s=pm(t,e),{messages:s,stagedCount:i.length}}function Rc(t,e){let r=0;for(let n of e.stages)n.committed||(n.committed=!0,r++);return r===0?{messages:t,committed:0}:{messages:mm(t,e),committed:r}}function pm(t,e){return e.stages.filter(n=>n.committed).length===0?t:mm(t,e)}function mm(t,e){let r=e.stages.filter(o=>o.committed).sort((o,s)=>s.range[0]-o.range[0]),n=[...t];for(let o of r){let[s,i]=o.range;if(s>=n.length)continue;let a=Math.min(i,n.length),c={role:"system",content:o.summary};n.splice(s,a-s,c)}return n}function uP(t,e,r){let n=Math.max(0,t.length-Math.floor(r/2)),o=[],s=new Set(e.stages.map(c=>`${c.range[0]}-${c.range[1]}`)),i=-1,a=0;for(let c=0;c<n;c++){let l=t[c];if(l.role==="tool"||l.role==="assistant"&&typeof l.content=="string"&&l.content==="")i<0&&(i=c),a++;else{if(a>=3){let u=`${i}-${i+a}`;s.has(u)||o.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let c=`${i}-${i+a}`;s.has(c)||o.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return o}import{existsSync as Sc,readFileSync as fm,writeFileSync as pP,readdirSync as hm,mkdirSync as mP}from"node:fs";import{join as wc,dirname as gP}from"node:path";var ym=0;var fP="skill-patterns.json";function bm(t){return wc(t,".qlogicagent",fP)}function hP(t){let e=bm(t);try{return JSON.parse(fm(e,"utf8"))}catch{return{version:1,patterns:{}}}}function gm(t,e){let r=bm(t);mP(gP(r),{recursive:!0}),pP(r,JSON.stringify(e,null,2),"utf8")}function yP(t){let e=Date.now()-ju;for(let[r,n]of Object.entries(t.patterns))new Date(n.lastSeen).getTime()<e&&delete t.patterns[r]}function vm(t,e){if(e.length===0)return!1;let r=ts(e),n=hP(t);yP(n);let o=new Date().toISOString(),s=n.patterns[r];if(s||(s={signature:r,count:0,firstSeen:o,lastSeen:o,promoted:!1},n.patterns[r]=s),s.promoted)return gm(t,n),!1;s.count++,s.lastSeen=o;let i=s.count>=Ou;return i&&(s.promoted=!0),gm(t,n),i}function ts(t){return[...t].sort().join("+")}function bP(t,e){if(!Sc(e))return null;let r=ts(t);try{let n=hm(e,{withFileTypes:!0});for(let o of n){if(!o.isDirectory())continue;let s=wc(e,o.name,"SKILL.md");try{let a=fm(s,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(a){let c=a[1].split(`
|
|
163
|
-
`).map(l=>l.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(ts(c)===r)return o.name}}catch{}}}catch{}return null}function vP(t){if(!Sc(t))return 0;try{return hm(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&Sc(wc(t,e.name,"SKILL.md"))).length}catch{return 0}}function kP(t,e){return!(!t.ok||t.existingSkillName||!t.multiStep||t.toolCallCount<ka||t.distinctToolCount<Ra||Date.now()-ym<Sa||e?.projectSkillsDir&&(vP(e.projectSkillsDir)>=va||e.tools.length>0&&bP(e.tools,e.projectSkillsDir))||e?.projectRoot&&e.tools.length>0&&!vm(e.projectRoot,e.tools))}function RP(t){return t.existingSkillName?t.feedback==="negative":!1}function rs(t,e){return RP(t)?{type:"skill.improve",skillName:t.existingSkillName,reason:"negative user feedback on existing skill execution"}:kP(t,e)?(ym=Date.now(),{type:"skill.create",suggestedName:e.suggestedName??`auto-skill-${e.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${e.tools.join(", ")}`,tools:e.tools,stepCount:t.toolCallCount}):null}function km(t){return t.function&&typeof t.function=="object"&&typeof t.function.name=="string"?t.function.name.trim():typeof t.name=="string"?t.name.trim():""}function SP(t){return t==="enabled-eligible"||t==="installed-awaiting-approval"}function wP(t){return new Map((t??[]).map(e=>[e.toolName,e]))}function TP(t){if(!t.eligibility?.length)return[...t.tools];let e=wP(t.eligibility);return t.tools.filter(r=>{let n=km(r);if(!n)return!1;let o=e.get(n);return!o||SP(o.status)})}function AP(t){let e=[],r=t.compatibility??{},n=t.toolChoice;if(t.thinkingEnabled&&r.requireAutoWhenThinking){let o=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;o&&o!=="auto"&&o!=="none"&&(e.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&r.allowRequiredToolChoice===!1){let o=r.requiredFallback??"auto";e.push(`tool_choice=required is not supported by this provider; downgraded to ${o}.`),n=o}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&r.allowNamedToolChoice===!1){let o=r.namedFallback??"required";e.push(`named tool_choice is not supported by this provider; downgraded to ${o}.`),n=o}return{normalizedToolChoice:n,warnings:e}}function Tc(t){let e=AP({toolChoice:t.toolChoice,thinkingEnabled:t.thinkingEnabled,compatibility:t.compatibility}),r=e.normalizedToolChoice,n=[...e.warnings],o=TP({tools:t.tools,eligibility:t.eligibility});if(!r||r==="auto")return{tools:o,normalizedToolChoice:r,warnings:n};if(r==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(r==="required"){if(o.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:o,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:n}}if(typeof r=="object"&&!Array.isArray(r)&&r.type==="function"){let s=r.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=o.filter(c=>km(c)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:n}}return{tools:o,normalizedToolChoice:r,warnings:n}}var xP=["stop","aborted","timeout","cancelled","interrupted","error"],PP=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Rm(t){return t==null?[]:typeof t=="string"?t.length>0?[{type:"text",text:t}]:[]:Array.isArray(t)?t:[{type:"text",text:String(t)}]}function CP(t,e){return{...t,content:[...Rm(t.content),...Rm(e.content)]}}function IP(t){if(!t||typeof t!="object")return!1;if(t.function&&typeof t.function=="object"){let e=t.function.name;if(typeof e=="string"&&e.length>0)return!0}return typeof t.name=="string"&&t.name.length>0}function EP(t){return new Set((t??xP).map(e=>e.trim().toLowerCase()))}function _P(t,e){return t?EP(e).has(t.trim().toLowerCase()):!1}function Ac(t){if(!Array.isArray(t)||t.length===0)return[...t];let e=t.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let c=a.tool_calls.filter(l=>IP(l));return{...a,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...a}}),r=new Set;for(let a of e)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let c of a.tool_calls)typeof c.id=="string"&&c.id&&r.add(c.id);let n=e.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&r.has(a.tool_call_id))),o=new Set;for(let a of n)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.add(a.tool_call_id);let s=[];for(let a of n){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let c=a.tool_calls.filter(l=>typeof l.id=="string"&&o.has(l.id));if(c.length===0){let{tool_calls:l,...d}=a;d.content!=null&&d.content!==""&&s.push(d);continue}if(c.length<a.tool_calls.length){s.push({...a,tool_calls:c});continue}}s.push(a)}let i=[];for(let a of s){let c=i.length>0?i[i.length-1]:void 0;if(a.role==="user"&&c?.role==="user"){i[i.length-1]=CP(c,a);continue}i.push(a)}return i}function xc(t,e){return _P(e?.stopReason,e?.forcedStopReasons)?t.map(r=>{if(r.role!=="assistant")return{...r};let n={...r};for(let o of PP)delete n[o];return n}):[...t]}function Pc(t,e){let r=e?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let s of t)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let o=[];for(let s of t)if(o.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||n.has(i.id)||(n.add(i.id),o.push({role:"tool",tool_call_id:i.id,content:r}));return o}function Cc(t,e){let r=Ac(t),n=xc(r,e);return Pc(n,e)}function MP(t){let e=new Set,r=new Set;for(let n of t){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let o of n.tool_calls)typeof o.id=="string"&&o.id&&e.add(o.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&r.add(n.tool_call_id)}return[...e].filter(n=>!r.has(n))}function DP(t){let e=new Set;for(let r of t)r.role==="tool"&&typeof r.tool_call_id=="string"&&r.tool_call_id&&e.add(r.tool_call_id);return[...e]}function NP(t){return{round:t.round??0,maxRounds:t.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??[]],completedToolCallIds:[...t.completedToolCallIds??[]],lastStopReason:t.lastStopReason,replayMessages:[...t.replayMessages??[]]}}function Ic(t,e){return{round:t.round+1,maxRounds:t.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??t.pendingToolCallIds],completedToolCallIds:[...e.completedToolCallIds??t.completedToolCallIds],lastStopReason:e.lastStopReason??t.lastStopReason,replayMessages:[...e.replayMessages??t.replayMessages]}}function ns(t,e){return{round:t.round,maxRounds:t.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...e.completedToolCallIds??t.completedToolCallIds],lastStopReason:e.lastStopReason??t.lastStopReason,replayMessages:[...e.replayMessages??t.replayMessages]}}function os(t){let e=[],r=Ac(t.replayMessages);r.length!==t.replayMessages.length&&e.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=xc(r,t.options);n.some((s,i)=>s!==r[i])&&e.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let o=Pc(n,t.options);return o.length>n.length&&e.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:NP({maxRounds:t.maxRounds,round:t.round,lastStopReason:t.lastStopReason,replayMessages:o,pendingToolCallIds:MP(o),completedToolCallIds:DP(o)}),recoveryActions:e}}var LP=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ec(t){return t?LP.has(t):!0}function _c(t){return t===429||t===529}function ss(t,e=500,r=32e3){let n=Math.min(e*Math.pow(2,t-1),r);return n+Math.floor(Math.random()*n*.25)}var FB={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function is(){let t=process.env.QLOGICAGENT_PERSISTENT_RETRY;return t==="1"||t==="true"}var $n=class extends Error{constructor(r,n){super(`Model fallback triggered: ${r} -> ${n}`);this.originalModel=r;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Mc(t,e){if(e.allowedTools&&e.allowedTools.length>0){let r=new Set(e.allowedTools);return t.filter(n=>r.has(n))}if(e.toolAccessMode==="none")return[];if(e.toolAccessMode==="read-only"){let r=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(n=>!r.has(n))}return e.canFork?[...t]:t.filter(r=>r!=="agent")}var OP={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolAccessMode:"full",canFork:!1},jP={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","tool_search"],canFork:!1},$P={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","task","tool_search"],canFork:!1},UP={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},FP={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolAccessMode:"read-only",allowedTools:["web_search","web_fetch","read_file","search","think","memory"],canFork:!1},HP={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolAccessMode:"full",allowedTools:["exec","read_file","search","think"],canFork:!1},Sm=[OP,jP,$P,UP,FP,HP];function Dc(){return[...Sm]}function Un(t){return Sm.find(e=>e.name===t)}function Nc(t){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:t.maxOutputTokens,consecutiveTruncations:0,aborted:t.abortSignal?.aborted??!1}}function Lc(t,e){if(t.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let r=e.contextWindowTokens-e.responseBufferTokens-t.currentMaxOutputTokens,n=r>0?t.promptTokens/r*100:100;return t.promptTokens>=r?t.hasAttemptedReactiveCompact||!e.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:r-t.promptTokens}:{level:"ok"}}function Oc(t,e,r){let n=t.message?.toLowerCase()??"",o=t.status??0;return o===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!e.hasAttemptedReactiveCompact&&r.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:o>=500&&o<600?{action:"retry",reason:`server_error_${o}`}:o===429?{action:"retry",reason:"rate_limited"}:o===401||o===403?{action:"abort",reason:"auth_error"}:o===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:n||"unknown_error"}}function jc(t,e,r){if(!e.outputEscalationEnabled)return{shouldEscalate:!1,newMax:t.currentMaxOutputTokens};if(t.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:t.currentMaxOutputTokens};let n=Math.min(t.currentMaxOutputTokens*2,r);return n<=t.currentMaxOutputTokens?{shouldEscalate:!1,newMax:t.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function $c(t,e){return t.aborted?!0:e.abortSignal?.aborted?(t.aborted=!0,!0):!1}var BP={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Uc(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function zr(t,e=BP){return!(t.attemptedThisTurn||t.consecutiveFailures>=e.maxConsecutiveFailures)}import{accumulateToolCalls as vC}from"@xiaozhiclaw/provider-core";function as(t,e){let r=e.ok?typeof e.payload=="string"?e.payload:JSON.stringify(e.payload??""):`Error: ${e.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:t,content:r,...!e.ok&&{is_error:!0},...e.toolReferences?.length?{toolReferences:e.toolReferences}:{},...e.imageUrls?.length?{imageUrls:e.imageUrls}:{}}}import{mkdir as WP,writeFile as GP}from"fs/promises";import{join as wm}from"path";import{tmpdir as KP}from"os";var zP="tool-results",Tm="<persisted-output>",VP="</persisted-output>";function Am(){return{seenIds:new Set,replacements:new Map}}function xm(t){return wm(KP(),"qlogicagent-sessions",t,zP)}async function XP(t){try{await WP(xm(t),{recursive:!0})}catch{}}function YP(t,e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_");return wm(xm(t),`${r}.txt`)}function JP(t,e){if(t.length<=e)return{preview:t,hasMore:!1};let n=t.slice(0,e).lastIndexOf(`
|
|
163
|
+
`).map(l=>l.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(ts(c)===r)return o.name}}catch{}}}catch{}return null}function vP(t){if(!Sc(t))return 0;try{return hm(t,{withFileTypes:!0}).filter(e=>e.isDirectory()&&Sc(wc(t,e.name,"SKILL.md"))).length}catch{return 0}}function kP(t,e){return!(!t.ok||t.existingSkillName||!t.multiStep||t.toolCallCount<ka||t.distinctToolCount<Ra||Date.now()-ym<Sa||e?.projectSkillsDir&&(vP(e.projectSkillsDir)>=va||e.tools.length>0&&bP(e.tools,e.projectSkillsDir))||e?.projectRoot&&e.tools.length>0&&!vm(e.projectRoot,e.tools))}function RP(t){return t.existingSkillName?t.feedback==="negative":!1}function rs(t,e){return RP(t)?{type:"skill.improve",skillName:t.existingSkillName,reason:"negative user feedback on existing skill execution"}:kP(t,e)?(ym=Date.now(),{type:"skill.create",suggestedName:e.suggestedName??`auto-skill-${e.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${e.tools.join(", ")}`,tools:e.tools,stepCount:t.toolCallCount}):null}function km(t){return t.function&&typeof t.function=="object"&&typeof t.function.name=="string"?t.function.name.trim():typeof t.name=="string"?t.name.trim():""}function SP(t){return t==="enabled-eligible"||t==="installed-awaiting-approval"}function wP(t){return new Map((t??[]).map(e=>[e.toolName,e]))}function TP(t){if(!t.eligibility?.length)return[...t.tools];let e=wP(t.eligibility);return t.tools.filter(r=>{let n=km(r);if(!n)return!1;let o=e.get(n);return!o||SP(o.status)})}function AP(t){let e=[],r=t.compatibility??{},n=t.toolChoice;if(t.thinkingEnabled&&r.requireAutoWhenThinking){let o=typeof n=="object"&&n&&!Array.isArray(n)?String(n.type??""):n;o&&o!=="auto"&&o!=="none"&&(e.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),n="auto")}if(n==="required"&&r.allowRequiredToolChoice===!1){let o=r.requiredFallback??"auto";e.push(`tool_choice=required is not supported by this provider; downgraded to ${o}.`),n=o}if(n&&typeof n=="object"&&!Array.isArray(n)&&n.type==="function"&&r.allowNamedToolChoice===!1){let o=r.namedFallback??"required";e.push(`named tool_choice is not supported by this provider; downgraded to ${o}.`),n=o}return{normalizedToolChoice:n,warnings:e}}function Tc(t){let e=AP({toolChoice:t.toolChoice,thinkingEnabled:t.thinkingEnabled,compatibility:t.compatibility}),r=e.normalizedToolChoice,n=[...e.warnings],o=TP({tools:t.tools,eligibility:t.eligibility});if(!r||r==="auto")return{tools:o,normalizedToolChoice:r,warnings:n};if(r==="none")return{tools:[],normalizedToolChoice:"none",warnings:n};if(r==="required"){if(o.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:o,normalizedToolChoice:"required",extraSystemPrompt:"You must call one of the available tools before responding.",warnings:n}}if(typeof r=="object"&&!Array.isArray(r)&&r.type==="function"){let s=r.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=o.filter(c=>km(c)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:n}}return{tools:o,normalizedToolChoice:r,warnings:n}}var xP=["stop","aborted","timeout","cancelled","interrupted","error"],PP=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function Rm(t){return t==null?[]:typeof t=="string"?t.length>0?[{type:"text",text:t}]:[]:Array.isArray(t)?t:[{type:"text",text:String(t)}]}function CP(t,e){return{...t,content:[...Rm(t.content),...Rm(e.content)]}}function IP(t){if(!t||typeof t!="object")return!1;if(t.function&&typeof t.function=="object"){let e=t.function.name;if(typeof e=="string"&&e.length>0)return!0}return typeof t.name=="string"&&t.name.length>0}function EP(t){return new Set((t??xP).map(e=>e.trim().toLowerCase()))}function _P(t,e){return t?EP(e).has(t.trim().toLowerCase()):!1}function Ac(t){if(!Array.isArray(t)||t.length===0)return[...t];let e=t.map(a=>{if(a.role==="assistant"&&Array.isArray(a.tool_calls)){let c=a.tool_calls.filter(l=>IP(l));return{...a,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...a}}),r=new Set;for(let a of e)if(!(a.role!=="assistant"||!Array.isArray(a.tool_calls)))for(let c of a.tool_calls)typeof c.id=="string"&&c.id&&r.add(c.id);let n=e.filter(a=>a.role!=="tool"?!0:!!(a.tool_call_id&&r.has(a.tool_call_id))),o=new Set;for(let a of n)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.add(a.tool_call_id);let s=[];for(let a of n){if(a.role==="assistant"&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0){let c=a.tool_calls.filter(l=>typeof l.id=="string"&&o.has(l.id));if(c.length===0){let{tool_calls:l,...d}=a;d.content!=null&&d.content!==""&&s.push(d);continue}if(c.length<a.tool_calls.length){s.push({...a,tool_calls:c});continue}}s.push(a)}let i=[];for(let a of s){let c=i.length>0?i[i.length-1]:void 0;if(a.role==="user"&&c?.role==="user"){i[i.length-1]=CP(c,a);continue}i.push(a)}return i}function xc(t,e){return _P(e?.stopReason,e?.forcedStopReasons)?t.map(r=>{if(r.role!=="assistant")return{...r};let n={...r};for(let o of PP)delete n[o];return n}):[...t]}function Pc(t,e){let r=e?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",n=new Set;for(let s of t)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&n.add(s.tool_call_id);let o=[];for(let s of t)if(o.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||n.has(i.id)||(n.add(i.id),o.push({role:"tool",tool_call_id:i.id,content:r}));return o}function Cc(t,e){let r=Ac(t),n=xc(r,e);return Pc(n,e)}function MP(t){let e=new Set,r=new Set;for(let n of t){if(n.role==="assistant"&&Array.isArray(n.tool_calls))for(let o of n.tool_calls)typeof o.id=="string"&&o.id&&e.add(o.id);n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&r.add(n.tool_call_id)}return[...e].filter(n=>!r.has(n))}function DP(t){let e=new Set;for(let r of t)r.role==="tool"&&typeof r.tool_call_id=="string"&&r.tool_call_id&&e.add(r.tool_call_id);return[...e]}function NP(t){return{round:t.round??0,maxRounds:t.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??[]],completedToolCallIds:[...t.completedToolCallIds??[]],lastStopReason:t.lastStopReason,replayMessages:[...t.replayMessages??[]]}}function Ic(t,e){return{round:t.round+1,maxRounds:t.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??t.pendingToolCallIds],completedToolCallIds:[...e.completedToolCallIds??t.completedToolCallIds],lastStopReason:e.lastStopReason??t.lastStopReason,replayMessages:[...e.replayMessages??t.replayMessages]}}function ns(t,e){return{round:t.round,maxRounds:t.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...e.completedToolCallIds??t.completedToolCallIds],lastStopReason:e.lastStopReason??t.lastStopReason,replayMessages:[...e.replayMessages??t.replayMessages]}}function os(t){let e=[],r=Ac(t.replayMessages);r.length!==t.replayMessages.length&&e.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let n=xc(r,t.options);n.some((s,i)=>s!==r[i])&&e.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let o=Pc(n,t.options);return o.length>n.length&&e.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:NP({maxRounds:t.maxRounds,round:t.round,lastStopReason:t.lastStopReason,replayMessages:o,pendingToolCallIds:MP(o),completedToolCallIds:DP(o)}),recoveryActions:e}}var LP=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Ec(t){return t?LP.has(t):!0}function _c(t){return t===429||t===529}function ss(t,e=500,r=32e3){let n=Math.min(e*Math.pow(2,t-1),r);return n+Math.floor(Math.random()*n*.25)}var HB={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function is(){let t=process.env.QLOGICAGENT_PERSISTENT_RETRY;return t==="1"||t==="true"}var $n=class extends Error{constructor(r,n){super(`Model fallback triggered: ${r} -> ${n}`);this.originalModel=r;this.fallbackModel=n;this.name="FallbackTriggeredError"}originalModel;fallbackModel};function Mc(t,e){if(e.allowedTools&&e.allowedTools.length>0){let r=new Set(e.allowedTools);return t.filter(n=>r.has(n))}if(e.toolAccessMode==="none")return[];if(e.toolAccessMode==="read-only"){let r=new Set(["file_edit","create_file","write_file","replace_string_in_file","multi_replace_string_in_file","create_directory","delete_file","rename_file","move_file","exec","run_in_terminal","run_command","git_commit","git_push","patch"]);return t.filter(n=>!r.has(n))}return e.canFork?[...t]:t.filter(r=>r!=="agent")}var OP={name:"general",label:"General Purpose",description:"A general-purpose sub-agent that can perform any task with full tool access.",maxTurns:200,toolAccessMode:"full",canFork:!1},jP={name:"explore",label:"Explore",description:"Fast read-only codebase exploration. Search files, read code, analyze structure. Cannot write or execute.",maxTurns:50,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","tool_search"],canFork:!1},$P={name:"plan",label:"Plan",description:"Planning mode. Explore, analyze, and produce a structured plan. Cannot write files or execute commands.",maxTurns:80,toolAccessMode:"read-only",allowedTools:["read_file","search","web_search","web_fetch","think","memory","task","tool_search"],canFork:!1},UP={name:"code",label:"Code",description:"A coding sub-agent with full tool access for implementation tasks.",maxTurns:200,toolAccessMode:"full",canFork:!0},FP={name:"research",label:"Research",description:"Web research and information gathering. Searches the web, fetches pages, and synthesizes findings.",maxTurns:30,toolAccessMode:"read-only",allowedTools:["web_search","web_fetch","read_file","search","think","memory"],canFork:!1},HP={name:"verify",label:"Verify",description:"Verification agent. Runs tests, checks build output, validates changes are correct.",maxTurns:40,toolAccessMode:"full",allowedTools:["exec","read_file","search","think"],canFork:!1},Sm=[OP,jP,$P,UP,FP,HP];function Dc(){return[...Sm]}function Un(t){return Sm.find(e=>e.name===t)}function Nc(t){return{promptTokens:0,hasAttemptedReactiveCompact:!1,currentMaxOutputTokens:t.maxOutputTokens,consecutiveTruncations:0,aborted:t.abortSignal?.aborted??!1}}function Lc(t,e){if(t.aborted)return{level:"blocking",usagePercent:100,reason:"budget_exhausted"};let r=e.contextWindowTokens-e.responseBufferTokens-t.currentMaxOutputTokens,n=r>0?t.promptTokens/r*100:100;return t.promptTokens>=r?t.hasAttemptedReactiveCompact||!e.reactiveCompactEnabled?{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:{level:"blocking",usagePercent:n,reason:"prompt_too_long"}:n>=85?{level:"warning",usagePercent:n,remainingTokens:r-t.promptTokens}:{level:"ok"}}function Oc(t,e,r){let n=t.message?.toLowerCase()??"",o=t.status??0;return o===413||n.includes("prompt_too_long")||n.includes("context_length_exceeded")?!e.hasAttemptedReactiveCompact&&r.reactiveCompactEnabled?{action:"reactive_compact"}:{action:"abort",reason:"prompt_too_long_unrecoverable"}:o>=500&&o<600?{action:"retry",reason:`server_error_${o}`}:o===429?{action:"retry",reason:"rate_limited"}:o===401||o===403?{action:"abort",reason:"auth_error"}:o===404?{action:"abort",reason:"model_not_found"}:{action:"abort",reason:n||"unknown_error"}}function jc(t,e,r){if(!e.outputEscalationEnabled)return{shouldEscalate:!1,newMax:t.currentMaxOutputTokens};if(t.consecutiveTruncations>=3)return{shouldEscalate:!1,newMax:t.currentMaxOutputTokens};let n=Math.min(t.currentMaxOutputTokens*2,r);return n<=t.currentMaxOutputTokens?{shouldEscalate:!1,newMax:t.currentMaxOutputTokens}:{shouldEscalate:!0,newMax:n}}function $c(t,e){return t.aborted?!0:e.abortSignal?.aborted?(t.aborted=!0,!0):!1}var BP={maxConsecutiveFailures:3,minMessagesAfterCompact:4,targetUsagePercent:50};function Uc(){return{consecutiveFailures:0,attemptedThisTurn:!1,lastCompactAt:null,toolsAtLastCompact:[]}}function zr(t,e=BP){return!(t.attemptedThisTurn||t.consecutiveFailures>=e.maxConsecutiveFailures)}import{accumulateToolCalls as vC}from"@xiaozhiclaw/provider-core";function as(t,e){let r=e.ok?typeof e.payload=="string"?e.payload:JSON.stringify(e.payload??""):`Error: ${e.error??"Tool execution failed"}`;return{role:"tool",tool_call_id:t,content:r,...!e.ok&&{is_error:!0},...e.toolReferences?.length?{toolReferences:e.toolReferences}:{},...e.imageUrls?.length?{imageUrls:e.imageUrls}:{}}}import{mkdir as WP,writeFile as GP}from"fs/promises";import{join as wm}from"path";import{tmpdir as KP}from"os";var zP="tool-results",Tm="<persisted-output>",VP="</persisted-output>";function Am(){return{seenIds:new Set,replacements:new Map}}function xm(t){return wm(KP(),"qlogicagent-sessions",t,zP)}async function XP(t){try{await WP(xm(t),{recursive:!0})}catch{}}function YP(t,e){let r=e.replace(/[^a-zA-Z0-9_-]/g,"_");return wm(xm(t),`${r}.txt`)}function JP(t,e){if(t.length<=e)return{preview:t,hasMore:!1};let n=t.slice(0,e).lastIndexOf(`
|
|
164
164
|
`),o=n>e*.5?n:e;return{preview:t.slice(0,o),hasMore:!0}}function Pm(t){return t.includes(Tm)}async function Cm(t,e,r){await XP(r);let n=YP(r,e);try{await GP(n,t,{encoding:"utf-8",flag:"wx"})}catch(i){if(i.code!=="EEXIST")return null}let{preview:o,hasMore:s}=JP(t,jo);return{filepath:n,originalSize:t.length,preview:o,hasMore:s}}function Im(t){let e=`${Tm}
|
|
165
165
|
`;return e+=`Output too large (${t.originalSize} chars). Full output saved to: ${t.filepath}
|
|
166
166
|
|
|
@@ -250,7 +250,7 @@ ${c||"(\u65E0)"}`].join(`
|
|
|
250
250
|
|
|
251
251
|
\u521A\u624D\u53D1\u751F\u4E86: ${t.turnSummary}
|
|
252
252
|
|
|
253
|
-
\u7528\u4E00\u53E5\u8BDD(\u226420\u5B57)\u4EE5\u4F60\u7684\u6027\u683C\u505A\u51FA\u7B80\u77ED\u53CD\u5E94\u3002\u53EA\u8F93\u51FA\u53CD\u5E94\u6587\u672C\uFF0C\u4E0D\u8981\u5176\u4ED6\u5185\u5BB9\u3002${r}`;try{let o=await e(n,50);if(!o||o.length>50)return null;Vn.push(o),Vn.length>b_&&Vn.shift();let s=/[!!✨🎉]|搞定|完美|太棒/.test(o)?"excited":/[.。…]|嗯|想|看看/.test(o)?"thinking":/[zZ]|困|睡|累/.test(o)?"sleepy":"normal";return{text:o,style:s}}catch{return null}}var gl=[{id:"bubble_detail",name:"Bubble Detail",description:"Longer speech bubbles for status text",unlockedAtLevel:2,surface:"presentation"},{id:"gaze_follow",name:"Gaze Follow",description:"Eyes follow pointer focus more smoothly",unlockedAtLevel:3,surface:"presentation"},{id:"micro_expression",name:"Micro Expression",description:"Tiny antenna and eye sparkle animations",unlockedAtLevel:5,surface:"presentation"},{id:"tidy_motion",name:"Tidy Motion",description:"A gentle tidying animation after local profile updates",unlockedAtLevel:7,surface:"presentation"},{id:"mood_badge",name:"Mood Badge",description:"Small weather-like mood badges in bubbles",unlockedAtLevel:10,surface:"presentation"},{id:"quiet_rest",name:"Quiet Rest",description:"Calmer idle and sleeping animations",unlockedAtLevel:12,surface:"presentation"},{id:"activity_glow",name:"Activity Glow",description:"Soft glow during visible activity changes",unlockedAtLevel:15,surface:"presentation"},{id:"style_tint",name:"Style Tint",description:"Subtle color accents for the companion style",unlockedAtLevel:20,surface:"presentation"}],uh=["\u7B2C\u4E00\u6B21\u8131\u58F3\uFF01\u5C0F\u867E\u58F3\u53D8\u5F97\u66F4\u6709\u5149\u6CFD\u4E86","\u58F3\u9762\u5F00\u59CB\u51FA\u73B0\u7EC6\u5FAE\u7684\u5F69\u8679\u7EB9\u7406","\u94B3\u5B50\u53D8\u5F97\u66F4\u52A0\u6709\u529B\uFF0C\u80FD\u5939\u8D77\u66F4\u591A\u4E1C\u897F\u4E86","\u89E6\u89D2\u7075\u654F\u5EA6\u63D0\u5347\uFF0C\u611F\u77E5\u8303\u56F4\u6269\u5927","\u5168\u8EAB\u6563\u53D1\u5FAE\u5149\uFF0C\u50CF\u662F\u5185\u5728\u529B\u91CF\u5728\u89C9\u9192","\u8FDB\u5165\u7A00\u6709\u4F53\u8272\u53D8\u5F02\u9636\u6BB5..."],se=class t{static xpForLevel(e){return e*100}static processXpGain(e,r){let n=[],o={},s=e.level,i=e.experience+r;for(;i>=t.xpForLevel(s);){if(i-=t.xpForLevel(s),s++,n.push({type:"level_up",level:s}),s%5===0){let c=Math.floor(s/5),l=t.getMoltResult(c,e.stats);n.push({type:"molt",level:s,moltStage:c});for(let[d,u]of Object.entries(l.statBoost)){let p=d;o[p]=(o[p]??0)+(u??0)}}let a=gl.find(c=>c.unlockedAtLevel===s);a&&n.push({type:"display_trait_unlock",level:s,displayTrait:a})}return{newLevel:s,newXp:i,events:n,statBoosts:o}}static getMoltResult(e,r){let n=uh[Math.min(e-1,uh.length-1)]??"\u7EE7\u7EED\u6210\u957F\u4E2D...",o=["grip","patience","curiosity","appetite","humor"],i={[o[(e-1)%o.length]]:1};return{stage:e,description:n,statBoost:i}}static getUnlockedDisplayTraits(e){return gl.filter(r=>r.unlockedAtLevel<=e)}static getNextDisplayTrait(e){return gl.find(r=>r.unlockedAtLevel>e)??null}static xpForEvent(e){switch(e){case"turn.end":return 10;case"turn.error":return 2;case"session.created":return 5;case"interact.pat":return 3;case"interact.feed":return 5;case"interact.poke":return 1;case"tool.success":return 2;default:return 1}}};import{createHash as
|
|
253
|
+
\u7528\u4E00\u53E5\u8BDD(\u226420\u5B57)\u4EE5\u4F60\u7684\u6027\u683C\u505A\u51FA\u7B80\u77ED\u53CD\u5E94\u3002\u53EA\u8F93\u51FA\u53CD\u5E94\u6587\u672C\uFF0C\u4E0D\u8981\u5176\u4ED6\u5185\u5BB9\u3002${r}`;try{let o=await e(n,50);if(!o||o.length>50)return null;Vn.push(o),Vn.length>b_&&Vn.shift();let s=/[!!✨🎉]|搞定|完美|太棒/.test(o)?"excited":/[.。…]|嗯|想|看看/.test(o)?"thinking":/[zZ]|困|睡|累/.test(o)?"sleepy":"normal";return{text:o,style:s}}catch{return null}}var gl=[{id:"bubble_detail",name:"Bubble Detail",description:"Longer speech bubbles for status text",unlockedAtLevel:2,surface:"presentation"},{id:"gaze_follow",name:"Gaze Follow",description:"Eyes follow pointer focus more smoothly",unlockedAtLevel:3,surface:"presentation"},{id:"micro_expression",name:"Micro Expression",description:"Tiny antenna and eye sparkle animations",unlockedAtLevel:5,surface:"presentation"},{id:"tidy_motion",name:"Tidy Motion",description:"A gentle tidying animation after local profile updates",unlockedAtLevel:7,surface:"presentation"},{id:"mood_badge",name:"Mood Badge",description:"Small weather-like mood badges in bubbles",unlockedAtLevel:10,surface:"presentation"},{id:"quiet_rest",name:"Quiet Rest",description:"Calmer idle and sleeping animations",unlockedAtLevel:12,surface:"presentation"},{id:"activity_glow",name:"Activity Glow",description:"Soft glow during visible activity changes",unlockedAtLevel:15,surface:"presentation"},{id:"style_tint",name:"Style Tint",description:"Subtle color accents for the companion style",unlockedAtLevel:20,surface:"presentation"}],uh=["\u7B2C\u4E00\u6B21\u8131\u58F3\uFF01\u5C0F\u867E\u58F3\u53D8\u5F97\u66F4\u6709\u5149\u6CFD\u4E86","\u58F3\u9762\u5F00\u59CB\u51FA\u73B0\u7EC6\u5FAE\u7684\u5F69\u8679\u7EB9\u7406","\u94B3\u5B50\u53D8\u5F97\u66F4\u52A0\u6709\u529B\uFF0C\u80FD\u5939\u8D77\u66F4\u591A\u4E1C\u897F\u4E86","\u89E6\u89D2\u7075\u654F\u5EA6\u63D0\u5347\uFF0C\u611F\u77E5\u8303\u56F4\u6269\u5927","\u5168\u8EAB\u6563\u53D1\u5FAE\u5149\uFF0C\u50CF\u662F\u5185\u5728\u529B\u91CF\u5728\u89C9\u9192","\u8FDB\u5165\u7A00\u6709\u4F53\u8272\u53D8\u5F02\u9636\u6BB5..."],se=class t{static xpForLevel(e){return e*100}static processXpGain(e,r){let n=[],o={},s=e.level,i=e.experience+r;for(;i>=t.xpForLevel(s);){if(i-=t.xpForLevel(s),s++,n.push({type:"level_up",level:s}),s%5===0){let c=Math.floor(s/5),l=t.getMoltResult(c,e.stats);n.push({type:"molt",level:s,moltStage:c});for(let[d,u]of Object.entries(l.statBoost)){let p=d;o[p]=(o[p]??0)+(u??0)}}let a=gl.find(c=>c.unlockedAtLevel===s);a&&n.push({type:"display_trait_unlock",level:s,displayTrait:a})}return{newLevel:s,newXp:i,events:n,statBoosts:o}}static getMoltResult(e,r){let n=uh[Math.min(e-1,uh.length-1)]??"\u7EE7\u7EED\u6210\u957F\u4E2D...",o=["grip","patience","curiosity","appetite","humor"],i={[o[(e-1)%o.length]]:1};return{stage:e,description:n,statBoost:i}}static getUnlockedDisplayTraits(e){return gl.filter(r=>r.unlockedAtLevel<=e)}static getNextDisplayTrait(e){return gl.find(r=>r.unlockedAtLevel>e)??null}static xpForEvent(e){switch(e){case"turn.end":return 10;case"turn.error":return 2;case"session.created":return 5;case"interact.pat":return 3;case"interact.feed":return 5;case"interact.poke":return 1;case"tool.success":return 2;default:return 1}}};import{createHash as RG}from"node:crypto";import wG from"node:fs";var TG=500*1024,AG=20*1024,v_=["idle"];function fl(t){if(!t||typeof t!="object")throw new Error("Manifest must be an object");let e=t;if(e.version!==1)throw new Error(`Unsupported manifest version: ${e.version}`);for(let o of["name","author","created"])if(typeof e[o]!="string"||e[o].length===0)throw new Error(`Manifest missing or invalid field: ${o}`);if(e.name.length>30)throw new Error("Manifest name exceeds 30 characters");if(!e.dimensions||typeof e.dimensions!="object")throw new Error("Manifest missing dimensions");let r=e.dimensions;if(typeof r.width!="number"||typeof r.height!="number")throw new Error("Manifest dimensions must be numbers");if(r.width>400||r.height>400||r.width<50||r.height<50)throw new Error("Manifest dimensions must be 50-400px");if(!e.states||typeof e.states!="object")throw new Error("Manifest missing states");let n=e.states;for(let o of v_)if(!(o in n))throw new Error(`Manifest missing required state: ${o}`);for(let[o,s]of Object.entries(n)){if(!s||typeof s!="object")throw new Error(`Invalid state config for "${o}"`);let i=s;if(typeof i.file!="string")throw new Error(`State "${o}" missing file path`);if(typeof i.loop!="boolean")throw new Error(`State "${o}" missing loop flag`);if(i.file.includes("..")||i.file.startsWith("/"))throw new Error(`State "${o}" file path contains path traversal`)}}function Ir(t){let e=t.replace(/<\?xml[^?]*\?>/gi,"").replace(/<!DOCTYPE[^>]*>/gi,"");return e=e.replace(/<script[\s\S]*?<\/script>/gi,""),e=e.replace(/<script[^>]*\/>/gi,""),e=e.replace(/<foreignObject[\s\S]*?<\/foreignObject>/gi,""),e=e.replace(/<foreignObject[^>]*\/>/gi,""),e=e.replace(/\s+on\w+\s*=\s*"[^"]*"/gi,""),e=e.replace(/\s+on\w+\s*=\s*'[^']*'/gi,""),e=e.replace(/href\s*=\s*"javascript:[^"]*"/gi,'href=""'),e=e.replace(/href\s*=\s*'javascript:[^']*'/gi,"href=''"),e=e.replace(/xlink:href\s*=\s*"javascript:[^"]*"/gi,'xlink:href=""'),e=e.replace(/(href|src)\s*=\s*"(https?:\/\/[^"]*)"/gi,'$1=""'),e=e.replace(/(href|src)\s*=\s*'(https?:\/\/[^']*)'/gi,"$1=''"),e=e.replace(/<use[^>]*href\s*=\s*"https?:\/\/[^"]*"[^>]*\/?>/gi,""),e=e.replace(/@import\s+url\([^)]*https?:\/\/[^)]*\)[^;]*;/gi,""),e=e.replace(/url\(\s*['"]?https?:\/\/[^)]*\)/gi,"url()"),e.trim()}var hl={idle:{body:"breathe",eyes:"blink",arms:"sway"},thinking:{body:"tilt",eyes:"lookup",arms:"still",effects:["ellipsis"]},working:{body:"lean",eyes:"focus",arms:"hammer"},done:{body:"bounce",eyes:"sparkle",arms:"raised",effects:["sparkle"]},happy:{body:"sway",eyes:"sparkle",arms:"wave",effects:["heart"]},error:{body:"shrink",eyes:"dizzy",arms:"covering",effects:["sweat"]},sleeping:{body:"still",eyes:"closed",arms:"still",effects:["zzz"]},eating:{body:"still",eyes:"blink",arms:"eat"},plan:{body:"tilt",eyes:"focus",arms:"hold",effects:["ellipsis"]},dream:{body:"float",eyes:"closed",arms:"sway",effects:["sparkle","music"]},subagent:{body:"lean",eyes:"focus",arms:"hammer"},"random-look":{body:"breathe",eyes:"lookup",arms:"still"}},k_={breathe:"@keyframes body-anim { 0%,100% { transform: scaleY(1); } 50% { transform: scaleY(1.03); } }",sway:"@keyframes body-anim { 0%,100% { transform: rotate(0deg); } 25% { transform: rotate(2deg); } 75% { transform: rotate(-2deg); } }",lean:"@keyframes body-anim { 0%,100% { transform: rotate(0deg) translateX(0); } 50% { transform: rotate(-3deg) translateX(-2px); } }",tilt:"@keyframes body-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(5deg); } }",shrink:"@keyframes body-anim { 0%,100% { transform: scale(0.92); } 50% { transform: scale(0.88); } }",bounce:"@keyframes body-anim { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-8px); } }",still:"@keyframes body-anim { 0%,100% { transform: none; } }",float:"@keyframes body-anim { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-5px); } }"},R_={blink:"@keyframes eye-anim { 0%,90%,100% { transform: scaleY(1); } 95% { transform: scaleY(0.1); } }",lookup:"@keyframes eye-anim { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-2px); } }",focus:"@keyframes eye-anim { 0%,100% { transform: scale(1); } 50% { transform: scale(0.9); } }",closed:"@keyframes eye-anim { 0%,100% { transform: scaleY(0.1); } }",wide:"@keyframes eye-anim { 0%,100% { transform: scale(1.2); } }",sparkle:"@keyframes eye-anim { 0%,100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.1); opacity: 0.8; } }",dizzy:"@keyframes eye-anim { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }",sleepy:"@keyframes eye-anim { 0%,100% { transform: scaleY(0.3); } }"},S_={sway:`@keyframes left-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(5deg); } }
|
|
254
254
|
@keyframes right-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(-5deg); } }`,still:`@keyframes left-arm-anim { 0%,100% { transform: none; } }
|
|
255
255
|
@keyframes right-arm-anim { 0%,100% { transform: none; } }`,hammer:`@keyframes left-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(-20deg); } }
|
|
256
256
|
@keyframes right-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(-25deg); } }`,wave:`@keyframes left-arm-anim { 0%,100% { transform: rotate(0deg); } 50% { transform: rotate(15deg); } }
|
|
@@ -324,8 +324,8 @@ ${l}`);return d&&(u=u.replace(/<\/svg>/,`${d}
|
|
|
324
324
|
\u89D2\u8272\uFF1A${t}
|
|
325
325
|
\u72B6\u6001\uFF1A${e}`}function ph(t){let e=new Set,r=/#[0-9a-fA-F]{6}/g,n;for(;(n=r.exec(t))!==null;)e.add(n[0].toUpperCase());return e}function T_(t,e){if(t.size===0||e.size===0)return 0;let r=0;for(let n of t)e.has(n)&&r++;return r/Math.max(t.size,e.size)}function gh(t,e){return t instanceof Error?t.message:e}function wl(t){let e=se.getNextDisplayTrait(t.level);return{level:t.level,experience:t.experience,xpNeeded:se.xpForLevel(t.level),displayTraits:se.getUnlockedDisplayTraits(t.level).map(Er),nextDisplayTrait:e?Er(e):void 0}}function Er(t){return{id:t.id,name:t.name,description:t.description,level:t.unlockedAtLevel,surface:t.surface}}async function fh(t){let e=t.params,r=this.getActiveProjectRoot(),n=new xt(r),o=n.load();if(o){this.sendNotification("pet.soul_ready",{name:o.name,species:o.species,personality:o.personality,catchphrase:o.catchphrase,stats:o.stats,rarity:o.rarity,breed:o.breed,breedColors:o.breedColors}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,soul:o,growth:wl(o)});return}let s=this.deviceId??"default-user";try{let i=this.petRuntime.createPetSoulGenerator(),a=await n.hatch(s,i,e?.breed);this.sendNotification("pet.soul_ready",{name:a.name,species:a.species,personality:a.personality,catchphrase:a.catchphrase,stats:a.stats,rarity:a.rarity,breed:a.breed,breedColors:a.breedColors}),this.sendNotification("pet.growth",{level:a.level,experience:a.experience,xpNeeded:se.xpForLevel(a.level),displayTraits:se.getUnlockedDisplayTraits(a.level).map(Er)}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,soul:a,growth:wl(a)})}catch(i){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:gh(i,"Failed to hatch pet")})}}async function hh(t){let r=t.params?.action??"pat",n=this.getActiveProjectRoot(),o=new xt(n),s=o.load();if(!s){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Pet not hatched yet"});return}let i=se.xpForEvent(`interact.${r}`),{newLevel:a,newXp:c,events:l,statBoosts:d}=se.processXpGain(s,i);s.level=a,s.experience=c;for(let[g,f]of Object.entries(d)){let h=g;s.stats[h]=Math.min(10,s.stats[h]+(f??0))}o.updateSoul(s),this.sendNotification("pet.state",{state:"happy"});let u=se.getNextDisplayTrait(a);this.sendNotification("pet.growth",{level:a,experience:c,xpNeeded:se.xpForLevel(a),displayTraits:se.getUnlockedDisplayTraits(a).map(Er),nextDisplayTrait:u?Er(u):void 0});for(let g of l)g.type==="molt"?this.sendNotification("pet.reaction",{text:`\u2728 \u8131\u58F3\u4E86\uFF01\u7B2C ${g.moltStage} \u6B21\u8715\u53D8`,style:"excited"}):g.type==="display_trait_unlock"&&g.displayTrait&&this.sendNotification("pet.reaction",{text:`Display trait unlocked: ${g.displayTrait.name}`,style:"excited"});let p=null,m="excited";try{let g=[],f=this.getActiveProjectRoot?.()??"";if(f){let R=f.split(/[\\/]/).pop()??f;g.push(`\u7528\u6237\u6B63\u5728\u9879\u76EE\u300C${R}\u300D\u4E2D\u5DE5\u4F5C`)}if(this.sessionState){let R=this.sessionState.turnCount??0;R>0&&g.push(`\u672C\u6B21\u4F1A\u8BDD\u5DF2\u8FDB\u884C\u4E86 ${R} \u8F6E\u5BF9\u8BDD`)}if(this.memoryProvider&&this.memoryUserId)try{let R=this.memoryProvider.getActivitySummary(this.memoryUserId,7);if(R?.highlights?.length){let P=R.highlights.slice(0,3).map(I=>I.text);g.push(`\u7528\u6237\u8FD1\u671F\u8BB0\u5FC6\u4EAE\u70B9: ${P.join("\uFF1B")}`)}}catch{}let h=new Date().getHours(),v=h<6?"\u6DF1\u591C":h<9?"\u65E9\u6668":h<12?"\u4E0A\u5348":h<14?"\u4E2D\u5348":h<18?"\u4E0B\u5348":h<22?"\u665A\u4E0A":"\u6DF1\u591C";g.push(`\u5F53\u524D\u65F6\u6BB5: ${v}`);let b=r==="pat"?"\u7528\u6237\u6478\u4E86\u6478\u4F60":r==="feed"?"\u7528\u6237\u5582\u4E86\u4F60\u4E1C\u897F":`\u7528\u6237\u5BF9\u4F60\u505A\u4E86\u300C${r}\u300D`;g.push(b);let S=g.join("\u3002"),T=this.petRuntime.createSmallLLMCall();if(T){let R=await Yn({turnSummary:S,soul:s},T);R&&(p=R.text,m=R.style)}}catch{}if(!p){let g=Xn("session.created");p=g?.text??null,m=g?.style??"excited"}p&&this.sendNotification("pet.reaction",{text:p,style:m}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,action:r,level:a,experience:c,events:l.map(g=>({type:g.type,level:g.level})),reaction:p?{text:p,style:m}:null})}async function yh(t){let e=this.getActiveProjectRoot(),n=new xt(e).load();if(t.id!==void 0&&this.sendResponse(t.id,{ok:!0,soul:n??null,growth:n?wl(n):null}),n){this.sendNotification("pet.soul_ready",{name:n.name,species:n.species,personality:n.personality,catchphrase:n.catchphrase,stats:n.stats,rarity:n.rarity,breed:n.breed,breedColors:n.breedColors});let o=se.getNextDisplayTrait(n.level);this.sendNotification("pet.growth",{level:n.level,experience:n.experience,xpNeeded:se.xpForLevel(n.level),displayTraits:se.getUnlockedDisplayTraits(n.level).map(Er),nextDisplayTrait:o?Er(o):void 0})}}async function bh(t){let e=t.params;if(!e?.description&&!e?.imageBase64){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Provide description or imageBase64"});return}typeof this.ensureModelRegistryHydrated=="function"&&await this.ensureModelRegistryHydrated(),this.sendNotification("pet.state",{state:"building"}),this.sendNotification("pet.reaction",{text:"\u6B63\u5728\u5B75\u5316\u4F60\u7684\u4E13\u5C5E\u5BA0\u7269...",style:"thinking"});try{let r=e.description?.slice(0,10)??"\u81EA\u5B9A\u4E49\u5BA0\u7269",n=e.description??"";e.imageBase64&&(n=await this.petRuntime.forgeAnalyzeImage(e.imageBase64,e.description),this.sendNotification("pet.reaction",{text:"\u5206\u6790\u5B8C\u6210\uFF0C\u6B63\u5728\u751F\u6210\u9AA8\u67B6...",style:"thinking"}));let o=await this.petRuntime.forgeGenerateSkeleton(n),s=Ir(o),i=Ms(s),a=0;for(;i.length>0&&a<2;){a++,this.sendNotification("pet.reaction",{text:`\u9AA8\u67B6\u7F3A\u5C11 ${i.join("\u3001")}\uFF0C\u91CD\u65B0\u751F\u6210 (${a}/${2})...`,style:"thinking",duration:3e3});let m=`\u4E0A\u6B21\u751F\u6210\u7F3A\u5C11\u4EE5\u4E0B\u90E8\u4F4D: ${i.join(", ")}\u3002\u8BF7\u786E\u4FDD\u6240\u6709 id \u5C5E\u6027\u90FD\u5B58\u5728\u3002`;o=await this.petRuntime.forgeGenerateSkeleton(n+`
|
|
326
326
|
|
|
327
|
-
`+m),s=Ir(o),i=Ms(s)}i.length>0&&this.sendNotification("pet.reaction",{text:"\u9AA8\u67B6\u4E0D\u5B8C\u6574\uFF0C\u90E8\u5206\u52A8\u753B\u53EF\u80FD\u7F3A\u5931\uFF0C\u7EE7\u7EED\u751F\u6210...",style:"normal",duration:3e3}),this.sendNotification("pet.reaction",{text:"\u9AA8\u67B6\u751F\u6210\u5B8C\u6210\uFF0C\u5F00\u59CB\u6E32\u67D3\u5404\u72B6\u6001...",style:"thinking"});let c=["idle","thinking","working","done","happy","error","sleeping","eating"],l={baseSvg:s,parts:Is(s),colors:_s(s),characterDesc:n},d={};for(let m of c)d[m]=Es(l,m),this.sendNotification("pet.reaction",{text:`\u6E32\u67D3 ${m} \u72B6\u6001... (${Object.keys(d).length}/${c.length})`,style:"thinking",duration:2e3});let u=kl(d.idle,d,{threshold:6});if(!u.passedAll&&u.retryStates.length>0&&(this.sendNotification("pet.reaction",{text:`\u4E00\u81F4\u6027\u68C0\u67E5\uFF1A${u.retryStates.length} \u4E2A\u72B6\u6001\u9700\u4F18\u5316...`,style:"thinking",duration:3e3}),u.overallScore<4)){let m=Rl(n,"all","\u9AA8\u67B6\u7ED3\u6784\u4E0D\u5B8C\u6574\u5BFC\u81F4\u591A\u72B6\u6001\u4E00\u81F4\u6027\u5DEE",1);o=await this.petRuntime.forgeGenerateSkeleton(m);let g={baseSvg:Ir(o),parts:Is(Ir(o)),colors:_s(Ir(o)),characterDesc:n};for(let f of c)d[f]=Es(g,f)}let p={version:1,name:r,author:"user-generated",created:new Date().toISOString(),generator:"xiaozhi-pet-forge-v2-skeleton",source:{type:e.imageBase64?"image":"text",prompt:e.description},dimensions:{width:200,height:200},states:Object.fromEntries(c.map(m=>[m,{file:`states/${m}.svg`,loop:m!=="done"&&m!=="happy"&&m!=="eating",...m==="done"||m==="happy"?{duration:3e3}:m==="eating"?{duration:4e3}:{}}])),eyeTracking:{enabled:!0,pupils:[".left-eye .pupil",".right-eye .pupil"],maxOffset:3},colors:l.colors,consistency:{score:u.overallScore,method:"skeleton-parameterized"}};fl(p),this.sendNotification("pet.reaction",{text:`\u2705 \u5BA0\u7269\u300C${r}\u300D\u5DF2\u953B\u9020\u5B8C\u6210\uFF01\u4E00\u81F4\u6027\u8BC4\u5206 ${u.overallScore.toFixed(1)}/10`,style:"excited"}),this.sendNotification("pet.state",{state:"done"}),this.sendNotification("pet.forged",{name:r,svgs:d}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,manifest:p,svgs:d,status:"complete",consistency:{score:u.overallScore,passedAll:u.passedAll}})}catch(r){this.sendNotification("pet.state",{state:"error"}),this.sendNotification("pet.reaction",{text:"\u953B\u9020\u5931\u8D25\u4E86...",style:"normal"}),t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:gh(r,"Forge failed")})}}import*as Ih from"node:path";D();import{randomUUID as U_}from"node:crypto";var Jt=class{nodes=new Map;edges=[];constructor(e){for(let r of e){if(this.nodes.has(r.id))throw new Error(`Duplicate node ID: ${r.id}`);this.nodes.set(r.id,{id:r.id,kind:r.kind??"agent",params:r.params??{},status:"pending",outPorts:r.outPorts??["default"],joinPolicy:r.joinPolicy??"all",runIndex:0,maxIterations:r.maxIterations})}for(let r of e)for(let n of r.dependsOn??[]){if(!this.nodes.has(n))throw new Error(`Node "${r.id}" depends on unknown node "${n}"`);this.edges.push({from:n,to:r.id,fromPort:"default"})}this.validateDag()}getNode(e){return this.nodes.get(e)}getAllNodes(){return[...this.nodes.values()]}getReadyNodes(){let e=[];for(let r of this.nodes.values()){if(r.status!=="pending"||this.isBlockedByFailed(r.id))continue;let n=this.incomingForwardEdges(r.id);if(n.length===0){e.push(r);continue}r.joinPolicy==="any"?n.some(o=>this.edgeSatisfied(o))&&e.push(r):n.every(o=>this.edgeSatisfied(o))&&e.push(r)}return e}isFinished(){for(let e of this.nodes.values())if(e.status==="running"||e.status==="paused"||e.status==="pending"&&!this.isBlockedByFailed(e.id)&&!this.isSkippable(e.id))return!1;return!0}isAllCompleted(){return[...this.nodes.values()].every(e=>e.status==="completed"||e.status==="skipped")}getBlockedNodes(){return[...this.nodes.values()].filter(e=>e.status==="pending"&&this.isBlockedByFailed(e.id))}getProgress(){let e=0,r=0,n=0,o=0,s=0,i=0;for(let a of this.nodes.values())switch(a.status){case"completed":e++;break;case"running":r++;break;case"failed":n++;break;case"pending":o++;break;case"paused":s++;break;case"skipped":i++;break}return{total:this.nodes.size,completed:e,running:r,failed:n,pending:o,paused:s,skipped:i}}markRunning(e){let r=this.requireNode(e);if(r.status!=="pending")throw new Error(`Node "${e}" is ${r.status}, cannot start`);r.status="running",r.startedAt=Date.now()}markCompleted(e,r){let n=this.requireNode(e);if(n.status!=="running")throw new Error(`Node "${e}" is ${n.status}, cannot complete`);n.status="completed",n.output=r.output,n.completedAt=Date.now(),n.firedPorts=r.firedPorts??n.outPorts,this.propagateSkips()}markFailed(e,r){let n=this.requireNode(e);n.status="failed",n.error=r,n.completedAt=Date.now(),this.propagateSkips()}markPaused(e){let r=this.requireNode(e);r.status==="running"&&(r.status="paused")}resumePaused(e){let r=this.requireNode(e);r.status==="paused"&&(r.status="pending")}markSkipped(e){let r=this.requireNode(e);if(r.status!=="pending")throw new Error(`Node "${e}" is ${r.status}, cannot skip`);r.status="skipped",r.firedPorts=[],this.propagateSkips()}pauseAll(){for(let e of this.nodes.values())e.status==="running"&&(e.status="paused")}resumeAll(){for(let e of this.nodes.values())e.status==="paused"&&(e.status="pending")}decideLoop(e,r){let n=this.requireNode(e);if(n.kind!=="loop")throw new Error(`Node "${e}" is not a loop controller`);if(!n.maxIterations||n.maxIterations<=0)throw new Error(`Loop "${e}" requires maxIterations > 0`);let o=n.iteration??0;r&&o<n.maxIterations?(n.iteration=o+1,n.firedPorts=["loop"],this.resetLoopScope(e)):(n.firedPorts=["done"],r&&(n.error=`loop_cap_reached:${n.maxIterations}`)),this.propagateSkips()}addNode(e){if(this.nodes.has(e.id))throw new Error(`Node "${e.id}" already exists`);for(let r of e.dependsOn??[])if(!this.nodes.has(r))throw new Error(`Node "${e.id}" depends on unknown node "${r}"`);this.nodes.set(e.id,{id:e.id,kind:e.kind??"agent",params:e.params??{},status:"pending",outPorts:e.outPorts??["default"],joinPolicy:e.joinPolicy??"all",runIndex:0,maxIterations:e.maxIterations});for(let r of e.dependsOn??[])this.edges.push({from:r,to:e.id,fromPort:"default"});try{this.validateDag()}catch(r){throw this.nodes.delete(e.id),this.edges=this.edges.filter(n=>n.to!==e.id||!e.dependsOn?.includes(n.from)),r}}addNodes(e){let r=[],n=[];try{for(let o of e){if(this.nodes.has(o.id))throw new Error(`Node "${o.id}" already exists`);for(let i of o.dependsOn??[])if(!this.nodes.has(i))throw new Error(`Unknown dep "${i}" for "${o.id}"`);this.nodes.set(o.id,{id:o.id,kind:o.kind??"agent",params:o.params??{},status:"pending",outPorts:o.outPorts??["default"],joinPolicy:o.joinPolicy??"all",runIndex:0,maxIterations:o.maxIterations}),r.push(o.id);let s=(o.dependsOn??[]).map(i=>({from:i,to:o.id,fromPort:"default"}));this.edges.push(...s),n.push(...s)}this.validateDag()}catch(o){for(let s of r)this.nodes.delete(s);throw this.edges=this.edges.filter(s=>!n.includes(s)),o}}removeNode(e){let r=this.requireNode(e);if(r.status==="running")throw new Error(`Cannot remove running node "${e}"`);if(r.status==="completed")throw new Error(`Cannot remove completed node "${e}"`);this.edges=this.edges.filter(n=>n.from!==e&&n.to!==e),this.nodes.delete(e)}retryNode(e,r){let n=this.requireNode(e);if(n.status!=="failed")throw new Error(`Node "${e}" is ${n.status}, only failed nodes can be retried`);n.status="pending",n.error=void 0,n.output=void 0,n.firedPorts=void 0,n.startedAt=void 0,n.completedAt=void 0,r&&Object.assign(n.params,r)}updateNodeParams(e,r){let n=this.requireNode(e);if(n.status!=="pending")throw new Error(`Node "${e}" is ${n.status}, can only update pending nodes`);Object.assign(n.params,r)}addEdge(e){let{from:r,to:n,fromPort:o="default",loopBack:s=!1}=e;if(!this.nodes.has(r))throw new Error(`Unknown source node "${r}"`);if(!this.nodes.has(n))throw new Error(`Unknown target node "${n}"`);let i=this.nodes.get(r);if(!s&&!i.outPorts.includes(o))throw new Error(`Node "${r}" has no outPort "${o}"`);if(!this.edges.find(c=>c.from===r&&c.to===n&&(c.fromPort??"default")===o))if(this.edges.push({from:r,to:n,fromPort:o,loopBack:s}),s){let c=this.nodes.get(n);if(!c.maxIterations||c.maxIterations<=0)throw this.edges.pop(),new Error(`LoopBack controller "${n}" requires maxIterations > 0`)}else try{this.validateDag()}catch(c){throw this.edges=this.edges.filter(l=>!(l.from===r&&l.to===n&&(l.fromPort??"default")===o)),c}}removeEdge(e,r,n){let o=n??"default";this.edges=this.edges.filter(s=>!(s.from===e&&s.to===r&&(s.fromPort??"default")===o))}serialize(){return[...this.nodes.values()].map(e=>{let r=this.incomingForwardEdges(e.id).map(n=>n.from);return{id:e.id,kind:e.kind,params:e.params,dependsOn:r,outPorts:e.outPorts,joinPolicy:e.joinPolicy,status:e.status,firedPorts:e.firedPorts,output:e.output,error:e.error,startedAt:e.startedAt,completedAt:e.completedAt,runIndex:e.runIndex,maxIterations:e.maxIterations,iteration:e.iteration}})}restore(e){for(let r of e){let n=this.nodes.get(r.id);n&&(n.status=r.status==="running"?"pending":r.status,n.output=r.output,n.error=r.error,n.firedPorts=r.firedPorts,n.startedAt=r.startedAt,n.completedAt=r.completedAt,n.runIndex=r.runIndex??0,n.iteration=r.iteration)}}edgeSatisfied(e){let r=this.nodes.get(e.from);if(!r||r.status!=="completed")return!1;let n=e.fromPort??"default";return(r.firedPorts??r.outPorts).includes(n)}edgeDead(e){let r=this.nodes.get(e.from);if(!r)return!1;if(r.status==="skipped")return!0;if(r.status==="completed"){if(r.kind==="loop"&&!(r.firedPorts??[]).includes("done"))return!1;let n=e.fromPort??"default";return!(r.firedPorts??r.outPorts).includes(n)}return!1}incomingForwardEdges(e){return this.edges.filter(r=>r.to===e&&!r.loopBack)}isBlockedByFailed(e){return this.incomingForwardEdges(e).some(r=>this.nodes.get(r.from)?.status==="failed")}isSkippable(e){let r=this.incomingForwardEdges(e);return r.length===0?!1:this.nodes.get(e).joinPolicy==="any"?r.every(o=>this.edgeDead(o)):r.some(o=>this.edgeDead(o))}propagateSkips(){let e=!0;for(;e;){e=!1;for(let r of this.nodes.values())r.status==="pending"&&this.isSkippable(r.id)&&(r.status="skipped",r.firedPorts=[],e=!0)}}resetLoopScope(e){let r=this.loopBodyNodes(e);for(let n of r){let o=this.nodes.get(n);o.status="pending",o.runIndex=(o.runIndex??0)+1,o.output=void 0,o.firedPorts=void 0,o.error=void 0,o.startedAt=void 0,o.completedAt=void 0}}loopBodyNodes(e){let r=new Set,n=(o,s)=>{for(let i of this.edges)i.from!==o||i.loopBack||s&&(i.fromPort??"default")!=="loop"||i.to!==e&&(r.has(i.to)||(r.add(i.to),n(i.to,!1)))};return n(e,!0),r}validateDag(){for(let s of this.edges){if(!this.nodes.has(s.from))throw new Error(`Edge references unknown source "${s.from}"`);if(!this.nodes.has(s.to))throw new Error(`Edge references unknown target "${s.to}"`)}let e=this.edges.filter(s=>!s.loopBack),r=new Set,n=new Set,o=s=>{if(n.has(s))throw new Error(`Cycle detected involving node "${s}"`);if(!r.has(s)){n.add(s);for(let i of e)i.from===s&&o(i.to);n.delete(s),r.add(s)}};for(let s of this.nodes.keys())o(s);for(let s of this.edges){if(!s.loopBack)continue;let i=this.nodes.get(s.to);if(!i?.maxIterations||i.maxIterations<=0)throw new Error(`LoopBack controller "${s.to}" must have maxIterations > 0`)}for(let s of this.nodes.values())if(s.maxIterations!==void 0&&s.maxIterations>1e3)throw new Error(`Loop "${s.id}" maxIterations ${s.maxIterations} exceeds the hard cap of 1000`)}requireNode(e){let r=this.nodes.get(e);if(!r)throw new Error(`Unknown node: "${e}"`);return r}};var Jn=class{maxTotalTokens;maxDuration;usedTokens=0;startedAt;warningEmitted=!1;constructor(e){this.maxTotalTokens=e?.maxTotalTokens,this.maxDuration=e?.maxDuration,this.startedAt=Date.now()}addUsage(e,r){this.usedTokens+=e+r}addFromTracker(e){if(!e.hasData())return;let r=e.getUsage();this.usedTokens+=r.totalTokens}getElapsed(){return Date.now()-this.startedAt}getBudget(){return{maxTotalTokens:this.maxTotalTokens,maxDuration:this.maxDuration,usedTokens:this.usedTokens,elapsed:this.getElapsed()}}check(){let e=this.getElapsed();if(this.maxDuration&&e>=this.maxDuration)return{action:"exceeded",percentage:Math.round(e/this.maxDuration*100),usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(this.maxTotalTokens){let n=Math.round(this.usedTokens/this.maxTotalTokens*100);if(this.usedTokens>=this.maxTotalTokens)return{action:"exceeded",percentage:n,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(n>=80&&!this.warningEmitted)return this.warningEmitted=!0,{action:"warning",percentage:n,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}return{action:"ok",percentage:this.maxTotalTokens?Math.round(this.usedTokens/this.maxTotalTokens*100):0,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}restore(e){this.usedTokens=e.usedTokens,this.startedAt=e.startedAt,this.warningEmitted=e.warningEmitted}serialize(){return{usedTokens:this.usedTokens,startedAt:this.startedAt,warningEmitted:this.warningEmitted}}};import{join as Tl}from"node:path";import{mkdir as D_,readdir as N_}from"node:fs/promises";import{readFile as A_,writeFile as x_,mkdir as P_,rename as C_,unlink as I_}from"node:fs/promises";import{dirname as E_,join as __}from"node:path";import{randomUUID as M_}from"node:crypto";async function sn(t,e){let r=E_(t);await P_(r,{recursive:!0});let n=__(r,`.tmp-${M_()}`);try{await x_(n,e,"utf-8");let o;for(let s=0;s<3;s++)try{await C_(n,t);return}catch(i){if(o=i,i.code!=="EPERM")throw i;await new Promise(a=>setTimeout(a,50*(s+1)))}throw o}catch(o){throw await I_(n).catch(()=>{}),o}}async function Qt(t){try{let e=await A_(t,"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return;throw e}}async function cr(t,e){await sn(t,JSON.stringify(e,null,2)+`
|
|
328
|
-
`)}D();function vh(t){return Tl(re(t),"products")}function kh(t,e){return Tl(vh(e),t)}function Rh(t,e){return Tl(kh(t,e),"product-state.json")}async function Sh(t,e){let r=kh(t.productId,e);await D_(r,{recursive:!0}),await cr(Rh(t.productId,e),t)}async function Al(t,e){return Qt(Rh(t,e))}async function wh(t){let e=vh(t),r;try{r=await N_(e)}catch{return[]}let n=[];for(let o of r){let s=await Al(o,t);s&&n.push(s)}return n}var Qn=class t{constructor(e={}){this.callbacks=e}callbacks;static DEFAULT_INTERVAL=5*6e4;static LONG_RUNNING_INTERVAL=30*6e4;static LONG_RUNNING_THRESHOLD=2880*6e4;timer=null;lastCheckpointAt=0;cwd;start(e){this.cwd=e,this.stop(),this.timer=setInterval(()=>{let r=this.callbacks.getState?.();r&&this.checkpoint(r).catch(n=>{this.callbacks.log?.warn(`[checkpoint] periodic save failed: ${n instanceof Error?n.message:String(n)}`)})},t.DEFAULT_INTERVAL),this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}getInterval(e){return e>t.LONG_RUNNING_THRESHOLD?t.LONG_RUNNING_INTERVAL:t.DEFAULT_INTERVAL}isDue(e){if(this.lastCheckpointAt===0)return!0;let r=this.getInterval(e);return Date.now()-this.lastCheckpointAt>=r}async checkpoint(e){let r=new Date().toISOString();e.lastCheckpointAt=r,await Sh(e,this.cwd),this.lastCheckpointAt=Date.now(),this.callbacks.onCheckpoint?.(e.productId,r),this.callbacks.log?.info(`[checkpoint] saved ${e.productId} at ${r}`)}getLastCheckpointAt(){return this.lastCheckpointAt}};import{execFile as L_}from"node:child_process";import{promisify as O_}from"node:util";import{join as Th}from"node:path";import{mkdir as j_,rm as $_}from"node:fs/promises";var an=O_(L_);async function Zn(t){try{let{stdout:e}=await an("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8"});return e.trim()}catch{return null}}async function Ds(t,e,r){let n=Th(t,".worktrees");await j_(n,{recursive:!0});let o=Th(n,e),i=["worktree","add","-B",`solo/${e}`,o];return r?i.push(r):i.push("HEAD"),await an("git",i,{cwd:t,encoding:"utf8"}),o}async function xl(t){try{await an("git",["add","-A"],{cwd:t});let{stdout:e}=await an("git",["diff","--cached","--stat"],{cwd:t,encoding:"utf8"});return e.trim()}catch{return""}}async function Ah(t,e){try{await an("git",["worktree","remove","--force",e],{cwd:t,encoding:"utf8"})}catch{try{await $_(e,{recursive:!0,force:!0})}catch{}}}async function xh(t,e){let{stdout:r}=await an("git",["merge","--no-ff",e,"-m",`solo: merge ${e}`],{cwd:t,encoding:"utf8"});return r.trim()}var Ns=class{constructor(e,r,n,o={}){this.processManager=e;this.acpDetector=r;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;async create(e){let{name:r,cwd:n,instances:o,tasks:s,budget:i}=e;if(o.length===0)throw new Error("Product requires at least 1 instance");if(s.length===0)throw new Error("Product requires at least 1 task");let a=new Set(o.map(b=>b.name));for(let b of s)if(!a.has(b.assignee))throw new Error(`Task "${b.taskId}" references unknown instance "${b.assignee}"`);let c=`product-${U_().slice(0,8)}`,l=s.map(b=>({id:b.taskId,kind:"agent",params:{agentId:b.assignee,prompt:b.prompt},dependsOn:b.dependsOn})),d=new Jt(l),u=new Jn(i),p=new Qn({onCheckpoint:(b,S)=>this.callbacks.onCheckpointed?.(b,S),getState:()=>{let b=this.sessions.get(c);return b?this.buildPersistedState(b):null},log:this.callbacks.log}),m=await Zn(n),g=o.map((b,S)=>({instanceId:`${c}:${b.name}:${S}`,name:b.name,agentId:b.agentId,state:"idle"})),f={productId:c,name:r,cwd:n,phase:"active",instances:g,dag:d,budget:u,checkpoint:p,createdAt:new Date().toISOString(),gitRoot:m};this.sessions.set(c,f),p.start(n),this.callbacks.log?.info(`[product] created ${c} "${r}" with ${o.length} instances, ${s.length} tasks`);let h=s.map(b=>({id:b.taskId,label:b.taskId,deps:b.dependsOn??[]})),v=[];for(let b of s)if(b.dependsOn)for(let S of b.dependsOn)v.push({from:S,to:b.taskId});return this.callbacks.onDagTopology?.(c,h,v),setTimeout(()=>this.scheduleNext(f),0),c}async resume(e,r){let n=await Al(e,r);if(!n)throw new Error(`Product ${e} not found on disk`);let o=new Jt(n.tasks);o.restore(n.tasks);let s=new Jn({maxTotalTokens:n.budget.maxTotalTokens,maxDuration:n.budget.maxDuration});s.restore(n.budget);let i=new Qn({onCheckpoint:(d,u)=>this.callbacks.onCheckpointed?.(d,u),getState:()=>{let d=this.sessions.get(e);return d?this.buildPersistedState(d):null},log:this.callbacks.log}),a=await Zn(n.cwd),c=n.instances.map((d,u)=>({instanceId:`${e}:${d.name}:${u}`,name:d.name,agentId:d.agentId,state:"idle"})),l={productId:n.productId,name:n.name,cwd:n.cwd,phase:"active",instances:c,dag:o,budget:s,checkpoint:i,createdAt:n.createdAt,gitRoot:a};this.sessions.set(e,l),i.start(n.cwd),this.callbacks.log?.info(`[product] resumed ${e}`),this.scheduleNext(l)}async pause(e){let r=this.sessions.get(e);if(!r)throw new Error(`Product ${e} not found`);if(r.phase!=="active")throw new Error(`Product ${e} is not active`);r.phase="paused",r.dag.pauseAll();for(let n of r.instances)if(n.state==="running"&&n.memberId){try{this.processManager.kill(n.memberId)}catch{}n.state="paused"}await r.checkpoint.checkpoint(this.buildPersistedState(r)),r.checkpoint.stop(),this.callbacks.log?.info(`[product] paused ${e}`)}async checkpoint(e){let r=this.sessions.get(e);if(!r)throw new Error(`Product ${e} not found`);await r.checkpoint.checkpoint(this.buildPersistedState(r))}async delete(e){let r=this.sessions.get(e);if(!r)throw new Error(`Product ${e} not found`);if(r.phase==="active"){r.phase="failed",r.dag.pauseAll();for(let n of r.instances)if(n.state==="running"&&n.memberId){try{this.processManager.kill(n.memberId)}catch{}n.state="failed"}}r.checkpoint.stop(),this.sessions.delete(e),this.callbacks.log?.info(`[product] deleted ${e}`)}async rollback(e,r){let n=this.sessions.get(e);if(!n)throw new Error(`Product ${e} not found`);let o=n.cwd;await this.delete(e),await this.resume(e,o),this.callbacks.log?.info(`[product] rolled back ${e} to checkpoint ${r}`)}getStatus(e){let r=this.sessions.get(e);return r?{productId:r.productId,name:r.name,phase:r.phase,instances:r.instances.map(n=>{let s=(n.memberId?this.processManager.getUsageTracker(n.memberId):null)?.getUsage();return{instanceId:n.instanceId,name:n.name,agentId:n.agentId,state:n.state,worktreePath:n.worktreePath,usage:s&&(s.inputTokens>0||s.outputTokens>0)?{inputTokens:s.inputTokens,outputTokens:s.outputTokens}:void 0}}),tasks:r.dag.getAllNodes().map(n=>({taskId:n.id,assignee:n.params.agentId,status:n.status,result:n.output,error:n.error,startedAt:n.startedAt?new Date(n.startedAt).toISOString():void 0,completedAt:n.completedAt?new Date(n.completedAt).toISOString():void 0})),budget:r.budget.getBudget(),lastCheckpointAt:new Date(r.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}:null}async list(e){let r=[];for(let o of this.sessions.values()){let s=o.dag.getAllNodes();r.push({productId:o.productId,name:o.name,phase:o.phase,instanceCount:o.instances.length,taskCount:s.length,completedTasks:s.filter(i=>i.status==="completed").length,createdAt:o.createdAt,lastCheckpointAt:new Date(o.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()})}let n=await wh(e);for(let o of n)this.sessions.has(o.productId)||r.push({productId:o.productId,name:o.name,phase:o.phase,instanceCount:o.instances.length,taskCount:o.tasks.length,completedTasks:o.tasks.filter(s=>s.status==="completed").length,createdAt:o.createdAt,lastCheckpointAt:o.lastCheckpointAt});return r}scheduleNext(e){if(e.phase!=="active")return;let r=e.budget.check();if(r.action==="exceeded"){this.callbacks.log?.warn(`[product] ${e.productId} budget exceeded, auto-pausing`),this.pause(e.productId).catch(o=>{this.callbacks.log?.warn(`[product] auto-pause failed: ${o instanceof Error?o.message:String(o)}`)});return}if(r.action==="warning"&&this.callbacks.onBudgetWarning?.(e.productId,r.usedTokens,r.maxTotalTokens,r.percentage),e.dag.isFinished()){this.finishProduct(e);return}let n=e.dag.getReadyNodes();for(let o of n)this.dispatchTask(e,o)}dispatchTask(e,r){let n=e.instances.find(o=>o.name===r.params.agentId);if(!n){e.dag.markFailed(r.id,`No instance found for assignee "${r.params.agentId}"`),this.callbacks.onTaskFailed?.(e.productId,r.id,`No instance for "${r.params.agentId}"`),this.scheduleNext(e);return}e.dag.markRunning(r.id),n.state="running",this.callbacks.onTaskStarted?.(e.productId,r.id,r.params.agentId),this.callbacks.log?.info(`[product] ${e.productId} dispatching task ${r.id} to ${r.params.agentId}`),this.runTask(e,n,r).catch(o=>{this.callbacks.log?.warn(`[product] task dispatch error: ${o instanceof Error?o.message:String(o)}`)})}async runTask(e,r,n){let o=`${e.productId}:${r.name}:${n.id}`;r.memberId=o;try{let s=this.acpDetector.buildExternalDescriptor(r.agentId);if(!s)throw new Error(`Agent ${r.agentId} is not available`);let i=e.cwd;if(e.gitRoot){let d=`${e.productId}-${r.name}-${n.id}`;try{i=await Ds(e.gitRoot,d),r.worktreePath=i}catch{this.callbacks.log?.warn(`[product] worktree creation failed for ${n.id}, using project cwd`)}}await this.processManager.spawn({memberId:o,name:`product-${r.name}`,cwd:i,prompt:n.params.prompt,external:s});let a=await this.processManager.sendTask(o,n.params.prompt),c=typeof a=="string"?a:JSON.stringify(a),l=this.processManager.getUsageTracker(o);if(l?.hasData()){let d=l.getUsage();e.budget.addUsage(d.inputTokens,d.outputTokens);let u=e.budget.getBudget();this.callbacks.onBudgetUpdate?.(e.productId,u.usedTokens,0,u.elapsed,u.maxTotalTokens)}e.dag.markCompleted(n.id,{output:c}),r.state="completed",this.callbacks.onTaskCompleted?.(e.productId,n.id,c);try{this.processManager.kill(o)}catch{}this.processManager.remove(o)}catch(s){let i=s instanceof Error?s.message:String(s);e.dag.markFailed(n.id,i),r.state="failed",this.callbacks.onTaskFailed?.(e.productId,n.id,i);try{this.processManager.kill(o)}catch{}try{this.processManager.remove(o)}catch{}}try{await e.checkpoint.checkpoint(this.buildPersistedState(e))}catch(s){this.callbacks.log?.warn(`[product] checkpoint failed: ${s instanceof Error?s.message:String(s)}`)}this.scheduleNext(e)}finishProduct(e){if(e.dag.isAllCompleted()){e.phase="completed";let r=e.dag.getAllNodes(),n=`Product "${e.name}" completed: ${r.length} tasks all done.`;this.callbacks.onCompleted?.(e.productId,n)}else{e.phase="failed";let n=e.dag.getAllNodes().filter(i=>i.status==="failed").length,o=e.dag.getBlockedNodes().length,s=`Product "${e.name}" finished with ${n} failed, ${o} blocked tasks.`;this.callbacks.onCompleted?.(e.productId,s)}e.checkpoint.stop(),e.checkpoint.checkpoint(this.buildPersistedState(e)).catch(r=>{this.callbacks.log?.warn(`[product] final checkpoint failed: ${r instanceof Error?r.message:String(r)}`)}),this.callbacks.log?.info(`[product] ${e.productId} finished (phase=${e.phase})`)}buildPersistedState(e){return{productId:e.productId,name:e.name,phase:e.phase,cwd:e.cwd,instances:e.instances.map(r=>({name:r.name,role:"",agentId:r.agentId})),tasks:e.dag.serialize(),budget:e.budget.serialize(),createdAt:e.createdAt,lastCheckpointAt:new Date(e.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}}};import{randomUUID as Ph}from"node:crypto";function F_(t,e){let r=e?`
|
|
327
|
+
`+m),s=Ir(o),i=Ms(s)}i.length>0&&this.sendNotification("pet.reaction",{text:"\u9AA8\u67B6\u4E0D\u5B8C\u6574\uFF0C\u90E8\u5206\u52A8\u753B\u53EF\u80FD\u7F3A\u5931\uFF0C\u7EE7\u7EED\u751F\u6210...",style:"normal",duration:3e3}),this.sendNotification("pet.reaction",{text:"\u9AA8\u67B6\u751F\u6210\u5B8C\u6210\uFF0C\u5F00\u59CB\u6E32\u67D3\u5404\u72B6\u6001...",style:"thinking"});let c=["idle","thinking","working","done","happy","error","sleeping","eating"],l={baseSvg:s,parts:Is(s),colors:_s(s),characterDesc:n},d={};for(let m of c)d[m]=Es(l,m),this.sendNotification("pet.reaction",{text:`\u6E32\u67D3 ${m} \u72B6\u6001... (${Object.keys(d).length}/${c.length})`,style:"thinking",duration:2e3});let u=kl(d.idle,d,{threshold:6});if(!u.passedAll&&u.retryStates.length>0&&(this.sendNotification("pet.reaction",{text:`\u4E00\u81F4\u6027\u68C0\u67E5\uFF1A${u.retryStates.length} \u4E2A\u72B6\u6001\u9700\u4F18\u5316...`,style:"thinking",duration:3e3}),u.overallScore<4)){let m=Rl(n,"all","\u9AA8\u67B6\u7ED3\u6784\u4E0D\u5B8C\u6574\u5BFC\u81F4\u591A\u72B6\u6001\u4E00\u81F4\u6027\u5DEE",1);o=await this.petRuntime.forgeGenerateSkeleton(m);let g={baseSvg:Ir(o),parts:Is(Ir(o)),colors:_s(Ir(o)),characterDesc:n};for(let f of c)d[f]=Es(g,f)}let p={version:1,name:r,author:"user-generated",created:new Date().toISOString(),generator:"xiaozhi-pet-forge-v2-skeleton",source:{type:e.imageBase64?"image":"text",prompt:e.description},dimensions:{width:200,height:200},states:Object.fromEntries(c.map(m=>[m,{file:`states/${m}.svg`,loop:m!=="done"&&m!=="happy"&&m!=="eating",...m==="done"||m==="happy"?{duration:3e3}:m==="eating"?{duration:4e3}:{}}])),eyeTracking:{enabled:!0,pupils:[".left-eye .pupil",".right-eye .pupil"],maxOffset:3},colors:l.colors,consistency:{score:u.overallScore,method:"skeleton-parameterized"}};fl(p),this.sendNotification("pet.reaction",{text:`\u2705 \u5BA0\u7269\u300C${r}\u300D\u5DF2\u953B\u9020\u5B8C\u6210\uFF01\u4E00\u81F4\u6027\u8BC4\u5206 ${u.overallScore.toFixed(1)}/10`,style:"excited"}),this.sendNotification("pet.state",{state:"done"}),this.sendNotification("pet.forged",{name:r,svgs:d}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,manifest:p,svgs:d,status:"complete",consistency:{score:u.overallScore,passedAll:u.passedAll}})}catch(r){this.sendNotification("pet.state",{state:"error"}),this.sendNotification("pet.reaction",{text:"\u953B\u9020\u5931\u8D25\u4E86...",style:"normal"}),t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:gh(r,"Forge failed")})}}import*as Ih from"node:path";D();import{randomUUID as U_}from"node:crypto";var Qt=class{nodes=new Map;edges=[];constructor(e){for(let r of e){if(this.nodes.has(r.id))throw new Error(`Duplicate node ID: ${r.id}`);this.nodes.set(r.id,{id:r.id,kind:r.kind??"agent",params:r.params??{},status:"pending",outPorts:r.outPorts??["default"],joinPolicy:r.joinPolicy??"all",runIndex:0,maxIterations:r.maxIterations})}for(let r of e)for(let n of r.dependsOn??[]){if(!this.nodes.has(n))throw new Error(`Node "${r.id}" depends on unknown node "${n}"`);this.edges.push({from:n,to:r.id,fromPort:"default"})}this.validateDag()}getNode(e){return this.nodes.get(e)}getAllNodes(){return[...this.nodes.values()]}getReadyNodes(){let e=[];for(let r of this.nodes.values()){if(r.status!=="pending"||this.isBlockedByFailed(r.id))continue;let n=this.incomingForwardEdges(r.id);if(n.length===0){e.push(r);continue}r.joinPolicy==="any"?n.some(o=>this.edgeSatisfied(o))&&e.push(r):n.every(o=>this.edgeSatisfied(o))&&e.push(r)}return e}isFinished(){for(let e of this.nodes.values())if(e.status==="running"||e.status==="paused"||e.status==="pending"&&!this.isBlockedByFailed(e.id)&&!this.isSkippable(e.id))return!1;return!0}isAllCompleted(){return[...this.nodes.values()].every(e=>e.status==="completed"||e.status==="skipped")}getBlockedNodes(){return[...this.nodes.values()].filter(e=>e.status==="pending"&&this.isBlockedByFailed(e.id))}getProgress(){let e=0,r=0,n=0,o=0,s=0,i=0;for(let a of this.nodes.values())switch(a.status){case"completed":e++;break;case"running":r++;break;case"failed":n++;break;case"pending":o++;break;case"paused":s++;break;case"skipped":i++;break}return{total:this.nodes.size,completed:e,running:r,failed:n,pending:o,paused:s,skipped:i}}markRunning(e){let r=this.requireNode(e);if(r.status!=="pending")throw new Error(`Node "${e}" is ${r.status}, cannot start`);r.status="running",r.startedAt=Date.now()}markCompleted(e,r){let n=this.requireNode(e);if(n.status!=="running")throw new Error(`Node "${e}" is ${n.status}, cannot complete`);n.status="completed",n.output=r.output,n.completedAt=Date.now(),n.firedPorts=r.firedPorts??n.outPorts,this.propagateSkips()}markFailed(e,r){let n=this.requireNode(e);n.status="failed",n.error=r,n.completedAt=Date.now(),this.propagateSkips()}markPaused(e){let r=this.requireNode(e);r.status==="running"&&(r.status="paused")}resumePaused(e){let r=this.requireNode(e);r.status==="paused"&&(r.status="pending")}markSkipped(e){let r=this.requireNode(e);if(r.status!=="pending")throw new Error(`Node "${e}" is ${r.status}, cannot skip`);r.status="skipped",r.firedPorts=[],this.propagateSkips()}pauseAll(){for(let e of this.nodes.values())e.status==="running"&&(e.status="paused")}resumeAll(){for(let e of this.nodes.values())e.status==="paused"&&(e.status="pending")}decideLoop(e,r){let n=this.requireNode(e);if(n.kind!=="loop")throw new Error(`Node "${e}" is not a loop controller`);if(!n.maxIterations||n.maxIterations<=0)throw new Error(`Loop "${e}" requires maxIterations > 0`);let o=n.iteration??0;r&&o<n.maxIterations?(n.iteration=o+1,n.firedPorts=["loop"],this.resetLoopScope(e)):(n.firedPorts=["done"],r&&(n.error=`loop_cap_reached:${n.maxIterations}`)),this.propagateSkips()}addNode(e){if(this.nodes.has(e.id))throw new Error(`Node "${e.id}" already exists`);for(let r of e.dependsOn??[])if(!this.nodes.has(r))throw new Error(`Node "${e.id}" depends on unknown node "${r}"`);this.nodes.set(e.id,{id:e.id,kind:e.kind??"agent",params:e.params??{},status:"pending",outPorts:e.outPorts??["default"],joinPolicy:e.joinPolicy??"all",runIndex:0,maxIterations:e.maxIterations});for(let r of e.dependsOn??[])this.edges.push({from:r,to:e.id,fromPort:"default"});try{this.validateDag()}catch(r){throw this.nodes.delete(e.id),this.edges=this.edges.filter(n=>n.to!==e.id||!e.dependsOn?.includes(n.from)),r}}addNodes(e){let r=[],n=[];try{for(let o of e){if(this.nodes.has(o.id))throw new Error(`Node "${o.id}" already exists`);for(let i of o.dependsOn??[])if(!this.nodes.has(i))throw new Error(`Unknown dep "${i}" for "${o.id}"`);this.nodes.set(o.id,{id:o.id,kind:o.kind??"agent",params:o.params??{},status:"pending",outPorts:o.outPorts??["default"],joinPolicy:o.joinPolicy??"all",runIndex:0,maxIterations:o.maxIterations}),r.push(o.id);let s=(o.dependsOn??[]).map(i=>({from:i,to:o.id,fromPort:"default"}));this.edges.push(...s),n.push(...s)}this.validateDag()}catch(o){for(let s of r)this.nodes.delete(s);throw this.edges=this.edges.filter(s=>!n.includes(s)),o}}removeNode(e){let r=this.requireNode(e);if(r.status==="running")throw new Error(`Cannot remove running node "${e}"`);if(r.status==="completed")throw new Error(`Cannot remove completed node "${e}"`);this.edges=this.edges.filter(n=>n.from!==e&&n.to!==e),this.nodes.delete(e)}retryNode(e,r){let n=this.requireNode(e);if(n.status!=="failed")throw new Error(`Node "${e}" is ${n.status}, only failed nodes can be retried`);n.status="pending",n.error=void 0,n.output=void 0,n.firedPorts=void 0,n.startedAt=void 0,n.completedAt=void 0,r&&Object.assign(n.params,r)}updateNodeParams(e,r){let n=this.requireNode(e);if(n.status!=="pending")throw new Error(`Node "${e}" is ${n.status}, can only update pending nodes`);Object.assign(n.params,r)}addEdge(e){let{from:r,to:n,fromPort:o="default",loopBack:s=!1}=e;if(!this.nodes.has(r))throw new Error(`Unknown source node "${r}"`);if(!this.nodes.has(n))throw new Error(`Unknown target node "${n}"`);let i=this.nodes.get(r);if(!s&&!i.outPorts.includes(o))throw new Error(`Node "${r}" has no outPort "${o}"`);if(!this.edges.find(c=>c.from===r&&c.to===n&&(c.fromPort??"default")===o))if(this.edges.push({from:r,to:n,fromPort:o,loopBack:s}),s){let c=this.nodes.get(n);if(!c.maxIterations||c.maxIterations<=0)throw this.edges.pop(),new Error(`LoopBack controller "${n}" requires maxIterations > 0`)}else try{this.validateDag()}catch(c){throw this.edges=this.edges.filter(l=>!(l.from===r&&l.to===n&&(l.fromPort??"default")===o)),c}}removeEdge(e,r,n){let o=n??"default";this.edges=this.edges.filter(s=>!(s.from===e&&s.to===r&&(s.fromPort??"default")===o))}serialize(){return[...this.nodes.values()].map(e=>{let r=this.incomingForwardEdges(e.id).map(n=>n.from);return{id:e.id,kind:e.kind,params:e.params,dependsOn:r,outPorts:e.outPorts,joinPolicy:e.joinPolicy,status:e.status,firedPorts:e.firedPorts,output:e.output,error:e.error,startedAt:e.startedAt,completedAt:e.completedAt,runIndex:e.runIndex,maxIterations:e.maxIterations,iteration:e.iteration}})}restore(e){for(let r of e){let n=this.nodes.get(r.id);n&&(n.status=r.status==="running"?"pending":r.status,n.output=r.output,n.error=r.error,n.firedPorts=r.firedPorts,n.startedAt=r.startedAt,n.completedAt=r.completedAt,n.runIndex=r.runIndex??0,n.iteration=r.iteration)}}edgeSatisfied(e){let r=this.nodes.get(e.from);if(!r||r.status!=="completed")return!1;let n=e.fromPort??"default";return(r.firedPorts??r.outPorts).includes(n)}edgeDead(e){let r=this.nodes.get(e.from);if(!r)return!1;if(r.status==="skipped")return!0;if(r.status==="completed"){if(r.kind==="loop"&&!(r.firedPorts??[]).includes("done"))return!1;let n=e.fromPort??"default";return!(r.firedPorts??r.outPorts).includes(n)}return!1}incomingForwardEdges(e){return this.edges.filter(r=>r.to===e&&!r.loopBack)}isBlockedByFailed(e){return this.incomingForwardEdges(e).some(r=>this.nodes.get(r.from)?.status==="failed")}isSkippable(e){let r=this.incomingForwardEdges(e);return r.length===0?!1:this.nodes.get(e).joinPolicy==="any"?r.every(o=>this.edgeDead(o)):r.some(o=>this.edgeDead(o))}propagateSkips(){let e=!0;for(;e;){e=!1;for(let r of this.nodes.values())r.status==="pending"&&this.isSkippable(r.id)&&(r.status="skipped",r.firedPorts=[],e=!0)}}resetLoopScope(e){let r=this.loopBodyNodes(e);for(let n of r){let o=this.nodes.get(n);o.status="pending",o.runIndex=(o.runIndex??0)+1,o.output=void 0,o.firedPorts=void 0,o.error=void 0,o.startedAt=void 0,o.completedAt=void 0}}loopBodyNodes(e){let r=new Set,n=(o,s)=>{for(let i of this.edges)i.from!==o||i.loopBack||s&&(i.fromPort??"default")!=="loop"||i.to!==e&&(r.has(i.to)||(r.add(i.to),n(i.to,!1)))};return n(e,!0),r}validateDag(){for(let s of this.edges){if(!this.nodes.has(s.from))throw new Error(`Edge references unknown source "${s.from}"`);if(!this.nodes.has(s.to))throw new Error(`Edge references unknown target "${s.to}"`)}let e=this.edges.filter(s=>!s.loopBack),r=new Set,n=new Set,o=s=>{if(n.has(s))throw new Error(`Cycle detected involving node "${s}"`);if(!r.has(s)){n.add(s);for(let i of e)i.from===s&&o(i.to);n.delete(s),r.add(s)}};for(let s of this.nodes.keys())o(s);for(let s of this.edges){if(!s.loopBack)continue;let i=this.nodes.get(s.to);if(!i?.maxIterations||i.maxIterations<=0)throw new Error(`LoopBack controller "${s.to}" must have maxIterations > 0`)}for(let s of this.nodes.values())if(s.maxIterations!==void 0&&s.maxIterations>1e3)throw new Error(`Loop "${s.id}" maxIterations ${s.maxIterations} exceeds the hard cap of 1000`)}requireNode(e){let r=this.nodes.get(e);if(!r)throw new Error(`Unknown node: "${e}"`);return r}};var Jn=class{maxTotalTokens;maxDuration;usedTokens=0;startedAt;warningEmitted=!1;constructor(e){this.maxTotalTokens=e?.maxTotalTokens,this.maxDuration=e?.maxDuration,this.startedAt=Date.now()}addUsage(e,r){this.usedTokens+=e+r}addFromTracker(e){if(!e.hasData())return;let r=e.getUsage();this.usedTokens+=r.totalTokens}getElapsed(){return Date.now()-this.startedAt}getBudget(){return{maxTotalTokens:this.maxTotalTokens,maxDuration:this.maxDuration,usedTokens:this.usedTokens,elapsed:this.getElapsed()}}check(){let e=this.getElapsed();if(this.maxDuration&&e>=this.maxDuration)return{action:"exceeded",percentage:Math.round(e/this.maxDuration*100),usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(this.maxTotalTokens){let n=Math.round(this.usedTokens/this.maxTotalTokens*100);if(this.usedTokens>=this.maxTotalTokens)return{action:"exceeded",percentage:n,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration};if(n>=80&&!this.warningEmitted)return this.warningEmitted=!0,{action:"warning",percentage:n,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}return{action:"ok",percentage:this.maxTotalTokens?Math.round(this.usedTokens/this.maxTotalTokens*100):0,usedTokens:this.usedTokens,maxTotalTokens:this.maxTotalTokens,elapsed:e,maxDuration:this.maxDuration}}restore(e){this.usedTokens=e.usedTokens,this.startedAt=e.startedAt,this.warningEmitted=e.warningEmitted}serialize(){return{usedTokens:this.usedTokens,startedAt:this.startedAt,warningEmitted:this.warningEmitted}}};import{join as Tl}from"node:path";import{mkdir as D_,readdir as N_}from"node:fs/promises";import{readFile as A_,writeFile as x_,mkdir as P_,rename as C_,unlink as I_}from"node:fs/promises";import{dirname as E_,join as __}from"node:path";import{randomUUID as M_}from"node:crypto";async function sn(t,e){let r=E_(t);await P_(r,{recursive:!0});let n=__(r,`.tmp-${M_()}`);try{await x_(n,e,"utf-8");let o;for(let s=0;s<3;s++)try{await C_(n,t);return}catch(i){if(o=i,i.code!=="EPERM")throw i;await new Promise(a=>setTimeout(a,50*(s+1)))}throw o}catch(o){throw await I_(n).catch(()=>{}),o}}async function Zt(t){try{let e=await A_(t,"utf-8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return;throw e}}async function cr(t,e){await sn(t,JSON.stringify(e,null,2)+`
|
|
328
|
+
`)}D();function vh(t){return Tl(re(t),"products")}function kh(t,e){return Tl(vh(e),t)}function Rh(t,e){return Tl(kh(t,e),"product-state.json")}async function Sh(t,e){let r=kh(t.productId,e);await D_(r,{recursive:!0}),await cr(Rh(t.productId,e),t)}async function Al(t,e){return Zt(Rh(t,e))}async function wh(t){let e=vh(t),r;try{r=await N_(e)}catch{return[]}let n=[];for(let o of r){let s=await Al(o,t);s&&n.push(s)}return n}var Qn=class t{constructor(e={}){this.callbacks=e}callbacks;static DEFAULT_INTERVAL=5*6e4;static LONG_RUNNING_INTERVAL=30*6e4;static LONG_RUNNING_THRESHOLD=2880*6e4;timer=null;lastCheckpointAt=0;cwd;start(e){this.cwd=e,this.stop(),this.timer=setInterval(()=>{let r=this.callbacks.getState?.();r&&this.checkpoint(r).catch(n=>{this.callbacks.log?.warn(`[checkpoint] periodic save failed: ${n instanceof Error?n.message:String(n)}`)})},t.DEFAULT_INTERVAL),this.timer.unref()}stop(){this.timer&&(clearInterval(this.timer),this.timer=null)}getInterval(e){return e>t.LONG_RUNNING_THRESHOLD?t.LONG_RUNNING_INTERVAL:t.DEFAULT_INTERVAL}isDue(e){if(this.lastCheckpointAt===0)return!0;let r=this.getInterval(e);return Date.now()-this.lastCheckpointAt>=r}async checkpoint(e){let r=new Date().toISOString();e.lastCheckpointAt=r,await Sh(e,this.cwd),this.lastCheckpointAt=Date.now(),this.callbacks.onCheckpoint?.(e.productId,r),this.callbacks.log?.info(`[checkpoint] saved ${e.productId} at ${r}`)}getLastCheckpointAt(){return this.lastCheckpointAt}};import{execFile as L_}from"node:child_process";import{promisify as O_}from"node:util";import{join as Th}from"node:path";import{mkdir as j_,rm as $_}from"node:fs/promises";var an=O_(L_);async function Zn(t){try{let{stdout:e}=await an("git",["rev-parse","--show-toplevel"],{cwd:t,encoding:"utf8"});return e.trim()}catch{return null}}async function Ds(t,e,r){let n=Th(t,".worktrees");await j_(n,{recursive:!0});let o=Th(n,e),i=["worktree","add","-B",`solo/${e}`,o];return r?i.push(r):i.push("HEAD"),await an("git",i,{cwd:t,encoding:"utf8"}),o}async function xl(t){try{await an("git",["add","-A"],{cwd:t});let{stdout:e}=await an("git",["diff","--cached","--stat"],{cwd:t,encoding:"utf8"});return e.trim()}catch{return""}}async function Ah(t,e){try{await an("git",["worktree","remove","--force",e],{cwd:t,encoding:"utf8"})}catch{try{await $_(e,{recursive:!0,force:!0})}catch{}}}async function xh(t,e){let{stdout:r}=await an("git",["merge","--no-ff",e,"-m",`solo: merge ${e}`],{cwd:t,encoding:"utf8"});return r.trim()}var Ns=class{constructor(e,r,n,o={}){this.processManager=e;this.acpDetector=r;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;async create(e){let{name:r,cwd:n,instances:o,tasks:s,budget:i}=e;if(o.length===0)throw new Error("Product requires at least 1 instance");if(s.length===0)throw new Error("Product requires at least 1 task");let a=new Set(o.map(b=>b.name));for(let b of s)if(!a.has(b.assignee))throw new Error(`Task "${b.taskId}" references unknown instance "${b.assignee}"`);let c=`product-${U_().slice(0,8)}`,l=s.map(b=>({id:b.taskId,kind:"agent",params:{agentId:b.assignee,prompt:b.prompt},dependsOn:b.dependsOn})),d=new Qt(l),u=new Jn(i),p=new Qn({onCheckpoint:(b,S)=>this.callbacks.onCheckpointed?.(b,S),getState:()=>{let b=this.sessions.get(c);return b?this.buildPersistedState(b):null},log:this.callbacks.log}),m=await Zn(n),g=o.map((b,S)=>({instanceId:`${c}:${b.name}:${S}`,name:b.name,agentId:b.agentId,state:"idle"})),f={productId:c,name:r,cwd:n,phase:"active",instances:g,dag:d,budget:u,checkpoint:p,createdAt:new Date().toISOString(),gitRoot:m};this.sessions.set(c,f),p.start(n),this.callbacks.log?.info(`[product] created ${c} "${r}" with ${o.length} instances, ${s.length} tasks`);let h=s.map(b=>({id:b.taskId,label:b.taskId,deps:b.dependsOn??[]})),v=[];for(let b of s)if(b.dependsOn)for(let S of b.dependsOn)v.push({from:S,to:b.taskId});return this.callbacks.onDagTopology?.(c,h,v),setTimeout(()=>this.scheduleNext(f),0),c}async resume(e,r){let n=await Al(e,r);if(!n)throw new Error(`Product ${e} not found on disk`);let o=new Qt(n.tasks);o.restore(n.tasks);let s=new Jn({maxTotalTokens:n.budget.maxTotalTokens,maxDuration:n.budget.maxDuration});s.restore(n.budget);let i=new Qn({onCheckpoint:(d,u)=>this.callbacks.onCheckpointed?.(d,u),getState:()=>{let d=this.sessions.get(e);return d?this.buildPersistedState(d):null},log:this.callbacks.log}),a=await Zn(n.cwd),c=n.instances.map((d,u)=>({instanceId:`${e}:${d.name}:${u}`,name:d.name,agentId:d.agentId,state:"idle"})),l={productId:n.productId,name:n.name,cwd:n.cwd,phase:"active",instances:c,dag:o,budget:s,checkpoint:i,createdAt:n.createdAt,gitRoot:a};this.sessions.set(e,l),i.start(n.cwd),this.callbacks.log?.info(`[product] resumed ${e}`),this.scheduleNext(l)}async pause(e){let r=this.sessions.get(e);if(!r)throw new Error(`Product ${e} not found`);if(r.phase!=="active")throw new Error(`Product ${e} is not active`);r.phase="paused",r.dag.pauseAll();for(let n of r.instances)if(n.state==="running"&&n.memberId){try{this.processManager.kill(n.memberId)}catch{}n.state="paused"}await r.checkpoint.checkpoint(this.buildPersistedState(r)),r.checkpoint.stop(),this.callbacks.log?.info(`[product] paused ${e}`)}async checkpoint(e){let r=this.sessions.get(e);if(!r)throw new Error(`Product ${e} not found`);await r.checkpoint.checkpoint(this.buildPersistedState(r))}async delete(e){let r=this.sessions.get(e);if(!r)throw new Error(`Product ${e} not found`);if(r.phase==="active"){r.phase="failed",r.dag.pauseAll();for(let n of r.instances)if(n.state==="running"&&n.memberId){try{this.processManager.kill(n.memberId)}catch{}n.state="failed"}}r.checkpoint.stop(),this.sessions.delete(e),this.callbacks.log?.info(`[product] deleted ${e}`)}async rollback(e,r){let n=this.sessions.get(e);if(!n)throw new Error(`Product ${e} not found`);let o=n.cwd;await this.delete(e),await this.resume(e,o),this.callbacks.log?.info(`[product] rolled back ${e} to checkpoint ${r}`)}getStatus(e){let r=this.sessions.get(e);return r?{productId:r.productId,name:r.name,phase:r.phase,instances:r.instances.map(n=>{let s=(n.memberId?this.processManager.getUsageTracker(n.memberId):null)?.getUsage();return{instanceId:n.instanceId,name:n.name,agentId:n.agentId,state:n.state,worktreePath:n.worktreePath,usage:s&&(s.inputTokens>0||s.outputTokens>0)?{inputTokens:s.inputTokens,outputTokens:s.outputTokens}:void 0}}),tasks:r.dag.getAllNodes().map(n=>({taskId:n.id,assignee:n.params.agentId,status:n.status,result:n.output,error:n.error,startedAt:n.startedAt?new Date(n.startedAt).toISOString():void 0,completedAt:n.completedAt?new Date(n.completedAt).toISOString():void 0})),budget:r.budget.getBudget(),lastCheckpointAt:new Date(r.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}:null}async list(e){let r=[];for(let o of this.sessions.values()){let s=o.dag.getAllNodes();r.push({productId:o.productId,name:o.name,phase:o.phase,instanceCount:o.instances.length,taskCount:s.length,completedTasks:s.filter(i=>i.status==="completed").length,createdAt:o.createdAt,lastCheckpointAt:new Date(o.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()})}let n=await wh(e);for(let o of n)this.sessions.has(o.productId)||r.push({productId:o.productId,name:o.name,phase:o.phase,instanceCount:o.instances.length,taskCount:o.tasks.length,completedTasks:o.tasks.filter(s=>s.status==="completed").length,createdAt:o.createdAt,lastCheckpointAt:o.lastCheckpointAt});return r}scheduleNext(e){if(e.phase!=="active")return;let r=e.budget.check();if(r.action==="exceeded"){this.callbacks.log?.warn(`[product] ${e.productId} budget exceeded, auto-pausing`),this.pause(e.productId).catch(o=>{this.callbacks.log?.warn(`[product] auto-pause failed: ${o instanceof Error?o.message:String(o)}`)});return}if(r.action==="warning"&&this.callbacks.onBudgetWarning?.(e.productId,r.usedTokens,r.maxTotalTokens,r.percentage),e.dag.isFinished()){this.finishProduct(e);return}let n=e.dag.getReadyNodes();for(let o of n)this.dispatchTask(e,o)}dispatchTask(e,r){let n=e.instances.find(o=>o.name===r.params.agentId);if(!n){e.dag.markFailed(r.id,`No instance found for assignee "${r.params.agentId}"`),this.callbacks.onTaskFailed?.(e.productId,r.id,`No instance for "${r.params.agentId}"`),this.scheduleNext(e);return}e.dag.markRunning(r.id),n.state="running",this.callbacks.onTaskStarted?.(e.productId,r.id,r.params.agentId),this.callbacks.log?.info(`[product] ${e.productId} dispatching task ${r.id} to ${r.params.agentId}`),this.runTask(e,n,r).catch(o=>{this.callbacks.log?.warn(`[product] task dispatch error: ${o instanceof Error?o.message:String(o)}`)})}async runTask(e,r,n){let o=`${e.productId}:${r.name}:${n.id}`;r.memberId=o;try{let s=this.acpDetector.buildExternalDescriptor(r.agentId);if(!s)throw new Error(`Agent ${r.agentId} is not available`);let i=e.cwd;if(e.gitRoot){let d=`${e.productId}-${r.name}-${n.id}`;try{i=await Ds(e.gitRoot,d),r.worktreePath=i}catch{this.callbacks.log?.warn(`[product] worktree creation failed for ${n.id}, using project cwd`)}}await this.processManager.spawn({memberId:o,name:`product-${r.name}`,cwd:i,prompt:n.params.prompt,external:s});let a=await this.processManager.sendTask(o,n.params.prompt),c=typeof a=="string"?a:JSON.stringify(a),l=this.processManager.getUsageTracker(o);if(l?.hasData()){let d=l.getUsage();e.budget.addUsage(d.inputTokens,d.outputTokens);let u=e.budget.getBudget();this.callbacks.onBudgetUpdate?.(e.productId,u.usedTokens,0,u.elapsed,u.maxTotalTokens)}e.dag.markCompleted(n.id,{output:c}),r.state="completed",this.callbacks.onTaskCompleted?.(e.productId,n.id,c);try{this.processManager.kill(o)}catch{}this.processManager.remove(o)}catch(s){let i=s instanceof Error?s.message:String(s);e.dag.markFailed(n.id,i),r.state="failed",this.callbacks.onTaskFailed?.(e.productId,n.id,i);try{this.processManager.kill(o)}catch{}try{this.processManager.remove(o)}catch{}}try{await e.checkpoint.checkpoint(this.buildPersistedState(e))}catch(s){this.callbacks.log?.warn(`[product] checkpoint failed: ${s instanceof Error?s.message:String(s)}`)}this.scheduleNext(e)}finishProduct(e){if(e.dag.isAllCompleted()){e.phase="completed";let r=e.dag.getAllNodes(),n=`Product "${e.name}" completed: ${r.length} tasks all done.`;this.callbacks.onCompleted?.(e.productId,n)}else{e.phase="failed";let n=e.dag.getAllNodes().filter(i=>i.status==="failed").length,o=e.dag.getBlockedNodes().length,s=`Product "${e.name}" finished with ${n} failed, ${o} blocked tasks.`;this.callbacks.onCompleted?.(e.productId,s)}e.checkpoint.stop(),e.checkpoint.checkpoint(this.buildPersistedState(e)).catch(r=>{this.callbacks.log?.warn(`[product] final checkpoint failed: ${r instanceof Error?r.message:String(r)}`)}),this.callbacks.log?.info(`[product] ${e.productId} finished (phase=${e.phase})`)}buildPersistedState(e){return{productId:e.productId,name:e.name,phase:e.phase,cwd:e.cwd,instances:e.instances.map(r=>({name:r.name,role:"",agentId:r.agentId})),tasks:e.dag.serialize(),budget:e.budget.serialize(),createdAt:e.createdAt,lastCheckpointAt:new Date(e.checkpoint.getLastCheckpointAt()||Date.now()).toISOString()}}};import{randomUUID as Ph}from"node:crypto";function F_(t,e){let r=e?`
|
|
329
329
|
|
|
330
330
|
Budget constraints: ${e.maxTotalTokens?`max ${e.maxTotalTokens} total tokens`:""}${e.maxDuration?` / max ${Math.round(e.maxDuration/6e4)} minutes`:""}`:"";return`You are a team leader agent managing a software development project.
|
|
331
331
|
|
|
@@ -394,18 +394,18 @@ If no action needed, just respond with a progress update message to the user.`,e
|
|
|
394
394
|
`),warn:r=>process.stderr.write(`${r}
|
|
395
395
|
`)},onTaskStarted:(r,n,o)=>{this.sendNotification("product.taskStarted",{productId:r,taskId:n,assignee:o})},onTaskCompleted:(r,n,o)=>{this.sendNotification("product.taskCompleted",{productId:r,taskId:n,result:o})},onTaskFailed:(r,n,o)=>{this.sendNotification("product.taskFailed",{productId:r,taskId:n,error:o})},onCheckpointed:(r,n)=>{this.sendNotification("product.checkpointed",{productId:r,timestamp:n})},onBudgetWarning:(r,n,o,s)=>{this.sendNotification("product.budgetWarning",{productId:r,usedTokens:n,maxTotalTokens:o,percentage:s})},onCompleted:(r,n)=>{this.sendNotification("product.completed",{productId:r,summary:n})},onDagTopology:(r,n,o)=>{this.sendNotification("product.dagTopology",{productId:r,nodes:n,edges:o})},onBudgetUpdate:(r,n,o,s,i)=>{this.sendNotification("product.budgetUpdate",{productId:r,inputTokens:n,outputTokens:o,elapsed:s,maxTotalTokens:i})},onTaskOutputDelta:(r,n,o)=>{this.sendNotification("product.taskOutput",{productId:r,taskId:n,text:o})}};this.productOrchestrator=new Ns(t,this.acpDetector,this.agentConfigStore,e),this.productProcessManager=t}return this.productOrchestrator}function _r(){return this.productPlanner||(ye.call(this),this.productPlanner=new Ls(this.productProcessManager,this.acpDetector,this.agentConfigStore,{log:{info:t=>process.stderr.write(`${t}
|
|
396
396
|
`),warn:t=>process.stderr.write(`${t}
|
|
397
|
-
`)},onPlanReady:(t,e)=>{this.sendNotification("product.planReady",{productId:t,plan:e})},onPlanFailed:(t,e)=>{this.sendNotification("product.planFailed",{productId:t,error:e})},onPlanningDelta:(t,e)=>{this.sendNotification("product.planningDelta",{productId:t,text:e})}})),this.productPlanner}async function Eh(t){try{let e=t.params;if(!e?.goal||!e?.cwd||!e?.leaderAgentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"goal, cwd, and leaderAgentId are required."});return}let n=await _r.call(this).plan(e);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function _h(t){try{let e=t.params;if(!e?.productId||!e?.instances||!e?.tasks){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId, instances, and tasks are required."});return}let r=_r.call(this),n=await r.confirm(e),o=r.getSession(e.productId);o&&await ye.call(this).create({name:o.plan?.name??o.goal.slice(0,50),cwd:o.cwd,instances:e.instances,tasks:e.tasks,budget:e.budget}),t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Mh(t){try{let e=t.params;if(!e?.productId||!e?.content){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId and content are required."});return}let n=await _r.call(this).message(e.productId,e.content);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Dh(t){try{let e=t.params,r;if(e?.name&&e?.cwd&&e?.instances&&e?.tasks)r=e;else if(e?.tasks&&Array.isArray(e.tasks)){let i=e.config?.workdir??this.getActiveProjectRoot(),a=e.tasks.map(c=>({taskId:String(c.id??c.taskId??`task_${Math.random().toString(36).slice(2,8)}`),assignee:String(c.assignee??"default"),prompt:String(c.description??c.prompt??""),dependsOn:c.dependsOn??[]}));r={name:String(e.name??`product_${Date.now()}`),cwd:i,instances:[{name:"default",role:"executor",agentId:"self"}],tasks:a},e.budget&&(r.budget=e.budget)}else{t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"tasks is required. Provide either {name, cwd, instances, tasks} or simplified {tasks, config}."});return}if(!r.projectId){let s=oe();s&&(r.projectId=s.id)}let o=await ye.call(this).create(r);t.id!==void 0&&this.sendResponse(t.id,{productId:o})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Nh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).resume(e.productId,this.getActiveProjectRoot()),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Lh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).pause(e.productId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Oh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).checkpoint(e.productId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function jh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}let n=ye.call(this).getStatus(e.productId);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function $h(t){try{let r=await ye.call(this).list(this.getActiveProjectRoot());t.id!==void 0&&this.sendResponse(t.id,r)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Uh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).delete(e.productId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Fh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).delete(e.productId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Hh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).rollback(e.productId,e.checkpoint??"latest"),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}import*as uy from"node:path";import{randomUUID as py}from"node:crypto";D();function cn(t,e){return e?{json:t,binary:e}:{json:t}}function Bh(t){let e={};for(let r of Object.keys(t).sort())e[r]=t[r].map(n=>({json:n.json,binary:n.binary?Object.fromEntries(Object.keys(n.binary).sort().map(o=>[o,n.binary[o].ref])):void 0}));return Cl(e)}function Cl(t){return JSON.stringify(Pl(t))}function Pl(t){if(Array.isArray(t))return t.map(Pl);if(t&&typeof t=="object"){let e={};for(let r of Object.keys(t).sort())e[r]=Pl(t[r]);return e}return t}var Gh=new Set(["__proto__","prototype","constructor"]);function qh(t,e){let r=B_(t),n=new _l(r,t),o=n.parseExpression();return n.expectEnd(),ln(o,e)}function Dl(t,e){let r=t.match(/^\s*\{\{([\s\S]*)\}\}\s*$/);return r?qh(r[1],e):t.includes("{{")?t.replace(/\{\{([\s\S]*?)\}\}/g,(n,o)=>{let s=qh(o,e);if(s==null)throw new Error(`Expression "{{${o.trim()}}}" resolved to ${s} in string interpolation`);return typeof s=="object"?JSON.stringify(s):String(s)}):t}function Kh(t,e){return El(t,e)}function El(t,e){if(typeof t=="string")return Dl(t,e);if(Array.isArray(t))return t.map(r=>El(r,e));if(t&&typeof t=="object"){let r={};for(let[n,o]of Object.entries(t))r[n]=El(o,e);return r}return t}function B_(t){let e=[],r=0,n=s=>/[A-Za-z_]/.test(s),o=s=>/[A-Za-z0-9_]/.test(s);for(;r<t.length;){let s=t[r];if(/\s/.test(s)){r++;continue}if(s==="$"){r++;let i="";for(;r<t.length&&o(t[r]);)i+=t[r++];if(!i)throw new Error('Bare "$" is not a valid expression');e.push({t:"dollar",v:i});continue}if(n(s)){let i="";for(;r<t.length&&o(t[r]);)i+=t[r++];e.push({t:"id",v:i});continue}if(/[0-9]/.test(s)||s==="-"&&/[0-9]/.test(t[r+1]??"")){let i=t[r++];for(;r<t.length&&/[0-9.]/.test(t[r]);)i+=t[r++];e.push({t:"num",v:i});continue}if(s==='"'||s==="'"){let i=s;r++;let a="";for(;r<t.length&&t[r]!==i;)t[r]==="\\"&&r+1<t.length?(a+=t[r+1],r+=2):a+=t[r++];if(t[r]!==i)throw new Error("Unterminated string literal in expression");r++,e.push({t:"str",v:a});continue}if(".[](),".includes(s)){e.push({t:"punc",v:s}),r++;continue}throw new Error(`Unexpected character "${s}" in expression`)}return e}var _l=class{constructor(e,r){this.toks=e;this.src=r}toks;src;pos=0;parseExpression(){return this.parseAccessors(this.parseAtom())}peek(){return this.toks[this.pos]}next(){return this.toks[this.pos++]}expectEnd(){if(this.pos!==this.toks.length)throw new Error(`Unexpected trailing tokens in expression "${this.src.trim()}"`)}parseAtom(){let e=this.peek();if(!e)throw new Error("Empty expression");if(e.t==="dollar")return this.next(),{type:"root",name:e.v};if(e.t==="num")return this.next(),{type:"lit",value:Number(e.v)};if(e.t==="str")return this.next(),{type:"lit",value:e.v};if(e.t==="id"){if(e.v==="true")return this.next(),{type:"lit",value:!0};if(e.v==="false")return this.next(),{type:"lit",value:!1};if(e.v==="null")return this.next(),{type:"lit",value:null};if(this.next(),this.peek()?.t==="punc"&&this.peek().v==="("){let r=this.parseArgs();return{type:"func",name:e.v,args:r}}throw new Error(`Bare identifier "${e.v}" is not allowed (only whitelist function calls)`)}if(e.t==="punc"&&e.v==="("){this.next();let r=this.parseExpression();return this.expectPunc(")"),r}throw new Error(`Unexpected token "${e.v}" in expression`)}parseAccessors(e){let r=e;for(;;){let n=this.peek();if(!n||n.t!=="punc")break;if(n.v==="."){this.next();let o=this.next();if(!o||o.t!=="id"&&o.t!=="num")throw new Error('Expected property name after "."');r={type:"prop",target:r,key:o.v}}else if(n.v==="["){this.next();let o=this.next(),s;if(o.t==="num")s=Number(o.v);else if(o.t==="str")s=o.v;else throw new Error("Index must be a number or string literal");this.expectPunc("]"),r={type:"index",target:r,key:s}}else if(n.v==="("){let o=this.parseArgs();r={type:"call",target:r,args:o}}else break}return r}parseArgs(){this.expectPunc("(");let e=[];if(this.peek()?.t==="punc"&&this.peek().v===")")return this.next(),e;for(;;){e.push(this.parseExpression());let r=this.next();if(!r)throw new Error("Unterminated argument list");if(r.t==="punc"&&r.v===")")break;if(!(r.t==="punc"&&r.v===","))throw new Error('Expected "," or ")" in argument list')}return e}expectPunc(e){let r=this.next();if(!r||r.t!=="punc"||r.v!==e)throw new Error(`Expected "${e}" in expression`)}},zh=Symbol("nodeAccessor");function ln(t,e){switch(t.type){case"lit":return t.value;case"root":return q_(t.name,e);case"func":return W_(t.name,t.args.map(r=>ln(r,e)));case"prop":return Wh(ln(t.target,e),t.key);case"index":return Wh(ln(t.target,e),t.key);case"call":{if(ln(t.target,e)===zh){let n=t.args.map(s=>ln(s,e));if(n.length!==1||typeof n[0]!="string")throw new Error("$node(...) takes exactly one string argument");let o=e.nodes?.[n[0]];if(!o)throw new Error(`$node("${n[0]}") not found (not completed or unknown)`);return o}throw new Error("Only $node(...) is callable in this position")}}}function q_(t,e){switch(t){case"input":return e.input??{};case"json":return e.json??{};case"vars":return e.vars??{};case"trigger":return e.trigger??{};case"now":return(e.now?e.now():new Date).toISOString();case"node":return zh;default:throw new Error(`Unknown context root "$${t}" (allowed: $input $json $node $now $vars $trigger)`)}}function Wh(t,e){if(typeof e=="string"&&Gh.has(e))throw new Error(`Access to "${e}" is forbidden`);if(t==null)throw new Error(`Cannot read "${e}" of ${t}`);if(typeof e=="number"){if(!Array.isArray(t))throw new Error(`Cannot index non-array with [${e}]`);return t[e]}return t[e]}function W_(t,e){switch(t){case"len":{let r=e[0];if(typeof r=="string"||Array.isArray(r))return r.length;if(r&&typeof r=="object")return Object.keys(r).length;throw new Error(`len() expects string/array/object, got ${typeof r}`)}case"upper":return String(js(e,0,"upper")).toUpperCase();case"lower":return String(js(e,0,"lower")).toLowerCase();case"default":return e[0]===null||e[0]===void 0?e[1]:e[0];case"jsonpath":return K_(e[0],String(js(e,1,"jsonpath")));case"date":return z_(e);case"eq":return Ml(e[0],e[1]);case"ne":return!Ml(e[0],e[1]);case"gt":return Os(e[0],e[1])>0;case"gte":return Os(e[0],e[1])>=0;case"lt":return Os(e[0],e[1])<0;case"lte":return Os(e[0],e[1])<=0;case"not":return!Il(js(e,0,"not"));case"and":return e.every(Il);case"or":return e.some(Il);case"contains":return G_(e[0],e[1]);default:throw new Error(`Unknown function "${t}()" (whitelist: len upper lower default jsonpath date eq ne gt gte lt lte not and or contains)`)}}function Il(t){return!!t}function Ml(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):!1}function Os(t,e){if(typeof t=="number"&&typeof e=="number")return t-e;if(typeof t=="string"&&typeof e=="string")return t<e?-1:t>e?1:0;throw new Error(`Cannot compare ${typeof t} with ${typeof e}`)}function G_(t,e){if(typeof t=="string")return t.includes(String(e));if(Array.isArray(t))return t.some(r=>Ml(r,e));throw new Error("contains() expects string/array as first argument")}function js(t,e,r){if(t.length<=e||t[e]===void 0)throw new Error(`${r}() missing required argument #${e+1}`);return t[e]}function K_(t,e){let r=e.match(/[^.[\]]+/g)??[],n=t;for(let o of r){if(Gh.has(o))throw new Error(`jsonpath segment "${o}" is forbidden`);if(n==null)return;let s=/^\d+$/.test(o)?Number(o):o;n=n[s]}return n}function z_(t){let e=t.length===0?new Date:new Date(t[0]);if(Number.isNaN(e.getTime()))throw new Error(`date() received an invalid date: ${String(t[0])}`);if(t.length<2)return e.toISOString();let r=String(t[1]),n=o=>String(o).padStart(2,"0");return r.replace(/YYYY/g,String(e.getUTCFullYear())).replace(/MM/g,n(e.getUTCMonth()+1)).replace(/DD/g,n(e.getUTCDate())).replace(/HH/g,n(e.getUTCHours())).replace(/mm/g,n(e.getUTCMinutes())).replace(/ss/g,n(e.getUTCSeconds()))}var V_=(t,e)=>({outputs:{default:[{json:e.json&&typeof e.json=="object"&&!Array.isArray(e.json)?e.json:{value:e.json??e.value??null}}]}}),X_=t=>({outputs:{default:t.default??[]}}),Y_=t=>{let e=[];for(let r of Object.keys(t))e.push(...t[r]);return{outputs:{default:e}}},J_=(t,e)=>{let n=!!e.condition?"true":"false",o=t.default??[],s={true:[],false:[]};return s[n]=o,{outputs:s,firedPorts:[n]}},Q_=(t,e,r)=>({outputs:{default:[{json:r.trigger??(e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{})}]}}),Vh={set:V_,passthrough:X_,merge:Y_,if:J_,trigger:Q_};var dn=class{executors=new Map;constructor(e=!0){if(e)for(let[r,n]of Object.entries(Vh))this.executors.set(r,n)}register(e,r){if(this.executors.has(e))throw new Error(`NodeExecutor for kind "${e}" already registered`);this.executors.set(e,r)}override(e,r){if(!this.executors.has(e))throw new Error(`Cannot override unregistered kind "${e}"`);this.executors.set(e,r)}has(e){return this.executors.has(e)}get(e){let r=this.executors.get(e);if(!r)throw new Error(`No NodeExecutor registered for kind "${e}"`);return r}kinds(){return[...this.executors.keys()]}};function eo(t,e){if(!t)throw new Error(`Node kind "${e}" requires a host (ExecutorHost) but none was injected. Provide one via WorkflowRuntimeOptions.host.`);return t}function un(t,e,r){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Node kind "${r}" requires string param "${e}"`);return n}function Xh(t,e){let r=t[e];if(r==null)return{};if(typeof r!="object"||Array.isArray(r))throw new Error(`Param "${e}" must be an object`);return r}var Z_=async(t,e,r)=>({outputs:{default:await eo(r.host,"agent").runAgent({agentId:typeof e.agentId=="string"?e.agentId:void 0,prompt:un(e,"prompt","agent"),input:t.default??[],signal:r.signal})}}),eM=async(t,e,r)=>({outputs:{default:await eo(r.host,"tool").invokeTool({tool:un(e,"tool","tool"),args:Xh(e,"args"),input:t.default??[],signal:r.signal})}}),tM=async(t,e,r)=>{let n=eo(r.host,"http"),o=typeof e.method=="string"?e.method:"GET";return{outputs:{default:await n.httpRequest({method:o,url:un(e,"url","http"),headers:e.headers,body:e.body,signal:r.signal})}}},rM=async(t,e,r)=>({outputs:{default:await eo(r.host,"mcp").invokeMcp({server:un(e,"server","mcp"),tool:un(e,"tool","mcp"),args:Xh(e,"args"),signal:r.signal})}}),nM=async(t,e,r)=>({outputs:{default:await eo(r.host,"channel").sendChannel({channel:un(e,"channel","channel"),target:typeof e.target=="string"?e.target:void 0,payload:e.payload??t.default?.[0]?.json??{},input:t.default??[],signal:r.signal})}}),to={agent:Z_,tool:eM,http:tM,mcp:rM,channel:nM},I2=Object.keys(to);var pn=class extends Error{constructor(r){super(r?`Workflow paused at "${r}"`:"Workflow paused");this.atNodeId=r;this.name="WorkflowPauseSignal"}atNodeId},$s=class{constructor(e,r={}){this.def=e;if(this.registry=r.registry??new dn,this.gate=r.gate,this.now=r.now??(()=>new Date),this.trigger=r.trigger,this.log=r.log,this.host=r.host,this.signal=r.signal,this.checkpoint=r.checkpoint,this.host)for(let[n,o]of Object.entries(to))this.registry.has(n)||this.registry.register(n,o);for(let n of e.nodes)this.nodeDefs.set(n.id,n);for(let n of e.edges)n.loopBack&&this.loopBackOf.set(n.from,n.to)}def;registry;gate;now;trigger;log;host;signal;checkpoint;dag;nodeDefs=new Map;nodeOutputs=new Map;cache=new Map;loopBackOf=new Map;pauseRequested=!1;checkpointLoaded=!1;setNodeParams(e,r){let n=this.nodeDefs.get(e);if(!n)throw new Error(`Unknown node "${e}"`);n.params={...n.params??{},...r}}pause(){this.pauseRequested=!0}extendBudget(e){if(!this.gate?.extend)throw new Error("WorkflowRuntime has no extensible budget gate to raise");this.gate.extend(e)}async run(){await this.loadCheckpoint(),this.dag=this.buildDag(),this.nodeOutputs.clear(),this.pauseRequested=!1;let e=new Set,r;try{let s=0;for(;!this.dag.isFinished();){if(++s>1e5)throw new Error("WorkflowRuntime did not converge");let i=this.dag.getReadyNodes();if(i.length===0)break;for(let a of i)await this.executeNode(a,e)}}catch(s){if(s instanceof pn)r=s.atNodeId;else throw s}let n={};for(let[s,i]of this.nodeOutputs)n[s]=i;let o=r?"paused":this.dag.isAllCompleted()?"completed":"failed";return o==="completed"&&this.checkpoint&&await this.checkpoint.clear(),{status:o,outputs:n,executed:e,progress:this.dag.getProgress(),pausedAt:r}}async loadCheckpoint(){if(!this.checkpoint||this.checkpointLoaded)return;this.checkpointLoaded=!0;let e=await this.checkpoint.load();if(e)for(let r of e.entries)this.cache.set(r.key,r.result)}async persistCheckpoint(){if(!this.checkpoint)return;let e=[...this.cache.entries()].map(([r,n])=>({key:r,result:n}));await this.checkpoint.persist(e)}async executeNode(e,r){if(this.pauseRequested)throw new pn(e.id);if(e.kind==="loop"){this.enterLoop(e);return}let n=this.collectInputs(e.id),o=this.buildExprContext(n),s=this.nodeDefs.get(e.id)?.params??{},i=Kh(s,o),a=this.cacheKey(e.kind,i,n,e.runIndex),c=this.cache.get(a);if(c)this.dag.markRunning(e.id);else{this.gate?.check(e.id,e.kind),this.dag.markRunning(e.id);let d={nodeId:e.id,kind:e.kind,runIndex:e.runIndex,vars:this.def.vars??{},trigger:this.trigger,now:this.now,log:this.log,host:this.host,signal:this.signal};c=await this.registry.get(e.kind)(n,i,d),this.cache.set(a,c),r.add(e.id),await this.persistCheckpoint()}this.nodeOutputs.set(e.id,c.outputs),this.dag.markCompleted(e.id,{output:c.outputs,firedPorts:c.firedPorts});let l=this.loopBackOf.get(e.id);l&&this.decideLoopBack(l)}enterLoop(e){this.dag.markRunning(e.id);let r={loop:[{json:{iteration:e.iteration??0}}],done:[]};this.nodeOutputs.set(e.id,r),this.dag.markCompleted(e.id,{output:r,firedPorts:["loop"]})}decideLoopBack(e){let r=this.evalLoopCondition(e);this.dag.decideLoop(e,r);let n=this.dag.getNode(e),o=n.firedPorts??[];this.nodeOutputs.set(e,{loop:o.includes("loop")?[{json:{iteration:n.iteration??0}}]:[],done:o.includes("done")?[{json:{iteration:n.iteration??0}}]:[]})}evalLoopCondition(e){let n=this.nodeDefs.get(e)?.params?.condition;if(n==null||n==="")return!0;let o=this.buildExprContext({});return!!(typeof n=="string"?Dl(n,o):n)}collectInputs(e){let r={};for(let n of this.def.edges){if(n.to!==e||n.loopBack)continue;let o=n.fromPort??"default",s=n.toPort??"default",i=this.nodeOutputs.get(n.from);if(!i)continue;let a=i[o];a&&(r[s]??=[]).push(...a)}return r}buildExprContext(e){let r={};for(let[n,o]of this.nodeOutputs)r[n]={output:o};return{input:e,json:e.default?.[0]?.json??{},nodes:r,vars:this.def.vars??{},trigger:this.trigger,now:this.now}}cacheKey(e,r,n,o){return Cl([e,r,Bh(n),o])}buildDag(){let e=this.def.nodes.map(n=>({id:n.id,kind:n.kind,params:n.params??{},outPorts:n.outPorts??oM(n.kind),joinPolicy:n.joinPolicy??"all",maxIterations:n.maxIterations})),r=new Jt(e);for(let n of this.def.edges)n.loopBack||r.addEdge({from:n.from,to:n.to,fromPort:n.fromPort??"default"});for(let n of this.def.edges)n.loopBack&&r.addEdge({from:n.from,to:n.to,loopBack:!0});return r}};function oM(t){return t==="if"?["true","false"]:t==="loop"?["loop","done"]:["default"]}var sM=new Set(["agent","tool","http","mcp","channel","im"]),Nl=class extends Error{constructor(r,n,o){super(`Permission denied: node "${r}" (kind "${n}") may not run under unattended trigger "${o}". Authorize it by adding "${n}" to allowUnattendedKinds.`);this.nodeId=r;this.kind=n;this.trigger=o;this.name="WorkflowPermissionDenied"}nodeId;kind;trigger},Us=class extends pn{constructor(r,n,o){super(r);this.reason=n;this.limit=o;this.name="WorkflowBudgetExceeded",this.message=`Budget exceeded (${n} limit ${o}) before node "${r}"`}reason;limit},Fs=class{trigger;maxNodeExecutions;maxDurationMs;allow;now;executions=0;startedAt=-1;constructor(e){if(!Number.isInteger(e.maxNodeExecutions)||e.maxNodeExecutions<=0)throw new Error(`BudgetPermissionGate: maxNodeExecutions must be a positive integer, got ${e.maxNodeExecutions}`);if(e.maxDurationMs!==void 0&&!(e.maxDurationMs>0))throw new Error(`BudgetPermissionGate: maxDurationMs must be greater than 0 when provided, got ${e.maxDurationMs}`);this.trigger=e.trigger,this.maxNodeExecutions=e.maxNodeExecutions,this.maxDurationMs=e.maxDurationMs,this.allow=new Set(e.allowUnattendedKinds??[]),this.now=e.now??(()=>Date.now())}get unattended(){return this.trigger!=="manual"}check(e,r){if(this.unattended&&sM.has(r)&&!this.allow.has(r))throw new Nl(e,r,this.trigger);if(this.startedAt<0&&(this.startedAt=this.now()),this.maxDurationMs!==void 0&&this.now()-this.startedAt>=this.maxDurationMs)throw new Us(e,"duration",this.maxDurationMs);if(this.executions>=this.maxNodeExecutions)throw new Us(e,"executions",this.maxNodeExecutions);this.executions++}extend(e){if(e.executions!==void 0){if(!Number.isInteger(e.executions)||e.executions<=0)throw new Error(`BudgetPermissionGate.extend: executions delta must be a positive integer, got ${e.executions}`);this.maxNodeExecutions+=e.executions}if(e.durationMs!==void 0){if(!(e.durationMs>0))throw new Error(`BudgetPermissionGate.extend: durationMs delta must be greater than 0, got ${e.durationMs}`);if(this.maxDurationMs===void 0)throw new Error("BudgetPermissionGate.extend: cannot extend duration on a gate with no duration cap");this.maxDurationMs+=e.durationMs}}};function Qh(t){switch(t.type){case"manual":return[];case"schedule":return Ol(t.cron);case"im-message":return cM(t.channel,t.match);case"webhook":return lM(t.path);default:return[`unknown trigger type: ${JSON.stringify(t)}`]}}var Yh=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"],Jh=["SUN","MON","TUE","WED","THU","FRI","SAT"];function Ol(t){if(typeof t!="string"||t.trim()==="")return["schedule.cron must be a non-empty string"];let e=t.trim().split(/\s+/);if(e.length!==5&&e.length!==6)return[`schedule.cron must have 5 or 6 fields, got ${e.length}: "${t}"`];let n=e.length===6?[{label:"second",min:0,max:59},{label:"minute",min:0,max:59},{label:"hour",min:0,max:23},{label:"day-of-month",min:1,max:31},{label:"month",min:1,max:12,names:Yh},{label:"day-of-week",min:0,max:7,names:Jh}]:[{label:"minute",min:0,max:59},{label:"hour",min:0,max:23},{label:"day-of-month",min:1,max:31},{label:"month",min:1,max:12,names:Yh},{label:"day-of-week",min:0,max:7,names:Jh}],o=[];for(let s=0;s<n.length;s++){let i=iM(e[s],n[s]);i&&o.push(`schedule.cron ${i}`)}return o}function iM(t,e){for(let r of t.split(",")){let n=aM(r,e);if(n)return n}}function aM(t,e){if(t==="")return`${e.label} has an empty list element`;let r=t,n,o=t.indexOf("/");if(o!==-1&&(r=t.slice(0,o),n=t.slice(o+1),!/^\d+$/.test(n)||Number(n)<=0))return`${e.label} has an invalid step "/${n}"`;if(r==="*")return;let s=r.indexOf("-");if(s!==-1){let a=Ll(r.slice(0,s),e),c=Ll(r.slice(s+1),e);return a===void 0||c===void 0?`${e.label} has an invalid range "${r}"`:a>c?`${e.label} range "${r}" is descending`:void 0}if(r===""&&n!==void 0)return`${e.label} step "${t}" needs a base ("*" or a range)`;if(Ll(r,e)===void 0)return`${e.label} value "${r}" is out of range ${e.min}-${e.max}`}function Ll(t,e){let r;if(/^\d+$/.test(t))r=Number(t);else if(e.names){let n=e.names.indexOf(t.toUpperCase());if(n===-1)return;r=e.label==="month"?n+1:n}else return;if(!(r<e.min||r>e.max))return r}function cM(t,e){let r=[];if((typeof t!="string"||t.trim()==="")&&r.push("im-message.channel must be a non-empty string"),e!==void 0)if(typeof e!="string")r.push("im-message.match must be a string regex");else try{new RegExp(e)}catch(n){r.push(`im-message.match is not a valid regex: ${n.message}`)}return r}function lM(t){return typeof t!="string"||t===""?["webhook.path must be a non-empty string"]:t.startsWith("/")?/\s/.test(t)?[`webhook.path must not contain whitespace: "${t}"`]:t.includes("..")?[`webhook.path must not contain "..": "${t}"`]:/^\/[A-Za-z0-9\-._~/]*$/.test(t)?[]:[`webhook.path contains illegal characters: "${t}"`]:[`webhook.path must start with "/": "${t}"`]}var lr=class extends Error{constructor(r){super(`Patch rejected: ${r.join("; ")}`);this.errors=r;this.name="PatchError"}errors};function Zh(t,e){let r=[],n=pM(t),o=new Map(n.def.nodes.map(l=>[l.id,l])),s=e.scope?new Set(e.scope):void 0,i=new Set,a=l=>!s||s.has(l)||i.has(l),c=[];for(let[l,d]of e.patch.entries()){let u=`op[${l}] ${d.op}`;switch(d.op){case"add_node":{d.node?.id?o.has(d.node.id)?r.push(`${u}: node "${d.node.id}" already exists`):(n.def.nodes.push(d.node),o.set(d.node.id,d.node),s&&i.add(d.node.id)):r.push(`${u}: node.id is required`);break}case"remove_node":{o.has(d.nodeId)?a(d.nodeId)?(n.def.nodes=n.def.nodes.filter(p=>p.id!==d.nodeId),o.delete(d.nodeId),n.def.edges=n.def.edges.filter(p=>p.from!==d.nodeId&&p.to!==d.nodeId)):r.push(`${u}: node "${d.nodeId}" is outside the edit scope`):r.push(`${u}: node "${d.nodeId}" not found`);break}case"update_params":{let p=o.get(d.nodeId);p?a(d.nodeId)?p.params=dM(p.params,d.params):r.push(`${u}: node "${d.nodeId}" is outside the edit scope`):r.push(`${u}: node "${d.nodeId}" not found`);break}case"rename_node":{let p=o.get(d.nodeId);p?a(d.nodeId)?p.name=d.name:r.push(`${u}: node "${d.nodeId}" is outside the edit scope`):r.push(`${u}: node "${d.nodeId}" not found`);break}case"add_edge":{let p=d.edge;!p?.from||!p?.to?r.push(`${u}: edge.from and edge.to are required`):s&&!a(p.from)&&!a(p.to)?r.push(`${u}: edge ${p.from}\u2192${p.to} has no endpoint in the edit scope`):n.def.edges.push(p);break}case"remove_edge":{let{from:p,to:m,fromPort:g}=d.edge;if(s&&!a(p)&&!a(m))r.push(`${u}: edge ${p}\u2192${m} has no endpoint in the edit scope`);else{let f=n.def.edges.length;n.def.edges=n.def.edges.filter(h=>!(h.from===p&&h.to===m&&(h.fromPort??"default")===(g??"default"))),n.def.edges.length===f&&r.push(`${u}: edge ${p}\u2192${m} not found`)}break}case"set_trigger":{if(s)r.push(`${u}: trigger is workflow-global and cannot be changed in a scoped edit`);else if(d.trigger){let p=Qh(d.trigger);if(p.length>0)for(let m of p)r.push(`${u}: ${m}`);else n.meta.trigger=d.trigger}else n.meta.trigger=d.trigger;break}case"set_meta":{s?r.push(`${u}: meta is workflow-global and cannot be changed in a scoped edit`):(d.meta.name!==void 0&&(n.meta.name=d.meta.name),d.meta.active!==void 0&&(n.meta.active=d.meta.active));break}default:r.push(`${u}: unknown op`)}r.length===0&&c.push(d)}if(r.length>0)throw new lr(r);if(ey(n.def,r),r.length>0)throw new lr(r);return{target:n,applied:c}}function dM(t,e){let r={...t??{}};for(let[n,o]of Object.entries(e))o===null?delete r[n]:r[n]=o;return r}function jl(t){let e=[];return ey(t,e),e}function ey(t,e){try{let r=t.nodes.map(o=>({id:o.id,kind:o.kind,params:o.params??{},outPorts:o.outPorts??uM(o.kind),joinPolicy:o.joinPolicy??"all",maxIterations:o.maxIterations})),n=new Jt(r);for(let o of t.edges)o.loopBack||n.addEdge({from:o.from,to:o.to,fromPort:o.fromPort??"default"});for(let o of t.edges)o.loopBack&&n.addEdge({from:o.from,to:o.to,loopBack:!0})}catch(r){e.push(`graph invalid: ${r.message}`)}}function uM(t){return t==="if"?["true","false"]:t==="loop"?["loop","done"]:["default"]}function pM(t){return{def:{...t.def,nodes:t.def.nodes.map(e=>({...e,params:e.params?{...e.params}:void 0})),edges:t.def.edges.map(e=>({...e})),vars:t.def.vars?{...t.def.vars}:void 0},meta:{...t.meta}}}function ty(t,e={}){let r=e.maxNodes??50,n=e.maxValueLen??60,o=`Workflow ${JSON.stringify(t.name)} (rev ${t.rev}, trigger: ${mM(t.trigger)}, ${t.active?"active":"inactive"})`,s=t.def.nodes,a=s.slice(0,r).map(u=>" "+gM(u,n)),c=s.length===0?"nodes: (none)":["nodes:",...a].join(`
|
|
397
|
+
`)},onPlanReady:(t,e)=>{this.sendNotification("product.planReady",{productId:t,plan:e})},onPlanFailed:(t,e)=>{this.sendNotification("product.planFailed",{productId:t,error:e})},onPlanningDelta:(t,e)=>{this.sendNotification("product.planningDelta",{productId:t,text:e})}})),this.productPlanner}async function Eh(t){try{let e=t.params;if(!e?.goal||!e?.cwd||!e?.leaderAgentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"goal, cwd, and leaderAgentId are required."});return}let n=await _r.call(this).plan(e);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function _h(t){try{let e=t.params;if(!e?.productId||!e?.instances||!e?.tasks){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId, instances, and tasks are required."});return}let r=_r.call(this),n=await r.confirm(e),o=r.getSession(e.productId);o&&await ye.call(this).create({name:o.plan?.name??o.goal.slice(0,50),cwd:o.cwd,instances:e.instances,tasks:e.tasks,budget:e.budget}),t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Mh(t){try{let e=t.params;if(!e?.productId||!e?.content){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId and content are required."});return}let n=await _r.call(this).message(e.productId,e.content);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Dh(t){try{let e=t.params,r;if(e?.name&&e?.cwd&&e?.instances&&e?.tasks)r=e;else if(e?.tasks&&Array.isArray(e.tasks)){let i=e.config?.workdir??this.getActiveProjectRoot(),a=e.tasks.map(c=>({taskId:String(c.id??c.taskId??`task_${Math.random().toString(36).slice(2,8)}`),assignee:String(c.assignee??"default"),prompt:String(c.description??c.prompt??""),dependsOn:c.dependsOn??[]}));r={name:String(e.name??`product_${Date.now()}`),cwd:i,instances:[{name:"default",role:"executor",agentId:"self"}],tasks:a},e.budget&&(r.budget=e.budget)}else{t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"tasks is required. Provide either {name, cwd, instances, tasks} or simplified {tasks, config}."});return}if(!r.projectId){let s=oe();s&&(r.projectId=s.id)}let o=await ye.call(this).create(r);t.id!==void 0&&this.sendResponse(t.id,{productId:o})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Nh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).resume(e.productId,this.getActiveProjectRoot()),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Lh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).pause(e.productId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Oh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).checkpoint(e.productId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function jh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}let n=ye.call(this).getStatus(e.productId);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function $h(t){try{let r=await ye.call(this).list(this.getActiveProjectRoot());t.id!==void 0&&this.sendResponse(t.id,r)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Uh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).delete(e.productId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Fh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).delete(e.productId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Hh(t){try{let e=t.params;if(!e?.productId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"productId is required."});return}await ye.call(this).rollback(e.productId,e.checkpoint??"latest"),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}import*as uy from"node:path";import{randomUUID as py}from"node:crypto";D();function cn(t,e){return e?{json:t,binary:e}:{json:t}}function Bh(t){let e={};for(let r of Object.keys(t).sort())e[r]=t[r].map(n=>({json:n.json,binary:n.binary?Object.fromEntries(Object.keys(n.binary).sort().map(o=>[o,n.binary[o].ref])):void 0}));return Cl(e)}function Cl(t){return JSON.stringify(Pl(t))}function Pl(t){if(Array.isArray(t))return t.map(Pl);if(t&&typeof t=="object"){let e={};for(let r of Object.keys(t).sort())e[r]=Pl(t[r]);return e}return t}var Gh=new Set(["__proto__","prototype","constructor"]);function qh(t,e){let r=B_(t),n=new _l(r,t),o=n.parseExpression();return n.expectEnd(),ln(o,e)}function Dl(t,e){let r=t.match(/^\s*\{\{([\s\S]*)\}\}\s*$/);return r?qh(r[1],e):t.includes("{{")?t.replace(/\{\{([\s\S]*?)\}\}/g,(n,o)=>{let s=qh(o,e);if(s==null)throw new Error(`Expression "{{${o.trim()}}}" resolved to ${s} in string interpolation`);return typeof s=="object"?JSON.stringify(s):String(s)}):t}function Kh(t,e){return El(t,e)}function El(t,e){if(typeof t=="string")return Dl(t,e);if(Array.isArray(t))return t.map(r=>El(r,e));if(t&&typeof t=="object"){let r={};for(let[n,o]of Object.entries(t))r[n]=El(o,e);return r}return t}function B_(t){let e=[],r=0,n=s=>/[A-Za-z_]/.test(s),o=s=>/[A-Za-z0-9_]/.test(s);for(;r<t.length;){let s=t[r];if(/\s/.test(s)){r++;continue}if(s==="$"){r++;let i="";for(;r<t.length&&o(t[r]);)i+=t[r++];if(!i)throw new Error('Bare "$" is not a valid expression');e.push({t:"dollar",v:i});continue}if(n(s)){let i="";for(;r<t.length&&o(t[r]);)i+=t[r++];e.push({t:"id",v:i});continue}if(/[0-9]/.test(s)||s==="-"&&/[0-9]/.test(t[r+1]??"")){let i=t[r++];for(;r<t.length&&/[0-9.]/.test(t[r]);)i+=t[r++];e.push({t:"num",v:i});continue}if(s==='"'||s==="'"){let i=s;r++;let a="";for(;r<t.length&&t[r]!==i;)t[r]==="\\"&&r+1<t.length?(a+=t[r+1],r+=2):a+=t[r++];if(t[r]!==i)throw new Error("Unterminated string literal in expression");r++,e.push({t:"str",v:a});continue}if(".[](),".includes(s)){e.push({t:"punc",v:s}),r++;continue}throw new Error(`Unexpected character "${s}" in expression`)}return e}var _l=class{constructor(e,r){this.toks=e;this.src=r}toks;src;pos=0;parseExpression(){return this.parseAccessors(this.parseAtom())}peek(){return this.toks[this.pos]}next(){return this.toks[this.pos++]}expectEnd(){if(this.pos!==this.toks.length)throw new Error(`Unexpected trailing tokens in expression "${this.src.trim()}"`)}parseAtom(){let e=this.peek();if(!e)throw new Error("Empty expression");if(e.t==="dollar")return this.next(),{type:"root",name:e.v};if(e.t==="num")return this.next(),{type:"lit",value:Number(e.v)};if(e.t==="str")return this.next(),{type:"lit",value:e.v};if(e.t==="id"){if(e.v==="true")return this.next(),{type:"lit",value:!0};if(e.v==="false")return this.next(),{type:"lit",value:!1};if(e.v==="null")return this.next(),{type:"lit",value:null};if(this.next(),this.peek()?.t==="punc"&&this.peek().v==="("){let r=this.parseArgs();return{type:"func",name:e.v,args:r}}throw new Error(`Bare identifier "${e.v}" is not allowed (only whitelist function calls)`)}if(e.t==="punc"&&e.v==="("){this.next();let r=this.parseExpression();return this.expectPunc(")"),r}throw new Error(`Unexpected token "${e.v}" in expression`)}parseAccessors(e){let r=e;for(;;){let n=this.peek();if(!n||n.t!=="punc")break;if(n.v==="."){this.next();let o=this.next();if(!o||o.t!=="id"&&o.t!=="num")throw new Error('Expected property name after "."');r={type:"prop",target:r,key:o.v}}else if(n.v==="["){this.next();let o=this.next(),s;if(o.t==="num")s=Number(o.v);else if(o.t==="str")s=o.v;else throw new Error("Index must be a number or string literal");this.expectPunc("]"),r={type:"index",target:r,key:s}}else if(n.v==="("){let o=this.parseArgs();r={type:"call",target:r,args:o}}else break}return r}parseArgs(){this.expectPunc("(");let e=[];if(this.peek()?.t==="punc"&&this.peek().v===")")return this.next(),e;for(;;){e.push(this.parseExpression());let r=this.next();if(!r)throw new Error("Unterminated argument list");if(r.t==="punc"&&r.v===")")break;if(!(r.t==="punc"&&r.v===","))throw new Error('Expected "," or ")" in argument list')}return e}expectPunc(e){let r=this.next();if(!r||r.t!=="punc"||r.v!==e)throw new Error(`Expected "${e}" in expression`)}},zh=Symbol("nodeAccessor");function ln(t,e){switch(t.type){case"lit":return t.value;case"root":return q_(t.name,e);case"func":return W_(t.name,t.args.map(r=>ln(r,e)));case"prop":return Wh(ln(t.target,e),t.key);case"index":return Wh(ln(t.target,e),t.key);case"call":{if(ln(t.target,e)===zh){let n=t.args.map(s=>ln(s,e));if(n.length!==1||typeof n[0]!="string")throw new Error("$node(...) takes exactly one string argument");let o=e.nodes?.[n[0]];if(!o)throw new Error(`$node("${n[0]}") not found (not completed or unknown)`);return o}throw new Error("Only $node(...) is callable in this position")}}}function q_(t,e){switch(t){case"input":return e.input??{};case"json":return e.json??{};case"vars":return e.vars??{};case"trigger":return e.trigger??{};case"now":return(e.now?e.now():new Date).toISOString();case"node":return zh;default:throw new Error(`Unknown context root "$${t}" (allowed: $input $json $node $now $vars $trigger)`)}}function Wh(t,e){if(typeof e=="string"&&Gh.has(e))throw new Error(`Access to "${e}" is forbidden`);if(t==null)throw new Error(`Cannot read "${e}" of ${t}`);if(typeof e=="number"){if(!Array.isArray(t))throw new Error(`Cannot index non-array with [${e}]`);return t[e]}return t[e]}function W_(t,e){switch(t){case"len":{let r=e[0];if(typeof r=="string"||Array.isArray(r))return r.length;if(r&&typeof r=="object")return Object.keys(r).length;throw new Error(`len() expects string/array/object, got ${typeof r}`)}case"upper":return String(js(e,0,"upper")).toUpperCase();case"lower":return String(js(e,0,"lower")).toLowerCase();case"default":return e[0]===null||e[0]===void 0?e[1]:e[0];case"jsonpath":return K_(e[0],String(js(e,1,"jsonpath")));case"date":return z_(e);case"eq":return Ml(e[0],e[1]);case"ne":return!Ml(e[0],e[1]);case"gt":return Os(e[0],e[1])>0;case"gte":return Os(e[0],e[1])>=0;case"lt":return Os(e[0],e[1])<0;case"lte":return Os(e[0],e[1])<=0;case"not":return!Il(js(e,0,"not"));case"and":return e.every(Il);case"or":return e.some(Il);case"contains":return G_(e[0],e[1]);default:throw new Error(`Unknown function "${t}()" (whitelist: len upper lower default jsonpath date eq ne gt gte lt lte not and or contains)`)}}function Il(t){return!!t}function Ml(t,e){return t===e?!0:typeof t!=typeof e?!1:t&&e&&typeof t=="object"?JSON.stringify(t)===JSON.stringify(e):!1}function Os(t,e){if(typeof t=="number"&&typeof e=="number")return t-e;if(typeof t=="string"&&typeof e=="string")return t<e?-1:t>e?1:0;throw new Error(`Cannot compare ${typeof t} with ${typeof e}`)}function G_(t,e){if(typeof t=="string")return t.includes(String(e));if(Array.isArray(t))return t.some(r=>Ml(r,e));throw new Error("contains() expects string/array as first argument")}function js(t,e,r){if(t.length<=e||t[e]===void 0)throw new Error(`${r}() missing required argument #${e+1}`);return t[e]}function K_(t,e){let r=e.match(/[^.[\]]+/g)??[],n=t;for(let o of r){if(Gh.has(o))throw new Error(`jsonpath segment "${o}" is forbidden`);if(n==null)return;let s=/^\d+$/.test(o)?Number(o):o;n=n[s]}return n}function z_(t){let e=t.length===0?new Date:new Date(t[0]);if(Number.isNaN(e.getTime()))throw new Error(`date() received an invalid date: ${String(t[0])}`);if(t.length<2)return e.toISOString();let r=String(t[1]),n=o=>String(o).padStart(2,"0");return r.replace(/YYYY/g,String(e.getUTCFullYear())).replace(/MM/g,n(e.getUTCMonth()+1)).replace(/DD/g,n(e.getUTCDate())).replace(/HH/g,n(e.getUTCHours())).replace(/mm/g,n(e.getUTCMinutes())).replace(/ss/g,n(e.getUTCSeconds()))}var V_=(t,e)=>({outputs:{default:[{json:e.json&&typeof e.json=="object"&&!Array.isArray(e.json)?e.json:{value:e.json??e.value??null}}]}}),X_=t=>({outputs:{default:t.default??[]}}),Y_=t=>{let e=[];for(let r of Object.keys(t))e.push(...t[r]);return{outputs:{default:e}}},J_=(t,e)=>{let n=!!e.condition?"true":"false",o=t.default??[],s={true:[],false:[]};return s[n]=o,{outputs:s,firedPorts:[n]}},Q_=(t,e,r)=>({outputs:{default:[{json:r.trigger??(e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{})}]}}),Vh={set:V_,passthrough:X_,merge:Y_,if:J_,trigger:Q_};var dn=class{executors=new Map;constructor(e=!0){if(e)for(let[r,n]of Object.entries(Vh))this.executors.set(r,n)}register(e,r){if(this.executors.has(e))throw new Error(`NodeExecutor for kind "${e}" already registered`);this.executors.set(e,r)}override(e,r){if(!this.executors.has(e))throw new Error(`Cannot override unregistered kind "${e}"`);this.executors.set(e,r)}has(e){return this.executors.has(e)}get(e){let r=this.executors.get(e);if(!r)throw new Error(`No NodeExecutor registered for kind "${e}"`);return r}kinds(){return[...this.executors.keys()]}};function eo(t,e){if(!t)throw new Error(`Node kind "${e}" requires a host (ExecutorHost) but none was injected. Provide one via WorkflowRuntimeOptions.host.`);return t}function un(t,e,r){let n=t[e];if(typeof n!="string"||n.length===0)throw new Error(`Node kind "${r}" requires string param "${e}"`);return n}function Xh(t,e){let r=t[e];if(r==null)return{};if(typeof r!="object"||Array.isArray(r))throw new Error(`Param "${e}" must be an object`);return r}var Z_=async(t,e,r)=>({outputs:{default:await eo(r.host,"agent").runAgent({agentId:typeof e.agentId=="string"?e.agentId:void 0,prompt:un(e,"prompt","agent"),input:t.default??[],signal:r.signal})}}),eM=async(t,e,r)=>({outputs:{default:await eo(r.host,"tool").invokeTool({tool:un(e,"tool","tool"),args:Xh(e,"args"),input:t.default??[],signal:r.signal})}}),tM=async(t,e,r)=>{let n=eo(r.host,"http"),o=typeof e.method=="string"?e.method:"GET";return{outputs:{default:await n.httpRequest({method:o,url:un(e,"url","http"),headers:e.headers,body:e.body,signal:r.signal})}}},rM=async(t,e,r)=>({outputs:{default:await eo(r.host,"mcp").invokeMcp({server:un(e,"server","mcp"),tool:un(e,"tool","mcp"),args:Xh(e,"args"),signal:r.signal})}}),nM=async(t,e,r)=>({outputs:{default:await eo(r.host,"channel").sendChannel({channel:un(e,"channel","channel"),target:typeof e.target=="string"?e.target:void 0,payload:e.payload??t.default?.[0]?.json??{},input:t.default??[],signal:r.signal})}}),to={agent:Z_,tool:eM,http:tM,mcp:rM,channel:nM},E2=Object.keys(to);var pn=class extends Error{constructor(r){super(r?`Workflow paused at "${r}"`:"Workflow paused");this.atNodeId=r;this.name="WorkflowPauseSignal"}atNodeId},$s=class{constructor(e,r={}){this.def=e;if(this.registry=r.registry??new dn,this.gate=r.gate,this.now=r.now??(()=>new Date),this.trigger=r.trigger,this.log=r.log,this.host=r.host,this.signal=r.signal,this.checkpoint=r.checkpoint,this.host)for(let[n,o]of Object.entries(to))this.registry.has(n)||this.registry.register(n,o);for(let n of e.nodes)this.nodeDefs.set(n.id,n);for(let n of e.edges)n.loopBack&&this.loopBackOf.set(n.from,n.to)}def;registry;gate;now;trigger;log;host;signal;checkpoint;dag;nodeDefs=new Map;nodeOutputs=new Map;cache=new Map;loopBackOf=new Map;pauseRequested=!1;checkpointLoaded=!1;setNodeParams(e,r){let n=this.nodeDefs.get(e);if(!n)throw new Error(`Unknown node "${e}"`);n.params={...n.params??{},...r}}pause(){this.pauseRequested=!0}extendBudget(e){if(!this.gate?.extend)throw new Error("WorkflowRuntime has no extensible budget gate to raise");this.gate.extend(e)}async run(){await this.loadCheckpoint(),this.dag=this.buildDag(),this.nodeOutputs.clear(),this.pauseRequested=!1;let e=new Set,r;try{let s=0;for(;!this.dag.isFinished();){if(++s>1e5)throw new Error("WorkflowRuntime did not converge");let i=this.dag.getReadyNodes();if(i.length===0)break;for(let a of i)await this.executeNode(a,e)}}catch(s){if(s instanceof pn)r=s.atNodeId;else throw s}let n={};for(let[s,i]of this.nodeOutputs)n[s]=i;let o=r?"paused":this.dag.isAllCompleted()?"completed":"failed";return o==="completed"&&this.checkpoint&&await this.checkpoint.clear(),{status:o,outputs:n,executed:e,progress:this.dag.getProgress(),pausedAt:r}}async loadCheckpoint(){if(!this.checkpoint||this.checkpointLoaded)return;this.checkpointLoaded=!0;let e=await this.checkpoint.load();if(e)for(let r of e.entries)this.cache.set(r.key,r.result)}async persistCheckpoint(){if(!this.checkpoint)return;let e=[...this.cache.entries()].map(([r,n])=>({key:r,result:n}));await this.checkpoint.persist(e)}async executeNode(e,r){if(this.pauseRequested)throw new pn(e.id);if(e.kind==="loop"){this.enterLoop(e);return}let n=this.collectInputs(e.id),o=this.buildExprContext(n),s=this.nodeDefs.get(e.id)?.params??{},i=Kh(s,o),a=this.cacheKey(e.kind,i,n,e.runIndex),c=this.cache.get(a);if(c)this.dag.markRunning(e.id);else{this.gate?.check(e.id,e.kind),this.dag.markRunning(e.id);let d={nodeId:e.id,kind:e.kind,runIndex:e.runIndex,vars:this.def.vars??{},trigger:this.trigger,now:this.now,log:this.log,host:this.host,signal:this.signal};c=await this.registry.get(e.kind)(n,i,d),this.cache.set(a,c),r.add(e.id),await this.persistCheckpoint()}this.nodeOutputs.set(e.id,c.outputs),this.dag.markCompleted(e.id,{output:c.outputs,firedPorts:c.firedPorts});let l=this.loopBackOf.get(e.id);l&&this.decideLoopBack(l)}enterLoop(e){this.dag.markRunning(e.id);let r={loop:[{json:{iteration:e.iteration??0}}],done:[]};this.nodeOutputs.set(e.id,r),this.dag.markCompleted(e.id,{output:r,firedPorts:["loop"]})}decideLoopBack(e){let r=this.evalLoopCondition(e);this.dag.decideLoop(e,r);let n=this.dag.getNode(e),o=n.firedPorts??[];this.nodeOutputs.set(e,{loop:o.includes("loop")?[{json:{iteration:n.iteration??0}}]:[],done:o.includes("done")?[{json:{iteration:n.iteration??0}}]:[]})}evalLoopCondition(e){let n=this.nodeDefs.get(e)?.params?.condition;if(n==null||n==="")return!0;let o=this.buildExprContext({});return!!(typeof n=="string"?Dl(n,o):n)}collectInputs(e){let r={};for(let n of this.def.edges){if(n.to!==e||n.loopBack)continue;let o=n.fromPort??"default",s=n.toPort??"default",i=this.nodeOutputs.get(n.from);if(!i)continue;let a=i[o];a&&(r[s]??=[]).push(...a)}return r}buildExprContext(e){let r={};for(let[n,o]of this.nodeOutputs)r[n]={output:o};return{input:e,json:e.default?.[0]?.json??{},nodes:r,vars:this.def.vars??{},trigger:this.trigger,now:this.now}}cacheKey(e,r,n,o){return Cl([e,r,Bh(n),o])}buildDag(){let e=this.def.nodes.map(n=>({id:n.id,kind:n.kind,params:n.params??{},outPorts:n.outPorts??oM(n.kind),joinPolicy:n.joinPolicy??"all",maxIterations:n.maxIterations})),r=new Qt(e);for(let n of this.def.edges)n.loopBack||r.addEdge({from:n.from,to:n.to,fromPort:n.fromPort??"default"});for(let n of this.def.edges)n.loopBack&&r.addEdge({from:n.from,to:n.to,loopBack:!0});return r}};function oM(t){return t==="if"?["true","false"]:t==="loop"?["loop","done"]:["default"]}var sM=new Set(["agent","tool","http","mcp","channel","im"]),Nl=class extends Error{constructor(r,n,o){super(`Permission denied: node "${r}" (kind "${n}") may not run under unattended trigger "${o}". Authorize it by adding "${n}" to allowUnattendedKinds.`);this.nodeId=r;this.kind=n;this.trigger=o;this.name="WorkflowPermissionDenied"}nodeId;kind;trigger},Us=class extends pn{constructor(r,n,o){super(r);this.reason=n;this.limit=o;this.name="WorkflowBudgetExceeded",this.message=`Budget exceeded (${n} limit ${o}) before node "${r}"`}reason;limit},Fs=class{trigger;maxNodeExecutions;maxDurationMs;allow;now;executions=0;startedAt=-1;constructor(e){if(!Number.isInteger(e.maxNodeExecutions)||e.maxNodeExecutions<=0)throw new Error(`BudgetPermissionGate: maxNodeExecutions must be a positive integer, got ${e.maxNodeExecutions}`);if(e.maxDurationMs!==void 0&&!(e.maxDurationMs>0))throw new Error(`BudgetPermissionGate: maxDurationMs must be greater than 0 when provided, got ${e.maxDurationMs}`);this.trigger=e.trigger,this.maxNodeExecutions=e.maxNodeExecutions,this.maxDurationMs=e.maxDurationMs,this.allow=new Set(e.allowUnattendedKinds??[]),this.now=e.now??(()=>Date.now())}get unattended(){return this.trigger!=="manual"}check(e,r){if(this.unattended&&sM.has(r)&&!this.allow.has(r))throw new Nl(e,r,this.trigger);if(this.startedAt<0&&(this.startedAt=this.now()),this.maxDurationMs!==void 0&&this.now()-this.startedAt>=this.maxDurationMs)throw new Us(e,"duration",this.maxDurationMs);if(this.executions>=this.maxNodeExecutions)throw new Us(e,"executions",this.maxNodeExecutions);this.executions++}extend(e){if(e.executions!==void 0){if(!Number.isInteger(e.executions)||e.executions<=0)throw new Error(`BudgetPermissionGate.extend: executions delta must be a positive integer, got ${e.executions}`);this.maxNodeExecutions+=e.executions}if(e.durationMs!==void 0){if(!(e.durationMs>0))throw new Error(`BudgetPermissionGate.extend: durationMs delta must be greater than 0, got ${e.durationMs}`);if(this.maxDurationMs===void 0)throw new Error("BudgetPermissionGate.extend: cannot extend duration on a gate with no duration cap");this.maxDurationMs+=e.durationMs}}};function Qh(t){switch(t.type){case"manual":return[];case"schedule":return Ol(t.cron);case"im-message":return cM(t.channel,t.match);case"webhook":return lM(t.path);default:return[`unknown trigger type: ${JSON.stringify(t)}`]}}var Yh=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"],Jh=["SUN","MON","TUE","WED","THU","FRI","SAT"];function Ol(t){if(typeof t!="string"||t.trim()==="")return["schedule.cron must be a non-empty string"];let e=t.trim().split(/\s+/);if(e.length!==5&&e.length!==6)return[`schedule.cron must have 5 or 6 fields, got ${e.length}: "${t}"`];let n=e.length===6?[{label:"second",min:0,max:59},{label:"minute",min:0,max:59},{label:"hour",min:0,max:23},{label:"day-of-month",min:1,max:31},{label:"month",min:1,max:12,names:Yh},{label:"day-of-week",min:0,max:7,names:Jh}]:[{label:"minute",min:0,max:59},{label:"hour",min:0,max:23},{label:"day-of-month",min:1,max:31},{label:"month",min:1,max:12,names:Yh},{label:"day-of-week",min:0,max:7,names:Jh}],o=[];for(let s=0;s<n.length;s++){let i=iM(e[s],n[s]);i&&o.push(`schedule.cron ${i}`)}return o}function iM(t,e){for(let r of t.split(",")){let n=aM(r,e);if(n)return n}}function aM(t,e){if(t==="")return`${e.label} has an empty list element`;let r=t,n,o=t.indexOf("/");if(o!==-1&&(r=t.slice(0,o),n=t.slice(o+1),!/^\d+$/.test(n)||Number(n)<=0))return`${e.label} has an invalid step "/${n}"`;if(r==="*")return;let s=r.indexOf("-");if(s!==-1){let a=Ll(r.slice(0,s),e),c=Ll(r.slice(s+1),e);return a===void 0||c===void 0?`${e.label} has an invalid range "${r}"`:a>c?`${e.label} range "${r}" is descending`:void 0}if(r===""&&n!==void 0)return`${e.label} step "${t}" needs a base ("*" or a range)`;if(Ll(r,e)===void 0)return`${e.label} value "${r}" is out of range ${e.min}-${e.max}`}function Ll(t,e){let r;if(/^\d+$/.test(t))r=Number(t);else if(e.names){let n=e.names.indexOf(t.toUpperCase());if(n===-1)return;r=e.label==="month"?n+1:n}else return;if(!(r<e.min||r>e.max))return r}function cM(t,e){let r=[];if((typeof t!="string"||t.trim()==="")&&r.push("im-message.channel must be a non-empty string"),e!==void 0)if(typeof e!="string")r.push("im-message.match must be a string regex");else try{new RegExp(e)}catch(n){r.push(`im-message.match is not a valid regex: ${n.message}`)}return r}function lM(t){return typeof t!="string"||t===""?["webhook.path must be a non-empty string"]:t.startsWith("/")?/\s/.test(t)?[`webhook.path must not contain whitespace: "${t}"`]:t.includes("..")?[`webhook.path must not contain "..": "${t}"`]:/^\/[A-Za-z0-9\-._~/]*$/.test(t)?[]:[`webhook.path contains illegal characters: "${t}"`]:[`webhook.path must start with "/": "${t}"`]}var lr=class extends Error{constructor(r){super(`Patch rejected: ${r.join("; ")}`);this.errors=r;this.name="PatchError"}errors};function Zh(t,e){let r=[],n=pM(t),o=new Map(n.def.nodes.map(l=>[l.id,l])),s=e.scope?new Set(e.scope):void 0,i=new Set,a=l=>!s||s.has(l)||i.has(l),c=[];for(let[l,d]of e.patch.entries()){let u=`op[${l}] ${d.op}`;switch(d.op){case"add_node":{d.node?.id?o.has(d.node.id)?r.push(`${u}: node "${d.node.id}" already exists`):(n.def.nodes.push(d.node),o.set(d.node.id,d.node),s&&i.add(d.node.id)):r.push(`${u}: node.id is required`);break}case"remove_node":{o.has(d.nodeId)?a(d.nodeId)?(n.def.nodes=n.def.nodes.filter(p=>p.id!==d.nodeId),o.delete(d.nodeId),n.def.edges=n.def.edges.filter(p=>p.from!==d.nodeId&&p.to!==d.nodeId)):r.push(`${u}: node "${d.nodeId}" is outside the edit scope`):r.push(`${u}: node "${d.nodeId}" not found`);break}case"update_params":{let p=o.get(d.nodeId);p?a(d.nodeId)?p.params=dM(p.params,d.params):r.push(`${u}: node "${d.nodeId}" is outside the edit scope`):r.push(`${u}: node "${d.nodeId}" not found`);break}case"rename_node":{let p=o.get(d.nodeId);p?a(d.nodeId)?p.name=d.name:r.push(`${u}: node "${d.nodeId}" is outside the edit scope`):r.push(`${u}: node "${d.nodeId}" not found`);break}case"add_edge":{let p=d.edge;!p?.from||!p?.to?r.push(`${u}: edge.from and edge.to are required`):s&&!a(p.from)&&!a(p.to)?r.push(`${u}: edge ${p.from}\u2192${p.to} has no endpoint in the edit scope`):n.def.edges.push(p);break}case"remove_edge":{let{from:p,to:m,fromPort:g}=d.edge;if(s&&!a(p)&&!a(m))r.push(`${u}: edge ${p}\u2192${m} has no endpoint in the edit scope`);else{let f=n.def.edges.length;n.def.edges=n.def.edges.filter(h=>!(h.from===p&&h.to===m&&(h.fromPort??"default")===(g??"default"))),n.def.edges.length===f&&r.push(`${u}: edge ${p}\u2192${m} not found`)}break}case"set_trigger":{if(s)r.push(`${u}: trigger is workflow-global and cannot be changed in a scoped edit`);else if(d.trigger){let p=Qh(d.trigger);if(p.length>0)for(let m of p)r.push(`${u}: ${m}`);else n.meta.trigger=d.trigger}else n.meta.trigger=d.trigger;break}case"set_meta":{s?r.push(`${u}: meta is workflow-global and cannot be changed in a scoped edit`):(d.meta.name!==void 0&&(n.meta.name=d.meta.name),d.meta.active!==void 0&&(n.meta.active=d.meta.active));break}default:r.push(`${u}: unknown op`)}r.length===0&&c.push(d)}if(r.length>0)throw new lr(r);if(ey(n.def,r),r.length>0)throw new lr(r);return{target:n,applied:c}}function dM(t,e){let r={...t??{}};for(let[n,o]of Object.entries(e))o===null?delete r[n]:r[n]=o;return r}function jl(t){let e=[];return ey(t,e),e}function ey(t,e){try{let r=t.nodes.map(o=>({id:o.id,kind:o.kind,params:o.params??{},outPorts:o.outPorts??uM(o.kind),joinPolicy:o.joinPolicy??"all",maxIterations:o.maxIterations})),n=new Qt(r);for(let o of t.edges)o.loopBack||n.addEdge({from:o.from,to:o.to,fromPort:o.fromPort??"default"});for(let o of t.edges)o.loopBack&&n.addEdge({from:o.from,to:o.to,loopBack:!0})}catch(r){e.push(`graph invalid: ${r.message}`)}}function uM(t){return t==="if"?["true","false"]:t==="loop"?["loop","done"]:["default"]}function pM(t){return{def:{...t.def,nodes:t.def.nodes.map(e=>({...e,params:e.params?{...e.params}:void 0})),edges:t.def.edges.map(e=>({...e})),vars:t.def.vars?{...t.def.vars}:void 0},meta:{...t.meta}}}function ty(t,e={}){let r=e.maxNodes??50,n=e.maxValueLen??60,o=`Workflow ${JSON.stringify(t.name)} (rev ${t.rev}, trigger: ${mM(t.trigger)}, ${t.active?"active":"inactive"})`,s=t.def.nodes,a=s.slice(0,r).map(u=>" "+gM(u,n)),c=s.length===0?"nodes: (none)":["nodes:",...a].join(`
|
|
398
398
|
`),l=s.length>r?`
|
|
399
399
|
\u2026 ${s.length-r} more node(s); call workflow.get for the full definition`:"",d=yM(t.def.edges);return`${o}
|
|
400
400
|
${c}${l}
|
|
401
401
|
${d}`}function mM(t){if(!t)return"none";switch(t.type){case"manual":return"manual";case"schedule":return`schedule ${JSON.stringify(t.cron)}`;case"im-message":return t.match?`im-message ${t.channel} match=${JSON.stringify(t.match)}`:`im-message ${t.channel}`;case"webhook":return`webhook ${t.path}`}}function gM(t,e){let r=t.name?` "${t.name}"`:"",n=fM(t.params,e),o=(t.outPorts??bM(t.kind)).join(","),s=[`${t.id} [${t.kind}]${r}`];return n&&s.push(n),s.push(`out: ${o}`),s.join(" ")}function fM(t,e){if(!t)return"";let r=Object.keys(t).sort();return r.length===0?"":r.map(n=>`${n}=${hM(t[n],e)}`).join(" ")}function hM(t,e){let r;return typeof t=="string"?r=t.includes("{{")?t:JSON.stringify(t):r=JSON.stringify(t),r.length>e&&(r=r.slice(0,e-1)+"\u2026"),r}function yM(t){return t.length===0?"edges: (none)":`edges:
|
|
402
|
-
${t.map(r=>{let n=r.fromPort??"default",o=r.toPort??"default",s=r.loopBack?" (loopBack)":"";return`${r.from}.${n}\u2192${r.to}.${o}${s}`}).join(" ; ")}`}function bM(t){return t==="if"?["true","false"]:t==="loop"?["loop","done"]:["default"]}var vM={"n8n-nodes-base.set":"set","n8n-nodes-base.if":"if","n8n-nodes-base.merge":"merge","n8n-nodes-base.noOp":"passthrough","n8n-nodes-base.httpRequest":"http","n8n-nodes-base.manualTrigger":"trigger","n8n-nodes-base.scheduleTrigger":"trigger","n8n-nodes-base.cron":"trigger","n8n-nodes-base.webhook":"trigger"},Mr=class extends Error{constructor(r){super(`n8n import rejected: ${r.join("; ")}`);this.errors=r;this.name="N8nImportError"}errors};function ry(t,e){let r=kM(t),n=[],o=new Set,s=[];for(let[a,c]of r.nodes.entries()){if(typeof c?.name!="string"||c.name===""){n.push(`nodes[${a}] has a missing/empty name`);continue}if(o.has(c.name)){n.push(`duplicate node name "${c.name}"`);continue}if(o.add(c.name),typeof c.type!="string"||c.type===""){n.push(`node "${c.name}" has a missing/empty type`);continue}let l=vM[c.type];if(!l){n.push(`node "${c.name}" has unsupported type "${c.type}" (not in the import type map)`);continue}let d={id:c.name,kind:l,name:c.name,params:{...c.parameters??{},_n8nType:c.type}};l==="if"&&(d.outPorts=["true","false"]),s.push(d)}let i=r.connections?RM(r.connections,o,s,n):[];if(s.length===0&&n.length===0&&n.push("workflow has no nodes"),n.length>0)throw new Mr(n);return{name:typeof r.name=="string"&&r.name!==""?r.name:e,def:{id:e,nodes:s,edges:i}}}function kM(t){let e;if(typeof t=="string")try{e=JSON.parse(t)}catch(n){throw new Mr([`invalid JSON: ${n.message}`])}else e=t;if(!e||typeof e!="object")throw new Mr(["workflow must be a JSON object"]);let r=e;if(!Array.isArray(r.nodes))throw new Mr(["workflow.nodes must be an array"]);if(r.connections!==void 0&&(typeof r.connections!="object"||r.connections===null))throw new Mr(["workflow.connections must be an object"]);return{name:r.name,nodes:r.nodes,connections:r.connections??{}}}function RM(t,e,r,n){let o=new Map(r.map(i=>[i.id,i.kind])),s=[];for(let i of Object.keys(t).sort()){if(!e.has(i)){n.push(`connection source "${i}" is not a declared node`);continue}let a=t[i]?.main;if(Array.isArray(a))for(let c=0;c<a.length;c++){let l=SM(i,o.get(i),c,n),d=a[c];if(Array.isArray(d))for(let u of d){if(!u||typeof u.node!="string"){n.push(`connection from "${i}" has a malformed target`);continue}if(!e.has(u.node)){n.push(`connection from "${i}" targets missing node "${u.node}"`);continue}let p={from:i,to:u.node};l!=="default"&&(p.fromPort=l),s.push(p)}}}return s}function SM(t,e,r,n){return e==="if"?r===0?"true":r===1?"false":(n.push(`if node "${t}" has an unsupported output index ${r} (only 0/1)`),"default"):(r===0||n.push(`node "${t}" has an unmodeled multi-output index ${r} (only single-output supported)`),"default")}var dr=class{constructor(e,r){this.store=e;this.runtimeFactory=r}store;runtimeFactory;slots=new Map;async create(e){let r=jl(e.def);if(r.length>0)throw new lr(r);let n=new Date().toISOString(),o={id:e.id,name:e.name,def:e.def,active:e.active??!1,concurrency:e.concurrency??"queue",rev:1,createdAt:n,updatedAt:n};return await this.store.save(o),o}async update(e,r){let o={...await this.store.require(e),...r,updatedAt:new Date().toISOString()};if(r.def!==void 0){let s=jl(o.def);if(s.length>0)throw new lr(s)}return await this.store.save(o),o}async setActive(e,r){return this.update(e,{active:r})}async importN8n(e,r,n={}){let{name:o,def:s}=ry(r,e);return this.create({id:e,name:o,def:s,concurrency:n.concurrency})}async get(e){return this.store.require(e)}async describe(e,r){let n=await this.store.require(e);return ty(n,r)}async patch(e,r){let n=await this.store.require(e),o=r.baseRev!==void 0&&r.baseRev<n.rev,s={def:n.def,meta:{name:n.name,active:n.active,trigger:n.trigger??null}},i,a;try{let l=Zh(s,r);i=l.applied,a=l.target}catch(l){if(o&&l instanceof lr)return{ok:!1,conflict:{latestRev:n.rev}};throw l}let c={...n,def:a.def,name:a.meta.name??n.name,active:a.meta.active??n.active,trigger:a.meta.trigger??null,rev:n.rev+1,updatedAt:new Date().toISOString()};return await this.store.save(c),{ok:!0,rev:c.rev,applied:i}}async run(e,r){let n=await this.store.require(e),o={type:r?.type??"manual",payload:r?.payload},s=this.slotFor(e);if(s.pending>0)switch(n.concurrency){case"skip":return{workflowId:e,status:"skipped"};case"parallel":return this.startParallel(e,n.def,o);case"queue":return this.track(e,s,n.def,o,!0)}return this.track(e,s,n.def,o,!1)}pause(e){let r=this.slots.get(e);if(!r?.runtime||r.pending===0)throw new Error(`Workflow "${e}" has no active run to pause`);r.runtime.pause()}async resume(e,r={}){let n=this.slots.get(e);if(!n?.runtime)throw new Error(`Workflow "${e}" has no runtime to resume`);let o=n.runtime;r.extraBudget&&o.extendBudget(r.extraBudget),n.pending++;let s=o.run().then(i=>({workflowId:e,status:i.status,result:i})).finally(()=>{n.pending--});return n.tail=s.catch(()=>{}),s}async listActive(){return this.store.listActive()}slotFor(e){let r=this.slots.get(e);return r||(r={tail:Promise.resolve(),pending:0},this.slots.set(e,r)),r}track(e,r,n,o,s){r.pending++;let i=()=>{let l=this.runtimeFactory(n,o);return r.runtime=l,l.run().then(d=>({workflowId:e,status:d.status,result:d}))},c=(s?r.tail.then(i):i()).finally(()=>{r.pending--});return r.tail=c.catch(()=>{}),c}async startParallel(e,r,n){let s=await this.runtimeFactory(r,n).run();return{workflowId:e,status:s.status,result:s}}};function ny(t){return(e,r)=>new $s(e,{registry:t.registry,host:t.host,trigger:r.payload,now:t.now,gate:new Fs({trigger:r.type,maxNodeExecutions:t.budget.maxNodeExecutions,maxDurationMs:t.budget.maxDurationMs,allowUnattendedKinds:t.allowUnattendedKinds,now:t.now?()=>t.now().getTime():void 0})})}import{join as Bs}from"node:path";import{mkdir as wM,readdir as TM,rm as AM}from"node:fs/promises";D();function Hs(t){return Bs(re(t),"workflows")}function oy(t,e){return Bs(Hs(e),t,"workflow.json")}var ur=class{constructor(e){this.cwd=e;if(!e)throw new Error("WorkflowStore requires a project cwd")}cwd;async save(e){if(!e.id)throw new Error("WorkflowRecord.id is required");let r=Bs(Hs(this.cwd),e.id);await wM(r,{recursive:!0}),await cr(oy(e.id,this.cwd),e)}async load(e){return
|
|
402
|
+
${t.map(r=>{let n=r.fromPort??"default",o=r.toPort??"default",s=r.loopBack?" (loopBack)":"";return`${r.from}.${n}\u2192${r.to}.${o}${s}`}).join(" ; ")}`}function bM(t){return t==="if"?["true","false"]:t==="loop"?["loop","done"]:["default"]}var vM={"n8n-nodes-base.set":"set","n8n-nodes-base.if":"if","n8n-nodes-base.merge":"merge","n8n-nodes-base.noOp":"passthrough","n8n-nodes-base.httpRequest":"http","n8n-nodes-base.manualTrigger":"trigger","n8n-nodes-base.scheduleTrigger":"trigger","n8n-nodes-base.cron":"trigger","n8n-nodes-base.webhook":"trigger"},Mr=class extends Error{constructor(r){super(`n8n import rejected: ${r.join("; ")}`);this.errors=r;this.name="N8nImportError"}errors};function ry(t,e){let r=kM(t),n=[],o=new Set,s=[];for(let[a,c]of r.nodes.entries()){if(typeof c?.name!="string"||c.name===""){n.push(`nodes[${a}] has a missing/empty name`);continue}if(o.has(c.name)){n.push(`duplicate node name "${c.name}"`);continue}if(o.add(c.name),typeof c.type!="string"||c.type===""){n.push(`node "${c.name}" has a missing/empty type`);continue}let l=vM[c.type];if(!l){n.push(`node "${c.name}" has unsupported type "${c.type}" (not in the import type map)`);continue}let d={id:c.name,kind:l,name:c.name,params:{...c.parameters??{},_n8nType:c.type}};l==="if"&&(d.outPorts=["true","false"]),s.push(d)}let i=r.connections?RM(r.connections,o,s,n):[];if(s.length===0&&n.length===0&&n.push("workflow has no nodes"),n.length>0)throw new Mr(n);return{name:typeof r.name=="string"&&r.name!==""?r.name:e,def:{id:e,nodes:s,edges:i}}}function kM(t){let e;if(typeof t=="string")try{e=JSON.parse(t)}catch(n){throw new Mr([`invalid JSON: ${n.message}`])}else e=t;if(!e||typeof e!="object")throw new Mr(["workflow must be a JSON object"]);let r=e;if(!Array.isArray(r.nodes))throw new Mr(["workflow.nodes must be an array"]);if(r.connections!==void 0&&(typeof r.connections!="object"||r.connections===null))throw new Mr(["workflow.connections must be an object"]);return{name:r.name,nodes:r.nodes,connections:r.connections??{}}}function RM(t,e,r,n){let o=new Map(r.map(i=>[i.id,i.kind])),s=[];for(let i of Object.keys(t).sort()){if(!e.has(i)){n.push(`connection source "${i}" is not a declared node`);continue}let a=t[i]?.main;if(Array.isArray(a))for(let c=0;c<a.length;c++){let l=SM(i,o.get(i),c,n),d=a[c];if(Array.isArray(d))for(let u of d){if(!u||typeof u.node!="string"){n.push(`connection from "${i}" has a malformed target`);continue}if(!e.has(u.node)){n.push(`connection from "${i}" targets missing node "${u.node}"`);continue}let p={from:i,to:u.node};l!=="default"&&(p.fromPort=l),s.push(p)}}}return s}function SM(t,e,r,n){return e==="if"?r===0?"true":r===1?"false":(n.push(`if node "${t}" has an unsupported output index ${r} (only 0/1)`),"default"):(r===0||n.push(`node "${t}" has an unmodeled multi-output index ${r} (only single-output supported)`),"default")}var dr=class{constructor(e,r){this.store=e;this.runtimeFactory=r}store;runtimeFactory;slots=new Map;async create(e){let r=jl(e.def);if(r.length>0)throw new lr(r);let n=new Date().toISOString(),o={id:e.id,name:e.name,def:e.def,active:e.active??!1,concurrency:e.concurrency??"queue",rev:1,createdAt:n,updatedAt:n};return await this.store.save(o),o}async update(e,r){let o={...await this.store.require(e),...r,updatedAt:new Date().toISOString()};if(r.def!==void 0){let s=jl(o.def);if(s.length>0)throw new lr(s)}return await this.store.save(o),o}async setActive(e,r){return this.update(e,{active:r})}async importN8n(e,r,n={}){let{name:o,def:s}=ry(r,e);return this.create({id:e,name:o,def:s,concurrency:n.concurrency})}async get(e){return this.store.require(e)}async describe(e,r){let n=await this.store.require(e);return ty(n,r)}async patch(e,r){let n=await this.store.require(e),o=r.baseRev!==void 0&&r.baseRev<n.rev,s={def:n.def,meta:{name:n.name,active:n.active,trigger:n.trigger??null}},i,a;try{let l=Zh(s,r);i=l.applied,a=l.target}catch(l){if(o&&l instanceof lr)return{ok:!1,conflict:{latestRev:n.rev}};throw l}let c={...n,def:a.def,name:a.meta.name??n.name,active:a.meta.active??n.active,trigger:a.meta.trigger??null,rev:n.rev+1,updatedAt:new Date().toISOString()};return await this.store.save(c),{ok:!0,rev:c.rev,applied:i}}async run(e,r){let n=await this.store.require(e),o={type:r?.type??"manual",payload:r?.payload},s=this.slotFor(e);if(s.pending>0)switch(n.concurrency){case"skip":return{workflowId:e,status:"skipped"};case"parallel":return this.startParallel(e,n.def,o);case"queue":return this.track(e,s,n.def,o,!0)}return this.track(e,s,n.def,o,!1)}pause(e){let r=this.slots.get(e);if(!r?.runtime||r.pending===0)throw new Error(`Workflow "${e}" has no active run to pause`);r.runtime.pause()}async resume(e,r={}){let n=this.slots.get(e);if(!n?.runtime)throw new Error(`Workflow "${e}" has no runtime to resume`);let o=n.runtime;r.extraBudget&&o.extendBudget(r.extraBudget),n.pending++;let s=o.run().then(i=>({workflowId:e,status:i.status,result:i})).finally(()=>{n.pending--});return n.tail=s.catch(()=>{}),s}async listActive(){return this.store.listActive()}slotFor(e){let r=this.slots.get(e);return r||(r={tail:Promise.resolve(),pending:0},this.slots.set(e,r)),r}track(e,r,n,o,s){r.pending++;let i=()=>{let l=this.runtimeFactory(n,o);return r.runtime=l,l.run().then(d=>({workflowId:e,status:d.status,result:d}))},c=(s?r.tail.then(i):i()).finally(()=>{r.pending--});return r.tail=c.catch(()=>{}),c}async startParallel(e,r,n){let s=await this.runtimeFactory(r,n).run();return{workflowId:e,status:s.status,result:s}}};function ny(t){return(e,r)=>new $s(e,{registry:t.registry,host:t.host,trigger:r.payload,now:t.now,gate:new Fs({trigger:r.type,maxNodeExecutions:t.budget.maxNodeExecutions,maxDurationMs:t.budget.maxDurationMs,allowUnattendedKinds:t.allowUnattendedKinds,now:t.now?()=>t.now().getTime():void 0})})}import{join as Bs}from"node:path";import{mkdir as wM,readdir as TM,rm as AM}from"node:fs/promises";D();function Hs(t){return Bs(re(t),"workflows")}function oy(t,e){return Bs(Hs(e),t,"workflow.json")}var ur=class{constructor(e){this.cwd=e;if(!e)throw new Error("WorkflowStore requires a project cwd")}cwd;async save(e){if(!e.id)throw new Error("WorkflowRecord.id is required");let r=Bs(Hs(this.cwd),e.id);await wM(r,{recursive:!0}),await cr(oy(e.id,this.cwd),e)}async load(e){return Zt(oy(e,this.cwd))}async require(e){let r=await this.load(e);if(!r)throw new Error(`Workflow "${e}" not found`);return r}async list(){let e;try{e=await TM(Hs(this.cwd))}catch{return[]}let r=[];for(let n of e){let o=await this.load(n);o&&r.push(o)}return r}async listActive(){return(await this.list()).filter(e=>e.active)}async delete(e){await AM(Bs(Hs(this.cwd),e),{recursive:!0,force:!0})}};function xM(t){return(t.content??[]).filter(r=>r.type==="text"&&typeof r.text=="string").map(r=>r.text).join(`
|
|
403
403
|
`)}function sy(t){let e=t.findTool??ve,r=t.fetchImpl??fetch;return{async runAgent(n){let o=await t.runAgent({agentId:n.agentId,prompt:n.prompt,signal:n.signal});return[cn({output:o})]},async invokeTool(n){let o=e(n.tool);if(!o)throw new Error(`workflow tool node: no qlogicagent tool named "${n.tool}"`);let s=`wf_${n.tool}_${Date.now().toString(36)}`,i=await o.execute(s,n.args,n.signal);return[cn({result:xM(i),details:i.details??null})]},async httpRequest(n){let o=await r(n.url,{method:n.method||"GET",headers:n.headers,body:n.body===void 0?void 0:typeof n.body=="string"?n.body:JSON.stringify(n.body),signal:n.signal}),s=await o.text(),i=o.headers.get("content-type")??"",a=s;if(i.includes("application/json")&&s.length>0)try{a=JSON.parse(s)}catch{a={__unparsedJson:s}}return[cn({status:o.status,ok:o.ok,body:a})]},async invokeMcp(n){let o=await t.invokeMcp({server:n.server,tool:n.tool,args:n.args,signal:n.signal});return[cn({result:o})]},async sendChannel(n){if(!t.sendChannel)throw new Error("workflow channel node: sendChannel requires the openclaw gateway host, none injected (channel/IM nodes are unavailable in standalone qlogicagent \u2014 D12/D13).");let o=await t.sendChannel({channel:n.channel,target:n.target,payload:n.payload,signal:n.signal});return[cn({sent:!0,result:o})]}}}var iy=null;function ay(t){iy=t}function qs(){return iy}var cy=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"],ly=["SUN","MON","TUE","WED","THU","FRI","SAT"];function PM(t){if(typeof t!="string"||t.trim()==="")throw new Error("cron must be a non-empty string");let e=t.trim().split(/\s+/);if(e.length!==5&&e.length!==6)throw new Error(`cron must have 5 or 6 fields, got ${e.length}: "${t}"`);let r=e.length===6,n=r?[{label:"second",min:0,max:59},{label:"minute",min:0,max:59},{label:"hour",min:0,max:23},{label:"day-of-month",min:1,max:31},{label:"month",min:1,max:12,names:cy},{label:"day-of-week",min:0,max:7,names:ly}]:[{label:"minute",min:0,max:59},{label:"hour",min:0,max:23},{label:"day-of-month",min:1,max:31},{label:"month",min:1,max:12,names:cy},{label:"day-of-week",min:0,max:7,names:ly}],o=n.map((c,l)=>({spec:c,raw:e[l],set:CM(e[l],n[l])})),s=c=>{let l=o.find(d=>d.spec.label===c);if(!l)throw new Error(`internal: missing cron field ${c}`);return l},i=s("day-of-week"),a=new Set;for(let c of i.set)a.add(c===7?0:c);return{hasSeconds:r,seconds:r?s("second").set:new Set([0]),minutes:s("minute").set,hours:s("hour").set,doms:s("day-of-month").set,months:s("month").set,dows:a,domRestricted:s("day-of-month").raw.trim()!=="*",dowRestricted:i.raw.trim()!=="*"}}function CM(t,e){let r=new Set;for(let n of t.split(","))IM(n,e,r);if(r.size===0)throw new Error(`cron ${e.label} expanded to an empty set: "${t}"`);return r}function IM(t,e,r){if(t==="")throw new Error(`cron ${e.label} has an empty list element`);let n=t,o=1,s=t.indexOf("/");if(s!==-1){n=t.slice(0,s);let c=t.slice(s+1);if(!/^\d+$/.test(c)||Number(c)<=0)throw new Error(`cron ${e.label} has an invalid step "/${c}"`);o=Number(c)}let i,a;if(n==="*")i=e.min,a=e.max;else{let c=n.indexOf("-");if(c!==-1){let l=$l(n.slice(0,c),e),d=$l(n.slice(c+1),e);if(l===void 0||d===void 0)throw new Error(`cron ${e.label} has an invalid range "${n}"`);if(l>d)throw new Error(`cron ${e.label} range "${n}" is descending`);i=l,a=d}else{let l=$l(n,e);if(l===void 0)throw new Error(`cron ${e.label} value "${n}" is out of range ${e.min}-${e.max}`);i=l,a=o===1?l:e.max}}for(let c=i;c<=a;c+=o)r.add(c)}function $l(t,e){let r;if(/^\d+$/.test(t))r=Number(t);else if(e.names){let n=e.names.indexOf(t.toUpperCase());if(n===-1)return;r=e.label==="month"?n+1:n}else return;if(!(r<e.min||r>e.max))return r}var EM=5*366+32;function Ul(t,e){let r=PM(t),n=new Date(e);r.hasSeconds?(n.setUTCMilliseconds(0),n.setUTCSeconds(n.getUTCSeconds()+1)):(n.setUTCSeconds(0,0),n.setUTCMinutes(n.getUTCMinutes()+1));for(let o=0;o<EM;o++){if(!r.months.has(n.getUTCMonth()+1)){n.setUTCMonth(n.getUTCMonth()+1,1),n.setUTCHours(0,0,0,0);continue}if(!_M(r,n)){n.setUTCDate(n.getUTCDate()+1),n.setUTCHours(0,0,0,0);continue}if(!r.hours.has(n.getUTCHours())){n.setUTCHours(n.getUTCHours()+1,0,0,0);continue}if(!r.minutes.has(n.getUTCMinutes())){n.setUTCMinutes(n.getUTCMinutes()+1,0,0);continue}if(r.hasSeconds&&!r.seconds.has(n.getUTCSeconds())){n.setUTCSeconds(n.getUTCSeconds()+1,0);continue}return n.getTime()}throw new Error(`cron "${t}" has no matching time within ~5 years of ${new Date(e).toISOString()}`)}function _M(t,e){let r=t.doms.has(e.getUTCDate()),n=t.dows.has(e.getUTCDay());return t.domRestricted&&t.dowRestricted?r||n:t.domRestricted?r:t.dowRestricted?n:!0}var MM={now:()=>Date.now(),setTimer:(t,e)=>setTimeout(t,e),clearTimer:t=>clearTimeout(t)},dy=2e9,Ws=class{controller;clock;onError;triggers=new Map;cronArms=new Map;started=!1;constructor(e){if(!e.controller)throw new Error("WorkflowScheduler requires a controller");if(typeof e.onError!="function")throw new Error("WorkflowScheduler requires an onError handler");this.controller=e.controller,this.clock=e.clock??MM,this.onError=e.onError}async start(){if(this.started)throw new Error("WorkflowScheduler already started");this.started=!0;let e=await this.controller.listActive();for(let r of e)this.registerTrigger(r.id,r.trigger??{type:"manual"})}stop(){for(let e of this.cronArms.values())this.clock.clearTimer(e.handle);this.cronArms.clear(),this.triggers.clear(),this.started=!1}async refresh(e){let r;try{r=await this.controller.get(e)}catch{this.unregister(e);return}if(!r.active){this.unregister(e);return}this.registerTrigger(e,r.trigger??{type:"manual"})}unregister(e){let r=this.cronArms.get(e);r&&(this.clock.clearTimer(r.handle),this.cronArms.delete(e)),this.triggers.delete(e)}registeredIds(){return[...this.triggers.keys()]}nextFireAt(e){return this.cronArms.get(e)?.fireAt}async onWebhook(e,r){let n=this.matchingIds(o=>o.type==="webhook"&&o.path===e);return Promise.all(n.map(o=>this.controller.run(o,{type:"webhook",payload:r})))}async onImMessage(e,r,n){let o=this.matchingIds(i=>i.type==="im-message"&&i.channel===e&&DM(i.match,r)),s={...n,channel:e,text:r};return Promise.all(o.map(i=>this.controller.run(i,{type:"im-message",payload:s})))}async triggerManual(e,r){return this.controller.run(e,{type:"manual",payload:r})}matchingIds(e){let r=[];for(let[n,o]of this.triggers)e(o)&&r.push(n);return r}registerTrigger(e,r){if(this.unregister(e),this.triggers.set(e,r),r.type==="schedule"){let n=Ul(r.cron,this.clock.now());this.armCron(e,r.cron,n)}}armCron(e,r,n){let o=Math.max(0,n-this.clock.now()),s={cron:r,fireAt:n,handle:void 0};o>dy?s.handle=this.clock.setTimer(()=>{this.cronArms.get(e)===s&&this.armCron(e,r,n)},dy):s.handle=this.clock.setTimer(()=>this.fireCron(e,s),o),this.cronArms.set(e,s)}fireCron(e,r){if(this.cronArms.get(e)!==r)return;let n;try{n=Ul(r.cron,r.fireAt)}catch(o){this.cronArms.delete(e),this.onError(o,e);return}this.armCron(e,r.cron,n),this.controller.run(e,{type:"schedule"}).catch(o=>this.onError(o,e))}};function DM(t,e){return t===void 0?!0:new RegExp(t).test(e)}var NM=1e3;function Ut(){if(!this.workflowController){let t=this.getActiveProjectRoot(),e=new ur(t),r=new at({log:{info:a=>process.stderr.write(`[workflow:pm] ${a}
|
|
404
404
|
`),warn:a=>process.stderr.write(`[workflow:pm] WARN ${a}
|
|
405
405
|
`)},onMcpToolCall:(a,c,l)=>this.handleMcpToolCall(a,c,l),sessionDir:uy.join(F(),"agent-logs")}),n=sy({runAgent:async({agentId:a,prompt:c,signal:l})=>{let d=a??"self",u=this.acpDetector.buildExternalDescriptor(d);if(!u)throw new Error(`workflow agent node: agent "${d}" is not available`);let p=`workflow-agent-${py().slice(0,8)}`;if(l?.aborted)throw new Error("workflow agent node aborted before dispatch");await r.spawn({memberId:p,name:`workflow-${d}`,cwd:t,prompt:c,external:u});try{let m=await r.sendTask(p,c);return typeof m=="string"?m:JSON.stringify(m)}finally{try{r.kill(p),r.remove(p)}catch(m){process.stderr.write(`[workflow:pm] WARN cleanup of ${p} failed: ${m instanceof Error?m.message:String(m)}
|
|
406
406
|
`)}}},invokeMcp:({server:a,tool:c,args:l})=>this.handleMcpToolCall(`workflow-mcp:${a}`,c,l),sendChannel:async({channel:a,target:c,payload:l})=>(this.sendNotification("workflow.channel.send",{channel:a,target:c,payload:l}),{queued:!0})}),o=new dn;for(let[a,c]of Object.entries(to))o.register(a,c);let s=ny({registry:o,host:n,budget:{maxNodeExecutions:NM}});this.workflowController=new dr(e,s),this.workflowStore=e,this.workflowProcessManager=r,ay(this.workflowController);let i=new Ws({controller:this.workflowController,onError:(a,c)=>{let l=a instanceof Error?a.message:String(a);process.stderr.write(`[workflow:scheduler] run error for ${c}: ${l}
|
|
407
407
|
`),this.sendNotification("workflow.runError",{workflowId:c,error:l})}});this.workflowScheduler=i,i.start().catch(a=>{process.stderr.write(`[workflow:scheduler] start failed: ${a instanceof Error?a.message:String(a)}
|
|
408
|
-
`)})}return this.workflowController}function Zt(t){return t.params??{}}function er(t,e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:e})}async function my(t){let e=Zt(t);if(!e.def)return er.call(this,t,"workflow.create requires `def`");let r=Ut.call(this),n=String(e.id??`wf_${py().slice(0,8)}`),o=await r.create({id:n,name:String(e.name??n),def:e.def,concurrency:e.concurrency,active:e.active===!0});o.active&&await this.workflowScheduler?.refresh(o.id),t.id!==void 0&&this.sendResponse(t.id,o)}async function gy(t){let e=Zt(t);if(!e.id)return er.call(this,t,"workflow.get requires `id`");let n=await Ut.call(this).get(String(e.id));t.id!==void 0&&this.sendResponse(t.id,n)}async function fy(t){let e=Zt(t);if(!e.id)return er.call(this,t,"workflow.describe requires `id`");let n=await Ut.call(this).describe(String(e.id));t.id!==void 0&&this.sendResponse(t.id,{rendered:n})}async function hy(t){let e=Zt(t);if(!e.id||!e.patch)return er.call(this,t,"workflow.patch requires `id` and `patch`");let r=Ut.call(this),n={patch:e.patch,baseRev:e.baseRev,scope:e.scope},o=await r.patch(String(e.id),n);await this.workflowScheduler?.refresh(String(e.id)),t.id!==void 0&&this.sendResponse(t.id,o)}async function yy(t){let e=Zt(t);if(!e.id)return er.call(this,t,"workflow.run requires `id`");let r=Ut.call(this),n=e.trigger??{type:"manual"},o=await r.run(String(e.id),n);t.id!==void 0&&this.sendResponse(t.id,o)}async function by(t){let e=Zt(t);if(!e.id||typeof e.active!="boolean")return er.call(this,t,"workflow.setActive requires `id` and boolean `active`");let n=await Ut.call(this).setActive(String(e.id),e.active);await this.workflowScheduler?.refresh(n.id),t.id!==void 0&&this.sendResponse(t.id,n)}async function vy(t){Ut.call(this);let r=await this.workflowStore.list();t.id!==void 0&&this.sendResponse(t.id,{workflows:r})}async function ky(t){let e=Zt(t);if(!e.id)return er.call(this,t,"workflow.delete requires `id`");Ut.call(this),await this.workflowStore.delete(String(e.id)),await this.workflowScheduler?.refresh(String(e.id)),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function Ry(t){let e=Zt(t);if(!e.channel||typeof e.text!="string")return er.call(this,t,"workflow.onImMessage requires `channel` and string `text`");Ut.call(this);let r=await this.workflowScheduler.onImMessage(String(e.channel),e.text,e.payload);t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}async function Sy(t){let e=Zt(t);if(!e.path)return er.call(this,t,"workflow.onWebhook requires `path`");Ut.call(this);let r=await this.workflowScheduler.onWebhook(String(e.path),e.payload);t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}import*as J from"node:fs";import*as ie from"node:path";D();D();import*as Me from"node:fs";import*as ro from"node:path";function Gs(t){let e=F(),r=re(t);Me.existsSync(r)||Me.mkdirSync(r,{recursive:!0});let n=ro.join(e,"INSTRUCTIONS.md"),o=ro.join(r,"INSTRUCTIONS.md");if(Me.existsSync(n)&&!Me.existsSync(o))try{Me.copyFileSync(n,o)}catch{}let s=Ju(),i=ir(t);if(Me.existsSync(s)&&!Me.existsSync(i))try{Me.mkdirSync(i,{recursive:!0});for(let a of Me.readdirSync(s)){if(!a.endsWith(".md"))continue;let c=ro.join(s,a),l=ro.join(i,a);Me.statSync(c).isFile()&&Me.copyFileSync(c,l)}}catch{}}var LM=["creating","running","completed","cancelled"];function OM(t){return typeof t=="string"&&LM.includes(t)}function wy(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let r=e.workspaceDir||ie.join(F(),"workspaces",e.name);if(e.groupId){let c=fs(e.groupId);if(c){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:c,deduplicated:!0});return}}let o=V().find(c=>c.name===e.name);if(!J.existsSync(r))try{J.mkdirSync(r,{recursive:!0})}catch{t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Cannot create workspace directory: ${r}`});return}let s=gs({name:e.name,workspaceDir:r,type:e.type??"personal",groupId:e.groupId,skipAutoSwitch:e.type==="solo"||e.type==="product"}),i=s.type==="solo"||s.type==="product";i||(wt(s.id),this.setActiveWorkdir(s.workspaceDir)),Gs(s.workspaceDir);let a=this.projectMemoryStoreFactory.create(s.workspaceDir);if(a.ensureInitialized(),i||(this.memdir=a),i||this.mediaPersistence.setProjectDir(s.workspaceDir),s.type==="solo"){let c=ie.join(re(s.workspaceDir),"solo-state.json");J.existsSync(c)||J.writeFileSync(c,JSON.stringify({agents:[],status:"idle",createdAt:new Date().toISOString()},null,2))}else if(s.type==="product"){let c=ie.join(re(s.workspaceDir),"product-state.json");J.existsSync(c)||J.writeFileSync(c,JSON.stringify({tasks:[],instances:[],status:"idle",createdAt:new Date().toISOString()},null,2))}if(this.sendNotification("project.created",{id:s.id,name:s.name,workspaceDir:s.workspaceDir,type:s.type}),i||this.sendNotification("project.switched",{id:s.id,name:s.name,workspaceDir:s.workspaceDir}),t.id!==void 0){let c={ok:!0,project:s};o&&(c.warning=`\u5DF2\u5B58\u5728\u540C\u540D\u9879\u76EE\u300C${o.name}\u300D\uFF08\u4F4D\u4E8E ${o.workspaceDir}\uFF09\uFF0C\u5EFA\u8BAE\u4FEE\u6539\u540D\u79F0\u4EE5\u4FBF\u533A\u5206`),this.sendResponse(t.id,c)}}function Ty(t){let e=V();t.id!==void 0&&this.sendResponse(t.id,{projects:e})}function Ay(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Ee(e.projectId),n=Yc(e.projectId);if(!n.deleted){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot delete project (not found or is default project)"});return}let o=!1,s;if(r?.workspaceDir){let i=ie.join(F(),"workspaces"),a=ie.resolve(r.workspaceDir);if(a.startsWith(ie.resolve(i)+ie.sep)){try{this.mediaPersistence?.releaseProjectDir?.(a)}catch{}for(let c=0;c<3;c++)try{J.rmSync(a,{recursive:!0,force:!0}),o=!0;break}catch(l){if(c<2&&(l.code==="EBUSY"||l.code==="EPERM"||l.code==="ENOTEMPTY")){let d=Date.now();for(;Date.now()-d<200;);}else{s=l.message??String(l);break}}}else s="\u9879\u76EE\u76EE\u5F55\u4E0D\u5728\u6258\u7BA1\u76EE\u5F55\u4E0B\uFF0C\u4E0D\u4F1A\u81EA\u52A8\u5220\u9664"}this.sendNotification("project.deleted",{id:e.projectId}),n.switchedTo&&(this.setActiveWorkdir(n.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:n.switchedTo,dirDeleted:o,dirDeleteError:s})}function xy(t){let e=V(),r=ie.join(F(),"workspaces"),n=ie.resolve(r)+ie.sep,o=0,s=[];for(let a of e)if(a.type!=="default"){if(Yc(a.id),o++,a.workspaceDir){let c=ie.resolve(a.workspaceDir);try{this.mediaPersistence?.releaseProjectDir?.(c)}catch{}for(let l=0;l<3;l++)try{J.existsSync(c)&&J.rmSync(c,{recursive:!0,force:!0});break}catch(d){if(l<2&&(d.code==="EBUSY"||d.code==="EPERM"||d.code==="ENOTEMPTY")){let u=Date.now();for(;Date.now()-u<300;);}else{s.push(`${a.name}: ${d.message??d}`);break}}}this.sendNotification("project.deleted",{id:a.id})}if(J.existsSync(r)){let a=V().find(d=>d.type==="default"),c=new Set;a?.workspaceDir&&c.add(ie.resolve(a.workspaceDir));let l=d=>{try{let u=J.readdirSync(d,{withFileTypes:!0});for(let p of u){if(!p.isDirectory())continue;let m=ie.join(d,p.name);if(!c.has(ie.resolve(m))){if(p.name==="groups"){l(m);try{J.readdirSync(m).length===0&&J.rmdirSync(m)}catch{}continue}try{J.rmSync(m,{recursive:!0,force:!0})}catch(g){s.push(`orphan:${p.name}: ${g.message??g}`)}}}}catch{}};l(r)}let i=V().find(a=>a.type==="default");i&&(this.setActiveWorkdir(i.workspaceDir),this.sendNotification("project.switched",{id:i.id,name:i.name,workspaceDir:i.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o,dirErrors:s.length?s:void 0})}function Py(t){let e=t.params;if(!e?.projectId||!e?.newName){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required params: projectId, newName"});return}let r=wg(e.projectId,e.newName);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot rename project (not found, is default, or name already taken)"});return}let n=ie.join(F(),"workspaces"),o=ie.resolve(r.workspaceDir);if(o.startsWith(ie.resolve(n)+ie.sep)){let s=ie.join(n,e.newName);if(J.existsSync(o)&&!J.existsSync(s))try{J.renameSync(o,s),Tg(e.projectId,s),r.workspaceDir=s,this.getActiveProjectRoot()===o&&this.setActiveWorkdir(s)}catch{}}this.sendNotification("project.renamed",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function Cy(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Ag(e.projectId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot archive project (not found or is default project)"});return}this.sendNotification("project.archived",{id:e.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:r.switchedTo})}function Iy(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=xg(e.projectId);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot unarchive project (not found or not archived)"});return}this.sendNotification("project.unarchived",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function Ey(t){let e=t.params;if(!e?.groupId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: groupId"});return}let r=Pg(e.groupId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"No active project with this groupId"});return}this.sendNotification("project.deleted",{id:r.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:r.projectId})}function _y(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"projectId is required"});return}let r={};if("planStatus"in e){if(e.planStatus!==void 0&&!OM(e.planStatus)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Invalid planStatus: ${e.planStatus}`});return}r.planStatus=e.planStatus}"planAgents"in e&&(r.planAgents=e.planAgents),"planWinnerId"in e&&(r.planWinnerId=e.planWinnerId),"leaderSessionId"in e&&(r.leaderSessionId=e.leaderSessionId);let n=Rg(e.projectId,r);t.id!==void 0&&this.sendResponse(t.id,{ok:n})}import{randomUUID as Hl}from"node:crypto";import*as Ue from"node:fs";import*as mr from"node:path";var pr=class{sessionId;_trustAccepted=!1;_modelUsage=new Map;_totalInputTokens=0;_totalOutputTokens=0;_turnCount=0;_toolCallCount=0;_listeners=new Set;constructor(e){this.sessionId=e}get trustAccepted(){return this._trustAccepted}setTrustAccepted(e){this._trustAccepted=e,this.notifyListeners()}get totalInputTokens(){return this._totalInputTokens}get totalOutputTokens(){return this._totalOutputTokens}get turnCount(){return this._turnCount}get toolCallCount(){return this._toolCallCount}getModelUsage(e){return this._modelUsage.get(e)}getAllModelUsage(){let e={};for(let[r,n]of this._modelUsage)e[r]={...n};return e}addUsage(e,r){this._totalInputTokens+=e.inputTokens,this._totalOutputTokens+=e.outputTokens;let n=this._modelUsage.get(r);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.cacheRead+=e.cacheRead??0,n.cacheCreation+=e.cacheWrite??0):this._modelUsage.set(r,{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheRead:e.cacheRead??0,cacheCreation:e.cacheWrite??0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0}),this.notifyListeners()}addMediaUsage(e,r,n){let o=this._modelUsage.get(e),s=o??{inputTokens:0,outputTokens:0,cacheRead:0,cacheCreation:0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0};switch(o||this._modelUsage.set(e,s),s.mediaCalls+=1,r){case"per_second":s.mediaDurationSeconds+=n;break;case"per_character":s.mediaCharacters+=n;break;case"per_token":s.outputTokens+=n;break}this.notifyListeners()}recordToolCall(){this._toolCallCount++}recordTurnCompleted(){this._turnCount++}createSnapshot(){return{sessionId:this.sessionId,modelUsage:this.getAllModelUsage(),totalInputTokens:this._totalInputTokens,totalOutputTokens:this._totalOutputTokens,turnCount:this._turnCount,lastSavedAt:Date.now()}}restoreFromSnapshot(e){if(e.sessionId!==this.sessionId)return!1;this._totalInputTokens=e.totalInputTokens,this._totalOutputTokens=e.totalOutputTokens,this._turnCount=e.turnCount,this._modelUsage.clear();for(let[r,n]of Object.entries(e.modelUsage))this._modelUsage.set(r,{...n});return this.notifyListeners(),!0}onStateChange(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}notifyListeners(){for(let e of this._listeners)try{e()}catch{}}};import*as My from"node:fs";import*as Fl from"node:path";D();var mn=class{getSessionsRoot(e){let r=Ee(e);if(!r)throw new Error(`Project not found: ${e}`);return Mt(r.workspaceDir)}getProjectWorkspaceDir(e){let r=Ee(e);if(!r)throw new Error(`Project not found: ${e}`);return r.workspaceDir}getSessionDir(e,r){return Fl.join(this.getSessionsRoot(e),r)}resolveWorkspaceDir(e,r){if(r)return this.getProjectWorkspaceDir(r);let n=V();for(let o of n){let s=Mt(o.workspaceDir),i=Fl.join(s,e);try{if(My.existsSync(i))return o.workspaceDir}catch{}}return this.getActiveProjectWorkspaceDir()}getActiveProjectWorkspaceDir(){let e=oe();if(e)return e.workspaceDir;let r=V();if(r.length>0)return r[0].workspaceDir;throw new Error("No active project available")}getActiveProjectId(){let e=oe();if(e)return e.id;let r=V();if(r.length>0)return r[0].id;throw new Error("No active project available")}};import{randomUUID as Dy}from"node:crypto";async function Ny(t,e){let r=new Date(t.lastActiveAt).getTime();if(Date.now()-r<$u)return{split:!1,activeSessionId:t.sessionId};let s=Dy(),i=new Date().toISOString();await Qe(t.sessionId,{sealedAt:i},e);let a=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981] ${t.taskSummary}`:void 0;return await Qe(s,{sessionId:s,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:a},e),{split:!0,activeSessionId:s,sealedSessionId:t.sessionId}}async function Ly(t,e){if(t.type!=="group")return{split:!1,activeSessionId:t.sessionId};if(t.turnCount<Uu)return{split:!1,activeSessionId:t.sessionId};let r=Dy(),n=new Date().toISOString();await Qe(t.sessionId,{sealedAt:n},e);let o=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981 \u2014 \u56E0\u6D88\u606F\u6570\u8FBE\u5230\u4E0A\u9650\u81EA\u52A8\u5207\u5206] ${t.taskSummary}`:void 0;return await Qe(r,{sessionId:r,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:o},e),{split:!0,activeSessionId:r,sealedSessionId:t.sessionId}}D();var $e=new mn;function pt(t,e="Unknown error"){return t instanceof Error?t.message:e}function jM(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}function gn(t,e,r){if(r)return $e.resolveWorkspaceDir(e,r);let n=t.getActiveProjectRoot();if(n){let o=mr.join(Mt(n),jM(e));try{if(Ue.existsSync(o))return n}catch{}}return $e.resolveWorkspaceDir(e)}function Oy(t){let e=t.params,r=e?.id??Hl();this.log(`[thread.create] id=${r} title=${e?.title??"(none)"}`),e?.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.currentSessionId=r,this.sessionState=new pr(r),this.sessionTaskDomain=void 0,this.memoryPrefetchState=ht(),this.enableIdleDream(),t.id!==void 0&&this.sendResponse(t.id,{id:r,title:e?.title,status:"active",createdAt:new Date().toISOString()})}async function jy(t){let e=t.params,r=e?.limit??20;try{let n=e?.projectId??$e.getActiveProjectId(),o=$e.getProjectWorkspaceDir(n),i=(await Dt(r,o)).map(a=>({id:a.sessionId,title:a.title,status:"active",turnCount:a.messageCount,createdAt:a.createdAt,lastActiveAt:a.lastActiveAt}));t.id!==void 0&&this.sendResponse(t.id,{threads:i})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list threads: ${pt(n)}`})}}async function $y(t){let e=t.params,r=e?.sessionId??Hl();try{let n=e?.projectId??$e.getActiveProjectId(),o=$e.getProjectWorkspaceDir(n);await Qe(r,{sessionId:r,title:e?.title,type:e?.type,ownerId:e?.ownerId,groupKey:e?.groupKey,groupName:e?.groupName,groupPlatform:e?.groupPlatform,projectId:n},o),t.id!==void 0&&this.sendResponse(t.id,{sessionId:r,title:e?.title})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to create session: ${pt(n)}`})}}async function Uy(t){let e=t.params;if(t.id===void 0)return;let r=e?.platform??"desktop",n=e?.chatId,o=e?.chatType,s=e?.userId??"local";try{if(r==="desktop"&&n){let d=e?.projectId??$e.getActiveProjectId(),u=$e.getProjectWorkspaceDir(d),m=(await Dt(500,u)).find(g=>g.sessionId===n);if(m){this.sendResponse(t.id,{sessionId:n,title:m.title,type:m.type??"personal",ownerId:s,projectId:d});return}await Qe(n,{sessionId:n,type:"personal",ownerId:s,projectId:d},u),this.sendResponse(t.id,{sessionId:n,type:"personal",ownerId:s,projectId:d});return}if(o==="group"&&n&&r){let d=`group:${r}:${n}`,u=V();for(let p of u){if(!p.workspaceDir)continue;let g=(await Dt(500,p.workspaceDir)).find(f=>f.groupKey===d&&!f.sealedAt);if(g){let f=Kt(g.sessionId,p.workspaceDir);if(f){let h=await Ny(f,p.workspaceDir);if(h.split){this.sendResponse(t.id,{sessionId:h.activeSessionId,title:void 0,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:p.id,previousSessionId:h.sealedSessionId});return}}this.sendResponse(t.id,{sessionId:g.sessionId,title:g.title,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:p.id});return}}}let i=Hl(),a=$e.getActiveProjectId(),c=$e.getProjectWorkspaceDir(a),l=o==="group"?`group:${r}:${n}`:void 0;await Qe(i,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a},c),this.sendResponse(t.id,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a})}catch(i){this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resolve session: ${pt(i)}`})}}async function Fy(t){let e=t.params,r=e?.limit??50;try{let n;if(e?.projectId){let s=Ee(e.projectId);if(!s){t.id!==void 0&&this.sendResponse(t.id,{sessions:[]});return}let i=s.workspaceDir;n=await Dt(r*2,i),n=n.filter(a=>a.projectId===e.projectId);for(let a of n)a.projectId=e.projectId}else{let s=V(),i=new Set,a=[];for(let c of s){if(!c.workspaceDir)continue;let l=await Dt(r,c.workspaceDir);for(let d of l)i.has(d.sessionId)||d.projectId&&(i.add(d.sessionId),a.push(d))}a.sort((c,l)=>c.lastActiveAt>l.lastActiveAt?-1:c.lastActiveAt<l.lastActiveAt?1:0),n=a}e?.archived===!0?n=n.filter(s=>s.archivedAt!=null):e?.archived===!1&&(n=n.filter(s=>s.archivedAt==null));let o=n.slice(0,r).map(s=>({sessionId:s.sessionId,title:s.title,type:s.type??"personal",lastActiveAt:s.lastActiveAt,pinnedAt:s.pinnedAt??null,archivedAt:s.archivedAt??null,sealedAt:s.sealedAt??null,projectId:s.projectId,previousSessionId:s.previousSessionId??null,carryoverSummary:s.carryoverSummary??null}));t.id!==void 0&&this.sendResponse(t.id,{sessions:o})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list sessions: ${pt(n)}`})}}async function Hy(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=gn(this,e.sessionId,e.projectId),o=(await Dt(500,r)).find(s=>s.sessionId===e.sessionId);t.id!==void 0&&this.sendResponse(t.id,{session:o?{sessionId:o.sessionId,title:o.title,type:o.type,lastActiveAt:o.lastActiveAt,pinnedAt:o.pinnedAt??null,archivedAt:o.archivedAt??null,projectId:o.projectId}:null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get session: ${pt(r)}`})}}async function By(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=gn(this,e.sessionId,e.projectId),n=await Ga(e.sessionId,r);if(!n){t.id!==void 0&&this.sendResponse(t.id,{messages:[],total:0});return}let o=n.messages,s=e.limit&&e.limit>0?e.limit:o.length,i=o.slice(-s);t.id!==void 0&&this.sendResponse(t.id,{messages:i,total:o.length})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get messages: ${pt(r)}`})}}async function qy(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=gn(this,e.sessionId,e.projectId),n=await Qe(e.sessionId,{...e.title!==void 0?{title:e.title}:{},...e.pinnedAt!==void 0?{pinnedAt:e.pinnedAt}:{},...e.archivedAt!==void 0?{archivedAt:e.archivedAt}:{}},r);n&&this.sendNotification("session.info",{sessionId:e.sessionId,title:n.title,pinnedAt:n.pinnedAt??null,archivedAt:n.archivedAt??null,projectId:e.projectId||void 0}),t.id!==void 0&&this.sendResponse(t.id,{ok:n!==null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to update session: ${pt(r)}`})}}async function Wy(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=gn(this,e.sessionId,e.projectId);await Ka(e.sessionId,r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete session: ${pt(r)}`})}}async function Gy(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}try{let r=$e.getProjectWorkspaceDir(e.projectId),n=(await Dt(1e4,r)).filter(s=>s.projectId===e.projectId),o=0;for(let s of n)await Ka(s.sessionId,r),o++;t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete all sessions: ${pt(r)}`})}}async function Ky(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=gn(this,e.sessionId,e.projectId);await Qe(e.sessionId,{archivedAt:new Date().toISOString()},r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to archive session: ${pt(r)}`})}}async function zy(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"sessionId is required"});return}try{let n=gn(this,r,e?.projectId),o=await Ga(r,n);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Session not found: ${r}`});return}o.messages&&o.messages.length>0&&this.sessionHistory.saveResumedSession(r,o.messages),t.id!==void 0&&this.sendResponse(t.id,{metadata:o.metadata,messages:o.messages})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resume session: ${pt(n)}`})}}function Vy(t){let e=this.currentSessionId||"default",r=this.sessionState?.createSnapshot(),n,o=this.getActiveProjectRoot();o&&(n=mr.join(Mt(o),e));let s={sessionId:e,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:n,agentHome:F(),settings:de()},usage:r?{turnCount:r.turnCount,inputTokens:r.totalInputTokens,outputTokens:r.totalOutputTokens}:void 0};t.id!==void 0&&this.sendResponse(t.id,s)}function Xy(t){let e=t.params,r=null;if(e?.projectId)r=Ee(e.projectId);else if(e?.projectName){let s=V(),i=e.projectName.toLowerCase();if(r=s.find(a=>a.name.toLowerCase()===i)??null,r||(r=s.find(a=>a.name.toLowerCase().includes(i))??null),!r){let a=s.map(c=>c.name).slice(0,10);t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`No project matching "${e.projectName}". Available: ${a.join(", ")||"(none)"}`});return}}else{t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId or projectName"});return}if(!r||r.status!=="active"){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Project not found or archived: ${e.projectId??e.projectName}`});return}let n=e.workspaceDir??r.workspaceDir;if(!Ue.existsSync(n)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Workspace directory does not exist: ${n}`});return}let o=wt(r.id);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Switch failed"});return}this.setActiveWorkdir(o.workspaceDir),this.sendNotification("project.switched",{id:o.id,name:o.name,workspaceDir:o.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:o})}function Yy(t){let e=oe(),r=V();t.id!==void 0&&this.sendResponse(t.id,{sessionId:this.currentSessionId,activeProject:e,projects:r})}async function Jy(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,{ok:!1});return}let n=V();for(let o of n)try{let s=$e.getProjectWorkspaceDir(o.id),i=await Kt(r,s);if(i&&i.projectId===o.id){wt(o.id),this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} for session ${r}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}catch{}if(e?.projectName){let o=n.find(s=>s.name===e.projectName);if(o){let s=$e.getProjectWorkspaceDir(o.id);this.getActiveProjectRoot()!==s&&(this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} by name "${e.projectName}"`)),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}t.id!==void 0&&this.sendResponse(t.id,{ok:!1})}async function Qy(t){let e=t.params,{sessionId:r,fromProjectId:n,toProjectId:o}=e??{};if(!r||!n||!o){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"sessionId, fromProjectId, and toProjectId are required");return}if(n===o){t.id!==void 0&&this.sendResponse(t.id,{ok:!0});return}let s=Ee(n),i=Ee(o);if(!s||!i){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"Source or target project not found");return}let a=mr.join($e.getProjectWorkspaceDir(n),".qlogicagent","sessions",r),c=mr.join($e.getProjectWorkspaceDir(o),".qlogicagent","sessions",r);if(!Ue.existsSync(a)){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,`Session ${r} not found in project ${n}`);return}try{Ue.mkdirSync(mr.dirname(c),{recursive:!0}),Ue.cpSync(a,c,{recursive:!0});let l=mr.join(c,"metadata.json");if(Ue.existsSync(l)){let d=JSON.parse(Ue.readFileSync(l,"utf-8"));d.projectId=o,Ue.writeFileSync(l,JSON.stringify(d,null,2))}Ue.rmSync(a,{recursive:!0,force:!0}),this.sendNotification("session-update",{sessionId:r,projectId:o}),this.log(`[session.moveToProject] moved ${r}: ${n} \u2192 ${o}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o})}catch(l){let d=pt(l);this.log(`[session.moveToProject] error: ${d}`),t.id!==void 0&&this.sendError(t.id,y.INTERNAL_ERROR,`Move failed: ${d}`)}}We();function $M(t){return t.length<=8?"****":`${t.slice(0,3)}***${t.slice(-4)}`}function Ze(t,e,r,n=y.INTERNAL_ERROR){if(e.id!==void 0){if(typeof t.sendError=="function"){t.sendError(e.id,n,r);return}t.sendResponse(e.id,void 0,{code:n,message:r})}}function Bl(t,e){Ze(t,e,Bo)}function UM(t){let e={};for(let r of t)for(let n of r.purposes)e[n]??=[],e[n].push(r);return e}async function FM(){let t=M(),e=await Cn(t);return t.save(),e}async function Zy(t){try{return await FM(),!0}catch(e){if(t)throw e;return!1}}function ql(t=M()){try{return fp()}catch{return t.getKnownProviderDef(ne)?.baseUrl??"https://www.qlogicagent.com"}}async function eb(t){let e=M(),r=e.getKeyForProvider(ne);if(!r){if(t)throw new Error("LLMRouter API Key is required to fetch available models.");return!1}let n=e.getProviderStatus(ne)?.baseUrl??ql(e);try{if((await Za(e,{baseUrl:n,apiKey:r})).length===0){if(t)throw new Error("LLMRouter did not return any available models for this API Key.");return!1}return e.save(),!0}catch(o){if(t)throw o;return!1}}async function tb(t=!1){let e=M();if(!!e.getProviderStatus(ne)?.keys.length)return await eb(!1)?!0:Zy(t);let o=e.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId).some(s=>s!=="deepseek"&&s!==ne);return!t&&!o?!1:Zy(t)}async function rb(t){try{let e=M(),r=["deepseek",ne].map(s=>e.getKnownProviderDef(s)).filter(s=>!!s).map(s=>({id:s.id,displayName:s.name,baseUrl:s.baseUrl,modelCount:s.models?.length??0})),n=await Ja().catch(()=>[]),o=n.map(s=>({id:s.id,displayName:yp(s),baseUrl:Qa(s)??"",modelCount:s.models?.length??0}));o.unshift({id:ne,displayName:Xa,baseUrl:ql(e),modelCount:n.reduce((s,i)=>s+(i.models?.length??0),0)});for(let s of r.reverse()){let i=o.findIndex(a=>a.id===s.id);if(i>=0){s.id!==ne&&o.splice(i,1,s);continue}o.unshift(s)}t.id!==void 0&&this.sendResponse(t.id,{providers:o})}catch(e){Ze(this,t,e instanceof Error?e.message:String(e))}}async function nb(t){let e=t.params;if(!e?.providerId||!e?.key){Ze(this,t,"Required: providerId (string), key (string)",y.INVALID_PARAMS);return}let{providerId:r,key:n,label:o}=e,s=M(),i,a=!1;try{let c=await mb(r);if(!c){Ze(this,t,`Unknown provider: ${r}`,y.INVALID_PARAMS);return}let l=s.getProviderStatus(r);if(l?.keys.some(d=>d.key===n)){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"\u8BE5 Key \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u6DFB\u52A0"});return}if(a=!l,s.addProvider(r,{baseUrl:c}),i=s.addKey(r,n,{label:o}),r===ne&&(await Za(s,{baseUrl:c,apiKey:n})).length===0)throw new Error("LLMRouter did not return any available models for this API Key.");for(let d of Pn)if(!s.getBinding(d)){let u=s.listModels({purpose:d,provider:r,enabledOnly:!0});u.length===0&&(u=s.listModels({purpose:d,provider:r}),u[0]&&s.enableModel(u[0].id)),u.length>0&&s.setBinding(d,u[0].id)}s.setKeyHealth(i,"healthy"),s.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,keyId:i,providerId:r})}catch(c){i&&(s.removeKey(i),a&&s.removeProvider(r));let l=c instanceof Error?c.message:Bo;Ze(this,t,l)}}function ob(t){let e=t.params;if(!e?.keyId){Ze(this,t,"Required: keyId (string)",y.INVALID_PARAMS);return}let r=M();r.removeKey(e.keyId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function sb(t){let e=t.params;if(!e?.keyId||typeof e.enabled!="boolean"){Ze(this,t,"Required: keyId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=M();r.updateKey(e.keyId,{enabled:e.enabled}),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function ib(t){let e=t.params;if(!e?.modelId||typeof e.enabled!="boolean"){Ze(this,t,"Required: modelId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=M();e.enabled?r.enableModel(e.modelId):r.disableModel(e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function ab(t){let e=t.params;try{await tb(!1);let r=M(),n=new Set(r.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId)),o=r.listModels({purpose:e?.purpose,provider:e?.provider}).filter(s=>r.hasConfiguredKeyForProviderVariant(s.provider));t.id!==void 0&&this.sendResponse(t.id,{models:o,grouped:UM(o),configuredProviderIds:[...n]})}catch{Bl(this,t)}}function cb(t){let e=t.params;if(!e?.purpose||!e?.modelId){Ze(this,t,"Required: purpose (string), modelId (string)",y.INVALID_PARAMS);return}try{let r=M();r.setBinding(e.purpose,e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){Ze(this,t,r instanceof Error?r.message:String(r),y.INVALID_PARAMS)}}function lb(t){let e=t.params;if(!e?.purpose){Ze(this,t,"Required: purpose (string)",y.INVALID_PARAMS);return}let r=M(),n=r.getBinding(e.purpose);t.id!==void 0&&this.sendResponse(t.id,{model:n?{id:n.id,provider:n.provider,model:n.model,displayName:n.displayName,purposes:n.purposes,enabled:n.enabled}:null,available:r.isAvailable(e.purpose)})}async function db(t){try{await tb(!1);let e=M(),r=e.getAllProviderStatus().map(s=>({providerId:s.providerId,displayName:s.providerId===ne?Xa:s.providerId,baseUrl:s.baseUrl,keyCount:s.keys.length,healthyKeys:s.keys.filter(i=>i.healthStatus==="healthy"&&i.enabled).length,totalKeys:s.keys.length,keys:s.keys.map(i=>({id:i.id,label:i.label,maskedKey:$M(i.key),enabled:i.enabled,health:i.healthStatus}))})),n=e.getAllBindings(),o={};for(let s of Pn){let i=n[s];o[s]={bound:!!i,modelId:i?.id,modelName:i?.displayName,available:e.isAvailable(s)}}t.id!==void 0&&this.sendResponse(t.id,{providers:r,purposes:o})}catch{Bl(this,t)}}async function ub(t){try{let e=M();e.load(),await eb(!1)||await Cn(e),e.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,catalogRefreshed:!0})}catch{Bl(this,t)}}async function pb(t){let e=t.params;if(!e?.providerId||!e?.apiKey){Ze(this,t,"providerId and apiKey required",y.INVALID_PARAMS);return}try{let r=e.baseUrl||await mb(e.providerId);if(!r){Ze(this,t,`Unknown provider: ${e.providerId}`,y.INVALID_PARAMS);return}let n=e.providerId===ne?Ya(r):`${r.replace(/\/$/,"")}/models`,o=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(1e4)});if(o.ok){t.id!==void 0&&this.sendResponse(t.id,{valid:!0,status:o.status});return}let s=await o.text().catch(()=>"");t.id!==void 0&&this.sendResponse(t.id,{valid:!1,status:o.status,error:s.slice(0,500)})}catch(r){let n=r instanceof Error?r.message:String(r);t.id!==void 0&&this.sendResponse(t.id,{valid:!1,status:0,error:n})}}async function mb(t){if(t===ne)return ql();let e=M().getKnownProviderDef(t);if(e?.baseUrl)return e.baseUrl;let r=await bp(t);return r?Qa(r):void 0}D();import*as q from"node:fs";import*as ce from"node:path";import{join as HM}from"node:path";import{readFileSync as BM,writeFileSync as qM,mkdirSync as WM}from"node:fs";var Dr=null,Wl=!1;function gb(t){return HM(t,"skill-stats.json")}function Gl(t){if(Dr)return Dr;try{Dr=JSON.parse(BM(gb(t),"utf8"))}catch{Dr={}}return Dr}function GM(t){if(!(!Wl||!Dr))try{WM(t,{recursive:!0}),qM(gb(t),JSON.stringify(Dr,null,2),"utf8"),Wl=!1}catch{}}function Ks(t,e,r){let n=Gl(t);n[e]||(n[e]={invokeCount:0,activeCount:0,positiveCount:0,negativeCount:0}),n[e].invokeCount++,n[e].lastUsedAt=new Date().toISOString(),r?n[e].positiveCount++:n[e].negativeCount++,n[e].invokeCount>0&&(n[e].successRate=(n[e].invokeCount-n[e].negativeCount)/n[e].invokeCount),Wl=!0,GM(t)}function fb(t,e){return Gl(t)[e]}function hb(t){return Gl(t)}function yb(t){try{let e=q.readFileSync(t,"utf8"),r=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),n=e.match(/^---\n[\s\S]*?^description:\s*(.+)/m);return{version:r?.[1],description:n?.[1]?.trim()}}catch{return{}}}function bb(t){return{key:`capability.skill.${t}.name`,fallback:t}}function vb(t,e){return{key:`capability.skill.${t}.description`,fallback:e??""}}function kb(t){return t.startsWith("auto-skill-")||t.startsWith("test-skill-")}function KM(t){return t==="active"||t==="stale"||t==="archived"}function Rb(t){let r=t.params?.projectId,n=this.getActiveProjectRoot();if(r&&this.projectLocator){let a=this.projectLocator.resolveProjectRoot(r);a&&(n=a)}let o=n?_t(n):void 0,s=yt(),i=[];if(o&&q.existsSync(o))for(let a of q.readdirSync(o)){let c=ce.join(o,a);if(!q.statSync(c).isDirectory())continue;let l=ce.join(c,"SKILL.md"),d=ce.join(c,"SKILL.md.disabled"),u=q.existsSync(l)?l:null;if(u||q.existsSync(d)){let p=u?yb(u):{};i.push({id:`project:${a}`,name:a,path:c,active:!!u,scope:"project",category:"automation",displayName:bb(a),displayDescription:vb(a,p.description),fallbackName:a,fallbackDescription:p.description??"",systemGenerated:kb(a),version:p.version,description:p.description})}}if(q.existsSync(s))for(let a of q.readdirSync(s)){let c=ce.join(s,a);try{if(!q.statSync(c).isDirectory())continue}catch{continue}let l=ce.join(c,"SKILL.md"),d=ce.join(c,"SKILL.md.disabled"),u=q.existsSync(l)?l:null;if(u||q.existsSync(d)){let p=u?yb(u):{};i.push({id:`global:${a}`,name:a,path:c,active:!!u,scope:"global",category:"automation",displayName:bb(a),displayDescription:vb(a,p.description),fallbackName:a,fallbackDescription:p.description??"",systemGenerated:kb(a),version:p.version,description:p.description})}}t.id!==void 0&&this.sendResponse(t.id,{skills:i})}function Sb(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?_t(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=ce.join(o,r),i=ce.join(s,"SKILL.md.disabled"),a=ce.join(s,"SKILL.md");if(q.existsSync(a)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}if(q.existsSync(i))try{q.renameSync(i,a);let c=W(),l=ge(c),d=At(l,r);d.state!=="active"&&(d.state="active",d.staleAt=void 0,d.archivedAt=void 0),ke(c,l),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"activate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to activate skill: ${c instanceof Error?c.message:c}`})}else t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found`})}function wb(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?_t(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=ce.join(o,r),i=ce.join(s,"SKILL.md"),a=ce.join(s,"SKILL.md.disabled");if(!q.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}try{q.renameSync(i,a),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"deactivate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to deactivate skill: ${c instanceof Error?c.message:c}`})}}function Tb(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=W(),o=ge(n);if(o.records[r]?.pinned){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Skill "${r}" is pinned. Unpin it first.`});return}let s=e?.scope??"project",i;if(s==="global")i=ce.join(yt(),r);else{let a=this.getActiveProjectRoot(),c=a?_t(a):void 0;if(!c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}i=ce.join(c,r)}if(!q.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in ${s} scope`});return}try{q.rmSync(i,{recursive:!0,force:!0}),ct(),vs(o,r),ke(n,o),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deleted:r,scope:s}),this.sendNotification("skills.updated",{action:"delete",name:r})}catch(a){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete skill: ${a instanceof Error?a.message:a}`})}}function Ab(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=this.getActiveProjectRoot(),o=n?_t(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=ce.join(o,r),i=ce.join(s,"SKILL.md");if(!q.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in project scope`});return}let a=yt(),c=ce.join(a,r);try{q.mkdirSync(c,{recursive:!0});let l=q.readdirSync(s);for(let d of l){let u=q.readFileSync(ce.join(s,d));q.writeFileSync(ce.join(c,d),u)}e?.keepLocal||q.rmSync(s,{recursive:!0,force:!0}),ct(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,promoted:r,globalPath:c,removedFromProject:!e?.keepLocal})}catch(l){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to promote skill: ${l instanceof Error?l.message:l}`})}}function xb(t){let e=t.params,r=W();if(e?.name){let n=fb(r,e.name);t.id!==void 0&&this.sendResponse(t.id,{name:e.name,stats:n??null})}else{let n=hb(r);t.id!==void 0&&this.sendResponse(t.id,{stats:n})}}function Pb(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=W(),n=ge(r);At(n,e.name),Ng(n,e.name),ke(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!0})}function Cb(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=W(),n=ge(r);Lg(n,e.name),ke(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!1})}function Ib(t){let e=W(),r=this.getActiveProjectRoot(),n=r?ce.join(r,".qlogicagent","skills"):yt(),o=Og(e,n);o.transitioned.length>0&&ct(),t.id!==void 0&&this.sendResponse(t.id,o)}function Eb(t){let e=t.params,r=W(),n=ge(r);if(e?.name){let o=n.records[e.name]??null;t.id!==void 0&&this.sendResponse(t.id,{record:o})}else if(e?.state){if(!KM(e.state)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Invalid skill lifecycle state"});return}let o=jg(n,e.state);t.id!==void 0&&this.sendResponse(t.id,{records:o})}else t.id!==void 0&&this.sendResponse(t.id,{records:Object.values(n.records)})}import*as Lb from"node:path";import{randomUUID as YM}from"node:crypto";import{join as Kl}from"node:path";import{mkdir as zM,readdir as VM}from"node:fs/promises";D();function _b(t){return Kl(re(t),"solos")}function zl(t,e){return Kl(_b(e),t)}function Mb(t,e){return Kl(zl(t,e),"solo-state.json")}async function Db(t,e){let r=zl(t.soloId,e);await zM(r,{recursive:!0}),await cr(Mb(t.soloId,e),t)}async function XM(t,e){return Qt(Mb(t,e))}async function Nb(t){let e=_b(t),r;try{r=await VM(e)}catch{return[]}let n=[];for(let o of r){let s=await XM(o,t);s&&n.push(s)}return n}async function Vl(t,e){let{rm:r}=await import("node:fs/promises"),n=zl(t,e);try{return await r(n,{recursive:!0,force:!0}),!0}catch{return!1}}var zs=class{constructor(e,r,n,o={}){this.processManager=e;this.acpDetector=r;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;persistSession(e){let r={soloId:e.soloId,state:e.state,task:e.task,cwd:e.cwd,gitRoot:e.gitRoot,agents:e.agents.map(n=>({agentId:n.agentId,memberId:n.memberId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,state:n.state,resultText:n.resultText,diff:n.diff,usage:n.usage,error:n.error,turns:n.turns})),evaluation:e.evaluation,createdAt:e.createdAt};Db(r,e.cwd).catch(()=>{})}async restoreFromDisk(e){let r=await Nb(e);for(let n of r)this.sessions.has(n.soloId)||this.sessions.set(n.soloId,{soloId:n.soloId,state:n.state,task:n.task,cwd:n.cwd,gitRoot:n.gitRoot,agents:n.agents.map(o=>({...o,turns:o.turns??[]})),evaluation:n.evaluation,createdAt:n.createdAt});return r.length}async deleteSolo(e){return this.sessions.delete(e),Vl(e)}async start(e){let{task:r,agents:n,cwd:o,sharedConfig:s}=e;if(n.length<2)throw new Error("Solo Mode requires at least 2 agents");let i=await Zn(o);if(!i)throw new Error("Solo Mode requires a git repository");let a=r;if(s){let p=[];s.rules?.length&&p.push(`<rules>
|
|
408
|
+
`)})}return this.workflowController}function er(t){return t.params??{}}function tr(t,e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:e})}async function my(t){let e=er(t);if(!e.def)return tr.call(this,t,"workflow.create requires `def`");let r=Ut.call(this),n=String(e.id??`wf_${py().slice(0,8)}`),o=await r.create({id:n,name:String(e.name??n),def:e.def,concurrency:e.concurrency,active:e.active===!0});o.active&&await this.workflowScheduler?.refresh(o.id),t.id!==void 0&&this.sendResponse(t.id,o)}async function gy(t){let e=er(t);if(!e.id)return tr.call(this,t,"workflow.get requires `id`");let n=await Ut.call(this).get(String(e.id));t.id!==void 0&&this.sendResponse(t.id,n)}async function fy(t){let e=er(t);if(!e.id)return tr.call(this,t,"workflow.describe requires `id`");let n=await Ut.call(this).describe(String(e.id));t.id!==void 0&&this.sendResponse(t.id,{rendered:n})}async function hy(t){let e=er(t);if(!e.id||!e.patch)return tr.call(this,t,"workflow.patch requires `id` and `patch`");let r=Ut.call(this),n={patch:e.patch,baseRev:e.baseRev,scope:e.scope},o=await r.patch(String(e.id),n);await this.workflowScheduler?.refresh(String(e.id)),t.id!==void 0&&this.sendResponse(t.id,o)}async function yy(t){let e=er(t);if(!e.id)return tr.call(this,t,"workflow.run requires `id`");let r=Ut.call(this),n=e.trigger??{type:"manual"},o=await r.run(String(e.id),n);t.id!==void 0&&this.sendResponse(t.id,o)}async function by(t){let e=er(t);if(!e.id||typeof e.active!="boolean")return tr.call(this,t,"workflow.setActive requires `id` and boolean `active`");let n=await Ut.call(this).setActive(String(e.id),e.active);await this.workflowScheduler?.refresh(n.id),t.id!==void 0&&this.sendResponse(t.id,n)}async function vy(t){Ut.call(this);let r=await this.workflowStore.list();t.id!==void 0&&this.sendResponse(t.id,{workflows:r})}async function ky(t){let e=er(t);if(!e.id)return tr.call(this,t,"workflow.delete requires `id`");Ut.call(this),await this.workflowStore.delete(String(e.id)),await this.workflowScheduler?.refresh(String(e.id)),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function Ry(t){let e=er(t);if(!e.channel||typeof e.text!="string")return tr.call(this,t,"workflow.onImMessage requires `channel` and string `text`");Ut.call(this);let r=await this.workflowScheduler.onImMessage(String(e.channel),e.text,e.payload);t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}async function Sy(t){let e=er(t);if(!e.path)return tr.call(this,t,"workflow.onWebhook requires `path`");Ut.call(this);let r=await this.workflowScheduler.onWebhook(String(e.path),e.payload);t.id!==void 0&&this.sendResponse(t.id,{outcomes:r})}import*as J from"node:fs";import*as ie from"node:path";D();D();import*as Me from"node:fs";import*as ro from"node:path";function Gs(t){let e=F(),r=re(t);Me.existsSync(r)||Me.mkdirSync(r,{recursive:!0});let n=ro.join(e,"INSTRUCTIONS.md"),o=ro.join(r,"INSTRUCTIONS.md");if(Me.existsSync(n)&&!Me.existsSync(o))try{Me.copyFileSync(n,o)}catch{}let s=Ju(),i=ir(t);if(Me.existsSync(s)&&!Me.existsSync(i))try{Me.mkdirSync(i,{recursive:!0});for(let a of Me.readdirSync(s)){if(!a.endsWith(".md"))continue;let c=ro.join(s,a),l=ro.join(i,a);Me.statSync(c).isFile()&&Me.copyFileSync(c,l)}}catch{}}var LM=["creating","running","completed","cancelled"];function OM(t){return typeof t=="string"&&LM.includes(t)}function wy(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let r=e.workspaceDir||ie.join(F(),"workspaces",e.name);if(e.groupId){let c=fs(e.groupId);if(c){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:c,deduplicated:!0});return}}let o=V().find(c=>c.name===e.name);if(!J.existsSync(r))try{J.mkdirSync(r,{recursive:!0})}catch{t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Cannot create workspace directory: ${r}`});return}let s=gs({name:e.name,workspaceDir:r,type:e.type??"personal",groupId:e.groupId,skipAutoSwitch:e.type==="solo"||e.type==="product"}),i=s.type==="solo"||s.type==="product";i||(wt(s.id),this.setActiveWorkdir(s.workspaceDir)),Gs(s.workspaceDir);let a=this.projectMemoryStoreFactory.create(s.workspaceDir);if(a.ensureInitialized(),i||(this.memdir=a),i||this.mediaPersistence.setProjectDir(s.workspaceDir),s.type==="solo"){let c=ie.join(re(s.workspaceDir),"solo-state.json");J.existsSync(c)||J.writeFileSync(c,JSON.stringify({agents:[],status:"idle",createdAt:new Date().toISOString()},null,2))}else if(s.type==="product"){let c=ie.join(re(s.workspaceDir),"product-state.json");J.existsSync(c)||J.writeFileSync(c,JSON.stringify({tasks:[],instances:[],status:"idle",createdAt:new Date().toISOString()},null,2))}if(this.sendNotification("project.created",{id:s.id,name:s.name,workspaceDir:s.workspaceDir,type:s.type}),i||this.sendNotification("project.switched",{id:s.id,name:s.name,workspaceDir:s.workspaceDir}),t.id!==void 0){let c={ok:!0,project:s};o&&(c.warning=`\u5DF2\u5B58\u5728\u540C\u540D\u9879\u76EE\u300C${o.name}\u300D\uFF08\u4F4D\u4E8E ${o.workspaceDir}\uFF09\uFF0C\u5EFA\u8BAE\u4FEE\u6539\u540D\u79F0\u4EE5\u4FBF\u533A\u5206`),this.sendResponse(t.id,c)}}function Ty(t){let e=V();t.id!==void 0&&this.sendResponse(t.id,{projects:e})}function Ay(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Ee(e.projectId),n=Yc(e.projectId);if(!n.deleted){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot delete project (not found or is default project)"});return}let o=!1,s;if(r?.workspaceDir){let i=ie.join(F(),"workspaces"),a=ie.resolve(r.workspaceDir);if(a.startsWith(ie.resolve(i)+ie.sep)){try{this.mediaPersistence?.releaseProjectDir?.(a)}catch{}for(let c=0;c<3;c++)try{J.rmSync(a,{recursive:!0,force:!0}),o=!0;break}catch(l){if(c<2&&(l.code==="EBUSY"||l.code==="EPERM"||l.code==="ENOTEMPTY")){let d=Date.now();for(;Date.now()-d<200;);}else{s=l.message??String(l);break}}}else s="\u9879\u76EE\u76EE\u5F55\u4E0D\u5728\u6258\u7BA1\u76EE\u5F55\u4E0B\uFF0C\u4E0D\u4F1A\u81EA\u52A8\u5220\u9664"}this.sendNotification("project.deleted",{id:e.projectId}),n.switchedTo&&(this.setActiveWorkdir(n.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:n.switchedTo.id,name:n.switchedTo.name,workspaceDir:n.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:n.switchedTo,dirDeleted:o,dirDeleteError:s})}function xy(t){let e=V(),r=ie.join(F(),"workspaces"),n=ie.resolve(r)+ie.sep,o=0,s=[];for(let a of e)if(a.type!=="default"){if(Yc(a.id),o++,a.workspaceDir){let c=ie.resolve(a.workspaceDir);try{this.mediaPersistence?.releaseProjectDir?.(c)}catch{}for(let l=0;l<3;l++)try{J.existsSync(c)&&J.rmSync(c,{recursive:!0,force:!0});break}catch(d){if(l<2&&(d.code==="EBUSY"||d.code==="EPERM"||d.code==="ENOTEMPTY")){let u=Date.now();for(;Date.now()-u<300;);}else{s.push(`${a.name}: ${d.message??d}`);break}}}this.sendNotification("project.deleted",{id:a.id})}if(J.existsSync(r)){let a=V().find(d=>d.type==="default"),c=new Set;a?.workspaceDir&&c.add(ie.resolve(a.workspaceDir));let l=d=>{try{let u=J.readdirSync(d,{withFileTypes:!0});for(let p of u){if(!p.isDirectory())continue;let m=ie.join(d,p.name);if(!c.has(ie.resolve(m))){if(p.name==="groups"){l(m);try{J.readdirSync(m).length===0&&J.rmdirSync(m)}catch{}continue}try{J.rmSync(m,{recursive:!0,force:!0})}catch(g){s.push(`orphan:${p.name}: ${g.message??g}`)}}}}catch{}};l(r)}let i=V().find(a=>a.type==="default");i&&(this.setActiveWorkdir(i.workspaceDir),this.sendNotification("project.switched",{id:i.id,name:i.name,workspaceDir:i.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o,dirErrors:s.length?s:void 0})}function Py(t){let e=t.params;if(!e?.projectId||!e?.newName){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required params: projectId, newName"});return}let r=wg(e.projectId,e.newName);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot rename project (not found, is default, or name already taken)"});return}let n=ie.join(F(),"workspaces"),o=ie.resolve(r.workspaceDir);if(o.startsWith(ie.resolve(n)+ie.sep)){let s=ie.join(n,e.newName);if(J.existsSync(o)&&!J.existsSync(s))try{J.renameSync(o,s),Tg(e.projectId,s),r.workspaceDir=s,this.getActiveProjectRoot()===o&&this.setActiveWorkdir(s)}catch{}}this.sendNotification("project.renamed",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function Cy(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=Ag(e.projectId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot archive project (not found or is default project)"});return}this.sendNotification("project.archived",{id:e.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,switchedTo:r.switchedTo})}function Iy(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}let r=xg(e.projectId);if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Cannot unarchive project (not found or not archived)"});return}this.sendNotification("project.unarchived",{id:r.id,name:r.name,workspaceDir:r.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:r})}function Ey(t){let e=t.params;if(!e?.groupId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: groupId"});return}let r=Pg(e.groupId);if(!r.archived){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"No active project with this groupId"});return}this.sendNotification("project.deleted",{id:r.projectId}),r.switchedTo&&(this.setActiveWorkdir(r.switchedTo.workspaceDir),this.sendNotification("project.switched",{id:r.switchedTo.id,name:r.switchedTo.name,workspaceDir:r.switchedTo.workspaceDir})),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:r.projectId})}function _y(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"projectId is required"});return}let r={};if("planStatus"in e){if(e.planStatus!==void 0&&!OM(e.planStatus)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Invalid planStatus: ${e.planStatus}`});return}r.planStatus=e.planStatus}"planAgents"in e&&(r.planAgents=e.planAgents),"planWinnerId"in e&&(r.planWinnerId=e.planWinnerId),"leaderSessionId"in e&&(r.leaderSessionId=e.leaderSessionId);let n=Rg(e.projectId,r);t.id!==void 0&&this.sendResponse(t.id,{ok:n})}import{randomUUID as Hl}from"node:crypto";import*as Ue from"node:fs";import*as mr from"node:path";var pr=class{sessionId;_trustAccepted=!1;_modelUsage=new Map;_totalInputTokens=0;_totalOutputTokens=0;_turnCount=0;_toolCallCount=0;_listeners=new Set;constructor(e){this.sessionId=e}get trustAccepted(){return this._trustAccepted}setTrustAccepted(e){this._trustAccepted=e,this.notifyListeners()}get totalInputTokens(){return this._totalInputTokens}get totalOutputTokens(){return this._totalOutputTokens}get turnCount(){return this._turnCount}get toolCallCount(){return this._toolCallCount}getModelUsage(e){return this._modelUsage.get(e)}getAllModelUsage(){let e={};for(let[r,n]of this._modelUsage)e[r]={...n};return e}addUsage(e,r){this._totalInputTokens+=e.inputTokens,this._totalOutputTokens+=e.outputTokens;let n=this._modelUsage.get(r);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.cacheRead+=e.cacheRead??0,n.cacheCreation+=e.cacheWrite??0):this._modelUsage.set(r,{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cacheRead:e.cacheRead??0,cacheCreation:e.cacheWrite??0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0}),this.notifyListeners()}addMediaUsage(e,r,n){let o=this._modelUsage.get(e),s=o??{inputTokens:0,outputTokens:0,cacheRead:0,cacheCreation:0,mediaCalls:0,mediaDurationSeconds:0,mediaCharacters:0};switch(o||this._modelUsage.set(e,s),s.mediaCalls+=1,r){case"per_second":s.mediaDurationSeconds+=n;break;case"per_character":s.mediaCharacters+=n;break;case"per_token":s.outputTokens+=n;break}this.notifyListeners()}recordToolCall(){this._toolCallCount++}recordTurnCompleted(){this._turnCount++}createSnapshot(){return{sessionId:this.sessionId,modelUsage:this.getAllModelUsage(),totalInputTokens:this._totalInputTokens,totalOutputTokens:this._totalOutputTokens,turnCount:this._turnCount,lastSavedAt:Date.now()}}restoreFromSnapshot(e){if(e.sessionId!==this.sessionId)return!1;this._totalInputTokens=e.totalInputTokens,this._totalOutputTokens=e.totalOutputTokens,this._turnCount=e.turnCount,this._modelUsage.clear();for(let[r,n]of Object.entries(e.modelUsage))this._modelUsage.set(r,{...n});return this.notifyListeners(),!0}onStateChange(e){return this._listeners.add(e),()=>{this._listeners.delete(e)}}notifyListeners(){for(let e of this._listeners)try{e()}catch{}}};import*as My from"node:fs";import*as Fl from"node:path";D();var mn=class{getSessionsRoot(e){let r=Ee(e);if(!r)throw new Error(`Project not found: ${e}`);return Mt(r.workspaceDir)}getProjectWorkspaceDir(e){let r=Ee(e);if(!r)throw new Error(`Project not found: ${e}`);return r.workspaceDir}getSessionDir(e,r){return Fl.join(this.getSessionsRoot(e),r)}resolveWorkspaceDir(e,r){if(r)return this.getProjectWorkspaceDir(r);let n=V();for(let o of n){let s=Mt(o.workspaceDir),i=Fl.join(s,e);try{if(My.existsSync(i))return o.workspaceDir}catch{}}return this.getActiveProjectWorkspaceDir()}getActiveProjectWorkspaceDir(){let e=oe();if(e)return e.workspaceDir;let r=V();if(r.length>0)return r[0].workspaceDir;throw new Error("No active project available")}getActiveProjectId(){let e=oe();if(e)return e.id;let r=V();if(r.length>0)return r[0].id;throw new Error("No active project available")}};import{randomUUID as Dy}from"node:crypto";async function Ny(t,e){let r=new Date(t.lastActiveAt).getTime();if(Date.now()-r<$u)return{split:!1,activeSessionId:t.sessionId};let s=Dy(),i=new Date().toISOString();await Qe(t.sessionId,{sealedAt:i},e);let a=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981] ${t.taskSummary}`:void 0;return await Qe(s,{sessionId:s,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:a},e),{split:!0,activeSessionId:s,sealedSessionId:t.sessionId}}async function Ly(t,e){if(t.type!=="group")return{split:!1,activeSessionId:t.sessionId};if(t.turnCount<Uu)return{split:!1,activeSessionId:t.sessionId};let r=Dy(),n=new Date().toISOString();await Qe(t.sessionId,{sealedAt:n},e);let o=t.taskSummary?`[\u4E0A\u4E00\u8F6E\u5BF9\u8BDD\u6458\u8981 \u2014 \u56E0\u6D88\u606F\u6570\u8FBE\u5230\u4E0A\u9650\u81EA\u52A8\u5207\u5206] ${t.taskSummary}`:void 0;return await Qe(r,{sessionId:r,projectId:t.projectId,type:"group",ownerId:t.ownerId,groupKey:t.groupKey,groupName:t.groupName,groupPlatform:t.groupPlatform,previousSessionId:t.sessionId,carryoverSummary:o},e),{split:!0,activeSessionId:r,sealedSessionId:t.sessionId}}D();var $e=new mn;function pt(t,e="Unknown error"){return t instanceof Error?t.message:e}function jM(t){return t.replace(/[^a-zA-Z0-9_-]/g,"_")}function gn(t,e,r){if(r)return $e.resolveWorkspaceDir(e,r);let n=t.getActiveProjectRoot();if(n){let o=mr.join(Mt(n),jM(e));try{if(Ue.existsSync(o))return n}catch{}}return $e.resolveWorkspaceDir(e)}function Oy(t){let e=t.params,r=e?.id??Hl();this.log(`[thread.create] id=${r} title=${e?.title??"(none)"}`),e?.cwd&&typeof e.cwd=="string"&&this.setActiveWorkdir(e.cwd),this.currentSessionId=r,this.sessionState=new pr(r),this.sessionTaskDomain=void 0,this.memoryPrefetchState=ht(),this.enableIdleDream(),t.id!==void 0&&this.sendResponse(t.id,{id:r,title:e?.title,status:"active",createdAt:new Date().toISOString()})}async function jy(t){let e=t.params,r=e?.limit??20;try{let n=e?.projectId??$e.getActiveProjectId(),o=$e.getProjectWorkspaceDir(n),i=(await Dt(r,o)).map(a=>({id:a.sessionId,title:a.title,status:"active",turnCount:a.messageCount,createdAt:a.createdAt,lastActiveAt:a.lastActiveAt}));t.id!==void 0&&this.sendResponse(t.id,{threads:i})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list threads: ${pt(n)}`})}}async function $y(t){let e=t.params,r=e?.sessionId??Hl();try{let n=e?.projectId??$e.getActiveProjectId(),o=$e.getProjectWorkspaceDir(n);await Qe(r,{sessionId:r,title:e?.title,type:e?.type,ownerId:e?.ownerId,groupKey:e?.groupKey,groupName:e?.groupName,groupPlatform:e?.groupPlatform,projectId:n},o),t.id!==void 0&&this.sendResponse(t.id,{sessionId:r,title:e?.title})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to create session: ${pt(n)}`})}}async function Uy(t){let e=t.params;if(t.id===void 0)return;let r=e?.platform??"desktop",n=e?.chatId,o=e?.chatType,s=e?.userId??"local";try{if(r==="desktop"&&n){let d=e?.projectId??$e.getActiveProjectId(),u=$e.getProjectWorkspaceDir(d),m=(await Dt(500,u)).find(g=>g.sessionId===n);if(m){this.sendResponse(t.id,{sessionId:n,title:m.title,type:m.type??"personal",ownerId:s,projectId:d});return}await Qe(n,{sessionId:n,type:"personal",ownerId:s,projectId:d},u),this.sendResponse(t.id,{sessionId:n,type:"personal",ownerId:s,projectId:d});return}if(o==="group"&&n&&r){let d=`group:${r}:${n}`,u=V();for(let p of u){if(!p.workspaceDir)continue;let g=(await Dt(500,p.workspaceDir)).find(f=>f.groupKey===d&&!f.sealedAt);if(g){let f=zt(g.sessionId,p.workspaceDir);if(f){let h=await Ny(f,p.workspaceDir);if(h.split){this.sendResponse(t.id,{sessionId:h.activeSessionId,title:void 0,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:p.id,previousSessionId:h.sealedSessionId});return}}this.sendResponse(t.id,{sessionId:g.sessionId,title:g.title,type:"group",ownerId:s,groupKey:d,groupPlatform:r,groupName:e?.groupName,projectId:p.id});return}}}let i=Hl(),a=$e.getActiveProjectId(),c=$e.getProjectWorkspaceDir(a),l=o==="group"?`group:${r}:${n}`:void 0;await Qe(i,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a},c),this.sendResponse(t.id,{sessionId:i,type:o==="group"?"group":"personal",ownerId:s,groupKey:l,groupPlatform:o==="group"?r:void 0,groupName:e?.groupName,projectId:a})}catch(i){this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resolve session: ${pt(i)}`})}}async function Fy(t){let e=t.params,r=e?.limit??50;try{let n;if(e?.projectId){let s=Ee(e.projectId);if(!s){t.id!==void 0&&this.sendResponse(t.id,{sessions:[]});return}let i=s.workspaceDir;n=await Dt(r*2,i),n=n.filter(a=>a.projectId===e.projectId);for(let a of n)a.projectId=e.projectId}else{let s=V(),i=new Set,a=[];for(let c of s){if(!c.workspaceDir)continue;let l=await Dt(r,c.workspaceDir);for(let d of l)i.has(d.sessionId)||d.projectId&&(i.add(d.sessionId),a.push(d))}a.sort((c,l)=>c.lastActiveAt>l.lastActiveAt?-1:c.lastActiveAt<l.lastActiveAt?1:0),n=a}e?.archived===!0?n=n.filter(s=>s.archivedAt!=null):e?.archived===!1&&(n=n.filter(s=>s.archivedAt==null));let o=n.slice(0,r).map(s=>({sessionId:s.sessionId,title:s.title,type:s.type??"personal",lastActiveAt:s.lastActiveAt,pinnedAt:s.pinnedAt??null,archivedAt:s.archivedAt??null,sealedAt:s.sealedAt??null,projectId:s.projectId,previousSessionId:s.previousSessionId??null,carryoverSummary:s.carryoverSummary??null}));t.id!==void 0&&this.sendResponse(t.id,{sessions:o})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to list sessions: ${pt(n)}`})}}async function Hy(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=gn(this,e.sessionId,e.projectId),o=(await Dt(500,r)).find(s=>s.sessionId===e.sessionId);t.id!==void 0&&this.sendResponse(t.id,{session:o?{sessionId:o.sessionId,title:o.title,type:o.type,lastActiveAt:o.lastActiveAt,pinnedAt:o.pinnedAt??null,archivedAt:o.archivedAt??null,projectId:o.projectId}:null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get session: ${pt(r)}`})}}async function By(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=gn(this,e.sessionId,e.projectId),n=await Ga(e.sessionId,r);if(!n){t.id!==void 0&&this.sendResponse(t.id,{messages:[],total:0});return}let o=n.messages,s=e.limit&&e.limit>0?e.limit:o.length,i=o.slice(-s);t.id!==void 0&&this.sendResponse(t.id,{messages:i,total:o.length})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to get messages: ${pt(r)}`})}}async function qy(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=gn(this,e.sessionId,e.projectId),n=await Qe(e.sessionId,{...e.title!==void 0?{title:e.title}:{},...e.pinnedAt!==void 0?{pinnedAt:e.pinnedAt}:{},...e.archivedAt!==void 0?{archivedAt:e.archivedAt}:{}},r);n&&this.sendNotification("session.info",{sessionId:e.sessionId,title:n.title,pinnedAt:n.pinnedAt??null,archivedAt:n.archivedAt??null,projectId:e.projectId||void 0}),t.id!==void 0&&this.sendResponse(t.id,{ok:n!==null})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to update session: ${pt(r)}`})}}async function Wy(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=gn(this,e.sessionId,e.projectId);await Ka(e.sessionId,r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete session: ${pt(r)}`})}}async function Gy(t){let e=t.params;if(!e?.projectId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId"});return}try{let r=$e.getProjectWorkspaceDir(e.projectId),n=(await Dt(1e4,r)).filter(s=>s.projectId===e.projectId),o=0;for(let s of n)await Ka(s.sessionId,r),o++;t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deletedCount:o})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete all sessions: ${pt(r)}`})}}async function Ky(t){let e=t.params;if(!e?.sessionId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: sessionId"});return}try{let r=gn(this,e.sessionId,e.projectId);await Qe(e.sessionId,{archivedAt:new Date().toISOString()},r),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to archive session: ${pt(r)}`})}}async function zy(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"sessionId is required"});return}try{let n=gn(this,r,e?.projectId),o=await Ga(r,n);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Session not found: ${r}`});return}o.messages&&o.messages.length>0&&this.sessionHistory.saveResumedSession(r,o.messages),t.id!==void 0&&this.sendResponse(t.id,{metadata:o.metadata,messages:o.messages})}catch(n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to resume session: ${pt(n)}`})}}function Vy(t){let e=this.currentSessionId||"default",r=this.sessionState?.createSnapshot(),n,o=this.getActiveProjectRoot();o&&(n=mr.join(Mt(o),e));let s={sessionId:e,model:this.currentModel||void 0,cwd:process.cwd(),paths:{sessionDir:n,agentHome:F(),settings:de()},usage:r?{turnCount:r.turnCount,inputTokens:r.totalInputTokens,outputTokens:r.totalOutputTokens}:void 0};t.id!==void 0&&this.sendResponse(t.id,s)}function Xy(t){let e=t.params,r=null;if(e?.projectId)r=Ee(e.projectId);else if(e?.projectName){let s=V(),i=e.projectName.toLowerCase();if(r=s.find(a=>a.name.toLowerCase()===i)??null,r||(r=s.find(a=>a.name.toLowerCase().includes(i))??null),!r){let a=s.map(c=>c.name).slice(0,10);t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`No project matching "${e.projectName}". Available: ${a.join(", ")||"(none)"}`});return}}else{t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: projectId or projectName"});return}if(!r||r.status!=="active"){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Project not found or archived: ${e.projectId??e.projectName}`});return}let n=e.workspaceDir??r.workspaceDir;if(!Ue.existsSync(n)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Workspace directory does not exist: ${n}`});return}let o=wt(r.id);if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"Switch failed"});return}this.setActiveWorkdir(o.workspaceDir),this.sendNotification("project.switched",{id:o.id,name:o.name,workspaceDir:o.workspaceDir}),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,project:o})}function Yy(t){let e=oe(),r=V();t.id!==void 0&&this.sendResponse(t.id,{sessionId:this.currentSessionId,activeProject:e,projects:r})}async function Jy(t){let e=t.params,r=e?.sessionId;if(!r){t.id!==void 0&&this.sendResponse(t.id,{ok:!1});return}let n=V();for(let o of n)try{let s=$e.getProjectWorkspaceDir(o.id),i=await zt(r,s);if(i&&i.projectId===o.id){wt(o.id),this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} for session ${r}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}catch{}if(e?.projectName){let o=n.find(s=>s.name===e.projectName);if(o){let s=$e.getProjectWorkspaceDir(o.id);this.getActiveProjectRoot()!==s&&(this.setActiveWorkdir(s),this.log(`[session.focus] switched to project ${o.id} by name "${e.projectName}"`)),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o.id});return}}t.id!==void 0&&this.sendResponse(t.id,{ok:!1})}async function Qy(t){let e=t.params,{sessionId:r,fromProjectId:n,toProjectId:o}=e??{};if(!r||!n||!o){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"sessionId, fromProjectId, and toProjectId are required");return}if(n===o){t.id!==void 0&&this.sendResponse(t.id,{ok:!0});return}let s=Ee(n),i=Ee(o);if(!s||!i){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,"Source or target project not found");return}let a=mr.join($e.getProjectWorkspaceDir(n),".qlogicagent","sessions",r),c=mr.join($e.getProjectWorkspaceDir(o),".qlogicagent","sessions",r);if(!Ue.existsSync(a)){t.id!==void 0&&this.sendError(t.id,y.INVALID_PARAMS,`Session ${r} not found in project ${n}`);return}try{Ue.mkdirSync(mr.dirname(c),{recursive:!0}),Ue.cpSync(a,c,{recursive:!0});let l=mr.join(c,"metadata.json");if(Ue.existsSync(l)){let d=JSON.parse(Ue.readFileSync(l,"utf-8"));d.projectId=o,Ue.writeFileSync(l,JSON.stringify(d,null,2))}Ue.rmSync(a,{recursive:!0,force:!0}),this.sendNotification("session-update",{sessionId:r,projectId:o}),this.log(`[session.moveToProject] moved ${r}: ${n} \u2192 ${o}`),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,projectId:o})}catch(l){let d=pt(l);this.log(`[session.moveToProject] error: ${d}`),t.id!==void 0&&this.sendError(t.id,y.INTERNAL_ERROR,`Move failed: ${d}`)}}We();function $M(t){return t.length<=8?"****":`${t.slice(0,3)}***${t.slice(-4)}`}function Ze(t,e,r,n=y.INTERNAL_ERROR){if(e.id!==void 0){if(typeof t.sendError=="function"){t.sendError(e.id,n,r);return}t.sendResponse(e.id,void 0,{code:n,message:r})}}function Bl(t,e){Ze(t,e,Bo)}function UM(t){let e={};for(let r of t)for(let n of r.purposes)e[n]??=[],e[n].push(r);return e}async function FM(){let t=M(),e=await Cn(t);return t.save(),e}async function Zy(t){try{return await FM(),!0}catch(e){if(t)throw e;return!1}}function ql(t=M()){try{return fp()}catch{return t.getKnownProviderDef(ne)?.baseUrl??"https://www.qlogicagent.com"}}async function eb(t){let e=M(),r=e.getKeyForProvider(ne);if(!r){if(t)throw new Error("LLMRouter API Key is required to fetch available models.");return!1}let n=e.getProviderStatus(ne)?.baseUrl??ql(e);try{if((await Za(e,{baseUrl:n,apiKey:r})).length===0){if(t)throw new Error("LLMRouter did not return any available models for this API Key.");return!1}return e.save(),!0}catch(o){if(t)throw o;return!1}}async function tb(t=!1){let e=M();if(!!e.getProviderStatus(ne)?.keys.length)return await eb(!1)?!0:Zy(t);let o=e.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId).some(s=>s!=="deepseek"&&s!==ne);return!t&&!o?!1:Zy(t)}async function rb(t){try{let e=M(),r=["deepseek",ne].map(s=>e.getKnownProviderDef(s)).filter(s=>!!s).map(s=>({id:s.id,displayName:s.name,baseUrl:s.baseUrl,modelCount:s.models?.length??0})),n=await Ja().catch(()=>[]),o=n.map(s=>({id:s.id,displayName:yp(s),baseUrl:Qa(s)??"",modelCount:s.models?.length??0}));o.unshift({id:ne,displayName:Xa,baseUrl:ql(e),modelCount:n.reduce((s,i)=>s+(i.models?.length??0),0)});for(let s of r.reverse()){let i=o.findIndex(a=>a.id===s.id);if(i>=0){s.id!==ne&&o.splice(i,1,s);continue}o.unshift(s)}t.id!==void 0&&this.sendResponse(t.id,{providers:o})}catch(e){Ze(this,t,e instanceof Error?e.message:String(e))}}async function nb(t){let e=t.params;if(!e?.providerId||!e?.key){Ze(this,t,"Required: providerId (string), key (string)",y.INVALID_PARAMS);return}let{providerId:r,key:n,label:o}=e,s=M(),i,a=!1;try{let c=await mb(r);if(!c){Ze(this,t,`Unknown provider: ${r}`,y.INVALID_PARAMS);return}let l=s.getProviderStatus(r);if(l?.keys.some(d=>d.key===n)){t.id!==void 0&&this.sendResponse(t.id,{ok:!1,error:"\u8BE5 Key \u5DF2\u5B58\u5728\uFF0C\u65E0\u9700\u91CD\u590D\u6DFB\u52A0"});return}if(a=!l,s.addProvider(r,{baseUrl:c}),i=s.addKey(r,n,{label:o}),r===ne&&(await Za(s,{baseUrl:c,apiKey:n})).length===0)throw new Error("LLMRouter did not return any available models for this API Key.");for(let d of Pn)if(!s.getBinding(d)){let u=s.listModels({purpose:d,provider:r,enabledOnly:!0});u.length===0&&(u=s.listModels({purpose:d,provider:r}),u[0]&&s.enableModel(u[0].id)),u.length>0&&s.setBinding(d,u[0].id)}s.setKeyHealth(i,"healthy"),s.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,keyId:i,providerId:r})}catch(c){i&&(s.removeKey(i),a&&s.removeProvider(r));let l=c instanceof Error?c.message:Bo;Ze(this,t,l)}}function ob(t){let e=t.params;if(!e?.keyId){Ze(this,t,"Required: keyId (string)",y.INVALID_PARAMS);return}let r=M();r.removeKey(e.keyId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function sb(t){let e=t.params;if(!e?.keyId||typeof e.enabled!="boolean"){Ze(this,t,"Required: keyId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=M();r.updateKey(e.keyId,{enabled:e.enabled}),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}function ib(t){let e=t.params;if(!e?.modelId||typeof e.enabled!="boolean"){Ze(this,t,"Required: modelId (string), enabled (boolean)",y.INVALID_PARAMS);return}let r=M();e.enabled?r.enableModel(e.modelId):r.disableModel(e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}async function ab(t){let e=t.params;try{await tb(!1);let r=M(),n=new Set(r.getAllProviderStatus().filter(s=>s.keys.length>0).map(s=>s.providerId)),o=r.listModels({purpose:e?.purpose,provider:e?.provider}).filter(s=>r.hasConfiguredKeyForProviderVariant(s.provider));t.id!==void 0&&this.sendResponse(t.id,{models:o,grouped:UM(o),configuredProviderIds:[...n]})}catch{Bl(this,t)}}function cb(t){let e=t.params;if(!e?.purpose||!e?.modelId){Ze(this,t,"Required: purpose (string), modelId (string)",y.INVALID_PARAMS);return}try{let r=M();r.setBinding(e.purpose,e.modelId),r.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(r){Ze(this,t,r instanceof Error?r.message:String(r),y.INVALID_PARAMS)}}function lb(t){let e=t.params;if(!e?.purpose){Ze(this,t,"Required: purpose (string)",y.INVALID_PARAMS);return}let r=M(),n=r.getBinding(e.purpose);t.id!==void 0&&this.sendResponse(t.id,{model:n?{id:n.id,provider:n.provider,model:n.model,displayName:n.displayName,purposes:n.purposes,enabled:n.enabled}:null,available:r.isAvailable(e.purpose)})}async function db(t){try{await tb(!1);let e=M(),r=e.getAllProviderStatus().map(s=>({providerId:s.providerId,displayName:s.providerId===ne?Xa:s.providerId,baseUrl:s.baseUrl,keyCount:s.keys.length,healthyKeys:s.keys.filter(i=>i.healthStatus==="healthy"&&i.enabled).length,totalKeys:s.keys.length,keys:s.keys.map(i=>({id:i.id,label:i.label,maskedKey:$M(i.key),enabled:i.enabled,health:i.healthStatus}))})),n=e.getAllBindings(),o={};for(let s of Pn){let i=n[s];o[s]={bound:!!i,modelId:i?.id,modelName:i?.displayName,available:e.isAvailable(s)}}t.id!==void 0&&this.sendResponse(t.id,{providers:r,purposes:o})}catch{Bl(this,t)}}async function ub(t){try{let e=M();e.load(),await eb(!1)||await Cn(e),e.save(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,catalogRefreshed:!0})}catch{Bl(this,t)}}async function pb(t){let e=t.params;if(!e?.providerId||!e?.apiKey){Ze(this,t,"providerId and apiKey required",y.INVALID_PARAMS);return}try{let r=e.baseUrl||await mb(e.providerId);if(!r){Ze(this,t,`Unknown provider: ${e.providerId}`,y.INVALID_PARAMS);return}let n=e.providerId===ne?Ya(r):`${r.replace(/\/$/,"")}/models`,o=await fetch(n,{method:"GET",headers:{Authorization:`Bearer ${e.apiKey}`},signal:AbortSignal.timeout(1e4)});if(o.ok){t.id!==void 0&&this.sendResponse(t.id,{valid:!0,status:o.status});return}let s=await o.text().catch(()=>"");t.id!==void 0&&this.sendResponse(t.id,{valid:!1,status:o.status,error:s.slice(0,500)})}catch(r){let n=r instanceof Error?r.message:String(r);t.id!==void 0&&this.sendResponse(t.id,{valid:!1,status:0,error:n})}}async function mb(t){if(t===ne)return ql();let e=M().getKnownProviderDef(t);if(e?.baseUrl)return e.baseUrl;let r=await bp(t);return r?Qa(r):void 0}D();import*as q from"node:fs";import*as ce from"node:path";import{join as HM}from"node:path";import{readFileSync as BM,writeFileSync as qM,mkdirSync as WM}from"node:fs";var Dr=null,Wl=!1;function gb(t){return HM(t,"skill-stats.json")}function Gl(t){if(Dr)return Dr;try{Dr=JSON.parse(BM(gb(t),"utf8"))}catch{Dr={}}return Dr}function GM(t){if(!(!Wl||!Dr))try{WM(t,{recursive:!0}),qM(gb(t),JSON.stringify(Dr,null,2),"utf8"),Wl=!1}catch{}}function Ks(t,e,r){let n=Gl(t);n[e]||(n[e]={invokeCount:0,activeCount:0,positiveCount:0,negativeCount:0}),n[e].invokeCount++,n[e].lastUsedAt=new Date().toISOString(),r?n[e].positiveCount++:n[e].negativeCount++,n[e].invokeCount>0&&(n[e].successRate=(n[e].invokeCount-n[e].negativeCount)/n[e].invokeCount),Wl=!0,GM(t)}function fb(t,e){return Gl(t)[e]}function hb(t){return Gl(t)}function yb(t){try{let e=q.readFileSync(t,"utf8"),r=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),n=e.match(/^---\n[\s\S]*?^description:\s*(.+)/m);return{version:r?.[1],description:n?.[1]?.trim()}}catch{return{}}}function bb(t){return{key:`capability.skill.${t}.name`,fallback:t}}function vb(t,e){return{key:`capability.skill.${t}.description`,fallback:e??""}}function kb(t){return t.startsWith("auto-skill-")||t.startsWith("test-skill-")}function KM(t){return t==="active"||t==="stale"||t==="archived"}function Rb(t){let r=t.params?.projectId,n=this.getActiveProjectRoot();if(r&&this.projectLocator){let a=this.projectLocator.resolveProjectRoot(r);a&&(n=a)}let o=n?_t(n):void 0,s=yt(),i=[];if(o&&q.existsSync(o))for(let a of q.readdirSync(o)){let c=ce.join(o,a);if(!q.statSync(c).isDirectory())continue;let l=ce.join(c,"SKILL.md"),d=ce.join(c,"SKILL.md.disabled"),u=q.existsSync(l)?l:null;if(u||q.existsSync(d)){let p=u?yb(u):{};i.push({id:`project:${a}`,name:a,path:c,active:!!u,scope:"project",category:"automation",displayName:bb(a),displayDescription:vb(a,p.description),fallbackName:a,fallbackDescription:p.description??"",systemGenerated:kb(a),version:p.version,description:p.description})}}if(q.existsSync(s))for(let a of q.readdirSync(s)){let c=ce.join(s,a);try{if(!q.statSync(c).isDirectory())continue}catch{continue}let l=ce.join(c,"SKILL.md"),d=ce.join(c,"SKILL.md.disabled"),u=q.existsSync(l)?l:null;if(u||q.existsSync(d)){let p=u?yb(u):{};i.push({id:`global:${a}`,name:a,path:c,active:!!u,scope:"global",category:"automation",displayName:bb(a),displayDescription:vb(a,p.description),fallbackName:a,fallbackDescription:p.description??"",systemGenerated:kb(a),version:p.version,description:p.description})}}t.id!==void 0&&this.sendResponse(t.id,{skills:i})}function Sb(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?_t(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=ce.join(o,r),i=ce.join(s,"SKILL.md.disabled"),a=ce.join(s,"SKILL.md");if(q.existsSync(a)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}if(q.existsSync(i))try{q.renameSync(i,a);let c=W(),l=ge(c),d=At(l,r);d.state!=="active"&&(d.state="active",d.staleAt=void 0,d.archivedAt=void 0),ke(c,l),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"activate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to activate skill: ${c instanceof Error?c.message:c}`})}else t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found`})}function wb(t){let r=t.params?.name;if(!r){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing required param: name"});return}let n=this.getActiveProjectRoot(),o=n?_t(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=ce.join(o,r),i=ce.join(s,"SKILL.md"),a=ce.join(s,"SKILL.md.disabled");if(!q.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,{ok:!0,already:!0});return}try{q.renameSync(i,a),t.id!==void 0&&this.sendResponse(t.id,{ok:!0}),this.sendNotification("skills.updated",{action:"deactivate",name:r})}catch(c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to deactivate skill: ${c instanceof Error?c.message:c}`})}}function Tb(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=W(),o=ge(n);if(o.records[r]?.pinned){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Skill "${r}" is pinned. Unpin it first.`});return}let s=e?.scope??"project",i;if(s==="global")i=ce.join(yt(),r);else{let a=this.getActiveProjectRoot(),c=a?_t(a):void 0;if(!c){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}i=ce.join(c,r)}if(!q.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in ${s} scope`});return}try{q.rmSync(i,{recursive:!0,force:!0}),ct(),vs(o,r),ke(n,o),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,deleted:r,scope:s}),this.sendNotification("skills.updated",{action:"delete",name:r})}catch(a){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to delete skill: ${a instanceof Error?a.message:a}`})}}function Ab(t){let e=t.params,r=e?.name;if(!r||/[\/\\]|\.\./.test(r)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Missing or invalid skill name"});return}let n=this.getActiveProjectRoot(),o=n?_t(n):void 0;if(!o){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:"No active project workspace"});return}let s=ce.join(o,r),i=ce.join(s,"SKILL.md");if(!q.existsSync(i)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Skill "${r}" not found in project scope`});return}let a=yt(),c=ce.join(a,r);try{q.mkdirSync(c,{recursive:!0});let l=q.readdirSync(s);for(let d of l){let u=q.readFileSync(ce.join(s,d));q.writeFileSync(ce.join(c,d),u)}e?.keepLocal||q.rmSync(s,{recursive:!0,force:!0}),ct(),t.id!==void 0&&this.sendResponse(t.id,{ok:!0,promoted:r,globalPath:c,removedFromProject:!e?.keepLocal})}catch(l){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:`Failed to promote skill: ${l instanceof Error?l.message:l}`})}}function xb(t){let e=t.params,r=W();if(e?.name){let n=fb(r,e.name);t.id!==void 0&&this.sendResponse(t.id,{name:e.name,stats:n??null})}else{let n=hb(r);t.id!==void 0&&this.sendResponse(t.id,{stats:n})}}function Pb(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=W(),n=ge(r);At(n,e.name),Ng(n,e.name),ke(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!0})}function Cb(t){let e=t.params;if(!e?.name){t.id!==void 0&&this.sendResponse(t.id,null,{code:-32602,message:"Missing 'name' parameter"});return}let r=W(),n=ge(r);Lg(n,e.name),ke(r,n),t.id!==void 0&&this.sendResponse(t.id,{name:e.name,pinned:!1})}function Ib(t){let e=W(),r=this.getActiveProjectRoot(),n=r?ce.join(r,".qlogicagent","skills"):yt(),o=Og(e,n);o.transitioned.length>0&&ct(),t.id!==void 0&&this.sendResponse(t.id,o)}function Eb(t){let e=t.params,r=W(),n=ge(r);if(e?.name){let o=n.records[e.name]??null;t.id!==void 0&&this.sendResponse(t.id,{record:o})}else if(e?.state){if(!KM(e.state)){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"Invalid skill lifecycle state"});return}let o=jg(n,e.state);t.id!==void 0&&this.sendResponse(t.id,{records:o})}else t.id!==void 0&&this.sendResponse(t.id,{records:Object.values(n.records)})}import*as Lb from"node:path";import{randomUUID as YM}from"node:crypto";import{join as Kl}from"node:path";import{mkdir as zM,readdir as VM}from"node:fs/promises";D();function _b(t){return Kl(re(t),"solos")}function zl(t,e){return Kl(_b(e),t)}function Mb(t,e){return Kl(zl(t,e),"solo-state.json")}async function Db(t,e){let r=zl(t.soloId,e);await zM(r,{recursive:!0}),await cr(Mb(t.soloId,e),t)}async function XM(t,e){return Zt(Mb(t,e))}async function Nb(t){let e=_b(t),r;try{r=await VM(e)}catch{return[]}let n=[];for(let o of r){let s=await XM(o,t);s&&n.push(s)}return n}async function Vl(t,e){let{rm:r}=await import("node:fs/promises"),n=zl(t,e);try{return await r(n,{recursive:!0,force:!0}),!0}catch{return!1}}var zs=class{constructor(e,r,n,o={}){this.processManager=e;this.acpDetector=r;this.configStore=n;this.callbacks=o}processManager;acpDetector;configStore;callbacks;sessions=new Map;persistSession(e){let r={soloId:e.soloId,state:e.state,task:e.task,cwd:e.cwd,gitRoot:e.gitRoot,agents:e.agents.map(n=>({agentId:n.agentId,memberId:n.memberId,worktreePath:n.worktreePath,worktreeBranch:n.worktreeBranch,state:n.state,resultText:n.resultText,diff:n.diff,usage:n.usage,error:n.error,turns:n.turns})),evaluation:e.evaluation,createdAt:e.createdAt};Db(r,e.cwd).catch(()=>{})}async restoreFromDisk(e){let r=await Nb(e);for(let n of r)this.sessions.has(n.soloId)||this.sessions.set(n.soloId,{soloId:n.soloId,state:n.state,task:n.task,cwd:n.cwd,gitRoot:n.gitRoot,agents:n.agents.map(o=>({...o,turns:o.turns??[]})),evaluation:n.evaluation,createdAt:n.createdAt});return r.length}async deleteSolo(e){return this.sessions.delete(e),Vl(e)}async start(e){let{task:r,agents:n,cwd:o,sharedConfig:s}=e;if(n.length<2)throw new Error("Solo Mode requires at least 2 agents");let i=await Zn(o);if(!i)throw new Error("Solo Mode requires a git repository");let a=r;if(s){let p=[];s.rules?.length&&p.push(`<rules>
|
|
409
409
|
${s.rules.join(`
|
|
410
410
|
`)}
|
|
411
411
|
</rules>`),s.memory?.length&&p.push(`<memory>
|
|
@@ -420,14 +420,14 @@ ${r}`)}let c=`solo-${YM().slice(0,8)}`,l={soloId:c,state:"running",task:r,cwd:o,
|
|
|
420
420
|
`),warn:r=>process.stderr.write(`[solo:pm] WARN ${r}
|
|
421
421
|
`)},onNotification:(r,n,o)=>{(n==="agents.error"||n==="agents.status")&&this.sendNotification(n,o),this.sendNotification("team.member.notification",{memberId:r,method:n,params:o})},onStateChange:(r,n)=>{let o=t.getHandle(r),i=t.getUsageTracker(r)?.getUsage();this.emitAgentStatus(r,n,{missedBeats:t.getMissedBeats(r),lastActivityAt:o?.lastActivityAt,usage:i&&i.totalTokens>0?{inputTokens:i.inputTokens,outputTokens:i.outputTokens,totalTokens:i.totalTokens}:void 0})},onMcpToolCall:(r,n,o)=>this.handleMcpToolCall(r,n,o),sessionDir:Lb.join(F(),"agent-logs")}),e={log:{info:r=>process.stderr.write(`${r}
|
|
422
422
|
`),warn:r=>process.stderr.write(`${r}
|
|
423
|
-
`)},onProgress:(r,n,o,s)=>{this.sendNotification("solo.progress",{soloId:r,agentId:n,state:o,progress:s})},onEvaluation:(r,n)=>{this.sendNotification("solo.evaluation",{soloId:r,winnerId:n.winnerId,reasoning:n.reasoning})},onAgentDelta:(r,n,o)=>{this.sendNotification("solo.agentDelta",{soloId:r,agentId:n,text:o})},onAgentDiff:(r,n,o)=>{this.sendNotification("solo.agentDiff",{soloId:r,agentId:n,files:o})},onAgentUsage:(r,n,o,s)=>{this.sendNotification("solo.agentUsage",{soloId:r,agentId:n,inputTokens:o,outputTokens:s})}};this.soloEvaluator=new zs(t,this.acpDetector,this.agentConfigStore,e),this.soloProcessManager=t}return this.soloEvaluator}async function Ob(t){try{let e=t.params;if(!e?.task||!e?.agents||!e?.cwd){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"task, agents, and cwd are required."});return}let r=e;if(!r.projectId){let i=oe();i&&(r.projectId=i.id)}let n=Ve.call(this),o=await n.start(r),s=n.getStatus(o);t.id!==void 0&&this.sendResponse(t.id,s)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function jb(t){try{let e=t.params;if(!e?.soloId){this.soloEvaluator?t.id!==void 0&&this.sendResponse(t.id,this.soloEvaluator.listSessions()):t.id!==void 0&&this.sendResponse(t.id,[]);return}let n=Ve.call(this).getStatus(e.soloId);if(!n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Solo session ${e.soloId} not found.`});return}t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function $b(t){try{let e=t.params;if(!e?.soloId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"soloId is required."});return}await Ve.call(this).cancel(e.soloId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Ub(t){try{let e=t.params;if(!e?.soloId||!e?.winnerId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"soloId and winnerId are required."});return}let n=await Ve.call(this).select(e);t.id!==void 0&&this.sendResponse(t.id,{ok:!0,mergedBranch:n})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function Fb(t){try{this.soloEvaluator?t.id!==void 0&&this.sendResponse(t.id,this.soloEvaluator.listSessions()):t.id!==void 0&&this.sendResponse(t.id,[])}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Hb(t){try{let e=t.params;if(!e?.soloId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"soloId is required."});return}await Ve.call(this).delete(e.soloId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Bb(t){try{let e=t.params;if(!e?.soloId||!e?.agentId||!e?.content){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"soloId, agentId, and content are required."});return}let n=await Ve.call(this).message(e.soloId,e.agentId,e.content,e.agentIndex);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function qb(t){try{let e=t.params;if(!e?.soloId||!e?.evaluatorAgentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"soloId and evaluatorAgentId are required."});return}let n=await Ve.call(this).triggerEvaluation(e.soloId,e.evaluatorAgentId,e.evaluatorIndex);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}We();import{randomUUID as
|
|
423
|
+
`)},onProgress:(r,n,o,s)=>{this.sendNotification("solo.progress",{soloId:r,agentId:n,state:o,progress:s})},onEvaluation:(r,n)=>{this.sendNotification("solo.evaluation",{soloId:r,winnerId:n.winnerId,reasoning:n.reasoning})},onAgentDelta:(r,n,o)=>{this.sendNotification("solo.agentDelta",{soloId:r,agentId:n,text:o})},onAgentDiff:(r,n,o)=>{this.sendNotification("solo.agentDiff",{soloId:r,agentId:n,files:o})},onAgentUsage:(r,n,o,s)=>{this.sendNotification("solo.agentUsage",{soloId:r,agentId:n,inputTokens:o,outputTokens:s})}};this.soloEvaluator=new zs(t,this.acpDetector,this.agentConfigStore,e),this.soloProcessManager=t}return this.soloEvaluator}async function Ob(t){try{let e=t.params;if(!e?.task||!e?.agents||!e?.cwd){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"task, agents, and cwd are required."});return}let r=e;if(!r.projectId){let i=oe();i&&(r.projectId=i.id)}let n=Ve.call(this),o=await n.start(r),s=n.getStatus(o);t.id!==void 0&&this.sendResponse(t.id,s)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function jb(t){try{let e=t.params;if(!e?.soloId){this.soloEvaluator?t.id!==void 0&&this.sendResponse(t.id,this.soloEvaluator.listSessions()):t.id!==void 0&&this.sendResponse(t.id,[]);return}let n=Ve.call(this).getStatus(e.soloId);if(!n){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:`Solo session ${e.soloId} not found.`});return}t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function $b(t){try{let e=t.params;if(!e?.soloId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"soloId is required."});return}await Ve.call(this).cancel(e.soloId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Ub(t){try{let e=t.params;if(!e?.soloId||!e?.winnerId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"soloId and winnerId are required."});return}let n=await Ve.call(this).select(e);t.id!==void 0&&this.sendResponse(t.id,{ok:!0,mergedBranch:n})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}function Fb(t){try{this.soloEvaluator?t.id!==void 0&&this.sendResponse(t.id,this.soloEvaluator.listSessions()):t.id!==void 0&&this.sendResponse(t.id,[])}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Hb(t){try{let e=t.params;if(!e?.soloId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"soloId is required."});return}await Ve.call(this).delete(e.soloId),t.id!==void 0&&this.sendResponse(t.id,{ok:!0})}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function Bb(t){try{let e=t.params;if(!e?.soloId||!e?.agentId||!e?.content){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"soloId, agentId, and content are required."});return}let n=await Ve.call(this).message(e.soloId,e.agentId,e.content,e.agentIndex);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}async function qb(t){try{let e=t.params;if(!e?.soloId||!e?.evaluatorAgentId){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INVALID_PARAMS,message:"soloId and evaluatorAgentId are required."});return}let n=await Ve.call(this).triggerEvaluation(e.soloId,e.evaluatorAgentId,e.evaluatorIndex);t.id!==void 0&&this.sendResponse(t.id,n)}catch(e){t.id!==void 0&&this.sendResponse(t.id,void 0,{code:y.INTERNAL_ERROR,message:e instanceof Error?e.message:String(e)})}}We();import{randomUUID as nO}from"node:crypto";import*as j from"node:fs";import*as U from"node:path";import{execFile as yN}from"node:child_process";var JM="think",QM={type:"object",properties:{thought:{type:"string",description:["Your internal reasoning about the current situation.","Use this to:","\u2022 Analyze what the user really wants (disambiguate vague requests)","\u2022 Plan multi-step approaches before executing","\u2022 Evaluate which tool(s) to use and why","\u2022 Consider edge cases or potential issues","\u2022 Reflect on conversation context and user preferences","This content is never shown to the user."].join(`
|
|
424
424
|
`)}},required:["thought"]};function Wb(){return{name:JM,label:"Think",shouldDefer:!0,description:["Use this tool to think and reason about the current situation BEFORE taking action.","Call this tool when you need to:","- Analyze an ambiguous or complex user request before deciding what to do","- Plan a multi-step approach (what tools to call and in what order)","- Identify which steps can run in parallel vs. which must be sequential","- Evaluate tradeoffs between different approaches","- Reflect on user preferences from conversation history","- Process new information that changes your understanding","","This tool has NO side effects \u2014 it simply records your reasoning process.","Your thought is NOT shown to the user; it only improves YOUR decision quality.","After thinking, proceed to take the appropriate action.","","When planning multi-step work, be explicit about parallelism:",'- Say "\u8FD9\u4E9B\u53EF\u4EE5\u5E76\u884C\u751F\u6210" or "these can run in parallel" for independent tasks.','- Say "\u5148\u2026\u7136\u540E\u2026" or "step 1 first, then step 2" for sequential dependencies.'].join(`
|
|
425
|
-
`),parameters:QM,execute:async(t,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}import{isAbsolute as w0,resolve as T0}from"node:path";var Gb=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Kb=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),zb=new Set(["ls","tree","du"]);var Vb=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function ZM(t){let r=t.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!r)return null;let n=r.split(/\s+/),o=0;for(;o<n.length&&/^[A-Za-z_]\w*=/.test(n[o]);)o++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;o<n.length;){let c=n[o];if(s.test(c)){for(o++;o<n.length&&/^[-+]/.test(n[o]);)o++;o<n.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(n[o])&&o++;continue}break}if(o>=n.length)return null;let i=n[o],a=i.lastIndexOf("/");return a>=0?i.slice(a+1):i}function Xb(t){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(t)}function Xl(t){let e=ZM(t),r=e!==null&&Gb.has(e),n=e!==null&&Kb.has(e),o=e!==null&&zb.has(e),s=e!==null&&Vb.has(e),i=/(?:[^2]>|^>|\|>)/.test(t),a=Xb(t),c=(r||n||o)&&!i&&!a;return{firstCommand:e,isSearch:r,isRead:n,isList:o,isSilent:s,isConcurrencySafe:c,isReadOnly:c}}var e0=t=>({isError:t!==0,message:t!==0?`Command failed with exit code ${t}`:void 0}),t0=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 r0(t){let e=t.trim(),r=e.split(/\s*\|\s*/);return(r[r.length-1]??e).trim().split(/\s+/)[0]??""}function Yl(t,e,r,n){let o=r0(t);return(t0.get(o)??e0)(e,r,n)}function Jl(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}import{spawn as f0}from"node:child_process";import{constants as Ys,readFileSync as h0,unlinkSync as y0}from"node:fs";import{mkdir as b0,open as v0,realpath as Zb}from"node:fs/promises";import{isAbsolute as k0,resolve as R0}from"node:path";function Nr(){if(process.platform!=="win32")return!1;let t=process.env.QLOGICAGENT_USE_POWERSHELL;return t==="1"||t==="true"}function Ql(){return Nr()?"powershell":"bash"}function Zl(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as n0,readFile as o0,writeFile as s0,unlink as i0}from"node:fs/promises";import{join as Yb}from"node:path";import{tmpdir as a0}from"node:os";var c0=8*1024*1024,l0=5*1024*1024*1024;var ed;function no(){if(!ed){let t=Math.random().toString(36).slice(2,10);ed=Yb(a0(),"qla-tasks",t)}return ed}function Jb(t){return Yb(no(),`${t}.output`)}function tr(t="local_bash"){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var gr=class{taskId;path;stdoutToFile;#e="";#r="";#o=0;#s=0;#t;#i;#n=0;#a=!1;constructor(e,r,n=!1,o=c0){this.taskId=e,this.path=Jb(e),this.stdoutToFile=n,this.#t=o,this.#i=r}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#o+=d0(e),this.#d()}writeStderr(e){this.#r+=e}async getStdout(){if(this.stdoutToFile)try{let e=await o0(this.path,"utf-8");return this.#n=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#r}get outputFileSize(){return this.#n}get outputFileRedundant(){return this.#n<=this.#t}#d(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&n0(no(),{recursive:!0}).then(()=>s0(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await i0(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#r="",this.#i=null,this.deleteOutputFile())}};function d0(t){let e=0;for(let r=0;r<t.length;r++)t.charCodeAt(r)===10&&e++;return e}var td=137,Qb=143,u0=5e3,rd=5*1024*1024*1024,Vs=class{#e;#r;#o;#s=!1;constructor(e,r,n){this.#e=e,this.#r=r,this.#o=n,e.setEncoding("utf-8"),e.on("data",this.#t)}#t=e=>{let r=typeof e=="string"?e:e.toString();this.#o?this.#r.writeStderr(r):this.#r.writeStdout(r)};cleanup(){this.#s||(this.#s=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#r=null)}},nd=class t{#e="running";#r;#o;#s;#t;#i=null;#n=null;#a=!1;#d;#c;#u;#g;#b;#p=null;#m=null;#l=null;taskOutput;result;onTimeout;constructor(e,r,n,o,s=!1,i=rd){this.#t=e,this.#c=r,this.#g=n,this.#b=s,this.#d=i,this.taskOutput=o,this.#s=e.stderr?new Vs(e.stderr,o,!0):null,this.#o=e.stdout?new Vs(e.stdout,o,!1):null,s&&(this.onTimeout=a=>{this.#u=a}),this.result=this.#A()}get status(){return this.#e}static#k(e){e.#b&&e.#u?e.#u(e.background.bind(e)):e.#y(Qb)}#R(){this.#c.reason!=="interrupt"&&this.kill()}#S(e,r){let n=e??(r==="SIGTERM"?144:1);this.#f(n)}#w(){this.#f(1)}#f(e){this.#m&&(this.#m(e),this.#m=null)}#h(){this.#v(),this.#i&&(clearTimeout(this.#i),this.#i=null),this.#l&&(this.#c.removeEventListener("abort",this.#l),this.#l=null)}#v(){this.#n&&(clearInterval(this.#n),this.#n=null)}#T(){this.#n=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(r=>{r.size>this.#d&&this.#e==="backgrounded"&&this.#n!==null&&(this.#a=!0,this.#v(),this.#y(td))},()=>{}))},u0),this.#n.unref?.()}#A(){this.#l=this.#R.bind(this),this.#c.addEventListener("abort",this.#l,{once:!0}),this.#t.once("exit",this.#S.bind(this)),this.#t.once("error",this.#w.bind(this)),this.#i=setTimeout(t.#k,this.#g,this);let e=new Promise(r=>{this.#m=r});return new Promise(r=>{this.#p=r,e.then(this.#x.bind(this))})}async#x(e){this.#h(),(this.#e==="running"||this.#e==="backgrounded")&&(this.#e="completed");let r=await this.taskOutput.getStdout(),n={code:e,stdout:r,stderr:this.taskOutput.getStderr(),interrupted:e===td,backgroundTaskId:this.#r};this.taskOutput.stdoutToFile&&!this.#r&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(n.outputFilePath=this.taskOutput.path,n.outputFileSize=this.taskOutput.outputFileSize)),this.#a?n.stderr=`Background command killed: output file exceeded ${rd} bytes. ${n.stderr}`:e===Qb&&(n.stderr=`Command timed out after ${this.#g}ms. ${n.stderr}`),this.#p&&(this.#p(n),this.#p=null)}#y(e){this.#e="killed";let r=this.#t.pid;if(r)try{if(process.platform==="win32")import("node:child_process").then(({execSync:n})=>{try{n(`taskkill /PID ${r} /T /F`,{stdio:"ignore"})}catch{}});else try{process.kill(-r,"SIGKILL")}catch{try{process.kill(r,"SIGKILL")}catch{}}}catch{try{this.#t.kill("SIGKILL")}catch{}}this.#f(e??td)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#r=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#T():this.taskOutput.spillToDisk(),!0):!1}cleanup(){this.#o?.cleanup(),this.#s?.cleanup(),this.taskOutput.clear(),this.#h(),this.#t=null,this.#c=null,this.#u=void 0}};function od(t,e,r,n,o=!1,s=rd){return new nd(t,e,r,n,o,s)}function Xs(t,e){let r=new gr(tr("local_bash"),null);return{status:"killed",result:Promise.resolve({code:e?.code??145,stdout:"",stderr:e?.stderr??"Command aborted before execution",interrupted:!0,backgroundTaskId:t}),taskOutput:r,background:()=>!1,kill:()=>{},cleanup:()=>{}}}function sd(t){let e=new gr(tr("local_bash"),null);return{status:"completed",result:Promise.resolve({code:1,stdout:"",stderr:t,interrupted:!1,preSpawnError:t}),taskOutput:e,background:()=>!1,kill:()=>{},cleanup:()=>{}}}var p0=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","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"]),m0=["_SECRET","_TOKEN","_PASSWORD","_CREDENTIAL","_API_KEY","SECRET_","TOKEN_","PASSWORD_","CREDENTIAL_","_AUTH_","PRIVATE_KEY"];function id(){let t={...process.env};for(let e of Object.keys(t))g0(e)&&delete t[e];return t}function g0(t){if(p0.has(t))return!0;let e=t.toUpperCase();for(let r of m0)if(e.includes(r))return!0;return!1}var S0=1800*1e3,Js=process.cwd(),ev=process.cwd();function Qs(){return Js}function ad(t,e){Js=k0(t)?t:R0(e||Js,t)}function tv(){return ev}function Zs(t){Js=t,ev=t}var cd=null;function oo(t){cd={provider:t}}function rv(){if(!cd)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return cd.provider}async function ei(t,e,r,n){let{timeout:o,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:c,cwd:l}=n??{},d=o||S0,u=r??Ql(),p=rv(),m=Zl(),{commandString:g,cwdFilePath:f}=await p.buildExecCommand(t,{id:m,useSandbox:!1}),h=g,v=l??Qs();try{await Zb(v)}catch{let N=tv();try{await Zb(N),ad(N),v=N}catch{return sd(`Working directory "${v}" no longer exists.`)}}if(e.aborted)return Xs();let b=p.shellPath,S=p.getSpawnArgs(h),T=await p.getEnvironmentOverrides(t),R=!!c,P=tr("local_bash"),I=new gr(P,s??null,!R);await b0(no(),{recursive:!0});let E;if(!R){let N=Ys.O_NOFOLLOW??0;E=await v0(I.path,process.platform==="win32"?"w":Ys.O_WRONLY|Ys.O_CREAT|Ys.O_APPEND|N)}try{let N=f0(b,S,{env:{...id(),GIT_EDITOR:"true",QLOGICAGENT:"1",...T},cwd:v,stdio:R?["pipe","pipe","pipe"]:["pipe",E?.fd,E?.fd],detached:p.detached,windowsHide:!0}),xe=od(N,e,d,I,a);if(E!==void 0)try{await E.close()}catch{}return N.stdout&&c&&N.stdout.on("data",k=>{c(typeof k=="string"?k:k.toString())}),f&&xe.result.then(k=>{if(k&&!i&&!k.backgroundTaskId){try{let Q=h0(f,{encoding:"utf8"}).trim();Q&&Q.normalize("NFC")!==v&&ad(Q,v)}catch{}try{y0(f)}catch{}}}),xe}catch(N){if(E!==void 0)try{await E.close()}catch{}return I.clear(),Xs(void 0,{code:126,stderr:N instanceof Error?N.message:String(N)})}}var A0="exec",x0={type:"object",properties:{command:{type:"string",description:Nr()?"Shell command to execute in PowerShell.":"Shell command to execute in bash. Use Unix-style commands (ls, cat, mkdir -p, etc.)."},description:{type:"string",description:'Clear, concise description of what this command does (e.g. "Install dependencies", "Run unit tests"). Used for UI display and permission logging. For simple commands keep it 5-10 words; for complex piped/flagged commands add enough context to clarify intent.'},workdir:{type:"string",description:"Working directory for the command."},timeout:{type:"number",description:"Timeout in milliseconds (default: 120000). Only applies to foreground commands. Max allowed: 600000 (10 min)."},background:{type:"boolean",description:"If true, start the command in the background and return immediately with a task ID. Use getOutput to check on it later. Good for dev servers, watchers, long builds. Default: false."}},required:["command"]},P0=12e4,C0=6e5,ti=3e4;function so(t,e){if(t.length<=e)return t;let r=Math.floor(e/2)-50;return`${t.slice(0,r)}
|
|
425
|
+
`),parameters:QM,execute:async(t,e)=>({content:[{type:"text",text:"Thought recorded. Now proceed with the best action based on your reasoning."}],details:{type:"think"}})}}import{isAbsolute as w0,resolve as T0}from"node:path";var Gb=new Set(["find","grep","rg","ag","ack","locate","which","whereis"]),Kb=new Set(["cat","head","tail","less","more","wc","stat","file","strings","jq","awk","cut","sort","uniq","tr"]),zb=new Set(["ls","tree","du"]);var Vb=new Set(["mv","cp","rm","mkdir","rmdir","chmod","chown","chgrp","touch","ln","cd","export","unset","wait"]);function ZM(t){let r=t.replace(/\\\n/g," ").trim().split(/[|;&]/).shift()?.trim()??"";if(!r)return null;let n=r.split(/\s+/),o=0;for(;o<n.length&&/^[A-Za-z_]\w*=/.test(n[o]);)o++;let s=/^(?:timeout|time|nice|nohup|stdbuf|command|builtin|exec)$/;for(;o<n.length;){let c=n[o];if(s.test(c)){for(o++;o<n.length&&/^[-+]/.test(n[o]);)o++;o<n.length&&/^\d+(?:\.\d+)?[smhd]?$/.test(n[o])&&o++;continue}break}if(o>=n.length)return null;let i=n[o],a=i.lastIndexOf("/");return a>=0?i.slice(a+1):i}function Xb(t){return/(?:^|[;&|])\s*(?:cd|pushd|popd)\b/.test(t)}function Xl(t){let e=ZM(t),r=e!==null&&Gb.has(e),n=e!==null&&Kb.has(e),o=e!==null&&zb.has(e),s=e!==null&&Vb.has(e),i=/(?:[^2]>|^>|\|>)/.test(t),a=Xb(t),c=(r||n||o)&&!i&&!a;return{firstCommand:e,isSearch:r,isRead:n,isList:o,isSilent:s,isConcurrencySafe:c,isReadOnly:c}}var e0=t=>({isError:t!==0,message:t!==0?`Command failed with exit code ${t}`:void 0}),t0=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 r0(t){let e=t.trim(),r=e.split(/\s*\|\s*/);return(r[r.length-1]??e).trim().split(/\s+/)[0]??""}function Yl(t,e,r,n){let o=r0(t);return(t0.get(o)??e0)(e,r,n)}function Jl(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}import{spawn as f0}from"node:child_process";import{constants as Ys,readFileSync as h0,unlinkSync as y0}from"node:fs";import{mkdir as b0,open as v0,realpath as Zb}from"node:fs/promises";import{isAbsolute as k0,resolve as R0}from"node:path";function Nr(){if(process.platform!=="win32")return!1;let t=process.env.QLOGICAGENT_USE_POWERSHELL;return t==="1"||t==="true"}function Ql(){return Nr()?"powershell":"bash"}function Zl(){return Math.floor(Math.random()*65536).toString(16).padStart(4,"0")}import{mkdir as n0,readFile as o0,writeFile as s0,unlink as i0}from"node:fs/promises";import{join as Yb}from"node:path";import{tmpdir as a0}from"node:os";var c0=8*1024*1024,l0=5*1024*1024*1024;var ed;function no(){if(!ed){let t=Math.random().toString(36).slice(2,10);ed=Yb(a0(),"qla-tasks",t)}return ed}function Jb(t){return Yb(no(),`${t}.output`)}function rr(t="local_bash"){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var gr=class{taskId;path;stdoutToFile;#e="";#r="";#o=0;#s=0;#t;#i;#n=0;#a=!1;constructor(e,r,n=!1,o=c0){this.taskId=e,this.path=Jb(e),this.stdoutToFile=n,this.#t=o,this.#i=r}writeStdout(e){this.#e+=e,this.#s+=e.length,this.#o+=d0(e),this.#d()}writeStderr(e){this.#r+=e}async getStdout(){if(this.stdoutToFile)try{let e=await o0(this.path,"utf-8");return this.#n=Buffer.byteLength(e),e}catch{return""}return this.#e}getStderr(){return this.#r}get outputFileSize(){return this.#n}get outputFileRedundant(){return this.#n<=this.#t}#d(){this.#e.length>this.#t&&this.spillToDisk()}spillToDisk(){this.#e.length!==0&&n0(no(),{recursive:!0}).then(()=>s0(this.path,this.#e).catch(()=>{}))}async deleteOutputFile(){try{await i0(this.path)}catch{}}clear(){this.#a||(this.#a=!0,this.#e="",this.#r="",this.#i=null,this.deleteOutputFile())}};function d0(t){let e=0;for(let r=0;r<t.length;r++)t.charCodeAt(r)===10&&e++;return e}var td=137,Qb=143,u0=5e3,rd=5*1024*1024*1024,Vs=class{#e;#r;#o;#s=!1;constructor(e,r,n){this.#e=e,this.#r=r,this.#o=n,e.setEncoding("utf-8"),e.on("data",this.#t)}#t=e=>{let r=typeof e=="string"?e:e.toString();this.#o?this.#r.writeStderr(r):this.#r.writeStdout(r)};cleanup(){this.#s||(this.#s=!0,this.#e.removeListener("data",this.#t),this.#e=null,this.#r=null)}},nd=class t{#e="running";#r;#o;#s;#t;#i=null;#n=null;#a=!1;#d;#c;#u;#g;#b;#p=null;#m=null;#l=null;taskOutput;result;onTimeout;constructor(e,r,n,o,s=!1,i=rd){this.#t=e,this.#c=r,this.#g=n,this.#b=s,this.#d=i,this.taskOutput=o,this.#s=e.stderr?new Vs(e.stderr,o,!0):null,this.#o=e.stdout?new Vs(e.stdout,o,!1):null,s&&(this.onTimeout=a=>{this.#u=a}),this.result=this.#A()}get status(){return this.#e}static#k(e){e.#b&&e.#u?e.#u(e.background.bind(e)):e.#y(Qb)}#R(){this.#c.reason!=="interrupt"&&this.kill()}#S(e,r){let n=e??(r==="SIGTERM"?144:1);this.#f(n)}#w(){this.#f(1)}#f(e){this.#m&&(this.#m(e),this.#m=null)}#h(){this.#v(),this.#i&&(clearTimeout(this.#i),this.#i=null),this.#l&&(this.#c.removeEventListener("abort",this.#l),this.#l=null)}#v(){this.#n&&(clearInterval(this.#n),this.#n=null)}#T(){this.#n=setInterval(()=>{import("node:fs/promises").then(({stat:e})=>e(this.taskOutput.path).then(r=>{r.size>this.#d&&this.#e==="backgrounded"&&this.#n!==null&&(this.#a=!0,this.#v(),this.#y(td))},()=>{}))},u0),this.#n.unref?.()}#A(){this.#l=this.#R.bind(this),this.#c.addEventListener("abort",this.#l,{once:!0}),this.#t.once("exit",this.#S.bind(this)),this.#t.once("error",this.#w.bind(this)),this.#i=setTimeout(t.#k,this.#g,this);let e=new Promise(r=>{this.#m=r});return new Promise(r=>{this.#p=r,e.then(this.#x.bind(this))})}async#x(e){this.#h(),(this.#e==="running"||this.#e==="backgrounded")&&(this.#e="completed");let r=await this.taskOutput.getStdout(),n={code:e,stdout:r,stderr:this.taskOutput.getStderr(),interrupted:e===td,backgroundTaskId:this.#r};this.taskOutput.stdoutToFile&&!this.#r&&(this.taskOutput.outputFileRedundant?this.taskOutput.deleteOutputFile():(n.outputFilePath=this.taskOutput.path,n.outputFileSize=this.taskOutput.outputFileSize)),this.#a?n.stderr=`Background command killed: output file exceeded ${rd} bytes. ${n.stderr}`:e===Qb&&(n.stderr=`Command timed out after ${this.#g}ms. ${n.stderr}`),this.#p&&(this.#p(n),this.#p=null)}#y(e){this.#e="killed";let r=this.#t.pid;if(r)try{if(process.platform==="win32")import("node:child_process").then(({execSync:n})=>{try{n(`taskkill /PID ${r} /T /F`,{stdio:"ignore"})}catch{}});else try{process.kill(-r,"SIGKILL")}catch{try{process.kill(r,"SIGKILL")}catch{}}}catch{try{this.#t.kill("SIGKILL")}catch{}}this.#f(e??td)}kill(){this.#y()}background(e){return this.#e==="running"?(this.#r=e,this.#e="backgrounded",this.#h(),this.taskOutput.stdoutToFile?this.#T():this.taskOutput.spillToDisk(),!0):!1}cleanup(){this.#o?.cleanup(),this.#s?.cleanup(),this.taskOutput.clear(),this.#h(),this.#t=null,this.#c=null,this.#u=void 0}};function od(t,e,r,n,o=!1,s=rd){return new nd(t,e,r,n,o,s)}function Xs(t,e){let r=new gr(rr("local_bash"),null);return{status:"killed",result:Promise.resolve({code:e?.code??145,stdout:"",stderr:e?.stderr??"Command aborted before execution",interrupted:!0,backgroundTaskId:t}),taskOutput:r,background:()=>!1,kill:()=>{},cleanup:()=>{}}}function sd(t){let e=new gr(rr("local_bash"),null);return{status:"completed",result:Promise.resolve({code:1,stdout:"",stderr:t,interrupted:!1,preSpawnError:t}),taskOutput:e,background:()=>!1,kill:()=>{},cleanup:()=>{}}}var p0=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","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"]),m0=["_SECRET","_TOKEN","_PASSWORD","_CREDENTIAL","_API_KEY","SECRET_","TOKEN_","PASSWORD_","CREDENTIAL_","_AUTH_","PRIVATE_KEY"];function id(){let t={...process.env};for(let e of Object.keys(t))g0(e)&&delete t[e];return t}function g0(t){if(p0.has(t))return!0;let e=t.toUpperCase();for(let r of m0)if(e.includes(r))return!0;return!1}var S0=1800*1e3,Js=process.cwd(),ev=process.cwd();function Qs(){return Js}function ad(t,e){Js=k0(t)?t:R0(e||Js,t)}function tv(){return ev}function Zs(t){Js=t,ev=t}var cd=null;function oo(t){cd={provider:t}}function rv(){if(!cd)throw new Error("Shell provider not configured. Call setShellProvider() at startup.");return cd.provider}async function ei(t,e,r,n){let{timeout:o,onProgress:s,preventCwdChanges:i,shouldAutoBackground:a,onStdout:c,cwd:l}=n??{},d=o||S0,u=r??Ql(),p=rv(),m=Zl(),{commandString:g,cwdFilePath:f}=await p.buildExecCommand(t,{id:m,useSandbox:!1}),h=g,v=l??Qs();try{await Zb(v)}catch{let N=tv();try{await Zb(N),ad(N),v=N}catch{return sd(`Working directory "${v}" no longer exists.`)}}if(e.aborted)return Xs();let b=p.shellPath,S=p.getSpawnArgs(h),T=await p.getEnvironmentOverrides(t),R=!!c,P=rr("local_bash"),I=new gr(P,s??null,!R);await b0(no(),{recursive:!0});let E;if(!R){let N=Ys.O_NOFOLLOW??0;E=await v0(I.path,process.platform==="win32"?"w":Ys.O_WRONLY|Ys.O_CREAT|Ys.O_APPEND|N)}try{let N=f0(b,S,{env:{...id(),GIT_EDITOR:"true",QLOGICAGENT:"1",...T},cwd:v,stdio:R?["pipe","pipe","pipe"]:["pipe",E?.fd,E?.fd],detached:p.detached,windowsHide:!0}),xe=od(N,e,d,I,a);if(E!==void 0)try{await E.close()}catch{}return N.stdout&&c&&N.stdout.on("data",k=>{c(typeof k=="string"?k:k.toString())}),f&&xe.result.then(k=>{if(k&&!i&&!k.backgroundTaskId){try{let Q=h0(f,{encoding:"utf8"}).trim();Q&&Q.normalize("NFC")!==v&&ad(Q,v)}catch{}try{y0(f)}catch{}}}),xe}catch(N){if(E!==void 0)try{await E.close()}catch{}return I.clear(),Xs(void 0,{code:126,stderr:N instanceof Error?N.message:String(N)})}}var A0="exec",x0={type:"object",properties:{command:{type:"string",description:Nr()?"Shell command to execute in PowerShell.":"Shell command to execute in bash. Use Unix-style commands (ls, cat, mkdir -p, etc.)."},description:{type:"string",description:'Clear, concise description of what this command does (e.g. "Install dependencies", "Run unit tests"). Used for UI display and permission logging. For simple commands keep it 5-10 words; for complex piped/flagged commands add enough context to clarify intent.'},workdir:{type:"string",description:"Working directory for the command."},timeout:{type:"number",description:"Timeout in milliseconds (default: 120000). Only applies to foreground commands. Max allowed: 600000 (10 min)."},background:{type:"boolean",description:"If true, start the command in the background and return immediately with a task ID. Use getOutput to check on it later. Good for dev servers, watchers, long builds. Default: false."}},required:["command"]},P0=12e4,C0=6e5,ti=3e4;function so(t,e){if(t.length<=e)return t;let r=Math.floor(e/2)-50;return`${t.slice(0,r)}
|
|
426
426
|
|
|
427
427
|
... [truncated ${t.length-e} chars] ...
|
|
428
428
|
|
|
429
|
-
${t.slice(-r)}`}function I0(t){return t==null||t<=0?P0:Math.min(t,C0)}async function*E0(t){let{command:e,abortController:r,timeout:n,shouldAutoBackground:o,cwd:s}=t,i="",a=0,c=0,l=Date.now(),d=null;function u(){return new Promise(g=>{d=()=>g(null)})}let p=await ei(e,r.signal,void 0,{timeout:n,onProgress(g,f,h,v,b){i=f,a=h,c=v,d&&(d(),d=null)},shouldAutoBackground:o,cwd:s});for(p.onTimeout&&o&&p.onTimeout(g=>{let f=
|
|
430
|
-
IMPORTANT: Do NOT use this tool for file operations when dedicated tools exist. Use the 'write' tool instead of echo/cat/heredoc for creating files. Use the 'edit' tool instead of sed/awk for modifying files. Use the 'read' tool instead of cat/head/tail for reading files. Reserve this tool exclusively for system commands, builds, tests, and terminal operations that require shell execution.`,searchHint:"execute shell commands",parameters:x0,maxResultSizeChars:ti,execute:async(e,r)=>{let n=Xl(r.command);if(!r.background){let m=Jl(r.command);if(m)return{content:[{type:"text",text:`Command blocked: ${m}`}],details:{type:"exec",error:"blocked_sleep_pattern",classification:n}}}if(t.validateCommand){let m=await t.validateCommand(r.command);if(m)return{content:[{type:"text",text:`Command blocked: ${m}`}],details:{type:"exec",error:"blocked_by_guard",reason:m,classification:n}}}let o=new AbortController,s=I0(r.timeout),i=r.workdir?w0(r.workdir)?r.workdir:T0(Qs(),r.workdir):void 0;if(r.background){let m=await ei(r.command,o.signal,void 0,{shouldAutoBackground:!1,cwd:i}),g=
|
|
429
|
+
${t.slice(-r)}`}function I0(t){return t==null||t<=0?P0:Math.min(t,C0)}async function*E0(t){let{command:e,abortController:r,timeout:n,shouldAutoBackground:o,cwd:s}=t,i="",a=0,c=0,l=Date.now(),d=null;function u(){return new Promise(g=>{d=()=>g(null)})}let p=await ei(e,r.signal,void 0,{timeout:n,onProgress(g,f,h,v,b){i=f,a=h,c=v,d&&(d(),d=null)},shouldAutoBackground:o,cwd:s});for(p.onTimeout&&o&&p.onTimeout(g=>{let f=rr("bg");g(f)});p.status==="running"&&await Promise.race([u(),p.result])===null;)yield{type:"exec_progress",output:i.slice(-4096),fullOutput:i,elapsedTimeSeconds:(Date.now()-l)/1e3,totalLines:a,totalBytes:c};let m=await p.result;return p.cleanup(),m}function nv(t={}){return{name:A0,label:"Execute Command",description:"Execute a shell command. Supports foreground (blocking, returns output) and background (non-blocking, returns task ID) modes. "+(Nr()?"Uses PowerShell. ":"Uses bash. ")+`Commands are classified for safety: search/read commands may run in parallel; silent commands (mv, cp, rm) show 'Done' instead of empty output. Output is truncated and persisted if too long.
|
|
430
|
+
IMPORTANT: Do NOT use this tool for file operations when dedicated tools exist. Use the 'write' tool instead of echo/cat/heredoc for creating files. Use the 'edit' tool instead of sed/awk for modifying files. Use the 'read' tool instead of cat/head/tail for reading files. Reserve this tool exclusively for system commands, builds, tests, and terminal operations that require shell execution.`,searchHint:"execute shell commands",parameters:x0,maxResultSizeChars:ti,execute:async(e,r)=>{let n=Xl(r.command);if(!r.background){let m=Jl(r.command);if(m)return{content:[{type:"text",text:`Command blocked: ${m}`}],details:{type:"exec",error:"blocked_sleep_pattern",classification:n}}}if(t.validateCommand){let m=await t.validateCommand(r.command);if(m)return{content:[{type:"text",text:`Command blocked: ${m}`}],details:{type:"exec",error:"blocked_by_guard",reason:m,classification:n}}}let o=new AbortController,s=I0(r.timeout),i=r.workdir?w0(r.workdir)?r.workdir:T0(Qs(),r.workdir):void 0;if(r.background){let m=await ei(r.command,o.signal,void 0,{shouldAutoBackground:!1,cwd:i}),g=rr("bg");if(m.background(g))return{content:[{type:"text",text:`Background task started (id: ${g}).
|
|
431
431
|
Use getOutput to check on it later.`}],details:{type:"exec_background",backgroundTaskId:g,description:r.description,classification:n}}}let a=E0({command:r.command,abortController:o,timeout:s,shouldAutoBackground:!0,cwd:i}),c;do c=await a.next(),!c.done&&t.onProgress&&t.onProgress(c.value);while(!c.done);let l=c.value,d=[];if(l.backgroundTaskId)return{content:[{type:"text",text:`Command auto-backgrounded (task: ${l.backgroundTaskId}).`}],details:{type:"exec_background",backgroundTaskId:l.backgroundTaskId,assistantAutoBackgrounded:l.assistantAutoBackgrounded,classification:n}};l.outputFilePath?(d.push(so(l.stdout,ti)),d.push(`[full output: ${l.outputFilePath} (${l.outputFileSize} bytes)]`)):l.stdout&&d.push(so(l.stdout,ti)),l.stderr&&d.push(`[stderr]
|
|
432
432
|
${so(l.stderr,Math.floor(ti/4))}`),l.interrupted&&d.push(`[interrupted \u2014 exit code ${l.code}]`);let u=l.code!==0?Yl(r.command,l.code,l.stdout,l.stderr):void 0;u&&!u.isError&&u.message&&d.push(`[exit ${l.code}: ${u.message}]`);let p;return l.code!==0&&t.interpretExitCode&&(!u||u.isError)&&(p=t.interpretExitCode(l.code,l.stderr),p&&d.push(`[exit ${l.code}: ${p}]`)),d.length===0&&d.push(n.isSilent&&l.code===0?"Done":`(exit code ${l.code}, no output)`),{content:[{type:"text",text:d.join(`
|
|
433
433
|
`)}],details:{type:"exec",exitCode:l.code,interrupted:l.interrupted,stdout:so(l.stdout,8e3),stderr:so(l.stderr,4e3),description:r.description,returnCodeInterpretation:p??u?.message,noOutputExpected:n.isSilent,outputFilePath:l.outputFilePath,semanticNonError:u?!u.isError:void 0,classification:n}}}}}import{tmpdir as _0}from"node:os";import{join as M0,posix as ld}from"node:path";function D0(t){return t.replace(/(\d?)>nul\b/gi,(e,r)=>`${r||""}>/dev/null`)}function N0(t){return!(/(?:^|[;&|])\s*<\s/.test(t)||/<<[-]?\s*['"]?[A-Za-z_]/.test(t))}function L0(t,e){return`$'${t.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n")}'${e?" < /dev/null":""}`}function ov(t){return process.platform!=="win32"?t:t.replace(/^([A-Za-z]):/,(e,r)=>`/${r.toLowerCase()}`).replace(/\\/g,"/")}function ri(t,e){let r=e?.snapshotFilePath;return{type:"bash",shellPath:t,detached:!0,async buildExecCommand(n,o){let s=process.platform==="win32",i=_0(),a=s?ov(i):i,c=o.useSandbox&&o.sandboxTmpDir?ld.join(o.sandboxTmpDir,`cwd-${o.id}`):ld.join(a,`qla-${o.id}-cwd`),l=o.useSandbox&&o.sandboxTmpDir?ld.join(o.sandboxTmpDir,`cwd-${o.id}`):M0(i,`qla-${o.id}-cwd`),d=D0(n),u=N0(d),p=L0(d,u),m=[];if(r){let f=s?ov(r):r;m.push(`source '${f}' 2>/dev/null || true`)}return e?.sessionEnvScript&&m.push(e.sessionEnvScript),m.push(`eval ${p}`),m.push(`pwd -P >| '${c}'`),{commandString:m.join(" && "),cwdFilePath:l}},getSpawnArgs(n){return["-c",...!!r?[]:["-l"],n]},async getEnvironmentOverrides(n){return{GIT_EDITOR:"true",QLOGICAGENT:"1"}}}}import{tmpdir as O0}from"node:os";import{join as j0,posix as $0}from"node:path";function sv(t){return Buffer.from(t,"utf16le").toString("base64")}function U0(t){return["-NoProfile","-NonInteractive","-Command",t]}function dd(t){return{type:"powershell",shellPath:t,detached:!1,async buildExecCommand(e,r){let n=r.useSandbox&&r.sandboxTmpDir?$0.join(r.sandboxTmpDir,`qla-pwd-ps-${r.id}`):j0(O0(),`qla-pwd-ps-${r.id}`),s=["","$_ec = if ($null -ne $LASTEXITCODE) { $LASTEXITCODE } elseif ($?) { 0 } else { 1 }",`(Get-Location).Path | Out-File -FilePath '${n.replace(/'/g,"''")}' -Encoding utf8 -NoNewline`,"exit $_ec"].join(`
|
|
@@ -514,7 +514,7 @@ exit: Leave worktree (keep or remove it).
|
|
|
514
514
|
list: Show all active worktrees.`},name:{type:"string",description:"Worktree/branch name (for enter). Must be kebab-case, max 64 characters. If omitted, auto-generated from task context."},exitAction:{type:"string",enum:["keep","remove"],description:"For exit: 'keep' retains the worktree for later use; 'remove' deletes it."},discardChanges:{type:"boolean",description:"Required true to confirm discarding uncommitted changes when exitAction='remove'. Safety mechanism to prevent data loss."}},required:["action"]},yD=/^[a-z0-9][a-z0-9-]{0,62}[a-z0-9]?$/;function Av(t){return{name:fD,label:"Git Worktree",description:"Create isolated git worktree branches for parallel development. Each worktree has its own working directory independent of the main branch. Use for: parallel features, safe experimentation, sub-agent isolation. Exit to keep or remove the worktree when done.",parameters:hD,execute:async(e,r)=>{switch(r.action){case"enter":{if(t.isInWorktree())return{content:[{type:"text",text:"Error: already in a worktree. Exit first before entering another."}],details:{type:"worktree",error:"already_in_worktree"}};if(r.name&&!yD.test(r.name))return{content:[{type:"text",text:"Error: name must be kebab-case (a-z, 0-9, hyphens), 2-64 characters."}],details:{type:"worktree",error:"invalid_name"}};let n=await t.enterWorktree(r.name);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error||"failed to create worktree"}`}],details:{type:"worktree",error:n.error}};let o=n.worktree;return{content:[{type:"text",text:[`Entered worktree: ${o.name}`,` Branch: ${o.branch}`,` Path: ${o.path}`,"","Working in isolated branch. Changes here do not affect the main branch.","Use action='exit' when done (keep or remove)."].join(`
|
|
515
515
|
`)}],details:{type:"worktree",action:"enter",name:o.name,branch:o.branch,path:o.path}}}case"exit":{if(!t.isInWorktree())return{content:[{type:"text",text:"Error: not in a worktree."}],details:{type:"worktree",error:"not_in_worktree"}};let n=r.exitAction||"keep";if(n==="remove"){let i=t.currentWorktree?.();if(i&&(i.hasChanges||i.unpushedCommits>0)&&!r.discardChanges){let a=[];return i.hasChanges&&a.push("uncommitted changes"),i.unpushedCommits>0&&a.push(`${i.unpushedCommits} unpushed commit(s)`),{content:[{type:"text",text:`Error: worktree has ${a.join(" and ")}. Set discardChanges=true to confirm removal, or use exitAction='keep'.`}],details:{type:"worktree",error:"has_changes",hasChanges:i.hasChanges,unpushedCommits:i.unpushedCommits}}}}let o=await t.exitWorktree(n,r.discardChanges);return o.success?{content:[{type:"text",text:`Exited worktree. ${n==="keep"?"Worktree kept for later use.":"Worktree removed."}
|
|
516
516
|
Restored to: ${o.previousCwd||"main workspace"}`}],details:{type:"worktree",action:"exit",exitAction:n,previousCwd:o.previousCwd}}:{content:[{type:"text",text:`Error: ${o.error||"failed to exit worktree"}`}],details:{type:"worktree",error:o.error}}}case"list":{let n=await t.listWorktrees();if(!n.worktrees||n.worktrees.length===0)return{content:[{type:"text",text:"No worktrees (only the main working tree)."}],details:{type:"worktree",action:"list",count:0}};let o=[`Worktrees (${n.worktrees.length}):`,""];for(let s of n.worktrees){let i=s.isCurrent?" \u2190 current":"",a=s.hasChanges?" (has changes)":"";o.push(` ${s.name} [${s.branch}]${i}${a}`),o.push(` path: ${s.path}`)}return{content:[{type:"text",text:o.join(`
|
|
517
|
-
`)}],details:{type:"worktree",action:"list",count:n.worktrees.length}}}default:return{content:[{type:"text",text:`Error: unknown action "${r.action}".`}],details:{type:"worktree",error:"unknown_action"}}}}}}D();import{execFile as bD}from"node:child_process";import{promisify as vD}from"node:util";import{join as Lr,resolve as xv,basename as hd}from"node:path";import{mkdir as Mv,rm as Dv,symlink as kD,readdir as
|
|
517
|
+
`)}],details:{type:"worktree",action:"list",count:n.worktrees.length}}}default:return{content:[{type:"text",text:`Error: unknown action "${r.action}".`}],details:{type:"worktree",error:"unknown_action"}}}}}}D();import{execFile as bD}from"node:child_process";import{promisify as vD}from"node:util";import{join as Lr,resolve as xv,basename as hd}from"node:path";import{mkdir as Mv,rm as Dv,symlink as kD,readdir as jV,stat as RD}from"node:fs/promises";var ao=vD(bD),SD=/^[a-zA-Z0-9._-]+$/,Pv=64;function Nv(t){if(t.length>Pv)throw new Error(`Invalid worktree name: must be ${Pv} characters or fewer (got ${t.length})`);for(let e of t.split("/")){if(e==="."||e==="..")throw new Error(`Invalid worktree name "${t}": must not contain "." or ".." path segments`);if(!SD.test(e))throw new Error(`Invalid worktree name "${t}": segment must contain only letters, digits, dots, underscores, and dashes`)}}function yd(t){return t.replaceAll("/","+")}function Lv(t){return`worktree-${yd(t)}`}var et=null;async function we(t,e){try{let{stdout:r,stderr:n}=await ao("git",t,{cwd:e??process.cwd(),env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:""},timeout:3e4});return{stdout:r,stderr:n,code:0}}catch(r){let n=r;return{stdout:n.stdout??"",stderr:n.stderr??String(r),code:n.code??1}}}async function io(t){let{stdout:e,code:r}=await we(["rev-parse","--show-toplevel"],t);return r===0?e.trim():null}async function Cv(t){let{stdout:e,code:r}=await we(["status","--porcelain"],t);return r!==0?-1:e.trim().split(`
|
|
518
518
|
`).filter(Boolean).length}async function Iv(t,e){let{stdout:r,code:n}=await we(["rev-list",`origin/${e}..${e}`,"--count"],t);return n!==0?0:parseInt(r.trim(),10)||0}async function Ov(t,e,r,n){for(let o of r){if(o.includes("..")||o.startsWith("/")||o.startsWith("\\")){n?.warn(`[worktree] skipping symlink for "${o}": path traversal detected`);continue}let s=Lr(t,o),i=Lr(e,o);try{await kD(s,i,"dir"),n?.info(`[worktree] symlinked ${o} from main repo to worktree`)}catch(a){let c=a.code;c!=="ENOENT"&&c!=="EEXIST"&&n?.warn(`[worktree] failed to symlink ${o} (${c??"unknown"}): ${a}`)}}}async function wD(t,e,r){let{code:n,stderr:o}=await we(["sparse-checkout","set","--cone","--",...r],t);if(n!==0)throw await we(["worktree","remove","--force",t],e),new Error(`Failed to configure sparse-checkout: ${o}`);let{code:s,stderr:i}=await we(["checkout","HEAD"],t);if(s!==0)throw await we(["worktree","remove","--force",t],e),new Error(`Failed to checkout sparse worktree: ${i}`);return!0}async function TD(){try{return await ao("tmux",["-V"],{timeout:5e3}),!0}catch{return!1}}function AD(t,e){return`${hd(t)}_${e}`.replace(/[/.]/g,"_")}async function xD(t,e){if(!await TD())return null;try{return await ao("tmux",["new-session","-d","-s",e,"-c",t],{timeout:1e4}),e}catch{return null}}async function Ev(t){try{return await ao("tmux",["kill-session","-t",t],{timeout:5e3}),!0}catch{return!1}}async function _v(t,e,r,n){let o=Zu(e),s=Lr(o,t);try{if(!(await RD(s)).isFile())return null}catch{return null}try{let{stdout:i,stderr:a}=await ao(s,[],{cwd:e,env:{...process.env,...r},timeout:3e4});return n?.info(`[worktree] hook ${t} succeeded: ${i.trim()}`),i.trim()||null}catch(i){return n?.warn(`[worktree] hook ${t} failed: ${i}`),null}}async function jv(t,e,r){Nv(e);let n=yd(e),o=Lv(e),s=Lr(t,".worktrees"),i=Lr(s,n);await Mv(s,{recursive:!0});let{code:a,stderr:c}=await we(["worktree","add","-B",o,i,"HEAD"],t);return a!==0?(r?.warn(`[worktree] agent worktree creation failed: ${c}`),null):(await Ov(t,i,["node_modules"],r),r?.info(`[worktree] agent worktree created: ${e} at ${i}`),{worktreePath:i,branch:o})}async function $v(t,e,r,n){let{code:o}=await we(["worktree","remove","--force",e],t);return o!==0&&(await Dv(e,{recursive:!0,force:!0}).catch(()=>{}),await we(["worktree","prune"],t)),await we(["branch","-D",r],t),n?.info(`[worktree] agent worktree removed: ${e}`),!0}function Uv(t){let{log:e,symlinkDirs:r=["node_modules"],sparsePaths:n}=t;return{async enterWorktree(o){try{let s=Date.now(),i=await io();if(!i)return{success:!1,error:"Not in a git repository"};let a=await _v("worktree-create",i,{WORKTREE_NAME:o??""},e);if(a){let I=process.cwd();return process.chdir(a),et={originalCwd:I,worktreePath:a,worktreeName:o??hd(a),worktreeBranch:"",hookBased:!0,creationDurationMs:Date.now()-s},{success:!0,worktree:{name:et.worktreeName,path:a,branch:"",isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let c=o??`agent-${Date.now().toString(36)}`;Nv(c);let l=yd(c),d=Lv(c),u=Lr(i,".worktrees"),p=Lr(u,l);await Mv(u,{recursive:!0});let{stdout:m}=await we(["worktree","list","--porcelain"],i),g=m.split(`
|
|
519
519
|
`).find(I=>I.startsWith("worktree ")&&I.includes(l));if(g){let I=g.replace("worktree ","").trim(),E=process.cwd();return process.chdir(I),et={originalCwd:E,worktreePath:I,worktreeName:c,worktreeBranch:d},e.info(`[worktree] resumed existing worktree: ${c} at ${I}`),{success:!0,worktree:{name:c,path:I,branch:d,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}let f=n&&n.length>0,h=["worktree","add"];f&&h.push("--no-checkout"),h.push("-B",d,p,"HEAD");let{code:v,stderr:b}=await we(h,i);if(v!==0)return{success:!1,error:`git worktree add failed: ${b.trim()}`};let S=!1;f&&n&&(await wD(p,i,n),S=!0),await Ov(i,p,r,e);let T=process.cwd();process.chdir(p);let R=AD(i,d),P=await xD(p,R);return et={originalCwd:T,worktreePath:p,worktreeName:c,worktreeBranch:d,tmuxSessionName:P??void 0,creationDurationMs:Date.now()-s,usedSparsePaths:S},e.info(`[worktree] entered: ${c} at ${p}`),{success:!0,worktree:{name:c,path:p,branch:d,isCurrent:!0,hasChanges:!1,unpushedCommits:0}}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}},async exitWorktree(o,s){if(!et)return{success:!1,error:"Not in a worktree"};try{let i=et,a=await io(i.originalCwd);if(!a)return{success:!1,error:"Original git root not found"};if(o==="remove"){let c=await Cv(i.worktreePath),l=await Iv(i.worktreePath,i.worktreeBranch);if((c>0||l>0)&&!s)return{success:!1,error:`Worktree has ${c} uncommitted change(s) and ${l} unpushed commit(s). Set discardChanges=true to confirm.`};process.chdir(i.originalCwd),et=null,i.tmuxSessionName&&await Ev(i.tmuxSessionName),await _v("worktree-remove",a,{WORKTREE_PATH:i.worktreePath},e);let d=["worktree","remove"];s&&d.push("--force"),d.push(i.worktreePath);let{code:u,stderr:p}=await we(d,a);u!==0&&(e.warn(`[worktree] git worktree remove failed: ${p.trim()}, cleaning up manually`),await Dv(i.worktreePath,{recursive:!0,force:!0}).catch(()=>{}),await we(["worktree","prune"],a)),await we(["branch","-D",i.worktreeBranch],a),e.info(`[worktree] removed: ${i.worktreeName}`)}else process.chdir(i.originalCwd),i.tmuxSessionName&&await Ev(i.tmuxSessionName),et=null,e.info(`[worktree] exited (kept): ${i.worktreeName}`);return{success:!0,previousCwd:i.originalCwd}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}},async listWorktrees(){try{let{stdout:o,code:s}=await we(["worktree","list","--porcelain"]);if(s!==0)return{success:!0,worktrees:[]};let i=[],a=process.cwd(),c=o.split(`
|
|
520
520
|
|
|
@@ -534,7 +534,7 @@ ${u}${p}`}],details:{type:"notebook_edit",edit_mode:o,cell_number:n,total_cells:
|
|
|
534
534
|
`),parameters:LD,execute:async(e,r,n)=>{let o=Math.max(1,Math.min(3600,Math.round(r.duration))),s=o*1e3,i=new AbortController,a=()=>i.abort();n?.addEventListener("abort",a,{once:!0}),n?.aborted&&i.abort();try{let c=await t.sleep(s,i.signal),l=[];return c.interrupted?(l.push(`Sleep interrupted after ${c.sleptSeconds}s.`),c.interruptReason&&l.push(`Reason: ${c.interruptReason}`),l.push("Check for new messages or tasks.")):l.push(`Slept for ${c.sleptSeconds}s. Waking up.`),{content:[{type:"text",text:l.join(`
|
|
535
535
|
`)}],details:{...c,requestedSeconds:o}}}finally{n?.removeEventListener("abort",a)}}}}var OD="tool_search",jD={type:"object",properties:{query:{type:"string",description:'Search query for tools. Use "select:toolName" to directly activate a deferred tool, or provide keywords to search tool names/descriptions. Prefix a term with "+" to mark it as required (all +terms must match).'},maxResults:{type:"number",description:"Maximum number of results to return (default: 5)."}},required:["query"]},$D=5;function zv(t){return{name:OD,label:"Tool Search",description:'Search for available tools that are not currently loaded. Many tools are deferred to save context tokens. Use "select:toolName" to directly activate a tool, or provide keywords to find relevant tools. Activated tools become available in subsequent messages.',parameters:jD,execute:async(e,r)=>{if(!r.query||r.query.trim().length===0)return{content:[{type:"text",text:"Error: query is required."}],details:{type:"tool_search",error:"empty_query"}};let n=r.query.trim(),o=r.maxResults??$D;if(n.startsWith("select:")){let i=n.slice(7).split(",").map(d=>d.trim()).filter(Boolean),a=[],c=[];if(t.activateTool)for(let d of i)await t.activateTool(d)?a.push(d):c.push(d);else{let d=await t.searchTools(n,{maxResults:o});return Kv(d)}let l=[];return a.length>0&&l.push(`Activated: ${a.join(", ")}. These tools are now available.`),c.length>0&&l.push(`Not found: ${c.join(", ")}.`),{content:[{type:"text",text:l.join(`
|
|
536
536
|
`)}],details:{type:"tool_search",activated:a,notFound:c,mode:"select"}}}let s=await t.searchTools(n,{maxResults:o});return Kv(s)}}}function Kv(t){if(t.matches.length===0)return{content:[{type:"text",text:`No tools found matching "${t.query}". Total deferred tools available: ${t.totalDeferred}.`}],details:{type:"tool_search",query:t.query,matchCount:0,totalDeferred:t.totalDeferred}};let e=[`Found ${t.matches.length} tool(s) matching "${t.query}" (${t.totalDeferred} total deferred):`,""];for(let r of t.matches)e.push(`- **${r.name}**: ${r.description}`);return e.push(""),e.push('Use "select:toolName" to activate a tool for use in subsequent messages.'),{content:[{type:"text",text:e.join(`
|
|
537
|
-
`)}],details:{type:"tool_search",query:t.query,matchCount:t.matches.length,totalDeferred:t.totalDeferred,matches:t.matches.map(r=>r.name)}}}var bd="image_generate",UD={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: e.g. '1024x1792' (portrait), '1792x1024' (landscape), '1024x1024' (square). Default: '1024x1024'."},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."},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 Vv(t){return{name:bd,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: If the user has not specified purpose or preferred style, use ask_user to clarify (e.g. purpose: social-media / wallpaper / poster; style: photorealistic / anime / watercolor) before calling this tool. 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. 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:UD,execute:async(e,r)=>{let n=await t.generateImage({prompt:r.prompt,purpose:r.purpose,style:r.style,size:r.size,imageUrl:r.image_url,n:r.n,quality:r.quality,seed:r.seed}),o=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${o} image${o>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"image_generate",model:n.model,size:n.size,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var FD={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 Xv(t){return{name:"tts",label:"TTS",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:FD,execute:async(e,r)=>{let n=await t.textToSpeech({text:r.text,channel:r.channel,voice:r.voice,speed:r.speed});return{content:[{type:"text",text:"\u5DF2\u6210\u529F\u751F\u6210\u8BED\u97F3\u3002"}],details:{type:"tts",audioPath:n.audioPath,provider:n.provider,voiceCompatible:n.voiceCompatible,mediaUrls:n.mediaUrls}}}}}var vd="video_generate",HD={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 Yv(t){return{name:vd,label:"Video Generate",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:HD,execute:async(e,r)=>{let n=await t.generateVideo({prompt:r.prompt,purpose:r.purpose,style:r.style,imageUrl:r.image_url,referenceVideos:r.reference_videos,referenceAudios:r.reference_audios,generateAudio:r.generate_audio,aspectRatio:r.aspect_ratio,duration:r.duration,resolution:r.resolution,fps:r.fps,seed:r.seed,cameraFixed:r.camera_fixed,returnLastFrame:r.return_last_frame,draft:r.draft,serviceTier:r.service_tier,callbackUrl:r.callback_url,safetyIdentifier:r.safety_identifier,executionExpiresAfterSeconds:r.execution_expires_after,videoTools:r.video_tools}),o=n.mediaUrls.length,s=[`Generated ${o} video${o>1?"s":""}`];return n.model&&s.push(`model: ${n.model}`),n.lastFrameUrl&&s.push(`last_frame: ${n.lastFrameUrl}`),n.taskId&&s.push(`task_id: ${n.taskId}`),{content:[{type:"text",text:s.length>1?`${s[0]} (${s.slice(1).join(", ")})`:s[0]}],details:{type:"video_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls,...n.taskId?{taskId:n.taskId}:{}}}}}}var kd="music_generate",BD={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 Jv(t){return{name:kd,label:"Music Generate",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:BD,execute:async(e,r)=>{let n=r.lyrics;if(!n&&!r.is_instrumental&&t.generateLyrics)try{n=await t.generateLyrics(r.prompt)}catch{}let o=await t.generateMusic({prompt:r.prompt,purpose:r.purpose,style:r.style,lyrics:n,duration:r.duration,isInstrumental:r.is_instrumental,audioUrl:r.cover_audio_url,audioFormat:r.audio_format}),s=o.mediaUrls.length;return{content:[{type:"text",text:`Generated ${s} audio track${s>1?"s":""}${o.model?` (model: ${o.model})`:""}`}],details:{type:"music_generate",model:o.model,durationMs:o.durationMs,mediaUrls:o.mediaUrls}}}}}var qD="video_edit",WD={type:"object",properties:{prompt:{type:"string",description:"Edit instruction. Reference videos as \u89C6\u98911, \u89C6\u98912, \u89C6\u98913. Reference images as \u56FE\u72471, \u56FE\u72472. Operations: add/remove/modify elements, extend, track fill."},source_videos:{type:"array",items:{type:"string"},minItems:1,maxItems:3,description:"Video(s) to edit (1-3 URLs). Order: [0]=\u89C6\u98911, [1]=\u89C6\u98912, [2]=\u89C6\u98913. All URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},reference_images:{type:"array",items:{type:"string"},maxItems:9,description:"Optional reference images for element replacement (up to 9). All URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},duration:{type:"number",minimum:4,maximum:15,description:"Output duration in seconds (4-15s). Default: same as source."},aspect_ratio:{type:"string",description:"Output aspect ratio: 16:9, 9:16, 1:1, 4:3, 3:4, 21:9. Default: same as source."},resolution:{type:"string",description:"Output resolution: '480p' or '720p'. Default: '720p'."}},required:["prompt","source_videos"]};function Qv(t){return{name:qD,label:"Video Edit",description:"Edit existing videos: add/remove/modify elements, extend, or bridge clips. Requires source_videos (max 3). Max 9 reference images for element replacement. Max 720p. All video/image URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file. For generating NEW videos from scratch, use video_generate instead.",parameters:WD,execute:async(e,r)=>{if(!r.source_videos?.length)return{content:[{type:"text",text:"Error: source_videos is required."}]};let n=await t.editVideo({prompt:r.prompt,sourceVideos:r.source_videos,referenceImages:r.reference_images,duration:r.duration,aspectRatio:r.aspect_ratio,resolution:r.resolution});return{content:[{type:"text",text:`Video edited successfully${n.model?` (model: ${n.model})`:""}`}],details:{type:"video_edit",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var GD="video_merge",KD={type:"object",properties:{clips:{type:"array",items:{type:"object",properties:{video:{type:"string",description:"Video URL or file path. MUST be publicly accessible HTTP/HTTPS URL. Use file_upload tool first if local file."},audio:{type:"string",description:"Narration audio file path (from TTS)."},trimStart:{type:"number",description:"Trim start in seconds (default 0)."},trimEnd:{type:"number",description:"Trim end in seconds (default: full)."}},required:["video"]},minItems:2,description:"Array of video clips to merge, in order."},transition:{type:"string",description:"Transition effect: 'crossfade' (default), 'fade', 'wipeleft', 'cut', 'dissolve', etc."},transitionDuration:{type:"number",description:"Transition duration in seconds (0.1-2.0, default 0.5)."},subtitles:{type:"string",description:"Path to SRT subtitle file to burn-in."},bgm:{type:"string",description:"Background music file path."},bgmVolume:{type:"number",description:"BGM volume (0.0-1.0, default 0.15)."},outputResolution:{type:"string",description:"Output resolution: '1920x1080', '1080x1920', etc. Default: auto."},outputFps:{type:"number",description:"Output FPS (default 30)."}},required:["clips"]};function Zv(t){return{name:GD,label:"Video Merge",description:"Merge multiple video clips into a single video with transitions, subtitles, and background music. Requires at least 2 clips. Supports crossfade, fade, wipe, dissolve, and cut transitions. All video/audio URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides local files. Audio per clip is preserved; BGM is mixed at adjustable volume.",parameters:KD,execute:async(e,r)=>{if(!r.clips||r.clips.length<2)return{content:[{type:"text",text:"Error: at least 2 clips are required for merging."}]};let n=await t.mergeVideos({clips:r.clips,transition:r.transition,transitionDuration:r.transitionDuration,subtitles:r.subtitles,bgm:r.bgm,bgmVolume:r.bgmVolume,outputResolution:r.outputResolution,outputFps:r.outputFps});return{content:[{type:"text",text:`Merged ${n.clipCount} clips \u2192 ${n.durationSec.toFixed(1)}s video`+(r.transition?` (transition: ${r.transition})`:"")}],details:{type:"video_merge",localPath:n.localPath,servePath:n.servePath,durationSec:n.durationSec,clipCount:n.clipCount,mediaUrls:n.mediaUrls}}}}}var zD="video_upscale",VD={type:"object",properties:{video:{type:"string",description:"Video URL to upscale. MUST be publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},targetResolution:{type:"string",description:"Target resolution: '1080p' (default, 1920x1080/1080x1920), '2k' (2560x1440/1440x2560)."},sharpness:{type:"string",description:"Sharpening intensity: 'light' (default), 'medium', 'strong'."}},required:["video"]};function ek(t){return{name:zD,label:"Video Upscale",description:"Upscale a video to higher resolution with optional sharpening. Auto-detects orientation (landscape/portrait). Uses Lanczos interpolation + unsharp mask. Supports 1080p and 2K targets. Video URL MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file. Best used as post-processing after video_merge.",parameters:VD,execute:async(e,r)=>{let n=await t.upscaleVideo({video:r.video,targetResolution:r.targetResolution,sharpness:r.sharpness});return{content:[{type:"text",text:`Upscaled to ${n.resolution}${r.sharpness?` (sharpness: ${r.sharpness})`:""}`}],details:{type:"video_upscale",localPath:n.localPath,servePath:n.servePath,resolution:n.resolution,durationSec:n.durationSec,mediaUrls:n.mediaUrls}}}}}var XD="three_d_generate",YD={type:"object",properties:{prompt:{type:"string",description:"3D model generation prompt. Describe the object's shape, material, texture, color, and pose. For text-to-3D, provide a detailed description. For image-to-3D, also provide image_url."},image_url:{type:"string",description:"Reference image URL for image-to-3D generation. The image should show the object clearly from a single viewpoint with clean background for best results. MUST be a publicly accessible HTTP/HTTPS URL. Local file paths and data: URLs are NOT supported."},output_format:{type:"string",description:"3D model output format: 'glb' (default), 'obj', 'usd', 'usdz'."},seed:{type:"number",description:"Random seed for reproducible generation."}},required:["prompt"]};function tk(t){return{name:XD,label:"3D Generate",description:"Generate a 3D model from a text prompt or reference image. Supports text-to-3D and image-to-3D workflows. Output formats include GLB, OBJ, USD. The generated model can be viewed in any 3D viewer or imported into game engines. IMPORTANT: Describe the object in detail \u2014 shape, size, material, texture, color, and pose.",parameters:YD,execute:async(e,r)=>{let n=await t.generate3D({prompt:r.prompt,imageUrl:r.image_url,outputFormat:r.output_format,seed:r.seed}),o=n.mediaUrls.length,s=`Generated ${o} 3D model${o>1?"s":""}${n.model?` (model: ${n.model})`:""}`;return o===0&&n.metadata?.debugResponseKeys&&(s+=` [debug: response keys=${JSON.stringify(n.metadata.debugResponseKeys)}, content=${n.metadata.debugContentSample??"null"}]`),{content:[{type:"text",text:s}],details:{type:"three_d_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls,...n.metadata??{}}}}}}var JD={type:"object",properties:{audio_url:{type:"string",description:"URL of the audio file to transcribe. Supports mp3, wav, m4a, ogg, flac formats. MUST be a publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},language:{type:"string",description:"Language hint for transcription: 'zh' (Chinese), 'en' (English), or auto-detect if omitted."}},required:["audio_url"]};function rk(t){return{name:"stt",label:"STT",description:"Transcribe audio to text (Speech-to-Text). Provide an audio file URL and receive the spoken content as text. Supports Chinese and English. Use for meeting transcription, voice message reading, subtitle generation, or any audio-to-text conversion.",parameters:JD,execute:async(e,r)=>{if(!r.audio_url)return{content:[{type:"text",text:"Error: audio_url parameter is required. Provide a publicly accessible HTTP/HTTPS URL to an audio file."}],details:{error:"audio_url parameter is required"}};let n=await t.speechToText({audioUrl:r.audio_url,language:r.language}),o=n.transcription.length>200?n.transcription.slice(0,200)+"\u2026":n.transcription;return{content:[{type:"text",text:n.transcription}],details:{type:"stt",model:n.model,durationMs:n.durationMs,transcriptionLength:n.transcription.length,preview:o}}}}}var QD="voice_clone",ZD={type:"object",properties:{text:{type:"string",description:"Text to synthesize in the cloned voice."},sample_audio_url:{type:"string",description:"URL of an audio sample (5-30 seconds recommended) of the voice to clone. The sample should be clear speech with minimal background noise. MUST be a publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},speed:{type:"number",description:"Speech speed multiplier (0.5-2.0). Default is 1.0."}},required:["text","sample_audio_url"]};function nk(t){return{name:QD,label:"Voice Clone",description:"Clone a voice from an audio sample and synthesize new speech in that voice. Requires a clear audio sample (5-30s recommended) of the target voice. Use for personalized narration, character voices, or voice preservation. DO NOT use for impersonation or deception. For standard TTS with preset voices, use the tts tool instead.",parameters:ZD,execute:async(e,r)=>{let n=await t.cloneVoice({text:r.text,sampleAudioUrl:r.sample_audio_url,speed:r.speed});return{content:[{type:"text",text:`Voice cloned and synthesized speech${n.model?` (model: ${n.model})`:""}`}],details:{type:"voice_clone",model:n.model,voiceId:n.voiceId,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var eN="media_cancel",tN={type:"object",properties:{task_id:{type:"string",description:"The task ID of the media generation to cancel (returned in previous generation results)."},provider:{type:"string",description:"Provider name (e.g. 'doubao', 'zhipu'). If omitted, auto-detects from task context."}},required:["task_id"]};function ok(t){return{name:eN,label:"Media Cancel",description:"Cancel an in-progress media generation task (video, 3D, etc.). Provide the task_id from a previous generation result. Use this when a user wants to abort a long-running generation.",parameters:tN,execute:async(e,r)=>{if(!r.task_id)return{content:[{type:"text",text:"Error: task_id is required."}],details:{error:"task_id is required"}};let n=await t.cancelTask({taskId:r.task_id,provider:r.provider});return{content:[{type:"text",text:n.ok?`Task ${r.task_id} cancelled.`:`Cancel failed: ${n.message}`}],details:n.ok?void 0:{error:n.message}}}}}var rN="file_upload",nN={type:"object",properties:{file_path:{type:"string",description:"Absolute path to the local file to upload. Supported: images (jpg/png/webp/gif), audio (mp3/wav/m4a/ogg/flac), video (mp4/mov/avi). The file will be uploaded to the configured provider's Files API and a file ID or public URL will be returned."},purpose:{type:"string",description:"Upload purpose hint: 'media_reference' (for image/video/audio generation), 'user_data' (general). Default: 'media_reference'."}},required:["file_path"]};function sk(t){return{name:rN,label:"File Upload",description:"Upload a local file to the cloud provider's Files API. Returns a file ID (or public URL) that can be used as input for media generation tools (image_generate, video_generate, video_edit, etc.). Use this when the user provides a local file that needs to be referenced by URL in media tools. IMPORTANT: Only call this tool for files that actually need to be uploaded for media generation. Not all providers support file upload \u2014 tool availability depends on the configured provider.",parameters:nN,execute:async(e,r)=>{let n=await t.uploadFile({filePath:r.file_path,purpose:r.purpose}),o=[`Uploaded "${n.filename}" (${Rd(n.bytes)}) via ${n.provider}`];return n.url&&o.push(`URL: ${n.url}`),o.push(`File ID: ${n.fileId}`),{content:[{type:"text",text:o.join(`
|
|
537
|
+
`)}],details:{type:"tool_search",query:t.query,matchCount:t.matches.length,totalDeferred:t.totalDeferred,matches:t.matches.map(r=>r.name)}}}var bd="image_generate",UD={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: e.g. '1024x1792' (portrait), '1792x1024' (landscape), '1024x1024' (square). Default: '1024x1024'."},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."},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 Vv(t){return{name:bd,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. Do NOT invent Markdown image URLs, placeholder attachment paths, or claim an image was generated without this tool returning mediaUrls. 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:UD,execute:async(e,r)=>{let n=await t.generateImage({prompt:r.prompt,purpose:r.purpose,style:r.style,size:r.size,imageUrl:r.image_url,n:r.n,quality:r.quality,seed:r.seed}),o=n.mediaUrls.length;return{content:[{type:"text",text:`Generated ${o} image${o>1?"s":""}${n.model?` (model: ${n.model})`:""}`}],details:{type:"image_generate",model:n.model,size:n.size,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var FD={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 Xv(t){return{name:"tts",label:"TTS",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:FD,execute:async(e,r)=>{let n=await t.textToSpeech({text:r.text,channel:r.channel,voice:r.voice,speed:r.speed});return{content:[{type:"text",text:"\u5DF2\u6210\u529F\u751F\u6210\u8BED\u97F3\u3002"}],details:{type:"tts",audioPath:n.audioPath,provider:n.provider,voiceCompatible:n.voiceCompatible,mediaUrls:n.mediaUrls}}}}}var vd="video_generate",HD={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 Yv(t){return{name:vd,label:"Video Generate",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:HD,execute:async(e,r)=>{let n=await t.generateVideo({prompt:r.prompt,purpose:r.purpose,style:r.style,imageUrl:r.image_url,referenceVideos:r.reference_videos,referenceAudios:r.reference_audios,generateAudio:r.generate_audio,aspectRatio:r.aspect_ratio,duration:r.duration,resolution:r.resolution,fps:r.fps,seed:r.seed,cameraFixed:r.camera_fixed,returnLastFrame:r.return_last_frame,draft:r.draft,serviceTier:r.service_tier,callbackUrl:r.callback_url,safetyIdentifier:r.safety_identifier,executionExpiresAfterSeconds:r.execution_expires_after,videoTools:r.video_tools}),o=n.mediaUrls.length,s=[`Generated ${o} video${o>1?"s":""}`];return n.model&&s.push(`model: ${n.model}`),n.lastFrameUrl&&s.push(`last_frame: ${n.lastFrameUrl}`),n.taskId&&s.push(`task_id: ${n.taskId}`),{content:[{type:"text",text:s.length>1?`${s[0]} (${s.slice(1).join(", ")})`:s[0]}],details:{type:"video_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls,...n.taskId?{taskId:n.taskId}:{}}}}}}var kd="music_generate",BD={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 Jv(t){return{name:kd,label:"Music Generate",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:BD,execute:async(e,r)=>{let n=r.lyrics;if(!n&&!r.is_instrumental&&t.generateLyrics)try{n=await t.generateLyrics(r.prompt)}catch{}let o=await t.generateMusic({prompt:r.prompt,purpose:r.purpose,style:r.style,lyrics:n,duration:r.duration,isInstrumental:r.is_instrumental,audioUrl:r.cover_audio_url,audioFormat:r.audio_format}),s=o.mediaUrls.length;return{content:[{type:"text",text:`Generated ${s} audio track${s>1?"s":""}${o.model?` (model: ${o.model})`:""}`}],details:{type:"music_generate",model:o.model,durationMs:o.durationMs,mediaUrls:o.mediaUrls}}}}}var qD="video_edit",WD={type:"object",properties:{prompt:{type:"string",description:"Edit instruction. Reference videos as \u89C6\u98911, \u89C6\u98912, \u89C6\u98913. Reference images as \u56FE\u72471, \u56FE\u72472. Operations: add/remove/modify elements, extend, track fill."},source_videos:{type:"array",items:{type:"string"},minItems:1,maxItems:3,description:"Video(s) to edit (1-3 URLs). Order: [0]=\u89C6\u98911, [1]=\u89C6\u98912, [2]=\u89C6\u98913. All URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},reference_images:{type:"array",items:{type:"string"},maxItems:9,description:"Optional reference images for element replacement (up to 9). All URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file."},duration:{type:"number",minimum:4,maximum:15,description:"Output duration in seconds (4-15s). Default: same as source."},aspect_ratio:{type:"string",description:"Output aspect ratio: 16:9, 9:16, 1:1, 4:3, 3:4, 21:9. Default: same as source."},resolution:{type:"string",description:"Output resolution: '480p' or '720p'. Default: '720p'."}},required:["prompt","source_videos"]};function Qv(t){return{name:qD,label:"Video Edit",description:"Edit existing videos: add/remove/modify elements, extend, or bridge clips. Requires source_videos (max 3). Max 9 reference images for element replacement. Max 720p. All video/image URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file. For generating NEW videos from scratch, use video_generate instead.",parameters:WD,execute:async(e,r)=>{if(!r.source_videos?.length)return{content:[{type:"text",text:"Error: source_videos is required."}]};let n=await t.editVideo({prompt:r.prompt,sourceVideos:r.source_videos,referenceImages:r.reference_images,duration:r.duration,aspectRatio:r.aspect_ratio,resolution:r.resolution});return{content:[{type:"text",text:`Video edited successfully${n.model?` (model: ${n.model})`:""}`}],details:{type:"video_edit",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var GD="video_merge",KD={type:"object",properties:{clips:{type:"array",items:{type:"object",properties:{video:{type:"string",description:"Video URL or file path. MUST be publicly accessible HTTP/HTTPS URL. Use file_upload tool first if local file."},audio:{type:"string",description:"Narration audio file path (from TTS)."},trimStart:{type:"number",description:"Trim start in seconds (default 0)."},trimEnd:{type:"number",description:"Trim end in seconds (default: full)."}},required:["video"]},minItems:2,description:"Array of video clips to merge, in order."},transition:{type:"string",description:"Transition effect: 'crossfade' (default), 'fade', 'wipeleft', 'cut', 'dissolve', etc."},transitionDuration:{type:"number",description:"Transition duration in seconds (0.1-2.0, default 0.5)."},subtitles:{type:"string",description:"Path to SRT subtitle file to burn-in."},bgm:{type:"string",description:"Background music file path."},bgmVolume:{type:"number",description:"BGM volume (0.0-1.0, default 0.15)."},outputResolution:{type:"string",description:"Output resolution: '1920x1080', '1080x1920', etc. Default: auto."},outputFps:{type:"number",description:"Output FPS (default 30)."}},required:["clips"]};function Zv(t){return{name:GD,label:"Video Merge",description:"Merge multiple video clips into a single video with transitions, subtitles, and background music. Requires at least 2 clips. Supports crossfade, fade, wipe, dissolve, and cut transitions. All video/audio URLs MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides local files. Audio per clip is preserved; BGM is mixed at adjustable volume.",parameters:KD,execute:async(e,r)=>{if(!r.clips||r.clips.length<2)return{content:[{type:"text",text:"Error: at least 2 clips are required for merging."}]};let n=await t.mergeVideos({clips:r.clips,transition:r.transition,transitionDuration:r.transitionDuration,subtitles:r.subtitles,bgm:r.bgm,bgmVolume:r.bgmVolume,outputResolution:r.outputResolution,outputFps:r.outputFps});return{content:[{type:"text",text:`Merged ${n.clipCount} clips \u2192 ${n.durationSec.toFixed(1)}s video`+(r.transition?` (transition: ${r.transition})`:"")}],details:{type:"video_merge",localPath:n.localPath,servePath:n.servePath,durationSec:n.durationSec,clipCount:n.clipCount,mediaUrls:n.mediaUrls}}}}}var zD="video_upscale",VD={type:"object",properties:{video:{type:"string",description:"Video URL to upscale. MUST be publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},targetResolution:{type:"string",description:"Target resolution: '1080p' (default, 1920x1080/1080x1920), '2k' (2560x1440/1440x2560)."},sharpness:{type:"string",description:"Sharpening intensity: 'light' (default), 'medium', 'strong'."}},required:["video"]};function ek(t){return{name:zD,label:"Video Upscale",description:"Upscale a video to higher resolution with optional sharpening. Auto-detects orientation (landscape/portrait). Uses Lanczos interpolation + unsharp mask. Supports 1080p and 2K targets. Video URL MUST be publicly accessible HTTP/HTTPS. Use file_upload tool first if the user provides a local file. Best used as post-processing after video_merge.",parameters:VD,execute:async(e,r)=>{let n=await t.upscaleVideo({video:r.video,targetResolution:r.targetResolution,sharpness:r.sharpness});return{content:[{type:"text",text:`Upscaled to ${n.resolution}${r.sharpness?` (sharpness: ${r.sharpness})`:""}`}],details:{type:"video_upscale",localPath:n.localPath,servePath:n.servePath,resolution:n.resolution,durationSec:n.durationSec,mediaUrls:n.mediaUrls}}}}}var XD="three_d_generate",YD={type:"object",properties:{prompt:{type:"string",description:"3D model generation prompt. Describe the object's shape, material, texture, color, and pose. For text-to-3D, provide a detailed description. For image-to-3D, also provide image_url."},image_url:{type:"string",description:"Reference image URL for image-to-3D generation. The image should show the object clearly from a single viewpoint with clean background for best results. MUST be a publicly accessible HTTP/HTTPS URL. Local file paths and data: URLs are NOT supported."},output_format:{type:"string",description:"3D model output format: 'glb' (default), 'obj', 'usd', 'usdz'."},seed:{type:"number",description:"Random seed for reproducible generation."}},required:["prompt"]};function tk(t){return{name:XD,label:"3D Generate",description:"Generate a 3D model from a text prompt or reference image. Supports text-to-3D and image-to-3D workflows. Output formats include GLB, OBJ, USD. The generated model can be viewed in any 3D viewer or imported into game engines. IMPORTANT: Describe the object in detail \u2014 shape, size, material, texture, color, and pose.",parameters:YD,execute:async(e,r)=>{let n=await t.generate3D({prompt:r.prompt,imageUrl:r.image_url,outputFormat:r.output_format,seed:r.seed}),o=n.mediaUrls.length,s=`Generated ${o} 3D model${o>1?"s":""}${n.model?` (model: ${n.model})`:""}`;return o===0&&n.metadata?.debugResponseKeys&&(s+=` [debug: response keys=${JSON.stringify(n.metadata.debugResponseKeys)}, content=${n.metadata.debugContentSample??"null"}]`),{content:[{type:"text",text:s}],details:{type:"three_d_generate",model:n.model,durationMs:n.durationMs,mediaUrls:n.mediaUrls,...n.metadata??{}}}}}}var JD={type:"object",properties:{audio_url:{type:"string",description:"URL of the audio file to transcribe. Supports mp3, wav, m4a, ogg, flac formats. MUST be a publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},language:{type:"string",description:"Language hint for transcription: 'zh' (Chinese), 'en' (English), or auto-detect if omitted."}},required:["audio_url"]};function rk(t){return{name:"stt",label:"STT",description:"Transcribe audio to text (Speech-to-Text). Provide an audio file URL and receive the spoken content as text. Supports Chinese and English. Use for meeting transcription, voice message reading, subtitle generation, or any audio-to-text conversion.",parameters:JD,execute:async(e,r)=>{if(!r.audio_url)return{content:[{type:"text",text:"Error: audio_url parameter is required. Provide a publicly accessible HTTP/HTTPS URL to an audio file."}],details:{error:"audio_url parameter is required"}};let n=await t.speechToText({audioUrl:r.audio_url,language:r.language}),o=n.transcription.length>200?n.transcription.slice(0,200)+"\u2026":n.transcription;return{content:[{type:"text",text:n.transcription}],details:{type:"stt",model:n.model,durationMs:n.durationMs,transcriptionLength:n.transcription.length,preview:o}}}}}var QD="voice_clone",ZD={type:"object",properties:{text:{type:"string",description:"Text to synthesize in the cloned voice."},sample_audio_url:{type:"string",description:"URL of an audio sample (5-30 seconds recommended) of the voice to clone. The sample should be clear speech with minimal background noise. MUST be a publicly accessible HTTP/HTTPS URL. Use file_upload tool first if the user provides a local file."},speed:{type:"number",description:"Speech speed multiplier (0.5-2.0). Default is 1.0."}},required:["text","sample_audio_url"]};function nk(t){return{name:QD,label:"Voice Clone",description:"Clone a voice from an audio sample and synthesize new speech in that voice. Requires a clear audio sample (5-30s recommended) of the target voice. Use for personalized narration, character voices, or voice preservation. DO NOT use for impersonation or deception. For standard TTS with preset voices, use the tts tool instead.",parameters:ZD,execute:async(e,r)=>{let n=await t.cloneVoice({text:r.text,sampleAudioUrl:r.sample_audio_url,speed:r.speed});return{content:[{type:"text",text:`Voice cloned and synthesized speech${n.model?` (model: ${n.model})`:""}`}],details:{type:"voice_clone",model:n.model,voiceId:n.voiceId,durationMs:n.durationMs,mediaUrls:n.mediaUrls}}}}}var eN="media_cancel",tN={type:"object",properties:{task_id:{type:"string",description:"The task ID of the media generation to cancel (returned in previous generation results)."},provider:{type:"string",description:"Provider name (e.g. 'doubao', 'zhipu'). If omitted, auto-detects from task context."}},required:["task_id"]};function ok(t){return{name:eN,label:"Media Cancel",description:"Cancel an in-progress media generation task (video, 3D, etc.). Provide the task_id from a previous generation result. Use this when a user wants to abort a long-running generation.",parameters:tN,execute:async(e,r)=>{if(!r.task_id)return{content:[{type:"text",text:"Error: task_id is required."}],details:{error:"task_id is required"}};let n=await t.cancelTask({taskId:r.task_id,provider:r.provider});return{content:[{type:"text",text:n.ok?`Task ${r.task_id} cancelled.`:`Cancel failed: ${n.message}`}],details:n.ok?void 0:{error:n.message}}}}}var rN="file_upload",nN={type:"object",properties:{file_path:{type:"string",description:"Absolute path to the local file to upload. Supported: images (jpg/png/webp/gif), audio (mp3/wav/m4a/ogg/flac), video (mp4/mov/avi). The file will be uploaded to the configured provider's Files API and a file ID or public URL will be returned."},purpose:{type:"string",description:"Upload purpose hint: 'media_reference' (for image/video/audio generation), 'user_data' (general). Default: 'media_reference'."}},required:["file_path"]};function sk(t){return{name:rN,label:"File Upload",description:"Upload a local file to the cloud provider's Files API. Returns a file ID (or public URL) that can be used as input for media generation tools (image_generate, video_generate, video_edit, etc.). Use this when the user provides a local file that needs to be referenced by URL in media tools. IMPORTANT: Only call this tool for files that actually need to be uploaded for media generation. Not all providers support file upload \u2014 tool availability depends on the configured provider.",parameters:nN,execute:async(e,r)=>{let n=await t.uploadFile({filePath:r.file_path,purpose:r.purpose}),o=[`Uploaded "${n.filename}" (${Rd(n.bytes)}) via ${n.provider}`];return n.url&&o.push(`URL: ${n.url}`),o.push(`File ID: ${n.fileId}`),{content:[{type:"text",text:o.join(`
|
|
538
538
|
`)}],details:{type:"file_upload",fileId:n.fileId,url:n.url,filename:n.filename,bytes:n.bytes,provider:n.provider}}}}}var oN="file_query",sN={type:"object",properties:{file_id:{type:"string",description:"Query a specific file by ID. If omitted, lists recent uploaded files."},limit:{type:"number",description:"Max number of files to list when file_id is omitted. Default: 10, max: 100."}},required:[]};function ik(t){return{name:oN,label:"File Query",description:"Query or list uploaded files from the provider's Files API. Use file_id to get info on a specific file, or omit to list recent uploads. Returns file ID, name, size, status, and URL (if available).",parameters:sN,execute:async(e,r)=>{if(r.file_id){let i=await t.queryFile({fileId:r.file_id}),a=[`File: ${i.filename}`,`ID: ${i.id}`,`Size: ${Rd(i.bytes)}`,`Status: ${i.status}`];return i.url&&a.push(`URL: ${i.url}`),i.createdAt&&a.push(`Created: ${i.createdAt}`),{content:[{type:"text",text:a.join(`
|
|
539
539
|
`)}],details:{type:"file_query",fileId:i.id}}}let n=Math.min(Math.max(r.limit??10,1),100),o=await t.listFiles({limit:n});if(o.length===0)return{content:[{type:"text",text:"No uploaded files found."}],details:{type:"file_query",count:0}};let s=[`Found ${o.length} file(s):
|
|
540
540
|
`];for(let i of o)s.push(`- ${i.filename} | ID: ${i.id} | ${Rd(i.bytes)} | ${i.status}${i.url?` | ${i.url}`:""}`);return{content:[{type:"text",text:s.join(`
|
|
@@ -542,11 +542,11 @@ ${u}${p}`}],details:{type:"notebook_edit",edit_mode:o,cell_number:n,total_cells:
|
|
|
542
542
|
`)}],details:{type:"ask_user",answers:o,questionCount:r.questions.length}}}}}var dN="project_switch",uN={type:"object",properties:{projectName:{type:"string",description:"The name of the project to switch to. Use the exact project name from the available project list."}},required:["projectName"]};function lk(t){return{name:dN,label:"Switch Project",description:["Switch the active project context. ONLY call this when the user EXPLICITLY asks to switch projects","(e.g. '\u5207\u6362\u5230XX\u9879\u76EE', 'switch to project X').","Do NOT call this if the user merely mentions a project name in conversation.","The projectName must be an EXACT match from the available project list.","If unsure which project the user means, ask them to clarify first."].join(`
|
|
543
543
|
`),parameters:uN,isReadOnly:!1,isConcurrencySafe:!1,shouldDefer:!0,searchHint:"switch project change workspace \u5207\u6362\u9879\u76EE",execute:async(e,r)=>{let n=t.listProjects();if(n.length===0)return{content:[{type:"text",text:"Error: No projects available."}]};let o=r.projectName.toLowerCase().trim(),s=n.find(a=>a.name.toLowerCase()===o);if(!s){let a=n.map(c=>`"${c.name}"`).join(", ");return{content:[{type:"text",text:`Error: No project with exact name "${r.projectName}". Available projects: ${a}. Please confirm the exact project name with the user before retrying.`}]}}let i=t.switchProject(s.id);return i?(t.onSwitched?.(i),{content:[{type:"text",text:`Switched to project "${i.name}" (workspace: ${i.workspaceDir}).`}]}):{content:[{type:"text",text:`Error: Failed to switch to project "${s.name}".`}]}}}}import*as fn from"node:fs";import*as oi from"node:path";function pN(t={}){let e=t.createGeminiFileApi??Pu,r=t.isVolcengineFileTransport??xu,n=a=>{if(a.mediaClient)for(let[,c]of Object.entries(a.mediaProviders)){if(!c)continue;let l=a.mediaClient.getTransport(c.provider),d=sr(a.mediaApiKeys,c.provider);if(r(l)&&d)return{id:c.provider,type:"volcengine"}}if(a.mediaApiKeys.google)return{id:"google",type:"gemini"}},o=a=>{let c=n(a);if(!c)throw new Error("No file API provider available. Configure a media provider with Files API support (e.g. Volcengine, Google).");return c},s=(a,c)=>{let l=a.mediaClient?.getTransport(c);if(!r(l))throw new Error(`File API only supported via Volcengine or Google provider. Current: ${c}`);return l},i=(a,c)=>{let l=sr(a.mediaApiKeys,c);if(!l)throw new Error(`No API key for file API provider: ${c}`);return l};return{resolveProvider:n,uploadFile:async(a,c)=>{let l=o(a);if(l.type==="gemini"){let g=e(),f=a.mediaApiKeys.google,h=await g.uploadFile(c.buffer,f,{mimeType:c.mimeType,displayName:c.filename}),v=h.state==="PROCESSING"?await g.waitForProcessing(h.name,f):h;return{fileId:v.name,url:v.uri,filename:c.filename,bytes:c.bytes,provider:"google"}}let d=s(a,l.id),u=i(a,l.id),p=await d.uploadFile(new Blob([c.buffer]),u,{purpose:c.purpose??"media_reference",filename:c.filename}),m;try{let g=await d.getFile(p.id,u);typeof g.url=="string"&&g.url&&(m=g.url)}catch{}return{fileId:p.id,url:m,filename:c.filename,bytes:c.bytes,provider:l.id}},queryFile:async(a,c)=>{let l=o(a);if(l.type==="gemini"){let p=await e().getFile(c,a.mediaApiKeys.google);return dk(p)}let u=await s(a,l.id).getFile(c,i(a,l.id));return uk(u,c)},listFiles:async(a,c)=>{let l=o(a);return l.type==="gemini"?(await e().listFiles(a.mediaApiKeys.google,{pageSize:c})).files.map(dk):((await s(a,l.id).listFiles(i(a,l.id),{limit:c})).data??[]).map(p=>uk(p))},deleteFile:async(a,c)=>{let l=o(a);if(l.type==="gemini"){await e().deleteFile(c,a.mediaApiKeys.google);return}await s(a,l.id).deleteFile(c,i(a,l.id))}}}var Sd=pN();function dk(t){return{id:t.name,filename:t.displayName??"",bytes:Number(t.sizeBytes??0),status:t.state?.toLowerCase()??"unknown",createdAt:t.createTime,url:t.uri}}function uk(t,e=""){return{id:String(t.id??e),filename:String(t.filename??""),bytes:Number(t.bytes??0),status:String(t.status??"unknown"),createdAt:t.created_at?String(t.created_at):void 0,url:t.url?String(t.url):void 0}}function pk(t){let e=t.maxUploadBytes??104857600,r=t.mediaFileApiService??Sd;return{isAvailable:()=>mk(t.getContext(),r),uploadFile:async n=>{ni(t.getContext(),r,"upload");let o=t.resolvePath(n.filePath);if(!fn.existsSync(o))throw new Error(`File not found: ${o}`);let s=fn.statSync(o);if(s.size>e)throw new Error(`File too large (${(s.size/1024/1024).toFixed(1)} MB). Max: ${(e/1024/1024).toFixed(0)} MB.`);let i=await fn.promises.readFile(o),a=oi.basename(o),c=oi.extname(o).toLowerCase();return r.uploadFile(t.getContext(),{buffer:Buffer.from(i),filename:a,bytes:s.size,mimeType:mN[c]??"application/octet-stream",purpose:n.purpose??"media_reference"})},queryFile:async n=>(ni(t.getContext(),r,"query"),r.queryFile(t.getContext(),n.fileId)),listFiles:async n=>(ni(t.getContext(),r,"list"),r.listFiles(t.getContext(),n.limit??10)),deleteFile:async n=>{ni(t.getContext(),r,"delete"),await r.deleteFile(t.getContext(),n.fileId)}}}function mk(t,e=Sd){return!!e.resolveProvider(t)}function ni(t,e,r){if(!mk(t,e))throw new Error(`No file ${r} provider available. Configure a media provider with Files API support (e.g. Volcengine, Google).`)}var mN={".pdf":"application/pdf",".txt":"text/plain",".html":"text/html",".htm":"text/html",".css":"text/css",".js":"text/javascript",".ts":"text/plain",".json":"application/json",".xml":"application/xml",".csv":"text/csv",".md":"text/markdown",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".svg":"image/svg+xml",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".flac":"audio/flac",".m4a":"audio/mp4",".aac":"audio/aac",".mp4":"video/mp4",".webm":"video/webm",".avi":"video/x-msvideo",".mov":"video/quicktime",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function gk(t,e){return!t?.webSearch||!t.capabilities.includes("web_search")?e:async(r,n)=>{try{let s=await t.webSearch(r,{maxResults:n?.maxResults});if(n?.allowedDomains?.length){let i=new Set(n.allowedDomains.map(a=>a.toLowerCase()));s=s.filter(a=>{try{return i.has(new URL(a.url).hostname.toLowerCase())}catch{return!1}})}if(n?.blockedDomains?.length){let i=new Set(n.blockedDomains.map(a=>a.toLowerCase()));s=s.filter(a=>{try{return!i.has(new URL(a.url).hostname.toLowerCase())}catch{return!0}})}if(s.length>0)return{query:r,results:s.map(i=>({title:i.title,url:i.url,snippet:i.snippet}))}}catch{}return e(r,n)}}var gN=[{pattern:"Bash",behavior:"ask",reason:"Group security: shell commands require approval in group chat",source:"group-policy"},{pattern:"computer",behavior:"deny",reason:"Group security: computer control blocked in group chat",source:"group-policy"}],fN=[/\.env($|\.)/i,/\.(key|pem|p12|pfx|jks)$/i,/id_rsa/i,/id_ed25519/i,/\.ssh\//i,/secret/i,/credential/i,/token/i,/password/i,/\.aws\//i,/\.gnupg\//i];function fk(){return[...gN]}function wd(t){return fN.some(e=>e.test(t))}D();var Id=!1;function Ed(t){Id=t}var De,Or={},vk,Ad,fr={},kk;function _d(t){kk=t}var Rk=null,bN;var xd;function Sk(t){xd=t}function wk(t){Rk=t}function Tk(t,e,r,n,o){De=t,Or=e??{},vk=r,Ad=o,fr=n??{},vN()}function Md(t){let e=fr[t];if(!(!e||!De))return De.resolveModelById(e.provider,e.model,t)}function vN(){kN(),RN(),SN(),wN()}function kN(){let t=ve(vd);if(!t)return;let e=fr.video;if(!e||!De)return;let r=De.resolveModelById(e.provider,e.model,"video");if(!r)return;let n=r.modelInfo.mediaCapabilities;if(!n)return;let o=n.maxDurationSeconds??10,s=o>=10?4:3,i=n.resolutions?.join("/")||"720P",a=r.modelInfo.name||r.modelInfo.id;t.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. Current model: ${a}. Single-shot: ${s}\u2013${o}s. For longer videos (>${o}s), 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: ${s}-${o}s). Auto-set aspect_ratio based on stated purpose (e.g. 9:16 for short-video / Douyin, 16:9 for presentation).`;let c=t.parameters?.properties,l=c?.duration;l&&(l.minimum=s,l.maximum=o,l.description=`Video duration in seconds (${s}\u2013${o}s for ${a}). For longer videos (>${o}s), use multi-shot storyboard workflow (generate + extend/merge). Must be confirmed by user before generation.`);let d=c?.resolution;d&&n.resolutions&&(d.description=`Output resolution: ${i}. Default: '720p'.`)}function RN(){let t=ve(bd);if(!t)return;let e=Md("image");if(!e)return;let r=e.modelInfo.mediaCapabilities,n=e.modelInfo.name||e.modelInfo.id,o=[];if(r?.sizes?.length&&o.push(`Sizes: ${r.sizes.join(", ")}`),r?.transparentBackground&&o.push("Supports transparent background"),t.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. Current model: ${n}. ${o.join(". ")}${o.length?". ":""}IMPORTANT: If the user has not specified purpose or preferred style, use ask_user to clarify (e.g. purpose: social-media / wallpaper / poster; style: photorealistic / anime / watercolor). Infer image size automatically from purpose. ALL reference image URLs MUST be publicly accessible HTTP/HTTPS URLs. Use file_upload tool first if the user provides a local file.`,r?.sizes?.length){let i=t.parameters?.properties?.size;i&&(i.description=`Dimensions: ${r.sizes.join(", ")}. Default: '1024x1024'. Auto-infer from purpose.`)}}function SN(){let t=ve("tts");if(!t)return;let e=Md("tts");if(!e)return;let r=e.modelInfo.mediaCapabilities,n=e.modelInfo.name||e.modelInfo.id,o=[];if(r?.voices?.length&&o.push(`Voices: ${r.voices.join(", ")}`),r?.maxCharacters&&o.push(`Max: ${r.maxCharacters} characters per request`),r?.formats?.length&&o.push(`Formats: ${r.formats.join(", ")}`),t.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. Current model: ${n}. ${o.join(". ")}${o.length?".":""}`,r?.voices?.length){let i=t.parameters?.properties?.voice;i&&(i.description=`Voice name. Available: ${r.voices.join(", ")}.`)}}function wN(){let t=ve(kd);if(!t)return;let e=Md("music");if(!e)return;let r=e.modelInfo.mediaCapabilities,n=e.modelInfo.name||e.modelInfo.id,o=[];if(r?.maxDurationSeconds&&o.push(`Max duration: ${r.maxDurationSeconds}s`),r?.formats?.length&&o.push(`Formats: ${r.formats.join(", ")}`),t.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. Current model: ${n}. ${o.join(". ")}${o.length?". ":""}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).`,r?.maxDurationSeconds){let i=t.parameters?.properties?.duration;i&&(i.maximum=r.maxDurationSeconds,i.description=`Duration in seconds (5\u2013${r.maxDurationSeconds}s for ${n}). Infer from purpose: ringtone 15-30s, BGM 30-60s, full song 120-180s.`)}}async function Ft(t){if(!De)throw new Error(`No media provider configured for ${t.mediaType}`);let e=fr[t.mediaType],r=e?.provider,n=e?.model||t.model;if(!r)throw new Error(`No provider configured for ${t.mediaType}. Please configure a provider in settings.`);let o={...t};Ad&&!o.onProgress&&(o.onProgress=(c,l,d)=>{Ad(d??"pending",t.mediaType,c,l,r)});let s=await hk(r,n||t.model,o);if(s.ok)return s.result;let i=De.listMediaModels(t.mediaType),a=[`${r}: ${s.error}`];for(let c of i){if(c.providerId===r||!Or[c.providerId])continue;let d=await hk(c.providerId,c.modelInfo.id,t);if(d.ok)return d.result;a.push(`${c.providerId}/${c.modelInfo.id}: ${d.error}`)}throw new Error(`All media providers failed for ${t.mediaType}:
|
|
544
544
|
`+a.map(c=>` - ${c}`).join(`
|
|
545
|
-
`))}async function hk(t,e,r){let n=De.getTransport(t);if(!n)return{ok:!1,error:"transport not available"};let o=sr(Or,t);if(!o)return{ok:!1,error:"no API key"};try{let s={...r,model:e},i=await n.generate(s,o);i.billingUnit||(r.mediaType==="tts"&&r.text?(i.billingUnit="per_character",i.billingQuantity=r.text.length):(r.mediaType==="video"||r.mediaType==="music")&&r.duration?(i.billingUnit="per_second",i.billingQuantity=r.duration):(i.billingUnit="per_call",i.billingQuantity=1));let a=i.model??s.model,c=i.billingUnit??"per_call",l=i.billingQuantity??1;return vk?.(a,c,l),{ok:!0,result:i}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Ht(t){if(!De)return!1;let e=fr[t];if(!e)return!1;let r=De.getTransport(e.provider),n=sr(Or,e.provider);return!!(r&&n)}function Td(t,e){if(!Ht(t))return!1;let r=fr[t],n=De.resolveModelById(r.provider,r.model,t);if(!n)return!1;let o=n.modelInfo.mediaCapabilities;return!o||!("operations"in o)||!o.operations?!0:o.operations.includes(e)}var Xe=process.cwd(),Pd=!1;function Ak(t){Xe=t,Pd=!0,Zs(t)}function Ne(t){return U.isAbsolute(t)?U.normalize(t):U.resolve(Xe,t)}function co(t){let e=U.resolve(Xe)+U.sep,r=U.resolve(t);return process.platform==="win32"?r.toLowerCase().startsWith(e.toLowerCase())||r.toLowerCase()===e.slice(0,-1).toLowerCase():r.startsWith(e)||r===e.slice(0,-1)}function
|
|
545
|
+
`))}async function hk(t,e,r){let n=De.getTransport(t);if(!n)return{ok:!1,error:"transport not available"};let o=sr(Or,t);if(!o)return{ok:!1,error:"no API key"};try{let s={...r,model:e},i=await n.generate(s,o);i.billingUnit||(r.mediaType==="tts"&&r.text?(i.billingUnit="per_character",i.billingQuantity=r.text.length):(r.mediaType==="video"||r.mediaType==="music")&&r.duration?(i.billingUnit="per_second",i.billingQuantity=r.duration):(i.billingUnit="per_call",i.billingQuantity=1));let a=i.model??s.model,c=i.billingUnit??"per_call",l=i.billingQuantity??1;return vk?.(a,c,l),{ok:!0,result:i}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Ht(t){if(!De)return!1;let e=fr[t];if(!e)return!1;let r=De.getTransport(e.provider),n=sr(Or,e.provider);return!!(r&&n)}function Td(t,e){if(!Ht(t))return!1;let r=fr[t],n=De.resolveModelById(r.provider,r.model,t);if(!n)return!1;let o=n.modelInfo.mediaCapabilities;return!o||!("operations"in o)||!o.operations?!0:o.operations.includes(e)}var Xe=process.cwd(),Pd=!1;function Ak(t){Xe=t,Pd=!0,Zs(t)}function Ne(t){return U.isAbsolute(t)?U.normalize(t):U.resolve(Xe,t)}function co(t){let e=U.resolve(Xe)+U.sep,r=U.resolve(t);return process.platform==="win32"?r.toLowerCase().startsWith(e.toLowerCase())||r.toLowerCase()===e.slice(0,-1).toLowerCase():r.startsWith(e)||r===e.slice(0,-1)}function nr(t){return co(t)?null:`Blocked: path "${t}" is outside the workspace boundary "${Xe}"`}function yk(t){let e=t.replace(/\\/g,"/");return e.includes("../")||e.includes("..")}var TN=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".svg",".ico"]),xk=new Set([".exe",".dll",".so",".dylib",".zip",".tar",".gz",".7z",".rar",".wasm",".class"]),Cd=new Set;function AN(){return{resolvePath:Ne,async readFile(t){let e=Ne(t),r=U.extname(e).toLowerCase();if(Pd){let o=nr(e);if(o)throw new Error(o)}else if(yk(t)&&!co(e))throw new Error(`Blocked: path traversal "${t}" escapes workspace "${Xe}"`);if(e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/"))throw new Error(`Blocked: reading device/system path ${e}`);if(xk.has(r))return{type:"binary",mimeType:"application/octet-stream"};if(TN.has(r))return{type:"image",localPath:e,mimeType:r===".png"?"image/png":r===".svg"?"image/svg+xml":r===".gif"?"image/gif":r===".webp"?"image/webp":"image/jpeg"};let n=await j.promises.readFile(e,"utf8");return Cd.add(e),{type:"text",text:n}},validatePath(t){let e=Ne(t);if(Pd){let r=nr(e);if(r)return r}else if(yk(t)&&!co(e))return`Blocked: path traversal "${t}" escapes workspace "${Xe}"`;return e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: reading device/system path ${e}`:Id&&wd(e)?"Blocked: reading sensitive file in group chat mode":null}}}function xN(){return{resolvePath:Ne,validatePath(t){let e=Ne(t),r=nr(e);return r||(e.startsWith("/dev/")||e.startsWith("/proc/")||e.startsWith("/sys/")?`Blocked: writing to device/system path ${e}`:Id&&wd(e)?"Blocked: writing sensitive file in group chat mode":null)},checkReadBeforeWrite(t){try{j.accessSync(t,j.constants.F_OK)}catch{return null}return Cd.has(t)?null:"File already exists but has not been read yet in this session. Read it first with the read tool before overwriting, to avoid unintended data loss. If you intend to completely replace the file, read it first to confirm."},async writeFile(t,e){let r=Ne(t),n=nr(r);if(n)throw new Error(n);await j.promises.mkdir(U.dirname(r),{recursive:!0}),await j.promises.writeFile(r,e,"utf8"),Cd.add(r)}}}function PN(){return{resolvePath:Ne,async readFile(t){let e=Ne(t),r=nr(e);if(r)throw new Error(r);return j.promises.readFile(e,"utf8")},async writeFile(t,e){let r=Ne(t),n=nr(r);if(n)throw new Error(n);await j.promises.mkdir(U.dirname(r),{recursive:!0}),await j.promises.writeFile(r,e,"utf8")}}}function CN(){return{resolvePath:Ne,async readFile(t){let e=Ne(t),r=nr(e);if(r)throw new Error(r);return j.promises.readFile(e,"utf8")},async writeFile(t,e){let r=Ne(t),n=nr(r);if(n)throw new Error(n);await j.promises.mkdir(U.dirname(r),{recursive:!0}),await j.promises.writeFile(r,e,"utf8")},async deleteFile(t){let e=Ne(t),r=nr(e);if(r)throw new Error(r);await j.promises.unlink(e)},async fileExists(t){let e=Ne(t);try{return await j.promises.access(e),!0}catch{return!1}}}}function IN(){return{resolvePath:Ne,async glob(t,e){let r=e.cwd||Xe,n=e.limit||1e3,o=[],s=!1,i=t.replace(/\\/g,"/").split("/"),a=i.some(d=>d==="**"),c=i[i.length-1]??"*",l=Pk(c);try{await Dd(r,async d=>{if(o.length>=n)return s=!0,!1;let u=U.basename(d);return l.test(u)&&o.push(d),!0},a?1/0:1)}catch{}return{files:o,truncated:s}},async grep(t,e){let r=e.cwd||Xe;try{return await _N(t,r,e)}catch{return await MN(t,r,e)}}}}function Pk(t){let e=t.replace(/[.+^$|()[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return e=e.replace(/\\\{([^}]+)\\\}/g,(r,n)=>"("+n.replace(/,/g,"|")+")"),new RegExp(`^${e}$`,"i")}var EN=new Set([".git",".svn",".hg","node_modules","__pycache__",".next","dist",".tox",".venv"]);async function Dd(t,e,r,n=0,o=""){if(n>r)return;let s;try{s=await j.promises.readdir(t,{withFileTypes:!0})}catch{return}for(let i of s){let a=o?`${o}/${i.name}`:i.name;if(i.isDirectory()){if(EN.has(i.name))continue;await Dd(U.join(t,i.name),e,r,n+1,a)}else if(i.isFile()&&!await e(a))return}}function _N(t,e,r){return new Promise((n,o)=>{let s=["--json","--no-heading","--max-columns","500"];r.caseInsensitive&&s.push("-i"),r.contextLines&&s.push("-C",String(r.contextLines)),r.fileGlob&&s.push("-g",r.fileGlob),s.push("--max-count",String(r.headLimit??250)),s.push(t),s.push("."),yN("rg",s,{cwd:e,maxBuffer:10*1024*1024,timeout:3e4},(i,a)=>{if(i&&!("killed"in i&&i.killed)&&i.code!==1){o(i);return}let c=[];for(let p of a.split(`
|
|
546
546
|
`))if(p.trim())try{let m=JSON.parse(p);m.type==="match"&&m.data&&c.push({path:m.data.path?.text??"",line:m.data.line_number??0,text:(m.data.lines?.text??"").trimEnd()})}catch{}let l=r.headLimit??250,d=r.offset??0,u=c.slice(d,d+l);n({matches:u,truncated:c.length>d+l})})})}async function MN(t,e,r){let n=new RegExp(t,r.caseInsensitive?"i":""),o=r.headLimit??250,s=r.offset??0,i=r.fileGlob?Pk(r.fileGlob):null,a=[],c=!1;return await Dd(e,async l=>{if(a.length>=s+o+1)return c=!0,!1;if(i&&!i.test(U.basename(l)))return!0;let d=U.extname(l).toLowerCase();if(xk.has(d))return!0;try{let p=(await j.promises.readFile(U.join(e,l),"utf8")).split(`
|
|
547
|
-
`);for(let m=0;m<p.length;m++)if(n.test(p[m])&&(a.push({path:l,line:m+1,text:p[m].slice(0,500)}),a.length>=s+o+1))return c=!0,!1}catch{}return!0},1/0),{matches:a.slice(s,s+o),truncated:c}}var bk=!1;function DN(){if(!bk)if(bk=!0,Nr()){let t=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";oo(dd(t))}else if(process.platform==="win32"){let t=NN();oo(ri(t))}else{let t=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";oo(ri(t))}}function NN(){let t=process.env.QLOGICAGENT_BASH_PATH;if(t&&j.existsSync(t))return t;let e=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"],r=process.env.ProgramFiles?U.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;r&&!e.includes(r)&&e.unshift(r);for(let n of e)if(j.existsSync(n))return n;return"bash"}function LN(){return{async fetchUrl(t){let e=new AbortController,r=setTimeout(()=>e.abort(),3e4);try{let n=await fetch(t.url,{signal:e.signal,headers:{"User-Agent":"Mozilla/5.0 (compatible; QLogicAgent/1.0)",Accept:"text/html,application/xhtml+xml,text/plain,*/*"},redirect:"follow"});if(!n.ok)return{content:`HTTP ${n.status} ${n.statusText}`};let o=n.headers.get("content-type")??"",s=await n.text();return t.maxChars&&s.length>t.maxChars&&(s=s.slice(0,t.maxChars)),o.includes("html")&&t.extractMode!=="json"&&(s=ON(s)),{content:s,title:jN(s)}}finally{clearTimeout(r)}}}}function ON(t){return t.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s{2,}/g," ").trim()}function jN(t){return t.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function $N(){let t=async(e,r)=>{let{getModelRegistry:n}=await Promise.resolve().then(()=>(We(),mp)),o=n().getTunable("searxngBaseUrl")??process.env.SEARXNG_BASE_URL?.trim();if(!o)return{query:e,results:[],totalResults:0};let s=r?.maxResults??10,i=new URL("/search",o);i.searchParams.set("q",e),i.searchParams.set("format","json"),i.searchParams.set("pageno","1");let a=new AbortController,c=setTimeout(()=>a.abort(),15e3);try{let l=await fetch(i.toString(),{signal:a.signal,headers:{Accept:"application/json"}});if(!l.ok)return{query:e,results:[]};let d=await l.json(),u=(d.results??[]).slice(0,s).map(p=>({title:p.title??"",url:p.url??"",snippet:p.content??""}));if(r?.allowedDomains?.length){let p=new Set(r.allowedDomains.map(m=>m.toLowerCase()));return{query:e,results:u.filter(m=>{try{return p.has(new URL(m.url).hostname.toLowerCase())}catch{return!1}})}}if(r?.blockedDomains?.length){let p=new Set(r.blockedDomains.map(m=>m.toLowerCase()));return{query:e,results:u.filter(m=>{try{return!p.has(new URL(m.url).hostname.toLowerCase())}catch{return!0}})}}return{query:e,results:u,totalResults:d.number_of_results}}finally{clearTimeout(c)}};return{search:(e,r)=>gk(kk,t)(e,r)}}function UN(){function t(o){if(o==="default")return oe()?.workspaceDir??Xe;let s=Ee(o);if(!s)throw new Error(`Unknown project: ${o}`);return s.workspaceDir}function e(o){return ir(t(o))}function r(o,s){if(!s.endsWith(".md"))throw new Error("Filename must end with .md");if(s.includes(".."))throw new Error("Path traversal not allowed");let i=e(o),a=U.resolve(i,s);if(!a.startsWith(i+U.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function n(o,s){if(!j.existsSync(o))return[];let i=[];for(let a of j.readdirSync(o,{withFileTypes:!0})){let c=U.join(o,a.name);if(a.isDirectory())i.push(...n(c,s));else if(a.isFile()&&a.name.endsWith(".md")){let l=j.statSync(c);i.push({filename:U.relative(s,c).replace(/\\/g,"/"),path:c,size:l.size,updatedAt:l.mtime.toISOString(),content:j.readFileSync(c,"utf-8")})}}return i}return{list(o){let s=e(o);return n(s,s).map(i=>({filename:i.filename,path:i.path,size:i.size,updatedAt:i.updatedAt}))},read(o,s){try{let i=r(o,s);if(!j.existsSync(i))return null;let a=j.statSync(i),c=j.readFileSync(i,"utf-8");return{filename:s,path:i,size:a.size,updatedAt:a.mtime.toISOString(),content:c}}catch{return null}},write(o,s,i){let a=r(o,s);j.mkdirSync(U.dirname(a),{recursive:!0}),j.writeFileSync(a,i,"utf-8");let c=j.statSync(a);return{filename:s,path:a,size:c.size,updatedAt:c.mtime.toISOString(),content:i}},remove(o,s){try{let i=r(o,s);return j.existsSync(i)?(j.unlinkSync(i),!0):!1}catch{return!1}}}}var FN={think:"orchestration",task:"orchestration",ask_user:"orchestration",exec:"developer",read:"filesystem",write:"filesystem",edit:"filesystem",patch:"filesystem",apply_patch:"filesystem",search:"search",web_fetch:"web",web_search:"web",instructions:"filesystem",worktree:"developer",notebook_edit:"developer",workflow:"automation",sleep:"automation",project_switch:"system",tool_search:"search",image_generate:"media",tts:"media",video_generate:"media",music_generate:"media",video_edit:"media",video_merge:"media",video_upscale:"media",three_d_generate:"media",stt:"media",voice_clone:"media",media_cancel:"media",file_upload:"filesystem",file_query:"filesystem",file_delete:"filesystem"};function HN(t){for(let e of t)e.category??=FN[e.name]??"other",e.displayName??={key:`capability.tool.${e.name}.name`,fallback:e.label},e.displayDescription??={key:`capability.tool.${e.name}.description`,fallback:""}}var BN=()=>{throw new Error("workflow tool: this controller is authoring-only; `run` requires the initialized engine")};function qN(t){function e(){let r=new ur(t),n=qs();return{controller:n??new dr(r,BN),live:n,store:r}}return{async list(){return e().store.list()},async get(r){return e().store.require(r)},async describe(r){return e().controller.describe(r)},async create(r){return e().controller.create({id:r.id,name:r.name,def:r.def,active:r.active})},async patch(r,n){return e().controller.patch(r,{patch:n.patch,baseRev:n.baseRev,scope:n.scope})},async setActive(r,n){return e().controller.setActive(r,n)},async run(r){let{live:n}=e();if(!n)throw new Error("workflow engine is not initialized in this context. Activate the workflow (setActive) so a trigger runs it, or run it from the app.");let o={type:"manual"};return n.run(r,o)},async delete(r){await e().store.delete(r)}}}function Ck(t){t?.workdir&&(Xe=t.workdir),DN(),Zs(Xe);let e=[];e.push(Wb()),e.push(pf(void 0,{onTaskCreated:d=>xd?.onTaskCreated?.(d),onTaskCompleted:d=>xd?.onTaskCompleted?.(d)})),e.push(ck({askUser:async d=>Rk?.(d)??null})),e.push(nv({onProgress:t?.onExecProgress,validateCommand:async d=>{let u=/(?:>>?|[12]>)\s*(?:"([^"]+)"|'([^']+)'|(\S+))/g,p;for(;(p=u.exec(d))!==null;){let g=p[1]||p[2]||p[3];if(g){let f=U.isAbsolute(g)?U.normalize(g):U.resolve(Xe,g);if(!co(f))return`Blocked: output redirection to path outside workspace: ${g}`}}let m=[/(?:^|[\s;|&(])(?:"(\/[^"]+)"|'(\/[^']+)'|(\/(?!dev\/null\b)[^\s;|&><)]+))/g,/(?:^|[\s;|&(])(?:"([A-Za-z]:[\\\/][^"]+)"|'([A-Za-z]:[\\\/][^']+)'|([A-Za-z]:[\\\/][^\s;|&><)]+))/g,/(?:^|[\s;|&(])(?:"([^"]*\.\.[\\/][^"]+)"|'([^']*\.\.[\\/][^']+)'|([^\s;|&><)"']*\.\.[\\/][^\s;|&><)]+))/g];for(let g of m){let f;for(;(f=g.exec(d))!==null;){let h=f[1]||f[2]||f[3];if(!h||/^\/[a-zA-Z](?:[- ]|$)/.test(h)||/^\/[a-zA-Z]{1,3}$/.test(h))continue;let v;if(process.platform==="win32"&&/^\/[a-zA-Z]\//.test(h)){let b=h.replace(/^\/([a-zA-Z])\//,(S,T)=>`${T.toUpperCase()}:\\`).replace(/\//g,"\\");v=U.normalize(b)}else v=U.isAbsolute(h)?U.normalize(h):U.resolve(Xe,h);if(!co(v))return`Blocked: command references path outside workspace: ${h}`}}return null},interpretExitCode:(d,u)=>{if(d===127)return"command not found";if(d===126)return"permission denied";if(d===137)return"killed (SIGKILL / OOM)";if(d===143)return"terminated (SIGTERM)";if(d===130)return"interrupted (Ctrl+C)"}}));let r=AN(),n=xN(),o=PN(),s=CN();e.push(iv(r)),e.push(cv(n)),e.push(lv(o)),e.push(fd(s)),e.push(mv(s)),e.push(pv(IN())),e.push(Sv(LN())),e.push(wv($N()));let i=UN();e.push(Tv(i));let a=t?.log??{info:()=>{},warn:()=>{}};e.push(Av(Uv({log:a}))),e.push(qv()),e.push(Wv({getService:()=>qN(Xe)})),e.push(Gv({sleep:(d,u)=>new Promise(p=>{let m=Date.now(),g=setTimeout(()=>{p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!1})},d),f=()=>{clearTimeout(g),p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!0,interruptReason:"aborted"})};u.addEventListener("abort",f,{once:!0}),u.aborted&&(clearTimeout(g),f())})}));let c={listProjects:()=>V(),switchProject:d=>wt(d),onSwitched:d=>bN?.(d)};e.push(lk(c)),e.push(zv({searchTools:async(d,u)=>{let p=u?.maxResults??5,m=Yt(),g=d.toLowerCase().split(/\s+/).filter(Boolean),f=[],h=[];for(let R of g)R.startsWith("+")&&R.length>1?f.push(R.slice(1)):h.push(R);let v=[...f,...h],b=R=>R.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase().split(/\s+/).filter(Boolean);return{matches:m.map(R=>{let P=ve(R),I=b(R),E=(P?.description??"").toLowerCase(),N=(P?.searchHint??"").toLowerCase();if(f.length>0){let k=`${I.join(" ")} ${E} ${N}`;if(!f.every(Le=>k.includes(Le)))return null}let xe=0;for(let k of v){let Q=0;I.some(Le=>Le===k)?Q=10:I.some(Le=>Le.includes(k))?Q=5:R.toLowerCase().includes(k)&&(Q=3),N&&new RegExp(`\\b${k}`,"i").test(N)&&(Q+=4),new RegExp(`\\b${k}`,"i").test(E)&&(Q+=2),xe+=Q}return{name:R,description:P?.description??"",searchHint:P?.searchHint,score:xe}}).filter(R=>R!==null&&R.score>0).sort((R,P)=>P.score-R.score).slice(0,p),query:d,totalDeferred:m.length}},activateTool:async d=>tm(d)})),e.push({...Vv({generateImage:async d=>{let u=await Ft({mediaType:"image",model:"",prompt:d.prompt,purpose:d.purpose,style:d.style,size:d.size,imageUrl:d.imageUrl,n:d.n,quality:d.quality,seed:d.seed});return{mediaUrls:u.mediaUrls,model:u.model,size:u.size,durationMs:u.durationMs}}}),isConcurrencySafe:!0,isEnabled:()=>Ht("image")}),e.push({...Xv({textToSpeech:async d=>{let u=await Ft({mediaType:"tts",model:"",prompt:"",text:d.text,channel:d.channel,voice:d.voice,speed:d.speed});return{audioPath:"",provider:u.model,mediaUrls:u.mediaUrls}}}),isConcurrencySafe:!0,isEnabled:()=>Ht("tts")}),e.push({...Yv({generateVideo:async d=>{let u=await Ft({mediaType:"video",model:"",prompt:d.prompt,purpose:d.purpose,style:d.style,imageUrl:d.imageUrl,referenceVideos:d.referenceVideos,referenceAudios:d.referenceAudios,generateAudio:d.generateAudio,aspectRatio:d.aspectRatio,duration:d.duration,resolution:d.resolution,fps:d.fps,seed:d.seed,cameraFixed:d.cameraFixed,returnLastFrame:d.returnLastFrame,draft:d.draft,serviceTier:d.serviceTier,callbackUrl:d.callbackUrl,safetyIdentifier:d.safetyIdentifier,executionExpiresAfterSeconds:d.executionExpiresAfterSeconds,videoTools:d.videoTools});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs,lastFrameUrl:u.lastFrameUrl,taskId:u.taskId}}}),isConcurrencySafe:!0,isEnabled:()=>Ht("video")}),e.push({...Jv({generateMusic:async d=>{let u=await Ft({mediaType:"music",model:"",prompt:d.prompt,purpose:d.purpose,style:d.style,lyrics:d.lyrics,duration:d.duration,isInstrumental:d.isInstrumental,audioUrl:d.audioUrl,audioFormat:d.audioFormat});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs}},generateLyrics:async d=>{let u=fr.music;if(!u||!De)return"";let p=De.getTransport(u.provider);if(!Au(p))return"";let m=sr(Or,u.provider);return m?p.generateLyrics(d,m):""}}),isConcurrencySafe:!0,isEnabled:()=>Ht("music")}),e.push({...Qv({editVideo:async d=>{let u=await Ft({mediaType:"video",model:"",prompt:d.prompt,operation:"edit",sourceVideos:d.sourceVideos,referenceImages:d.referenceImages,duration:d.duration,aspectRatio:d.aspectRatio,resolution:d.resolution});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs}}}),shouldDefer:!0,isEnabled:()=>Td("video","edit")}),e.push({...Zv({mergeVideos:async d=>{let u=[`merge ${d.clips.length} clips`];d.transition&&u.push(`transition: ${d.transition}${d.transitionDuration?` (${d.transitionDuration}s)`:""}`),d.subtitles&&u.push(`burn-in subtitles: ${d.subtitles}`),d.bgm&&u.push(`background music: ${d.bgm}${d.bgmVolume!==void 0?` at volume ${d.bgmVolume}`:""}`);let p=await Ft({mediaType:"video",model:"",prompt:u.join("; "),operation:"merge",sourceVideos:d.clips.map(m=>m.video),resolution:d.outputResolution,fps:d.outputFps});return{localPath:"",servePath:p.mediaUrls[0]??"",durationSec:(p.durationMs??0)/1e3,clipCount:d.clips.length,mediaUrls:p.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>Td("video","merge")}),e.push({...ek({upscaleVideo:async d=>{let u=["upscale"];d.sharpness&&u.push(`sharpness: ${d.sharpness}`);let p=await Ft({mediaType:"video",model:"",prompt:u.join(", "),operation:"upscale",sourceVideos:[d.video],resolution:d.targetResolution??"1080p"});return{localPath:"",servePath:p.mediaUrls[0]??"",resolution:d.targetResolution??"1080p",durationSec:(p.durationMs??0)/1e3,mediaUrls:p.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>Td("video","upscale")}),e.push({...tk({generate3D:async d=>{let u=await Ft({mediaType:"3d",model:"",prompt:d.prompt,imageUrl:d.imageUrl,outputFormat:d.outputFormat,seed:d.seed});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs,metadata:u.metadata}}}),isConcurrencySafe:!0,shouldDefer:!0,isEnabled:()=>Ht("3d")}),e.push({...rk({speechToText:async d=>{let u=await Ft({mediaType:"stt",model:"",prompt:"",audioUrl:d.audioUrl,metadata:d.language?{language:d.language}:void 0});return{transcription:u.metadata?.transcription??"",model:u.model,durationMs:u.durationMs}}}),shouldDefer:!0,isEnabled:()=>Ht("stt")}),e.push({...nk({cloneVoice:async d=>{let u=await Ft({mediaType:"voice_clone",model:"",prompt:"",text:d.text,audioUrl:d.sampleAudioUrl,speed:d.speed});return{mediaUrls:u.mediaUrls,model:u.model,voiceId:u.metadata?.voiceId,durationMs:u.durationMs}}}),shouldDefer:!0,isEnabled:()=>Ht("voice_clone")}),e.push({...ok({cancelTask:async d=>{let u=d.provider??"doubao";if(!De)return{ok:!1,message:"Media client not configured."};let p=De.getTransport(u);if(!p)return{ok:!1,message:`No transport for provider: ${u}`};let m=sr(Or,u);if(!m)return{ok:!1,message:`No API key for provider: ${u}`};try{return"deleteVideoTask"in p&&typeof p.deleteVideoTask=="function"?(await p.deleteVideoTask(d.taskId,m),{ok:!0,message:"Task cancelled."}):{ok:!1,message:`Provider ${u} does not support task cancellation.`}}catch(g){return{ok:!1,message:g instanceof Error?g.message:String(g)}}}}),shouldDefer:!0,isEnabled:()=>Ht("video")||Ht("3d")});let l=pk({getContext:()=>({mediaClient:De,mediaProviders:fr,mediaApiKeys:Or}),resolvePath:Ne});return e.push({...sk(l),shouldDefer:!0,isEnabled:()=>l.isAvailable()}),e.push({...ik(l),shouldDefer:!0,isEnabled:()=>l.isAvailable()}),e.push({...ak(l),shouldDefer:!0,isEnabled:()=>l.isAvailable()}),HN(e),em(e),t?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(d=>d.isEnabled?.()!==!1).length} enabled): ${Yt().join(", ")}`),e}var hn=class{mode;rules;defaultBehavior;compiledPatterns;constructor(e){this.mode=e.mode,this.rules=[...e.rules],this.defaultBehavior=e.defaultBehavior,this.compiledPatterns=this.compileRules(this.rules)}getMode(){return this.mode}setMode(e){this.mode=e}getRules(){return this.rules}getDefaultBehavior(){return this.defaultBehavior}replaceRules(e){this.rules=[...e],this.compiledPatterns=this.compileRules(this.rules)}setDefaultBehavior(e){this.defaultBehavior=e}addRule(e){this.rules.push(e),this.compiledPatterns=this.compileRules(this.rules)}applyUpdate(e){let r={pattern:e.pattern,behavior:e.behavior,reason:e.description,source:"user"};this.rules=[r,...this.rules.filter(n=>!VN(n.pattern,e.pattern))],this.compiledPatterns=this.compileRules(this.rules)}check(e){let{toolName:r,meta:n}=e;switch(this.mode){case"bypassPermissions":return{behavior:"allow",decisionReason:{type:"mode",mode:"bypassPermissions"}};case"dontAsk":return n?.isReadOnly?{behavior:"allow",decisionReason:{type:"mode",mode:"dontAsk"}}:{behavior:"deny",message:`Tool "${r}" denied \u2014 mode is dontAsk`,decisionReason:{type:"mode",mode:"dontAsk"}};case"plan":return{behavior:"deny",message:`Tool "${r}" paused \u2014 mode is plan (execution suspended)`,decisionReason:{type:"mode",mode:"plan"}}}for(let{rule:o,regex:s}of this.compiledPatterns)if(s.test(r))return GN(o,e);return n?.isReadOnly?{behavior:"allow",decisionReason:{type:"tool_check",reason:"isReadOnly"}}:n?.requiresApproval?{behavior:"ask",message:`Tool "${r}" requires approval`,toolName:r,input:e.arguments,decisionReason:{type:"tool_check",reason:"requiresApproval"}}:n?.isDangerous?{behavior:"ask",message:`Tool "${r}" is marked dangerous`,toolName:r,input:e.arguments,decisionReason:{type:"tool_check",reason:"isDangerous"}}:this.mode==="acceptEdits"?{behavior:"allow",decisionReason:{type:"mode",mode:"acceptEdits"}}:this.defaultBehavior==="allow"?{behavior:"allow"}:this.defaultBehavior==="deny"?{behavior:"deny",message:`Tool "${r}" denied by default policy`,decisionReason:{type:"other",reason:"default_deny"}}:{behavior:"ask",message:`Tool "${r}" requires approval (default policy)`,toolName:r,input:e.arguments}}compileRules(e){return e.map(r=>({rule:r,regex:WN(r.pattern)}))}};function jr(t){if(!t||typeof t!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=t,r=[];for(let a of["allow","deny","ask"]){let c=e[a];if(Array.isArray(c))for(let l of c)typeof l=="string"&&r.push({pattern:l,behavior:a,source:"config"})}if(Array.isArray(e.rules)){for(let a of e.rules)if(a&&typeof a=="object"){let c=a,l=c.pattern,d=c.behavior??c.action;typeof l=="string"&&typeof d=="string"&&(d==="allow"||d==="deny"||d==="ask")&&r.push({pattern:l,behavior:d,reason:typeof c.reason=="string"?c.reason:void 0,source:typeof c.source=="string"?c.source:"config"})}}let n=e.mode,o=typeof n=="string"&&KN(n)?n:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&zN(s)?s:"allow";return{mode:o,rules:r,defaultBehavior:i}}function WN(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${r}$`,"i")}function GN(t,e){let r={type:"rule",rule:t};return t.behavior==="allow"?{behavior:"allow",decisionReason:r}:t.behavior==="deny"?{behavior:"deny",message:t.reason??`Tool "${e.toolName}" denied by rule "${t.pattern}"`,decisionReason:r}:{behavior:"ask",message:t.reason??`Tool "${e.toolName}" requires approval (rule "${t.pattern}")`,toolName:e.toolName,input:e.arguments,decisionReason:r}}function KN(t){return t==="default"||t==="bypassPermissions"||t==="acceptEdits"||t==="dontAsk"||t==="plan"||t==="auto"}function zN(t){return t==="allow"||t==="deny"||t==="ask"}function VN(t,e){return t.toLocaleLowerCase()===e.toLocaleLowerCase()}function Ik(t,e){let r=jr(e);return t.setMode(r.mode),t.replaceRules(r.rules),t.setDefaultBehavior(r.defaultBehavior),r}import{randomUUID as XN}from"node:crypto";function Ek(t){wk(async e=>{let r=`ask-${XN().slice(0,8)}`;return new Promise(n=>{t.pendingAskUser.set(r,{resolve:n}),t.sendNotification("turn.ask_user",{requestId:r,questions:e.map(o=>({header:o.header,question:o.question,options:o.options}))})})})}function ii(t,e){return{name:t,compute:e,cacheBreak:!1}}function nr(t,e,r){return{name:t,compute:e,cacheBreak:!0}}var si=new Map;async function YN(t){return(await Promise.all(t.map(async r=>{if(!r.cacheBreak&&si.has(r.name))return si.get(r.name)??null;let n=await r.compute();return si.set(r.name,n),n}))).filter(r=>r!=null)}function _k(){si.clear()}async function ai(t){let e=[];if(t.instructionBlock&&e.push(t.instructionBlock),t.customSystemPrompt?e.push(t.customSystemPrompt):t.basePrompt&&e.push(t.basePrompt),t.sections?.length){let r=await YN(t.sections);e.push(...r)}return t.appendSystemPrompt&&e.push(t.appendSystemPrompt),e.filter(Boolean).join(`
|
|
547
|
+
`);for(let m=0;m<p.length;m++)if(n.test(p[m])&&(a.push({path:l,line:m+1,text:p[m].slice(0,500)}),a.length>=s+o+1))return c=!0,!1}catch{}return!0},1/0),{matches:a.slice(s,s+o),truncated:c}}var bk=!1;function DN(){if(!bk)if(bk=!0,Nr()){let t=process.env.QLOGICAGENT_POWERSHELL_PATH??"powershell.exe";oo(dd(t))}else if(process.platform==="win32"){let t=NN();oo(ri(t))}else{let t=process.env.SHELL?.endsWith("bash")?process.env.SHELL:"/bin/bash";oo(ri(t))}}function NN(){let t=process.env.QLOGICAGENT_BASH_PATH;if(t&&j.existsSync(t))return t;let e=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe"],r=process.env.ProgramFiles?U.join(process.env.ProgramFiles,"Git","bin","bash.exe"):null;r&&!e.includes(r)&&e.unshift(r);for(let n of e)if(j.existsSync(n))return n;return"bash"}function LN(){return{async fetchUrl(t){let e=new AbortController,r=setTimeout(()=>e.abort(),3e4);try{let n=await fetch(t.url,{signal:e.signal,headers:{"User-Agent":"Mozilla/5.0 (compatible; QLogicAgent/1.0)",Accept:"text/html,application/xhtml+xml,text/plain,*/*"},redirect:"follow"});if(!n.ok)return{content:`HTTP ${n.status} ${n.statusText}`};let o=n.headers.get("content-type")??"",s=await n.text();return t.maxChars&&s.length>t.maxChars&&(s=s.slice(0,t.maxChars)),o.includes("html")&&t.extractMode!=="json"&&(s=ON(s)),{content:s,title:jN(s)}}finally{clearTimeout(r)}}}}function ON(t){return t.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/ /gi," ").replace(/&/gi,"&").replace(/</gi,"<").replace(/>/gi,">").replace(/"/gi,'"').replace(/'/gi,"'").replace(/\s{2,}/g," ").trim()}function jN(t){return t.match(/<title[^>]*>([^<]+)<\/title>/i)?.[1]?.trim()}function $N(){let t=async(e,r)=>{let{getModelRegistry:n}=await Promise.resolve().then(()=>(We(),mp)),o=n().getTunable("searxngBaseUrl")??process.env.SEARXNG_BASE_URL?.trim();if(!o)return{query:e,results:[],totalResults:0};let s=r?.maxResults??10,i=new URL("/search",o);i.searchParams.set("q",e),i.searchParams.set("format","json"),i.searchParams.set("pageno","1");let a=new AbortController,c=setTimeout(()=>a.abort(),15e3);try{let l=await fetch(i.toString(),{signal:a.signal,headers:{Accept:"application/json"}});if(!l.ok)return{query:e,results:[]};let d=await l.json(),u=(d.results??[]).slice(0,s).map(p=>({title:p.title??"",url:p.url??"",snippet:p.content??""}));if(r?.allowedDomains?.length){let p=new Set(r.allowedDomains.map(m=>m.toLowerCase()));return{query:e,results:u.filter(m=>{try{return p.has(new URL(m.url).hostname.toLowerCase())}catch{return!1}})}}if(r?.blockedDomains?.length){let p=new Set(r.blockedDomains.map(m=>m.toLowerCase()));return{query:e,results:u.filter(m=>{try{return!p.has(new URL(m.url).hostname.toLowerCase())}catch{return!0}})}}return{query:e,results:u,totalResults:d.number_of_results}}finally{clearTimeout(c)}};return{search:(e,r)=>gk(kk,t)(e,r)}}function UN(){function t(o){if(o==="default")return oe()?.workspaceDir??Xe;let s=Ee(o);if(!s)throw new Error(`Unknown project: ${o}`);return s.workspaceDir}function e(o){return ir(t(o))}function r(o,s){if(!s.endsWith(".md"))throw new Error("Filename must end with .md");if(s.includes(".."))throw new Error("Path traversal not allowed");let i=e(o),a=U.resolve(i,s);if(!a.startsWith(i+U.sep)&&a!==i)throw new Error("Path traversal not allowed");return a}function n(o,s){if(!j.existsSync(o))return[];let i=[];for(let a of j.readdirSync(o,{withFileTypes:!0})){let c=U.join(o,a.name);if(a.isDirectory())i.push(...n(c,s));else if(a.isFile()&&a.name.endsWith(".md")){let l=j.statSync(c);i.push({filename:U.relative(s,c).replace(/\\/g,"/"),path:c,size:l.size,updatedAt:l.mtime.toISOString(),content:j.readFileSync(c,"utf-8")})}}return i}return{list(o){let s=e(o);return n(s,s).map(i=>({filename:i.filename,path:i.path,size:i.size,updatedAt:i.updatedAt}))},read(o,s){try{let i=r(o,s);if(!j.existsSync(i))return null;let a=j.statSync(i),c=j.readFileSync(i,"utf-8");return{filename:s,path:i,size:a.size,updatedAt:a.mtime.toISOString(),content:c}}catch{return null}},write(o,s,i){let a=r(o,s);j.mkdirSync(U.dirname(a),{recursive:!0}),j.writeFileSync(a,i,"utf-8");let c=j.statSync(a);return{filename:s,path:a,size:c.size,updatedAt:c.mtime.toISOString(),content:i}},remove(o,s){try{let i=r(o,s);return j.existsSync(i)?(j.unlinkSync(i),!0):!1}catch{return!1}}}}var FN={think:"orchestration",task:"orchestration",ask_user:"orchestration",exec:"developer",read:"filesystem",write:"filesystem",edit:"filesystem",patch:"filesystem",apply_patch:"filesystem",search:"search",web_fetch:"web",web_search:"web",instructions:"filesystem",worktree:"developer",notebook_edit:"developer",workflow:"automation",sleep:"automation",project_switch:"system",tool_search:"search",image_generate:"media",tts:"media",video_generate:"media",music_generate:"media",video_edit:"media",video_merge:"media",video_upscale:"media",three_d_generate:"media",stt:"media",voice_clone:"media",media_cancel:"media",file_upload:"filesystem",file_query:"filesystem",file_delete:"filesystem"};function HN(t){for(let e of t)e.category??=FN[e.name]??"other",e.displayName??={key:`capability.tool.${e.name}.name`,fallback:e.label},e.displayDescription??={key:`capability.tool.${e.name}.description`,fallback:""}}var BN=()=>{throw new Error("workflow tool: this controller is authoring-only; `run` requires the initialized engine")};function qN(t){function e(){let r=new ur(t),n=qs();return{controller:n??new dr(r,BN),live:n,store:r}}return{async list(){return e().store.list()},async get(r){return e().store.require(r)},async describe(r){return e().controller.describe(r)},async create(r){return e().controller.create({id:r.id,name:r.name,def:r.def,active:r.active})},async patch(r,n){return e().controller.patch(r,{patch:n.patch,baseRev:n.baseRev,scope:n.scope})},async setActive(r,n){return e().controller.setActive(r,n)},async run(r){let{live:n}=e();if(!n)throw new Error("workflow engine is not initialized in this context. Activate the workflow (setActive) so a trigger runs it, or run it from the app.");let o={type:"manual"};return n.run(r,o)},async delete(r){await e().store.delete(r)}}}function Ck(t){t?.workdir&&(Xe=t.workdir),DN(),Zs(Xe);let e=[];e.push(Wb()),e.push(pf(void 0,{onTaskCreated:d=>xd?.onTaskCreated?.(d),onTaskCompleted:d=>xd?.onTaskCompleted?.(d)})),e.push(ck({askUser:async d=>Rk?.(d)??null})),e.push(nv({onProgress:t?.onExecProgress,validateCommand:async d=>{let u=/(?:>>?|[12]>)\s*(?:"([^"]+)"|'([^']+)'|(\S+))/g,p;for(;(p=u.exec(d))!==null;){let g=p[1]||p[2]||p[3];if(g){let f=U.isAbsolute(g)?U.normalize(g):U.resolve(Xe,g);if(!co(f))return`Blocked: output redirection to path outside workspace: ${g}`}}let m=[/(?:^|[\s;|&(])(?:"(\/[^"]+)"|'(\/[^']+)'|(\/(?!dev\/null\b)[^\s;|&><)]+))/g,/(?:^|[\s;|&(])(?:"([A-Za-z]:[\\\/][^"]+)"|'([A-Za-z]:[\\\/][^']+)'|([A-Za-z]:[\\\/][^\s;|&><)]+))/g,/(?:^|[\s;|&(])(?:"([^"]*\.\.[\\/][^"]+)"|'([^']*\.\.[\\/][^']+)'|([^\s;|&><)"']*\.\.[\\/][^\s;|&><)]+))/g];for(let g of m){let f;for(;(f=g.exec(d))!==null;){let h=f[1]||f[2]||f[3];if(!h||/^\/[a-zA-Z](?:[- ]|$)/.test(h)||/^\/[a-zA-Z]{1,3}$/.test(h))continue;let v;if(process.platform==="win32"&&/^\/[a-zA-Z]\//.test(h)){let b=h.replace(/^\/([a-zA-Z])\//,(S,T)=>`${T.toUpperCase()}:\\`).replace(/\//g,"\\");v=U.normalize(b)}else v=U.isAbsolute(h)?U.normalize(h):U.resolve(Xe,h);if(!co(v))return`Blocked: command references path outside workspace: ${h}`}}return null},interpretExitCode:(d,u)=>{if(d===127)return"command not found";if(d===126)return"permission denied";if(d===137)return"killed (SIGKILL / OOM)";if(d===143)return"terminated (SIGTERM)";if(d===130)return"interrupted (Ctrl+C)"}}));let r=AN(),n=xN(),o=PN(),s=CN();e.push(iv(r)),e.push(cv(n)),e.push(lv(o)),e.push(fd(s)),e.push(mv(s)),e.push(pv(IN())),e.push(Sv(LN())),e.push(wv($N()));let i=UN();e.push(Tv(i));let a=t?.log??{info:()=>{},warn:()=>{}};e.push(Av(Uv({log:a}))),e.push(qv()),e.push(Wv({getService:()=>qN(Xe)})),e.push(Gv({sleep:(d,u)=>new Promise(p=>{let m=Date.now(),g=setTimeout(()=>{p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!1})},d),f=()=>{clearTimeout(g),p({sleptSeconds:Math.round((Date.now()-m)/1e3),interrupted:!0,interruptReason:"aborted"})};u.addEventListener("abort",f,{once:!0}),u.aborted&&(clearTimeout(g),f())})}));let c={listProjects:()=>V(),switchProject:d=>wt(d),onSwitched:d=>bN?.(d)};e.push(lk(c)),e.push(zv({searchTools:async(d,u)=>{let p=u?.maxResults??5,m=Jt(),g=d.toLowerCase().split(/\s+/).filter(Boolean),f=[],h=[];for(let R of g)R.startsWith("+")&&R.length>1?f.push(R.slice(1)):h.push(R);let v=[...f,...h],b=R=>R.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase().split(/\s+/).filter(Boolean);return{matches:m.map(R=>{let P=ve(R),I=b(R),E=(P?.description??"").toLowerCase(),N=(P?.searchHint??"").toLowerCase();if(f.length>0){let k=`${I.join(" ")} ${E} ${N}`;if(!f.every(Le=>k.includes(Le)))return null}let xe=0;for(let k of v){let Q=0;I.some(Le=>Le===k)?Q=10:I.some(Le=>Le.includes(k))?Q=5:R.toLowerCase().includes(k)&&(Q=3),N&&new RegExp(`\\b${k}`,"i").test(N)&&(Q+=4),new RegExp(`\\b${k}`,"i").test(E)&&(Q+=2),xe+=Q}return{name:R,description:P?.description??"",searchHint:P?.searchHint,score:xe}}).filter(R=>R!==null&&R.score>0).sort((R,P)=>P.score-R.score).slice(0,p),query:d,totalDeferred:m.length}},activateTool:async d=>tm(d)})),e.push({...Vv({generateImage:async d=>{let u=await Ft({mediaType:"image",model:"",prompt:d.prompt,purpose:d.purpose,style:d.style,size:d.size,imageUrl:d.imageUrl,n:d.n,quality:d.quality,seed:d.seed});return{mediaUrls:u.mediaUrls,model:u.model,size:u.size,durationMs:u.durationMs}}}),isConcurrencySafe:!0,isEnabled:()=>Ht("image")}),e.push({...Xv({textToSpeech:async d=>{let u=await Ft({mediaType:"tts",model:"",prompt:"",text:d.text,channel:d.channel,voice:d.voice,speed:d.speed});return{audioPath:"",provider:u.model,mediaUrls:u.mediaUrls}}}),isConcurrencySafe:!0,isEnabled:()=>Ht("tts")}),e.push({...Yv({generateVideo:async d=>{let u=await Ft({mediaType:"video",model:"",prompt:d.prompt,purpose:d.purpose,style:d.style,imageUrl:d.imageUrl,referenceVideos:d.referenceVideos,referenceAudios:d.referenceAudios,generateAudio:d.generateAudio,aspectRatio:d.aspectRatio,duration:d.duration,resolution:d.resolution,fps:d.fps,seed:d.seed,cameraFixed:d.cameraFixed,returnLastFrame:d.returnLastFrame,draft:d.draft,serviceTier:d.serviceTier,callbackUrl:d.callbackUrl,safetyIdentifier:d.safetyIdentifier,executionExpiresAfterSeconds:d.executionExpiresAfterSeconds,videoTools:d.videoTools});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs,lastFrameUrl:u.lastFrameUrl,taskId:u.taskId}}}),isConcurrencySafe:!0,isEnabled:()=>Ht("video")}),e.push({...Jv({generateMusic:async d=>{let u=await Ft({mediaType:"music",model:"",prompt:d.prompt,purpose:d.purpose,style:d.style,lyrics:d.lyrics,duration:d.duration,isInstrumental:d.isInstrumental,audioUrl:d.audioUrl,audioFormat:d.audioFormat});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs}},generateLyrics:async d=>{let u=fr.music;if(!u||!De)return"";let p=De.getTransport(u.provider);if(!Au(p))return"";let m=sr(Or,u.provider);return m?p.generateLyrics(d,m):""}}),isConcurrencySafe:!0,isEnabled:()=>Ht("music")}),e.push({...Qv({editVideo:async d=>{let u=await Ft({mediaType:"video",model:"",prompt:d.prompt,operation:"edit",sourceVideos:d.sourceVideos,referenceImages:d.referenceImages,duration:d.duration,aspectRatio:d.aspectRatio,resolution:d.resolution});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs}}}),shouldDefer:!0,isEnabled:()=>Td("video","edit")}),e.push({...Zv({mergeVideos:async d=>{let u=[`merge ${d.clips.length} clips`];d.transition&&u.push(`transition: ${d.transition}${d.transitionDuration?` (${d.transitionDuration}s)`:""}`),d.subtitles&&u.push(`burn-in subtitles: ${d.subtitles}`),d.bgm&&u.push(`background music: ${d.bgm}${d.bgmVolume!==void 0?` at volume ${d.bgmVolume}`:""}`);let p=await Ft({mediaType:"video",model:"",prompt:u.join("; "),operation:"merge",sourceVideos:d.clips.map(m=>m.video),resolution:d.outputResolution,fps:d.outputFps});return{localPath:"",servePath:p.mediaUrls[0]??"",durationSec:(p.durationMs??0)/1e3,clipCount:d.clips.length,mediaUrls:p.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>Td("video","merge")}),e.push({...ek({upscaleVideo:async d=>{let u=["upscale"];d.sharpness&&u.push(`sharpness: ${d.sharpness}`);let p=await Ft({mediaType:"video",model:"",prompt:u.join(", "),operation:"upscale",sourceVideos:[d.video],resolution:d.targetResolution??"1080p"});return{localPath:"",servePath:p.mediaUrls[0]??"",resolution:d.targetResolution??"1080p",durationSec:(p.durationMs??0)/1e3,mediaUrls:p.mediaUrls}}}),shouldDefer:!0,isEnabled:()=>Td("video","upscale")}),e.push({...tk({generate3D:async d=>{let u=await Ft({mediaType:"3d",model:"",prompt:d.prompt,imageUrl:d.imageUrl,outputFormat:d.outputFormat,seed:d.seed});return{mediaUrls:u.mediaUrls,model:u.model,durationMs:u.durationMs,metadata:u.metadata}}}),isConcurrencySafe:!0,shouldDefer:!0,isEnabled:()=>Ht("3d")}),e.push({...rk({speechToText:async d=>{let u=await Ft({mediaType:"stt",model:"",prompt:"",audioUrl:d.audioUrl,metadata:d.language?{language:d.language}:void 0});return{transcription:u.metadata?.transcription??"",model:u.model,durationMs:u.durationMs}}}),shouldDefer:!0,isEnabled:()=>Ht("stt")}),e.push({...nk({cloneVoice:async d=>{let u=await Ft({mediaType:"voice_clone",model:"",prompt:"",text:d.text,audioUrl:d.sampleAudioUrl,speed:d.speed});return{mediaUrls:u.mediaUrls,model:u.model,voiceId:u.metadata?.voiceId,durationMs:u.durationMs}}}),shouldDefer:!0,isEnabled:()=>Ht("voice_clone")}),e.push({...ok({cancelTask:async d=>{let u=d.provider??"doubao";if(!De)return{ok:!1,message:"Media client not configured."};let p=De.getTransport(u);if(!p)return{ok:!1,message:`No transport for provider: ${u}`};let m=sr(Or,u);if(!m)return{ok:!1,message:`No API key for provider: ${u}`};try{return"deleteVideoTask"in p&&typeof p.deleteVideoTask=="function"?(await p.deleteVideoTask(d.taskId,m),{ok:!0,message:"Task cancelled."}):{ok:!1,message:`Provider ${u} does not support task cancellation.`}}catch(g){return{ok:!1,message:g instanceof Error?g.message:String(g)}}}}),shouldDefer:!0,isEnabled:()=>Ht("video")||Ht("3d")});let l=pk({getContext:()=>({mediaClient:De,mediaProviders:fr,mediaApiKeys:Or}),resolvePath:Ne});return e.push({...sk(l),shouldDefer:!0,isEnabled:()=>l.isAvailable()}),e.push({...ik(l),shouldDefer:!0,isEnabled:()=>l.isAvailable()}),e.push({...ak(l),shouldDefer:!0,isEnabled:()=>l.isAvailable()}),HN(e),em(e),t?.log?.info(`[tool-bootstrap] Registered ${e.length} local tools (${e.filter(d=>d.isEnabled?.()!==!1).length} enabled): ${Jt().join(", ")}`),e}var hn=class{mode;rules;defaultBehavior;compiledPatterns;constructor(e){this.mode=e.mode,this.rules=[...e.rules],this.defaultBehavior=e.defaultBehavior,this.compiledPatterns=this.compileRules(this.rules)}getMode(){return this.mode}setMode(e){this.mode=e}getRules(){return this.rules}getDefaultBehavior(){return this.defaultBehavior}replaceRules(e){this.rules=[...e],this.compiledPatterns=this.compileRules(this.rules)}setDefaultBehavior(e){this.defaultBehavior=e}addRule(e){this.rules.push(e),this.compiledPatterns=this.compileRules(this.rules)}applyUpdate(e){let r={pattern:e.pattern,behavior:e.behavior,reason:e.description,source:"user"};this.rules=[r,...this.rules.filter(n=>!VN(n.pattern,e.pattern))],this.compiledPatterns=this.compileRules(this.rules)}check(e){let{toolName:r,meta:n}=e;switch(this.mode){case"bypassPermissions":return{behavior:"allow",decisionReason:{type:"mode",mode:"bypassPermissions"}};case"dontAsk":return n?.isReadOnly?{behavior:"allow",decisionReason:{type:"mode",mode:"dontAsk"}}:{behavior:"deny",message:`Tool "${r}" denied \u2014 mode is dontAsk`,decisionReason:{type:"mode",mode:"dontAsk"}};case"plan":return{behavior:"deny",message:`Tool "${r}" paused \u2014 mode is plan (execution suspended)`,decisionReason:{type:"mode",mode:"plan"}}}for(let{rule:o,regex:s}of this.compiledPatterns)if(s.test(r))return GN(o,e);return n?.isReadOnly?{behavior:"allow",decisionReason:{type:"tool_check",reason:"isReadOnly"}}:n?.requiresApproval?{behavior:"ask",message:`Tool "${r}" requires approval`,toolName:r,input:e.arguments,decisionReason:{type:"tool_check",reason:"requiresApproval"}}:n?.isDangerous?{behavior:"ask",message:`Tool "${r}" is marked dangerous`,toolName:r,input:e.arguments,decisionReason:{type:"tool_check",reason:"isDangerous"}}:this.mode==="acceptEdits"?{behavior:"allow",decisionReason:{type:"mode",mode:"acceptEdits"}}:this.defaultBehavior==="allow"?{behavior:"allow"}:this.defaultBehavior==="deny"?{behavior:"deny",message:`Tool "${r}" denied by default policy`,decisionReason:{type:"other",reason:"default_deny"}}:{behavior:"ask",message:`Tool "${r}" requires approval (default policy)`,toolName:r,input:e.arguments}}compileRules(e){return e.map(r=>({rule:r,regex:WN(r.pattern)}))}};function jr(t){if(!t||typeof t!="object")return{mode:"default",rules:[],defaultBehavior:"allow"};let e=t,r=[];for(let a of["allow","deny","ask"]){let c=e[a];if(Array.isArray(c))for(let l of c)typeof l=="string"&&r.push({pattern:l,behavior:a,source:"config"})}if(Array.isArray(e.rules)){for(let a of e.rules)if(a&&typeof a=="object"){let c=a,l=c.pattern,d=c.behavior??c.action;typeof l=="string"&&typeof d=="string"&&(d==="allow"||d==="deny"||d==="ask")&&r.push({pattern:l,behavior:d,reason:typeof c.reason=="string"?c.reason:void 0,source:typeof c.source=="string"?c.source:"config"})}}let n=e.mode,o=typeof n=="string"&&KN(n)?n:"default",s=e.default??e.defaultBehavior,i=typeof s=="string"&&zN(s)?s:"allow";return{mode:o,rules:r,defaultBehavior:i}}function WN(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*+/g,".*");return new RegExp(`^${r}$`,"i")}function GN(t,e){let r={type:"rule",rule:t};return t.behavior==="allow"?{behavior:"allow",decisionReason:r}:t.behavior==="deny"?{behavior:"deny",message:t.reason??`Tool "${e.toolName}" denied by rule "${t.pattern}"`,decisionReason:r}:{behavior:"ask",message:t.reason??`Tool "${e.toolName}" requires approval (rule "${t.pattern}")`,toolName:e.toolName,input:e.arguments,decisionReason:r}}function KN(t){return t==="default"||t==="bypassPermissions"||t==="acceptEdits"||t==="dontAsk"||t==="plan"||t==="auto"}function zN(t){return t==="allow"||t==="deny"||t==="ask"}function VN(t,e){return t.toLocaleLowerCase()===e.toLocaleLowerCase()}function Ik(t,e){let r=jr(e);return t.setMode(r.mode),t.replaceRules(r.rules),t.setDefaultBehavior(r.defaultBehavior),r}import{randomUUID as XN}from"node:crypto";function Ek(t){wk(async e=>{let r=`ask-${XN().slice(0,8)}`;return new Promise(n=>{t.pendingAskUser.set(r,{resolve:n}),t.sendNotification("turn.ask_user",{requestId:r,questions:e.map(o=>({header:o.header,question:o.question,options:o.options}))})})})}function ii(t,e){return{name:t,compute:e,cacheBreak:!1}}function Bt(t,e,r){return{name:t,compute:e,cacheBreak:!0}}var si=new Map;async function YN(t){return(await Promise.all(t.map(async r=>{if(!r.cacheBreak&&si.has(r.name))return si.get(r.name)??null;let n=await r.compute();return si.set(r.name,n),n}))).filter(r=>r!=null)}function _k(){si.clear()}async function ai(t){let e=[];if(t.instructionBlock&&e.push(t.instructionBlock),t.customSystemPrompt?e.push(t.customSystemPrompt):t.basePrompt&&e.push(t.basePrompt),t.sections?.length){let r=await YN(t.sections);e.push(...r)}return t.appendSystemPrompt&&e.push(t.appendSystemPrompt),e.filter(Boolean).join(`
|
|
548
548
|
|
|
549
|
-
`)}var JN=250;async function Mk(t,e){let r=new AbortController;t.activeTurn&&(t.activeTurn.abort(),await QN(t.turnDone)),t.activeTurn=r;let n;return t.turnDone=new Promise(o=>{n=o}),e&&e!==t.currentSessionId&&(t.currentSessionId&&t.currentHooks&&(t.currentHooks.invoke("session.ended",{sessionId:t.currentSessionId}).catch(()=>{}),_k()),t.currentSessionId=e,t.sessionState=new pr(e),t.sessionTaskDomain=void 0,t.memoryPrefetchState=ht(),t.enableIdleDream()),{abortController:r,resolveTurnDone:n}}async function QN(t){let e;try{await Promise.race([t,new Promise(r=>{e=setTimeout(r,JN),e.unref?.()})])}finally{e&&clearTimeout(e)}}function Nd(t,e){t.activeTurn===e.abortController&&(t.activeTurn=null),e.resolveTurnDone()}We();var ZN=[{purpose:"imageGeneration",capability:"image"},{purpose:"tts",capability:"tts"},{purpose:"videoGeneration",capability:"video"},{purpose:"musicGeneration",capability:"music"},{purpose:"threeDGeneration",capability:"3d"},{purpose:"stt",capability:"stt"},{purpose:"voiceClone",capability:"voice_clone"}];function eL(t){let e={};for(let{purpose:r,capability:n}of ZN){let o=t.getBinding(r);o&&(e[n]={provider:o.provider,model:o.nativeModelId??o.model})}return e}function ci(t){let{host:e,config:r,turnId:n}=t,o=M(),s=o.snapshotProviderKeys();e.currentMediaApiKeys=s;let i={...eL(o),...r?.mediaProviders};Tk(e.mediaClient,s,(c,l,d)=>{e.sessionState?.addMediaUsage(c,l,d)},i,(c,l,d,u,p)=>{e.sendNotification("turn.media_progress",{turnId:n,taskId:c,mediaType:l,percent:d,status:u,...p?{provider:p}:{}})});let a=o.getActiveModel("textGeneration");a?(_d(wu(a.provider,a.apiKey)),a.keyHandle.release({success:!0})):_d(void 0)}import*as lo from"node:path";D();var tL=1800*1e3,Nk=new mn;function Lk(t){let{config:e,host:r,sessionId:n}=t;if(e?.workdir&&typeof e.workdir=="string"&&r.setActiveWorkdir(e.workdir),!e?.workdir&&n&&e?.projectId){let i=e.projectId;try{let a=Nk.getProjectWorkspaceDir(i);r.getActiveProjectRoot()!==a&&(r.log(`[turn] routing session ${n} to project ${i} (${a})`),r.setActiveWorkdir(a))}catch{r.log(`[turn] project ${i} not found, using active project`)}}e?.sessionType==="group"&&typeof e?.groupKey=="string"&&rL(e,r);let o=nL(e,r,t.nowMs??Date.now()),s=oL(e,r);return{sessionProjectRoot:s,sessionProjectId:sL(e,s,n),projectHintStale:o.projectHintStale,staleProjectHintContext:o.staleProjectHintContext}}function rL(t,e){let r=t.groupKey,n=r.split(":"),o=n.length>=3?n.slice(1).join(":"):r,s=fs(o);if(s){e.setActiveWorkdir(s.workspaceDir),oe()?.id!==s.id&&wt(s.id);return}let i=t.groupName||o,a=o.replace(/[<>:"/\\|?*\x00-\x1f]/g,"_").trim()||"group",c=lo.join(F(),"workspaces","groups",a),l=gs({name:i,workspaceDir:c,type:"group",groupId:o});e.setActiveWorkdir(l.workspaceDir),wt(l.id),e.sendNotification("project.created",{id:l.id,name:l.name,type:"group",groupId:o,workspaceDir:l.workspaceDir})}function nL(t,e,r){let n=t?.projectHint,o=n&&typeof n=="object"&&"name"in n?n:typeof n=="string"?{name:n,updatedAt:r}:null;if(!o||t?.sessionType==="group")return{projectHintStale:!1};let s=r-o.updatedAt;if(s>tL)return e.log(`[projectHint] stale (${Math.round(s/6e4)}min old), skipping auto-switch`),{projectHintStale:!0,staleProjectHintContext:{activeProjectName:oe()?.name,projectNames:V().filter(l=>l.status==="active").map(l=>l.name).slice(0,10)}};let i=o.name,a=oe();if(!a||a.name.toLowerCase()!==i.toLowerCase()){let c=V(),l=i.toLowerCase(),d=c.find(u=>u.name.toLowerCase()===l)??c.find(u=>u.name.toLowerCase().includes(l));d&&d.status==="active"&&(wt(d.id),e.setActiveWorkdir(d.workspaceDir))}return{projectHintStale:!1}}function oL(t,e){if(typeof t?.workdir=="string"&&t.workdir)return t.workdir;let r=t?.projectId;if(r)try{return Nk.getProjectWorkspaceDir(r)}catch{}return e.getActiveProjectRoot()}function sL(t,e,r){if(r){let i=
|
|
549
|
+
`)}var JN=250;async function Mk(t,e){let r=new AbortController;t.activeTurn&&(t.activeTurn.abort(),await QN(t.turnDone)),t.activeTurn=r;let n;return t.turnDone=new Promise(o=>{n=o}),e&&e!==t.currentSessionId&&(t.currentSessionId&&t.currentHooks&&(t.currentHooks.invoke("session.ended",{sessionId:t.currentSessionId}).catch(()=>{}),_k()),t.currentSessionId=e,t.sessionState=new pr(e),t.sessionTaskDomain=void 0,t.memoryPrefetchState=ht(),t.enableIdleDream()),{abortController:r,resolveTurnDone:n}}async function QN(t){let e;try{await Promise.race([t,new Promise(r=>{e=setTimeout(r,JN),e.unref?.()})])}finally{e&&clearTimeout(e)}}function Nd(t,e){t.activeTurn===e.abortController&&(t.activeTurn=null),e.resolveTurnDone()}We();var ZN=[{purpose:"imageGeneration",capability:"image"},{purpose:"tts",capability:"tts"},{purpose:"videoGeneration",capability:"video"},{purpose:"musicGeneration",capability:"music"},{purpose:"threeDGeneration",capability:"3d"},{purpose:"stt",capability:"stt"},{purpose:"voiceClone",capability:"voice_clone"}];function eL(t){let e={};for(let{purpose:r,capability:n}of ZN){let o=t.getBinding(r);o&&(e[n]={provider:o.provider,model:o.nativeModelId??o.model})}return e}function ci(t){let{host:e,config:r,turnId:n}=t,o=M(),s=o.snapshotProviderKeys();e.currentMediaApiKeys=s;let i={...eL(o),...r?.mediaProviders};Tk(e.mediaClient,s,(c,l,d)=>{e.sessionState?.addMediaUsage(c,l,d)},i,(c,l,d,u,p)=>{e.sendNotification("turn.media_progress",{turnId:n,taskId:c,mediaType:l,percent:d,status:u,...p?{provider:p}:{}})});let a=o.getActiveModel("textGeneration");a?(_d(wu(a.provider,a.apiKey)),a.keyHandle.release({success:!0})):_d(void 0)}import*as lo from"node:path";D();var tL=1800*1e3,Nk=new mn;function Lk(t){let{config:e,host:r,sessionId:n}=t;if(e?.workdir&&typeof e.workdir=="string"&&r.setActiveWorkdir(e.workdir),!e?.workdir&&n&&e?.projectId){let i=e.projectId;try{let a=Nk.getProjectWorkspaceDir(i);r.getActiveProjectRoot()!==a&&(r.log(`[turn] routing session ${n} to project ${i} (${a})`),r.setActiveWorkdir(a))}catch{r.log(`[turn] project ${i} not found, using active project`)}}e?.sessionType==="group"&&typeof e?.groupKey=="string"&&rL(e,r);let o=nL(e,r,t.nowMs??Date.now()),s=oL(e,r);return{sessionProjectRoot:s,sessionProjectId:sL(e,s,n),projectHintStale:o.projectHintStale,staleProjectHintContext:o.staleProjectHintContext}}function rL(t,e){let r=t.groupKey,n=r.split(":"),o=n.length>=3?n.slice(1).join(":"):r,s=fs(o);if(s){e.setActiveWorkdir(s.workspaceDir),oe()?.id!==s.id&&wt(s.id);return}let i=t.groupName||o,a=o.replace(/[<>:"/\\|?*\x00-\x1f]/g,"_").trim()||"group",c=lo.join(F(),"workspaces","groups",a),l=gs({name:i,workspaceDir:c,type:"group",groupId:o});e.setActiveWorkdir(l.workspaceDir),wt(l.id),e.sendNotification("project.created",{id:l.id,name:l.name,type:"group",groupId:o,workspaceDir:l.workspaceDir})}function nL(t,e,r){let n=t?.projectHint,o=n&&typeof n=="object"&&"name"in n?n:typeof n=="string"?{name:n,updatedAt:r}:null;if(!o||t?.sessionType==="group")return{projectHintStale:!1};let s=r-o.updatedAt;if(s>tL)return e.log(`[projectHint] stale (${Math.round(s/6e4)}min old), skipping auto-switch`),{projectHintStale:!0,staleProjectHintContext:{activeProjectName:oe()?.name,projectNames:V().filter(l=>l.status==="active").map(l=>l.name).slice(0,10)}};let i=o.name,a=oe();if(!a||a.name.toLowerCase()!==i.toLowerCase()){let c=V(),l=i.toLowerCase(),d=c.find(u=>u.name.toLowerCase()===l)??c.find(u=>u.name.toLowerCase().includes(l));d&&d.status==="active"&&(wt(d.id),e.setActiveWorkdir(d.workspaceDir))}return{projectHintStale:!1}}function oL(t,e){if(typeof t?.workdir=="string"&&t.workdir)return t.workdir;let r=t?.projectId;if(r)try{return Nk.getProjectWorkspaceDir(r)}catch{}return e.getActiveProjectRoot()}function sL(t,e,r){if(r){let i=zt(r,e);if(i?.projectId)return i.projectId}let n=t?.projectId;if(n&&Ee(n))return n;let o=oe();return o&&Dk(o.workspaceDir,e)?o.id:V().find(i=>Dk(i.workspaceDir,e))?.id}function Dk(t,e){return lo.resolve(t).toLowerCase()===lo.resolve(e).toLowerCase()}import{randomUUID as Ok}from"node:crypto";function li(t){let{event:e,turnId:r,now:n,host:o}=t;switch(e.type){case"delta":return o.sendNotification("turn.delta",{turnId:e.turnId,text:e.text,item:{id:`${r}-delta`,type:"message",role:"assistant",text:e.text,createdAt:n}}),!0;case"tool_call":return o.sendNotification("turn.tool_call",{turnId:e.turnId,callId:e.callId,name:e.name,arguments:e.arguments,...e.inputSummary?{inputSummary:e.inputSummary}:{},item:{id:e.callId,type:"tool_call",role:"assistant",toolName:e.name,toolCallId:e.callId,arguments:e.arguments,createdAt:n}}),!0;case"tool_result":return o.sendNotification("turn.tool_result",{turnId:e.turnId,callId:e.callId,name:e.name,ok:e.ok,...e.error?{error:e.error}:{},...e.outputPreview?{outputPreview:e.outputPreview}:{},...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...e.exitCode!==void 0?{exitCode:e.exitCode}:{},...e.stdout?{stdout:e.stdout}:{},...e.stderr?{stderr:e.stderr}:{},...e.details?{details:e.details}:{},item:{id:`${e.callId}-result`,type:"tool_result",role:"assistant",toolName:e.name,toolCallId:e.callId,output:e.ok?e.outputPreview??"":e.error,approved:e.ok,createdAt:n}}),!0;case"tool_blocked":return o.sendNotification("turn.tool_blocked",{turnId:e.turnId,callId:e.callId,name:e.name,reason:e.reason,item:{id:`${e.callId}-blocked`,type:"tool_blocked",role:"system",toolName:e.name,toolCallId:e.callId,text:e.reason,approved:!1,createdAt:n}}),!0;case"recovery":return o.sendNotification("turn.recovery",{turnId:e.turnId,action:e.action,...e.detail?{detail:e.detail}:{},item:{id:`${r}-recovery-${Ok().slice(0,8)}`,type:"recovery",role:"system",strategy:e.action,text:e.detail,createdAt:n}}),!0;case"plan_update":return o.sendNotification("turn.plan_update",{turnId:e.turnId,slug:e.slug,content:e.content,item:{id:`${r}-plan-${Ok().slice(0,8)}`,type:"plan_update",role:"assistant",text:e.content,createdAt:n}}),!0;case"reasoning_delta":return o.sendNotification("turn.reasoning_delta",{turnId:e.turnId,text:e.text}),!0;case"suggestions":return o.sendNotification("turn.suggestions",{turnId:e.turnId,items:e.items}),!0;case"media_result":return o.sendNotification("turn.media_result",{turnId:e.turnId,mediaType:e.mediaType,url:e.url,...e.model?{model:e.model}:{},...e.provider?{provider:e.provider}:{},...e.taskId?{taskId:e.taskId}:{}}),!0;case"artifact":return o.sendNotification("turn.artifact",{turnId:e.turnId,artifactId:e.artifactId,type:e.artifactType,title:e.title,...e.filePath?{filePath:e.filePath}:{},...e.language?{language:e.language}:{},...e.content?{content:e.content}:{},...e.mimeType?{mimeType:e.mimeType}:{}}),!0;case"subagent_started":return o.sendNotification("turn.subagent_started",{turnId:e.turnId,subagentId:e.subagentId,agentType:e.agentType,...e.prompt?{prompt:e.prompt}:{}}),!0;case"subagent_ended":return o.sendNotification("turn.subagent_ended",{turnId:e.turnId,subagentId:e.subagentId,agentType:e.agentType,ok:e.ok,...e.outputPreview?{outputPreview:e.outputPreview}:{},...e.error?{error:e.error}:{}}),!0;case"annotations":return o.sendNotification("turn.annotations",{turnId:e.turnId,annotations:e.annotations}),!0;case"heartbeat":return o.sendNotification("turn.heartbeat",{turnId:e.turnId,message:e.message}),!0;case"tool_use_summary":return o.sendNotification("turn.tool_use_summary",{turnId:e.turnId,summary:e.summary}),!0;default:return!1}}var iL=`[SUGGESTION MODE]
|
|
550
550
|
Based on the conversation, suggest 1-3 short follow-up actions the user might naturally do next.
|
|
551
551
|
Be specific: "run the tests" beats "continue".
|
|
552
552
|
Stay silent if the next step isn't obvious.
|
|
@@ -557,25 +557,26 @@ Reply with ONLY a JSON array: [{"text":"short suggestion"}]. No explanation.`;as
|
|
|
557
557
|
`+o+`taskDomain: ${e}
|
|
558
558
|
`,"utf-8")}else Uk(n,o+`taskDomain: ${e}
|
|
559
559
|
`,"utf-8");return!0}catch{return!1}}function qk(t,e){return e==="general"?!1:(Od(t)[e]??0)>=fL}import{release as hL,homedir as yL}from"node:os";import{resolve as Wk}from"node:path";function bL(){let e=(process.env.SHELL??process.env.ComSpec??"").toLowerCase();return e.includes("zsh")?"zsh":e.includes("bash")?"bash":e.includes("fish")?"fish":e.includes("powershell")||e.includes("pwsh")?"powershell":e.includes("cmd")?"cmd":process.platform==="win32"?"powershell":"bash"}function vL(){let t=process.platform,e=hL();return t==="win32"?e.toLowerCase().includes("microsoft")||e.toLowerCase().includes("wsl")?"Windows (WSL)":`Windows ${e.split(".")[0]??""}`.trim():t==="darwin"?"macOS":t==="linux"?"Linux":t}function pi(t){let e=Wk(t??process.cwd());return ii(`environment_context:${e}`,()=>{let r=bL(),n=vL(),o=process.version,s=yL(),i=["# Environment","",`- Platform: ${n}`,`- Shell: ${r}`,`- Working directory: ${Wk(e)}`,`- Home directory: ${s}`,`- Node.js: ${o}`];return r==="powershell"?i.push("- Note: Use PowerShell syntax (semicolons, not &&; use $env: for env vars)"):r==="cmd"&&i.push("- Note: Use CMD syntax (%VAR%, not $VAR)"),i.join(`
|
|
560
|
-
`)})}function ui(){return["## Problem Solving","- If an approach fails, diagnose why before switching tactics \u2014 read the error, check your assumptions, try a focused fix. Don't retry the identical action blindly, but don't abandon a viable approach after a single failure either.","- Report outcomes faithfully: if verification fails, say so with the relevant output; if you did not run a verification step, say that rather than implying it succeeded.","- Do not create files unless they are absolutely necessary for achieving your goal. Prefer editing an existing file to creating a new one.","","## Safety","- Be careful not to introduce security vulnerabilities such as command injection, XSS, SQL injection, and other OWASP top 10 vulnerabilities.","- If you notice that you wrote insecure code, immediately fix it. Prioritize writing safe, secure, and correct code."]}function kL(){return["# Doing Tasks","","You will primarily perform software engineering tasks: solving bugs, adding new functionality, refactoring code, and more.","","## Code Quality","- In general, do not propose changes to code you haven't read. If you need to modify a file, read it first. Understand existing code before suggesting modifications.","","## Implementation Discipline",`- Don't add features, refactor code, or make "improvements" beyond what was asked. A bug fix doesn't need surrounding code cleaned up. A simple feature doesn't need extra configurability.`,"- Don't add error handling, fallbacks, or validation for scenarios that can't happen. Trust internal code and framework guarantees. Only validate at system boundaries (user input, external APIs).","- Don't create helpers, utilities, or abstractions for one-time operations. Don't design for hypothetical future requirements. Three similar lines of code is better than a premature abstraction.","- Default to writing no comments unless the WHY is non-obvious: a hidden constraint, a subtle invariant, a workaround for a specific bug. Don't explain WHAT the code does \u2014 well-named identifiers already do that.",'- Avoid backwards-compatibility hacks like renaming unused _vars, re-exporting types, adding "// removed" comments for removed code. If code is unused, delete it completely.',"","## Completeness and Correctness","- When a task lists multiple constraints or requirements, implement ALL of them explicitly. Do not drop any.","- When refactoring, commit fully to the new pattern. Do NOT mix old and new patterns in the same codebase.","- After making changes, verify you met every requirement from the original request.","- For security fixes, use standard proven patterns (parameterized queries, input validation, etc.).","- NEVER leave TODO comments, placeholder implementations, or stub functions. Every function you write must have a complete, working implementation.","- When creating multiple files that import from each other, ensure every import resolves to a real export. Do not leave dead imports or forward declarations without implementations.","- If you create a file with a function signature, you MUST provide the full body \u2014 not `// implement later` or `throw new Error('not implemented')`.","","## Proactive Action","- When asked to fix, change, or improve code, implement the changes directly by writing to the file. Do not merely describe what should be changed.","- When you identify issues (bugs, security vulnerabilities, style problems), fix them immediately using your tools rather than listing recommendations.","- Default to action: read the file, make the fix, write it back. Only describe without acting when explicitly asked for advice or review only.","","## Faithful Reporting","- Report outcomes faithfully: if a tool call failed, say so with the error output. Do not claim success when a tool returned an error.","- If you did not run a verification step, say that rather than implying it succeeded.","- Never claim 'all tests pass' or 'file created successfully' when tool output shows otherwise.","- If you are unsure whether your changes are complete, state that explicitly rather than asserting completeness."]}function RL(){return["# Doing Tasks","","You will assist with office and analytical tasks: reports, data analysis, documents, presentations, and more.","","## Accuracy and Rigor","- Verify numerical calculations and statistical claims. When presenting data, ensure totals, percentages, and comparisons are mathematically correct.","- Distinguish clearly between facts, inferences, and assumptions. Label uncertain information explicitly.","- When summarizing source material, preserve the original meaning. Do not introduce information not present in the source.","","## Structure and Formatting","- Use clear headings, bullet points, and tables to organize information. Match the formatting conventions of the document type (report, memo, email, slides).","- For data-heavy outputs, prefer tables over prose. Include units, time periods, and comparison baselines.","- Keep language professional and concise. Avoid filler, hedging, and unnecessary qualifiers.","","## Completeness","- When the task lists multiple sections, data points, or requirements, address ALL of them. Do not silently omit items.","- If source data is insufficient to answer a question, state what is missing rather than guessing."]}function SL(){return["# Doing Tasks","","You will assist with creative and content tasks: writing, copywriting, brainstorming, and content strategy.","","## Voice and Style","- Match the requested tone, register, and style. If no style is specified, adapt to the content type (formal for press releases, conversational for blog posts, punchy for ad copy).","- Vary sentence length and structure for rhythm. Avoid monotonous patterns.","- Show, don't tell where appropriate. Use concrete details and vivid language over abstract statements.","","## Audience Awareness","- Write for the intended audience. Consider their knowledge level, interests, and expectations.","- For marketing/copywriting, lead with the benefit. Focus on what matters to the reader, not the feature list.","- Respect cultural context and sensitivity in language choices.","","## Creative Process","- When brainstorming, provide diverse options rather than variations on a single idea. Quantity and variety first, then refine.","- When editing existing text, preserve the author's voice. Make targeted improvements rather than rewriting from scratch.","- If creative constraints are given (word count, format, platform), follow them precisely."]}function Gk(t="general"){return
|
|
561
|
-
`)})}function mi(){return ii("tool_guidance",()=>["# Tool Usage Guidance","","You have access to specialized tools. Use them appropriately:","","## Agent Delegation","Use the `agent` tool to delegate complex, multi-step tasks to sub-agents:","- Research/exploration tasks that benefit from focused attention","- File analysis across multiple files that need independent reasoning","- Any task the user explicitly asks you to delegate","- **When the user says 'delegate', 'sub-agent', 'fork', or 'hand off', you MUST use the `agent` tool \u2014 never handle it yourself**","Do NOT use `agent` for simple file reads or single-step operations.","","## Skill System","Use the `skill` tool (unified meta-tool) for all skill operations:","- action 'invoke' \u2014 run a skill by name","- action 'list' \u2014 discover available skills (shows scope: project/global)","- action 'create' \u2014 save a new skill to current project","- action 'promote' \u2014 copy a project skill to global (user-level)","When recalled memories show '[Cross-project skill available]', proactively offer to use or save the skill.","","## Checkpoint","Use the `checkpoint` tool (not raw git commands) to:","- Save workspace state before making changes","- Restore to a previous state if changes go wrong","The checkpoint tool manages git shadow history automatically.","","## Ask User","Use `ask_user` to clarify ambiguous requests before proceeding
|
|
560
|
+
`)})}function ui(){return["## Problem Solving","- If an approach fails, diagnose why before switching tactics \u2014 read the error, check your assumptions, try a focused fix. Don't retry the identical action blindly, but don't abandon a viable approach after a single failure either.","- Report outcomes faithfully: if verification fails, say so with the relevant output; if you did not run a verification step, say that rather than implying it succeeded.","- Do not create files unless they are absolutely necessary for achieving your goal. Prefer editing an existing file to creating a new one.","","## Safety","- Be careful not to introduce security vulnerabilities such as command injection, XSS, SQL injection, and other OWASP top 10 vulnerabilities.","- If you notice that you wrote insecure code, immediately fix it. Prioritize writing safe, secure, and correct code."]}function kL(){return["# Doing Tasks","","You will primarily perform software engineering tasks: solving bugs, adding new functionality, refactoring code, and more.","","## Code Quality","- In general, do not propose changes to code you haven't read. If you need to modify a file, read it first. Understand existing code before suggesting modifications.","","## Implementation Discipline",`- Don't add features, refactor code, or make "improvements" beyond what was asked. A bug fix doesn't need surrounding code cleaned up. A simple feature doesn't need extra configurability.`,"- Don't add error handling, fallbacks, or validation for scenarios that can't happen. Trust internal code and framework guarantees. Only validate at system boundaries (user input, external APIs).","- Don't create helpers, utilities, or abstractions for one-time operations. Don't design for hypothetical future requirements. Three similar lines of code is better than a premature abstraction.","- Default to writing no comments unless the WHY is non-obvious: a hidden constraint, a subtle invariant, a workaround for a specific bug. Don't explain WHAT the code does \u2014 well-named identifiers already do that.",'- Avoid backwards-compatibility hacks like renaming unused _vars, re-exporting types, adding "// removed" comments for removed code. If code is unused, delete it completely.',"","## Completeness and Correctness","- When a task lists multiple constraints or requirements, implement ALL of them explicitly. Do not drop any.","- When refactoring, commit fully to the new pattern. Do NOT mix old and new patterns in the same codebase.","- After making changes, verify you met every requirement from the original request.","- For security fixes, use standard proven patterns (parameterized queries, input validation, etc.).","- NEVER leave TODO comments, placeholder implementations, or stub functions. Every function you write must have a complete, working implementation.","- When creating multiple files that import from each other, ensure every import resolves to a real export. Do not leave dead imports or forward declarations without implementations.","- If you create a file with a function signature, you MUST provide the full body \u2014 not `// implement later` or `throw new Error('not implemented')`.","","## Proactive Action","- When asked to fix, change, or improve code, implement the changes directly by writing to the file. Do not merely describe what should be changed.","- When you identify issues (bugs, security vulnerabilities, style problems), fix them immediately using your tools rather than listing recommendations.","- Default to action: read the file, make the fix, write it back. Only describe without acting when explicitly asked for advice or review only.","","## Faithful Reporting","- Report outcomes faithfully: if a tool call failed, say so with the error output. Do not claim success when a tool returned an error.","- If you did not run a verification step, say that rather than implying it succeeded.","- Never claim 'all tests pass' or 'file created successfully' when tool output shows otherwise.","- If you are unsure whether your changes are complete, state that explicitly rather than asserting completeness."]}function RL(){return["# Doing Tasks","","You will assist with office and analytical tasks: reports, data analysis, documents, presentations, and more.","","## Accuracy and Rigor","- Verify numerical calculations and statistical claims. When presenting data, ensure totals, percentages, and comparisons are mathematically correct.","- Distinguish clearly between facts, inferences, and assumptions. Label uncertain information explicitly.","- When summarizing source material, preserve the original meaning. Do not introduce information not present in the source.","","## Structure and Formatting","- Use clear headings, bullet points, and tables to organize information. Match the formatting conventions of the document type (report, memo, email, slides).","- For data-heavy outputs, prefer tables over prose. Include units, time periods, and comparison baselines.","- Keep language professional and concise. Avoid filler, hedging, and unnecessary qualifiers.","","## Completeness","- When the task lists multiple sections, data points, or requirements, address ALL of them. Do not silently omit items.","- If source data is insufficient to answer a question, state what is missing rather than guessing."]}function SL(){return["# Doing Tasks","","You will assist with creative and content tasks: writing, copywriting, brainstorming, and content strategy.","","## Voice and Style","- Match the requested tone, register, and style. If no style is specified, adapt to the content type (formal for press releases, conversational for blog posts, punchy for ad copy).","- Vary sentence length and structure for rhythm. Avoid monotonous patterns.","- Show, don't tell where appropriate. Use concrete details and vivid language over abstract statements.","","## Audience Awareness","- Write for the intended audience. Consider their knowledge level, interests, and expectations.","- For marketing/copywriting, lead with the benefit. Focus on what matters to the reader, not the feature list.","- Respect cultural context and sensitivity in language choices.","","## Creative Process","- When brainstorming, provide diverse options rather than variations on a single idea. Quantity and variety first, then refine.","- When editing existing text, preserve the author's voice. Make targeted improvements rather than rewriting from scratch.","- If creative constraints are given (word count, format, platform), follow them precisely."]}function Gk(t="general"){return Bt("task_guidance",()=>{let e;switch(t){case"coding":e=[...kL(),"",...ui()];break;case"office":e=[...RL(),"",...ui()];break;case"creative":e=[...SL(),"",...ui()];break;default:e=["# Doing Tasks","","You are a versatile assistant that handles software engineering, office, and creative tasks.","",...ui(),"","## When Coding","- Read existing code before modifying it. Understand the structure before making changes.","- When refactoring, commit fully to the new pattern. Do NOT mix old and new patterns.","- Implement ALL listed constraints or requirements explicitly. Do not drop any.","- Don't add features or abstractions beyond what was asked.","- When asked to fix or change code, implement changes directly by writing to the file \u2014 do not merely describe what to change.","","## When Writing Documents or Analyzing Data","- Verify numerical calculations and statistical claims for correctness.","- Use clear structure: headings, tables, bullet points as appropriate.","- Distinguish facts from inferences. Label uncertain information.","","## When Creating Content","- Match the requested tone, style, and audience. Adapt if not specified.","- Lead with the benefit for marketing/copywriting tasks.","- Provide diverse options when brainstorming."];break}return e.join(`
|
|
561
|
+
`)})}function mi(){return ii("tool_guidance",()=>["# Tool Usage Guidance","","You have access to specialized tools. Use them appropriately:","","## Agent Delegation","Use the `agent` tool to delegate complex, multi-step tasks to sub-agents:","- Research/exploration tasks that benefit from focused attention","- File analysis across multiple files that need independent reasoning","- Any task the user explicitly asks you to delegate","- **When the user says 'delegate', 'sub-agent', 'fork', or 'hand off', you MUST use the `agent` tool \u2014 never handle it yourself**","Do NOT use `agent` for simple file reads or single-step operations.","","## Skill System","Use the `skill` tool (unified meta-tool) for all skill operations:","- action 'invoke' \u2014 run a skill by name","- action 'list' \u2014 discover available skills (shows scope: project/global)","- action 'create' \u2014 save a new skill to current project","- action 'promote' \u2014 copy a project skill to global (user-level)","When recalled memories show '[Cross-project skill available]', proactively offer to use or save the skill.","","## Checkpoint","Use the `checkpoint` tool (not raw git commands) to:","- Save workspace state before making changes","- Restore to a previous state if changes go wrong","The checkpoint tool manages git shadow history automatically.","","## Ask User","Use `ask_user` to clarify genuinely ambiguous requests before proceeding.","For ordinary creative media requests, infer sensible defaults and use the appropriate media tool directly.","Ask before media generation only when a missing detail is critical to the result or the user is choosing among materially different outputs.","","## Project Rules Management","You can create, edit, and delete project rule files at `.qlogicagent/rules/*.md`.","These files are loaded into your system prompt every turn \u2014 changes take effect immediately.","Use this to help users establish coding conventions, workflow guidelines, or project-specific instructions.","When the user asks to 'add a rule', 'set up conventions', or 'configure instructions', write to `.qlogicagent/rules/<descriptive-name>.md`.","You may also create or edit `.qlogicagent/INSTRUCTIONS.md` for a single top-level instruction file."].join(`
|
|
562
562
|
`))}function gi(t){return ii("language",()=>t?["# Language","",`Always respond in ${t}.`,`Use ${t} for all text output, explanations, and descriptions.`,"Use English only for: code, file paths, tool arguments, variable names, and technical identifiers."].join(`
|
|
563
563
|
`):["# Language","","Respond in the same language as the user's message.","If the user writes in English, respond in English. If in Chinese, respond in Chinese.","Use English only for: code, file paths, tool arguments, variable names, and technical identifiers."].join(`
|
|
564
|
-
`))}var Kk={requiresFreshTool:!1,allowedToolNames:[]},wL=["txt","json","jsonl","ts","tsx","js","jsx","mjs","cjs","md","mdx","yaml","yml","toml","ini","xml","csv","tsv","env","py","go","rs","java","kt","kts","cs","cpp","c","h","hpp","html","css","scss","sass","less","sql","lock","log","sh","ps1","bat","cmd"],jd=new RegExp(`(?:^|[\\s"'\`([{:,])(?:\\.?[\\w@~.-]+[\\\\/])*[\\w@~.-]+\\.(?:${wL.join("|")})\\b`,"i"),TL=/write|create|edit|replace|change|update|modify|overwrite|fix|implement|\u5199|\u65b0\u5efa|\u521b\u5efa|\u7f16\u8f91|\u66ff\u6362|\u6539\u6210|\u4fee\u6539|\u4fee\u590d|\u5b9e\u73b0|\u8986\u76d6/i,AL=/(?:memory|\u8bb0\u5fc6).*(?:create_file|\u8bb0\u5fc6\u6587\u4ef6|\u6587\u4ef6)|(?:create_file).*(?:memory|\u8bb0\u5fc6)/i,xL=/(?:memory|\u8bb0\u5fc6).*(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b|\u5220\u9664|\u79fb\u9664|\u66ff\u6362|\u521b\u5efa|\u8bfb\u53d6|\u641c\u7d22)|(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b).*(?:memory|\u8bb0\u5fc6)/i,PL=/(?:current\s+directory|directory\s+(?:contains|listing|files)|list\s+(?:the\s+)?files|what\s+files|\u5f53\u524d\u76ee\u5f55|\u76ee\u5f55\u4e0b|\u54ea\u4e9b\u6587\u4ef6|\u5217\u51fa.*\u6587\u4ef6)/i,CL=/(?:which\s+file.*contains|contains.*which\s+file|\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6.*\u5305\u542b|\u5305\u542b.*\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6)/i,IL=/(?:^|\s)(?:run|execute)\s+(?:this\s+)?(?:command|shell)?\b|\b(?:echo|pwd|ls|dir|cat|type)\b|\u6267\u884c|\u8fd0\u884c/i,EL=/https?:\/\/\S+/i,_L=/fetch|open|visit|url|return|response|httpbin|\u8bbf\u95ee|\u7f51\u9875|\u8fd4\u56de|\u770b\u4e0b|\u770b\u770b/i;function fi(t){let e=typeof t=="string"?t:
|
|
565
|
-
`)):t.reason==="memory-mutation"?
|
|
566
|
-
`)):
|
|
567
|
-
`))
|
|
564
|
+
`))}var Kk={requiresFreshTool:!1,allowedToolNames:[]},wL=["txt","json","jsonl","ts","tsx","js","jsx","mjs","cjs","md","mdx","yaml","yml","toml","ini","xml","csv","tsv","env","py","go","rs","java","kt","kts","cs","cpp","c","h","hpp","html","css","scss","sass","less","sql","lock","log","sh","ps1","bat","cmd"],jd=new RegExp(`(?:^|[\\s"'\`([{:,])(?:\\.?[\\w@~.-]+[\\\\/])*[\\w@~.-]+\\.(?:${wL.join("|")})\\b`,"i"),TL=/write|create|edit|replace|change|update|modify|overwrite|fix|implement|\u5199|\u65b0\u5efa|\u521b\u5efa|\u7f16\u8f91|\u66ff\u6362|\u6539\u6210|\u4fee\u6539|\u4fee\u590d|\u5b9e\u73b0|\u8986\u76d6/i,AL=/(?:memory|\u8bb0\u5fc6).*(?:create_file|\u8bb0\u5fc6\u6587\u4ef6|\u6587\u4ef6)|(?:create_file).*(?:memory|\u8bb0\u5fc6)/i,xL=/(?:memory|\u8bb0\u5fc6).*(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b|\u5220\u9664|\u79fb\u9664|\u66ff\u6362|\u521b\u5efa|\u8bfb\u53d6|\u641c\u7d22)|(?:(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\s+action\b|action\s*[:=]?\s*['"]?(?:add|replace|remove|create_file|write_file|read_file|delete_file|list_files|search|remember|temporal|feedback)\b).*(?:memory|\u8bb0\u5fc6)/i,PL=/(?:current\s+directory|directory\s+(?:contains|listing|files)|list\s+(?:the\s+)?files|what\s+files|\u5f53\u524d\u76ee\u5f55|\u76ee\u5f55\u4e0b|\u54ea\u4e9b\u6587\u4ef6|\u5217\u51fa.*\u6587\u4ef6)/i,CL=/(?:which\s+file.*contains|contains.*which\s+file|\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6.*\u5305\u542b|\u5305\u542b.*\u54ea(?:\u4e2a|\u4e9b|\u4e00\u4e2a)?\u6587\u4ef6)/i,IL=/(?:^|\s)(?:run|execute)\s+(?:this\s+)?(?:command|shell)?\b|\b(?:echo|pwd|ls|dir|cat|type)\b|\u6267\u884c|\u8fd0\u884c/i,EL=/https?:\/\/\S+/i,_L=/fetch|open|visit|url|return|response|httpbin|\u8bbf\u95ee|\u7f51\u9875|\u8fd4\u56de|\u770b\u4e0b|\u770b\u770b/i,ML=/(?:\bimage_generate\b|\bgenerate\s+(?:an?\s+)?image\b|\bmake\s+(?:an?\s+)?image\b|\bdraw\s+(?:an?\s+)?(?:image|picture|illustration)\b|\bcreate\s+(?:an?\s+)?(?:image|picture|illustration)\b|\u751f\u56fe|\u751f\u6210(?:一张|个|幅)?(?:图片|图像|插画|海报|头像)?|\u753b(?:一张|一个|一幅|一只|一群|个|张|幅|一下)?.+|\u753b(?:一张|个|幅|一幅)?.*(?:图|图片|图像|插画|画面)|(?:图片|图像|插画|海报|头像).*\u751f\u6210)/i;function fi(t){let e=typeof t=="string"?t:DL(t);return e.trim()?ML.test(e)?{requiresFreshTool:!0,reason:"media-generation",allowedToolNames:["image_generate"]}:EL.test(e)&&_L.test(e)?{requiresFreshTool:!0,reason:"web",allowedToolNames:["web_fetch"]}:AL.test(e)&&jd.test(e)||xL.test(e)?{requiresFreshTool:!0,reason:"memory-mutation",allowedToolNames:["memory"]}:TL.test(e)&&jd.test(e)?{requiresFreshTool:!0,reason:"file-mutation",allowedToolNames:["read","search","write","edit","patch","apply_patch"]}:jd.test(e)?{requiresFreshTool:!0,reason:"file-read",allowedToolNames:["read","search"]}:PL.test(e)?{requiresFreshTool:!0,reason:"directory-list",allowedToolNames:["exec"]}:CL.test(e)?{requiresFreshTool:!0,reason:"content-search",allowedToolNames:["search"]}:IL.test(e)?{requiresFreshTool:!0,reason:"shell",allowedToolNames:["exec"]}:Kk:Kk}function hi(t,e){if(!e.requiresFreshTool||e.allowedToolNames.length===0)return[...t];let r=new Set(e.allowedToolNames),n=t.filter(o=>r.has(LL(o)));return n.length>0?n:[...t]}function yi(t){if(!t.requiresFreshTool)return null;let e=t.allowedToolNames.join(", ");return t.reason==="file-mutation"?Bt("fresh_workspace_evidence",()=>["# Workspace File Action Required","","The latest user request asks you to create, edit, fix, or implement files in the workspace.",`Before answering, call the appropriate tool for this turn: ${e}.`,"Use write/edit/patch/apply_patch to make the requested on-disk change. Reading or searching can locate context, but does not satisfy the requested action.","Do not merely describe code, print snippets, or claim completion without a successful file-changing tool result.","If a file-changing tool fails, make at most two focused attempts, then report the exact failure."].join(`
|
|
565
|
+
`)):t.reason==="memory-mutation"?Bt("fresh_workspace_evidence",()=>["# Memory File Action Required","","The latest user request explicitly asks to use the memory tool for a memory file action.",`Before answering, call the appropriate tool for this turn: ${e}.`,"Use the requested memory action and target filename instead of workspace file write/edit tools.","For removal requests, call memory with action='remove' and set old_text to the exact INDEX.md line or labeled marker line the user asked to remove.","Do not call action='add', action='remember', or action='create_file' for a removal request.","Do not merely describe the memory content or create a regular workspace file."].join(`
|
|
566
|
+
`)):t.reason==="media-generation"?Bt("fresh_workspace_evidence",()=>["# Media Generation Required","","The latest user request asks you to create an image.",`Before answering, call the appropriate media tool for this turn: ${e}.`,"Do not answer by inventing a Markdown image URL or placeholder attachment path.","For ordinary creative requests, infer reasonable defaults for purpose, style, and size instead of asking follow-up questions.","Ask the user only when a missing detail is critical to the result or the request is genuinely ambiguous."].join(`
|
|
567
|
+
`)):Bt("fresh_workspace_evidence",()=>["# Fresh Workspace Evidence","","The latest user request asks for current workspace, shell, or URL state.",`Before answering, call one of these tools for this turn: ${e}.`,"Do not answer this request from conversation history, memory, or prior tool results.","For an explicit filename, inspect that exact file first and report the observed value.","If the filename is not found at the given path, use search to locate it, then read the located file before answering.","A filename search alone is not enough to answer content or code-symbol questions."].join(`
|
|
568
|
+
`))}function DL(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(r?.role==="user")return NL(r.content)}return""}function NL(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>{if(!e||typeof e!="object")return"";let r=e;return typeof r.text=="string"?r.text:""}).join(""):""}function LL(t){return t.function?.name??t.name??""}D();import{readFile as OL,readdir as jL,stat as $L}from"node:fs/promises";import{dirname as vi,extname as UL,isAbsolute as FL,join as go,parse as Vk,resolve as zk}from"node:path";import{homedir as HL}from"node:os";var BL="INSTRUCTIONS.md",qL="INSTRUCTIONS.local.md",WL=new Set([".md",".txt",".text",".json",".yaml",".yml",".toml",".xml",".csv",".html",".htm",".css",".scss",".sass",".less",".js",".ts",".tsx",".jsx",".mjs",".cjs",".mts",".cts",".py",".pyi",".pyw",".rb",".erb",".rake",".go",".rs",".java",".kt",".kts",".scala",".c",".cpp",".cc",".cxx",".h",".hpp",".hxx",".cs",".swift",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".env",".ini",".cfg",".conf",".config",".properties",".sql",".graphql",".gql",".proto",".vue",".svelte",".astro",".php",".pl",".pm",".lua",".r",".R",".dart",".ex",".exs",".erl",".hrl",".clj",".cljs",".cljc",".edn",".hs",".lhs",".elm",".ml",".mli",".f",".f90",".f95",".for",".cmake",".make",".makefile",".gradle",".sbt",".rst",".adoc",".asciidoc",".org",".tex",".latex",".lock",".log",".diff",".patch"]);async function GL(t){try{return await OL(t,"utf-8")}catch{return null}}function KL(t){return t.includes("<!--")?t.replace(/^[ \t]*<!--[\s\S]*?-->[ \t]*$/gm,""):t}function zL(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);if(!e)return{content:t};let r=e[1],n=t.slice(e[0].length),o=r.match(/^paths:\s*(.+)$/m);if(!o)return{content:n};let s=[],i=o[1].trim();if(i.startsWith("["))try{s=JSON.parse(i)}catch{}else s=i.split(",").map(c=>c.trim()).filter(Boolean);let a=s.map(c=>c.endsWith("/**")?c.slice(0,-3):c).filter(c=>c.length>0&&c!=="**");return{content:n,globs:a.length>0?a:void 0}}function VL(t,e){let r=new Set,n=/(?:^|\s)@((?:[^\s\\]|\\ )+)/g,s=t.replace(/```[\s\S]*?```/g,"").replace(/`[^`]+`/g,""),i;for(;(i=n.exec(s))!==null;){let a=i[1];if(!a)continue;let c=a.indexOf("#");if(c!==-1&&(a=a.substring(0,c)),!a)continue;a=a.replace(/\\ /g," ");let l;if(a.startsWith("~/"))l=go(HL(),a.slice(2));else if(FL(a))l=a;else if(a.startsWith("./"))l=zk(vi(e),a);else if(/^[a-zA-Z0-9._-]/.test(a)&&!a.startsWith("@"))l=zk(vi(e),a);else continue;r.add(l)}return[...r]}async function mo(t,e,r,n=0,o){let s=t.toLowerCase();if(r.has(s)||n>=_a)return[];let i=UL(t).toLowerCase();if(i&&!WL.has(i))return[];r.add(s);let a=await GL(t);if(!a?.trim())return[];let{content:c,globs:l}=zL(a),d=KL(c);if(!d.trim())return[];let u=[],p={path:t,type:e,content:d.trim()};o&&(p.parent=o),l&&(p.globs=l),u.push(p);let m=VL(c,t);for(let g of m){let f=await mo(g,e,r,n+1,t);u.push(...f)}return u}async function Xk(t,e,r,n,o=new Set){if(o.has(t))return[];o.add(t);let s=[];try{let i=await jL(t,{withFileTypes:!0});for(let a of i){let c=go(t,a.name);if(a.isDirectory())s.push(...await Xk(c,e,r,n,o));else if(a.isFile()&&a.name.endsWith(".md")){let l=await mo(c,e,r);s.push(...l.filter(d=>n?!!d.globs:!d.globs))}}}catch{}return s}async function XL(t){let e=t,r=Vk(e).root;for(;e!==r;){try{let n=go(e,".git"),o=await $L(n);if(o.isDirectory()||o.isFile())return e}catch{}e=vi(e)}return null}async function YL(t,e){let r=[],n=new Set,s=await XL(t)??Vk(t).root,i=[],a=t;for(;i.push(a),!(a===s&&a!==t);){let c=vi(a);if(c===a)break;a=c}for(let c of i.reverse())r.push(...await mo(go(c,BL),"Project",n)),r.push(...await mo(vr(c),"Project",n)),r.push(...await Xk(ir(c),"Project",n,!1)),r.push(...await mo(go(c,qL),"Local",n));return e&&r.length>0&&e.invoke("instructions.loaded",{sessionId:"",source:t,fileCount:r.length}).catch(()=>{}),r}function ki(t){if(t.length===0)return"";let e="Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.",r=[],n=$d(t);n.length>0&&r.push(["## Active literal response requirements","The current instruction files contain hard requirements for exact response markers.","When responding, reproduce these literals exactly and do not omit them for brevity:",...n.map(o=>`- ${o.placement}: "${o.marker}"`)].join(`
|
|
568
569
|
`));for(let o of t){if(!o.content)continue;let s=o.type==="Project"?" (project instructions, checked into the codebase)":o.type==="Local"?" (user's private project instructions, not checked in)":" (user's private global instructions for all projects)";r.push(`Contents of ${o.path}${s}:
|
|
569
570
|
|
|
570
571
|
${o.content.trim()}`)}return r.length>0?`${e}
|
|
571
572
|
|
|
572
573
|
${r.join(`
|
|
573
574
|
|
|
574
|
-
`)}`:""}function $d(t){let e=new Map;for(let r of t){let n=r.content,o=/["'“”‘’]([^"'“”‘’\r\n]{2,100})["'“”‘’]/g,s;for(;(s=o.exec(n))!==null;){let i=s[1]?.trim();if(!i||!
|
|
575
|
+
`)}`:""}function $d(t){let e=new Map;for(let r of t){let n=r.content,o=/["'“”‘’]([^"'“”‘’\r\n]{2,100})["'“”‘’]/g,s;for(;(s=o.exec(n))!==null;){let i=s[1]?.trim();if(!i||!eO(i))continue;let a=JL(n,s.index,o.lastIndex);QL(a)&&e.set(i,{marker:i,placement:ZL(a)})}}return[...e.values()]}function JL(t,e,r){let n=[`
|
|
575
576
|
`,".","\u3002",";","\uFF1B"].map(a=>t.lastIndexOf(a,e)),o=Math.max(-1,...n)+1,s=[`
|
|
576
|
-
`,".","\u3002",";","\uFF1B"].map(a=>t.indexOf(a,r)).filter(a=>a>=0),i=s.length>0?Math.min(...s):t.length;return t.slice(o,i)}function Yk(t,e){let r=t;for(let n of e)
|
|
577
|
-
${n.marker}`:n.marker));return r}function
|
|
578
|
-
`):null},"memory INDEX.md may change between turns")]}),L=[...s].reverse().find(x=>x.role==="user");L&&Wa(o,L,l,r).catch(()=>{}),await this.mcpReady;let Pe=Ie(),X=new Set(Pe.map(x=>x.function.name)),Fe=hi([...Pe,...i.filter(x=>!X.has(x.function.name))],E);sO(this.permissionChecker,Fe);let nt=s;if(u&&s.length>0){let x=p?.activeProjectName,H=p?.projectNames.join(", ")??"";nt=[{role:"system",content:`[\u6CE8\u610F\uFF1A\u7528\u6237\u4ECE IM \u7AEF\u53D1\u6765\u6D88\u606F\uFF0C\u4F46\u684C\u9762\u7AEF\u5DF2\u8D85\u8FC730\u5206\u949F\u672A\u6D3B\u8DC3\uFF0C\u65E0\u6CD5\u786E\u5B9A\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u5DE5\u4F5C\u3002\u5F53\u524D\u6D3B\u8DC3\u9879\u76EE\uFF1A${x??"\u65E0"}\u3002\u53EF\u7528\u9879\u76EE\uFF1A${H||"\u65E0"}\u3002\u8BF7\u5728\u56DE\u590D\u5F00\u5934\u7B80\u77ED\u8BE2\u95EE\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u7EE7\u7EED\uFF0C\u4F8B\u5982\uFF1A"\u4F60\u60F3\u7EE7\u7EED\u5728\u300CXX\u300D\u9879\u76EE\u4E2D\u5DE5\u4F5C\u5417\uFF1F"]`},...s]}let Y=a?.desktopRecentContext;if(!u&&Y&&Y.length>0&&s.length>0){let x=s[s.length-1],H=x?.role==="user"&&typeof x.content=="string"?x.content:"";if(oO(H)){let $={role:"system",content:"[\u4EE5\u4E0B\u662F\u7528\u6237\u5728\u684C\u9762\u7AEF\u7684\u8FD1\u671F\u5BF9\u8BDD\uFF0C\u4F9B\u4F60\u53C2\u8003\u4EE5\u4FDD\u6301\u4E0A\u4E0B\u6587\u8FDE\u8D2F]"},gt={role:"system",content:"[\u684C\u9762\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u7ED3\u675F\uFF0C\u4EE5\u4E0B\u662F\u5F53\u524D IM \u7AEF\u7684\u5BF9\u8BDD]"};nt=[$,...Y,gt,...nt],this.log(`[continuation] injected ${Y.length} desktop messages as reference`)}}if(!Kt(o,l)?.title){let x=typeof L?.content=="string"?L.content:Array.isArray(L?.content)?L.content.filter(H=>H.type==="text").map(H=>H.text??"").join(""):"";if(x.trim()){let H=null,$=this.resolveClientForPurpose("smallModel");$&&(H=await ip(x,{transport:$.transport,apiKey:$.apiKey,model:$.model})),H||(H=x.trim().slice(0,20)+(x.trim().length>20?"\u2026":"")),await Qe(o,{title:H,projectId:d},l).catch(()=>{}),this.sendNotification("session.info",{sessionId:o,title:H,projectId:d}),this.log(`[title-gen] generated title for session ${o}: "${H}"`)}}for await(let x of v.run({turnId:r,sessionId:o,messages:nt,tools:Fe,systemPrompt:Le,config:h},g.signal)){let H=new Date().toISOString();if(li({event:x,turnId:r,now:H,host:this})){x.type==="tool_call"&&this.sessionState?.recordToolCall();continue}switch(x.type){case"start":break;case"end":{let $=Yk(x.content,S);if(this.sendNotification("turn.end",{turnId:x.turnId,content:$,usage:x.usage,model:x.model,provider:x.provider,item:{id:`${r}-end`,type:"message",role:"assistant",text:$,createdAt:H}}),x.usage&&this.sessionState){this.sessionState.addUsage(x.usage,x.model??this.currentModel);let gt=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:x.turnId,usage:x.usage,model:x.model??this.currentModel,sessionCostUSD:gt.totalInputTokens*3e-6+gt.totalOutputTokens*15e-6})}$&&(this.lastAssistantMessageForExtract=$,Wa(o,{role:"assistant",content:$},l,r).catch(()=>{}));break}case"error":if(this.sendNotification("turn.error",{turnId:x.turnId,error:{message:x.error,code:x.code}}),x.usage&&this.sessionState){this.sessionState.addUsage(x.usage,this.currentModel);let $=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:x.turnId,usage:x.usage,model:this.currentModel,sessionCostUSD:$.totalInputTokens*3e-6+$.totalOutputTokens*15e-6})}break;case"skill_instruction":this.sendNotification("turn.skill_instruction",{turnId:x.turnId,instruction:x.instruction}),Wg({instruction:x.instruction,eventTurnId:x.turnId,projectRoot:l,host:this});break}}if(this.log(`turn ${r} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState){sp(o,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:l,projectId:d,messageCount:s.length},l).catch(()=>{});let x=this.sessionState.createSnapshot();this.sendNotification("session.info",{sessionId:o,model:this.currentModel||void 0,cwd:l,turnCount:x.turnCount,projectId:d});let H=this.resolveClientForPurpose("smallModel");if(H&&ap(o,{sessionId:o,projectId:d??"",createdAt:"",lastActiveAt:"",turnCount:x.turnCount,messageCount:s.length},s,{transport:H.transport,apiKey:H.apiKey,model:H.model},l),jk({turnId:r,messages:s,client:this.resolveClientForPurpose("textGeneration"),sendNotification:($,gt)=>this.sendNotification($,gt)}),this.petRuntime.awardXp("turn.end"),this.petRuntime.reactAfterTurn(s),a?.sessionType==="group"&&this.sessionState){let $=this.sessionState.createSnapshot(),gt=Kt(o,l);gt&&Ly({...gt,turnCount:$.turnCount},l).then(br=>{br.split&&this.sendNotification("session-update",{sessionId:br.activeSessionId,projectId:d??"",title:"",type:"group"})}).catch(()=>{})}}}catch(h){if(g.signal.aborted)this.sendNotification("turn.error",{turnId:r,error:{message:"Turn aborted",code:"ABORTED"}});else{let v=h instanceof Error?h.message:String(h);this.sendNotification("turn.error",{turnId:r,error:{message:v,code:"INTERNAL_ERROR"}})}}finally{Nd(this,m)}}function Ye(t){return Si(t)}function mt(t){return Si(t)}function Bt(t){return Si(t)}function hr(t){return Si(t)}function Si(t){return t.multiAgentHandlerHost??t}function rR(t){return new Map([["initialize",e=>Tf.call(t,e)],["agent.ping",e=>Af.call(t,e)],["agent.health",e=>xf.call(t,e)],["agent.metrics",e=>Pf.call(t,e)],["agent.cancel",e=>Cf.call(t,e)],["thread.turn",e=>tR.call(t,e)],["memory.dream",e=>Yr.call(t,e)],["agent.abort",e=>Qk.call(t,e)],["tool.approval.response",e=>Zk.call(t,e)],["thread.user_response",e=>eR.call(t,e)],["thread.list",e=>jy.call(t,e)],["session.resume",e=>zy.call(t,e)],["thread.create",e=>Oy.call(t,e)],["session.getInfo",e=>Vy.call(t,e)],["session.create",e=>$y.call(t,e)],["session.resolve",e=>Uy.call(t,e)],["session.list",e=>Fy.call(t,e)],["session.get",e=>Hy.call(t,e)],["session.getMessages",e=>By.call(t,e)],["session.update",e=>qy.call(t,e)],["session.delete",e=>Wy.call(t,e)],["session.deleteAll",e=>Gy.call(t,e)],["session.archive",e=>Ky.call(t,e)],["memory.list",e=>Jf.call(t,e)],["memory.atlas",e=>Qf.call(t,e)],["memory.activity",e=>Zf.call(t,e)],["memory.observe",e=>eh.call(t,e)],["memory.propose",e=>th.call(t,e)],["memory.consolidate",e=>rh.call(t,e)],["memory.read",e=>nh.call(t,e)],["memory.write",e=>oh.call(t,e)],["memory.search",e=>sh.call(t,e)],["memory.delete",e=>ih.call(t,e)],["memory.update",e=>ah.call(t,e)],["tools.list",e=>mf.call(t,e)],["media.listModels",e=>Wf.call(t,e)],["media.cancel",e=>Gf.call(t,e)],["media.status",e=>Kf.call(t,e)],["media.stt",e=>zf.call(t,e)],["settings.listProviders",e=>rb.call(t,e)],["settings.addKey",e=>nb.call(t,e)],["settings.removeKey",e=>ob.call(t,e)],["settings.toggleKey",e=>sb.call(t,e)],["settings.toggleModel",e=>ib.call(t,e)],["settings.listModels",e=>ab.call(t,e)],["settings.setActiveModel",e=>cb.call(t,e)],["settings.getActiveModel",e=>lb.call(t,e)],["settings.getOverview",e=>db.call(t,e)],["settings.refreshModels",e=>ub.call(t,e)],["settings.validateKey",e=>pb.call(t,e)],["provider.list",e=>gf.call(t,e)],["config.get",e=>ff.call(t,e)],["config.update",e=>yf.call(t,e)],["config.tunables",e=>bf.call(t,e)],["config.updateTunable",e=>vf.call(t,e)],["community.getConsent",e=>Jg.call(t,e)],["community.setConsent",e=>Qg.call(t,e)],["community.listShared",e=>Zg.call(t,e)],["community.withdrawShared",e=>af.call(t,e)],["community.withdrawAllShared",e=>cf.call(t,e)],["community.listNotices",e=>lf.call(t,e)],["community.markNoticeRead",e=>df.call(t,e)],["community.listPublishAudit",e=>sf.call(t,e)],["community.resolveInstall",e=>ef.call(t,e)],["community.installResource",e=>tf.call(t,e)],["community.publishSkill",e=>rf.call(t,e)],["community.recordSignal",e=>nf.call(t,e)],["community.recordTelemetry",e=>of.call(t,e)],["todos.list",e=>kf.call(t,e)],["tasks.list",e=>Rf.call(t,e)],["tasks.cancel",e=>Sf.call(t,e)],["agents.scan",e=>eg.call(Ye(t),e)],["agents.list",e=>tg.call(Ye(t),e)],["agents.prompt",e=>mg.call(Ye(t),e)],["agents.config",e=>rg.call(Ye(t),e)],["agents.setConfig",e=>ng.call(Ye(t),e)],["agents.getConfig",e=>og.call(Ye(t),e)],["agents.removeConfig",e=>sg.call(Ye(t),e)],["agents.setGateway",e=>ig.call(Ye(t),e)],["agents.getGateway",e=>ag.call(Ye(t),e)],["agents.processes",e=>lg.call(Ye(t),e)],["agents.kill",e=>dg.call(Ye(t),e)],["agents.listConfigured",e=>cg.call(Ye(t),e)],["agents.getLog",e=>ug.call(Ye(t),e)],["agents.testConnection",e=>pg.call(Ye(t),e)],["solo.start",e=>Ob.call(hr(t),e)],["solo.status",e=>jb.call(hr(t),e)],["solo.cancel",e=>$b.call(hr(t),e)],["solo.select",e=>Ub.call(hr(t),e)],["solo.list",e=>Fb.call(hr(t),e)],["solo.delete",e=>Hb.call(hr(t),e)],["solo.message",e=>Bb.call(hr(t),e)],["solo.evaluate",e=>qb.call(hr(t),e)],["product.plan",e=>Eh.call(mt(t),e)],["product.confirm",e=>_h.call(mt(t),e)],["product.message",e=>Mh.call(mt(t),e)],["product.create",e=>Dh.call(mt(t),e)],["product.resume",e=>Nh.call(mt(t),e)],["product.pause",e=>Lh.call(mt(t),e)],["product.checkpoint",e=>Oh.call(mt(t),e)],["product.status",e=>jh.call(mt(t),e)],["product.list",e=>$h.call(mt(t),e)],["product.delete",e=>Uh.call(mt(t),e)],["product.cancel",e=>Fh.call(mt(t),e)],["product.rollback",e=>Hh.call(mt(t),e)],["workflow.create",e=>my.call(Bt(t),e)],["workflow.get",e=>gy.call(Bt(t),e)],["workflow.describe",e=>fy.call(Bt(t),e)],["workflow.patch",e=>hy.call(Bt(t),e)],["workflow.run",e=>yy.call(Bt(t),e)],["workflow.setActive",e=>by.call(Bt(t),e)],["workflow.list",e=>vy.call(Bt(t),e)],["workflow.delete",e=>ky.call(Bt(t),e)],["workflow.onImMessage",e=>Ry.call(Bt(t),e)],["workflow.onWebhook",e=>Sy.call(Bt(t),e)],["project.create",e=>wy.call(t,e)],["project.list",e=>Ty.call(t,e)],["project.delete",e=>Ay.call(t,e)],["project.purgeAll",e=>xy.call(t,e)],["project.rename",e=>Py.call(t,e)],["project.archive",e=>Cy.call(t,e)],["project.unarchive",e=>Iy.call(t,e)],["project.update",e=>_y.call(t,e)],["project.archiveByGroup",e=>Ey.call(t,e)],["session.switchProject",e=>Xy.call(t,e)],["session.focus",e=>Jy.call(t,e)],["session.moveToProject",e=>Qy.call(t,e)],["session.getState",e=>Yy.call(t,e)],["files.list",e=>_f.call(t,e)],["files.create",e=>Mf.call(t,e)],["files.rename",e=>Df.call(t,e)],["files.delete",e=>Nf.call(t,e)],["files.gitStatus",e=>Lf.call(t,e)],["instructions.list",e=>Of.call(t,e)],["instructions.read",e=>jf.call(t,e)],["instructions.write",e=>$f.call(t,e)],["instructions.delete",e=>Uf.call(t,e)],["plans.list",e=>Ff.call(t,e)],["skills.list",e=>Rb.call(t,e)],["skills.activate",e=>Sb.call(t,e)],["skills.deactivate",e=>wb.call(t,e)],["skills.delete",e=>Tb.call(t,e)],["skills.promote",e=>Ab.call(t,e)],["skills.stats",e=>xb.call(t,e)],["skills.pin",e=>Pb.call(t,e)],["skills.unpin",e=>Cb.call(t,e)],["skills.curator",e=>Ib.call(t,e)],["skills.lifecycle",e=>Eb.call(t,e)],["pet.hatch",e=>fh.call(t,e)],["pet.interact",e=>hh.call(t,e)],["pet.status",e=>yh.call(t,e)],["pet.forge",e=>bh.call(t,e)],["pet.confirm_response",e=>ch.call(t,e)]])}import{randomUUID as nR}from"node:crypto";import*as oR from"node:path";D();async function sR(t,e){t.log(`[acp] x/dream: session=${e.sessionId}`);let r=t.resolveClientForPurpose("textGeneration");if(!r)return{ok:!1,summary:"No LLM transport configured for dream"};let n=F(),o={jsonrpc:"2.0",id:`acp-dream-${nR().slice(0,8)}`,method:"memory.dream",params:{turnId:`dream-${nR().slice(0,8)}`,sessionId:e.sessionId||t.currentSessionId,config:{memoryRoot:e.config?.memoryRoot||n,transcriptDir:e.config?.transcriptDir||oR.join(n,"agent-logs"),model:r.model,apiKey:r.apiKey,...e.config}}};return await Yr.call(t,o),{ok:!0,summary:"Dream consolidation triggered"}}async function iR(t,e){t.log("[acp] x/solo.start");let r=Ve.call(t),n=await r.start(e);return r.getStatus(n)}async function aR(t,e){t.log("[acp] x/solo.status");let r=e.soloId;if(!r)return t.soloEvaluator?t.soloEvaluator.listSessions():[];let o=Ve.call(t).getStatus(r);if(!o)throw new Error(`Solo session ${r} not found`);return o}async function cR(t,e){return t.log("[acp] x/solo.select"),{ok:!0,mergedBranch:await Ve.call(t).select(e)}}async function lR(t,e){t.log("[acp] x/solo.cancel");let r=Ve.call(t),n=e.soloId;return await r.cancel(n),{ok:!0}}async function dR(t,e){return t.log("[acp] x/solo.subscribe"),{ok:!0,soloId:e.soloId}}async function uR(t,e){t.log("[acp] x/solo.message");let r=Ve.call(t),{soloId:n,agentId:o,content:s,agentIndex:i}=e;return r.message(n,o,s,i)}async function pR(t,e){t.log("[acp] x/solo.evaluate");let r=Ve.call(t),{soloId:n,evaluatorAgentId:o,evaluatorIndex:s}=e;return r.triggerEvaluation(n,o,s)}async function mR(t){return t.log("[acp] x/agents.list"),Dc()}async function gR(t,e){return t.log("[acp] x/product.create"),{productId:await ye.call(t).create(e)}}async function fR(t,e){return t.log("[acp] x/product.plan"),_r.call(t).plan(e)}async function hR(t,e){t.log("[acp] x/product.confirm");let r=_r.call(t),n=e,o=await r.confirm(n),s=r.getSession(n.productId);return s&&await ye.call(t).create({name:s.plan?.name??s.goal.slice(0,50),cwd:s.cwd,instances:n.instances,tasks:n.tasks,budget:n.budget}),o}async function yR(t,e){t.log("[acp] x/product.message");let r=_r.call(t),n=e;return r.message(n.productId,n.content)}async function bR(t,e){t.log("[acp] x/product.resume");let r=ye.call(t),n=e.productId;return await r.resume(n,t.getActiveProjectRoot()),{ok:!0}}async function vR(t,e){t.log("[acp] x/product.status");let r=e.productId;if(!t.productOrchestrator)return r?null:[];if(!r)return t.productOrchestrator.list(t.getActiveProjectRoot());let n=t.productOrchestrator.getStatus(r);if(!n)throw new Error(`Product session ${r} not found`);return n}async function kR(t,e){t.log("[acp] x/product.pause");let r=ye.call(t),n=e.productId;return await r.pause(n),{ok:!0}}async function RR(t,e){t.log("[acp] x/product.cancel");let r=ye.call(t),n=e.productId;return await r.delete(n),{ok:!0}}async function SR(t,e){t.log("[acp] x/product.rollback");let r=ye.call(t),n=e.productId,o=e.checkpointId??"latest";return await r.rollback(n,o),{ok:!0}}async function wR(t,e){return t.log("[acp] x/product.subscribe"),{ok:!0,productId:e.productId}}async function TR(t,e){let r=e.agentType,n=e.prompt,o=e.maxTurns;if(!n)throw new Error("Missing required param: prompt");if(!r)throw new Error("Missing required param: agentType");let s=Un(r);if(!s)throw new Error(`Unknown agent type: ${r}`);let i=t.resolveClientForPurpose("textGeneration");if(!i)throw new Error("No LLM provider configured; send a prompt first to configure the model");if(t.log(`[acp] x/team.delegate: agent=${r}, maxTurns=${o??s.maxTurns}`),ut.isTeamBudgetExceeded())return{ok:!1,agentType:r,output:void 0,error:ut.teamBudgetExceededError(),tokensUsed:0};let a={invoke:async()=>({result:"Tool execution not available in delegated mode"})},c={info:p=>t.log(`[delegate:${r}] ${p}`),warn:p=>t.log(`[delegate:${r}] WARN: ${p}`),error:p=>t.log(`[delegate:${r}] ERROR: ${p}`),debug:p=>t.log(`[delegate:${r}] ${p}`)},l=await Wr({promptMessages:[{role:"user",content:n}],tools:[],transport:i.transport,toolInvoker:a,createAgentRunner:Xr,apiKey:i.apiKey,model:i.model,log:c,forkLabel:`team-delegate-${r}`,maxTurns:o??s.maxTurns,parentSignal:t.activeTurn?.signal,parentDepth:0}),d=l.events.filter(p=>p.type==="end"&&"content"in p).map(p=>p.content??"").join("")||l.events.filter(p=>p.type==="delta"&&"text"in p).map(p=>p.text).join(""),u=l.totalUsage.inputTokens+l.totalUsage.outputTokens;return ut.recordForkTokens(u),{ok:l.ok,agentType:r,output:d||void 0,error:l.error,tokensUsed:u}}import{randomUUID as AR}from"node:crypto";async function xR(t,e,r){let n=e.clientInfo?.name??"unknown";t.log(`[acp] initialize: host=${n}`);let o={extendedEvents:!0,extendedMethods:!0,orchestration:!0,configOptions:[{name:"model",type:"string",description:"LLM model identifier"},{name:"provider",type:"string",description:"LLM provider identifier"},{name:"maxRounds",type:"number",description:"Max tool loop rounds"},{name:"temperature",type:"number",description:"Sampling temperature"}]};return t.ensureDefaultProject(),{protocolVersion:1,agentInfo:{name:"qlogicagent",version:r},agentCapabilities:o}}async function PR(t,e){let r=e.sessionId??AR();return t.log(`[acp] session/new: id=${r}`),t.currentSessionId=r,t.sessionState=new pr(r),t.sessionTaskDomain=void 0,t.memoryPrefetchState=ht(),e.cwd&&typeof e.cwd=="string"&&t.setActiveWorkdir(e.cwd),t.enableIdleDream(),{sessionId:r}}async function CR(t,e){let r=AR(),n=e.sessionId,o=e.prompt.map(a=>a.type==="text"?a.text:`[${a.type}]`).join("");if(!o.trim())return t.sendNotification("turn.start",{turnId:r,model:t.currentModel||void 0}),t.sendNotification("turn.end",{turnId:r,content:"",item:{id:`${r}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),{stopReason:"end_turn"};let s=t.sessionHistory.appendAcpUserMessage(n,o),i=await lO(t,r,n,[...s]);return i.content&&t.sessionHistory.appendAcpAssistantMessage(n,i.content),i}async function lO(t,e,r,n){let o=new AbortController;t.activeTurn=o,t.sendNotification("turn.start",{turnId:e,model:t.currentModel||void 0});try{let s={model:t.currentModel||void 0,provider:t.currentProvider||void 0,apiKey:t.currentApiKey||void 0,baseUrl:t.currentBaseUrl||void 0},i=fi(n);i.requiresFreshTool&&(s.toolChoice="required");let a=t.resolveAgent(s);if(!a)return t.sendNotification("turn.delta",{turnId:e,text:"Error: No LLM provider configured. Configure via ~/.qlogicagent/settings.json or pass provider/apiKey in session config.",item:{id:`${e}-err`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),t.sendNotification("turn.end",{turnId:e,content:"",item:{id:`${e}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),t.activeTurn=null,{stopReason:"end_turn"};await t.mcpReady;let c=hi(Ie(),i),l=t.getActiveProjectRoot(),d=await Ri(l,t.currentHooks??void 0),u=d.length>0?ki(d):void 0,p=yi(i),m=await ai({instructionBlock:u,sections:[pi(l),gi(),mi(),...p?[p]:[]]}),g,f="end_turn",h="";for await(let v of a.run({turnId:e,sessionId:r,messages:n,tools:c,systemPrompt:m,config:s},o.signal)){let b=new Date().toISOString();if(!li({event:v,turnId:e,now:b,host:t}))switch(v.type){case"start":break;case"end":v.usage&&(g={inputTokens:v.usage.inputTokens??0,outputTokens:v.usage.outputTokens??0,cacheReadTokens:v.usage.cacheRead,cacheWriteTokens:v.usage.cacheWrite}),h=v.content??"",t.sendNotification("turn.end",{turnId:v.turnId,content:v.content,usage:v.usage,model:v.model,provider:v.provider,item:{id:`${e}-end`,type:"message",role:"assistant",text:v.content,createdAt:b}});break;case"error":f="end_turn",t.sendNotification("turn.error",{turnId:v.turnId,error:{message:v.error,code:v.code}});break}}return t.activeTurn=null,{stopReason:f,usage:g,content:h}}catch(s){t.activeTurn=null;let i=s instanceof Error?s.message:String(s);return t.log(`[acp] runAcpTurn error: ${i}`),t.sendNotification("turn.error",{turnId:e,error:{message:i,code:"INTERNAL_ERROR"}}),{stopReason:"end_turn"}}}async function IR(t,e){t.log(`[acp] session/end: id=${e.sessionId}`),t.sessionHistory.clearAcpSession(e.sessionId),t.currentSessionId===e.sessionId&&(t.cancelIdleDreamTimer(),t.currentHooks&&await t.currentHooks.invoke("session.ended",{sessionId:e.sessionId}).catch(()=>{}),t.currentSessionId="",t.sessionState=null,t.disposeSessionRuntime?.())}async function ER(t,e){let r=e.configId??e.option;t.log(`[acp] session/set_config: ${r}=${JSON.stringify(e.value)}`);let n=typeof e.value=="string"?e.value:"";switch(r){case"model":t.currentModel=n;break;case"provider":t.currentProvider=n;break;case"apiKey":t.currentApiKey=n;break;case"baseUrl":t.currentBaseUrl=n;break}}async function _R(t,e,r){t.log(`[acp] session/set_model: ${r} (note: model is managed by ModelRegistry, this is a hint only)`),r&&(t.currentModel=r)}async function MR(t,e,r){t.log(`[acp] session/set_mode: ${r}`)}function DR(t,e,r=t){return{handleAcpInitialize:n=>xR(t,n,e),handleAcpSessionNew:n=>PR(t,n),handleAcpSessionPrompt:n=>CR(t,n),handleAcpSessionEnd:n=>IR(t,n),handleAcpSessionSetConfig:n=>ER(t,n),handleAcpSessionSetModel:(n,o)=>_R(t,n,o),handleAcpSessionSetMode:(n,o)=>MR(t,n,o),handleAcpPermissionResponse:(n,o)=>{t.log(`[acp] permission response: ${n} -> ${o}`),t.permissionChecker?.resolveApproval({approvalId:n,decision:o==="allow"||o==="allowAlways"?"approved":"denied"})},handleAcpAbort:async n=>{t.log(`[acp] abort: session=${n.sessionId}`),t.activeTurn&&(t.activeTurn.abort(),t.activeTurn=null)},handleAcpDream:n=>sR(r,n),handleAcpAgentsList:()=>mR(r),handleAcpSoloStart:n=>iR(r,n),handleAcpSoloStatus:n=>aR(r,n),handleAcpSoloSelect:n=>cR(r,n),handleAcpSoloCancel:n=>lR(r,n),handleAcpSoloSubscribe:n=>dR(r,n),handleAcpSoloMessage:n=>uR(r,n),handleAcpSoloEvaluate:n=>pR(r,n),handleAcpProductCreate:n=>gR(r,n),handleAcpProductPlan:n=>fR(r,n),handleAcpProductConfirm:n=>hR(r,n),handleAcpProductMessage:n=>yR(r,n),handleAcpProductPause:n=>kR(r,n),handleAcpProductResume:n=>bR(r,n),handleAcpProductCancel:n=>RR(r,n),handleAcpProductRollback:n=>SR(r,n),handleAcpProductStatus:n=>vR(r,n),handleAcpProductSubscribe:n=>wR(r,n),handleAcpTeamDelegate:n=>TR(r,n)}}import{resolve as uO}from"node:path";var wi=class{constructor(e){this.mediaPersistence=e}mediaPersistence;activeWorkdir=null;getActiveProjectRoot(){if(this.activeWorkdir)return this.activeWorkdir;let e=oe();return e?.workspaceDir?e.workspaceDir:process.cwd()}setActiveWorkdir(e){let r=uO(e);this.activeWorkdir!==r&&(this.activeWorkdir=r,Ak(r),this.mediaPersistence.setProjectDir(r))}resolveProjectDir(e){if(e)return $t(e)??void 0}};import{createRequire as CO}from"node:module";D();import*as Ai from"node:fs";import*as OR from"node:path";import{randomUUID as fo}from"node:crypto";var pO=`
|
|
577
|
+
`,".","\u3002",";","\uFF1B"].map(a=>t.indexOf(a,r)).filter(a=>a>=0),i=s.length>0?Math.min(...s):t.length;return t.slice(o,i)}function Yk(t,e){let r=t;for(let n of e)tO(n.marker)&&(r.includes(n.marker)||(n.placement==="prefix"?r=r.trim().length>0?`${n.marker} ${r}`:n.marker:r=r.trim().length>0?`${r.trimEnd()}
|
|
578
|
+
${n.marker}`:n.marker));return r}function QL(t){let e=t.toLowerCase();return e.includes("every response")||e.includes("all responses")||e.includes("always")||t.includes("\u6240\u6709\u56DE\u590D")||t.includes("\u6BCF\u6B21\u56DE\u590D")||t.includes("\u6BCF\u4E2A\u56DE\u590D")||t.includes("\u6C38\u8FDC")?e.includes("must")||e.includes("required")||e.includes("exact")||t.includes("\u5FC5\u987B")||t.includes("\u52A1\u5FC5")||t.includes("\u786C\u6027\u8981\u6C42"):!1}function ZL(t){let e=t.toLowerCase(),r=bi(e,["start with","begin with"])+bi(t,["\u5F00\u5934","\u5FC5\u987B\u4EE5"]),n=bi(e,["end with","append","at the end"])+bi(t,["\u672B\u5C3E","\u7ED3\u5C3E","\u7ED3\u675F\u6807\u8BB0"]);return r>=0||n>=0?r>n?"prefix":"suffix":"include"}function bi(t,e){let r=-1;for(let n of e){let o=t.lastIndexOf(n);o>r&&(r=o)}return r}function eO(t){let e=t.trim();return e.length<2||e.length>100||/https?:\/\//i.test(e)?!1:/[A-Z0-9_\-[\]—-]/.test(e)}function tO(t){return/[A-Z\[\]—-]/.test(t)}async function Ri(t,e){return YL(t,e)}function Jk(){}var oO=[/继续(桌面|电脑|刚才|上次|之前)的/,/接着(桌面|电脑|刚才|上次|之前)的/,/刚才(那个|那件|说的|聊的|做的)/,/上次(说到|聊到|做到|讲到)/,/桌面(端|上)?(那个|那边|的任务|的对话|在做)/,/电脑(端|上)?(那个|那边|的任务|的对话|在做)/,/之前(那个|在做的|讨论的|说的)/,/帮我继续/,/接着(做|干|搞|写|改)/,/continue (from |where |the )?desktop/i,/pick up where/i,/what were we (doing|working on|talking about)/i,/continue (the |our )?(last |previous )?(task|conversation|chat)/i];function sO(t){return!t||t.length<3?!1:oO.some(e=>e.test(t))}function Qk(t){let e=t.params?.turnId??"";this.log(`abort requested for turn ${e}`),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),t.id!==void 0&&this.sendResponse(t.id,{aborted:!0})}function Zk(t){let e=t.params;if(!e)return;let r=e.approvalId,n=e.decision;if(!r||!n){this.log("[warn] tool.approval.response missing approvalId or decision");return}let o={approvalId:r,decision:aO(n)?"approved":"denied",updatedInput:e.updatedInput,permissionUpdate:cO(e,n)};this.permissionChecker&&this.permissionChecker.resolveApproval(o),t.id!==void 0&&this.sendResponse(t.id,{received:!0})}function iO(t,e){t?.setToolMeta?.(e)}function aO(t){return t==="approved"||t==="allow"||t==="allow-once"||t==="allow-session"||t==="allow-always"}function cO(t,e){if(t.permissionUpdate)return t.permissionUpdate;if(e!=="allow-always")return;let r=t.toolName;if(!(typeof r!="string"||!r))return{pattern:r,behavior:"allow",scope:"persistent",description:`Always allow ${r}`}}function eR(t){let e=t.params,r=e?.requestId;if(!r){this.log("[warn] thread.user_response missing requestId"),t.id!==void 0&&this.sendResponse(t.id,{received:!1});return}let n=this.pendingAskUser.get(r);if(!n){this.log(`[warn] thread.user_response: no pending request ${r}`),t.id!==void 0&&this.sendResponse(t.id,{received:!1});return}if(this.pendingAskUser.delete(r),e?.declined===!0)n.resolve(null);else{let s=e?.answers??{};n.resolve(s)}t.id!==void 0&&this.sendResponse(t.id,{received:!0})}async function tR(t){let e=t.params??{},r=e.turnId??nO(),n=typeof this.currentTurnId=="string"?this.currentTurnId:void 0;this.currentTurnId=r;let o=e.sessionId,s=e.messages??[],i=e.tools??[],a=e.config;t.id!==void 0&&this.sendResponse(t.id,{accepted:!0,turnId:r}),s=this.sessionHistory.withResumedHistory(o,s);let c=Lk({config:a,sessionId:o,host:this}),{sessionProjectRoot:l,sessionProjectId:d,projectHintStale:u,staleProjectHintContext:p}=c;ci({host:this,config:a,turnId:r}),Ek(this),this.activeTurn&&n&&n!==r&&this.sendNotification("turn.error",{turnId:n,error:{message:"Turn aborted by a newer turn",code:"ABORTED"}});let m=await Mk(this,o),g=m.abortController;this.log(`turn ${r} starting (session: ${o})`),this.sendNotification("turn.start",{turnId:r,model:a?.model??(this.currentModel||void 0),provider:a?.provider||void 0,projectId:d});let f=[...s].reverse().find(h=>h.role==="user");if(this.lastUserMessageForAutoExtract=typeof f?.content=="string"?f.content:void 0,!f||!String(f.content??"").trim()){this.sendNotification("turn.end",{turnId:r,content:"",item:{id:`${r}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),Nd(this,m);return}try{let h={provider:a?.provider,model:a?.model,apiKey:a?.apiKey,baseUrl:a?.baseUrl,maxRounds:a?.maxRounds,temperature:a?.temperature,contextWindowTokens:a?.contextWindowTokens,maxOutputTokens:a?.maxOutputTokens,modelMaxOutputTokens:a?.modelMaxOutputTokens,maxConcurrentTools:a?.maxConcurrentTools,mediaProviders:a?.mediaProviders,reasoning:a?.reasoning,promptCacheKey:a?.promptCacheKey,promptCacheRetention:a?.promptCacheRetention,serviceTier:a?.serviceTier,openaiBuiltinTools:a?.openaiBuiltinTools,maxToolCalls:a?.maxToolCalls,parallelToolCalls:a?.parallelToolCalls,textVerbosity:a?.textVerbosity,toolChoice:a?.toolChoice,mcpServers:a?.mcpServers,fallbackModel:M().resolveModelForPurpose("smallModel")??void 0};{let x=h.provider??"",H=h.model??"";x&&H&&M().getModelInfo(x,H)?.streamRequired&&(h.streamRequired=!0)}let v=this.resolveAgent(h);if(this.permissionChecker?.ruleEngineRef&&a?.permissions){let x=Ik(this.permissionChecker.ruleEngineRef,a.permissions);x.mode}if(!v){this.sendNotification("turn.error",{turnId:r,error:{message:"No LLM provider configured. Provide provider/model/apiKey in agent.turn config, or set DEEPSEEK_API_KEY / OPENAI_API_KEY / ANTHROPIC_API_KEY environment variable.",code:"NO_PROVIDER"}});return}let b,S=[],T=a?.workdir??this.getActiveProjectRoot();this.setActiveWorkdir(T);try{let x=await Ri(T,this.currentHooks??void 0);x.length>0&&(b=ki(x),S=$d(x))}catch{}let R=s.filter(x=>x.role==="user").map(x=>typeof x.content=="string"?x.content:"").join(" "),{domain:P,source:I}=Hk({cwd:T,hostOverride:a?.taskDomain,sessionDomain:this.sessionTaskDomain,userText:R});this.sessionTaskDomain=P,I==="auto-detect"&&qk(R,P)&&Bk(T,P);let E=fi(s),N=yi(E);!h.toolChoice&&E.requiresFreshTool&&(h.toolChoice="required");let xe=this.projectMemoryStoreFactory.getRootPath(T);if(!this.memdir||this.memdir.getRootPath()!==xe){let x=this.projectMemoryStoreFactory.create(T);x.ensureInitialized(),this.memdir=x}let k=this.memdir,Q;if(o){let x=zt(o,l);x?.carryoverSummary&&(Q=x.carryoverSummary)}let Le=await ai({basePrompt:a?.systemPrompt,instructionBlock:b,customSystemPrompt:a?.customSystemPrompt,appendSystemPrompt:a?.appendSystemPrompt,sections:[pi(T),gi(),Gk(P),mi(),...N?[N]:[],...Q?[Bt("carryover",()=>Q,"carryover from predecessor session")]:[],Bt("memory",()=>{if(!k)return null;let x=k.getIndexForPrompt();return x?["## Your Memory (project-level notes \u2014 always visible)","",x,"","<!-- Use memory(action='remember') for user-level long-term facts/preferences that persist across projects.>","<!-- Use memory(action='add') for project-specific notes that should be visible every turn.>"].join(`
|
|
579
|
+
`):null},"memory INDEX.md may change between turns")]}),L=[...s].reverse().find(x=>x.role==="user");L&&Wa(o,L,l,r).catch(()=>{}),await this.mcpReady;let Pe=Ie(),X=new Set(Pe.map(x=>x.function.name)),Fe=hi([...Pe,...i.filter(x=>!X.has(x.function.name))],E);iO(this.permissionChecker,Fe);let nt=s;if(u&&s.length>0){let x=p?.activeProjectName,H=p?.projectNames.join(", ")??"";nt=[{role:"system",content:`[\u6CE8\u610F\uFF1A\u7528\u6237\u4ECE IM \u7AEF\u53D1\u6765\u6D88\u606F\uFF0C\u4F46\u684C\u9762\u7AEF\u5DF2\u8D85\u8FC730\u5206\u949F\u672A\u6D3B\u8DC3\uFF0C\u65E0\u6CD5\u786E\u5B9A\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u5DE5\u4F5C\u3002\u5F53\u524D\u6D3B\u8DC3\u9879\u76EE\uFF1A${x??"\u65E0"}\u3002\u53EF\u7528\u9879\u76EE\uFF1A${H||"\u65E0"}\u3002\u8BF7\u5728\u56DE\u590D\u5F00\u5934\u7B80\u77ED\u8BE2\u95EE\u7528\u6237\u60F3\u5728\u54EA\u4E2A\u9879\u76EE\u4E2D\u7EE7\u7EED\uFF0C\u4F8B\u5982\uFF1A"\u4F60\u60F3\u7EE7\u7EED\u5728\u300CXX\u300D\u9879\u76EE\u4E2D\u5DE5\u4F5C\u5417\uFF1F"]`},...s]}let Y=a?.desktopRecentContext;if(!u&&Y&&Y.length>0&&s.length>0){let x=s[s.length-1],H=x?.role==="user"&&typeof x.content=="string"?x.content:"";if(sO(H)){let $={role:"system",content:"[\u4EE5\u4E0B\u662F\u7528\u6237\u5728\u684C\u9762\u7AEF\u7684\u8FD1\u671F\u5BF9\u8BDD\uFF0C\u4F9B\u4F60\u53C2\u8003\u4EE5\u4FDD\u6301\u4E0A\u4E0B\u6587\u8FDE\u8D2F]"},gt={role:"system",content:"[\u684C\u9762\u5BF9\u8BDD\u4E0A\u4E0B\u6587\u7ED3\u675F\uFF0C\u4EE5\u4E0B\u662F\u5F53\u524D IM \u7AEF\u7684\u5BF9\u8BDD]"};nt=[$,...Y,gt,...nt],this.log(`[continuation] injected ${Y.length} desktop messages as reference`)}}if(!zt(o,l)?.title){let x=typeof L?.content=="string"?L.content:Array.isArray(L?.content)?L.content.filter(H=>H.type==="text").map(H=>H.text??"").join(""):"";if(x.trim()){let H=null,$=this.resolveClientForPurpose("smallModel");$&&(H=await ip(x,{transport:$.transport,apiKey:$.apiKey,model:$.model})),H||(H=x.trim().slice(0,20)+(x.trim().length>20?"\u2026":"")),await Qe(o,{title:H,projectId:d},l).catch(()=>{}),this.sendNotification("session.info",{sessionId:o,title:H,projectId:d}),this.log(`[title-gen] generated title for session ${o}: "${H}"`)}}for await(let x of v.run({turnId:r,sessionId:o,messages:nt,tools:Fe,systemPrompt:Le,config:h},g.signal)){let H=new Date().toISOString();if(li({event:x,turnId:r,now:H,host:this})){x.type==="tool_call"&&this.sessionState?.recordToolCall();continue}switch(x.type){case"start":break;case"end":{let $=Yk(x.content,S);if(this.sendNotification("turn.end",{turnId:x.turnId,content:$,usage:x.usage,model:x.model,provider:x.provider,item:{id:`${r}-end`,type:"message",role:"assistant",text:$,createdAt:H}}),x.usage&&this.sessionState){this.sessionState.addUsage(x.usage,x.model??this.currentModel);let gt=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:x.turnId,usage:x.usage,model:x.model??this.currentModel,sessionCostUSD:gt.totalInputTokens*3e-6+gt.totalOutputTokens*15e-6})}$&&(this.lastAssistantMessageForExtract=$,Wa(o,{role:"assistant",content:$},l,r).catch(()=>{}));break}case"error":if(this.sendNotification("turn.error",{turnId:x.turnId,error:{message:x.error,code:x.code}}),x.usage&&this.sessionState){this.sessionState.addUsage(x.usage,this.currentModel);let $=this.sessionState.createSnapshot();this.sendNotification("turn.usage_update",{turnId:x.turnId,usage:x.usage,model:this.currentModel,sessionCostUSD:$.totalInputTokens*3e-6+$.totalOutputTokens*15e-6})}break;case"skill_instruction":this.sendNotification("turn.skill_instruction",{turnId:x.turnId,instruction:x.instruction}),Wg({instruction:x.instruction,eventTurnId:x.turnId,projectRoot:l,host:this});break}}if(this.log(`turn ${r} completed`),this.sessionState?.recordTurnCompleted(),this.sessionState){sp(o,this.sessionState.createSnapshot(),{model:this.currentModel,cwd:l,projectId:d,messageCount:s.length},l).catch(()=>{});let x=this.sessionState.createSnapshot();this.sendNotification("session.info",{sessionId:o,model:this.currentModel||void 0,cwd:l,turnCount:x.turnCount,projectId:d});let H=this.resolveClientForPurpose("smallModel");if(H&&ap(o,{sessionId:o,projectId:d??"",createdAt:"",lastActiveAt:"",turnCount:x.turnCount,messageCount:s.length},s,{transport:H.transport,apiKey:H.apiKey,model:H.model},l),jk({turnId:r,messages:s,client:this.resolveClientForPurpose("textGeneration"),sendNotification:($,gt)=>this.sendNotification($,gt)}),this.petRuntime.awardXp("turn.end"),this.petRuntime.reactAfterTurn(s),a?.sessionType==="group"&&this.sessionState){let $=this.sessionState.createSnapshot(),gt=zt(o,l);gt&&Ly({...gt,turnCount:$.turnCount},l).then(br=>{br.split&&this.sendNotification("session-update",{sessionId:br.activeSessionId,projectId:d??"",title:"",type:"group"})}).catch(()=>{})}}}catch(h){if(g.signal.aborted)this.sendNotification("turn.error",{turnId:r,error:{message:"Turn aborted",code:"ABORTED"}});else{let v=h instanceof Error?h.message:String(h);this.sendNotification("turn.error",{turnId:r,error:{message:v,code:"INTERNAL_ERROR"}})}}finally{Nd(this,m)}}function Ye(t){return Si(t)}function mt(t){return Si(t)}function qt(t){return Si(t)}function hr(t){return Si(t)}function Si(t){return t.multiAgentHandlerHost??t}function rR(t){return new Map([["initialize",e=>Tf.call(t,e)],["agent.ping",e=>Af.call(t,e)],["agent.health",e=>xf.call(t,e)],["agent.metrics",e=>Pf.call(t,e)],["agent.cancel",e=>Cf.call(t,e)],["thread.turn",e=>tR.call(t,e)],["memory.dream",e=>Yr.call(t,e)],["agent.abort",e=>Qk.call(t,e)],["tool.approval.response",e=>Zk.call(t,e)],["thread.user_response",e=>eR.call(t,e)],["thread.list",e=>jy.call(t,e)],["session.resume",e=>zy.call(t,e)],["thread.create",e=>Oy.call(t,e)],["session.getInfo",e=>Vy.call(t,e)],["session.create",e=>$y.call(t,e)],["session.resolve",e=>Uy.call(t,e)],["session.list",e=>Fy.call(t,e)],["session.get",e=>Hy.call(t,e)],["session.getMessages",e=>By.call(t,e)],["session.update",e=>qy.call(t,e)],["session.delete",e=>Wy.call(t,e)],["session.deleteAll",e=>Gy.call(t,e)],["session.archive",e=>Ky.call(t,e)],["memory.list",e=>Jf.call(t,e)],["memory.atlas",e=>Qf.call(t,e)],["memory.activity",e=>Zf.call(t,e)],["memory.observe",e=>eh.call(t,e)],["memory.propose",e=>th.call(t,e)],["memory.consolidate",e=>rh.call(t,e)],["memory.read",e=>nh.call(t,e)],["memory.write",e=>oh.call(t,e)],["memory.search",e=>sh.call(t,e)],["memory.delete",e=>ih.call(t,e)],["memory.update",e=>ah.call(t,e)],["tools.list",e=>mf.call(t,e)],["media.listModels",e=>Wf.call(t,e)],["media.cancel",e=>Gf.call(t,e)],["media.status",e=>Kf.call(t,e)],["media.stt",e=>zf.call(t,e)],["settings.listProviders",e=>rb.call(t,e)],["settings.addKey",e=>nb.call(t,e)],["settings.removeKey",e=>ob.call(t,e)],["settings.toggleKey",e=>sb.call(t,e)],["settings.toggleModel",e=>ib.call(t,e)],["settings.listModels",e=>ab.call(t,e)],["settings.setActiveModel",e=>cb.call(t,e)],["settings.getActiveModel",e=>lb.call(t,e)],["settings.getOverview",e=>db.call(t,e)],["settings.refreshModels",e=>ub.call(t,e)],["settings.validateKey",e=>pb.call(t,e)],["provider.list",e=>gf.call(t,e)],["config.get",e=>ff.call(t,e)],["config.update",e=>yf.call(t,e)],["config.tunables",e=>bf.call(t,e)],["config.updateTunable",e=>vf.call(t,e)],["community.getConsent",e=>Jg.call(t,e)],["community.setConsent",e=>Qg.call(t,e)],["community.listShared",e=>Zg.call(t,e)],["community.withdrawShared",e=>af.call(t,e)],["community.withdrawAllShared",e=>cf.call(t,e)],["community.listNotices",e=>lf.call(t,e)],["community.markNoticeRead",e=>df.call(t,e)],["community.listPublishAudit",e=>sf.call(t,e)],["community.resolveInstall",e=>ef.call(t,e)],["community.installResource",e=>tf.call(t,e)],["community.publishSkill",e=>rf.call(t,e)],["community.recordSignal",e=>nf.call(t,e)],["community.recordTelemetry",e=>of.call(t,e)],["todos.list",e=>kf.call(t,e)],["tasks.list",e=>Rf.call(t,e)],["tasks.cancel",e=>Sf.call(t,e)],["agents.scan",e=>eg.call(Ye(t),e)],["agents.list",e=>tg.call(Ye(t),e)],["agents.prompt",e=>mg.call(Ye(t),e)],["agents.config",e=>rg.call(Ye(t),e)],["agents.setConfig",e=>ng.call(Ye(t),e)],["agents.getConfig",e=>og.call(Ye(t),e)],["agents.removeConfig",e=>sg.call(Ye(t),e)],["agents.setGateway",e=>ig.call(Ye(t),e)],["agents.getGateway",e=>ag.call(Ye(t),e)],["agents.processes",e=>lg.call(Ye(t),e)],["agents.kill",e=>dg.call(Ye(t),e)],["agents.listConfigured",e=>cg.call(Ye(t),e)],["agents.getLog",e=>ug.call(Ye(t),e)],["agents.testConnection",e=>pg.call(Ye(t),e)],["solo.start",e=>Ob.call(hr(t),e)],["solo.status",e=>jb.call(hr(t),e)],["solo.cancel",e=>$b.call(hr(t),e)],["solo.select",e=>Ub.call(hr(t),e)],["solo.list",e=>Fb.call(hr(t),e)],["solo.delete",e=>Hb.call(hr(t),e)],["solo.message",e=>Bb.call(hr(t),e)],["solo.evaluate",e=>qb.call(hr(t),e)],["product.plan",e=>Eh.call(mt(t),e)],["product.confirm",e=>_h.call(mt(t),e)],["product.message",e=>Mh.call(mt(t),e)],["product.create",e=>Dh.call(mt(t),e)],["product.resume",e=>Nh.call(mt(t),e)],["product.pause",e=>Lh.call(mt(t),e)],["product.checkpoint",e=>Oh.call(mt(t),e)],["product.status",e=>jh.call(mt(t),e)],["product.list",e=>$h.call(mt(t),e)],["product.delete",e=>Uh.call(mt(t),e)],["product.cancel",e=>Fh.call(mt(t),e)],["product.rollback",e=>Hh.call(mt(t),e)],["workflow.create",e=>my.call(qt(t),e)],["workflow.get",e=>gy.call(qt(t),e)],["workflow.describe",e=>fy.call(qt(t),e)],["workflow.patch",e=>hy.call(qt(t),e)],["workflow.run",e=>yy.call(qt(t),e)],["workflow.setActive",e=>by.call(qt(t),e)],["workflow.list",e=>vy.call(qt(t),e)],["workflow.delete",e=>ky.call(qt(t),e)],["workflow.onImMessage",e=>Ry.call(qt(t),e)],["workflow.onWebhook",e=>Sy.call(qt(t),e)],["project.create",e=>wy.call(t,e)],["project.list",e=>Ty.call(t,e)],["project.delete",e=>Ay.call(t,e)],["project.purgeAll",e=>xy.call(t,e)],["project.rename",e=>Py.call(t,e)],["project.archive",e=>Cy.call(t,e)],["project.unarchive",e=>Iy.call(t,e)],["project.update",e=>_y.call(t,e)],["project.archiveByGroup",e=>Ey.call(t,e)],["session.switchProject",e=>Xy.call(t,e)],["session.focus",e=>Jy.call(t,e)],["session.moveToProject",e=>Qy.call(t,e)],["session.getState",e=>Yy.call(t,e)],["files.list",e=>_f.call(t,e)],["files.create",e=>Mf.call(t,e)],["files.rename",e=>Df.call(t,e)],["files.delete",e=>Nf.call(t,e)],["files.gitStatus",e=>Lf.call(t,e)],["instructions.list",e=>Of.call(t,e)],["instructions.read",e=>jf.call(t,e)],["instructions.write",e=>$f.call(t,e)],["instructions.delete",e=>Uf.call(t,e)],["plans.list",e=>Ff.call(t,e)],["skills.list",e=>Rb.call(t,e)],["skills.activate",e=>Sb.call(t,e)],["skills.deactivate",e=>wb.call(t,e)],["skills.delete",e=>Tb.call(t,e)],["skills.promote",e=>Ab.call(t,e)],["skills.stats",e=>xb.call(t,e)],["skills.pin",e=>Pb.call(t,e)],["skills.unpin",e=>Cb.call(t,e)],["skills.curator",e=>Ib.call(t,e)],["skills.lifecycle",e=>Eb.call(t,e)],["pet.hatch",e=>fh.call(t,e)],["pet.interact",e=>hh.call(t,e)],["pet.status",e=>yh.call(t,e)],["pet.forge",e=>bh.call(t,e)],["pet.confirm_response",e=>ch.call(t,e)]])}import{randomUUID as nR}from"node:crypto";import*as oR from"node:path";D();async function sR(t,e){t.log(`[acp] x/dream: session=${e.sessionId}`);let r=t.resolveClientForPurpose("textGeneration");if(!r)return{ok:!1,summary:"No LLM transport configured for dream"};let n=F(),o={jsonrpc:"2.0",id:`acp-dream-${nR().slice(0,8)}`,method:"memory.dream",params:{turnId:`dream-${nR().slice(0,8)}`,sessionId:e.sessionId||t.currentSessionId,config:{memoryRoot:e.config?.memoryRoot||n,transcriptDir:e.config?.transcriptDir||oR.join(n,"agent-logs"),model:r.model,apiKey:r.apiKey,...e.config}}};return await Yr.call(t,o),{ok:!0,summary:"Dream consolidation triggered"}}async function iR(t,e){t.log("[acp] x/solo.start");let r=Ve.call(t),n=await r.start(e);return r.getStatus(n)}async function aR(t,e){t.log("[acp] x/solo.status");let r=e.soloId;if(!r)return t.soloEvaluator?t.soloEvaluator.listSessions():[];let o=Ve.call(t).getStatus(r);if(!o)throw new Error(`Solo session ${r} not found`);return o}async function cR(t,e){return t.log("[acp] x/solo.select"),{ok:!0,mergedBranch:await Ve.call(t).select(e)}}async function lR(t,e){t.log("[acp] x/solo.cancel");let r=Ve.call(t),n=e.soloId;return await r.cancel(n),{ok:!0}}async function dR(t,e){return t.log("[acp] x/solo.subscribe"),{ok:!0,soloId:e.soloId}}async function uR(t,e){t.log("[acp] x/solo.message");let r=Ve.call(t),{soloId:n,agentId:o,content:s,agentIndex:i}=e;return r.message(n,o,s,i)}async function pR(t,e){t.log("[acp] x/solo.evaluate");let r=Ve.call(t),{soloId:n,evaluatorAgentId:o,evaluatorIndex:s}=e;return r.triggerEvaluation(n,o,s)}async function mR(t){return t.log("[acp] x/agents.list"),Dc()}async function gR(t,e){return t.log("[acp] x/product.create"),{productId:await ye.call(t).create(e)}}async function fR(t,e){return t.log("[acp] x/product.plan"),_r.call(t).plan(e)}async function hR(t,e){t.log("[acp] x/product.confirm");let r=_r.call(t),n=e,o=await r.confirm(n),s=r.getSession(n.productId);return s&&await ye.call(t).create({name:s.plan?.name??s.goal.slice(0,50),cwd:s.cwd,instances:n.instances,tasks:n.tasks,budget:n.budget}),o}async function yR(t,e){t.log("[acp] x/product.message");let r=_r.call(t),n=e;return r.message(n.productId,n.content)}async function bR(t,e){t.log("[acp] x/product.resume");let r=ye.call(t),n=e.productId;return await r.resume(n,t.getActiveProjectRoot()),{ok:!0}}async function vR(t,e){t.log("[acp] x/product.status");let r=e.productId;if(!t.productOrchestrator)return r?null:[];if(!r)return t.productOrchestrator.list(t.getActiveProjectRoot());let n=t.productOrchestrator.getStatus(r);if(!n)throw new Error(`Product session ${r} not found`);return n}async function kR(t,e){t.log("[acp] x/product.pause");let r=ye.call(t),n=e.productId;return await r.pause(n),{ok:!0}}async function RR(t,e){t.log("[acp] x/product.cancel");let r=ye.call(t),n=e.productId;return await r.delete(n),{ok:!0}}async function SR(t,e){t.log("[acp] x/product.rollback");let r=ye.call(t),n=e.productId,o=e.checkpointId??"latest";return await r.rollback(n,o),{ok:!0}}async function wR(t,e){return t.log("[acp] x/product.subscribe"),{ok:!0,productId:e.productId}}async function TR(t,e){let r=e.agentType,n=e.prompt,o=e.maxTurns;if(!n)throw new Error("Missing required param: prompt");if(!r)throw new Error("Missing required param: agentType");let s=Un(r);if(!s)throw new Error(`Unknown agent type: ${r}`);let i=t.resolveClientForPurpose("textGeneration");if(!i)throw new Error("No LLM provider configured; send a prompt first to configure the model");if(t.log(`[acp] x/team.delegate: agent=${r}, maxTurns=${o??s.maxTurns}`),ut.isTeamBudgetExceeded())return{ok:!1,agentType:r,output:void 0,error:ut.teamBudgetExceededError(),tokensUsed:0};let a={invoke:async()=>({result:"Tool execution not available in delegated mode"})},c={info:p=>t.log(`[delegate:${r}] ${p}`),warn:p=>t.log(`[delegate:${r}] WARN: ${p}`),error:p=>t.log(`[delegate:${r}] ERROR: ${p}`),debug:p=>t.log(`[delegate:${r}] ${p}`)},l=await Wr({promptMessages:[{role:"user",content:n}],tools:[],transport:i.transport,toolInvoker:a,createAgentRunner:Xr,apiKey:i.apiKey,model:i.model,log:c,forkLabel:`team-delegate-${r}`,maxTurns:o??s.maxTurns,parentSignal:t.activeTurn?.signal,parentDepth:0}),d=l.events.filter(p=>p.type==="end"&&"content"in p).map(p=>p.content??"").join("")||l.events.filter(p=>p.type==="delta"&&"text"in p).map(p=>p.text).join(""),u=l.totalUsage.inputTokens+l.totalUsage.outputTokens;return ut.recordForkTokens(u),{ok:l.ok,agentType:r,output:d||void 0,error:l.error,tokensUsed:u}}import{randomUUID as AR}from"node:crypto";async function xR(t,e,r){let n=e.clientInfo?.name??"unknown";t.log(`[acp] initialize: host=${n}`);let o={extendedEvents:!0,extendedMethods:!0,orchestration:!0,configOptions:[{name:"model",type:"string",description:"LLM model identifier"},{name:"provider",type:"string",description:"LLM provider identifier"},{name:"maxRounds",type:"number",description:"Max tool loop rounds"},{name:"temperature",type:"number",description:"Sampling temperature"}]};return t.ensureDefaultProject(),{protocolVersion:1,agentInfo:{name:"qlogicagent",version:r},agentCapabilities:o}}async function PR(t,e){let r=e.sessionId??AR();return t.log(`[acp] session/new: id=${r}`),t.currentSessionId=r,t.sessionState=new pr(r),t.sessionTaskDomain=void 0,t.memoryPrefetchState=ht(),e.cwd&&typeof e.cwd=="string"&&t.setActiveWorkdir(e.cwd),t.enableIdleDream(),{sessionId:r}}async function CR(t,e){let r=AR(),n=e.sessionId,o=e.prompt.map(a=>a.type==="text"?a.text:`[${a.type}]`).join("");if(!o.trim())return t.sendNotification("turn.start",{turnId:r,model:t.currentModel||void 0}),t.sendNotification("turn.end",{turnId:r,content:"",item:{id:`${r}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),{stopReason:"end_turn"};let s=t.sessionHistory.appendAcpUserMessage(n,o),i=await dO(t,r,n,[...s]);return i.content&&t.sessionHistory.appendAcpAssistantMessage(n,i.content),i}async function dO(t,e,r,n){let o=new AbortController;t.activeTurn=o,t.sendNotification("turn.start",{turnId:e,model:t.currentModel||void 0});try{let s={model:t.currentModel||void 0,provider:t.currentProvider||void 0,apiKey:t.currentApiKey||void 0,baseUrl:t.currentBaseUrl||void 0},i=fi(n);i.requiresFreshTool&&(s.toolChoice="required");let a=t.resolveAgent(s);if(!a)return t.sendNotification("turn.delta",{turnId:e,text:"Error: No LLM provider configured. Configure via ~/.qlogicagent/settings.json or pass provider/apiKey in session config.",item:{id:`${e}-err`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),t.sendNotification("turn.end",{turnId:e,content:"",item:{id:`${e}-end`,type:"message",role:"assistant",text:"",createdAt:new Date().toISOString()}}),t.activeTurn=null,{stopReason:"end_turn"};await t.mcpReady;let c=hi(Ie(),i),l=t.getActiveProjectRoot(),d=await Ri(l,t.currentHooks??void 0),u=d.length>0?ki(d):void 0,p=yi(i),m=await ai({instructionBlock:u,sections:[pi(l),gi(),mi(),...p?[p]:[]]}),g,f="end_turn",h="";for await(let v of a.run({turnId:e,sessionId:r,messages:n,tools:c,systemPrompt:m,config:s},o.signal)){let b=new Date().toISOString();if(!li({event:v,turnId:e,now:b,host:t}))switch(v.type){case"start":break;case"end":v.usage&&(g={inputTokens:v.usage.inputTokens??0,outputTokens:v.usage.outputTokens??0,cacheReadTokens:v.usage.cacheRead,cacheWriteTokens:v.usage.cacheWrite}),h=v.content??"",t.sendNotification("turn.end",{turnId:v.turnId,content:v.content,usage:v.usage,model:v.model,provider:v.provider,item:{id:`${e}-end`,type:"message",role:"assistant",text:v.content,createdAt:b}});break;case"error":f="end_turn",t.sendNotification("turn.error",{turnId:v.turnId,error:{message:v.error,code:v.code}});break}}return t.activeTurn=null,{stopReason:f,usage:g,content:h}}catch(s){t.activeTurn=null;let i=s instanceof Error?s.message:String(s);return t.log(`[acp] runAcpTurn error: ${i}`),t.sendNotification("turn.error",{turnId:e,error:{message:i,code:"INTERNAL_ERROR"}}),{stopReason:"end_turn"}}}async function IR(t,e){t.log(`[acp] session/end: id=${e.sessionId}`),t.sessionHistory.clearAcpSession(e.sessionId),t.currentSessionId===e.sessionId&&(t.cancelIdleDreamTimer(),t.currentHooks&&await t.currentHooks.invoke("session.ended",{sessionId:e.sessionId}).catch(()=>{}),t.currentSessionId="",t.sessionState=null,t.disposeSessionRuntime?.())}async function ER(t,e){let r=e.configId??e.option;t.log(`[acp] session/set_config: ${r}=${JSON.stringify(e.value)}`);let n=typeof e.value=="string"?e.value:"";switch(r){case"model":t.currentModel=n;break;case"provider":t.currentProvider=n;break;case"apiKey":t.currentApiKey=n;break;case"baseUrl":t.currentBaseUrl=n;break}}async function _R(t,e,r){t.log(`[acp] session/set_model: ${r} (note: model is managed by ModelRegistry, this is a hint only)`),r&&(t.currentModel=r)}async function MR(t,e,r){t.log(`[acp] session/set_mode: ${r}`)}function DR(t,e,r=t){return{handleAcpInitialize:n=>xR(t,n,e),handleAcpSessionNew:n=>PR(t,n),handleAcpSessionPrompt:n=>CR(t,n),handleAcpSessionEnd:n=>IR(t,n),handleAcpSessionSetConfig:n=>ER(t,n),handleAcpSessionSetModel:(n,o)=>_R(t,n,o),handleAcpSessionSetMode:(n,o)=>MR(t,n,o),handleAcpPermissionResponse:(n,o)=>{t.log(`[acp] permission response: ${n} -> ${o}`),t.permissionChecker?.resolveApproval({approvalId:n,decision:o==="allow"||o==="allowAlways"?"approved":"denied"})},handleAcpAbort:async n=>{t.log(`[acp] abort: session=${n.sessionId}`),t.activeTurn&&(t.activeTurn.abort(),t.activeTurn=null)},handleAcpDream:n=>sR(r,n),handleAcpAgentsList:()=>mR(r),handleAcpSoloStart:n=>iR(r,n),handleAcpSoloStatus:n=>aR(r,n),handleAcpSoloSelect:n=>cR(r,n),handleAcpSoloCancel:n=>lR(r,n),handleAcpSoloSubscribe:n=>dR(r,n),handleAcpSoloMessage:n=>uR(r,n),handleAcpSoloEvaluate:n=>pR(r,n),handleAcpProductCreate:n=>gR(r,n),handleAcpProductPlan:n=>fR(r,n),handleAcpProductConfirm:n=>hR(r,n),handleAcpProductMessage:n=>yR(r,n),handleAcpProductPause:n=>kR(r,n),handleAcpProductResume:n=>bR(r,n),handleAcpProductCancel:n=>RR(r,n),handleAcpProductRollback:n=>SR(r,n),handleAcpProductStatus:n=>vR(r,n),handleAcpProductSubscribe:n=>wR(r,n),handleAcpTeamDelegate:n=>TR(r,n)}}import{resolve as pO}from"node:path";var wi=class{constructor(e){this.mediaPersistence=e}mediaPersistence;activeWorkdir=null;getActiveProjectRoot(){if(this.activeWorkdir)return this.activeWorkdir;let e=oe();return e?.workspaceDir?e.workspaceDir:process.cwd()}setActiveWorkdir(e){let r=pO(e);this.activeWorkdir!==r&&(this.activeWorkdir=r,Ak(r),this.mediaPersistence.setProjectDir(r))}resolveProjectDir(e){if(e)return $t(e)??void 0}};import{createRequire as IO}from"node:module";D();import*as Ai from"node:fs";import*as OR from"node:path";import{randomUUID as fo}from"node:crypto";var mO=`
|
|
579
580
|
CREATE TABLE IF NOT EXISTS memories (
|
|
580
581
|
id TEXT PRIMARY KEY,
|
|
581
582
|
text TEXT NOT NULL,
|
|
@@ -705,7 +706,7 @@ CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
|
|
|
705
706
|
INSERT INTO memories_fts(rowid, id, user_id, text, category, tags)
|
|
706
707
|
VALUES (new.rowid, new.id, new.user_id, new.text, new.category, new.tags);
|
|
707
708
|
END;
|
|
708
|
-
`,Ti=class{db;constructor(e){this.db=e,this.initSchema()}initSchema(){this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.exec(
|
|
709
|
+
`,Ti=class{db;constructor(e){this.db=e,this.initSchema()}initSchema(){this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.exec(mO)}insert(e){let r=`mem_${fo().replace(/-/g,"").slice(0,16)}`,n=Date.now(),o=JSON.stringify(e.tags??[]),s=e.embedding?Buffer.from(e.embedding.buffer,e.embedding.byteOffset,e.embedding.byteLength):null;return this.db.prepare(`
|
|
709
710
|
INSERT INTO memories (id, text, user_id, category, importance, confidence, source, session_id, event_date, tags, embedding, created_at, updated_at, last_accessed_at)
|
|
710
711
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
711
712
|
`).run(r,e.text,e.userId,e.category??"general",e.importance??.5,e.confidence??1,e.source??"agent",e.sessionId??"",e.eventDate??"",o,s,n,n,n),r}searchFts(e,r,n=10){let o=e.replace(/['"*()]/g," ").trim();return o?this.db.prepare(`
|
|
@@ -720,7 +721,7 @@ END;
|
|
|
720
721
|
SELECT id, text, category, importance, tags, created_at, access_count, embedding
|
|
721
722
|
FROM memories
|
|
722
723
|
WHERE user_id = ? AND is_archived = 0 AND embedding IS NOT NULL
|
|
723
|
-
`).all(r),i=[],a=LR(e);for(let c of s){let l=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.byteLength/4),d=LR(l),u=
|
|
724
|
+
`).all(r),i=[],a=LR(e);for(let c of s){let l=new Float32Array(c.embedding.buffer,c.embedding.byteOffset,c.embedding.byteLength/4),d=LR(l),u=hO(a,d);u>=o&&i.push({id:c.id,text:c.text,score:u*.7+c.importance*.3,category:c.category,importance:c.importance,metadata:{tags:JSON.parse(c.tags||"[]"),createdAt:c.created_at,accessCount:c.access_count,cosineSimilarity:u}})}return i.sort((c,l)=>l.score-c.score),i.slice(0,n)}searchHybrid(e,r,n,o=10){let s=this.searchFts(e,n,o*2);if(!r)return s.slice(0,o);let i=this.searchVector(r,n,o*2),a=new Map;for(let c of s)a.set(c.id,c);for(let c of i){let l=a.get(c.id);(!l||c.score>l.score)&&a.set(c.id,c)}return Array.from(a.values()).sort((c,l)=>l.score-c.score).slice(0,o)}listByUser(e,r=1,n=50,o=!0){let s=(r-1)*n,i=o?"AND is_archived = 0":"";return this.db.prepare(`
|
|
724
725
|
SELECT * FROM memories
|
|
725
726
|
WHERE user_id = ? ${i}
|
|
726
727
|
ORDER BY created_at DESC
|
|
@@ -910,11 +911,11 @@ END;
|
|
|
910
911
|
SELECT * FROM memory_conflicts
|
|
911
912
|
WHERE user_id = ?
|
|
912
913
|
ORDER BY updated_at DESC
|
|
913
|
-
`).all(e).map(mO)}close(){this.db.close()}};function Ud(t){return{id:t.id,text:t.text,userId:t.user_id,category:t.category,importance:t.importance,confidence:t.confidence??1,source:t.source,sessionId:t.session_id,eventDate:t.event_date,tags:JSON.parse(t.tags||"[]"),embedding:t.embedding?new Float32Array(t.embedding.buffer,t.embedding.byteOffset,t.embedding.byteLength/4):null,createdAt:t.created_at,updatedAt:t.updated_at,accessCount:t.access_count,lastAccessedAt:t.last_accessed_at,isArchived:!!t.is_archived}}function NR(t){return{id:t.id,memoryId:t.memory_id??"",userId:t.user_id,entity:t.entity??"",predicate:t.predicate??"",value:gO(t.value_json),text:t.text,category:t.category,importance:t.importance,confidence:t.confidence,source:t.source,sourcePriority:t.source_priority,status:t.status,validTime:t.valid_time??"",evidenceIds:jR(t.evidence_ids),supersedesClaimId:t.supersedes_claim_id??"",conflictGroupId:t.conflict_group_id??"",createdAt:t.created_at,updatedAt:t.updated_at}}function mO(t){return{id:t.id,userId:t.user_id,claimAId:t.claim_a_id,claimBId:t.claim_b_id,reason:t.reason,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at}}function gO(t){if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function jR(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}catch{return[]}}function LR(t){let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];if(e=Math.sqrt(e),e===0)return t;let r=new Float32Array(t.length);for(let n=0;n<t.length;n++)r[n]=t[n]/e;return r}function fO(t,e){let r=0,n=Math.min(t.length,e.length);for(let o=0;o<n;o++)r+=t[o]*e[o];return r}function $R(t=Br()){let e=Gu(t);return Ai.existsSync(e)||Ai.mkdirSync(e,{recursive:!0}),OR.join(e,"memories.db")}var Fd=class{dimensions=0;model="none";async embed(e){return new Float32Array(0)}async embedBatch(e){return e.map(()=>new Float32Array(0))}},Hd=class{dimensions;model;baseUrl;apiKey;timeoutMs;format;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.apiKey=e.apiKey,this.model=e.model,this.dimensions=e.dimensions??1536,this.timeoutMs=e.timeoutMs??1e4,this.format=e.format??"openai"}async embed(e){return(await this.embedBatch([e]))[0]}async embedBatch(e){if(e.length===0)return[];let r=new AbortController,n=setTimeout(()=>r.abort(),this.timeoutMs);try{let{url:o,body:s}=this.buildRequest(e),i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s),signal:r.signal});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`Embedding API error [${this.format}]: ${i.status} ${i.statusText}${c?` \u2014 ${c.slice(0,200)}`:""}`)}let a=await i.json();return this.parseResponse(a,e.length)}finally{clearTimeout(n)}}buildRequest(e){switch(this.format){case"minimax":return{url:`${this.baseUrl}/v1/embeddings`,body:{model:this.model,texts:e,type:"db"}};case"volcengine":return{url:`${this.baseUrl}/v1/embeddings/multimodal`,body:{model:this.model,input:e.map(r=>({type:"text",text:r})),dimensions:this.dimensions}};default:return{url:`${this.baseUrl}/v1/embeddings`,body:{model:this.model,input:e,dimensions:this.dimensions}}}}parseResponse(e,r){switch(this.format){case"minimax":{let n=e.vectors;if(!n||n.length===0)throw new Error("MiniMax embedding returned empty vectors");return n.map(o=>new Float32Array(o))}case"volcengine":{let n=e.data;if(Array.isArray(n))return n.map(o=>new Float32Array(o.embedding));if(n?.embedding)return[new Float32Array(n.embedding)];throw new Error("Volcengine embedding returned unexpected structure")}default:{let n=e.data;if(!n||n.length===0)throw new Error("OpenAI embedding returned empty data");return n.sort((s,i)=>s.index-i.index).map(s=>new Float32Array(s.embedding))}}}};function UR(t){return t?.api?new Hd(t.api):new Fd}var hO={qwen:{format:"openai",baseUrl:"https://dashscope.aliyuncs.com/compatible-mode",defaultModel:"text-embedding-v3",defaultDimensions:1024},zhipu:{format:"openai",baseUrl:"https://open.bigmodel.cn/api/paas",defaultModel:"embedding-3",defaultDimensions:2048},minimax:{format:"minimax",baseUrl:"https://api.minimax.chat",defaultModel:"embo-01",defaultDimensions:1024},volcengine:{format:"volcengine",baseUrl:"https://ark.cn-beijing.volces.com/api",defaultModel:"doubao-embedding-vision-251215",defaultDimensions:1024},openai:{format:"openai",baseUrl:"https://api.openai.com",defaultModel:"text-embedding-3-small",defaultDimensions:1536},google:{format:"openai",baseUrl:"https://generativelanguage.googleapis.com",defaultModel:"text-embedding-004",defaultDimensions:768},deepseek:{format:"openai",baseUrl:"https://api.deepseek.com",defaultModel:"text-embedding-v1",defaultDimensions:1024}};function FR(t,e,r){let n=hO[t.toLowerCase()];return n?{baseUrl:r?.baseUrl||n.baseUrl,apiKey:e,model:r?.model||n.defaultModel,dimensions:r?.dimensions||n.defaultDimensions,format:n.format}:null}var yO={observationsAdded:0,proposalsAdded:0,claimsAdded:0,conflictsAdded:0,memoriesAdded:0,observationIds:[],proposalIds:[],claimIds:[],conflictIds:[]},Ci=class{constructor(e,r){this.store=e;this.embed=r}store;embed;async observe(e,r,n){let o=Pi(n?.source),s=ho(o),i=qd();for(let a of e){let c=a.text?.trim();if(!c)continue;let l=this.store.insertObservation({userId:r,text:c,source:o,sourcePriority:s,sessionId:n?.sessionId??"",evidenceType:"text",payload:{category:a.category,importance:a.importance,tags:a.tags??[]}});i.observationsAdded++,i.observationIds.push(l)}return i}async proposeExtracted(e,r,n){let o=Pi(n?.source),s=ho(o),i=qd();for(let a of e){let c=a.text?.trim();if(!c)continue;let l=this.store.insertObservation({userId:r,text:c,source:o,sourcePriority:s,sessionId:n?.sessionId??"",evidenceType:"text",payload:{category:a.category,importance:a.importance,eventDate:a.event_date,tags:a.tags??[]}});i.observationsAdded++,i.observationIds.push(l);let d=HR(c,a,o),u=this.store.insertProposal({userId:r,observationIds:[l],text:c,category:a.category??"general",importance:or(a.importance??.5,.1,1),confidence:d.confidence,source:o,sourcePriority:s,entity:d.entity,predicate:d.predicate,value:d.value,validTime:d.validTime,tags:a.tags??[],status:"pending"});i.proposalsAdded++,i.proposalIds.push(u)}return i}async commitExtracted(e,r,n){let o=Pi(n?.source),s=ho(o),i=qd();for(let a of e){let c=a.text?.trim();if(!c)continue;let l=this.store.insertObservation({userId:r,text:c,source:o,sourcePriority:s,sessionId:n?.sessionId??"",evidenceType:"text",payload:{category:a.category,importance:a.importance,eventDate:a.event_date,tags:a.tags??[]}});i.observationsAdded++,i.observationIds.push(l);let d=HR(c,a,o),u=this.store.insertProposal({userId:r,observationIds:[l],text:c,category:a.category??"general",importance:or(a.importance??.5,.1,1),confidence:d.confidence,source:o,sourcePriority:s,entity:d.entity,predicate:d.predicate,value:d.value,validTime:d.validTime,tags:a.tags??[],status:"pending"});i.proposalsAdded++,i.proposalIds.push(u);let p=this.store.findClaimsByFact(r,d.entity,d.predicate,d.validTime),m=p.find(b=>SO(b.value,d.value));if(m){this.store.mergeClaimEvidence(m.id,[l],Math.max(m.confidence,d.confidence),or(a.importance??m.importance,.1,1)),this.store.updateProposalStatus(u,"merged",[m.id]),i.claimIds.push(m.id);continue}let g=p.find(b=>b.status==="active"||b.status==="pending_confirmation");if(g){let b=this.store.insertClaim({userId:r,entity:d.entity,predicate:d.predicate,value:d.value,text:c,category:a.category??"general",importance:or(a.importance??.5,.1,1),confidence:d.confidence,source:o,sourcePriority:s,status:"conflicted",validTime:d.validTime,evidenceIds:[l]}),S=this.store.insertConflict({userId:r,claimAId:g.id,claimBId:b,reason:`same entity + same predicate + different value: ${d.entity}.${d.predicate}`});this.store.updateProposalStatus(u,"conflicted",[g.id,b]),i.claimsAdded++,i.conflictsAdded++,i.claimIds.push(b),i.conflictIds.push(S);continue}let f=bO(o,d.confidence),h=f==="active"?this.store.insert({text:c,userId:r,category:a.category??"general",importance:or(a.importance??.5,.1,1),confidence:d.confidence,source:o,sessionId:n?.sessionId??"",eventDate:a.event_date??"",tags:a.tags??[],embedding:await this.embed(c)}):"",v=this.store.insertClaim({userId:r,memoryId:h,entity:d.entity,predicate:d.predicate,value:d.value,text:c,category:a.category??"general",importance:or(a.importance??.5,.1,1),confidence:d.confidence,source:o,sourcePriority:s,status:f,validTime:d.validTime,evidenceIds:[l]});this.store.updateProposalStatus(u,f==="active"?"accepted":"pending",[v]),i.claimsAdded++,i.memoriesAdded+=h?1:0,i.claimIds.push(v)}return i}};function ho(t){let e=Pi(t);return e==="manual"||e==="user_edit"?100:e==="explicit"||e==="agent-remember"||e==="agent"?90:e==="document"||e==="image"||e==="video"?70:e==="auto"||e==="turn"?45:e==="dream"||e==="dream-consolidation"||e==="profile-extraction"?20:40}function bO(t,e){return ho(t)>=45&&e>=.55?"active":"pending_confirmation"}function HR(t,e,r){let n=TO(t),o=(e.tags??[]).join(" "),s=vO(t,o),i=kO(t);if(i)return{entity:s,predicate:"contract_amount",value:i,validTime:qR(e.event_date),confidence:Bd(r,.92)};let a=RO(t);if(a)return{entity:s,predicate:"progress_update_schedule",value:a,validTime:"",confidence:Bd(r,.86)};let c=wO(e.category??"general");return{entity:s,predicate:c,value:{text:n},validTime:qR(e.event_date),confidence:Bd(r,.7)}}function Bd(t,e){let r=ho(t);return r>=90?or(e+.04,.1,.99):r<=20?or(e-.18,.1,.95):or(e,.1,.98)}function vO(t,e){let r=`${t} ${e}`;if(/Galaxy\s*Tech|Galaxy/i.test(r))return"Galaxy Tech";let n=r.match(/\b[A-Z][A-Za-z0-9]*(?:\s+[A-Z][A-Za-z0-9]*){0,3}\b/);if(n?.[0])return n[0].trim();let o=r.match(/([\u4e00-\u9fa5A-Za-z0-9]{2,18})(?:公司|客户|合同|项目)/);return o?.[1]?o[1]:"user"}function kO(t){if(!/(合同|contract)/i.test(t))return null;let e=t.match(/(\d+(?:\.\d+)?)\s*k\b/i);if(e)return{amount:Math.round(Number(e[1])*1e3),currency:xi(t)};let r=t.match(/(\d+(?:\.\d+)?)\s*万/);if(r)return{amount:Math.round(Number(r[1])*1e4),currency:xi(t)};let n=t.match(/(?:金额|amount)[^\d]*(\d{5,})/i);return n?{amount:Number(n[1]),currency:xi(t)}:/一十八万/.test(t)?{amount:18e4,currency:xi(t)}:null}function RO(t){if(!/(提醒|进展|更新|progress|schedule|每周)/i.test(t))return null;let e=/周一|星期一|Monday/i.test(t)?"monday":/周二|星期二|Tuesday/i.test(t)?"tuesday":/周三|星期三|Wednesday/i.test(t)?"wednesday":/周四|星期四|Thursday/i.test(t)?"thursday":/周五|星期五|Friday/i.test(t)?"friday":/周六|星期六|Saturday/i.test(t)?"saturday":/周日|周天|星期日|星期天|Sunday/i.test(t)?"sunday":"";if(!e)return null;let r=t.match(/(?:上午|早上)?\s*(\d{1,2})\s*点/);return{cadence:"weekly",weekday:e,hour:r?Number(r[1]):null}}function SO(t,e){return BR(t)===BR(e)}function BR(t){let e=Object.keys(t).sort();return JSON.stringify(e.reduce((r,n)=>(r[n]=t[n],r),{}))}function xi(t){return/[¥¥]|人民币|CNY/i.test(t)?"CNY":/\$|USD/i.test(t)?"USD":"unknown"}function wO(t){return t.trim().toLowerCase().replace(/[^a-z0-9_\-\u4e00-\u9fa5]+/g,"_")||"general"}function qR(t){if(!t)return"";let e=new Date(t);return Number.isNaN(e.getTime())?"":`${e.getUTCFullYear()}-${String(e.getUTCMonth()+1).padStart(2,"0")}`}function TO(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function Pi(t){return t?.trim()||"agent"}function or(t,e,r){return Number.isFinite(t)?Math.max(e,Math.min(r,t)):e}function qd(){return{...yO,observationIds:[],proposalIds:[],claimIds:[],conflictIds:[]}}D();import*as qt from"node:fs";var WR="qmemory-local",Gd=class{providerId=WR;store;embedding;consolidator;userIdPrefix;dbPath;constructor(e){if(this.dbPath=$R(e.ownerUserId),this.userIdPrefix=e.userIdPrefix??"",this.embedding=UR(e.embedding),!e.createDatabase)throw new Error("LocalMemoryProvider requires a createDatabase factory. Install better-sqlite3 and pass: (path) => new Database(path)");e.migrateLegacyMemory&&AO(this.dbPath,e.createDatabase);let r=e.createDatabase(this.dbPath);this.store=new Ti(r),this.consolidator=new Ci(this.store,n=>this.buildEmbedding(n))}resolveUserId(e){return this.userIdPrefix?`${this.userIdPrefix}:${e}`:e}async buildEmbedding(e){if(this.embedding.dimensions!==0)try{let r=await this.embedding.embed(e);return r.length?r:void 0}catch{return}}async search(e,r,n){let o=this.resolveUserId(r),s=n?.limit??10,i=n?.minScore??.1,a=null;if(this.embedding.dimensions>0)try{a=await this.embedding.embed(e)}catch{}let c=Math.min(s*3,50),l=this.store.searchHybrid(e,a,o,c),d=this.rerank(l.map(u=>({id:u.id,text:u.text,score:u.score,category:u.category,metadata:{...u.metadata,createdAt:u.metadata?.createdAt,accessCount:u.metadata?.accessCount}})),{preferredCategories:n?.preferredCategories});for(let u of d.slice(0,3))this.store.recordAccess(u.id);return d.filter(u=>u.score>=i).slice(0,s).map(u=>({blockId:u.id,text:u.text,score:u.score,source:WR,metadata:u.metadata}))}async ingest(e,r,n){let o=this.resolveUserId(r),s=e.filter(i=>i.content?.trim()&&i.content.trim().length>=10).map(i=>({text:i.content,category:"conversation",importance:.4}));await this.consolidator.observe(s,o,{source:n?.source??"turn",sessionId:n?.sessionId??""})}async addText(e,r,n){return this.ingestExtracted([{text:e,category:n?.category??"fact",importance:n?.importance??.6}],r,{...n,source:n?.source??"agent",sessionId:n?.sessionId??""})}async remove(e){return this.store.updateClaimsByMemoryId(e,"archived"),this.store.delete(e)}async update(e,r){let n=this.store.getById(e);if(!n)return!1;let o=r.text?.trim(),s=o&&o!==n.text?await this.buildEmbedding(o):void 0,i=this.store.update(e,{...r,text:o||void 0,embedding:s});return i&&this.store.updateClaimsByMemoryId(e,"superseded"),i}async ingestExtracted(e,r,n){if(e.length===0)return Wd();let o=this.resolveUserId(r);return this.consolidator.commitExtracted(e,o,{source:n?.source??"agent",sessionId:n?.sessionId??""})}async observeExtracted(e,r,n){return e.length===0?Wd():this.consolidator.observe(e,this.resolveUserId(r),{source:n?.source??"agent",sessionId:n?.sessionId??""})}async proposeExtracted(e,r,n){return e.length===0?Wd():this.consolidator.proposeExtracted(e,this.resolveUserId(r),{source:n?.source??"agent",sessionId:n?.sessionId??""})}listClaims(e){return this.store.listClaims(this.resolveUserId(e))}listConflicts(e){return this.store.listConflicts(this.resolveUserId(e))}async triggerDecay(e,r=90){let n=this.resolveUserId(e),o=this.store.runFullDecay(n),s=this.store.enforceCapacityLimit(n,1e4);return o.total+s>10&&(this.store.exportAndPurgeArchived(n,200),this.store.vacuum()),{decayed:o.total+s}}async feedback(e,r){let n=0;for(let o of e)this.store.applyFeedback(o,r)&&n++;return{affected:n}}getProfile(e,r){return this.store.getProfile(this.resolveUserId(e),r)}setProfile(e,r,n){this.store.setProfile(this.resolveUserId(e),r,n)}getAllProfiles(e){return this.store.getAllProfiles(this.resolveUserId(e))}deleteProfile(e,r){return this.store.deleteProfile(this.resolveUserId(e),r)}getTemporalSlice(e,r,n,o){return this.store.getTemporalSlice(this.resolveUserId(e),r,n,o)}getActivitySummary(e,r=7){return this.store.getActivitySummary(this.resolveUserId(e),r)}list(e,r){return this.store.listByUser(this.resolveUserId(e),r?.page??1,r?.pageSize??500,r?.activeOnly??!0)}getAtlas(e,r){return this.store.getAtlas(this.resolveUserId(e),r)}findByEventDate(e,r,n=1){return this.store.findByEventDate(this.resolveUserId(e),r,n)}async findRelatedEvents(e,r,n){let o=this.resolveUserId(r),s=n?.minSimilarity??.55,i=n?.maxSimilarity??.82,a=n?.maxDaysBack??14,c=n?.limit??5;if(this.embedding.dimensions===0)return[];let l;try{l=await this.embedding.embed(e)}catch{return[]}let d=this.store.searchVector(l,o,c*3,s),u=Date.now()-a*864e5;return d.filter(p=>{let m=p.metadata?.cosineSimilarity??p.score,g=p.metadata?.createdAt??0;return m>=s&&m<i&&g>=u}).slice(0,c).map(p=>({id:p.id,text:p.text,score:p.metadata?.cosineSimilarity??p.score,date:new Date(p.metadata?.createdAt??Date.now()).toISOString().slice(0,10)}))}synthesizeTimeline(e,r,n){let o=this.getTemporalSlice(e,r,n);if(o.length===0)return"No memories in this time range.";let s=[];for(let i of o){s.push(`## ${i.date}`);for(let a of i.memories){let c=a.importance>=.7?"*":"-";s.push(`${c} [${a.category}] ${a.text}`)}}return s.join(`
|
|
914
|
-
`)}rerank(e,r){let n=(r?.recencyBoostDays??7)*864e5,o=Date.now(),s=new Set(r?.preferredCategories??[]);return e.map(i=>{let a=i.score,c=i.metadata?.createdAt??0;if(c>0){let d=o-c;d<n&&(a+=.1*(1-d/n))}let l=i.metadata?.accessCount??0;return l>0&&(a+=Math.min(.05,l*.01)),s.size>0&&i.category&&s.has(i.category)&&(a+=.08),{...i,score:Math.min(1,a)}}).sort((i,a)=>a.score-i.score)}async health(){return{status:"healthy",memoryCount:0,dbPath:this.dbPath}}count(e){return this.store.count(this.resolveUserId(e))}async resetUser(e){return this.store.resetUser(this.resolveUserId(e))}close(){this.store.close()}};function KR(t){return new Gd(t)}function
|
|
914
|
+
`).all(e).map(gO)}close(){this.db.close()}};function Ud(t){return{id:t.id,text:t.text,userId:t.user_id,category:t.category,importance:t.importance,confidence:t.confidence??1,source:t.source,sessionId:t.session_id,eventDate:t.event_date,tags:JSON.parse(t.tags||"[]"),embedding:t.embedding?new Float32Array(t.embedding.buffer,t.embedding.byteOffset,t.embedding.byteLength/4):null,createdAt:t.created_at,updatedAt:t.updated_at,accessCount:t.access_count,lastAccessedAt:t.last_accessed_at,isArchived:!!t.is_archived}}function NR(t){return{id:t.id,memoryId:t.memory_id??"",userId:t.user_id,entity:t.entity??"",predicate:t.predicate??"",value:fO(t.value_json),text:t.text,category:t.category,importance:t.importance,confidence:t.confidence,source:t.source,sourcePriority:t.source_priority,status:t.status,validTime:t.valid_time??"",evidenceIds:jR(t.evidence_ids),supersedesClaimId:t.supersedes_claim_id??"",conflictGroupId:t.conflict_group_id??"",createdAt:t.created_at,updatedAt:t.updated_at}}function gO(t){return{id:t.id,userId:t.user_id,claimAId:t.claim_a_id,claimBId:t.claim_b_id,reason:t.reason,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at}}function fO(t){if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function jR(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}catch{return[]}}function LR(t){let e=0;for(let n=0;n<t.length;n++)e+=t[n]*t[n];if(e=Math.sqrt(e),e===0)return t;let r=new Float32Array(t.length);for(let n=0;n<t.length;n++)r[n]=t[n]/e;return r}function hO(t,e){let r=0,n=Math.min(t.length,e.length);for(let o=0;o<n;o++)r+=t[o]*e[o];return r}function $R(t=Br()){let e=Gu(t);return Ai.existsSync(e)||Ai.mkdirSync(e,{recursive:!0}),OR.join(e,"memories.db")}var Fd=class{dimensions=0;model="none";async embed(e){return new Float32Array(0)}async embedBatch(e){return e.map(()=>new Float32Array(0))}},Hd=class{dimensions;model;baseUrl;apiKey;timeoutMs;format;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.apiKey=e.apiKey,this.model=e.model,this.dimensions=e.dimensions??1536,this.timeoutMs=e.timeoutMs??1e4,this.format=e.format??"openai"}async embed(e){return(await this.embedBatch([e]))[0]}async embedBatch(e){if(e.length===0)return[];let r=new AbortController,n=setTimeout(()=>r.abort(),this.timeoutMs);try{let{url:o,body:s}=this.buildRequest(e),i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s),signal:r.signal});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`Embedding API error [${this.format}]: ${i.status} ${i.statusText}${c?` \u2014 ${c.slice(0,200)}`:""}`)}let a=await i.json();return this.parseResponse(a,e.length)}finally{clearTimeout(n)}}buildRequest(e){switch(this.format){case"minimax":return{url:`${this.baseUrl}/v1/embeddings`,body:{model:this.model,texts:e,type:"db"}};case"volcengine":return{url:`${this.baseUrl}/v1/embeddings/multimodal`,body:{model:this.model,input:e.map(r=>({type:"text",text:r})),dimensions:this.dimensions}};default:return{url:`${this.baseUrl}/v1/embeddings`,body:{model:this.model,input:e,dimensions:this.dimensions}}}}parseResponse(e,r){switch(this.format){case"minimax":{let n=e.vectors;if(!n||n.length===0)throw new Error("MiniMax embedding returned empty vectors");return n.map(o=>new Float32Array(o))}case"volcengine":{let n=e.data;if(Array.isArray(n))return n.map(o=>new Float32Array(o.embedding));if(n?.embedding)return[new Float32Array(n.embedding)];throw new Error("Volcengine embedding returned unexpected structure")}default:{let n=e.data;if(!n||n.length===0)throw new Error("OpenAI embedding returned empty data");return n.sort((s,i)=>s.index-i.index).map(s=>new Float32Array(s.embedding))}}}};function UR(t){return t?.api?new Hd(t.api):new Fd}var yO={qwen:{format:"openai",baseUrl:"https://dashscope.aliyuncs.com/compatible-mode",defaultModel:"text-embedding-v3",defaultDimensions:1024},zhipu:{format:"openai",baseUrl:"https://open.bigmodel.cn/api/paas",defaultModel:"embedding-3",defaultDimensions:2048},minimax:{format:"minimax",baseUrl:"https://api.minimax.chat",defaultModel:"embo-01",defaultDimensions:1024},volcengine:{format:"volcengine",baseUrl:"https://ark.cn-beijing.volces.com/api",defaultModel:"doubao-embedding-vision-251215",defaultDimensions:1024},openai:{format:"openai",baseUrl:"https://api.openai.com",defaultModel:"text-embedding-3-small",defaultDimensions:1536},google:{format:"openai",baseUrl:"https://generativelanguage.googleapis.com",defaultModel:"text-embedding-004",defaultDimensions:768},deepseek:{format:"openai",baseUrl:"https://api.deepseek.com",defaultModel:"text-embedding-v1",defaultDimensions:1024}};function FR(t,e,r){let n=yO[t.toLowerCase()];return n?{baseUrl:r?.baseUrl||n.baseUrl,apiKey:e,model:r?.model||n.defaultModel,dimensions:r?.dimensions||n.defaultDimensions,format:n.format}:null}var bO={observationsAdded:0,proposalsAdded:0,claimsAdded:0,conflictsAdded:0,memoriesAdded:0,observationIds:[],proposalIds:[],claimIds:[],conflictIds:[]},Ci=class{constructor(e,r){this.store=e;this.embed=r}store;embed;async observe(e,r,n){let o=Pi(n?.source),s=ho(o),i=qd();for(let a of e){let c=a.text?.trim();if(!c)continue;let l=this.store.insertObservation({userId:r,text:c,source:o,sourcePriority:s,sessionId:n?.sessionId??"",evidenceType:"text",payload:{category:a.category,importance:a.importance,tags:a.tags??[]}});i.observationsAdded++,i.observationIds.push(l)}return i}async proposeExtracted(e,r,n){let o=Pi(n?.source),s=ho(o),i=qd();for(let a of e){let c=a.text?.trim();if(!c)continue;let l=this.store.insertObservation({userId:r,text:c,source:o,sourcePriority:s,sessionId:n?.sessionId??"",evidenceType:"text",payload:{category:a.category,importance:a.importance,eventDate:a.event_date,tags:a.tags??[]}});i.observationsAdded++,i.observationIds.push(l);let d=HR(c,a,o),u=this.store.insertProposal({userId:r,observationIds:[l],text:c,category:a.category??"general",importance:or(a.importance??.5,.1,1),confidence:d.confidence,source:o,sourcePriority:s,entity:d.entity,predicate:d.predicate,value:d.value,validTime:d.validTime,tags:a.tags??[],status:"pending"});i.proposalsAdded++,i.proposalIds.push(u)}return i}async commitExtracted(e,r,n){let o=Pi(n?.source),s=ho(o),i=qd();for(let a of e){let c=a.text?.trim();if(!c)continue;let l=this.store.insertObservation({userId:r,text:c,source:o,sourcePriority:s,sessionId:n?.sessionId??"",evidenceType:"text",payload:{category:a.category,importance:a.importance,eventDate:a.event_date,tags:a.tags??[]}});i.observationsAdded++,i.observationIds.push(l);let d=HR(c,a,o),u=this.store.insertProposal({userId:r,observationIds:[l],text:c,category:a.category??"general",importance:or(a.importance??.5,.1,1),confidence:d.confidence,source:o,sourcePriority:s,entity:d.entity,predicate:d.predicate,value:d.value,validTime:d.validTime,tags:a.tags??[],status:"pending"});i.proposalsAdded++,i.proposalIds.push(u);let p=this.store.findClaimsByFact(r,d.entity,d.predicate,d.validTime),m=p.find(b=>wO(b.value,d.value));if(m){this.store.mergeClaimEvidence(m.id,[l],Math.max(m.confidence,d.confidence),or(a.importance??m.importance,.1,1)),this.store.updateProposalStatus(u,"merged",[m.id]),i.claimIds.push(m.id);continue}let g=p.find(b=>b.status==="active"||b.status==="pending_confirmation");if(g){let b=this.store.insertClaim({userId:r,entity:d.entity,predicate:d.predicate,value:d.value,text:c,category:a.category??"general",importance:or(a.importance??.5,.1,1),confidence:d.confidence,source:o,sourcePriority:s,status:"conflicted",validTime:d.validTime,evidenceIds:[l]}),S=this.store.insertConflict({userId:r,claimAId:g.id,claimBId:b,reason:`same entity + same predicate + different value: ${d.entity}.${d.predicate}`});this.store.updateProposalStatus(u,"conflicted",[g.id,b]),i.claimsAdded++,i.conflictsAdded++,i.claimIds.push(b),i.conflictIds.push(S);continue}let f=vO(o,d.confidence),h=f==="active"?this.store.insert({text:c,userId:r,category:a.category??"general",importance:or(a.importance??.5,.1,1),confidence:d.confidence,source:o,sessionId:n?.sessionId??"",eventDate:a.event_date??"",tags:a.tags??[],embedding:await this.embed(c)}):"",v=this.store.insertClaim({userId:r,memoryId:h,entity:d.entity,predicate:d.predicate,value:d.value,text:c,category:a.category??"general",importance:or(a.importance??.5,.1,1),confidence:d.confidence,source:o,sourcePriority:s,status:f,validTime:d.validTime,evidenceIds:[l]});this.store.updateProposalStatus(u,f==="active"?"accepted":"pending",[v]),i.claimsAdded++,i.memoriesAdded+=h?1:0,i.claimIds.push(v)}return i}};function ho(t){let e=Pi(t);return e==="manual"||e==="user_edit"?100:e==="explicit"||e==="agent-remember"||e==="agent"?90:e==="document"||e==="image"||e==="video"?70:e==="auto"||e==="turn"?45:e==="dream"||e==="dream-consolidation"||e==="profile-extraction"?20:40}function vO(t,e){return ho(t)>=45&&e>=.55?"active":"pending_confirmation"}function HR(t,e,r){let n=AO(t),o=(e.tags??[]).join(" "),s=kO(t,o),i=RO(t);if(i)return{entity:s,predicate:"contract_amount",value:i,validTime:qR(e.event_date),confidence:Bd(r,.92)};let a=SO(t);if(a)return{entity:s,predicate:"progress_update_schedule",value:a,validTime:"",confidence:Bd(r,.86)};let c=TO(e.category??"general");return{entity:s,predicate:c,value:{text:n},validTime:qR(e.event_date),confidence:Bd(r,.7)}}function Bd(t,e){let r=ho(t);return r>=90?or(e+.04,.1,.99):r<=20?or(e-.18,.1,.95):or(e,.1,.98)}function kO(t,e){let r=`${t} ${e}`;if(/Galaxy\s*Tech|Galaxy/i.test(r))return"Galaxy Tech";let n=r.match(/\b[A-Z][A-Za-z0-9]*(?:\s+[A-Z][A-Za-z0-9]*){0,3}\b/);if(n?.[0])return n[0].trim();let o=r.match(/([\u4e00-\u9fa5A-Za-z0-9]{2,18})(?:公司|客户|合同|项目)/);return o?.[1]?o[1]:"user"}function RO(t){if(!/(合同|contract)/i.test(t))return null;let e=t.match(/(\d+(?:\.\d+)?)\s*k\b/i);if(e)return{amount:Math.round(Number(e[1])*1e3),currency:xi(t)};let r=t.match(/(\d+(?:\.\d+)?)\s*万/);if(r)return{amount:Math.round(Number(r[1])*1e4),currency:xi(t)};let n=t.match(/(?:金额|amount)[^\d]*(\d{5,})/i);return n?{amount:Number(n[1]),currency:xi(t)}:/一十八万/.test(t)?{amount:18e4,currency:xi(t)}:null}function SO(t){if(!/(提醒|进展|更新|progress|schedule|每周)/i.test(t))return null;let e=/周一|星期一|Monday/i.test(t)?"monday":/周二|星期二|Tuesday/i.test(t)?"tuesday":/周三|星期三|Wednesday/i.test(t)?"wednesday":/周四|星期四|Thursday/i.test(t)?"thursday":/周五|星期五|Friday/i.test(t)?"friday":/周六|星期六|Saturday/i.test(t)?"saturday":/周日|周天|星期日|星期天|Sunday/i.test(t)?"sunday":"";if(!e)return null;let r=t.match(/(?:上午|早上)?\s*(\d{1,2})\s*点/);return{cadence:"weekly",weekday:e,hour:r?Number(r[1]):null}}function wO(t,e){return BR(t)===BR(e)}function BR(t){let e=Object.keys(t).sort();return JSON.stringify(e.reduce((r,n)=>(r[n]=t[n],r),{}))}function xi(t){return/[¥¥]|人民币|CNY/i.test(t)?"CNY":/\$|USD/i.test(t)?"USD":"unknown"}function TO(t){return t.trim().toLowerCase().replace(/[^a-z0-9_\-\u4e00-\u9fa5]+/g,"_")||"general"}function qR(t){if(!t)return"";let e=new Date(t);return Number.isNaN(e.getTime())?"":`${e.getUTCFullYear()}-${String(e.getUTCMonth()+1).padStart(2,"0")}`}function AO(t){return t.trim().replace(/\s+/g," ").toLowerCase()}function Pi(t){return t?.trim()||"agent"}function or(t,e,r){return Number.isFinite(t)?Math.max(e,Math.min(r,t)):e}function qd(){return{...bO,observationIds:[],proposalIds:[],claimIds:[],conflictIds:[]}}D();import*as Wt from"node:fs";var WR="qmemory-local",Gd=class{providerId=WR;store;embedding;consolidator;userIdPrefix;dbPath;constructor(e){if(this.dbPath=$R(e.ownerUserId),this.userIdPrefix=e.userIdPrefix??"",this.embedding=UR(e.embedding),!e.createDatabase)throw new Error("LocalMemoryProvider requires a createDatabase factory. Install better-sqlite3 and pass: (path) => new Database(path)");e.migrateLegacyMemory&&xO(this.dbPath,e.createDatabase);let r=e.createDatabase(this.dbPath);this.store=new Ti(r),this.consolidator=new Ci(this.store,n=>this.buildEmbedding(n))}resolveUserId(e){return this.userIdPrefix?`${this.userIdPrefix}:${e}`:e}async buildEmbedding(e){if(this.embedding.dimensions!==0)try{let r=await this.embedding.embed(e);return r.length?r:void 0}catch{return}}async search(e,r,n){let o=this.resolveUserId(r),s=n?.limit??10,i=n?.minScore??.1,a=null;if(this.embedding.dimensions>0)try{a=await this.embedding.embed(e)}catch{}let c=Math.min(s*3,50),l=this.store.searchHybrid(e,a,o,c),d=this.rerank(l.map(u=>({id:u.id,text:u.text,score:u.score,category:u.category,metadata:{...u.metadata,createdAt:u.metadata?.createdAt,accessCount:u.metadata?.accessCount}})),{preferredCategories:n?.preferredCategories});for(let u of d.slice(0,3))this.store.recordAccess(u.id);return d.filter(u=>u.score>=i).slice(0,s).map(u=>({blockId:u.id,text:u.text,score:u.score,source:WR,metadata:u.metadata}))}async ingest(e,r,n){let o=this.resolveUserId(r),s=e.filter(i=>i.content?.trim()&&i.content.trim().length>=10).map(i=>({text:i.content,category:"conversation",importance:.4}));await this.consolidator.observe(s,o,{source:n?.source??"turn",sessionId:n?.sessionId??""})}async addText(e,r,n){return this.ingestExtracted([{text:e,category:n?.category??"fact",importance:n?.importance??.6}],r,{...n,source:n?.source??"agent",sessionId:n?.sessionId??""})}async remove(e){return this.store.updateClaimsByMemoryId(e,"archived"),this.store.delete(e)}async update(e,r){let n=this.store.getById(e);if(!n)return!1;let o=r.text?.trim(),s=o&&o!==n.text?await this.buildEmbedding(o):void 0,i=this.store.update(e,{...r,text:o||void 0,embedding:s});return i&&this.store.updateClaimsByMemoryId(e,"superseded"),i}async ingestExtracted(e,r,n){if(e.length===0)return Wd();let o=this.resolveUserId(r);return this.consolidator.commitExtracted(e,o,{source:n?.source??"agent",sessionId:n?.sessionId??""})}async observeExtracted(e,r,n){return e.length===0?Wd():this.consolidator.observe(e,this.resolveUserId(r),{source:n?.source??"agent",sessionId:n?.sessionId??""})}async proposeExtracted(e,r,n){return e.length===0?Wd():this.consolidator.proposeExtracted(e,this.resolveUserId(r),{source:n?.source??"agent",sessionId:n?.sessionId??""})}listClaims(e){return this.store.listClaims(this.resolveUserId(e))}listConflicts(e){return this.store.listConflicts(this.resolveUserId(e))}async triggerDecay(e,r=90){let n=this.resolveUserId(e),o=this.store.runFullDecay(n),s=this.store.enforceCapacityLimit(n,1e4);return o.total+s>10&&(this.store.exportAndPurgeArchived(n,200),this.store.vacuum()),{decayed:o.total+s}}async feedback(e,r){let n=0;for(let o of e)this.store.applyFeedback(o,r)&&n++;return{affected:n}}getProfile(e,r){return this.store.getProfile(this.resolveUserId(e),r)}setProfile(e,r,n){this.store.setProfile(this.resolveUserId(e),r,n)}getAllProfiles(e){return this.store.getAllProfiles(this.resolveUserId(e))}deleteProfile(e,r){return this.store.deleteProfile(this.resolveUserId(e),r)}getTemporalSlice(e,r,n,o){return this.store.getTemporalSlice(this.resolveUserId(e),r,n,o)}getActivitySummary(e,r=7){return this.store.getActivitySummary(this.resolveUserId(e),r)}list(e,r){return this.store.listByUser(this.resolveUserId(e),r?.page??1,r?.pageSize??500,r?.activeOnly??!0)}getAtlas(e,r){return this.store.getAtlas(this.resolveUserId(e),r)}findByEventDate(e,r,n=1){return this.store.findByEventDate(this.resolveUserId(e),r,n)}async findRelatedEvents(e,r,n){let o=this.resolveUserId(r),s=n?.minSimilarity??.55,i=n?.maxSimilarity??.82,a=n?.maxDaysBack??14,c=n?.limit??5;if(this.embedding.dimensions===0)return[];let l;try{l=await this.embedding.embed(e)}catch{return[]}let d=this.store.searchVector(l,o,c*3,s),u=Date.now()-a*864e5;return d.filter(p=>{let m=p.metadata?.cosineSimilarity??p.score,g=p.metadata?.createdAt??0;return m>=s&&m<i&&g>=u}).slice(0,c).map(p=>({id:p.id,text:p.text,score:p.metadata?.cosineSimilarity??p.score,date:new Date(p.metadata?.createdAt??Date.now()).toISOString().slice(0,10)}))}synthesizeTimeline(e,r,n){let o=this.getTemporalSlice(e,r,n);if(o.length===0)return"No memories in this time range.";let s=[];for(let i of o){s.push(`## ${i.date}`);for(let a of i.memories){let c=a.importance>=.7?"*":"-";s.push(`${c} [${a.category}] ${a.text}`)}}return s.join(`
|
|
915
|
+
`)}rerank(e,r){let n=(r?.recencyBoostDays??7)*864e5,o=Date.now(),s=new Set(r?.preferredCategories??[]);return e.map(i=>{let a=i.score,c=i.metadata?.createdAt??0;if(c>0){let d=o-c;d<n&&(a+=.1*(1-d/n))}let l=i.metadata?.accessCount??0;return l>0&&(a+=Math.min(.05,l*.01)),s.size>0&&i.category&&s.has(i.category)&&(a+=.08),{...i,score:Math.min(1,a)}}).sort((i,a)=>a.score-i.score)}async health(){return{status:"healthy",memoryCount:0,dbPath:this.dbPath}}count(e){return this.store.count(this.resolveUserId(e))}async resetUser(e){return this.store.resetUser(this.resolveUserId(e))}close(){this.store.close()}};function KR(t){return new Gd(t)}function xO(t,e){let r=Wu();t===r||!Wt.existsSync(r)||GR(t,e)>0||GR(r,e)===0||(Wt.mkdirSync(CO(t),{recursive:!0}),PO(r,t))}function GR(t,e){let r=null;try{r=e(t),r.pragma("wal_checkpoint(FULL)");let n=r.prepare("SELECT COUNT(*) AS count FROM memories").get();return Number(n?.count??0)}catch{return 0}finally{try{r?.close()}catch{}}}function PO(t,e){for(let r of["","-wal","-shm"]){let n=`${e}${r}`;Wt.existsSync(n)&&Wt.rmSync(n,{force:!0})}for(let r of["","-wal","-shm"]){let n=`${t}${r}`;Wt.existsSync(n)&&Wt.copyFileSync(n,`${e}${r}`)}}function CO(t){return t.replace(/[/\\][^/\\]+$/,"")}function Wd(){return{observationsAdded:0,proposalsAdded:0,claimsAdded:0,conflictsAdded:0,memoriesAdded:0,observationIds:[],proposalIds:[],claimIds:[],conflictIds:[]}}We();D();function zR(t){try{let e=EO();if(e){let r={projectRoot:t.projectRoot,ownerUserId:t.ownerUserId,userIdPrefix:t.userIdPrefix,embedding:t.embedding,createDatabase:e,migrateLegacyMemory:!0};return{provider:KR(r),mode:"local"}}}catch(e){return{provider:null,mode:"none",error:`Local provider failed: ${e.message}`}}return{provider:null,mode:"none",error:"better-sqlite3 not available"}}function EO(){try{let e=IO(import.meta.url)("better-sqlite3"),r=e.default??e;if(typeof r!="function")return null;let n=r;return o=>new n(o)}catch{return null}}function VR(t){let e=process.env.QMEMORY_USER_PREFIX||void 0,r=Br(),o=M().getActiveModel("embedding");if(o){let i=MO({provider:o.provider,apiKey:o.apiKey,model:o.model||"text-embedding-3-small",baseUrl:o.baseUrl}),a={projectRoot:t,ownerUserId:r,userIdPrefix:e,embedding:{api:i}};return o.keyHandle.release({success:!0}),a}let s=_O();return{projectRoot:t,ownerUserId:r,userIdPrefix:e,embedding:s?{api:s}:void 0}}function _O(){let t=XR(process.env.QLOGIC_LLMROUTER_BASE_URL);if(!t)return;let e=process.env.QLOGIC_LLMROUTER_ACCESS_TOKEN?.trim();if(!e)return;let r=parseInt(process.env.QLOGIC_LLMROUTER_EMBEDDING_DIMENSIONS||process.env.QMEMORY_EMBEDDING_DIMENSIONS||"1024",10);return{baseUrl:t,apiKey:e,model:process.env.QLOGIC_LLMROUTER_EMBEDDING_MODEL||"BAAI/bge-m3",dimensions:Number.isFinite(r)?r:1024,format:"openai",timeoutMs:YR()}}function MO(t){return{...FR(t.provider,t.apiKey,{model:t.model,baseUrl:t.baseUrl})??{baseUrl:XR(t.baseUrl)||"",apiKey:t.apiKey,model:t.model,format:"openai"},timeoutMs:YR()}}function XR(t){return t?.trim().replace(/\/+$/,"")??""}function YR(){let t=parseInt(process.env.QMEMORY_EMBEDDING_TIMEOUT_MS||"1500",10);return Number.isFinite(t)&&t>0?t:1500}var JR="memory",QR="Memory",DO=["add","replace","remove","create_file","write_file","read_file","delete_file","list_files","search","remember","temporal","feedback"],ZR={type:"object",properties:{action:{type:"string",enum:DO,description:["Operation to perform:","","INDEX.md operations (project-level notes, always visible in system prompt):","- 'add' - Append a note to INDEX.md","- 'replace' - Replace text in INDEX.md (str_replace semantics)","- 'remove' - Remove text from INDEX.md","","Topic file operations (project-level, on-demand, for longer content):","- 'create_file' - Create a new .md topic file","- 'write_file' - Overwrite an existing topic file","- 'read_file' - Read a topic file","- 'delete_file' - Delete a topic file","- 'list_files' - List all memory topic files","","Long-term memory (user-level, persists across projects):","- 'remember' - Submit a fact/preference/lesson to the memory consolidation pipeline","- 'search' - Search long-term memory + local keyword match","- 'temporal' - Query memories by time range ('what happened last week')","","Feedback:","- 'feedback' - Mark memories as useful/irrelevant/outdated/wrong"].join(`
|
|
915
916
|
`)},content:{type:"string",description:["Content for add/replace/create_file/write_file.","For INDEX.md notes: write concise, factual statements.","For topic files: can be longer (up to 8KB), use markdown formatting."].join(`
|
|
916
917
|
`)},old_text:{type:"string",description:"For 'replace'/'remove': the exact text to find in INDEX.md."},new_text:{type:"string",description:"For 'replace': the replacement text."},file:{type:"string",description:"Filename for file operations (e.g. 'project-notes.md', 'lesson-esbuild.md'). Must be kebab-case .md."},query:{type:"string",description:"For 'search'/'temporal': natural language query to find relevant memories."},days:{type:"number",description:"For 'temporal': look back N days from today (default: 7)."},memory_ids:{type:"array",items:{type:"string"},description:"For 'feedback': IDs of memories to give feedback on."},signal:{type:"string",enum:["useful","irrelevant","outdated","wrong"],description:"For 'feedback': the feedback signal to apply."},category:{type:"string",enum:["preference","personal_fact","lesson","pattern","decision","context"],description:"For 'remember': categorize the memory (helps with future recall precision)."}},required:["action"]},eS=["Manage persistent memory across sessions. Two distinct systems with clear roles:","","## Project memory (INDEX.md + topic files)","Scope: current project / workspace. Visible every turn.","Use for: architecture decisions, file conventions, build commands, known issues, task logs.","Actions: add, replace, remove, create_file, write_file, read_file, delete_file, list_files.","","## Long-term memory (QMemory)","Scope: user-level, persists across all projects. Searched on demand.","Use for: user preferences, personal facts, recurring lessons, communication style, past insights.","Actions: remember, search, temporal, feedback.","","## When to store (guidelines):","- User explicitly says 'remember this' or 'note that' -> submit a high-priority memory candidate","- User states a preference (style, format, tools, habits) -> remember (long-term)","- Project-specific decision or fact -> add/create_file (project memory)","- A debugging lesson or insight that applies broadly -> remember (long-term)","- DO NOT store: trivial/obvious info, one-off questions, transient state","- DO NOT store: information the user did not share or confirm","","## When to recall:","- Use 'search' when you suspect relevant past context exists for the current task","- Use 'temporal' to find what happened in a specific time period","- Memory is auto-recalled each turn - manual search is for deeper queries"].join(`
|
|
917
|
-
`),
|
|
918
|
+
`),NO=[/ignore\s+(previous|all|above|prior)\s+instructions/i,/you\s+are\s+now\s+/i,/do\s+not\s+tell\s+the\s+user/i,/system\s+prompt\s+override/i];function LO(t){return!NO.some(e=>e.test(t))}async function tS(t,e){let{action:r}=t,{memdir:n}=e;if(r==="add"){let o=t.content?.trim();if(!o)return{ok:!1,message:"content is required for 'add'.",action:r};let s=await n.addToIndex(o);return{ok:s.ok,message:s.message,action:r}}if(r==="replace"){let o=t.old_text?.trim(),s=t.new_text?.trim()||t.content?.trim();if(!o)return{ok:!1,message:"old_text is required for 'replace'.",action:r};if(!s)return{ok:!1,message:"new_text (or content) is required for 'replace'.",action:r};let i=await n.replaceInIndex(o,s);return{ok:i.ok,message:i.message,action:r}}if(r==="remove"){let o=t.old_text?.trim();if(!o)return{ok:!1,message:"old_text is required for 'remove'.",action:r};let s=await n.removeFromIndex(o);return{ok:s.ok,message:s.message,action:r}}if(r==="create_file"){let o=t.file?.trim(),s=t.content?.trim();if(!o)return{ok:!1,message:"file is required for 'create_file'.",action:r};if(!s)return{ok:!1,message:"content is required for 'create_file'.",action:r};let i=await n.createFile(o,s);return{ok:i.ok,message:i.message,action:r}}if(r==="write_file"){let o=t.file?.trim(),s=t.content?.trim();if(!o)return{ok:!1,message:"file is required for 'write_file'.",action:r};if(!s)return{ok:!1,message:"content is required for 'write_file'.",action:r};let i=await n.writeFile(o,s);return{ok:i.ok,message:i.message,action:r}}if(r==="read_file"){let o=t.file?.trim();if(!o)return{ok:!1,message:"file is required for 'read_file'.",action:r};let s=await n.readFile(o);return s.ok?{ok:!0,message:s.content,action:r}:{ok:!1,message:s.message,action:r}}if(r==="delete_file"){let o=t.file?.trim();if(!o)return{ok:!1,message:"file is required for 'delete_file'.",action:r};let s=await n.deleteFile(o);return{ok:s.ok,message:s.message,action:r}}if(r==="list_files"){let o=await n.listFiles();if(o.length===0)return{ok:!0,message:"No topic files yet. Use 'create_file' to create one.",action:r};let s=o.map(i=>{let a=(i.size/1024).toFixed(1),c=i.modifiedAt.slice(0,10);return`--${i.name} (${a}KB, ${c})${i.preview?""+i.preview:""}`}).join(`
|
|
918
919
|
`);return{ok:!0,message:`Memory files (${o.length}):
|
|
919
920
|
${s}`,action:r}}if(r==="search"){let o=t.query?.trim();if(!o)return{ok:!1,message:"query is required for 'search'.",action:r};let s=[],i;try{let a=await n.searchLocal(o);a.length>0&&s.push(`## Local Memory
|
|
920
921
|
`+a.map(c=>`--[${c.file}] ${c.snippet}`).join(`
|
|
@@ -922,36 +923,36 @@ ${s}`,action:r}}if(r==="search"){let o=t.query?.trim();if(!o)return{ok:!1,messag
|
|
|
922
923
|
`+a.map((c,l)=>`${l+1}. ${c.text}`).join(`
|
|
923
924
|
`))}catch{}return s.length===0?{ok:!0,message:"No matching memories found.",action:r,results:[]}:{ok:!0,message:s.join(`
|
|
924
925
|
|
|
925
|
-
`),action:r,results:i}}if(r==="remember"){if(!e.localProvider)return{ok:!1,message:"Long-term memory requires local memory provider.",action:r};let o=t.content?.trim();if(!o)return{ok:!1,message:"content is required for 'remember'.",action:r};if(!
|
|
926
|
+
`),action:r,results:i}}if(r==="remember"){if(!e.localProvider)return{ok:!1,message:"Long-term memory requires local memory provider.",action:r};let o=t.content?.trim();if(!o)return{ok:!1,message:"content is required for 'remember'.",action:r};if(!LO(o))return{ok:!1,message:"Content blocked by safety filter.",action:r};if(o.length<10)return{ok:!1,message:"Memory too short - provide a meaningful fact or insight (>=10 chars).",action:r};if(o.length>2e3)return{ok:!1,message:"Memory too long (max 2000 chars). Condense the insight.",action:r};try{return await e.localProvider.addText(o,e.userId,{source:"agent-remember",category:t.category??"lesson",importance:.7}),{ok:!0,message:`Stored to long-term memory: "${o.slice(0,80)}${o.length>80?"...":""}"`,action:r}}catch(s){return{ok:!1,message:`Failed to store: ${s instanceof Error?s.message:String(s)}`,action:r}}}if(r==="temporal"){if(!e.localProvider)return{ok:!1,message:"Temporal query requires local memory provider.",action:r};let o=t.days??7,s=Date.now()-o*864e5;return{ok:!0,message:e.localProvider.synthesizeTimeline(e.userId,s,Date.now()),action:r}}if(r==="feedback"){if(!e.localProvider)return{ok:!1,message:"Feedback requires local memory provider.",action:r};let o=t.memory_ids,s=t.signal;if(!o||o.length===0)return{ok:!1,message:"memory_ids is required for 'feedback'.",action:r};if(!s)return{ok:!1,message:"signal is required for 'feedback' (useful/irrelevant/outdated/wrong).",action:r};let i=await e.localProvider.feedback(o,s);return{ok:!0,message:`Feedback '${s}' applied to ${i.affected} memories.`,action:r}}return{ok:!1,message:`Unknown action: "${r}".`,action:r}}function rS(t,e){return{recallProvider:t,runtimeHookProvider:t,learningSink:t,toolProvider:t,handlerProvider:t,dreamProvider:t,userId:e}}function Kd(t,e){try{let r=VR(t),n=zR(r);if(n.provider)return rS(n.provider,r.ownerUserId||e)}catch{}return rS(null,e)}function nS(t){let e=Kd(t.projectRoot,t.currentUserId);return!e.recallProvider||!e.runtimeHookProvider||!e.userId||(Hu(t.hooks,{memoryProvider:e.recallProvider,localMemoryProvider:e.runtimeHookProvider,userId:e.userId,log:{debug:r=>t.log.debug(r),warn:r=>t.log.warn(r)},getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,llmExtract:async r=>{let n=t.resolveSmallModelClient();if(!n)return null;try{let o="";for await(let s of n.transport.stream({model:n.model,messages:[{role:"user",content:r}],tools:[],maxTokens:512},n.apiKey))s.type==="delta"&&(o+=s.text);return o.trim()||null}catch{return null}}},t.prefetchState),t.log.info("[memory] local provider initialized")),e}function oS(t){K({name:JR,label:QR,description:eS,parameters:ZR,execute:async(e,r)=>{let n=t.memoryUserId?t.memoryProvider??void 0:void 0,o=await tS(r,{memdir:t.memdir,provider:n,localProvider:n,userId:t.memoryUserId});return{content:[{type:"text",text:o.message}],details:{type:"memory",action:o.action,ok:o.ok}}}})}function sS(){return{findTool:ve,getToolManifest:Ie,getToolNames:Jt}}function iS(t){Ck({log:{info:e=>t.log(e),warn:e=>t.log(`[warn] ${e}`),error:e=>t.log(`[error] ${e}`),debug:e=>{t.verbose&&t.log(`[debug] ${e}`)}},onExecProgress:e=>{t.sendNotification("turn.exec_progress",{output:e.output,elapsedTimeSeconds:e.elapsedTimeSeconds,totalLines:e.totalLines,totalBytes:e.totalBytes})}})}var OO="agent",aS=["general","explore","plan","code","research","verify"],jO={type:"object",properties:{agent:{type:"string",enum:["general","explore","plan","code","research","verify"],description:`Sub-agent type to fork:
|
|
926
927
|
- general: Full tool access, any task
|
|
927
928
|
- explore: Read-only codebase exploration (search, read, analyze)
|
|
928
929
|
- plan: Planning mode (explore + produce plan, no writes)
|
|
929
930
|
- code: Coding agent with full tool access
|
|
930
931
|
- research: Web research and information gathering
|
|
931
|
-
- verify: Run tests, check builds, validate changes`},prompt:{type:"string",description:"Detailed task for the sub-agent. The sub-agent shares your conversation history as context (prompt cache shared). Be specific about what information to return in the final response."},description:{type:"string",description:"Short description (3-7 words) for status tracking."},maxTurns:{type:"number",description:"Max turns for the sub-agent. Defaults: general=200, explore=50, plan=80, code=200, research=30, verify=40."},background:{type:"boolean",description:"If true, runs in background and returns a task_id. Poll with task tool. Default: false."}},required:["agent","prompt"],additionalProperties:!1},cS=4;function lS(t){return{name:
|
|
932
|
+
- verify: Run tests, check builds, validate changes`},prompt:{type:"string",description:"Detailed task for the sub-agent. The sub-agent shares your conversation history as context (prompt cache shared). Be specific about what information to return in the final response."},description:{type:"string",description:"Short description (3-7 words) for status tracking."},maxTurns:{type:"number",description:"Max turns for the sub-agent. Defaults: general=200, explore=50, plan=80, code=200, research=30, verify=40."},background:{type:"boolean",description:"If true, runs in background and returns a task_id. Poll with task tool. Default: false."}},required:["agent","prompt"],additionalProperties:!1},cS=4;function lS(t){return{name:OO,label:"Sub-Agent",description:"Fork a sub-agent to handle complex tasks autonomously. Sub-agents share your conversation context (prompt cache) and have isolated tool state. Use for: parallel research, code exploration, testing, delegating large tasks to specialized agents.",parameters:jO,searchHint:"fork subagent delegate spawn child parallel worker",isConcurrencySafe:!0,execute:async(e,r)=>{if(!r.prompt||r.prompt.trim().length<10)return{content:[{type:"text",text:"Error: prompt must be at least 10 characters."}],details:{type:"agent",error:"prompt_too_short"}};if(!aS.includes(r.agent))return{content:[{type:"text",text:`Error: unknown agent "${r.agent}". Available: ${aS.join(", ")}`}],details:{type:"agent",error:"invalid_agent_type"}};let n=t.currentForkDepth??0;if(n>=cS)return{content:[{type:"text",text:`Error: maximum fork depth (${cS}) reached. Cannot spawn more sub-agents. Complete current work instead.`}],details:{type:"agent",error:"max_depth_reached",depth:n}};try{let o=await t.forkAgent({agent:r.agent,prompt:r.prompt.trim(),description:r.description,maxTurns:r.maxTurns,background:r.background,abortSignal:t.abortSignal});if(r.background&&o.status==="running")return{content:[{type:"text",text:`Sub-agent "${r.agent}" started in background.
|
|
932
933
|
Agent ID: ${o.agentId}
|
|
933
934
|
Use task tool with this ID to check status and get output.`}],details:{type:"agent",agentId:o.agentId,status:"running",background:!0}};if(o.status==="failed")return{content:[{type:"text",text:`Sub-agent failed: ${o.error||"unknown error"}`}],details:{type:"agent",agentId:o.agentId,status:"failed",error:o.error}};let s=o.output||"(sub-agent returned no output)",i=o.maxTurnsReached?`
|
|
934
935
|
|
|
935
|
-
[Note: Sub-agent reached turn limit. Output may be incomplete.]`:"";return{content:[{type:"text",text:s+i}],details:{type:"agent",agentId:o.agentId,status:"completed",tokensUsed:o.tokensUsed,maxTurnsReached:o.maxTurnsReached}}}catch(o){let s=o instanceof Error?o.message:String(o);return{content:[{type:"text",text:`Sub-agent execution failed: ${s}`}],details:{type:"agent",error:"execution_error",message:s}}}}}}import{randomUUID as
|
|
936
|
+
[Note: Sub-agent reached turn limit. Output may be incomplete.]`:"";return{content:[{type:"text",text:s+i}],details:{type:"agent",agentId:o.agentId,status:"completed",tokensUsed:o.tokensUsed,maxTurnsReached:o.maxTurnsReached}}}catch(o){let s=o instanceof Error?o.message:String(o);return{content:[{type:"text",text:`Sub-agent execution failed: ${s}`}],details:{type:"agent",error:"execution_error",message:s}}}}}}import{randomUUID as $O}from"node:crypto";function dS({host:t,hooks:e,log:r,toolInvoker:n}){return{abortSignal:void 0,currentForkDepth:0,forkAgent:async o=>{let s=Un(o.agent);if(!s)return{agentId:"",status:"failed",error:`Unknown agent type: ${o.agent}`};if(!t.agent||!t.currentTransport||!t.currentApiKey||!t.currentModel)return{agentId:"",status:"failed",error:"No LLM provider configured"};let i=Jt(),a=Mc(i,s),l=Ie().filter(f=>a.includes(f.function.name)),d=cc(l,!0),u=o.maxTurns??s.maxTurns??200;if(ut.isTeamBudgetExceeded())return{agentId:`fork-${o.agent}-budget-exceeded`,status:"failed",output:void 0,error:ut.teamBudgetExceededError(),tokensUsed:0};let p=await Wr({promptMessages:[{role:"user",content:o.prompt}],tools:d,transport:t.currentTransport,toolInvoker:n,createAgentRunner:Xr,apiKey:t.currentApiKey,model:t.currentModel,log:r,hooks:e,forkLabel:`agent-${o.agent}`,maxTurns:u,parentSignal:o.abortSignal,parentDepth:0,onEvent:f=>{f.type==="delta"&&f.text&&t.sendNotification("turn.subagent_delta",{agentType:o.agent,text:f.text})}}),m=p.events.filter(f=>f.type==="end"&&"content"in f).map(f=>f.content??"").join("")||p.events.filter(f=>f.type==="delta"&&"text"in f).map(f=>f.text).join(""),g=p.totalUsage.inputTokens+p.totalUsage.outputTokens;return ut.recordForkTokens(g),{agentId:`fork-${o.agent}-${$O().slice(0,8)}`,status:p.ok?"completed":"failed",output:m||void 0,error:p.error,tokensUsed:g}}}}function uS({host:t,hooks:e,log:r,toolInvoker:n}){K(lS(dS({host:t,hooks:e,log:r,toolInvoker:n})))}var UO="checkpoint",FO={type:"object",properties:{action:{type:"string",enum:["create","list","restore","diff"],description:"Action: create (snapshot current state), list (show checkpoints), restore (revert to checkpoint), diff (show changes since checkpoint)."},checkpointId:{type:"string",description:"Checkpoint ID. Required for restore and diff."},message:{type:"string",description:"Optional descriptive message for the checkpoint."},paths:{type:"array",items:{type:"string"},description:"File paths to restore (partial restore). Omit to restore everything."}},required:["action"]},pS=/^[0-9a-fA-F]{4,64}$/;function mS(t){return{name:UO,label:"Checkpoint",description:"Manage workspace checkpoints (shadow snapshots independent of user's git). Create snapshots before risky operations, list history, restore on errors, or diff to see what changed. Checkpoints do NOT affect user's .git.",parameters:FO,execute:async(e,r)=>{switch(r.action){case"create":{let n=await t.createCheckpoint(r.message);return n.success?{content:[{type:"text",text:`Checkpoint created: ${n.checkpoint.id}
|
|
936
937
|
Message: ${n.checkpoint.message}
|
|
937
938
|
Files: ${n.checkpoint.fileCount}`}],details:{type:"checkpoint",action:"create",checkpointId:n.checkpoint.id}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"checkpoint",error:n.error}}}case"list":{let n=await t.listCheckpoints();if(!n.checkpoints||n.checkpoints.length===0)return{content:[{type:"text",text:"No checkpoints available."}],details:{type:"checkpoint",action:"list",count:0}};let o=[`Checkpoints (${n.checkpoints.length}):`,""];for(let s of n.checkpoints)o.push(`- ${s.id.slice(0,8)} [${s.timestamp}] ${s.message} (${s.fileCount} files)`);return{content:[{type:"text",text:o.join(`
|
|
938
939
|
`)}],details:{type:"checkpoint",action:"list",count:n.checkpoints.length}}}case"restore":{if(!r.checkpointId)return{content:[{type:"text",text:"Error: checkpointId required for restore."}],details:{type:"checkpoint",error:"missing_id"}};if(!pS.test(r.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let n=await t.restoreCheckpoint(r.checkpointId,r.paths);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"checkpoint",error:n.error}};let o=r.paths?`(${r.paths.length} files)`:"(full workspace)";return{content:[{type:"text",text:`Restored to checkpoint ${r.checkpointId.slice(0,8)} ${o}`}],details:{type:"checkpoint",action:"restore",checkpointId:r.checkpointId}}}case"diff":{if(!r.checkpointId)return{content:[{type:"text",text:"Error: checkpointId required for diff."}],details:{type:"checkpoint",error:"missing_id"}};if(!pS.test(r.checkpointId))return{content:[{type:"text",text:"Error: invalid checkpoint ID format."}],details:{type:"checkpoint",error:"invalid_id"}};let n=await t.diffCheckpoint(r.checkpointId);return n.success?{content:[{type:"text",text:n.diff||"(no changes since checkpoint)"}],details:{type:"checkpoint",action:"diff",checkpointId:r.checkpointId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"checkpoint",error:n.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${r.action}".`}],details:{type:"checkpoint",error:"unknown_action"}}}}}}D();import*as Je from"node:fs";import*as yn from"node:path";function gS(t,e){let r=Qu(t,e);return{createCheckpoint:async n=>{try{Je.mkdirSync(r,{recursive:!0});let{execSync:o}=await import("node:child_process"),s=yn.join(r,".git");Je.existsSync(s)||(o("git init",{cwd:r,stdio:"pipe"}),o('git config user.email "checkpoint@agent"',{cwd:r,stdio:"pipe"}),o('git config user.name "Checkpoint"',{cwd:r,stdio:"pipe"})),Je.cpSync(t,r,{recursive:!0,filter:l=>!l.includes(".git")&&!l.includes("node_modules")}),o("git add -A",{cwd:r,stdio:"pipe"});let i=n||`checkpoint ${new Date().toISOString()}`;o(`git commitallow-empty -m "${i.replace(/"/g,'\\"')}"`,{cwd:r,stdio:"pipe"});let a=o("git rev-parse HEAD",{cwd:r,stdio:"pipe"}).toString().trim(),c=parseInt(o("git ls-files | wc -l",{cwd:r,stdio:"pipe"}).toString().trim(),10)||0;return{success:!0,checkpoint:{id:a,message:i,timestamp:new Date().toISOString(),fileCount:c}}}catch(o){return{success:!1,error:o.message}}},listCheckpoints:async()=>{try{let{execSync:n}=await import("node:child_process"),o=yn.join(r,".git");if(!Je.existsSync(o))return{success:!0,checkpoints:[]};let s=n('git logformat="%H|%aI|%s"max-count=20',{cwd:r,stdio:"pipe"}).toString().trim();return s?{success:!0,checkpoints:s.split(`
|
|
939
|
-
`).map(a=>{let[c="",l="",...d]=a.split("|");return{id:c,timestamp:l,message:d.join("|"),fileCount:0}})}:{success:!0,checkpoints:[]}}catch(n){return{success:!1,error:n.message}}},restoreCheckpoint:async(n,o)=>{try{let{execSync:s}=await import("node:child_process");if(o&&o.length>0){s(`git checkout ${n} ${o.map(i=>`"${i.replace(/"/g,'\\"')}"`).join(" ")}`,{cwd:r,stdio:"pipe"});for(let i of o){let a=yn.join(r,i),c=yn.join(t,i);Je.existsSync(a)&&Je.cpSync(a,c,{recursive:!0})}}else{s(`git checkout ${n} .`,{cwd:r,stdio:"pipe"});let i=Je.readdirSync(t);for(let a of i){if(a===".git"||a==="node_modules")continue;let c=yn.join(t,a);Je.rmSync(c,{recursive:!0,force:!0})}Je.cpSync(r,t,{recursive:!0,filter:a=>!a.includes(".git")})}return{success:!0}}catch(s){return{success:!1,error:s.message}}},diffCheckpoint:async n=>{try{let{execSync:o}=await import("node:child_process");return{success:!0,diff:o(`git diff ${n} HEAD`,{cwd:r,stdio:"pipe"}).toString()}}catch(o){return{success:!1,error:o.message}}}}}function fS(t){let e=typeof t.config.workdir=="string"?t.config.workdir:t.cwd??process.cwd();return gS(e,t.sessionId||"default")}function hS({config:t,host:e}){K(mS(fS({config:t,sessionId:e.currentSessionId})))}var
|
|
940
|
+
`).map(a=>{let[c="",l="",...d]=a.split("|");return{id:c,timestamp:l,message:d.join("|"),fileCount:0}})}:{success:!0,checkpoints:[]}}catch(n){return{success:!1,error:n.message}}},restoreCheckpoint:async(n,o)=>{try{let{execSync:s}=await import("node:child_process");if(o&&o.length>0){s(`git checkout ${n} ${o.map(i=>`"${i.replace(/"/g,'\\"')}"`).join(" ")}`,{cwd:r,stdio:"pipe"});for(let i of o){let a=yn.join(r,i),c=yn.join(t,i);Je.existsSync(a)&&Je.cpSync(a,c,{recursive:!0})}}else{s(`git checkout ${n} .`,{cwd:r,stdio:"pipe"});let i=Je.readdirSync(t);for(let a of i){if(a===".git"||a==="node_modules")continue;let c=yn.join(t,a);Je.rmSync(c,{recursive:!0,force:!0})}Je.cpSync(r,t,{recursive:!0,filter:a=>!a.includes(".git")})}return{success:!0}}catch(s){return{success:!1,error:s.message}}},diffCheckpoint:async n=>{try{let{execSync:o}=await import("node:child_process");return{success:!0,diff:o(`git diff ${n} HEAD`,{cwd:r,stdio:"pipe"}).toString()}}catch(o){return{success:!1,error:o.message}}}}}function fS(t){let e=typeof t.config.workdir=="string"?t.config.workdir:t.cwd??process.cwd();return gS(e,t.sessionId||"default")}function hS({config:t,host:e}){K(mS(fS({config:t,sessionId:e.currentSessionId})))}var HO="config",BO={type:"object",properties:{action:{type:"string",enum:["get","set","list","reset"],description:`Action:
|
|
940
941
|
- get: Read a config setting
|
|
941
942
|
- set: Write a config setting
|
|
942
943
|
- list: List all available settings
|
|
943
|
-
- reset: Reset a setting to default`},key:{type:"string",description:"Config key path (e.g. 'model', 'language', 'theme', 'permissions.defaultMode'). Required for get/set/reset."},value:{description:"Value to set. Type depends on the setting. Required for 'set' action."}},required:["action"]},yo=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function yS(t){return{name:
|
|
944
|
+
- reset: Reset a setting to default`},key:{type:"string",description:"Config key path (e.g. 'model', 'language', 'theme', 'permissions.defaultMode'). Required for get/set/reset."},value:{description:"Value to set. Type depends on the setting. Required for 'set' action."}},required:["action"]},yo=["permissions.securityPolicy","api.key","api.secret","auth.token","system.adminMode"];function yS(t){return{name:HO,label:"Config",description:"Read and write agent configuration settings. Supports preferences like model selection, language, theme, tool enablement, etc. Security-critical settings (API keys, permissions) are read-only. Changes persist across sessions.",parameters:BO,execute:async(e,r)=>{switch(r.action){case"get":{if(!r.key)return{content:[{type:"text",text:"Error: key is required for get."}],details:{type:"config",error:"missing_key"}};if(t.isValidKey&&!t.isValidKey(r.key))return{content:[{type:"text",text:`Error: unknown config key "${r.key}". Use action='list' to see available settings.`}],details:{type:"config",error:"unknown_key"}};let n=await t.getConfig(r.key);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}};let o=n.setting,s=[`${o.key} = ${JSON.stringify(o.value)}`,` Type: ${o.type}${o.options?` (${o.options.join(" | ")})`:""}`,` ${o.description}`];return o.readOnly&&s.push(" \u26A0\uFE0F Read-only (cannot be changed)"),{content:[{type:"text",text:s.join(`
|
|
944
945
|
`)}],details:{type:"config",action:"get",key:r.key,value:o.value}}}case"set":{if(!r.key)return{content:[{type:"text",text:"Error: key is required for set."}],details:{type:"config",error:"missing_key"}};if(r.value===void 0)return{content:[{type:"text",text:"Error: value is required for set."}],details:{type:"config",error:"missing_value"}};if(yo.includes(r.key))return{content:[{type:"text",text:`Error: "${r.key}" is a security-critical setting and cannot be modified.`}],details:{type:"config",error:"readonly_key"}};if(t.isValidKey&&!t.isValidKey(r.key))return{content:[{type:"text",text:`Error: unknown config key "${r.key}".`}],details:{type:"config",error:"unknown_key"}};let n=await t.setConfig(r.key,r.value);return n.success?{content:[{type:"text",text:`Updated "${r.key}": ${JSON.stringify(n.previousValue)} \u2192 ${JSON.stringify(r.value)}`}],details:{type:"config",action:"set",key:r.key,previousValue:n.previousValue,newValue:r.value}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}}}case"list":{let n=await t.listConfig();if(!n.settings||n.settings.length===0)return{content:[{type:"text",text:"No config settings available."}],details:{type:"config",action:"list",count:0}};let o=[`Available settings (${n.settings.length}):`,""];for(let s of n.settings){let i=s.readOnly?" [read-only]":"",a=JSON.stringify(s.value);o.push(` ${s.key} = ${a}${i}`),o.push(` ${s.description}`)}return{content:[{type:"text",text:o.join(`
|
|
945
|
-
`)}],details:{type:"config",action:"list",count:n.settings.length}}}case"reset":{if(!r.key)return{content:[{type:"text",text:"Error: key is required for reset."}],details:{type:"config",error:"missing_key"}};if(yo.includes(r.key))return{content:[{type:"text",text:`Error: "${r.key}" cannot be reset (security-critical).`}],details:{type:"config",error:"readonly_key"}};let n=await t.resetConfig(r.key);return n.success?{content:[{type:"text",text:`Reset "${r.key}" to default: ${JSON.stringify(n.setting?.value)}`}],details:{type:"config",action:"reset",key:r.key,value:n.setting?.value}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${r.action}".`}],details:{type:"config",error:"unknown_action"}}}}}}D();import*as Ii from"node:fs";import*as bS from"node:path";function vS(t){let e=t.configFilePath??de(),r=new Map([["model",{key:"model",value:t.currentModel??"",type:"string",description:"Default LLM model"}],["language",{key:"language",value:"zh-cn",type:"string",description:"UI / response language"}],["verbose",{key:"verbose",value:t.verbose,type:"boolean",description:"Enable verbose logging"}],["maxRounds",{key:"maxRounds",value:25,type:"number",description:"Default max tool-call rounds per turn"}],["theme",{key:"theme",value:"auto",type:"enum",description:"Color theme",options:["auto","light","dark"]}]]),n=async()=>{try{return JSON.parse(await Ii.promises.readFile(e,"utf8"))}catch{return{}}},o=async s=>{await Ii.promises.mkdir(bS.dirname(e),{recursive:!0}),await Ii.promises.writeFile(e,JSON.stringify(s,null,2),"utf8")};return{getConfig:async s=>{let i=r.get(s);if(!i)return{success:!1,error:`Unknown key: ${s}`};let a=await n(),c=s in a?a[s]:i.value;return{success:!0,setting:{...i,value:c,readOnly:yo.includes(s)}}},setConfig:async(s,i)=>{let a=r.get(s);if(!a)return{success:!1,error:`Unknown key: ${s}`};let c=await n(),l=s in c?c[s]:a.value;return c[s]=i,await o(c),{success:!0,previousValue:l,setting:{...a,value:i}}},listConfig:async()=>{let s=await n();return{success:!0,settings:[...r.values()].map(a=>({...a,value:a.key in s?s[a.key]:a.value,readOnly:yo.includes(a.key)}))}},resetConfig:async s=>{let i=r.get(s);if(!i)return{success:!1,error:`Unknown key: ${s}`};let a=await n();return delete a[s],await o(a),{success:!0,setting:i}},isValidKey:s=>r.has(s)}}function kS({host:t}){K(yS(vS({currentModel:t.currentModel,verbose:t.verbose})))}var
|
|
946
|
+
`)}],details:{type:"config",action:"list",count:n.settings.length}}}case"reset":{if(!r.key)return{content:[{type:"text",text:"Error: key is required for reset."}],details:{type:"config",error:"missing_key"}};if(yo.includes(r.key))return{content:[{type:"text",text:`Error: "${r.key}" cannot be reset (security-critical).`}],details:{type:"config",error:"readonly_key"}};let n=await t.resetConfig(r.key);return n.success?{content:[{type:"text",text:`Reset "${r.key}" to default: ${JSON.stringify(n.setting?.value)}`}],details:{type:"config",action:"reset",key:r.key,value:n.setting?.value}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"config",error:n.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${r.action}".`}],details:{type:"config",error:"unknown_action"}}}}}}D();import*as Ii from"node:fs";import*as bS from"node:path";function vS(t){let e=t.configFilePath??de(),r=new Map([["model",{key:"model",value:t.currentModel??"",type:"string",description:"Default LLM model"}],["language",{key:"language",value:"zh-cn",type:"string",description:"UI / response language"}],["verbose",{key:"verbose",value:t.verbose,type:"boolean",description:"Enable verbose logging"}],["maxRounds",{key:"maxRounds",value:25,type:"number",description:"Default max tool-call rounds per turn"}],["theme",{key:"theme",value:"auto",type:"enum",description:"Color theme",options:["auto","light","dark"]}]]),n=async()=>{try{return JSON.parse(await Ii.promises.readFile(e,"utf8"))}catch{return{}}},o=async s=>{await Ii.promises.mkdir(bS.dirname(e),{recursive:!0}),await Ii.promises.writeFile(e,JSON.stringify(s,null,2),"utf8")};return{getConfig:async s=>{let i=r.get(s);if(!i)return{success:!1,error:`Unknown key: ${s}`};let a=await n(),c=s in a?a[s]:i.value;return{success:!0,setting:{...i,value:c,readOnly:yo.includes(s)}}},setConfig:async(s,i)=>{let a=r.get(s);if(!a)return{success:!1,error:`Unknown key: ${s}`};let c=await n(),l=s in c?c[s]:a.value;return c[s]=i,await o(c),{success:!0,previousValue:l,setting:{...a,value:i}}},listConfig:async()=>{let s=await n();return{success:!0,settings:[...r.values()].map(a=>({...a,value:a.key in s?s[a.key]:a.value,readOnly:yo.includes(a.key)}))}},resetConfig:async s=>{let i=r.get(s);if(!i)return{success:!1,error:`Unknown key: ${s}`};let a=await n();return delete a[s],await o(a),{success:!0,setting:i}},isValidKey:s=>r.has(s)}}function kS({host:t}){K(yS(vS({currentModel:t.currentModel,verbose:t.verbose})))}var qO="cron",WO={type:"object",properties:{action:{type:"string",enum:["create","list","get","update","delete","pause","resume","trigger"],description:"Workflow-backed action: create/list/get/update/delete/pause/resume/trigger."},jobId:{type:"string",description:"Job ID. Required for get/update/delete/pause/resume/trigger."},prompt:{type:"string",description:"Task prompt to execute on schedule. Required for create."},schedule:{type:"string",description:"Schedule expression for the unified workflow scheduler. Supports cron ('0 9 * * *') and shorthand ('5m', '1h', '1d'). Required for create."},name:{type:"string",description:"Human-readable job name."},repeat:{type:"number",description:"Deprecated. Finite repeats must be modeled inside the workflow graph."},allowedTools:{type:"array",items:{type:"string"},description:"Deprecated. Tool access must be enforced by permission rules or workflow nodes."},enabled:{type:"boolean",description:"Whether the job is enabled (for update)."}},required:["action"]},RS=50;function SS(t){return{name:qO,label:"Cron",description:"Thin entry point for scheduled workflows. Create recurring agent workflows with cron expressions or shorthand ('5m', '1h', '0 9 * * *'). Jobs persist in .qlogicagent/workflows. Actions: create, list, get, update, delete, pause, resume, trigger (run now).",parameters:WO,execute:async(e,r)=>{switch(r.action){case"create":{if(!r.prompt)return{content:[{type:"text",text:"Error: prompt is required for create."}],details:{type:"cron",error:"missing_prompt"}};if(!r.schedule)return{content:[{type:"text",text:"Error: schedule is required for create."}],details:{type:"cron",error:"missing_schedule"}};if(t.validateSchedule){let s=t.validateSchedule(r.schedule);if(s)return{content:[{type:"text",text:`Error: invalid schedule \u2014 ${s}`}],details:{type:"cron",error:"invalid_schedule"}}}let n=await t.listJobs();if(n.jobs&&n.jobs.length>=RS)return{content:[{type:"text",text:`Error: maximum ${RS} jobs reached. Delete unused jobs first.`}],details:{type:"cron",error:"max_jobs_reached"}};let o=await t.createJob({prompt:r.prompt,schedule:r.schedule,name:r.name,repeat:r.repeat,allowedTools:r.allowedTools});return o.success?{content:[{type:"text",text:zd(o.job)}],details:{type:"cron",action:"create",jobId:o.job.id}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"list":{let n=await t.listJobs();if(!n.jobs||n.jobs.length===0)return{content:[{type:"text",text:"No scheduled jobs."}],details:{type:"cron",action:"list",count:0}};let o=[`Scheduled jobs (${n.jobs.length}):`,""];for(let s of n.jobs)o.push(`- **${s.name||s.id}** [${s.state}] ${s.scheduleDisplay} \u2014 next: ${s.nextRunAt||"N/A"}`);return{content:[{type:"text",text:o.join(`
|
|
946
947
|
`)}],details:{type:"cron",action:"list",count:n.jobs.length}}}case"get":{if(!r.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await t.getJob(r.jobId);return n.success?{content:[{type:"text",text:zd(n.job)}],details:{type:"cron",action:"get",jobId:r.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"update":{if(!r.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n={};r.prompt!==void 0&&(n.prompt=r.prompt),r.schedule!==void 0&&(n.schedule=r.schedule),r.name!==void 0&&(n.name=r.name),r.enabled!==void 0&&(n.enabled=r.enabled),r.repeat!==void 0&&(n.repeat=r.repeat),r.allowedTools!==void 0&&(n.allowedTools=r.allowedTools);let o=await t.updateJob(r.jobId,n);return o.success?{content:[{type:"text",text:`Job updated.
|
|
947
948
|
${zd(o.job)}`}],details:{type:"cron",action:"update",jobId:r.jobId}}:{content:[{type:"text",text:`Error: ${o.error}`}],details:{type:"cron",error:o.error}}}case"delete":{if(!r.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await t.deleteJob(r.jobId);return n.success?{content:[{type:"text",text:`Job ${r.jobId} deleted.`}],details:{type:"cron",action:"delete",jobId:r.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"pause":{if(!r.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await t.pauseJob(r.jobId);return n.success?{content:[{type:"text",text:`Job ${r.jobId} paused.`}],details:{type:"cron",action:"pause",jobId:r.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"resume":{if(!r.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await t.resumeJob(r.jobId);return n.success?{content:[{type:"text",text:`Job ${r.jobId} resumed.`}],details:{type:"cron",action:"resume",jobId:r.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}case"trigger":{if(!r.jobId)return{content:[{type:"text",text:"Error: jobId required."}],details:{type:"cron",error:"missing_jobId"}};let n=await t.triggerJob(r.jobId);return n.success?{content:[{type:"text",text:`Job ${r.jobId} triggered (running now).`}],details:{type:"cron",action:"trigger",jobId:r.jobId}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"cron",error:n.error}}}default:return{content:[{type:"text",text:`Error: unknown action "${r.action}".`}],details:{type:"cron",error:"unknown_action"}}}}}}function zd(t){let e=[`Job: ${t.name||t.id}`,`ID: ${t.id}`,`Schedule: ${t.scheduleDisplay} (${t.schedule})`,`State: ${t.state}`,`Repeat: ${t.repeat.times===null?"infinite":`${t.repeat.completed}/${t.repeat.times}`}`];return t.nextRunAt&&e.push(`Next run: ${t.nextRunAt}`),t.lastRunAt&&e.push(`Last run: ${t.lastRunAt} (${t.lastStatus||"unknown"})`),e.push(`Prompt: ${t.prompt.slice(0,100)}${t.prompt.length>100?"...":""}`),e.join(`
|
|
948
|
-
`)}import{randomUUID as
|
|
949
|
-
`),parameters:
|
|
949
|
+
`)}import{randomUUID as GO}from"node:crypto";var KO=()=>{throw new Error("cron workflow service: running requires the initialized workflow engine")};function TS(t){let e=t.idFactory??(()=>GO().slice(0,8));function r(){let n=new ur(t.getProjectRoot()),o=qs();return{controller:new dr(n,KO),live:o,store:n}}return{async createJob(n){let o=wS(n);if(o)return o;let s=Vd(n.schedule),i=Xd(s);if(i)return{success:!1,error:i};let a=`cron_${e().slice(0,8)}`,c=n.name??`Scheduled task ${a}`,l=zO(a,n.prompt),{controller:d,store:u}=r();try{await d.create({id:a,name:c,def:l,active:!1,concurrency:"queue"}),await d.patch(a,{patch:[{op:"set_trigger",trigger:{type:"schedule",cron:s}},{op:"set_meta",meta:{active:!0}}]});let p=await u.require(a);return{success:!0,job:$r(p)}}catch(p){throw await u.delete(a),p}},async listJobs(){return{success:!0,jobs:(await r().store.list()).filter(AS).map(o=>$r(o))}},async getJob(n){let o=await bn(r().store,n);return o?{success:!0,job:$r(o)}:{success:!1,error:`Scheduled workflow not found: ${n}`}},async updateJob(n,o){let s=wS(o);if(s)return s;let{controller:i,store:a}=r(),c=await bn(a,n);if(!c)return{success:!1,error:`Scheduled workflow not found: ${n}`};let l=[],d,u;if(o.prompt!==void 0&&(d=VO(c.def,o.prompt)),o.name!==void 0&&(u=o.name),o.schedule!==void 0){let p=Vd(o.schedule),m=Xd(p);if(m)return{success:!1,error:m};l.push({op:"set_trigger",trigger:{type:"schedule",cron:p}})}return o.enabled!==void 0&&l.push({op:"set_meta",meta:{active:o.enabled}}),(d||u!==void 0)&&await i.update(n,{def:d,name:u}),l.length>0&&await i.patch(n,{patch:l}),{success:!0,job:$r(await a.require(n))}},async deleteJob(n){let{store:o}=r();return await bn(o,n)?(await o.delete(n),{success:!0}):{success:!1,error:`Scheduled workflow not found: ${n}`}},async pauseJob(n){let{controller:o,store:s}=r();return await bn(s,n)?{success:!0,job:$r(await o.setActive(n,!1))}:{success:!1,error:`Scheduled workflow not found: ${n}`}},async resumeJob(n){let{controller:o,store:s}=r();return await bn(s,n)?{success:!0,job:$r(await o.setActive(n,!0))}:{success:!1,error:`Scheduled workflow not found: ${n}`}},async triggerJob(n){let{live:o,store:s}=r(),i=await bn(s,n);if(!i)return{success:!1,error:`Scheduled workflow not found: ${n}`};if(!o)throw new Error("cron trigger requires the initialized workflow engine; activate/run from the app host");let a={type:"manual",payload:{source:"cron.trigger"}},c=await o.run(n,a);return{success:!0,job:$r(i,c.status==="completed"?"success":"error")}},validateSchedule(n){return Xd(Vd(n))}}}function zO(t,e){return{id:t,nodes:[{id:"trigger",kind:"trigger",name:"Schedule trigger"},{id:"agent",kind:"agent",name:"Run prompt",params:{prompt:e}}],edges:[{from:"trigger",to:"agent"}]}}function VO(t,e){let r=t.nodes.map(n=>n.kind!=="agent"?n:{...n,params:{...n.params??{},prompt:e}});if(!r.some(n=>n.kind==="agent"))throw new Error(`Scheduled workflow "${t.id}" has no agent node to update`);return{...t,nodes:r}}function XO(t){let r=t.nodes.find(n=>n.kind==="agent")?.params?.prompt;return typeof r=="string"?r:""}function Vd(t){let e=t.trim(),r=/^(\d+)([smhd])$/.exec(e);if(!r)return e;let n=Number(r[1]),o=r[2];if(!Number.isInteger(n)||n<=0)return e;switch(o){case"s":return`*/${n} * * * * *`;case"m":return`*/${n} * * * *`;case"h":return`0 */${n} * * *`;case"d":return`0 0 */${n} * *`;default:return e}}function Xd(t){let e=Ol(t);return e.length===0?null:e.join("; ")}function AS(t){return t.trigger?.type==="schedule"}async function bn(t,e){let r=await t.load(e);return r&&AS(r)?r:void 0}function $r(t,e=null){let r=t.trigger?.type==="schedule"?t.trigger.cron:"";return{id:t.id,name:t.name,prompt:XO(t.def),schedule:r,scheduleDisplay:r,state:t.active?"scheduled":"paused",enabled:t.active,repeat:{times:null,completed:0},lastStatus:e}}function wS(t){return t.repeat!==void 0&&t.repeat!==null?{success:!1,error:"repeat is not a cron-layer field in the unified workflow scheduler; model finite repeats inside the workflow graph"}:t.allowedTools!==void 0&&t.allowedTools.length>0?{success:!1,error:"allowedTools is not a cron-layer field in the unified workflow scheduler; enforce tool access through permission rules or workflow nodes"}:null}function xS({host:t}){let e=TS({getProjectRoot:()=>t.getActiveProjectRoot()});K(SS(e))}var YO="monitor",JO={type:"object",properties:{action:{type:"string",enum:["start","stop","list"],description:"Action to perform: start a new monitor, stop an existing one, or list active monitors."},monitorId:{type:"string",description:"Identifier for the monitor instance. Required for start/stop."},source:{type:"string",enum:["process","file","task","custom"],description:"Type of event source to watch."},target:{type:"string",description:"Selector for the monitored target. For process: PID or background job id. For file: glob pattern. For task: task ID. For custom: host-defined key."},conditions:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["exit","output_match","file_changed","task_status"]},value:{type:"string"}},required:["type"]},description:"Conditions that trigger a wake-up notification."},timeoutSeconds:{type:"number",description:"Auto-stop after this many seconds (default: 3600).",minimum:1,maximum:86400}},required:["action"]};function PS(t){return{name:YO,label:"Monitor",shouldDefer:!0,description:["Set up event-driven monitoring to wake up when something happens.","","Use this to watch for:","\u2022 Background process completion or specific output patterns","\u2022 File system changes (new file, modification)","\u2022 Async task state transitions (pending \u2192 completed/failed)","\u2022 Custom host-defined events","","When a monitored condition triggers, you'll receive a notification in your next tick.","This is more efficient than polling with Sleep \u2014 you only wake up when there's work to do.","","Actions:","\u2022 start \u2014 register a new monitor (requires monitorId, source, target)","\u2022 stop \u2014 deregister an active monitor","\u2022 list \u2014 show all active monitors and their event counts"].join(`
|
|
950
|
+
`),parameters:JO,execute:async(e,r)=>{let{action:n}=r;if(n==="list"){let i=await t.listMonitors();return i.length===0?{content:[{type:"text",text:"No active monitors."}],details:{action:n,monitors:[]}}:{content:[{type:"text",text:`Active monitors:
|
|
950
951
|
${i.map(c=>`\u2022 ${c.monitorId} [${c.source}] \u2192 ${c.target} (events: ${c.eventCount}, timeout: ${c.timeoutSeconds}s)`).join(`
|
|
951
|
-
`)}`}],details:{action:n,monitors:i}}}if(!r.monitorId)return{content:[{type:"text",text:"Error: monitorId is required for start/stop."}],details:{action:n,success:!1,error:"missing_monitor_id"}};if(n==="stop"){let i=await t.stopMonitor(r.monitorId);return{content:[{type:"text",text:i.success?`Monitor "${r.monitorId}" stopped.`:`Failed to stop monitor "${r.monitorId}": ${i.error??"not found"}`}],details:{...i}}}if(!r.source||!r.target)return{content:[{type:"text",text:"Error: source and target are required to start a monitor."}],details:{action:n,success:!1,error:"missing_source_or_target"}};let o=await t.startMonitor({monitorId:r.monitorId,source:r.source,target:r.target,conditions:r.conditions??[],timeoutSeconds:r.timeoutSeconds??3600});return{content:[{type:"text",text:o.success?`Monitor "${r.monitorId}" started: watching ${r.source} "${r.target}".`:`Failed to start monitor: ${o.error??"unknown"}`}],details:{...o}}}}}import*as CS from"node:fs";function IS(t){let e=new Map;return{async startMonitor(r){if(e.has(r.monitorId))return{action:"start",success:!1,error:`Monitor "${r.monitorId}" already exists.`};let n={monitorId:r.monitorId,source:r.source,target:r.target,conditions:r.conditions,startedAt:Date.now(),timeoutSeconds:r.timeoutSeconds,eventCount:0},o=()=>{};if(r.source==="file")try{let s=CS.watch(r.target,{persistent:!1},()=>{n.eventCount++,t.info(`[monitor] file change detected: ${r.target}`)});o=()=>s.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${r.target}`}}if(r.timeoutSeconds>0){let s=setTimeout(()=>{let a=e.get(r.monitorId);a&&(a.cleanup(),e.delete(r.monitorId))},r.timeoutSeconds*1e3),i=o;o=()=>{clearTimeout(s),i()}}return e.set(r.monitorId,{info:n,cleanup:o}),{action:"start",success:!0,monitorId:r.monitorId}},async stopMonitor(r){let n=e.get(r);return n?(n.cleanup(),e.delete(r),{action:"stop",success:!0,monitorId:r}):{action:"stop",success:!1,error:`Monitor "${r}" not found.`}},async listMonitors(){return[...e.values()].map(r=>r.info)},dispose(){for(let r of e.values())r.cleanup();e.clear()}}}function ES({log:t}){let e=IS(t);
|
|
952
|
+
`)}`}],details:{action:n,monitors:i}}}if(!r.monitorId)return{content:[{type:"text",text:"Error: monitorId is required for start/stop."}],details:{action:n,success:!1,error:"missing_monitor_id"}};if(n==="stop"){let i=await t.stopMonitor(r.monitorId);return{content:[{type:"text",text:i.success?`Monitor "${r.monitorId}" stopped.`:`Failed to stop monitor "${r.monitorId}": ${i.error??"not found"}`}],details:{...i}}}if(!r.source||!r.target)return{content:[{type:"text",text:"Error: source and target are required to start a monitor."}],details:{action:n,success:!1,error:"missing_source_or_target"}};let o=await t.startMonitor({monitorId:r.monitorId,source:r.source,target:r.target,conditions:r.conditions??[],timeoutSeconds:r.timeoutSeconds??3600});return{content:[{type:"text",text:o.success?`Monitor "${r.monitorId}" started: watching ${r.source} "${r.target}".`:`Failed to start monitor: ${o.error??"unknown"}`}],details:{...o}}}}}import*as CS from"node:fs";function IS(t){let e=new Map;return{async startMonitor(r){if(e.has(r.monitorId))return{action:"start",success:!1,error:`Monitor "${r.monitorId}" already exists.`};let n={monitorId:r.monitorId,source:r.source,target:r.target,conditions:r.conditions,startedAt:Date.now(),timeoutSeconds:r.timeoutSeconds,eventCount:0},o=()=>{};if(r.source==="file")try{let s=CS.watch(r.target,{persistent:!1},()=>{n.eventCount++,t.info(`[monitor] file change detected: ${r.target}`)});o=()=>s.close()}catch{return{action:"start",success:!1,error:`Cannot watch: ${r.target}`}}if(r.timeoutSeconds>0){let s=setTimeout(()=>{let a=e.get(r.monitorId);a&&(a.cleanup(),e.delete(r.monitorId))},r.timeoutSeconds*1e3),i=o;o=()=>{clearTimeout(s),i()}}return e.set(r.monitorId,{info:n,cleanup:o}),{action:"start",success:!0,monitorId:r.monitorId}},async stopMonitor(r){let n=e.get(r);return n?(n.cleanup(),e.delete(r),{action:"stop",success:!0,monitorId:r}):{action:"stop",success:!1,error:`Monitor "${r}" not found.`}},async listMonitors(){return[...e.values()].map(r=>r.info)},dispose(){for(let r of e.values())r.cleanup();e.clear()}}}function ES({log:t}){let e=IS(t);Vt(async()=>e.dispose()),K(PS(e))}var QO="team",ZO={type:"object",properties:{action:{type:"string",enum:["create","delete","list","status"],description:"Team action: create (new team), delete (disband), list (all teams), status (team details)."},teamName:{type:"string",description:"Team name. Required for create/delete/status."},description:{type:"string",description:"Team description/objective. Used for create."},members:{type:"array",description:"Team members with roles and tool restrictions.",items:{type:"object",properties:{name:{type:"string",description:"Agent name/role identifier."},role:{type:"string",description:"Role description (e.g. 'frontend developer')."},tools:{type:"array",items:{type:"string"},description:"Allowed tools for this member."}},required:["name","role"]}}},required:["action"]};function _S(t){return{name:QO,label:"Team",description:"Manage multi-agent teams. Create teams of specialized agents that collaborate via send_message. Each member has a role and optional tool restrictions. Use for complex tasks requiring parallel work.",parameters:ZO,execute:async(e,r)=>{switch(r.action){case"create":{if(!r.teamName)return{content:[{type:"text",text:"Error: teamName required for create."}],details:{type:"team",error:"missing_name"}};let n=await t.createTeam({teamName:r.teamName,description:r.description,members:r.members});if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}};let o=[`Team "${n.team.name}" created.`,`Lead: ${n.team.leadId}`,`Members: ${n.team.members.length}`];for(let s of n.team.members)o.push(` - ${s.name} (${s.role})`);return{content:[{type:"text",text:o.join(`
|
|
952
953
|
`)}],details:{type:"team",action:"create",teamName:n.team.name}}}case"delete":{if(!r.teamName)return{content:[{type:"text",text:"Error: teamName required for delete."}],details:{type:"team",error:"missing_name"}};let n=await t.deleteTeam(r.teamName);return n.success?{content:[{type:"text",text:`Team "${r.teamName}" disbanded.`}],details:{type:"team",action:"delete",teamName:r.teamName}}:{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}}}case"list":{let n=await t.listTeams();if(!n.teams||n.teams.length===0)return{content:[{type:"text",text:"No active teams."}],details:{type:"team",action:"list",count:0}};let o=[`Active teams (${n.teams.length}):`,""];for(let s of n.teams)o.push(`- **${s.name}**: ${s.description||"(no description)"} \u2014 ${s.members.length} members`);return{content:[{type:"text",text:o.join(`
|
|
953
954
|
`)}],details:{type:"team",action:"list",count:n.teams.length}}}case"status":{if(!r.teamName)return{content:[{type:"text",text:"Error: teamName required for status."}],details:{type:"team",error:"missing_name"}};let n=await t.getTeamStatus(r.teamName);if(!n.success)return{content:[{type:"text",text:`Error: ${n.error}`}],details:{type:"team",error:n.error}};let o=n.team,s=n.memberProgress??{},i=[`Team: ${o.name}`,`Description: ${o.description||"\u2014"}`,`Lead: ${o.leadId}`,`Created: ${o.createdAt}`,"",`Members (${o.members.length}):`];for(let a of o.members){let c=a.tools?` [tools: ${a.tools.join(", ")}]`:"",l=a.worktreePath?` [worktree: ${a.worktreePath}]`:a.cwd?` [cwd: ${a.cwd}]`:"",d=s[a.name],u=a.isActive===!1?" (idle)":" (active)";if(d){let p=[];if(d.runningFor&&p.push(`running ${Math.round(d.runningFor/1e3)}s`),d.lastToolCall&&p.push(`tool: ${d.lastToolCall}`),d.idleFor!==void 0&&d.idleFor>5&&p.push(`idle ${d.idleFor}s`),d.mediaProgress){let m=d.mediaProgress;p.push(`${m.mediaType} ${m.percent}% [${m.status}] taskId=${m.taskId}${m.provider?` provider=${m.provider}`:""}`)}p.length&&(u=` (${p.join(", ")})`)}i.push(` - ${a.name} (${a.role})${c}${l}${u}`)}return{content:[{type:"text",text:i.join(`
|
|
954
|
-
`)}],details:{type:"team",action:"status",teamName:o.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${r.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}import*as MS from"node:path";D();function DS(t,e){let r=new Map,n={info:s=>e.info(s),warn:s=>e.warn(s)},o=new at({onNotification:(s,i,a)=>{t.sendNotification("team.member.notification",{memberId:s,method:i,params:a})},onStateChange:(s,i)=>{t.sendNotification("team.member.state",{memberId:s,state:i});let a=o.getHandle(s),l=o.getUsageTracker(s)?.getUsage();t.emitAgentStatus(s,i,{missedBeats:o.getMissedBeats(s),lastActivityAt:a?.lastActivityAt,usage:l&&l.totalTokens>0?{inputTokens:l.inputTokens,outputTokens:l.outputTokens,totalTokens:l.totalTokens}:void 0})},onExit:(s,i,a)=>{for(let c of r.values()){let l=c.members.find(d=>d.cwd&&bo(c.name,d.name)===s);l&&(l.isActive=!1)}e.info(`[team] member ${s} exited (code=${i}, signal=${a})`)},onMcpToolCall:(s,i,a)=>t.handleMcpToolCall(s,i,a),log:{info:s=>e.info(s),warn:s=>e.warn(s),debug:s=>e.debug(s)},sessionDir:MS.join(F(),"agent-logs")});return{async createTeam(s){if(r.has(s.teamName))return{success:!1,error:`Team "${s.teamName}" already exists.`};let i=await io(),a=[];for(let l of s.members??[]){let d={...l,isActive:!0};if(i){let u=`team-${s.teamName}-${l.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),p=await jv(i,u,n);p?(d.worktreePath=p.worktreePath,d.worktreeBranch=p.branch,d.cwd=p.worktreePath,e.info(`[team] provisioned worktree for ${l.name}: ${p.worktreePath}`)):(d.cwd=process.cwd(),e.warn(`[team] worktree provision failed for ${l.name}, using shared cwd`))}else d.cwd=process.cwd();a.push(d)}let c={name:s.teamName,description:s.description,leadId:t.currentSessionId??"default",members:a,createdAt:new Date().toISOString()};r.set(s.teamName,c);for(let l of a){if(!l.cwd)continue;let d=bo(s.teamName,l.name);try{await o.spawn({memberId:d,name:l.name,cwd:l.cwd,prompt:`You are the "${l.name}" team member. Role: ${l.role}.`,agentType:l.role,verbose:t.verbose}),e.info(`[team] spawned child process for ${l.name} in ${l.cwd}`)}catch(u){e.warn(`[team] failed to spawn child process for ${l.name}: ${u instanceof Error?u.message:String(u)}`),l.isActive=!1}}return t.sendNotification("team.updated",{teamName:s.teamName,action:"created",members:c.members.map(l=>({agentName:l.name,role:l.role,worktreePath:l.worktreePath,pid:o.getHandle(bo(s.teamName,l.name))?.pid}))}),{success:!0,team:c}},async deleteTeam(s){let i=r.get(s);if(!i)return{success:!1,error:`Team "${s}" not found.`};for(let c of i.members){let l=bo(s,c.name);o.kill(l),o.remove(l)}let a=await io();if(a)for(let c of i.members)c.worktreePath&&c.worktreeBranch&&(await $v(a,c.worktreePath,c.worktreeBranch,n),e.info(`[team] cleaned up worktree for ${c.name}: ${c.worktreePath}`));return r.delete(s),t.sendNotification("team.updated",{teamName:s,action:"destroyed",members:[]}),{success:!0}},async listTeams(){return{success:!0,teams:[...r.values()]}},async getTeamStatus(s){let i=r.get(s);if(!i)return{success:!1,error:`Team "${s}" not found.`};let a={};for(let c of i.members){let l=bo(s,c.name),d=o.getStatus(l);d&&(c.isActive=d.alive,a[c.name]={mediaProgress:d.mediaProgress,lastToolCall:d.lastToolCall,idleFor:d.idleFor,runningFor:d.runningFor})}return{success:!0,team:i,memberProgress:a}},dispose(){o.dispose()}}}function bo(t,e){return`team-${t}-${e}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()}function NS({host:t,log:e}){let r=DS(t,e);
|
|
955
|
+
`)}],details:{type:"team",action:"status",teamName:o.name}}}default:return{content:[{type:"text",text:`Error: unknown action "${r.action}".`}],details:{type:"team",error:"unknown_action"}}}}}}import*as MS from"node:path";D();function DS(t,e){let r=new Map,n={info:s=>e.info(s),warn:s=>e.warn(s)},o=new at({onNotification:(s,i,a)=>{t.sendNotification("team.member.notification",{memberId:s,method:i,params:a})},onStateChange:(s,i)=>{t.sendNotification("team.member.state",{memberId:s,state:i});let a=o.getHandle(s),l=o.getUsageTracker(s)?.getUsage();t.emitAgentStatus(s,i,{missedBeats:o.getMissedBeats(s),lastActivityAt:a?.lastActivityAt,usage:l&&l.totalTokens>0?{inputTokens:l.inputTokens,outputTokens:l.outputTokens,totalTokens:l.totalTokens}:void 0})},onExit:(s,i,a)=>{for(let c of r.values()){let l=c.members.find(d=>d.cwd&&bo(c.name,d.name)===s);l&&(l.isActive=!1)}e.info(`[team] member ${s} exited (code=${i}, signal=${a})`)},onMcpToolCall:(s,i,a)=>t.handleMcpToolCall(s,i,a),log:{info:s=>e.info(s),warn:s=>e.warn(s),debug:s=>e.debug(s)},sessionDir:MS.join(F(),"agent-logs")});return{async createTeam(s){if(r.has(s.teamName))return{success:!1,error:`Team "${s.teamName}" already exists.`};let i=await io(),a=[];for(let l of s.members??[]){let d={...l,isActive:!0};if(i){let u=`team-${s.teamName}-${l.name}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase(),p=await jv(i,u,n);p?(d.worktreePath=p.worktreePath,d.worktreeBranch=p.branch,d.cwd=p.worktreePath,e.info(`[team] provisioned worktree for ${l.name}: ${p.worktreePath}`)):(d.cwd=process.cwd(),e.warn(`[team] worktree provision failed for ${l.name}, using shared cwd`))}else d.cwd=process.cwd();a.push(d)}let c={name:s.teamName,description:s.description,leadId:t.currentSessionId??"default",members:a,createdAt:new Date().toISOString()};r.set(s.teamName,c);for(let l of a){if(!l.cwd)continue;let d=bo(s.teamName,l.name);try{await o.spawn({memberId:d,name:l.name,cwd:l.cwd,prompt:`You are the "${l.name}" team member. Role: ${l.role}.`,agentType:l.role,verbose:t.verbose}),e.info(`[team] spawned child process for ${l.name} in ${l.cwd}`)}catch(u){e.warn(`[team] failed to spawn child process for ${l.name}: ${u instanceof Error?u.message:String(u)}`),l.isActive=!1}}return t.sendNotification("team.updated",{teamName:s.teamName,action:"created",members:c.members.map(l=>({agentName:l.name,role:l.role,worktreePath:l.worktreePath,pid:o.getHandle(bo(s.teamName,l.name))?.pid}))}),{success:!0,team:c}},async deleteTeam(s){let i=r.get(s);if(!i)return{success:!1,error:`Team "${s}" not found.`};for(let c of i.members){let l=bo(s,c.name);o.kill(l),o.remove(l)}let a=await io();if(a)for(let c of i.members)c.worktreePath&&c.worktreeBranch&&(await $v(a,c.worktreePath,c.worktreeBranch,n),e.info(`[team] cleaned up worktree for ${c.name}: ${c.worktreePath}`));return r.delete(s),t.sendNotification("team.updated",{teamName:s,action:"destroyed",members:[]}),{success:!0}},async listTeams(){return{success:!0,teams:[...r.values()]}},async getTeamStatus(s){let i=r.get(s);if(!i)return{success:!1,error:`Team "${s}" not found.`};let a={};for(let c of i.members){let l=bo(s,c.name),d=o.getStatus(l);d&&(c.isActive=d.alive,a[c.name]={mediaProgress:d.mediaProgress,lastToolCall:d.lastToolCall,idleFor:d.idleFor,runningFor:d.runningFor})}return{success:!0,team:i,memberProgress:a}},dispose(){o.dispose()}}}function bo(t,e){return`team-${t}-${e}`.replace(/[^a-zA-Z0-9-]/g,"-").toLowerCase()}function NS({host:t,log:e}){let r=DS(t,e);Vt(async()=>r.dispose()),K(_S(r))}var ej="notify",tj={type:"object",properties:{message:{type:"string",description:"Notification content to send to the user."},title:{type:"string",description:"Optional notification title/subject line."},priority:{type:"string",enum:["low","normal","high"],description:"Notification priority (default: normal). High may trigger sound/vibration."},channel:{type:"string",description:"Target delivery channel (e.g. 'wechat', 'feishu', 'discord'). Default: user's primary."}},required:["message"]};function LS(t){return{name:ej,label:"Notify",description:"Send a notification to the user. Used for alerting about completed long-running tasks, important updates, or requesting attention. Supports multiple channels (WeChat, Feishu, Discord, etc).",parameters:tj,execute:async(e,r)=>{if(!r.message||r.message.trim().length===0)return{content:[{type:"text",text:"Error: message is required."}],details:{type:"notify",error:"empty_message"}};let n=await t.sendNotification({message:r.message.trim(),title:r.title,priority:r.priority||"normal",channel:r.channel});return n.delivered?{content:[{type:"text",text:`Notification sent via ${n.channel}.`}],details:{type:"notify",delivered:!0,channel:n.channel}}:{content:[{type:"text",text:`Notification failed: ${n.error||"delivery error"}`}],details:{type:"notify",delivered:!1,error:n.error}}}}}var rj="send_message",nj={type:"object",properties:{to:{type:"string",description:"Target agent name or '*' for broadcast to all team members. Must be a valid agent name within the current team."},message:{type:"string",description:"Message content to send to the target agent."},summary:{type:"string",description:"Optional short summary (for logging/routing)."}},required:["to","message"]};function OS(t){return{name:rj,label:"Send Message",description:"Send a message to another agent in your team. Use '*' to broadcast to all teammates. Messages are delivered asynchronously. Use for coordination, delegation, and status updates.",parameters:nj,execute:async(e,r)=>{if(!r.to||r.to.trim().length===0)return{content:[{type:"text",text:"Error: 'to' is required (agent name or '*')."}],details:{type:"send_message",error:"missing_target"}};if(!r.message||r.message.trim().length===0)return{content:[{type:"text",text:"Error: message is required."}],details:{type:"send_message",error:"empty_message"}};if(r.to!=="*"&&t.listTeammates){let s=t.listTeammates();if(!s.includes(r.to))return{content:[{type:"text",text:`Error: agent "${r.to}" not found in team. Available: ${s.join(", ")}`}],details:{type:"send_message",error:"target_not_found",available:s}}}let n=await t.sendMessage({to:r.to.trim(),message:r.message.trim(),summary:r.summary,senderId:t.getSenderId()});return n.success?{content:[{type:"text",text:`Message sent to ${r.to==="*"?`broadcast (${n.recipients?.length||0} recipients)`:r.to}.`}],details:{type:"send_message",success:!0,to:r.to,recipients:n.recipients}}:{content:[{type:"text",text:`Message delivery failed: ${n.error||"unknown error"}`}],details:{type:"send_message",success:!1,error:n.error}}}}}function jS({host:t,log:e}){K(LS({sendNotification:async r=>(e.info(`[notify] ${r.title??""}: ${r.message}`),{delivered:!0,channel:r.channel??"cli"})})),K(OS({sendMessage:async r=>(e.info(`[send_message] ${r.senderId} -> ${r.to}: ${r.message}`),{success:!0,recipients:[r.to]}),getSenderId:()=>t.currentSessionId??"default",listTeammates:()=>[]}))}function $S(t){uS({host:{get agent(){return t.host.agent},get currentTransport(){return t.host.currentTransport},get currentApiKey(){return t.host.currentApiKey},get currentModel(){return t.host.currentModel},sendNotification:t.host.sendNotification.bind(t.host)},hooks:t.hooks,log:t.log,toolInvoker:t.toolInvoker}),kS({host:{currentModel:t.host.currentModel,verbose:t.host.verbose}}),xS({host:{getActiveProjectRoot:()=>t.host.getActiveProjectRoot()}}),ES({log:t.log}),hS({config:t.config,host:{currentSessionId:t.host.currentSessionId}}),NS({host:{get currentSessionId(){return t.host.currentSessionId},get verbose(){return t.host.verbose},sendNotification:t.host.sendNotification.bind(t.host),emitAgentStatus:t.host.emitAgentStatus.bind(t.host),handleMcpToolCall:t.host.handleMcpToolCall.bind(t.host)},log:t.log}),jS({host:{get currentSessionId(){return t.host.currentSessionId}},log:t.log})}function US(t){let e={get agent(){return t.host.getAgent()},get currentTransport(){return t.host.getCurrentTransport()},get currentApiKey(){return t.host.getCurrentApiKey()},get currentModel(){return t.host.getCurrentModel()},get currentSessionId(){return t.host.getCurrentSessionId()},getActiveProjectRoot:()=>t.host.getActiveProjectRoot(),get verbose(){return t.host.getVerbose()},sendNotification(n,o){t.host.sendNotification(n,o)},emitAgentStatus(n,o,s){t.host.emitAgentStatus(n,o,s)},handleMcpToolCall(n,o,s){return t.host.handleMcpToolCall(n,o,s)}},r={config:t.config,host:e,hooks:t.hooks,log:t.log,toolInvoker:t.toolInvoker};$S(r)}var oj={type:"object",properties:{operation:{type:"string",enum:["goToDefinition","findReferences","hover","documentSymbol","diagnostics","completion","signatureHelp","rename","codeAction"],description:`LSP operation:
|
|
955
956
|
- goToDefinition: jump to symbol definition
|
|
956
957
|
- findReferences: find all usages of a symbol
|
|
957
958
|
- hover: get type/docs for symbol at position
|
|
@@ -960,33 +961,33 @@ ${i.map(c=>`\u2022 ${c.monitorId} [${c.source}] \u2192 ${c.target} (events: ${c.
|
|
|
960
961
|
- completion: get completions at position
|
|
961
962
|
- signatureHelp: get function signature at call site
|
|
962
963
|
- rename: preview rename of symbol
|
|
963
|
-
- codeAction: get available quick-fixes/refactorings`},filePath:{type:"string",description:"File path. Absolute or relative to workspace root."},line:{type:"number",description:"Line number (1-indexed). Required for positional operations."},character:{type:"number",description:"Character position (1-indexed). Required for positional operations."},newName:{type:"string",description:"New name for rename operation."},includeContext:{type:"boolean",description:"Include surrounding code context in results (default: true)."}},required:["operation","filePath"]},
|
|
964
|
+
- codeAction: get available quick-fixes/refactorings`},filePath:{type:"string",description:"File path. Absolute or relative to workspace root."},line:{type:"number",description:"Line number (1-indexed). Required for positional operations."},character:{type:"number",description:"Character position (1-indexed). Required for positional operations."},newName:{type:"string",description:"New name for rename operation."},includeContext:{type:"boolean",description:"Include surrounding code context in results (default: true)."}},required:["operation","filePath"]},sj=10*1024*1024,ij=["goToDefinition","findReferences","hover","completion","signatureHelp","rename","codeAction"];function FS(t){return{name:"lsp",label:"LSP",description:"Query language servers for code intelligence. Supports go-to-definition, find-references, hover (type info), document symbols, diagnostics (errors/warnings), completions, signature help, rename preview, and code actions. Read-only \u2014 does not modify files.",parameters:oj,execute:async(e,r)=>{if(!r.filePath||r.filePath.trim().length===0)return{content:[{type:"text",text:"Error: filePath is required."}],details:{type:"lsp",error:"missing_filePath"}};if(r.filePath.startsWith("\\\\")||r.filePath.startsWith("//"))return{content:[{type:"text",text:"Error: UNC paths are not allowed."}],details:{type:"lsp",error:"unc_blocked"}};if(ij.includes(r.operation)){if(r.line==null||r.character==null)return{content:[{type:"text",text:`Error: line and character are required for ${r.operation}.`}],details:{type:"lsp",error:"missing_position"}};if(r.line<1||r.character<1)return{content:[{type:"text",text:"Error: line and character must be \u2265 1."}],details:{type:"lsp",error:"invalid_position"}}}if(r.operation==="rename"&&!r.newName)return{content:[{type:"text",text:"Error: newName is required for rename operation."}],details:{type:"lsp",error:"missing_newName"}};let n=t.resolvePath(r.filePath);if(t.statFile){let s=await t.statFile(n);if(!s||!s.exists)return{content:[{type:"text",text:`Error: file not found: ${r.filePath}`}],details:{type:"lsp",error:"file_not_found"}};if(s.size>sj)return{content:[{type:"text",text:`Error: file too large (${(s.size/1024/1024).toFixed(1)}MB, max 10MB).`}],details:{type:"lsp",error:"file_too_large"}}}let o=await t.executeOperation({operation:r.operation,filePath:n,line:r.line,character:r.character,newName:r.newName,includeContext:r.includeContext??!0});return{content:[{type:"text",text:aj(r.operation,o)}],details:{type:"lsp",operation:r.operation}}}}}function aj(t,e){switch(e.type){case"locations":{if(e.locations.length===0)return"No results found.";let r=[`Found ${e.locations.length} location(s):`,""];for(let n of e.locations.slice(0,50))r.push(` ${n.filePath}:${n.line}:${n.character}`),n.context&&r.push(` ${n.context.trim()}`);return e.locations.length>50&&r.push(` ... and ${e.locations.length-50} more`),r.join(`
|
|
964
965
|
`)}case"symbols":{if(e.symbols.length===0)return"No symbols found.";let r=[`Document symbols (${e.symbols.length}):`,""];for(let n of e.symbols)if(r.push(` ${n.kind} ${n.name} (L${n.range.startLine}-${n.range.endLine})`),n.children){for(let o of n.children.slice(0,10))r.push(` ${o.kind} ${o.name} (L${o.range.startLine})`);n.children.length>10&&r.push(` ... and ${n.children.length-10} more`)}return r.join(`
|
|
965
966
|
`)}case"diagnostics":{if(e.diagnostics.length===0)return"No diagnostics (clean file).";let r=[`Diagnostics (${e.diagnostics.length}):`,""];for(let n of e.diagnostics){let o=n.severity==="error"?"\u274C":n.severity==="warning"?"\u26A0\uFE0F":"\u2139\uFE0F";r.push(` ${o} L${n.line}:${n.character} [${n.source||""}${n.code?`:${n.code}`:""}] ${n.message}`)}return r.join(`
|
|
966
967
|
`)}case"hover":return e.hover?e.hover.contents:"No hover information available.";case"completions":{if(e.completions.length===0)return"No completions available.";let r=[`Completions (${e.completions.length}):`,""];for(let n of e.completions.slice(0,20))r.push(` [${n.kind}] ${n.label}${n.detail?` \u2014 ${n.detail}`:""}`);return e.completions.length>20&&r.push(` ... and ${e.completions.length-20} more`),r.join(`
|
|
967
968
|
`)}case"signatureHelp":return e.signatures.length===0?"No signature information available.":e.signatures.join(`
|
|
968
969
|
`);case"rename":{if(e.edits.length===0)return"No edits generated for rename.";let n=[`Rename would affect ${e.edits.reduce((o,s)=>o+s.edits.length,0)} location(s) in ${e.edits.length} file(s):`,""];for(let o of e.edits)n.push(` ${o.filePath} (${o.edits.length} edits)`);return n.join(`
|
|
969
970
|
`)}case"codeActions":{if(e.actions.length===0)return"No code actions available.";let r=[`Available code actions (${e.actions.length}):`,""];for(let n of e.actions)r.push(` ${n.isPreferred?"\u2605":"-"} ${n.title}${n.kind?` [${n.kind}]`:""}`);return r.join(`
|
|
970
|
-
`)}default:return"Unknown result type."}}var
|
|
971
|
+
`)}default:return"Unknown result type."}}var cj="repl",lj={type:"object",properties:{code:{type:"string",description:`JavaScript code to execute. The VM has access to these built-in primitives:
|
|
971
972
|
- readFile(path): Promise<string> \u2014 read a file
|
|
972
973
|
- writeFile(path, content): Promise<void> \u2014 write a file
|
|
973
974
|
- editFile(path, edits): Promise<string> \u2014 apply edits [{oldText, newText}]
|
|
974
975
|
- exec(command): Promise<{stdout, stderr, exitCode}> \u2014 run shell command
|
|
975
976
|
- glob(pattern): Promise<string[]> \u2014 find files by glob
|
|
976
977
|
- grep(pattern, path?): Promise<{file,line,text}[]> \u2014 search files
|
|
977
|
-
Use this for batch operations (rename many files, transform data, etc) to reduce tool call round-trips.`}},required:["code"]};var HS=1e5,BS=5e4;function qS(t){return{name:
|
|
978
|
+
Use this for batch operations (rename many files, transform data, etc) to reduce tool call round-trips.`}},required:["code"]};var HS=1e5,BS=5e4;function qS(t){return{name:cj,label:"REPL",description:"Execute JavaScript in a persistent VM with built-in file/shell primitives. Use for batch operations that would otherwise require many individual tool calls. The VM persists variables between calls within the same session. Each primitive (readFile, writeFile, exec, etc.) still goes through permission checks.",parameters:lj,execute:async(e,r)=>{if(!r.code||r.code.trim().length===0)return{content:[{type:"text",text:"Error: code is required."}],details:{type:"repl",error:"empty_code"}};if(r.code.length>HS)return{content:[{type:"text",text:`Error: code too large (${r.code.length} chars, max ${HS}).`}],details:{type:"repl",error:"code_too_large"}};let n=await t.executeInVm(r.code),o=n.output||"";return o.length>BS&&(o=o.slice(0,BS)+`
|
|
978
979
|
... (truncated)`),n.error?{content:[{type:"text",text:`Error: ${n.error}
|
|
979
980
|
|
|
980
981
|
Output:
|
|
981
982
|
${o}`}],details:{type:"repl",error:n.error,duration:n.duration}}:{content:[{type:"text",text:o||"(no output)"}],details:{type:"repl",duration:n.duration,outputLength:o.length}}}}}import*as Ei from"node:path";function WS(t){let e=t.workdir;return{executeOperation:async r=>{switch(r.operation){case"goToDefinition":case"findReferences":return{type:"locations",locations:[]};case"hover":return{type:"hover",hover:null};case"documentSymbol":return{type:"symbols",symbols:[]};case"diagnostics":return{type:"diagnostics",diagnostics:[]};case"completion":return{type:"completions",completions:[]};case"signatureHelp":return{type:"signatureHelp",signatures:[]};case"rename":return{type:"rename",edits:[]};case"codeAction":return{type:"codeActions",actions:[]};default:return{type:"locations",locations:[]}}},resolvePath:r=>Ei.isAbsolute(r)?r:Ei.resolve(e,r)}}import*as vo from"node:fs";import*as vn from"node:path";import*as _i from"node:vm";function GS(t){let e,r=t.workdir,n=()=>(e||(e=_i.createContext({...{readFile:async s=>vo.promises.readFile(vn.resolve(r,s),"utf8"),writeFile:async(s,i)=>{await vo.promises.writeFile(vn.resolve(r,s),i,"utf8")},editFile:async(s,i)=>{let a=await vo.promises.readFile(vn.resolve(r,s),"utf8");for(let c of i)a=a.replace(c.oldText,c.newText);return await vo.promises.writeFile(vn.resolve(r,s),a,"utf8"),a},exec:async s=>{let i=await import("node:child_process");return new Promise(a=>{i.execFile("bash",["-c",s],{cwd:r,timeout:3e4},(c,l,d)=>{a({stdout:l?.toString()??"",stderr:d?.toString()??"",exitCode:c?c.code??1:0})})})},glob:async s=>{try{let{globSync:i}=await import("node:fs");return i(s,{cwd:r})}catch{return[]}},grep:async(s,i)=>{let a=[],c=vn.resolve(r,i??".");try{let l=await import("node:child_process"),d=await new Promise(u=>{l.execFile("grep",["-rn",s,c,"--include=*"],{timeout:1e4},(p,m)=>{u(m?.toString()??"")})});for(let u of d.split(`
|
|
982
|
-
`).filter(Boolean).slice(0,100)){let p=u.match(/^(.+?):(\d+):(.*)$/);p&&a.push({file:p[1],line:parseInt(p[2],10),text:p[3]})}}catch{}return a},console:{log:(...s)=>s.map(String).join(" ")}},setTimeout,clearTimeout,Promise,JSON,Math,Date,Array,Object,String,Number,Boolean,RegExp,Map,Set,Error,Buffer})),e);return{executeInVm:async o=>{let s=Date.now();try{let i=n(),a=await _i.runInContext(`(async () => { ${o} })()`,i,{timeout:3e4});return{output:a!==void 0?String(a):"",duration:Date.now()-s}}catch(i){return{output:"",error:i instanceof Error?i.message:String(i),duration:Date.now()-s}}},resetVm:()=>{e=void 0}}}function KS(t){let e=typeof t.config.workdir=="string"?t.config.workdir:process.cwd();K(qS(GS({workdir:e}))),K(FS(WS({workdir:e})))}import*as kn from"node:fs";import Li from"node:path";import{fileURLToPath as
|
|
983
|
+
`).filter(Boolean).slice(0,100)){let p=u.match(/^(.+?):(\d+):(.*)$/);p&&a.push({file:p[1],line:parseInt(p[2],10),text:p[3]})}}catch{}return a},console:{log:(...s)=>s.map(String).join(" ")}},setTimeout,clearTimeout,Promise,JSON,Math,Date,Array,Object,String,Number,Boolean,RegExp,Map,Set,Error,Buffer})),e);return{executeInVm:async o=>{let s=Date.now();try{let i=n(),a=await _i.runInContext(`(async () => { ${o} })()`,i,{timeout:3e4});return{output:a!==void 0?String(a):"",duration:Date.now()-s}}catch(i){return{output:"",error:i instanceof Error?i.message:String(i),duration:Date.now()-s}}},resetVm:()=>{e=void 0}}}function KS(t){let e=typeof t.config.workdir=="string"?t.config.workdir:process.cwd();K(qS(GS({workdir:e}))),K(FS(WS({workdir:e})))}import*as kn from"node:fs";import Li from"node:path";import{fileURLToPath as bj}from"node:url";import{spawn as mj}from"node:child_process";import{createInterface as gj}from"node:readline";var dj=new Set(["describe","fetch","find","get","inspect","list","query","read","search","stat"]),uj=new Set(["append","copy","create","delete","edit","move","patch","remove","rename","set","update","upload","write"]);function Mi(t){let e=t.annotations,r=pj(t.name),n=r.some(c=>uj.has(c)),o=r.some(c=>dj.has(c)),s=e?.destructiveHint===!0||n,i=e?.readOnlyHint===!0||!s&&o,a=i||e?.idempotentHint===!0&&!s;return{isReadOnly:i,isConcurrencySafe:a,isDestructive:s}}function pj(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}var Di=class{process=null;readline=null;pending=new Map;nextId=1;connected=!1;toolsCache=[];serverName="";serverVersion="";supportsToolsListChanged=!1;onToolsChanged=null;stderrBuffer="";config;constructor(e){this.config=e}async connect(){if(this.connected)return;let e={...process.env,...this.config.env};this.process=mj(this.config.command,this.config.args??[],{stdio:["pipe","pipe","pipe"],env:e,cwd:this.config.cwd,windowsHide:!0}),this.process.on("error",n=>{this.handleProcessError(n)}),this.process.on("exit",n=>{this.handleProcessExit(n)}),this.process.stderr?.on("data",n=>{this.stderrBuffer+=n.toString(),this.stderrBuffer.length>4096&&(this.stderrBuffer=this.stderrBuffer.slice(-4096))}),this.readline=gj({input:this.process.stdout,crlfDelay:Number.POSITIVE_INFINITY}),this.readline.on("line",n=>this.handleLine(n));let r=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"qlogicagent",version:"0.3.0"}},this.config.initTimeoutMs??3e4);this.serverName=r.serverInfo?.name??this.config.name,this.serverVersion=r.serverInfo?.version??"unknown",this.supportsToolsListChanged=r.capabilities?.tools?.listChanged??!1,this.sendNotification("notifications/initialized",{}),this.connected=!0,await this.refreshTools()}async disconnect(){if(!this.connected)return;this.connected=!1;for(let[,r]of this.pending)r.reject(new Error("MCP client disconnecting"));this.pending.clear(),this.toolsCache=[],this.readline?.close(),this.readline=null;let e=this.process;this.process=null,e&&await new Promise(r=>{let n=!1,o=()=>{n||(n=!0,clearTimeout(s),r())},s=setTimeout(()=>{e.kill("SIGKILL"),o()},5e3);e.once("exit",o),e.kill("SIGTERM")})}get isConnected(){return this.connected}get info(){return{name:this.serverName,version:this.serverVersion}}async refreshTools(){if(!this.connected)return[];try{let e=await this.sendRequest("tools/list",{});this.toolsCache=e.tools??[]}catch{this.toolsCache=[]}return this.toolsCache}getCachedTools(){return this.toolsCache}async callTool(e,r,n){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return await this.sendRequest("tools/call",{name:e,arguments:r??{}},12e4,n)}async listResources(){if(!this.connected)return[];try{return(await this.sendRequest("resources/list",{})).resources??[]}catch{return[]}}async readResource(e){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return(await this.sendRequest("resources/read",{uri:e})).contents??[]}toPortableTools(){let e=fj(this.config.name);return this.toolsCache.map(r=>{let n=Mi(r);return{name:`mcp__${e}__${r.name}`,label:`[${this.config.name}] ${r.name}`,description:r.description??`MCP tool from ${this.config.name}`,parameters:r.inputSchema??{type:"object",properties:{}},isConcurrencySafe:n.isConcurrencySafe,isReadOnly:n.isReadOnly,isDestructive:n.isDestructive,searchHint:`mcp ${this.config.name} ${r.name}`,execute:async(o,s,i)=>this.executeAsTool(r.name,s,i)}})}setOnToolsChanged(e){this.onToolsChanged=e}async executeAsTool(e,r,n){try{let o=await this.callTool(e,r,n);return{content:[{type:"text",text:o.content.filter(a=>a.type==="text"&&a.text).map(a=>a.text).join(`
|
|
983
984
|
`)||"(no text output)"}],...o.isError?{details:{error:"mcp_tool_error"}}:{}}}catch(o){let s=o instanceof Error?o.message:String(o);return{content:[{type:"text",text:`MCP tool error: ${s}`}],details:{error:s}}}}sendRequest(e,r,n=3e4,o){return new Promise((s,i)=>{if(o?.aborted){i(new Error("Aborted"));return}let a=this.nextId++,c={jsonrpc:"2.0",id:a,method:e,params:r},l=setTimeout(()=>{this.pending.delete(a),i(new Error(`MCP request ${e} timed out after ${n}ms`))},n),d=()=>{clearTimeout(l),this.pending.delete(a)};o?.addEventListener("abort",()=>{d(),i(new Error("Aborted"))},{once:!0}),this.pending.set(a,{resolve:u=>{d(),u.error?i(new Error(`MCP error ${u.error.code}: ${u.error.message}`)):s(u.result)},reject:u=>{d(),i(u)}}),this.writeLine(JSON.stringify(c))})}sendNotification(e,r){let n={jsonrpc:"2.0",method:e,params:r};this.writeLine(JSON.stringify(n))}writeLine(e){this.process?.stdin?.writable&&this.process.stdin.write(e+`
|
|
984
|
-
`)}handleLine(e){let r=e.trim();if(!r)return;let n;try{n=JSON.parse(r)}catch{return}if("id"in n&&("result"in n||"error"in n)){let o=n.id,s=this.pending.get(o);s&&s.resolve(n)}else"method"in n&&!("id"in n)&&this.handleNotification(n)}handleNotification(e){e.method==="notifications/tools/list_changed"&&this.refreshTools().then(()=>{this.onToolsChanged?.()}).catch(()=>{})}handleProcessError(e){this.connected=!1;for(let[,r]of this.pending)r.reject(new Error(`MCP process error: ${e.message}`));this.pending.clear()}handleProcessExit(e){this.connected=!1;for(let[,r]of this.pending)r.reject(new Error(`MCP process exited with code ${e}`));this.pending.clear()}};function
|
|
985
|
-
`);i=l.pop()??"";for(let d of l){if(!d.startsWith("data: "))continue;let u=d.slice(6).trim();if(u)try{let p=JSON.parse(u);if("method"in p&&p.method==="notifications/tools/list_changed"){this.onToolsChanged?.();continue}if(p.id===r){if(p.error)throw new Error(`MCP error ${p.error.code}: ${p.error.message}`);return p.result}}catch(p){if(p instanceof Error&&p.message.startsWith("MCP error"))throw p}}}}finally{o.releaseLock()}throw new Error("MCP SSE stream ended without response")}schemaToPortableTool(e){let r=this,n=
|
|
986
|
-
`)||"(no output)"}],details:c.isError?{type:"mcp",error:"tool_error"}:{type:"mcp"}}}catch(c){let l=c instanceof Error?c.message:String(c);return{content:[{type:"text",text:`MCP tool error: ${l}`}],details:{type:"mcp",error:l}}}}}}};function
|
|
987
|
-
`).trim()}],details:{type:"list_mcp_resources",count:o.length}}}}}var
|
|
985
|
+
`)}handleLine(e){let r=e.trim();if(!r)return;let n;try{n=JSON.parse(r)}catch{return}if("id"in n&&("result"in n||"error"in n)){let o=n.id,s=this.pending.get(o);s&&s.resolve(n)}else"method"in n&&!("id"in n)&&this.handleNotification(n)}handleNotification(e){e.method==="notifications/tools/list_changed"&&this.refreshTools().then(()=>{this.onToolsChanged?.()}).catch(()=>{})}handleProcessError(e){this.connected=!1;for(let[,r]of this.pending)r.reject(new Error(`MCP process error: ${e.message}`));this.pending.clear()}handleProcessExit(e){this.connected=!1;for(let[,r]of this.pending)r.reject(new Error(`MCP process exited with code ${e}`));this.pending.clear()}};function fj(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}import{randomUUID as hj}from"node:crypto";var Ni=class{connected=!1;toolsCache=[];serverName="";serverVersion="";sessionId=null;onToolsChanged=null;config;constructor(e){this.config=e}async connect(){if(this.connected)return;let e=await this.sendRequest("initialize",{protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"qlogicagent",version:"0.3.0"}},this.config.initTimeoutMs??3e4);this.serverName=e.serverInfo?.name??this.config.name,this.serverVersion=e.serverInfo?.version??"unknown",await this.sendNotification("notifications/initialized",{}),this.connected=!0,await this.refreshTools()}async disconnect(){this.connected=!1,this.toolsCache=[],this.sessionId=null}async callTool(e,r,n){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return await this.sendRequest("tools/call",{name:e,arguments:r??{}},this.config.toolCallTimeoutMs??12e4,n)}async listResources(){if(!this.connected)return[];try{return(await this.sendRequest("resources/list",{})).resources??[]}catch{return[]}}async readResource(e){if(!this.connected)throw new Error(`MCP server ${this.config.name} not connected`);return(await this.sendRequest("resources/read",{uri:e})).contents??[]}toPortableTools(){return this.toolsCache.map(e=>this.schemaToPortableTool(e))}getCachedTools(){return[...this.toolsCache]}get isConnected(){return this.connected}get info(){return{name:this.serverName,version:this.serverVersion}}setOnToolsChanged(e){this.onToolsChanged=e}async refreshTools(){let e=await this.sendRequest("tools/list",{});this.toolsCache=e.tools??[]}async sendRequest(e,r,n=3e4,o){let s=hj(),i={jsonrpc:"2.0",id:s,method:e,params:r},a=new AbortController,c=setTimeout(()=>a.abort(),n);o&&o.addEventListener("abort",()=>a.abort(),{once:!0});try{let l={"Content-Type":"application/json",Accept:"application/json, text/event-stream",...this.config.headers};this.sessionId&&(l["Mcp-Session-Id"]=this.sessionId);let d=await fetch(this.config.url,{method:"POST",headers:l,body:JSON.stringify(i),signal:a.signal}),u=d.headers.get("mcp-session-id");if(u&&(this.sessionId=u),!d.ok)throw new Error(`MCP HTTP error ${d.status}: ${d.statusText}`);if((d.headers.get("content-type")??"").includes("text/event-stream"))return await this.parseSSEResponse(d,s);let m=await d.json();if(m.error)throw new Error(`MCP error ${m.error.code}: ${m.error.message}`);return m.result}finally{clearTimeout(c)}}async sendNotification(e,r){let n={jsonrpc:"2.0",method:e,params:r},o={"Content-Type":"application/json",...this.config.headers};this.sessionId&&(o["Mcp-Session-Id"]=this.sessionId),await fetch(this.config.url,{method:"POST",headers:o,body:JSON.stringify(n)}).catch(()=>{})}async parseSSEResponse(e,r){let n=e.body;if(!n)throw new Error("MCP SSE response has no body");let o=n.getReader(),s=new TextDecoder,i="";try{for(;;){let{done:a,value:c}=await o.read();if(a)break;i+=s.decode(c,{stream:!0});let l=i.split(`
|
|
986
|
+
`);i=l.pop()??"";for(let d of l){if(!d.startsWith("data: "))continue;let u=d.slice(6).trim();if(u)try{let p=JSON.parse(u);if("method"in p&&p.method==="notifications/tools/list_changed"){this.onToolsChanged?.();continue}if(p.id===r){if(p.error)throw new Error(`MCP error ${p.error.code}: ${p.error.message}`);return p.result}}catch(p){if(p instanceof Error&&p.message.startsWith("MCP error"))throw p}}}}finally{o.releaseLock()}throw new Error("MCP SSE stream ended without response")}schemaToPortableTool(e){let r=this,n=yj(this.config.name),o=Mi(e);return{name:`mcp__${n}__${e.name}`,label:`[${this.config.name}] ${e.name}`,description:e.description??`MCP tool from ${this.config.name}`,parameters:e.inputSchema??{type:"object",properties:{}},isConcurrencySafe:o.isConcurrencySafe,isReadOnly:o.isReadOnly,isDestructive:o.isDestructive,searchHint:`mcp ${this.config.name} ${e.name}`,execute:async(s,i,a)=>{try{let c=await r.callTool(e.name,i,a);return{content:[{type:"text",text:(c.content??[]).filter(u=>u.type==="text"&&u.text).map(u=>u.text).join(`
|
|
987
|
+
`)||"(no output)"}],details:c.isError?{type:"mcp",error:"tool_error"}:{type:"mcp"}}}catch(c){let l=c instanceof Error?c.message:String(c);return{content:[{type:"text",text:`MCP tool error: ${l}`}],details:{type:"mcp",error:l}}}}}}};function yj(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var Oi=class{clients=new Map;injected=!1;log;workspaceRoot;constructor(e){this.log=e.log??{info:()=>{},warn:()=>{}},this.workspaceRoot=e.workspaceRoot?Li.resolve(e.workspaceRoot):void 0;for(let r of e.servers){if(r.disabled)continue;if((r.type??(r.url?"http":"stdio"))==="http"){if(!r.url){this.log.warn(`[mcp] server "${r.name}" is type "http" but has no url, skipping`);continue}let o={name:r.name,url:r.url,headers:r.headers,initTimeoutMs:r.initTimeoutMs};this.clients.set(r.name,new Ni(o))}else{if(!r.command){this.log.warn(`[mcp] server "${r.name}" is type "stdio" but has no command, skipping`);continue}let o={name:r.name,command:r.command,args:r.args,env:r.env,cwd:r.cwd,initTimeoutMs:r.initTimeoutMs};this.clients.set(r.name,new Di(o))}}}async connectAll(){let e=Array.from(this.clients.entries()).map(async([r,n])=>{try{await n.connect(),this.log.info(`[mcp] connected to ${r} (${n.info.name} v${n.info.version})`),n.setOnToolsChanged(()=>{this.log.info(`[mcp] tools changed on ${r}, re-injecting`),this.injected&&this.reinjectTools(r,n)})}catch(o){this.log.warn(`[mcp] failed to connect to ${r}: ${o instanceof Error?o.message:o}`)}});await Promise.allSettled(e)}injectTools(){this.injected=!0;for(let[e,r]of this.clients){if(!r.isConnected)continue;let n=this.wrapToolsForWorkspaceBoundary(r.toPortableTools());dc(n),this.log.info(`[mcp] injected ${n.length} tools from ${e}`)}}getConnectedServers(){return Array.from(this.clients.entries()).filter(([,e])=>e.isConnected).map(([e])=>e)}getToolCount(){let e=0;for(let r of this.clients.values())r.isConnected&&(e+=r.getCachedTools().length);return e}async disconnectAll(){let e=Array.from(this.clients.values()).map(async r=>{try{await r.disconnect()}catch{}});await Promise.allSettled(e),this.clients.clear(),this.injected=!1}async listResources(e){let r=e?[[e,this.clients.get(e)]].filter(([,o])=>o):Array.from(this.clients.entries());return(await Promise.all(r.map(async([o,s])=>{if(!s?.isConnected||!s.listResources)return[];try{return(await s.listResources()).map(a=>({...a,server:o}))}catch{return this.log.warn(`[mcp] failed to list resources from ${o}`),[]}}))).flat()}async readResource(e,r){let n=this.clients.get(e);if(!n?.isConnected)throw new Error(`MCP server "${e}" is not connected`);if(!n.readResource)throw new Error(`MCP server "${e}" does not support resources`);let o=zS(`mcp__${XS(e)}__read_resource`,{uri:r},this.workspaceRoot);if(o)throw new Error(o);return n.readResource(r)}wrapToolsForWorkspaceBoundary(e){return this.workspaceRoot?e.map(r=>{if(!r.execute)return r;let n=r.execute;return{...r,execute:async(o,s,i)=>{let a=zS(r.name,s,this.workspaceRoot);return a?{content:[{type:"text",text:a}],details:{type:"mcp",error:"workspace_boundary"}}:n(o,s,i)}}}):e}reinjectTools(e,r){if(!this.injected)return;let n=`mcp__${XS(e)}__`;for(let s of Jt())s.startsWith(n)&&Jo(s);let o=this.wrapToolsForWorkspaceBoundary(r.toPortableTools());dc(o),this.log.info(`[mcp] re-injected ${o.length} tools from ${e}`)}},vj=/(?:^|_)(path|paths|file|files|filename|filenames|dir|dirs|directory|directories|folder|folders|cwd|root|uri)(?:$|_)/i;function zS(t,e,r){if(!r)return null;for(let n of Yd(e)){let o=Sj(n.value,r);if(o&&!wj(o.candidate,o.root,o.pathApi))return`Blocked: MCP tool "${t}" path "${n.value}" is outside the workspace boundary "${o.root}"`}return null}function Yd(t,e="",r=0){if(r>8)return[];if(typeof t=="string")return kj(e,t)?[{key:e,value:t}]:[];if(Array.isArray(t))return t.flatMap(o=>Yd(o,e,r+1));if(!t||typeof t!="object")return[];let n=[];for(let[o,s]of Object.entries(t))n.push(...Yd(s,o,r+1));return n}function kj(t,e){if(!vj.test(t))return!1;let r=e.trim();return!r||/^https?:\/\//i.test(r)?!1:Rj(r)}function Rj(t){return Li.isAbsolute(t)||/^[A-Za-z]:[\\/]/.test(t)||/^\\\\/.test(t)||/^file:\/\//i.test(t)||t.includes("../")||t.includes("..\\")||t.startsWith(".\\")||t.startsWith("./")||t.includes("/")||t.includes("\\")}function Sj(t,e){let r=t.trim();if(/^file:\/\//i.test(r))try{r=bj(r)}catch{return null}let n=VS(r)||VS(e)?Li.win32:Li,o=n.resolve(e);return{candidate:n.isAbsolute(r)?n.resolve(r):n.resolve(o,r),root:o,pathApi:n}}function wj(t,e,r){let n=r.relative(e,t);return n===""||!n.startsWith("..")&&!r.isAbsolute(n)}function VS(t){return/^[A-Za-z]:[\\/]/.test(t)||/^\\\\/.test(t)}function XS(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}function Jd(t){if(!t||typeof t!="object")return[];let e=t,r=[],n=e.mcpServers??e.servers??e;for(let[o,s]of Object.entries(n)){if(!s||typeof s!="object")continue;let i=s;if(typeof i.url=="string"){r.push({name:o,type:"http",url:i.url,headers:i.headers&&typeof i.headers=="object"?i.headers:void 0,disabled:i.disabled===!0,initTimeoutMs:typeof i.initTimeoutMs=="number"?i.initTimeoutMs:void 0});continue}typeof i.command=="string"&&r.push({name:o,type:"stdio",command:i.command,args:Array.isArray(i.args)?i.args:void 0,env:i.env&&typeof i.env=="object"?i.env:void 0,cwd:typeof i.cwd=="string"?i.cwd:void 0,disabled:i.disabled===!0})}return r}var Tj={type:"object",properties:{server:{type:"string",description:"MCP server name to list resources from. Omit to list from all connected servers."}}};function YS(t){return{name:"list_mcp_resources",label:"List MCP Resources",description:"List resources available from connected MCP servers. Resources are data items (files, database records, API data) exposed by MCP servers that can be read with read_mcp_resource.",parameters:Tj,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource list browse discover",execute:async(e,r)=>{let n=t();if(!n)return{content:[{type:"text",text:"No MCP servers configured."}],details:{type:"list_mcp_resources",count:0}};let o=await n.listResources(r.server);if(o.length===0)return{content:[{type:"text",text:r.server?`No resources found from MCP server "${r.server}".`:"No resources found from any connected MCP server."}],details:{type:"list_mcp_resources",count:0}};let s=new Map;for(let a of o){let c=s.get(a.server)??[];c.push(a),s.set(a.server,c)}let i=[];for(let[a,c]of s){i.push(`Server: ${a} (${c.length} resources)`);for(let l of c){let d=l.mimeType?` [${l.mimeType}]`:"",u=l.description?` \u2014 ${l.description}`:"";i.push(` ${l.name}: ${l.uri}${d}${u}`)}i.push("")}return{content:[{type:"text",text:i.join(`
|
|
988
|
+
`).trim()}],details:{type:"list_mcp_resources",count:o.length}}}}}var Aj={type:"object",properties:{server:{type:"string",description:"Name of the MCP server that hosts the resource."},uri:{type:"string",description:"URI of the resource to read (from list_mcp_resources output)."}},required:["server","uri"]};function JS(t){return{name:"read_mcp_resource",label:"Read MCP Resource",description:"Read a specific resource from an MCP server by URI. Returns the resource content (text or binary metadata). Use list_mcp_resources first to discover available URIs.",parameters:Aj,shouldDefer:!0,isConcurrencySafe:!0,isReadOnly:!0,searchHint:"mcp resource read fetch content",execute:async(e,r)=>{let n=t();if(!n)return{content:[{type:"text",text:"No MCP servers configured."}],details:{error:"no_mcp"}};try{let o=await n.readResource(r.server,r.uri);if(o.length===0)return{content:[{type:"text",text:`Resource "${r.uri}" returned no content.`}],details:{type:"read_mcp_resource",empty:!0}};let s=[];for(let i of o)if(i.text){let a=i.mimeType?` (${i.mimeType})`:"";s.push({type:"text",text:`--- ${i.uri}${a}-
|
|
988
989
|
${i.text}`})}else if(i.blob){let a=Math.ceil(i.blob.length*3/4/1024);s.push({type:"text",text:`--- ${i.uri} (binary, ~${a}KB, ${i.mimeType??"unknown"})-
|
|
989
|
-
[Binary content not displayed. Use appropriate tool to process.]`})}return s.length===0?{content:[{type:"text",text:`Resource "${r.uri}" has no readable content.`}],details:{type:"read_mcp_resource",empty:!0}}:{content:s,details:{type:"read_mcp_resource",uri:r.uri,server:r.server,contentCount:o.length}}}catch(o){return{content:[{type:"text",text:`Error reading resource: ${o.message}`}],details:{error:o.message}}}}}}var
|
|
990
|
+
[Binary content not displayed. Use appropriate tool to process.]`})}return s.length===0?{content:[{type:"text",text:`Resource "${r.uri}" has no readable content.`}],details:{type:"read_mcp_resource",empty:!0}}:{content:s,details:{type:"read_mcp_resource",uri:r.uri,server:r.server,contentCount:o.length}}}catch(o){return{content:[{type:"text",text:`Error reading resource: ${o.message}`}],details:{error:o.message}}}}}}var Pj="mcp",Cj={type:"object",properties:{action:{type:"string",enum:["list_servers","list_tools","call_tool","list_resources","read_resource","list_prompts","get_prompt","authenticate","manage_server"],description:`MCP action:
|
|
990
991
|
- list_servers: List configured MCP servers, their status and capabilities
|
|
991
992
|
- list_tools: List tools provided by a specific server
|
|
992
993
|
- call_tool: Execute a tool on an MCP server
|
|
@@ -995,12 +996,12 @@ ${i.text}`})}else if(i.blob){let a=Math.ceil(i.blob.length*3/4/1024);s.push({typ
|
|
|
995
996
|
- list_prompts: List prompts available from a server
|
|
996
997
|
- get_prompt: Get a specific prompt with arguments
|
|
997
998
|
- authenticate: Initiate OAuth authentication with a server
|
|
998
|
-
- manage_server: Add, remove, restart, or check server status`},server:{type:"string",description:"MCP server name. Required for all actions except list_servers."},toolName:{type:"string",description:"Tool name on the MCP server. Required for call_tool."},arguments:{type:"object",description:"Arguments for the tool call or prompt. Used with call_tool and get_prompt."},uri:{type:"string",description:"Resource URI. Required for read_resource."},promptName:{type:"string",description:"Prompt name. Required for get_prompt."},manageAction:{type:"string",enum:["add","remove","restart","health_check","enable","disable"],description:"Sub-action for manage_server."},config:{type:"object",description:"Server configuration. Required for manage_server add."}},required:["action"]};function QS(t){return{name:
|
|
999
|
+
- manage_server: Add, remove, restart, or check server status`},server:{type:"string",description:"MCP server name. Required for all actions except list_servers."},toolName:{type:"string",description:"Tool name on the MCP server. Required for call_tool."},arguments:{type:"object",description:"Arguments for the tool call or prompt. Used with call_tool and get_prompt."},uri:{type:"string",description:"Resource URI. Required for read_resource."},promptName:{type:"string",description:"Prompt name. Required for get_prompt."},manageAction:{type:"string",enum:["add","remove","restart","health_check","enable","disable"],description:"Sub-action for manage_server."},config:{type:"object",description:"Server configuration. Required for manage_server add."}},required:["action"]};function QS(t){return{name:Pj,label:"MCP",description:`Interact with external MCP (Model Context Protocol) servers. Discover and call tools, read resources, get prompts, manage servers, and handle authentication. MCP servers extend agent capabilities with external integrations (databases, APIs, code analysis, custom tools).
|
|
999
1000
|
|
|
1000
|
-
Dynamic tools: When MCP servers are connected, their tools also appear as individual entries in the tool list (prefixed mcp__server__tool) for direct invocation without going through this management tool.`,parameters:
|
|
1001
|
-
`)}],details:{type:"mcp",action:"list_servers",count:o.length}}}case"list_tools":{if(!r.server)return le("server is required for list_tools.");let o=await t.listTools(r.server);if(o.length===0)return{content:[{type:"text",text:`No tools available from server "${r.server}".`}],details:{type:"mcp",action:"list_tools",server:r.server,count:0}};let s=[`Tools from "${r.server}" (${o.length}):`,""];for(let i of o){let a=
|
|
1001
|
+
Dynamic tools: When MCP servers are connected, their tools also appear as individual entries in the tool list (prefixed mcp__server__tool) for direct invocation without going through this management tool.`,parameters:Cj,shouldDefer:!0,execute:async(e,r,n)=>{switch(r.action){case"list_servers":{let o=await t.listServers();if(o.length===0)return{content:[{type:"text",text:"No MCP servers configured. Use manage_server action to add one."}],details:{type:"mcp",action:"list_servers",count:0}};let s=[`MCP Servers (${o.length}):`,""];for(let i of o){let a=Ij(i.status);if(s.push(`${a} **${i.name}** [${i.transport}] \u2014 ${i.status}`),s.push(` Tools: ${i.toolCount} | Resources: ${i.resourceCount} | Prompts: ${i.promptCount}`),i.capabilities){let c=[];i.capabilities.tools?.listChanged&&c.push("tools/listChanged"),i.capabilities.resources?.subscribe&&c.push("resources/subscribe"),i.capabilities.prompts?.listChanged&&c.push("prompts/listChanged"),c.length>0&&s.push(` Capabilities: ${c.join(", ")}`)}i.serverVersion&&s.push(` Version: ${i.serverVersion}`),i.error&&s.push(` \u26A0 Error: ${i.error}`),s.push("")}return{content:[{type:"text",text:s.join(`
|
|
1002
|
+
`)}],details:{type:"mcp",action:"list_servers",count:o.length}}}case"list_tools":{if(!r.server)return le("server is required for list_tools.");let o=await t.listTools(r.server);if(o.length===0)return{content:[{type:"text",text:`No tools available from server "${r.server}".`}],details:{type:"mcp",action:"list_tools",server:r.server,count:0}};let s=[`Tools from "${r.server}" (${o.length}):`,""];for(let i of o){let a=Ej(i.annotations);s.push(`- **${i.name}**${a}${i.description?`: ${i.description}`:""}`),i.prefixedName&&s.push(` Direct call: \`${i.prefixedName}\``)}return{content:[{type:"text",text:s.join(`
|
|
1002
1003
|
`)}],details:{type:"mcp",action:"list_tools",server:r.server,count:o.length}}}case"call_tool":{if(!r.server)return le("server is required for call_tool.");if(!r.toolName)return le("toolName is required for call_tool.");let o=await t.callTool(r.server,r.toolName,r.arguments,n);return!o.success||o.isError?{content:[{type:"text",text:`MCP tool error (${r.server}/${r.toolName}): ${o.error||o.content||"unknown error"}`}],details:{type:"mcp",action:"call_tool",server:r.server,toolName:r.toolName,success:!1}}:o.contentBlocks&&o.contentBlocks.length>0?{content:o.contentBlocks.map(i=>i.type==="image"&&i.data?{type:"image",data:i.data,mimeType:i.mimeType}:{type:"text",text:i.text||""}),details:{type:"mcp",action:"call_tool",server:r.server,toolName:r.toolName,success:!0}}:{content:[{type:"text",text:o.content||"(no output)"}],details:{type:"mcp",action:"call_tool",server:r.server,toolName:r.toolName,success:!0}}}case"list_resources":{let o=await t.listResources(r.server);if(o.length===0)return{content:[{type:"text",text:r.server?`No resources from "${r.server}".`:"No MCP resources available."}],details:{type:"mcp",action:"list_resources",count:0}};let s=[`MCP Resources (${o.length}):`,""];for(let i of o)s.push(`- **${i.name}** \`${i.uri}\`${i.mimeType?` [${i.mimeType}]`:""}`),i.description&&s.push(` ${i.description}`),i.server&&s.push(` Server: ${i.server}`);return{content:[{type:"text",text:s.join(`
|
|
1003
|
-
`)}],details:{type:"mcp",action:"list_resources",count:o.length,server:r.server}}}case"read_resource":{if(!r.server)return le("server is required for read_resource.");if(!r.uri)return le("uri is required for read_resource.");let o=await t.readResource(r.server,r.uri);if(o.length===0)return{content:[{type:"text",text:"Resource returned no content."}],details:{type:"mcp",action:"read_resource",server:r.server,uri:r.uri}};let s=[];for(let i of o)i.blobSavedTo?s.push({type:"text",text:`[Binary content saved to: ${i.blobSavedTo}${i.blobSize?` (${
|
|
1004
|
+
`)}],details:{type:"mcp",action:"list_resources",count:o.length,server:r.server}}}case"read_resource":{if(!r.server)return le("server is required for read_resource.");if(!r.uri)return le("uri is required for read_resource.");let o=await t.readResource(r.server,r.uri);if(o.length===0)return{content:[{type:"text",text:"Resource returned no content."}],details:{type:"mcp",action:"read_resource",server:r.server,uri:r.uri}};let s=[];for(let i of o)i.blobSavedTo?s.push({type:"text",text:`[Binary content saved to: ${i.blobSavedTo}${i.blobSize?` (${_j(i.blobSize)})`:""}]`}):i.text&&s.push({type:"text",text:i.text});return s.length===0&&s.push({type:"text",text:"(empty content)"}),{content:s,details:{type:"mcp",action:"read_resource",server:r.server,uri:r.uri}}}case"list_prompts":{if(!r.server)return le("server is required for list_prompts.");if(!t.listPrompts)return le("Prompt listing not supported by the current MCP host.");let o=await t.listPrompts(r.server);if(o.length===0)return{content:[{type:"text",text:`No prompts available from "${r.server}".`}],details:{type:"mcp",action:"list_prompts",server:r.server,count:0}};let s=[`Prompts from "${r.server}" (${o.length}):`,""];for(let i of o)if(s.push(`- **${i.name}**${i.description?`: ${i.description}`:""}`),i.arguments&&i.arguments.length>0){let a=i.arguments.map(c=>`${c.name}${c.required?" (required)":""}${c.description?`: ${c.description}`:""}`);s.push(` Arguments: ${a.join(", ")}`)}return{content:[{type:"text",text:s.join(`
|
|
1004
1005
|
`)}],details:{type:"mcp",action:"list_prompts",server:r.server,count:o.length}}}case"get_prompt":{if(!r.server)return le("server is required for get_prompt.");if(!r.promptName)return le("promptName is required for get_prompt.");if(!t.getPrompt)return le("Prompt retrieval not supported by the current MCP host.");let o=r.arguments?Object.fromEntries(Object.entries(r.arguments).map(([a,c])=>[a,String(c)])):void 0,s=await t.getPrompt(r.server,r.promptName,o),i=[];s.description&&i.push(`> ${s.description}`,"");for(let a of s.messages)i.push(`**[${a.role}]:**`),a.content.type==="text"?i.push(a.content.text):a.content.type==="resource"?(i.push(`[Resource: ${a.content.resource.uri}]`),a.content.resource.text&&i.push(a.content.resource.text)):a.content.type==="image"&&i.push("[Image content]"),i.push("");return{content:[{type:"text",text:i.join(`
|
|
1005
1006
|
`)||"(empty prompt)"}],details:{type:"mcp",action:"get_prompt",server:r.server,promptName:r.promptName}}}case"authenticate":{if(!r.server)return le("server is required for authenticate.");let o=await t.authenticate(r.server);switch(o.status){case"auth_url":return{content:[{type:"text",text:`Authentication required for "${r.server}".
|
|
1006
1007
|
|
|
@@ -1010,11 +1011,11 @@ ${o.authUrl}
|
|
|
1010
1011
|
${o.message||"Once you complete authentication, the server's tools will become available automatically."}`}],details:{type:"mcp",action:"authenticate",server:r.server,status:"auth_url"}};case"already_authenticated":return{content:[{type:"text",text:`Server "${r.server}" is already authenticated.`}],details:{type:"mcp",action:"authenticate",server:r.server,status:"already_authenticated"}};case"step_up_required":return{content:[{type:"text",text:`Server "${r.server}" requires elevated permissions.
|
|
1011
1012
|
Required scopes: ${o.requiredScopes?.join(", ")||"unknown"}
|
|
1012
1013
|
|
|
1013
|
-
`+(o.authUrl?`Re-authorize at: ${o.authUrl}`:"Please re-authenticate with elevated permissions.")}],details:{type:"mcp",action:"authenticate",server:r.server,status:"step_up_required"}};case"unsupported":return{content:[{type:"text",text:`Authentication not supported for "${r.server}" (${o.message||"uses local transport"}).`}],details:{type:"mcp",action:"authenticate",server:r.server,status:"unsupported"}};default:return{content:[{type:"text",text:`Authentication error for "${r.server}": ${o.message||"unknown error"}`}],details:{type:"mcp",action:"authenticate",server:r.server,status:"error"}}}}case"manage_server":{if(!r.server)return le("server is required for manage_server.");if(!r.manageAction)return le("manageAction is required for manage_server.");switch(r.manageAction){case"add":{if(!t.addServer)return le("Server addition not supported by the current MCP host.");if(!r.config)return le("config is required for manage_server add.");let o=await t.addServer(r.server,r.config);return ko("add",r.server,o)}case"remove":{if(!t.removeServer)return le("Server removal not supported by the current MCP host.");let o=await t.removeServer(r.server);return ko("remove",r.server,o)}case"restart":{if(!t.restartServer)return le("Server restart not supported by the current MCP host.");let o=await t.restartServer(r.server);return ko("restart",r.server,o)}case"health_check":{if(!t.healthCheck)return le("Health check not supported by the current MCP host.");let o=await t.healthCheck(r.server);return ko("health_check",r.server,o)}case"enable":case"disable":{if(!t.setServerEnabled)return le("Server enable/disable not supported by the current MCP host.");let o=await t.setServerEnabled(r.server,r.manageAction==="enable");return ko(r.manageAction,r.server,o)}default:return le(`Unknown manageAction: ${r.manageAction}`)}}default:return le(`Unknown action: "${r.action}".`)}}}}function le(t){return{content:[{type:"text",text:`Error: ${t}`}],details:{type:"mcp",error:t}}}function
|
|
1014
|
-
`)}],details:{type:"mcp",action:"manage_server",manageAction:t,server:e,success:r.success}}}import*as
|
|
1015
|
-
`).pop()?.trim();if(!l)return r.warn(`[marketplace] npm pack returned no output for ${a}`),null;let d=So.join(i,l),p=l.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=So.join(i,`${t}@${p}`);be.existsSync(m)||be.mkdirSync(m,{recursive:!0}),await s("tar",["xzf",d,"-C",m,"--strip-components=1"],{timeout:3e4});try{be.unlinkSync(d)}catch{}let g=So.join(m,"package.json");if(be.existsSync(g))try{await s("npm",["install","--production","--no-save"],{cwd:m,timeout:12e4})}catch(f){r.warn(`[marketplace] npm install for ${t} failed: ${f.message}`)}return r.info(`[marketplace] installed ${t}@${p} from npm`),{name:t,version:p,installPath:m}}catch(c){return r.warn(`[marketplace] failed to install ${a} from npm: ${c.message}`),null}}function
|
|
1016
|
-
`)}}catch(l){return{success:!1,error:l.message}}},listResources:async r=>(await t.listResources(r)).map(o=>({uri:o.uri,name:o.name,mimeType:o.mimeType,description:o.description,server:o.server})),readResource:async(r,n)=>(await t.readResource(r,n)).map(s=>({uri:s.uri,mimeType:s.mimeType,text:s.text})),authenticate:async()=>({status:"unsupported",message:"OAuth not yet implemented in McpManager"})})}function sw(t){let e=[],r=Ku();kn.existsSync(r)&&e.push(r);let n=t.config.pluginPaths;if(Array.isArray(n))for(let o of n)typeof o=="string"&&kn.existsSync(o)&&e.push(o);rw(e,t.log).then(o=>{if(o.length===0)return;let s=new ji({pluginDirs:o,hookRegistry:t.hooks,log:t.log});t.setPluginLoader(s),s.loadAll().then(i=>{t.log.info(`[plugins] ${i.length} loaded, ${s.getPluginSkills().length} skills`)}).catch(i=>{t.log.warn(`[plugins] load error: ${i instanceof Error?i.message:i}`)}),t.hooks.register({point:"turn.submitted",handler:async()=>(await s.discoverNew(),await s.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(o=>{t.log.warn(`[plugins] marketplace resolve error: ${o instanceof Error?o.message:o}`)})}import*as Pt from"node:fs";import*as wo from"node:path";var
|
|
1017
|
-
`;Pt.appendFileSync(this.filePath,n,"utf-8")}catch{}}};function iw(t){if(!t)return;let e={},r=/key|secret|token|password|credential|auth/i;for(let[n,o]of Object.entries(t))r.test(n)?e[n]="[REDACTED]":typeof o=="string"&&o.length>500?e[n]=o.slice(0,500)+"...[truncated]":e[n]=o;return e}import{randomUUID as
|
|
1014
|
+
`+(o.authUrl?`Re-authorize at: ${o.authUrl}`:"Please re-authenticate with elevated permissions.")}],details:{type:"mcp",action:"authenticate",server:r.server,status:"step_up_required"}};case"unsupported":return{content:[{type:"text",text:`Authentication not supported for "${r.server}" (${o.message||"uses local transport"}).`}],details:{type:"mcp",action:"authenticate",server:r.server,status:"unsupported"}};default:return{content:[{type:"text",text:`Authentication error for "${r.server}": ${o.message||"unknown error"}`}],details:{type:"mcp",action:"authenticate",server:r.server,status:"error"}}}}case"manage_server":{if(!r.server)return le("server is required for manage_server.");if(!r.manageAction)return le("manageAction is required for manage_server.");switch(r.manageAction){case"add":{if(!t.addServer)return le("Server addition not supported by the current MCP host.");if(!r.config)return le("config is required for manage_server add.");let o=await t.addServer(r.server,r.config);return ko("add",r.server,o)}case"remove":{if(!t.removeServer)return le("Server removal not supported by the current MCP host.");let o=await t.removeServer(r.server);return ko("remove",r.server,o)}case"restart":{if(!t.restartServer)return le("Server restart not supported by the current MCP host.");let o=await t.restartServer(r.server);return ko("restart",r.server,o)}case"health_check":{if(!t.healthCheck)return le("Health check not supported by the current MCP host.");let o=await t.healthCheck(r.server);return ko("health_check",r.server,o)}case"enable":case"disable":{if(!t.setServerEnabled)return le("Server enable/disable not supported by the current MCP host.");let o=await t.setServerEnabled(r.server,r.manageAction==="enable");return ko(r.manageAction,r.server,o)}default:return le(`Unknown manageAction: ${r.manageAction}`)}}default:return le(`Unknown action: "${r.action}".`)}}}}function le(t){return{content:[{type:"text",text:`Error: ${t}`}],details:{type:"mcp",error:t}}}function Ij(t){switch(t){case"connected":return"\u2705";case"connecting":return"\u23F3";case"needs-auth":return"\u{1F511}";case"failed":return"\u274C";case"disconnected":return"\u26AA";case"disabled":return"\u{1F6AB}";default:return"\u2753"}}function Ej(t){if(!t)return"";let e=[];return t.readOnlyHint&&e.push("\u{1F4D6}"),t.destructiveHint&&e.push("\u26A0\uFE0F"),t.idempotentHint&&e.push("\u267B\uFE0F"),e.length>0?` ${e.join("")}`:""}function _j(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function ko(t,e,r){let n=[];return n.push(`${r.success?"\u2705":"\u274C"} ${t} "${e}": ${r.message}`),r.serverState&&(n.push(""),n.push(` Status: ${r.serverState.status}`),n.push(` Tools: ${r.serverState.toolCount} | Resources: ${r.serverState.resourceCount}`)),{content:[{type:"text",text:n.join(`
|
|
1015
|
+
`)}],details:{type:"mcp",action:"manage_server",manageAction:t,server:e,success:r.success}}}import*as Gt from"node:fs";import*as Ro from"node:path";import{pathToFileURL as Mj}from"node:url";var ZS={preToolUse:"tool.before_invoke",postToolUse:"tool.after_invoke",onTurnStart:"turn.submitted",onTurnEnd:"turn.completed",onSessionEnd:"session.ended"};var ji=class{constructor(e){this.config=e;this.log=e.log??{info:()=>{},warn:()=>{}}}config;loaded=[];pluginSkills=[];activations=new Map;log;async loadAll(){for(let e of this.config.pluginDirs){if(!Gt.existsSync(e))continue;let r;try{r=Gt.readdirSync(e,{withFileTypes:!0})}catch{continue}for(let n of r){if(!n.isDirectory()||n.name.startsWith(".")||n.name.startsWith("_"))continue;let o=Ro.join(e,n.name);await this.loadPlugin(n.name,o)}}return this.log.info(`[plugins] loaded ${this.loaded.length} plugin(s): ${this.loaded.map(e=>e.name).join(", ")||"(none)"}`),this.loaded}getPluginSkills(){return this.pluginSkills}getLoaded(){return this.loaded}async discoverNew(){let e=new Set(this.loaded.map(n=>n.name)),r=0;for(let n of this.config.pluginDirs){if(!Gt.existsSync(n))continue;let o;try{o=Gt.readdirSync(n,{withFileTypes:!0})}catch{continue}for(let s of o){if(!s.isDirectory()||s.name.startsWith(".")||s.name.startsWith("_")||e.has(s.name))continue;let i=Ro.join(n,s.name);await this.loadPlugin(s.name,i),r++}}return r>0&&this.log.info(`[plugins] discovered ${r} new plugin(s)`),r}async refreshActivations(){let e=Date.now();for(let[r,n]of this.activations){if(e-n.lastCheckAt<n.ttlMs)continue;let o;try{o=await n.checkFn()}catch(s){this.log.warn(`[plugins] ${r}: check_fn error: ${s instanceof Error?s.message:s}`),o=n.lastResult}if(n.lastCheckAt=e,o!==n.lastResult){if(n.lastResult=o,o&&!n.active){for(let s of n.tools)K(s);n.active=!0,this.log.info(`[plugins] ${r}: reactivated (${n.tools.length} tools)`)}else if(!o&&n.active){for(let s of n.tools)Jo(s.name);for(let s of n.hookUnregisterFns)s();n.active=!1,this.log.info(`[plugins] ${r}: deactivated`)}}}}async loadPlugin(e,r){let n=["index.js","index.mjs"],o=null;for(let f of n){let h=Ro.join(r,f);if(Gt.existsSync(h)){o=h;break}}if(!o){this.log.warn(`[plugins] ${e}: no index.js found, skipping`);return}let s=0,i=0,a=0,c=[],l=[],d=null,u=6e4,p={},m=Ro.join(r,"config.json");if(Gt.existsSync(m))try{p=JSON.parse(Gt.readFileSync(m,"utf8"))}catch{}let g={pluginName:e,registerTool:f=>{K(f),c.push(f),s++},registerHook:(f,h)=>{let v=ZS[f];if(!v){this.log.warn(`[plugins] ${e}: unknown hook phase "${f}"`);return}let b=this.config.hookRegistry.register({point:v,handler:h,label:`plugin:${e}:${f}`,priority:200});l.push(b),i++},registerSkill:f=>{this.pluginSkills.push(f),a++},getConfig:()=>p,setActivationCheck:(f,h)=>{d=f,h!==void 0&&(u=h)}};try{let h=await import(Mj(o).href);if(typeof h.register!="function"){this.log.warn(`[plugins] ${e}: no register() export, skipping`);return}await h.register(g),d&&this.activations.set(e,{checkFn:d,ttlMs:u,lastCheckAt:Date.now(),lastResult:!0,tools:c,hookUnregisterFns:l,active:!0}),this.loaded.push({name:e,directory:r,toolCount:s,hookCount:i,skillCount:a}),this.log.info(`[plugins] ${e}: ${s} tools, ${i} hooks, ${a} skills`)}catch(f){this.log.warn(`[plugins] ${e}: load error: ${f instanceof Error?f.message:f}`)}}};D();import*as be from"node:fs";import*as So from"node:path";function Qd(){return Vu()}function ew(){return So.join(Qd(),"installed_plugins.json")}function tw(){let t=ew();if(!be.existsSync(t))return{version:1,plugins:[]};try{return JSON.parse(be.readFileSync(t,"utf-8"))}catch{return{version:1,plugins:[]}}}function Dj(t){let e=Qd();be.existsSync(e)||be.mkdirSync(e,{recursive:!0}),be.writeFileSync(ew(),JSON.stringify(t,null,2),"utf-8")}function Nj(t,e){return!(e.blocklist?.includes(t)||e.allowlist&&!e.allowlist.includes(t))}async function Lj(t,e,r){let{execFile:n}=await import("node:child_process"),{promisify:o}=await import("node:util"),s=o(n),i=Qd(),a=e?`${t}@${e}`:t;try{let{stdout:c}=await s("npm",["pack",a,"--pack-destination",i],{timeout:6e4,cwd:i}),l=c.trim().split(`
|
|
1016
|
+
`).pop()?.trim();if(!l)return r.warn(`[marketplace] npm pack returned no output for ${a}`),null;let d=So.join(i,l),p=l.match(/^(.+)-(\d+\.\d+\.\d+.*)\.tgz$/)?.[2]??"0.0.0",m=So.join(i,`${t}@${p}`);be.existsSync(m)||be.mkdirSync(m,{recursive:!0}),await s("tar",["xzf",d,"-C",m,"--strip-components=1"],{timeout:3e4});try{be.unlinkSync(d)}catch{}let g=So.join(m,"package.json");if(be.existsSync(g))try{await s("npm",["install","--production","--no-save"],{cwd:m,timeout:12e4})}catch(f){r.warn(`[marketplace] npm install for ${t} failed: ${f.message}`)}return r.info(`[marketplace] installed ${t}@${p} from npm`),{name:t,version:p,installPath:m}}catch(c){return r.warn(`[marketplace] failed to install ${a} from npm: ${c.message}`),null}}function Oj(){return tw().plugins.filter(e=>be.existsSync(e.installPath)).map(e=>e.installPath)}async function jj(t,e){let r=tw(),n=[];for(let o of t.enabledPlugins){let s=o.specifier.split("/").pop()??o.specifier;if(!Nj(s,t)){e.warn(`[marketplace] plugin "${s}" blocked by enterprise policy`);continue}let i=r.plugins.find(c=>c.source.specifier===o.specifier&&c.source.type===o.type);if(i&&be.existsSync(i.installPath)&&(!o.version||i.version===o.version)){n.push(i.installPath);continue}let a=null;switch(o.type){case"npm":a=await Lj(o.specifier,o.version,e);break;case"git":case"url":e.warn(`[marketplace] ${o.type} source not yet implemented for "${o.specifier}"`);break}if(a){let c={name:a.name,version:a.version,source:o,installPath:a.installPath,installedAt:new Date().toISOString()};r.plugins=r.plugins.filter(l=>!(l.source.specifier===o.specifier&&l.source.type===o.type)),r.plugins.push(c),n.push(a.installPath)}}return Dj(r),n}function $j(){let t=Yu();if(!be.existsSync(t))return null;try{return JSON.parse(be.readFileSync(t,"utf-8"))}catch{return null}}async function rw(t,e){let r=[...t],n=Oj();r.push(...n);let o=$j();if(o&&o.enabledPlugins.length>0)try{let s=await jj(o,e),i=new Set(r);for(let a of s)i.has(a)||r.push(a)}catch(s){e.warn(`[marketplace] failed to update plugins: ${s.message}`)}return r}D();function ow(t){let e=t.config.mcpServers,r,n=Xu();try{kn.existsSync(n)&&(r=JSON.parse(kn.readFileSync(n,"utf8")))}catch{}let o=Uj({turnMcpConfig:e??{},userMcpConfig:r,projectRoot:t.projectRoot});if(o.length===0)return;t.currentManager?.disconnectAll().catch(()=>{});let s=new Oi({servers:o,log:t.log,workspaceRoot:t.projectRoot});t.setManager(s),Vt(async()=>{await s.disconnectAll()});let i=()=>s;K(YS(i)),K(JS(i)),K(Fj(s,t.toolCatalog)),t.setReady(s.connectAll().then(()=>{s.injectTools(),t.log.info(`[mcp] ${s.getToolCount()} tools from ${s.getConnectedServers().length} servers`)}).catch(a=>{t.log.warn(`[mcp] connection error: ${a instanceof Error?a.message:a}`)}))}function Uj(t){let e=nw(Jd(t.turnMcpConfig??{}),t.projectRoot),r=nw(Jd(t.userMcpConfig??{}),t.projectRoot),n=new Set(e.map(o=>o.name));return[...e,...r.filter(o=>!n.has(o.name))]}function nw(t,e){return t.map(r=>(r.type??"stdio")!=="stdio"||r.cwd?r:{...r,cwd:e})}function Fj(t,e){return QS({listServers:async()=>t.getConnectedServers().map(n=>({name:n,status:"connected",transport:"stdio",toolCount:0,resourceCount:0,promptCount:0})),listTools:async r=>{let n=`mcp__${r.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`;return e.getToolNames().filter(o=>o.startsWith(n)).map(o=>({name:o.slice(n.length),prefixedName:o}))},callTool:async(r,n,o,s)=>{let a=`mcp__${r.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}__`+n,c=e.findTool(a);if(!c||!("execute"in c)||typeof c.execute!="function")return{success:!1,error:`Tool not found: ${a}`};try{return{success:!0,content:(await c.execute(`mcp_${Date.now()}`,o??{},s)).content.map(u=>u.text??"").join(`
|
|
1017
|
+
`)}}catch(l){return{success:!1,error:l.message}}},listResources:async r=>(await t.listResources(r)).map(o=>({uri:o.uri,name:o.name,mimeType:o.mimeType,description:o.description,server:o.server})),readResource:async(r,n)=>(await t.readResource(r,n)).map(s=>({uri:s.uri,mimeType:s.mimeType,text:s.text})),authenticate:async()=>({status:"unsupported",message:"OAuth not yet implemented in McpManager"})})}function sw(t){let e=[],r=Ku();kn.existsSync(r)&&e.push(r);let n=t.config.pluginPaths;if(Array.isArray(n))for(let o of n)typeof o=="string"&&kn.existsSync(o)&&e.push(o);rw(e,t.log).then(o=>{if(o.length===0)return;let s=new ji({pluginDirs:o,hookRegistry:t.hooks,log:t.log});t.setPluginLoader(s),s.loadAll().then(i=>{t.log.info(`[plugins] ${i.length} loaded, ${s.getPluginSkills().length} skills`)}).catch(i=>{t.log.warn(`[plugins] load error: ${i instanceof Error?i.message:i}`)}),t.hooks.register({point:"turn.submitted",handler:async()=>(await s.discoverNew(),await s.refreshActivations(),{action:"continue"}),label:"plugin-activation-refresh",priority:50})}).catch(o=>{t.log.warn(`[plugins] marketplace resolve error: ${o instanceof Error?o.message:o}`)})}import*as Pt from"node:fs";import*as wo from"node:path";var Hj="audit",Bj="denials.jsonl",qj=10*1024*1024,$i=class{filePath;writeQueue=Promise.resolve();constructor(e){let r=wo.join(e,".qlogicagent",Hj);this.filePath=wo.join(r,Bj)}record(e){this.writeQueue=this.writeQueue.then(()=>this.doWrite(e)).catch(()=>{})}getFilePath(){return this.filePath}async doWrite(e){try{let r=wo.dirname(this.filePath);if(Pt.existsSync(r)||Pt.mkdirSync(r,{recursive:!0}),Pt.existsSync(this.filePath)&&Pt.statSync(this.filePath).size>qj){let s=this.filePath+".1";Pt.renameSync(this.filePath,s)}let n=JSON.stringify(e)+`
|
|
1018
|
+
`;Pt.appendFileSync(this.filePath,n,"utf-8")}catch{}}};function iw(t){if(!t)return;let e={},r=/key|secret|token|password|credential|auth/i;for(let[n,o]of Object.entries(t))r.test(n)?e[n]="[REDACTED]":typeof o=="string"&&o.length>500?e[n]=o.slice(0,500)+"...[truncated]":e[n]=o;return e}import{randomUUID as Qj}from"node:crypto";var Wj=new Set(["nodeversion","npmversion","npxversion","pnpmversion","yarnversion","bunversion","denoversion","pythonversion","python3version","pipversion","rubyversion","go version","rustcversion","cargoversion","java -version","javac -version","dotnetversion","gccversion","g++version","clangversion","gitversion","dockerversion","--help","-h"]),aw=new Set(["ls","dir","find","fd","locate","which","where","type","cat","head","tail","less","more","bat","wc","file","stat","du","df","tree","exa","eza","grep","rg","ripgrep","ag","ack","fgrep","egrep","git status","git log","git diff","git show","git branch","git tag","git remote","git stash list","git blame","git shortlog","git describe","git rev-parse","git ls-files","git ls-tree","git cat-file","git reflog","ps","top","htop","uptime","uname","hostname","whoami","id","env","printenv","echo","ping","nslookup","dig","host","ifconfig","ip","netstat","ss","npm list","npm ls","npm info","npm view","npm outdated","npm audit","pnpm list","pnpm ls","pnpm outdated","pip list","pip show","pip freeze","cargo tree","npm test","npm run test","npm run build","npm run lint","pnpm test","pnpm run test","pnpm run build","pnpm run lint","yarn test","yarn build","yarn lint","cargo test","cargo build","cargo check","cargo clippy","go test","go build","go vet","make","cmake","pytest","python -m pytest","python3 -m pytest","jest","vitest","mocha","tsc","tscnoEmit","eslint","prettier","oxlint"]),Gj=[/\brm\s+-rf?\s+[/~]/,/\brm\s+-rf?\s+\.\.\//,/\bsudo\b/,/\bsu\s/,/\bchmod\s+777\b/,/\bmkfs\b/,/\bfdisk\b/,/\bdd\s+if=/,/\bsystemctl\s+(start|stop|restart|enable|disable)\b/,/\bservice\s+\S+\s+(start|stop|restart)\b/,/\breg\s+(add|delete)\b/i,/\\Windows\\System32/i,/\/etc\/(passwd|shadow|sudoers|fstab)/,/\bgit\s+push\s+.*--force\b/,/\bgit\s+push\s+-f\b/,/\bcurl\b.*(-H|--header)\s+.*[Aa]uthorization/,/\bwget\b.*--header.*[Aa]uthorization/,/\bcurl\b.*\|\s*(sh|bash|zsh)\b/,/\bwget\b.*-O\s*-\s*\|\s*(sh|bash|zsh)\b/,/\bnpm\s+install\s+-g\b/,/\bpip\s+install\b(?!.*-r\b)(?!.*requirements)/,/\bDROP\s+(DATABASE|TABLE|SCHEMA)\b/i,/\bTRUNCATE\s+TABLE\b/i],cw=new Set(["npm install","npm i","npm ci","pnpm install","pnpm i","yarn install","yarn","pip install -r","pip install -e","cargo build","cargo install","go mod download","go get","bundle install","composer install","git add","git commit","git stash","git checkout","git switch","git merge","git rebase","git cherry-pick","git pull","git fetch","docker build","docker compose","mkdir","touch","cp"]);function lw(t,e,r){let n=t.trim();if(!n)return{decision:"allow",reason:"empty command"};let o=ud(n)??pd(n)??void 0;for(let l of Gj)if(l.test(n))return{decision:"deny",reason:`matches dangerous pattern: ${l.source}`,destructiveWarning:o};for(let l of Wj)if(n===l||n.startsWith(l+" "))return{decision:"allow",reason:`known safe command: ${l}`,destructiveWarning:o};let s=n.split(/\s+/),i=s[0],a=s.length>1?`${s[0]} ${s[1]}`:i;return aw.has(i)||aw.has(a)?{decision:"allow",reason:`known safe command: ${i}`,destructiveWarning:o}:e&&r&&e.startsWith(r)&&(cw.has(i)||cw.has(a))?{decision:"allow",reason:`safe in project: ${a}`,destructiveWarning:o}:{decision:"defer",reason:"unknown command \u2014 needs LLM classification",destructiveWarning:o}}function Kj(t){let e=Object.keys(t).sort(),r={};for(let n of e){let o=t[n];typeof o=="string"?r[n]=o.replace(/\s+/g," ").trim():r[n]=o}return JSON.stringify(r)}function Zd(t,e){return`${t}::${Kj(e)}`}var zj=500,Ui=class{cache=new Map;get(e,r){let n=Zd(e,r),o=this.cache.get(n);if(o)return o.hitCount++,o}set(e,r,n){if(this.cache.size>=zj){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let o=Zd(e,r);this.cache.set(o,{shouldBlock:n.shouldBlock,reason:n.reason,classifiedAt:Date.now(),hitCount:0})}has(e,r){return this.cache.has(Zd(e,r))}clear(){this.cache.clear()}get size(){return this.cache.size}get totalHits(){let e=0;for(let r of this.cache.values())e+=r.hitCount;return e}};var Vj=new Set(["read","search","instructions","think","task","memory","skill","tool_search","plan_mode","lsp","brief","web_search","image_generate","video_generate","music_generate","tts","three_d_generate","checkpoint"]);function To(t){return Vj.has(t)}var dw=`You are a security classifier for an AI coding agent. Your job is to decide whether a tool invocation is safe to execute without user confirmation.
|
|
1018
1019
|
|
|
1019
1020
|
The agent operates in a workspace and has been given permission to use tools autonomously. You must decide if each tool call is SAFE (routine development work) or DANGEROUS (could cause harm, data loss, or unexpected side effects).
|
|
1020
1021
|
|
|
@@ -1036,7 +1037,7 @@ DANGEROUS operations (SHOULD be blocked):
|
|
|
1036
1037
|
- Running commands with sudo/admin privileges
|
|
1037
1038
|
- Downloading and executing unknown scripts
|
|
1038
1039
|
|
|
1039
|
-
Respond ONLY with XML. No other text.`;async function eu(t,e,r,n){let o=Date.now();if(To(t))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-o};let s=
|
|
1040
|
+
Respond ONLY with XML. No other text.`;async function eu(t,e,r,n){let o=Date.now();if(To(t))return{shouldBlock:!1,reason:"allowlisted safe tool",stage:"allowlist",durationMs:Date.now()-o};let s=Xj(r),i=Yj(t,e),a=`<transcript>
|
|
1040
1041
|
${s}
|
|
1041
1042
|
</transcript>
|
|
1042
1043
|
|
|
@@ -1052,24 +1053,24 @@ ${s}
|
|
|
1052
1053
|
${i}
|
|
1053
1054
|
</action>
|
|
1054
1055
|
|
|
1055
|
-
The fast classifier flagged this action. Review carefullyis it actually dangerous, or is it safe development work? Consider the project context. Use <thinking> tags to reason, then respond with <block>yes</block> or <block>no</block> and <reason>explanation</reason>.`,p=await n({system:dw,messages:[{role:"user",content:u}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=mw(p.text),g=uw(m),f=pw(m)??pw(l)??"classifier decision";return{shouldBlock:g!==!1,reason:f,stage:"thinking",durationMs:Date.now()-o}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-o}}}function
|
|
1056
|
-
`)}function
|
|
1057
|
-
Arguments: ${n}`}function uw(t){let e=t.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function pw(t){let e=t.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function mw(t){return t.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var gw={maxConsecutive:3,maxTotal:20};function fw(){return{consecutiveDenials:0,totalDenials:0}}function tu(t){return{consecutiveDenials:t.consecutiveDenials+1,totalDenials:t.totalDenials+1}}function ru(t){return t.consecutiveDenials===0?t:{...t,consecutiveDenials:0}}function hw(t){return t.consecutiveDenials>=gw.maxConsecutive||t.totalDenials>=gw.maxTotal}var Yj=[{pattern:"exec",behavior:"deny",reason:"Community L1 sandbox denied shell execution",source:"community-sandbox",ruleId:"community-l1-shell"},{pattern:"Bash",behavior:"deny",reason:"Community L1 sandbox denied shell execution",source:"community-sandbox",ruleId:"community-l1-shell"},{pattern:"execute_command",behavior:"deny",reason:"Community L1 sandbox denied shell execution",source:"community-sandbox",ruleId:"community-l1-shell"},{pattern:"read",behavior:"deny",reason:"Community L1 sandbox denied file reads",source:"community-sandbox",ruleId:"community-l1-file-read"},{pattern:"write",behavior:"deny",reason:"Community L1 sandbox denied file writes",source:"community-sandbox",ruleId:"community-l1-file-write"},{pattern:"edit",behavior:"deny",reason:"Community L1 sandbox denied file edits",source:"community-sandbox",ruleId:"community-l1-file-write"},{pattern:"apply_patch",behavior:"deny",reason:"Community L1 sandbox denied file patching",source:"community-sandbox",ruleId:"community-l1-file-write"},{pattern:"web_fetch",behavior:"deny",reason:"Community L1 sandbox denied network egress",source:"community-sandbox",ruleId:"community-l1-network"},{pattern:"web_search",behavior:"deny",reason:"Community L1 sandbox denied network egress",source:"community-sandbox",ruleId:"community-l1-network"},{pattern:"mcp",behavior:"deny",reason:"Community L1 sandbox denied MCP access",source:"community-sandbox",ruleId:"community-l1-mcp"},{pattern:"mcp__*",behavior:"deny",reason:"Community L1 sandbox denied MCP access",source:"community-sandbox",ruleId:"community-l1-mcp"},{pattern:"computer",behavior:"deny",reason:"Community L1 sandbox denied host control",source:"community-sandbox",ruleId:"community-l1-host-control"},{pattern:"notify",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"send_message",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"agent",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"team",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"cron",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"monitor",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"file_upload",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for local file data egress",source:"community-sandbox",ruleId:"community-l2-data-egress"},{pattern:"image_generate",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider prompt egress",source:"community-sandbox",ruleId:"community-l2-provider-prompt-egress"},{pattern:"video_generate",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider prompt egress",source:"community-sandbox",ruleId:"community-l2-provider-prompt-egress"},{pattern:"music_generate",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider prompt egress",source:"community-sandbox",ruleId:"community-l2-provider-prompt-egress"},{pattern:"tts",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider prompt egress",source:"community-sandbox",ruleId:"community-l2-provider-prompt-egress"},{pattern:"three_d_generate",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider prompt egress",source:"community-sandbox",ruleId:"community-l2-provider-prompt-egress"},{pattern:"video_edit",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider media egress",source:"community-sandbox",ruleId:"community-l2-provider-media-egress"},{pattern:"video_merge",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider media egress",source:"community-sandbox",ruleId:"community-l2-provider-media-egress"},{pattern:"video_upscale",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider media egress",source:"community-sandbox",ruleId:"community-l2-provider-media-egress"},{pattern:"voice_clone",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider media egress",source:"community-sandbox",ruleId:"community-l2-provider-media-egress"},{pattern:"stt",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider media egress",source:"community-sandbox",ruleId:"community-l2-provider-media-egress"}];function yw(){return Yj.map(({ruleId:t,...e})=>({...e}))}var Qj=12e4,Fi=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;auditLogger;sessionId;getTurnId;communityTelemetryRecorder;communitySandboxTurnIds=new Set;communitySandboxRuleEngine=new hn({mode:"default",defaultBehavior:"allow",rules:yw()});unregisterHook=null;toolMetaCache=new Map;classifierCache=new Ui;denialTracking=fw();constructor(e){this.ruleEngine=e.ruleEngine,this.hookRegistry=e.hookRegistry,this.onRequestApproval=e.onRequestApproval,this.onPermissionUpdate=e.onPermissionUpdate,this.onDenied=e.onDenied,this.classifierLLMCall=e.classifierLLMCall,this.getRecentMessages=e.getRecentMessages,this.permissionRole=e.permissionRole??"interactive",this.auditLogger=e.auditLogger,this.sessionId=e.sessionId??"",this.getTurnId=e.getTurnId??(()=>""),this.communityTelemetryRecorder=e.communityTelemetryRecorder}register(){this.unregisterHook&&this.unregisterHook(),this.classifierCache.clear();let e=this.hookRegistry.register({point:"tool.before_invoke",priority:100,label:"permission-checker",handler:async(o,s)=>{let i=this.toolMetaCache.get(s.toolName),a={toolName:s.toolName,arguments:s.arguments,meta:i?{isReadOnly:i.isReadOnly,isDangerous:i.isDangerous,requiresApproval:i.requiresApproval,parallelSafe:i.parallelSafe}:void 0},c=this.communitySandboxTurnIds.has(s.turnId)?this.checkCommunitySandboxThenBase(a):this.ruleEngine.check(a);return this.handleResult(c,s.callId,s.toolName,s.arguments)}}),r=this.hookRegistry.register({point:"subagent.started",priority:20,label:"community-sandbox-scope-start",handler:(o,s)=>(s.agentType?.startsWith("community-skill:")&&this.communitySandboxTurnIds.add(s.turnId),{action:"continue"})}),n=this.hookRegistry.register({point:"subagent.stopped",priority:20,label:"community-sandbox-scope-stop",handler:(o,s)=>(s.agentType?.startsWith("community-skill:")&&this.communitySandboxTurnIds.delete(s.turnId),{action:"continue"})});return this.unregisterHook=()=>{e(),r(),n(),this.communitySandboxTurnIds.clear()},()=>{this.unregisterHook?.(),this.unregisterHook=null,this.cancelAllPending()}}resolveApproval(e){let r=this.pendingApprovals.get(e.approvalId);r&&(clearTimeout(r.timeoutId),this.pendingApprovals.delete(e.approvalId),r.resolve(e))}setToolMeta(e){this.toolMetaCache.clear();for(let r of e)r.meta&&this.toolMetaCache.set(r.function.name,r.meta)}get ruleEngineRef(){return this.ruleEngine}checkCommunitySandboxThenBase(e){let r=this.communitySandboxRuleEngine.check(e);return r.behavior!=="allow"?r:this.ruleEngine.check(e)}fireDenied(e,r,n,o="classifier",s,i=e$(o)){this.onDenied?.(r,n),this.hookRegistry.invoke("permission.denied",{sessionId:this.sessionId,turnId:this.getTurnId(),approvalId:e,callId:e,toolName:r,decision:"denied",reason:n}).catch(()=>{}),this.auditLogger&&this.auditLogger.record({timestamp:new Date().toISOString(),sessionId:this.sessionId,turnId:this.getTurnId(),toolName:r,reason:n,source:o,permissionRole:this.permissionRole,callId:e,toolArgs:iw(s),cumulativeDenials:this.denialTracking.totalDenials,consecutiveDenials:this.denialTracking.consecutiveDenials}),Zj(o)&&this.communityTelemetryRecorder?.recordTelemetry({event:"community.sandbox.violation",metadata:{surface:"permission-checker",action:"blocked",source:o,ruleId:i,platform:process.platform}}).catch(()=>{})}async handleResult(e,r,n,o){if(e.behavior==="allow")return{action:"continue",context:e.updatedInput?{arguments:e.updatedInput}:void 0};if(e.behavior==="deny")return this.fireDenied(r,n,e.message,"rule-engine",o,nu(e.decisionReason)),{action:"abort",reason:e.message};let s=t$(e),i=e.decisionReason?.type==="tool_check"&&(e.decisionReason.reason==="isDangerous"||e.decisionReason.reason==="requiresApproval");if(s&&this.permissionRole!=="interactive")return this.fireDenied(r,n,`community sandbox requires interactive approval: ${e.message}`,"safety",o,nu(e.decisionReason)),{action:"abort",reason:`Tool "${n}" blocked by community sandbox (${this.permissionRole} agents cannot approve tainted egress)`};if(s)return this.handleInteractiveApproval(e,r,n,o);if(i&&this.permissionRole!=="interactive")return this.fireDenied(r,n,`safety check: ${e.message} (${this.permissionRole} cannot override)`,"safety",o,nu(e.decisionReason)),{action:"abort",reason:`Tool "${n}" blocked by safety check (${this.permissionRole} agents cannot override dangerous tool restrictions)`};if((n==="bash"||n==="execute_command"||n==="Bash"||n==="shell")&&o){let c=o.command??o.cmd??"";if(c){let l=lw(c);if(l.decision==="allow")return{action:"continue"};if(l.decision==="deny")return this.fireDenied(r,n,l.reason,"classifier",o,"bash-classifier-deny"),{action:"abort",reason:l.reason}}}if(o){let c=this.classifierCache.get(n,o);if(c)return c.shouldBlock?(this.fireDenied(r,n,`cached: ${c.reason}`,"classifier",o,"classifier-cached-deny"),{action:"abort",reason:c.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(r,n,o);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(n)?.isReadOnly||To(n)?{action:"continue"}:this.handleWorkerAsk(r,n,o);if(this.ruleEngine.getMode()==="auto"){if(To(n))return{action:"continue"};let c=hw(this.denialTracking);if(this.classifierLLMCall&&!c)try{let l=this.getRecentMessages?.()??[],d=await eu(n,o??{},l,this.classifierLLMCall);if(o&&this.classifierCache.set(n,o,{shouldBlock:d.shouldBlock,reason:d.reason}),!d.shouldBlock)return this.denialTracking=ru(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:d.reason}}};this.denialTracking=tu(this.denialTracking)}catch{}}return this.handleInteractiveApproval(e,r,n,o)}async handleInteractiveApproval(e,r,n,o){let s=Jj(),i={approvalId:s,callId:r,toolName:n,arguments:o,message:e.message,suggestions:e.suggestions};this.hookRegistry.invoke("approval.requested",{sessionId:"",turnId:"",approvalId:s,callId:r,toolName:n}).catch(()=>{});try{let a=await this.requestApproval(i);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:s,callId:r,toolName:n,decision:a.decision==="approved"?"approved":"denied"}).catch(()=>{}),a.permissionUpdate&&(this.ruleEngine.applyUpdate(a.permissionUpdate),this.onPermissionUpdate?.(a.permissionUpdate)),a.decision==="approved"?{action:"continue",context:a.updatedInput?{arguments:a.updatedInput}:void 0}:(this.fireDenied(r,n,`denied by user (approval ${s})`,"user",o),{action:"abort",reason:`Tool "${n}" denied by user`})}catch{return this.fireDenied(r,n,`approval timeout or error (approval ${s})`,"timeout",o),{action:"abort",reason:`Tool "${n}"approval timed out`}}}async handleWorkerAsk(e,r,n){if(To(r))return{action:"continue"};if(this.classifierLLMCall)try{let o=this.getRecentMessages?.()??[],s=await eu(r,n??{},o,this.classifierLLMCall);return n&&this.classifierCache.set(r,n,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=tu(this.denialTracking),this.fireDenied(e,r,`blocked by classifier in ${this.permissionRole} mode: ${s.reason}`,"classifier",n,"classifier-deny"),{action:"abort",reason:`Tool "${r}" blocked by classifier (${this.permissionRole})`}):(this.denialTracking=ru(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:this.permissionRole,reason:s.reason}}})}catch{}return this.fireDenied(e,r,`no classifier available in ${this.permissionRole} mode`,"static-deny",void 0,"static-deny"),{action:"abort",reason:`Tool "${r}" deniedno classifier for ${this.permissionRole} mode`}}requestApproval(e){return new Promise((r,n)=>{let o=setTimeout(()=>{this.pendingApprovals.delete(e.approvalId),n(new Error("Approval timed out"))},Qj);this.pendingApprovals.set(e.approvalId,{resolve:r,reject:n,timeoutId:o}),this.onRequestApproval(e).then(s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),r(s))},s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),n(s))})})}clearClassifierCache(){this.classifierCache.clear(),this.denialTracking={consecutiveDenials:0,totalDenials:0}}cancelAllPending(){this.classifierCache.clear();for(let[e,r]of this.pendingApprovals)clearTimeout(r.timeoutId),r.reject(new Error("Permission checker destroyed")),this.pendingApprovals.delete(e)}};function Zj(t){return t==="classifier"||t==="rule-engine"||t==="safety"||t==="static-deny"}function e$(t){return`${t}-deny`}function nu(t){switch(t?.type){case"sandbox":return"sandbox-deny";case"rule":return"rule-engine-deny";case"mode":return`mode-${t.mode}`;case"tool_check":return`tool-${t.reason}`;case"classifier":return"classifier-deny";case"eligibility":return"eligibility-deny";case"hook":return"hook-deny";case"other":return"policy-deny";default:return"rule-engine-deny"}}function t$(t){return t.behavior==="ask"&&t.decisionReason?.type==="rule"&&t.decisionReason.rule.source==="community-sandbox"}D();import*as Rn from"node:fs";import*as vw from"node:path";function kw(t,e=de()){if(t.scope==="session")return;let r=r$(e),n=n$(r),s=[{pattern:t.pattern,behavior:t.behavior,reason:t.description,source:"user"},...n.rules.filter(i=>!c$(i.pattern,t.pattern))];r.permissions={...ou(r.permissions),mode:n.mode,defaultBehavior:n.defaultBehavior,rules:s},Rn.mkdirSync(vw.dirname(e),{recursive:!0}),Rn.writeFileSync(e,`${JSON.stringify(r,null,2)}
|
|
1058
|
-
`,"utf-8")}function r$(t){try{return JSON.parse(Rn.readFileSync(t,"utf-8"))}catch{return{}}}function n$(t){let e=ou(t.permissions);return{mode:i$(e.mode??t.permissionMode),defaultBehavior:a$(e.defaultBehavior??e.default??t.defaultBehavior),rules:o$(t,e)}}function o$(t,e){return s$(e)?bw(e,"rules"):Array.isArray(t.permissionRules)?Rw(t.permissionRules):bw(t,"rules")}function bw(t,e){let r=[];for(let n of["allow","deny","ask"]){let o=t[n];if(Array.isArray(o))for(let s of o)typeof s=="string"&&s.trim()&&r.push({pattern:s,behavior:n,source:"config"})}return r.push(...Rw(t[e])),r}function Rw(t){if(!Array.isArray(t))return[];let e=[];for(let r of t){let n=ou(r);if(!n)continue;let o=n.pattern,s=Sw(n.behavior??n.action);if(typeof o!="string"||!o.trim()||!s)continue;let i={pattern:o,behavior:s};typeof n.reason=="string"&&(i.reason=n.reason),typeof n.source=="string"&&(i.source=n.source),e.push(i)}return e}function s$(t){return Array.isArray(t.rules)||Array.isArray(t.allow)||Array.isArray(t.ask)||Array.isArray(t.deny)}function i$(t){return t==="default"||t==="bypassPermissions"||t==="acceptEdits"||t==="dontAsk"||t==="plan"||t==="auto"?t:"default"}function a$(t){return Sw(t)??"allow"}function Sw(t){return t==="allow"||t==="ask"||t==="deny"?t:void 0}function c$(t,e){return t.toLocaleLowerCase()===e.toLocaleLowerCase()}function ou(t){return t&&typeof t=="object"?t:{}}function ww(){return oe()?.type==="group"}function Tw(t){let e=jr(t.config.permissions),r=new hn(e);if(e.mode,ww()){let o=fk();for(let s of o)r.addRule(s);Ed(!0),t.log.info(`[permissions] group security mode active: ${o.length} rules injected`)}else Ed(!1);t.currentUnregister?.();let n=new Fi({ruleEngine:r,hookRegistry:t.hooks,auditLogger:new $i(t.getActiveProjectRoot()),sessionId:t.sessionId,getTurnId:t.getTurnId,communityTelemetryRecorder:Rs()??void 0,onRequestApproval:o=>l$(o,t),onPermissionUpdate:o=>{try{kw(o)}catch(s){t.log.warn(`[permissions] failed to persist rule "${o.pattern}": ${s instanceof Error?s.message:String(s)}`)}t.log.info(`[permissions] rule saved: ${o.pattern} -> ${o.behavior}`),t.sendNotification("permission.rule_updated",{pattern:o.pattern,behavior:o.behavior,scope:o.scope??"persistent"})},onDenied:(o,s)=>{t.log.warn(`[permissions] blocked "${o}": ${s}`)}});return n.setToolMeta(Ie()),{permissionChecker:n,permissionUnregister:n.register(),ruleEngine:r}}async function l$(t,e){let r=e.getAcpPermissionSession();if(r)try{let n=await r.requestPermission({sessionId:r.sessionId,permissionId:t.approvalId,toolCall:{callId:t.callId,toolName:t.toolName,arguments:t.arguments?JSON.stringify(t.arguments):""},message:t.message,options:[{id:"allow",label:"Allow"},{id:"deny",label:"Deny"},{id:"allowAlways",label:"Always allow",persistent:!0}]});return d$(t,n.optionId)}catch{return{approvalId:t.approvalId,decision:"denied"}}if(e.sendNotification("tool.approval.request",{approvalId:t.approvalId,callId:t.callId,toolName:t.toolName,arguments:t.arguments?JSON.stringify(t.arguments):"",message:t.message,suggestions:t.suggestions?.map(n=>`${n.pattern}:${n.behavior}`)}),e.isPetActive()){let n=t.toolName.match(/delete|rm|drop|reset|force/i)?"high":t.toolName.match(/write|exec|bash|shell|move/i)?"medium":"low";e.sendNotification("pet.confirm",{confirmId:t.approvalId,toolName:t.toolName,description:t.message??`Allow ${t.toolName}`,risk:n,timeoutMs:3e4})}return new Promise(()=>{})}function d$(t,e){if(e!=="allow"&&e!=="allowAlways")return{approvalId:t.approvalId,decision:"denied"};let r={approvalId:t.approvalId,decision:"approved"};return e==="allowAlways"&&(r.permissionUpdate={pattern:t.toolName,behavior:"allow",scope:"persistent",description:`Always allow ${t.toolName}`}),r}function Aw(t){let e=new Map;return{register(r){let n=e.get(r.point)??[],o={handler:r.handler,priority:r.priority??100,label:r.label};return n.push(o),n.sort((s,i)=>s.priority-i.priority),e.set(r.point,n),()=>{let s=n.indexOf(o);s>=0&&n.splice(s,1)}},async invoke(r,n){let o=e.get(r);if(!o||o.length===0)return{action:"continue",context:n};let s=n;for(let i of o)try{let a=await i.handler(r,s);if(!a||a.action==="continue"){a?.context&&(s=a.context);continue}if(a.action==="abort"||a.action==="skip")return t.info({hook:r,label:i.label,action:a.action,reason:a.reason},"hook intercepted"),a}catch(a){t.warn({hook:r,label:i.label,err:a.message},"hook handler failed (non-blocking)")}return{action:"continue",context:s}}}}function xw(t){let e=Aw(t.log);t.taskStore.setHooks(e,t.sessionId),Sk({onTaskCreated:n=>{e.invoke("task.created",{sessionId:t.sessionId,taskId:String(n.id),taskType:"planning",label:n.title}).catch(()=>{})},onTaskCompleted:n=>{e.invoke("task.completed",{sessionId:t.sessionId,taskId:String(n.id),taskType:"planning",label:n.title}).catch(()=>{})}});let r=nS({hooks:e,projectRoot:t.projectRoot,currentUserId:t.currentUserId,log:t.log,prefetchState:t.prefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient});return Cg(e,{currentCwd:t.projectRoot,log:{debug:n=>t.log.debug(n),warn:n=>t.log.warn(n)}}),jm(e,t.log,{transport:t.compressionClient.transport,apiKey:t.compressionClient.apiKey}),oS({memdir:t.memdir,memoryProvider:r.toolProvider,memoryUserId:r.userId}),Bu(e,{getMemorySource:()=>t.memdir,log:{debug:n=>t.log.debug(n),warn:n=>t.log.warn(n)}},t.prefetchState),{hooks:e,memoryHandlerProvider:r.handlerProvider,memoryDreamProvider:r.dreamProvider,memoryLearningSink:r.learningSink,memoryUserId:r.userId}}D();import{watch as u$}from"node:fs";import{stat as p$}from"node:fs/promises";import{join as Pw,relative as m$,resolve as g$}from"node:path";var f$=[`${je}/settings.json`,"INSTRUCTIONS.md",`${je}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${je}/rules`],h$=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${je}/rules`],su=class{watchers=new Map;deps;debounceTimers=new Map;_cwd;constructor(e){this.deps=e,this._cwd=e.projectRoot}get cwd(){return this._cwd}async start(){for(let e of f$){let r=Pw(this.deps.projectRoot,e);this.watchPath(r,e)}this.deps.log?.(`file-watcher: watching ${this.watchers.size} paths`)}watchPath(e,r){if(!this.watchers.has(e))try{let n=u$(e,{persistent:!1,recursive:r.includes("/")?!1:void 0},(o,s)=>{let i=s?Pw(e,s):e;this.handleChange(i,o==="rename"?"created":"modified")});n.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,n)}catch{}}handleChange(e,r){let n=this.debounceTimers.get(e);n&&clearTimeout(n),this.debounceTimers.set(e,setTimeout(async()=>{this.debounceTimers.delete(e);let o=r;try{await p$(e)}catch{o="deleted"}let s=m$(this.deps.projectRoot,e);this.deps.log?.(`file-watcher: ${o} ${s}`),this.deps.hooks.invoke("file.changed",{sessionId:this.deps.sessionId,filePath:e,changeType:o}).catch(()=>{}),h$.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let r=g$(e);if(r===this._cwd)return;let n=this._cwd;this._cwd=r,this.deps.hooks.invoke("cwd.changed",{sessionId:this.deps.sessionId,oldCwd:n,newCwd:r}).catch(()=>{}),this.deps.onInstructionCacheReset?.()}stop(){for(let[,e]of this.watchers)e.close();this.watchers.clear();for(let[,e]of this.debounceTimers)clearTimeout(e);this.debounceTimers.clear()}};async function Cw(t){let e=new su(t);return await e.start(),e}import{readFile as y$}from"node:fs/promises";import{watch as b$}from"node:fs";import{join as v$}from"node:path";D();var k$=je,R$="settings.json";function S$(t){return v$(t,k$,R$)}async function w$(t){try{let e=await y$(t,"utf-8");return JSON.parse(e)}catch{return null}}function T$(t,e,r,n){let o=!1,s=A$(t);s&&(t.permissionMode=s.mode,t.permissionRules=[...s.rules],t.defaultBehavior=s.defaultBehavior,s.mode!==e.getMode()&&(e.setMode(s.mode),n?.(`settings: permission mode \u2192 ${t.permissionMode}`),o=!0),x$(s.rules,e.getRules())||(e.replaceRules(s.rules),n?.(`settings: ${s.rules.length} permission rules loaded`),o=!0),s.defaultBehavior!==e.getDefaultBehavior()&&(e.setDefaultBehavior(s.defaultBehavior),n?.(`settings: default behavior \u2192 ${t.defaultBehavior}`),o=!0),o&&r&&r.invoke("config.changed",{sessionId:"",key:"permissions",oldValue:void 0,newValue:t}).catch(()=>{}))}function Iw(t){let e=S$(t.projectRoot),r=null,n=null,o=async()=>{let s=await w$(e);s&&T$(s,t.ruleEngine,t.hooks,t.log)};o().catch(()=>{});try{r=b$(e,{persistent:!1},s=>{n&&clearTimeout(n),n=setTimeout(()=>{o().catch(()=>{})},200)}),r.on("error",()=>{})}catch{}return()=>{n&&clearTimeout(n),r?.close(),r=null}}function A$(t){return t.permissions&&typeof t.permissions=="object"?jr(t.permissions):t.permissionMode===void 0&&t.permissionRules===void 0&&t.defaultBehavior===void 0?null:jr({mode:t.permissionMode,rules:t.permissionRules,defaultBehavior:t.defaultBehavior})}function x$(t,e){return t.length!==e.length?!1:t.every((r,n)=>{let o=e[n];return!!o&&r.pattern===o.pattern&&r.behavior===o.behavior&&r.reason===o.reason&&r.source===o.source})}function Ew(t){let e=typeof t.config.workdir=="string"?t.config.workdir:process.cwd(),r=Iw({projectRoot:e,ruleEngine:t.ruleEngine,hooks:t.hooks,log:n=>t.log.info(`[settings] ${n}`)});zt(async()=>{r()}),t.currentFileWatcher?.stop(),t.setFileWatcher(null),Cw({projectRoot:e,sessionId:t.sessionId,hooks:t.hooks,log:n=>t.log.debug(n),onInstructionCacheReset:Jk}).then(n=>{t.setFileWatcher(n),zt(async()=>{n.stop()})}).catch(n=>{t.log.warn(`[file-watcher] init error: ${n instanceof Error?n.message:n}`)})}import{randomUUID as L$}from"node:crypto";import*as pe from"node:fs";import*as Ae from"node:path";D();var P$="skill",C$={type:"object",properties:{action:{type:"string",enum:["invoke","list","view","create","edit","patch","delete","promote"],description:["The operation to perform:","\u2022 'invoke' \u2014 Run a skill by name (provide 'name', optional 'args')","\u2022 'list' \u2014 List all available skills (optional 'category' filter)","\u2022 'view' \u2014 View full skill content (provide 'name', optional 'filePath')","\u2022 'create' \u2014 Create a new skill (provide 'name', 'content')","\u2022 'edit' \u2014 Overwrite skill content (provide 'name', 'content')","\u2022 'patch' \u2014 Find/replace in skill (provide 'name', 'oldString', 'newString')","\u2022 'delete' \u2014 Remove a skill (provide 'name')","\u2022 'promote' \u2014 Promote a project-level skill to global/user-level (provide 'name')"].join(`
|
|
1059
|
-
`)},name:{type:"string",description:"Skill name (required for invoke/view/create/edit/patch/delete/promote)."},args:{type:"string",description:"Arguments or context to pass when invoking a skill."},category:{type:"string",description:"Filter skills by category (for 'list' action)."},content:{type:"string",description:"Full SKILL.md content for create/edit actions."},filePath:{type:"string",description:"View a specific file within the skill (for 'view' action)."},fileContent:{type:"string",description:"Content for writing supporting files."},oldString:{type:"string",description:"Text to find for patch action."},newString:{type:"string",description:"Replacement text for patch action."}},required:["action"]};function _w(t){return{name:
|
|
1056
|
+
The fast classifier flagged this action. Review carefullyis it actually dangerous, or is it safe development work? Consider the project context. Use <thinking> tags to reason, then respond with <block>yes</block> or <block>no</block> and <reason>explanation</reason>.`,p=await n({system:dw,messages:[{role:"user",content:u}],maxTokens:4096,temperature:0,cacheSystemPrompt:!0}),m=mw(p.text),g=uw(m),f=pw(m)??pw(l)??"classifier decision";return{shouldBlock:g!==!1,reason:f,stage:"thinking",durationMs:Date.now()-o}}catch{return{shouldBlock:!0,reason:"classifier unavailable",stage:"fast",durationMs:Date.now()-o}}}function Xj(t){return t.slice(-20).map(r=>{let n=r.role==="user"?"User":r.role==="assistant"?"Assistant":"System",o=typeof r.content=="string"?r.content.slice(0,500):JSON.stringify(r.content).slice(0,500);return`${n}: ${o}`}).join(`
|
|
1057
|
+
`)}function Yj(t,e){let r=JSON.stringify(e,null,0),n=r.length>2e3?r.slice(0,2e3)+"...":r;return`Tool: ${t}
|
|
1058
|
+
Arguments: ${n}`}function uw(t){let e=t.match(/<block>(yes|no)<\/block>/i);return e?e[1].toLowerCase()==="yes":null}function pw(t){let e=t.match(/<reason>([\s\S]*?)(?:<\/reason>|$)/i);return e?e[1].trim():null}function mw(t){return t.replace(/<thinking>[\s\S]*?<\/thinking>/gi,"").trim()}var gw={maxConsecutive:3,maxTotal:20};function fw(){return{consecutiveDenials:0,totalDenials:0}}function tu(t){return{consecutiveDenials:t.consecutiveDenials+1,totalDenials:t.totalDenials+1}}function ru(t){return t.consecutiveDenials===0?t:{...t,consecutiveDenials:0}}function hw(t){return t.consecutiveDenials>=gw.maxConsecutive||t.totalDenials>=gw.maxTotal}var Jj=[{pattern:"exec",behavior:"deny",reason:"Community L1 sandbox denied shell execution",source:"community-sandbox",ruleId:"community-l1-shell"},{pattern:"Bash",behavior:"deny",reason:"Community L1 sandbox denied shell execution",source:"community-sandbox",ruleId:"community-l1-shell"},{pattern:"execute_command",behavior:"deny",reason:"Community L1 sandbox denied shell execution",source:"community-sandbox",ruleId:"community-l1-shell"},{pattern:"read",behavior:"deny",reason:"Community L1 sandbox denied file reads",source:"community-sandbox",ruleId:"community-l1-file-read"},{pattern:"write",behavior:"deny",reason:"Community L1 sandbox denied file writes",source:"community-sandbox",ruleId:"community-l1-file-write"},{pattern:"edit",behavior:"deny",reason:"Community L1 sandbox denied file edits",source:"community-sandbox",ruleId:"community-l1-file-write"},{pattern:"apply_patch",behavior:"deny",reason:"Community L1 sandbox denied file patching",source:"community-sandbox",ruleId:"community-l1-file-write"},{pattern:"web_fetch",behavior:"deny",reason:"Community L1 sandbox denied network egress",source:"community-sandbox",ruleId:"community-l1-network"},{pattern:"web_search",behavior:"deny",reason:"Community L1 sandbox denied network egress",source:"community-sandbox",ruleId:"community-l1-network"},{pattern:"mcp",behavior:"deny",reason:"Community L1 sandbox denied MCP access",source:"community-sandbox",ruleId:"community-l1-mcp"},{pattern:"mcp__*",behavior:"deny",reason:"Community L1 sandbox denied MCP access",source:"community-sandbox",ruleId:"community-l1-mcp"},{pattern:"computer",behavior:"deny",reason:"Community L1 sandbox denied host control",source:"community-sandbox",ruleId:"community-l1-host-control"},{pattern:"notify",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"send_message",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"agent",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"team",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"cron",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"monitor",behavior:"deny",reason:"Community L2 sandbox denied host side effects",source:"community-sandbox",ruleId:"community-l2-host-side-effect"},{pattern:"file_upload",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for local file data egress",source:"community-sandbox",ruleId:"community-l2-data-egress"},{pattern:"image_generate",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider prompt egress",source:"community-sandbox",ruleId:"community-l2-provider-prompt-egress"},{pattern:"video_generate",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider prompt egress",source:"community-sandbox",ruleId:"community-l2-provider-prompt-egress"},{pattern:"music_generate",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider prompt egress",source:"community-sandbox",ruleId:"community-l2-provider-prompt-egress"},{pattern:"tts",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider prompt egress",source:"community-sandbox",ruleId:"community-l2-provider-prompt-egress"},{pattern:"three_d_generate",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider prompt egress",source:"community-sandbox",ruleId:"community-l2-provider-prompt-egress"},{pattern:"video_edit",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider media egress",source:"community-sandbox",ruleId:"community-l2-provider-media-egress"},{pattern:"video_merge",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider media egress",source:"community-sandbox",ruleId:"community-l2-provider-media-egress"},{pattern:"video_upscale",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider media egress",source:"community-sandbox",ruleId:"community-l2-provider-media-egress"},{pattern:"voice_clone",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider media egress",source:"community-sandbox",ruleId:"community-l2-provider-media-egress"},{pattern:"stt",behavior:"ask",reason:"Community L2 sandbox requires explicit approval for provider media egress",source:"community-sandbox",ruleId:"community-l2-provider-media-egress"}];function yw(){return Jj.map(({ruleId:t,...e})=>({...e}))}var Zj=12e4,Fi=class{ruleEngine;hookRegistry;onRequestApproval;onPermissionUpdate;onDenied;classifierLLMCall;getRecentMessages;permissionRole;pendingApprovals=new Map;auditLogger;sessionId;getTurnId;communityTelemetryRecorder;communitySandboxTurnIds=new Set;communitySandboxRuleEngine=new hn({mode:"default",defaultBehavior:"allow",rules:yw()});unregisterHook=null;toolMetaCache=new Map;classifierCache=new Ui;denialTracking=fw();constructor(e){this.ruleEngine=e.ruleEngine,this.hookRegistry=e.hookRegistry,this.onRequestApproval=e.onRequestApproval,this.onPermissionUpdate=e.onPermissionUpdate,this.onDenied=e.onDenied,this.classifierLLMCall=e.classifierLLMCall,this.getRecentMessages=e.getRecentMessages,this.permissionRole=e.permissionRole??"interactive",this.auditLogger=e.auditLogger,this.sessionId=e.sessionId??"",this.getTurnId=e.getTurnId??(()=>""),this.communityTelemetryRecorder=e.communityTelemetryRecorder}register(){this.unregisterHook&&this.unregisterHook(),this.classifierCache.clear();let e=this.hookRegistry.register({point:"tool.before_invoke",priority:100,label:"permission-checker",handler:async(o,s)=>{let i=this.toolMetaCache.get(s.toolName),a={toolName:s.toolName,arguments:s.arguments,meta:i?{isReadOnly:i.isReadOnly,isDangerous:i.isDangerous,requiresApproval:i.requiresApproval,parallelSafe:i.parallelSafe}:void 0},c=this.communitySandboxTurnIds.has(s.turnId)?this.checkCommunitySandboxThenBase(a):this.ruleEngine.check(a);return this.handleResult(c,s.callId,s.toolName,s.arguments)}}),r=this.hookRegistry.register({point:"subagent.started",priority:20,label:"community-sandbox-scope-start",handler:(o,s)=>(s.agentType?.startsWith("community-skill:")&&this.communitySandboxTurnIds.add(s.turnId),{action:"continue"})}),n=this.hookRegistry.register({point:"subagent.stopped",priority:20,label:"community-sandbox-scope-stop",handler:(o,s)=>(s.agentType?.startsWith("community-skill:")&&this.communitySandboxTurnIds.delete(s.turnId),{action:"continue"})});return this.unregisterHook=()=>{e(),r(),n(),this.communitySandboxTurnIds.clear()},()=>{this.unregisterHook?.(),this.unregisterHook=null,this.cancelAllPending()}}resolveApproval(e){let r=this.pendingApprovals.get(e.approvalId);r&&(clearTimeout(r.timeoutId),this.pendingApprovals.delete(e.approvalId),r.resolve(e))}setToolMeta(e){this.toolMetaCache.clear();for(let r of e)r.meta&&this.toolMetaCache.set(r.function.name,r.meta)}get ruleEngineRef(){return this.ruleEngine}checkCommunitySandboxThenBase(e){let r=this.communitySandboxRuleEngine.check(e);return r.behavior!=="allow"?r:this.ruleEngine.check(e)}fireDenied(e,r,n,o="classifier",s,i=t$(o)){this.onDenied?.(r,n),this.hookRegistry.invoke("permission.denied",{sessionId:this.sessionId,turnId:this.getTurnId(),approvalId:e,callId:e,toolName:r,decision:"denied",reason:n}).catch(()=>{}),this.auditLogger&&this.auditLogger.record({timestamp:new Date().toISOString(),sessionId:this.sessionId,turnId:this.getTurnId(),toolName:r,reason:n,source:o,permissionRole:this.permissionRole,callId:e,toolArgs:iw(s),cumulativeDenials:this.denialTracking.totalDenials,consecutiveDenials:this.denialTracking.consecutiveDenials}),e$(o)&&this.communityTelemetryRecorder?.recordTelemetry({event:"community.sandbox.violation",metadata:{surface:"permission-checker",action:"blocked",source:o,ruleId:i,platform:process.platform}}).catch(()=>{})}async handleResult(e,r,n,o){if(e.behavior==="allow")return{action:"continue",context:e.updatedInput?{arguments:e.updatedInput}:void 0};if(e.behavior==="deny")return this.fireDenied(r,n,e.message,"rule-engine",o,nu(e.decisionReason)),{action:"abort",reason:e.message};let s=r$(e),i=e.decisionReason?.type==="tool_check"&&(e.decisionReason.reason==="isDangerous"||e.decisionReason.reason==="requiresApproval");if(s&&this.permissionRole!=="interactive")return this.fireDenied(r,n,`community sandbox requires interactive approval: ${e.message}`,"safety",o,nu(e.decisionReason)),{action:"abort",reason:`Tool "${n}" blocked by community sandbox (${this.permissionRole} agents cannot approve tainted egress)`};if(s)return this.handleInteractiveApproval(e,r,n,o);if(i&&this.permissionRole!=="interactive")return this.fireDenied(r,n,`safety check: ${e.message} (${this.permissionRole} cannot override)`,"safety",o,nu(e.decisionReason)),{action:"abort",reason:`Tool "${n}" blocked by safety check (${this.permissionRole} agents cannot override dangerous tool restrictions)`};if((n==="bash"||n==="execute_command"||n==="Bash"||n==="shell")&&o){let c=o.command??o.cmd??"";if(c){let l=lw(c);if(l.decision==="allow")return{action:"continue"};if(l.decision==="deny")return this.fireDenied(r,n,l.reason,"classifier",o,"bash-classifier-deny"),{action:"abort",reason:l.reason}}}if(o){let c=this.classifierCache.get(n,o);if(c)return c.shouldBlock?(this.fireDenied(r,n,`cached: ${c.reason}`,"classifier",o,"classifier-cached-deny"),{action:"abort",reason:c.reason}):{action:"continue"}}if(this.permissionRole==="worker")return this.handleWorkerAsk(r,n,o);if(this.permissionRole==="coordinator")return this.toolMetaCache.get(n)?.isReadOnly||To(n)?{action:"continue"}:this.handleWorkerAsk(r,n,o);if(this.ruleEngine.getMode()==="auto"){if(To(n))return{action:"continue"};let c=hw(this.denialTracking);if(this.classifierLLMCall&&!c)try{let l=this.getRecentMessages?.()??[],d=await eu(n,o??{},l,this.classifierLLMCall);if(o&&this.classifierCache.set(n,o,{shouldBlock:d.shouldBlock,reason:d.reason}),!d.shouldBlock)return this.denialTracking=ru(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:"auto",reason:d.reason}}};this.denialTracking=tu(this.denialTracking)}catch{}}return this.handleInteractiveApproval(e,r,n,o)}async handleInteractiveApproval(e,r,n,o){let s=Qj(),i={approvalId:s,callId:r,toolName:n,arguments:o,message:e.message,suggestions:e.suggestions};this.hookRegistry.invoke("approval.requested",{sessionId:"",turnId:"",approvalId:s,callId:r,toolName:n}).catch(()=>{});try{let a=await this.requestApproval(i);return this.hookRegistry.invoke("approval.responded",{sessionId:"",turnId:"",approvalId:s,callId:r,toolName:n,decision:a.decision==="approved"?"approved":"denied"}).catch(()=>{}),a.permissionUpdate&&(this.ruleEngine.applyUpdate(a.permissionUpdate),this.onPermissionUpdate?.(a.permissionUpdate)),a.decision==="approved"?{action:"continue",context:a.updatedInput?{arguments:a.updatedInput}:void 0}:(this.fireDenied(r,n,`denied by user (approval ${s})`,"user",o),{action:"abort",reason:`Tool "${n}" denied by user`})}catch{return this.fireDenied(r,n,`approval timeout or error (approval ${s})`,"timeout",o),{action:"abort",reason:`Tool "${n}"approval timed out`}}}async handleWorkerAsk(e,r,n){if(To(r))return{action:"continue"};if(this.classifierLLMCall)try{let o=this.getRecentMessages?.()??[],s=await eu(r,n??{},o,this.classifierLLMCall);return n&&this.classifierCache.set(r,n,{shouldBlock:s.shouldBlock,reason:s.reason}),s.shouldBlock?(this.denialTracking=tu(this.denialTracking),this.fireDenied(e,r,`blocked by classifier in ${this.permissionRole} mode: ${s.reason}`,"classifier",n,"classifier-deny"),{action:"abort",reason:`Tool "${r}" blocked by classifier (${this.permissionRole})`}):(this.denialTracking=ru(this.denialTracking),{action:"continue",context:{decisionReason:{type:"classifier",classifier:this.permissionRole,reason:s.reason}}})}catch{}return this.fireDenied(e,r,`no classifier available in ${this.permissionRole} mode`,"static-deny",void 0,"static-deny"),{action:"abort",reason:`Tool "${r}" deniedno classifier for ${this.permissionRole} mode`}}requestApproval(e){return new Promise((r,n)=>{let o=setTimeout(()=>{this.pendingApprovals.delete(e.approvalId),n(new Error("Approval timed out"))},Zj);this.pendingApprovals.set(e.approvalId,{resolve:r,reject:n,timeoutId:o}),this.onRequestApproval(e).then(s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),r(s))},s=>{let i=this.pendingApprovals.get(e.approvalId);i&&(clearTimeout(i.timeoutId),this.pendingApprovals.delete(e.approvalId),n(s))})})}clearClassifierCache(){this.classifierCache.clear(),this.denialTracking={consecutiveDenials:0,totalDenials:0}}cancelAllPending(){this.classifierCache.clear();for(let[e,r]of this.pendingApprovals)clearTimeout(r.timeoutId),r.reject(new Error("Permission checker destroyed")),this.pendingApprovals.delete(e)}};function e$(t){return t==="classifier"||t==="rule-engine"||t==="safety"||t==="static-deny"}function t$(t){return`${t}-deny`}function nu(t){switch(t?.type){case"sandbox":return"sandbox-deny";case"rule":return"rule-engine-deny";case"mode":return`mode-${t.mode}`;case"tool_check":return`tool-${t.reason}`;case"classifier":return"classifier-deny";case"eligibility":return"eligibility-deny";case"hook":return"hook-deny";case"other":return"policy-deny";default:return"rule-engine-deny"}}function r$(t){return t.behavior==="ask"&&t.decisionReason?.type==="rule"&&t.decisionReason.rule.source==="community-sandbox"}D();import*as Rn from"node:fs";import*as vw from"node:path";function kw(t,e=de()){if(t.scope==="session")return;let r=n$(e),n=o$(r),s=[{pattern:t.pattern,behavior:t.behavior,reason:t.description,source:"user"},...n.rules.filter(i=>!l$(i.pattern,t.pattern))];r.permissions={...ou(r.permissions),mode:n.mode,defaultBehavior:n.defaultBehavior,rules:s},Rn.mkdirSync(vw.dirname(e),{recursive:!0}),Rn.writeFileSync(e,`${JSON.stringify(r,null,2)}
|
|
1059
|
+
`,"utf-8")}function n$(t){try{return JSON.parse(Rn.readFileSync(t,"utf-8"))}catch{return{}}}function o$(t){let e=ou(t.permissions);return{mode:a$(e.mode??t.permissionMode),defaultBehavior:c$(e.defaultBehavior??e.default??t.defaultBehavior),rules:s$(t,e)}}function s$(t,e){return i$(e)?bw(e,"rules"):Array.isArray(t.permissionRules)?Rw(t.permissionRules):bw(t,"rules")}function bw(t,e){let r=[];for(let n of["allow","deny","ask"]){let o=t[n];if(Array.isArray(o))for(let s of o)typeof s=="string"&&s.trim()&&r.push({pattern:s,behavior:n,source:"config"})}return r.push(...Rw(t[e])),r}function Rw(t){if(!Array.isArray(t))return[];let e=[];for(let r of t){let n=ou(r);if(!n)continue;let o=n.pattern,s=Sw(n.behavior??n.action);if(typeof o!="string"||!o.trim()||!s)continue;let i={pattern:o,behavior:s};typeof n.reason=="string"&&(i.reason=n.reason),typeof n.source=="string"&&(i.source=n.source),e.push(i)}return e}function i$(t){return Array.isArray(t.rules)||Array.isArray(t.allow)||Array.isArray(t.ask)||Array.isArray(t.deny)}function a$(t){return t==="default"||t==="bypassPermissions"||t==="acceptEdits"||t==="dontAsk"||t==="plan"||t==="auto"?t:"default"}function c$(t){return Sw(t)??"allow"}function Sw(t){return t==="allow"||t==="ask"||t==="deny"?t:void 0}function l$(t,e){return t.toLocaleLowerCase()===e.toLocaleLowerCase()}function ou(t){return t&&typeof t=="object"?t:{}}function ww(){return oe()?.type==="group"}function Tw(t){let e=jr(t.config.permissions),r=new hn(e);if(e.mode,ww()){let o=fk();for(let s of o)r.addRule(s);Ed(!0),t.log.info(`[permissions] group security mode active: ${o.length} rules injected`)}else Ed(!1);t.currentUnregister?.();let n=new Fi({ruleEngine:r,hookRegistry:t.hooks,auditLogger:new $i(t.getActiveProjectRoot()),sessionId:t.sessionId,getTurnId:t.getTurnId,communityTelemetryRecorder:Rs()??void 0,onRequestApproval:o=>d$(o,t),onPermissionUpdate:o=>{try{kw(o)}catch(s){t.log.warn(`[permissions] failed to persist rule "${o.pattern}": ${s instanceof Error?s.message:String(s)}`)}t.log.info(`[permissions] rule saved: ${o.pattern} -> ${o.behavior}`),t.sendNotification("permission.rule_updated",{pattern:o.pattern,behavior:o.behavior,scope:o.scope??"persistent"})},onDenied:(o,s)=>{t.log.warn(`[permissions] blocked "${o}": ${s}`)}});return n.setToolMeta(Ie()),{permissionChecker:n,permissionUnregister:n.register(),ruleEngine:r}}async function d$(t,e){let r=e.getAcpPermissionSession();if(r)try{let n=await r.requestPermission({sessionId:r.sessionId,permissionId:t.approvalId,toolCall:{callId:t.callId,toolName:t.toolName,arguments:t.arguments?JSON.stringify(t.arguments):""},message:t.message,options:[{id:"allow",label:"Allow"},{id:"deny",label:"Deny"},{id:"allowAlways",label:"Always allow",persistent:!0}]});return u$(t,n.optionId)}catch{return{approvalId:t.approvalId,decision:"denied"}}if(e.sendNotification("tool.approval.request",{approvalId:t.approvalId,callId:t.callId,toolName:t.toolName,arguments:t.arguments?JSON.stringify(t.arguments):"",message:t.message,suggestions:t.suggestions?.map(n=>`${n.pattern}:${n.behavior}`)}),e.isPetActive()){let n=t.toolName.match(/delete|rm|drop|reset|force/i)?"high":t.toolName.match(/write|exec|bash|shell|move/i)?"medium":"low";e.sendNotification("pet.confirm",{confirmId:t.approvalId,toolName:t.toolName,description:t.message??`Allow ${t.toolName}`,risk:n,timeoutMs:3e4})}return new Promise(()=>{})}function u$(t,e){if(e!=="allow"&&e!=="allowAlways")return{approvalId:t.approvalId,decision:"denied"};let r={approvalId:t.approvalId,decision:"approved"};return e==="allowAlways"&&(r.permissionUpdate={pattern:t.toolName,behavior:"allow",scope:"persistent",description:`Always allow ${t.toolName}`}),r}function Aw(t){let e=new Map;return{register(r){let n=e.get(r.point)??[],o={handler:r.handler,priority:r.priority??100,label:r.label};return n.push(o),n.sort((s,i)=>s.priority-i.priority),e.set(r.point,n),()=>{let s=n.indexOf(o);s>=0&&n.splice(s,1)}},async invoke(r,n){let o=e.get(r);if(!o||o.length===0)return{action:"continue",context:n};let s=n;for(let i of o)try{let a=await i.handler(r,s);if(!a||a.action==="continue"){a?.context&&(s=a.context);continue}if(a.action==="abort"||a.action==="skip")return t.info({hook:r,label:i.label,action:a.action,reason:a.reason},"hook intercepted"),a}catch(a){t.warn({hook:r,label:i.label,err:a.message},"hook handler failed (non-blocking)")}return{action:"continue",context:s}}}}function xw(t){let e=Aw(t.log);t.taskStore.setHooks(e,t.sessionId),Sk({onTaskCreated:n=>{e.invoke("task.created",{sessionId:t.sessionId,taskId:String(n.id),taskType:"planning",label:n.title}).catch(()=>{})},onTaskCompleted:n=>{e.invoke("task.completed",{sessionId:t.sessionId,taskId:String(n.id),taskType:"planning",label:n.title}).catch(()=>{})}});let r=nS({hooks:e,projectRoot:t.projectRoot,currentUserId:t.currentUserId,log:t.log,prefetchState:t.prefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient});return Cg(e,{currentCwd:t.projectRoot,log:{debug:n=>t.log.debug(n),warn:n=>t.log.warn(n)}}),jm(e,t.log,{transport:t.compressionClient.transport,apiKey:t.compressionClient.apiKey}),oS({memdir:t.memdir,memoryProvider:r.toolProvider,memoryUserId:r.userId}),Bu(e,{getMemorySource:()=>t.memdir,log:{debug:n=>t.log.debug(n),warn:n=>t.log.warn(n)}},t.prefetchState),{hooks:e,memoryHandlerProvider:r.handlerProvider,memoryDreamProvider:r.dreamProvider,memoryLearningSink:r.learningSink,memoryUserId:r.userId}}D();import{watch as p$}from"node:fs";import{stat as m$}from"node:fs/promises";import{join as Pw,relative as g$,resolve as f$}from"node:path";var h$=[`${je}/settings.json`,"INSTRUCTIONS.md",`${je}/INSTRUCTIONS.md`,"INSTRUCTIONS.local.md",`${je}/rules`],y$=["INSTRUCTIONS.md","INSTRUCTIONS.local.md",`${je}/rules`],su=class{watchers=new Map;deps;debounceTimers=new Map;_cwd;constructor(e){this.deps=e,this._cwd=e.projectRoot}get cwd(){return this._cwd}async start(){for(let e of h$){let r=Pw(this.deps.projectRoot,e);this.watchPath(r,e)}this.deps.log?.(`file-watcher: watching ${this.watchers.size} paths`)}watchPath(e,r){if(!this.watchers.has(e))try{let n=p$(e,{persistent:!1,recursive:r.includes("/")?!1:void 0},(o,s)=>{let i=s?Pw(e,s):e;this.handleChange(i,o==="rename"?"created":"modified")});n.on("error",()=>{this.watchers.delete(e)}),this.watchers.set(e,n)}catch{}}handleChange(e,r){let n=this.debounceTimers.get(e);n&&clearTimeout(n),this.debounceTimers.set(e,setTimeout(async()=>{this.debounceTimers.delete(e);let o=r;try{await m$(e)}catch{o="deleted"}let s=g$(this.deps.projectRoot,e);this.deps.log?.(`file-watcher: ${o} ${s}`),this.deps.hooks.invoke("file.changed",{sessionId:this.deps.sessionId,filePath:e,changeType:o}).catch(()=>{}),y$.some(a=>s.includes(a)||e.includes(a))&&this.deps.onInstructionCacheReset?.()},300))}setCwd(e){let r=f$(e);if(r===this._cwd)return;let n=this._cwd;this._cwd=r,this.deps.hooks.invoke("cwd.changed",{sessionId:this.deps.sessionId,oldCwd:n,newCwd:r}).catch(()=>{}),this.deps.onInstructionCacheReset?.()}stop(){for(let[,e]of this.watchers)e.close();this.watchers.clear();for(let[,e]of this.debounceTimers)clearTimeout(e);this.debounceTimers.clear()}};async function Cw(t){let e=new su(t);return await e.start(),e}import{readFile as b$}from"node:fs/promises";import{watch as v$}from"node:fs";import{join as k$}from"node:path";D();var R$=je,S$="settings.json";function w$(t){return k$(t,R$,S$)}async function T$(t){try{let e=await b$(t,"utf-8");return JSON.parse(e)}catch{return null}}function A$(t,e,r,n){let o=!1,s=x$(t);s&&(t.permissionMode=s.mode,t.permissionRules=[...s.rules],t.defaultBehavior=s.defaultBehavior,s.mode!==e.getMode()&&(e.setMode(s.mode),n?.(`settings: permission mode \u2192 ${t.permissionMode}`),o=!0),P$(s.rules,e.getRules())||(e.replaceRules(s.rules),n?.(`settings: ${s.rules.length} permission rules loaded`),o=!0),s.defaultBehavior!==e.getDefaultBehavior()&&(e.setDefaultBehavior(s.defaultBehavior),n?.(`settings: default behavior \u2192 ${t.defaultBehavior}`),o=!0),o&&r&&r.invoke("config.changed",{sessionId:"",key:"permissions",oldValue:void 0,newValue:t}).catch(()=>{}))}function Iw(t){let e=w$(t.projectRoot),r=null,n=null,o=async()=>{let s=await T$(e);s&&A$(s,t.ruleEngine,t.hooks,t.log)};o().catch(()=>{});try{r=v$(e,{persistent:!1},s=>{n&&clearTimeout(n),n=setTimeout(()=>{o().catch(()=>{})},200)}),r.on("error",()=>{})}catch{}return()=>{n&&clearTimeout(n),r?.close(),r=null}}function x$(t){return t.permissions&&typeof t.permissions=="object"?jr(t.permissions):t.permissionMode===void 0&&t.permissionRules===void 0&&t.defaultBehavior===void 0?null:jr({mode:t.permissionMode,rules:t.permissionRules,defaultBehavior:t.defaultBehavior})}function P$(t,e){return t.length!==e.length?!1:t.every((r,n)=>{let o=e[n];return!!o&&r.pattern===o.pattern&&r.behavior===o.behavior&&r.reason===o.reason&&r.source===o.source})}function Ew(t){let e=typeof t.config.workdir=="string"?t.config.workdir:process.cwd(),r=Iw({projectRoot:e,ruleEngine:t.ruleEngine,hooks:t.hooks,log:n=>t.log.info(`[settings] ${n}`)});Vt(async()=>{r()}),t.currentFileWatcher?.stop(),t.setFileWatcher(null),Cw({projectRoot:e,sessionId:t.sessionId,hooks:t.hooks,log:n=>t.log.debug(n),onInstructionCacheReset:Jk}).then(n=>{t.setFileWatcher(n),Vt(async()=>{n.stop()})}).catch(n=>{t.log.warn(`[file-watcher] init error: ${n instanceof Error?n.message:n}`)})}import{randomUUID as O$}from"node:crypto";import*as pe from"node:fs";import*as Ae from"node:path";D();var C$="skill",I$={type:"object",properties:{action:{type:"string",enum:["invoke","list","view","create","edit","patch","delete","promote"],description:["The operation to perform:","\u2022 'invoke' \u2014 Run a skill by name (provide 'name', optional 'args')","\u2022 'list' \u2014 List all available skills (optional 'category' filter)","\u2022 'view' \u2014 View full skill content (provide 'name', optional 'filePath')","\u2022 'create' \u2014 Create a new skill (provide 'name', 'content')","\u2022 'edit' \u2014 Overwrite skill content (provide 'name', 'content')","\u2022 'patch' \u2014 Find/replace in skill (provide 'name', 'oldString', 'newString')","\u2022 'delete' \u2014 Remove a skill (provide 'name')","\u2022 'promote' \u2014 Promote a project-level skill to global/user-level (provide 'name')"].join(`
|
|
1060
|
+
`)},name:{type:"string",description:"Skill name (required for invoke/view/create/edit/patch/delete/promote)."},args:{type:"string",description:"Arguments or context to pass when invoking a skill."},category:{type:"string",description:"Filter skills by category (for 'list' action)."},content:{type:"string",description:"Full SKILL.md content for create/edit actions."},filePath:{type:"string",description:"View a specific file within the skill (for 'view' action)."},fileContent:{type:"string",description:"Content for writing supporting files."},oldString:{type:"string",description:"Text to find for patch action."},newString:{type:"string",description:"Replacement text for patch action."}},required:["action"]};function _w(t){return{name:C$,label:"Skill",description:L$(t),parameters:I$,isConcurrencySafe:!1,isReadOnly:!1,searchHint:"skill invoke list view create edit delete command workflow",execute:async(e,r,n)=>{let{action:o}=r;switch(o){case"invoke":return E$(t,r,n);case"list":return _$(t,r);case"view":return M$(t,r);case"create":case"edit":case"patch":case"delete":return D$(t,r);case"promote":return N$(t,r);default:return{content:[{type:"text",text:`Unknown action: ${o}. Use invoke, list, view, create, edit, patch, delete, or promote.`}]}}}}}async function E$(t,e,r){let{name:n,args:o}=e;if(!n)return{content:[{type:"text",text:`Error: 'name' is required for invoke. Available skills: ${t.listSkills().map(l=>l.name).join(", ")||"(none)"}`}]};let s=await t.readSkillContent(n);if(!s){let c=t.listSkills().map(l=>l.name).join(", ");return{content:[{type:"text",text:`Skill "${n}" not found. Available skills: ${c||"(none)"}`}]}}if(t.executeSkillSubturn)try{return{content:[{type:"text",text:await t.executeSkillSubturn(n,s,o,r)}],details:{skillName:n,action:"invoke",mode:"subturn"}}}catch(c){let l=c instanceof Error?c.message:String(c);return{content:[{type:"text",text:`Skill execution error: ${l}`}],details:{error:l,skillName:n}}}let i=`## Skill: ${n}
|
|
1060
1061
|
|
|
1061
1062
|
`,a=o?`
|
|
1062
1063
|
|
|
1063
1064
|
### User Context
|
|
1064
1065
|
${o}`:"";return{content:[{type:"text",text:`${i}Follow these instructions:
|
|
1065
1066
|
|
|
1066
|
-
${s}${a}`}],details:{skillName:n,action:"invoke",mode:"inline"}}}async function
|
|
1067
|
-
`)}],details:{action:"list",count:r.skills.length}}}async function
|
|
1067
|
+
${s}${a}`}],details:{skillName:n,action:"invoke",mode:"inline"}}}async function _$(t,e){let r=await t.listSkillsFull(e.category);if(r.skills.length===0)return{content:[{type:"text",text:e.category?`No skills found in category "${e.category}".`:"No skills available."}],details:{action:"list",count:0}};let n=[`Available skills (${r.skills.length}):`];r.categories.length>0&&n.push(`Categories: ${r.categories.join(", ")}`),n.push("");for(let o of r.skills){let s=o.category?` [${o.category}]`:"",i=o.version?` (v${o.version})`:"",a=o.scope?` {${o.scope}}`:"";n.push(`- **${o.name}**${i}${s}${a}: ${o.description}`)}return{content:[{type:"text",text:n.join(`
|
|
1068
|
+
`)}],details:{action:"list",count:r.skills.length}}}async function M$(t,e){if(!e.name)return{content:[{type:"text",text:"Error: 'name' is required for view."}]};let r=await t.viewSkill(e.name,e.filePath);if(!r)return{content:[{type:"text",text:`Skill "${e.name}" not found. Use action: "list" to see available skills.`}],details:{action:"view",error:"not_found"}};let n=[`## Skill: ${r.name}
|
|
1068
1069
|
`,r.content];return r.referenceFiles&&r.referenceFiles.length>0&&n.push(`
|
|
1069
1070
|
### Reference Files
|
|
1070
1071
|
${r.referenceFiles.map(o=>`- ${o}`).join(`
|
|
1071
1072
|
`)}`),{content:[{type:"text",text:n.join(`
|
|
1072
|
-
`)}],details:{action:"view",name:r.name}}}async function
|
|
1073
|
+
`)}],details:{action:"view",name:r.name}}}async function D$(t,e){if(!e.name)return{content:[{type:"text",text:`Error: 'name' is required for ${e.action}.`}]};let r=await t.manageSkill({action:e.action,name:e.name,category:e.category,content:e.content,filePath:e.filePath,fileContent:e.fileContent,oldString:e.oldString,newString:e.newString});return{content:[{type:"text",text:r.message}],details:{action:e.action,success:r.success,path:r.path}}}async function N$(t,e){if(!e.name)return{content:[{type:"text",text:"Error: 'name' is required for promote."}]};if(!t.promoteSkill)return{content:[{type:"text",text:"Promote is not available in this configuration. Skills may already be at user-level."}]};let r=await t.promoteSkill(e.name);return{content:[{type:"text",text:r.message}],details:{action:"promote",success:r.success,name:e.name}}}function L$(t){let e=t.listSkills(),r=`Manage and invoke skills \u2014 reusable workflows and domain-specific knowledge packages. Use action: 'list' to discover skills, 'view' to read content, 'invoke' to run a skill. Skills can also be created, edited, patched, or deleted. Use 'promote' (with name) to copy a project skill to global (user-level) so it's available across all projects.
|
|
1073
1074
|
|
|
1074
1075
|
CROSS-PROJECT RECALL: When you see '[Cross-project skill available]' in recalled memories, it means a relevant skill exists in another project. You should proactively inform the user and offer to use it (invoke) or promote it to global. Do not wait for explicit instructions \u2014 the user may not know the skill exists. Typical user signals: '\u4E4B\u524D\u505A\u8FC7', '\u53C2\u8003XX\u9879\u76EE', 'didn't you do this before', 'same as the other project'.`;if(e.length===0)return r;let n=e.slice(0,50).map(o=>`- ${o.name}: ${o.description??"(no description)"}`).join(`
|
|
1075
1076
|
`);return`${r}
|
|
@@ -1077,16 +1078,16 @@ CROSS-PROJECT RECALL: When you see '[Cross-project skill available]' in recalled
|
|
|
1077
1078
|
Available skills:
|
|
1078
1079
|
${n}`}function Mw(t,e){let r=e.config,n=_t(t.getActiveProjectRoot()),o=[n,yt(),...Array.isArray(r?.skillPaths)?r.skillPaths:[]];K(_w({listSkills:()=>{let s=[];s.push(...t.getPluginSkills());let i=r?.skillPaths;if(Array.isArray(i)){for(let a of i)if(typeof a=="string"){let c=Ae.basename(a);s.some(l=>l.name===c)||s.push({name:c,source:"gateway",filePath:Ae.join(a,"SKILL.md"),baseDir:a})}}return s},listSkillsFull:async s=>{let i=[],a=new Set,c=yt();for(let l of o)try{let d=await pe.promises.readdir(l,{withFileTypes:!0});for(let u of d){if(!u.isDirectory())continue;let p=Ae.join(l,u.name,"SKILL.md");try{let m=await pe.promises.readFile(p,"utf8"),g=Ae.basename(l);if(s&&g!==s)continue;a.add(g);let f=l===c?"global":l===n?"project":"config",v=m.match(/^---\n[\s\S]*?^version:\s*(\S+)/m)?.[1],b=m.startsWith(`---
|
|
1079
1080
|
`)?m.indexOf("---",4):-1,R=(b>=0?m.slice(b+3).trimStart():m).split(`
|
|
1080
|
-
`).find(P=>P.trim()&&!P.startsWith("#"))?.trim()??`Skill from ${g}`;i.push({name:u.name,description:R,category:g,scope:f,version:v})}catch{}}}catch{}for(let l of t.getPluginSkills())s&&l.source!==s||(a.add(l.source??"plugin"),i.push({name:l.name,description:`Plugin skill (${l.source})`,category:l.source,scope:"plugin"}));return{skills:i,categories:[...a]}},readSkillContent:async s=>{for(let i of o){let a=Ae.join(i,s,"SKILL.md");try{return await pe.promises.readFile(a,"utf8")}catch{}}return null},viewSkill:async(s,i)=>{for(let a of o){let c=i?Ae.join(a,s,i):Ae.join(a,s,"SKILL.md");try{let l=await pe.promises.readFile(c,"utf8");return{name:s,content:l}}catch{}}return null},executeSkillSubturn:async(s,i,a,c)=>{let l=`skill_${s}_${
|
|
1081
|
-
`).slice(0,3).join(" ").slice(0,200),T=i?Ae.basename(i):"unknown";h.ingestExtracted([{text:`Learned skill "${s.name}" in project "${T}": ${S}`,category:"skill-learning"}],v).catch(()=>{})}let b=i?` (project-scoped). To make it available across all projects, use: skill promote name:"${s.name}"`:"";return{success:!0,message:`Skill "${s.name}" created${b}`,path:c}}case"edit":{let u=ge(d);if(u.records[s.name]?.pinned)return{success:!1,message:`Skill "${s.name}" is pinned. Unpin it first.`};let p=s.content??"",g=nl(p,s.name)??p;return await pe.promises.writeFile(l,g,"utf8"),el(u,s.name),ke(d,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-edit-${Date.now()}`,instruction:{name:s.name,category:s.category??"learned",content:g,scope:"project"}}),{success:!0,message:`Skill "${s.name}" updated`,path:l}}case"patch":{let u=ge(d);if(u.records[s.name]?.pinned)return{success:!1,message:`Skill "${s.name}" is pinned. Unpin it first.`};let p=await pe.promises.readFile(l,"utf8");if(!s.oldString||!p.includes(s.oldString))return{success:!1,message:"oldString not found in SKILL.md"};let m=p.replace(s.oldString,s.newString??"");return await pe.promises.writeFile(l,m,"utf8"),el(u,s.name),ke(d,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-patch-${Date.now()}`,instruction:{name:s.name,category:s.category??"learned",content:m,scope:"project"}}),{success:!0,message:`Skill "${s.name}" patched`,path:l}}case"delete":{let u=ge(d);return u.records[s.name]?.pinned?{success:!1,message:`Skill "${s.name}" is pinned. Unpin it first.`}:(await pe.promises.rm(c,{recursive:!0,force:!0}),vs(u,s.name),ke(d,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-delete-${Date.now()}`,instruction:{name:s.name,category:s.category??"learned",action:"delete",scope:"project"}}),ct(),{success:!0,message:`Skill "${s.name}" deleted`})}default:return{success:!1,message:`Unknown action: ${s.action}`}}},promoteSkill:async s=>{let i=_t(t.getActiveProjectRoot()),a=Ae.join(i,s,"SKILL.md");try{await pe.promises.access(a)}catch{return{success:!1,message:`Skill "${s}" not found in project skills. Cannot promote.`}}let c=yt(),l=Ae.join(c,s);await pe.promises.mkdir(l,{recursive:!0});let d=Ae.join(i,s),u=await pe.promises.readdir(d);for(let p of u){let m=await pe.promises.readFile(Ae.join(d,p));await pe.promises.writeFile(Ae.join(l,p),m)}return t.sendNotification("turn.skill_instruction",{turnId:`skill-promote-${Date.now()}`,instruction:{name:s,category:"promoted",content:await pe.promises.readFile(a,"utf8"),scope:"global"}}),await pe.promises.rm(d,{recursive:!0,force:!0}),t.sendNotification("turn.skill_instruction",{turnId:`skill-promote-cleanup-${Date.now()}`,instruction:{name:s,category:"learned",action:"delete",scope:"project"}}),ct(),{success:!0,message:`Skill "${s}" promoted to global (user-level) and removed from project scope. It will now be available across all projects.`,path:l}}}))}function
|
|
1082
|
-
`),n=e.length>0?[...e,...t.result.imageUrls??[]]:t.result.imageUrls,o=t.result.details?.error,s=o?r:void 0,i=t.result.details?.type,a=i?.split("_")[0];if(i==="three_d_generate"&&(a="3d"),a&&["image","tts","video","music","3d"].includes(a)){let l=t.result.details?.mediaUrls??[],d=a;for(let u of l)t.sendNotification("turn.media_result",{turnId:t.turnId,mediaType:d,url:u,model:t.result.details?.model,provider:t.result.details?.provider,...t.result.details?.durationMs?{durationSeconds:t.result.details.durationMs/1e3}:{},...t.result.details?.taskId?{taskId:t.result.details.taskId}:{}});if(l.length>0)try{let u=await t.mediaPersistence.downloadAll(l,{type:a,sessionId:t.sessionId||void 0},{warn:p=>t.log(p)});if(u.length>0){for(let p of u)r=r.replaceAll(p.remoteUrl,p.localPath);t.sendNotification("turn.media_persisted",{turnId:t.turnId,files:u.map(p=>({remoteUrl:p.remoteUrl,localPath:p.localPath,bytes:p.bytes,mimeType:p.mimeType}))})}}catch{}}if(i==="task"&&!o&&t.result.details?.taskList)try{let l=t.result.details;l?.taskList&&t.sendNotification("turn.todos_updated",{turnId:t.turnId,items:l.taskList,summary:{total:l.total??l.taskList.length,completed:l.completed??0,inProgress:l.inProgress??0,notStarted:l.notStarted??0}})}catch{}let c=Array.isArray(t.result.details?.matches)?t.result.details.matches:void 0;return{result:r,error:s,toolReferences:c,imageUrls:n,details:t.result.details}}function Lw(t){return{invoke:async(e,r,n,o)=>{if(r.startsWith("$"))return{result:n};let s=ve(r);if(!s)return{result:"",error:`Unknown tool: ${r}`};let i=`tc_${
|
|
1081
|
+
`).find(P=>P.trim()&&!P.startsWith("#"))?.trim()??`Skill from ${g}`;i.push({name:u.name,description:R,category:g,scope:f,version:v})}catch{}}}catch{}for(let l of t.getPluginSkills())s&&l.source!==s||(a.add(l.source??"plugin"),i.push({name:l.name,description:`Plugin skill (${l.source})`,category:l.source,scope:"plugin"}));return{skills:i,categories:[...a]}},readSkillContent:async s=>{for(let i of o){let a=Ae.join(i,s,"SKILL.md");try{return await pe.promises.readFile(a,"utf8")}catch{}}return null},viewSkill:async(s,i)=>{for(let a of o){let c=i?Ae.join(a,s,i):Ae.join(a,s,"SKILL.md");try{let l=await pe.promises.readFile(c,"utf8");return{name:s,content:l}}catch{}}return null},executeSkillSubturn:async(s,i,a,c)=>{let l=`skill_${s}_${O$().slice(0,8)}`,d=t.getAgent();if(!d)return"[skill] Cannot execute: no LLM provider configured";let u=W(),p=t.getCurrentSessionId()||"skill",m=ge(u).records[s],g=j$(s,m);t.getCurrentHooks()?.invoke("subagent.started",{sessionId:p,turnId:l,subagentId:l,agentType:g}).catch(()=>{});let f=new Set(["skill","agent"]),h=Ie().filter(R=>!f.has(R.function.name)),v=a??`Execute skill "${s}" instructions.`,b=[],S;for await(let R of d.run({turnId:l,sessionId:p,messages:[{role:"user",content:v}],tools:h,systemPrompt:i,config:{parentDepth:1,maxRounds:5}},c)){if(R.type==="end"&&R.content){t.getCurrentHooks()?.invoke("subagent.stopped",{sessionId:p,turnId:l,subagentId:l,agentType:g,reason:"normal"}).catch(()=>{}),Ks(u,s,!0);let P=ge(u);return Zc(P,s),ke(u,P),R.content}if(R.type==="delta"&&R.text&&b.push(R.text),R.type==="error"){S=R.error;break}}if(t.getCurrentHooks()?.invoke("subagent.stopped",{sessionId:p,turnId:l,subagentId:l,agentType:g,reason:S?"error":"normal",error:S}).catch(()=>{}),S)return Ks(u,s,!1),`[skill "${s}"] error: ${S}`;Ks(u,s,!0);let T=ge(u);return Zc(T,s),ke(u,T),b.join("")||`[skill "${s}"] completed (no output)`},manageSkill:async s=>{let i=t.getActiveProjectRoot(),a=_t(i),c=Ae.join(a,s.name),l=Ae.join(c,"SKILL.md"),d=W();switch(s.action){case"create":{let u=s.content??"",m=nl(u,s.name,`Skill: ${s.name}`)??u,g=ws(m,s.name);if(!g.valid)return{success:!1,message:`Skill validation failed: ${g.errors.join("; ")}`};let f=ge(d);if(f.records[s.name]?.pinned&&pe.existsSync(l))return{success:!1,message:`Skill "${s.name}" is pinned. Unpin it first.`};await pe.promises.mkdir(c,{recursive:!0}),await pe.promises.writeFile(l,m,"utf8"),t.sendNotification("turn.skill_instruction",{turnId:`skill-create-${Date.now()}`,instruction:{name:s.name,category:s.category??"learned",content:m,scope:"project"}}),ct(),At(f,s.name,"created"),ke(d,f);let h=t.getMemoryLearningSink(),v=t.getMemoryUserId();if(h&&v){let S=m.split(`
|
|
1082
|
+
`).slice(0,3).join(" ").slice(0,200),T=i?Ae.basename(i):"unknown";h.ingestExtracted([{text:`Learned skill "${s.name}" in project "${T}": ${S}`,category:"skill-learning"}],v).catch(()=>{})}let b=i?` (project-scoped). To make it available across all projects, use: skill promote name:"${s.name}"`:"";return{success:!0,message:`Skill "${s.name}" created${b}`,path:c}}case"edit":{let u=ge(d);if(u.records[s.name]?.pinned)return{success:!1,message:`Skill "${s.name}" is pinned. Unpin it first.`};let p=s.content??"",g=nl(p,s.name)??p;return await pe.promises.writeFile(l,g,"utf8"),el(u,s.name),ke(d,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-edit-${Date.now()}`,instruction:{name:s.name,category:s.category??"learned",content:g,scope:"project"}}),{success:!0,message:`Skill "${s.name}" updated`,path:l}}case"patch":{let u=ge(d);if(u.records[s.name]?.pinned)return{success:!1,message:`Skill "${s.name}" is pinned. Unpin it first.`};let p=await pe.promises.readFile(l,"utf8");if(!s.oldString||!p.includes(s.oldString))return{success:!1,message:"oldString not found in SKILL.md"};let m=p.replace(s.oldString,s.newString??"");return await pe.promises.writeFile(l,m,"utf8"),el(u,s.name),ke(d,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-patch-${Date.now()}`,instruction:{name:s.name,category:s.category??"learned",content:m,scope:"project"}}),{success:!0,message:`Skill "${s.name}" patched`,path:l}}case"delete":{let u=ge(d);return u.records[s.name]?.pinned?{success:!1,message:`Skill "${s.name}" is pinned. Unpin it first.`}:(await pe.promises.rm(c,{recursive:!0,force:!0}),vs(u,s.name),ke(d,u),t.sendNotification("turn.skill_instruction",{turnId:`skill-delete-${Date.now()}`,instruction:{name:s.name,category:s.category??"learned",action:"delete",scope:"project"}}),ct(),{success:!0,message:`Skill "${s.name}" deleted`})}default:return{success:!1,message:`Unknown action: ${s.action}`}}},promoteSkill:async s=>{let i=_t(t.getActiveProjectRoot()),a=Ae.join(i,s,"SKILL.md");try{await pe.promises.access(a)}catch{return{success:!1,message:`Skill "${s}" not found in project skills. Cannot promote.`}}let c=yt(),l=Ae.join(c,s);await pe.promises.mkdir(l,{recursive:!0});let d=Ae.join(i,s),u=await pe.promises.readdir(d);for(let p of u){let m=await pe.promises.readFile(Ae.join(d,p));await pe.promises.writeFile(Ae.join(l,p),m)}return t.sendNotification("turn.skill_instruction",{turnId:`skill-promote-${Date.now()}`,instruction:{name:s,category:"promoted",content:await pe.promises.readFile(a,"utf8"),scope:"global"}}),await pe.promises.rm(d,{recursive:!0,force:!0}),t.sendNotification("turn.skill_instruction",{turnId:`skill-promote-cleanup-${Date.now()}`,instruction:{name:s,category:"learned",action:"delete",scope:"project"}}),ct(),{success:!0,message:`Skill "${s}" promoted to global (user-level) and removed from project scope. It will now be available across all projects.`,path:l}}}))}function j$(t,e){return $$(e)?`community-skill:${t}`:`skill:${t}`}function $$(t){return t?.source!=="installed"?!1:t.registrySourceTier!=="official"}function Dw(t){let e=xw({log:t.log,taskStore:t.taskStore,sessionId:t.sessionId,projectRoot:t.projectRoot,memdir:t.memdir,currentUserId:t.currentUserId,prefetchState:t.memoryPrefetchState,getLastUserMessage:t.getLastUserMessage,getLastAssistantMessage:t.getLastAssistantMessage,resolveSmallModelClient:t.resolveSmallModelClient,compressionClient:{transport:t.agentClient.transport,apiKey:t.agentClient.apiKey}}),r=e.hooks;ow({config:t.config,projectRoot:t.projectRoot,log:t.log,toolCatalog:t.toolCatalog,currentManager:t.currentMcpManager,setManager:t.setMcpManager,setReady:t.setMcpReady}),sw({config:t.config,hooks:r,log:t.log,setPluginLoader:t.setPluginLoader});let n=Tw({config:t.config,hooks:r,log:t.log,sessionId:t.sessionId,getTurnId:t.getTurnId,getActiveProjectRoot:()=>t.projectRoot,getAcpPermissionSession:t.getAcpPermissionSession,sendNotification:t.sendNotification,isPetActive:t.isPetActive,currentUnregister:t.currentPermissionUnregister});return Mw({getActiveProjectRoot:()=>t.projectRoot,getPluginSkills:t.getPluginSkills,getAgent:t.getAgent,getCurrentSessionId:()=>t.sessionId,getCurrentHooks:()=>r,sendNotification:t.sendNotification,getMemoryLearningSink:()=>e.memoryLearningSink,getMemoryUserId:()=>e.memoryUserId},{config:t.config}),US({config:t.config,host:t.coreToolHost,hooks:r,log:t.log,toolInvoker:t.toolInvoker}),KS({config:t.config}),t.sessionId&&r.invoke("session.created",{sessionId:t.sessionId}).catch(()=>{}),Ew({config:t.config,hooks:r,ruleEngine:n.ruleEngine,sessionId:t.sessionId,currentFileWatcher:t.currentFileWatcher,log:t.log,setFileWatcher:t.setFileWatcher}),{hooks:r,memoryHandlerProvider:e.memoryHandlerProvider,memoryDreamProvider:e.memoryDreamProvider,memoryUserId:e.memoryUserId,permissionChecker:n.permissionChecker,permissionUnregister:n.permissionUnregister,ruleEngine:n.ruleEngine}}import{randomUUID as U$}from"node:crypto";async function Nw(t){let e=[],r=t.result.content.map(l=>{if(l.type==="image"&&l.data){let d=l.mimeType||"image/png";return e.push(`data:${d};base64,${l.data}`),"[Image]"}return l.text??""}).join(`
|
|
1083
|
+
`),n=e.length>0?[...e,...t.result.imageUrls??[]]:t.result.imageUrls,o=t.result.details?.error,s=o?r:void 0,i=t.result.details?.type,a=i?.split("_")[0];if(i==="three_d_generate"&&(a="3d"),a&&["image","tts","video","music","3d"].includes(a)){let l=t.result.details?.mediaUrls??[],d=a;for(let u of l)t.sendNotification("turn.media_result",{turnId:t.turnId,mediaType:d,url:u,model:t.result.details?.model,provider:t.result.details?.provider,...t.result.details?.durationMs?{durationSeconds:t.result.details.durationMs/1e3}:{},...t.result.details?.taskId?{taskId:t.result.details.taskId}:{}});if(l.length>0)try{let u=await t.mediaPersistence.downloadAll(l,{type:a,sessionId:t.sessionId||void 0},{warn:p=>t.log(p)});if(u.length>0){for(let p of u)r=r.replaceAll(p.remoteUrl,p.localPath);t.sendNotification("turn.media_persisted",{turnId:t.turnId,files:u.map(p=>({remoteUrl:p.remoteUrl,localPath:p.localPath,bytes:p.bytes,mimeType:p.mimeType}))})}}catch{}}if(i==="task"&&!o&&t.result.details?.taskList)try{let l=t.result.details;l?.taskList&&t.sendNotification("turn.todos_updated",{turnId:t.turnId,items:l.taskList,summary:{total:l.total??l.taskList.length,completed:l.completed??0,inProgress:l.inProgress??0,notStarted:l.notStarted??0}})}catch{}let c=Array.isArray(t.result.details?.matches)?t.result.details.matches:void 0;return{result:r,error:s,toolReferences:c,imageUrls:n,details:t.result.details}}function Lw(t){return{invoke:async(e,r,n,o)=>{if(r.startsWith("$"))return{result:n};let s=ve(r);if(!s)return{result:"",error:`Unknown tool: ${r}`};let i=`tc_${U$().slice(0,8)}`;try{let a=JSON.parse(n),c=await s.execute(i,a,o);return await Nw({turnId:e,sessionId:t.getSessionId(),result:c,mediaPersistence:t.mediaPersistence,log:t.log,sendNotification:(l,d)=>t.sendNotification(l,d)})}catch(a){return{result:"",error:a instanceof Error?a.message:String(a)}}}}}D();import{join as jw}from"node:path";import{chmod as F$}from"node:fs/promises";var $w="agent-configs.json";function Ow(){return jw(W(),$w)}function H$(t){return jw(re(t),$w)}function B$(){return{agents:{}}}var Hi=class{data=B$();cwd;constructor(e){this.cwd=e}async load(){let e=await Zt(Ow()),r=this.cwd?await Zt(H$(this.cwd)):void 0,n={gatewayUrl:e?.gatewayUrl,agents:{...e?.agents},customAgents:{...e?.customAgents}};if(r){r.gatewayUrl&&(n.gatewayUrl=r.gatewayUrl);for(let[o,s]of Object.entries(r.agents??{}))n.agents[o]={...n.agents[o],...s};for(let[o,s]of Object.entries(r.customAgents??{}))n.customAgents??={},n.customAgents[o]=s}this.data=n}getData(){return this.data}getAgentConfig(e){return this.data.agents[e]??null}async setAgentConfig(e,r){this.data.agents[e]={...this.data.agents[e],...r},await this.save()}async removeAgentConfig(e){delete this.data.agents[e],await this.save()}getGatewayUrl(){return this.data.gatewayUrl}async setGatewayUrl(e){this.data.gatewayUrl=e,await this.save()}registerCustomAgent(e){this.data.customAgents??={},this.data.customAgents[e.id]=e}unregisterCustomAgent(e){this.data.customAgents&&delete this.data.customAgents[e]}getCustomAgents(){return{...this.data.customAgents}}async save(){let e=Ow();await cr(e,this.data);try{await F$(e,384)}catch{}}};var Bi=class{constructor(e){this.deps=e}deps;store=null;get currentStore(){return this.store}async ensureStore(){return this.store||(this.store=new Hi(this.deps.getActiveProjectRoot()),await this.store.load(),this.deps.acpDetector.setConfigStore(this.store.getData())),this.store}};function Uw(t){return new Bi(t)}var qi=class{soloEvaluator=null;productOrchestrator=null;productPlanner=null;soloProcessManager=null;productProcessManager=null};function Fw(t){let e=t.acpDetector??new ls,r=new qi,o=(t.createAgentConfigRuntime??Uw)({acpDetector:e,getActiveProjectRoot:t.getActiveProjectRoot});return{acpDetector:e,get agentConfigStore(){return o.currentStore},ensureAgentConfigStore:()=>o.ensureStore(),get soloEvaluator(){return r.soloEvaluator},set soloEvaluator(s){r.soloEvaluator=s},get productOrchestrator(){return r.productOrchestrator},set productOrchestrator(s){r.productOrchestrator=s},get productPlanner(){return r.productPlanner},set productPlanner(s){r.productPlanner=s},get soloProcessManager(){return r.soloProcessManager},set soloProcessManager(s){r.soloProcessManager=s},get productProcessManager(){return r.productProcessManager},set productProcessManager(s){r.productProcessManager=s},getActiveProjectRoot:t.getActiveProjectRoot,emitAgentStatus:t.emitAgentStatus,handleMcpToolCall:t.handleMcpToolCall,log:t.log,sendNotification:t.sendNotification,sendResponse:t.sendResponse}}var Wi=class{acpSessionHistories=new Map;resumedSessionHistories=new Map;appendAcpUserMessage(e,r){let n=this.getOrCreateAcpHistory(e);return n.push({role:"user",content:r}),[...n]}appendAcpAssistantMessage(e,r){r&&this.getOrCreateAcpHistory(e).push({role:"assistant",content:r})}clearAcpSession(e){this.acpSessionHistories.delete(e)}saveResumedSession(e,r){if(r.length===0){this.resumedSessionHistories.delete(e);return}this.resumedSessionHistories.set(e,[...r])}withResumedHistory(e,r){let n=this.resumedSessionHistories.get(e);if(!n||n.length===0)return r;let o=q$(r,n)?r.slice(n.length):r;return[G$(n),...n,...o]}getOrCreateAcpHistory(e){let r=this.acpSessionHistories.get(e);return r||(r=[],this.acpSessionHistories.set(e,r)),r}};function q$(t,e){if(t.length<e.length)return!1;for(let r=0;r<e.length;r++)if(!W$(t[r],e[r]))return!1;return!0}function W$(t,e){return t.role===e.role&&JSON.stringify(t.content)===JSON.stringify(e.content)}function G$(t){let e=t.filter(n=>n.role==="user"&&typeof n.content=="string").map(n=>String(n.content).replace(/\s+/g," ").trim()).filter(Boolean).slice(-8);return{role:"system",content:["Resumed session context follows. It is authoritative prior conversation for this same session.","If the current user asks about information already present there, answer directly from it before using memory or tools.",e.length>0?` Prior user statements recovered from this session:
|
|
1083
1084
|
${e.map(n=>`- ${n.slice(0,500)}`).join(`
|
|
1084
|
-
`)}`:""].join(" ")}}import{randomUUID as
|
|
1085
|
-
`)||"OK"}catch(n){return`Error: ${n instanceof Error?n.message:String(n)}`}}var
|
|
1086
|
-
`);return await e(o,{model:o.model,messages:[{role:"user",content:s,imageUrls:[`data:image/png;base64,${r}`]}],maxTokens:200})||n||"A cute rounded desktop pet character"},async forgeGenerateSkeleton(r){let n=t.resolveClientForPurpose("textGeneration");if(!n)throw new Error("No model available for skeleton generation");let s=(await e(n,{model:n.model,messages:[{role:"user",content:yl(r)}],maxTokens:6e3})).match(/<svg[\s\S]*?<\/svg>/i);if(!s)throw new Error("Failed to generate skeleton SVG");return s[0]},async forgeScoreConsistency(r,n,o,s){let i=t.resolveClientForPurpose("imageUnderstanding");if(!i)throw new Error("No vision model available for consistency scoring");let a=`data:image/svg+xml;base64,${Yw.from(r).toString("base64")}`,c=`data:image/svg+xml;base64,${Yw.from(n).toString("base64")}`,l=await e(i,{model:i.model,messages:[{role:"user",content:bl(s,o),imageUrls:[a,c]}],maxTokens:200});return vl(l)},async awardXp(r){try{let n=new xt(t.getActiveProjectRoot()),o=n.load();if(!o)return;let s=se.xpForEvent(r),{newLevel:i,newXp:a,events:c,statBoosts:l}=se.processXpGain(o,s);o.level=i,o.experience=a;for(let[d,u]of Object.entries(l)){let p=d;o.stats[p]=Math.min(10,o.stats[p]+(u??0))}n.updateSoul(o),t.sendNotification("pet.growth",{level:i,experience:a,xpNeeded:se.xpForLevel(i),displayTraits:se.getUnlockedDisplayTraits(i).map(d=>({id:d.id,name:d.name,description:d.description,level:d.unlockedAtLevel,surface:d.surface}))});for(let d of c)d.type==="molt"?t.sendNotification("pet.reaction",{text:`\u5BA0\u7269\u8715\u53D8\uFF1A\u7B2C ${d.moltStage} \u9636\u6BB5`,style:"excited"}):d.type==="display_trait_unlock"&&d.displayTrait&&t.sendNotification("pet.reaction",{text:`Display trait unlocked: ${d.displayTrait.name}`,style:"excited"})}catch{}},async reactAfterTurn(r){try{let o=new xt(t.getActiveProjectRoot()).load(),s=t.resolveClientForPurpose("smallModel");if(o&&s){let a=[...r].reverse().find(d=>d.role==="assistant"),c=typeof a?.content=="string"?a.content.slice(0,100):"Task completed.",l=await Yn({turnSummary:c,soul:o},async(d,u)=>await e(s,{model:s.model,messages:[{role:"user",content:d}],maxTokens:u})||null);if(l){t.sendNotification("pet.reaction",{text:l.text,style:l.style,duration:1e4});return}}let i=Xn("turn.end");i&&t.sendNotification("pet.reaction",{text:i.text,style:i.style,duration:1e4})}catch{}},isActive(){return new xt(t.getActiveProjectRoot()).load()!==null}}}var Ki=class{constructor(e){this.deps=e}deps;pendingConfirms=new Map;requestConfirm(e,r,n,o=3e4){let s=`confirm_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return this.deps.sendNotification("pet.confirm",{confirmId:s,toolName:e,description:r,risk:n,timeoutMs:o}),new Promise(i=>{let a=setTimeout(()=>{this.pendingConfirms.delete(s),i(!1)},o+2e3);this.pendingConfirms.set(s,c=>{clearTimeout(a),i(c)})})}handleResponse({confirmId:e,approved:r}){this.deps.getPermissionResolver()?.resolveApproval({approvalId:e,decision:r?"approved":"denied"});let n=this.pendingConfirms.get(e);n&&(this.pendingConfirms.delete(e),n(!!r))}};function Qw(t){let{dreamHost:e,multiAgentHost:r}=t;return{get activeTurn(){return e.activeTurn},set activeTurn(n){e.activeTurn=n??null},get currentTransport(){return e.currentTransport},get currentApiKey(){return e.currentApiKey},get currentModel(){return e.currentModel},get currentHooks(){return e.currentHooks},get memoryProvider(){return e.memoryProvider},get memoryUserId(){return e.memoryUserId},get verbose(){return e.verbose},log:t.log,resolveAgent:t.resolveAgent,sendNotification:t.sendNotification,sendResponse:t.sendResponse,get acpDetector(){return r.acpDetector},get agentConfigStore(){return r.agentConfigStore},get soloEvaluator(){return r.soloEvaluator},set soloEvaluator(n){r.soloEvaluator=n},get soloProcessManager(){return r.soloProcessManager},set soloProcessManager(n){r.soloProcessManager=n},get productOrchestrator(){return r.productOrchestrator},set productOrchestrator(n){r.productOrchestrator=n},get productPlanner(){return r.productPlanner},set productPlanner(n){r.productPlanner=n},get productProcessManager(){return r.productProcessManager},set productProcessManager(n){r.productProcessManager=n},get currentSessionId(){return t.getCurrentSessionId()},getActiveProjectRoot:t.getActiveProjectRoot,emitAgentStatus:t.emitAgentStatus,handleMcpToolCall:t.handleMcpToolCall,resolveClientForPurpose:t.resolveClientForPurpose}}D();import{readFile as iu,readdir as Zw,unlink as
|
|
1087
|
-
`),n=[],o=!1;for(let s=0;s<r.length;s++){let i=r[s];if(
|
|
1088
|
-
`):null}function
|
|
1089
|
-
`);
|
|
1085
|
+
`)}`:""].join(" ")}}import{randomUUID as K$}from"node:crypto";var z$={setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},Gi=class{constructor(e){this.options=e;this.dreamState=e.dreamState??ut.dream,this.now=e.now??(()=>Date.now()),this.randomId=e.randomId??(()=>K$().slice(0,8)),this.timers=e.timers??z$}options;dreamState;now;randomId;timers;idleTimer=null;applyEnvOverrides(e){let r=Number(e.QLOGICAGENT_IDLE_DREAM_MS);r>0&&(this.dreamState.idleMinutes=r/6e4);let n=Number(e.QLOGICAGENT_DREAM_COOLDOWN_MS);n>=0&&(this.dreamState.cooldownMs=n)}enable(e){this.dreamState.enabled=!0,e&&e>0&&(this.dreamState.idleMinutes=e),this.resetTimer()}handleTurnNotification(e){e==="turn.end"&&this.resetTimer(),e==="turn.start"&&this.cancelTimer()}cancelTimer(){this.idleTimer&&(this.timers.clearTimeout(this.idleTimer),this.idleTimer=null)}resetTimer(){this.cancelTimer(),this.dreamState.enabled&&this.options.getCurrentSessionId()&&(this.idleTimer=this.timers.setTimeout(()=>{this.triggerIdleDream()},this.dreamState.idleMinutes*6e4),this.idleTimer.unref?.())}async triggerIdleDream(){if(this.now()-this.dreamState.lastDreamAt<this.dreamState.cooldownMs){this.options.log("[dream:idle] Skipped - cooldown not elapsed");return}let e=this.options.resolveDreamClient();if(!e){this.options.log("[dream:idle] Skipped - no LLM transport configured");return}if(this.options.getActiveTurn()){this.options.log("[dream:idle] Skipped - turn in progress");return}this.options.log("[dream:idle] Triggering idle dream consolidation"),this.dreamState.lastDreamAt=this.now(),this.options.sendNotification("system.activity",{category:"dream",level:"info",title:"\u7A7A\u95F2\u68A6\u5883\u6574\u7406\u89E6\u53D1",detail:`\u7A7A\u95F2 ${this.dreamState.idleMinutes} \u5206\u949F\u540E\u81EA\u52A8\u89E6\u53D1`});let r=this.timers.setTimeout(()=>{let a=this.options.getActiveTurn();a&&(this.options.log("[dream:idle] Aborting - max duration reached"),a.abort())},this.dreamState.maxDurationMs);r.unref?.();let n=this.options.getAgentHome(),o=this.options.getCurrentSessionId(),s=[];try{s=(await this.options.listRecentSessions()).filter(c=>c.sessionId!==o).map(c=>c.sessionId)}catch{}let i={jsonrpc:"2.0",method:"memory.dream",params:{turnId:`idle-dream-${this.randomId()}`,sessionId:o,config:{memoryRoot:n,transcriptDir:V$(n),dreamSessionIds:s,currentSessionTurnCount:this.options.getCurrentTurnCount(),model:e.model,apiKey:e.apiKey,force:!1}}};try{await this.options.runDream(i)}finally{this.timers.clearTimeout(r)}this.resetTimer()}};function V$(t){let e=t.replace(/[\\/]+$/,""),r=e.includes("\\")&&!e.includes("/")?"\\":"/";return`${e}${r}agent-logs`}We();function Hw(t,e){let r=t.provider,n=t.model,o=t.apiKey,s=t.baseUrl;if(!r||!o){let a=M().getActiveModel("textGeneration");a&&(r=r??a.provider,n=n??a.model,o=o??a.apiKey,s=s??a.baseUrl,a.keyHandle.release({success:!0}),e?.(`[resolveAgent] from ModelRegistry: ${r}/${n}`))}return!r||!o?null:(n=n??M().getProviderDefaultModel(r)??"",{provider:r,model:n,apiKey:o,baseUrl:s,configKey:`${r}:${n}:${o.slice(0,8)}:${s??""}`})}function Bw(t){let r=M().getActiveModel(t.purpose);if(!r)return null;let{provider:n,model:o,apiKey:s,baseUrl:i,keyHandle:a}=r;return a.release({success:!0}),n===t.currentProvider&&t.currentTransport?{transport:t.currentTransport,apiKey:s,model:o}:{transport:Do({provider:n,model:o,apiKey:s,baseUrl:i},t.providerRegistry).transport,apiKey:s,model:o}}function qw(t){let{provider:e,model:r,apiKey:n,baseUrl:o}=t.resolvedConfig,s=Do({provider:e,model:r,apiKey:n,baseUrl:o},t.providerRegistry);return s.transport=Tu(s.transport,t.sessionId||"default"),{transport:s.transport,apiKey:n,model:r,provider:e,baseUrl:o??""}}function Ww(t){return{agent:new Vr({llmTransport:t.client.transport,apiKey:t.client.apiKey,toolInvoker:t.toolInvoker,log:t.log,hooks:t.hooks,maxRounds:t.maxRounds,verbose:t.verbose,projectRoot:t.projectRoot}),...t.client}}import{randomUUID as X$}from"node:crypto";async function Gw(t){let e=t.toolCatalog.findTool(t.toolName);if(!e?.execute)return`Error: Unknown tool "${t.toolName}"`;let r=`mcp_${t.memberId}_${X$().slice(0,8)}`;try{return(await e.execute(r,t.args)).content.map(o=>o.text??"").join(`
|
|
1086
|
+
`)||"OK"}catch(n){return`Error: ${n instanceof Error?n.message:String(n)}`}}var Y$={starting:"spawning",ready:"available",running:"running",completed:"available",failed:"failed",killed:"unavailable"};function Kw(t,e,r){let n={agentId:t,status:Y$[e]??"unavailable"};return(r?.missedBeats!==void 0||r?.lastActivityAt!==void 0)&&(n.health={missedBeats:r.missedBeats??0,lastActiveAt:r.lastActivityAt?new Date(r.lastActivityAt).toISOString():new Date().toISOString()}),r?.usage&&(n.usage=r.usage),n}function zw(t){return{get activeTurn(){return t.getActiveTurn()},set activeTurn(e){t.setActiveTurn(e??null)},get currentTransport(){return t.getCurrentTransport()},get currentApiKey(){return t.getCurrentApiKey()},get currentModel(){return t.getCurrentModel()},get currentHooks(){return t.getCurrentHooks()},get memoryProvider(){return t.getMemoryProvider()},get memoryUserId(){return t.getMemoryUserId()},get verbose(){return t.getVerbose()},log(e){t.log(e)},resolveAgent(e){return t.resolveAgent(e)},sendNotification(e,r){t.sendNotification(e,r)},sendResponse(e,r,n){t.sendResponse(e,r,n)}}}D();import*as Sn from"node:fs";import*as Vw from"node:path";function Xw(t){let e=oe();if(e)e.workspaceDir&&t.pathService.setActiveWorkdir(e.workspaceDir);else{let n=Vw.join(F(),"workspaces","default");Sn.existsSync(n)||Sn.mkdirSync(n,{recursive:!0});let o=Sg(n);Gs(n),t.pathService.setActiveWorkdir(n),t.sendNotification("project.created",{id:o.id,name:o.name,workspaceDir:o.workspaceDir,type:o.type})}J$();let r=t.projectMemoryStoreFactory.create(t.pathService.getActiveProjectRoot());return r.ensureInitialized(),r}function J$(){let e=V().find(r=>r.type==="default"&&r.status==="active");e&&(Sn.existsSync(e.workspaceDir)||Sn.mkdirSync(e.workspaceDir,{recursive:!0}))}import{Buffer as Yw}from"node:buffer";function Jw(t){let e=async(r,n)=>{let o="";for await(let s of r.transport.stream(n,r.apiKey))s.type==="delta"&&(o+=s.text);return o.trim()};return{createPetSoulGenerator(){let r=t.resolveClientForPurpose("smallModel");if(r)return async n=>{let o=`\u4F60\u662F\u684C\u9762\u5BA0\u7269\u7075\u9B42\u751F\u6210\u5668\u3002\u4E25\u683C\u8F93\u51FA JSON\uFF0C\u5305\u542B name\u3001personality\u3001catchphrase\u3002 \u7A00\u6709\u5EA6: ${n}\u3002\u540D\u5B57 2-4 \u4E2A\u4E2D\u6587\u5B57\u7B26\uFF0C\u6027\u683C 15 \u5B57\u5185\uFF0C\u53E3\u5934\u7985 6 \u5B57\u5185\u3002`;try{let i=(await e(r,{model:r.model,messages:[{role:"user",content:o}],maxTokens:100})).match(/\{[\s\S]*\}/);if(i){let a=JSON.parse(i[0]);if(a.name&&a.personality&&a.catchphrase)return{name:String(a.name).slice(0,8),personality:String(a.personality).slice(0,30),catchphrase:String(a.catchphrase).slice(0,12)}}}catch{}throw new Error("LLM_GENERATION_FAILED")}},createSmallLLMCall(){let r=t.resolveClientForPurpose("smallModel")??t.resolveClientForPurpose("textGeneration");if(r)return async(n,o)=>{try{return await e(r,{model:r.model,messages:[{role:"user",content:n}],maxTokens:o})||null}catch{return null}}},async forgeAnalyzeImage(r,n){let o=t.resolveClientForPurpose("imageUnderstanding");if(!o)throw new Error("No vision model available for image analysis");let s=["Analyze this character image for a 200x200 animated SVG desktop pet.","Return a concise plain-text character description covering species, colors, body shape, key features, eyes, and style.",n?`User hint: ${n}`:""].filter(Boolean).join(`
|
|
1087
|
+
`);return await e(o,{model:o.model,messages:[{role:"user",content:s,imageUrls:[`data:image/png;base64,${r}`]}],maxTokens:200})||n||"A cute rounded desktop pet character"},async forgeGenerateSkeleton(r){let n=t.resolveClientForPurpose("textGeneration");if(!n)throw new Error("No model available for skeleton generation");let s=(await e(n,{model:n.model,messages:[{role:"user",content:yl(r)}],maxTokens:6e3})).match(/<svg[\s\S]*?<\/svg>/i);if(!s)throw new Error("Failed to generate skeleton SVG");return s[0]},async forgeScoreConsistency(r,n,o,s){let i=t.resolveClientForPurpose("imageUnderstanding");if(!i)throw new Error("No vision model available for consistency scoring");let a=`data:image/svg+xml;base64,${Yw.from(r).toString("base64")}`,c=`data:image/svg+xml;base64,${Yw.from(n).toString("base64")}`,l=await e(i,{model:i.model,messages:[{role:"user",content:bl(s,o),imageUrls:[a,c]}],maxTokens:200});return vl(l)},async awardXp(r){try{let n=new xt(t.getActiveProjectRoot()),o=n.load();if(!o)return;let s=se.xpForEvent(r),{newLevel:i,newXp:a,events:c,statBoosts:l}=se.processXpGain(o,s);o.level=i,o.experience=a;for(let[d,u]of Object.entries(l)){let p=d;o.stats[p]=Math.min(10,o.stats[p]+(u??0))}n.updateSoul(o),t.sendNotification("pet.growth",{level:i,experience:a,xpNeeded:se.xpForLevel(i),displayTraits:se.getUnlockedDisplayTraits(i).map(d=>({id:d.id,name:d.name,description:d.description,level:d.unlockedAtLevel,surface:d.surface}))});for(let d of c)d.type==="molt"?t.sendNotification("pet.reaction",{text:`\u5BA0\u7269\u8715\u53D8\uFF1A\u7B2C ${d.moltStage} \u9636\u6BB5`,style:"excited"}):d.type==="display_trait_unlock"&&d.displayTrait&&t.sendNotification("pet.reaction",{text:`Display trait unlocked: ${d.displayTrait.name}`,style:"excited"})}catch{}},async reactAfterTurn(r){try{let o=new xt(t.getActiveProjectRoot()).load(),s=t.resolveClientForPurpose("smallModel");if(o&&s){let a=[...r].reverse().find(d=>d.role==="assistant"),c=typeof a?.content=="string"?a.content.slice(0,100):"Task completed.",l=await Yn({turnSummary:c,soul:o},async(d,u)=>await e(s,{model:s.model,messages:[{role:"user",content:d}],maxTokens:u})||null);if(l){t.sendNotification("pet.reaction",{text:l.text,style:l.style,duration:1e4});return}}let i=Xn("turn.end");i&&t.sendNotification("pet.reaction",{text:i.text,style:i.style,duration:1e4})}catch{}},isActive(){return new xt(t.getActiveProjectRoot()).load()!==null}}}var Ki=class{constructor(e){this.deps=e}deps;pendingConfirms=new Map;requestConfirm(e,r,n,o=3e4){let s=`confirm_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;return this.deps.sendNotification("pet.confirm",{confirmId:s,toolName:e,description:r,risk:n,timeoutMs:o}),new Promise(i=>{let a=setTimeout(()=>{this.pendingConfirms.delete(s),i(!1)},o+2e3);this.pendingConfirms.set(s,c=>{clearTimeout(a),i(c)})})}handleResponse({confirmId:e,approved:r}){this.deps.getPermissionResolver()?.resolveApproval({approvalId:e,decision:r?"approved":"denied"});let n=this.pendingConfirms.get(e);n&&(this.pendingConfirms.delete(e),n(!!r))}};function Qw(t){let{dreamHost:e,multiAgentHost:r}=t;return{get activeTurn(){return e.activeTurn},set activeTurn(n){e.activeTurn=n??null},get currentTransport(){return e.currentTransport},get currentApiKey(){return e.currentApiKey},get currentModel(){return e.currentModel},get currentHooks(){return e.currentHooks},get memoryProvider(){return e.memoryProvider},get memoryUserId(){return e.memoryUserId},get verbose(){return e.verbose},log:t.log,resolveAgent:t.resolveAgent,sendNotification:t.sendNotification,sendResponse:t.sendResponse,get acpDetector(){return r.acpDetector},get agentConfigStore(){return r.agentConfigStore},get soloEvaluator(){return r.soloEvaluator},set soloEvaluator(n){r.soloEvaluator=n},get soloProcessManager(){return r.soloProcessManager},set soloProcessManager(n){r.soloProcessManager=n},get productOrchestrator(){return r.productOrchestrator},set productOrchestrator(n){r.productOrchestrator=n},get productPlanner(){return r.productPlanner},set productPlanner(n){r.productPlanner=n},get productProcessManager(){return r.productProcessManager},set productProcessManager(n){r.productProcessManager=n},get currentSessionId(){return t.getCurrentSessionId()},getActiveProjectRoot:t.getActiveProjectRoot,emitAgentStatus:t.emitAgentStatus,handleMcpToolCall:t.handleMcpToolCall,resolveClientForPurpose:t.resolveClientForPurpose}}D();import{readFile as iu,readdir as Zw,unlink as Q$,stat as Z$,mkdir as eU}from"node:fs/promises";import{existsSync as Ct,readFileSync as eT,mkdirSync as tT,writeFileSync as tU}from"node:fs";import{join as tt}from"node:path";var fe=12288,au=200,zi=8192,rU="memory",yr="INDEX.md";function cu(t){return tt(re(t),rU)}var nU=[/ignore\s+(previous|all|above|prior)\s+instructions/i,/you\s+are\s+now\s+/i,/do\s+not\s+tell\s+the\s+user/i,/system\s+prompt\s+override/i];function Vi(t){return!nU.some(e=>e.test(t))}var oU=/^[a-z0-9][a-z0-9\-_.]*\.md$/i;function Xi(t){return!(!oU.test(t)||t===yr||t.includes("..")||t.includes("/")||t.includes("\\"))}function sU(t){return t.trim().match(/^([A-Za-z][A-Za-z0-9_-]{2,})\s*:/)?.[1]??null}function iU(t,e){let r=t.split(`
|
|
1088
|
+
`),n=[],o=!1;for(let s=0;s<r.length;s++){let i=r[s];if(aU(i)&&i.includes(e)){for(o=!0;s+1<r.length&&rT(r[s+1]);)s++;continue}n.push(i)}return o?n.join(`
|
|
1089
|
+
`):null}function aU(t){return t.trim()!==""&&!t.startsWith("#")&&!t.startsWith("<!--")&&!rT(t)}function rT(t){return t.startsWith(" ")||t.startsWith(" ")}var Yi=class{root;indexCache=null;constructor(e){this.root=cu(e)}getRootPath(){return this.root}ensureInitialized(){Ct(this.root)||tT(this.root,{recursive:!0});let e=tt(this.root,yr);if(!Ct(e)){let r=["# Memory Index","","<!-- Agent-managed memory. Lines here are always visible in system prompt.>","<!-- Use memory tool to add notes, or create topic files for longer content.>","","## User Profile","","## Notes",""].join(`
|
|
1090
|
+
`);cU(e,r)}}getIndexForPrompt(){let e=tt(this.root,yr);if(!Ct(e))return"";let r;try{r=eT(e,"utf-8")}catch{return""}this.indexCache=r;let n=r.split(`
|
|
1090
1091
|
`);return n.length>au&&(r=n.slice(0,au).join(`
|
|
1091
1092
|
`)+`
|
|
1092
1093
|
|
|
@@ -1105,18 +1106,18 @@ ${e.map(n=>`- ${n.slice(0,500)}`).join(`
|
|
|
1105
1106
|
`)?u+r+`
|
|
1106
1107
|
`:u+`
|
|
1107
1108
|
`+r+`
|
|
1108
|
-
`;return Buffer.byteLength(p,"utf-8")<=fe?p:null}async replaceInIndex(e,r){if(!e.trim())return{ok:!1,message:"old_text cannot be empty."};if(!r.trim())return{ok:!1,message:"new_text cannot be empty. Use 'remove' to delete."};if(!Vi(r))return{ok:!1,message:"Content rejected: potential injection detected."};let n=this.getIndexRaw(),o=n.split(e).length-1;if(o===0)return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};if(o>1)return{ok:!1,message:`Multiple matches (${o}) for: "${e.slice(0,80)}". Be more specific.`};let s=n.replace(e,r);if(Buffer.byteLength(s,"utf-8")>fe)return{ok:!1,message:`Replacement would exceed INDEX.md limit (${Buffer.byteLength(s,"utf-8")}/${fe} bytes).`};await this.writeIndex(s);let i=this.getIndexUsage();return{ok:!0,message:`Replaced in INDEX.md. [${i.chars}/${fe} chars]`,indexUsage:`${i.chars}/${fe}`}}async removeFromIndex(e){if(!e.trim())return{ok:!1,message:"old_text cannot be empty."};let r=this.getIndexRaw(),n=
|
|
1109
|
+
`;return Buffer.byteLength(p,"utf-8")<=fe?p:null}async replaceInIndex(e,r){if(!e.trim())return{ok:!1,message:"old_text cannot be empty."};if(!r.trim())return{ok:!1,message:"new_text cannot be empty. Use 'remove' to delete."};if(!Vi(r))return{ok:!1,message:"Content rejected: potential injection detected."};let n=this.getIndexRaw(),o=n.split(e).length-1;if(o===0)return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};if(o>1)return{ok:!1,message:`Multiple matches (${o}) for: "${e.slice(0,80)}". Be more specific.`};let s=n.replace(e,r);if(Buffer.byteLength(s,"utf-8")>fe)return{ok:!1,message:`Replacement would exceed INDEX.md limit (${Buffer.byteLength(s,"utf-8")}/${fe} bytes).`};await this.writeIndex(s);let i=this.getIndexUsage();return{ok:!0,message:`Replaced in INDEX.md. [${i.chars}/${fe} chars]`,indexUsage:`${i.chars}/${fe}`}}async removeFromIndex(e){if(!e.trim())return{ok:!1,message:"old_text cannot be empty."};let r=this.getIndexRaw(),n=sU(e),o=n?iU(r,n):null;if(o===null){if(!r.includes(e))return{ok:!1,message:`No match found for: "${e.slice(0,80)}"`};o=r.replace(e,"")}o=o.replace(/\n{3,}/g,`
|
|
1109
1110
|
|
|
1110
|
-
`),await this.writeIndex(o);let s=this.getIndexUsage();return{ok:!0,message:`Removed from INDEX.md. [${s.chars}/${fe} chars]`,indexUsage:`${s.chars}/${fe}`}}async listFiles(){if(!Ct(this.root))return[];let e=await Zw(this.root),r=[];for(let n of e){if(n===yr||!n.endsWith(".md"))continue;let o=tt(this.root,n);try{let s=await
|
|
1111
|
+
`),await this.writeIndex(o);let s=this.getIndexUsage();return{ok:!0,message:`Removed from INDEX.md. [${s.chars}/${fe} chars]`,indexUsage:`${s.chars}/${fe}`}}async listFiles(){if(!Ct(this.root))return[];let e=await Zw(this.root),r=[];for(let n of e){if(n===yr||!n.endsWith(".md"))continue;let o=tt(this.root,n);try{let s=await Z$(o);if(!s.isFile())continue;let a=(await iu(o,"utf-8")).split(`
|
|
1111
1112
|
`).find(c=>c.trim()&&!c.startsWith("#"))?.trim();r.push({name:n,size:s.size,modifiedAt:s.mtime.toISOString(),preview:a?.slice(0,100)})}catch{}}return r.sort((n,o)=>o.modifiedAt.localeCompare(n.modifiedAt))}async createFile(e,r){if(!Xi(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files (e.g. "project-notes.md").`};if(!Vi(r))return{ok:!1,message:"Content rejected: potential injection detected."};if(r.length>zi)return{ok:!1,message:`Content too long (${r.length} chars, max ${zi}).`};let n=tt(this.root,e);if(Ct(n))return{ok:!1,message:`File already exists: "${e}". Use write_file to update.`};await this.ensureDir(),await sn(n,r);let o=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;return await this.appendIndexEntry(o),{ok:!0,message:`Created "${e}" (${r.length} chars). Entry added to INDEX.md.`,file:e}}async writeFile(e,r){if(!Xi(e))return{ok:!1,message:`Invalid filename: "${e}". Use kebab-case .md files.`};if(!Vi(r))return{ok:!1,message:"Content rejected: potential injection detected."};if(r.length>zi)return this.writeFileSplit(e,r);let n=tt(this.root,e),o=!Ct(n);if(await this.ensureDir(),await sn(n,r),o){let s=`- [${e}] \u2014 created ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(s)}return{ok:!0,message:`${o?"Created":"Updated"} "${e}" (${r.length} chars).`,file:e}}async writeFileSplit(e,r){let n=e.replace(/\.md$/,""),o=r.split(/\n{2,}/),s=[],i="";for(let l of o)i.length+l.length+2>zi*.9&&i.length>0?(s.push(i),i=l):i=i?i+`
|
|
1112
1113
|
|
|
1113
|
-
`+l:l;i&&s.push(i);let a=[];for(let l=0;l<s.length;l++){let d=`${n}-${l+1}.md`,u=tt(this.root,d);await this.ensureDir(),await sn(u,s[l]),a.push(d)}let c=this.getIndexRaw();for(let l of a)if(!c.includes(`[${l}]`)){let d=`- [${l}] \u2014 auto-split ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(d)}return{ok:!0,message:`Auto-split "${e}" into ${s.length} parts (${r.length} chars total): ${a.join(", ")}`,file:a[0]}}async readFile(e){if(!Xi(e)&&e!==yr)return{ok:!1,message:`Invalid filename: "${e}".`};let r=tt(this.root,e);try{let n=await iu(r,"utf-8");return{ok:!0,content:n,message:`Read "${e}" (${n.length} chars).`}}catch(n){return n.code==="ENOENT"?{ok:!1,message:`File not found: "${e}".`}:{ok:!1,message:`Error reading "${e}": ${n.message}`}}}async deleteFile(e){if(e===yr)return{ok:!1,message:"Cannot delete INDEX.md. Use 'remove' to clear entries."};if(!Xi(e))return{ok:!1,message:`Invalid filename: "${e}".`};let r=tt(this.root,e);if(!Ct(r))return{ok:!1,message:`File not found: "${e}".`};await
|
|
1114
|
+
`+l:l;i&&s.push(i);let a=[];for(let l=0;l<s.length;l++){let d=`${n}-${l+1}.md`,u=tt(this.root,d);await this.ensureDir(),await sn(u,s[l]),a.push(d)}let c=this.getIndexRaw();for(let l of a)if(!c.includes(`[${l}]`)){let d=`- [${l}] \u2014 auto-split ${new Date().toISOString().slice(0,10)}`;await this.appendIndexEntry(d)}return{ok:!0,message:`Auto-split "${e}" into ${s.length} parts (${r.length} chars total): ${a.join(", ")}`,file:a[0]}}async readFile(e){if(!Xi(e)&&e!==yr)return{ok:!1,message:`Invalid filename: "${e}".`};let r=tt(this.root,e);try{let n=await iu(r,"utf-8");return{ok:!0,content:n,message:`Read "${e}" (${n.length} chars).`}}catch(n){return n.code==="ENOENT"?{ok:!1,message:`File not found: "${e}".`}:{ok:!1,message:`Error reading "${e}": ${n.message}`}}}async deleteFile(e){if(e===yr)return{ok:!1,message:"Cannot delete INDEX.md. Use 'remove' to clear entries."};if(!Xi(e))return{ok:!1,message:`Invalid filename: "${e}".`};let r=tt(this.root,e);if(!Ct(r))return{ok:!1,message:`File not found: "${e}".`};await Q$(r);let n=this.getIndexRaw(),o=new RegExp(`^.*\\[${lU(e)}\\].*$\\n?`,"m");if(o.test(n)){let s=n.replace(o,"").replace(/\n{3,}/g,`
|
|
1114
1115
|
|
|
1115
1116
|
`);await this.writeIndex(s)}return{ok:!0,message:`Deleted "${e}" and removed INDEX.md entry.`,file:e}}async searchLocal(e){if(!Ct(this.root))return[];let r=e.toLowerCase().split(/\s+/).filter(s=>s.length>1);if(r.length===0)return[];let n=await Zw(this.root),o=[];for(let s of n){if(!s.endsWith(".md"))continue;let i=tt(this.root,s);try{let a=await iu(i,"utf-8"),c=a.toLowerCase(),l=r.filter(m=>c.includes(m)).length;if(l===0)continue;let d=a.split(`
|
|
1116
|
-
`),u="",p=0;for(let m of d){let g=m.toLowerCase(),f=r.filter(h=>g.includes(h)).length;f>p&&(p=f,u=m.trim())}o.push({file:s,snippet:u.slice(0,200),score:l/r.length})}catch{}}return o.sort((s,i)=>i.score-s.score).slice(0,10)}async writeIndex(e){await this.ensureDir(),await sn(tt(this.root,yr),e),this.indexCache=e}async ensureDir(){Ct(this.root)||await
|
|
1117
|
+
`),u="",p=0;for(let m of d){let g=m.toLowerCase(),f=r.filter(h=>g.includes(h)).length;f>p&&(p=f,u=m.trim())}o.push({file:s,snippet:u.slice(0,200),score:l/r.length})}catch{}}return o.sort((s,i)=>i.score-s.score).slice(0,10)}async writeIndex(e){await this.ensureDir(),await sn(tt(this.root,yr),e),this.indexCache=e}async ensureDir(){Ct(this.root)||await eU(this.root,{recursive:!0})}async appendIndexEntry(e){let r=this.getIndexRaw();if(r.includes(e))return;let n=r.endsWith(`
|
|
1117
1118
|
`)?r+e+`
|
|
1118
1119
|
`:r+`
|
|
1119
1120
|
`+e+`
|
|
1120
|
-
`;Buffer.byteLength(n,"utf-8")<=fe&&await this.writeIndex(n)}};function aU(t,e){let r=tt(t,"..");Ct(r)||tT(r,{recursive:!0}),eU(t,e,"utf-8")}function cU(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nT(){return{getRootPath(t){return cu(t)},create(t){return new Yi(t)}}}var dU=lU(import.meta.url);function uU(){for(let t of["../package.json","../../package.json"])try{return dU(t).version}catch{}return"0.0.0"}var oT=uU();var pU=new Set(["thread.user_response","tool.approval.response"]);var Ji=class{running=!1;startedAt=Date.now();packageVersion=oT;rpcContract=new In;rpcIds=new Map;rpcDeadlineTimers=new Map;activeTurn=null;turnDone=Promise.resolve();verbose;transport;registry;mediaClient;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentHooks=null;mcpManager=null;mcpReady=Promise.resolve();pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new Uo;mediaPersistence=new qo;pathService;toolCatalog=sS();memoryPrefetchState=ht();memoryProvider=null;memoryDreamProvider=null;memoryUserId="";lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;projectMemoryStoreFactory=nT();fileWatcher=null;pendingAskUser=new Map;sessionTaskDomain;multiAgentHandlerHost;acpServer=null;sessionHistory=new Wi;idleDreamCoordinator;petRuntime;petConfirmCoordinator;modelRegistryHydration=null;constructor(e){this.verbose=e.verbose,this.registry=new Su,this.mediaClient=new Ru({registry:this.registry}),this.pathService=new wi(this.mediaPersistence),this.petRuntime=Jw({getActiveProjectRoot:()=>this.getActiveProjectRoot(),resolveClientForPurpose:r=>this.resolveClientForPurpose(r),sendNotification:(r,n)=>this.sendNotification(r,n)}),this.petConfirmCoordinator=new Ki({getPermissionResolver:()=>this.permissionChecker,sendNotification:(r,n)=>this.sendNotification(r,n)}),this.multiAgentHandlerHost=Fw({getActiveProjectRoot:()=>this.getActiveProjectRoot(),emitAgentStatus:(r,n,o)=>this.emitAgentStatus(r,n,o),handleMcpToolCall:(r,n,o)=>this.handleMcpToolCall(r,n,o),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),sendResponse:(r,n,o)=>this.sendResponse(r,n,o)}),this.idleDreamCoordinator=new Gi({log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),getCurrentSessionId:()=>this.currentSessionId,getCurrentTurnCount:()=>this.sessionState?.turnCount??0,getActiveTurn:()=>this.activeTurn,resolveDreamClient:()=>this.resolveClientForPurpose("textGeneration"),getAgentHome:()=>F(),listRecentSessions:()=>Dt(20,this.getActiveProjectRoot()),runDream:r=>Yr.call(this.createDreamHandlerHost(),r)}),M().onChange(()=>{this.lastLlmConfigKey=""}),this.ensureModelRegistryHydrated().catch(()=>{}),this.idleDreamCoordinator.applyEnvOverrides(process.env),this.transport=e.transport??new Ur({verbose:e.verbose}),this.taskStore.onTaskChange((r,n)=>{n&&this.sendNotification("task.updated",{taskId:r,type:n.type,lifecycle:n.lifecycle,label:n.label})}),iS({verbose:e.verbose,log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n)})}getActiveProjectRoot(){return this.pathService.getActiveProjectRoot()}async ensureModelRegistryHydrated(){return this.modelRegistryHydration||(this.modelRegistryHydration=(async()=>{let e=M();e.load(),await Cn(e),e.save()})().catch(e=>{this.modelRegistryHydration=null;let r=e instanceof Error?e.message:String(e);throw this.log(`[model-registry] failed to refresh llmrouter catalog: ${r}`),e})),this.modelRegistryHydration}syncToolListMediaConfig(){ci({host:this,config:void 0,turnId:this.currentTurnId||"tools-list"})}setActiveWorkdir(e){this.pathService.setActiveWorkdir(e)}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(this.acpServer){if(nc(e)||_n(e)){this.acpServer.dispatchMessage(e);return}if(En(e)){let r=e.method;if(r==="initialize"||r.startsWith("session/")||r.startsWith("x/")||r.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!tc(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}async stop(){if(this.running){this.running=!1,this.cancelIdleDreamTimer();for(let e of this.rpcDeadlineTimers.values())clearTimeout(e);this.rpcDeadlineTimers.clear(),this.rpcIds.clear(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{if(await cp(),this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null),this.mcpManager){let e=this.mcpManager;this.mcpManager=null,await e.disconnectAll()}this.permissionUnregister&&(this.permissionUnregister(),this.permissionUnregister=null),this.closeMemoryProviders(),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),this.transport.close()}catch(e){this.currentSessionId&&this.currentHooks&&this.currentHooks.invoke("stop.failed",{sessionId:this.currentSessionId,reason:"cleanup_error",error:e.message}).catch(()=>{})}this.log("stopped")}}methodHandlers=rR(this);handleMessage(e){if(e.id!==void 0&&!pU.has(e.method)){let n=Go(e);if(!n.ok){this.sendContractError(e.id,n.error);return}let o=this.rpcContract.begin(e.method,n.meta);if(o.status==="rejected"){this.sendContractError(e.id,o.error);return}if(o.status==="deduped"){this.sendContractErrorOrResult(e.id,o.result,o.error);return}this.rpcIds.set(e.id,n.meta),this.scheduleRpcDeadline(e.id,e.method,n.meta)}let r=this.methodHandlers.get(e.method);r?r(e):e.id!==void 0&&this.sendResponse(e.id,void 0,{code:y.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}ensureDefaultProject(){this.memdir=Xw({pathService:this.pathService,projectMemoryStoreFactory:this.projectMemoryStoreFactory,sendNotification:(e,r)=>this.sendNotification(e,r)})}resolveClientForPurpose(e){return Bw({purpose:e,providerRegistry:this.registry,currentProvider:this.currentProvider,currentTransport:this.currentTransport})}ensureMemoryProvider(){if(this.memoryProvider)return;let e=Kd(this.getActiveProjectRoot(),this.memoryUserId);this.memoryProvider=e.handlerProvider,this.memoryDreamProvider=e.dreamProvider,this.memoryUserId=e.userId}resolveAgent(e){let r=Hw(e,g=>this.log(g));if(!r)return null;let{provider:n,model:o,apiKey:s,baseUrl:i,configKey:a}=r;if(this.agent&&this.lastLlmConfigKey===a)return e.model=o,e.provider=n,e.apiKey=s,i&&(e.baseUrl=i),this.agent;e.model=o,e.provider=n,e.apiKey=s,i&&(e.baseUrl=i);let c={info:g=>this.log(g),warn:g=>this.log(`[warn] ${g}`),error:g=>this.log(`[error] ${g}`),debug:g=>{this.verbose&&this.log(`[debug] ${g}`)}},l=Lw({mediaPersistence:this.mediaPersistence,getSessionId:()=>this.currentSessionId,log:g=>this.log(g),sendNotification:(g,f)=>this.sendNotification(g,f)}),d=qw({resolvedConfig:r,providerRegistry:this.registry,sessionId:this.currentSessionId}),u=Dw({config:e,log:c,taskStore:this.taskStore,sessionId:this.currentSessionId??"",getTurnId:()=>this.currentTurnId,projectRoot:this.getActiveProjectRoot(),memdir:this.memdir,currentUserId:this.memoryUserId,memoryPrefetchState:this.memoryPrefetchState,getLastUserMessage:()=>this.lastUserMessageForAutoExtract,getLastAssistantMessage:()=>this.lastAssistantMessageForExtract,resolveSmallModelClient:()=>this.resolveClientForPurpose("smallModel"),agentClient:d,toolCatalog:this.toolCatalog,currentMcpManager:this.mcpManager,setMcpManager:g=>{this.mcpManager=g},setMcpReady:g=>{this.mcpReady=g},setPluginLoader:g=>{this.pluginLoader=g},getPluginSkills:()=>this.pluginLoader?.getPluginSkills()??[],getAgent:()=>this.agent,getAcpPermissionSession:()=>this.acpServer?.sessionId?{sessionId:this.acpServer.sessionId,requestPermission:g=>this.acpServer.requestPermission(g)}:void 0,sendNotification:(g,f)=>this.sendNotification(g,f),isPetActive:()=>this.petRuntime.isActive(),currentPermissionUnregister:this.permissionUnregister,coreToolHost:{getAgent:()=>this.agent,getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),getVerbose:()=>this.verbose,sendNotification:(g,f)=>this.sendNotification(g,f),emitAgentStatus:(g,f,h)=>this.emitAgentStatus(g,f,h),handleMcpToolCall:(g,f,h)=>this.handleMcpToolCall(g,f,h)},toolInvoker:l,currentFileWatcher:this.fileWatcher,setFileWatcher:g=>{this.fileWatcher=g}}),p=u.hooks;this.currentHooks=p,this.memoryProvider=u.memoryHandlerProvider,this.memoryDreamProvider=u.memoryDreamProvider,this.memoryUserId=u.memoryUserId,this.permissionChecker=u.permissionChecker,this.permissionUnregister=u.permissionUnregister;let m=Ww({client:d,toolInvoker:l,log:c,hooks:p,maxRounds:e.maxRounds,verbose:this.verbose,projectRoot:this.getActiveProjectRoot()});return this.agent=m.agent,this.lastLlmConfigKey=a,this.currentTransport=m.transport,this.currentApiKey=m.apiKey,this.currentModel=m.model,this.currentProvider=m.provider,this.currentBaseUrl=m.baseUrl,this.log(`created Agent (provider: ${n}, model: ${o})`),this.agent}emitAgentStatus(e,r,n){this.sendNotification("agents.status",Kw(e,r,n))}createDreamHandlerHost(){return zw({getActiveTurn:()=>this.activeTurn,setActiveTurn:e=>{this.activeTurn=e},getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentHooks:()=>this.currentHooks,getMemoryProvider:()=>this.memoryDreamProvider,getMemoryUserId:()=>this.memoryUserId,getVerbose:()=>this.verbose,log:e=>this.log(e),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n)})}createAcpExtendedHandlerHost(){return Qw({dreamHost:this.createDreamHandlerHost(),multiAgentHost:this.multiAgentHandlerHost,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),log:e=>this.log(e),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n),emitAgentStatus:(e,r,n)=>this.emitAgentStatus(e,r,n),handleMcpToolCall:(e,r,n)=>this.handleMcpToolCall(e,r,n),resolveClientForPurpose:e=>this.resolveClientForPurpose(e)})}async handleMcpToolCall(e,r,n){return Gw({toolCatalog:this.toolCatalog,memberId:e,toolName:r,args:n})}sendResponse(e,r,n){let o=this.rpcIds.get(e);if(o){let i=this.rpcContract.settle(o.requestId,r,n);if(this.clearRpcLifecycle(e),!i.accepted){this.log(`[rpc] dropped late response id=${String(e)} requestId=${o.requestId} reason=${i.reason}`);return}}let s={jsonrpc:"2.0",id:e};n?s.error=n:s.result=r,this.writeStdout(s)}sendContractError(e,r){let n={jsonrpc:"2.0",id:e,error:r};this.writeStdout(n)}sendContractErrorOrResult(e,r,n){if(n){this.sendContractError(e,n);return}let o={jsonrpc:"2.0",id:e,result:r};this.writeStdout(o)}scheduleRpcDeadline(e,r,n){let o=Math.max(0,n.deadlineAt-Date.now()),s=setTimeout(()=>{if(!this.rpcIds.has(e))return;let i=this.rpcContract.expire(n.requestId);this.clearRpcLifecycle(e),i&&(this.log(`[rpc] deadline exceeded method=${r} id=${String(e)} requestId=${n.requestId}`),this.writeStdout({jsonrpc:"2.0",id:e,error:{code:y.REQUEST_DEADLINE_EXCEEDED,message:`RPC request deadline exceeded: ${r}.`}}))},o);s.unref?.(),this.rpcDeadlineTimers.set(e,s)}clearRpcLifecycle(e){let r=this.rpcDeadlineTimers.get(e);r&&clearTimeout(r),this.rpcDeadlineTimers.delete(e),this.rpcIds.delete(e)}sendNotification(e,r){if(this.acpServer&&this.acpServer.sessionId)Ip(this.acpServer,this.acpServer.sessionId,e,r);else{let n={jsonrpc:"2.0",method:e,params:r};this.writeStdout(n)}this.idleDreamCoordinator.handleTurnNotification(e)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`${JSON.stringify({ts:new Date().toISOString(),level:"info",service:"qlogicagent",message:e})}
|
|
1121
|
-
`)}enableIdleDream(e){this.idleDreamCoordinator.enable(e)}cancelIdleDreamTimer(){this.idleDreamCoordinator.cancelTimer()}disposeSessionRuntime(){this.permissionUnregister&&(this.permissionUnregister(),this.permissionUnregister=null),this.closeMemoryProviders(),this.agent=null,this.currentHooks=null,this.lastLlmConfigKey="",this.memoryPrefetchState=ht()}closeMemoryProviders(){let e=new Set;for(let r of[this.memoryProvider,this.memoryDreamProvider]){if(!r||e.has(r))continue;e.add(r);let n=r.close;if(typeof n=="function")try{n.call(r)}catch{}}this.memoryProvider=null,this.memoryDreamProvider=null}initAcpServer(){let e=DR(this,oT,this.createAcpExtendedHandlerHost());this.acpServer=new zo(this.transport,e,{verbose:this.verbose})}getAcpServer(){return this.acpServer}};function sT(t){let e={verbose:!1};for(let r of t.slice(2))(r==="--verbose"||r==="-v")&&(e.verbose=!0);return e}import{writeFileSync as
|
|
1122
|
-
`;lT.call(process.stderr,e);try{aT(du,e)}catch{}}var lT=process.stderr.write.bind(process.stderr);process.stderr.write=((t,...e)=>{let r=typeof t=="string"?t:Buffer.from(t).toString();try{aT(du,r)}catch{}return lT(t,...e)});rt(`PID=${process.pid} argv=${JSON.stringify(process.argv.slice(1))} cwd=${process.cwd()} HOME=${process.env.QLOGICAGENT_HOME??"(unset)"} NODE=${process.version}`);var dT=sT(process.argv),
|
|
1121
|
+
`;Buffer.byteLength(n,"utf-8")<=fe&&await this.writeIndex(n)}};function cU(t,e){let r=tt(t,"..");Ct(r)||tT(r,{recursive:!0}),tU(t,e,"utf-8")}function lU(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function nT(){return{getRootPath(t){return cu(t)},create(t){return new Yi(t)}}}var uU=dU(import.meta.url);function pU(){for(let t of["../package.json","../../package.json"])try{return uU(t).version}catch{}return"0.0.0"}var oT=pU();var mU=new Set(["thread.user_response","tool.approval.response"]);var Ji=class{running=!1;startedAt=Date.now();packageVersion=oT;rpcContract=new In;rpcIds=new Map;rpcDeadlineTimers=new Map;activeTurn=null;turnDone=Promise.resolve();verbose;transport;registry;mediaClient;agent=null;lastLlmConfigKey="";currentSessionId="";currentTurnId="";currentHooks=null;mcpManager=null;mcpReady=Promise.resolve();pluginLoader=null;permissionChecker=null;permissionUnregister=null;currentTransport=null;currentApiKey="";currentModel="";currentProvider="";currentBaseUrl="";sessionState=null;currentMediaApiKeys=null;taskStore=new Uo;mediaPersistence=new qo;pathService;toolCatalog=sS();memoryPrefetchState=ht();memoryProvider=null;memoryDreamProvider=null;memoryUserId="";lastUserMessageForAutoExtract;lastAssistantMessageForExtract;memdir=null;projectMemoryStoreFactory=nT();fileWatcher=null;pendingAskUser=new Map;sessionTaskDomain;multiAgentHandlerHost;acpServer=null;sessionHistory=new Wi;idleDreamCoordinator;petRuntime;petConfirmCoordinator;modelRegistryHydration=null;constructor(e){this.verbose=e.verbose,this.registry=new Su,this.mediaClient=new Ru({registry:this.registry}),this.pathService=new wi(this.mediaPersistence),this.petRuntime=Jw({getActiveProjectRoot:()=>this.getActiveProjectRoot(),resolveClientForPurpose:r=>this.resolveClientForPurpose(r),sendNotification:(r,n)=>this.sendNotification(r,n)}),this.petConfirmCoordinator=new Ki({getPermissionResolver:()=>this.permissionChecker,sendNotification:(r,n)=>this.sendNotification(r,n)}),this.multiAgentHandlerHost=Fw({getActiveProjectRoot:()=>this.getActiveProjectRoot(),emitAgentStatus:(r,n,o)=>this.emitAgentStatus(r,n,o),handleMcpToolCall:(r,n,o)=>this.handleMcpToolCall(r,n,o),log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),sendResponse:(r,n,o)=>this.sendResponse(r,n,o)}),this.idleDreamCoordinator=new Gi({log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n),getCurrentSessionId:()=>this.currentSessionId,getCurrentTurnCount:()=>this.sessionState?.turnCount??0,getActiveTurn:()=>this.activeTurn,resolveDreamClient:()=>this.resolveClientForPurpose("textGeneration"),getAgentHome:()=>F(),listRecentSessions:()=>Dt(20,this.getActiveProjectRoot()),runDream:r=>Yr.call(this.createDreamHandlerHost(),r)}),M().onChange(()=>{this.lastLlmConfigKey=""}),this.ensureModelRegistryHydrated().catch(()=>{}),this.idleDreamCoordinator.applyEnvOverrides(process.env),this.transport=e.transport??new Ur({verbose:e.verbose}),this.taskStore.onTaskChange((r,n)=>{n&&this.sendNotification("task.updated",{taskId:r,type:n.type,lifecycle:n.lifecycle,label:n.label})}),iS({verbose:e.verbose,log:r=>this.log(r),sendNotification:(r,n)=>this.sendNotification(r,n)})}getActiveProjectRoot(){return this.pathService.getActiveProjectRoot()}async ensureModelRegistryHydrated(){return this.modelRegistryHydration||(this.modelRegistryHydration=(async()=>{let e=M();e.load(),await Cn(e),e.save()})().catch(e=>{this.modelRegistryHydration=null;let r=e instanceof Error?e.message:String(e);throw this.log(`[model-registry] failed to refresh llmrouter catalog: ${r}`),e})),this.modelRegistryHydration}syncToolListMediaConfig(){ci({host:this,config:void 0,turnId:this.currentTurnId||"tools-list"})}setActiveWorkdir(e){this.pathService.setActiveWorkdir(e)}start(){this.running=!0,this.log("qlogicagent started, waiting for JSON-RPC messages..."),this.transport.onMessage(e=>{if(this.acpServer){if(nc(e)||_n(e)){this.acpServer.dispatchMessage(e);return}if(En(e)){let r=e.method;if(r==="initialize"||r.startsWith("session/")||r.startsWith("x/")||r.startsWith("fs/")){this.acpServer.dispatchMessage(e);return}}}if(!tc(e)){this.log("[warn] ignoring non-request message");return}this.handleMessage(e)}),this.transport.onClose(()=>{this.log("transport closed, shutting down"),this.stop()}),this.transport.start()}async stop(){if(this.running){this.running=!1,this.cancelIdleDreamTimer();for(let e of this.rpcDeadlineTimers.values())clearTimeout(e);this.rpcDeadlineTimers.clear(),this.rpcIds.clear(),this.currentSessionId&&this.currentHooks&&(this.currentHooks.invoke("stop",{sessionId:this.currentSessionId,reason:"shutdown"}).catch(()=>{}),this.currentHooks.invoke("session.ended",{sessionId:this.currentSessionId}).catch(()=>{}));try{if(await cp(),this.fileWatcher&&(this.fileWatcher.stop(),this.fileWatcher=null),this.mcpManager){let e=this.mcpManager;this.mcpManager=null,await e.disconnectAll()}this.permissionUnregister&&(this.permissionUnregister(),this.permissionUnregister=null),this.closeMemoryProviders(),this.activeTurn&&(this.activeTurn.abort(),this.activeTurn=null),this.transport.close()}catch(e){this.currentSessionId&&this.currentHooks&&this.currentHooks.invoke("stop.failed",{sessionId:this.currentSessionId,reason:"cleanup_error",error:e.message}).catch(()=>{})}this.log("stopped")}}methodHandlers=rR(this);handleMessage(e){if(e.id!==void 0&&!mU.has(e.method)){let n=Go(e);if(!n.ok){this.sendContractError(e.id,n.error);return}let o=this.rpcContract.begin(e.method,n.meta);if(o.status==="rejected"){this.sendContractError(e.id,o.error);return}if(o.status==="deduped"){this.sendContractErrorOrResult(e.id,o.result,o.error);return}this.rpcIds.set(e.id,n.meta),this.scheduleRpcDeadline(e.id,e.method,n.meta)}let r=this.methodHandlers.get(e.method);r?r(e):e.id!==void 0&&this.sendResponse(e.id,void 0,{code:y.METHOD_NOT_FOUND,message:`Unknown method: ${e.method}`})}ensureDefaultProject(){this.memdir=Xw({pathService:this.pathService,projectMemoryStoreFactory:this.projectMemoryStoreFactory,sendNotification:(e,r)=>this.sendNotification(e,r)})}resolveClientForPurpose(e){return Bw({purpose:e,providerRegistry:this.registry,currentProvider:this.currentProvider,currentTransport:this.currentTransport})}ensureMemoryProvider(){if(this.memoryProvider)return;let e=Kd(this.getActiveProjectRoot(),this.memoryUserId);this.memoryProvider=e.handlerProvider,this.memoryDreamProvider=e.dreamProvider,this.memoryUserId=e.userId}resolveAgent(e){let r=Hw(e,g=>this.log(g));if(!r)return null;let{provider:n,model:o,apiKey:s,baseUrl:i,configKey:a}=r;if(this.agent&&this.lastLlmConfigKey===a)return e.model=o,e.provider=n,e.apiKey=s,i&&(e.baseUrl=i),this.agent;e.model=o,e.provider=n,e.apiKey=s,i&&(e.baseUrl=i);let c={info:g=>this.log(g),warn:g=>this.log(`[warn] ${g}`),error:g=>this.log(`[error] ${g}`),debug:g=>{this.verbose&&this.log(`[debug] ${g}`)}},l=Lw({mediaPersistence:this.mediaPersistence,getSessionId:()=>this.currentSessionId,log:g=>this.log(g),sendNotification:(g,f)=>this.sendNotification(g,f)}),d=qw({resolvedConfig:r,providerRegistry:this.registry,sessionId:this.currentSessionId}),u=Dw({config:e,log:c,taskStore:this.taskStore,sessionId:this.currentSessionId??"",getTurnId:()=>this.currentTurnId,projectRoot:this.getActiveProjectRoot(),memdir:this.memdir,currentUserId:this.memoryUserId,memoryPrefetchState:this.memoryPrefetchState,getLastUserMessage:()=>this.lastUserMessageForAutoExtract,getLastAssistantMessage:()=>this.lastAssistantMessageForExtract,resolveSmallModelClient:()=>this.resolveClientForPurpose("smallModel"),agentClient:d,toolCatalog:this.toolCatalog,currentMcpManager:this.mcpManager,setMcpManager:g=>{this.mcpManager=g},setMcpReady:g=>{this.mcpReady=g},setPluginLoader:g=>{this.pluginLoader=g},getPluginSkills:()=>this.pluginLoader?.getPluginSkills()??[],getAgent:()=>this.agent,getAcpPermissionSession:()=>this.acpServer?.sessionId?{sessionId:this.acpServer.sessionId,requestPermission:g=>this.acpServer.requestPermission(g)}:void 0,sendNotification:(g,f)=>this.sendNotification(g,f),isPetActive:()=>this.petRuntime.isActive(),currentPermissionUnregister:this.permissionUnregister,coreToolHost:{getAgent:()=>this.agent,getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),getVerbose:()=>this.verbose,sendNotification:(g,f)=>this.sendNotification(g,f),emitAgentStatus:(g,f,h)=>this.emitAgentStatus(g,f,h),handleMcpToolCall:(g,f,h)=>this.handleMcpToolCall(g,f,h)},toolInvoker:l,currentFileWatcher:this.fileWatcher,setFileWatcher:g=>{this.fileWatcher=g}}),p=u.hooks;this.currentHooks=p,this.memoryProvider=u.memoryHandlerProvider,this.memoryDreamProvider=u.memoryDreamProvider,this.memoryUserId=u.memoryUserId,this.permissionChecker=u.permissionChecker,this.permissionUnregister=u.permissionUnregister;let m=Ww({client:d,toolInvoker:l,log:c,hooks:p,maxRounds:e.maxRounds,verbose:this.verbose,projectRoot:this.getActiveProjectRoot()});return this.agent=m.agent,this.lastLlmConfigKey=a,this.currentTransport=m.transport,this.currentApiKey=m.apiKey,this.currentModel=m.model,this.currentProvider=m.provider,this.currentBaseUrl=m.baseUrl,this.log(`created Agent (provider: ${n}, model: ${o})`),this.agent}emitAgentStatus(e,r,n){this.sendNotification("agents.status",Kw(e,r,n))}createDreamHandlerHost(){return zw({getActiveTurn:()=>this.activeTurn,setActiveTurn:e=>{this.activeTurn=e},getCurrentTransport:()=>this.currentTransport,getCurrentApiKey:()=>this.currentApiKey,getCurrentModel:()=>this.currentModel,getCurrentHooks:()=>this.currentHooks,getMemoryProvider:()=>this.memoryDreamProvider,getMemoryUserId:()=>this.memoryUserId,getVerbose:()=>this.verbose,log:e=>this.log(e),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n)})}createAcpExtendedHandlerHost(){return Qw({dreamHost:this.createDreamHandlerHost(),multiAgentHost:this.multiAgentHandlerHost,getCurrentSessionId:()=>this.currentSessionId,getActiveProjectRoot:()=>this.getActiveProjectRoot(),log:e=>this.log(e),resolveAgent:e=>this.resolveAgent(e),sendNotification:(e,r)=>this.sendNotification(e,r),sendResponse:(e,r,n)=>this.sendResponse(e,r,n),emitAgentStatus:(e,r,n)=>this.emitAgentStatus(e,r,n),handleMcpToolCall:(e,r,n)=>this.handleMcpToolCall(e,r,n),resolveClientForPurpose:e=>this.resolveClientForPurpose(e)})}async handleMcpToolCall(e,r,n){return Gw({toolCatalog:this.toolCatalog,memberId:e,toolName:r,args:n})}sendResponse(e,r,n){let o=this.rpcIds.get(e);if(o){let i=this.rpcContract.settle(o.requestId,r,n);if(this.clearRpcLifecycle(e),!i.accepted){this.log(`[rpc] dropped late response id=${String(e)} requestId=${o.requestId} reason=${i.reason}`);return}}let s={jsonrpc:"2.0",id:e};n?s.error=n:s.result=r,this.writeStdout(s)}sendContractError(e,r){let n={jsonrpc:"2.0",id:e,error:r};this.writeStdout(n)}sendContractErrorOrResult(e,r,n){if(n){this.sendContractError(e,n);return}let o={jsonrpc:"2.0",id:e,result:r};this.writeStdout(o)}scheduleRpcDeadline(e,r,n){let o=Math.max(0,n.deadlineAt-Date.now()),s=setTimeout(()=>{if(!this.rpcIds.has(e))return;let i=this.rpcContract.expire(n.requestId);this.clearRpcLifecycle(e),i&&(this.log(`[rpc] deadline exceeded method=${r} id=${String(e)} requestId=${n.requestId}`),this.writeStdout({jsonrpc:"2.0",id:e,error:{code:y.REQUEST_DEADLINE_EXCEEDED,message:`RPC request deadline exceeded: ${r}.`}}))},o);s.unref?.(),this.rpcDeadlineTimers.set(e,s)}clearRpcLifecycle(e){let r=this.rpcDeadlineTimers.get(e);r&&clearTimeout(r),this.rpcDeadlineTimers.delete(e),this.rpcIds.delete(e)}sendNotification(e,r){if(this.acpServer&&this.acpServer.sessionId)Ip(this.acpServer,this.acpServer.sessionId,e,r);else{let n={jsonrpc:"2.0",method:e,params:r};this.writeStdout(n)}this.idleDreamCoordinator.handleTurnNotification(e)}writeStdout(e){this.transport.send(e)}log(e){this.verbose&&process.stderr.write(`${JSON.stringify({ts:new Date().toISOString(),level:"info",service:"qlogicagent",message:e})}
|
|
1122
|
+
`)}enableIdleDream(e){this.idleDreamCoordinator.enable(e)}cancelIdleDreamTimer(){this.idleDreamCoordinator.cancelTimer()}disposeSessionRuntime(){this.permissionUnregister&&(this.permissionUnregister(),this.permissionUnregister=null),this.closeMemoryProviders(),this.agent=null,this.currentHooks=null,this.lastLlmConfigKey="",this.memoryPrefetchState=ht()}closeMemoryProviders(){let e=new Set;for(let r of[this.memoryProvider,this.memoryDreamProvider]){if(!r||e.has(r))continue;e.add(r);let n=r.close;if(typeof n=="function")try{n.call(r)}catch{}}this.memoryProvider=null,this.memoryDreamProvider=null}initAcpServer(){let e=DR(this,oT,this.createAcpExtendedHandlerHost());this.acpServer=new zo(this.transport,e,{verbose:this.verbose})}getAcpServer(){return this.acpServer}};function sT(t){let e={verbose:!1};for(let r of t.slice(2))(r==="--verbose"||r==="-v")&&(e.verbose=!0);return e}import{writeFileSync as gU,appendFileSync as aT,mkdirSync as fU}from"node:fs";import{join as lu}from"node:path";import{homedir as hU}from"node:os";var cT=lu(process.env.QLOGICAGENT_HOME||lu(hU(),".qlogicagent"),"debug-logs");try{fU(cT,{recursive:!0})}catch{}var du=lu(cT,"acp-session.log");try{gU(du,"")}catch{}function rt(t){let e=`[${new Date().toISOString()}] ${t}
|
|
1123
|
+
`;lT.call(process.stderr,e);try{aT(du,e)}catch{}}var lT=process.stderr.write.bind(process.stderr);process.stderr.write=((t,...e)=>{let r=typeof t=="string"?t:Buffer.from(t).toString();try{aT(du,r)}catch{}return lT(t,...e)});rt(`PID=${process.pid} argv=${JSON.stringify(process.argv.slice(1))} cwd=${process.cwd()} HOME=${process.env.QLOGICAGENT_HOME??"(unset)"} NODE=${process.version}`);var dT=sT(process.argv),yU=!process.argv.includes("--no-acp"),bU=new Ur({verbose:dT.verbose}),uu=new Ji({verbose:dT.verbose,transport:bU});yU&&(uu.initAcpServer(),rt("ACP server initialized, waiting for messages"));process.on("unhandledRejection",t=>{rt(`unhandledRejection: ${t instanceof Error?t.stack??t.message:String(t)}`)});process.on("uncaughtException",t=>{rt(`uncaughtException: ${t.stack??t.message}`)});process.stdin.on("end",()=>{rt("stdin END received")});process.stdin.on("close",()=>{rt("stdin CLOSE received")});process.stdout.on("error",t=>{rt(`stdout ERROR: ${t.message}`)});process.stdout.on("close",()=>{rt("stdout CLOSE")});process.on("exit",t=>{rt(`process.exit code=${t}`)});var iT=!1;async function uT(t){if(!iT){iT=!0,rt(`${t} received`);try{await uu.stop()}finally{process.exit(0)}}}process.on("SIGTERM",()=>{uT("SIGTERM")});process.on("SIGINT",()=>{uT("SIGINT")});process.on("SIGHUP",()=>{rt("SIGHUP received")});rt("calling server.start()");uu.start();rt("server.start() returned, event loop active");
|