@superglue/cli 1.1.215 → 1.1.217

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "superglue",
3
3
  "description": "Build, test, and manage superglue tools via the sg CLI. Use when working with superglue tools, systems, APIs, SDKs, or the sg command.",
4
- "version": "1.1.215",
4
+ "version": "1.1.217",
5
5
  "author": {
6
6
  "name": "superglue",
7
7
  "email": "hello@superglue.cloud"
package/dist/cli.js CHANGED
@@ -1870,9 +1870,9 @@ ${e.format(r)}`.trim())}};Hz.exports=uQ});var dQ=m((F$e,Vz)=>{"use strict";var{I
1870
1870
  ${s}`;return}if(rE(e,i,Jke)){Wke(e,o)&&(r.retry=e.toString("utf8",o));return}if(rE(e,i,Vke)){Zke(e,o)&&(r.id=e.toString("utf8",o));return}if(rE(e,i,Yke)){let s=e.toString("utf8",o);s.length>0&&(r.event=s)}}processEvent(e){e.retry&&jke(e.retry)&&(this.state.reconnectionTime=parseInt(e.retry,10)),e.id!==void 0&&zke(e.id)&&(this.state.lastEventId=e.id),e.data!==void 0&&this.push({type:e.event||"message",options:{data:e.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event.data=void 0,this.event.event=void 0,this.event.id=void 0,this.event.retry=void 0}hasPendingEvent(){return this.event.data!==void 0||this.event.event!==void 0||this.event.id!==void 0||this.event.retry!==void 0}hasCurrentByte(){return this.chunkIndex<this.chunks.length&&this.pos<this.chunks[this.chunkIndex].length}currentByte(){return this.chunks[this.chunkIndex][this.pos]}consumeCurrentByte(){this.advanceCursor(),this.syncLineStartToCursor()}advanceCursor(){for(this.pos++;this.chunkIndex<this.chunks.length&&this.pos>=this.chunks[this.chunkIndex].length;)this.chunkIndex++,this.pos=0}syncLineStartToCursor(){this.lineChunkIndex=this.chunkIndex,this.linePos=this.pos,this.dropConsumedChunks()}dropConsumedChunks(){for(;this.lineChunkIndex>0;)this.chunks.shift(),this.lineChunkIndex--,this.chunkIndex--;this.chunkIndex===this.chunks.length&&(this.chunks.length=0,this.chunkIndex=0,this.pos=0,this.lineChunkIndex=0,this.linePos=0)}readLine(){if(this.lineChunkIndex===this.chunkIndex)return this.chunks[this.chunkIndex].subarray(this.linePos,this.pos);let e=[],r=0;for(let n=this.lineChunkIndex;n<=this.chunkIndex;n++){let i=this.chunks[n],o=n===this.lineChunkIndex?this.linePos:0,s=n===this.chunkIndex?this.pos:i.length,a=i.subarray(o,s);r+=a.length,e.push(a)}return Buffer.concat(e,r)}peekBufferedByte(e){let r=this.lineChunkIndex,n=this.linePos;for(;r<this.chunks.length;){let i=this.chunks[r],o=i.length-n;if(e<o)return i[n+e];e-=o,r++,n=0}}discardLeadingBytes(e){for(;e>0&&this.lineChunkIndex<this.chunks.length;){let n=this.chunks[this.lineChunkIndex].length-this.linePos;e<n?(this.linePos+=e,e=0):(e-=n,this.lineChunkIndex++,this.linePos=0)}this.chunkIndex=this.lineChunkIndex,this.pos=this.linePos,this.dropConsumedChunks()}handleBOM(){let e=this.peekBufferedByte(0),r=this.peekBufferedByte(1),n=this.peekBufferedByte(2);return r===void 0?(e===fl[0]||(this.checkBOM=!1),!0):n===void 0?e===fl[0]&&r===fl[1]?!0:(this.checkBOM=!1,!1):(e===fl[0]&&r===fl[1]&&n===fl[2]&&this.discardLeadingBytes(3),this.checkBOM=!1,!this.hasCurrentByte())}};NY.exports={EventSourceStream:Nv}});var FY=m((UFe,$Y)=>{"use strict";var{pipeline:Kke}=require("stream"),{fetching:Xke}=np(),{makeRequest:eOe}=il(),{webidl:mr}=Wt(),{EventSourceStream:tOe}=kY(),{parseMIMEType:rOe}=Un(),{createFastMessageEvent:nOe}=Hy(),{isNetworkError:OY}=ep(),{kEnumerableProperty:Nc}=Se(),{environmentSettingsObject:UY}=Xr(),MY=!1,xY=3e3,lp=0,LY=1,dp=2,iOe="anonymous",oOe="use-credentials",hl=class t extends EventTarget{#e={open:null,error:null,message:null};#t;#n=!1;#i=lp;#o=null;#r=null;#c;#s;constructor(e,r={}){super(),mr.util.markAsUncloneable(this);let n="EventSource constructor";mr.argumentLengthCheck(arguments,1,n),MY||(MY=!0,process.emitWarning("EventSource is experimental, expect them to change at any time.",{code:"UNDICI-ES"})),e=mr.converters.USVString(e),r=mr.converters.EventSourceInitDict(r,n,"eventSourceInitDict"),this.#c=r.node.dispatcher||r.dispatcher,this.#s={lastEventId:"",reconnectionTime:r.node.reconnectionTime};let i=UY,o;try{o=new URL(e,i.settingsObject.baseUrl),this.#s.origin=o.origin}catch(c){throw new DOMException(c,"SyntaxError")}this.#t=o.href;let s=iOe;r.withCredentials===!0&&(s=oOe,this.#n=!0);let a={redirect:"follow",keepalive:!0,mode:"cors",credentials:s==="anonymous"?"same-origin":"omit",referrer:"no-referrer"};a.client=UY.settingsObject,a.headersList=[["accept",{name:"accept",value:"text/event-stream"}]],a.cache="no-store",a.initiator="other",a.urlList=[new URL(this.#t)],this.#o=eOe(a),this.#a()}get readyState(){return this.#i}get url(){return this.#t}get withCredentials(){return this.#n}#a(){if(this.#i===dp)return;this.#i=lp;let e={request:this.#o,dispatcher:this.#c},r=n=>{if(!OY(n))return this.#u()};e.processResponseEndOfBody=r,e.processResponse=n=>{if(OY(n))if(n.aborted){this.close(),this.dispatchEvent(new Event("error"));return}else{this.#u();return}let i=n.headersList.get("content-type",!0),o=i!==null?rOe(i):"failure",s=o!=="failure"&&o.essence==="text/event-stream";if(n.status!==200||s===!1){this.close(),this.dispatchEvent(new Event("error"));return}this.#i=LY,this.dispatchEvent(new Event("open")),this.#s.origin=n.urlList[n.urlList.length-1].origin;let a=new tOe({eventSourceSettings:this.#s,push:c=>{this.dispatchEvent(nOe(c.type,c.options))}});Kke(n.body.stream,a,c=>{c?.aborted===!1&&(this.close(),this.dispatchEvent(new Event("error")))})},this.#r=Xke(e)}#u(){this.#i!==dp&&(this.#i=lp,this.dispatchEvent(new Event("error")),setTimeout(()=>{this.#i===lp&&(this.#s.lastEventId.length&&this.#o.headersList.set("last-event-id",this.#s.lastEventId,!0),this.#a())},this.#s.reconnectionTime)?.unref())}close(){mr.brandCheck(this,t),this.#i!==dp&&(this.#i=dp,this.#r.abort(),this.#o=null)}get onopen(){return this.#e.open}set onopen(e){this.#e.open&&this.removeEventListener("open",this.#e.open);let r=mr.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("open",r),this.#e.open=e):this.#e.open=null}get onmessage(){return this.#e.message}set onmessage(e){this.#e.message&&this.removeEventListener("message",this.#e.message);let r=mr.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("message",r),this.#e.message=e):this.#e.message=null}get onerror(){return this.#e.error}set onerror(e){this.#e.error&&this.removeEventListener("error",this.#e.error);let r=mr.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("error",r),this.#e.error=e):this.#e.error=null}},PY={CONNECTING:{__proto__:null,configurable:!1,enumerable:!0,value:lp,writable:!1},OPEN:{__proto__:null,configurable:!1,enumerable:!0,value:LY,writable:!1},CLOSED:{__proto__:null,configurable:!1,enumerable:!0,value:dp,writable:!1}};Object.defineProperties(hl,PY);Object.defineProperties(hl.prototype,PY);Object.defineProperties(hl.prototype,{close:Nc,onerror:Nc,onmessage:Nc,onopen:Nc,readyState:Nc,url:Nc,withCredentials:Nc});mr.converters.EventSourceInitDict=mr.dictionaryConverter([{key:"withCredentials",converter:mr.converters.boolean,defaultValue:()=>!1},{key:"dispatcher",converter:mr.converters.any},{key:"node",converter:mr.dictionaryConverter([{key:"reconnectionTime",converter:mr.converters["unsigned long"],defaultValue:()=>xY},{key:"dispatcher",converter:mr.converters.any}]),defaultValue:()=>({})}]);$Y.exports={EventSource:hl,defaultReconnectionTime:xY}});var YY=m((MFe,K)=>{"use strict";var sOe=Gs(),zY=cA(),aOe=oc(),cOe=Qj(),uOe=Rj(),lOe=cc(),dOe=A_(),AOe=c_(),pOe=g2(),fOe=S2(),hOe=_2(),HY=me(),iE=Se(),{InvalidArgumentError:nE}=HY,gl=az(),gOe=Va(),mOe=K_(),{MockCallHistory:yOe,MockCallHistoryLog:EOe}=tQ(),IOe=lQ(),COe=oQ(),bOe=sH(),SOe=U_(),wOe=Zm(),{getGlobalDispatcher:qY,setGlobalDispatcher:BOe}=Ay(),_Oe=Ku(),QOe=yQ();Object.assign(zY.prototype,gl);K.exports.Dispatcher=zY;K.exports.Client=sOe;K.exports.Pool=aOe;K.exports.BalancedPool=cOe;K.exports.RoundRobinPool=uOe;K.exports.Agent=lOe;K.exports.ProxyAgent=dOe;K.exports.Socks5ProxyAgent=AOe;K.exports.EnvHttpProxyAgent=pOe;K.exports.RetryAgent=fOe;K.exports.H2CClient=hOe;K.exports.RetryHandler=wOe;K.exports.DecoratorHandler=_Oe;K.exports.RedirectHandler=QOe;K.exports.interceptors={redirect:mH(),responseError:EH(),retry:CH(),dump:wH(),dns:vH(),cache:sq(),decompress:Aq(),deduplicate:mq()};K.exports.cacheStores={MemoryCacheStore:NQ()};var vOe=Iq();K.exports.cacheStores.SqliteCacheStore=vOe;K.exports.buildConnector=gOe;K.exports.errors=HY;K.exports.util={parseHeaders:iE.parseHeaders,headerNameToString:iE.headerNameToString};function Ap(t){return(e,r,n)=>{if(typeof r=="function"&&(n=r,r=null),!e||typeof e!="string"&&typeof e!="object"&&!(e instanceof URL))throw new nE("invalid url");if(r!=null&&typeof r!="object")throw new nE("invalid opts");if(r&&r.path!=null){if(typeof r.path!="string")throw new nE("invalid opts.path");let s=r.path;r.path.startsWith("/")||(s=`/${s}`),e=new URL(iE.parseOrigin(e).origin+s)}else r||(r=typeof e=="object"?e:{}),e=iE.parseURL(e);let{agent:i,dispatcher:o=qY()}=r;if(i)throw new nE("unsupported opts.agent. Did you mean opts.client?");return t.call(o,{...r,origin:e.origin,path:e.search?`${e.pathname}${e.search}`:e.pathname,method:r.method||(r.body?"PUT":"GET")},n)}}K.exports.setGlobalDispatcher=BOe;K.exports.getGlobalDispatcher=qY;var DOe=np().fetch,jY=typeof __filename<"u"?__filename:void 0;function GY(t,e){if(!t||typeof t!="object")return;let r=typeof t.stack=="string"?t.stack:"",n=e.replace(/\\/g,"/");if(r&&(r.includes(e)||r.includes(n)))return;let i={};if(Error.captureStackTrace(i,GY),!i.stack)return;let o=i.stack.split(`
1871
1871
  `).slice(1).join(`
1872
1872
  `);t.stack=r?`${r}
1873
- ${o}`:i.stack}K.exports.fetch=function(e,r=void 0){return DOe(e,r).catch(n=>{throw jY?GY(n,jY):n&&typeof n=="object"&&Error.captureStackTrace(n,K.exports.fetch),n})};K.exports.Headers=wc().Headers;K.exports.Response=ep().Response;K.exports.Request=il().Request;K.exports.FormData=Bm().FormData;var{setGlobalOrigin:TOe,getGlobalOrigin:ROe}=Yw();K.exports.setGlobalOrigin=TOe;K.exports.getGlobalOrigin=ROe;var{CacheStorage:NOe}=TG(),{kConstruct:kOe}=Je();K.exports.caches=new NOe(kOe);var{deleteCookie:OOe,getCookies:UOe,getSetCookies:MOe,setCookie:xOe,parseCookie:LOe}=jG();K.exports.deleteCookie=OOe;K.exports.getCookies=UOe;K.exports.getSetCookies=MOe;K.exports.setCookie=xOe;K.exports.parseCookie=LOe;var{parseMIMEType:POe,serializeAMimeType:$Oe}=Un();K.exports.parseMIMEType=POe;K.exports.serializeAMimeType=$Oe;var{CloseEvent:FOe,ErrorEvent:jOe,MessageEvent:zOe}=Hy(),{WebSocket:HOe,ping:qOe}=CY();K.exports.WebSocket=HOe;K.exports.CloseEvent=FOe;K.exports.ErrorEvent=jOe;K.exports.MessageEvent=zOe;K.exports.ping=qOe;K.exports.WebSocketStream=DY().WebSocketStream;K.exports.WebSocketError=Qv().WebSocketError;K.exports.request=Ap(gl.request);K.exports.stream=Ap(gl.stream);K.exports.pipeline=Ap(gl.pipeline);K.exports.connect=Ap(gl.connect);K.exports.upgrade=Ap(gl.upgrade);K.exports.MockClient=mOe;K.exports.MockCallHistory=yOe;K.exports.MockCallHistoryLog=EOe;K.exports.MockPool=COe;K.exports.MockAgent=IOe;K.exports.SnapshotAgent=bOe;K.exports.mockErrors=SOe;var{EventSource:GOe}=FY();K.exports.EventSource=GOe;function YOe(){globalThis.fetch=K.exports.fetch,globalThis.Headers=K.exports.Headers,globalThis.Response=K.exports.Response,globalThis.Request=K.exports.Request,globalThis.FormData=K.exports.FormData,globalThis.WebSocket=K.exports.WebSocket,globalThis.CloseEvent=K.exports.CloseEvent,globalThis.ErrorEvent=K.exports.ErrorEvent,globalThis.MessageEvent=K.exports.MessageEvent,globalThis.EventSource=K.exports.EventSource}K.exports.install=YOe});var JY=m(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});yl.SuperglueClient=yl.SuperglueHttpError=void 0;var ml=xr(),Or=tS(),VOe=zS(),JOe=s$(),WOe=Dn(),ds=pu(),ZOe=Ld(),fp=14400*1e3,pp;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:t}=YY();pp=new t({headersTimeout:fp,bodyTimeout:fp})}catch{}function VY(t){if(t?.aborted)throw t.reason??new DOMException("Aborted","AbortError")}var oE=class extends Error{constructor(e,r,n,i){super(e),this.status=r,this.code=n,this.details=i,this.name="SuperglueHttpError"}};yl.SuperglueHttpError=oE;var kv=class{constructor({apiKey:e,apiEndpoint:r,onInfrastructureError:n,refreshToken:i,sseTokenProvider:o,tokenProvider:s}){if(!e&&!s)throw new Error("SuperglueClient requires either apiKey or tokenProvider");this.tokenProvider=s??(async()=>e),this.apiEndpoint=r??"https://api.superglue.cloud",this.sseManager=new VOe.SSELogSubscriptionManager(this.apiEndpoint,o??this.tokenProvider,i),this.onInfrastructureError=n,this.refreshToken=i}async getApiKey(){return this.tokenProvider()}async fetchWithAuthRetry(e,r){let n=await this.getApiKey(),i=await e(n);if(i.status!==401||!this.refreshToken)return i;VY(r);let o=await this.refreshToken();return VY(r),!o||o===n?i:(i.body?.cancel(),e(o))}isInfrastructureError(e){return(0,WOe.isAbortError)(e)?!1:!!(e instanceof TypeError&&e.message.toLowerCase().includes("fetch")||e instanceof Error&&e.name==="TimeoutError")}async restRequest(e,r,n,i,o){let a=await(await this.restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o})).text();if(a)return JSON.parse(a)}async restData(...e){return(await this.restRequest(...e)).data}async restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o}){let s=`${this.apiEndpoint.replace(/\/$/,"")}${r}`,a=n!=null,c=typeof FormData<"u"&&n instanceof FormData,u=d=>{let A={Authorization:`Bearer ${d}`,...i};return a&&!c&&e!=="GET"&&(A["Content-Type"]="application/json"),fetch(s,{...o,method:e,headers:A,body:a?c?n:JSON.stringify(n):void 0,signal:o?.signal??AbortSignal.timeout(fp),...pp?{dispatcher:pp}:{}})},l;try{l=await this.fetchWithAuthRetry(u,o?.signal)}catch(d){throw this.isInfrastructureError(d)&&this.onInfrastructureError?.(),d}if(!l.ok)throw await this.buildHttpError(l);return l}async uploadFiles(e,r){if(typeof r?.process!="boolean")throw new Error("process must be a boolean");if(e.length===0)return[];let n=e.map(l=>({...l,contentLength:l.contentLength??this.getUploadContentLength(l.content)})),o=(await this.restRequest("POST","/v1/files/uploads",{process:r.process,...r.allowUnprocessed?{allowUnprocessed:!0}:{},files:n.map(({fileName:l,contentType:d,contentLength:A})=>({fileName:l,contentLength:A,...d?{contentType:d}:{}}))})).data.files;if(o.length!==n.length)throw await Promise.all(o.map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),new Error("Upload response did not match the selected files");let s=await Promise.allSettled(o.map(async(l,d)=>{let A=n[d],p=await fetch(l.uploadUrl,{method:"PUT",body:A.content,headers:{...l.uploadHeaders,...A.contentType?{"Content-Type":A.contentType}:{}},signal:AbortSignal.timeout(Math.min(fp,l.expiresIn*1e3))});if(!p.ok)throw new Error(`Upload failed for ${A.fileName}: ${p.status} ${p.statusText}`);return l.id})),a=s.flatMap(l=>l.status==="fulfilled"?[l.value]:[]),c=new Map;if(a.length>0)try{let l=await this.restRequest("POST","/v1/files/uploads/complete",{fileIds:a});c=new Map(l.data.files.map(d=>[d.id,d]))}catch(l){c=new Map(a.map(d=>[d,{id:d,fileName:n[o.findIndex(A=>A.id===d)]?.fileName||d,contentLength:n[o.findIndex(A=>A.id===d)]?.contentLength||0,status:"failed",error:l instanceof Error?l.message:String(l)}]))}let u=o.map((l,d)=>{let A=s[d],p=n[d];return A.status==="rejected"?{id:l.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:A.reason instanceof Error?A.reason.message:String(A.reason)}:c.get(l.id)||{id:l.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:"Upload completion returned no result"}});return await Promise.all(u.filter(l=>l.status==="failed").map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),u}async deleteFileUpload(e){await this.restRequest("DELETE",`/v1/files/uploads/${encodeURIComponent(e)}`)}getUploadContentLength(e){return typeof e=="string"?new TextEncoder().encode(e).byteLength:e instanceof Uint8Array?e.byteLength:e.size}async buildHttpError(e){e.status>=500&&this.onInfrastructureError?.();let r=await e.text(),n=`HTTP ${e.status}: ${r}`,i,o;try{let s=JSON.parse(r);s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),typeof s?.code=="string"&&(i=s.code);let a=s.error;typeof a=="string"?n=a:a&&typeof a=="object"&&(n=a.message||JSON.stringify(a))}catch{}return new oE(n,e.status,i,o)}async streamRequest(e,r,n){let i=e.includes("?")?"&":"?",o=`${this.apiEndpoint.replace(/\/$/,"")}${e}${i}stream=true`,s=u=>fetch(o,{method:"POST",headers:{Authorization:`Bearer ${u}`,Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(r),signal:n??AbortSignal.timeout(fp),...pp?{dispatcher:pp}:{}}),a;try{a=await this.fetchWithAuthRetry(s,n)}catch(u){throw this.isInfrastructureError(u)&&this.onInfrastructureError?.(),u}if(!a.ok)throw await this.buildHttpError(a);if(!(a.headers.get("content-type")||"").includes("text/event-stream")){let u=await a.text();return u?JSON.parse(u):void 0}try{return await(0,JOe.consumeEventStreamResult)(a)}catch(u){throw this.isInfrastructureError(u)&&this.onInfrastructureError?.(),u}}async subscribeToLogsSSE(e={}){return this.sseManager.subscribeToLogs(e)}async disconnect(){await this.sseManager.disconnect()}async listMemoryNotes(e={}){let r=new URLSearchParams;e.scope&&r.set("scope",e.scope),e.query&&r.set("query",e.query);let n=r.toString();return this.restData("GET",`/v1/memory-notes${n?`?${n}`:""}`)}async createMemoryNote(e){return this.restData("POST","/v1/memory-notes",e)}async updateMemoryNote(e,r){return this.restData("PATCH",`/v1/memory-notes/${encodeURIComponent(e)}`,r)}async deleteMemoryNote(e){await this.restRequest("DELETE",`/v1/memory-notes/${encodeURIComponent(e)}`)}async clearMemoryNotes(e){return(await this.restRequest("DELETE",`/v1/memory-notes?scope=${e}`)).data.deleted}async getMe(){return this.restRequest("GET","/v1/me")}async completeOnboarding(){return this.restRequest("POST","/v1/me/onboarding/complete")}async runTool(e){let r=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e.toolId)}/run`,{inputs:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture},void 0,e.signal?{signal:e.signal}:void 0);return{success:r.status==="success",data:r.data,error:r.error,tool:r.tool,stepResults:r.stepResults?.map(n=>({...n}))||[],...r.fileArtifacts&&r.fileArtifacts.length>0?{fileArtifacts:r.fileArtifacts}:{},...r.metadata?.warnings?.length?{warnings:r.metadata.warnings}:{}}}async runToolConfig(e){let r=e.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",n=await this.restRequest("POST",r,{tool:e.tool,payload:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture,executionKind:e.executionKind,parentToolId:e.parentToolId,draftId:e.draftId},e.traceId?{"X-Trace-Id":e.traceId}:void 0,e.signal?{signal:e.signal}:void 0);return{success:n.status?n.status==="success":n.success??!1,data:n.data,error:n.error,tool:n.tool||e.tool,stepResults:n.stepResults?.map(o=>({...o}))||[],...n.fileArtifacts&&n.fileArtifacts.length>0?{fileArtifacts:n.fileArtifacts}:{},...n.metadata?.warnings?.length?{warnings:n.metadata.warnings}:{}}}async abortToolExecution(e){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(e)}/cancel`)).runId}}async executeStep({step:e,payload:r,files:n,previousResults:i,credentials:o,credentialsList:s,options:a,runId:c,systemIds:u,credentialId:l,systemAuth:d,createRun:A,parentToolId:p,stepIndex:h,stepId:g,signal:w,stream:B}){let _={step:e,payload:r,files:n,previousResults:i,credentials:o,credentialsList:s,options:a,runId:c,systemIds:u,credentialId:l,systemAuth:d,createRun:A,parentToolId:p,stepIndex:h,stepId:g};return B?this.streamRequest("/v1/tools/step/run",_,w):this.restRequest("POST","/v1/tools/step/run",_,void 0,w?{signal:w}:void 0)}async abortStep(e){return this.restRequest("POST","/v1/tools/step/abort",{runId:e})}async executeTransformOnly({outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:u,parentToolId:l,stepId:d,signal:A,stream:p}){let h={outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:u,parentToolId:l,stepId:d};return p?this.streamRequest("/v1/tools/transform/run",h,A):this.restRequest("POST","/v1/tools/transform/run",h,void 0,A?{signal:A}:void 0)}async createRun({toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:c,completedAt:u,executionKind:l,parentToolId:d,draftId:A}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:(0,ds.toUTCISOString)(c,"run.startedAt"),completedAt:(0,ds.toUTCISOString)(u,"run.completedAt"),executionKind:l,parentToolId:d,draftId:A})}async checkRunLimit(){return this.restData("POST","/v1/runs/check-limit")}async extract({file:e,envelope:r}){if(!e)throw new Error("File must be provided for extract.");let n=new FormData;n.append("file",e);let i=r?"/v1/extract?envelope=true":"/v1/extract";return this.restRequest("POST",i,n)}mapOpenAPIRunToRun(e){let r={running:ml.RunStatus.RUNNING,success:ml.RunStatus.SUCCESS,failed:ml.RunStatus.FAILED,aborted:ml.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:r[e.status]??ml.RunStatus.FAILED,toolPayload:e.toolPayload,data:e.data,toolResult:e.data,error:e.error,stepResults:e.stepResults,options:e.options,requestSource:e.requestSource,traceId:e.traceId,resultStorageUri:e.resultStorageUri,userId:e.userId,userEmail:e.userEmail,userName:e.userName,metadata:{...e.metadata,executionKind:e.metadata?.executionKind??ml.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,ds.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,ds.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,ds.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,ds.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e={}){let r=(0,Or.createSearchListQueryParams)(e);e.toolId!==void 0&&r.set("toolId",e.toolId),e.searchUserIds?.length&&r.set("searchUserIds",e.searchUserIds.join(",")),e.includeTotal!==void 0&&r.set("includeTotal",String(e.includeTotal)),e.startedAfter!==void 0&&r.set("startedAfter",e.startedAfter instanceof Date?(0,ds.toUTCISOString)(e.startedAfter,"run.startedAfter"):e.startedAfter),e.statuses!==void 0?r.set("status",e.statuses.join(",")):e.status!==void 0&&r.set("status",e.status),e.requestSources!==void 0&&r.set("requestSources",e.requestSources.join(",")),e.executionKinds!==void 0&&r.set("executionKinds",e.executionKinds.join(",")),e.userId!==void 0&&r.set("userId",e.userId),e.systemId!==void 0&&r.set("systemId",e.systemId),e.systemIds!==void 0&&r.set("systemIds",e.systemIds.join(","));let n=r.size>0?`?${r.toString()}`:"",i=await this.restRequest("GET",`/v1/runs${n}`,void 0,void 0,{signal:e.signal});return{data:i.data.map(o=>this.mapOpenAPIRunToRun(o)),total:i.total,page:i.page,limit:i.limit,hasMore:i.hasMore}}async getActivityCounts(e){let r=new URLSearchParams;e?.from&&r.set("from",e.from instanceof Date?(0,ds.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&r.set("to",e.to instanceof Date?(0,ds.toUTCISOString)(e.to,"activity.to"):e.to);let n=r.toString();return(await this.restRequest("GET",`/v1/activity/counts${n?`?${n}`:""}`,void 0,void 0,{signal:e?.signal})).counts}async getRun(e){try{let r=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(e)}`);return this.mapOpenAPIRunToRun(r)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found"))return null;throw r}}async getTool(e){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}`)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found")||r.message?.includes("403")||r.message?.includes("not allowed"))return null;throw r}}async getToolState(e){return(await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/state`)).state}async setToolState(e,r){await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/state`,{state:r})}async deleteToolState(e){return(await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/state`)).deletedKeys}async archiveTool(e,r=!0){return this.updateTool(e,{archived:r})}async bulkArchiveTools(e,r=!0){return this.restRequest("POST","/v1/tools/bulk/archive",{ids:e,archived:r})}async bulkDeleteTools(e){return this.restRequest("POST","/v1/tools/bulk/delete",{ids:e})}async listTools(e={}){let r=(0,Or.createListQueryParams)(e);e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived));let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/tools${n}`)}async listAllTools(e={}){return(0,Or.listAllPages)((r,n)=>this.listTools({...e,page:r,limit:n}))}async createTool(e,r){return this.restRequest("POST","/v1/tools",{...r,id:e})}async updateTool(e,r){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}`,r)}async deleteTool(e){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}`),!0}catch(r){if(r.message?.includes("404"))return!1;throw r}}async renameTool(e,r){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/rename`,{newId:r})}async getWorkflow(e){return this.getTool(e)}async archiveWorkflow(e,r=!0){return this.upsertWorkflow(e,{archived:r})}async createWorkflow(e,r){return this.createTool(e,r)}async updateWorkflow(e,r){return this.updateTool(e,r)}async upsertWorkflow(e,r){return await this.getTool(e)?this.updateTool(e,r):this.createTool(e,r)}async deleteWorkflow(e){return this.deleteTool(e)}async renameWorkflow(e,r){return this.renameTool(e,r)}async listProjectSummaries(e={}){let r=(0,Or.createSearchListQueryParams)(e);return r.set("includeResources","false"),e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived)),this.restRequest("GET",`/v1/projects?${r.toString()}`)}async listAllProjectSummaries({includeArchived:e}={}){return(0,Or.listAllPages)((r,n)=>this.listProjectSummaries({page:r,limit:n,...e!==void 0?{includeArchived:e}:{}}))}async listAllProjectTasks(e){return(0,Or.listAllPages)((r,n)=>this.restRequest("GET",`/v1/projects/${encodeURIComponent(e)}/tasks?page=${r}&limit=${n}`))}async saveProjectTask({projectId:e,taskId:r,input:n}){let i=`/v1/projects/${encodeURIComponent(e)}/tasks${r?`/${encodeURIComponent(r)}`:""}`;return this.restData(r?"PATCH":"POST",i,n)}async listAllProjectLabels(e){return(0,Or.listAllPages)((r,n)=>this.restRequest("GET",`/v1/projects/${encodeURIComponent(e)}/labels?page=${r}&limit=${n}`))}async saveProjectLabel({projectId:e,labelId:r,input:n}){let i=`/v1/projects/${encodeURIComponent(e)}/labels${r?`/${encodeURIComponent(r)}`:""}`;return this.restData(r?"PATCH":"POST",i,n)}async deleteProjectLabel({projectId:e,labelId:r}){await this.restRequest("DELETE",`/v1/projects/${encodeURIComponent(e)}/labels/${encodeURIComponent(r)}`)}async listSchedules(e={}){let r=(0,Or.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"",i=e.toolId?`/v1/tools/${encodeURIComponent(e.toolId)}/schedules${n}`:`/v1/schedules${n}`,o=await this.restRequest("GET",i);return{...o,data:o.data.map(s=>this.mapOpenAPIScheduleToToolSchedule(s))}}async listAllSchedules(e={}){return(0,Or.listAllPages)((r,n)=>this.listSchedules({...e,page:r,limit:n}))}async getToolSchedule(e,r){try{let n=await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`);return this.mapOpenAPIScheduleToToolSchedule(n)}catch(n){if(n.message?.includes("404")||n.message?.includes("not found"))return null;throw n}}async createToolSchedule(e,r){let n=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/schedules`,{...r,timezone:r.timezone||(0,ZOe.getRuntimeTimezone)()});return this.mapOpenAPIScheduleToToolSchedule(n)}async updateToolSchedule(e,r,n){let i=await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`,n);return this.mapOpenAPIScheduleToToolSchedule(i)}async deleteToolSchedule(e,r){return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`),!0}async bulkSetSchedulesEnabled(e,r){return this.restRequest("POST","/v1/schedules/bulk/enable",{ids:e,enabled:r})}async bulkDeleteSchedules(e){return this.restRequest("POST","/v1/schedules/bulk/delete",{ids:e})}async listConnections(e={}){let r=(0,Or.createListQueryParams)(e);e.systemId!==void 0&&r.set("systemId",e.systemId);let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/connections${n}`)}async listAllConnections(e={}){return(0,Or.listAllPages)((r,n)=>this.listConnections({...e,page:r,limit:n}))}async updateOAuthApp(e,r){return this.restData("PUT",`/v1/oauth-apps/${encodeURIComponent(e)}`,r)}async deleteOAuthApp(e){await this.restRequest("DELETE",`/v1/oauth-apps/${encodeURIComponent(e)}`)}async listOAuthApps({systemId:e}={}){return(0,Or.listAllPages)(async(r,n)=>{let i=new URLSearchParams({page:String(r),limit:String(n),...e?{systemId:e}:{}});return this.restRequest("GET",`/v1/oauth-apps?${i}`)})}async getConnectionSetup(e){return this.restData("GET",`/v1/connections/setup/${encodeURIComponent(e)}`)}async createConnection(e){return this.restData("POST","/v1/connections",e)}async replaceConnection(e,r){return this.restData("PUT",`/v1/connections/${encodeURIComponent(e)}`,{credentials:r})}async updateConnection(e,r){return this.restData("PATCH",`/v1/connections/${encodeURIComponent(e)}`,r)}async deleteConnection(e){await this.restRequest("DELETE",`/v1/connections/${encodeURIComponent(e)}`)}async setDefaultConnection(e){await this.restRequest("POST",`/v1/connections/${encodeURIComponent(e)}/default`)}async listSystems(e={}){let r=(0,Or.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/systems${n}`)}async listAllSystems(e={}){return(0,Or.listAllPages)((r,n)=>this.listSystems({...e,page:r,limit:n}))}async createOAuthExchange(e){return(await this.restRequest("POST","/v1/oauth/exchanges",e)).data}async completeOAuthExchange(e,r){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/complete`,r)).data}async generateCredentialsLink(e){try{return{success:!0,credentialsUrl:(await this.restRequest("POST","/v1/authenticate",e||{})).data.credentialsUrl}}catch(r){return{success:!1,error:r.message}}}};yl.SuperglueClient=kv});var ZY=m(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.UnquotedKeyStrategy=ft.TripleQuoteStrategy=ft.TrailingCommaStrategy=ft.SingleQuoteStrategy=ft.PythonLiteralStrategy=ft.CommentStrategy=ft.ResilientJsonParser=ft.RepairStrategy=void 0;ft.parseJsonResilient=KOe;ft.parseJSON=XOe;ft.isValidJson=eUe;ft.prettyPrintJson=tUe;ft.minifyJson=rUe;var ci=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};ft.RepairStrategy=ci;var sE=class extends ci{constructor(){super(...arguments),this.name="TripleQuoteRepair",this.description="Converts triple-quoted strings to proper JSON, parsing nested JSON content"}canApply(e){return/"""/.test(e)}apply(e){return e.replace(/"""([\s\S]*?)"""/g,(r,n)=>{let i=n.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let s=JSON.parse(i);return JSON.stringify(s)}catch{return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`})}};ft.TripleQuoteStrategy=sE;var aE=class extends ci{constructor(){super(...arguments),this.name="PythonLiteralRepair",this.description="Converts Python literals to JavaScript equivalents"}canApply(e){return/\b(None|True|False)\b/.test(e)}apply(e){return e.replace(/\bNone\b/g,"null").replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false")}};ft.PythonLiteralStrategy=aE;var cE=class extends ci{constructor(){super(...arguments),this.name="TrailingCommaRepair",this.description="Removes trailing commas from objects and arrays"}canApply(e){return/,\s*[}\]]/.test(e)}apply(e){return e.replace(/,(\s*[}\]])/g,"$1")}};ft.TrailingCommaStrategy=cE;var uE=class extends ci{constructor(){super(...arguments),this.name="SingleQuoteRepair",this.description="Converts single quotes to double quotes"}canApply(e){return/[{,]\s*'[^']*'\s*:/.test(e)||/:\s*'[^']*'/.test(e)}apply(e){let r=e.replace(/([{,]\s*)'([^']+)'(\s*:)/g,'$1"$2"$3');return r=r.replace(/(:\s*)'([^']+)'(\s*[,}])/g,'$1"$2"$3'),r}};ft.SingleQuoteStrategy=uE;var lE=class extends ci{constructor(){super(...arguments),this.name="UnquotedKeyRepair",this.description="Adds quotes to unquoted object keys"}canApply(e){return/[{,]\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*:/.test(e)}apply(e){return e.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)(\s*:)/g,'$1"$2"$3')}};ft.UnquotedKeyStrategy=lE;var dE=class extends ci{constructor(){super(...arguments),this.name="CommentRemoval",this.description="Removes JavaScript-style comments"}canApply(e){return/\/\/.*$|\/\*[\s\S]*?\*\//m.test(e)}apply(e){let r=e.replace(/\/\/.*$/gm,"");return r=r.replace(/\/\*[\s\S]*?\*\//g,""),r}};ft.CommentStrategy=dE;var Ov=class extends ci{constructor(){super(...arguments),this.name="UnescapedControlCharactersRepair",this.description="Escapes unescaped control characters (newlines, tabs, etc.) in JSON strings"}canApply(e){try{return JSON.parse(e),!1}catch(r){let n=r.message||"";return n.includes("control character")||n.includes("Bad control")||n.includes("Unexpected token")&&/[\n\r\t]/.test(e)}}apply(e){let r="",n=!1,i=!1;for(let o=0;o<e.length;o++){let s=e[o],a=o>0?e[o-1]:"";if(i){r+=s,i=!1;continue}if(s==="\\"&&n){r+=s,i=!0;continue}if(s==='"'&&a!=="\\"){n=!n,r+=s;continue}if(n)switch(s){case`
1874
- `:r+="\\n";break;case"\r":r+="\\r";break;case" ":r+="\\t";break;case"\b":r+="\\b";break;case"\f":r+="\\f";break;default:let c=s.charCodeAt(0);c<32?r+="\\u"+("0000"+c.toString(16)).slice(-4):r+=s}else r+=s}return r}},Uv=class extends ci{constructor(){super(...arguments),this.name="TrailingCharactersRepair",this.description="Removes trailing characters after valid JSON structure"}canApply(e){let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return!1;let n=0,i=0,o=!1,s=!1;for(let a=0;a<r.length;a++){let c=r[a];if(o)s?s=!1:c==="\\"?s=!0:c==='"'&&(o=!1);else if(c==='"')o=!0;else if(c==="{")n++;else if(c==="}"){if(n--,n===0&&i===0&&a>0&&a<r.length-1)return!0}else if(c==="[")i++;else if(c==="]"&&(i--,i===0&&n===0&&a>0&&a<r.length-1))return!0}return!1}apply(e){let r=e.trim(),n=0,i=0,o=!1,s=!1,a=-1;for(let c=0;c<r.length;c++){let u=r[c];if(o)s?s=!1:u==="\\"?s=!0:u==='"'&&(o=!1);else if(u==='"')o=!0;else if(u==="{")n++;else if(u==="}"){if(n--,n===0&&i===0&&c>0){a=c;break}}else if(u==="[")i++;else if(u==="]"&&(i--,i===0&&n===0&&c>0)){a=c;break}}return a>0&&a<r.length-1?r.substring(0,a+1):e}},El=class{constructor(e={}){this.strategies=[],this.repairLog=[],this.options={attemptRepair:!0,maxDepth:10,preserveStringsOnFailure:!1,logRepairs:!1,...e},this.initializeDefaultStrategies(),e.customStrategies&&this.strategies.push(...e.customStrategies)}initializeDefaultStrategies(){this.strategies=[new sE,new uE,new Ov,new Uv,new aE,new cE,new lE,new dE]}parse(e){let r=Date.now();this.repairLog=[];let n=e instanceof Buffer?e.toString("utf8"):String(e);try{return{success:!0,data:JSON.parse(n),metadata:{parseTime:Date.now()-r,strategiesApplied:[]}}}catch(s){if(!this.options.attemptRepair)return{success:!1,error:`JSON parse error: ${s}`,metadata:{parseTime:Date.now()-r}}}let i=n,o=[];for(let s of this.strategies)if(s.canApply(i)){let a=i;if(i=s.apply(i),a!==i){o.push(s.name),this.repairLog.push(s.description),this.options.logRepairs&&console.log(`Applied ${s.name}: ${s.description}`);try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}catch{}}}try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}catch(s){let a=this.aggressiveFallback(i);return a.success?{...a,repairs:[...this.repairLog,"Applied aggressive fallback"],metadata:{parseTime:Date.now()-r,strategiesApplied:[...o,"AggressiveFallback"]}}:{success:!1,error:`Failed to parse JSON after applying ${o.length} strategies: ${s}`,repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}}aggressiveFallback(e){try{let r=e.indexOf("{"),n=e.indexOf("[");if(r===-1&&n===-1)return{success:!1,error:"No JSON-like structure found"};let i=r===-1?n:n===-1?r:Math.min(r,n),o=e.substring(i);for(let a of this.strategies)a.canApply(o)&&(o=a.apply(o));return{success:!0,data:JSON.parse(o)}}catch(r){return{success:!1,error:`Aggressive fallback failed: ${r}`}}}addStrategy(e){this.strategies.push(e)}removeStrategy(e){this.strategies=this.strategies.filter(r=>r.name!==e)}getStrategies(){return this.strategies.map(e=>e.name)}};ft.ResilientJsonParser=El;var WY=new El;function KOe(t,e){return(e?new El(e):WY).parse(t)}function XOe(t){let e=WY.parse(t);if(e.success)return e.repairs&&e.repairs.length>0&&console.log("JSON parsed with repairs:",e.repairs),e.data;throw new Error(`Failed to parse JSON: ${e.error}`)}function eUe(t){try{return JSON.parse(t),!0}catch{return!1}}function tUe(t,e=2){return JSON.stringify(t,null,e)}function rUe(t){let r=new El().parse(t);if(r.success)return JSON.stringify(r.data);throw new Error("Cannot minify invalid JSON")}});var KY=m(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.MANAGED_OAUTH_APP_PREFIX=void 0;yr.projectOAuthAppAuthentication=oUe;yr.isDynamicOAuthConfiguration=sUe;yr.isReusableOAuthAppForTemplate=aUe;yr.getManagedOAuthTemplateId=cUe;yr.getOAuthAppSharedConfiguration=uUe;yr.copyOAuthAppConfiguration=lUe;yr.encryptConnectionAuthentication=dUe;yr.decryptConnectionAuthentication=AUe;yr.isManagedOAuthEndpointAllowed=pUe;var nUe=$S(),iUe=Dn();function oUe(t){let{clientSecret:e,config:r,...n}=t,{extraHeaders:i,extraBodyParams:o,...s}=r??{};return{...n,...r?{config:s}:{}}}yr.MANAGED_OAUTH_APP_PREFIX="managed:";function sUe({authentication:t,template:e}){return t.oauthClientMode==="dynamic"||!!e?.oauth?.registrationUrl&&!t.clientSecret}function aUe({app:t,template:e}){return!e?.oauth?.registrationUrl||t.hasClientSecret}function cUe(t){if(t?.type==="oauth2")return t.oauthAppId?.startsWith(yr.MANAGED_OAUTH_APP_PREFIX)?t.oauthAppId.slice(yr.MANAGED_OAUTH_APP_PREFIX.length):void 0}function uUe(t){let{grantType:e,scopes:r,oauthAppId:n,...i}=t;return i}function lUe({appAuthentication:t,authentication:e}){if(e?.type!=="oauth2")return{...t};let r=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0));return{...t,...r,config:{...t.config,...e.config}}}function dUe({authentication:t,encrypt:e}){if(t.type!=="oauth2")return t;let r={...t,config:{...t.config}};t.clientSecret!==void 0&&(r.clientSecret=e({value:t.clientSecret}).value);for(let n of["extraHeaders","extraBodyParams"]){let i=t.config?.[n];i!==void 0&&(r.config[n]=e({value:(0,iUe.safeStringify)(i)}).value)}return r}function AUe({authentication:t,decrypt:e}){if(t.type!=="oauth2")return t;let r={...t,config:{...t.config}};t.clientSecret!==void 0&&(r.clientSecret=e({value:t.clientSecret}).value);for(let n of["extraHeaders","extraBodyParams"]){let i=t.config?.[n];typeof i=="string"&&(r.config[n]=JSON.parse(e({value:i}).value))}return r}function pUe({templateId:t,endpoint:e,url:r}){let n=nUe.systems[t]?.oauth,i=n?.[e];if(!n?.managed||!i)return!1;try{let o=new URL(r),s=new URL(i);return o.protocol!=="https:"||o.port||o.username||o.password||o.hash||o.pathname!==s.pathname?!1:o.hostname===s.hostname||(n.managedEndpointHosts??[]).some(a=>a.startsWith("*.")?o.hostname.endsWith(a.slice(1)):o.hostname===a)}catch{return!1}}});var eV=m(XY=>{"use strict";Object.defineProperty(XY,"__esModule",{value:!0})});var Er=m(W=>{"use strict";var fUe=W&&W.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),ne=W&&W.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&fUe(e,t,r)};Object.defineProperty(W,"__esModule",{value:!0});W.SSELogSubscriptionManager=W.SuperglueHttpError=W.SuperglueClient=void 0;ne(gx(),W);ne(bx(),W);ne(Ox(),W);ne(Mx(),W);ne(Fx(),W);ne(jx(),W);ne(Hx(),W);ne(Sg(),W);ne(CL(),W);ne(Wf(),W);ne(BL(),W);ne(_L(),W);ne(QL(),W);ne(vL(),W);ne(DL(),W);ne(tS(),W);ne(RL(),W);ne(OL(),W);ne(UL(),W);ne(ML(),W);ne(iS(),W);ne(cS(),W);ne(LL(),W);ne(PL(),W);ne(FL(),W);ne(uh(),W);ne(zL(),W);ne(HL(),W);ne(GL(),W);ne(YL(),W);ne(WL(),W);ne(dP(),W);ne(ES(),W);ne(Vd(),W);ne(yS(),W);ne(gP(),W);ne(yP(),W);ne(IP(),W);ne(Eg(),W);ne(DP(),W);ne(RP(),W);ne(Ig(),W);ne(fS(),W);ne(xP(),W);ne(LP(),W);ne($S(),W);ne(JP(),W);ne(WP(),W);ne(ZP(),W);ne(t$(),W);ne(n$(),W);ne(xr(),W);ne(Dn(),W);ne(i$(),W);ne(o$(),W);ne(Fg(),W);ne(pu(),W);ne(Ld(),W);var tV=JY();Object.defineProperty(W,"SuperglueClient",{enumerable:!0,get:function(){return tV.SuperglueClient}});Object.defineProperty(W,"SuperglueHttpError",{enumerable:!0,get:function(){return tV.SuperglueHttpError}});var hUe=zS();Object.defineProperty(W,"SSELogSubscriptionManager",{enumerable:!0,get:function(){return hUe.SSELogSubscriptionManager}});ne(ZY(),W);ne(KY(),W);ne(eV(),W)});var JE=require("commander");var Ur=ye(require("fs")),iV=ye(require("os")),As=ye(require("path")),hp=ye(Er()),rV=new Set(["runner","builder","admin"]),nV={output:{mode:"stdout",directory:".superglue/output"},preset:"admin"};function ps(t){let e=As.join(process.cwd(),".superglue"),r=iV.homedir();if(!r)return e;let n=As.join(r,".superglue");return t===!0?e:t===!1?n:Ur.existsSync(As.join(e,"config.json"))?e:n}function Mv(t){return As.join(ps(t),"config.json")}function AE(t){let e=Mv(t);if(!Ur.existsSync(e))return{};try{return JSON.parse(Ur.readFileSync(e,"utf-8"))}catch{return{}}}function Il(t){let e=AE(),r=t.apiKey||(0,hp.readProcessEnvironmentValue)("SUPERGLUE_API_KEY")||e.apiKey||"",n=t.endpoint||(0,hp.readProcessEnvironmentValue)("SUPERGLUE_API_ENDPOINT")||e.endpoint||"https://api.superglue.cloud",i=(0,hp.readProcessEnvironmentValue)("SUPERGLUE_WEB_ENDPOINT")||e.webEndpoint||n.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue"),o=(0,hp.readProcessEnvironmentValue)("SUPERGLUE_CLI_PRESET"),s=o&&rV.has(o)?o:e.preset&&rV.has(e.preset)?e.preset:"admin";return{...nV,...e,apiKey:r,endpoint:n,webEndpoint:i,preset:s,output:{...nV.output,...e.output}}}function pE(t,e){let r=ps(e);Ur.existsSync(r)||Ur.mkdirSync(r,{recursive:!0}),Ur.writeFileSync(As.join(r,"config.json"),JSON.stringify(t,null,2)+`
1875
- `,{mode:384})}function fE(t,e){let r=As.join(ps(e),"drafts");if(Ur.existsSync(r)||Ur.mkdirSync(r,{recursive:!0}),t.output.mode==="stdout+file"){let n=As.resolve(t.output.directory);Ur.existsSync(n)||Ur.mkdirSync(n,{recursive:!0})}}var zv=ye(Er());var xv=ye(require("readline"));var aV=require("child_process"),cV=require("util");var oV={name:"@superglue/cli",version:"1.1.215",bin:{sg:"./dist/cli.js"},files:[".claude-plugin/","dist/","skills/","LICENSE"],dependencies:{commander:"15.0.0-0","fast-json-patch":"3.1.1"},devDependencies:{"@superglue/shared":"file:../shared","@types/node":"25.5.0",tsup:"8.5.1",typescript:"5.8.3"},scripts:{build:"tsup && (cp -r skills dist/ 2>/dev/null || true)",dev:"tsup --watch","type-check":"tsc --noEmit",prepublishOnly:"npm run build"},publishConfig:{access:"public"}};var mUe=(0,cV.promisify)(aV.exec),Ir=oV.version;function sV(t){let e=t.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:t}}function gE(t,e){let r=t.split("."),n=e.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o++){let s=sV(r[o]||"0"),a=sV(n[o]||"0");if(s.numeric<a.numeric)return-1;if(s.numeric>a.numeric||s.prerelease===null&&a.prerelease!==null)return 1;if(s.prerelease!==null&&a.prerelease===null)return-1;if(s.prerelease!==null&&a.prerelease!==null){if(s.prerelease<a.prerelease)return-1;if(s.prerelease>a.prerelease)return 1}}return 0}async function mE(){try{let t=await fetch("https://registry.npmjs.org/@superglue/cli/latest",{signal:AbortSignal.timeout(5e3)});return t.ok&&(await t.json()).version||null}catch{return null}}var hE=null;function uV(){le()&&(hE=mE())}async function lV(){if(!(!le()||!hE)){try{let t=new Promise(r=>{setTimeout(()=>r(null),2e3).unref()}),e=await Promise.race([hE,t]);e&&gE(Ir,e)<0&&(console.error(""),console.error(`${I.cyan}${I.bold} Update available: ${Ir} \u2192 ${e}${I.reset}`),console.error(`${I.cyan} Run ${I.bold}sg update${I.reset}${I.cyan} to upgrade${I.reset}`),console.error(""))}catch{}hE=null}}async function dV(){let t=await mE();if(!t)return{success:!1,message:"Could not fetch latest version from npm"};if(gE(Ir,t)>=0)return{success:!0,message:`Already on latest version (${Ir})`};try{return await mUe("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${Ir} to ${t}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var le=()=>process.argv.includes("--table")&&process.stdout.isTTY,Hn=()=>process.argv.includes("--full"),I={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m"};function AV(t,e){let r=e||t;return`\x1B]8;;${t}\x07${I.underline}${I.cyan}${r}${I.reset}\x1B]8;;\x07`}function pV(){if(!le())return;let t=I.reset,e=I.dim,r="\x1B[47;30m",n=[" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@- "," =@@@- @@@@ "," @@@ @@% "," -@@ @@@@= @@@ @@@ @@@@@#@ @@@@@@@ @@@@@@@ @@@@@@ @@@ @@@ @@@ @@@@@@* %@@ "," @@ @@@ *@ @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @% @@@ @@@ @@@ @@* @@# "," #@@ @@@# @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @@@ @@@ @@@ @@* @@ "," @@- @@@@= @@@ @@@ @@@@@@@ @@@@@@ @@@@@@@ @@@ @@% @@@ @@@ @@@ @@@@@. @@."," #@% .@@@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* @@ "," @@ @ @@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* *@@ "," -@@ @@@@= @@@@@@ @@@ @@@@@@@ @@@ -@@ @@@@@@ @@@@@@% @@@@@@. @@@@@@* #@@ "," :@@* @@@ "," %@@@ =@@@. "," :@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% "];console.log(""),n.forEach(i=>{let o=i.search(/\S/),s=i.length-[...i].reverse().join("").search(/\S/)-1;if(o===-1)return console.log(" "+i);let a=i.slice(0,o),c=i.slice(o,s+1).split("").map(l=>l===" "?" ":"\u2588").join(""),u=i.slice(s+1);console.log(` ${a}${r}${c}${t}${u}`)}),console.log(` ${e} CLI v${Ir}${t}`),console.log("")}function Ot(t){if(!le())return{stop:()=>{},update:()=>{},log:()=>{}};let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],r=0,n=t,i=()=>process.stdout.write("\r\x1B[2K"),o=()=>{process.stdout.write(`\r ${I.cyan}${e[r++%e.length]}${I.reset} ${n}`)},s=setInterval(o,80);return{update:a=>{n=a},log:a=>{i(),console.log(` ${I.dim}\u2502${I.reset} ${a}`),o()},stop:a=>{clearInterval(s),i(),a&&console.log(` ${a}`)}}}function te(t){le()?yE(t):console.log(JSON.stringify(t,null,2))}function De(t,e){le()?(console.log(` ${I.green}\u2713${I.reset} ${t}`),e&&yE(e,4)):console.log(JSON.stringify({success:!0,message:t,...e&&typeof e=="object"?e:{data:e}}))}function v(t,e){le()?(console.error(` ${I.red}\u2717${I.reset} ${t}`),e&&yE(e,4)):console.error(JSON.stringify({success:!1,error:t,details:e}))}function un(t){le()&&console.log(` ${I.dim}${t}${I.reset}`)}function kc(t){le()&&(console.log(`
1873
+ ${o}`:i.stack}K.exports.fetch=function(e,r=void 0){return DOe(e,r).catch(n=>{throw jY?GY(n,jY):n&&typeof n=="object"&&Error.captureStackTrace(n,K.exports.fetch),n})};K.exports.Headers=wc().Headers;K.exports.Response=ep().Response;K.exports.Request=il().Request;K.exports.FormData=Bm().FormData;var{setGlobalOrigin:TOe,getGlobalOrigin:ROe}=Yw();K.exports.setGlobalOrigin=TOe;K.exports.getGlobalOrigin=ROe;var{CacheStorage:NOe}=TG(),{kConstruct:kOe}=Je();K.exports.caches=new NOe(kOe);var{deleteCookie:OOe,getCookies:UOe,getSetCookies:MOe,setCookie:xOe,parseCookie:LOe}=jG();K.exports.deleteCookie=OOe;K.exports.getCookies=UOe;K.exports.getSetCookies=MOe;K.exports.setCookie=xOe;K.exports.parseCookie=LOe;var{parseMIMEType:POe,serializeAMimeType:$Oe}=Un();K.exports.parseMIMEType=POe;K.exports.serializeAMimeType=$Oe;var{CloseEvent:FOe,ErrorEvent:jOe,MessageEvent:zOe}=Hy(),{WebSocket:HOe,ping:qOe}=CY();K.exports.WebSocket=HOe;K.exports.CloseEvent=FOe;K.exports.ErrorEvent=jOe;K.exports.MessageEvent=zOe;K.exports.ping=qOe;K.exports.WebSocketStream=DY().WebSocketStream;K.exports.WebSocketError=Qv().WebSocketError;K.exports.request=Ap(gl.request);K.exports.stream=Ap(gl.stream);K.exports.pipeline=Ap(gl.pipeline);K.exports.connect=Ap(gl.connect);K.exports.upgrade=Ap(gl.upgrade);K.exports.MockClient=mOe;K.exports.MockCallHistory=yOe;K.exports.MockCallHistoryLog=EOe;K.exports.MockPool=COe;K.exports.MockAgent=IOe;K.exports.SnapshotAgent=bOe;K.exports.mockErrors=SOe;var{EventSource:GOe}=FY();K.exports.EventSource=GOe;function YOe(){globalThis.fetch=K.exports.fetch,globalThis.Headers=K.exports.Headers,globalThis.Response=K.exports.Response,globalThis.Request=K.exports.Request,globalThis.FormData=K.exports.FormData,globalThis.WebSocket=K.exports.WebSocket,globalThis.CloseEvent=K.exports.CloseEvent,globalThis.ErrorEvent=K.exports.ErrorEvent,globalThis.MessageEvent=K.exports.MessageEvent,globalThis.EventSource=K.exports.EventSource}K.exports.install=YOe});var JY=m(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});yl.SuperglueClient=yl.SuperglueHttpError=void 0;var ml=xr(),Or=tS(),VOe=zS(),JOe=s$(),WOe=Dn(),ds=pu(),ZOe=Ld(),fp=14400*1e3,pp;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:t}=YY();pp=new t({headersTimeout:fp,bodyTimeout:fp})}catch{}function VY(t){if(t?.aborted)throw t.reason??new DOMException("Aborted","AbortError")}var oE=class extends Error{constructor(e,r,n,i){super(e),this.status=r,this.code=n,this.details=i,this.name="SuperglueHttpError"}};yl.SuperglueHttpError=oE;var kv=class{constructor({apiKey:e,apiEndpoint:r,onInfrastructureError:n,refreshToken:i,sseTokenProvider:o,tokenProvider:s}){if(!e&&!s)throw new Error("SuperglueClient requires either apiKey or tokenProvider");this.tokenProvider=s??(async()=>e),this.apiEndpoint=r??"https://api.superglue.cloud",this.sseManager=new VOe.SSELogSubscriptionManager(this.apiEndpoint,o??this.tokenProvider,i),this.onInfrastructureError=n,this.refreshToken=i}async getApiKey(){return this.tokenProvider()}async fetchWithAuthRetry(e,r){let n=await this.getApiKey(),i=await e(n);if(i.status!==401||!this.refreshToken)return i;VY(r);let o=await this.refreshToken();return VY(r),!o||o===n?i:(i.body?.cancel(),e(o))}isInfrastructureError(e){return(0,WOe.isAbortError)(e)?!1:!!(e instanceof TypeError&&e.message.toLowerCase().includes("fetch")||e instanceof Error&&e.name==="TimeoutError")}async restRequest(e,r,n,i,o){let a=await(await this.restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o})).text();if(a)return JSON.parse(a)}async restData(...e){return(await this.restRequest(...e)).data}async restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o}){let s=`${this.apiEndpoint.replace(/\/$/,"")}${r}`,a=n!=null,c=typeof FormData<"u"&&n instanceof FormData,u=d=>{let A={Authorization:`Bearer ${d}`,...i};return a&&!c&&e!=="GET"&&(A["Content-Type"]="application/json"),fetch(s,{...o,method:e,headers:A,body:a?c?n:JSON.stringify(n):void 0,signal:o?.signal??AbortSignal.timeout(fp),...pp?{dispatcher:pp}:{}})},l;try{l=await this.fetchWithAuthRetry(u,o?.signal)}catch(d){throw this.isInfrastructureError(d)&&this.onInfrastructureError?.(),d}if(!l.ok)throw await this.buildHttpError(l);return l}async uploadFiles(e,r){if(typeof r?.process!="boolean")throw new Error("process must be a boolean");if(e.length===0)return[];let n=e.map(l=>({...l,contentLength:l.contentLength??this.getUploadContentLength(l.content)})),o=(await this.restRequest("POST","/v1/files/uploads",{process:r.process,...r.allowUnprocessed?{allowUnprocessed:!0}:{},files:n.map(({fileName:l,contentType:d,contentLength:A})=>({fileName:l,contentLength:A,...d?{contentType:d}:{}}))})).data.files;if(o.length!==n.length)throw await Promise.all(o.map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),new Error("Upload response did not match the selected files");let s=await Promise.allSettled(o.map(async(l,d)=>{let A=n[d],p=await fetch(l.uploadUrl,{method:"PUT",body:A.content,headers:{...l.uploadHeaders,...A.contentType?{"Content-Type":A.contentType}:{}},signal:AbortSignal.timeout(Math.min(fp,l.expiresIn*1e3))});if(!p.ok)throw new Error(`Upload failed for ${A.fileName}: ${p.status} ${p.statusText}`);return l.id})),a=s.flatMap(l=>l.status==="fulfilled"?[l.value]:[]),c=new Map;if(a.length>0)try{let l=await this.restRequest("POST","/v1/files/uploads/complete",{fileIds:a});c=new Map(l.data.files.map(d=>[d.id,d]))}catch(l){c=new Map(a.map(d=>[d,{id:d,fileName:n[o.findIndex(A=>A.id===d)]?.fileName||d,contentLength:n[o.findIndex(A=>A.id===d)]?.contentLength||0,status:"failed",error:l instanceof Error?l.message:String(l)}]))}let u=o.map((l,d)=>{let A=s[d],p=n[d];return A.status==="rejected"?{id:l.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:A.reason instanceof Error?A.reason.message:String(A.reason)}:c.get(l.id)||{id:l.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:"Upload completion returned no result"}});return await Promise.all(u.filter(l=>l.status==="failed").map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),u}async deleteFileUpload(e){await this.restRequest("DELETE",`/v1/files/uploads/${encodeURIComponent(e)}`)}getUploadContentLength(e){return typeof e=="string"?new TextEncoder().encode(e).byteLength:e instanceof Uint8Array?e.byteLength:e.size}async buildHttpError(e){e.status>=500&&this.onInfrastructureError?.();let r=await e.text(),n=`HTTP ${e.status}: ${r}`,i,o;try{let s=JSON.parse(r);s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),typeof s?.code=="string"&&(i=s.code);let a=s.error;typeof a=="string"?n=a:a&&typeof a=="object"&&(n=a.message||JSON.stringify(a))}catch{}return new oE(n,e.status,i,o)}async streamRequest(e,r,n){let i=e.includes("?")?"&":"?",o=`${this.apiEndpoint.replace(/\/$/,"")}${e}${i}stream=true`,s=u=>fetch(o,{method:"POST",headers:{Authorization:`Bearer ${u}`,Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(r),signal:n??AbortSignal.timeout(fp),...pp?{dispatcher:pp}:{}}),a;try{a=await this.fetchWithAuthRetry(s,n)}catch(u){throw this.isInfrastructureError(u)&&this.onInfrastructureError?.(),u}if(!a.ok)throw await this.buildHttpError(a);if(!(a.headers.get("content-type")||"").includes("text/event-stream")){let u=await a.text();return u?JSON.parse(u):void 0}try{return await(0,JOe.consumeEventStreamResult)(a)}catch(u){throw this.isInfrastructureError(u)&&this.onInfrastructureError?.(),u}}async subscribeToLogsSSE(e={}){return this.sseManager.subscribeToLogs(e)}async disconnect(){await this.sseManager.disconnect()}async listMemoryNotes(e={}){let r=new URLSearchParams;e.scope&&r.set("scope",e.scope),e.query&&r.set("query",e.query);let n=r.toString();return this.restData("GET",`/v1/memory-notes${n?`?${n}`:""}`)}async createMemoryNote(e){return this.restData("POST","/v1/memory-notes",e)}async updateMemoryNote(e,r){return this.restData("PATCH",`/v1/memory-notes/${encodeURIComponent(e)}`,r)}async deleteMemoryNote(e){await this.restRequest("DELETE",`/v1/memory-notes/${encodeURIComponent(e)}`)}async clearMemoryNotes(e){return(await this.restRequest("DELETE",`/v1/memory-notes?scope=${e}`)).data.deleted}async getMe(){return this.restRequest("GET","/v1/me")}async completeOnboarding(){return this.restRequest("POST","/v1/me/onboarding/complete")}async runTool(e){let r=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e.toolId)}/run`,{inputs:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture},void 0,e.signal?{signal:e.signal}:void 0);return{success:r.status==="success",data:r.data,error:r.error,tool:r.tool,stepResults:r.stepResults?.map(n=>({...n}))||[],...r.fileArtifacts&&r.fileArtifacts.length>0?{fileArtifacts:r.fileArtifacts}:{},...r.metadata?.warnings?.length?{warnings:r.metadata.warnings}:{}}}async runToolConfig(e){let r=e.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",n=await this.restRequest("POST",r,{tool:e.tool,payload:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture,executionKind:e.executionKind,parentToolId:e.parentToolId,draftId:e.draftId},e.traceId?{"X-Trace-Id":e.traceId}:void 0,e.signal?{signal:e.signal}:void 0);return{success:n.status?n.status==="success":n.success??!1,data:n.data,error:n.error,tool:n.tool||e.tool,stepResults:n.stepResults?.map(o=>({...o}))||[],...n.fileArtifacts&&n.fileArtifacts.length>0?{fileArtifacts:n.fileArtifacts}:{},...n.metadata?.warnings?.length?{warnings:n.metadata.warnings}:{}}}async abortToolExecution(e){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(e)}/cancel`)).runId}}async executeStep({step:e,payload:r,files:n,previousResults:i,credentials:o,credentialsList:s,options:a,runId:c,systemIds:u,credentialId:l,systemAuth:d,createRun:A,parentToolId:p,stepIndex:h,stepId:g,signal:w,stream:B}){let _={step:e,payload:r,files:n,previousResults:i,credentials:o,credentialsList:s,options:a,runId:c,systemIds:u,credentialId:l,systemAuth:d,createRun:A,parentToolId:p,stepIndex:h,stepId:g};return B?this.streamRequest("/v1/tools/step/run",_,w):this.restRequest("POST","/v1/tools/step/run",_,void 0,w?{signal:w}:void 0)}async abortStep(e){return this.restRequest("POST","/v1/tools/step/abort",{runId:e})}async executeTransformOnly({outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:u,parentToolId:l,stepId:d,signal:A,stream:p}){let h={outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:u,parentToolId:l,stepId:d};return p?this.streamRequest("/v1/tools/transform/run",h,A):this.restRequest("POST","/v1/tools/transform/run",h,void 0,A?{signal:A}:void 0)}async createRun({toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:c,completedAt:u,executionKind:l,parentToolId:d,draftId:A}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:(0,ds.toUTCISOString)(c,"run.startedAt"),completedAt:(0,ds.toUTCISOString)(u,"run.completedAt"),executionKind:l,parentToolId:d,draftId:A})}async checkRunLimit(){return this.restData("POST","/v1/runs/check-limit")}async extract({file:e,envelope:r}){if(!e)throw new Error("File must be provided for extract.");let n=new FormData;n.append("file",e);let i=r?"/v1/extract?envelope=true":"/v1/extract";return this.restRequest("POST",i,n)}mapOpenAPIRunToRun(e){let r={running:ml.RunStatus.RUNNING,success:ml.RunStatus.SUCCESS,failed:ml.RunStatus.FAILED,aborted:ml.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:r[e.status]??ml.RunStatus.FAILED,toolPayload:e.toolPayload,data:e.data,toolResult:e.data,error:e.error,stepResults:e.stepResults,options:e.options,requestSource:e.requestSource,traceId:e.traceId,resultStorageUri:e.resultStorageUri,userId:e.userId,userEmail:e.userEmail,userName:e.userName,metadata:{...e.metadata,executionKind:e.metadata?.executionKind??ml.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,ds.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,ds.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,ds.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,ds.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e={}){let r=(0,Or.createSearchListQueryParams)(e);e.toolId!==void 0&&r.set("toolId",e.toolId),e.searchUserIds?.length&&r.set("searchUserIds",e.searchUserIds.join(",")),e.includeTotal!==void 0&&r.set("includeTotal",String(e.includeTotal)),e.startedAfter!==void 0&&r.set("startedAfter",e.startedAfter instanceof Date?(0,ds.toUTCISOString)(e.startedAfter,"run.startedAfter"):e.startedAfter),e.statuses!==void 0?r.set("status",e.statuses.join(",")):e.status!==void 0&&r.set("status",e.status),e.requestSources!==void 0&&r.set("requestSources",e.requestSources.join(",")),e.executionKinds!==void 0&&r.set("executionKinds",e.executionKinds.join(",")),e.userId!==void 0&&r.set("userId",e.userId),e.systemId!==void 0&&r.set("systemId",e.systemId),e.systemIds!==void 0&&r.set("systemIds",e.systemIds.join(","));let n=r.size>0?`?${r.toString()}`:"",i=await this.restRequest("GET",`/v1/runs${n}`,void 0,void 0,{signal:e.signal});return{data:i.data.map(o=>this.mapOpenAPIRunToRun(o)),total:i.total,page:i.page,limit:i.limit,hasMore:i.hasMore}}async getActivityCounts(e){let r=new URLSearchParams;e?.from&&r.set("from",e.from instanceof Date?(0,ds.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&r.set("to",e.to instanceof Date?(0,ds.toUTCISOString)(e.to,"activity.to"):e.to);let n=r.toString();return(await this.restRequest("GET",`/v1/activity/counts${n?`?${n}`:""}`,void 0,void 0,{signal:e?.signal})).counts}async getRun(e){try{let r=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(e)}`);return this.mapOpenAPIRunToRun(r)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found"))return null;throw r}}async getTool(e){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}`)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found")||r.message?.includes("403")||r.message?.includes("not allowed"))return null;throw r}}async getToolState(e){return(await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/state`)).state}async setToolState(e,r){await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/state`,{state:r})}async deleteToolState(e){return(await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/state`)).deletedKeys}async archiveTool(e,r=!0){return this.updateTool(e,{archived:r})}async bulkArchiveTools(e,r=!0){return this.restRequest("POST","/v1/tools/bulk/archive",{ids:e,archived:r})}async bulkDeleteTools(e){return this.restRequest("POST","/v1/tools/bulk/delete",{ids:e})}async listTools(e={}){let r=(0,Or.createListQueryParams)(e);e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived));let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/tools${n}`)}async listAllTools(e={}){return(0,Or.listAllPages)((r,n)=>this.listTools({...e,page:r,limit:n}))}async createTool(e,r){return this.restRequest("POST","/v1/tools",{...r,id:e})}async updateTool(e,r){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}`,r)}async deleteTool(e){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}`),!0}catch(r){if(r.message?.includes("404"))return!1;throw r}}async renameTool(e,r){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/rename`,{newId:r})}async getWorkflow(e){return this.getTool(e)}async archiveWorkflow(e,r=!0){return this.upsertWorkflow(e,{archived:r})}async createWorkflow(e,r){return this.createTool(e,r)}async updateWorkflow(e,r){return this.updateTool(e,r)}async upsertWorkflow(e,r){return await this.getTool(e)?this.updateTool(e,r):this.createTool(e,r)}async deleteWorkflow(e){return this.deleteTool(e)}async renameWorkflow(e,r){return this.renameTool(e,r)}async listProjectSummaries(e={}){let r=(0,Or.createSearchListQueryParams)(e);return r.set("includeResources","false"),e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived)),this.restRequest("GET",`/v1/projects?${r.toString()}`)}async listAllProjectSummaries({includeArchived:e}={}){return(0,Or.listAllPages)((r,n)=>this.listProjectSummaries({page:r,limit:n,...e!==void 0?{includeArchived:e}:{}}))}async listAllProjectTasks(e){return(0,Or.listAllPages)((r,n)=>this.restRequest("GET",`/v1/projects/${encodeURIComponent(e)}/tasks?page=${r}&limit=${n}`))}async saveProjectTask({projectId:e,taskId:r,input:n}){let i=`/v1/projects/${encodeURIComponent(e)}/tasks${r?`/${encodeURIComponent(r)}`:""}`;return this.restData(r?"PATCH":"POST",i,n)}async listAllProjectLabels(e){return(0,Or.listAllPages)((r,n)=>this.restRequest("GET",`/v1/projects/${encodeURIComponent(e)}/labels?page=${r}&limit=${n}`))}async saveProjectLabel({projectId:e,labelId:r,input:n}){let i=`/v1/projects/${encodeURIComponent(e)}/labels${r?`/${encodeURIComponent(r)}`:""}`;return this.restData(r?"PATCH":"POST",i,n)}async deleteProjectLabel({projectId:e,labelId:r}){await this.restRequest("DELETE",`/v1/projects/${encodeURIComponent(e)}/labels/${encodeURIComponent(r)}`)}async listSchedules(e={}){let r=(0,Or.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"",i=e.toolId?`/v1/tools/${encodeURIComponent(e.toolId)}/schedules${n}`:`/v1/schedules${n}`,o=await this.restRequest("GET",i);return{...o,data:o.data.map(s=>this.mapOpenAPIScheduleToToolSchedule(s))}}async listAllSchedules(e={}){return(0,Or.listAllPages)((r,n)=>this.listSchedules({...e,page:r,limit:n}))}async getToolSchedule(e,r){try{let n=await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`);return this.mapOpenAPIScheduleToToolSchedule(n)}catch(n){if(n.message?.includes("404")||n.message?.includes("not found"))return null;throw n}}async createToolSchedule(e,r){let n=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/schedules`,{...r,timezone:r.timezone||(0,ZOe.getRuntimeTimezone)()});return this.mapOpenAPIScheduleToToolSchedule(n)}async updateToolSchedule(e,r,n){let i=await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`,n);return this.mapOpenAPIScheduleToToolSchedule(i)}async deleteToolSchedule(e,r){return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`),!0}async bulkSetSchedulesEnabled(e,r){return this.restRequest("POST","/v1/schedules/bulk/enable",{ids:e,enabled:r})}async bulkDeleteSchedules(e){return this.restRequest("POST","/v1/schedules/bulk/delete",{ids:e})}async listConnections(e={}){let r=(0,Or.createListQueryParams)(e);e.systemId!==void 0&&r.set("systemId",e.systemId);let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/connections${n}`)}async listAllConnections(e={}){return(0,Or.listAllPages)((r,n)=>this.listConnections({...e,page:r,limit:n}))}async updateOAuthApp(e,r){return this.restData("PUT",`/v1/oauth-apps/${encodeURIComponent(e)}`,r)}async deleteOAuthApp(e){await this.restRequest("DELETE",`/v1/oauth-apps/${encodeURIComponent(e)}`)}async listOAuthApps({systemId:e}={}){return(0,Or.listAllPages)(async(r,n)=>{let i=new URLSearchParams({page:String(r),limit:String(n),...e?{systemId:e}:{}});return this.restRequest("GET",`/v1/oauth-apps?${i}`)})}async getConnectionSetup(e){return this.restData("GET",`/v1/connections/setup/${encodeURIComponent(e)}`)}async createConnection(e){return this.restData("POST","/v1/connections",e)}async replaceConnection(e,r){return this.restData("PUT",`/v1/connections/${encodeURIComponent(e)}`,{credentials:r})}async updateConnection(e,r){return this.restData("PATCH",`/v1/connections/${encodeURIComponent(e)}`,r)}async deleteConnection(e){await this.restRequest("DELETE",`/v1/connections/${encodeURIComponent(e)}`)}async setDefaultConnection(e){await this.restRequest("POST",`/v1/connections/${encodeURIComponent(e)}/default`)}async listSystems(e={}){let r=(0,Or.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/systems${n}`)}async listAllSystems(e={}){return(0,Or.listAllPages)((r,n)=>this.listSystems({...e,page:r,limit:n}))}async createOAuthExchange(e){return(await this.restRequest("POST","/v1/oauth/exchanges",e)).data}async completeOAuthExchange(e,r){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/complete`,r)).data}async describeOAuthProviderPage(e){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/provider-page`)).data}async generateCredentialsLink(e){try{return{success:!0,credentialsUrl:(await this.restRequest("POST","/v1/authenticate",e||{})).data.credentialsUrl}}catch(r){return{success:!1,error:r.message}}}};yl.SuperglueClient=kv});var ZY=m(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.UnquotedKeyStrategy=ft.TripleQuoteStrategy=ft.TrailingCommaStrategy=ft.SingleQuoteStrategy=ft.PythonLiteralStrategy=ft.CommentStrategy=ft.ResilientJsonParser=ft.RepairStrategy=void 0;ft.parseJsonResilient=KOe;ft.parseJSON=XOe;ft.isValidJson=eUe;ft.prettyPrintJson=tUe;ft.minifyJson=rUe;var ci=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};ft.RepairStrategy=ci;var sE=class extends ci{constructor(){super(...arguments),this.name="TripleQuoteRepair",this.description="Converts triple-quoted strings to proper JSON, parsing nested JSON content"}canApply(e){return/"""/.test(e)}apply(e){return e.replace(/"""([\s\S]*?)"""/g,(r,n)=>{let i=n.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let s=JSON.parse(i);return JSON.stringify(s)}catch{return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`})}};ft.TripleQuoteStrategy=sE;var aE=class extends ci{constructor(){super(...arguments),this.name="PythonLiteralRepair",this.description="Converts Python literals to JavaScript equivalents"}canApply(e){return/\b(None|True|False)\b/.test(e)}apply(e){return e.replace(/\bNone\b/g,"null").replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false")}};ft.PythonLiteralStrategy=aE;var cE=class extends ci{constructor(){super(...arguments),this.name="TrailingCommaRepair",this.description="Removes trailing commas from objects and arrays"}canApply(e){return/,\s*[}\]]/.test(e)}apply(e){return e.replace(/,(\s*[}\]])/g,"$1")}};ft.TrailingCommaStrategy=cE;var uE=class extends ci{constructor(){super(...arguments),this.name="SingleQuoteRepair",this.description="Converts single quotes to double quotes"}canApply(e){return/[{,]\s*'[^']*'\s*:/.test(e)||/:\s*'[^']*'/.test(e)}apply(e){let r=e.replace(/([{,]\s*)'([^']+)'(\s*:)/g,'$1"$2"$3');return r=r.replace(/(:\s*)'([^']+)'(\s*[,}])/g,'$1"$2"$3'),r}};ft.SingleQuoteStrategy=uE;var lE=class extends ci{constructor(){super(...arguments),this.name="UnquotedKeyRepair",this.description="Adds quotes to unquoted object keys"}canApply(e){return/[{,]\s*[a-zA-Z_$][a-zA-Z0-9_$]*\s*:/.test(e)}apply(e){return e.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)(\s*:)/g,'$1"$2"$3')}};ft.UnquotedKeyStrategy=lE;var dE=class extends ci{constructor(){super(...arguments),this.name="CommentRemoval",this.description="Removes JavaScript-style comments"}canApply(e){return/\/\/.*$|\/\*[\s\S]*?\*\//m.test(e)}apply(e){let r=e.replace(/\/\/.*$/gm,"");return r=r.replace(/\/\*[\s\S]*?\*\//g,""),r}};ft.CommentStrategy=dE;var Ov=class extends ci{constructor(){super(...arguments),this.name="UnescapedControlCharactersRepair",this.description="Escapes unescaped control characters (newlines, tabs, etc.) in JSON strings"}canApply(e){try{return JSON.parse(e),!1}catch(r){let n=r.message||"";return n.includes("control character")||n.includes("Bad control")||n.includes("Unexpected token")&&/[\n\r\t]/.test(e)}}apply(e){let r="",n=!1,i=!1;for(let o=0;o<e.length;o++){let s=e[o],a=o>0?e[o-1]:"";if(i){r+=s,i=!1;continue}if(s==="\\"&&n){r+=s,i=!0;continue}if(s==='"'&&a!=="\\"){n=!n,r+=s;continue}if(n)switch(s){case`
1874
+ `:r+="\\n";break;case"\r":r+="\\r";break;case" ":r+="\\t";break;case"\b":r+="\\b";break;case"\f":r+="\\f";break;default:let c=s.charCodeAt(0);c<32?r+="\\u"+("0000"+c.toString(16)).slice(-4):r+=s}else r+=s}return r}},Uv=class extends ci{constructor(){super(...arguments),this.name="TrailingCharactersRepair",this.description="Removes trailing characters after valid JSON structure"}canApply(e){let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return!1;let n=0,i=0,o=!1,s=!1;for(let a=0;a<r.length;a++){let c=r[a];if(o)s?s=!1:c==="\\"?s=!0:c==='"'&&(o=!1);else if(c==='"')o=!0;else if(c==="{")n++;else if(c==="}"){if(n--,n===0&&i===0&&a>0&&a<r.length-1)return!0}else if(c==="[")i++;else if(c==="]"&&(i--,i===0&&n===0&&a>0&&a<r.length-1))return!0}return!1}apply(e){let r=e.trim(),n=0,i=0,o=!1,s=!1,a=-1;for(let c=0;c<r.length;c++){let u=r[c];if(o)s?s=!1:u==="\\"?s=!0:u==='"'&&(o=!1);else if(u==='"')o=!0;else if(u==="{")n++;else if(u==="}"){if(n--,n===0&&i===0&&c>0){a=c;break}}else if(u==="[")i++;else if(u==="]"&&(i--,i===0&&n===0&&c>0)){a=c;break}}return a>0&&a<r.length-1?r.substring(0,a+1):e}},El=class{constructor(e={}){this.strategies=[],this.repairLog=[],this.options={attemptRepair:!0,maxDepth:10,preserveStringsOnFailure:!1,logRepairs:!1,...e},this.initializeDefaultStrategies(),e.customStrategies&&this.strategies.push(...e.customStrategies)}initializeDefaultStrategies(){this.strategies=[new sE,new uE,new Ov,new Uv,new aE,new cE,new lE,new dE]}parse(e){let r=Date.now();this.repairLog=[];let n=e instanceof Buffer?e.toString("utf8"):String(e);try{return{success:!0,data:JSON.parse(n),metadata:{parseTime:Date.now()-r,strategiesApplied:[]}}}catch(s){if(!this.options.attemptRepair)return{success:!1,error:`JSON parse error: ${s}`,metadata:{parseTime:Date.now()-r}}}let i=n,o=[];for(let s of this.strategies)if(s.canApply(i)){let a=i;if(i=s.apply(i),a!==i){o.push(s.name),this.repairLog.push(s.description),this.options.logRepairs&&console.log(`Applied ${s.name}: ${s.description}`);try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}catch{}}}try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}catch(s){let a=this.aggressiveFallback(i);return a.success?{...a,repairs:[...this.repairLog,"Applied aggressive fallback"],metadata:{parseTime:Date.now()-r,strategiesApplied:[...o,"AggressiveFallback"]}}:{success:!1,error:`Failed to parse JSON after applying ${o.length} strategies: ${s}`,repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}}aggressiveFallback(e){try{let r=e.indexOf("{"),n=e.indexOf("[");if(r===-1&&n===-1)return{success:!1,error:"No JSON-like structure found"};let i=r===-1?n:n===-1?r:Math.min(r,n),o=e.substring(i);for(let a of this.strategies)a.canApply(o)&&(o=a.apply(o));return{success:!0,data:JSON.parse(o)}}catch(r){return{success:!1,error:`Aggressive fallback failed: ${r}`}}}addStrategy(e){this.strategies.push(e)}removeStrategy(e){this.strategies=this.strategies.filter(r=>r.name!==e)}getStrategies(){return this.strategies.map(e=>e.name)}};ft.ResilientJsonParser=El;var WY=new El;function KOe(t,e){return(e?new El(e):WY).parse(t)}function XOe(t){let e=WY.parse(t);if(e.success)return e.repairs&&e.repairs.length>0&&console.log("JSON parsed with repairs:",e.repairs),e.data;throw new Error(`Failed to parse JSON: ${e.error}`)}function eUe(t){try{return JSON.parse(t),!0}catch{return!1}}function tUe(t,e=2){return JSON.stringify(t,null,e)}function rUe(t){let r=new El().parse(t);if(r.success)return JSON.stringify(r.data);throw new Error("Cannot minify invalid JSON")}});var KY=m(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.MANAGED_OAUTH_APP_PREFIX=void 0;yr.projectOAuthAppAuthentication=oUe;yr.isDynamicOAuthConfiguration=sUe;yr.isReusableOAuthAppForTemplate=aUe;yr.getManagedOAuthTemplateId=cUe;yr.getOAuthAppSharedConfiguration=uUe;yr.copyOAuthAppConfiguration=lUe;yr.encryptConnectionAuthentication=dUe;yr.decryptConnectionAuthentication=AUe;yr.isManagedOAuthEndpointAllowed=pUe;var nUe=$S(),iUe=Dn();function oUe(t){let{clientSecret:e,config:r,...n}=t,{extraHeaders:i,extraBodyParams:o,...s}=r??{};return{...n,...r?{config:s}:{}}}yr.MANAGED_OAUTH_APP_PREFIX="managed:";function sUe({authentication:t,template:e}){return t.oauthClientMode==="dynamic"||!!e?.oauth?.registrationUrl&&!t.clientSecret}function aUe({app:t,template:e}){return!e?.oauth?.registrationUrl||!!t.clientSecretHash}function cUe(t){if(t?.type==="oauth2")return t.oauthAppId?.startsWith(yr.MANAGED_OAUTH_APP_PREFIX)?t.oauthAppId.slice(yr.MANAGED_OAUTH_APP_PREFIX.length):void 0}function uUe(t){let{grantType:e,scopes:r,oauthAppId:n,...i}=t;return i}function lUe({appAuthentication:t,authentication:e}){if(e?.type!=="oauth2")return{...t};let r=Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0));return{...t,...r,config:{...t.config,...e.config}}}function dUe({authentication:t,encrypt:e}){if(t.type!=="oauth2")return t;let r={...t,config:{...t.config}};t.clientSecret!==void 0&&(r.clientSecret=e({value:t.clientSecret}).value);for(let n of["extraHeaders","extraBodyParams"]){let i=t.config?.[n];i!==void 0&&(r.config[n]=e({value:(0,iUe.safeStringify)(i)}).value)}return r}function AUe({authentication:t,decrypt:e}){if(t.type!=="oauth2")return t;let r={...t,config:{...t.config}};t.clientSecret!==void 0&&(r.clientSecret=e({value:t.clientSecret}).value);for(let n of["extraHeaders","extraBodyParams"]){let i=t.config?.[n];typeof i=="string"&&(r.config[n]=JSON.parse(e({value:i}).value))}return r}function pUe({templateId:t,endpoint:e,url:r}){let n=nUe.systems[t]?.oauth,i=n?.[e];if(!n?.managed||!i)return!1;try{let o=new URL(r),s=new URL(i);return o.protocol!=="https:"||o.port||o.username||o.password||o.hash||o.pathname!==s.pathname?!1:o.hostname===s.hostname||(n.managedEndpointHosts??[]).some(a=>a.startsWith("*.")?o.hostname.endsWith(a.slice(1)):o.hostname===a)}catch{return!1}}});var eV=m(XY=>{"use strict";Object.defineProperty(XY,"__esModule",{value:!0})});var Er=m(W=>{"use strict";var fUe=W&&W.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),ne=W&&W.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&fUe(e,t,r)};Object.defineProperty(W,"__esModule",{value:!0});W.SSELogSubscriptionManager=W.SuperglueHttpError=W.SuperglueClient=void 0;ne(gx(),W);ne(bx(),W);ne(Ox(),W);ne(Mx(),W);ne(Fx(),W);ne(jx(),W);ne(Hx(),W);ne(Sg(),W);ne(CL(),W);ne(Wf(),W);ne(BL(),W);ne(_L(),W);ne(QL(),W);ne(vL(),W);ne(DL(),W);ne(tS(),W);ne(RL(),W);ne(OL(),W);ne(UL(),W);ne(ML(),W);ne(iS(),W);ne(cS(),W);ne(LL(),W);ne(PL(),W);ne(FL(),W);ne(uh(),W);ne(zL(),W);ne(HL(),W);ne(GL(),W);ne(YL(),W);ne(WL(),W);ne(dP(),W);ne(ES(),W);ne(Vd(),W);ne(yS(),W);ne(gP(),W);ne(yP(),W);ne(IP(),W);ne(Eg(),W);ne(DP(),W);ne(RP(),W);ne(Ig(),W);ne(fS(),W);ne(xP(),W);ne(LP(),W);ne($S(),W);ne(JP(),W);ne(WP(),W);ne(ZP(),W);ne(t$(),W);ne(n$(),W);ne(xr(),W);ne(Dn(),W);ne(i$(),W);ne(o$(),W);ne(Fg(),W);ne(pu(),W);ne(Ld(),W);var tV=JY();Object.defineProperty(W,"SuperglueClient",{enumerable:!0,get:function(){return tV.SuperglueClient}});Object.defineProperty(W,"SuperglueHttpError",{enumerable:!0,get:function(){return tV.SuperglueHttpError}});var hUe=zS();Object.defineProperty(W,"SSELogSubscriptionManager",{enumerable:!0,get:function(){return hUe.SSELogSubscriptionManager}});ne(ZY(),W);ne(KY(),W);ne(eV(),W)});var JE=require("commander");var Ur=ye(require("fs")),iV=ye(require("os")),As=ye(require("path")),hp=ye(Er()),rV=new Set(["runner","builder","admin"]),nV={output:{mode:"stdout",directory:".superglue/output"},preset:"admin"};function ps(t){let e=As.join(process.cwd(),".superglue"),r=iV.homedir();if(!r)return e;let n=As.join(r,".superglue");return t===!0?e:t===!1?n:Ur.existsSync(As.join(e,"config.json"))?e:n}function Mv(t){return As.join(ps(t),"config.json")}function AE(t){let e=Mv(t);if(!Ur.existsSync(e))return{};try{return JSON.parse(Ur.readFileSync(e,"utf-8"))}catch{return{}}}function Il(t){let e=AE(),r=t.apiKey||(0,hp.readProcessEnvironmentValue)("SUPERGLUE_API_KEY")||e.apiKey||"",n=t.endpoint||(0,hp.readProcessEnvironmentValue)("SUPERGLUE_API_ENDPOINT")||e.endpoint||"https://api.superglue.cloud",i=(0,hp.readProcessEnvironmentValue)("SUPERGLUE_WEB_ENDPOINT")||e.webEndpoint||n.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue"),o=(0,hp.readProcessEnvironmentValue)("SUPERGLUE_CLI_PRESET"),s=o&&rV.has(o)?o:e.preset&&rV.has(e.preset)?e.preset:"admin";return{...nV,...e,apiKey:r,endpoint:n,webEndpoint:i,preset:s,output:{...nV.output,...e.output}}}function pE(t,e){let r=ps(e);Ur.existsSync(r)||Ur.mkdirSync(r,{recursive:!0}),Ur.writeFileSync(As.join(r,"config.json"),JSON.stringify(t,null,2)+`
1875
+ `,{mode:384})}function fE(t,e){let r=As.join(ps(e),"drafts");if(Ur.existsSync(r)||Ur.mkdirSync(r,{recursive:!0}),t.output.mode==="stdout+file"){let n=As.resolve(t.output.directory);Ur.existsSync(n)||Ur.mkdirSync(n,{recursive:!0})}}var zv=ye(Er());var xv=ye(require("readline"));var aV=require("child_process"),cV=require("util");var oV={name:"@superglue/cli",version:"1.1.217",bin:{sg:"./dist/cli.js"},files:[".claude-plugin/","dist/","skills/","LICENSE"],dependencies:{commander:"15.0.0-0","fast-json-patch":"3.1.1"},devDependencies:{"@superglue/shared":"file:../shared","@types/node":"25.5.0",tsup:"8.5.1",typescript:"5.8.3"},scripts:{build:"tsup && (cp -r skills dist/ 2>/dev/null || true)",dev:"tsup --watch","type-check":"tsc --noEmit",prepublishOnly:"npm run build"},publishConfig:{access:"public"}};var mUe=(0,cV.promisify)(aV.exec),Ir=oV.version;function sV(t){let e=t.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:t}}function gE(t,e){let r=t.split("."),n=e.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o++){let s=sV(r[o]||"0"),a=sV(n[o]||"0");if(s.numeric<a.numeric)return-1;if(s.numeric>a.numeric||s.prerelease===null&&a.prerelease!==null)return 1;if(s.prerelease!==null&&a.prerelease===null)return-1;if(s.prerelease!==null&&a.prerelease!==null){if(s.prerelease<a.prerelease)return-1;if(s.prerelease>a.prerelease)return 1}}return 0}async function mE(){try{let t=await fetch("https://registry.npmjs.org/@superglue/cli/latest",{signal:AbortSignal.timeout(5e3)});return t.ok&&(await t.json()).version||null}catch{return null}}var hE=null;function uV(){le()&&(hE=mE())}async function lV(){if(!(!le()||!hE)){try{let t=new Promise(r=>{setTimeout(()=>r(null),2e3).unref()}),e=await Promise.race([hE,t]);e&&gE(Ir,e)<0&&(console.error(""),console.error(`${I.cyan}${I.bold} Update available: ${Ir} \u2192 ${e}${I.reset}`),console.error(`${I.cyan} Run ${I.bold}sg update${I.reset}${I.cyan} to upgrade${I.reset}`),console.error(""))}catch{}hE=null}}async function dV(){let t=await mE();if(!t)return{success:!1,message:"Could not fetch latest version from npm"};if(gE(Ir,t)>=0)return{success:!0,message:`Already on latest version (${Ir})`};try{return await mUe("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${Ir} to ${t}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var le=()=>process.argv.includes("--table")&&process.stdout.isTTY,Hn=()=>process.argv.includes("--full"),I={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m"};function AV(t,e){let r=e||t;return`\x1B]8;;${t}\x07${I.underline}${I.cyan}${r}${I.reset}\x1B]8;;\x07`}function pV(){if(!le())return;let t=I.reset,e=I.dim,r="\x1B[47;30m",n=[" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@- "," =@@@- @@@@ "," @@@ @@% "," -@@ @@@@= @@@ @@@ @@@@@#@ @@@@@@@ @@@@@@@ @@@@@@ @@@ @@@ @@@ @@@@@@* %@@ "," @@ @@@ *@ @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @% @@@ @@@ @@@ @@* @@# "," #@@ @@@# @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @@@ @@@ @@@ @@* @@ "," @@- @@@@= @@@ @@@ @@@@@@@ @@@@@@ @@@@@@@ @@@ @@% @@@ @@@ @@@ @@@@@. @@."," #@% .@@@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* @@ "," @@ @ @@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* *@@ "," -@@ @@@@= @@@@@@ @@@ @@@@@@@ @@@ -@@ @@@@@@ @@@@@@% @@@@@@. @@@@@@* #@@ "," :@@* @@@ "," %@@@ =@@@. "," :@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% "];console.log(""),n.forEach(i=>{let o=i.search(/\S/),s=i.length-[...i].reverse().join("").search(/\S/)-1;if(o===-1)return console.log(" "+i);let a=i.slice(0,o),c=i.slice(o,s+1).split("").map(l=>l===" "?" ":"\u2588").join(""),u=i.slice(s+1);console.log(` ${a}${r}${c}${t}${u}`)}),console.log(` ${e} CLI v${Ir}${t}`),console.log("")}function Ot(t){if(!le())return{stop:()=>{},update:()=>{},log:()=>{}};let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],r=0,n=t,i=()=>process.stdout.write("\r\x1B[2K"),o=()=>{process.stdout.write(`\r ${I.cyan}${e[r++%e.length]}${I.reset} ${n}`)},s=setInterval(o,80);return{update:a=>{n=a},log:a=>{i(),console.log(` ${I.dim}\u2502${I.reset} ${a}`),o()},stop:a=>{clearInterval(s),i(),a&&console.log(` ${a}`)}}}function te(t){le()?yE(t):console.log(JSON.stringify(t,null,2))}function De(t,e){le()?(console.log(` ${I.green}\u2713${I.reset} ${t}`),e&&yE(e,4)):console.log(JSON.stringify({success:!0,message:t,...e&&typeof e=="object"?e:{data:e}}))}function v(t,e){le()?(console.error(` ${I.red}\u2717${I.reset} ${t}`),e&&yE(e,4)):console.error(JSON.stringify({success:!1,error:t,details:e}))}function un(t){le()&&console.log(` ${I.dim}${t}${I.reset}`)}function kc(t){le()&&(console.log(`
1876
1876
  ${I.bold}${I.cyan}${t}${I.reset}`),console.log(` ${I.dim}${"\u2500".repeat(t.length)}${I.reset}`))}function Pt(t,e,r){if(!le()){console.log(JSON.stringify({success:!0,total:r?.total??t.length,items:t}));return}if(t.length===0){console.log(`
1877
1877
  ${I.dim}0 results${I.reset}
1878
1878
  `);return}let n=e||Object.keys(t[0]),i=Hn()?1/0:60,o=n.map(l=>Math.min(i,Math.max(l.length,...t.map(d=>String(d[l]??"").replace(/[\n\r]+/g," ").trim().length))));console.log("");let s=n.map((l,d)=>`${I.bold}${I.cyan}${l.toUpperCase().padEnd(o[d])}${I.reset}`).join(" ");console.log(` ${s}`);let a=o.map(l=>`${I.dim}${"\u2500".repeat(l)}${I.reset}`).join(`${I.dim}\u2500\u2500${I.reset}`);console.log(` ${a}`);for(let l of t){let d=n.map((A,p)=>{let h=String(l[A]??"").replace(/[\n\r]+/g," ").trim();if(h.length>i){let w=`\u2026 (${h.length})`;h=h.slice(0,Math.max(0,i-w.length))+`${I.dim}${w}${I.reset}`}return A==="status"?`${{success:I.green,running:I.yellow,failed:I.red,aborted:I.red,error:I.red,pending:I.dim}[h.toLowerCase()]||""}${h.padEnd(o[p])}${I.reset}`:h.padEnd(o[p])}).join(" ");console.log(` ${d}`)}let c=r?.total??t.length,u=c===t.length?`${t.length} result${t.length===1?"":"s"}`:`${t.length} of ${c} result${c===1?"":"s"}`;console.log(`
@@ -1937,7 +1937,7 @@ Quick Reference:
1937
1937
  sg tool state reset <toolId> Delete persistent state
1938
1938
 
1939
1939
  Output: JSON by default. Use --table for human-readable, --full to disable truncation.
1940
- `);ME(n,"build","tool.build",r,()=>kV(n,e)),UV(n,e,r),ME(n,"edit","tool.edit",r,()=>LV(n,e)),ME(n,"save","tool.save",r,()=>PV(n,e)),ME(n,"state","tool.state",r,()=>zV(n,e)),FV(n,e)}var LE=ye(Er());var gp=ye(Er());function qV(t){if(!t.createdAt)return Number.POSITIVE_INFINITY;let e=new Date(t.createdAt).getTime();return Number.isNaN(e)?Number.POSITIVE_INFINITY:e}function PUe(t){let e=t.filter(r=>r.isOwner);return e.find(r=>r.isDefault)||e.sort((r,n)=>qV(r)-qV(n))[0]}async function ko(t,e,r){let n=await t.listAllConnections({systemId:e});if(!r)return PUe(n);let i=n.find(o=>o.id===r);if(!i)throw new Error(`Connection '${r}' is not accessible under '${e}'`);return i}async function GV({client:t,systemId:e,credentials:r,url:n,authentication:i,tunnel:o,usageInstructions:s,oauthAppId:a,connectionId:c}){let u=await ko(t,e,c);if(!u){if(Object.keys(r??{}).length===0&&n===void 0&&i===void 0&&o===void 0&&s===void 0&&a===void 0)return null;if(!i&&!a)throw new Error(`No connection exists for '${e}' yet. Pass --authentication (for example '{"type":"api_key"}' or '{"type":"none"}') to create one.`);if(a!==void 0&&i&&i.type!=="oauth2")throw new Error("oauthAppId requires OAuth authentication");return t.createConnection({systemId:e,credentials:r,url:n||void 0,authentication:i??{type:"oauth2"},tunnel:o,...s?{usageInstructions:s}:{},...a?{oauthAppId:a}:{}})}if(a!==void 0&&(i??u.authentication).type!=="oauth2")throw new Error("oauthAppId requires OAuth authentication");let l=r===void 0?u:await t.replaceConnection(u.id,r);return n===void 0&&i===void 0&&o===void 0&&s===void 0&&a===void 0?l:t.updateConnection(u.id,{...n===void 0?{}:{url:n||null},...i===void 0?{}:{authentication:i},...o===void 0?{}:{tunnel:o},...s===void 0?{}:{usageInstructions:s||null},...a===void 0?{}:{oauthAppId:a}})}async function YV(t,e,r){let n=await ko(t,e,r);return n?t.replaceConnection(n.id,{}):null}function Vv(t){return{id:t.id,name:t.name,templateName:t.templateName||"",connections:t.connectionCount}}async function $Ue(t,e){let[r,n]=await Promise.all([ko(t,e.id),t.listOAuthApps({systemId:e.id})]),i=(0,gp.findTemplateForSystem)({id:e.id,url:r?.url});return{system:{...Vv(e),...r?.url?{url:r.url}:{},authType:r?.authentication?.type||"none",credentialKeys:(r?.credentialKeys||[]).map(o=>({...o,placeholder:`<<${e.id}_${o.key}>>`})),urlPlaceholder:`<<${e.id}_url>>`},template:i?.template||null,oauthApps:n}}function VV(t,e){t.command("oauth-apps").description("List reusable organization and superglue OAuth apps").option("--system-id <id>","Filter by connection namespace").option("--limit <n>","Max results","25").option("--offset <n>","Skip first N results","0").action(async r=>{try{let{client:n}=e(),i=await n.listOAuthApps({systemId:r.systemId}),o=Math.min(Math.max(parseInt(r.limit,10)||25,1),gp.LIST_MAX_LIMIT),s=Math.max(parseInt(r.offset,10)||0,0),a=i.slice(s,s+o);le()?Pt(a.map(c=>({id:c.id,name:c.name,systemId:c.systemId,source:c.source,hasClientSecret:c.hasClientSecret})),["id","name","systemId","source","hasClientSecret"]):te({oauthApps:a,total:i.length,hasMore:s+a.length<i.length})}catch(n){v(n.message),process.exit(1)}}),t.command("list").description("List the system ids your org uses").option("--limit <n>","Max results","25").option("--offset <n>","Skip first N results","0").action(async r=>{let{client:n}=e();try{let i=Math.min(Math.max(parseInt(r.limit,10)||25,1),gp.LIST_MAX_LIMIT),o=Math.max(parseInt(r.offset,10)||0,0),{items:s,total:a,hasMore:c}=await UE({limit:i,offset:o,fetchPage:(l,d)=>n.listSystems({limit:d,page:l})}),u=s.map(Vv);le()?Pt(u,["id","name","templateName","connections","knowledgeDocs"],{total:a}):te({success:!0,total:a,hasMore:c,items:u})}catch(i){v(i.message),process.exit(1)}}),t.command("find [query]").description("Find systems by query or exact ID").option("--id <exactId>","Exact system ID lookup").action(async(r,n)=>{let{client:i}=e();try{let o=await i.listAllSystems();if(n.id){let u=o.find(l=>l.id===n.id);u||(v(`System not found: ${n.id}`),process.exit(1)),te({success:!0,...await $Ue(i,u)});return}let s=(r||"*").trim(),a=s.toLowerCase().split(/\s+/),c=s==="*"?o:o.filter(u=>{let l=[u.id,u.name,u.templateName].filter(Boolean).join(" ").toLowerCase();return a.some(d=>l.includes(d))});te({success:!0,total:c.length,systems:c.map(Vv)})}catch(o){v(o.message),process.exit(1)}})}var xE=ye(Er());function FUe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&"currentItem"in t&&"data"in t&&typeof t.success=="boolean"}function JV(t,e){t.command("call").description("Call a system (API, database, file server)").option("--url <url>","Absolute URL, or <<systemId_url>> followed by the path").option("--system-id <id>","System ID; selects your connection and adds its auth header").option("--connection-id <id>","Connection override; implies its system ID when --system-id is omitted").option("--auth <mode>","auto (default) adds the auth header; none sends no default header","auto").option("--method <method>","HTTP method","GET").option("--headers <json>","HTTP headers JSON").option("--body <string>","Request body").option("--timeout <ms>","Per-request timeout in milliseconds (minimum 1000)").option("--continue-on-error","Return failed response envelope instead of exiting non-zero").option("--file <key=path...>","File references",(r,n)=>(n.push(r),n),[]).addHelpText("after",`
1940
+ `);ME(n,"build","tool.build",r,()=>kV(n,e)),UV(n,e,r),ME(n,"edit","tool.edit",r,()=>LV(n,e)),ME(n,"save","tool.save",r,()=>PV(n,e)),ME(n,"state","tool.state",r,()=>zV(n,e)),FV(n,e)}var LE=ye(Er());var gp=ye(Er());function qV(t){if(!t.createdAt)return Number.POSITIVE_INFINITY;let e=new Date(t.createdAt).getTime();return Number.isNaN(e)?Number.POSITIVE_INFINITY:e}function PUe(t){let e=t.filter(r=>r.isOwner);return e.find(r=>r.isDefault)||e.sort((r,n)=>qV(r)-qV(n))[0]}async function ko(t,e,r){let n=await t.listAllConnections({systemId:e});if(!r)return PUe(n);let i=n.find(o=>o.id===r);if(!i)throw new Error(`Connection '${r}' is not accessible under '${e}'`);return i}async function GV({client:t,systemId:e,credentials:r,url:n,authentication:i,tunnel:o,usageInstructions:s,oauthAppId:a,connectionId:c}){let u=await ko(t,e,c);if(!u){if(Object.keys(r??{}).length===0&&n===void 0&&i===void 0&&o===void 0&&s===void 0&&a===void 0)return null;if(!i&&!a)throw new Error(`No connection exists for '${e}' yet. Pass --authentication (for example '{"type":"api_key"}' or '{"type":"none"}') to create one.`);if(a!==void 0&&i&&i.type!=="oauth2")throw new Error("oauthAppId requires OAuth authentication");return t.createConnection({systemId:e,credentials:r,url:n||void 0,authentication:i??{type:"oauth2"},tunnel:o,...s?{usageInstructions:s}:{},...a?{oauthAppId:a}:{}})}if(a!==void 0&&(i??u.authentication).type!=="oauth2")throw new Error("oauthAppId requires OAuth authentication");let l=r===void 0?u:await t.replaceConnection(u.id,r);return n===void 0&&i===void 0&&o===void 0&&s===void 0&&a===void 0?l:t.updateConnection(u.id,{...n===void 0?{}:{url:n||null},...i===void 0?{}:{authentication:i},...o===void 0?{}:{tunnel:o},...s===void 0?{}:{usageInstructions:s||null},...a===void 0?{}:{oauthAppId:a}})}async function YV(t,e,r){let n=await ko(t,e,r);return n?t.replaceConnection(n.id,{}):null}function Vv(t){return{id:t.id,name:t.name,templateName:t.templateName||"",connections:t.connectionCount}}async function $Ue(t,e){let[r,n]=await Promise.all([ko(t,e.id),t.listOAuthApps({systemId:e.id})]),i=(0,gp.findTemplateForSystem)({id:e.id,url:r?.url});return{system:{...Vv(e),...r?.url?{url:r.url}:{},authType:r?.authentication?.type||"none",credentialKeys:(r?.credentialKeys||[]).map(o=>({...o,placeholder:`<<${e.id}_${o.key}>>`})),urlPlaceholder:`<<${e.id}_url>>`},template:i?.template||null,oauthApps:n}}function VV(t,e){t.command("oauth-apps").description("List reusable organization and superglue OAuth apps").option("--system-id <id>","Filter by connection namespace").option("--limit <n>","Max results","25").option("--offset <n>","Skip first N results","0").action(async r=>{try{let{client:n}=e(),i=await n.listOAuthApps({systemId:r.systemId}),o=Math.min(Math.max(parseInt(r.limit,10)||25,1),gp.LIST_MAX_LIMIT),s=Math.max(parseInt(r.offset,10)||0,0),a=i.slice(s,s+o);le()?Pt(a.map(c=>({id:c.id,name:c.name,systemId:c.systemId,source:c.source,clientSecretHash:c.clientSecretHash??""})),["id","name","systemId","source","clientSecretHash"]):te({oauthApps:a,total:i.length,hasMore:s+a.length<i.length})}catch(n){v(n.message),process.exit(1)}}),t.command("list").description("List the system ids your org uses").option("--limit <n>","Max results","25").option("--offset <n>","Skip first N results","0").action(async r=>{let{client:n}=e();try{let i=Math.min(Math.max(parseInt(r.limit,10)||25,1),gp.LIST_MAX_LIMIT),o=Math.max(parseInt(r.offset,10)||0,0),{items:s,total:a,hasMore:c}=await UE({limit:i,offset:o,fetchPage:(l,d)=>n.listSystems({limit:d,page:l})}),u=s.map(Vv);le()?Pt(u,["id","name","templateName","connections","knowledgeDocs"],{total:a}):te({success:!0,total:a,hasMore:c,items:u})}catch(i){v(i.message),process.exit(1)}}),t.command("find [query]").description("Find systems by query or exact ID").option("--id <exactId>","Exact system ID lookup").action(async(r,n)=>{let{client:i}=e();try{let o=await i.listAllSystems();if(n.id){let u=o.find(l=>l.id===n.id);u||(v(`System not found: ${n.id}`),process.exit(1)),te({success:!0,...await $Ue(i,u)});return}let s=(r||"*").trim(),a=s.toLowerCase().split(/\s+/),c=s==="*"?o:o.filter(u=>{let l=[u.id,u.name,u.templateName].filter(Boolean).join(" ").toLowerCase();return a.some(d=>l.includes(d))});te({success:!0,total:c.length,systems:c.map(Vv)})}catch(o){v(o.message),process.exit(1)}})}var xE=ye(Er());function FUe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&"currentItem"in t&&"data"in t&&typeof t.success=="boolean"}function JV(t,e){t.command("call").description("Call a system (API, database, file server)").option("--url <url>","Absolute URL, or <<systemId_url>> followed by the path").option("--system-id <id>","System ID; selects your connection and adds its auth header").option("--connection-id <id>","Connection override; implies its system ID when --system-id is omitted").option("--auth <mode>","auto (default) adds the auth header; none sends no default header","auto").option("--method <method>","HTTP method","GET").option("--headers <json>","HTTP headers JSON").option("--body <string>","Request body").option("--timeout <ms>","Per-request timeout in milliseconds (minimum 1000)").option("--continue-on-error","Return failed response envelope instead of exiting non-zero").option("--file <key=path...>","File references",(r,n)=>(n.push(r),n),[]).addHelpText("after",`
1941
1941
  ${I.bold}Authentication:${I.reset}
1942
1942
  With --system-id or --connection-id the server picks your connection (your starred one, otherwise
1943
1943
  the accessible one you have held longest, owned or shared), refreshes OAuth tokens, and adds the
@@ -147,14 +147,16 @@ Systems are derived: a connection namespace is derived from existing connections
147
147
 
148
148
  Removed commands (`sg system create`, `edit`, `credentials`, and `search-docs`) return a deprecation error with `sg update` and replacement guidance. Removed system API endpoints return HTTP 410 with the same guidance. Run `sg update`, then use connection commands; use `sg system find --id <id>` for system knowledge. Legacy `/credentials` API aliases remain available with deprecation headers.
149
149
 
150
- 1. Read the relevant tool's namespace first, then inspect existing namespaces with `sg system find <query>` and the connections you can access under one with `sg system connection list --system-id <id>`. Reuse that exact id, even when other users' connections are hidden. For a new namespace, use the template id, not its display name. Without a template, choose a descriptive id. Keep account labels in connection names; separate namespaces when tools need distinct services or environments.
150
+ Match accessible owned and shared connections to the requested account, tenant, and environment, even across different system IDs. Respect an explicit connection choice or request for separate access. Otherwise, prefer suitable existing access; ask only when the account or connection choice is unclear. Defaults apply within one system ID and do not establish authentication or suitability.
151
+
152
+ 1. Read the relevant tool's namespace first, then inspect existing namespaces with `sg system find <query>`. List accessible connections in each candidate namespace with `sg system connection list --system-id <id>`. Reuse an existing id for the same logical service; preserve IDs referenced by saved tools. For a new namespace, use the template id, not its display name. Without a template, choose a descriptive id. Keep account labels in connection names; separate namespaces when tools need distinct services or environments.
151
153
  2. Save your connection under the id: `sg system connection set --system-id <id> --url "..." --credentials '{...}' --authentication '{"type":"api_key"}'`. `--authentication` or `--oauth-app-id` is required when creating a connection; use `{"type":"none"}` for unauthenticated systems. Use the saved connection's returned `systemId` in later commands, tool steps, and placeholders.
152
154
  3. For OAuth: discover reusable apps with `sg system oauth-apps [--system-id <id>]` and link one with `--oauth-app-id <id>`. When several apps fit, ask the user which one to use. A new client ID and secret creates a reusable org app automatically, including default scopes. Otherwise add the client config with `--authentication '{"type":"oauth2",...}'`, then `sg system oauth --system-id <id> [--scopes "..."]` opens a browser flow. Omit `--scopes` to use saved connection scopes. Supply it to replace the set, including more or fewer scopes; `--scopes ""` requests none. Overrides are saved on the connection and do not change app defaults. User approves → tokens saved to your connection
153
155
  4. For private systems: `--tunnel-id <id>` binds a Secure Gateway tunnel to the connection
154
156
  5. Verify connectivity with `sg system call`
155
157
  6. For updates: re-run `sg system connection set --system-id <id>` with the fields to change. When the namespace holds several connections, pass `--connection-id <id>` from `sg system connection list` to `set`, `clear`, `oauth`, and `call`; without it, `set` and `oauth` target your default or oldest owned connection
156
158
 
157
- A connection linked to an OAuth app uses the app's client ID, client secret, and token URL; app secret rotations reach every linked connection. Other authentication fields are copied on selection and stay connection-specific; scope edits remain local. Changing the client ID or token URL detaches the connection and requires its own client secret; `--oauth-app-id ""` also detaches and must be sent together with the connection's own client secret. Changing client settings retains tokens and supplemental secrets; authorize again afterward. Managed secrets stay hidden and restricted to approved provider endpoints.
159
+ A connection linked to an OAuth app uses the app's client ID, client secret, and token URL; app secret rotations reach every linked connection. Other authentication fields are copied on selection and stay connection-specific; scope edits remain local. Changing the client ID or token URL detaches the connection and requires its own client secret; `--oauth-app-id ""` also detaches and must be sent together with the connection's own client secret. Changing client settings retains tokens and supplemental secrets; authorize again afterward. Managed secrets stay hidden and restricted to approved provider endpoints. Every org member can use any organization OAuth app; its creator and administrators edit it. Client credentials connections keep their own client ID and secret and never take `--oauth-app-id`.
158
160
 
159
161
  When selecting an OAuth app on an existing non-OAuth connection, also pass `--authentication '{"type":"oauth2"}'`. An app-only update to a non-OAuth connection returns a validation error.
160
162
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superglue/cli",
3
- "version": "1.1.215",
3
+ "version": "1.1.217",
4
4
  "bin": {
5
5
  "sg": "./dist/cli.js"
6
6
  },
@@ -147,14 +147,16 @@ Systems are derived: a connection namespace is derived from existing connections
147
147
 
148
148
  Removed commands (`sg system create`, `edit`, `credentials`, and `search-docs`) return a deprecation error with `sg update` and replacement guidance. Removed system API endpoints return HTTP 410 with the same guidance. Run `sg update`, then use connection commands; use `sg system find --id <id>` for system knowledge. Legacy `/credentials` API aliases remain available with deprecation headers.
149
149
 
150
- 1. Read the relevant tool's namespace first, then inspect existing namespaces with `sg system find <query>` and the connections you can access under one with `sg system connection list --system-id <id>`. Reuse that exact id, even when other users' connections are hidden. For a new namespace, use the template id, not its display name. Without a template, choose a descriptive id. Keep account labels in connection names; separate namespaces when tools need distinct services or environments.
150
+ Match accessible owned and shared connections to the requested account, tenant, and environment, even across different system IDs. Respect an explicit connection choice or request for separate access. Otherwise, prefer suitable existing access; ask only when the account or connection choice is unclear. Defaults apply within one system ID and do not establish authentication or suitability.
151
+
152
+ 1. Read the relevant tool's namespace first, then inspect existing namespaces with `sg system find <query>`. List accessible connections in each candidate namespace with `sg system connection list --system-id <id>`. Reuse an existing id for the same logical service; preserve IDs referenced by saved tools. For a new namespace, use the template id, not its display name. Without a template, choose a descriptive id. Keep account labels in connection names; separate namespaces when tools need distinct services or environments.
151
153
  2. Save your connection under the id: `sg system connection set --system-id <id> --url "..." --credentials '{...}' --authentication '{"type":"api_key"}'`. `--authentication` or `--oauth-app-id` is required when creating a connection; use `{"type":"none"}` for unauthenticated systems. Use the saved connection's returned `systemId` in later commands, tool steps, and placeholders.
152
154
  3. For OAuth: discover reusable apps with `sg system oauth-apps [--system-id <id>]` and link one with `--oauth-app-id <id>`. When several apps fit, ask the user which one to use. A new client ID and secret creates a reusable org app automatically, including default scopes. Otherwise add the client config with `--authentication '{"type":"oauth2",...}'`, then `sg system oauth --system-id <id> [--scopes "..."]` opens a browser flow. Omit `--scopes` to use saved connection scopes. Supply it to replace the set, including more or fewer scopes; `--scopes ""` requests none. Overrides are saved on the connection and do not change app defaults. User approves → tokens saved to your connection
153
155
  4. For private systems: `--tunnel-id <id>` binds a Secure Gateway tunnel to the connection
154
156
  5. Verify connectivity with `sg system call`
155
157
  6. For updates: re-run `sg system connection set --system-id <id>` with the fields to change. When the namespace holds several connections, pass `--connection-id <id>` from `sg system connection list` to `set`, `clear`, `oauth`, and `call`; without it, `set` and `oauth` target your default or oldest owned connection
156
158
 
157
- A connection linked to an OAuth app uses the app's client ID, client secret, and token URL; app secret rotations reach every linked connection. Other authentication fields are copied on selection and stay connection-specific; scope edits remain local. Changing the client ID or token URL detaches the connection and requires its own client secret; `--oauth-app-id ""` also detaches and must be sent together with the connection's own client secret. Changing client settings retains tokens and supplemental secrets; authorize again afterward. Managed secrets stay hidden and restricted to approved provider endpoints.
159
+ A connection linked to an OAuth app uses the app's client ID, client secret, and token URL; app secret rotations reach every linked connection. Other authentication fields are copied on selection and stay connection-specific; scope edits remain local. Changing the client ID or token URL detaches the connection and requires its own client secret; `--oauth-app-id ""` also detaches and must be sent together with the connection's own client secret. Changing client settings retains tokens and supplemental secrets; authorize again afterward. Managed secrets stay hidden and restricted to approved provider endpoints. Every org member can use any organization OAuth app; its creator and administrators edit it. Client credentials connections keep their own client ID and secret and never take `--oauth-app-id`.
158
160
 
159
161
  When selecting an OAuth app on an existing non-OAuth connection, also pass `--authentication '{"type":"oauth2"}'`. An app-only update to a non-OAuth connection returns a validation error.
160
162