@superglue/cli 1.1.59 → 1.1.61

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.59",
4
+ "version": "1.1.61",
5
5
  "author": {
6
6
  "name": "superglue",
7
7
  "email": "hello@superglue.cloud"
package/dist/cli.js CHANGED
@@ -364,7 +364,7 @@ ${e.map(t=>`- ${t.path}: ${t.message}`).join(`
364
364
  `).split(`
365
365
  `).map(a=>`${e}${a}`)].join(`
366
366
  `)}function gi(o,e){return o.includes(`
367
- `)?xY(o,e):JSON.stringify(o)}function zY(o){let e=["---"];if(e.push(`name: ${gi(o.id," ")}`),e.push(`title: ${gi(o.name," ")}`),e.push(`when_to_run: ${gi(o.whenToRun," ")}`),o.systemRefs.length>0){e.push("systems:");for(let a of o.systemRefs)e.push(` - id: ${gi(a.id," ")}`)}if(o.toolRefs.length>0){e.push("tools:");for(let a of o.toolRefs)e.push(` - id: ${gi(a.id," ")}`)}if(o.credentialRefs.length>0){e.push("credentials:");for(let a of o.credentialRefs)e.push(` - id: ${gi(a.id," ")}`)}if(o.fileRefs.length>0){e.push("files:");for(let a of o.fileRefs)e.push(` - ${gi(a.name," ")}`)}e.push(`completion_criteria: ${gi(o.completionCriteria," ")}`),e.push("---"),e.push(""),o.inputs.trim()&&(e.push("## Required inputs"),e.push(""),e.push(o.inputs.trim()),e.push("")),e.push("## Instructions"),e.push(""),e.push(o.instructions.trim()),e.push("");let t=e.join(`
367
+ `)?xY(o,e):JSON.stringify(o)}function zY(o){let e=["---"];if(e.push(`name: ${gi(o.id," ")}`),e.push(`title: ${gi(o.name," ")}`),e.push(`when_to_run: ${gi(o.whenToRun," ")}`),o.systemRefs.length>0){e.push("systems:");for(let a of o.systemRefs)e.push(` - id: ${gi(a.id," ")}`)}if(o.toolRefs.length>0){e.push("tools:");for(let a of o.toolRefs)e.push(` - id: ${gi(a.id," ")}`)}if(o.credentialRefs.length>0){e.push("credentials:");for(let a of o.credentialRefs)e.push(` - id: ${gi(a.id," ")}`)}if(o.fileRefs.length>0){e.push("files:");for(let a of o.fileRefs)e.push(` - ${gi(a.name," ")}`);e.push(`# read attachments at /org/playbooks/${o.id}/files/<name>.json (.raw for original bytes)`)}e.push(`completion_criteria: ${gi(o.completionCriteria," ")}`),e.push("---"),e.push(""),o.inputs.trim()&&(e.push("## Required inputs"),e.push(""),e.push(o.inputs.trim()),e.push("")),e.push("## Instructions"),e.push(""),e.push(o.instructions.trim()),e.push("");let t=e.join(`
368
368
  `);if(t.length>d2.PLAYBOOK_LIMITS.compiledRender)throw new Error(`Compiled playbook render for '${o.id}' exceeds ${d2.PLAYBOOK_LIMITS.compiledRender} chars (${t.length})`);return t}});var rb=y(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.RESOURCE_KINDS=Rt.RESOURCE_DEFINITIONS=void 0;Rt.isResourceKind=qY;Rt.getResourceDefinition=EY;Rt.RESOURCE_DEFINITIONS={tool:{label:"Tool",pluralLabel:"Tools",collectionKey:"tools",memberDefaultPermission:"editor",pickerDefaultPermission:"editor"},system:{label:"System",pluralLabel:"Systems",collectionKey:"systems",memberDefaultPermission:"editor",pickerDefaultPermission:"editor"},credential:{label:"Credential",pluralLabel:"Credentials",collectionKey:"credentials",pickerDefaultPermission:"viewer"},playbook:{label:"Playbook",pluralLabel:"Playbooks",collectionKey:"playbooks",pickerDefaultPermission:"editor"},artifact:{label:"Artifact",pluralLabel:"Artifacts",collectionKey:"artifacts",pickerDefaultPermission:"editor"},file:{label:"File",pluralLabel:"Files",collectionKey:"files",pickerDefaultPermission:"viewer"},project:{label:"Project",pluralLabel:"Projects",collectionKey:"projects",pickerDefaultPermission:"viewer"}};Rt.RESOURCE_KINDS=Object.keys(Rt.RESOURCE_DEFINITIONS);function qY(o){return typeof o=="string"&&Object.prototype.hasOwnProperty.call(Rt.RESOURCE_DEFINITIONS,o)}function EY(o){return Rt.RESOURCE_DEFINITIONS[o]}});var z2=y(_=>{"use strict";Object.defineProperty(_,"__esModule",{value:!0});_.RESERVED_ROLE_NAMES=_.RESERVED_ROLE_IDS=_.PREDEFINED_ROLE_IDS=void 0;_.toResourceRef=Oc;_.toWildcardResourceRef=Fc;_.getDefaultMemberResourceGrants=IY;_.parseResourceRef=Nu;_.getWildcardResourceRef=p2;_.normalizeResourcePermissions=pi;_.permissionSatisfies=Uu;_.highestResourcePermission=Mu;_.grantHasPermission=mb;_.grantMatchesResource=Rr;_.getEffectiveResourcePermissions=lb;_.hasResourcePermission=CY;_.getRoleResourceGrants=_u;_.getAllowedResourceIds=h2;_.getAllowedResourceIdsForRoles=Ou;_.getEffectiveResourcePermissionsForRoles=Tr;_.getAllowedToolIds=f2;_.getAllowedSystemIds=b2;_.pickLongestHeldResource=QY;_.getAllowedCredentialsIds=BY;_.getEffectiveCredentialsPermissions=SY;_.getEffectiveToolPermissions=DY;_.getEffectiveSystemPermissions=RY;_.checkResourcePermission=Fu;_.isToolAllowed=TY;_.isSystemVisible=NY;_.isPlaybookVisible=UY;_.hasAllSystems=MY;_.hasAllTools=_Y;_.getResourceGrantSources=y2;_.getSharePermissionForResource=k2;_.getAccessRulePermissionForResource=A2;_.hasAdminBaseRole=ub;_.resolveResourceAccessForRoles=OY;_.normalizeResourceGrantInput=w2;_.normalizeRoleResourceGrantInput=FY;_.isPredefinedRole=LY;_.isReservedRoleId=PY;_.isReservedRoleName=HY;_.hasRole=YY;_.getRoleIds=GY;_.getBaseRole=v2;_.getBaseRoleId=VY;_.getPersonalRole=x2;_.getPersonalRoleId=WY;var Ru=rb(),Tu="*";function Oc(o,e){if(!e||e===Tu)throw new Error("Resource id is required");return`${o}:${encodeURIComponent(e)}`}function Fc(o){return`${o}:${Tu}`}function IY(){return Ru.RESOURCE_KINDS.flatMap(o=>{let e=(0,Ru.getResourceDefinition)(o).memberDefaultPermission;return e?[{resourceRef:Fc(o),permissions:[e]}]:[]})}function Nu(o){let e=o.indexOf(":");if(e<=0)return null;let t=o.slice(0,e);if(!(0,Ru.isResourceKind)(t))return null;let a=o.slice(e+1);if(!a)return null;if(a===Tu)return{kind:t,id:Tu,isWildcard:!0};try{return{kind:t,id:decodeURIComponent(a),isWildcard:!1}}catch{return null}}function p2(o){let e=Nu(o);return e?Fc(e.kind):null}function pi(o){let e=new Set;for(let t of o||[])(t==="viewer"||t==="editor")&&e.add(t);return e.has("editor")&&e.add("viewer"),Array.from(e)}function Uu(o,e){return o===e||o==="editor"&&e==="viewer"}function Mu(o){let e=pi(o);if(e.includes("editor"))return"editor";if(e.includes("viewer"))return"viewer"}function mb(o,e){return o.revokedAt?!1:pi(o.permissions).some(t=>Uu(t,e))}function Rr(o,e){return o.revokedAt?!1:o.resourceRef===e||o.resourceRef===p2(e)}function lb(o,e){let t=new Set;for(let a of o)if(Rr(a,e))for(let i of pi(a.permissions))t.add(i);return Array.from(t)}function CY(o,e,t){return lb(o,e).some(a=>Uu(a,t))}function _u(o){return o.flatMap(e=>e.isBaseRole&&e.id==="admin"?[]:e.resourceGrants||[])}function h2(o,e,t){let a=Fc(e),i=new Set;for(let s of o){if(!mb(s,t))continue;if(s.resourceRef===a)return;let r=Nu(s.resourceRef);r?.kind===e&&!r.isWildcard&&i.add(r.id)}return Array.from(i)}function Ou(o,e,t){if(!ub(o))return h2(_u(o),e,t)}function Tr(o,e,t){return ub(o)?["editor","viewer"]:lb(_u(o),Oc(e,t))}function jY(o){return(0,Ru.getResourceDefinition)(o).label}function f2(o,e="viewer"){return Ou(o,"tool",e)}function b2(o,e="viewer"){return Ou(o,"system",e)}var cb=Number.MAX_SAFE_INTEGER;function nb(o){if(!o)return cb;let e=new Date(o).getTime();return Number.isNaN(e)?cb:e}function QY(o,e,t){if(o.length<=1)return o[0];let a=i=>{let s=Oc(t,i.id),r=cb;for(let n of e)Rr(n,s)&&(r=Math.min(r,nb(n.createdAt)));return r};return[...o].sort((i,s)=>{let r=a(i)-a(s);return r!==0?r:nb(i.createdAt)-nb(s.createdAt)})[0]}function BY(o,e="viewer"){return Ou(o,"credential",e)}function SY(o,e){return Tr(o,"credential",e)}function DY(o,e){return Tr(o,"tool",e)}function RY(o,e){return Tr(o,"system",e)}function Fu(o,e,t,a){return Tr(o,e,t).some(s=>Uu(s,a))?{allowed:!0}:{allowed:!1,error:`${jY(e)} '${t}' requires a '${a}' grant`}}function TY(o,e,t="viewer"){return Fu(o,"tool",e,t)}function NY(o,e,t="viewer"){return Fu(o,"system",e,t)}function UY(o,e,t="viewer"){return Fu(o,"playbook",e,t)}function MY(o,e="viewer"){return b2(o,e)===void 0}function _Y(o,e="viewer"){return f2(o,e)===void 0}function y2(o,e,t="viewer"){let a=new Set;for(let i of o)Rr(i,e)&&mb(i,t)&&a.add(i.source);return Array.from(a)}function k2(o,e){let t=o.filter(a=>a.source==="share"&&Rr(a,e)).flatMap(a=>pi(a.permissions));return Mu(t)}function A2(o,e){let t=o.filter(a=>a.source==="access_rule"&&Rr(a,e)).flatMap(a=>pi(a.permissions));return Mu(t)}function ub(o){return o.some(e=>e.isBaseRole&&e.id==="admin")}function OY({roles:o,resource:e,userId:t}){let a=Oc(e.kind,e.id),i=_u(o),s=new Set(Tr(o,e.kind,e.id)),r=new Set(y2(i,a));e.ownerUserId&&e.ownerUserId===t&&(s.add("editor"),s.add("viewer"),r.add("ownership"));let n=pi(Array.from(s));return{permissions:n,sources:Array.from(r),sharePermission:k2(i,a),accessRulePermission:A2(i,a),maxPermission:Mu(n)}}function w2(o){let e=Nu(o.resourceRef);if(!e)throw new Error(`Invalid resource ref '${o.resourceRef}'`);return{...o,resourceRef:e.isWildcard?Fc(e.kind):Oc(e.kind,e.id),permissions:pi(o.permissions||["viewer"]),source:o.source||"access_rule"}}function FY(o){let e=w2({resourceRef:o.resourceRef,permissions:o.permissions,source:"access_rule"});return{resourceRef:e.resourceRef,permissions:e.permissions,source:"access_rule"}}_.PREDEFINED_ROLE_IDS=["admin","member"];_.RESERVED_ROLE_IDS=["admin","member","__admin__"];_.RESERVED_ROLE_NAMES=["member","admin"];function LY(o){return _.PREDEFINED_ROLE_IDS.includes(o)}function PY(o){return _.RESERVED_ROLE_IDS.includes(o)}function HY(o){return _.RESERVED_ROLE_NAMES.includes(o.toLowerCase().trim())}function YY(o,e){return o.some(t=>t.id===e)}function GY(o){return o.map(e=>e.id)}function v2(o){let e=o.filter(t=>t.isBaseRole);return e.length===1?e[0]:null}function VY(o){let e=v2(o);return e?e.id:null}function x2(o){return o.find(e=>e.isPersonalRole)||null}function WY(o){let e=x2(o);return e?e.id:null}});var E2=y(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.NOTIFICATION_EXCLUDED_REQUEST_SOURCES=Lo.CLIENT_REQUEST_SOURCES=Lo.REQUEST_SOURCES=void 0;Lo.isRequestSource=q2;Lo.isClientRequestSource=KY;Lo.parseRequestSource=ZY;var fo=at();Lo.REQUEST_SOURCES=[fo.RequestSource.API,fo.RequestSource.FRONTEND,fo.RequestSource.AGENT,fo.RequestSource.SCHEDULER,fo.RequestSource.MCP,fo.RequestSource.TOOL_CHAIN,fo.RequestSource.WEBHOOK,fo.RequestSource.CLI];Lo.CLIENT_REQUEST_SOURCES=[fo.RequestSource.FRONTEND,fo.RequestSource.AGENT,fo.RequestSource.MCP,fo.RequestSource.CLI];Lo.NOTIFICATION_EXCLUDED_REQUEST_SOURCES=[fo.RequestSource.FRONTEND,fo.RequestSource.AGENT,fo.RequestSource.MCP];var $Y=new Set(Lo.REQUEST_SOURCES),JY=new Set(Lo.CLIENT_REQUEST_SOURCES);function q2(o){return $Y.has(o)}function KY(o){return JY.has(o)}function ZY(o){let e=o.toLowerCase();return q2(e)?e:void 0}});var gb=y(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.systemOptions=Ae.systems=void 0;Ae.getSystemTemplateAuthentication=Q2;Ae.mergeSystemTemplateAuthentication=B2;Ae.resolveSystemAuthentication=db;Ae.findTemplateForSystem=Pu;Ae.uniqueKeywords=oG;Ae.getOAuthConfig=tG;Ae.getOAuthTokenExchangeConfig=aG;Ae.getOAuthTokenUrl=iG;var j2=Nc(),Lu=Su();function XY(o){let e=o?.split(/[,\s]+/).filter(Boolean);return e?.length?e:void 0}function Q2(o){if(!o?.preferredAuthType)return;if(o.preferredAuthType!=="oauth2")return{type:o.preferredAuthType};let e=o.oauth;if(!e)return{type:"oauth2"};let t={};e.tokenAuthMethod&&(t.tokenAuthMethod=e.tokenAuthMethod),e.tokenContentType&&(t.tokenContentType=e.tokenContentType),e.extraHeaders&&(t.extraHeaders=e.extraHeaders),e.extraBodyParams&&(t.extraBodyParams=e.extraBodyParams),e.usePKCE!==void 0&&(t.usePKCE=e.usePKCE);let a=XY(e.scopes);return{type:"oauth2",...e.authUrl?{authUrl:e.authUrl}:{},...e.tokenUrl?{tokenUrl:e.tokenUrl}:{},...e.client_id?{clientId:e.client_id}:{},...e.grant_type?{grantType:e.grant_type}:{},...a?{scopes:a}:{},...Object.keys(t).length?{config:t}:{}}}function eG(o){return!o.config||Object.keys(o.config).length===0}function I2(o,e){let t={...o||{},...e||{}};return Object.keys(t).length>0?t:void 0}function C2(o,e){if(e)return{...o,config:e};let{config:t,...a}=o;return a}function B2({authentication:o,template:e}){let t=Q2(e),a=(0,j2.normalizeSystemAuthentication)(o);if(!a)return t;if(!t)return a;if(a.type==="none"&&eG(a))return t;if(a.type!==t.type)return a;if(a.type==="oauth2"&&t.type==="oauth2"){let i={...t};a.oauthClientMode==="custom"&&(delete i.clientId,delete i.clientSecret);let s={...i,...a};return a.oauthClientMode==="managed"&&t.clientId&&(s.clientId=t.clientId),C2(s,I2(t.config,a.config))}return C2({...t,...a},I2(t.config,a.config))}function db(o){let e=(0,j2.normalizeSystemAuthentication)(o.authentication)||{type:"none"};return B2({authentication:e,template:Pu(o)?.template})||e}Ae.systems={postgres:{name:"postgres",apiUrl:"postgres://<<username>>:<<password>>@<<host>>:<<port>>/<<database>>",regex:"^.*(postgres|postgresql).*$",icon:"postgresql",docsUrl:"",preferredAuthType:"connection_string",connectionFields:[{key:"host",label:"Host",placeholder:"db.example.com",required:!0},{key:"port",label:"Port",type:"number",defaultValue:"5432",placeholder:"5432"},{key:"database",label:"Database",placeholder:"mydb",required:!0},{key:"username",label:"Username",placeholder:"postgres",required:!0},{key:"password",label:"Password",type:"password",required:!0}],keywords:["database","sql","postgres","postgresql","api key","tables"]},redis_direct:{name:"redis_direct",apiUrl:"redis://<<username>>:<<password>>@<<host>>:<<port>>/<<database>>",regex:"^.*(rediss?://).*$",icon:"redis",docsUrl:"https://redis.io/docs/latest/commands/",preferredAuthType:"connection_string",connectionFields:[{key:"host",label:"Host",placeholder:"redis.example.com",required:!0},{key:"port",label:"Port",type:"number",defaultValue:"6379",placeholder:"6379"},{key:"database",label:"Database Index",placeholder:"0"},{key:"username",label:"Username",placeholder:"default"},{key:"password",label:"Password",type:"password",required:!0}],keywords:["database","cache","redis","key-value","nosql"]},mongodb_direct:{name:"mongodb_direct",apiUrl:"mongodb://<<username>>:<<password>>@<<host>>:<<port>>/<<database>>?authSource=admin",regex:"^.*(mongodb(\\+srv)?://).*$",icon:"mongodb",docsUrl:"https://www.mongodb.com/docs/manual/reference/method/",preferredAuthType:"connection_string",connectionFields:[{key:"host",label:"Host",placeholder:"cluster.example.com",required:!0},{key:"port",label:"Port",type:"number",defaultValue:"27017",placeholder:"27017"},{key:"database",label:"Database",placeholder:"mydb",required:!0},{key:"username",label:"Username",placeholder:"admin"},{key:"password",label:"Password",type:"password"}],keywords:["database","mongodb","mongo","nosql","document","collection","atlas"]},azure_sql:{name:"azure_sql",apiUrl:"mssql://<<user>>:<<password>>@<<host>>:1433/<<database>>",regex:"^.*(azure.*sql|sql.*azure|database\\.windows\\.net).*$",icon:"/logos/azure_sql.svg",docsUrl:"https://learn.microsoft.com/en-us/azure/azure-sql/",preferredAuthType:"connection_string",connectionFields:[{key:"host",label:"Host",placeholder:"myserver.database.windows.net",required:!0},{key:"database",label:"Database",placeholder:"mydb",required:!0},{key:"user",label:"Username",placeholder:"user@domain.com",required:!0},{key:"password",label:"Password",type:"password",required:!0},{key:"authType",label:"Auth Type",placeholder:"azure-active-directory-password"},{key:"clientId",label:"Client ID",placeholder:"App Registration client ID"},{key:"clientSecret",label:"Client Secret",type:"password",placeholder:"Service principal secret"},{key:"tenantId",label:"Tenant ID",placeholder:"Azure AD directory ID"}],systemSpecificInstructions:`Azure SQL supports two authentication modes:
369
369
 
370
370
  SQL Server Authentication (default): user + password in the connection URL. No additional fields needed.
@@ -541,6 +541,13 @@ WRITE SPECIFICS:
541
541
  - Setting lookups on write: use @odata.bind \u2014 e.g. "parentaccountid@odata.bind": "/accounts(<guid>)"
542
542
  - Disassociating a lookup: set the navigation property to null (without @odata.bind), e.g. "parentcustomerid_account": null
543
543
 
544
+ DATAVERSE CUSTOMIZATION:
545
+ - For specialized metadata, inspect an existing working object and adapt its structure. Do not invent undocumented definitions.
546
+ - Do not infer write properties from similarly named read properties.
547
+ - Treat metadata-write success as provisional. Read the object back and test its native behavior.
548
+ - Use type-specific metadata endpoints when inspecting specialized columns.
549
+ - Allow 120 seconds for metadata writes.
550
+
544
551
  RATE LIMITS (Service Protection):
545
552
  - 429 Too Many Requests returned when limits exceeded. Always implement Retry-After handling.
546
553
  - Per-user limits per 5-min window: 6,000 requests, 20 min combined execution time, 52+ concurrent requests.
@@ -1401,7 +1408,7 @@ ${s}`;break;case"retry":k5(s)&&(t[i]=s);break;case"id":A5(s)&&(t[i]=s);break;cas
1401
1408
  `);o.stack=t?`${t}
1402
1409
  ${s}`:i.stack}B.exports.fetch=function(e,t=void 0){return Lce(e,t).catch(a=>{throw B5?T5(a,B5):a&&typeof a=="object"&&Error.captureStackTrace(a,B.exports.fetch),a})};B.exports.Headers=Gs().Headers;B.exports.Response=_m().Response;B.exports.Request=bn().Request;B.exports.FormData=ud().FormData;var{setGlobalOrigin:Pce,getGlobalOrigin:Hce}=Ay();B.exports.setGlobalOrigin=Pce;B.exports.getGlobalOrigin=Hce;var{CacheStorage:Yce}=b9(),{kConstruct:Gce}=de();B.exports.caches=new Yce(Gce);var{deleteCookie:Vce,getCookies:Wce,getSetCookies:$ce,setCookie:Jce,parseCookie:Kce}=j9();B.exports.deleteCookie=Vce;B.exports.getCookies=Wce;B.exports.getSetCookies=$ce;B.exports.setCookie=Jce;B.exports.parseCookie=Kce;var{parseMIMEType:Zce,serializeAMimeType:Xce}=ht();B.exports.parseMIMEType=Zce;B.exports.serializeAMimeType=Xce;var{CloseEvent:eme,ErrorEvent:ome,MessageEvent:tme}=Qg(),{WebSocket:ame,ping:ime}=c5();B.exports.WebSocket=ame;B.exports.CloseEvent=eme;B.exports.ErrorEvent=ome;B.exports.MessageEvent=tme;B.exports.ping=ime;B.exports.WebSocketStream=f5().WebSocketStream;B.exports.WebSocketError=Jw().WebSocketError;B.exports.request=Km(Cn.request);B.exports.stream=Km(Cn.stream);B.exports.pipeline=Km(Cn.pipeline);B.exports.connect=Km(Cn.connect);B.exports.upgrade=Km(Cn.upgrade);B.exports.MockClient=Qce;B.exports.MockCallHistory=Bce;B.exports.MockCallHistoryLog=Sce;B.exports.MockPool=Rce;B.exports.MockAgent=Dce;B.exports.SnapshotAgent=Tce;B.exports.mockErrors=Nce;var{EventSource:sme}=Q5();B.exports.EventSource=sme;function rme(){globalThis.fetch=B.exports.fetch,globalThis.Headers=B.exports.Headers,globalThis.Response=B.exports.Response,globalThis.Request=B.exports.Request,globalThis.FormData=B.exports.FormData,globalThis.WebSocket=B.exports.WebSocket,globalThis.CloseEvent=B.exports.CloseEvent,globalThis.ErrorEvent=B.exports.ErrorEvent,globalThis.MessageEvent=B.exports.MessageEvent,globalThis.EventSource=B.exports.EventSource}B.exports.install=rme});var U5=y(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.SuperglueClient=Qn.SuperglueHttpError=void 0;var jn=at(),Ya=Gf(),nme=fb(),cme=$2(),mme=$t(),Ga=Er(),lme=yu(),Xm=14400*1e3,Zm;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:o}=N5();Zm=new o({headersTimeout:Xm,bodyTimeout:Xm})}catch{}var Hg=class extends Error{constructor(e,t,a,i){super(e),this.status=t,this.code=a,this.details=i,this.name="SuperglueHttpError"}};Qn.SuperglueHttpError=Hg;var tv=class{constructor({apiKey:e,apiEndpoint:t,onInfrastructureError:a,sseTokenProvider:i,tokenProvider:s}){if(!e&&!s)throw new Error("SuperglueClient requires either apiKey or tokenProvider");this.tokenProvider=s??(async()=>e),this.apiEndpoint=t??"https://api.superglue.cloud",this.sseManager=new nme.SSELogSubscriptionManager(this.apiEndpoint,i??this.tokenProvider),this.onInfrastructureError=a}async getApiKey(){return this.tokenProvider()}isInfrastructureError(e){return(0,mme.isAbortError)(e)?!1:!!(e instanceof TypeError&&e.message.toLowerCase().includes("fetch")||e instanceof Error&&e.name==="TimeoutError")}async restRequest(e,t,a,i,s){let n=await(await this.restResponse({method:e,path:t,body:a,extraHeaders:i,requestInit:s})).text();if(n)return JSON.parse(n)}async restResponse({method:e,path:t,body:a,extraHeaders:i,requestInit:s}){let r=`${this.apiEndpoint.replace(/\/$/,"")}${t}`,n=a!=null,c=typeof FormData<"u"&&a instanceof FormData,l={Authorization:`Bearer ${await this.getApiKey()}`,...i};n&&!c&&e!=="GET"&&(l["Content-Type"]="application/json");let u;try{u=await fetch(r,{...s,method:e,headers:l,body:n?c?a:JSON.stringify(a):void 0,signal:s?.signal??AbortSignal.timeout(Xm),...Zm?{dispatcher:Zm}:{}})}catch(d){throw this.isInfrastructureError(d)&&this.onInfrastructureError?.(),d}if(!u.ok)throw await this.buildHttpError(u);return u}async uploadFiles(e,t){if(typeof t?.process!="boolean")throw new Error("process must be a boolean");if(e.length===0)return[];let a=e.map(l=>({...l,contentLength:l.contentLength??this.getUploadContentLength(l.content)})),s=(await this.restRequest("POST","/v1/files/uploads",{process:t.process,files:a.map(({fileName:l,contentType:u,contentLength:d})=>({fileName:l,contentLength:d,...u?{contentType:u}:{}}))})).data.files;if(s.length!==a.length)throw await Promise.all(s.map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),new Error("Upload response did not match the selected files");let r=await Promise.allSettled(s.map(async(l,u)=>{let d=a[u],g=await fetch(l.uploadUrl,{method:"PUT",body:d.content,headers:d.contentType?{"Content-Type":d.contentType}:void 0,signal:AbortSignal.timeout(Math.min(Xm,l.expiresIn*1e3))});if(!g.ok)throw new Error(`Upload failed for ${d.fileName}: ${g.status} ${g.statusText}`);return l.id})),n=r.flatMap(l=>l.status==="fulfilled"?[l.value]:[]),c=new Map;if(n.length>0)try{let l=await this.restRequest("POST","/v1/files/uploads/complete",{fileIds:n});c=new Map(l.data.files.map(u=>[u.id,u]))}catch(l){c=new Map(n.map(u=>[u,{id:u,fileName:a[s.findIndex(d=>d.id===u)]?.fileName||u,contentLength:a[s.findIndex(d=>d.id===u)]?.contentLength||0,status:"failed",error:l instanceof Error?l.message:String(l)}]))}let m=s.map((l,u)=>{let d=r[u],g=a[u];return d.status==="rejected"?{id:l.id,fileName:g.fileName,contentLength:g.contentLength,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)}:c.get(l.id)||{id:l.id,fileName:g.fileName,contentLength:g.contentLength,status:"failed",error:"Upload completion returned no result"}});return await Promise.all(m.filter(l=>l.status==="failed").map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),m}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 t=await e.text(),a=`HTTP ${e.status}: ${t}`,i,s;try{let r=JSON.parse(t);r&&typeof r=="object"&&!Array.isArray(r)&&(s=r),typeof r?.code=="string"&&(i=r.code);let n=r.error;typeof n=="string"?a=n:n&&typeof n=="object"&&(a=n.message||JSON.stringify(n))}catch{}return new Hg(a,e.status,i,s)}async streamRequest(e,t,a){let i=e.includes("?")?"&":"?",s=`${this.apiEndpoint.replace(/\/$/,"")}${e}${i}stream=true`,n={Authorization:`Bearer ${await this.getApiKey()}`,Accept:"text/event-stream","Content-Type":"application/json"},c;try{c=await fetch(s,{method:"POST",headers:n,body:JSON.stringify(t),signal:a??AbortSignal.timeout(Xm),...Zm?{dispatcher:Zm}:{}})}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}if(!c.ok)throw await this.buildHttpError(c);if(!(c.headers.get("content-type")||"").includes("text/event-stream")){let l=await c.text();return l?JSON.parse(l):void 0}try{return await(0,cme.consumeEventStreamResult)(c)}catch(l){throw this.isInfrastructureError(l)&&this.onInfrastructureError?.(),l}}async subscribeToLogsSSE(e={}){return this.sseManager.subscribeToLogs(e)}async disconnect(){await this.sseManager.disconnect()}async getMe(){return this.restRequest("GET","/v1/me")}async runTool(e){let t=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:t.status==="success",data:t.data,error:t.error,tool:t.tool,stepResults:t.stepResults?.map(a=>({...a}))||[],...t.fileArtifacts&&t.fileArtifacts.length>0?{fileArtifacts:t.fileArtifacts}:{},...t.metadata?.warnings?.length?{warnings:t.metadata.warnings}:{}}}async runToolConfig(e){let t=e.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",a=await this.restRequest("POST",t,{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:a.status?a.status==="success":a.success??!1,data:a.data,error:a.error,tool:a.tool||e.tool,stepResults:a.stepResults?.map(s=>({...s}))||[],...a.fileArtifacts&&a.fileArtifacts.length>0?{fileArtifacts:a.fileArtifacts}:{},...a.metadata?.warnings?.length?{warnings:a.metadata.warnings}:{}}}async abortToolExecution(e){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(e)}/cancel`)).runId}}async executeStep({step:e,payload:t,files:a,previousResults:i,credentials:s,options:r,runId:n,systemIds:c,createRun:m,parentToolId:l,stepIndex:u,stepId:d,signal:g,stream:p}){let b={step:e,payload:t,files:a,previousResults:i,credentials:s,options:r,runId:n,systemIds:c,createRun:m,parentToolId:l,stepIndex:u,stepId:d};return p?this.streamRequest("/v1/tools/step/run",b,g):this.restRequest("POST","/v1/tools/step/run",b,void 0,g?{signal:g}:void 0)}async abortStep(e){return this.restRequest("POST","/v1/tools/step/abort",{runId:e})}async executeTransformOnly({outputTransform:e,outputSchema:t,inputSchema:a,payload:i,files:s,stepResults:r,options:n,runId:c,createRun:m,parentToolId:l,stepId:u,signal:d,stream:g}){let p={outputTransform:e,outputSchema:t,inputSchema:a,payload:i,files:s,stepResults:r,options:n,runId:c,createRun:m,parentToolId:l,stepId:u};return g?this.streamRequest("/v1/tools/transform/run",p,d):this.restRequest("POST","/v1/tools/transform/run",p,void 0,d?{signal:d}:void 0)}async createRun({toolId:e,toolConfig:t,toolResult:a,stepResults:i,toolPayload:s,status:r,error:n,startedAt:c,completedAt:m,executionKind:l,parentToolId:u,draftId:d}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:t,toolResult:a,stepResults:i,toolPayload:s,status:r,error:n,startedAt:(0,Ga.toUTCISOString)(c,"run.startedAt"),completedAt:(0,Ga.toUTCISOString)(m,"run.completedAt"),executionKind:l,parentToolId:u,draftId:d})}async checkRunLimit(){return(await this.restRequest("POST","/v1/runs/check-limit")).data}async extract({file:e,envelope:t}){if(!e)throw new Error("File must be provided for extract.");let a=new FormData;a.append("file",e);let i=t?"/v1/extract?envelope=true":"/v1/extract";return this.restRequest("POST",i,a)}mapOpenAPIRunToRun(e){let t={running:jn.RunStatus.RUNNING,success:jn.RunStatus.SUCCESS,failed:jn.RunStatus.FAILED,aborted:jn.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:t[e.status]??jn.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??jn.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,Ga.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,Ga.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,Ga.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,Ga.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e={}){let t=(0,Ya.createSearchListQueryParams)(e);e.toolId!==void 0&&t.set("toolId",e.toolId),e.searchUserIds?.length&&t.set("searchUserIds",e.searchUserIds.join(",")),e.includeTotal!==void 0&&t.set("includeTotal",String(e.includeTotal)),e.startedAfter!==void 0&&t.set("startedAfter",e.startedAfter instanceof Date?(0,Ga.toUTCISOString)(e.startedAfter,"run.startedAfter"):e.startedAfter),e.statuses!==void 0?t.set("status",e.statuses.join(",")):e.status!==void 0&&t.set("status",e.status),e.requestSources!==void 0&&t.set("requestSources",e.requestSources.join(",")),e.executionKinds!==void 0&&t.set("executionKinds",e.executionKinds.join(",")),e.userId!==void 0&&t.set("userId",e.userId),e.systemId!==void 0&&t.set("systemId",e.systemId),e.systemIds!==void 0&&t.set("systemIds",e.systemIds.join(","));let a=t.size>0?`?${t.toString()}`:"",i=await this.restRequest("GET",`/v1/runs${a}`,void 0,void 0,{signal:e.signal});return{data:i.data.map(s=>this.mapOpenAPIRunToRun(s)),total:i.total,page:i.page,limit:i.limit,hasMore:i.hasMore}}async getActivityCounts(e){let t=new URLSearchParams;e?.from&&t.set("from",e.from instanceof Date?(0,Ga.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&t.set("to",e.to instanceof Date?(0,Ga.toUTCISOString)(e.to,"activity.to"):e.to);let a=t.toString();return(await this.restRequest("GET",`/v1/activity/counts${a?`?${a}`:""}`,void 0,void 0,{signal:e?.signal})).counts}async getRun(e){try{let t=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(e)}`);return this.mapOpenAPIRunToRun(t)}catch(t){if(t.message?.includes("404")||t.message?.includes("not found"))return null;throw t}}async getTool(e){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}`)}catch(t){if(t.message?.includes("404")||t.message?.includes("not found")||t.message?.includes("403")||t.message?.includes("not allowed"))return null;throw t}}async getToolState(e){return(await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/state`)).state}async setToolState(e,t){await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/state`,{state:t})}async deleteToolState(e){return(await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/state`)).deletedKeys}async archiveTool(e,t=!0){return this.updateTool(e,{archived:t})}async bulkArchiveTools(e,t=!0){return this.restRequest("POST","/v1/tools/bulk/archive",{ids:e,archived:t})}async bulkDeleteTools(e){return this.restRequest("POST","/v1/tools/bulk/delete",{ids:e})}async listTools(e={}){let t=(0,Ya.createListQueryParams)(e);e.includeArchived!==void 0&&t.set("includeArchived",String(e.includeArchived));let a=t.size>0?`?${t.toString()}`:"";return this.restRequest("GET",`/v1/tools${a}`)}async listAllTools(e={}){return(0,Ya.listAllPages)((t,a)=>this.listTools({...e,page:t,limit:a}))}async createTool(e,t){return this.restRequest("POST","/v1/tools",{...t,id:e})}async updateTool(e,t){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}`,t)}async deleteTool(e){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}`),!0}catch(t){if(t.message?.includes("404"))return!1;throw t}}async renameTool(e,t){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/rename`,{newId:t})}async getWorkflow(e){return this.getTool(e)}async archiveWorkflow(e,t=!0){return this.upsertWorkflow(e,{archived:t})}async createWorkflow(e,t){return this.createTool(e,t)}async updateWorkflow(e,t){return this.updateTool(e,t)}async upsertWorkflow(e,t){return await this.getTool(e)?this.updateTool(e,t):this.createTool(e,t)}async deleteWorkflow(e){return this.deleteTool(e)}async renameWorkflow(e,t){return this.renameTool(e,t)}async listSchedules(e={}){let t=(0,Ya.createListQueryParams)(e),a=t.size>0?`?${t.toString()}`:"",i=e.toolId?`/v1/tools/${encodeURIComponent(e.toolId)}/schedules${a}`:`/v1/schedules${a}`,s=await this.restRequest("GET",i);return{...s,data:s.data.map(r=>this.mapOpenAPIScheduleToToolSchedule(r))}}async listAllSchedules(e={}){return(0,Ya.listAllPages)((t,a)=>this.listSchedules({...e,page:t,limit:a}))}async getToolSchedule(e,t){try{let a=await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`);return this.mapOpenAPIScheduleToToolSchedule(a)}catch(a){if(a.message?.includes("404")||a.message?.includes("not found"))return null;throw a}}async createToolSchedule(e,t){let a=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/schedules`,{...t,timezone:t.timezone||(0,lme.getRuntimeTimezone)()});return this.mapOpenAPIScheduleToToolSchedule(a)}async updateToolSchedule(e,t,a){let i=await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`,a);return this.mapOpenAPIScheduleToToolSchedule(i)}async deleteToolSchedule(e,t){return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(t)}`),!0}async bulkSetSchedulesEnabled(e,t){return this.restRequest("POST","/v1/schedules/bulk/enable",{ids:e,enabled:t})}async bulkDeleteSchedules(e){return this.restRequest("POST","/v1/schedules/bulk/delete",{ids:e})}async listCredentials(e={}){let t=(0,Ya.createListQueryParams)(e);e.systemId!==void 0&&t.set("systemId",e.systemId);let a=t.size>0?`?${t.toString()}`:"";return this.restRequest("GET",`/v1/credentials${a}`)}async listAllCredentials(e={}){return(0,Ya.listAllPages)((t,a)=>this.listCredentials({...e,page:t,limit:a}))}async createCredentials(e){return(await this.restRequest("POST","/v1/credentials",e)).data}async replaceCredentials(e,t){return(await this.restRequest("PUT",`/v1/credentials/${encodeURIComponent(e)}`,{credentials:t})).data}async updateCredentials(e,t){return(await this.restRequest("PATCH",`/v1/credentials/${encodeURIComponent(e)}`,t)).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 t=(0,Ya.createListQueryParams)(e),a=t.size>0?`?${t.toString()}`:"";return this.restRequest("GET",`/v1/systems${a}`)}async listAllSystems(e={}){return(0,Ya.listAllPages)((t,a)=>this.listSystems({...e,page:t,limit:a}))}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,t){return(await this.restRequest("PATCH",`/v1/systems/${encodeURIComponent(e)}`,t)).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,t){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/complete`,t)).data}async searchSystemDocumentation(e,t){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/search`,{keywords:t})).data}async triggerSystemDocumentationScrapeJob(e,t){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/scrape`,t)).data}async fetchOpenApiSpec(e,t,a){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/openapi`,{url:t,link:a?.link})).data}async uploadSystemDocumentationFiles(e,t,a){let i=await this.uploadFiles(t,{process:!0}),s=i.flatMap(r=>r.status==="uploaded"?[r.id]:[]);if(s.length>0)try{await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/files`,{fileIds:s,link:a?.link!==!1})}catch(r){throw await Promise.all(s.map(n=>this.deleteFileUpload(n).catch(()=>{}))),r}if(!a?.settle){let r=i.filter(n=>n.status==="failed");if(r.length>0)throw new Error(r.map(n=>n.error).join("; "))}return i}async listSystemDocumentationFiles(e,t){let a=new URLSearchParams;t?.length&&a.set("fileIds",t.join(","));let i=a.size>0?`?${a.toString()}`:"";return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files${i}`)).data}async getSystemDocumentationFileContent(e,t,a){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(t)}/content?processed=${a.processed}`)).data}async deleteSystemDocumentationFile(e,t){await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(t)}`)}async generateCredentialsLink(e){try{return{success:!0,credentialsUrl:(await this.restRequest("POST","/v1/authenticate",e||{})).data.credentialsUrl}}catch(t){return{success:!1,error:t.message}}}};Qn.SuperglueClient=tv});var _5=y(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.UnquotedKeyStrategy=Ce.TripleQuoteStrategy=Ce.TrailingCommaStrategy=Ce.SingleQuoteStrategy=Ce.PythonLiteralStrategy=Ce.CommentStrategy=Ce.ResilientJsonParser=Ce.RepairStrategy=void 0;Ce.parseJsonResilient=ume;Ce.parseJSON=dme;Ce.isValidJson=gme;Ce.prettyPrintJson=pme;Ce.minifyJson=hme;var Lt=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};Ce.RepairStrategy=Lt;var Yg=class extends Lt{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,(t,a)=>{let i=a.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let r=JSON.parse(i);return JSON.stringify(r)}catch{return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`})}};Ce.TripleQuoteStrategy=Yg;var Gg=class extends Lt{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")}};Ce.PythonLiteralStrategy=Gg;var Vg=class extends Lt{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")}};Ce.TrailingCommaStrategy=Vg;var Wg=class extends Lt{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 t=e.replace(/([{,]\s*)'([^']+)'(\s*:)/g,'$1"$2"$3');return t=t.replace(/(:\s*)'([^']+)'(\s*[,}])/g,'$1"$2"$3'),t}};Ce.SingleQuoteStrategy=Wg;var $g=class extends Lt{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')}};Ce.UnquotedKeyStrategy=$g;var Jg=class extends Lt{constructor(){super(...arguments),this.name="CommentRemoval",this.description="Removes JavaScript-style comments"}canApply(e){return/\/\/.*$|\/\*[\s\S]*?\*\//m.test(e)}apply(e){let t=e.replace(/\/\/.*$/gm,"");return t=t.replace(/\/\*[\s\S]*?\*\//g,""),t}};Ce.CommentStrategy=Jg;var av=class extends Lt{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(t){let a=t.message||"";return a.includes("control character")||a.includes("Bad control")||a.includes("Unexpected token")&&/[\n\r\t]/.test(e)}}apply(e){let t="",a=!1,i=!1;for(let s=0;s<e.length;s++){let r=e[s],n=s>0?e[s-1]:"";if(i){t+=r,i=!1;continue}if(r==="\\"&&a){t+=r,i=!0;continue}if(r==='"'&&n!=="\\"){a=!a,t+=r;continue}if(a)switch(r){case`
1403
1410
  `:t+="\\n";break;case"\r":t+="\\r";break;case" ":t+="\\t";break;case"\b":t+="\\b";break;case"\f":t+="\\f";break;default:let c=r.charCodeAt(0);c<32?t+="\\u"+("0000"+c.toString(16)).slice(-4):t+=r}else t+=r}return t}},iv=class extends Lt{constructor(){super(...arguments),this.name="TrailingCharactersRepair",this.description="Removes trailing characters after valid JSON structure"}canApply(e){let t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return!1;let a=0,i=0,s=!1,r=!1;for(let n=0;n<t.length;n++){let c=t[n];if(s)r?r=!1:c==="\\"?r=!0:c==='"'&&(s=!1);else if(c==='"')s=!0;else if(c==="{")a++;else if(c==="}"){if(a--,a===0&&i===0&&n>0&&n<t.length-1)return!0}else if(c==="[")i++;else if(c==="]"&&(i--,i===0&&a===0&&n>0&&n<t.length-1))return!0}return!1}apply(e){let t=e.trim(),a=0,i=0,s=!1,r=!1,n=-1;for(let c=0;c<t.length;c++){let m=t[c];if(s)r?r=!1:m==="\\"?r=!0:m==='"'&&(s=!1);else if(m==='"')s=!0;else if(m==="{")a++;else if(m==="}"){if(a--,a===0&&i===0&&c>0){n=c;break}}else if(m==="[")i++;else if(m==="]"&&(i--,i===0&&a===0&&c>0)){n=c;break}}return n>0&&n<t.length-1?t.substring(0,n+1):e}},Bn=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 Yg,new Wg,new av,new iv,new Gg,new Vg,new $g,new Jg]}parse(e){let t=Date.now();this.repairLog=[];let a=e instanceof Buffer?e.toString("utf8"):String(e);try{return{success:!0,data:JSON.parse(a),metadata:{parseTime:Date.now()-t,strategiesApplied:[]}}}catch(r){if(!this.options.attemptRepair)return{success:!1,error:`JSON parse error: ${r}`,metadata:{parseTime:Date.now()-t}}}let i=a,s=[];for(let r of this.strategies)if(r.canApply(i)){let n=i;if(i=r.apply(i),n!==i){s.push(r.name),this.repairLog.push(r.description),this.options.logRepairs&&console.log(`Applied ${r.name}: ${r.description}`);try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-t,strategiesApplied:s}}}catch{}}}try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-t,strategiesApplied:s}}}catch(r){let n=this.aggressiveFallback(i);return n.success?{...n,repairs:[...this.repairLog,"Applied aggressive fallback"],metadata:{parseTime:Date.now()-t,strategiesApplied:[...s,"AggressiveFallback"]}}:{success:!1,error:`Failed to parse JSON after applying ${s.length} strategies: ${r}`,repairs:this.repairLog,metadata:{parseTime:Date.now()-t,strategiesApplied:s}}}}aggressiveFallback(e){try{let t=e.indexOf("{"),a=e.indexOf("[");if(t===-1&&a===-1)return{success:!1,error:"No JSON-like structure found"};let i=t===-1?a:a===-1?t:Math.min(t,a),s=e.substring(i);for(let n of this.strategies)n.canApply(s)&&(s=n.apply(s));return{success:!0,data:JSON.parse(s)}}catch(t){return{success:!1,error:`Aggressive fallback failed: ${t}`}}}addStrategy(e){this.strategies.push(e)}removeStrategy(e){this.strategies=this.strategies.filter(t=>t.name!==e)}getStrategies(){return this.strategies.map(e=>e.name)}};Ce.ResilientJsonParser=Bn;var M5=new Bn;function ume(o,e){return(e?new Bn(e):M5).parse(o)}function dme(o){let e=M5.parse(o);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 gme(o){try{return JSON.parse(o),!0}catch{return!1}}function pme(o,e=2){return JSON.stringify(o,null,e)}function hme(o){let t=new Bn().parse(o);if(t.success)return JSON.stringify(t.data);throw new Error("Cannot minify invalid JSON")}});var et=y(L=>{"use strict";var fme=L&&L.__createBinding||(Object.create?(function(o,e,t,a){a===void 0&&(a=t);var i=Object.getOwnPropertyDescriptor(e,t);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[t]}}),Object.defineProperty(o,a,i)}):(function(o,e,t,a){a===void 0&&(a=t),o[a]=e[t]})),X=L&&L.__exportStar||function(o,e){for(var t in o)t!=="default"&&!Object.prototype.hasOwnProperty.call(e,t)&&fme(e,o,t)};Object.defineProperty(L,"__esModule",{value:!0});L.SSELogSubscriptionManager=L.SuperglueHttpError=L.SuperglueClient=void 0;X(eE(),L);X(lE(),L);X(hE(),L);X(kE(),L);X(Nc(),L);X(TE(),L);X(NE(),L);X(UE(),L);X(ME(),L);X(Gf(),L);X(OE(),L);X(FE(),L);X(LE(),L);X(HE(),L);X(YE(),L);X(VE(),L);X(bl(),L);X($E(),L);X(JE(),L);X(ZE(),L);X(o2(),L);X(a2(),L);X(m2(),L);X(u2(),L);X(g2(),L);X(z2(),L);X(E2(),L);X(rb(),L);X(N2(),L);X(gb(),L);X(O2(),L);X(H2(),L);X(G2(),L);X(at(),L);X($t(),L);X(V2(),L);X(W2(),L);X(Su(),L);X(Er(),L);X(yu(),L);var O5=U5();Object.defineProperty(L,"SuperglueClient",{enumerable:!0,get:function(){return O5.SuperglueClient}});Object.defineProperty(L,"SuperglueHttpError",{enumerable:!0,get:function(){return O5.SuperglueHttpError}});var bme=fb();Object.defineProperty(L,"SSELogSubscriptionManager",{enumerable:!0,get:function(){return bme.SSELogSubscriptionManager}});X(_5(),L)});var Qp=require("commander");var Do=$(require("fs")),P5=$(require("os")),Va=$(require("path")),el=$(et()),F5=new Set(["runner","builder","admin"]),L5={output:{mode:"stdout",directory:".superglue/output"},preset:"admin"};function Wa(o){let e=Va.join(process.cwd(),".superglue"),t=P5.homedir();if(!t)return e;let a=Va.join(t,".superglue");return o===!0?e:o===!1?a:Do.existsSync(Va.join(e,"config.json"))?e:a}function sv(o){return Va.join(Wa(o),"config.json")}function Kg(o){let e=sv(o);if(!Do.existsSync(e))return{};try{return JSON.parse(Do.readFileSync(e,"utf-8"))}catch{return{}}}function Sn(o){let e=Kg(),t=o.apiKey||(0,el.readProcessEnvironmentValue)("SUPERGLUE_API_KEY")||e.apiKey||"",a=o.endpoint||(0,el.readProcessEnvironmentValue)("SUPERGLUE_API_ENDPOINT")||e.endpoint||"https://api.superglue.cloud",i=(0,el.readProcessEnvironmentValue)("SUPERGLUE_WEB_ENDPOINT")||e.webEndpoint||a.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue"),s=(0,el.readProcessEnvironmentValue)("SUPERGLUE_CLI_PRESET"),r=s&&F5.has(s)?s:e.preset&&F5.has(e.preset)?e.preset:"admin";return{...L5,...e,apiKey:t,endpoint:a,webEndpoint:i,preset:r,output:{...L5.output,...e.output}}}function Zg(o,e){let t=Wa(e);Do.existsSync(t)||Do.mkdirSync(t,{recursive:!0}),Do.writeFileSync(Va.join(t,"config.json"),JSON.stringify(o,null,2)+`
1404
- `,{mode:384})}function Xg(o,e){let t=Va.join(Wa(e),"drafts");if(Do.existsSync(t)||Do.mkdirSync(t,{recursive:!0}),o.output.mode==="stdout+file"){let a=Va.resolve(o.output.directory);Do.existsSync(a)||Do.mkdirSync(a,{recursive:!0})}}var dv=$(et());var rv=$(require("readline"));var G5=require("child_process"),V5=require("util");var H5={name:"@superglue/cli",version:"1.1.59",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 kme=(0,V5.promisify)(G5.exec),wo=H5.version;function Y5(o){let e=o.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:o}}function op(o,e){let t=o.split("."),a=e.split("."),i=Math.max(t.length,a.length);for(let s=0;s<i;s++){let r=Y5(t[s]||"0"),n=Y5(a[s]||"0");if(r.numeric<n.numeric)return-1;if(r.numeric>n.numeric||r.prerelease===null&&n.prerelease!==null)return 1;if(r.prerelease!==null&&n.prerelease===null)return-1;if(r.prerelease!==null&&n.prerelease!==null){if(r.prerelease<n.prerelease)return-1;if(r.prerelease>n.prerelease)return 1}}return 0}async function tp(){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 ep=null;function W5(){Y()&&(ep=tp())}async function $5(){if(!(!Y()||!ep)){try{let o=new Promise(t=>{setTimeout(()=>t(null),2e3).unref()}),e=await Promise.race([ep,o]);e&&op(wo,e)<0&&(console.error(""),console.error(`${h.cyan}${h.bold} Update available: ${wo} \u2192 ${e}${h.reset}`),console.error(`${h.cyan} Run ${h.bold}sg update${h.reset}${h.cyan} to upgrade${h.reset}`),console.error(""))}catch{}ep=null}}async function J5(){let o=await tp();if(!o)return{success:!1,message:"Could not fetch latest version from npm"};if(op(wo,o)>=0)return{success:!0,message:`Already on latest version (${wo})`};try{return await kme("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${wo} to ${o}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var Y=()=>process.argv.includes("--table")&&process.stdout.isTTY,zt=()=>process.argv.includes("--full"),h={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 K5(o,e){let t=e||o;return`\x1B]8;;${o}\x07${h.underline}${h.cyan}${t}${h.reset}\x1B]8;;\x07`}function Z5(){if(!Y())return;let o=h.reset,e=h.dim,t="\x1B[47;30m",a=[" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@- "," =@@@- @@@@ "," @@@ @@% "," -@@ @@@@= @@@ @@@ @@@@@#@ @@@@@@@ @@@@@@@ @@@@@@ @@@ @@@ @@@ @@@@@@* %@@ "," @@ @@@ *@ @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @% @@@ @@@ @@@ @@* @@# "," #@@ @@@# @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @@@ @@@ @@@ @@* @@ "," @@- @@@@= @@@ @@@ @@@@@@@ @@@@@@ @@@@@@@ @@@ @@% @@@ @@@ @@@ @@@@@. @@."," #@% .@@@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* @@ "," @@ @ @@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* *@@ "," -@@ @@@@= @@@@@@ @@@ @@@@@@@ @@@ -@@ @@@@@@ @@@@@@% @@@@@@. @@@@@@* #@@ "," :@@* @@@ "," %@@@ =@@@. "," :@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% "];console.log(""),a.forEach(i=>{let s=i.search(/\S/),r=i.length-[...i].reverse().join("").search(/\S/)-1;if(s===-1)return console.log(" "+i);let n=i.slice(0,s),c=i.slice(s,r+1).split("").map(l=>l===" "?" ":"\u2588").join(""),m=i.slice(r+1);console.log(` ${n}${t}${c}${o}${m}`)}),console.log(` ${e} CLI v${wo}${o}`),console.log("")}function Ee(o){if(!Y())return{stop:()=>{},update:()=>{},log:()=>{}};let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],t=0,a=o,i=()=>process.stdout.write("\r\x1B[2K"),s=()=>{process.stdout.write(`\r ${h.cyan}${e[t++%e.length]}${h.reset} ${a}`)},r=setInterval(s,80);return{update:n=>{a=n},log:n=>{i(),console.log(` ${h.dim}\u2502${h.reset} ${n}`),s()},stop:n=>{clearInterval(r),i(),n&&console.log(` ${n}`)}}}function U(o){Y()?ap(o):console.log(JSON.stringify(o,null,2))}function se(o,e){Y()?(console.log(` ${h.green}\u2713${h.reset} ${o}`),e&&ap(e,4)):console.log(JSON.stringify({success:!0,message:o,...e&&typeof e=="object"?e:{data:e}}))}function z(o,e){Y()?(console.error(` ${h.red}\u2717${h.reset} ${o}`),e&&ap(e,4)):console.error(JSON.stringify({success:!1,error:o,details:e}))}function X5(o){Y()&&console.log(` ${h.yellow}\u26A0${h.reset} ${o}`)}function lo(o){Y()&&console.log(` ${h.dim}${o}${h.reset}`)}function $a(o){Y()&&(console.log(`
1411
+ `,{mode:384})}function Xg(o,e){let t=Va.join(Wa(e),"drafts");if(Do.existsSync(t)||Do.mkdirSync(t,{recursive:!0}),o.output.mode==="stdout+file"){let a=Va.resolve(o.output.directory);Do.existsSync(a)||Do.mkdirSync(a,{recursive:!0})}}var dv=$(et());var rv=$(require("readline"));var G5=require("child_process"),V5=require("util");var H5={name:"@superglue/cli",version:"1.1.61",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 kme=(0,V5.promisify)(G5.exec),wo=H5.version;function Y5(o){let e=o.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:o}}function op(o,e){let t=o.split("."),a=e.split("."),i=Math.max(t.length,a.length);for(let s=0;s<i;s++){let r=Y5(t[s]||"0"),n=Y5(a[s]||"0");if(r.numeric<n.numeric)return-1;if(r.numeric>n.numeric||r.prerelease===null&&n.prerelease!==null)return 1;if(r.prerelease!==null&&n.prerelease===null)return-1;if(r.prerelease!==null&&n.prerelease!==null){if(r.prerelease<n.prerelease)return-1;if(r.prerelease>n.prerelease)return 1}}return 0}async function tp(){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 ep=null;function W5(){Y()&&(ep=tp())}async function $5(){if(!(!Y()||!ep)){try{let o=new Promise(t=>{setTimeout(()=>t(null),2e3).unref()}),e=await Promise.race([ep,o]);e&&op(wo,e)<0&&(console.error(""),console.error(`${h.cyan}${h.bold} Update available: ${wo} \u2192 ${e}${h.reset}`),console.error(`${h.cyan} Run ${h.bold}sg update${h.reset}${h.cyan} to upgrade${h.reset}`),console.error(""))}catch{}ep=null}}async function J5(){let o=await tp();if(!o)return{success:!1,message:"Could not fetch latest version from npm"};if(op(wo,o)>=0)return{success:!0,message:`Already on latest version (${wo})`};try{return await kme("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${wo} to ${o}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var Y=()=>process.argv.includes("--table")&&process.stdout.isTTY,zt=()=>process.argv.includes("--full"),h={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 K5(o,e){let t=e||o;return`\x1B]8;;${o}\x07${h.underline}${h.cyan}${t}${h.reset}\x1B]8;;\x07`}function Z5(){if(!Y())return;let o=h.reset,e=h.dim,t="\x1B[47;30m",a=[" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@- "," =@@@- @@@@ "," @@@ @@% "," -@@ @@@@= @@@ @@@ @@@@@#@ @@@@@@@ @@@@@@@ @@@@@@ @@@ @@@ @@@ @@@@@@* %@@ "," @@ @@@ *@ @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @% @@@ @@@ @@@ @@* @@# "," #@@ @@@# @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @@@ @@@ @@@ @@* @@ "," @@- @@@@= @@@ @@@ @@@@@@@ @@@@@@ @@@@@@@ @@@ @@% @@@ @@@ @@@ @@@@@. @@."," #@% .@@@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* @@ "," @@ @ @@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* *@@ "," -@@ @@@@= @@@@@@ @@@ @@@@@@@ @@@ -@@ @@@@@@ @@@@@@% @@@@@@. @@@@@@* #@@ "," :@@* @@@ "," %@@@ =@@@. "," :@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% "];console.log(""),a.forEach(i=>{let s=i.search(/\S/),r=i.length-[...i].reverse().join("").search(/\S/)-1;if(s===-1)return console.log(" "+i);let n=i.slice(0,s),c=i.slice(s,r+1).split("").map(l=>l===" "?" ":"\u2588").join(""),m=i.slice(r+1);console.log(` ${n}${t}${c}${o}${m}`)}),console.log(` ${e} CLI v${wo}${o}`),console.log("")}function Ee(o){if(!Y())return{stop:()=>{},update:()=>{},log:()=>{}};let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],t=0,a=o,i=()=>process.stdout.write("\r\x1B[2K"),s=()=>{process.stdout.write(`\r ${h.cyan}${e[t++%e.length]}${h.reset} ${a}`)},r=setInterval(s,80);return{update:n=>{a=n},log:n=>{i(),console.log(` ${h.dim}\u2502${h.reset} ${n}`),s()},stop:n=>{clearInterval(r),i(),n&&console.log(` ${n}`)}}}function U(o){Y()?ap(o):console.log(JSON.stringify(o,null,2))}function se(o,e){Y()?(console.log(` ${h.green}\u2713${h.reset} ${o}`),e&&ap(e,4)):console.log(JSON.stringify({success:!0,message:o,...e&&typeof e=="object"?e:{data:e}}))}function z(o,e){Y()?(console.error(` ${h.red}\u2717${h.reset} ${o}`),e&&ap(e,4)):console.error(JSON.stringify({success:!1,error:o,details:e}))}function X5(o){Y()&&console.log(` ${h.yellow}\u26A0${h.reset} ${o}`)}function lo(o){Y()&&console.log(` ${h.dim}${o}${h.reset}`)}function $a(o){Y()&&(console.log(`
1405
1412
  ${h.bold}${h.cyan}${o}${h.reset}`),console.log(` ${h.dim}${"\u2500".repeat(o.length)}${h.reset}`))}function da(o,e,t){if(!Y()){console.log(JSON.stringify({success:!0,total:t?.total??o.length,items:o}));return}if(o.length===0){console.log(`
1406
1413
  ${h.dim}0 results${h.reset}
1407
1414
  `);return}let a=e||Object.keys(o[0]),i=zt()?1/0:60,s=a.map(l=>Math.min(i,Math.max(l.length,...o.map(u=>String(u[l]??"").replace(/[\n\r]+/g," ").trim().length))));console.log("");let r=a.map((l,u)=>`${h.bold}${h.cyan}${l.toUpperCase().padEnd(s[u])}${h.reset}`).join(" ");console.log(` ${r}`);let n=s.map(l=>`${h.dim}${"\u2500".repeat(l)}${h.reset}`).join(`${h.dim}\u2500\u2500${h.reset}`);console.log(` ${n}`);for(let l of o){let u=a.map((d,g)=>{let p=String(l[d]??"").replace(/[\n\r]+/g," ").trim();if(p.length>i){let w=`\u2026 (${p.length})`;p=p.slice(0,Math.max(0,i-w.length))+`${h.dim}${w}${h.reset}`}return d==="status"?`${{success:h.green,running:h.yellow,failed:h.red,aborted:h.red,error:h.red,pending:h.dim}[p.toLowerCase()]||""}${p.padEnd(s[g])}${h.reset}`:p.padEnd(s[g])}).join(" ");console.log(` ${u}`)}let c=t?.total??o.length,m=c===o.length?`${o.length} result${o.length===1?"":"s"}`:`${o.length} of ${c} result${c===1?"":"s"}`;console.log(`
@@ -1445,7 +1452,7 @@ Provide --draft or --tool. Editing a saved tool creates a new draft.
1445
1452
  Returns: { success, draftId, draftPath, diffs }
1446
1453
 
1447
1454
  Run 'sg skill' for common patch patterns and the build\u2192run\u2192edit\u2192save workflow.
1448
- `).action(async t=>{!t.draft&&!t.tool&&(z("Provide --draft or --tool"),process.exit(1)),t.patches||(z("--patches is required"),process.exit(1));let a;try{let l=kp.existsSync(t.patches)?kp.readFileSync(t.patches,"utf-8"):t.patches;a=JSON.parse(l),Array.isArray(a)||(a=[a])}catch(l){z(`Invalid patches: ${l.message}`),process.exit(1)}let i,s;if(t.tool)try{let{client:l}=e(),u=await l.getWorkflow(t.tool);u||(z(`Tool not found: ${t.tool}`),process.exit(1)),i=u,s=`fix-${t.tool}-${Date.now()}`}catch(l){z(l.message),process.exit(1)}else{let l=Nn(t.draft);l||(z(`Draft not found: ${t.draft}`),process.exit(1)),i=l.config,s=t.draft}let r;try{let l=JSON.parse(JSON.stringify(i)),u=x6.applyPatch(l,a,!0,!0);r=(0,v6.normalizeToolSchemas)(u.newDocument||l)}catch(l){z(`Patch failed: ${l.message}`),process.exit(1)}let n=a.map(l=>({op:l.op,path:l.path,..."value"in l?{value:l.value}:{},..."from"in l&&l.from?{from:l.from}:{}}));Y()&&($a("Proposed Changes"),console.log(e6(n)),console.log(""));let c={draftId:s,config:{...r,instruction:r.instruction??i.instruction,updatedAt:new Date().toISOString()},systemIds:r.systemIds||[],instruction:r.instruction??"",createdAt:new Date().toISOString()};gp(c);let m=Ja(s);Y()?(se(`Draft updated: ${h.bold}${s}${h.reset}`),console.log(` ${h.dim}draft file:${h.reset} ${m}`),console.log("")):U({success:!0,draftId:s,draftPath:m,diffs:n})})}function q6(o,e){o.command("save").description("Persist a draft tool to the database").requiredOption("--draft <id>","Draft ID to save").option("--id <customId>","Custom ID for the saved tool").action(async t=>{let{config:a,client:i}=e(),s=Nn(t.draft);s||(z(`Draft not found: ${t.draft}`),process.exit(1));let r=t.id||s.config.id,n=Ja(t.draft),c=Ee(`Saving tool ${h.bold}${r}${h.reset}...`);try{let m=await i.upsertWorkflow(r,{...s.config,id:r,systemIds:s.systemIds});b6(t.draft),c.stop();let l=a.endpoint;Y()?(se(`Tool saved: ${h.bold}${m.id}${h.reset}`),console.log(` ${h.dim}webhook:${h.reset} ${l}/v1/hooks/${m.id}`),console.log(` ${h.dim}draft ${t.draft} deleted:${h.reset} ${n}`),console.log("")):U({success:!0,toolId:m.id,deletedDraftPath:n,webhookUrl:`${l}/v1/hooks/${m.id}?token=YOUR_API_KEY`})}catch(m){c.stop(),z(m.message),process.exit(1)}})}var E6=$(et());async function Ap({fetchPage:o,limit:e,offset:t}){let a=Math.floor(t/e)+1,i=t%e,s=await o(a,e),r=s.data.slice(i);if(r.length<e&&t+r.length<s.total){let n=await o(a+1,e);r.push(...n.data.slice(0,e-r.length))}return{items:r,total:s.total,hasMore:t+r.length<s.total}}function I6(o,e){o.command("list").description("List all tools").option("--limit <n>","Max results","25").option("--offset <n>","Skip first N results","0").action(async t=>{let{client:a}=e();try{let i=Math.min(Math.max(parseInt(t.limit,10)||25,1),E6.LIST_MAX_LIMIT),s=Math.max(parseInt(t.offset,10)||0,0),{items:r,total:n,hasMore:c}=await Ap({limit:i,offset:s,fetchPage:(u,d)=>a.listTools({limit:d,page:u})}),m=zt(),l=r.map(u=>({id:u.id,instruction:m?u.instruction||"":(u.instruction||"").slice(0,60),steps:u.steps?.length||0}));Y()?da(l,["id","instruction","steps"],{total:n}):U({success:!0,total:n,hasMore:c,items:l})}catch(i){z(i.message),process.exit(1)}}),o.command("find [query]").description("Find tools by query or exact ID").option("--id <exactId>","Exact tool ID lookup").option("--fields <fields>","Comma-separated top-level fields to return (requires --id), e.g. instruction,inputSchema").action(async(t,a)=>{let{client:i}=e();try{if(a.fields&&!a.id&&(z("--fields requires --id (field selection only applies to exact-ID lookups)"),process.exit(1)),a.id){let m=await i.getWorkflow(a.id);if(m||(z(`Tool not found: ${a.id}`),process.exit(1)),a.fields){let l=a.fields.split(",").map(p=>p.trim()).filter(Boolean),u=Object.keys(m),d=l.filter(p=>!u.includes(p)),g=Object.fromEntries(l.filter(p=>u.includes(p)).map(p=>[p,m[p]]));U({success:!0,tool:g,...d.length?{unknownFields:d,availableFields:u}:{}});return}U({success:!0,tool:m});return}let s=(t||"").trim()||"*",r=await i.listAllTools(),n=s==="*"?r:(()=>{let m=s.toLowerCase().split(/\s+/).filter(d=>d.length>0),u=r.map(d=>{let g=[d.id,d.name,d.instruction].filter(Boolean).join(" ").toLowerCase();return{tool:d,score:m.filter(p=>g.includes(p)).length}}).filter(d=>d.score>0);return u.sort((d,g)=>g.score-d.score),u.map(d=>d.tool)})(),c=zt();U({success:!0,total:n.length,items:n.map(m=>({id:m.id,instruction:c?m.instruction||"":(m.instruction||"").slice(0,80),steps:m.steps?.length||0}))})}catch(s){z(s.message),process.exit(1)}})}var C6=$(require("fs"));function Fme(o){!o.state&&!o.stateFile&&(z("Provide --state <json> or --state-file <path>"),process.exit(1)),o.state&&o.stateFile&&(z("Only one of --state or --state-file can be used"),process.exit(1));let e;try{e=JSON.parse(o.stateFile?C6.readFileSync(o.stateFile,"utf-8"):o.state)}catch(t){z(`Invalid state JSON: ${t.message}`),process.exit(1)}return(e===null||typeof e!="object"||Array.isArray(e))&&(z("State must be a plain JSON object"),process.exit(1)),e}function j6(o,e){let t=o.command("state").description("Inspect, set, or reset a saved tool's persistent state");t.command("get <toolId>").description("Show the tool's current persistent state").action(async a=>{let{client:i}=e();try{let s=await i.getToolState(a);U({success:!0,toolId:a,state:s})}catch(s){z(s.message),process.exit(1)}}),t.command("set <toolId>").description("Replace the tool's persistent state (full replace)").option("--state <json>","Replacement state JSON object").option("--state-file <path>","Replacement state JSON file").addHelpText("after",`
1455
+ `).action(async t=>{!t.draft&&!t.tool&&(z("Provide --draft or --tool"),process.exit(1)),t.patches||(z("--patches is required"),process.exit(1));let a;try{let l=kp.existsSync(t.patches)?kp.readFileSync(t.patches,"utf-8"):t.patches;a=JSON.parse(l),Array.isArray(a)||(a=[a])}catch(l){z(`Invalid patches: ${l.message}`),process.exit(1)}let i,s;if(t.tool)try{let{client:l}=e(),u=await l.getWorkflow(t.tool);u||(z(`Tool not found: ${t.tool}`),process.exit(1)),i=u,s=`fix-${t.tool}-${Date.now()}`}catch(l){z(l.message),process.exit(1)}else{let l=Nn(t.draft);l||(z(`Draft not found: ${t.draft}`),process.exit(1)),i=l.config,s=t.draft}let r;try{let l=JSON.parse(JSON.stringify(i)),u=x6.applyPatch(l,a,!0,!0);r=(0,v6.normalizeToolSchemas)(u.newDocument||l)}catch(l){z(`Patch failed: ${l.message}`),process.exit(1)}let n=a.map(l=>({op:l.op,path:l.path,..."value"in l?{value:l.value}:{},..."from"in l&&l.from?{from:l.from}:{}}));Y()&&($a("Proposed Changes"),console.log(e6(n)),console.log(""));let c={draftId:s,config:{...r,instruction:r.instruction??i.instruction,updatedAt:new Date().toISOString()},systemIds:r.systemIds||[],instruction:r.instruction??"",createdAt:new Date().toISOString()};gp(c);let m=Ja(s);Y()?(se(`Draft updated: ${h.bold}${s}${h.reset}`),console.log(` ${h.dim}draft file:${h.reset} ${m}`),console.log("")):U({success:!0,draftId:s,draftPath:m,diffs:n})})}function q6(o,e){o.command("save").description("Persist a draft tool to the database").requiredOption("--draft <id>","Draft ID to save").option("--id <customId>","Custom ID for the saved tool").action(async t=>{let{config:a,client:i}=e(),s=Nn(t.draft);s||(z(`Draft not found: ${t.draft}`),process.exit(1));let r=t.id||s.config.id,n=Ja(t.draft),c=Ee(`Saving tool ${h.bold}${r}${h.reset}...`);try{let m=await i.upsertWorkflow(r,{...s.config,id:r});b6(t.draft),c.stop();let l=a.endpoint;Y()?(se(`Tool saved: ${h.bold}${m.id}${h.reset}`),console.log(` ${h.dim}webhook:${h.reset} ${l}/v1/hooks/${m.id}`),console.log(` ${h.dim}draft ${t.draft} deleted:${h.reset} ${n}`),console.log("")):U({success:!0,toolId:m.id,deletedDraftPath:n,webhookUrl:`${l}/v1/hooks/${m.id}?token=YOUR_API_KEY`})}catch(m){c.stop(),z(m.message),process.exit(1)}})}var E6=$(et());async function Ap({fetchPage:o,limit:e,offset:t}){let a=Math.floor(t/e)+1,i=t%e,s=await o(a,e),r=s.data.slice(i);if(r.length<e&&t+r.length<s.total){let n=await o(a+1,e);r.push(...n.data.slice(0,e-r.length))}return{items:r,total:s.total,hasMore:t+r.length<s.total}}function I6(o,e){o.command("list").description("List all tools").option("--limit <n>","Max results","25").option("--offset <n>","Skip first N results","0").action(async t=>{let{client:a}=e();try{let i=Math.min(Math.max(parseInt(t.limit,10)||25,1),E6.LIST_MAX_LIMIT),s=Math.max(parseInt(t.offset,10)||0,0),{items:r,total:n,hasMore:c}=await Ap({limit:i,offset:s,fetchPage:(u,d)=>a.listTools({limit:d,page:u})}),m=zt(),l=r.map(u=>({id:u.id,instruction:m?u.instruction||"":(u.instruction||"").slice(0,60),steps:u.steps?.length||0}));Y()?da(l,["id","instruction","steps"],{total:n}):U({success:!0,total:n,hasMore:c,items:l})}catch(i){z(i.message),process.exit(1)}}),o.command("find [query]").description("Find tools by query or exact ID").option("--id <exactId>","Exact tool ID lookup").option("--fields <fields>","Comma-separated top-level fields to return (requires --id), e.g. instruction,inputSchema").action(async(t,a)=>{let{client:i}=e();try{if(a.fields&&!a.id&&(z("--fields requires --id (field selection only applies to exact-ID lookups)"),process.exit(1)),a.id){let m=await i.getWorkflow(a.id);if(m||(z(`Tool not found: ${a.id}`),process.exit(1)),a.fields){let l=a.fields.split(",").map(p=>p.trim()).filter(Boolean),u=Object.keys(m),d=l.filter(p=>!u.includes(p)),g=Object.fromEntries(l.filter(p=>u.includes(p)).map(p=>[p,m[p]]));U({success:!0,tool:g,...d.length?{unknownFields:d,availableFields:u}:{}});return}U({success:!0,tool:m});return}let s=(t||"").trim()||"*",r=await i.listAllTools(),n=s==="*"?r:(()=>{let m=s.toLowerCase().split(/\s+/).filter(d=>d.length>0),u=r.map(d=>{let g=[d.id,d.name,d.instruction].filter(Boolean).join(" ").toLowerCase();return{tool:d,score:m.filter(p=>g.includes(p)).length}}).filter(d=>d.score>0);return u.sort((d,g)=>g.score-d.score),u.map(d=>d.tool)})(),c=zt();U({success:!0,total:n.length,items:n.map(m=>({id:m.id,instruction:c?m.instruction||"":(m.instruction||"").slice(0,80),steps:m.steps?.length||0}))})}catch(s){z(s.message),process.exit(1)}})}var C6=$(require("fs"));function Fme(o){!o.state&&!o.stateFile&&(z("Provide --state <json> or --state-file <path>"),process.exit(1)),o.state&&o.stateFile&&(z("Only one of --state or --state-file can be used"),process.exit(1));let e;try{e=JSON.parse(o.stateFile?C6.readFileSync(o.stateFile,"utf-8"):o.state)}catch(t){z(`Invalid state JSON: ${t.message}`),process.exit(1)}return(e===null||typeof e!="object"||Array.isArray(e))&&(z("State must be a plain JSON object"),process.exit(1)),e}function j6(o,e){let t=o.command("state").description("Inspect, set, or reset a saved tool's persistent state");t.command("get <toolId>").description("Show the tool's current persistent state").action(async a=>{let{client:i}=e();try{let s=await i.getToolState(a);U({success:!0,toolId:a,state:s})}catch(s){z(s.message),process.exit(1)}}),t.command("set <toolId>").description("Replace the tool's persistent state (full replace)").option("--state <json>","Replacement state JSON object").option("--state-file <path>","Replacement state JSON file").addHelpText("after",`
1449
1456
  Replaces all keys, subject to the same key and size limits as run-time state writes.
1450
1457
  State is stored unencrypted; never put credential values in it.
1451
1458
  `).action(async(a,i)=>{let{client:s}=e(),r=Fme(i);try{await s.setToolState(a,r),U({success:!0,toolId:a,keyCount:Object.keys(r).length})}catch(n){z(n.message),process.exit(1)}}),t.command("reset <toolId>").description("Delete all persistent state keys so the next run cold-starts").action(async a=>{let{client:i}=e();try{let s=await i.deleteToolState(a);U({success:!0,toolId:a,deletedKeys:s})}catch(s){z(s.message),process.exit(1)}})}function wp(o,e,t,a,i){ga(a,t)?i():o.command(e,{hidden:!0}).allowUnknownOption().allowExcessArguments(!0).action(()=>{z(pa(t,a)),process.exit(1)})}function Q6(o,e,t){let a=o.command("tool").description("Manage superglue tools").addHelpText("after",`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superglue/cli",
3
- "version": "1.1.59",
3
+ "version": "1.1.61",
4
4
  "bin": {
5
5
  "sg": "./dist/cli.js"
6
6
  },