@superglue/cli 1.1.19 → 1.1.20
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.
- package/.claude-plugin/plugin.json +1 -1
- package/dist/cli.js +3 -3
- package/package.json +1 -1
|
@@ -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.
|
|
4
|
+
"version": "1.1.20",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "superglue",
|
|
7
7
|
"email": "hello@superglue.cloud"
|
package/dist/cli.js
CHANGED
|
@@ -1088,8 +1088,8 @@ attempted value: ${B}
|
|
|
1088
1088
|
};
|
|
1089
1089
|
}
|
|
1090
1090
|
`}),ju=ne(o=>{"use strict";var i=o&&o.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(o,"__esModule",{value:!0}),o.encryptCliApiKey=g,o.decryptCliApiKey=p;var n=i(require("crypto"));function g(a,c,l){if(!l)throw new Error("Server secret required for CLI OAuth encryption");let y=n.default.createHash("sha256").update(`${l}:cli-oauth:${c}`).digest(),b=n.default.randomBytes(12),h=n.default.createCipheriv("aes-256-gcm",y,b),w=h.update(a,"utf8","hex");w+=h.final("hex");let z=h.getAuthTag().toString("hex");return`${b.toString("hex")}:${w}:${z}`}function p(a,c,l){if(!l)return null;try{let[y,b,h]=a.split(":");if(!y||!b||!h)return null;let w=n.default.createHash("sha256").update(`${l}:cli-oauth:${c}`).digest(),z=Buffer.from(y,"hex"),_=Buffer.from(h,"hex"),O=n.default.createDecipheriv("aes-256-gcm",w,z);O.setAuthTag(_);let $=O.update(b,"hex","utf8");return $+=O.final("utf8"),$}catch{return null}}}),Yr=ne(o=>{"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.SSELogSubscriptionManager=void 0;var i=tt(),n=class{constructor(g,p){this.controllers=new Map,this.apiEndpoint=g.replace(/\/$/,""),this.apiKey=p}async subscribeToLogs(g={}){let p=new AbortController,a=Math.random().toString(36).substring(2,15);this.controllers.set(a,p);let c=new URLSearchParams;g.traceId&&c.set("traceId",g.traceId);let l=`${this.apiEndpoint}/v1/logs/stream${c.toString()?`?${c}`:""}`,y=()=>this.controllers.delete(a),b=async(h=0)=>{try{let w=await fetch(l,{headers:{Authorization:`Bearer ${this.apiKey}`},signal:p.signal});if(!w.ok||!w.body)throw new Error(`SSE connection failed: ${w.status}`);h=0;let z=w.body.getReader(),_=new TextDecoder,O="";for(;;){let{done:$,value:C}=await z.read();if($)break;O+=_.decode(C,{stream:!0});let v=O.split(`
|
|
1091
|
-
`);O=v.pop()||"";for(let A of v)if(A.startsWith("data: "))try{let k=JSON.parse(A.slice(6));if(k.timestamp=new Date(k.timestamp),g.traceId&&k.traceId!==g.traceId||!g.includeDebug&&k.level===i.LogLevel.DEBUG)continue;g.onLog?.(k)}catch{}}if(!p.signal.aborted){let $=Math.min(2e3*Math.pow(2,h),3e4);await new Promise(C=>setTimeout(C,$)),p.signal.aborted||b(h+1);return}y(),g.onComplete?.()}catch(w){if(w.name==="AbortError"){y();return}if(h<10&&!p.signal.aborted){let z=Math.min(2e3*Math.pow(2,h),3e4);await new Promise(_=>setTimeout(_,z)),p.signal.aborted||b(h+1);return}y(),g.onError?.(w)}};return b(),{unsubscribe:()=>{let h=this.controllers.get(a);h&&(h.abort(),this.controllers.delete(a))}}}async disconnect(){for(let[g,p]of this.controllers)p.abort();this.controllers.clear()}};o.SSELogSubscriptionManager=n}),Su=ne(o=>{"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.SuperglueClient=void 0;var i=tt(),n=Yr(),g=Gr(),p=class{constructor({apiKey:a,apiEndpoint:c,onInfrastructureError:l}){this.apiKey=a,this.apiEndpoint=c??"https://api.superglue.cloud",this.sseManager=new n.SSELogSubscriptionManager(this.apiEndpoint,this.apiKey),this.onInfrastructureError=l}isInfrastructureError(a){return(0,g.isAbortError)(a)?!1:!!(a instanceof TypeError&&a.message.toLowerCase().includes("fetch")||a instanceof Error&&a.name==="TimeoutError")}async restRequest(a,c,l,y,b){let h=`${this.apiEndpoint.replace(/\/$/,"")}${c}`,w={Authorization:`Bearer ${this.apiKey}`,...y};l&&a!=="GET"&&(w["Content-Type"]="application/json");let z;try{z=await fetch(h,{method:a,headers:w,body:l?JSON.stringify(l):void 0,signal:b?.signal})}catch(O){throw this.isInfrastructureError(O)&&this.onInfrastructureError?.(),O}if(!z.ok){z.status>=500&&this.onInfrastructureError?.();let O=await z.text(),$=`HTTP ${z.status}: ${O}`;try{let C=JSON.parse(O).error;typeof C=="string"?$=C:C&&typeof C=="object"&&($=C.message||JSON.stringify(C))}catch{}throw new Error($)}let _=await z.text();if(_)return JSON.parse(_)}async subscribeToLogsSSE(a={}){return this.sseManager.subscribeToLogs(a)}async disconnect(){await this.sseManager.disconnect()}async runTool(a){let c=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(a.toolId)}/run`,{inputs:a.payload,files:a.files,credentials:a.credentials,options:a.options,runId:a.runId});return{success:c.status==="success",data:c.data,error:c.error,tool:c.tool,stepResults:c.stepResults?.map(l=>({...l}))}}async runToolConfig(a){let c=a.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",l=await this.restRequest("POST",c,{tool:a.tool,payload:a.payload,files:a.files,credentials:a.credentials,options:a.options,runId:a.runId},a.traceId?{"X-Trace-Id":a.traceId}:void 0);return{success:l.status?l.status==="success":l.success??!1,data:l.data,error:l.error,tool:l.tool||a.tool,stepResults:l.stepResults?.map(y=>({...y}))||[]}}async abortToolExecution(a){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(a)}/cancel`)).runId}}async executeStep({step:a,payload:c,files:l,previousResults:y,credentials:b,options:h,runId:w,mode:z,systemIds:_}){return this.restRequest("POST","/v1/tools/step/run",{step:a,payload:c,files:l,previousResults:y,credentials:b,options:h,runId:w,mode:z,systemIds:_})}async abortStep(a){return this.restRequest("POST","/v1/tools/step/abort",{runId:a})}async executeTransformOnly({outputTransform:a,outputSchema:c,inputSchema:l,payload:y,files:b,stepResults:h,responseFilters:w,options:z,runId:_}){return this.restRequest("POST","/v1/tools/transform/run",{outputTransform:a,outputSchema:c,inputSchema:l,payload:y,files:b,stepResults:h,responseFilters:w,options:z,runId:_})}async createRun({toolId:a,toolConfig:c,toolResult:l,stepResults:y,toolPayload:b,status:h,error:w,startedAt:z,completedAt:_}){return this.restRequest("POST","/v1/runs",{toolId:a,toolConfig:c,toolResult:l,stepResults:y,toolPayload:b,status:h,error:w,startedAt:z.toISOString(),completedAt:_.toISOString()})}async extract({file:a,envelope:c}){if(!a)throw new Error("File must be provided for extract.");let l=new FormData;l.append("file",a);let y=new URL(`${this.apiEndpoint.replace(/\/$/,"")}/v1/extract`);c&&y.searchParams.set("envelope","true");let b=y.toString(),h=await fetch(b,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:l});if(!h.ok){let w=await h.text(),z=`HTTP ${h.status}: ${w}`;try{let _=JSON.parse(w);_.error&&(z=_.error)}catch{}throw new Error(z)}return h.json()}mapOpenAPIRunToRun(a){let c={running:i.RunStatus.RUNNING,success:i.RunStatus.SUCCESS,failed:i.RunStatus.FAILED,aborted:i.RunStatus.ABORTED};return{runId:a.runId??a.id,toolId:a.toolId,tool:a.tool,status:c[a.status]??i.RunStatus.FAILED,toolPayload:a.toolPayload,data:a.data,toolResult:a.data,error:a.error,stepResults:a.stepResults,options:a.options,requestSource:a.requestSource,traceId:a.traceId,resultStorageUri:a.resultStorageUri,userId:a.userId,userEmail:a.userEmail,userName:a.userName,metadata:a.metadata}}async listRuns(a){let{limit:c=100,page:l=1,toolId:y,search:b,searchUserIds:h,includeTotal:w=!0,startedAfter:z,status:_,requestSources:O,userId:$,systemId:C,signal:v}=a??{},A=new URLSearchParams({limit:String(c),page:String(l)});y&&A.set("toolId",y),b?.trim()&&A.set("search",b.trim()),h&&h.length>0&&A.set("searchUserIds",h.join(",")),w||A.set("includeTotal","false"),z&&A.set("startedAfter",z instanceof Date?z.toISOString():z),_&&A.set("status",_),O&&O.length>0&&A.set("requestSources",O.join(",")),$&&A.set("userId",$),C&&A.set("systemId",C);let k=await this.restRequest("GET",`/v1/runs?${A.toString()}`,void 0,void 0,{signal:v});return{items:k.data.map(L=>this.mapOpenAPIRunToRun(L)),total:k.total,page:k.page,limit:k.limit,hasMore:k.hasMore}}async getRun(a){try{let c=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(a)}`);return this.mapOpenAPIRunToRun(c)}catch(c){if(c.message?.includes("404")||c.message?.includes("not found"))return null;throw c}}async getWorkflow(a){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(a)}`)}catch(c){if(c.message?.includes("404")||c.message?.includes("not found")||c.message?.includes("403")||c.message?.includes("not allowed"))return null;throw c}}async archiveWorkflow(a,c=!0){return this.upsertWorkflow(a,{archived:c})}async listWorkflows(a=10,c=0,l=!1){let y=Math.floor(c/a)+1,b=l?"&includeArchived=true":"",h=await this.restRequest("GET",`/v1/tools?limit=${a}&page=${y}${b}`);return{items:h.data,total:h.total}}async createWorkflow(a,c){return this.restRequest("POST","/v1/tools",{...c,id:a})}async updateWorkflow(a,c){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(a)}`,c)}async upsertWorkflow(a,c){return await this.getWorkflow(a)?this.updateWorkflow(a,c):this.createWorkflow(a,c)}async deleteWorkflow(a){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(a)}`),!0}catch(c){if(c.message?.includes("404"))return!1;throw c}}async renameWorkflow(a,c){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(a)}/rename`,{newId:c})}async listSystems(a=10,c=1,l){let y=new URLSearchParams({limit:String(a),page:String(c)});l?.mode&&y.set("mode",l.mode);let b=await this.restRequest("GET",`/v1/systems?${y.toString()}`);return{items:b.data,total:b.total}}async getSystem(a,c){let l=c?.environment?`?env=${c.environment}`:"";return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(a)}${l}`)).data}async createSystem(a){return(await this.restRequest("POST","/v1/systems",a)).data}async updateSystem(a,c,l){let y=l?.environment?`?env=${l.environment}`:"";return(await this.restRequest("PATCH",`/v1/systems/${encodeURIComponent(a)}${y}`,c)).data}async deleteSystem(a,c){let l=c?.environment?`?env=${c.environment}`:"";return await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(a)}${l}`),!0}async cacheOAuthSecret(a){return await this.restRequest("POST","/v1/oauth/secrets",a),!0}async getOAuthSecret(a){return(await this.restRequest("GET",`/v1/oauth/secrets/${encodeURIComponent(a)}`)).data}async getTemplateOAuthCredentials(a){return(await this.restRequest("GET",`/v1/oauth/templates/${encodeURIComponent(a)}/credentials`)).data}async searchSystemDocumentation(a,c){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(a)}/documentation/search`,{keywords:c})).data}async cacheOauthClientCredentials(a){return this.restRequest("POST","/v1/oauth/secrets",{uid:a.clientCredentialsUid,clientId:a.clientId,clientSecret:a.clientSecret})}async getOAuthClientCredentials(a){if(a.clientCredentialsUid)return(await this.restRequest("GET",`/v1/oauth/secrets/${encodeURIComponent(a.clientCredentialsUid)}`)).data;if(!a.templateId)throw new Error("No valid credentials source provided");return(await this.restRequest("GET",`/v1/oauth/templates/${encodeURIComponent(a.templateId)}/credentials`)).data}async getCliOAuthSecret(){return(await this.restRequest("GET","/v1/oauth/cli-secret")).data}async triggerSystemDocumentationScrapeJob(a,c){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(a)}/documentation/scrape`,c)).data}async fetchOpenApiSpec(a,c){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(a)}/documentation/openapi`,{url:c})).data}async createSystemFileUploadUrls(a,c){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(a)}/file-references`,{files:c.map(l=>({fileName:l.fileName,metadata:{contentType:l.contentType,contentLength:l.contentLength}}))})).data.files}async uploadSystemFileReferences(a,c){let l=await this.createSystemFileUploadUrls(a,c.map(y=>({fileName:y.fileName,contentType:y.contentType,contentLength:y.contentLength})));return await Promise.all(l.map(async(y,b)=>{let h=await fetch(y.uploadUrl,{method:"PUT",body:c[b].content,headers:c[b].contentType?{"Content-Type":c[b].contentType}:void 0});if(!h.ok)throw new Error(`Upload failed for ${c[b].fileName}: ${h.status} ${h.statusText}`)})),l.map((y,b)=>({id:y.id,fileName:c[b].fileName}))}async listSystemFileReferences(a){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(a)}/file-references`)).data}async deleteSystemFileReference(a,c){await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(a)}/file-references/${encodeURIComponent(c)}`)}async getFileReferenceContent(a){return(await this.restRequest("GET",`/v1/file-references/${encodeURIComponent(a)}?includeContent=true`)).data.content??null}async getTenantInfo(){return this.restRequest("GET","/v1/tenant-info")}async setTenantInfo(a){return this.restRequest("PUT","/v1/tenant-info",a)}async generatePortalLink(){try{return{success:!0,portalUrl:(await this.restRequest("POST","/v1/authenticate",{})).data.portalUrl}}catch(a){return{success:!1,error:a.message}}}};o.SuperglueClient=p}),Ou=io&&io.__createBinding||(Object.create?(function(o,i,n,g){g===void 0&&(g=n);var p=Object.getOwnPropertyDescriptor(i,n);(!p||("get"in p?!i.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return i[n]}}),Object.defineProperty(o,g,p)}):(function(o,i,n,g){g===void 0&&(g=n),o[g]=i[n]})),sa=io&&io.__exportStar||function(o,i){for(var n in o)n!=="default"&&!Object.prototype.hasOwnProperty.call(i,n)&&Ou(i,o,n)};Object.defineProperty(io,"__esModule",{value:!0});io.SSELogSubscriptionManager=io.SuperglueClient=void 0;sa(kl(),io);sa(gr(),io);sa(zl(),io);sa(ql(),io);sa(jl(),io);sa(Sl(),io);sa(tt(),io);sa(Gr(),io);sa(qu(),io);sa(ju(),io);var _u=Su();Object.defineProperty(io,"SuperglueClient",{enumerable:!0,get:function(){return _u.SuperglueClient}});var Eu=Yr();Object.defineProperty(io,"SSELogSubscriptionManager",{enumerable:!0,get:function(){return Eu.SSELogSubscriptionManager}})});var zi=require("commander");var Mo=Ee(require("fs")),os=Ee(require("os")),pa=Ee(require("path")),Xc=new Set(["runner","builder","admin"]),es={output:{mode:"stdout",directory:".superglue/output"},preset:"admin"};function Pa(o){let i=pa.join(process.cwd(),".superglue"),n=os.homedir();if(!n)return i;let g=pa.join(n,".superglue");return o===!0?i:o===!1?g:Mo.existsSync(pa.join(i,"config.json"))?i:g}function ml(o){return pa.join(Pa(o),"config.json")}function ll(){let o=ml();if(!Mo.existsSync(o))return{};try{return JSON.parse(Mo.readFileSync(o,"utf-8"))}catch{return{}}}function Di(o){let i=ll(),n=o.apiKey||process.env.SUPERGLUE_API_KEY||i.apiKey||"",g=o.endpoint||process.env.SUPERGLUE_API_ENDPOINT||i.endpoint||"https://api.superglue.cloud",p=process.env.SUPERGLUE_WEB_ENDPOINT||i.webEndpoint||g.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue"),a=process.env.SUPERGLUE_CLI_PRESET,c=a&&Xc.has(a)?a:i.preset&&Xc.has(i.preset)?i.preset:"admin";return{...es,...i,apiKey:n,endpoint:g,webEndpoint:p,preset:c,output:{...es.output,...i.output}}}function as(o,i){let n=Pa(i);Mo.existsSync(n)||Mo.mkdirSync(n,{recursive:!0}),Mo.writeFileSync(pa.join(n,"config.json"),JSON.stringify(o,null,2)+`
|
|
1092
|
-
`,{mode:384})}function ts(o,i){let n=pa.join(Pa(i),"drafts");if(Mo.existsSync(n)||Mo.mkdirSync(n,{recursive:!0}),o.output.mode==="stdout+file"){let g=pa.resolve(o.output.directory);Mo.existsSync(g)||Mo.mkdirSync(g,{recursive:!0})}}var ln=Ee(ra());var mc=Ee(require("readline"));var Qr=require("child_process"),Xr=require("util");var Zr={name:"@superglue/cli",version:"1.1.
|
|
1091
|
+
`);O=v.pop()||"";for(let A of v)if(A.startsWith("data: "))try{let k=JSON.parse(A.slice(6));if(k.timestamp=new Date(k.timestamp),g.traceId&&k.traceId!==g.traceId||!g.includeDebug&&k.level===i.LogLevel.DEBUG)continue;g.onLog?.(k)}catch{}}if(!p.signal.aborted){let $=Math.min(2e3*Math.pow(2,h),3e4);await new Promise(C=>setTimeout(C,$)),p.signal.aborted||b(h+1);return}y(),g.onComplete?.()}catch(w){if(w.name==="AbortError"){y();return}if(h<10&&!p.signal.aborted){let z=Math.min(2e3*Math.pow(2,h),3e4);await new Promise(_=>setTimeout(_,z)),p.signal.aborted||b(h+1);return}y(),g.onError?.(w)}};return b(),{unsubscribe:()=>{let h=this.controllers.get(a);h&&(h.abort(),this.controllers.delete(a))}}}async disconnect(){for(let[g,p]of this.controllers)p.abort();this.controllers.clear()}};o.SSELogSubscriptionManager=n}),Su=ne(o=>{"use strict";Object.defineProperty(o,"__esModule",{value:!0}),o.SuperglueClient=void 0;var i=tt(),n=Yr(),g=Gr(),p=class{constructor({apiKey:a,apiEndpoint:c,onInfrastructureError:l}){this.apiKey=a,this.apiEndpoint=c??"https://api.superglue.cloud",this.sseManager=new n.SSELogSubscriptionManager(this.apiEndpoint,this.apiKey),this.onInfrastructureError=l}isInfrastructureError(a){return(0,g.isAbortError)(a)?!1:!!(a instanceof TypeError&&a.message.toLowerCase().includes("fetch")||a instanceof Error&&a.name==="TimeoutError")}async restRequest(a,c,l,y,b){let h=`${this.apiEndpoint.replace(/\/$/,"")}${c}`,w={Authorization:`Bearer ${this.apiKey}`,...y};l&&a!=="GET"&&(w["Content-Type"]="application/json");let z;try{z=await fetch(h,{method:a,headers:w,body:l?JSON.stringify(l):void 0,signal:b?.signal})}catch(O){throw this.isInfrastructureError(O)&&this.onInfrastructureError?.(),O}if(!z.ok){z.status>=500&&this.onInfrastructureError?.();let O=await z.text(),$=`HTTP ${z.status}: ${O}`;try{let C=JSON.parse(O).error;typeof C=="string"?$=C:C&&typeof C=="object"&&($=C.message||JSON.stringify(C))}catch{}throw new Error($)}let _=await z.text();if(_)return JSON.parse(_)}async subscribeToLogsSSE(a={}){return this.sseManager.subscribeToLogs(a)}async disconnect(){await this.sseManager.disconnect()}async runTool(a){let c=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(a.toolId)}/run`,{inputs:a.payload,files:a.files,credentials:a.credentials,options:a.options,runId:a.runId});return{success:c.status==="success",data:c.data,error:c.error,tool:c.tool,stepResults:c.stepResults?.map(l=>({...l}))||[]}}async runToolConfig(a){let c=a.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",l=await this.restRequest("POST",c,{tool:a.tool,payload:a.payload,files:a.files,credentials:a.credentials,options:a.options,runId:a.runId},a.traceId?{"X-Trace-Id":a.traceId}:void 0);return{success:l.status?l.status==="success":l.success??!1,data:l.data,error:l.error,tool:l.tool||a.tool,stepResults:l.stepResults?.map(y=>({...y}))||[]}}async abortToolExecution(a){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(a)}/cancel`)).runId}}async executeStep({step:a,payload:c,files:l,previousResults:y,credentials:b,options:h,runId:w,mode:z,systemIds:_}){return this.restRequest("POST","/v1/tools/step/run",{step:a,payload:c,files:l,previousResults:y,credentials:b,options:h,runId:w,mode:z,systemIds:_})}async abortStep(a){return this.restRequest("POST","/v1/tools/step/abort",{runId:a})}async executeTransformOnly({outputTransform:a,outputSchema:c,inputSchema:l,payload:y,files:b,stepResults:h,responseFilters:w,options:z,runId:_}){return this.restRequest("POST","/v1/tools/transform/run",{outputTransform:a,outputSchema:c,inputSchema:l,payload:y,files:b,stepResults:h,responseFilters:w,options:z,runId:_})}async createRun({toolId:a,toolConfig:c,toolResult:l,stepResults:y,toolPayload:b,status:h,error:w,startedAt:z,completedAt:_}){return this.restRequest("POST","/v1/runs",{toolId:a,toolConfig:c,toolResult:l,stepResults:y,toolPayload:b,status:h,error:w,startedAt:z.toISOString(),completedAt:_.toISOString()})}async extract({file:a,envelope:c}){if(!a)throw new Error("File must be provided for extract.");let l=new FormData;l.append("file",a);let y=new URL(`${this.apiEndpoint.replace(/\/$/,"")}/v1/extract`);c&&y.searchParams.set("envelope","true");let b=y.toString(),h=await fetch(b,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:l});if(!h.ok){let w=await h.text(),z=`HTTP ${h.status}: ${w}`;try{let _=JSON.parse(w);_.error&&(z=_.error)}catch{}throw new Error(z)}return h.json()}mapOpenAPIRunToRun(a){let c={running:i.RunStatus.RUNNING,success:i.RunStatus.SUCCESS,failed:i.RunStatus.FAILED,aborted:i.RunStatus.ABORTED};return{runId:a.runId??a.id,toolId:a.toolId,tool:a.tool,status:c[a.status]??i.RunStatus.FAILED,toolPayload:a.toolPayload,data:a.data,toolResult:a.data,error:a.error,stepResults:a.stepResults,options:a.options,requestSource:a.requestSource,traceId:a.traceId,resultStorageUri:a.resultStorageUri,userId:a.userId,userEmail:a.userEmail,userName:a.userName,metadata:a.metadata}}async listRuns(a){let{limit:c=100,page:l=1,toolId:y,search:b,searchUserIds:h,includeTotal:w=!0,startedAfter:z,status:_,requestSources:O,userId:$,systemId:C,signal:v}=a??{},A=new URLSearchParams({limit:String(c),page:String(l)});y&&A.set("toolId",y),b?.trim()&&A.set("search",b.trim()),h&&h.length>0&&A.set("searchUserIds",h.join(",")),w||A.set("includeTotal","false"),z&&A.set("startedAfter",z instanceof Date?z.toISOString():z),_&&A.set("status",_),O&&O.length>0&&A.set("requestSources",O.join(",")),$&&A.set("userId",$),C&&A.set("systemId",C);let k=await this.restRequest("GET",`/v1/runs?${A.toString()}`,void 0,void 0,{signal:v});return{items:k.data.map(L=>this.mapOpenAPIRunToRun(L)),total:k.total,page:k.page,limit:k.limit,hasMore:k.hasMore}}async getRun(a){try{let c=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(a)}`);return this.mapOpenAPIRunToRun(c)}catch(c){if(c.message?.includes("404")||c.message?.includes("not found"))return null;throw c}}async getWorkflow(a){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(a)}`)}catch(c){if(c.message?.includes("404")||c.message?.includes("not found")||c.message?.includes("403")||c.message?.includes("not allowed"))return null;throw c}}async archiveWorkflow(a,c=!0){return this.upsertWorkflow(a,{archived:c})}async listWorkflows(a=10,c=0,l=!1){let y=Math.floor(c/a)+1,b=l?"&includeArchived=true":"",h=await this.restRequest("GET",`/v1/tools?limit=${a}&page=${y}${b}`);return{items:h.data,total:h.total}}async createWorkflow(a,c){return this.restRequest("POST","/v1/tools",{...c,id:a})}async updateWorkflow(a,c){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(a)}`,c)}async upsertWorkflow(a,c){return await this.getWorkflow(a)?this.updateWorkflow(a,c):this.createWorkflow(a,c)}async deleteWorkflow(a){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(a)}`),!0}catch(c){if(c.message?.includes("404"))return!1;throw c}}async renameWorkflow(a,c){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(a)}/rename`,{newId:c})}async listSystems(a=10,c=1,l){let y=new URLSearchParams({limit:String(a),page:String(c)});l?.mode&&y.set("mode",l.mode);let b=await this.restRequest("GET",`/v1/systems?${y.toString()}`);return{items:b.data,total:b.total}}async getSystem(a,c){let l=c?.environment?`?env=${c.environment}`:"";return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(a)}${l}`)).data}async createSystem(a){return(await this.restRequest("POST","/v1/systems",a)).data}async updateSystem(a,c,l){let y=l?.environment?`?env=${l.environment}`:"";return(await this.restRequest("PATCH",`/v1/systems/${encodeURIComponent(a)}${y}`,c)).data}async deleteSystem(a,c){let l=c?.environment?`?env=${c.environment}`:"";return await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(a)}${l}`),!0}async cacheOAuthSecret(a){return await this.restRequest("POST","/v1/oauth/secrets",a),!0}async getOAuthSecret(a){return(await this.restRequest("GET",`/v1/oauth/secrets/${encodeURIComponent(a)}`)).data}async getTemplateOAuthCredentials(a){return(await this.restRequest("GET",`/v1/oauth/templates/${encodeURIComponent(a)}/credentials`)).data}async searchSystemDocumentation(a,c){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(a)}/documentation/search`,{keywords:c})).data}async cacheOauthClientCredentials(a){return this.restRequest("POST","/v1/oauth/secrets",{uid:a.clientCredentialsUid,clientId:a.clientId,clientSecret:a.clientSecret})}async getOAuthClientCredentials(a){if(a.clientCredentialsUid)return(await this.restRequest("GET",`/v1/oauth/secrets/${encodeURIComponent(a.clientCredentialsUid)}`)).data;if(!a.templateId)throw new Error("No valid credentials source provided");return(await this.restRequest("GET",`/v1/oauth/templates/${encodeURIComponent(a.templateId)}/credentials`)).data}async getCliOAuthSecret(){return(await this.restRequest("GET","/v1/oauth/cli-secret")).data}async triggerSystemDocumentationScrapeJob(a,c){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(a)}/documentation/scrape`,c)).data}async fetchOpenApiSpec(a,c){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(a)}/documentation/openapi`,{url:c})).data}async createSystemFileUploadUrls(a,c){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(a)}/file-references`,{files:c.map(l=>({fileName:l.fileName,metadata:{contentType:l.contentType,contentLength:l.contentLength}}))})).data.files}async uploadSystemFileReferences(a,c){let l=await this.createSystemFileUploadUrls(a,c.map(y=>({fileName:y.fileName,contentType:y.contentType,contentLength:y.contentLength})));return await Promise.all(l.map(async(y,b)=>{let h=await fetch(y.uploadUrl,{method:"PUT",body:c[b].content,headers:c[b].contentType?{"Content-Type":c[b].contentType}:void 0});if(!h.ok)throw new Error(`Upload failed for ${c[b].fileName}: ${h.status} ${h.statusText}`)})),l.map((y,b)=>({id:y.id,fileName:c[b].fileName}))}async listSystemFileReferences(a){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(a)}/file-references`)).data}async deleteSystemFileReference(a,c){await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(a)}/file-references/${encodeURIComponent(c)}`)}async getFileReferenceContent(a){return(await this.restRequest("GET",`/v1/file-references/${encodeURIComponent(a)}?includeContent=true`)).data.content??null}async getTenantInfo(){return this.restRequest("GET","/v1/tenant-info")}async setTenantInfo(a){return this.restRequest("PUT","/v1/tenant-info",a)}async generatePortalLink(){try{return{success:!0,portalUrl:(await this.restRequest("POST","/v1/authenticate",{})).data.portalUrl}}catch(a){return{success:!1,error:a.message}}}};o.SuperglueClient=p}),Ou=io&&io.__createBinding||(Object.create?(function(o,i,n,g){g===void 0&&(g=n);var p=Object.getOwnPropertyDescriptor(i,n);(!p||("get"in p?!i.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return i[n]}}),Object.defineProperty(o,g,p)}):(function(o,i,n,g){g===void 0&&(g=n),o[g]=i[n]})),sa=io&&io.__exportStar||function(o,i){for(var n in o)n!=="default"&&!Object.prototype.hasOwnProperty.call(i,n)&&Ou(i,o,n)};Object.defineProperty(io,"__esModule",{value:!0});io.SSELogSubscriptionManager=io.SuperglueClient=void 0;sa(kl(),io);sa(gr(),io);sa(zl(),io);sa(ql(),io);sa(jl(),io);sa(Sl(),io);sa(tt(),io);sa(Gr(),io);sa(qu(),io);sa(ju(),io);var _u=Su();Object.defineProperty(io,"SuperglueClient",{enumerable:!0,get:function(){return _u.SuperglueClient}});var Eu=Yr();Object.defineProperty(io,"SSELogSubscriptionManager",{enumerable:!0,get:function(){return Eu.SSELogSubscriptionManager}})});var zi=require("commander");var Mo=Ee(require("fs")),os=Ee(require("os")),pa=Ee(require("path")),Xc=new Set(["runner","builder","admin"]),es={output:{mode:"stdout",directory:".superglue/output"},preset:"admin"};function Pa(o){let i=pa.join(process.cwd(),".superglue"),n=os.homedir();if(!n)return i;let g=pa.join(n,".superglue");return o===!0?i:o===!1?g:Mo.existsSync(pa.join(i,"config.json"))?i:g}function ml(o){return pa.join(Pa(o),"config.json")}function ll(){let o=ml();if(!Mo.existsSync(o))return{};try{return JSON.parse(Mo.readFileSync(o,"utf-8"))}catch{return{}}}function Di(o){let i=ll(),n=o.apiKey||process.env.SUPERGLUE_API_KEY||i.apiKey||"",g=o.endpoint||process.env.SUPERGLUE_API_ENDPOINT||i.endpoint||"https://api.superglue.cloud",p=process.env.SUPERGLUE_WEB_ENDPOINT||i.webEndpoint||g.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue"),a=process.env.SUPERGLUE_CLI_PRESET,c=a&&Xc.has(a)?a:i.preset&&Xc.has(i.preset)?i.preset:"admin";return{...es,...i,apiKey:n,endpoint:g,webEndpoint:p,preset:c,output:{...es.output,...i.output}}}function as(o,i){let n=Pa(i);Mo.existsSync(n)||Mo.mkdirSync(n,{recursive:!0}),Mo.writeFileSync(pa.join(n,"config.json"),JSON.stringify(o,null,2)+`
|
|
1092
|
+
`,{mode:384})}function ts(o,i){let n=pa.join(Pa(i),"drafts");if(Mo.existsSync(n)||Mo.mkdirSync(n,{recursive:!0}),o.output.mode==="stdout+file"){let g=pa.resolve(o.output.directory);Mo.existsSync(g)||Mo.mkdirSync(g,{recursive:!0})}}var ln=Ee(ra());var mc=Ee(require("readline"));var Qr=require("child_process"),Xr=require("util");var Zr={name:"@superglue/cli",version:"1.1.20",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 Au=(0,Xr.promisify)(Qr.exec),_o=Zr.version;function Kr(o){let i=o.match(/^(\d+)(?:-(.+))?$/);return i?{numeric:parseInt(i[1],10),prerelease:i[2]||null}:{numeric:0,prerelease:o}}function At(o,i){let n=o.split("."),g=i.split("."),p=Math.max(n.length,g.length);for(let a=0;a<p;a++){let c=Kr(n[a]||"0"),l=Kr(g[a]||"0");if(c.numeric<l.numeric)return-1;if(c.numeric>l.numeric||c.prerelease===null&&l.prerelease!==null)return 1;if(c.prerelease!==null&&l.prerelease===null)return-1;if(c.prerelease!==null&&l.prerelease!==null){if(c.prerelease<l.prerelease)return-1;if(c.prerelease>l.prerelease)return 1}}return 0}async function en(o){try{let i=`${o.replace(/\/$/,"")}/v1/health`,n=await fetch(i,{signal:AbortSignal.timeout(3e3)});if(!n.ok)return;let g=await n.json();if(!g.minCliVersion)return;At(_o,g.minCliVersion)<0&&(console.error(""),console.error(`${S.yellow}${S.bold}\u26A0 CLI version ${_o} is outdated.${S.reset}`),console.error(`${S.yellow} Server requires at least v${g.minCliVersion}. Run: ${S.bold}sg update${S.reset}`),console.error(""))}catch{}}async function li(){try{let o=await fetch("https://registry.npmjs.org/@superglue/cli/latest",{signal:AbortSignal.timeout(5e3)});return o.ok&&(await o.json()).version||null}catch{return null}}var mi=null;function on(){mi=li()}async function an(){if(mi){try{let o=new Promise(n=>{setTimeout(()=>n(null),2e3).unref()}),i=await Promise.race([mi,o]);i&&At(_o,i)<0&&(console.error(""),console.error(`${S.cyan}${S.bold} Update available: ${_o} \u2192 ${i}${S.reset}`),console.error(`${S.cyan} Run ${S.bold}sg update${S.reset}${S.cyan} to upgrade${S.reset}`),console.error(""))}catch{}mi=null}}async function tn(){let o=await li();if(!o)return{success:!1,message:"Could not fetch latest version from npm"};if(At(_o,o)>=0)return{success:!0,message:`Already on latest version (${_o})`};try{return await Au("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${_o} to ${o}`}}catch(i){return{success:!1,message:`Update failed: ${i.message}. Try manually: npm install -g @superglue/cli@latest`}}}var Ce=()=>process.argv.includes("--table")&&process.stdout.isTTY,na=()=>process.argv.includes("--full"),S={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 cn(o,i){let n=i||o;return`\x1B]8;;${o}\x07${S.underline}${S.cyan}${n}${S.reset}\x1B]8;;\x07`}function sn(){if(!Ce())return;let o=S.reset,i=S.dim,n="\x1B[47;30m",g=[" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@- "," =@@@- @@@@ "," @@@ @@% "," -@@ @@@@= @@@ @@@ @@@@@#@ @@@@@@@ @@@@@@@ @@@@@@ @@@ @@@ @@@ @@@@@@* %@@ "," @@ @@@ *@ @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @% @@@ @@@ @@@ @@* @@# "," #@@ @@@# @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @@@ @@@ @@@ @@* @@ "," @@- @@@@= @@@ @@@ @@@@@@@ @@@@@@ @@@@@@@ @@@ @@% @@@ @@@ @@@ @@@@@. @@."," #@% .@@@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* @@ "," @@ @ @@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* *@@ "," -@@ @@@@= @@@@@@ @@@ @@@@@@@ @@@ -@@ @@@@@@ @@@@@@% @@@@@@. @@@@@@* #@@ "," :@@* @@@ "," %@@@ =@@@. "," :@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% "];console.log(""),g.forEach(p=>{let a=p.search(/\S/),c=p.length-[...p].reverse().join("").search(/\S/)-1;if(a===-1)return console.log(" "+p);let l=p.slice(0,a),y=p.slice(a,c+1).split("").map(h=>h===" "?" ":"\u2588").join(""),b=p.slice(c+1);console.log(` ${l}${n}${y}${o}${b}`)}),console.log(` ${i} CLI v${_o}${o}`),console.log("")}function vo(o){if(!Ce())return{stop:()=>{},update:()=>{},log:()=>{}};let i=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],n=0,g=o,p=()=>process.stdout.write("\r\x1B[2K"),a=()=>{process.stdout.write(`\r ${S.cyan}${i[n++%i.length]}${S.reset} ${g}`)},c=setInterval(a,80);return{update:l=>{g=l},log:l=>{p(),console.log(` ${S.dim}\u2502${S.reset} ${l}`),a()},stop:l=>{clearInterval(c),p(),l&&console.log(` ${l}`)}}}function Te(o){Ce()?ui(o):console.log(JSON.stringify(o,null,2))}function co(o,i){Ce()?(console.log(` ${S.green}\u2713${S.reset} ${o}`),i&&ui(i,4)):console.log(JSON.stringify({success:!0,message:o,...i&&typeof i=="object"?i:{data:i}}))}function X(o,i){Ce()?(console.error(` ${S.red}\u2717${S.reset} ${o}`),i&&ui(i,4)):console.error(JSON.stringify({success:!1,error:o,details:i}))}function rn(o){Ce()&&console.log(` ${S.yellow}\u26A0${S.reset} ${o}`)}function qa(o){Ce()&&console.log(` ${S.dim}${o}${S.reset}`)}function da(o){Ce()&&(console.log(`
|
|
1093
1093
|
${S.bold}${S.cyan}${o}${S.reset}`),console.log(` ${S.dim}${"\u2500".repeat(o.length)}${S.reset}`))}function it(o,i,n){if(!Ce()){console.log(JSON.stringify({success:!0,total:n?.total??o.length,items:o}));return}if(o.length===0){console.log(`
|
|
1094
1094
|
${S.dim}0 results${S.reset}
|
|
1095
1095
|
`);return}let g=i||Object.keys(o[0]),p=na()?1/0:60,a=g.map(h=>Math.min(p,Math.max(h.length,...o.map(w=>String(w[h]??"").replace(/[\n\r]+/g," ").trim().length))));console.log("");let c=g.map((h,w)=>`${S.bold}${S.cyan}${h.toUpperCase().padEnd(a[w])}${S.reset}`).join(" ");console.log(` ${c}`);let l=a.map(h=>`${S.dim}${"\u2500".repeat(h)}${S.reset}`).join(`${S.dim}\u2500\u2500${S.reset}`);console.log(` ${l}`);for(let h of o){let w=g.map((z,_)=>{let O=String(h[z]??"").replace(/[\n\r]+/g," ").trim();if(O.length>p){let C=`\u2026 (${O.length})`;O=O.slice(0,Math.max(0,p-C.length))+`${S.dim}${C}${S.reset}`}return z==="status"?`${{success:S.green,running:S.yellow,failed:S.red,aborted:S.red,error:S.red,pending:S.dim}[O.toLowerCase()]||""}${O.padEnd(a[_])}${S.reset}`:O.padEnd(a[_])}).join(" ");console.log(` ${w}`)}let y=n?.total??o.length,b=y===o.length?`${o.length} result${o.length===1?"":"s"}`:`${o.length} of ${y} result${y===1?"":"s"}`;console.log(`
|
|
@@ -1121,7 +1121,7 @@ Provide exactly one of: --tool, --draft, --config, or --config-file.
|
|
|
1121
1121
|
Returns: { success, data, error? }
|
|
1122
1122
|
|
|
1123
1123
|
Run 'sg skill' for payload syntax, variable references, and data selectors.
|
|
1124
|
-
`).action(async g=>{let{config:p,client:a}=i(),c=[g.tool,g.draft,g.config,g.configFile].filter(Boolean);c.length===0&&(X("Provide one of --tool, --draft, --config, or --config-file"),process.exit(1)),c.length>1&&(X("Only one of --tool, --draft, --config, or --config-file can be used"),process.exit(1));let l=g.tool?"tool":g.draft?"draft":g.configFile?"config-file":"config";hn(n,l)||(X(`--${l} is not available in the '${n}' preset. Use --tool <id> to run a saved tool, or change preset to 'builder' or 'admin'.`),process.exit(1));let y=await st(g.file,a),b=g.payloadFile?JSON.parse(ha.readFileSync(g.payloadFile,"utf-8")):g.payload?JSON.parse(g.payload):void 0;if(b){let v=fi(b,y);v.success||(X(v.error),process.exit(1)),b=v.resolved}let h,w=g.tool||g.draft||"inline-config",z=vn.randomUUID(),_=vo(`Running ${S.bold}${w}${S.reset}...`),O=await a.subscribeToLogsSSE({traceId:z,onLog:v=>_.log(`${S.dim}${v.message}${S.reset}`)}).catch(()=>({unsubscribe:()=>{}})),$=async v=>{try{let A=await a.runToolConfig({tool:v,payload:b,options:{requestSource:hc.RequestSource.CLI},traceId:z,createRun:!0});return O.unsubscribe(),_.stop(),A}catch(A){O.unsubscribe(),_.stop(),X(A.message),process.exit(1)}};if(g.tool)try{h=await a.runTool({toolId:g.tool,payload:b,options:{requestSource:hc.RequestSource.CLI,traceId:z}}),O.unsubscribe(),_.stop()}catch(v){O.unsubscribe(),_.stop(),X(v.message),process.exit(1)}else if(g.config||g.configFile){let v;try{v=g.configFile?JSON.parse(ha.readFileSync(g.configFile,"utf-8")):JSON.parse(g.config)}catch(A){O.unsubscribe(),_.stop(),X(`Invalid tool config JSON: ${A.message}`),process.exit(1)}h=await $(v)}else{let v=ct(g.draft);v||(O.unsubscribe(),_.stop(),X(`Draft not found: ${g.draft}`),process.exit(1)),h=await $(v.config)}let C={success:h.success,data:h.data,...h.error?{error:h.error}:{},...g.includeStepResults&&h.stepResults?{stepResults:h.stepResults}:{},...g.includeConfig&&h.tool?{config:h.tool}:{}};if(Te(C),p.output.mode==="stdout+file"){let v=rt.resolve(p.output.directory);ha.existsSync(v)||ha.mkdirSync(v,{recursive:!0});let A=g.tool||g.draft||"inline-config",L=`${rt.basename(A).replace(/[^a-zA-Z0-9_-]/g,"_")}-${Date.now()}.json`;ha.writeFileSync(rt.join(v,L),JSON.stringify(C,null,2))}h.success||process.exit(1)})}var vi=Ee(require("fs")),xn=Ee(ra()),zn=Ee(require("fast-json-patch"));function qn(o,i){o.command("edit").description("Edit a tool using JSON Patch operations").option("--draft <id>","Draft ID to edit").option("--tool <id>","Saved tool ID to edit").option("--patches <json-or-file>","JSON Patch array (inline JSON or file path)").addHelpText("after",`
|
|
1124
|
+
`).action(async g=>{let{config:p,client:a}=i(),c=[g.tool,g.draft,g.config,g.configFile].filter(Boolean);c.length===0&&(X("Provide one of --tool, --draft, --config, or --config-file"),process.exit(1)),c.length>1&&(X("Only one of --tool, --draft, --config, or --config-file can be used"),process.exit(1));let l=g.tool?"tool":g.draft?"draft":g.configFile?"config-file":"config";hn(n,l)||(X(`--${l} is not available in the '${n}' preset. Use --tool <id> to run a saved tool, or change preset to 'builder' or 'admin'.`),process.exit(1));let y=await st(g.file,a),b=g.payloadFile?JSON.parse(ha.readFileSync(g.payloadFile,"utf-8")):g.payload?JSON.parse(g.payload):void 0;if(b){let v=fi(b,y);v.success||(X(v.error),process.exit(1)),b=v.resolved}let h,w=g.tool||g.draft||"inline-config",z=vn.randomUUID(),_=vo(`Running ${S.bold}${w}${S.reset}...`),O=await a.subscribeToLogsSSE({traceId:z,onLog:v=>_.log(`${S.dim}${v.message}${S.reset}`)}).catch(()=>({unsubscribe:()=>{}})),$=async v=>{try{let A=await a.runToolConfig({tool:v,payload:b,options:{requestSource:hc.RequestSource.CLI},traceId:z,createRun:!0});return O.unsubscribe(),_.stop(),A}catch(A){O.unsubscribe(),_.stop(),X(A.message),process.exit(1)}};if(g.tool)try{h=await a.runTool({toolId:g.tool,payload:b,options:{requestSource:hc.RequestSource.CLI,traceId:z}}),O.unsubscribe(),_.stop()}catch(v){O.unsubscribe(),_.stop(),X(v.message),process.exit(1)}else if(g.config||g.configFile){let v;try{v=g.configFile?JSON.parse(ha.readFileSync(g.configFile,"utf-8")):JSON.parse(g.config)}catch(A){O.unsubscribe(),_.stop(),X(`Invalid tool config JSON: ${A.message}`),process.exit(1)}h=await $(v)}else{let v=ct(g.draft);v||(O.unsubscribe(),_.stop(),X(`Draft not found: ${g.draft}`),process.exit(1)),h=await $(v.config)}let C={success:h.success,data:h.data,...h.error?{error:h.error}:{},...g.includeStepResults&&h.stepResults?{stepResults:h.stepResults}:{},...g.includeConfig&&h.tool?{config:h.tool}:{},...h.important_notice?{important_notice:h.important_notice}:{}};if(Te(C),p.output.mode==="stdout+file"){let v=rt.resolve(p.output.directory);ha.existsSync(v)||ha.mkdirSync(v,{recursive:!0});let A=g.tool||g.draft||"inline-config",L=`${rt.basename(A).replace(/[^a-zA-Z0-9_-]/g,"_")}-${Date.now()}.json`;ha.writeFileSync(rt.join(v,L),JSON.stringify(C,null,2))}h.success||process.exit(1)})}var vi=Ee(require("fs")),xn=Ee(ra()),zn=Ee(require("fast-json-patch"));function qn(o,i){o.command("edit").description("Edit a tool using JSON Patch operations").option("--draft <id>","Draft ID to edit").option("--tool <id>","Saved tool ID to edit").option("--patches <json-or-file>","JSON Patch array (inline JSON or file path)").addHelpText("after",`
|
|
1125
1125
|
Patches use JSON Patch (RFC 6902) format:
|
|
1126
1126
|
[{"op":"replace","path":"/steps/0/config/url","value":"https://..."}]
|
|
1127
1127
|
|