jaz-clio 5.47.9 → 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.
- package/assets/skills/api/SKILL.md +1 -1
- package/assets/skills/cli/SKILL.md +1 -1
- package/assets/skills/conversion/SKILL.md +1 -1
- package/assets/skills/jaz-kit/SKILL.md +1 -1
- package/assets/skills/jaz-pseudo-sql/SKILL.md +1 -1
- package/assets/skills/jobs/SKILL.md +1 -1
- package/assets/skills/transaction-recipes/SKILL.md +1 -1
- package/cli.mjs +1 -1
- package/package.json +1 -1
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}
|