@whoz-oss/coday-server 0.105.0 → 0.105.2

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/server.js +4 -4
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whoz-oss/coday-server",
3
- "version": "0.105.0",
3
+ "version": "0.105.2",
4
4
  "repository": "https://github.com/whoz-oss/coday",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
package/server.js CHANGED
@@ -874,7 +874,7 @@ Are you sure you want to delete this MCP server configuration?
874
874
 
875
875
  Here are the information collected during previous chats:
876
876
  `),n.join(`
877
- `)):""}loadMemoriesFrom(e){this.memories=[],this.userMemoriesPath=this.readMemories(this.userMemoriesPath)?this.userMemoriesPath:void 0;let t=e?.configPath?tE.join(e.configPath,xM):void 0;this.projectMemoriesPath=this.readMemories(t)?t:void 0,e&&this.checkInit()}readMemories(e){if(!e)return!1;try{if(!Hit(e)){let n=kfe.stringify({memories:[]});Wit(e,n)}let t=ta(e);return t?(this.memories.push(...t.memories),!0):!1}catch{return!1}}checkInit(){if(!this.userMemoriesPath||!this.projectMemoriesPath)throw new Error("user or project path not set for memory service")}saveMemories(){this.checkInit();let e=this.memories.filter(n=>n.level==="USER"),t=this.memories.filter(n=>n.level==="PROJECT");Mn(this.userMemoriesPath,{memories:e}),Mn(this.projectMemoriesPath,{memories:t})}};import*as Cfe from"crypto";import*as Va from"node:fs/promises";import*as Fc from"path";var xm=class r{constructor(e,t,n){this.repository=e;this.defaultProject=t;this.isForcedMode=n}maskingService=new B2;listProjects(){let e=this.repository.listProjects();return this.isForcedMode&&this.defaultProject?e.filter(t=>t===this.defaultProject).map(t=>{let n=this.repository.getConfig(t);return{name:t,volatile:n?.volatile}}):e.map(t=>{let n=this.repository.getConfig(t);return{name:t,volatile:n?.volatile}})}getDefaultProject(){return this.defaultProject||null}getForcedMode(){return this.isForcedMode}getProject(e){this.checkAgainstForced(e);let t=this.repository.getConfig(e);if(t)return{name:e,config:t};if(!this.isForcedMode&&this.defaultProject){let n=process.cwd(),i=r.generateProjectId(n),a=Fc.basename(n);if(e===a||e===i||e===this.defaultProject){console.log(`[PROJECT_SERVICE] Creating volatile project for '${e}' at ${n}`);let o=this.getOrCreateVolatileProject(n);if(t=this.repository.getConfig(o),t)return{name:o,config:t}}}return null}exists(e){return this.checkAgainstForced(e),this.repository.exists(e)}createProject(e,t){if(this.checkAgainstForced(e),!e||!t)throw new Error("Project name and path are required");if(!this.repository.createProject(e,t))throw new Error(`Project '${e}' already exists`)}updateProjectConfig(e,t){if(this.checkAgainstForced(e),!this.repository.exists(e))throw new Error(`Project '${e}' does not exist`);this.repository.saveConfig(e,t)}deleteProject(e){if(this.checkAgainstForced(e),!this.repository.deleteProject(e))throw new Error(`Project '${e}' does not exist`)}getProjectConfigForClient(e){this.checkAgainstForced(e);let t=this.repository.getConfig(e);return t?this.maskingService.maskConfig(t):null}updateProjectConfigFromClient(e,t){this.checkAgainstForced(e);let n=this.repository.getConfig(e);if(!n)throw new Error(`Project '${e}' does not exist`);let i=this.maskingService.unmaskConfig(t,n);this.repository.saveConfig(e,i)}checkAgainstForced(e){if(this.isForcedMode&&this.defaultProject&&this.defaultProject!==e)throw Error(`Project selection outside of ${this.defaultProject} not allowed`)}getOrCreateVolatileProject(e){let t=r.generateProjectId(e);if(this.repository.exists(t))return t;this.repository.createProject(t,e);let n=this.repository.getConfig(t);return n&&(n.volatile=!0,n.createdAt=Date.now(),this.repository.saveConfig(t,n)),t}async registerWorktreeProject(e,t,n){let i=this.repository.getConfig(n),a=i?{...i,path:t,volatile:void 0,createdAt:void 0}:{version:1,path:t,integration:{},storage:{type:"file"},agents:[]};this.repository.createProject(e,t),this.repository.saveConfig(e,a);let o=this.repository.getProjectInfo(n);if(o){let s=this.repository.getProjectInfo(e);if(s)for(let c of["agents","prompts","schedulers","memories"]){let u=Fc.join(o.configPath,c),l=Fc.join(s.configPath,c);try{await Va.access(u),await Va.symlink(u,l)}catch{}}}}async unregisterWorktreeProject(e){let t=this.repository.getProjectInfo(e);if(!t)return;let n=e.lastIndexOf("__");if(n!==-1){let i=e.substring(0,n),a=this.repository.getProjectInfo(i);a&&await this.migrateThreadsToParent(t.configPath,a.configPath)}await Va.rm(t.configPath,{recursive:!0,force:!0})}async migrateThreadsToParent(e,t){let n=Fc.join(e,"threads"),i=Fc.join(t,"threads");try{await Va.access(n)}catch{return}await Va.mkdir(i,{recursive:!0});let a=await Va.readdir(n);for(let o of a){let s=Fc.join(n,o),c=Fc.join(i,o);try{await Va.access(c)}catch{await Va.rename(s,c)}}}static generateProjectId(e){let t=Fc.basename(e),n=Cfe.createHash("sha256").update(e).digest("hex").substring(0,8);return`${t}_${n}`}};var Dfe=ur(po(),1);import*as wm from"node:path";import*as Pfe from"node:os";import{mkdirSync as Vit}from"fs";var Git="projects",Tfe="project.yaml",_m=class{constructor(e,t,n){this.interactor=e;this.projectService=t;let i=wm.join(Pfe.userInfo().homedir,".coday");this.projectsConfigPath=wm.join(n??i,Git),Vit(this.projectsConfigPath,{recursive:!0}),this.projects=this.projectService.listProjects().map(a=>a.name)}projectsConfigPath;maskingService=new B2;projects;selectedProjectBehaviorSubject=new Dfe.BehaviorSubject(null);selectedProject$=this.selectedProjectBehaviorSubject.asObservable();selectProject(e){let t=wm.join(this.projectsConfigPath,e),n=wm.join(t,Tfe),i=this.projectService.getProject(e)?.config;if(!i?.path){console.log(`[PROJECT_STATE_SERVICE] ERROR: No project path in config for '${e}'`),this.interactor.error("Invalid selection, project path needed \u{1F622}.");return}let o={name:e,config:i,configPath:t};console.log(`[PROJECT_STATE_SERVICE] Selected '${e}' \u2192 ${i.path}`),this.updateSelectedProject(o),this.interactor.displayText(`Project local configuration used: ${n}`)}updateSelectedProject(e){this.selectedProjectBehaviorSubject.next(e)}get selectedProject(){return this.selectedProjectBehaviorSubject.value}save(e){let t=this.selectedProjectBehaviorSubject.value;if(!t){this.interactor.error("No current project selected, save not possible");return}let n={...t.config,...e};Mn(wm.join(t.configPath,Tfe),n),t.config=n,this.updateSelectedProject(t)}getConfigForClient(){let e=this.selectedProjectBehaviorSubject.value;return e?this.maskingService.maskConfig(e.config):null}updateConfigFromClient(e){let t=this.selectedProjectBehaviorSubject.value;if(!t){this.interactor.error("No current project selected, update not possible");return}let n=this.maskingService.unmaskConfig(e,t.config);this.save(n)}};import*as Gu from"node:path";import*as $fe from"node:os";import{randomUUID as Jit}from"node:crypto";import{existsSync as W2,mkdirSync as Kit,readdirSync as Ofe,unlinkSync as Yit}from"fs";import*as wM from"node:path";import*as Ife from"node:os";function Zit(r){return r.replace(/[^a-zA-Z0-9]/g,"_")}function Sm(r,e){try{let t=wM.join(Ife.userInfo().homedir,".coday"),n=Zit(r),i=wM.join(e??t,"users",n,"user.yaml"),a=ta(i);return a?a.groups?.includes("CODAY_ADMIN")??!1:!1}catch{return!1}}var rE=class{codayConfigDir;projectService;nativeHandlerStubs=[];constructor(e,t){let n=Gu.join($fe.userInfo().homedir,".coday");this.codayConfigDir=e??n,this.projectService=t}getProjectPath(e){if(this.projectService)return this.projectService.getProject(e)?.config.path}async getOrCreatePromptsDir(e,t){let n;if(t==="local")n=Gu.join(this.codayConfigDir,"projects",e,"prompts");else{let i=this.getProjectPath(e);if(!i)throw new Error("Project path not configured, cannot access project prompts");let a=await f2({text:"coday.yaml",root:i});if(a.length===0)throw new Error(`coday.yaml not found in project path: ${i}`);let o=Gu.dirname(a[0]);n=Gu.join(i,o,"prompts")}return W2(n)||(Kit(n,{recursive:!0}),console.log(`[PROMPT] Created prompts directory: ${n}`)),n}async getOrCreatePromptFilePath(e,t,n){let i=await this.getOrCreatePromptsDir(e,n);return Gu.join(i,`${t}.yml`)}async findPromptSource(e,t){let n=await this.getOrCreatePromptFilePath(e,t,"local");if(W2(n))return"local";if(this.projectService)try{let i=await this.getOrCreatePromptFilePath(e,t,"project");if(W2(i))return"project"}catch{}return null}async findProjectForPrompt(e){let t=Gu.join(this.codayConfigDir,"projects");if(!W2(t))return null;let n=Ofe(t,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of n){let a=Gu.join(this.codayConfigDir,"projects",i,"prompts",`${e}.yml`);if(W2(a))return i;if(this.projectService)try{let o=await this.getOrCreatePromptFilePath(i,e,"project");if(W2(o))return i}catch{}}return null}validatePlaceholders(e){let t=/\{\{(\w+)\}\}/g,n=[],i=/^[A-Za-z][A-Za-z0-9-]*$/;if(e.forEach(a=>{let o;for(;(o=t.exec(a))!==null;){let s=o[1];s&&s!=="PARAMETERS"&&!i.test(s)&&n.push(s)}}),n.length>0)throw new Error(`Invalid parameter keys: ${n.join(", ")}. Keys must start with a letter and contain only letters, digits, and hyphens.`)}async create(e,t,n="local"){try{this.validatePlaceholders(t.commands);let i=Jit(),a={...t,id:i,source:n,createdAt:new Date().toISOString(),parameterFormat:this.getParameterFormat(t.commands)},o=await this.getOrCreatePromptFilePath(e,i,n);if(W2(o))throw new Error(`Prompt with ID ${i} already exists`);return Mn(o,a),console.log(`[PROMPT] Created prompt ${i} in ${n} for project ${e}`),a}catch(i){throw new Error(`Failed to create prompt: ${i instanceof Error?i.message:"Unknown error"}`)}}async get(e,t){try{let n=await this.findPromptSource(e,t);if(!n)return null;let i=await this.getOrCreatePromptFilePath(e,t,n),a=ta(i);return a?(a.source||(a.source=n),a):null}catch(n){return console.error(`Failed to get prompt ${t}:`,n),null}}async getById(e){try{let t=await this.findProjectForPrompt(e);if(!t)return null;let n=await this.get(t,e);return n?{prompt:n,projectName:t}:null}catch(t){return console.error(`Failed to get prompt ${e}:`,t),null}}async update(e,t,n,i){try{let a=await this.get(e,t);if(!a)return null;if(n.webhookEnabled!==void 0&&n.webhookEnabled!==a.webhookEnabled&&!Sm(i,this.codayConfigDir))throw new Error("Only CODAY_ADMIN can enable/disable webhook for prompts");let{id:o,createdAt:s,source:c,...u}=n;n.commands&&this.validatePlaceholders(n.commands);let l={...a,...u,updatedAt:new Date().toISOString()};n.commands&&(l.parameterFormat=this.getParameterFormat(n.commands));let f=await this.getOrCreatePromptFilePath(e,t,a.source);return Mn(f,l),console.log(`[PROMPT] Updated prompt ${t} (${a.source}) by user ${i}`),l}catch(a){throw console.error(`Failed to update prompt ${t}:`,a),a}}async delete(e,t){try{let n=await this.findPromptSource(e,t);if(!n)return!1;let i=await this.getOrCreatePromptFilePath(e,t,n);return Yit(i),console.log(`[PROMPT] Deleted prompt ${t} from ${n}`),!0}catch(n){return console.error(`Failed to delete prompt ${t}:`,n),!1}}getParameterFormat(e){if(e.some(a=>/\{\{PARAMETERS\}\}/.test(a)))return"";let n=/\{\{(\w+)\}\}/g,i=new Set;return e.forEach(a=>{let o;for(;(o=n.exec(a))!==null;){let s=o[1];s&&s!=="PARAMETERS"&&i.add(s)}}),i.size===0?"":Array.from(i).map(a=>`${a}=""`).join(" ")}registerNativeHandler(e){this.nativeHandlerStubs.find(t=>t.id===e.id)||this.nativeHandlerStubs.push(e)}async list(e,t=[]){try{let n=[],i=["local"];this.projectService&&i.push("project");for(let a of i)try{let o=await this.getOrCreatePromptsDir(e,a);if(!W2(o))continue;let c=Ofe(o).filter(u=>u.endsWith(".yml"));for(let u of c){let l=u.replace(".yml",""),f=await this.get(e,l);f&&n.push({id:f.id,name:f.name,description:f.description,webhookEnabled:f.webhookEnabled,createdBy:f.createdBy,createdAt:f.createdAt,updatedAt:f.updatedAt,source:f.source||a,parameterFormat:f.parameterFormat})}}catch(o){console.log(`[PROMPT] Could not access ${a} prompts for ${e}:`,o)}return n.push(...E0),n.push(...this.nativeHandlerStubs),n.push(...t),n.sort((a,o)=>new Date(o.createdAt).getTime()-new Date(a.createdAt).getTime())}catch(n){return console.error(`Failed to list prompts for project ${e}:`,n),[]}}async enableWebhook(e,t,n){return this.update(e,t,{webhookEnabled:!0},n)}async disableWebhook(e,t,n){return this.update(e,t,{webhookEnabled:!1},n)}};var jfe=ur(po(),1),nE=class{constructor(e){this.promptService=e}threadCodayManager;threadService;codayOptions;logger;initialize(e,t,n,i){this.threadCodayManager=e,this.threadService=t,this.codayOptions=n,this.logger=i}processCommands(e,t){let n;if(typeof t=="string"){let a=e.some(s=>/\{\{PARAMETERS\}\}/.test(s));if(e.some(s=>/\{\{(?!PARAMETERS\}\})\w+\}\}/.test(s)))throw new Error("Prompt contains structured placeholders ({{key}}). Use an object parameter instead of a string.");a?n=e.map(s=>s.replace(/\{\{PARAMETERS\}\}/g,t)):n=e.map((s,c)=>c===0?`${s} ${t}`.trim():s)}else typeof t=="object"&&t!==null?n=e.map(a=>{let o=a;return Object.entries(t).forEach(([s,c])=>{let u=`{{${s}}}`;o=o.replaceAll(u,String(c))}),o}):n=[...e];let i=new Set;if(n.forEach(a=>{let o=a.match(/\{\{(\w+)\}\}/g);o&&o.forEach(s=>i.add(s))}),i.size>0){let a=Array.from(i).map(o=>o.replace(/[{}]/g,"")).join(", ");throw new Error(`Missing required parameters: ${a}`)}return n}async executePrompt(e,t,n,i,a){if(!this.threadCodayManager||!this.threadService||!this.codayOptions||!this.logger)throw new Error("PromptExecutionService not initialized. Call initialize() first.");let{title:o,awaitFinalAnswer:s=!1,projectName:c}=a||{},u,l;if(c){if(l=c,u=await this.promptService.get(l,e),!u)throw new Error(`Prompt ${e} not found in project ${l}`)}else{let y=await this.promptService.getById(e);if(!y)throw new Error(`Prompt not found: ${e}`);u=y.prompt,l=y.projectName}if(i==="webhook"&&!u.webhookEnabled)throw new Error(`Prompt ${e} is not enabled for webhook execution`);if(!u.commands||u.commands.length===0)throw new Error("Prompt has no commands configured");let f=this.processCommands(u.commands,t);if(!n)throw new Error("Username is required");let d=(await this.threadService.createThread(l,n,o)).id;console.log(`[PROMPT_EXEC] Created new thread: ${d} for ${i} execution`);let m={...this.codayOptions,oneshot:!0,project:l,thread:d,prompts:f};console.log(`[PROMPT_EXEC] Creating instance for ${i} execution with ${f.length} prompts:`,f);let h=this.threadCodayManager.createWithoutConnection(d,l,n,m);h.prepareCoday();let g=h.coday.interactor,v={project:l,title:o??"Untitled",username:n,clientId:d,promptCount:f.length,awaitFinalAnswer:!!s,promptName:u.name,promptId:u.id,executionMode:i};if(i==="webhook"?this.logger.logWebhook(v):this.logger.logWebhook({...v,webhookName:u.name,webhookUuid:u.id}),s){let y=[],x=g.events.pipe((0,jfe.filter)(k=>(console.log(`[PROMPT_EXEC] Received event type: ${k.type}, role: ${k instanceof $t?k.role:"N/A"}`),k instanceof $t&&k.role==="assistant"&&!!k.name))).subscribe(k=>{y.push(k)});try{await h.coday.run(),x.unsubscribe();let k=y[y.length-1];return await this.threadCodayManager.cleanup(d),{threadId:d,lastEvent:k}}catch(k){x.unsubscribe();let S=k instanceof Error?k.message:"Unknown error";throw this.logger.logWebhookError({error:`Prompt execution failed: ${S}`,username:n,project:l,clientId:d}),console.error("[PROMPT_EXEC] Error waiting for prompt completion:",k),await this.threadCodayManager.cleanup(d),k}}else return h.coday.run().catch(y=>{console.error("[PROMPT_EXEC] Error during prompt Coday run:",y)}),setTimeout(()=>{this.threadCodayManager.cleanup(d).catch(y=>{console.error("[PROMPT_EXEC] Error cleaning up prompt thread after timeout:",y)})},300*1e3),{threadId:d}}};var X6=ur(Pc(),1);import*as ai from"fs";import*as Em from"path";import{randomUUID as Xit}from"node:crypto";var iE=class{constructor(e,t,n){this.logger=e;this.promptService=t;this.codayConfigDir=n}schedulers=new Map;checkInterval;CHECK_INTERVAL_MS=3e4;promptExecutionService;initializeExecution(e){this.promptExecutionService=e}async initialize(){console.log("[SCHEDULER] Initializing SchedulerService..."),await this.loadAllSchedulers(),this.startScheduler(),console.log(`[SCHEDULER] SchedulerService initialized with ${this.schedulers.size} schedulers`)}stop(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=void 0,console.log("[SCHEDULER] SchedulerService stopped"))}async loadAllSchedulers(){this.schedulers.clear();let e=Em.join(this.codayConfigDir,"projects");if(!ai.existsSync(e))return;let t=ai.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name);for(let n of t)try{let i=await this.loadProjectSchedulers(n);for(let a of i)this.schedulers.set(a.id,a)}catch(i){console.error(`[SCHEDULER] Failed to load schedulers for project ${n}:`,i)}}async loadProjectSchedulers(e){let t=this.getSchedulersDir(e);if(!ai.existsSync(t))return[];let n=ai.readdirSync(t),i=[];for(let a of n)if(a.endsWith(".yml"))try{let o=Em.join(t,a),s=ai.readFileSync(o,"utf-8"),c=X6.parse(s),u=this.calculateNextRunSkippingMissed(c),l=u.occurrenceCount!==c.occurrenceCount;c.nextRun=u.nextRun,c.occurrenceCount=u.occurrenceCount,l&&await this.saveScheduler(c,e),i.push(c)}catch(o){console.error(`[SCHEDULER] Failed to load scheduler from ${a}:`,o)}return i}startScheduler(){this.checkInterval=setInterval(()=>{this.checkAndExecuteSchedulers()},this.CHECK_INTERVAL_MS),this.checkAndExecuteSchedulers()}async checkAndExecuteSchedulers(){for(let e of this.schedulers.values())e.enabled&&yce(e.schedule,e.nextRun??null,e.occurrenceCount??0)&&this.executeScheduler(e).catch(t=>{console.error(`[SCHEDULER] Failed to execute scheduler ${e.id}:`,t)})}async executeSchedulerInternal(e,t,n){if(!this.promptExecutionService)throw new Error("PromptExecutionService not initialized");console.log(`[SCHEDULER] Executing scheduler "${e.name}" (${e.id}) [${n}]`);let i=e.parameters;e.parameters&&typeof e.parameters=="object"&&Object.keys(e.parameters).length===1&&"PARAMETERS"in e.parameters&&(i=String(e.parameters.PARAMETERS));let a=await this.promptExecutionService.executePrompt(e.promptId,i,e.createdBy,"scheduled",{title:n==="scheduled"?`Scheduled: ${e.name}`:`Manual: ${e.name}`,awaitFinalAnswer:!1,projectName:t});return console.log(`[SCHEDULER] Scheduler "${e.name}" executed successfully. Thread: ${a.threadId}`),a.threadId}async executeScheduler(e){let t=new Date().toISOString();console.log(`[SCHEDULER] Executing scheduler "${e.name}" (${e.id})`);let n=this.findProjectForScheduler(e.id);if(!n){console.error(`[SCHEDULER] Cannot find project for scheduler ${e.id}, skipping execution`);return}let i,a,o;e.lastRun=t,e.occurrenceCount=(e.occurrenceCount??0)+1,e.nextRun=lh(e.schedule,new Date,e.occurrenceCount);try{await this.saveScheduler(e,n),console.log(`[SCHEDULER] Next execution for "${e.name}": ${e.nextRun}`),this.schedulers.set(e.id,e),a=await this.executeSchedulerInternal(e,n,"scheduled"),i=!0}catch(s){i=!1,o=s instanceof Error?s.message:String(s),console.error(`[SCHEDULER] Scheduler "${e.name}" failed:`,s)}this.logger.logTriggerExecution({triggerId:e.id,triggerName:e.name,webhookUuid:e.promptId,projectName:n,success:i,threadId:a,error:o})}validateSchedule(e){return vce(e)}calculateNextRunSkippingMissed(e){let t=new Date,n=e.occurrenceCount??0,i=e.nextRun;if(!i)return{nextRun:lh(e.schedule,t,n),occurrenceCount:n};if(new Date(i)>=t)return{nextRun:i,occurrenceCount:n};let a=1e3,o=0,s=0;for(;o<a;){if(n++,s++,i=lh(e.schedule,t,n),!i)return s>0&&console.log(`[SCHEDULER] Scheduler "${e.name}" (${e.id}) expired after skipping ${s} missed occurrence(s)`),{nextRun:null,occurrenceCount:n};if(new Date(i)>=t)return s>0&&console.log(`[SCHEDULER] Scheduler "${e.name}" (${e.id}) skipped ${s} missed occurrence(s), next run: ${i}`),{nextRun:i,occurrenceCount:n};o++}return console.warn(`[SCHEDULER] Could not find future nextRun for scheduler ${e.id} after ${a} iterations`),{nextRun:null,occurrenceCount:n}}getSchedulersDir(e){return Em.join(this.codayConfigDir,"projects",e,"schedulers")}getSchedulerFilePath(e,t){return Em.join(this.getSchedulersDir(e),`${t}.yml`)}findProjectForScheduler(e){let t=Em.join(this.codayConfigDir,"projects");if(!ai.existsSync(t))return null;let n=ai.readdirSync(t,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of n){let a=this.getSchedulerFilePath(i,e);if(ai.existsSync(a))return i}return null}canAccessScheduler(e,t){return e.createdBy===t?!0:Sm(t,this.codayConfigDir)}async listSchedulers(e,t){return(await this.loadProjectSchedulers(e)).filter(i=>this.canAccessScheduler(i,t)).map(i=>({id:i.id,name:i.name,enabled:i.enabled,promptId:i.promptId,schedule:i.schedule,parameters:i.parameters,lastRun:i.lastRun,nextRun:i.nextRun,createdBy:i.createdBy}))}async getScheduler(e,t,n){let i=this.getSchedulerFilePath(e,t);if(!ai.existsSync(i))return null;try{let a=ai.readFileSync(i,"utf-8"),o=X6.parse(a),s=this.calculateNextRunSkippingMissed(o);return o.nextRun=s.nextRun,o.occurrenceCount=s.occurrenceCount,n&&!this.canAccessScheduler(o,n)?(console.log(`[SCHEDULER] Access denied for user ${n} to scheduler ${t}`),null):o}catch(a){return console.error(`[SCHEDULER] Failed to load scheduler ${t}:`,a),null}}async createScheduler(e,t,n){let i=this.validateSchedule(t.schedule);if(!i.valid)throw new Error(`Invalid schedule: ${i.error}`);if(!await this.promptService.getById(t.promptId))throw new Error(`Prompt not found: ${t.promptId}`);let o={id:Xit(),name:t.name,enabled:t.enabled??!0,promptId:t.promptId,schedule:t.schedule,parameters:t.parameters,createdBy:n,createdAt:new Date().toISOString(),nextRun:lh(t.schedule,new Date,0),occurrenceCount:0};return await this.saveScheduler(o,e),this.schedulers.set(o.id,o),console.log(`[SCHEDULER] Created scheduler "${o.name}" (${o.id}) for project ${e}`),o}async updateScheduler(e,t,n,i){let a=await this.getScheduler(e,t,i);if(!a)throw new Error(`Scheduler not found or access denied: ${t}`);if(console.log(`[SCHEDULER] Updating scheduler ${t} by user ${i}`),n.name!==void 0&&(a.name=n.name),n.enabled!==void 0&&(a.enabled=n.enabled),n.parameters!==void 0&&(a.parameters=n.parameters),n.promptId!==void 0){if(!await this.promptService.getById(n.promptId))throw new Error(`Prompt not found: ${n.promptId}`);a.promptId=n.promptId}if(n.schedule!==void 0){let o=this.validateSchedule(n.schedule);if(!o.valid)throw new Error(`Invalid schedule: ${o.error}`);a.schedule=n.schedule,a.occurrenceCount=0,a.nextRun=lh(n.schedule,new Date,0)}return await this.saveScheduler(a,e),this.schedulers.set(a.id,a),console.log(`[SCHEDULER] Updated scheduler "${a.name}" (${a.id})`),a}async deleteScheduler(e,t,n){if(!await this.getScheduler(e,t,n))return!1;let a=this.getSchedulerFilePath(e,t);return ai.unlinkSync(a),this.schedulers.delete(t),console.log(`[SCHEDULER] Deleted scheduler ${t} by user ${n}`),!0}async enableScheduler(e,t,n){return this.updateScheduler(e,t,{enabled:!0},n)}async disableScheduler(e,t,n){return this.updateScheduler(e,t,{enabled:!1},n)}async runSchedulerNow(e,t,n){let i=await this.getScheduler(e,t,n);if(!i)throw new Error(`Scheduler not found or access denied: ${t}`);let a=await this.executeSchedulerInternal(i,e,"manual");return i.lastRun=new Date().toISOString(),await this.saveScheduler(i,e),this.schedulers.set(i.id,i),this.logger.logTriggerExecution({triggerId:i.id,triggerName:i.name,webhookUuid:i.promptId,projectName:e,success:!0,threadId:a}),a}async saveScheduler(e,t){if(!t&&(t=this.findProjectForScheduler(e.id),!t))throw new Error(`Cannot find project for scheduler ${e.id}`);let n=this.getSchedulersDir(t);ai.mkdirSync(n,{recursive:!0});let i=this.getSchedulerFilePath(t,e.id),a=X6.stringify(e);ai.writeFileSync(i,a,"utf-8")}};import*as Mc from"node:path";import*as Ffe from"node:os";import{existsSync as Rfe,lstatSync as Qit,mkdirSync as Nfe,readdirSync as eat}from"fs";var aE=class r{projectsConfigPath;static PROJECT_FILENAME="project.yaml";constructor(e){let t=Mc.join(Ffe.userInfo().homedir,".coday");this.projectsConfigPath=Mc.join(e??t,"projects"),Nfe(this.projectsConfigPath,{recursive:!0})}listProjects(){return eat(this.projectsConfigPath).filter(t=>Qit(Mc.join(this.projectsConfigPath,t)).isDirectory())}getProjectInfo(e){let t=Mc.join(this.projectsConfigPath,e),n=Mc.join(t,r.PROJECT_FILENAME);return Rfe(n)?{name:e,configPath:t}:null}exists(e){return this.getProjectInfo(e)!==null}getConfig(e){let t=this.getProjectInfo(e);if(!t)return console.log(`[PROJECT_REPO] No project info found for: '${e}'`),null;let n=Mc.join(t.configPath,r.PROJECT_FILENAME),i=ta(n);if(!i)return console.log(`[PROJECT_REPO] Failed to load config for '${e}' from ${n}`),null;let a=uh(i,bce);return a!==i&&(console.log(`[PROJECT_REPO] Config migrated for '${e}', saving...`),Mn(n,a)),a}saveConfig(e,t){let n=this.getProjectInfo(e);if(!n)throw new Error(`Project '${e}' does not exist`);let i=Mc.join(n.configPath,r.PROJECT_FILENAME);Mn(i,t)}createProject(e,t){let n=Mc.join(this.projectsConfigPath,e),i=Mc.join(n,r.PROJECT_FILENAME);return Rfe(i)?!1:(console.log(`[PROJECT_REPO] Creating project '${e}' with path: ${t}`),Nfe(n,{recursive:!0}),Mn(i,{version:1,path:t,integration:{},storage:{type:"file"},agents:[]}),console.log(`[PROJECT_REPO] Project '${e}' created successfully`),!0)}deleteProject(e){return this.getProjectInfo(e),!1}};var _M=ur(Pc(),1);import{promises as Zu}from"fs";import Jp from"path";var Mfe=async r=>{try{let e=await Zu.readFile(r,"utf-8");return _M.default.parse(e)}catch{return null}},oE=class{constructor(e){this.projectsDir=e}getThreadsDir(e){return Jp.join(this.projectsDir,e,"threads")}async ensureThreadsDir(e){let t=this.getThreadsDir(e);try{await Zu.mkdir(t,{recursive:!0})}catch(n){throw new Eu(`Failed to initialize threads directory for project ${e}`,n)}}getThreadFileName(e){return`${e.id}.yml`}async findThreadFile(e,t){try{let n=this.getThreadsDir(e),i=`${t}.yml`;try{return await Zu.access(Jp.join(n,i)),i}catch{}return(await Zu.readdir(n)).find(s=>s.endsWith(`-${t}.yml`))||null}catch(n){throw new Eu(`Error finding thread ${t} in project ${e}`,n)}}async getById(e,t){try{let n=await this.findThreadFile(e,t);if(!n)return null;let i=this.getThreadsDir(e),a=Jp.join(i,n),o=await Mfe(a);if(!o)return null;let s=uh(o,YR);return s.projectId||(s.projectId=e),s!==o&&Mn(a,s),new ku(s)}catch(n){throw new Eu(`Failed to read thread ${t} from project ${e}`,n)}}async save(e,t){await this.ensureThreadsDir(e);try{if(t.id||(t.id=crypto.randomUUID()),t.projectId||(t.projectId=e),t.projectId!==e)throw new Error(`Thread projectId mismatch: expected ${e}, got ${t.projectId}`);let n=this.getThreadsDir(e),i=this.getThreadFileName(t),a=Jp.join(n,i),o=await this.findThreadFile(e,t.id);if(o&&o!==i){let u=Jp.join(n,o);try{await Zu.unlink(u),console.log(`[THREAD-REPO] Migrated/renamed thread file: ${o} \u2192 ${i}`)}catch(l){console.warn(`[THREAD-REPO] Could not delete old thread file: ${o}`,l)}}let s={...t.serialize(),version:YR.length+1},c=_M.default.stringify(s);return await Zu.writeFile(a,c,"utf-8"),t}catch(n){throw new Eu(`Failed to save thread ${t.id} to project ${e}`,n)}}async listByProject(e){try{let t=this.getThreadsDir(e);try{await Zu.access(t)}catch{return[]}let n=await Zu.readdir(t);return(await Promise.all(n.filter(a=>a.endsWith(".yml")).map(async a=>{let o=await Mfe(Jp.join(t,a));if(!o)return null;let s=o.projectId||e;return{id:o.id,username:o.username,projectId:s,name:o.name??"...",summary:o.summary??"",createdDate:o.createdDate??"",modifiedDate:o.modifiedDate??"",price:o.price??0,starring:o.starring??[],users:Array.isArray(o.users)?o.users.map(c=>typeof c=="string"?{userId:c}:c):o.username?[{userId:o.username}]:[],parentThreadId:o.parentThreadId,parentEventId:o.parentEventId,delegatedAgentName:o.delegatedAgentName,delegatedTask:o.delegatedTask}}))).filter(a=>!!a).sort((a,o)=>a.modifiedDate>o.modifiedDate?-1:1)}catch(t){throw new Eu(`Failed to list threads for project ${e}`,t)}}async delete(e,t){try{let n=await this.findThreadFile(e,t);if(!n)return!1;let i=this.getThreadsDir(e);return await Zu.unlink(Jp.join(i,n)),!0}catch(n){throw new Eu(`Failed to delete thread ${t} from project ${e}`,n)}}};var sE=class{constructor(e,t,n){this.projectRepository=e;this.projectsDir=t;this.threadFileService=n}repositoryCache=new Map;threadListCache=new Map;CACHE_TTL_MS=14400*1e3;loadingPromises=new Map;getThreadRepository(e){let t=this.repositoryCache.get(e);if(t)return t;if(!this.projectRepository.getProjectInfo(e))throw new Error(`Project '${e}' not found`);let i=new oE(this.projectsDir);return this.repositoryCache.set(e,i),i}clearCache(e){e?this.repositoryCache.delete(e):this.repositoryCache.clear()}async listThreads(e,t){let n=this.threadListCache.get(e);if(n&&Date.now()-n.timestamp<this.CACHE_TTL_MS)return n.data.filter(o=>rn(o,t)).sort((o,s)=>o.modifiedDate>s.modifiedDate?-1:1);let i=this.loadingPromises.get(e);if(i)return await i,this.listThreads(e,t);let a=this.loadThreadListFromDisk(e);this.loadingPromises.set(e,a);try{return(await a).filter(s=>rn(s,t)).sort((s,c)=>s.modifiedDate>c.modifiedDate?-1:1)}catch(o){throw this.threadListCache.delete(e),o}finally{this.loadingPromises.delete(e)}}async loadThreadListFromDisk(e){let n=await this.getThreadRepository(e).listByProject(e);return this.threadListCache.set(e,{data:n,timestamp:Date.now()}),n}toThreadSummary(e){return{id:e.id,username:e.username,projectId:e.projectId,name:e.name,summary:e.summary,createdDate:e.createdDate,modifiedDate:e.modifiedDate,price:e.price,starring:e.starring,users:e.users,parentThreadId:e.parentThreadId,parentEventId:e.parentEventId,delegatedAgentName:e.delegatedAgentName,delegatedTask:e.delegatedTask}}updateThreadInCache(e,t){let n=this.threadListCache.get(e);if(!n)return;let i=n.data.findIndex(a=>a.id===t.id);i!==-1?n.data[i]=t:n.data.push(t)}removeThreadFromCache(e,t){let n=this.threadListCache.get(e);n&&(n.data=n.data.filter(i=>i.id!==t))}async getThread(e,t){return await this.getThreadRepository(e).getById(e,t)}async createThread(e,t,n){let i=this.getThreadRepository(e),a=new ku({id:crypto.randomUUID(),username:t,projectId:e,name:n||"",price:0}),o=await i.save(e,a);return this.updateThreadInCache(e,this.toThreadSummary(o)),o}async updateThread(e,t,n){let i=this.getThreadRepository(e),a=await i.getById(e,t);if(!a){let c=this.threadListCache.get(e)?.data.find(u=>u.id===t);if(c)a=new ku({id:c.id,username:c.username,projectId:c.projectId,name:c.name,price:c.price});else throw new Error(`Thread '${t}' not found in project '${e}'`)}n.name!==void 0&&(a.name=n.name),n.summary!==void 0&&(a.summary=n.summary),n.users!==void 0&&(a.users=n.users);let o=await i.save(e,a);return this.updateThreadInCache(e,this.toThreadSummary(o)),o}async starThread(e,t,n){let i=this.getThreadRepository(e),a=await i.getById(e,t);if(!a)throw new Error(`Thread '${t}' not found in project '${e}'`);a.starring.includes(n)||a.starring.push(n);let o=await i.save(e,a);return this.updateThreadInCache(e,this.toThreadSummary(o)),o}async unstarThread(e,t,n){let i=this.getThreadRepository(e),a=await i.getById(e,t);if(!a)throw new Error(`Thread '${t}' not found in project '${e}'`);a.starring=a.starring.filter(s=>s!==n);let o=await i.save(e,a);return this.updateThreadInCache(e,this.toThreadSummary(o)),o}async deleteThread(e,t){let i=await this.getThreadRepository(e).delete(e,t);return i&&(await this.threadFileService.deleteThreadFiles(e,t),this.removeThreadFromCache(e,t)),i}async saveThread(e,t){let i=await this.getThreadRepository(e).save(e,t);return this.updateThreadInCache(e,this.toThreadSummary(i)),i}async listAllThreads(e){let t=this.threadListCache.get(e);if(t&&Date.now()-t.timestamp<this.CACHE_TTL_MS)return t.data.sort((a,o)=>a.modifiedDate>o.modifiedDate?-1:1);let n=this.loadingPromises.get(e);if(n)return await n,this.listAllThreads(e);let i=this.loadThreadListFromDisk(e);this.loadingPromises.set(e,i);try{return(await i).sort((o,s)=>o.modifiedDate>s.modifiedDate?-1:1)}catch(a){throw this.threadListCache.delete(e),a}finally{this.loadingPromises.delete(e)}}async exists(e,t){return await this.getThread(e,t)!==null}};var Bfe=ur(Pc(),1);import*as ba from"fs/promises";import*as Q6 from"path";var Lfe=5,qfe=24,Ufe=100,zfe={SHORT_THREADS:7,LONG_THREADS:30},cE=class{constructor(e,t){this.projectsConfigPath=e;this.logger=t}cleanupTimer=null;initialTimer=null;isRunning=!1;async start(){if(this.isRunning){this.log("Thread cleanup service already running");return}this.isRunning=!0,this.log("Starting thread cleanup service with user message-based retention"),this.initialTimer=setTimeout(async()=>{await this.performCleanup(),this.cleanupTimer=setInterval(async()=>{await this.performCleanup()},qfe*60*60*1e3),this.log(`Thread cleanup scheduled every ${qfe} hours`)},Lfe*60*1e3),this.log(`Initial cleanup scheduled in ${Lfe} minutes`)}async stop(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.isRunning=!1,this.log("Thread cleanup service stopped (all timers cleared)")}async performCleanup(){let e=Date.now(),t=0,n=0,i=0;try{this.log("Starting thread cleanup...");let a=await ba.readdir(this.projectsConfigPath);this.log(`Found ${a.length} projects to scan`);for(let s of a)try{let c=Q6.join(this.projectsConfigPath,s);if(!(await ba.lstat(c)).isDirectory())continue;let l=Q6.join(c,"threads");try{await ba.access(l)}catch{continue}let{scanned:f,deleted:p,errors:d}=await this.cleanupProjectThreads(s,l);t+=f,n+=p,i+=d}catch(c){this.logError(`Error processing project ${s}: ${c}`),i++}let o=Date.now()-e;this.log(`Cleanup completed: ${n}/${t} threads deleted across all projects in ${o}ms (${i} errors)`)}catch(a){let o=Date.now()-e;this.logError(`Cleanup failed after ${o}ms: ${a}`)}}async cleanupProjectThreads(e,t){let n=0,i=0,a=0;try{let s=(await ba.readdir(t)).filter(c=>c.endsWith(".yml"));if(n=s.length,s.length===0)return{scanned:n,deleted:i,errors:a};this.log(`Scanning ${s.length} threads in project ${e}`);for(let c=0;c<s.length;c+=Ufe){let u=s.slice(c,c+Ufe),l=await this.processBatch(u,t,e);i+=l.deleted,a+=l.errors}i>0&&this.log(`Project ${e}: deleted ${i}/${n} expired threads`)}catch(o){this.logError(`Error scanning project ${e}: ${o}`),a++}return{scanned:n,deleted:i,errors:a}}async processBatch(e,t,n){let i=0,a=0;return await Promise.all(e.map(async o=>{let s=Q6.join(t,o),c;try{let u=await ba.readFile(s,"utf-8");c=Bfe.parse(u)}catch(u){await ba.unlink(s),this.logError(`Error processing file ${o} in project ${n}: ${u}`)}if(!(!c||!c.modifiedDate)&&!(c.starring&&Array.isArray(c.starring)&&c.starring.length>0)&&this.shouldDeleteThread(c)){let u=this.countUserMessages(c.messages||[]),l=this.getDaysSinceModified(c.modifiedDate),f=c.id||o.replace(".yml","");await ba.unlink(s),await this.deleteThreadFiles(t,f),i++,this.logger.logThreadCleanup(n,o),console.log(`ThreadCleanup: Deleted thread ${f} and its files directory (${u} user messages, ${l} days old)`)}})),{deleted:i,errors:a}}shouldDeleteThread(e){if(!e||!e.modifiedDate)return!1;let n=this.countUserMessages(e.messages||[])<=3?zfe.SHORT_THREADS:zfe.LONG_THREADS;return this.getDaysSinceModified(e.modifiedDate)>n}countUserMessages(e){return e.filter(t=>t&&t.type==="message"&&t.role==="user").length}getDaysSinceModified(e){let t=new Date(e),i=new Date().getTime()-t.getTime();return Math.floor(i/(1e3*60*60*24))}async deleteThreadFiles(e,t){try{let n=Q6.join(e,`${t}-files`);try{await ba.access(n),await ba.rm(n,{recursive:!0,force:!0}),console.log(`ThreadCleanup: Deleted files directory ${n}`)}catch(i){if(i.code!=="ENOENT")throw i}}catch(n){console.error(`ThreadCleanup: Error deleting files for ${t}:`,n)}}log(e){let t=new Date().toISOString();console.log(`[${t}] ThreadCleanup: ${e}`)}logError(e){let t=new Date().toISOString();console.error(`[${t}] ThreadCleanup ERROR: ${e}`)}async forceCleanup(){this.log("Manual cleanup triggered"),await this.performCleanup()}};import*as qi from"path";import*as Kp from"fs";import*as xa from"fs/promises";var uE=class{constructor(e){this.projectsDir=e}getThreadFilesDir(e,t){return qi.join(this.projectsDir,e,"threads",`${t}-files`)}async ensureThreadFilesDir(e,t){let n=this.getThreadFilesDir(e,t);Kp.existsSync(n)||await xa.mkdir(n,{recursive:!0})}async listFiles(e,t){await this.ensureThreadFilesDir(e,t);let n=this.getThreadFilesDir(e,t),i=await xa.readdir(n);return await Promise.all(i.map(async o=>{let s=qi.join(n,o),c=await xa.stat(s);return{filename:o,size:c.size,lastModified:c.mtime.toISOString()}}))}async saveFile(e,t,n,i){let a=this.getThreadFilesDir(e,t);await xa.mkdir(a,{recursive:!0});let o=qi.join(a,n);await xa.writeFile(o,i)}async getFile(e,t,n){await this.ensureThreadFilesDir(e,t);let i=this.getThreadFilesDir(e,t),a=qi.join(i,n),o=qi.resolve(a),s=qi.resolve(i);if(!o.startsWith(s))throw new Error("Access denied: invalid file path");if(!Kp.existsSync(a))throw new Error(`File '${n}' not found`);return await xa.readFile(a)}async getFilePath(e,t,n){await this.ensureThreadFilesDir(e,t);let i=this.getThreadFilesDir(e,t),a=qi.join(i,n),o=qi.resolve(a),s=qi.resolve(i);if(!o.startsWith(s))throw new Error("Access denied: invalid file path");if(!Kp.existsSync(a))throw new Error(`File '${n}' not found`);return a}fileExists(e,t,n){let i=this.getThreadFilesDir(e,t),a=qi.join(i,n),o=qi.resolve(a),s=qi.resolve(i);return o.startsWith(s)?Kp.existsSync(a):!1}async deleteFile(e,t,n){await this.ensureThreadFilesDir(e,t);let i=this.getThreadFilesDir(e,t),a=qi.join(i,n),o=qi.resolve(a),s=qi.resolve(i);if(!o.startsWith(s))throw new Error("Access denied: invalid file path");if(!Kp.existsSync(a))throw new Error(`File '${n}' not found`);await xa.unlink(a)}async deleteThreadFiles(e,t){try{let n=this.getThreadFilesDir(e,t);Kp.existsSync(n)&&(await xa.rm(n,{recursive:!0,force:!0}),console.log(`Deleted thread files directory: ${n}`))}catch(n){console.error(`Error deleting thread files for ${t}:`,n)}}};var Hfe=ur(po(),1);var lE=class{constructor(e,t,n,i){this.threadRepository=t;this.projectId=n;this.interactor=i;this.username=e.username}activeThread$=new Hfe.BehaviorSubject(null);isKilled=!1;activeThread=this.activeThread$.asObservable();username;async kill(){this.isKilled=!0,this.activeThread$.complete()}async create(e){let t=new ku({id:"",username:this.username,name:e??"",price:0});return this.activeThread$.next(t),t}async select(e){let t=await this.threadRepository.getById(this.projectId,e);if(!t)throw new Error(`Thread ${e} not found`);return this.activeThread$.next(t),t}async save(e){let t=this.activeThread$.value;if(!t){console.error(`No thread existing when save attempt with name '${e}'`);return}e&&(t.name=e);let n=await this.threadRepository.save(this.projectId,t);this.activeThread$.next(n)}async autoSave(e){if(this.isKilled){console.log("Autosave skipped: service has been killed");return}let t=this.activeThread$.value;if(!t||t.messagesLength==0){console.log(`Autosave of an empty or falsy thread aborted, threadId: ${t?.id}, user: ${this.username}`);return}try{e&&(t.name=e),await this.threadRepository.save(this.projectId,t),this.interactor&&this.interactor.sendEvent(new gc({threadId:t.id,name:t.name||void 0}))}catch(n){console.log("Autosave failed (service may have been killed):",n instanceof Error?n.message:n)}}async truncateAtUserMessage(e){let t=this.activeThread$.value;if(!t)return console.error("No active thread available for truncation"),!1;let n=t.truncateAtUserMessage(e);return n||this.interactor?.warn("Failed to truncate thread."),n}getCurrentThread(){return this.activeThread$.value}};async function Wfe(r,e){let t=e.project.selectedProject,n=e.user.getUserData(t.name),i=await eE(t.config.path,r,n),a=new A0({...i,root:t.config.path,name:t.name},e.user.username);return console.log(`[BUILD_CONTEXT] Context for '${a.project.name}' \u2192 root: ${a.project.root}, desc: ${a.project.description?.length||0} chars`),a}var fE=class extends Re{constructor(t,n){super({commandWord:"select-project",description:"Select an existing project"});this.interactor=t;this.services=n}async handle(t,n){try{let i=this.getSubCommand(t);return await this.selectProject(i)??n}catch(i){return this.interactor.error(`Invalid project selection because: ${i.toString()}`),n}}async selectProject(t){return this.services.project.selectProject(t),this.services.project.selectedProject?Wfe(this.interactor,this.services):null}};var pE=class extends Re{constructor(t,n,i){super({commandWord:"add",description:"Add a new integration configuration. User level is default, use --project/-p for project level."});this.interactor=t;this.service=n;this.editHandler=i}async handle(t,n){let a=!!Tt(this.getSubCommand(t),[{key:"project",alias:"p"}]).project,o=a?"project":"user",s=this.service.getMergedIntegrations(),c=Object.keys(s),u=Qf.filter(h=>!c.includes(h));if(u.length===0)return this.interactor.displayText(`All available integrations (${Qf.join(", ")}) are already configured.`),n;let l=await this.interactor.chooseOption(u.sort(),"Select integration to add:",`Available integrations to configure:
877
+ `)):""}loadMemoriesFrom(e){this.memories=[],this.userMemoriesPath=this.readMemories(this.userMemoriesPath)?this.userMemoriesPath:void 0;let t=e?.configPath?tE.join(e.configPath,xM):void 0;this.projectMemoriesPath=this.readMemories(t)?t:void 0,e&&this.checkInit()}readMemories(e){if(!e)return!1;try{if(!Hit(e)){let n=kfe.stringify({memories:[]});Wit(e,n)}let t=ta(e);return t?(this.memories.push(...t.memories),!0):!1}catch{return!1}}checkInit(){if(!this.userMemoriesPath||!this.projectMemoriesPath)throw new Error("user or project path not set for memory service")}saveMemories(){this.checkInit();let e=this.memories.filter(n=>n.level==="USER"),t=this.memories.filter(n=>n.level==="PROJECT");Mn(this.userMemoriesPath,{memories:e}),Mn(this.projectMemoriesPath,{memories:t})}};import*as Cfe from"crypto";import*as Va from"node:fs/promises";import*as Fc from"path";var xm=class r{constructor(e,t,n){this.repository=e;this.defaultProject=t;this.isForcedMode=n}maskingService=new B2;listProjects(){let e=this.repository.listProjects();return this.isForcedMode&&this.defaultProject?e.filter(t=>t===this.defaultProject).map(t=>{let n=this.repository.getConfig(t);return{name:t,volatile:n?.volatile}}):e.map(t=>{let n=this.repository.getConfig(t);return{name:t,volatile:n?.volatile}})}getDefaultProject(){return this.defaultProject||null}getForcedMode(){return this.isForcedMode}getProject(e){this.checkAgainstForced(e);let t=this.repository.getConfig(e);if(t)return{name:e,config:t};if(!this.isForcedMode&&this.defaultProject){let n=process.cwd(),i=r.generateProjectId(n),a=Fc.basename(n);if(e===a||e===i||e===this.defaultProject){console.log(`[PROJECT_SERVICE] Creating volatile project for '${e}' at ${n}`);let o=this.getOrCreateVolatileProject(n);if(t=this.repository.getConfig(o),t)return{name:o,config:t}}}return null}exists(e){return this.checkAgainstForced(e),this.repository.exists(e)}createProject(e,t){if(this.checkAgainstForced(e),!e||!t)throw new Error("Project name and path are required");if(!this.repository.createProject(e,t))throw new Error(`Project '${e}' already exists`)}updateProjectConfig(e,t){if(this.checkAgainstForced(e),!this.repository.exists(e))throw new Error(`Project '${e}' does not exist`);this.repository.saveConfig(e,t)}deleteProject(e){if(this.checkAgainstForced(e),!this.repository.deleteProject(e))throw new Error(`Project '${e}' does not exist`)}getProjectConfigForClient(e){this.checkAgainstForced(e);let t=this.repository.getConfig(e);return t?this.maskingService.maskConfig(t):null}updateProjectConfigFromClient(e,t){this.checkAgainstForced(e);let n=this.repository.getConfig(e);if(!n)throw new Error(`Project '${e}' does not exist`);let i=this.maskingService.unmaskConfig(t,n);this.repository.saveConfig(e,i)}checkAgainstForced(e){if(this.isForcedMode&&this.defaultProject&&this.defaultProject!==e)throw Error(`Project selection outside of ${this.defaultProject} not allowed`)}getOrCreateVolatileProject(e){let t=r.generateProjectId(e);if(this.repository.exists(t))return t;this.repository.createProject(t,e);let n=this.repository.getConfig(t);return n&&(n.volatile=!0,n.createdAt=Date.now(),this.repository.saveConfig(t,n)),t}async registerWorktreeProject(e,t,n){let i=this.repository.getConfig(n),a=i?{...i,path:t,volatile:void 0,createdAt:void 0}:{version:1,path:t,integration:{},storage:{type:"file"},agents:[]};this.repository.createProject(e,t),this.repository.saveConfig(e,a);let o=this.repository.getProjectInfo(n);if(o){let s=this.repository.getProjectInfo(e);if(s)for(let c of["agents","prompts","schedulers","memories"]){let u=Fc.join(o.configPath,c),l=Fc.join(s.configPath,c);try{await Va.access(u),await Va.symlink(u,l)}catch{}}}}async unregisterWorktreeProject(e){let t=this.repository.getProjectInfo(e);if(!t)return;let n=e.lastIndexOf("__");if(n!==-1){let i=e.substring(0,n),a=this.repository.getProjectInfo(i);a&&await this.migrateThreadsToParent(t.configPath,a.configPath)}await Va.rm(t.configPath,{recursive:!0,force:!0})}async migrateThreadsToParent(e,t){let n=Fc.join(e,"threads"),i=Fc.join(t,"threads");try{await Va.access(n)}catch{return}await Va.mkdir(i,{recursive:!0});let a=await Va.readdir(n);for(let o of a){let s=Fc.join(n,o),c=Fc.join(i,o);try{await Va.access(c)}catch{await Va.rename(s,c)}}}static generateProjectId(e){let t=Fc.basename(e),n=Cfe.createHash("sha256").update(e).digest("hex").substring(0,8);return`${t}_${n}`}};var Dfe=ur(po(),1);import*as wm from"node:path";import*as Pfe from"node:os";import{mkdirSync as Vit}from"fs";var Git="projects",Tfe="project.yaml",_m=class{constructor(e,t,n){this.interactor=e;this.projectService=t;let i=wm.join(Pfe.userInfo().homedir,".coday");this.projectsConfigPath=wm.join(n??i,Git),Vit(this.projectsConfigPath,{recursive:!0}),this.projects=this.projectService.listProjects().map(a=>a.name)}projectsConfigPath;maskingService=new B2;projects;selectedProjectBehaviorSubject=new Dfe.BehaviorSubject(null);selectedProject$=this.selectedProjectBehaviorSubject.asObservable();selectProject(e){let t=wm.join(this.projectsConfigPath,e),n=wm.join(t,Tfe),i=this.projectService.getProject(e)?.config;if(!i?.path){console.log(`[PROJECT_STATE_SERVICE] ERROR: No project path in config for '${e}'`),this.interactor.error("Invalid selection, project path needed \u{1F622}.");return}let o={name:e,config:i,configPath:t};console.log(`[PROJECT_STATE_SERVICE] Selected '${e}' \u2192 ${i.path}`),this.updateSelectedProject(o),this.interactor.displayText(`Project local configuration used: ${n}`)}updateSelectedProject(e){this.selectedProjectBehaviorSubject.next(e)}get selectedProject(){return this.selectedProjectBehaviorSubject.value}save(e){let t=this.selectedProjectBehaviorSubject.value;if(!t){this.interactor.error("No current project selected, save not possible");return}let n={...t.config,...e};Mn(wm.join(t.configPath,Tfe),n),t.config=n,this.updateSelectedProject(t)}getConfigForClient(){let e=this.selectedProjectBehaviorSubject.value;return e?this.maskingService.maskConfig(e.config):null}updateConfigFromClient(e){let t=this.selectedProjectBehaviorSubject.value;if(!t){this.interactor.error("No current project selected, update not possible");return}let n=this.maskingService.unmaskConfig(e,t.config);this.save(n)}};import*as Gu from"node:path";import*as $fe from"node:os";import{randomUUID as Jit}from"node:crypto";import{existsSync as W2,mkdirSync as Kit,readdirSync as Ofe,unlinkSync as Yit}from"fs";import*as wM from"node:path";import*as Ife from"node:os";function Zit(r){return r.replace(/[^a-zA-Z0-9]/g,"_")}function Sm(r,e){try{let t=wM.join(Ife.userInfo().homedir,".coday"),n=Zit(r),i=wM.join(e??t,"users",n,"user.yaml"),a=ta(i);return a?a.groups?.includes("CODAY_ADMIN")??!1:!1}catch{return!1}}var rE=class{codayConfigDir;projectService;nativeHandlerStubs=[];constructor(e,t){let n=Gu.join($fe.userInfo().homedir,".coday");this.codayConfigDir=e??n,this.projectService=t}getProjectPath(e){if(this.projectService)return this.projectService.getProject(e)?.config.path}async getOrCreatePromptsDir(e,t){let n;if(t==="local")n=Gu.join(this.codayConfigDir,"projects",e,"prompts");else{let i=this.getProjectPath(e);if(!i)throw new Error("Project path not configured, cannot access project prompts");let a=await f2({text:"coday.yaml",root:i});if(a.length===0)throw new Error(`coday.yaml not found in project path: ${i}`);let o=Gu.dirname(a[0]);n=Gu.join(i,o,"prompts")}return W2(n)||(Kit(n,{recursive:!0}),console.log(`[PROMPT] Created prompts directory: ${n}`)),n}async getOrCreatePromptFilePath(e,t,n){let i=await this.getOrCreatePromptsDir(e,n);return Gu.join(i,`${t}.yml`)}async findPromptSource(e,t){let n=await this.getOrCreatePromptFilePath(e,t,"local");if(W2(n))return"local";if(this.projectService)try{let i=await this.getOrCreatePromptFilePath(e,t,"project");if(W2(i))return"project"}catch{}return null}async findProjectForPrompt(e){let t=Gu.join(this.codayConfigDir,"projects");if(!W2(t))return null;let n=Ofe(t,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of n){let a=Gu.join(this.codayConfigDir,"projects",i,"prompts",`${e}.yml`);if(W2(a))return i;if(this.projectService)try{let o=await this.getOrCreatePromptFilePath(i,e,"project");if(W2(o))return i}catch{}}return null}validatePlaceholders(e){let t=/\{\{(\w+)\}\}/g,n=[],i=/^[A-Za-z][A-Za-z0-9-]*$/;if(e.forEach(a=>{let o;for(;(o=t.exec(a))!==null;){let s=o[1];s&&s!=="PARAMETERS"&&!i.test(s)&&n.push(s)}}),n.length>0)throw new Error(`Invalid parameter keys: ${n.join(", ")}. Keys must start with a letter and contain only letters, digits, and hyphens.`)}async create(e,t,n="local"){try{this.validatePlaceholders(t.commands);let i=Jit(),a={...t,id:i,source:n,createdAt:new Date().toISOString(),parameterFormat:this.getParameterFormat(t.commands)},o=await this.getOrCreatePromptFilePath(e,i,n);if(W2(o))throw new Error(`Prompt with ID ${i} already exists`);return Mn(o,a),console.log(`[PROMPT] Created prompt ${i} in ${n} for project ${e}`),a}catch(i){throw new Error(`Failed to create prompt: ${i instanceof Error?i.message:"Unknown error"}`)}}async get(e,t){try{let n=await this.findPromptSource(e,t);if(!n)return null;let i=await this.getOrCreatePromptFilePath(e,t,n),a=ta(i);return a?(a.source||(a.source=n),a):null}catch(n){return console.error(`Failed to get prompt ${t}:`,n),null}}async getById(e){try{let t=await this.findProjectForPrompt(e);if(!t)return null;let n=await this.get(t,e);return n?{prompt:n,projectName:t}:null}catch(t){return console.error(`Failed to get prompt ${e}:`,t),null}}async update(e,t,n,i){try{let a=await this.get(e,t);if(!a)return null;if(n.webhookEnabled!==void 0&&n.webhookEnabled!==a.webhookEnabled&&!Sm(i,this.codayConfigDir))throw new Error("Only CODAY_ADMIN can enable/disable webhook for prompts");let{id:o,createdAt:s,source:c,...u}=n;n.commands&&this.validatePlaceholders(n.commands);let l={...a,...u,updatedAt:new Date().toISOString()};n.commands&&(l.parameterFormat=this.getParameterFormat(n.commands));let f=await this.getOrCreatePromptFilePath(e,t,a.source);return Mn(f,l),console.log(`[PROMPT] Updated prompt ${t} (${a.source}) by user ${i}`),l}catch(a){throw console.error(`Failed to update prompt ${t}:`,a),a}}async delete(e,t){try{let n=await this.findPromptSource(e,t);if(!n)return!1;let i=await this.getOrCreatePromptFilePath(e,t,n);return Yit(i),console.log(`[PROMPT] Deleted prompt ${t} from ${n}`),!0}catch(n){return console.error(`Failed to delete prompt ${t}:`,n),!1}}getParameterFormat(e){if(e.some(a=>/\{\{PARAMETERS\}\}/.test(a)))return"";let n=/\{\{(\w+)\}\}/g,i=new Set;return e.forEach(a=>{let o;for(;(o=n.exec(a))!==null;){let s=o[1];s&&s!=="PARAMETERS"&&i.add(s)}}),i.size===0?"":Array.from(i).map(a=>`${a}=""`).join(" ")}registerNativeHandler(e){this.nativeHandlerStubs.find(t=>t.id===e.id)||this.nativeHandlerStubs.push(e)}async list(e,t=[]){try{let n=[],i=["local"];this.projectService&&i.push("project");for(let a of i)try{let o=await this.getOrCreatePromptsDir(e,a);if(!W2(o))continue;let c=Ofe(o).filter(u=>u.endsWith(".yml"));for(let u of c){let l=u.replace(".yml",""),f=await this.get(e,l);f&&n.push({id:f.id,name:f.name,description:f.description,webhookEnabled:f.webhookEnabled,createdBy:f.createdBy,createdAt:f.createdAt,updatedAt:f.updatedAt,source:f.source||a,parameterFormat:f.parameterFormat})}}catch(o){console.log(`[PROMPT] Could not access ${a} prompts for ${e}:`,o)}return n.push(...E0),n.push(...this.nativeHandlerStubs),n.push(...t),n.sort((a,o)=>new Date(o.createdAt).getTime()-new Date(a.createdAt).getTime())}catch(n){return console.error(`Failed to list prompts for project ${e}:`,n),[]}}async enableWebhook(e,t,n){return this.update(e,t,{webhookEnabled:!0},n)}async disableWebhook(e,t,n){return this.update(e,t,{webhookEnabled:!1},n)}};var jfe=ur(po(),1),nE=class{constructor(e){this.promptService=e}threadCodayManager;threadService;codayOptions;logger;initialize(e,t,n,i){this.threadCodayManager=e,this.threadService=t,this.codayOptions=n,this.logger=i}processCommands(e,t){let n;if(typeof t=="string"){let a=e.some(s=>/\{\{PARAMETERS\}\}/.test(s));if(e.some(s=>/\{\{(?!PARAMETERS\}\})\w+\}\}/.test(s)))throw new Error("Prompt contains structured placeholders ({{key}}). Use an object parameter instead of a string.");a?n=e.map(s=>s.replace(/\{\{PARAMETERS\}\}/g,t)):n=e.map((s,c)=>c===0?`${s} ${t}`.trim():s)}else typeof t=="object"&&t!==null?n=e.map(a=>{let o=a;return Object.entries(t).forEach(([s,c])=>{let u=`{{${s}}}`;o=o.replaceAll(u,String(c))}),o}):n=[...e];let i=new Set;if(n.forEach(a=>{let o=a.match(/\{\{(\w+)\}\}/g);o&&o.forEach(s=>i.add(s))}),i.size>0){let a=Array.from(i).map(o=>o.replace(/[{}]/g,"")).join(", ");throw new Error(`Missing required parameters: ${a}`)}return n}async executePrompt(e,t,n,i,a){if(!this.threadCodayManager||!this.threadService||!this.codayOptions||!this.logger)throw new Error("PromptExecutionService not initialized. Call initialize() first.");let{title:o,awaitFinalAnswer:s=!1,projectName:c}=a||{},u,l;if(c){if(l=c,u=await this.promptService.get(l,e),!u)throw new Error(`Prompt ${e} not found in project ${l}`)}else{let y=await this.promptService.getById(e);if(!y)throw new Error(`Prompt not found: ${e}`);u=y.prompt,l=y.projectName}if(i==="webhook"&&!u.webhookEnabled)throw new Error(`Prompt ${e} is not enabled for webhook execution`);if(!u.commands||u.commands.length===0)throw new Error("Prompt has no commands configured");let f=this.processCommands(u.commands,t);if(!n)throw new Error("Username is required");let d=(await this.threadService.createThread(l,n,o)).id;console.log(`[PROMPT_EXEC] Created new thread: ${d} for ${i} execution`);let m={...this.codayOptions,oneshot:!0,project:l,thread:d,prompts:f};console.log(`[PROMPT_EXEC] Creating instance for ${i} execution with ${f.length} prompts:`,f);let h=this.threadCodayManager.createWithoutConnection(d,l,n,m);h.prepareCoday();let g=h.coday.interactor,v={project:l,title:o??"Untitled",username:n,clientId:d,promptCount:f.length,awaitFinalAnswer:!!s,promptName:u.name,promptId:u.id,executionMode:i};if(i==="webhook"?this.logger.logWebhook(v):this.logger.logWebhook({...v,webhookName:u.name,webhookUuid:u.id}),s){let y=[],x=g.events.pipe((0,jfe.filter)(k=>(console.log(`[PROMPT_EXEC] Received event type: ${k.type}, role: ${k instanceof $t?k.role:"N/A"}`),k instanceof $t&&k.role==="assistant"&&!!k.name))).subscribe(k=>{y.push(k)});try{await h.coday.run(),x.unsubscribe();let k=y[y.length-1];return await this.threadCodayManager.cleanup(d),{threadId:d,lastEvent:k}}catch(k){x.unsubscribe();let S=k instanceof Error?k.message:"Unknown error";throw this.logger.logWebhookError({error:`Prompt execution failed: ${S}`,username:n,project:l,clientId:d}),console.error("[PROMPT_EXEC] Error waiting for prompt completion:",k),await this.threadCodayManager.cleanup(d),k}}else return h.coday.run().catch(y=>{console.error("[PROMPT_EXEC] Error during prompt Coday run:",y)}),setTimeout(()=>{this.threadCodayManager.cleanup(d).catch(y=>{console.error("[PROMPT_EXEC] Error cleaning up prompt thread after timeout:",y)})},300*1e3),{threadId:d}}};var X6=ur(Pc(),1);import*as ai from"fs";import*as Em from"path";import{randomUUID as Xit}from"node:crypto";var iE=class{constructor(e,t,n){this.logger=e;this.promptService=t;this.codayConfigDir=n}schedulers=new Map;checkInterval;CHECK_INTERVAL_MS=3e4;promptExecutionService;initializeExecution(e){this.promptExecutionService=e}async initialize(){console.log("[SCHEDULER] Initializing SchedulerService..."),await this.loadAllSchedulers(),this.startScheduler(),console.log(`[SCHEDULER] SchedulerService initialized with ${this.schedulers.size} schedulers`)}stop(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=void 0,console.log("[SCHEDULER] SchedulerService stopped"))}async loadAllSchedulers(){this.schedulers.clear();let e=Em.join(this.codayConfigDir,"projects");if(!ai.existsSync(e))return;let t=ai.readdirSync(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name);for(let n of t)try{let i=await this.loadProjectSchedulers(n);for(let a of i)this.schedulers.set(a.id,a)}catch(i){console.error(`[SCHEDULER] Failed to load schedulers for project ${n}:`,i)}}async loadProjectSchedulers(e){let t=this.getSchedulersDir(e);if(!ai.existsSync(t))return[];let n=ai.readdirSync(t),i=[];for(let a of n)if(a.endsWith(".yml"))try{let o=Em.join(t,a),s=ai.readFileSync(o,"utf-8"),c=X6.parse(s),u=this.calculateNextRunSkippingMissed(c),l=u.occurrenceCount!==c.occurrenceCount;c.nextRun=u.nextRun,c.occurrenceCount=u.occurrenceCount,l&&await this.saveScheduler(c,e),i.push(c)}catch(o){console.error(`[SCHEDULER] Failed to load scheduler from ${a}:`,o)}return i}startScheduler(){this.checkInterval=setInterval(()=>{this.checkAndExecuteSchedulers()},this.CHECK_INTERVAL_MS),this.checkAndExecuteSchedulers()}async checkAndExecuteSchedulers(){for(let e of this.schedulers.values())e.enabled&&yce(e.schedule,e.nextRun??null,e.occurrenceCount??0)&&this.executeScheduler(e).catch(t=>{console.error(`[SCHEDULER] Failed to execute scheduler ${e.id}:`,t)})}async executeSchedulerInternal(e,t,n){if(!this.promptExecutionService)throw new Error("PromptExecutionService not initialized");console.log(`[SCHEDULER] Executing scheduler "${e.name}" (${e.id}) [${n}]`);let i=e.parameters;e.parameters&&typeof e.parameters=="object"&&Object.keys(e.parameters).length===1&&"PARAMETERS"in e.parameters&&(i=String(e.parameters.PARAMETERS));let a=await this.promptExecutionService.executePrompt(e.promptId,i,e.createdBy,"scheduled",{title:n==="scheduled"?`Scheduled: ${e.name}`:`Manual: ${e.name}`,awaitFinalAnswer:!1,projectName:t});return console.log(`[SCHEDULER] Scheduler "${e.name}" executed successfully. Thread: ${a.threadId}`),a.threadId}async executeScheduler(e){let t=new Date().toISOString();console.log(`[SCHEDULER] Executing scheduler "${e.name}" (${e.id})`);let n=this.findProjectForScheduler(e.id);if(!n){console.error(`[SCHEDULER] Cannot find project for scheduler ${e.id}, skipping execution`);return}let i,a,o;e.lastRun=t,e.occurrenceCount=(e.occurrenceCount??0)+1,e.nextRun=lh(e.schedule,new Date,e.occurrenceCount);try{await this.saveScheduler(e,n),console.log(`[SCHEDULER] Next execution for "${e.name}": ${e.nextRun}`),this.schedulers.set(e.id,e),a=await this.executeSchedulerInternal(e,n,"scheduled"),i=!0}catch(s){i=!1,o=s instanceof Error?s.message:String(s),console.error(`[SCHEDULER] Scheduler "${e.name}" failed:`,s)}this.logger.logTriggerExecution({triggerId:e.id,triggerName:e.name,webhookUuid:e.promptId,projectName:n,success:i,threadId:a,error:o})}validateSchedule(e){return vce(e)}calculateNextRunSkippingMissed(e){let t=new Date,n=e.occurrenceCount??0,i=e.nextRun;if(!i)return{nextRun:lh(e.schedule,t,n),occurrenceCount:n};if(new Date(i)>=t)return{nextRun:i,occurrenceCount:n};let a=1e3,o=0,s=0;for(;o<a;){if(n++,s++,i=lh(e.schedule,t,n),!i)return s>0&&console.log(`[SCHEDULER] Scheduler "${e.name}" (${e.id}) expired after skipping ${s} missed occurrence(s)`),{nextRun:null,occurrenceCount:n};if(new Date(i)>=t)return s>0&&console.log(`[SCHEDULER] Scheduler "${e.name}" (${e.id}) skipped ${s} missed occurrence(s), next run: ${i}`),{nextRun:i,occurrenceCount:n};o++}return console.warn(`[SCHEDULER] Could not find future nextRun for scheduler ${e.id} after ${a} iterations`),{nextRun:null,occurrenceCount:n}}getSchedulersDir(e){return Em.join(this.codayConfigDir,"projects",e,"schedulers")}getSchedulerFilePath(e,t){return Em.join(this.getSchedulersDir(e),`${t}.yml`)}findProjectForScheduler(e){let t=Em.join(this.codayConfigDir,"projects");if(!ai.existsSync(t))return null;let n=ai.readdirSync(t,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name);for(let i of n){let a=this.getSchedulerFilePath(i,e);if(ai.existsSync(a))return i}return null}canAccessScheduler(e,t){return e.createdBy===t?!0:Sm(t,this.codayConfigDir)}async listSchedulers(e,t){return(await this.loadProjectSchedulers(e)).filter(i=>this.canAccessScheduler(i,t)).map(i=>({id:i.id,name:i.name,enabled:i.enabled,promptId:i.promptId,schedule:i.schedule,parameters:i.parameters,lastRun:i.lastRun,nextRun:i.nextRun,createdBy:i.createdBy}))}async getScheduler(e,t,n){let i=this.getSchedulerFilePath(e,t);if(!ai.existsSync(i))return null;try{let a=ai.readFileSync(i,"utf-8"),o=X6.parse(a),s=this.calculateNextRunSkippingMissed(o);return o.nextRun=s.nextRun,o.occurrenceCount=s.occurrenceCount,n&&!this.canAccessScheduler(o,n)?(console.log(`[SCHEDULER] Access denied for user ${n} to scheduler ${t}`),null):o}catch(a){return console.error(`[SCHEDULER] Failed to load scheduler ${t}:`,a),null}}async createScheduler(e,t,n){let i=this.validateSchedule(t.schedule);if(!i.valid)throw new Error(`Invalid schedule: ${i.error}`);if(!await this.promptService.getById(t.promptId))throw new Error(`Prompt not found: ${t.promptId}`);let o={id:Xit(),name:t.name,enabled:t.enabled??!0,promptId:t.promptId,schedule:t.schedule,parameters:t.parameters,createdBy:n,createdAt:new Date().toISOString(),nextRun:lh(t.schedule,new Date,0),occurrenceCount:0};return await this.saveScheduler(o,e),this.schedulers.set(o.id,o),console.log(`[SCHEDULER] Created scheduler "${o.name}" (${o.id}) for project ${e}`),o}async updateScheduler(e,t,n,i){let a=await this.getScheduler(e,t,i);if(!a)throw new Error(`Scheduler not found or access denied: ${t}`);if(console.log(`[SCHEDULER] Updating scheduler ${t} by user ${i}`),n.name!==void 0&&(a.name=n.name),n.enabled!==void 0&&(a.enabled=n.enabled),n.parameters!==void 0&&(a.parameters=n.parameters),n.promptId!==void 0){if(!await this.promptService.getById(n.promptId))throw new Error(`Prompt not found: ${n.promptId}`);a.promptId=n.promptId}if(n.schedule!==void 0){let o=this.validateSchedule(n.schedule);if(!o.valid)throw new Error(`Invalid schedule: ${o.error}`);a.schedule=n.schedule,a.occurrenceCount=0,a.nextRun=lh(n.schedule,new Date,0)}return await this.saveScheduler(a,e),this.schedulers.set(a.id,a),console.log(`[SCHEDULER] Updated scheduler "${a.name}" (${a.id})`),a}async deleteScheduler(e,t,n){if(!await this.getScheduler(e,t,n))return!1;let a=this.getSchedulerFilePath(e,t);return ai.unlinkSync(a),this.schedulers.delete(t),console.log(`[SCHEDULER] Deleted scheduler ${t} by user ${n}`),!0}async enableScheduler(e,t,n){return this.updateScheduler(e,t,{enabled:!0},n)}async disableScheduler(e,t,n){return this.updateScheduler(e,t,{enabled:!1},n)}async runSchedulerNow(e,t,n){let i=await this.getScheduler(e,t,n);if(!i)throw new Error(`Scheduler not found or access denied: ${t}`);let a=await this.executeSchedulerInternal(i,e,"manual");return i.lastRun=new Date().toISOString(),await this.saveScheduler(i,e),this.schedulers.set(i.id,i),this.logger.logTriggerExecution({triggerId:i.id,triggerName:i.name,webhookUuid:i.promptId,projectName:e,success:!0,threadId:a}),a}async saveScheduler(e,t){if(!t&&(t=this.findProjectForScheduler(e.id),!t))throw new Error(`Cannot find project for scheduler ${e.id}`);let n=this.getSchedulersDir(t);ai.mkdirSync(n,{recursive:!0});let i=this.getSchedulerFilePath(t,e.id),a=X6.stringify(e);ai.writeFileSync(i,a,"utf-8")}};import*as Mc from"node:path";import*as Ffe from"node:os";import{existsSync as Rfe,lstatSync as Qit,mkdirSync as Nfe,readdirSync as eat}from"fs";var aE=class r{projectsConfigPath;static PROJECT_FILENAME="project.yaml";constructor(e){let t=Mc.join(Ffe.userInfo().homedir,".coday");this.projectsConfigPath=Mc.join(e??t,"projects"),Nfe(this.projectsConfigPath,{recursive:!0})}listProjects(){return eat(this.projectsConfigPath).filter(t=>Qit(Mc.join(this.projectsConfigPath,t)).isDirectory())}getProjectInfo(e){let t=Mc.join(this.projectsConfigPath,e),n=Mc.join(t,r.PROJECT_FILENAME);return Rfe(n)?{name:e,configPath:t}:null}exists(e){return this.getProjectInfo(e)!==null}getConfig(e){let t=this.getProjectInfo(e);if(!t)return console.log(`[PROJECT_REPO] No project info found for: '${e}'`),null;let n=Mc.join(t.configPath,r.PROJECT_FILENAME),i=ta(n);if(!i)return console.log(`[PROJECT_REPO] Failed to load config for '${e}' from ${n}`),null;let a=uh(i,bce);return a!==i&&(console.log(`[PROJECT_REPO] Config migrated for '${e}', saving...`),Mn(n,a)),a}saveConfig(e,t){let n=this.getProjectInfo(e);if(!n)throw new Error(`Project '${e}' does not exist`);let i=Mc.join(n.configPath,r.PROJECT_FILENAME);Mn(i,t)}createProject(e,t){let n=Mc.join(this.projectsConfigPath,e),i=Mc.join(n,r.PROJECT_FILENAME);return Rfe(i)?!1:(console.log(`[PROJECT_REPO] Creating project '${e}' with path: ${t}`),Nfe(n,{recursive:!0}),Mn(i,{version:1,path:t,integration:{},storage:{type:"file"},agents:[]}),console.log(`[PROJECT_REPO] Project '${e}' created successfully`),!0)}deleteProject(e){return this.getProjectInfo(e),!1}};var _M=ur(Pc(),1);import{promises as Zu}from"fs";import Jp from"path";var Mfe=async r=>{try{let e=await Zu.readFile(r,"utf-8");return _M.default.parse(e)}catch{return null}},oE=class{constructor(e){this.projectsDir=e}getThreadsDir(e){return Jp.join(this.projectsDir,e,"threads")}async ensureThreadsDir(e){let t=this.getThreadsDir(e);try{await Zu.mkdir(t,{recursive:!0})}catch(n){throw new Eu(`Failed to initialize threads directory for project ${e}`,n)}}getThreadFileName(e){return`${e.id}.yml`}async findThreadFile(e,t){try{let n=this.getThreadsDir(e),i=`${t}.yml`;try{return await Zu.access(Jp.join(n,i)),i}catch{}return(await Zu.readdir(n)).find(s=>s.endsWith(`-${t}.yml`))||null}catch(n){throw new Eu(`Error finding thread ${t} in project ${e}`,n)}}async getById(e,t){try{let n=await this.findThreadFile(e,t);if(!n)return null;let i=this.getThreadsDir(e),a=Jp.join(i,n),o=await Mfe(a);if(!o)return null;let s=uh(o,YR);return s.projectId||(s.projectId=e),s!==o&&Mn(a,s),new ku(s)}catch(n){throw new Eu(`Failed to read thread ${t} from project ${e}`,n)}}async save(e,t){await this.ensureThreadsDir(e);try{if(t.id||(t.id=crypto.randomUUID()),t.projectId||(t.projectId=e),t.projectId!==e)throw new Error(`Thread projectId mismatch: expected ${e}, got ${t.projectId}`);let n=this.getThreadsDir(e),i=this.getThreadFileName(t),a=Jp.join(n,i),o=await this.findThreadFile(e,t.id);if(o&&o!==i){let u=Jp.join(n,o);try{await Zu.unlink(u),console.log(`[THREAD-REPO] Migrated/renamed thread file: ${o} \u2192 ${i}`)}catch(l){console.warn(`[THREAD-REPO] Could not delete old thread file: ${o}`,l)}}let s={...t.serialize(),version:YR.length+1},c=_M.default.stringify(s);return await Zu.writeFile(a,c,"utf-8"),t}catch(n){throw new Eu(`Failed to save thread ${t.id} to project ${e}`,n)}}async listByProject(e){try{let t=this.getThreadsDir(e);try{await Zu.access(t)}catch{return[]}let n=await Zu.readdir(t);return(await Promise.all(n.filter(a=>a.endsWith(".yml")).map(async a=>{let o=await Mfe(Jp.join(t,a));if(!o)return null;let s=o.projectId||e;return{id:o.id,username:o.username,projectId:s,name:o.name??"...",summary:o.summary??"",createdDate:o.createdDate??"",modifiedDate:o.modifiedDate??"",price:o.price??0,starring:o.starring??[],users:Array.isArray(o.users)?o.users.map(c=>typeof c=="string"?{userId:c}:c):o.username?[{userId:o.username}]:[],parentThreadId:o.parentThreadId,parentEventId:o.parentEventId,delegatedAgentName:o.delegatedAgentName,delegatedTask:o.delegatedTask}}))).filter(a=>!!a).sort((a,o)=>a.modifiedDate>o.modifiedDate?-1:1)}catch(t){throw new Eu(`Failed to list threads for project ${e}`,t)}}async delete(e,t){try{let n=await this.findThreadFile(e,t);if(!n)return!1;let i=this.getThreadsDir(e);return await Zu.unlink(Jp.join(i,n)),!0}catch(n){throw new Eu(`Failed to delete thread ${t} from project ${e}`,n)}}};var sE=class{constructor(e,t,n){this.projectRepository=e;this.projectsDir=t;this.threadFileService=n}repositoryCache=new Map;threadListCache=new Map;CACHE_TTL_MS=14400*1e3;loadingPromises=new Map;getThreadRepository(e){let t=this.repositoryCache.get(e);if(t)return t;if(!this.projectRepository.getProjectInfo(e))throw new Error(`Project '${e}' not found`);let i=new oE(this.projectsDir);return this.repositoryCache.set(e,i),i}clearCache(e){e?this.repositoryCache.delete(e):this.repositoryCache.clear()}async listThreads(e,t){let n=this.threadListCache.get(e);if(n&&Date.now()-n.timestamp<this.CACHE_TTL_MS)return n.data.filter(o=>rn(o,t)).sort((o,s)=>o.modifiedDate>s.modifiedDate?-1:1);let i=this.loadingPromises.get(e);if(i)return await i,this.listThreads(e,t);let a=this.loadThreadListFromDisk(e);this.loadingPromises.set(e,a);try{return(await a).filter(s=>rn(s,t)).sort((s,c)=>s.modifiedDate>c.modifiedDate?-1:1)}catch(o){throw this.threadListCache.delete(e),o}finally{this.loadingPromises.delete(e)}}async loadThreadListFromDisk(e){let n=await this.getThreadRepository(e).listByProject(e);return this.threadListCache.set(e,{data:n,timestamp:Date.now()}),n}toThreadSummary(e){return{id:e.id,username:e.username,projectId:e.projectId,name:e.name,summary:e.summary,createdDate:e.createdDate,modifiedDate:e.modifiedDate,price:e.price,starring:e.starring,users:e.users,parentThreadId:e.parentThreadId,parentEventId:e.parentEventId,delegatedAgentName:e.delegatedAgentName,delegatedTask:e.delegatedTask}}updateThreadInCache(e,t){let n=this.threadListCache.get(e);if(!n)return;let i=n.data.findIndex(a=>a.id===t.id);i!==-1?n.data[i]=t:n.data.push(t)}removeThreadFromCache(e,t){let n=this.threadListCache.get(e);n&&(n.data=n.data.filter(i=>i.id!==t))}async getThread(e,t){return await this.getThreadRepository(e).getById(e,t)}async createThread(e,t,n){let i=this.getThreadRepository(e),a=new ku({id:crypto.randomUUID(),username:t,projectId:e,name:n||"",price:0}),o=await i.save(e,a);return this.updateThreadInCache(e,this.toThreadSummary(o)),o}async updateThread(e,t,n){let i=this.getThreadRepository(e),a=await i.getById(e,t);if(!a){let c=this.threadListCache.get(e)?.data.find(u=>u.id===t);if(c)a=new ku({id:c.id,username:c.username,projectId:c.projectId,name:c.name,summary:c.summary,price:c.price,starring:c.starring,users:c.users,parentThreadId:c.parentThreadId,parentEventId:c.parentEventId,delegatedAgentName:c.delegatedAgentName,delegatedTask:c.delegatedTask});else throw new Error(`Thread '${t}' not found in project '${e}'`)}n.name!==void 0&&(a.name=n.name),n.summary!==void 0&&(a.summary=n.summary),n.users!==void 0&&(a.users=n.users);let o=await i.save(e,a);return this.updateThreadInCache(e,this.toThreadSummary(o)),o}async starThread(e,t,n){let i=this.getThreadRepository(e),a=await i.getById(e,t);if(!a)throw new Error(`Thread '${t}' not found in project '${e}'`);a.starring.includes(n)||a.starring.push(n);let o=await i.save(e,a);return this.updateThreadInCache(e,this.toThreadSummary(o)),o}async unstarThread(e,t,n){let i=this.getThreadRepository(e),a=await i.getById(e,t);if(!a)throw new Error(`Thread '${t}' not found in project '${e}'`);a.starring=a.starring.filter(s=>s!==n);let o=await i.save(e,a);return this.updateThreadInCache(e,this.toThreadSummary(o)),o}async deleteThread(e,t){let i=await this.getThreadRepository(e).delete(e,t);return i&&(await this.threadFileService.deleteThreadFiles(e,t),this.removeThreadFromCache(e,t)),i}async saveThread(e,t){let i=await this.getThreadRepository(e).save(e,t);return this.updateThreadInCache(e,this.toThreadSummary(i)),i}async listAllThreads(e){let t=this.threadListCache.get(e);if(t&&Date.now()-t.timestamp<this.CACHE_TTL_MS)return t.data.sort((a,o)=>a.modifiedDate>o.modifiedDate?-1:1);let n=this.loadingPromises.get(e);if(n)return await n,this.listAllThreads(e);let i=this.loadThreadListFromDisk(e);this.loadingPromises.set(e,i);try{return(await i).sort((o,s)=>o.modifiedDate>s.modifiedDate?-1:1)}catch(a){throw this.threadListCache.delete(e),a}finally{this.loadingPromises.delete(e)}}async exists(e,t){return await this.getThread(e,t)!==null}};var Bfe=ur(Pc(),1);import*as ba from"fs/promises";import*as Q6 from"path";var Lfe=5,qfe=24,Ufe=100,zfe={SHORT_THREADS:7,LONG_THREADS:30},cE=class{constructor(e,t){this.projectsConfigPath=e;this.logger=t}cleanupTimer=null;initialTimer=null;isRunning=!1;async start(){if(this.isRunning){this.log("Thread cleanup service already running");return}this.isRunning=!0,this.log("Starting thread cleanup service with user message-based retention"),this.initialTimer=setTimeout(async()=>{await this.performCleanup(),this.cleanupTimer=setInterval(async()=>{await this.performCleanup()},qfe*60*60*1e3),this.log(`Thread cleanup scheduled every ${qfe} hours`)},Lfe*60*1e3),this.log(`Initial cleanup scheduled in ${Lfe} minutes`)}async stop(){this.initialTimer&&(clearTimeout(this.initialTimer),this.initialTimer=null),this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null),this.isRunning=!1,this.log("Thread cleanup service stopped (all timers cleared)")}async performCleanup(){let e=Date.now(),t=0,n=0,i=0;try{this.log("Starting thread cleanup...");let a=await ba.readdir(this.projectsConfigPath);this.log(`Found ${a.length} projects to scan`);for(let s of a)try{let c=Q6.join(this.projectsConfigPath,s);if(!(await ba.lstat(c)).isDirectory())continue;let l=Q6.join(c,"threads");try{await ba.access(l)}catch{continue}let{scanned:f,deleted:p,errors:d}=await this.cleanupProjectThreads(s,l);t+=f,n+=p,i+=d}catch(c){this.logError(`Error processing project ${s}: ${c}`),i++}let o=Date.now()-e;this.log(`Cleanup completed: ${n}/${t} threads deleted across all projects in ${o}ms (${i} errors)`)}catch(a){let o=Date.now()-e;this.logError(`Cleanup failed after ${o}ms: ${a}`)}}async cleanupProjectThreads(e,t){let n=0,i=0,a=0;try{let s=(await ba.readdir(t)).filter(c=>c.endsWith(".yml"));if(n=s.length,s.length===0)return{scanned:n,deleted:i,errors:a};this.log(`Scanning ${s.length} threads in project ${e}`);for(let c=0;c<s.length;c+=Ufe){let u=s.slice(c,c+Ufe),l=await this.processBatch(u,t,e);i+=l.deleted,a+=l.errors}i>0&&this.log(`Project ${e}: deleted ${i}/${n} expired threads`)}catch(o){this.logError(`Error scanning project ${e}: ${o}`),a++}return{scanned:n,deleted:i,errors:a}}async processBatch(e,t,n){let i=0,a=0;return await Promise.all(e.map(async o=>{let s=Q6.join(t,o),c;try{let u=await ba.readFile(s,"utf-8");c=Bfe.parse(u)}catch(u){await ba.unlink(s),this.logError(`Error processing file ${o} in project ${n}: ${u}`)}if(!(!c||!c.modifiedDate)&&!(c.starring&&Array.isArray(c.starring)&&c.starring.length>0)&&this.shouldDeleteThread(c)){let u=this.countUserMessages(c.messages||[]),l=this.getDaysSinceModified(c.modifiedDate),f=c.id||o.replace(".yml","");await ba.unlink(s),await this.deleteThreadFiles(t,f),i++,this.logger.logThreadCleanup(n,o),console.log(`ThreadCleanup: Deleted thread ${f} and its files directory (${u} user messages, ${l} days old)`)}})),{deleted:i,errors:a}}shouldDeleteThread(e){if(!e||!e.modifiedDate)return!1;let n=this.countUserMessages(e.messages||[])<=3?zfe.SHORT_THREADS:zfe.LONG_THREADS;return this.getDaysSinceModified(e.modifiedDate)>n}countUserMessages(e){return e.filter(t=>t&&t.type==="message"&&t.role==="user").length}getDaysSinceModified(e){let t=new Date(e),i=new Date().getTime()-t.getTime();return Math.floor(i/(1e3*60*60*24))}async deleteThreadFiles(e,t){try{let n=Q6.join(e,`${t}-files`);try{await ba.access(n),await ba.rm(n,{recursive:!0,force:!0}),console.log(`ThreadCleanup: Deleted files directory ${n}`)}catch(i){if(i.code!=="ENOENT")throw i}}catch(n){console.error(`ThreadCleanup: Error deleting files for ${t}:`,n)}}log(e){let t=new Date().toISOString();console.log(`[${t}] ThreadCleanup: ${e}`)}logError(e){let t=new Date().toISOString();console.error(`[${t}] ThreadCleanup ERROR: ${e}`)}async forceCleanup(){this.log("Manual cleanup triggered"),await this.performCleanup()}};import*as qi from"path";import*as Kp from"fs";import*as xa from"fs/promises";var uE=class{constructor(e){this.projectsDir=e}getThreadFilesDir(e,t){return qi.join(this.projectsDir,e,"threads",`${t}-files`)}async ensureThreadFilesDir(e,t){let n=this.getThreadFilesDir(e,t);Kp.existsSync(n)||await xa.mkdir(n,{recursive:!0})}async listFiles(e,t){await this.ensureThreadFilesDir(e,t);let n=this.getThreadFilesDir(e,t),i=await xa.readdir(n);return await Promise.all(i.map(async o=>{let s=qi.join(n,o),c=await xa.stat(s);return{filename:o,size:c.size,lastModified:c.mtime.toISOString()}}))}async saveFile(e,t,n,i){let a=this.getThreadFilesDir(e,t);await xa.mkdir(a,{recursive:!0});let o=qi.join(a,n);await xa.writeFile(o,i)}async getFile(e,t,n){await this.ensureThreadFilesDir(e,t);let i=this.getThreadFilesDir(e,t),a=qi.join(i,n),o=qi.resolve(a),s=qi.resolve(i);if(!o.startsWith(s))throw new Error("Access denied: invalid file path");if(!Kp.existsSync(a))throw new Error(`File '${n}' not found`);return await xa.readFile(a)}async getFilePath(e,t,n){await this.ensureThreadFilesDir(e,t);let i=this.getThreadFilesDir(e,t),a=qi.join(i,n),o=qi.resolve(a),s=qi.resolve(i);if(!o.startsWith(s))throw new Error("Access denied: invalid file path");if(!Kp.existsSync(a))throw new Error(`File '${n}' not found`);return a}fileExists(e,t,n){let i=this.getThreadFilesDir(e,t),a=qi.join(i,n),o=qi.resolve(a),s=qi.resolve(i);return o.startsWith(s)?Kp.existsSync(a):!1}async deleteFile(e,t,n){await this.ensureThreadFilesDir(e,t);let i=this.getThreadFilesDir(e,t),a=qi.join(i,n),o=qi.resolve(a),s=qi.resolve(i);if(!o.startsWith(s))throw new Error("Access denied: invalid file path");if(!Kp.existsSync(a))throw new Error(`File '${n}' not found`);await xa.unlink(a)}async deleteThreadFiles(e,t){try{let n=this.getThreadFilesDir(e,t);Kp.existsSync(n)&&(await xa.rm(n,{recursive:!0,force:!0}),console.log(`Deleted thread files directory: ${n}`))}catch(n){console.error(`Error deleting thread files for ${t}:`,n)}}};var Hfe=ur(po(),1);var lE=class{constructor(e,t,n,i){this.threadRepository=t;this.projectId=n;this.interactor=i;this.username=e.username}activeThread$=new Hfe.BehaviorSubject(null);isKilled=!1;activeThread=this.activeThread$.asObservable();username;async kill(){this.isKilled=!0,this.activeThread$.complete()}async create(e){let t=new ku({id:"",username:this.username,name:e??"",price:0});return this.activeThread$.next(t),t}async select(e){let t=await this.threadRepository.getById(this.projectId,e);if(!t)throw new Error(`Thread ${e} not found`);return this.activeThread$.next(t),t}async save(e){let t=this.activeThread$.value;if(!t){console.error(`No thread existing when save attempt with name '${e}'`);return}e&&(t.name=e);let n=await this.threadRepository.save(this.projectId,t);this.activeThread$.next(n)}async autoSave(e){if(this.isKilled){console.log("Autosave skipped: service has been killed");return}let t=this.activeThread$.value;if(!t||t.messagesLength==0){console.log(`Autosave of an empty or falsy thread aborted, threadId: ${t?.id}, user: ${this.username}`);return}try{e&&(t.name=e),await this.threadRepository.save(this.projectId,t),this.interactor&&this.interactor.sendEvent(new gc({threadId:t.id,name:t.name||void 0}))}catch(n){console.log("Autosave failed (service may have been killed):",n instanceof Error?n.message:n)}}async truncateAtUserMessage(e){let t=this.activeThread$.value;if(!t)return console.error("No active thread available for truncation"),!1;let n=t.truncateAtUserMessage(e);return n||this.interactor?.warn("Failed to truncate thread."),n}getCurrentThread(){return this.activeThread$.value}};async function Wfe(r,e){let t=e.project.selectedProject,n=e.user.getUserData(t.name),i=await eE(t.config.path,r,n),a=new A0({...i,root:t.config.path,name:t.name},e.user.username);return console.log(`[BUILD_CONTEXT] Context for '${a.project.name}' \u2192 root: ${a.project.root}, desc: ${a.project.description?.length||0} chars`),a}var fE=class extends Re{constructor(t,n){super({commandWord:"select-project",description:"Select an existing project"});this.interactor=t;this.services=n}async handle(t,n){try{let i=this.getSubCommand(t);return await this.selectProject(i)??n}catch(i){return this.interactor.error(`Invalid project selection because: ${i.toString()}`),n}}async selectProject(t){return this.services.project.selectProject(t),this.services.project.selectedProject?Wfe(this.interactor,this.services):null}};var pE=class extends Re{constructor(t,n,i){super({commandWord:"add",description:"Add a new integration configuration. User level is default, use --project/-p for project level."});this.interactor=t;this.service=n;this.editHandler=i}async handle(t,n){let a=!!Tt(this.getSubCommand(t),[{key:"project",alias:"p"}]).project,o=a?"project":"user",s=this.service.getMergedIntegrations(),c=Object.keys(s),u=Qf.filter(h=>!c.includes(h));if(u.length===0)return this.interactor.displayText(`All available integrations (${Qf.join(", ")}) are already configured.`),n;let l=await this.interactor.chooseOption(u.sort(),"Select integration to add:",`Available integrations to configure:
878
878
 
879
879
  ${u.map(h=>`- **${h}**`).join(`
880
880
  `)}
@@ -1137,7 +1137,7 @@ Summary:
1137
1137
 
1138
1138
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let o of r.seen.entries()){let s=o[1];if(e===o[0]){a(o);continue}if(r.external){let u=r.external.registry.get(o[0])?.id;if(e!==o[0]&&u){a(o);continue}}if(r.metadataRegistry.get(o[0])?.id){a(o);continue}if(s.cycle){a(o);continue}if(s.count>1&&r.reused==="ref"){a(o);continue}}}function Pk(r,e){let t=r.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=o=>{let s=r.seen.get(o);if(s.ref===null)return;let c=s.def??s.schema,u={...c},l=s.ref;if(s.ref=null,l){n(l);let p=r.seen.get(l),d=p.schema;if(d.$ref&&(r.target==="draft-07"||r.target==="draft-04"||r.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(d)):Object.assign(c,d),Object.assign(c,u),o._zod.parent===l)for(let h in c)h==="$ref"||h==="allOf"||h in u||delete c[h];if(d.$ref&&p.def)for(let h in c)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(c[h])===JSON.stringify(p.def[h])&&delete c[h]}let f=o._zod.parent;if(f&&f!==l){n(f);let p=r.seen.get(f);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(let d in c)d==="$ref"||d==="allOf"||d in p.def&&JSON.stringify(c[d])===JSON.stringify(p.def[d])&&delete c[d]}r.override({zodSchema:o,jsonSchema:c,path:s.path??[]})};for(let o of[...r.seen.entries()].reverse())n(o[0]);let i={};if(r.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":r.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":r.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":r.target,r.external?.uri){let o=r.external.registry.get(e)?.id;if(!o)throw new Error("Schema is missing an `id` property");i.$id=r.external.uri(o)}Object.assign(i,t.def??t.schema);let a=r.external?.defs??{};for(let o of r.seen.entries()){let s=o[1];s.def&&s.defId&&(a[s.defId]=s.def)}r.external||Object.keys(a).length>0&&(r.target==="draft-2020-12"?i.$defs=a:i.definitions=a);try{let o=JSON.parse(JSON.stringify(i));return Object.defineProperty(o,"~standard",{value:{...e["~standard"],jsonSchema:{input:Jg(e,"input",r.processors),output:Jg(e,"output",r.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function ka(r,e){let t=e??{seen:new Set};if(t.seen.has(r))return!1;t.seen.add(r);let n=r._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ka(n.element,t);if(n.type==="set")return ka(n.valueType,t);if(n.type==="lazy")return ka(n.getter(),t);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return ka(n.innerType,t);if(n.type==="intersection")return ka(n.left,t)||ka(n.right,t);if(n.type==="record"||n.type==="map")return ka(n.keyType,t)||ka(n.valueType,t);if(n.type==="pipe")return ka(n.in,t)||ka(n.out,t);if(n.type==="object"){for(let i in n.shape)if(ka(n.shape[i],t))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(ka(i,t))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(ka(i,t))return!0;return!!(n.rest&&ka(n.rest,t))}return!1}var Ade=(r,e={})=>t=>{let n=Ck({...t,processors:e});return Xr(r,n),Tk(n,r),Pk(n,r)},Jg=(r,e,t={})=>n=>{let{libraryOptions:i,target:a}=n??{},o=Ck({...i??{},target:a,io:e,processors:t});return Xr(r,o),Tk(o,r),Pk(o,r)};var gut={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Cde=(r,e,t,n)=>{let i=t;i.type="string";let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:u}=r._zod.bag;if(typeof a=="number"&&(i.minLength=a),typeof o=="number"&&(i.maxLength=o),s&&(i.format=gut[s]??s,i.format===""&&delete i.format,s==="time"&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?i.pattern=l[0].source:l.length>1&&(i.allOf=[...l.map(f=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:f.source}))])}},Tde=(r,e,t,n)=>{let i=t,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=r._zod.bag;typeof s=="string"&&s.includes("int")?i.type="integer":i.type="number",typeof l=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l),typeof a=="number"&&(i.minimum=a,typeof l=="number"&&e.target!=="draft-04"&&(l>=a?delete i.minimum:delete i.exclusiveMinimum)),typeof u=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u),typeof o=="number"&&(i.maximum=o,typeof u=="number"&&e.target!=="draft-04"&&(u<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof c=="number"&&(i.multipleOf=c)},Pde=(r,e,t,n)=>{t.type="boolean"},Dde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Ide=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},Ode=(r,e,t,n)=>{e.target==="openapi-3.0"?(t.type="string",t.nullable=!0,t.enum=[null]):t.type="null"},$de=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},jde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Rde=(r,e,t,n)=>{t.not={}},Nde=(r,e,t,n)=>{},Fde=(r,e,t,n)=>{},Mde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Lde=(r,e,t,n)=>{let i=r._zod.def,a=vg(i.entries);a.every(o=>typeof o=="number")&&(t.type="number"),a.every(o=>typeof o=="string")&&(t.type="string"),t.enum=a},qde=(r,e,t,n)=>{let i=r._zod.def,a=[];for(let o of i.values)if(o===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");a.push(Number(o))}else a.push(o);if(a.length!==0)if(a.length===1){let o=a[0];t.type=o===null?"null":typeof o,e.target==="draft-04"||e.target==="openapi-3.0"?t.enum=[o]:t.const=o}else a.every(o=>typeof o=="number")&&(t.type="number"),a.every(o=>typeof o=="string")&&(t.type="string"),a.every(o=>typeof o=="boolean")&&(t.type="boolean"),a.every(o=>o===null)&&(t.type="null"),t.enum=a},Ude=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},zde=(r,e,t,n)=>{let i=t,a=r._zod.pattern;if(!a)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=a.source},Bde=(r,e,t,n)=>{let i=t,a={type:"string",format:"binary",contentEncoding:"binary"},{minimum:o,maximum:s,mime:c}=r._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(i,a)},Hde=(r,e,t,n)=>{t.type="boolean"},Wde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Vde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},Gde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Zde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Jde=(r,e,t,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Kde=(r,e,t,n)=>{let i=t,a=r._zod.def,{minimum:o,maximum:s}=r._zod.bag;typeof o=="number"&&(i.minItems=o),typeof s=="number"&&(i.maxItems=s),i.type="array",i.items=Xr(a.element,e,{...n,path:[...n.path,"items"]})},Yde=(r,e,t,n)=>{let i=t,a=r._zod.def;i.type="object",i.properties={};let o=a.shape;for(let u in o)i.properties[u]=Xr(o[u],e,{...n,path:[...n.path,"properties",u]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(u=>{let l=a.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type==="never"?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Xr(a.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},xU=(r,e,t,n)=>{let i=r._zod.def,a=i.inclusive===!1,o=i.options.map((s,c)=>Xr(s,e,{...n,path:[...n.path,a?"oneOf":"anyOf",c]}));a?t.oneOf=o:t.anyOf=o},Xde=(r,e,t,n)=>{let i=r._zod.def,a=Xr(i.left,e,{...n,path:[...n.path,"allOf",0]}),o=Xr(i.right,e,{...n,path:[...n.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];t.allOf=c},Qde=(r,e,t,n)=>{let i=t,a=r._zod.def;i.type="array";let o=e.target==="draft-2020-12"?"prefixItems":"items",s=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=a.items.map((p,d)=>Xr(p,e,{...n,path:[...n.path,o,d]})),u=a.rest?Xr(a.rest,e,{...n,path:[...n.path,s,...e.target==="openapi-3.0"?[a.items.length]:[]]}):null;e.target==="draft-2020-12"?(i.prefixItems=c,u&&(i.items=u)):e.target==="openapi-3.0"?(i.items={anyOf:c},u&&i.items.anyOf.push(u),i.minItems=c.length,u||(i.maxItems=c.length)):(i.items=c,u&&(i.additionalItems=u));let{minimum:l,maximum:f}=r._zod.bag;typeof l=="number"&&(i.minItems=l),typeof f=="number"&&(i.maxItems=f)},e3e=(r,e,t,n)=>{let i=t,a=r._zod.def;i.type="object";let o=a.keyType,c=o._zod.bag?.patterns;if(a.mode==="loose"&&c&&c.size>0){let l=Xr(a.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let f of c)i.patternProperties[f.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=Xr(a.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=Xr(a.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=o._zod.values;if(u){let l=[...u].filter(f=>typeof f=="string"||typeof f=="number");l.length>0&&(i.required=l)}},t3e=(r,e,t,n)=>{let i=r._zod.def,a=Xr(i.innerType,e,n),o=e.seen.get(r);e.target==="openapi-3.0"?(o.ref=i.innerType,t.nullable=!0):t.anyOf=[a,{type:"null"}]},r3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType},n3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType,t.default=JSON.parse(JSON.stringify(i.defaultValue))},i3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType,e.io==="input"&&(t._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},a3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=o},o3e=(r,e,t,n)=>{let i=r._zod.def,a=e.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;Xr(a,e,n);let o=e.seen.get(r);o.ref=a},s3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType,t.readOnly=!0},c3e=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType},wU=(r,e,t,n)=>{let i=r._zod.def;Xr(i.innerType,e,n);let a=e.seen.get(r);a.ref=i.innerType},u3e=(r,e,t,n)=>{let i=r._zod.innerType;Xr(i,e,n);let a=e.seen.get(r);a.ref=i};function Km(r){return!!r._zod}function sd(r,e){return Km(r)?Wm(r,e):r.safeParse(e)}function Dk(r){var e,t;if(!r)return;let n;if(Km(r)?n=(t=(e=r._zod)===null||e===void 0?void 0:e.def)===null||t===void 0?void 0:t.shape:n=r.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function p3e(r){var e;if(Km(r)){let o=(e=r._zod)===null||e===void 0?void 0:e.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let n=r._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let i=r.value;if(i!==void 0)return i}var Yg={};Df(Yg,{ZodAny:()=>I3e,ZodArray:()=>R3e,ZodBase64:()=>WU,ZodBase64URL:()=>VU,ZodBigInt:()=>Lk,ZodBigIntFormat:()=>JU,ZodBoolean:()=>Mk,ZodCIDRv4:()=>BU,ZodCIDRv6:()=>HU,ZodCUID:()=>NU,ZodCUID2:()=>FU,ZodCatch:()=>t0e,ZodCodec:()=>nz,ZodCustom:()=>Bk,ZodCustomStringFormat:()=>Qg,ZodDate:()=>YU,ZodDefault:()=>J3e,ZodDiscriminatedUnion:()=>F3e,ZodE164:()=>GU,ZodEmail:()=>$U,ZodEmoji:()=>jU,ZodEnum:()=>Xg,ZodExactOptional:()=>V3e,ZodFile:()=>H3e,ZodFunction:()=>l0e,ZodGUID:()=>Ok,ZodIPv4:()=>UU,ZodIPv6:()=>zU,ZodIntersection:()=>M3e,ZodJWT:()=>ZU,ZodKSUID:()=>qU,ZodLazy:()=>s0e,ZodLiteral:()=>B3e,ZodMAC:()=>A3e,ZodMap:()=>U3e,ZodNaN:()=>n0e,ZodNanoID:()=>RU,ZodNever:()=>$3e,ZodNonOptional:()=>tz,ZodNull:()=>P3e,ZodNullable:()=>Z3e,ZodNumber:()=>Fk,ZodNumberFormat:()=>Ym,ZodObject:()=>qk,ZodOptional:()=>ez,ZodPipe:()=>rz,ZodPrefault:()=>Y3e,ZodPromise:()=>u0e,ZodReadonly:()=>i0e,ZodRecord:()=>zk,ZodSet:()=>z3e,ZodString:()=>Rk,ZodStringFormat:()=>Gr,ZodSuccess:()=>e0e,ZodSymbol:()=>C3e,ZodTemplateLiteral:()=>o0e,ZodTransform:()=>W3e,ZodTuple:()=>L3e,ZodType:()=>Bt,ZodULID:()=>MU,ZodURL:()=>Nk,ZodUUID:()=>nl,ZodUndefined:()=>T3e,ZodUnion:()=>Uk,ZodUnknown:()=>O3e,ZodVoid:()=>j3e,ZodXID:()=>LU,ZodXor:()=>N3e,_ZodString:()=>OU,_default:()=>K3e,_function:()=>Olt,any:()=>hlt,array:()=>or,base64:()=>Yut,base64url:()=>Xut,bigint:()=>ult,boolean:()=>si,catch:()=>r0e,check:()=>$lt,cidrv4:()=>Jut,cidrv6:()=>Kut,codec:()=>Plt,cuid:()=>Uut,cuid2:()=>zut,custom:()=>iz,date:()=>glt,describe:()=>jlt,discriminatedUnion:()=>XU,e164:()=>Qut,email:()=>Iut,emoji:()=>Lut,enum:()=>Za,exactOptional:()=>G3e,file:()=>klt,float32:()=>alt,float64:()=>olt,function:()=>Olt,guid:()=>Out,hash:()=>ilt,hex:()=>nlt,hostname:()=>rlt,httpUrl:()=>Mut,instanceof:()=>Nlt,int:()=>IU,int32:()=>slt,int64:()=>llt,intersection:()=>e8,ipv4:()=>Vut,ipv6:()=>Zut,json:()=>Mlt,jwt:()=>elt,keyof:()=>vlt,ksuid:()=>Wut,lazy:()=>c0e,literal:()=>ct,looseObject:()=>Bc,looseRecord:()=>wlt,mac:()=>Gut,map:()=>_lt,meta:()=>Rlt,nan:()=>Tlt,nanoid:()=>qut,nativeEnum:()=>Elt,never:()=>KU,nonoptional:()=>Q3e,null:()=>D3e,nullable:()=>$k,nullish:()=>Alt,number:()=>pn,object:()=>Je,optional:()=>zt,partialRecord:()=>xlt,pipe:()=>jk,prefault:()=>X3e,preprocess:()=>az,promise:()=>Ilt,readonly:()=>a0e,record:()=>dn,refine:()=>f0e,set:()=>Slt,strictObject:()=>ylt,string:()=>xe,stringFormat:()=>tlt,stringbool:()=>Flt,success:()=>Clt,superRefine:()=>p0e,symbol:()=>plt,templateLiteral:()=>Dlt,transform:()=>QU,tuple:()=>q3e,uint32:()=>clt,uint64:()=>flt,ulid:()=>But,undefined:()=>dlt,union:()=>an,unknown:()=>nn,url:()=>Fut,uuid:()=>$ut,uuidv4:()=>jut,uuidv6:()=>Rut,uuidv7:()=>Nut,void:()=>mlt,xid:()=>Hut,xor:()=>blt});var Ik={};Df(Ik,{endsWith:()=>Bg,gt:()=>tl,gte:()=>Ea,includes:()=>Ug,length:()=>Zm,lowercase:()=>Lg,lt:()=>el,lte:()=>Do,maxLength:()=>Gm,maxSize:()=>od,mime:()=>Hg,minLength:()=>ef,minSize:()=>rl,multipleOf:()=>ad,negative:()=>uU,nonnegative:()=>fU,nonpositive:()=>lU,normalize:()=>Wg,overwrite:()=>zc,positive:()=>cU,property:()=>pU,regex:()=>Mg,size:()=>Vm,slugify:()=>Ak,startsWith:()=>zg,toLowerCase:()=>Gg,toUpperCase:()=>Zg,trim:()=>Vg,uppercase:()=>qg});var Kg={};Df(Kg,{ZodISODate:()=>kU,ZodISODateTime:()=>SU,ZodISODuration:()=>PU,ZodISOTime:()=>CU,date:()=>AU,datetime:()=>EU,duration:()=>DU,time:()=>TU});var SU=ie("ZodISODateTime",(r,e)=>{FL.init(r,e),Gr.init(r,e)});function EU(r){return Lq(SU,r)}var kU=ie("ZodISODate",(r,e)=>{ML.init(r,e),Gr.init(r,e)});function AU(r){return qq(kU,r)}var CU=ie("ZodISOTime",(r,e)=>{LL.init(r,e),Gr.init(r,e)});function TU(r){return Uq(CU,r)}var PU=ie("ZodISODuration",(r,e)=>{qL.init(r,e),Gr.init(r,e)});function DU(r){return zq(PU,r)}var d3e=(r,e)=>{WE.init(r,e),r.name="ZodError",Object.defineProperties(r,{format:{value:t=>GE(r,t)},flatten:{value:t=>VE(r,t)},addIssue:{value:t=>{r.issues.push(t),r.message=JSON.stringify(r.issues,zm,2)}},addIssues:{value:t=>{r.issues.push(...t),r.message=JSON.stringify(r.issues,zm,2)}},isEmpty:{get(){return r.issues.length===0}}})},Rrr=ie("ZodError",d3e),Io=ie("ZodError",d3e,{Parent:Error});var h3e=Sg(Io),m3e=kg(Io),g3e=Cg(Io),v3e=Tg(Io),y3e=Cpe(Io),b3e=Tpe(Io),x3e=Ppe(Io),w3e=Dpe(Io),_3e=Ipe(Io),S3e=Ope(Io),E3e=$pe(Io),k3e=jpe(Io);var Bt=ie("ZodType",(r,e)=>(It.init(r,e),Object.assign(r["~standard"],{jsonSchema:{input:Jg(r,"input"),output:Jg(r,"output")}}),r.toJSONSchema=Ade(r,{}),r.def=e,r.type=e.type,Object.defineProperty(r,"_def",{value:e}),r.check=(...t)=>r.clone(Te.mergeDefs(e,{checks:[...e.checks??[],...t.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),r.with=r.check,r.clone=(t,n)=>_a(r,t,n),r.brand=()=>r,r.register=((t,n)=>(t.add(r,n),r)),r.parse=(t,n)=>h3e(r,t,n,{callee:r.parse}),r.safeParse=(t,n)=>g3e(r,t,n),r.parseAsync=async(t,n)=>m3e(r,t,n,{callee:r.parseAsync}),r.safeParseAsync=async(t,n)=>v3e(r,t,n),r.spa=r.safeParseAsync,r.encode=(t,n)=>y3e(r,t,n),r.decode=(t,n)=>b3e(r,t,n),r.encodeAsync=async(t,n)=>x3e(r,t,n),r.decodeAsync=async(t,n)=>w3e(r,t,n),r.safeEncode=(t,n)=>_3e(r,t,n),r.safeDecode=(t,n)=>S3e(r,t,n),r.safeEncodeAsync=async(t,n)=>E3e(r,t,n),r.safeDecodeAsync=async(t,n)=>k3e(r,t,n),r.refine=(t,n)=>r.check(f0e(t,n)),r.superRefine=t=>r.check(p0e(t)),r.overwrite=t=>r.check(zc(t)),r.optional=()=>zt(r),r.exactOptional=()=>G3e(r),r.nullable=()=>$k(r),r.nullish=()=>zt($k(r)),r.nonoptional=t=>Q3e(r,t),r.array=()=>or(r),r.or=t=>an([r,t]),r.and=t=>e8(r,t),r.transform=t=>jk(r,QU(t)),r.default=t=>K3e(r,t),r.prefault=t=>X3e(r,t),r.catch=t=>r0e(r,t),r.pipe=t=>jk(r,t),r.readonly=()=>a0e(r),r.describe=t=>{let n=r.clone();return Sa.add(n,{description:t}),n},Object.defineProperty(r,"description",{get(){return Sa.get(r)?.description},configurable:!0}),r.meta=(...t)=>{if(t.length===0)return Sa.get(r);let n=r.clone();return Sa.add(n,t[0]),n},r.isOptional=()=>r.safeParse(void 0).success,r.isNullable=()=>r.safeParse(null).success,r.apply=t=>t(r),r)),OU=ie("_ZodString",(r,e)=>{id.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(n,i,a)=>Cde(r,n,i,a);let t=r._zod.bag;r.format=t.format??null,r.minLength=t.minimum??null,r.maxLength=t.maximum??null,r.regex=(...n)=>r.check(Mg(...n)),r.includes=(...n)=>r.check(Ug(...n)),r.startsWith=(...n)=>r.check(zg(...n)),r.endsWith=(...n)=>r.check(Bg(...n)),r.min=(...n)=>r.check(ef(...n)),r.max=(...n)=>r.check(Gm(...n)),r.length=(...n)=>r.check(Zm(...n)),r.nonempty=(...n)=>r.check(ef(1,...n)),r.lowercase=n=>r.check(Lg(n)),r.uppercase=n=>r.check(qg(n)),r.trim=()=>r.check(Vg()),r.normalize=(...n)=>r.check(Wg(...n)),r.toLowerCase=()=>r.check(Gg()),r.toUpperCase=()=>r.check(Zg()),r.slugify=()=>r.check(Ak())}),Rk=ie("ZodString",(r,e)=>{id.init(r,e),OU.init(r,e),r.email=t=>r.check(ok($U,t)),r.url=t=>r.check(Fg(Nk,t)),r.jwt=t=>r.check(kk(ZU,t)),r.emoji=t=>r.check(fk(jU,t)),r.guid=t=>r.check(Ng(Ok,t)),r.uuid=t=>r.check(sk(nl,t)),r.uuidv4=t=>r.check(ck(nl,t)),r.uuidv6=t=>r.check(uk(nl,t)),r.uuidv7=t=>r.check(lk(nl,t)),r.nanoid=t=>r.check(pk(RU,t)),r.guid=t=>r.check(Ng(Ok,t)),r.cuid=t=>r.check(dk(NU,t)),r.cuid2=t=>r.check(hk(FU,t)),r.ulid=t=>r.check(mk(MU,t)),r.base64=t=>r.check(_k(WU,t)),r.base64url=t=>r.check(Sk(VU,t)),r.xid=t=>r.check(gk(LU,t)),r.ksuid=t=>r.check(vk(qU,t)),r.ipv4=t=>r.check(yk(UU,t)),r.ipv6=t=>r.check(bk(zU,t)),r.cidrv4=t=>r.check(xk(BU,t)),r.cidrv6=t=>r.check(wk(HU,t)),r.e164=t=>r.check(Ek(GU,t)),r.datetime=t=>r.check(EU(t)),r.date=t=>r.check(AU(t)),r.time=t=>r.check(TU(t)),r.duration=t=>r.check(DU(t))});function xe(r){return Fq(Rk,r)}var Gr=ie("ZodStringFormat",(r,e)=>{zr.init(r,e),OU.init(r,e)}),$U=ie("ZodEmail",(r,e)=>{TL.init(r,e),Gr.init(r,e)});function Iut(r){return ok($U,r)}var Ok=ie("ZodGUID",(r,e)=>{AL.init(r,e),Gr.init(r,e)});function Out(r){return Ng(Ok,r)}var nl=ie("ZodUUID",(r,e)=>{CL.init(r,e),Gr.init(r,e)});function $ut(r){return sk(nl,r)}function jut(r){return ck(nl,r)}function Rut(r){return uk(nl,r)}function Nut(r){return lk(nl,r)}var Nk=ie("ZodURL",(r,e)=>{PL.init(r,e),Gr.init(r,e)});function Fut(r){return Fg(Nk,r)}function Mut(r){return Fg(Nk,{protocol:/^https?$/,hostname:is.domain,...Te.normalizeParams(r)})}var jU=ie("ZodEmoji",(r,e)=>{DL.init(r,e),Gr.init(r,e)});function Lut(r){return fk(jU,r)}var RU=ie("ZodNanoID",(r,e)=>{IL.init(r,e),Gr.init(r,e)});function qut(r){return pk(RU,r)}var NU=ie("ZodCUID",(r,e)=>{OL.init(r,e),Gr.init(r,e)});function Uut(r){return dk(NU,r)}var FU=ie("ZodCUID2",(r,e)=>{$L.init(r,e),Gr.init(r,e)});function zut(r){return hk(FU,r)}var MU=ie("ZodULID",(r,e)=>{jL.init(r,e),Gr.init(r,e)});function But(r){return mk(MU,r)}var LU=ie("ZodXID",(r,e)=>{RL.init(r,e),Gr.init(r,e)});function Hut(r){return gk(LU,r)}var qU=ie("ZodKSUID",(r,e)=>{NL.init(r,e),Gr.init(r,e)});function Wut(r){return vk(qU,r)}var UU=ie("ZodIPv4",(r,e)=>{UL.init(r,e),Gr.init(r,e)});function Vut(r){return yk(UU,r)}var A3e=ie("ZodMAC",(r,e)=>{BL.init(r,e),Gr.init(r,e)});function Gut(r){return Mq(A3e,r)}var zU=ie("ZodIPv6",(r,e)=>{zL.init(r,e),Gr.init(r,e)});function Zut(r){return bk(zU,r)}var BU=ie("ZodCIDRv4",(r,e)=>{HL.init(r,e),Gr.init(r,e)});function Jut(r){return xk(BU,r)}var HU=ie("ZodCIDRv6",(r,e)=>{WL.init(r,e),Gr.init(r,e)});function Kut(r){return wk(HU,r)}var WU=ie("ZodBase64",(r,e)=>{VL.init(r,e),Gr.init(r,e)});function Yut(r){return _k(WU,r)}var VU=ie("ZodBase64URL",(r,e)=>{GL.init(r,e),Gr.init(r,e)});function Xut(r){return Sk(VU,r)}var GU=ie("ZodE164",(r,e)=>{ZL.init(r,e),Gr.init(r,e)});function Qut(r){return Ek(GU,r)}var ZU=ie("ZodJWT",(r,e)=>{JL.init(r,e),Gr.init(r,e)});function elt(r){return kk(ZU,r)}var Qg=ie("ZodCustomStringFormat",(r,e)=>{KL.init(r,e),Gr.init(r,e)});function tlt(r,e,t={}){return Jm(Qg,r,e,t)}function rlt(r){return Jm(Qg,"hostname",is.hostname,r)}function nlt(r){return Jm(Qg,"hex",is.hex,r)}function ilt(r,e){let t=e?.enc??"hex",n=`${r}_${t}`,i=is[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return Jm(Qg,n,i,e)}var Fk=ie("ZodNumber",(r,e)=>{rk.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(n,i,a)=>Tde(r,n,i,a),r.gt=(n,i)=>r.check(tl(n,i)),r.gte=(n,i)=>r.check(Ea(n,i)),r.min=(n,i)=>r.check(Ea(n,i)),r.lt=(n,i)=>r.check(el(n,i)),r.lte=(n,i)=>r.check(Do(n,i)),r.max=(n,i)=>r.check(Do(n,i)),r.int=n=>r.check(IU(n)),r.safe=n=>r.check(IU(n)),r.positive=n=>r.check(tl(0,n)),r.nonnegative=n=>r.check(Ea(0,n)),r.negative=n=>r.check(el(0,n)),r.nonpositive=n=>r.check(Do(0,n)),r.multipleOf=(n,i)=>r.check(ad(n,i)),r.step=(n,i)=>r.check(ad(n,i)),r.finite=()=>r;let t=r._zod.bag;r.minValue=Math.max(t.minimum??Number.NEGATIVE_INFINITY,t.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,r.maxValue=Math.min(t.maximum??Number.POSITIVE_INFINITY,t.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,r.isInt=(t.format??"").includes("int")||Number.isSafeInteger(t.multipleOf??.5),r.isFinite=!0,r.format=t.format??null});function pn(r){return Bq(Fk,r)}var Ym=ie("ZodNumberFormat",(r,e)=>{YL.init(r,e),Fk.init(r,e)});function IU(r){return Hq(Ym,r)}function alt(r){return Wq(Ym,r)}function olt(r){return Vq(Ym,r)}function slt(r){return Gq(Ym,r)}function clt(r){return Zq(Ym,r)}var Mk=ie("ZodBoolean",(r,e)=>{$g.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Pde(r,t,n,i)});function si(r){return Jq(Mk,r)}var Lk=ie("ZodBigInt",(r,e)=>{nk.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(n,i,a)=>Dde(r,n,i,a),r.gte=(n,i)=>r.check(Ea(n,i)),r.min=(n,i)=>r.check(Ea(n,i)),r.gt=(n,i)=>r.check(tl(n,i)),r.gte=(n,i)=>r.check(Ea(n,i)),r.min=(n,i)=>r.check(Ea(n,i)),r.lt=(n,i)=>r.check(el(n,i)),r.lte=(n,i)=>r.check(Do(n,i)),r.max=(n,i)=>r.check(Do(n,i)),r.positive=n=>r.check(tl(BigInt(0),n)),r.negative=n=>r.check(el(BigInt(0),n)),r.nonpositive=n=>r.check(Do(BigInt(0),n)),r.nonnegative=n=>r.check(Ea(BigInt(0),n)),r.multipleOf=(n,i)=>r.check(ad(n,i));let t=r._zod.bag;r.minValue=t.minimum??null,r.maxValue=t.maximum??null,r.format=t.format??null});function ult(r){return Kq(Lk,r)}var JU=ie("ZodBigIntFormat",(r,e)=>{XL.init(r,e),Lk.init(r,e)});function llt(r){return Yq(JU,r)}function flt(r){return Xq(JU,r)}var C3e=ie("ZodSymbol",(r,e)=>{QL.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Ide(r,t,n,i)});function plt(r){return Qq(C3e,r)}var T3e=ie("ZodUndefined",(r,e)=>{eq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>$de(r,t,n,i)});function dlt(r){return eU(T3e,r)}var P3e=ie("ZodNull",(r,e)=>{tq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Ode(r,t,n,i)});function D3e(r){return tU(P3e,r)}var I3e=ie("ZodAny",(r,e)=>{rq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Nde(r,t,n,i)});function hlt(){return rU(I3e)}var O3e=ie("ZodUnknown",(r,e)=>{nq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Fde(r,t,n,i)});function nn(){return nU(O3e)}var $3e=ie("ZodNever",(r,e)=>{iq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Rde(r,t,n,i)});function KU(r){return iU($3e,r)}var j3e=ie("ZodVoid",(r,e)=>{aq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>jde(r,t,n,i)});function mlt(r){return aU(j3e,r)}var YU=ie("ZodDate",(r,e)=>{oq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(n,i,a)=>Mde(r,n,i,a),r.min=(n,i)=>r.check(Ea(n,i)),r.max=(n,i)=>r.check(Do(n,i));let t=r._zod.bag;r.minDate=t.minimum?new Date(t.minimum):null,r.maxDate=t.maximum?new Date(t.maximum):null});function glt(r){return oU(YU,r)}var R3e=ie("ZodArray",(r,e)=>{sq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Kde(r,t,n,i),r.element=e.element,r.min=(t,n)=>r.check(ef(t,n)),r.nonempty=t=>r.check(ef(1,t)),r.max=(t,n)=>r.check(Gm(t,n)),r.length=(t,n)=>r.check(Zm(t,n)),r.unwrap=()=>r.element});function or(r,e){return kde(R3e,r,e)}function vlt(r){let e=r._zod.def.shape;return Za(Object.keys(e))}var qk=ie("ZodObject",(r,e)=>{wde.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Yde(r,t,n,i),Te.defineLazy(r,"shape",()=>e.shape),r.keyof=()=>Za(Object.keys(r._zod.def.shape)),r.catchall=t=>r.clone({...r._zod.def,catchall:t}),r.passthrough=()=>r.clone({...r._zod.def,catchall:nn()}),r.loose=()=>r.clone({...r._zod.def,catchall:nn()}),r.strict=()=>r.clone({...r._zod.def,catchall:KU()}),r.strip=()=>r.clone({...r._zod.def,catchall:void 0}),r.extend=t=>Te.extend(r,t),r.safeExtend=t=>Te.safeExtend(r,t),r.merge=t=>Te.merge(r,t),r.pick=t=>Te.pick(r,t),r.omit=t=>Te.omit(r,t),r.partial=(...t)=>Te.partial(ez,r,t[0]),r.required=(...t)=>Te.required(tz,r,t[0])});function Je(r,e){let t={type:"object",shape:r??{},...Te.normalizeParams(e)};return new qk(t)}function ylt(r,e){return new qk({type:"object",shape:r,catchall:KU(),...Te.normalizeParams(e)})}function Bc(r,e){return new qk({type:"object",shape:r,catchall:nn(),...Te.normalizeParams(e)})}var Uk=ie("ZodUnion",(r,e)=>{jg.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>xU(r,t,n,i),r.options=e.options});function an(r,e){return new Uk({type:"union",options:r,...Te.normalizeParams(e)})}var N3e=ie("ZodXor",(r,e)=>{Uk.init(r,e),cq.init(r,e),r._zod.processJSONSchema=(t,n,i)=>xU(r,t,n,i),r.options=e.options});function blt(r,e){return new N3e({type:"union",options:r,inclusive:!1,...Te.normalizeParams(e)})}var F3e=ie("ZodDiscriminatedUnion",(r,e)=>{Uk.init(r,e),uq.init(r,e)});function XU(r,e,t){return new F3e({type:"union",options:e,discriminator:r,...Te.normalizeParams(t)})}var M3e=ie("ZodIntersection",(r,e)=>{lq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Xde(r,t,n,i)});function e8(r,e){return new M3e({type:"intersection",left:r,right:e})}var L3e=ie("ZodTuple",(r,e)=>{ik.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Qde(r,t,n,i),r.rest=t=>r.clone({...r._zod.def,rest:t})});function q3e(r,e,t){let n=e instanceof It,i=n?t:e,a=n?e:null;return new L3e({type:"tuple",items:r,rest:a,...Te.normalizeParams(i)})}var zk=ie("ZodRecord",(r,e)=>{fq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>e3e(r,t,n,i),r.keyType=e.keyType,r.valueType=e.valueType});function dn(r,e,t){return new zk({type:"record",keyType:r,valueType:e,...Te.normalizeParams(t)})}function xlt(r,e,t){let n=_a(r);return n._zod.values=void 0,new zk({type:"record",keyType:n,valueType:e,...Te.normalizeParams(t)})}function wlt(r,e,t){return new zk({type:"record",keyType:r,valueType:e,mode:"loose",...Te.normalizeParams(t)})}var U3e=ie("ZodMap",(r,e)=>{pq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Zde(r,t,n,i),r.keyType=e.keyType,r.valueType=e.valueType,r.min=(...t)=>r.check(rl(...t)),r.nonempty=t=>r.check(rl(1,t)),r.max=(...t)=>r.check(od(...t)),r.size=(...t)=>r.check(Vm(...t))});function _lt(r,e,t){return new U3e({type:"map",keyType:r,valueType:e,...Te.normalizeParams(t)})}var z3e=ie("ZodSet",(r,e)=>{dq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Jde(r,t,n,i),r.min=(...t)=>r.check(rl(...t)),r.nonempty=t=>r.check(rl(1,t)),r.max=(...t)=>r.check(od(...t)),r.size=(...t)=>r.check(Vm(...t))});function Slt(r,e){return new z3e({type:"set",valueType:r,...Te.normalizeParams(e)})}var Xg=ie("ZodEnum",(r,e)=>{hq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(n,i,a)=>Lde(r,n,i,a),r.enum=e.entries,r.options=Object.values(e.entries);let t=new Set(Object.keys(e.entries));r.extract=(n,i)=>{let a={};for(let o of n)if(t.has(o))a[o]=e.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Xg({...e,checks:[],...Te.normalizeParams(i),entries:a})},r.exclude=(n,i)=>{let a={...e.entries};for(let o of n)if(t.has(o))delete a[o];else throw new Error(`Key ${o} not found in enum`);return new Xg({...e,checks:[],...Te.normalizeParams(i),entries:a})}});function Za(r,e){let t=Array.isArray(r)?Object.fromEntries(r.map(n=>[n,n])):r;return new Xg({type:"enum",entries:t,...Te.normalizeParams(e)})}function Elt(r,e){return new Xg({type:"enum",entries:r,...Te.normalizeParams(e)})}var B3e=ie("ZodLiteral",(r,e)=>{mq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>qde(r,t,n,i),r.values=new Set(e.values),Object.defineProperty(r,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function ct(r,e){return new B3e({type:"literal",values:Array.isArray(r)?r:[r],...Te.normalizeParams(e)})}var H3e=ie("ZodFile",(r,e)=>{gq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Bde(r,t,n,i),r.min=(t,n)=>r.check(rl(t,n)),r.max=(t,n)=>r.check(od(t,n)),r.mime=(t,n)=>r.check(Hg(Array.isArray(t)?t:[t],n))});function klt(r){return dU(H3e,r)}var W3e=ie("ZodTransform",(r,e)=>{vq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Gde(r,t,n,i),r._zod.parse=(t,n)=>{if(n.direction==="backward")throw new td(r.constructor.name);t.addIssue=a=>{if(typeof a=="string")t.issues.push(Te.issue(a,t.value,e));else{let o=a;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=t.value),o.inst??(o.inst=r),t.issues.push(Te.issue(o))}};let i=e.transform(t.value,t);return i instanceof Promise?i.then(a=>(t.value=a,t)):(t.value=i,t)}});function QU(r){return new W3e({type:"transform",transform:r})}var ez=ie("ZodOptional",(r,e)=>{ak.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>wU(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function zt(r){return new ez({type:"optional",innerType:r})}var V3e=ie("ZodExactOptional",(r,e)=>{yq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>wU(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function G3e(r){return new V3e({type:"optional",innerType:r})}var Z3e=ie("ZodNullable",(r,e)=>{bq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>t3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function $k(r){return new Z3e({type:"nullable",innerType:r})}function Alt(r){return zt($k(r))}var J3e=ie("ZodDefault",(r,e)=>{xq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>n3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType,r.removeDefault=r.unwrap});function K3e(r,e){return new J3e({type:"default",innerType:r,get defaultValue(){return typeof e=="function"?e():Te.shallowClone(e)}})}var Y3e=ie("ZodPrefault",(r,e)=>{wq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>i3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function X3e(r,e){return new Y3e({type:"prefault",innerType:r,get defaultValue(){return typeof e=="function"?e():Te.shallowClone(e)}})}var tz=ie("ZodNonOptional",(r,e)=>{_q.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>r3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function Q3e(r,e){return new tz({type:"nonoptional",innerType:r,...Te.normalizeParams(e)})}var e0e=ie("ZodSuccess",(r,e)=>{Sq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Hde(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function Clt(r){return new e0e({type:"success",innerType:r})}var t0e=ie("ZodCatch",(r,e)=>{Eq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>a3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType,r.removeCatch=r.unwrap});function r0e(r,e){return new t0e({type:"catch",innerType:r,catchValue:typeof e=="function"?e:()=>e})}var n0e=ie("ZodNaN",(r,e)=>{kq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Ude(r,t,n,i)});function Tlt(r){return sU(n0e,r)}var rz=ie("ZodPipe",(r,e)=>{Aq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>o3e(r,t,n,i),r.in=e.in,r.out=e.out});function jk(r,e){return new rz({type:"pipe",in:r,out:e})}var nz=ie("ZodCodec",(r,e)=>{rz.init(r,e),Rg.init(r,e)});function Plt(r,e,t){return new nz({type:"pipe",in:r,out:e,transform:t.decode,reverseTransform:t.encode})}var i0e=ie("ZodReadonly",(r,e)=>{Cq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>s3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function a0e(r){return new i0e({type:"readonly",innerType:r})}var o0e=ie("ZodTemplateLiteral",(r,e)=>{Tq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>zde(r,t,n,i)});function Dlt(r,e){return new o0e({type:"template_literal",parts:r,...Te.normalizeParams(e)})}var s0e=ie("ZodLazy",(r,e)=>{Iq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>u3e(r,t,n,i),r.unwrap=()=>r._zod.def.getter()});function c0e(r){return new s0e({type:"lazy",getter:r})}var u0e=ie("ZodPromise",(r,e)=>{Dq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>c3e(r,t,n,i),r.unwrap=()=>r._zod.def.innerType});function Ilt(r){return new u0e({type:"promise",innerType:r})}var l0e=ie("ZodFunction",(r,e)=>{Pq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Vde(r,t,n,i)});function Olt(r){return new l0e({type:"function",input:Array.isArray(r?.input)?q3e(r?.input):r?.input??or(nn()),output:r?.output??nn()})}var Bk=ie("ZodCustom",(r,e)=>{Oq.init(r,e),Bt.init(r,e),r._zod.processJSONSchema=(t,n,i)=>Wde(r,t,n,i)});function $lt(r){let e=new Vr({check:"custom"});return e._zod.check=r,e}function iz(r,e){return hU(Bk,r??(()=>!0),e)}function f0e(r,e={}){return mU(Bk,r,e)}function p0e(r){return gU(r)}var jlt=vU,Rlt=yU;function Nlt(r,e={}){let t=new Bk({type:"custom",check:"custom",fn:n=>n instanceof r,abort:!0,...Te.normalizeParams(e)});return t._zod.bag.Class=r,t._zod.check=n=>{n.value instanceof r||n.issues.push({code:"invalid_type",expected:r.name,input:n.value,inst:t,path:[...t._zod.def.path??[]]})},t}var Flt=(...r)=>bU({Codec:nz,Boolean:Mk,String:Rk},...r);function Mlt(r){let e=c0e(()=>an([xe(r),pn(),si(),D3e(),or(e),dn(xe(),e)]));return e}function az(r,e){return jk(QU(r),e)}var d0e;d0e||(d0e={});var Brr={...Yg,...Ik,iso:Kg};oi($q());var sz="2025-06-18";var h0e=[sz,"2025-03-26","2024-11-05","2024-10-07"],Wk="2.0",Hc=iz(r=>r!==null&&(typeof r=="object"||typeof r=="function")),m0e=an([xe(),pn().int()]),g0e=xe(),zlt=Bc({progressToken:m0e.optional()}),Ls=Bc({_meta:zlt.optional()}),Ja=Je({method:xe(),params:Ls.optional()}),Qm=Bc({_meta:dn(xe(),nn()).optional()}),qs=Je({method:xe(),params:Qm.optional()}),as=Bc({_meta:dn(xe(),nn()).optional()}),Vk=an([xe(),pn().int()]),v0e=Je({jsonrpc:ct(Wk),id:Vk,...Ja.shape}).strict(),y0e=r=>v0e.safeParse(r).success,b0e=Je({jsonrpc:ct(Wk),...qs.shape}).strict(),x0e=r=>b0e.safeParse(r).success,w0e=Je({jsonrpc:ct(Wk),id:Vk,result:as}).strict(),cz=r=>w0e.safeParse(r).success,xi;(function(r){r[r.ConnectionClosed=-32e3]="ConnectionClosed",r[r.RequestTimeout=-32001]="RequestTimeout",r[r.ParseError=-32700]="ParseError",r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError",r[r.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(xi||(xi={}));var _0e=Je({jsonrpc:ct(Wk),id:Vk,error:Je({code:pn().int(),message:xe(),data:zt(nn())})}).strict(),S0e=r=>_0e.safeParse(r).success,E0e=an([v0e,b0e,w0e,_0e]),cd=as.strict(),Blt=Qm.extend({requestId:Vk,reason:xe().optional()}),Gk=qs.extend({method:ct("notifications/cancelled"),params:Blt}),Hlt=Je({src:xe(),mimeType:xe().optional(),sizes:or(xe()).optional()}),t8=Je({icons:or(Hlt).optional()}),Xm=Je({name:xe(),title:xe().optional()}),k0e=Xm.extend({...Xm.shape,...t8.shape,version:xe(),websiteUrl:xe().optional()}),Wlt=e8(Je({applyDefaults:si().optional()}),dn(xe(),nn())),Vlt=az(r=>r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0?{form:{}}:r,e8(Je({form:Wlt.optional(),url:Hc.optional()}),dn(xe(),nn()).optional())),Glt=Je({experimental:dn(xe(),Hc).optional(),sampling:Je({context:Hc.optional(),tools:Hc.optional()}).optional(),elicitation:Vlt.optional(),roots:Je({listChanged:si().optional()}).optional()}),Zlt=Ls.extend({protocolVersion:xe(),capabilities:Glt,clientInfo:k0e}),Jlt=Ja.extend({method:ct("initialize"),params:Zlt});var Klt=Je({experimental:dn(xe(),Hc).optional(),logging:Hc.optional(),completions:Hc.optional(),prompts:zt(Je({listChanged:zt(si())})),resources:Je({subscribe:si().optional(),listChanged:si().optional()}).optional(),tools:Je({listChanged:si().optional()}).optional()}),uz=as.extend({protocolVersion:xe(),capabilities:Klt,serverInfo:k0e,instructions:xe().optional()}),Ylt=qs.extend({method:ct("notifications/initialized")});var Zk=Ja.extend({method:ct("ping")}),Xlt=Je({progress:pn(),total:zt(pn()),message:zt(xe())}),Qlt=Je({...Qm.shape,...Xlt.shape,progressToken:m0e}),Jk=qs.extend({method:ct("notifications/progress"),params:Qlt}),e2t=Ls.extend({cursor:g0e.optional()}),Kk=Ja.extend({params:e2t.optional()}),Yk=as.extend({nextCursor:zt(g0e)}),A0e=Je({uri:xe(),mimeType:zt(xe()),_meta:dn(xe(),nn()).optional()}),C0e=A0e.extend({text:xe()}),lz=xe().refine(r=>{try{return atob(r),!0}catch{return!1}},{message:"Invalid Base64 string"}),T0e=A0e.extend({blob:lz}),P0e=Je({...Xm.shape,...t8.shape,uri:xe(),description:zt(xe()),mimeType:zt(xe()),_meta:zt(Bc({}))}),t2t=Je({...Xm.shape,...t8.shape,uriTemplate:xe(),description:zt(xe()),mimeType:zt(xe()),_meta:zt(Bc({}))}),r2t=Kk.extend({method:ct("resources/list")}),fz=Yk.extend({resources:or(P0e)}),n2t=Kk.extend({method:ct("resources/templates/list")}),pz=Yk.extend({resourceTemplates:or(t2t)}),dz=Ls.extend({uri:xe()}),i2t=dz,a2t=Ja.extend({method:ct("resources/read"),params:i2t}),hz=as.extend({contents:or(an([C0e,T0e]))}),o2t=qs.extend({method:ct("notifications/resources/list_changed")}),s2t=dz,c2t=Ja.extend({method:ct("resources/subscribe"),params:s2t}),u2t=dz,l2t=Ja.extend({method:ct("resources/unsubscribe"),params:u2t}),f2t=Qm.extend({uri:xe()}),p2t=qs.extend({method:ct("notifications/resources/updated"),params:f2t}),d2t=Je({name:xe(),description:zt(xe()),required:zt(si())}),h2t=Je({...Xm.shape,...t8.shape,description:zt(xe()),arguments:zt(or(d2t)),_meta:zt(Bc({}))}),m2t=Kk.extend({method:ct("prompts/list")}),mz=Yk.extend({prompts:or(h2t)}),g2t=Ls.extend({name:xe(),arguments:dn(xe(),xe()).optional()}),v2t=Ja.extend({method:ct("prompts/get"),params:g2t}),D0e=Je({type:ct("text"),text:xe(),_meta:dn(xe(),nn()).optional()}),I0e=Je({type:ct("image"),data:lz,mimeType:xe(),_meta:dn(xe(),nn()).optional()}),O0e=Je({type:ct("audio"),data:lz,mimeType:xe(),_meta:dn(xe(),nn()).optional()}),y2t=Je({type:ct("tool_use"),name:xe(),id:xe(),input:Je({}).passthrough(),_meta:zt(Je({}).passthrough())}).passthrough(),b2t=Je({type:ct("resource"),resource:an([C0e,T0e]),_meta:dn(xe(),nn()).optional()}),x2t=P0e.extend({type:ct("resource_link")}),gz=an([D0e,I0e,O0e,x2t,b2t]),w2t=Je({role:Za(["user","assistant"]),content:gz}),vz=as.extend({description:zt(xe()),messages:or(w2t)}),_2t=qs.extend({method:ct("notifications/prompts/list_changed")}),S2t=Je({title:xe().optional(),readOnlyHint:si().optional(),destructiveHint:si().optional(),idempotentHint:si().optional(),openWorldHint:si().optional()}),$0e=Je({...Xm.shape,...t8.shape,description:xe().optional(),inputSchema:Je({type:ct("object"),properties:dn(xe(),Hc).optional(),required:or(xe()).optional()}).catchall(nn()),outputSchema:Je({type:ct("object"),properties:dn(xe(),Hc).optional(),required:or(xe()).optional()}).catchall(nn()).optional(),annotations:zt(S2t),_meta:dn(xe(),nn()).optional()}),E2t=Kk.extend({method:ct("tools/list")}),yz=Yk.extend({tools:or($0e)}),Xk=as.extend({content:or(gz).default([]),structuredContent:dn(xe(),nn()).optional(),isError:zt(si())}),cnr=Xk.or(as.extend({toolResult:nn()})),k2t=Ls.extend({name:xe(),arguments:zt(dn(xe(),nn()))}),A2t=Ja.extend({method:ct("tools/call"),params:k2t}),C2t=qs.extend({method:ct("notifications/tools/list_changed")}),j0e=Za(["debug","info","notice","warning","error","critical","alert","emergency"]),T2t=Ls.extend({level:j0e}),P2t=Ja.extend({method:ct("logging/setLevel"),params:T2t}),D2t=Qm.extend({level:j0e,logger:xe().optional(),data:nn()}),I2t=qs.extend({method:ct("notifications/message"),params:D2t}),O2t=Je({name:xe().optional()}),$2t=Je({hints:zt(or(O2t)),costPriority:zt(pn().min(0).max(1)),speedPriority:zt(pn().min(0).max(1)),intelligencePriority:zt(pn().min(0).max(1))}),j2t=Je({mode:zt(Za(["auto","required","none"]))}),R2t=Je({type:ct("tool_result"),toolUseId:xe().describe("The unique identifier for the corresponding tool call."),content:or(gz).default([]),structuredContent:Je({}).passthrough().optional(),isError:zt(si()),_meta:zt(Je({}).passthrough())}).passthrough(),Hk=XU("type",[D0e,I0e,O0e,y2t,R2t]),N2t=Je({role:Za(["user","assistant"]),content:an([Hk,or(Hk)]),_meta:zt(Je({}).passthrough())}).passthrough(),F2t=Ls.extend({messages:or(N2t),modelPreferences:$2t.optional(),systemPrompt:xe().optional(),includeContext:Za(["none","thisServer","allServers"]).optional(),temperature:pn().optional(),maxTokens:pn().int(),stopSequences:or(xe()).optional(),metadata:Hc.optional(),tools:zt(or($0e)),toolChoice:zt(j2t)}),M2t=Ja.extend({method:ct("sampling/createMessage"),params:F2t}),L2t=as.extend({model:xe(),stopReason:zt(Za(["endTurn","stopSequence","maxTokens","toolUse"]).or(xe())),role:Za(["user","assistant"]),content:an([Hk,or(Hk)])}),q2t=Je({type:ct("boolean"),title:xe().optional(),description:xe().optional(),default:si().optional()}),U2t=Je({type:ct("string"),title:xe().optional(),description:xe().optional(),minLength:pn().optional(),maxLength:pn().optional(),format:Za(["email","uri","date","date-time"]).optional(),default:xe().optional()}),z2t=Je({type:Za(["number","integer"]),title:xe().optional(),description:xe().optional(),minimum:pn().optional(),maximum:pn().optional(),default:pn().optional()}),B2t=Je({type:ct("string"),title:xe().optional(),description:xe().optional(),enum:or(xe()),default:xe().optional()}),H2t=Je({type:ct("string"),title:xe().optional(),description:xe().optional(),oneOf:or(Je({const:xe(),title:xe()})),default:xe().optional()}),W2t=Je({type:ct("string"),title:xe().optional(),description:xe().optional(),enum:or(xe()),enumNames:or(xe()).optional(),default:xe().optional()}),V2t=an([B2t,H2t]),G2t=Je({type:ct("array"),title:xe().optional(),description:xe().optional(),minItems:pn().optional(),maxItems:pn().optional(),items:Je({type:ct("string"),enum:or(xe())}),default:or(xe()).optional()}),Z2t=Je({type:ct("array"),title:xe().optional(),description:xe().optional(),minItems:pn().optional(),maxItems:pn().optional(),items:Je({anyOf:or(Je({const:xe(),title:xe()}))}),default:or(xe()).optional()}),J2t=an([G2t,Z2t]),K2t=an([W2t,V2t,J2t]),Y2t=an([K2t,q2t,U2t,z2t]),X2t=Ls.extend({mode:ct("form").optional(),message:xe(),requestedSchema:Je({type:ct("object"),properties:dn(xe(),Y2t),required:or(xe()).optional()})}),Q2t=Ls.extend({mode:ct("url"),message:xe(),elicitationId:xe(),url:xe().url()}),eft=an([X2t,Q2t]),bz=Ja.extend({method:ct("elicitation/create"),params:eft}),tft=Qm.extend({elicitationId:xe()}),rft=qs.extend({method:ct("notifications/elicitation/complete"),params:tft}),xz=as.extend({action:Za(["accept","decline","cancel"]),content:dn(xe(),an([xe(),pn(),si(),or(xe())])).optional()}),nft=Je({type:ct("ref/resource"),uri:xe()});var ift=Je({type:ct("ref/prompt"),name:xe()}),aft=Ls.extend({ref:an([ift,nft]),argument:Je({name:xe(),value:xe()}),context:Je({arguments:dn(xe(),xe()).optional()}).optional()}),oft=Ja.extend({method:ct("completion/complete"),params:aft});var wz=as.extend({completion:Bc({values:or(xe()).max(100),total:zt(pn().int()),hasMore:zt(si())})}),sft=Je({uri:xe().startsWith("file://"),name:xe().optional(),_meta:dn(xe(),nn()).optional()}),cft=Ja.extend({method:ct("roots/list")}),uft=as.extend({roots:or(sft)}),lft=qs.extend({method:ct("notifications/roots/list_changed")}),unr=an([Zk,Jlt,oft,P2t,v2t,m2t,r2t,n2t,a2t,c2t,l2t,A2t,E2t]),lnr=an([Gk,Jk,Ylt,lft]),fnr=an([cd,L2t,xz,uft]),pnr=an([Zk,M2t,bz,cft]),dnr=an([Gk,Jk,I2t,p2t,o2t,C2t,_2t,rft]),hnr=an([cd,uz,wz,vz,mz,fz,pz,hz,Xk,yz]),Ui=class r extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===xi.UrlElicitationRequired&&n){let i=n;if(i.elicitations)return new oz(i.elicitations,t)}return new r(e,t,n)}},oz=class extends Ui{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(xi.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){var e,t;return(t=(e=this.data)===null||e===void 0?void 0:e.elicitations)!==null&&t!==void 0?t:[]}};var fft=Symbol("Let zodToJsonSchema decide on which parser to use");var Gnr=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function _z(r){let e=Dk(r),t=e?.method;if(!t)throw new Error("Schema is missing a method literal");let n=p3e(t);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Sz(r,e){let t=sd(r,e);if(!t.success)throw t.error;return t.data}var vft=6e4,Qk=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(Gk,t=>{let n=this._requestHandlerAbortControllers.get(t.params.requestId);n?.abort(t.params.reason)}),this.setNotificationHandler(Jk,t=>{this._onprogress(t)}),this.setRequestHandler(Zk,t=>({}))}_setupTimeout(e,t,n,i,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:a,onTimeout:i})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Ui.fromError(xi.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var t,n,i;this._transport=e;let a=(t=this.transport)===null||t===void 0?void 0:t.onclose;this._transport.onclose=()=>{a?.(),this._onclose()};let o=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{o?.(c),this._onerror(c)};let s=(i=this._transport)===null||i===void 0?void 0:i.onmessage;this._transport.onmessage=(c,u)=>{s?.(c,u),cz(c)||S0e(c)?this._onresponse(c):y0e(c)?this._onrequest(c,u):x0e(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=Ui.fromError(xi.ConnectionClosed,"Connection closed");for(let i of t.values())i(n)}_onerror(e){var t;(t=this.onerror)===null||t===void 0||t.call(this,e)}_onnotification(e){var t;let n=(t=this._notificationHandlers.get(e.method))!==null&&t!==void 0?t:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(i=>this._onerror(new Error(`Uncaught error in notification handler: ${i}`)))}_onrequest(e,t){var n,i;let a=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,o=this._transport;if(a===void 0){o?.send({jsonrpc:"2.0",id:e.id,error:{code:xi.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(e.id,s);let c={signal:s.signal,sessionId:o?.sessionId,_meta:(i=e.params)===null||i===void 0?void 0:i._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,l,f)=>this.request(u,l,{...f,relatedRequestId:e.id}),authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo};Promise.resolve().then(()=>a(e,c)).then(u=>{if(!s.signal.aborted)return o?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var l;if(!s.signal.aborted)return o?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:xi.InternalError,message:(l=u.message)!==null&&l!==void 0?l:"Internal error",...u.data!==void 0&&{data:u.data}}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,i=Number(t),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){o(c);return}a(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(t),this._progressHandlers.delete(t),this._cleanupTimeout(t),cz(e))n(e);else{let i=Ui.fromError(e.error.code,e.error.message,e.error.data);n(i)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,t,n){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}=n??{};return new Promise((s,c)=>{var u,l,f,p,d,m;if(!this._transport){c(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(l=n?.signal)===null||l===void 0||l.throwIfAborted();let h=this._requestMessageId++,g={...e,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),g.params={...e.params,_meta:{...((f=e.params)===null||f===void 0?void 0:f._meta)||{},progressToken:h}});let v=k=>{var S;this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),(S=this._transport)===null||S===void 0||S.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(k)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(A=>this._onerror(new Error(`Failed to send cancellation: ${A}`))),c(k)};this._responseHandlers.set(h,k=>{var S;if(!(!((S=n?.signal)===null||S===void 0)&&S.aborted)){if(k instanceof Error)return c(k);try{let A=sd(t,k.result);A.success?s(A.data):c(A.error)}catch(A){c(A)}}}),(p=n?.signal)===null||p===void 0||p.addEventListener("abort",()=>{var k;v((k=n?.signal)===null||k===void 0?void 0:k.reason)});let y=(d=n?.timeout)!==null&&d!==void 0?d:vft,x=()=>v(Ui.fromError(xi.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(h,y,n?.maxTotalTimeout,x,(m=n?.resetTimeoutOnProgress)!==null&&m!==void 0?m:!1),this._transport.send(g,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(k=>{this._cleanupTimeout(h),c(k)})})}async notification(e,t){var n,i;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((i=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&i!==void 0?i:[]).includes(e.method)&&!e.params&&!t?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(u,t).catch(l=>this._onerror(l))});return}let s={...e,jsonrpc:"2.0"};await this._transport.send(s,t)}setRequestHandler(e,t){let n=_z(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=Sz(e,i);return Promise.resolve(t(o,a))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=_z(e);this._notificationHandlers.set(n,i=>{let a=Sz(e,i);return Promise.resolve(t(a))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function R0e(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function N0e(r,e){let t={...r};for(let n in e){let i=n,a=e[i];if(a===void 0)continue;let o=t[i];R0e(o)&&R0e(a)?t[i]={...o,...a}:t[i]=a}return t}var _1e=ur(cH(),1),S1e=ur(w1e(),1);function cmt(){let r=new _1e.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,S1e.default)(r),r}var RA=class{constructor(e){this._ajv=e??cmt()}getValidator(e){var t;let n="$id"in e&&typeof e.$id=="string"?(t=this._ajv.getSchema(e.$id))!==null&&t!==void 0?t:this._ajv.compile(e):this._ajv.compile(e);return i=>n(i)?{valid:!0,data:i,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};function NA(r,e){if(!(!r||e===null||typeof e!="object")){if(r.type==="object"&&r.properties&&typeof r.properties=="object"){let t=e,n=r.properties;for(let i of Object.keys(n)){let a=n[i];t[i]===void 0&&Object.prototype.hasOwnProperty.call(a,"default")&&(t[i]=a.default),t[i]!==void 0&&NA(a,t[i])}}if(Array.isArray(r.anyOf))for(let t of r.anyOf)NA(t,e);if(Array.isArray(r.oneOf))for(let t of r.oneOf)NA(t,e)}}function umt(r){if(!r)return{supportsFormMode:!1,supportsUrlMode:!1};let e=r.form!==void 0,t=r.url!==void 0;return{supportsFormMode:e||!e&&!t,supportsUrlMode:t}}var FA=class extends Qk{constructor(e,t){var n,i;super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(n=t?.capabilities)!==null&&n!==void 0?n:{},this._jsonSchemaValidator=(i=t?.jsonSchemaValidator)!==null&&i!==void 0?i:new RA}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=N0e(this._capabilities,e)}setRequestHandler(e,t){var n,i,a;let o=Dk(e),s=o?.method;if(!s)throw new Error("Schema is missing a method literal");let c;if(Km(s)){let l=s,f=(n=l._zod)===null||n===void 0?void 0:n.def;c=(i=f?.value)!==null&&i!==void 0?i:l.value}else{let l=s,f=l._def;c=(a=f?.value)!==null&&a!==void 0?a:l.value}if(typeof c!="string")throw new Error("Schema method literal must be a string");if(c==="elicitation/create"){let l=async(f,p)=>{var d,m,h;let g=sd(bz,f);if(!g.success){let w=g.error instanceof Error?g.error.message:String(g.error);throw new Ui(xi.InvalidParams,`Invalid elicitation request: ${w}`)}let{params:v}=g.data,y=(d=v.mode)!==null&&d!==void 0?d:"form",{supportsFormMode:x,supportsUrlMode:k}=umt(this._capabilities.elicitation);if(y==="form"&&!x)throw new Ui(xi.InvalidParams,"Client does not support form-mode elicitation requests");if(y==="url"&&!k)throw new Ui(xi.InvalidParams,"Client does not support URL-mode elicitation requests");let S=await Promise.resolve(t(f,p)),A=sd(xz,S);if(!A.success){let w=A.error instanceof Error?A.error.message:String(A.error);throw new Ui(xi.InvalidParams,`Invalid elicitation result: ${w}`)}let $=A.data,O=y==="form"?v.requestedSchema:void 0;if(y==="form"&&$.action==="accept"&&$.content&&O&&!((h=(m=this._capabilities.elicitation)===null||m===void 0?void 0:m.form)===null||h===void 0)&&h.applyDefaults)try{NA(O,$.content)}catch{}return $};return super.setRequestHandler(e,l)}return super.setRequestHandler(e,t)}assertCapability(e,t){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:sz,capabilities:this._capabilities,clientInfo:this._clientInfo}},uz,t);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!h0e.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var t,n,i,a,o;switch(e){case"logging/setLevel":if(!(!((t=this._serverCapabilities)===null||t===void 0)&&t.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var t;switch(e){case"notifications/roots/list_changed":if(!(!((t=this._capabilities.roots)===null||t===void 0)&&t.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},cd,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},wz,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},cd,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},vz,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},mz,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},fz,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},pz,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},hz,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},cd,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},cd,t)}async callTool(e,t=Xk,n){let i=await this.request({method:"tools/call",params:e},t,n),a=this.getToolOutputValidator(e.name);if(a){if(!i.structuredContent&&!i.isError)throw new Ui(xi.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(i.structuredContent)try{let o=a(i.structuredContent);if(!o.valid)throw new Ui(xi.InvalidParams,`Structured content does not match the tool's output schema: ${o.errorMessage}`)}catch(o){throw o instanceof Ui?o:new Ui(xi.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return i}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let t of e)if(t.outputSchema){let n=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,n)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:"tools/list",params:e},yz,t);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var d4e=ur(f4e(),1);import UA from"node:process";import{PassThrough as Fmt}from"node:stream";var LA=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
1139
1139
  `);if(e===-1)return null;let t=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Nmt(t)}clear(){this._buffer=void 0}};function Nmt(r){return E0e.parse(JSON.parse(r))}function p4e(r){return JSON.stringify(r)+`
1140
- `}var Mmt=UA.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Lmt(){let r={};for(let e of Mmt){let t=UA.env[e];t!==void 0&&(t.startsWith("()")||(r[e]=t))}return r}var qA=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new LA,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Fmt)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{var n,i,a,o,s;this._process=(0,d4e.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...Lmt(),...this._serverParams.env},stdio:["pipe","pipe",(i=this._serverParams.stderr)!==null&&i!==void 0?i:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:UA.platform==="win32"&&qmt(),cwd:this._serverParams.cwd}),this._process.on("error",c=>{var u,l;if(c.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}t(c),(l=this.onerror)===null||l===void 0||l.call(this,c)}),this._process.on("spawn",()=>{e()}),this._process.on("close",c=>{var u;this._process=void 0,(u=this.onclose)===null||u===void 0||u.call(this)}),(a=this._process.stdin)===null||a===void 0||a.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),(o=this._process.stdout)===null||o===void 0||o.on("data",c=>{this._readBuffer.append(c),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,t;return this._stderrStream?this._stderrStream:(t=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&t!==void 0?t:null}get pid(){var e,t;return(t=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&t!==void 0?t:null}processReadBuffer(){for(var e,t;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(t=this.onerror)===null||t===void 0||t.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(t=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let i=p4e(e);this._process.stdin.write(i)?t():this._process.stdin.once("drain",t)})}};function qmt(){return"type"in UA}import{spawn as Umt}from"child_process";var kH=15e3,zA=class extends Vt{constructor(t){super(new yc("not used"),t.name);this.serverConfig=t;this.name=t.name}clientPromise;toolsPromise;inspectorProcess;transport;serverProcessPid=null;name="Not defined yet";errorLogged=!1;lastUsed=Date.now();async kill(){if(this.tools=[],console.log(`Closing mcp client ${this.serverConfig.name}`),this.inspectorProcess){console.log(`Stopping MCP Inspector process for ${this.serverConfig.name}`);try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector process: ${t}`)}this.inspectorProcess=void 0}try{await(await this.clientPromise)?.close()}catch{console.log(`MCP client ${this.serverConfig.name} was already failed/closed`)}if(this.transport){try{await this.transport.close(),console.log(`Transport closed for ${this.serverConfig.name}`)}catch(t){console.log(`Error closing transport for ${this.serverConfig.name}: ${t}`)}this.transport=void 0}console.log(`Closed mcp client ${this.serverConfig.name}`)}async buildTools(t,n){if(this.tools.length)return this.tools;if(!this.serverConfig.enabled)return console.debug(`[MCP] Server ${this.serverConfig.name} is disabled, skipping`),[];try{this.clientPromise||(console.log(`Initializing MCP server ${this.serverConfig.name}...`),this.clientPromise=this.buildClient());let i=await this.clientPromise;this.toolsPromise||(this.toolsPromise=this.buildInternalTools(i));let a=await this.toolsPromise;return console.log(`MCP server ${this.serverConfig.name} loaded ${a.length} tools successfully`),a}catch(i){let a=i instanceof Error?i.message:String(i);return this.errorLogged||(this.errorLogged=!0,console.error(`[MCP] Server ${this.serverConfig.name} failed to initialize: ${a}`),console.warn(`[MCP] Server '${this.serverConfig.name}' is unavailable and will be skipped: ${a}`)),[]}}async buildClient(){let t=new FA({name:"Coday MCP Client",version:"1.0.0"},{capabilities:{}});if(this.serverConfig.url)throw new Error("Remote HTTP/HTTPS MCP servers are not supported yet. Use local command-based servers instead.");if(this.serverConfig.command){let n={};if(this.serverConfig.debug&&!this.inspectorProcess){let a=["@modelcontextprotocol/inspector",this.serverConfig.command,...this.serverConfig.args||[]],o={};this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(o.env=this.serverConfig.env),this.serverConfig.cwd&&(o.cwd=this.serverConfig.cwd),console.log(`Starting MCP Inspector process for ${this.serverConfig.name}}`),this.inspectorProcess=Umt("npx",a,{stdio:"inherit",...o}),this.inspectorProcess.on("exit",(s,c)=>{console.log(`MCP Inspector process for ${this.serverConfig.name} exited (code: ${s}, signal: ${c})`)})}n.command=this.serverConfig.command,n.args=this.serverConfig.args||[],this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(n.env=this.serverConfig.env,console.log(`Using custom environment variables for MCP server ${this.serverConfig.name}`)),this.serverConfig.cwd&&(n.cwd=this.serverConfig.cwd,console.log(`Using working directory: ${this.serverConfig.cwd}`)),this.transport=new qA(n),console.log(`Starting MCP server ${this.serverConfig.name} with command: ${n.command}`),this.transport.onerror=i=>{console.error(`MCP server ${this.serverConfig.name} transport error:`,i)},this.transport.onclose=()=>{console.log(`MCP server ${this.serverConfig.name} transport closed`),this.serverProcessPid=null}}else throw new Error(`MCP server ${this.serverConfig.name} has no command configured. Only local command-based servers are supported.`);try{let n=t.connect(this.transport),i=new Promise((a,o)=>setTimeout(()=>o(new Error(`Connection timeout after ${kH}ms`)),kH));return await Promise.race([n,i]),this.transport&&"pid"in this.transport?(this.serverProcessPid=this.transport.pid,console.log(`Successfully connected to MCP server ${this.serverConfig.name} (PID: ${this.serverProcessPid})`)):console.log(`Successfully connected to MCP server ${this.serverConfig.name}`),t}catch(n){await this.cleanupOnError();let i=n instanceof Error?n.message:String(n);throw console.error(`Failed to connect to MCP server ${this.serverConfig.name}: ${i}`),i.includes("docker")||i.includes("Docker")||i.includes("container")||i.includes("Container")?new Error(`MCP server ${this.serverConfig.name} failed to start. This may be because Docker is not available or the Docker container failed to start. Original error: ${i}`):i.includes("timeout")||i.includes("Connection timeout")?new Error(`MCP server ${this.serverConfig.name} did not respond within ${kH}ms. Check if the server command is correct and the server starts quickly. Original error: ${i}`):i.includes("ENOENT")||i.includes("command not found")?new Error(`MCP server ${this.serverConfig.name} command not found. Check that the command '${this.serverConfig.command}' is available in your PATH. Original error: ${i}`):new Error(`MCP server ${this.serverConfig.name} connection failed: ${i}`)}}async cleanupOnError(){if(console.log(`Cleaning up failed MCP connection for ${this.serverConfig.name}`),this.inspectorProcess){try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector during cleanup: ${t}`)}this.inspectorProcess=void 0}if(this.transport){try{await this.transport.close()}catch(t){console.log(`Error closing transport during cleanup: ${t}`)}this.transport=void 0}if(this.serverProcessPid){try{process.kill(this.serverProcessPid,0),console.log(`Force killing MCP server process ${this.serverProcessPid} for ${this.serverConfig.name}`),process.kill(this.serverProcessPid,"SIGTERM"),await new Promise(t=>setTimeout(t,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(t){t.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${t}`)}this.serverProcessPid=null}}async buildInternalTools(t){let n=[];try{let i=await t.listResourceTemplates();if(i&&i.templates&&Array.isArray(i.templates))for(let a of i.templates)n.push(this.createResourceTool(this.serverConfig,t,a))}catch(i){i instanceof Error&&!i.message.includes("-32601: Method not found")?console.warn(`[MCP] Error listing resource templates from server ${this.serverConfig.name}: ${i}`):console.debug(`[MCP] Server ${this.serverConfig.name} doesn't support resource templates, continuing with tools only.`)}try{let i=await t.listTools();if(i&&i.tools&&Array.isArray(i.tools))for(let a of i.tools)n.push(this.createFunctionTool(this.serverConfig,t,a))}catch(i){console.warn(`[MCP] Error listing tools from server ${this.serverConfig.name}: ${i}`)}if(this.serverConfig.debug){let i=n.map(a=>`- ${a.function.name}
1140
+ `}var Mmt=UA.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function Lmt(){let r={};for(let e of Mmt){let t=UA.env[e];t!==void 0&&(t.startsWith("()")||(r[e]=t))}return r}var qA=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new LA,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Fmt)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,t)=>{var n,i,a,o,s;this._process=(0,d4e.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...Lmt(),...this._serverParams.env},stdio:["pipe","pipe",(i=this._serverParams.stderr)!==null&&i!==void 0?i:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:UA.platform==="win32"&&qmt(),cwd:this._serverParams.cwd}),this._process.on("error",c=>{var u,l;if(c.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}t(c),(l=this.onerror)===null||l===void 0||l.call(this,c)}),this._process.on("spawn",()=>{e()}),this._process.on("close",c=>{var u;this._process=void 0,(u=this.onclose)===null||u===void 0||u.call(this)}),(a=this._process.stdin)===null||a===void 0||a.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),(o=this._process.stdout)===null||o===void 0||o.on("data",c=>{this._readBuffer.append(c),this.processReadBuffer()}),(s=this._process.stdout)===null||s===void 0||s.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,t;return this._stderrStream?this._stderrStream:(t=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&t!==void 0?t:null}get pid(){var e,t;return(t=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&t!==void 0?t:null}processReadBuffer(){for(var e,t;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(t=this.onerror)===null||t===void 0||t.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(t=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let i=p4e(e);this._process.stdin.write(i)?t():this._process.stdin.once("drain",t)})}};function qmt(){return"type"in UA}import{spawn as Umt}from"child_process";var kH=15e3,zA=class extends Vt{constructor(t){super(new yc("not used"),t.name);this.serverConfig=t;this.name=t.name}clientPromise;toolsPromise;inspectorProcess;transport;serverProcessPid=null;name="Not defined yet";errorLogged=!1;lastUsed=Date.now();async kill(){if(this.tools=[],console.log(`Closing mcp client ${this.serverConfig.name}`),this.inspectorProcess){console.log(`Stopping MCP Inspector process for ${this.serverConfig.name}`);try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector process: ${t}`)}this.inspectorProcess=void 0}try{await(await this.clientPromise)?.close()}catch{console.log(`MCP client ${this.serverConfig.name} was already failed/closed`)}if(this.transport){try{await this.transport.close(),console.log(`Transport closed for ${this.serverConfig.name}`),this.serverProcessPid=null}catch(t){console.log(`Error closing transport for ${this.serverConfig.name}: ${t}`)}this.transport=void 0}if(this.serverProcessPid){try{process.kill(this.serverProcessPid,0),console.log(`Force killing MCP server process ${this.serverProcessPid} for ${this.serverConfig.name}`),process.kill(this.serverProcessPid,"SIGTERM"),await new Promise(t=>setTimeout(t,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(t){t.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${t}`)}this.serverProcessPid=null}console.log(`Closed mcp client ${this.serverConfig.name}`)}async buildTools(t,n){if(this.tools.length)return this.tools;if(!this.serverConfig.enabled)return console.debug(`[MCP] Server ${this.serverConfig.name} is disabled, skipping`),[];try{this.clientPromise||(console.log(`Initializing MCP server ${this.serverConfig.name}...`),this.clientPromise=this.buildClient());let i=await this.clientPromise;this.toolsPromise||(this.toolsPromise=this.buildInternalTools(i));let a=await this.toolsPromise;return console.log(`MCP server ${this.serverConfig.name} loaded ${a.length} tools successfully`),a}catch(i){let a=i instanceof Error?i.message:String(i);return this.errorLogged||(this.errorLogged=!0,console.error(`[MCP] Server ${this.serverConfig.name} failed to initialize: ${a}`),console.warn(`[MCP] Server '${this.serverConfig.name}' is unavailable and will be skipped: ${a}`)),[]}}async buildClient(){let t=new FA({name:"Coday MCP Client",version:"1.0.0"},{capabilities:{}});if(this.serverConfig.url)throw new Error("Remote HTTP/HTTPS MCP servers are not supported yet. Use local command-based servers instead.");if(this.serverConfig.command){let n={};if(this.serverConfig.debug&&!this.inspectorProcess){let a=["@modelcontextprotocol/inspector",this.serverConfig.command,...this.serverConfig.args||[]],o={};this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(o.env=this.serverConfig.env),this.serverConfig.cwd&&(o.cwd=this.serverConfig.cwd),console.log(`Starting MCP Inspector process for ${this.serverConfig.name}}`),this.inspectorProcess=Umt("npx",a,{stdio:"inherit",...o}),this.inspectorProcess.on("exit",(s,c)=>{console.log(`MCP Inspector process for ${this.serverConfig.name} exited (code: ${s}, signal: ${c})`)})}n.command=this.serverConfig.command,n.args=this.serverConfig.args||[],this.serverConfig.env&&Object.keys(this.serverConfig.env).length>0&&(n.env=this.serverConfig.env,console.log(`Using custom environment variables for MCP server ${this.serverConfig.name}`)),this.serverConfig.cwd&&(n.cwd=this.serverConfig.cwd,console.log(`Using working directory: ${this.serverConfig.cwd}`)),this.transport=new qA(n),console.log(`Starting MCP server ${this.serverConfig.name} with command: ${n.command}`),this.transport.onerror=i=>{console.error(`MCP server ${this.serverConfig.name} transport error:`,i)},this.transport.onclose=()=>{console.log(`MCP server ${this.serverConfig.name} transport closed`),this.serverProcessPid=null}}else throw new Error(`MCP server ${this.serverConfig.name} has no command configured. Only local command-based servers are supported.`);try{let n=t.connect(this.transport),i,a=new Promise((o,s)=>{i=setTimeout(()=>s(new Error(`Connection timeout after ${kH}ms`)),kH)});try{await Promise.race([n,a])}finally{clearTimeout(i)}return this.transport&&"pid"in this.transport?(this.serverProcessPid=this.transport.pid,console.log(`Successfully connected to MCP server ${this.serverConfig.name} (PID: ${this.serverProcessPid})`)):console.log(`Successfully connected to MCP server ${this.serverConfig.name}`),t}catch(n){await this.cleanupOnError();let i=n instanceof Error?n.message:String(n);throw console.error(`Failed to connect to MCP server ${this.serverConfig.name}: ${i}`),i.includes("docker")||i.includes("Docker")||i.includes("container")||i.includes("Container")?new Error(`MCP server ${this.serverConfig.name} failed to start. This may be because Docker is not available or the Docker container failed to start. Original error: ${i}`):i.includes("timeout")||i.includes("Connection timeout")?new Error(`MCP server ${this.serverConfig.name} did not respond within ${kH}ms. Check if the server command is correct and the server starts quickly. Original error: ${i}`):i.includes("ENOENT")||i.includes("command not found")?new Error(`MCP server ${this.serverConfig.name} command not found. Check that the command '${this.serverConfig.command}' is available in your PATH. Original error: ${i}`):new Error(`MCP server ${this.serverConfig.name} connection failed: ${i}`)}}async cleanupOnError(){if(console.log(`Cleaning up failed MCP connection for ${this.serverConfig.name}`),this.inspectorProcess){try{this.inspectorProcess.kill("SIGTERM"),await new Promise(t=>setTimeout(t,100)),this.inspectorProcess.killed||this.inspectorProcess.kill("SIGKILL")}catch(t){console.log(`Error killing inspector during cleanup: ${t}`)}this.inspectorProcess=void 0}if(this.transport){try{await this.transport.close()}catch(t){console.log(`Error closing transport during cleanup: ${t}`)}this.transport=void 0}if(this.serverProcessPid){try{process.kill(this.serverProcessPid,0),console.log(`Force killing MCP server process ${this.serverProcessPid} for ${this.serverConfig.name}`),process.kill(this.serverProcessPid,"SIGTERM"),await new Promise(t=>setTimeout(t,100));try{process.kill(this.serverProcessPid,0),process.kill(this.serverProcessPid,"SIGKILL"),console.log(`Force killed with SIGKILL: ${this.serverProcessPid}`)}catch{}}catch(t){t.code!=="ESRCH"&&console.log(`Error killing MCP server process ${this.serverProcessPid}: ${t}`)}this.serverProcessPid=null}}async buildInternalTools(t){let n=[];try{let i=await t.listResourceTemplates();if(i&&i.templates&&Array.isArray(i.templates))for(let a of i.templates)n.push(this.createResourceTool(this.serverConfig,t,a))}catch(i){i instanceof Error&&!i.message.includes("-32601: Method not found")?console.warn(`[MCP] Error listing resource templates from server ${this.serverConfig.name}: ${i}`):console.debug(`[MCP] Server ${this.serverConfig.name} doesn't support resource templates, continuing with tools only.`)}try{let i=await t.listTools();if(i&&i.tools&&Array.isArray(i.tools))for(let a of i.tools)n.push(this.createFunctionTool(this.serverConfig,t,a))}catch(i){console.warn(`[MCP] Error listing tools from server ${this.serverConfig.name}: ${i}`)}if(this.serverConfig.debug){let i=n.map(a=>`- ${a.function.name}
1141
1141
  `).join();console.debug(`[MCP] ${this.serverConfig.name}:
1142
1142
  ${i}`)}return n}createResourceTool(t,n,i){let a=`mcp__${t.id}__${i.name}`,o=async u=>{try{this.lastUsed=Date.now();let l=i.uriTemplate.replace(/\{([^}]+)\}/g,(p,d)=>encodeURIComponent(u[d]||"")),f=await n.readResource({uri:l});if(!f||!f.contents)throw new Error(`No content returned from resource ${i.name}`);return f.contents.map(p=>"text"in p?{uri:p.uri,text:p.text,mimeType:p.mimeType||"text/plain"}:"blob"in p?{uri:p.uri,blob:p.blob,mimeType:p.mimeType||"application/octet-stream"}:p)}catch(l){throw console.error(`[MCP] Error retrieving resource ${i.name}: ${l}`),new Error(`Failed to retrieve resource: ${l}`)}},s={},c=i.uriTemplate.match(/\{([^}]+)\}/g)||[];for(let u of c){let l=u.slice(1,-1);s[l]={type:"string",description:`Parameter ${l} for resource ${i.name}`}}return{type:"function",function:{name:a,description:i.description||`Resource from MCP server ${t.name}`,parameters:{type:"object",properties:s},parse:JSON.parse,function:o}}}createFunctionTool(t,n,i){let a=`${t.name}__${i.name}`,o=async s=>{this.lastUsed=Date.now(),this.serverConfig.debug&&console.debug(`[MCP] ${a} input:
1143
1143
 
@@ -1154,7 +1154,7 @@ Maximum wait time is 300 seconds (5 minutes).`,parameters:{type:"object",propert
1154
1154
  `):"No threads found."}catch(l){let f=`Failed to list threads: ${l instanceof Error?l.message:"Unknown error"}`;return this.interactor.error(f),f}}}};i.push(s);let c={type:"function",function:{name:`${this.name}__get_thread_content`,description:"Get the message content (user and assistant messages only, no tool calls) of a specific thread by its id. Useful to query or summarize another thread without switching to it.",parameters:{type:"object",properties:{threadId:{type:"string",description:"The id of the thread to read."},lastN:{type:"number",description:"Optional: only return the last N text messages. If omitted, returns all messages."}}},parse:JSON.parse,function:async({threadId:l,lastN:f})=>{try{let p=await this.threadService.getThread(a,l);if(!p)return`Thread '${l}' not found.`;if(!rn(p,o))return`Access denied: thread '${l}' belongs to another user.`;let{messages:d}=await p.getMessages(void 0,void 0),m=d.filter(h=>h instanceof $t).map(h=>{let g=h.role==="user"?`[${h.name||o}]`:`[${h.name||"assistant"}]`,v=h.content.filter(y=>y.type==="text").map(y=>y.content).join(`
1155
1155
  `);return`${g} ${v}`});return f&&f>0&&(m=m.slice(-f)),m.length?m.join(`
1156
1156
 
1157
- `):"Thread has no text messages."}catch(p){let d=`Failed to get thread content: ${p instanceof Error?p.message:"Unknown error"}`;return this.interactor.error(d),d}}}};i.push(c);let u={type:"function",function:{name:`${this.name}__update_thread`,description:"Update the name and/or summary of a thread. Defaults to the current thread if no threadId is provided. Use this to rename or summarize a thread after a conversation.",parameters:{type:"object",properties:{name:{type:"string",description:"New name for the thread. Short, descriptive title of the conversation."},summary:{type:"string",description:"Summary of the thread content. 2-4 sentences capturing the main topics and outcomes."},threadId:{type:"string",description:"Id of the thread to update. Defaults to the current thread if omitted."}}},parse:JSON.parse,function:async({name:l,summary:f,threadId:p})=>{try{let d=p??t.aiThread?.id;if(!d)return"No thread id provided and no current thread available.";if(!l&&!f)return"At least one of name or summary must be provided.";let m=await this.threadService.getThread(a,d);if(!m)return`Thread '${d}' not found.`;if(!rn(m,o))return`Access denied: thread '${d}' belongs to another user.`;l!==void 0&&(m.name=l),f!==void 0&&(m.summary=f),await this.threadService.getThreadRepository(a).save(a,m),this.threadService.clearCache(a),this.interactor.sendEvent(new gc({threadId:d,name:l,summary:f}));let g=[];return l!==void 0&&g.push(`name: "${l}"`),f!==void 0&&g.push("summary updated"),`Thread '${d}' updated: ${g.join(", ")}.`}catch(d){let m=`Failed to update thread: ${d instanceof Error?d.message:"Unknown error"}`;return this.interactor.error(m),m}}}};return i.push(u),i}};var j8=class extends Vt{constructor(t,n,i,a){super(t,i,a);this.memoryService=n}static TYPE="MEMORY";async buildTools(t,n){let i=[],a=async({title:d})=>{try{if(d){let m=this.memoryService.listMemories("PROJECT",n),h=this.memoryService.listMemories("USER",n),v=[...m,...h].find(y=>y.title===d);return v?`# ${v.title}
1157
+ `):"Thread has no text messages."}catch(p){let d=`Failed to get thread content: ${p instanceof Error?p.message:"Unknown error"}`;return this.interactor.error(d),d}}}};i.push(c);let u={type:"function",function:{name:`${this.name}__update_thread`,description:"Update the name and/or summary of a thread. Defaults to the current thread if no threadId is provided. Use this to rename or summarize a thread after a conversation.",parameters:{type:"object",properties:{name:{type:"string",description:"New name for the thread. Short, descriptive title of the conversation."},summary:{type:"string",description:"Summary of the thread content. 2-4 sentences capturing the main topics and outcomes."},threadId:{type:"string",description:"Id of the thread to update. Defaults to the current thread if omitted."}}},parse:JSON.parse,function:async({name:l,summary:f,threadId:p})=>{try{let d=p??t.aiThread?.id;if(!d)return"No thread id provided and no current thread available.";if(!l&&!f)return"At least one of name or summary must be provided.";let m=await this.threadService.getThread(a,d);if(!m)return`Thread '${d}' not found.`;if(!rn(m,o))return`Access denied: thread '${d}' belongs to another user.`;await this.threadService.updateThread(a,d,{name:l,summary:f}),this.interactor.sendEvent(new gc({threadId:d,name:l,summary:f}));let h=[];return l!==void 0&&h.push(`name: "${l}"`),f!==void 0&&h.push("summary updated"),`Thread '${d}' updated: ${h.join(", ")}.`}catch(d){let m=`Failed to update thread: ${d instanceof Error?d.message:"Unknown error"}`;return this.interactor.error(m),m}}}};return i.push(u),i}};var j8=class extends Vt{constructor(t,n,i,a){super(t,i,a);this.memoryService=n}static TYPE="MEMORY";async buildTools(t,n){let i=[],a=async({title:d})=>{try{if(d){let m=this.memoryService.listMemories("PROJECT",n),h=this.memoryService.listMemories("USER",n),v=[...m,...h].find(y=>y.title===d);return v?`# ${v.title}
1158
1158
 
1159
1159
  **Level:** ${v.level}
1160
1160
 
@@ -1417,7 +1417,7 @@ JSON:`,c,u;try{let p=(await this.aiClient.complete(s,{maxTokens:300})).replace(/
1417
1417
 
1418
1418
  `;e.writableEnded||e.write(o)}}catch(t){ue("THREAD_CODAY","Error replaying thread history:",t)}}removeConnection(e){this.connections.delete(e),ue("THREAD_CODAY",`Removed SSE connection from thread ${this.threadId} (remaining: ${this.connections.size})`)}get connectionCount(){return this.connections.size}updateActivity(){this.lastActivity=Date.now(),this.resetInactivityTimeout()}resetInactivityTimeout(){this.inactivityTimeout&&clearTimeout(this.inactivityTimeout);let e=this.isOneshot?r.ONESHOT_TIMEOUT:r.INTERACTIVE_TIMEOUT;this.inactivityTimeout=setTimeout(()=>{let t=Date.now()-this.lastActivity;ue("THREAD_CODAY",`Inactivity timeout reached for thread ${this.threadId} after ${Math.round(t/1e3)}s`),this.onTimeout(this.threadId)},e)}markAsOneshot(){this.isOneshot=!0,this.resetInactivityTimeout()}getInactiveTime(){return Date.now()-this.lastActivity}prepareCoday(){if(this.updateActivity(),this.coday)return ue("THREAD_CODAY",`Coday already running for thread ${this.threadId}`),!1;ue("THREAD_CODAY",`Creating Coday instance for thread ${this.threadId}`),console.log(`[THREAD_CODAY] Preparing instance for thread '${this.threadId}' (project: ${this.projectName}, user: ${this.username})`);let e=new yc(this.threadId),t=new H2(this.options.configDir,this.username,e),n=new _m(e,this.projectService,this.options.configDir),i=new mm(n,t),a=new hm(t,n,e),o=new ym(n,t),s=new vm(t,n,e);return e.events.subscribe(c=>{this.broadcastEvent(c)}),this.coday=new fT(e,this.options,{user:t,project:n,projectService:this.projectService,integration:i,integrationConfig:a,memory:o,mcp:s,mcpPool:this.mcpPool,thread:this.threadService,prompt:this.promptService,logger:this.logger,options:this.options}),console.log(`[THREAD_CODAY] Instance created for thread '${this.threadId}'`),!0}startCoday(){this.updateActivity();let e=this.prepareCoday();return this.coday?(this.coday.run().catch(t=>{ue("THREAD_CODAY",`Error during Coday run for thread ${this.threadId}:`,t),console.error(`Coday run failed for thread ${this.threadId}:`,t)}).finally(()=>{ue("THREAD_CODAY",`Coday run finished for thread ${this.threadId}`)}),e):!1}sendHeartbeat(){if(this.connections.size!==0)try{let e=new _0({});this.broadcastEvent(e)}catch(e){ue("THREAD_CODAY",`Error sending heartbeat for thread ${this.threadId}:`,e)}}broadcastEvent(e){e instanceof gc&&(e.name||e.summary)&&(ue("THREAD_CODAY",`Updating thread cache for ${this.threadId} name/summary`),this.threadService.updateThread(this.projectName,this.threadId,{name:e.name,summary:e.summary}).catch(n=>{ue("THREAD_CODAY","Error updating thread cache:",n)}));let t=`data: ${JSON.stringify(e)}
1419
1419
 
1420
- `;for(let n of this.connections)try{n.writableEnded?this.connections.delete(n):n.write(t)}catch(i){ue("THREAD_CODAY","Error broadcasting to connection:",i),this.connections.delete(n)}}stop(){this.coday?.stop()}async handleOAuthCallback(e){if(!this.coday){ue("THREAD_CODAY",`Cannot handle OAuth callback: Coday not initialized for thread ${this.threadId}`);return}if(!this.coday.services.agent){ue("THREAD_CODAY","Cannot handle OAuth callback: Agent service not initialized");return}let n=this.coday.services.agent?.toolbox;if(!n){ue("THREAD_CODAY","Cannot handle OAuth callback: Toolbox not initialized");return}ue("THREAD_CODAY",`Routing OAuth callback for ${e.integrationName}`),await n.handleOAuthCallback(e)}async cleanup(){ue("THREAD_CODAY",`Cleaning up thread ${this.threadId}`),this.inactivityTimeout&&(clearTimeout(this.inactivityTimeout),this.inactivityTimeout=void 0);for(let e of this.connections)try{e.end()}catch(t){ue("THREAD_CODAY","Error closing connection:",t)}if(this.connections.clear(),this.coday){let e=this.coday.context?.aiThread,t=this.coday.aiClientProvider,n=t?.getClient(void 0,"SMALL")??t?.getClient(void 0);e&&n?new pT(n,this.threadService).process(e,this.projectName):ue("THREAD_CODAY",`Skipping post-processing for thread ${this.threadId}: no thread or AI client`)}if(this.coday){try{await this.coday.kill()}catch(e){ue("THREAD_CODAY","Error during Coday kill:",e)}this.coday=void 0}}},hT=class r{constructor(e,t,n,i,a){this.logger=e;this.projectService=t;this.threadService=n;this.promptService=i;this.mcpPool=a;this.heartbeatInterval=setInterval(()=>this.sendHeartbeats(),r.HEARTBEAT_INTERVAL),ue("THREAD_CODAY_MANAGER","Heartbeat mechanism started")}instances=new Map;heartbeatInterval;static HEARTBEAT_INTERVAL=3e4;sendHeartbeats(){for(let e of this.instances.values())e.connectionCount>0&&e.sendHeartbeat()}handleInstanceTimeout=async e=>{ue("THREAD_CODAY_MANAGER",`Handling timeout for thread ${e}`),await this.cleanup(e)};getOrCreate(e,t,n,i,a){let o=this.instances.get(e);return o?ue("THREAD_CODAY",`Reusing existing instance for thread ${e}`):(ue("THREAD_CODAY",`Creating new instance for thread ${e}`),o=new dT(e,t,n,i,this.logger,this.projectService,this.threadService,this.promptService,this.mcpPool,this.handleInstanceTimeout),this.instances.set(e,o)),o.addConnection(a),o}createWithoutConnection(e,t,n,i){let a=this.instances.get(e);return a?ue("THREAD_CODAY",`Reusing existing instance for thread ${e}`):(ue("THREAD_CODAY",`Creating new instance for thread ${e} (no SSE connection)`),a=new dT(e,t,n,i,this.logger,this.projectService,this.threadService,this.promptService,this.mcpPool,this.handleInstanceTimeout),a.markAsOneshot(),this.instances.set(e,a)),a}get(e){return this.instances.get(e)}removeConnection(e,t){let n=this.instances.get(e);n&&(n.removeConnection(t),n.connectionCount===0&&ue("THREAD_CODAY",`Thread ${e} has no active connections but instance kept alive`))}stop(e){let t=this.instances.get(e);t&&t.stop()}async cleanup(e){let t=this.instances.get(e);t&&(await this.mcpPool.releaseThread(e),await t.cleanup(),this.instances.delete(e),ue("THREAD_CODAY",`Removed instance for thread ${e}`))}getStats(){let e=0,t=0;for(let n of this.instances.values())n.connectionCount>0&&e++,n.isOneshot&&t++;return{total:this.instances.size,withConnections:e,oneshot:t}}async shutdown(){ue("THREAD_CODAY_MANAGER",`Shutting down ${this.instances.size} thread instances`),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),ue("THREAD_CODAY_MANAGER","Heartbeat mechanism stopped"));let e=[];for(let[t,n]of this.instances.entries())ue("THREAD_CODAY_MANAGER",`Cleaning up thread ${t}`),e.push(n.cleanup());await Promise.all(e),this.instances.clear(),await this.mcpPool.shutdown(),ue("THREAD_CODAY_MANAGER","All thread instances cleaned up")}};async function I7e(r,e=100){let t=await import("node:net");return new Promise((n,i)=>{function a(o,s){let c=t.createServer();c.listen(o,()=>{c.close(()=>{ue("PORT",`Port ${o} is available`),n(o)})}),c.on("error",u=>{u.code==="EADDRINUSE"?s>0?(ue("PORT",`Port ${o} is in use, trying next`),a(o+1,s-1)):i(new Error(`Could not find an available port starting from ${r}`)):i(u)})}a(r,e)})}function O7e(r,e,t){r.get("/api/config/user",(n,i)=>{try{let a=t(n);if(!a){i.status(401).json({error:"Username not found in request headers"});return}ue("CONFIG",`GET user config for: ${a}`);let c={...e.getUserService(a).getConfigForClient(),username:a};i.status(200).json(c)}catch(a){console.error("Error retrieving user config:",a),i.status(500).json({error:"Failed to retrieve user configuration"})}}),r.put("/api/config/user",(n,i)=>{try{let a=t(n);if(!a){i.status(401).json({error:"Username not found in request headers"});return}let o=n.body;if(!o||typeof o!="object"){i.status(422).json({error:"Invalid configuration format"});return}if(typeof o.version!="number"){i.status(422).json({error:"Configuration must have a version number"});return}ue("CONFIG",`PUT user config for: ${a}`),e.getUserService(a).updateConfigFromClient(o),i.status(200).json({success:!0,message:"User configuration updated successfully"})}catch(a){console.error("Error updating user config:",a);let o=a instanceof Error?a.message:"Unknown error";i.status(500).json({error:`Failed to update user configuration: ${o}`})}})}function je(r){return Array.isArray(r)?r[0]||"":r||""}function $7e(r,e){r.get("/api/projects",(t,n)=>{try{ue("PROJECT","GET all projects");let i=e.listProjects(),a=e.getDefaultProject(),o=e.getForcedMode();n.status(200).json({projects:i,defaultProject:a,forcedProject:o?a:null})}catch(i){console.error("Error listing projects:",i),n.status(500).json({error:"Failed to list projects"})}}),r.get("/api/projects/:name",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`GET project: ${i}`);let a=e.getProject(i);if(!a){n.status(404).json({error:`Project '${i}' not found`});return}n.status(200).json(a)}catch(i){console.error("Error retrieving project:",i),n.status(500).json({error:"Failed to retrieve project"})}}),r.post("/api/projects",(t,n)=>{try{let{name:i,path:a}=t.body;if(!i||!a){n.status(400).json({error:"Project name and path are required"});return}ue("PROJECT",`POST create project: ${i} at ${a}`),e.createProject(i,a),n.status(201).json({success:!0,message:`Project '${i}' created successfully`})}catch(i){console.error("Error creating project:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to create project: ${a}`})}}),r.get("/api/projects/:name/config",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`GET project config: ${i}`);let a=e.getProjectConfigForClient(i);if(!a){n.status(404).json({error:`Project '${i}' not found`});return}n.status(200).json(a)}catch(i){console.error("Error retrieving project config:",i),n.status(500).json({error:"Failed to retrieve project configuration"})}}),r.put("/api/projects/:name/config",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}let a=t.body;if(!a||typeof a!="object"){n.status(422).json({error:"Invalid configuration format"});return}if(typeof a.version!="number"){n.status(422).json({error:"Configuration must have a version number"});return}if(!a.path||typeof a.path!="string"){n.status(422).json({error:"Configuration must have a valid path"});return}ue("PROJECT",`PUT project config: ${i}`),e.updateProjectConfigFromClient(i,a),n.status(200).json({success:!0,message:"Project configuration updated successfully"})}catch(i){console.error("Error updating project config:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to update project configuration: ${a}`})}}),r.delete("/api/projects/:name",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`DELETE project: ${i}`),e.deleteProject(i),n.status(200).json({success:!0,message:`Project '${i}' deleted successfully`})}catch(i){console.error("Error deleting project:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to delete project: ${a}`})}})}import{existsSync as Y9t,readFileSync as X9t}from"fs";function j7e(r,e,t,n,i,a){r.get("/api/projects/:projectName/threads",async(o,s)=>{try{let c=je(o.params.projectName);if(!c){s.status(400).json({error:"Project name is required"});return}let u=i(o);if(!u){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET threads for project: ${c}, user: ${u}`);let l=await e.listThreads(c,u);s.status(200).json(l)}catch(c){console.error("Error listing threads:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to list threads: ${u}`})}}),r.post("/api/projects/:projectName/threads",async(o,s)=>{try{let c=je(o.params.projectName);if(!c){s.status(400).json({error:"Project name is required"});return}let u=i(o);if(!u){s.status(401).json({error:"Authentication required"});return}let{name:l}=o.body;ue("THREAD",`POST create thread in project: ${c}, user: ${u}, name: ${l||"untitled"}`);let f=await e.createThread(c,u,l);s.status(201).json({success:!0,thread:{id:f.id,name:f.name,projectId:f.projectId,username:f.username,createdDate:f.createdDate,modifiedDate:f.modifiedDate}})}catch(c){console.error("Error creating thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to create thread: ${u}`})}}),r.get("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET thread: ${u} from project: ${c}`);let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}s.status(200).json({id:f.id,name:f.name,projectId:f.projectId,username:f.username,summary:f.summary,createdDate:f.createdDate,modifiedDate:f.modifiedDate,price:f.price,messageCount:f.messagesLength,users:f.users})}catch(c){console.error("Error retrieving thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to retrieve thread: ${u}`})}}),r.put("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let{name:f,users:p}=o.body,d=await e.getThread(c,u);if(!d){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(d,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}let m;if(p!==void 0){if(!rn(d,l)){s.status(403).json({error:"Access denied: only thread participants can modify the users list"});return}if(!Array.isArray(p)){s.status(400).json({error:"Invalid users format: must be an array"});return}for(let g of p)if(!g||typeof g.userId!="string"||g.userId.trim()===""){s.status(400).json({error:"Invalid users format: each user must have a non-empty userId string"});return}m=p}ue("THREAD",`PUT update thread: ${u} in project: ${c}`);let h=await e.updateThread(c,u,{name:f,users:m});if(m!==void 0){let v=n.get(u)?.coday?.context?.aiThread;v&&(v.users=m,ue("THREAD",`Synced users to live AiThread for thread ${u}`))}s.status(200).json({success:!0,thread:{id:h.id,name:h.name,projectId:h.projectId,modifiedDate:h.modifiedDate}})}catch(c){console.error("Error updating thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to update thread: ${u}`})}}),r.get("/api/projects/:projectName/threads/:threadId/messages",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET messages for thread: ${u} in project: ${c}`);let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}let{messages:p}=await f.getMessages(void 0,void 0);s.status(200).json({messages:p})}catch(c){console.error("Error retrieving thread messages:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to retrieve thread messages: ${u}`})}}),r.post("/api/projects/:projectName/threads/:threadId/star",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}if(!await e.getThread(c,u)){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}ue("THREAD",`POST star thread: ${u} in project: ${c} by user: ${l}`);let p=await e.starThread(c,u,l);s.status(200).json({success:!0,thread:{id:p.id,starring:p.starring,modifiedDate:p.modifiedDate}})}catch(c){console.error("Error starring thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to star thread: ${u}`})}}),r.delete("/api/projects/:projectName/threads/:threadId/star",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}if(!await e.getThread(c,u)){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}ue("THREAD",`DELETE unstar thread: ${u} in project: ${c} by user: ${l}`);let p=await e.unstarThread(c,u,l);s.status(200).json({success:!0,thread:{id:p.id,starring:p.starring,modifiedDate:p.modifiedDate}})}catch(c){console.error("Error unstarring thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to unstar thread: ${u}`})}}),r.post("/api/projects/:projectName/threads/:threadId/stop",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}ue("THREAD",`POST stop thread: ${u} in project: ${c}`),n.stop(u),s.status(200).json({success:!0,message:"Stop signal sent successfully"})}catch(c){console.error("Error stopping thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to stop thread: ${u}`})}}),r.delete("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}ue("THREAD",`DELETE
1420
+ `;for(let n of this.connections)try{n.writableEnded?this.connections.delete(n):n.write(t)}catch(i){ue("THREAD_CODAY","Error broadcasting to connection:",i),this.connections.delete(n)}}stop(){this.coday?.stop()}async handleOAuthCallback(e){if(!this.coday){ue("THREAD_CODAY",`Cannot handle OAuth callback: Coday not initialized for thread ${this.threadId}`);return}if(!this.coday.services.agent){ue("THREAD_CODAY","Cannot handle OAuth callback: Agent service not initialized");return}let n=this.coday.services.agent?.toolbox;if(!n){ue("THREAD_CODAY","Cannot handle OAuth callback: Toolbox not initialized");return}ue("THREAD_CODAY",`Routing OAuth callback for ${e.integrationName}`),await n.handleOAuthCallback(e)}async cleanup(){ue("THREAD_CODAY",`Cleaning up thread ${this.threadId}`),this.inactivityTimeout&&(clearTimeout(this.inactivityTimeout),this.inactivityTimeout=void 0);for(let e of this.connections)try{e.end()}catch(t){ue("THREAD_CODAY","Error closing connection:",t)}if(this.connections.clear(),this.coday){let e=this.coday.context?.aiThread,t=this.coday.aiClientProvider,n=t?.getClient(void 0,"SMALL")??t?.getClient(void 0);e&&n?new pT(n,this.threadService).process(e,this.projectName):ue("THREAD_CODAY",`Skipping post-processing for thread ${this.threadId}: no thread or AI client`)}if(this.coday){try{await this.coday.kill()}catch(e){ue("THREAD_CODAY","Error during Coday kill:",e)}this.coday=void 0}}},hT=class r{constructor(e,t,n,i,a){this.logger=e;this.projectService=t;this.threadService=n;this.promptService=i;this.mcpPool=a;this.heartbeatInterval=setInterval(()=>this.sendHeartbeats(),r.HEARTBEAT_INTERVAL),ue("THREAD_CODAY_MANAGER","Heartbeat mechanism started")}instances=new Map;heartbeatInterval;static HEARTBEAT_INTERVAL=3e4;sendHeartbeats(){for(let e of this.instances.values())e.connectionCount>0&&e.sendHeartbeat()}handleInstanceTimeout=async e=>{ue("THREAD_CODAY_MANAGER",`Handling timeout for thread ${e}`),await this.cleanup(e)};getOrCreate(e,t,n,i,a){let o=this.instances.get(e);return o?ue("THREAD_CODAY",`Reusing existing instance for thread ${e}`):(ue("THREAD_CODAY",`Creating new instance for thread ${e}`),o=new dT(e,t,n,i,this.logger,this.projectService,this.threadService,this.promptService,this.mcpPool,this.handleInstanceTimeout),this.instances.set(e,o)),o.addConnection(a),o}createWithoutConnection(e,t,n,i){let a=this.instances.get(e);return a?ue("THREAD_CODAY",`Reusing existing instance for thread ${e}`):(ue("THREAD_CODAY",`Creating new instance for thread ${e} (no SSE connection)`),a=new dT(e,t,n,i,this.logger,this.projectService,this.threadService,this.promptService,this.mcpPool,this.handleInstanceTimeout),a.markAsOneshot(),this.instances.set(e,a)),a}get(e){return this.instances.get(e)}removeConnection(e,t){let n=this.instances.get(e);n&&(n.removeConnection(t),n.connectionCount===0&&ue("THREAD_CODAY",`Thread ${e} has no active connections but instance kept alive`))}stop(e){let t=this.instances.get(e);t&&t.stop()}async cleanup(e){let t=this.instances.get(e);t&&(await t.cleanup(),await this.mcpPool.releaseThread(e),this.instances.delete(e),ue("THREAD_CODAY",`Removed instance for thread ${e}`))}getStats(){let e=0,t=0;for(let n of this.instances.values())n.connectionCount>0&&e++,n.isOneshot&&t++;return{total:this.instances.size,withConnections:e,oneshot:t}}async shutdown(){ue("THREAD_CODAY_MANAGER",`Shutting down ${this.instances.size} thread instances`),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),ue("THREAD_CODAY_MANAGER","Heartbeat mechanism stopped"));let e=[];for(let[t,n]of this.instances.entries())ue("THREAD_CODAY_MANAGER",`Cleaning up thread ${t}`),e.push(n.cleanup().then(()=>this.mcpPool.releaseThread(t)).catch(i=>{ue("THREAD_CODAY_MANAGER",`Error cleaning up thread ${t}:`,i)}));await Promise.all(e),this.instances.clear(),await this.mcpPool.shutdown(),ue("THREAD_CODAY_MANAGER","All thread instances cleaned up")}};async function I7e(r,e=100){let t=await import("node:net");return new Promise((n,i)=>{function a(o,s){let c=t.createServer();c.listen(o,()=>{c.close(()=>{ue("PORT",`Port ${o} is available`),n(o)})}),c.on("error",u=>{u.code==="EADDRINUSE"?s>0?(ue("PORT",`Port ${o} is in use, trying next`),a(o+1,s-1)):i(new Error(`Could not find an available port starting from ${r}`)):i(u)})}a(r,e)})}function O7e(r,e,t){r.get("/api/config/user",(n,i)=>{try{let a=t(n);if(!a){i.status(401).json({error:"Username not found in request headers"});return}ue("CONFIG",`GET user config for: ${a}`);let c={...e.getUserService(a).getConfigForClient(),username:a};i.status(200).json(c)}catch(a){console.error("Error retrieving user config:",a),i.status(500).json({error:"Failed to retrieve user configuration"})}}),r.put("/api/config/user",(n,i)=>{try{let a=t(n);if(!a){i.status(401).json({error:"Username not found in request headers"});return}let o=n.body;if(!o||typeof o!="object"){i.status(422).json({error:"Invalid configuration format"});return}if(typeof o.version!="number"){i.status(422).json({error:"Configuration must have a version number"});return}ue("CONFIG",`PUT user config for: ${a}`),e.getUserService(a).updateConfigFromClient(o),i.status(200).json({success:!0,message:"User configuration updated successfully"})}catch(a){console.error("Error updating user config:",a);let o=a instanceof Error?a.message:"Unknown error";i.status(500).json({error:`Failed to update user configuration: ${o}`})}})}function je(r){return Array.isArray(r)?r[0]||"":r||""}function $7e(r,e){r.get("/api/projects",(t,n)=>{try{ue("PROJECT","GET all projects");let i=e.listProjects(),a=e.getDefaultProject(),o=e.getForcedMode();n.status(200).json({projects:i,defaultProject:a,forcedProject:o?a:null})}catch(i){console.error("Error listing projects:",i),n.status(500).json({error:"Failed to list projects"})}}),r.get("/api/projects/:name",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`GET project: ${i}`);let a=e.getProject(i);if(!a){n.status(404).json({error:`Project '${i}' not found`});return}n.status(200).json(a)}catch(i){console.error("Error retrieving project:",i),n.status(500).json({error:"Failed to retrieve project"})}}),r.post("/api/projects",(t,n)=>{try{let{name:i,path:a}=t.body;if(!i||!a){n.status(400).json({error:"Project name and path are required"});return}ue("PROJECT",`POST create project: ${i} at ${a}`),e.createProject(i,a),n.status(201).json({success:!0,message:`Project '${i}' created successfully`})}catch(i){console.error("Error creating project:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to create project: ${a}`})}}),r.get("/api/projects/:name/config",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`GET project config: ${i}`);let a=e.getProjectConfigForClient(i);if(!a){n.status(404).json({error:`Project '${i}' not found`});return}n.status(200).json(a)}catch(i){console.error("Error retrieving project config:",i),n.status(500).json({error:"Failed to retrieve project configuration"})}}),r.put("/api/projects/:name/config",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}let a=t.body;if(!a||typeof a!="object"){n.status(422).json({error:"Invalid configuration format"});return}if(typeof a.version!="number"){n.status(422).json({error:"Configuration must have a version number"});return}if(!a.path||typeof a.path!="string"){n.status(422).json({error:"Configuration must have a valid path"});return}ue("PROJECT",`PUT project config: ${i}`),e.updateProjectConfigFromClient(i,a),n.status(200).json({success:!0,message:"Project configuration updated successfully"})}catch(i){console.error("Error updating project config:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to update project configuration: ${a}`})}}),r.delete("/api/projects/:name",(t,n)=>{try{let i=je(t.params.name);if(!i){n.status(400).json({error:"Project name is required"});return}ue("PROJECT",`DELETE project: ${i}`),e.deleteProject(i),n.status(200).json({success:!0,message:`Project '${i}' deleted successfully`})}catch(i){console.error("Error deleting project:",i);let a=i instanceof Error?i.message:"Unknown error";n.status(500).json({error:`Failed to delete project: ${a}`})}})}import{existsSync as Y9t,readFileSync as X9t}from"fs";function j7e(r,e,t,n,i,a){r.get("/api/projects/:projectName/threads",async(o,s)=>{try{let c=je(o.params.projectName);if(!c){s.status(400).json({error:"Project name is required"});return}let u=i(o);if(!u){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET threads for project: ${c}, user: ${u}`);let l=await e.listThreads(c,u);s.status(200).json(l)}catch(c){console.error("Error listing threads:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to list threads: ${u}`})}}),r.post("/api/projects/:projectName/threads",async(o,s)=>{try{let c=je(o.params.projectName);if(!c){s.status(400).json({error:"Project name is required"});return}let u=i(o);if(!u){s.status(401).json({error:"Authentication required"});return}let{name:l}=o.body;ue("THREAD",`POST create thread in project: ${c}, user: ${u}, name: ${l||"untitled"}`);let f=await e.createThread(c,u,l);s.status(201).json({success:!0,thread:{id:f.id,name:f.name,projectId:f.projectId,username:f.username,createdDate:f.createdDate,modifiedDate:f.modifiedDate}})}catch(c){console.error("Error creating thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to create thread: ${u}`})}}),r.get("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET thread: ${u} from project: ${c}`);let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}s.status(200).json({id:f.id,name:f.name,projectId:f.projectId,username:f.username,summary:f.summary,createdDate:f.createdDate,modifiedDate:f.modifiedDate,price:f.price,messageCount:f.messagesLength,users:f.users})}catch(c){console.error("Error retrieving thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to retrieve thread: ${u}`})}}),r.put("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let{name:f,users:p}=o.body,d=await e.getThread(c,u);if(!d){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(d,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}let m;if(p!==void 0){if(!rn(d,l)){s.status(403).json({error:"Access denied: only thread participants can modify the users list"});return}if(!Array.isArray(p)){s.status(400).json({error:"Invalid users format: must be an array"});return}for(let g of p)if(!g||typeof g.userId!="string"||g.userId.trim()===""){s.status(400).json({error:"Invalid users format: each user must have a non-empty userId string"});return}m=p}ue("THREAD",`PUT update thread: ${u} in project: ${c}`);let h=await e.updateThread(c,u,{name:f,users:m});if(m!==void 0){let v=n.get(u)?.coday?.context?.aiThread;v&&(v.users=m,ue("THREAD",`Synced users to live AiThread for thread ${u}`))}s.status(200).json({success:!0,thread:{id:h.id,name:h.name,projectId:h.projectId,modifiedDate:h.modifiedDate}})}catch(c){console.error("Error updating thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to update thread: ${u}`})}}),r.get("/api/projects/:projectName/threads/:threadId/messages",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}ue("THREAD",`GET messages for thread: ${u} in project: ${c}`);let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}let{messages:p}=await f.getMessages(void 0,void 0);s.status(200).json({messages:p})}catch(c){console.error("Error retrieving thread messages:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to retrieve thread messages: ${u}`})}}),r.post("/api/projects/:projectName/threads/:threadId/star",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}if(!await e.getThread(c,u)){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}ue("THREAD",`POST star thread: ${u} in project: ${c} by user: ${l}`);let p=await e.starThread(c,u,l);s.status(200).json({success:!0,thread:{id:p.id,starring:p.starring,modifiedDate:p.modifiedDate}})}catch(c){console.error("Error starring thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to star thread: ${u}`})}}),r.delete("/api/projects/:projectName/threads/:threadId/star",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}if(!await e.getThread(c,u)){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}ue("THREAD",`DELETE unstar thread: ${u} in project: ${c} by user: ${l}`);let p=await e.unstarThread(c,u,l);s.status(200).json({success:!0,thread:{id:p.id,starring:p.starring,modifiedDate:p.modifiedDate}})}catch(c){console.error("Error unstarring thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to unstar thread: ${u}`})}}),r.post("/api/projects/:projectName/threads/:threadId/stop",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}ue("THREAD",`POST stop thread: ${u} in project: ${c}`),n.stop(u),s.status(200).json({success:!0,message:"Stop signal sent successfully"})}catch(c){console.error("Error stopping thread:",c);let u=c instanceof Error?c.message:"Unknown error";s.status(500).json({error:`Failed to stop thread: ${u}`})}}),r.delete("/api/projects/:projectName/threads/:threadId",async(o,s)=>{try{let c=je(o.params.projectName),u=je(o.params.threadId);if(!c||!u){s.status(400).json({error:"Project name and thread ID are required"});return}let l=i(o);if(!l){s.status(401).json({error:"Authentication required"});return}let f=await e.getThread(c,u);if(!f){s.status(404).json({error:`Thread '${u}' not found in project '${c}'`});return}if(!rn(f,l)){s.status(403).json({error:"Access denied: thread belongs to another user"});return}ue("THREAD",`DELETE
1421
1421
  thread:
1422
1422
  ${u}
1423
1423
  from