jaz-clio 5.36.0 → 5.36.2
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/README.md +1 -1
- package/assets/skills/api/SKILL.md +2 -2
- package/assets/skills/cli/SKILL.md +1 -1
- package/assets/skills/conversion/SKILL.md +1 -1
- package/assets/skills/jaz-kit/SKILL.md +1 -1
- package/assets/skills/jaz-pseudo-sql/SKILL.md +1 -1
- package/assets/skills/jobs/SKILL.md +1 -1
- package/assets/skills/transaction-recipes/SKILL.md +1 -1
- package/cli.mjs +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -159,7 +159,7 @@ Runs on your machine. Calls go to the Jaz API over HTTPS. No telemetry, no data
|
|
|
159
159
|
|
|
160
160
|
## Support
|
|
161
161
|
|
|
162
|
-
[help.jaz.ai](https://help.jaz.ai) · [GitHub Issues](https://github.com/teamtinvio/jaz-ai/issues) ·
|
|
162
|
+
[help.jaz.ai](https://help.jaz.ai) · [GitHub Issues](https://github.com/teamtinvio/jaz-ai/issues) · build.with@jaz.ai
|
|
163
163
|
|
|
164
164
|
## License
|
|
165
165
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: jaz-api
|
|
3
|
-
version: 5.36.
|
|
3
|
+
version: 5.36.2
|
|
4
4
|
description: >-
|
|
5
5
|
Use this skill whenever you call, debug, or review code that touches the Jaz
|
|
6
6
|
REST API. Covers field names, response shapes, 158 production gotchas, error
|
|
@@ -419,7 +419,7 @@ Bills, invoices, and credit notes share identical mandatory field specs. Adding
|
|
|
419
419
|
- `POST /api/v1/drafts/convert-to-active` (async, jobId) → `convert_drafts_to_active`. Promotes drafts to ACTIVE. Poll `search_background_jobs` filtered by `resourceId`; on PARTIAL_SUCCESS read `data[0].errorDetails`.
|
|
420
420
|
- `POST /api/v1/drafts/submit-for-approval` (async, jobId) → `submit_drafts_for_approval`. Routes drafts into the approval workflow.
|
|
421
421
|
|
|
422
|
-
129. **Drafts lifecycle request shape (mix-friendly)** — all 3 endpoints accept the same body: `{ items: [{btResourceId, btType}] }` with `btType ∈ {SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE}`. **Max 500 items per call. ONE batch can mix any combination of types** — no need to group by btType client-side, no need to make multiple calls per entity type. **Mapping**: `SALE` → invoice, `PURCHASE` → bill, `SALE_CREDIT_NOTE` → customer credit note, `PURCHASE_CREDIT_NOTE` → supplier credit note. Journals are NOT in the enum
|
|
422
|
+
129. **Drafts lifecycle request shape (mix-friendly)** — all 3 endpoints accept the same body: `{ items: [{btResourceId, btType}] }` with `btType ∈ {SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE}`. **Max 500 items per call. ONE batch can mix any combination of types** — no need to group by btType client-side, no need to make multiple calls per entity type. **Mapping**: `SALE` → invoice, `PURCHASE` → bill, `SALE_CREDIT_NOTE` → customer credit note, `PURCHASE_CREDIT_NOTE` → supplier credit note. Journals are NOT in the enum: they have no approval state (ACTIVE | VOID | DRAFT), so they never entered this lifecycle. Promote a DRAFT journal with `bulk_update_journals` (`saveAsDraft: false`) or `update_journal` — that IS the supported path, not a workaround.
|
|
423
423
|
|
|
424
424
|
130. **Drafts lifecycle is NOT idempotent** — a second `convert_drafts_to_active` on already-ACTIVE drafts returns 422; a second `submit_drafts_for_approval` on drafts with an in-flight approval returns 422. Filter the draft list by `status: DRAFT` before submitting (the entity-specific search tools — `search_invoices`, `search_bills`, etc. — accept `status` filters). `validate_drafts` IS safe to call repeatedly (read-only, no state change).
|
|
425
425
|
|
package/cli.mjs
CHANGED
|
@@ -678,7 +678,7 @@ Unsupported type: `+t.type,"ENOTSUP");t._finish()})};Gc.prototype._stat=function
|
|
|
678
678
|
`,a),u=c!==-1?c:i.length;return i.slice(s,u).trim()}catch{return null}}function WCr(){let t=wnt(import.meta.url),e=Int(t),r=[am(e,"..","..","..","help-center-mirror"),am(e,"..","..","..","assets","skills","api","help-center-mirror"),am(e,"help-center-mirror")];for(let n of r)try{return Zue(am(n,"index.md"),"utf-8"),n}catch{}return null}var bnt,Cnt,qCr,jCr,YCr,HCr,zCr,GCr,JCr,YH,vnt,Wue,oT=X(()=>{"use strict";Vue();Hb();bnt=1.2,Cnt=.75,qCr=1.5,jCr=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"]),YCr=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"]]]);HCr=.7,zCr=3,GCr=32,JCr=5;YH=null,vnt=null;Wue=null});import{existsSync as ZCr,readFileSync as XCr}from"node:fs";import{dirname as KCr,join as Kue}from"node:path";import{fileURLToPath as evr}from"node:url";function sT(t){let e=t??ovr();if(!e)return null;if(HH&&xnt===e)return HH;try{let r=XCr(e,"utf-8");return HH=JSON.parse(r),xnt=e,HH}catch{return null}}function ovr(){let t=evr(import.meta.url),e=KCr(t),r=[Kue(e,"..","..","..","help-center-mirror","help-center-embeddings.json"),Kue(e,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),Kue(e,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(ZCr(n))return n;return null}function knt(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 Nnt(){return zH!==null?zH:(zH=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",zH||null)}async function ede(t){let e=Nnt();if(!e)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),rvr),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:tvr,input:t}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!Bnt&&(Bnt=!0,process.stderr.write(`[help-center] CLIO_HELP_CENTER_OPENAI_API_KEY rejected by OpenAI \u2014 falling back to BM25
|
|
679
679
|
`)),null)}catch{return null}}async function aT(t,e,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??nvr,c=n.minBm25??ivr;if(i==="bm25"||!e)return _y(t,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await ede(r);return m?Tnt(t,e,m,{limit:o,section:s}).filter(g=>g.score>=a):_y(t,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([ede(r),Promise.resolve(_y(t,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=Tnt(t,e,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return Ont(p,h,o)}function Tnt(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=knt(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 Ont(t,e,r){let n=new Map;for(let o=0;o<t.length;o++){let s=t[o],a=1/(Rnt+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/(Rnt+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 tde(t){return t!==null&&!!Nnt()}var tvr,rvr,Rnt,nvr,ivr,HH,xnt,zH,Bnt,GH=X(()=>{"use strict";oT();tvr="text-embedding-3-small",rvr=2e3,Rnt=60,nvr=.3,ivr=1.5,HH=null,xnt=null,zH=null,Bnt=!1});async function Fnt(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=nT();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:sT(),u=await aT(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=(Xue(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 Qnt(){let t=process.env.CLIO_HELP_CENTER_URL?.trim();return t&&t.length>0?t:svr}async function JH(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(Qnt())}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(avr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return cvr(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 cvr(t){if(typeof t!="object"||t===null)return!1;let e=t;return Array.isArray(e.results)?!0:typeof e.error=="string"}async function rde(t,e={}){return process.env.CLIO_DAEMON==="1"||iT()?Fnt(t,e):JH(t,e)}var svr,avr,Lnt=X(()=>{"use strict";oT();GH();svr="https://mcp.jaz.ai/help-center/search",avr=4e3});var nde=X(()=>{"use strict";oT();GH();Lnt();oT()});var Mnt,Pnt=X(()=>{"use strict";Mnt={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 VH(t,e){let{blueprint:r,accountMap:n,finalize:i}=e,o=!i;lvr(e);let s=await uvr(t,r.capsuleType),a=r.steps[0]?.date??new Date().toISOString().slice(0,10),c=`${r.capsuleName} (${a})`,d={resourceId:(await aA(t,{capsuleTypeResourceId:s,title:c,description:r.capsuleDescription})).data.resourceId,type:r.capsuleType,title:c},f=qnt(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 dvr(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 lvr(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)ode(f.account,r)||o.push(f.account);let s=[...new Set(o)];if(s.length>0)throw new Error(`Unmapped account(s) in --input: ${s.join(", ")}.
|
|
680
680
|
Add these to your account mapping JSON.`);let a=qnt(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 uvr(t,e){let n=(await xE(t)).data.find(o=>o.displayName.toLowerCase()===e.toLowerCase());return n?n.resourceId:(await xw(t,{displayName:e})).data.resourceId}function qnt(t){if(!t.existingTxnId)return null;let e=Mnt[t.calcType];return e?t.blueprint.steps.find(n=>e.includes(n.action))?.step??null:null}async function dvr(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 tg(t,{reference:s,valueDate:e.date,journalEntries:ide(e.lines,i),internalNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"bill":{a=(await sA(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:Unt(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"invoice":{a=(await KA(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:Unt(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"cash-in":{let{contraLines:c}=$nt(e.lines,r.bankAccountId,i);a=(await NI(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:ide(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}case"cash-out":{let{contraLines:c}=$nt(e.lines,r.bankAccountId,i);a=(await OI(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:ide(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 ide(t,e){return t.map(r=>({accountResourceId:sde(r.account,e),type:r.debit>0?"DEBIT":"CREDIT",amount:r.debit>0?r.debit:r.credit}))}function Unt(t,e){return t.filter(r=>ode(r.account,e)).map(r=>({name:r.account,quantity:1,unitPrice:r.debit>0?r.debit:r.credit,accountResourceId:sde(r.account,e)}))}function $nt(t,e,r){let n=[],i=null;for(let o of t)sde(o.account,r)===e&&!i?i=o:n.push(o);return i?{bankLine:i,contraLines:n}:{bankLine:t[0],contraLines:t.slice(1)}}function ode(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 sde(t,e){let r=ode(t,e);if(!r)throw new Error(`Unmapped account: "${t}"`);return e[r]}var ade=X(()=>{"use strict";IC();wd();eg();RH();Tw();Pnt()});async function jnt(t,e){let n=(await xp((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=GM(s,n);if(a)i[s]=a.resourceId;else{let c=lC(s,n,{threshold:.3,limit:3});o.push({name:s,candidates:c.map(u=>u.item.name)})}}return{mapping:i,failures:o}}async function Ynt(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 Vf(t,e)).data;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}let n=e.trim(),o=(await fc(t,{filter:{billingName:{contains:n}},limit:50})).data;if(o.length===0&&(o=(await Jf(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=JM(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 Hnt(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 qb(t,e);return{resourceId:i.data.resourceId,displayName:i.data.name}}let n=await PA(t,e);return{resourceId:n.resourceId,displayName:n.name}}var znt=X(()=>{"use strict";SE();Wf();yp();NM();QZ();LZ();FL()});async function cm(t,e){await t.delete(`/api/v1/cash-entries/${e}`)}async function lm(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}var cT=X(()=>{"use strict"});async function WH(t,e){return t.post("/api/v1/transfer-trial-balance",{...e,currency:jr(e.currency),taxCurrency:jr(e.taxCurrency)})}var cde=X(()=>{"use strict";Pn()});async function ZH(t,e){return t.list("/api/v1/organization/bookmarks",e)}async function XH(t,e){return t.get(`/api/v1/organization/bookmarks/${e}`)}async function lT(t,e){return t.post("/api/v1/organization/bookmarks",{items:e})}async function KH(t,e,r){return t.put(`/api/v1/organization/bookmarks/${e}`,r)}var lde=X(()=>{"use strict"});function fvr(t){let{refs:e,...r}=t;return e?{...r,refs:e.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function QI(t,e){return t.post("/api/v1/jots",{entries:e.map(fvr)})}async function ez(t,e){return t.post("/api/v1/jots/search",e)}async function Gnt(t,e,r){return t.post(`/api/v1/jots/${e}/disposition`,r)}var tz=X(()=>{"use strict"});async function Jnt(t,e){return t.post("/api/v1/agents/memories",e)}async function ude(t,e){return t.post("/api/v1/agents/memories/forget",e)}var Vnt=X(()=>{"use strict"});function rz(){return process.env.ENABLE_MEMORY==="true"}function dde(){return process.env.ENABLE_MEMORY_CHAT==="true"}function Wnt(t){return!rz()||!t||!t.progressive?"memory_disabled":t.isInboxOwner?null:"not_owner"}var fde=X(()=>{"use strict"});var hde={};gs(hde,{default:()=>hvr,log:()=>pde});var nz,pvr,Znt,pde,hvr,mde=X(()=>{"use strict";nz=()=>{},pvr=()=>pde,Znt=(...t)=>{try{process.stderr.write(t.map(String).join(" ")+`
|
|
681
|
-
`)}catch{}},pde={info:nz,warn:nz,error:Znt,debug:nz,trace:nz,fatal:Znt,child:pvr,level:"error"},hvr=pde});import{createHash as mvr}from"node:crypto";function Svr(t){if(!t||!t.trim())return[null,"directive_required"];let e=t.normalize("NFKC").trim();return e.length>300?[null,"directive_too_long"]:gvr.some(r=>e.includes(r))?[null,"directive_invalid"]:Avr.test(e)?[null,"directive_invalid"]:Ivr.test(e)?[null,"directive_contains_url"]:wvr.test(e)?[null,"directive_contains_email"]:[e,null]}function Rvr(t){return t==null?[null,null]:Number.isInteger(t)?t<_vr||t>Dvr?[null,"invalid_importance"]:[t,null]:[null,"invalid_importance"]}function xvr(t,e,r,n,i,o,s,a){if(t)return mvr("sha256").update(`${t}:${e}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function Bvr(t){Promise.resolve().then(()=>(mde(),hde)).then(({log:e})=>e.info(t,"memory_tool.call")).catch(()=>{})}async function nit(t,e,r){let n=e.action,i=e.category,o=Cvr[e.scope??"this_org"]??"ORG_USER",s=typeof e.key=="string"?e.key.trim():"",a=null,c=d=>(Bvr({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=Wnt(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>yvr||!vvr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[g,y]=Svr(e.directive);if(y)return u(y);p=g;let[C,E]=Rvr(e.importance);if(E)return u(E);h=C}if(a=1,e.key_type!==void 0&&e.key_type!==null){if(!e.match_value||!e.match_value.trim())return u("match_value_required");a=2}else if(e.match_value)return u("key_type_required");if(d.writes>=Evr)return u("write_limit");d.writes+=1;let m=d.gtid||"",A;if(n==="set"){let g={gtid:m};d.quote&&(g.quote=d.quote.slice(0,bvr));let y=xvr(m,n,o,i,s,p,e.confirms_key,e.replaces_key),C={scope:o,tier:a,category:i,key:s,...e.key_type?{keyType:e.key_type}:{},...e.match_value?{matchValue:e.match_value}:{},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:g,...y?{idempotencyKey:y}:{},...h!==null?{importance:h}:{}};A=await Ade(()=>Jnt(t.client,C)),A.ok&&(d.remembered=!0)}else if(n==="forget"){let g={category:i,key:s,scope:o};A=await Ade(()=>ude(t.client,g))}else{let g={forgetAll:!0};A=await Ade(()=>ude(t.client,g))}return c(A)}catch{return c({ok:!1,reason:"internal_error"})}}async function Ade(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 ao?e.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${e.status}`}:{ok:!1,reason:"network_error"}}}var Avr,gvr,yvr,Evr,bvr,Knt,eit,tit,rit,Cvr,vvr,Ivr,wvr,_vr,Dvr,iit=X(()=>{"use strict";Vnt();uc();fde();fde();Avr=/[\x00-\x1f\x7f]/,gvr=["{{","}}","```","<",">"],yvr=120,Evr=3,bvr=140,Knt=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling","autonomy-grant"],eit=["set","forget","forget_all"],tit=["this_org","all_orgs"],rit=["SENDER_ADDRESS","SENDER_DOMAIN","VENDOR_NAME","SUBJECT_TOKEN"],Cvr={this_org:"ORG_USER",all_orgs:"USER"},vvr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Ivr=/https?:\/\//i,wvr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,_vr=0,Dvr=100});async function iz(t,e){return t.list("/api/v1/organization-users",e)}async function oz(t,e){return t.search("/api/v1/organization-users/search",e)}async function LI(t,e){return t.post("/api/v1/organization-users/invite",e)}async function sz(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function az(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var gde=X(()=>{"use strict"});async function cz(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 uT(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function lz(t,e){return t.get(`/api/v1/payments/${e}`)}async function uz(t,e,r){return t.put(`/api/v1/payments/${e}`,{...r,currency:jr(r.currency)})}async function dz(t,e){await t.delete(`/api/v1/payments/${e}`)}var yde=X(()=>{"use strict";Pn()});async function fz(t,e,r={}){let n=Tvr.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`;return t.post(n,r)}var Tvr,Ede=X(()=>{"use strict";Tvr=new Set(["statement-of-account-export"])});import{createHash as kvr}from"node:crypto";import{writeFile as Nvr,mkdir as Ovr}from"node:fs/promises";import{dirname as Fvr,isAbsolute as Qvr,join as Lvr}from"node:path";async function oit(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function bde(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 Cde(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function Mvr(t){return kvr("sha256").update(t).digest("hex").slice(0,16)}async function sit(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Mvr(e),o=await bde(t,e,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(;Date.now()<a&&!(c.status==="COMPLETED"||c.status==="FAILED"||c.status==="EXPIRED"||(await new Promise(p=>setTimeout(p,2e3)),Date.now()>=a));)c=(await Cde(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&&!Qvr(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??Lvr(f,"Downloads",`pseudo-sql-${s}.csv`);return await Ovr(Fvr(p),{recursive:!0}),await Nvr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}async function ait(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 cit=X(()=>{"use strict"});async function pz(t){return t.get("/api/v1/capsule-recipes")}async function hz(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function mz(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function Az(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function gz(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function da(t){if(!t||typeof t!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(typeof e.recipeName!="string"||e.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(e.recipeVersion!==void 0&&(typeof e.recipeVersion!="number"||!Number.isInteger(e.recipeVersion)||e.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(e.inputs===null||e.inputs===void 0||typeof e.inputs!="object"||Array.isArray(e.inputs))throw new Error("capsuleRecipe.inputs is required and must be a non-null object (recipe-specific shape; see descriptor.versions[].inputSchema).");let r=["baseTransactionResourceId","baseTransactionType","organizationResourceId"],n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length>0&&n.length<r.length)throw new Error(`capsuleRecipe base-transaction triplet is all-or-nothing \u2014 supply all of [baseTransactionResourceId, baseTransactionType, organizationResourceId] or none. Currently supplied: [${n.join(", ")}].`);if(e.templateOverrides!==void 0&&e.templateOverrides!==null){if(!Array.isArray(e.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;e.templateOverrides.forEach((o,s)=>{if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`capsuleRecipe.templateOverrides[${s}] must be an object {slotKey, template?}.`);let a=o;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey is required (non-empty string). Valid keys: get_capsule_recipe \u2192 versions[].templateSlots[].slotKey.`);if(a.slotKey.length>128)throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new Error(`capsuleRecipe.templateOverrides has a duplicate slotKey "${a.slotKey}" \u2014 one override per slot.`);if(i.add(a.slotKey),a.template!==void 0&&a.template!==null){if(typeof a.template!="string")throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var vde=X(()=>{"use strict"});async function ci(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 Ez(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 bz(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var yz,um=X(()=>{"use strict";yz=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function Ja(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Cz=X(()=>{"use strict"});async function vz(t,e){return t.post("/api/v1/claims/conversion/preview",e)}async function Iz(t,e){if(e.idempotencyKey&&/^CONV[:-]/.test(e.idempotencyKey))throw new Error('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return t.post("/api/v1/claims/conversion/commit",e)}var dT,Ide=X(()=>{"use strict";dT=["POST","POST_AND_RECORD"]});async function wz(t,e){if(!(e.amount>0))throw new Error("amount must be greater than 0.");return t.post("/api/v1/claims/payouts/record",e)}async function _z(t,e){return t.search("/api/v1/employees/payouts/search",e)}var lit,wde=X(()=>{"use strict";lit=["REIMBURSEMENT","ADVANCE"]});function uit(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 dit=X(()=>{"use strict"});import{randomUUID as Pvr}from"node:crypto";import{rmSync as Uvr}from"node:fs";function Dde(t){for(let e of t.tempDirs??[])try{Uvr(e,{recursive:!0,force:!0})}catch{}}function pit(t){for(let[e,r]of Dy)t-r.createdAt>fit&&(Dde(r.plan),Dy.delete(e))}function qvr(){_de||(_de=setInterval(()=>pit(Date.now()),$vr),_de.unref?.())}function hit(t,e){let r=Date.now();pit(r),qvr();let n=`dc_${Pvr()}`;return Dy.set(n,{plan:t,createdAt:r,ownerKey:e}),n}function mit(t,e){let r=Dy.get(t);return!r||r.ownerKey!==e?null:Date.now()-r.createdAt>fit?(Dde(r.plan),Dy.delete(t),null):r.plan}function Ait(t,e){let r=Dy.get(t);!r||r.ownerKey!==e||(Dde(r.plan),Dy.delete(t))}var fit,$vr,Dy,_de,git=X(()=>{"use strict";fit=1800*1e3,$vr=300*1e3,Dy=new Map});function jvr(t){if(!t||typeof t!="object")return;let e=t;return e.validFiles?.[0]?.workflowResourceId??e.workflowResourceId}function Yvr(t,e){let r=new Set(e);return{...t,folders:t.folders.map(n=>({...n,files:n.files.filter(i=>_1(i.documentType)&&r.has(i.documentType))}))}}async function yit(t){let{plan:e,client:r,bankAccountId:n,documentTypes:i}=t,o=i&&i.length>0?Yvr(e,i):e;if(!n&&Hvr(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 QL({plan:o,client:r,bankAccountId:n}),a=s.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?jvr(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 Hvr(t){return t.folders.some(e=>e.files.some(r=>r.documentType==="BANK_STATEMENT"))}var Eit=X(()=>{"use strict";F5();Xf()});async function Ku(t,e,r){if(!e)return t;let n=zvr(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 zvr(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 Df(t,e){return!e||!t||typeof t!="object"?t:{...t,_fx:e}}var bit=X(()=>{"use strict"});async function Dz(t,e){return t.list("/api/v1/bank-rules",e)}async function fT(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 Sz(t,e){return t.search("/api/v1/bank-rules/search",e)}async function Rz(t,e){return t.post("/api/v1/bank-rules",e)}async function xz(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function Bz(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var Sde=X(()=>{"use strict"});async function Tz(t,e){return t.list("/api/v1/fixed-assets",e)}async function kz(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function Nz(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function Oz(t,e){return t.post("/api/v1/fixed-assets",e)}async function Fz(t,e,r){return t.put(`/api/v1/fixed-assets/${e}`,r)}async function Qz(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function Lz(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function pT(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function Mz(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function Pz(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function Uz(t,e){return Zo(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var $z=X(()=>{"use strict";Da()});async function qz(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function hT(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function jz(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function Yz(t,e,r){let n={...r};if(n.endDate){let i=!n.startDate,o=!n.repeat&&!n.interval;if(i||o){let s=await hT(t,e);if(i&&(n.startDate=s.data.startDate),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 Hz(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function zz(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 Gz(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var Rde=X(()=>{"use strict"});async function Jz(t,e){return t.list("/api/v1/contact-groups",e)}async function Vz(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function Wz(t,e){return t.search("/api/v1/contact-groups/search",e)}async function Zz(t,e){return t.post("/api/v1/contact-groups",e)}async function Xz(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,r)}async function Kz(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var xde=X(()=>{"use strict"});async function e8(t,e){return t.list("/api/v1/inventory-items",e)}async function t8(t,e){return t.post("/api/v1/inventory-items",e)}async function r8(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var Bde=X(()=>{"use strict"});async function n8(t,e){return t.list("/api/v1/custom-fields",e)}async function i8(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function o8(t,e){return t.search("/api/v1/custom-fields/search",e)}async function s8(t,e){return t.post("/api/v1/custom-fields",e)}async function a8(t,e,r){return t.put(`/api/v1/custom-fields/${e}`,r)}async function c8(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var Tde=X(()=>{"use strict"});function Cit(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function mT(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return Cit(n)}async function AT(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return Cit(n)}var Gvr,Jvr,Vvr,MI,kde=X(()=>{"use strict";Gvr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],Jvr=["journals","cash-entries"],Vvr=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],MI=[...Gvr,...Jvr,...Vvr]});async function l8(t,e){return t.list("/api/v1/nano-classifiers",e)}async function u8(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function d8(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function gT(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function yT(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,r)}async function f8(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var Nde=X(()=>{"use strict"});async function p8(t,e){return t.post("/api/v1/export-records",e)}async function h8(t,e){return t.post("/api/v1/export-records/preview",e)}async function m8(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var Ode=X(()=>{"use strict"});async function ET(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var Fde=X(()=>{"use strict"});function PI(t){Mn(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!Wvr.has(n.btType))throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.`)})}async function A8(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:Xvr(r.data)}}function Zvr(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 Xvr(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(Zvr),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function g8(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function y8(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var Wvr,Qde=X(()=>{"use strict";Da();Wvr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function Iit(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function Lde(t,e){if(!t||typeof t!="object")throw new Error(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${e}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${e}.lineItems per call.`);dc([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&dc([i],["valueDate"])}function tIr(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>=Kvr?"high":r>=vit?"medium":"low";if(n!==void 0){if(n>=eIr)return"high";if(n>=vit)return"medium"}return"low"}function wit(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,v,I;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(v=bT.magicMatch,I={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(v=bT.withPayments,I={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&&(v=bT.learnedPrediction,I={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&&(v=bT.applyBankRule,I={actionShortcutResourceId:B,businessTransactionResourceIds:[c]});break}default:break}let T=v?tIr(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),N=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,z=v!==bT.withPayments||S,q=T==="high"&&!!v&&!!I&&z&&N;o.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:m,isCrossCurrency:A,recommendedTool:v,execute:I,confidenceTier:T,autoCommitEligible:q,alternativeCount:d.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return o}function nIr(t,e,r){return{bankStatementEntryResourceId:t.bankStatementEntryResourceId,confidenceTier:t.confidenceTier,recommendationType:t.recommendationType,recommendedTool:t.recommendedTool,execute:t.execute,bankLine:e,match:r}}async function iIr(t,e,r){let n=e.matchedTransactionResourceId,i=e.matchedTransactionCount;if(!n)return e.matchAmount!==void 0?{type:"transaction",amount:e.matchAmount,count:i}:null;let o=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let s of o)try{let{data:a}=s==="bill"?await Ds(t,n):await Ns(t,n);return{type:s,reference:a.reference,amount:e.matchAmount??a.totalAmount,documentTotalAmount:a.totalAmount,count:i,resourceId:n}}catch{}return{type:"transaction",amount:e.matchAmount,count:i,resourceId:n}}async function _it(t,e,r){let n=r.filter(o=>o.recommendedTool&&!o.autoCommitEligible).slice(0,rIr);if(n.length===0)return[];let i=new Map;if(e)try{let o=await jb(t,e,{filter:{status:{eq:"UNRECONCILED"}},limit:500});for(let s of o.data??[])i.set(s.resourceId,s)}catch{}return Promise.all(n.map(async o=>{let s=i.get(o.bankStatementEntryResourceId),a=s?{valueDate:s.valueDate,netAmount:s.netAmount,currencyCode:s.currencyCode,currencySymbol:s.currencySymbol,description:s.description,counterparty:s.extContactName}:null;return nIr(o,a,await iIr(t,o,a?.netAmount))}))}async function E8(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function b8(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function C8(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function v8(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function I8(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function w8(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function _8(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function D8(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function S8(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function R8(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function x8(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}async function B8(t,e){return t.post("/api/v1/reconciliations/reset",e)}var bT,Kvr,eIr,vit,rIr,Mde=X(()=>{"use strict";yp();wd();Da();eg();bT={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},Kvr=.9,eIr=.95,vit=.7;rIr=25});function $s(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 go(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),o={valueDate:Pde(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=Pde(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=Pde(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(I=>I.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,C=a.debitAmount,E=a.creditAmount,v=a.type??(typeof C=="number"&&C>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||v||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 Pde(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 Lo(t,e,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=$s(t,e,n),a=go(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 fa,Jc,no,Gl,Dit=X(()=>{"use strict";fa=[{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}],Jc=[...fa],no=fa.filter(t=>t.field!=="dueDate"),Gl=[{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 Vc(t){let e={};t.name!=null&&(e.name=t.name),t.quantity!=null&&(e.quantity=t.quantity),t.unitPrice!=null&&(e.unitPrice=t.unitPrice),t.unit&&(e.unit=t.unit);let r=t.accountResourceId||t.organizationAccountResourceId;r&&(e.accountResourceId=r);let n=t.taxProfileResourceId||(t.taxProfile&&typeof t.taxProfile=="object"?t.taxProfile.resourceId:null);return n&&(e.taxProfileResourceId=n),t.itemResourceId&&(e.itemResourceId=t.itemResourceId),t.discount!=null&&(e.discount=typeof t.discount=="object"?t.discount.rateValue??0:t.discount),e}function UI(t){let e={},r=t.accountResourceId||t.organizationAccountResourceId;return r&&(e.accountResourceId=r),t.amount!=null?e.amount=t.amount:t.debitAmount!=null&&t.debitAmount>0?e.amount=t.debitAmount:t.creditAmount!=null&&t.creditAmount>0&&(e.amount=t.creditAmount),t.type?e.type=t.type:t.debitAmount!=null&&t.debitAmount>0?e.type="DEBIT":t.creditAmount!=null&&t.creditAmount>0&&(e.type="CREDIT"),t.description&&(e.description=t.description),t.contactResourceId&&(e.contactResourceId=t.contactResourceId),e}function Mt(t){if(t)return t.split("T")[0]}var Ude=X(()=>{"use strict"});function ed(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 T8(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=UI(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),o})}return r}var Sit=X(()=>{"use strict";Ude()});var $de=X(()=>{"use strict";Dit();Ude();Sit()});var CT,Jl,Rit=X(()=>{"use strict";CT="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",Jl="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function jde(t){return oIr.get(t)}function xit(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!qde.has(o));return n.length===0?[]:Ri.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 Ri,qde,oIr,td=X(()=>{"use strict";Ri=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, and transition (accept a quote, confirm an order, void, delete). A Sale Order links to its quote via saleQuoteResourceId; the quote must be accepted first. Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (raise the invoice separately).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, and transition (accept a request, confirm an order, void, delete). A Purchase Order links to its request via purchaseRequestResourceId; the request must be accepted first. Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (raise the bill separately).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections.",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry \u2014 write side. Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments \u2014 the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Twelve endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created \u2014 it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace \u2014 switch there or call by name).",groups:["financial_reports"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail.",groups:["operational_reports","exports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema) + sync preview (\u2264100 rows) + async CSV export. Use when search_* / download_export canonical reports don't cover the question.",groups:["pseudo_sql"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Bulk upsert contacts from CSV / spreadsheet imports \u2014 async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs \u2014 named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"nano_classifiers",title:"Tracking Categories",description:"Nano classifiers (tracking categories/dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts \u2014 including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes.",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules \u2014 how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via document attachment / conversion (no bare create); the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only \u2014 no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once \u2014 asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); bind a login user to an employee (permanent); and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"capsules_and_recipes",title:"IFRS Recipes & Capsules",description:"Capsules (transaction groupings/capsule types). Financial recipes: amortization, depreciation, deferred revenue, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal. Two recipe execution paths: offline (plan_recipe + execute_recipe \u2014 client-side calculators, no API key) and server-side (list/get/preview/resume/rollback_capsule_recipe \u2014 produce real capsule entities via Jaz API). Plus capsuleRecipe payload on trigger mutations (create_bill, create_journal, create_cash_in, etc.) to create and trigger a recipe in one shot, with optional templateOverrides to customize the generated text (Customize Recipe). Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, rollback recipe, customize template overrides slots.",groups:["capsules","recipes","capsule_recipes"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). List/search saved report templates.",groups:["organization","org_users","modules","report_templates"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets \u2014 CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill or invoice via AI extraction (create_bt_from_attachment, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork \u2014 "create docs from this Dropbox folder link", a pile/batch of invoices and bills \u2014 into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications.",groups:["payments","cashflow","search"]},{name:"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"]}],qde=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"]),oIr=new Map(Ri.flatMap(t=>t.groups.map(e=>[e,t.name])))});function $I(t){let e=new Set,r=[];for(let n of t)for(let i of Vl(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function vT(){return Ri.map(t=>{let e=$I(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 sIr(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 Sy(t,e=!1){let r=qI(void 0).length,n=Ri.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:sIr(t,i,r)}:{},map:vT(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var k8=X(()=>{"use strict";td();rd()});function N8(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=N8(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=N8(i);e.properties=r,t.required?.length&&(e.required=t.required)}return e}function Sf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=N8(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function Ry(t){return{name:t.name,description:t.description,input_schema:Sf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var jI=X(()=>{"use strict"});function IT(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 O8(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&IT(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function cIr(t){return t.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function lIr(t){let e=cIr(t);return!e||aIr.has(e)?!0:e.split(" ").filter(n=>n.length>=2&&!qde.has(n)).length===0}function F8(t){if(lIr(t)){let{next:i,...o}=Sy();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=xit(t,5);if(e.length===0){let{operations:i,namespaces:o}=Sy();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=>Vl(u)),s=o.map(u=>`${u.name} ${(u.aliases??[]).join(" ")} ${u.searchHint??""} ${u.description}`.toLowerCase()),a=new Map(n.map(u=>{let d=s.filter(f=>f.includes(u)).length;return[u,Math.log((o.length+1)/(d+1))]})),c=o.map((u,d)=>{let f=s[d],p=n.reduce((h,m)=>f.includes(m)?h+(a.get(m)??0):h,0);return{tool:u,score:p}}).sort((u,d)=>d.score-u.score);return{namespace:i.name,description:i.description,tools:c.map(u=>({name:u.tool.name,description:u.tool.description.split(`
|
|
681
|
+
`)}catch{}},pde={info:nz,warn:nz,error:Znt,debug:nz,trace:nz,fatal:Znt,child:pvr,level:"error"},hvr=pde});import{createHash as mvr}from"node:crypto";function Svr(t){if(!t||!t.trim())return[null,"directive_required"];let e=t.normalize("NFKC").trim();return e.length>300?[null,"directive_too_long"]:gvr.some(r=>e.includes(r))?[null,"directive_invalid"]:Avr.test(e)?[null,"directive_invalid"]:Ivr.test(e)?[null,"directive_contains_url"]:wvr.test(e)?[null,"directive_contains_email"]:[e,null]}function Rvr(t){return t==null?[null,null]:Number.isInteger(t)?t<_vr||t>Dvr?[null,"invalid_importance"]:[t,null]:[null,"invalid_importance"]}function xvr(t,e,r,n,i,o,s,a){if(t)return mvr("sha256").update(`${t}:${e}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function Bvr(t){Promise.resolve().then(()=>(mde(),hde)).then(({log:e})=>e.info(t,"memory_tool.call")).catch(()=>{})}async function nit(t,e,r){let n=e.action,i=e.category,o=Cvr[e.scope??"this_org"]??"ORG_USER",s=typeof e.key=="string"?e.key.trim():"",a=null,c=d=>(Bvr({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=Wnt(d);if(f)return u(f);if(!d)return u("memory_disabled");if(!s||s.length>yvr||!vvr.test(s))return u("invalid_key");let p=null,h=null;if(n==="set"){let[g,y]=Svr(e.directive);if(y)return u(y);p=g;let[C,E]=Rvr(e.importance);if(E)return u(E);h=C}if(a=1,e.key_type!==void 0&&e.key_type!==null){if(!e.match_value||!e.match_value.trim())return u("match_value_required");a=2}else if(e.match_value)return u("key_type_required");if(d.writes>=Evr)return u("write_limit");d.writes+=1;let m=d.gtid||"",A;if(n==="set"){let g={gtid:m};d.quote&&(g.quote=d.quote.slice(0,bvr));let y=xvr(m,n,o,i,s,p,e.confirms_key,e.replaces_key),C={scope:o,tier:a,category:i,key:s,...e.key_type?{keyType:e.key_type}:{},...e.match_value?{matchValue:e.match_value}:{},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:g,...y?{idempotencyKey:y}:{},...h!==null?{importance:h}:{}};A=await Ade(()=>Jnt(t.client,C)),A.ok&&(d.remembered=!0)}else if(n==="forget"){let g={category:i,key:s,scope:o};A=await Ade(()=>ude(t.client,g))}else{let g={forgetAll:!0};A=await Ade(()=>ude(t.client,g))}return c(A)}catch{return c({ok:!1,reason:"internal_error"})}}async function Ade(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 ao?e.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${e.status}`}:{ok:!1,reason:"network_error"}}}var Avr,gvr,yvr,Evr,bvr,Knt,eit,tit,rit,Cvr,vvr,Ivr,wvr,_vr,Dvr,iit=X(()=>{"use strict";Vnt();uc();fde();fde();Avr=/[\x00-\x1f\x7f]/,gvr=["{{","}}","```","<",">"],yvr=120,Evr=3,bvr=140,Knt=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling","autonomy-grant"],eit=["set","forget","forget_all"],tit=["this_org","all_orgs"],rit=["SENDER_ADDRESS","SENDER_DOMAIN","VENDOR_NAME","SUBJECT_TOKEN"],Cvr={this_org:"ORG_USER",all_orgs:"USER"},vvr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Ivr=/https?:\/\//i,wvr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/,_vr=0,Dvr=100});async function iz(t,e){return t.list("/api/v1/organization-users",e)}async function oz(t,e){return t.search("/api/v1/organization-users/search",e)}async function LI(t,e){return t.post("/api/v1/organization-users/invite",e)}async function sz(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function az(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var gde=X(()=>{"use strict"});async function cz(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 uT(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function lz(t,e){return t.get(`/api/v1/payments/${e}`)}async function uz(t,e,r){return t.put(`/api/v1/payments/${e}`,{...r,currency:jr(r.currency)})}async function dz(t,e){await t.delete(`/api/v1/payments/${e}`)}var yde=X(()=>{"use strict";Pn()});async function fz(t,e,r={}){let n=Tvr.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`;return t.post(n,r)}var Tvr,Ede=X(()=>{"use strict";Tvr=new Set(["statement-of-account-export"])});import{createHash as kvr}from"node:crypto";import{writeFile as Nvr,mkdir as Ovr}from"node:fs/promises";import{dirname as Fvr,isAbsolute as Qvr,join as Lvr}from"node:path";async function oit(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function bde(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 Cde(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function Mvr(t){return kvr("sha256").update(t).digest("hex").slice(0,16)}async function sit(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=Mvr(e),o=await bde(t,e,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(;Date.now()<a&&!(c.status==="COMPLETED"||c.status==="FAILED"||c.status==="EXPIRED"||(await new Promise(p=>setTimeout(p,2e3)),Date.now()>=a));)c=(await Cde(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&&!Qvr(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??Lvr(f,"Downloads",`pseudo-sql-${s}.csv`);return await Ovr(Fvr(p),{recursive:!0}),await Nvr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}async function ait(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 cit=X(()=>{"use strict"});async function pz(t){return t.get("/api/v1/capsule-recipes")}async function hz(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function mz(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function Az(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function gz(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function da(t){if(!t||typeof t!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(typeof e.recipeName!="string"||e.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(e.recipeVersion!==void 0&&(typeof e.recipeVersion!="number"||!Number.isInteger(e.recipeVersion)||e.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(e.inputs===null||e.inputs===void 0||typeof e.inputs!="object"||Array.isArray(e.inputs))throw new Error("capsuleRecipe.inputs is required and must be a non-null object (recipe-specific shape; see descriptor.versions[].inputSchema).");let r=["baseTransactionResourceId","baseTransactionType","organizationResourceId"],n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length>0&&n.length<r.length)throw new Error(`capsuleRecipe base-transaction triplet is all-or-nothing \u2014 supply all of [baseTransactionResourceId, baseTransactionType, organizationResourceId] or none. Currently supplied: [${n.join(", ")}].`);if(e.templateOverrides!==void 0&&e.templateOverrides!==null){if(!Array.isArray(e.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;e.templateOverrides.forEach((o,s)=>{if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`capsuleRecipe.templateOverrides[${s}] must be an object {slotKey, template?}.`);let a=o;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey is required (non-empty string). Valid keys: get_capsule_recipe \u2192 versions[].templateSlots[].slotKey.`);if(a.slotKey.length>128)throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new Error(`capsuleRecipe.templateOverrides has a duplicate slotKey "${a.slotKey}" \u2014 one override per slot.`);if(i.add(a.slotKey),a.template!==void 0&&a.template!==null){if(typeof a.template!="string")throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var vde=X(()=>{"use strict"});async function ci(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 Ez(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 bz(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var yz,um=X(()=>{"use strict";yz=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function Ja(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var Cz=X(()=>{"use strict"});async function vz(t,e){return t.post("/api/v1/claims/conversion/preview",e)}async function Iz(t,e){if(e.idempotencyKey&&/^CONV[:-]/.test(e.idempotencyKey))throw new Error('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return t.post("/api/v1/claims/conversion/commit",e)}var dT,Ide=X(()=>{"use strict";dT=["POST","POST_AND_RECORD"]});async function wz(t,e){if(!(e.amount>0))throw new Error("amount must be greater than 0.");return t.post("/api/v1/claims/payouts/record",e)}async function _z(t,e){return t.search("/api/v1/employees/payouts/search",e)}var lit,wde=X(()=>{"use strict";lit=["REIMBURSEMENT","ADVANCE"]});function uit(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 dit=X(()=>{"use strict"});import{randomUUID as Pvr}from"node:crypto";import{rmSync as Uvr}from"node:fs";function Dde(t){for(let e of t.tempDirs??[])try{Uvr(e,{recursive:!0,force:!0})}catch{}}function pit(t){for(let[e,r]of Dy)t-r.createdAt>fit&&(Dde(r.plan),Dy.delete(e))}function qvr(){_de||(_de=setInterval(()=>pit(Date.now()),$vr),_de.unref?.())}function hit(t,e){let r=Date.now();pit(r),qvr();let n=`dc_${Pvr()}`;return Dy.set(n,{plan:t,createdAt:r,ownerKey:e}),n}function mit(t,e){let r=Dy.get(t);return!r||r.ownerKey!==e?null:Date.now()-r.createdAt>fit?(Dde(r.plan),Dy.delete(t),null):r.plan}function Ait(t,e){let r=Dy.get(t);!r||r.ownerKey!==e||(Dde(r.plan),Dy.delete(t))}var fit,$vr,Dy,_de,git=X(()=>{"use strict";fit=1800*1e3,$vr=300*1e3,Dy=new Map});function jvr(t){if(!t||typeof t!="object")return;let e=t;return e.validFiles?.[0]?.workflowResourceId??e.workflowResourceId}function Yvr(t,e){let r=new Set(e);return{...t,folders:t.folders.map(n=>({...n,files:n.files.filter(i=>_1(i.documentType)&&r.has(i.documentType))}))}}async function yit(t){let{plan:e,client:r,bankAccountId:n,documentTypes:i}=t,o=i&&i.length>0?Yvr(e,i):e;if(!n&&Hvr(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 QL({plan:o,client:r,bankAccountId:n}),a=s.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?jvr(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 Hvr(t){return t.folders.some(e=>e.files.some(r=>r.documentType==="BANK_STATEMENT"))}var Eit=X(()=>{"use strict";F5();Xf()});async function Ku(t,e,r){if(!e)return t;let n=zvr(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 zvr(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 Df(t,e){return!e||!t||typeof t!="object"?t:{...t,_fx:e}}var bit=X(()=>{"use strict"});async function Dz(t,e){return t.list("/api/v1/bank-rules",e)}async function fT(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 Sz(t,e){return t.search("/api/v1/bank-rules/search",e)}async function Rz(t,e){return t.post("/api/v1/bank-rules",e)}async function xz(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function Bz(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var Sde=X(()=>{"use strict"});async function Tz(t,e){return t.list("/api/v1/fixed-assets",e)}async function kz(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function Nz(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function Oz(t,e){return t.post("/api/v1/fixed-assets",e)}async function Fz(t,e,r){return t.put(`/api/v1/fixed-assets/${e}`,r)}async function Qz(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function Lz(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function pT(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function Mz(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function Pz(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function Uz(t,e){return Zo(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var $z=X(()=>{"use strict";Da()});async function qz(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function hT(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function jz(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function Yz(t,e,r){let n={...r};if(n.endDate){let i=!n.startDate,o=!n.repeat&&!n.interval;if(i||o){let s=await hT(t,e);if(i&&(n.startDate=s.data.startDate),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 Hz(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function zz(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 Gz(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var Rde=X(()=>{"use strict"});async function Jz(t,e){return t.list("/api/v1/contact-groups",e)}async function Vz(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function Wz(t,e){return t.search("/api/v1/contact-groups/search",e)}async function Zz(t,e){return t.post("/api/v1/contact-groups",e)}async function Xz(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,r)}async function Kz(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var xde=X(()=>{"use strict"});async function e8(t,e){return t.list("/api/v1/inventory-items",e)}async function t8(t,e){return t.post("/api/v1/inventory-items",e)}async function r8(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var Bde=X(()=>{"use strict"});async function n8(t,e){return t.list("/api/v1/custom-fields",e)}async function i8(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function o8(t,e){return t.search("/api/v1/custom-fields/search",e)}async function s8(t,e){return t.post("/api/v1/custom-fields",e)}async function a8(t,e,r){return t.put(`/api/v1/custom-fields/${e}`,r)}async function c8(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var Tde=X(()=>{"use strict"});function Cit(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function mT(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return Cit(n)}async function AT(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return Cit(n)}var Gvr,Jvr,Vvr,MI,kde=X(()=>{"use strict";Gvr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],Jvr=["journals","cash-entries"],Vvr=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],MI=[...Gvr,...Jvr,...Vvr]});async function l8(t,e){return t.list("/api/v1/nano-classifiers",e)}async function u8(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function d8(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function gT(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function yT(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,r)}async function f8(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var Nde=X(()=>{"use strict"});async function p8(t,e){return t.post("/api/v1/export-records",e)}async function h8(t,e){return t.post("/api/v1/export-records/preview",e)}async function m8(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var Ode=X(()=>{"use strict"});async function ET(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var Fde=X(()=>{"use strict"});function PI(t){Mn(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!Wvr.has(n.btType)){let i=String(n.btType).toUpperCase().startsWith("JOURNAL")?" Journals are not part of this lifecycle: they have no approval state. To promote a DRAFT journal to ACTIVE use `bulk_update_journals` with `saveAsDraft: false` (or `update_journal` for one) \u2014 that is the supported path, not a workaround.":"";throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.${i}`)}})}async function A8(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:Xvr(r.data)}}function Zvr(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 Xvr(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(Zvr),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function g8(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function y8(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var Wvr,Qde=X(()=>{"use strict";Da();Wvr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function Iit(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function Lde(t,e){if(!t||typeof t!="object")throw new Error(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${e}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${e}.lineItems per call.`);dc([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&dc([i],["valueDate"])}function tIr(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>=Kvr?"high":r>=vit?"medium":"low";if(n!==void 0){if(n>=eIr)return"high";if(n>=vit)return"medium"}return"low"}function wit(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,v,I;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(v=bT.magicMatch,I={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(v=bT.withPayments,I={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&&(v=bT.learnedPrediction,I={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&&(v=bT.applyBankRule,I={actionShortcutResourceId:B,businessTransactionResourceIds:[c]});break}default:break}let T=v?tIr(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),N=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,z=v!==bT.withPayments||S,q=T==="high"&&!!v&&!!I&&z&&N;o.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:m,isCrossCurrency:A,recommendedTool:v,execute:I,confidenceTier:T,autoCommitEligible:q,alternativeCount:d.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return o}function nIr(t,e,r){return{bankStatementEntryResourceId:t.bankStatementEntryResourceId,confidenceTier:t.confidenceTier,recommendationType:t.recommendationType,recommendedTool:t.recommendedTool,execute:t.execute,bankLine:e,match:r}}async function iIr(t,e,r){let n=e.matchedTransactionResourceId,i=e.matchedTransactionCount;if(!n)return e.matchAmount!==void 0?{type:"transaction",amount:e.matchAmount,count:i}:null;let o=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let s of o)try{let{data:a}=s==="bill"?await Ds(t,n):await Ns(t,n);return{type:s,reference:a.reference,amount:e.matchAmount??a.totalAmount,documentTotalAmount:a.totalAmount,count:i,resourceId:n}}catch{}return{type:"transaction",amount:e.matchAmount,count:i,resourceId:n}}async function _it(t,e,r){let n=r.filter(o=>o.recommendedTool&&!o.autoCommitEligible).slice(0,rIr);if(n.length===0)return[];let i=new Map;if(e)try{let o=await jb(t,e,{filter:{status:{eq:"UNRECONCILED"}},limit:500});for(let s of o.data??[])i.set(s.resourceId,s)}catch{}return Promise.all(n.map(async o=>{let s=i.get(o.bankStatementEntryResourceId),a=s?{valueDate:s.valueDate,netAmount:s.netAmount,currencyCode:s.currencyCode,currencySymbol:s.currencySymbol,description:s.description,counterparty:s.extContactName}:null;return nIr(o,a,await iIr(t,o,a?.netAmount))}))}async function E8(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function b8(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function C8(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function v8(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function I8(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function w8(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function _8(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function D8(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function S8(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function R8(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function x8(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}async function B8(t,e){return t.post("/api/v1/reconciliations/reset",e)}var bT,Kvr,eIr,vit,rIr,Mde=X(()=>{"use strict";yp();wd();Da();eg();bT={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},Kvr=.9,eIr=.95,vit=.7;rIr=25});function $s(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 go(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),o={valueDate:Pde(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=Pde(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=Pde(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(I=>I.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,C=a.debitAmount,E=a.creditAmount,v=a.type??(typeof C=="number"&&C>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||v||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 Pde(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 Lo(t,e,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=$s(t,e,n),a=go(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 fa,Jc,no,Gl,Dit=X(()=>{"use strict";fa=[{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}],Jc=[...fa],no=fa.filter(t=>t.field!=="dueDate"),Gl=[{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 Vc(t){let e={};t.name!=null&&(e.name=t.name),t.quantity!=null&&(e.quantity=t.quantity),t.unitPrice!=null&&(e.unitPrice=t.unitPrice),t.unit&&(e.unit=t.unit);let r=t.accountResourceId||t.organizationAccountResourceId;r&&(e.accountResourceId=r);let n=t.taxProfileResourceId||(t.taxProfile&&typeof t.taxProfile=="object"?t.taxProfile.resourceId:null);return n&&(e.taxProfileResourceId=n),t.itemResourceId&&(e.itemResourceId=t.itemResourceId),t.discount!=null&&(e.discount=typeof t.discount=="object"?t.discount.rateValue??0:t.discount),e}function UI(t){let e={},r=t.accountResourceId||t.organizationAccountResourceId;return r&&(e.accountResourceId=r),t.amount!=null?e.amount=t.amount:t.debitAmount!=null&&t.debitAmount>0?e.amount=t.debitAmount:t.creditAmount!=null&&t.creditAmount>0&&(e.amount=t.creditAmount),t.type?e.type=t.type:t.debitAmount!=null&&t.debitAmount>0?e.type="DEBIT":t.creditAmount!=null&&t.creditAmount>0&&(e.type="CREDIT"),t.description&&(e.description=t.description),t.contactResourceId&&(e.contactResourceId=t.contactResourceId),e}function Mt(t){if(t)return t.split("T")[0]}var Ude=X(()=>{"use strict"});function ed(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 T8(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=UI(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),o})}return r}var Sit=X(()=>{"use strict";Ude()});var $de=X(()=>{"use strict";Dit();Ude();Sit()});var CT,Jl,Rit=X(()=>{"use strict";CT="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",Jl="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function jde(t){return oIr.get(t)}function xit(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!qde.has(o));return n.length===0?[]:Ri.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 Ri,qde,oIr,td=X(()=>{"use strict";Ri=[{name:"capabilities",title:"What Jaz Can Do",description:"The capability map: catalog, inventory, and overview of the whole operation surface. Returns every namespace with its operation count, drills into one namespace's operations, or ranks operations by keyword. Call before concluding an operation does not exist.",groups:["capabilities"]},{name:"invoices",title:"Invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",title:"Customer Credit Notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",title:"Bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",title:"Supplier Credit Notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",title:"Sales Quotes & Orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, and transition (accept a quote, confirm an order, void, delete). A Sale Order links to its quote via saleQuoteResourceId; the quote must be accepted first. Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (raise the invoice separately).",groups:["sale_orders"]},{name:"purchase_orders",title:"Purchase Requests & Orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, and transition (accept a request, confirm an order, void, delete). A Purchase Order links to its request via purchaseRequestResourceId; the request must be accepted first. Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (raise the bill separately).",groups:["purchase_orders"]},{name:"journals",title:"Journal Entries",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections.",groups:["journals"]},{name:"cash_entries",title:"Cash In & Out",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",title:"Cash Transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",title:"Bank Accounts & Statements",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",title:"Bank Rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",title:"Bank Reconciliation",description:"Apply a reconciliation decision to a bank statement entry \u2014 write side. Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments \u2014 the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Twelve endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), undo_reconciliations (bulk reverse), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side. To reverse a reconciliation use undo_reconciliations, which unlinks the entry but does NOT delete a record a reconcile call created \u2014 it returns linkedRecords so you can delete that record too.",groups:["reconciliations"]},{name:"financial_reports",title:"Financial Reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace \u2014 switch there or call by name).",groups:["financial_reports"]},{name:"operational_reports",title:"Aging, Exports & Anomalies",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail.",groups:["operational_reports","exports"]},{name:"pseudo_sql",title:"Ad-hoc Queries (SQL)",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema) + sync preview (\u2264100 rows) + async CSV export. Use when search_* / download_export canonical reports don't cover the question.",groups:["pseudo_sql"]},{name:"contacts",title:"Contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Bulk upsert contacts from CSV / spreadsheet imports \u2014 async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",title:"Items & Inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",title:"Catalogs",description:"Catalogs \u2014 named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",title:"Tags & Custom Fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"nano_classifiers",title:"Tracking Categories",description:"Nano classifiers (tracking categories/dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",title:"Chart of Accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts \u2014 including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",title:"Currencies & FX Rates",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",title:"Tax Profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes.",groups:["tax_profiles"]},{name:"claim_settings",title:"Expense Claim Settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",title:"Claim Posting Rules",description:"Claim posting rules \u2014 how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",title:"Expense Claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via document attachment / conversion (no bare create); the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",title:"Claim Processing & Payouts",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only \u2014 no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once \u2014 asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",title:"Employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); bind a login user to an employee (permanent); and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"capsules_and_recipes",title:"IFRS Recipes & Capsules",description:"Capsules (transaction groupings/capsule types). Financial recipes: amortization, depreciation, deferred revenue, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal. Two recipe execution paths: offline (plan_recipe + execute_recipe \u2014 client-side calculators, no API key) and server-side (list/get/preview/resume/rollback_capsule_recipe \u2014 produce real capsule entities via Jaz API). Plus capsuleRecipe payload on trigger mutations (create_bill, create_journal, create_cash_in, etc.) to create and trigger a recipe in one shot, with optional templateOverrides to customize the generated text (Customize Recipe). Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, rollback recipe, customize template overrides slots.",groups:["capsules","recipes","capsule_recipes"]},{name:"scheduled_transactions",title:"Scheduled Transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",title:"Subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",title:"Organization & Users",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). List/search saved report templates.",groups:["organization","org_users","modules","report_templates"]},{name:"document_ai",title:"Document AI (Scan & Extract)",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets \u2014 CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill or invoice via AI extraction (create_bt_from_attachment, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork \u2014 "create docs from this Dropbox folder link", a pile/batch of invoices and bills \u2014 into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",title:"Fixed Assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",title:"Payments & Universal Search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications.",groups:["payments","cashflow","search"]},{name:"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"]}],qde=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"]),oIr=new Map(Ri.flatMap(t=>t.groups.map(e=>[e,t.name])))});function $I(t){let e=new Set,r=[];for(let n of t)for(let i of Vl(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function vT(){return Ri.map(t=>{let e=$I(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 sIr(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 Sy(t,e=!1){let r=qI(void 0).length,n=Ri.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:sIr(t,i,r)}:{},map:vT(),next:`Call with { namespace: "invoices" } for one area's operations and their parameters, or { query: "depreciation" } to rank all ${r}.`}}var k8=X(()=>{"use strict";td();rd()});function N8(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=N8(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=N8(i);e.properties=r,t.required?.length&&(e.required=t.required)}return e}function Sf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=N8(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function Ry(t){return{name:t.name,description:t.description,input_schema:Sf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var jI=X(()=>{"use strict"});function IT(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 O8(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&IT(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function cIr(t){return t.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function lIr(t){let e=cIr(t);return!e||aIr.has(e)?!0:e.split(" ").filter(n=>n.length>=2&&!qde.has(n)).length===0}function F8(t){if(lIr(t)){let{next:i,...o}=Sy();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=xit(t,5);if(e.length===0){let{operations:i,namespaces:o}=Sy();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=>Vl(u)),s=o.map(u=>`${u.name} ${(u.aliases??[]).join(" ")} ${u.searchHint??""} ${u.description}`.toLowerCase()),a=new Map(n.map(u=>{let d=s.filter(f=>f.includes(u)).length;return[u,Math.log((o.length+1)/(d+1))]})),c=o.map((u,d)=>{let f=s[d],p=n.reduce((h,m)=>f.includes(m)?h+(a.get(m)??0):h,0);return{tool:u,score:p}}).sort((u,d)=>d.score-u.score);return{namespace:i.name,description:i.description,tools:c.map(u=>({name:u.tool.name,description:u.tool.description.split(`
|
|
682
682
|
`)[0],...u.tool.searchHint?{searchHint:u.tool.searchHint}:{}}))}}),hint:"Call describe_tools with the tool names you need, then execute_tool to run them."}}function Bit(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=Q8(n);if(!i){r.push(n);continue}e.push({...Ry(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&IT(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 aIr,uIr,dIr,fIr,Rf,dm,YI=X(()=>{"use strict";td();k8();rd();jI();aIr=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"]);uIr={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:Sf({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};dIr={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:Sf({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},fIr={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:Sf({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"])},Rf={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:Sf({},[])},dm=[uIr,dIr,fIr]});function AIr(t){if(!(Wl in t))return{cleanedInput:t};let{[Wl]:e,...r}=t;return{jotText:typeof e=="string"&&e.trim()!==""?e.trim():void 0,cleanedInput:r}}function Nit(t,e){if(t.params[Wl])return{cleanedInput:e};let{jotText:r,cleanedInput:n}=AIr(e);return t.readOnly?{cleanedInput:n}:{jotText:r,cleanedInput:n}}function gIr(t){let e=hIr.exec(t);return e?{kind:e[1],call:t.slice(e[0].length)||t}:{call:t}}function EIr(t){let e=t.toLowerCase();for(let[r,n]of yIr)if(n.test(e))return r}function bIr(t,e){let r=EIr(t),n=[],i=new Set,o=(s,a)=>{if(!(n.length>=Tit||a>mIr||!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>=Tit)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 L8(t,e,r,n){let{kind:i,call:o}=gIr(r),s=bIr(e,n),a={...i?{kind:i}:{},tier:"MEDIUM",call:o,frame:`tool:${e}`,...s.length?{refs:s}:{},writePath:"PIGGYBACK"};QI(t,[a]).catch(c=>{let u=c instanceof Error?c.message:String(c);Promise.resolve().then(()=>(mde(),hde)).then(({log:d})=>d.error({tool:e,error:u},"Piggyback jot write failed")).catch(()=>process.stderr.write(`[jots-piggyback] jot write failed (${e}): ${u}
|
|
683
683
|
`))})}var Wl,kit,pIr,hIr,Tit,mIr,yIr,M8=X(()=>{"use strict";tz();mC();Wl="jot",kit='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. '+aP,pIr=["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],hIr=new RegExp(`^(${pIr.join("|")})\\s*:\\s*`),Tit=20,mIr=6;yIr=[["RECONCILE",/(?:^|_)reconcile(?:_|$)/],["PAY",/(?:^|_)(?:pay|payment|payout|cash_out|disburse|disbursement|refund)(?:_|$)/],["FINALIZE",/(?:^|_)(?:finalize|convert_drafts_to_active)(?:_|$)/],["DELETE",/(?:^|_)(?:delete|void|discard|rollback)(?:_|$)/],["TRIGGER",/(?:^|_)(?:recipe|trigger|execute)(?:_|$)/],["UPDATE",/(?:^|_)update(?:_|$)/],["CREATE",/(?:^|_)create(?:_|$)/]]});function Oit(t){let e=new Set,r=[];for(let n of t)for(let i of Vl(n))e.has(i.name)||(e.add(i.name),r.push(i));return r}function CIr(t){return t.split("_").map(e=>e&&e[0].toUpperCase()+e.slice(1)).join(" ")}function HI(t){let e=t.readOnly?"read":IT(t)?"destructive":"write",r=Object.keys(t.params).filter(s=>!t.required.includes(s)),n=t.required.length?` required: ${t.required.join(", ")};`:"",i=r.length?` optional: ${r.slice(0,10).join(", ")}${r.length>10?", \u2026":""}`:"",o=(t.searchHint||t.description.split(`
|
|
684
684
|
`)[0]||"").trim().slice(0,140);return`- ${t.name} (${e}): ${o}${n}${i}`}function P8(t=!1){return Ri.map(e=>{let r=Oit(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=>IT(d)),a=r.filter(d=>d.acceptsHostFile).map(d=>d.name),c=`${e.description}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jaz-clio",
|
|
3
|
-
"version": "5.36.
|
|
3
|
+
"version": "5.36.2",
|
|
4
4
|
"description": "Clio: Command Line Interface Operator for Jaz AI.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"type": "git",
|
|
36
36
|
"url": "https://github.com/teamtinvio/jaz-ai"
|
|
37
37
|
},
|
|
38
|
-
"author": "Jaz <
|
|
38
|
+
"author": "Jaz <build.with@jaz.ai>",
|
|
39
39
|
"license": "MIT",
|
|
40
40
|
"engines": {
|
|
41
41
|
"node": ">=18"
|