@superglue/cli 1.1.126 → 1.1.127

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.126",
4
+ "version": "1.1.127",
5
5
  "author": {
6
6
  "name": "superglue",
7
7
  "email": "hello@superglue.cloud"
package/dist/cli.js CHANGED
@@ -1714,7 +1714,7 @@ ${o}`;break;case"retry":CH(o)&&(r[i]=o);break;case"id":bH(o)&&(r[i]=o);break;cas
1714
1714
  `);t.stack=r?`${r}
1715
1715
  ${o}`:i.stack}V.exports.fetch=function(e,r=void 0){return E_e(e,r).catch(n=>{throw NH?xH(n,NH):n&&typeof n=="object"&&Error.captureStackTrace(n,V.exports.fetch),n})};V.exports.Headers=Ha().Headers;V.exports.Response=cd().Response;V.exports.Request=bu().Request;V.exports.FormData=uh().FormData;var{setGlobalOrigin:I_e,getGlobalOrigin:C_e}=tS();V.exports.setGlobalOrigin=I_e;V.exports.getGlobalOrigin=C_e;var{CacheStorage:b_e}=Eq(),{kConstruct:S_e}=Fe();V.exports.caches=new b_e(S_e);var{deleteCookie:B_e,getCookies:Q_e,getSetCookies:w_e,setCookie:v_e,parseCookie:__e}=Rq();V.exports.deleteCookie=B_e;V.exports.getCookies=Q_e;V.exports.getSetCookies=w_e;V.exports.setCookie=v_e;V.exports.parseCookie=__e;var{parseMIMEType:D_e,serializeAMimeType:T_e}=cn();V.exports.parseMIMEType=D_e;V.exports.serializeAMimeType=T_e;var{CloseEvent:R_e,ErrorEvent:k_e,MessageEvent:N_e}=_m(),{WebSocket:O_e,ping:U_e}=lH();V.exports.WebSocket=O_e;V.exports.CloseEvent=R_e;V.exports.ErrorEvent=k_e;V.exports.MessageEvent=N_e;V.exports.ping=U_e;V.exports.WebSocketStream=yH().WebSocketStream;V.exports.WebSocketError=Rw().WebSocketError;V.exports.request=Id(Nu.request);V.exports.stream=Id(Nu.stream);V.exports.pipeline=Id(Nu.pipeline);V.exports.connect=Id(Nu.connect);V.exports.upgrade=Id(Nu.upgrade);V.exports.MockClient=a_e;V.exports.MockCallHistory=c_e;V.exports.MockCallHistoryLog=u_e;V.exports.MockPool=A_e;V.exports.MockAgent=l_e;V.exports.SnapshotAgent=d_e;V.exports.mockErrors=f_e;var{EventSource:M_e}=kH();V.exports.EventSource=M_e;function x_e(){globalThis.fetch=V.exports.fetch,globalThis.Headers=V.exports.Headers,globalThis.Response=V.exports.Response,globalThis.Request=V.exports.Request,globalThis.FormData=V.exports.FormData,globalThis.WebSocket=V.exports.WebSocket,globalThis.CloseEvent=V.exports.CloseEvent,globalThis.ErrorEvent=V.exports.ErrorEvent,globalThis.MessageEvent=V.exports.MessageEvent,globalThis.EventSource=V.exports.EventSource}V.exports.install=x_e});var FH=h(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});Uu.SuperglueClient=Uu.SuperglueHttpError=void 0;var Ou=qr(),Fo=SC(),L_e=ZC(),P_e=ZM(),F_e=jn(),$o=Sc(),$_e=jf(),bd=14400*1e3,Cd;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:t}=LH();Cd=new t({headersTimeout:bd,bodyTimeout:bd})}catch{}function PH(t){if(t?.aborted)throw t.reason??new DOMException("Aborted","AbortError")}var jm=class extends Error{constructor(e,r,n,i){super(e),this.status=r,this.code=n,this.details=i,this.name="SuperglueHttpError"}};Uu.SuperglueHttpError=jm;var xw=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 L_e.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;PH(r);let o=await this.refreshToken();return PH(r),!o||o===n?i:(i.body?.cancel(),e(o))}isInfrastructureError(e){return(0,F_e.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 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=A=>{let d={Authorization:`Bearer ${A}`,...i};return a&&!c&&e!=="GET"&&(d["Content-Type"]="application/json"),fetch(s,{...o,method:e,headers:d,body:a?c?n:JSON.stringify(n):void 0,signal:o?.signal??AbortSignal.timeout(bd),...Cd?{dispatcher:Cd}:{}})},l;try{l=await this.fetchWithAuthRetry(u,o?.signal)}catch(A){throw this.isInfrastructureError(A)&&this.onInfrastructureError?.(),A}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,files:n.map(({fileName:l,contentType:A,contentLength:d})=>({fileName:l,contentLength:d,...A?{contentType:A}:{}}))})).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,A)=>{let d=n[A],f=await fetch(l.uploadUrl,{method:"PUT",body:d.content,headers:d.contentType?{"Content-Type":d.contentType}:void 0,signal:AbortSignal.timeout(Math.min(bd,l.expiresIn*1e3))});if(!f.ok)throw new Error(`Upload failed for ${d.fileName}: ${f.status} ${f.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(A=>[A.id,A]))}catch(l){c=new Map(a.map(A=>[A,{id:A,fileName:n[o.findIndex(d=>d.id===A)]?.fileName||A,contentLength:n[o.findIndex(d=>d.id===A)]?.contentLength||0,status:"failed",error:l instanceof Error?l.message:String(l)}]))}let u=o.map((l,A)=>{let d=s[A],f=n[A];return d.status==="rejected"?{id:l.id,fileName:f.fileName,contentLength:f.contentLength,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)}:c.get(l.id)||{id:l.id,fileName:f.fileName,contentLength:f.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 jm(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(bd),...Cd?{dispatcher:Cd}:{}}),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,P_e.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 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,options:s,runId:a,systemIds:c,createRun:u,parentToolId:l,stepIndex:A,stepId:d,signal:f,stream:g}){let I={step:e,payload:r,files:n,previousResults:i,credentials:o,options:s,runId:a,systemIds:c,createRun:u,parentToolId:l,stepIndex:A,stepId:d};return g?this.streamRequest("/v1/tools/step/run",I,f):this.restRequest("POST","/v1/tools/step/run",I,void 0,f?{signal:f}: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:A,signal:d,stream:f}){let g={outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:u,parentToolId:l,stepId:A};return f?this.streamRequest("/v1/tools/transform/run",g,d):this.restRequest("POST","/v1/tools/transform/run",g,void 0,d?{signal:d}: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:A,draftId:d}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:(0,$o.toUTCISOString)(c,"run.startedAt"),completedAt:(0,$o.toUTCISOString)(u,"run.completedAt"),executionKind:l,parentToolId:A,draftId:d})}async checkRunLimit(){return(await this.restRequest("POST","/v1/runs/check-limit")).data}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:Ou.RunStatus.RUNNING,success:Ou.RunStatus.SUCCESS,failed:Ou.RunStatus.FAILED,aborted:Ou.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:r[e.status]??Ou.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??Ou.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,$o.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,$o.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,$o.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,$o.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e={}){let r=(0,Fo.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,$o.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,$o.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&r.set("to",e.to instanceof Date?(0,$o.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,Fo.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,Fo.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 listSchedules(e={}){let r=(0,Fo.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,Fo.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,$_e.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 listCredentials(e={}){let r=(0,Fo.createListQueryParams)(e);e.systemId!==void 0&&r.set("systemId",e.systemId);let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/credentials${n}`)}async listAllCredentials(e={}){return(0,Fo.listAllPages)((r,n)=>this.listCredentials({...e,page:r,limit:n}))}async createCredentials(e){return(await this.restRequest("POST","/v1/credentials",e)).data}async replaceCredentials(e,r){return(await this.restRequest("PUT",`/v1/credentials/${encodeURIComponent(e)}`,{credentials:r})).data}async updateCredentials(e,r){return(await this.restRequest("PATCH",`/v1/credentials/${encodeURIComponent(e)}`,r)).data}async deleteCredentials(e){await this.restRequest("DELETE",`/v1/credentials/${encodeURIComponent(e)}`)}async setDefaultCredentials(e){await this.restRequest("POST",`/v1/credentials/${encodeURIComponent(e)}/default`)}async listSystems(e={}){let r=(0,Fo.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/systems${n}`)}async listAllSystems(e={}){return(0,Fo.listAllPages)((r,n)=>this.listSystems({...e,page:r,limit:n}))}async getSystem(e){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}`)).data}async createSystem(e){return(await this.restRequest("POST","/v1/systems",e)).data}async updateSystem(e,r){return(await this.restRequest("PATCH",`/v1/systems/${encodeURIComponent(e)}`,r)).data}async deleteSystem(e){return await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}`),!0}async bulkDeleteSystems(e){return this.restRequest("POST","/v1/systems/bulk/delete",{ids:e})}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 searchSystemDocumentation(e,r){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/search`,{keywords:r})).data}async triggerSystemDocumentationScrapeJob(e,r){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/scrape`,r)).data}async fetchOpenApiSpec(e,r,n){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/openapi`,{url:r,link:n?.link})).data}async uploadSystemDocumentationFiles(e,r,n){let i=await this.uploadFiles(r,{process:!0}),o=i.flatMap(s=>s.status==="uploaded"?[s.id]:[]);if(o.length>0)try{await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/files`,{fileIds:o,link:n?.link!==!1})}catch(s){throw await Promise.all(o.map(a=>this.deleteFileUpload(a).catch(()=>{}))),s}if(!n?.settle){let s=i.filter(a=>a.status==="failed");if(s.length>0)throw new Error(s.map(a=>a.error).join("; "))}return i}async listSystemDocumentationFiles(e,r){let n=new URLSearchParams;r?.length&&n.set("fileIds",r.join(","));let i=n.size>0?`?${n.toString()}`:"";return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files${i}`)).data}async getSystemDocumentationFileContent(e,r,n){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(r)}/content?processed=${n.processed}`)).data}async deleteSystemDocumentationFile(e,r){await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(r)}`)}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}}}};Uu.SuperglueClient=xw});var jH=h(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.UnquotedKeyStrategy=nt.TripleQuoteStrategy=nt.TrailingCommaStrategy=nt.SingleQuoteStrategy=nt.PythonLiteralStrategy=nt.CommentStrategy=nt.ResilientJsonParser=nt.RepairStrategy=void 0;nt.parseJsonResilient=j_e;nt.parseJSON=q_e;nt.isValidJson=H_e;nt.prettyPrintJson=G_e;nt.minifyJson=V_e;var Un=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};nt.RepairStrategy=Un;var qm=class extends Un{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")}"`})}};nt.TripleQuoteStrategy=qm;var Hm=class extends Un{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")}};nt.PythonLiteralStrategy=Hm;var Gm=class extends Un{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")}};nt.TrailingCommaStrategy=Gm;var Vm=class extends Un{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}};nt.SingleQuoteStrategy=Vm;var zm=class extends Un{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')}};nt.UnquotedKeyStrategy=zm;var Ym=class extends Un{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}};nt.CommentStrategy=Ym;var Lw=class extends Un{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`
1716
1716
  `: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}},Pw=class extends Un{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}},Mu=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 qm,new Vm,new Lw,new Pw,new Hm,new Gm,new zm,new Ym]}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)}};nt.ResilientJsonParser=Mu;var $H=new Mu;function j_e(t,e){return(e?new Mu(e):$H).parse(t)}function q_e(t){let e=$H.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 H_e(t){try{return JSON.parse(t),!0}catch{return!1}}function G_e(t,e=2){return JSON.stringify(t,null,e)}function V_e(t){let r=new Mu().parse(t);if(r.success)return JSON.stringify(r.data);throw new Error("Cannot minify invalid JSON")}});var Fr=h(te=>{"use strict";var z_e=te&&te.__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]})),ge=te&&te.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&z_e(e,t,r)};Object.defineProperty(te,"__esModule",{value:!0});te.SSELogSubscriptionManager=te.SuperglueHttpError=te.SuperglueClient=void 0;ge(NR(),te);ge(qR(),te);ge(aU(),te);ge(dU(),te);ge(fU(),te);ge(iA(),te);ge(NU(),te);ge(OU(),te);ge(UU(),te);ge(MU(),te);ge(SC(),te);ge(LU(),te);ge(PU(),te);ge(FU(),te);ge(wC(),te);ge(jU(),te);ge(HU(),te);ge(GU(),te);ge(zU(),te);ge(Fd(),te);ge(JU(),te);ge(WU(),te);ge(KU(),te);ge(tM(),te);ge(rM(),te);ge(cM(),te);ge(lM(),te);ge(dM(),te);ge(fM(),te);ge(BM(),te);ge(wM(),te);ge($C(),te);ge(LM(),te);ge(YC(),te);ge(jM(),te);ge(VM(),te);ge(YM(),te);ge(qr(),te);ge(jn(),te);ge(JM(),te);ge(WM(),te);ge(Dg(),te);ge(Sc(),te);ge(jf(),te);var qH=FH();Object.defineProperty(te,"SuperglueClient",{enumerable:!0,get:function(){return qH.SuperglueClient}});Object.defineProperty(te,"SuperglueHttpError",{enumerable:!0,get:function(){return qH.SuperglueHttpError}});var Y_e=ZC();Object.defineProperty(te,"SSELogSubscriptionManager",{enumerable:!0,get:function(){return Y_e.SSELogSubscriptionManager}});ge(jH(),te)});var Dy=require("commander");var mr=pe(require("fs")),VH=pe(require("os")),jo=pe(require("path")),Sd=pe(Fr()),HH=new Set(["runner","builder","admin"]),GH={output:{mode:"stdout",directory:".superglue/output"},preset:"admin"};function qo(t){let e=jo.join(process.cwd(),".superglue"),r=VH.homedir();if(!r)return e;let n=jo.join(r,".superglue");return t===!0?e:t===!1?n:mr.existsSync(jo.join(e,"config.json"))?e:n}function Fw(t){return jo.join(qo(t),"config.json")}function Jm(t){let e=Fw(t);if(!mr.existsSync(e))return{};try{return JSON.parse(mr.readFileSync(e,"utf-8"))}catch{return{}}}function xu(t){let e=Jm(),r=t.apiKey||(0,Sd.readProcessEnvironmentValue)("SUPERGLUE_API_KEY")||e.apiKey||"",n=t.endpoint||(0,Sd.readProcessEnvironmentValue)("SUPERGLUE_API_ENDPOINT")||e.endpoint||"https://api.superglue.cloud",i=(0,Sd.readProcessEnvironmentValue)("SUPERGLUE_WEB_ENDPOINT")||e.webEndpoint||n.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue"),o=(0,Sd.readProcessEnvironmentValue)("SUPERGLUE_CLI_PRESET"),s=o&&HH.has(o)?o:e.preset&&HH.has(e.preset)?e.preset:"admin";return{...GH,...e,apiKey:r,endpoint:n,webEndpoint:i,preset:s,output:{...GH.output,...e.output}}}function Wm(t,e){let r=qo(e);mr.existsSync(r)||mr.mkdirSync(r,{recursive:!0}),mr.writeFileSync(jo.join(r,"config.json"),JSON.stringify(t,null,2)+`
1717
- `,{mode:384})}function Zm(t,e){let r=jo.join(qo(e),"drafts");if(mr.existsSync(r)||mr.mkdirSync(r,{recursive:!0}),t.output.mode==="stdout+file"){let n=jo.resolve(t.output.directory);mr.existsSync(n)||mr.mkdirSync(n,{recursive:!0})}}var zw=pe(Fr());var $w=pe(require("readline"));var JH=require("child_process"),WH=require("util");var zH={name:"@superglue/cli",version:"1.1.126",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 W_e=(0,WH.promisify)(JH.exec),nr=zH.version;function YH(t){let e=t.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:t}}function Xm(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=YH(r[o]||"0"),a=YH(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 ey(){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 Km=null;function ZH(){ue()&&(Km=ey())}async function KH(){if(!(!ue()||!Km)){try{let t=new Promise(r=>{setTimeout(()=>r(null),2e3).unref()}),e=await Promise.race([Km,t]);e&&Xm(nr,e)<0&&(console.error(""),console.error(`${m.cyan}${m.bold} Update available: ${nr} \u2192 ${e}${m.reset}`),console.error(`${m.cyan} Run ${m.bold}sg update${m.reset}${m.cyan} to upgrade${m.reset}`),console.error(""))}catch{}Km=null}}async function XH(){let t=await ey();if(!t)return{success:!1,message:"Could not fetch latest version from npm"};if(Xm(nr,t)>=0)return{success:!0,message:`Already on latest version (${nr})`};try{return await W_e("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${nr} to ${t}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var ue=()=>process.argv.includes("--table")&&process.stdout.isTTY,mn=()=>process.argv.includes("--full"),m={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 eG(t,e){let r=e||t;return`\x1B]8;;${t}\x07${m.underline}${m.cyan}${r}${m.reset}\x1B]8;;\x07`}function tG(){if(!ue())return;let t=m.reset,e=m.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${nr}${t}`),console.log("")}function et(t){if(!ue())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 ${m.cyan}${e[r++%e.length]}${m.reset} ${n}`)},s=setInterval(o,80);return{update:a=>{n=a},log:a=>{i(),console.log(` ${m.dim}\u2502${m.reset} ${a}`),o()},stop:a=>{clearInterval(s),i(),a&&console.log(` ${a}`)}}}function re(t){ue()?ty(t):console.log(JSON.stringify(t,null,2))}function Qe(t,e){ue()?(console.log(` ${m.green}\u2713${m.reset} ${t}`),e&&ty(e,4)):console.log(JSON.stringify({success:!0,message:t,...e&&typeof e=="object"?e:{data:e}}))}function v(t,e){ue()?(console.error(` ${m.red}\u2717${m.reset} ${t}`),e&&ty(e,4)):console.error(JSON.stringify({success:!1,error:t,details:e}))}function rG(t){ue()&&console.log(` ${m.yellow}\u26A0${m.reset} ${t}`)}function zt(t){ue()&&console.log(` ${m.dim}${t}${m.reset}`)}function Ho(t){ue()&&(console.log(`
1717
+ `,{mode:384})}function Zm(t,e){let r=jo.join(qo(e),"drafts");if(mr.existsSync(r)||mr.mkdirSync(r,{recursive:!0}),t.output.mode==="stdout+file"){let n=jo.resolve(t.output.directory);mr.existsSync(n)||mr.mkdirSync(n,{recursive:!0})}}var zw=pe(Fr());var $w=pe(require("readline"));var JH=require("child_process"),WH=require("util");var zH={name:"@superglue/cli",version:"1.1.127",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 W_e=(0,WH.promisify)(JH.exec),nr=zH.version;function YH(t){let e=t.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:t}}function Xm(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=YH(r[o]||"0"),a=YH(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 ey(){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 Km=null;function ZH(){ue()&&(Km=ey())}async function KH(){if(!(!ue()||!Km)){try{let t=new Promise(r=>{setTimeout(()=>r(null),2e3).unref()}),e=await Promise.race([Km,t]);e&&Xm(nr,e)<0&&(console.error(""),console.error(`${m.cyan}${m.bold} Update available: ${nr} \u2192 ${e}${m.reset}`),console.error(`${m.cyan} Run ${m.bold}sg update${m.reset}${m.cyan} to upgrade${m.reset}`),console.error(""))}catch{}Km=null}}async function XH(){let t=await ey();if(!t)return{success:!1,message:"Could not fetch latest version from npm"};if(Xm(nr,t)>=0)return{success:!0,message:`Already on latest version (${nr})`};try{return await W_e("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${nr} to ${t}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var ue=()=>process.argv.includes("--table")&&process.stdout.isTTY,mn=()=>process.argv.includes("--full"),m={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 eG(t,e){let r=e||t;return`\x1B]8;;${t}\x07${m.underline}${m.cyan}${r}${m.reset}\x1B]8;;\x07`}function tG(){if(!ue())return;let t=m.reset,e=m.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${nr}${t}`),console.log("")}function et(t){if(!ue())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 ${m.cyan}${e[r++%e.length]}${m.reset} ${n}`)},s=setInterval(o,80);return{update:a=>{n=a},log:a=>{i(),console.log(` ${m.dim}\u2502${m.reset} ${a}`),o()},stop:a=>{clearInterval(s),i(),a&&console.log(` ${a}`)}}}function re(t){ue()?ty(t):console.log(JSON.stringify(t,null,2))}function Qe(t,e){ue()?(console.log(` ${m.green}\u2713${m.reset} ${t}`),e&&ty(e,4)):console.log(JSON.stringify({success:!0,message:t,...e&&typeof e=="object"?e:{data:e}}))}function v(t,e){ue()?(console.error(` ${m.red}\u2717${m.reset} ${t}`),e&&ty(e,4)):console.error(JSON.stringify({success:!1,error:t,details:e}))}function rG(t){ue()&&console.log(` ${m.yellow}\u26A0${m.reset} ${t}`)}function zt(t){ue()&&console.log(` ${m.dim}${t}${m.reset}`)}function Ho(t){ue()&&(console.log(`
1718
1718
  ${m.bold}${m.cyan}${t}${m.reset}`),console.log(` ${m.dim}${"\u2500".repeat(t.length)}${m.reset}`))}function io(t,e,r){if(!ue()){console.log(JSON.stringify({success:!0,total:r?.total??t.length,items:t}));return}if(t.length===0){console.log(`
1719
1719
  ${m.dim}0 results${m.reset}
1720
1720
  `);return}let n=e||Object.keys(t[0]),i=mn()?1/0:60,o=n.map(l=>Math.min(i,Math.max(l.length,...t.map(A=>String(A[l]??"").replace(/[\n\r]+/g," ").trim().length))));console.log("");let s=n.map((l,A)=>`${m.bold}${m.cyan}${l.toUpperCase().padEnd(o[A])}${m.reset}`).join(" ");console.log(` ${s}`);let a=o.map(l=>`${m.dim}${"\u2500".repeat(l)}${m.reset}`).join(`${m.dim}\u2500\u2500${m.reset}`);console.log(` ${a}`);for(let l of t){let A=n.map((d,f)=>{let g=String(l[d]??"").replace(/[\n\r]+/g," ").trim();if(g.length>i){let b=`\u2026 (${g.length})`;g=g.slice(0,Math.max(0,i-b.length))+`${m.dim}${b}${m.reset}`}return d==="status"?`${{success:m.green,running:m.yellow,failed:m.red,aborted:m.red,error:m.red,pending:m.dim}[g.toLowerCase()]||""}${g.padEnd(o[f])}${m.reset}`:g.padEnd(o[f])}).join(" ");console.log(` ${A}`)}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(`
@@ -1906,12 +1906,12 @@ Quick Reference:
1906
1906
  sg run download <runId> <fileKey> Download a specific file artifact
1907
1907
 
1908
1908
  Output: JSON by default. Use --table for human-readable, --full to disable truncation.
1909
- `);sV(n,e),aV(n,e),cV(n,e)}var wy=pe(require("fs"));function zu(t,e=!1){let r={id:t.id,toolId:t.toolId,status:t.enabled?"active":"inactive",cronExpression:t.cronExpression,timezone:t.timezone,nextRunAt:t.nextRunAt.toISOString()};return e?{...r,payload:t.payload||{},options:t.options||{},createdByUserId:t.createdByUserId,lastRunAt:t.lastRunAt?.toISOString(),createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString()}:r}function AV(t){return{active:t.filter(e=>e.enabled).length,inactive:t.filter(e=>!e.enabled).length}}function Qy(t,e){let r;try{r=JSON.parse(t)}catch(n){throw new Error(`Invalid ${e} JSON: ${n.message}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`${e} must be a JSON object`);return r}function NDe(t,e){let r=t.trim().startsWith("{")?t:wy.readFileSync(t,"utf-8");return Qy(r,e)}function vy({inline:t,file:e,label:r}){if(t!==void 0&&e!==void 0)throw new Error(`Use either --${r} or --${r}-file, not both`);if(e!==void 0)return Qy(wy.readFileSync(e,"utf-8"),r);if(t!==void 0)return Qy(t,r)}function lV({value:t,name:e,min:r,max:n}){let i=Number(t);if(!Number.isInteger(i)||i<r||n!==void 0&&i>n){let o=n===void 0?`at least ${r}`:`between ${r} and ${n}`;throw new Error(`--${e} must be an integer ${o}`)}return i}function nv(t){return t.options!==void 0||t.optionsFile!==void 0||t.clearOptions||t.webhookUrl!==void 0||t.toolChain!==void 0||t.clearWebhook||t.retries!==void 0||t.timeout!==void 0}function _y(t,e){if(!nv(t))return;if(t.options!==void 0&&t.optionsFile!==void 0)throw new Error("Use either --options or --options-file, not both");if(t.webhookUrl!==void 0&&t.toolChain!==void 0)throw new Error("Use either --webhook-url or --tool-chain, not both");if(t.clearWebhook&&(t.webhookUrl!==void 0||t.toolChain!==void 0))throw new Error("Use --clear-webhook without --webhook-url or --tool-chain");let r=t.clearOptions?{}:{...e||{}};return t.options!==void 0&&(r=NDe(t.options,"options")),t.optionsFile!==void 0&&(r=Qy(wy.readFileSync(t.optionsFile,"utf-8"),"options")),t.retries!==void 0&&(r.retries=lV({value:t.retries,name:"retries",min:0,max:10})),t.timeout!==void 0&&(r.timeout=lV({value:t.timeout,name:"timeout",min:100})),t.clearWebhook?delete r.webhookUrl:t.toolChain!==void 0?r.webhookUrl=`tool:${t.toolChain}`:t.webhookUrl!==void 0&&(r.webhookUrl=t.webhookUrl),r}function Yu(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("fetch failed")?["Could not reach the configured superglue API endpoint.","Set SUPERGLUE_API_ENDPOINT or pass --endpoint, then run `sg login` or provide an org-scoped API key for headless auth."].join(" "):e}function dV(t,e){t.command("create").description("Create a schedule for a saved tool").requiredOption("--tool <id>","Saved tool ID to schedule").requiredOption("--cron <expression>","5-field cron expression").option("--timezone <name>","IANA timezone, defaults to the local timezone").option("--disabled","Create the schedule disabled").option("--payload <json>","JSON object payload passed to each scheduled run").option("--payload-file <path>","JSON file payload passed to each scheduled run").option("--options <json-or-file>","Request options JSON object or file path").option("--options-file <path>","Request options JSON file").option("--webhook-url <url>","Webhook URL called after successful execution").option("--tool-chain <toolId>","Tool ID to run after successful execution").option("--retries <n>","Retry count, 0-10").option("--timeout <ms>","Request timeout in milliseconds").addHelpText("after",`
1909
+ `);sV(n,e),aV(n,e),cV(n,e)}var wy=pe(require("fs"));function zu(t,e=!1){let r={id:t.id,toolId:t.toolId,status:t.enabled?"active":"inactive",cronExpression:t.cronExpression,timezone:t.timezone,nextRunAt:t.nextRunAt.toISOString()};return e?{...r,payload:t.payload||{},options:t.options||{},createdByUserId:t.createdByUserId,lastRunAt:t.lastRunAt?.toISOString(),createdAt:t.createdAt.toISOString(),updatedAt:t.updatedAt.toISOString()}:r}function AV(t){return{active:t.filter(e=>e.enabled).length,inactive:t.filter(e=>!e.enabled).length}}function Qy(t,e){let r;try{r=JSON.parse(t)}catch(n){throw new Error(`Invalid ${e} JSON: ${n.message}`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`${e} must be a JSON object`);return r}function NDe(t,e){let r=t.trim().startsWith("{")?t:wy.readFileSync(t,"utf-8");return Qy(r,e)}function vy({inline:t,file:e,label:r}){if(t!==void 0&&e!==void 0)throw new Error(`Use either --${r} or --${r}-file, not both`);if(e!==void 0)return Qy(wy.readFileSync(e,"utf-8"),r);if(t!==void 0)return Qy(t,r)}function lV({value:t,name:e,min:r,max:n}){let i=Number(t);if(!Number.isInteger(i)||i<r||n!==void 0&&i>n){let o=n===void 0?`at least ${r}`:`between ${r} and ${n}`;throw new Error(`--${e} must be an integer ${o}`)}return i}function nv(t){return t.options!==void 0||t.optionsFile!==void 0||t.clearOptions||t.webhookUrl!==void 0||t.toolChain!==void 0||t.clearWebhook||t.retries!==void 0||t.timeout!==void 0}function _y(t,e){if(!nv(t))return;if(t.options!==void 0&&t.optionsFile!==void 0)throw new Error("Use either --options or --options-file, not both");if(t.webhookUrl!==void 0&&t.toolChain!==void 0)throw new Error("Use either --webhook-url or --tool-chain, not both");if(t.clearWebhook&&(t.webhookUrl!==void 0||t.toolChain!==void 0))throw new Error("Use --clear-webhook without --webhook-url or --tool-chain");let r=t.clearOptions?{}:{...e||{}};return t.options!==void 0&&(r=NDe(t.options,"options")),t.optionsFile!==void 0&&(r=Qy(wy.readFileSync(t.optionsFile,"utf-8"),"options")),t.retries!==void 0&&(r.retries=lV({value:t.retries,name:"retries",min:0,max:3})),t.timeout!==void 0&&(r.timeout=lV({value:t.timeout,name:"timeout",min:100})),t.clearWebhook?delete r.webhookUrl:t.toolChain!==void 0?r.webhookUrl=`tool:${t.toolChain}`:t.webhookUrl!==void 0&&(r.webhookUrl=t.webhookUrl),r}function Yu(t){let e=t instanceof Error?t.message:String(t);return e.toLowerCase().includes("fetch failed")?["Could not reach the configured superglue API endpoint.","Set SUPERGLUE_API_ENDPOINT or pass --endpoint, then run `sg login` or provide an org-scoped API key for headless auth."].join(" "):e}function dV(t,e){t.command("create").description("Create a schedule for a saved tool").requiredOption("--tool <id>","Saved tool ID to schedule").requiredOption("--cron <expression>","5-field cron expression").option("--timezone <name>","IANA timezone, defaults to the local timezone").option("--disabled","Create the schedule disabled").option("--payload <json>","JSON object payload passed to each scheduled run").option("--payload-file <path>","JSON file payload passed to each scheduled run").option("--options <json-or-file>","Request options JSON object or file path").option("--options-file <path>","Request options JSON file").option("--webhook-url <url>","Webhook URL called after successful execution").option("--tool-chain <toolId>","Tool ID to run after successful execution").option("--retries <n>","Retry count, 0-3").option("--timeout <ms>","Request timeout in milliseconds").addHelpText("after",`
1910
1910
  Examples:
1911
1911
  sg schedule create --tool daily_report --cron "0 9 * * 1-5" --timezone UTC
1912
1912
  sg schedule create --tool sync_crm --cron "*/15 * * * *" --timezone Europe/Berlin --payload '{"limit":100}'
1913
1913
  sg schedule create --tool import_orders --cron "0 * * * *" --timezone UTC --tool-chain notify_team
1914
- `).action(async r=>{let{client:n}=e();try{let i=vy({inline:r.payload,file:r.payloadFile,label:"payload"}),o=_y(r),s=await n.createToolSchedule(r.tool,{cronExpression:r.cron,timezone:r.timezone,enabled:!r.disabled,payload:i,options:o});ue()?Qe(`Schedule created: ${m.bold}${s.id}${m.reset}`,{toolId:s.toolId,status:s.enabled?"active":"inactive",nextRunAt:s.nextRunAt.toISOString()}):re({success:!0,schedule:zu(s,!0)})}catch(i){v(Yu(i)),process.exit(1)}})}function fV(t,e){t.command("edit").description("Edit an existing schedule").requiredOption("--tool <id>","Saved tool ID that owns the schedule").requiredOption("--id <id>","Schedule ID").option("--cron <expression>","New 5-field cron expression").option("--timezone <name>","New IANA timezone").option("--enabled","Enable the schedule").option("--disabled","Disable the schedule").option("--payload <json>","Replacement JSON object payload").option("--payload-file <path>","Replacement JSON payload file").option("--options <json-or-file>","Replacement request options JSON object or file path").option("--options-file <path>","Replacement request options JSON file").option("--clear-options","Replace request options with an empty object").option("--webhook-url <url>","Set webhook URL called after successful execution").option("--tool-chain <toolId>","Set tool ID to run after successful execution").option("--clear-webhook","Remove webhook/tool-chain success action from options").option("--retries <n>","Set retry count, 0-10").option("--timeout <ms>","Set request timeout in milliseconds").addHelpText("after",`
1914
+ `).action(async r=>{let{client:n}=e();try{let i=vy({inline:r.payload,file:r.payloadFile,label:"payload"}),o=_y(r),s=await n.createToolSchedule(r.tool,{cronExpression:r.cron,timezone:r.timezone,enabled:!r.disabled,payload:i,options:o});ue()?Qe(`Schedule created: ${m.bold}${s.id}${m.reset}`,{toolId:s.toolId,status:s.enabled?"active":"inactive",nextRunAt:s.nextRunAt.toISOString()}):re({success:!0,schedule:zu(s,!0)})}catch(i){v(Yu(i)),process.exit(1)}})}function fV(t,e){t.command("edit").description("Edit an existing schedule").requiredOption("--tool <id>","Saved tool ID that owns the schedule").requiredOption("--id <id>","Schedule ID").option("--cron <expression>","New 5-field cron expression").option("--timezone <name>","New IANA timezone").option("--enabled","Enable the schedule").option("--disabled","Disable the schedule").option("--payload <json>","Replacement JSON object payload").option("--payload-file <path>","Replacement JSON payload file").option("--options <json-or-file>","Replacement request options JSON object or file path").option("--options-file <path>","Replacement request options JSON file").option("--clear-options","Replace request options with an empty object").option("--webhook-url <url>","Set webhook URL called after successful execution").option("--tool-chain <toolId>","Set tool ID to run after successful execution").option("--clear-webhook","Remove webhook/tool-chain success action from options").option("--retries <n>","Set retry count, 0-3").option("--timeout <ms>","Set request timeout in milliseconds").addHelpText("after",`
1915
1915
  Examples:
1916
1916
  sg schedule edit --tool daily_report --id <scheduleId> --disabled
1917
1917
  sg schedule edit --tool daily_report --id <scheduleId> --cron "0 8 * * *" --timezone UTC
@@ -179,16 +179,16 @@ Set step-level `failureBehavior: "continue"` to keep the workflow running after
179
179
 
180
180
  **Connection/server errors:**
181
181
 
182
- - Default 5 retries, configurable via `retries` on the step
183
- - Retries on fetch-level errors (network/DNS/abort except timeout) and on 5xx responses
184
- - Fixed delay between retries (default 1000ms, configurable via `retryDelay`)
182
+ - Default 1 retry per request. Steps and direct system calls have no retry setting; schedule `options.retries` (0-3) applies to every request in the scheduled run
183
+ - Retries on fetch-level connection failures (reset, TLS, DNS) and on 5xx responses. Other 4xx responses fail immediately
184
+ - Fixed 1000ms delay between retries
185
185
 
186
186
  **Rate limiting (429):**
187
187
 
188
- - Counts against the same retry budget as 5xx/network errors
189
- - Respects `Retry-After` header (seconds or HTTP-date)
190
- - Without header: exponential backoff `10^n * 1000ms + jitter` (capped at 1hr per wait)
191
- - Total wait across all 429 retries capped at `MAX_RATE_LIMIT_WAIT_MS` (1hr)
188
+ - Separate from the `retries` budget; applies even when `retries` is 0
189
+ - Respects `Retry-After` header (seconds or HTTP-date) on the first retry
190
+ - Otherwise exponential backoff `4^n * 1000ms + jitter` (4s, 16s, 64s, 256s, 1024s)
191
+ - Fails once the total 429 wait would exceed `MAX_RATE_LIMIT_WAIT_MS` (1hr)
192
192
 
193
193
  **Timeouts:** Request timeout aborts the fetch and throws immediately — timeouts are not retried.
194
194
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superglue/cli",
3
- "version": "1.1.126",
3
+ "version": "1.1.127",
4
4
  "bin": {
5
5
  "sg": "./dist/cli.js"
6
6
  },
@@ -179,16 +179,16 @@ Set step-level `failureBehavior: "continue"` to keep the workflow running after
179
179
 
180
180
  **Connection/server errors:**
181
181
 
182
- - Default 5 retries, configurable via `retries` on the step
183
- - Retries on fetch-level errors (network/DNS/abort except timeout) and on 5xx responses
184
- - Fixed delay between retries (default 1000ms, configurable via `retryDelay`)
182
+ - Default 1 retry per request. Steps and direct system calls have no retry setting; schedule `options.retries` (0-3) applies to every request in the scheduled run
183
+ - Retries on fetch-level connection failures (reset, TLS, DNS) and on 5xx responses. Other 4xx responses fail immediately
184
+ - Fixed 1000ms delay between retries
185
185
 
186
186
  **Rate limiting (429):**
187
187
 
188
- - Counts against the same retry budget as 5xx/network errors
189
- - Respects `Retry-After` header (seconds or HTTP-date)
190
- - Without header: exponential backoff `10^n * 1000ms + jitter` (capped at 1hr per wait)
191
- - Total wait across all 429 retries capped at `MAX_RATE_LIMIT_WAIT_MS` (1hr)
188
+ - Separate from the `retries` budget; applies even when `retries` is 0
189
+ - Respects `Retry-After` header (seconds or HTTP-date) on the first retry
190
+ - Otherwise exponential backoff `4^n * 1000ms + jitter` (4s, 16s, 64s, 256s, 1024s)
191
+ - Fails once the total 429 wait would exceed `MAX_RATE_LIMIT_WAIT_MS` (1hr)
192
192
 
193
193
  **Timeouts:** Request timeout aborts the fetch and throws immediately — timeouts are not retried.
194
194