@superglue/cli 1.1.176 → 1.1.177

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.176",
4
+ "version": "1.1.177",
5
5
  "author": {
6
6
  "name": "superglue",
7
7
  "email": "hello@superglue.cloud"
package/dist/cli.js CHANGED
@@ -79,7 +79,7 @@ ${t.slice(t.length-n)}`}function HX(t){return t instanceof Error?t.message:typeo
79
79
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of t.seen.entries()){let a=s[1];if(e===s[0]){o(s);continue}if(t.external){let u=t.external.registry.get(s[0])?.id;if(e!==s[0]&&u){o(s);continue}}if(t.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}if(a.count>1&&t.reused==="ref"){o(s);continue}}}function jC(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=t.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},d=c.ref;if(c.ref=null,d){n(d);let p=t.seen.get(d),h=p.schema;if(h.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(h)):Object.assign(u,h),Object.assign(u,l),a._zod.parent===d)for(let S in u)S==="$ref"||S==="allOf"||S in l||delete u[S];if(h.$ref&&p.def)for(let S in u)S==="$ref"||S==="allOf"||S in p.def&&JSON.stringify(u[S])===JSON.stringify(p.def[S])&&delete u[S]}let A=a._zod.parent;if(A&&A!==d){n(A);let p=t.seen.get(A);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let h in u)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(u[h])===JSON.stringify(p.def[h])&&delete u[h]}t.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let i={};if(t.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(a)}Object.assign(i,r.def??r.schema);let o=t.metadataRegistry.get(e)?.id;o!==void 0&&i.id===o&&delete i.id;let s=t.external?.defs??{};for(let a of t.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,s[c.defId]=c.def)}t.external||Object.keys(s).length>0&&(t.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{let a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:(0,dn.createStandardJSONSchemaMethod)(e,"input",t.processors),output:(0,dn.createStandardJSONSchemaMethod)(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function rr(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return rr(n.element,r);if(n.type==="set")return rr(n.valueType,r);if(n.type==="lazy")return rr(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return rr(n.innerType,r);if(n.type==="intersection")return rr(n.left,r)||rr(n.right,r);if(n.type==="record"||n.type==="map")return rr(n.keyType,r)||rr(n.valueType,r);if(n.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:rr(n.in,r)||rr(n.out,r);if(n.type==="object"){for(let i in n.shape)if(rr(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(let i of n.options)if(rr(i,r))return!0;return!1}if(n.type==="tuple"){for(let i of n.items)if(rr(i,r))return!0;return!!(n.rest&&rr(n.rest,r))}return!1}var zae=(t,e={})=>r=>{let n=FC({...r,processors:e});return Dh(t,n),$C(n,t),jC(n,t)};dn.createToJSONSchemaMethod=zae;var Hae=(t,e,r={})=>n=>{let{libraryOptions:i,target:o}=n??{},s=FC({...i??{},target:o,io:e,processors:r});return Dh(t,s),$C(s,t),jC(s,t)};dn.createStandardJSONSchemaMethod=Hae});var ld=m(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.allProcessors=R.lazyProcessor=R.optionalProcessor=R.promiseProcessor=R.readonlyProcessor=R.pipeProcessor=R.catchProcessor=R.prefaultProcessor=R.defaultProcessor=R.nonoptionalProcessor=R.nullableProcessor=R.recordProcessor=R.tupleProcessor=R.intersectionProcessor=R.unionProcessor=R.objectProcessor=R.arrayProcessor=R.setProcessor=R.mapProcessor=R.transformProcessor=R.functionProcessor=R.customProcessor=R.successProcessor=R.fileProcessor=R.templateLiteralProcessor=R.nanProcessor=R.literalProcessor=R.enumProcessor=R.dateProcessor=R.unknownProcessor=R.anyProcessor=R.neverProcessor=R.voidProcessor=R.undefinedProcessor=R.nullProcessor=R.symbolProcessor=R.bigintProcessor=R.booleanProcessor=R.numberProcessor=R.stringProcessor=void 0;R.toJSONSchema=Nce;var Le=ud(),Gae=X(),Yae={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Vae=(t,e,r,n)=>{let i=r;i.type="string";let{minimum:o,maximum:s,format:a,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof o=="number"&&(i.minLength=o),typeof s=="number"&&(i.maxLength=s),a&&(i.format=Yae[a]??a,i.format===""&&delete i.format,a==="time"&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?i.pattern=l[0].source:l.length>1&&(i.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}};R.stringProcessor=Vae;var Jae=(t,e,r,n)=>{let i=r,{minimum:o,maximum:s,format:a,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof a=="string"&&a.includes("int")?i.type="integer":i.type="number";let d=typeof l=="number"&&l>=(o??Number.NEGATIVE_INFINITY),A=typeof u=="number"&&u<=(s??Number.POSITIVE_INFINITY),p=e.target==="draft-04"||e.target==="openapi-3.0";d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof o=="number"&&(i.minimum=o),A?p?(i.maximum=u,i.exclusiveMaximum=!0):i.exclusiveMaximum=u:typeof s=="number"&&(i.maximum=s),typeof c=="number"&&(i.multipleOf=c)};R.numberProcessor=Jae;var Wae=(t,e,r,n)=>{r.type="boolean"};R.booleanProcessor=Wae;var Zae=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};R.bigintProcessor=Zae;var Kae=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")};R.symbolProcessor=Kae;var Xae=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};R.nullProcessor=Xae;var ece=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")};R.undefinedProcessor=ece;var tce=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")};R.voidProcessor=tce;var rce=(t,e,r,n)=>{r.not={}};R.neverProcessor=rce;var nce=(t,e,r,n)=>{};R.anyProcessor=nce;var ice=(t,e,r,n)=>{};R.unknownProcessor=ice;var oce=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")};R.dateProcessor=oce;var sce=(t,e,r,n)=>{let i=t._zod.def,o=(0,Gae.getEnumValues)(i.entries);o.every(s=>typeof s=="number")&&(r.type="number"),o.every(s=>typeof s=="string")&&(r.type="string"),r.enum=o};R.enumProcessor=sce;var ace=(t,e,r,n)=>{let i=t._zod.def,o=[];for(let s of i.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(s))}else o.push(s);if(o.length!==0)if(o.length===1){let s=o[0];r.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[s]:r.const=s}else o.every(s=>typeof s=="number")&&(r.type="number"),o.every(s=>typeof s=="string")&&(r.type="string"),o.every(s=>typeof s=="boolean")&&(r.type="boolean"),o.every(s=>s===null)&&(r.type="null"),r.enum=o};R.literalProcessor=ace;var cce=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")};R.nanProcessor=cce;var uce=(t,e,r,n)=>{let i=r,o=t._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=o.source};R.templateLiteralProcessor=uce;var lce=(t,e,r,n)=>{let i=r,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:c}=t._zod.bag;s!==void 0&&(o.minLength=s),a!==void 0&&(o.maxLength=a),c?c.length===1?(o.contentMediaType=c[0],Object.assign(i,o)):(Object.assign(i,o),i.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(i,o)};R.fileProcessor=lce;var dce=(t,e,r,n)=>{r.type="boolean"};R.successProcessor=dce;var Ace=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};R.customProcessor=Ace;var pce=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")};R.functionProcessor=pce;var fce=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};R.transformProcessor=fce;var hce=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")};R.mapProcessor=hce;var gce=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")};R.setProcessor=gce;var mce=(t,e,r,n)=>{let i=r,o=t._zod.def,{minimum:s,maximum:a}=t._zod.bag;typeof s=="number"&&(i.minItems=s),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=(0,Le.process)(o.element,e,{...n,path:[...n.path,"items"]})};R.arrayProcessor=mce;var yce=(t,e,r,n)=>{let i=r,o=t._zod.def;i.type="object",i.properties={};let s=o.shape;for(let u in s)i.properties[u]=(0,Le.process)(s[u],e,{...n,path:[...n.path,"properties",u]});let a=new Set(Object.keys(s)),c=new Set([...a].filter(u=>{let l=o.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(i.required=Array.from(c)),o.catchall?._zod.def.type==="never"?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=(0,Le.process)(o.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)};R.objectProcessor=yce;var Ece=(t,e,r,n)=>{let i=t._zod.def,o=i.inclusive===!1,s=i.options.map((a,c)=>(0,Le.process)(a,e,{...n,path:[...n.path,o?"oneOf":"anyOf",c]}));o?r.oneOf=s:r.anyOf=s};R.unionProcessor=Ece;var Ice=(t,e,r,n)=>{let i=t._zod.def,o=(0,Le.process)(i.left,e,{...n,path:[...n.path,"allOf",0]}),s=(0,Le.process)(i.right,e,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];r.allOf=c};R.intersectionProcessor=Ice;var Cce=(t,e,r,n)=>{let i=r,o=t._zod.def;i.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=o.items.map((A,p)=>(0,Le.process)(A,e,{...n,path:[...n.path,s,p]})),u=o.rest?(0,Le.process)(o.rest,e,{...n,path:[...n.path,a,...e.target==="openapi-3.0"?[o.items.length]:[]]}):null;e.target==="draft-2020-12"?(i.prefixItems=c,u&&(i.items=u)):e.target==="openapi-3.0"?(i.items={anyOf:c},u&&i.items.anyOf.push(u),i.minItems=c.length,u||(i.maxItems=c.length)):(i.items=c,u&&(i.additionalItems=u));let{minimum:l,maximum:d}=t._zod.bag;typeof l=="number"&&(i.minItems=l),typeof d=="number"&&(i.maxItems=d)};R.tupleProcessor=Cce;var bce=(t,e,r,n)=>{let i=r,o=t._zod.def;i.type="object";let s=o.keyType,c=s._zod.bag?.patterns;if(o.mode==="loose"&&c&&c.size>0){let l=(0,Le.process)(o.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(let d of c)i.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=(0,Le.process)(o.keyType,e,{...n,path:[...n.path,"propertyNames"]})),i.additionalProperties=(0,Le.process)(o.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=s._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(i.required=l)}};R.recordProcessor=bce;var Sce=(t,e,r,n)=>{let i=t._zod.def,o=(0,Le.process)(i.innerType,e,n),s=e.seen.get(t);e.target==="openapi-3.0"?(s.ref=i.innerType,r.nullable=!0):r.anyOf=[o,{type:"null"}]};R.nullableProcessor=Sce;var wce=(t,e,r,n)=>{let i=t._zod.def;(0,Le.process)(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType};R.nonoptionalProcessor=wce;var Bce=(t,e,r,n)=>{let i=t._zod.def;(0,Le.process)(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType,r.default=JSON.parse(JSON.stringify(i.defaultValue))};R.defaultProcessor=Bce;var Qce=(t,e,r,n)=>{let i=t._zod.def;(0,Le.process)(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(i.defaultValue)))};R.prefaultProcessor=Qce;var vce=(t,e,r,n)=>{let i=t._zod.def;(0,Le.process)(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType;let s;try{s=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=s};R.catchProcessor=vce;var _ce=(t,e,r,n)=>{let i=t._zod.def,o=i.in._zod.traits.has("$ZodTransform"),s=e.io==="input"?o?i.out:i.in:i.out;(0,Le.process)(s,e,n);let a=e.seen.get(t);a.ref=s};R.pipeProcessor=_ce;var Dce=(t,e,r,n)=>{let i=t._zod.def;(0,Le.process)(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType,r.readOnly=!0};R.readonlyProcessor=Dce;var Tce=(t,e,r,n)=>{let i=t._zod.def;(0,Le.process)(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType};R.promiseProcessor=Tce;var Rce=(t,e,r,n)=>{let i=t._zod.def;(0,Le.process)(i.innerType,e,n);let o=e.seen.get(t);o.ref=i.innerType};R.optionalProcessor=Rce;var kce=(t,e,r,n)=>{let i=t._zod.innerType;(0,Le.process)(i,e,n);let o=e.seen.get(t);o.ref=i};R.lazyProcessor=kce;R.allProcessors={string:R.stringProcessor,number:R.numberProcessor,boolean:R.booleanProcessor,bigint:R.bigintProcessor,symbol:R.symbolProcessor,null:R.nullProcessor,undefined:R.undefinedProcessor,void:R.voidProcessor,never:R.neverProcessor,any:R.anyProcessor,unknown:R.unknownProcessor,date:R.dateProcessor,enum:R.enumProcessor,literal:R.literalProcessor,nan:R.nanProcessor,template_literal:R.templateLiteralProcessor,file:R.fileProcessor,success:R.successProcessor,custom:R.customProcessor,function:R.functionProcessor,transform:R.transformProcessor,map:R.mapProcessor,set:R.setProcessor,array:R.arrayProcessor,object:R.objectProcessor,union:R.unionProcessor,intersection:R.intersectionProcessor,tuple:R.tupleProcessor,record:R.recordProcessor,nullable:R.nullableProcessor,nonoptional:R.nonoptionalProcessor,default:R.defaultProcessor,prefault:R.prefaultProcessor,catch:R.catchProcessor,pipe:R.pipeProcessor,readonly:R.readonlyProcessor,promise:R.promiseProcessor,optional:R.optionalProcessor,lazy:R.lazyProcessor};function Nce(t,e){if("_idmap"in t){let n=t,i=(0,Le.initializeContext)({...e,processors:R.allProcessors}),o={};for(let c of n._idmap.entries()){let[u,l]=c;(0,Le.process)(l,i)}let s={},a={registry:n,uri:e?.uri,defs:o};i.external=a;for(let c of n._idmap.entries()){let[u,l]=c;(0,Le.extractDefs)(i,l),s[u]=(0,Le.finalize)(i,l)}if(Object.keys(o).length>0){let c=i.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[c]:o}}return{schemas:s}}let r=(0,Le.initializeContext)({...e,processors:R.allProcessors});return(0,Le.process)(t,r),(0,Le.extractDefs)(r,t),(0,Le.finalize)(r,t)}});var mU=m(Rh=>{"use strict";Object.defineProperty(Rh,"__esModule",{value:!0});Rh.JSONSchemaGenerator=void 0;var Oce=ld(),Th=ud(),qC=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let r=e?.target??"draft-2020-12";r==="draft-4"&&(r="draft-04"),r==="draft-7"&&(r="draft-07"),this.ctx=(0,Th.initializeContext)({processors:Oce.allProcessors,target:r,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,r={path:[],schemaPath:[]}){return(0,Th.process)(e,this.ctx,r)}emit(e,r){r&&(r.cycles&&(this.ctx.cycles=r.cycles),r.reused&&(this.ctx.reused=r.reused),r.external&&(this.ctx.external=r.external)),(0,Th.extractDefs)(this.ctx,e);let n=(0,Th.finalize)(this.ctx,e),{"~standard":i,...o}=n;return o}};Rh.JSONSchemaGenerator=qC});var EU=m(yU=>{"use strict";Object.defineProperty(yU,"__esModule",{value:!0})});var hr=m(ke=>{"use strict";var IU=ke&&ke.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Uce=ke&&ke.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Wi=ke&&ke.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&IU(e,t,r)},kh=ke&&ke.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&IU(e,t,r);return Uce(e,t),e};Object.defineProperty(ke,"__esModule",{value:!0});ke.JSONSchema=ke.JSONSchemaGenerator=ke.toJSONSchema=ke.locales=ke.regexes=ke.util=void 0;Wi(ya(),ke);Wi(vC(),ke);Wi(BC(),ke);Wi(UC(),ke);Wi(If(),ke);Wi(kC(),ke);ke.util=kh(X());ke.regexes=kh(Ef());ke.locales=kh(PC());Wi(sd(),ke);Wi(RC(),ke);Wi(gU(),ke);Wi(ud(),ke);var Mce=ld();Object.defineProperty(ke,"toJSONSchema",{enumerable:!0,get:function(){return Mce.toJSONSchema}});var xce=mU();Object.defineProperty(ke,"JSONSchemaGenerator",{enumerable:!0,get:function(){return xce.JSONSchemaGenerator}});ke.JSONSchema=kh(EU())});var Nh=m(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.slugify=ee.toUpperCase=ee.toLowerCase=ee.trim=ee.normalize=ee.overwrite=ee.mime=ee.property=ee.endsWith=ee.startsWith=ee.includes=ee.uppercase=ee.lowercase=ee.regex=ee.length=ee.minLength=ee.maxLength=ee.size=ee.minSize=ee.maxSize=ee.multipleOf=ee.nonnegative=ee.nonpositive=ee.negative=ee.positive=ee.gte=ee.gt=ee.lte=ee.lt=void 0;var Pe=hr();Object.defineProperty(ee,"lt",{enumerable:!0,get:function(){return Pe._lt}});Object.defineProperty(ee,"lte",{enumerable:!0,get:function(){return Pe._lte}});Object.defineProperty(ee,"gt",{enumerable:!0,get:function(){return Pe._gt}});Object.defineProperty(ee,"gte",{enumerable:!0,get:function(){return Pe._gte}});Object.defineProperty(ee,"positive",{enumerable:!0,get:function(){return Pe._positive}});Object.defineProperty(ee,"negative",{enumerable:!0,get:function(){return Pe._negative}});Object.defineProperty(ee,"nonpositive",{enumerable:!0,get:function(){return Pe._nonpositive}});Object.defineProperty(ee,"nonnegative",{enumerable:!0,get:function(){return Pe._nonnegative}});Object.defineProperty(ee,"multipleOf",{enumerable:!0,get:function(){return Pe._multipleOf}});Object.defineProperty(ee,"maxSize",{enumerable:!0,get:function(){return Pe._maxSize}});Object.defineProperty(ee,"minSize",{enumerable:!0,get:function(){return Pe._minSize}});Object.defineProperty(ee,"size",{enumerable:!0,get:function(){return Pe._size}});Object.defineProperty(ee,"maxLength",{enumerable:!0,get:function(){return Pe._maxLength}});Object.defineProperty(ee,"minLength",{enumerable:!0,get:function(){return Pe._minLength}});Object.defineProperty(ee,"length",{enumerable:!0,get:function(){return Pe._length}});Object.defineProperty(ee,"regex",{enumerable:!0,get:function(){return Pe._regex}});Object.defineProperty(ee,"lowercase",{enumerable:!0,get:function(){return Pe._lowercase}});Object.defineProperty(ee,"uppercase",{enumerable:!0,get:function(){return Pe._uppercase}});Object.defineProperty(ee,"includes",{enumerable:!0,get:function(){return Pe._includes}});Object.defineProperty(ee,"startsWith",{enumerable:!0,get:function(){return Pe._startsWith}});Object.defineProperty(ee,"endsWith",{enumerable:!0,get:function(){return Pe._endsWith}});Object.defineProperty(ee,"property",{enumerable:!0,get:function(){return Pe._property}});Object.defineProperty(ee,"mime",{enumerable:!0,get:function(){return Pe._mime}});Object.defineProperty(ee,"overwrite",{enumerable:!0,get:function(){return Pe._overwrite}});Object.defineProperty(ee,"normalize",{enumerable:!0,get:function(){return Pe._normalize}});Object.defineProperty(ee,"trim",{enumerable:!0,get:function(){return Pe._trim}});Object.defineProperty(ee,"toLowerCase",{enumerable:!0,get:function(){return Pe._toLowerCase}});Object.defineProperty(ee,"toUpperCase",{enumerable:!0,get:function(){return Pe._toUpperCase}});Object.defineProperty(ee,"slugify",{enumerable:!0,get:function(){return Pe._slugify}})});var dd=m(rt=>{"use strict";var Lce=rt&&rt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Pce=rt&&rt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),CU=rt&&rt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Lce(e,t,r);return Pce(e,t),e};Object.defineProperty(rt,"__esModule",{value:!0});rt.ZodISODuration=rt.ZodISOTime=rt.ZodISODate=rt.ZodISODateTime=void 0;rt.datetime=Fce;rt.date=$ce;rt.time=jce;rt.duration=qce;var An=CU(hr()),Oh=CU(Ad());rt.ZodISODateTime=An.$constructor("ZodISODateTime",(t,e)=>{An.$ZodISODateTime.init(t,e),Oh.ZodStringFormat.init(t,e)});function Fce(t){return An._isoDateTime(rt.ZodISODateTime,t)}rt.ZodISODate=An.$constructor("ZodISODate",(t,e)=>{An.$ZodISODate.init(t,e),Oh.ZodStringFormat.init(t,e)});function $ce(t){return An._isoDate(rt.ZodISODate,t)}rt.ZodISOTime=An.$constructor("ZodISOTime",(t,e)=>{An.$ZodISOTime.init(t,e),Oh.ZodStringFormat.init(t,e)});function jce(t){return An._isoTime(rt.ZodISOTime,t)}rt.ZodISODuration=An.$constructor("ZodISODuration",(t,e)=>{An.$ZodISODuration.init(t,e),Oh.ZodStringFormat.init(t,e)});function qce(t){return An._isoDuration(rt.ZodISODuration,t)}});var zC=m(pn=>{"use strict";var zce=pn&&pn.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Hce=pn&&pn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),SU=pn&&pn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&zce(e,t,r);return Hce(e,t),e};Object.defineProperty(pn,"__esModule",{value:!0});pn.ZodRealError=pn.ZodError=void 0;var Uh=SU(hr()),Gce=hr(),bU=SU(X()),wU=(t,e)=>{Gce.$ZodError.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Uh.formatError(t,r)},flatten:{value:r=>Uh.flattenError(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,bU.jsonStringifyReplacer,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,bU.jsonStringifyReplacer,2)}},isEmpty:{get(){return t.issues.length===0}}})};pn.ZodError=Uh.$constructor("ZodError",wU);pn.ZodRealError=Uh.$constructor("ZodError",wU,{Parent:Error})});var HC=m(Ne=>{"use strict";var Yce=Ne&&Ne.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Vce=Ne&&Ne.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Jce=Ne&&Ne.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Yce(e,t,r);return Vce(e,t),e};Object.defineProperty(Ne,"__esModule",{value:!0});Ne.safeDecodeAsync=Ne.safeEncodeAsync=Ne.safeDecode=Ne.safeEncode=Ne.decodeAsync=Ne.encodeAsync=Ne.decode=Ne.encode=Ne.safeParseAsync=Ne.safeParse=Ne.parseAsync=Ne.parse=void 0;var fn=Jce(hr()),hn=zC();Ne.parse=fn._parse(hn.ZodRealError);Ne.parseAsync=fn._parseAsync(hn.ZodRealError);Ne.safeParse=fn._safeParse(hn.ZodRealError);Ne.safeParseAsync=fn._safeParseAsync(hn.ZodRealError);Ne.encode=fn._encode(hn.ZodRealError);Ne.decode=fn._decode(hn.ZodRealError);Ne.encodeAsync=fn._encodeAsync(hn.ZodRealError);Ne.decodeAsync=fn._decodeAsync(hn.ZodRealError);Ne.safeEncode=fn._safeEncode(hn.ZodRealError);Ne.safeDecode=fn._safeDecode(hn.ZodRealError);Ne.safeEncodeAsync=fn._safeEncodeAsync(hn.ZodRealError);Ne.safeDecodeAsync=fn._safeDecodeAsync(hn.ZodRealError)});var Ad=m(f=>{"use strict";var Wce=f&&f.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Zce=f&&f.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),pd=f&&f.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Wce(e,t,r);return Zce(e,t),e};Object.defineProperty(f,"__esModule",{value:!0});f.ZodLiteral=f.ZodEnum=f.ZodSet=f.ZodMap=f.ZodRecord=f.ZodTuple=f.ZodIntersection=f.ZodDiscriminatedUnion=f.ZodXor=f.ZodUnion=f.ZodObject=f.ZodArray=f.ZodDate=f.ZodVoid=f.ZodNever=f.ZodUnknown=f.ZodAny=f.ZodNull=f.ZodUndefined=f.ZodSymbol=f.ZodBigIntFormat=f.ZodBigInt=f.ZodBoolean=f.ZodNumberFormat=f.ZodNumber=f.ZodCustomStringFormat=f.ZodJWT=f.ZodE164=f.ZodBase64URL=f.ZodBase64=f.ZodCIDRv6=f.ZodCIDRv4=f.ZodIPv6=f.ZodMAC=f.ZodIPv4=f.ZodKSUID=f.ZodXID=f.ZodULID=f.ZodCUID2=f.ZodCUID=f.ZodNanoID=f.ZodEmoji=f.ZodURL=f.ZodUUID=f.ZodGUID=f.ZodEmail=f.ZodStringFormat=f.ZodString=f._ZodString=f.ZodType=void 0;f.stringbool=f.meta=f.describe=f.ZodCustom=f.ZodFunction=f.ZodPromise=f.ZodLazy=f.ZodTemplateLiteral=f.ZodReadonly=f.ZodPreprocess=f.ZodCodec=f.ZodPipe=f.ZodNaN=f.ZodCatch=f.ZodSuccess=f.ZodNonOptional=f.ZodPrefault=f.ZodDefault=f.ZodNullable=f.ZodExactOptional=f.ZodOptional=f.ZodTransform=f.ZodFile=void 0;f.string=xh;f.email=Kce;f.guid=Xce;f.uuid=eue;f.uuidv4=tue;f.uuidv6=rue;f.uuidv7=nue;f.url=iue;f.httpUrl=oue;f.emoji=sue;f.nanoid=aue;f.cuid=cue;f.cuid2=uue;f.ulid=lue;f.xid=due;f.ksuid=Aue;f.ipv4=pue;f.mac=fue;f.ipv6=hue;f.cidrv4=gue;f.cidrv6=mue;f.base64=yue;f.base64url=Eue;f.e164=Iue;f.jwt=Cue;f.stringFormat=bue;f.hostname=Sue;f.hex=wue;f.hash=Bue;f.number=QU;f.int=YC;f.float32=Que;f.float64=vue;f.int32=_ue;f.uint32=Due;f.boolean=vU;f.bigint=Tue;f.int64=Rue;f.uint64=kue;f.symbol=Nue;f.undefined=Oue;f.null=_U;f.any=Uue;f.unknown=Jc;f.never=JC;f.void=Mue;f.date=xue;f.array=Fh;f.keyof=Lue;f.object=Pue;f.strictObject=Fue;f.looseObject=$ue;f.union=WC;f.xor=jue;f.discriminatedUnion=que;f.intersection=DU;f.tuple=TU;f.record=RU;f.partialRecord=zue;f.looseRecord=Hue;f.map=Gue;f.set=Yue;f.enum=ZC;f.nativeEnum=Vue;f.literal=Jue;f.file=Wue;f.transform=KC;f.optional=Lh;f.exactOptional=kU;f.nullable=Ph;f.nullish=Zue;f._default=NU;f.prefault=OU;f.nonoptional=UU;f.success=Kue;f.catch=MU;f.nan=Xue;f.pipe=VC;f.codec=ele;f.invertCodec=tle;f.readonly=xU;f.templateLiteral=rle;f.lazy=LU;f.promise=nle;f._function=$h;f.function=$h;f._function=$h;f.function=$h;f.check=ile;f.custom=ole;f.refine=PU;f.superRefine=FU;f.instanceof=sle;f.json=cle;f.preprocess=ule;var I=pd(hr()),Qe=hr(),be=pd(ld()),GC=ud(),ge=pd(Nh()),Mh=pd(dd()),gn=pd(HC()),BU=new WeakMap;function fd(t,e,r){let n=Object.getPrototypeOf(t),i=BU.get(n);if(i||(i=new Set,BU.set(n,i)),!i.has(e)){i.add(e);for(let o in r){let s=r[o];Object.defineProperty(n,o,{configurable:!0,enumerable:!1,get(){let a=s.bind(this);return Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:a}),a},set(a){Object.defineProperty(this,o,{configurable:!0,writable:!0,enumerable:!0,value:a})}})}}}f.ZodType=I.$constructor("ZodType",(t,e)=>(I.$ZodType.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:(0,GC.createStandardJSONSchemaMethod)(t,"input"),output:(0,GC.createStandardJSONSchemaMethod)(t,"output")}}),t.toJSONSchema=(0,GC.createToJSONSchemaMethod)(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(r,n)=>gn.parse(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>gn.safeParse(t,r,n),t.parseAsync=async(r,n)=>gn.parseAsync(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>gn.safeParseAsync(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>gn.encode(t,r,n),t.decode=(r,n)=>gn.decode(t,r,n),t.encodeAsync=async(r,n)=>gn.encodeAsync(t,r,n),t.decodeAsync=async(r,n)=>gn.decodeAsync(t,r,n),t.safeEncode=(r,n)=>gn.safeEncode(t,r,n),t.safeDecode=(r,n)=>gn.safeDecode(t,r,n),t.safeEncodeAsync=async(r,n)=>gn.safeEncodeAsync(t,r,n),t.safeDecodeAsync=async(r,n)=>gn.safeDecodeAsync(t,r,n),fd(t,"ZodType",{check(...r){let n=this.def;return this.clone(Qe.util.mergeDefs(n,{checks:[...n.checks??[],...r.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...r){return this.check(...r)},clone(r,n){return I.clone(this,r,n)},brand(){return this},register(r,n){return r.add(this,n),this},refine(r,n){return this.check(PU(r,n))},superRefine(r,n){return this.check(FU(r,n))},overwrite(r){return this.check(ge.overwrite(r))},optional(){return Lh(this)},exactOptional(){return kU(this)},nullable(){return Ph(this)},nullish(){return Lh(Ph(this))},nonoptional(r){return UU(this,r)},array(){return Fh(this)},or(r){return WC([this,r])},and(r){return DU(this,r)},transform(r){return VC(this,KC(r))},default(r){return NU(this,r)},prefault(r){return OU(this,r)},catch(r){return MU(this,r)},pipe(r){return VC(this,r)},readonly(){return xU(this)},describe(r){let n=this.clone();return I.globalRegistry.add(n,{description:r}),n},meta(...r){if(r.length===0)return I.globalRegistry.get(this);let n=this.clone();return I.globalRegistry.add(n,r[0]),n},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(r){return r(this)}}),Object.defineProperty(t,"description",{get(){return I.globalRegistry.get(t)?.description},configurable:!0}),t));f._ZodString=I.$constructor("_ZodString",(t,e)=>{I.$ZodString.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>be.stringProcessor(t,n,i,o);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,fd(t,"_ZodString",{regex(...n){return this.check(ge.regex(...n))},includes(...n){return this.check(ge.includes(...n))},startsWith(...n){return this.check(ge.startsWith(...n))},endsWith(...n){return this.check(ge.endsWith(...n))},min(...n){return this.check(ge.minLength(...n))},max(...n){return this.check(ge.maxLength(...n))},length(...n){return this.check(ge.length(...n))},nonempty(...n){return this.check(ge.minLength(1,...n))},lowercase(n){return this.check(ge.lowercase(n))},uppercase(n){return this.check(ge.uppercase(n))},trim(){return this.check(ge.trim())},normalize(...n){return this.check(ge.normalize(...n))},toLowerCase(){return this.check(ge.toLowerCase())},toUpperCase(){return this.check(ge.toUpperCase())},slugify(){return this.check(ge.slugify())}})});f.ZodString=I.$constructor("ZodString",(t,e)=>{I.$ZodString.init(t,e),f._ZodString.init(t,e),t.email=r=>t.check(I._email(f.ZodEmail,r)),t.url=r=>t.check(I._url(f.ZodURL,r)),t.jwt=r=>t.check(I._jwt(f.ZodJWT,r)),t.emoji=r=>t.check(I._emoji(f.ZodEmoji,r)),t.guid=r=>t.check(I._guid(f.ZodGUID,r)),t.uuid=r=>t.check(I._uuid(f.ZodUUID,r)),t.uuidv4=r=>t.check(I._uuidv4(f.ZodUUID,r)),t.uuidv6=r=>t.check(I._uuidv6(f.ZodUUID,r)),t.uuidv7=r=>t.check(I._uuidv7(f.ZodUUID,r)),t.nanoid=r=>t.check(I._nanoid(f.ZodNanoID,r)),t.guid=r=>t.check(I._guid(f.ZodGUID,r)),t.cuid=r=>t.check(I._cuid(f.ZodCUID,r)),t.cuid2=r=>t.check(I._cuid2(f.ZodCUID2,r)),t.ulid=r=>t.check(I._ulid(f.ZodULID,r)),t.base64=r=>t.check(I._base64(f.ZodBase64,r)),t.base64url=r=>t.check(I._base64url(f.ZodBase64URL,r)),t.xid=r=>t.check(I._xid(f.ZodXID,r)),t.ksuid=r=>t.check(I._ksuid(f.ZodKSUID,r)),t.ipv4=r=>t.check(I._ipv4(f.ZodIPv4,r)),t.ipv6=r=>t.check(I._ipv6(f.ZodIPv6,r)),t.cidrv4=r=>t.check(I._cidrv4(f.ZodCIDRv4,r)),t.cidrv6=r=>t.check(I._cidrv6(f.ZodCIDRv6,r)),t.e164=r=>t.check(I._e164(f.ZodE164,r)),t.datetime=r=>t.check(Mh.datetime(r)),t.date=r=>t.check(Mh.date(r)),t.time=r=>t.check(Mh.time(r)),t.duration=r=>t.check(Mh.duration(r))});function xh(t){return I._string(f.ZodString,t)}f.ZodStringFormat=I.$constructor("ZodStringFormat",(t,e)=>{I.$ZodStringFormat.init(t,e),f._ZodString.init(t,e)});f.ZodEmail=I.$constructor("ZodEmail",(t,e)=>{I.$ZodEmail.init(t,e),f.ZodStringFormat.init(t,e)});function Kce(t){return I._email(f.ZodEmail,t)}f.ZodGUID=I.$constructor("ZodGUID",(t,e)=>{I.$ZodGUID.init(t,e),f.ZodStringFormat.init(t,e)});function Xce(t){return I._guid(f.ZodGUID,t)}f.ZodUUID=I.$constructor("ZodUUID",(t,e)=>{I.$ZodUUID.init(t,e),f.ZodStringFormat.init(t,e)});function eue(t){return I._uuid(f.ZodUUID,t)}function tue(t){return I._uuidv4(f.ZodUUID,t)}function rue(t){return I._uuidv6(f.ZodUUID,t)}function nue(t){return I._uuidv7(f.ZodUUID,t)}f.ZodURL=I.$constructor("ZodURL",(t,e)=>{I.$ZodURL.init(t,e),f.ZodStringFormat.init(t,e)});function iue(t){return I._url(f.ZodURL,t)}function oue(t){return I._url(f.ZodURL,{protocol:I.regexes.httpProtocol,hostname:I.regexes.domain,...Qe.util.normalizeParams(t)})}f.ZodEmoji=I.$constructor("ZodEmoji",(t,e)=>{I.$ZodEmoji.init(t,e),f.ZodStringFormat.init(t,e)});function sue(t){return I._emoji(f.ZodEmoji,t)}f.ZodNanoID=I.$constructor("ZodNanoID",(t,e)=>{I.$ZodNanoID.init(t,e),f.ZodStringFormat.init(t,e)});function aue(t){return I._nanoid(f.ZodNanoID,t)}f.ZodCUID=I.$constructor("ZodCUID",(t,e)=>{I.$ZodCUID.init(t,e),f.ZodStringFormat.init(t,e)});function cue(t){return I._cuid(f.ZodCUID,t)}f.ZodCUID2=I.$constructor("ZodCUID2",(t,e)=>{I.$ZodCUID2.init(t,e),f.ZodStringFormat.init(t,e)});function uue(t){return I._cuid2(f.ZodCUID2,t)}f.ZodULID=I.$constructor("ZodULID",(t,e)=>{I.$ZodULID.init(t,e),f.ZodStringFormat.init(t,e)});function lue(t){return I._ulid(f.ZodULID,t)}f.ZodXID=I.$constructor("ZodXID",(t,e)=>{I.$ZodXID.init(t,e),f.ZodStringFormat.init(t,e)});function due(t){return I._xid(f.ZodXID,t)}f.ZodKSUID=I.$constructor("ZodKSUID",(t,e)=>{I.$ZodKSUID.init(t,e),f.ZodStringFormat.init(t,e)});function Aue(t){return I._ksuid(f.ZodKSUID,t)}f.ZodIPv4=I.$constructor("ZodIPv4",(t,e)=>{I.$ZodIPv4.init(t,e),f.ZodStringFormat.init(t,e)});function pue(t){return I._ipv4(f.ZodIPv4,t)}f.ZodMAC=I.$constructor("ZodMAC",(t,e)=>{I.$ZodMAC.init(t,e),f.ZodStringFormat.init(t,e)});function fue(t){return I._mac(f.ZodMAC,t)}f.ZodIPv6=I.$constructor("ZodIPv6",(t,e)=>{I.$ZodIPv6.init(t,e),f.ZodStringFormat.init(t,e)});function hue(t){return I._ipv6(f.ZodIPv6,t)}f.ZodCIDRv4=I.$constructor("ZodCIDRv4",(t,e)=>{I.$ZodCIDRv4.init(t,e),f.ZodStringFormat.init(t,e)});function gue(t){return I._cidrv4(f.ZodCIDRv4,t)}f.ZodCIDRv6=I.$constructor("ZodCIDRv6",(t,e)=>{I.$ZodCIDRv6.init(t,e),f.ZodStringFormat.init(t,e)});function mue(t){return I._cidrv6(f.ZodCIDRv6,t)}f.ZodBase64=I.$constructor("ZodBase64",(t,e)=>{I.$ZodBase64.init(t,e),f.ZodStringFormat.init(t,e)});function yue(t){return I._base64(f.ZodBase64,t)}f.ZodBase64URL=I.$constructor("ZodBase64URL",(t,e)=>{I.$ZodBase64URL.init(t,e),f.ZodStringFormat.init(t,e)});function Eue(t){return I._base64url(f.ZodBase64URL,t)}f.ZodE164=I.$constructor("ZodE164",(t,e)=>{I.$ZodE164.init(t,e),f.ZodStringFormat.init(t,e)});function Iue(t){return I._e164(f.ZodE164,t)}f.ZodJWT=I.$constructor("ZodJWT",(t,e)=>{I.$ZodJWT.init(t,e),f.ZodStringFormat.init(t,e)});function Cue(t){return I._jwt(f.ZodJWT,t)}f.ZodCustomStringFormat=I.$constructor("ZodCustomStringFormat",(t,e)=>{I.$ZodCustomStringFormat.init(t,e),f.ZodStringFormat.init(t,e)});function bue(t,e,r={}){return I._stringFormat(f.ZodCustomStringFormat,t,e,r)}function Sue(t){return I._stringFormat(f.ZodCustomStringFormat,"hostname",I.regexes.hostname,t)}function wue(t){return I._stringFormat(f.ZodCustomStringFormat,"hex",I.regexes.hex,t)}function Bue(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,i=I.regexes[n];if(!i)throw new Error(`Unrecognized hash format: ${n}`);return I._stringFormat(f.ZodCustomStringFormat,n,i,e)}f.ZodNumber=I.$constructor("ZodNumber",(t,e)=>{I.$ZodNumber.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>be.numberProcessor(t,n,i,o),fd(t,"ZodNumber",{gt(n,i){return this.check(ge.gt(n,i))},gte(n,i){return this.check(ge.gte(n,i))},min(n,i){return this.check(ge.gte(n,i))},lt(n,i){return this.check(ge.lt(n,i))},lte(n,i){return this.check(ge.lte(n,i))},max(n,i){return this.check(ge.lte(n,i))},int(n){return this.check(YC(n))},safe(n){return this.check(YC(n))},positive(n){return this.check(ge.gt(0,n))},nonnegative(n){return this.check(ge.gte(0,n))},negative(n){return this.check(ge.lt(0,n))},nonpositive(n){return this.check(ge.lte(0,n))},multipleOf(n,i){return this.check(ge.multipleOf(n,i))},step(n,i){return this.check(ge.multipleOf(n,i))},finite(){return this}});let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function QU(t){return I._number(f.ZodNumber,t)}f.ZodNumberFormat=I.$constructor("ZodNumberFormat",(t,e)=>{I.$ZodNumberFormat.init(t,e),f.ZodNumber.init(t,e)});function YC(t){return I._int(f.ZodNumberFormat,t)}function Que(t){return I._float32(f.ZodNumberFormat,t)}function vue(t){return I._float64(f.ZodNumberFormat,t)}function _ue(t){return I._int32(f.ZodNumberFormat,t)}function Due(t){return I._uint32(f.ZodNumberFormat,t)}f.ZodBoolean=I.$constructor("ZodBoolean",(t,e)=>{I.$ZodBoolean.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.booleanProcessor(t,r,n,i)});function vU(t){return I._boolean(f.ZodBoolean,t)}f.ZodBigInt=I.$constructor("ZodBigInt",(t,e)=>{I.$ZodBigInt.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>be.bigintProcessor(t,n,i,o),t.gte=(n,i)=>t.check(ge.gte(n,i)),t.min=(n,i)=>t.check(ge.gte(n,i)),t.gt=(n,i)=>t.check(ge.gt(n,i)),t.gte=(n,i)=>t.check(ge.gte(n,i)),t.min=(n,i)=>t.check(ge.gte(n,i)),t.lt=(n,i)=>t.check(ge.lt(n,i)),t.lte=(n,i)=>t.check(ge.lte(n,i)),t.max=(n,i)=>t.check(ge.lte(n,i)),t.positive=n=>t.check(ge.gt(BigInt(0),n)),t.negative=n=>t.check(ge.lt(BigInt(0),n)),t.nonpositive=n=>t.check(ge.lte(BigInt(0),n)),t.nonnegative=n=>t.check(ge.gte(BigInt(0),n)),t.multipleOf=(n,i)=>t.check(ge.multipleOf(n,i));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function Tue(t){return I._bigint(f.ZodBigInt,t)}f.ZodBigIntFormat=I.$constructor("ZodBigIntFormat",(t,e)=>{I.$ZodBigIntFormat.init(t,e),f.ZodBigInt.init(t,e)});function Rue(t){return I._int64(f.ZodBigIntFormat,t)}function kue(t){return I._uint64(f.ZodBigIntFormat,t)}f.ZodSymbol=I.$constructor("ZodSymbol",(t,e)=>{I.$ZodSymbol.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.symbolProcessor(t,r,n,i)});function Nue(t){return I._symbol(f.ZodSymbol,t)}f.ZodUndefined=I.$constructor("ZodUndefined",(t,e)=>{I.$ZodUndefined.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.undefinedProcessor(t,r,n,i)});function Oue(t){return I._undefined(f.ZodUndefined,t)}f.ZodNull=I.$constructor("ZodNull",(t,e)=>{I.$ZodNull.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.nullProcessor(t,r,n,i)});function _U(t){return I._null(f.ZodNull,t)}f.ZodAny=I.$constructor("ZodAny",(t,e)=>{I.$ZodAny.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.anyProcessor(t,r,n,i)});function Uue(){return I._any(f.ZodAny)}f.ZodUnknown=I.$constructor("ZodUnknown",(t,e)=>{I.$ZodUnknown.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.unknownProcessor(t,r,n,i)});function Jc(){return I._unknown(f.ZodUnknown)}f.ZodNever=I.$constructor("ZodNever",(t,e)=>{I.$ZodNever.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.neverProcessor(t,r,n,i)});function JC(t){return I._never(f.ZodNever,t)}f.ZodVoid=I.$constructor("ZodVoid",(t,e)=>{I.$ZodVoid.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.voidProcessor(t,r,n,i)});function Mue(t){return I._void(f.ZodVoid,t)}f.ZodDate=I.$constructor("ZodDate",(t,e)=>{I.$ZodDate.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>be.dateProcessor(t,n,i,o),t.min=(n,i)=>t.check(ge.gte(n,i)),t.max=(n,i)=>t.check(ge.lte(n,i));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function xue(t){return I._date(f.ZodDate,t)}f.ZodArray=I.$constructor("ZodArray",(t,e)=>{I.$ZodArray.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.arrayProcessor(t,r,n,i),t.element=e.element,fd(t,"ZodArray",{min(r,n){return this.check(ge.minLength(r,n))},nonempty(r){return this.check(ge.minLength(1,r))},max(r,n){return this.check(ge.maxLength(r,n))},length(r,n){return this.check(ge.length(r,n))},unwrap(){return this.element}})});function Fh(t,e){return I._array(f.ZodArray,t,e)}function Lue(t){let e=t._zod.def.shape;return ZC(Object.keys(e))}f.ZodObject=I.$constructor("ZodObject",(t,e)=>{I.$ZodObjectJIT.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.objectProcessor(t,r,n,i),Qe.util.defineLazy(t,"shape",()=>e.shape),fd(t,"ZodObject",{keyof(){return ZC(Object.keys(this._zod.def.shape))},catchall(r){return this.clone({...this._zod.def,catchall:r})},passthrough(){return this.clone({...this._zod.def,catchall:Jc()})},loose(){return this.clone({...this._zod.def,catchall:Jc()})},strict(){return this.clone({...this._zod.def,catchall:JC()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(r){return Qe.util.extend(this,r)},safeExtend(r){return Qe.util.safeExtend(this,r)},merge(r){return Qe.util.merge(this,r)},pick(r){return Qe.util.pick(this,r)},omit(r){return Qe.util.omit(this,r)},partial(...r){return Qe.util.partial(f.ZodOptional,this,r[0])},required(...r){return Qe.util.required(f.ZodNonOptional,this,r[0])}})});function Pue(t,e){let r={type:"object",shape:t??{},...Qe.util.normalizeParams(e)};return new f.ZodObject(r)}function Fue(t,e){return new f.ZodObject({type:"object",shape:t,catchall:JC(),...Qe.util.normalizeParams(e)})}function $ue(t,e){return new f.ZodObject({type:"object",shape:t,catchall:Jc(),...Qe.util.normalizeParams(e)})}f.ZodUnion=I.$constructor("ZodUnion",(t,e)=>{I.$ZodUnion.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.unionProcessor(t,r,n,i),t.options=e.options});function WC(t,e){return new f.ZodUnion({type:"union",options:t,...Qe.util.normalizeParams(e)})}f.ZodXor=I.$constructor("ZodXor",(t,e)=>{f.ZodUnion.init(t,e),I.$ZodXor.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.unionProcessor(t,r,n,i),t.options=e.options});function jue(t,e){return new f.ZodXor({type:"union",options:t,inclusive:!1,...Qe.util.normalizeParams(e)})}f.ZodDiscriminatedUnion=I.$constructor("ZodDiscriminatedUnion",(t,e)=>{f.ZodUnion.init(t,e),I.$ZodDiscriminatedUnion.init(t,e)});function que(t,e,r){return new f.ZodDiscriminatedUnion({type:"union",options:e,discriminator:t,...Qe.util.normalizeParams(r)})}f.ZodIntersection=I.$constructor("ZodIntersection",(t,e)=>{I.$ZodIntersection.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.intersectionProcessor(t,r,n,i)});function DU(t,e){return new f.ZodIntersection({type:"intersection",left:t,right:e})}f.ZodTuple=I.$constructor("ZodTuple",(t,e)=>{I.$ZodTuple.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.tupleProcessor(t,r,n,i),t.rest=r=>t.clone({...t._zod.def,rest:r})});function TU(t,e,r){let n=e instanceof I.$ZodType,i=n?r:e,o=n?e:null;return new f.ZodTuple({type:"tuple",items:t,rest:o,...Qe.util.normalizeParams(i)})}f.ZodRecord=I.$constructor("ZodRecord",(t,e)=>{I.$ZodRecord.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.recordProcessor(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType});function RU(t,e,r){return!e||!e._zod?new f.ZodRecord({type:"record",keyType:xh(),valueType:t,...Qe.util.normalizeParams(e)}):new f.ZodRecord({type:"record",keyType:t,valueType:e,...Qe.util.normalizeParams(r)})}function zue(t,e,r){let n=I.clone(t);return n._zod.values=void 0,new f.ZodRecord({type:"record",keyType:n,valueType:e,...Qe.util.normalizeParams(r)})}function Hue(t,e,r){return new f.ZodRecord({type:"record",keyType:t,valueType:e,mode:"loose",...Qe.util.normalizeParams(r)})}f.ZodMap=I.$constructor("ZodMap",(t,e)=>{I.$ZodMap.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.mapProcessor(t,r,n,i),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(I._minSize(...r)),t.nonempty=r=>t.check(I._minSize(1,r)),t.max=(...r)=>t.check(I._maxSize(...r)),t.size=(...r)=>t.check(I._size(...r))});function Gue(t,e,r){return new f.ZodMap({type:"map",keyType:t,valueType:e,...Qe.util.normalizeParams(r)})}f.ZodSet=I.$constructor("ZodSet",(t,e)=>{I.$ZodSet.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.setProcessor(t,r,n,i),t.min=(...r)=>t.check(I._minSize(...r)),t.nonempty=r=>t.check(I._minSize(1,r)),t.max=(...r)=>t.check(I._maxSize(...r)),t.size=(...r)=>t.check(I._size(...r))});function Yue(t,e){return new f.ZodSet({type:"set",valueType:t,...Qe.util.normalizeParams(e)})}f.ZodEnum=I.$constructor("ZodEnum",(t,e)=>{I.$ZodEnum.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(n,i,o)=>be.enumProcessor(t,n,i,o),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,i)=>{let o={};for(let s of n)if(r.has(s))o[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new f.ZodEnum({...e,checks:[],...Qe.util.normalizeParams(i),entries:o})},t.exclude=(n,i)=>{let o={...e.entries};for(let s of n)if(r.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new f.ZodEnum({...e,checks:[],...Qe.util.normalizeParams(i),entries:o})}});function ZC(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new f.ZodEnum({type:"enum",entries:r,...Qe.util.normalizeParams(e)})}function Vue(t,e){return new f.ZodEnum({type:"enum",entries:t,...Qe.util.normalizeParams(e)})}f.ZodLiteral=I.$constructor("ZodLiteral",(t,e)=>{I.$ZodLiteral.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.literalProcessor(t,r,n,i),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function Jue(t,e){return new f.ZodLiteral({type:"literal",values:Array.isArray(t)?t:[t],...Qe.util.normalizeParams(e)})}f.ZodFile=I.$constructor("ZodFile",(t,e)=>{I.$ZodFile.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.fileProcessor(t,r,n,i),t.min=(r,n)=>t.check(I._minSize(r,n)),t.max=(r,n)=>t.check(I._maxSize(r,n)),t.mime=(r,n)=>t.check(I._mime(Array.isArray(r)?r:[r],n))});function Wue(t){return I._file(f.ZodFile,t)}f.ZodTransform=I.$constructor("ZodTransform",(t,e)=>{I.$ZodTransform.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.transformProcessor(t,r,n,i),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new I.$ZodEncodeError(t.constructor.name);r.addIssue=o=>{if(typeof o=="string")r.issues.push(Qe.util.issue(o,r.value,e));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=t),r.issues.push(Qe.util.issue(s))}};let i=e.transform(r.value,r);return i instanceof Promise?i.then(o=>(r.value=o,r.fallback=!0,r)):(r.value=i,r.fallback=!0,r)}});function KC(t){return new f.ZodTransform({type:"transform",transform:t})}f.ZodOptional=I.$constructor("ZodOptional",(t,e)=>{I.$ZodOptional.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.optionalProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Lh(t){return new f.ZodOptional({type:"optional",innerType:t})}f.ZodExactOptional=I.$constructor("ZodExactOptional",(t,e)=>{I.$ZodExactOptional.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.optionalProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function kU(t){return new f.ZodExactOptional({type:"optional",innerType:t})}f.ZodNullable=I.$constructor("ZodNullable",(t,e)=>{I.$ZodNullable.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.nullableProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Ph(t){return new f.ZodNullable({type:"nullable",innerType:t})}function Zue(t){return Lh(Ph(t))}f.ZodDefault=I.$constructor("ZodDefault",(t,e)=>{I.$ZodDefault.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.defaultProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function NU(t,e){return new f.ZodDefault({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():Qe.util.shallowClone(e)}})}f.ZodPrefault=I.$constructor("ZodPrefault",(t,e)=>{I.$ZodPrefault.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.prefaultProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function OU(t,e){return new f.ZodPrefault({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():Qe.util.shallowClone(e)}})}f.ZodNonOptional=I.$constructor("ZodNonOptional",(t,e)=>{I.$ZodNonOptional.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.nonoptionalProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function UU(t,e){return new f.ZodNonOptional({type:"nonoptional",innerType:t,...Qe.util.normalizeParams(e)})}f.ZodSuccess=I.$constructor("ZodSuccess",(t,e)=>{I.$ZodSuccess.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.successProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function Kue(t){return new f.ZodSuccess({type:"success",innerType:t})}f.ZodCatch=I.$constructor("ZodCatch",(t,e)=>{I.$ZodCatch.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.catchProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function MU(t,e){return new f.ZodCatch({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}f.ZodNaN=I.$constructor("ZodNaN",(t,e)=>{I.$ZodNaN.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.nanProcessor(t,r,n,i)});function Xue(t){return I._nan(f.ZodNaN,t)}f.ZodPipe=I.$constructor("ZodPipe",(t,e)=>{I.$ZodPipe.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.pipeProcessor(t,r,n,i),t.in=e.in,t.out=e.out});function VC(t,e){return new f.ZodPipe({type:"pipe",in:t,out:e})}f.ZodCodec=I.$constructor("ZodCodec",(t,e)=>{f.ZodPipe.init(t,e),I.$ZodCodec.init(t,e)});function ele(t,e,r){return new f.ZodCodec({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}function tle(t){let e=t._zod.def;return new f.ZodCodec({type:"pipe",in:e.out,out:e.in,transform:e.reverseTransform,reverseTransform:e.transform})}f.ZodPreprocess=I.$constructor("ZodPreprocess",(t,e)=>{f.ZodPipe.init(t,e),I.$ZodPreprocess.init(t,e)});f.ZodReadonly=I.$constructor("ZodReadonly",(t,e)=>{I.$ZodReadonly.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.readonlyProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function xU(t){return new f.ZodReadonly({type:"readonly",innerType:t})}f.ZodTemplateLiteral=I.$constructor("ZodTemplateLiteral",(t,e)=>{I.$ZodTemplateLiteral.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.templateLiteralProcessor(t,r,n,i)});function rle(t,e){return new f.ZodTemplateLiteral({type:"template_literal",parts:t,...Qe.util.normalizeParams(e)})}f.ZodLazy=I.$constructor("ZodLazy",(t,e)=>{I.$ZodLazy.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.lazyProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.getter()});function LU(t){return new f.ZodLazy({type:"lazy",getter:t})}f.ZodPromise=I.$constructor("ZodPromise",(t,e)=>{I.$ZodPromise.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.promiseProcessor(t,r,n,i),t.unwrap=()=>t._zod.def.innerType});function nle(t){return new f.ZodPromise({type:"promise",innerType:t})}f.ZodFunction=I.$constructor("ZodFunction",(t,e)=>{I.$ZodFunction.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.functionProcessor(t,r,n,i)});function $h(t){return new f.ZodFunction({type:"function",input:Array.isArray(t?.input)?TU(t?.input):t?.input??Fh(Jc()),output:t?.output??Jc()})}f.ZodCustom=I.$constructor("ZodCustom",(t,e)=>{I.$ZodCustom.init(t,e),f.ZodType.init(t,e),t._zod.processJSONSchema=(r,n,i)=>be.customProcessor(t,r,n,i)});function ile(t){let e=new I.$ZodCheck({check:"custom"});return e._zod.check=t,e}function ole(t,e){return I._custom(f.ZodCustom,t??(()=>!0),e)}function PU(t,e={}){return I._refine(f.ZodCustom,t,e)}function FU(t,e){return I._superRefine(t,e)}f.describe=I.describe;f.meta=I.meta;function sle(t,e={}){let r=new f.ZodCustom({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...Qe.util.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=n=>{n.value instanceof t||n.issues.push({code:"invalid_type",expected:t.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var ale=(...t)=>I._stringbool({Codec:f.ZodCodec,Boolean:f.ZodBoolean,String:f.ZodString},...t);f.stringbool=ale;function cle(t){let e=LU(()=>WC([xh(t),QU(),vU(),_U(),Fh(e),RU(xh(),e)]));return e}function ule(t,e){return new f.ZodPreprocess({type:"pipe",in:KC(t),out:e})}});var zU=m(Nt=>{"use strict";var lle=Nt&&Nt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),dle=Nt&&Nt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ale=Nt&&Nt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&lle(e,t,r);return dle(e,t),e};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.ZodFirstPartyTypeKind=Nt.config=Nt.$brand=Nt.ZodIssueCode=void 0;Nt.setErrorMap=ple;Nt.getErrorMap=fle;var jU=Ale(hr());Nt.ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var qU=hr();Object.defineProperty(Nt,"$brand",{enumerable:!0,get:function(){return qU.$brand}});Object.defineProperty(Nt,"config",{enumerable:!0,get:function(){return qU.config}});function ple(t){jU.config({customError:t})}function fle(){return jU.config().customError}var $U;$U||(Nt.ZodFirstPartyTypeKind=$U={})});var GU=m(vo=>{"use strict";var hle=vo&&vo.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),gle=vo&&vo.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),XC=vo&&vo.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&hle(e,t,r);return gle(e,t),e};Object.defineProperty(vo,"__esModule",{value:!0});vo.fromJSONSchema=wle;var mle=sd(),yle=XC(Nh()),Ele=XC(dd()),Ile=XC(Ad()),z={...Ile,...yle,iso:Ele},Cle=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function ble(t,e){let r=t.$schema;return r==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":r==="http://json-schema.org/draft-07/schema#"?"draft-7":r==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function Sle(t,e){if(!t.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let r=t.slice(1).split("/").filter(Boolean);if(r.length===0)return e.rootSchema;let n=e.version==="draft-2020-12"?"$defs":"definitions";if(r[0]===n){let i=r[1];if(!i||!e.defs[i])throw new Error(`Reference not found: ${t}`);return e.defs[i]}throw new Error(`Reference not found: ${t}`)}function HU(t,e){if(t.not!==void 0){if(typeof t.not=="object"&&Object.keys(t.not).length===0)return z.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(t.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(t.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(t.if!==void 0||t.then!==void 0||t.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(t.dependentSchemas!==void 0||t.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(t.$ref){let i=t.$ref;if(e.refs.has(i))return e.refs.get(i);if(e.processing.has(i))return z.lazy(()=>{if(!e.refs.has(i))throw new Error(`Circular reference not resolved: ${i}`);return e.refs.get(i)});e.processing.add(i);let o=Sle(i,e),s=Ht(o,e);return e.refs.set(i,s),e.processing.delete(i),s}if(t.enum!==void 0){let i=t.enum;if(e.version==="openapi-3.0"&&t.nullable===!0&&i.length===1&&i[0]===null)return z.null();if(i.length===0)return z.never();if(i.length===1)return z.literal(i[0]);if(i.every(s=>typeof s=="string"))return z.enum(i);let o=i.map(s=>z.literal(s));return o.length<2?o[0]:z.union([o[0],o[1],...o.slice(2)])}if(t.const!==void 0)return z.literal(t.const);let r=t.type;if(Array.isArray(r)){let i=r.map(o=>{let s={...t,type:o};return HU(s,e)});return i.length===0?z.never():i.length===1?i[0]:z.union(i)}if(!r)return z.any();let n;switch(r){case"string":{let i=z.string();if(t.format){let o=t.format;o==="email"?i=i.check(z.email()):o==="uri"||o==="uri-reference"?i=i.check(z.url()):o==="uuid"||o==="guid"?i=i.check(z.uuid()):o==="date-time"?i=i.check(z.iso.datetime()):o==="date"?i=i.check(z.iso.date()):o==="time"?i=i.check(z.iso.time()):o==="duration"?i=i.check(z.iso.duration()):o==="ipv4"?i=i.check(z.ipv4()):o==="ipv6"?i=i.check(z.ipv6()):o==="mac"?i=i.check(z.mac()):o==="cidr"?i=i.check(z.cidrv4()):o==="cidr-v6"?i=i.check(z.cidrv6()):o==="base64"?i=i.check(z.base64()):o==="base64url"?i=i.check(z.base64url()):o==="e164"?i=i.check(z.e164()):o==="jwt"?i=i.check(z.jwt()):o==="emoji"?i=i.check(z.emoji()):o==="nanoid"?i=i.check(z.nanoid()):o==="cuid"?i=i.check(z.cuid()):o==="cuid2"?i=i.check(z.cuid2()):o==="ulid"?i=i.check(z.ulid()):o==="xid"?i=i.check(z.xid()):o==="ksuid"&&(i=i.check(z.ksuid()))}typeof t.minLength=="number"&&(i=i.min(t.minLength)),typeof t.maxLength=="number"&&(i=i.max(t.maxLength)),t.pattern&&(i=i.regex(new RegExp(t.pattern))),n=i;break}case"number":case"integer":{let i=r==="integer"?z.number().int():z.number();typeof t.minimum=="number"&&(i=i.min(t.minimum)),typeof t.maximum=="number"&&(i=i.max(t.maximum)),typeof t.exclusiveMinimum=="number"?i=i.gt(t.exclusiveMinimum):t.exclusiveMinimum===!0&&typeof t.minimum=="number"&&(i=i.gt(t.minimum)),typeof t.exclusiveMaximum=="number"?i=i.lt(t.exclusiveMaximum):t.exclusiveMaximum===!0&&typeof t.maximum=="number"&&(i=i.lt(t.maximum)),typeof t.multipleOf=="number"&&(i=i.multipleOf(t.multipleOf)),n=i;break}case"boolean":{n=z.boolean();break}case"null":{n=z.null();break}case"object":{let i={},o=t.properties||{},s=new Set(t.required||[]);for(let[c,u]of Object.entries(o)){let l=Ht(u,e);i[c]=s.has(c)?l:l.optional()}if(t.propertyNames){let c=Ht(t.propertyNames,e),u=t.additionalProperties&&typeof t.additionalProperties=="object"?Ht(t.additionalProperties,e):z.any();if(Object.keys(i).length===0){n=z.record(c,u);break}let l=z.object(i).passthrough(),d=z.looseRecord(c,u);n=z.intersection(l,d);break}if(t.patternProperties){let c=t.patternProperties,u=Object.keys(c),l=[];for(let A of u){let p=Ht(c[A],e),h=z.string().regex(new RegExp(A));l.push(z.looseRecord(h,p))}let d=[];if(Object.keys(i).length>0&&d.push(z.object(i).passthrough()),d.push(...l),d.length===0)n=z.object({}).passthrough();else if(d.length===1)n=d[0];else{let A=z.intersection(d[0],d[1]);for(let p=2;p<d.length;p++)A=z.intersection(A,d[p]);n=A}break}let a=z.object(i);t.additionalProperties===!1?n=a.strict():typeof t.additionalProperties=="object"?n=a.catchall(Ht(t.additionalProperties,e)):n=a.passthrough();break}case"array":{let i=t.prefixItems,o=t.items;if(i&&Array.isArray(i)){let s=i.map(c=>Ht(c,e)),a=o&&typeof o=="object"&&!Array.isArray(o)?Ht(o,e):void 0;a?n=z.tuple(s).rest(a):n=z.tuple(s),typeof t.minItems=="number"&&(n=n.check(z.minLength(t.minItems))),typeof t.maxItems=="number"&&(n=n.check(z.maxLength(t.maxItems)))}else if(Array.isArray(o)){let s=o.map(c=>Ht(c,e)),a=t.additionalItems&&typeof t.additionalItems=="object"?Ht(t.additionalItems,e):void 0;a?n=z.tuple(s).rest(a):n=z.tuple(s),typeof t.minItems=="number"&&(n=n.check(z.minLength(t.minItems))),typeof t.maxItems=="number"&&(n=n.check(z.maxLength(t.maxItems)))}else if(o!==void 0){let s=Ht(o,e),a=z.array(s);typeof t.minItems=="number"&&(a=a.min(t.minItems)),typeof t.maxItems=="number"&&(a=a.max(t.maxItems)),n=a}else n=z.array(z.any());break}default:throw new Error(`Unsupported type: ${r}`)}return n}function Ht(t,e){if(typeof t=="boolean")return t?z.any():z.never();let r=HU(t,e),n=t.type||t.enum!==void 0||t.const!==void 0;if(t.anyOf&&Array.isArray(t.anyOf)){let a=t.anyOf.map(u=>Ht(u,e)),c=z.union(a);r=n?z.intersection(r,c):c}if(t.oneOf&&Array.isArray(t.oneOf)){let a=t.oneOf.map(u=>Ht(u,e)),c=z.xor(a);r=n?z.intersection(r,c):c}if(t.allOf&&Array.isArray(t.allOf))if(t.allOf.length===0)r=n?r:z.any();else{let a=n?r:Ht(t.allOf[0],e),c=n?0:1;for(let u=c;u<t.allOf.length;u++)a=z.intersection(a,Ht(t.allOf[u],e));r=a}t.nullable===!0&&e.version==="openapi-3.0"&&(r=z.nullable(r)),t.readOnly===!0&&(r=z.readonly(r)),t.default!==void 0&&(r=r.default(t.default));let i={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of o)a in t&&(i[a]=t[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in t&&(i[a]=t[a]);for(let a of Object.keys(t))Cle.has(a)||(i[a]=t[a]);return Object.keys(i).length>0&&e.registry.add(r,i),t.description&&(r=r.describe(t.description)),r}function wle(t,e){if(typeof t=="boolean")return t?z.any():z.never();let r;try{r=JSON.parse(JSON.stringify(t))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}let n=ble(r,e?.defaultTarget),i=r.$defs||r.definitions||{},o={version:n,defs:i,refs:new Map,processing:new Set,rootSchema:r,registry:e?.registry??mle.globalRegistry};return Ht(r,o)}});var VU=m(Ur=>{"use strict";var Ble=Ur&&Ur.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Qle=Ur&&Ur.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),YU=Ur&&Ur.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&Ble(e,t,r);return Qle(e,t),e};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.string=vle;Ur.number=_le;Ur.boolean=Dle;Ur.bigint=Tle;Ur.date=Rle;var hd=YU(hr()),gd=YU(Ad());function vle(t){return hd._coercedString(gd.ZodString,t)}function _le(t){return hd._coercedNumber(gd.ZodNumber,t)}function Dle(t){return hd._coercedBoolean(gd.ZodBoolean,t)}function Tle(t){return hd._coercedBigint(gd.ZodBigInt,t)}function Rle(t){return hd._coercedDate(gd.ZodDate,t)}});var eb=m(J=>{"use strict";var JU=J&&J.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),kle=J&&J.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),jh=J&&J.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&JU(e,t,r);return kle(e,t),e},md=J&&J.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&JU(e,t,r)},Nle=J&&J.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(J,"__esModule",{value:!0});J.coerce=J.iso=J.ZodISODuration=J.ZodISOTime=J.ZodISODate=J.ZodISODateTime=J.locales=J.fromJSONSchema=J.toJSONSchema=J.NEVER=J.util=J.TimePrecision=J.flattenError=J.formatError=J.prettifyError=J.treeifyError=J.regexes=J.clone=J.$brand=J.$input=J.$output=J.config=J.registry=J.globalRegistry=J.core=void 0;J.core=jh(hr());md(Ad(),J);md(Nh(),J);md(zC(),J);md(HC(),J);md(zU(),J);var Ole=hr(),Ule=Nle(MC());(0,Ole.config)((0,Ule.default)());var nr=hr();Object.defineProperty(J,"globalRegistry",{enumerable:!0,get:function(){return nr.globalRegistry}});Object.defineProperty(J,"registry",{enumerable:!0,get:function(){return nr.registry}});Object.defineProperty(J,"config",{enumerable:!0,get:function(){return nr.config}});Object.defineProperty(J,"$output",{enumerable:!0,get:function(){return nr.$output}});Object.defineProperty(J,"$input",{enumerable:!0,get:function(){return nr.$input}});Object.defineProperty(J,"$brand",{enumerable:!0,get:function(){return nr.$brand}});Object.defineProperty(J,"clone",{enumerable:!0,get:function(){return nr.clone}});Object.defineProperty(J,"regexes",{enumerable:!0,get:function(){return nr.regexes}});Object.defineProperty(J,"treeifyError",{enumerable:!0,get:function(){return nr.treeifyError}});Object.defineProperty(J,"prettifyError",{enumerable:!0,get:function(){return nr.prettifyError}});Object.defineProperty(J,"formatError",{enumerable:!0,get:function(){return nr.formatError}});Object.defineProperty(J,"flattenError",{enumerable:!0,get:function(){return nr.flattenError}});Object.defineProperty(J,"TimePrecision",{enumerable:!0,get:function(){return nr.TimePrecision}});Object.defineProperty(J,"util",{enumerable:!0,get:function(){return nr.util}});Object.defineProperty(J,"NEVER",{enumerable:!0,get:function(){return nr.NEVER}});var Mle=ld();Object.defineProperty(J,"toJSONSchema",{enumerable:!0,get:function(){return Mle.toJSONSchema}});var xle=GU();Object.defineProperty(J,"fromJSONSchema",{enumerable:!0,get:function(){return xle.fromJSONSchema}});J.locales=jh(PC());var qh=dd();Object.defineProperty(J,"ZodISODateTime",{enumerable:!0,get:function(){return qh.ZodISODateTime}});Object.defineProperty(J,"ZodISODate",{enumerable:!0,get:function(){return qh.ZodISODate}});Object.defineProperty(J,"ZodISOTime",{enumerable:!0,get:function(){return qh.ZodISOTime}});Object.defineProperty(J,"ZodISODuration",{enumerable:!0,get:function(){return qh.ZodISODuration}});J.iso=jh(dd());J.coerce=jh(VU())});var tb=m(gr=>{"use strict";var WU=gr&&gr.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),Lle=gr&&gr.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ple=gr&&gr.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!=="default"&&Object.prototype.hasOwnProperty.call(t,r)&&WU(e,t,r);return Lle(e,t),e},Fle=gr&&gr.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&WU(e,t,r)};Object.defineProperty(gr,"__esModule",{value:!0});gr.z=void 0;var ZU=Ple(eb());gr.z=ZU;Fle(eb(),gr);gr.default=ZU});var rb=m(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.PROJECT_LIMITS=_o.PROJECT_TASK_STATUSES=_o.PROJECT_RESOURCE_TYPES=void 0;_o.projectResourceKey=$le;_o.PROJECT_RESOURCE_TYPES=["system","playbook","artifact","file","tool"];_o.PROJECT_TASK_STATUSES=["not_started","in_progress","waiting","done"];_o.PROJECT_LIMITS={name:80,description:500,taskName:120,taskDescription:1e4,taskResources:100};function $le(t){return`${t.type}:${t.id}`}});var zh=m(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.RESOURCE_KINDS=Mr.RESOURCE_DEFINITIONS=void 0;Mr.isResourceKind=jle;Mr.getResourceDefinition=qle;Mr.getResourceAppPath=zle;Mr.RESOURCE_DEFINITIONS={tool:{label:"Tool",pluralLabel:"Tools",collectionKey:"tools",appPath:"/tools",hasDetailPage:!0,memberDefaultPermission:"editor",pickerDefaultPermission:"editor"},system:{label:"System",pluralLabel:"Systems",collectionKey:"systems",appPath:"/systems",hasDetailPage:!0,memberDefaultPermission:"editor",pickerDefaultPermission:"editor"},credential:{label:"Credential",pluralLabel:"Credentials",collectionKey:"credentials",appPath:"/credentials",hasDetailPage:!1,pickerDefaultPermission:"viewer"},playbook:{label:"Playbook",pluralLabel:"Playbooks",collectionKey:"playbooks",appPath:"/playbooks",hasDetailPage:!0,pickerDefaultPermission:"editor"},artifact:{label:"Artifact",pluralLabel:"Artifacts",collectionKey:"artifacts",appPath:"/artifacts",hasDetailPage:!0,pickerDefaultPermission:"editor"},file:{label:"File",pluralLabel:"Files",collectionKey:"files",appPath:"/files",hasDetailPage:!1,pickerDefaultPermission:"viewer"},project:{label:"Project",pluralLabel:"Projects",collectionKey:"projects",appPath:"/projects",hasDetailPage:!0,pickerDefaultPermission:"viewer"}};Mr.RESOURCE_KINDS=Object.keys(Mr.RESOURCE_DEFINITIONS);function jle(t){return typeof t=="string"&&Object.prototype.hasOwnProperty.call(Mr.RESOURCE_DEFINITIONS,t)}function qle(t){return Mr.RESOURCE_DEFINITIONS[t]}function zle(t,e){let r=Mr.RESOURCE_DEFINITIONS[t];return r.hasDetailPage?`${r.appPath}/${encodeURIComponent(e)}`:r.appPath}});var tM=m(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.SDK_ERROR_DETAILS_SCHEMA=Ea.SDK_OUTPUT_CONTRACTS=void 0;Ea.toSdkJsonSchema=Vle;var b=tb(),Hle=rb(),Gle=zh(),Yle=dr();function Vle({schema:t}){return b.z.toJSONSchema(t,{target:"draft-7",io:"output",unrepresentable:"any"})}var KU=b.z.looseObject({statusCode:b.z.number(),headers:b.z.record(b.z.string(),b.z.union([b.z.string(),b.z.array(b.z.string())])),omittedHeaderCount:b.z.number().optional()}),XU=b.z.looseObject({vfsPath:b.z.string(),storedBytes:b.z.number(),originalOutputBytes:b.z.number(),storageTruncated:b.z.boolean()}),eM=b.z.object({action:b.z.enum(["approve","reject","oauth_success","oauth_failure"]),source:b.z.enum(["user","automatic"])});function ps(t){return b.z.looseObject({toolCallId:b.z.string(),toolName:b.z.string(),outcome:b.z.literal("success"),confirmation:eM.optional(),data:t})}var nb={http:KU.optional(),credential:b.z.looseObject({id:b.z.string(),name:b.z.string(),isOwner:b.z.boolean()}).optional().describe("The credential the call ran with."),auth:b.z.looseObject({applied:b.z.enum(["bearer","basic","explicit","none","unavailable"]),header:b.z.string().optional(),placeholders:b.z.array(b.z.string()),reason:b.z.string().optional()}).optional().describe("How authentication was sent: a default Bearer or Basic header, the request's own explicit placeholders, none, or unavailable with the reason. placeholders lists the credential's <<systemId_secretName>> strings."),credentialPlaceholders:b.z.looseObject({keys:b.z.array(b.z.string()),resolved:b.z.boolean()}).optional()},Jle=b.z.discriminatedUnion("protocol",[b.z.looseObject({protocol:b.z.enum(["postgres","odbc"]),data:b.z.array(b.z.record(b.z.string(),b.z.unknown())).describe("Returned database rows."),...nb}),b.z.looseObject({protocol:b.z.literal("mssql"),data:b.z.union([b.z.array(b.z.record(b.z.string(),b.z.unknown())),b.z.array(b.z.array(b.z.record(b.z.string(),b.z.unknown()))),b.z.looseObject({rowsAffected:b.z.array(b.z.number())})]).describe("One recordset, multiple recordsets, or affected row counts."),...nb}),b.z.looseObject({protocol:b.z.enum(Yle.CONNECTION_PROTOCOLS.filter(t=>t!=="postgres"&&t!=="mssql"&&t!=="odbc")),data:b.z.unknown().describe("Complete protocol response payload. Preserve sibling fields, including files and metadata; do not unwrap a nested data field."),...nb})]),Wle=b.z.union([b.z.looseObject({tools:b.z.array(b.z.unknown()).describe("All tools from every tools/list page, each with name and inputSchema.")}),b.z.looseObject({result:b.z.looseObject({content:b.z.array(b.z.unknown()).optional(),structuredContent:b.z.unknown().optional(),isError:b.z.boolean().optional()}).describe("The tools/call result with content blocks and optional structuredContent.")})]),Zle=b.z.looseObject({stepId:b.z.string(),success:b.z.boolean(),data:b.z.unknown().optional(),error:b.z.string().nullable().optional(),http:KU.optional(),stepFileKeys:b.z.array(b.z.string()).optional()}),Kle=b.z.looseObject({toolId:b.z.string(),success:b.z.boolean(),run:b.z.looseObject({id:b.z.string()}).optional(),data:b.z.unknown().optional().describe("Tool output, determined by its output transform."),error:b.z.string().optional(),stepResults:b.z.array(Zle),fileArtifacts:b.z.array(b.z.looseObject({fileKey:b.z.string(),filename:b.z.string(),contentType:b.z.string(),size:b.z.number(),downloadUrl:b.z.string().optional()})).optional(),warnings:b.z.array(b.z.string()).optional(),inputSchema:b.z.unknown().optional(),resultMetadata:XU.optional()}),Xle=ps(b.z.looseObject({resource:b.z.looseObject({id:b.z.string(),name:b.z.string().optional(),version:b.z.union([b.z.number(),b.z.string()]).optional()}),created:b.z.boolean(),projectId:b.z.string().optional(),addedFiles:b.z.array(b.z.looseObject({id:b.z.string(),fileName:b.z.string()})).optional(),projectAttribution:b.z.looseObject({attached:b.z.boolean(),projectId:b.z.string(),projectName:b.z.string().optional(),resource:b.z.looseObject({type:b.z.enum(Hle.PROJECT_RESOURCE_TYPES),id:b.z.string()}),error:b.z.string().optional()}).optional()}));Ea.SDK_OUTPUT_CONTRACTS={assignSessionToProject:{name:"SuperglueSessionProjectResult",schema:ps(b.z.object({sessionId:b.z.string(),projectId:b.z.string().nullable()})),description:"Returns the saved session ID and project ID, or null when unassigned. Throws SuperglueError on failure."},callSystem:{name:"SuperglueCallSystemResult",schema:Jle,description:"Returns the complete protocol payload in data, available HTTP metadata, the credential used, and how authentication was sent. Throws SuperglueError on failure; details contains the canonical result and unprojected execution output."},callMcp:{name:"SuperglueCallMcpResult",schema:Wle,description:"Returns { tools } when tool is omitted, or { result } from tools/call. Throws SuperglueError on HTTP, JSON-RPC, or result.isError failures; details.result.data contains statusCode, rpcError, or the failed result."},runTool:{name:"SuperglueRunToolResult",schema:Kle,description:"Returns successful tool output, step results, files, and available result reference. Throws SuperglueError on failure; details.result.data preserves this result shape with success: false, the error, and available run and step results. details.resultMetadata references the saved failed result when available."},writeResource:{name:"SuperglueWriteResult",schema:Xle,description:"Returns saved resource identity, creation status, and available project attribution or added files. Throws SuperglueError on failure."},installBundle:{name:"SuperglueBundleInstallResult",schema:ps(b.z.looseObject({bundleId:b.z.string(),system:b.z.looseObject({id:b.z.string(),name:b.z.string(),requiredCredentialKeys:b.z.array(b.z.string()),hasUserCredentials:b.z.boolean()}),tools:b.z.array(b.z.looseObject({id:b.z.string(),name:b.z.string().optional()})),mcpServer:b.z.looseObject({id:b.z.string(),name:b.z.string()}).optional(),playbook:b.z.looseObject({id:b.z.string(),name:b.z.string()}).optional()})),description:"Returns the installed system, tool, MCP server, and playbook identities, the secret names the user must supply, and whether the user has a complete credential. Throws SuperglueError on failure."},setToolState:{name:"SuperglueToolStateResult",schema:ps(b.z.looseObject({resource:b.z.looseObject({id:b.z.string()}),action:b.z.enum(["set","reset"])})),description:"Returns the saved tool identity and state action. Throws SuperglueError on failure."},shareResource:{name:"SuperglueShareResult",schema:ps(b.z.looseObject({resource:b.z.looseObject({kind:b.z.enum(Gle.RESOURCE_KINDS),id:b.z.string()})})),description:"Returns the shared resource identity. Throws SuperglueError on failure."},notifyUser:{name:"SuperglueNotifyResult",schema:ps(b.z.looseObject({actionCount:b.z.number()})),description:"Returns the notification action count. Throws SuperglueError on failure."},writeOrgSettings:{name:"SuperglueOrgSettingsResult",schema:ps(b.z.looseObject({updated:b.z.array(b.z.enum(["name","logo","brandGuidelines","preferences","notifications"])),notificationTest:b.z.looseObject({channel:b.z.enum(["slack","email"]),sent:b.z.boolean(),error:b.z.string().optional()}).optional()})),description:"Returns updated settings and any notification test result. Throws SuperglueError on failure."},readQbm:{name:"SuperglueReadQbmResult",schema:ps(b.z.looseObject({folder:b.z.string(),objects:b.z.array(b.z.looseObject({type:b.z.string(),files:b.z.array(b.z.string()),records:b.z.number()})),rawTables:b.z.array(b.z.looseObject({table:b.z.string(),files:b.z.array(b.z.string()),rows:b.z.number()})),encryptedValues:b.z.array(b.z.looseObject({table:b.z.string(),column:b.z.string(),values:b.z.number()})),unmappedCodes:b.z.array(b.z.looseObject({field:b.z.string(),code:b.z.string(),records:b.z.number()})).optional(),attachments:b.z.looseObject({documents:b.z.number(),note:b.z.string()}).optional(),rejectedRows:b.z.array(b.z.looseObject({table:b.z.string(),rows:b.z.number()})).optional()})),description:"Returns the folder that holds the extracted files, record counts per object type and raw table, encrypted columns, codes the reader cannot decode, and expected attachments. The folder also holds coverage.json.raw with the same summary plus the mapped source tables. Throws SuperglueError on failure."},previewArtifact:{name:"SuperglueArtifactPreviewResult",schema:b.z.looseObject({draftId:b.z.string(),bytes:b.z.number()}),description:"Returns the artifact draft identity and byte count. Throws SuperglueError on failure."}};var ede=b.z.looseObject({code:b.z.string(),path:b.z.array(b.z.union([b.z.string(),b.z.number(),b.z.symbol()])),message:b.z.string()});Ea.SDK_ERROR_DETAILS_SCHEMA=b.z.discriminatedUnion("kind",[b.z.looseObject({kind:b.z.literal("tool_result"),resultMetadata:XU.optional(),result:b.z.looseObject({toolCallId:b.z.string(),toolName:b.z.string(),outcome:b.z.enum(["success","failure","rejected","aborted"]),confirmation:eM.optional(),error:b.z.looseObject({message:b.z.string()}).optional(),data:b.z.unknown().optional()}),output:b.z.unknown().describe("Unprojected execution output, including the original error and any available response data or metadata.")}),b.z.looseObject({kind:b.z.enum(["input_validation","output_validation"]),toolName:b.z.string(),issues:b.z.array(ede),output:b.z.unknown().optional()})])});var pM=m(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.SERVER_OWNED_SESSION_RESOURCE_KINDS=Ee.AgentRequestValidationError=Ee.AGENT_TOOL_CONTINUATION_ACTION_BY_CONFIRMATION_STATE=Ee.AGENT_TOOL_CONTINUATION_ACTIONS=Ee.AGENT_IDENTIFIER_PATTERN=Ee.AGENT_REQUEST_LIMITS=void 0;Ee.validateAgentRequestPayload=cM;Ee.validateResourceBinding=uM;Ee.validateClientResourceBinding=lM;Ee.validateAgentSessionIdentity=dM;Ee.validateAgentSessionTarget=AM;Ee.validateAgentRequestSubmission=sde;Ee.isAgentMessagePayload=ade;Ee.isAgentToolContinuationPayload=cde;var Do=dr();Ee.AGENT_REQUEST_LIMITS={messageContentChars:5e4,identifierChars:256,attachedFiles:20,toolContinuations:20,continuationInputChars:1e5,frontendDraftsChars:2e6,accessRulesContextChars:2e6};Ee.AGENT_IDENTIFIER_PATTERN=/^[A-Za-z0-9._-]+$/;Ee.AGENT_TOOL_CONTINUATION_ACTIONS=["approve","reject","oauth_success","oauth_failure"];Ee.AGENT_TOOL_CONTINUATION_ACTION_BY_CONFIRMATION_STATE={[Do.ConfirmationAction.CONFIRMED]:"approve",[Do.ConfirmationAction.DECLINED]:"reject",[Do.ConfirmationAction.OAUTH_SUCCESS]:"oauth_success",[Do.ConfirmationAction.OAUTH_FAILURE]:"oauth_failure"};var Hh=class extends Error{constructor(e){super(e),this.name="AgentRequestValidationError"}};Ee.AgentRequestValidationError=Hh;function Ge(t){throw new Hh(t)}function Zi(t,e){return(!t||typeof t!="object"||Array.isArray(t))&&Ge(`${e} must be an object`),t}function Ia(t,e){(typeof t!="string"||!t.trim())&&Ge(`${e} must be a non-empty string`);let r=t.trim();return r.length>Ee.AGENT_REQUEST_LIMITS.identifierChars&&Ge(`${e} exceeds ${Ee.AGENT_REQUEST_LIMITS.identifierChars} characters`),Ee.AGENT_IDENTIFIER_PATTERN.test(r)||Ge(`${e} may only contain letters, numbers, dots, underscores, and hyphens`),r}function tde(t,e){return typeof t!="boolean"&&Ge(`${e} must be a boolean`),t}function ib(t,e){try{return JSON.stringify(t).length}catch{return Ge(`${e} must be JSON-serializable`)}}function rde(t,e){if(t!==void 0)return Array.isArray(t)||Ge(`${e} must be an array`),t.length>Ee.AGENT_REQUEST_LIMITS.attachedFiles&&Ge(`${e} exceeds ${Ee.AGENT_REQUEST_LIMITS.attachedFiles} entries`),t.map((r,n)=>{let i=Zi(r,`${e}[${n}]`);return{...i,key:Ia(i.key,`${e}[${n}].key`)}})}function rM({value:t,label:e,requireHidden:r}){let n=Zi(t,e),i=Ia(n.id,`${e}.id`);typeof n.content!="string"&&Ge(`${e}.content must be a string`);let o=n.content;o.length>Ee.AGENT_REQUEST_LIMITS.messageContentChars&&Ge(`${e}.content exceeds ${Ee.AGENT_REQUEST_LIMITS.messageContentChars} characters`);let s=tde(n.isHidden,`${e}.isHidden`);r&&!s&&Ge(`${e}.isHidden must be true`);let a=rde(n.attachedFiles,`${e}.attachedFiles`);return!o.trim()&&!a?.length&&Ge(`${e}.content may only be empty when an attachment is present`),{id:i,content:o,isHidden:s,...a?{attachedFiles:a}:{}}}function iM(t){if(t===void 0)return;let e=Zi(t,"frontendDrafts");return ib(e,"frontendDrafts")>Ee.AGENT_REQUEST_LIMITS.frontendDraftsChars&&Ge(`frontendDrafts exceeds ${Ee.AGENT_REQUEST_LIMITS.frontendDraftsChars} characters`),e}function oM(t){if(t===void 0)return;let e=Zi(t,"accessRulesContext");return ib(e,"accessRulesContext")>Ee.AGENT_REQUEST_LIMITS.accessRulesContextChars&&Ge(`accessRulesContext exceeds ${Ee.AGENT_REQUEST_LIMITS.accessRulesContextChars} characters`),e}function sM(t){if(t!==void 0)return(typeof t!="string"||!Do.AGENT_APPROVAL_MODES.includes(t))&&Ge(`request.approvalMode must be one of: ${Do.AGENT_APPROVAL_MODES.join(", ")}`),t}function aM(t,e){let r=Zi(t,e),n=Ia(r.toolCallId,`${e}.toolCallId`);return(typeof r.action!="string"||!Ee.AGENT_TOOL_CONTINUATION_ACTIONS.includes(r.action))&&Ge(`${e}.action must be one of: ${Ee.AGENT_TOOL_CONTINUATION_ACTIONS.join(", ")}`),r.input!==void 0&&ib(r.input,`${e}.input`)>Ee.AGENT_REQUEST_LIMITS.continuationInputChars&&Ge(`${e}.input exceeds ${Ee.AGENT_REQUEST_LIMITS.continuationInputChars} characters`),{toolCallId:n,action:r.action,...r.input!==void 0?{input:r.input}:{}}}function nde(t){if(t===void 0)return;(!Array.isArray(t)||t.length===0)&&Ge("request.toolContinuations must be a non-empty array"),t.length>Ee.AGENT_REQUEST_LIMITS.toolContinuations&&Ge(`request.toolContinuations exceeds ${Ee.AGENT_REQUEST_LIMITS.toolContinuations} entries`);let e=t.map((r,n)=>aM(r,`request.toolContinuations[${n}]`));return new Set(e.map(({toolCallId:r})=>r)).size!==e.length&&Ge("request.toolContinuations must not contain duplicate toolCallId values"),e}function nM(t,e){if(t===void 0)return;(typeof t!="string"||!t.trim())&&Ge(`${e} must be a non-empty string`);let r=t.trim();return r.length>Ee.AGENT_REQUEST_LIMITS.messageContentChars&&Ge(`${e} exceeds ${Ee.AGENT_REQUEST_LIMITS.messageContentChars} characters`),r}function ide(t){let e=rM({value:t.message,label:"request.message"}),r=nM(t.title,"request.title"),n=nM(t.titleInput,"request.titleInput"),i=t.hiddenSteeringMessage===void 0?void 0:rM({value:t.hiddenSteeringMessage,label:"request.hiddenSteeringMessage",requireHidden:!0});i&&i.id===e.id&&Ge("request.hiddenSteeringMessage.id must differ from request.message.id");let o=nde(t.toolContinuations),s=sM(t.approvalMode),a=iM(t.frontendDrafts),c=oM(t.accessRulesContext);return{kind:"message",message:e,...i?{hiddenSteeringMessage:i}:{},...r?{title:r}:{},...n?{titleInput:n}:{},...o?{toolContinuations:o}:{},...s?{approvalMode:s}:{},...a?{frontendDrafts:a}:{},...c?{accessRulesContext:c}:{}}}function ode(t){let e=aM(t,"request"),r=sM(t.approvalMode),n=iM(t.frontendDrafts),i=oM(t.accessRulesContext);return{kind:"tool_continuation",...e,...r?{approvalMode:r}:{},...n?{frontendDrafts:n}:{},...i?{accessRulesContext:i}:{}}}function cM(t){let e=Zi(t,"request");return e.kind==="message"?ide(e):e.kind==="tool_continuation"?ode(e):Ge('request.kind must be "message" or "tool_continuation"')}function uM(t,e){let r=Zi(t,e);return(typeof r.kind!="string"||!Do.AGENT_SESSION_RESOURCE_KINDS.includes(r.kind))&&Ge(`${e}.kind must be one of: ${Do.AGENT_SESSION_RESOURCE_KINDS.join(", ")}`),{kind:r.kind,id:Ia(r.id,`${e}.id`)}}Ee.SERVER_OWNED_SESSION_RESOURCE_KINDS=["briefing"];function lM(t,e){let r=uM(t,e);return Ee.SERVER_OWNED_SESSION_RESOURCE_KINDS.includes(r.kind)&&Ge(`${e}.kind "${r.kind}" is assigned by the server`),r}function dM(t,e="session.createIfMissing"){let r=Zi(t,e),n=r.projectId===void 0?void 0:Ia(r.projectId,`${e}.projectId`),i=r.taskId===void 0?void 0:Ia(r.taskId,`${e}.taskId`);i&&!n&&Ge(`${e}.taskId requires ${e}.projectId`);let o=Object.values(Do.AgentType);(typeof r.agentId!="string"||!o.includes(r.agentId))&&Ge(`${e}.agentId must be one of: ${o.join(", ")}`);let s=r.resourceBinding===void 0?void 0:lM(r.resourceBinding,`${e}.resourceBinding`);return{agentId:r.agentId,...n?{projectId:n}:{},...i?{taskId:i}:{},...s?{resourceBinding:s}:{}}}function AM(t){let e=Zi(t,"session"),r=e.createIfMissing===void 0?void 0:dM(e.createIfMissing);return{id:Ia(e.id,"session.id"),...r?{createIfMissing:r}:{}}}function sde(t){let e=Zi(t,"body");return{session:AM(e.session),request:cM(e.request)}}function ade(t){return t.kind==="message"}function cde(t){return t.kind==="tool_continuation"}});var hM=m(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.ARTIFACT_EXPORT_FORMATS=Fe.ARTIFACT_RESPONSE_RESERVED_FIELD_NAMES=Fe.ARTIFACT_RESPONSE_PATCH_DEBOUNCE_MS=Fe.MAX_SPREADSHEET_ARTIFACT_BYTES=Fe.MAX_HTML_ARTIFACT_IMAGE_BYTES=Fe.MAX_HTML_ARTIFACT_BYTES=Fe.MAX_SPREADSHEET_CELL_TEXT_LENGTH=Fe.MAX_SPREADSHEET_SHEET_NAME_LENGTH=Fe.MAX_SPREADSHEET_GRID_CELLS=Fe.MAX_SPREADSHEET_SHEETS=Fe.SPREADSHEET_CELL_TYPES=void 0;Fe.isValidSpreadsheetCell=dde;Fe.isArtifactExportFormat=Ade;Fe.isArtifactExportFormatForKind=pde;var fM=tb();Fe.SPREADSHEET_CELL_TYPES=["text","integer","number","percent","currency","boolean","date","datetime"];Fe.MAX_SPREADSHEET_SHEETS=20;Fe.MAX_SPREADSHEET_GRID_CELLS=1e6;Fe.MAX_SPREADSHEET_SHEET_NAME_LENGTH=31;Fe.MAX_SPREADSHEET_CELL_TEXT_LENGTH=32767;var ude=fM.z.iso.date(),lde=fM.z.iso.datetime({offset:!0});function dde(t,e){return t===null?!0:e==="text"?typeof t=="string"&&t.length<=Fe.MAX_SPREADSHEET_CELL_TEXT_LENGTH:e==="boolean"?typeof t=="boolean":["integer","number","percent","currency"].includes(e)?typeof t=="number"&&Number.isFinite(t)&&(e!=="integer"||Number.isInteger(t)):typeof t!="string"?!1:(e==="datetime"?lde:ude).safeParse(t).success}Fe.MAX_HTML_ARTIFACT_BYTES=1024*1024;Fe.MAX_HTML_ARTIFACT_IMAGE_BYTES=12*1024*1024;Fe.MAX_SPREADSHEET_ARTIFACT_BYTES=10*1024*1024;Fe.ARTIFACT_RESPONSE_PATCH_DEBOUNCE_MS=300;Fe.ARTIFACT_RESPONSE_RESERVED_FIELD_NAMES=new Set(["__proto__","constructor","prototype"]);Fe.ARTIFACT_EXPORT_FORMATS=["html","pdf","docx","xlsx"];function Ade(t){return Fe.ARTIFACT_EXPORT_FORMATS.some(e=>e===t)}function pde(t,e){return t==="html"||e==="xlsx"}});var IM=m(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.API_KEY_ACTION_LABELS=Me.API_KEY_SURFACE_LABELS=Me.API_KEY_SCOPES=Me.API_KEY_SURFACE_ACTIONS=Me.API_KEY_ACTIONS=Me.API_KEY_SURFACES=void 0;Me.getApiKeySurface=mM;Me.getApiKeyAction=yM;Me.getApiKeySurfaceActions=ob;Me.parseApiKeyScopes=EM;Me.validateApiKeyScopesInput=mde;Me.isApiKeyScopeAllowed=yde;Me.formatApiKeyScopes=Ede;Me.API_KEY_SURFACES=["api","mcp"];Me.API_KEY_ACTIONS=["read","write","execute"];Me.API_KEY_SURFACE_ACTIONS={api:Me.API_KEY_ACTIONS,mcp:["execute"]};Me.API_KEY_SCOPES=Me.API_KEY_SURFACES.flatMap(t=>Me.API_KEY_SURFACE_ACTIONS[t].map(e=>`${t}:${e}`));Me.API_KEY_SURFACE_LABELS={api:"API & CLI",mcp:"MCP"};Me.API_KEY_ACTION_LABELS={read:"Read",write:"Write",execute:"Execute"};var gM=new Set(Me.API_KEY_SCOPES),fde={"/v1/tools":["read"],"/v1/tools/:toolId/run":["execute"],"/v1/authenticate":["write"],"/v1/memory-notes":["read","write"]},hde=new Set(["/v1/api-keys","/v1/api-keys/:id","/v1/api-keys/:id/reveal"]),gde=new Set(["/v1/me"]);function mM(t){let e=t.split("?")[0];return e==="/mcp"||e.startsWith("/mcp/")?"mcp":"api"}function yM(t){return t==="read"?"read":t==="execute"?"execute":"write"}function ob(t,e){return Me.API_KEY_SURFACE_ACTIONS[e].filter(r=>(t||[]).includes(`${e}:${r}`))}function EM(t){if(!Array.isArray(t))return null;let e=[...new Set(t.filter(r=>gM.has(r)))];return e.length>0?e:null}function mde(t){if(t==null)return{scopes:null};let e=`Valid scopes: ${Me.API_KEY_SCOPES.join(", ")}. Use null for full access.`;if(!Array.isArray(t)||t.length===0)return{error:`scopes must be a non-empty array of API key scopes. ${e}`};let r=t.filter(n=>!gM.has(n));return r.length>0?{error:`Unknown API key scope(s): ${r.map(String).join(", ")}. ${e}`}:{scopes:EM(t)}}function yde({scopes:t,path:e,type:r}){if(!t||t.length===0)return!0;let n=e.split("?")[0];if(hde.has(n))return!1;if(gde.has(n))return!0;let i=yM(r),o=mM(n);return o==="api"&&fde[n]?.some(s=>s===r)&&ob(t,"mcp").length>0?!0:t.includes(`${o}:${i}`)}function Ede(t){return!t||t.length===0?"Full access":Me.API_KEY_SURFACES.map(e=>({surface:e,actions:ob(t,e)})).filter(e=>e.actions.length>0).map(e=>Me.API_KEY_SURFACE_ACTIONS[e.surface].length===1?Me.API_KEY_SURFACE_LABELS[e.surface]:`${Me.API_KEY_SURFACE_LABELS[e.surface]} ${e.actions.join("/")}`).join(", ")}});var CM=m(sb=>{"use strict";Object.defineProperty(sb,"__esModule",{value:!0});sb.isValidEmail=Ide;function Ide(t){return/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{1,}$/.test(t)}});var SM=m(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.GATEWAY_UNINSTALL_COMMANDS=dt.GATEWAY_API_KEY_NAME_PREFIX=dt.GATEWAY_TARGET_NAME_PATTERN=dt.GATEWAY_SETUP_GUIDE_URL=dt.GATEWAY_DOWNLOAD_BASE_URL=dt.GATEWAY_INSTALL_TOKEN_PREFIX=void 0;dt.getGatewayServerUrl=bM;dt.buildGatewayInstallToken=bde;dt.buildGatewayInstallCommand=Sde;dt.getGatewayApiKeyName=wde;dt.GATEWAY_INSTALL_TOKEN_PREFIX="sgi1.";dt.GATEWAY_DOWNLOAD_BASE_URL="https://downloads.superglue.cloud";dt.GATEWAY_SETUP_GUIDE_URL="https://superglue.ai/docs/guides/secure-gateway/";dt.GATEWAY_TARGET_NAME_PATTERN=/^[a-z0-9]([a-z0-9_-]{0,61}[a-z0-9])?$/;function bM(t){let e=new URL(t);return e.protocol=e.protocol==="http:"?"ws:":"wss:",e.pathname=`${e.pathname.replace(/\/+$/,"")}/ws/tunnels`,e.search="",e.hash="",e.toString()}function Cde(t){let e=new TextEncoder().encode(t),r="";for(let n of e)r+=String.fromCharCode(n);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function bde(t){let e={v:1,serverUrl:bM(t.apiEndpoint),tunnelId:t.tunnelId,apiKey:t.apiKey,targets:t.targets,enableScriptRunner:t.enableScriptRunner};return dt.GATEWAY_INSTALL_TOKEN_PREFIX+Cde(JSON.stringify(e))}function Sde(t,e){return t==="windows"?['$ErrorActionPreference = "Stop"',"[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor 3072",'$ProgressPreference = "SilentlyContinue"','$gateway = "$env:TEMP\\superglue-gateway.exe"',"Remove-Item $gateway -Force -ErrorAction SilentlyContinue",`Invoke-WebRequest -UseBasicParsing "${dt.GATEWAY_DOWNLOAD_BASE_URL}/superglue-gateway-windows.exe" -OutFile $gateway`,`"${e}" | & $gateway install -`].join("; "):["d=$(mktemp -d)",`u="${dt.GATEWAY_DOWNLOAD_BASE_URL}/superglue-gateway-linux-$(uname -m | sed 's/aarch64/arm64/')"`,'s=$([ "$(id -u)" -eq 0 ] || echo sudo)','{ if command -v curl >/dev/null; then curl -fsSL -o "$d/superglue-gateway" "$u"; else wget -qO "$d/superglue-gateway" "$u"; fi; }','$s install -m 0755 "$d/superglue-gateway" /usr/local/bin/superglue-gateway',`echo '${e}' | $s /usr/local/bin/superglue-gateway install -`].join(" && ")}dt.GATEWAY_API_KEY_NAME_PREFIX="Gateway: ";function wde(t){return dt.GATEWAY_API_KEY_NAME_PREFIX+t}dt.GATEWAY_UNINSTALL_COMMANDS={windows:'& "C:\\Program Files\\superglue Gateway\\superglue-gateway.exe" uninstall',linux:"sudo /usr/local/bin/superglue-gateway uninstall"}});var bd=m(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.OAUTH_CONFIG_CREDENTIAL_KEYS=void 0;de.hasMeaningfulValue=At;de.stringValue=Pt;de.validateOAuthConnection=Ude;de.formatOAuthConnectionDisabledReason=xde;de.objectValue=Ro;de.parseScopes=Id;de.normalizeGrantType=Cd;de.normalizeOAuthClientMode=ub;de.normalizeSystemAuthentication=Gt;de.resolveOAuthClientMode=Pde;de.flattenSystemAuthentication=_M;de.maskedFlatSystemAuthentication=Fde;de.isMaskedSecretValue=DM;de.pickAgentAuthInputFields=$de;de.maskSystemAuthenticationForResponse=jde;de.restoreMaskedClientSecret=qde;de.mapAgentAuthInput=TM;de.mergeAgentAuthInput=eAe;de.getAuthenticationConfigCredentialKeys=RM;de.buildAuthenticationEditorModel=tAe;de.getCredentialRequirements=rAe;de.isCredentialRequirementSatisfied=kM;de.hasUnsatisfiedCredentialRequirements=nAe;de.updateAuthenticationEditorField=iAe;de.validateOAuthAuthenticationConfigPlacement=NM;de.authenticationToLegacyCredentials=OM;de.isRuntimeCredentialMetadataKey=oAe;de.resolveCredentialAuthentication=sAe;de.getCredentialAuthenticationStorageError=aAe;de.buildRuntimeCredentialsFromAuthentication=cAe;de.resolveOAuthConfigFromAuthentication=uAe;de.toCredentialInputValue=lb;de.getCredentialEntries=lAe;de.getCredentialInputValues=dAe;de.getCredentialDisplayHiddenKeys=AAe;de.hasOAuthTokenCredentials=pAe;de.getOAuthExpiryText=fAe;de.hasRuntimeCredentialValues=hAe;de.validateCredentialObjectKeys=UM;de.validateCredentialKeyList=MM;de.normalizeAskForUserInputs=xM;de.validateSystemInputCollection=gAe;de.mapOAuthMissingFieldsForAgent=mAe;de.validateOAuthAuthenticationAndCredentialInputs=yAe;var It=ln(),Bde=Lc();de.OAUTH_CONFIG_CREDENTIAL_KEYS=["auth_url","authUrl","token_url","tokenUrl","token_uri","scopes","scope","grant_type","grantType","oauthClientMode","client_id","clientId","client_secret","clientSecret","tokenAuthMethod","tokenContentType","usePKCE","extraHeaders","extraBodyParams"];var Gh=["host","port","database","path","homeDirectory"],vM=["type","oauthClientMode","grantType","authUrl","tokenUrl","scopes","clientId","clientSecret","tokenAuthMethod","tokenContentType","usePKCE","extraHeaders","extraBodyParams","protocol",...Gh],Qde=new Set(vM),vde="type, oauthClientMode, grantType, authUrl, tokenUrl, scopes, clientId, clientSecret, tokenAuthMethod, tokenContentType, usePKCE, extraHeaders, extraBodyParams, protocol, host, port, database, path, homeDirectory",_de=["grantType","authUrl","tokenUrl","scopes","clientId","clientSecret"],Dde={grantType:["grantType","grant_type"],authUrl:["authUrl","auth_url"],tokenUrl:["tokenUrl","token_url","token_uri"],scopes:["scopes","scope"],clientId:["clientId","client_id"],clientSecret:["clientSecret","client_secret"]},Ed=["tokenAuthMethod","tokenContentType","usePKCE","extraHeaders","extraBodyParams"],Tde=new Set(_de),Rde=new Set(["access_token","accessToken","refresh_token","refreshToken","expires_at","expiresAt","expires_in","expiresIn","expiry","token_type","tokenType"]),kde=["access_token","refresh_token","api_key","bearer_token","token","client_id","client_secret","auth_url","token_url","scopes","grant_type","token_type","expires_at","expiry","expires_in","host","hostname","port","database","dbname","db","username","password"],wM=new Map(kde.map((t,e)=>[(0,It.normalizeCredentialKey)(t),e]));function Ca(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0))}function ab({config:t,key:e,value:r}){let n={...t||{}};return At(r)?n[e]=r:delete n[e],Object.keys(n).length>0?n:void 0}function At(t){return(0,It.hasCredentialValue)(t)}function Pt(t){if(At(t))return typeof t=="string"?t:String(t)}var Nde={"grant_type authorization_code or client_credentials":"authorization_code or client_credentials",client_id:"client ID",token_url:"token URL",auth_url:"authorization URL","client_secret or usePKCE":"client secret or PKCE","client_secret or oauth_cert + oauth_key":"client secret or OAuth certificate and key"};function To(...t){return t.find(e=>At(e))}function Ode(t){return t===!0||t==="true"}function Ude(t){let e=t||{},r=Pt(To(e.grant_type,e.grantType)),n=r==="client_credentials"?"client_credentials":"authorization_code",i=r&&r!=="authorization_code"&&r!=="client_credentials",o=To(e.client_id,e.clientId),s=To(e.client_secret,e.clientSecret),a=To(e.auth_url,e.authUrl),c=To(e.token_url,e.tokenUrl,e.token_uri),u=To(e.oauth_cert,e.oauthCert),l=To(e.oauth_key,e.oauthKey),d=At(u)&&At(l)||e.hasServerSideCertificateCredentials===!0,A=e.hasServerSideClientSecret===!0,p=At(s)||A,h=Ode(To(e.usePKCE,e.usePkce)),g=[];return i&&g.push("grant_type authorization_code or client_credentials"),At(o)||g.push("client_id"),At(c)||g.push("token_url"),n==="client_credentials"?!p&&!d&&g.push("client_secret or oauth_cert + oauth_key"):(At(a)||g.push("auth_url"),!p&&!h&&g.push("client_secret or usePKCE")),{grantType:n,hasAccessToken:At(To(e.access_token,e.accessToken)),hasCertificateCredentials:d,isReadyToConnect:g.length===0,missingFields:g,usePKCE:h}}function Mde(t){return t.length<=1?t[0]||"":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}function xde(t){if(!t||t.isReadyToConnect)return null;let e=t.missingFields.map(r=>Nde[r]||r);return`OAuth connection is disabled because ${Mde(e)} ${e.length===1?"is":"are"} missing.`}function Ro(t){if(!(!t||typeof t!="object"||Array.isArray(t)))return t}function Ki(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Id(t){if(At(t)){if(Array.isArray(t))return t.map(String).filter(Boolean);if(typeof t=="string"){let e=t.trim().split(/[,\s]+/).map(r=>r.trim()).filter(Boolean);return e.length>0?e:void 0}return[String(t)]}}function Cd(t){let e=Pt(t);if(e==="authorization_code"||e==="client_credentials"||e==="password"||e==="service_account"||e==="custom")return e;if(e)return"custom"}function ub(t){return t==="managed"||t==="dynamic"||t==="custom"?t:void 0}function Lde(t){let e=Object.entries(t).filter(([r])=>!Tde.has(r));return e.length>0?Object.fromEntries(e):void 0}function Wc(t,e,r){for(let i of Dde[r])if(At(t[i]))return t[i];let n=Ro(t.client);return r==="clientId"&&At(n?.id)?n.id:r==="clientSecret"&&At(n?.secret)?n.secret:e[r]}function Gt(t){if(!t)return;let e=t;if(e.type==="oauth2"){let r=Ro(e.config)||{},n=Lde(r)||{};return Ca({type:"oauth2",oauthClientMode:ub(e.oauthClientMode),grantType:Cd(Wc(e,r,"grantType")),authUrl:Pt(Wc(e,r,"authUrl")),tokenUrl:Pt(Wc(e,r,"tokenUrl")),scopes:Id(Wc(e,r,"scopes")),clientId:Pt(Wc(e,r,"clientId")),clientSecret:Pt(Wc(e,r,"clientSecret")),config:Object.keys(n).length>0?n:void 0})}return e.type==="connection_string"?Ca({type:"connection_string",protocol:e.protocol,config:Ro(e.config??e.components)}):e.type==="api_key"||e.type==="basic_auth"||e.type==="none"?Ca({type:e.type,config:Ro(e.config)}):{type:"none"}}function Pde({authentication:t,templateManaged:e,templateRegistrationUrl:r}){let n=Gt(t);if(n?.type!=="oauth2")return"custom";let i=n.oauthClientMode;return i?i==="managed"&&!e?"custom":i:r?"dynamic":e&&!n.clientSecret?"managed":"custom"}function _M(t){let e=Gt(t);if(!e)return;let{config:r,scopes:n,...i}=e,o={};return r&&typeof r=="object"&&Object.assign(o,r),Object.assign(o,i),Array.isArray(n)?o.scopes=n.join(" "):n!==void 0&&(o.scopes=n),o}function cb(t,e=""){return t==null?t:Array.isArray(t)?t.map(r=>cb(r)):typeof t=="object"?Object.fromEntries(Object.entries(t).map(([r,n])=>[r,cb(n,r)])):e&&(0,It.isSensitiveCredentialKey)(e)?(0,It.maskCredentialValue)(e,t):t}function Fde(t){let e=_M(t);if(e)return cb(e)}function DM(t){return(0,It.isMaskedValue)(t)||(0,It.isFullyMaskedCredentialValue)(t)}function $de(t){let e=Ro(t);if(!e)return;let r={};for(let n of vM){if(!Ki(e,n))continue;let i=e[n];i!==void 0&&(r[n]=i)}return r}function jde(t){return!t||t.type!=="oauth2"||!At(t.clientSecret)?t:{...t,clientSecret:It.FULLY_MASKED_CREDENTIAL_VALUE}}function qde({incoming:t,existing:e}){if(!t||t.type!=="oauth2"||!DM(t.clientSecret))return t;let r=e?.type==="oauth2"?e.clientSecret:void 0;return{...t,clientSecret:r}}function zde(t){if(t==="none"||t==="api_key"||t==="basic_auth"||t==="oauth2"||t==="connection_string")return t}function Hde(t){return Object.entries(t||{})}function Gde(t){let e=Gh.flatMap(r=>{if(!Ki(t,r))return[];let n=t[r];return At(n)?[[r,n]]:[]});return e.length>0?Object.fromEntries(e):void 0}function Yde(t){return Gh.filter(e=>Ki(t,e))}function Vde(t){let e=Gh.flatMap(r=>Ki(t,r)?[[r,t[r]]]:[]);return e.length>0?Object.fromEntries(e):void 0}function Jde(t){let e=new Set(["oauthClientMode","grantType","authUrl","tokenUrl","scopes","clientId","clientSecret",...Ed]);return Object.keys(t).filter(r=>e.has(r))}function TM(t){if(t==null)return{};let e=Ro(t);if(!e)return{error:"auth must be an object."};let r=zde(e.type);if(!r)return{error:"auth.type is required."};let n=Object.keys(e).filter(a=>!Qde.has(a));if(n.length>0)return{error:`Unknown auth field(s): ${n.join(", ")}. Accepted: ${vde}.`};let i=Yde(e);if(r!=="connection_string"&&i.length>0)return{error:`Connection auth field(s) require auth.type 'connection_string': ${i.join(", ")}.`};let o=Jde(e);if(r!=="oauth2"&&o.length>0)return{error:`OAuth auth field(s) require auth.type 'oauth2': ${o.join(", ")}.`};if(r!=="oauth2"){let a=Gde(e);return{authentication:Ca({type:r,protocol:r==="connection_string"?e.protocol:void 0,config:a})}}let s={...Object.fromEntries(Ed.flatMap(a=>{if(!Ki(e,a))return[];let c=e[a];return At(c)?[[a,c]]:[]}))};return{authentication:Ca({type:"oauth2",oauthClientMode:ub(e.oauthClientMode),grantType:Cd(e.grantType),authUrl:Pt(e.authUrl),tokenUrl:Pt(e.tokenUrl),scopes:Id(e.scopes),clientId:Pt(e.clientId),clientSecret:Pt(e.clientSecret),config:Object.keys(s).length>0?s:void 0})}}function ba(t){return t===""||t===null||t===void 0}function yd(t,e,r,n){if(Ki(e,r)){if(ba(e[r])){delete t[n];return}t[n]=Pt(e[r])}}function Wde(t,e){if(Ki(e,"scopes")){if(ba(e.scopes)){delete t.scopes;return}t.scopes=Id(e.scopes)}}function Zde(t,e){if(Ki(e,"grantType")){if(ba(e.grantType)){delete t.grantType;return}t.grantType=Cd(e.grantType)}}function Kde(t,e,r){if(Ki(e,r)){if(ba(e[r])){delete t[r];return}t[r]=e[r]}}function Xde(t,e){if(ba(e))return;let r=Ro(e);if(!r)return t;let n={...t||{}};for(let[i,o]of Object.entries(r))ba(o)?delete n[i]:n[i]=o;return Object.keys(n).length>0?n:void 0}function eAe(t,e){let r=TM(e);if(r.error)return Gt(t)||{type:"none"};let n=r.authentication||{type:"none"},i=Ro(e)||{},o=Gt(t),s=o?.type===n.type;if(n.type!=="oauth2"){let d=Vde(i),A=s&&o?{...o}:{type:n.type};return n.type==="connection_string"&&Ki(i,"protocol")&&(ba(i.protocol)?delete A.protocol:A.protocol=i.protocol),d&&(A.config=Xde(o?.config,d)),Gt(A)||{type:n.type}}let c={...s&&o?.type==="oauth2"?{...o,config:{...o.config||{}}}:{type:"oauth2",config:{}}};yd(c,i,"oauthClientMode","oauthClientMode"),Zde(c,i),yd(c,i,"authUrl","authUrl"),yd(c,i,"tokenUrl","tokenUrl"),Wde(c,i),yd(c,i,"clientId","clientId"),yd(c,i,"clientSecret","clientSecret");let l={...c.config||{}};for(let d of Ed)Kde(l,i,d);return c.config=Object.keys(l).length>0?l:void 0,Gt(c)||{type:"oauth2"}}function RM(t){let e=Gt(t);if(!e)return[];let r=new Set;for(let n of Object.keys(e.config||{}))r.add(n);return e.type==="oauth2"&&(e.grantType&&(r.add("grant_type"),r.add("grantType")),e.authUrl&&(r.add("auth_url"),r.add("authUrl")),e.tokenUrl&&(r.add("token_url"),r.add("tokenUrl"),r.add("token_uri")),e.scopes&&(r.add("scopes"),r.add("scope")),e.clientId&&(r.add("client_id"),r.add("clientId")),e.clientSecret&&(r.add("client_secret"),r.add("clientSecret"))),[...r]}function BM(t,e,r){if(r)for(let[n,i]of Object.entries(r))t.push({path:`${e}.${n}`,label:n,value:i})}function tAe({authentication:t}){let e=Gt(t)||{type:"none"},r=[];if(e.type==="oauth2"){r.push({path:"oauth2.clientId",label:"clientId",value:e.clientId},{path:"oauth2.clientSecret",label:"clientSecret",value:e.clientSecret},{path:"oauth2.grantType",label:"grantType",value:e.grantType||"authorization_code"},{path:"oauth2.authUrl",label:"authUrl",value:e.authUrl},{path:"oauth2.tokenUrl",label:"tokenUrl",value:e.tokenUrl},{path:"oauth2.scopes",label:"scopes",value:e.scopes?.join(" ")});for(let n of Ed)r.push({path:`oauth2.config.${n}`,label:n,value:e.config?.[n]});for(let[n,i]of Object.entries(e.config||{}))Ed.includes(n)||r.push({path:`oauth2.config.${n}`,label:n,value:i})}else e.type==="connection_string"?(e.protocol&&r.push({path:"connection.protocol",label:"protocol",value:e.protocol}),BM(r,"connection.config",e.config)):BM(r,`${e.type}.config`,e.config);return{type:e.type,authentication:e,configFields:r,hiddenCredentialKeys:RM(e)}}function rAe(t){let e=Gt(t);if(!e||e.type!=="connection_string")return[];let r={type:"field",field:{key:"username",aliases:["user"]}},n={type:"field",field:{key:"password"}};switch(e.protocol){case"sftp":return[r,{type:"oneOf",fields:[{key:"password"},{key:"privateKey"}]},{type:"field",field:{key:"passphrase"},optional:!0}];case"smb":return[r,n,{type:"field",field:{key:"domain"},optional:!0}];case"sqlserver":return[{type:"field",field:{key:"user",aliases:["username"]}},n];default:return[r,n]}}function QM(t,e){return(0,It.hasCredentialValue)(e[t.key])?!0:(t.aliases??[]).some(r=>(0,It.hasCredentialValue)(e[r]))}function kM(t,e){return t.optional?!0:t.type==="field"?QM(t.field,e):t.fields.some(r=>QM(r,e))}function nAe(t,e){let r=e||{};return t.some(n=>!kM(n,r))}function iAe({authentication:t,path:e,value:r}){let n=Gt(t)||{type:"none"};if(n.type==="oauth2"){if(e==="oauth2.grantType")return{...n,grantType:Cd(r)};if(e==="oauth2.authUrl")return{...n,authUrl:Pt(r)};if(e==="oauth2.tokenUrl")return{...n,tokenUrl:Pt(r)};if(e==="oauth2.scopes")return{...n,scopes:Id(r)};if(e==="oauth2.clientId")return{...n,clientId:Pt(r)};if(e==="oauth2.clientSecret")return{...n,clientSecret:Pt(r)};if(e.startsWith("oauth2.config.")){let o=e.slice(14);return{...n,config:ab({config:n.config,key:o,value:r})}}}if(n.type==="connection_string"){if(e==="connection.protocol")return{...n,protocol:Pt(r)};if(e.startsWith("connection.config.")){let o=e.slice(18);return{...n,config:ab({config:n.config,key:o,value:r})}}}let i=`${n.type}.config.`;if(e.startsWith(i)){let o=e.slice(i.length);return{...n,config:ab({config:n.config,key:o,value:r})}}return n}function NM({authentication:t,credentials:e}){if(Gt(t)?.type!=="oauth2"||!e||typeof e!="object"||Array.isArray(e))return null;let n=Object.keys(e).filter(i=>de.OAUTH_CONFIG_CREDENTIAL_KEYS.includes(i));return n.length===0?null:`OAuth configuration keys belong in auth, not credentials: ${n.join(", ")}. Move OAuth client ID to auth.clientId, client secret to auth.clientSecret, auth URL to auth.authUrl, token URL to auth.tokenUrl, scopes to auth.scopes, grant type to auth.grantType, and token request settings to auth fields such as tokenAuthMethod/usePKCE/extraHeaders. Runtime OAuth access and refresh tokens are created by authenticate_oauth.`}function OM(t){let e=Gt(t);return e?e.type==="oauth2"?Ca({...e.config||{},grant_type:e.grantType,auth_url:e.authUrl,token_url:e.tokenUrl,scopes:e.scopes?.join(" "),client_id:e.clientId,client_secret:e.clientSecret}):e.type==="connection_string"?e.config||{}:e.config||{}:{}}function oAe(t){return Rde.has(t.trim())}function sAe({credential:t,system:e}){return t?.authentication??e?.authentication??void 0}function aAe(t){let e=Gt(t);return e?.type==="oauth2"&&e.oauthClientMode==="managed"&&e.clientSecret?"Managed OAuth client secrets cannot be stored on credentials":null}function cAe({authentication:t,credentials:e}){let r=OM(t);return Gt(t)?.type==="oauth2"?{...e||{},...r}:{...r,...e||{}}}function uAe({input:t,authentication:e,templateOAuth:r}){let n=Gt(e),i=n?.type==="oauth2"?n:void 0,o=i?.config||{},s=t||{},a=(...c)=>c.find(u=>u!=null);return Ca({grant_type:a(s.grantType,s.grant_type,i?.grantType,r?.grant_type)||"authorization_code",scopes:a(s.scopes,i?.scopes?.join(" "),r?.scopes),client_id:a(s.clientId,s.client_id,i?.clientId),client_secret:a(s.clientSecret,s.client_secret,i?.clientSecret),auth_url:a(s.authUrl,s.auth_url,i?.authUrl,r?.authUrl),token_url:a(s.tokenUrl,s.token_url,i?.tokenUrl,r?.tokenUrl),resource:a(s.resource,o.resource,r?.resource),tokenAuthMethod:a(s.tokenAuthMethod,o.tokenAuthMethod,r?.tokenAuthMethod),tokenContentType:a(s.tokenContentType,o.tokenContentType,r?.tokenContentType),usePKCE:a(s.usePKCE,o.usePKCE,r?.usePKCE),extraHeaders:a(s.extraHeaders,o.extraHeaders,r?.extraHeaders),extraBodyParams:a(s.extraBodyParams,o.extraBodyParams,r?.extraBodyParams)})}function lb(t){if(t==null)return"";if(typeof t=="string")return t;let e=JSON.stringify(t);return e===void 0?String(t):e}function lAe(t,e={}){let r=new Set((e.hiddenKeys||[]).map(It.normalizeCredentialKey));return Object.entries(t).filter(([n])=>!r.has((0,It.normalizeCredentialKey)(n))).sort(([n],[i])=>{let o=wM.get((0,It.normalizeCredentialKey)(n))??Number.MAX_SAFE_INTEGER,s=wM.get((0,It.normalizeCredentialKey)(i))??Number.MAX_SAFE_INTEGER;if(o!==s)return o-s;let a=(0,It.isSensitiveCredentialKey)(n),c=(0,It.isSensitiveCredentialKey)(i);return a!==c?a?-1:1:n.localeCompare(i)}).map(([n,i])=>({key:n,value:lb(i),isReservedMasked:e.maskAll||(0,It.isSensitiveCredentialKey)(n)}))}function dAe(t){return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,lb(r)]))}function AAe({hideOAuthFiles:t=!1,configKeys:e=[]}){return[...e,...t?["oauth_cert","oauth_key"]:[]]}function pAe(t){return At(t.access_token)||At(t.refresh_token)}function fAe(t){let e=t.expires_at??t.expiry;if(e){let n=(0,Bde.parseUTCDate)(e);if(n)return`Expires ${n.toLocaleString()}`}let r=t.expires_in;return At(r)?`Expires in ${r} seconds`:null}function hAe(t){return!!(t&&typeof t=="object"&&!Array.isArray(t)&&Object.values(t).some(e=>At(e)))}function UM(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=(0,It.getInvalidCredentialKeyNames)(Object.keys(t));return e.length===0?null:`${It.CREDENTIAL_KEY_VALIDATION_DESCRIPTION} Invalid keys: ${e.join(", ")}`}function MM(t){let e=(0,It.getInvalidCredentialKeyNames)(t);return e.length===0?null:`${It.CREDENTIAL_KEY_VALIDATION_DESCRIPTION} Invalid keys: ${e.join(", ")}`}function xM(t){return Array.isArray(t)?[...new Set(t.map(e=>String(e||"").trim()).filter(Boolean))]:[]}function gAe({credentials:t,askForUserInputs:e}){let r=UM(t);if(r)return r;let n=xM(e),i=MM(n);if(i)return i;if(t&&typeof t=="object"&&!Array.isArray(t))for(let[o,s]of Hde(t)){if(s===""||s===null)return"Blank secret values are not allowed; list secret names to collect from the user in askForUserInputs.";if(n.includes(o))return`Secret name '${o}' cannot be in both credentials and askForUserInputs.`}return null}function mAe(t){let e={"grant_type authorization_code or client_credentials":"grantType authorization_code or client_credentials",client_id:"clientId",token_url:"tokenUrl",auth_url:"authUrl","client_secret or usePKCE":"clientSecret or usePKCE","client_secret or oauth_cert + oauth_key":"clientSecret or oauth_cert + oauth_key"};return t.map(r=>e[r]||r)}function yAe({authentication:t,credentials:e}){return NM({authentication:t,credentials:e})}});var nx=m(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.bundles=void 0;Fn.buildBundleAgentLaunch=RAe;Fn.getBundle=kAe;Fn.listBundles=NAe;Fn.rewriteBundleToolSystemId=OAe;var EAe=dr(),IAe="https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap",CAe="<<(p) => { const value = p['sage_intacct_entity_id']; if (!value) return ''; const escaped = String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('\"', '&quot;').replaceAll(\"'\", '&apos;'); return `<locationid>${escaped}</locationid>`; }>>",LM="<<() => crypto.randomUUID()>>";function pt(t){return`<?xml version="1.0" encoding="UTF-8"?><request><control><senderid><<sage_intacct_sender_id>></senderid><password><<sage_intacct_sender_password>></password><controlid>${LM}</controlid><uniqueid>false</uniqueid><dtdversion>3.0</dtdversion></control><operation><authentication><login><userid><<sage_intacct_user_id>></userid><companyid><<sage_intacct_company_id>></companyid><password><<sage_intacct_user_password>></password>${CAe}</login></authentication><content><function controlid="${LM}">${t}</function></content></operation></request>`}function fs({stepId:t,objectNameExpression:e,collectionName:r,mapExpression:n,includeTotalCount:i=!1}){let o=i?"Number(data && data.TOTALCOUNT ? data.TOTALCOUNT : rows.length)":"rows.length",s=n?`rows.map(${n})`:"rows";return`(sourceData) => { const response = sourceData.${t} && sourceData.${t}.data ? sourceData.${t}.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? \` Sage support ID: \${supportIds.join(', ')}.\` : ''; throw new Error(\`Sage Intacct request failed\${details.length ? \`: \${details.join('; ')}\` : '.'}\${suffix}\`); } const data = result ? result.DATA : undefined; const objectName = ${e}; const raw = data ? data[objectName] : undefined; const rows = (Array.isArray(raw) ? raw : (raw ? [raw] : [])).slice(0, (sourceData && sourceData.maxResults) ?? ${i?"1000":"200"}); return { total: ${o}, ${r}: ${s} }; }`}var hs=`const esc = (value) => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;');`,PM="const toIntacctDate = (value) => { const match = String(value).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); if (!match) throw new Error('Dates must be in YYYY-MM-DD format.'); return match[2] + '/' + match[3] + '/' + match[1]; };",FM="const assertBalanced = (lines) => { const balance = lines.reduce((sum, line) => sum + (line.type === 'credit' ? -1 : 1) * Math.abs(Number(line.amount)), 0); if (Math.abs(balance) > 0.005) throw new Error('Journal lines must balance: debits minus credits is ' + balance.toFixed(2) + '.'); };",$M=`const lineXml = (line) => { const amount = Number(line.amount); if (!Number.isFinite(amount) || amount <= 0) throw new Error('Every journal line needs a positive amount.'); const type = line.type === 'credit' ? -1 : line.type === 'debit' ? 1 : null; if (type === null) throw new Error("Every journal line needs type 'debit' or 'credit'."); if (!line.accountNo) throw new Error('Every journal line needs accountNo.'); let xml = '<GLENTRY><ACCOUNTNO>' + esc(line.accountNo) + '</ACCOUNTNO><TR_TYPE>' + type + '</TR_TYPE><TRX_AMOUNT>' + amount + '</TRX_AMOUNT>'; if (line.department) xml += '<DEPARTMENT>' + esc(line.department) + '</DEPARTMENT>'; if (line.location) xml += '<LOCATION>' + esc(line.location) + '</LOCATION>'; if (line.memo) xml += '<DESCRIPTION>' + esc(line.memo) + '</DESCRIPTION>'; return xml + '</GLENTRY>'; };`;function Zc({stepId:t,objectName:e}){return`(sourceData) => { const response = sourceData.${t} && sourceData.${t}.data ? sourceData.${t}.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? \` Sage support ID: \${supportIds.join(', ')}.\` : ''; throw new Error(\`Sage Intacct request failed\${details.length ? \`: \${details.join('; ')}\` : '.'}\${suffix}\`); } const data = result ? result.DATA : undefined; const raw = data ? (data.${e} || data.${e.toLowerCase()}) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: record && record.RECORDNO ? Number(record.RECORDNO) : undefined, record }; }`}var Qd="netsuite",pb=100,Bd=1e4,Xh=String.raw`<<(p) => { const url = String(p['netsuite_url'] || ''); if (!url || url.includes('{accountId}')) throw new Error('NetSuite is not connected yet: set the account ID so the system URL is https://<account>.suitetalk.api.netsuite.com/services/rest'); return url.replace(/\/+$/, ''); }>>`,eg={Authorization:"Bearer <<netsuite_access_token>>",Accept:"application/json"},fb=String.raw`const has = (value) => value !== undefined && value !== null && value !== ''; const nsId = (value, name) => { const text = String(value ?? '').trim(); if (!/^-?\d+$/.test(text)) throw new Error(name + ' must be a NetSuite internal ID.'); return text; }; const nsDate = (value, name) => { const text = String(value ?? '').trim(); if (!/^\d{4}-\d{2}-\d{2}$/.test(text)) throw new Error(name + ' must be a date in YYYY-MM-DD format.'); return text; }; const ref = (value, name) => ({ id: nsId(value, name) });`,bAe=String.raw`const str = (value) => (value === undefined || value === null || value === '' ? null : String(value)); const num = (value) => (value === undefined || value === null || value === '' ? null : Number(value)); const bool = (value) => value === 'T' || value === true; const ids = (value) => (value === undefined || value === null || value === '' ? [] : String(value).split(',').map((part) => part.trim()).filter(Boolean)); const status = (value) => (value ? String(value).replace(/^[^:]*:\s*/, '') : null);`,jM=String.raw`const stripLinks = (value) => { if (Array.isArray(value)) return value.map(stripLinks); if (value && typeof value === 'object') { const result = {}; for (const [key, entry] of Object.entries(value)) { if (key !== 'links') result[key] = stripLinks(entry); } return result; } return value; };`,SAe={type:"integer",minimum:1,maximum:Bd,description:`Maximum number of records to return (max ${Bd}). Defaults to ${pb}. The result always reports the full match count in total, so use maxResults 1 to count. Prefer filters over large values: big results can exceed an AI client's tool output limit.`},wAe={type:"boolean",description:"Only return active records. Defaults to false (inactive records are included)."},BAe={type:"string",description:"Optional subsidiary internal ID to filter by."},QAe={type:"string",description:"Optional earliest transaction date as YYYY-MM-DD."},vAe={type:"string",description:"Optional latest transaction date as YYYY-MM-DD."},_Ae={type:"object",description:"Optional extra NetSuite REST field values merged into the record body as-is, e.g. custom fields like { custentity_region: 'EMEA' } or references like { terms: { id: '2' } }. Fields that this tool's own inputs set are rejected; use those inputs instead.",properties:{},additionalProperties:!0},Sd=t=>({input:"activeOnly",kind:"flag",clause:`${t}.isinactive = 'F'`,schema:wAe}),wd=t=>({input:"subsidiaryId",kind:"id",clause:`${t}.subsidiary = $`,schema:BAe}),db=[{input:"fromDate",kind:"date",clause:"t.trandate >= TO_DATE('$', 'YYYY-MM-DD')",schema:QAe},{input:"toDate",kind:"date",clause:"t.trandate <= TO_DATE('$', 'YYYY-MM-DD')",schema:vAe}];function DAe(t){let e=`p[${JSON.stringify(t.input)}]`;if(t.kind==="flag")return`if (${e} === true || ${e} === 'true') where.push(${JSON.stringify(t.clause)});`;let[r,n]=t.clause.split("$");if(t.kind==="enum")return`if (has(${e})) { const allowed = ${JSON.stringify(t.values)}; if (!allowed.includes(String(${e}))) throw new Error(${JSON.stringify(`${t.input} must be one of: ${t.values.join(", ")}.`)}); where.push(${JSON.stringify(r)} + String(${e}) + ${JSON.stringify(n)}); }`;if(t.kind==="prefix")return`if (has(${e})) { const text = String(${e}).trim(); if (!/^[A-Za-z0-9._-]{1,40}$/.test(text)) throw new Error(${JSON.stringify(`${t.input} may only contain letters, digits, dots, underscores and hyphens.`)}); where.push(${JSON.stringify(r)} + text + ${JSON.stringify(n)}); }`;let i=t.kind==="id"?"nsId":"nsDate";return`if (has(${e})) where.push(${JSON.stringify(r)} + ${i}(${e}, ${JSON.stringify(t.input)}) + ${JSON.stringify(n)});`}function gs({id:t,name:e,shortName:r,instruction:n,stepId:i,collection:o,select:s,baseWhere:a=[],orderBy:c,filters:u=[],properties:l={},required:d=[],mapRow:A}){let p=typeof s=="string"?JSON.stringify(s):s.js,h=`<<(p) => { ${fb} const where = ${JSON.stringify(a)}; ${u.map(DAe).join(" ")} return JSON.stringify({ q: ${p} + (where.length ? ' WHERE ' + where.join(' AND ') : '') + ${JSON.stringify(` ORDER BY ${c}`)} }); }>>`;return{id:t,name:e,shortName:r,instruction:`${n} Rows are ordered by internal ID. If more than ${Bd} rows match, narrow with the filters or page with the SuiteQL query tool (ORDER BY id, WHERE id > last id).`,inputSchema:{type:"object",properties:{...l,maxResults:SAe,...Object.fromEntries(u.map(g=>[g.input,g.schema]))},...d.length>0?{required:d}:{},additionalProperties:!1},steps:[{id:i,instruction:"Run the SuiteQL query page by page.",config:{type:"request",systemId:Qd,url:`${Xh}/query/v1/suiteql`,method:"POST",headers:{...eg,"Content-Type":"application/json",Prefer:"transient"},queryParams:{limit:"1000",offset:"<<offset>>"},body:h,pagination:{type:"offsetBased",pageSize:"1000",stopCondition:`(response, pageInfo, sourceData) => { if (sourceData && ["offset", "limit", "page"].some((key) => sourceData[key] !== undefined)) throw new Error("offset, limit and page are not inputs of this tool: use maxResults and the filters."); const page = response && response.data ? response.data : {}; const merged = pageInfo && pageInfo.mergedResult && Array.isArray(pageInfo.mergedResult.items) ? pageInfo.mergedResult.items.length : 0; const max = Math.min(Math.max(Math.floor(Number(sourceData && sourceData.maxResults)) || ${pb}, 1), ${Bd}); return page.hasMore !== true || merged >= max; }`}}}],outputTransform:`(sourceData) => { ${bAe} const raw = sourceData.${i} ? sourceData.${i}.data : undefined; const pages = Array.isArray(raw) ? raw : (raw ? [raw] : []); const items = pages.flatMap((page) => (page && Array.isArray(page.items) ? page.items : [])); const last = pages.length ? pages[pages.length - 1] : {}; const max = Math.min(Math.max(Math.floor(Number(sourceData.maxResults)) || ${pb}, 1), ${Bd}); const rows = items.slice(0, max).map(${A}).map((row) => Object.fromEntries(Object.entries(row).filter((entry) => entry[1] !== null))); const total = last && last.totalResults !== undefined ? Number(last.totalResults) : items.length; return { total, returned: rows.length, hasMore: total > rows.length, ${o}: rows }; }`}}function mr({id:t,name:e,shortName:r,instruction:n,stepId:i,recordType:o,mode:s,properties:a,required:c,body:u,replaceSublist:l}){let d=[...new Set(Array.from(u.matchAll(/record\.([A-Za-z0-9_]+)\s*=/g)).map(p=>p[1]))],A=s==="create"?`/record/v1/${o}`:`/record/v1/${o}/<<(p) => { ${fb} return nsId(p.internalId, 'internalId'); }>>`;return{id:t,name:e,shortName:r,instruction:n,inputSchema:{type:"object",properties:{...s==="update"?{internalId:{type:"string",description:`Internal ID of the ${o} to update.`}}:{},...a,fields:_Ae},required:s==="update"?["internalId",...c]:c,additionalProperties:!1},steps:[{id:i,instruction:`${s==="create"?"Create":"Update"} the ${o} record.`,modify:!0,config:{type:"request",systemId:Qd,url:`${Xh}${A}`,method:s==="create"?"POST":"PATCH",headers:{...eg,"Content-Type":"application/json","X-NetSuite-idempotency-key":"<<() => crypto.randomUUID()>>"},...l?{queryParams:{replace:`<<(p) => (Array.isArray(p[${JSON.stringify(l.input)}]) && p[${JSON.stringify(l.input)}].length > 0 ? ${JSON.stringify(l.sublist)} : undefined)>>`}}:{},body:`<<(p) => { ${fb} const record = {}; ${u} if (p.fields && typeof p.fields === 'object' && !Array.isArray(p.fields)) { const managed = ${JSON.stringify(d)}; const reserved = Object.keys(p.fields).filter((key) => managed.includes(key)); if (reserved.length > 0) throw new Error('fields may not set ' + reserved.join(', ') + ': use this tool\\'s own inputs for them.'); Object.assign(record, p.fields); } if (Object.keys(record).length === 0) throw new Error('Provide at least one field to ${s}.'); return JSON.stringify(record); }>>`,captureHttpResponse:!0}}],outputTransform:s==="create"?`(sourceData) => { const step = sourceData.${i} || {}; const location = step.http && step.http.headers ? String(step.http.headers.location || '') : ''; const match = location.match(/\\/record\\/v1\\/[^/]+\\/([^/?#]+)/); if (!match) throw new Error('NetSuite did not return the location of the new ${o}.'); return { id: decodeURIComponent(match[1]), recordType: '${o}' }; }`:`(sourceData) => ({ id: String(sourceData.internalId).trim(), recordType: '${o}', updated: true })`}}var qM=String.raw`const lines = Array.isArray(p.lines) ? p.lines : []; let balance = 0; const items = lines.map((line, index) => { const amount = Number(line && line.amount); if (!Number.isFinite(amount) || amount <= 0) throw new Error('lines[' + index + '].amount must be a positive number.'); if (line.type !== 'debit' && line.type !== 'credit') throw new Error("lines[" + index + "].type must be 'debit' or 'credit'."); balance += line.type === 'debit' ? amount : -amount; const item = { account: ref(line.accountId, 'lines[' + index + '].accountId') }; item[line.type] = amount; if (has(line.memo)) item.memo = String(line.memo); if (has(line.departmentId)) item.department = ref(line.departmentId, 'lines[' + index + '].departmentId'); if (has(line.classId)) item.class = ref(line.classId, 'lines[' + index + '].classId'); if (has(line.locationId)) item.location = ref(line.locationId, 'lines[' + index + '].locationId'); if (has(line.entityId)) item.entity = ref(line.entityId, 'lines[' + index + '].entityId'); return item; }); if (lines.length > 0 && Math.abs(balance) > 0.005) throw new Error('Journal lines must balance: debits minus credits is ' + balance.toFixed(2) + '.'); if (items.length > 0) record.line = { items };`,zM=String.raw`if (has(p.subsidiaryId)) record.subsidiary = ref(p.subsidiaryId, 'subsidiaryId'); if (has(p.date)) record.tranDate = nsDate(p.date, 'date'); if (has(p.memo)) record.memo = String(p.memo); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.externalId)) record.externalId = String(p.externalId);`,HM={type:"object",properties:{accountId:{type:"string",description:"GL account internal ID."},type:{type:"string",enum:["debit","credit"]},amount:{type:"number",description:"Positive amount."},memo:{type:"string",description:"Optional line memo."},departmentId:{type:"string",description:"Optional department internal ID."},classId:{type:"string",description:"Optional class internal ID."},locationId:{type:"string",description:"Optional location internal ID."},entityId:{type:"string",description:"Optional customer, vendor or employee internal ID for the line."}},required:["accountId","type","amount"],additionalProperties:!1},GM=t=>({subsidiaryId:{type:"string",description:t==="create"?"Subsidiary internal ID. Required in OneWorld accounts.":"Optional new subsidiary internal ID."},date:{type:"string",description:t==="create"?"Transaction date as YYYY-MM-DD.":"Optional new transaction date as YYYY-MM-DD."},memo:{type:"string",description:"Journal entry memo."},currencyId:{type:"string",description:"Optional currency internal ID."},externalId:{type:"string",description:"Optional external ID."}}),Yh=String.raw`if (p.isPerson === true || p.isPerson === 'true') record.isPerson = true; if (p.isPerson === false || p.isPerson === 'false') record.isPerson = false; if (has(p.entityId)) record.entityId = String(p.entityId); if (has(p.companyName)) record.companyName = String(p.companyName); if (has(p.firstName)) record.firstName = String(p.firstName); if (has(p.lastName)) record.lastName = String(p.lastName); if (has(p.subsidiaryId)) record.subsidiary = ref(p.subsidiaryId, 'subsidiaryId'); if (has(p.email)) record.email = String(p.email); if (has(p.phone)) record.phone = String(p.phone); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.externalId)) record.externalId = String(p.externalId); if (p.isInactive === true || p.isInactive === 'true') record.isInactive = true; if (p.isInactive === false || p.isInactive === 'false') record.isInactive = false;`;function Vh(t){return{companyName:{type:"string",description:`Company name of the ${t}.`},isPerson:{type:"boolean",description:`True when the ${t} is an individual; then set firstName and lastName.`},firstName:{type:"string",description:"First name for an individual."},lastName:{type:"string",description:"Last name for an individual."},entityId:{type:"string",description:`${t==="customer"?"Customer":"Vendor"} ID. Omit when auto-numbering assigns it.`},subsidiaryId:{type:"string",description:"Primary subsidiary internal ID. Required on create in OneWorld accounts."},email:{type:"string",description:"Email address."},phone:{type:"string",description:"Phone number."},currencyId:{type:"string",description:"Primary currency internal ID."},externalId:{type:"string",description:"Optional external ID."}}}var Jh={isInactive:{type:"boolean",description:"Set true to inactivate, false to reactivate."}},Wh=String.raw`if (Array.isArray(p.subsidiaryIds) && p.subsidiaryIds.length > 0) record.subsidiary = { items: p.subsidiaryIds.map((value, index) => ref(value, 'subsidiaryIds[' + index + ']')) }; if (p.includeChildren === true || p.includeChildren === 'true') record.includeChildren = true; if (p.includeChildren === false || p.includeChildren === 'false') record.includeChildren = false;`,tx={subsidiaryIds:{type:"array",items:{type:"string"},description:"Subsidiary internal IDs the record is available in. On update the list replaces the current subsidiaries."},includeChildren:{type:"boolean",description:"Also make the record available to child subsidiaries."}},hb=["AcctPay","AcctRec","Bank","COGS","CredCard","DeferExpense","DeferRevenue","Equity","Expense","FixedAsset","Income","LongTermLiab","NonPosting","OthAsset","OthCurrAsset","OthCurrLiab","OthExpense","OthIncome","Stat","UnbilledRec"],YM=String.raw`if (has(p.acctNumber)) record.acctNumber = String(p.acctNumber); if (has(p.acctName)) record.acctName = String(p.acctName); if (has(p.acctType)) record.acctType = { id: String(p.acctType) }; if (has(p.parentId)) record.parent = ref(p.parentId, 'parentId'); if (has(p.description)) record.description = String(p.description); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.externalId)) record.externalId = String(p.externalId); if (p.isInactive === true || p.isInactive === 'true') record.isInactive = true; if (p.isInactive === false || p.isInactive === 'false') record.isInactive = false;`,VM={acctNumber:{type:"string",description:"Account number."},acctName:{type:"string",description:"Account name."},acctType:{type:"string",enum:hb,description:"NetSuite account type."},parentId:{type:"string",description:"Optional parent account internal ID."},description:{type:"string",description:"Optional description."},currencyId:{type:"string",description:"Optional currency internal ID (bank and credit card accounts)."},externalId:{type:"string",description:"Optional external ID."},...tx},JM=String.raw`if (has(p.name)) record.name = String(p.name); if (has(p.parentId)) record.parent = ref(p.parentId, 'parentId'); if (has(p.externalId)) record.externalId = String(p.externalId); if (p.isInactive === true || p.isInactive === 'true') record.isInactive = true; if (p.isInactive === false || p.isInactive === 'false') record.isInactive = false;`,WM={name:{type:"string",description:"Department name."},parentId:{type:"string",description:"Optional parent department internal ID."},externalId:{type:"string",description:"Optional external ID."},...tx},Zh=t=>String.raw`if (has(p.${t})) record.entity = ref(p.${t}, '${t}'); if (has(p.subsidiaryId)) record.subsidiary = ref(p.subsidiaryId, 'subsidiaryId'); if (has(p.date)) record.tranDate = nsDate(p.date, 'date'); if (has(p.dueDate)) record.dueDate = nsDate(p.dueDate, 'dueDate'); if (has(p.memo)) record.memo = String(p.memo); if (has(p.currencyId)) record.currency = ref(p.currencyId, 'currencyId'); if (has(p.termsId)) record.terms = ref(p.termsId, 'termsId'); if (has(p.departmentId)) record.department = ref(p.departmentId, 'departmentId'); if (has(p.classId)) record.class = ref(p.classId, 'classId'); if (has(p.locationId)) record.location = ref(p.locationId, 'locationId'); if (has(p.externalId)) record.externalId = String(p.externalId);`,Kh=t=>({subsidiaryId:{type:"string",description:t==="create"?"Optional subsidiary internal ID; defaults to the entity's subsidiary.":"Optional new subsidiary internal ID."},date:{type:"string",description:t==="create"?"Transaction date as YYYY-MM-DD.":"Optional new transaction date as YYYY-MM-DD."},dueDate:{type:"string",description:"Optional due date as YYYY-MM-DD."},memo:{type:"string",description:"Optional memo."},currencyId:{type:"string",description:"Optional currency internal ID."},termsId:{type:"string",description:"Optional payment terms internal ID."},departmentId:{type:"string",description:"Optional header department internal ID."},classId:{type:"string",description:"Optional header class internal ID."},locationId:{type:"string",description:"Optional header location internal ID."},externalId:{type:"string",description:"Optional external ID."}}),rx=String.raw`if (has(line.departmentId)) item.department = ref(line.departmentId, 'lines[' + index + '].departmentId'); if (has(line.classId)) item.class = ref(line.classId, 'lines[' + index + '].classId'); if (has(line.locationId)) item.location = ref(line.locationId, 'lines[' + index + '].locationId');`,ZM=String.raw`if (Array.isArray(p.lines) && p.lines.length > 0) record.item = { items: p.lines.map((line, index) => { const item = { item: ref(line && line.itemId, 'lines[' + index + '].itemId') }; if (has(line.quantity)) { const quantity = Number(line.quantity); if (!Number.isFinite(quantity)) throw new Error('lines[' + index + '].quantity must be a number.'); item.quantity = quantity; } if (has(line.rate)) { const rate = Number(line.rate); if (!Number.isFinite(rate)) throw new Error('lines[' + index + '].rate must be a number.'); item.rate = rate; } if (has(line.amount)) { const amount = Number(line.amount); if (!Number.isFinite(amount)) throw new Error('lines[' + index + '].amount must be a number.'); item.amount = amount; } if (has(line.description)) item.description = String(line.description); if (has(line.taxCodeId)) item.taxCode = ref(line.taxCodeId, 'lines[' + index + '].taxCodeId'); ${rx} return item; }) };`,KM={type:"object",properties:{itemId:{type:"string",description:"Item internal ID."},quantity:{type:"number",description:"Optional quantity. Defaults to 1."},rate:{type:"number",description:"Optional unit price; defaults to the item price."},amount:{type:"number",description:"Optional line amount."},description:{type:"string",description:"Optional line description."},taxCodeId:{type:"string",description:"Optional tax code internal ID."},departmentId:{type:"string",description:"Optional department internal ID."},classId:{type:"string",description:"Optional class internal ID. Some accounts ignore line classes on invoices; check the saved record."},locationId:{type:"string",description:"Optional location internal ID."}},required:["itemId"],additionalProperties:!1},XM=String.raw`if (Array.isArray(p.lines) && p.lines.length > 0) record.expense = { items: p.lines.map((line, index) => { const amount = Number(line && line.amount); if (!Number.isFinite(amount) || amount <= 0) throw new Error('lines[' + index + '].amount must be a positive number.'); const item = { account: ref(line.accountId, 'lines[' + index + '].accountId'), amount }; if (has(line.memo)) item.memo = String(line.memo); ${rx} return item; }) };`,ex={type:"object",properties:{accountId:{type:"string",description:"Expense account internal ID."},amount:{type:"number",description:"Positive amount."},memo:{type:"string",description:"Optional line memo."},departmentId:{type:"string",description:"Optional department internal ID."},classId:{type:"string",description:"Optional class internal ID."},locationId:{type:"string",description:"Optional location internal ID."}},required:["accountId","amount"],additionalProperties:!1},Sa="Re-running this tool creates another record; it is not idempotent.",TAe=[gs({id:"netsuite-list-accounts",name:"List NetSuite chart of accounts",shortName:"Chart of accounts",instruction:"Lists general ledger accounts (the chart of accounts) from NetSuite with number, name, type, parent and subsidiaries. Useful for validating an imported chart of accounts.",stepId:"queryAccounts",collection:"accounts",select:"SELECT a.id, a.acctnumber, a.accountsearchdisplaynamecopy AS name, a.fullname, a.accttype, a.parent, a.subsidiary, cur.symbol AS currency, a.description, a.issummary, a.isinactive FROM account a LEFT JOIN currency cur ON cur.id = a.currency",orderBy:"a.id",filters:[Sd("a"),{input:"accountType",kind:"enum",values:hb,clause:"a.accttype = '$'",schema:{type:"string",enum:hb,description:"Only accounts of this NetSuite account type, e.g. Bank or Expense."}},{input:"numberPrefix",kind:"prefix",clause:"a.acctnumber LIKE '$%'",schema:{type:"string",description:"Only accounts whose number starts with this value, e.g. 1000 or 60."}}],mapRow:"(row) => ({ id: row.id, number: str(row.acctnumber), name: str(row.name), fullName: str(row.fullname), type: str(row.accttype), parentId: str(row.parent), subsidiaryIds: ids(row.subsidiary), currency: str(row.currency), description: str(row.description), isSummary: bool(row.issummary), isInactive: bool(row.isinactive) })"}),gs({id:"netsuite-list-customers",name:"List NetSuite customers",shortName:"Customers",instruction:"Lists customer records from NetSuite with subsidiary, currency and open balance. Useful for verifying migrated AR master data.",stepId:"queryCustomers",collection:"customers",select:"SELECT c.id, c.entityid, c.companyname, c.isperson, c.firstname, c.lastname, c.email, c.phone, c.subsidiary, BUILTIN.DF(c.subsidiary) AS subsidiaryname, cur.symbol AS currency, c.balancesearch, c.overduebalancesearch, c.isinactive, TO_CHAR(c.datecreated, 'YYYY-MM-DD') AS datecreated, TO_CHAR(c.lastmodifieddate, 'YYYY-MM-DD') AS lastmodified FROM customer c LEFT JOIN currency cur ON cur.id = c.currency",orderBy:"c.id",filters:[Sd("c"),wd("c")],mapRow:"(row) => ({ id: row.id, entityId: str(row.entityid), companyName: str(row.companyname), isPerson: bool(row.isperson), firstName: str(row.firstname), lastName: str(row.lastname), email: str(row.email), phone: str(row.phone), subsidiaryId: str(row.subsidiary), subsidiary: str(row.subsidiaryname), currency: str(row.currency), balance: num(row.balancesearch), overdueBalance: num(row.overduebalancesearch), isInactive: bool(row.isinactive), createdOn: str(row.datecreated), modifiedOn: str(row.lastmodified) })"}),gs({id:"netsuite-list-vendors",name:"List NetSuite vendors",shortName:"Vendors",instruction:"Lists vendor records from NetSuite with subsidiary, currency and balance. Useful for verifying migrated AP master data.",stepId:"queryVendors",collection:"vendors",select:"SELECT v.id, v.entityid, v.companyname, v.isperson, v.firstname, v.lastname, v.email, v.phone, v.subsidiary, BUILTIN.DF(v.subsidiary) AS subsidiaryname, cur.symbol AS currency, v.balance, v.isinactive, TO_CHAR(v.datecreated, 'YYYY-MM-DD') AS datecreated, TO_CHAR(v.lastmodifieddate, 'YYYY-MM-DD') AS lastmodified FROM vendor v LEFT JOIN currency cur ON cur.id = v.currency",orderBy:"v.id",filters:[Sd("v"),wd("v")],mapRow:"(row) => ({ id: row.id, entityId: str(row.entityid), companyName: str(row.companyname), isPerson: bool(row.isperson), firstName: str(row.firstname), lastName: str(row.lastname), email: str(row.email), phone: str(row.phone), subsidiaryId: str(row.subsidiary), subsidiary: str(row.subsidiaryname), currency: str(row.currency), balance: num(row.balance), isInactive: bool(row.isinactive), createdOn: str(row.datecreated), modifiedOn: str(row.lastmodified) })"}),gs({id:"netsuite-list-journal-entries",name:"List NetSuite journal entries",shortName:"Journal entries",instruction:"Lists journal entry lines from NetSuite, one row per GL line and accounting book with journal, date, period, account, debit, credit and dimensions. Useful for verifying opening balances and postings at cutover.",stepId:"queryJournalLines",collection:"journalLines",select:"SELECT t.id AS journalid, t.tranid, TO_CHAR(t.trandate, 'YYYY-MM-DD') AS trandate, BUILTIN.DF(t.postingperiod) AS period, t.subsidiary, BUILTIN.DF(t.status) AS status, t.posting, t.memo AS journalmemo, cur.symbol AS currency, tl.id AS lineid, tal.accountingbook, tal.account, a.acctnumber, a.accountsearchdisplaynamecopy AS accountname, tal.debit, tal.credit, tl.memo, tl.department, tl.class, tl.location, tl.entity FROM transaction t JOIN transactionline tl ON tl.transaction = t.id JOIN transactionaccountingline tal ON tal.transaction = tl.transaction AND tal.transactionline = tl.id JOIN account a ON a.id = tal.account LEFT JOIN currency cur ON cur.id = t.currency",baseWhere:["t.type = 'Journal'"],orderBy:"t.id, tl.id, tal.accountingbook",filters:[...db,wd("t")],mapRow:"(row) => ({ journalId: row.journalid, tranId: str(row.tranid), date: str(row.trandate), period: str(row.period), subsidiaryId: str(row.subsidiary), status: status(row.status), posting: bool(row.posting), journalMemo: str(row.journalmemo), currency: str(row.currency), line: num(row.lineid), accountingBookId: str(row.accountingbook), accountId: str(row.account), accountNumber: str(row.acctnumber), accountName: str(row.accountname), debit: num(row.debit), credit: num(row.credit), memo: str(row.memo), departmentId: str(row.department), classId: str(row.class), locationId: str(row.location), entityId: str(row.entity) })"}),gs({id:"netsuite-list-invoices",name:"List NetSuite invoices",shortName:"Invoices",instruction:"Lists customer invoices from NetSuite with customer, dates, status, total and amount due. Useful for verifying migrated open AR at go-live.",stepId:"queryInvoices",collection:"invoices",select:"SELECT t.id, t.tranid, t.entity, BUILTIN.DF(t.entity) AS customername, TO_CHAR(t.trandate, 'YYYY-MM-DD') AS trandate, TO_CHAR(t.duedate, 'YYYY-MM-DD') AS duedate, BUILTIN.DF(t.status) AS status, cur.symbol AS currency, t.foreigntotal, t.foreignamountunpaid, t.subsidiary, t.memo FROM transaction t LEFT JOIN currency cur ON cur.id = t.currency",baseWhere:["t.type = 'CustInvc'"],orderBy:"t.id",filters:[...db,wd("t"),{input:"openOnly",kind:"flag",clause:"t.status = 'A'",schema:{type:"boolean",description:"Only return open (unpaid) invoices."}}],mapRow:"(row) => ({ id: row.id, tranId: str(row.tranid), customerId: str(row.entity), customer: str(row.customername), date: str(row.trandate), dueDate: str(row.duedate), status: status(row.status), currency: str(row.currency), total: num(row.foreigntotal), amountDue: num(row.foreignamountunpaid), subsidiaryId: str(row.subsidiary), memo: str(row.memo) })"}),gs({id:"netsuite-list-vendor-bills",name:"List NetSuite vendor bills",shortName:"Vendor bills",instruction:"Lists vendor bills from NetSuite with vendor, dates, status, approval status, total and amount due. Useful for verifying migrated open AP at go-live.",stepId:"queryBills",collection:"bills",select:"SELECT t.id, t.tranid, t.entity, BUILTIN.DF(t.entity) AS vendorname, TO_CHAR(t.trandate, 'YYYY-MM-DD') AS trandate, TO_CHAR(t.duedate, 'YYYY-MM-DD') AS duedate, BUILTIN.DF(t.status) AS status, BUILTIN.DF(t.approvalstatus) AS approvalstatus, cur.symbol AS currency, t.foreigntotal, t.foreignamountunpaid, t.subsidiary, t.memo FROM transaction t LEFT JOIN currency cur ON cur.id = t.currency",baseWhere:["t.type = 'VendBill'"],orderBy:"t.id",filters:[...db,wd("t"),{input:"openOnly",kind:"flag",clause:"t.status = 'A'",schema:{type:"boolean",description:"Only return open bills (approved and not fully paid)."}}],mapRow:"(row) => ({ id: row.id, referenceNo: str(row.tranid), vendorId: str(row.entity), vendor: str(row.vendorname), date: str(row.trandate), dueDate: str(row.duedate), status: status(row.status), approvalStatus: str(row.approvalstatus), currency: str(row.currency), total: row.foreigntotal === undefined ? null : Math.abs(Number(row.foreigntotal)), amountDue: num(row.foreignamountunpaid), subsidiaryId: str(row.subsidiary), memo: str(row.memo) })"}),gs({id:"netsuite-list-dimensions",name:"List NetSuite departments, classes or locations",shortName:"Departments, classes, locations",instruction:"Lists department, class or location records from NetSuite with hierarchy and subsidiaries. Useful for validating the dimension setup after an implementation and for finding the internal IDs the write tools need.",stepId:"queryDimensions",collection:"records",properties:{dimension:{type:"string",enum:["department","class","location"],description:"Which dimension to list."}},required:["dimension"],select:{js:String.raw`'SELECT d.id, d.name, d.fullname, d.parent, d.subsidiary, d.includechildren, d.isinactive FROM ' + (() => { const table = { department: 'department', class: 'classification', location: 'location' }[String(p.dimension || '')]; if (!table) throw new Error("dimension must be 'department', 'class' or 'location'."); return table; })() + ' d'`},orderBy:"d.id",filters:[Sd("d")],mapRow:"(row) => ({ id: row.id, name: str(row.name), fullName: str(row.fullname), parentId: str(row.parent), subsidiaryIds: ids(row.subsidiary), includeChildren: bool(row.includechildren), isInactive: bool(row.isinactive) })"}),gs({id:"netsuite-list-subsidiaries",name:"List NetSuite subsidiaries",shortName:"Subsidiaries",instruction:"Lists subsidiaries from NetSuite with hierarchy, country, base currency and elimination flag. Most create tools need a subsidiary ID from this list in OneWorld accounts.",stepId:"querySubsidiaries",collection:"subsidiaries",select:"SELECT s.id, s.name, s.fullname, s.parent, s.country, cur.symbol AS currency, s.iselimination, s.isinactive FROM subsidiary s LEFT JOIN currency cur ON cur.id = s.currency",orderBy:"s.id",filters:[Sd("s")],mapRow:"(row) => ({ id: row.id, name: str(row.name), fullName: str(row.fullname), parentId: str(row.parent), country: str(row.country), currency: str(row.currency), isElimination: bool(row.iselimination), isInactive: bool(row.isinactive) })"}),{id:"netsuite-suiteql-query",name:"Run a NetSuite SuiteQL query",shortName:"SuiteQL query",instruction:"Runs a read-only SuiteQL SELECT query against NetSuite, for any record type, join or aggregate outside the prebuilt lists (for example items, employees, transaction lines or custom records). The workhorse tool for migration validation. Returns up to 1000 rows in one call with the total row count and hasMore; values are strings as NetSuite returns them.",inputSchema:{type:"object",properties:{query:{type:"string",description:`SuiteQL SELECT statement, e.g. "SELECT id, itemid, displayname FROM item WHERE isinactive = 'F' ORDER BY id". Dates come back in the user's date format; use TO_CHAR(field, 'YYYY-MM-DD') for ISO dates and BUILTIN.DF(field) for display names. For more than 1000 rows, page by key: ORDER BY id and add WHERE id > <last id>. Common columns: account (id, acctnumber, accountsearchdisplaynamecopy as the name, fullname, accttype, isinactive; there is no acctname column), customer (id, entityid, companyname, email, subsidiary, balancesearch, isinactive), vendor (id, entityid, companyname, email, subsidiary, balance, isinactive), transaction (id, tranid, type, trandate, entity, status, foreigntotal, foreignamountunpaid, subsidiary). Alias tables and qualify columns: FROM transaction t ... t.subsidiary works, an unqualified subsidiary fails.`},maxResults:{type:"integer",minimum:1,maximum:1e3,description:"Maximum number of rows to return (max 1000). Defaults to 100."}},required:["query"],additionalProperties:!1},steps:[{id:"runSuiteQl",instruction:"Run the SuiteQL query.",config:{type:"request",systemId:Qd,url:`${Xh}/query/v1/suiteql`,method:"POST",headers:{...eg,"Content-Type":"application/json",Prefer:"transient"},queryParams:{limit:"<<(p) => Math.min(Math.max(Math.floor(Number(p.maxResults)) || 100, 2), 1000)>>",offset:"0"},body:String.raw`<<(p) => { const query = String(p.query || '').trim(); if (!/^(select|with)\b/i.test(query)) throw new Error('query must be a SuiteQL SELECT statement.'); return JSON.stringify({ q: query }); }>>`}}],outputTransform:`(sourceData) => { ${jM} const data = sourceData.runSuiteQl && sourceData.runSuiteQl.data ? sourceData.runSuiteQl.data : {}; const items = Array.isArray(data.items) ? data.items : []; const max = Math.min(Math.max(Math.floor(Number(sourceData.maxResults)) || 100, 1), 1000); const records = stripLinks(items.slice(0, max)); const total = data.totalResults !== undefined ? Number(data.totalResults) : items.length; return { total, returned: records.length, hasMore: total > records.length, records }; }`},{id:"netsuite-get-record",name:"Get a NetSuite record",shortName:"Get record",instruction:"Fetches one NetSuite record of any type by internal ID or external ID through the REST record API, including its sublists such as transaction lines. Useful for inspecting a record in full before or after a write.",inputSchema:{type:"object",properties:{recordType:{type:"string",description:'REST record type, e.g. "customer", "vendor", "invoice", "vendorbill", "journalentry", "account", "department" or a custom record like "customrecord_x".'},internalId:{type:"string",description:"Internal ID of the record."},externalId:{type:"string",description:"External ID of the record, used when internalId is not set."},expandSubResources:{type:"boolean",description:"Include sublists and subrecords inline. Defaults to true."}},required:["recordType"],additionalProperties:!1},steps:[{id:"getRecord",instruction:"Fetch the record from the REST record API.",config:{type:"request",systemId:Qd,url:`${Xh}/record/v1/<<(p) => { const type = String(p.recordType || '').trim().toLowerCase(); if (!/^[a-z][a-z0-9_]*$/.test(type)) throw new Error('recordType must contain only letters, numbers and underscores.'); return type; }>>/<<(p) => { if (p.internalId !== undefined && p.internalId !== null && p.internalId !== '') { const id = String(p.internalId).trim(); if (!/^-?\\d+$/.test(id)) throw new Error('internalId must be a NetSuite internal ID.'); return id; } if (p.externalId !== undefined && p.externalId !== null && p.externalId !== '') return 'eid:' + encodeURIComponent(String(p.externalId)); throw new Error('Provide internalId or externalId.'); }>>`,method:"GET",headers:eg,queryParams:{expandSubResources:"<<(p) => (p.expandSubResources === false || p.expandSubResources === 'false' ? 'false' : 'true')>>"}}}],outputTransform:`(sourceData) => { ${jM} const record = sourceData.getRecord ? sourceData.getRecord.data : undefined; if (!record || typeof record !== 'object') throw new Error('NetSuite returned no record.'); return { record: stripLinks(record) }; }`},mr({id:"netsuite-create-journal-entry",name:"Create NetSuite journal entry",shortName:"Create journal entry",instruction:`Creates a journal entry in NetSuite through the REST record API. Debit and credit lines must balance. Returns the new internal ID. ${Sa}`,stepId:"createJournalEntry",recordType:"journalentry",mode:"create",properties:{...GM("create"),lines:{type:"array",description:"Journal lines. Debit and credit totals must balance.",items:HM}},required:["date","lines"],body:`${zM} if (!Array.isArray(p.lines) || p.lines.length < 2) throw new Error('lines must contain at least two journal lines.'); ${qM}`}),mr({id:"netsuite-update-journal-entry",name:"Update NetSuite journal entry",shortName:"Update journal entry",instruction:"Updates an existing NetSuite journal entry by internal ID. Only the provided fields change. When lines are provided they replace all existing lines and must balance. Entries in closed periods refuse updates.",stepId:"updateJournalEntry",recordType:"journalentry",mode:"update",properties:{...GM("update"),lines:{type:"array",description:"Optional replacement lines. When set, they replace every existing line and must balance.",items:HM}},required:[],body:`${zM} if (Array.isArray(p.lines) && p.lines.length < 2) throw new Error('lines must contain at least two journal lines; omit lines to keep the current ones.'); ${qM}`,replaceSublist:{input:"lines",sublist:"line"}}),mr({id:"netsuite-create-vendor",name:"Create NetSuite vendor",shortName:"Create vendor",instruction:`Creates a vendor record in NetSuite. OneWorld accounts need a subsidiaryId. Omit entityId when auto-numbering assigns it. ${Sa}`,stepId:"createVendor",recordType:"vendor",mode:"create",properties:Vh("vendor"),required:[],body:`if (!has(p.companyName) && !((p.isPerson === true || p.isPerson === 'true') && has(p.lastName))) throw new Error('Provide companyName, or isPerson with lastName.'); ${Yh}`}),mr({id:"netsuite-update-vendor",name:"Update NetSuite vendor",shortName:"Update vendor",instruction:"Updates an existing NetSuite vendor by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it.",stepId:"updateVendor",recordType:"vendor",mode:"update",properties:{...Vh("vendor"),...Jh},required:[],body:Yh}),mr({id:"netsuite-create-customer",name:"Create NetSuite customer",shortName:"Create customer",instruction:`Creates a customer record in NetSuite. OneWorld accounts need a subsidiaryId. Omit entityId when auto-numbering assigns it. ${Sa}`,stepId:"createCustomer",recordType:"customer",mode:"create",properties:Vh("customer"),required:[],body:`if (!has(p.companyName) && !((p.isPerson === true || p.isPerson === 'true') && has(p.lastName))) throw new Error('Provide companyName, or isPerson with lastName.'); ${Yh}`}),mr({id:"netsuite-update-customer",name:"Update NetSuite customer",shortName:"Update customer",instruction:"Updates an existing NetSuite customer by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it.",stepId:"updateCustomer",recordType:"customer",mode:"update",properties:{...Vh("customer"),...Jh},required:[],body:Yh}),mr({id:"netsuite-create-account",name:"Create NetSuite GL account",shortName:"Create GL account",instruction:`Creates a general ledger account in NetSuite's chart of accounts. ${Sa}`,stepId:"createAccount",recordType:"account",mode:"create",properties:VM,required:["acctName","acctType"],body:`if (!has(p.acctName) || !has(p.acctType)) throw new Error('acctName and acctType are required.'); ${YM} ${Wh}`}),mr({id:"netsuite-update-account",name:"Update NetSuite GL account",shortName:"Update GL account",instruction:"Updates an existing NetSuite GL account by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it. Accounts with transactions may refuse a type change.",stepId:"updateAccount",recordType:"account",mode:"update",properties:{...VM,...Jh},required:[],body:`${YM} ${Wh}`}),mr({id:"netsuite-create-invoice",name:"Create NetSuite invoice",shortName:"Create invoice",instruction:`Creates a customer invoice in NetSuite with item lines. Item, tax and posting rules of the account apply. ${Sa}`,stepId:"createInvoice",recordType:"invoice",mode:"create",properties:{customerId:{type:"string",description:"Customer internal ID."},...Kh("create"),lines:{type:"array",description:"Item lines.",items:KM}},required:["customerId","lines"],body:`if (!Array.isArray(p.lines) || p.lines.length === 0) throw new Error('lines must contain at least one item line.'); ${Zh("customerId")} ${ZM}`}),mr({id:"netsuite-update-invoice",name:"Update NetSuite invoice",shortName:"Update invoice",instruction:"Updates an existing NetSuite invoice by internal ID. Only the provided fields change. When lines are provided they replace all existing item lines. Paid invoices and closed periods may refuse updates.",stepId:"updateInvoice",recordType:"invoice",mode:"update",properties:{customerId:{type:"string",description:"Optional new customer internal ID."},...Kh("update"),lines:{type:"array",description:"Optional replacement item lines; they replace every existing item line.",items:KM}},required:[],body:`if (Array.isArray(p.lines) && p.lines.length === 0) throw new Error('lines must contain at least one item line; omit lines to keep the current ones.'); ${Zh("customerId")} ${ZM}`,replaceSublist:{input:"lines",sublist:"item"}}),mr({id:"netsuite-create-vendor-bill",name:"Create NetSuite vendor bill",shortName:"Create vendor bill",instruction:`Creates a vendor bill in NetSuite with expense lines. Approval routing of the account applies. ${Sa}`,stepId:"createVendorBill",recordType:"vendorbill",mode:"create",properties:{vendorId:{type:"string",description:"Vendor internal ID."},referenceNo:{type:"string",description:"Optional vendor invoice reference number."},...Kh("create"),lines:{type:"array",description:"Expense lines.",items:ex}},required:["vendorId","lines"],body:`if (!Array.isArray(p.lines) || p.lines.length === 0) throw new Error('lines must contain at least one expense line.'); ${Zh("vendorId")} if (has(p.referenceNo)) record.tranId = String(p.referenceNo); ${XM}`}),mr({id:"netsuite-update-vendor-bill",name:"Update NetSuite vendor bill",shortName:"Update vendor bill",instruction:"Updates an existing NetSuite vendor bill by internal ID. Only the provided fields change. When lines are provided they replace all existing expense lines. Paid bills and closed periods may refuse updates.",stepId:"updateVendorBill",recordType:"vendorbill",mode:"update",properties:{vendorId:{type:"string",description:"Optional new vendor internal ID."},referenceNo:{type:"string",description:"Optional vendor invoice reference number."},...Kh("update"),lines:{type:"array",description:"Optional replacement expense lines; they replace every existing expense line.",items:ex}},required:[],body:`if (Array.isArray(p.lines) && p.lines.length === 0) throw new Error('lines must contain at least one expense line; omit lines to keep the current ones.'); ${Zh("vendorId")} if (has(p.referenceNo)) record.tranId = String(p.referenceNo); ${XM}`,replaceSublist:{input:"lines",sublist:"expense"}}),mr({id:"netsuite-create-department",name:"Create NetSuite department",shortName:"Create department",instruction:`Creates a department in NetSuite. Without subsidiaryIds NetSuite assigns the parent subsidiary. ${Sa}`,stepId:"createDepartment",recordType:"department",mode:"create",properties:WM,required:["name"],body:`if (!has(p.name)) throw new Error('name is required.'); ${JM} ${Wh}`}),mr({id:"netsuite-update-department",name:"Update NetSuite department",shortName:"Update department",instruction:"Updates an existing NetSuite department by internal ID. Only the provided fields change; set isInactive to inactivate or reactivate it.",stepId:"updateDepartment",recordType:"department",mode:"update",properties:{...WM,...Jh},required:[],body:`${JM} ${Wh}`})],Ab={sap_s4hana:{bundleId:"sap_s4hana",templateId:"sap_s4hana",systemId:"sap_s4hana",displayName:"SAP S/4HANA",description:"Read business partners, sales orders, products and purchase orders from SAP.",systemUrl:IAe,credentialHint:"Works instantly with SAP's demo data. Add your own key later for your live system.",requiredCredentialKeys:["api_key"],demoCredentials:{api_key:"K8reTgiKCCaqvAPWC4cOjqqiLdLE8dqz"},mcpServer:{name:"sap",displayName:"SAP S/4HANA",description:"Business partners, sales orders, products and purchase orders from SAP."},installMcpServer:!0,agentLaunch:{userPrompt:"I just installed the SAP S/4HANA bundle. What can I do with it?",nextSteps:"Your first reply must be short: SAP is connected to free demo data and works right now, so offer to run one tool immediately as proof. No credential collection is needed to start. If they want their own data: their own free key comes from https://api.sap.com (SAP Business Accelerator Hub), collected with set_credentials, never as chat text and never via the Credentials page; the system URL can then be switched to their own SAP host. Do not list the installed tools, do not add tips or explain SAP concepts unless asked."},tools:[{id:"sap-list-business-partners",name:"List SAP business partners",shortName:"Business partners",instruction:"Lists business partners (customers, suppliers, contacts) from SAP S/4HANA. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "BusinessPartnerCategory eq '2'" for organizations.`},maxResults:{type:"integer",description:"Maximum number of business partners to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchBusinessPartners",instruction:"Fetch business partners, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_BUSINESS_PARTNER/A_BusinessPartner",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"BusinessPartner,BusinessPartnerFullName,BusinessPartnerCategory,BusinessPartnerGrouping,CreationDate"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchBusinessPartners?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, businessPartners: rows.map((r) => ({ id: r.BusinessPartner, name: r.BusinessPartnerFullName, category: r.BusinessPartnerCategory, grouping: r.BusinessPartnerGrouping, createdOn: d(r.CreationDate) })) }; }"},{id:"sap-list-sales-orders",name:"List SAP sales orders",shortName:"Sales orders",instruction:"Lists sales orders from SAP S/4HANA with their net amount, currency and sold-to party. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "SalesOrderType eq 'OR'" or "TotalNetAmount gt 1000".`},maxResults:{type:"integer",description:"Maximum number of sales orders to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchSalesOrders",instruction:"Fetch sales orders, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_SALES_ORDER_SRV/A_SalesOrder",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"SalesOrder,SalesOrderType,SoldToParty,TotalNetAmount,TransactionCurrency,SalesOrderDate,OverallSDProcessStatus"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchSalesOrders?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, salesOrders: rows.map((r) => ({ id: r.SalesOrder, type: r.SalesOrderType, soldToParty: r.SoldToParty, netAmount: Number(r.TotalNetAmount), currency: r.TransactionCurrency, orderDate: d(r.SalesOrderDate), status: r.OverallSDProcessStatus })) }; }"},{id:"sap-list-products",name:"List SAP products",shortName:"Products",instruction:"Lists products (materials) from SAP S/4HANA with their type, group and base unit. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "ProductType eq 'FERT'" for finished goods.`},maxResults:{type:"integer",description:"Maximum number of products to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchProducts",instruction:"Fetch products, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_PRODUCT_SRV/A_Product",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$expand:"to_Description",$select:"Product,ProductType,ProductGroup,BaseUnit,GrossWeight,WeightUnit,CreationDate,to_Description/Language,to_Description/ProductDescription"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const nameOf = (r) => { const list = r.to_Description?.results ?? []; const hit = list.find((x) => x.Language === 'EN') ?? list[0]; return hit?.ProductDescription; }; const rows = (sourceData.fetchProducts?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, products: rows.map((r) => ({ id: r.Product, name: nameOf(r), type: r.ProductType, group: r.ProductGroup, baseUnit: r.BaseUnit, grossWeight: Number(r.GrossWeight), weightUnit: r.WeightUnit, createdOn: d(r.CreationDate) })) }; }"},{id:"sap-list-purchase-orders",name:"List SAP purchase orders",shortName:"Purchase orders",instruction:"Lists purchase orders from SAP S/4HANA with their supplier, currency and creation date. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "PurchaseOrderType eq 'NB'" for standard orders.`},maxResults:{type:"integer",description:"Maximum number of purchase orders to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchPurchaseOrders",instruction:"Fetch purchase orders, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_PURCHASEORDER_PROCESS_SRV/A_PurchaseOrder",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"PurchaseOrder,PurchaseOrderType,Supplier,PurchaseOrderDate,DocumentCurrency,CreatedByUser"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchPurchaseOrders?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, purchaseOrders: rows.map((r) => ({ id: r.PurchaseOrder, type: r.PurchaseOrderType, supplier: r.Supplier, orderDate: d(r.PurchaseOrderDate), currency: r.DocumentCurrency, createdBy: r.CreatedByUser })) }; }"},{id:"sap-list-gl-accounts",name:"List SAP chart of accounts",shortName:"Chart of accounts",instruction:"Lists general ledger accounts (the chart of accounts) from SAP S/4HANA. Supports an optional OData $filter, e.g. by ChartOfAccounts.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "ChartOfAccounts eq 'YCOA'" or "GLAccountType eq 'X'".`},maxResults:{type:"integer",description:"Maximum number of accounts to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchGLAccounts",instruction:"Fetch GL accounts, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_GLACCOUNTINCHARTOFACCOUNTS_SRV/A_GLAccountInChartOfAccounts",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:`<<(p) => p.filter ? "ChartOfAccounts ne '' and (" + p.filter + ")" : "ChartOfAccounts ne ''">>`,$expand:"to_Text",$select:"GLAccount,ChartOfAccounts,GLAccountType,GLAccountGroup,IsBalanceSheetAccount,AccountIsBlockedForPosting,to_Text/Language,to_Text/GLAccountName"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const nameOf = (r) => { const list = r.to_Text?.results ?? []; const hit = list.find((x) => x.Language === 'EN') ?? list[0]; return hit?.GLAccountName; }; const rows = (sourceData.fetchGLAccounts?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, accounts: rows.map((r) => ({ account: r.GLAccount, name: nameOf(r), chartOfAccounts: r.ChartOfAccounts, type: r.GLAccountType, group: r.GLAccountGroup, isBalanceSheet: r.IsBalanceSheetAccount, blockedForPosting: r.AccountIsBlockedForPosting })) }; }"},{id:"sap-list-billing-documents",name:"List SAP billing documents",shortName:"Billing documents",instruction:"Lists billing documents (invoices, credit memos) from SAP S/4HANA with amount, currency and sold-to party. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "BillingDocumentType eq 'F2'" or "TotalNetAmount gt 1000".`},maxResults:{type:"integer",description:"Maximum number of billing documents to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchBillingDocuments",instruction:"Fetch billing documents, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_BILLING_DOCUMENT_SRV/A_BillingDocument",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"BillingDocument,BillingDocumentType,SoldToParty,TotalNetAmount,TransactionCurrency,BillingDocumentDate"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchBillingDocuments?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, billingDocuments: rows.map((r) => ({ id: r.BillingDocument, type: r.BillingDocumentType, soldToParty: r.SoldToParty, netAmount: Number(r.TotalNetAmount), currency: r.TransactionCurrency, date: d(r.BillingDocumentDate) })) }; }"},{id:"sap-list-journal-entry-items",name:"List SAP journal entry line items",shortName:"Journal entries",instruction:"Lists journal entry line items (accounting document items) from SAP S/4HANA with company code, GL account, amount and posting date. Filter by CompanyCode, FiscalYear or PostingDate to keep results focused. Useful for verifying opening balances at cutover.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "CompanyCode eq '1010' and FiscalYear eq '2026'".`},maxResults:{type:"integer",description:"Maximum number of line items to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"fetchJournalItems",instruction:"Fetch accounting document line items, paging through results with $skip.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/API_OPLACCTGDOCITEMCUBE_SRV/A_OperationalAcctgDocItemCube",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$top:"<<pageSize>>",$skip:"<<offset>>",$filter:"<<filter>>",$select:"AccountingDocument,CompanyCode,FiscalYear,GLAccount,AmountInCompanyCodeCurrency,PostingDate"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const d = (v) => { if (typeof v !== 'string' || !v.startsWith('/Date(')) return v; const n = parseInt(v.slice(6), 10); return Number.isFinite(n) ? new Date(n).toISOString().slice(0, 10) : v; }; const rows = (sourceData.fetchJournalItems?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 200); return { total: rows.length, journalItems: rows.map((r) => ({ document: r.AccountingDocument, companyCode: r.CompanyCode, fiscalYear: r.FiscalYear, account: r.GLAccount, amount: Number(r.AmountInCompanyCodeCurrency), postingDate: d(r.PostingDate) })) }; }"},{id:"sap-query-odata",name:"Query any SAP OData service",shortName:"Query any service",instruction:"Queries any SAP S/4HANA OData service and entity set (for example API_PRODUCT_SRV/A_ProductDescription or API_SALES_ORDER_SRV/A_SalesOrderItem) with optional $select and $filter. The workhorse tool for data checks beyond the prebuilt lists.",inputSchema:{type:"object",properties:{servicePath:{type:"string",description:'Service and entity set in SERVICE/EntitySet form, e.g. "API_SALES_ORDER_SRV/A_SalesOrderItem".'},select:{type:"string",description:"Comma-separated OData $select field list. Omit for all fields."},filter:{type:"string",description:"Optional OData $filter expression."},maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 100."}},required:["servicePath"],additionalProperties:!0},steps:[{id:"queryService",instruction:"Query the requested OData service and entity set.",config:{type:"request",systemId:"sap_s4hana",url:"<<sap_s4hana_url>>/<<servicePath>>",method:"GET",headers:{APIKey:"<<sap_s4hana_api_key>>",Accept:"application/json"},queryParams:{$format:"json",$select:"<<select>>",$filter:"<<filter>>",$top:"<<pageSize>>",$skip:"<<offset>>"},pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const rows = response?.data?.d?.results ?? []; const fetched = pageInfo?.mergedResult?.d?.results?.length ?? 0; const max = sourceData?.maxResults ?? 100; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:"(sourceData) => { const rows = (sourceData.queryService?.data?.d?.results ?? []).slice(0, sourceData.maxResults ?? 100); return { total: rows.length, records: rows.map((r) => { const { __metadata, ...rest } = r; return rest; }) }; }"}]},sage100:{bundleId:"sage100",templateId:"sage100",systemId:"sage100",displayName:"Sage 100",description:"Connect on-premises Sage 100 through the superglue Secure Gateway, with a guided setup playbook and a connection test against the Business Object Interface.",systemUrl:"script://runner/vbs32",credentialHint:"Your assistant first helps you connect a Secure Gateway on your Sage 100 server, then collects your Sage company and user details.",requiredCredentialKeys:["sage_home","sage_company","sage_user","sage_password"],mcpServer:{name:"sage-100",displayName:"Sage 100",description:"Sage 100 Business Object Interface access through the Secure Gateway."},installMcpServer:!1,playbook:{id:"sage100-native-integration",name:"Sage 100 Native Integration (BOI)",whenToRun:"Use when connecting a Sage 100 installation to superglue, testing that connection, or building tools that read or write Sage 100 data through the Business Object Interface.",inputs:"A Sage 100 installation on a Windows machine the user can access; a superglue API key for the gateway; the Sage company code, a Sage user with module access, and the path to the MAS90\\Home directory; the business outcome once connected.",instructions:"First check /org/tunnels for a connected gateway with a runner target. If none is connected, call setup_gateway with os windows and enableScriptRunner true (no targets are needed); the user runs the install command in PowerShell opened with 'Run as administrator' on the machine where Sage 100 and Workstation Setup are installed (the gateway must run there, ProvideX.Script is a local 32-bit COM class). The command installs the gateway as a Windows service and the call completes when it connects; never ask for the command or its key in chat. The same setup is in Systems \u2192 Connect system \u2192 Private System \u2192 Set up a gateway. The script runner option is required: it opts the gateway into running Sage scripts (it is code execution on their machine, so it is off by default), and it is what registers the built-in runner target. Only if the user cannot use that page, fall back to the manual setup: download https://downloads.superglue.cloud/superglue-gateway-windows.exe, create a config.yaml next to it with a tunnel_id, the server_url ending in /ws/tunnels (wss://api.superglue.cloud/ws/tunnels for hosted superglue), an API key from the API Keys page, and the line enable_script_runner: true, then run the executable. If a tunnel is connected but has no runner target, the gateway was set up without the script runner or is an outdated build; have the user set up the gateway again with the option selected, or add the flag and restart. The service runs as the Windows system account: if Sage data is on a mapped drive or a network share that account cannot reach, the connection test fails with a path or access error. When the tunnel with the runner target appears, attach it to this Sage 100 system with tools.writeSystem from superglue/approved (tunnel with that tunnelId) and keep the URL script://runner/vbs32. Collect sage_home (full path to the MAS90\\Home directory, for example C:\\Sage\\Sage100\\MAS90\\Home, not the MAS90 directory itself), sage_company, sage_user and sage_password through the secure credential form, never as chat text. Then run the Test Sage 100 connection tool once and interpret the result: retVal 0 failures carry the Sage reason in sLastErrorMsg (wrong credentials, missing role access, wrong company code); COM error 0x80040154 means the gateway is not running on a machine with Sage 100 Workstation Setup; a no-license message means all Sage user seats are in use. For new capabilities, build tools whose steps use the script protocol with VBScript in the body: log on with SY_Session, set module context before touching data (nSetDate with YYYYMMDD dates, nSetModule, nLookupTask, nSetProgram), use _svc service objects for reads and _bus business objects for writes, and always release the session with nCleanup and DropObject so the license seat frees up. For reads, set each key segment with nSetKeyValue then nFind for a single record, or browse with nMoveFirst and nMoveNext, and read each field with nGetValue passing a variable that receives the value. To write a document that has lines, such as a sales order, get the header _bus object, set the header fields, get its oLines object, call nAddLine, set the line fields, then call nWrite on the header to commit the header and its lines together. A write fails with a lock error if the record is open in the Sage desktop or held by another session, so report the lock message instead of retrying. Each running script briefly consumes a Sage user seat. Ask for explicit approval before any script that writes to Sage, and warn that records open in the Sage desktop UI cause lock errors.",completionCriteria:"The gateway is connected, the installed Sage 100 system has the tunnel attached and credentials saved, and the connection test returned company data from Sage 100. Any additional requested capability works end to end, with writes explicitly approved before they ran."},agentLaunch:{userPrompt:"I just installed the Sage 100 integration. Help me connect my Sage 100 server.",nextSteps:'Your first reply must be short: one line confirming the Sage 100 integration and setup playbook are installed, then start the connection flow. Check /org/tunnels for a connected gateway with a runner target first. If none exists, call setup_gateway with os windows and enableScriptRunner true (no targets are needed), and tell the user to run the install command in PowerShell opened with "Run as administrator" on the Windows machine where Sage 100 is installed and Workstation Setup has run. The call completes when the gateway connects; never ask for the command or its key in chat. The script runner option is required: it opts the gateway into running scripts on their machine (off by default because it is code execution) and is what registers the runner target. If a tunnel is connected but has no runner target, the gateway was set up without the script runner or is an outdated build: have the user set up the gateway again with the option selected. When setup_gateway completes, check that the returned targets include runner, then attach that tunnel to this Sage 100 system with tools.writeSystem from superglue/approved, keeping the URL script://runner/vbs32. Use set_credentials to collect sage_home (full path to the MAS90\\Home directory, for example C:\\Sage\\Sage100\\MAS90\\Home, not MAS90 itself), sage_company (for example ABC for the demo company), sage_user and sage_password. Never send the user to the Credentials page and never accept secrets as chat text. Then run the Test Sage 100 connection tool once. If it fails, explain the specific cause in plain language before retrying. Mention that each test briefly uses one Sage user license seat. Do not list tools or add tips unless asked.'},tools:[{id:"sage100-test-connection",name:"Test Sage 100 connection",shortName:"Connection test",instruction:"Logs on to Sage 100 through the Secure Gateway, opens the configured company, and reads the first customer record to verify the Business Object Interface end to end. Briefly consumes one Sage user license seat.",steps:[{id:"testConnection",instruction:"Run a VBScript through the gateway script runner that logs on via SY_Session, sets A/R module context, and reads the first customer.",config:{type:"request",systemId:"sage100",url:"<<sage100_url>>",method:"POST",body:["Option Explicit","On Error Resume Next","Dim oScript, oSS, oCust, retVal, custNo, custName, today",'Set oScript = CreateObject("ProvideX.Script")','FailOnErr "CREATE", " (Sage 100 Workstation Setup has not registered ProvideX.Script on this machine; the gateway must run on a prepared Sage 100 machine)"','oScript.Init "<<sage100_sage_home>>"','FailOnErr "INIT", " (sage_home must be the full path to the MAS90\\Home directory, not MAS90 itself)"','Set oSS = oScript.NewObject("SY_Session")','FailOnErr "SESSION", ""','retVal = oSS.nSetUser("<<sage100_sage_user>>", "<<sage100_sage_password>>")','FailOnErr "LOGON", ""',"If retVal = 0 Then",' WScript.Echo "LOGON FAILED: " & oSS.sLastErrorMsg'," WScript.Quit 1","End If",'retVal = oSS.nSetCompany("<<sage100_sage_company>>")','FailOnErr "COMPANY", ""',"If retVal = 0 Then",' WScript.Echo "COMPANY FAILED: " & oSS.sLastErrorMsg'," oSS.nCleanup"," oSS.DropObject"," WScript.Quit 1","End If",'today = Year(Date) & Right("0" & Month(Date), 2) & Right("0" & Day(Date), 2)','retVal = oSS.nSetDate("A/R", today)','FailOnErr "DATE", ""','retVal = oSS.nSetModule("A/R")','FailOnErr "MODULE", ""','retVal = oSS.nSetProgram(oSS.nLookupTask("AR_Customer_ui"))','FailOnErr "TASK", ""',"If retVal = 0 Then",' WScript.Echo "TASK FAILED: " & oSS.sLastErrorMsg'," oSS.nCleanup"," oSS.DropObject"," WScript.Quit 1","End If",'Set oCust = oScript.NewObject("AR_Customer_svc", oSS)','FailOnErr "CUSTOMER OBJECT", ""',"retVal = oCust.nMoveFirst()",'FailOnErr "READ", ""',"If retVal = 0 Then",' WScript.Echo "READ FAILED: " & oCust.sLastErrorMsg',"Else",' custNo = "" : custName = ""',' retVal = oCust.nGetValue("CustomerNo$", custNo)',' retVal = oCust.nGetValue("CustomerName$", custName)',' FailOnErr "READ VALUE", " (ByRef value marshalling failed)"',' WScript.Echo "CONNECTED - company <<sage100_sage_company>>, first customer: " & custNo & " / " & custName',"End If","oCust.DropObject","oSS.nCleanup","oSS.DropObject","If retVal = 0 Then WScript.Quit 1","","Sub FailOnErr(stage, hint)"," If Err.Number <> 0 Then",' WScript.Echo stage & " FAILED: [0x" & Hex(Err.Number) & "] " & Err.Description & hint'," WScript.Quit 1"," End If","End Sub"].join(`
80
80
  `)}}]}]},sage_intacct:{bundleId:"sage_intacct",templateId:"sage_intacct",systemId:"sage_intacct",displayName:"Sage Intacct",description:"Install a Sage Intacct system, eight read/query tools, fourteen write tools and a native integration playbook.",systemUrl:"https://api.intacct.com/ia/xml/xmlgw.phtml",credentialHint:"Works instantly with a Sage Intacct demo company. Enter your company ID and API user credentials to use your own company. Web Services sender credentials are preconfigured.",requiredCredentialKeys:["sender_id","sender_password","user_id","user_password","company_id"],demoCredentials:{company_id:"IndexCommerceMPP-DEV",user_id:"superglue",user_password:"Linux123___"},mcpServer:{name:"sage-intacct",displayName:"Sage Intacct",description:"Chart of accounts, customers, vendors, journal entries and ad-hoc object queries from Sage Intacct, plus create and update tools for GL accounts, journal entries, invoices, bills, departments, vendors and customers."},installMcpServer:!1,playbook:{id:"sage-intacct-native-integration",name:"Sage Intacct Native Integration",whenToRun:"Use when connecting, validating, querying or extending a Sage Intacct integration through XML Web Services.",inputs:"A configured Sage Intacct system; the object or business process to work with; optional Location/Entity ID for multi-entity companies; validation criteria and desired output.",instructions:"Use the installed read-only tools for chart of accounts, customers, vendors, journal entries, invoices, bills and departments. Use Query any Sage Intacct object for supported objects outside the named library. Use the installed create and update tools for GL accounts, journal entries, invoices, bills, departments, vendors and customers only after the user explicitly confirms the exact records to write; the create tools are not idempotent and re-running them duplicates records. Apply the configured Location/Entity ID when present. Verify every XML Web Services response at control, authentication and function-result level, and preserve Sage support IDs in failures. For other objects or operations, inspect Sage object documentation, create separate least-privilege tools, validate them in a development company and require explicit user confirmation before modifying Sage data.",completionCriteria:"The requested Sage data, write result or validation result is returned; entity scope is correct; Sage XML failures are surfaced as failures with support IDs; no Sage data is modified unless the user explicitly requested and confirmed the write."},agentLaunch:{userPrompt:"I just installed the Sage Intacct integration. What can I do with it?",nextSteps:"Your first reply must be short: one line confirming the Sage Intacct integration and native integration playbook are installed, then offer one read-only test run. If the user entered no company credentials during install, the system uses a shared Sage Intacct demo company and works right now. Other users share the demo company, so run create or update tools against it only when the user explicitly asks and confirms the exact records. For their own company, use set_credentials for this system to collect user_id, user_password and company_id, plus optional entity_id when the user wants to target one entity in a multi-entity company. The Web Services sender credentials are already configured. Never send the user to the Credentials page and never accept secrets as chat text. The user id and password are an API user login in the company; company id is the Intacct company id. Do not list the installed tools or add tips unless asked. The query tool accepts other supported Intacct object names, and additional read or write tools can be built beyond the default library. The installed create and update tools modify Sage data; run them only after the user confirms the exact records to write."},tools:[{id:"sage-intacct-list-accounts",name:"List Sage Intacct chart of accounts",shortName:"Chart of accounts",instruction:"Lists general ledger accounts (the chart of accounts) from Sage Intacct via the XML Web Services API. Useful for validating an imported chart of accounts after a migration.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryAccounts",instruction:"Query GLACCOUNT records via readByQuery-style paging.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt("<query><object>GLACCOUNT</object><select><field>RECORDNO</field><field>ACCOUNTNO</field><field>TITLE</field><field>ACCOUNTTYPE</field><field>NORMALBALANCE</field><field>STATUS</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.GLACCOUNT : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.GLACCOUNT : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:fs({stepId:"queryAccounts",objectNameExpression:"'GLACCOUNT'",collectionName:"accounts",mapExpression:"(record) => ({ recordNo: record.RECORDNO, account: record.ACCOUNTNO, name: record.TITLE, type: record.ACCOUNTTYPE, normalBalance: record.NORMALBALANCE, status: record.STATUS })"})},{id:"sage-intacct-list-customers",name:"List Sage Intacct customers",shortName:"Customers",instruction:"Lists customer master records from Sage Intacct accounts receivable. Useful for verifying migrated AR master data.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryCustomers",instruction:"Query CUSTOMER records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt("<query><object>CUSTOMER</object><select><field>RECORDNO</field><field>CUSTOMERID</field><field>NAME</field><field>STATUS</field><field>WHENCREATED</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.CUSTOMER : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.CUSTOMER : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:fs({stepId:"queryCustomers",objectNameExpression:"'CUSTOMER'",collectionName:"customers",mapExpression:"(record) => ({ recordNo: record.RECORDNO, customerId: record.CUSTOMERID, name: record.NAME, status: record.STATUS, createdOn: record.WHENCREATED })"})},{id:"sage-intacct-list-vendors",name:"List Sage Intacct vendors",shortName:"Vendors",instruction:"Lists vendor master records from Sage Intacct accounts payable. Useful for verifying migrated AP master data.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryVendors",instruction:"Query VENDOR records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt("<query><object>VENDOR</object><select><field>RECORDNO</field><field>VENDORID</field><field>NAME</field><field>STATUS</field><field>WHENCREATED</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.VENDOR : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.VENDOR : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:fs({stepId:"queryVendors",objectNameExpression:"'VENDOR'",collectionName:"vendors",mapExpression:"(record) => ({ recordNo: record.RECORDNO, vendorId: record.VENDORID, name: record.NAME, status: record.STATUS, createdOn: record.WHENCREATED })"})},{id:"sage-intacct-list-journal-entries",name:"List Sage Intacct journal entries",shortName:"Journal entries",instruction:"Lists general ledger entries from Sage Intacct with account, type and amount. Useful for verifying opening balances and postings at cutover.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryJournalEntries",instruction:"Query GLENTRY records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt("<query><object>GLENTRY</object><select><field>RECORDNO</field><field>BATCHNO</field><field>ACCOUNTNO</field><field>TR_TYPE</field><field>AMOUNT</field><field>ENTRY_DATE</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.GLENTRY : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.GLENTRY : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:fs({stepId:"queryJournalEntries",objectNameExpression:"'GLENTRY'",collectionName:"journalEntries",mapExpression:"(record) => ({ recordNo: record.RECORDNO, batch: record.BATCHNO, account: record.ACCOUNTNO, type: record.TR_TYPE, amount: Number(record.AMOUNT), date: record.ENTRY_DATE })"})},{id:"sage-intacct-list-invoices",name:"List Sage Intacct invoices",shortName:"Invoices",instruction:"Lists accounts receivable invoices from Sage Intacct. Useful for verifying migrated open AR at go-live.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryInvoices",instruction:"Query ARINVOICE records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt("<query><object>ARINVOICE</object><select><field>RECORDNO</field><field>RECORDID</field><field>CUSTOMERID</field><field>TOTALDUE</field><field>WHENCREATED</field><field>STATE</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.ARINVOICE : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.ARINVOICE : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:fs({stepId:"queryInvoices",objectNameExpression:"'ARINVOICE'",collectionName:"invoices",mapExpression:"(record) => ({ recordNo: record.RECORDNO, invoiceId: record.RECORDID, customerId: record.CUSTOMERID, totalDue: Number(record.TOTALDUE), createdOn: record.WHENCREATED, state: record.STATE })"})},{id:"sage-intacct-list-bills",name:"List Sage Intacct bills",shortName:"Bills",instruction:"Lists accounts payable bills from Sage Intacct. Useful for verifying migrated open AP at go-live.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryBills",instruction:"Query APBILL records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt("<query><object>APBILL</object><select><field>RECORDNO</field><field>RECORDID</field><field>VENDORID</field><field>TOTALDUE</field><field>WHENCREATED</field><field>STATE</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.APBILL : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.APBILL : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:fs({stepId:"queryBills",objectNameExpression:"'APBILL'",collectionName:"bills",mapExpression:"(record) => ({ recordNo: record.RECORDNO, billId: record.RECORDID, vendorId: record.VENDORID, totalDue: Number(record.TOTALDUE), createdOn: record.WHENCREATED, state: record.STATE })"})},{id:"sage-intacct-list-departments",name:"List Sage Intacct departments",shortName:"Departments",instruction:"Lists department dimensions from Sage Intacct. Useful for validating the dimension setup after an implementation.",inputSchema:{type:"object",properties:{maxResults:{type:"integer",description:"Maximum number of records to return. Defaults to 200."}},additionalProperties:!0},steps:[{id:"queryDepartments",instruction:"Query DEPARTMENT records.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt("<query><object>DEPARTMENT</object><select><field>RECORDNO</field><field>DEPARTMENTID</field><field>TITLE</field><field>STATUS</field></select><pagesize><<pageSize>></pagesize><offset><<offset>></offset></query>"),pagination:{type:"offsetBased",pageSize:"100",stopCondition:"(response, pageInfo, sourceData) => { const dig = (o) => o && o.RESPONSE && o.RESPONSE.OPERATION && o.RESPONSE.OPERATION.RESULT ? o.RESPONSE.OPERATION.RESULT.DATA : undefined; const cur = dig(response && response.data); const cr = cur ? cur.DEPARTMENT : undefined; const rows = Array.isArray(cr) ? cr : (cr ? [cr] : []); const mr = dig(pageInfo && pageInfo.mergedResult); const mraw = mr ? mr.DEPARTMENT : undefined; const fetched = Array.isArray(mraw) ? mraw.length : (mraw ? 1 : 0); const max = (sourceData && sourceData.maxResults) ?? 200; return rows.length === 0 || fetched >= max; }"}}}],outputTransform:fs({stepId:"queryDepartments",objectNameExpression:"'DEPARTMENT'",collectionName:"departments",mapExpression:"(record) => ({ recordNo: record.RECORDNO, departmentId: record.DEPARTMENTID, name: record.TITLE, status: record.STATUS })"})},{id:"sage-intacct-query-object",name:"Query any Sage Intacct object",shortName:"Query any object",instruction:"Queries any Sage Intacct object by name (for example GLACCOUNT, PROJECT, GLENTRY, ARINVOICE) using the XML Web Services readByQuery, with an optional Intacct query filter. The workhorse tool for migration validation beyond the prebuilt lists. Returns up to 1000 records in one call.",inputSchema:{type:"object",properties:{object:{type:"string",description:'Intacct object name, e.g. "GLACCOUNT", "PROJECT", "GLENTRY", "ARINVOICE".'},query:{type:"string",description:`Optional Intacct query filter, e.g. "STATUS = 'active'". Leave empty to return all records.`},maxResults:{type:"integer",description:"Maximum number of records to return (max 1000). Defaults to 100."}},required:["object"],additionalProperties:!0},steps:[{id:"queryObject",instruction:"Run readByQuery for the requested object.",config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt("<readByQuery><object><<(p) => { const value = String(p.object || '').toUpperCase(); if (!/^[A-Z][A-Z0-9_]*$/.test(value)) throw new Error('Sage Intacct object must contain only letters, numbers, and underscores.'); return value; }>></object><fields>*</fields><query><<(p) => String(p.query || '').replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')>></query><pagesize><<(p) => Math.min(Math.max(Number(p.maxResults) || 100, 1), 1000)>></pagesize></readByQuery>")}}],outputTransform:fs({stepId:"queryObject",objectNameExpression:"(sourceData && sourceData.object ? String(sourceData.object) : '').toUpperCase()",collectionName:"records",includeTotalCount:!0})},{id:"sage-intacct-create-journal-entry",name:"Create Sage Intacct journal entry",shortName:"Create journal entry",instruction:"Creates a journal entry (GLBATCH with GLENTRY lines) in Sage Intacct via the XML Web Services API. Debits and credits must balance. Re-running this tool creates another journal entry; it is not idempotent.",inputSchema:{type:"object",properties:{journal:{type:"string",description:'Journal symbol, e.g. "GJ". Defaults to GJ.'},date:{type:"string",description:"Posting date as YYYY-MM-DD."},title:{type:"string",description:"Journal entry description."},lines:{type:"array",description:"Journal lines. Debit and credit totals must balance.",items:{type:"object",properties:{accountNo:{type:"string",description:"GL account number."},type:{type:"string",enum:["debit","credit"]},amount:{type:"number",description:"Positive amount."},department:{type:"string",description:"Optional department ID."},location:{type:"string",description:"Optional location ID."},memo:{type:"string",description:"Optional line description."}},required:["accountNo","type","amount"],additionalProperties:!0}}},required:["date","title","lines"],additionalProperties:!0},steps:[{id:"createJournalEntry",instruction:"Create the GLBATCH record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<create><GLBATCH><JOURNAL><<(sourceData) => { ${hs} return esc(sourceData.journal || 'GJ'); }>></JOURNAL><BATCH_DATE><<(sourceData) => { ${PM} return toIntacctDate(sourceData.date); }>></BATCH_DATE><BATCH_TITLE><<(sourceData) => { ${hs} return esc(sourceData.title); }>></BATCH_TITLE><ENTRIES><<(sourceData) => { ${hs} ${$M} ${FM} const lines = Array.isArray(sourceData.lines) ? sourceData.lines : []; if (lines.length === 0) throw new Error('lines must contain at least one journal line.'); assertBalanced(lines); return lines.map(lineXml).join(''); }>></ENTRIES></GLBATCH></create>`)}}],outputTransform:Zc({stepId:"createJournalEntry",objectName:"GLBATCH"})},{id:"sage-intacct-update-journal-entry",name:"Update Sage Intacct journal entry",shortName:"Update journal entry",instruction:"Updates an existing journal entry (GLBATCH) in Sage Intacct by record number. Posted or locked entries may refuse updates. When lines are provided they replace all existing lines of the entry.",inputSchema:{type:"object",properties:{recordNo:{type:"integer",description:"RECORDNO of the journal entry to update."},journal:{type:"string",description:"Optional new journal symbol."},date:{type:"string",description:"Optional new posting date as YYYY-MM-DD."},title:{type:"string",description:"Optional new description."},lines:{type:"array",description:"Optional replacement lines. When set, they replace every existing line and must balance.",items:{type:"object",properties:{accountNo:{type:"string",description:"GL account number."},type:{type:"string",enum:["debit","credit"]},amount:{type:"number",description:"Positive amount."},department:{type:"string",description:"Optional department ID."},location:{type:"string",description:"Optional location ID."},memo:{type:"string",description:"Optional line description."}},required:["accountNo","type","amount"],additionalProperties:!0}}},required:["recordNo"],additionalProperties:!0},steps:[{id:"updateJournalEntry",instruction:"Update the GLBATCH record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<update><GLBATCH><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { ${hs} ${PM} ${$M} ${FM} let xml = ''; if (sourceData.journal) xml += '<JOURNAL>' + esc(sourceData.journal) + '</JOURNAL>'; if (sourceData.date) xml += '<BATCH_DATE>' + toIntacctDate(sourceData.date) + '</BATCH_DATE>'; if (sourceData.title) xml += '<BATCH_TITLE>' + esc(sourceData.title) + '</BATCH_TITLE>'; if (Array.isArray(sourceData.lines) && sourceData.lines.length > 0) { assertBalanced(sourceData.lines); xml += '<ENTRIES>' + sourceData.lines.map(lineXml).join('') + '</ENTRIES>'; } if (!xml) throw new Error('Provide at least one field to update.'); return xml; }>></GLBATCH></update>`)}}],outputTransform:Zc({stepId:"updateJournalEntry",objectName:"GLBATCH"})},{id:"sage-intacct-create-vendor",name:"Create Sage Intacct vendor",shortName:"Create vendor",instruction:"Creates a vendor master record in Sage Intacct via the XML Web Services API. Omit vendorId when the company uses vendor auto-numbering. Re-running this tool creates another vendor; it is not idempotent.",inputSchema:{type:"object",properties:{vendorId:{type:"string",description:"Vendor ID. Omit when auto-numbering assigns it."},name:{type:"string",description:"Vendor name."},taxId:{type:"string",description:"Optional tax ID."}},required:["name"],additionalProperties:!0},steps:[{id:"createVendor",instruction:"Create the VENDOR record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<create><VENDOR><<(sourceData) => { ${hs} if (!sourceData.name) throw new Error('name is required.'); let xml = ''; if (sourceData.vendorId) xml += '<VENDORID>' + esc(sourceData.vendorId) + '</VENDORID>'; xml += '<NAME>' + esc(sourceData.name) + '</NAME>'; if (sourceData.taxId) xml += '<TAXID>' + esc(sourceData.taxId) + '</TAXID>'; return xml; }>></VENDOR></create>`)}}],outputTransform:Zc({stepId:"createVendor",objectName:"VENDOR"})},{id:"sage-intacct-update-vendor",name:"Update Sage Intacct vendor",shortName:"Update vendor",instruction:"Updates an existing vendor master record in Sage Intacct by record number. Only the provided fields change.",inputSchema:{type:"object",properties:{recordNo:{type:"integer",description:"RECORDNO of the vendor to update."},name:{type:"string",description:"Optional new vendor name."},status:{type:"string",enum:["active","inactive"]},taxId:{type:"string",description:"Optional new tax ID."}},required:["recordNo"],additionalProperties:!0},steps:[{id:"updateVendor",instruction:"Update the VENDOR record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<update><VENDOR><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { ${hs} let xml = ''; if (sourceData.name) xml += '<NAME>' + esc(sourceData.name) + '</NAME>'; if (sourceData.status) xml += '<STATUS>' + esc(sourceData.status) + '</STATUS>'; if (sourceData.taxId) xml += '<TAXID>' + esc(sourceData.taxId) + '</TAXID>'; if (!xml) throw new Error('Provide at least one field to update.'); return xml; }>></VENDOR></update>`)}}],outputTransform:Zc({stepId:"updateVendor",objectName:"VENDOR"})},{id:"sage-intacct-create-customer",name:"Create Sage Intacct customer",shortName:"Create customer",instruction:"Creates a customer master record in Sage Intacct via the XML Web Services API. Omit customerId when the company uses customer auto-numbering. Re-running this tool creates another customer; it is not idempotent.",inputSchema:{type:"object",properties:{customerId:{type:"string",description:"Customer ID. Omit when auto-numbering assigns it."},name:{type:"string",description:"Customer name."},taxId:{type:"string",description:"Optional tax ID."}},required:["name"],additionalProperties:!0},steps:[{id:"createCustomer",instruction:"Create the CUSTOMER record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<create><CUSTOMER><<(sourceData) => { ${hs} if (!sourceData.name) throw new Error('name is required.'); let xml = ''; if (sourceData.customerId) xml += '<CUSTOMERID>' + esc(sourceData.customerId) + '</CUSTOMERID>'; xml += '<NAME>' + esc(sourceData.name) + '</NAME>'; if (sourceData.taxId) xml += '<TAXID>' + esc(sourceData.taxId) + '</TAXID>'; return xml; }>></CUSTOMER></create>`)}}],outputTransform:Zc({stepId:"createCustomer",objectName:"CUSTOMER"})},{id:"sage-intacct-update-customer",name:"Update Sage Intacct customer",shortName:"Update customer",instruction:"Updates an existing customer master record in Sage Intacct by record number. Only the provided fields change.",inputSchema:{type:"object",properties:{recordNo:{type:"integer",description:"RECORDNO of the customer to update."},name:{type:"string",description:"Optional new customer name."},status:{type:"string",enum:["active","inactive"]},taxId:{type:"string",description:"Optional new tax ID."}},required:["recordNo"],additionalProperties:!0},steps:[{id:"updateCustomer",instruction:"Update the CUSTOMER record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<update><CUSTOMER><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { ${hs} let xml = ''; if (sourceData.name) xml += '<NAME>' + esc(sourceData.name) + '</NAME>'; if (sourceData.status) xml += '<STATUS>' + esc(sourceData.status) + '</STATUS>'; if (sourceData.taxId) xml += '<TAXID>' + esc(sourceData.taxId) + '</TAXID>'; if (!xml) throw new Error('Provide at least one field to update.'); return xml; }>></CUSTOMER></update>`)}}],outputTransform:Zc({stepId:"updateCustomer",objectName:"CUSTOMER"})},{id:"sage-intacct-create-account",name:"Create Sage Intacct GL account",shortName:"Create GL account",instruction:"Creates a general ledger account in Sage Intacct via the XML Web Services API. Re-running this tool creates another account; it is not idempotent.",inputSchema:{type:"object",required:["accountNo","title","normalBalance","accountType"],properties:{title:{type:"string"},accountNo:{type:"string"},accountType:{type:"string",enum:["balancesheet","incomestatement"]},normalBalance:{type:"string",enum:["debit","credit"]},closingType:{type:"string",enum:["non-closing account","closing account"],description:"Period-end closing type. Defaults to non-closing account."},closingAccountNo:{type:"string",description:"Account to close into. Sage requires it when closingType is closing account."}}},steps:[{id:"createAccount",instruction:"Create the GLACCOUNT record via the Sage Intacct XML API.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<create><GLACCOUNT><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;'); if (!sourceData.accountNo) throw new Error('accountNo is required.'); if (!sourceData.title) throw new Error('title is required.'); let xml = '<ACCOUNTNO>' + esc(sourceData.accountNo) + '</ACCOUNTNO>'; xml += '<TITLE>' + esc(sourceData.title) + '</TITLE>'; xml += '<NORMALBALANCE>' + esc(sourceData.normalBalance || 'debit') + '</NORMALBALANCE>'; xml += '<ACCOUNTTYPE>' + esc(sourceData.accountType || 'balancesheet') + '</ACCOUNTTYPE>'; xml += '<CLOSINGTYPE>' + esc(sourceData.closingType || 'non-closing account') + '</CLOSINGTYPE>'; if (sourceData.closingAccountNo) xml += '<CLOSINGACCOUNTNO>' + esc(sourceData.closingAccountNo) + '</CLOSINGACCOUNTNO>'; return xml; }>></GLACCOUNT></create>`)}}],outputTransform:"(sourceData) => { const response = sourceData.createAccount && sourceData.createAccount.data ? sourceData.createAccount.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.GLACCOUNT || data.glaccount) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: record && record.RECORDNO ? Number(record.RECORDNO) : undefined, record }; }"},{id:"sage-intacct-update-account",name:"Update Sage Intacct GL account",shortName:"Update GL account",instruction:"Updates an existing general ledger account in Sage Intacct by account number. Only the provided fields change.",inputSchema:{type:"object",required:["accountNo"],properties:{title:{type:"string"},accountNo:{type:"string"},accountType:{type:"string",enum:["balancesheet","incomestatement"]},normalBalance:{type:"string",enum:["debit","credit"]},status:{type:"string",enum:["active","inactive"]}}},steps:[{id:"updateAccount",instruction:"Update the GLACCOUNT record by account number.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<update><GLACCOUNT><ACCOUNTNO><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;'); if (!sourceData.accountNo) throw new Error('accountNo is required.'); return esc(sourceData.accountNo); }>></ACCOUNTNO><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;'); let xml = ''; if (sourceData.title) xml += '<TITLE>' + esc(sourceData.title) + '</TITLE>'; if (sourceData.normalBalance) xml += '<NORMALBALANCE>' + esc(sourceData.normalBalance) + '</NORMALBALANCE>'; if (sourceData.accountType) xml += '<ACCOUNTTYPE>' + esc(sourceData.accountType) + '</ACCOUNTTYPE>'; if (sourceData.status) xml += '<STATUS>' + esc(sourceData.status) + '</STATUS>'; if (!xml) throw new Error('Provide at least one field to update.'); return xml; }>></GLACCOUNT></update>`)}}],outputTransform:"(sourceData) => { const response = sourceData.updateAccount && sourceData.updateAccount.data ? sourceData.updateAccount.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.GLACCOUNT || data.glaccount) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { accountNo: sourceData.accountNo, record }; }"},{id:"sage-intacct-create-invoice",name:"Create Sage Intacct AR invoice",shortName:"Create invoice",instruction:"Creates an AR invoice in Sage Intacct via the XML Web Services API. Requires a customer ID, transaction date, and at least one line item with a GL account and amount. Re-running creates another invoice; it is not idempotent.",inputSchema:{type:"object",required:["customerId","dateCreated","dateDue","lines"],properties:{lines:{type:"array",items:{type:"object",required:["glAccountNo","amount"],properties:{memo:{type:"string"},amount:{type:"number"},glAccountNo:{type:"string"},departmentId:{type:"string"},locationId:{type:"string"},vendorId:{type:"string"},customerId:{type:"string"},projectId:{type:"string"}}}},dateDue:{type:"string"},customerId:{type:"string"},dateCreated:{type:"string"},datePosted:{type:"string"},termName:{type:"string"},description:{type:"string"}}},steps:[{id:"createInvoice",instruction:"Create the ARINVOICE record with line items.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt("<create><ARINVOICE><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('\"', '&quot;').replaceAll(\"'\", '&apos;'); if (!sourceData.customerId) throw new Error('customerId is required.'); if (!sourceData.dateCreated) throw new Error('dateCreated is required (YYYY-MM-DD).'); const lines = Array.isArray(sourceData.lines) ? sourceData.lines : []; if (lines.length === 0) throw new Error('lines must contain at least one invoice line.'); const match = String(sourceData.dateCreated).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); const dateXml = match ? `<WHENCREATED><YEAR>${match[1]}</YEAR><MONTH>${match[2]}</MONTH><DAY>${match[3]}</DAY></WHENCREATED>` : `<WHENCREATED>${esc(sourceData.dateCreated)}</WHENCREATED>`; let xml = '<CUSTOMERID>' + esc(sourceData.customerId) + '</CUSTOMERID>'; xml += dateXml; if (sourceData.datePosted) { const mp = String(sourceData.datePosted).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); if (mp) xml += `<WHENPOSTED><YEAR>${mp[1]}</YEAR><MONTH>${mp[2]}</MONTH><DAY>${mp[3]}</DAY></WHENPOSTED>`; } if (sourceData.dateDue) { const md = String(sourceData.dateDue).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); if (md) xml += `<WHENDUE><YEAR>${md[1]}</YEAR><MONTH>${md[2]}</MONTH><DAY>${md[3]}</DAY></WHENDUE>`; } else if (sourceData.termName) { xml += '<TERMNAME>' + esc(sourceData.termName) + '</TERMNAME>'; } if (sourceData.description) xml += '<DESCRIPTION>' + esc(sourceData.description) + '</DESCRIPTION>'; xml += '<ARINVOICEITEMS>'; lines.forEach((line) => { if (!line.glAccountNo) throw new Error('Each line requires glAccountNo.'); if (line.amount == null) throw new Error('Each line requires amount.'); xml += '<ARINVOICEITEM>'; xml += '<ACCOUNTNO>' + esc(line.glAccountNo) + '</ACCOUNTNO>'; xml += '<AMOUNT>' + Number(line.amount) + '</AMOUNT>'; if (line.memo) xml += '<MEMO>' + esc(line.memo) + '</MEMO>'; if (line.departmentId) xml += '<DEPARTMENTID>' + esc(line.departmentId) + '</DEPARTMENTID>'; if (line.locationId) xml += '<LOCATIONID>' + esc(line.locationId) + '</LOCATIONID>'; if (line.vendorId) xml += '<VENDORID>' + esc(line.vendorId) + '</VENDORID>'; if (line.customerId) xml += '<CUSTOMERID>' + esc(line.customerId) + '</CUSTOMERID>'; if (line.projectId) xml += '<PROJECTID>' + esc(line.projectId) + '</PROJECTID>'; xml += '</ARINVOICEITEM>'; }); xml += '</ARINVOICEITEMS>'; return xml; }>></ARINVOICE></create>")}}],outputTransform:"(sourceData) => { const response = sourceData.createInvoice && sourceData.createInvoice.data ? sourceData.createInvoice.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.ARINVOICE || data.arinvoice) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: record && record.RECORDNO ? Number(record.RECORDNO) : undefined, record }; }"},{id:"sage-intacct-update-invoice",name:"Update Sage Intacct AR invoice",shortName:"Update invoice",instruction:"Updates an existing AR invoice in Sage Intacct by record number. Only the provided fields change. Line items can be added or updated by line number.",inputSchema:{type:"object",required:["recordNo"],properties:{recordNo:{type:"integer"},description:{type:"string"},customerId:{type:"string"},dateCreated:{type:"string"},dateDue:{type:"string"},termName:{type:"string"},lines:{type:"array",items:{type:"object",properties:{lineNo:{type:"integer"},memo:{type:"string"},amount:{type:"number"},glAccountNo:{type:"string"},departmentId:{type:"string"},locationId:{type:"string"},vendorId:{type:"string"},customerId:{type:"string"},projectId:{type:"string"}}}}}},steps:[{id:"updateInvoice",instruction:"Update the ARINVOICE record by RECORDNO.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt("<update><ARINVOICE><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('\"', '&quot;').replaceAll(\"'\", '&apos;'); let xml = ''; if (sourceData.customerId) xml += '<CUSTOMERID>' + esc(sourceData.customerId) + '</CUSTOMERID>'; if (sourceData.dateCreated) { const match = String(sourceData.dateCreated).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); if (match) xml += `<WHENCREATED><YEAR>${match[1]}</YEAR><MONTH>${match[2]}</MONTH><DAY>${match[3]}</DAY></WHENCREATED>`; } if (sourceData.dateDue) { const md = String(sourceData.dateDue).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); if (md) xml += `<WHENDUE><YEAR>${md[1]}</YEAR><MONTH>${md[2]}</MONTH><DAY>${md[3]}</DAY></WHENDUE>`; } if (sourceData.termName) xml += '<TERMNAME>' + esc(sourceData.termName) + '</TERMNAME>'; if (sourceData.description) xml += '<DESCRIPTION>' + esc(sourceData.description) + '</DESCRIPTION>'; const lines = Array.isArray(sourceData.lines) ? sourceData.lines : []; if (lines.length > 0) { xml += '<ARINVOICEITEMS>'; lines.forEach((line) => { xml += '<ARINVOICEITEM>'; if (line.lineNo) xml += '<LINE_NO>' + Number(line.lineNo) + '</LINE_NO>'; if (line.glAccountNo) xml += '<ACCOUNTNO>' + esc(line.glAccountNo) + '</ACCOUNTNO>'; if (line.amount != null) xml += '<AMOUNT>' + Number(line.amount) + '</AMOUNT>'; if (line.memo) xml += '<MEMO>' + esc(line.memo) + '</MEMO>'; if (line.departmentId) xml += '<DEPARTMENTID>' + esc(line.departmentId) + '</DEPARTMENTID>'; if (line.locationId) xml += '<LOCATIONID>' + esc(line.locationId) + '</LOCATIONID>'; if (line.vendorId) xml += '<VENDORID>' + esc(line.vendorId) + '</VENDORID>'; if (line.customerId) xml += '<CUSTOMERID>' + esc(line.customerId) + '</CUSTOMERID>'; if (line.projectId) xml += '<PROJECTID>' + esc(line.projectId) + '</PROJECTID>'; xml += '</ARINVOICEITEM>'; }); xml += '</ARINVOICEITEMS>'; } if (!xml && lines.length === 0) throw new Error('Provide at least one field to update.'); return xml; }>></ARINVOICE></update>")}}],outputTransform:"(sourceData) => { const response = sourceData.updateInvoice && sourceData.updateInvoice.data ? sourceData.updateInvoice.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.ARINVOICE || data.arinvoice) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: sourceData.recordNo, record }; }"},{id:"sage-intacct-create-bill",name:"Create Sage Intacct AP bill",shortName:"Create bill",instruction:"Creates an AP bill in Sage Intacct via the XML Web Services API. Requires a vendor ID, transaction date, and at least one line item with a GL account and amount. Re-running creates another bill; it is not idempotent.",inputSchema:{type:"object",required:["lines","dateDue","vendorId","dateCreated"],properties:{lines:{type:"array",items:{type:"object",required:["glAccountNo","amount"],properties:{memo:{type:"string"},amount:{type:"number"},glAccountNo:{type:"string"},departmentId:{type:"string"},locationId:{type:"string"},vendorId:{type:"string"},customerId:{type:"string"},projectId:{type:"string"}}}},dateDue:{type:"string"},vendorId:{type:"string"},dateCreated:{type:"string"},datePosted:{type:"string"},termName:{type:"string"},description:{type:"string"}}},steps:[{id:"createBill",instruction:"Create the APBILL record with line items.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<create><APBILL><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;'); if (!sourceData.vendorId) throw new Error('vendorId is required.'); if (!sourceData.dateCreated) throw new Error('dateCreated is required (YYYY-MM-DD).'); const lines = Array.isArray(sourceData.lines) ? sourceData.lines : []; if (lines.length === 0) throw new Error('lines must contain at least one bill line.'); const match = String(sourceData.dateCreated).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); const dateStr = match ? match[2] + '/' + match[3] + '/' + match[1] : sourceData.dateCreated; let xml = '<VENDORID>' + esc(sourceData.vendorId) + '</VENDORID>'; xml += '<WHENCREATED>' + esc(dateStr) + '</WHENCREATED>'; if (sourceData.datePosted) { const mp = String(sourceData.datePosted).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); xml += '<WHENPOSTED>' + esc(mp ? mp[2] + '/' + mp[3] + '/' + mp[1] : sourceData.datePosted) + '</WHENPOSTED>'; } if (sourceData.dateDue) { const md = String(sourceData.dateDue).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); xml += '<WHENDUE>' + esc(md ? md[2] + '/' + md[3] + '/' + md[1] : sourceData.dateDue) + '</WHENDUE>'; } else if (sourceData.termName) { xml += '<TERMNAME>' + esc(sourceData.termName) + '</TERMNAME>'; } if (sourceData.description) xml += '<DESCRIPTION>' + esc(sourceData.description) + '</DESCRIPTION>'; xml += '<APBILLITEMS>'; lines.forEach((line) => { if (!line.glAccountNo) throw new Error('Each line requires glAccountNo.'); if (line.amount == null) throw new Error('Each line requires amount.'); xml += '<APBILLITEM>'; xml += '<ACCOUNTNO>' + esc(line.glAccountNo) + '</ACCOUNTNO>'; xml += '<AMOUNT>' + Number(line.amount) + '</AMOUNT>'; if (line.memo) xml += '<MEMO>' + esc(line.memo) + '</MEMO>'; if (line.departmentId) xml += '<DEPARTMENTID>' + esc(line.departmentId) + '</DEPARTMENTID>'; if (line.locationId) xml += '<LOCATIONID>' + esc(line.locationId) + '</LOCATIONID>'; if (line.vendorId) xml += '<VENDORID>' + esc(line.vendorId) + '</VENDORID>'; if (line.customerId) xml += '<CUSTOMERID>' + esc(line.customerId) + '</CUSTOMERID>'; if (line.projectId) xml += '<PROJECTID>' + esc(line.projectId) + '</PROJECTID>'; xml += '</APBILLITEM>'; }); xml += '</APBILLITEMS>'; return xml; }>></APBILL></create>`)}}],outputTransform:"(sourceData) => { const response = sourceData.createBill && sourceData.createBill.data ? sourceData.createBill.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.APBILL || data.apbill) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: record && record.RECORDNO ? Number(record.RECORDNO) : undefined, record }; }"},{id:"sage-intacct-update-bill",name:"Update Sage Intacct AP bill",shortName:"Update bill",instruction:"Updates an existing AP bill in Sage Intacct by record number. Only the provided fields change. Line items can be added or updated by line number.",inputSchema:{type:"object",required:["recordNo"],properties:{recordNo:{type:"integer"},description:{type:"string"},vendorId:{type:"string"},dateCreated:{type:"string"},dateDue:{type:"string"},termName:{type:"string"},lines:{type:"array",items:{type:"object",properties:{lineNo:{type:"integer"},memo:{type:"string"},amount:{type:"number"},glAccountNo:{type:"string"},departmentId:{type:"string"},locationId:{type:"string"},vendorId:{type:"string"},customerId:{type:"string"},projectId:{type:"string"}}}}}},steps:[{id:"updateBill",instruction:"Update the APBILL record by RECORDNO.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<update><APBILL><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;'); let xml = ''; if (sourceData.vendorId) xml += '<VENDORID>' + esc(sourceData.vendorId) + '</VENDORID>'; if (sourceData.dateCreated) { const match = String(sourceData.dateCreated).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); xml += '<WHENCREATED>' + esc(match ? match[2] + '/' + match[3] + '/' + match[1] : sourceData.dateCreated) + '</WHENCREATED>'; } if (sourceData.dateDue) { const md = String(sourceData.dateDue).match(/^(\\d{4})-(\\d{2})-(\\d{2})/); xml += '<WHENDUE>' + esc(md ? md[2] + '/' + md[3] + '/' + md[1] : sourceData.dateDue) + '</WHENDUE>'; } if (sourceData.termName) xml += '<TERMNAME>' + esc(sourceData.termName) + '</TERMNAME>'; if (sourceData.description) xml += '<DESCRIPTION>' + esc(sourceData.description) + '</DESCRIPTION>'; const lines = Array.isArray(sourceData.lines) ? sourceData.lines : []; if (lines.length > 0) { xml += '<APBILLITEMS>'; lines.forEach((line) => { xml += '<APBILLITEM>'; if (line.lineNo) xml += '<LINE_NO>' + Number(line.lineNo) + '</LINE_NO>'; if (line.glAccountNo) xml += '<ACCOUNTNO>' + esc(line.glAccountNo) + '</ACCOUNTNO>'; if (line.amount != null) xml += '<AMOUNT>' + Number(line.amount) + '</AMOUNT>'; if (line.memo) xml += '<MEMO>' + esc(line.memo) + '</MEMO>'; if (line.departmentId) xml += '<DEPARTMENTID>' + esc(line.departmentId) + '</DEPARTMENTID>'; if (line.locationId) xml += '<LOCATIONID>' + esc(line.locationId) + '</LOCATIONID>'; if (line.vendorId) xml += '<VENDORID>' + esc(line.vendorId) + '</VENDORID>'; if (line.customerId) xml += '<CUSTOMERID>' + esc(line.customerId) + '</CUSTOMERID>'; if (line.projectId) xml += '<PROJECTID>' + esc(line.projectId) + '</PROJECTID>'; xml += '</APBILLITEM>'; }); xml += '</APBILLITEMS>'; } if (!xml && lines.length === 0) throw new Error('Provide at least one field to update.'); return xml; }>></APBILL></update>`)}}],outputTransform:"(sourceData) => { const response = sourceData.updateBill && sourceData.updateBill.data ? sourceData.updateBill.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.APBILL || data.apbill) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: sourceData.recordNo, record }; }"},{id:"sage-intacct-create-department",name:"Create Sage Intacct department",shortName:"Create department",instruction:"Creates a department in Sage Intacct via the XML Web Services API. Requires a department ID and title. Re-running creates another department; it is not idempotent.",inputSchema:{type:"object",required:["departmentId","title"],properties:{title:{type:"string"},departmentId:{type:"string"}}},steps:[{id:"createDepartment",instruction:"Create the DEPARTMENT record.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<create><DEPARTMENT><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;'); if (!sourceData.departmentId) throw new Error('departmentId is required.'); if (!sourceData.title) throw new Error('title is required.'); let xml = '<DEPARTMENTID>' + esc(sourceData.departmentId) + '</DEPARTMENTID>'; xml += '<TITLE>' + esc(sourceData.title) + '</TITLE>'; if (sourceData.parentId) xml += '<PARENTID>' + esc(sourceData.parentId) + '</PARENTID>'; if (sourceData.status) xml += '<STATUS>' + esc(sourceData.status) + '</STATUS>'; return xml; }>></DEPARTMENT></create>`)}}],outputTransform:"(sourceData) => { const response = sourceData.createDepartment && sourceData.createDepartment.data ? sourceData.createDepartment.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.DEPARTMENT || data.department) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: record && record.RECORDNO ? Number(record.RECORDNO) : undefined, record }; }"},{id:"sage-intacct-update-department",name:"Update Sage Intacct department",shortName:"Update department",instruction:"Updates an existing department in Sage Intacct by record number. Only the provided fields change.",inputSchema:{type:"object",required:["recordNo"],properties:{title:{type:"string"},recordNo:{type:"integer"},parentId:{type:"string"},status:{type:"string",enum:["active","inactive"]}}},steps:[{id:"updateDepartment",instruction:"Update the DEPARTMENT record by RECORDNO.",modify:!0,config:{type:"request",systemId:"sage_intacct",url:"<<sage_intacct_url>>",method:"POST",headers:{"Content-Type":"application/xml",Accept:"application/xml"},body:pt(`<update><DEPARTMENT><RECORDNO><<(sourceData) => { const recordNo = Number(sourceData.recordNo); if (!Number.isInteger(recordNo) || recordNo <= 0) throw new Error('recordNo must be a positive integer.'); return recordNo; }>></RECORDNO><<(sourceData) => { const esc = (value) => String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;').replaceAll("'", '&apos;'); let xml = ''; if (sourceData.title) xml += '<TITLE>' + esc(sourceData.title) + '</TITLE>'; if (sourceData.parentId) xml += '<PARENTID>' + esc(sourceData.parentId) + '</PARENTID>'; if (sourceData.status) xml += '<STATUS>' + esc(sourceData.status) + '</STATUS>'; if (!xml) throw new Error('Provide at least one field to update.'); return xml; }>></DEPARTMENT></update>`)}}],outputTransform:"(sourceData) => { const response = sourceData.updateDepartment && sourceData.updateDepartment.data ? sourceData.updateDepartment.data.RESPONSE : undefined; const control = response ? response.CONTROL : undefined; const operation = response ? response.OPERATION : undefined; const authentication = operation ? operation.AUTHENTICATION : undefined; const result = operation ? operation.RESULT : undefined; const statuses = [control && control.STATUS, authentication && authentication.STATUS, result && result.STATUS].filter(Boolean).map((value) => String(value).toLowerCase()); if (statuses.includes('failure')) { const message = (result && result.ERRORMESSAGE) || (authentication && authentication.ERR ? authentication.ERR.ERRORMESSAGE : undefined) || (control && control.ERR ? control.ERR.ERRORMESSAGE : undefined); const rawErrors = message ? message.ERROR : undefined; const errors = Array.isArray(rawErrors) ? rawErrors : (rawErrors ? [rawErrors] : []); const details = errors.map((error) => [error.ERRORNO, error.DESCRIPTION2 || error.DESCRIPTION, error.CORRECTION].filter(Boolean).join(' - ')).filter(Boolean); const supportIds = errors.map((error) => error.SUPPORTID).filter(Boolean); const suffix = supportIds.length ? ` Sage support ID: ${supportIds.join(', ')}.` : ''; throw new Error(`Sage Intacct request failed${details.length ? `: ${details.join('; ')}` : '.'}${suffix}`); } const data = result ? result.DATA : undefined; const raw = data ? (data.DEPARTMENT || data.department) : undefined; const record = Array.isArray(raw) ? raw[0] : raw; return { recordNo: sourceData.recordNo, record }; }"}]},dynamics365_sales:{bundleId:"dynamics365_sales",templateId:"dynamics365_sales",systemId:"dynamics365_sales",displayName:"Dynamics 365 Sales",description:"Read accounts, contacts and the sales pipeline from Dynamics 365 Sales.",systemUrl:"https://<<api_host>>/api/data/v9.2",credentialHint:"Set api_host to your environment host, then connect with Microsoft OAuth. Your assistant walks you through it.",requiredCredentialKeys:["api_host","access_token"],mcpServer:{name:"dynamics-sales",displayName:"Dynamics 365 Sales",description:"Accounts, contacts, opportunity pipeline and ad-hoc Dataverse queries from Dynamics 365 Sales."},installMcpServer:!0,agentLaunch:{userPrompt:"I just installed the Dynamics 365 Sales bundle. What can I do with it?",nextSteps:'Your first reply must be short: one line confirming the Dynamics MCP server is installed, then ask for their environment host in chat (like contoso.crm.dynamics.com \u2014 it is not a secret, so never collect it through a secure form; form values are redacted and you cannot read them back). When they reply, save it with set_credentials passing credentials: { api_host: "<their host>" } directly, without askForUserInputs. Then start Microsoft OAuth with authenticate_oauth and substitute the same host into the scopes yourself \u2014 send "https://<host>/user_impersonation offline_access", never the <<api_host>> placeholder, which Microsoft rejects. OAuth fills access_token automatically; never send the user to the Credentials page, never ask for a token as chat text, and never suggest the az CLI. Once connected, the MCP server is ready; offer one test run. Do not list the installed tools, do not add tips unless asked. If asked later: OAuth refresh is automatic, the query tool accepts any Dataverse entity set, and record totals above 5000 are reported as capped by Dataverse rather than exact.'},tools:[{id:"dynamics-list-accounts",name:"List Dynamics 365 accounts",shortName:"Accounts",instruction:"Lists account records from Dynamics 365 with name, account number and creation date. Supports an optional OData $filter. Useful for validating migrated accounts.",inputSchema:{type:"object",properties:{filter:{type:"string",description:`Optional OData $filter expression, e.g. "createdon gt 2026-01-01T00:00:00Z" or "contains(name,'GmbH')".`},maxResults:{type:"integer",description:"Maximum number of accounts to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchAccounts",instruction:"Fetch accounts from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/accounts",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"name,accountnumber,telephone1,websiteurl,createdon,modifiedon",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchAccounts?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, accounts: rows.map((r) => ({ id: r.accountid, name: r.name, accountNumber: r.accountnumber, phone: r.telephone1, website: r.websiteurl, createdOn: r.createdon, modifiedOn: r.modifiedon })) }; }'},{id:"dynamics-list-contacts",name:"List Dynamics 365 contacts",shortName:"Contacts",instruction:"Lists contact records from Dynamics 365 with name, email and creation date. Supports an optional OData $filter. Useful for validating migrated contacts.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional OData $filter expression, e.g. "emailaddress1 eq null" to find contacts missing an email.'},maxResults:{type:"integer",description:"Maximum number of contacts to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchContacts",instruction:"Fetch contacts from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/contacts",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"fullname,emailaddress1,telephone1,jobtitle,createdon,modifiedon",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchContacts?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, contacts: rows.map((r) => ({ id: r.contactid, name: r.fullname, email: r.emailaddress1, phone: r.telephone1, jobTitle: r.jobtitle, createdOn: r.createdon, modifiedOn: r.modifiedon })) }; }'},{id:"dynamics-open-opportunities",name:"List Dynamics 365 open opportunities",shortName:"Open opportunities",instruction:"Lists open opportunities from Dynamics 365 with estimated value and close date. Supports an optional additional OData $filter. Useful for pipeline verification during UAT.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional additional OData $filter combined with the open-state filter, e.g. "estimatedvalue gt 10000".'},maxResults:{type:"integer",description:"Maximum number of opportunities to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchOpportunities",instruction:"Fetch open opportunities from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/opportunities",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"name,estimatedvalue,estimatedclosedate,createdon,statecode,_parentaccountid_value",$filter:'<<(p) => p.filter ? "statecode eq 0 and (" + p.filter + ")" : "statecode eq 0">>',$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchOpportunities?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, opportunities: rows.map((r) => ({ id: r.opportunityid, name: r.name, estimatedValue: r.estimatedvalue, estimatedCloseDate: r.estimatedclosedate, accountId: r._parentaccountid_value, createdOn: r.createdon })) }; }'},{id:"dynamics-list-leads",name:"List Dynamics 365 leads",shortName:"Leads",instruction:"Lists lead records from Dynamics 365 with subject, name and company. Supports an optional OData $filter. Useful for validating migrated leads.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional OData $filter expression, e.g. "statecode eq 0" for open leads.'},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchLeads",instruction:"Fetch leads from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/leads",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"subject,fullname,companyname,statecode,createdon,modifiedon",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchLeads?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, records: rows.map((r) => ({ id: r.leadid, subject: r.subject, name: r.fullname, company: r.companyname, state: r.statecode, createdOn: r.createdon, modifiedOn: r.modifiedon })) }; }'},{id:"dynamics-list-cases",name:"List Dynamics 365 cases",shortName:"Cases",instruction:"Lists case (incident) records from Dynamics 365 with title, ticket number and status. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional OData $filter expression, e.g. "statecode eq 0" for active cases.'},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchCases",instruction:"Fetch incidents from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/incidents",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"title,ticketnumber,statecode,createdon,_customerid_value",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchCases?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, records: rows.map((r) => ({ id: r.incidentid, title: r.title, ticketNumber: r.ticketnumber, state: r.statecode, customerId: r._customerid_value, createdOn: r.createdon })) }; }'},{id:"dynamics-list-users",name:"List Dynamics 365 users",shortName:"Users",instruction:"Lists system users from Dynamics 365 with name, email and disabled state. Useful for owner-mapping checks during migrations.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional OData $filter expression, e.g. "isdisabled eq false" for active users.'},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchUsers",instruction:"Fetch systemusers from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/systemusers",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"fullname,internalemailaddress,isdisabled,createdon",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchUsers?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, records: rows.map((r) => ({ id: r.systemuserid, name: r.fullname, email: r.internalemailaddress, disabled: r.isdisabled, createdOn: r.createdon })) }; }'},{id:"dynamics-list-products",name:"List Dynamics 365 products",shortName:"Products",instruction:"Lists product catalog records from Dynamics 365 with name, number and state. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{filter:{type:"string",description:'Optional OData $filter expression, e.g. "statecode eq 0" for active products.'},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},additionalProperties:!0},steps:[{id:"fetchProducts",instruction:"Fetch products from the Dataverse Web API.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/products",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"name,productnumber,statecode,createdon",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchProducts?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, records: rows.map((r) => ({ id: r.productid, name: r.name, number: r.productnumber, state: r.statecode, createdOn: r.createdon })) }; }'},{id:"dynamics-query-dataverse",name:"Query any Dynamics 365 entity",shortName:"Query any entity",instruction:'Queries any Dataverse entity set. Required input: entitySet \u2014 the plural entity set name, e.g. "leads", "systemusers", "incidents". Optional inputs: select (OData $select field list), filter (OData $filter expression), maxResults (record cap, default 100). The workhorse tool for CRM migration validation and data quality checks beyond the prebuilt lists.',inputSchema:{type:"object",properties:{entitySet:{type:"string",description:'Dataverse entity set name (plural), e.g. "leads", "systemusers", "incidents".'},select:{type:"string",description:'Comma-separated OData $select field list, e.g. "subject,createdon". Omit for all fields.'},filter:{type:"string",description:"Optional OData $filter expression."},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},required:["entitySet"],additionalProperties:!0},steps:[{id:"queryEntity",instruction:"Query the requested Dataverse entity set.",config:{type:"request",systemId:"dynamics365_sales",url:"https://<<dynamics365_sales_api_host>>/api/data/v9.2/<<entitySet>>",method:"GET",headers:{Authorization:"Bearer <<dynamics365_sales_access_token>>",Accept:"application/json","OData-MaxVersion":"4.0","OData-Version":"4.0","If-None-Match":"null"},queryParams:{$select:"<<select>>",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.queryEntity?.data ?? {}; const rows = data.value ?? []; const capped = data["@Microsoft.Dynamics.CRM.totalrecordcountlimitexceeded"] === true; return { total: capped ? null : (data["@odata.count"] ?? rows.length), totalCapped: capped, returned: rows.length, records: rows }; }'}]},dynamics365_business_central:{bundleId:"dynamics365_business_central",templateId:"dynamics365_business_central",systemId:"dynamics365_business_central",displayName:"Dynamics 365 Business Central",description:"Read companies, customers, vendors and the chart of accounts from Business Central.",systemUrl:"https://api.businesscentral.dynamics.com/v2.0/<<environment>>/api/v2.0",credentialHint:"Connect your Business Central environment. Your assistant walks you through it.",requiredCredentialKeys:["environment","access_token"],mcpServer:{name:"business-central",displayName:"Dynamics 365 Business Central",description:"Companies, customers, vendors, chart of accounts and ad-hoc entity queries from Business Central."},installMcpServer:!0,agentLaunch:{userPrompt:"I just installed the Dynamics 365 Business Central bundle. What can I do with it?",nextSteps:"Your first reply must be short: one line confirming the Business Central MCP server is installed, then collect the credentials. Use set_credentials for this system to collect environment (their BC environment name, usually production or sandbox) and access_token; never send the user to the Credentials page and never accept secrets as chat text. Fastest token: az account get-access-token --resource https://api.businesscentral.dynamics.com. Once saved, the MCP server is ready; run the companies tool as the test, because its result contains the company id every other tool needs. Do not list the installed tools, do not add tips unless asked. If asked later: tokens expire after about an hour, so a 401 means refresh access_token; the query tool accepts any Business Central entity set like items or salesInvoices."},tools:[{id:"business-central-list-companies",name:"List Business Central companies",shortName:"Companies",instruction:"Lists the companies in the Business Central environment. Run this first: every other Business Central tool needs a companyId from this list.",inputSchema:{type:"object",properties:{},additionalProperties:!0},steps:[{id:"fetchCompanies",instruction:"Fetch the companies in this environment.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"}}}],outputTransform:"(sourceData) => { const rows = sourceData.fetchCompanies?.data?.value ?? []; return { total: rows.length, companies: rows.map((r) => ({ companyId: r.id, name: r.name, displayName: r.displayName })) }; }"},{id:"business-central-list-customers",name:"List Business Central customers",shortName:"Customers",instruction:"Lists customer master records from a Business Central company. Requires a companyId from the companies tool. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:`Optional OData $filter expression, e.g. "blocked ne ''" or "contains(displayName,'GmbH')".`},maxResults:{type:"integer",description:"Maximum number of customers to return in one call. Defaults to 100."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchCustomers",instruction:"Fetch customers for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/customers",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,number,displayName,email,phoneNumber,blocked,lastModifiedDateTime",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchCustomers?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, customers: rows.map((r) => ({ id: r.id, number: r.number, name: r.displayName, email: r.email, phone: r.phoneNumber, blocked: r.blocked, lastModified: r.lastModifiedDateTime })) }; }'},{id:"business-central-list-vendors",name:"List Business Central vendors",shortName:"Vendors",instruction:"Lists vendor master records from a Business Central company. Requires a companyId from the companies tool. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:"Optional OData $filter expression."},maxResults:{type:"integer",description:"Maximum number of vendors to return in one call. Defaults to 100."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchVendors",instruction:"Fetch vendors for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/vendors",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,number,displayName,email,phoneNumber,blocked,lastModifiedDateTime",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchVendors?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, vendors: rows.map((r) => ({ id: r.id, number: r.number, name: r.displayName, email: r.email, phone: r.phoneNumber, blocked: r.blocked, lastModified: r.lastModifiedDateTime })) }; }'},{id:"business-central-list-accounts",name:"List Business Central chart of accounts",shortName:"Chart of accounts",instruction:"Lists general ledger accounts (the chart of accounts) from a Business Central company. Requires a companyId from the companies tool. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:`Optional OData $filter expression, e.g. "category eq 'Assets'".`},maxResults:{type:"integer",description:"Maximum number of accounts to return in one call. Defaults to 200."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchAccounts",instruction:"Fetch general ledger accounts for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/accounts",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,number,displayName,category,subCategory,blocked,accountType",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 200>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchAccounts?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, accounts: rows.map((r) => ({ id: r.id, number: r.number, name: r.displayName, category: r.category, subCategory: r.subCategory, type: r.accountType, blocked: r.blocked })) }; }'},{id:"business-central-list-items",name:"List Business Central items",shortName:"Items",instruction:"Lists item (product) master records from a Business Central company. Requires a companyId from the companies tool. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:`Optional OData $filter expression, e.g. "type eq 'Inventory'".`},maxResults:{type:"integer",description:"Maximum number of items to return in one call. Defaults to 100."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchItems",instruction:"Fetch items for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/items",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,number,displayName,type,unitPrice,inventory,blocked,lastModifiedDateTime",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchItems?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, items: rows.map((r) => ({ id: r.id, number: r.number, name: r.displayName, type: r.type, unitPrice: r.unitPrice, inventory: r.inventory, blocked: r.blocked })) }; }'},{id:"business-central-list-sales-invoices",name:"List Business Central sales invoices",shortName:"Sales invoices",instruction:"Lists sales invoices from a Business Central company with customer, total and status. Requires a companyId from the companies tool. Supports an optional OData $filter.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:`Optional OData $filter expression, e.g. "status eq 'Open'".`},maxResults:{type:"integer",description:"Maximum number of invoices to return in one call. Defaults to 100."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchSalesInvoices",instruction:"Fetch sales invoices for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/salesInvoices",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,number,customerName,invoiceDate,totalAmountIncludingTax,currencyCode,status",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchSalesInvoices?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, invoices: rows.map((r) => ({ id: r.id, number: r.number, customer: r.customerName, date: r.invoiceDate, total: r.totalAmountIncludingTax, currency: r.currencyCode, status: r.status })) }; }'},{id:"business-central-list-gl-entries",name:"List Business Central general ledger entries",shortName:"GL entries",instruction:"Lists general ledger entries from a Business Central company with account, amounts and posting date. Requires a companyId from the companies tool. Filter by postingDate to verify opening balances at cutover.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},filter:{type:"string",description:'Optional OData $filter expression, e.g. "postingDate ge 2026-01-01".'},maxResults:{type:"integer",description:"Maximum number of entries to return in one call. Defaults to 200."}},required:["companyId"],additionalProperties:!0},steps:[{id:"fetchGLEntries",instruction:"Fetch general ledger entries for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/generalLedgerEntries",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"id,entryNumber,postingDate,documentNumber,accountNumber,description,debitAmount,creditAmount",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 200>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.fetchGLEntries?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, entries: rows.map((r) => ({ entryNumber: r.entryNumber, postingDate: r.postingDate, document: r.documentNumber, account: r.accountNumber, description: r.description, debit: r.debitAmount, credit: r.creditAmount })) }; }'},{id:"business-central-query-entity",name:"Query any Business Central entity",shortName:"Query any entity",instruction:"Queries any Business Central entity set by name (for example items, salesInvoices, generalLedgerEntries) within a company, with optional OData $select and $filter. The workhorse tool for migration validation beyond the prebuilt lists.",inputSchema:{type:"object",properties:{companyId:{type:"string",description:"Company id (GUID) from the companies tool."},entitySet:{type:"string",description:'Business Central entity set name, e.g. "items", "salesInvoices", "generalLedgerEntries".'},select:{type:"string",description:"Comma-separated OData $select field list. Omit for all fields."},filter:{type:"string",description:"Optional OData $filter expression."},maxResults:{type:"integer",description:"Maximum number of records to return in one call. Defaults to 100."}},required:["companyId","entitySet"],additionalProperties:!0},steps:[{id:"queryEntity",instruction:"Query the requested entity set for the given company.",config:{type:"request",systemId:"dynamics365_business_central",url:"https://api.businesscentral.dynamics.com/v2.0/<<dynamics365_business_central_environment>>/api/v2.0/companies(<<companyId>>)/<<entitySet>>",method:"GET",headers:{Authorization:"Bearer <<dynamics365_business_central_access_token>>",Accept:"application/json","Data-Access-Intent":"ReadOnly"},queryParams:{$select:"<<select>>",$filter:"<<filter>>",$top:"<<(p) => p.maxResults ?? 100>>",$count:"true"}}}],outputTransform:'(sourceData) => { const data = sourceData.queryEntity?.data ?? {}; const rows = data.value ?? []; return { total: data["@odata.count"] ?? rows.length, records: rows }; }'}]},netsuite:{bundleId:"netsuite",templateId:"netsuite",systemId:Qd,displayName:"NetSuite",description:"Install a NetSuite system, ten read/query tools, fourteen write tools and a native integration playbook.",systemUrl:"https://{accountId}.suitetalk.api.netsuite.com/services/rest",credentialHint:"Connects through your own NetSuite integration record with OAuth 2.0. Your assistant asks for the account ID and the integration record's client ID and secret, then opens the NetSuite sign-in.",requiredCredentialKeys:["access_token"],oauthSignIn:!0,mcpServer:{name:"netsuite",displayName:"NetSuite",description:"Chart of accounts, customers, vendors, journal entries, invoices, vendor bills, subsidiaries and dimensions from NetSuite, SuiteQL queries and record lookups, plus create and update tools for journal entries, vendors, customers, GL accounts, invoices, vendor bills and departments."},installMcpServer:!1,playbook:{id:"netsuite-native-integration",name:"NetSuite Native Integration",whenToRun:"Use when connecting, validating, querying or extending a NetSuite integration through REST Web Services and SuiteQL.",inputs:"A configured NetSuite system with an OAuth sign-in; the record type or business process to work with; subsidiary scope for OneWorld accounts; validation criteria and desired output.",instructions:"Use the installed read-only tools for the chart of accounts, customers, vendors, journal entry lines, invoices, vendor bills, departments, subsidiaries, classes and locations. Use the SuiteQL query tool for any other record type, join or aggregate, and the get-record tool to inspect one record in full. Use the installed create and update tools for journal entries, vendors, customers, GL accounts, invoices, vendor bills and departments only after the user explicitly confirms the exact records to write; the create tools are not idempotent and re-running them duplicates records. Reference other records by internal ID from the list tools, and pass a subsidiary on OneWorld accounts. Surface NetSuite error details (o:errorDetails) as failures. For other record types or operations, inspect the account's metadata catalog, create separate least-privilege tools, validate them in a sandbox account and require explicit user confirmation before modifying NetSuite data.",completionCriteria:"The requested NetSuite data, write result or validation result is returned; subsidiary scope is correct; NetSuite errors are surfaced as failures with their details; no NetSuite data is modified unless the user explicitly requested and confirmed the write."},agentLaunch:{userPrompt:"I just installed the NetSuite integration. What can I do with it?",nextSteps:'Your first reply must be short: one line confirming the NetSuite integration and native integration playbook are installed. If the system already has a NetSuite sign-in for this user, offer one read-only test run and stop. Otherwise connect it in this order. 1) Ask in chat for the NetSuite account ID (Setup > Company > Company Information, like 1234567 or 1234567_SB1 for a sandbox; it is not a secret). 2) Build the host from it in lowercase with "_" replaced by "-" (1234567_SB1 becomes 1234567-sb1) and edit the system: url https://<host>.suitetalk.api.netsuite.com/services/rest, authentication type oauth2 with oauthClientMode custom, authUrl https://<host>.app.netsuite.com/app/login/oauth2/authorize.nl and tokenUrl https://<host>.suitetalk.api.netsuite.com/services/rest/auth/oauth2/v1/token. Read the system back and confirm no {accountId} remains; never start OAuth while it does. 3) Ask for the client ID and client secret of their NetSuite integration record in chat and store them in the system authentication. If they have no integration record yet, explain: Setup > Integration > Manage Integrations > New, enable Authorization Code Grant with the REST Web Services and RESTlets scopes, set the redirect URI to the superglue OAuth callback URL exactly, and copy the client ID and secret shown once after saving; the NetSuite role needs REST Web Services and Log in using OAuth 2.0 Access Tokens permissions. 4) Run authenticate_oauth for this system. OAuth fills access_token; never ask for a token as chat text and never send the user to the Credentials page. Once connected, the integration is ready; offer one read-only test run. Do not list the installed tools or add tips unless asked. If asked later: the sign-in lasts seven days and a 401 means signing in again; the SuiteQL tool reads any record type; the installed create and update tools modify NetSuite data, so run them only after the user confirms the exact records to write.'},tools:TAe}};Fn.bundles={...Ab,sage_intacct_mcp:{...Ab.sage_intacct,bundleId:"sage_intacct_mcp",description:"Install the Sage Intacct integration and an OAuth-protected MCP server for its read/query and write tools.",installMcpServer:!0},netsuite_mcp:{...Ab.netsuite,bundleId:"netsuite_mcp",description:"Install the NetSuite integration and an OAuth-protected MCP server for its read/query and write tools.",installMcpServer:!0}};function RAe({bundle:t,install:e}){let r=e.tools.map(s=>` - ${s.id}${s.name?` (${s.name})`:""}`).join(`
81
81
  `),n=e.system.requiredCredentialKeys.join(", "),i=e.mcpServer?[` - MCP server: ${e.mcpServer.name} (id: ${e.mcpServer.id})`,"","Silently load the systems and tool-deployment skills before replying. Do not narrate the skill loads.","","The MCP server card is already visible in this conversation with the server URL, its tools, and the client export options for Claude, Cursor, Langdock and curl. Do not describe or reproduce client setup in prose; point at the card."]:["","Silently load the systems skill before replying. Do not narrate the skill load."],o=[`The user just installed the "${t.displayName}" ${e.mcpServer?"MCP server and integration":"integration"} from the superglue website. Everything below already exists. Do not create, rebuild or duplicate any of it.`,"","Installed:",` - System: ${e.system.id} (${e.system.name}) at ${t.systemUrl}`," - Tools:",r,e.playbook?` - Playbook: ${e.playbook.name} (id: ${e.playbook.id})`:void 0,...i,"",e.system.hasUserCredentials?t.demoCredentials?"The system is preloaded with a shared demo credential, so every tool works right now without any setup.":"The system already has credentials for this user.":`The system does not have a complete credential set yet, so no tool will run until the user adds the missing values. Required credential keys: ${n}. ${t.credentialHint}`,t.agentLaunch.nextSteps,"","The user already saw this inventory on the install screen. Do not repeat it back to them."];return{userPrompt:t.agentLaunch.userPrompt,hiddenStarterMessage:o.filter(s=>s!==void 0).join(`
82
- `)}}function kAe(t){return typeof t!="string"||!Object.prototype.hasOwnProperty.call(Fn.bundles,t)?null:Fn.bundles[t]}function NAe(){return Object.values(Fn.bundles)}function OAe({tool:t,fromSystemId:e,toSystemId:r}){if(e===r)return t;let n=i=>typeof i=="string"?i.split(`${e}_`).join(`${r}_`):Array.isArray(i)?i.map(n):i&&typeof i=="object"?Object.fromEntries(Object.entries(i).map(([o,s])=>[o,n(s)])):i;return{...t,steps:t.steps.map(i=>{let o=n(i.config);return(0,EAe.isRequestConfig)(o)&&o.systemId===e&&(o.systemId=r),{...i,config:o}}),outputTransform:n(t.outputTransform)}}});var ix=m(ko=>{"use strict";var UAe=ko&&ko.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),MAe=ko&&ko.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xAe=ko&&ko.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&UAe(r,e,n[i]);return MAe(r,e),r}})();Object.defineProperty(ko,"__esModule",{value:!0});ko.applyDiffsToConfig=$Ae;var LAe=xAe(require("fast-json-patch")),PAe=cp(),FAe=ln();function $Ae(t,e){if(!e?.length)return t;let r=JSON.parse(JSON.stringify(t)),n=(0,PAe.normalizeToolSchemas)(r),i=(0,FAe.normalizeToolDiffs)(e);return LAe.applyPatch(n,i,!0,!0).newDocument||n}});var ox=m(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.MCP_TOOL_GRANT_PARAM=Xi.MCP_TOOL_GRANT_SCOPE=Xi.MCP_OAUTH_REFRESH_TOKEN_EXPIRES_IN_SECONDS=Xi.MCP_OAUTH_ACCESS_TOKEN_EXPIRES_IN_SECONDS=void 0;Xi.MCP_OAUTH_ACCESS_TOKEN_EXPIRES_IN_SECONDS=3600;Xi.MCP_OAUTH_REFRESH_TOKEN_EXPIRES_IN_SECONDS=3600*24*365;Xi.MCP_TOOL_GRANT_SCOPE="superglue:mcp:new";Xi.MCP_TOOL_GRANT_PARAM="mcp_tool_grant"});var sx=m(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.MAX_LOGO_SIZE_BYTES=nt.MAX_API_REQUEST_BODY_BYTES=nt.MAX_SESSION_ARTIFACT_BYTES=nt.MAX_TOOL_RESULT_BYTES=nt.MAX_UPLOAD_FILES_PER_BATCH=nt.MAX_QBM_UPLOAD_FILE_BYTES=nt.MAX_UPLOAD_FILE_BYTES=nt.MAX_INLINE_FILE_BASE64_BYTES=nt.V8_MAX_STRING_CHARS=void 0;nt.maxSessionUploadBytes=jAe;nt.V8_MAX_STRING_CHARS=536870888;nt.MAX_INLINE_FILE_BASE64_BYTES=375*1024*1024;nt.MAX_UPLOAD_FILE_BYTES=50*1024*1024;nt.MAX_QBM_UPLOAD_FILE_BYTES=200*1024*1024;function jAe(t){return/\.qbm$/i.test(t)?nt.MAX_QBM_UPLOAD_FILE_BYTES:nt.MAX_UPLOAD_FILE_BYTES}nt.MAX_UPLOAD_FILES_PER_BATCH=10;nt.MAX_TOOL_RESULT_BYTES=500*1024*1024;nt.MAX_SESSION_ARTIFACT_BYTES=nt.MAX_TOOL_RESULT_BYTES;nt.MAX_API_REQUEST_BODY_BYTES=500*1024*1024;nt.MAX_LOGO_SIZE_BYTES=10*1024*1024});var mb=m(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.RUN_LIST_EXECUTION_KINDS=ft.RUN_LIST_STATUSES=ft.FILE_RESOURCE_SOURCES=ft.LIST_MAX_SEARCH_LENGTH=ft.LIST_MAX_LIMIT=ft.LIST_DEFAULT_LIMIT=ft.LIST_DEFAULT_PAGE=void 0;ft.createListQueryParams=ax;ft.createSearchListQueryParams=qAe;ft.listAllPages=zAe;ft.fileResourceSource=HAe;ft.createListResponse=GAe;var gb=dr();ft.LIST_DEFAULT_PAGE=1;ft.LIST_DEFAULT_LIMIT=1e3;ft.LIST_MAX_LIMIT=1e3;ft.LIST_MAX_SEARCH_LENGTH=200;function ax(t){let e=new URLSearchParams;return t.page!==void 0&&e.set("page",String(t.page)),t.limit!==void 0&&e.set("limit",String(t.limit)),e}function qAe(t){let e=ax(t);return t.search!==void 0&&e.set("search",t.search),e}async function zAe(t){let e=[];for(let r=1;;r+=1){let n=await t(r,ft.LIST_MAX_LIMIT);if(e.push(...n.data),!n.hasMore||n.data.length===0)return e}}ft.FILE_RESOURCE_SOURCES=["upload","task","system","playbook"];function HAe(t){return t.origin?t.origin.type:t.tasks.length>0?"task":"upload"}ft.RUN_LIST_STATUSES=["running","success","failed","aborted"];ft.RUN_LIST_EXECUTION_KINDS=[gb.RunExecutionKind.FULL,gb.RunExecutionKind.DRAFT,gb.RunExecutionKind.SINGLE_STEP];function GAe({data:t,page:e,limit:r,total:n}){return{data:t,page:e,limit:r,total:n,hasMore:(e-1)*r+t.length<n}}});var cx=m(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.AGENT_SESSION_EMAIL_LOGO_CID=void 0;mn.emailTemplate=wa;mn.buildPasswordResetEmail=VAe;mn.buildOrgInvitationEmail=JAe;mn.buildOrgLoginEmail=WAe;mn.buildAgentSessionEmail=KAe;mn.buildArtifactSubmissionEmail=XAe;mn.buildResourceShareEmail=epe;var YAe="https://superglue.cloud/logos/sg_logo.png";function Ze(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function wa({body:t}){return`<!doctype html>
82
+ `)}}function kAe(t){return typeof t!="string"||!Object.prototype.hasOwnProperty.call(Fn.bundles,t)?null:Fn.bundles[t]}function NAe(){return Object.values(Fn.bundles)}function OAe({tool:t,fromSystemId:e,toSystemId:r}){if(e===r)return t;let n=i=>typeof i=="string"?i.split(`${e}_`).join(`${r}_`):Array.isArray(i)?i.map(n):i&&typeof i=="object"?Object.fromEntries(Object.entries(i).map(([o,s])=>[o,n(s)])):i;return{...t,steps:t.steps.map(i=>{let o=n(i.config);return(0,EAe.isRequestConfig)(o)&&o.systemId===e&&(o.systemId=r),{...i,config:o}}),outputTransform:n(t.outputTransform)}}});var ix=m(ko=>{"use strict";var UAe=ko&&ko.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),MAe=ko&&ko.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xAe=ko&&ko.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),i=0;i<n.length;i++)n[i]!=="default"&&UAe(r,e,n[i]);return MAe(r,e),r}})();Object.defineProperty(ko,"__esModule",{value:!0});ko.applyDiffsToConfig=$Ae;var LAe=xAe(require("fast-json-patch")),PAe=cp(),FAe=ln();function $Ae(t,e){if(!e?.length)return t;let r=JSON.parse(JSON.stringify(t)),n=(0,PAe.normalizeToolSchemas)(r),i=(0,FAe.normalizeToolDiffs)(e);return LAe.applyPatch(n,i,!0,!0).newDocument||n}});var ox=m(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.MCP_TOOL_GRANT_PARAM=Xi.MCP_TOOL_GRANT_SCOPE=Xi.MCP_OAUTH_REFRESH_TOKEN_EXPIRES_IN_SECONDS=Xi.MCP_OAUTH_ACCESS_TOKEN_EXPIRES_IN_SECONDS=void 0;Xi.MCP_OAUTH_ACCESS_TOKEN_EXPIRES_IN_SECONDS=3600;Xi.MCP_OAUTH_REFRESH_TOKEN_EXPIRES_IN_SECONDS=3600*24*365;Xi.MCP_TOOL_GRANT_SCOPE="superglue:mcp:new";Xi.MCP_TOOL_GRANT_PARAM="mcp_tool_grant"});var sx=m(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.MAX_LOGO_SIZE_BYTES=nt.MAX_API_REQUEST_BODY_BYTES=nt.MAX_SESSION_ARTIFACT_BYTES=nt.MAX_TOOL_RESULT_BYTES=nt.MAX_UPLOAD_FILES_PER_BATCH=nt.MAX_QBM_UPLOAD_FILE_BYTES=nt.MAX_UPLOAD_FILE_BYTES=nt.MAX_INLINE_FILE_BASE64_BYTES=nt.V8_MAX_STRING_CHARS=void 0;nt.maxUploadFileBytes=jAe;nt.V8_MAX_STRING_CHARS=536870888;nt.MAX_INLINE_FILE_BASE64_BYTES=375*1024*1024;nt.MAX_UPLOAD_FILE_BYTES=50*1024*1024;nt.MAX_QBM_UPLOAD_FILE_BYTES=200*1024*1024;function jAe(t){return/\.qbm$/i.test(t)?nt.MAX_QBM_UPLOAD_FILE_BYTES:nt.MAX_UPLOAD_FILE_BYTES}nt.MAX_UPLOAD_FILES_PER_BATCH=10;nt.MAX_TOOL_RESULT_BYTES=500*1024*1024;nt.MAX_SESSION_ARTIFACT_BYTES=nt.MAX_TOOL_RESULT_BYTES;nt.MAX_API_REQUEST_BODY_BYTES=500*1024*1024;nt.MAX_LOGO_SIZE_BYTES=10*1024*1024});var mb=m(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.RUN_LIST_EXECUTION_KINDS=ft.RUN_LIST_STATUSES=ft.FILE_RESOURCE_SOURCES=ft.LIST_MAX_SEARCH_LENGTH=ft.LIST_MAX_LIMIT=ft.LIST_DEFAULT_LIMIT=ft.LIST_DEFAULT_PAGE=void 0;ft.createListQueryParams=ax;ft.createSearchListQueryParams=qAe;ft.listAllPages=zAe;ft.fileResourceSource=HAe;ft.createListResponse=GAe;var gb=dr();ft.LIST_DEFAULT_PAGE=1;ft.LIST_DEFAULT_LIMIT=1e3;ft.LIST_MAX_LIMIT=1e3;ft.LIST_MAX_SEARCH_LENGTH=200;function ax(t){let e=new URLSearchParams;return t.page!==void 0&&e.set("page",String(t.page)),t.limit!==void 0&&e.set("limit",String(t.limit)),e}function qAe(t){let e=ax(t);return t.search!==void 0&&e.set("search",t.search),e}async function zAe(t){let e=[];for(let r=1;;r+=1){let n=await t(r,ft.LIST_MAX_LIMIT);if(e.push(...n.data),!n.hasMore||n.data.length===0)return e}}ft.FILE_RESOURCE_SOURCES=["upload","task","system","playbook"];function HAe(t){return t.origin?t.origin.type:t.tasks.length>0?"task":"upload"}ft.RUN_LIST_STATUSES=["running","success","failed","aborted"];ft.RUN_LIST_EXECUTION_KINDS=[gb.RunExecutionKind.FULL,gb.RunExecutionKind.DRAFT,gb.RunExecutionKind.SINGLE_STEP];function GAe({data:t,page:e,limit:r,total:n}){return{data:t,page:e,limit:r,total:n,hasMore:(e-1)*r+t.length<n}}});var cx=m(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.AGENT_SESSION_EMAIL_LOGO_CID=void 0;mn.emailTemplate=wa;mn.buildPasswordResetEmail=VAe;mn.buildOrgInvitationEmail=JAe;mn.buildOrgLoginEmail=WAe;mn.buildAgentSessionEmail=KAe;mn.buildArtifactSubmissionEmail=XAe;mn.buildResourceShareEmail=epe;var YAe="https://superglue.cloud/logos/sg_logo.png";function Ze(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function wa({body:t}){return`<!doctype html>
83
83
  <html lang="en">
84
84
  <body style="margin:0;padding:0;background:#f6f6f6;font-family:Inter,-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;color:#111111;">
85
85
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#f6f6f6;padding:28px 16px;">
@@ -1768,9 +1768,9 @@ ${e.format(r)}`.trim())}};hj.exports=pQ});var hQ=m((_xe,Ej)=>{"use strict";var{I
1768
1768
  ${s}`;return}if(Cy(e,i,KTe)){XTe(e,o)&&(r.retry=e.toString("utf8",o));return}if(Cy(e,i,ZTe)){eRe(e,o)&&(r.id=e.toString("utf8",o));return}if(Cy(e,i,WTe)){let s=e.toString("utf8",o);s.length>0&&(r.event=s)}}processEvent(e){e.retry&&HTe(e.retry)&&(this.state.reconnectionTime=parseInt(e.retry,10)),e.id!==void 0&&GTe(e.id)&&(this.state.lastEventId=e.id),e.data!==void 0&&this.push({type:e.event||"message",options:{data:e.data,lastEventId:this.state.lastEventId,origin:this.state.origin}})}clearEvent(){this.event.data=void 0,this.event.event=void 0,this.event.id=void 0,this.event.retry=void 0}hasPendingEvent(){return this.event.data!==void 0||this.event.event!==void 0||this.event.id!==void 0||this.event.retry!==void 0}hasCurrentByte(){return this.chunkIndex<this.chunks.length&&this.pos<this.chunks[this.chunkIndex].length}currentByte(){return this.chunks[this.chunkIndex][this.pos]}consumeCurrentByte(){this.advanceCursor(),this.syncLineStartToCursor()}advanceCursor(){for(this.pos++;this.chunkIndex<this.chunks.length&&this.pos>=this.chunks[this.chunkIndex].length;)this.chunkIndex++,this.pos=0}syncLineStartToCursor(){this.lineChunkIndex=this.chunkIndex,this.linePos=this.pos,this.dropConsumedChunks()}dropConsumedChunks(){for(;this.lineChunkIndex>0;)this.chunks.shift(),this.lineChunkIndex--,this.chunkIndex--;this.chunkIndex===this.chunks.length&&(this.chunks.length=0,this.chunkIndex=0,this.pos=0,this.lineChunkIndex=0,this.linePos=0)}readLine(){if(this.lineChunkIndex===this.chunkIndex)return this.chunks[this.chunkIndex].subarray(this.linePos,this.pos);let e=[],r=0;for(let n=this.lineChunkIndex;n<=this.chunkIndex;n++){let i=this.chunks[n],o=n===this.lineChunkIndex?this.linePos:0,s=n===this.chunkIndex?this.pos:i.length,a=i.subarray(o,s);r+=a.length,e.push(a)}return Buffer.concat(e,r)}peekBufferedByte(e){let r=this.lineChunkIndex,n=this.linePos;for(;r<this.chunks.length;){let i=this.chunks[r],o=i.length-n;if(e<o)return i[n+e];e-=o,r++,n=0}}discardLeadingBytes(e){for(;e>0&&this.lineChunkIndex<this.chunks.length;){let n=this.chunks[this.lineChunkIndex].length-this.linePos;e<n?(this.linePos+=e,e=0):(e-=n,this.lineChunkIndex++,this.linePos=0)}this.chunkIndex=this.lineChunkIndex,this.pos=this.linePos,this.dropConsumedChunks()}handleBOM(){let e=this.peekBufferedByte(0),r=this.peekBufferedByte(1),n=this.peekBufferedByte(2);return r===void 0?(e===Hu[0]||(this.checkBOM=!1),!0):n===void 0?e===Hu[0]&&r===Hu[1]?!0:(this.checkBOM=!1,!1):(e===Hu[0]&&r===Hu[1]&&n===Hu[2]&&this.discardLeadingBytes(3),this.checkBOM=!1,!this.hasCurrentByte())}};nG.exports={EventSourceStream:Mv}});var AG=m((bLe,dG)=>{"use strict";var{pipeline:tRe}=require("stream"),{fetching:rRe}=OA(),{makeRequest:nRe}=Uu(),{webidl:cr}=Ft(),{EventSourceStream:iRe}=iG(),{parseMIMEType:oRe}=In(),{createFastMessageEvent:sRe}=uy(),{isNetworkError:oG}=RA(),{kEnumerableProperty:pc}=ye(),{environmentSettingsObject:sG}=jr(),aG=!1,cG=3e3,$A=0,uG=1,jA=2,aRe="anonymous",cRe="use-credentials",Gu=class t extends EventTarget{#e={open:null,error:null,message:null};#t;#n=!1;#i=$A;#o=null;#r=null;#c;#s;constructor(e,r={}){super(),cr.util.markAsUncloneable(this);let n="EventSource constructor";cr.argumentLengthCheck(arguments,1,n),aG||(aG=!0,process.emitWarning("EventSource is experimental, expect them to change at any time.",{code:"UNDICI-ES"})),e=cr.converters.USVString(e),r=cr.converters.EventSourceInitDict(r,n,"eventSourceInitDict"),this.#c=r.node.dispatcher||r.dispatcher,this.#s={lastEventId:"",reconnectionTime:r.node.reconnectionTime};let i=sG,o;try{o=new URL(e,i.settingsObject.baseUrl),this.#s.origin=o.origin}catch(c){throw new DOMException(c,"SyntaxError")}this.#t=o.href;let s=aRe;r.withCredentials===!0&&(s=cRe,this.#n=!0);let a={redirect:"follow",keepalive:!0,mode:"cors",credentials:s==="anonymous"?"same-origin":"omit",referrer:"no-referrer"};a.client=sG.settingsObject,a.headersList=[["accept",{name:"accept",value:"text/event-stream"}]],a.cache="no-store",a.initiator="other",a.urlList=[new URL(this.#t)],this.#o=nRe(a),this.#a()}get readyState(){return this.#i}get url(){return this.#t}get withCredentials(){return this.#n}#a(){if(this.#i===jA)return;this.#i=$A;let e={request:this.#o,dispatcher:this.#c},r=n=>{if(!oG(n))return this.#u()};e.processResponseEndOfBody=r,e.processResponse=n=>{if(oG(n))if(n.aborted){this.close(),this.dispatchEvent(new Event("error"));return}else{this.#u();return}let i=n.headersList.get("content-type",!0),o=i!==null?oRe(i):"failure",s=o!=="failure"&&o.essence==="text/event-stream";if(n.status!==200||s===!1){this.close(),this.dispatchEvent(new Event("error"));return}this.#i=uG,this.dispatchEvent(new Event("open")),this.#s.origin=n.urlList[n.urlList.length-1].origin;let a=new iRe({eventSourceSettings:this.#s,push:c=>{this.dispatchEvent(sRe(c.type,c.options))}});tRe(n.body.stream,a,c=>{c?.aborted===!1&&(this.close(),this.dispatchEvent(new Event("error")))})},this.#r=rRe(e)}#u(){this.#i!==jA&&(this.#i=$A,this.dispatchEvent(new Event("error")),setTimeout(()=>{this.#i===$A&&(this.#s.lastEventId.length&&this.#o.headersList.set("last-event-id",this.#s.lastEventId,!0),this.#a())},this.#s.reconnectionTime)?.unref())}close(){cr.brandCheck(this,t),this.#i!==jA&&(this.#i=jA,this.#r.abort(),this.#o=null)}get onopen(){return this.#e.open}set onopen(e){this.#e.open&&this.removeEventListener("open",this.#e.open);let r=cr.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("open",r),this.#e.open=e):this.#e.open=null}get onmessage(){return this.#e.message}set onmessage(e){this.#e.message&&this.removeEventListener("message",this.#e.message);let r=cr.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("message",r),this.#e.message=e):this.#e.message=null}get onerror(){return this.#e.error}set onerror(e){this.#e.error&&this.removeEventListener("error",this.#e.error);let r=cr.converters.EventHandlerNonNull(e);r!==null?(this.addEventListener("error",r),this.#e.error=e):this.#e.error=null}},lG={CONNECTING:{__proto__:null,configurable:!1,enumerable:!0,value:$A,writable:!1},OPEN:{__proto__:null,configurable:!1,enumerable:!0,value:uG,writable:!1},CLOSED:{__proto__:null,configurable:!1,enumerable:!0,value:jA,writable:!1}};Object.defineProperties(Gu,lG);Object.defineProperties(Gu.prototype,lG);Object.defineProperties(Gu.prototype,{close:pc,onerror:pc,onmessage:pc,onopen:pc,readyState:pc,url:pc,withCredentials:pc});cr.converters.EventSourceInitDict=cr.dictionaryConverter([{key:"withCredentials",converter:cr.converters.boolean,defaultValue:()=>!1},{key:"dispatcher",converter:cr.converters.any},{key:"node",converter:cr.dictionaryConverter([{key:"reconnectionTime",converter:cr.converters["unsigned long"],defaultValue:()=>cG},{key:"dispatcher",converter:cr.converters.any}]),defaultValue:()=>({})}]);dG.exports={EventSource:Gu,defaultReconnectionTime:cG}});var yG=m((SLe,V)=>{"use strict";var uRe=Rs(),fG=Pd(),lRe=Fa(),dRe=K$(),ARe=r1(),pRe=qa(),fRe=gB(),hRe=AB(),gRe=$1(),mRe=V1(),yRe=Z1(),hG=fe(),Sy=ye(),{InvalidArgumentError:by}=hG,Yu=k2(),ERe=Da(),IRe=rQ(),{MockCallHistory:CRe,MockCallHistoryLog:bRe}=oQ(),SRe=fQ(),wRe=uQ(),BRe=Rj(),QRe=PB(),vRe=gm(),{getGlobalDispatcher:gG,setGlobalDispatcher:_Re}=Rm(),DRe=Du(),TRe=bQ();Object.assign(fG.prototype,Yu);V.exports.Dispatcher=fG;V.exports.Client=uRe;V.exports.Pool=lRe;V.exports.BalancedPool=dRe;V.exports.RoundRobinPool=ARe;V.exports.Agent=pRe;V.exports.ProxyAgent=fRe;V.exports.Socks5ProxyAgent=hRe;V.exports.EnvHttpProxyAgent=gRe;V.exports.RetryAgent=mRe;V.exports.H2CClient=yRe;V.exports.RetryHandler=vRe;V.exports.DecoratorHandler=DRe;V.exports.RedirectHandler=TRe;V.exports.interceptors={redirect:jj(),responseError:zj(),retry:Gj(),dump:Jj(),dns:Xj(),cache:Rq(),decompress:xq(),deduplicate:jq()};V.exports.cacheStores={MemoryCacheStore:MQ()};var RRe=Hq();V.exports.cacheStores.SqliteCacheStore=RRe;V.exports.buildConnector=ERe;V.exports.errors=hG;V.exports.util={parseHeaders:Sy.parseHeaders,headerNameToString:Sy.headerNameToString};function qA(t){return(e,r,n)=>{if(typeof r=="function"&&(n=r,r=null),!e||typeof e!="string"&&typeof e!="object"&&!(e instanceof URL))throw new by("invalid url");if(r!=null&&typeof r!="object")throw new by("invalid opts");if(r&&r.path!=null){if(typeof r.path!="string")throw new by("invalid opts.path");let s=r.path;r.path.startsWith("/")||(s=`/${s}`),e=new URL(Sy.parseOrigin(e).origin+s)}else r||(r=typeof e=="object"?e:{}),e=Sy.parseURL(e);let{agent:i,dispatcher:o=gG()}=r;if(i)throw new by("unsupported opts.agent. Did you mean opts.client?");return t.call(o,{...r,origin:e.origin,path:e.search?`${e.pathname}${e.search}`:e.pathname,method:r.method||(r.body?"PUT":"GET")},n)}}V.exports.setGlobalDispatcher=_Re;V.exports.getGlobalDispatcher=gG;var kRe=OA().fetch,pG=typeof __filename<"u"?__filename:void 0;function mG(t,e){if(!t||typeof t!="object")return;let r=typeof t.stack=="string"?t.stack:"",n=e.replace(/\\/g,"/");if(r&&(r.includes(e)||r.includes(n)))return;let i={};if(Error.captureStackTrace(i,mG),!i.stack)return;let o=i.stack.split(`
1769
1769
  `).slice(1).join(`
1770
1770
  `);t.stack=r?`${r}
1771
- ${o}`:i.stack}V.exports.fetch=function(e,r=void 0){return kRe(e,r).catch(n=>{throw pG?mG(n,pG):n&&typeof n=="object"&&Error.captureStackTrace(n,V.exports.fetch),n})};V.exports.Headers=oc().Headers;V.exports.Response=RA().Response;V.exports.Request=Uu().Request;V.exports.FormData=zg().FormData;var{setGlobalOrigin:NRe,getGlobalOrigin:ORe}=ZS();V.exports.setGlobalOrigin=NRe;V.exports.getGlobalOrigin=ORe;var{CacheStorage:URe}=tH(),{kConstruct:MRe}=$e();V.exports.caches=new URe(MRe);var{deleteCookie:xRe,getCookies:LRe,getSetCookies:PRe,setCookie:FRe,parseCookie:$Re}=pH();V.exports.deleteCookie=xRe;V.exports.getCookies=LRe;V.exports.getSetCookies=PRe;V.exports.setCookie=FRe;V.exports.parseCookie=$Re;var{parseMIMEType:jRe,serializeAMimeType:qRe}=In();V.exports.parseMIMEType=jRe;V.exports.serializeAMimeType=qRe;var{CloseEvent:zRe,ErrorEvent:HRe,MessageEvent:GRe}=uy(),{WebSocket:YRe,ping:VRe}=GH();V.exports.WebSocket=YRe;V.exports.CloseEvent=zRe;V.exports.ErrorEvent=HRe;V.exports.MessageEvent=GRe;V.exports.ping=VRe;V.exports.WebSocketStream=eG().WebSocketStream;V.exports.WebSocketError=Rv().WebSocketError;V.exports.request=qA(Yu.request);V.exports.stream=qA(Yu.stream);V.exports.pipeline=qA(Yu.pipeline);V.exports.connect=qA(Yu.connect);V.exports.upgrade=qA(Yu.upgrade);V.exports.MockClient=IRe;V.exports.MockCallHistory=CRe;V.exports.MockCallHistoryLog=bRe;V.exports.MockPool=wRe;V.exports.MockAgent=SRe;V.exports.SnapshotAgent=BRe;V.exports.mockErrors=QRe;var{EventSource:JRe}=AG();V.exports.EventSource=JRe;function WRe(){globalThis.fetch=V.exports.fetch,globalThis.Headers=V.exports.Headers,globalThis.Response=V.exports.Response,globalThis.Request=V.exports.Request,globalThis.FormData=V.exports.FormData,globalThis.WebSocket=V.exports.WebSocket,globalThis.CloseEvent=V.exports.CloseEvent,globalThis.ErrorEvent=V.exports.ErrorEvent,globalThis.MessageEvent=V.exports.MessageEvent,globalThis.EventSource=V.exports.EventSource}V.exports.install=WRe});var IG=m(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});Ju.SuperglueClient=Ju.SuperglueHttpError=void 0;var Vu=dr(),Dn=mb(),ZRe=Yb(),KRe=RL(),XRe=ln(),Vo=Lc(),eke=Xl(),HA=14400*1e3,zA;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:t}=yG();zA=new t({headersTimeout:HA,bodyTimeout:HA})}catch{}function EG(t){if(t?.aborted)throw t.reason??new DOMException("Aborted","AbortError")}var wy=class extends Error{constructor(e,r,n,i){super(e),this.status=r,this.code=n,this.details=i,this.name="SuperglueHttpError"}};Ju.SuperglueHttpError=wy;var xv=class{constructor({apiKey:e,apiEndpoint:r,onInfrastructureError:n,refreshToken:i,sseTokenProvider:o,tokenProvider:s}){if(!e&&!s)throw new Error("SuperglueClient requires either apiKey or tokenProvider");this.tokenProvider=s??(async()=>e),this.apiEndpoint=r??"https://api.superglue.cloud",this.sseManager=new ZRe.SSELogSubscriptionManager(this.apiEndpoint,o??this.tokenProvider,i),this.onInfrastructureError=n,this.refreshToken=i}async getApiKey(){return this.tokenProvider()}async fetchWithAuthRetry(e,r){let n=await this.getApiKey(),i=await e(n);if(i.status!==401||!this.refreshToken)return i;EG(r);let o=await this.refreshToken();return EG(r),!o||o===n?i:(i.body?.cancel(),e(o))}isInfrastructureError(e){return(0,XRe.isAbortError)(e)?!1:!!(e instanceof TypeError&&e.message.toLowerCase().includes("fetch")||e instanceof Error&&e.name==="TimeoutError")}async restRequest(e,r,n,i,o){let a=await(await this.restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o})).text();if(a)return JSON.parse(a)}async restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o}){let s=`${this.apiEndpoint.replace(/\/$/,"")}${r}`,a=n!=null,c=typeof FormData<"u"&&n instanceof FormData,u=d=>{let A={Authorization:`Bearer ${d}`,...i};return a&&!c&&e!=="GET"&&(A["Content-Type"]="application/json"),fetch(s,{...o,method:e,headers:A,body:a?c?n:JSON.stringify(n):void 0,signal:o?.signal??AbortSignal.timeout(HA),...zA?{dispatcher:zA}:{}})},l;try{l=await this.fetchWithAuthRetry(u,o?.signal)}catch(d){throw this.isInfrastructureError(d)&&this.onInfrastructureError?.(),d}if(!l.ok)throw await this.buildHttpError(l);return l}async uploadFiles(e,r){if(typeof r?.process!="boolean")throw new Error("process must be a boolean");if(e.length===0)return[];let n=e.map(l=>({...l,contentLength:l.contentLength??this.getUploadContentLength(l.content)})),o=(await this.restRequest("POST","/v1/files/uploads",{process:r.process,files:n.map(({fileName:l,contentType:d,contentLength:A})=>({fileName:l,contentLength:A,...d?{contentType:d}:{}}))})).data.files;if(o.length!==n.length)throw await Promise.all(o.map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),new Error("Upload response did not match the selected files");let s=await Promise.allSettled(o.map(async(l,d)=>{let A=n[d],p=await fetch(l.uploadUrl,{method:"PUT",body:A.content,headers:A.contentType?{"Content-Type":A.contentType}:void 0,signal:AbortSignal.timeout(Math.min(HA,l.expiresIn*1e3))});if(!p.ok)throw new Error(`Upload failed for ${A.fileName}: ${p.status} ${p.statusText}`);return l.id})),a=s.flatMap(l=>l.status==="fulfilled"?[l.value]:[]),c=new Map;if(a.length>0)try{let l=await this.restRequest("POST","/v1/files/uploads/complete",{fileIds:a});c=new Map(l.data.files.map(d=>[d.id,d]))}catch(l){c=new Map(a.map(d=>[d,{id:d,fileName:n[o.findIndex(A=>A.id===d)]?.fileName||d,contentLength:n[o.findIndex(A=>A.id===d)]?.contentLength||0,status:"failed",error:l instanceof Error?l.message:String(l)}]))}let u=o.map((l,d)=>{let A=s[d],p=n[d];return A.status==="rejected"?{id:l.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:A.reason instanceof Error?A.reason.message:String(A.reason)}:c.get(l.id)||{id:l.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:"Upload completion returned no result"}});return await Promise.all(u.filter(l=>l.status==="failed").map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),u}async deleteFileUpload(e){await this.restRequest("DELETE",`/v1/files/uploads/${encodeURIComponent(e)}`)}getUploadContentLength(e){return typeof e=="string"?new TextEncoder().encode(e).byteLength:e instanceof Uint8Array?e.byteLength:e.size}async buildHttpError(e){e.status>=500&&this.onInfrastructureError?.();let r=await e.text(),n=`HTTP ${e.status}: ${r}`,i,o;try{let s=JSON.parse(r);s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),typeof s?.code=="string"&&(i=s.code);let a=s.error;typeof a=="string"?n=a:a&&typeof a=="object"&&(n=a.message||JSON.stringify(a))}catch{}return new wy(n,e.status,i,o)}async streamRequest(e,r,n){let i=e.includes("?")?"&":"?",o=`${this.apiEndpoint.replace(/\/$/,"")}${e}${i}stream=true`,s=u=>fetch(o,{method:"POST",headers:{Authorization:`Bearer ${u}`,Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(r),signal:n??AbortSignal.timeout(HA),...zA?{dispatcher:zA}:{}}),a;try{a=await this.fetchWithAuthRetry(s,n)}catch(u){throw this.isInfrastructureError(u)&&this.onInfrastructureError?.(),u}if(!a.ok)throw await this.buildHttpError(a);if(!(a.headers.get("content-type")||"").includes("text/event-stream")){let u=await a.text();return u?JSON.parse(u):void 0}try{return await(0,KRe.consumeEventStreamResult)(a)}catch(u){throw this.isInfrastructureError(u)&&this.onInfrastructureError?.(),u}}async subscribeToLogsSSE(e={}){return this.sseManager.subscribeToLogs(e)}async disconnect(){await this.sseManager.disconnect()}async listMemoryNotes(e={}){let r=new URLSearchParams;e.scope&&r.set("scope",e.scope),e.query&&r.set("query",e.query);let n=r.toString();return(await this.restRequest("GET",`/v1/memory-notes${n?`?${n}`:""}`)).data}async createMemoryNote(e){return(await this.restRequest("POST","/v1/memory-notes",e)).data}async updateMemoryNote(e,r){return(await this.restRequest("PATCH",`/v1/memory-notes/${encodeURIComponent(e)}`,r)).data}async deleteMemoryNote(e){await this.restRequest("DELETE",`/v1/memory-notes/${encodeURIComponent(e)}`)}async clearMemoryNotes(e){return(await this.restRequest("DELETE",`/v1/memory-notes?scope=${e}`)).data.deleted}async getMe(){return this.restRequest("GET","/v1/me")}async completeOnboarding(){return this.restRequest("POST","/v1/me/onboarding/complete")}async runTool(e){let r=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e.toolId)}/run`,{inputs:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture},void 0,e.signal?{signal:e.signal}:void 0);return{success:r.status==="success",data:r.data,error:r.error,tool:r.tool,stepResults:r.stepResults?.map(n=>({...n}))||[],...r.fileArtifacts&&r.fileArtifacts.length>0?{fileArtifacts:r.fileArtifacts}:{},...r.metadata?.warnings?.length?{warnings:r.metadata.warnings}:{}}}async runToolConfig(e){let r=e.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",n=await this.restRequest("POST",r,{tool:e.tool,payload:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture,executionKind:e.executionKind,parentToolId:e.parentToolId,draftId:e.draftId},e.traceId?{"X-Trace-Id":e.traceId}:void 0,e.signal?{signal:e.signal}:void 0);return{success:n.status?n.status==="success":n.success??!1,data:n.data,error:n.error,tool:n.tool||e.tool,stepResults:n.stepResults?.map(o=>({...o}))||[],...n.fileArtifacts&&n.fileArtifacts.length>0?{fileArtifacts:n.fileArtifacts}:{},...n.metadata?.warnings?.length?{warnings:n.metadata.warnings}:{}}}async abortToolExecution(e){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(e)}/cancel`)).runId}}async executeStep({step:e,payload:r,files:n,previousResults:i,credentials:o,options:s,runId:a,systemIds:c,credentialId:u,systemAuth:l,createRun:d,parentToolId:A,stepIndex:p,stepId:h,signal:g,stream:S}){let B={step:e,payload:r,files:n,previousResults:i,credentials:o,options:s,runId:a,systemIds:c,credentialId:u,systemAuth:l,createRun:d,parentToolId:A,stepIndex:p,stepId:h};return S?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:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:u,parentToolId:l,stepId:d,signal:A,stream:p}){let h={outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:u,parentToolId:l,stepId:d};return p?this.streamRequest("/v1/tools/transform/run",h,A):this.restRequest("POST","/v1/tools/transform/run",h,void 0,A?{signal:A}:void 0)}async createRun({toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:c,completedAt:u,executionKind:l,parentToolId:d,draftId:A}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:(0,Vo.toUTCISOString)(c,"run.startedAt"),completedAt:(0,Vo.toUTCISOString)(u,"run.completedAt"),executionKind:l,parentToolId:d,draftId:A})}async checkRunLimit(){return(await this.restRequest("POST","/v1/runs/check-limit")).data}async extract({file:e,envelope:r}){if(!e)throw new Error("File must be provided for extract.");let n=new FormData;n.append("file",e);let i=r?"/v1/extract?envelope=true":"/v1/extract";return this.restRequest("POST",i,n)}mapOpenAPIRunToRun(e){let r={running:Vu.RunStatus.RUNNING,success:Vu.RunStatus.SUCCESS,failed:Vu.RunStatus.FAILED,aborted:Vu.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:r[e.status]??Vu.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??Vu.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,Vo.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,Vo.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,Vo.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,Vo.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e={}){let r=(0,Dn.createSearchListQueryParams)(e);e.toolId!==void 0&&r.set("toolId",e.toolId),e.searchUserIds?.length&&r.set("searchUserIds",e.searchUserIds.join(",")),e.includeTotal!==void 0&&r.set("includeTotal",String(e.includeTotal)),e.startedAfter!==void 0&&r.set("startedAfter",e.startedAfter instanceof Date?(0,Vo.toUTCISOString)(e.startedAfter,"run.startedAfter"):e.startedAfter),e.statuses!==void 0?r.set("status",e.statuses.join(",")):e.status!==void 0&&r.set("status",e.status),e.requestSources!==void 0&&r.set("requestSources",e.requestSources.join(",")),e.executionKinds!==void 0&&r.set("executionKinds",e.executionKinds.join(",")),e.userId!==void 0&&r.set("userId",e.userId),e.systemId!==void 0&&r.set("systemId",e.systemId),e.systemIds!==void 0&&r.set("systemIds",e.systemIds.join(","));let n=r.size>0?`?${r.toString()}`:"",i=await this.restRequest("GET",`/v1/runs${n}`,void 0,void 0,{signal:e.signal});return{data:i.data.map(o=>this.mapOpenAPIRunToRun(o)),total:i.total,page:i.page,limit:i.limit,hasMore:i.hasMore}}async getActivityCounts(e){let r=new URLSearchParams;e?.from&&r.set("from",e.from instanceof Date?(0,Vo.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&r.set("to",e.to instanceof Date?(0,Vo.toUTCISOString)(e.to,"activity.to"):e.to);let n=r.toString();return(await this.restRequest("GET",`/v1/activity/counts${n?`?${n}`:""}`,void 0,void 0,{signal:e?.signal})).counts}async getRun(e){try{let r=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(e)}`);return this.mapOpenAPIRunToRun(r)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found"))return null;throw r}}async getTool(e){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}`)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found")||r.message?.includes("403")||r.message?.includes("not allowed"))return null;throw r}}async getToolState(e){return(await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/state`)).state}async setToolState(e,r){await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/state`,{state:r})}async deleteToolState(e){return(await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/state`)).deletedKeys}async archiveTool(e,r=!0){return this.updateTool(e,{archived:r})}async bulkArchiveTools(e,r=!0){return this.restRequest("POST","/v1/tools/bulk/archive",{ids:e,archived:r})}async bulkDeleteTools(e){return this.restRequest("POST","/v1/tools/bulk/delete",{ids:e})}async listTools(e={}){let r=(0,Dn.createListQueryParams)(e);e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived));let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/tools${n}`)}async listAllTools(e={}){return(0,Dn.listAllPages)((r,n)=>this.listTools({...e,page:r,limit:n}))}async createTool(e,r){return this.restRequest("POST","/v1/tools",{...r,id:e})}async updateTool(e,r){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}`,r)}async deleteTool(e){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}`),!0}catch(r){if(r.message?.includes("404"))return!1;throw r}}async renameTool(e,r){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/rename`,{newId:r})}async getWorkflow(e){return this.getTool(e)}async archiveWorkflow(e,r=!0){return this.upsertWorkflow(e,{archived:r})}async createWorkflow(e,r){return this.createTool(e,r)}async updateWorkflow(e,r){return this.updateTool(e,r)}async upsertWorkflow(e,r){return await this.getTool(e)?this.updateTool(e,r):this.createTool(e,r)}async deleteWorkflow(e){return this.deleteTool(e)}async renameWorkflow(e,r){return this.renameTool(e,r)}async listProjectSummaries(e={}){let r=(0,Dn.createSearchListQueryParams)(e);return r.set("includeResources","false"),e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived)),this.restRequest("GET",`/v1/projects?${r.toString()}`)}async listAllProjectSummaries({includeArchived:e}={}){return(0,Dn.listAllPages)((r,n)=>this.listProjectSummaries({page:r,limit:n,...e!==void 0?{includeArchived:e}:{}}))}async listAllProjectTasks(e){return(0,Dn.listAllPages)((r,n)=>this.restRequest("GET",`/v1/projects/${encodeURIComponent(e)}/tasks?page=${r}&limit=${n}`))}async saveProjectTask({projectId:e,taskId:r,input:n}){let i=`/v1/projects/${encodeURIComponent(e)}/tasks${r?`/${encodeURIComponent(r)}`:""}`;return(await this.restRequest(r?"PATCH":"POST",i,n)).data}async listSchedules(e={}){let r=(0,Dn.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"",i=e.toolId?`/v1/tools/${encodeURIComponent(e.toolId)}/schedules${n}`:`/v1/schedules${n}`,o=await this.restRequest("GET",i);return{...o,data:o.data.map(s=>this.mapOpenAPIScheduleToToolSchedule(s))}}async listAllSchedules(e={}){return(0,Dn.listAllPages)((r,n)=>this.listSchedules({...e,page:r,limit:n}))}async getToolSchedule(e,r){try{let n=await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`);return this.mapOpenAPIScheduleToToolSchedule(n)}catch(n){if(n.message?.includes("404")||n.message?.includes("not found"))return null;throw n}}async createToolSchedule(e,r){let n=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/schedules`,{...r,timezone:r.timezone||(0,eke.getRuntimeTimezone)()});return this.mapOpenAPIScheduleToToolSchedule(n)}async updateToolSchedule(e,r,n){let i=await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`,n);return this.mapOpenAPIScheduleToToolSchedule(i)}async deleteToolSchedule(e,r){return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`),!0}async bulkSetSchedulesEnabled(e,r){return this.restRequest("POST","/v1/schedules/bulk/enable",{ids:e,enabled:r})}async bulkDeleteSchedules(e){return this.restRequest("POST","/v1/schedules/bulk/delete",{ids:e})}async listCredentials(e={}){let r=(0,Dn.createListQueryParams)(e);e.systemId!==void 0&&r.set("systemId",e.systemId);let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/credentials${n}`)}async listAllCredentials(e={}){return(0,Dn.listAllPages)((r,n)=>this.listCredentials({...e,page:r,limit:n}))}async createCredentials(e){return(await this.restRequest("POST","/v1/credentials",e)).data}async replaceCredentials(e,r){return(await this.restRequest("PUT",`/v1/credentials/${encodeURIComponent(e)}`,{credentials:r})).data}async updateCredentials(e,r){return(await this.restRequest("PATCH",`/v1/credentials/${encodeURIComponent(e)}`,r)).data}async deleteCredentials(e){await this.restRequest("DELETE",`/v1/credentials/${encodeURIComponent(e)}`)}async setDefaultCredentials(e){await this.restRequest("POST",`/v1/credentials/${encodeURIComponent(e)}/default`)}async listSystems(e={}){let r=(0,Dn.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/systems${n}`)}async listAllSystems(e={}){return(0,Dn.listAllPages)((r,n)=>this.listSystems({...e,page:r,limit:n}))}async getSystem(e){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}`)).data}async createSystem(e){return(await this.restRequest("POST","/v1/systems",e)).data}async updateSystem(e,r){return(await this.restRequest("PATCH",`/v1/systems/${encodeURIComponent(e)}`,r)).data}async deleteSystem(e){return await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}`),!0}async bulkDeleteSystems(e){return this.restRequest("POST","/v1/systems/bulk/delete",{ids:e})}async listManagedOAuthTemplateIds(){return(await this.restRequest("GET","/v1/oauth2/managed-apps")).data.templateIds}async createOAuthExchange(e){return(await this.restRequest("POST","/v1/oauth/exchanges",e)).data}async completeOAuthExchange(e,r){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/complete`,r)).data}async searchSystemDocumentation(e,r){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/search`,{keywords:r})).data}async triggerSystemDocumentationScrapeJob(e,r){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/scrape`,r)).data}async fetchOpenApiSpec(e,r,n){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/openapi`,{url:r,link:n?.link})).data}async uploadSystemDocumentationFiles(e,r,n){let i=await this.uploadFiles(r,{process:!0}),o=i.flatMap(s=>s.status==="uploaded"?[s.id]:[]);if(o.length>0)try{await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/files`,{fileIds:o,link:n?.link!==!1})}catch(s){throw await Promise.all(o.map(a=>this.deleteFileUpload(a).catch(()=>{}))),s}if(!n?.settle){let s=i.filter(a=>a.status==="failed");if(s.length>0)throw new Error(s.map(a=>a.error).join("; "))}return i}async listSystemDocumentationFiles(e,r){let n=new URLSearchParams;r?.length&&n.set("fileIds",r.join(","));let i=n.size>0?`?${n.toString()}`:"";return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files${i}`)).data}async getSystemDocumentationFileContent(e,r,n){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(r)}/content?processed=${n.processed}`)).data}async deleteSystemDocumentationFile(e,r){await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(r)}`)}async generateCredentialsLink(e){try{return{success:!0,credentialsUrl:(await this.restRequest("POST","/v1/authenticate",e||{})).data.credentialsUrl}}catch(r){return{success:!1,error:r.message}}}};Ju.SuperglueClient=xv});var bG=m(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.UnquotedKeyStrategy=at.TripleQuoteStrategy=at.TrailingCommaStrategy=at.SingleQuoteStrategy=at.PythonLiteralStrategy=at.CommentStrategy=at.ResilientJsonParser=at.RepairStrategy=void 0;at.parseJsonResilient=tke;at.parseJSON=rke;at.isValidJson=nke;at.prettyPrintJson=ike;at.minifyJson=oke;var Yn=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};at.RepairStrategy=Yn;var By=class extends Yn{constructor(){super(...arguments),this.name="TripleQuoteRepair",this.description="Converts triple-quoted strings to proper JSON, parsing nested JSON content"}canApply(e){return/"""/.test(e)}apply(e){return e.replace(/"""([\s\S]*?)"""/g,(r,n)=>{let i=n.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let s=JSON.parse(i);return JSON.stringify(s)}catch{return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`})}};at.TripleQuoteStrategy=By;var Qy=class extends Yn{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")}};at.PythonLiteralStrategy=Qy;var vy=class extends Yn{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")}};at.TrailingCommaStrategy=vy;var _y=class extends Yn{constructor(){super(...arguments),this.name="SingleQuoteRepair",this.description="Converts single quotes to double quotes"}canApply(e){return/[{,]\s*'[^']*'\s*:/.test(e)||/:\s*'[^']*'/.test(e)}apply(e){let r=e.replace(/([{,]\s*)'([^']+)'(\s*:)/g,'$1"$2"$3');return r=r.replace(/(:\s*)'([^']+)'(\s*[,}])/g,'$1"$2"$3'),r}};at.SingleQuoteStrategy=_y;var Dy=class extends Yn{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')}};at.UnquotedKeyStrategy=Dy;var Ty=class extends Yn{constructor(){super(...arguments),this.name="CommentRemoval",this.description="Removes JavaScript-style comments"}canApply(e){return/\/\/.*$|\/\*[\s\S]*?\*\//m.test(e)}apply(e){let r=e.replace(/\/\/.*$/gm,"");return r=r.replace(/\/\*[\s\S]*?\*\//g,""),r}};at.CommentStrategy=Ty;var Lv=class extends Yn{constructor(){super(...arguments),this.name="UnescapedControlCharactersRepair",this.description="Escapes unescaped control characters (newlines, tabs, etc.) in JSON strings"}canApply(e){try{return JSON.parse(e),!1}catch(r){let n=r.message||"";return n.includes("control character")||n.includes("Bad control")||n.includes("Unexpected token")&&/[\n\r\t]/.test(e)}}apply(e){let r="",n=!1,i=!1;for(let o=0;o<e.length;o++){let s=e[o],a=o>0?e[o-1]:"";if(i){r+=s,i=!1;continue}if(s==="\\"&&n){r+=s,i=!0;continue}if(s==='"'&&a!=="\\"){n=!n,r+=s;continue}if(n)switch(s){case`
1771
+ ${o}`:i.stack}V.exports.fetch=function(e,r=void 0){return kRe(e,r).catch(n=>{throw pG?mG(n,pG):n&&typeof n=="object"&&Error.captureStackTrace(n,V.exports.fetch),n})};V.exports.Headers=oc().Headers;V.exports.Response=RA().Response;V.exports.Request=Uu().Request;V.exports.FormData=zg().FormData;var{setGlobalOrigin:NRe,getGlobalOrigin:ORe}=ZS();V.exports.setGlobalOrigin=NRe;V.exports.getGlobalOrigin=ORe;var{CacheStorage:URe}=tH(),{kConstruct:MRe}=$e();V.exports.caches=new URe(MRe);var{deleteCookie:xRe,getCookies:LRe,getSetCookies:PRe,setCookie:FRe,parseCookie:$Re}=pH();V.exports.deleteCookie=xRe;V.exports.getCookies=LRe;V.exports.getSetCookies=PRe;V.exports.setCookie=FRe;V.exports.parseCookie=$Re;var{parseMIMEType:jRe,serializeAMimeType:qRe}=In();V.exports.parseMIMEType=jRe;V.exports.serializeAMimeType=qRe;var{CloseEvent:zRe,ErrorEvent:HRe,MessageEvent:GRe}=uy(),{WebSocket:YRe,ping:VRe}=GH();V.exports.WebSocket=YRe;V.exports.CloseEvent=zRe;V.exports.ErrorEvent=HRe;V.exports.MessageEvent=GRe;V.exports.ping=VRe;V.exports.WebSocketStream=eG().WebSocketStream;V.exports.WebSocketError=Rv().WebSocketError;V.exports.request=qA(Yu.request);V.exports.stream=qA(Yu.stream);V.exports.pipeline=qA(Yu.pipeline);V.exports.connect=qA(Yu.connect);V.exports.upgrade=qA(Yu.upgrade);V.exports.MockClient=IRe;V.exports.MockCallHistory=CRe;V.exports.MockCallHistoryLog=bRe;V.exports.MockPool=wRe;V.exports.MockAgent=SRe;V.exports.SnapshotAgent=BRe;V.exports.mockErrors=QRe;var{EventSource:JRe}=AG();V.exports.EventSource=JRe;function WRe(){globalThis.fetch=V.exports.fetch,globalThis.Headers=V.exports.Headers,globalThis.Response=V.exports.Response,globalThis.Request=V.exports.Request,globalThis.FormData=V.exports.FormData,globalThis.WebSocket=V.exports.WebSocket,globalThis.CloseEvent=V.exports.CloseEvent,globalThis.ErrorEvent=V.exports.ErrorEvent,globalThis.MessageEvent=V.exports.MessageEvent,globalThis.EventSource=V.exports.EventSource}V.exports.install=WRe});var IG=m(Ju=>{"use strict";Object.defineProperty(Ju,"__esModule",{value:!0});Ju.SuperglueClient=Ju.SuperglueHttpError=void 0;var Vu=dr(),Dn=mb(),ZRe=Yb(),KRe=RL(),XRe=ln(),Vo=Lc(),eke=Xl(),HA=14400*1e3,zA;if(typeof globalThis.process<"u"&&globalThis.process.versions?.node)try{let{Agent:t}=yG();zA=new t({headersTimeout:HA,bodyTimeout:HA})}catch{}function EG(t){if(t?.aborted)throw t.reason??new DOMException("Aborted","AbortError")}var wy=class extends Error{constructor(e,r,n,i){super(e),this.status=r,this.code=n,this.details=i,this.name="SuperglueHttpError"}};Ju.SuperglueHttpError=wy;var xv=class{constructor({apiKey:e,apiEndpoint:r,onInfrastructureError:n,refreshToken:i,sseTokenProvider:o,tokenProvider:s}){if(!e&&!s)throw new Error("SuperglueClient requires either apiKey or tokenProvider");this.tokenProvider=s??(async()=>e),this.apiEndpoint=r??"https://api.superglue.cloud",this.sseManager=new ZRe.SSELogSubscriptionManager(this.apiEndpoint,o??this.tokenProvider,i),this.onInfrastructureError=n,this.refreshToken=i}async getApiKey(){return this.tokenProvider()}async fetchWithAuthRetry(e,r){let n=await this.getApiKey(),i=await e(n);if(i.status!==401||!this.refreshToken)return i;EG(r);let o=await this.refreshToken();return EG(r),!o||o===n?i:(i.body?.cancel(),e(o))}isInfrastructureError(e){return(0,XRe.isAbortError)(e)?!1:!!(e instanceof TypeError&&e.message.toLowerCase().includes("fetch")||e instanceof Error&&e.name==="TimeoutError")}async restRequest(e,r,n,i,o){let a=await(await this.restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o})).text();if(a)return JSON.parse(a)}async restResponse({method:e,path:r,body:n,extraHeaders:i,requestInit:o}){let s=`${this.apiEndpoint.replace(/\/$/,"")}${r}`,a=n!=null,c=typeof FormData<"u"&&n instanceof FormData,u=d=>{let A={Authorization:`Bearer ${d}`,...i};return a&&!c&&e!=="GET"&&(A["Content-Type"]="application/json"),fetch(s,{...o,method:e,headers:A,body:a?c?n:JSON.stringify(n):void 0,signal:o?.signal??AbortSignal.timeout(HA),...zA?{dispatcher:zA}:{}})},l;try{l=await this.fetchWithAuthRetry(u,o?.signal)}catch(d){throw this.isInfrastructureError(d)&&this.onInfrastructureError?.(),d}if(!l.ok)throw await this.buildHttpError(l);return l}async uploadFiles(e,r){if(typeof r?.process!="boolean")throw new Error("process must be a boolean");if(e.length===0)return[];let n=e.map(l=>({...l,contentLength:l.contentLength??this.getUploadContentLength(l.content)})),o=(await this.restRequest("POST","/v1/files/uploads",{process:r.process,...r.allowUnprocessed?{allowUnprocessed:!0}:{},files:n.map(({fileName:l,contentType:d,contentLength:A})=>({fileName:l,contentLength:A,...d?{contentType:d}:{}}))})).data.files;if(o.length!==n.length)throw await Promise.all(o.map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),new Error("Upload response did not match the selected files");let s=await Promise.allSettled(o.map(async(l,d)=>{let A=n[d],p=await fetch(l.uploadUrl,{method:"PUT",body:A.content,headers:A.contentType?{"Content-Type":A.contentType}:void 0,signal:AbortSignal.timeout(Math.min(HA,l.expiresIn*1e3))});if(!p.ok)throw new Error(`Upload failed for ${A.fileName}: ${p.status} ${p.statusText}`);return l.id})),a=s.flatMap(l=>l.status==="fulfilled"?[l.value]:[]),c=new Map;if(a.length>0)try{let l=await this.restRequest("POST","/v1/files/uploads/complete",{fileIds:a});c=new Map(l.data.files.map(d=>[d.id,d]))}catch(l){c=new Map(a.map(d=>[d,{id:d,fileName:n[o.findIndex(A=>A.id===d)]?.fileName||d,contentLength:n[o.findIndex(A=>A.id===d)]?.contentLength||0,status:"failed",error:l instanceof Error?l.message:String(l)}]))}let u=o.map((l,d)=>{let A=s[d],p=n[d];return A.status==="rejected"?{id:l.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:A.reason instanceof Error?A.reason.message:String(A.reason)}:c.get(l.id)||{id:l.id,fileName:p.fileName,contentLength:p.contentLength,status:"failed",error:"Upload completion returned no result"}});return await Promise.all(u.filter(l=>l.status==="failed").map(l=>this.deleteFileUpload(l.id).catch(()=>{}))),u}async deleteFileUpload(e){await this.restRequest("DELETE",`/v1/files/uploads/${encodeURIComponent(e)}`)}getUploadContentLength(e){return typeof e=="string"?new TextEncoder().encode(e).byteLength:e instanceof Uint8Array?e.byteLength:e.size}async buildHttpError(e){e.status>=500&&this.onInfrastructureError?.();let r=await e.text(),n=`HTTP ${e.status}: ${r}`,i,o;try{let s=JSON.parse(r);s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),typeof s?.code=="string"&&(i=s.code);let a=s.error;typeof a=="string"?n=a:a&&typeof a=="object"&&(n=a.message||JSON.stringify(a))}catch{}return new wy(n,e.status,i,o)}async streamRequest(e,r,n){let i=e.includes("?")?"&":"?",o=`${this.apiEndpoint.replace(/\/$/,"")}${e}${i}stream=true`,s=u=>fetch(o,{method:"POST",headers:{Authorization:`Bearer ${u}`,Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify(r),signal:n??AbortSignal.timeout(HA),...zA?{dispatcher:zA}:{}}),a;try{a=await this.fetchWithAuthRetry(s,n)}catch(u){throw this.isInfrastructureError(u)&&this.onInfrastructureError?.(),u}if(!a.ok)throw await this.buildHttpError(a);if(!(a.headers.get("content-type")||"").includes("text/event-stream")){let u=await a.text();return u?JSON.parse(u):void 0}try{return await(0,KRe.consumeEventStreamResult)(a)}catch(u){throw this.isInfrastructureError(u)&&this.onInfrastructureError?.(),u}}async subscribeToLogsSSE(e={}){return this.sseManager.subscribeToLogs(e)}async disconnect(){await this.sseManager.disconnect()}async listMemoryNotes(e={}){let r=new URLSearchParams;e.scope&&r.set("scope",e.scope),e.query&&r.set("query",e.query);let n=r.toString();return(await this.restRequest("GET",`/v1/memory-notes${n?`?${n}`:""}`)).data}async createMemoryNote(e){return(await this.restRequest("POST","/v1/memory-notes",e)).data}async updateMemoryNote(e,r){return(await this.restRequest("PATCH",`/v1/memory-notes/${encodeURIComponent(e)}`,r)).data}async deleteMemoryNote(e){await this.restRequest("DELETE",`/v1/memory-notes/${encodeURIComponent(e)}`)}async clearMemoryNotes(e){return(await this.restRequest("DELETE",`/v1/memory-notes?scope=${e}`)).data.deleted}async getMe(){return this.restRequest("GET","/v1/me")}async completeOnboarding(){return this.restRequest("POST","/v1/me/onboarding/complete")}async runTool(e){let r=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e.toolId)}/run`,{inputs:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture},void 0,e.signal?{signal:e.signal}:void 0);return{success:r.status==="success",data:r.data,error:r.error,tool:r.tool,stepResults:r.stepResults?.map(n=>({...n}))||[],...r.fileArtifacts&&r.fileArtifacts.length>0?{fileArtifacts:r.fileArtifacts}:{},...r.metadata?.warnings?.length?{warnings:r.metadata.warnings}:{}}}async runToolConfig(e){let r=e.createRun?"/v1/tools/run?createRun=true":"/v1/tools/run",n=await this.restRequest("POST",r,{tool:e.tool,payload:e.payload,files:e.files,credentials:e.credentials,includeStepResultData:e.includeStepResultData,options:e.options,runId:e.runId,stateFixture:e.stateFixture,executionKind:e.executionKind,parentToolId:e.parentToolId,draftId:e.draftId},e.traceId?{"X-Trace-Id":e.traceId}:void 0,e.signal?{signal:e.signal}:void 0);return{success:n.status?n.status==="success":n.success??!1,data:n.data,error:n.error,tool:n.tool||e.tool,stepResults:n.stepResults?.map(o=>({...o}))||[],...n.fileArtifacts&&n.fileArtifacts.length>0?{fileArtifacts:n.fileArtifacts}:{},...n.metadata?.warnings?.length?{warnings:n.metadata.warnings}:{}}}async abortToolExecution(e){return{success:!0,runId:(await this.restRequest("POST",`/v1/runs/${encodeURIComponent(e)}/cancel`)).runId}}async executeStep({step:e,payload:r,files:n,previousResults:i,credentials:o,options:s,runId:a,systemIds:c,credentialId:u,systemAuth:l,createRun:d,parentToolId:A,stepIndex:p,stepId:h,signal:g,stream:S}){let B={step:e,payload:r,files:n,previousResults:i,credentials:o,options:s,runId:a,systemIds:c,credentialId:u,systemAuth:l,createRun:d,parentToolId:A,stepIndex:p,stepId:h};return S?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:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:u,parentToolId:l,stepId:d,signal:A,stream:p}){let h={outputTransform:e,outputSchema:r,inputSchema:n,payload:i,files:o,stepResults:s,options:a,runId:c,createRun:u,parentToolId:l,stepId:d};return p?this.streamRequest("/v1/tools/transform/run",h,A):this.restRequest("POST","/v1/tools/transform/run",h,void 0,A?{signal:A}:void 0)}async createRun({toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:c,completedAt:u,executionKind:l,parentToolId:d,draftId:A}){return this.restRequest("POST","/v1/runs",{toolId:e,toolConfig:r,toolResult:n,stepResults:i,toolPayload:o,status:s,error:a,startedAt:(0,Vo.toUTCISOString)(c,"run.startedAt"),completedAt:(0,Vo.toUTCISOString)(u,"run.completedAt"),executionKind:l,parentToolId:d,draftId:A})}async checkRunLimit(){return(await this.restRequest("POST","/v1/runs/check-limit")).data}async extract({file:e,envelope:r}){if(!e)throw new Error("File must be provided for extract.");let n=new FormData;n.append("file",e);let i=r?"/v1/extract?envelope=true":"/v1/extract";return this.restRequest("POST",i,n)}mapOpenAPIRunToRun(e){let r={running:Vu.RunStatus.RUNNING,success:Vu.RunStatus.SUCCESS,failed:Vu.RunStatus.FAILED,aborted:Vu.RunStatus.ABORTED};return{runId:e.runId??e.id,toolId:e.toolId,tool:e.tool,systemIds:e.systemIds,status:r[e.status]??Vu.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??Vu.RunExecutionKind.FULL},fileArtifacts:e.fileArtifacts}}mapOpenAPIScheduleToToolSchedule(e){return{...e,lastRunAt:e.lastRunAt?(0,Vo.requireUTCDate)(e.lastRunAt,"schedule.lastRunAt"):void 0,nextRunAt:(0,Vo.requireUTCDate)(e.nextRunAt,"schedule.nextRunAt"),createdAt:(0,Vo.requireUTCDate)(e.createdAt,"schedule.createdAt"),updatedAt:(0,Vo.requireUTCDate)(e.updatedAt,"schedule.updatedAt")}}async listRuns(e={}){let r=(0,Dn.createSearchListQueryParams)(e);e.toolId!==void 0&&r.set("toolId",e.toolId),e.searchUserIds?.length&&r.set("searchUserIds",e.searchUserIds.join(",")),e.includeTotal!==void 0&&r.set("includeTotal",String(e.includeTotal)),e.startedAfter!==void 0&&r.set("startedAfter",e.startedAfter instanceof Date?(0,Vo.toUTCISOString)(e.startedAfter,"run.startedAfter"):e.startedAfter),e.statuses!==void 0?r.set("status",e.statuses.join(",")):e.status!==void 0&&r.set("status",e.status),e.requestSources!==void 0&&r.set("requestSources",e.requestSources.join(",")),e.executionKinds!==void 0&&r.set("executionKinds",e.executionKinds.join(",")),e.userId!==void 0&&r.set("userId",e.userId),e.systemId!==void 0&&r.set("systemId",e.systemId),e.systemIds!==void 0&&r.set("systemIds",e.systemIds.join(","));let n=r.size>0?`?${r.toString()}`:"",i=await this.restRequest("GET",`/v1/runs${n}`,void 0,void 0,{signal:e.signal});return{data:i.data.map(o=>this.mapOpenAPIRunToRun(o)),total:i.total,page:i.page,limit:i.limit,hasMore:i.hasMore}}async getActivityCounts(e){let r=new URLSearchParams;e?.from&&r.set("from",e.from instanceof Date?(0,Vo.toUTCISOString)(e.from,"activity.from"):e.from),e?.to&&r.set("to",e.to instanceof Date?(0,Vo.toUTCISOString)(e.to,"activity.to"):e.to);let n=r.toString();return(await this.restRequest("GET",`/v1/activity/counts${n?`?${n}`:""}`,void 0,void 0,{signal:e?.signal})).counts}async getRun(e){try{let r=await this.restRequest("GET",`/v1/runs/${encodeURIComponent(e)}`);return this.mapOpenAPIRunToRun(r)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found"))return null;throw r}}async getTool(e){try{return await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}`)}catch(r){if(r.message?.includes("404")||r.message?.includes("not found")||r.message?.includes("403")||r.message?.includes("not allowed"))return null;throw r}}async getToolState(e){return(await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/state`)).state}async setToolState(e,r){await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/state`,{state:r})}async deleteToolState(e){return(await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/state`)).deletedKeys}async archiveTool(e,r=!0){return this.updateTool(e,{archived:r})}async bulkArchiveTools(e,r=!0){return this.restRequest("POST","/v1/tools/bulk/archive",{ids:e,archived:r})}async bulkDeleteTools(e){return this.restRequest("POST","/v1/tools/bulk/delete",{ids:e})}async listTools(e={}){let r=(0,Dn.createListQueryParams)(e);e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived));let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/tools${n}`)}async listAllTools(e={}){return(0,Dn.listAllPages)((r,n)=>this.listTools({...e,page:r,limit:n}))}async createTool(e,r){return this.restRequest("POST","/v1/tools",{...r,id:e})}async updateTool(e,r){return this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}`,r)}async deleteTool(e){try{return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}`),!0}catch(r){if(r.message?.includes("404"))return!1;throw r}}async renameTool(e,r){return this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/rename`,{newId:r})}async getWorkflow(e){return this.getTool(e)}async archiveWorkflow(e,r=!0){return this.upsertWorkflow(e,{archived:r})}async createWorkflow(e,r){return this.createTool(e,r)}async updateWorkflow(e,r){return this.updateTool(e,r)}async upsertWorkflow(e,r){return await this.getTool(e)?this.updateTool(e,r):this.createTool(e,r)}async deleteWorkflow(e){return this.deleteTool(e)}async renameWorkflow(e,r){return this.renameTool(e,r)}async listProjectSummaries(e={}){let r=(0,Dn.createSearchListQueryParams)(e);return r.set("includeResources","false"),e.includeArchived!==void 0&&r.set("includeArchived",String(e.includeArchived)),this.restRequest("GET",`/v1/projects?${r.toString()}`)}async listAllProjectSummaries({includeArchived:e}={}){return(0,Dn.listAllPages)((r,n)=>this.listProjectSummaries({page:r,limit:n,...e!==void 0?{includeArchived:e}:{}}))}async listAllProjectTasks(e){return(0,Dn.listAllPages)((r,n)=>this.restRequest("GET",`/v1/projects/${encodeURIComponent(e)}/tasks?page=${r}&limit=${n}`))}async saveProjectTask({projectId:e,taskId:r,input:n}){let i=`/v1/projects/${encodeURIComponent(e)}/tasks${r?`/${encodeURIComponent(r)}`:""}`;return(await this.restRequest(r?"PATCH":"POST",i,n)).data}async listSchedules(e={}){let r=(0,Dn.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"",i=e.toolId?`/v1/tools/${encodeURIComponent(e.toolId)}/schedules${n}`:`/v1/schedules${n}`,o=await this.restRequest("GET",i);return{...o,data:o.data.map(s=>this.mapOpenAPIScheduleToToolSchedule(s))}}async listAllSchedules(e={}){return(0,Dn.listAllPages)((r,n)=>this.listSchedules({...e,page:r,limit:n}))}async getToolSchedule(e,r){try{let n=await this.restRequest("GET",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`);return this.mapOpenAPIScheduleToToolSchedule(n)}catch(n){if(n.message?.includes("404")||n.message?.includes("not found"))return null;throw n}}async createToolSchedule(e,r){let n=await this.restRequest("POST",`/v1/tools/${encodeURIComponent(e)}/schedules`,{...r,timezone:r.timezone||(0,eke.getRuntimeTimezone)()});return this.mapOpenAPIScheduleToToolSchedule(n)}async updateToolSchedule(e,r,n){let i=await this.restRequest("PUT",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`,n);return this.mapOpenAPIScheduleToToolSchedule(i)}async deleteToolSchedule(e,r){return await this.restRequest("DELETE",`/v1/tools/${encodeURIComponent(e)}/schedules/${encodeURIComponent(r)}`),!0}async bulkSetSchedulesEnabled(e,r){return this.restRequest("POST","/v1/schedules/bulk/enable",{ids:e,enabled:r})}async bulkDeleteSchedules(e){return this.restRequest("POST","/v1/schedules/bulk/delete",{ids:e})}async listCredentials(e={}){let r=(0,Dn.createListQueryParams)(e);e.systemId!==void 0&&r.set("systemId",e.systemId);let n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/credentials${n}`)}async listAllCredentials(e={}){return(0,Dn.listAllPages)((r,n)=>this.listCredentials({...e,page:r,limit:n}))}async createCredentials(e){return(await this.restRequest("POST","/v1/credentials",e)).data}async replaceCredentials(e,r){return(await this.restRequest("PUT",`/v1/credentials/${encodeURIComponent(e)}`,{credentials:r})).data}async updateCredentials(e,r){return(await this.restRequest("PATCH",`/v1/credentials/${encodeURIComponent(e)}`,r)).data}async deleteCredentials(e){await this.restRequest("DELETE",`/v1/credentials/${encodeURIComponent(e)}`)}async setDefaultCredentials(e){await this.restRequest("POST",`/v1/credentials/${encodeURIComponent(e)}/default`)}async listSystems(e={}){let r=(0,Dn.createListQueryParams)(e),n=r.size>0?`?${r.toString()}`:"";return this.restRequest("GET",`/v1/systems${n}`)}async listAllSystems(e={}){return(0,Dn.listAllPages)((r,n)=>this.listSystems({...e,page:r,limit:n}))}async getSystem(e){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}`)).data}async createSystem(e){return(await this.restRequest("POST","/v1/systems",e)).data}async updateSystem(e,r){return(await this.restRequest("PATCH",`/v1/systems/${encodeURIComponent(e)}`,r)).data}async deleteSystem(e){return await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}`),!0}async bulkDeleteSystems(e){return this.restRequest("POST","/v1/systems/bulk/delete",{ids:e})}async listManagedOAuthTemplateIds(){return(await this.restRequest("GET","/v1/oauth2/managed-apps")).data.templateIds}async createOAuthExchange(e){return(await this.restRequest("POST","/v1/oauth/exchanges",e)).data}async completeOAuthExchange(e,r){return(await this.restRequest("POST",`/v1/oauth/exchanges/${encodeURIComponent(e)}/complete`,r)).data}async searchSystemDocumentation(e,r){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/search`,{keywords:r})).data}async triggerSystemDocumentationScrapeJob(e,r){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/scrape`,r)).data}async fetchOpenApiSpec(e,r,n){return(await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/openapi`,{url:r,link:n?.link})).data}async uploadSystemDocumentationFiles(e,r,n){let i=await this.uploadFiles(r,{process:!0}),o=i.flatMap(s=>s.status==="uploaded"?[s.id]:[]);if(o.length>0)try{await this.restRequest("POST",`/v1/systems/${encodeURIComponent(e)}/documentation/files`,{fileIds:o,link:n?.link!==!1})}catch(s){throw await Promise.all(o.map(a=>this.deleteFileUpload(a).catch(()=>{}))),s}if(!n?.settle){let s=i.filter(a=>a.status==="failed");if(s.length>0)throw new Error(s.map(a=>a.error).join("; "))}return i}async listSystemDocumentationFiles(e,r){let n=new URLSearchParams;r?.length&&n.set("fileIds",r.join(","));let i=n.size>0?`?${n.toString()}`:"";return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files${i}`)).data}async getSystemDocumentationFileContent(e,r,n){return(await this.restRequest("GET",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(r)}/content?processed=${n.processed}`)).data}async deleteSystemDocumentationFile(e,r){await this.restRequest("DELETE",`/v1/systems/${encodeURIComponent(e)}/documentation/files/${encodeURIComponent(r)}`)}async generateCredentialsLink(e){try{return{success:!0,credentialsUrl:(await this.restRequest("POST","/v1/authenticate",e||{})).data.credentialsUrl}}catch(r){return{success:!1,error:r.message}}}};Ju.SuperglueClient=xv});var bG=m(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.UnquotedKeyStrategy=at.TripleQuoteStrategy=at.TrailingCommaStrategy=at.SingleQuoteStrategy=at.PythonLiteralStrategy=at.CommentStrategy=at.ResilientJsonParser=at.RepairStrategy=void 0;at.parseJsonResilient=tke;at.parseJSON=rke;at.isValidJson=nke;at.prettyPrintJson=ike;at.minifyJson=oke;var Yn=class{validate(e){try{return JSON.parse(e),!0}catch{return!1}}};at.RepairStrategy=Yn;var By=class extends Yn{constructor(){super(...arguments),this.name="TripleQuoteRepair",this.description="Converts triple-quoted strings to proper JSON, parsing nested JSON content"}canApply(e){return/"""/.test(e)}apply(e){return e.replace(/"""([\s\S]*?)"""/g,(r,n)=>{let i=n.trim();if(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]"))try{let s=JSON.parse(i);return JSON.stringify(s)}catch{return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`}return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")}"`})}};at.TripleQuoteStrategy=By;var Qy=class extends Yn{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")}};at.PythonLiteralStrategy=Qy;var vy=class extends Yn{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")}};at.TrailingCommaStrategy=vy;var _y=class extends Yn{constructor(){super(...arguments),this.name="SingleQuoteRepair",this.description="Converts single quotes to double quotes"}canApply(e){return/[{,]\s*'[^']*'\s*:/.test(e)||/:\s*'[^']*'/.test(e)}apply(e){let r=e.replace(/([{,]\s*)'([^']+)'(\s*:)/g,'$1"$2"$3');return r=r.replace(/(:\s*)'([^']+)'(\s*[,}])/g,'$1"$2"$3'),r}};at.SingleQuoteStrategy=_y;var Dy=class extends Yn{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')}};at.UnquotedKeyStrategy=Dy;var Ty=class extends Yn{constructor(){super(...arguments),this.name="CommentRemoval",this.description="Removes JavaScript-style comments"}canApply(e){return/\/\/.*$|\/\*[\s\S]*?\*\//m.test(e)}apply(e){let r=e.replace(/\/\/.*$/gm,"");return r=r.replace(/\/\*[\s\S]*?\*\//g,""),r}};at.CommentStrategy=Ty;var Lv=class extends Yn{constructor(){super(...arguments),this.name="UnescapedControlCharactersRepair",this.description="Escapes unescaped control characters (newlines, tabs, etc.) in JSON strings"}canApply(e){try{return JSON.parse(e),!1}catch(r){let n=r.message||"";return n.includes("control character")||n.includes("Bad control")||n.includes("Unexpected token")&&/[\n\r\t]/.test(e)}}apply(e){let r="",n=!1,i=!1;for(let o=0;o<e.length;o++){let s=e[o],a=o>0?e[o-1]:"";if(i){r+=s,i=!1;continue}if(s==="\\"&&n){r+=s,i=!0;continue}if(s==='"'&&a!=="\\"){n=!n,r+=s;continue}if(n)switch(s){case`
1772
1772
  `:r+="\\n";break;case"\r":r+="\\r";break;case" ":r+="\\t";break;case"\b":r+="\\b";break;case"\f":r+="\\f";break;default:let c=s.charCodeAt(0);c<32?r+="\\u"+("0000"+c.toString(16)).slice(-4):r+=s}else r+=s}return r}},Pv=class extends Yn{constructor(){super(...arguments),this.name="TrailingCharactersRepair",this.description="Removes trailing characters after valid JSON structure"}canApply(e){let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return!1;let n=0,i=0,o=!1,s=!1;for(let a=0;a<r.length;a++){let c=r[a];if(o)s?s=!1:c==="\\"?s=!0:c==='"'&&(o=!1);else if(c==='"')o=!0;else if(c==="{")n++;else if(c==="}"){if(n--,n===0&&i===0&&a>0&&a<r.length-1)return!0}else if(c==="[")i++;else if(c==="]"&&(i--,i===0&&n===0&&a>0&&a<r.length-1))return!0}return!1}apply(e){let r=e.trim(),n=0,i=0,o=!1,s=!1,a=-1;for(let c=0;c<r.length;c++){let u=r[c];if(o)s?s=!1:u==="\\"?s=!0:u==='"'&&(o=!1);else if(u==='"')o=!0;else if(u==="{")n++;else if(u==="}"){if(n--,n===0&&i===0&&c>0){a=c;break}}else if(u==="[")i++;else if(u==="]"&&(i--,i===0&&n===0&&c>0)){a=c;break}}return a>0&&a<r.length-1?r.substring(0,a+1):e}},Wu=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 By,new _y,new Lv,new Pv,new Qy,new vy,new Dy,new Ty]}parse(e){let r=Date.now();this.repairLog=[];let n=e instanceof Buffer?e.toString("utf8"):String(e);try{return{success:!0,data:JSON.parse(n),metadata:{parseTime:Date.now()-r,strategiesApplied:[]}}}catch(s){if(!this.options.attemptRepair)return{success:!1,error:`JSON parse error: ${s}`,metadata:{parseTime:Date.now()-r}}}let i=n,o=[];for(let s of this.strategies)if(s.canApply(i)){let a=i;if(i=s.apply(i),a!==i){o.push(s.name),this.repairLog.push(s.description),this.options.logRepairs&&console.log(`Applied ${s.name}: ${s.description}`);try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}catch{}}}try{return{success:!0,data:JSON.parse(i),repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}catch(s){let a=this.aggressiveFallback(i);return a.success?{...a,repairs:[...this.repairLog,"Applied aggressive fallback"],metadata:{parseTime:Date.now()-r,strategiesApplied:[...o,"AggressiveFallback"]}}:{success:!1,error:`Failed to parse JSON after applying ${o.length} strategies: ${s}`,repairs:this.repairLog,metadata:{parseTime:Date.now()-r,strategiesApplied:o}}}}aggressiveFallback(e){try{let r=e.indexOf("{"),n=e.indexOf("[");if(r===-1&&n===-1)return{success:!1,error:"No JSON-like structure found"};let i=r===-1?n:n===-1?r:Math.min(r,n),o=e.substring(i);for(let a of this.strategies)a.canApply(o)&&(o=a.apply(o));return{success:!0,data:JSON.parse(o)}}catch(r){return{success:!1,error:`Aggressive fallback failed: ${r}`}}}addStrategy(e){this.strategies.push(e)}removeStrategy(e){this.strategies=this.strategies.filter(r=>r.name!==e)}getStrategies(){return this.strategies.map(e=>e.name)}};at.ResilientJsonParser=Wu;var CG=new Wu;function tke(t,e){return(e?new Wu(e):CG).parse(t)}function rke(t){let e=CG.parse(t);if(e.success)return e.repairs&&e.repairs.length>0&&console.log("JSON parsed with repairs:",e.repairs),e.data;throw new Error(`Failed to parse JSON: ${e.error}`)}function nke(t){try{return JSON.parse(t),!0}catch{return!1}}function ike(t,e=2){return JSON.stringify(t,null,e)}function oke(t){let r=new Wu().parse(t);if(r.success)return JSON.stringify(r.data);throw new Error("Cannot minify invalid JSON")}});var ur=m(K=>{"use strict";var ske=K&&K.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(e,r);(!i||("get"in i?!e.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,i)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),le=K&&K.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&ske(e,t,r)};Object.defineProperty(K,"__esModule",{value:!0});K.SSELogSubscriptionManager=K.SuperglueHttpError=K.SuperglueClient=void 0;le(Mk(),K);le(tM(),K);le(pM(),K);le(hM(),K);le(IM(),K);le(CM(),K);le(SM(),K);le(bd(),K);le(nx(),K);le(ix(),K);le(ox(),K);le(sx(),K);le(mb(),K);le(cx(),K);le(dx(),K);le(Ax(),K);le(px(),K);le(Eb(),K);le(hx(),K);le(mx(),K);le(yx(),K);le(Ix(),K);le(cp(),K);le(bx(),K);le(Sx(),K);le(Bx(),K);le(Qx(),K);le(Dx(),K);le(Tx(),K);le(Ux(),K);le(xx(),K);le(Px(),K);le(rb(),K);le(Jx(),K);le(Zx(),K);le(zh(),K);le(lL(),K);le(gL(),K);le(mL(),K);le(qb(),K);le(CL(),K);le(bL(),K);le(QL(),K);le(_L(),K);le(dr(),K);le(ln(),K);le(DL(),K);le(TL(),K);le(og(),K);le(Lc(),K);le(Xl(),K);var SG=IG();Object.defineProperty(K,"SuperglueClient",{enumerable:!0,get:function(){return SG.SuperglueClient}});Object.defineProperty(K,"SuperglueHttpError",{enumerable:!0,get:function(){return SG.SuperglueHttpError}});var ake=Yb();Object.defineProperty(K,"SSELogSubscriptionManager",{enumerable:!0,get:function(){return ake.SSELogSubscriptionManager}});le(bG(),K)});var fE=require("commander");var Br=pe(require("fs")),QG=pe(require("os")),Jo=pe(require("path")),GA=pe(ur()),wG=new Set(["runner","builder","admin"]),BG={output:{mode:"stdout",directory:".superglue/output"},preset:"admin"};function Wo(t){let e=Jo.join(process.cwd(),".superglue"),r=QG.homedir();if(!r)return e;let n=Jo.join(r,".superglue");return t===!0?e:t===!1?n:Br.existsSync(Jo.join(e,"config.json"))?e:n}function Fv(t){return Jo.join(Wo(t),"config.json")}function Ry(t){let e=Fv(t);if(!Br.existsSync(e))return{};try{return JSON.parse(Br.readFileSync(e,"utf-8"))}catch{return{}}}function Zu(t){let e=Ry(),r=t.apiKey||(0,GA.readProcessEnvironmentValue)("SUPERGLUE_API_KEY")||e.apiKey||"",n=t.endpoint||(0,GA.readProcessEnvironmentValue)("SUPERGLUE_API_ENDPOINT")||e.endpoint||"https://api.superglue.cloud",i=(0,GA.readProcessEnvironmentValue)("SUPERGLUE_WEB_ENDPOINT")||e.webEndpoint||n.replace(/:3002\b/,":3001").replace(/api\.superglue/,"app.superglue"),o=(0,GA.readProcessEnvironmentValue)("SUPERGLUE_CLI_PRESET"),s=o&&wG.has(o)?o:e.preset&&wG.has(e.preset)?e.preset:"admin";return{...BG,...e,apiKey:r,endpoint:n,webEndpoint:i,preset:s,output:{...BG.output,...e.output}}}function ky(t,e){let r=Wo(e);Br.existsSync(r)||Br.mkdirSync(r,{recursive:!0}),Br.writeFileSync(Jo.join(r,"config.json"),JSON.stringify(t,null,2)+`
1773
- `,{mode:384})}function Ny(t,e){let r=Jo.join(Wo(e),"drafts");if(Br.existsSync(r)||Br.mkdirSync(r,{recursive:!0}),t.output.mode==="stdout+file"){let n=Jo.resolve(t.output.directory);Br.existsSync(n)||Br.mkdirSync(n,{recursive:!0})}}var Yv=pe(ur());var $v=pe(require("readline"));var DG=require("child_process"),TG=require("util");var vG={name:"@superglue/cli",version:"1.1.176",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 uke=(0,TG.promisify)(DG.exec),lr=vG.version;function _G(t){let e=t.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:t}}function Uy(t,e){let r=t.split("."),n=e.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o++){let s=_G(r[o]||"0"),a=_G(n[o]||"0");if(s.numeric<a.numeric)return-1;if(s.numeric>a.numeric||s.prerelease===null&&a.prerelease!==null)return 1;if(s.prerelease!==null&&a.prerelease===null)return-1;if(s.prerelease!==null&&a.prerelease!==null){if(s.prerelease<a.prerelease)return-1;if(s.prerelease>a.prerelease)return 1}}return 0}async function My(){try{let t=await fetch("https://registry.npmjs.org/@superglue/cli/latest",{signal:AbortSignal.timeout(5e3)});return t.ok&&(await t.json()).version||null}catch{return null}}var Oy=null;function RG(){re()&&(Oy=My())}async function kG(){if(!(!re()||!Oy)){try{let t=new Promise(r=>{setTimeout(()=>r(null),2e3).unref()}),e=await Promise.race([Oy,t]);e&&Uy(lr,e)<0&&(console.error(""),console.error(`${y.cyan}${y.bold} Update available: ${lr} \u2192 ${e}${y.reset}`),console.error(`${y.cyan} Run ${y.bold}sg update${y.reset}${y.cyan} to upgrade${y.reset}`),console.error(""))}catch{}Oy=null}}async function NG(){let t=await My();if(!t)return{success:!1,message:"Could not fetch latest version from npm"};if(Uy(lr,t)>=0)return{success:!0,message:`Already on latest version (${lr})`};try{return await uke("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${lr} to ${t}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var re=()=>process.argv.includes("--table")&&process.stdout.isTTY,Qr=()=>process.argv.includes("--full"),y={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 OG(t,e){let r=e||t;return`\x1B]8;;${t}\x07${y.underline}${y.cyan}${r}${y.reset}\x1B]8;;\x07`}function UG(){if(!re())return;let t=y.reset,e=y.dim,r="\x1B[47;30m",n=[" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@- "," =@@@- @@@@ "," @@@ @@% "," -@@ @@@@= @@@ @@@ @@@@@#@ @@@@@@@ @@@@@@@ @@@@@@ @@@ @@@ @@@ @@@@@@* %@@ "," @@ @@@ *@ @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @% @@@ @@@ @@@ @@* @@# "," #@@ @@@# @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @@@ @@@ @@@ @@* @@ "," @@- @@@@= @@@ @@@ @@@@@@@ @@@@@@ @@@@@@@ @@@ @@% @@@ @@@ @@@ @@@@@. @@."," #@% .@@@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* @@ "," @@ @ @@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* *@@ "," -@@ @@@@= @@@@@@ @@@ @@@@@@@ @@@ -@@ @@@@@@ @@@@@@% @@@@@@. @@@@@@* #@@ "," :@@* @@@ "," %@@@ =@@@. "," :@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% "];console.log(""),n.forEach(i=>{let o=i.search(/\S/),s=i.length-[...i].reverse().join("").search(/\S/)-1;if(o===-1)return console.log(" "+i);let a=i.slice(0,o),c=i.slice(o,s+1).split("").map(l=>l===" "?" ":"\u2588").join(""),u=i.slice(s+1);console.log(` ${a}${r}${c}${t}${u}`)}),console.log(` ${e} CLI v${lr}${t}`),console.log("")}function it(t){if(!re())return{stop:()=>{},update:()=>{},log:()=>{}};let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],r=0,n=t,i=()=>process.stdout.write("\r\x1B[2K"),o=()=>{process.stdout.write(`\r ${y.cyan}${e[r++%e.length]}${y.reset} ${n}`)},s=setInterval(o,80);return{update:a=>{n=a},log:a=>{i(),console.log(` ${y.dim}\u2502${y.reset} ${a}`),o()},stop:a=>{clearInterval(s),i(),a&&console.log(` ${a}`)}}}function W(t){re()?xy(t):console.log(JSON.stringify(t,null,2))}function we(t,e){re()?(console.log(` ${y.green}\u2713${y.reset} ${t}`),e&&xy(e,4)):console.log(JSON.stringify({success:!0,message:t,...e&&typeof e=="object"?e:{data:e}}))}function _(t,e){re()?(console.error(` ${y.red}\u2717${y.reset} ${t}`),e&&xy(e,4)):console.error(JSON.stringify({success:!1,error:t,details:e}))}function MG(t){re()&&console.log(` ${y.yellow}\u26A0${y.reset} ${t}`)}function Xt(t){re()&&console.log(` ${y.dim}${t}${y.reset}`)}function Zo(t){re()&&(console.log(`
1773
+ `,{mode:384})}function Ny(t,e){let r=Jo.join(Wo(e),"drafts");if(Br.existsSync(r)||Br.mkdirSync(r,{recursive:!0}),t.output.mode==="stdout+file"){let n=Jo.resolve(t.output.directory);Br.existsSync(n)||Br.mkdirSync(n,{recursive:!0})}}var Yv=pe(ur());var $v=pe(require("readline"));var DG=require("child_process"),TG=require("util");var vG={name:"@superglue/cli",version:"1.1.177",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 uke=(0,TG.promisify)(DG.exec),lr=vG.version;function _G(t){let e=t.match(/^(\d+)(?:-(.+))?$/);return e?{numeric:parseInt(e[1],10),prerelease:e[2]||null}:{numeric:0,prerelease:t}}function Uy(t,e){let r=t.split("."),n=e.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o++){let s=_G(r[o]||"0"),a=_G(n[o]||"0");if(s.numeric<a.numeric)return-1;if(s.numeric>a.numeric||s.prerelease===null&&a.prerelease!==null)return 1;if(s.prerelease!==null&&a.prerelease===null)return-1;if(s.prerelease!==null&&a.prerelease!==null){if(s.prerelease<a.prerelease)return-1;if(s.prerelease>a.prerelease)return 1}}return 0}async function My(){try{let t=await fetch("https://registry.npmjs.org/@superglue/cli/latest",{signal:AbortSignal.timeout(5e3)});return t.ok&&(await t.json()).version||null}catch{return null}}var Oy=null;function RG(){re()&&(Oy=My())}async function kG(){if(!(!re()||!Oy)){try{let t=new Promise(r=>{setTimeout(()=>r(null),2e3).unref()}),e=await Promise.race([Oy,t]);e&&Uy(lr,e)<0&&(console.error(""),console.error(`${y.cyan}${y.bold} Update available: ${lr} \u2192 ${e}${y.reset}`),console.error(`${y.cyan} Run ${y.bold}sg update${y.reset}${y.cyan} to upgrade${y.reset}`),console.error(""))}catch{}Oy=null}}async function NG(){let t=await My();if(!t)return{success:!1,message:"Could not fetch latest version from npm"};if(Uy(lr,t)>=0)return{success:!0,message:`Already on latest version (${lr})`};try{return await uke("npm install -g @superglue/cli@latest"),{success:!0,message:`Updated from ${lr} to ${t}`}}catch(e){return{success:!1,message:`Update failed: ${e.message}. Try manually: npm install -g @superglue/cli@latest`}}}var re=()=>process.argv.includes("--table")&&process.stdout.isTTY,Qr=()=>process.argv.includes("--full"),y={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 OG(t,e){let r=e||t;return`\x1B]8;;${t}\x07${y.underline}${y.cyan}${r}${y.reset}\x1B]8;;\x07`}function UG(){if(!re())return;let t=y.reset,e=y.dim,r="\x1B[47;30m",n=[" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@- "," =@@@- @@@@ "," @@@ @@% "," -@@ @@@@= @@@ @@@ @@@@@#@ @@@@@@@ @@@@@@@ @@@@@@ @@@ @@@ @@@ @@@@@@* %@@ "," @@ @@@ *@ @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @% @@@ @@@ @@@ @@* @@# "," #@@ @@@# @@@ @@@ @@@ :@@ @@@ @@@ -@@ @@@ @@@ @@@ @@@ @@* @@ "," @@- @@@@= @@@ @@@ @@@@@@@ @@@@@@ @@@@@@@ @@@ @@% @@@ @@@ @@@ @@@@@. @@."," #@% .@@@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* @@ "," @@ @ @@@ @@@ @@@ @@@ @@@ @@@ -@@ @@@ @@% @@@ @@@ @@@ @@* *@@ "," -@@ @@@@= @@@@@@ @@@ @@@@@@@ @@@ -@@ @@@@@@ @@@@@@% @@@@@@. @@@@@@* #@@ "," :@@* @@@ "," %@@@ =@@@. "," :@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@% "];console.log(""),n.forEach(i=>{let o=i.search(/\S/),s=i.length-[...i].reverse().join("").search(/\S/)-1;if(o===-1)return console.log(" "+i);let a=i.slice(0,o),c=i.slice(o,s+1).split("").map(l=>l===" "?" ":"\u2588").join(""),u=i.slice(s+1);console.log(` ${a}${r}${c}${t}${u}`)}),console.log(` ${e} CLI v${lr}${t}`),console.log("")}function it(t){if(!re())return{stop:()=>{},update:()=>{},log:()=>{}};let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],r=0,n=t,i=()=>process.stdout.write("\r\x1B[2K"),o=()=>{process.stdout.write(`\r ${y.cyan}${e[r++%e.length]}${y.reset} ${n}`)},s=setInterval(o,80);return{update:a=>{n=a},log:a=>{i(),console.log(` ${y.dim}\u2502${y.reset} ${a}`),o()},stop:a=>{clearInterval(s),i(),a&&console.log(` ${a}`)}}}function W(t){re()?xy(t):console.log(JSON.stringify(t,null,2))}function we(t,e){re()?(console.log(` ${y.green}\u2713${y.reset} ${t}`),e&&xy(e,4)):console.log(JSON.stringify({success:!0,message:t,...e&&typeof e=="object"?e:{data:e}}))}function _(t,e){re()?(console.error(` ${y.red}\u2717${y.reset} ${t}`),e&&xy(e,4)):console.error(JSON.stringify({success:!1,error:t,details:e}))}function MG(t){re()&&console.log(` ${y.yellow}\u26A0${y.reset} ${t}`)}function Xt(t){re()&&console.log(` ${y.dim}${t}${y.reset}`)}function Zo(t){re()&&(console.log(`
1774
1774
  ${y.bold}${y.cyan}${t}${y.reset}`),console.log(` ${y.dim}${"\u2500".repeat(t.length)}${y.reset}`))}function vr(t,e,r){if(!re()){console.log(JSON.stringify({success:!0,total:r?.total??t.length,items:t}));return}if(t.length===0){console.log(`
1775
1775
  ${y.dim}0 results${y.reset}
1776
1776
  `);return}let n=e||Object.keys(t[0]),i=Qr()?1/0:60,o=n.map(l=>Math.min(i,Math.max(l.length,...t.map(d=>String(d[l]??"").replace(/[\n\r]+/g," ").trim().length))));console.log("");let s=n.map((l,d)=>`${y.bold}${y.cyan}${l.toUpperCase().padEnd(o[d])}${y.reset}`).join(" ");console.log(` ${s}`);let a=o.map(l=>`${y.dim}${"\u2500".repeat(l)}${y.reset}`).join(`${y.dim}\u2500\u2500${y.reset}`);console.log(` ${a}`);for(let l of t){let d=n.map((A,p)=>{let h=String(l[A]??"").replace(/[\n\r]+/g," ").trim();if(h.length>i){let S=`\u2026 (${h.length})`;h=h.slice(0,Math.max(0,i-S.length))+`${y.dim}${S}${y.reset}`}return A==="status"?`${{success:y.green,running:y.yellow,failed:y.red,aborted:y.red,error:y.red,pending:y.dim}[h.toLowerCase()]||""}${h.padEnd(o[p])}${y.reset}`:h.padEnd(o[p])}).join(" ");console.log(` ${d}`)}let c=r?.total??t.length,u=c===t.length?`${t.length} result${t.length===1?"":"s"}`:`${t.length} of ${c} result${c===1?"":"s"}`;console.log(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superglue/cli",
3
- "version": "1.1.176",
3
+ "version": "1.1.177",
4
4
  "bin": {
5
5
  "sg": "./dist/cli.js"
6
6
  },