jaz-clio 5.47.8 → 5.47.10

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.47.8
3
+ version: 5.47.10
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, 159 production gotchas, error
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-cli
3
- version: 5.47.8
3
+ version: 5.47.10
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.47.8
3
+ version: 5.47.10
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-kit
3
- version: 5.47.8
3
+ version: 5.47.10
4
4
  description: >-
5
5
  Use this skill when an accountant, bookkeeper, or owner is running real books
6
6
  in Jaz across one or more organizations from the terminal — setting up a
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-pseudo-sql
3
- version: 5.47.8
3
+ version: 5.47.10
4
4
  description: >-
5
5
  Use this skill when answering ad-hoc data questions that aren't covered by
6
6
  download_export (canonical reports — anomaly, audit, aging, P&L, BS, GL,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-jobs
3
- version: 5.47.8
3
+ version: 5.47.10
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-recipes
3
- version: 5.47.8
3
+ version: 5.47.10
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,7 +678,7 @@ Unsupported type: `+t.type,"ENOTSUP");t._finish()})};Jc.prototype._stat=function
678
678
  `,a),u=c!==-1?c:i.length;return i.slice(s,u).trim()}catch{return null}}function Svr(){let t=Ait(import.meta.url),e=mit(t),r=[dm(e,"..","..","..","help-center-mirror"),dm(e,"..","..","..","assets","skills","api","help-center-mirror"),dm(e,"help-center-mirror")];for(let n of r)try{return _de(dm(n,"index.md"),"utf-8"),n}catch{}return null}var fit,pit,Evr,bvr,Cvr,Ivr,vvr,wvr,_vr,cz,hit,wde,hB=X(()=>{"use strict";vde();Jb();fit=1.2,pit=.75,Evr=1.5,bvr=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","shall","should","may","might","must","can","could","am","i","me","my","we","our","you","your","he","she","it","they","them","this","that","these","those","what","which","who","whom","how","when","where","why","if","then","than","so","no","not","or","and","but","in","on","at","to","for","of","with","by","from","as","into","about","between","through","after","before","during","above","below","up","down","out","off","over","under","again","further","just","also","very","too","only","own","same","both","each","all","any","few","more","most","other","some","such","here","there"]),Cvr=new Map([["recon",["reconciliation","reconcile","reconciled"]],["txn",["transaction","transactions"]],["txns",["transactions","transaction"]],["acct",["account","accounts"]],["accts",["accounts","account"]],["inv",["invoice","invoices"]],["cn",["credit","note"]],["ar",["receivable","receivables"]],["ap",["payable","payables"]],["pmt",["payment","payments"]],["stmt",["statement","statements"]],["bal",["balance","balances"]],["fa",["fixed","assets","asset"]],["gst",["tax","goods","services"]],["vat",["tax","value","added"]],["fx",["foreign","exchange","currency"]],["config",["configuration","configure","settings"]],["depr",["depreciation"]],["amort",["amortization"]],["coa",["chart","accounts"]],["po",["purchase","order"]],["so",["sales","order"]],["org",["organization"]],["subs",["subscription","subscriptions"]],["amt",["amount","amounts"]],["qty",["quantity"]],["desc",["description"]],["ref",["reference"]],["num",["number"]]]);Ivr=.7,vvr=3,wvr=32,_vr=5;cz=null,hit=null;wde=null});import{existsSync as Rvr,readFileSync as xvr}from"node:fs";import{dirname as Tvr,join as Sde}from"node:path";import{fileURLToPath as Bvr}from"node:url";function mB(t){let e=t??Qvr();if(!e)return null;if(lz&&Cit===e)return lz;try{let r=xvr(e,"utf-8");return lz=JSON.parse(r),Cit=e,lz}catch{return null}}function Qvr(){let t=Bvr(import.meta.url),e=Tvr(t),r=[Sde(e,"..","..","..","help-center-mirror","help-center-embeddings.json"),Sde(e,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),Sde(e,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(Rvr(n))return n;return null}function wit(t,e){let r=Math.min(t.length,e.length),n=0;for(let i=0;i<r;i++)n+=t[i]*e[i];return n}function _it(){return uz!==null?uz:(uz=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",uz||null)}async function Rde(t){let e=_it();if(!e)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),Nvr),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:kvr,input:t}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!Iit&&(Iit=!0,process.stderr.write(`[help-center] CLIO_HELP_CENTER_OPENAI_API_KEY rejected by OpenAI \u2014 falling back to BM25
679
679
  `)),null)}catch{return null}}async function AB(t,e,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??Ovr,c=n.minBm25??Fvr;if(i==="bm25"||!e)return Ty(t,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await Rde(r);return m?vit(t,e,m,{limit:o,section:s}).filter(g=>g.score>=a):Ty(t,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([Rde(r),Promise.resolve(Ty(t,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=vit(t,e,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Dit(p,h,o)}function vit(t,e,r,n){let i=new Map(t.sections.map(c=>[c.slug,c])),o=new Map(t.articles.map(c=>[c.id,c])),s=[];for(let c of e.embeddings){let u=o.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let d=wit(r,c.vector);s.push({articleId:c.articleId,score:d})}s.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of s.slice(0,n.limit)){let d=o.get(c);if(!d)continue;let f=i.get(d.section);f&&a.push({article:d,score:u,scoreKind:"cosine",section:f,matchedTerms:[]})}return a}function Dit(t,e,r){let n=new Map;for(let o=0;o<t.length;o++){let s=t[o],a=1/(bit+o+1),c=n.get(s.article.id);c?c.score+=a:n.set(s.article.id,{score:a,result:s})}for(let o=0;o<e.length;o++){let s=e[o],a=1/(bit+o+1),c=n.get(s.article.id);c?(c.score+=a,c.result=s):n.set(s.article.id,{score:a,result:s})}let i=Array.from(n.values());return i.sort((o,s)=>s.score-o.score),i.slice(0,r).map(o=>({...o.result,score:o.score,scoreKind:"rrf"}))}function xde(t){return t!==null&&!!_it()}var kvr,Nvr,bit,Ovr,Fvr,lz,Cit,uz,Iit,dz=X(()=>{"use strict";hB();kvr="text-embedding-3-small",Nvr=2e3,bit=60,Ovr=.3,Fvr=1.5,lz=null,Cit=null,uz=null,Iit=!1});async function Sit(t,e={}){let r=String(t??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=typeof e.limit=="number"&&!Number.isNaN(e.limit)?e.limit:3,i=Math.max(1,Math.min(10,Math.floor(n))),o=typeof e.section=="string"?e.section:void 0,s=e.mode??"hybrid";try{let a=fB();if(o&&!a.sections.some(d=>d.slug===o))return{error:`Unknown section: "${o}".`,code:"unknown_section",available:a.sections.map(d=>d.slug),hint:"Omit the section parameter to search every section, or pick a slug from the available list."};let c=s==="bm25"?null:mB(),u=await AB(a,c,r,{mode:s,limit:i,section:o});return u.length===0?{results:[],hint:"No matching articles. Try broader keywords or rephrase the question."}:{results:u.map(d=>{let f=(Dde(d.article)??d.article.snippet).slice(0,1500);return{title:d.article.title,section:d.section.name,sectionSlug:d.section.slug,content:f,url:d.article.sourceUrl,score:Math.round(d.score*1e3)/1e3,scoreKind:d.scoreKind,matchedTerms:d.matchedTerms}}),totalArticles:a.articleCount,searchedSections:o?[o]:void 0}}catch(a){return{error:"Help center search failed.",code:"load_failure",detail:a instanceof Error?a.message:String(a),hint:"The help center index could not be loaded."}}}function Rit(){let t=process.env.CLIO_HELP_CENTER_URL?.trim();return t&&t.length>0?t:Lvr}async function fz(t,e={}){let r=String(t??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=o=>({error:"Help center is temporarily unavailable.",hint:o}),i;try{i=new URL(Rit())}catch{return n("Set CLIO_HELP_CENTER_URL to a valid URL, or browse https://help.jaz.ai.")}i.searchParams.set("q",r),typeof e.limit=="number"&&Number.isFinite(e.limit)&&i.searchParams.set("limit",String(e.limit)),typeof e.section=="string"&&e.section&&i.searchParams.set("section",e.section);try{let s=await(await fetch(i,{signal:AbortSignal.timeout(Mvr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return Pvr(a)?a:n("Try again shortly, or browse https://help.jaz.ai.")}catch{return n("Check your connection, or browse https://help.jaz.ai.")}}function Pvr(t){if(typeof t!="object"||t===null)return!1;let e=t;return Array.isArray(e.results)?!0:typeof e.error=="string"}async function Tde(t,e={}){return process.env.CLIO_DAEMON==="1"||pB()?Sit(t,e):fz(t,e)}var Lvr,Mvr,xit=X(()=>{"use strict";hB();dz();Lvr="https://mcp.jaz.ai/help-center/search",Mvr=4e3});var Bde=X(()=>{"use strict";hB();dz();xit();hB()});var Tit,Bit=X(()=>{"use strict";Tit={loan:["cash-in"],lease:["journal"],"prepaid-expense":["bill","cash-out"],"deferred-revenue":["invoice","cash-in"],provision:["journal"],"fixed-deposit":["cash-out"],"accrued-expense":["journal"],dividend:["journal"]}});async function pz(t,e){let{blueprint:r,accountMap:n,finalize:i}=e,o=!i;Uvr(e);let s=await $vr(t,r.capsuleType),a=r.steps[0]?.date??new Date().toISOString().slice(0,10),c=`${r.capsuleName} (${a})`,d={resourceId:(await pA(t,{capsuleTypeResourceId:s,title:c,description:r.capsuleDescription})).data.resourceId,type:r.capsuleType,title:c},f=Oit(e),p=[],h=[];for(let A of r.steps){if(A.step===f){p.push({step:A.step,action:A.action,status:"existing",resourceId:e.existingTxnId,description:A.description});continue}if(A.action==="fixed-asset"||A.action==="note"){p.push({step:A.step,action:A.action,status:"skipped",description:A.description}),h.push(`Step ${A.step} (${A.action}): ${A.description}`);continue}let g=await qvr(t,A,e,o);p.push(g),g.error&&h.push(`Step ${A.step} failed: ${g.error}`)}let m={total:p.length,created:p.filter(A=>A.status==="created").length,existing:p.filter(A=>A.status==="existing").length,skipped:p.filter(A=>A.status==="skipped").length,errors:p.filter(A=>A.status==="error").length,notes:h};return{recipe:e.calcType,capsule:d,steps:p,summary:m}}function Uvr(t){let{blueprint:e,accountMap:r,bankAccountId:n,contactId:i}=t;if(!e.steps.length)throw new Error("Blueprint has no steps to execute.");let o=[];for(let d of e.steps)for(let f of d.lines)Nde(f.account,r)||o.push(f.account);let s=[...new Set(o)];if(s.length>0)throw new Error(`Unmapped account(s) in --input: ${s.join(", ")}.
680
680
  Add these to your account mapping JSON.`);let a=Oit(t);if(e.steps.some(d=>(d.action==="cash-in"||d.action==="cash-out")&&d.step!==a)&&!n)throw new Error("--bank-account is required for recipes with cash-in/cash-out steps.");if(e.steps.some(d=>(d.action==="bill"||d.action==="invoice")&&d.step!==a)&&!i)throw new Error("--contact is required for recipes with bill/invoice steps.")}async function $vr(t,e){let n=(await kE(t)).data.find(o=>o.displayName.toLowerCase()===e.toLowerCase());return n?n.resourceId:(await Ow(t,{displayName:e})).data.resourceId}function Oit(t){if(!t.existingTxnId)return null;let e=Tit[t.calcType];return e?t.blueprint.steps.find(n=>e.includes(n.action))?.step??null:null}async function qvr(t,e,r,n){let{accountMap:i,referencePrefix:o}=r,s=o?`${o}-${e.step}`:void 0;try{let a;switch(e.action){case"journal":{a=(await ig(t,{reference:s,valueDate:e.date,journalEntries:kde(e.lines,i),internalNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"bill":{a=(await dA(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:kit(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"invoice":{a=(await rg(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:kit(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"cash-in":{let{contraLines:c}=Nit(e.lines,r.bankAccountId,i);a=(await Fv(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:kde(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}case"cash-out":{let{contraLines:c}=Nit(e.lines,r.bankAccountId,i);a=(await Qv(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:kde(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}default:return{step:e.step,action:e.action,status:"skipped",description:e.description}}return{step:e.step,action:e.action,status:"created",resourceId:a,description:e.description}}catch(a){return{step:e.step,action:e.action,status:"error",description:e.description,error:a.message}}}function kde(t,e){return t.map(r=>({accountResourceId:Ode(r.account,e),type:r.debit>0?"DEBIT":"CREDIT",amount:r.debit>0?r.debit:r.credit}))}function kit(t,e){return t.filter(r=>Nde(r.account,e)).map(r=>({name:r.account,quantity:1,unitPrice:r.debit>0?r.debit:r.credit,accountResourceId:Ode(r.account,e)}))}function Nit(t,e,r){let n=[],i=null;for(let o of t)Ode(o.account,r)===e&&!i?i=o:n.push(o);return i?{bankLine:i,contraLines:n}:{bankLine:t[0],contraLines:t.slice(1)}}function Nde(t,e){if(e[t])return t;let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return n;return null}function Ode(t,e){let r=Nde(t,e);if(!r)throw new Error(`Unmapped account: "${t}"`);return e[r]}var Fde=X(()=>{"use strict";og();_d();ng();zH();Qw();Bit()});async function Fit(t,e){let n=(await Op((s,a)=>Dd(t,{offset:s,limit:a}))).data;if(n.length===0)return{mapping:{},failures:e.map(s=>({name:s,candidates:[]}))};let i={},o=[];for(let s of e){let a=lP(s,n);if(a)i[s]=a.resourceId;else{let c=fC(s,n,{threshold:.3,limit:3});o.push({name:s,candidates:c.map(u=>u.item.name)})}}return{mapping:i,failures:o}}async function Qit(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let d=(await Zf(t,e)).data;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}let n=e.trim(),o=(await pc(t,{filter:{billingName:{contains:n}},limit:50})).data;if(o.length===0&&(o=(await Wf(t,{offset:0,limit:500})).data),o.length===0)throw new Error("No contacts found. Create one in Jaz first.");let s=n.toLowerCase(),a=o.find(u=>u.billingName?.toLowerCase()===s||u.name?.toLowerCase()===s);if(a)return{resourceId:a.resourceId,displayName:a.billingName||a.name||"Unknown"};let c=uP(n,o,{threshold:.5,limit:5});if(c.length>=1&&c[0].score>=.7){let u=c[0],d=c.length>1?c[1].score:0;if(c.length===1||u.score-d>=.1){let f=u.item;return{resourceId:f.resourceId,displayName:f.billingName||f.name||"Unknown"}}}if(c.length>1){let u=c.map(d=>`${d.item.billingName||d.item.name} (${(d.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 Lit(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let i=await Hb(t,e);return{resourceId:i.data.resourceId,displayName:i.data.name}}let n=await jA(t,e);return{resourceId:n.resourceId,displayName:n.name}}var Mit=X(()=>{"use strict";TE();Xf();vp();VM();lX();uX();ZL()});async function fm(t,e){await t.delete(`/api/v1/cash-entries/${e}`)}async function pm(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}var gB=X(()=>{"use strict";mn()});async function hz(t,e){return t.post("/api/v1/transfer-trial-balance",{...e,currency:Ur(e.currency),taxCurrency:Ur(e.taxCurrency)})}var Qde=X(()=>{"use strict";An()});async function mz(t,e){return t.list("/api/v1/organization/bookmarks",e)}async function Az(t,e){return t.get(`/api/v1/organization/bookmarks/${e}`)}async function yB(t,e){return t.post("/api/v1/organization/bookmarks",{items:e})}async function gz(t,e,r){return t.put(`/api/v1/organization/bookmarks/${e}`,r)}var Lde=X(()=>{"use strict"});function jvr(t){let{refs:e,...r}=t;return e?{...r,refs:e.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function Mv(t,e){return t.post("/api/v1/jots",{entries:e.map(jvr)})}async function yz(t,e){return t.post("/api/v1/jots/search",e)}async function Pit(t,e,r){return t.post(`/api/v1/jots/${e}/disposition`,r)}var Ez=X(()=>{"use strict"});async function Uit(t,e){return t.post("/api/v1/agents/memories",e)}async function Mde(t,e){return t.post("/api/v1/agents/memories/forget",e)}var $it=X(()=>{"use strict"});function bz(){return process.env.ENABLE_MEMORY==="true"}function Pde(){return process.env.ENABLE_MEMORY_CHAT==="true"}function qit(t){return!bz()||!t||!t.progressive?"memory_disabled":t.isInboxOwner?null:"not_owner"}var Ude=X(()=>{"use strict"});var qde={};bs(qde,{default:()=>Hvr,log:()=>$de});var Cz,Yvr,jit,$de,Hvr,jde=X(()=>{"use strict";Cz=()=>{},Yvr=()=>$de,jit=(...t)=>{try{process.stderr.write(t.map(String).join(" ")+`
681
- `)}catch{}},$de={info:Cz,warn:Cz,error:jit,debug:Cz,trace:Cz,fatal:jit,child:Yvr,level:"error"},Hvr=$de});import{createHash as zvr}from"node:crypto";function n0r(t){if(!t||!t.trim())return[null,"directive_required"];let e=t.normalize("NFKC").trim();return e.length>300?[null,"directive_too_long"]:zit.some(r=>e.includes(r))?[null,"directive_invalid"]:Hit.test(e)?[null,"directive_invalid"]:Xvr.test(e)?[null,"directive_contains_url"]:Kvr.test(e)?[null,"directive_contains_email"]:[e,null]}function i0r(t){if(t==null)return[null,null];let e=t.normalize("NFKC").trim();return e?e.length>e0r?[null,"match_condition_too_long"]:zit.some(r=>e.includes(r))?[null,"match_condition_invalid"]:Hit.test(e)?[null,"match_condition_invalid"]:[e,null]:[null,"match_condition_invalid"]}function o0r(t){return t==null?[null,null]:Number.isInteger(t)?t<t0r||t>r0r?[null,"invalid_importance"]:[t,null]:[null,"invalid_importance"]}function s0r(t,e,r,n,i,o,s,a){if(t)return zvr("sha256").update(`${t}:${e}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function a0r(t){Promise.resolve().then(()=>(jde(),qde)).then(({log:e})=>e.info(t,"memory_tool.call")).catch(()=>{})}async function Wit(t,e,r){let n=e.action,i=e.category,o=Wvr[e.scope??"this_org"]??"ORG_USER",s=typeof e.key=="string"?e.key.trim():"",a=null,c=d=>(a0r({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=t.memoryTurn,f=qit(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>Gvr||!Zvr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[C,E]=n0r(e.directive);if(E)return u(E);p=C;let[I,v]=o0r(e.importance);if(v)return u(v);h=I}let[m,A]=i0r(e.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=Jvr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let C={gtid:g};d.quote&&(C.quote=d.quote.slice(0,Vvr));let E=s0r(g,n,o,i,s,p,e.confirms_key,e.replaces_key),I={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...e.replaces_key?{replacesKey:e.replaces_key}:{},...e.confirms_key?{confirmsKey:e.confirms_key}:{},pending:e.pending===!0,source:r?.source??"TOOL",provenance:C,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await Yde(()=>Uit(t.client,I)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let C={category:i,key:s,scope:o};y=await Yde(()=>Mde(t.client,C))}else{let C={forgetAll:!0};y=await Yde(()=>Mde(t.client,C))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function Yde(t){try{let e=await t(),r=e&&typeof e=="object"&&e.data&&typeof e.data=="object"?e.data:e??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(e){return e instanceof lo?e.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${e.status}`}:{ok:!1,reason:"network_error"}}}var Hit,zit,Gvr,Jvr,Vvr,Git,Jit,Vit,Wvr,Zvr,Xvr,Kvr,e0r,t0r,r0r,Zit=X(()=>{"use strict";$it();Sa();Ude();Ude();Hit=/[\x00-\x1f\x7f]/,zit=["{{","}}","```","<",">"],Gvr=120,Jvr=3,Vvr=140,Git=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Jit=["set","forget","forget_all"],Vit=["this_org","all_orgs"],Wvr={this_org:"ORG_USER",all_orgs:"USER"},Zvr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Xvr=/https?:\/\//i,Kvr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,e0r=255,t0r=0,r0r=100});async function Iz(t,e){return t.list("/api/v1/organization-users",e)}async function vz(t,e){return t.search("/api/v1/organization-users/search",e)}async function Pv(t,e){return t.post("/api/v1/organization-users/invite",e)}async function wz(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function _z(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var Hde=X(()=>{"use strict"});async function Dz(t,e){return t.search("/api/v1/cashflow-transactions/search",{limit:e?.limit??100,offset:e?.offset??0,sort:{sortBy:["valueDate"],order:"DESC"}})}async function EB(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function Sz(t,e){return t.get(`/api/v1/payments/${e}`)}async function Rz(t,e,r){return t.put(`/api/v1/payments/${e}`,{...r,currency:Ur(r.currency)})}async function xz(t,e){await t.delete(`/api/v1/payments/${e}`)}function Tz(t,e){return(r,n)=>r.post(`/api/v1/${t}/${e}`,{...n,transactions:n.transactions.map(i=>({...i,currency:Ur(i.currency)}))})}var _in,Din,Sin,Rin,zde=X(()=>{"use strict";An();_in=Tz("sales","bulk-payments"),Din=Tz("sales","batch-payments"),Sin=Tz("purchases","bulk-payments"),Rin=Tz("purchases","batch-payments")});async function Bz(t,e,r={}){let n=c0r.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`;return t.post(n,r)}var c0r,Gde=X(()=>{"use strict";c0r=new Set(["statement-of-account-export"])});import{createHash as l0r}from"node:crypto";import{writeFile as u0r,mkdir as d0r}from"node:fs/promises";import{dirname as f0r,isAbsolute as p0r,join as h0r}from"node:path";async function Xit(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function Jde(t,e,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),t.post("/api/v1/reports/sql-query/export",{query:e},{headers:n})}async function Vde(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function m0r(t){return l0r("sha256").update(t).digest("hex").slice(0,16)}async function Kit(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=m0r(e),o=await Jde(t,e,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(;Date.now()<a&&!(c.status==="COMPLETED"||c.status==="FAILED"||c.status==="EXPIRED"||(await new Promise(p=>setTimeout(p,2e3)),Date.now()>=a));)c=(await Vde(t,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!p0r(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??h0r(f,"Downloads",`pseudo-sql-${s}.csv`);return await d0r(f0r(p),{recursive:!0}),await u0r(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}async function eot(t){let e=await t.get("/api/v1/reports/sql-query/schema"),r=e.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return e}var tot=X(()=>{"use strict"});async function kz(t){return t.get("/api/v1/capsule-recipes")}async function Nz(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function Oz(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function Fz(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function Qz(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function ha(t){if(!t||typeof t!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(typeof e.recipeName!="string"||e.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(e.recipeVersion!==void 0&&(typeof e.recipeVersion!="number"||!Number.isInteger(e.recipeVersion)||e.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(e.inputs===null||e.inputs===void 0||typeof e.inputs!="object"||Array.isArray(e.inputs))throw new Error("capsuleRecipe.inputs is required and must be a non-null object (recipe-specific shape; see descriptor.versions[].inputSchema).");let r=["baseTransactionResourceId","baseTransactionType","organizationResourceId"],n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length>0&&n.length<r.length)throw new Error(`capsuleRecipe base-transaction triplet is all-or-nothing \u2014 supply all of [baseTransactionResourceId, baseTransactionType, organizationResourceId] or none. Currently supplied: [${n.join(", ")}].`);if(e.templateOverrides!==void 0&&e.templateOverrides!==null){if(!Array.isArray(e.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;e.templateOverrides.forEach((o,s)=>{if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`capsuleRecipe.templateOverrides[${s}] must be an object {slotKey, template?}.`);let a=o;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey is required (non-empty string). Valid keys: get_capsule_recipe \u2192 versions[].templateSlots[].slotKey.`);if(a.slotKey.length>128)throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new Error(`capsuleRecipe.templateOverrides has a duplicate slotKey "${a.slotKey}" \u2014 one override per slot.`);if(i.add(a.slotKey),a.template!==void 0&&a.template!==null){if(typeof a.template!="string")throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var Wde=X(()=>{"use strict"});async function li(t,e,r){let n=await t.get(`/api/v1/${e}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function Mz(t,e){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=e,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),t.postMultipart(`/api/v1/${r}/${n}/attachments`,o)}async function Pz(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var Lz,hm=X(()=>{"use strict";Lz=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function ui(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Uz=X(()=>{"use strict"});async function $z(t,e){return t.post("/api/v1/claims/conversion/preview",e)}async function qz(t,e){if(e.idempotencyKey&&/^CONV[:-]/.test(e.idempotencyKey))throw new Error('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return t.post("/api/v1/claims/conversion/commit",e)}var bB,Zde=X(()=>{"use strict";bB=["POST","POST_AND_RECORD"]});async function jz(t,e){if(!(e.amount>0))throw new Error("amount must be greater than 0.");return t.post("/api/v1/claims/payouts/record",e)}async function Yz(t,e){return t.search("/api/v1/employees/payouts/search",e)}var rot,Xde=X(()=>{"use strict";rot=["REIMBURSEMENT","ADVANCE"]});function not(t){return{source:t.source,sourceType:t.sourceType,...t.cloudProvider?{cloudProvider:t.cloudProvider}:{},summary:t.summary,files:t.folders.flatMap(e=>e.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}var iot=X(()=>{"use strict"});import{randomUUID as A0r}from"node:crypto";import{rmSync as g0r}from"node:fs";function efe(t){for(let e of t.tempDirs??[])try{g0r(e,{recursive:!0,force:!0})}catch{}}function sot(t){for(let[e,r]of By)t-r.createdAt>oot&&(efe(r.plan),By.delete(e))}function E0r(){Kde||(Kde=setInterval(()=>sot(Date.now()),y0r),Kde.unref?.())}function aot(t,e){let r=Date.now();sot(r),E0r();let n=`dc_${A0r()}`;return By.set(n,{plan:t,createdAt:r,ownerKey:e}),n}function cot(t,e){let r=By.get(t);return!r||r.ownerKey!==e?null:Date.now()-r.createdAt>oot?(efe(r.plan),By.delete(t),null):r.plan}function lot(t,e){let r=By.get(t);!r||r.ownerKey!==e||(efe(r.plan),By.delete(t))}var oot,y0r,By,Kde,uot=X(()=>{"use strict";oot=1800*1e3,y0r=300*1e3,By=new Map});function b0r(t){if(!t||typeof t!="object")return;let e=t;return e.validFiles?.[0]?.workflowResourceId??e.workflowResourceId}function C0r(t,e){let r=new Set(e);return{...t,folders:t.folders.map(n=>({...n,files:n.files.filter(i=>$1(i.documentType)&&r.has(i.documentType))}))}}async function dot(t){let{plan:e,client:r,bankAccountId:n,documentTypes:i}=t,o=i&&i.length>0?C0r(e,i):e;if(!n&&I0r(o))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");let s=await XL({plan:o,client:r,bankAccountId:n}),a=s.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?b0r(u.response):void 0,error:u.error})),c=a.map(u=>u.workflowId).filter(u=>!!u);return{total:s.total,uploaded:s.success,skipped:a.filter(u=>u.status==="skipped").length,failed:s.failed,workflowIds:c,files:a}}function I0r(t){return t.folders.some(e=>e.files.some(r=>r.documentType==="BANK_STATEMENT"))}var fot=X(()=>{"use strict";c7();np()});async function ed(t,e,r){if(!e)return t;let n=v0r(t);if(!n)return t;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return t&&typeof t=="object"?{...t,_hydration:s}:{result:t,_hydration:s}}}function v0r(t){if(!t||typeof t!="object")return;let e=t,r=e.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=e.resourceId;if(typeof n=="string"&&n.length>0)return n}function Sf(t,e){return!e||!t||typeof t!="object"?t:{_fx:e,...t}}var pot=X(()=>{"use strict"});async function Hz(t,e){return t.list("/api/v1/bank-rules",e)}async function CB(t,e){let r=await t.get(`/api/v1/bank-rules/${e}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${e}`)}async function zz(t,e){return t.search("/api/v1/bank-rules/search",e)}async function Gz(t,e){return t.post("/api/v1/bank-rules",e)}async function Jz(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function Vz(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var tfe=X(()=>{"use strict"});async function Wz(t,e){return t.list("/api/v1/fixed-assets",e)}async function IB(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function Zz(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function Xz(t,e){return t.post("/api/v1/fixed-assets",e)}async function Kz(t,e,r){let i=(await IB(t,e)).data,o={};for(let s of w0r){let a=i[s];if(a==null)continue;let c=_0r.has(s)?hc(a):a;c!==void 0&&(o[s]=c)}for(let[s,a]of Object.entries(r))a!==void 0&&(o[s]=a);return o.resourceId=e,t.put(`/api/v1/fixed-assets/${e}`,o)}async function e8(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function t8(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function vB(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function r8(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function n8(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function i8(t,e){return po(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var w0r,_0r,o8=X(()=>{"use strict";mn();fA();w0r=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","fixedAssetsSetting","capsuleResourceId"],_0r=new Set(["purchaseDate","depreciationStartDate"])});async function s8(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function wB(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function a8(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function c8(t,e,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.data!==void 0&&(n.invoice??=n.data,delete n.data),n.endDate){let i=!n.startDate,o=!n.repeat;if(i||o){let s=await wB(t,e);if(i){let a=hc(s.data.startDate);if(!a)throw new Error("Subscription has no readable startDate \u2014 cannot auto-fill for update");n.startDate=a}if(o){if(!s.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=s.data.interval}}}return t.put(`/api/v1/scheduled/subscriptions/${e}`,n)}async function l8(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function u8(t,e,r){return t.put(`/api/v1/scheduled/cancel-subscriptions/${e}`,{resourceId:e,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function d8(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var rfe=X(()=>{"use strict";fA()});async function f8(t,e){return t.list("/api/v1/contact-groups",e)}async function p8(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function h8(t,e){return t.search("/api/v1/contact-groups/search",e)}async function m8(t,e){return t.post("/api/v1/contact-groups",e)}async function A8(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,_E(r,c9))}async function g8(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var nfe=X(()=>{"use strict";mn()});async function y8(t,e){return t.list("/api/v1/inventory-items",e)}async function E8(t,e){return t.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...e})}async function b8(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var ife=X(()=>{"use strict"});async function C8(t,e){return t.list("/api/v1/custom-fields",e)}async function _B(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function I8(t,e){return t.search("/api/v1/custom-fields/search",e)}async function v8(t,e){return t.post("/api/v1/custom-fields",e)}function S0r(t){return t!==void 0&&D0r.every(e=>t[e]!==void 0)}function R0r(t){let e=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:e(t.applyToSales),bills:e(t.applyToPurchase),customerCredits:e(t.applyToSaleCreditNote??t.applyToCreditNote),supplierCredits:e(t.applyToPurchaseCreditNote??t.applyToCreditNote),payments:e(t.applyToPayment)}}function x0r(t){return[t.applyToSales,t.applyToPurchase,t.applyToSaleCreditNote,t.applyToPurchaseCreditNote,t.applyToPayment,t.applyToCreditNote].some(e=>e==="PRINT")}async function w8(t,e,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!S0r(n.appliesTo)){let i=await _B(t,e);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??x0r(i.data),n.appliesTo={...R0r(i.data),...r.appliesTo}}return t.put(`/api/v1/custom-fields/${e}`,n)}async function _8(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var D0r,ofe=X(()=>{"use strict";D0r=["invoices","bills","customerCredits","supplierCredits","payments"]});function hot(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function DB(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return hot(n)}async function SB(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return hot(n)}var T0r,B0r,k0r,Uv,sfe=X(()=>{"use strict";T0r=["invoices","bills","customer-credit-notes","supplier-credit-notes"],B0r=["journals","cash-entries"],k0r=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],Uv=[...T0r,...B0r,...k0r]});async function D8(t,e){return t.list("/api/v1/nano-classifiers",e)}async function S8(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function R8(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function RB(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function xB(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,{...r,resourceId:e})}async function x8(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var afe=X(()=>{"use strict"});async function T8(t,e){return t.post("/api/v1/export-records",e)}async function B8(t,e){return t.post("/api/v1/export-records/preview",e)}async function k8(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var cfe=X(()=>{"use strict"});async function TB(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var lfe=X(()=>{"use strict"});function N8(t,e){if(!e.has(t))throw new Error(`unknown entity "${t}" \u2014 expected one of ${[...e].join(", ")}`)}function Aot(t,e,r,n=!1){if(!Array.isArray(t))throw new Error(`${r}: resourceIds must be an array, not a ${typeof t}`);if(t.length===0)throw new Error(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(t).size!==t.length)throw new Error(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(t.length>e)throw new Error(`${r}: ${t.length} ids exceeds the ${e}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${e} or fewer.`)}async function got(t,e,r){return N8(e,ufe),ts(r,"resourceId","Pass the document resourceId."),t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/approve`)}async function yot(t,e,r){return N8(e,ufe),Aot(r,N0r,"bulk approve",!0),r.forEach(n=>ts(n,"resourceIds[]","Every id must be a document resourceId.")),t.post(`/api/v1/${encodeURIComponent(e)}/bulk-approve`,{resourceIds:r})}async function Eot(t,e,r,n){N8(e,mot),ts(r,"resourceId","Pass the document resourceId."),Cot(n);let i=await t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:Q0r(i)}}}async function bot(t,e,r,n){return N8(e,mot),Cot(n),Aot(r,O0r,"bulk request changes"),r.forEach(i=>ts(i,"resourceIds[]","Every id must be a document resourceId.")),t.post(F0r(e),{resourceIds:r,message:n})}function F0r(t){return t==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${encodeURIComponent(t)}/bulk-request-changes`}function Cot(t){if(!t||t.trim().length===0)throw new Error("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function Q0r(t){let e=t?.data??t;if(!e||typeof e!="object")return[];let r=e.records;if(Array.isArray(r))return r;let n=e.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var ufe,mot,N0r,O0r,Iot=X(()=>{"use strict";An();ufe=new Set(["invoices","bills","customer-credit-notes","supplier-credit-notes"]),mot=new Set([...ufe,"purchase-orders","purchase-requests","sale-orders","sale-quotes","claims"]);N0r=100,O0r=500});function L0r(t,e,r){let n=Math.random().toString(36).slice(2,10);return`restore:${t}:${vot(e)}:${vot(r)}:${n}`}function vot(t){return t.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function dfe(t){if(!wot.has(t))throw new Error(`unknown entity "${t}" \u2014 expected one of ${[...wot].join(", ")}`)}async function _ot(t,e,r){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}`)}async function Dot(t,e,r,n){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function Sot(t,e,r,n,i){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.post(`/api/v1/rollback/${encodeURIComponent(e)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??L0r(e,r,n)}})}async function Rot(t,e,r){return t.get(`/api/v1/organization/currencies/${encodeURIComponent(e)}/effective-rate`,r?{date:r}:void 0)}var wot,xot=X(()=>{"use strict";An();wot=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function $v(t){Nt(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!M0r.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function O8(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:U0r(r.data)}}function P0r(t){return{btResourceId:t.btResourceId,btType:t.btType,eligible:t.eligible,errors:t.errors,displayData:t.displayData,contactSignals:t.contactInsight??null,breakdown:t.breakdown??null}}function U0r(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(P0r),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function F8(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function Q8(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var M0r,ffe=X(()=>{"use strict";mn();M0r=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function Bot(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function pfe(t,e){if(!t||typeof t!="object")throw new Error(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${e}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${e}.lineItems per call.`);dl([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&dl([i],["valueDate"])}function j0r(t,e){let r=typeof e=="number"&&!Number.isNaN(e)?e:void 0,n=typeof t=="number"&&!Number.isNaN(t)?t:void 0;if(r!==void 0)return r>=$0r?"high":r>=Tot?"medium":"low";if(n!==void 0){if(n>=q0r)return"high";if(n>=Tot)return"medium"}return"low"}function kot(t,e={}){let r=t??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,alternativeCount:0});continue}let d=u.slice().sort((D,B)=>{let L=D.confidenceScore??D.matchScore??-1;return(B.confidenceScore??B.matchScore??-1)-L}),f=d[0],p=typeof f.recommendationType=="string"?f.recommendationType:void 0,h=typeof f.matchScore=="number"?f.matchScore:void 0,m=typeof f.confidenceScore=="number"?f.confidenceScore:void 0,A=typeof f.isCrossCurrency=="boolean"?f.isCrossCurrency:void 0,g=typeof f.cftBtResourceId=="string"?f.cftBtResourceId:void 0,y=Array.isArray(f.cftBtResourceIds)?f.cftBtResourceIds:[],C=f.isBatch===!0||y.length>1,E=typeof f.cftAmount=="number"?f.cftAmount:void 0,I,v;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(I=BB.magicMatch,v={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(I=BB.withPayments,v={bankStatementEntryResourceId:c,businessTransactionPayments:[{cashflowTransactionResourceId:g,...E!==void 0?{transactionAmount:E}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let D=typeof f.learnedPredictionResourceId=="string"?f.learnedPredictionResourceId:void 0,B=typeof f.predictedPayload=="string"?f.predictedPayload:void 0,L=typeof f.predictedPayloadSchemaVersion=="string"?f.predictedPayloadSchemaVersion:void 0;D&&B&&L&&(I=BB.learnedPrediction,v={bankStatementEntryResourceId:c,learnedPredictionResourceId:D,predictedPayload:B,predictedPayloadSchemaVersion:L});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let D=f.actionShortcut??{},B=typeof D.resourceId=="string"?D.resourceId:void 0;B&&(I=BB.applyBankRule,v={actionShortcutResourceId:B,businessTransactionResourceIds:[c]});break}default:break}let x=I?j0r(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),N=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,z=I!==BB.withPayments||S,q=x==="high"&&!!I&&!!v&&z&&N;o.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:m,isCrossCurrency:A,recommendedTool:I,execute:v,confidenceTier:x,autoCommitEligible:q,alternativeCount:d.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return o}function H0r(t,e,r){return{bankStatementEntryResourceId:t.bankStatementEntryResourceId,confidenceTier:t.confidenceTier,recommendationType:t.recommendationType,recommendedTool:t.recommendedTool,execute:t.execute,bankLine:e,match:r}}async function z0r(t,e,r){let n=e.matchedTransactionResourceId,i=e.matchedTransactionCount;if(!n)return e.matchAmount!==void 0?{type:"transaction",amount:e.matchAmount,count:i}:null;let o=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let s of o)try{let{data:a}=s==="bill"?await xs(t,n):await Qs(t,n);return{type:s,reference:a.reference,amount:e.matchAmount??a.totalAmount,documentTotalAmount:a.totalAmount,count:i,resourceId:n}}catch{}return{type:"transaction",amount:e.matchAmount,count:i,resourceId:n}}async function Not(t,e,r){let n=r.filter(o=>o.recommendedTool&&!o.autoCommitEligible).slice(0,Y0r);if(n.length===0)return[];let i=new Map;if(e)try{let o=await zb(t,e,{filter:{status:{eq:"UNRECONCILED"}},limit:500});for(let s of o.data??[])i.set(s.resourceId,s)}catch{}return Promise.all(n.map(async o=>{let s=i.get(o.bankStatementEntryResourceId),a=s?{valueDate:s.valueDate,netAmount:s.netAmount,currencyCode:s.currencyCode,currencySymbol:s.currencySymbol,description:s.description,counterparty:s.extContactName}:null;return H0r(o,a,await z0r(t,o,a?.netAmount))}))}async function L8(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function M8(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function P8(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function U8(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function $8(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function q8(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function j8(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function Y8(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function H8(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function z8(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function G8(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}async function J8(t,e){return t.post("/api/v1/reconciliations/reset",e)}var BB,$0r,q0r,Tot,Y0r,hfe=X(()=>{"use strict";vp();_d();mn();ng();BB={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},$0r=.9,q0r=.95,Tot=.7;Y0r=25});function Ys(t,e,r="lineItems"){let n=[];for(let i of e)if(i.perLineItem){let o=t[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(t)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function Co(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),o={valueDate:mfe(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=mfe(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=mfe(t,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=t[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(v=>v.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,C=a.debitAmount,E=a.creditAmount,I=a.type??(typeof C=="number"&&C>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||I||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function mfe(t,e,r,n,i){let o=i.find(s=>s.field===e);if(!o){let s=t[e];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(t)){let s=t[e];return e==="contactResourceId"?{status:"ok",value:t.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function $o(t,e,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Ys(t,e,n),a=Co(t,e,n);return{resourceId:t.resourceId,reference:t.reference||null,totalAmount:t.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var ma,Vc,oo,Jl,Oot=X(()=>{"use strict";ma=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:t=>!!t.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:t=>t.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:t=>!!t.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:t=>t.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0}],Vc=[...ma],oo=ma.filter(t=>t.field!=="dueDate"),Jl=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:t=>t.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:t=>t.amount!=null&&t.amount>0||t.debitAmount!=null&&t.debitAmount>0||t.creditAmount!=null&&t.creditAmount>0,perLineItem:!0}]});function Wc(t){let e={};t.name!=null&&(e.name=t.name),t.quantity!=null&&(e.quantity=t.quantity),t.unitPrice!=null&&(e.unitPrice=t.unitPrice),t.unit&&(e.unit=t.unit);let r=t.accountResourceId||t.organizationAccountResourceId;r&&(e.accountResourceId=r);let n=t.taxProfileResourceId||(t.taxProfile&&typeof t.taxProfile=="object"?t.taxProfile.resourceId:null);return n&&(e.taxProfileResourceId=n),t.itemResourceId&&(e.itemResourceId=t.itemResourceId),t.discount!=null&&(e.discount=typeof t.discount=="object"?t.discount.rateValue??0:t.discount),e}function qv(t){let e={},r=t.accountResourceId||t.organizationAccountResourceId;return r&&(e.accountResourceId=r),t.amount!=null?e.amount=t.amount:t.debitAmount!=null&&t.debitAmount>0?e.amount=t.debitAmount:t.creditAmount!=null&&t.creditAmount>0&&(e.amount=t.creditAmount),t.type?e.type=t.type:t.debitAmount!=null&&t.debitAmount>0?e.type="DEBIT":t.creditAmount!=null&&t.creditAmount>0&&(e.type="CREDIT"),t.description&&(e.description=t.description),t.contactResourceId&&(e.contactResourceId=t.contactResourceId),e}function Pt(t){if(t)return t.split("T")[0]}var Afe=X(()=>{"use strict"});function td(t,e){let r={};if(e.contact&&(r.contactResourceId=e.contact),e.date&&(r.valueDate=e.date),e.due&&(r.dueDate=e.due),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.tag!==void 0&&(r.tag=e.tag),e.tax&&(r.isTaxVatApplicable=!0),e.tax&&e.taxInclusive?r.taxInclusion=!0:e.tax&&(r.taxInclusion=!1),e.lines)r.lineItems=e.lines;else if(e.account||e.taxProfile){let n=t.lineItems??[];r.lineItems=n.map(i=>{let o=Wc(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),e.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=e.taxProfile),o})}return r}function V8(t,e){let r={};if(e.date&&(r.valueDate=e.date),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.entries)r.journalEntries=e.entries;else if(e.account){let n=t.journalEntries??[];r.journalEntries=n.map(i=>{let o=qv(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),o})}return r}var Fot=X(()=>{"use strict";Afe()});var gfe=X(()=>{"use strict";Oot();Afe();Fot()});var kB,Vl,Qot=X(()=>{"use strict";kB="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",Vl="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function Efe(t){return G0r.get(t)}function Lot(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!yfe.has(o));return n.length===0?[]:Ti.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,e).map(o=>o.ns)}var Ti,yfe,G0r,rd=X(()=>{"use strict";Ti=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, and transition (accept a quote, confirm an order, void, delete). A Sale Order links to its quote via saleQuoteResourceId; the quote must be accepted first. Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (raise the invoice separately).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, and transition (accept a request, confirm an order, void, delete). A Purchase Order links to its request via purchaseRequestResourceId; the request must be accepted first. Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (raise the bill separately).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections.",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry \u2014 write side. Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments \u2014 the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Twelve endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created \u2014 it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace \u2014 switch there or call by name).",groups:["financial_reports"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail.",groups:["operational_reports","exports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema) + sync preview (\u2264100 rows) + async CSV export. Use when search_* / download_export canonical reports don't cover the question.",groups:["pseudo_sql"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Bulk upsert contacts from CSV / spreadsheet imports \u2014 async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs \u2014 named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"nano_classifiers",title:"Tracking Categories",description:"Nano classifiers (tracking categories/dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts \u2014 including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes.",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules \u2014 how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via document attachment / conversion (no bare create); the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only \u2014 no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once \u2014 asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); bind a login user to an employee (permanent); and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"capsules_and_recipes",title:"IFRS Recipes & Capsules",description:"Capsules (transaction groupings/capsule types). Financial recipes: amortization, depreciation, deferred revenue, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal. Two recipe execution paths: offline (plan_recipe + execute_recipe \u2014 client-side calculators, no API key) and server-side (list/get/preview/resume/rollback_capsule_recipe \u2014 produce real capsule entities via Jaz API). Plus capsuleRecipe payload on trigger mutations (create_bill, create_journal, create_cash_in, etc.) to create and trigger a recipe in one shot, with optional templateOverrides to customize the generated text (Customize Recipe). Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, rollback recipe, customize template overrides slots.",groups:["capsules","recipes","capsule_recipes"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). List/search saved report templates.",groups:["organization","org_users","modules","report_templates"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets \u2014 CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill or invoice via AI extraction (create_bt_from_attachment, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork \u2014 "create docs from this Dropbox folder link", a pile/batch of invoices and bills \u2014 into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications.",groups:["payments","cashflow","search"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve documents awaiting approval, or send them back for changes. Covers invoices, bills, both credit notes, sale/purchase orders, quotes, requests and claims. Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:"Quick Fix: bulk-update multiple transactions or line items in one call. Change dates, contacts, tags, accounts, tax profiles, custom fields across many invoices/bills/journals/credit-notes/cash-entries/schedulers at once. Also: batch update, mass edit.",groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions \u2014 both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK \u2014 one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user \u2014 including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see \u2014 for invoices, bills, reports, settings, or a specific transaction.",groups:["navigation"]}],yfe=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),G0r=new Map(Ti.flatMap(t=>t.groups.map(e=>[e,t.name])))});function jv(t){let e=new Set,r=[];for(let n of t)for(let i of Wl(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function NB(){return Ti.map(t=>{let e=jv(t.groups),r=e.filter(i=>i.isDestructive??!1).length,n=e.filter(i=>i.readOnly).length;return{namespace:t.name,operations:e.length,read:n,write:e.length-n-r,destructive:r,summary:(t.description.split(".")[0]??"").trim()}})}function J0r(t,e,r){let n=t==="namespace"?`Each entry in your tool list is a namespace router: ${e} entries, ${r} operations. Every tool's description lists its own operations.`:t==="meta"?`Your tool list holds discovery tools, not the catalogue: ${e} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${e} entries for ${r} operations.`;return{shape:t,this_connector_lists:e,operations:r,note:n}}function ky(t,e=!1){let r=Yv(void 0).length,n=Ti.length,i=t==="namespace"?n+(e?1:0):t==="flat"?r+(e?1:0):t==="meta"?3+(e?1:0):void 0;return{operations:r,namespaces:n,...t&&i!==void 0?{packaging:J0r(t,i,r)}:{},map:NB(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var W8=X(()=>{"use strict";rd();nd()});function Z8(t){let e={type:t.type};if(t.description&&(e.description=t.description),t.enum&&(e.enum=t.enum),t.type==="array"&&t.items&&(e.items=Z8(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=Z8(i);e.properties=r,t.required?.length&&(e.required=[...t.required])}return e}function Rf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=Z8(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function Ny(t){return{name:t.name,description:t.description,input_schema:Rf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var Hv=X(()=>{"use strict"});function OB(t){if(typeof t!="string")return t.isDestructive??!1;let e=t;return e.startsWith("delete_")||e.startsWith("pay_")||e.startsWith("finalize_")||e.includes("refund")||e==="remove_org_user"}function X8(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&OB(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function W0r(t){return t.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Z0r(t){let e=W0r(t);return!e||V0r.has(e)?!0:e.split(" ").filter(n=>n.length>=2&&!yfe.has(n)).length===0}function K8(t){if(Z0r(t)){let{next:i,...o}=ky();return{...o,hint:"Call search_tools with a namespace name or keyword to see operation names in that area, then describe_tools for full schemas before executing."}}let e=Lot(t,5);if(e.length===0){let{operations:i,namespaces:o}=ky();return{matches:[],hint:`No operation matches "${t}". Jaz has ${i} operations across ${o} namespaces \u2014 call search_tools with an empty query for the full map before concluding this is unsupported. Namespaces are named after accounting objects (contacts, employees, journals, claims), not task wording.`}}let n=t.toLowerCase().split(/\s+/).filter(Boolean);return{matches:e.map(i=>{let o=i.groups.flatMap(u=>Wl(u)),s=o.map(u=>`${u.name} ${(u.aliases??[]).join(" ")} ${u.searchHint??""} ${u.description}`.toLowerCase()),a=new Map(n.map(u=>{let d=s.filter(f=>f.includes(u)).length;return[u,Math.log((o.length+1)/(d+1))]})),c=o.map((u,d)=>{let f=s[d],p=n.reduce((h,m)=>f.includes(m)?h+(a.get(m)??0):h,0);return{tool:u,score:p}}).sort((u,d)=>d.score-u.score);return{namespace:i.name,description:i.description,tools:c.map(u=>({name:u.tool.name,description:u.tool.description.split(`
681
+ `)}catch{}},$de={info:Cz,warn:Cz,error:jit,debug:Cz,trace:Cz,fatal:jit,child:Yvr,level:"error"},Hvr=$de});import{createHash as zvr}from"node:crypto";function n0r(t){if(!t||!t.trim())return[null,"directive_required"];let e=t.normalize("NFKC").trim();return e.length>300?[null,"directive_too_long"]:zit.some(r=>e.includes(r))?[null,"directive_invalid"]:Hit.test(e)?[null,"directive_invalid"]:Xvr.test(e)?[null,"directive_contains_url"]:Kvr.test(e)?[null,"directive_contains_email"]:[e,null]}function i0r(t){if(t==null)return[null,null];let e=t.normalize("NFKC").trim();return e?e.length>e0r?[null,"match_condition_too_long"]:zit.some(r=>e.includes(r))?[null,"match_condition_invalid"]:Hit.test(e)?[null,"match_condition_invalid"]:[e,null]:[null,"match_condition_invalid"]}function o0r(t){return t==null?[null,null]:Number.isInteger(t)?t<t0r||t>r0r?[null,"invalid_importance"]:[t,null]:[null,"invalid_importance"]}function s0r(t,e,r,n,i,o,s,a){if(t)return zvr("sha256").update(`${t}:${e}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function a0r(t){Promise.resolve().then(()=>(jde(),qde)).then(({log:e})=>e.info(t,"memory_tool.call")).catch(()=>{})}async function Wit(t,e,r){let n=e.action,i=e.category,o=Wvr[e.scope??"this_org"]??"ORG_USER",s=typeof e.key=="string"?e.key.trim():"",a=null,c=d=>(a0r({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=t.memoryTurn,f=qit(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>Gvr||!Zvr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[C,E]=n0r(e.directive);if(E)return u(E);p=C;let[I,v]=o0r(e.importance);if(v)return u(v);h=I}let[m,A]=i0r(e.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=Jvr)return u("write_limit");d.writes+=1;let g=d.gtid||"",y;if(n==="set"){let C={gtid:g};d.quote&&(C.quote=d.quote.slice(0,Vvr));let E=s0r(g,n,o,i,s,p,e.confirms_key,e.replaces_key),I={scope:o,tier:a,category:i,key:s,...m?{matchCondition:m}:{},directive:p??"",...e.replaces_key?{replacesKey:e.replaces_key}:{},...e.confirms_key?{confirmsKey:e.confirms_key}:{},pending:e.pending===!0,source:r?.source??"TOOL",provenance:C,...E?{idempotencyKey:E}:{},...h!==null?{importance:h}:{}};y=await Yde(()=>Uit(t.client,I)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let C={category:i,key:s,scope:o};y=await Yde(()=>Mde(t.client,C))}else{let C={forgetAll:!0};y=await Yde(()=>Mde(t.client,C))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function Yde(t){try{let e=await t(),r=e&&typeof e=="object"&&e.data&&typeof e.data=="object"?e.data:e??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(e){return e instanceof lo?e.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${e.status}`}:{ok:!1,reason:"network_error"}}}var Hit,zit,Gvr,Jvr,Vvr,Git,Jit,Vit,Wvr,Zvr,Xvr,Kvr,e0r,t0r,r0r,Zit=X(()=>{"use strict";$it();Sa();Ude();Ude();Hit=/[\x00-\x1f\x7f]/,zit=["{{","}}","```","<",">"],Gvr=120,Jvr=3,Vvr=140,Git=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],Jit=["set","forget","forget_all"],Vit=["this_org","all_orgs"],Wvr={this_org:"ORG_USER",all_orgs:"USER"},Zvr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Xvr=/https?:\/\//i,Kvr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,e0r=255,t0r=0,r0r=100});async function Iz(t,e){return t.list("/api/v1/organization-users",e)}async function vz(t,e){return t.search("/api/v1/organization-users/search",e)}async function Pv(t,e){return t.post("/api/v1/organization-users/invite",e)}async function wz(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function _z(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var Hde=X(()=>{"use strict"});async function Dz(t,e){return t.search("/api/v1/cashflow-transactions/search",{limit:e?.limit??100,offset:e?.offset??0,sort:{sortBy:["valueDate"],order:"DESC"}})}async function EB(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function Sz(t,e){return t.get(`/api/v1/payments/${e}`)}async function Rz(t,e,r){return t.put(`/api/v1/payments/${e}`,{...r,currency:Ur(r.currency)})}async function xz(t,e){await t.delete(`/api/v1/payments/${e}`)}function Tz(t,e){return(r,n)=>r.post(`/api/v1/${t}/${e}`,{...n,transactions:n.transactions.map(i=>({...i,currency:Ur(i.currency)}))})}var _in,Din,Sin,Rin,zde=X(()=>{"use strict";An();_in=Tz("sales","bulk-payments"),Din=Tz("sales","batch-payments"),Sin=Tz("purchases","bulk-payments"),Rin=Tz("purchases","batch-payments")});async function Bz(t,e,r={}){let n=c0r.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`;return t.post(n,r)}var c0r,Gde=X(()=>{"use strict";c0r=new Set(["statement-of-account-export"])});import{createHash as l0r}from"node:crypto";import{writeFile as u0r,mkdir as d0r}from"node:fs/promises";import{dirname as f0r,isAbsolute as p0r,join as h0r}from"node:path";async function Xit(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function Jde(t,e,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),t.post("/api/v1/reports/sql-query/export",{query:e},{headers:n})}async function Vde(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function m0r(t){return l0r("sha256").update(t).digest("hex").slice(0,16)}async function Kit(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=m0r(e),o=await Jde(t,e,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(;Date.now()<a&&!(c.status==="COMPLETED"||c.status==="FAILED"||c.status==="EXPIRED"||(await new Promise(p=>setTimeout(p,2e3)),Date.now()>=a));)c=(await Vde(t,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!p0r(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??h0r(f,"Downloads",`pseudo-sql-${s}.csv`);return await d0r(f0r(p),{recursive:!0}),await u0r(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}async function eot(t){let e=await t.get("/api/v1/reports/sql-query/schema"),r=e.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return e}var tot=X(()=>{"use strict"});async function kz(t){return t.get("/api/v1/capsule-recipes")}async function Nz(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function Oz(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function Fz(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function Qz(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function ha(t){if(!t||typeof t!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(typeof e.recipeName!="string"||e.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(e.recipeVersion!==void 0&&(typeof e.recipeVersion!="number"||!Number.isInteger(e.recipeVersion)||e.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(e.inputs===null||e.inputs===void 0||typeof e.inputs!="object"||Array.isArray(e.inputs))throw new Error("capsuleRecipe.inputs is required and must be a non-null object (recipe-specific shape; see descriptor.versions[].inputSchema).");let r=["baseTransactionResourceId","baseTransactionType","organizationResourceId"],n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length>0&&n.length<r.length)throw new Error(`capsuleRecipe base-transaction triplet is all-or-nothing \u2014 supply all of [baseTransactionResourceId, baseTransactionType, organizationResourceId] or none. Currently supplied: [${n.join(", ")}].`);if(e.templateOverrides!==void 0&&e.templateOverrides!==null){if(!Array.isArray(e.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;e.templateOverrides.forEach((o,s)=>{if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`capsuleRecipe.templateOverrides[${s}] must be an object {slotKey, template?}.`);let a=o;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey is required (non-empty string). Valid keys: get_capsule_recipe \u2192 versions[].templateSlots[].slotKey.`);if(a.slotKey.length>128)throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new Error(`capsuleRecipe.templateOverrides has a duplicate slotKey "${a.slotKey}" \u2014 one override per slot.`);if(i.add(a.slotKey),a.template!==void 0&&a.template!==null){if(typeof a.template!="string")throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var Wde=X(()=>{"use strict"});async function li(t,e,r){let n=await t.get(`/api/v1/${e}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function Mz(t,e){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=e,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),t.postMultipart(`/api/v1/${r}/${n}/attachments`,o)}async function Pz(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var Lz,hm=X(()=>{"use strict";Lz=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function ui(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Uz=X(()=>{"use strict"});async function $z(t,e){return t.post("/api/v1/claims/conversion/preview",e)}async function qz(t,e){if(e.idempotencyKey&&/^CONV[:-]/.test(e.idempotencyKey))throw new Error('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return t.post("/api/v1/claims/conversion/commit",e)}var bB,Zde=X(()=>{"use strict";bB=["POST","POST_AND_RECORD"]});async function jz(t,e){if(!(e.amount>0))throw new Error("amount must be greater than 0.");return t.post("/api/v1/claims/payouts/record",e)}async function Yz(t,e){return t.search("/api/v1/employees/payouts/search",e)}var rot,Xde=X(()=>{"use strict";rot=["REIMBURSEMENT","ADVANCE"]});function not(t){return{source:t.source,sourceType:t.sourceType,...t.cloudProvider?{cloudProvider:t.cloudProvider}:{},summary:t.summary,files:t.folders.flatMap(e=>e.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}var iot=X(()=>{"use strict"});import{randomUUID as A0r}from"node:crypto";import{rmSync as g0r}from"node:fs";function efe(t){for(let e of t.tempDirs??[])try{g0r(e,{recursive:!0,force:!0})}catch{}}function sot(t){for(let[e,r]of By)t-r.createdAt>oot&&(efe(r.plan),By.delete(e))}function E0r(){Kde||(Kde=setInterval(()=>sot(Date.now()),y0r),Kde.unref?.())}function aot(t,e){let r=Date.now();sot(r),E0r();let n=`dc_${A0r()}`;return By.set(n,{plan:t,createdAt:r,ownerKey:e}),n}function cot(t,e){let r=By.get(t);return!r||r.ownerKey!==e?null:Date.now()-r.createdAt>oot?(efe(r.plan),By.delete(t),null):r.plan}function lot(t,e){let r=By.get(t);!r||r.ownerKey!==e||(efe(r.plan),By.delete(t))}var oot,y0r,By,Kde,uot=X(()=>{"use strict";oot=1800*1e3,y0r=300*1e3,By=new Map});function b0r(t){if(!t||typeof t!="object")return;let e=t;return e.validFiles?.[0]?.workflowResourceId??e.workflowResourceId}function C0r(t,e){let r=new Set(e);return{...t,folders:t.folders.map(n=>({...n,files:n.files.filter(i=>$1(i.documentType)&&r.has(i.documentType))}))}}async function dot(t){let{plan:e,client:r,bankAccountId:n,documentTypes:i}=t,o=i&&i.length>0?C0r(e,i):e;if(!n&&I0r(o))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");let s=await XL({plan:o,client:r,bankAccountId:n}),a=s.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?b0r(u.response):void 0,error:u.error})),c=a.map(u=>u.workflowId).filter(u=>!!u);return{total:s.total,uploaded:s.success,skipped:a.filter(u=>u.status==="skipped").length,failed:s.failed,workflowIds:c,files:a}}function I0r(t){return t.folders.some(e=>e.files.some(r=>r.documentType==="BANK_STATEMENT"))}var fot=X(()=>{"use strict";c7();np()});async function ed(t,e,r){if(!e)return t;let n=v0r(t);if(!n)return t;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return t&&typeof t=="object"?{...t,_hydration:s}:{result:t,_hydration:s}}}function v0r(t){if(!t||typeof t!="object")return;let e=t,r=e.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=e.resourceId;if(typeof n=="string"&&n.length>0)return n}function Sf(t,e){return!e||!t||typeof t!="object"?t:{_fx:e,...t}}var pot=X(()=>{"use strict"});async function Hz(t,e){return t.list("/api/v1/bank-rules",e)}async function CB(t,e){let r=await t.get(`/api/v1/bank-rules/${e}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${e}`)}async function zz(t,e){return t.search("/api/v1/bank-rules/search",e)}async function Gz(t,e){return t.post("/api/v1/bank-rules",e)}async function Jz(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function Vz(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var tfe=X(()=>{"use strict"});async function Wz(t,e){return t.list("/api/v1/fixed-assets",e)}async function IB(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function Zz(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function Xz(t,e){return t.post("/api/v1/fixed-assets",e)}async function Kz(t,e,r){let i=(await IB(t,e)).data,o={};for(let s of w0r){let a=i[s];if(a==null)continue;let c=_0r.has(s)?hc(a):a;c!==void 0&&(o[s]=c)}for(let[s,a]of Object.entries(r))a!==void 0&&(o[s]=a);return o.resourceId=e,t.put(`/api/v1/fixed-assets/${e}`,o)}async function e8(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function t8(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function vB(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function r8(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function n8(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function i8(t,e){return po(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var w0r,_0r,o8=X(()=>{"use strict";mn();fA();w0r=["name","reference","typeCode","typeName","category","purchaseAmount","purchaseDate","purchaseAssetAccountResourceId","depreciationStartDate","depreciationMethod","depreciationRateType","effectiveLife","depreciableValueCostLimitAmount","depreciableValueResidualAmount","depreciationExpenseAccountResourceId","accumulatedDepreciationAccountResourceId","bookValueAccumulatedDepreciationAmount","purchaseBusinessTransactionType","purchaseBusinessTransactionResourceId","internalNotes","tags","customFields","classifierConfig","fixedAssetsSetting","capsuleResourceId"],_0r=new Set(["purchaseDate","depreciationStartDate"])});async function s8(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function wB(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function a8(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function c8(t,e,r){let n={...r};if(n.interval!==void 0&&(n.repeat??=n.interval,delete n.interval),n.data!==void 0&&(n.invoice??=n.data,delete n.data),n.endDate){let i=!n.startDate,o=!n.repeat;if(i||o){let s=await wB(t,e);if(i){let a=hc(s.data.startDate);if(!a)throw new Error("Subscription has no readable startDate \u2014 cannot auto-fill for update");n.startDate=a}if(o){if(!s.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=s.data.interval}}}return t.put(`/api/v1/scheduled/subscriptions/${e}`,n)}async function l8(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function u8(t,e,r){return t.put(`/api/v1/scheduled/cancel-subscriptions/${e}`,{resourceId:e,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function d8(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var rfe=X(()=>{"use strict";fA()});async function f8(t,e){return t.list("/api/v1/contact-groups",e)}async function p8(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function h8(t,e){return t.search("/api/v1/contact-groups/search",e)}async function m8(t,e){return t.post("/api/v1/contact-groups",e)}async function A8(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,_E(r,c9))}async function g8(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var nfe=X(()=>{"use strict";mn()});async function y8(t,e){return t.list("/api/v1/inventory-items",e)}async function E8(t,e){return t.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...e})}async function b8(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var ife=X(()=>{"use strict"});async function C8(t,e){return t.list("/api/v1/custom-fields",e)}async function _B(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function I8(t,e){return t.search("/api/v1/custom-fields/search",e)}async function v8(t,e){return t.post("/api/v1/custom-fields",e)}function S0r(t){return t!==void 0&&D0r.every(e=>t[e]!==void 0)}function R0r(t){let e=r=>r!=null&&r!==""&&r!=="NULL";return{invoices:e(t.applyToSales),bills:e(t.applyToPurchase),customerCredits:e(t.applyToSaleCreditNote??t.applyToCreditNote),supplierCredits:e(t.applyToPurchaseCreditNote??t.applyToCreditNote),payments:e(t.applyToPayment)}}function x0r(t){return[t.applyToSales,t.applyToPurchase,t.applyToSaleCreditNote,t.applyToPurchaseCreditNote,t.applyToPayment,t.applyToCreditNote].some(e=>e==="PRINT")}async function w8(t,e,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!S0r(n.appliesTo)){let i=await _B(t,e);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??x0r(i.data),n.appliesTo={...R0r(i.data),...r.appliesTo}}return t.put(`/api/v1/custom-fields/${e}`,n)}async function _8(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var D0r,ofe=X(()=>{"use strict";D0r=["invoices","bills","customerCredits","supplierCredits","payments"]});function hot(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function DB(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return hot(n)}async function SB(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return hot(n)}var T0r,B0r,k0r,Uv,sfe=X(()=>{"use strict";T0r=["invoices","bills","customer-credit-notes","supplier-credit-notes"],B0r=["journals","cash-entries"],k0r=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],Uv=[...T0r,...B0r,...k0r]});async function D8(t,e){return t.list("/api/v1/nano-classifiers",e)}async function S8(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function R8(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function RB(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function xB(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,{...r,resourceId:e})}async function x8(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var afe=X(()=>{"use strict"});async function T8(t,e){return t.post("/api/v1/export-records",e)}async function B8(t,e){return t.post("/api/v1/export-records/preview",e)}async function k8(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var cfe=X(()=>{"use strict"});async function TB(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var lfe=X(()=>{"use strict"});function N8(t,e){if(!e.has(t))throw new Error(`unknown entity "${t}" \u2014 expected one of ${[...e].join(", ")}`)}function Aot(t,e,r,n=!1){if(!Array.isArray(t))throw new Error(`${r}: resourceIds must be an array, not a ${typeof t}`);if(t.length===0)throw new Error(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(t).size!==t.length)throw new Error(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(t.length>e)throw new Error(`${r}: ${t.length} ids exceeds the ${e}-id ceiling. The API rejects the whole batch with 422 and writes nothing \u2014 split into chunks of ${e} or fewer.`)}async function got(t,e,r){return N8(e,ufe),ts(r,"resourceId","Pass the document resourceId."),t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/approve`)}async function yot(t,e,r){return N8(e,ufe),Aot(r,N0r,"bulk approve",!0),r.forEach(n=>ts(n,"resourceIds[]","Every id must be a document resourceId.")),t.post(`/api/v1/${encodeURIComponent(e)}/bulk-approve`,{resourceIds:r})}async function Eot(t,e,r,n){N8(e,mot),ts(r,"resourceId","Pass the document resourceId."),Cot(n);let i=await t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:Q0r(i)}}}async function bot(t,e,r,n){return N8(e,mot),Cot(n),Aot(r,O0r,"bulk request changes"),r.forEach(i=>ts(i,"resourceIds[]","Every id must be a document resourceId.")),t.post(F0r(e),{resourceIds:r,message:n})}function F0r(t){return t==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${encodeURIComponent(t)}/bulk-request-changes`}function Cot(t){if(!t||t.trim().length===0)throw new Error("request changes: message is required and cannot be blank. It is posted as the first comment on the collaboration thread and is the only record of the reason.")}function Q0r(t){let e=t?.data??t;if(!e||typeof e!="object")return[];let r=e.records;if(Array.isArray(r))return r;let n=e.claims;return Array.isArray(n)?n.map(i=>({resourceId:i.resourceId,isSuccess:i.status==="SUCCESS"?!0:i.status==="FAILED"?!1:void 0,status:i.status,failureReason:i.errorMessage??null,errorCode:i.errorCode??null,collaborationThreadPath:i.collaborationThreadPath})):[]}var ufe,mot,N0r,O0r,Iot=X(()=>{"use strict";An();ufe=new Set(["invoices","bills","customer-credit-notes","supplier-credit-notes"]),mot=new Set([...ufe,"purchase-orders","purchase-requests","sale-orders","sale-quotes","claims"]);N0r=100,O0r=500});function L0r(t,e,r){let n=Math.random().toString(36).slice(2,10);return`restore:${t}:${vot(e)}:${vot(r)}:${n}`}function vot(t){return t.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function dfe(t){if(!wot.has(t))throw new Error(`unknown entity "${t}" \u2014 expected one of ${[...wot].join(", ")}`)}async function _ot(t,e,r){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}`)}async function Dot(t,e,r,n){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function Sot(t,e,r,n,i){return dfe(e),ts(r,"resourceId","Pass the document resourceId."),t.post(`/api/v1/rollback/${encodeURIComponent(e)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??L0r(e,r,n)}})}async function Rot(t,e,r){return t.get(`/api/v1/organization/currencies/${encodeURIComponent(e)}/effective-rate`,r?{date:r}:void 0)}var wot,xot=X(()=>{"use strict";An();wot=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function $v(t){Nt(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!M0r.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function O8(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:U0r(r.data)}}function P0r(t){return{btResourceId:t.btResourceId,btType:t.btType,eligible:t.eligible,errors:t.errors,displayData:t.displayData,contactSignals:t.contactInsight??null,breakdown:t.breakdown??null}}function U0r(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(P0r),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function F8(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function Q8(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var M0r,ffe=X(()=>{"use strict";mn();M0r=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function Bot(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function pfe(t,e){if(!t||typeof t!="object")throw new Error(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${e}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${e}.lineItems per call.`);dl([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&dl([i],["valueDate"])}function j0r(t,e){let r=typeof e=="number"&&!Number.isNaN(e)?e:void 0,n=typeof t=="number"&&!Number.isNaN(t)?t:void 0;if(r!==void 0)return r>=$0r?"high":r>=Tot?"medium":"low";if(n!==void 0){if(n>=q0r)return"high";if(n>=Tot)return"medium"}return"low"}function kot(t,e={}){let r=t??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,alternativeCount:0});continue}let d=u.slice().sort((D,B)=>{let L=D.confidenceScore??D.matchScore??-1;return(B.confidenceScore??B.matchScore??-1)-L}),f=d[0],p=typeof f.recommendationType=="string"?f.recommendationType:void 0,h=typeof f.matchScore=="number"?f.matchScore:void 0,m=typeof f.confidenceScore=="number"?f.confidenceScore:void 0,A=typeof f.isCrossCurrency=="boolean"?f.isCrossCurrency:void 0,g=typeof f.cftBtResourceId=="string"?f.cftBtResourceId:void 0,y=Array.isArray(f.cftBtResourceIds)?f.cftBtResourceIds:[],C=f.isBatch===!0||y.length>1,E=typeof f.cftAmount=="number"?f.cftAmount:void 0,I,v;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(I=BB.magicMatch,v={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(I=BB.withPayments,v={bankStatementEntryResourceId:c,businessTransactionPayments:[{cashflowTransactionResourceId:g,...E!==void 0?{transactionAmount:E}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let D=typeof f.learnedPredictionResourceId=="string"?f.learnedPredictionResourceId:void 0,B=typeof f.predictedPayload=="string"?f.predictedPayload:void 0,L=typeof f.predictedPayloadSchemaVersion=="string"?f.predictedPayloadSchemaVersion:void 0;D&&B&&L&&(I=BB.learnedPrediction,v={bankStatementEntryResourceId:c,learnedPredictionResourceId:D,predictedPayload:B,predictedPayloadSchemaVersion:L});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let D=f.actionShortcut??{},B=typeof D.resourceId=="string"?D.resourceId:void 0;B&&(I=BB.applyBankRule,v={actionShortcutResourceId:B,businessTransactionResourceIds:[c]});break}default:break}let x=I?j0r(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),N=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,z=I!==BB.withPayments||S,q=x==="high"&&!!I&&!!v&&z&&N;o.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:m,isCrossCurrency:A,recommendedTool:I,execute:v,confidenceTier:x,autoCommitEligible:q,alternativeCount:d.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return o}function H0r(t,e,r){return{bankStatementEntryResourceId:t.bankStatementEntryResourceId,confidenceTier:t.confidenceTier,recommendationType:t.recommendationType,recommendedTool:t.recommendedTool,execute:t.execute,bankLine:e,match:r}}async function z0r(t,e,r){let n=e.matchedTransactionResourceId,i=e.matchedTransactionCount;if(!n)return e.matchAmount!==void 0?{type:"transaction",amount:e.matchAmount,count:i}:null;let o=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let s of o)try{let{data:a}=s==="bill"?await xs(t,n):await Qs(t,n);return{type:s,reference:a.reference,amount:e.matchAmount??a.totalAmount,documentTotalAmount:a.totalAmount,count:i,resourceId:n}}catch{}return{type:"transaction",amount:e.matchAmount,count:i,resourceId:n}}async function Not(t,e,r){let n=r.filter(o=>o.recommendedTool&&!o.autoCommitEligible).slice(0,Y0r);if(n.length===0)return[];let i=new Map;if(e)try{let o=await zb(t,e,{filter:{status:{eq:"UNRECONCILED"}},limit:500});for(let s of o.data??[])i.set(s.resourceId,s)}catch{}return Promise.all(n.map(async o=>{let s=i.get(o.bankStatementEntryResourceId),a=s?{valueDate:s.valueDate,netAmount:s.netAmount,currencyCode:s.currencyCode,currencySymbol:s.currencySymbol,description:s.description,counterparty:s.extContactName}:null;return H0r(o,a,await z0r(t,o,a?.netAmount))}))}async function L8(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function M8(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function P8(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function U8(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function $8(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function q8(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function j8(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function Y8(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function H8(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function z8(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function G8(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}async function J8(t,e){return t.post("/api/v1/reconciliations/reset",e)}var BB,$0r,q0r,Tot,Y0r,hfe=X(()=>{"use strict";vp();_d();mn();ng();BB={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},$0r=.9,q0r=.95,Tot=.7;Y0r=25});function Ys(t,e,r="lineItems"){let n=[];for(let i of e)if(i.perLineItem){let o=t[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(t)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function Co(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),o={valueDate:mfe(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=mfe(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=mfe(t,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=t[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(v=>v.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,C=a.debitAmount,E=a.creditAmount,I=a.type??(typeof C=="number"&&C>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||I||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function mfe(t,e,r,n,i){let o=i.find(s=>s.field===e);if(!o){let s=t[e];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(t)){let s=t[e];return e==="contactResourceId"?{status:"ok",value:t.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function $o(t,e,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Ys(t,e,n),a=Co(t,e,n);return{resourceId:t.resourceId,reference:t.reference||null,totalAmount:t.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var ma,Vc,oo,Jl,Oot=X(()=>{"use strict";ma=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:t=>!!t.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:t=>t.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:t=>!!t.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:t=>t.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0}],Vc=[...ma],oo=ma.filter(t=>t.field!=="dueDate"),Jl=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:t=>t.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:t=>t.amount!=null&&t.amount>0||t.debitAmount!=null&&t.debitAmount>0||t.creditAmount!=null&&t.creditAmount>0,perLineItem:!0}]});function Wc(t){let e={};t.name!=null&&(e.name=t.name),t.quantity!=null&&(e.quantity=t.quantity),t.unitPrice!=null&&(e.unitPrice=t.unitPrice),t.unit&&(e.unit=t.unit);let r=t.accountResourceId||t.organizationAccountResourceId;r&&(e.accountResourceId=r);let n=t.taxProfileResourceId||(t.taxProfile&&typeof t.taxProfile=="object"?t.taxProfile.resourceId:null);return n&&(e.taxProfileResourceId=n),t.itemResourceId&&(e.itemResourceId=t.itemResourceId),t.discount!=null&&(e.discount=typeof t.discount=="object"?t.discount.rateValue??0:t.discount),e}function qv(t){let e={},r=t.accountResourceId||t.organizationAccountResourceId;return r&&(e.accountResourceId=r),t.amount!=null?e.amount=t.amount:t.debitAmount!=null&&t.debitAmount>0?e.amount=t.debitAmount:t.creditAmount!=null&&t.creditAmount>0&&(e.amount=t.creditAmount),t.type?e.type=t.type:t.debitAmount!=null&&t.debitAmount>0?e.type="DEBIT":t.creditAmount!=null&&t.creditAmount>0&&(e.type="CREDIT"),t.description&&(e.description=t.description),t.contactResourceId&&(e.contactResourceId=t.contactResourceId),e}function Pt(t){if(t)return t.split("T")[0]}var Afe=X(()=>{"use strict"});function td(t,e){let r={};if(e.contact&&(r.contactResourceId=e.contact),e.date&&(r.valueDate=e.date),e.due&&(r.dueDate=e.due),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.tag!==void 0&&(r.tag=e.tag),e.tax&&(r.isTaxVatApplicable=!0),e.tax&&e.taxInclusive?r.taxInclusion=!0:e.tax&&(r.taxInclusion=!1),e.lines)r.lineItems=e.lines;else if(e.account||e.taxProfile){let n=t.lineItems??[];r.lineItems=n.map(i=>{let o=Wc(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),e.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=e.taxProfile),o})}return r}function V8(t,e){let r={};if(e.date&&(r.valueDate=e.date),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.entries)r.journalEntries=e.entries;else if(e.account){let n=t.journalEntries??[];r.journalEntries=n.map(i=>{let o=qv(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),o})}return r}var Fot=X(()=>{"use strict";Afe()});var gfe=X(()=>{"use strict";Oot();Afe();Fot()});var kB,Vl,Qot=X(()=>{"use strict";kB="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",Vl="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function Efe(t){return G0r.get(t)}function Lot(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!yfe.has(o));return n.length===0?[]:Ti.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,e).map(o=>o.ns)}var Ti,yfe,G0r,rd=X(()=>{"use strict";Ti=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, and transition (accept a quote, confirm an order, void, delete). A Sale Order links to its quote via saleQuoteResourceId; the quote must be accepted first. Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (raise the invoice separately).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, and transition (accept a request, confirm an order, void, delete). A Purchase Order links to its request via purchaseRequestResourceId; the request must be accepted first. Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (raise the bill separately).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections, transfer trial balance (TTB).",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry \u2014 write side. Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments \u2014 the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Twelve endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created \u2014 it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace \u2014 switch there or call by name).",groups:["financial_reports"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail, ledger highlights.",groups:["operational_reports","exports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema) + sync preview (\u2264100 rows) + async CSV export. Use when search_* / download_export canonical reports don't cover the question.",groups:["pseudo_sql"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Bulk upsert contacts from CSV / spreadsheet imports \u2014 async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs \u2014 named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"nano_classifiers",title:"Tracking Categories",description:"Nano classifiers (tracking categories/dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts \u2014 including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes.",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules \u2014 how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via document attachment / conversion (no bare create); the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only \u2014 no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once \u2014 asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); bind a login user to an employee (permanent); and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"capsules_and_recipes",title:"IFRS Recipes & Capsules",description:"Capsules (transaction groupings/capsule types). Financial recipes: amortization, depreciation, deferred revenue, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal. Two recipe execution paths: offline (plan_recipe + execute_recipe \u2014 client-side calculators, no API key) and server-side (list/get/preview/resume/rollback_capsule_recipe \u2014 produce real capsule entities via Jaz API). Plus capsuleRecipe payload on trigger mutations (create_bill, create_journal, create_cash_in, etc.) to create and trigger a recipe in one shot, with optional templateOverrides to customize the generated text (Customize Recipe). Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, rollback recipe, customize template overrides slots.",groups:["capsules","recipes","capsule_recipes"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). List/search saved report templates. Agent context bundle.",groups:["organization","org_users","modules","report_templates"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets \u2014 CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill, invoice, or expense claim via AI extraction (create_bt_from_attachment, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork \u2014 "create docs from this Dropbox folder link", a pile/batch of invoices and bills \u2014 into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications, transaction summary.",groups:["payments","cashflow","search"]},{name:"versions",title:"Version History",description:"Document version history and restore. List the versions held for a journal, bill, invoice or credit note, read one snapshot, or restore the document to it. Restoring replaces current state.",groups:["versions"]},{name:"approvals",title:"Approvals",description:"Approve documents awaiting approval, or send them back for changes. Covers invoices, bills, both credit notes, sale/purchase orders, quotes, requests and claims. Approving posts the ledger and is one-shot. Find what is waiting with the approvalStatus filter on the relevant search tool.",groups:["approvals"]},{name:"quick_fix",title:"Bulk Edit (Quick Fix)",description:"Quick Fix: bulk-update multiple transactions or line items in one call. Change dates, contacts, tags, accounts, tax profiles, custom fields across many invoices/bills/journals/credit-notes/cash-entries/schedulers at once. Also: batch update, mass edit.",groups:["quick_fix"]},{name:"export_records",title:"Record Exports",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",title:"Background Jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",title:"Drafts",description:"Draft business transactions \u2014 both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK \u2014 one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"help_center",title:"Help Center Search",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",title:"Judgment Journal",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Tier: CRITICAL only for money-out, delete, finalize, or a recovery that re-drove a write; a withheld write is HIGH. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",title:"Dashboard Links",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user \u2014 including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see \u2014 for invoices, bills, reports, settings, or a specific transaction.",groups:["navigation"]}],yfe=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"]),G0r=new Map(Ti.flatMap(t=>t.groups.map(e=>[e,t.name])))});function jv(t){let e=new Set,r=[];for(let n of t)for(let i of Wl(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function NB(){return Ti.map(t=>{let e=jv(t.groups),r=e.filter(i=>i.isDestructive??!1).length,n=e.filter(i=>i.readOnly).length;return{namespace:t.name,operations:e.length,read:n,write:e.length-n-r,destructive:r,summary:(t.description.split(".")[0]??"").trim()}})}function J0r(t,e,r){let n=t==="namespace"?`Each entry in your tool list is a namespace router: ${e} entries, ${r} operations. Every tool's description lists its own operations.`:t==="meta"?`Your tool list holds discovery tools, not the catalogue: ${e} entries, ${r} operations reached through them.`:`Every operation is listed directly: ${e} entries for ${r} operations.`;return{shape:t,this_connector_lists:e,operations:r,note:n}}function ky(t,e=!1){let r=Yv(void 0).length,n=Ti.length,i=t==="namespace"?n+(e?1:0):t==="flat"?r+(e?1:0):t==="meta"?3+(e?1:0):void 0;return{operations:r,namespaces:n,...t&&i!==void 0?{packaging:J0r(t,i,r)}:{},map:NB(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var W8=X(()=>{"use strict";rd();nd()});function Z8(t){let e={type:t.type};if(t.description&&(e.description=t.description),t.enum&&(e.enum=t.enum),t.type==="array"&&t.items&&(e.items=Z8(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=Z8(i);e.properties=r,t.required?.length&&(e.required=[...t.required])}return e}function Rf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=Z8(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function Ny(t){return{name:t.name,description:t.description,input_schema:Rf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var Hv=X(()=>{"use strict"});function OB(t){if(typeof t!="string")return t.isDestructive??!1;let e=t;return e.startsWith("delete_")||e.startsWith("pay_")||e.startsWith("finalize_")||e.includes("refund")||e==="remove_org_user"}function X8(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&OB(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function W0r(t){return t.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Z0r(t){let e=W0r(t);return!e||V0r.has(e)?!0:e.split(" ").filter(n=>n.length>=2&&!yfe.has(n)).length===0}function K8(t){if(Z0r(t)){let{next:i,...o}=ky();return{...o,hint:"Call search_tools with a namespace name or keyword to see operation names in that area, then describe_tools for full schemas before executing."}}let e=Lot(t,5);if(e.length===0){let{operations:i,namespaces:o}=ky();return{matches:[],hint:`No operation matches "${t}". Jaz has ${i} operations across ${o} namespaces \u2014 call search_tools with an empty query for the full map before concluding this is unsupported. Namespaces are named after accounting objects (contacts, employees, journals, claims), not task wording.`}}let n=t.toLowerCase().split(/\s+/).filter(Boolean);return{matches:e.map(i=>{let o=i.groups.flatMap(u=>Wl(u)),s=o.map(u=>`${u.name} ${(u.aliases??[]).join(" ")} ${u.searchHint??""} ${u.description}`.toLowerCase()),a=new Map(n.map(u=>{let d=s.filter(f=>f.includes(u)).length;return[u,Math.log((o.length+1)/(d+1))]})),c=o.map((u,d)=>{let f=s[d],p=n.reduce((h,m)=>f.includes(m)?h+(a.get(m)??0):h,0);return{tool:u,score:p}}).sort((u,d)=>d.score-u.score);return{namespace:i.name,description:i.description,tools:c.map(u=>({name:u.tool.name,description:u.tool.description.split(`
682
682
  `)[0],...u.tool.searchHint?{searchHint:u.tool.searchHint}:{}}))}}),hint:"Call describe_tools with the tool names you need, then execute_tool to run them."}}function Mot(t){if(!Array.isArray(t)||!t.every(n=>typeof n=="string"))return{error:"Invalid `tools` parameter. Expected string[]."};if(t.length===0)return{error:"Provide at least one tool name. Use search_tools first to discover tool names."};let e=[],r=[];for(let n of t){let i=e3(n);if(!i){r.push(n);continue}e.push({...Ny(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&OB(i),group:i.group})}return{tools:e,...r.length>0?{notFound:r,hint:`Tools not found: ${r.join(", ")}. Use search_tools to find correct names.`}:{}}}var V0r,X0r,K0r,ewr,xf,mm,zv=X(()=>{"use strict";rd();W8();nd();Hv();V0r=new Set(["capabilities","capability","overview","everything","catalog","catalogue","menu","features","feature list","functions","tool list","all tools","all operations","list tools","list all tools","list operations","full list","full catalog","full catalogue","whats available","what is available","whats possible","show everything","show me everything","what else can you do","how many tools","how many operations"]);X0r={name:"search_tools",description:"Search for available Jaz accounting tools by keyword. Returns matching tool namespaces with tool names and descriptions. Call with empty query to list all namespaces. ALWAYS call this first to discover what tools are available.",inputSchema:Rf({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};K0r={name:"describe_tools",description:"Get full JSON Schema (parameters, types, required fields) for specific tools. Call this after search_tools to get the exact input format before calling execute_tool.",inputSchema:Rf({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},ewr={name:"execute_tool",description:"Execute a Jaz accounting tool. Call describe_tools first to get the required parameters. Pass the tool name and its arguments.",inputSchema:Rf({tool:{type:"string",description:'Tool name (e.g. "create_invoice")'},arguments:{type:"object",description:"Tool arguments (see describe_tools for schema)"},org_id:{type:"string",description:"Organization ID (UUID). Required in multi-org mode (PAT or multiple API keys). Call list_organizations to get available IDs."}},["tool"])},xf={name:"list_organizations",description:"List organizations available to the current authentication. Returns org names and resource IDs for use as org_id in execute_tool calls.",inputSchema:Rf({},[])},mm=[X0r,K0r,ewr]});function iwr(t){if(!(Zl in t))return{cleanedInput:t};let{[Zl]:e,...r}=t;return{jotText:typeof e=="string"&&e.trim()!==""?e.trim():void 0,cleanedInput:r}}function $ot(t,e){if(t.params[Zl])return{cleanedInput:e};let{jotText:r,cleanedInput:n}=iwr(e);return t.readOnly?{cleanedInput:n}:{jotText:r,cleanedInput:n}}function owr(t){let e=rwr.exec(t);return e?{kind:e[1],call:t.slice(e[0].length)||t}:{call:t}}function awr(t){let e=t.toLowerCase();for(let[r,n]of swr)if(n.test(e))return r}function cwr(t,e){let r=awr(t),n=[],i=new Set,o=(s,a)=>{if(!(n.length>=Pot||a>nwr||!s||typeof s!="object")){if(Array.isArray(s)){for(let c of s)o(c,a+1);return}for(let[c,u]of Object.entries(s)){if(n.length>=Pot)return;c==="resourceId"&&typeof u=="string"&&u&&!i.has(u)?(i.add(u),n.push(u)):o(u,a+1)}}};return o(e,0),n.map(s=>({id:s,...r?{relation:r}:{}}))}function t3(t,e,r,n){let{kind:i,call:o}=owr(r),s=cwr(e,n),a={...i?{kind:i}:{},tier:"MEDIUM",call:o,frame:`tool:${e}`,...s.length?{refs:s}:{},writePath:"PIGGYBACK"};Mv(t,[a]).catch(c=>{let u=c instanceof Error?c.message:String(c);Promise.resolve().then(()=>(jde(),qde)).then(({log:d})=>d.error({tool:e,error:u},"Piggyback jot write failed")).catch(()=>process.stderr.write(`[jots-piggyback] jot write failed (${e}): ${u}
683
683
  `))})}var Zl,Uot,twr,rwr,Pot,nwr,swr,r3=X(()=>{"use strict";Ez();yC();Zl="jot",Uot='Optional but valued: if this action involved a judgment call (which account, which match, an assumption, a risk accepted, a deviation), record it in one line, e.g. "MATCH: treated as distinct from BILL bil_x because references differ". Skip it for mechanical actions. '+vP,twr=["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],rwr=new RegExp(`^(${twr.join("|")})\\s*:\\s*`),Pot=20,nwr=6;swr=[["RECONCILE",/(?:^|_)reconcile(?:_|$)/],["PAY",/(?:^|_)(?:pay|payment|payout|cash_out|disburse|disbursement|refund)(?:_|$)/],["FINALIZE",/(?:^|_)(?:finalize|convert_drafts_to_active)(?:_|$)/],["DELETE",/(?:^|_)(?:delete|void|discard)(?:_|$)|^rollback_capsule_recipe$/],["TRIGGER",/(?:^|_)(?:recipe|trigger|execute)(?:_|$)/],["UPDATE",/(?:^|_)update(?:_|$)|^rollback_document_version$/],["CREATE",/(?:^|_)create(?:_|$)/]]});function qot(t){let e=new Set,r=[];for(let n of t)for(let i of Wl(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function lwr(t){return t.split("_").map(e=>e&&e[0].toUpperCase()+e.slice(1)).join(" ")}function Gv(t){let e=t.readOnly?"read":OB(t)?"destructive":"write",r=Object.keys(t.params).filter(s=>!t.required.includes(s)),n=t.required.length?` required: ${t.required.join(", ")};`:"",i=r.length?` optional: ${r.slice(0,10).join(", ")}${r.length>10?", \u2026":""}`:"",o=(t.searchHint||t.description.split(`
684
684
  `)[0]||"").trim().slice(0,140);return`- ${t.name} (${e}): ${o}${n}${i}`}function n3(t=!1){return Ti.map(e=>{let r=qot(e.groups),n=r.map(d=>d.name),i=r.length>0&&r.every(d=>d.readOnly),o=r.some(d=>!d.readOnly),s=r.some(d=>OB(d)),a=r.filter(d=>d.acceptsHostFile).map(d=>d.name),c=`${e.description}
@@ -687,7 +687,7 @@ Call with { operation, arguments${o?`, ${Zl}`:""}${a.length?", file":""}${t?", o
687
687
  `+r.map(Gv).join(`
688
688
  `)+(t?`
689
689
 
690
- Multiple organizations are accessible: pass org_id (from list_organizations) to target one. Confirm the organization with the user before any create/update/delete.`:""),u={operation:{type:"string",enum:n,description:`The ${e.name} operation to run.`},arguments:{type:"object",description:"Parameters for the chosen operation (see the operation list above). Validated by the Jaz API.",additionalProperties:!0}};return o&&(u[Zl]={type:"string",description:Uot}),a.length&&(u.file={type:"object",description:`A file from the conversation, when the client supports passing one. Accepted by: ${a.join(", ")}. The content is fetched server-side \u2014 leave source arguments out of \`arguments\`.`,properties:{download_url:{type:"string",description:"URL the file content can be fetched from (may be temporary)."},file_id:{type:"string",description:"Host-side file identifier."},mime_type:{type:"string"},file_name:{type:"string"}},required:["download_url"]}),t&&(u.org_id={type:"string",description:"The organization (resourceId from list_organizations) to run this operation against. Required when more than one organization is accessible."}),{name:e.name,description:c,inputSchema:{type:"object",properties:u,required:["operation"],additionalProperties:!1},...a.length?{_meta:{"openai/fileParams":["file"]}}:{},annotations:{title:`${e.title??lwr(e.name)} \xB7 ${r.length} operation${r.length===1?"":"s"}`,readOnlyHint:i,destructiveHint:!i&&s,idempotentHint:i,openWorldHint:!1}}})}function jot(t){return uwr.has(t)}function bfe(t,e){let r=Ti.find(o=>o.name===t);if(!r)return{error:`Unknown namespace: ${t}.`};let n=qot(r.groups),i=n.find(o=>o.name===e||o.aliases?.includes(e));return i?{tool:i}:{error:`Unknown operation "${e}" for the ${t} tool.`,operations:n.map(o=>o.name)}}var uwr,FB=X(()=>{"use strict";rd();nd();zv();r3();uwr=new Set(Ti.map(t=>t.name))});var Yot={};bs(Yot,{loadAgentSuiteContent:()=>Awr});import{readFileSync as dwr}from"node:fs";import{dirname as fwr,join as pwr}from"node:path";import{fileURLToPath as hwr}from"node:url";function Awr(){return Cfe||(Cfe=JSON.parse(dwr(pwr(mwr,"agent-suite-content.json"),"utf8"))),Cfe}var mwr,Cfe,Hot=X(()=>{"use strict";mwr=fwr(hwr(import.meta.url)),Cfe=null});var zot={};bs(zot,{buildCapabilityMap:()=>ywr});async function gwr(){try{let{loadAgentSuiteContent:t}=await Promise.resolve().then(()=>(Hot(),Yot)),e=t().counts;return{cli_command_groups:e.commands,api_rules:e.apiRules,skills:e.skills,ifrs_recipes:e.recipes,calculators:e.calculators,job_playbooks:e.jobs}}catch{return}}async function ywr(t={}){if(t.query&&t.query.trim())return K8(t.query);if(t.namespace){let r=Ti.find(i=>i.name===t.namespace);if(!r)return{error:`Unknown namespace "${t.namespace}".`,namespaces:Ti.map(i=>i.name),hint:"Call with no arguments for the full map, or pass `query` to rank operations by keyword."};let n=jv(r.groups);return{namespace:r.name,description:r.description,operations:n.length,operation_list:n.map(Gv),hint:"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}}let e=ky(t.surface,t.multiOrg);return{...e,map:t.full?NB().map(r=>({...r,operation_list:jv(Ti.find(n=>n.name===r.namespace).groups).map(Gv)})):e.map,beyond_mcp:await gwr()}}var Got=X(()=>{"use strict";rd();FB();zv();W8()});import{randomUUID as Ewr}from"node:crypto";function ost(t,e,r){return{type:"object",description:`The ${t.toLowerCase()} to create. Required.`,properties:{reference:{type:"string",description:`${t} reference`},contactResourceId:{type:"string",description:`${e} UUID`},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},dueDate:{type:"string",description:"YYYY-MM-DD. Defaults to value date."},taxInclusion:{type:"boolean"},isTaxVATApplicable:{type:"boolean"},lineItems:{type:"array",description:`${t} line items (max 500)`,items:{type:"object",properties:{name:{type:"string",description:"Line description"},quantity:{type:"number"},unit:{type:"string"},unitPrice:{type:"number"},organizationAccountResourceId:{type:"string",description:`${r} account UUID`},itemResourceId:{type:"string"},taxProfileResourceId:{type:"string"}},required:["name"]}},recordedPayment:{type:"object",description:"Optional. The matching payment record \u2014 auto-built from the bank entry if omitted.",properties:{reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},organizationAccountResourceId:{type:"string"},paymentAmount:{type:"number"},transactionAmount:{type:"number"},paymentMethod:Vv,adjustment:Wv}},capsuleResourceId:{type:"string"}},required:["reference","lineItems"]}}function Est(t){let e=t.limit,r=t.offset;return{limit:e,offset:r,sortBy:void 0,sortOrder:void 0}}function hr(t,e,r,n,i,o){let s={...Tfe};return o?.leanView&&(s.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). List lean, then drill in with get_*."}),{name:t,description:e,params:s,required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(a,c)=>{let{limit:u,offset:d}=Est(c),f=o?.leanView?c.view==="full"?"full":"lean":void 0;return eS((h,m)=>n(a.client,h,m,f),u,d,f==="lean"?50:20)}}}function Bi(t,e,r,n,i,o){return{name:t,description:e,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(s,a)=>n(s.client,a.resourceId)}}function bst(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e=t.data;return e&&typeof e=="object"&&!Array.isArray(e)?e:t}function Cst(t,e,r,n){return{[e]:!0,...bst(t),[r]:n}}function MB(t){return`Deletes a DRAFT ${t}; VOIDs an active one and KEEPS it. force: true hard-deletes either.`}function Rwr(t,e,r){let n=bst(t);return{outcome:(typeof n.status=="string"?Swr[n.status]:void 0)??(r?"DELETED":"DELETED_IF_DRAFT_VOIDED_IF_ACTIVE"),...n,resourceId:e}}function Wr(t,e,r,n,i,o){let s=o?.verb??"deleted";return{name:t,description:e,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"},...o?.voidable?Dwr:{}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(a,c)=>{let u=c.resourceId;ts(u,"resourceId",`Nothing was deleted. Source a real resourceId from a search_* or list_* result before calling ${t}.`);let d=c.force,f=await n(a.client,u,{force:d,internalNotes:c.internalNotes});return o?.voidable?Rwr(f,u,d):Cst(f,s,"resourceId",u)}}}function PB(t,e,r,n){return{name:t,description:`Download ${/^[aeiou]/i.test(e)?"an":"a"} ${e} as PDF. Returns { fileUrl } (may be pending/empty if the document is not yet rendered).`,params:{resourceId:{type:"string",description:`${e[0].toUpperCase()}${e.slice(1)} resourceId`}},required:["resourceId"],group:r,readOnly:!0,searchHint:`download ${e} as PDF document file`,isConcurrencySafe:!0,execute:async(i,o)=>n(i.client,o.resourceId)}}function xfe(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,...i?.destructive?{isDestructive:!0}:{},...i?.searchHint?{searchHint:i.searchHint}:{},execute:async(o,s)=>n(o.client,s.resourceId)}}function ust(t){if(typeof t!="string"||/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let e=/^(\d{4}-\d{2}-\d{2})T/.exec(t);return e?e[1]:t}function Fwr(t){return Array.isArray(t)?t.map(e=>{let r={};for(let[n,i]of Object.entries(e)){if(i==null)continue;let o=RX.get(n);if(o)r[o]=i;else if(n==="taxProfile"&&typeof i=="object"&&i!==null){let s=i.resourceId;s&&(r.taxProfileResourceId=s)}else if(n==="discount"&&typeof i=="object"&&i!==null){let s=i.rateValue;s&&Number(s)!==0&&(r.discount=i)}else Owr.has(n)&&(r[n]=i)}return r}):t}async function UB(t,e,r,n){let s=(await(e==="invoice"?Qs:e==="bill"?xs:e==="customer_credit_note"?Ol:Fl)(t,r)).data,a=Nwr[e],c={};for(let[p,h]of Object.entries(s))a.has(p)&&h!==null&&h!==void 0&&(c[p]=h);c.valueDate&&(c.valueDate=ust(c.valueDate)),c.dueDate&&(c.dueDate=ust(c.dueDate)),c.lineItems&&(c.lineItems=Fwr(c.lineItems));for(let[p,h]of Object.entries(n))h!==void 0&&(c[p]=h);let u=e==="invoice"?Vc:e==="bill"?ma:oo,{missingFields:d,ready:f}=Ys(c,u);if(!f)throw new Error(`Cannot finalize: missing ${d.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function dst(t,e,r,n){if((await t(e,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function a3(t,e,r){if(!(typeof t=="string"&&e.includes(t)))return{error:`Unknown documentType ${JSON.stringify(t)}.`,status:422,hint:`Use one of: ${e.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}function hst(t,e,r){let n=pst[t];if(!n)return{error:`Unknown documentType "${t}".`,status:422,hint:`Valid document types: ${Object.keys(pst).join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}};if(!n.includes(e)){let i=n.includes("ACCEPT")?"ACCEPT":"CONFIRM";return{error:`Action "${e}" is not valid for ${t}. Valid actions: ${n.join(", ")}.`,status:422,hint:`${t} advances its lifecycle with ${i}, not ${e}.`,repair:{tool:r,arguments:{documentType:t,action:i},reason:`${t} is advanced with ${i}.`}}}}async function mst(t,e,r,n,i,o,s){let a;try{a=(await e(t,r)).data?.status}catch{return}if(a==="DRAFT"||a==="VOID"){let c=a==="DRAFT"?`A DRAFT ${n} can't be linked or accepted \u2014 issue it by creating the ${n} with saveAsDraft:false (status ${s}), then link the order to that one.`:`A VOID ${n} can't be used \u2014 create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a ${a} ${n} (${r}).`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. ${c}`,repair:{tool:o,arguments:{documentType:i,saveAsDraft:!1},reason:c}}}}async function Ast(t,e,r,n,i,o){let s;try{s=(await e(t,r)).data?.status}catch{return}if(s==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:o,arguments:{},reason:`The source ${n} is VOID.`}}}async function gst(t,e,r,n,i){let o;try{o=(await e(t,r,n)).data?.status}catch{return}if(o&&o!=="DRAFT")return{error:`Cannot DELETE a ${o} ${r} \u2014 delete is only allowed on DRAFT records.`,status:422,hint:"Use action VOID to cancel a non-draft quote/request/order.",repair:{tool:i,arguments:{documentType:r,resourceId:n,action:"VOID"},reason:`${r} is ${o}; void it instead of deleting.`}}}var bwr,Za,Io,Xl,vo,di,id,i3,Oy,Jot,Cwr,Vot,Wot,Ife,vfe,Jv,QB,Iwr,vwr,wfe,Zot,Xot,_fe,Tfe,Am,Dfe,Kot,est,tst,rst,Qi,nst,LB,wwr,Sfe,o3,Aa,ist,yst,od,Vv,Wv,_wr,Dwr,Swr,Ist,xwr,sst,ast,cst,Twr,Bwr,Rfe,lst,kwr,Nwr,Owr,$B,qB,s3,fst,pst,Tf,c3=X(()=>{"use strict";gP();yC();xX();dMe();gMe();ZD();Sa();fr();An();fA();cA();TE();APe();bPe();Xf();ng();_d();YX();HX();og();zX();vp();xF();zF();Qw();GX();UPe();eU();aU();pU();ait();Mw();XF();jw();LH();zw();VP();zH();bde();Cde();az();Ide();Bde();Fde();Mit();vp();gB();Qde();Lde();Ez();Zit();Hde();zde();Gde();tot();Wde();hm();Uz();oD();Zde();Xde();Gw();i7();iot();uot();fot();NX();pot();tfe();o8();rfe();nfe();ife();ofe();sfe();afe();cfe();lfe();Xf();ng();Iot();og();xot();_d();eU();aU();og();o8();mn();ffe();hfe();fr();gfe();Qot();bwr=xP.join(" | "),Za={type:"string",description:"Resource ID of the record"},Io={type:"string",description:"Transaction date (YYYY-MM-DD)"},Xl={type:"string",description:"Due date (YYYY-MM-DD)"},vo={type:"string",description:"Reference number"},di={type:"string",description:"Notes or memo text"},id={type:"string",description:"Tag name for categorization"},i3={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},Oy={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},Jot={recipe:{type:"string",enum:[...xy],description:"Recipe type"},amount:{type:"number",description:"Amount (for amortization, accrued-expense, dividend, ecl, provision, fx-reval)"},principal:{type:"number",description:"Principal (for loan, fixed-deposit)"},startDate:{type:"string",description:"Start date YYYY-MM-DD (REQUIRED for blueprint generation \u2014 default to today if user does not specify)"},currency:{type:"string",description:"Currency code (e.g. SGD, USD)"},periods:{type:"number",description:"Number of periods (for amortization, accrued-expense, leave-accrual)"},frequency:{type:"string",enum:["monthly","quarterly","annual"],description:"Frequency (for depreciation, amortization, accrued-expense)"},annualRate:{type:"number",description:"Annual interest/discount rate %"},termMonths:{type:"number"},monthlyPayment:{type:"number",description:"Monthly lease payment (for lease)"},usefulLifeMonths:{type:"number",description:"Asset useful life in months (hire purchase)"},cost:{type:"number",description:"Asset cost"},salvageValue:{type:"number"},usefulLifeYears:{type:"number"},method:{type:"string",enum:["sl","ddb","150db"],description:"Depreciation method"},acquisitionDate:{type:"string",description:"Acquisition date YYYY-MM-DD"},disposalDate:{type:"string",description:"Disposal date YYYY-MM-DD"},proceeds:{type:"number",description:"Disposal proceeds"},bookRate:{type:"number",description:"Original booking rate. Declare which way it reads via rateDirection (REQUIRED for fx-reval)."},closingRate:{type:"number",description:"Period-end closing rate. Same direction as bookRate."},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"REQUIRED for fx-reval. FUNCTIONAL_TO_SOURCE = 1 base unit = N foreign, what list_currency_rates returns. SOURCE_TO_FUNCTIONAL = 1 foreign unit = N base, the everyday quote."},position:{type:"string",enum:["ASSET","LIABILITY"],description:"Balance-sheet side: ASSET (receivable/deposit, default) or LIABILITY (payable/provision). A rising base value is a gain on an asset and a loss on a liability."},baseCurrency:{type:"string",description:"Base (functional) currency"},buckets:{type:"array",items:{type:"object",properties:{name:{type:"string"},balance:{type:"number"},rate:{type:"number"}},required:["name","balance","rate"]},description:"ECL aging buckets"},existingProvision:{type:"number",description:"Existing ECL provision balance"},compounding:{type:"string",enum:["none","monthly","quarterly","annually"]},employees:{type:"number"},daysPerYear:{type:"number",description:"Leave days per employee per year"},dailyRate:{type:"number",description:"Average daily rate"},declarationDate:{type:"string",description:"Board resolution date YYYY-MM-DD"},paymentDate:{type:"string",description:"Settlement date YYYY-MM-DD"},withholdingRate:{type:"number",description:"Withholding tax rate %"}},Cwr={type:"boolean",description:"Retry-only: set true after the duplicate guard surfaced a candidate and the user confirmed this is a separate document. Never on a first attempt."},Vot={type:"string",enum:[...kX],description:"CUSTOM (default) = free text; ALL_* = a picklist of that population. Datatype is derived, not chosen."},Wot={type:"object",properties:{address:{type:"string",description:"Street address \u2014 sent as addressLine1"},city:{type:"string"},state:{type:"string"},postalCode:{type:"string"},country:{type:"string"}},required:["address","country"]},Ife={type:"string",description:"Contact resourceId (customer or supplier)"},vfe={type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID)"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Draft entity type"}},required:["btResourceId","btType"]}},Jv={type:"string",description:"Chart-of-accounts account the line posts to (revenue on a sale, expense on a purchase)"},QB={type:"string",description:"Account the payment posts to. For paymentMethod BANK_TRANSFER/CASH/CHEQUE this MUST be a bank or cash account. Any other method accepts any org account \u2014 that is how a deposit drawdown works (paymentMethod OTHER + the deposit account)."},Iwr={type:"number",description:"Payment amount (in bank currency)"},vwr={type:"string",description:"Period start date (YYYY-MM-DD)"},wfe={type:"string",description:"Period end date (YYYY-MM-DD)"},Zot={type:"string",enum:["full","aggregate"],description:`Output detail (default 'full'). 'aggregate' returns a compact aging-bucket summary (current, <1 month, 1/2/3 months, older + total outstanding + contact count). Prefer 'aggregate' for a general or unqualified report request (e.g. "show me my aged receivables", "my AR report") \u2014 it's the at-a-glance overview a chat user expects and it won't truncate on large orgs. Use 'full' only when the user explicitly asks for the per-contact (customer/supplier) breakdown for deeper analysis.`},Xot={type:"string",description:"Currency code (e.g. SGD, USD)"},_fe={type:"string",description:"Display name"},Tfe={limit:{type:"number",description:"Max results per page (\u22641000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},Am={type:"object",required:["sourceCurrency"],properties:{sourceCurrency:{type:"string",description:"Foreign currency code (ISO 4217)."},exchangeRate:{type:"number",description:'Base\u2192source: N where 1 org-base unit = N sourceCurrency. Invert ONLY if your quote reads "1 source = X base" (send 1/X), or declare rateDirection and skip the arithmetic. Omit for the org/platform rate.'},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"How exchangeRate reads. SOURCE_TO_FUNCTIONAL accepts a bank quote verbatim. Default FUNCTIONAL_TO_SOURCE."}}},Dfe={type:"string",enum:[...Hd],description:"Entity type to export"},Kot={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.'},est={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},tst={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."},rst={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."},Qi={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},nst={type:"array",description:"Full replacement line-item set \u2014 non-empty REPLACES all lines, [] clears, omit = no change. claimTypeResourceId + name + unitPrice + quantity are required at submit time.",items:{type:"object",properties:{resourceId:{type:"string",description:"Existing line resourceId (omit to add a new line)"},claimTypeResourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"Line name"},description:{type:"string",description:"Line description"},unitPrice:{type:"number",description:"Unit price"},quantity:{type:"number",description:"Quantity"},currency:{type:"string",description:"Line currency (ISO 4217; falls back to header)"},itemSubTotal:{type:"number",description:"Line subtotal (unitPrice \xD7 quantity)"}}}},LB={type:"array",items:{type:"string"},description:"Claim resourceIds (1-500)"},wwr={type:"array",items:{type:"object",required:["resourceId","type","selectedClasses","printable"],properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",required:["className"],properties:{className:{type:"string"},resourceId:Za}}},printable:{type:"boolean"}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},Sfe={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)"},o3={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Offset account resourceId"},amount:{type:"number",description:"Amount (positive; direction comes from the endpoint)"},description:{type:"string",description:"Line description"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId"}},required:["accountResourceId","amount"]},description:"Offset lines. No `type` \u2014 cash-in credits these and cash-out debits them, decided by the endpoint."},Aa={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:Jv,taxProfileResourceId:{type:"string"},classifierConfig:wwr},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},ist={type:"array",items:{type:"object",properties:{itemName:{type:"string",description:"Display name of the catalog item"},itemResourceId:{type:"string",description:"Underlying item resourceId (from search_items)"},price:{type:"number",description:"Default unit price (0-1e9)"},unit:{type:"string",description:"Unit of measure"},quantityDefault:{type:"number",description:"Default quantity when added to a document (0-100)"},discountDefault:{type:"number",description:"Default discount % when added to a document (0-100)"},uiIndex:{type:"number",description:"Display position in the catalog (integer, min 0)"},classifiers:{type:"array",items:{type:"object"},description:"Classifier assignments. Same shape as classifierConfig on invoice/bill line items."}},required:["itemName","itemResourceId","price"]},description:"Catalog item rows. itemName, itemResourceId and price are required on every row."},yst={type:"array",items:{type:"object",properties:{slotKey:{type:"string",description:"Slot from get_capsule_recipe templateSlots[]."},template:{type:"string",description:"Text with {{vars}} for that slot; empty string clears a nullable slot. Max 2000."}},required:["slotKey"]},description:"Optional. Customize recipe-generated text via published slots (see get_capsule_recipe)."},od={type:"object",description:"Optional IFRS recipe trigger. Mutex with capsuleResourceId. Silent-null on failure \u2014 preview_capsule_recipe first. Rule 143.",properties:{recipeName:{type:"string",enum:["LOAN_AMORTIZATION","ACCRUAL_REVERSAL","PREPAID_AMORTIZATION","DEFERRED_REVENUE","IFRS16_LEASE"],description:"Must match mutation's allowedBaseTransactionTypes (see list_capsule_recipes)."},recipeVersion:{type:"number",description:"Optional version pin."},inputs:{type:"object",description:"Schema at versions[0].inputSchema. Single-currency; *AccountResourceId x-accountClass-locked."},templateOverrides:yst},required:["recipeName","inputs"]},Vv={type:"string",enum:[...qMe],description:"Payment method (default BANK_TRANSFER)"},Wv={type:"object",description:"Cash-leg adjustment (overpayment/rounding). Bank leg only, never AR/AP. Not with DEBT_WRITE_OFF/CLEARING_SETTLEMENT/INTER_COMPANY/WITHHOLDING_TAX_CERTIFICATE. See rule 160.",properties:{adjustmentValue:{type:"number",description:"Signed, non-zero, max 2dp"},adjustmentAccountResourceId:{type:"string",description:"Non-controlled account, not bank/cash"},adjustmentDescription:{type:"string",description:"Optional"}},required:["adjustmentValue","adjustmentAccountResourceId"]},_wr={...Wv,description:"Adding or changing an adjustment applies here. REMOVING does not: 0 is rejected and null reads as omitted, so both leave the stored value unchanged. To remove one, delete the payment and record it again. A change is rejected if the payment is reconciled or lock-dated, and amount, account and description are all compared, so resend all three unchanged if you are not editing it. See rule 160."};Dwr={force:{type:"boolean",description:"Hard-delete instead of voiding."},internalNotes:{type:"string",description:"Note recorded with the void."}},Swr={VOID:"VOIDED",SUCCEEDED:"DELETED"};Ist=["invoices","bills","customer-credit-notes","supplier-credit-notes"],xwr=[...Ist,"purchase-orders","purchase-requests","sale-orders","sale-quotes","claims"],sst={type:"string",description:"Document family",enum:Ist},ast={type:"string",description:"Document family",enum:xwr},cst={type:"string",description:"Why it is sent back. Opens a thread; the only record of the reason."},Twr=[{name:"approve_documents",description:"Approve one document awaiting approval. Posts its ledger entries and makes it live. One-shot, and the refusal channel differs by entity: invoices/bills THROW 422; credit notes return 200 with isSuccess:false and a STALE approvalStatus of APPROVED. Check isSuccess and catch the throw \u2014 approvalStatus alone cannot tell refusal from success.",params:{entity:sst,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"approvals",readOnly:!1,searchHint:"approve pending invoice bill credit note post ledger",execute:async(t,e)=>got(t.client,e.entity,e.resourceId)},{name:"bulk_approve_documents",description:"Approve up to 100 documents awaiting approval. Async \u2014 returns a jobId; poll search_background_jobs. Each approval posts a ledger.",params:{entity:sst,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-100)"}},required:["entity","resourceIds"],group:"approvals",readOnly:!1,searchHint:"bulk approve many pending documents at once",execute:async(t,e)=>yot(t.client,e.entity,e.resourceIds)},{name:"request_document_changes",description:"Send one document back for changes instead of approving it. Also covers orders, quotes, requests and claims.",params:{entity:ast,resourceId:{type:"string",description:"Document resourceId"},message:cst},required:["entity","resourceId","message"],group:"approvals",readOnly:!1,searchHint:"request changes reject send back document for revision",execute:async(t,e)=>Eot(t.client,e.entity,e.resourceId,e.message)},{name:"bulk_request_document_changes",description:"Send up to 500 documents back for changes with one message. Async \u2014 returns a jobId; poll search_background_jobs.",params:{entity:ast,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-500)"},message:cst},required:["entity","resourceIds","message"],group:"approvals",readOnly:!1,searchHint:"bulk request changes send back many documents",execute:async(t,e)=>bot(t.client,e.entity,e.resourceIds,e.message)}],Bwr=["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"],Rfe={type:"string",description:"Document family",enum:Bwr},lst={type:"string",description:"Version id from get_document_version_history"},kwr=[{name:"get_document_version_history",description:"The stored versions of a document, newest first. Not paginated. Use before restoring to pick a version id.",params:{entity:Rfe,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"versions",readOnly:!0,searchHint:"list document version history revisions audit trail",isConcurrencySafe:!0,execute:async(t,e)=>_ot(t.client,e.entity,e.resourceId)},{name:"get_document_version",description:"Read one stored version of a document. An unknown resourceId/version pair returns 422.",params:{entity:Rfe,resourceId:{type:"string",description:"Document resourceId"},version:lst},required:["entity","resourceId","version"],group:"versions",readOnly:!0,searchHint:"get read one document version snapshot",isConcurrencySafe:!0,execute:async(t,e)=>Dot(t.client,e.entity,e.resourceId,e.version)},{name:"rollback_document_version",description:"Restore a document to a stored version. REPLACES current state \u2014 read the version first with get_document_version.",params:{entity:Rfe,resourceId:{type:"string",description:"Document resourceId"},version:lst},required:["entity","resourceId","version"],group:"versions",readOnly:!1,searchHint:"restore rollback document to previous version undo changes",isDestructive:!0,execute:async(t,e)=>Sot(t.client,e.entity,e.resourceId,e.version)},{name:"get_currency_effective_rate",description:"The organization effective rate for a currency on a date: its own custom rate when set, else the platform daily rate. Defaults to today.",params:{currencyCode:{type:"string",description:"ISO 4217 code, e.g. USD (not a resourceId)"},date:{type:"string",description:"YYYY-MM-DD (optional, defaults to today)"}},required:["currencyCode"],group:"currencies",readOnly:!0,searchHint:"currency effective exchange rate for a date custom or platform",isConcurrencySafe:!0,execute:async(t,e)=>Rot(t.client,e.currencyCode,e.date)}];Nwr={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","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"])};Owr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);$B={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},qB={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},s3={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."},fst={type:"string",enum:["ACCEPT","CONFIRM","VOID","DELETE"],description:"Lifecycle action. ACCEPT=quote/request only; CONFIRM=order only; VOID=any non-draft; DELETE=draft only."},pst={SALE_QUOTE:["ACCEPT","VOID","DELETE"],SALE_ORDER:["CONFIRM","VOID","DELETE"],PURCHASE_REQUEST:["ACCEPT","VOID","DELETE"],PURCHASE_ORDER:["CONFIRM","VOID","DELETE"]};Tf=[{name:"get_organization",description:"Get organization details: name, base currency, country, and financial year end.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>Ra(t.client)},{name:"get_my_context",description:"Resolve the CALLER's own context \u2014 identity, the employee bound to their login (if any), and per-module access (moduleRoles). Use to route a receipt (bill if PURCHASES access, expense claim if EMPLOYEE_CLAIMS access). A service api-key usually has no bound employee. Magic claim drafts auto-bind the uploader server-side \u2014 no need to read employee.resourceId to bind one.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"who am i my employee my permissions module roles what can i do self caller capabilities bills claims",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>t0e(t.client)},hr("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(t,e,r)=>Dd(t,{limit:r,offset:e}),"list chart of accounts with code type class status"),Wt({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:US,defaults:$S,fetcher:xE,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: ${bwr}. COGS = "Direct Costs". Common variants normalized client-side. "interest expense"/"interest income" is NOT auto-classified \u2014 ask, do not infer: Finance/Financing, Investing or Operating by main business activity.`},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code lock date",execute:async(t,e)=>{let r=e.name,n=await E1(t.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=BE(e.accountType);return Nw(t.client,{code:e.code,name:r,accountType:i,currencyCode:e.currencyCode,lockDate:e.lockDate})}},{name:"update_account",description:"Update a chart of accounts entry \u2014 rename, re-code, set its period lock date, or remove an existing lock date. Setting lockDate (YYYY-MM-DD) is how an individual ledger account is locked for a period: it blocks recording or editing any transaction on that account dated on or before the lock date. Pass clearLockDate to remove (unlock) an existing lock.",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."},clearLockDate:{type:"boolean",description:"Set true to remove an existing period lock date (unlock the period). Use when the user asks to remove, delete, clear, lift, or unset the lock. Do not also pass lockDate."}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code lock date unlock remove clear lock",execute:async(t,e)=>{let r=e.resourceId,n=(await TF(t.client,r)).data,o=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(a=>n[a]!==void 0&&n[a]!==null).map(a=>[a,n[a]]));!o.classificationType&&n.accountType&&(o.classificationType=n.accountType);let s=e.clearLockDate===!0;if(s&&e.lockDate!==void 0)throw new Error("clearLockDate and lockDate are mutually exclusive \u2014 pass one or the other.");return!s&&typeof n.accountLockDate=="string"&&n.accountLockDate&&(o.lockDate=n.accountLockDate.slice(0,10)),e.name!==void 0&&(o.name=e.name),e.code!==void 0&&(o.code=e.code),!s&&e.lockDate!==void 0&&(o.lockDate=e.lockDate),F0e(t.client,r,o)}},{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.
690
+ Multiple organizations are accessible: pass org_id (from list_organizations) to target one. Confirm the organization with the user before any create/update/delete.`:""),u={operation:{type:"string",enum:n,description:`The ${e.name} operation to run.`},arguments:{type:"object",description:"Parameters for the chosen operation (see the operation list above). Validated by the Jaz API.",additionalProperties:!0}};return o&&(u[Zl]={type:"string",description:Uot}),a.length&&(u.file={type:"object",description:`A file from the conversation, when the client supports passing one. Accepted by: ${a.join(", ")}. The content is fetched server-side \u2014 leave source arguments out of \`arguments\`.`,properties:{download_url:{type:"string",description:"URL the file content can be fetched from (may be temporary)."},file_id:{type:"string",description:"Host-side file identifier."},mime_type:{type:"string"},file_name:{type:"string"}},required:["download_url"]}),t&&(u.org_id={type:"string",description:"The organization (resourceId from list_organizations) to run this operation against. Required when more than one organization is accessible."}),{name:e.name,description:c,inputSchema:{type:"object",properties:u,required:["operation"],additionalProperties:!1},...a.length?{_meta:{"openai/fileParams":["file"]}}:{},annotations:{title:`${e.title??lwr(e.name)} \xB7 ${r.length} operation${r.length===1?"":"s"}`,readOnlyHint:i,destructiveHint:!i&&s,idempotentHint:i,openWorldHint:!1}}})}function jot(t){return uwr.has(t)}function bfe(t,e){let r=Ti.find(o=>o.name===t);if(!r)return{error:`Unknown namespace: ${t}.`};let n=qot(r.groups),i=n.find(o=>o.name===e||o.aliases?.includes(e));return i?{tool:i}:{error:`Unknown operation "${e}" for the ${t} tool.`,operations:n.map(o=>o.name)}}var uwr,FB=X(()=>{"use strict";rd();nd();zv();r3();uwr=new Set(Ti.map(t=>t.name))});var Yot={};bs(Yot,{loadAgentSuiteContent:()=>Awr});import{readFileSync as dwr}from"node:fs";import{dirname as fwr,join as pwr}from"node:path";import{fileURLToPath as hwr}from"node:url";function Awr(){return Cfe||(Cfe=JSON.parse(dwr(pwr(mwr,"agent-suite-content.json"),"utf8"))),Cfe}var mwr,Cfe,Hot=X(()=>{"use strict";mwr=fwr(hwr(import.meta.url)),Cfe=null});var zot={};bs(zot,{buildCapabilityMap:()=>ywr});async function gwr(){try{let{loadAgentSuiteContent:t}=await Promise.resolve().then(()=>(Hot(),Yot)),e=t().counts;return{cli_command_groups:e.commands,api_rules:e.apiRules,skills:e.skills,ifrs_recipes:e.recipes,calculators:e.calculators,job_playbooks:e.jobs}}catch{return}}async function ywr(t={}){if(t.query&&t.query.trim())return K8(t.query);if(t.namespace){let r=Ti.find(i=>i.name===t.namespace);if(!r)return{error:`Unknown namespace "${t.namespace}".`,namespaces:Ti.map(i=>i.name),hint:"Call with no arguments for the full map, or pass `query` to rank operations by keyword."};let n=jv(r.groups);return{namespace:r.name,description:r.description,operations:n.length,operation_list:n.map(Gv),hint:"Call the namespace tool with { operation, arguments }, or execute_tool with the operation name on a meta-tool surface."}}let e=ky(t.surface,t.multiOrg);return{...e,map:t.full?NB().map(r=>({...r,operation_list:jv(Ti.find(n=>n.name===r.namespace).groups).map(Gv)})):e.map,beyond_mcp:await gwr()}}var Got=X(()=>{"use strict";rd();FB();zv();W8()});import{randomUUID as Ewr}from"node:crypto";function ost(t,e,r){return{type:"object",description:`The ${t.toLowerCase()} to create. Required.`,properties:{reference:{type:"string",description:`${t} reference`},contactResourceId:{type:"string",description:`${e} UUID`},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},dueDate:{type:"string",description:"YYYY-MM-DD. Defaults to value date."},taxInclusion:{type:"boolean"},isTaxVATApplicable:{type:"boolean"},lineItems:{type:"array",description:`${t} line items (max 500)`,items:{type:"object",properties:{name:{type:"string",description:"Line description"},quantity:{type:"number"},unit:{type:"string"},unitPrice:{type:"number"},organizationAccountResourceId:{type:"string",description:`${r} account UUID`},itemResourceId:{type:"string"},taxProfileResourceId:{type:"string"}},required:["name"]}},recordedPayment:{type:"object",description:"Optional. The matching payment record \u2014 auto-built from the bank entry if omitted.",properties:{reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},organizationAccountResourceId:{type:"string"},paymentAmount:{type:"number"},transactionAmount:{type:"number"},paymentMethod:Vv,adjustment:Wv}},capsuleResourceId:{type:"string"}},required:["reference","lineItems"]}}function Est(t){let e=t.limit,r=t.offset;return{limit:e,offset:r,sortBy:void 0,sortOrder:void 0}}function hr(t,e,r,n,i,o){let s={...Tfe};return o?.leanView&&(s.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). List lean, then drill in with get_*."}),{name:t,description:e,params:s,required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(a,c)=>{let{limit:u,offset:d}=Est(c),f=o?.leanView?c.view==="full"?"full":"lean":void 0;return eS((h,m)=>n(a.client,h,m,f),u,d,f==="lean"?50:20)}}}function Bi(t,e,r,n,i,o){return{name:t,description:e,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(s,a)=>n(s.client,a.resourceId)}}function bst(t){if(!t||typeof t!="object"||Array.isArray(t))return{};let e=t.data;return e&&typeof e=="object"&&!Array.isArray(e)?e:t}function Cst(t,e,r,n){return{[e]:!0,...bst(t),[r]:n}}function MB(t){return`Deletes a DRAFT ${t}; VOIDs an active one and KEEPS it. force: true hard-deletes either.`}function Rwr(t,e,r){let n=bst(t);return{outcome:(typeof n.status=="string"?Swr[n.status]:void 0)??(r?"DELETED":"DELETED_IF_DRAFT_VOIDED_IF_ACTIVE"),...n,resourceId:e}}function Wr(t,e,r,n,i,o){let s=o?.verb??"deleted";return{name:t,description:e,params:{resourceId:{type:"string",description:o?.paramDescription??"Resource ID (UUID)"},...o?.voidable?Dwr:{}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(a,c)=>{let u=c.resourceId;ts(u,"resourceId",`Nothing was deleted. Source a real resourceId from a search_* or list_* result before calling ${t}.`);let d=c.force,f=await n(a.client,u,{force:d,internalNotes:c.internalNotes});return o?.voidable?Rwr(f,u,d):Cst(f,s,"resourceId",u)}}}function PB(t,e,r,n){return{name:t,description:`Download ${/^[aeiou]/i.test(e)?"an":"a"} ${e} as PDF. Returns { fileUrl } (may be pending/empty if the document is not yet rendered).`,params:{resourceId:{type:"string",description:`${e[0].toUpperCase()}${e.slice(1)} resourceId`}},required:["resourceId"],group:r,readOnly:!0,searchHint:`download ${e} as PDF document file`,isConcurrencySafe:!0,execute:async(i,o)=>n(i.client,o.resourceId)}}function xfe(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,...i?.destructive?{isDestructive:!0}:{},...i?.searchHint?{searchHint:i.searchHint}:{},execute:async(o,s)=>n(o.client,s.resourceId)}}function ust(t){if(typeof t!="string"||/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let e=/^(\d{4}-\d{2}-\d{2})T/.exec(t);return e?e[1]:t}function Fwr(t){return Array.isArray(t)?t.map(e=>{let r={};for(let[n,i]of Object.entries(e)){if(i==null)continue;let o=RX.get(n);if(o)r[o]=i;else if(n==="taxProfile"&&typeof i=="object"&&i!==null){let s=i.resourceId;s&&(r.taxProfileResourceId=s)}else if(n==="discount"&&typeof i=="object"&&i!==null){let s=i.rateValue;s&&Number(s)!==0&&(r.discount=i)}else Owr.has(n)&&(r[n]=i)}return r}):t}async function UB(t,e,r,n){let s=(await(e==="invoice"?Qs:e==="bill"?xs:e==="customer_credit_note"?Ol:Fl)(t,r)).data,a=Nwr[e],c={};for(let[p,h]of Object.entries(s))a.has(p)&&h!==null&&h!==void 0&&(c[p]=h);c.valueDate&&(c.valueDate=ust(c.valueDate)),c.dueDate&&(c.dueDate=ust(c.dueDate)),c.lineItems&&(c.lineItems=Fwr(c.lineItems));for(let[p,h]of Object.entries(n))h!==void 0&&(c[p]=h);let u=e==="invoice"?Vc:e==="bill"?ma:oo,{missingFields:d,ready:f}=Ys(c,u);if(!f)throw new Error(`Cannot finalize: missing ${d.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function dst(t,e,r,n){if((await t(e,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function a3(t,e,r){if(!(typeof t=="string"&&e.includes(t)))return{error:`Unknown documentType ${JSON.stringify(t)}.`,status:422,hint:`Use one of: ${e.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}function hst(t,e,r){let n=pst[t];if(!n)return{error:`Unknown documentType "${t}".`,status:422,hint:`Valid document types: ${Object.keys(pst).join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}};if(!n.includes(e)){let i=n.includes("ACCEPT")?"ACCEPT":"CONFIRM";return{error:`Action "${e}" is not valid for ${t}. Valid actions: ${n.join(", ")}.`,status:422,hint:`${t} advances its lifecycle with ${i}, not ${e}.`,repair:{tool:r,arguments:{documentType:t,action:i},reason:`${t} is advanced with ${i}.`}}}}async function mst(t,e,r,n,i,o,s){let a;try{a=(await e(t,r)).data?.status}catch{return}if(a==="DRAFT"||a==="VOID"){let c=a==="DRAFT"?`A DRAFT ${n} can't be linked or accepted \u2014 issue it by creating the ${n} with saveAsDraft:false (status ${s}), then link the order to that one.`:`A VOID ${n} can't be used \u2014 create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a ${a} ${n} (${r}).`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. ${c}`,repair:{tool:o,arguments:{documentType:i,saveAsDraft:!1},reason:c}}}}async function Ast(t,e,r,n,i,o){let s;try{s=(await e(t,r)).data?.status}catch{return}if(s==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:o,arguments:{},reason:`The source ${n} is VOID.`}}}async function gst(t,e,r,n,i){let o;try{o=(await e(t,r,n)).data?.status}catch{return}if(o&&o!=="DRAFT")return{error:`Cannot DELETE a ${o} ${r} \u2014 delete is only allowed on DRAFT records.`,status:422,hint:"Use action VOID to cancel a non-draft quote/request/order.",repair:{tool:i,arguments:{documentType:r,resourceId:n,action:"VOID"},reason:`${r} is ${o}; void it instead of deleting.`}}}var bwr,Za,Io,Xl,vo,di,id,i3,Oy,Jot,Cwr,Vot,Wot,Ife,vfe,Jv,QB,Iwr,vwr,wfe,Zot,Xot,_fe,Tfe,Am,Dfe,Kot,est,tst,rst,Qi,nst,LB,wwr,Sfe,o3,Aa,ist,yst,od,Vv,Wv,_wr,Dwr,Swr,Ist,xwr,sst,ast,cst,Twr,Bwr,Rfe,lst,kwr,Nwr,Owr,$B,qB,s3,fst,pst,Tf,c3=X(()=>{"use strict";gP();yC();xX();dMe();gMe();ZD();Sa();fr();An();fA();cA();TE();APe();bPe();Xf();ng();_d();YX();HX();og();zX();vp();xF();zF();Qw();GX();UPe();eU();aU();pU();ait();Mw();XF();jw();LH();zw();VP();zH();bde();Cde();az();Ide();Bde();Fde();Mit();vp();gB();Qde();Lde();Ez();Zit();Hde();zde();Gde();tot();Wde();hm();Uz();oD();Zde();Xde();Gw();i7();iot();uot();fot();NX();pot();tfe();o8();rfe();nfe();ife();ofe();sfe();afe();cfe();lfe();Xf();ng();Iot();og();xot();_d();eU();aU();og();o8();mn();ffe();hfe();fr();gfe();Qot();bwr=xP.join(" | "),Za={type:"string",description:"Resource ID of the record"},Io={type:"string",description:"Transaction date (YYYY-MM-DD)"},Xl={type:"string",description:"Due date (YYYY-MM-DD)"},vo={type:"string",description:"Reference number"},di={type:"string",description:"Notes or memo text"},id={type:"string",description:"Tag name for categorization"},i3={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},Oy={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},Jot={recipe:{type:"string",enum:[...xy],description:"Recipe type"},amount:{type:"number",description:"Amount (for amortization, accrued-expense, dividend, ecl, provision, fx-reval)"},principal:{type:"number",description:"Principal (for loan, fixed-deposit)"},startDate:{type:"string",description:"Start date YYYY-MM-DD (REQUIRED for blueprint generation \u2014 default to today if user does not specify)"},currency:{type:"string",description:"Currency code (e.g. SGD, USD)"},periods:{type:"number",description:"Number of periods (for amortization, accrued-expense, leave-accrual)"},frequency:{type:"string",enum:["monthly","quarterly","annual"],description:"Frequency (for depreciation, amortization, accrued-expense)"},annualRate:{type:"number",description:"Annual interest/discount rate %"},termMonths:{type:"number"},monthlyPayment:{type:"number",description:"Monthly lease payment (for lease)"},usefulLifeMonths:{type:"number",description:"Asset useful life in months (hire purchase)"},cost:{type:"number",description:"Asset cost"},salvageValue:{type:"number"},usefulLifeYears:{type:"number"},method:{type:"string",enum:["sl","ddb","150db"],description:"Depreciation method"},acquisitionDate:{type:"string",description:"Acquisition date YYYY-MM-DD"},disposalDate:{type:"string",description:"Disposal date YYYY-MM-DD"},proceeds:{type:"number",description:"Disposal proceeds"},bookRate:{type:"number",description:"Original booking rate. Declare which way it reads via rateDirection (REQUIRED for fx-reval)."},closingRate:{type:"number",description:"Period-end closing rate. Same direction as bookRate."},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"REQUIRED for fx-reval. FUNCTIONAL_TO_SOURCE = 1 base unit = N foreign, what list_currency_rates returns. SOURCE_TO_FUNCTIONAL = 1 foreign unit = N base, the everyday quote."},position:{type:"string",enum:["ASSET","LIABILITY"],description:"Balance-sheet side: ASSET (receivable/deposit, default) or LIABILITY (payable/provision). A rising base value is a gain on an asset and a loss on a liability."},baseCurrency:{type:"string",description:"Base (functional) currency"},buckets:{type:"array",items:{type:"object",properties:{name:{type:"string"},balance:{type:"number"},rate:{type:"number"}},required:["name","balance","rate"]},description:"ECL aging buckets"},existingProvision:{type:"number",description:"Existing ECL provision balance"},compounding:{type:"string",enum:["none","monthly","quarterly","annually"]},employees:{type:"number"},daysPerYear:{type:"number",description:"Leave days per employee per year"},dailyRate:{type:"number",description:"Average daily rate"},declarationDate:{type:"string",description:"Board resolution date YYYY-MM-DD"},paymentDate:{type:"string",description:"Settlement date YYYY-MM-DD"},withholdingRate:{type:"number",description:"Withholding tax rate %"}},Cwr={type:"boolean",description:"Retry-only: set true after the duplicate guard surfaced a candidate and the user confirmed this is a separate document. Never on a first attempt."},Vot={type:"string",enum:[...kX],description:"CUSTOM (default) = free text; ALL_* = a picklist of that population. Datatype is derived, not chosen."},Wot={type:"object",properties:{address:{type:"string",description:"Street address \u2014 sent as addressLine1"},city:{type:"string"},state:{type:"string"},postalCode:{type:"string"},country:{type:"string"}},required:["address","country"]},Ife={type:"string",description:"Contact resourceId (customer or supplier)"},vfe={type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID)"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Draft entity type"}},required:["btResourceId","btType"]}},Jv={type:"string",description:"Chart-of-accounts account the line posts to (revenue on a sale, expense on a purchase)"},QB={type:"string",description:"Account the payment posts to. For paymentMethod BANK_TRANSFER/CASH/CHEQUE this MUST be a bank or cash account. Any other method accepts any org account \u2014 that is how a deposit drawdown works (paymentMethod OTHER + the deposit account)."},Iwr={type:"number",description:"Payment amount (in bank currency)"},vwr={type:"string",description:"Period start date (YYYY-MM-DD)"},wfe={type:"string",description:"Period end date (YYYY-MM-DD)"},Zot={type:"string",enum:["full","aggregate"],description:`Output detail (default 'full'). 'aggregate' returns a compact aging-bucket summary (current, <1 month, 1/2/3 months, older + total outstanding + contact count). Prefer 'aggregate' for a general or unqualified report request (e.g. "show me my aged receivables", "my AR report") \u2014 it's the at-a-glance overview a chat user expects and it won't truncate on large orgs. Use 'full' only when the user explicitly asks for the per-contact (customer/supplier) breakdown for deeper analysis.`},Xot={type:"string",description:"Currency code (e.g. SGD, USD)"},_fe={type:"string",description:"Display name"},Tfe={limit:{type:"number",description:"Max results per page (\u22641000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},Am={type:"object",required:["sourceCurrency"],properties:{sourceCurrency:{type:"string",description:"Foreign currency code (ISO 4217)."},exchangeRate:{type:"number",description:'Base\u2192source: N where 1 org-base unit = N sourceCurrency. Invert ONLY if your quote reads "1 source = X base" (send 1/X), or declare rateDirection and skip the arithmetic. Omit for the org/platform rate.'},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:"How exchangeRate reads. SOURCE_TO_FUNCTIONAL accepts a bank quote verbatim. Default FUNCTIONAL_TO_SOURCE."}}},Dfe={type:"string",enum:[...Hd],description:"Entity type to export"},Kot={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.'},est={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},tst={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."},rst={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."},Qi={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},nst={type:"array",description:"Full replacement line-item set \u2014 non-empty REPLACES all lines, [] clears, omit = no change. claimTypeResourceId + name + unitPrice + quantity are required at submit time.",items:{type:"object",properties:{resourceId:{type:"string",description:"Existing line resourceId (omit to add a new line)"},claimTypeResourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"Line name"},description:{type:"string",description:"Line description"},unitPrice:{type:"number",description:"Unit price"},quantity:{type:"number",description:"Quantity"},currency:{type:"string",description:"Line currency (ISO 4217; falls back to header)"},itemSubTotal:{type:"number",description:"Line subtotal (unitPrice \xD7 quantity)"}}}},LB={type:"array",items:{type:"string"},description:"Claim resourceIds (1-500)"},wwr={type:"array",items:{type:"object",required:["resourceId","type","selectedClasses","printable"],properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",required:["className"],properties:{className:{type:"string"},resourceId:Za}}},printable:{type:"boolean",description:"Show on printed documents."}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},Sfe={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)"},o3={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Offset account resourceId"},amount:{type:"number",description:"Amount (positive; direction comes from the endpoint)"},description:{type:"string",description:"Line description"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId"}},required:["accountResourceId","amount"]},description:"Offset lines. No `type` \u2014 cash-in credits these and cash-out debits them, decided by the endpoint."},Aa={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:Jv,taxProfileResourceId:{type:"string"},classifierConfig:wwr},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},ist={type:"array",items:{type:"object",properties:{itemName:{type:"string",description:"Display name of the catalog item"},itemResourceId:{type:"string",description:"Underlying item resourceId (from search_items)"},price:{type:"number",description:"Default unit price (0-1e9)"},unit:{type:"string",description:"Unit of measure"},quantityDefault:{type:"number",description:"Default quantity when added to a document (0-100)"},discountDefault:{type:"number",description:"Default discount % when added to a document (0-100)"},uiIndex:{type:"number",description:"Display position in the catalog (integer, min 0)"},classifiers:{type:"array",items:{type:"object"},description:"Classifier assignments. Same shape as classifierConfig on invoice/bill line items."}},required:["itemName","itemResourceId","price"]},description:"Catalog item rows. itemName, itemResourceId and price are required on every row."},yst={type:"array",items:{type:"object",properties:{slotKey:{type:"string",description:"Slot from get_capsule_recipe templateSlots[]."},template:{type:"string",description:"Text with {{vars}} for that slot; empty string clears a nullable slot. Max 2000."}},required:["slotKey"]},description:"Optional. Customize recipe-generated text via published slots (see get_capsule_recipe)."},od={type:"object",description:"Optional IFRS recipe trigger. Mutex with capsuleResourceId. Silent-null on failure \u2014 preview_capsule_recipe first. Rule 143.",properties:{recipeName:{type:"string",enum:["LOAN_AMORTIZATION","ACCRUAL_REVERSAL","PREPAID_AMORTIZATION","DEFERRED_REVENUE","IFRS16_LEASE"],description:"Must match mutation's allowedBaseTransactionTypes (see list_capsule_recipes)."},recipeVersion:{type:"number",description:"Optional version pin."},inputs:{type:"object",description:"Schema at versions[0].inputSchema. Single-currency; *AccountResourceId x-accountClass-locked."},templateOverrides:yst},required:["recipeName","inputs"]},Vv={type:"string",enum:[...qMe],description:"Payment method (default BANK_TRANSFER)"},Wv={type:"object",description:"Cash-leg adjustment (overpayment/rounding). Bank leg only, never AR/AP. Not with DEBT_WRITE_OFF/CLEARING_SETTLEMENT/INTER_COMPANY/WITHHOLDING_TAX_CERTIFICATE. See rule 160.",properties:{adjustmentValue:{type:"number",description:"Signed, non-zero, max 2dp"},adjustmentAccountResourceId:{type:"string",description:"Non-controlled account, not bank/cash"},adjustmentDescription:{type:"string",description:"Optional"}},required:["adjustmentValue","adjustmentAccountResourceId"]},_wr={...Wv,description:"Adding or changing an adjustment applies here. REMOVING does not: 0 is rejected and null reads as omitted, so both leave the stored value unchanged. To remove one, delete the payment and record it again. A change is rejected if the payment is reconciled or lock-dated, and amount, account and description are all compared, so resend all three unchanged if you are not editing it. See rule 160."};Dwr={force:{type:"boolean",description:"Hard-delete instead of voiding."},internalNotes:{type:"string",description:"Note recorded with the void."}},Swr={VOID:"VOIDED",SUCCEEDED:"DELETED"};Ist=["invoices","bills","customer-credit-notes","supplier-credit-notes"],xwr=[...Ist,"purchase-orders","purchase-requests","sale-orders","sale-quotes","claims"],sst={type:"string",description:"Document family",enum:Ist},ast={type:"string",description:"Document family",enum:xwr},cst={type:"string",description:"Why it is sent back. Opens a thread; the only record of the reason."},Twr=[{name:"approve_documents",description:"Approve one document awaiting approval. Posts its ledger entries and makes it live. One-shot, and the refusal channel differs by entity: invoices/bills THROW 422; credit notes return 200 with isSuccess:false and a STALE approvalStatus of APPROVED. Check isSuccess and catch the throw \u2014 approvalStatus alone cannot tell refusal from success.",params:{entity:sst,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"approvals",readOnly:!1,searchHint:"approve pending invoice bill credit note post ledger",execute:async(t,e)=>got(t.client,e.entity,e.resourceId)},{name:"bulk_approve_documents",description:"Approve up to 100 documents awaiting approval. Async \u2014 returns a jobId; poll search_background_jobs. Each approval posts a ledger.",params:{entity:sst,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-100)"}},required:["entity","resourceIds"],group:"approvals",readOnly:!1,searchHint:"bulk approve many pending documents at once",execute:async(t,e)=>yot(t.client,e.entity,e.resourceIds)},{name:"request_document_changes",description:"Send one document back for changes instead of approving it. Also covers orders, quotes, requests and claims.",params:{entity:ast,resourceId:{type:"string",description:"Document resourceId"},message:cst},required:["entity","resourceId","message"],group:"approvals",readOnly:!1,searchHint:"request changes reject send back document for revision",execute:async(t,e)=>Eot(t.client,e.entity,e.resourceId,e.message)},{name:"bulk_request_document_changes",description:"Send up to 500 documents back for changes with one message. Async \u2014 returns a jobId; poll search_background_jobs.",params:{entity:ast,resourceIds:{type:"array",items:{type:"string"},description:"resourceIds (1-500)"},message:cst},required:["entity","resourceIds","message"],group:"approvals",readOnly:!1,searchHint:"bulk request changes send back many documents",execute:async(t,e)=>bot(t.client,e.entity,e.resourceIds,e.message)}],Bwr=["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"],Rfe={type:"string",description:"Document family",enum:Bwr},lst={type:"string",description:"Version id from get_document_version_history"},kwr=[{name:"get_document_version_history",description:"The stored versions of a document, newest first. Not paginated. Use before restoring to pick a version id.",params:{entity:Rfe,resourceId:{type:"string",description:"Document resourceId"}},required:["entity","resourceId"],group:"versions",readOnly:!0,searchHint:"list document version history revisions audit trail",isConcurrencySafe:!0,execute:async(t,e)=>_ot(t.client,e.entity,e.resourceId)},{name:"get_document_version",description:"Read one stored version of a document. An unknown resourceId/version pair returns 422.",params:{entity:Rfe,resourceId:{type:"string",description:"Document resourceId"},version:lst},required:["entity","resourceId","version"],group:"versions",readOnly:!0,searchHint:"get read one document version snapshot",isConcurrencySafe:!0,execute:async(t,e)=>Dot(t.client,e.entity,e.resourceId,e.version)},{name:"rollback_document_version",description:"Restore a document to a stored version. REPLACES current state \u2014 read the version first with get_document_version.",params:{entity:Rfe,resourceId:{type:"string",description:"Document resourceId"},version:lst},required:["entity","resourceId","version"],group:"versions",readOnly:!1,searchHint:"restore rollback document to previous version undo changes",isDestructive:!0,execute:async(t,e)=>Sot(t.client,e.entity,e.resourceId,e.version)},{name:"get_currency_effective_rate",description:"The organization effective rate for a currency on a date: its own custom rate when set, else the platform daily rate. Defaults to today.",params:{currencyCode:{type:"string",description:"ISO 4217 code, e.g. USD (not a resourceId)"},date:{type:"string",description:"YYYY-MM-DD (optional, defaults to today)"}},required:["currencyCode"],group:"currencies",readOnly:!0,searchHint:"currency effective exchange rate for a date custom or platform",isConcurrencySafe:!0,execute:async(t,e)=>Rot(t.client,e.currencyCode,e.date)}];Nwr={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","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"])};Owr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);$B={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},qB={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},s3={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."},fst={type:"string",enum:["ACCEPT","CONFIRM","VOID","DELETE"],description:"Lifecycle action. ACCEPT=quote/request only; CONFIRM=order only; VOID=any non-draft; DELETE=draft only."},pst={SALE_QUOTE:["ACCEPT","VOID","DELETE"],SALE_ORDER:["CONFIRM","VOID","DELETE"],PURCHASE_REQUEST:["ACCEPT","VOID","DELETE"],PURCHASE_ORDER:["CONFIRM","VOID","DELETE"]};Tf=[{name:"get_organization",description:"Get organization details: name, base currency, country, and financial year end.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>Ra(t.client)},{name:"get_my_context",description:"Resolve the CALLER's own context \u2014 identity, the employee bound to their login (if any), and per-module access (moduleRoles). Use to route a receipt (bill if PURCHASES access, expense claim if EMPLOYEE_CLAIMS access). A service api-key usually has no bound employee. Magic claim drafts auto-bind the uploader server-side \u2014 no need to read employee.resourceId to bind one.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"who am i my employee my permissions module roles what can i do self caller capabilities bills claims",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>t0e(t.client)},hr("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(t,e,r)=>Dd(t,{limit:r,offset:e}),"list chart of accounts with code type class status"),Wt({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:US,defaults:$S,fetcher:xE,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: ${bwr}. COGS = "Direct Costs". Common variants normalized client-side. "interest expense"/"interest income" is NOT auto-classified \u2014 ask, do not infer: Finance/Financing, Investing or Operating by main business activity.`},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code lock date",execute:async(t,e)=>{let r=e.name,n=await E1(t.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=BE(e.accountType);return Nw(t.client,{code:e.code,name:r,accountType:i,currencyCode:e.currencyCode,lockDate:e.lockDate})}},{name:"update_account",description:"Update a chart of accounts entry \u2014 rename, re-code, set its period lock date, or remove an existing lock date. Setting lockDate (YYYY-MM-DD) is how an individual ledger account is locked for a period: it blocks recording or editing any transaction on that account dated on or before the lock date. Pass clearLockDate to remove (unlock) an existing lock.",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."},clearLockDate:{type:"boolean",description:"Set true to remove an existing period lock date (unlock the period). Use when the user asks to remove, delete, clear, lift, or unset the lock. Do not also pass lockDate."}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code lock date unlock remove clear lock",execute:async(t,e)=>{let r=e.resourceId,n=(await TF(t.client,r)).data,o=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(a=>n[a]!==void 0&&n[a]!==null).map(a=>[a,n[a]]));!o.classificationType&&n.accountType&&(o.classificationType=n.accountType);let s=e.clearLockDate===!0;if(s&&e.lockDate!==void 0)throw new Error("clearLockDate and lockDate are mutually exclusive \u2014 pass one or the other.");return!s&&typeof n.accountLockDate=="string"&&n.accountLockDate&&(o.lockDate=n.accountLockDate.slice(0,10)),e.name!==void 0&&(o.name=e.name),e.code!==void 0&&(o.code=e.code),!s&&e.lockDate!==void 0&&(o.lockDate=e.lockDate),F0e(t.client,r,o)}},{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.
691
691
 
692
692
  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 all 23 accountType values (see create_account); common variants normalized via normalizeAccountType.
693
693
 
@@ -740,7 +740,7 @@ Optional capsuleRecipe (JOURNAL_MANUAL base \u2014 ACCRUAL_REVERSAL, IFRS16_LEAS
740
740
  - Line items use "name" for item description.
741
741
  - 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:Jv},required:["name","quantity","unitPrice"]},description:"Credit note line items"},currency:Am,saveAsDraft:{type:"boolean",description:"Save as draft (default true)"},notes:di,tag:id,customFields:Qi},required:["valueDate","lineItems"],group:"customer_credit_notes",readOnly:!1,searchHint:"create new customer credit note draft",execute:async(t,e)=>{let r=fl(e);if(r)return r;let{notes:n,tag:i,...o}=e,s={...o,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};s.reference||(s.reference=ui("CCN"));let a=await hR(t.client,s);return Sf(a,Ww(a.appliedRate,e.currency))}},Wr("delete_customer_credit_note",MB("customer credit note"),"customer_credit_notes",W2,"delete draft or void active customer credit note",{paramDescription:"Customer credit note resourceId",voidable:!0}),{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:vo,valueDate:Io,lineItems:Aa,notes:di,tag:id,customFields:Qi},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"update customer credit note lines reference",execute:async(t,e)=>{let{resourceId:r,notes:n,tag:i,...o}=e,s={...o,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};return V2(t.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:vo,valueDate:Io,lineItems:Aa,notes:di},required:["resourceId"],group:"customer_credit_notes",readOnly:!1,searchHint:"approve finalize customer credit note",isDestructive:!0,execute:async(t,e)=>{let{resourceId:r,notes:n,...i}=e,o={...i,...n!==void 0&&{invoiceNotes:n}},s=await UB(t.client,"customer_credit_note",r,o),a=fl(s,{assumeFinalize:!0});return a||mR(t.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:QB,valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},reference:{type:"string",description:"Payment reference"},paymentMethod:Vv,adjustment:Wv},required:["creditNoteId","paymentAmount","accountResourceId","valueDate"],group:"customer_credit_notes",readOnly:!1,searchHint:"refund customer credit note to bank account",isDestructive:!0,execute:async(t,e)=>{let r=Number(e.paymentAmount);if(!Number.isFinite(r)||r<=0)throw new Error("paymentAmount must be a positive number");let n=Number(e.transactionAmount??r);if(!Number.isFinite(n)||n<=0)throw new Error("transactionAmount must be a positive number");return AR(t.client,e.creditNoteId,{paymentAmount:r,transactionAmount:n,accountResourceId:e.accountResourceId,valueDate:e.valueDate,dueDate:e.valueDate,reference:e.reference??"",paymentMethod:e.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1,adjustment:e.adjustment})}},{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(t,e)=>Z2(t.client,e.creditNoteId)},hr("list_supplier_credit_notes","List supplier credit notes (AP adjustments/refunds). Paginated \u2014 response includes totalElements. Use limit/offset to page.","supplier_credit_notes",(t,e,r,n)=>tU(t,{limit:r,offset:e,view:n}),"list supplier credit notes with status pagination",{leanView:!0}),Wt({name:"search_supplier_credit_notes",description:"Search supplier credit notes. Status: DRAFT, UNAPPLIED, PARTIALLY_APPLIED, APPLIED, VOID.",group:"supplier_credit_notes",fields:$p,defaults:sS,fetcher:gR,searchHint:"find supplier credit notes refunds CN by reference status contact tag"}),{name:"get_supplier_credit_note",description:"Fetch a supplier credit note by internal resourceId. To search by other fields, use `search_supplier_credit_notes`.",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(t,e)=>Fl(t.client,e.resourceId)},{name:"create_supplier_credit_note",description:`Create a supplier credit note. Saves as draft by default.
742
742
  - Status when finalized is UNAPPLIED (not APPROVED).
743
- - Line items use "name" for item description.`,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:Jv},required:["name","quantity","unitPrice"]},description:"Credit note line items"},currency:Am,saveAsDraft:{type:"boolean",description:"Save as draft (default true)"},notes:di,tag:id,customFields:Qi},required:["valueDate","lineItems"],group:"supplier_credit_notes",readOnly:!1,searchHint:"create new supplier credit note draft",execute:async(t,e)=>{let r=fl(e);if(r)return r;let{notes:n,tag:i,...o}=e,s={...o,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};s.reference||(s.reference=ui("SCN"));let a=await yR(t.client,s);return Sf(a,Ww(a.appliedRate,e.currency))}},Wr("delete_supplier_credit_note",MB("supplier credit note"),"supplier_credit_notes",nU,"delete draft or void active supplier credit note",{paramDescription:"Supplier credit note resourceId",voidable:!0}),PB("download_supplier_credit_note_pdf","supplier credit note","supplier_credit_notes",(t,e)=>iU(t,e)),{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:vo,valueDate:Io,lineItems:Aa,notes:di,tag:id,customFields:Qi},required:["resourceId"],group:"supplier_credit_notes",readOnly:!1,searchHint:"update supplier credit note lines reference",execute:async(t,e)=>{let{resourceId:r,notes:n,tag:i,...o}=e,s={...o,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};return rU(t.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:vo,valueDate:Io,lineItems:Aa,notes:di},required:["resourceId"],group:"supplier_credit_notes",readOnly:!1,searchHint:"approve finalize supplier credit note",isDestructive:!0,execute:async(t,e)=>{let{resourceId:r,notes:n,...i}=e,o={...i,...n!==void 0&&{invoiceNotes:n}},s=await UB(t.client,"supplier_credit_note",r,o),a=fl(s,{assumeFinalize:!0});return a||ER(t.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:QB,valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},reference:{type:"string",description:"Payment reference"},paymentMethod:Vv,adjustment:Wv},required:["creditNoteId","paymentAmount","accountResourceId","valueDate"],group:"supplier_credit_notes",readOnly:!1,searchHint:"refund supplier credit note from bank account",isDestructive:!0,execute:async(t,e)=>{let r=Number(e.paymentAmount);if(!Number.isFinite(r)||r<=0)throw new Error("paymentAmount must be a positive number");let n=Number(e.transactionAmount??r);if(!Number.isFinite(n)||n<=0)throw new Error("transactionAmount must be a positive number");return bR(t.client,e.creditNoteId,{paymentAmount:r,transactionAmount:n,accountResourceId:e.accountResourceId,valueDate:e.valueDate,dueDate:e.valueDate,reference:e.reference??"",paymentMethod:e.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1,adjustment:e.adjustment})}},{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(t,e)=>oU(t.client,e.creditNoteId)},{name:"list_currencies",description:"List currencies enabled for the organization. Returns code, name, symbol, isBaseCurrency.",params:{},required:[],group:"currencies",readOnly:!0,searchHint:"list currencies enabled active organization base currency code symbol",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async t=>CR(t.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(t,e)=>{let r=e.currencies,n=await CR(t.client),i=new Set(n.data.map(c=>c.currencyCode.toUpperCase())),o=r.filter(c=>i.has(c.toUpperCase())),s=r.filter(c=>!i.has(c.toUpperCase()));if(s.length===0)return{_guard:"duplicate_skipped",message:`All currencies already enabled: ${r.join(", ")}.`,existing:o};let a=await cU(t.client,s);return o.length>0?{...a,_note:`Skipped already-enabled: ${o.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")'},...Tfe},required:["currencyCode"],group:"currencies",readOnly:!0,searchHint:"list exchange rates for a currency pair",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(t,e)=>{let{limit:r,offset:n}=Est(e),i=e.currencyCode;return eS((o,s)=>lU(t.client,i,{limit:s,offset:o}),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 direction is base\u2192source (1 org-base unit = N of this currency); see the rate param before sending. Call list_currencies first to get valid currency codes.',params:{currencyCode:{type:"string",description:"Currency code"},rate:{type:"number",description:'Base\u2192source: N where 1 org-base unit = N of this currency. Invert ONLY if your figure reads "1 thisCurrency = X base" \u2014 SGD org + USD ("1 USD = 1.35 SGD") \u2192 0.74; USD org + PHP ("1 USD = 56.5 PHP") \u2192 56.5 unchanged. Or declare rateDirection and pass your figure as-is.'},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:'Optional. Declare how your rate reads and skip the mental arithmetic: SOURCE_TO_FUNCTIONAL lets you pass a bank quote ("1 USD = 1.35 SGD" \u2192 1.35) verbatim. Default FUNCTIONAL_TO_SOURCE.'},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(t,e)=>uU(t.client,e.currencyCode,{rate:e.rate,rateDirection:e.rateDirection,rateApplicableFrom:e.rateApplicableFrom,rateApplicableTo:e.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 rate. Base\u2192source: N where 1 org-base unit = N of this currency. Invert only if your figure reads "1 thisCurrency = X base" (send 1/X), or declare rateDirection.'},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:'Optional. Declare how your rate reads and skip the mental arithmetic: SOURCE_TO_FUNCTIONAL lets you pass a bank quote ("1 USD = 1.35 SGD" \u2192 1.35) verbatim. Default FUNCTIONAL_TO_SOURCE.'},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(t,e)=>dU(t.client,e.currencyCode,e.resourceId,{rate:e.rate,rateDirection:e.rateDirection,rateApplicableFrom:e.rateApplicableFrom,rateApplicableTo:e.rateApplicableTo})},{name:"bulk_upsert_currency_rates",description:"Max 500 exchange rates 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(t,e)=>(await fU(t.client,e.rates)).data},hr("list_tax_profiles","List tax profiles (GST, VAT, etc.). Returns name, rate, tax type.","tax_profiles",(t,e,r)=>OE(t,{limit:r,offset:e}),"list tax profiles GST VAT rates"),hr("list_tax_types","List available tax types. Use the tax type code when creating tax profiles.","tax_profiles",(t,e,r)=>MF(t,{limit:r,offset:e}),"list available tax types for profile creation"),hr("list_modules","List the modules (features/capabilities) enabled for the organization.","modules",(t,e,r)=>hPe(t,{limit:r,offset:e}),"list enabled org modules features capabilities"),Bi("get_module","Get details for a single org module by resourceId.","modules",(t,e)=>mPe(t,e),"get module details"),hr("list_account_classifications","List account classifications (reference list for categorising chart-of-accounts entries).","accounts",(t,e,r)=>Q0e(t,{limit:r,offset:e}),"list account classifications categories for chart of accounts"),hr("list_purchase_items","List purchase-side catalog items.","purchase_items",(t,e,r)=>gPe(t,{limit:r,offset:e}),"list purchase items purchasable catalog products"),Bi("get_purchase_item","Get a single purchase item by resourceId.","purchase_items",(t,e)=>yPe(t,e),"get purchase item details"),Wt({name:"search_purchase_items",description:"Search purchase items by name, reference, or currency.",group:"purchase_items",fields:PX,defaults:UX,fetcher:EPe,searchHint:"find purchase items purchasable catalog by name reference currency"}),hr("list_catalogs","List catalogs (product/service groupings).","catalogs",(t,e,r)=>q2(t,{limit:r,offset:e}),"list catalogs product service groupings"),Bi("get_catalog","Get a catalog by resourceId (includes its items).","catalogs",(t,e)=>j2(t,e),"get catalog details items"),Wt({name:"search_catalogs",description:"Search catalogs by name, description, status, or contact group.",group:"catalogs",fields:vS,defaults:wS,fetcher:Y2,searchHint:"find catalogs by name description status contact group"}),{name:"create_catalog",description:"Create a catalog. status defaults to INACTIVE. items[] are catalog-item rows; contactGroupResourceIds[] scopes it to contact groups.",params:{catalogName:{type:"string",description:"Catalog name"},description:{type:"string",description:"Catalog description"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Record status (defaults INACTIVE)"},contactGroupResourceIds:{type:"array",items:{type:"string"},description:"Contact group resourceIds to scope the catalog to"},items:ist},required:["catalogName","items"],group:"catalogs",readOnly:!1,searchHint:"create new catalog product service grouping",execute:async(t,e)=>H2(t.client,{catalogName:e.catalogName,description:e.description,status:e.status,contactGroupResourceIds:e.contactGroupResourceIds,items:e.items})},{name:"update_catalog",description:"Update a catalog. FULL REPLACEMENT \u2014 GET first, merge, then send the complete body; omitting items or contactGroupResourceIds DROPS them.",params:{resourceId:{type:"string",description:"Catalog resourceId"},catalogName:{type:"string",description:"Catalog name"},description:{type:"string",description:"Catalog description"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Record status"},contactGroupResourceIds:{type:"array",items:{type:"string"},description:"Contact group resourceIds"},items:ist},required:["resourceId","catalogName","items"],group:"catalogs",readOnly:!1,searchHint:"update edit catalog",execute:async(t,e)=>z2(t.client,e.resourceId,{catalogName:e.catalogName,description:e.description,status:e.status,contactGroupResourceIds:e.contactGroupResourceIds,items:e.items})},Wr("delete_catalog","Delete a catalog.","catalogs",(t,e)=>G2(t,e),"delete remove catalog"),hr("list_organization_report_templates","List saved organization report templates.","report_templates",(t,e,r)=>LPe(t,{limit:r,offset:e}),"list organization report templates saved"),Bi("get_organization_report_template","Get a saved report template by resourceId.","report_templates",(t,e)=>MPe(t,e),"get report template details"),Wt({name:"search_organization_report_templates",description:"Search report templates by type, category, or default flag.",group:"report_templates",fields:$X,defaults:qX,fetcher:PPe,searchHint:"find organization report templates by type category default"}),{name:"move_transaction_capsules",description:"Move business transactions from one capsule to another. Pass the transaction resourceIds, the source capsule (oldCapsuleResourceId), and the destination (newCapsuleResourceId).",params:{businessTransactionResourceIds:{type:"array",items:{type:"string"},description:"Transaction resourceIds to move"},newCapsuleResourceId:{type:"string",description:"Destination capsule resourceId"},oldCapsuleResourceId:{type:"string",description:"Source capsule resourceId"}},required:["businessTransactionResourceIds","newCapsuleResourceId","oldCapsuleResourceId"],group:"capsules",readOnly:!1,searchHint:"move transactions between capsules regroup reassign capsule",execute:async(t,e)=>LF(t.client,{businessTransactionResourceIds:e.businessTransactionResourceIds,newCapsuleResourceId:e.newCapsuleResourceId,oldCapsuleResourceId:e.oldCapsuleResourceId})},{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(t,e)=>{let r=e.name,n=await b1(t.client,r);return n?{_guard:"duplicate_skipped",message:`Tax profile "${r}" already exists.`,existing:n}:PF(t.client,{name:r,taxRate:e.taxRate,taxTypeCode:e.taxTypeCode})}},hr("list_cash_in","List cash-in entries (direct cash receipts). Paginated.","cash_entries",(t,e,r)=>UH(t,{limit:r,offset:e}),"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.
743
+ - Line items use "name" for item description.`,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:Jv},required:["name","quantity","unitPrice"]},description:"Credit note line items"},currency:Am,saveAsDraft:{type:"boolean",description:"Save as draft (default true)"},notes:di,tag:id,customFields:Qi},required:["valueDate","lineItems"],group:"supplier_credit_notes",readOnly:!1,searchHint:"create new supplier credit note draft",execute:async(t,e)=>{let r=fl(e);if(r)return r;let{notes:n,tag:i,...o}=e,s={...o,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};s.reference||(s.reference=ui("SCN"));let a=await yR(t.client,s);return Sf(a,Ww(a.appliedRate,e.currency))}},Wr("delete_supplier_credit_note",MB("supplier credit note"),"supplier_credit_notes",nU,"delete draft or void active supplier credit note",{paramDescription:"Supplier credit note resourceId",voidable:!0}),PB("download_supplier_credit_note_pdf","supplier credit note","supplier_credit_notes",(t,e)=>iU(t,e)),{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:vo,valueDate:Io,lineItems:Aa,notes:di,tag:id,customFields:Qi},required:["resourceId"],group:"supplier_credit_notes",readOnly:!1,searchHint:"update supplier credit note lines reference",execute:async(t,e)=>{let{resourceId:r,notes:n,tag:i,...o}=e,s={...o,...n!==void 0&&{invoiceNotes:n},...i!==void 0&&{tags:[i]}};return rU(t.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:vo,valueDate:Io,lineItems:Aa,notes:di},required:["resourceId"],group:"supplier_credit_notes",readOnly:!1,searchHint:"approve finalize supplier credit note",isDestructive:!0,execute:async(t,e)=>{let{resourceId:r,notes:n,...i}=e,o={...i,...n!==void 0&&{invoiceNotes:n}},s=await UB(t.client,"supplier_credit_note",r,o),a=fl(s,{assumeFinalize:!0});return a||ER(t.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:QB,valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},reference:{type:"string",description:"Payment reference"},paymentMethod:Vv,adjustment:Wv},required:["creditNoteId","paymentAmount","accountResourceId","valueDate"],group:"supplier_credit_notes",readOnly:!1,searchHint:"refund supplier credit note from bank account",isDestructive:!0,execute:async(t,e)=>{let r=Number(e.paymentAmount);if(!Number.isFinite(r)||r<=0)throw new Error("paymentAmount must be a positive number");let n=Number(e.transactionAmount??r);if(!Number.isFinite(n)||n<=0)throw new Error("transactionAmount must be a positive number");return bR(t.client,e.creditNoteId,{paymentAmount:r,transactionAmount:n,accountResourceId:e.accountResourceId,valueDate:e.valueDate,dueDate:e.valueDate,reference:e.reference??"",paymentMethod:e.paymentMethod??"BANK_TRANSFER",saveAsDraft:!1,adjustment:e.adjustment})}},{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(t,e)=>oU(t.client,e.creditNoteId)},{name:"list_currencies",description:"List currencies enabled for the organization. Returns code, name, symbol, isBaseCurrency.",params:{},required:[],group:"currencies",readOnly:!0,searchHint:"list currencies enabled active organization base currency code symbol",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async t=>CR(t.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(t,e)=>{let r=e.currencies,n=await CR(t.client),i=new Set(n.data.map(c=>c.currencyCode.toUpperCase())),o=r.filter(c=>i.has(c.toUpperCase())),s=r.filter(c=>!i.has(c.toUpperCase()));if(s.length===0)return{_guard:"duplicate_skipped",message:`All currencies already enabled: ${r.join(", ")}.`,existing:o};let a=await cU(t.client,s);return o.length>0?{...a,_note:`Skipped already-enabled: ${o.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")'},...Tfe},required:["currencyCode"],group:"currencies",readOnly:!0,searchHint:"list exchange rates for a currency pair",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(t,e)=>{let{limit:r,offset:n}=Est(e),i=e.currencyCode;return eS((o,s)=>lU(t.client,i,{limit:s,offset:o}),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 direction is base\u2192source (1 org-base unit = N of this currency); see the rate param before sending. Call list_currencies first to get valid currency codes.',params:{currencyCode:{type:"string",description:"Currency code"},rate:{type:"number",description:'Base\u2192source: N where 1 org-base unit = N of this currency. Invert ONLY if your figure reads "1 thisCurrency = X base" \u2014 SGD org + USD ("1 USD = 1.35 SGD") \u2192 0.74; USD org + PHP ("1 USD = 56.5 PHP") \u2192 56.5 unchanged. Or declare rateDirection and pass your figure as-is.'},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:'Optional. Declare how your rate reads and skip the mental arithmetic: SOURCE_TO_FUNCTIONAL lets you pass a bank quote ("1 USD = 1.35 SGD" \u2192 1.35) verbatim. Default FUNCTIONAL_TO_SOURCE.'},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(t,e)=>uU(t.client,e.currencyCode,{rate:e.rate,rateDirection:e.rateDirection,rateApplicableFrom:e.rateApplicableFrom,rateApplicableTo:e.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 rate. Base\u2192source: N where 1 org-base unit = N of this currency. Invert only if your figure reads "1 thisCurrency = X base" (send 1/X), or declare rateDirection.'},rateDirection:{type:"string",enum:["FUNCTIONAL_TO_SOURCE","SOURCE_TO_FUNCTIONAL"],description:'Optional. Declare how your rate reads and skip the mental arithmetic: SOURCE_TO_FUNCTIONAL lets you pass a bank quote ("1 USD = 1.35 SGD" \u2192 1.35) verbatim. Default FUNCTIONAL_TO_SOURCE.'},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(t,e)=>dU(t.client,e.currencyCode,e.resourceId,{rate:e.rate,rateDirection:e.rateDirection,rateApplicableFrom:e.rateApplicableFrom,rateApplicableTo:e.rateApplicableTo})},{name:"bulk_upsert_currency_rates",description:"Max 500 exchange rates 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:"Must be > 0. Read in whatever direction rateDirection declares."},rateDirection:{type:"string",description:'REQUIRED here, no default. FUNCTIONAL_TO_SOURCE = 1 org-base unit = N of this currency (what list_currency_rates returns). SOURCE_TO_FUNCTIONAL = a bank quote ("1 USD = 1.35 SGD" \u2192 1.35) passed verbatim.',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(t,e)=>(await fU(t.client,e.rates)).data},hr("list_tax_profiles","List tax profiles (GST, VAT, etc.). Returns name, rate, tax type.","tax_profiles",(t,e,r)=>OE(t,{limit:r,offset:e}),"list tax profiles GST VAT rates"),hr("list_tax_types","List available tax types. Use the tax type code when creating tax profiles.","tax_profiles",(t,e,r)=>MF(t,{limit:r,offset:e}),"list available tax types for profile creation"),hr("list_modules","List the modules (features/capabilities) enabled for the organization.","modules",(t,e,r)=>hPe(t,{limit:r,offset:e}),"list enabled org modules features capabilities"),Bi("get_module","Get details for a single org module by resourceId.","modules",(t,e)=>mPe(t,e),"get module details"),hr("list_account_classifications","List account classifications (reference list for categorising chart-of-accounts entries).","accounts",(t,e,r)=>Q0e(t,{limit:r,offset:e}),"list account classifications categories for chart of accounts"),hr("list_purchase_items","List purchase-side catalog items.","purchase_items",(t,e,r)=>gPe(t,{limit:r,offset:e}),"list purchase items purchasable catalog products"),Bi("get_purchase_item","Get a single purchase item by resourceId.","purchase_items",(t,e)=>yPe(t,e),"get purchase item details"),Wt({name:"search_purchase_items",description:"Search purchase items by name, reference, or currency.",group:"purchase_items",fields:PX,defaults:UX,fetcher:EPe,searchHint:"find purchase items purchasable catalog by name reference currency"}),hr("list_catalogs","List catalogs (product/service groupings).","catalogs",(t,e,r)=>q2(t,{limit:r,offset:e}),"list catalogs product service groupings"),Bi("get_catalog","Get a catalog by resourceId (includes its items).","catalogs",(t,e)=>j2(t,e),"get catalog details items"),Wt({name:"search_catalogs",description:"Search catalogs by name, description, status, or contact group.",group:"catalogs",fields:vS,defaults:wS,fetcher:Y2,searchHint:"find catalogs by name description status contact group"}),{name:"create_catalog",description:"Create a catalog. status defaults to INACTIVE. items[] are catalog-item rows; contactGroupResourceIds[] scopes it to contact groups.",params:{catalogName:{type:"string",description:"Catalog name"},description:{type:"string",description:"Catalog description"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Record status (defaults INACTIVE)"},contactGroupResourceIds:{type:"array",items:{type:"string"},description:"Contact group resourceIds to scope the catalog to"},items:ist},required:["catalogName","items"],group:"catalogs",readOnly:!1,searchHint:"create new catalog product service grouping",execute:async(t,e)=>H2(t.client,{catalogName:e.catalogName,description:e.description,status:e.status,contactGroupResourceIds:e.contactGroupResourceIds,items:e.items})},{name:"update_catalog",description:"Update a catalog. FULL REPLACEMENT \u2014 GET first, merge, then send the complete body; omitting items or contactGroupResourceIds DROPS them.",params:{resourceId:{type:"string",description:"Catalog resourceId"},catalogName:{type:"string",description:"Catalog name"},description:{type:"string",description:"Catalog description"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Record status"},contactGroupResourceIds:{type:"array",items:{type:"string"},description:"Contact group resourceIds"},items:ist},required:["resourceId","catalogName","items"],group:"catalogs",readOnly:!1,searchHint:"update edit catalog",execute:async(t,e)=>z2(t.client,e.resourceId,{catalogName:e.catalogName,description:e.description,status:e.status,contactGroupResourceIds:e.contactGroupResourceIds,items:e.items})},Wr("delete_catalog","Delete a catalog.","catalogs",(t,e)=>G2(t,e),"delete remove catalog"),hr("list_organization_report_templates","List saved organization report templates.","report_templates",(t,e,r)=>LPe(t,{limit:r,offset:e}),"list organization report templates saved"),Bi("get_organization_report_template","Get a saved report template by resourceId.","report_templates",(t,e)=>MPe(t,e),"get report template details"),Wt({name:"search_organization_report_templates",description:"Search report templates by type, category, or default flag.",group:"report_templates",fields:$X,defaults:qX,fetcher:PPe,searchHint:"find organization report templates by type category default"}),{name:"move_transaction_capsules",description:"Move business transactions from one capsule to another. Pass the transaction resourceIds, the source capsule (oldCapsuleResourceId), and the destination (newCapsuleResourceId).",params:{businessTransactionResourceIds:{type:"array",items:{type:"string"},description:"Transaction resourceIds to move"},newCapsuleResourceId:{type:"string",description:"Destination capsule resourceId"},oldCapsuleResourceId:{type:"string",description:"Source capsule resourceId"}},required:["businessTransactionResourceIds","newCapsuleResourceId","oldCapsuleResourceId"],group:"capsules",readOnly:!1,searchHint:"move transactions between capsules regroup reassign capsule",execute:async(t,e)=>LF(t.client,{businessTransactionResourceIds:e.businessTransactionResourceIds,newCapsuleResourceId:e.newCapsuleResourceId,oldCapsuleResourceId:e.oldCapsuleResourceId})},{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(t,e)=>{let r=e.name,n=await b1(t.client,r);return n?{_guard:"duplicate_skipped",message:`Tax profile "${r}" already exists.`,existing:n}:PF(t.client,{name:r,taxRate:e.taxRate,taxTypeCode:e.taxTypeCode})}},hr("list_cash_in","List cash-in entries (direct cash receipts). Paginated.","cash_entries",(t,e,r)=>UH(t,{limit:r,offset:e}),"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.
744
744
 
745
745
  accountResourceId MUST be a Bank/Cash account (from list_bank_accounts) \u2014 any other type fails. Cannot appear in lines (API enforces separation).
746
746
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jaz-clio",
3
- "version": "5.47.8",
3
+ "version": "5.47.10",
4
4
  "description": "Clio: Command Line Interface Operator for Jaz AI.",
5
5
  "type": "module",
6
6
  "bin": {