@membranehq/cli 1.1.21 → 1.1.22

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/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -138,7 +138,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
138
138
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
139
139
  `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let i=[];if(r&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(We(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(ua(t.key)&&!We(t.sep,"newline")){const o=Nt(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:l}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(We(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Nt(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):We(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!We(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||We(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){const r=us(n),i=Nt(r);da(e);const o=e.end.splice(1,e.end.length);o.push(this.sourceToken);const a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
140
140
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
141
- `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=us(e),n=Nt(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=us(e),n=Nt(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}function fa(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new ca||null,prettyErrors:e}}c(fa,"parseOptions");function zu(s,e={}){const{lineCounter:t,prettyErrors:n}=fa(e),r=new Pr(t?.addNewLine),i=new Or(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(ss(s,t)),a.warnings.forEach(ss(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(zu,"parseAllDocuments");function ha(s,e={}){const{lineCounter:t,prettyErrors:n}=fa(e),r=new Pr(t?.addNewLine),i=new Or(e);let o=null;for(const a of i.compose(r.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new st(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(ss(s,t)),o.warnings.forEach(ss(s,t))),o}c(ha,"parseDocument");function Yu(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=ha(s,t);if(!r)return null;if(r.warnings.forEach(i=>To(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},t))}c(Yu,"parse");function Xu(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(s===void 0){const{keepUndefined:r}=t??e??{};if(!r)return}return Ze(s)&&!n?s.toString(t):new Bt(s,n,t).toString(t)}c(Xu,"stringify");var Qu=Object.freeze({__proto__:null,Alias:qn,CST:Hu,Composer:Or,Document:Bt,Lexer:aa,LineCounter:ca,Pair:se,Parser:Pr,Scalar:R,Schema:Ls,YAMLError:kr,YAMLMap:le,YAMLParseError:st,YAMLSeq:Ue,YAMLWarning:Vo,isAlias:Be,isCollection:z,isDocument:Ze,isMap:St,isNode:Y,isPair:V,isScalar:H,isSeq:Ct,parse:Yu,parseAllDocuments:zu,parseDocument:ha,stringify:Xu,visit:et,visitAsync:Fn});const ue={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Zu={ignored:kl,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:20,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class ed extends nr{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=dt(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(L.existsSync(this.membraneDir)||L.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Zc.watch(this.membraneDir,Zu),this.watcher.on("add",e=>this.handleFileSystemEvent(ue.Updated,e)).on("change",e=>this.handleFileSystemEvent(ue.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(ue.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(ue.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=K.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=K.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+K.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=K.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===ue.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const o=this.processFileEvent(t,r);this.updateCache(n,r),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return L.readFileSync(e,"utf8")}processFileEvent(e,t){const n=K.relative(this.membraneDir,e);let r;try{r=t?Qu.parse(t):void 0}catch{r=void 0}return{filePath:e,relativePath:n,data:r}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return Xc.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){L.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=L.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=K.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=L.readFileSync(r,"utf8"),o=K.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var Rr=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(Rr||{});const td={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class nd extends nr{static{c(this,"RemoteElementWatcher")}constructor(e=td){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;connectionTimeout;isStarted=!1;isConnected=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.isConnected=!1,this.clearReconnectTimeout(),this.clearConnectionTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{b.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await B.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;b.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new el(n),this.setupEventSourceHandlers()}catch(e){b.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.debug("[remote-events] Connected to server"),this.reconnectAttempts=0,this.isConnected=!0,this.resetConnectionTimeout(),this.emit("connected",{})},this.eventSource.onmessage=e=>{try{this.resetConnectionTimeout();const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.debug(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.isConnected=!1,this.clearConnectionTimeout(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Bc.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===N.Connector){const{filePath:i,eventType:o,newPath:a}=r;return b.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,i,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const r=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,r)}scheduleConnectorFileUpdate(e,t,n,r){const i=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(i);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(i),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:r})},this.config.debounceMs);this.debounceTimeouts.set(i,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&(b.error("[remote-events] Max reconnection attempts reached. Connection will not be retried."),this.emit("error",{error:new Error("Max reconnection attempts reached")}));return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.reconnectAttempts++;const e=this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),t=Math.random()*.3*e,n=Math.min(e+t,this.config.maxBackoffMs);b.debug(`[remote-events] Reconnecting in ${Math.round(n)}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},n)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}resetConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeout=setTimeout(()=>{this.isConnected&&this.isStarted&&(b.debug("[remote-events] Connection timeout detected, reconnecting..."),this.isConnected=!1,this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.scheduleReconnect())},this.config.connectionTimeoutMs)}clearConnectionTimeout(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class pa{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const r=this.typeIndex.get(e.type);r&&(r.delete(t),r.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}const xt="connectors",Pe="development",Mr={};async function sd(){const e=(await B.withClient(o=>o.get("org-workspace-id"))).id,t={};b.info("[connectors] Loading custom connectors"),await B.withClient(o=>o.get(`/connectors?workspaceId=${e}`)),b.info("[connectors] Loading public connectors");const n=Je(),i=(F.existsSync(n)?F.readdirSync(n):[]).filter(o=>{if(o.startsWith("."))return!1;const a=U.join(n,o);try{return F.statSync(a).isDirectory()}catch{return!1}});for(const o of i){b.info(`[connectors] Loading connector from: ${o}`);const a=F.readdirSync(U.join(n,o)),l=await Lr(o);if(!l)continue;"baseUri"in l&&delete l.baseUri;let u;if(l.uuid&&(u=await B.withClient(d=>d.get(`/connectors/${l.uuid}`),!1)),u)t[l.id]=u.id,b.info(`[connectors] Matched ${l.name} uuid: ${l.uuid}`),u.archivedAt&&(b.info(`[connectors] Restoring archived connector ${l.name}`),await B.withClient(d=>d.post(`connectors/${u.id}/restore`))),b.info(`[connectors] Updating connector ${l.name}`),await B.withClient(d=>d.patch(`connectors/${u.id}`,{...l,workspaceId:e}));else if(!t[l.id]){let d=!1;try{const h=await Dr({connectorId:l.id});h&&h.isPublic&&(d=!0)}catch{}if(!d){b.info(`[connectors] Creating custom connector ${l.name} (${l.key})`);const h=await B.withClient(g=>g.post("connectors",{...l,workspaceId:e}));t[l.id]=h.id}}const f=a.filter(d=>F.statSync(U.join(n,o,d)).isDirectory());for(const d of f)await od({connector:l,version:d,connectorId:t[l.id]})}return t}c(sd,"pushConnectors");async function ma({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=Ni(),o=await Dr({connectorId:s});if(!o.isPublic||t){if(!o?.key){b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await ad({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await cd({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(ma,"pullRemoteConnector");function Je(){const s=tr();return U.join(s.membraneDirPath,xt)}c(Je,"getConnectorsPath");async function Lr(s){const e=U.join(Je(),s,`${s}.yml`);return ir(e,!1)}c(Lr,"readConnector");async function rd(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=F.createWriteStream(e),i=tl("zip",{zlib:{level:9}});r.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{b.info("[connectors] Data has been drained")}),i.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),i.on("error",a=>{n(a)}),i.pipe(r);const o=F.readdirSync(s);for(const a of o){const l=U.join(s,a),u=F.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(rd,"createZipArchive");async function id(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=sl.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=U.join(e,o);F.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=U.join(e,o),u=U.dirname(l);F.mkdirSync(u,{recursive:!0});const f=F.createWriteStream(l);i.pipe(f),f.on("finish",()=>{})}}),r.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(s),r.end()})}c(id,"extractZipArchive");async function od({connector:s,version:e,connectorId:t}){const n=U.join(Je(),Re(s),ga(e)),r=U.join(n,"src"),i=U.join(n,"src.zip"),o=F.existsSync(i);if(F.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await rd(r,i)),!F.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new nl;if(a.append("file",F.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Pe)b.info(`[connectors] Uploading connector ${t}`),await B.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await B.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){b.info(`[connectors] Version ${e} already published`);return}b.info(`[connectors] Publishing version ${e} of connector ${t}`),await B.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&F.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),F.unlinkSync(i))}}c(od,"pushConnectorVersion");async function Dr({connectorId:s}){if(s){if(Mr[s])return Mr[s];try{const e=await B.withClient(t=>t.get(`connectors/${s}`),!1);return Mr[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(Dr,"getConnector");async function ad({basePath:s,connector:e}){const t=Re(e),n=U.join(s,xt,t);F.mkdirSync(n,{recursive:!0});const r=U.join(n,`${Re(e)}.yml`);F.writeFileSync(r,Wt.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(ad,"pullConnector");async function cd({connector:s,connectorVersion:e,basePath:t}){const n=Re(s),r=ga(e),i=U.join(t,"connectors",n,r),o=await B.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));F.mkdirSync(i,{recursive:!0});const a=U.join(i,"src.zip");if(F.writeFileSync(a,o),!e){const l=U.join(i,"src");F.mkdirSync(l,{recursive:!0}),await id(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(cd,"pullConnectorVersion");function Re(s){return s.key}c(Re,"getConnectorDirName");function ga(s){return s??Pe}c(ga,"getConnectorVersionDirName");function ld(s){const e=Ni(),t=Re(s);return U.join(e,xt,t)}c(ld,"getConnectorDirPath");function ud(s){return s.match(`${xt}/[^/]+/${Pe}/src/.*`)!==null}c(ud,"isConnectorSourceFile");async function dd(s){const e=s.match(`${xt}/([^/]+)/${Pe}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Lr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=F.readFileSync(s,"utf-8");await B.withClient(a=>a.put(`connectors/${i}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}c(dd,"putConnectorFile");async function fd(s){const e=s.match(`${xt}/([^/]+)/${Pe}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Lr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await B.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(fd,"deleteConnectorFile");async function hd(s,e){try{const t=await B.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await B.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=Re(t),i=U.join(Je(),r,Pe,"src",e);F.mkdirSync(U.dirname(i),{recursive:!0}),n!=null?(F.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):F.existsSync(i)&&(F.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}c(hd,"pullConnectorFile");async function pd(s,e){const t=await B.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=U.join(Je(),n,Pe,"src",e);F.existsSync(r)&&(F.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(pd,"deleteLocalConnectorFile");async function md(s,e,t){if(t&&e!==t)try{const n=await B.withClient(l=>l.get(`connectors/${s}`),!1);if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=Re(n),i=U.join(Je(),r,Pe,"src"),o=U.join(i,e),a=U.join(i,t);F.existsSync(o)&&(F.mkdirSync(U.dirname(a),{recursive:!0}),F.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}c(md,"renameLocalConnectorDirectory");async function gd(s,e){try{const t=await B.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=U.join(Je(),n,Pe,"src",e);if(F.existsSync(r)){const i=U.resolve(Je());if(!U.resolve(r).startsWith(i))return;F.rmSync(r,{recursive:!0,force:!0}),b.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){b.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}c(gd,"deleteLocalConnectorDirectory");const ya=[N.DataSource,N.FieldMapping,N.Action,N.Flow,N.Package,N.AppDataSchema,N.AppEventType,N.DataLinkTable];class En{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Oe,this.localCache=new pa,this.remoteCache=new pa,this.localRepo=new Bl(this.localCache),this.remoteRepo=new Ul(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{const i=await n.putElement(e);r.put(i)}catch(i){throw b.error(`Failed to update element ${e.id}: ${i}`),i}}async deleteElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),r.remove(e)}catch(i){throw b.error(`Failed to delete element ${e.id}: ${i}`),i}}async pullConnectors(e=!1){const t=this.remoteCache.getElementsByType(N.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await ma({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await sd();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new ed({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(ue.Updated,e=>this.handleLocalEvent(e,ue.Updated)),this.localWatcher.on(ue.Deleted,e=>this.handleLocalEvent(e,ue.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new nd,this.remoteWatcher.on(Rr.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(Rr.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),await this.remoteWatcher.start(),b.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),r=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||r){const o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ae.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ae.INCOMING)),t===N.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await Dr({connectorId:o});if(!l?.key)return;const u=ld(l);await this.localWatcher?.executeWithPathLock(u,async()=>ma({connectorId:o,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Js.ConnectorFileDeleted:await pd(e,t);break;case Js.ConnectorDirectoryRenamed:await md(e,t,r);break;case Js.ConnectorDirectoryDeleted:await gd(e,t);break;default:await hd(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(ud(e.filePath))switch(t){case ue.Updated:await dd(e.filePath);break;case ue.Deleted:await fd(e.filePath);break}else{let n=X.fromPathAndData(e.filePath,e.data);if(!n){const r=X.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ae.OUTGOING)}] ${Fl.toSentenceCase(t)}: ${n.id}`),t){case ue.Updated:await this.updateElement(n,ae.OUTGOING);break;case ue.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=En.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=En.getChanges(ae.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;b.info("[resolver] Resolving changes.."),b.info("[resolver] Resolving integration elements");const e=this.changes.filter(r=>r.element.type===N.Integration);await Promise.all(e.map(async r=>this.resolveChange(r))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===ae.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==N.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of ya){const i=t.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of ya){const i=n.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case $e.DELETE:return this.deleteElement(e.element,e.direction);case $e.CREATE:return this.updateElement(e.element,e.direction);case $e.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),o=new Set([...r,...i]),a=[];for(const l of o){const u=t.get(l),f=n.get(l),d=En.detectChangeForElement(u,f,e);d&&a.push(d)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ae.INCOMING:return"local\u2190remote";case ae.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:$e.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:$e.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:$e.UPDATE,element:e,direction:n,isConflict:!1}:null}}const He=K.join(rl.tmpdir(),"membrane-mcp-status"),wa=3e4;class yd{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=ds(void 0,e),n=ba(e);t&&Oe.setMcpStatus(t),await Oe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function ds(s,e){try{const t=e||process.cwd();if(!s){const r=ba(t);return r.length===0?null:r[0]}const n=qr(s,t);if(L.existsSync(n)){const r=L.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>wa)return tn(s,t),null;const a=L.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>wa)return tn(s,t),null}return l}}catch{s&&e&&tn(s,e)}return null}c(ds,"getMcpStatus");function ba(s){try{const e=s||process.cwd(),t=Fr(e);if(!L.existsSync(He))return[];const n=L.readdirSync(He),r=[];for(const i of n){const o=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=ds(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(ba,"getAllMcpStatusFiles");function jr(s){try{const t={...ds(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};L.existsSync(He)||L.mkdirSync(He,{recursive:!0});const n=qr(s.processId,s.cwd);L.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(jr,"updateMcpStatus");function tn(s,e){try{const t=e||process.cwd();if(s){const n=qr(s,t);L.existsSync(n)&&L.unlinkSync(n)}else{const n=Fr(t);if(L.existsSync(He)){const r=L.readdirSync(He);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&L.unlinkSync(K.join(He,i))}}}catch{}}c(tn,"clearMcpStatus");function wd(s,e){const t=ds(s,e);t&&jr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(wd,"trackToolExecution");function Fr(s){return Qc("md5").update(s).digest("hex").slice(0,8)}c(Fr,"getCwdHash");function qr(s,e){const t=Fr(e);return K.join(He,`mcp-${t}-${s}.json`)}c(qr,"getStatusFilePath");const nn={Agent:"agent",Cli:"cli"},P={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"};class Sa{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Oe,this.mcpStatusService=new yd,this.syncService=new En,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}getSyncedElements(){return this.syncService.localCache.getAll()}getSyncedElementsByType(e){return this.syncService.localCache.getElementsByType(e)}async fetchElements(){await this.syncService.fetchElements()}async pullWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&B.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(P.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(P.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async pushWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&B.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(P.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(P.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to push workspace: ${n}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(P.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(P.SYNCED),e.watch&&(await this.notifier.setState(P.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(P.NOT_INITIALIZED);try{await this.loadConfig(),Qe.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(P.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(P.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=Qe.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const r=Qe.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===nn.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===nn.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===nn.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}const Ca=Bs(null);function bd({children:s,membraneCLIService:e}){const{data:t}=Ti("/account"),[n,r]=J(P.NOT_INITIALIZED),[i,o]=J([]),[a,l]=J({}),[u,f]=J([]),[d,h]=J(null),y=t?.workspaces?.find(p=>p.workspaceKey===d?.workspaceKey)||null;return Fe(()=>{const p=c(({state:I})=>r(I),"handleStateChanged"),w=c(({stats:I})=>l(I),"handleStatsChanged"),T=c(({log:I})=>f($=>[...$,I]),"handleLogAdded"),E=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),O=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(Q.StateChanged,p),e.notifier.on(Q.StatsChanged,w),e.notifier.on(Q.LogAdded,T),e.notifier.on(Q.ConflictsChanged,E),e.notifier.on(Q.ConfigChanged,O),e.init(),()=>{e.notifier.off(Q.StateChanged,p),e.notifier.off(Q.StatsChanged,w),e.notifier.off(Q.LogAdded,T),e.notifier.off(Q.ConflictsChanged,E),e.notifier.off(Q.ConfigChanged,O)}},[]),m(Ca.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:d,updateConfig:c(p=>e.updateConfig(p),"updateConfig"),resolveConflicts:c(p=>e.syncWorkspaces(p),"resolveConflicts"),pull:c(p=>e.pullWorkspace(p),"pull"),push:c(p=>e.pushWorkspace(p),"push"),exit:c(()=>e.shutdown(),"exit"),fetchElements:c(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:c(p=>e.getSyncedElementsByType(p),"getSyncedElementsByType")},children:s})}c(bd,"MembraneCLIServiceProvider");function de(){const s=Us(Ca);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(de,"useMembraneCLIService");const va=Bs(process.cwd());function Sd({cwd:s,children:e}){return m(va.Provider,{value:s,children:e})}c(Sd,"CwdProvider");function Cd(){return Us(va)}c(Cd,"useCwd");function sn({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Sd,{cwd:n,children:m(Lc,{value:{fetcher:Sl()},children:m(bd,{membraneCLIService:t,children:e})})})}c(sn,"Layout");const Kr=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=K.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(L.existsSync(s))try{t=JSON.parse(L.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return L.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=K.join(process.cwd(),".cursor"),e=K.join(s,"mcp.json");L.existsSync(s)||L.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(L.existsSync(e))try{n=JSON.parse(L.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return L.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function vd({onExit:s,onComplete:e}){const[t,n]=J(0),[r,i]=J(!1),[o,a]=J(null),[l,u]=J(""),[f,d]=J("");Xe((y,p)=>{if(l||f){(p.escape||y==="q"||p.return)&&e();return}if(r)p.return||y===" "?h(o):p.escape&&(i(!1),a(null));else if(p.escape)s();else if(p.upArrow||y==="k")n(Math.max(0,t-1));else if(p.downArrow||y==="j")n(Math.min(Kr.length-1,t+1));else if(p.return||y===" "){const w=Kr[t];a(w),i(!0)}});const h=c(y=>{try{const p=y.addConfig();u(p)}catch(p){d(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"green",children:"Success"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"green",children:l}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(S,{marginTop:1,paddingLeft:2,children:m(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"red",children:"Error"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:m(v,{color:"red",children:f})}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Confirmation"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[_(v,{children:["Connect ",m(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,children:m(v,{color:"yellow",bold:!0,children:o.actionDescription})}),m(S,{marginTop:2,marginBottom:1,children:_(v,{children:[m(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Select Agent"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,flexDirection:"column",children:Kr.map((y,p)=>_(S,{children:[_(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",y.name]}),_(v,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(vd,"AddMcpServerScreen");function kd(){const[s,e]=J(null),[t,n]=J([]),[r,i]=J(null);return Fe(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Oe.on(Q.McpStatusChanged,o),Oe.on(Q.McpServersChanged,a),()=>{Oe.off(Q.McpStatusChanged,o),Oe.off(Q.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:r,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(kd,"useMcpStatus");function Td(){const{error:s,serverCount:e,allMcpServers:t}=kd(),n=Math.min(100,process.stdout.columns||100);return _(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(S,{marginTop:-1,marginBottom:0,flexDirection:"column",children:_(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(v,{color:"red",children:"error reading status"}):e===0?m(v,{color:"yellow",children:"none"}):m(v,{color:"green",children:e})]})}),!s&&e===0&&m(S,{marginTop:1,children:_(v,{color:"grey",children:["Connect your AI agents to Membrane.",m(Rc,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(S,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>m(S,{children:_(v,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[a: connect an agent]"})})]})}c(Td,"Agent");const fs=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function ka(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(ka,"truncateText");function Br({children:s}){const{state:e,logs:t}=de();return!e||e===P.NOT_INITIALIZED?_(S,{gap:1,flexDirection:"row",children:[m(ol,{type:"dots"}),m(v,{children:"Initializing..."})]}):e===P.SETTING_UP?m(S,{gap:1,flexDirection:"row",children:m(v,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===P.ERROR?m(S,{flexDirection:"column",children:t.slice().map((n,r)=>m(v,{color:fs(n.type),children:n.message},n.timestamp+r))}):s}c(Br,"EnsureInitialized");function Ta({onExit:s,showEscOption:e=!0}){const[t,n]=J(""),{data:r,error:i,isLoading:o}=Ti("/account"),{updateConfig:a}=de(),l=r?.workspaces,u=o;if(Xe((p,w)=>{w.escape&&s?.()}),u)return _(S,{children:[m(An,{}),m(v,{children:" Fetching workspaces..."})]});if(i)return _(S,{flexDirection:"column",children:[_(v,{color:"red",children:["Error: ",i.message]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]});const f=l?.filter(p=>p.name.toLowerCase().includes(t.toLowerCase()))??[],d=f.map(p=>({label:p.name,value:p.id})),h=d.length,g=l?.length??0;async function y(p){const w=f.find(O=>O.id===p);if(!w)return;const{key:T,secret:E}=w;!T||!E||(await a({workspaceKey:T,workspaceSecret:E}),s?.())}return c(y,"handleSelect"),_(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,children:m(v,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),_(S,{marginTop:1,children:[m(v,{children:"Search: "}),m(al,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&_(v,{children:["Showing ",h," of ",g," workspaces."]}),m(S,{marginTop:1,children:m(cl,{options:d,onChange:c(p=>{p&&y(p)},"onChange")})}),e&&m(S,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]})}c(Ta,"SelectWorkspace");function Ed({currentPat:s,onSubmit:e}){const[t,n]=J(""),[r,i]=J(!1),[o,a]=J(null);return _(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,marginBottom:1,children:m(v,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(v,{children:"Please provide your Personal Access Token. You can find it here:"}),m(S,{marginTop:1,marginBottom:1,children:m(v,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(v,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m($i,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),i(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{i(!1)}},"handleSubmit")}),r&&m(S,{marginTop:1,children:_(v,{children:[m(An,{type:"dots"})," Validating token..."]})}),o&&m(v,{color:"red",children:o})]})}c(Ed,"PersonalAccessTokenInput");var rn=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(rn||{});const _d={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Ur=[rn.Authenticate,rn.ConnectWorkspace];function Ea({onComplete:s}){const{config:e}=de(),[t,n]=J(!1),[r,i]=J(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=Pi(),l=Ur[r],u=r+1,f=Ur.length,d=Ur.map((y,p)=>{let w="pending";return p<r?w="done":p===r&&(w="current"),{id:y,label:_d[y],status:w}});async function h(y){const p=a&&y===""?a:y,w=new Ri;try{await w.request("/account",{headers:{Authorization:`Bearer ${p}`}}),bl(p),i(T=>T+1)}catch(T){console.error(T)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Xe((y,p)=>{o&&p.escape&&s&&s()}),t?m(S,{children:m(v,{children:"\u2705 Setup complete. You are ready to go!"})}):_(S,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",_(v,{color:"cyan",children:["Step ",u," of ",f]}),o&&m(v,{color:"grey",children:" [esc: go back]"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:d.map(y=>m(Id,{status:y.status,label:y.label},y.id))})]}),l===rn.Authenticate&&m(Ed,{currentPat:a,onSubmit:h}),l===rn.ConnectWorkspace&&m(Ta,{onExit:g,showEscOption:!1})]})}c(Ea,"Setup");function Id({status:s,label:e}){return _(S,{children:[_(S,{width:2,children:[s==="current"&&m(An,{type:"dots"}),s==="done"&&m(v,{children:"\u2705"})]}),m(v,{dimColor:s!=="current",children:e})]})}c(Id,"StepDisplay");function Wr(){const{stats:s}=de(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:_(S,{flexDirection:"column",children:[m(S,{children:m(S,{width:12,children:m(v,{color:"grey",children:"Elements:"})})}),m(S,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>_(S,{children:[m(S,{width:20,children:_(v,{children:[t,":"]})}),m(v,{color:"green",children:n})]},t))})]})}c(Wr,"ElementStats");const Jr=5,Ad=6;function Od(){const{logs:s}=de(),[e,t]=J(0),n=Math.min(100,process.stdout.columns||100),r=Jr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-Ad,u=e<s.length-r,f=e>0;return Xe((d,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-r);t(y=>Math.min(g,y+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),_(S,{flexDirection:"column",paddingTop:1,children:[_(v,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>Jr&&m(v,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(S,{marginLeft:1,children:m(v,{color:fs(d.type),children:ka(d.message,l)})},d.timestamp+h)),s.length>Jr&&_(S,{marginLeft:1,flexDirection:"row",children:[u&&m(v,{color:"grey",children:"\u2191 "}),f&&m(v,{color:"grey",children:"\u2193 "})]})]})}c(Od,"Logs");const hs=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function $d(){const{state:s,resolveConflicts:e,exit:t}=de(),[n,r]=J(0),[i,o]=J(!1),[a,l]=J(!1);return Xe((u,f)=>{if(!i){if(f.ctrl&&u.toLowerCase()==="r"){l(!a);return}f.upArrow?r(d=>d>0?d-1:hs.length-1):f.downArrow?r(d=>d<hs.length-1?d+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(f.return||u===" ")&&(o(!0),hs[n].value==="sync"?e({watch:!0}):t())}}),Fe(()=>{s!==P.CONFLICTS&&i&&o(!1)},[s,i]),_(S,{flexDirection:"column",paddingTop:1,children:[m(S,{children:m(S,{flexDirection:"row",gap:2,children:m(v,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(S,{children:m(v,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(S,{marginTop:1,marginLeft:2,children:m(Hr,{isExpanded:a})}),_(S,{marginTop:2,flexDirection:"row",gap:1,children:[m(v,{color:"white",bold:!0,children:"What would you like to do?"}),m(v,{color:"grey",children:"[up/down, enter]"})]}),m(S,{children:i?_(S,{flexDirection:"row",gap:1,children:[m(An,{type:"dots"}),m(v,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(S,{flexDirection:"column",children:hs.map((u,f)=>m(S,{flexDirection:"column",children:_(S,{flexDirection:"row",gap:1,children:[m(v,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),m(v,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}c($d,"ResolveChangesUI");const Nd={[$e.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[$e.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[$e.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Hr({isExpanded:s,showControls:e=!0}){const{conflicts:t}=de(),n=5,r=Dc(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return m(S,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=Nd[a][l];return _(S,{flexDirection:"column",children:[_(S,{flexDirection:"row",gap:1,children:[_(v,{color:"yellow",children:[u.label," (",o.length,")"]}),m(v,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(f=>m(S,{marginLeft:2,children:_(v,{color:"grey",children:["\u2022 ",f.element.id," (",f.element.relativePath,")"]})},f.element.id)),!s&&o.length>n&&m(S,{marginLeft:2,children:_(v,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&m(S,{marginLeft:2,children:m(v,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Hr,"Conflicts");function xd(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=de(),i=n?.name,o=i?ka(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Fe(()=>{r({watch:!0})},[]),_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(S,{marginTop:-1,marginBottom:1,children:_(S,{flexDirection:"row",gap:1,children:[m(v,{bold:!0,children:"\u{1F504} Workspace"}),_(v,{color:Rd(e),children:[" [",Pd(e),"] "]})]})}),_(S,{children:[m(S,{width:12,children:m(v,{color:"grey",children:"Local:"})}),m(v,{color:"grey",children:process.cwd()})]}),_(S,{children:[m(S,{width:12,children:m(v,{color:"grey",children:"Remote:"})}),s?.workspaceKey?_(v,{color:"grey",children:[o," [o: open in console] [w: change]"]}):_(v,{children:[m(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===P.CONFLICTS?m($d,{}):_(ut,{children:[m(S,{paddingTop:1,children:m(Wr,{})}),t.length>0&&m(Od,{})]})]})}c(xd,"Workspace");function Pd(s){switch(s){case P.PULLING:return"pulling";case P.PUSHING:return"pushing";case P.CONFLICTS:return"conflicts";case P.SYNCED:return"synced";case P.ERROR:return"error";case P.WATCHING:return"tracking changes";case P.RESOLVING:return"resolving";case P.NOT_SYNCED:return"not synced";case P.INITIALIZED:return"initialized";case P.SETTING_UP:return"setup required";default:return"unknown"}}c(Pd,"getStatusDisplay");function Rd(s){switch(s){case P.PULLING:return"yellow";case P.PUSHING:return"yellow";case P.CONFLICTS:return"red";case P.SYNCED:return"green";case P.ERROR:return"red";case P.WATCHING:return"green";case P.RESOLVING:return"yellow";case P.NOT_SYNCED:return"grey";case P.SETTING_UP:return"yellow";default:return"grey"}}c(Rd,"getStatusColor");const Md="https://console.integration.app/w";function Ld(){const s=Cd(),e=Ws(!0),{exit:t,state:n}=de(),[r,i]=J(null),o=r??(n===P.SETTING_UP?"setup":"main");Xe(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===P.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await ji(s),u=`${Md}/${l}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";il(`${f} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Fe(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Ta,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?m(vd,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?m(Ea,{onComplete:c(()=>i(null),"onComplete")},Date.now()):m(Br,{children:_(S,{flexDirection:"column",children:[m(S,{flexGrow:1,children:m(Td,{})}),m(xd,{}),m(S,{paddingLeft:2,children:m(v,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Ld,"Main");const Dd=c(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 Real-time agent mode is experimental and subject to changes. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
141
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=us(e),n=Nt(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=us(e),n=Nt(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}function fa(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new ca||null,prettyErrors:e}}c(fa,"parseOptions");function zu(s,e={}){const{lineCounter:t,prettyErrors:n}=fa(e),r=new Pr(t?.addNewLine),i=new Or(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(ss(s,t)),a.warnings.forEach(ss(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(zu,"parseAllDocuments");function ha(s,e={}){const{lineCounter:t,prettyErrors:n}=fa(e),r=new Pr(t?.addNewLine),i=new Or(e);let o=null;for(const a of i.compose(r.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new st(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(ss(s,t)),o.warnings.forEach(ss(s,t))),o}c(ha,"parseDocument");function Yu(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=ha(s,t);if(!r)return null;if(r.warnings.forEach(i=>To(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},t))}c(Yu,"parse");function Xu(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(s===void 0){const{keepUndefined:r}=t??e??{};if(!r)return}return Ze(s)&&!n?s.toString(t):new Bt(s,n,t).toString(t)}c(Xu,"stringify");var Qu=Object.freeze({__proto__:null,Alias:qn,CST:Hu,Composer:Or,Document:Bt,Lexer:aa,LineCounter:ca,Pair:se,Parser:Pr,Scalar:R,Schema:Ls,YAMLError:kr,YAMLMap:le,YAMLParseError:st,YAMLSeq:Ue,YAMLWarning:Vo,isAlias:Be,isCollection:z,isDocument:Ze,isMap:St,isNode:Y,isPair:V,isScalar:H,isSeq:Ct,parse:Yu,parseAllDocuments:zu,parseDocument:ha,stringify:Xu,visit:et,visitAsync:Fn});const ue={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Zu={ignored:kl,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:20,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class ed extends nr{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=dt(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(L.existsSync(this.membraneDir)||L.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Zc.watch(this.membraneDir,Zu),this.watcher.on("add",e=>this.handleFileSystemEvent(ue.Updated,e)).on("change",e=>this.handleFileSystemEvent(ue.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(ue.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(ue.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=K.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=K.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+K.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=K.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===ue.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const o=this.processFileEvent(t,r);this.updateCache(n,r),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return L.readFileSync(e,"utf8")}processFileEvent(e,t){const n=K.relative(this.membraneDir,e);let r;try{r=t?Qu.parse(t):void 0}catch{r=void 0}return{filePath:e,relativePath:n,data:r}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return Xc.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){L.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=L.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=K.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=L.readFileSync(r,"utf8"),o=K.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var Rr=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(Rr||{});const td={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class nd extends nr{static{c(this,"RemoteElementWatcher")}constructor(e=td){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;connectionTimeout;isStarted=!1;isConnected=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.isConnected=!1,this.clearReconnectTimeout(),this.clearConnectionTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{b.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await B.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;b.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new el(n),this.setupEventSourceHandlers()}catch(e){b.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.debug("[remote-events] Connected to server"),this.reconnectAttempts=0,this.isConnected=!0,this.resetConnectionTimeout(),this.emit("connected",{})},this.eventSource.onmessage=e=>{try{this.resetConnectionTimeout();const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.debug(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.isConnected=!1,this.clearConnectionTimeout(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Bc.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===N.Connector){const{filePath:i,eventType:o,newPath:a}=r;return b.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,i,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const r=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,r)}scheduleConnectorFileUpdate(e,t,n,r){const i=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(i);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(i),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:r})},this.config.debounceMs);this.debounceTimeouts.set(i,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&(b.error("[remote-events] Max reconnection attempts reached. Connection will not be retried."),this.emit("error",{error:new Error("Max reconnection attempts reached")}));return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.reconnectAttempts++;const e=this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),t=Math.random()*.3*e,n=Math.min(e+t,this.config.maxBackoffMs);b.debug(`[remote-events] Reconnecting in ${Math.round(n)}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},n)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}resetConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeout=setTimeout(()=>{this.isConnected&&this.isStarted&&(b.debug("[remote-events] Connection timeout detected, reconnecting..."),this.isConnected=!1,this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.scheduleReconnect())},this.config.connectionTimeoutMs)}clearConnectionTimeout(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class pa{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const r=this.typeIndex.get(e.type);r&&(r.delete(t),r.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}const xt="connectors",Pe="development",Mr={};async function sd(){const e=(await B.withClient(o=>o.get("org-workspace-id"))).id,t={};b.info("[connectors] Loading custom connectors"),await B.withClient(o=>o.get(`/connectors?workspaceId=${e}`)),b.info("[connectors] Loading public connectors");const n=Je(),i=(F.existsSync(n)?F.readdirSync(n):[]).filter(o=>{if(o.startsWith("."))return!1;const a=U.join(n,o);try{return F.statSync(a).isDirectory()}catch{return!1}});for(const o of i){b.info(`[connectors] Loading connector from: ${o}`);const a=F.readdirSync(U.join(n,o)),l=await Lr(o);if(!l)continue;"baseUri"in l&&delete l.baseUri;let u;if(l.uuid&&(u=await B.withClient(d=>d.get(`/connectors/${l.uuid}`),!1)),u)t[l.id]=u.id,b.info(`[connectors] Matched ${l.name} uuid: ${l.uuid}`),u.archivedAt&&(b.info(`[connectors] Restoring archived connector ${l.name}`),await B.withClient(d=>d.post(`connectors/${u.id}/restore`))),b.info(`[connectors] Updating connector ${l.name}`),await B.withClient(d=>d.patch(`connectors/${u.id}`,{...l,workspaceId:e}));else if(!t[l.id]){let d=!1;try{const h=await Dr({connectorId:l.id});h&&h.isPublic&&(d=!0)}catch{}if(!d){b.info(`[connectors] Creating custom connector ${l.name} (${l.key})`);const h=await B.withClient(g=>g.post("connectors",{...l,workspaceId:e}));t[l.id]=h.id}}const f=a.filter(d=>F.statSync(U.join(n,o,d)).isDirectory());for(const d of f)await od({connector:l,version:d,connectorId:t[l.id]})}return t}c(sd,"pushConnectors");async function ma({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=Ni(),o=await Dr({connectorId:s});if(!o.isPublic||t){if(!o?.key){b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await ad({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await cd({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(ma,"pullRemoteConnector");function Je(){const s=tr();return U.join(s.membraneDirPath,xt)}c(Je,"getConnectorsPath");async function Lr(s){const e=U.join(Je(),s,`${s}.yml`);return ir(e,!1)}c(Lr,"readConnector");async function rd(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=F.createWriteStream(e),i=tl("zip",{zlib:{level:9}});r.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{b.info("[connectors] Data has been drained")}),i.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),i.on("error",a=>{n(a)}),i.pipe(r);const o=F.readdirSync(s);for(const a of o){const l=U.join(s,a),u=F.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(rd,"createZipArchive");async function id(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=sl.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=U.join(e,o);F.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=U.join(e,o),u=U.dirname(l);F.mkdirSync(u,{recursive:!0});const f=F.createWriteStream(l);i.pipe(f),f.on("finish",()=>{})}}),r.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(s),r.end()})}c(id,"extractZipArchive");async function od({connector:s,version:e,connectorId:t}){const n=U.join(Je(),Re(s),ga(e)),r=U.join(n,"src"),i=U.join(n,"src.zip"),o=F.existsSync(i);if(F.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await rd(r,i)),!F.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new nl;if(a.append("file",F.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Pe)b.info(`[connectors] Uploading connector ${t}`),await B.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await B.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){b.info(`[connectors] Version ${e} already published`);return}b.info(`[connectors] Publishing version ${e} of connector ${t}`),await B.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&F.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),F.unlinkSync(i))}}c(od,"pushConnectorVersion");async function Dr({connectorId:s}){if(s){if(Mr[s])return Mr[s];try{const e=await B.withClient(t=>t.get(`connectors/${s}`),!1);return Mr[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(Dr,"getConnector");async function ad({basePath:s,connector:e}){const t=Re(e),n=U.join(s,xt,t);F.mkdirSync(n,{recursive:!0});const r=U.join(n,`${Re(e)}.yml`);F.writeFileSync(r,Wt.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(ad,"pullConnector");async function cd({connector:s,connectorVersion:e,basePath:t}){const n=Re(s),r=ga(e),i=U.join(t,"connectors",n,r),o=await B.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));F.mkdirSync(i,{recursive:!0});const a=U.join(i,"src.zip");if(F.writeFileSync(a,o),!e){const l=U.join(i,"src");F.mkdirSync(l,{recursive:!0}),await id(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(cd,"pullConnectorVersion");function Re(s){return s.key}c(Re,"getConnectorDirName");function ga(s){return s??Pe}c(ga,"getConnectorVersionDirName");function ld(s){const e=Ni(),t=Re(s);return U.join(e,xt,t)}c(ld,"getConnectorDirPath");function ud(s){return s.match(`${xt}/[^/]+/${Pe}/src/.*`)!==null}c(ud,"isConnectorSourceFile");async function dd(s){const e=s.match(`${xt}/([^/]+)/${Pe}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Lr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=F.readFileSync(s,"utf-8");await B.withClient(a=>a.put(`connectors/${i}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}c(dd,"putConnectorFile");async function fd(s){const e=s.match(`${xt}/([^/]+)/${Pe}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Lr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await B.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(fd,"deleteConnectorFile");async function hd(s,e){try{const t=await B.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await B.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=Re(t),i=U.join(Je(),r,Pe,"src",e);F.mkdirSync(U.dirname(i),{recursive:!0}),n!=null?(F.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):F.existsSync(i)&&(F.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}c(hd,"pullConnectorFile");async function pd(s,e){const t=await B.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=U.join(Je(),n,Pe,"src",e);F.existsSync(r)&&(F.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(pd,"deleteLocalConnectorFile");async function md(s,e,t){if(t&&e!==t)try{const n=await B.withClient(l=>l.get(`connectors/${s}`),!1);if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=Re(n),i=U.join(Je(),r,Pe,"src"),o=U.join(i,e),a=U.join(i,t);F.existsSync(o)&&(F.mkdirSync(U.dirname(a),{recursive:!0}),F.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}c(md,"renameLocalConnectorDirectory");async function gd(s,e){try{const t=await B.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=U.join(Je(),n,Pe,"src",e);if(F.existsSync(r)){const i=U.resolve(Je());if(!U.resolve(r).startsWith(i))return;F.rmSync(r,{recursive:!0,force:!0}),b.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){b.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}c(gd,"deleteLocalConnectorDirectory");const ya=[N.AppDataSchema,N.AppEventType,N.DataLinkTable,N.DataSource,N.FieldMapping,N.Action,N.Flow,N.Package];class En{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Oe,this.localCache=new pa,this.remoteCache=new pa,this.localRepo=new Bl(this.localCache),this.remoteRepo=new Ul(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{const i=await n.putElement(e);r.put(i)}catch(i){throw b.error(`Failed to update element ${e.id}: ${i}`),i}}async deleteElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),r.remove(e)}catch(i){throw b.error(`Failed to delete element ${e.id}: ${i}`),i}}async pullConnectors(e=!1){const t=this.remoteCache.getElementsByType(N.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await ma({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await sd();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new ed({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(ue.Updated,e=>this.handleLocalEvent(e,ue.Updated)),this.localWatcher.on(ue.Deleted,e=>this.handleLocalEvent(e,ue.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new nd,this.remoteWatcher.on(Rr.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(Rr.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),await this.remoteWatcher.start(),b.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),r=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||r){const o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ae.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ae.INCOMING)),t===N.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await Dr({connectorId:o});if(!l?.key)return;const u=ld(l);await this.localWatcher?.executeWithPathLock(u,async()=>ma({connectorId:o,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Js.ConnectorFileDeleted:await pd(e,t);break;case Js.ConnectorDirectoryRenamed:await md(e,t,r);break;case Js.ConnectorDirectoryDeleted:await gd(e,t);break;default:await hd(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(ud(e.filePath))switch(t){case ue.Updated:await dd(e.filePath);break;case ue.Deleted:await fd(e.filePath);break}else{let n=X.fromPathAndData(e.filePath,e.data);if(!n){const r=X.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ae.OUTGOING)}] ${Fl.toSentenceCase(t)}: ${n.id}`),t){case ue.Updated:await this.updateElement(n,ae.OUTGOING);break;case ue.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=En.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=En.getChanges(ae.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;b.info("[resolver] Resolving changes.."),b.info("[resolver] Resolving integration elements");const e=this.changes.filter(r=>r.element.type===N.Integration);await Promise.all(e.map(async r=>this.resolveChange(r))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===ae.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==N.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of ya){const i=t.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of ya){const i=n.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case $e.DELETE:return this.deleteElement(e.element,e.direction);case $e.CREATE:return this.updateElement(e.element,e.direction);case $e.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),o=new Set([...r,...i]),a=[];for(const l of o){const u=t.get(l),f=n.get(l),d=En.detectChangeForElement(u,f,e);d&&a.push(d)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ae.INCOMING:return"local\u2190remote";case ae.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:$e.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:$e.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:$e.UPDATE,element:e,direction:n,isConflict:!1}:null}}const He=K.join(rl.tmpdir(),"membrane-mcp-status"),wa=3e4;class yd{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=ds(void 0,e),n=ba(e);t&&Oe.setMcpStatus(t),await Oe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function ds(s,e){try{const t=e||process.cwd();if(!s){const r=ba(t);return r.length===0?null:r[0]}const n=qr(s,t);if(L.existsSync(n)){const r=L.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>wa)return tn(s,t),null;const a=L.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>wa)return tn(s,t),null}return l}}catch{s&&e&&tn(s,e)}return null}c(ds,"getMcpStatus");function ba(s){try{const e=s||process.cwd(),t=Fr(e);if(!L.existsSync(He))return[];const n=L.readdirSync(He),r=[];for(const i of n){const o=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=ds(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(ba,"getAllMcpStatusFiles");function jr(s){try{const t={...ds(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};L.existsSync(He)||L.mkdirSync(He,{recursive:!0});const n=qr(s.processId,s.cwd);L.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(jr,"updateMcpStatus");function tn(s,e){try{const t=e||process.cwd();if(s){const n=qr(s,t);L.existsSync(n)&&L.unlinkSync(n)}else{const n=Fr(t);if(L.existsSync(He)){const r=L.readdirSync(He);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&L.unlinkSync(K.join(He,i))}}}catch{}}c(tn,"clearMcpStatus");function wd(s,e){const t=ds(s,e);t&&jr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(wd,"trackToolExecution");function Fr(s){return Qc("md5").update(s).digest("hex").slice(0,8)}c(Fr,"getCwdHash");function qr(s,e){const t=Fr(e);return K.join(He,`mcp-${t}-${s}.json`)}c(qr,"getStatusFilePath");const nn={Agent:"agent",Cli:"cli"},P={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"};class Sa{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Oe,this.mcpStatusService=new yd,this.syncService=new En,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}getSyncedElements(){return this.syncService.localCache.getAll()}getSyncedElementsByType(e){return this.syncService.localCache.getElementsByType(e)}async fetchElements(){await this.syncService.fetchElements()}async pullWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&B.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(P.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(P.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async pushWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&B.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(P.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(P.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to push workspace: ${n}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(P.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(P.SYNCED),e.watch&&(await this.notifier.setState(P.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(P.NOT_INITIALIZED);try{await this.loadConfig(),Qe.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(P.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(P.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=Qe.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const r=Qe.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===nn.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===nn.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===nn.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}const Ca=Bs(null);function bd({children:s,membraneCLIService:e}){const{data:t}=Ti("/account"),[n,r]=J(P.NOT_INITIALIZED),[i,o]=J([]),[a,l]=J({}),[u,f]=J([]),[d,h]=J(null),y=t?.workspaces?.find(p=>p.workspaceKey===d?.workspaceKey)||null;return Fe(()=>{const p=c(({state:I})=>r(I),"handleStateChanged"),w=c(({stats:I})=>l(I),"handleStatsChanged"),T=c(({log:I})=>f($=>[...$,I]),"handleLogAdded"),E=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),O=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(Q.StateChanged,p),e.notifier.on(Q.StatsChanged,w),e.notifier.on(Q.LogAdded,T),e.notifier.on(Q.ConflictsChanged,E),e.notifier.on(Q.ConfigChanged,O),e.init(),()=>{e.notifier.off(Q.StateChanged,p),e.notifier.off(Q.StatsChanged,w),e.notifier.off(Q.LogAdded,T),e.notifier.off(Q.ConflictsChanged,E),e.notifier.off(Q.ConfigChanged,O)}},[]),m(Ca.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:d,updateConfig:c(p=>e.updateConfig(p),"updateConfig"),resolveConflicts:c(p=>e.syncWorkspaces(p),"resolveConflicts"),pull:c(p=>e.pullWorkspace(p),"pull"),push:c(p=>e.pushWorkspace(p),"push"),exit:c(()=>e.shutdown(),"exit"),fetchElements:c(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:c(p=>e.getSyncedElementsByType(p),"getSyncedElementsByType")},children:s})}c(bd,"MembraneCLIServiceProvider");function de(){const s=Us(Ca);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(de,"useMembraneCLIService");const va=Bs(process.cwd());function Sd({cwd:s,children:e}){return m(va.Provider,{value:s,children:e})}c(Sd,"CwdProvider");function Cd(){return Us(va)}c(Cd,"useCwd");function sn({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Sd,{cwd:n,children:m(Lc,{value:{fetcher:Sl()},children:m(bd,{membraneCLIService:t,children:e})})})}c(sn,"Layout");const Kr=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=K.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(L.existsSync(s))try{t=JSON.parse(L.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return L.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=K.join(process.cwd(),".cursor"),e=K.join(s,"mcp.json");L.existsSync(s)||L.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(L.existsSync(e))try{n=JSON.parse(L.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return L.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function vd({onExit:s,onComplete:e}){const[t,n]=J(0),[r,i]=J(!1),[o,a]=J(null),[l,u]=J(""),[f,d]=J("");Xe((y,p)=>{if(l||f){(p.escape||y==="q"||p.return)&&e();return}if(r)p.return||y===" "?h(o):p.escape&&(i(!1),a(null));else if(p.escape)s();else if(p.upArrow||y==="k")n(Math.max(0,t-1));else if(p.downArrow||y==="j")n(Math.min(Kr.length-1,t+1));else if(p.return||y===" "){const w=Kr[t];a(w),i(!0)}});const h=c(y=>{try{const p=y.addConfig();u(p)}catch(p){d(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"green",children:"Success"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"green",children:l}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(S,{marginTop:1,paddingLeft:2,children:m(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"red",children:"Error"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:m(v,{color:"red",children:f})}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Confirmation"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[_(v,{children:["Connect ",m(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,children:m(v,{color:"yellow",bold:!0,children:o.actionDescription})}),m(S,{marginTop:2,marginBottom:1,children:_(v,{children:[m(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Select Agent"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,flexDirection:"column",children:Kr.map((y,p)=>_(S,{children:[_(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",y.name]}),_(v,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(vd,"AddMcpServerScreen");function kd(){const[s,e]=J(null),[t,n]=J([]),[r,i]=J(null);return Fe(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Oe.on(Q.McpStatusChanged,o),Oe.on(Q.McpServersChanged,a),()=>{Oe.off(Q.McpStatusChanged,o),Oe.off(Q.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:r,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(kd,"useMcpStatus");function Td(){const{error:s,serverCount:e,allMcpServers:t}=kd(),n=Math.min(100,process.stdout.columns||100);return _(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(S,{marginTop:-1,marginBottom:0,flexDirection:"column",children:_(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(v,{color:"red",children:"error reading status"}):e===0?m(v,{color:"yellow",children:"none"}):m(v,{color:"green",children:e})]})}),!s&&e===0&&m(S,{marginTop:1,children:_(v,{color:"grey",children:["Connect your AI agents to Membrane.",m(Rc,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(S,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>m(S,{children:_(v,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[a: connect an agent]"})})]})}c(Td,"Agent");const fs=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function ka(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(ka,"truncateText");function Br({children:s}){const{state:e,logs:t}=de();return!e||e===P.NOT_INITIALIZED?_(S,{gap:1,flexDirection:"row",children:[m(ol,{type:"dots"}),m(v,{children:"Initializing..."})]}):e===P.SETTING_UP?m(S,{gap:1,flexDirection:"row",children:m(v,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===P.ERROR?m(S,{flexDirection:"column",children:t.slice().map((n,r)=>m(v,{color:fs(n.type),children:n.message},n.timestamp+r))}):s}c(Br,"EnsureInitialized");function Ta({onExit:s,showEscOption:e=!0}){const[t,n]=J(""),{data:r,error:i,isLoading:o}=Ti("/account"),{updateConfig:a}=de(),l=r?.workspaces,u=o;if(Xe((p,w)=>{w.escape&&s?.()}),u)return _(S,{children:[m(An,{}),m(v,{children:" Fetching workspaces..."})]});if(i)return _(S,{flexDirection:"column",children:[_(v,{color:"red",children:["Error: ",i.message]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]});const f=l?.filter(p=>p.name.toLowerCase().includes(t.toLowerCase()))??[],d=f.map(p=>({label:p.name,value:p.id})),h=d.length,g=l?.length??0;async function y(p){const w=f.find(O=>O.id===p);if(!w)return;const{key:T,secret:E}=w;!T||!E||(await a({workspaceKey:T,workspaceSecret:E}),s?.())}return c(y,"handleSelect"),_(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,children:m(v,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),_(S,{marginTop:1,children:[m(v,{children:"Search: "}),m(al,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&_(v,{children:["Showing ",h," of ",g," workspaces."]}),m(S,{marginTop:1,children:m(cl,{options:d,onChange:c(p=>{p&&y(p)},"onChange")})}),e&&m(S,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]})}c(Ta,"SelectWorkspace");function Ed({currentPat:s,onSubmit:e}){const[t,n]=J(""),[r,i]=J(!1),[o,a]=J(null);return _(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,marginBottom:1,children:m(v,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(v,{children:"Please provide your Personal Access Token. You can find it here:"}),m(S,{marginTop:1,marginBottom:1,children:m(v,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(v,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m($i,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),i(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{i(!1)}},"handleSubmit")}),r&&m(S,{marginTop:1,children:_(v,{children:[m(An,{type:"dots"})," Validating token..."]})}),o&&m(v,{color:"red",children:o})]})}c(Ed,"PersonalAccessTokenInput");var rn=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(rn||{});const _d={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Ur=[rn.Authenticate,rn.ConnectWorkspace];function Ea({onComplete:s}){const{config:e}=de(),[t,n]=J(!1),[r,i]=J(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=Pi(),l=Ur[r],u=r+1,f=Ur.length,d=Ur.map((y,p)=>{let w="pending";return p<r?w="done":p===r&&(w="current"),{id:y,label:_d[y],status:w}});async function h(y){const p=a&&y===""?a:y,w=new Ri;try{await w.request("/account",{headers:{Authorization:`Bearer ${p}`}}),bl(p),i(T=>T+1)}catch(T){console.error(T)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Xe((y,p)=>{o&&p.escape&&s&&s()}),t?m(S,{children:m(v,{children:"\u2705 Setup complete. You are ready to go!"})}):_(S,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",_(v,{color:"cyan",children:["Step ",u," of ",f]}),o&&m(v,{color:"grey",children:" [esc: go back]"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:d.map(y=>m(Id,{status:y.status,label:y.label},y.id))})]}),l===rn.Authenticate&&m(Ed,{currentPat:a,onSubmit:h}),l===rn.ConnectWorkspace&&m(Ta,{onExit:g,showEscOption:!1})]})}c(Ea,"Setup");function Id({status:s,label:e}){return _(S,{children:[_(S,{width:2,children:[s==="current"&&m(An,{type:"dots"}),s==="done"&&m(v,{children:"\u2705"})]}),m(v,{dimColor:s!=="current",children:e})]})}c(Id,"StepDisplay");function Wr(){const{stats:s}=de(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:_(S,{flexDirection:"column",children:[m(S,{children:m(S,{width:12,children:m(v,{color:"grey",children:"Elements:"})})}),m(S,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>_(S,{children:[m(S,{width:20,children:_(v,{children:[t,":"]})}),m(v,{color:"green",children:n})]},t))})]})}c(Wr,"ElementStats");const Jr=5,Ad=6;function Od(){const{logs:s}=de(),[e,t]=J(0),n=Math.min(100,process.stdout.columns||100),r=Jr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-Ad,u=e<s.length-r,f=e>0;return Xe((d,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-r);t(y=>Math.min(g,y+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),_(S,{flexDirection:"column",paddingTop:1,children:[_(v,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>Jr&&m(v,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(S,{marginLeft:1,children:m(v,{color:fs(d.type),children:ka(d.message,l)})},d.timestamp+h)),s.length>Jr&&_(S,{marginLeft:1,flexDirection:"row",children:[u&&m(v,{color:"grey",children:"\u2191 "}),f&&m(v,{color:"grey",children:"\u2193 "})]})]})}c(Od,"Logs");const hs=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function $d(){const{state:s,resolveConflicts:e,exit:t}=de(),[n,r]=J(0),[i,o]=J(!1),[a,l]=J(!1);return Xe((u,f)=>{if(!i){if(f.ctrl&&u.toLowerCase()==="r"){l(!a);return}f.upArrow?r(d=>d>0?d-1:hs.length-1):f.downArrow?r(d=>d<hs.length-1?d+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(f.return||u===" ")&&(o(!0),hs[n].value==="sync"?e({watch:!0}):t())}}),Fe(()=>{s!==P.CONFLICTS&&i&&o(!1)},[s,i]),_(S,{flexDirection:"column",paddingTop:1,children:[m(S,{children:m(S,{flexDirection:"row",gap:2,children:m(v,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(S,{children:m(v,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(S,{marginTop:1,marginLeft:2,children:m(Hr,{isExpanded:a})}),_(S,{marginTop:2,flexDirection:"row",gap:1,children:[m(v,{color:"white",bold:!0,children:"What would you like to do?"}),m(v,{color:"grey",children:"[up/down, enter]"})]}),m(S,{children:i?_(S,{flexDirection:"row",gap:1,children:[m(An,{type:"dots"}),m(v,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(S,{flexDirection:"column",children:hs.map((u,f)=>m(S,{flexDirection:"column",children:_(S,{flexDirection:"row",gap:1,children:[m(v,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),m(v,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}c($d,"ResolveChangesUI");const Nd={[$e.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[$e.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[$e.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Hr({isExpanded:s,showControls:e=!0}){const{conflicts:t}=de(),n=5,r=Dc(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return m(S,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=Nd[a][l];return _(S,{flexDirection:"column",children:[_(S,{flexDirection:"row",gap:1,children:[_(v,{color:"yellow",children:[u.label," (",o.length,")"]}),m(v,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(f=>m(S,{marginLeft:2,children:_(v,{color:"grey",children:["\u2022 ",f.element.id," (",f.element.relativePath,")"]})},f.element.id)),!s&&o.length>n&&m(S,{marginLeft:2,children:_(v,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&m(S,{marginLeft:2,children:m(v,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Hr,"Conflicts");function xd(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=de(),i=n?.name,o=i?ka(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Fe(()=>{r({watch:!0})},[]),_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(S,{marginTop:-1,marginBottom:1,children:_(S,{flexDirection:"row",gap:1,children:[m(v,{bold:!0,children:"\u{1F504} Workspace"}),_(v,{color:Rd(e),children:[" [",Pd(e),"] "]})]})}),_(S,{children:[m(S,{width:12,children:m(v,{color:"grey",children:"Local:"})}),m(v,{color:"grey",children:process.cwd()})]}),_(S,{children:[m(S,{width:12,children:m(v,{color:"grey",children:"Remote:"})}),s?.workspaceKey?_(v,{color:"grey",children:[o," [o: open in console] [w: change]"]}):_(v,{children:[m(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===P.CONFLICTS?m($d,{}):_(ut,{children:[m(S,{paddingTop:1,children:m(Wr,{})}),t.length>0&&m(Od,{})]})]})}c(xd,"Workspace");function Pd(s){switch(s){case P.PULLING:return"pulling";case P.PUSHING:return"pushing";case P.CONFLICTS:return"conflicts";case P.SYNCED:return"synced";case P.ERROR:return"error";case P.WATCHING:return"tracking changes";case P.RESOLVING:return"resolving";case P.NOT_SYNCED:return"not synced";case P.INITIALIZED:return"initialized";case P.SETTING_UP:return"setup required";default:return"unknown"}}c(Pd,"getStatusDisplay");function Rd(s){switch(s){case P.PULLING:return"yellow";case P.PUSHING:return"yellow";case P.CONFLICTS:return"red";case P.SYNCED:return"green";case P.ERROR:return"red";case P.WATCHING:return"green";case P.RESOLVING:return"yellow";case P.NOT_SYNCED:return"grey";case P.SETTING_UP:return"yellow";default:return"grey"}}c(Rd,"getStatusColor");const Md="https://console.integration.app/w";function Ld(){const s=Cd(),e=Ws(!0),{exit:t,state:n}=de(),[r,i]=J(null),o=r??(n===P.SETTING_UP?"setup":"main");Xe(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===P.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await ji(s),u=`${Md}/${l}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";il(`${f} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Fe(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Ta,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?m(vd,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?m(Ea,{onComplete:c(()=>i(null),"onComplete")},Date.now()):m(Br,{children:_(S,{flexDirection:"column",children:[m(S,{flexGrow:1,children:m(Td,{})}),m(xd,{}),m(S,{paddingLeft:2,children:m(v,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Ld,"Main");const Dd=c(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 Real-time agent mode is experimental and subject to changes. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
142
142
  `),"createExperimentalWarning$2"),on=Mc(process.argv.slice(2)),_a=on.cwd?xc(on.cwd):process.cwd(),jd=new Sa(nn.Agent,_a);if(on.verbose&&b.setVerboseMode(!0),on.rps!==void 0){const s=parseInt(on.rps,10);!isNaN(s)&&s>0&&s<=1e3?B.init({maxRequestsPerSecond:s}):isNaN(s)||(b.error(`Invalid RPS value: ${s}. Must be between 1 and 1000.`),process.exit(1))}const Fd=c(()=>m(sn,{cwd:_a,membraneCLIService:jd,children:m(Ld,{})}),"App");function qd(){console.warn(Dd()),Ut(m(Fd,{}))}c(qd,"runAgent");function it(s){if(s.type){if(Array.isArray(s.type))return{anyOf:s.type.map(t=>it({...s,type:t}))};if(s.type==="array"){const t={type:"array",items:s.items?it(s.items):{type:"object"}};return s.title&&(t.title=s.title),s.description&&(t.description=s.description),s.minItems!==void 0&&(t.minItems=s.minItems),s.maxItems!==void 0&&(t.maxItems=s.maxItems),s.uniqueItems!==void 0&&(t.uniqueItems=s.uniqueItems),t}}const e={};if(s.type&&!Array.isArray(s.type)&&(e.type=s.type),s.title&&(e.title=s.title),s.description&&(e.description=s.description),s.format&&(e.format=s.format),s.enum&&(e.enum=s.enum),s.default!==void 0&&(e.default=s.default),s.minimum!==void 0&&(e.minimum=s.minimum),s.maximum!==void 0&&(e.maximum=s.maximum),s.minLength!==void 0&&(e.minLength=s.minLength),s.maxLength!==void 0&&(e.maxLength=s.maxLength),s.maxItems!==void 0&&(e.maxItems=s.maxItems),s.readOnly!==void 0&&(e.readOnly=s.readOnly),s.writeOnly!==void 0&&(e.writeOnly=s.writeOnly),s.examples&&s.examples.length>0&&(e.example=s.examples[0]),s.properties){e.properties={};for(const[t,n]of Object.entries(s.properties))e.properties[t]=it(n)}return s.anyOf&&(e.anyOf=s.anyOf.map(it)),s.additionalProperties!==void 0&&(typeof s.additionalProperties=="boolean"?e.additionalProperties=s.additionalProperties:e.additionalProperties=it(s.additionalProperties)),s.required&&(e.required=s.required),e}c(it,"convertDataSchemaToOpenAPI");function Kd(s){const{membraneInterfaces:{actions:e}}=s,t=Bd(e);return JSON.stringify({openapi:"3.0.0",info:{title:"Membrane Actions API",version:"1.0.0",description:"Generated OpenAPI specification for Membrane actions"},paths:{},components:{schemas:t}},null,2)}c(Kd,"generateOpenAPIContent");function Bd(s){const e={};return s.forEach(t=>{const n=Xs(Ys(t.key)),r={type:"object",properties:{id:{type:"string",description:"Request ID"},action:{type:"string",enum:[t.key]}},required:["id","action"]};if(t?.inputSchema){const a=it(t.inputSchema);a.properties&&(r.properties={...r.properties,...a.properties}),a.required&&(r.required=[...r.required||[],...a.required])}e[`${n}Request`]=r;const i={type:"object",properties:{id:{type:"string",description:"Response ID"},success:{type:"boolean"},data:{type:"object"}},required:["id","success"]},o=t?.customOutputSchema||t?.outputSchema;if(o){const a=it(o);i.properties={...i.properties,data:a}}e[`${n}Response`]=i}),e}c(Bd,"generateOpenAPISchemas");function Ud(s){const{membraneInterfaces:{actions:e}}=s,t=fl(e,"key"),n=new dl({indentNumberOfSpaces:2,newLine:`
143
143
  `});return n.writeLine("// Generated TypeScript definitions for Membrane actions"),n.newLine(),n.writeLine("import type {"),n.writeLine(" ActionAccessor,"),n.writeLine(" ConnectionLevelActionAccessor,"),n.writeLine('} from "@membranehq/sdk";'),n.newLine(),Wd(n,t),n.toString()}c(Ud,"generateTypeScriptContent");function Wd(s,e){s.writeLine('declare module "@membranehq/sdk" {'),s.indent(()=>{e.forEach(t=>{const n=Gr(t),r=t?.inputSchema;ps(s,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=zr(t),o=t?.customOutputSchema||t?.outputSchema;ps(s,{interfaceName:i,properties:o?.properties,required:o?.required||[],fallbackContent:"result: unknown"}),s.newLine()}),ps(s,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=Gr(t),r=zr(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),s.newLine(),ps(s,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=Gr(t),r=zr(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),s.writeLine("}")}c(Wd,"generateModuleAugmentation");function ps(s,e){const{interfaceName:t,properties:n,required:r=[],methods:i,fallbackContent:o}=e;s.writeLine(`interface ${t} {`),s.indent(()=>{n&&Object.keys(n).length>0&&Jd(s,n,r),i&&i.length>0&&(n&&Object.keys(n).length>0&&s.newLine(),i.forEach((a,l)=>{s.writeLine(`${a.name}(${a.parameters}): ${a.returnType};`),l<i.length-1&&s.newLine()})),o&&(!n||Object.keys(n).length===0)&&(!i||i.length===0)&&s.writeLine(o)}),s.writeLine("}")}c(ps,"generateTypeScriptInterface");function Jd(s,e,t){Object.entries(e).forEach(([n,r])=>{const o=t.includes(n)?"":"?",a=Vr(r);s.writeLine(`readonly ${n}${o}: ${a}`)})}c(Jd,"generateTypeScriptProperties");function Vr(s){return s.type==="string"?s.enum?s.enum.map(e=>`'${e}'`).join(" | "):"string":s.type==="number"||s.type==="integer"?"number":s.type==="boolean"?"boolean":s.type==="array"?`${s.items?Vr(s.items):"unknown"}[]`:s.type==="object"?s.properties?`{ ${Object.entries(s.properties).map(([t,n])=>{const i=(s.required||[]).includes(t)?"":"?",o=Vr(n);return`readonly ${t}${i}: ${o}`}).join("; ")} }`:"Record<string, unknown>":"unknown"}c(Vr,"convertJsonSchemaToTypeScript");function Gr(s){return`${Xs(Ys(s.key))}Input`}c(Gr,"getInputTypeName");function zr(s){return`${Xs(Ys(s.key))}Output`}c(zr,"getOutputTypeName");async function Yr(s){const{out:e}=s;await L.promises.mkdir(e,{recursive:!0});const t=Hd(s);for(const[n,r]of Object.entries(t)){const i=K.join(e,n);await L.promises.writeFile(i,r,"utf-8")}}c(Yr,"generateCode");function Hd(s){switch(s.target){case"openapi":return{"openapi.json":Kd(s)};case"typescript":return{"generated.d.ts":Ud(s)};default:throw new Error(`Unsupported target: ${s.target}`)}}c(Hd,"generateContent");const Xr=c(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 The codegen command is experimental and subject to rapid changes.\u2502"),k.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
144
144
  `),"createExperimentalWarning$1");function Vd(s,e){s.command("codegen").description("\u26A0\uFE0F EXPERIMENTAL: Generate code for easy integration within projects - This feature is experimental and will be changing rapidly. Use at your own risk.").requiredOption("--actions <actions>",'Comma-separated list of action names (e.g., "list-files,get-file-by-id")').requiredOption("--out <path>","Output directory for generated files").requiredOption("--target <type>","Target format: openapi or typescript").requiredOption("--schemasOnly","Generate only schemas without implementation").addHelpText("after",Xr()).addHelpText("after",["",k.bold("Examples:"),` ${k.gray("\u25B8")} ${k.cyan("membrane codegen --actions list-files,get-file-by-id --out src/generated --target openapi --schemasOnly")}`,` ${k.gray("\u25B8")} ${k.cyan("membrane install --actions delete-file --out src/generated --target typescript --schemasOnly")}`,"",Xr()].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@membranehq/cli",
3
- "version": "1.1.21",
3
+ "version": "1.1.22",
4
4
  "keywords": [
5
5
  "cli",
6
6
  "integration",