jaz-clio 5.20.6 → 5.20.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-api
3
- version: 5.20.6
3
+ version: 5.20.8
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
@@ -376,7 +376,7 @@ Bills, invoices, and credit notes share identical mandatory field specs. Adding
376
376
  113. **Nano-classifier API gotchas** — CREATE uses `classes: string[]` (NOT `classNames` or `[{className}]`). `printable: boolean` is required — defaults to `false` (most classifiers are not printable). GET single is double-wrapped: `{data: {data: [...], totalElements, totalPages}}` — extract the first element from the inner paginated response. GET/LIST response returns classes as `[{className, resourceId}]` (objects), while CREATE accepts plain `string[]`.
377
377
 
378
378
  ### Scheduler Response Asymmetry
379
- 114. **Scheduler response uses `interval`, not `repeat`** — POST/PUT uses `repeat` field (values: `WEEKLY`, `MONTHLY`, `QUARTERLY`, `YEARLY`). GET response returns `interval` field (same values). PUT accepts the full transaction template (`invoice`, `bill`, or journal entries at top level), not just schedule metadata — same structure as POST.
379
+ 114. **Scheduler response uses `interval`, not `repeat`** — POST/PUT uses `repeat` field (values: `ONE_TIME`, `DAILY`, `WEEKLY`, `MONTHLY`, `YEARLY`; `QUARTERLY` is rejected with 422). GET response returns `interval` field (same values; legacy rows may still show `QUARTERLY`). PUT accepts the full transaction template (`invoice`, `bill`, or journal entries at top level), not just schedule metadata — same structure as POST.
380
380
 
381
381
  ### Payment Record CRUD
382
382
  115. **Payment record CRUD** — `GET /payments/:resourceId` returns `{data: PaymentRecord}` (wrapped). Payment resourceIds come from invoice/bill GET response → `paymentRecords[].resourceId`. **Cashflow transaction IDs ≠ payment IDs** — don't mix them. `POST /cashflow-transactions/search` returns cashflow IDs, while payment CRUD uses separate payment IDs from the parent document.
@@ -1353,7 +1353,7 @@ Same but with `"bill"` wrapper instead of `"invoice"`.
1353
1353
 
1354
1354
  **CRITICAL notes from live testing**:
1355
1355
  - Recurrence field is `repeat` — NOT `frequency` or `interval`. Using `frequency` or `interval` silently defaults to ONE_TIME.
1356
- - Valid `repeat` values: `"WEEKLY"`, `"MONTHLY"`, `"QUARTERLY"`, `"YEARLY"`
1356
+ - Valid `repeat` values: `"ONE_TIME"`, `"DAILY"`, `"WEEKLY"`, `"MONTHLY"`, `"YEARLY"` (`"QUARTERLY"` is rejected with 422)
1357
1357
  - `saveAsDraft: false` is REQUIRED on the wrapped invoice/bill. Using `saveAsDraft: true` causes `INVALID_SALE_STATUS` (invoices) or `INVALID_PURCHASE_STATUS` (bills).
1358
1358
  - Since `saveAsDraft: false`, every line item MUST have `accountResourceId`.
1359
1359
  - Response uses `interval` field (not `repeat`): `{ "status": "ACTIVE", "interval": "MONTHLY", ... }`
@@ -1395,7 +1395,7 @@ Subscriptions auto-generate invoices on schedule with proration support. **Diffe
1395
1395
  - `proratedConfig` is **REQUIRED** on create, update, and cancel. Omitting it causes 500 (server null pointer).
1396
1396
  - `businessTransactionType` is NOT in the OAS — the API ignores it. Don't send it.
1397
1397
  - Uses `repeat` + `invoice` wrapper — same structure as scheduled invoices (`POST /scheduled/invoices`).
1398
- - `repeat`: `"WEEKLY"`, `"MONTHLY"`, `"QUARTERLY"`, `"YEARLY"`.
1398
+ - `repeat`: `"ONE_TIME"`, `"DAILY"`, `"WEEKLY"`, `"MONTHLY"`, `"YEARLY"` (`"QUARTERLY"` is rejected with 422).
1399
1399
  - `saveAsDraft: false` is REQUIRED inside the `invoice` wrapper.
1400
1400
  - Currency, tax, and account details are the SAME for all items and CANNOT be changed after creation.
1401
1401
  - Mid-period cancellations or amount changes auto-generate prorated credit notes.
@@ -2186,7 +2186,7 @@ Accepts scheduling fields AND the full invoice template (same structure as POST)
2186
2186
  ```json
2187
2187
  // Request:
2188
2188
  {
2189
- "repeat": "QUARTERLY",
2189
+ "repeat": "MONTHLY",
2190
2190
  "startDate": "2026-03-01",
2191
2191
  "endDate": "2027-03-01",
2192
2192
  "invoice": {
@@ -432,7 +432,7 @@ DELETE → expects "A" (parentEntityResourceId, via /cash-entries/:id)
432
432
 
433
433
  | What You'd Guess | Actual API Field | Notes |
434
434
  |------------------|-------------------|-------|
435
- | `frequency` | `repeat` | Creation field. `"WEEKLY"`, `"MONTHLY"`, `"QUARTERLY"`, `"YEARLY"`. NOT `frequency` or `interval` |
435
+ | `frequency` | `repeat` | Creation field. `"ONE_TIME"`, `"DAILY"`, `"WEEKLY"`, `"MONTHLY"`, `"YEARLY"` (`"QUARTERLY"` rejected, 422). NOT `frequency` or `interval` |
436
436
  | `interval` (response) | `interval` | Response field. Shows the recurrence after creation. Different name from creation! |
437
437
  | (flat payload) | `{ invoice: {...} }` or `{ bill: {...} }` | Document wrapped in type key |
438
438
  | `saveAsDraft: true` | `saveAsDraft: false` | MUST be false — true causes INVALID_SALE_STATUS / INVALID_PURCHASE_STATUS |
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-cli
3
- version: 5.20.6
3
+ version: 5.20.8
4
4
  description: >-
5
5
  Use this skill when running Clio CLI commands, building shell scripts with
6
6
  Clio, debugging auth issues, understanding --json output, paginating results,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-conversion
3
- version: 5.20.6
3
+ version: 5.20.8
4
4
  description: >-
5
5
  Use this skill when migrating accounting data into Jaz — importing from Xero,
6
6
  QuickBooks, Sage, MYOB, or Excel exports. Covers the full conversion pipeline:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-pseudo-sql
3
- version: 5.20.6
3
+ version: 5.20.8
4
4
  description: >-
5
5
  Use this skill when answering ad-hoc data questions that aren't covered by
6
6
  download_export (canonical reports — anomaly, audit, aging, P&L, BS, GL,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-jobs
3
- version: 5.20.6
3
+ version: 5.20.8
4
4
  description: >-
5
5
  Use this skill for recurring accounting workflows — month/quarter/year-end
6
6
  close, bank reconciliation, GST/VAT filing, payment runs, credit control,
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: jaz-recipes
3
- version: 5.20.6
3
+ version: 5.20.8
4
4
  description: >-
5
5
  Use this skill when modeling complex multi-step accounting transactions —
6
6
  anything that spans multiple periods, involves changing amounts, or requires
package/cli.mjs CHANGED
@@ -677,7 +677,7 @@ Unsupported type: `+e.type,"ENOTSUP");e._finish()})};Rc.prototype._stat=function
677
677
  ---
678
678
  `,a),u=c!==-1?c:i.length;return i.slice(o,u).trim()}catch{return null}}function qmr(){let e=bXe(import.meta.url),t=EXe(e),r=[Nh(t,"..","..","..","help-center-mirror"),Nh(t,"..","..","..","assets","skills","api","help-center-mirror"),Nh(t,"help-center-mirror")];for(let n of r)try{return zae(Nh(n,"index.md"),"utf-8"),n}catch{}return null}var mXe,gXe,Fmr,Omr,Qmr,Lmr,Mmr,Pmr,$mr,Aj,yXe,Gae=re(()=>{"use strict";Yae();tb();mXe=1.2,gXe=.75,Fmr=1.5,Omr=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"]),Qmr=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"]]]);Lmr=.7,Mmr=3,Pmr=32,$mr=5;Aj=null,yXe=null});import{existsSync as jmr,readFileSync as Ymr}from"node:fs";import{dirname as zmr,join as Vae}from"node:path";import{fileURLToPath as Hmr}from"node:url";function WR(e){let t=e??Zmr();if(!t)return null;if(mj&&IXe===t)return mj;try{let r=Ymr(t,"utf-8");return mj=JSON.parse(r),IXe=t,mj}catch{return null}}function Zmr(){let e=Hmr(import.meta.url),t=zmr(e),r=[Vae(t,"..","..","..","help-center-mirror","help-center-embeddings.json"),Vae(t,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),Vae(t,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(jmr(n))return n;return null}function SXe(e,t){let r=Math.min(e.length,t.length),n=0;for(let i=0;i<r;i++)n+=e[i]*t[i];return n}function BXe(){return gj!==null?gj:(gj=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",gj||null)}async function Jae(e){let t=BXe();if(!t)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),Vmr),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({model:Gmr,input:e}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!_Xe&&(_Xe=!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 ZR(e,t,r,n={}){let i=n.mode??"hybrid",s=n.limit??5,o=n.section,a=n.minCosine??Jmr,c=n.minBm25??Wmr;if(i==="bm25"||!t)return Wg(e,r,{limit:s,section:o}).filter(m=>m.score>=c);if(i==="semantic"){let A=await Jae(r);return A?DXe(e,t,A,{limit:s,section:o}).filter(g=>g.score>=a):Wg(e,r,{limit:s,section:o}).filter(y=>y.score>=c)}let[u,f]=await Promise.all([Jae(r),Promise.resolve(Wg(e,r,{limit:s*2,section:o}))]);if(!u)return f.filter(A=>A.score>=c).slice(0,s);let p=DXe(e,t,u,{limit:s*2,section:o}).filter(A=>A.score>=a),h=f.filter(A=>A.score>=c);return RXe(p,h,s)}function DXe(e,t,r,n){let i=new Map(e.sections.map(c=>[c.slug,c])),s=new Map(e.articles.map(c=>[c.id,c])),o=[];for(let c of t.embeddings){let u=s.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let f=SXe(r,c.vector);o.push({articleId:c.articleId,score:f})}o.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of o.slice(0,n.limit)){let f=s.get(c);if(!f)continue;let d=i.get(f.section);d&&a.push({article:f,score:u,scoreKind:"cosine",section:d,matchedTerms:[]})}return a}function RXe(e,t,r){let n=new Map;for(let s=0;s<e.length;s++){let o=e[s],a=1/(wXe+s+1),c=n.get(o.article.id);c?c.score+=a:n.set(o.article.id,{score:a,result:o})}for(let s=0;s<t.length;s++){let o=t[s],a=1/(wXe+s+1),c=n.get(o.article.id);c?(c.score+=a,c.result=o):n.set(o.article.id,{score:a,result:o})}let i=Array.from(n.values());return i.sort((s,o)=>o.score-s.score),i.slice(0,r).map(s=>({...s.result,score:s.score,scoreKind:"rrf"}))}function Wae(e){return e!==null&&!!BXe()}var Gmr,Vmr,wXe,Jmr,Wmr,mj,IXe,gj,_Xe,Zae=re(()=>{"use strict";Gae();Gmr="text-embedding-3-small",Vmr=2e3,wXe=60,Jmr=.3,Wmr=1.5,mj=null,IXe=null,gj=null,_Xe=!1});var Kae=re(()=>{"use strict";Gae();Zae()});var xXe,TXe=re(()=>{"use strict";xXe={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 yj(e,t){let{blueprint:r,accountMap:n,finalize:i}=t,s=!i;Kmr(t);let o=await Xmr(e,r.capsuleType),a=r.steps[0]?.date??new Date().toISOString().slice(0,10),c=`${r.capsuleName} (${a})`,f={resourceId:(await Em(e,{capsuleTypeResourceId:o,title:c,description:r.capsuleDescription})).data.resourceId,type:r.capsuleType,title:c},d=FXe(t),p=[],h=[];for(let m of r.steps){if(m.step===d){p.push({step:m.step,action:m.action,status:"existing",resourceId:t.existingTxnId,description:m.description});continue}if(m.action==="fixed-asset"||m.action==="note"){p.push({step:m.step,action:m.action,status:"skipped",description:m.description}),h.push(`Step ${m.step} (${m.action}): ${m.description}`);continue}let g=await egr(e,m,t,s);p.push(g),g.error&&h.push(`Step ${m.step} failed: ${g.error}`)}let A={total:p.length,created:p.filter(m=>m.status==="created").length,existing:p.filter(m=>m.status==="existing").length,skipped:p.filter(m=>m.status==="skipped").length,errors:p.filter(m=>m.status==="error").length,notes:h};return{recipe:t.calcType,capsule:f,steps:p,summary:A}}function Kmr(e){let{blueprint:t,accountMap:r,bankAccountId:n,contactId:i}=e;if(!t.steps.length)throw new Error("Blueprint has no steps to execute.");let s=[];for(let f of t.steps)for(let d of f.lines)ece(d.account,r)||s.push(d.account);let o=[...new Set(s)];if(o.length>0)throw new Error(`Unmapped account(s) in --input: ${o.join(", ")}.
680
- Add these to your account mapping JSON.`);let a=FXe(e);if(t.steps.some(f=>(f.action==="cash-in"||f.action==="cash-out")&&f.step!==a)&&!n)throw new Error("--bank-account is required for recipes with cash-in/cash-out steps.");if(t.steps.some(f=>(f.action==="bill"||f.action==="invoice")&&f.step!==a)&&!i)throw new Error("--contact is required for recipes with bill/invoice steps.")}async function Xmr(e,t){let n=(await wb(e)).data.find(s=>s.displayName.toLowerCase()===t.toLowerCase());return n?n.resourceId:(await P_(e,{displayName:t})).data.resourceId}function FXe(e){if(!e.existingTxnId)return null;let t=xXe[e.calcType];return t?e.blueprint.steps.find(n=>t.includes(n.action))?.step??null:null}async function egr(e,t,r,n){let{accountMap:i,referencePrefix:s}=r,o=s?`${s}-${t.step}`:void 0;try{let a;switch(t.action){case"journal":{a=(await Dm(e,{reference:o,valueDate:t.date,journalEntries:Xae(t.lines,i),internalNotes:t.description,saveAsDraft:n})).data.resourceId;break}case"bill":{a=(await um(e,{reference:o,valueDate:t.date,dueDate:t.date,contactResourceId:r.contactId,lineItems:kXe(t.lines,i),invoiceNotes:t.description,saveAsDraft:n})).data.resourceId;break}case"invoice":{a=(await Im(e,{reference:o,valueDate:t.date,dueDate:t.date,contactResourceId:r.contactId,lineItems:kXe(t.lines,i),invoiceNotes:t.description,saveAsDraft:n})).data.resourceId;break}case"cash-in":{let{contraLines:c}=NXe(t.lines,r.bankAccountId,i);a=(await ev(e,{reference:o,valueDate:t.date,accountResourceId:r.bankAccountId,lines:Xae(c,i),internalNotes:t.description,saveAsDraft:n})).data?.resourceId;break}case"cash-out":{let{contraLines:c}=NXe(t.lines,r.bankAccountId,i);a=(await tv(e,{reference:o,valueDate:t.date,accountResourceId:r.bankAccountId,lines:Xae(c,i),internalNotes:t.description,saveAsDraft:n})).data?.resourceId;break}default:return{step:t.step,action:t.action,status:"skipped",description:t.description}}return{step:t.step,action:t.action,status:"created",resourceId:a,description:t.description}}catch(a){return{step:t.step,action:t.action,status:"error",description:t.description,error:a.message}}}function Xae(e,t){return e.map(r=>({accountResourceId:tce(r.account,t),type:r.debit>0?"DEBIT":"CREDIT",amount:r.debit>0?r.debit:r.credit}))}function kXe(e,t){return e.filter(r=>ece(r.account,t)).map(r=>({name:r.account,quantity:1,unitPrice:r.debit>0?r.debit:r.credit,accountResourceId:tce(r.account,t)}))}function NXe(e,t,r){let n=[],i=null;for(let s of e)tce(s.account,r)===t&&!i?i=s:n.push(s);return i?{bankLine:i,contraLines:n}:{bankLine:e[0],contraLines:e.slice(1)}}function ece(e,t){if(t[e])return e;let r=e.toLowerCase();for(let n of Object.keys(t))if(n.toLowerCase()===r)return n;return null}function tce(e,t){let r=ece(e,t);if(!r)throw new Error(`Unmapped account: "${e}"`);return t[r]}var rce=re(()=>{"use strict";Yb();Ud();_m();ej();U_();TXe()});async function OXe(e,t){let n=(await tp((o,a)=>Ef(e,{offset:o,limit:a}))).data;if(n.length===0)return{mapping:{},failures:t.map(o=>({name:o,candidates:[]}))};let i={},s=[];for(let o of t){let a=eL(o,n);if(a)i[o]=a.resourceId;else{let c=Tb(o,n,{threshold:.3,limit:3});s.push({name:o,candidates:c.map(u=>u.item.name)})}}return{mapping:i,failures:s}}async function QXe(e,t){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){let f=(await jd(e,t)).data;return{resourceId:f.resourceId,displayName:f.billingName||f.name||"Unknown"}}let n=t.trim(),s=(await oc(e,{filter:{billingName:{contains:n}},limit:50})).data;if(s.length===0&&(s=(await qd(e,{offset:0,limit:500})).data),s.length===0)throw new Error("No contacts found. Create one in Jaz first.");let o=n.toLowerCase(),a=s.find(u=>u.billingName?.toLowerCase()===o||u.name?.toLowerCase()===o);if(a)return{resourceId:a.resourceId,displayName:a.billingName||a.name||"Unknown"};let c=tL(n,s,{threshold:.5,limit:5});if(c.length>=1&&c[0].score>=.7){let u=c[0],f=c.length>1?c[1].score:0;if(c.length===1||u.score-f>=.1){let d=u.item;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}}if(c.length>1){let u=c.map(f=>`${f.item.billingName||f.item.name} (${(f.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 LXe(e,t){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){let i=await KE(e,t);return{resourceId:i.data.resourceId,displayName:i.data.name}}let n=await am(e,t);return{resourceId:n.resourceId,displayName:n.name}}var MXe=re(()=>{"use strict";xb();Yd();$d();AQ();MW();PW();iO()});async function Fh(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function Oh(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var KR=re(()=>{"use strict"});async function Ej(e,t){return e.post("/api/v1/transfer-trial-balance",t)}var nce=re(()=>{"use strict"});async function bj(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function Cj(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function XR(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function vj(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var ice=re(()=>{"use strict"});async function wj(e,t){return e.list("/api/v1/organization-users",t)}async function Ij(e,t){return e.search("/api/v1/organization-users/search",t)}async function nv(e,t){return e.post("/api/v1/organization-users/invite",t)}async function _j(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function Dj(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var sce=re(()=>{"use strict"});async function Sj(e,t){return e.search("/api/v1/cashflow-transactions/search",{limit:t?.limit??100,offset:t?.offset??0,sort:{sortBy:["valueDate"],order:"DESC"}})}async function ex(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}async function Bj(e,t){return e.get(`/api/v1/payments/${t}`)}async function Rj(e,t,r){return e.put(`/api/v1/payments/${t}`,r)}async function xj(e,t){await e.delete(`/api/v1/payments/${t}`)}var oce=re(()=>{"use strict"});async function Tj(e,t,r={}){let n=tgr.has(t)?`/api/v1/${t}`:`/api/v1/data-exports/${t}`;return e.post(n,r)}var tgr,ace=re(()=>{"use strict";tgr=new Set(["statement-of-account-export"])});import{createHash as rgr}from"node:crypto";import{writeFile as ngr,mkdir as igr}from"node:fs/promises";import{dirname as sgr,isAbsolute as ogr,join as agr}from"node:path";async function PXe(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t})}async function cce(e,t,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),e.post("/api/v1/reports/sql-query/export",{query:t},{headers:n})}async function uce(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function cgr(e){return rgr("sha256").update(e).digest("hex").slice(0,16)}async function $Xe(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=cgr(t),s=await cce(e,t,{idempotencyKey:i}),o=s.data.jobId,a=Date.now()+n*1e3,c=s.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 uce(e,o)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:o,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:o,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let f=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let d=process.env.HOME??".";if(r.outPath&&!ogr(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??agr(d,"Downloads",`pseudo-sql-${o}.csv`);return await igr(sgr(p),{recursive:!0}),await ngr(p,f),{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:f}}}async function UXe(e){let t=await e.get("/api/v1/reports/sql-query/schema"),r=t.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 t}var qXe=re(()=>{"use strict"});async function kj(e){return e.get("/api/v1/capsule-recipes")}async function Nj(e,t){return e.get(`/api/v1/capsule-recipes/${encodeURIComponent(t)}`)}async function Fj(e,t){return e.post("/api/v1/capsule-recipes/preview",t)}async function Oj(e,t){return e.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(t)}`)}async function Qj(e,t,r={}){return e.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(t)}`,{dryRun:r.dryRun??!1})}function ea(e){if(!e||typeof e!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let t=e;if(typeof t.recipeName!="string"||t.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(t.recipeVersion!==void 0&&(typeof t.recipeVersion!="number"||!Number.isInteger(t.recipeVersion)||t.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(t.inputs===null||t.inputs===void 0||typeof t.inputs!="object"||Array.isArray(t.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=>t[i]!==void 0&&t[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(t.templateOverrides!==void 0&&t.templateOverrides!==null){if(!Array.isArray(t.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;t.templateOverrides.forEach((s,o)=>{if(!s||typeof s!="object"||Array.isArray(s))throw new Error(`capsuleRecipe.templateOverrides[${o}] must be an object {slotKey, template?}.`);let a=s;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${o}].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[${o}].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 lce=re(()=>{"use strict"});async function ri(e,t,r){let n=await e.get(`/api/v1/${t}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(o=>({...o,resourceId:o.resourceId??o.attachmentResourceId??""})):[]}}async function Mj(e,t){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=t,s=new FormData;return i.file&&s.append("file",i.file,i.fileName??"file"),i.attachmentId&&s.append("attachmentId",i.attachmentId),e.postMultipart(`/api/v1/${r}/${n}/attachments`,s)}async function Pj(e,t,r,n){return e.delete(`/api/v1/${t}/${r}/attachments/${n}`)}var Lj,Qh=re(()=>{"use strict";Lj=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function Nl(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var fce=re(()=>{"use strict"});function jXe(e){return{source:e.source,sourceType:e.sourceType,...e.cloudProvider?{cloudProvider:e.cloudProvider}:{},summary:e.summary,files:e.folders.flatMap(t=>t.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 YXe=re(()=>{"use strict"});import{randomUUID as ugr}from"node:crypto";import{rmSync as lgr}from"node:fs";function pce(e){for(let t of e.tempDirs??[])try{lgr(t,{recursive:!0,force:!0})}catch{}}function HXe(e){for(let[t,r]of Zg)e-r.createdAt>zXe&&(pce(r.plan),Zg.delete(t))}function dgr(){dce||(dce=setInterval(()=>HXe(Date.now()),fgr),dce.unref?.())}function GXe(e,t){let r=Date.now();HXe(r),dgr();let n=`dc_${ugr()}`;return Zg.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function VXe(e,t){let r=Zg.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>zXe?(pce(r.plan),Zg.delete(e),null):r.plan}function JXe(e,t){let r=Zg.get(e);!r||r.ownerKey!==t||(pce(r.plan),Zg.delete(e))}var zXe,fgr,Zg,dce,WXe=re(()=>{"use strict";zXe=1800*1e3,fgr=300*1e3,Zg=new Map});function pgr(e){if(!e||typeof e!="object")return;let t=e;return t.validFiles?.[0]?.workflowResourceId??t.workflowResourceId}function hgr(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>GN(i.documentType)&&r.has(i.documentType))}))}}async function ZXe(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i}=e,s=i&&i.length>0?hgr(t,i):t;if(!n&&Agr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");let o=await sO({plan:s,client:r,bankAccountId:n}),a=o.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?pgr(u.response):void 0,error:u.error})),c=a.map(u=>u.workflowId).filter(u=>!!u);return{total:o.total,uploaded:o.success,skipped:a.filter(u=>u.status==="skipped").length,failed:o.failed,workflowIds:c,files:a}}function Agr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var KXe=re(()=>{"use strict";LJ();FA()});async function Fl(e,t,r){if(!t)return e;let n=mgr(e);if(!n)return e;try{return await r(n)}catch(i){let s=i instanceof Error?i.message:String(i),o={status:"failed",resourceId:n,message:s};return e&&typeof e=="object"?{...e,_hydration:o}:{result:e,_hydration:o}}}function mgr(e){if(!e||typeof e!="object")return;let t=e,r=t.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=t.resourceId;if(typeof n=="string"&&n.length>0)return n}var XXe=re(()=>{"use strict"});async function $j(e,t){return e.list("/api/v1/bank-rules",t)}async function tx(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let 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/${t}`)}async function Uj(e,t){return e.search("/api/v1/bank-rules/search",t)}async function qj(e,t){return e.post("/api/v1/bank-rules",t)}async function jj(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function Yj(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var hce=re(()=>{"use strict"});async function zj(e,t){return e.list("/api/v1/fixed-assets",t)}async function Hj(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function Gj(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function Vj(e,t){return e.post("/api/v1/fixed-assets",t)}async function Jj(e,t,r){return e.put(`/api/v1/fixed-assets/${t}`,r)}async function Wj(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function Zj(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t})}async function rx(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t)}async function Kj(e,t){return e.post("/api/v1/transfer-fixed-assets",t)}async function Xj(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{})}async function eY(e,t){return zs(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var tY=re(()=>{"use strict";sc()});async function rY(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function nx(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function nY(e,t){return e.post("/api/v1/scheduled/subscriptions",t)}async function iY(e,t,r){let n={...r};if(n.endDate){let i=!n.startDate,s=!n.repeat&&!n.interval;if(i||s){let o=await nx(e,t);if(i&&(n.startDate=o.data.startDate),s){if(!o.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=o.data.interval}}}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}async function sY(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function oY(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function aY(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var Ace=re(()=>{"use strict"});async function cY(e,t){return e.list("/api/v1/contact-groups",t)}async function uY(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function lY(e,t){return e.search("/api/v1/contact-groups/search",t)}async function fY(e,t){return e.post("/api/v1/contact-groups",t)}async function dY(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,r)}async function pY(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var mce=re(()=>{"use strict"});async function hY(e,t){return e.list("/api/v1/inventory-items",t)}async function AY(e,t){return e.post("/api/v1/inventory-items",t)}async function mY(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}var gce=re(()=>{"use strict"});async function gY(e,t){return e.list("/api/v1/custom-fields",t)}async function yY(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function EY(e,t){return e.search("/api/v1/custom-fields/search",t)}async function bY(e,t){return e.post("/api/v1/custom-fields",t)}async function CY(e,t,r){return e.put(`/api/v1/custom-fields/${t}`,r)}async function vY(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var yce=re(()=>{"use strict"});function eet(e){return{updated:e.updated??[],failed:(e.failed??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}}async function ix(e,t,r){let n=await e.post(`/api/v1/quick-fix/${t}`,r);return eet(n)}async function sx(e,t,r){let n=await e.post(`/api/v1/quick-fix/${t}/line-items`,r);return eet(n)}var ggr,ygr,Egr,iv,Ece=re(()=>{"use strict";ggr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],ygr=["journals","cash-entries"],Egr=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],iv=[...ggr,...ygr,...Egr]});async function wY(e,t){return e.list("/api/v1/nano-classifiers",t)}async function IY(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function _Y(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function ox(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function ax(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,r)}async function DY(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}var bce=re(()=>{"use strict"});async function SY(e,t){return e.post("/api/v1/export-records",t)}async function BY(e,t){return e.post("/api/v1/export-records/preview",t)}async function RY(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var Cce=re(()=>{"use strict"});async function cx(e,t={}){return e.search("/api/v1/background-jobs/search",t)}var vce=re(()=>{"use strict"});function sv(e){Ii(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!bgr.has(n.btType))throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.`)})}async function xY(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t});return{data:vgr(r.data)}}function Cgr(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function vgr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(Cgr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function TY(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function kY(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var bgr,wce=re(()=>{"use strict";sc();bgr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function net(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function Ice(e,t){if(!e||typeof e!="object")throw new Error(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${t}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${t}.lineItems per call.`);ic([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&ic([i],["valueDate"])}function _gr(e,t){let r=typeof t=="number"&&!Number.isNaN(t)?t:void 0,n=typeof e=="number"&&!Number.isNaN(e)?e:void 0;if(r!==void 0)return r>=wgr?"high":r>=tet?"medium":"low";if(n!==void 0){if(n>=Igr)return"high";if(n>=tet)return"medium"}return"low"}function iet(e,t={}){let r=e??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let s=[];for(let o of i){let a=o??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){s.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,alternativeCount:0});continue}let f=u.slice().sort((D,R)=>{let Q=D.confidenceScore??D.matchScore??-1;return(R.confidenceScore??R.matchScore??-1)-Q}),d=f[0],p=typeof d.recommendationType=="string"?d.recommendationType:void 0,h=typeof d.matchScore=="number"?d.matchScore:void 0,A=typeof d.confidenceScore=="number"?d.confidenceScore:void 0,m=typeof d.isCrossCurrency=="boolean"?d.isCrossCurrency:void 0,g=typeof d.cftBtResourceId=="string"?d.cftBtResourceId:void 0,y=Array.isArray(d.cftBtResourceIds)?d.cftBtResourceIds:[],C=d.isBatch===!0||y.length>1,E=typeof d.cftAmount=="number"?d.cftAmount:void 0,v,w;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(v=ux.magicMatch,w={...t.bankAccountResourceId?{bankAccountResourceId:t.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(v=ux.withPayments,w={bankStatementEntryResourceId:c,businessTransactionPayments:[{cashflowTransactionResourceId:g,...E!==void 0?{transactionAmount:E}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let D=typeof d.learnedPredictionResourceId=="string"?d.learnedPredictionResourceId:void 0,R=typeof d.predictedPayload=="string"?d.predictedPayload:void 0,Q=typeof d.predictedPayloadSchemaVersion=="string"?d.predictedPayloadSchemaVersion:void 0;D&&R&&Q&&(v=ux.learnedPrediction,w={bankStatementEntryResourceId:c,learnedPredictionResourceId:D,predictedPayload:R,predictedPayloadSchemaVersion:Q});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let D=d.actionShortcut??{},R=typeof D.resourceId=="string"?D.resourceId:void 0;R&&(v=ux.applyBankRule,w={actionShortcutResourceId:R,businessTransactionResourceIds:[c]});break}default:break}let T=v?_gr(h,A):"low",S=typeof E=="number"&&!Number.isNaN(E),k=!(t.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=t.autoCommitMaxAmount,Y=v!==ux.withPayments||S,U=T==="high"&&!!v&&!!w&&Y&&k;s.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:A,isCrossCurrency:m,recommendedTool:v,execute:w,confidenceTier:T,autoCommitEligible:U,alternativeCount:f.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return s}function Sgr(e,t,r){return{bankStatementEntryResourceId:e.bankStatementEntryResourceId,confidenceTier:e.confidenceTier,recommendationType:e.recommendationType,recommendedTool:e.recommendedTool,execute:e.execute,bankLine:t,match:r}}async function Bgr(e,t,r){let n=t.matchedTransactionResourceId,i=t.matchedTransactionCount;if(!n)return t.matchAmount!==void 0?{type:"transaction",amount:t.matchAmount,count:i}:null;let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let o of s)try{let{data:a}=o==="bill"?await go(e,n):await bo(e,n);return{type:o,reference:a.reference,amount:t.matchAmount??a.totalAmount,documentTotalAmount:a.totalAmount,count:i,resourceId:n}}catch{}return{type:"transaction",amount:t.matchAmount,count:i,resourceId:n}}async function set(e,t,r){let n=r.filter(s=>s.recommendedTool&&!s.autoCommitEligible).slice(0,Dgr);if(n.length===0)return[];let i=new Map;if(t)try{let s=await XE(e,t,{filter:{status:{eq:"UNRECONCILED"}},limit:500});for(let o of s.data??[])i.set(o.resourceId,o)}catch{}return Promise.all(n.map(async s=>{let o=i.get(s.bankStatementEntryResourceId),a=o?{valueDate:o.valueDate,netAmount:o.netAmount,currencyCode:o.currencyCode,currencySymbol:o.currencySymbol,description:o.description,counterparty:o.extContactName}:null;return Sgr(s,a,await Bgr(e,s,a?.netAmount))}))}async function NY(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t)}async function FY(e,t){return e.post("/api/v1/reconciliations/bank-rule",t)}async function OY(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t)}async function QY(e,t){return e.post("/api/v1/reconciliations/cash-journal",t)}async function LY(e,t){return e.post("/api/v1/reconciliations/manual-journal",t)}async function MY(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t)}async function PY(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t)}async function $Y(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t)}async function UY(e,t){return e.post("/api/v1/reconciliations/with-payments",t)}async function qY(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t)}async function jY(e,t){return e.post("/api/v1/reconciliations/magic-match",t)}var ux,wgr,Igr,tet,Dgr,_ce=re(()=>{"use strict";$d();Ud();sc();_m();ux={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},wgr=.9,Igr=.95,tet=.7;Dgr=25});function Bo(e,t,r="lineItems"){let n=[];for(let i of t)if(i.perLineItem){let s=e[r]??[];for(let o=0;o<s.length;o++)i.check(s[o])||n.push(`${r}[${o}].${i.field}`)}else i.check(e)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function as(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),s={valueDate:Dce(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(s.contact=Dce(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(s.dueDate=Dce(e,"dueDate","Due date","--due <YYYY-MM-DD>",n));let o=e[r]??[];return s.lineItems=o.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,f=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let m=i.find(w=>w.field==="amount"),g=m?m.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:f}}let d=i.find(m=>m.field==="name"),p=i.find(m=>m.field==="unitPrice"),h=d?d.check(a):!0,A=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:A?"ok":"missing",account:f}}),s}function Dce(e,t,r,n,i){let s=i.find(o=>o.field===t);if(!s){let o=e[t];return o?{status:"ok",value:o}:{status:"ok"}}if(s.check(e)){let o=e[t];return t==="contactResourceId"?{status:"ok",value:e.contactName||o,resourceId:o}:{status:"ok",value:o}}return{status:"missing",hint:n}}function _s(e,t,r,n="lineItems"){let{missingFields:i,missingCount:s,ready:o}=Bo(e,t,n),a=as(e,t,n);return{resourceId:e.resourceId,reference:e.reference||null,totalAmount:e.totalAmount??0,attachmentCount:r,ready:o,missingCount:s,missingFields:i,validation:a}}var ta,xc,Vi,xu,oet=re(()=>{"use strict";ta=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:e=>!!e.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:e=>e.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:e=>!!e.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:e=>e.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0}],xc=[...ta],Vi=ta.filter(e=>e.field!=="dueDate"),xu=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:e=>e.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:e=>e.amount!=null&&e.amount>0||e.debitAmount!=null&&e.debitAmount>0||e.creditAmount!=null&&e.creditAmount>0,perLineItem:!0}]});function Tc(e){let t={};e.name!=null&&(t.name=e.name),e.quantity!=null&&(t.quantity=e.quantity),e.unitPrice!=null&&(t.unitPrice=e.unitPrice),e.unit&&(t.unit=e.unit);let r=e.accountResourceId||e.organizationAccountResourceId;r&&(t.accountResourceId=r);let n=e.taxProfileResourceId||(e.taxProfile&&typeof e.taxProfile=="object"?e.taxProfile.resourceId:null);return n&&(t.taxProfileResourceId=n),e.itemResourceId&&(t.itemResourceId=e.itemResourceId),e.discount!=null&&(t.discount=typeof e.discount=="object"?e.discount.rateValue??0:e.discount),t}function ov(e){let t={},r=e.accountResourceId||e.organizationAccountResourceId;return r&&(t.accountResourceId=r),e.amount!=null?t.amount=e.amount:e.debitAmount!=null&&e.debitAmount>0?t.amount=e.debitAmount:e.creditAmount!=null&&e.creditAmount>0&&(t.amount=e.creditAmount),e.type?t.type=e.type:e.debitAmount!=null&&e.debitAmount>0?t.type="DEBIT":e.creditAmount!=null&&e.creditAmount>0&&(t.type="CREDIT"),e.description&&(t.description=e.description),e.contactResourceId&&(t.contactResourceId=e.contactResourceId),t}function Ft(e){if(e)return e.split("T")[0]}var Sce=re(()=>{"use strict"});function Ol(e,t){let r={};if(t.contact&&(r.contactResourceId=t.contact),t.date&&(r.valueDate=t.date),t.due&&(r.dueDate=t.due),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.tag!==void 0&&(r.tag=t.tag),t.tax&&(r.isTaxVatApplicable=!0),t.tax&&t.taxInclusive?r.taxInclusion=!0:t.tax&&(r.taxInclusion=!1),t.lines)r.lineItems=t.lines;else if(t.account||t.taxProfile){let n=e.lineItems??[];r.lineItems=n.map(i=>{let s=Tc(i);return t.account&&!s.accountResourceId&&(s.accountResourceId=t.account),t.taxProfile&&!s.taxProfileResourceId&&(s.taxProfileResourceId=t.taxProfile),s})}return r}function YY(e,t){let r={};if(t.date&&(r.valueDate=t.date),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.entries)r.journalEntries=t.entries;else if(t.account){let n=e.journalEntries??[];r.journalEntries=n.map(i=>{let s=ov(i);return t.account&&!s.accountResourceId&&(s.accountResourceId=t.account),s})}return r}var aet=re(()=>{"use strict";Sce()});var Bce=re(()=>{"use strict";oet();Sce();aet()});var lx,Tu,cet=re(()=>{"use strict";lx="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",Tu="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function _et(e){let t=e.limit,r=e.offset;return{limit:t,offset:r,sortBy:void 0,sortOrder:void 0}}function cn(e,t,r,n,i,s){let o={...Nce};return s?.leanView&&(o.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). List lean, then drill in with get_*."}),{name:e,description:t,params:o,required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(a,c)=>{let{limit:u,offset:f}=_et(c),d=s?.leanView?c.view==="full"?"full":"lean":void 0;return eD((h,A)=>n(a.client,h,A,d),u,f,d==="lean"?50:20)}}}function Qa(e,t,r,n,i){return{name:e,description:t,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(s,o)=>n(s.client,o.resourceId)}}function Ro(e,t,r,n,i){return{name:e,description:t,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(s,o)=>(await n(s.client,o.resourceId),{deleted:!0,resourceId:o.resourceId})}}function met(e){if(typeof e!="string"||/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let t=/^(\d{4}-\d{2}-\d{2})T/.exec(e);return t?t[1]:e}function Fgr(e){return Array.isArray(e)?e.map(t=>{let r={};for(let[n,i]of Object.entries(t))if(i!=null)if(n==="organizationAccountResourceId")r.accountResourceId=i;else if(n==="taxProfile"&&typeof i=="object"&&i!==null){let s=i.resourceId;s&&(r.taxProfileResourceId=s)}else if(n==="discount"&&typeof i=="object"&&i!==null){let s=i.rateValue;s&&Number(s)!==0&&(r.discount=i)}else Ngr.has(n)&&(r[n]=i);return r}):e}async function dx(e,t,r,n){let o=(await(t==="invoice"?bo:t==="bill"?go:t==="customer_credit_note"?mu:gu)(e,r)).data,a=kgr[t],c={};for(let[p,h]of Object.entries(o))a.has(p)&&h!==null&&h!==void 0&&(c[p]=h);c.valueDate&&(c.valueDate=met(c.valueDate)),c.dueDate&&(c.dueDate=met(c.dueDate)),c.lineItems&&(c.lineItems=Fgr(c.lineItems));for(let[p,h]of Object.entries(n))h!==void 0&&(c[p]=h);let u=t==="invoice"?xc:t==="bill"?ta:Vi,{missingFields:f,ready:d}=Bo(c,u);if(!d)throw new Error(`Cannot finalize: missing ${f.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function get(e,t,r,n){if((await e(t,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function GY(e,t,r){if(!(typeof e=="string"&&t.includes(e)))return{error:`Unknown documentType ${JSON.stringify(e)}.`,status:422,hint:`Use one of: ${t.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}function bet(e,t,r){let n=Eet[e];if(!n)return{error:`Unknown documentType "${e}".`,status:422,hint:`Valid document types: ${Object.keys(Eet).join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}};if(!n.includes(t)){let i=n.includes("ACCEPT")?"ACCEPT":"CONFIRM";return{error:`Action "${t}" is not valid for ${e}. Valid actions: ${n.join(", ")}.`,status:422,hint:`${e} advances its lifecycle with ${i}, not ${t}.`,repair:{tool:r,arguments:{documentType:e,action:i},reason:`${e} is advanced with ${i}.`}}}}async function Cet(e,t,r,n,i,s,o){let a;try{a=(await t(e,r)).data?.status}catch{return}if(a==="DRAFT"||a==="VOID"){let c=a==="DRAFT"?`A DRAFT ${n} can't be linked or accepted \u2014 issue it by creating the ${n} with saveAsDraft:false (status ${o}), then link the order to that one.`:`A VOID ${n} can't be used \u2014 create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a ${a} ${n} (${r}).`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. ${c}`,repair:{tool:s,arguments:{documentType:i,saveAsDraft:!1},reason:c}}}}async function vet(e,t,r,n,i,s){let o;try{o=(await t(e,r)).data?.status}catch{return}if(o==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:s,arguments:{},reason:`The source ${n} is VOID.`}}}async function wet(e,t,r,n,i){let s;try{s=(await t(e,r,n)).data?.status}catch{return}if(s&&s!=="DRAFT")return{error:`Cannot DELETE a ${s} ${r} \u2014 delete is only allowed on DRAFT records.`,status:422,hint:"Use action VOID to cancel a non-draft quote/request/order.",repair:{tool:i,arguments:{documentType:r,resourceId:n,action:"VOID"},reason:`${r} is ${s}; void it instead of deleting.`}}}var La,cs,ku,us,ni,Ql,zY,Kg,Rce,ty,Rgr,xgr,xce,uet,fet,Tce,Nce,Xg,kce,det,pet,het,Aet,Ji,Tgr,ey,ra,Iet,Ll,fx,kgr,Ngr,px,hx,HY,yet,Eet,kc,av=re(()=>{"use strict";LFe();jFe();Z_();Vu();Jr();ip();TA();xb();Yd();_m();Ud();l5();f5();Yb();d5();$d();NQ();HQ();U_();uM();mM();vM();dXe();q_();ej();Pae();$ae();Uae();qae();Kae();rce();MXe();$d();KR();nce();ice();sce();oce();ace();qXe();lce();Qh();fce();rO();NJ();YXe();WXe();KXe();s5();XXe();hce();tY();Ace();mce();gce();yce();Ece();bce();Cce();vce();Yd();_m();Ud();uM();mM();Yb();tY();sc();wce();_ce();Jr();Bce();cet();La={type:"string",description:"Resource ID of the record"},cs={type:"string",description:"Transaction date (YYYY-MM-DD)"},ku={type:"string",description:"Due date (YYYY-MM-DD)"},us={type:"string",description:"Reference number"},ni={type:"string",description:"Notes or memo text"},Ql={type:"string",description:"Tag name for categorization"},zY={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},Kg={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},Rce={type:"string",description:"Contact resourceId (customer or supplier)"},ty={type:"string",description:"Bank/cash account resourceId"},Rgr={type:"number",description:"Payment amount (in bank currency)"},xgr={type:"string",description:"Period start date (YYYY-MM-DD)"},xce={type:"string",description:"Period end date (YYYY-MM-DD)"},uet={type:"string",enum:["full","aggregate"],description:`Output detail (default 'full'). 'aggregate' returns a compact aging-bucket summary (current, <1 month, 1/2/3 months, older + total outstanding + contact count). Prefer 'aggregate' for a general or unqualified report request (e.g. "show me my aged receivables", "my AR report") \u2014 it's the at-a-glance overview a chat user expects and it won't truncate on large orgs. Use 'full' only when the user explicitly asks for the per-contact (customer/supplier) breakdown for deeper analysis.`},fet={type:"string",description:"Currency code (e.g. SGD, USD)"},Tce={type:"string",description:"Display name"},Nce={limit:{type:"number",description:"Max results per page (\u22641000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},Xg={type:"object",properties:{sourceCurrency:{type:"string"},exchangeRate:{type:"number"}}},kce={type:"string",enum:[...Cf],description:"Entity type to export"},det={type:"string",description:'Structured search query using dashboard syntax (e.g., "status:unpaid $500+ date:this month"). Mutually exclusive with filter \u2014 pass one or the other, never both.'},pet={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},het={type:"array",items:{type:"object",properties:{path:{type:"string",description:"Column path from get_export_columns (e.g., s.reference)"},header:{type:"string",description:"Column header label in the export file"},type:{type:"string",enum:["STRING","NUMBER","CURRENCY","DATE","BOOLEAN"],description:"Column data type (optional)"}},required:["path","header"]},description:"Custom column definitions. Omit to use default columns. Use get_export_columns to discover available paths."},Aet={type:"object",properties:{field:{type:"string",description:"Column path to sort by (e.g., s.total_amount)"},direction:{type:"string",enum:["ASC","DESC"],description:"Sort direction"}},required:["field"],description:"Sort results by a column path."},Ji={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},Tgr={type:"array",items:{type:"object",properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",properties:{className:{type:"string"},resourceId:La}}},printable:{type:"boolean"}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},ey={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account resourceId"},type:{type:"string",enum:["DEBIT","CREDIT"],description:"Debit or credit"},amount:{type:"number",description:"Amount"},description:{type:"string",description:"Line description"}},required:["accountResourceId","type","amount"]},description:"Journal entries (debit/credit lines with accountResourceId, type, amount)"},ra={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:ty,taxProfileResourceId:{type:"string"},classifierConfig:Tgr},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},Iet={type:"array",items:{type:"object",properties:{slotKey:{type:"string",description:"Slot from get_capsule_recipe templateSlots[]."},template:{type:"string",description:"Text with {{vars}} for that slot; empty string clears a nullable slot. Max 2000."}},required:["slotKey"]},description:"Optional. Customize recipe-generated text via published slots (see get_capsule_recipe)."},Ll={type:"object",description:"Optional IFRS recipe trigger. Mutex with capsuleResourceId. Silent-null on failure \u2014 preview_capsule_recipe first. Rule 143.",properties:{recipeName:{type:"string",description:"list_capsule_recipes enum. Must match mutation's allowedBaseTransactionTypes."},recipeVersion:{type:"number",description:"Optional version pin."},inputs:{type:"object",description:"Schema at versions[0].inputSchema. Single-currency; *AccountResourceId x-accountClass-locked."},templateOverrides:Iet},required:["recipeName","inputs"]},fx={type:"string",enum:[...h1e],description:"Payment method (default BANK_TRANSFER)"};kgr={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId"]),customer_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"]),supplier_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"])};Ngr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);px={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},hx={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},HY={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."},yet={type:"string",enum:["ACCEPT","CONFIRM","VOID","DELETE"],description:"Lifecycle action. ACCEPT=quote/request only; CONFIRM=order only; VOID=any non-draft; DELETE=draft only."},Eet={SALE_QUOTE:["ACCEPT","VOID","DELETE"],SALE_ORDER:["CONFIRM","VOID","DELETE"],PURCHASE_REQUEST:["ACCEPT","VOID","DELETE"],PURCHASE_ORDER:["CONFIRM","VOID","DELETE"]};kc=[{name:"get_organization",description:"Get organization details: name, base currency, country, and financial year end.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>pa(e.client)},cn("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(e,t,r)=>Ef(e,{limit:r,offset:t}),"list chart of accounts with code type class status"),tn({name:"search_accounts",description:'Search chart of accounts. For OR (name or code), use filter: {"or":{"name":{"contains":"X"},"code":{"contains":"X"}}}.',group:"accounts",fields:wD,defaults:ID,fetcher:Rb,searchHint:"find accounts chart of accounts CoA by name code type class status OR search"}),{name:"create_account",description:"Create a new chart of accounts entry. Auto-checks for duplicates by name \u2014 returns existing account if found. Code must be unique. Account class is inferred from accountType.",params:{name:{type:"string",description:"Account name"},code:{type:"string",description:"Account code (unique)"},accountType:{type:"string",description:'Exact API string. Classic 12: Bank Accounts | Cash | Current Asset | Fixed Asset | Inventory | Current Liability | Non-current Liability | Shareholders Equity | Operating Revenue | Other Revenue | Operating Expense | Direct Costs. IFRS 18 (effective 2027): Discontinued Expense | Discontinued Income | Finance Cost | Financing Income | Goodwill | Income Tax Expense | Investing Expense | Investing Income | Investment. Common variants normalized client-side. For "interest expense"/"interest income", pick Financing or Investing yourself \u2014 depends on entity main business activity, NOT auto-classified.'},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code lock date",execute:async(e,t)=>{let r=t.name,n=await VQ(e.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=Bb(t.accountType);return z_(e.client,{code:t.code,name:r,accountType:i,currencyCode:t.currencyCode,lockDate:t.lockDate})}},{name:"update_account",description:"Update a chart of accounts entry \u2014 rename, re-code, set its period lock date, or remove an existing lock date. Setting lockDate (YYYY-MM-DD) is how an individual ledger account is locked for a period: it blocks recording or editing any transaction on that account dated on or before the lock date. Pass clearLockDate to remove (unlock) an existing lock.",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."},clearLockDate:{type:"boolean",description:"Set true to remove an existing period lock date (unlock the period). Use when the user asks to remove, delete, clear, lift, or unset the lock. Do not also pass lockDate."}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code lock date unlock remove clear lock",execute:async(e,t)=>{let r=t.resourceId,n=(await KNe(e.client,r)).data,s=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(a=>n[a]!==void 0&&n[a]!==null).map(a=>[a,n[a]]));!s.classificationType&&n.accountType&&(s.classificationType=n.accountType);let o=t.clearLockDate===!0;if(o&&t.lockDate!==void 0)throw new Error("clearLockDate and lockDate are mutually exclusive \u2014 pass one or the other.");return!o&&typeof n.accountLockDate=="string"&&n.accountLockDate&&(s.lockDate=n.accountLockDate.slice(0,10)),t.name!==void 0&&(s.name=t.name),t.code!==void 0&&(s.code=t.code),!o&&t.lockDate!==void 0&&(s.lockDate=t.lockDate),XNe(e.client,r,s)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount } \u2014 no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
680
+ Add these to your account mapping JSON.`);let a=FXe(e);if(t.steps.some(f=>(f.action==="cash-in"||f.action==="cash-out")&&f.step!==a)&&!n)throw new Error("--bank-account is required for recipes with cash-in/cash-out steps.");if(t.steps.some(f=>(f.action==="bill"||f.action==="invoice")&&f.step!==a)&&!i)throw new Error("--contact is required for recipes with bill/invoice steps.")}async function Xmr(e,t){let n=(await wb(e)).data.find(s=>s.displayName.toLowerCase()===t.toLowerCase());return n?n.resourceId:(await P_(e,{displayName:t})).data.resourceId}function FXe(e){if(!e.existingTxnId)return null;let t=xXe[e.calcType];return t?e.blueprint.steps.find(n=>t.includes(n.action))?.step??null:null}async function egr(e,t,r,n){let{accountMap:i,referencePrefix:s}=r,o=s?`${s}-${t.step}`:void 0;try{let a;switch(t.action){case"journal":{a=(await Dm(e,{reference:o,valueDate:t.date,journalEntries:Xae(t.lines,i),internalNotes:t.description,saveAsDraft:n})).data.resourceId;break}case"bill":{a=(await um(e,{reference:o,valueDate:t.date,dueDate:t.date,contactResourceId:r.contactId,lineItems:kXe(t.lines,i),invoiceNotes:t.description,saveAsDraft:n})).data.resourceId;break}case"invoice":{a=(await Im(e,{reference:o,valueDate:t.date,dueDate:t.date,contactResourceId:r.contactId,lineItems:kXe(t.lines,i),invoiceNotes:t.description,saveAsDraft:n})).data.resourceId;break}case"cash-in":{let{contraLines:c}=NXe(t.lines,r.bankAccountId,i);a=(await ev(e,{reference:o,valueDate:t.date,accountResourceId:r.bankAccountId,lines:Xae(c,i),internalNotes:t.description,saveAsDraft:n})).data?.resourceId;break}case"cash-out":{let{contraLines:c}=NXe(t.lines,r.bankAccountId,i);a=(await tv(e,{reference:o,valueDate:t.date,accountResourceId:r.bankAccountId,lines:Xae(c,i),internalNotes:t.description,saveAsDraft:n})).data?.resourceId;break}default:return{step:t.step,action:t.action,status:"skipped",description:t.description}}return{step:t.step,action:t.action,status:"created",resourceId:a,description:t.description}}catch(a){return{step:t.step,action:t.action,status:"error",description:t.description,error:a.message}}}function Xae(e,t){return e.map(r=>({accountResourceId:tce(r.account,t),type:r.debit>0?"DEBIT":"CREDIT",amount:r.debit>0?r.debit:r.credit}))}function kXe(e,t){return e.filter(r=>ece(r.account,t)).map(r=>({name:r.account,quantity:1,unitPrice:r.debit>0?r.debit:r.credit,accountResourceId:tce(r.account,t)}))}function NXe(e,t,r){let n=[],i=null;for(let s of e)tce(s.account,r)===t&&!i?i=s:n.push(s);return i?{bankLine:i,contraLines:n}:{bankLine:e[0],contraLines:e.slice(1)}}function ece(e,t){if(t[e])return e;let r=e.toLowerCase();for(let n of Object.keys(t))if(n.toLowerCase()===r)return n;return null}function tce(e,t){let r=ece(e,t);if(!r)throw new Error(`Unmapped account: "${e}"`);return t[r]}var rce=re(()=>{"use strict";Yb();Ud();_m();ej();U_();TXe()});async function OXe(e,t){let n=(await tp((o,a)=>Ef(e,{offset:o,limit:a}))).data;if(n.length===0)return{mapping:{},failures:t.map(o=>({name:o,candidates:[]}))};let i={},s=[];for(let o of t){let a=eL(o,n);if(a)i[o]=a.resourceId;else{let c=Tb(o,n,{threshold:.3,limit:3});s.push({name:o,candidates:c.map(u=>u.item.name)})}}return{mapping:i,failures:s}}async function QXe(e,t){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){let f=(await jd(e,t)).data;return{resourceId:f.resourceId,displayName:f.billingName||f.name||"Unknown"}}let n=t.trim(),s=(await oc(e,{filter:{billingName:{contains:n}},limit:50})).data;if(s.length===0&&(s=(await qd(e,{offset:0,limit:500})).data),s.length===0)throw new Error("No contacts found. Create one in Jaz first.");let o=n.toLowerCase(),a=s.find(u=>u.billingName?.toLowerCase()===o||u.name?.toLowerCase()===o);if(a)return{resourceId:a.resourceId,displayName:a.billingName||a.name||"Unknown"};let c=tL(n,s,{threshold:.5,limit:5});if(c.length>=1&&c[0].score>=.7){let u=c[0],f=c.length>1?c[1].score:0;if(c.length===1||u.score-f>=.1){let d=u.item;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}}if(c.length>1){let u=c.map(f=>`${f.item.billingName||f.item.name} (${(f.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 LXe(e,t){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)){let i=await KE(e,t);return{resourceId:i.data.resourceId,displayName:i.data.name}}let n=await am(e,t);return{resourceId:n.resourceId,displayName:n.name}}var MXe=re(()=>{"use strict";xb();Yd();$d();AQ();MW();PW();iO()});async function Fh(e,t){await e.delete(`/api/v1/cash-entries/${t}`)}async function Oh(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}var KR=re(()=>{"use strict"});async function Ej(e,t){return e.post("/api/v1/transfer-trial-balance",t)}var nce=re(()=>{"use strict"});async function bj(e,t){return e.list("/api/v1/organization/bookmarks",t)}async function Cj(e,t){return e.get(`/api/v1/organization/bookmarks/${t}`)}async function XR(e,t){return e.post("/api/v1/organization/bookmarks",{items:t})}async function vj(e,t,r){return e.put(`/api/v1/organization/bookmarks/${t}`,r)}var ice=re(()=>{"use strict"});async function wj(e,t){return e.list("/api/v1/organization-users",t)}async function Ij(e,t){return e.search("/api/v1/organization-users/search",t)}async function nv(e,t){return e.post("/api/v1/organization-users/invite",t)}async function _j(e,t,r){return e.put(`/api/v1/organization-users/${t}`,r)}async function Dj(e,t){await e.delete(`/api/v1/organization-users/${t}`)}var sce=re(()=>{"use strict"});async function Sj(e,t){return e.search("/api/v1/cashflow-transactions/search",{limit:t?.limit??100,offset:t?.offset??0,sort:{sortBy:["valueDate"],order:"DESC"}})}async function ex(e,t){return e.search("/api/v1/cashflow-transactions/search",t)}async function Bj(e,t){return e.get(`/api/v1/payments/${t}`)}async function Rj(e,t,r){return e.put(`/api/v1/payments/${t}`,r)}async function xj(e,t){await e.delete(`/api/v1/payments/${t}`)}var oce=re(()=>{"use strict"});async function Tj(e,t,r={}){let n=tgr.has(t)?`/api/v1/${t}`:`/api/v1/data-exports/${t}`;return e.post(n,r)}var tgr,ace=re(()=>{"use strict";tgr=new Set(["statement-of-account-export"])});import{createHash as rgr}from"node:crypto";import{writeFile as ngr,mkdir as igr}from"node:fs/promises";import{dirname as sgr,isAbsolute as ogr,join as agr}from"node:path";async function PXe(e,t){return e.post("/api/v1/reports/sql-query/preview",{query:t})}async function cce(e,t,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),e.post("/api/v1/reports/sql-query/export",{query:t},{headers:n})}async function uce(e,t){return e.get(`/api/v1/reports/sql-query/export/${t}`)}function cgr(e){return rgr("sha256").update(e).digest("hex").slice(0,16)}async function $Xe(e,t,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=cgr(t),s=await cce(e,t,{idempotencyKey:i}),o=s.data.jobId,a=Date.now()+n*1e3,c=s.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 uce(e,o)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:o,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:o,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let f=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let d=process.env.HOME??".";if(r.outPath&&!ogr(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??agr(d,"Downloads",`pseudo-sql-${o}.csv`);return await igr(sgr(p),{recursive:!0}),await ngr(p,f),{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:o,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:f}}}async function UXe(e){let t=await e.get("/api/v1/reports/sql-query/schema"),r=t.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 t}var qXe=re(()=>{"use strict"});async function kj(e){return e.get("/api/v1/capsule-recipes")}async function Nj(e,t){return e.get(`/api/v1/capsule-recipes/${encodeURIComponent(t)}`)}async function Fj(e,t){return e.post("/api/v1/capsule-recipes/preview",t)}async function Oj(e,t){return e.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(t)}`)}async function Qj(e,t,r={}){return e.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(t)}`,{dryRun:r.dryRun??!1})}function ea(e){if(!e||typeof e!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let t=e;if(typeof t.recipeName!="string"||t.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(t.recipeVersion!==void 0&&(typeof t.recipeVersion!="number"||!Number.isInteger(t.recipeVersion)||t.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(t.inputs===null||t.inputs===void 0||typeof t.inputs!="object"||Array.isArray(t.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=>t[i]!==void 0&&t[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(t.templateOverrides!==void 0&&t.templateOverrides!==null){if(!Array.isArray(t.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;t.templateOverrides.forEach((s,o)=>{if(!s||typeof s!="object"||Array.isArray(s))throw new Error(`capsuleRecipe.templateOverrides[${o}] must be an object {slotKey, template?}.`);let a=s;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${o}].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[${o}].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 lce=re(()=>{"use strict"});async function ri(e,t,r){let n=await e.get(`/api/v1/${t}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(o=>({...o,resourceId:o.resourceId??o.attachmentResourceId??""})):[]}}async function Mj(e,t){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=t,s=new FormData;return i.file&&s.append("file",i.file,i.fileName??"file"),i.attachmentId&&s.append("attachmentId",i.attachmentId),e.postMultipart(`/api/v1/${r}/${n}/attachments`,s)}async function Pj(e,t,r,n){return e.delete(`/api/v1/${t}/${r}/attachments/${n}`)}var Lj,Qh=re(()=>{"use strict";Lj=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function Nl(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var fce=re(()=>{"use strict"});function jXe(e){return{source:e.source,sourceType:e.sourceType,...e.cloudProvider?{cloudProvider:e.cloudProvider}:{},summary:e.summary,files:e.folders.flatMap(t=>t.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 YXe=re(()=>{"use strict"});import{randomUUID as ugr}from"node:crypto";import{rmSync as lgr}from"node:fs";function pce(e){for(let t of e.tempDirs??[])try{lgr(t,{recursive:!0,force:!0})}catch{}}function HXe(e){for(let[t,r]of Zg)e-r.createdAt>zXe&&(pce(r.plan),Zg.delete(t))}function dgr(){dce||(dce=setInterval(()=>HXe(Date.now()),fgr),dce.unref?.())}function GXe(e,t){let r=Date.now();HXe(r),dgr();let n=`dc_${ugr()}`;return Zg.set(n,{plan:e,createdAt:r,ownerKey:t}),n}function VXe(e,t){let r=Zg.get(e);return!r||r.ownerKey!==t?null:Date.now()-r.createdAt>zXe?(pce(r.plan),Zg.delete(e),null):r.plan}function JXe(e,t){let r=Zg.get(e);!r||r.ownerKey!==t||(pce(r.plan),Zg.delete(e))}var zXe,fgr,Zg,dce,WXe=re(()=>{"use strict";zXe=1800*1e3,fgr=300*1e3,Zg=new Map});function pgr(e){if(!e||typeof e!="object")return;let t=e;return t.validFiles?.[0]?.workflowResourceId??t.workflowResourceId}function hgr(e,t){let r=new Set(t);return{...e,folders:e.folders.map(n=>({...n,files:n.files.filter(i=>GN(i.documentType)&&r.has(i.documentType))}))}}async function ZXe(e){let{plan:t,client:r,bankAccountId:n,documentTypes:i}=e,s=i&&i.length>0?hgr(t,i):t;if(!n&&Agr(s))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");let o=await sO({plan:s,client:r,bankAccountId:n}),a=o.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?pgr(u.response):void 0,error:u.error})),c=a.map(u=>u.workflowId).filter(u=>!!u);return{total:o.total,uploaded:o.success,skipped:a.filter(u=>u.status==="skipped").length,failed:o.failed,workflowIds:c,files:a}}function Agr(e){return e.folders.some(t=>t.files.some(r=>r.documentType==="BANK_STATEMENT"))}var KXe=re(()=>{"use strict";LJ();FA()});async function Fl(e,t,r){if(!t)return e;let n=mgr(e);if(!n)return e;try{return await r(n)}catch(i){let s=i instanceof Error?i.message:String(i),o={status:"failed",resourceId:n,message:s};return e&&typeof e=="object"?{...e,_hydration:o}:{result:e,_hydration:o}}}function mgr(e){if(!e||typeof e!="object")return;let t=e,r=t.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=t.resourceId;if(typeof n=="string"&&n.length>0)return n}var XXe=re(()=>{"use strict"});async function $j(e,t){return e.list("/api/v1/bank-rules",t)}async function tx(e,t){let r=await e.get(`/api/v1/bank-rules/${t}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let 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/${t}`)}async function Uj(e,t){return e.search("/api/v1/bank-rules/search",t)}async function qj(e,t){return e.post("/api/v1/bank-rules",t)}async function jj(e,t,r){return e.put(`/api/v1/bank-rules/${t}`,r)}async function Yj(e,t){await e.delete(`/api/v1/bank-rules/${t}`)}var hce=re(()=>{"use strict"});async function zj(e,t){return e.list("/api/v1/fixed-assets",t)}async function Hj(e,t){return e.get(`/api/v1/fixed-assets/${t}`)}async function Gj(e,t){return e.search("/api/v1/fixed-assets/search",{...t,sort:t.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function Vj(e,t){return e.post("/api/v1/fixed-assets",t)}async function Jj(e,t,r){return e.put(`/api/v1/fixed-assets/${t}`,r)}async function Wj(e,t){await e.delete(`/api/v1/fixed-assets/${t}`)}async function Zj(e,t,r){return e.post(`/api/v1/discard-fixed-assets/${t}`,{...r,resourceId:t})}async function rx(e,t){return e.post("/api/v1/mark-as-sold/fixed-assets",t)}async function Kj(e,t){return e.post("/api/v1/transfer-fixed-assets",t)}async function Xj(e,t){return e.post(`/api/v1/undo-disposal/fixed-assets/${t}`,{})}async function eY(e,t){return zs(e,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",t)}var tY=re(()=>{"use strict";sc()});async function rY(e,t){return e.list("/api/v1/scheduled/subscriptions",t)}async function nx(e,t){return e.get(`/api/v1/scheduled/subscriptions/${t}`)}async function nY(e,t){return e.post("/api/v1/scheduled/subscriptions",t)}async function iY(e,t,r){let n={...r};if(n.endDate){let i=!n.startDate,s=!n.repeat&&!n.interval;if(i||s){let o=await nx(e,t);if(i&&(n.startDate=o.data.startDate),s){if(!o.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=o.data.interval}}}return e.put(`/api/v1/scheduled/subscriptions/${t}`,n)}async function sY(e,t){await e.delete(`/api/v1/scheduled/subscriptions/${t}`)}async function oY(e,t,r){return e.put(`/api/v1/scheduled/cancel-subscriptions/${t}`,{resourceId:t,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function aY(e,t){return e.search("/api/v1/scheduled-transaction/search",{...t,sort:t.sort??{sortBy:["startDate"],order:"DESC"}})}var Ace=re(()=>{"use strict"});async function cY(e,t){return e.list("/api/v1/contact-groups",t)}async function uY(e,t){return e.get(`/api/v1/contact-groups/${t}`)}async function lY(e,t){return e.search("/api/v1/contact-groups/search",t)}async function fY(e,t){return e.post("/api/v1/contact-groups",t)}async function dY(e,t,r){return e.put(`/api/v1/contact-groups/${t}`,r)}async function pY(e,t){await e.delete(`/api/v1/contact-groups/${t}`)}var mce=re(()=>{"use strict"});async function hY(e,t){return e.list("/api/v1/inventory-items",t)}async function AY(e,t){return e.post("/api/v1/inventory-items",t)}async function mY(e,t){return e.get(`/api/v1/inventory-item-balance/${t}`)}var gce=re(()=>{"use strict"});async function gY(e,t){return e.list("/api/v1/custom-fields",t)}async function yY(e,t){return e.get(`/api/v1/custom-fields/${t}`)}async function EY(e,t){return e.search("/api/v1/custom-fields/search",t)}async function bY(e,t){return e.post("/api/v1/custom-fields",t)}async function CY(e,t,r){return e.put(`/api/v1/custom-fields/${t}`,r)}async function vY(e,t){await e.delete(`/api/v1/custom-fields/${t}`)}var yce=re(()=>{"use strict"});function eet(e){return{updated:e.updated??[],failed:(e.failed??[]).map(t=>({...t,errorCode:t.errorCode??"UNKNOWN_ERROR"}))}}async function ix(e,t,r){let n=await e.post(`/api/v1/quick-fix/${t}`,r);return eet(n)}async function sx(e,t,r){let n=await e.post(`/api/v1/quick-fix/${t}/line-items`,r);return eet(n)}var ggr,ygr,Egr,iv,Ece=re(()=>{"use strict";ggr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],ygr=["journals","cash-entries"],Egr=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],iv=[...ggr,...ygr,...Egr]});async function wY(e,t){return e.list("/api/v1/nano-classifiers",t)}async function IY(e,t){return{data:(await e.get(`/api/v1/nano-classifiers/${t}`)).data.data[0]}}async function _Y(e,t){return e.search("/api/v1/nano-classifiers/search",t)}async function ox(e,t){return e.post("/api/v1/nano-classifiers",{...t,printable:t.printable??!1})}async function ax(e,t,r){return e.put(`/api/v1/nano-classifiers/${t}`,r)}async function DY(e,t){await e.delete(`/api/v1/nano-classifiers/${t}`)}var bce=re(()=>{"use strict"});async function SY(e,t){return e.post("/api/v1/export-records",t)}async function BY(e,t){return e.post("/api/v1/export-records/preview",t)}async function RY(e,t){return e.get(`/api/v1/export-records/columns/${t}`)}var Cce=re(()=>{"use strict"});async function cx(e,t={}){return e.search("/api/v1/background-jobs/search",t)}var vce=re(()=>{"use strict"});function sv(e){Ii(e,"items"),e.forEach((t,r)=>{if(!t||typeof t!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=t;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!bgr.has(n.btType))throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.`)})}async function xY(e,t){let r=await e.post("/api/v1/drafts/validate",{items:t});return{data:vgr(r.data)}}function Cgr(e){return{btResourceId:e.btResourceId,btType:e.btType,eligible:e.eligible,errors:e.errors,displayData:e.displayData,contactSignals:e.contactInsight??null,breakdown:e.breakdown??null}}function vgr(e){return{eligibleCount:e.eligibleCount,ineligibleCount:e.ineligibleCount,results:e.results.map(Cgr),columns:e.columns,errorColumns:e.errorColumns,contactSignalsMeta:e.contactInsightsMeta??null}}async function TY(e,t){return e.post("/api/v1/drafts/convert-to-active",{items:t})}async function kY(e,t){return e.post("/api/v1/drafts/submit-for-approval",{items:t})}var bgr,wce=re(()=>{"use strict";sc();bgr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function net(e){let t=e??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(t.businessTransactionPayments)&&!r(t.matchedPayments)&&!r(t.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function Ice(e,t){if(!e||typeof e!="object")throw new Error(`${t} is required.`);let r=e,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${t}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${t}.lineItems per call.`);ic([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&ic([i],["valueDate"])}function _gr(e,t){let r=typeof t=="number"&&!Number.isNaN(t)?t:void 0,n=typeof e=="number"&&!Number.isNaN(e)?e:void 0;if(r!==void 0)return r>=wgr?"high":r>=tet?"medium":"low";if(n!==void 0){if(n>=Igr)return"high";if(n>=tet)return"medium"}return"low"}function iet(e,t={}){let r=e??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let s=[];for(let o of i){let a=o??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){s.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,alternativeCount:0});continue}let f=u.slice().sort((D,R)=>{let Q=D.confidenceScore??D.matchScore??-1;return(R.confidenceScore??R.matchScore??-1)-Q}),d=f[0],p=typeof d.recommendationType=="string"?d.recommendationType:void 0,h=typeof d.matchScore=="number"?d.matchScore:void 0,A=typeof d.confidenceScore=="number"?d.confidenceScore:void 0,m=typeof d.isCrossCurrency=="boolean"?d.isCrossCurrency:void 0,g=typeof d.cftBtResourceId=="string"?d.cftBtResourceId:void 0,y=Array.isArray(d.cftBtResourceIds)?d.cftBtResourceIds:[],C=d.isBatch===!0||y.length>1,E=typeof d.cftAmount=="number"?d.cftAmount:void 0,v,w;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(v=ux.magicMatch,w={...t.bankAccountResourceId?{bankAccountResourceId:t.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(v=ux.withPayments,w={bankStatementEntryResourceId:c,businessTransactionPayments:[{cashflowTransactionResourceId:g,...E!==void 0?{transactionAmount:E}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let D=typeof d.learnedPredictionResourceId=="string"?d.learnedPredictionResourceId:void 0,R=typeof d.predictedPayload=="string"?d.predictedPayload:void 0,Q=typeof d.predictedPayloadSchemaVersion=="string"?d.predictedPayloadSchemaVersion:void 0;D&&R&&Q&&(v=ux.learnedPrediction,w={bankStatementEntryResourceId:c,learnedPredictionResourceId:D,predictedPayload:R,predictedPayloadSchemaVersion:Q});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let D=d.actionShortcut??{},R=typeof D.resourceId=="string"?D.resourceId:void 0;R&&(v=ux.applyBankRule,w={actionShortcutResourceId:R,businessTransactionResourceIds:[c]});break}default:break}let T=v?_gr(h,A):"low",S=typeof E=="number"&&!Number.isNaN(E),k=!(t.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=t.autoCommitMaxAmount,Y=v!==ux.withPayments||S,U=T==="high"&&!!v&&!!w&&Y&&k;s.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:A,isCrossCurrency:m,recommendedTool:v,execute:w,confidenceTier:T,autoCommitEligible:U,alternativeCount:f.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return s}function Sgr(e,t,r){return{bankStatementEntryResourceId:e.bankStatementEntryResourceId,confidenceTier:e.confidenceTier,recommendationType:e.recommendationType,recommendedTool:e.recommendedTool,execute:e.execute,bankLine:t,match:r}}async function Bgr(e,t,r){let n=t.matchedTransactionResourceId,i=t.matchedTransactionCount;if(!n)return t.matchAmount!==void 0?{type:"transaction",amount:t.matchAmount,count:i}:null;let s=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let o of s)try{let{data:a}=o==="bill"?await go(e,n):await bo(e,n);return{type:o,reference:a.reference,amount:t.matchAmount??a.totalAmount,documentTotalAmount:a.totalAmount,count:i,resourceId:n}}catch{}return{type:"transaction",amount:t.matchAmount,count:i,resourceId:n}}async function set(e,t,r){let n=r.filter(s=>s.recommendedTool&&!s.autoCommitEligible).slice(0,Dgr);if(n.length===0)return[];let i=new Map;if(t)try{let s=await XE(e,t,{filter:{status:{eq:"UNRECONCILED"}},limit:500});for(let o of s.data??[])i.set(o.resourceId,o)}catch{}return Promise.all(n.map(async s=>{let o=i.get(s.bankStatementEntryResourceId),a=o?{valueDate:o.valueDate,netAmount:o.netAmount,currencyCode:o.currencyCode,currencySymbol:o.currencySymbol,description:o.description,counterparty:o.extContactName}:null;return Sgr(s,a,await Bgr(e,s,a?.netAmount))}))}async function NY(e,t){return e.post("/api/v1/reconciliations/quick-reconcile",t)}async function FY(e,t){return e.post("/api/v1/reconciliations/bank-rule",t)}async function OY(e,t){return e.post("/api/v1/reconciliations/direct-cash-entry",t)}async function QY(e,t){return e.post("/api/v1/reconciliations/cash-journal",t)}async function LY(e,t){return e.post("/api/v1/reconciliations/manual-journal",t)}async function MY(e,t){return e.post("/api/v1/reconciliations/cash-transfer",t)}async function PY(e,t){return e.post("/api/v1/reconciliations/invoice-receipt",t)}async function $Y(e,t){return e.post("/api/v1/reconciliations/bill-receipt",t)}async function UY(e,t){return e.post("/api/v1/reconciliations/with-payments",t)}async function qY(e,t){return e.post("/api/v1/reconciliations/learned-prediction",t)}async function jY(e,t){return e.post("/api/v1/reconciliations/magic-match",t)}var ux,wgr,Igr,tet,Dgr,_ce=re(()=>{"use strict";$d();Ud();sc();_m();ux={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},wgr=.9,Igr=.95,tet=.7;Dgr=25});function Bo(e,t,r="lineItems"){let n=[];for(let i of t)if(i.perLineItem){let s=e[r]??[];for(let o=0;o<s.length;o++)i.check(s[o])||n.push(`${r}[${o}].${i.field}`)}else i.check(e)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function as(e,t,r="lineItems"){let n=t.filter(a=>!a.perLineItem),i=t.filter(a=>a.perLineItem),s={valueDate:Dce(e,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(s.contact=Dce(e,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(s.dueDate=Dce(e,"dueDate","Due date","--due <YYYY-MM-DD>",n));let o=e[r]??[];return s.lineItems=o.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,f=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let m=i.find(w=>w.field==="amount"),g=m?m.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:f}}let d=i.find(m=>m.field==="name"),p=i.find(m=>m.field==="unitPrice"),h=d?d.check(a):!0,A=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:A?"ok":"missing",account:f}}),s}function Dce(e,t,r,n,i){let s=i.find(o=>o.field===t);if(!s){let o=e[t];return o?{status:"ok",value:o}:{status:"ok"}}if(s.check(e)){let o=e[t];return t==="contactResourceId"?{status:"ok",value:e.contactName||o,resourceId:o}:{status:"ok",value:o}}return{status:"missing",hint:n}}function _s(e,t,r,n="lineItems"){let{missingFields:i,missingCount:s,ready:o}=Bo(e,t,n),a=as(e,t,n);return{resourceId:e.resourceId,reference:e.reference||null,totalAmount:e.totalAmount??0,attachmentCount:r,ready:o,missingCount:s,missingFields:i,validation:a}}var ta,xc,Vi,xu,oet=re(()=>{"use strict";ta=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:e=>!!e.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:e=>e.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:e=>!!e.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:e=>e.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0}],xc=[...ta],Vi=ta.filter(e=>e.field!=="dueDate"),xu=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:e=>!!e.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:e=>e.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:e=>!!(e.accountResourceId||e.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:e=>e.amount!=null&&e.amount>0||e.debitAmount!=null&&e.debitAmount>0||e.creditAmount!=null&&e.creditAmount>0,perLineItem:!0}]});function Tc(e){let t={};e.name!=null&&(t.name=e.name),e.quantity!=null&&(t.quantity=e.quantity),e.unitPrice!=null&&(t.unitPrice=e.unitPrice),e.unit&&(t.unit=e.unit);let r=e.accountResourceId||e.organizationAccountResourceId;r&&(t.accountResourceId=r);let n=e.taxProfileResourceId||(e.taxProfile&&typeof e.taxProfile=="object"?e.taxProfile.resourceId:null);return n&&(t.taxProfileResourceId=n),e.itemResourceId&&(t.itemResourceId=e.itemResourceId),e.discount!=null&&(t.discount=typeof e.discount=="object"?e.discount.rateValue??0:e.discount),t}function ov(e){let t={},r=e.accountResourceId||e.organizationAccountResourceId;return r&&(t.accountResourceId=r),e.amount!=null?t.amount=e.amount:e.debitAmount!=null&&e.debitAmount>0?t.amount=e.debitAmount:e.creditAmount!=null&&e.creditAmount>0&&(t.amount=e.creditAmount),e.type?t.type=e.type:e.debitAmount!=null&&e.debitAmount>0?t.type="DEBIT":e.creditAmount!=null&&e.creditAmount>0&&(t.type="CREDIT"),e.description&&(t.description=e.description),e.contactResourceId&&(t.contactResourceId=e.contactResourceId),t}function Ft(e){if(e)return e.split("T")[0]}var Sce=re(()=>{"use strict"});function Ol(e,t){let r={};if(t.contact&&(r.contactResourceId=t.contact),t.date&&(r.valueDate=t.date),t.due&&(r.dueDate=t.due),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.tag!==void 0&&(r.tag=t.tag),t.tax&&(r.isTaxVatApplicable=!0),t.tax&&t.taxInclusive?r.taxInclusion=!0:t.tax&&(r.taxInclusion=!1),t.lines)r.lineItems=t.lines;else if(t.account||t.taxProfile){let n=e.lineItems??[];r.lineItems=n.map(i=>{let s=Tc(i);return t.account&&!s.accountResourceId&&(s.accountResourceId=t.account),t.taxProfile&&!s.taxProfileResourceId&&(s.taxProfileResourceId=t.taxProfile),s})}return r}function YY(e,t){let r={};if(t.date&&(r.valueDate=t.date),t.ref!==void 0&&(r.reference=t.ref),t.notes!==void 0&&(r.notes=t.notes),t.entries)r.journalEntries=t.entries;else if(t.account){let n=e.journalEntries??[];r.journalEntries=n.map(i=>{let s=ov(i);return t.account&&!s.accountResourceId&&(s.accountResourceId=t.account),s})}return r}var aet=re(()=>{"use strict";Sce()});var Bce=re(()=>{"use strict";oet();Sce();aet()});var lx,Tu,cet=re(()=>{"use strict";lx="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",Tu="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});function _et(e){let t=e.limit,r=e.offset;return{limit:t,offset:r,sortBy:void 0,sortOrder:void 0}}function cn(e,t,r,n,i,s){let o={...Nce};return s?.leanView&&(o.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). List lean, then drill in with get_*."}),{name:e,description:t,params:o,required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(a,c)=>{let{limit:u,offset:f}=_et(c),d=s?.leanView?c.view==="full"?"full":"lean":void 0;return eD((h,A)=>n(a.client,h,A,d),u,f,d==="lean"?50:20)}}}function Qa(e,t,r,n,i){return{name:e,description:t,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(s,o)=>n(s.client,o.resourceId)}}function Ro(e,t,r,n,i){return{name:e,description:t,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(s,o)=>(await n(s.client,o.resourceId),{deleted:!0,resourceId:o.resourceId})}}function met(e){if(typeof e!="string"||/^\d{4}-\d{2}-\d{2}$/.test(e))return e;let t=/^(\d{4}-\d{2}-\d{2})T/.exec(e);return t?t[1]:e}function Fgr(e){return Array.isArray(e)?e.map(t=>{let r={};for(let[n,i]of Object.entries(t))if(i!=null)if(n==="organizationAccountResourceId")r.accountResourceId=i;else if(n==="taxProfile"&&typeof i=="object"&&i!==null){let s=i.resourceId;s&&(r.taxProfileResourceId=s)}else if(n==="discount"&&typeof i=="object"&&i!==null){let s=i.rateValue;s&&Number(s)!==0&&(r.discount=i)}else Ngr.has(n)&&(r[n]=i);return r}):e}async function dx(e,t,r,n){let o=(await(t==="invoice"?bo:t==="bill"?go:t==="customer_credit_note"?mu:gu)(e,r)).data,a=kgr[t],c={};for(let[p,h]of Object.entries(o))a.has(p)&&h!==null&&h!==void 0&&(c[p]=h);c.valueDate&&(c.valueDate=met(c.valueDate)),c.dueDate&&(c.dueDate=met(c.dueDate)),c.lineItems&&(c.lineItems=Fgr(c.lineItems));for(let[p,h]of Object.entries(n))h!==void 0&&(c[p]=h);let u=t==="invoice"?xc:t==="bill"?ta:Vi,{missingFields:f,ready:d}=Bo(c,u);if(!d)throw new Error(`Cannot finalize: missing ${f.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function get(e,t,r,n){if((await e(t,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function GY(e,t,r){if(!(typeof e=="string"&&t.includes(e)))return{error:`Unknown documentType ${JSON.stringify(e)}.`,status:422,hint:`Use one of: ${t.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}function bet(e,t,r){let n=Eet[e];if(!n)return{error:`Unknown documentType "${e}".`,status:422,hint:`Valid document types: ${Object.keys(Eet).join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}};if(!n.includes(t)){let i=n.includes("ACCEPT")?"ACCEPT":"CONFIRM";return{error:`Action "${t}" is not valid for ${e}. Valid actions: ${n.join(", ")}.`,status:422,hint:`${e} advances its lifecycle with ${i}, not ${t}.`,repair:{tool:r,arguments:{documentType:e,action:i},reason:`${e} is advanced with ${i}.`}}}}async function Cet(e,t,r,n,i,s,o){let a;try{a=(await t(e,r)).data?.status}catch{return}if(a==="DRAFT"||a==="VOID"){let c=a==="DRAFT"?`A DRAFT ${n} can't be linked or accepted \u2014 issue it by creating the ${n} with saveAsDraft:false (status ${o}), then link the order to that one.`:`A VOID ${n} can't be used \u2014 create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a ${a} ${n} (${r}).`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. ${c}`,repair:{tool:s,arguments:{documentType:i,saveAsDraft:!1},reason:c}}}}async function vet(e,t,r,n,i,s){let o;try{o=(await t(e,r)).data?.status}catch{return}if(o==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:s,arguments:{},reason:`The source ${n} is VOID.`}}}async function wet(e,t,r,n,i){let s;try{s=(await t(e,r,n)).data?.status}catch{return}if(s&&s!=="DRAFT")return{error:`Cannot DELETE a ${s} ${r} \u2014 delete is only allowed on DRAFT records.`,status:422,hint:"Use action VOID to cancel a non-draft quote/request/order.",repair:{tool:i,arguments:{documentType:r,resourceId:n,action:"VOID"},reason:`${r} is ${s}; void it instead of deleting.`}}}var La,cs,ku,us,ni,Ql,zY,Kg,Rce,ty,Rgr,xgr,xce,uet,fet,Tce,Nce,Xg,kce,det,pet,het,Aet,Ji,Tgr,ey,ra,Iet,Ll,fx,kgr,Ngr,px,hx,HY,yet,Eet,kc,av=re(()=>{"use strict";LFe();jFe();Z_();Vu();Jr();ip();TA();xb();Yd();_m();Ud();l5();f5();Yb();d5();$d();NQ();HQ();U_();uM();mM();vM();dXe();q_();ej();Pae();$ae();Uae();qae();Kae();rce();MXe();$d();KR();nce();ice();sce();oce();ace();qXe();lce();Qh();fce();rO();NJ();YXe();WXe();KXe();s5();XXe();hce();tY();Ace();mce();gce();yce();Ece();bce();Cce();vce();Yd();_m();Ud();uM();mM();Yb();tY();sc();wce();_ce();Jr();Bce();cet();La={type:"string",description:"Resource ID of the record"},cs={type:"string",description:"Transaction date (YYYY-MM-DD)"},ku={type:"string",description:"Due date (YYYY-MM-DD)"},us={type:"string",description:"Reference number"},ni={type:"string",description:"Notes or memo text"},Ql={type:"string",description:"Tag name for categorization"},zY={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},Kg={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},Rce={type:"string",description:"Contact resourceId (customer or supplier)"},ty={type:"string",description:"Bank/cash account resourceId"},Rgr={type:"number",description:"Payment amount (in bank currency)"},xgr={type:"string",description:"Period start date (YYYY-MM-DD)"},xce={type:"string",description:"Period end date (YYYY-MM-DD)"},uet={type:"string",enum:["full","aggregate"],description:`Output detail (default 'full'). 'aggregate' returns a compact aging-bucket summary (current, <1 month, 1/2/3 months, older + total outstanding + contact count). Prefer 'aggregate' for a general or unqualified report request (e.g. "show me my aged receivables", "my AR report") \u2014 it's the at-a-glance overview a chat user expects and it won't truncate on large orgs. Use 'full' only when the user explicitly asks for the per-contact (customer/supplier) breakdown for deeper analysis.`},fet={type:"string",description:"Currency code (e.g. SGD, USD)"},Tce={type:"string",description:"Display name"},Nce={limit:{type:"number",description:"Max results per page (\u22641000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},Xg={type:"object",properties:{sourceCurrency:{type:"string"},exchangeRate:{type:"number"}}},kce={type:"string",enum:[...Cf],description:"Entity type to export"},det={type:"string",description:'Structured search query using dashboard syntax (e.g., "status:unpaid $500+ date:this month"). Mutually exclusive with filter \u2014 pass one or the other, never both.'},pet={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},het={type:"array",items:{type:"object",properties:{path:{type:"string",description:"Column path from get_export_columns (e.g., s.reference)"},header:{type:"string",description:"Column header label in the export file"},type:{type:"string",enum:["STRING","NUMBER","CURRENCY","DATE","BOOLEAN"],description:"Column data type (optional)"}},required:["path","header"]},description:"Custom column definitions. Omit to use default columns. Use get_export_columns to discover available paths."},Aet={type:"object",properties:{field:{type:"string",description:"Column path to sort by (e.g., s.total_amount)"},direction:{type:"string",enum:["ASC","DESC"],description:"Sort direction"}},required:["field"],description:"Sort results by a column path."},Ji={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},Tgr={type:"array",items:{type:"object",properties:{resourceId:{type:"string",description:"Capsule type resourceId"},type:{type:"string",enum:["invoice","bill"],description:"Resource type"},selectedClasses:{type:"array",items:{type:"object",properties:{className:{type:"string"},resourceId:La}}},printable:{type:"boolean"}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},ey={type:"array",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account resourceId"},type:{type:"string",enum:["DEBIT","CREDIT"],description:"Debit or credit"},amount:{type:"number",description:"Amount"},description:{type:"string",description:"Line description"}},required:["accountResourceId","type","amount"]},description:"Journal entries (debit/credit lines with accountResourceId, type, amount)"},ra={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:ty,taxProfileResourceId:{type:"string"},classifierConfig:Tgr},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},Iet={type:"array",items:{type:"object",properties:{slotKey:{type:"string",description:"Slot from get_capsule_recipe templateSlots[]."},template:{type:"string",description:"Text with {{vars}} for that slot; empty string clears a nullable slot. Max 2000."}},required:["slotKey"]},description:"Optional. Customize recipe-generated text via published slots (see get_capsule_recipe)."},Ll={type:"object",description:"Optional IFRS recipe trigger. Mutex with capsuleResourceId. Silent-null on failure \u2014 preview_capsule_recipe first. Rule 143.",properties:{recipeName:{type:"string",enum:["LOAN_AMORTIZATION","ACCRUAL_REVERSAL","PREPAID_AMORTIZATION","DEFERRED_REVENUE","IFRS16_LEASE"],description:"Must match mutation's allowedBaseTransactionTypes (see list_capsule_recipes)."},recipeVersion:{type:"number",description:"Optional version pin."},inputs:{type:"object",description:"Schema at versions[0].inputSchema. Single-currency; *AccountResourceId x-accountClass-locked."},templateOverrides:Iet},required:["recipeName","inputs"]},fx={type:"string",enum:[...h1e],description:"Payment method (default BANK_TRANSFER)"};kgr={invoice:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","notes","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId","customerPaymentProfileResourceId"]),bill:new Set(["reference","valueDate","dueDate","contactResourceId","lineItems","invoiceNotes","internalNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","terms","currency","customFields","capsuleResourceId","capsuleRecipe","taxProfileResourceId"]),customer_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"]),supplier_credit_note:new Set(["reference","valueDate","contactResourceId","lineItems","invoiceNotes","tag","tags","isTaxVatApplicable","isTaxVATApplicable","taxInclusion","currency","customFields","capsuleResourceId","taxProfileResourceId"])};Ngr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);px={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},hx={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},HY={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."},yet={type:"string",enum:["ACCEPT","CONFIRM","VOID","DELETE"],description:"Lifecycle action. ACCEPT=quote/request only; CONFIRM=order only; VOID=any non-draft; DELETE=draft only."},Eet={SALE_QUOTE:["ACCEPT","VOID","DELETE"],SALE_ORDER:["CONFIRM","VOID","DELETE"],PURCHASE_REQUEST:["ACCEPT","VOID","DELETE"],PURCHASE_ORDER:["CONFIRM","VOID","DELETE"]};kc=[{name:"get_organization",description:"Get organization details: name, base currency, country, and financial year end.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>pa(e.client)},cn("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(e,t,r)=>Ef(e,{limit:r,offset:t}),"list chart of accounts with code type class status"),tn({name:"search_accounts",description:'Search chart of accounts. For OR (name or code), use filter: {"or":{"name":{"contains":"X"},"code":{"contains":"X"}}}.',group:"accounts",fields:wD,defaults:ID,fetcher:Rb,searchHint:"find accounts chart of accounts CoA by name code type class status OR search"}),{name:"create_account",description:"Create a new chart of accounts entry. Auto-checks for duplicates by name \u2014 returns existing account if found. Code must be unique. Account class is inferred from accountType.",params:{name:{type:"string",description:"Account name"},code:{type:"string",description:"Account code (unique)"},accountType:{type:"string",description:'Exact API string. Classic 12: Bank Accounts | Cash | Current Asset | Fixed Asset | Inventory | Current Liability | Non-current Liability | Shareholders Equity | Operating Revenue | Other Revenue | Operating Expense | Direct Costs. IFRS 18 (effective 2027): Discontinued Expense | Discontinued Income | Finance Cost | Financing Income | Goodwill | Income Tax Expense | Investing Expense | Investing Income | Investment. Common variants normalized client-side. For "interest expense"/"interest income", pick Financing or Investing yourself \u2014 depends on entity main business activity, NOT auto-classified.'},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."}},required:["name","code","accountType"],group:"accounts",readOnly:!1,searchHint:"create new chart of accounts entry with type code lock date",execute:async(e,t)=>{let r=t.name,n=await VQ(e.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=Bb(t.accountType);return z_(e.client,{code:t.code,name:r,accountType:i,currencyCode:t.currencyCode,lockDate:t.lockDate})}},{name:"update_account",description:"Update a chart of accounts entry \u2014 rename, re-code, set its period lock date, or remove an existing lock date. Setting lockDate (YYYY-MM-DD) is how an individual ledger account is locked for a period: it blocks recording or editing any transaction on that account dated on or before the lock date. Pass clearLockDate to remove (unlock) an existing lock.",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."},clearLockDate:{type:"boolean",description:"Set true to remove an existing period lock date (unlock the period). Use when the user asks to remove, delete, clear, lift, or unset the lock. Do not also pass lockDate."}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code lock date unlock remove clear lock",execute:async(e,t)=>{let r=t.resourceId,n=(await KNe(e.client,r)).data,s=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(a=>n[a]!==void 0&&n[a]!==null).map(a=>[a,n[a]]));!s.classificationType&&n.accountType&&(s.classificationType=n.accountType);let o=t.clearLockDate===!0;if(o&&t.lockDate!==void 0)throw new Error("clearLockDate and lockDate are mutually exclusive \u2014 pass one or the other.");return!o&&typeof n.accountLockDate=="string"&&n.accountLockDate&&(s.lockDate=n.accountLockDate.slice(0,10)),t.name!==void 0&&(s.name=t.name),t.code!==void 0&&(s.code=t.code),!o&&t.lockDate!==void 0&&(s.lockDate=t.lockDate),XNe(e.client,r,s)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount } \u2014 no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
681
681
 
682
682
  resourceId per row \u2192 update; omit \u2192 create. Note: dedup is by NAME (not code) \u2014 duplicate name surfaces ORGANIZATION_CHART_OF_ACCOUNT_DUPLICATED per row. Accepts classic 12 + 9 IFRS 18 accountType values; common variants normalized via normalizeAccountType.
683
683
 
@@ -745,7 +745,7 @@ Optional capsuleRecipe \u2014 no v1 recipe lists JOURNAL_DIRECT_CASH_OUT; passin
745
745
 
746
746
  NOT for external parties \u2014 use create_cash_in (receiving) / create_cash_out (paying).
747
747
 
748
- cashOut = source, cashIn = destination. Each side needs accountResourceId + amount. reference auto-generated if omitted. Do NOT send currency/exchangeRate (derived server-side).`,params:{reference:{type:"string",description:"Reference number"},valueDate:{type:"string",description:"Date (YYYY-MM-DD)"},cashOut:{type:"object",properties:{accountResourceId:{type:"string",description:"Source bank account resourceId"},amount:{type:"number",description:"Transfer amount"}},required:["accountResourceId","amount"]},cashIn:{type:"object",properties:{accountResourceId:{type:"string",description:"Destination bank account resourceId"},amount:{type:"number",description:"Transfer amount"}},required:["accountResourceId","amount"]},tags:{type:"array",items:{type:"string"},description:"Tags (string array)"},saveAsDraft:{type:"boolean",description:"Save as draft (default true)"}},required:["valueDate","cashOut","cashIn"],group:"cash_transfers",readOnly:!1,searchHint:"create cash transfer between bank accounts",execute:async(e,t)=>{let r={...t};return r.reference||(r.reference=`CT-${Date.now()}`),GR(e.client,r)}},Ro("delete_cash_in","Delete (void) a cash-in entry. Uses parentEntityResourceId from create response.","cash_entries",(e,t)=>Fh(e,t),"delete void a cash in receipt entry"),Ro("delete_cash_out","Delete (void) a cash-out entry. Uses parentEntityResourceId from create response.","cash_entries",(e,t)=>Fh(e,t),"delete void a cash out payment entry"),Ro("delete_cash_transfer","Delete (void) a cash transfer. Uses parentEntityResourceId from create response.","cash_transfers",(e,t)=>Fh(e,t),"delete void a cash transfer between accounts"),cn("list_scheduled_invoices","List scheduled (recurring) invoices. Paginated.","schedulers",(e,t,r)=>nj(e,{limit:r,offset:t}),"list recurring scheduled invoices subscriptions"),cn("list_scheduled_bills","List scheduled (recurring) bills. Paginated.","schedulers",(e,t,r)=>ij(e,{limit:r,offset:t}),"list recurring scheduled bills subscriptions"),cn("list_scheduled_journals","List scheduled (recurring) journals. Paginated.","schedulers",(e,t,r)=>sj(e,{limit:r,offset:t}),"list recurring scheduled journal entries"),{name:"get_bank_account",description:"Get full bank account details by resourceId.",params:{resourceId:{type:"string",description:"Bank account resourceId"}},required:["resourceId"],group:"bank",readOnly:!0,searchHint:"get bank account details balance by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>KE(e.client,t.resourceId)},tn({name:"search_bank_records",description:"Search bank records for a specific account. Call list_bank_accounts first to get accountResourceId.",group:"bank",fields:pD,defaults:hD,fetcher:XE,pathParam:"accountResourceId",pathParamDescription:"Bank account resourceId (UUID). Call list_bank_accounts first.",searchHint:"find bank records statement entries transactions by status date amount description payer reference range"}),tn({name:"search_cashflow_transactions",description:"Search cashflow transactions (unified ledger across cash entries / payments / journals). direction enum: PAYIN | PAYOUT.",group:"cashflow",fields:vf,defaults:wf,fetcher:Oh,searchHint:"find cashflow transactions money movement by type direction PAYIN PAYOUT status date reference account"}),cn("list_bookmarks","List organization bookmarks (saved values/settings).","bookmarks",(e,t,r)=>bj(e,{limit:r,offset:t}),"list saved bookmarks reports shortcuts"),{name:"get_bookmark",description:"Get a bookmark by resourceId.",params:{resourceId:{type:"string",description:"Bookmark resourceId"}},required:["resourceId"],group:"bookmarks",readOnly:!0,searchHint:"get bookmark saved report details",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>Cj(e.client,t.resourceId)},{name:"create_bookmarks",description:"Create one or more bookmarks. categoryCode must be one of: AUDIT_AND_ASSURANCE, BANKING_AND_FINANCE, BUDGETS_AND_CONTROLS, EMPLOYEES_AND_PAYROLL, EXTERNAL_DOCUMENTS, GENERAL_INFORMATION, OWNERS_AND_DIRECTORS, TAXATION_AND_COMPLIANCE, WORKFLOWS_AND_PROCESSES.",params:{items:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Bookmark name"},value:{type:"string",description:"Bookmark value"},categoryCode:{type:"string",description:"Category code (e.g., GENERAL_INFORMATION)"},datatypeCode:{type:"string",description:"Datatype code (default: TEXT)"}},required:["name","value","categoryCode","datatypeCode"]},description:"Bookmarks to create"}},required:["items"],group:"bookmarks",readOnly:!1,searchHint:"create new bookmark saved report shortcut",execute:async(e,t)=>XR(e.client,t.items)},{name:"update_bookmark",description:"Update an existing bookmark (name, value, or category). Use when modifying a previously created bookmark.",params:{resourceId:{type:"string",description:"Bookmark resourceId"},name:{type:"string",description:"New name"},value:{type:"string",description:"New value"},categoryCode:{type:"string",description:"New category code"}},required:["resourceId"],group:"bookmarks",readOnly:!1,searchHint:"update bookmark name or configuration",execute:async(e,t)=>{let{resourceId:r,...n}=t;return vj(e.client,r,n)}},cn("list_org_users","List organization users (team members). Returns name, email, roles.","org_users",(e,t,r)=>wj(e,{limit:r,offset:t}),"list organization users team members"),tn({name:"search_org_users",description:"Search organization users. For OR (name or email), use filter param.",group:"org_users",fields:OD,defaults:QD,fetcher:Ij,searchHint:"find organization users team members by name email role status OR search"}),{name:"invite_org_user",description:`Invite a new user to the organization.
748
+ cashOut = source, cashIn = destination. Each side needs accountResourceId + amount. reference auto-generated if omitted. Do NOT send currency/exchangeRate (derived server-side).`,params:{reference:{type:"string",description:"Reference number"},valueDate:{type:"string",description:"Date (YYYY-MM-DD)"},cashOut:{type:"object",properties:{accountResourceId:{type:"string",description:"Source bank account resourceId"},amount:{type:"number",description:"Transfer amount"}},required:["accountResourceId","amount"]},cashIn:{type:"object",properties:{accountResourceId:{type:"string",description:"Destination bank account resourceId"},amount:{type:"number",description:"Transfer amount"}},required:["accountResourceId","amount"]},tags:{type:"array",items:{type:"string"},description:"Tags (string array)"},saveAsDraft:{type:"boolean",description:"Save as draft (default true)"}},required:["valueDate","cashOut","cashIn"],group:"cash_transfers",readOnly:!1,searchHint:"create cash transfer between bank accounts",execute:async(e,t)=>{let r={...t};return r.reference||(r.reference=`CT-${Date.now()}`),GR(e.client,r)}},Ro("delete_cash_in","Delete (void) a cash-in entry. Uses parentEntityResourceId from create response.","cash_entries",(e,t)=>Fh(e,t),"delete void a cash in receipt entry"),Ro("delete_cash_out","Delete (void) a cash-out entry. Uses parentEntityResourceId from create response.","cash_entries",(e,t)=>Fh(e,t),"delete void a cash out payment entry"),Ro("delete_cash_transfer","Delete (void) a cash transfer. Uses parentEntityResourceId from create response.","cash_transfers",(e,t)=>Fh(e,t),"delete void a cash transfer between accounts"),cn("list_scheduled_invoices","List scheduled (recurring) invoices. Paginated.","schedulers",(e,t,r)=>nj(e,{limit:r,offset:t}),"list recurring scheduled invoices subscriptions"),cn("list_scheduled_bills","List scheduled (recurring) bills. Paginated.","schedulers",(e,t,r)=>ij(e,{limit:r,offset:t}),"list recurring scheduled bills subscriptions"),cn("list_scheduled_journals","List scheduled (recurring) journals. Paginated.","schedulers",(e,t,r)=>sj(e,{limit:r,offset:t}),"list recurring scheduled journal entries"),{name:"get_bank_account",description:"Get full bank account details by resourceId.",params:{resourceId:{type:"string",description:"Bank account resourceId"}},required:["resourceId"],group:"bank",readOnly:!0,searchHint:"get bank account details balance by id",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>KE(e.client,t.resourceId)},tn({name:"search_bank_records",description:"Search bank records for a specific account. Call list_bank_accounts first to get accountResourceId.",group:"bank",fields:pD,defaults:hD,fetcher:XE,pathParam:"accountResourceId",pathParamDescription:"Bank account resourceId (UUID). Call list_bank_accounts first.",searchHint:"find bank records statement entries transactions by status date amount description payer reference range"}),tn({name:"search_cashflow_transactions",description:"Search cashflow transactions (unified ledger across cash entries / payments / journals). direction enum: PAYIN | PAYOUT.",group:"cashflow",fields:vf,defaults:wf,fetcher:Oh,searchHint:"find cashflow transactions money movement by type direction PAYIN PAYOUT status date reference account"}),cn("list_bookmarks","List organization bookmarks (saved values/settings).","bookmarks",(e,t,r)=>bj(e,{limit:r,offset:t}),"list saved bookmarks reports shortcuts"),{name:"get_bookmark",description:"Get a bookmark by resourceId.",params:{resourceId:{type:"string",description:"Bookmark resourceId"}},required:["resourceId"],group:"bookmarks",readOnly:!0,searchHint:"get bookmark saved report details",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>Cj(e.client,t.resourceId)},{name:"create_bookmarks",description:"Create one or more bookmarks. categoryCode must be one of: AUDIT_AND_ASSURANCE, BANKING_AND_FINANCE, BUDGETS_AND_CONTROLS, EMPLOYEES_AND_PAYROLL, EXTERNAL_DOCUMENTS, GENERAL_INFORMATION, OWNERS_AND_DIRECTORS, TAXATION_AND_COMPLIANCE, WORKFLOWS_AND_PROCESSES.",params:{items:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Bookmark name"},value:{type:"string",description:"Bookmark value"},categoryCode:{type:"string",enum:["AUDIT_AND_ASSURANCE","BANKING_AND_FINANCE","BUDGETS_AND_CONTROLS","EMPLOYEES_AND_PAYROLL","EXTERNAL_DOCUMENTS","GENERAL_INFORMATION","OWNERS_AND_DIRECTORS","TAXATION_AND_COMPLIANCE","WORKFLOWS_AND_PROCESSES"],description:"Category code"},datatypeCode:{type:"string",enum:["TEXT","NUMBER","BOOLEAN","DATE","LINK"],description:"Datatype code (default: TEXT)"}},required:["name","value","categoryCode","datatypeCode"]},description:"Bookmarks to create"}},required:["items"],group:"bookmarks",readOnly:!1,searchHint:"create new bookmark saved report shortcut",execute:async(e,t)=>XR(e.client,t.items)},{name:"update_bookmark",description:"Update an existing bookmark (name, value, or category). Use when modifying a previously created bookmark.",params:{resourceId:{type:"string",description:"Bookmark resourceId"},name:{type:"string",description:"New name"},value:{type:"string",description:"New value"},categoryCode:{type:"string",enum:["AUDIT_AND_ASSURANCE","BANKING_AND_FINANCE","BUDGETS_AND_CONTROLS","EMPLOYEES_AND_PAYROLL","EXTERNAL_DOCUMENTS","GENERAL_INFORMATION","OWNERS_AND_DIRECTORS","TAXATION_AND_COMPLIANCE","WORKFLOWS_AND_PROCESSES"],description:"New category code"}},required:["resourceId"],group:"bookmarks",readOnly:!1,searchHint:"update bookmark name or configuration",execute:async(e,t)=>{let{resourceId:r,...n}=t;return vj(e.client,r,n)}},cn("list_org_users","List organization users (team members). Returns name, email, roles.","org_users",(e,t,r)=>wj(e,{limit:r,offset:t}),"list organization users team members"),tn({name:"search_org_users",description:"Search organization users. For OR (name or email), use filter param.",group:"org_users",fields:OD,defaults:QD,fetcher:Ij,searchHint:"find organization users team members by name email role status OR search"}),{name:"invite_org_user",description:`Invite a new user to the organization.
749
749
 
750
750
  userType drives access:
751
751
  - ADMIN: full access to every module \u2014 moduleRoles is ignored.
@@ -782,17 +782,17 @@ Supported: ${Jg.join(", ")}.
782
782
 
783
783
  ALTERNATIVE \u2014 for 5 recipes (loan, lease, prepaid-expense, deferred-revenue, accrued-expense) server-side capsule-recipe engine is also available via capsuleRecipe payload on create_bill/create_invoice/create_journal/create_cash_in.
784
784
 
785
- Requires startDate. Auto-resolves accounts from CoA. Provide bankAccountName for recipes with cash-in/cash-out steps, contactName for recipes with invoice/bill steps.`,params:{recipe:{type:"string",enum:[...Jg],description:"Recipe type"},amount:{type:"number"},principal:{type:"number"},startDate:{type:"string",description:"Start date YYYY-MM-DD (REQUIRED for execution)"},currency:{type:"string"},periods:{type:"number"},frequency:{type:"string",enum:["monthly","quarterly","annual"]},annualRate:{type:"number"},termMonths:{type:"number"},monthlyPayment:{type:"number"},usefulLifeMonths:{type:"number"},cost:{type:"number"},salvageValue:{type:"number"},usefulLifeYears:{type:"number"},method:{type:"string",enum:["sl","ddb","150db"]},acquisitionDate:{type:"string"},disposalDate:{type:"string"},proceeds:{type:"number"},bookRate:{type:"number"},closingRate:{type:"number"},baseCurrency:{type:"string"},buckets:{type:"array",items:{type:"object",properties:{name:{type:"string"},balance:{type:"number"},rate:{type:"number"}},required:["name","balance","rate"]}},existingProvision:{type:"number"},compounding:{type:"string",enum:["none","monthly","quarterly","annually"]},employees:{type:"number"},daysPerYear:{type:"number"},dailyRate:{type:"number"},declarationDate:{type:"string"},paymentDate:{type:"string"},withholdingRate:{type:"number"},bankAccountName:{type:"string",description:"Bank/cash account name (for cash-in/cash-out steps) \u2014 auto-resolved by fuzzy match"},contactName:{type:"string",description:"Contact name (for invoice/bill steps) \u2014 auto-resolved by fuzzy match"},existingTxnId:{type:"string",description:"Attach to existing transaction \u2014 skip initial step"},referencePrefix:{type:"string",description:"Reference prefix (generates prefix-1, prefix-2, ...)"},finalize:{type:"boolean",description:"Approve transactions immediately (default: drafts)"}},required:["recipe","startDate"],group:"recipes",readOnly:!1,searchHint:"execute transaction recipe capsule blueprint with dated steps. Posts depreciation, amortization, prepaid, deferred revenue, IFRS 16 lease, hire purchase, loan, fixed deposit, FX revaluation, ECL, IAS 37 provision, asset disposal, accrued expense, leave accrual, dividend entries.",maxResultSizeChars:1e5,execute:async(e,t)=>{let r=t.recipe,n=Is(r,t),i=VR(n);if(!i)throw new Error("No blueprint generated. Ensure startDate is provided.");let s=rv(r,n),o=await OXe(e.client,s.plan.requiredAccounts);if(o.failures.length>0){let u=o.failures.map(f=>`${f.name}${f.candidates.length>0?` (closest: ${f.candidates.join(", ")})`:""}`).join("; ");throw new Error(`Cannot auto-resolve ${o.failures.length} account(s): ${u}. Create them in Jaz first.`)}let a;t.contactName&&(a=(await QXe(e.client,t.contactName)).resourceId);let c;return t.bankAccountName&&(c=(await LXe(e.client,t.bankAccountName)).resourceId),yj(e.client,{blueprint:i,calcType:r,accountMap:o.mapping,bankAccountId:c,contactId:a,existingTxnId:t.existingTxnId,referencePrefix:t.referencePrefix,finalize:t.finalize})}},{name:"list_capsule_recipes",description:"Server-side recipe lifecycle (NOT the offline calculator \u2014 for offline planning use plan_recipe + execute_recipe). List all registered IFRS capsule recipes with per-version JSON Schemas. Source of truth for recipeName values used in capsuleRecipe payloads on trigger mutations (create_bill, create_journal, create_cash_in, etc.) \u2014 DON'T hard-code the 5 enum values. Each descriptor carries displayName, capsuleType, requiresBaseTransaction, allowedBaseTransactionTypes[], expectedAtomTypes[], and versions[] with inputSchema (JSON Schema Draft 7) per version.",params:{},required:[],group:"capsule_recipes",readOnly:!0,isConcurrencySafe:!0,searchHint:"list available IFRS capsule recipes amortization deferred revenue loan lease accrual",execute:async e=>kj(e.client)},{name:"get_capsule_recipe",description:"Get one capsule recipe descriptor by enum name. inputSchema at `data.versions[0].inputSchema` (NOT top-level). Carries `allowedBaseTransactionTypes`, `x-accountClass` per *AccountResourceId slot, `x-baseTrxBinding` for auto-fills, and `versions[].templateSlots[]` \u2014 the slotKeys + supportedVariables you can pass to capsuleRecipe.templateOverrides (Customize Recipe). Use list_capsule_recipes for available names.",params:{name:{type:"string",description:"Recipe enum name (uppercase, see list_capsule_recipes for valid values)."}},required:["name"],group:"capsule_recipes",readOnly:!0,isConcurrencySafe:!0,searchHint:"recipe descriptor inputs required fields prepaid loan deferred lease accrual",execute:async(e,t)=>Nj(e.client,t.name)},{name:"preview_capsule_recipe",description:"Compute the blueprint a recipe would build, WITHOUT persisting. Returns { legs[], expectedOutput[], previewMarkdown }. **Pre-flight gate** before sending capsuleRecipe payloads \u2014 trigger mutations silently null on publish failure but preview surfaces every problem as a clean 422 (ERR_RECIPE_ACCOUNT_CURRENCY_MISMATCH, RECIPE_INVALID_BASE_TRANSACTION_TYPE, ERR_RECIPE_OVERRIDE_* \u2014 Rule 143). Also the gate for templateOverrides: invalid slotKeys/variables come back as ERR_RECIPE_OVERRIDE_* here. The base-trx triplet (baseTransactionResourceId, baseTransactionType, organizationResourceId) is all-or-nothing \u2014 supply all three to auto-fill totalAmount/currency/anchor dates, OR omit all three for a pure compute preview.",params:{recipeName:{type:"string",description:"Recipe enum name. Source of truth: list_capsule_recipes."},recipeVersion:{type:"number",description:"Optional version pin (default: latest registered)."},inputs:{type:"object",description:"Recipe-specific inputs object. See descriptor.versions[].inputSchema (via get_capsule_recipe) for per-recipe shape. Must be non-null."},baseTransactionResourceId:{type:"string",description:"Optional base-trx UUIDv4. Triplet is all-or-nothing."},baseTransactionType:{type:"string",description:"Optional. Must be one of allowedBaseTransactionTypes for the recipe (SALE | PURCHASE | JOURNAL_MANUAL | JOURNAL_DIRECT_CASH_IN | JOURNAL_DIRECT_CASH_OUT | JOURNAL_CASHFLOW). Triplet is all-or-nothing."},organizationResourceId:{type:"string",description:"Optional org UUIDv4. Triplet is all-or-nothing."},templateOverrides:Iet},required:["recipeName","inputs"],group:"capsule_recipes",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview recipe blueprint amortization schedule without posting verify inputs",execute:async(e,t)=>{let r=t;return ea(r),Fj(e.client,r)}},{name:"resume_capsule_recipe",description:"Server-side recipe lifecycle. Resume a FAILED recipe job from the leg that failed. NOT idempotent \u2014 each call counts toward the 3-attempt limit. After 3 same-leg failures the job is terminally BLOCKED_AFTER_3_RESUME_ATTEMPTS and only rollback_capsule_recipe remains. Returns the updated CapsuleRecipeJob handle with status, resumeAttempts, terminalReason.",params:{capsuleResourceId:{type:"string",description:"UUIDv4 of the capsule whose recipe job is being resumed."}},required:["capsuleResourceId"],group:"capsule_recipes",readOnly:!1,searchHint:"retry failed recipe job leg resume after failure",execute:async(e,t)=>Oj(e.client,t.capsuleResourceId)},{name:"rollback_capsule_recipe",description:`Server-side recipe lifecycle. Delete every scheduler atom posted by this capsule's recipe. dryRun=true returns the would-delete list without deleting (idempotent, safe to call repeatedly). dryRun=false performs the delete. Status enum: SUCCESS | BLOCKED | PARTIAL_ROLLBACK | DRY_RUN. PARTIAL_ROLLBACK with blockedAtomResourceIds[] means some atoms are referenced downstream \u2014 retry idempotent; escalate if persistent. Capsules NOT created via the recipe engine return 422 RECIPE_ROLLBACK_JOB_NOT_FOUND ("nothing to roll back").`,params:{capsuleResourceId:{type:"string",description:"UUIDv4 of the capsule to roll back."},dryRun:{type:"boolean",description:"When true (recommended first), preview the would-delete list without actually deleting. Default false."}},required:["capsuleResourceId"],group:"capsule_recipes",readOnly:!1,searchHint:"rollback recipe undo delete scheduler atoms dry run preview",execute:async(e,t)=>{let r=t.dryRun??!1;return Qj(e.client,t.capsuleResourceId,{dryRun:r})}},{name:"create_scheduled_journal",description:`Recurring journal. Use \`schedulerEntries\` (NOT journalEntries) \u2014 each needs accountResourceId, amount, type (DEBIT|CREDIT), name. Use \`repeat\` (NOT frequency/interval): WEEKLY|MONTHLY|QUARTERLY|YEARLY. Debits must equal credits. Flat structure \u2014 reference, valueDate, saveAsDraft at top level.
785
+ Requires startDate. Auto-resolves accounts from CoA. Provide bankAccountName for recipes with cash-in/cash-out steps, contactName for recipes with invoice/bill steps.`,params:{recipe:{type:"string",enum:[...Jg],description:"Recipe type"},amount:{type:"number"},principal:{type:"number"},startDate:{type:"string",description:"Start date YYYY-MM-DD (REQUIRED for execution)"},currency:{type:"string"},periods:{type:"number"},frequency:{type:"string",enum:["monthly","quarterly","annual"]},annualRate:{type:"number"},termMonths:{type:"number"},monthlyPayment:{type:"number"},usefulLifeMonths:{type:"number"},cost:{type:"number"},salvageValue:{type:"number"},usefulLifeYears:{type:"number"},method:{type:"string",enum:["sl","ddb","150db"]},acquisitionDate:{type:"string"},disposalDate:{type:"string"},proceeds:{type:"number"},bookRate:{type:"number"},closingRate:{type:"number"},baseCurrency:{type:"string"},buckets:{type:"array",items:{type:"object",properties:{name:{type:"string"},balance:{type:"number"},rate:{type:"number"}},required:["name","balance","rate"]}},existingProvision:{type:"number"},compounding:{type:"string",enum:["none","monthly","quarterly","annually"]},employees:{type:"number"},daysPerYear:{type:"number"},dailyRate:{type:"number"},declarationDate:{type:"string"},paymentDate:{type:"string"},withholdingRate:{type:"number"},bankAccountName:{type:"string",description:"Bank/cash account name (for cash-in/cash-out steps) \u2014 auto-resolved by fuzzy match"},contactName:{type:"string",description:"Contact name (for invoice/bill steps) \u2014 auto-resolved by fuzzy match"},existingTxnId:{type:"string",description:"Attach to existing transaction \u2014 skip initial step"},referencePrefix:{type:"string",description:"Reference prefix (generates prefix-1, prefix-2, ...)"},finalize:{type:"boolean",description:"Approve transactions immediately (default: drafts)"}},required:["recipe","startDate"],group:"recipes",readOnly:!1,searchHint:"execute transaction recipe capsule blueprint with dated steps. Posts depreciation, amortization, prepaid, deferred revenue, IFRS 16 lease, hire purchase, loan, fixed deposit, FX revaluation, ECL, IAS 37 provision, asset disposal, accrued expense, leave accrual, dividend entries.",maxResultSizeChars:1e5,execute:async(e,t)=>{let r=t.recipe,n=Is(r,t),i=VR(n);if(!i)throw new Error("No blueprint generated. Ensure startDate is provided.");let s=rv(r,n),o=await OXe(e.client,s.plan.requiredAccounts);if(o.failures.length>0){let u=o.failures.map(f=>`${f.name}${f.candidates.length>0?` (closest: ${f.candidates.join(", ")})`:""}`).join("; ");throw new Error(`Cannot auto-resolve ${o.failures.length} account(s): ${u}. Create them in Jaz first.`)}let a;t.contactName&&(a=(await QXe(e.client,t.contactName)).resourceId);let c;return t.bankAccountName&&(c=(await LXe(e.client,t.bankAccountName)).resourceId),yj(e.client,{blueprint:i,calcType:r,accountMap:o.mapping,bankAccountId:c,contactId:a,existingTxnId:t.existingTxnId,referencePrefix:t.referencePrefix,finalize:t.finalize})}},{name:"list_capsule_recipes",description:"Server-side recipe lifecycle (NOT the offline calculator \u2014 for offline planning use plan_recipe + execute_recipe). List all registered IFRS capsule recipes with per-version JSON Schemas. Source of truth for recipeName values used in capsuleRecipe payloads on trigger mutations (create_bill, create_journal, create_cash_in, etc.) \u2014 DON'T hard-code the 5 enum values. Each descriptor carries displayName, capsuleType, requiresBaseTransaction, allowedBaseTransactionTypes[], expectedAtomTypes[], and versions[] with inputSchema (JSON Schema Draft 7) per version.",params:{},required:[],group:"capsule_recipes",readOnly:!0,isConcurrencySafe:!0,searchHint:"list available IFRS capsule recipes amortization deferred revenue loan lease accrual",execute:async e=>kj(e.client)},{name:"get_capsule_recipe",description:"Get one capsule recipe descriptor by enum name. inputSchema at `data.versions[0].inputSchema` (NOT top-level). Carries `allowedBaseTransactionTypes`, `x-accountClass` per *AccountResourceId slot, `x-baseTrxBinding` for auto-fills, and `versions[].templateSlots[]` \u2014 the slotKeys + supportedVariables you can pass to capsuleRecipe.templateOverrides (Customize Recipe). Use list_capsule_recipes for available names.",params:{name:{type:"string",description:"Recipe enum name (uppercase, see list_capsule_recipes for valid values)."}},required:["name"],group:"capsule_recipes",readOnly:!0,isConcurrencySafe:!0,searchHint:"recipe descriptor inputs required fields prepaid loan deferred lease accrual",execute:async(e,t)=>Nj(e.client,t.name)},{name:"preview_capsule_recipe",description:"Compute the blueprint a recipe would build, WITHOUT persisting. Returns { legs[], expectedOutput[], previewMarkdown }. **Pre-flight gate** before sending capsuleRecipe payloads \u2014 trigger mutations silently null on publish failure but preview surfaces every problem as a clean 422 (ERR_RECIPE_ACCOUNT_CURRENCY_MISMATCH, RECIPE_INVALID_BASE_TRANSACTION_TYPE, ERR_RECIPE_OVERRIDE_* \u2014 Rule 143). Also the gate for templateOverrides: invalid slotKeys/variables come back as ERR_RECIPE_OVERRIDE_* here. The base-trx triplet (baseTransactionResourceId, baseTransactionType, organizationResourceId) is all-or-nothing \u2014 supply all three to auto-fill totalAmount/currency/anchor dates, OR omit all three for a pure compute preview.",params:{recipeName:{type:"string",description:"Recipe enum name. Source of truth: list_capsule_recipes."},recipeVersion:{type:"number",description:"Optional version pin (default: latest registered)."},inputs:{type:"object",description:"Recipe-specific inputs object. See descriptor.versions[].inputSchema (via get_capsule_recipe) for per-recipe shape. Must be non-null."},baseTransactionResourceId:{type:"string",description:"Optional base-trx UUIDv4. Triplet is all-or-nothing."},baseTransactionType:{type:"string",description:"Optional. Must be one of allowedBaseTransactionTypes for the recipe (SALE | PURCHASE | JOURNAL_MANUAL | JOURNAL_DIRECT_CASH_IN | JOURNAL_DIRECT_CASH_OUT | JOURNAL_CASHFLOW). Triplet is all-or-nothing."},organizationResourceId:{type:"string",description:"Optional org UUIDv4. Triplet is all-or-nothing."},templateOverrides:Iet},required:["recipeName","inputs"],group:"capsule_recipes",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview recipe blueprint amortization schedule without posting verify inputs",execute:async(e,t)=>{let r=t;return ea(r),Fj(e.client,r)}},{name:"resume_capsule_recipe",description:"Server-side recipe lifecycle. Resume a FAILED recipe job from the leg that failed. NOT idempotent \u2014 each call counts toward the 3-attempt limit. After 3 same-leg failures the job is terminally BLOCKED_AFTER_3_RESUME_ATTEMPTS and only rollback_capsule_recipe remains. Returns the updated CapsuleRecipeJob handle with status, resumeAttempts, terminalReason.",params:{capsuleResourceId:{type:"string",description:"UUIDv4 of the capsule whose recipe job is being resumed."}},required:["capsuleResourceId"],group:"capsule_recipes",readOnly:!1,searchHint:"retry failed recipe job leg resume after failure",execute:async(e,t)=>Oj(e.client,t.capsuleResourceId)},{name:"rollback_capsule_recipe",description:`Server-side recipe lifecycle. Delete every scheduler atom posted by this capsule's recipe. dryRun=true returns the would-delete list without deleting (idempotent, safe to call repeatedly). dryRun=false performs the delete. Status enum: SUCCESS | BLOCKED | PARTIAL_ROLLBACK | DRY_RUN. PARTIAL_ROLLBACK with blockedAtomResourceIds[] means some atoms are referenced downstream \u2014 retry idempotent; escalate if persistent. Capsules NOT created via the recipe engine return 422 RECIPE_ROLLBACK_JOB_NOT_FOUND ("nothing to roll back").`,params:{capsuleResourceId:{type:"string",description:"UUIDv4 of the capsule to roll back."},dryRun:{type:"boolean",description:"When true (recommended first), preview the would-delete list without actually deleting. Default false."}},required:["capsuleResourceId"],group:"capsule_recipes",readOnly:!1,searchHint:"rollback recipe undo delete scheduler atoms dry run preview",execute:async(e,t)=>{let r=t.dryRun??!1;return Qj(e.client,t.capsuleResourceId,{dryRun:r})}},{name:"create_scheduled_journal",description:`Recurring journal. Use \`schedulerEntries\` (NOT journalEntries) \u2014 each needs accountResourceId, amount, type (DEBIT|CREDIT), name. Use \`repeat\` (NOT frequency/interval): ONE_TIME|DAILY|WEEKLY|MONTHLY|YEARLY. Debits must equal credits. Flat structure \u2014 reference, valueDate, saveAsDraft at top level.
786
786
 
787
- Dynamic strings (reference/name/notes): ${lx}.`,params:{reference:{type:"string",description:"Journal reference"},valueDate:{type:"string",description:"Template date (YYYY-MM-DD)"},startDate:{type:"string",description:"First occurrence (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence (YYYY-MM-DD, optional)"},repeat:{type:"string",enum:["WEEKLY","MONTHLY","QUARTERLY","YEARLY"],description:"Recurrence interval"},schedulerEntries:{type:"array",items:{type:"object",properties:{accountResourceId:ty,amount:{type:"number"},type:{type:"string",enum:["DEBIT","CREDIT"]},name:{type:"string",description:"Line description"}},required:["accountResourceId","amount","type"]}},notes:{type:"string",description:"Journal notes"}},required:["startDate","repeat","valueDate","schedulerEntries"],group:"schedulers",readOnly:!1,searchHint:"create recurring scheduled journal entry",execute:async(e,t)=>JD(e.client,{status:"ACTIVE",startDate:t.startDate,endDate:t.endDate,repeat:t.repeat,valueDate:t.valueDate,schedulerEntries:t.schedulerEntries,reference:t.reference,internalNotes:t.notes})},{name:"create_scheduled_invoice",description:`Recurring invoice. Use for fixed-amount recurrence where you want per-period control over currency / tax / line items. DIFFERENT from subscriptions: no proration, but currency/tax/items can differ per occurrence.
787
+ Dynamic strings (reference/name/notes): ${lx}.`,params:{reference:{type:"string",description:"Journal reference"},valueDate:{type:"string",description:"Template date (YYYY-MM-DD)"},startDate:{type:"string",description:"First occurrence (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence (YYYY-MM-DD, optional)"},repeat:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Recurrence interval (QUARTERLY is rejected with 422)"},schedulerEntries:{type:"array",items:{type:"object",properties:{accountResourceId:ty,amount:{type:"number"},type:{type:"string",enum:["DEBIT","CREDIT"]},name:{type:"string",description:"Line description"}},required:["accountResourceId","amount","type"]}},notes:{type:"string",description:"Journal notes"}},required:["startDate","repeat","valueDate","schedulerEntries"],group:"schedulers",readOnly:!1,searchHint:"create recurring scheduled journal entry",execute:async(e,t)=>JD(e.client,{status:"ACTIVE",startDate:t.startDate,endDate:t.endDate,repeat:t.repeat,valueDate:t.valueDate,schedulerEntries:t.schedulerEntries,reference:t.reference,internalNotes:t.notes})},{name:"create_scheduled_invoice",description:`Recurring invoice. Use for fixed-amount recurrence where you want per-period control over currency / tax / line items. DIFFERENT from subscriptions: no proration, but currency/tax/items can differ per occurrence.
788
788
 
789
- CRITICAL: saveAsDraft MUST be false (API rejects INVALID_SALE_STATUS). Use \`repeat\` (NOT frequency/interval): WEEKLY | MONTHLY | QUARTERLY | YEARLY. Each lineItem needs name, unitPrice, quantity, accountResourceId.
789
+ CRITICAL: saveAsDraft MUST be false (API rejects INVALID_SALE_STATUS). Use \`repeat\` (NOT frequency/interval): ONE_TIME | DAILY | WEEKLY | MONTHLY | YEARLY. Each lineItem needs name, unitPrice, quantity, accountResourceId.
790
790
 
791
- Dynamic strings (reference/name/notes): ${lx}.`,params:{startDate:{type:"string",description:"First occurrence (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence (YYYY-MM-DD, optional)"},repeat:{type:"string",enum:["WEEKLY","MONTHLY","QUARTERLY","YEARLY"],description:"Recurrence interval"},contactResourceId:{type:"string",description:"Customer contact resourceId"},reference:{type:"string",description:"Invoice reference"},valueDate:{type:"string",description:"Template issue date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Template due date (YYYY-MM-DD)"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string"},unitPrice:{type:"number"},quantity:{type:"number"},accountResourceId:ty,taxProfileResourceId:{type:"string"}},required:["name","unitPrice","quantity","accountResourceId"]}},tag:{type:"string",description:"Tag name"}},required:["startDate","repeat","contactResourceId","reference","valueDate","dueDate","lineItems"],group:"schedulers",readOnly:!1,searchHint:"create recurring scheduled invoice subscription",execute:async(e,t)=>qD(e.client,{status:"ACTIVE",startDate:t.startDate,endDate:t.endDate,repeat:t.repeat,invoice:{reference:t.reference,valueDate:t.valueDate,dueDate:t.dueDate,contactResourceId:t.contactResourceId,lineItems:t.lineItems,tags:t.tag?[t.tag]:void 0,saveAsDraft:!1}})},{name:"create_scheduled_bill",description:`Create a scheduled (recurring) bill. CRITICAL:
791
+ Dynamic strings (reference/name/notes): ${lx}.`,params:{startDate:{type:"string",description:"First occurrence (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence (YYYY-MM-DD, optional)"},repeat:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Recurrence interval (QUARTERLY is rejected with 422)"},contactResourceId:{type:"string",description:"Customer contact resourceId"},reference:{type:"string",description:"Invoice reference"},valueDate:{type:"string",description:"Template issue date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Template due date (YYYY-MM-DD)"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string"},unitPrice:{type:"number"},quantity:{type:"number"},accountResourceId:ty,taxProfileResourceId:{type:"string"}},required:["name","unitPrice","quantity","accountResourceId"]}},tag:{type:"string",description:"Tag name"}},required:["startDate","repeat","contactResourceId","reference","valueDate","dueDate","lineItems"],group:"schedulers",readOnly:!1,searchHint:"create recurring scheduled invoice subscription",execute:async(e,t)=>qD(e.client,{status:"ACTIVE",startDate:t.startDate,endDate:t.endDate,repeat:t.repeat,invoice:{reference:t.reference,valueDate:t.valueDate,dueDate:t.dueDate,contactResourceId:t.contactResourceId,lineItems:t.lineItems,tags:t.tag?[t.tag]:void 0,saveAsDraft:!1}})},{name:"create_scheduled_bill",description:`Create a scheduled (recurring) bill. CRITICAL:
792
792
  - saveAsDraft MUST be false (API rejects INVALID_PURCHASE_STATUS otherwise).
793
- - Use repeat (NOT frequency/interval): WEEKLY, MONTHLY, QUARTERLY, YEARLY.
793
+ - Use repeat (NOT frequency/interval): ONE_TIME, DAILY, WEEKLY, MONTHLY, YEARLY.
794
794
  - Each lineItem needs name, unitPrice, quantity, accountResourceId.
795
- Dynamic strings (reference/name/notes): ${lx} \u2014 relative to transaction date.`,params:{startDate:{type:"string",description:"First occurrence (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence (YYYY-MM-DD, optional)"},repeat:{type:"string",enum:["WEEKLY","MONTHLY","QUARTERLY","YEARLY"],description:"Recurrence interval"},contactResourceId:{type:"string",description:"Supplier contact resourceId"},reference:{type:"string",description:"Bill reference"},valueDate:{type:"string",description:"Template issue date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Template due date (YYYY-MM-DD)"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string"},unitPrice:{type:"number"},quantity:{type:"number"},accountResourceId:ty,taxProfileResourceId:{type:"string"}},required:["name","unitPrice","quantity","accountResourceId"]}},tag:{type:"string",description:"Tag name"}},required:["startDate","repeat","contactResourceId","reference","valueDate","dueDate","lineItems"],group:"schedulers",readOnly:!1,searchHint:"create recurring scheduled bill subscription",execute:async(e,t)=>ZI(e.client,{status:"ACTIVE",startDate:t.startDate,endDate:t.endDate,repeat:t.repeat,bill:{reference:t.reference,valueDate:t.valueDate,dueDate:t.dueDate,contactResourceId:t.contactResourceId,lineItems:t.lineItems,tags:t.tag?[t.tag]:void 0,saveAsDraft:!1}})},{name:"update_journal",description:"Update an existing journal entry. Can modify reference, valueDate, entries, notes. Set saveAsDraft=false to finalize. Optional capsuleRecipe retro-attaches a recipe; same base-type constraint as create variant. Mutex with capsuleResourceId. Rule 143.",params:{resourceId:{type:"string",description:"Journal resourceId"},reference:{type:"string",description:"Updated reference"},valueDate:{type:"string",description:"Updated date (YYYY-MM-DD)"},journalEntries:ey,notes:ni,tags:{type:"array",items:{type:"string"},description:"Tags (string array)"},saveAsDraft:{type:"boolean",description:"Keep as draft (default true)"},capsuleRecipe:Ll},required:["resourceId"],group:"journals",readOnly:!1,searchHint:"update journal entry lines reference notes capsule recipe",execute:async(e,t)=>(t.capsuleRecipe!==void 0&&ea(t.capsuleRecipe),jb(e.client,t.resourceId,{reference:t.reference,valueDate:t.valueDate,journalEntries:t.journalEntries,internalNotes:t.notes,tags:t.tags,saveAsDraft:t.saveAsDraft,...t.capsuleRecipe!==void 0&&{capsuleRecipe:t.capsuleRecipe}}))},{name:"bulk_update_journals",description:`Bulk-update journals \u2014 most common use is bulk-finalize (saveAsDraft: false on each row). Sync; per-row sequential execution; max 500 per call (~1-2 min wall-clock for a full 500).
795
+ Dynamic strings (reference/name/notes): ${lx} \u2014 relative to transaction date.`,params:{startDate:{type:"string",description:"First occurrence (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence (YYYY-MM-DD, optional)"},repeat:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Recurrence interval (QUARTERLY is rejected with 422)"},contactResourceId:{type:"string",description:"Supplier contact resourceId"},reference:{type:"string",description:"Bill reference"},valueDate:{type:"string",description:"Template issue date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Template due date (YYYY-MM-DD)"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string"},unitPrice:{type:"number"},quantity:{type:"number"},accountResourceId:ty,taxProfileResourceId:{type:"string"}},required:["name","unitPrice","quantity","accountResourceId"]}},tag:{type:"string",description:"Tag name"}},required:["startDate","repeat","contactResourceId","reference","valueDate","dueDate","lineItems"],group:"schedulers",readOnly:!1,searchHint:"create recurring scheduled bill subscription",execute:async(e,t)=>ZI(e.client,{status:"ACTIVE",startDate:t.startDate,endDate:t.endDate,repeat:t.repeat,bill:{reference:t.reference,valueDate:t.valueDate,dueDate:t.dueDate,contactResourceId:t.contactResourceId,lineItems:t.lineItems,tags:t.tag?[t.tag]:void 0,saveAsDraft:!1}})},{name:"update_journal",description:"Update an existing journal entry. Can modify reference, valueDate, entries, notes. Set saveAsDraft=false to finalize. Optional capsuleRecipe retro-attaches a recipe; same base-type constraint as create variant. Mutex with capsuleResourceId. Rule 143.",params:{resourceId:{type:"string",description:"Journal resourceId"},reference:{type:"string",description:"Updated reference"},valueDate:{type:"string",description:"Updated date (YYYY-MM-DD)"},journalEntries:ey,notes:ni,tags:{type:"array",items:{type:"string"},description:"Tags (string array)"},saveAsDraft:{type:"boolean",description:"Keep as draft (default true)"},capsuleRecipe:Ll},required:["resourceId"],group:"journals",readOnly:!1,searchHint:"update journal entry lines reference notes capsule recipe",execute:async(e,t)=>(t.capsuleRecipe!==void 0&&ea(t.capsuleRecipe),jb(e.client,t.resourceId,{reference:t.reference,valueDate:t.valueDate,journalEntries:t.journalEntries,internalNotes:t.notes,tags:t.tags,saveAsDraft:t.saveAsDraft,...t.capsuleRecipe!==void 0&&{capsuleRecipe:t.capsuleRecipe}}))},{name:"bulk_update_journals",description:`Bulk-update journals \u2014 most common use is bulk-finalize (saveAsDraft: false on each row). Sync; per-row sequential execution; max 500 per call (~1-2 min wall-clock for a full 500).
796
796
 
797
797
  bulk_finalize_drafts only handles invoices/bills/credit-notes \u2014 journals need this. Common monthly-close pattern: search_journals(filter:{capsuleResourceId:{eq:<id>}, status:{eq:'DRAFT'}}) \u2192 map to {resourceId, saveAsDraft: false} \u2192 bulk_update_journals.
798
798
 
@@ -829,7 +829,7 @@ accountResourceId + taxProfileResourceId apply to ALL line items (immutable). in
829
829
 
830
830
  Dynamic strings (reference/lineItem name/notes): ${lx} \u2014 relative to transaction date.`,params:{interval:{type:"string",enum:["WEEKLY","MONTHLY","QUARTERLY","YEARLY"],description:"Billing interval"},startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD, optional for ongoing)"},contactResourceId:{type:"string",description:"Customer contact resourceId"},reference:{type:"string",description:"Invoice reference (REQUIRED). Supports dynamic strings: {{Month}}, {{Year}}, etc."},valueDate:{type:"string",description:"Invoice date (YYYY-MM-DD)"},dueDate:{type:"string",description:"Due date (YYYY-MM-DD)"},accountResourceId:{type:"string",description:"Revenue account resourceId (applied to ALL line items \u2014 must be same)"},taxProfileResourceId:{type:"string",description:"Tax profile resourceId (applied to ALL line items \u2014 must be same)"},lineItems:{type:"array",items:{type:"object",properties:{name:{type:"string"},unitPrice:{type:"number"},quantity:{type:"number"}},required:["name","unitPrice","quantity"]},description:"Line items (name, unitPrice, quantity only \u2014 account/tax set at top level)"},proratedConfig:{type:"object",description:"Optional prorated-period customization. All fields optional.",properties:{proratedStartDate:{type:"string",description:"Prorated window start (YYYY-MM-DD). Defaults to subscription startDate."},proratedAdjustmentLineText:{type:"string",description:'Adjustment line label on the prorated invoice (default "Prorated adjustment").'},itemResourceId:{type:"string",description:"Non-inventory item resourceId (UUIDv4) for the prorated adjustment line. Defaults to the subscription's first line item."},includeNextPeriod:{type:"boolean",description:"If true: bundle the next full period at 2x quantity AND advance nextScheduleDate by one extra interval. Response carries bundledPeriodEndDate + bundledAmount."}}}},required:["interval","startDate","contactResourceId","lineItems","accountResourceId","valueDate","dueDate","reference"],group:"subscriptions",readOnly:!1,searchHint:"create new recurring subscription billing schedule with proration",execute:async(e,t)=>{let{interval:r,startDate:n,endDate:i,contactResourceId:s,reference:o,valueDate:a,dueDate:c,accountResourceId:u,taxProfileResourceId:f,lineItems:d,proratedConfig:p}=t,h=d.map(m=>({...m,accountResourceId:u,...f?{taxProfileResourceId:f}:{}})),A={repeat:r,startDate:n,status:"ACTIVE",proratedConfig:{proratedAdjustmentLineText:"Prorated adjustment",...p??{}},invoice:{contactResourceId:s,reference:o||`SUB-${Date.now()}`,valueDate:a,dueDate:c,lineItems:h,saveAsDraft:!1}};return i&&(A.endDate=i),nY(e.client,A)}},{name:"update_subscription",description:"Update an existing subscription (interval, end date, transaction template, or proratedConfig). When the user asks to update a subscription, use this tool directly. NOTE: accountResourceId and taxProfileResourceId on line items are immutable after creation \u2014 to change them, cancel and recreate. proratedConfig fields can be amended on update (proratedStartDate, proratedAdjustmentLineText, itemResourceId, includeNextPeriod).",params:{resourceId:{type:"string",description:"Subscription resourceId"},interval:{type:"string",enum:["WEEKLY","MONTHLY","QUARTERLY","YEARLY"]},endDate:{type:"string",description:"New end date (YYYY-MM-DD)"},proratedConfig:{type:"object",description:"Amend the prorated-period customization. All fields optional.",properties:{proratedStartDate:{type:"string",description:"YYYY-MM-DD"},proratedAdjustmentLineText:{type:"string"},itemResourceId:{type:"string",description:"UUIDv4"},includeNextPeriod:{type:"boolean"}}},data:{type:"object",description:"Updated transaction template"}},required:["resourceId"],group:"subscriptions",readOnly:!1,searchHint:"update subscription schedule amount details proration",execute:async(e,t)=>{let{resourceId:r,...n}=t;return iY(e.client,r,n)}},Ro("delete_subscription","Delete a subscription. Removes the recurring schedule.","subscriptions",(e,t)=>sY(e,t),"permanently delete a subscription schedule"),{name:"cancel_subscription",description:"Cancel an active subscription. Prorates remaining period and stops future billing. Safe to call \u2014 subscriptions can be reactivated after cancellation. Always use this tool when the user asks to cancel a subscription. Must cancel before delete.",params:{resourceId:{type:"string",description:"Subscription resourceId"},cancelDateType:{type:"string",enum:["END_OF_CURRENT_PERIOD","END_OF_LAST_PERIOD","CUSTOM_DATE"],description:"When to end (default: END_OF_CURRENT_PERIOD)"},endDate:{type:"string",description:"Custom cancel date YYYY-MM-DD (only with CUSTOM_DATE)"},proratedAdjustmentLineText:{type:"string",description:'Label for proration line item (default: "Prorated adjustment")'}},required:["resourceId"],group:"subscriptions",readOnly:!1,searchHint:"cancel stop a recurring subscription",isDestructive:!0,execute:async(e,t)=>oY(e.client,t.resourceId,{cancelDateType:t.cancelDateType,endDate:t.endDate,proratedAdjustmentLineText:t.proratedAdjustmentLineText})},tn({name:"search_scheduled_transactions",description:"Search scheduled transactions (subscriptions / recurring invoices / journals / cash entries).",group:"subscriptions",fields:ED,defaults:bD,fetcher:aY,searchHint:"find scheduled recurring transactions subscriptions schedulers by type status interval contact"}),{name:"generate_vat_ledger",description:"Generate VAT/GST ledger report showing all tax transactions for the period.",params:{startDate:{type:"string",description:"Start date (YYYY-MM-DD)"},endDate:{type:"string",description:"End date (YYYY-MM-DD)"}},required:["startDate","endDate"],group:"financial_reports",readOnly:!0,searchHint:"generate VAT GST tax ledger report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>VL(e.client,{startDate:t.startDate,endDate:t.endDate})},{name:"generate_equity_movement",description:"Generate equity movement report (statement of changes in equity).",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'},compareWith:{type:"string",description:'Compare with period (e.g., "PREVIOUS_YEAR")'},compareCount:{type:"number",description:"Number of comparison periods"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"financial_reports",readOnly:!0,searchHint:"generate equity movement statement report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>JL(e.client,t)},{name:"generate_bank_balance_summary",description:"Generate bank balance summary report \u2014 snapshot of all bank account balances at a point in time.",params:{primarySnapshotDate:{type:"string",description:"Snapshot date (YYYY-MM-DD)"},currencyCode:{type:"string",description:'Currency code (e.g., "SGD")'}},required:["primarySnapshotDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank account balance summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>WL(e.client,{primarySnapshotDate:t.primarySnapshotDate,currencyCode:t.currencyCode})},{name:"generate_bank_recon_summary",description:"Generate bank reconciliation summary for a specific bank account. Essential for month-end close \u2014 call this for each in-scope bank account for the current entity and reporting period. Use for bank recon status, unreconciled items count, or reconciliation summaries.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},currencyCode:{type:"string",description:"Currency code"},tags:{type:"array",items:{type:"string"},description:"Filter by tags"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation summary report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>ZL(e.client,t)},{name:"generate_bank_recon_details",description:"Generate detailed bank reconciliation report showing matched/unmatched items.",params:{bankAccountResourceId:{type:"string",description:"Bank account resourceId"},primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},filter:{type:"object",description:'Filter criteria (e.g., { status: "UNMATCHED" })'},currencyCode:{type:"string",description:"Currency code"}},required:["bankAccountResourceId","primarySnapshotStartDate","primarySnapshotEndDate","filter"],group:"operational_reports",readOnly:!0,searchHint:"generate bank reconciliation detailed report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>KL(e.client,t)},{name:"generate_fa_summary",description:"Generate fixed assets summary report grouped by account, type, category, or status.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},groupBy:{type:"string",enum:["ACCOUNT","TYPE","CATEGORY","STATUS"],description:"Grouping dimension"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate","groupBy"],group:"operational_reports",readOnly:!0,searchHint:"generate fixed asset summary depreciation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>XL(e.client,t)},{name:"generate_fa_recon_summary",description:"Generate fixed assets reconciliation summary \u2014 reconciles asset register with general ledger.",params:{primarySnapshotStartDate:{type:"string",description:"Period start date (YYYY-MM-DD)"},primarySnapshotEndDate:{type:"string",description:"Period end date (YYYY-MM-DD)"},accountResourceIds:{type:"array",items:{type:"string"},description:"Filter by specific asset account IDs"},currencyCode:{type:"string",description:"Currency code"}},required:["primarySnapshotStartDate","primarySnapshotEndDate"],group:"operational_reports",readOnly:!0,searchHint:"generate fixed asset reconciliation report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>eM(e.client,t)},{name:"generate_ar_report",description:"Generate accounts receivable aging report. Shows outstanding invoices grouped by aging buckets. Use this when discussing customer payment allocation, credit control, or AR status \u2014 generate the report to show the full picture.",params:{endDate:{type:"string",description:"Report date (YYYY-MM-DD) \u2014 point-in-time snapshot"}},required:["endDate"],group:"operational_reports",readOnly:!0,searchHint:"generate detailed accounts receivable report",isConcurrencySafe:!0,maxResultSizeChars:1e5,execute:async(e,t)=>tM(e.client,{endDate:t.endDate})},{name:"get_ledger_highlights",description:"Get ledger highlights \u2014 summary metadata about the org general ledger: transaction counts by type, date range, active accounts, active currencies, and cross-currency detection. No parameters needed.",params:{},required:[],group:"operational_reports",readOnly:!0,searchHint:"get ledger highlights key metrics for period",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async e=>rM(e.client)},cn("list_contact_groups","List contact groups with their associated contacts. Used to segment customers/suppliers.","contact_groups",(e,t,r)=>cY(e,{limit:r,offset:t}),"list contact groups customer supplier categories"),Qa("get_contact_group","Get contact group details including all associated contacts.","contact_groups",(e,t)=>uY(e,t),"get contact group details members"),tn({name:"search_contact_groups",description:"Search contact groups.",group:"contact_groups",fields:ND,defaults:FD,fetcher:lY,searchHint:"find contact groups segments categories by name"}),{name:"create_contact_group",description:'Create a new contact group for segmenting contacts (e.g., "VIP Customers", "Government", "Overdue > 90 Days").',params:{name:{type:"string",description:"Group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to add to the group"}},required:["name"],group:"contact_groups",readOnly:!1,searchHint:"create new contact group category",execute:async(e,t)=>fY(e.client,{name:t.name,contactResourceIds:t.contactResourceIds})},{name:"update_contact_group",description:"Update a contact group name or members. NOTE: Update endpoint has a known 500 bug on some orgs \u2014 retry or recreate if it fails.",params:{resourceId:{type:"string",description:"Contact group resourceId"},name:{type:"string",description:"New group name"},contactResourceIds:{type:"array",items:{type:"string"},description:"Contact IDs to set as group members (replaces existing)"}},required:["resourceId"],group:"contact_groups",readOnly:!1,searchHint:"update contact group name details",execute:async(e,t)=>dY(e.client,t.resourceId,{name:t.name,contactResourceIds:t.contactResourceIds})},Ro("delete_contact_group","Delete a contact group. Does not delete the contacts themselves.","contact_groups",(e,t)=>pY(e,t),"permanently delete a contact group"),cn("list_custom_fields","List custom fields defined for the organization. Custom fields add extra data to invoices, bills, credit notes, and payments.","custom_fields",(e,t,r)=>gY(e,{limit:r,offset:t}),"list custom fields metadata on transactions"),{name:"get_custom_field",description:"Get a custom field by resourceId. Returns full definition including appliesTo flags and list options.",params:{resourceId:{type:"string",description:"Custom field resourceId"}},required:["resourceId"],group:"custom_fields",readOnly:!0,searchHint:"get custom field definition details",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>yY(e.client,t.resourceId)},tn({name:"search_custom_fields",description:"Search custom fields.",group:"custom_fields",fields:TD,defaults:kD,fetcher:EY,searchHint:"find custom fields user-defined attributes by name data type"}),{name:"create_custom_field",description:`Create a new custom field. Custom fields appear on transactions (invoices, bills, credit notes, payments).
831
831
  - Use appliesTo to control which transaction types show this field.
832
- - printOnDocuments controls whether the field appears on PDFs.`,params:{name:{type:"string",description:'Field name (e.g., "PO Number", "Cost Center")'},description:{type:"string",description:"Field description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents (default false)"},appliesTo:{type:"object",description:"Which transaction types: { invoices: true, bills: true, customerCredits: true, supplierCredits: true, payments: true }"},fieldType:{type:"string",description:'Field type (e.g., "TEXT", "NUMBER", "DATE") \u2014 legacy param'},entityType:{type:"string",description:"Entity type \u2014 legacy param"}},required:["name"],group:"custom_fields",readOnly:!1,searchHint:"create new custom field for transactions",execute:async(e,t)=>bY(e.client,t)},{name:"update_custom_field",description:"Update a custom field definition. Can change name, description, printOnDocuments, and appliesTo flags.",params:{resourceId:{type:"string",description:"Custom field resourceId"},name:{type:"string",description:"New field name"},description:{type:"string",description:"New description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents"},appliesTo:{type:"object",description:"Which transaction types: { invoices, bills, customerCredits, supplierCredits, payments }"}},required:["resourceId"],group:"custom_fields",readOnly:!1,searchHint:"update custom field name type settings",execute:async(e,t)=>{let{resourceId:r,...n}=t;return CY(e.client,r,n)}},Ro("delete_custom_field","Delete a custom field. Removes it from all future transactions.","custom_fields",(e,t)=>vY(e,t),"permanently delete a custom field definition"),{name:"list_withholding_tax_codes",description:"List withholding tax codes (industry classification codes for PH/SG compliance). Returns full list (no pagination).",params:{},required:[],group:"tax_profiles",readOnly:!0,searchHint:"list withholding tax WHT codes",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async e=>UQ(e.client)},tn({name:"search_tax_profiles",description:"Search tax profiles. Use appliesToSale / appliesToPurchase filters to scope by transaction type.",group:"tax_profiles",fields:SD,defaults:BD,fetcher:Db,searchHint:"find tax profiles GST VAT WHT by name tax type code applicability sale purchase"}),Qa("get_tax_profile","Get full tax profile details including tax rate, type code, and status.","tax_profiles",(e,t)=>PQ(e,t),"get tax profile details rate code"),{name:"update_tax_profile",description:"Update an existing tax profile (name, rate, or status).",params:{resourceId:{type:"string",description:"Tax profile resourceId"},name:Tce,taxRate:{type:"number"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Status (ACTIVE or INACTIVE)"}},required:["resourceId"],group:"tax_profiles",readOnly:!1,searchHint:"update tax profile name rate details",execute:async(e,t)=>$Q(e.client,t.resourceId,{name:t.name,taxRate:t.taxRate,status:t.status})},cn("list_inventory_items","List inventory-tracked items with stock details, COGS accounts, and purchase/sale accounts.","inventory",(e,t,r)=>hY(e,{limit:r,offset:t}),"list inventory items stock levels quantities"),{name:"get_inventory_balance",description:"Get current inventory balance for a specific item \u2014 quantity on hand, average cost, base unit.",params:{itemResourceId:{type:"string",description:"Item resourceId"}},required:["itemResourceId"],group:"inventory",readOnly:!0,searchHint:"get inventory balance stock level for item",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>mY(e.client,t.itemResourceId)},{name:"create_inventory_item",description:"Create a new inventory-tracked item. Requires itemCode, name, costingMethod (FIXED or WAC), cogsResourceId, and account links. Use --input for full JSON body.",params:{itemCode:{type:"string",description:"Unique item code (SKU)"},name:{type:"string",description:"Item name"},unit:{type:"string",description:'Unit of measure (e.g., "pcs", "kg")'},costingMethod:{type:"string",description:"Costing method: FIXED or WAC"},cogsResourceId:{type:"string",description:"COGS account resourceId (required)"},purchaseAccountResourceId:{type:"string",description:"Purchase account resourceId (required if cogsResourceId set)"},saleAccountResourceId:{type:"string",description:"Sale account resourceId (required if cogsResourceId set)"},appliesToSale:{type:"boolean",description:"Whether item applies to sales (required if cogsResourceId set)"},appliesToPurchase:{type:"boolean",description:"Whether item applies to purchases (required if cogsResourceId set)"},blockInsufficientDeductions:{type:"boolean",description:"Block transactions when insufficient stock (default: false)"}},required:["itemCode","name","costingMethod","cogsResourceId"],group:"inventory",readOnly:!1,searchHint:"create new inventory tracked stock item",execute:async(e,t)=>{let r={itemCode:t.itemCode,name:t.name,costingMethod:t.costingMethod,cogsResourceId:t.cogsResourceId,blockInsufficientDeductions:t.blockInsufficientDeductions??!1};return t.unit&&(r.unit=t.unit),t.purchaseAccountResourceId&&(r.purchaseAccountResourceId=t.purchaseAccountResourceId),t.saleAccountResourceId&&(r.saleAccountResourceId=t.saleAccountResourceId),t.appliesToSale!==void 0&&(r.appliesToSale=t.appliesToSale),t.appliesToPurchase!==void 0&&(r.appliesToPurchase=t.appliesToPurchase),AY(e.client,r)}},Ro("delete_contact","Delete a contact. Cannot delete contacts with existing transactions.","contacts",(e,t)=>gO(e,t),"permanently delete a customer supplier contact"),Ro("delete_account","Delete a chart of accounts entry. Cannot delete accounts with existing transactions.","accounts",(e,t)=>XQ(e,t),"permanently delete a chart of accounts entry"),Qa("get_cash_transfer","Get full cash transfer details by resourceId.","cash_transfers",(e,t)=>rj(e,t),"get cash transfer details between accounts"),{name:"download_credit_note_pdf",description:"Download a customer credit note as PDF. Returns a file URL.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"}},required:["resourceId"],group:"customer_credit_notes",readOnly:!0,searchHint:"download customer credit note as PDF file",isConcurrencySafe:!0,execute:async(e,t)=>aM(e.client,t.resourceId)},{name:"get_transaction_summary",description:`Get a complete summary of any transaction \u2014 fetches the transaction, its attachments, and payment history in one call.
832
+ - printOnDocuments controls whether the field appears on PDFs.`,params:{name:{type:"string",description:'Field name (e.g., "PO Number", "Cost Center")'},description:{type:"string",description:"Field description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents (default false)"},appliesTo:{type:"object",description:"Which transaction types: { invoices: true, bills: true, customerCredits: true, supplierCredits: true, payments: true }"},fieldType:{type:"string",description:'Field type (e.g., "TEXT", "NUMBER", "DATE") \u2014 legacy param'},entityType:{type:"string",description:"Entity type \u2014 legacy param"}},required:["name"],group:"custom_fields",readOnly:!1,searchHint:"create new custom field for transactions",execute:async(e,t)=>bY(e.client,t)},{name:"update_custom_field",description:"Update a custom field definition. Can change name, description, printOnDocuments, and appliesTo flags.",params:{resourceId:{type:"string",description:"Custom field resourceId"},name:{type:"string",description:"New field name"},description:{type:"string",description:"New description"},printOnDocuments:{type:"boolean",description:"Show on PDF documents"},appliesTo:{type:"object",description:"Which transaction types: { invoices, bills, customerCredits, supplierCredits, payments }"}},required:["resourceId"],group:"custom_fields",readOnly:!1,searchHint:"update custom field name type settings",execute:async(e,t)=>{let{resourceId:r,...n}=t;return CY(e.client,r,n)}},Ro("delete_custom_field","Delete a custom field. Removes it from all future transactions.","custom_fields",(e,t)=>vY(e,t),"permanently delete a custom field definition"),{name:"list_withholding_tax_codes",description:"List withholding tax codes (industry classification codes for PH/SG compliance). Returns full list (no pagination).",params:{},required:[],group:"tax_profiles",readOnly:!0,searchHint:"list withholding tax WHT codes",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async e=>UQ(e.client)},tn({name:"search_tax_profiles",description:"Search tax profiles. Use appliesToSale / appliesToPurchase filters to scope by transaction type.",group:"tax_profiles",fields:SD,defaults:BD,fetcher:Db,searchHint:"find tax profiles GST VAT WHT by name tax type code applicability sale purchase"}),Qa("get_tax_profile","Get full tax profile details including tax rate, type code, and status.","tax_profiles",(e,t)=>PQ(e,t),"get tax profile details rate code"),{name:"update_tax_profile",description:"Update an existing tax profile (name, rate, or status).",params:{resourceId:{type:"string",description:"Tax profile resourceId"},name:Tce,taxRate:{type:"number"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Status (ACTIVE or INACTIVE)"}},required:["resourceId"],group:"tax_profiles",readOnly:!1,searchHint:"update tax profile name rate details",execute:async(e,t)=>$Q(e.client,t.resourceId,{name:t.name,taxRate:t.taxRate,status:t.status})},cn("list_inventory_items","List inventory-tracked items with stock details, COGS accounts, and purchase/sale accounts.","inventory",(e,t,r)=>hY(e,{limit:r,offset:t}),"list inventory items stock levels quantities"),{name:"get_inventory_balance",description:"Get current inventory balance for a specific item \u2014 quantity on hand, average cost, base unit.",params:{itemResourceId:{type:"string",description:"Item resourceId"}},required:["itemResourceId"],group:"inventory",readOnly:!0,searchHint:"get inventory balance stock level for item",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>mY(e.client,t.itemResourceId)},{name:"create_inventory_item",description:"Create a new inventory-tracked item. Requires itemCode, name, costingMethod (FIXED or WAC), cogsResourceId, and account links. Use --input for full JSON body.",params:{itemCode:{type:"string",description:"Unique item code (SKU)"},name:{type:"string",description:"Item name"},unit:{type:"string",description:'Unit of measure (e.g., "pcs", "kg")'},costingMethod:{type:"string",enum:["FIXED","WAC"],description:"Costing method: FIXED or WAC"},cogsResourceId:{type:"string",description:"COGS account resourceId (required)"},purchaseAccountResourceId:{type:"string",description:"Purchase account resourceId (required if cogsResourceId set)"},saleAccountResourceId:{type:"string",description:"Sale account resourceId (required if cogsResourceId set)"},appliesToSale:{type:"boolean",description:"Whether item applies to sales (required if cogsResourceId set)"},appliesToPurchase:{type:"boolean",description:"Whether item applies to purchases (required if cogsResourceId set)"},blockInsufficientDeductions:{type:"boolean",description:"Block transactions when insufficient stock (default: false)"}},required:["itemCode","name","costingMethod","cogsResourceId"],group:"inventory",readOnly:!1,searchHint:"create new inventory tracked stock item",execute:async(e,t)=>{let r={itemCode:t.itemCode,name:t.name,costingMethod:t.costingMethod,cogsResourceId:t.cogsResourceId,blockInsufficientDeductions:t.blockInsufficientDeductions??!1};return t.unit&&(r.unit=t.unit),t.purchaseAccountResourceId&&(r.purchaseAccountResourceId=t.purchaseAccountResourceId),t.saleAccountResourceId&&(r.saleAccountResourceId=t.saleAccountResourceId),t.appliesToSale!==void 0&&(r.appliesToSale=t.appliesToSale),t.appliesToPurchase!==void 0&&(r.appliesToPurchase=t.appliesToPurchase),AY(e.client,r)}},Ro("delete_contact","Delete a contact. Cannot delete contacts with existing transactions.","contacts",(e,t)=>gO(e,t),"permanently delete a customer supplier contact"),Ro("delete_account","Delete a chart of accounts entry. Cannot delete accounts with existing transactions.","accounts",(e,t)=>XQ(e,t),"permanently delete a chart of accounts entry"),Qa("get_cash_transfer","Get full cash transfer details by resourceId.","cash_transfers",(e,t)=>rj(e,t),"get cash transfer details between accounts"),{name:"download_credit_note_pdf",description:"Download a customer credit note as PDF. Returns a file URL.",params:{resourceId:{type:"string",description:"Customer credit note resourceId"}},required:["resourceId"],group:"customer_credit_notes",readOnly:!0,searchHint:"download customer credit note as PDF file",isConcurrencySafe:!0,execute:async(e,t)=>aM(e.client,t.resourceId)},{name:"get_transaction_summary",description:`Get a complete summary of any transaction \u2014 fetches the transaction, its attachments, and payment history in one call.
833
833
  Works for invoices, bills, customer credit notes, supplier credit notes, and journals.`,params:{transactionType:{type:"string",enum:["invoice","bill","customer_credit_note","supplier_credit_note","journal"],description:"Transaction type"},resourceId:{type:"string",description:"Transaction resourceId"}},required:["transactionType","resourceId"],group:"search",readOnly:!0,searchHint:"get aggregated transaction counts totals by status",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(e,t)=>{let r=t.transactionType,n=t.resourceId,i=r==="invoice"?bo(e.client,n):r==="bill"?go(e.client,n):r==="customer_credit_note"?mu(e.client,n):r==="supplier_credit_note"?gu(e.client,n):Au(e.client,n),s=r==="invoice"?"invoices":r==="bill"?"bills":r==="customer_credit_note"?"customer-credit-notes":r==="supplier_credit_note"?"supplier-credit-notes":"journals",[o,a]=await Promise.all([i,ri(e.client,s,n)]),c;if(r==="invoice"||r==="bill")try{c=await ex(e.client,{filter:{businessTransactionResourceId:{eq:n}},limit:100})}catch{}let u=a.data??[];return{transaction:o.data,attachments:u,attachmentCount:u.length,...c?{payments:c.data,paymentCount:c.totalElements}:{}}}},{name:"bulk_finalize_drafts",description:"Finalize multiple draft transactions in one call. Attempts finalization for each item and returns per-item pass/fail results. Supports invoices, bills, and credit notes.",params:{items:{type:"array",items:{type:"object",properties:{type:{type:"string",enum:["invoice","bill","customer_credit_note","supplier_credit_note"],description:"Transaction type"},resourceId:{type:"string",description:"Transaction resourceId"}},required:["type","resourceId"]},description:"Array of {type, resourceId} to finalize"}},required:["items"],group:"drafts",readOnly:!1,searchHint:"bulk finalize approve multiple draft transactions",isDestructive:!0,execute:async(e,t)=>{let r=t.items,n=[];for(let i of r)try{let s=await dx(e.client,i.type,i.resourceId,{});i.type==="invoice"?await jD(e.client,i.resourceId,s):i.type==="bill"?await JI(e.client,i.resourceId,s):i.type==="customer_credit_note"?await KD(e.client,i.resourceId,s):i.type==="supplier_credit_note"&&await rS(e.client,i.resourceId,s),n.push({...i,success:!0})}catch(s){n.push({...i,success:!1,error:s instanceof Error?s.message:String(s)})}return{total:r.length,succeeded:n.filter(i=>i.success).length,failed:n.filter(i=>!i.success).length,results:n}}},{name:"bulk_invite_org_users",description:"Invite multiple users to the organization in one call. Accepts an array of user objects. Each user follows the same contract as invite_org_user. Returns per-user pass/fail results.",params:{users:{type:"array",items:{type:"object",properties:{email:{type:"string",description:"User email"},firstName:{type:"string",description:"First name"},lastName:{type:"string",description:"Last name"},userType:{type:"string",enum:[...wm],description:"ADMIN = full access (moduleRoles ignored). CUSTOM_USER = per-module access via moduleRoles."},moduleRoles:{type:"array",items:{type:"object",properties:{moduleName:{type:"string",enum:[...Lb]},roleCode:{type:"string",enum:[...vm]}},required:["moduleName","roleCode"]},description:"Use when userType is CUSTOM_USER; ignored for ADMIN."}},required:["email","firstName","lastName","userType"]},description:"Array of users to invite"}},required:["users"],group:"org_users",readOnly:!1,searchHint:"bulk invite multiple users to organization",execute:async(e,t)=>{let r=t.users,n=[];for(let i of r)try{let s=await nv(e.client,i);n.push({email:i.email,success:!0,resourceId:s.data?.resourceId})}catch(s){n.push({email:i.email,success:!1,error:s instanceof Error?s.message:String(s)})}return{total:r.length,succeeded:n.filter(i=>i.success).length,failed:n.filter(i=>!i.success).length,results:n}}},{name:"bulk_create_contacts",description:`Create multiple contacts in one call. Deduplicates against existing contacts (exact name match).
834
834
  Returns per-contact result: created, skipped (duplicate), or failed.`,params:{contacts:{type:"array",items:{type:"object",properties:{billingName:{type:"string",description:"Official billing name"},name:{type:"string",description:"Display name"},email:{type:"string",description:"Primary email"},customer:{type:"boolean",description:"Is a customer"},supplier:{type:"boolean",description:"Is a supplier"}},required:["billingName"]},description:"Array of contacts to create"},skipDuplicates:{type:"boolean",description:"Skip contacts that match existing names (default true)"}},required:["contacts"],group:"contacts",readOnly:!1,searchHint:"bulk create multiple customer supplier contacts",execute:async(e,t)=>{let r=t.contacts,n=t.skipDuplicates??!0,i=[];for(let s of r)try{if(n){let a=await Y_(e.client,s.name??s.billingName);if(a){i.push({billingName:s.billingName,status:"skipped",resourceId:a.resourceId});continue}}let o=await rb(e.client,{billingName:s.billingName,name:s.name??s.billingName,emails:s.email?[s.email]:void 0,customer:s.customer??!0,supplier:s.supplier??!1});i.push({billingName:s.billingName,status:"created",resourceId:o.data.resourceId})}catch(o){i.push({billingName:s.billingName,status:"failed",error:o instanceof Error?o.message:String(o)})}return{total:r.length,created:i.filter(s=>s.status==="created").length,skipped:i.filter(s=>s.status==="skipped").length,failed:i.filter(s=>s.status==="failed").length,results:i}}},{name:"quick_fix_transactions",description:`Bulk-update transactions of the same type. Only included fields change; omitted fields preserved.
835
835
 
@@ -848,7 +848,7 @@ Request patterns:
848
848
 
849
849
  Common line attrs: name, quantity, unit, unitPrice, discount, organizationAccountResourceId, taxProfileResourceId, classifierConfig. Purchase + withholdingTax. Journals/cash-entries use amount + description instead of unit/unitPrice. Full matrix in jaz-api Rule 107.
850
850
 
851
- Response: { updated, failed: [{resourceId, error, errorCode}] }. HTTP 207 = partial.`,params:{entity:{type:"string",enum:[...iv],description:"Transaction type"},lineItemResourceIds:{type:"array",items:{type:"string"},description:"Line item resourceIds to update (ARAP + accounting entities)"},attributes:{type:"object",description:"Fields to update on all specified line items"},schedulerUpdates:{type:"array",items:{type:"object"},description:"Per-scheduler updates: [{ schedulerResourceId, lineItemUpdates: [{ arrayIndex, ...fields }] }]. EXCEPTION: journal-schedules use lineItemResourceId (UUID) instead of arrayIndex."}},required:["entity"],group:"quick_fix",readOnly:!1,searchHint:"bulk update line item accounts tax profiles",execute:async(e,t)=>{let r=t.entity,n=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"].includes(r),i={};if(n){if(!t.schedulerUpdates)throw new Error("schedulerUpdates is required for scheduler entities (sale-schedules, purchase-schedules, subscription-schedules, journal-schedules)");i.schedulerUpdates=t.schedulerUpdates}else{if(!t.lineItemResourceIds)throw new Error("lineItemResourceIds is required for non-scheduler entities");i.lineItemResourceIds=t.lineItemResourceIds,i.attributes=t.attributes??{}}return sx(e.client,r,i)}},cn("list_nano_classifiers","List nano classifiers (tracking categories). Paginated. Nano classifiers tag line items with structured categories.","nano_classifiers",(e,t,r)=>wY(e,{limit:r,offset:t}),"list nano classifiers tracking categories types"),Qa("get_nano_classifier","Get a nano classifier by resourceId. Returns type and all classes.","nano_classifiers",(e,t)=>IY(e,t),"get nano classifier tracking category details"),tn({name:"search_nano_classifiers",description:"Search nano classifiers (tracking categories).",group:"nano_classifiers",fields:PD,defaults:$D,fetcher:_Y,searchHint:"find nano classifiers tracking categories cost centers departments by type name"}),{name:"create_nano_classifier",description:"Create a nano classifier (tracking category). Provide a type name and list of class names. printable defaults to true (NOTE: printable: false is currently rejected by a server bug \u2014 always use true).",params:{type:{type:"string",description:'Classifier type name (e.g., "Department", "Project")'},classes:{type:"array",items:{type:"string"},description:'Class names: ["Sales", "Marketing", "Engineering"]'},printable:{type:"boolean",description:"Show on printed documents (default: true). NOTE: false is rejected by a server bug."}},required:["type","classes"],group:"nano_classifiers",readOnly:!1,searchHint:"create new nano classifier tracking category",execute:async(e,t)=>ox(e.client,{type:t.type,classes:t.classes,printable:t.printable??!0})},{name:"update_nano_classifier",description:"Update a nano classifier \u2014 change type name, modify classes, or toggle printable.",params:{resourceId:{type:"string",description:"Nano classifier resourceId"},type:{type:"string",description:"New type name"},classes:{type:"array",items:{type:"string"},description:'Updated class names: ["Sales", "Marketing"]'},printable:{type:"boolean",description:"Show on printed documents"}},required:["resourceId"],group:"nano_classifiers",readOnly:!1,searchHint:"update nano classifier classes and settings",execute:async(e,t)=>{let r={};return t.type&&(r.type=t.type),t.classes&&(r.classes=t.classes),t.printable!==void 0&&(r.printable=t.printable),ax(e.client,t.resourceId,r)}},Ro("delete_nano_classifier","Delete a nano classifier.","nano_classifiers",(e,t)=>DY(e,t),"permanently delete a nano classifier type"),{name:"list_invoice_payments",description:"List all payments recorded against an invoice. Returns payment records with amounts, dates, and methods.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"payments",readOnly:!0,searchHint:"list payment records on an invoice",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>mL(e.client,t.resourceId)},{name:"list_invoice_credits",description:"List all credit notes applied to an invoice.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"payments",readOnly:!0,searchHint:"list credit applications on an invoice",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>gL(e.client,t.resourceId)},{name:"reverse_invoice_credit",description:"Reverse (unapply) a credit note from an invoice. The credit note becomes UNAPPLIED again.",params:{resourceId:{type:"string",description:"Invoice resourceId"},creditResourceId:{type:"string",description:"Credit application resourceId to reverse"}},required:["resourceId","creditResourceId"],group:"payments",readOnly:!1,searchHint:"reverse a credit note application on invoice",isDestructive:!0,execute:async(e,t)=>(await yL(e.client,t.resourceId,t.creditResourceId),{reversed:!0,invoiceId:t.resourceId,creditId:t.creditResourceId})},{name:"list_bill_payments",description:"List all payments recorded against a bill. Returns payment records with amounts, dates, and methods.",params:{resourceId:{type:"string",description:"Bill resourceId"}},required:["resourceId"],group:"payments",readOnly:!0,searchHint:"list payment records on a bill",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>fO(e.client,t.resourceId)},{name:"list_bill_credits",description:"List all credit notes applied to a bill.",params:{resourceId:{type:"string",description:"Bill resourceId"}},required:["resourceId"],group:"payments",readOnly:!0,searchHint:"list credit applications on a bill",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>dO(e.client,t.resourceId)},{name:"reverse_bill_credit",description:"Reverse (unapply) a supplier credit note from a bill. The credit note becomes UNAPPLIED again.",params:{resourceId:{type:"string",description:"Bill resourceId"},creditResourceId:{type:"string",description:"Credit application resourceId to reverse"}},required:["resourceId","creditResourceId"],group:"payments",readOnly:!1,searchHint:"reverse a credit note application on bill",isDestructive:!0,execute:async(e,t)=>(await pO(e.client,t.resourceId,t.creditResourceId),{reversed:!0,billId:t.resourceId,creditId:t.creditResourceId})},Qa("get_scheduled_invoice","Get a scheduled (recurring) invoice by resourceId.","schedulers",(e,t)=>oj(e,t),"get scheduled recurring invoice details"),{name:"update_scheduled_invoice",description:"Update a scheduled invoice \u2014 change schedule settings and/or the invoice template.",params:{resourceId:{type:"string",description:"Scheduled invoice resourceId"},repeat:{type:"string",description:"Recurrence: WEEKLY, MONTHLY, QUARTERLY, YEARLY"},startDate:{type:"string",description:"First occurrence date (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence date (YYYY-MM-DD)"},status:{type:"string",description:"Status: ACTIVE or PAUSED"},invoice:{type:"object",description:"Invoice template: { reference, valueDate, dueDate, contactResourceId, lineItems, currency, tag, saveAsDraft }"}},required:["resourceId"],group:"schedulers",readOnly:!1,searchHint:"update recurring scheduled invoice settings",execute:async(e,t)=>{let r={};return t.repeat&&(r.repeat=t.repeat),t.startDate&&(r.startDate=t.startDate),t.endDate&&(r.endDate=t.endDate),t.status&&(r.status=t.status),t.invoice&&(r.invoice=t.invoice),aj(e.client,t.resourceId,r)}},Ro("delete_scheduled_invoice","Delete a scheduled (recurring) invoice.","schedulers",(e,t)=>cj(e,t),"delete a recurring scheduled invoice"),Qa("get_scheduled_bill","Get a scheduled (recurring) bill by resourceId.","schedulers",(e,t)=>uj(e,t),"get scheduled recurring bill details"),{name:"update_scheduled_bill",description:"Update a scheduled bill \u2014 change schedule settings and/or the bill template.",params:{resourceId:{type:"string",description:"Scheduled bill resourceId"},repeat:{type:"string",description:"Recurrence: WEEKLY, MONTHLY, QUARTERLY, YEARLY"},startDate:{type:"string",description:"First occurrence date (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence date (YYYY-MM-DD)"},status:{type:"string",description:"Status: ACTIVE or PAUSED"},bill:{type:"object",description:"Bill template: { reference, valueDate, dueDate, contactResourceId, lineItems, currency, tag, saveAsDraft }"}},required:["resourceId"],group:"schedulers",readOnly:!1,searchHint:"update recurring scheduled bill settings",execute:async(e,t)=>{let r={};return t.repeat&&(r.repeat=t.repeat),t.startDate&&(r.startDate=t.startDate),t.endDate&&(r.endDate=t.endDate),t.status&&(r.status=t.status),t.bill&&(r.bill=t.bill),lj(e.client,t.resourceId,r)}},Ro("delete_scheduled_bill","Delete a scheduled (recurring) bill.","schedulers",(e,t)=>fj(e,t),"delete a recurring scheduled bill"),Qa("get_scheduled_journal","Get a scheduled (recurring) journal by resourceId.","schedulers",(e,t)=>dj(e,t),"get scheduled recurring journal details"),{name:"update_scheduled_journal",description:"Update a scheduled journal \u2014 change schedule settings and/or the journal template.",params:{resourceId:{type:"string",description:"Scheduled journal resourceId"},repeat:{type:"string",description:"Recurrence: WEEKLY, MONTHLY, QUARTERLY, YEARLY"},startDate:{type:"string",description:"First occurrence date (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence date (YYYY-MM-DD)"},status:{type:"string",description:"Status: ACTIVE or PAUSED"},valueDate:{type:"string",description:"Journal date (YYYY-MM-DD)"},schedulerEntries:{type:"array",items:{type:"object"},description:"Journal entries: [{ accountResourceId, type: CREDIT|DEBIT, amount, ... }]"},reference:{type:"string",description:"Journal reference"},notes:{type:"string",description:"Journal notes"}},required:["resourceId"],group:"schedulers",readOnly:!1,searchHint:"update recurring scheduled journal settings",execute:async(e,t)=>{let r={};return t.repeat&&(r.repeat=t.repeat),t.startDate&&(r.startDate=t.startDate),t.endDate&&(r.endDate=t.endDate),t.status&&(r.status=t.status),t.valueDate&&(r.valueDate=t.valueDate),t.schedulerEntries&&(r.schedulerEntries=t.schedulerEntries),t.reference&&(r.reference=t.reference),t.notes&&(r.notes=t.notes),pj(e.client,t.resourceId,r)}},Ro("delete_scheduled_journal","Delete a scheduled (recurring) journal.","schedulers",(e,t)=>hj(e,t),"delete a recurring scheduled journal"),Qa("get_payment","Get a specific payment record by resourceId. Returns payment amount, method, date, and reference.","payments",(e,t)=>Bj(e,t),"get payment record details by id"),{name:"update_payment",description:"Update a payment record \u2014 correct amount, reference, date, method, or account.",params:{resourceId:{type:"string",description:"Payment resourceId (from invoice/bill paymentRecords)"},paymentAmount:{type:"number",description:"Corrected payment amount (bank currency)"},reference:{type:"string",description:"Payment reference"},valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},paymentMethod:fx,accountResourceId:{type:"string",description:"Bank/cash account resourceId"},transactionFee:{type:"number",description:"Transaction fee amount"}},required:["resourceId"],group:"payments",readOnly:!1,searchHint:"update payment amount reference date method",execute:async(e,t)=>{let r={};return t.paymentAmount!==void 0&&(r.paymentAmount=t.paymentAmount),t.reference&&(r.reference=t.reference),t.valueDate&&(r.valueDate=t.valueDate),t.paymentMethod&&(r.paymentMethod=t.paymentMethod),t.accountResourceId&&(r.accountResourceId=t.accountResourceId),t.transactionFee!==void 0&&(r.transactionFee=t.transactionFee),Rj(e.client,t.resourceId,r)}},Ro("delete_payment","Delete (void) a payment record. The associated invoice/bill balance is restored.","payments",(e,t)=>xj(e,t),"delete void a payment record restore balance"),{name:"get_export_columns",description:"List all exportable columns for an entity type, including their paths and data types. Use paths from this response to build custom column sets for export_records or preview_export_records.",params:{entityType:kce},required:["entityType"],group:"export_records",readOnly:!0,isConcurrencySafe:!0,searchHint:"list export columns fields for entity type",execute:async(e,t)=>RY(e.client,t.entityType)},{name:"preview_export_records",description:"Preview an export before generating the file. Returns totalRecords, up to 10 sample rows, resolved column definitions, and a human-readable filterDescription. Use this to confirm scope before calling export_records. Pass either query OR filter, never both.",params:{entityType:kce,query:det,filter:pet,columns:het,sort:Aet},required:["entityType"],group:"export_records",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview export records count sample rows filter",execute:async(e,t)=>BY(e.client,{entityType:t.entityType,outputFormat:"XLSX",query:t.query,filter:t.filter,columns:t.columns,sort:t.sort})},{name:"export_records",description:`Raw entity-row XLSX export for one entity type (invoices/bills/contacts/items/journals/bank records/cashflow/fixed assets \u2014 one row per record, with column selection). Returns pre-signed download URL (~5 min), fileName, totalCount. Pass query OR filter, never both. Use preview_export_records first to confirm scope.
851
+ Response: { updated, failed: [{resourceId, error, errorCode}] }. HTTP 207 = partial.`,params:{entity:{type:"string",enum:[...iv],description:"Transaction type"},lineItemResourceIds:{type:"array",items:{type:"string"},description:"Line item resourceIds to update (ARAP + accounting entities)"},attributes:{type:"object",description:"Fields to update on all specified line items"},schedulerUpdates:{type:"array",items:{type:"object"},description:"Per-scheduler updates: [{ schedulerResourceId, lineItemUpdates: [{ arrayIndex, ...fields }] }]. EXCEPTION: journal-schedules use lineItemResourceId (UUID) instead of arrayIndex."}},required:["entity"],group:"quick_fix",readOnly:!1,searchHint:"bulk update line item accounts tax profiles",execute:async(e,t)=>{let r=t.entity,n=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"].includes(r),i={};if(n){if(!t.schedulerUpdates)throw new Error("schedulerUpdates is required for scheduler entities (sale-schedules, purchase-schedules, subscription-schedules, journal-schedules)");i.schedulerUpdates=t.schedulerUpdates}else{if(!t.lineItemResourceIds)throw new Error("lineItemResourceIds is required for non-scheduler entities");i.lineItemResourceIds=t.lineItemResourceIds,i.attributes=t.attributes??{}}return sx(e.client,r,i)}},cn("list_nano_classifiers","List nano classifiers (tracking categories). Paginated. Nano classifiers tag line items with structured categories.","nano_classifiers",(e,t,r)=>wY(e,{limit:r,offset:t}),"list nano classifiers tracking categories types"),Qa("get_nano_classifier","Get a nano classifier by resourceId. Returns type and all classes.","nano_classifiers",(e,t)=>IY(e,t),"get nano classifier tracking category details"),tn({name:"search_nano_classifiers",description:"Search nano classifiers (tracking categories).",group:"nano_classifiers",fields:PD,defaults:$D,fetcher:_Y,searchHint:"find nano classifiers tracking categories cost centers departments by type name"}),{name:"create_nano_classifier",description:"Create a nano classifier (tracking category). Provide a type name and list of class names. printable defaults to true.",params:{type:{type:"string",description:'Classifier type name (e.g., "Department", "Project")'},classes:{type:"array",items:{type:"string"},description:'Class names: ["Sales", "Marketing", "Engineering"]'},printable:{type:"boolean",description:"Show on printed documents (default: true)."}},required:["type","classes"],group:"nano_classifiers",readOnly:!1,searchHint:"create new nano classifier tracking category",execute:async(e,t)=>ox(e.client,{type:t.type,classes:t.classes,printable:t.printable??!0})},{name:"update_nano_classifier",description:"Update a nano classifier \u2014 change type name, modify classes, or toggle printable.",params:{resourceId:{type:"string",description:"Nano classifier resourceId"},type:{type:"string",description:"New type name"},classes:{type:"array",items:{type:"object",properties:{className:{type:"string",description:"Class name"},resourceId:{type:"string",description:"Existing class resourceId (omit to add a new class)"},deleted:{type:"boolean",description:"true removes the class"}},required:["className"]},description:"Diff-style class updates: [{className, resourceId?, deleted?}]. Rename by passing resourceId + new className; add by omitting resourceId; remove with deleted: true. Plain strings are rejected by the API."},printable:{type:"boolean",description:"Show on printed documents"}},required:["resourceId"],group:"nano_classifiers",readOnly:!1,searchHint:"update nano classifier classes and settings",execute:async(e,t)=>{let r={};return t.type&&(r.type=t.type),t.classes&&(r.classes=t.classes),t.printable!==void 0&&(r.printable=t.printable),ax(e.client,t.resourceId,r)}},Ro("delete_nano_classifier","Delete a nano classifier.","nano_classifiers",(e,t)=>DY(e,t),"permanently delete a nano classifier type"),{name:"list_invoice_payments",description:"List all payments recorded against an invoice. Returns payment records with amounts, dates, and methods.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"payments",readOnly:!0,searchHint:"list payment records on an invoice",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>mL(e.client,t.resourceId)},{name:"list_invoice_credits",description:"List all credit notes applied to an invoice.",params:{resourceId:{type:"string",description:"Invoice resourceId"}},required:["resourceId"],group:"payments",readOnly:!0,searchHint:"list credit applications on an invoice",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>gL(e.client,t.resourceId)},{name:"reverse_invoice_credit",description:"Reverse (unapply) a credit note from an invoice. The credit note becomes UNAPPLIED again.",params:{resourceId:{type:"string",description:"Invoice resourceId"},creditResourceId:{type:"string",description:"Credit application resourceId to reverse"}},required:["resourceId","creditResourceId"],group:"payments",readOnly:!1,searchHint:"reverse a credit note application on invoice",isDestructive:!0,execute:async(e,t)=>(await yL(e.client,t.resourceId,t.creditResourceId),{reversed:!0,invoiceId:t.resourceId,creditId:t.creditResourceId})},{name:"list_bill_payments",description:"List all payments recorded against a bill. Returns payment records with amounts, dates, and methods.",params:{resourceId:{type:"string",description:"Bill resourceId"}},required:["resourceId"],group:"payments",readOnly:!0,searchHint:"list payment records on a bill",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>fO(e.client,t.resourceId)},{name:"list_bill_credits",description:"List all credit notes applied to a bill.",params:{resourceId:{type:"string",description:"Bill resourceId"}},required:["resourceId"],group:"payments",readOnly:!0,searchHint:"list credit applications on a bill",isConcurrencySafe:!0,maxResultSizeChars:5e4,execute:async(e,t)=>dO(e.client,t.resourceId)},{name:"reverse_bill_credit",description:"Reverse (unapply) a supplier credit note from a bill. The credit note becomes UNAPPLIED again.",params:{resourceId:{type:"string",description:"Bill resourceId"},creditResourceId:{type:"string",description:"Credit application resourceId to reverse"}},required:["resourceId","creditResourceId"],group:"payments",readOnly:!1,searchHint:"reverse a credit note application on bill",isDestructive:!0,execute:async(e,t)=>(await pO(e.client,t.resourceId,t.creditResourceId),{reversed:!0,billId:t.resourceId,creditId:t.creditResourceId})},Qa("get_scheduled_invoice","Get a scheduled (recurring) invoice by resourceId.","schedulers",(e,t)=>oj(e,t),"get scheduled recurring invoice details"),{name:"update_scheduled_invoice",description:"Update a scheduled invoice \u2014 change schedule settings and/or the invoice template.",params:{resourceId:{type:"string",description:"Scheduled invoice resourceId"},repeat:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Recurrence interval (QUARTERLY is rejected with 422)"},startDate:{type:"string",description:"First occurrence date (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence date (YYYY-MM-DD)"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Status: ACTIVE or INACTIVE (PAUSED is rejected with 422)"},invoice:{type:"object",description:"Invoice template: { reference, valueDate, dueDate, contactResourceId, lineItems, currency, tag, saveAsDraft }"}},required:["resourceId"],group:"schedulers",readOnly:!1,searchHint:"update recurring scheduled invoice settings",execute:async(e,t)=>{let r={};return t.repeat&&(r.repeat=t.repeat),t.startDate&&(r.startDate=t.startDate),t.endDate&&(r.endDate=t.endDate),t.status&&(r.status=t.status),t.invoice&&(r.invoice=t.invoice),aj(e.client,t.resourceId,r)}},Ro("delete_scheduled_invoice","Delete a scheduled (recurring) invoice.","schedulers",(e,t)=>cj(e,t),"delete a recurring scheduled invoice"),Qa("get_scheduled_bill","Get a scheduled (recurring) bill by resourceId.","schedulers",(e,t)=>uj(e,t),"get scheduled recurring bill details"),{name:"update_scheduled_bill",description:"Update a scheduled bill \u2014 change schedule settings and/or the bill template.",params:{resourceId:{type:"string",description:"Scheduled bill resourceId"},repeat:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Recurrence interval (QUARTERLY is rejected with 422)"},startDate:{type:"string",description:"First occurrence date (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence date (YYYY-MM-DD)"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Status: ACTIVE or INACTIVE (PAUSED is rejected with 422)"},bill:{type:"object",description:"Bill template: { reference, valueDate, dueDate, contactResourceId, lineItems, currency, tag, saveAsDraft }"}},required:["resourceId"],group:"schedulers",readOnly:!1,searchHint:"update recurring scheduled bill settings",execute:async(e,t)=>{let r={};return t.repeat&&(r.repeat=t.repeat),t.startDate&&(r.startDate=t.startDate),t.endDate&&(r.endDate=t.endDate),t.status&&(r.status=t.status),t.bill&&(r.bill=t.bill),lj(e.client,t.resourceId,r)}},Ro("delete_scheduled_bill","Delete a scheduled (recurring) bill.","schedulers",(e,t)=>fj(e,t),"delete a recurring scheduled bill"),Qa("get_scheduled_journal","Get a scheduled (recurring) journal by resourceId.","schedulers",(e,t)=>dj(e,t),"get scheduled recurring journal details"),{name:"update_scheduled_journal",description:"Update a scheduled journal \u2014 change schedule settings and/or the journal template.",params:{resourceId:{type:"string",description:"Scheduled journal resourceId"},repeat:{type:"string",enum:["ONE_TIME","DAILY","WEEKLY","MONTHLY","YEARLY"],description:"Recurrence interval (QUARTERLY is rejected with 422)"},startDate:{type:"string",description:"First occurrence date (YYYY-MM-DD)"},endDate:{type:"string",description:"Last occurrence date (YYYY-MM-DD)"},status:{type:"string",enum:["ACTIVE","INACTIVE"],description:"Status: ACTIVE or INACTIVE (PAUSED is rejected with 422)"},valueDate:{type:"string",description:"Journal date (YYYY-MM-DD)"},schedulerEntries:{type:"array",items:{type:"object"},description:"Journal entries: [{ accountResourceId, type: CREDIT|DEBIT, amount, ... }]"},reference:{type:"string",description:"Journal reference"},notes:{type:"string",description:"Journal notes"}},required:["resourceId"],group:"schedulers",readOnly:!1,searchHint:"update recurring scheduled journal settings",execute:async(e,t)=>{let r={};return t.repeat&&(r.repeat=t.repeat),t.startDate&&(r.startDate=t.startDate),t.endDate&&(r.endDate=t.endDate),t.status&&(r.status=t.status),t.valueDate&&(r.valueDate=t.valueDate),t.schedulerEntries&&(r.schedulerEntries=t.schedulerEntries),t.reference&&(r.reference=t.reference),t.notes&&(r.notes=t.notes),pj(e.client,t.resourceId,r)}},Ro("delete_scheduled_journal","Delete a scheduled (recurring) journal.","schedulers",(e,t)=>hj(e,t),"delete a recurring scheduled journal"),Qa("get_payment","Get a specific payment record by resourceId. Returns payment amount, method, date, and reference.","payments",(e,t)=>Bj(e,t),"get payment record details by id"),{name:"update_payment",description:"Update a payment record \u2014 correct amount, reference, date, method, or account.",params:{resourceId:{type:"string",description:"Payment resourceId (from invoice/bill paymentRecords)"},paymentAmount:{type:"number",description:"Corrected payment amount (bank currency)"},reference:{type:"string",description:"Payment reference"},valueDate:{type:"string",description:"Payment date (YYYY-MM-DD)"},paymentMethod:fx,accountResourceId:{type:"string",description:"Bank/cash account resourceId"},transactionFee:{type:"object",description:"Transaction fee. The API requires the full fee object \u2014 a bare number is rejected.",properties:{feeAccountResourceId:{type:"string",description:"Fee expense account resourceId"},feeType:{type:"string",enum:["FLAT","PERCENTAGE"],description:"How feeValue is interpreted"},feeValue:{type:"number",description:"Fee amount (FLAT) or percentage (PERCENTAGE)"},feeTaxVatApplicable:{type:"boolean",description:"Whether VAT applies to the fee"},feeDescription:{type:"string",description:"Optional fee description"},taxVatProfileResourceId:{type:"string",description:"Optional tax profile for the fee"}},required:["feeAccountResourceId","feeType","feeValue","feeTaxVatApplicable"]}},required:["resourceId"],group:"payments",readOnly:!1,searchHint:"update payment amount reference date method",execute:async(e,t)=>{let r={};return t.paymentAmount!==void 0&&(r.paymentAmount=t.paymentAmount),t.reference&&(r.reference=t.reference),t.valueDate&&(r.valueDate=t.valueDate),t.paymentMethod&&(r.paymentMethod=t.paymentMethod),t.accountResourceId&&(r.accountResourceId=t.accountResourceId),t.transactionFee!==void 0&&(r.transactionFee=t.transactionFee),Rj(e.client,t.resourceId,r)}},Ro("delete_payment","Delete (void) a payment record. The associated invoice/bill balance is restored.","payments",(e,t)=>xj(e,t),"delete void a payment record restore balance"),{name:"get_export_columns",description:"List all exportable columns for an entity type, including their paths and data types. Use paths from this response to build custom column sets for export_records or preview_export_records.",params:{entityType:kce},required:["entityType"],group:"export_records",readOnly:!0,isConcurrencySafe:!0,searchHint:"list export columns fields for entity type",execute:async(e,t)=>RY(e.client,t.entityType)},{name:"preview_export_records",description:"Preview an export before generating the file. Returns totalRecords, up to 10 sample rows, resolved column definitions, and a human-readable filterDescription. Use this to confirm scope before calling export_records. Pass either query OR filter, never both.",params:{entityType:kce,query:det,filter:pet,columns:het,sort:Aet},required:["entityType"],group:"export_records",readOnly:!0,isConcurrencySafe:!0,searchHint:"preview export records count sample rows filter",execute:async(e,t)=>BY(e.client,{entityType:t.entityType,outputFormat:"XLSX",query:t.query,filter:t.filter,columns:t.columns,sort:t.sort})},{name:"export_records",description:`Raw entity-row XLSX export for one entity type (invoices/bills/contacts/items/journals/bank records/cashflow/fixed assets \u2014 one row per record, with column selection). Returns pre-signed download URL (~5 min), fileName, totalCount. Pass query OR filter, never both. Use preview_export_records first to confirm scope.
852
852
 
853
853
  DO NOT use this for analytical / audit reports, financial statements, aging, summary reports, or statement-of-account \u2014 those go through download_export.`,params:{entityType:kce,query:det,filter:pet,columns:het,sort:Aet},required:["entityType"],group:"export_records",readOnly:!0,isConcurrencySafe:!0,searchHint:"export records download xlsx file url",execute:async(e,t)=>SY(e.client,{entityType:t.entityType,outputFormat:"XLSX",query:t.query,filter:t.filter,columns:t.columns,sort:t.sort})},tn({name:"search_background_jobs",description:"Search and poll background jobs. ANY operation that returns a jobId (bulk_upsert_contacts, bulk_upsert_items, bank statement import, magic file processing, etc.) can be tracked here. Filter by resourceId (the jobId value) to poll a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS. Use processedCount/failedCount/totalRecords for progress. IMPORTANT: filter by resourceId field, NOT jobId \u2014 they differ.",group:"background_jobs",fields:CD,defaults:vD,fetcher:cx,searchHint:"poll background job status by jobId type status"}),{name:"bulk_upsert_contacts",description:`Bulk create/update contacts (max 500). resourceId per row \u2192 update (partial; omitted fields preserve existing). Omit resourceId \u2192 create. ${Tu} Per-row failures in errorDetails (NOT failedRows \u2014 that's the sync pattern). On PARTIAL_SUCCESS: succeeded rows are committed; re-submit only failed rowIndex entries.
854
854
 
@@ -862,7 +862,7 @@ ASYNC: returns jobId \u2192 poll search_background_jobs(filter:{resourceId:{eq:j
862
862
 
863
863
  Required per row: reference, registrationType (NEW | TRANSFER). Recommended: typeCode, typeName, category (TANGIBLE | INTANGIBLE), cost (synonym: purchaseAmount), valueDate, depreciationStartDate, effectiveLife (synonym: usefulLifeMonths), depreciationMethod, purchaseAssetAccountResourceId, depreciationExpenseAccountResourceId, accumulatedDepreciationAccountResourceId. Account fields = UUIDv4.
864
864
 
865
- ASYNC: returns jobId \u2192 poll search_background_jobs(filter:{resourceId:{eq:jobId}}); on PARTIAL_SUCCESS read data[0].errorDetails. Dates ISO 8601 (YYYY-MM-DD).`,params:{fixedAssets:{type:"array",description:"Fixed assets to create/update (max 500).",items:{type:"object",properties:{rowIndex:{type:"string"},resourceId:{type:"string"},reference:{type:"string",description:"Natural key \u2014 required"},registrationType:{type:"string",enum:["NEW","TRANSFER"],description:"NEW = newly acquired, TRANSFER = inherited \u2014 required"},typeCode:{type:"string",description:"Asset class code (e.g. FURNITURE_AND_FIXTURE)"},typeName:{type:"string",description:"Human label for typeCode"},category:{type:"string",description:"TANGIBLE | INTANGIBLE"},name:{type:"string",description:"Asset name"},valueDate:{type:"string",description:"Acquisition date YYYY-MM-DD (request only; GET response uses purchaseDate)."},cost:{type:"number",description:"Cost basis (alias purchaseAmount)."},purchaseAmount:{type:"number",description:"Synonym of cost."},currencyCode:{type:"string"},depreciationStartDate:{type:"number",description:"Epoch ms (NOT YYYY-MM-DD on this endpoint \u2014 sending YYYY-MM-DD \u2192 400). Omit to default to valueDate."},effectiveLife:{type:"number",description:"Useful life months (alias usefulLifeMonths)."},usefulLifeMonths:{type:"number",description:"Synonym of effectiveLife."},depreciationMethod:{type:"string",description:"STRAIGHT_LINE | DOUBLE_DECLINING_BALANCE | \u2026"},purchaseAssetAccountResourceId:{type:"string",description:"Asset (PPE) account UUIDv4."},depreciationExpenseAccountResourceId:{type:"string",description:"Depreciation expense account UUIDv4."},accumulatedDepreciationAccountResourceId:{type:"string",description:"Accumulated depreciation account UUIDv4."},internalNotes:{type:"string"},tags:{type:"array",items:{type:"string"}}}}}},required:["fixedAssets"],group:"fixed_assets",readOnly:!1,searchHint:"bulk fixed assets ppe register upsert import migrate",execute:async(e,t)=>{Ii(t.fixedAssets,"fixedAssets",500,"fixed assets");let r=t.fixedAssets;return ic(r,["valueDate"]),eY(e.client,r)}},{name:"quick_reconcile",description:`Bulk-reconcile bank statement entries against a list of journals (max 500). Reconciliation mode is hardcoded to QUICK_RECON. ${Tu} Caller provides bankAccountResourceId + journalsForReconciliation[] (each row: bankStatementEntryResourceId, journalReference, journalAccountResourceId).`,params:{bankAccountResourceId:{type:"string",description:"Bank account UUID (the entries belong to this account)"},journalsForReconciliation:{type:"array",description:"Per-row reconciliation instructions (max 500).",items:{type:"object",properties:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},journalReference:{type:"string",description:"Journal reference text \u2014 required"},journalAccountResourceId:{type:"string",description:"Offsetting account UUID (revenue for cash-in, expense for cash-out) \u2014 required"},contactResourceId:{type:"string",description:"Contact UUID"},capsuleResourceId:{type:"string",description:"Capsule UUID"},taxProfileResourceId:{type:"string",description:"Tax profile UUID"},internalNotes:{type:"string"},journalEntryDescription:{type:"string"},tags:{type:"array",items:{type:"string"}},rowIndex:{type:"string",description:"Optional caller-supplied index for error correlation"}}}}},required:["bankAccountResourceId","journalsForReconciliation"],group:"reconciliations",readOnly:!1,searchHint:"bulk reconcile bank statement journals match",execute:async(e,t)=>(Ii(t.journalsForReconciliation,"journalsForReconciliation",500,"journals"),NY(e.client,t))},{name:"apply_bank_rule",description:"Apply a pre-configured bank rule (action shortcut) to a batch of bank statement entries (max 500). Async \u2014 returns a jobId. Poll search_background_jobs filtered by resourceId. The rule executes its configured action (e.g. RECONCILE_WITH_DIRECT_CASH_ENTRY) on each entry.",params:{actionShortcutResourceId:{type:"string",description:"Bank rule UUID \u2014 required"},businessTransactionResourceIds:{type:"array",description:"Bank statement entry UUIDs to apply the rule to (max 500). Note: the field is named businessTransactionResourceIds for legacy reasons but accepts bank entry IDs.",items:{type:"string"}}},required:["actionShortcutResourceId","businessTransactionResourceIds"],group:"reconciliations",readOnly:!1,searchHint:"bank rule apply action shortcut bulk reconcile",execute:async(e,t)=>(Ii(t.businessTransactionResourceIds,"businessTransactionResourceIds",500,"entries"),FY(e.client,t))},{name:"reconcile_direct_cash_entry",description:"Reconcile a bank statement entry with a single cash-in / cash-out line. Direction (cash-in vs cash-out) is INFERRED from the bank entry sign. Sync \u2014 returns the reconciled entry status. NOT idempotent: calling twice on the same bankStatementEntryResourceId creates duplicate journals. Confirm reconciled-state via view_auto_reconciliation before retrying.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID (used to look up the entry) \u2014 required"},reference:{type:"string",description:"Reference for the cash entry \u2014 required"},accountResourceId:{type:"string",description:"Offsetting account UUID (revenue for cash-in, expense for cash-out) \u2014 required"},amount:{type:"number",description:"Amount in source currency. Defaults to bank entry amount if omitted."},description:{type:"string"},contactResourceId:{type:"string"},taxProfileResourceId:{type:"string"},internalNotes:{type:"string"},bankAccountJournalEntryDescription:{type:"string",description:"Description for the bank-side journal entry"},tags:{type:"array",items:{type:"string"}},taxVatApplicable:{type:"boolean"},taxInclusion:{type:"boolean"},capsuleResourceId:{type:"string"}},required:["bankStatementEntryResourceId","bankAccountResourceId","reference","accountResourceId"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry direct cash in out single line",execute:async(e,t)=>OY(e.client,t)},{name:"reconcile_cash_journal",description:"Reconcile a bank statement entry with a multi-line cashflow journal (multiple cash splits, max 200 lines). Sync \u2014 returns the reconciled entry status. NOT idempotent \u2014 confirm reconciled-state before retrying.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID \u2014 required"},reference:{type:"string",description:"Journal reference \u2014 required"},journalEntries:{type:"array",description:"Cash journal lines (max 200). Each row is one debit OR credit against an account.",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account UUID \u2014 required"},amount:{type:"number",description:"Amount in source currency \u2014 required (>0)"},description:{type:"string"},taxProfileResourceId:{type:"string"}}}},contactResourceId:{type:"string"},bankAccountJournalEntryDescription:{type:"string"},internalNotes:{type:"string"},tags:{type:"array",items:{type:"string"}},taxVatApplicable:{type:"boolean"},taxInclusion:{type:"boolean"},capsuleResourceId:{type:"string"}},required:["bankStatementEntryResourceId","bankAccountResourceId","reference","journalEntries"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry multi line cash journal splits",execute:async(e,t)=>(Ii(t.journalEntries,"journalEntries",200,"entries"),QY(e.client,t))},{name:"reconcile_manual_journal",description:'\u26A0\uFE0F CALLER PROVIDES ONLY THE OFFSET LEG(S) \u2014 backend AUTO-ADDS the bank-side leg from the statement entry. Sending both debit AND credit legs \u2192 422 "sum of debit and credit amounts are not equal" (your sides duplicate after the auto-add). Reconcile a bank statement entry with a double-entry manual journal. Sync \u2014 returns the reconciled entry status. valueDate prefills from bank entry if omitted. NOT idempotent.',params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID \u2014 required"},status:{type:"string",enum:["DRAFT","ACTIVE"],description:"Journal status \u2014 required"},journalEntries:{type:"array",description:"Offset-side journal entries only (max 200). The bank-side leg is auto-added by the API.",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account UUID \u2014 required"},type:{type:"string",enum:["DEBIT","CREDIT"]},amount:{type:"number",description:"Amount \u2014 required"},description:{type:"string"},contactResourceId:{type:"string"},taxProfileResourceId:{type:"string"}}}},reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},contactResourceId:{type:"string"},internalNotes:{type:"string"},bankAccountJournalEntryDescription:{type:"string"},taxVatApplicable:{type:"boolean"},taxInclusion:{type:"boolean"},tags:{type:"array",items:{type:"string"}},capsuleResourceId:{type:"string"}},required:["bankStatementEntryResourceId","bankAccountResourceId","status","journalEntries"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry manual journal double entry",execute:async(e,t)=>(Ii(t.journalEntries,"journalEntries",200,"entries"),LY(e.client,t))},{name:"reconcile_cash_transfer",description:"Reconcile a bank statement entry with an inter-account transfer. Sync \u2014 returns the reconciled entry status. amount is required only when the counterparty account is in a non-functional currency. NOT idempotent.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID \u2014 required"},accountResourceId:{type:"string",description:"Counterparty cash account UUID \u2014 required"},reference:{type:"string",description:"Transfer reference \u2014 required"},amount:{type:"number",description:"Amount in source currency. Required only for cross-currency transfers."},contactResourceId:{type:"string"},internalNotes:{type:"string"},tags:{type:"array",items:{type:"string"}},capsuleResourceId:{type:"string"}},required:["bankStatementEntryResourceId","bankAccountResourceId","accountResourceId","reference"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry transfer between accounts",execute:async(e,t)=>MY(e.client,t)},{name:"reconcile_invoice_receipt",description:'CREATES A NEW invoice and auto-reconciles it to a bank statement entry (AR). To match an EXISTING open invoice instead, use reconcile_with_payments (do not create a duplicate). \u26A0\uFE0F BSE must have `paymentDirection: PAYIN` (money in \u2014 AR). Produce via `bank add-records` with a POSITIVE amount (creates `credit_amount > 0` \u2192 PAYIN). Statement-imported BSEs from `bank import` also work. The error code "Invalid business transaction type" (422) is misleadingly named \u2014 the actual gate is direction, not entry type. Sync \u2014 returns the reconciled entry status. valueDate / dueDate / payment amount prefill from the bank entry if omitted. NOT idempotent.',params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID \u2014 required"},invoiceDetails:{type:"object",description:"The invoice to create. Required.",properties:{reference:{type:"string",description:"Invoice reference \u2014 required"},contactResourceId:{type:"string",description:"Customer UUID"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},dueDate:{type:"string",description:"YYYY-MM-DD. Defaults to value date."},taxInclusion:{type:"boolean"},isTaxVATApplicable:{type:"boolean"},lineItems:{type:"array",description:"Invoice line items (max 500) \u2014 required",items:{type:"object",properties:{name:{type:"string",description:"Line description \u2014 required"},quantity:{type:"number"},unit:{type:"string"},unitPrice:{type:"number"},organizationAccountResourceId:{type:"string",description:"Revenue account UUID"},itemResourceId:{type:"string"},taxProfileResourceId:{type:"string"}}}},recordedPayment:{type:"object",description:"Optional. The matching payment record \u2014 auto-built from the bank entry if omitted.",properties:{reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},organizationAccountResourceId:{type:"string"},paymentAmount:{type:"number"},transactionAmount:{type:"number"},paymentMethod:{type:"string",description:"Defaults to BANK_TRANSFER"}}},capsuleResourceId:{type:"string"}}}},required:["bankStatementEntryResourceId","bankAccountResourceId","invoiceDetails"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry invoice receipt AR sale",execute:async(e,t)=>(Ice(t.invoiceDetails,"invoiceDetails"),PY(e.client,t))},{name:"reconcile_bill_receipt",description:'CREATES A NEW bill and auto-reconciles it to a bank statement entry (AP). To match an EXISTING open bill instead, use reconcile_with_payments (do not create a duplicate). \u26A0\uFE0F BSE must have `paymentDirection: PAYOUT` (money out \u2014 AP). Produce via `bank add-records` with a NEGATIVE amount (creates `debit_amount > 0` \u2192 PAYOUT). Statement-imported BSEs from `bank import` also work. The error code "Invalid business transaction type" (422) is misleadingly named \u2014 the actual gate is direction, not entry type. Sync \u2014 returns the reconciled entry status. valueDate / dueDate / payment amount prefill from the bank entry if omitted. NOT idempotent.',params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID \u2014 required"},billDetails:{type:"object",description:"The bill to create. Required.",properties:{reference:{type:"string",description:"Bill reference \u2014 required"},contactResourceId:{type:"string",description:"Supplier UUID"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},dueDate:{type:"string",description:"YYYY-MM-DD. Defaults to value date."},taxInclusion:{type:"boolean"},isTaxVATApplicable:{type:"boolean"},lineItems:{type:"array",description:"Bill line items (max 500) \u2014 required",items:{type:"object",properties:{name:{type:"string",description:"Line description \u2014 required"},quantity:{type:"number"},unit:{type:"string"},unitPrice:{type:"number"},organizationAccountResourceId:{type:"string",description:"Expense account UUID"},itemResourceId:{type:"string"},taxProfileResourceId:{type:"string"}}}},recordedPayment:{type:"object",description:"Optional. The matching payment record \u2014 auto-built from the bank entry if omitted.",properties:{reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD"},organizationAccountResourceId:{type:"string"},paymentAmount:{type:"number"},transactionAmount:{type:"number"},paymentMethod:{type:"string",description:"Defaults to BANK_TRANSFER"}}},capsuleResourceId:{type:"string"}}}},required:["bankStatementEntryResourceId","bankAccountResourceId","billDetails"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry bill receipt AP purchase",execute:async(e,t)=>(Ice(t.billDetails,"billDetails"),$Y(e.client,t))},{name:"reconcile_with_payments",description:"USE THIS to match a bank statement entry to an EXISTING open bill / invoice / payment (NOT reconcile_bill_receipt or reconcile_invoice_receipt, which CREATE a new bill/invoice). Pass the open transaction's cashflowTransactionResourceId (from search_cashflow_transactions or a view_auto_reconciliation suggestion) in businessTransactionPayments[] \u2014 this CREATES the payment AND reconciles in one call; no pay_bill / pay_invoice first. FX is resolved server-side \u2014 pass NO rate for the common case (only supply paymentAmount + currencySettings for the rare bill-currency \u2260 bank-currency case). Sync \u2014 returns the reconciled entry status. NOT idempotent: a blind retry double-creates a payment; confirm reconciled-state via search_bank_records(status: RECONCILED) before retrying.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},businessTransactionPayments:{type:"array",description:"Open business transactions (bills/invoices) to reconcile by creating a payment against each.",items:{type:"object",properties:{cashflowTransactionResourceId:{type:"string",description:"Open BT cashflow UUID (the bill/invoice) \u2014 required"},transactionAmount:{type:"number",description:"Payment amount in the BT currency \u2014 required (>0)"},paymentAmount:{type:"number",description:"Actual amount in bank-statement currency. Required ONLY when bank currency \u2260 BT currency."},currencySettings:{type:"object",description:"FX settings \u2014 supply ONLY for cross-currency (bank ccy \u2260 BT ccy). Omit otherwise (server resolves).",properties:{sourceCurrencyCode:{type:"string",description:"BT currency (ISO 4217)"},rateFunctionalToSource:{type:"number"},exchangeToken:{type:"string"}}}}}},matchedPayments:{type:"array",items:{type:"string"},description:"Existing payment UUIDs to reconcile against the entry"},matchedBatchPayments:{type:"array",items:{type:"string"},description:"Existing batch payment UUIDs to reconcile against the entry"},adjustment:{type:"object",description:"Optional adjustment leg to balance payments vs the statement amount (over/under-payment, rounding, or FX gain/loss write-off \u2014 the platform does NOT auto-post FX gain/loss).",properties:{reference:{type:"string"},contactResourceId:{type:"string"},tags:{type:"array",items:{type:"string"}},cashAdjustmentEntries:{type:"array",items:{type:"object",properties:{organizationAccountResourceId:{type:"string",description:"e.g. the FX gain/loss account UUID"},amount:{type:"number"},description:{type:"string"},taxProfileResourceId:{type:"string"},rateSourceToFunctional:{type:"number",description:"Required when this account is in a non-functional currency."}}}},bankAccountJournalEntryRateFunctionalToSource:{type:"number",description:"Required when the bank account is in a non-functional currency."}}}},required:["bankStatementEntryResourceId"],group:"reconciliations",readOnly:!1,searchHint:"match bank entry to existing open bill invoice payment reconcile with payments pay outstanding",execute:async(e,t)=>(net(t),UY(e.client,t))},{name:"reconcile_magic_match",description:"Bulk-accept MAGIC_MATCH suggestions: reconcile many bank entries against EXISTING open business transactions and/or payments in one call (max 500 entries). Feed entries from view_auto_reconciliation suggestions. Returns a per-entry split { reconciled[], failed[] } \u2014 a 200 with a non-empty failed[] is a PARTIAL success; surface failed entries (with their errorCode) and loop. Entry-level idempotency-keyed server-side. Use reconcile_with_payments for a single precise match; use this to accept a batch of suggestions at once.",params:{bankAccountResourceId:{type:"string",description:"Bank account UUID the entries belong to \u2014 required"},autoReconcileRunResourceId:{type:"string",description:"Auto-reconciliation run UUID for batch tracking"},entries:{type:"array",description:"One row per bank entry to reconcile (max 500).",items:{type:"object",properties:{workflowType:{type:"string",enum:["MAGIC_MATCH"],description:"Only MAGIC_MATCH (match to existing) is supported here."},bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},matchedBusinessTransactions:{type:"array",items:{type:"string"},description:"Open BT cashflow UUIDs to reconcile by creating payments"},matchedPayments:{type:"array",items:{type:"string"},description:"Existing payment UUIDs"},matchedBatchResourceId:{type:"string",description:"Batch payment UUID"}}}}},required:["bankAccountResourceId","entries"],group:"reconciliations",readOnly:!1,searchHint:"bulk accept magic match suggestions reconcile many bank entries to existing",execute:async(e,t)=>(Ii(t.entries,"entries",500,"entries"),jY(e.client,t))},{name:"reconcile_learned_prediction",description:"Accept an ML learned-prediction suggestion to reconcile a bank entry. predictedPayload + predictedPayloadSchemaVersion are passed through VERBATIM from a view_auto_reconciliation suggestion (recommendationType MAGIC_RECONCILE_WITH_CASH_IN_OUT) \u2014 do not construct them by hand. Pass retryToken to force a fresh journal on an edit-then-retry; omit it for an idempotent replay. Sync \u2014 returns the reconciled entry status. On failure (stale/invalid payload), fall back to reconcile_with_payments \u2014 do NOT retry the same opaque payload.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},learnedPredictionResourceId:{type:"string",description:"Learned-prediction UUID from the suggestion \u2014 required"},predictedPayload:{type:"string",description:"Opaque JSON payload from the suggestion \u2014 required, passed verbatim"},predictedPayloadSchemaVersion:{type:"string",description:"Schema version from the suggestion \u2014 required"},retryToken:{type:"string",description:"Optional idempotency retry token"},autoReconcileRunResourceId:{type:"string",description:"Auto-reconciliation run UUID for batch tracking"}},required:["bankStatementEntryResourceId","learnedPredictionResourceId","predictedPayload","predictedPayloadSchemaVersion"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry learned prediction ML cash in out accept suggestion",execute:async(e,t)=>qY(e.client,t)},{name:"validate_drafts",description:`BULK validate up to 500 draft business transactions in ONE call, mixing any btType. SYNC \u2014 returns per-item errors + display data; no state change. Run before convert_drafts_to_active.
865
+ ASYNC: returns jobId \u2192 poll search_background_jobs(filter:{resourceId:{eq:jobId}}); on PARTIAL_SUCCESS read data[0].errorDetails. Dates ISO 8601 (YYYY-MM-DD).`,params:{fixedAssets:{type:"array",description:"Fixed assets to create/update (max 500).",items:{type:"object",properties:{rowIndex:{type:"string"},resourceId:{type:"string"},reference:{type:"string",description:"Natural key \u2014 required"},registrationType:{type:"string",enum:["NEW","TRANSFER"],description:"NEW = newly acquired, TRANSFER = inherited \u2014 required"},typeCode:{type:"string",description:"Asset class code (e.g. FURNITURE_AND_FIXTURE)"},typeName:{type:"string",description:"Human label for typeCode"},category:{type:"string",enum:["TANGIBLE","INTANGIBLE"],description:"TANGIBLE | INTANGIBLE"},name:{type:"string",description:"Asset name"},valueDate:{type:"string",description:"Acquisition date YYYY-MM-DD (request only; GET response uses purchaseDate)."},cost:{type:"number",description:"Cost basis (alias purchaseAmount)."},purchaseAmount:{type:"number",description:"Synonym of cost."},currencyCode:{type:"string"},depreciationStartDate:{type:"number",description:"Epoch ms (NOT YYYY-MM-DD on this endpoint \u2014 sending YYYY-MM-DD \u2192 400). Omit to default to valueDate."},effectiveLife:{type:"number",description:"Useful life months (alias usefulLifeMonths)."},usefulLifeMonths:{type:"number",description:"Synonym of effectiveLife."},depreciationMethod:{type:"string",enum:["STRAIGHT_LINE","NO_DEPRECIATION"],description:"Bulk accepts only STRAIGHT_LINE or NO_DEPRECIATION (422 otherwise) \u2014 use create_fixed_asset for declining-balance methods."},purchaseAssetAccountResourceId:{type:"string",description:"Asset (PPE) account UUIDv4."},depreciationExpenseAccountResourceId:{type:"string",description:"Depreciation expense account UUIDv4."},accumulatedDepreciationAccountResourceId:{type:"string",description:"Accumulated depreciation account UUIDv4."},internalNotes:{type:"string"},tags:{type:"array",items:{type:"string"}}}}}},required:["fixedAssets"],group:"fixed_assets",readOnly:!1,searchHint:"bulk fixed assets ppe register upsert import migrate",execute:async(e,t)=>{Ii(t.fixedAssets,"fixedAssets",500,"fixed assets");let r=t.fixedAssets;return ic(r,["valueDate"]),eY(e.client,r)}},{name:"quick_reconcile",description:`Bulk-reconcile bank statement entries against a list of journals (max 500). Reconciliation mode is hardcoded to QUICK_RECON. ${Tu} Caller provides bankAccountResourceId + journalsForReconciliation[] (each row: bankStatementEntryResourceId, journalReference, journalAccountResourceId).`,params:{bankAccountResourceId:{type:"string",description:"Bank account UUID (the entries belong to this account)"},journalsForReconciliation:{type:"array",description:"Per-row reconciliation instructions (max 500).",items:{type:"object",properties:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},journalReference:{type:"string",description:"Journal reference text \u2014 required"},journalAccountResourceId:{type:"string",description:"Offsetting account UUID (revenue for cash-in, expense for cash-out) \u2014 required"},contactResourceId:{type:"string",description:"Contact UUID"},capsuleResourceId:{type:"string",description:"Capsule UUID"},taxProfileResourceId:{type:"string",description:"Tax profile UUID"},internalNotes:{type:"string"},journalEntryDescription:{type:"string"},tags:{type:"array",items:{type:"string"}},rowIndex:{type:"string",description:"Optional caller-supplied index for error correlation"}}}}},required:["bankAccountResourceId","journalsForReconciliation"],group:"reconciliations",readOnly:!1,searchHint:"bulk reconcile bank statement journals match",execute:async(e,t)=>(Ii(t.journalsForReconciliation,"journalsForReconciliation",500,"journals"),NY(e.client,t))},{name:"apply_bank_rule",description:"Apply a pre-configured bank rule (action shortcut) to a batch of bank statement entries (max 500). Async \u2014 returns a jobId. Poll search_background_jobs filtered by resourceId. The rule executes its configured action (e.g. RECONCILE_WITH_DIRECT_CASH_ENTRY) on each entry.",params:{actionShortcutResourceId:{type:"string",description:"Bank rule UUID \u2014 required"},businessTransactionResourceIds:{type:"array",description:"Bank statement entry UUIDs to apply the rule to (max 500). Note: the field is named businessTransactionResourceIds for legacy reasons but accepts bank entry IDs.",items:{type:"string"}}},required:["actionShortcutResourceId","businessTransactionResourceIds"],group:"reconciliations",readOnly:!1,searchHint:"bank rule apply action shortcut bulk reconcile",execute:async(e,t)=>(Ii(t.businessTransactionResourceIds,"businessTransactionResourceIds",500,"entries"),FY(e.client,t))},{name:"reconcile_direct_cash_entry",description:"Reconcile a bank statement entry with a single cash-in / cash-out line. Direction (cash-in vs cash-out) is INFERRED from the bank entry sign. Sync \u2014 returns the reconciled entry status. NOT idempotent: calling twice on the same bankStatementEntryResourceId creates duplicate journals. Confirm reconciled-state via view_auto_reconciliation before retrying.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID (used to look up the entry) \u2014 required"},reference:{type:"string",description:"Reference for the cash entry \u2014 required"},accountResourceId:{type:"string",description:"Offsetting account UUID (revenue for cash-in, expense for cash-out) \u2014 required"},amount:{type:"number",description:"Amount in source currency. Defaults to bank entry amount if omitted."},description:{type:"string"},contactResourceId:{type:"string"},taxProfileResourceId:{type:"string"},internalNotes:{type:"string"},bankAccountJournalEntryDescription:{type:"string",description:"Description for the bank-side journal entry"},tags:{type:"array",items:{type:"string"}},taxVatApplicable:{type:"boolean"},taxInclusion:{type:"boolean"},capsuleResourceId:{type:"string"}},required:["bankStatementEntryResourceId","bankAccountResourceId","reference","accountResourceId"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry direct cash in out single line",execute:async(e,t)=>OY(e.client,t)},{name:"reconcile_cash_journal",description:"Reconcile a bank statement entry with a multi-line cashflow journal (multiple cash splits, max 200 lines). Sync \u2014 returns the reconciled entry status. NOT idempotent \u2014 confirm reconciled-state before retrying.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID \u2014 required"},reference:{type:"string",description:"Journal reference \u2014 required"},journalEntries:{type:"array",description:"Cash journal lines (max 200). Each row is one debit OR credit against an account.",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account UUID \u2014 required"},amount:{type:"number",description:"Amount in source currency \u2014 required (>0)"},description:{type:"string"},taxProfileResourceId:{type:"string"}}}},contactResourceId:{type:"string"},bankAccountJournalEntryDescription:{type:"string"},internalNotes:{type:"string"},tags:{type:"array",items:{type:"string"}},taxVatApplicable:{type:"boolean"},taxInclusion:{type:"boolean"},capsuleResourceId:{type:"string"}},required:["bankStatementEntryResourceId","bankAccountResourceId","reference","journalEntries"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry multi line cash journal splits",execute:async(e,t)=>(Ii(t.journalEntries,"journalEntries",200,"entries"),QY(e.client,t))},{name:"reconcile_manual_journal",description:'\u26A0\uFE0F CALLER PROVIDES ONLY THE OFFSET LEG(S) \u2014 backend AUTO-ADDS the bank-side leg from the statement entry. Sending both debit AND credit legs \u2192 422 "sum of debit and credit amounts are not equal" (your sides duplicate after the auto-add). Reconcile a bank statement entry with a double-entry manual journal. Sync \u2014 returns the reconciled entry status. valueDate prefills from bank entry if omitted. NOT idempotent.',params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID \u2014 required"},status:{type:"string",enum:["DRAFT","ACTIVE"],description:"Journal status \u2014 required"},journalEntries:{type:"array",description:"Offset-side journal entries only (max 200). The bank-side leg is auto-added by the API.",items:{type:"object",properties:{accountResourceId:{type:"string",description:"Account UUID \u2014 required"},type:{type:"string",enum:["DEBIT","CREDIT"]},amount:{type:"number",description:"Amount \u2014 required"},description:{type:"string"},contactResourceId:{type:"string"},taxProfileResourceId:{type:"string"}}}},reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},contactResourceId:{type:"string"},internalNotes:{type:"string"},bankAccountJournalEntryDescription:{type:"string"},taxVatApplicable:{type:"boolean"},taxInclusion:{type:"boolean"},tags:{type:"array",items:{type:"string"}},capsuleResourceId:{type:"string"}},required:["bankStatementEntryResourceId","bankAccountResourceId","status","journalEntries"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry manual journal double entry",execute:async(e,t)=>(Ii(t.journalEntries,"journalEntries",200,"entries"),LY(e.client,t))},{name:"reconcile_cash_transfer",description:"Reconcile a bank statement entry with an inter-account transfer. Sync \u2014 returns the reconciled entry status. amount is required only when the counterparty account is in a non-functional currency. NOT idempotent.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID \u2014 required"},accountResourceId:{type:"string",description:"Counterparty cash account UUID \u2014 required"},reference:{type:"string",description:"Transfer reference \u2014 required"},amount:{type:"number",description:"Amount in source currency. Required only for cross-currency transfers."},contactResourceId:{type:"string"},internalNotes:{type:"string"},tags:{type:"array",items:{type:"string"}},capsuleResourceId:{type:"string"}},required:["bankStatementEntryResourceId","bankAccountResourceId","accountResourceId","reference"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry transfer between accounts",execute:async(e,t)=>MY(e.client,t)},{name:"reconcile_invoice_receipt",description:'CREATES A NEW invoice and auto-reconciles it to a bank statement entry (AR). To match an EXISTING open invoice instead, use reconcile_with_payments (do not create a duplicate). \u26A0\uFE0F BSE must have `paymentDirection: PAYIN` (money in \u2014 AR). Produce via `bank add-records` with a POSITIVE amount (creates `credit_amount > 0` \u2192 PAYIN). Statement-imported BSEs from `bank import` also work. The error code "Invalid business transaction type" (422) is misleadingly named \u2014 the actual gate is direction, not entry type. Sync \u2014 returns the reconciled entry status. valueDate / dueDate / payment amount prefill from the bank entry if omitted. NOT idempotent.',params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID \u2014 required"},invoiceDetails:{type:"object",description:"The invoice to create. Required.",properties:{reference:{type:"string",description:"Invoice reference \u2014 required"},contactResourceId:{type:"string",description:"Customer UUID"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},dueDate:{type:"string",description:"YYYY-MM-DD. Defaults to value date."},taxInclusion:{type:"boolean"},isTaxVATApplicable:{type:"boolean"},lineItems:{type:"array",description:"Invoice line items (max 500) \u2014 required",items:{type:"object",properties:{name:{type:"string",description:"Line description \u2014 required"},quantity:{type:"number"},unit:{type:"string"},unitPrice:{type:"number"},organizationAccountResourceId:{type:"string",description:"Revenue account UUID"},itemResourceId:{type:"string"},taxProfileResourceId:{type:"string"}}}},recordedPayment:{type:"object",description:"Optional. The matching payment record \u2014 auto-built from the bank entry if omitted.",properties:{reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},organizationAccountResourceId:{type:"string"},paymentAmount:{type:"number"},transactionAmount:{type:"number"},paymentMethod:{type:"string",description:"Defaults to BANK_TRANSFER"}}},capsuleResourceId:{type:"string"}}}},required:["bankStatementEntryResourceId","bankAccountResourceId","invoiceDetails"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry invoice receipt AR sale",execute:async(e,t)=>(Ice(t.invoiceDetails,"invoiceDetails"),PY(e.client,t))},{name:"reconcile_bill_receipt",description:'CREATES A NEW bill and auto-reconciles it to a bank statement entry (AP). To match an EXISTING open bill instead, use reconcile_with_payments (do not create a duplicate). \u26A0\uFE0F BSE must have `paymentDirection: PAYOUT` (money out \u2014 AP). Produce via `bank add-records` with a NEGATIVE amount (creates `debit_amount > 0` \u2192 PAYOUT). Statement-imported BSEs from `bank import` also work. The error code "Invalid business transaction type" (422) is misleadingly named \u2014 the actual gate is direction, not entry type. Sync \u2014 returns the reconciled entry status. valueDate / dueDate / payment amount prefill from the bank entry if omitted. NOT idempotent.',params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},bankAccountResourceId:{type:"string",description:"Bank account UUID \u2014 required"},billDetails:{type:"object",description:"The bill to create. Required.",properties:{reference:{type:"string",description:"Bill reference \u2014 required"},contactResourceId:{type:"string",description:"Supplier UUID"},valueDate:{type:"string",description:"YYYY-MM-DD. Defaults to bank entry value date."},dueDate:{type:"string",description:"YYYY-MM-DD. Defaults to value date."},taxInclusion:{type:"boolean"},isTaxVATApplicable:{type:"boolean"},lineItems:{type:"array",description:"Bill line items (max 500) \u2014 required",items:{type:"object",properties:{name:{type:"string",description:"Line description \u2014 required"},quantity:{type:"number"},unit:{type:"string"},unitPrice:{type:"number"},organizationAccountResourceId:{type:"string",description:"Expense account UUID"},itemResourceId:{type:"string"},taxProfileResourceId:{type:"string"}}}},recordedPayment:{type:"object",description:"Optional. The matching payment record \u2014 auto-built from the bank entry if omitted.",properties:{reference:{type:"string"},valueDate:{type:"string",description:"YYYY-MM-DD"},organizationAccountResourceId:{type:"string"},paymentAmount:{type:"number"},transactionAmount:{type:"number"},paymentMethod:{type:"string",description:"Defaults to BANK_TRANSFER"}}},capsuleResourceId:{type:"string"}}}},required:["bankStatementEntryResourceId","bankAccountResourceId","billDetails"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry bill receipt AP purchase",execute:async(e,t)=>(Ice(t.billDetails,"billDetails"),$Y(e.client,t))},{name:"reconcile_with_payments",description:"USE THIS to match a bank statement entry to an EXISTING open bill / invoice / payment (NOT reconcile_bill_receipt or reconcile_invoice_receipt, which CREATE a new bill/invoice). Pass the open transaction's cashflowTransactionResourceId (from search_cashflow_transactions or a view_auto_reconciliation suggestion) in businessTransactionPayments[] \u2014 this CREATES the payment AND reconciles in one call; no pay_bill / pay_invoice first. FX is resolved server-side \u2014 pass NO rate for the common case (only supply paymentAmount + currencySettings for the rare bill-currency \u2260 bank-currency case). Sync \u2014 returns the reconciled entry status. NOT idempotent: a blind retry double-creates a payment; confirm reconciled-state via search_bank_records(status: RECONCILED) before retrying.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},businessTransactionPayments:{type:"array",description:"Open business transactions (bills/invoices) to reconcile by creating a payment against each.",items:{type:"object",properties:{cashflowTransactionResourceId:{type:"string",description:"Open BT cashflow UUID (the bill/invoice) \u2014 required"},transactionAmount:{type:"number",description:"Payment amount in the BT currency \u2014 required (>0)"},paymentAmount:{type:"number",description:"Actual amount in bank-statement currency. Required ONLY when bank currency \u2260 BT currency."},currencySettings:{type:"object",description:"FX settings \u2014 supply ONLY for cross-currency (bank ccy \u2260 BT ccy). Omit otherwise (server resolves).",properties:{sourceCurrencyCode:{type:"string",description:"BT currency (ISO 4217)"},rateFunctionalToSource:{type:"number"},exchangeToken:{type:"string"}}}}}},matchedPayments:{type:"array",items:{type:"string"},description:"Existing payment UUIDs to reconcile against the entry"},matchedBatchPayments:{type:"array",items:{type:"string"},description:"Existing batch payment UUIDs to reconcile against the entry"},adjustment:{type:"object",description:"Optional adjustment leg to balance payments vs the statement amount (over/under-payment, rounding, or FX gain/loss write-off \u2014 the platform does NOT auto-post FX gain/loss).",properties:{reference:{type:"string"},contactResourceId:{type:"string"},tags:{type:"array",items:{type:"string"}},cashAdjustmentEntries:{type:"array",items:{type:"object",properties:{organizationAccountResourceId:{type:"string",description:"e.g. the FX gain/loss account UUID"},amount:{type:"number"},description:{type:"string"},taxProfileResourceId:{type:"string"},rateSourceToFunctional:{type:"number",description:"Required when this account is in a non-functional currency."}}}},bankAccountJournalEntryRateFunctionalToSource:{type:"number",description:"Required when the bank account is in a non-functional currency."}}}},required:["bankStatementEntryResourceId"],group:"reconciliations",readOnly:!1,searchHint:"match bank entry to existing open bill invoice payment reconcile with payments pay outstanding",execute:async(e,t)=>(net(t),UY(e.client,t))},{name:"reconcile_magic_match",description:"Bulk-accept MAGIC_MATCH suggestions: reconcile many bank entries against EXISTING open business transactions and/or payments in one call (max 500 entries). Feed entries from view_auto_reconciliation suggestions. Returns a per-entry split { reconciled[], failed[] } \u2014 a 200 with a non-empty failed[] is a PARTIAL success; surface failed entries (with their errorCode) and loop. Entry-level idempotency-keyed server-side. Use reconcile_with_payments for a single precise match; use this to accept a batch of suggestions at once.",params:{bankAccountResourceId:{type:"string",description:"Bank account UUID the entries belong to \u2014 required"},autoReconcileRunResourceId:{type:"string",description:"Auto-reconciliation run UUID for batch tracking"},entries:{type:"array",description:"One row per bank entry to reconcile (max 500).",items:{type:"object",properties:{workflowType:{type:"string",enum:["MAGIC_MATCH"],description:"Only MAGIC_MATCH (match to existing) is supported here."},bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},matchedBusinessTransactions:{type:"array",items:{type:"string"},description:"Open BT cashflow UUIDs to reconcile by creating payments"},matchedPayments:{type:"array",items:{type:"string"},description:"Existing payment UUIDs"},matchedBatchResourceId:{type:"string",description:"Batch payment UUID"}}}}},required:["bankAccountResourceId","entries"],group:"reconciliations",readOnly:!1,searchHint:"bulk accept magic match suggestions reconcile many bank entries to existing",execute:async(e,t)=>(Ii(t.entries,"entries",500,"entries"),jY(e.client,t))},{name:"reconcile_learned_prediction",description:"Accept an ML learned-prediction suggestion to reconcile a bank entry. predictedPayload + predictedPayloadSchemaVersion are passed through VERBATIM from a view_auto_reconciliation suggestion (recommendationType MAGIC_RECONCILE_WITH_CASH_IN_OUT) \u2014 do not construct them by hand. Pass retryToken to force a fresh journal on an edit-then-retry; omit it for an idempotent replay. Sync \u2014 returns the reconciled entry status. On failure (stale/invalid payload), fall back to reconcile_with_payments \u2014 do NOT retry the same opaque payload.",params:{bankStatementEntryResourceId:{type:"string",description:"Bank entry UUID \u2014 required"},learnedPredictionResourceId:{type:"string",description:"Learned-prediction UUID from the suggestion \u2014 required"},predictedPayload:{type:"string",description:"Opaque JSON payload from the suggestion \u2014 required, passed verbatim"},predictedPayloadSchemaVersion:{type:"string",description:"Schema version from the suggestion \u2014 required"},retryToken:{type:"string",description:"Optional idempotency retry token"},autoReconcileRunResourceId:{type:"string",description:"Auto-reconciliation run UUID for batch tracking"}},required:["bankStatementEntryResourceId","learnedPredictionResourceId","predictedPayload","predictedPayloadSchemaVersion"],group:"reconciliations",readOnly:!1,searchHint:"reconcile bank entry learned prediction ML cash in out accept suggestion",execute:async(e,t)=>qY(e.client,t)},{name:"validate_drafts",description:`BULK validate up to 500 draft business transactions in ONE call, mixing any btType. SYNC \u2014 returns per-item errors + display data; no state change. Run before convert_drafts_to_active.
866
866
 
867
867
  btType enum: SALE = invoice, PURCHASE = bill, SALE_CREDIT_NOTE = customer CN, PURCHASE_CREDIT_NOTE = supplier CN. Journals NOT in this enum.
868
868
 
@@ -1125,7 +1125,7 @@ Dynamic Strings (usable in reference, line item name, notes):
1125
1125
  {{MonthRange:X}} Month range spanning X months
1126
1126
  {{Year}} Year (2026)
1127
1127
  {{Year+X}} Year + X years (e.g., {{Year+1}} \u2192 2027)
1128
- Strings are replaced with values relative to the transaction date.`);t.command("list-invoices").description("List scheduled invoices").option("--limit <n>","Max results (default 100)",we).option("--offset <n>","Page number offset (0-indexed)",it).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",we).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(j(async(r,n)=>{let i=await Ke(n,s=>nj(r,s),{label:"Fetching scheduled invoices"});Je(i,Uce,n,"Scheduled Invoices")})),t.command("list-bills").description("List scheduled bills").option("--limit <n>","Max results (default 100)",we).option("--offset <n>","Page number offset (0-indexed)",it).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",we).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(j(async(r,n)=>{let i=await Ke(n,s=>ij(r,s),{label:"Fetching scheduled bills"});Je(i,Uce,n,"Scheduled Bills")})),t.command("list-journals").description("List scheduled journals").option("--limit <n>","Max results (default 100)",we).option("--offset <n>","Page number offset (0-indexed)",it).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",we).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(j(async(r,n)=>{let i=await Ke(n,s=>sj(r,s),{label:"Fetching scheduled journals"});Je(i,Uce,n,"Scheduled Journals")})),t.command("create-invoice").description("Create a scheduled (recurring) invoice").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date (optional)").option("--repeat <interval>","Recurrence: WEEKLY, MONTHLY, QUARTERLY, YEARLY").option("--contact <resourceId>","Customer contact resourceId").option("--reference <ref>","Invoice reference").option("--value-date <YYYY-MM-DD>","Template issue date").option("--due-date <YYYY-MM-DD>","Template due date").option("--line-items <json>","Line items as JSON string").option("--tag <name>","Tag name").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(j(async(r,n)=>{let i=Ce(n),s;if(i)s=await qD(r,i);else{Xe(n,[{flag:"--start-date",key:"startDate"},{flag:"--repeat",key:"repeat"},{flag:"--contact",key:"contact"},{flag:"--reference",key:"reference"},{flag:"--value-date",key:"valueDate"},{flag:"--due-date",key:"dueDate"},{flag:"--line-items",key:"lineItems"}]);let o=$n(n.lineItems);s=await qD(r,{status:"ACTIVE",startDate:n.startDate,endDate:n.endDate,repeat:n.repeat,invoice:{reference:n.reference,valueDate:n.valueDate,dueDate:n.dueDate,contactResourceId:n.contact,lineItems:o,tags:n.tag?[n.tag]:void 0,saveAsDraft:!1}})}n.json?console.log(JSON.stringify(s.data,null,2)):console.log(V("Scheduled invoice created"))})),t.command("create-bill").description("Create a scheduled (recurring) bill").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date (optional)").option("--repeat <interval>","Recurrence: WEEKLY, MONTHLY, QUARTERLY, YEARLY").option("--contact <resourceId>","Supplier contact resourceId").option("--reference <ref>","Bill reference").option("--value-date <YYYY-MM-DD>","Template issue date").option("--due-date <YYYY-MM-DD>","Template due date").option("--line-items <json>","Line items as JSON string").option("--tag <name>","Tag name").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(j(async(r,n)=>{let i=Ce(n),s;if(i)s=await ZI(r,i);else{Xe(n,[{flag:"--start-date",key:"startDate"},{flag:"--repeat",key:"repeat"},{flag:"--contact",key:"contact"},{flag:"--reference",key:"reference"},{flag:"--value-date",key:"valueDate"},{flag:"--due-date",key:"dueDate"},{flag:"--line-items",key:"lineItems"}]);let o=$n(n.lineItems);s=await ZI(r,{status:"ACTIVE",startDate:n.startDate,endDate:n.endDate,repeat:n.repeat,bill:{reference:n.reference,valueDate:n.valueDate,dueDate:n.dueDate,contactResourceId:n.contact,lineItems:o,tags:n.tag?[n.tag]:void 0,saveAsDraft:!1}})}n.json?console.log(JSON.stringify(s.data,null,2)):console.log(V("Scheduled bill created"))})),t.command("create-journal").description("Create a scheduled (recurring) journal").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date (optional)").option("--repeat <interval>","Recurrence: WEEKLY, MONTHLY, QUARTERLY, YEARLY").option("--reference <ref>","Journal reference").option("--value-date <YYYY-MM-DD>","Template date").option("--entries <json>","Scheduler entries as JSON string").option("--notes <text>","Journal notes").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(j(async(r,n)=>{let i=Ce(n),s;if(i)s=await JD(r,i);else{Xe(n,[{flag:"--start-date",key:"startDate"},{flag:"--repeat",key:"repeat"},{flag:"--value-date",key:"valueDate"},{flag:"--entries",key:"entries"}]);let o=cc(n.entries);s=await JD(r,{status:"ACTIVE",startDate:n.startDate,endDate:n.endDate,repeat:n.repeat,valueDate:n.valueDate,schedulerEntries:o,reference:n.reference,internalNotes:n.notes})}n.json?console.log(JSON.stringify(s.data,null,2)):console.log(V("Scheduled journal created"))})),t.command("get-invoice <resourceId>").description("Get a scheduled invoice by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=await oj(i,r);if(n.json)console.log(JSON.stringify(s.data,null,2));else{let o=s.data;console.log(N("ID:"),o.resourceId),console.log(N("Status:"),o.status),console.log(N("Repeat:"),o.interval??o.repeat),console.log(N("Start:"),o.startDate),o.endDate&&console.log(N("End:"),o.endDate)}})(n)),t.command("update-invoice <resourceId>").description("Update a scheduled invoice").option("--repeat <interval>","Recurrence: WEEKLY, MONTHLY, QUARTERLY, YEARLY").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date").option("--status <status>","Status: ACTIVE or PAUSED").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=Ce(n),o=s??{};s||(n.repeat&&(o.repeat=n.repeat),n.startDate&&(o.startDate=n.startDate),n.endDate&&(o.endDate=n.endDate),n.status&&(o.status=n.status));let a=await aj(i,r,o);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(V(`Scheduled invoice ${r} updated.`))})(n)),t.command("delete-invoice <resourceId>").description("Delete a scheduled invoice").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{await cj(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(V(`Scheduled invoice ${r} deleted.`))})(n)),t.command("get-bill <resourceId>").description("Get a scheduled bill by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=await uj(i,r);if(n.json)console.log(JSON.stringify(s.data,null,2));else{let o=s.data;console.log(N("ID:"),o.resourceId),console.log(N("Status:"),o.status),console.log(N("Repeat:"),o.interval??o.repeat),console.log(N("Start:"),o.startDate),o.endDate&&console.log(N("End:"),o.endDate)}})(n)),t.command("update-bill <resourceId>").description("Update a scheduled bill").option("--repeat <interval>","Recurrence: WEEKLY, MONTHLY, QUARTERLY, YEARLY").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date").option("--status <status>","Status: ACTIVE or PAUSED").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=Ce(n),o=s??{};s||(n.repeat&&(o.repeat=n.repeat),n.startDate&&(o.startDate=n.startDate),n.endDate&&(o.endDate=n.endDate),n.status&&(o.status=n.status));let a=await lj(i,r,o);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(V(`Scheduled bill ${r} updated.`))})(n)),t.command("delete-bill <resourceId>").description("Delete a scheduled bill").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{await fj(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(V(`Scheduled bill ${r} deleted.`))})(n)),t.command("get-journal <resourceId>").description("Get a scheduled journal by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=await dj(i,r);if(n.json)console.log(JSON.stringify(s.data,null,2));else{let o=s.data;console.log(N("ID:"),o.resourceId),console.log(N("Status:"),o.status),console.log(N("Repeat:"),o.interval??o.repeat),console.log(N("Start:"),o.startDate),o.endDate&&console.log(N("End:"),o.endDate)}})(n)),t.command("update-journal <resourceId>").description("Update a scheduled journal").option("--repeat <interval>","Recurrence: WEEKLY, MONTHLY, QUARTERLY, YEARLY").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date").option("--status <status>","Status: ACTIVE or PAUSED").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=Ce(n),o=s??{};s||(n.repeat&&(o.repeat=n.repeat),n.startDate&&(o.startDate=n.startDate),n.endDate&&(o.endDate=n.endDate),n.status&&(o.status=n.status));let a=await pj(i,r,o);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(V(`Scheduled journal ${r} updated.`))})(n)),t.command("delete-journal <resourceId>").description("Delete a scheduled journal").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{await hj(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(V(`Scheduled journal ${r} deleted.`))})(n))}Le();ace();Tt();qt();function Rtt(e){e.command("exports").description("Manage data exports").command("download").description("Download a data export report").option("--type <exportType>","Export type (e.g., trial-balance, balance-sheet, profit-and-loss, general-ledger, sales-summary, etc.)").option("--format <XLSX|PDF>","Output format. Defaults to XLSX. PDF only for: balance-sheet, profit-and-loss, trial-balance, cashflow.").option("--start-date <YYYY-MM-DD>","Period start date").option("--end-date <YYYY-MM-DD>","Period end date").option("--currency <code>","Currency code override").option("--tags <csv>","Comma-separated tag names").option("--contact <resourceId>","Filter by contact resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(j(async(r,n)=>{Xe(n,[{flag:"--type",key:"type"}]);let i=n.type,s={};if(n.format){let a=n.format.toUpperCase();if(a!=="XLSX"&&a!=="PDF")throw new Error(`Invalid --format: ${n.format}. Allowed: XLSX, PDF.`);s.outputFormat=a}n.startDate&&(s.startDate=n.startDate),n.endDate&&(["balance-sheet"].includes(i)?s.snapshotDate=n.endDate:s.endDate=n.endDate),n.currency&&(s.currencyCode=n.currency),n.tags&&(s.tags=n.tags.split(",").map(a=>a.trim())),n.contact&&(s.contactResourceId=n.contact);let o=await Tj(r,i,s);if(n.json)console.log(JSON.stringify(o.data,null,2));else{let a=o.data;console.log(V("Export ready")),a.fileName&&console.log(N("File:"),a.fileName),a.fileUrl&&console.log(N("URL:"),a.fileUrl)}}))}Kae();Zae();Le();function xtt(e){e.command("help-center").alias("hc").description("Search the Jaz help center").argument("<query...>",'Search query (e.g. "bank recon", "how to apply credit")').option("--limit <n>","Max results (default 5)",parseInt).option("--section <slug>","Filter by section (e.g. invoices, bills, settings)").option("--json","Output as JSON").action(async(t,r)=>{try{let n=JR(),i=t.join(" "),s=r.limit??5,o=r.section,a=WR(),c=Wae(a),u=c?await ZR(n,a,i,{mode:"hybrid",limit:s,section:o}):Wg(n,i,{limit:s,section:o}),f=c?"hybrid":"keyword";if(r.json){console.log(JSON.stringify({query:i,mode:f,resultCount:u.length,results:u.map((d,p)=>({rank:p+1,score:Math.round(d.score*1e4)/1e4,title:d.article.title,section:d.article.section,sourceUrl:d.article.sourceUrl,snippet:d.article.snippet,questions:d.article.questions,matchedTerms:d.matchedTerms}))},null,2));return}if(u.length===0){console.log(`No results for "${i}".`);return}console.log(""),console.log(N(` ${u.length} result${u.length!==1?"s":""} for "${i}"`)),console.log("");for(let d=0;d<u.length;d++){let p=u[d];console.log(Se(` ${d+1}. ${p.article.title}`)+H(` (${p.section.name})`)),p.article.snippet&&console.log(H(` ${p.article.snippet.slice(0,120)}${p.article.snippet.length>120?"...":""}`)),p.article.sourceUrl&&console.log(H(` ${p.article.sourceUrl}`)),console.log("")}}catch(n){console.error(se(`Error: ${n instanceof Error?n.message:String(n)}`)),process.exit(1)}})}function Ttt(e){e.command("context").description("Generate agent context (not available in bundled CLI)").action(()=>{console.error("clio context is not available in the bundled CLI."),process.exit(1)})}import Zit from"node:process";var Nrn=Object.freeze({status:"aborted"});function ge(e,t,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(e),t(a,c);for(let f in o.prototype)f in a||Object.defineProperty(a,f,{value:o.prototype[f].bind(a)});a._zod.constr=o,a._zod.def=c}let i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function o(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let f of u._zod.deferred)f();return u}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var nd=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},KY={};function Nc(e){return e&&Object.assign(KY,e),KY}var kr={};qc(kr,{BIGINT_FORMAT_RANGES:()=>Ntt,Class:()=>jce,NUMBER_FORMAT_RANGES:()=>Zce,aborted:()=>ny,allowsEval:()=>Vce,assert:()=>uyr,assertEqual:()=>syr,assertIs:()=>ayr,assertNever:()=>cyr,assertNotEqual:()=>oyr,assignProp:()=>Gce,cached:()=>yx,captureStackTrace:()=>e8,cleanEnum:()=>vyr,cleanRegex:()=>bx,clone:()=>Ul,createTransparentProxy:()=>Ayr,defineLazy:()=>gn,esc:()=>ry,escapeRegex:()=>Mh,extend:()=>yyr,finalizeIssue:()=>Nu,floatSafeRemainder:()=>Hce,getElementAtPath:()=>lyr,getEnumValues:()=>Yce,getLengthableOrigin:()=>Cx,getParsedType:()=>hyr,getSizableOrigin:()=>Ftt,isObject:()=>cv,isPlainObject:()=>uv,issue:()=>Kce,joinValues:()=>XY,jsonStringifyReplacer:()=>zce,merge:()=>Eyr,normalizeParams:()=>bt,nullish:()=>Ex,numKeys:()=>pyr,omit:()=>gyr,optionalKeys:()=>Wce,partial:()=>byr,pick:()=>myr,prefixIssues:()=>ql,primitiveTypes:()=>ktt,promiseAllObject:()=>fyr,propertyKeyTypes:()=>Jce,randomString:()=>dyr,required:()=>Cyr,stringifyPrimitive:()=>t8,unwrapMessage:()=>gx});function syr(e){return e}function oyr(e){return e}function ayr(e){}function cyr(e){throw new Error}function uyr(e){}function Yce(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function XY(e,t="|"){return e.map(r=>t8(r)).join(t)}function zce(e,t){return typeof t=="bigint"?t.toString():t}function yx(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ex(e){return e==null}function bx(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Hce(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}function gn(e,t,r){Object.defineProperty(e,t,{get(){{let i=r();return e[t]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Gce(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function lyr(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function fyr(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let i={};for(let s=0;s<t.length;s++)i[t[s]]=n[s];return i})}function dyr(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function ry(e){return JSON.stringify(e)}var e8=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function cv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Vce=yx(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function uv(e){if(cv(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(cv(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function pyr(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var hyr=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Jce=new Set(["string","number","symbol"]),ktt=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Mh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ul(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function bt(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Ayr(e){let t;return new Proxy({},{get(r,n,i){return t??(t=e()),Reflect.get(t,n,i)},set(r,n,i,s){return t??(t=e()),Reflect.set(t,n,i,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,i){return t??(t=e()),Reflect.defineProperty(t,n,i)}})}function t8(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Wce(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Zce={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ntt={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function myr(e,t){let r={},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return Ul(e,{...e._zod.def,shape:r,checks:[]})}function gyr(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return Ul(e,{...e._zod.def,shape:r,checks:[]})}function yyr(e,t){if(!uv(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Gce(this,"shape",n),n},checks:[]};return Ul(e,r)}function Eyr(e,t){return Ul(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Gce(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function byr(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)i[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return Ul(t,{...t._zod.def,shape:i,checks:[]})}function Cyr(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(let s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return Ul(t,{...t._zod.def,shape:i,checks:[]})}function ny(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ql(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function gx(e){return typeof e=="string"?e:e?.message}function Nu(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let i=gx(e.inst?._zod.def?.error?.(e))??gx(t?.error?.(e))??gx(r.customError?.(e))??gx(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Ftt(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Cx(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Kce(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function vyr(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var jce=class{constructor(...t){}};var Ott=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,zce,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},r8=ge("$ZodError",Ott),Xce=ge("$ZodError",Ott,{Parent:Error});function Qtt(e,t=r=>r.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function Ltt(e,t){let r=t||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>i({issues:a}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(o))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(e),n}var Mtt=e=>(t,r,n,i)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new nd;if(o.issues.length){let a=new(i?.Err??e)(o.issues.map(c=>Nu(c,s,Nc())));throw e8(a,i?.callee),a}return o.value};var Ptt=e=>async(t,r,n,i)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){let a=new(i?.Err??e)(o.issues.map(c=>Nu(c,s,Nc())));throw e8(a,i?.callee),a}return o.value};var eue=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new nd;return s.issues.length?{success:!1,error:new(e??r8)(s.issues.map(o=>Nu(o,i,Nc())))}:{success:!0,data:s.value}},vx=eue(Xce),tue=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(o=>Nu(o,i,Nc())))}:{success:!0,data:s.value}},n8=tue(Xce);var $tt=/^[cC][^\s-]{8,}$/,Utt=/^[0-9a-z]+$/,qtt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,jtt=/^[0-9a-vA-V]{20}$/,Ytt=/^[A-Za-z0-9]{27}$/,ztt=/^[a-zA-Z0-9_-]{21}$/,Htt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Gtt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,rue=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var Vtt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Iyr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Jtt(){return new RegExp(Iyr,"u")}var Wtt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ztt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Ktt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Xtt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ert=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,nue=/^[A-Za-z0-9_-]*$/,trt=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var rrt=/^\+(?:[0-9]){6,14}[0-9]$/,nrt="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",irt=new RegExp(`^${nrt}$`);function srt(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ort(e){return new RegExp(`^${srt(e)}$`)}function art(e){let t=srt({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${nrt}T(?:${n})$`)}var crt=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var urt=/^\d+$/,lrt=/^-?\d+(?:\.\d+)?/i,frt=/true|false/i,drt=/null/i;var prt=/^[^A-Z]*$/,hrt=/^[^a-z]*$/;var eo=ge("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Art={number:"number",bigint:"bigint",object:"date"},sue=ge("$ZodCheckLessThan",(e,t)=>{eo.init(e,t);let r=Art[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),oue=ge("$ZodCheckGreaterThan",(e,t)=>{eo.init(e,t);let r=Art[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),mrt=ge("$ZodCheckMultipleOf",(e,t)=>{eo.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Hce(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),grt=ge("$ZodCheckNumberFormat",(e,t)=>{eo.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,s]=Zce[t.format];e._zod.onattach.push(o=>{let a=o._zod.bag;a.format=t.format,a.minimum=i,a.maximum=s,r&&(a.pattern=urt)}),e._zod.check=o=>{let a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}});var yrt=ge("$ZodCheckMaxLength",(e,t)=>{var r;eo.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Ex(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;if(i.length<=t.maximum)return;let o=Cx(i);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ert=ge("$ZodCheckMinLength",(e,t)=>{var r;eo.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Ex(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;if(i.length>=t.minimum)return;let o=Cx(i);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),brt=ge("$ZodCheckLengthEquals",(e,t)=>{var r;eo.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Ex(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{let i=n.value,s=i.length;if(s===t.length)return;let o=Cx(i),a=s>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),wx=ge("$ZodCheckStringFormat",(e,t)=>{var r,n;eo.init(e,t),e._zod.onattach.push(i=>{let s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Crt=ge("$ZodCheckRegex",(e,t)=>{wx.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),vrt=ge("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=prt),wx.init(e,t)}),wrt=ge("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=hrt),wx.init(e,t)}),Irt=ge("$ZodCheckIncludes",(e,t)=>{eo.init(e,t);let r=Mh(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(i=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),_rt=ge("$ZodCheckStartsWith",(e,t)=>{eo.init(e,t);let r=new RegExp(`^${Mh(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Drt=ge("$ZodCheckEndsWith",(e,t)=>{eo.init(e,t);let r=new RegExp(`.*${Mh(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Srt=ge("$ZodCheckOverwrite",(e,t)=>{eo.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var i8=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
1128
+ Strings are replaced with values relative to the transaction date.`);t.command("list-invoices").description("List scheduled invoices").option("--limit <n>","Max results (default 100)",we).option("--offset <n>","Page number offset (0-indexed)",it).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",we).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(j(async(r,n)=>{let i=await Ke(n,s=>nj(r,s),{label:"Fetching scheduled invoices"});Je(i,Uce,n,"Scheduled Invoices")})),t.command("list-bills").description("List scheduled bills").option("--limit <n>","Max results (default 100)",we).option("--offset <n>","Page number offset (0-indexed)",it).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",we).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(j(async(r,n)=>{let i=await Ke(n,s=>ij(r,s),{label:"Fetching scheduled bills"});Je(i,Uce,n,"Scheduled Bills")})),t.command("list-journals").description("List scheduled journals").option("--limit <n>","Max results (default 100)",we).option("--offset <n>","Page number offset (0-indexed)",it).option("--all","Fetch all pages").option("--max-rows <n>","Max rows for --all (default 1000)",we).option("--api-key <key>","API key (overrides stored/env)").option("--format <type>","Output format: table, json, csv, yaml").option("--json","Output as JSON").action(j(async(r,n)=>{let i=await Ke(n,s=>sj(r,s),{label:"Fetching scheduled journals"});Je(i,Uce,n,"Scheduled Journals")})),t.command("create-invoice").description("Create a scheduled (recurring) invoice").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date (optional)").option("--repeat <interval>","Recurrence: ONE_TIME, DAILY, WEEKLY, MONTHLY, YEARLY").option("--contact <resourceId>","Customer contact resourceId").option("--reference <ref>","Invoice reference").option("--value-date <YYYY-MM-DD>","Template issue date").option("--due-date <YYYY-MM-DD>","Template due date").option("--line-items <json>","Line items as JSON string").option("--tag <name>","Tag name").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(j(async(r,n)=>{let i=Ce(n),s;if(i)s=await qD(r,i);else{Xe(n,[{flag:"--start-date",key:"startDate"},{flag:"--repeat",key:"repeat"},{flag:"--contact",key:"contact"},{flag:"--reference",key:"reference"},{flag:"--value-date",key:"valueDate"},{flag:"--due-date",key:"dueDate"},{flag:"--line-items",key:"lineItems"}]);let o=$n(n.lineItems);s=await qD(r,{status:"ACTIVE",startDate:n.startDate,endDate:n.endDate,repeat:n.repeat,invoice:{reference:n.reference,valueDate:n.valueDate,dueDate:n.dueDate,contactResourceId:n.contact,lineItems:o,tags:n.tag?[n.tag]:void 0,saveAsDraft:!1}})}n.json?console.log(JSON.stringify(s.data,null,2)):console.log(V("Scheduled invoice created"))})),t.command("create-bill").description("Create a scheduled (recurring) bill").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date (optional)").option("--repeat <interval>","Recurrence: ONE_TIME, DAILY, WEEKLY, MONTHLY, YEARLY").option("--contact <resourceId>","Supplier contact resourceId").option("--reference <ref>","Bill reference").option("--value-date <YYYY-MM-DD>","Template issue date").option("--due-date <YYYY-MM-DD>","Template due date").option("--line-items <json>","Line items as JSON string").option("--tag <name>","Tag name").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(j(async(r,n)=>{let i=Ce(n),s;if(i)s=await ZI(r,i);else{Xe(n,[{flag:"--start-date",key:"startDate"},{flag:"--repeat",key:"repeat"},{flag:"--contact",key:"contact"},{flag:"--reference",key:"reference"},{flag:"--value-date",key:"valueDate"},{flag:"--due-date",key:"dueDate"},{flag:"--line-items",key:"lineItems"}]);let o=$n(n.lineItems);s=await ZI(r,{status:"ACTIVE",startDate:n.startDate,endDate:n.endDate,repeat:n.repeat,bill:{reference:n.reference,valueDate:n.valueDate,dueDate:n.dueDate,contactResourceId:n.contact,lineItems:o,tags:n.tag?[n.tag]:void 0,saveAsDraft:!1}})}n.json?console.log(JSON.stringify(s.data,null,2)):console.log(V("Scheduled bill created"))})),t.command("create-journal").description("Create a scheduled (recurring) journal").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date (optional)").option("--repeat <interval>","Recurrence: ONE_TIME, DAILY, WEEKLY, MONTHLY, YEARLY").option("--reference <ref>","Journal reference").option("--value-date <YYYY-MM-DD>","Template date").option("--entries <json>","Scheduler entries as JSON string").option("--notes <text>","Journal notes").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(j(async(r,n)=>{let i=Ce(n),s;if(i)s=await JD(r,i);else{Xe(n,[{flag:"--start-date",key:"startDate"},{flag:"--repeat",key:"repeat"},{flag:"--value-date",key:"valueDate"},{flag:"--entries",key:"entries"}]);let o=cc(n.entries);s=await JD(r,{status:"ACTIVE",startDate:n.startDate,endDate:n.endDate,repeat:n.repeat,valueDate:n.valueDate,schedulerEntries:o,reference:n.reference,internalNotes:n.notes})}n.json?console.log(JSON.stringify(s.data,null,2)):console.log(V("Scheduled journal created"))})),t.command("get-invoice <resourceId>").description("Get a scheduled invoice by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=await oj(i,r);if(n.json)console.log(JSON.stringify(s.data,null,2));else{let o=s.data;console.log(N("ID:"),o.resourceId),console.log(N("Status:"),o.status),console.log(N("Repeat:"),o.interval??o.repeat),console.log(N("Start:"),o.startDate),o.endDate&&console.log(N("End:"),o.endDate)}})(n)),t.command("update-invoice <resourceId>").description("Update a scheduled invoice").option("--repeat <interval>","Recurrence: ONE_TIME, DAILY, WEEKLY, MONTHLY, YEARLY").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date").option("--status <status>","Status: ACTIVE or PAUSED").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=Ce(n),o=s??{};s||(n.repeat&&(o.repeat=n.repeat),n.startDate&&(o.startDate=n.startDate),n.endDate&&(o.endDate=n.endDate),n.status&&(o.status=n.status));let a=await aj(i,r,o);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(V(`Scheduled invoice ${r} updated.`))})(n)),t.command("delete-invoice <resourceId>").description("Delete a scheduled invoice").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{await cj(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(V(`Scheduled invoice ${r} deleted.`))})(n)),t.command("get-bill <resourceId>").description("Get a scheduled bill by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=await uj(i,r);if(n.json)console.log(JSON.stringify(s.data,null,2));else{let o=s.data;console.log(N("ID:"),o.resourceId),console.log(N("Status:"),o.status),console.log(N("Repeat:"),o.interval??o.repeat),console.log(N("Start:"),o.startDate),o.endDate&&console.log(N("End:"),o.endDate)}})(n)),t.command("update-bill <resourceId>").description("Update a scheduled bill").option("--repeat <interval>","Recurrence: ONE_TIME, DAILY, WEEKLY, MONTHLY, YEARLY").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date").option("--status <status>","Status: ACTIVE or PAUSED").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=Ce(n),o=s??{};s||(n.repeat&&(o.repeat=n.repeat),n.startDate&&(o.startDate=n.startDate),n.endDate&&(o.endDate=n.endDate),n.status&&(o.status=n.status));let a=await lj(i,r,o);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(V(`Scheduled bill ${r} updated.`))})(n)),t.command("delete-bill <resourceId>").description("Delete a scheduled bill").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{await fj(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(V(`Scheduled bill ${r} deleted.`))})(n)),t.command("get-journal <resourceId>").description("Get a scheduled journal by resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=await dj(i,r);if(n.json)console.log(JSON.stringify(s.data,null,2));else{let o=s.data;console.log(N("ID:"),o.resourceId),console.log(N("Status:"),o.status),console.log(N("Repeat:"),o.interval??o.repeat),console.log(N("Start:"),o.startDate),o.endDate&&console.log(N("End:"),o.endDate)}})(n)),t.command("update-journal <resourceId>").description("Update a scheduled journal").option("--repeat <interval>","Recurrence: ONE_TIME, DAILY, WEEKLY, MONTHLY, YEARLY").option("--start-date <YYYY-MM-DD>","First occurrence date").option("--end-date <YYYY-MM-DD>","Last occurrence date").option("--status <status>","Status: ACTIVE or PAUSED").option("--input <file>","Read full request body from JSON file (or pipe via stdin)").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{let s=Ce(n),o=s??{};s||(n.repeat&&(o.repeat=n.repeat),n.startDate&&(o.startDate=n.startDate),n.endDate&&(o.endDate=n.endDate),n.status&&(o.status=n.status));let a=await pj(i,r,o);n.json?console.log(JSON.stringify(a.data,null,2)):console.log(V(`Scheduled journal ${r} updated.`))})(n)),t.command("delete-journal <resourceId>").description("Delete a scheduled journal").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action((r,n)=>j(async i=>{await hj(i,r),n.json?console.log(JSON.stringify({deleted:!0,resourceId:r})):console.log(V(`Scheduled journal ${r} deleted.`))})(n))}Le();ace();Tt();qt();function Rtt(e){e.command("exports").description("Manage data exports").command("download").description("Download a data export report").option("--type <exportType>","Export type (e.g., trial-balance, balance-sheet, profit-and-loss, general-ledger, sales-summary, etc.)").option("--format <XLSX|PDF>","Output format. Defaults to XLSX. PDF only for: balance-sheet, profit-and-loss, trial-balance, cashflow.").option("--start-date <YYYY-MM-DD>","Period start date").option("--end-date <YYYY-MM-DD>","Period end date").option("--currency <code>","Currency code override").option("--tags <csv>","Comma-separated tag names").option("--contact <resourceId>","Filter by contact resourceId").option("--api-key <key>","API key (overrides stored/env)").option("--json","Output as JSON").action(j(async(r,n)=>{Xe(n,[{flag:"--type",key:"type"}]);let i=n.type,s={};if(n.format){let a=n.format.toUpperCase();if(a!=="XLSX"&&a!=="PDF")throw new Error(`Invalid --format: ${n.format}. Allowed: XLSX, PDF.`);s.outputFormat=a}n.startDate&&(s.startDate=n.startDate),n.endDate&&(["balance-sheet"].includes(i)?s.snapshotDate=n.endDate:s.endDate=n.endDate),n.currency&&(s.currencyCode=n.currency),n.tags&&(s.tags=n.tags.split(",").map(a=>a.trim())),n.contact&&(s.contactResourceId=n.contact);let o=await Tj(r,i,s);if(n.json)console.log(JSON.stringify(o.data,null,2));else{let a=o.data;console.log(V("Export ready")),a.fileName&&console.log(N("File:"),a.fileName),a.fileUrl&&console.log(N("URL:"),a.fileUrl)}}))}Kae();Zae();Le();function xtt(e){e.command("help-center").alias("hc").description("Search the Jaz help center").argument("<query...>",'Search query (e.g. "bank recon", "how to apply credit")').option("--limit <n>","Max results (default 5)",parseInt).option("--section <slug>","Filter by section (e.g. invoices, bills, settings)").option("--json","Output as JSON").action(async(t,r)=>{try{let n=JR(),i=t.join(" "),s=r.limit??5,o=r.section,a=WR(),c=Wae(a),u=c?await ZR(n,a,i,{mode:"hybrid",limit:s,section:o}):Wg(n,i,{limit:s,section:o}),f=c?"hybrid":"keyword";if(r.json){console.log(JSON.stringify({query:i,mode:f,resultCount:u.length,results:u.map((d,p)=>({rank:p+1,score:Math.round(d.score*1e4)/1e4,title:d.article.title,section:d.article.section,sourceUrl:d.article.sourceUrl,snippet:d.article.snippet,questions:d.article.questions,matchedTerms:d.matchedTerms}))},null,2));return}if(u.length===0){console.log(`No results for "${i}".`);return}console.log(""),console.log(N(` ${u.length} result${u.length!==1?"s":""} for "${i}"`)),console.log("");for(let d=0;d<u.length;d++){let p=u[d];console.log(Se(` ${d+1}. ${p.article.title}`)+H(` (${p.section.name})`)),p.article.snippet&&console.log(H(` ${p.article.snippet.slice(0,120)}${p.article.snippet.length>120?"...":""}`)),p.article.sourceUrl&&console.log(H(` ${p.article.sourceUrl}`)),console.log("")}}catch(n){console.error(se(`Error: ${n instanceof Error?n.message:String(n)}`)),process.exit(1)}})}function Ttt(e){e.command("context").description("Generate agent context (not available in bundled CLI)").action(()=>{console.error("clio context is not available in the bundled CLI."),process.exit(1)})}import Zit from"node:process";var Nrn=Object.freeze({status:"aborted"});function ge(e,t,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(e),t(a,c);for(let f in o.prototype)f in a||Object.defineProperty(a,f,{value:o.prototype[f].bind(a)});a._zod.constr=o,a._zod.def=c}let i=r?.Parent??Object;class s extends i{}Object.defineProperty(s,"name",{value:e});function o(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let f of u._zod.deferred)f();return u}return Object.defineProperty(o,"init",{value:n}),Object.defineProperty(o,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var nd=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},KY={};function Nc(e){return e&&Object.assign(KY,e),KY}var kr={};qc(kr,{BIGINT_FORMAT_RANGES:()=>Ntt,Class:()=>jce,NUMBER_FORMAT_RANGES:()=>Zce,aborted:()=>ny,allowsEval:()=>Vce,assert:()=>uyr,assertEqual:()=>syr,assertIs:()=>ayr,assertNever:()=>cyr,assertNotEqual:()=>oyr,assignProp:()=>Gce,cached:()=>yx,captureStackTrace:()=>e8,cleanEnum:()=>vyr,cleanRegex:()=>bx,clone:()=>Ul,createTransparentProxy:()=>Ayr,defineLazy:()=>gn,esc:()=>ry,escapeRegex:()=>Mh,extend:()=>yyr,finalizeIssue:()=>Nu,floatSafeRemainder:()=>Hce,getElementAtPath:()=>lyr,getEnumValues:()=>Yce,getLengthableOrigin:()=>Cx,getParsedType:()=>hyr,getSizableOrigin:()=>Ftt,isObject:()=>cv,isPlainObject:()=>uv,issue:()=>Kce,joinValues:()=>XY,jsonStringifyReplacer:()=>zce,merge:()=>Eyr,normalizeParams:()=>bt,nullish:()=>Ex,numKeys:()=>pyr,omit:()=>gyr,optionalKeys:()=>Wce,partial:()=>byr,pick:()=>myr,prefixIssues:()=>ql,primitiveTypes:()=>ktt,promiseAllObject:()=>fyr,propertyKeyTypes:()=>Jce,randomString:()=>dyr,required:()=>Cyr,stringifyPrimitive:()=>t8,unwrapMessage:()=>gx});function syr(e){return e}function oyr(e){return e}function ayr(e){}function cyr(e){throw new Error}function uyr(e){}function Yce(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,i])=>t.indexOf(+n)===-1).map(([n,i])=>i)}function XY(e,t="|"){return e.map(r=>t8(r)).join(t)}function zce(e,t){return typeof t=="bigint"?t.toString():t}function yx(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ex(e){return e==null}function bx(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Hce(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}function gn(e,t,r){Object.defineProperty(e,t,{get(){{let i=r();return e[t]=i,i}throw new Error("cached value already set")},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function Gce(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function lyr(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function fyr(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let i={};for(let s=0;s<t.length;s++)i[t[s]]=n[s];return i})}function dyr(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function ry(e){return JSON.stringify(e)}var e8=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function cv(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Vce=yx(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function uv(e){if(cv(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(cv(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function pyr(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var hyr=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},Jce=new Set(["string","number","symbol"]),ktt=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Mh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ul(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function bt(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Ayr(e){let t;return new Proxy({},{get(r,n,i){return t??(t=e()),Reflect.get(t,n,i)},set(r,n,i,s){return t??(t=e()),Reflect.set(t,n,i,s)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,i){return t??(t=e()),Reflect.defineProperty(t,n,i)}})}function t8(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Wce(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Zce={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ntt={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function myr(e,t){let r={},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return Ul(e,{...e._zod.def,shape:r,checks:[]})}function gyr(e,t){let r={...e._zod.def.shape},n=e._zod.def;for(let i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return Ul(e,{...e._zod.def,shape:r,checks:[]})}function yyr(e,t){if(!uv(t))throw new Error("Invalid input to extend: expected a plain object");let r={...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return Gce(this,"shape",n),n},checks:[]};return Ul(e,r)}function Eyr(e,t){return Ul(e,{...e._zod.def,get shape(){let r={...e._zod.def.shape,...t._zod.def.shape};return Gce(this,"shape",r),r},catchall:t._zod.def.catchall,checks:[]})}function byr(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=e?new e({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)i[s]=e?new e({type:"optional",innerType:n[s]}):n[s];return Ul(t,{...t._zod.def,shape:i,checks:[]})}function Cyr(e,t,r){let n=t._zod.def.shape,i={...n};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:n[s]}))}else for(let s in n)i[s]=new e({type:"nonoptional",innerType:n[s]});return Ul(t,{...t._zod.def,shape:i,checks:[]})}function ny(e,t=0){for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ql(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function gx(e){return typeof e=="string"?e:e?.message}function Nu(e,t,r){let n={...e,path:e.path??[]};if(!e.message){let i=gx(e.inst?._zod.def?.error?.(e))??gx(t?.error?.(e))??gx(r.customError?.(e))??gx(r.localeError?.(e))??"Invalid input";n.message=i}return delete n.inst,delete n.continue,t?.reportInput||delete n.input,n}function Ftt(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function Cx(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Kce(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function vyr(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}var jce=class{constructor(...t){}};var Ott=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,zce,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},r8=ge("$ZodError",Ott),Xce=ge("$ZodError",Ott,{Parent:Error});function Qtt(e,t=r=>r.message){let r={},n=[];for(let i of e.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(t(i))):n.push(t(i));return{formErrors:n,fieldErrors:r}}function Ltt(e,t){let r=t||function(s){return s.message},n={_errors:[]},i=s=>{for(let o of s.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>i({issues:a}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)n._errors.push(r(o));else{let a=n,c=0;for(;c<o.path.length;){let u=o.path[c];c===o.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(o))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(e),n}var Mtt=e=>(t,r,n,i)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise)throw new nd;if(o.issues.length){let a=new(i?.Err??e)(o.issues.map(c=>Nu(c,s,Nc())));throw e8(a,i?.callee),a}return o.value};var Ptt=e=>async(t,r,n,i)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},o=t._zod.run({value:r,issues:[]},s);if(o instanceof Promise&&(o=await o),o.issues.length){let a=new(i?.Err??e)(o.issues.map(c=>Nu(c,s,Nc())));throw e8(a,i?.callee),a}return o.value};var eue=e=>(t,r,n)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new nd;return s.issues.length?{success:!1,error:new(e??r8)(s.issues.map(o=>Nu(o,i,Nc())))}:{success:!0,data:s.value}},vx=eue(Xce),tue=e=>async(t,r,n)=>{let i=n?Object.assign(n,{async:!0}):{async:!0},s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(o=>Nu(o,i,Nc())))}:{success:!0,data:s.value}},n8=tue(Xce);var $tt=/^[cC][^\s-]{8,}$/,Utt=/^[0-9a-z]+$/,qtt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,jtt=/^[0-9a-vA-V]{20}$/,Ytt=/^[A-Za-z0-9]{27}$/,ztt=/^[a-zA-Z0-9_-]{21}$/,Htt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Gtt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,rue=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var Vtt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Iyr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Jtt(){return new RegExp(Iyr,"u")}var Wtt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ztt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Ktt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Xtt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ert=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,nue=/^[A-Za-z0-9_-]*$/,trt=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var rrt=/^\+(?:[0-9]){6,14}[0-9]$/,nrt="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",irt=new RegExp(`^${nrt}$`);function srt(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function ort(e){return new RegExp(`^${srt(e)}$`)}function art(e){let t=srt({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${nrt}T(?:${n})$`)}var crt=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var urt=/^\d+$/,lrt=/^-?\d+(?:\.\d+)?/i,frt=/true|false/i,drt=/null/i;var prt=/^[^A-Z]*$/,hrt=/^[^a-z]*$/;var eo=ge("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Art={number:"number",bigint:"bigint",object:"date"},sue=ge("$ZodCheckLessThan",(e,t)=>{eo.init(e,t);let r=Art[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,s=(t.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?i.maximum=t.value:i.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),oue=ge("$ZodCheckGreaterThan",(e,t)=>{eo.init(e,t);let r=Art[typeof t.value];e._zod.onattach.push(n=>{let i=n._zod.bag,s=(t.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?i.minimum=t.value:i.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),mrt=ge("$ZodCheckMultipleOf",(e,t)=>{eo.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):Hce(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),grt=ge("$ZodCheckNumberFormat",(e,t)=>{eo.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[i,s]=Zce[t.format];e._zod.onattach.push(o=>{let a=o._zod.bag;a.format=t.format,a.minimum=i,a.maximum=s,r&&(a.pattern=urt)}),e._zod.check=o=>{let a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:t.format,code:"invalid_type",input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,continue:!t.abort});return}}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:e})}});var yrt=ge("$ZodCheckMaxLength",(e,t)=>{var r;eo.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Ex(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<i&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let i=n.value;if(i.length<=t.maximum)return;let o=Cx(i);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),Ert=ge("$ZodCheckMinLength",(e,t)=>{var r;eo.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Ex(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>i&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let i=n.value;if(i.length>=t.minimum)return;let o=Cx(i);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),brt=ge("$ZodCheckLengthEquals",(e,t)=>{var r;eo.init(e,t),(r=e._zod.def).when??(r.when=n=>{let i=n.value;return!Ex(i)&&i.length!==void 0}),e._zod.onattach.push(n=>{let i=n._zod.bag;i.minimum=t.length,i.maximum=t.length,i.length=t.length}),e._zod.check=n=>{let i=n.value,s=i.length;if(s===t.length)return;let o=Cx(i),a=s>t.length;n.issues.push({origin:o,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),wx=ge("$ZodCheckStringFormat",(e,t)=>{var r,n;eo.init(e,t),e._zod.onattach.push(i=>{let s=i._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Crt=ge("$ZodCheckRegex",(e,t)=>{wx.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),vrt=ge("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=prt),wx.init(e,t)}),wrt=ge("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=hrt),wx.init(e,t)}),Irt=ge("$ZodCheckIncludes",(e,t)=>{eo.init(e,t);let r=Mh(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(i=>{let s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),e._zod.check=i=>{i.value.includes(t.includes,t.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:i.value,inst:e,continue:!t.abort})}}),_rt=ge("$ZodCheckStartsWith",(e,t)=>{eo.init(e,t);let r=new RegExp(`^${Mh(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Drt=ge("$ZodCheckEndsWith",(e,t)=>{eo.init(e,t);let r=new RegExp(`.*${Mh(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let i=n._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Srt=ge("$ZodCheckOverwrite",(e,t)=>{eo.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var i8=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
1129
1129
  `).filter(o=>o),i=Math.min(...n.map(o=>o.length-o.trimStart().length)),s=n.map(o=>o.slice(i)).map(o=>" ".repeat(this.indent*2)+o);for(let o of s)this.content.push(o)}compile(){let t=Function,r=this?.args,i=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...r,i.join(`
1130
1130
  `))}};var Rrt={major:4,minor:0,patch:0};var yn=ge("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Rrt;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let i of n)for(let s of i._zod.onattach)s(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(s,o,a)=>{let c=ny(s),u;for(let f of o){if(f._zod.def.when){if(!f._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=f._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new nd;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=ny(s,d)))});else{if(s.issues.length===d)continue;c||(c=ny(s,d))}}return u?u.then(()=>s):s};e._zod.run=(s,o)=>{let a=e._zod.parse(s,o);if(a instanceof Promise){if(o.async===!1)throw new nd;return a.then(c=>i(c,n,o))}return i(a,n,o)}}e["~standard"]={validate:i=>{try{let s=vx(e,i);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return n8(e,i).then(o=>o.success?{value:o.data}:{issues:o.error?.issues})}},vendor:"zod",version:1}}),o8=ge("$ZodString",(e,t)=>{yn.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??crt(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),Sn=ge("$ZodStringFormat",(e,t)=>{wx.init(e,t),o8.init(e,t)}),Prt=ge("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Gtt),Sn.init(e,t)}),$rt=ge("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=rue(n))}else t.pattern??(t.pattern=rue());Sn.init(e,t)}),Urt=ge("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Vtt),Sn.init(e,t)}),qrt=ge("$ZodURL",(e,t)=>{Sn.init(e,t),e._zod.check=r=>{try{let n=r.value,i=new URL(n),s=i.href;t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:trt.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),jrt=ge("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Jtt()),Sn.init(e,t)}),Yrt=ge("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ztt),Sn.init(e,t)}),zrt=ge("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=$tt),Sn.init(e,t)}),Hrt=ge("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Utt),Sn.init(e,t)}),Grt=ge("$ZodULID",(e,t)=>{t.pattern??(t.pattern=qtt),Sn.init(e,t)}),Vrt=ge("$ZodXID",(e,t)=>{t.pattern??(t.pattern=jtt),Sn.init(e,t)}),Jrt=ge("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Ytt),Sn.init(e,t)}),Wrt=ge("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=art(t)),Sn.init(e,t)}),Zrt=ge("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=irt),Sn.init(e,t)}),Krt=ge("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=ort(t)),Sn.init(e,t)}),Xrt=ge("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Htt),Sn.init(e,t)}),ent=ge("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Wtt),Sn.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),tnt=ge("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Ztt),Sn.init(e,t),e._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),rnt=ge("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ktt),Sn.init(e,t)}),nnt=ge("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Xtt),Sn.init(e,t),e._zod.check=r=>{let[n,i]=r.value.split("/");try{if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});function int(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var snt=ge("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ert),Sn.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),e._zod.check=r=>{int(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});function _yr(e){if(!nue.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return int(r)}var ont=ge("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=nue),Sn.init(e,t),e._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),e._zod.check=r=>{_yr(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),ant=ge("$ZodE164",(e,t)=>{t.pattern??(t.pattern=rrt),Sn.init(e,t)});function Dyr(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var cnt=ge("$ZodJWT",(e,t)=>{Sn.init(e,t),e._zod.check=r=>{Dyr(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var cue=ge("$ZodNumber",(e,t)=>{yn.init(e,t),e._zod.pattern=e._zod.bag.pattern??lrt,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;let s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}}),unt=ge("$ZodNumber",(e,t)=>{grt.init(e,t),cue.init(e,t)}),lnt=ge("$ZodBoolean",(e,t)=>{yn.init(e,t),e._zod.pattern=frt,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}});var fnt=ge("$ZodNull",(e,t)=>{yn.init(e,t),e._zod.pattern=drt,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}});var dnt=ge("$ZodUnknown",(e,t)=>{yn.init(e,t),e._zod.parse=r=>r}),pnt=ge("$ZodNever",(e,t)=>{yn.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function xrt(e,t,r){e.issues.length&&t.issues.push(...ql(r,e.issues)),t.value[r]=e.value}var hnt=ge("$ZodArray",(e,t)=>{yn.init(e,t),e._zod.parse=(r,n)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=Array(i.length);let s=[];for(let o=0;o<i.length;o++){let a=i[o],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>xrt(u,r,o))):xrt(c,r,o)}return s.length?Promise.all(s).then(()=>r):r}});function s8(e,t,r){e.issues.length&&t.issues.push(...ql(r,e.issues)),t.value[r]=e.value}function Trt(e,t,r,n){e.issues.length?n[r]===void 0?r in n?t.value[r]=void 0:t.value[r]=e.value:t.issues.push(...ql(r,e.issues)):e.value===void 0?r in n&&(t.value[r]=void 0):t.value[r]=e.value}var Ant=ge("$ZodObject",(e,t)=>{yn.init(e,t);let r=yx(()=>{let d=Object.keys(t.shape);for(let h of d)if(!(t.shape[h]instanceof yn))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let p=Wce(t.shape);return{shape:t.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});gn(e._zod,"propValues",()=>{let d=t.shape,p={};for(let h in d){let A=d[h]._zod;if(A.values){p[h]??(p[h]=new Set);for(let m of A.values)p[h].add(m)}}return p});let n=d=>{let p=new i8(["shape","payload","ctx"]),h=r.value,A=C=>{let E=ry(C);return`shape[${E}]._zod.run({ value: input[${E}], issues: [] }, ctx)`};p.write("const input = payload.value;");let m=Object.create(null),g=0;for(let C of h.keys)m[C]=`key_${g++}`;p.write("const newResult = {}");for(let C of h.keys)if(h.optionalKeys.has(C)){let E=m[C];p.write(`const ${E} = ${A(C)};`);let v=ry(C);p.write(`
1131
1131
  if (${E}.issues.length) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jaz-clio",
3
- "version": "5.20.6",
3
+ "version": "5.20.8",
4
4
  "description": "Clio: Command Line Interface Operator for Jaz AI.",
5
5
  "type": "module",
6
6
  "bin": {