@whoz-oss/coday-server 0.45.0 → 0.46.1

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 +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whoz-oss/coday-server",
3
- "version": "0.45.0",
3
+ "version": "0.46.1",
4
4
  "repository": "https://github.com/whoz-oss/coday",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
package/server.js CHANGED
@@ -302,7 +302,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
302
302
  More details: https://github.com/chimurai/http-proxy-middleware/blob/master/MIGRATION.md#removed-logprovider-and-loglevel-options
303
303
  `)),t}function PM(r){let e=r.logProvider&&r.logProvider();return e&&(r.logger=e),(0,Jit.getLogger)(r)}});var Zpe=k(IM=>{"use strict";Object.defineProperty(IM,"__esModule",{value:!0});IM.legacyCreateProxyMiddleware=tat;var Qit=AM(),Zit=Nc(),eat=Xpe(),Qpe=Zit.Debug.extend("legacy-create-proxy-middleware");function tat(r,e){Qpe("init");let t=(0,eat.legacyOptionsAdapter)(r,e),n=(0,Qit.createProxyMiddleware)(t);return Qpe("add marker for patching req.url (old behavior)"),n.__LEGACY_HTTP_PROXY_MIDDLEWARE__=!0,n}});var ede=k(rE=>{"use strict";Object.defineProperty(rE,"__esModule",{value:!0});rE.legacyCreateProxyMiddleware=void 0;var rat=Zpe();Object.defineProperty(rE,"legacyCreateProxyMiddleware",{enumerable:!0,get:function(){return rat.legacyCreateProxyMiddleware}})});var tde=k(b0=>{"use strict";var nat=b0&&b0.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),iat=b0&&b0.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&nat(e,r,t)};Object.defineProperty(b0,"__esModule",{value:!0});iat(ede(),b0)});var rde=k(Wo=>{"use strict";var aat=Wo&&Wo.__createBinding||(Object.create?(function(r,e,t,n){n===void 0&&(n=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(r,n,i)}):(function(r,e,t,n){n===void 0&&(n=t),r[n]=e[t]})),nE=Wo&&Wo.__exportStar||function(r,e){for(var t in r)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&aat(e,r,t)};Object.defineProperty(Wo,"__esModule",{value:!0});nE(AM(),Wo);nE(Ype(),Wo);nE(eM(),Wo);nE(tde(),Wo)});var cE=Tr(_z(),1);import Lc from"path";import iE from"fs";var QK=Tr(As(),1);function Rk(r,e=80){if(r.length<=e)return r;try{if(r.trim().startsWith("{")||r.trim().startsWith("[")){let t=JSON.parse(r),n=JSON.stringify(t);return n.length<=e?n:n.substring(0,e)+`...(${n.length} chars)`}}catch{}return r.substring(0,e)+"..."}var ui=class{constructor(e,t){this.type=t;if(e.timestamp)this.timestamp=e.timestamp;else{let n=Math.random().toString(36).substring(2,7);this.timestamp=`${new Date().toISOString()}-${n}`}this.parentKey=e.parentKey,this.length=0}timestamp;parentKey;static type;length},fg=class extends ui{invite;constructor(e,t){super(e,t),this.invite=e.invite}buildAnswer(e){return new Wa({answer:e,parentKey:this.timestamp,invite:this.invite})}},Of=class r extends ui{static type="heartbeat";constructor(e){super(e,r.type)}},If=class r extends fg{defaultValue;static type="invite";constructor(e){super(e,r.type),this.defaultValue=e.defaultValue}},JK="InviteEventDefault",Wa=class r extends ui{answer;invite;static type="answer";constructor(e){super(e,r.type),this.answer=e.answer??"No answer",this.invite=e.invite}},hu=class r extends ui{speaker;text;static type="text";constructor(e){super(e,r.type),this.speaker=e.speaker,this.text=e.text}},Rf=class r extends ui{chunk;static type="text_chunk";constructor(e){super(e,r.type),this.chunk=e.chunk,this.length=this.chunk.length}},Ff=class r extends ui{warning;static type="warn";constructor(e){super(e,r.type),this.warning=e.warning}},Wi=class r extends ui{error;static type="error";constructor(e){super(e,r.type),this.error=e.error}},jf=class r extends fg{options;optionalQuestion;static type="choice";constructor(e){super(e,r.type),this.options=e.options,this.optionalQuestion=e.optionalQuestion}},fn=class r extends ui{toolRequestId;name;args;static type="tool_request";constructor(e){super(e,r.type),this.toolRequestId=e.toolRequestId??this.timestamp,this.name=e.name,this.args=e.args,this.length=this.args.length+this.name.length+this.toolRequestId.length+20}buildResponse(e){return new pn({output:e,toolRequestId:this.toolRequestId,parentKey:this.timestamp})}toSingleLineString(e=50){let t=Rk(this.args,e);return`\u{1F527} ${this.name}(${t})`}},pn=class r extends ui{toolRequestId;output;static type="tool_response";constructor(e){if(super(e,r.type),this.toolRequestId=e.toolRequestId||this.timestamp||new Date().toISOString(),this.output=e.output,typeof this.output=="string")this.length=this.output.length+this.toolRequestId.length+20;else if(this.output.type==="text")this.length=this.output.content.length+this.toolRequestId.length+20;else if(this.output.type==="image"){let t=(this.output.width??0)*(this.output.height??0)/750;this.length=(t?t*3.5:this.output.content.length)+this.toolRequestId.length+20}else this.length=this.toolRequestId.length+20}getTextOutput(){return typeof this.output=="string"?this.output:this.output.type==="text"?this.output.content:this.output.type==="image"?`[Image: ${this.output.mimeType}]`:""}toSingleLineString(e=50){let t=this.getTextOutput(),n=Rk(t,e),i=typeof this.output!="string"&&this.output.type==="image"?" [image]":"";return`\u2B91 ${n}${i}`}},mu=class r extends ui{static type="thinking";static debounce=5e3;constructor(e){super(e,r.type)}},Gi=class r extends ui{summary;static type="summary";constructor(e){super(e,r.type),this.summary=e.summary,this.length=this.summary.length}toSingleLineString(e=80){return`\u{1F4CB} Summary: ${Rk(this.summary,e)}`}},lr=class r extends ui{role;name;content;static type="message";constructor(e){super(e,r.type),this.role=e.role,this.name=e.name,this.content=e.content,this.length=this.content.map(t=>{if(t.type==="text")return t.content.length;if(t.type==="image"){let n=(t.width||0)*(t.height||0)/750;return n?n*3.5:t.content.length}return 0}).reduce((t,n)=>t+n,0)}getTextContent(){return this.content.filter(e=>e.type==="text").map(e=>e.content).join(`
304
304
  `)}},Mf=class r extends ui{threadId;name;static type="thread_update";constructor(e){super(e,r.type),this.threadId=e.threadId,this.name=e.name}},Cl=class r extends ui{filename;operation;size;mimeType;static type="file";constructor(e){super(e,r.type),this.filename=e.filename,this.operation=e.operation,this.size=e.size,this.mimeType=e.mimeType}toSingleLineString(){let e=this.operation==="created"?"\u{1F4C4}":this.operation==="updated"?"\u{1F4DD}":"\u{1F5D1}\uFE0F",t=this.size?` (${(this.size/1024).toFixed(1)} KB)`:"";return`${e} ${this.operation}: ${this.filename}${t}`}},DRe={[lr.type]:lr,[Wa.type]:Wa,[jf.type]:jf,[Wi.type]:Wi,[Of.type]:Of,[If.type]:If,[fn.type]:fn,[pn.type]:pn,[hu.type]:hu,[Rf.type]:Rf,[mu.type]:mu,[Ff.type]:Ff,[Mf.type]:Mf,[Gi.type]:Gi,[Cl.type]:Cl};function YK(r){let e=DRe[r.type];return e?new e(r):void 0}var ic=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="ThreadRepositoryError"}},Th={input:0,output:0,cache_read:0,cache_write:0,price:0,iterations:0,priceThreshold:2,iterationsThreshold:100};function XK(r,e,t=.7){if(!e||!r.length)return{messages:r,overflow:[]};let n=0,i=0,a=e*t;for(let c of r)i+=c.length,n+=i<a?1:0;if(i<e)return{messages:r,overflow:[]};let s=r.slice(0,n),o=r.slice(n);return{messages:s,overflow:o}}var PRe=[lr.type,fn.type,pn.type,Gi.type],Al=class r{id;username;projectId;name;summary;starring=[];createdDate;modifiedDate;runStatus="STOPPED";data={};usage={...Th};price=0;delegationDepth=0;forkedThreads=new Map;parentThread;messages;get messagesLength(){return this.messages.length}constructor(e){this.id=e.id,this.username=e.username,this.projectId=e.projectId??"",this.name=e.name??"",this.summary=e.summary??"",this.starring=e.starring??[],this.createdDate=e.createdDate??new Date().toISOString(),this.modifiedDate=e.modifiedDate??this.createdDate,this.price=e.price??0;let t=e.messages??[];Array.isArray(t)?this.messages=t.filter(n=>PRe.includes(n.type)).map(n=>YK(n)).filter(n=>n!==void 0):this.messages=[]}async getMessages(e,t){if((!this.messages||!Array.isArray(this.messages))&&(this.messages=[]),!e){let u=this.getMessagesUpToFirstSummary();return{messages:this.cleanToolRequestResponseConsistency(u),compacted:!1}}let n=this.getMessagesUpToFirstSummary(),i=Math.floor(e*.5),a=n.map(u=>{if(u instanceof pn&&u.length>i){let f=Math.floor(e*.15),d=u.getTextOutput(),p=`[... truncated ${u.length-f} chars]
305
- `+d.slice(-f);return new pn({...u,output:p})}return u}),{messages:s,overflow:o}=XK(a.toReversed(),e);if(s=s.toReversed(),o=o.toReversed(),!t||o.length===0)return{messages:this.cleanToolRequestResponseConsistency(s),compacted:o.length>0};let c;try{c=await t(o);let u=o[o.length-1];if(u){let f=this.messages.indexOf(u);f!==-1&&this.messages.splice(f+1,0,c)}}catch(u){return console.error("[AiThread] Compaction failed, keeping recent messages only:",u),{messages:this.cleanToolRequestResponseConsistency(s),compacted:!0}}let l=this.cleanToolRequestResponseConsistency(s);return{messages:[c,...l],compacted:!0}}getAllMessages(){return this.cleanToolRequestResponseConsistency([...this.messages])}getMessagesUpToFirstSummary(){let e=[...this.messages].reverse(),t=[];for(let n of e){if(n instanceof Gi){t.push(n);break}t.push(n)}return t.reverse()}cleanToolRequestResponseConsistency(e){let t=[],n=new Set,i=new Set;for(let a of e)a instanceof fn&&a.toolRequestId?n.add(a.toolRequestId):a instanceof pn&&a.toolRequestId&&i.add(a.toolRequestId);for(let a of e){let s=!0;a instanceof fn?a.toolRequestId&&!i.has(a.toolRequestId)&&(console.debug(`[AiThread] Removing orphaned tool request: ${a.name} (ID: ${a.toolRequestId})`),s=!1):a instanceof pn&&(a.toolRequestId?n.has(a.toolRequestId)||(console.debug(`[AiThread] Removing orphaned tool response for missing request ID: ${a.toolRequestId}`),s=!1):(console.warn(`[AiThread] Removing tool response without tool reference (timestamp: ${a.timestamp})`),s=!1)),s&&t.push(a)}return t}resetUsageForRun(){this.usage={...Th}}addUsage(e){this.price+=e.price??0,this.usage.price+=e.price??0,this.usage.iterations+=1;let t=this.usage;t.input+=e.input??0,t.output+=e.output??0,t.cache_read+=e.cache_read??0,t.cache_write+=e.cache_write??0}add(e){this.messages.push(e)}findToolRequestById(e){return this.messages.find(t=>t instanceof fn&&t.toolRequestId===e)}findSimilarToolRequests(e){return this.messages.filter(t=>t!==e&&t instanceof fn&&t.name===e.name&&t.args===e.args)}findToolResponsesToRequests(e){return this.messages.filter(t=>t instanceof pn&&e.some(n=>n.toolRequestId===t.toolRequestId))}removeMessages(e){this.messages=this.messages.filter(t=>!e.includes(t))}addUserMessage(e,t){let n=this.messages[this.messages.length-1];n&&n instanceof lr&&n.role==="user"&&n.name===e?n.content.push(t):this.add(new lr({role:"user",content:[t],name:e})),this.modifiedDate=new Date().toISOString()}addAgentMessage(e,t){let n=this.messages[this.messages.length-1];n&&n instanceof lr&&n.role==="assistant"&&n.name===e?n.content.push(t):this.add(new lr({role:"assistant",content:[t],name:e})),this.modifiedDate=new Date().toISOString()}fork(e){let t=this.forkedThreads.get(e??null);if(t)return t.runStatus="RUNNING",t;let n=new r({id:this.id,username:this.username,projectId:this.projectId,name:e?`${this.name} - Delegated to ${e}`:`${this.name} - Forked`,summary:this.summary,createdDate:this.createdDate,modifiedDate:new Date().toISOString(),price:0,messages:[...this.messages]});return n.delegationDepth=this.delegationDepth+1,n.parentThread=this,n.runStatus="RUNNING",this.forkedThreads.set(e??null,n),n}merge(e){this.price+=e.price,e.price=0}get totalPrice(){return this.price+(this.parentThread?.totalPrice??0)}getLastAgentName(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t instanceof lr&&t.role==="assistant"&&t.name)return t.name}}getUserMessageCount(){return this.messages.filter(e=>e instanceof lr&&e.role==="user").length}getEventById(e){return this.messages.find(t=>t.timestamp===e)}truncateAtUserMessage(e){let t=this.messages.findIndex(i=>i.timestamp===e);if(t===-1)return!1;let n=this.messages[t];return!(n instanceof lr)||n.role!=="user"||t===0?!1:(this.messages=this.messages.slice(0,t),this.modifiedDate=new Date().toISOString(),!0)}addToolRequests(e,t){t.forEach(n=>{!n.toolRequestId||!n.name||!n.args||this.add(n)})}addToolResponseEvents(e){e.forEach(t=>{if(!t.toolRequestId||!t.output)return;let n=this.findToolRequestById(t.toolRequestId);if(!n)return;let i=this.findSimilarToolRequests(n),a=this.findToolResponsesToRequests(i);this.removeMessages([...i,...a]),this.add(t)})}addToolCalls(e,t){t.forEach(n=>{!n.id||!n.name||!n.args||this.add(new fn({name:n.name,args:n.args,toolRequestId:n.id}))})}addToolResponses(e,t){t.forEach(n=>{if(!n.id||!n.response)return;let i=this.findToolRequestById(n.id);if(!i)return;let a=this.findSimilarToolRequests(i),s=this.findToolResponsesToRequests(a);this.removeMessages([...a,...s]),this.add(new pn({toolRequestId:n.id,output:n.response}))})}};var pg=class{constructor(e,t,n,i){this.threadRepository=t;this.projectId=n;this.interactor=i;this.username=e.username}activeThread$=new QK.BehaviorSubject(null);isKilled=!1;activeThread=this.activeThread$.asObservable();username;async kill(){this.isKilled=!0,this.activeThread$.complete()}async create(e){let t=new Al({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{let n=e&&t.name!==e;e&&(t.name=e),await this.threadRepository.save(this.projectId,t),this.interactor&&this.interactor.sendEvent(new Mf({threadId:t.id,name:n?e: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}};var Nf=class r{constructor(e,t){this.project=e;this.username=t}commandQueue=[];clearCommands(){this.commandQueue=[]}oneshot=!1;fileReadOnly=!1;threadFilesRoot;stackDepth=1;data={};aiThread;addCommands(...e){this.commandQueue.unshift(...e)}getFirstCommand(){return this.commandQueue.shift()}getSubContext(...e){let t=new r(this.project,this.username);return t.oneshot=this.oneshot,t.fileReadOnly=this.fileReadOnly,t.addCommands(...e),t.stackDepth=this.stackDepth-1,t}cloneWithoutCommands(){let e=new r(this.project,this.username);return e.oneshot=this.oneshot,e.fileReadOnly=this.fileReadOnly,e.stackDepth=this.stackDepth,e.data=this.data,e}};var Me=class{commandWord;description;requiredIntegrations=[];isInternal=!1;constructor(e){this.commandWord=e.commandWord,this.description=e.description,this.requiredIntegrations=e.requiredIntegrations||[],this.isInternal=!!e?.isInternal}getSubCommand(e){return e.slice(this.commandWord.length).trim()}accept(e,t){return!!e&&e.toLowerCase().startsWith(this.commandWord)}};var dg={CONFLUENCE:[],GIT:[],GITLAB:[],JIRA:[]},gu=Object.keys(dg).filter(r=>dg[r]?.length===0);var xn=Tr(As(),1),hg=class{events=new xn.Subject;thinking$=new xn.Subject;subs=[];lastInviteEvent;debugLevelEnabled=!1;constructor(){this.subs.push(this.thinking$.pipe((0,xn.throttleTime)(mu.debounce)).subscribe(()=>this.sendEvent(new mu({}))))}async promptText(e,t){let n=new If({invite:e,defaultValue:t});this.lastInviteEvent=n;let i=this.events.pipe((0,xn.filter)(a=>a.parentKey===n.timestamp),(0,xn.filter)(a=>a instanceof Wa),(0,xn.take)(1),(0,xn.map)(a=>a.answer));this.sendEvent(n);try{return await(0,xn.firstValueFrom)(i)}catch(a){throw new Error(`No answer received over invite ${n.timestamp} : ${a.message}`)}}async promptSecretText(e,t,n="********"){let i=t?n:"",a=await this.promptText(e,i);if(a===n&&t)return t;if(a)return a}async chooseOption(e,t,n){let i=new jf({options:e,invite:t,optionalQuestion:n}),a=this.events.pipe((0,xn.filter)(s=>s.parentKey===i.timestamp),(0,xn.filter)(s=>s instanceof Wa),(0,xn.take)(1),(0,xn.map)(s=>s.answer));this.sendEvent(i);try{return await(0,xn.firstValueFrom)(a)}catch(s){throw new Error(`No answer received over choice ${i.timestamp} : ${s.message}`)}}displayText(e,t){this.sendEvent(new hu({text:e,speaker:t}))}debug(e){if(!this.debugLevelEnabled)return;let t=`${new Date().toISOString()} DEBUG: ${e.toString()}`;console.log(t),this.sendEvent(new hu({text:t}))}warn(e){this.sendEvent(new Ff({warning:e}))}error(e){this.sendEvent(new Wi({error:e}))}thinking(){this.thinking$.next(null)}sendEvent(e){this.events.next(e)}replayLastInvite(){this.lastInviteEvent&&this.sendEvent(this.lastInviteEvent)}kill(){this.subs.forEach(e=>e.unsubscribe()),this.events.complete()}};var dn=class extends Me{constructor(t,n){super(t);this.interactor=n}handlers=[];async handle(t,n){let i=this.getSubCommand(t),a=this.handlers.find(s=>s.accept(i,n));return a?a.handle(i,n):i.trim().length>0?(this.displayHelp(i),n):this.handleInteractiveSelection(n)}async handleInteractiveSelection(t){let n=this.buildHelpText();this.interactor.displayText(n);let i=this.handlers.filter(l=>!l.isInternal),a=new Map,s=i.map(l=>{let u=l.description.split(`
305
+ `+d.slice(-f);return new pn({...u,output:p})}return u}),{messages:s,overflow:o}=XK(a.toReversed(),e);if(s=s.toReversed(),o=o.toReversed(),!t||o.length===0)return{messages:this.cleanToolRequestResponseConsistency(s),compacted:o.length>0};let c;try{c=await t(o);let u=o[o.length-1];if(u){let f=this.messages.indexOf(u);f!==-1&&this.messages.splice(f+1,0,c)}}catch(u){return console.error("[AiThread] Compaction failed, keeping recent messages only:",u),{messages:this.cleanToolRequestResponseConsistency(s),compacted:!0}}let l=this.cleanToolRequestResponseConsistency(s);return{messages:[c,...l],compacted:!0}}getAllMessages(){return this.cleanToolRequestResponseConsistency([...this.messages])}getMessagesUpToFirstSummary(){let e=[...this.messages].reverse(),t=[];for(let n of e){if(n instanceof Gi){t.push(n);break}t.push(n)}return t.reverse()}cleanToolRequestResponseConsistency(e){let t=[],n=new Set,i=new Set;for(let a of e)a instanceof fn&&a.toolRequestId?n.add(a.toolRequestId):a instanceof pn&&a.toolRequestId&&i.add(a.toolRequestId);for(let a of e){let s=!0;a instanceof fn?a.toolRequestId&&!i.has(a.toolRequestId)&&(console.debug(`[AiThread] Removing orphaned tool request: ${a.name} (ID: ${a.toolRequestId})`),s=!1):a instanceof pn&&(a.toolRequestId?n.has(a.toolRequestId)||(console.debug(`[AiThread] Removing orphaned tool response for missing request ID: ${a.toolRequestId}`),s=!1):(console.warn(`[AiThread] Removing tool response without tool reference (timestamp: ${a.timestamp})`),s=!1)),s&&t.push(a)}return t}resetUsageForRun(){this.usage={...Th}}addUsage(e){this.price+=e.price??0,this.usage.price+=e.price??0,this.usage.iterations+=1;let t=this.usage;t.input+=e.input??0,t.output+=e.output??0,t.cache_read+=e.cache_read??0,t.cache_write+=e.cache_write??0}add(e){this.messages.push(e)}findToolRequestById(e){return this.messages.find(t=>t instanceof fn&&t.toolRequestId===e)}findSimilarToolRequests(e){return this.messages.filter(t=>t!==e&&t instanceof fn&&t.name===e.name&&t.args===e.args)}findToolResponsesToRequests(e){return this.messages.filter(t=>t instanceof pn&&e.some(n=>n.toolRequestId===t.toolRequestId))}removeMessages(e){this.messages=this.messages.filter(t=>!e.includes(t))}addUserMessage(e,t){let n=this.messages[this.messages.length-1];n&&n instanceof lr&&n.role==="user"&&n.name===e?n.content.push(t):this.add(new lr({role:"user",content:[t],name:e})),this.modifiedDate=new Date().toISOString()}addAgentMessage(e,t){let n=this.messages[this.messages.length-1];n&&n instanceof lr&&n.role==="assistant"&&n.name===e?n.content.push(t):this.add(new lr({role:"assistant",content:[t],name:e})),this.modifiedDate=new Date().toISOString()}fork(e){let t=this.forkedThreads.get(e??null);if(t)return t.runStatus="RUNNING",t;let n=new r({id:this.id,username:this.username,projectId:this.projectId,name:e?`${this.name} - Delegated to ${e}`:`${this.name} - Forked`,summary:this.summary,createdDate:this.createdDate,modifiedDate:new Date().toISOString(),price:0,messages:[...this.messages]});return n.delegationDepth=this.delegationDepth+1,n.parentThread=this,n.runStatus="RUNNING",this.forkedThreads.set(e??null,n),n}merge(e){this.price+=e.price,e.price=0}get totalPrice(){return this.price+(this.parentThread?.totalPrice??0)}getLastAgentName(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t instanceof lr&&t.role==="assistant"&&t.name)return t.name}}getUserMessageCount(){return this.messages.filter(e=>e instanceof lr&&e.role==="user").length}getEventById(e){return this.messages.find(t=>t.timestamp===e)}truncateAtUserMessage(e){let t=this.messages.findIndex(i=>i.timestamp===e);if(t===-1)return!1;let n=this.messages[t];return!(n instanceof lr)||n.role!=="user"||t===0?!1:(this.messages=this.messages.slice(0,t),this.modifiedDate=new Date().toISOString(),!0)}addToolRequests(e,t){t.forEach(n=>{!n.toolRequestId||!n.name||!n.args||this.add(n)})}addToolResponseEvents(e){e.forEach(t=>{if(!t.toolRequestId||!t.output)return;let n=this.findToolRequestById(t.toolRequestId);if(!n)return;let i=this.findSimilarToolRequests(n),a=this.findToolResponsesToRequests(i);this.removeMessages([...i,...a]),this.add(t)})}addToolCalls(e,t){t.forEach(n=>{!n.id||!n.name||!n.args||this.add(new fn({name:n.name,args:n.args,toolRequestId:n.id}))})}addToolResponses(e,t){t.forEach(n=>{if(!n.id||!n.response)return;let i=this.findToolRequestById(n.id);if(!i)return;let a=this.findSimilarToolRequests(i),s=this.findToolResponsesToRequests(a);this.removeMessages([...a,...s]),this.add(new pn({toolRequestId:n.id,output:n.response}))})}};var pg=class{constructor(e,t,n,i){this.threadRepository=t;this.projectId=n;this.interactor=i;this.username=e.username}activeThread$=new QK.BehaviorSubject(null);isKilled=!1;activeThread=this.activeThread$.asObservable();username;async kill(){this.isKilled=!0,this.activeThread$.complete()}async create(e){let t=new Al({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{let n=e&&t.name!==e;e&&(t.name=e),await this.threadRepository.save(this.projectId,t),this.interactor&&this.interactor.sendEvent(new Mf({threadId:t.id,name:n?e: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}};var Nf=class r{constructor(e,t){this.project=e;this.username=t}commandQueue=[];clearCommands(){this.commandQueue=[]}oneshot=!1;fileReadOnly=!1;threadFilesRoot;stackDepth=3;data={};aiThread;addCommands(...e){this.commandQueue.unshift(...e)}getFirstCommand(){return this.commandQueue.shift()}getSubContext(...e){let t=new r(this.project,this.username);return t.oneshot=this.oneshot,t.fileReadOnly=this.fileReadOnly,t.addCommands(...e),t.stackDepth=this.stackDepth-1,t}cloneWithoutCommands(){let e=new r(this.project,this.username);return e.oneshot=this.oneshot,e.fileReadOnly=this.fileReadOnly,e.stackDepth=this.stackDepth,e.data=this.data,e}};var Me=class{commandWord;description;requiredIntegrations=[];isInternal=!1;constructor(e){this.commandWord=e.commandWord,this.description=e.description,this.requiredIntegrations=e.requiredIntegrations||[],this.isInternal=!!e?.isInternal}getSubCommand(e){return e.slice(this.commandWord.length).trim()}accept(e,t){return!!e&&e.toLowerCase().startsWith(this.commandWord)}};var dg={CONFLUENCE:[],GIT:[],GITLAB:[],JIRA:[]},gu=Object.keys(dg).filter(r=>dg[r]?.length===0);var xn=Tr(As(),1),hg=class{events=new xn.Subject;thinking$=new xn.Subject;subs=[];lastInviteEvent;debugLevelEnabled=!1;constructor(){this.subs.push(this.thinking$.pipe((0,xn.throttleTime)(mu.debounce)).subscribe(()=>this.sendEvent(new mu({}))))}async promptText(e,t){let n=new If({invite:e,defaultValue:t});this.lastInviteEvent=n;let i=this.events.pipe((0,xn.filter)(a=>a.parentKey===n.timestamp),(0,xn.filter)(a=>a instanceof Wa),(0,xn.take)(1),(0,xn.map)(a=>a.answer));this.sendEvent(n);try{return await(0,xn.firstValueFrom)(i)}catch(a){throw new Error(`No answer received over invite ${n.timestamp} : ${a.message}`)}}async promptSecretText(e,t,n="********"){let i=t?n:"",a=await this.promptText(e,i);if(a===n&&t)return t;if(a)return a}async chooseOption(e,t,n){let i=new jf({options:e,invite:t,optionalQuestion:n}),a=this.events.pipe((0,xn.filter)(s=>s.parentKey===i.timestamp),(0,xn.filter)(s=>s instanceof Wa),(0,xn.take)(1),(0,xn.map)(s=>s.answer));this.sendEvent(i);try{return await(0,xn.firstValueFrom)(a)}catch(s){throw new Error(`No answer received over choice ${i.timestamp} : ${s.message}`)}}displayText(e,t){this.sendEvent(new hu({text:e,speaker:t}))}debug(e){if(!this.debugLevelEnabled)return;let t=`${new Date().toISOString()} DEBUG: ${e.toString()}`;console.log(t),this.sendEvent(new hu({text:t}))}warn(e){this.sendEvent(new Ff({warning:e}))}error(e){this.sendEvent(new Wi({error:e}))}thinking(){this.thinking$.next(null)}sendEvent(e){this.events.next(e)}replayLastInvite(){this.lastInviteEvent&&this.sendEvent(this.lastInviteEvent)}kill(){this.subs.forEach(e=>e.unsubscribe()),this.events.complete()}};var dn=class extends Me{constructor(t,n){super(t);this.interactor=n}handlers=[];async handle(t,n){let i=this.getSubCommand(t),a=this.handlers.find(s=>s.accept(i,n));return a?a.handle(i,n):i.trim().length>0?(this.displayHelp(i),n):this.handleInteractiveSelection(n)}async handleInteractiveSelection(t){let n=this.buildHelpText();this.interactor.displayText(n);let i=this.handlers.filter(l=>!l.isInternal),a=new Map,s=i.map(l=>{let u=l.description.split(`
306
306
  `)[0],f=`${l.commandWord}: ${u}`;return a.set(f,l.commandWord),f});s.push("exit: Cancel and return"),a.set("exit: Cancel and return","exit");let o=await this.interactor.chooseOption(s,"Select a command:","Enter your choice"),c=a.get(o);return!c||c==="exit"?t:this.handle(`${this.commandWord} ${c}`,t)}buildHelpText(t){let n=[];return t&&n.push(`Sub-command '${t}' not understood.`),n.push("Available commands:"),[...this.handlers].filter(a=>!a.isInternal).sort((a,s)=>a.commandWord.localeCompare(s.commandWord)).forEach(a=>{let s=a.description.split(`
307
307
  `).map((o,c)=>c===0?o:` ${o}`).join(`
308
308
  `);n.push(` - ${a.commandWord}: ${s}`)}),n.join(`