jaz-clio 5.4.26 → 5.4.28

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,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-api
3
- version: 5.4.26
3
+ version: 5.4.28
4
4
  description: >-
5
5
  Use this skill whenever you call, debug, or review code that touches the Jaz
6
6
  REST API. Covers field names, response shapes, 141 production gotchas, error
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-cli
3
- version: 5.4.26
3
+ version: 5.4.28
4
4
  description: >-
5
5
  Use this skill when running Clio CLI commands, building shell scripts with
6
6
  Clio, debugging auth issues, understanding --json output, paginating results,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-conversion
3
- version: 5.4.26
3
+ version: 5.4.28
4
4
  description: >-
5
5
  Use this skill when migrating accounting data into Jaz — importing from Xero,
6
6
  QuickBooks, Sage, MYOB, or Excel exports. Covers the full conversion pipeline:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-jobs
3
- version: 5.4.26
3
+ version: 5.4.28
4
4
  description: >-
5
5
  Use this skill for recurring accounting workflows — month/quarter/year-end
6
6
  close, bank reconciliation, GST/VAT filing, payment runs, credit control,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-practice
3
- version: 5.4.26
3
+ version: 5.4.28
4
4
  description: >-
5
5
  Use this skill whenever an accounting practitioner is doing client work in
6
6
  Jaz — closing the books, filing GST, year-end statutory, onboarding a new
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-recipes
3
- version: 5.4.26
3
+ version: 5.4.28
4
4
  description: >-
5
5
  Use this skill when modeling complex multi-step accounting transactions —
6
6
  anything that spans multiple periods, involves changing amounts, or requires
package/cli.mjs CHANGED
@@ -678,16 +678,16 @@ Strings are replaced with values relative to the transaction date.`);t.command("
678
678
  path: iss.path ? [${Ua(v)}, ...iss.path] : [${Ua(v)}]
679
679
  })));`),f.write(`newResult[${Ua(v)}] = ${y}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let D=f.compile();return(v,y)=>D(d,v,y)},o,i=ju,s=!bv.jitless,c=s&&mT.value,u=t.catchall,l;e._zod.parse=(d,f)=>{l??(l=r.value);let p=d.value;if(!i(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d;let m=[];if(s&&c&&f?.async===!1&&f.jitless!==!0)o||(o=n(t.shape)),d=o(d,f);else{d.value={};let y=l.shape;for(let b of l.keys){let S=y[b],E=S._zod.run({value:p[b],issues:[]},f),A=S._zod.optin==="optional"&&S._zod.optout==="optional";E instanceof Promise?m.push(E.then(O=>A?S6(O,d,b,p):xv(O,d,b))):A?S6(E,d,b,p):xv(E,d,b)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let h=[],g=l.keySet,D=u._zod,v=D.def.type;for(let y of Object.keys(p)){if(g.has(y))continue;if(v==="never"){h.push(y);continue}let b=D.run({value:p[y],issues:[]},f);b instanceof Promise?m.push(b.then(S=>xv(S,d,y))):xv(b,d,y)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:e}),m.length?Promise.all(m).then(()=>d):d}});function _6(e,t,r,n){for(let o of e)if(o.issues.length===0)return t.value=o.value,t;return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(o=>o.issues.map(i=>ko(i,n,co())))}),t}var TT=L("$ZodUnion",(e,t)=>{Dt.init(e,t),yt(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),yt(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),yt(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),yt(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Gf(n.source)).join("|")})$`)}}),e._zod.parse=(r,n)=>{let o=!1,i=[];for(let s of t.options){let a=s._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>_6(s,r,e,n)):_6(i,r,e,n)}}),sY=L("$ZodDiscriminatedUnion",(e,t)=>{TT.init(e,t);let r=e._zod.parse;yt(e._zod,"propValues",()=>{let o={};for(let i of t.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(let[a,c]of Object.entries(s)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Yf(()=>{let o=t.options,i=new Map;for(let s of o){let a=s._zod.propValues[t.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(let c of a){if(i.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);i.set(c,s)}}return i});e._zod.parse=(o,i)=>{let s=o.value;if(!ju(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=n.value.get(s?.[t.discriminator]);return a?a._zod.run(o,i):t.unionFallback?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[t.discriminator],inst:e}),o)}}),aY=L("$ZodIntersection",(e,t)=>{Dt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,u])=>E6(r,c,u)):E6(r,i,s)}});function AT(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Mu(e)&&Mu(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=AT(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n],s=AT(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function E6(e,t,r){if(t.issues.length&&e.issues.push(...t.issues),r.issues.length&&e.issues.push(...r.issues),qa(e))return e;let n=AT(t.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return e.value=n.data,e}var cY=L("$ZodRecord",(e,t)=>{Dt.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Mu(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),r;let i=[];if(t.keyType._zod.values){let s=t.keyType._zod.values;r.value={};for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=t.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?i.push(u.then(l=>{l.issues.length&&r.issues.push(...ii(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...ii(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)s.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:a})}else{r.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=t.keyType._zod.run({value:s,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>ko(u,n,co())),input:s,path:[s],inst:e}),r.value[a.value]=a.value;continue}let c=t.valueType._zod.run({value:o[s],issues:[]},n);c instanceof Promise?i.push(c.then(u=>{u.issues.length&&r.issues.push(...ii(s,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...ii(s,c.issues)),r.value[a.value]=c.value)}}return i.length?Promise.all(i).then(()=>r):r}});var uY=L("$ZodEnum",(e,t)=>{Dt.init(e,t);let r=lT(t.entries);e._zod.values=new Set(r),e._zod.pattern=new RegExp(`^(${r.filter(n=>hT.has(typeof n)).map(n=>typeof n=="string"?Cs(n):n.toString()).join("|")})$`),e._zod.parse=(n,o)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:"invalid_value",values:r,input:i,inst:e}),n}}),lY=L("$ZodLiteral",(e,t)=>{Dt.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Cs(r):r?r.toString():String(r)).join("|")})$`),e._zod.parse=(r,n)=>{let o=r.value;return e._zod.values.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}});var dY=L("$ZodTransform",(e,t)=>{Dt.init(e,t),e._zod.parse=(r,n)=>{let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(r.value=s,r));if(o instanceof Promise)throw new Li;return r.value=o,r}}),pY=L("$ZodOptional",(e,t)=>{Dt.init(e,t),e._zod.optin="optional",e._zod.optout="optional",yt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),yt(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Gf(r.source)})?$`):void 0}),e._zod.parse=(r,n)=>t.innerType._zod.optin==="optional"?t.innerType._zod.run(r,n):r.value===void 0?r:t.innerType._zod.run(r,n)}),fY=L("$ZodNullable",(e,t)=>{Dt.init(e,t),yt(e._zod,"optin",()=>t.innerType._zod.optin),yt(e._zod,"optout",()=>t.innerType._zod.optout),yt(e._zod,"pattern",()=>{let r=t.innerType._zod.pattern;return r?new RegExp(`^(${Gf(r.source)}|null)$`):void 0}),yt(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),mY=L("$ZodDefault",(e,t)=>{Dt.init(e,t),e._zod.optin="optional",yt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>C6(i,t)):C6(o,t)}});function C6(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var hY=L("$ZodPrefault",(e,t)=>{Dt.init(e,t),e._zod.optin="optional",yt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>(r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),gY=L("$ZodNonOptional",(e,t)=>{Dt.init(e,t),yt(e._zod,"values",()=>{let r=t.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>I6(i,e)):I6(o,e)}});function I6(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var yY=L("$ZodCatch",(e,t)=>{Dt.init(e,t),e._zod.optin="optional",yt(e._zod,"optout",()=>t.innerType._zod.optout),yt(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>(r.value=i.value,i.issues.length&&(r.value=t.catchValue({...r,error:{issues:i.issues.map(s=>ko(s,n,co()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=t.catchValue({...r,error:{issues:o.issues.map(i=>ko(i,n,co()))},input:r.value}),r.issues=[]),r)}});var DY=L("$ZodPipe",(e,t)=>{Dt.init(e,t),yt(e._zod,"values",()=>t.in._zod.values),yt(e._zod,"optin",()=>t.in._zod.optin),yt(e._zod,"optout",()=>t.out._zod.optout),e._zod.parse=(r,n)=>{let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>x6(i,t,n)):x6(o,t,n)}});function x6(e,t,r){return qa(e)?e:t.out._zod.run({value:e.value,issues:e.issues},r)}var bY=L("$ZodReadonly",(e,t)=>{Dt.init(e,t),yt(e._zod,"propValues",()=>t.innerType._zod.propValues),yt(e._zod,"values",()=>t.innerType._zod.values),yt(e._zod,"optin",()=>t.innerType._zod.optin),yt(e._zod,"optout",()=>t.innerType._zod.optout),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(A6):A6(o)}});function A6(e){return e.value=Object.freeze(e.value),e}var vY=L("$ZodCustom",(e,t)=>{Gr.init(e,t),Dt.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(i=>w6(i,r,n,e));w6(o,r,n,e)}});function w6(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(DT(o))}}var jfe=e=>{let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"NaN":"number";case"object":{if(Array.isArray(e))return"array";if(e===null)return"null";if(Object.getPrototypeOf(e)!==Object.prototype&&e.constructor)return e.constructor.name}}return t},Mfe=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function t(n){return e[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${jfe(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${_v(n.values[0])}`:`Invalid option: expected one of ${vv(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",i=t(n.origin);return i?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",i=t(n.origin);return i?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${i.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${vv(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function SY(){return{localeError:Mfe()}}var OT=class{constructor(){this._map=new Map,this._idmap=new Map}add(t,...r){let n=r[0];if(this._map.set(t,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,t)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(t)}}return this._map.get(t)}has(t){return this._map.has(t)}};function Bfe(){return new OT}var Zf=Bfe();function _Y(e,t){return new e({type:"string",...he(t)})}function EY(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...he(t)})}function $T(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...he(t)})}function CY(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...he(t)})}function IY(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...he(t)})}function xY(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...he(t)})}function AY(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...he(t)})}function wY(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...he(t)})}function TY(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...he(t)})}function OY(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...he(t)})}function $Y(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...he(t)})}function RY(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...he(t)})}function NY(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...he(t)})}function kY(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...he(t)})}function FY(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...he(t)})}function PY(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...he(t)})}function LY(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...he(t)})}function jY(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...he(t)})}function MY(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...he(t)})}function BY(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...he(t)})}function UY(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...he(t)})}function qY(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...he(t)})}function zY(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...he(t)})}function YY(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...he(t)})}function JY(e,t){return new e({type:"string",format:"date",check:"string_format",...he(t)})}function GY(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...he(t)})}function VY(e,t){return new e({type:"string",format:"duration",check:"string_format",...he(t)})}function HY(e,t){return new e({type:"number",checks:[],...he(t)})}function WY(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...he(t)})}function ZY(e,t){return new e({type:"boolean",...he(t)})}function KY(e,t){return new e({type:"null",...he(t)})}function XY(e){return new e({type:"unknown"})}function QY(e,t){return new e({type:"never",...he(t)})}function wv(e,t){return new IT({check:"less_than",...he(t),value:e,inclusive:!1})}function Kf(e,t){return new IT({check:"less_than",...he(t),value:e,inclusive:!0})}function Tv(e,t){return new xT({check:"greater_than",...he(t),value:e,inclusive:!1})}function Xf(e,t){return new xT({check:"greater_than",...he(t),value:e,inclusive:!0})}function Ov(e,t){return new s6({check:"multiple_of",...he(t),value:e})}function $v(e,t){return new c6({check:"max_length",...he(t),maximum:e})}function Bu(e,t){return new u6({check:"min_length",...he(t),minimum:e})}function Rv(e,t){return new l6({check:"length_equals",...he(t),length:e})}function RT(e,t){return new d6({check:"string_format",format:"regex",...he(t),pattern:e})}function NT(e){return new p6({check:"string_format",format:"lowercase",...he(e)})}function kT(e){return new f6({check:"string_format",format:"uppercase",...he(e)})}function FT(e,t){return new m6({check:"string_format",format:"includes",...he(t),includes:e})}function PT(e,t){return new h6({check:"string_format",format:"starts_with",...he(t),prefix:e})}function LT(e,t){return new g6({check:"string_format",format:"ends_with",...he(t),suffix:e})}function za(e){return new y6({check:"overwrite",tx:e})}function jT(e){return za(t=>t.normalize(e))}function MT(){return za(e=>e.trim())}function BT(){return za(e=>e.toLowerCase())}function UT(){return za(e=>e.toUpperCase())}function e4(e,t,r){return new e({type:"array",element:t,...he(r)})}function t4(e,t,r){let n=he(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function r4(e,t,r){return new e({type:"custom",check:"custom",fn:t,...he(r)})}function Uu(e){return!!e._zod}function Is(e,t){return Uu(e)?Hf(e,t):e.safeParse(t)}function Nv(e){if(!e)return;let t;if(Uu(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function n4(e){if(Uu(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}var em={};gi(em,{ZodISODate:()=>i4,ZodISODateTime:()=>o4,ZodISODuration:()=>a4,ZodISOTime:()=>s4,date:()=>zT,datetime:()=>qT,duration:()=>JT,time:()=>YT});var o4=L("ZodISODateTime",(e,t)=>{B6.init(e,t),Nt.init(e,t)});function qT(e){return YY(o4,e)}var i4=L("ZodISODate",(e,t)=>{U6.init(e,t),Nt.init(e,t)});function zT(e){return JY(i4,e)}var s4=L("ZodISOTime",(e,t)=>{q6.init(e,t),Nt.init(e,t)});function YT(e){return GY(s4,e)}var a4=L("ZodISODuration",(e,t)=>{z6.init(e,t),Nt.init(e,t)});function JT(e){return VY(a4,e)}var c4=(e,t)=>{Ev.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:r=>A9(e,r)},flatten:{value:r=>x9(e,r)},addIssue:{value:r=>e.issues.push(r)},addIssues:{value:r=>e.issues.push(...r)},isEmpty:{get(){return e.issues.length===0}}})},M3e=L("ZodError",c4),tm=L("ZodError",c4,{Parent:Error});var u4=w9(tm),l4=T9(tm),d4=vT(tm),p4=ST(tm);var qt=L("ZodType",(e,t)=>(Dt.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...r)=>e.clone({...t,checks:[...t.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),e.clone=(r,n)=>oi(e,r,n),e.brand=()=>e,e.register=((r,n)=>(r.add(e,n),e)),e.parse=(r,n)=>u4(e,r,n,{callee:e.parse}),e.safeParse=(r,n)=>d4(e,r,n),e.parseAsync=async(r,n)=>l4(e,r,n,{callee:e.parseAsync}),e.safeParseAsync=async(r,n)=>p4(e,r,n),e.spa=e.safeParseAsync,e.refine=(r,n)=>e.check(Lme(r,n)),e.superRefine=r=>e.check(jme(r)),e.overwrite=r=>e.check(za(r)),e.optional=()=>Ut(e),e.nullable=()=>h4(e),e.nullish=()=>Ut(h4(e)),e.nonoptional=r=>Ome(e,r),e.array=()=>Be(e),e.or=r=>bt([e,r]),e.and=r=>Fv(e,r),e.transform=r=>VT(e,v4(r)),e.default=r=>Ame(e,r),e.prefault=r=>Tme(e,r),e.catch=r=>Rme(e,r),e.pipe=r=>VT(e,r),e.readonly=()=>Fme(e),e.describe=r=>{let n=e.clone();return Zf.add(n,{description:r}),n},Object.defineProperty(e,"description",{get(){return Zf.get(e)?.description},configurable:!0}),e.meta=(...r)=>{if(r.length===0)return Zf.get(e);let n=e.clone();return Zf.add(n,r[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),g4=L("_ZodString",(e,t)=>{Av.init(e,t),qt.init(e,t);let r=e._zod.bag;e.format=r.format??null,e.minLength=r.minimum??null,e.maxLength=r.maximum??null,e.regex=(...n)=>e.check(RT(...n)),e.includes=(...n)=>e.check(FT(...n)),e.startsWith=(...n)=>e.check(PT(...n)),e.endsWith=(...n)=>e.check(LT(...n)),e.min=(...n)=>e.check(Bu(...n)),e.max=(...n)=>e.check($v(...n)),e.length=(...n)=>e.check(Rv(...n)),e.nonempty=(...n)=>e.check(Bu(1,...n)),e.lowercase=n=>e.check(NT(n)),e.uppercase=n=>e.check(kT(n)),e.trim=()=>e.check(MT()),e.normalize=(...n)=>e.check(jT(...n)),e.toLowerCase=()=>e.check(BT()),e.toUpperCase=()=>e.check(UT())}),Wfe=L("ZodString",(e,t)=>{Av.init(e,t),g4.init(e,t),e.email=r=>e.check(EY(Zfe,r)),e.url=r=>e.check(wY(Kfe,r)),e.jwt=r=>e.check(zY(pme,r)),e.emoji=r=>e.check(TY(Xfe,r)),e.guid=r=>e.check($T(f4,r)),e.uuid=r=>e.check(CY(kv,r)),e.uuidv4=r=>e.check(IY(kv,r)),e.uuidv6=r=>e.check(xY(kv,r)),e.uuidv7=r=>e.check(AY(kv,r)),e.nanoid=r=>e.check(OY(Qfe,r)),e.guid=r=>e.check($T(f4,r)),e.cuid=r=>e.check($Y(eme,r)),e.cuid2=r=>e.check(RY(tme,r)),e.ulid=r=>e.check(NY(rme,r)),e.base64=r=>e.check(BY(ume,r)),e.base64url=r=>e.check(UY(lme,r)),e.xid=r=>e.check(kY(nme,r)),e.ksuid=r=>e.check(FY(ome,r)),e.ipv4=r=>e.check(PY(ime,r)),e.ipv6=r=>e.check(LY(sme,r)),e.cidrv4=r=>e.check(jY(ame,r)),e.cidrv6=r=>e.check(MY(cme,r)),e.e164=r=>e.check(qY(dme,r)),e.datetime=r=>e.check(qT(r)),e.date=r=>e.check(zT(r)),e.time=r=>e.check(YT(r)),e.duration=r=>e.check(JT(r))});function P(e){return _Y(Wfe,e)}var Nt=L("ZodStringFormat",(e,t)=>{Et.init(e,t),g4.init(e,t)}),Zfe=L("ZodEmail",(e,t)=>{$6.init(e,t),Nt.init(e,t)});var f4=L("ZodGUID",(e,t)=>{T6.init(e,t),Nt.init(e,t)});var kv=L("ZodUUID",(e,t)=>{O6.init(e,t),Nt.init(e,t)});var Kfe=L("ZodURL",(e,t)=>{R6.init(e,t),Nt.init(e,t)});var Xfe=L("ZodEmoji",(e,t)=>{N6.init(e,t),Nt.init(e,t)});var Qfe=L("ZodNanoID",(e,t)=>{k6.init(e,t),Nt.init(e,t)});var eme=L("ZodCUID",(e,t)=>{F6.init(e,t),Nt.init(e,t)});var tme=L("ZodCUID2",(e,t)=>{P6.init(e,t),Nt.init(e,t)});var rme=L("ZodULID",(e,t)=>{L6.init(e,t),Nt.init(e,t)});var nme=L("ZodXID",(e,t)=>{j6.init(e,t),Nt.init(e,t)});var ome=L("ZodKSUID",(e,t)=>{M6.init(e,t),Nt.init(e,t)});var ime=L("ZodIPv4",(e,t)=>{Y6.init(e,t),Nt.init(e,t)});var sme=L("ZodIPv6",(e,t)=>{J6.init(e,t),Nt.init(e,t)});var ame=L("ZodCIDRv4",(e,t)=>{G6.init(e,t),Nt.init(e,t)});var cme=L("ZodCIDRv6",(e,t)=>{V6.init(e,t),Nt.init(e,t)});var ume=L("ZodBase64",(e,t)=>{W6.init(e,t),Nt.init(e,t)});var lme=L("ZodBase64URL",(e,t)=>{Z6.init(e,t),Nt.init(e,t)});var dme=L("ZodE164",(e,t)=>{K6.init(e,t),Nt.init(e,t)});var pme=L("ZodJWT",(e,t)=>{X6.init(e,t),Nt.init(e,t)});var y4=L("ZodNumber",(e,t)=>{wT.init(e,t),qt.init(e,t),e.gt=(n,o)=>e.check(Tv(n,o)),e.gte=(n,o)=>e.check(Xf(n,o)),e.min=(n,o)=>e.check(Xf(n,o)),e.lt=(n,o)=>e.check(wv(n,o)),e.lte=(n,o)=>e.check(Kf(n,o)),e.max=(n,o)=>e.check(Kf(n,o)),e.int=n=>e.check(m4(n)),e.safe=n=>e.check(m4(n)),e.positive=n=>e.check(Tv(0,n)),e.nonnegative=n=>e.check(Xf(0,n)),e.negative=n=>e.check(wv(0,n)),e.nonpositive=n=>e.check(Kf(0,n)),e.multipleOf=(n,o)=>e.check(Ov(n,o)),e.step=(n,o)=>e.check(Ov(n,o)),e.finite=()=>e;let r=e._zod.bag;e.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),e.isFinite=!0,e.format=r.format??null});function st(e){return HY(y4,e)}var fme=L("ZodNumberFormat",(e,t)=>{Q6.init(e,t),y4.init(e,t)});function m4(e){return WY(fme,e)}var mme=L("ZodBoolean",(e,t)=>{eY.init(e,t),qt.init(e,t)});function yr(e){return ZY(mme,e)}var hme=L("ZodNull",(e,t)=>{tY.init(e,t),qt.init(e,t)});function HT(e){return KY(hme,e)}var gme=L("ZodUnknown",(e,t)=>{rY.init(e,t),qt.init(e,t)});function kt(){return XY(gme)}var yme=L("ZodNever",(e,t)=>{nY.init(e,t),qt.init(e,t)});function Dme(e){return QY(yme,e)}var bme=L("ZodArray",(e,t)=>{oY.init(e,t),qt.init(e,t),e.element=t.element,e.min=(r,n)=>e.check(Bu(r,n)),e.nonempty=r=>e.check(Bu(1,r)),e.max=(r,n)=>e.check($v(r,n)),e.length=(r,n)=>e.check(Rv(r,n)),e.unwrap=()=>e.element});function Be(e,t){return e4(bme,e,t)}var D4=L("ZodObject",(e,t)=>{iY.init(e,t),qt.init(e,t),Ze.defineLazy(e,"shape",()=>t.shape),e.keyof=()=>Cn(Object.keys(e._zod.def.shape)),e.catchall=r=>e.clone({...e._zod.def,catchall:r}),e.passthrough=()=>e.clone({...e._zod.def,catchall:kt()}),e.loose=()=>e.clone({...e._zod.def,catchall:kt()}),e.strict=()=>e.clone({...e._zod.def,catchall:Dme()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=r=>Ze.extend(e,r),e.merge=r=>Ze.merge(e,r),e.pick=r=>Ze.pick(e,r),e.omit=r=>Ze.omit(e,r),e.partial=(...r)=>Ze.partial(S4,e,r[0]),e.required=(...r)=>Ze.required(_4,e,r[0])});function ee(e,t){let r={type:"object",get shape(){return Ze.assignProp(this,"shape",{...e}),this.shape},...Ze.normalizeParams(t)};return new D4(r)}function cn(e,t){return new D4({type:"object",get shape(){return Ze.assignProp(this,"shape",{...e}),this.shape},catchall:kt(),...Ze.normalizeParams(t)})}var b4=L("ZodUnion",(e,t)=>{TT.init(e,t),qt.init(e,t),e.options=t.options});function bt(e,t){return new b4({type:"union",options:e,...Ze.normalizeParams(t)})}var vme=L("ZodDiscriminatedUnion",(e,t)=>{b4.init(e,t),sY.init(e,t)});function WT(e,t,r){return new vme({type:"union",options:t,discriminator:e,...Ze.normalizeParams(r)})}var Sme=L("ZodIntersection",(e,t)=>{aY.init(e,t),qt.init(e,t)});function Fv(e,t){return new Sme({type:"intersection",left:e,right:t})}var _me=L("ZodRecord",(e,t)=>{cY.init(e,t),qt.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType});function Ft(e,t,r){return new _me({type:"record",keyType:e,valueType:t,...Ze.normalizeParams(r)})}var GT=L("ZodEnum",(e,t)=>{uY.init(e,t),qt.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new GT({...t,checks:[],...Ze.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new GT({...t,checks:[],...Ze.normalizeParams(o),entries:i})}});function Cn(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new GT({type:"enum",entries:r,...Ze.normalizeParams(t)})}var Eme=L("ZodLiteral",(e,t)=>{lY.init(e,t),qt.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function ce(e,t){return new Eme({type:"literal",values:Array.isArray(e)?e:[e],...Ze.normalizeParams(t)})}var Cme=L("ZodTransform",(e,t)=>{dY.init(e,t),qt.init(e,t),e._zod.parse=(r,n)=>{r.addIssue=i=>{if(typeof i=="string")r.issues.push(Ze.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=e),s.continue??(s.continue=!0),r.issues.push(Ze.issue(s))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function v4(e){return new Cme({type:"transform",transform:e})}var S4=L("ZodOptional",(e,t)=>{pY.init(e,t),qt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ut(e){return new S4({type:"optional",innerType:e})}var Ime=L("ZodNullable",(e,t)=>{fY.init(e,t),qt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function h4(e){return new Ime({type:"nullable",innerType:e})}var xme=L("ZodDefault",(e,t)=>{mY.init(e,t),qt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Ame(e,t){return new xme({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var wme=L("ZodPrefault",(e,t)=>{hY.init(e,t),qt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Tme(e,t){return new wme({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}var _4=L("ZodNonOptional",(e,t)=>{gY.init(e,t),qt.init(e,t),e.unwrap=()=>e._zod.def.innerType});function Ome(e,t){return new _4({type:"nonoptional",innerType:e,...Ze.normalizeParams(t)})}var $me=L("ZodCatch",(e,t)=>{yY.init(e,t),qt.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Rme(e,t){return new $me({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Nme=L("ZodPipe",(e,t)=>{DY.init(e,t),qt.init(e,t),e.in=t.in,e.out=t.out});function VT(e,t){return new Nme({type:"pipe",in:e,out:t})}var kme=L("ZodReadonly",(e,t)=>{bY.init(e,t),qt.init(e,t)});function Fme(e){return new kme({type:"readonly",innerType:e})}var E4=L("ZodCustom",(e,t)=>{vY.init(e,t),qt.init(e,t)});function Pme(e){let t=new Gr({check:"custom"});return t._zod.check=e,t}function C4(e,t){return t4(E4,e??(()=>!0),t)}function Lme(e,t={}){return r4(E4,e,t)}function jme(e){let t=Pme(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(Ze.issue(n,r.value,t._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=t),o.continue??(o.continue=!t._zod.def.abort),r.issues.push(Ze.issue(o))}},e(r.value,r)));return t}function ZT(e,t){return VT(v4(e),t)}co(SY());var XT="2025-11-25";var I4=[XT,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],xs="io.modelcontextprotocol/related-task",Lv="2.0",wr=C4(e=>e!==null&&(typeof e=="object"||typeof e=="function")),x4=bt([P(),st().int()]),A4=P(),R8e=cn({ttl:bt([st(),HT()]).optional(),pollInterval:st().optional()}),Mme=ee({ttl:st().optional()}),Bme=ee({taskId:P()}),QT=cn({progressToken:x4.optional(),[xs]:Bme.optional()}),zn=ee({_meta:QT.optional()}),rm=zn.extend({task:Mme.optional()}),w4=e=>rm.safeParse(e).success,Tr=ee({method:P(),params:zn.loose().optional()}),uo=ee({_meta:QT.optional()}),lo=ee({method:P(),params:uo.loose().optional()}),Or=cn({_meta:QT.optional()}),jv=bt([P(),st().int()]),T4=ee({jsonrpc:ce(Lv),id:jv,...Tr.shape}).strict(),e1=e=>T4.safeParse(e).success,O4=ee({jsonrpc:ce(Lv),...lo.shape}).strict(),$4=e=>O4.safeParse(e).success,t1=ee({jsonrpc:ce(Lv),id:jv,result:Or}).strict(),nm=e=>t1.safeParse(e).success;var Oe;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Oe||(Oe={}));var r1=ee({jsonrpc:ce(Lv),id:jv.optional(),error:ee({code:st().int(),message:P(),data:kt().optional()})}).strict();var R4=e=>r1.safeParse(e).success;var N4=bt([T4,O4,t1,r1]),N8e=bt([t1,r1]),Mv=Or.strict(),Ume=uo.extend({requestId:jv.optional(),reason:P().optional()}),Bv=lo.extend({method:ce("notifications/cancelled"),params:Ume}),qme=ee({src:P(),mimeType:P().optional(),sizes:Be(P()).optional(),theme:Cn(["light","dark"]).optional()}),om=ee({icons:Be(qme).optional()}),qu=ee({name:P(),title:P().optional()}),k4=qu.extend({...qu.shape,...om.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),zme=Fv(ee({applyDefaults:yr().optional()}),Ft(P(),kt())),Yme=ZT(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Fv(ee({form:zme.optional(),url:wr.optional()}),Ft(P(),kt()).optional())),Jme=cn({list:wr.optional(),cancel:wr.optional(),requests:cn({sampling:cn({createMessage:wr.optional()}).optional(),elicitation:cn({create:wr.optional()}).optional()}).optional()}),Gme=cn({list:wr.optional(),cancel:wr.optional(),requests:cn({tools:cn({call:wr.optional()}).optional()}).optional()}),Vme=ee({experimental:Ft(P(),wr).optional(),sampling:ee({context:wr.optional(),tools:wr.optional()}).optional(),elicitation:Yme.optional(),roots:ee({listChanged:yr().optional()}).optional(),tasks:Jme.optional()}),Hme=zn.extend({protocolVersion:P(),capabilities:Vme,clientInfo:k4}),n1=Tr.extend({method:ce("initialize"),params:Hme});var Wme=ee({experimental:Ft(P(),wr).optional(),logging:wr.optional(),completions:wr.optional(),prompts:ee({listChanged:yr().optional()}).optional(),resources:ee({subscribe:yr().optional(),listChanged:yr().optional()}).optional(),tools:ee({listChanged:yr().optional()}).optional(),tasks:Gme.optional()}),Zme=Or.extend({protocolVersion:P(),capabilities:Wme,serverInfo:k4,instructions:P().optional()}),o1=lo.extend({method:ce("notifications/initialized"),params:uo.optional()});var Uv=Tr.extend({method:ce("ping"),params:zn.optional()}),Kme=ee({progress:st(),total:Ut(st()),message:Ut(P())}),Xme=ee({...uo.shape,...Kme.shape,progressToken:x4}),qv=lo.extend({method:ce("notifications/progress"),params:Xme}),Qme=zn.extend({cursor:A4.optional()}),im=Tr.extend({params:Qme.optional()}),sm=Or.extend({nextCursor:A4.optional()}),ehe=Cn(["working","input_required","completed","failed","cancelled"]),am=ee({taskId:P(),status:ehe,ttl:bt([st(),HT()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:Ut(st()),statusMessage:Ut(P())}),zu=Or.extend({task:am}),the=uo.merge(am),cm=lo.extend({method:ce("notifications/tasks/status"),params:the}),zv=Tr.extend({method:ce("tasks/get"),params:zn.extend({taskId:P()})}),Yv=Or.merge(am),Jv=Tr.extend({method:ce("tasks/result"),params:zn.extend({taskId:P()})}),k8e=Or.loose(),Gv=im.extend({method:ce("tasks/list")}),Vv=sm.extend({tasks:Be(am)}),Hv=Tr.extend({method:ce("tasks/cancel"),params:zn.extend({taskId:P()})}),F4=Or.merge(am),P4=ee({uri:P(),mimeType:Ut(P()),_meta:Ft(P(),kt()).optional()}),L4=P4.extend({text:P()}),i1=P().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),j4=P4.extend({blob:i1}),um=Cn(["user","assistant"]),Yu=ee({audience:Be(um).optional(),priority:st().min(0).max(1).optional(),lastModified:em.datetime({offset:!0}).optional()}),M4=ee({...qu.shape,...om.shape,uri:P(),description:Ut(P()),mimeType:Ut(P()),annotations:Yu.optional(),_meta:Ut(cn({}))}),rhe=ee({...qu.shape,...om.shape,uriTemplate:P(),description:Ut(P()),mimeType:Ut(P()),annotations:Yu.optional(),_meta:Ut(cn({}))}),s1=im.extend({method:ce("resources/list")}),nhe=sm.extend({resources:Be(M4)}),ohe=im.extend({method:ce("resources/templates/list")}),ihe=sm.extend({resourceTemplates:Be(rhe)}),a1=zn.extend({uri:P()}),she=a1,c1=Tr.extend({method:ce("resources/read"),params:she}),ahe=Or.extend({contents:Be(bt([L4,j4]))}),che=lo.extend({method:ce("notifications/resources/list_changed"),params:uo.optional()}),uhe=a1,lhe=Tr.extend({method:ce("resources/subscribe"),params:uhe}),dhe=a1,phe=Tr.extend({method:ce("resources/unsubscribe"),params:dhe}),fhe=uo.extend({uri:P()}),mhe=lo.extend({method:ce("notifications/resources/updated"),params:fhe}),hhe=ee({name:P(),description:Ut(P()),required:Ut(yr())}),ghe=ee({...qu.shape,...om.shape,description:Ut(P()),arguments:Ut(Be(hhe)),_meta:Ut(cn({}))}),yhe=im.extend({method:ce("prompts/list")}),Dhe=sm.extend({prompts:Be(ghe)}),bhe=zn.extend({name:P(),arguments:Ft(P(),P()).optional()}),vhe=Tr.extend({method:ce("prompts/get"),params:bhe}),u1=ee({type:ce("text"),text:P(),annotations:Yu.optional(),_meta:Ft(P(),kt()).optional()}),l1=ee({type:ce("image"),data:i1,mimeType:P(),annotations:Yu.optional(),_meta:Ft(P(),kt()).optional()}),d1=ee({type:ce("audio"),data:i1,mimeType:P(),annotations:Yu.optional(),_meta:Ft(P(),kt()).optional()}),She=ee({type:ce("tool_use"),name:P(),id:P(),input:Ft(P(),kt()),_meta:Ft(P(),kt()).optional()}),_he=ee({type:ce("resource"),resource:bt([L4,j4]),annotations:Yu.optional(),_meta:Ft(P(),kt()).optional()}),Ehe=M4.extend({type:ce("resource_link")}),p1=bt([u1,l1,d1,Ehe,_he]),Che=ee({role:um,content:p1}),Ihe=Or.extend({description:P().optional(),messages:Be(Che)}),xhe=lo.extend({method:ce("notifications/prompts/list_changed"),params:uo.optional()}),Ahe=ee({title:P().optional(),readOnlyHint:yr().optional(),destructiveHint:yr().optional(),idempotentHint:yr().optional(),openWorldHint:yr().optional()}),whe=ee({taskSupport:Cn(["required","optional","forbidden"]).optional()}),B4=ee({...qu.shape,...om.shape,description:P().optional(),inputSchema:ee({type:ce("object"),properties:Ft(P(),wr).optional(),required:Be(P()).optional()}).catchall(kt()),outputSchema:ee({type:ce("object"),properties:Ft(P(),wr).optional(),required:Be(P()).optional()}).catchall(kt()).optional(),annotations:Ahe.optional(),execution:whe.optional(),_meta:Ft(P(),kt()).optional()}),f1=im.extend({method:ce("tools/list")}),The=sm.extend({tools:Be(B4)}),Wv=Or.extend({content:Be(p1).default([]),structuredContent:Ft(P(),kt()).optional(),isError:yr().optional()}),F8e=Wv.or(Or.extend({toolResult:kt()})),Ohe=rm.extend({name:P(),arguments:Ft(P(),kt()).optional()}),lm=Tr.extend({method:ce("tools/call"),params:Ohe}),$he=lo.extend({method:ce("notifications/tools/list_changed"),params:uo.optional()}),P8e=ee({autoRefresh:yr().default(!0),debounceMs:st().int().nonnegative().default(300)}),dm=Cn(["debug","info","notice","warning","error","critical","alert","emergency"]),Rhe=zn.extend({level:dm}),m1=Tr.extend({method:ce("logging/setLevel"),params:Rhe}),Nhe=uo.extend({level:dm,logger:P().optional(),data:kt()}),khe=lo.extend({method:ce("notifications/message"),params:Nhe}),Fhe=ee({name:P().optional()}),Phe=ee({hints:Be(Fhe).optional(),costPriority:st().min(0).max(1).optional(),speedPriority:st().min(0).max(1).optional(),intelligencePriority:st().min(0).max(1).optional()}),Lhe=ee({mode:Cn(["auto","required","none"]).optional()}),jhe=ee({type:ce("tool_result"),toolUseId:P().describe("The unique identifier for the corresponding tool call."),content:Be(p1).default([]),structuredContent:ee({}).loose().optional(),isError:yr().optional(),_meta:Ft(P(),kt()).optional()}),Mhe=WT("type",[u1,l1,d1]),Pv=WT("type",[u1,l1,d1,She,jhe]),Bhe=ee({role:um,content:bt([Pv,Be(Pv)]),_meta:Ft(P(),kt()).optional()}),Uhe=rm.extend({messages:Be(Bhe),modelPreferences:Phe.optional(),systemPrompt:P().optional(),includeContext:Cn(["none","thisServer","allServers"]).optional(),temperature:st().optional(),maxTokens:st().int(),stopSequences:Be(P()).optional(),metadata:wr.optional(),tools:Be(B4).optional(),toolChoice:Lhe.optional()}),qhe=Tr.extend({method:ce("sampling/createMessage"),params:Uhe}),pm=Or.extend({model:P(),stopReason:Ut(Cn(["endTurn","stopSequence","maxTokens"]).or(P())),role:um,content:Mhe}),h1=Or.extend({model:P(),stopReason:Ut(Cn(["endTurn","stopSequence","maxTokens","toolUse"]).or(P())),role:um,content:bt([Pv,Be(Pv)])}),zhe=ee({type:ce("boolean"),title:P().optional(),description:P().optional(),default:yr().optional()}),Yhe=ee({type:ce("string"),title:P().optional(),description:P().optional(),minLength:st().optional(),maxLength:st().optional(),format:Cn(["email","uri","date","date-time"]).optional(),default:P().optional()}),Jhe=ee({type:Cn(["number","integer"]),title:P().optional(),description:P().optional(),minimum:st().optional(),maximum:st().optional(),default:st().optional()}),Ghe=ee({type:ce("string"),title:P().optional(),description:P().optional(),enum:Be(P()),default:P().optional()}),Vhe=ee({type:ce("string"),title:P().optional(),description:P().optional(),oneOf:Be(ee({const:P(),title:P()})),default:P().optional()}),Hhe=ee({type:ce("string"),title:P().optional(),description:P().optional(),enum:Be(P()),enumNames:Be(P()).optional(),default:P().optional()}),Whe=bt([Ghe,Vhe]),Zhe=ee({type:ce("array"),title:P().optional(),description:P().optional(),minItems:st().optional(),maxItems:st().optional(),items:ee({type:ce("string"),enum:Be(P())}),default:Be(P()).optional()}),Khe=ee({type:ce("array"),title:P().optional(),description:P().optional(),minItems:st().optional(),maxItems:st().optional(),items:ee({anyOf:Be(ee({const:P(),title:P()}))}),default:Be(P()).optional()}),Xhe=bt([Zhe,Khe]),Qhe=bt([Hhe,Whe,Xhe]),ege=bt([Qhe,zhe,Yhe,Jhe]),tge=rm.extend({mode:ce("form").optional(),message:P(),requestedSchema:ee({type:ce("object"),properties:Ft(P(),ege),required:Be(P()).optional()})}),rge=rm.extend({mode:ce("url"),message:P(),elicitationId:P(),url:P().url()}),nge=bt([tge,rge]),oge=Tr.extend({method:ce("elicitation/create"),params:nge}),ige=uo.extend({elicitationId:P()}),sge=lo.extend({method:ce("notifications/elicitation/complete"),params:ige}),Ju=Or.extend({action:Cn(["accept","decline","cancel"]),content:ZT(e=>e===null?void 0:e,Ft(P(),bt([P(),st(),yr(),Be(P())])).optional())}),age=ee({type:ce("ref/resource"),uri:P()});var cge=ee({type:ce("ref/prompt"),name:P()}),uge=zn.extend({ref:bt([cge,age]),argument:ee({name:P(),value:P()}),context:ee({arguments:Ft(P(),P()).optional()}).optional()}),lge=Tr.extend({method:ce("completion/complete"),params:uge});var dge=Or.extend({completion:cn({values:Be(P()).max(100),total:Ut(st().int()),hasMore:Ut(yr())})}),pge=ee({uri:P().startsWith("file://"),name:P().optional(),_meta:Ft(P(),kt()).optional()}),fge=Tr.extend({method:ce("roots/list"),params:zn.optional()}),g1=Or.extend({roots:Be(pge)}),mge=lo.extend({method:ce("notifications/roots/list_changed"),params:uo.optional()}),L8e=bt([Uv,n1,lge,m1,vhe,yhe,s1,ohe,c1,lhe,phe,lm,f1,zv,Jv,Gv,Hv]),j8e=bt([Bv,qv,o1,mge,cm]),M8e=bt([Mv,pm,h1,Ju,g1,Yv,Vv,zu]),B8e=bt([Uv,qhe,oge,fge,zv,Jv,Gv,Hv]),U8e=bt([Bv,qv,khe,mhe,che,$he,xhe,cm,sge]),q8e=bt([Mv,Zme,dge,Ihe,Dhe,nhe,ihe,ahe,Wv,The,Yv,Vv,zu]),Ce=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===Oe.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new KT(o.elicitations,r)}return new e(t,r,n)}},KT=class extends Ce{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(Oe.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};function As(e){return e==="completed"||e==="failed"||e==="cancelled"}var S9e=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function y1(e){let r=Nv(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=n4(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function D1(e,t){let r=Is(e,t);if(!r.success)throw r.error;return r.data}var vge=6e4,Zv=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Bv,r=>{this._oncancel(r)}),this.setNotificationHandler(qv,r=>{this._onprogress(r)}),this.setRequestHandler(Uv,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(zv,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Ce(Oe.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Jv,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,f=new Ce(d.error.code,d.error.message,d.error.data);l(f)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new Ce(Oe.InvalidParams,`Task not found: ${i}`);if(!As(s.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(As(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...a,_meta:{...a._meta,[xs]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(Gv,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new Ce(Oe.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Hv,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Ce(Oe.InvalidParams,`Task not found: ${r.params.taskId}`);if(As(o.status))throw new Ce(Oe.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new Ce(Oe.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof Ce?o:new Ce(Oe.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),Ce.fromError(Oe.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),nm(i)||R4(i)?this._onresponse(i):e1(i)?this._onrequest(i,s):$4(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=Ce.fromError(Oe.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[xs]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:Oe.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let s=new AbortController;this._requestHandlerAbortControllers.set(t.id,s);let a=w4(t.params)?t.params.task:void 0,c=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,u={signal:s.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async l=>{if(s.signal.aborted)return;let d={relatedRequestId:t.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(s.signal.aborted)throw new Ce(Oe.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:t.id};i&&!p.relatedTask&&(p.relatedTask={taskId:i});let m=p.relatedTask?.taskId??i;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,p)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,u)).then(async l=>{if(s.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(s.signal.aborted)return;let d={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:Oe.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),nm(t))n(t);else{let s=new Ce(t.error.code,t.error.message,t.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(nm(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),nm(t))o(t);else{let s=Ce.fromError(t.error.code,t.error.message,t.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof Ce?s:new Ce(Oe.InternalError,String(s))}}return}let i;try{let s=await this.request(t,zu,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new Ce(Oe.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},As(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new Ce(Oe.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Ce(Oe.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof Ce?s:new Ce(Oe.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=v=>{l(v)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(v){d(v);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:f}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[xs]:c}});let m=v=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(v)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let y=v instanceof Ce?v:new Ce(Oe.RequestTimeout,String(v));l(y)};this._responseHandlers.set(f,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let y=Is(r,v.result);y.success?u(y.data):l(y.error)}catch(y){l(y)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??vge,g=()=>m(Ce.fromError(Oe.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let D=c?.taskId;if(D){let v=y=>{let b=this._responseHandlers.get(f);b?b(y):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,v),this._enqueueTaskMessage(D,{type:"request",message:p,timestamp:Date.now()}).catch(y=>{this._cleanupTimeout(f),l(y)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(v=>{this._cleanupTimeout(f),l(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Yv,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Vv,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},F4,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[xs]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[xs]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[xs]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=y1(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=D1(t,o);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=y1(t);this._notificationHandlers.set(n,o=>{let i=D1(t,o);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&e1(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new Ce(Oe.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(t);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new Ce(Oe.InvalidRequest,"Request cancelled"));return}let s=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new Ce(Oe.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new Ce(Oe.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=cm.parse({method:"notifications/tasks/status",params:a});await this.notification(c),As(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new Ce(Oe.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(As(a.status))throw new Ce(Oe.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let u=cm.parse({method:"notifications/tasks/status",params:c});await this.notification(u),As(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function U4(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function q4(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];U4(s)&&U4(i)?r[o]={...s,...i}:r[o]=i}return r}var wJ=vt(n$(),1),TJ=vt(AJ(),1);function dSe(){let e=new wJ.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,TJ.default)(e),e}var RS=class{constructor(t){this._ajv=t??dSe()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var NS=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(l=>l.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(i.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==d.size||![...l].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},pm,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},Ju,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function OJ(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function $J(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var kS=class extends Zv{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(dm.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new RS,this.setRequestHandler(n1,n=>this._oninitialize(n)),this.setNotificationHandler(o1,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(m1,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=dm.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new NS(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=q4(this._capabilities,t)}setRequestHandler(t,r){let o=Nv(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Uu(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,u)=>{let l=Is(lm,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new Ce(Oe.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let m=Is(zu,f);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new Ce(Oe.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let p=Is(Wv,f);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new Ce(Oe.InvalidParams,`Invalid tools/call result: ${m}`)}return p.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){$J(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&OJ(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:I4.includes(r)?r:XT,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Mv)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(u=>u.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(u=>u.type==="tool_use");if(i){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},h1,r):this.request({method:"sampling/createMessage",params:t},pm,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},Ju,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Ju,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new Ce(Oe.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof Ce?s:new Ce(Oe.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},g1,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};import NJ from"node:process";var FS=class{append(t){this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
680
680
  `);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),pSe(r)}clear(){this._buffer=void 0}};function pSe(e){return N4.parse(JSON.parse(e))}function RJ(e){return JSON.stringify(e)+`
681
- `}var PS=class{constructor(t=NJ.stdin,r=NJ.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new FS,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=RJ(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Yi=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","SALE_PAYMENT","PURCHASE_PAYMENT","BATCH_PAYMENT","CONTACT","ITEM","CAPSULE","SCHEDULED_TRANSACTION","JOURNAL","BANK_RECORD","CASHFLOW_TRANSACTION","FIXED_ASSET","CHART_OF_ACCOUNT","TAX_PROFILE"];Xi();kD();async function kJ(e,t){let n=(await ms((s,a)=>Ti(e,{offset:s,limit:a}))).data;if(n.length===0)return{mapping:{},failures:t.map(s=>({name:s,candidates:[]}))};let o={},i=[];for(let s of t){let a=yb(s,n);if(a)o[s]=a.resourceId;else{let c=Du(s,n,{threshold:.3,limit:3});i.push({name:s,candidates:c.map(u=>u.item.name)})}}return{mapping:o,failures:i}}async function FJ(e,t){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){let l=(await va(e,t)).data;return{resourceId:l.resourceId,displayName:l.billingName||l.name||"Unknown"}}let n=t.trim(),i=(await ro(e,{filter:{billingName:{contains:n}},limit:50})).data;if(i.length===0&&(i=(await ns(e,{offset:0,limit:500})).data),i.length===0)throw new Error("No contacts found. Create one in Jaz first.");let s=n.toLowerCase(),a=i.find(u=>u.billingName?.toLowerCase()===s||u.name?.toLowerCase()===s);if(a)return{resourceId:a.resourceId,displayName:a.billingName||a.name||"Unknown"};let c=Db(n,i,{threshold:.5,limit:5});if(c.length>=1&&c[0].score>=.7){let u=c[0],l=c.length>1?c[1].score:0;if(c.length===1||u.score-l>=.1){let d=u.item;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}}if(c.length>1){let u=c.map(l=>`${l.item.billingName||l.item.name} (${(l.score*100).toFixed(0)}%)`).join(", ");throw new Error(`Multiple contacts match "${n}": ${u}. Be more specific.`)}throw new Error(`No contact matching "${n}".`)}async function PJ(e,t){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){let o=await Yc(e,t);return{resourceId:o.data.resourceId,displayName:o.data.name}}let n=await ya(e,t);return{resourceId:n.resourceId,displayName:n.name}}async function LS(e,t){return e.list("/api/v1/bank-rules",t)}async function zm(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let o=r;if(o?.data&&typeof o.data=="object"&&o.data!==null&&"resourceId"in o.data)return{data:o.data};throw new Error(`Unexpected response shape from GET /bank-rules/${t}`)}async function jS(e,t){return e.search("/api/v1/bank-rules/search",t)}async function MS(e,t){return e.post("/api/v1/bank-rules",t)}async function BS(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function US(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}async function qS(e,t){return e.list("/api/v1/fixed-assets",t)}async function zS(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function YS(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function JS(e,t){return e.post("/api/v1/fixed-assets",t)}async function GS(e,t,r){return e.put(`/api/v1/fixed-assets/${t}`,r)}async function VS(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function HS(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t})}async function Ym(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t)}async function WS(e,t){return e.post("/api/v1/transfer-fixed-assets",t)}async function ZS(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{})}async function KS(e,t){return zr(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}async function XS(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function Jm(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function QS(e,t){return e.post("/api/v1/scheduled/subscriptions",t)}async function e_(e,t,r){let n={...r};if(n.endDate){let o=!n.startDate,i=!n.repeat&&!n.interval;if(o||i){let s=await Jm(e,t);if(o&&(n.startDate=s.data.startDate),i){if(!s.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=s.data.interval}}}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}async function t_(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function r_(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function n_(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}async function o_(e,t){return e.list("/api/v1/contact-groups",t)}async function i_(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function s_(e,t){return e.search("/api/v1/contact-groups/search",t)}async function a_(e,t){return e.post("/api/v1/contact-groups",t)}async function c_(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,r)}async function u_(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}async function l_(e,t){return e.list("/api/v1/inventory-items",t)}async function d_(e,t){return e.post("/api/v1/inventory-items",t)}async function p_(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function f_(e,t){return e.list("/api/v1/custom-fields",t)}async function m_(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function h_(e,t){return e.search("/api/v1/custom-fields/search",t)}async function g_(e,t){return e.post("/api/v1/custom-fields",t)}async function y_(e,t,r){return e.put(`/api/v1/custom-fields/${t}`,r)}async function D_(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var fSe=["invoices","bills","customer-credit-notes","supplier-credit-notes"],mSe=["journals","cash-entries"],hSe=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],ul=[...fSe,...mSe,...hSe];function LJ(e){return{updated:e.updated??[],failed:(e.failed??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}}async function Gm(e,t,r){let n=await e.post(`/api/v1/quick-fix/${t}`,r);return LJ(n)}async function Vm(e,t,r){let n=await e.post(`/api/v1/quick-fix/${t}/line-items`,r);return LJ(n)}async function b_(e,t){return e.list("/api/v1/nano-classifiers",t)}async function v_(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function S_(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function Hm(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function Wm(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,r)}async function __(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}async function E_(e,t){return e.post("/api/v1/export-records",t)}async function C_(e,t){return e.post("/api/v1/export-records/preview",t)}async function I_(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}async function Zm(e,t={}){return e.search("/api/v1/background-jobs/search",t)}var gSe=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"]);function ll(e){er(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!gSe.has(n.btType))throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.`)})}async function x_(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t});return{data:DSe(r.data)}}function ySe(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function DSe(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(ySe),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function A_(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function w_(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}function d$(e,t){if(!e||typeof e!="object")throw new Error(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${t}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${t}.lineItems per call.`);eo([r],["valueDate","dueDate"]);let o=r.recordedPayment;o&&typeof o=="object"&&eo([o],["valueDate"])}async function T_(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t)}async function O_(e,t){return e.post("/api/v1/reconciliations/bank-rule",t)}async function $_(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t)}async function R_(e,t){return e.post("/api/v1/reconciliations/cash-journal",t)}async function N_(e,t){return e.post("/api/v1/reconciliations/manual-journal",t)}async function k_(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t)}async function F_(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t)}async function P_(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t)}var Km="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",pi="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails.";var th={type:"string",description:"Resource ID of the record"},go={type:"string",description:"Transaction date (YYYY-MM-DD)"},Xm={type:"string",description:"Due date (YYYY-MM-DD)"},yo={type:"string",description:"Reference number"},Dr={type:"string",description:"Notes or memo text"},dl={type:"string",description:"Tag name for categorization"};var jJ={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},bSe={type:"string",description:"Contact resourceId (customer or supplier)"},rc={type:"string",description:"Bank/cash account resourceId"},vSe={type:"number",description:"Payment amount (in bank currency)"},SSe={type:"string",description:"Period start date (YYYY-MM-DD)"},p$={type:"string",description:"Period end date (YYYY-MM-DD)"},MJ={type:"string",description:"Currency code (e.g. SGD, USD)"},f$={type:"string",description:"Display name"},h$={limit:{type:"number",description:"Max results per page (default 20, max 1000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},ec={type:"object",properties:{sourceCurrency:{type:"string"},exchangeRate:{type:"number"}}},m$={type:"string",enum:[...Yi],description:"Entity type to export"},BJ={type:"string",description:'Structured search query using dashboard syntax (e.g., "status:unpaid $500+ date:this month"). Mutually exclusive with filter \u2014 pass one or the other, never both.'},UJ={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},qJ={type:"array",items:{type:"object",properties:{path:{type:"string",description:"Column path from get_export_columns (e.g., s.reference)"},header:{type:"string",description:"Column header label in the export file"},type:{type:"string",enum:["STRING","NUMBER","CURRENCY","DATE","BOOLEAN"],description:"Column data type (optional)"}},required:["path","header"]},description:"Custom column definitions. Omit to use default columns. Use get_export_columns to discover available paths."},zJ={type:"object",properties:{field:{type:"string",description:"Column path to sort by (e.g., s.total_amount)"},direction:{type:"string",enum:["ASC","DESC"],description:"Sort direction"}},required:["field"],description:"Sort results by a column path."},dn={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},_Se={type:"array",items:{type:"object",properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",properties:{className:{type:"string"},resourceId:th}}},printable:{type:"boolean"}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},tc={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account resourceId"},type:{type:"string",enum:["DEBIT","CREDIT"],description:"Debit or credit"},amount:{type:"number",description:"Amount"},description:{type:"string",description:"Line description"}},required:["accountResourceId","type","amount"]},description:"Journal entries (debit/credit lines with accountResourceId, type, amount)"},fi={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:rc,taxProfileResourceId:{type:"string"},classifierConfig:_Se},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},Qm={type:"string",enum:[...X3],description:"Payment method (default BANK_TRANSFER)"};function GJ(e){let t=e.limit,r=e.offset;return{limit:t,offset:r,sortBy:void 0,sortOrder:void 0}}function gt(e,t,r,n,o){return{name:e,description:t,params:{...h$},required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...o?{searchHint:o}:{},execute:async(i,s)=>{let{limit:a,offset:c}=GJ(s);return Lp((u,l)=>n(i.client,u,l),a,c,20)}}}function Yn(e,t,r,n,o){return{name:e,description:t,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...o?{searchHint:o}:{},execute:async(i,s)=>n(i.client,s.resourceId)}}function pn(e,t,r,n,o){return{name:e,description:t,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...o?{searchHint:o}:{},execute:async(i,s)=>(await n(i.client,s.resourceId),{deleted:!0,resourceId:s.resourceId})}}var ESe={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","taxProfileResourceId"]),customer_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"]),supplier_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"])};function YJ(e){if(typeof e!="string"||/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let t=/^(\d{4}-\d{2}-\d{2})T/.exec(e);return t?t[1]:e}var CSe=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);function ISe(e){return Array.isArray(e)?e.map(t=>{let r={};for(let[n,o]of Object.entries(t))if(o!=null)if(n==="organizationAccountResourceId")r.accountResourceId=o;else if(n==="taxProfile"&&typeof o=="object"&&o!==null){let i=o.resourceId;i&&(r.taxProfileResourceId=i)}else if(n==="discount"&&typeof o=="object"&&o!==null){let i=o.rateValue;i&&Number(i)!==0&&(r.discount=o)}else CSe.has(n)&&(r[n]=o);return r}):e}async function eh(e,t,r,n){let s=(await(t==="invoice"?io:t==="bill"?to:t==="customer_credit_note"?Ro:No)(e,r)).data,a=ESe[t],c={};for(let[f,p]of Object.entries(s))a.has(f)&&p!==null&&p!==void 0&&(c[f]=p);c.valueDate&&(c.valueDate=YJ(c.valueDate)),c.dueDate&&(c.dueDate=YJ(c.dueDate)),c.lineItems&&(c.lineItems=ISe(c.lineItems));for(let[f,p]of Object.entries(n))p!==void 0&&(c[f]=p);let u=t==="invoice"?so:t==="bill"?En:lr,{missingFields:l,ready:d}=an(c,u);if(!d)throw new Error(`Cannot finalize: missing ${l.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function JJ(e,t,r,n){if((await e(t,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}var pl=[{name:"get_organization",description:"Get organization details (name, currency, country, lock date, fiscal year end).",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>Pn(e.client)},gt("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(e,t,r)=>Ti(e,{limit:r,offset:t}),"list chart of accounts with code type class status"),Rt({name:"search_accounts",description:'Search chart of accounts by name, code, class, type, status. For OR search (name or code), use filter param: {"or":{"name":{"contains":"X"},"code":{"contains":"X"}}}.',group:"accounts",fields:nf,defaults:of,fetcher:yu,searchHint:"find accounts by name code type class status"}),{name:"create_account",description:"Create a new chart of accounts entry. Auto-checks for duplicates by name \u2014 returns existing account if found. Code must be unique. Account class is inferred from accountType.",params:{name:{type:"string",description:"Account name"},code:{type:"string",description:"Account code (unique)"},accountType:{type:"string",description:'Exact API string. Classic 12: Bank Accounts | Cash | Current Asset | Fixed Asset | Inventory | Current Liability | Non-current Liability | Shareholders Equity | Operating Revenue | Other Revenue | Operating Expense | Direct Costs. IFRS 18 (effective 2027): Discontinued Expense | Discontinued Income | Finance Cost | Financing Income | Goodwill | Income Tax Expense | Investing Expense | Investing Income | Investment. Common variants normalized client-side. For "interest expense"/"interest income", pick Financing or Investing yourself \u2014 depends on entity main business activity, NOT auto-classified.'},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code",execute:async(e,t)=>{let r=t.name,n=await db(e.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let o=gu(t.accountType);return bp(e.client,{code:t.code,name:r,accountType:o,currencyCode:t.currencyCode})}},{name:"update_account",description:"Update an existing chart of accounts entry (name or code).",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code",execute:async(e,t)=>{let r=t.resourceId,n=(await Yz(e.client,r)).data,i=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(s=>n[s]!==void 0&&n[s]!==null).map(s=>[s,n[s]]));return!i.classificationType&&n.accountType&&(i.classificationType=n.accountType),t.name!==void 0&&(i.name=t.name),t.code!==void 0&&(i.code=t.code),Jz(e.client,r,i)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount } \u2014 no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
681
+ `}var PS=class{constructor(t=NJ.stdin,r=NJ.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new FS,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=RJ(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var Yi=["INVOICE","BILL","CUSTOMER_CREDIT_NOTE","SUPPLIER_CREDIT_NOTE","SALE_PAYMENT","PURCHASE_PAYMENT","BATCH_PAYMENT","CONTACT","ITEM","CAPSULE","SCHEDULED_TRANSACTION","JOURNAL","BANK_RECORD","CASHFLOW_TRANSACTION","FIXED_ASSET","CHART_OF_ACCOUNT","TAX_PROFILE"];Xi();kD();async function kJ(e,t){let n=(await ms((s,a)=>Ti(e,{offset:s,limit:a}))).data;if(n.length===0)return{mapping:{},failures:t.map(s=>({name:s,candidates:[]}))};let o={},i=[];for(let s of t){let a=yb(s,n);if(a)o[s]=a.resourceId;else{let c=Du(s,n,{threshold:.3,limit:3});i.push({name:s,candidates:c.map(u=>u.item.name)})}}return{mapping:o,failures:i}}async function FJ(e,t){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){let l=(await va(e,t)).data;return{resourceId:l.resourceId,displayName:l.billingName||l.name||"Unknown"}}let n=t.trim(),i=(await ro(e,{filter:{billingName:{contains:n}},limit:50})).data;if(i.length===0&&(i=(await ns(e,{offset:0,limit:500})).data),i.length===0)throw new Error("No contacts found. Create one in Jaz first.");let s=n.toLowerCase(),a=i.find(u=>u.billingName?.toLowerCase()===s||u.name?.toLowerCase()===s);if(a)return{resourceId:a.resourceId,displayName:a.billingName||a.name||"Unknown"};let c=Db(n,i,{threshold:.5,limit:5});if(c.length>=1&&c[0].score>=.7){let u=c[0],l=c.length>1?c[1].score:0;if(c.length===1||u.score-l>=.1){let d=u.item;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}}if(c.length>1){let u=c.map(l=>`${l.item.billingName||l.item.name} (${(l.score*100).toFixed(0)}%)`).join(", ");throw new Error(`Multiple contacts match "${n}": ${u}. Be more specific.`)}throw new Error(`No contact matching "${n}".`)}async function PJ(e,t){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){let o=await Yc(e,t);return{resourceId:o.data.resourceId,displayName:o.data.name}}let n=await ya(e,t);return{resourceId:n.resourceId,displayName:n.name}}async function LS(e,t){return e.list("/api/v1/bank-rules",t)}async function zm(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let o=r;if(o?.data&&typeof o.data=="object"&&o.data!==null&&"resourceId"in o.data)return{data:o.data};throw new Error(`Unexpected response shape from GET /bank-rules/${t}`)}async function jS(e,t){return e.search("/api/v1/bank-rules/search",t)}async function MS(e,t){return e.post("/api/v1/bank-rules",t)}async function BS(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function US(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}async function qS(e,t){return e.list("/api/v1/fixed-assets",t)}async function zS(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function YS(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function JS(e,t){return e.post("/api/v1/fixed-assets",t)}async function GS(e,t,r){return e.put(`/api/v1/fixed-assets/${t}`,r)}async function VS(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function HS(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t})}async function Ym(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t)}async function WS(e,t){return e.post("/api/v1/transfer-fixed-assets",t)}async function ZS(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{})}async function KS(e,t){return zr(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}async function XS(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function Jm(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function QS(e,t){return e.post("/api/v1/scheduled/subscriptions",t)}async function e_(e,t,r){let n={...r};if(n.endDate){let o=!n.startDate,i=!n.repeat&&!n.interval;if(o||i){let s=await Jm(e,t);if(o&&(n.startDate=s.data.startDate),i){if(!s.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=s.data.interval}}}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}async function t_(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function r_(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function n_(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}async function o_(e,t){return e.list("/api/v1/contact-groups",t)}async function i_(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function s_(e,t){return e.search("/api/v1/contact-groups/search",t)}async function a_(e,t){return e.post("/api/v1/contact-groups",t)}async function c_(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,r)}async function u_(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}async function l_(e,t){return e.list("/api/v1/inventory-items",t)}async function d_(e,t){return e.post("/api/v1/inventory-items",t)}async function p_(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}async function f_(e,t){return e.list("/api/v1/custom-fields",t)}async function m_(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function h_(e,t){return e.search("/api/v1/custom-fields/search",t)}async function g_(e,t){return e.post("/api/v1/custom-fields",t)}async function y_(e,t,r){return e.put(`/api/v1/custom-fields/${t}`,r)}async function D_(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var fSe=["invoices","bills","customer-credit-notes","supplier-credit-notes"],mSe=["journals","cash-entries"],hSe=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],ul=[...fSe,...mSe,...hSe];function LJ(e){return{updated:e.updated??[],failed:(e.failed??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}}async function Gm(e,t,r){let n=await e.post(`/api/v1/quick-fix/${t}`,r);return LJ(n)}async function Vm(e,t,r){let n=await e.post(`/api/v1/quick-fix/${t}/line-items`,r);return LJ(n)}async function b_(e,t){return e.list("/api/v1/nano-classifiers",t)}async function v_(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function S_(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function Hm(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function Wm(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,r)}async function __(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}async function E_(e,t){return e.post("/api/v1/export-records",t)}async function C_(e,t){return e.post("/api/v1/export-records/preview",t)}async function I_(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}async function Zm(e,t={}){return e.search("/api/v1/background-jobs/search",t)}var gSe=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"]);function ll(e){er(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!gSe.has(n.btType))throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.`)})}async function x_(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t});return{data:DSe(r.data)}}function ySe(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function DSe(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(ySe),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function A_(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function w_(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}function d$(e,t){if(!e||typeof e!="object")throw new Error(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${t}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${t}.lineItems per call.`);eo([r],["valueDate","dueDate"]);let o=r.recordedPayment;o&&typeof o=="object"&&eo([o],["valueDate"])}async function T_(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t)}async function O_(e,t){return e.post("/api/v1/reconciliations/bank-rule",t)}async function $_(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t)}async function R_(e,t){return e.post("/api/v1/reconciliations/cash-journal",t)}async function N_(e,t){return e.post("/api/v1/reconciliations/manual-journal",t)}async function k_(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t)}async function F_(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t)}async function P_(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t)}var Km="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",pi="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails.";var th={type:"string",description:"Resource ID of the record"},go={type:"string",description:"Transaction date (YYYY-MM-DD)"},Xm={type:"string",description:"Due date (YYYY-MM-DD)"},yo={type:"string",description:"Reference number"},Dr={type:"string",description:"Notes or memo text"},dl={type:"string",description:"Tag name for categorization"};var jJ={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},bSe={type:"string",description:"Contact resourceId (customer or supplier)"},rc={type:"string",description:"Bank/cash account resourceId"},vSe={type:"number",description:"Payment amount (in bank currency)"},SSe={type:"string",description:"Period start date (YYYY-MM-DD)"},p$={type:"string",description:"Period end date (YYYY-MM-DD)"},MJ={type:"string",description:"Currency code (e.g. SGD, USD)"},f$={type:"string",description:"Display name"},h$={limit:{type:"number",description:"Max results per page (default 20, max 1000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},ec={type:"object",properties:{sourceCurrency:{type:"string"},exchangeRate:{type:"number"}}},m$={type:"string",enum:[...Yi],description:"Entity type to export"},BJ={type:"string",description:'Structured search query using dashboard syntax (e.g., "status:unpaid $500+ date:this month"). Mutually exclusive with filter \u2014 pass one or the other, never both.'},UJ={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},qJ={type:"array",items:{type:"object",properties:{path:{type:"string",description:"Column path from get_export_columns (e.g., s.reference)"},header:{type:"string",description:"Column header label in the export file"},type:{type:"string",enum:["STRING","NUMBER","CURRENCY","DATE","BOOLEAN"],description:"Column data type (optional)"}},required:["path","header"]},description:"Custom column definitions. Omit to use default columns. Use get_export_columns to discover available paths."},zJ={type:"object",properties:{field:{type:"string",description:"Column path to sort by (e.g., s.total_amount)"},direction:{type:"string",enum:["ASC","DESC"],description:"Sort direction"}},required:["field"],description:"Sort results by a column path."},dn={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},_Se={type:"array",items:{type:"object",properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",properties:{className:{type:"string"},resourceId:th}}},printable:{type:"boolean"}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},tc={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account resourceId"},type:{type:"string",enum:["DEBIT","CREDIT"],description:"Debit or credit"},amount:{type:"number",description:"Amount"},description:{type:"string",description:"Line description"}},required:["accountResourceId","type","amount"]},description:"Journal entries (debit/credit lines with accountResourceId, type, amount)"},fi={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:rc,taxProfileResourceId:{type:"string"},classifierConfig:_Se},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},Qm={type:"string",enum:[...X3],description:"Payment method (default BANK_TRANSFER)"};function GJ(e){let t=e.limit,r=e.offset;return{limit:t,offset:r,sortBy:void 0,sortOrder:void 0}}function gt(e,t,r,n,o){return{name:e,description:t,params:{...h$},required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...o?{searchHint:o}:{},execute:async(i,s)=>{let{limit:a,offset:c}=GJ(s);return Lp((u,l)=>n(i.client,u,l),a,c,20)}}}function Yn(e,t,r,n,o){return{name:e,description:t,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...o?{searchHint:o}:{},execute:async(i,s)=>n(i.client,s.resourceId)}}function pn(e,t,r,n,o){return{name:e,description:t,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...o?{searchHint:o}:{},execute:async(i,s)=>(await n(i.client,s.resourceId),{deleted:!0,resourceId:s.resourceId})}}var ESe={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","taxProfileResourceId"]),customer_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"]),supplier_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"])};function YJ(e){if(typeof e!="string"||/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let t=/^(\d{4}-\d{2}-\d{2})T/.exec(e);return t?t[1]:e}var CSe=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);function ISe(e){return Array.isArray(e)?e.map(t=>{let r={};for(let[n,o]of Object.entries(t))if(o!=null)if(n==="organizationAccountResourceId")r.accountResourceId=o;else if(n==="taxProfile"&&typeof o=="object"&&o!==null){let i=o.resourceId;i&&(r.taxProfileResourceId=i)}else if(n==="discount"&&typeof o=="object"&&o!==null){let i=o.rateValue;i&&Number(i)!==0&&(r.discount=o)}else CSe.has(n)&&(r[n]=o);return r}):e}async function eh(e,t,r,n){let s=(await(t==="invoice"?io:t==="bill"?to:t==="customer_credit_note"?Ro:No)(e,r)).data,a=ESe[t],c={};for(let[f,p]of Object.entries(s))a.has(f)&&p!==null&&p!==void 0&&(c[f]=p);c.valueDate&&(c.valueDate=YJ(c.valueDate)),c.dueDate&&(c.dueDate=YJ(c.dueDate)),c.lineItems&&(c.lineItems=ISe(c.lineItems));for(let[f,p]of Object.entries(n))p!==void 0&&(c[f]=p);let u=t==="invoice"?so:t==="bill"?En:lr,{missingFields:l,ready:d}=an(c,u);if(!d)throw new Error(`Cannot finalize: missing ${l.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function JJ(e,t,r,n){if((await e(t,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}var pl=[{name:"get_organization",description:"Get organization details (name, currency, country, lock date, fiscal year end).",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>Pn(e.client)},gt("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(e,t,r)=>Ti(e,{limit:r,offset:t}),"list chart of accounts with code type class status"),Rt({name:"search_accounts",description:'Search chart of accounts. For OR (name or code), use filter: {"or":{"name":{"contains":"X"},"code":{"contains":"X"}}}.',group:"accounts",fields:nf,defaults:of,fetcher:yu,searchHint:"find accounts chart of accounts CoA by name code type class status OR search"}),{name:"create_account",description:"Create a new chart of accounts entry. Auto-checks for duplicates by name \u2014 returns existing account if found. Code must be unique. Account class is inferred from accountType.",params:{name:{type:"string",description:"Account name"},code:{type:"string",description:"Account code (unique)"},accountType:{type:"string",description:'Exact API string. Classic 12: Bank Accounts | Cash | Current Asset | Fixed Asset | Inventory | Current Liability | Non-current Liability | Shareholders Equity | Operating Revenue | Other Revenue | Operating Expense | Direct Costs. IFRS 18 (effective 2027): Discontinued Expense | Discontinued Income | Finance Cost | Financing Income | Goodwill | Income Tax Expense | Investing Expense | Investing Income | Investment. Common variants normalized client-side. For "interest expense"/"interest income", pick Financing or Investing yourself \u2014 depends on entity main business activity, NOT auto-classified.'},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code",execute:async(e,t)=>{let r=t.name,n=await db(e.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let o=gu(t.accountType);return bp(e.client,{code:t.code,name:r,accountType:o,currencyCode:t.currencyCode})}},{name:"update_account",description:"Update an existing chart of accounts entry (name or code).",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code",execute:async(e,t)=>{let r=t.resourceId,n=(await Yz(e.client,r)).data,i=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(s=>n[s]!==void 0&&n[s]!==null).map(s=>[s,n[s]]));return!i.classificationType&&n.accountType&&(i.classificationType=n.accountType),t.name!==void 0&&(i.name=t.name),t.code!==void 0&&(i.code=t.code),Jz(e.client,r,i)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount } \u2014 no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
682
682
 
683
683
  resourceId per row \u2192 update; omit \u2192 create. Note: dedup is by NAME (not code) \u2014 duplicate name surfaces ORGANIZATION_CHART_OF_ACCOUNT_DUPLICATED per row. Accepts classic 12 + 9 IFRS 18 accountType values; common variants normalized via normalizeAccountType.
684
684
 
685
- Use for CoA imports / IFRS 18 migration / template seeding. For one-off creates with dedup, use create_account.`,params:{accounts:{type:"array",description:"Array of chart-of-accounts entries (max 500). Mix create and update freely.",items:{type:"object",properties:{resourceId:{type:"string",description:"Account resourceId (UUID) \u2014 provide to update, omit to create"},code:{type:"string",description:"Account code (unique per org)"},name:{type:"string",description:"Account name (unique per org \u2014 dedup key)"},accountType:{type:"string",description:'Classic 12 or IFRS 18 set per create_account description (e.g. "Operating Expense", "Finance Cost"). Variants normalized client-side ("income tax" \u2192 "Income Tax Expense"). Required for create.'},currencyCode:{type:"string",description:'Currency code (e.g. "SGD"). Defaults to org functional currency.'},description:{type:"string",description:"Optional description / memo"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Account status"}}}}},required:["accounts"],group:"accounts",readOnly:!1,searchHint:"bulk create or update chart of accounts import COA migration",execute:async(e,t)=>{er(t.accounts,"accounts",500,"chart-of-accounts entries");let r=t.accounts.map(mb);return(await hb(e.client,r)).data}},gt("list_contacts","List contacts (customers/suppliers). Returns billingName, name, emails, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","contacts",(e,t,r)=>ns(e,{limit:r,offset:t}),"list customers suppliers contacts with email status"),Rt({name:"search_contacts",description:"Search contacts by name, email, customer/supplier role, status.",group:"contacts",fields:zp,defaults:Yp,fetcher:ro,searchHint:"find customers suppliers by name email role status"}),{name:"get_contact",description:"Get full contact details by resourceId.",params:{resourceId:{type:"string",description:"Contact resourceId (UUID)"}},required:["resourceId"],group:"contacts",readOnly:!0,searchHint:"get contact customer supplier details by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>va(e.client,t.resourceId)},{name:"get_contact_signals",description:`Read-only contact pattern intelligence (cadence, outliers, divergences, severity). USE THIS for stand-alone history lookup before drafting (e.g. "what does this supplier normally look like?"). Use validate_drafts instead when you have a specific draft to score.
685
+ Use for CoA imports / IFRS 18 migration / template seeding. For one-off creates with dedup, use create_account.`,params:{accounts:{type:"array",description:"Array of chart-of-accounts entries (max 500). Mix create and update freely.",items:{type:"object",properties:{resourceId:{type:"string",description:"Account resourceId (UUID) \u2014 provide to update, omit to create"},code:{type:"string",description:"Account code (unique per org)"},name:{type:"string",description:"Account name (unique per org \u2014 dedup key)"},accountType:{type:"string",description:'Classic 12 or IFRS 18 set per create_account description (e.g. "Operating Expense", "Finance Cost"). Variants normalized client-side ("income tax" \u2192 "Income Tax Expense"). Required for create.'},currencyCode:{type:"string",description:'Currency code (e.g. "SGD"). Defaults to org functional currency.'},description:{type:"string",description:"Optional description / memo"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Account status"}}}}},required:["accounts"],group:"accounts",readOnly:!1,searchHint:"bulk create or update chart of accounts import COA migration",execute:async(e,t)=>{er(t.accounts,"accounts",500,"chart-of-accounts entries");let r=t.accounts.map(mb);return(await hb(e.client,r)).data}},gt("list_contacts","List contacts (customers/suppliers). Returns billingName, name, emails, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","contacts",(e,t,r)=>ns(e,{limit:r,offset:t}),"list customers suppliers contacts with email status"),Rt({name:"search_contacts",description:"Search contacts.",group:"contacts",fields:zp,defaults:Yp,fetcher:ro,searchHint:"find contacts customers suppliers vendors by name email role status tax-id tag"}),{name:"get_contact",description:"Get full contact details by resourceId.",params:{resourceId:{type:"string",description:"Contact resourceId (UUID)"}},required:["resourceId"],group:"contacts",readOnly:!0,searchHint:"get contact customer supplier details by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>va(e.client,t.resourceId)},{name:"get_contact_signals",description:`Read-only contact pattern intelligence (cadence, outliers, divergences, severity). USE THIS for stand-alone history lookup before drafting (e.g. "what does this supplier normally look like?"). Use validate_drafts instead when you have a specific draft to score.
686
686
 
687
687
  Returns null when the contact has no qualifying history yet (sampleSize < 5) or the freshness layer is unavailable. Per-pair cache (contactId \xD7 btType) \u2014 duplicate calls for the same pair return the same result.
688
688
 
689
689
  Three response slices (severitySummary, outlierFlags, revealedDivergences) populate ONLY on the validate_drafts path \u2014 empty/null here.`,params:{resourceId:{type:"string",description:"Contact resourceId (UUID)"},btType:{type:"string",description:"Business-transaction type to scope the signal sample to.",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"]}},required:["resourceId","btType"],group:"contacts",readOnly:!0,searchHint:"contact signals patterns cadence outliers severity history",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>{let r=t.resourceId;return zz(r,"resourceId","Call search_contacts to get a valid contact resourceId."),kM(e.client,r,t.btType)}},{name:"create_contact",description:"Create a new contact. Auto-checks for duplicates by name \u2014 returns existing contact if found instead of creating a duplicate.",params:{billingName:{type:"string",description:"Official billing name"},name:{type:"string",description:"Display name (usually same as billingName)"},email:{type:"string",description:"Primary email address"},customer:{type:"boolean",description:"Is a customer (default true)"},supplier:{type:"boolean",description:"Is a supplier (default false)"}},required:["billingName"],group:"contacts",readOnly:!1,searchHint:"create new customer or supplier contact",execute:async(e,t)=>{let r=t.name??t.billingName,n=await Dp(e.client,r);return n?{_guard:"duplicate_skipped",message:`Contact "${r}" already exists.`,existing:n}:Gc(e.client,{billingName:t.billingName,name:r,emails:t.email?[t.email]:void 0,customer:t.customer??!0,supplier:t.supplier??!1})}},{name:"update_contact",description:"Update an existing contact. Fetches current data first so you only need to send changed fields.",params:{resourceId:{type:"string",description:"Contact resourceId"},billingName:{type:"string"},name:f$,email:{type:"string"}},required:["resourceId"],group:"contacts",readOnly:!1,searchHint:"update existing contact billing name email details",execute:async(e,t)=>{let{resourceId:r,...n}=t,{data:o}=await va(e.client,r),i=["billingName","name","email","customer","supplier","taxId","phone","status","currencyCode","customerPaymentTerms"],s=o,a=Object.fromEntries(i.filter(c=>s[c]!==void 0&&s[c]!==null).map(c=>[c,s[c]]));return Object.assign(a,n),Fy(e.client,r,a)}},gt("list_invoices","List invoices. Returns reference, date, status, contact, totalAmount. Paginated \u2014 response includes totalElements. Use limit/offset to page.","invoices",(e,t,r)=>Rb(e,{limit:r,offset:t}),"list sales invoices with pagination and status"),Rt({name:"search_invoices",description:'Search invoices. Supports comma-separated status (e.g., "UNPAID,PARTIALLY_PAID"). Use filter param for advanced queries (nested paths, OR groups).',group:"invoices",fields:wu,defaults:Tu,fetcher:$u,searchHint:"find sales invoices by status date contact amount"}),{name:"get_invoice",description:"Get full invoice details including line items, payments, totals.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"invoices",readOnly:!0,searchHint:"get invoice details line items payments totals",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>io(e.client,t.resourceId)},{name:"create_invoice",description:'Create invoice. lineItem text field = `name` (not "description"). saveAsDraft defaults true \u2014 false only on "finalize".\n\nREQUIRED: contactResourceId (search first), and accountResourceId per lineItem when finalizing. lineItem minimum: `{ name, unitPrice, quantity, accountResourceId }`. Currency: `{ sourceCurrency: "USD", exchangeRate: 1.35 }`. Dates YYYY-MM-DD.\n\nreference MUST be unique per org \u2014 auto-generate with timestamp if user doesn\'t specify (e.g. INV-20260309-1430). Duplicate \u2192 422.',params:{reference:{type:"string",description:"Invoice reference number"},valueDate:{type:"string",description:"Invoice date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Due date (YYYY-MM-DD)"},contactResourceId:{type:"string",description:"Contact resourceId"},lineItems:fi,currency:ec,saveAsDraft:{type:"boolean",description:"Save as draft (default true)"},notes:Dr,tag:dl,customFields:dn},required:["reference","valueDate","dueDate","contactResourceId","lineItems"],group:"invoices",readOnly:!1,searchHint:"create new sales invoice draft with line items",execute:async(e,t)=>{let{notes:r,tag:n,...o}=t,i={...o,...r!==void 0&&{invoiceNotes:r},...n!==void 0&&{tags:[n]}};return ja(e.client,i)}},{name:"update_invoice",description:'Update an existing draft invoice (change reference, dates, line items, notes, custom fields). Use when the user says "update", "change", "fix", or "correct" a draft invoice. Line items CAN be fully replaced \u2014 pass the complete updated lineItems array.',params:{resourceId:{type:"string",description:"Invoice resourceId"},reference:yo,valueDate:go,dueDate:Xm,lineItems:fi,notes:Dr,customFields:dn},required:["resourceId"],group:"invoices",readOnly:!1,searchHint:"update draft invoice reference dates line items",execute:async(e,t)=>{let{resourceId:r,notes:n,tag:o,...i}=t,s={...i,...n!==void 0&&{invoiceNotes:n},...o!==void 0&&{tags:[o]}};return Nb(e.client,r,s)}},{name:"delete_invoice",description:"Delete a draft invoice. Cannot delete finalized invoices.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"invoices",readOnly:!1,searchHint:"permanently delete a draft invoice",isDestructive:!0,execute:async(e,t)=>kb(e.client,t.resourceId)},{name:"pay_invoice",description:"Record a payment against an invoice. Invoice must be APPROVED/UNPAID before payment \u2014 draft or voided invoices cannot be paid. If the invoice is still a DRAFT, call finalize_invoice first.",params:{resourceId:{type:"string",description:"Invoice resourceId"},paymentAmount:{type:"number",description:"Amount to pay (in bank currency)"},transactionAmount:{type:"number",description:"Amount in invoice currency (defaults to paymentAmount for same-currency)"},accountResourceId:{type:"string",description:"Bank/cash account resourceId for payment"},valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},reference:{type:"string",description:"Payment reference"},paymentMethod:Qm,customFields:dn},required:["resourceId","paymentAmount","accountResourceId","valueDate"],group:"invoices",readOnly:!1,searchHint:"record payment against an approved invoice",isDestructive:!0,execute:async(e,t)=>{let r=t.resourceId,n=Number(t.paymentAmount);if(!Number.isFinite(n)||n<=0)throw new Error("paymentAmount must be a positive number");let o=Number(t.transactionAmount??n);if(!Number.isFinite(o)||o<=0)throw new Error("transactionAmount must be a positive number");return await JJ(io,e.client,r,"invoice"),_f(e.client,r,{paymentAmount:n,transactionAmount:o,accountResourceId:t.accountResourceId,valueDate:t.valueDate,dueDate:t.valueDate,reference:t.reference||`PMT-${Date.now()}`,paymentMethod:t.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1,customFields:t.customFields})}},{name:"finalize_invoice",description:"Finalize a draft invoice (set saveAsDraft=false). Can optionally update fields in the same call. IMPORTANT: Every lineItem MUST have accountResourceId. If the draft was created without it, pass lineItems with accountResourceId added (search accounts first, e.g. Operating Revenue for sales).",params:{resourceId:{type:"string",description:"Invoice resourceId"},reference:yo,valueDate:go,dueDate:Xm,lineItems:fi,notes:Dr},required:["resourceId"],group:"invoices",readOnly:!1,searchHint:"approve finalize draft invoice for sending",isDestructive:!0,execute:async(e,t)=>{let{resourceId:r,notes:n,...o}=t,i={...o,...n!==void 0&&{invoiceNotes:n}},s=await eh(e.client,"invoice",r,i);if(s.reference){let a=s.reference;((await $u(e.client,{filter:{reference:{eq:a}},limit:1,offset:0,sort:{sortBy:["valueDate"],order:"DESC"}})).data??[]).filter(l=>l.resourceId!==r).length>0&&(s.reference=`${a}-${Date.now()%1e4}`)}return Cf(e.client,r,s)}},{name:"apply_credits_to_invoice",description:`Apply customer credit note(s) to an invoice. You MUST call this tool to actually apply credits \u2014 do not just describe the steps.
690
- Steps: 1) search_customer_credit_notes with status UNAPPLIED for the same contact. 2) If CN is still DRAFT, call finalize_customer_credit_note first. 3) Call this tool with creditNoteResourceId and amountApplied for each CN.`,params:{resourceId:{type:"string",description:"Invoice resourceId"},credits:{type:"array",items:{type:"object",properties:{creditNoteResourceId:{type:"string",description:"Customer credit note resourceId"},amountApplied:{type:"number",description:"Amount to apply"}},required:["creditNoteResourceId","amountApplied"]},description:"Credits to apply"}},required:["resourceId","credits"],group:"invoices",readOnly:!1,searchHint:"apply customer credit note to invoice balance",isDestructive:!0,execute:async(e,t)=>Fb(e.client,t.resourceId,t.credits)},{name:"download_invoice_pdf",description:"Download an invoice as PDF. Returns { fileUrl }.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"invoices",readOnly:!0,searchHint:"download invoice as PDF document file",isConcurrencySafe:!0,execute:async(e,t)=>Pb(e.client,t.resourceId)},gt("list_bills","List bills (purchase invoices). Returns reference, date, status, contact, amounts. Paginated \u2014 response includes totalElements. Use limit/offset to page.","bills",(e,t,r)=>xy(e,{limit:r,offset:t}),"list purchase bills with pagination and status"),Rt({name:"search_bills",description:'Search bills. Supports comma-separated status (e.g., "UNPAID,PARTIALLY_PAID"). Use filter param for advanced queries.',group:"bills",fields:jp,defaults:Mp,fetcher:Da,searchHint:"find purchase bills by status date supplier amount"}),{name:"get_bill",description:"Get full bill details.",params:{resourceId:th},required:["resourceId"],group:"bills",readOnly:!0,searchHint:"get bill details line items payments totals",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>to(e.client,t.resourceId)},{name:"create_bill",description:`Create a new bill. Same rules as create_invoice: name not description, saveAsDraft defaults true, accountResourceId REQUIRED on lineItems for finalized bills (search accounts first, e.g. Operating Expense). When selecting a tax profile, use search_tax_profiles with appliesTo "purchase" \u2014 sales-only profiles cause 422. reference MUST be unique \u2014 generate one with a timestamp if user doesn't specify.`,params:{reference:yo,valueDate:go,dueDate:Xm,contactResourceId:bSe,lineItems:fi,currency:ec,saveAsDraft:jJ,notes:Dr,tag:dl,customFields:dn},required:["reference","valueDate","dueDate","contactResourceId","lineItems"],group:"bills",readOnly:!1,searchHint:"create new purchase bill draft with line items",execute:async(e,t)=>{let{notes:r,tag:n,...o}=t,i={...o,...r!==void 0&&{invoiceNotes:r},...n!==void 0&&{tags:[n]}};return ba(e.client,i)}},{name:"update_bill",description:'Update an existing draft bill (change reference, dates, line items, notes, custom fields). Use when the user says "update", "change", "fix", or "correct" a draft bill. Line items CAN be fully replaced \u2014 pass the complete updated lineItems array.',params:{resourceId:{type:"string",description:"Bill resourceId"},reference:yo,valueDate:go,dueDate:Xm,lineItems:fi,notes:Dr,customFields:dn},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"update draft bill reference dates line items",execute:async(e,t)=>{let{resourceId:r,notes:n,tag:o,...i}=t,s={...i,...n!==void 0&&{invoiceNotes:n},...o!==void 0&&{tags:[o]}};return Ay(e.client,r,s)}},{name:"delete_bill",description:"Delete a draft bill.",params:{resourceId:th},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"permanently delete a draft bill",isDestructive:!0,execute:async(e,t)=>wy(e.client,t.resourceId)},{name:"pay_bill",description:"Record a payment against a bill. Bill must be APPROVED before payment \u2014 draft or voided bills cannot be paid.",params:{resourceId:th,paymentAmount:vSe,transactionAmount:{type:"number",description:"Amount in bill currency (defaults to paymentAmount for same-currency)"},accountResourceId:rc,valueDate:go,reference:yo,paymentMethod:Qm,customFields:dn},required:["resourceId","paymentAmount","accountResourceId","valueDate"],group:"bills",readOnly:!1,searchHint:"record payment against an approved bill",isDestructive:!0,execute:async(e,t)=>{let r=t.resourceId,n=Number(t.paymentAmount);if(!Number.isFinite(n)||n<=0)throw new Error("paymentAmount must be a positive number");let o=Number(t.transactionAmount??n);if(!Number.isFinite(o)||o<=0)throw new Error("transactionAmount must be a positive number");return await JJ(to,e.client,r,"bill"),Cd(e.client,r,{paymentAmount:n,transactionAmount:o,accountResourceId:t.accountResourceId,valueDate:t.valueDate,dueDate:t.valueDate,reference:t.reference||`PMT-${Date.now()}`,paymentMethod:t.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1,customFields:t.customFields})}},{name:"finalize_bill",description:"Finalize a draft bill (set saveAsDraft=false). Can optionally update fields in the same call. IMPORTANT: Every lineItem MUST have accountResourceId. If the draft was created without it, pass lineItems with accountResourceId added (search accounts first, e.g. Operating Expense for purchases).",params:{resourceId:{type:"string",description:"Bill resourceId"},reference:yo,valueDate:go,dueDate:Xm,lineItems:fi,notes:Dr},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"approve finalize draft bill for processing",isDestructive:!0,execute:async(e,t)=>{let{resourceId:r,notes:n,...o}=t,i={...o,...n!==void 0&&{invoiceNotes:n}},s=await eh(e.client,"bill",r,i);return Ed(e.client,r,s)}},{name:"apply_credits_to_bill",description:"Apply supplier credit note(s) to a bill. IMPORTANT: The credit note must be FINALIZED first (status UNAPPLIED, not DRAFT). If it is still a draft, call finalize_supplier_credit_note first. Then search_supplier_credit_notes with status UNAPPLIED to find available credits for the contact, and pass creditNoteResourceId and amountApplied for each.",params:{resourceId:{type:"string",description:"Bill resourceId"},credits:{type:"array",items:{type:"object",properties:{creditNoteResourceId:{type:"string",description:"Supplier credit note resourceId"},amountApplied:{type:"number",description:"Amount to apply"}},required:["creditNoteResourceId","amountApplied"]},description:"Credits to apply"}},required:["resourceId","credits"],group:"bills",readOnly:!1,searchHint:"apply supplier credit note to bill balance",isDestructive:!0,execute:async(e,t)=>Ty(e.client,t.resourceId,t.credits)},gt("list_journals","List journal entries. Paginated \u2014 response includes totalElements. Use limit/offset to page.","journals",(e,t,r)=>Gb(e,{limit:r,offset:t}),"list journal entries with pagination and status"),Yn("get_journal","Get full journal entry details by resourceId. Returns journal lines, amounts, status, and metadata.","journals",(e,t)=>ni(e,t),"get journal entry details debit credit lines"),Rt({name:"search_journals",description:"Search journals by status, type, date, reference, tag. Status uses ACTIVE (not FINALIZED). Supports comma-separated status/type.",group:"journals",fields:Up,defaults:qp,fetcher:If,searchHint:"find journals by status type date reference tag"}),{name:"create_journal",description:`Create a journal entry. IMPORTANT:
690
+ Steps: 1) search_customer_credit_notes with status UNAPPLIED for the same contact. 2) If CN is still DRAFT, call finalize_customer_credit_note first. 3) Call this tool with creditNoteResourceId and amountApplied for each CN.`,params:{resourceId:{type:"string",description:"Invoice resourceId"},credits:{type:"array",items:{type:"object",properties:{creditNoteResourceId:{type:"string",description:"Customer credit note resourceId"},amountApplied:{type:"number",description:"Amount to apply"}},required:["creditNoteResourceId","amountApplied"]},description:"Credits to apply"}},required:["resourceId","credits"],group:"invoices",readOnly:!1,searchHint:"apply customer credit note to invoice balance",isDestructive:!0,execute:async(e,t)=>Fb(e.client,t.resourceId,t.credits)},{name:"download_invoice_pdf",description:"Download an invoice as PDF. Returns { fileUrl }.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"invoices",readOnly:!0,searchHint:"download invoice as PDF document file",isConcurrencySafe:!0,execute:async(e,t)=>Pb(e.client,t.resourceId)},gt("list_bills","List bills (purchase invoices). Returns reference, date, status, contact, amounts. Paginated \u2014 response includes totalElements. Use limit/offset to page.","bills",(e,t,r)=>xy(e,{limit:r,offset:t}),"list purchase bills with pagination and status"),Rt({name:"search_bills",description:'Search bills. Supports comma-separated status (e.g., "UNPAID,PARTIALLY_PAID"). Use filter param for advanced queries.',group:"bills",fields:jp,defaults:Mp,fetcher:Da,searchHint:"find purchase bills by status date supplier amount"}),{name:"get_bill",description:"Get full bill details.",params:{resourceId:th},required:["resourceId"],group:"bills",readOnly:!0,searchHint:"get bill details line items payments totals",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>to(e.client,t.resourceId)},{name:"create_bill",description:`Create a new bill. Same rules as create_invoice: name not description, saveAsDraft defaults true, accountResourceId REQUIRED on lineItems for finalized bills (search accounts first, e.g. Operating Expense). When selecting a tax profile, use search_tax_profiles with appliesTo "purchase" \u2014 sales-only profiles cause 422. reference MUST be unique \u2014 generate one with a timestamp if user doesn't specify.`,params:{reference:yo,valueDate:go,dueDate:Xm,contactResourceId:bSe,lineItems:fi,currency:ec,saveAsDraft:jJ,notes:Dr,tag:dl,customFields:dn},required:["reference","valueDate","dueDate","contactResourceId","lineItems"],group:"bills",readOnly:!1,searchHint:"create new purchase bill draft with line items",execute:async(e,t)=>{let{notes:r,tag:n,...o}=t,i={...o,...r!==void 0&&{invoiceNotes:r},...n!==void 0&&{tags:[n]}};return ba(e.client,i)}},{name:"update_bill",description:'Update an existing draft bill (change reference, dates, line items, notes, custom fields). Use when the user says "update", "change", "fix", or "correct" a draft bill. Line items CAN be fully replaced \u2014 pass the complete updated lineItems array.',params:{resourceId:{type:"string",description:"Bill resourceId"},reference:yo,valueDate:go,dueDate:Xm,lineItems:fi,notes:Dr,customFields:dn},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"update draft bill reference dates line items",execute:async(e,t)=>{let{resourceId:r,notes:n,tag:o,...i}=t,s={...i,...n!==void 0&&{invoiceNotes:n},...o!==void 0&&{tags:[o]}};return Ay(e.client,r,s)}},{name:"delete_bill",description:"Delete a draft bill.",params:{resourceId:th},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"permanently delete a draft bill",isDestructive:!0,execute:async(e,t)=>wy(e.client,t.resourceId)},{name:"pay_bill",description:"Record a payment against a bill. Bill must be APPROVED before payment \u2014 draft or voided bills cannot be paid.",params:{resourceId:th,paymentAmount:vSe,transactionAmount:{type:"number",description:"Amount in bill currency (defaults to paymentAmount for same-currency)"},accountResourceId:rc,valueDate:go,reference:yo,paymentMethod:Qm,customFields:dn},required:["resourceId","paymentAmount","accountResourceId","valueDate"],group:"bills",readOnly:!1,searchHint:"record payment against an approved bill",isDestructive:!0,execute:async(e,t)=>{let r=t.resourceId,n=Number(t.paymentAmount);if(!Number.isFinite(n)||n<=0)throw new Error("paymentAmount must be a positive number");let o=Number(t.transactionAmount??n);if(!Number.isFinite(o)||o<=0)throw new Error("transactionAmount must be a positive number");return await JJ(to,e.client,r,"bill"),Cd(e.client,r,{paymentAmount:n,transactionAmount:o,accountResourceId:t.accountResourceId,valueDate:t.valueDate,dueDate:t.valueDate,reference:t.reference||`PMT-${Date.now()}`,paymentMethod:t.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1,customFields:t.customFields})}},{name:"finalize_bill",description:"Finalize a draft bill (set saveAsDraft=false). Can optionally update fields in the same call. IMPORTANT: Every lineItem MUST have accountResourceId. If the draft was created without it, pass lineItems with accountResourceId added (search accounts first, e.g. Operating Expense for purchases).",params:{resourceId:{type:"string",description:"Bill resourceId"},reference:yo,valueDate:go,dueDate:Xm,lineItems:fi,notes:Dr},required:["resourceId"],group:"bills",readOnly:!1,searchHint:"approve finalize draft bill for processing",isDestructive:!0,execute:async(e,t)=>{let{resourceId:r,notes:n,...o}=t,i={...o,...n!==void 0&&{invoiceNotes:n}},s=await eh(e.client,"bill",r,i);return Ed(e.client,r,s)}},{name:"apply_credits_to_bill",description:"Apply supplier credit note(s) to a bill. IMPORTANT: The credit note must be FINALIZED first (status UNAPPLIED, not DRAFT). If it is still a draft, call finalize_supplier_credit_note first. Then search_supplier_credit_notes with status UNAPPLIED to find available credits for the contact, and pass creditNoteResourceId and amountApplied for each.",params:{resourceId:{type:"string",description:"Bill resourceId"},credits:{type:"array",items:{type:"object",properties:{creditNoteResourceId:{type:"string",description:"Supplier credit note resourceId"},amountApplied:{type:"number",description:"Amount to apply"}},required:["creditNoteResourceId","amountApplied"]},description:"Credits to apply"}},required:["resourceId","credits"],group:"bills",readOnly:!1,searchHint:"apply supplier credit note to bill balance",isDestructive:!0,execute:async(e,t)=>Ty(e.client,t.resourceId,t.credits)},gt("list_journals","List journal entries. Paginated \u2014 response includes totalElements. Use limit/offset to page.","journals",(e,t,r)=>Gb(e,{limit:r,offset:t}),"list journal entries with pagination and status"),Yn("get_journal","Get full journal entry details by resourceId. Returns journal lines, amounts, status, and metadata.","journals",(e,t)=>ni(e,t),"get journal entry details debit credit lines"),Rt({name:"search_journals",description:"Search journals. Status uses ACTIVE (not FINALIZED). Supports comma-separated status/type.",group:"journals",fields:Up,defaults:qp,fetcher:If,searchHint:"find journals JE by status type date reference tag contact internal-notes"}),{name:"create_journal",description:`Create a journal entry. IMPORTANT:
691
691
  - Each entry needs accountResourceId, type (DEBIT or CREDIT), and amount.
692
692
  - Total debits MUST equal total credits \u2014 the API rejects unbalanced journals.
693
693
  - Search accounts first to get the correct resourceIds.
@@ -697,13 +697,13 @@ Steps: 1) search_customer_credit_notes with status UNAPPLIED for the same contac
697
697
  - Minimum 1 entry (unlike regular journals which require 2).
698
698
  - Each entry needs accountResourceId, type (DEBIT or CREDIT), and amount (must be > 0).
699
699
  - Skips lock date validation (opening balances are special).
700
- - Uses journalEntries (NOT lines \u2014 this is a journal type).`,params:{valueDate:{type:"string",description:"Opening balance date (YYYY-MM-DD)"},journalEntries:tc,currency:ec},required:["valueDate","journalEntries"],group:"journals",readOnly:!1,searchHint:"create transfer trial balance between periods",execute:async(e,t)=>Wb(e.client,t)},{name:"delete_journal",description:"Delete a draft journal entry.",params:{resourceId:th},required:["resourceId"],group:"journals",readOnly:!1,searchHint:"permanently delete a draft journal entry",isDestructive:!0,execute:async(e,t)=>Vb(e.client,t.resourceId)},{name:"generate_trial_balance",description:"Generate a trial balance report.",params:{endDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency override"}},required:["endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate trial balance report for period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>d0(e.client,t)},{name:"generate_balance_sheet",description:"Generate a balance sheet report.",params:{snapshotDate:{type:"string",description:"Snapshot date (YYYY-MM-DD). Defaults to today if omitted."},currencyCode:MJ},required:[],group:"financial_reports",readOnly:!0,searchHint:"generate balance sheet report as at date",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>{let r=t.snapshotDate??new Date().toISOString().slice(0,10);return p0(e.client,{primarySnapshotDate:r,currencyCode:t.currencyCode})}},{name:"generate_profit_and_loss",description:"Generate a profit & loss (income statement) report.",params:{startDate:{type:"string",description:"Period start (YYYY-MM-DD)"},endDate:{type:"string",description:"Period end (YYYY-MM-DD)"},currencyCode:MJ},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate profit and loss income statement report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>f0(e.client,t)},{name:"generate_cashflow",description:"Generate a cashflow report.",params:{startDate:SSe,endDate:p$},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate cashflow statement report for period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>m0(e.client,t)},{name:"generate_aged_ar",description:"Generate aged accounts receivable summary.",params:{endDate:p$},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:"generate aged accounts receivable summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>h0(e.client,t)},{name:"generate_aged_ap",description:"Generate aged accounts payable summary.",params:{endDate:p$},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:"generate aged accounts payable summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>g0(e.client,t)},{name:"generate_cash_balance",description:"Generate a cash balance report showing cash position at a specific date. PREFERRED for cash position questions \u2014 use this (NOT balance sheet) when asked about total cash, cash on hand, available cash, or cash position across all bank accounts.",params:{endDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"}},required:["endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate cash balance report across accounts",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>y0(e.client,t)},{name:"generate_general_ledger",description:"Generate a general ledger report.",params:{startDate:{type:"string",description:"Period start (YYYY-MM-DD)"},endDate:{type:"string",description:"Period end (YYYY-MM-DD)"},groupBy:{type:"string",description:"Group by: ACCOUNT (default), TRANSACTION, or CAPSULE"}},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate general ledger report for account period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>{let r=t;return D0(e.client,{...r,groupBy:r.groupBy??"ACCOUNT"})}},{name:"list_bank_accounts",description:"List bank accounts connected to the organization.",params:{},required:[],group:"bank",readOnly:!0,searchHint:"list bank and cash accounts with balances",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async e=>zc(e.client)},gt("list_items","List items (products & services). Returns internalName, itemCode, appliesToSale/Purchase. Paginated \u2014 response includes totalElements. Use limit/offset to page.","items",(e,t,r)=>HD(e,{limit:r,offset:t}),"list products services items with pagination"),Rt({name:"search_items",description:"Search items by status, category, sale/purchase applicability. Use list_items to search by name (internalName is not a filter field).",group:"items",fields:Wp,defaults:Zp,fetcher:lu,searchHint:"find items by status category sale purchase type"}),{name:"get_item",description:"Get full item details by resourceId.",params:{resourceId:{type:"string",description:"Item resourceId (UUID)"}},required:["resourceId"],group:"items",readOnly:!0,searchHint:"get item product service details by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>fp(e.client,t.resourceId)},{name:"create_item",description:`Create a new item. Auto-checks for duplicates by itemCode \u2014 returns existing item if found.
700
+ - Uses journalEntries (NOT lines \u2014 this is a journal type).`,params:{valueDate:{type:"string",description:"Opening balance date (YYYY-MM-DD)"},journalEntries:tc,currency:ec},required:["valueDate","journalEntries"],group:"journals",readOnly:!1,searchHint:"create transfer trial balance between periods",execute:async(e,t)=>Wb(e.client,t)},{name:"delete_journal",description:"Delete a draft journal entry.",params:{resourceId:th},required:["resourceId"],group:"journals",readOnly:!1,searchHint:"permanently delete a draft journal entry",isDestructive:!0,execute:async(e,t)=>Vb(e.client,t.resourceId)},{name:"generate_trial_balance",description:"Generate a trial balance report.",params:{endDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency override"}},required:["endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate trial balance report for period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>d0(e.client,t)},{name:"generate_balance_sheet",description:"Generate a balance sheet report.",params:{snapshotDate:{type:"string",description:"Snapshot date (YYYY-MM-DD). Defaults to today if omitted."},currencyCode:MJ},required:[],group:"financial_reports",readOnly:!0,searchHint:"generate balance sheet report as at date",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>{let r=t.snapshotDate??new Date().toISOString().slice(0,10);return p0(e.client,{primarySnapshotDate:r,currencyCode:t.currencyCode})}},{name:"generate_profit_and_loss",description:"Generate a profit & loss (income statement) report.",params:{startDate:{type:"string",description:"Period start (YYYY-MM-DD)"},endDate:{type:"string",description:"Period end (YYYY-MM-DD)"},currencyCode:MJ},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate profit and loss income statement report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>f0(e.client,t)},{name:"generate_cashflow",description:"Generate a cashflow report.",params:{startDate:SSe,endDate:p$},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate cashflow statement report for period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>m0(e.client,t)},{name:"generate_aged_ar",description:"Generate aged accounts receivable summary.",params:{endDate:p$},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:"generate aged accounts receivable summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>h0(e.client,t)},{name:"generate_aged_ap",description:"Generate aged accounts payable summary.",params:{endDate:p$},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:"generate aged accounts payable summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>g0(e.client,t)},{name:"generate_cash_balance",description:"Generate a cash balance report showing cash position at a specific date. PREFERRED for cash position questions \u2014 use this (NOT balance sheet) when asked about total cash, cash on hand, available cash, or cash position across all bank accounts.",params:{endDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"}},required:["endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate cash balance report across accounts",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>y0(e.client,t)},{name:"generate_general_ledger",description:"Generate a general ledger report.",params:{startDate:{type:"string",description:"Period start (YYYY-MM-DD)"},endDate:{type:"string",description:"Period end (YYYY-MM-DD)"},groupBy:{type:"string",description:"Group by: ACCOUNT (default), TRANSACTION, or CAPSULE"}},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate general ledger report for account period",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>{let r=t;return D0(e.client,{...r,groupBy:r.groupBy??"ACCOUNT"})}},{name:"list_bank_accounts",description:"List bank accounts connected to the organization.",params:{},required:[],group:"bank",readOnly:!0,searchHint:"list bank and cash accounts with balances",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async e=>zc(e.client)},gt("list_items","List items (products & services). Returns internalName, itemCode, appliesToSale/Purchase. Paginated \u2014 response includes totalElements. Use limit/offset to page.","items",(e,t,r)=>HD(e,{limit:r,offset:t}),"list products services items with pagination"),Rt({name:"search_items",description:"Search items. Use list_items to search by name (internalName is not a filter field).",group:"items",fields:Wp,defaults:Zp,fetcher:lu,searchHint:"find items products services by status category sale purchase type internalName via list_items"}),{name:"get_item",description:"Get full item details by resourceId.",params:{resourceId:{type:"string",description:"Item resourceId (UUID)"}},required:["resourceId"],group:"items",readOnly:!0,searchHint:"get item product service details by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>fp(e.client,t.resourceId)},{name:"create_item",description:`Create a new item. Auto-checks for duplicates by itemCode \u2014 returns existing item if found.
701
701
  - saleItemName/purchaseItemName are auto-set from internalName if not provided.
702
- - Set appliesToSale and/or appliesToPurchase to control where the item can be used.`,params:{itemCode:{type:"string",description:"Unique item code"},internalName:{type:"string",description:"Item name"},appliesToSale:{type:"boolean",description:"Can be used on invoices"},appliesToPurchase:{type:"boolean",description:"Can be used on bills"},salePrice:{type:"number",description:"Default sale price"},purchasePrice:{type:"number",description:"Default purchase price"},saleAccountResourceId:{type:"string",description:"Revenue account for sales"},purchaseAccountResourceId:{type:"string",description:"Expense account for purchases"},customFields:dn},required:["itemCode","internalName"],group:"items",readOnly:!1,searchHint:"create new product or service item for invoicing",execute:async(e,t)=>{let r=t.itemCode,n=await lb(e.client,r);if(n)return{_guard:"duplicate_skipped",message:`Item with code "${r}" already exists.`,existing:n};let{purchasePrice:o,...i}=t,s={...i,...o!==void 0&&{purchaseItemPrice:o}};return mp(e.client,s)}},{name:"update_item",description:"Update an existing item. Only send fields you want to change \u2014 required fields are auto-merged from current state.",params:{resourceId:{type:"string",description:"Item resourceId"},internalName:{type:"string",description:"New name"},itemCode:{type:"string",description:"New code"},salePrice:{type:"number"},purchasePrice:{type:"number"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Status (ACTIVE or INACTIVE)"},customFields:dn},required:["resourceId"],group:"items",readOnly:!1,searchHint:"update existing item name price account details",execute:async(e,t)=>{let{resourceId:r,purchasePrice:n,...o}=t,i={...o,...n!==void 0&&{purchaseItemPrice:n}};return WD(e.client,r,i)}},{name:"delete_item",description:"Delete an item.",params:{resourceId:{type:"string",description:"Item resourceId"}},required:["resourceId"],group:"items",readOnly:!1,searchHint:"permanently delete an item product service",isDestructive:!0,execute:async(e,t)=>ZD(e.client,t.resourceId)},{name:"bulk_upsert_items",description:"Create or update items in bulk (max 500 per call). Provide resourceId per item to update (partial \u2014 only changed fields needed, server preserves existing values). Omit resourceId to create (defaults: status=ACTIVE, itemCategory=NON_INVENTORY).",params:{items:{type:"array",description:"Array of items to create or update",items:{type:"object",properties:{resourceId:{type:"string",description:"Item resourceId (omit for create, provide for update)"},itemCode:{type:"string",description:"Unique item code (required for create)"},internalName:{type:"string",description:"Internal name (required for create)"},unit:{type:"string",description:"Unit of measure"},status:{type:"string",description:"Record status",enum:["ACTIVE","INACTIVE"]},appliesToSale:{type:"boolean",description:"Whether item applies to sales"},saleItemName:{type:"string",description:"Sale display name"},salePrice:{type:"number",description:"Sale price"},saleAccountResourceId:{type:"string",description:"Sale account resourceId"},saleTaxProfileResourceId:{type:"string",description:"Sale tax profile resourceId"},appliesToPurchase:{type:"boolean",description:"Whether item applies to purchases"},purchaseItemName:{type:"string",description:"Purchase display name"},purchasePrice:{type:"number",description:"Purchase price"},purchaseAccountResourceId:{type:"string",description:"Purchase account resourceId"},purchaseTaxProfileResourceId:{type:"string",description:"Purchase tax profile resourceId"},inventory:{type:"boolean",description:"Whether this is an inventory item"},cogsResourceId:{type:"string",description:"COGS account resourceId"},costingMethod:{type:"string",description:"Costing method",enum:["FIXED","WAC"]},itemCategory:{type:"string",description:"Item category",enum:["INVENTORY","NON_INVENTORY"]},blockInsufficientDeductions:{type:"boolean",description:"Block insufficient stock deductions"}}}}},required:["items"],group:"items",readOnly:!1,searchHint:"bulk create or update multiple items at once",execute:async(e,t)=>{let r=t.items.map(({purchasePrice:o,...i})=>({...i,...o!==void 0&&{purchaseItemPrice:o}}));return(await KD(e.client,r)).data}},gt("list_tags","List tags used for transaction categorization. Paginated \u2014 response includes totalElements. Use limit/offset to page.","tags",(e,t,r)=>hu(e,{limit:r,offset:t}),"list all tags for categorization tracking"),Rt({name:"search_tags",description:"Search tags by name.",group:"tags",fields:sf,defaults:af,fetcher:ab,searchHint:"find tags by name for categorization"}),{name:"create_tag",description:"Create a new tag. Automatically reuses existing tag if one with the same name exists.",params:{name:{type:"string",description:"Tag name"}},required:["name"],group:"tags",readOnly:!1,searchHint:"create new tag for transaction categorization",execute:async(e,t)=>{let r=t.name,n=await fb(e.client,r);return n?{data:n,_note:`Tag "${r}" already exists \u2014 reusing.`}:yp(e.client,{name:r})}},Yn("get_tag","Get a tag by resourceId.","tags",(e,t)=>sb(e,t),"get tag details by resource id"),{name:"update_tag",description:"Rename a tag.",params:{resourceId:{type:"string",description:"Tag resourceId"},name:{type:"string",description:"New tag name"}},required:["resourceId","name"],group:"tags",readOnly:!1,searchHint:"update rename existing tag name",execute:async(e,t)=>cb(e.client,t.resourceId,{name:t.name})},{name:"delete_tag",description:"Delete a tag.",params:{resourceId:{type:"string",description:"Tag resourceId"}},required:["resourceId"],group:"tags",readOnly:!1,searchHint:"permanently delete a tag",isDestructive:!0,execute:async(e,t)=>ub(e.client,t.resourceId)},{name:"list_capsule_types",description:"List capsule types (e.g., PREPAID_EXPENSE, DEFERRED_REVENUE). Use to get capsuleTypeResourceId before creating capsules.",params:{},required:[],group:"capsules",readOnly:!0,searchHint:"list capsule types for transaction grouping",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async e=>du(e.client)},gt("list_capsules","List capsules (transaction groupings for amortization, deferred revenue, etc.). Paginated \u2014 response includes totalElements. Use limit/offset to page.","capsules",(e,t,r)=>XD(e,{limit:r,offset:t}),"list capsules grouped transactions with pagination"),Rt({name:"search_capsules",description:"Search capsules by title or status.",group:"capsules",fields:lf,defaults:df,fetcher:pu,searchHint:"find capsules by title status type"}),{name:"get_capsule",description:"Get full capsule details by resourceId.",params:{resourceId:{type:"string",description:"Capsule resourceId (UUID)"}},required:["resourceId"],group:"capsules",readOnly:!0,searchHint:"get capsule details grouped transactions",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>gp(e.client,t.resourceId)},{name:"create_capsule",description:"Create a new capsule. List capsule types first to get the capsuleTypeResourceId.",params:{capsuleTypeResourceId:{type:"string",description:"Capsule type resourceId (from list_capsule_types)"},title:{type:"string",description:"Capsule title"},description:{type:"string",description:"Capsule description"}},required:["capsuleTypeResourceId","title"],group:"capsules",readOnly:!1,searchHint:"create new capsule to group related transactions",execute:async(e,t)=>{let r=t.title,n=await qz(e.client,r);return n?{_guard:"duplicate_skipped",message:`Capsule "${r}" already exists.`,existing:n}:Oa(e.client,{capsuleTypeResourceId:t.capsuleTypeResourceId,title:r,description:t.description})}},{name:"update_capsule",description:"Update a capsule title or description. Required fields are auto-merged from current state.",params:{resourceId:{type:"string",description:"Capsule resourceId"},title:{type:"string",description:"New title"},description:{type:"string",description:"New description"}},required:["resourceId"],group:"capsules",readOnly:!1,searchHint:"update capsule title description details",execute:async(e,t)=>{let{resourceId:r,...n}=t;return QD(e.client,r,n)}},{name:"delete_capsule",description:"Delete a capsule.",params:{resourceId:{type:"string",description:"Capsule resourceId"}},required:["resourceId"],group:"capsules",readOnly:!1,searchHint:"permanently delete a capsule group",isDestructive:!0,execute:async(e,t)=>eb(e.client,t.resourceId)},gt("list_customer_credit_notes","List customer credit notes (AR adjustments/refunds). Paginated \u2014 response includes totalElements. Use limit/offset to page.","customer_credit_notes",(e,t,r)=>T0(e,{limit:r,offset:t}),"list customer credit notes with status pagination"),Rt({name:"search_customer_credit_notes",description:"Search customer credit notes by reference, status, contact, tag. Status: DRAFT, UNAPPLIED, PARTIALLY_APPLIED, APPLIED, VOID.",group:"customer_credit_notes",fields:vs,defaults:Ou,fetcher:Tf,searchHint:"find customer credit notes by status contact reference"}),{name:"get_customer_credit_note",description:"Get full customer credit note details including line items.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"}},required:["resourceId"],group:"customer_credit_notes",readOnly:!0,searchHint:"get customer credit note details line items",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>Ro(e.client,t.resourceId)},{name:"create_customer_credit_note",description:`Create a customer credit note. Saves as draft by default.
702
+ - Set appliesToSale and/or appliesToPurchase to control where the item can be used.`,params:{itemCode:{type:"string",description:"Unique item code"},internalName:{type:"string",description:"Item name"},appliesToSale:{type:"boolean",description:"Can be used on invoices"},appliesToPurchase:{type:"boolean",description:"Can be used on bills"},salePrice:{type:"number",description:"Default sale price"},purchasePrice:{type:"number",description:"Default purchase price"},saleAccountResourceId:{type:"string",description:"Revenue account for sales"},purchaseAccountResourceId:{type:"string",description:"Expense account for purchases"},customFields:dn},required:["itemCode","internalName"],group:"items",readOnly:!1,searchHint:"create new product or service item for invoicing",execute:async(e,t)=>{let r=t.itemCode,n=await lb(e.client,r);if(n)return{_guard:"duplicate_skipped",message:`Item with code "${r}" already exists.`,existing:n};let{purchasePrice:o,...i}=t,s={...i,...o!==void 0&&{purchaseItemPrice:o}};return mp(e.client,s)}},{name:"update_item",description:"Update an existing item. Only send fields you want to change \u2014 required fields are auto-merged from current state.",params:{resourceId:{type:"string",description:"Item resourceId"},internalName:{type:"string",description:"New name"},itemCode:{type:"string",description:"New code"},salePrice:{type:"number"},purchasePrice:{type:"number"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Status (ACTIVE or INACTIVE)"},customFields:dn},required:["resourceId"],group:"items",readOnly:!1,searchHint:"update existing item name price account details",execute:async(e,t)=>{let{resourceId:r,purchasePrice:n,...o}=t,i={...o,...n!==void 0&&{purchaseItemPrice:n}};return WD(e.client,r,i)}},{name:"delete_item",description:"Delete an item.",params:{resourceId:{type:"string",description:"Item resourceId"}},required:["resourceId"],group:"items",readOnly:!1,searchHint:"permanently delete an item product service",isDestructive:!0,execute:async(e,t)=>ZD(e.client,t.resourceId)},{name:"bulk_upsert_items",description:"Create or update items in bulk (max 500 per call). Provide resourceId per item to update (partial \u2014 only changed fields needed, server preserves existing values). Omit resourceId to create (defaults: status=ACTIVE, itemCategory=NON_INVENTORY).",params:{items:{type:"array",description:"Array of items to create or update",items:{type:"object",properties:{resourceId:{type:"string",description:"Item resourceId (omit for create, provide for update)"},itemCode:{type:"string",description:"Unique item code (required for create)"},internalName:{type:"string",description:"Internal name (required for create)"},unit:{type:"string",description:"Unit of measure"},status:{type:"string",description:"Record status",enum:["ACTIVE","INACTIVE"]},appliesToSale:{type:"boolean",description:"Whether item applies to sales"},saleItemName:{type:"string",description:"Sale display name"},salePrice:{type:"number",description:"Sale price"},saleAccountResourceId:{type:"string",description:"Sale account resourceId"},saleTaxProfileResourceId:{type:"string",description:"Sale tax profile resourceId"},appliesToPurchase:{type:"boolean",description:"Whether item applies to purchases"},purchaseItemName:{type:"string",description:"Purchase display name"},purchasePrice:{type:"number",description:"Purchase price"},purchaseAccountResourceId:{type:"string",description:"Purchase account resourceId"},purchaseTaxProfileResourceId:{type:"string",description:"Purchase tax profile resourceId"},inventory:{type:"boolean",description:"Whether this is an inventory item"},cogsResourceId:{type:"string",description:"COGS account resourceId"},costingMethod:{type:"string",description:"Costing method",enum:["FIXED","WAC"]},itemCategory:{type:"string",description:"Item category",enum:["INVENTORY","NON_INVENTORY"]},blockInsufficientDeductions:{type:"boolean",description:"Block insufficient stock deductions"}}}}},required:["items"],group:"items",readOnly:!1,searchHint:"bulk create or update multiple items at once",execute:async(e,t)=>{let r=t.items.map(({purchasePrice:o,...i})=>({...i,...o!==void 0&&{purchaseItemPrice:o}}));return(await KD(e.client,r)).data}},gt("list_tags","List tags used for transaction categorization. Paginated \u2014 response includes totalElements. Use limit/offset to page.","tags",(e,t,r)=>hu(e,{limit:r,offset:t}),"list all tags for categorization tracking"),Rt({name:"search_tags",description:"Search tags.",group:"tags",fields:sf,defaults:af,fetcher:ab,searchHint:"find tags labels categorization by name"}),{name:"create_tag",description:"Create a new tag. Automatically reuses existing tag if one with the same name exists.",params:{name:{type:"string",description:"Tag name"}},required:["name"],group:"tags",readOnly:!1,searchHint:"create new tag for transaction categorization",execute:async(e,t)=>{let r=t.name,n=await fb(e.client,r);return n?{data:n,_note:`Tag "${r}" already exists \u2014 reusing.`}:yp(e.client,{name:r})}},Yn("get_tag","Get a tag by resourceId.","tags",(e,t)=>sb(e,t),"get tag details by resource id"),{name:"update_tag",description:"Rename a tag.",params:{resourceId:{type:"string",description:"Tag resourceId"},name:{type:"string",description:"New tag name"}},required:["resourceId","name"],group:"tags",readOnly:!1,searchHint:"update rename existing tag name",execute:async(e,t)=>cb(e.client,t.resourceId,{name:t.name})},{name:"delete_tag",description:"Delete a tag.",params:{resourceId:{type:"string",description:"Tag resourceId"}},required:["resourceId"],group:"tags",readOnly:!1,searchHint:"permanently delete a tag",isDestructive:!0,execute:async(e,t)=>ub(e.client,t.resourceId)},{name:"list_capsule_types",description:"List capsule types (e.g., PREPAID_EXPENSE, DEFERRED_REVENUE). Use to get capsuleTypeResourceId before creating capsules.",params:{},required:[],group:"capsules",readOnly:!0,searchHint:"list capsule types for transaction grouping",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async e=>du(e.client)},gt("list_capsules","List capsules (transaction groupings for amortization, deferred revenue, etc.). Paginated \u2014 response includes totalElements. Use limit/offset to page.","capsules",(e,t,r)=>XD(e,{limit:r,offset:t}),"list capsules grouped transactions with pagination"),Rt({name:"search_capsules",description:"Search capsules.",group:"capsules",fields:lf,defaults:df,fetcher:pu,searchHint:"find capsules workflow groups by title status type capsuleType"}),{name:"get_capsule",description:"Get full capsule details by resourceId.",params:{resourceId:{type:"string",description:"Capsule resourceId (UUID)"}},required:["resourceId"],group:"capsules",readOnly:!0,searchHint:"get capsule details grouped transactions",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>gp(e.client,t.resourceId)},{name:"create_capsule",description:"Create a new capsule. List capsule types first to get the capsuleTypeResourceId.",params:{capsuleTypeResourceId:{type:"string",description:"Capsule type resourceId (from list_capsule_types)"},title:{type:"string",description:"Capsule title"},description:{type:"string",description:"Capsule description"}},required:["capsuleTypeResourceId","title"],group:"capsules",readOnly:!1,searchHint:"create new capsule to group related transactions",execute:async(e,t)=>{let r=t.title,n=await qz(e.client,r);return n?{_guard:"duplicate_skipped",message:`Capsule "${r}" already exists.`,existing:n}:Oa(e.client,{capsuleTypeResourceId:t.capsuleTypeResourceId,title:r,description:t.description})}},{name:"update_capsule",description:"Update a capsule title or description. Required fields are auto-merged from current state.",params:{resourceId:{type:"string",description:"Capsule resourceId"},title:{type:"string",description:"New title"},description:{type:"string",description:"New description"}},required:["resourceId"],group:"capsules",readOnly:!1,searchHint:"update capsule title description details",execute:async(e,t)=>{let{resourceId:r,...n}=t;return QD(e.client,r,n)}},{name:"delete_capsule",description:"Delete a capsule.",params:{resourceId:{type:"string",description:"Capsule resourceId"}},required:["resourceId"],group:"capsules",readOnly:!1,searchHint:"permanently delete a capsule group",isDestructive:!0,execute:async(e,t)=>eb(e.client,t.resourceId)},gt("list_customer_credit_notes","List customer credit notes (AR adjustments/refunds). Paginated \u2014 response includes totalElements. Use limit/offset to page.","customer_credit_notes",(e,t,r)=>T0(e,{limit:r,offset:t}),"list customer credit notes with status pagination"),Rt({name:"search_customer_credit_notes",description:"Search customer credit notes. Status: DRAFT, UNAPPLIED, PARTIALLY_APPLIED, APPLIED, VOID.",group:"customer_credit_notes",fields:vs,defaults:Ou,fetcher:Tf,searchHint:"find customer credit notes refunds CN by reference status contact tag"}),{name:"get_customer_credit_note",description:"Get full customer credit note details including line items.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"}},required:["resourceId"],group:"customer_credit_notes",readOnly:!0,searchHint:"get customer credit note details line items",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>Ro(e.client,t.resourceId)},{name:"create_customer_credit_note",description:`Create a customer credit note. Saves as draft by default.
703
703
  - Status when finalized is UNAPPLIED (not APPROVED).
704
704
  - Line items use "name" for item description.
705
705
  - contactResourceId required \u2014 search contacts first.
706
- - reference MUST be unique \u2014 generate one with a timestamp if user doesn't specify.`,params:{reference:{type:"string",description:"Credit note reference number"},valueDate:{type:"string",description:"Credit note date (YYYY-MM-DD)"},contactResourceId:{type:"string",description:"Customer contact resourceId"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:rc},required:["name","quantity","unitPrice"]},description:"Credit note line items"},currency:ec,saveAsDraft:{type:"boolean",description:"Save as draft (default true)"},notes:Dr,tag:dl,customFields:dn},required:["valueDate","contactResourceId","lineItems"],group:"customer_credit_notes",readOnly:!1,searchHint:"create new customer credit note draft",execute:async(e,t)=>{let{notes:r,tag:n,...o}=t,i={...o,...r!==void 0&&{invoiceNotes:r},...n!==void 0&&{tags:[n]}};return i.reference||(i.reference=`CCN-${Date.now()}`),Of(e.client,i)}},{name:"delete_customer_credit_note",description:"Delete a draft customer credit note.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"}},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"permanently delete draft customer credit note",isDestructive:!0,execute:async(e,t)=>$0(e.client,t.resourceId)},{name:"update_customer_credit_note",description:'Update a draft customer credit note (change amount, line items, contact, date, notes). Use when the user says "update", "change", "fix", or "correct" a credit note.',params:{resourceId:{type:"string",description:"Customer credit note resourceId"},reference:yo,valueDate:go,lineItems:fi,notes:Dr,tag:dl,customFields:dn},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"update customer credit note lines reference",execute:async(e,t)=>{let{resourceId:r,notes:n,tag:o,...i}=t,s={...i,...n!==void 0&&{invoiceNotes:n},...o!==void 0&&{tags:[o]}};return O0(e.client,r,s)}},{name:"finalize_customer_credit_note",description:"Finalize a draft customer credit note (set saveAsDraft=false). Status becomes UNAPPLIED.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"},reference:yo,valueDate:go,lineItems:fi,notes:Dr},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"approve finalize customer credit note",isDestructive:!0,execute:async(e,t)=>{let{resourceId:r,notes:n,...o}=t,i={...o,...n!==void 0&&{invoiceNotes:n}},s=await eh(e.client,"customer_credit_note",r,i);return $f(e.client,r,s)}},{name:"create_customer_credit_note_refund",description:"Record a refund payment against a customer credit note.",params:{creditNoteId:{type:"string",description:"Customer credit note resourceId"},paymentAmount:{type:"number",description:"Refund amount"},transactionAmount:{type:"number",description:"Amount in credit note currency (defaults to paymentAmount for same-currency)"},accountResourceId:{type:"string",description:"Bank/cash account resourceId"},valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},reference:{type:"string",description:"Payment reference"},paymentMethod:Qm},required:["creditNoteId","paymentAmount","accountResourceId","valueDate"],group:"customer_credit_notes",readOnly:!1,searchHint:"refund customer credit note to bank account",isDestructive:!0,execute:async(e,t)=>{let r=Number(t.paymentAmount);if(!Number.isFinite(r)||r<=0)throw new Error("paymentAmount must be a positive number");let n=Number(t.transactionAmount??r);if(!Number.isFinite(n)||n<=0)throw new Error("transactionAmount must be a positive number");return Rf(e.client,t.creditNoteId,{paymentAmount:r,transactionAmount:n,accountResourceId:t.accountResourceId,valueDate:t.valueDate,dueDate:t.valueDate,reference:t.reference??"",paymentMethod:t.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1})}},{name:"list_customer_credit_note_refunds",description:"List refund payments for a customer credit note.",params:{creditNoteId:{type:"string",description:"Customer credit note resourceId"}},required:["creditNoteId"],group:"customer_credit_notes",readOnly:!0,searchHint:"list refunds on a customer credit note",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>R0(e.client,t.creditNoteId)},gt("list_supplier_credit_notes","List supplier credit notes (AP adjustments/refunds). Paginated \u2014 response includes totalElements. Use limit/offset to page.","supplier_credit_notes",(e,t,r)=>F0(e,{limit:r,offset:t}),"list supplier credit notes with status pagination"),Rt({name:"search_supplier_credit_notes",description:"Search supplier credit notes by reference, status, contact, tag. Status: DRAFT, UNAPPLIED, PARTIALLY_APPLIED, APPLIED, VOID.",group:"supplier_credit_notes",fields:vs,defaults:Bp,fetcher:Nf,searchHint:"find supplier credit notes by status contact reference"}),{name:"get_supplier_credit_note",description:"Get full supplier credit note details including line items.",params:{resourceId:{type:"string",description:"Supplier credit note resourceId"}},required:["resourceId"],group:"supplier_credit_notes",readOnly:!0,searchHint:"get supplier credit note details line items",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>No(e.client,t.resourceId)},{name:"create_supplier_credit_note",description:`Create a supplier credit note. Saves as draft by default.
706
+ - reference MUST be unique \u2014 generate one with a timestamp if user doesn't specify.`,params:{reference:{type:"string",description:"Credit note reference number"},valueDate:{type:"string",description:"Credit note date (YYYY-MM-DD)"},contactResourceId:{type:"string",description:"Customer contact resourceId"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:rc},required:["name","quantity","unitPrice"]},description:"Credit note line items"},currency:ec,saveAsDraft:{type:"boolean",description:"Save as draft (default true)"},notes:Dr,tag:dl,customFields:dn},required:["valueDate","contactResourceId","lineItems"],group:"customer_credit_notes",readOnly:!1,searchHint:"create new customer credit note draft",execute:async(e,t)=>{let{notes:r,tag:n,...o}=t,i={...o,...r!==void 0&&{invoiceNotes:r},...n!==void 0&&{tags:[n]}};return i.reference||(i.reference=`CCN-${Date.now()}`),Of(e.client,i)}},{name:"delete_customer_credit_note",description:"Delete a draft customer credit note.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"}},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"permanently delete draft customer credit note",isDestructive:!0,execute:async(e,t)=>$0(e.client,t.resourceId)},{name:"update_customer_credit_note",description:'Update a draft customer credit note (change amount, line items, contact, date, notes). Use when the user says "update", "change", "fix", or "correct" a credit note.',params:{resourceId:{type:"string",description:"Customer credit note resourceId"},reference:yo,valueDate:go,lineItems:fi,notes:Dr,tag:dl,customFields:dn},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"update customer credit note lines reference",execute:async(e,t)=>{let{resourceId:r,notes:n,tag:o,...i}=t,s={...i,...n!==void 0&&{invoiceNotes:n},...o!==void 0&&{tags:[o]}};return O0(e.client,r,s)}},{name:"finalize_customer_credit_note",description:"Finalize a draft customer credit note (set saveAsDraft=false). Status becomes UNAPPLIED.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"},reference:yo,valueDate:go,lineItems:fi,notes:Dr},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"approve finalize customer credit note",isDestructive:!0,execute:async(e,t)=>{let{resourceId:r,notes:n,...o}=t,i={...o,...n!==void 0&&{invoiceNotes:n}},s=await eh(e.client,"customer_credit_note",r,i);return $f(e.client,r,s)}},{name:"create_customer_credit_note_refund",description:"Record a refund payment against a customer credit note.",params:{creditNoteId:{type:"string",description:"Customer credit note resourceId"},paymentAmount:{type:"number",description:"Refund amount"},transactionAmount:{type:"number",description:"Amount in credit note currency (defaults to paymentAmount for same-currency)"},accountResourceId:{type:"string",description:"Bank/cash account resourceId"},valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},reference:{type:"string",description:"Payment reference"},paymentMethod:Qm},required:["creditNoteId","paymentAmount","accountResourceId","valueDate"],group:"customer_credit_notes",readOnly:!1,searchHint:"refund customer credit note to bank account",isDestructive:!0,execute:async(e,t)=>{let r=Number(t.paymentAmount);if(!Number.isFinite(r)||r<=0)throw new Error("paymentAmount must be a positive number");let n=Number(t.transactionAmount??r);if(!Number.isFinite(n)||n<=0)throw new Error("transactionAmount must be a positive number");return Rf(e.client,t.creditNoteId,{paymentAmount:r,transactionAmount:n,accountResourceId:t.accountResourceId,valueDate:t.valueDate,dueDate:t.valueDate,reference:t.reference??"",paymentMethod:t.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1})}},{name:"list_customer_credit_note_refunds",description:"List refund payments for a customer credit note.",params:{creditNoteId:{type:"string",description:"Customer credit note resourceId"}},required:["creditNoteId"],group:"customer_credit_notes",readOnly:!0,searchHint:"list refunds on a customer credit note",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>R0(e.client,t.creditNoteId)},gt("list_supplier_credit_notes","List supplier credit notes (AP adjustments/refunds). Paginated \u2014 response includes totalElements. Use limit/offset to page.","supplier_credit_notes",(e,t,r)=>F0(e,{limit:r,offset:t}),"list supplier credit notes with status pagination"),Rt({name:"search_supplier_credit_notes",description:"Search supplier credit notes. Status: DRAFT, UNAPPLIED, PARTIALLY_APPLIED, APPLIED, VOID.",group:"supplier_credit_notes",fields:vs,defaults:Bp,fetcher:Nf,searchHint:"find supplier credit notes refunds CN by reference status contact tag"}),{name:"get_supplier_credit_note",description:"Get full supplier credit note details including line items.",params:{resourceId:{type:"string",description:"Supplier credit note resourceId"}},required:["resourceId"],group:"supplier_credit_notes",readOnly:!0,searchHint:"get supplier credit note details line items",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>No(e.client,t.resourceId)},{name:"create_supplier_credit_note",description:`Create a supplier credit note. Saves as draft by default.
707
707
  - Status when finalized is UNAPPLIED (not APPROVED).
708
708
  - Line items use "name" for item description.
709
709
  - contactResourceId required \u2014 search contacts first.`,params:{reference:{type:"string",description:"Credit note reference number"},valueDate:{type:"string",description:"Credit note date (YYYY-MM-DD)"},contactResourceId:{type:"string",description:"Supplier contact resourceId"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:rc},required:["name","quantity","unitPrice"]},description:"Credit note line items"},currency:ec,saveAsDraft:{type:"boolean",description:"Save as draft (default true)"},notes:Dr,tag:dl,customFields:dn},required:["valueDate","contactResourceId","lineItems"],group:"supplier_credit_notes",readOnly:!1,searchHint:"create new supplier credit note draft",execute:async(e,t)=>{let{notes:r,tag:n,...o}=t,i={...o,...r!==void 0&&{invoiceNotes:r},...n!==void 0&&{tags:[n]}};return i.reference||(i.reference=`SCN-${Date.now()}`),kf(e.client,i)}},{name:"delete_supplier_credit_note",description:"Delete a draft supplier credit note.",params:{resourceId:{type:"string",description:"Supplier credit note resourceId"}},required:["resourceId"],group:"supplier_credit_notes",readOnly:!1,searchHint:"permanently delete draft supplier credit note",isDestructive:!0,execute:async(e,t)=>L0(e.client,t.resourceId)},{name:"update_supplier_credit_note",description:'Update a draft supplier credit note (change amount, line items, contact, date, notes). Use when the user says "update", "change", "fix", or "correct" a credit note.',params:{resourceId:{type:"string",description:"Supplier credit note resourceId"},reference:yo,valueDate:go,lineItems:fi,notes:Dr,tag:dl,customFields:dn},required:["resourceId"],group:"supplier_credit_notes",readOnly:!1,searchHint:"update supplier credit note lines reference",execute:async(e,t)=>{let{resourceId:r,notes:n,tag:o,...i}=t,s={...i,...n!==void 0&&{invoiceNotes:n},...o!==void 0&&{tags:[o]}};return P0(e.client,r,s)}},{name:"finalize_supplier_credit_note",description:"Finalize a draft supplier credit note (set saveAsDraft=false). Status becomes UNAPPLIED.",params:{resourceId:{type:"string",description:"Supplier credit note resourceId"},reference:yo,valueDate:go,lineItems:fi,notes:Dr},required:["resourceId"],group:"supplier_credit_notes",readOnly:!1,searchHint:"approve finalize supplier credit note",isDestructive:!0,execute:async(e,t)=>{let{resourceId:r,notes:n,...o}=t,i={...o,...n!==void 0&&{invoiceNotes:n}},s=await eh(e.client,"supplier_credit_note",r,i);return Ff(e.client,r,s)}},{name:"create_supplier_credit_note_refund",description:"Record a refund payment against a supplier credit note.",params:{creditNoteId:{type:"string",description:"Supplier credit note resourceId"},paymentAmount:{type:"number",description:"Refund amount"},transactionAmount:{type:"number",description:"Amount in credit note currency (defaults to paymentAmount for same-currency)"},accountResourceId:{type:"string",description:"Bank/cash account resourceId"},valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},reference:{type:"string",description:"Payment reference"},paymentMethod:Qm},required:["creditNoteId","paymentAmount","accountResourceId","valueDate"],group:"supplier_credit_notes",readOnly:!1,searchHint:"refund supplier credit note from bank account",isDestructive:!0,execute:async(e,t)=>{let r=Number(t.paymentAmount);if(!Number.isFinite(r)||r<=0)throw new Error("paymentAmount must be a positive number");let n=Number(t.transactionAmount??r);if(!Number.isFinite(n)||n<=0)throw new Error("transactionAmount must be a positive number");return Pf(e.client,t.creditNoteId,{paymentAmount:r,transactionAmount:n,accountResourceId:t.accountResourceId,valueDate:t.valueDate,dueDate:t.valueDate,reference:t.reference??"",paymentMethod:t.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1})}},{name:"list_supplier_credit_note_refunds",description:"List refund payments for a supplier credit note.",params:{creditNoteId:{type:"string",description:"Supplier credit note resourceId"}},required:["creditNoteId"],group:"supplier_credit_notes",readOnly:!0,searchHint:"list refunds on a supplier credit note",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>j0(e.client,t.creditNoteId)},{name:"list_currencies",description:"List currencies enabled for the organization. Returns currency code, name, symbol, and whether it is the base currency.",params:{},required:[],group:"currencies",readOnly:!0,searchHint:"list active currencies in organization",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async e=>Lf(e.client)},{name:"add_currency",description:"Enable one or more currencies for the organization.",params:{currencies:{type:"array",items:{type:"string"},description:'Currency codes to add (e.g., ["USD", "EUR"])'}},required:["currencies"],group:"currencies",readOnly:!1,searchHint:"add new currency to organization",execute:async(e,t)=>{let r=t.currencies,n=await Lf(e.client),o=new Set(n.data.map(c=>c.currencyCode.toUpperCase())),i=r.filter(c=>o.has(c.toUpperCase())),s=r.filter(c=>!o.has(c.toUpperCase()));if(s.length===0)return{_guard:"duplicate_skipped",message:`All currencies already enabled: ${r.join(", ")}.`,existing:i};let a=await B0(e.client,s);return i.length>0?{...a,_note:`Skipped already-enabled: ${i.join(", ")}`}:a}},{name:"list_currency_rates",description:"List exchange rates for a specific currency. IMPORTANT: You MUST call list_currencies first to discover which currencies the org has enabled \u2014 never guess or assume currency codes.",params:{currencyCode:{type:"string",description:'Currency code (e.g., "USD")'},...h$},required:["currencyCode"],group:"currencies",readOnly:!0,searchHint:"list exchange rates for a currency pair",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>{let{limit:r,offset:n}=GJ(t),o=t.currencyCode;return Lp((i,s)=>U0(e.client,o,{limit:s,offset:i}),r,n,100)}},{name:"add_currency_rate",description:'Add or set an exchange rate for a currency. ALWAYS use this tool even when the user says "update rate" \u2014 it handles both new and existing rates. Rate is relative to the base currency. Call list_currencies first to get valid currency codes.',params:{currencyCode:{type:"string",description:"Currency code"},rate:{type:"number",description:"Exchange rate (e.g., 1.35 for 1 USD = 1.35 SGD)"},rateApplicableFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},rateApplicableTo:{type:"string",description:"End date (YYYY-MM-DD, optional)"}},required:["currencyCode","rate","rateApplicableFrom"],group:"currencies",readOnly:!1,searchHint:"add new exchange rate for currency pair",execute:async(e,t)=>q0(e.client,t.currencyCode,{rate:t.rate,rateApplicableFrom:t.rateApplicableFrom,rateApplicableTo:t.rateApplicableTo})},{name:"update_currency_rate",description:'Update an EXISTING exchange rate record by its resourceId. Requires the rate resourceId from list_currency_rates. WARNING: If the user says "update the rate" or "set the rate", they almost always mean add_currency_rate (which creates/overwrites for a date). Only use this tool when explicitly modifying an existing rate record by ID.',params:{currencyCode:{type:"string",description:"Currency code"},resourceId:{type:"string",description:"Rate resourceId"},rate:{type:"number",description:"New exchange rate"},rateApplicableFrom:{type:"string",description:"Start date (YYYY-MM-DD)"},rateApplicableTo:{type:"string",description:"End date (YYYY-MM-DD, optional)"}},required:["currencyCode","resourceId","rate","rateApplicableFrom"],group:"currencies",readOnly:!1,searchHint:"update existing exchange rate value",execute:async(e,t)=>z0(e.client,t.currencyCode,t.resourceId,{rate:t.rate,rateApplicableFrom:t.rateApplicableFrom,rateApplicableTo:t.rateApplicableTo})},{name:"start_currency_rates_import_job",description:"Start an async job to import currency rates from a CSV file URL.",params:{currencyCode:{type:"string",description:"Currency code"},csvUrl:{type:"string",description:"URL of the CSV file to import"}},required:["currencyCode","csvUrl"],group:"currencies",readOnly:!1,searchHint:"import exchange rates from external source",execute:async(e,t)=>Y0(e.client,t.currencyCode,t.csvUrl)},{name:"get_currency_rates_import_job_status",description:"Check the status of a currency rates import job.",params:{jobId:{type:"string",description:"Job ID from start_currency_rates_import_job"}},required:["jobId"],group:"currencies",readOnly:!0,searchHint:"check status of currency rates import job",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>J0(e.client,t.jobId)},{name:"bulk_upsert_currency_rates",description:"Create exchange rates in bulk (max 500 per call). Auto-enables currencies not yet enabled in the org \u2014 no need to call add_currency first. Requires rateDirection per rate. Response surfaces per-row failures: `failedRows[]` (each with rowIndex, columnName, columnValue, errorCode, errorMessage) + `failedCount` alongside `resourceIds[]` for successful inserts. Omitting `rateApplicableTo` defaults it to `rateApplicableFrom - 0.999ms` (no temporal gap).",params:{rates:{type:"array",description:"Array of exchange rates to create",items:{type:"object",properties:{sourceCurrencyCode:{type:"string",description:"Source currency code (ISO 4217, e.g. USD, EUR)"},rate:{type:"number",description:"Exchange rate value (must be > 0)"},rateDirection:{type:"string",description:"Rate direction",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"]},rateApplicableFrom:{type:"string",description:"Rate start date (YYYY-MM-DD)"},rateApplicableTo:{type:"string",description:"Rate end date (YYYY-MM-DD, optional)"}},required:["sourceCurrencyCode","rate","rateDirection","rateApplicableFrom"]}}},required:["rates"],group:"currencies",readOnly:!1,searchHint:"bulk create or update multiple currency rates",execute:async(e,t)=>(await G0(e.client,t.rates)).data},gt("list_tax_profiles","List tax profiles (GST, VAT, etc.). Returns name, rate, tax type.","tax_profiles",(e,t,r)=>fu(e,{limit:r,offset:t}),"list tax profiles GST VAT rates"),gt("list_tax_types","List available tax types. Use the tax type code when creating tax profiles.","tax_profiles",(e,t,r)=>tb(e,{limit:r,offset:t}),"list available tax types for profile creation"),{name:"create_tax_profile",description:"Create a new tax profile. List tax types first to get the taxTypeCode. Automatically checks for duplicates by name \u2014 returns existing profile if found.",params:{name:{type:"string",description:'Tax profile name (e.g., "GST 9%")'},taxRate:{type:"number",description:"Tax rate as percentage (e.g., 9 for 9%)"},taxTypeCode:{type:"string",description:"Tax type code (from list_tax_types)"}},required:["name","taxRate","taxTypeCode"],group:"tax_profiles",readOnly:!1,searchHint:"create new tax profile GST VAT rate",execute:async(e,t)=>{let r=t.name,n=await pb(e.client,r);return n?{_guard:"duplicate_skipped",message:`Tax profile "${r}" already exists.`,existing:n}:rb(e.client,{name:r,taxRate:t.taxRate,taxTypeCode:t.taxTypeCode})}},gt("list_cash_in","List cash-in entries (direct cash receipts). Paginated.","cash_entries",(e,t,r)=>Qb(e,{limit:r,offset:t}),"list cash in receipt entries with pagination"),{name:"create_cash_in",description:`Record money received INTO a bank account from an EXTERNAL source (customer payment, refund received, deposit). For inter-account moves use create_cash_transfer.
@@ -718,7 +718,7 @@ lines = offsetting entries: { accountResourceId, type: 'DEBIT' (typical for the
718
718
 
719
719
  NOT for external parties \u2014 use create_cash_in (receiving) / create_cash_out (paying).
720
720
 
721
- cashOut = source, cashIn = destination. Each side needs accountResourceId + amount. reference auto-generated if omitted. Do NOT send currency/exchangeRate (derived server-side).`,params:{reference:{type:"string",description:"Reference number"},valueDate:{type:"string",description:"Date (YYYY-MM-DD)"},cashOut:{type:"object",properties:{accountResourceId:{type:"string",description:"Source bank account resourceId"},amount:{type:"number",description:"Transfer amount"}},required:["accountResourceId","amount"]},cashIn:{type:"object",properties:{accountResourceId:{type:"string",description:"Destination bank account resourceId"},amount:{type:"number",description:"Transfer amount"}},required:["accountResourceId","amount"]},tags:{type:"array",items:{type:"string"},description:"Tags (string array)"},saveAsDraft:{type:"boolean",description:"Save as draft (default true)"}},required:["valueDate","cashOut","cashIn"],group:"cash_transfers",readOnly:!1,searchHint:"create cash transfer between bank accounts",execute:async(e,t)=>{let r={...t};return r.reference||(r.reference=`CT-${Date.now()}`),Af(e.client,r)}},pn("delete_cash_in","Delete (void) a cash-in entry. Uses parentEntityResourceId from create response.","cash_entries",(e,t)=>_s(e,t),"delete void a cash in receipt entry"),pn("delete_cash_out","Delete (void) a cash-out entry. Uses parentEntityResourceId from create response.","cash_entries",(e,t)=>_s(e,t),"delete void a cash out payment entry"),pn("delete_cash_transfer","Delete (void) a cash transfer. Uses parentEntityResourceId from create response.","cash_transfers",(e,t)=>_s(e,t),"delete void a cash transfer between accounts"),gt("list_scheduled_invoices","List scheduled (recurring) invoices. Paginated.","schedulers",(e,t,r)=>nv(e,{limit:r,offset:t}),"list recurring scheduled invoices subscriptions"),gt("list_scheduled_bills","List scheduled (recurring) bills. Paginated.","schedulers",(e,t,r)=>ov(e,{limit:r,offset:t}),"list recurring scheduled bills subscriptions"),gt("list_scheduled_journals","List scheduled (recurring) journals. Paginated.","schedulers",(e,t,r)=>iv(e,{limit:r,offset:t}),"list recurring scheduled journal entries"),{name:"get_bank_account",description:"Get full bank account details by resourceId.",params:{resourceId:{type:"string",description:"Bank account resourceId"}},required:["resourceId"],group:"bank",readOnly:!0,searchHint:"get bank account details balance by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>Yc(e.client,t.resourceId)},Rt({name:"search_bank_records",description:"Search bank records for a specific account. Filter by status, date, description, payer, reference, amount range. Call list_bank_accounts first to get accountResourceId.",group:"bank",fields:Vp,defaults:Hp,fetcher:Cy,pathParam:"accountResourceId",pathParamDescription:"Bank account resourceId (UUID). Call list_bank_accounts first.",searchHint:"find bank records by status date amount description"}),Rt({name:"search_cashflow_transactions",description:"Search cashflow transactions (unified ledger). Filter by type, direction (PAYIN/PAYOUT), status, date, reference, account.",group:"cashflow",fields:Ni,defaults:ki,fetcher:Es,searchHint:"find cashflow transactions by type direction status"}),gt("list_bookmarks","List organization bookmarks (saved values/settings).","bookmarks",(e,t,r)=>V0(e,{limit:r,offset:t}),"list saved bookmarks reports shortcuts"),{name:"get_bookmark",description:"Get a bookmark by resourceId.",params:{resourceId:{type:"string",description:"Bookmark resourceId"}},required:["resourceId"],group:"bookmarks",readOnly:!0,searchHint:"get bookmark saved report details",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>H0(e.client,t.resourceId)},{name:"create_bookmarks",description:"Create one or more bookmarks. categoryCode must be one of: AUDIT_AND_ASSURANCE, BANKING_AND_FINANCE, BUDGETS_AND_CONTROLS, EMPLOYEES_AND_PAYROLL, EXTERNAL_DOCUMENTS, GENERAL_INFORMATION, OWNERS_AND_DIRECTORS, TAXATION_AND_COMPLIANCE, WORKFLOWS_AND_PROCESSES.",params:{items:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Bookmark name"},value:{type:"string",description:"Bookmark value"},categoryCode:{type:"string",description:"Category code (e.g., GENERAL_INFORMATION)"},datatypeCode:{type:"string",description:"Datatype code (default: TEXT)"}},required:["name","value","categoryCode","datatypeCode"]},description:"Bookmarks to create"}},required:["items"],group:"bookmarks",readOnly:!1,searchHint:"create new bookmark saved report shortcut",execute:async(e,t)=>jf(e.client,t.items)},{name:"update_bookmark",description:"Update an existing bookmark (name, value, or category). Use when modifying a previously created bookmark.",params:{resourceId:{type:"string",description:"Bookmark resourceId"},name:{type:"string",description:"New name"},value:{type:"string",description:"New value"},categoryCode:{type:"string",description:"New category code"}},required:["resourceId"],group:"bookmarks",readOnly:!1,searchHint:"update bookmark name or configuration",execute:async(e,t)=>{let{resourceId:r,...n}=t;return W0(e.client,r,n)}},gt("list_org_users","List organization users (team members). Returns name, email, roles.","org_users",(e,t,r)=>Z0(e,{limit:r,offset:t}),"list organization users team members"),Rt({name:"search_org_users",description:"Search organization users by name, email, role, status. For OR search (name or email), use filter param.",group:"org_users",fields:gf,defaults:yf,fetcher:K0,searchHint:"find organization users by name email role status"}),{name:"invite_org_user",description:"Invite a new user to the organization.",params:{firstName:{type:"string",description:"First name"},lastName:{type:"string",description:"Last name"},email:{type:"string",description:"Email address"},moduleRoles:{type:"array",items:{type:"object",properties:{moduleName:{type:"string",description:"Module name: ORGANIZATION, USER_MANAGEMENT, ACCOUNTING, SALES, PURCHASES, REPORTS, or FIXED_ASSET"},roleCode:{type:"string",description:"Role code: ADMIN, PREPARER, MEMBER, or NO_ACCESS"}},required:["moduleName","roleCode"]},description:"Module role assignments"}},required:["firstName","lastName","email","moduleRoles"],group:"org_users",readOnly:!1,searchHint:"invite new user to join organization team",execute:async(e,t)=>Pu(e.client,t)},{name:"update_org_user",description:"Update an organization user's module roles.",params:{resourceId:{type:"string",description:"Org user resourceId"},moduleRoles:{type:"array",items:{type:"object",properties:{moduleName:{type:"string",description:"Module name: ORGANIZATION, USER_MANAGEMENT, ACCOUNTING, SALES, PURCHASES, REPORTS, or FIXED_ASSET"},roleCode:{type:"string",description:"Role code: ADMIN, PREPARER, MEMBER, or NO_ACCESS"}},required:["moduleName","roleCode"]}}},required:["resourceId","moduleRoles"],group:"org_users",readOnly:!1,searchHint:"update organization user role permissions",execute:async(e,t)=>X0(e.client,t.resourceId,{moduleRoles:t.moduleRoles})},{name:"remove_org_user",description:"Remove a user from the organization.",params:{resourceId:{type:"string",description:"Org user resourceId"}},required:["resourceId"],group:"org_users",readOnly:!1,searchHint:"remove user from organization team",isDestructive:!0,execute:async(e,t)=>Q0(e.client,t.resourceId)},{name:"list_payments",description:"List recent payments across all transaction types. Paginated.",params:{...h$},required:[],group:"payments",readOnly:!0,searchHint:"list payment records transactions with pagination",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>{let r=t.limit,n=t.offset;return a0(e.client,{limit:r??100,offset:n??0})}},Rt({name:"search_payments",description:"Search payments by type, direction (PAYIN/PAYOUT), method, date, reference, account.",group:"payments",fields:Jp,defaults:Gp,fetcher:wf,searchHint:"find payments by type direction method date account"}),{name:"download_export",description:`Analytical / financial / audit report XLSX. Returns { fileName, fileUrl } (pre-signed, ~5 min).
721
+ cashOut = source, cashIn = destination. Each side needs accountResourceId + amount. reference auto-generated if omitted. Do NOT send currency/exchangeRate (derived server-side).`,params:{reference:{type:"string",description:"Reference number"},valueDate:{type:"string",description:"Date (YYYY-MM-DD)"},cashOut:{type:"object",properties:{accountResourceId:{type:"string",description:"Source bank account resourceId"},amount:{type:"number",description:"Transfer amount"}},required:["accountResourceId","amount"]},cashIn:{type:"object",properties:{accountResourceId:{type:"string",description:"Destination bank account resourceId"},amount:{type:"number",description:"Transfer amount"}},required:["accountResourceId","amount"]},tags:{type:"array",items:{type:"string"},description:"Tags (string array)"},saveAsDraft:{type:"boolean",description:"Save as draft (default true)"}},required:["valueDate","cashOut","cashIn"],group:"cash_transfers",readOnly:!1,searchHint:"create cash transfer between bank accounts",execute:async(e,t)=>{let r={...t};return r.reference||(r.reference=`CT-${Date.now()}`),Af(e.client,r)}},pn("delete_cash_in","Delete (void) a cash-in entry. Uses parentEntityResourceId from create response.","cash_entries",(e,t)=>_s(e,t),"delete void a cash in receipt entry"),pn("delete_cash_out","Delete (void) a cash-out entry. Uses parentEntityResourceId from create response.","cash_entries",(e,t)=>_s(e,t),"delete void a cash out payment entry"),pn("delete_cash_transfer","Delete (void) a cash transfer. Uses parentEntityResourceId from create response.","cash_transfers",(e,t)=>_s(e,t),"delete void a cash transfer between accounts"),gt("list_scheduled_invoices","List scheduled (recurring) invoices. Paginated.","schedulers",(e,t,r)=>nv(e,{limit:r,offset:t}),"list recurring scheduled invoices subscriptions"),gt("list_scheduled_bills","List scheduled (recurring) bills. Paginated.","schedulers",(e,t,r)=>ov(e,{limit:r,offset:t}),"list recurring scheduled bills subscriptions"),gt("list_scheduled_journals","List scheduled (recurring) journals. Paginated.","schedulers",(e,t,r)=>iv(e,{limit:r,offset:t}),"list recurring scheduled journal entries"),{name:"get_bank_account",description:"Get full bank account details by resourceId.",params:{resourceId:{type:"string",description:"Bank account resourceId"}},required:["resourceId"],group:"bank",readOnly:!0,searchHint:"get bank account details balance by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>Yc(e.client,t.resourceId)},Rt({name:"search_bank_records",description:"Search bank records for a specific account. Call list_bank_accounts first to get accountResourceId.",group:"bank",fields:Vp,defaults:Hp,fetcher:Cy,pathParam:"accountResourceId",pathParamDescription:"Bank account resourceId (UUID). Call list_bank_accounts first.",searchHint:"find bank records statement entries transactions by status date amount description payer reference range"}),Rt({name:"search_cashflow_transactions",description:"Search cashflow transactions (unified ledger). Filter by type, direction (PAYIN/PAYOUT), status, date, reference, account.",group:"cashflow",fields:Ni,defaults:ki,fetcher:Es,searchHint:"find cashflow transactions by type direction status"}),gt("list_bookmarks","List organization bookmarks (saved values/settings).","bookmarks",(e,t,r)=>V0(e,{limit:r,offset:t}),"list saved bookmarks reports shortcuts"),{name:"get_bookmark",description:"Get a bookmark by resourceId.",params:{resourceId:{type:"string",description:"Bookmark resourceId"}},required:["resourceId"],group:"bookmarks",readOnly:!0,searchHint:"get bookmark saved report details",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>H0(e.client,t.resourceId)},{name:"create_bookmarks",description:"Create one or more bookmarks. categoryCode must be one of: AUDIT_AND_ASSURANCE, BANKING_AND_FINANCE, BUDGETS_AND_CONTROLS, EMPLOYEES_AND_PAYROLL, EXTERNAL_DOCUMENTS, GENERAL_INFORMATION, OWNERS_AND_DIRECTORS, TAXATION_AND_COMPLIANCE, WORKFLOWS_AND_PROCESSES.",params:{items:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Bookmark name"},value:{type:"string",description:"Bookmark value"},categoryCode:{type:"string",description:"Category code (e.g., GENERAL_INFORMATION)"},datatypeCode:{type:"string",description:"Datatype code (default: TEXT)"}},required:["name","value","categoryCode","datatypeCode"]},description:"Bookmarks to create"}},required:["items"],group:"bookmarks",readOnly:!1,searchHint:"create new bookmark saved report shortcut",execute:async(e,t)=>jf(e.client,t.items)},{name:"update_bookmark",description:"Update an existing bookmark (name, value, or category). Use when modifying a previously created bookmark.",params:{resourceId:{type:"string",description:"Bookmark resourceId"},name:{type:"string",description:"New name"},value:{type:"string",description:"New value"},categoryCode:{type:"string",description:"New category code"}},required:["resourceId"],group:"bookmarks",readOnly:!1,searchHint:"update bookmark name or configuration",execute:async(e,t)=>{let{resourceId:r,...n}=t;return W0(e.client,r,n)}},gt("list_org_users","List organization users (team members). Returns name, email, roles.","org_users",(e,t,r)=>Z0(e,{limit:r,offset:t}),"list organization users team members"),Rt({name:"search_org_users",description:"Search organization users. For OR (name or email), use filter param.",group:"org_users",fields:gf,defaults:yf,fetcher:K0,searchHint:"find organization users team members by name email role status OR search"}),{name:"invite_org_user",description:"Invite a new user to the organization.",params:{firstName:{type:"string",description:"First name"},lastName:{type:"string",description:"Last name"},email:{type:"string",description:"Email address"},moduleRoles:{type:"array",items:{type:"object",properties:{moduleName:{type:"string",description:"Module name: ORGANIZATION, USER_MANAGEMENT, ACCOUNTING, SALES, PURCHASES, REPORTS, or FIXED_ASSET"},roleCode:{type:"string",description:"Role code: ADMIN, PREPARER, MEMBER, or NO_ACCESS"}},required:["moduleName","roleCode"]},description:"Module role assignments"}},required:["firstName","lastName","email","moduleRoles"],group:"org_users",readOnly:!1,searchHint:"invite new user to join organization team",execute:async(e,t)=>Pu(e.client,t)},{name:"update_org_user",description:"Update an organization user's module roles.",params:{resourceId:{type:"string",description:"Org user resourceId"},moduleRoles:{type:"array",items:{type:"object",properties:{moduleName:{type:"string",description:"Module name: ORGANIZATION, USER_MANAGEMENT, ACCOUNTING, SALES, PURCHASES, REPORTS, or FIXED_ASSET"},roleCode:{type:"string",description:"Role code: ADMIN, PREPARER, MEMBER, or NO_ACCESS"}},required:["moduleName","roleCode"]}}},required:["resourceId","moduleRoles"],group:"org_users",readOnly:!1,searchHint:"update organization user role permissions",execute:async(e,t)=>X0(e.client,t.resourceId,{moduleRoles:t.moduleRoles})},{name:"remove_org_user",description:"Remove a user from the organization.",params:{resourceId:{type:"string",description:"Org user resourceId"}},required:["resourceId"],group:"org_users",readOnly:!1,searchHint:"remove user from organization team",isDestructive:!0,execute:async(e,t)=>Q0(e.client,t.resourceId)},{name:"list_payments",description:"List recent payments across all transaction types. Paginated.",params:{...h$},required:[],group:"payments",readOnly:!0,searchHint:"list payment records transactions with pagination",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>{let r=t.limit,n=t.offset;return a0(e.client,{limit:r??100,offset:n??0})}},Rt({name:"search_payments",description:"Search payments by type, direction (PAYIN/PAYOUT), method, date, reference, account.",group:"payments",fields:Jp,defaults:Gp,fetcher:wf,searchHint:"find payments by type direction method date account"}),{name:"download_export",description:`Analytical / financial / audit report XLSX. Returns { fileName, fileUrl } (pre-signed, ~5 min).
722
722
 
723
723
  Use this tool (not export_records) for: analysis-* (anomalous-invoices/bills, cashflow-anomalies, gl-journal-audit, exchange-rate-audit, receivables-customer-risk, cash-expense-health); statements (trial-balance, balance-sheet, profit-and-loss, cashflow, general-ledger, cash-balance); aging (ar-report, ap-report); summaries (sales, sales-payments, purchase, purchase-payments, customer-revenue, product-sales, periodic-revenue, supplier-expense, product-purchase, periodic-expense, credit-note, sales-cost-margin); inventory movement (sale-/purchase-inventory-movement); statement-of-account-export.
724
724
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jaz-clio",
3
- "version": "5.4.26",
3
+ "version": "5.4.28",
4
4
  "description": "Clio: Command Line Interface Operator for Jaz AI.",
5
5
  "type": "module",
6
6
  "bin": {