jaz-clio 5.55.8 → 5.55.9
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 +2 -1
- package/package.json +1 -1
package/cli.mjs
CHANGED
|
@@ -672,7 +672,7 @@ Unsupported type: `+t.type,"ENOTSUP");t._finish()})};il.prototype._stat=function
|
|
|
672
672
|
`,a),u=c!==-1?c:i.length;return i.slice(s,u).trim()}catch{return null}}function i0r(){let t=Fit(import.meta.url),e=Oit(t),r=[Sm(e,"..","..","..","help-center-mirror"),Sm(e,"..","..","..","assets","skills","api","help-center-mirror"),Sm(e,"help-center-mirror")];for(let n of r)try{return Cfe(Sm(n,"index.md"),"utf-8"),n}catch{}return null}var Bit,kit,Wvr,Zvr,Xvr,Kvr,e0r,t0r,r0r,Wz,Nit,bfe,zB=X(()=>{"use strict";Efe();AC();Bit=1.2,kit=.75,Wvr=1.5,Zvr=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"]),Xvr=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"]]]);Kvr=.7,e0r=3,t0r=32,r0r=5;Wz=null,Nit=null;bfe=null});import{existsSync as o0r,readFileSync as s0r}from"node:fs";import{dirname as a0r,join as vfe}from"node:path";import{fileURLToPath as c0r}from"node:url";function GB(t){let e=t??p0r();if(!e)return null;if(Zz&&Uit===e)return Zz;try{let r=s0r(e,"utf-8");return Zz=JSON.parse(r),Uit=e,Zz}catch{return null}}function p0r(){let t=c0r(import.meta.url),e=a0r(t),r=[vfe(e,"..","..","..","help-center-mirror","help-center-embeddings.json"),vfe(e,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),vfe(e,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(o0r(n))return n;return null}function jit(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 Yit(){return Xz!==null?Xz:(Xz=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",Xz||null)}async function wfe(t){let e=Yit();if(!e)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),u0r),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:l0r,input:t}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!$it&&($it=!0,process.stderr.write(`[help-center] CLIO_HELP_CENTER_OPENAI_API_KEY rejected by OpenAI \u2014 falling back to BM25
|
|
673
673
|
`)),null)}catch{return null}}async function JB(t,e,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??d0r,c=n.minBm25??f0r;if(i==="bm25"||!e)return Gy(t,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await wfe(r);return m?qit(t,e,m,{limit:o,section:s}).filter(g=>g.score>=a):Gy(t,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([wfe(r),Promise.resolve(Gy(t,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=qit(t,e,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Hit(p,h,o)}function qit(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=jit(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 Hit(t,e,r){let n=new Map;for(let o=0;o<t.length;o++){let s=t[o],a=1/(Mit+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/(Mit+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 _fe(t){return t!==null&&!!Yit()}var l0r,u0r,Mit,d0r,f0r,Zz,Uit,Xz,$it,Kz=X(()=>{"use strict";zB();l0r="text-embedding-3-small",u0r=2e3,Mit=60,d0r=.3,f0r=1.5,Zz=null,Uit=null,Xz=null,$it=!1});async function zit(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=YB();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:GB(),u=await JB(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=(Ife(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 Git(){let t=process.env.CLIO_HELP_CENTER_URL?.trim();return t&&t.length>0?t:h0r}async function e8(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(Git())}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(m0r),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return A0r(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 A0r(t){if(typeof t!="object"||t===null)return!1;let e=t;return Array.isArray(e.results)?!0:typeof e.error=="string"}async function Dfe(t,e={}){return process.env.CLIO_DAEMON==="1"||HB()?zit(t,e):e8(t,e)}var h0r,m0r,Jit=X(()=>{"use strict";zB();Kz();h0r="https://mcp.jaz.ai/help-center/search",m0r=4e3});var Sfe=X(()=>{"use strict";zB();Kz();Jit();zB()});var Vit,Wit=X(()=>{"use strict";Vit={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 t8(t,e){let{blueprint:r,accountMap:n,finalize:i}=e,o=!i;g0r(e);let s=await y0r(t,r.capsuleType),a=r.steps[0]?.date??new Date().toISOString().slice(0,10),c=`${r.capsuleName} (${a})`,d={resourceId:(await TA(t,{capsuleTypeResourceId:s,title:c,description:r.capsuleDescription})).data.resourceId,type:r.capsuleType,title:c},f=Kit(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 E0r(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 g0r(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)xfe(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(", ")}.
|
|
674
674
|
Add these to your account mapping JSON.`);let a=Kit(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 y0r(t,e){let n=(await eb(t)).data.find(o=>o.displayName.toLowerCase()===e.toLowerCase());return n?n.resourceId:(await a_(t,{displayName:e})).data.resourceId}function Kit(t){if(!t.existingTxnId)return null;let e=Vit[t.calcType];return e?t.blueprint.steps.find(n=>e.includes(n.action))?.step??null:null}async function E0r(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 Cg(t,{reference:s,valueDate:e.date,journalEntries:Rfe(e.lines,i),internalNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"bill":{a=(await xA(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:Zit(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"invoice":{a=(await Eg(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:Zit(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"cash-in":{let{contraLines:c}=Xit(e.lines,r.bankAccountId,i);a=(await Kv(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:Rfe(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}case"cash-out":{let{contraLines:c}=Xit(e.lines,r.bankAccountId,i);a=(await e0(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:Rfe(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 Rfe(t,e){return t.map(r=>({accountResourceId:Tfe(r.account,e),type:r.debit>0?"DEBIT":"CREDIT",amount:r.debit>0?r.debit:r.credit}))}function Zit(t,e){return t.filter(r=>xfe(r.account,e)).map(r=>({name:r.account,quantity:1,unitPrice:r.debit>0?r.debit:r.credit,accountResourceId:Tfe(r.account,e)}))}function Xit(t,e,r){let n=[],i=null;for(let o of t)Tfe(o.account,r)===e&&!i?i=o:n.push(o);return i?{bankLine:i,contraLines:n}:{bankLine:t[0],contraLines:t.slice(1)}}function xfe(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 Tfe(t,e){let r=xfe(t,e);if(!r)throw new Error(`Unmapped account: "${t}"`);return e[r]}var Bfe=X(()=>{"use strict";Ig();Ud();bg();Oz();l_();Wit()});function r0(t,e,r={}){let n=r.threshold??.4,i=r.limit??5,o=t.toLowerCase().trim(),s=e.find(c=>c.code?.toLowerCase()===o);if(s)return[{item:s,score:1}];let a=e.find(c=>c.name.toLowerCase()===o);return a?[{item:a,score:1}]:og(t,e,c=>c.name,{threshold:n,limit:i})}function r8(t,e){let r=r0(t,e,{threshold:.45,limit:1});return r.length>0?r[0].item:null}function eot(t){return t.filter(e=>e.status==="ACTIVE"&&!e.controlFlag&&e.accountType!=="Bank Accounts"&&e.accountType!=="Cash")}function tot(t){return t.filter(e=>e.status==="ACTIVE"&&(e.accountType==="Bank Accounts"||e.accountType==="Cash"))}var kfe=X(()=>{"use strict";AC()});function n8(t,e,r={}){let n=r.threshold??.4,i=r.limit??5;return e.map(s=>{let a=[s.billingName,s.name].filter(Boolean),c=Math.max(...a.map(u=>hZ(t,u)));return{item:s,score:c}}).filter(s=>s.score>=n).sort((s,a)=>a.score-s.score).slice(0,i)}var Nfe=X(()=>{"use strict";AC()});async function rot(t,e){let n=(await $p((s,a)=>$d(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=r8(s,n);if(a)i[s]=a.resourceId;else{let c=r0(s,n,{threshold:.3,limit:3});o.push({name:s,candidates:c.map(u=>u.item.name)})}}return{mapping:i,failures:o}}async function not(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 fp(t,e)).data;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}let n=e.trim(),o=(await Cc(t,{filter:{name:{contains:n}},limit:50})).data;if(o.length===0&&(o=(await dp(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=n8(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 iot(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 pC(t,e);return{resourceId:i.data.resourceId,displayName:i.data.name}}let n=await sg(t,e);return{resourceId:n.resourceId,displayName:n.name}}var oot=X(()=>{"use strict";XE();pp();Mp();nM();kfe();Nfe();QP()});async function Rm(t,e){await t.delete(`/api/v1/cash-entries/${e}`)}async function xm(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}var VB=X(()=>{"use strict";En()});async function i8(t,e){return t.post("/api/v1/transfer-trial-balance",{...e,currency:Sr(e.currency),taxCurrency:Sr(e.taxCurrency)})}var Ofe=X(()=>{"use strict";dr()});async function o8(t,e){return t.list("/api/v1/organization/bookmarks",e)}async function s8(t,e){return t.get(`/api/v1/organization/bookmarks/${e}`)}async function WB(t,e){return t.post("/api/v1/organization/bookmarks",{items:e})}async function a8(t,e,r){return t.put(`/api/v1/organization/bookmarks/${e}`,r)}var Ffe=X(()=>{"use strict"});function b0r(t){let{refs:e,...r}=t;return e?{...r,refs:e.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function n0(t,e){return t.post("/api/v1/jots",{entries:e.map(b0r)})}async function c8(t,e){return t.post("/api/v1/jots/search",e)}async function sot(t,e,r){return t.post(`/api/v1/jots/${e}/disposition`,r)}var l8=X(()=>{"use strict"});async function aot(t,e){return t.post("/api/v1/agents/memories",e)}async function Qfe(t,e){return t.post("/api/v1/agents/memories/forget",e)}var cot=X(()=>{"use strict"});function u8(){return process.env.ENABLE_MEMORY==="true"}function Lfe(){return process.env.ENABLE_MEMORY_CHAT==="true"}function lot(t){return!u8()||!t||!t.progressive?"memory_disabled":t.isInboxOwner?null:"not_owner"}var Pfe=X(()=>{"use strict"});var Ufe={};xo(Ufe,{default:()=>I0r,log:()=>Mfe});var d8,C0r,uot,Mfe,I0r,$fe=X(()=>{"use strict";d8=()=>{},C0r=()=>Mfe,uot=(...t)=>{try{process.stderr.write(t.map(String).join(" ")+`
|
|
675
|
-
`)}catch{}},Mfe={info:d8,warn:d8,error:uot,debug:d8,trace:d8,fatal:uot,child:C0r,level:"error"},I0r=Mfe});import{createHash as v0r}from"node:crypto";function O0r(t){if(!t||!t.trim())return[null,"directive_required"];let e=t.normalize("NFKC").trim();return e.length>300?[null,"directive_too_long"]:pot.some(r=>e.includes(r))?[null,"directive_invalid"]:fot.test(e)?[null,"directive_invalid"]:x0r.test(e)?[null,"directive_contains_url"]:T0r.test(e)?[null,"directive_contains_email"]:[e,null]}function F0r(t){if(t==null)return[null,null];let e=t.normalize("NFKC").trim();return e?e.length>B0r?[null,"match_condition_too_long"]:pot.some(r=>e.includes(r))?[null,"match_condition_invalid"]:fot.test(e)?[null,"match_condition_invalid"]:[e,null]:[null,"match_condition_invalid"]}function Q0r(t){return t==null?[null,null]:Number.isInteger(t)?t<k0r||t>N0r?[null,"invalid_importance"]:[t,null]:[null,"invalid_importance"]}function L0r(t,e,r,n,i,o,s,a){if(t)return v0r("sha256").update(`${t}:${e}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function P0r(t){Promise.resolve().then(()=>($fe(),Ufe)).then(({log:e})=>e.info(t,"memory_tool.call")).catch(()=>{})}async function got(t,e,r){let n=e.action,i=e.category,o=S0r[e.scope??"this_org"]??"ORG_USER",s=typeof e.key=="string"?e.key.trim():"",a=null,c=d=>(P0r({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=lot(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>w0r||!R0r.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[C,E]=O0r(e.directive);if(E)return u(E);p=C;let[I,v]=Q0r(e.importance);if(v)return u(v);h=I}let[m,A]=F0r(e.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=_0r)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,D0r));let E=L0r(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 qfe(()=>aot(t.client,I)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let C={category:i,key:s,scope:o};y=await qfe(()=>Qfe(t.client,C))}else{let C={forgetAll:!0};y=await qfe(()=>Qfe(t.client,C))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function qfe(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 Wi?e.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${e.status}`}:{ok:!1,reason:"network_error"}}}var fot,pot,w0r,_0r,D0r,hot,mot,Aot,S0r,R0r,x0r,T0r,B0r,k0r,N0r,yot=X(()=>{"use strict";cot();Na();Pfe();Pfe();fot=/[\x00-\x1f\x7f]/,pot=["{{","}}","```","<",">"],w0r=120,_0r=3,D0r=140,hot=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],mot=["set","forget","forget_all"],Aot=["this_org","all_orgs"],S0r={this_org:"ORG_USER",all_orgs:"USER"},R0r=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,x0r=/https?:\/\//i,T0r=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,B0r=255,k0r=0,N0r=100});async function f8(t,e){return t.list("/api/v1/organization-users",e)}async function p8(t,e){return t.search("/api/v1/organization-users/search",e)}async function i0(t,e){return t.post("/api/v1/organization-users/invite",e)}async function h8(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function m8(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var jfe=X(()=>{"use strict"});async function A8(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 g8(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function y8(t,e){return t.get(`/api/v1/payments/${e}`)}async function E8(t,e,r){return t.put(`/api/v1/payments/${e}`,{...r,currency:Sr(r.currency)})}async function b8(t,e){await t.delete(`/api/v1/payments/${e}`)}function C8(t,e){return(r,n)=>r.post(`/api/v1/${t}/${e}`,{...n,transactions:n.transactions.map(i=>({...i,currency:Sr(i.currency)}))})}var Tin,Bin,kin,Nin,Yfe=X(()=>{"use strict";dr();Tin=C8("sales","bulk-payments"),Bin=C8("sales","batch-payments"),kin=C8("purchases","bulk-payments"),Nin=C8("purchases","batch-payments")});async function I8(t,e,r={}){let n=M0r.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`,i=await t.post(n,r),o=i?.data?.fileUrl,s=a=>{try{return/\.pdf$/i.test(new URL(a).pathname)}catch{return!1}};return r.outputFormat==="PDF"&&typeof o=="string"&&!s(o)?{...i,formatDowngraded:`PDF was requested but ${e} returned a non-PDF file. This export type does not produce PDF; re-request as XLSX, or use one of: ${[...Hfe].join(", ")}.`}:i}var M0r,Hfe,zfe=X(()=>{"use strict";M0r=new Set(["statement-of-account-export"]),Hfe=new Set(["trial-balance","balance-sheet","profit-and-loss","cashflow","cash-balance","ar-report","ap-report","tax-ledger","equity-movement","bank-closing-balance","fixed-assets-register"])});import{createHash as U0r}from"node:crypto";import{writeFile as $0r,mkdir as q0r}from"node:fs/promises";import{dirname as j0r,isAbsolute as Y0r,join as H0r}from"node:path";async function v8(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function ZB(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 o0(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function Gfe(t){return U0r("sha256").update(t).digest("hex").slice(0,16)}async function w8(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Gfe(e),o=await ZB(t,e,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await o0(t,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await o0(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&&!Y0r(r.outPath))throw new at(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??H0r(f,"Downloads",`pseudo-sql-${s}.csv`);return await q0r(j0r(p),{recursive:!0}),await $0r(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}}}function _8(t,e){let{agentSkillsDoc:r,...n}=t,i=e?.trim();if(!i)return n;let o=i.toLowerCase(),s=n.tables.filter(c=>c.name?.toLowerCase()===o);if(s.length===0)throw new at(`pseudo-sql: no table named "${i}". Available: ${n.tables.map(c=>c.name).join(", ")}`);let a=n.joins.filter(c=>c.leftTable?.toLowerCase()===o||c.rightTable?.toLowerCase()===o);return{...n,tables:s,joins:a,tableCount:s.length,joinCount:a.length,scopedTo:i}}async function s0(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 Jfe=X(()=>{"use strict";dr()});async function D8(t){return t.get("/api/v1/capsule-recipes")}async function S8(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function R8(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function x8(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function T8(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function Ea(t){if(!t||typeof t!="object")throw new at("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(!OD(e.recipeName))throw new at("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 at("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 at("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 at(`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 at("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 at(`capsuleRecipe.templateOverrides[${s}] must be an object {slotKey, template?}.`);let a=o;if(!OD(a.slotKey))throw new at(`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 at(`capsuleRecipe.templateOverrides[${s}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new at(`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 at(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new at(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var Vfe=X(()=>{"use strict";dr();MP()});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 k8(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 N8(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var B8,Tm=X(()=>{"use strict";B8=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function ol(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Wfe=X(()=>{"use strict"});async function O8(t,e){return t.post("/api/v1/claims/conversion/preview",e)}async function F8(t,e){if(e.idempotencyKey&&/^CONV[:-]/.test(e.idempotencyKey))throw new at('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return t.post("/api/v1/claims/conversion/commit",e)}var XB,Zfe=X(()=>{"use strict";dr();XB=["POST","POST_AND_RECORD"]});async function Q8(t,e){if(!(e.amount>0))throw new at("amount must be greater than 0.");return t.post("/api/v1/claims/payouts/record",e)}async function L8(t,e){return t.search("/api/v1/employees/payouts/search",e)}var Eot,Xfe=X(()=>{"use strict";dr();Eot=["REIMBURSEMENT","ADVANCE"]});function bot(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 Cot=X(()=>{"use strict"});import{randomUUID as z0r}from"node:crypto";import{rmSync as G0r}from"node:fs";function epe(t){for(let e of t.tempDirs??[])try{G0r(e,{recursive:!0,force:!0})}catch{}}function vot(t){for(let[e,r]of Jy)t-r.createdAt>Iot&&(epe(r.plan),Jy.delete(e))}function V0r(){Kfe||(Kfe=setInterval(()=>vot(Date.now()),J0r),Kfe.unref?.())}function wot(t,e){let r=Date.now();vot(r),V0r();let n=`dc_${z0r()}`;return Jy.set(n,{plan:t,createdAt:r,ownerKey:e}),n}function _ot(t,e){let r=Jy.get(t);return!r||r.ownerKey!==e?null:Date.now()-r.createdAt>Iot?(epe(r.plan),Jy.delete(t),null):r.plan}function Dot(t,e){let r=Jy.get(t);!r||r.ownerKey!==e||(epe(r.plan),Jy.delete(t))}var Iot,J0r,Jy,Kfe,Sot=X(()=>{"use strict";Iot=1800*1e3,J0r=300*1e3,Jy=new Map});function W0r(t){if(!t||typeof t!="object")return;let e=t;return e.validFiles?.[0]?.workflowResourceId??e.workflowResourceId}function Z0r(t,e){let r=new Set(e);return{...t,folders:t.folders.map(n=>({...n,files:n.files.filter(i=>DQ(i.documentType)&&r.has(i.documentType))}))}}async function Rot(t){let{plan:e,client:r,bankAccountId:n,documentTypes:i}=t,o=i&&i.length>0?Z0r(e,i):e;if(!n&&X0r(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 LP({plan:o,client:r,bankAccountId:n}),a=s.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?W0r(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 X0r(t){return t.folders.some(e=>e.files.some(r=>r.documentType==="BANK_STATEMENT"))}var xot=X(()=>{"use strict";mZ();Ep()});async function ud(t,e,r){if(!e)return t;let n=K0r(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 K0r(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 jf(t,e){return!e||!t||typeof t!="object"?t:{_fx:e,...t}}var Tot=X(()=>{"use strict"});async function P8(t,e){return t.list("/api/v1/bank-rules",e)}async function KB(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 M8(t,e){return t.search("/api/v1/bank-rules/search",e)}async function U8(t,e){return t.post("/api/v1/bank-rules",e)}async function $8(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function q8(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var tpe=X(()=>{"use strict"});async function j8(t,e){return t.list("/api/v1/fixed-assets",e)}async function ek(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function Y8(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function H8(t,e){return t.post("/api/v1/fixed-assets",e)}async function z8(t,e,r){let i=(await ek(t,e)).data,o={};for(let s of ewr){let a=i[s];if(a==null)continue;let c=twr.has(s)?Il(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 G8(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function J8(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function tk(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function V8(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function W8(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function Z8(t,e){return Ao(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var ewr,twr,X8=X(()=>{"use strict";En();JE();ewr=["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"],twr=new Set(["purchaseDate","depreciationStartDate"])});async function K8(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function rk(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function e3(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function t3(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 rk(t,e);if(i){let a=Il(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 r3(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function n3(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 i3(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var rpe=X(()=>{"use strict";JE()});async function o3(t,e){return t.list("/api/v1/contact-groups",e)}async function s3(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function a3(t,e){return t.search("/api/v1/contact-groups/search",e)}async function c3(t,e){return t.post("/api/v1/contact-groups",e)}async function l3(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,HE(r,m6))}async function u3(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var npe=X(()=>{"use strict";En()});async function d3(t,e){return t.list("/api/v1/inventory-items",e)}async function f3(t,e){return t.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...e})}async function p3(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var ipe=X(()=>{"use strict"});async function h3(t,e){return t.list("/api/v1/custom-fields",e)}async function nk(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function m3(t,e){return t.search("/api/v1/custom-fields/search",e)}async function A3(t,e){return t.post("/api/v1/custom-fields",e)}function nwr(t){return t!==void 0&&rwr.every(e=>t[e]!==void 0)}function iwr(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 owr(t){return[t.applyToSales,t.applyToPurchase,t.applyToSaleCreditNote,t.applyToPurchaseCreditNote,t.applyToPayment,t.applyToCreditNote].some(e=>e==="PRINT")}async function g3(t,e,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!nwr(n.appliesTo)){let i=await nk(t,e);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??owr(i.data),n.appliesTo={...iwr(i.data),...r.appliesTo}}return t.put(`/api/v1/custom-fields/${e}`,n)}async function y3(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var rwr,ope=X(()=>{"use strict";rwr=["invoices","bills","customerCredits","supplierCredits","payments"]});function Bot(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function ik(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return Bot(n)}async function ok(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return Bot(n)}var swr,awr,cwr,a0,spe=X(()=>{"use strict";swr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],awr=["journals","cash-entries"],cwr=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],a0=[...swr,...awr,...cwr]});async function E3(t,e){return t.list("/api/v1/nano-classifiers",e)}async function b3(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function C3(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function sk(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function ak(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,{...r,resourceId:e})}async function I3(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var ape=X(()=>{"use strict"});async function v3(t,e){return t.post("/api/v1/export-records",e)}async function w3(t,e){return t.post("/api/v1/export-records/preview",e)}async function _3(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var cpe=X(()=>{"use strict"});async function ck(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var lpe=X(()=>{"use strict"});function D3(t,e){if(!e.has(t))throw new at(`unknown entity "${t}" \u2014 expected one of ${[...e].join(", ")}`)}function Oot(t,e,r,n=!1){if(!Array.isArray(t))throw new at(`${r}: resourceIds must be an array, not a ${typeof t}`);if(t.length===0)throw new at(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(t).size!==t.length)throw new at(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(t.length>e)throw new at(`${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.`)}function Fot(t){if(!Array.isArray(t)||t.length===0)return{state:"unconfirmed"};let e=t.find(r=>r.isSuccess===!1||r.isSuccess===void 0&&!!(r.failureReason||r.errorCode));return e?{state:"refused",reason:e.failureReason||e.errorCode||"refused without a stated reason"}:{state:"approved"}}async function S3(t,e,r){return D3(e,kot),us(r,"resourceId","Pass the document resourceId."),t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/approve`)}async function R3(t,e,r){return D3(e,kot),Oot(r,lwr,"bulk approve",!0),r.forEach(n=>us(n,"resourceIds[]","Every id must be a document resourceId.")),t.post(`/api/v1/${encodeURIComponent(e)}/bulk-approve`,{resourceIds:r})}async function x3(t,e,r,n){D3(e,Not),us(r,"resourceId","Pass the document resourceId."),Qot(n);let i=await t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:fwr(i)}}}async function T3(t,e,r,n){return D3(e,Not),Qot(n),Oot(r,uwr,"bulk request changes"),r.forEach(i=>us(i,"resourceIds[]","Every id must be a document resourceId.")),t.post(dwr(e),{resourceIds:r,message:n})}function dwr(t){return t==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${encodeURIComponent(t)}/bulk-request-changes`}function Qot(t){if(!t||t.trim().length===0)throw new at("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 fwr(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 Vy,c0,kot,Not,lwr,uwr,upe=X(()=>{"use strict";dr();Vy=["invoices","bills","customer-credit-notes","supplier-credit-notes"],c0=[...Vy,"purchase-orders","purchase-requests","sale-orders","sale-quotes","claims"],kot=new Set(Vy),Not=new Set(c0);lwr=100,uwr=500});function pwr(t,e,r){let n=Math.random().toString(36).slice(2,10);return`restore:${t}:${Lot(e)}:${Lot(r)}:${n}`}function Lot(t){return t.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function dpe(t){if(!Pot.has(t))throw new at(`unknown entity "${t}" \u2014 expected one of ${[...Pot].join(", ")}`)}async function Mot(t,e,r){return dpe(e),us(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}`)}async function Uot(t,e,r,n){return dpe(e),us(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function $ot(t,e,r,n,i){if(dpe(e),us(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new at('restoreDocumentVersion: "CREATED" is a grouping node in the version history, not a restorable snapshot. Upstream DELETES the document for it and still returns 200. Pick a numeric version id from the history instead, and read it with getDocumentVersion first to confirm it carries document fields.');return t.post(`/api/v1/rollback/${encodeURIComponent(e)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??pwr(e,r,n)}})}async function qot(t,e,r){return t.get(`/api/v1/organization/currencies/${encodeURIComponent(e)}/effective-rate`,r?{date:r}:void 0)}var Pot,jot=X(()=>{"use strict";dr();Pot=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function l0(t){Qt(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new at(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(!OD(n.btResourceId))throw new at(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!hwr.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 at(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function B3(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:Awr(r.data)}}function mwr(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 Awr(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(mwr),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function k3(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function N3(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var hwr,fpe=X(()=>{"use strict";dr();MP();En();hwr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function gwr(t){switch(t){case 401:return"Invalid or missing API key. Run `clio auth add` or set JAZ_API_KEY.";case 402:return"Not included in this organization's plan. Retrying will not help \u2014 a plan change is needed.";case 403:return"Insufficient permissions for this operation.";case 404:return"Resource not found \u2014 check the resourceId. Use a search/list tool to look it up.";case 409:return"Conflict \u2014 resource may have been modified. Re-fetch and retry.";case 422:return"Validation error \u2014 check field values against the tool description.";case 429:return"Rate limited \u2014 wait a moment and retry.";default:return""}}function Ewr(t){let r=t?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function bwr(t,e){if(t!==ywr)return;let r=Ewr(e);if(r)return Yot.get(r)??Yot.get(r.replace(/_ERROR$/,""))}function ppe(t,e=300){let r=t instanceof Error?t.message:typeof t=="string"?t:(()=>{try{return JSON.stringify(t)??"unknown error"}catch{return"unknown error"}})();return r.length>e?`${r.slice(0,e-3)}...`:r}function O3(t,e={}){let r=e.readOnly===!1&&FD()?NFe:"";if(t instanceof Wi){let s=[bwr(t.status,t.body)??gwr(t.status),r].filter(Boolean).join(" "),a={error:t.message,status:t.status,endpoint:t.endpoint,...s?{hint:s}:{}};if(e.toolName&&e.input){let c=Q3(t,e.toolName,e.input);c&&(a.repair=c)}return a}let n=t instanceof Error?t.message:String(t),i=t instanceof Ki;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var ywr,Yot,F3=X(()=>{"use strict";Na();Pd();L3();UP();ywr=422,Yot=new Map([["PSEUDOSQL_DISABLED","The SQL query engine is switched off on the reporting service, so the query text is not what was rejected. Rewriting the SQL will not help \u2014 preview and export return this until the engine is re-enabled, which is a platform deployment change: it is not an organization setting, not a plan entitlement, and nothing the caller or an organization admin can turn on. Note the catalog is served from a static in-process snapshot and stays readable while the engine is off, so get_pseudo_sql_schema still lists tables and joins that cannot currently be queried; a table appearing there is not evidence the engine is on. Use the report tools instead."],["INVALID_BUSINESS_TRANSACTION_TYPE","Despite the name, the bank entry's DIRECTION is what was rejected, not its type. reconcile_invoice_receipt needs a money-IN entry and reconcile_bill_receipt needs money-OUT. `bank add-records` creates money-in from a POSITIVE amount and money-out from a NEGATIVE one; on an existing entry, `bank records` reports a signed netAmount. Check the entry before retrying \u2014 the same call will keep failing with this code."]])});function Got(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new at("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function hpe(t,e){if(!t||typeof t!="object")throw new at(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new at(`${e}.lineItems array is empty.`);if(n.length>500)throw new at(`max 500 ${e}.lineItems per call.`);Cl([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&Cl([i],["valueDate"])}function vwr(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>=Cwr?"high":r>=Hot?"medium":"low";if(n!==void 0){if(n>=Iwr)return"high";if(n>=Hot)return"medium"}return"low"}function Jot(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=lk.magicMatch,v={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(I=lk.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=lk.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=lk.applyBankRule,v={actionShortcutResourceId:B,businessTransactionResourceIds:[c]});break}default:break}let x=I?vwr(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),N=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,z=I!==lk.withPayments||S,Y=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:Y,alternativeCount:d.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return o}function wwr(t,e,r,n){return{bankStatementEntryResourceId:t.bankStatementEntryResourceId,confidenceTier:t.confidenceTier,recommendationType:t.recommendationType,recommendedTool:t.recommendedTool,execute:t.execute,...n?{bankLine:e}:{},match:r}}async function _wr(t,e,r,n){let i=e.matchedTransactionResourceId,o=e.matchedTransactionCount;if(!i)return e.matchAmount!==void 0?{type:"transaction",amount:e.matchAmount,count:o}:null;let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let a of s)try{let{data:c}=a==="bill"?await Qo(t,i):await $o(t,i);return{type:a,reference:c.reference,amount:e.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${ppe(c)}`)}return{type:"transaction",amount:e.matchAmount,count:o,resourceId:i}}async function Vot(t,e,r){let n=r.filter(c=>c.recommendedTool&&!c.autoCommitEligible).slice(0,zot);if(n.length===0)return{items:[]};let i=new Map,o=[],s=!1;if(e)try{let c=n.map(f=>f.bankStatementEntryResourceId).filter(Boolean),u=await hC(t,e,{filter:{resourceId:{in:c}},limit:zot}),d=Array.isArray(u)?u:u?.data??[];for(let f of d)i.set(f.resourceId,f);s=!0}catch(c){o.push(`bank-line detail: ${ppe(c)}`)}else o.push("bank-line detail: no bankAccountResourceId supplied, so the bank-records lookup was skipped \u2014 re-call with it to get the bank line");return{items:await Promise.all(n.map(async c=>{let u=i.get(c.bankStatementEntryResourceId),d=u?{valueDate:u.valueDate,netAmount:u.netAmount,currencyCode:u.currencyCode,currencySymbol:u.currencySymbol,description:u.description,counterparty:u.extContactName}:null;return wwr(c,d,await _wr(t,c,d?.netAmount,o),s)})),...o.length?{partialFailures:o}:{}}}async function P3(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function M3(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function U3(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function $3(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function q3(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function j3(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function Y3(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function H3(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function z3(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function G3(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function J3(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}async function V3(t,e){return t.post("/api/v1/reconciliations/reset",e)}var lk,Cwr,Iwr,Hot,zot,mpe=X(()=>{"use strict";Mp();F3();dr();Ud();En();bg();lk={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},Cwr=.9,Iwr=.95,Hot=.7;zot=25});function Vs(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 _o(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),o={valueDate:Ape(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=Ape(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=Ape(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 Ape(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 Vo(t,e,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Vs(t,e,n),a=_o(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 ba,sl,lo,ru,Wot=X(()=>{"use strict";ba=[{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}],sl=[...ba],lo=ba.filter(t=>t.field!=="dueDate"),ru=[{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 dd(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=vc(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),e.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=e.taxProfile),o})}return r}function W3(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=GE(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),o})}return r}var Zot=X(()=>{"use strict";RA()});var gpe=X(()=>{"use strict";Wot();RA();Zot()});var uk,nu,Xot=X(()=>{"use strict";uk="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",nu="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function Epe(t){return Dwr.get(t)}function Kot(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!ype.has(o));return n.length===0?[]:xi.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 xi,ype,Dwr,fd=X(()=>{"use strict";xi=[{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. Next document reference number (numbering series) for invoices, bills, credit notes, quotes, orders and journals.",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"]}],ype=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"]),Dwr=new Map(xi.flatMap(t=>t.groups.map(e=>[e,t.name])))});function u0(t){let e=new Set,r=[];for(let n of t)for(let i of iu(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function dk(){return xi.map(t=>{let e=u0(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 Swr(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 Wy(t,e=!1){let r=Bm(void 0).length,n=xi.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:Swr(t,i,r)}:{},map:dk(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var Z3=X(()=>{"use strict";fd();pd()});function X3(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=X3(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=X3(i);e.properties=r,t.required?.length&&(e.required=[...t.required])}return e}function Yf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=X3(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function Zy(t){return{name:t.name,description:t.description,input_schema:Yf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var d0=X(()=>{"use strict"});function fk(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 K3(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&fk(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function xwr(t){return t.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Twr(t){let e=xwr(t);return!e||Rwr.has(e)?!0:e.split(" ").filter(n=>n.length>=2&&!ype.has(n)).length===0}function eG(t){if(Twr(t)){let{next:i,...o}=Wy();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=Kot(t,5);if(e.length===0){let{operations:i,namespaces:o}=Wy();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=>iu(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(`
|
|
675
|
+
`)}catch{}},Mfe={info:d8,warn:d8,error:uot,debug:d8,trace:d8,fatal:uot,child:C0r,level:"error"},I0r=Mfe});import{createHash as v0r}from"node:crypto";function O0r(t){if(!t||!t.trim())return[null,"directive_required"];let e=t.normalize("NFKC").trim();return e.length>300?[null,"directive_too_long"]:pot.some(r=>e.includes(r))?[null,"directive_invalid"]:fot.test(e)?[null,"directive_invalid"]:x0r.test(e)?[null,"directive_contains_url"]:T0r.test(e)?[null,"directive_contains_email"]:[e,null]}function F0r(t){if(t==null)return[null,null];let e=t.normalize("NFKC").trim();return e?e.length>B0r?[null,"match_condition_too_long"]:pot.some(r=>e.includes(r))?[null,"match_condition_invalid"]:fot.test(e)?[null,"match_condition_invalid"]:[e,null]:[null,"match_condition_invalid"]}function Q0r(t){return t==null?[null,null]:Number.isInteger(t)?t<k0r||t>N0r?[null,"invalid_importance"]:[t,null]:[null,"invalid_importance"]}function L0r(t,e,r,n,i,o,s,a){if(t)return v0r("sha256").update(`${t}:${e}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function P0r(t){Promise.resolve().then(()=>($fe(),Ufe)).then(({log:e})=>e.info(t,"memory_tool.call")).catch(()=>{})}async function got(t,e,r){let n=e.action,i=e.category,o=S0r[e.scope??"this_org"]??"ORG_USER",s=typeof e.key=="string"?e.key.trim():"",a=null,c=d=>(P0r({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=lot(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>w0r||!R0r.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[C,E]=O0r(e.directive);if(E)return u(E);p=C;let[I,v]=Q0r(e.importance);if(v)return u(v);h=I}let[m,A]=F0r(e.match_condition);if(A)return u(A);if(a=m?2:1,d.writes>=_0r)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,D0r));let E=L0r(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 qfe(()=>aot(t.client,I)),y.ok&&(d.remembered=!0)}else if(n==="forget"){let C={category:i,key:s,scope:o};y=await qfe(()=>Qfe(t.client,C))}else{let C={forgetAll:!0};y=await qfe(()=>Qfe(t.client,C))}return c(y)}catch{return c({ok:!1,reason:"internal_error"})}}async function qfe(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 Wi?e.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${e.status}`}:{ok:!1,reason:"network_error"}}}var fot,pot,w0r,_0r,D0r,hot,mot,Aot,S0r,R0r,x0r,T0r,B0r,k0r,N0r,yot=X(()=>{"use strict";cot();Na();Pfe();Pfe();fot=/[\x00-\x1f\x7f]/,pot=["{{","}}","```","<",">"],w0r=120,_0r=3,D0r=140,hot=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling"],mot=["set","forget","forget_all"],Aot=["this_org","all_orgs"],S0r={this_org:"ORG_USER",all_orgs:"USER"},R0r=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,x0r=/https?:\/\//i,T0r=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,B0r=255,k0r=0,N0r=100});async function f8(t,e){return t.list("/api/v1/organization-users",e)}async function p8(t,e){return t.search("/api/v1/organization-users/search",e)}async function i0(t,e){return t.post("/api/v1/organization-users/invite",e)}async function h8(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function m8(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var jfe=X(()=>{"use strict"});async function A8(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 g8(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function y8(t,e){return t.get(`/api/v1/payments/${e}`)}async function E8(t,e,r){return t.put(`/api/v1/payments/${e}`,{...r,currency:Sr(r.currency)})}async function b8(t,e){await t.delete(`/api/v1/payments/${e}`)}function C8(t,e){return(r,n)=>r.post(`/api/v1/${t}/${e}`,{...n,transactions:n.transactions.map(i=>({...i,currency:Sr(i.currency)}))})}var Tin,Bin,kin,Nin,Yfe=X(()=>{"use strict";dr();Tin=C8("sales","bulk-payments"),Bin=C8("sales","batch-payments"),kin=C8("purchases","bulk-payments"),Nin=C8("purchases","batch-payments")});async function I8(t,e,r={}){let n=M0r.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`,i=await t.post(n,r),o=i?.data,s=Array.isArray(o)?{...i,data:o[0],...o.length>1?{files:o}:{}}:i,a=s?.data?.fileType,c=s?.data?.fileUrl,d=typeof a=="string"?a.toUpperCase()==="PDF":typeof c=="string"&&(f=>{try{return/\.pdf$/i.test(new URL(f).pathname)}catch{return!1}})(c);return r.outputFormat==="PDF"&&(typeof c=="string"||typeof a=="string")&&!d?{...s,formatDowngraded:`PDF was requested but ${e} returned a non-PDF file. This export type does not produce PDF; re-request as XLSX, or use one of: ${[...Hfe].join(", ")}.`}:s}var M0r,Hfe,zfe=X(()=>{"use strict";M0r=new Set(["statement-of-account-export"]),Hfe=new Set(["trial-balance","balance-sheet","profit-and-loss","cashflow","cash-balance","ar-report","ap-report","tax-ledger","equity-movement","bank-closing-balance","fixed-assets-register"])});import{createHash as U0r}from"node:crypto";import{writeFile as $0r,mkdir as q0r}from"node:fs/promises";import{dirname as j0r,isAbsolute as Y0r,join as H0r}from"node:path";async function v8(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function ZB(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 o0(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function Gfe(t){return U0r("sha256").update(t).digest("hex").slice(0,16)}async function w8(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Gfe(e),o=await ZB(t,e,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(c.downloadUrl||(c=(await o0(t,s)).data);(c.status==="PENDING"||c.status==="RUNNING")&&!(Date.now()>=a);)await new Promise(f=>setTimeout(f,2e3)),c=(await o0(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&&!Y0r(r.outPath))throw new at(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??H0r(f,"Downloads",`pseudo-sql-${s}.csv`);return await q0r(j0r(p),{recursive:!0}),await $0r(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}}}function _8(t,e){let{agentSkillsDoc:r,...n}=t,i=e?.trim();if(!i)return n;let o=i.toLowerCase(),s=n.tables.filter(c=>c.name?.toLowerCase()===o);if(s.length===0)throw new at(`pseudo-sql: no table named "${i}". Available: ${n.tables.map(c=>c.name).join(", ")}`);let a=n.joins.filter(c=>c.leftTable?.toLowerCase()===o||c.rightTable?.toLowerCase()===o);return{...n,tables:s,joins:a,tableCount:s.length,joinCount:a.length,scopedTo:i}}async function s0(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 Jfe=X(()=>{"use strict";dr()});async function D8(t){return t.get("/api/v1/capsule-recipes")}async function S8(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function R8(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function x8(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function T8(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function Ea(t){if(!t||typeof t!="object")throw new at("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(!OD(e.recipeName))throw new at("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 at("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 at("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 at(`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 at("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 at(`capsuleRecipe.templateOverrides[${s}] must be an object {slotKey, template?}.`);let a=o;if(!OD(a.slotKey))throw new at(`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 at(`capsuleRecipe.templateOverrides[${s}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new at(`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 at(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new at(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var Vfe=X(()=>{"use strict";dr();MP()});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 k8(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 N8(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var B8,Tm=X(()=>{"use strict";B8=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function ol(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Wfe=X(()=>{"use strict"});async function O8(t,e){return t.post("/api/v1/claims/conversion/preview",e)}async function F8(t,e){if(e.idempotencyKey&&/^CONV[:-]/.test(e.idempotencyKey))throw new at('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return t.post("/api/v1/claims/conversion/commit",e)}var XB,Zfe=X(()=>{"use strict";dr();XB=["POST","POST_AND_RECORD"]});async function Q8(t,e){if(!(e.amount>0))throw new at("amount must be greater than 0.");return t.post("/api/v1/claims/payouts/record",e)}async function L8(t,e){return t.search("/api/v1/employees/payouts/search",e)}var Eot,Xfe=X(()=>{"use strict";dr();Eot=["REIMBURSEMENT","ADVANCE"]});function bot(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 Cot=X(()=>{"use strict"});import{randomUUID as z0r}from"node:crypto";import{rmSync as G0r}from"node:fs";function epe(t){for(let e of t.tempDirs??[])try{G0r(e,{recursive:!0,force:!0})}catch{}}function vot(t){for(let[e,r]of Jy)t-r.createdAt>Iot&&(epe(r.plan),Jy.delete(e))}function V0r(){Kfe||(Kfe=setInterval(()=>vot(Date.now()),J0r),Kfe.unref?.())}function wot(t,e){let r=Date.now();vot(r),V0r();let n=`dc_${z0r()}`;return Jy.set(n,{plan:t,createdAt:r,ownerKey:e}),n}function _ot(t,e){let r=Jy.get(t);return!r||r.ownerKey!==e?null:Date.now()-r.createdAt>Iot?(epe(r.plan),Jy.delete(t),null):r.plan}function Dot(t,e){let r=Jy.get(t);!r||r.ownerKey!==e||(epe(r.plan),Jy.delete(t))}var Iot,J0r,Jy,Kfe,Sot=X(()=>{"use strict";Iot=1800*1e3,J0r=300*1e3,Jy=new Map});function W0r(t){if(!t||typeof t!="object")return;let e=t;return e.validFiles?.[0]?.workflowResourceId??e.workflowResourceId}function Z0r(t,e){let r=new Set(e);return{...t,folders:t.folders.map(n=>({...n,files:n.files.filter(i=>DQ(i.documentType)&&r.has(i.documentType))}))}}async function Rot(t){let{plan:e,client:r,bankAccountId:n,documentTypes:i}=t,o=i&&i.length>0?Z0r(e,i):e;if(!n&&X0r(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 LP({plan:o,client:r,bankAccountId:n}),a=s.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?W0r(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 X0r(t){return t.folders.some(e=>e.files.some(r=>r.documentType==="BANK_STATEMENT"))}var xot=X(()=>{"use strict";mZ();Ep()});async function ud(t,e,r){if(!e)return t;let n=K0r(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 K0r(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 jf(t,e){return!e||!t||typeof t!="object"?t:{_fx:e,...t}}var Tot=X(()=>{"use strict"});async function P8(t,e){return t.list("/api/v1/bank-rules",e)}async function KB(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 M8(t,e){return t.search("/api/v1/bank-rules/search",e)}async function U8(t,e){return t.post("/api/v1/bank-rules",e)}async function $8(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function q8(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var tpe=X(()=>{"use strict"});async function j8(t,e){return t.list("/api/v1/fixed-assets",e)}async function ek(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function Y8(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function H8(t,e){return t.post("/api/v1/fixed-assets",e)}async function z8(t,e,r){let i=(await ek(t,e)).data,o={};for(let s of ewr){let a=i[s];if(a==null)continue;let c=twr.has(s)?Il(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 G8(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function J8(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function tk(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function V8(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function W8(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function Z8(t,e){return Ao(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var ewr,twr,X8=X(()=>{"use strict";En();JE();ewr=["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"],twr=new Set(["purchaseDate","depreciationStartDate"])});async function K8(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function rk(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function e3(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function t3(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 rk(t,e);if(i){let a=Il(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 r3(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function n3(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 i3(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var rpe=X(()=>{"use strict";JE()});async function o3(t,e){return t.list("/api/v1/contact-groups",e)}async function s3(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function a3(t,e){return t.search("/api/v1/contact-groups/search",e)}async function c3(t,e){return t.post("/api/v1/contact-groups",e)}async function l3(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,HE(r,m6))}async function u3(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var npe=X(()=>{"use strict";En()});async function d3(t,e){return t.list("/api/v1/inventory-items",e)}async function f3(t,e){return t.post("/api/v1/inventory-items",{blockInsufficientDeductions:!1,...e})}async function p3(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var ipe=X(()=>{"use strict"});async function h3(t,e){return t.list("/api/v1/custom-fields",e)}async function nk(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function m3(t,e){return t.search("/api/v1/custom-fields/search",e)}async function A3(t,e){return t.post("/api/v1/custom-fields",e)}function nwr(t){return t!==void 0&&rwr.every(e=>t[e]!==void 0)}function iwr(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 owr(t){return[t.applyToSales,t.applyToPurchase,t.applyToSaleCreditNote,t.applyToPurchaseCreditNote,t.applyToPayment,t.applyToCreditNote].some(e=>e==="PRINT")}async function g3(t,e,r){let n={...r};if(n.name===void 0||n.description===void 0||n.printOnDocuments===void 0||!nwr(n.appliesTo)){let i=await nk(t,e);n.name??=i.data.customFieldName??i.data.name,n.description??=i.data.description,n.printOnDocuments??=i.data.printOnDocuments??owr(i.data),n.appliesTo={...iwr(i.data),...r.appliesTo}}return t.put(`/api/v1/custom-fields/${e}`,n)}async function y3(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var rwr,ope=X(()=>{"use strict";rwr=["invoices","bills","customerCredits","supplierCredits","payments"]});function Bot(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function ik(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return Bot(n)}async function ok(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return Bot(n)}var swr,awr,cwr,a0,spe=X(()=>{"use strict";swr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],awr=["journals","cash-entries"],cwr=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],a0=[...swr,...awr,...cwr]});async function E3(t,e){return t.list("/api/v1/nano-classifiers",e)}async function b3(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function C3(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function sk(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function ak(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,{...r,resourceId:e})}async function I3(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var ape=X(()=>{"use strict"});async function v3(t,e){return t.post("/api/v1/export-records",e)}async function w3(t,e){return t.post("/api/v1/export-records/preview",e)}async function _3(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var cpe=X(()=>{"use strict"});async function ck(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var lpe=X(()=>{"use strict"});function D3(t,e){if(!e.has(t))throw new at(`unknown entity "${t}" \u2014 expected one of ${[...e].join(", ")}`)}function Oot(t,e,r,n=!1){if(!Array.isArray(t))throw new at(`${r}: resourceIds must be an array, not a ${typeof t}`);if(t.length===0)throw new at(`${r}: resourceIds must contain at least 1 id`);if(n&&new Set(t).size!==t.length)throw new at(`${r}: resourceIds contains duplicates; the API rejects the whole batch`);if(t.length>e)throw new at(`${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.`)}function Fot(t){if(!Array.isArray(t)||t.length===0)return{state:"unconfirmed"};let e=t.find(r=>r.isSuccess===!1||r.isSuccess===void 0&&!!(r.failureReason||r.errorCode));return e?{state:"refused",reason:e.failureReason||e.errorCode||"refused without a stated reason"}:{state:"approved"}}async function S3(t,e,r){return D3(e,kot),us(r,"resourceId","Pass the document resourceId."),t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/approve`)}async function R3(t,e,r){return D3(e,kot),Oot(r,lwr,"bulk approve",!0),r.forEach(n=>us(n,"resourceIds[]","Every id must be a document resourceId.")),t.post(`/api/v1/${encodeURIComponent(e)}/bulk-approve`,{resourceIds:r})}async function x3(t,e,r,n){D3(e,Not),us(r,"resourceId","Pass the document resourceId."),Qot(n);let i=await t.post(`/api/v1/${encodeURIComponent(e)}/${encodeURIComponent(r)}/request-changes`,{message:n});return{data:{records:fwr(i)}}}async function T3(t,e,r,n){return D3(e,Not),Qot(n),Oot(r,uwr,"bulk request changes"),r.forEach(i=>us(i,"resourceIds[]","Every id must be a document resourceId.")),t.post(dwr(e),{resourceIds:r,message:n})}function dwr(t){return t==="claims"?"/api/v1/claims/bulk/request-changes":`/api/v1/${encodeURIComponent(t)}/bulk-request-changes`}function Qot(t){if(!t||t.trim().length===0)throw new at("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 fwr(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 Vy,c0,kot,Not,lwr,uwr,upe=X(()=>{"use strict";dr();Vy=["invoices","bills","customer-credit-notes","supplier-credit-notes"],c0=[...Vy,"purchase-orders","purchase-requests","sale-orders","sale-quotes","claims"],kot=new Set(Vy),Not=new Set(c0);lwr=100,uwr=500});function pwr(t,e,r){let n=Math.random().toString(36).slice(2,10);return`restore:${t}:${Lot(e)}:${Lot(r)}:${n}`}function Lot(t){return t.replace(/[^A-Za-z0-9._:-]/g,"").slice(0,64)}function dpe(t){if(!Pot.has(t))throw new at(`unknown entity "${t}" \u2014 expected one of ${[...Pot].join(", ")}`)}async function Mot(t,e,r){return dpe(e),us(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}`)}async function Uot(t,e,r,n){return dpe(e),us(r,"resourceId","Pass the document resourceId."),t.get(`/api/v1/rollback/${encodeURIComponent(e)}/versions/${encodeURIComponent(r)}/${encodeURIComponent(n)}`)}async function $ot(t,e,r,n,i){if(dpe(e),us(r,"resourceId","Pass the document resourceId."),n.trim().toUpperCase()==="CREATED")throw new at('restoreDocumentVersion: "CREATED" is a grouping node in the version history, not a restorable snapshot. Upstream DELETES the document for it and still returns 200. Pick a numeric version id from the history instead, and read it with getDocumentVersion first to confirm it carries document fields.');return t.post(`/api/v1/rollback/${encodeURIComponent(e)}/restore`,{resourceId:r,version:n},{headers:{"Idempotency-Key":i??pwr(e,r,n)}})}async function qot(t,e,r){return t.get(`/api/v1/organization/currencies/${encodeURIComponent(e)}/effective-rate`,r?{date:r}:void 0)}var Pot,jot=X(()=>{"use strict";dr();Pot=new Set(["journals","purchases","sales","purchase-credit-notes","sale-credit-notes"])});function l0(t){Qt(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new at(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(!OD(n.btResourceId))throw new at(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!hwr.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 at(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function B3(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:Awr(r.data)}}function mwr(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 Awr(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(mwr),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function k3(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function N3(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var hwr,fpe=X(()=>{"use strict";dr();MP();En();hwr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function gwr(t){switch(t){case 401:return"Invalid or missing API key. Run `clio auth add` or set JAZ_API_KEY.";case 402:return"Not included in this organization's plan. Retrying will not help \u2014 a plan change is needed.";case 403:return"Insufficient permissions for this operation.";case 404:return"Resource not found \u2014 check the resourceId. Use a search/list tool to look it up.";case 409:return"Conflict \u2014 resource may have been modified. Re-fetch and retry.";case 422:return"Validation error \u2014 check field values against the tool description.";case 429:return"Rate limited \u2014 wait a moment and retry.";default:return""}}function Ewr(t){let r=t?.error?.error_type;return typeof r=="string"&&r.trim()!==""?r.trim():void 0}function bwr(t,e){if(t!==ywr)return;let r=Ewr(e);if(r)return Yot.get(r)??Yot.get(r.replace(/_ERROR$/,""))}function ppe(t,e=300){let r=t instanceof Error?t.message:typeof t=="string"?t:(()=>{try{return JSON.stringify(t)??"unknown error"}catch{return"unknown error"}})();return r.length>e?`${r.slice(0,e-3)}...`:r}function O3(t,e={}){let r=e.readOnly===!1&&FD()?NFe:"";if(t instanceof Wi){let s=[bwr(t.status,t.body)??gwr(t.status),r].filter(Boolean).join(" "),a={error:t.message,status:t.status,endpoint:t.endpoint,...s?{hint:s}:{}};if(e.toolName&&e.input){let c=Q3(t,e.toolName,e.input);c&&(a.repair=c)}return a}let n=t instanceof Error?t.message:String(t),i=t instanceof Ki;return{error:n,...i?{kind:"validation",retriable:!1}:{},...r?{hint:r}:{}}}var ywr,Yot,F3=X(()=>{"use strict";Na();Pd();L3();UP();ywr=422,Yot=new Map([["PSEUDOSQL_DISABLED","The SQL query engine is switched off on the reporting service, so the query text is not what was rejected. Rewriting the SQL will not help \u2014 preview and export return this until the engine is re-enabled, which is a platform deployment change: it is not an organization setting, not a plan entitlement, and nothing the caller or an organization admin can turn on. Note the catalog is served from a static in-process snapshot and stays readable while the engine is off, so get_pseudo_sql_schema still lists tables and joins that cannot currently be queried; a table appearing there is not evidence the engine is on. Use the report tools instead."],["INVALID_BUSINESS_TRANSACTION_TYPE","Despite the name, the bank entry's DIRECTION is what was rejected, not its type. reconcile_invoice_receipt needs a money-IN entry and reconcile_bill_receipt needs money-OUT. `bank add-records` creates money-in from a POSITIVE amount and money-out from a NEGATIVE one; on an existing entry, `bank records` reports a signed netAmount. Check the entry before retrying \u2014 the same call will keep failing with this code."]])});function Got(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new at("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function hpe(t,e){if(!t||typeof t!="object")throw new at(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new at(`${e}.lineItems array is empty.`);if(n.length>500)throw new at(`max 500 ${e}.lineItems per call.`);Cl([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&Cl([i],["valueDate"])}function vwr(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>=Cwr?"high":r>=Hot?"medium":"low";if(n!==void 0){if(n>=Iwr)return"high";if(n>=Hot)return"medium"}return"low"}function Jot(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=lk.magicMatch,v={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(I=lk.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=lk.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=lk.applyBankRule,v={actionShortcutResourceId:B,businessTransactionResourceIds:[c]});break}default:break}let x=I?vwr(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),N=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,z=I!==lk.withPayments||S,Y=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:Y,alternativeCount:d.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return o}function wwr(t,e,r,n){return{bankStatementEntryResourceId:t.bankStatementEntryResourceId,confidenceTier:t.confidenceTier,recommendationType:t.recommendationType,recommendedTool:t.recommendedTool,execute:t.execute,...n?{bankLine:e}:{},match:r}}async function _wr(t,e,r,n){let i=e.matchedTransactionResourceId,o=e.matchedTransactionCount;if(!i)return e.matchAmount!==void 0?{type:"transaction",amount:e.matchAmount,count:o}:null;let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let a of s)try{let{data:c}=a==="bill"?await Qo(t,i):await $o(t,i);return{type:a,reference:c.reference,amount:e.matchAmount??c.totalAmount,documentTotalAmount:c.totalAmount,count:o,resourceId:i}}catch(c){c.status!==404&&n.push(`matched document (${a}): ${ppe(c)}`)}return{type:"transaction",amount:e.matchAmount,count:o,resourceId:i}}async function Vot(t,e,r){let n=r.filter(c=>c.recommendedTool&&!c.autoCommitEligible).slice(0,zot);if(n.length===0)return{items:[]};let i=new Map,o=[],s=!1;if(e)try{let c=n.map(f=>f.bankStatementEntryResourceId).filter(Boolean),u=await hC(t,e,{filter:{resourceId:{in:c}},limit:zot}),d=Array.isArray(u)?u:u?.data??[];for(let f of d)i.set(f.resourceId,f);s=!0}catch(c){o.push(`bank-line detail: ${ppe(c)}`)}else o.push("bank-line detail: no bankAccountResourceId supplied, so the bank-records lookup was skipped \u2014 re-call with it to get the bank line");return{items:await Promise.all(n.map(async c=>{let u=i.get(c.bankStatementEntryResourceId),d=u?{valueDate:u.valueDate,netAmount:u.netAmount,currencyCode:u.currencyCode,currencySymbol:u.currencySymbol,description:u.description,counterparty:u.extContactName}:null;return wwr(c,d,await _wr(t,c,d?.netAmount,o),s)})),...o.length?{partialFailures:o}:{}}}async function P3(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function M3(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function U3(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function $3(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function q3(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function j3(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function Y3(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function H3(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function z3(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function G3(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function J3(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}async function V3(t,e){return t.post("/api/v1/reconciliations/reset",e)}var lk,Cwr,Iwr,Hot,zot,mpe=X(()=>{"use strict";Mp();F3();dr();Ud();En();bg();lk={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},Cwr=.9,Iwr=.95,Hot=.7;zot=25});function Vs(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 _o(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),o={valueDate:Ape(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=Ape(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=Ape(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 Ape(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 Vo(t,e,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Vs(t,e,n),a=_o(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 ba,sl,lo,ru,Wot=X(()=>{"use strict";ba=[{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}],sl=[...ba],lo=ba.filter(t=>t.field!=="dueDate"),ru=[{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 dd(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=vc(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),e.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=e.taxProfile),o})}return r}function W3(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=GE(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),o})}return r}var Zot=X(()=>{"use strict";RA()});var gpe=X(()=>{"use strict";Wot();RA();Zot()});var uk,nu,Xot=X(()=>{"use strict";uk="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",nu="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function Epe(t){return Dwr.get(t)}function Kot(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!ype.has(o));return n.length===0?[]:xi.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 xi,ype,Dwr,fd=X(()=>{"use strict";xi=[{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. Next document reference number (numbering series) for invoices, bills, credit notes, quotes, orders and journals.",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"]}],ype=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"]),Dwr=new Map(xi.flatMap(t=>t.groups.map(e=>[e,t.name])))});function u0(t){let e=new Set,r=[];for(let n of t)for(let i of iu(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function dk(){return xi.map(t=>{let e=u0(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 Swr(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 Wy(t,e=!1){let r=Bm(void 0).length,n=xi.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:Swr(t,i,r)}:{},map:dk(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var Z3=X(()=>{"use strict";fd();pd()});function X3(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=X3(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=X3(i);e.properties=r,t.required?.length&&(e.required=[...t.required])}return e}function Yf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=X3(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function Zy(t){return{name:t.name,description:t.description,input_schema:Yf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var d0=X(()=>{"use strict"});function fk(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 K3(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&fk(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function xwr(t){return t.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Twr(t){let e=xwr(t);return!e||Rwr.has(e)?!0:e.split(" ").filter(n=>n.length>=2&&!ype.has(n)).length===0}function eG(t){if(Twr(t)){let{next:i,...o}=Wy();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=Kot(t,5);if(e.length===0){let{operations:i,namespaces:o}=Wy();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=>iu(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(`
|
|
676
676
|
`)[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 est(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=tG(n);if(!i){r.push(n);continue}e.push({...Zy(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&fk(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 Rwr,Bwr,kwr,Nwr,Hf,km,f0=X(()=>{"use strict";fd();Z3();pd();d0();Rwr=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"]);Bwr={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:Yf({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};kwr={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:Yf({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},Nwr={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:Yf({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"])},Hf={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:Yf({},[])},km=[Bwr,kwr,Nwr]});function Lwr(t){if(!(ou in t))return{cleanedInput:t};let{[ou]:e,...r}=t;return{jotText:typeof e=="string"&&e.trim()!==""?e.trim():void 0,cleanedInput:r}}function nst(t,e){if(t.params[ou])return{cleanedInput:e};let{jotText:r,cleanedInput:n}=Lwr(e);return t.readOnly?{cleanedInput:n}:{jotText:r,cleanedInput:n}}function Pwr(t){let e=Fwr.exec(t);return e?{kind:e[1],call:t.slice(e[0].length)||t}:{call:t}}function Uwr(t){let e=t.toLowerCase();for(let[r,n]of Mwr)if(n.test(e))return r}function $wr(t,e){let r=Uwr(t),n=[],i=new Set,o=(s,a)=>{if(!(n.length>=tst||a>Qwr||!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>=tst)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 rG(t,e,r,n){let{kind:i,call:o}=Pwr(r),s=$wr(e,n),a={...i?{kind:i}:{},tier:"MEDIUM",call:o,frame:`tool:${e}`,...s.length?{refs:s}:{},writePath:"PIGGYBACK"};n0(t,[a]).catch(c=>{let u=c instanceof Error?c.message:String(c);Promise.resolve().then(()=>($fe(),Ufe)).then(({log:d})=>d.error({tool:e,error:u},"Piggyback jot write failed")).catch(()=>process.stderr.write(`[jots-piggyback] jot write failed (${e}): ${u}
|
|
677
677
|
`))})}var ou,rst,Owr,Fwr,tst,Qwr,Mwr,nG=X(()=>{"use strict";l8();EC();ou="jot",rst='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. '+zP,Owr=["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],Fwr=new RegExp(`^(${Owr.join("|")})\\s*:\\s*`),tst=20,Qwr=6;Mwr=[["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 ist(t){let e=new Set,r=[];for(let n of t)for(let i of iu(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function qwr(t){return t.split("_").map(e=>e&&e[0].toUpperCase()+e.slice(1)).join(" ")}function p0(t){let e=t.readOnly?"read":fk(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(`
|
|
678
678
|
`)[0]||"").trim().slice(0,140);return`- ${t.name} (${e}): ${o}${n}${i}`}function iG(t=!1){return xi.map(e=>{let r=ist(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=>fk(d)),a=r.filter(d=>d.acceptsHostFile).map(d=>d.name),c=`${e.description}
|
|
@@ -768,6 +768,7 @@ Per-type date / scope (wrong set \u2192 422 "X is required"):
|
|
|
768
768
|
- bank-closing-balance \u2192 reportDate
|
|
769
769
|
- bank-reconciliation-* \u2192 startDate + endDate + bankAccountResourceId
|
|
770
770
|
- fixed-assets-reconciliation-summary \u2192 startDate + endDate + accountResourceId (fixed-asset UUIDs; search fixed_assets first)
|
|
771
|
+
- statement-of-account-export \u2192 contactResourceId (dates optional; omitted = all-time)
|
|
771
772
|
- trial-balance, cash-balance, ar-report, ap-report \u2192 endDate
|
|
772
773
|
- other summaries (P&L, GL, sales/purchase, tax, fixed-assets-register, etc.) \u2192 startDate + endDate
|
|
773
774
|
|