jaz-clio 5.25.0 → 5.25.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/skills/api/SKILL.md +1 -1
- package/assets/skills/cli/SKILL.md +1 -1
- package/assets/skills/conversion/SKILL.md +1 -1
- package/assets/skills/jaz-pseudo-sql/SKILL.md +1 -1
- package/assets/skills/jobs/SKILL.md +1 -1
- package/assets/skills/transaction-recipes/SKILL.md +1 -1
- package/cli.mjs +2 -2
- package/package.json +1 -1
package/cli.mjs
CHANGED
|
@@ -677,7 +677,7 @@ Unsupported type: `+t.type,"ENOTSUP");t._finish()})};Fc.prototype._stat=function
|
|
|
677
677
|
---
|
|
678
678
|
`,a),u=c!==-1?c:i.length;return i.slice(s,u).trim()}catch{return null}}function bbr(){let t=mrt(import.meta.url),e=hrt(t),r=[jh(e,"..","..","..","help-center-mirror"),jh(e,"..","..","..","assets","skills","api","help-center-mirror"),jh(e,"help-center-mirror")];for(let n of r)try{return rue(jh(n,"index.md"),"utf-8"),n}catch{}return null}var drt,frt,fbr,pbr,hbr,mbr,Abr,gbr,ybr,cH,prt,tue,Lx=X(()=>{"use strict";eue();fb();drt=1.2,frt=.75,fbr=1.5,pbr=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"]),hbr=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"]]]);mbr=.7,Abr=3,gbr=32,ybr=5;cH=null,prt=null;tue=null});import{existsSync as Cbr,readFileSync as vbr}from"node:fs";import{dirname as Ibr,join as iue}from"node:path";import{fileURLToPath as wbr}from"node:url";function Mx(t){let e=t??Bbr();if(!e)return null;if(lH&&brt===e)return lH;try{let r=vbr(e,"utf-8");return lH=JSON.parse(r),brt=e,lH}catch{return null}}function Bbr(){let t=wbr(import.meta.url),e=Ibr(t),r=[iue(e,"..","..","..","help-center-mirror","help-center-embeddings.json"),iue(e,"..","..","..","assets","skills","api","help-center-mirror","help-center-embeddings.json"),iue(e,"help-center-mirror","help-center-embeddings.json")];for(let n of r)if(Cbr(n))return n;return null}function Irt(t,e){let r=Math.min(t.length,e.length),n=0;for(let i=0;i<r;i++)n+=t[i]*e[i];return n}function wrt(){return uH!==null?uH:(uH=process.env.CLIO_HELP_CENTER_OPENAI_API_KEY??"",uH||null)}async function oue(t){let e=wrt();if(!e)return null;try{let r=new AbortController,n=setTimeout(()=>r.abort(),Dbr),i=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({model:_br,input:t}),signal:r.signal});return clearTimeout(n),i.ok?(await i.json()).data?.[0]?.embedding??null:((i.status===401||i.status===403)&&!Crt&&(Crt=!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 Px(t,e,r,n={}){let i=n.mode??"hybrid",o=n.limit??5,s=n.section,a=n.minCosine??Sbr,c=n.minBm25??Rbr;if(i==="bm25"||!e)return ay(t,r,{limit:o,section:s}).filter(A=>A.score>=c);if(i==="semantic"){let m=await oue(r);return m?vrt(t,e,m,{limit:o,section:s}).filter(g=>g.score>=a):ay(t,r,{limit:o,section:s}).filter(y=>y.score>=c)}let[u,d]=await Promise.all([oue(r),Promise.resolve(ay(t,r,{limit:o*2,section:s}))]);if(!u)return d.filter(m=>m.score>=c).slice(0,o);let p=vrt(t,e,u,{limit:o*2,section:s}).filter(m=>m.score>=a),h=d.filter(m=>m.score>=c);return _rt(p,h,o)}function vrt(t,e,r,n){let i=new Map(t.sections.map(c=>[c.slug,c])),o=new Map(t.articles.map(c=>[c.id,c])),s=[];for(let c of e.embeddings){let u=o.get(c.articleId);if(!u||n.section&&u.section!==n.section)continue;let d=Irt(r,c.vector);s.push({articleId:c.articleId,score:d})}s.sort((c,u)=>u.score-c.score);let a=[];for(let{articleId:c,score:u}of s.slice(0,n.limit)){let d=o.get(c);if(!d)continue;let f=i.get(d.section);f&&a.push({article:d,score:u,scoreKind:"cosine",section:f,matchedTerms:[]})}return a}function _rt(t,e,r){let n=new Map;for(let o=0;o<t.length;o++){let s=t[o],a=1/(Ert+o+1),c=n.get(s.article.id);c?c.score+=a:n.set(s.article.id,{score:a,result:s})}for(let o=0;o<e.length;o++){let s=e[o],a=1/(Ert+o+1),c=n.get(s.article.id);c?(c.score+=a,c.result=s):n.set(s.article.id,{score:a,result:s})}let i=Array.from(n.values());return i.sort((o,s)=>s.score-o.score),i.slice(0,r).map(o=>({...o.result,score:o.score,scoreKind:"rrf"}))}function sue(t){return t!==null&&!!wrt()}var _br,Dbr,Ert,Sbr,Rbr,lH,brt,uH,Crt,dH=X(()=>{"use strict";Lx();_br="text-embedding-3-small",Dbr=2e3,Ert=60,Sbr=.3,Rbr=1.5,lH=null,brt=null,uH=null,Crt=!1});async function Drt(t,e={}){let r=String(t??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=typeof e.limit=="number"&&!Number.isNaN(e.limit)?e.limit:3,i=Math.max(1,Math.min(10,Math.floor(n))),o=typeof e.section=="string"?e.section:void 0,s=e.mode??"hybrid";try{let a=Fx();if(o&&!a.sections.some(d=>d.slug===o))return{error:`Unknown section: "${o}".`,code:"unknown_section",available:a.sections.map(d=>d.slug),hint:"Omit the section parameter to search every section, or pick a slug from the available list."};let c=s==="bm25"?null:Mx(),u=await Px(a,c,r,{mode:s,limit:i,section:o});return u.length===0?{results:[],hint:"No matching articles. Try broader keywords or rephrase the question."}:{results:u.map(d=>{let f=(nue(d.article)??d.article.snippet).slice(0,1500);return{title:d.article.title,section:d.section.name,sectionSlug:d.section.slug,content:f,url:d.article.sourceUrl,score:Math.round(d.score*1e3)/1e3,scoreKind:d.scoreKind,matchedTerms:d.matchedTerms}}),totalArticles:a.articleCount,searchedSections:o?[o]:void 0}}catch(a){return{error:"Help center search failed.",code:"load_failure",detail:a instanceof Error?a.message:String(a),hint:"The help center index could not be loaded."}}}function Srt(){let t=process.env.CLIO_HELP_CENTER_URL?.trim();return t&&t.length>0?t:xbr}async function fH(t,e={}){let r=String(t??"").trim();if(!r)return{error:"Query is required.",code:"empty_query",hint:"Pass a natural-language question or keywords."};let n=o=>({error:"Help center is temporarily unavailable.",hint:o}),i;try{i=new URL(Srt())}catch{return n("Set CLIO_HELP_CENTER_URL to a valid URL, or browse https://help.jaz.ai.")}i.searchParams.set("q",r),typeof e.limit=="number"&&Number.isFinite(e.limit)&&i.searchParams.set("limit",String(e.limit)),typeof e.section=="string"&&e.section&&i.searchParams.set("section",e.section);try{let s=await(await fetch(i,{signal:AbortSignal.timeout(Tbr),headers:{accept:"application/json"}})).text(),a;try{a=JSON.parse(s)}catch{return n("Try again shortly, or browse https://help.jaz.ai.")}return kbr(a)?a:n("Try again shortly, or browse https://help.jaz.ai.")}catch{return n("Check your connection, or browse https://help.jaz.ai.")}}function kbr(t){if(typeof t!="object"||t===null)return!1;let e=t;return Array.isArray(e.results)?!0:typeof e.error=="string"}async function aue(t,e={}){return process.env.CLIO_DAEMON==="1"||Qx()?Drt(t,e):fH(t,e)}var xbr,Tbr,Rrt=X(()=>{"use strict";Lx();dH();xbr="https://mcp.jaz.ai/help-center/search",Tbr=4e3});var cue=X(()=>{"use strict";Lx();dH();Rrt();Lx()});var Brt,xrt=X(()=>{"use strict";Brt={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 pH(t,e){let{blueprint:r,accountMap:n,finalize:i}=e,o=!i;Nbr(e);let s=await Obr(t,r.capsuleType),a=r.steps[0]?.date??new Date().toISOString().slice(0,10),c=`${r.capsuleName} (${a})`,d={resourceId:(await RA(t,{capsuleTypeResourceId:s,title:c,description:r.capsuleDescription})).data.resourceId,type:r.capsuleType,title:c},f=Nrt(e),p=[],h=[];for(let A of r.steps){if(A.step===f){p.push({step:A.step,action:A.action,status:"existing",resourceId:e.existingTxnId,description:A.description});continue}if(A.action==="fixed-asset"||A.action==="note"){p.push({step:A.step,action:A.action,status:"skipped",description:A.description}),h.push(`Step ${A.step} (${A.action}): ${A.description}`);continue}let g=await Fbr(t,A,e,o);p.push(g),g.error&&h.push(`Step ${A.step} failed: ${g.error}`)}let m={total:p.length,created:p.filter(A=>A.status==="created").length,existing:p.filter(A=>A.status==="existing").length,skipped:p.filter(A=>A.status==="skipped").length,errors:p.filter(A=>A.status==="error").length,notes:h};return{recipe:e.calcType,capsule:d,steps:p,summary:m}}function Nbr(t){let{blueprint:e,accountMap:r,bankAccountId:n,contactId:i}=t;if(!e.steps.length)throw new Error("Blueprint has no steps to execute.");let o=[];for(let d of e.steps)for(let f of d.lines)uue(f.account,r)||o.push(f.account);let s=[...new Set(o)];if(s.length>0)throw new Error(`Unmapped account(s) in --input: ${s.join(", ")}.
|
|
680
|
-
Add these to your account mapping JSON.`);let a=Nrt(t);if(e.steps.some(d=>(d.action==="cash-in"||d.action==="cash-out")&&d.step!==a)&&!n)throw new Error("--bank-account is required for recipes with cash-in/cash-out steps.");if(e.steps.some(d=>(d.action==="bill"||d.action==="invoice")&&d.step!==a)&&!i)throw new Error("--contact is required for recipes with bill/invoice steps.")}async function Obr(t,e){let n=(await Nb(t)).data.find(o=>o.displayName.toLowerCase()===e.toLowerCase());return n?n.resourceId:(await X_(t,{displayName:e})).data.resourceId}function Nrt(t){if(!t.existingTxnId)return null;let e=Brt[t.calcType];return e?t.blueprint.steps.find(n=>e.includes(n.action))?.step??null:null}async function Fbr(t,e,r,n){let{accountMap:i,referencePrefix:o}=r,s=o?`${o}-${e.step}`:void 0;try{let a;switch(e.action){case"journal":{a=(await QA(t,{reference:s,valueDate:e.date,journalEntries:lue(e.lines,i),internalNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"bill":{a=(await yA(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:Trt(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"invoice":{a=(await OA(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:Trt(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"cash-in":{let{contraLines:c}=krt(e.lines,r.bankAccountId,i);a=(await hv(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:lue(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}case"cash-out":{let{contraLines:c}=krt(e.lines,r.bankAccountId,i);a=(await mv(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:lue(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}default:return{step:e.step,action:e.action,status:"skipped",description:e.description}}return{step:e.step,action:e.action,status:"created",resourceId:a,description:e.description}}catch(a){return{step:e.step,action:e.action,status:"error",description:e.description,error:a.message}}}function lue(t,e){return t.map(r=>({accountResourceId:due(r.account,e),type:r.debit>0?"DEBIT":"CREDIT",amount:r.debit>0?r.debit:r.credit}))}function Trt(t,e){return t.filter(r=>uue(r.account,e)).map(r=>({name:r.account,quantity:1,unitPrice:r.debit>0?r.debit:r.credit,accountResourceId:due(r.account,e)}))}function krt(t,e,r){let n=[],i=null;for(let o of t)due(o.account,r)===e&&!i?i=o:n.push(o);return i?{bankLine:i,contraLines:n}:{bankLine:t[0],contraLines:t.slice(1)}}function uue(t,e){if(e[t])return t;let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return n;return null}function due(t,e){let r=uue(t,e);if(!r)throw new Error(`Unmapped account: "${t}"`);return e[r]}var fue=X(()=>{"use strict";iC();Kf();FA();GY();tD();xrt()});async function Ort(t,e){let n=(await fp((s,a)=>Dd(t,{offset:s,limit:a}))).data;if(n.length===0)return{mapping:{},failures:e.map(s=>({name:s,candidates:[]}))};let i={},o=[];for(let s of e){let a=EM(s,n);if(a)i[s]=a.resourceId;else{let c=Hb(s,n,{threshold:.3,limit:3});o.push({name:s,candidates:c.map(u=>u.item.name)})}}return{mapping:i,failures:o}}async function Frt(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let d=(await ep(t,e)).data;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}let n=e.trim(),o=(await dc(t,{filter:{billingName:{contains:n}},limit:50})).data;if(o.length===0&&(o=(await Xf(t,{offset:0,limit:500})).data),o.length===0)throw new Error("No contacts found. Create one in Jaz first.");let s=n.toLowerCase(),a=o.find(u=>u.billingName?.toLowerCase()===s||u.name?.toLowerCase()===s);if(a)return{resourceId:a.resourceId,displayName:a.billingName||a.name||"Unknown"};let c=bM(n,o,{threshold:.5,limit:5});if(c.length>=1&&c[0].score>=.7){let u=c[0],d=c.length>1?c[1].score:0;if(c.length===1||u.score-d>=.1){let f=u.item;return{resourceId:f.resourceId,displayName:f.billingName||f.name||"Unknown"}}}if(c.length>1){let u=c.map(d=>`${d.item.billingName||d.item.name} (${(d.score*100).toFixed(0)}%)`).join(", ");throw new Error(`Multiple contacts match "${n}": ${u}. Be more specific.`)}throw new Error(`No contact matching "${n}".`)}async function Qrt(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let i=await lb(t,e);return{resourceId:i.data.resourceId,displayName:i.data.name}}let n=await AA(t,e);return{resourceId:n.resourceId,displayName:n.name}}var Lrt=X(()=>{"use strict";Yb();tp();Zf();oL();$7();q7();J1()});async function Yh(t,e){await t.delete(`/api/v1/cash-entries/${e}`)}async function Hh(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}var Ux=X(()=>{"use strict"});async function hH(t,e){return t.post("/api/v1/transfer-trial-balance",e)}var pue=X(()=>{"use strict"});async function mH(t,e){return t.list("/api/v1/organization/bookmarks",e)}async function AH(t,e){return t.get(`/api/v1/organization/bookmarks/${e}`)}async function $x(t,e){return t.post("/api/v1/organization/bookmarks",{items:e})}async function gH(t,e,r){return t.put(`/api/v1/organization/bookmarks/${e}`,r)}var hue=X(()=>{"use strict"});function Qbr(t){let{refs:e,...r}=t;return e?{...r,refs:e.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function gv(t,e){return t.post("/api/v1/jots",{entries:e.map(Qbr)})}async function yH(t,e){return t.post("/api/v1/jots/search",e)}async function Mrt(t,e,r){return t.post(`/api/v1/jots/${e}/disposition`,r)}var EH=X(()=>{"use strict"});async function Prt(t,e){return t.post("/api/v1/agents/memories",e)}async function mue(t,e){return t.post("/api/v1/agents/memories/forget",e)}var Urt=X(()=>{"use strict"});var gue={};Ga(gue,{default:()=>Mbr,log:()=>Aue});var yv,Lbr,Aue,Mbr,yue=X(()=>{"use strict";yv=()=>{},Lbr=()=>Aue,Aue={info:yv,warn:yv,error:yv,debug:yv,trace:yv,fatal:yv,child:Lbr,level:"silent"},Mbr=Aue});import{createHash as Pbr}from"node:crypto";function bue(){return process.env.ENABLE_MEMORY==="true"}function Wbr(t){if(!t||!t.trim())return[null,"directive_required"];let e=t.normalize("NFKC").trim();return e.length>qbr?[null,"directive_too_long"]:$br.some(r=>e.includes(r))?[null,"directive_invalid"]:Ubr.test(e)?[null,"directive_invalid"]:Jbr.test(e)?[null,"directive_contains_url"]:Vbr.test(e)?[null,"directive_contains_email"]:[e,null]}function Zbr(t,e,r,n,i,o,s,a){if(t)return Pbr("sha256").update(`${t}:${e}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function Kbr(t){Promise.resolve().then(()=>(yue(),gue)).then(({log:e})=>e.info(t,"memory_tool.call")).catch(()=>{})}async function Hrt(t,e){let r=e.action,n=e.category,i=zbr[e.scope??"this_org"]??"ORG_USER",o=typeof e.key=="string"?e.key.trim():"",s=null,a=u=>(Kbr({action:r,category:n,key:o,scope:i,tier:s,ok:u.ok,outcome:u.outcome??u.reason}),u),c=u=>a({ok:!1,reason:u});try{let u=t.memoryTurn;if(!bue()||!u||!u.progressive)return c("memory_disabled");if(!u.isInboxOwner)return c("not_owner");if(!o||o.length>jbr||!Gbr.test(o))return c("invalid_key");let d=null;if(r==="set"){let[h,m]=Wbr(e.directive);if(m)return c(m);d=h}if(s=1,e.key_type!==void 0&&e.key_type!==null){if(!e.match_value||!e.match_value.trim())return c("match_value_required");s=2}else if(e.match_value)return c("key_type_required");if(u.writes>=Ybr)return c("write_limit");u.writes+=1;let f=u.gtid||"",p;if(r==="set"){let h={gtid:f};u.quote&&(h.quote=u.quote.slice(0,Hbr));let m=Zbr(f,r,i,n,o,d,e.confirms_key,e.replaces_key),A={scope:i,tier:s,category:n,key:o,...e.key_type?{keyType:e.key_type}:{},...e.match_value?{matchValue:e.match_value}:{},directive:d??"",...e.replaces_key?{replacesKey:e.replaces_key}:{},...e.confirms_key?{confirmsKey:e.confirms_key}:{},pending:e.pending===!0,source:"TOOL",provenance:h,...m?{idempotencyKey:m}:{}};p=await Eue(()=>Prt(t.client,A))}else if(r==="forget"){let h={category:n,key:o,scope:i};p=await Eue(()=>mue(t.client,h))}else{let h={forgetAll:!0};p=await Eue(()=>mue(t.client,h))}return a(p)}catch{return a({ok:!1,reason:"internal_error"})}}async function Eue(t){try{let e=await t(),r=e&&typeof e=="object"&&e.data&&typeof e.data=="object"?e.data:e??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(e){return e instanceof ro?e.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${e.status}`}:{ok:!1,reason:"network_error"}}}var Ubr,$br,qbr,jbr,Ybr,Hbr,$rt,qrt,jrt,Yrt,zbr,Gbr,Jbr,Vbr,zrt=X(()=>{"use strict";Urt();nc();Ubr=/[\x00-\x1f\x7f]/,$br=["{{","}}","```","<",">"],qbr=300,jbr=120,Ybr=3,Hbr=140,$rt=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling","autonomy-grant"],qrt=["set","forget","forget_all"],jrt=["this_org","all_orgs"],Yrt=["SENDER_ADDRESS","SENDER_DOMAIN","VENDOR_NAME","SUBJECT_TOKEN"],zbr={this_org:"ORG_USER",all_orgs:"USER"},Gbr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Jbr=/https?:\/\//i,Vbr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/});async function bH(t,e){return t.list("/api/v1/organization-users",e)}async function CH(t,e){return t.search("/api/v1/organization-users/search",e)}async function Ev(t,e){return t.post("/api/v1/organization-users/invite",e)}async function vH(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function IH(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var Cue=X(()=>{"use strict"});async function wH(t,e){return t.search("/api/v1/cashflow-transactions/search",{limit:e?.limit??100,offset:e?.offset??0,sort:{sortBy:["valueDate"],order:"DESC"}})}async function qx(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function _H(t,e){return t.get(`/api/v1/payments/${e}`)}async function DH(t,e,r){return t.put(`/api/v1/payments/${e}`,r)}async function SH(t,e){await t.delete(`/api/v1/payments/${e}`)}var vue=X(()=>{"use strict"});async function RH(t,e,r={}){let n=Xbr.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`;return t.post(n,r)}var Xbr,Iue=X(()=>{"use strict";Xbr=new Set(["statement-of-account-export"])});import{createHash as eCr}from"node:crypto";import{writeFile as tCr,mkdir as rCr}from"node:fs/promises";import{dirname as nCr,isAbsolute as iCr,join as oCr}from"node:path";async function Grt(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function wue(t,e,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),t.post("/api/v1/reports/sql-query/export",{query:e},{headers:n})}async function _ue(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function sCr(t){return eCr("sha256").update(t).digest("hex").slice(0,16)}async function Jrt(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=sCr(e),o=await wue(t,e,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(;Date.now()<a&&!(c.status==="COMPLETED"||c.status==="FAILED"||c.status==="EXPIRED"||(await new Promise(p=>setTimeout(p,2e3)),Date.now()>=a));)c=(await _ue(t,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!iCr(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??oCr(f,"Downloads",`pseudo-sql-${s}.csv`);return await rCr(nCr(p),{recursive:!0}),await tCr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}async function Vrt(t){let e=await t.get("/api/v1/reports/sql-query/schema"),r=e.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return e}var Wrt=X(()=>{"use strict"});async function BH(t){return t.get("/api/v1/capsule-recipes")}async function xH(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function TH(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function kH(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function NH(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function na(t){if(!t||typeof t!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(typeof e.recipeName!="string"||e.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(e.recipeVersion!==void 0&&(typeof e.recipeVersion!="number"||!Number.isInteger(e.recipeVersion)||e.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(e.inputs===null||e.inputs===void 0||typeof e.inputs!="object"||Array.isArray(e.inputs))throw new Error("capsuleRecipe.inputs is required and must be a non-null object (recipe-specific shape; see descriptor.versions[].inputSchema).");let r=["baseTransactionResourceId","baseTransactionType","organizationResourceId"],n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length>0&&n.length<r.length)throw new Error(`capsuleRecipe base-transaction triplet is all-or-nothing \u2014 supply all of [baseTransactionResourceId, baseTransactionType, organizationResourceId] or none. Currently supplied: [${n.join(", ")}].`);if(e.templateOverrides!==void 0&&e.templateOverrides!==null){if(!Array.isArray(e.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;e.templateOverrides.forEach((o,s)=>{if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`capsuleRecipe.templateOverrides[${s}] must be an object {slotKey, template?}.`);let a=o;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey is required (non-empty string). Valid keys: get_capsule_recipe \u2192 versions[].templateSlots[].slotKey.`);if(a.slotKey.length>128)throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new Error(`capsuleRecipe.templateOverrides has a duplicate slotKey "${a.slotKey}" \u2014 one override per slot.`);if(i.add(a.slotKey),a.template!==void 0&&a.template!==null){if(typeof a.template!="string")throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var Due=X(()=>{"use strict"});async function oi(t,e,r){let n=await t.get(`/api/v1/${e}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function FH(t,e){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=e,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),t.postMultipart(`/api/v1/${r}/${n}/attachments`,o)}async function QH(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var OH,zh=X(()=>{"use strict";OH=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function Ua(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var LH=X(()=>{"use strict"});async function MH(t,e){return t.post("/api/v1/claims/conversion/preview",e)}async function PH(t,e){if(e.idempotencyKey&&/^CONV[:-]/.test(e.idempotencyKey))throw new Error('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return t.post("/api/v1/claims/conversion/commit",e)}var jx,Sue=X(()=>{"use strict";jx=["POST","POST_AND_RECORD"]});async function UH(t,e){if(!(e.amount>0))throw new Error("amount must be greater than 0.");return t.post("/api/v1/claims/payouts/record",e)}async function $H(t,e){return t.search("/api/v1/employees/payouts/search",e)}var Zrt,Rue=X(()=>{"use strict";Zrt=["REIMBURSEMENT","ADVANCE"]});function Krt(t){return{source:t.source,sourceType:t.sourceType,...t.cloudProvider?{cloudProvider:t.cloudProvider}:{},summary:t.summary,files:t.folders.flatMap(e=>e.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}var Xrt=X(()=>{"use strict"});import{randomUUID as aCr}from"node:crypto";import{rmSync as cCr}from"node:fs";function xue(t){for(let e of t.tempDirs??[])try{cCr(e,{recursive:!0,force:!0})}catch{}}function tnt(t){for(let[e,r]of cy)t-r.createdAt>ent&&(xue(r.plan),cy.delete(e))}function uCr(){Bue||(Bue=setInterval(()=>tnt(Date.now()),lCr),Bue.unref?.())}function rnt(t,e){let r=Date.now();tnt(r),uCr();let n=`dc_${aCr()}`;return cy.set(n,{plan:t,createdAt:r,ownerKey:e}),n}function nnt(t,e){let r=cy.get(t);return!r||r.ownerKey!==e?null:Date.now()-r.createdAt>ent?(xue(r.plan),cy.delete(t),null):r.plan}function int(t,e){let r=cy.get(t);!r||r.ownerKey!==e||(xue(r.plan),cy.delete(t))}var ent,lCr,cy,Bue,ont=X(()=>{"use strict";ent=1800*1e3,lCr=300*1e3,cy=new Map});function dCr(t){if(!t||typeof t!="object")return;let e=t;return e.validFiles?.[0]?.workflowResourceId??e.workflowResourceId}function fCr(t,e){let r=new Set(e);return{...t,folders:t.folders.map(n=>({...n,files:n.files.filter(i=>MO(i.documentType)&&r.has(i.documentType))}))}}async function snt(t){let{plan:e,client:r,bankAccountId:n,documentTypes:i}=t,o=i&&i.length>0?fCr(e,i):e;if(!n&&pCr(o))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");let s=await V1({plan:o,client:r,bankAccountId:n}),a=s.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?dCr(u.response):void 0,error:u.error})),c=a.map(u=>u.workflowId).filter(u=>!!u);return{total:s.total,uploaded:s.success,skipped:a.filter(u=>u.status==="skipped").length,failed:s.failed,workflowIds:c,files:a}}function pCr(t){return t.folders.some(e=>e.files.some(r=>r.documentType==="BANK_STATEMENT"))}var ant=X(()=>{"use strict";PW();Tf()});async function $u(t,e,r){if(!e)return t;let n=hCr(t);if(!n)return t;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return t&&typeof t=="object"?{...t,_hydration:s}:{result:t,_hydration:s}}}function hCr(t){if(!t||typeof t!="object")return;let e=t,r=e.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=e.resourceId;if(typeof n=="string"&&n.length>0)return n}var cnt=X(()=>{"use strict"});async function qH(t,e){return t.list("/api/v1/bank-rules",e)}async function Yx(t,e){let r=await t.get(`/api/v1/bank-rules/${e}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${e}`)}async function jH(t,e){return t.search("/api/v1/bank-rules/search",e)}async function YH(t,e){return t.post("/api/v1/bank-rules",e)}async function HH(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function zH(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var Tue=X(()=>{"use strict"});async function GH(t,e){return t.list("/api/v1/fixed-assets",e)}async function JH(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function VH(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function WH(t,e){return t.post("/api/v1/fixed-assets",e)}async function ZH(t,e,r){return t.put(`/api/v1/fixed-assets/${e}`,r)}async function KH(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function XH(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function Hx(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function ez(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function tz(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function rz(t,e){return Zo(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var nz=X(()=>{"use strict";Ba()});async function iz(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function zx(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function oz(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function sz(t,e,r){let n={...r};if(n.endDate){let i=!n.startDate,o=!n.repeat&&!n.interval;if(i||o){let s=await zx(t,e);if(i&&(n.startDate=s.data.startDate),o){if(!s.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=s.data.interval}}}return t.put(`/api/v1/scheduled/subscriptions/${e}`,n)}async function az(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function cz(t,e,r){return t.put(`/api/v1/scheduled/cancel-subscriptions/${e}`,{resourceId:e,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function lz(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var kue=X(()=>{"use strict"});async function uz(t,e){return t.list("/api/v1/contact-groups",e)}async function dz(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function fz(t,e){return t.search("/api/v1/contact-groups/search",e)}async function pz(t,e){return t.post("/api/v1/contact-groups",e)}async function hz(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,r)}async function mz(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var Nue=X(()=>{"use strict"});async function Az(t,e){return t.list("/api/v1/inventory-items",e)}async function gz(t,e){return t.post("/api/v1/inventory-items",e)}async function yz(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var Oue=X(()=>{"use strict"});async function Ez(t,e){return t.list("/api/v1/custom-fields",e)}async function bz(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function Cz(t,e){return t.search("/api/v1/custom-fields/search",e)}async function vz(t,e){return t.post("/api/v1/custom-fields",e)}async function Iz(t,e,r){return t.put(`/api/v1/custom-fields/${e}`,r)}async function wz(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var Fue=X(()=>{"use strict"});function lnt(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function Gx(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return lnt(n)}async function Jx(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return lnt(n)}var mCr,ACr,gCr,bv,Que=X(()=>{"use strict";mCr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],ACr=["journals","cash-entries"],gCr=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],bv=[...mCr,...ACr,...gCr]});async function _z(t,e){return t.list("/api/v1/nano-classifiers",e)}async function Dz(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function Sz(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function Vx(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function Wx(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,r)}async function Rz(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var Lue=X(()=>{"use strict"});async function Bz(t,e){return t.post("/api/v1/export-records",e)}async function xz(t,e){return t.post("/api/v1/export-records/preview",e)}async function Tz(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var Mue=X(()=>{"use strict"});async function Zx(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var Pue=X(()=>{"use strict"});function Cv(t){ei(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!yCr.has(n.btType))throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.`)})}async function kz(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:bCr(r.data)}}function ECr(t){return{btResourceId:t.btResourceId,btType:t.btType,eligible:t.eligible,errors:t.errors,displayData:t.displayData,contactSignals:t.contactInsight??null,breakdown:t.breakdown??null}}function bCr(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(ECr),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function Nz(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function Oz(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var yCr,Uue=X(()=>{"use strict";Ba();yCr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function dnt(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function $ue(t,e){if(!t||typeof t!="object")throw new Error(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${e}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${e}.lineItems per call.`);uc([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&uc([i],["valueDate"])}function ICr(t,e){let r=typeof e=="number"&&!Number.isNaN(e)?e:void 0,n=typeof t=="number"&&!Number.isNaN(t)?t:void 0;if(r!==void 0)return r>=CCr?"high":r>=unt?"medium":"low";if(n!==void 0){if(n>=vCr)return"high";if(n>=unt)return"medium"}return"low"}function fnt(t,e={}){let r=t??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,alternativeCount:0});continue}let d=u.slice().sort((D,x)=>{let L=D.confidenceScore??D.matchScore??-1;return(x.confidenceScore??x.matchScore??-1)-L}),f=d[0],p=typeof f.recommendationType=="string"?f.recommendationType:void 0,h=typeof f.matchScore=="number"?f.matchScore:void 0,m=typeof f.confidenceScore=="number"?f.confidenceScore:void 0,A=typeof f.isCrossCurrency=="boolean"?f.isCrossCurrency:void 0,g=typeof f.cftBtResourceId=="string"?f.cftBtResourceId:void 0,y=Array.isArray(f.cftBtResourceIds)?f.cftBtResourceIds:[],C=f.isBatch===!0||y.length>1,E=typeof f.cftAmount=="number"?f.cftAmount:void 0,v,I;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(v=Kx.magicMatch,I={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(v=Kx.withPayments,I={bankStatementEntryResourceId:c,businessTransactionPayments:[{cashflowTransactionResourceId:g,...E!==void 0?{transactionAmount:E}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let D=typeof f.learnedPredictionResourceId=="string"?f.learnedPredictionResourceId:void 0,x=typeof f.predictedPayload=="string"?f.predictedPayload:void 0,L=typeof f.predictedPayloadSchemaVersion=="string"?f.predictedPayloadSchemaVersion:void 0;D&&x&&L&&(v=Kx.learnedPrediction,I={bankStatementEntryResourceId:c,learnedPredictionResourceId:D,predictedPayload:x,predictedPayloadSchemaVersion:L});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let D=f.actionShortcut??{},x=typeof D.resourceId=="string"?D.resourceId:void 0;x&&(v=Kx.applyBankRule,I={actionShortcutResourceId:x,businessTransactionResourceIds:[c]});break}default:break}let k=v?ICr(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),N=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,H=v!==Kx.withPayments||S,q=k==="high"&&!!v&&!!I&&H&&N;o.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:m,isCrossCurrency:A,recommendedTool:v,execute:I,confidenceTier:k,autoCommitEligible:q,alternativeCount:d.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return o}function _Cr(t,e,r){return{bankStatementEntryResourceId:t.bankStatementEntryResourceId,confidenceTier:t.confidenceTier,recommendationType:t.recommendationType,recommendedTool:t.recommendedTool,execute:t.execute,bankLine:e,match:r}}async function DCr(t,e,r){let n=e.matchedTransactionResourceId,i=e.matchedTransactionCount;if(!n)return e.matchAmount!==void 0?{type:"transaction",amount:e.matchAmount,count:i}:null;let o=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let s of o)try{let{data:a}=s==="bill"?await vs(t,n):await _s(t,n);return{type:s,reference:a.reference,amount:e.matchAmount??a.totalAmount,documentTotalAmount:a.totalAmount,count:i,resourceId:n}}catch{}return{type:"transaction",amount:e.matchAmount,count:i,resourceId:n}}async function pnt(t,e,r){let n=r.filter(o=>o.recommendedTool&&!o.autoCommitEligible).slice(0,wCr);if(n.length===0)return[];let i=new Map;if(e)try{let o=await ub(t,e,{filter:{status:{eq:"UNRECONCILED"}},limit:500});for(let s of o.data??[])i.set(s.resourceId,s)}catch{}return Promise.all(n.map(async o=>{let s=i.get(o.bankStatementEntryResourceId),a=s?{valueDate:s.valueDate,netAmount:s.netAmount,currencyCode:s.currencyCode,currencySymbol:s.currencySymbol,description:s.description,counterparty:s.extContactName}:null;return _Cr(o,a,await DCr(t,o,a?.netAmount))}))}async function Fz(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function Qz(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function Lz(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function Mz(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function Pz(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function Uz(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function $z(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function qz(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function jz(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function Yz(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function Hz(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}var Kx,CCr,vCr,unt,wCr,que=X(()=>{"use strict";Zf();Kf();Ba();FA();Kx={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},CCr=.9,vCr=.95,unt=.7;wCr=25});function Ns(t,e,r="lineItems"){let n=[];for(let i of e)if(i.perLineItem){let o=t[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(t)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function fo(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),o={valueDate:jue(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=jue(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=jue(t,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=t[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(I=>I.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,C=a.debitAmount,E=a.creditAmount,v=a.type??(typeof C=="number"&&C>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||v||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function jue(t,e,r,n,i){let o=i.find(s=>s.field===e);if(!o){let s=t[e];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(t)){let s=t[e];return e==="contactResourceId"?{status:"ok",value:t.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function To(t,e,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Ns(t,e,n),a=fo(t,e,n);return{resourceId:t.resourceId,reference:t.reference||null,totalAmount:t.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var ia,Qc,Ki,Ql,hnt=X(()=>{"use strict";ia=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:t=>!!t.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:t=>t.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:t=>!!t.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:t=>t.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0}],Qc=[...ia],Ki=ia.filter(t=>t.field!=="dueDate"),Ql=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:t=>t.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:t=>t.amount!=null&&t.amount>0||t.debitAmount!=null&&t.debitAmount>0||t.creditAmount!=null&&t.creditAmount>0,perLineItem:!0}]});function Lc(t){let e={};t.name!=null&&(e.name=t.name),t.quantity!=null&&(e.quantity=t.quantity),t.unitPrice!=null&&(e.unitPrice=t.unitPrice),t.unit&&(e.unit=t.unit);let r=t.accountResourceId||t.organizationAccountResourceId;r&&(e.accountResourceId=r);let n=t.taxProfileResourceId||(t.taxProfile&&typeof t.taxProfile=="object"?t.taxProfile.resourceId:null);return n&&(e.taxProfileResourceId=n),t.itemResourceId&&(e.itemResourceId=t.itemResourceId),t.discount!=null&&(e.discount=typeof t.discount=="object"?t.discount.rateValue??0:t.discount),e}function vv(t){let e={},r=t.accountResourceId||t.organizationAccountResourceId;return r&&(e.accountResourceId=r),t.amount!=null?e.amount=t.amount:t.debitAmount!=null&&t.debitAmount>0?e.amount=t.debitAmount:t.creditAmount!=null&&t.creditAmount>0&&(e.amount=t.creditAmount),t.type?e.type=t.type:t.debitAmount!=null&&t.debitAmount>0?e.type="DEBIT":t.creditAmount!=null&&t.creditAmount>0&&(e.type="CREDIT"),t.description&&(e.description=t.description),t.contactResourceId&&(e.contactResourceId=t.contactResourceId),e}function Lt(t){if(t)return t.split("T")[0]}var Yue=X(()=>{"use strict"});function qu(t,e){let r={};if(e.contact&&(r.contactResourceId=e.contact),e.date&&(r.valueDate=e.date),e.due&&(r.dueDate=e.due),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.tag!==void 0&&(r.tag=e.tag),e.tax&&(r.isTaxVatApplicable=!0),e.tax&&e.taxInclusive?r.taxInclusion=!0:e.tax&&(r.taxInclusion=!1),e.lines)r.lineItems=e.lines;else if(e.account||e.taxProfile){let n=t.lineItems??[];r.lineItems=n.map(i=>{let o=Lc(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),e.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=e.taxProfile),o})}return r}function zz(t,e){let r={};if(e.date&&(r.valueDate=e.date),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.entries)r.journalEntries=e.entries;else if(e.account){let n=t.journalEntries??[];r.journalEntries=n.map(i=>{let o=vv(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),o})}return r}var mnt=X(()=>{"use strict";Yue()});var Hue=X(()=>{"use strict";hnt();Yue();mnt()});var Xx,Ll,Ant=X(()=>{"use strict";Xx="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",Ll="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});import{randomUUID as SCr}from"node:crypto";function Nnt(t){let e=t.limit,r=t.offset;return{limit:e,offset:r,sortBy:void 0,sortOrder:void 0}}function pr(t,e,r,n,i,o){let s={...Zue};return o?.leanView&&(s.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). List lean, then drill in with get_*."}),{name:t,description:e,params:s,required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(a,c)=>{let{limit:u,offset:d}=Nnt(c),f=o?.leanView?c.view==="full"?"full":"lean":void 0;return ID((h,m)=>n(a.client,h,m,f),u,d,f==="lean"?50:20)}}}function _i(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(o,s)=>n(o.client,s.resourceId)}}function Ti(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(o,s)=>(await n(o.client,s.resourceId),{deleted:!0,resourceId:s.resourceId})}}function Wue(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,...i?.destructive?{isDestructive:!0}:{},...i?.searchHint?{searchHint:i.searchHint}:{},execute:async(o,s)=>n(o.client,s.resourceId)}}function wnt(t){if(typeof t!="string"||/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let e=/^(\d{4}-\d{2}-\d{2})T/.exec(t);return e?e[1]:t}function NCr(t){return Array.isArray(t)?t.map(e=>{let r={};for(let[n,i]of Object.entries(e))if(i!=null)if(n==="organizationAccountResourceId")r.accountResourceId=i;else if(n==="taxProfile"&&typeof i=="object"&&i!==null){let o=i.resourceId;o&&(r.taxProfileResourceId=o)}else if(n==="discount"&&typeof i=="object"&&i!==null){let o=i.rateValue;o&&Number(o)!==0&&(r.discount=i)}else kCr.has(n)&&(r[n]=i);return r}):t}async function rT(t,e,r,n){let s=(await(e==="invoice"?_s:e==="bill"?vs:e==="customer_credit_note"?vl:Il)(t,r)).data,a=TCr[e],c={};for(let[p,h]of Object.entries(s))a.has(p)&&h!==null&&h!==void 0&&(c[p]=h);c.valueDate&&(c.valueDate=wnt(c.valueDate)),c.dueDate&&(c.dueDate=wnt(c.dueDate)),c.lineItems&&(c.lineItems=NCr(c.lineItems));for(let[p,h]of Object.entries(n))h!==void 0&&(c[p]=h);let u=e==="invoice"?Qc:e==="bill"?ia:Ki,{missingFields:d,ready:f}=Ns(c,u);if(!f)throw new Error(`Cannot finalize: missing ${d.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function _nt(t,e,r,n){if((await t(e,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function Vz(t,e,r){if(!(typeof t=="string"&&e.includes(t)))return{error:`Unknown documentType ${JSON.stringify(t)}.`,status:422,hint:`Use one of: ${e.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}function Rnt(t,e,r){let n=Snt[t];if(!n)return{error:`Unknown documentType "${t}".`,status:422,hint:`Valid document types: ${Object.keys(Snt).join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}};if(!n.includes(e)){let i=n.includes("ACCEPT")?"ACCEPT":"CONFIRM";return{error:`Action "${e}" is not valid for ${t}. Valid actions: ${n.join(", ")}.`,status:422,hint:`${t} advances its lifecycle with ${i}, not ${e}.`,repair:{tool:r,arguments:{documentType:t,action:i},reason:`${t} is advanced with ${i}.`}}}}async function Bnt(t,e,r,n,i,o,s){let a;try{a=(await e(t,r)).data?.status}catch{return}if(a==="DRAFT"||a==="VOID"){let c=a==="DRAFT"?`A DRAFT ${n} can't be linked or accepted \u2014 issue it by creating the ${n} with saveAsDraft:false (status ${s}), then link the order to that one.`:`A VOID ${n} can't be used \u2014 create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a ${a} ${n} (${r}).`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. ${c}`,repair:{tool:o,arguments:{documentType:i,saveAsDraft:!1},reason:c}}}}async function xnt(t,e,r,n,i,o){let s;try{s=(await e(t,r)).data?.status}catch{return}if(s==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:o,arguments:{},reason:`The source ${n} is VOID.`}}}async function Tnt(t,e,r,n,i){let o;try{o=(await e(t,r,n)).data?.status}catch{return}if(o&&o!=="DRAFT")return{error:`Cannot DELETE a ${o} ${r} \u2014 delete is only allowed on DRAFT records.`,status:422,hint:"Use action VOID to cancel a non-draft quote/request/order.",repair:{tool:i,arguments:{documentType:r,resourceId:n,action:"VOID"},reason:`${r} is ${o}; void it instead of deleting.`}}}var $a,po,Ml,ho,si,ju,Gz,ly,zue,fy,RCr,BCr,Gue,gnt,ynt,Jue,Zue,uy,Vue,Ent,bnt,Cnt,vnt,xi,Int,eT,xCr,dy,oa,knt,Yu,tT,TCr,kCr,nT,iT,Jz,Dnt,Snt,Mc,oT=X(()=>{"use strict";SM();fQe();yQe();bD();nc();dr();pc();Um();Yb();gLe();CLe();tp();FA();Kf();bZ();CZ();iC();vZ();Zf();IL();LL();tD();IZ();ULe();t2();c2();h2();srt();rD();jL();aD();MY();uD();WM();GY();Wle();Zle();Kle();Xle();cue();fue();Lrt();Zf();Ux();pue();hue();EH();zrt();Cue();vue();Iue();Wrt();Due();zh();LH();l_();Sue();Rue();dD();FW();Xrt();ont();ant();dZ();cnt();Tue();nz();kue();Nue();Oue();Fue();Que();Lue();Mue();Pue();tp();FA();Kf();t2();c2();iC();nz();Ba();Uue();que();dr();Hue();Ant();$a={type:"string",description:"Resource ID of the record"},po={type:"string",description:"Transaction date (YYYY-MM-DD)"},Ml={type:"string",description:"Due date (YYYY-MM-DD)"},ho={type:"string",description:"Reference number"},si={type:"string",description:"Notes or memo text"},ju={type:"string",description:"Tag name for categorization"},Gz={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},ly={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},zue={type:"string",description:"Contact resourceId (customer or supplier)"},fy={type:"string",description:"Bank/cash account resourceId"},RCr={type:"number",description:"Payment amount (in bank currency)"},BCr={type:"string",description:"Period start date (YYYY-MM-DD)"},Gue={type:"string",description:"Period end date (YYYY-MM-DD)"},gnt={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.`},ynt={type:"string",description:"Currency code (e.g. SGD, USD)"},Jue={type:"string",description:"Display name"},Zue={limit:{type:"number",description:"Max results per page (\u22641000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},uy={type:"object",properties:{sourceCurrency:{type:"string"},exchangeRate:{type:"number"}}},Vue={type:"string",enum:[...Rd],description:"Entity type to export"},Ent={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.'},bnt={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},Cnt={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."},vnt={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."},xi={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},Int={type:"array",description:"Full replacement line-item set \u2014 non-empty REPLACES all lines, [] clears, omit = no change. claimTypeResourceId + name + unitPrice + quantity are required at submit time.",items:{type:"object",properties:{resourceId:{type:"string",description:"Existing line resourceId (omit to add a new line)"},claimTypeResourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"Line name"},description:{type:"string",description:"Line description"},unitPrice:{type:"number",description:"Unit price"},quantity:{type:"number",description:"Quantity"},currency:{type:"string",description:"Line currency (ISO 4217; falls back to header)"},itemSubTotal:{type:"number",description:"Line subtotal (unitPrice \xD7 quantity)"}}}},eT={type:"array",items:{type:"string"},description:"Claim resourceIds (1-500)"},xCr={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:$a}}},printable:{type:"boolean"}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},dy={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)"},oa={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:fy,taxProfileResourceId:{type:"string"},classifierConfig:xCr},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},knt={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)."},Yu={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:knt},required:["recipeName","inputs"]},tT={type:"string",enum:[...jQe],description:"Payment method (default BANK_TRANSFER)"};TCr={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"])};kCr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);nT={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},iT={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},Jz={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."},Dnt={type:"string",enum:["ACCEPT","CONFIRM","VOID","DELETE"],description:"Lifecycle action. ACCEPT=quote/request only; CONFIRM=order only; VOID=any non-draft; DELETE=draft only."},Snt={SALE_QUOTE:["ACCEPT","VOID","DELETE"],SALE_ORDER:["CONFIRM","VOID","DELETE"],PURCHASE_REQUEST:["ACCEPT","VOID","DELETE"],PURCHASE_ORDER:["CONFIRM","VOID","DELETE"]};Mc=[{name:"get_organization",description:"Get organization details: name, base currency, country, and financial year end.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>Aa(t.client)},{name:"get_my_context",description:"Resolve the CALLER's own context \u2014 identity, the employee bound to their login (if any), and per-module access (moduleRoles). Use to route a receipt (bill if PURCHASES access, expense claim if EMPLOYEE_CLAIMS access). A service api-key usually has no bound employee. Magic claim drafts auto-bind the uploader server-side \u2014 no need to read employee.resourceId to bind one.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"who am i my employee my permissions module roles what can i do self caller capabilities bills claims",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>y0e(t.client)},pr("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(t,e,r)=>Dd(t,{limit:r,offset:e}),"list chart of accounts with code type class status"),Vt({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:lS,defaults:uS,fetcher:jb,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(t,e)=>{let r=e.name,n=await lM(t.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=qb(e.accountType);return pD(t.client,{code:e.code,name:r,accountType:i,currencyCode:e.currencyCode,lockDate:e.lockDate})}},{name:"update_account",description:"Update a chart of accounts entry \u2014 rename, re-code, set its period lock date, or remove an existing lock date. Setting lockDate (YYYY-MM-DD) is how an individual ledger account is locked for a period: it blocks recording or editing any transaction on that account dated on or before the lock date. Pass clearLockDate to remove (unlock) an existing lock.",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."},clearLockDate:{type:"boolean",description:"Set true to remove an existing period lock date (unlock the period). Use when the user asks to remove, delete, clear, lift, or unset the lock. Do not also pass lockDate."}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code lock date unlock remove clear lock",execute:async(t,e)=>{let r=e.resourceId,n=(await C1e(t.client,r)).data,o=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(a=>n[a]!==void 0&&n[a]!==null).map(a=>[a,n[a]]));!o.classificationType&&n.accountType&&(o.classificationType=n.accountType);let s=e.clearLockDate===!0;if(s&&e.lockDate!==void 0)throw new Error("clearLockDate and lockDate are mutually exclusive \u2014 pass one or the other.");return!s&&typeof n.accountLockDate=="string"&&n.accountLockDate&&(o.lockDate=n.accountLockDate.slice(0,10)),e.name!==void 0&&(o.name=e.name),e.code!==void 0&&(o.code=e.code),!s&&e.lockDate!==void 0&&(o.lockDate=e.lockDate),v1e(t.client,r,o)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount } \u2014 no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
|
|
680
|
+
Add these to your account mapping JSON.`);let a=Nrt(t);if(e.steps.some(d=>(d.action==="cash-in"||d.action==="cash-out")&&d.step!==a)&&!n)throw new Error("--bank-account is required for recipes with cash-in/cash-out steps.");if(e.steps.some(d=>(d.action==="bill"||d.action==="invoice")&&d.step!==a)&&!i)throw new Error("--contact is required for recipes with bill/invoice steps.")}async function Obr(t,e){let n=(await Nb(t)).data.find(o=>o.displayName.toLowerCase()===e.toLowerCase());return n?n.resourceId:(await X_(t,{displayName:e})).data.resourceId}function Nrt(t){if(!t.existingTxnId)return null;let e=Brt[t.calcType];return e?t.blueprint.steps.find(n=>e.includes(n.action))?.step??null:null}async function Fbr(t,e,r,n){let{accountMap:i,referencePrefix:o}=r,s=o?`${o}-${e.step}`:void 0;try{let a;switch(e.action){case"journal":{a=(await QA(t,{reference:s,valueDate:e.date,journalEntries:lue(e.lines,i),internalNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"bill":{a=(await yA(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:Trt(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"invoice":{a=(await OA(t,{reference:s,valueDate:e.date,dueDate:e.date,contactResourceId:r.contactId,lineItems:Trt(e.lines,i),invoiceNotes:e.description,saveAsDraft:n})).data.resourceId;break}case"cash-in":{let{contraLines:c}=krt(e.lines,r.bankAccountId,i);a=(await hv(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:lue(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}case"cash-out":{let{contraLines:c}=krt(e.lines,r.bankAccountId,i);a=(await mv(t,{reference:s,valueDate:e.date,accountResourceId:r.bankAccountId,lines:lue(c,i),internalNotes:e.description,saveAsDraft:n})).data?.resourceId;break}default:return{step:e.step,action:e.action,status:"skipped",description:e.description}}return{step:e.step,action:e.action,status:"created",resourceId:a,description:e.description}}catch(a){return{step:e.step,action:e.action,status:"error",description:e.description,error:a.message}}}function lue(t,e){return t.map(r=>({accountResourceId:due(r.account,e),type:r.debit>0?"DEBIT":"CREDIT",amount:r.debit>0?r.debit:r.credit}))}function Trt(t,e){return t.filter(r=>uue(r.account,e)).map(r=>({name:r.account,quantity:1,unitPrice:r.debit>0?r.debit:r.credit,accountResourceId:due(r.account,e)}))}function krt(t,e,r){let n=[],i=null;for(let o of t)due(o.account,r)===e&&!i?i=o:n.push(o);return i?{bankLine:i,contraLines:n}:{bankLine:t[0],contraLines:t.slice(1)}}function uue(t,e){if(e[t])return t;let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return n;return null}function due(t,e){let r=uue(t,e);if(!r)throw new Error(`Unmapped account: "${t}"`);return e[r]}var fue=X(()=>{"use strict";iC();Kf();FA();GY();tD();xrt()});async function Ort(t,e){let n=(await fp((s,a)=>Dd(t,{offset:s,limit:a}))).data;if(n.length===0)return{mapping:{},failures:e.map(s=>({name:s,candidates:[]}))};let i={},o=[];for(let s of e){let a=EM(s,n);if(a)i[s]=a.resourceId;else{let c=Hb(s,n,{threshold:.3,limit:3});o.push({name:s,candidates:c.map(u=>u.item.name)})}}return{mapping:i,failures:o}}async function Frt(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let d=(await ep(t,e)).data;return{resourceId:d.resourceId,displayName:d.billingName||d.name||"Unknown"}}let n=e.trim(),o=(await dc(t,{filter:{billingName:{contains:n}},limit:50})).data;if(o.length===0&&(o=(await Xf(t,{offset:0,limit:500})).data),o.length===0)throw new Error("No contacts found. Create one in Jaz first.");let s=n.toLowerCase(),a=o.find(u=>u.billingName?.toLowerCase()===s||u.name?.toLowerCase()===s);if(a)return{resourceId:a.resourceId,displayName:a.billingName||a.name||"Unknown"};let c=bM(n,o,{threshold:.5,limit:5});if(c.length>=1&&c[0].score>=.7){let u=c[0],d=c.length>1?c[1].score:0;if(c.length===1||u.score-d>=.1){let f=u.item;return{resourceId:f.resourceId,displayName:f.billingName||f.name||"Unknown"}}}if(c.length>1){let u=c.map(d=>`${d.item.billingName||d.item.name} (${(d.score*100).toFixed(0)}%)`).join(", ");throw new Error(`Multiple contacts match "${n}": ${u}. Be more specific.`)}throw new Error(`No contact matching "${n}".`)}async function Qrt(t,e){if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)){let i=await lb(t,e);return{resourceId:i.data.resourceId,displayName:i.data.name}}let n=await AA(t,e);return{resourceId:n.resourceId,displayName:n.name}}var Lrt=X(()=>{"use strict";Yb();tp();Zf();oL();$7();q7();J1()});async function Yh(t,e){await t.delete(`/api/v1/cash-entries/${e}`)}async function Hh(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}var Ux=X(()=>{"use strict"});async function hH(t,e){return t.post("/api/v1/transfer-trial-balance",e)}var pue=X(()=>{"use strict"});async function mH(t,e){return t.list("/api/v1/organization/bookmarks",e)}async function AH(t,e){return t.get(`/api/v1/organization/bookmarks/${e}`)}async function $x(t,e){return t.post("/api/v1/organization/bookmarks",{items:e})}async function gH(t,e,r){return t.put(`/api/v1/organization/bookmarks/${e}`,r)}var hue=X(()=>{"use strict"});function Qbr(t){let{refs:e,...r}=t;return e?{...r,refs:e.map(n=>typeof n=="string"?{raw:n}:n)}:r}async function gv(t,e){return t.post("/api/v1/jots",{entries:e.map(Qbr)})}async function yH(t,e){return t.post("/api/v1/jots/search",e)}async function Mrt(t,e,r){return t.post(`/api/v1/jots/${e}/disposition`,r)}var EH=X(()=>{"use strict"});async function Prt(t,e){return t.post("/api/v1/agents/memories",e)}async function mue(t,e){return t.post("/api/v1/agents/memories/forget",e)}var Urt=X(()=>{"use strict"});var gue={};Ga(gue,{default:()=>Mbr,log:()=>Aue});var yv,Lbr,Aue,Mbr,yue=X(()=>{"use strict";yv=()=>{},Lbr=()=>Aue,Aue={info:yv,warn:yv,error:yv,debug:yv,trace:yv,fatal:yv,child:Lbr,level:"silent"},Mbr=Aue});import{createHash as Pbr}from"node:crypto";function bue(){return process.env.ENABLE_MEMORY==="true"}function Wbr(t){if(!t||!t.trim())return[null,"directive_required"];let e=t.normalize("NFKC").trim();return e.length>qbr?[null,"directive_too_long"]:$br.some(r=>e.includes(r))?[null,"directive_invalid"]:Ubr.test(e)?[null,"directive_invalid"]:Jbr.test(e)?[null,"directive_contains_url"]:Vbr.test(e)?[null,"directive_contains_email"]:[e,null]}function Zbr(t,e,r,n,i,o,s,a){if(t)return Pbr("sha256").update(`${t}:${e}:${r}:${n}:${i}:${o??""}:${s??""}:${a??""}`).digest("hex").slice(0,64)}function Kbr(t){Promise.resolve().then(()=>(yue(),gue)).then(({log:e})=>e.info(t,"memory_tool.call")).catch(()=>{})}async function Hrt(t,e,r){let n=e.action,i=e.category,o=zbr[e.scope??"this_org"]??"ORG_USER",s=typeof e.key=="string"?e.key.trim():"",a=null,c=d=>(Kbr({action:n,category:i,key:s,scope:o,tier:a,ok:d.ok,outcome:d.outcome??d.reason}),d),u=d=>c({ok:!1,reason:d});try{let d=t.memoryTurn;if(!bue()||!d||!d.progressive)return u("memory_disabled");if(!d.isInboxOwner)return u("not_owner");if(!s||s.length>jbr||!Gbr.test(s))return u("invalid_key");let f=null;if(n==="set"){let[m,A]=Wbr(e.directive);if(A)return u(A);f=m}if(a=1,e.key_type!==void 0&&e.key_type!==null){if(!e.match_value||!e.match_value.trim())return u("match_value_required");a=2}else if(e.match_value)return u("key_type_required");if(d.writes>=Ybr)return u("write_limit");d.writes+=1;let p=d.gtid||"",h;if(n==="set"){let m={gtid:p};d.quote&&(m.quote=d.quote.slice(0,Hbr));let A=Zbr(p,n,o,i,s,f,e.confirms_key,e.replaces_key),g={scope:o,tier:a,category:i,key:s,...e.key_type?{keyType:e.key_type}:{},...e.match_value?{matchValue:e.match_value}:{},directive:f??"",...e.replaces_key?{replacesKey:e.replaces_key}:{},...e.confirms_key?{confirmsKey:e.confirms_key}:{},pending:e.pending===!0,source:r?.source??"TOOL",provenance:m,...A?{idempotencyKey:A}:{}};h=await Eue(()=>Prt(t.client,g)),h.ok&&(d.remembered=!0)}else if(n==="forget"){let m={category:i,key:s,scope:o};h=await Eue(()=>mue(t.client,m))}else{let m={forgetAll:!0};h=await Eue(()=>mue(t.client,m))}return c(h)}catch{return c({ok:!1,reason:"internal_error"})}}async function Eue(t){try{let e=await t(),r=e&&typeof e=="object"&&e.data&&typeof e.data=="object"?e.data:e??{};return typeof r.outcome!="string"?{ok:!1,reason:"malformed_response"}:{ok:!0,outcome:r.outcome,resource_id:r.resourceId}}catch(e){return e instanceof ro?e.status===429?{ok:!1,reason:"rate_limited"}:{ok:!1,reason:`http_${e.status}`}:{ok:!1,reason:"network_error"}}}var Ubr,$br,qbr,jbr,Ybr,Hbr,$rt,qrt,jrt,Yrt,zbr,Gbr,Jbr,Vbr,zrt=X(()=>{"use strict";Urt();nc();Ubr=/[\x00-\x1f\x7f]/,$br=["{{","}}","```","<",">"],qbr=300,jbr=120,Ybr=3,Hbr=140,$rt=["posting-policy","draft-policy","doc-handling","workflow","numbering-format","style","vendor-mapping","contact-mapping","sender-handling","autonomy-grant"],qrt=["set","forget","forget_all"],jrt=["this_org","all_orgs"],Yrt=["SENDER_ADDRESS","SENDER_DOMAIN","VENDOR_NAME","SUBJECT_TOKEN"],zbr={this_org:"ORG_USER",all_orgs:"USER"},Gbr=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Jbr=/https?:\/\//i,Vbr=/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/});async function bH(t,e){return t.list("/api/v1/organization-users",e)}async function CH(t,e){return t.search("/api/v1/organization-users/search",e)}async function Ev(t,e){return t.post("/api/v1/organization-users/invite",e)}async function vH(t,e,r){return t.put(`/api/v1/organization-users/${e}`,r)}async function IH(t,e){await t.delete(`/api/v1/organization-users/${e}`)}var Cue=X(()=>{"use strict"});async function wH(t,e){return t.search("/api/v1/cashflow-transactions/search",{limit:e?.limit??100,offset:e?.offset??0,sort:{sortBy:["valueDate"],order:"DESC"}})}async function qx(t,e){return t.search("/api/v1/cashflow-transactions/search",e)}async function _H(t,e){return t.get(`/api/v1/payments/${e}`)}async function DH(t,e,r){return t.put(`/api/v1/payments/${e}`,r)}async function SH(t,e){await t.delete(`/api/v1/payments/${e}`)}var vue=X(()=>{"use strict"});async function RH(t,e,r={}){let n=Xbr.has(e)?`/api/v1/${e}`:`/api/v1/data-exports/${e}`;return t.post(n,r)}var Xbr,Iue=X(()=>{"use strict";Xbr=new Set(["statement-of-account-export"])});import{createHash as eCr}from"node:crypto";import{writeFile as tCr,mkdir as rCr}from"node:fs/promises";import{dirname as nCr,isAbsolute as iCr,join as oCr}from"node:path";async function Grt(t,e){return t.post("/api/v1/reports/sql-query/preview",{query:e})}async function wue(t,e,r={}){let n={};return r.idempotencyKey&&(n["Idempotency-Key"]=r.idempotencyKey),t.post("/api/v1/reports/sql-query/export",{query:e},{headers:n})}async function _ue(t,e){return t.get(`/api/v1/reports/sql-query/export/${e}`)}function sCr(t){return eCr("sha256").update(t).digest("hex").slice(0,16)}async function Jrt(t,e,r={}){let n=Math.max(1,Math.min(r.timeoutSeconds??25,90)),i=sCr(e),o=await wue(t,e,{idempotencyKey:i}),s=o.data.jobId,a=Date.now()+n*1e3,c=o.data;for(;Date.now()<a&&!(c.status==="COMPLETED"||c.status==="FAILED"||c.status==="EXPIRED"||(await new Promise(p=>setTimeout(p,2e3)),Date.now()>=a));)c=(await _ue(t,s)).data;if(c.status==="PENDING"||c.status==="RUNNING")return{data:{jobId:s,status:"TIMED_OUT",downloadUrl:c.downloadUrl}};if(c.status!=="COMPLETED"||!c.downloadUrl)return{data:{jobId:s,status:c.status,rowCount:c.rowCount,error:c.error,downloadUrl:c.downloadUrl}};if(!r.downloadToFile&&!r.returnBuffer)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl}};let u=await fetch(c.downloadUrl);if(!u.ok)return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,error:`fetch ${u.status}`}};let d=Buffer.from(await u.arrayBuffer());if(r.downloadToFile){let f=process.env.HOME??".";if(r.outPath&&!iCr(r.outPath))throw new Error(`outPath must be absolute; got "${r.outPath}".`);let p=r.outPath??oCr(f,"Downloads",`pseudo-sql-${s}.csv`);return await rCr(nCr(p),{recursive:!0}),await tCr(p,d),{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,localPath:p}}}return{data:{jobId:s,status:"COMPLETED",rowCount:c.rowCount,truncated:c.truncated,downloadUrl:c.downloadUrl,buffer:d}}}async function Vrt(t){let e=await t.get("/api/v1/reports/sql-query/schema"),r=e.data;if(!r?.version||!Array.isArray(r.tables)||!Array.isArray(r.joins)||!Array.isArray(r.functions)||!r.agentSkillsDoc?.content)throw new Error("pseudo-sql schema: upstream returned malformed response");return e}var Wrt=X(()=>{"use strict"});async function BH(t){return t.get("/api/v1/capsule-recipes")}async function xH(t,e){return t.get(`/api/v1/capsule-recipes/${encodeURIComponent(e)}`)}async function TH(t,e){return t.post("/api/v1/capsule-recipes/preview",e)}async function kH(t,e){return t.post(`/api/v1/capsule-recipes/resume/${encodeURIComponent(e)}`)}async function NH(t,e,r={}){return t.post(`/api/v1/capsule-recipes/rollback/${encodeURIComponent(e)}`,{dryRun:r.dryRun??!1})}function na(t){if(!t||typeof t!="object")throw new Error("capsuleRecipe must be an object with {recipeName, inputs, recipeVersion?, base-trx triplet?}.");let e=t;if(typeof e.recipeName!="string"||e.recipeName.trim()==="")throw new Error("capsuleRecipe.recipeName is required (non-empty string). Source of truth: list_capsule_recipes.");if(e.recipeVersion!==void 0&&(typeof e.recipeVersion!="number"||!Number.isInteger(e.recipeVersion)||e.recipeVersion<1))throw new Error("capsuleRecipe.recipeVersion must be a positive integer when supplied.");if(e.inputs===null||e.inputs===void 0||typeof e.inputs!="object"||Array.isArray(e.inputs))throw new Error("capsuleRecipe.inputs is required and must be a non-null object (recipe-specific shape; see descriptor.versions[].inputSchema).");let r=["baseTransactionResourceId","baseTransactionType","organizationResourceId"],n=r.filter(i=>e[i]!==void 0&&e[i]!==null);if(n.length>0&&n.length<r.length)throw new Error(`capsuleRecipe base-transaction triplet is all-or-nothing \u2014 supply all of [baseTransactionResourceId, baseTransactionType, organizationResourceId] or none. Currently supplied: [${n.join(", ")}].`);if(e.templateOverrides!==void 0&&e.templateOverrides!==null){if(!Array.isArray(e.templateOverrides))throw new Error("capsuleRecipe.templateOverrides must be an array of {slotKey, template?} when supplied.");let i=new Set;e.templateOverrides.forEach((o,s)=>{if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`capsuleRecipe.templateOverrides[${s}] must be an object {slotKey, template?}.`);let a=o;if(typeof a.slotKey!="string"||a.slotKey.trim()==="")throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey is required (non-empty string). Valid keys: get_capsule_recipe \u2192 versions[].templateSlots[].slotKey.`);if(a.slotKey.length>128)throw new Error(`capsuleRecipe.templateOverrides[${s}].slotKey exceeds 128 chars.`);if(i.has(a.slotKey))throw new Error(`capsuleRecipe.templateOverrides has a duplicate slotKey "${a.slotKey}" \u2014 one override per slot.`);if(i.add(a.slotKey),a.template!==void 0&&a.template!==null){if(typeof a.template!="string")throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template must be a string, or null to clear a nullable slot.`);if(a.template.length>2e3)throw new Error(`capsuleRecipe.templateOverrides[slotKey="${a.slotKey}"].template exceeds 2000 chars.`)}})}}var Due=X(()=>{"use strict"});async function oi(t,e,r){let n=await t.get(`/api/v1/${e}/${r}/attachments`),i=n?.attachments??n?.data;return{data:Array.isArray(i)?i.map(s=>({...s,resourceId:s.resourceId??s.attachmentResourceId??""})):[]}}async function FH(t,e){let{businessTransactionType:r,businessTransactionResourceId:n,...i}=e,o=new FormData;return i.file&&o.append("file",i.file,i.fileName??"file"),i.attachmentId&&o.append("attachmentId",i.attachmentId),t.postMultipart(`/api/v1/${r}/${n}/attachments`,o)}async function QH(t,e,r,n){return t.delete(`/api/v1/${e}/${r}/attachments/${n}`)}var OH,zh=X(()=>{"use strict";OH=["sale-quotes","sale-orders","purchase-requests","purchase-orders"]});function Ua(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var LH=X(()=>{"use strict"});async function MH(t,e){return t.post("/api/v1/claims/conversion/preview",e)}async function PH(t,e){if(e.idempotencyKey&&/^CONV[:-]/.test(e.idempotencyKey))throw new Error('idempotencyKey must not start with "CONV:" or "CONV-" (reserved).');return t.post("/api/v1/claims/conversion/commit",e)}var jx,Sue=X(()=>{"use strict";jx=["POST","POST_AND_RECORD"]});async function UH(t,e){if(!(e.amount>0))throw new Error("amount must be greater than 0.");return t.post("/api/v1/claims/payouts/record",e)}async function $H(t,e){return t.search("/api/v1/employees/payouts/search",e)}var Zrt,Rue=X(()=>{"use strict";Zrt=["REIMBURSEMENT","ADVANCE"]});function Krt(t){return{source:t.source,sourceType:t.sourceType,...t.cloudProvider?{cloudProvider:t.cloudProvider}:{},summary:t.summary,files:t.folders.flatMap(e=>e.files.map(r=>({filename:r.filename,folder:r.folder,documentType:r.documentType,confidence:r.confidence,sizeBytes:r.sizeBytes,encrypted:!!r.encrypted,merged:!!r.merged,reason:r.reason})))}}var Xrt=X(()=>{"use strict"});import{randomUUID as aCr}from"node:crypto";import{rmSync as cCr}from"node:fs";function xue(t){for(let e of t.tempDirs??[])try{cCr(e,{recursive:!0,force:!0})}catch{}}function tnt(t){for(let[e,r]of cy)t-r.createdAt>ent&&(xue(r.plan),cy.delete(e))}function uCr(){Bue||(Bue=setInterval(()=>tnt(Date.now()),lCr),Bue.unref?.())}function rnt(t,e){let r=Date.now();tnt(r),uCr();let n=`dc_${aCr()}`;return cy.set(n,{plan:t,createdAt:r,ownerKey:e}),n}function nnt(t,e){let r=cy.get(t);return!r||r.ownerKey!==e?null:Date.now()-r.createdAt>ent?(xue(r.plan),cy.delete(t),null):r.plan}function int(t,e){let r=cy.get(t);!r||r.ownerKey!==e||(xue(r.plan),cy.delete(t))}var ent,lCr,cy,Bue,ont=X(()=>{"use strict";ent=1800*1e3,lCr=300*1e3,cy=new Map});function dCr(t){if(!t||typeof t!="object")return;let e=t;return e.validFiles?.[0]?.workflowResourceId??e.workflowResourceId}function fCr(t,e){let r=new Set(e);return{...t,folders:t.folders.map(n=>({...n,files:n.files.filter(i=>MO(i.documentType)&&r.has(i.documentType))}))}}async function snt(t){let{plan:e,client:r,bankAccountId:n,documentTypes:i}=t,o=i&&i.length>0?fCr(e,i):e;if(!n&&pCr(o))throw new Error("This collection contains bank statements \u2014 provide a bankAccountId, or pass documentTypes without BANK_STATEMENT to extract the rest first.");let s=await V1({plan:o,client:r,bankAccountId:n}),a=s.results.map(u=>({file:u.file,type:u.type,status:u.status,workflowId:u.status==="uploaded"?dCr(u.response):void 0,error:u.error})),c=a.map(u=>u.workflowId).filter(u=>!!u);return{total:s.total,uploaded:s.success,skipped:a.filter(u=>u.status==="skipped").length,failed:s.failed,workflowIds:c,files:a}}function pCr(t){return t.folders.some(e=>e.files.some(r=>r.documentType==="BANK_STATEMENT"))}var ant=X(()=>{"use strict";PW();Tf()});async function $u(t,e,r){if(!e)return t;let n=hCr(t);if(!n)return t;try{return await r(n)}catch(i){let o=i instanceof Error?i.message:String(i),s={status:"failed",resourceId:n,message:o};return t&&typeof t=="object"?{...t,_hydration:s}:{result:t,_hydration:s}}}function hCr(t){if(!t||typeof t!="object")return;let e=t,r=e.data?.resourceId;if(typeof r=="string"&&r.length>0)return r;let n=e.resourceId;if(typeof n=="string"&&n.length>0)return n}var cnt=X(()=>{"use strict"});async function qH(t,e){return t.list("/api/v1/bank-rules",e)}async function Yx(t,e){let r=await t.get(`/api/v1/bank-rules/${e}`),n=r;if(n?.data&&Array.isArray(n.data.data)&&n.data.data.length>0)return{data:n.data.data[0]};let i=r;if(i?.data&&typeof i.data=="object"&&i.data!==null&&"resourceId"in i.data)return{data:i.data};throw new Error(`Unexpected response shape from GET /bank-rules/${e}`)}async function jH(t,e){return t.search("/api/v1/bank-rules/search",e)}async function YH(t,e){return t.post("/api/v1/bank-rules",e)}async function HH(t,e,r){return t.put(`/api/v1/bank-rules/${e}`,r)}async function zH(t,e){await t.delete(`/api/v1/bank-rules/${e}`)}var Tue=X(()=>{"use strict"});async function GH(t,e){return t.list("/api/v1/fixed-assets",e)}async function JH(t,e){return t.get(`/api/v1/fixed-assets/${e}`)}async function VH(t,e){return t.search("/api/v1/fixed-assets/search",{...e,sort:e.sort??{sortBy:["purchaseDate"],order:"DESC"}})}async function WH(t,e){return t.post("/api/v1/fixed-assets",e)}async function ZH(t,e,r){return t.put(`/api/v1/fixed-assets/${e}`,r)}async function KH(t,e){await t.delete(`/api/v1/fixed-assets/${e}`)}async function XH(t,e,r){return t.post(`/api/v1/discard-fixed-assets/${e}`,{...r,resourceId:e})}async function Hx(t,e){return t.post("/api/v1/mark-as-sold/fixed-assets",e)}async function ez(t,e){return t.post("/api/v1/transfer-fixed-assets",e)}async function tz(t,e){return t.post(`/api/v1/undo-disposal/fixed-assets/${e}`,{})}async function rz(t,e){return Zo(t,"/api/v1/fixed-assets/bulk-upsert","fixedAssets",e)}var nz=X(()=>{"use strict";Ba()});async function iz(t,e){return t.list("/api/v1/scheduled/subscriptions",e)}async function zx(t,e){return t.get(`/api/v1/scheduled/subscriptions/${e}`)}async function oz(t,e){return t.post("/api/v1/scheduled/subscriptions",e)}async function sz(t,e,r){let n={...r};if(n.endDate){let i=!n.startDate,o=!n.repeat&&!n.interval;if(i||o){let s=await zx(t,e);if(i&&(n.startDate=s.data.startDate),o){if(!s.data.interval)throw new Error("Subscription missing repeat configuration \u2014 cannot auto-fill for update");n.repeat=s.data.interval}}}return t.put(`/api/v1/scheduled/subscriptions/${e}`,n)}async function az(t,e){await t.delete(`/api/v1/scheduled/subscriptions/${e}`)}async function cz(t,e,r){return t.put(`/api/v1/scheduled/cancel-subscriptions/${e}`,{resourceId:e,cancelDateType:r?.cancelDateType??"END_OF_CURRENT_PERIOD",proratedAdjustmentLineText:r?.proratedAdjustmentLineText??"Prorated adjustment",...r?.endDate?{endDate:r.endDate}:{}})}async function lz(t,e){return t.search("/api/v1/scheduled-transaction/search",{...e,sort:e.sort??{sortBy:["startDate"],order:"DESC"}})}var kue=X(()=>{"use strict"});async function uz(t,e){return t.list("/api/v1/contact-groups",e)}async function dz(t,e){return t.get(`/api/v1/contact-groups/${e}`)}async function fz(t,e){return t.search("/api/v1/contact-groups/search",e)}async function pz(t,e){return t.post("/api/v1/contact-groups",e)}async function hz(t,e,r){return t.put(`/api/v1/contact-groups/${e}`,r)}async function mz(t,e){await t.delete(`/api/v1/contact-groups/${e}`)}var Nue=X(()=>{"use strict"});async function Az(t,e){return t.list("/api/v1/inventory-items",e)}async function gz(t,e){return t.post("/api/v1/inventory-items",e)}async function yz(t,e){return t.get(`/api/v1/inventory-item-balance/${e}`)}var Oue=X(()=>{"use strict"});async function Ez(t,e){return t.list("/api/v1/custom-fields",e)}async function bz(t,e){return t.get(`/api/v1/custom-fields/${e}`)}async function Cz(t,e){return t.search("/api/v1/custom-fields/search",e)}async function vz(t,e){return t.post("/api/v1/custom-fields",e)}async function Iz(t,e,r){return t.put(`/api/v1/custom-fields/${e}`,r)}async function wz(t,e){await t.delete(`/api/v1/custom-fields/${e}`)}var Fue=X(()=>{"use strict"});function lnt(t){return{updated:t.updated??[],failed:(t.failed??[]).map(e=>({...e,errorCode:e.errorCode??"UNKNOWN_ERROR"}))}}async function Gx(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}`,r);return lnt(n)}async function Jx(t,e,r){let n=await t.post(`/api/v1/quick-fix/${e}/line-items`,r);return lnt(n)}var mCr,ACr,gCr,bv,Que=X(()=>{"use strict";mCr=["invoices","bills","customer-credit-notes","supplier-credit-notes"],ACr=["journals","cash-entries"],gCr=["sale-schedules","purchase-schedules","subscription-schedules","journal-schedules"],bv=[...mCr,...ACr,...gCr]});async function _z(t,e){return t.list("/api/v1/nano-classifiers",e)}async function Dz(t,e){return{data:(await t.get(`/api/v1/nano-classifiers/${e}`)).data.data[0]}}async function Sz(t,e){return t.search("/api/v1/nano-classifiers/search",e)}async function Vx(t,e){return t.post("/api/v1/nano-classifiers",{...e,printable:e.printable??!1})}async function Wx(t,e,r){return t.put(`/api/v1/nano-classifiers/${e}`,r)}async function Rz(t,e){await t.delete(`/api/v1/nano-classifiers/${e}`)}var Lue=X(()=>{"use strict"});async function Bz(t,e){return t.post("/api/v1/export-records",e)}async function xz(t,e){return t.post("/api/v1/export-records/preview",e)}async function Tz(t,e){return t.get(`/api/v1/export-records/columns/${e}`)}var Mue=X(()=>{"use strict"});async function Zx(t,e={}){return t.search("/api/v1/background-jobs/search",e)}var Pue=X(()=>{"use strict"});function Cv(t){ei(t,"items"),t.forEach((e,r)=>{if(!e||typeof e!="object")throw new Error(`items[${r}] must be an object with {btResourceId, btType}.`);let n=e;if(typeof n.btResourceId!="string"||n.btResourceId.trim()==="")throw new Error(`items[${r}].btResourceId is required (non-empty string).`);if(typeof n.btType!="string"||!yCr.has(n.btType))throw new Error(`items[${r}].btType must be one of SALE | PURCHASE | SALE_CREDIT_NOTE | PURCHASE_CREDIT_NOTE.`)})}async function kz(t,e){let r=await t.post("/api/v1/drafts/validate",{items:e});return{data:bCr(r.data)}}function ECr(t){return{btResourceId:t.btResourceId,btType:t.btType,eligible:t.eligible,errors:t.errors,displayData:t.displayData,contactSignals:t.contactInsight??null,breakdown:t.breakdown??null}}function bCr(t){return{eligibleCount:t.eligibleCount,ineligibleCount:t.ineligibleCount,results:t.results.map(ECr),columns:t.columns,errorColumns:t.errorColumns,contactSignalsMeta:t.contactInsightsMeta??null}}async function Nz(t,e){return t.post("/api/v1/drafts/convert-to-active",{items:e})}async function Oz(t,e){return t.post("/api/v1/drafts/submit-for-approval",{items:e})}var yCr,Uue=X(()=>{"use strict";Ba();yCr=new Set(["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"])});function dnt(t){let e=t??{},r=n=>Array.isArray(n)&&n.length>0;if(!r(e.businessTransactionPayments)&&!r(e.matchedPayments)&&!r(e.matchedBatchPayments))throw new Error("at least one of businessTransactionPayments, matchedPayments, or matchedBatchPayments must be non-empty.")}function $ue(t,e){if(!t||typeof t!="object")throw new Error(`${e} is required.`);let r=t,n=r.lineItems;if(!Array.isArray(n)||n.length===0)throw new Error(`${e}.lineItems array is empty.`);if(n.length>500)throw new Error(`max 500 ${e}.lineItems per call.`);uc([r],["valueDate","dueDate"]);let i=r.recordedPayment;i&&typeof i=="object"&&uc([i],["valueDate"])}function ICr(t,e){let r=typeof e=="number"&&!Number.isNaN(e)?e:void 0,n=typeof t=="number"&&!Number.isNaN(t)?t:void 0;if(r!==void 0)return r>=CCr?"high":r>=unt?"medium":"low";if(n!==void 0){if(n>=vCr)return"high";if(n>=unt)return"medium"}return"low"}function fnt(t,e={}){let r=t??{},i=((r.statementLines?r:r.data)??r).statementLines;if(!Array.isArray(i))return[];let o=[];for(let s of i){let a=s??{},c=typeof a.statementResourceId=="string"?a.statementResourceId:void 0;if(!c)continue;let u=Array.isArray(a.recommendations)?a.recommendations:[];if(u.length===0){o.push({bankStatementEntryResourceId:c,confidenceTier:"low",autoCommitEligible:!1,alternativeCount:0});continue}let d=u.slice().sort((D,x)=>{let L=D.confidenceScore??D.matchScore??-1;return(x.confidenceScore??x.matchScore??-1)-L}),f=d[0],p=typeof f.recommendationType=="string"?f.recommendationType:void 0,h=typeof f.matchScore=="number"?f.matchScore:void 0,m=typeof f.confidenceScore=="number"?f.confidenceScore:void 0,A=typeof f.isCrossCurrency=="boolean"?f.isCrossCurrency:void 0,g=typeof f.cftBtResourceId=="string"?f.cftBtResourceId:void 0,y=Array.isArray(f.cftBtResourceIds)?f.cftBtResourceIds:[],C=f.isBatch===!0||y.length>1,E=typeof f.cftAmount=="number"?f.cftAmount:void 0,v,I;switch(p){case"MAGIC_MATCH":{C&&y.length>0?(v=Kx.magicMatch,I={...e.bankAccountResourceId?{bankAccountResourceId:e.bankAccountResourceId}:{},entries:[{workflowType:"MAGIC_MATCH",bankStatementEntryResourceId:c,matchedBusinessTransactions:y}]}):g&&(v=Kx.withPayments,I={bankStatementEntryResourceId:c,businessTransactionPayments:[{cashflowTransactionResourceId:g,...E!==void 0?{transactionAmount:E}:{}}]});break}case"MAGIC_RECONCILE_WITH_CASH_IN_OUT":{let D=typeof f.learnedPredictionResourceId=="string"?f.learnedPredictionResourceId:void 0,x=typeof f.predictedPayload=="string"?f.predictedPayload:void 0,L=typeof f.predictedPayloadSchemaVersion=="string"?f.predictedPayloadSchemaVersion:void 0;D&&x&&L&&(v=Kx.learnedPrediction,I={bankStatementEntryResourceId:c,learnedPredictionResourceId:D,predictedPayload:x,predictedPayloadSchemaVersion:L});break}case"MAGIC_RECONCILE_WITH_BANK_RULE":{let D=f.actionShortcut??{},x=typeof D.resourceId=="string"?D.resourceId:void 0;x&&(v=Kx.applyBankRule,I={actionShortcutResourceId:x,businessTransactionResourceIds:[c]});break}default:break}let k=v?ICr(h,m):"low",S=typeof E=="number"&&!Number.isNaN(E),N=!(e.autoCommitMaxAmount!==void 0)||S&&Math.abs(E)<=e.autoCommitMaxAmount,H=v!==Kx.withPayments||S,q=k==="high"&&!!v&&!!I&&H&&N;o.push({bankStatementEntryResourceId:c,recommendationType:p,matchScore:h,confidenceScore:m,isCrossCurrency:A,recommendedTool:v,execute:I,confidenceTier:k,autoCommitEligible:q,alternativeCount:d.length-1,matchAmount:E,matchedTransactionResourceId:g??y[0],matchedTransactionCount:y.length||(g?1:void 0)})}return o}function _Cr(t,e,r){return{bankStatementEntryResourceId:t.bankStatementEntryResourceId,confidenceTier:t.confidenceTier,recommendationType:t.recommendationType,recommendedTool:t.recommendedTool,execute:t.execute,bankLine:e,match:r}}async function DCr(t,e,r){let n=e.matchedTransactionResourceId,i=e.matchedTransactionCount;if(!n)return e.matchAmount!==void 0?{type:"transaction",amount:e.matchAmount,count:i}:null;let o=(r??0)<0?["bill","invoice"]:["invoice","bill"];for(let s of o)try{let{data:a}=s==="bill"?await vs(t,n):await _s(t,n);return{type:s,reference:a.reference,amount:e.matchAmount??a.totalAmount,documentTotalAmount:a.totalAmount,count:i,resourceId:n}}catch{}return{type:"transaction",amount:e.matchAmount,count:i,resourceId:n}}async function pnt(t,e,r){let n=r.filter(o=>o.recommendedTool&&!o.autoCommitEligible).slice(0,wCr);if(n.length===0)return[];let i=new Map;if(e)try{let o=await ub(t,e,{filter:{status:{eq:"UNRECONCILED"}},limit:500});for(let s of o.data??[])i.set(s.resourceId,s)}catch{}return Promise.all(n.map(async o=>{let s=i.get(o.bankStatementEntryResourceId),a=s?{valueDate:s.valueDate,netAmount:s.netAmount,currencyCode:s.currencyCode,currencySymbol:s.currencySymbol,description:s.description,counterparty:s.extContactName}:null;return _Cr(o,a,await DCr(t,o,a?.netAmount))}))}async function Fz(t,e){return t.post("/api/v1/reconciliations/quick-reconcile",e)}async function Qz(t,e){return t.post("/api/v1/reconciliations/bank-rule",e)}async function Lz(t,e){return t.post("/api/v1/reconciliations/direct-cash-entry",e)}async function Mz(t,e){return t.post("/api/v1/reconciliations/cash-journal",e)}async function Pz(t,e){return t.post("/api/v1/reconciliations/manual-journal",e)}async function Uz(t,e){return t.post("/api/v1/reconciliations/cash-transfer",e)}async function $z(t,e){return t.post("/api/v1/reconciliations/invoice-receipt",e)}async function qz(t,e){return t.post("/api/v1/reconciliations/bill-receipt",e)}async function jz(t,e){return t.post("/api/v1/reconciliations/with-payments",e)}async function Yz(t,e){return t.post("/api/v1/reconciliations/learned-prediction",e)}async function Hz(t,e){return t.post("/api/v1/reconciliations/magic-match",e)}var Kx,CCr,vCr,unt,wCr,que=X(()=>{"use strict";Zf();Kf();Ba();FA();Kx={withPayments:"reconcile_with_payments",magicMatch:"reconcile_magic_match",applyBankRule:"apply_bank_rule",learnedPrediction:"reconcile_learned_prediction"},CCr=.9,vCr=.95,unt=.7;wCr=25});function Ns(t,e,r="lineItems"){let n=[];for(let i of e)if(i.perLineItem){let o=t[r]??[];for(let s=0;s<o.length;s++)i.check(o[s])||n.push(`${r}[${s}].${i.field}`)}else i.check(t)||n.push(i.field);return{missingFields:n,missingCount:n.length,ready:n.length===0}}function fo(t,e,r="lineItems"){let n=e.filter(a=>!a.perLineItem),i=e.filter(a=>a.perLineItem),o={valueDate:jue(t,"valueDate","Date","--date <YYYY-MM-DD>",n),lineItems:[]};n.some(a=>a.field==="contactResourceId")&&(o.contact=jue(t,"contactResourceId","Contact","--contact <name or UUID>",n)),n.some(a=>a.field==="dueDate")&&(o.dueDate=jue(t,"dueDate","Due date","--due <YYYY-MM-DD>",n));let s=t[r]??[];return o.lineItems=s.map((a,c)=>{let u=a.accountResourceId||a.organizationAccountResourceId,d=u?{status:"ok",resourceId:u}:{status:"missing",hint:"--account <name or UUID>"};if(r==="journalEntries"){let A=i.find(I=>I.field==="amount"),g=A?A.check(a):!0,y=a.amount??a.debitAmount??a.creditAmount??null,C=a.debitAmount,E=a.creditAmount,v=a.type??(typeof C=="number"&&C>0?"DEBIT":typeof E=="number"&&E>0?"CREDIT":null);return{index:c,name:a.description||v||null,nameStatus:"ok",unitPrice:y,unitPriceStatus:g?"ok":"missing",account:d}}let f=i.find(A=>A.field==="name"),p=i.find(A=>A.field==="unitPrice"),h=f?f.check(a):!0,m=p?p.check(a):!0;return{index:c,name:a.name||null,nameStatus:h?"ok":"missing",unitPrice:a.unitPrice??null,unitPriceStatus:m?"ok":"missing",account:d}}),o}function jue(t,e,r,n,i){let o=i.find(s=>s.field===e);if(!o){let s=t[e];return s?{status:"ok",value:s}:{status:"ok"}}if(o.check(t)){let s=t[e];return e==="contactResourceId"?{status:"ok",value:t.contactName||s,resourceId:s}:{status:"ok",value:s}}return{status:"missing",hint:n}}function To(t,e,r,n="lineItems"){let{missingFields:i,missingCount:o,ready:s}=Ns(t,e,n),a=fo(t,e,n);return{resourceId:t.resourceId,reference:t.reference||null,totalAmount:t.totalAmount??0,attachmentCount:r,ready:s,missingCount:o,missingFields:i,validation:a}}var ia,Qc,Ki,Ql,hnt=X(()=>{"use strict";ia=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"dueDate",label:"Due date",hint:"--due <YYYY-MM-DD>",check:t=>!!t.dueDate},{field:"lineItems",label:"Line items",hint:"--lines <json>",check:t=>t.lineItems?.length>0},{field:"name",label:"Item name",hint:"via --lines",check:t=>!!t.name,perLineItem:!0},{field:"unitPrice",label:"Unit price",hint:"via --lines",check:t=>t.unitPrice!=null,perLineItem:!0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0}],Qc=[...ia],Ki=ia.filter(t=>t.field!=="dueDate"),Ql=[{field:"valueDate",label:"Date",hint:"--date <YYYY-MM-DD>",check:t=>!!t.valueDate},{field:"journalEntries",label:"Journal entries",hint:"--entries <json>",check:t=>t.journalEntries?.length>0},{field:"accountResourceId",label:"Account",hint:"--account <name or UUID>",check:t=>!!(t.accountResourceId||t.organizationAccountResourceId),perLineItem:!0},{field:"amount",label:"Amount",hint:"via --entries",check:t=>t.amount!=null&&t.amount>0||t.debitAmount!=null&&t.debitAmount>0||t.creditAmount!=null&&t.creditAmount>0,perLineItem:!0}]});function Lc(t){let e={};t.name!=null&&(e.name=t.name),t.quantity!=null&&(e.quantity=t.quantity),t.unitPrice!=null&&(e.unitPrice=t.unitPrice),t.unit&&(e.unit=t.unit);let r=t.accountResourceId||t.organizationAccountResourceId;r&&(e.accountResourceId=r);let n=t.taxProfileResourceId||(t.taxProfile&&typeof t.taxProfile=="object"?t.taxProfile.resourceId:null);return n&&(e.taxProfileResourceId=n),t.itemResourceId&&(e.itemResourceId=t.itemResourceId),t.discount!=null&&(e.discount=typeof t.discount=="object"?t.discount.rateValue??0:t.discount),e}function vv(t){let e={},r=t.accountResourceId||t.organizationAccountResourceId;return r&&(e.accountResourceId=r),t.amount!=null?e.amount=t.amount:t.debitAmount!=null&&t.debitAmount>0?e.amount=t.debitAmount:t.creditAmount!=null&&t.creditAmount>0&&(e.amount=t.creditAmount),t.type?e.type=t.type:t.debitAmount!=null&&t.debitAmount>0?e.type="DEBIT":t.creditAmount!=null&&t.creditAmount>0&&(e.type="CREDIT"),t.description&&(e.description=t.description),t.contactResourceId&&(e.contactResourceId=t.contactResourceId),e}function Lt(t){if(t)return t.split("T")[0]}var Yue=X(()=>{"use strict"});function qu(t,e){let r={};if(e.contact&&(r.contactResourceId=e.contact),e.date&&(r.valueDate=e.date),e.due&&(r.dueDate=e.due),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.tag!==void 0&&(r.tag=e.tag),e.tax&&(r.isTaxVatApplicable=!0),e.tax&&e.taxInclusive?r.taxInclusion=!0:e.tax&&(r.taxInclusion=!1),e.lines)r.lineItems=e.lines;else if(e.account||e.taxProfile){let n=t.lineItems??[];r.lineItems=n.map(i=>{let o=Lc(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),e.taxProfile&&!o.taxProfileResourceId&&(o.taxProfileResourceId=e.taxProfile),o})}return r}function zz(t,e){let r={};if(e.date&&(r.valueDate=e.date),e.ref!==void 0&&(r.reference=e.ref),e.notes!==void 0&&(r.notes=e.notes),e.entries)r.journalEntries=e.entries;else if(e.account){let n=t.journalEntries??[];r.journalEntries=n.map(i=>{let o=vv(i);return e.account&&!o.accountResourceId&&(o.accountResourceId=e.account),o})}return r}var mnt=X(()=>{"use strict";Yue()});var Hue=X(()=>{"use strict";hnt();Yue();mnt()});var Xx,Ll,Ant=X(()=>{"use strict";Xx="{{Day}}, {{Date}}, {{Date+X}}, {{DateRange:X}}, {{Month}}, {{Month+X}}, {{MonthRange:X}}, {{Year}}, {{Year+X}}",Ll="Async; returns jobId \u2192 poll search_background_jobs by resourceId; PARTIAL_SUCCESS data[0].errorDetails."});import{randomUUID as SCr}from"node:crypto";function Nnt(t){let e=t.limit,r=t.offset;return{limit:e,offset:r,sortBy:void 0,sortOrder:void 0}}function pr(t,e,r,n,i,o){let s={...Zue};return o?.leanView&&(s.view={type:"string",enum:["lean","full"],description:"Payload tier: 'lean' (default) = summary row (id + key scalars); 'full' = whole entity per row (heavier). List lean, then drill in with get_*."}),{name:t,description:e,params:s,required:[],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:5e4,...i?{searchHint:i}:{},execute:async(a,c)=>{let{limit:u,offset:d}=Nnt(c),f=o?.leanView?c.view==="full"?"full":"lean":void 0;return ID((h,m)=>n(a.client,h,m,f),u,d,f==="lean"?50:20)}}}function _i(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!0,isConcurrencySafe:!0,maxResultSizeChars:2e4,...i?{searchHint:i}:{},execute:async(o,s)=>n(o.client,s.resourceId)}}function Ti(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,isDestructive:!0,...i?{searchHint:i}:{},execute:async(o,s)=>(await n(o.client,s.resourceId),{deleted:!0,resourceId:s.resourceId})}}function Wue(t,e,r,n,i){return{name:t,description:e,params:{resourceId:{type:"string",description:"Resource ID (UUID)"}},required:["resourceId"],group:r,readOnly:!1,...i?.destructive?{isDestructive:!0}:{},...i?.searchHint?{searchHint:i.searchHint}:{},execute:async(o,s)=>n(o.client,s.resourceId)}}function wnt(t){if(typeof t!="string"||/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let e=/^(\d{4}-\d{2}-\d{2})T/.exec(t);return e?e[1]:t}function NCr(t){return Array.isArray(t)?t.map(e=>{let r={};for(let[n,i]of Object.entries(e))if(i!=null)if(n==="organizationAccountResourceId")r.accountResourceId=i;else if(n==="taxProfile"&&typeof i=="object"&&i!==null){let o=i.resourceId;o&&(r.taxProfileResourceId=o)}else if(n==="discount"&&typeof i=="object"&&i!==null){let o=i.rateValue;o&&Number(o)!==0&&(r.discount=i)}else kCr.has(n)&&(r[n]=i);return r}):t}async function rT(t,e,r,n){let s=(await(e==="invoice"?_s:e==="bill"?vs:e==="customer_credit_note"?vl:Il)(t,r)).data,a=TCr[e],c={};for(let[p,h]of Object.entries(s))a.has(p)&&h!==null&&h!==void 0&&(c[p]=h);c.valueDate&&(c.valueDate=wnt(c.valueDate)),c.dueDate&&(c.dueDate=wnt(c.dueDate)),c.lineItems&&(c.lineItems=NCr(c.lineItems));for(let[p,h]of Object.entries(n))h!==void 0&&(c[p]=h);let u=e==="invoice"?Qc:e==="bill"?ia:Ki,{missingFields:d,ready:f}=Ns(c,u);if(!f)throw new Error(`Cannot finalize: missing ${d.join(", ")}. Use search_accounts (filter by accountType) and search_contacts to resolve, then pass the missing fields to this tool.`);return c}async function _nt(t,e,r,n){if((await t(e,r)).data.status==="DRAFT")throw new Error(`Cannot pay a DRAFT ${n}. Finalize it first with finalize_${n}.`)}function Vz(t,e,r){if(!(typeof t=="string"&&e.includes(t)))return{error:`Unknown documentType ${JSON.stringify(t)}.`,status:422,hint:`Use one of: ${e.join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}}}function Rnt(t,e,r){let n=Snt[t];if(!n)return{error:`Unknown documentType "${t}".`,status:422,hint:`Valid document types: ${Object.keys(Snt).join(", ")}.`,repair:{tool:r,arguments:{},reason:"Pass a supported documentType."}};if(!n.includes(e)){let i=n.includes("ACCEPT")?"ACCEPT":"CONFIRM";return{error:`Action "${e}" is not valid for ${t}. Valid actions: ${n.join(", ")}.`,status:422,hint:`${t} advances its lifecycle with ${i}, not ${e}.`,repair:{tool:r,arguments:{documentType:t,action:i},reason:`${t} is advanced with ${i}.`}}}}async function Bnt(t,e,r,n,i,o,s){let a;try{a=(await e(t,r)).data?.status}catch{return}if(a==="DRAFT"||a==="VOID"){let c=a==="DRAFT"?`A DRAFT ${n} can't be linked or accepted \u2014 issue it by creating the ${n} with saveAsDraft:false (status ${s}), then link the order to that one.`:`A VOID ${n} can't be used \u2014 create a fresh ${n} (saveAsDraft:false) and link to it.`;return{error:`Cannot create an order linked to a ${a} ${n} (${r}).`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. ${c}`,repair:{tool:o,arguments:{documentType:i,saveAsDraft:!1},reason:c}}}}async function xnt(t,e,r,n,i,o){let s;try{s=(await e(t,r)).data?.status}catch{return}if(s==="VOID")return{error:`Cannot convert a VOID ${n} (${r}) into a ${i}.`,status:422,hint:`Pre-flight guard \u2014 request never hit the API. Convert a non-VOID ${n}.`,repair:{tool:o,arguments:{},reason:`The source ${n} is VOID.`}}}async function Tnt(t,e,r,n,i){let o;try{o=(await e(t,r,n)).data?.status}catch{return}if(o&&o!=="DRAFT")return{error:`Cannot DELETE a ${o} ${r} \u2014 delete is only allowed on DRAFT records.`,status:422,hint:"Use action VOID to cancel a non-draft quote/request/order.",repair:{tool:i,arguments:{documentType:r,resourceId:n,action:"VOID"},reason:`${r} is ${o}; void it instead of deleting.`}}}var $a,po,Ml,ho,si,ju,Gz,ly,zue,fy,RCr,BCr,Gue,gnt,ynt,Jue,Zue,uy,Vue,Ent,bnt,Cnt,vnt,xi,Int,eT,xCr,dy,oa,knt,Yu,tT,TCr,kCr,nT,iT,Jz,Dnt,Snt,Mc,oT=X(()=>{"use strict";SM();fQe();yQe();bD();nc();dr();pc();Um();Yb();gLe();CLe();tp();FA();Kf();bZ();CZ();iC();vZ();Zf();IL();LL();tD();IZ();ULe();t2();c2();h2();srt();rD();jL();aD();MY();uD();WM();GY();Wle();Zle();Kle();Xle();cue();fue();Lrt();Zf();Ux();pue();hue();EH();zrt();Cue();vue();Iue();Wrt();Due();zh();LH();l_();Sue();Rue();dD();FW();Xrt();ont();ant();dZ();cnt();Tue();nz();kue();Nue();Oue();Fue();Que();Lue();Mue();Pue();tp();FA();Kf();t2();c2();iC();nz();Ba();Uue();que();dr();Hue();Ant();$a={type:"string",description:"Resource ID of the record"},po={type:"string",description:"Transaction date (YYYY-MM-DD)"},Ml={type:"string",description:"Due date (YYYY-MM-DD)"},ho={type:"string",description:"Reference number"},si={type:"string",description:"Notes or memo text"},ju={type:"string",description:"Tag name for categorization"},Gz={type:"boolean",description:"Save as draft (default true). Set false to finalize immediately."},ly={type:"boolean",description:"Return full entity (default: minimal {resourceId} only). Saves a follow-up get_* round trip."},zue={type:"string",description:"Contact resourceId (customer or supplier)"},fy={type:"string",description:"Bank/cash account resourceId"},RCr={type:"number",description:"Payment amount (in bank currency)"},BCr={type:"string",description:"Period start date (YYYY-MM-DD)"},Gue={type:"string",description:"Period end date (YYYY-MM-DD)"},gnt={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.`},ynt={type:"string",description:"Currency code (e.g. SGD, USD)"},Jue={type:"string",description:"Display name"},Zue={limit:{type:"number",description:"Max results per page (\u22641000)."},offset:{type:"number",description:"Page offset (0-indexed). Use with limit to paginate."}},uy={type:"object",properties:{sourceCurrency:{type:"string"},exchangeRate:{type:"number"}}},Vue={type:"string",enum:[...Rd],description:"Entity type to export"},Ent={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.'},bnt={type:"object",description:'Raw JSON filter object (e.g., {"status":{"in":["UNPAID"]}}). Mutually exclusive with query \u2014 pass one or the other, never both.'},Cnt={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."},vnt={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."},xi={type:"array",items:{type:"object",properties:{customFieldName:{type:"string"},actualValue:{type:"string"}}},description:'Custom field values: [{ customFieldName: "PO Number", actualValue: "PO-123" }]'},Int={type:"array",description:"Full replacement line-item set \u2014 non-empty REPLACES all lines, [] clears, omit = no change. claimTypeResourceId + name + unitPrice + quantity are required at submit time.",items:{type:"object",properties:{resourceId:{type:"string",description:"Existing line resourceId (omit to add a new line)"},claimTypeResourceId:{type:"string",description:"Claim type resourceId"},name:{type:"string",description:"Line name"},description:{type:"string",description:"Line description"},unitPrice:{type:"number",description:"Unit price"},quantity:{type:"number",description:"Quantity"},currency:{type:"string",description:"Line currency (ISO 4217; falls back to header)"},itemSubTotal:{type:"number",description:"Line subtotal (unitPrice \xD7 quantity)"}}}},eT={type:"array",items:{type:"string"},description:"Claim resourceIds (1-500)"},xCr={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:$a}}},printable:{type:"boolean"}}},description:"Nano classifier config for line items. Each entry links a capsule type with selected classes."},dy={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)"},oa={type:"array",items:{type:"object",properties:{name:{type:"string",description:"Line item description/name"},quantity:{type:"number"},unitPrice:{type:"number"},accountResourceId:fy,taxProfileResourceId:{type:"string"},classifierConfig:xCr},required:["name","quantity","unitPrice"]},description:"Line items \u2014 include accountResourceId on each line when finalizing (saveAsDraft: false)"},knt={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)."},Yu={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:knt},required:["recipeName","inputs"]},tT={type:"string",enum:[...jQe],description:"Payment method (default BANK_TRANSFER)"};TCr={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"])};kCr=new Set(["name","quantity","unitPrice","unit","accountResourceId","taxProfileResourceId","description","classifierConfig","itemResourceId","discount"]);nT={type:"string",enum:["SALE_QUOTE","SALE_ORDER"],description:"Which sales document: SALE_QUOTE (estimate) or SALE_ORDER."},iT={type:"string",enum:["PURCHASE_REQUEST","PURCHASE_ORDER"],description:"Which purchase document: PURCHASE_REQUEST (requisition) or PURCHASE_ORDER."},Jz={type:"number",description:"Payment terms in days (one of 0, 7, 15, 30, 45, 60)."},Dnt={type:"string",enum:["ACCEPT","CONFIRM","VOID","DELETE"],description:"Lifecycle action. ACCEPT=quote/request only; CONFIRM=order only; VOID=any non-draft; DELETE=draft only."},Snt={SALE_QUOTE:["ACCEPT","VOID","DELETE"],SALE_ORDER:["CONFIRM","VOID","DELETE"],PURCHASE_REQUEST:["ACCEPT","VOID","DELETE"],PURCHASE_ORDER:["CONFIRM","VOID","DELETE"]};Mc=[{name:"get_organization",description:"Get organization details: name, base currency, country, and financial year end.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"get organization details currency country fiscal year",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>Aa(t.client)},{name:"get_my_context",description:"Resolve the CALLER's own context \u2014 identity, the employee bound to their login (if any), and per-module access (moduleRoles). Use to route a receipt (bill if PURCHASES access, expense claim if EMPLOYEE_CLAIMS access). A service api-key usually has no bound employee. Magic claim drafts auto-bind the uploader server-side \u2014 no need to read employee.resourceId to bind one.",params:{},required:[],group:"organization",readOnly:!0,searchHint:"who am i my employee my permissions module roles what can i do self caller capabilities bills claims",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async t=>y0e(t.client)},pr("list_accounts","List chart of accounts. Returns account name, code, type, class, status. Paginated \u2014 response includes totalElements. Use limit/offset to page.","accounts",(t,e,r)=>Dd(t,{limit:r,offset:e}),"list chart of accounts with code type class status"),Vt({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:lS,defaults:uS,fetcher:jb,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(t,e)=>{let r=e.name,n=await lM(t.client,r);if(n)return{_guard:"duplicate_skipped",message:`Account "${r}" already exists.`,existing:n};let i=qb(e.accountType);return pD(t.client,{code:e.code,name:r,accountType:i,currencyCode:e.currencyCode,lockDate:e.lockDate})}},{name:"update_account",description:"Update a chart of accounts entry \u2014 rename, re-code, set its period lock date, or remove an existing lock date. Setting lockDate (YYYY-MM-DD) is how an individual ledger account is locked for a period: it blocks recording or editing any transaction on that account dated on or before the lock date. Pass clearLockDate to remove (unlock) an existing lock.",params:{resourceId:{type:"string",description:"Account resourceId"},name:{type:"string",description:"New account name"},code:{type:"string",description:"New account code"},lockDate:{type:"string",description:"Period lock date (YYYY-MM-DD, org timezone). Blocks recording or modifying any GL transaction on this account on or before this date."},clearLockDate:{type:"boolean",description:"Set true to remove an existing period lock date (unlock the period). Use when the user asks to remove, delete, clear, lift, or unset the lock. Do not also pass lockDate."}},required:["resourceId"],group:"accounts",readOnly:!1,searchHint:"update rename chart of accounts entry name code lock date unlock remove clear lock",execute:async(t,e)=>{let r=e.resourceId,n=(await C1e(t.client,r)).data,o=Object.fromEntries(["name","code","classificationType","taxProfileResourceId","currency","description"].filter(a=>n[a]!==void 0&&n[a]!==null).map(a=>[a,n[a]]));!o.classificationType&&n.accountType&&(o.classificationType=n.accountType);let s=e.clearLockDate===!0;if(s&&e.lockDate!==void 0)throw new Error("clearLockDate and lockDate are mutually exclusive \u2014 pass one or the other.");return!s&&typeof n.accountLockDate=="string"&&n.accountLockDate&&(o.lockDate=n.accountLockDate.slice(0,10)),e.name!==void 0&&(o.name=e.name),e.code!==void 0&&(o.code=e.code),!s&&e.lockDate!==void 0&&(o.lockDate=e.lockDate),v1e(t.client,r,o)}},{name:"bulk_upsert_chart_of_accounts",description:`Bulk create/update CoA entries (max 500). SYNC: returns { resourceIds, failedRows: [{rowIndex, columnName, columnValue, errorCode, errorMessage}], failedCount } \u2014 no jobId polling. PARTIAL_SUCCESS: failed rows surface in failedRows[]; others still succeed.
|
|
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
|
|
|
@@ -864,7 +864,7 @@ btType enum: SALE = invoice, PURCHASE = bill, SALE_CREDIT_NOTE = customer CN, PU
|
|
|
864
864
|
|
|
865
865
|
Each result carries contactSignals (Mid-7: cadence, outliers, severity, divergences from contact's modal pattern; null if no contact / no history) and breakdown (Balance-panel payload: line items + subtotal/tax/total/balance/exchange rate). Top-level contactSignalsMeta.unavailable=true \u2192 freshness layer offline for whole batch.
|
|
866
866
|
|
|
867
|
-
USE THIS to score a specific draft against contact history. For stand-alone "what does this contact normally look like?" without a draft \u2192 use get_contact_signals.`,params:{items:{type:"array",description:"Draft business transaction references (max 500). Mix any btType freely.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!0,isConcurrencySafe:!0,searchHint:"validate drafts eligibility check before convert promote",execute:async(t,e)=>(Cv(e.items),kz(t.client,e.items))},{name:"convert_drafts_to_active",description:`BULK promote \u2014 finalize up to 500 draft business transactions to ACTIVE in ONE call, mixing any combination of invoices, bills, and credit notes (no per-type tools needed). ${Ll} NOT idempotent: a second call on already-promoted drafts returns 422. Filter the draft list by status: DRAFT before submitting. Pair with validate_drafts for a pre-flight check on large batches.`,params:{items:{type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!1,searchHint:"convert drafts to active promote finalize bulk",execute:async(t,e)=>(Cv(e.items),Nz(t.client,e.items))},{name:"submit_drafts_for_approval",description:`BULK submit \u2014 route up to 500 draft business transactions into the approval workflow in ONE call, mixing any combination of invoices, bills, and credit notes. ${Ll} NOT idempotent on drafts that already have an in-flight approval request.`,params:{items:{type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!1,searchHint:"submit drafts for approval workflow review bulk",execute:async(t,e)=>(Cv(e.items),Oz(t.client,e.items))},{name:"search_help_center",description:'Search the Jaz help center for how-to articles, feature guides, and accounting concepts. Use this for "how do I..." or "what is..." questions about Jaz: bank reconciliation, GST/VAT filing, multi-currency, fixed assets, custom fields, integrations, and so on. Returns top matching articles with title, section, content, and source URL.',params:{query:{type:"string",description:'Natural-language question or keywords (e.g. "how do I reconcile a bank statement", "set up GST", "multi-currency invoice").'},limit:{type:"number",description:"Maximum number of articles to return (default 3, max 10)."},section:{type:"string",description:'Optional: restrict to a single help-center section slug (e.g. "bank-reconciliations", "invoices").'}},required:["query"],group:"help_center",readOnly:!0,searchHint:"help center docs how to guide article search question",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>{let r=typeof e.limit=="number"?e.limit:void 0,n=typeof e.section=="string"?e.section:void 0;return aue(String(e.query??""),{limit:r,section:n})}},{name:"jot",description:"Record judgment entries in the org's judgment journal. THE RULE: log a judgment when you chose among real alternatives and a write followed, or when you deliberately decided NOT to write; skip mechanical actions and calls where the platform, the data, or the user left you no choice. Jot AFTER the write succeeds, never before, and carry the written record's resourceId in refs. Kinds: CLASSIFICATION account/tax/category choice \xB7 MATCH decided which records correspond \xB7 SCOPE chose what is in or out of a set \xB7 ASSUMPTION filled a gap the data left open \xB7 RISK proceeded despite a known concern \xB7 METHOD picked a calculation or approach \xB7 RECOVERY decided how to proceed after a failure (incl. holding a write) \xB7 DEVIATION knowingly departed from a stated rule. Accepting or rejecting an inbound external document (an e-invoice a counterparty sent) is a FINALIZE act, so pin it. A decided omission (you deliberately did not post something) is RECOVERY, which pins via withheld-write, not DEVIATION. Always give why: a call without a basis is half a record. Batch related entries in one call; each entry is acked independently.",params:{entries:{type:"array",description:"Judgment entries to record (1-100). A bad entry never fails the batch: it acks with error while siblings persist.",items:{type:"object",properties:{kind:{type:"string",enum:["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],description:"Judgment kind: one-liners in the tool description."},tier:{type:"string",enum:["LOW","MEDIUM","HIGH","CRITICAL"],description:"Severity you assign the call."},call:{type:"string",description:'The decision, one line (e.g. "Posted to 6420 Travel: recurring Grab vendor pattern").'},why:{type:"string",description:"The basis for the call: a call without a basis is half a record."},ruledOut:{type:"string",description:"Alternatives considered and set aside."},refs:{type:"array",description:"Entity refs this judgment touches. Include the written record's resourceId.",items:{type:"string",description:'Grammar TYPE:resourceId[#field][:RELATION], e.g. "INVOICE:41f6\u2026:CREATE". RELATION: CREATE UPDATE DELETE FINALIZE PAY RECONCILE TRIGGER SUBJECT INPUT REJECTED SUPERSEDES (default SUBJECT).'}},frame:{type:"string",description:'For set-shaped subjects: the defining query + counts (e.g. "search_bills status=UNPAID \xB7 41 in scope, 4 deferred").'},confidence:{type:"string",enum:["LOW","MEDIUM","HIGH"],description:"Routing hint for review attention."},citedRule:{type:"string",description:"Org rule, policy, threshold, or precedent applied."},workflowLabel:{type:"string",description:"Short workflow label (e.g. month-end-close)."},agentLabel:{type:"string",description:"Self-reported product/model (e.g. jaz-clio/claude); informative, never authoritative."},idempotencyKey:{type:"string",description:"Retry key: a replay returns the existing entry, not a duplicate."}},required:["kind","tier","call"]}}},required:["entries"],group:"jots",readOnly:!1,alwaysLoaded:!0,searchHint:"jot judgment judgement journal record decision log rationale reasoning why chose ruled out classification match scope assumption risk method recovery deviation basis precedent note after write",execute:async(t,e)=>gv(t.client,e.entries)},{name:"recall",description:"Search the org's judgment journal (jots) for precedents, prior judgment calls with their basis. Check BEFORE repeating a judgment on the same entity, kind of decision, or workflow: a prior call with its why beats re-deriving from scratch; a FLAG or REJECT disposition on it is a warning, ENDORSE a strong precedent. Sort is pinned server-side (CRITICAL and withheld-write RECOVERY entries first, then newest). An empty page means no prior judgments match this filter, or none are recorded for this org yet.",params:{ref:{type:"string",description:'Entity ref filter, TYPE:resourceId (e.g. "INVOICE:41f626a3-\u2026").'},kind:{type:"string",enum:["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],description:"Judgment kind filter."},tier:{type:"string",enum:["LOW","MEDIUM","HIGH","CRITICAL"],description:"Severity tier filter."},dispositionVerb:{type:"string",enum:["FLAG","REJECT","ENDORSE"],description:"Only entries carrying at least one disposition with this verb."},freetext:{type:"string",description:"Case-insensitive substring over call and why."},createdFrom:{type:"number",description:"Created-at lower bound, epoch ms (inclusive)."},createdTo:{type:"number",description:"Created-at upper bound, epoch ms (inclusive)."},firstParty:{type:"boolean",description:"true = only entries from Jaz-operated agent surfaces (server-stamped origin, never self-reported); false = only external and pre-stamp entries. Omit for all."},pinned:{type:"boolean",description:"true = only pinned entries (critical or withheld-write, the same predicate the pinned sort uses); false = only unpinned. Omit for all."},limit:{type:"number",description:"Max results per page (1-1000, default 100)."},offset:{type:"number",description:"Page number, 0-indexed."},includeStats:{type:"boolean",description:"Include per-credential disposition counts."}},required:[],group:"jots",readOnly:!0,isConcurrencySafe:!0,searchHint:"recall search jots judgment judgement journal precedent prior decisions rationale history dispositions flagged rejected endorsed first party jaz agents pinned lookup why",maxResultSizeChars:2e4,execute:async(t,e)=>{let r={};for(let n of["ref","kind","tier","dispositionVerb","freetext"])typeof e[n]=="string"&&e[n]&&(r[n]=e[n]);for(let n of["createdFrom","createdTo"])typeof e[n]=="number"&&(r[n]=e[n]);for(let n of["firstParty","pinned"])typeof e[n]=="boolean"&&(r[n]=e[n]);return yH(t.client,{...typeof e.limit=="number"?{limit:e.limit}:{},...typeof e.offset=="number"?{offset:e.offset}:{},...Object.keys(r).length?{filter:r}:{},...e.includeStats===!0?{includeStats:!0}:{}})}},{name:"remember",description:'Save, update, or remove a standing user preference (memory). action "set" creates or updates the memory at (scope, category, key) \u2014 REUSE the exact key shown in the Saved preferences block when updating or reinforcing an existing entry; use replaces_key to supersede a different existing key; use confirms_key to confirm a pending candidate by its reference key. action "forget" removes one memory; "forget_all" removes ALL saved memories for this user. Setting key_type AND match_value makes the preference contextual (surfaced only on emails matching the sender address/domain, vendor name, or subject token); omit both for an always-on preference. category "autonomy-grant" is ALWAYS stored pending server-side and takes effect only after the user confirms. At most 3 memory writes per email turn. Returns {ok:true, outcome, resource_id} or {ok:false, reason} \u2014 NEVER tell the user a preference was saved unless the result has ok:true.',params:{action:{type:"string",enum:[...qrt],description:'"set" to save/update, "forget" to remove one memory, "forget_all" to remove all.'},category:{type:"string",enum:[...$rt],description:"Preference category the memory belongs to."},key:{type:"string",description:'Stable kebab-case identifier (max 120 chars), e.g. "acme-expense-account". Reuse keys shown in Saved preferences.'},directive:{type:"string",description:'The preference text to store (required for "set"; plain text, max 300 chars; no URLs, no email addresses \u2014 addresses belong in match_value; no markup or template syntax).'},scope:{type:"string",enum:[...jrt],description:'"this_org" applies in this organization only (default); "all_orgs" follows the user across all their organizations.'},key_type:{type:"string",enum:[...Yrt],description:"What match_value matches on, for contextual preferences."},match_value:{type:"string",description:"The address/domain/name/token to match (required when key_type is set)."},replaces_key:{type:"string",description:"Existing key this memory supersedes, if any."},confirms_key:{type:"string",description:"Reference key of a pending candidate the user just confirmed, if any."},pending:{type:"boolean",description:"True to store as a candidate awaiting user confirmation instead of an active preference."}},required:["action","category","key"],group:"memory",readOnly:!1,searchHint:"remember memory save user preference standing directive forget contextual sender vendor",channels:["channel"],disabled:!bue(),execute:async(t,e)=>Hrt(t,e)},{name:"present_questions",description:`Present the user with a bounded multiple-choice question (or a short sequence of them) as an interactive pick-list, instead of asking in prose. Use as your FINAL action when the user must choose among a KNOWN, finite set of options you ALREADY have from context (a prior search/list result, org defaults, or your own knowledge) to continue (e.g. "which bank account?", "which of these duplicate bills?"). Give 2-4 options per question \u2014 curate to the most likely, never dump a long list \u2014 and at most 4 questions; set multiSelect per question when more than one may apply. List the options and stop \u2014 the user's pick arrives as their next message and starts a new turn. Ask several questions at once when more than one thing is unspecified. Prose-ask only when there's no bounded set to offer (a free-text name or amount), to confirm destructive actions, or instead of fetching data just to populate options. Terminal: do not call further tools or re-list the options in text afterward.`,params:{questions:{type:"array",description:"Questions to ask, each rendered as one page of the pick-list (at most 4). Provide one unless you genuinely have several distinct choices to collect in sequence.",items:{type:"object",properties:{header:{type:"string",description:'Optional short eyebrow label categorizing the question (1-2 words, e.g. "Account", "Period").'},question:{type:"string",description:'The question, shown as the card title (e.g. "Which bank account should I inspect?").'},options:{type:"array",description:"2-4 concrete choices (hard cap \u2014 curate to the most likely; the user can still type a different answer if none fit).",items:{type:"object",properties:{label:{type:"string",description:"The choice shown on the row and relayed verbatim as the user's answer when picked \u2014 keep it self-contained and unambiguous."},description:{type:"string",description:'Optional one-line detail under the label (e.g. "554 unreconciled records").'}},required:["label"]}},multiSelect:{type:"boolean",description:"Set true to let the user select multiple options for this question; omit or false for a single pick."}},required:["question","options"]}}},required:["questions"],group:"interaction",alwaysLoaded:!0,interactive:!0,readOnly:!0,isConcurrencySafe:!0,searchHint:"present questions options choices pick select ask user interactive widget",maxResultSizeChars:2e4,execute:async(t,e)=>{let n=(Array.isArray(e?.questions)?e.questions:[]).filter(o=>typeof o=="object"&&o!==null).map(o=>{let s=(Array.isArray(o.options)?o.options:[]).filter(c=>typeof c=="object"&&c!==null).map(c=>{let u=String(c.label??"").trim();return c.description?{label:u,description:String(c.description)}:{label:u}}).filter(c=>c.label),a=String(o.question??"").trim();return{...o.header?{header:String(o.header)}:{},question:a,options:s,multiSelect:!!o.multiSelect}}).filter(o=>o.question&&o.options.length>=2);if(n.length===0)return{error:"present_questions needs at least one question with non-empty question text and \u22652 labeled options (a single-option pick-list is not a choice).",hint:"Provide questions: [{ question, options: [{ label }, { label }] }]. For open-ended input, ask in prose instead."};if(n.length>4)return{error:`present_questions renders at most 4 questions (got ${n.length}).`,hint:"Ask the 4 most important now; collect the rest on a later turn."};let i=n.find(o=>o.options.length>4);return i?{error:`Each question may offer at most 4 options ("${i.question}" has ${i.options.length}).`,hint:"Curate to the 4 most likely choices \u2014 the user can still type a different answer if none fit."}:{questions:n}}},{name:"navigate",description:'Dashboard navigation: discover destinations, then build deep links. Without `destination`: lists valid destinations as { key, label, kind } \u2014 filter with `query` (substring over key + label), `resource` (e.g. "sales"), or `kind` ("screen" | "modal"); results are capped, narrow if `truncated`. With `destination`: builds the URL to hand the user \u2014 a screen (e.g. "reports.profit-and-loss") or a record modal (e.g. "sales.modal.view-sale"); pass `resourceId` only for a record-specific modal (view/edit one record), never for screens or create/"new" modals. Returns { url, kind, label }; the link opens in the user\'s current org. Never write dashboard URLs or destination keys from memory \u2014 call with no destination to discover keys first.',params:{destination:{type:"string",description:'Destination key to link to, e.g. "reports.profit-and-loss" or "sales.modal.view-sale". Omit to discover valid keys instead.'},resourceId:{type:"string",description:"Jaz resourceId of the record to focus \u2014 only with a record-modal destination (view/edit a specific record). Omit for screens and create modals."},query:{type:"string",description:'Discovery only: case-insensitive substring over destination keys and labels (e.g. "invoice", "p&l", "bank").'},resource:{type:"string",description:'Discovery only: restrict to one resource namespace, e.g. "sales", "purchases", "reports", "settings".'},kind:{type:"string",description:'Discovery only: restrict to "screen" (list/report pages) or "modal" (record view/create/edit).',enum:["screen","modal"]}},required:[],group:"navigation",alwaysLoaded:!0,readOnly:!0,isConcurrencySafe:!0,aliases:["find_dashboard_destinations","get_dashboard_url"],searchHint:"dashboard url deep link navigate go to open screen record modal page share shareable list destinations keys catalog",maxResultSizeChars:16e3,execute:async(t,e)=>{let r=typeof e.destination=="string"&&e.destination?e.destination:void 0,n=typeof e.resourceId=="string"&&e.resourceId?e.resourceId:void 0;if(!r){if(n)return{error:"resourceId given without destination - pass the record-modal destination key, or omit resourceId to discover destinations."};let o=e.kind==="screen"||e.kind==="modal"?e.kind:void 0,s=gQe({query:typeof e.query=="string"?e.query:void 0,resource:typeof e.resource=="string"?e.resource:void 0,kind:o});return s.truncated?{...s,hint:`Showing ${s.results.length} of ${s.total} matches. Narrow with a more specific query, resource, or kind.`}:s.results.length===0?{...s,hint:'No matches. Destinations are named by product area, not task wording \u2014 retry with a broader or synonym term (e.g. "billing" not "card", "sales" not "invoice payment", "settings", "reports", "bank") before concluding the destination does not exist.'}:s}let{dashboardUrl:i}=dQe(t.platform??"jaz");try{return AQe(r,n,{dashboardUrl:i,orgResourceId:t.org?.resourceId})}catch(o){return{error:o instanceof Error?o.message:String(o)}}}}];lQe(Mc)});function OCr(){if(!Iv){Iv=new Map;for(let t of Mc)Iv.set(t.name,t);for(let t of Mc)for(let e of t.aliases??[])Iv.has(e)||Iv.set(e,t)}return Iv}function uf(t){return OCr().get(t)}function sT(){return Kue||(Kue=Mc.filter(t=>!t.disabled&&t.channels===void 0)),Kue}function QCr(){return Xue||(Xue=sT().filter(t=>!t.interactive)),Xue}function LCr(){return ede||(ede=Mc.filter(t=>!t.disabled&&t.channels!==void 0)),ede}function Fnt(t){let e=t!==void 0&&FCr.has(t)?sT():QCr();if(t===void 0)return e;let r=LCr().filter(i=>i.channels.includes(t));if(r.length===0)return e;let n=Ont.get(t);return n||(n=[...e,...r],Ont.set(t,n)),n}function Gh(t){return sT().filter(e=>e.group===t)}var Iv,Kue,FCr,Xue,ede,Ont,py=X(()=>{"use strict";oT();Iv=null,Kue=null;FCr=new Set(["chat"]),Xue=null;ede=null;Ont=new Map});function Sct(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!wwr.has(o));return n.length===0?[]:qc.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,e).map(o=>o.ns)}var qc,wwr,NT=X(()=>{"use strict";qc=[{name:"invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, and transition (accept a quote, confirm an order, void, delete). A Sale Order links to its quote via saleQuoteResourceId; the quote must be accepted first. Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (raise the invoice separately).",groups:["sale_orders"]},{name:"purchase_orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, and transition (accept a request, confirm an order, void, delete). A Purchase Order links to its request via purchaseRequestResourceId; the request must be accepted first. Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (raise the bill separately).",groups:["purchase_orders"]},{name:"journals",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections.",groups:["journals"]},{name:"cash_entries",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",description:"Apply a reconciliation decision to a bank statement entry \u2014 write side. Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments \u2014 the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Eleven endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side.",groups:["reconciliations"]},{name:"financial_reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace \u2014 switch there or call by name).",groups:["financial_reports"]},{name:"operational_reports",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail.",groups:["operational_reports","exports"]},{name:"pseudo_sql",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema) + sync preview (\u2264100 rows) + async CSV export. Use when search_* / download_export canonical reports don't cover the question.",groups:["pseudo_sql"]},{name:"contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Bulk upsert contacts from CSV / spreadsheet imports \u2014 async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",description:"Catalogs \u2014 named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"nano_classifiers",description:"Nano classifiers (tracking categories/dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts \u2014 including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes.",groups:["tax_profiles"]},{name:"claim_settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",description:"Claim posting rules \u2014 how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via document attachment / conversion (no bare create); the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only \u2014 no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once \u2014 asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); bind a login user to an employee (permanent); and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"capsules_and_recipes",description:"Capsules (transaction groupings/capsule types). Financial recipes: amortization, depreciation, deferred revenue, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal. Two recipe execution paths: offline (plan_recipe + execute_recipe \u2014 client-side calculators, no API key) and server-side (list/get/preview/resume/rollback_capsule_recipe \u2014 produce real capsule entities via Jaz API). Plus capsuleRecipe payload on trigger mutations (create_bill, create_journal, create_cash_in, etc.) to create and trigger a recipe in one shot, with optional templateOverrides to customize the generated text (Customize Recipe). Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, rollback recipe, customize template overrides slots.",groups:["capsules","recipes","capsule_recipes"]},{name:"scheduled_transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). List/search saved report templates.",groups:["organization","org_users","modules","report_templates"]},{name:"document_ai",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets \u2014 CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill or invoice via AI extraction (create_bt_from_attachment, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork \u2014 "create docs from this Dropbox folder link", a pile/batch of invoices and bills \u2014 into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications.",groups:["payments","cashflow","search"]},{name:"quick_fix",description:"Quick Fix: bulk-update multiple transactions or line items in one call. Change dates, contacts, tags, accounts, tax profiles, custom fields across many invoices/bills/journals/credit-notes/cash-entries/schedulers at once. Also: batch update, mass edit.",groups:["quick_fix"]},{name:"export_records",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",description:"Draft business transactions \u2014 both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK \u2014 one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"help_center",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user \u2014 including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see \u2014 for invoices, bills, reports, settings, or a specific transaction.",groups:["navigation"]}],wwr=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"])});function N8(t){let e={type:t.type};if(t.description&&(e.description=t.description),t.enum&&(e.enum=t.enum),t.type==="array"&&t.items&&(e.items=N8(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=N8(i);e.properties=r,t.required?.length&&(e.required=t.required)}return e}function pf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=N8(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function gy(t){return{name:t.name,description:t.description,input_schema:pf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var OT=X(()=>{"use strict"});function FT(t){if(typeof t!="string")return t.isDestructive??!1;let e=t;return e.startsWith("delete_")||e.startsWith("pay_")||e.startsWith("finalize_")||e.includes("refund")||e==="remove_org_user"}function O8(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&FT(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function Rct(t){if(!t.trim())return{namespaces:qc.map(i=>{let o=i.groups.flatMap(s=>Gh(s));return{name:i.name,description:i.description,toolCount:o.length,tools:o.map(s=>s.name)}}),hint:"Call describe_tools with specific tool names to get full schemas before executing."};let e=Sct(t,5);if(e.length===0)return{matches:[],hint:`No tools match "${t}". Try broader terms or call search_tools with empty query to see all namespaces.`};let n=t.toLowerCase().split(/\s+/).filter(Boolean);return{matches:e.map(i=>{let o=i.groups.flatMap(u=>Gh(u)),s=o.map(u=>`${u.name} ${(u.aliases??[]).join(" ")} ${u.searchHint??""} ${u.description}`.toLowerCase()),a=new Map(n.map(u=>{let d=s.filter(f=>f.includes(u)).length;return[u,Math.log((o.length+1)/(d+1))]})),c=o.map((u,d)=>{let f=s[d],p=n.reduce((h,m)=>f.includes(m)?h+(a.get(m)??0):h,0);return{tool:u,score:p}}).sort((u,d)=>d.score-u.score);return{namespace:i.name,description:i.description,tools:c.map(u=>({name:u.tool.name,description:u.tool.description.split(`
|
|
867
|
+
USE THIS to score a specific draft against contact history. For stand-alone "what does this contact normally look like?" without a draft \u2192 use get_contact_signals.`,params:{items:{type:"array",description:"Draft business transaction references (max 500). Mix any btType freely.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!0,isConcurrencySafe:!0,searchHint:"validate drafts eligibility check before convert promote",execute:async(t,e)=>(Cv(e.items),kz(t.client,e.items))},{name:"convert_drafts_to_active",description:`BULK promote \u2014 finalize up to 500 draft business transactions to ACTIVE in ONE call, mixing any combination of invoices, bills, and credit notes (no per-type tools needed). ${Ll} NOT idempotent: a second call on already-promoted drafts returns 422. Filter the draft list by status: DRAFT before submitting. Pair with validate_drafts for a pre-flight check on large batches.`,params:{items:{type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!1,searchHint:"convert drafts to active promote finalize bulk",execute:async(t,e)=>(Cv(e.items),Nz(t.client,e.items))},{name:"submit_drafts_for_approval",description:`BULK submit \u2014 route up to 500 draft business transactions into the approval workflow in ONE call, mixing any combination of invoices, bills, and credit notes. ${Ll} NOT idempotent on drafts that already have an in-flight approval request.`,params:{items:{type:"array",description:"Draft BT references (max 500). Mix any btType.",items:{type:"object",properties:{btResourceId:{type:"string",description:"Draft BT resource ID (UUID) \u2014 required"},btType:{type:"string",enum:["SALE","PURCHASE","SALE_CREDIT_NOTE","PURCHASE_CREDIT_NOTE"],description:"Required"}}}}},required:["items"],group:"drafts",readOnly:!1,searchHint:"submit drafts for approval workflow review bulk",execute:async(t,e)=>(Cv(e.items),Oz(t.client,e.items))},{name:"search_help_center",description:'Search the Jaz help center for how-to articles, feature guides, and accounting concepts. Use this for "how do I..." or "what is..." questions about Jaz: bank reconciliation, GST/VAT filing, multi-currency, fixed assets, custom fields, integrations, and so on. Returns top matching articles with title, section, content, and source URL.',params:{query:{type:"string",description:'Natural-language question or keywords (e.g. "how do I reconcile a bank statement", "set up GST", "multi-currency invoice").'},limit:{type:"number",description:"Maximum number of articles to return (default 3, max 10)."},section:{type:"string",description:'Optional: restrict to a single help-center section slug (e.g. "bank-reconciliations", "invoices").'}},required:["query"],group:"help_center",readOnly:!0,searchHint:"help center docs how to guide article search question",isConcurrencySafe:!0,maxResultSizeChars:2e4,execute:async(t,e)=>{let r=typeof e.limit=="number"?e.limit:void 0,n=typeof e.section=="string"?e.section:void 0;return aue(String(e.query??""),{limit:r,section:n})}},{name:"jot",description:"Record judgment entries in the org's judgment journal. THE RULE: log a judgment when you chose among real alternatives and a write followed, or when you deliberately decided NOT to write; skip mechanical actions and calls where the platform, the data, or the user left you no choice. Jot AFTER the write succeeds, never before, and carry the written record's resourceId in refs. Kinds: CLASSIFICATION account/tax/category choice \xB7 MATCH decided which records correspond \xB7 SCOPE chose what is in or out of a set \xB7 ASSUMPTION filled a gap the data left open \xB7 RISK proceeded despite a known concern \xB7 METHOD picked a calculation or approach \xB7 RECOVERY decided how to proceed after a failure (incl. holding a write) \xB7 DEVIATION knowingly departed from a stated rule. Accepting or rejecting an inbound external document (an e-invoice a counterparty sent) is a FINALIZE act, so pin it. A decided omission (you deliberately did not post something) is RECOVERY, which pins via withheld-write, not DEVIATION. Always give why: a call without a basis is half a record. Batch related entries in one call; each entry is acked independently.",params:{entries:{type:"array",description:"Judgment entries to record (1-100). A bad entry never fails the batch: it acks with error while siblings persist.",items:{type:"object",properties:{kind:{type:"string",enum:["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],description:"Judgment kind: one-liners in the tool description."},tier:{type:"string",enum:["LOW","MEDIUM","HIGH","CRITICAL"],description:"Severity you assign the call."},call:{type:"string",description:'The decision, one line (e.g. "Posted to 6420 Travel: recurring Grab vendor pattern").'},why:{type:"string",description:"The basis for the call: a call without a basis is half a record."},ruledOut:{type:"string",description:"Alternatives considered and set aside."},refs:{type:"array",description:"Entity refs this judgment touches. Include the written record's resourceId.",items:{type:"string",description:'Grammar TYPE:resourceId[#field][:RELATION], e.g. "INVOICE:41f6\u2026:CREATE". RELATION: CREATE UPDATE DELETE FINALIZE PAY RECONCILE TRIGGER SUBJECT INPUT REJECTED SUPERSEDES (default SUBJECT).'}},frame:{type:"string",description:'For set-shaped subjects: the defining query + counts (e.g. "search_bills status=UNPAID \xB7 41 in scope, 4 deferred").'},confidence:{type:"string",enum:["LOW","MEDIUM","HIGH"],description:"Routing hint for review attention."},citedRule:{type:"string",description:"Org rule, policy, threshold, or precedent applied."},workflowLabel:{type:"string",description:"Short workflow label (e.g. month-end-close)."},agentLabel:{type:"string",description:"Self-reported product/model (e.g. jaz-clio/claude); informative, never authoritative."},idempotencyKey:{type:"string",description:"Retry key: a replay returns the existing entry, not a duplicate."}},required:["kind","tier","call"]}}},required:["entries"],group:"jots",readOnly:!1,alwaysLoaded:!0,searchHint:"jot judgment judgement journal record decision log rationale reasoning why chose ruled out classification match scope assumption risk method recovery deviation basis precedent note after write",execute:async(t,e)=>gv(t.client,e.entries)},{name:"recall",description:"Search the org's judgment journal (jots) for precedents, prior judgment calls with their basis. Check BEFORE repeating a judgment on the same entity, kind of decision, or workflow: a prior call with its why beats re-deriving from scratch; a FLAG or REJECT disposition on it is a warning, ENDORSE a strong precedent. Sort is pinned server-side (CRITICAL and withheld-write RECOVERY entries first, then newest). An empty page means no prior judgments match this filter, or none are recorded for this org yet.",params:{ref:{type:"string",description:'Entity ref filter, TYPE:resourceId (e.g. "INVOICE:41f626a3-\u2026").'},kind:{type:"string",enum:["CLASSIFICATION","MATCH","SCOPE","ASSUMPTION","RISK","METHOD","RECOVERY","DEVIATION","NOTE"],description:"Judgment kind filter."},tier:{type:"string",enum:["LOW","MEDIUM","HIGH","CRITICAL"],description:"Severity tier filter."},dispositionVerb:{type:"string",enum:["FLAG","REJECT","ENDORSE"],description:"Only entries carrying at least one disposition with this verb."},freetext:{type:"string",description:"Case-insensitive substring over call and why."},createdFrom:{type:"number",description:"Created-at lower bound, epoch ms (inclusive)."},createdTo:{type:"number",description:"Created-at upper bound, epoch ms (inclusive)."},firstParty:{type:"boolean",description:"true = only entries from Jaz-operated agent surfaces (server-stamped origin, never self-reported); false = only external and pre-stamp entries. Omit for all."},pinned:{type:"boolean",description:"true = only pinned entries (critical or withheld-write, the same predicate the pinned sort uses); false = only unpinned. Omit for all."},limit:{type:"number",description:"Max results per page (1-1000, default 100)."},offset:{type:"number",description:"Page number, 0-indexed."},includeStats:{type:"boolean",description:"Include per-credential disposition counts."}},required:[],group:"jots",readOnly:!0,isConcurrencySafe:!0,searchHint:"recall search jots judgment judgement journal precedent prior decisions rationale history dispositions flagged rejected endorsed first party jaz agents pinned lookup why",maxResultSizeChars:2e4,execute:async(t,e)=>{let r={};for(let n of["ref","kind","tier","dispositionVerb","freetext"])typeof e[n]=="string"&&e[n]&&(r[n]=e[n]);for(let n of["createdFrom","createdTo"])typeof e[n]=="number"&&(r[n]=e[n]);for(let n of["firstParty","pinned"])typeof e[n]=="boolean"&&(r[n]=e[n]);return yH(t.client,{...typeof e.limit=="number"?{limit:e.limit}:{},...typeof e.offset=="number"?{offset:e.offset}:{},...Object.keys(r).length?{filter:r}:{},...e.includeStats===!0?{includeStats:!0}:{}})}},{name:"remember",description:'Save, update, or remove a standing user preference (memory). MANDATORY: whenever the inbox owner states a lasting preference ("always\u2026", "never\u2026", "from now on\u2026"), call this tool with action "set" before finalizing your reply \u2014 even if the preference matches your current default behavior; a jot never substitutes for it. action "set" creates or updates the memory at (scope, category, key) \u2014 REUSE the exact key shown in the Saved preferences block when updating or reinforcing an existing entry; use replaces_key to supersede a different existing key; use confirms_key to confirm a pending candidate by its reference key. action "forget" removes one memory; "forget_all" removes ALL saved memories for this user. Setting key_type AND match_value makes the preference contextual (surfaced only on emails matching the sender address/domain, vendor name, or subject token); omit both for an always-on preference. category "autonomy-grant" is ALWAYS stored pending server-side and takes effect only after the user confirms. At most 3 memory writes per email turn. Returns {ok:true, outcome, resource_id} or {ok:false, reason} \u2014 NEVER tell the user a preference was saved unless the result has ok:true.',params:{action:{type:"string",enum:[...qrt],description:'"set" to save/update, "forget" to remove one memory, "forget_all" to remove all.'},category:{type:"string",enum:[...$rt],description:"Preference category the memory belongs to."},key:{type:"string",description:'Stable kebab-case identifier (max 120 chars), e.g. "acme-expense-account". Reuse keys shown in Saved preferences.'},directive:{type:"string",description:'The preference text to store (required for "set"; plain text, max 300 chars; no URLs, no email addresses \u2014 addresses belong in match_value; no markup or template syntax).'},scope:{type:"string",enum:[...jrt],description:'"this_org" applies in this organization only (default); "all_orgs" follows the user across all their organizations.'},key_type:{type:"string",enum:[...Yrt],description:"What match_value matches on, for contextual preferences."},match_value:{type:"string",description:"The address/domain/name/token to match (required when key_type is set)."},replaces_key:{type:"string",description:"Existing key this memory supersedes, if any."},confirms_key:{type:"string",description:"Reference key of a pending candidate the user just confirmed, if any."},pending:{type:"boolean",description:"True to store as a candidate awaiting user confirmation instead of an active preference."}},required:["action","category","key"],group:"memory",readOnly:!1,searchHint:"remember memory save user preference standing directive forget contextual sender vendor",channels:["channel"],disabled:!bue(),execute:async(t,e)=>Hrt(t,e)},{name:"present_questions",description:`Present the user with a bounded multiple-choice question (or a short sequence of them) as an interactive pick-list, instead of asking in prose. Use as your FINAL action when the user must choose among a KNOWN, finite set of options you ALREADY have from context (a prior search/list result, org defaults, or your own knowledge) to continue (e.g. "which bank account?", "which of these duplicate bills?"). Give 2-4 options per question \u2014 curate to the most likely, never dump a long list \u2014 and at most 4 questions; set multiSelect per question when more than one may apply. List the options and stop \u2014 the user's pick arrives as their next message and starts a new turn. Ask several questions at once when more than one thing is unspecified. Prose-ask only when there's no bounded set to offer (a free-text name or amount), to confirm destructive actions, or instead of fetching data just to populate options. Terminal: do not call further tools or re-list the options in text afterward.`,params:{questions:{type:"array",description:"Questions to ask, each rendered as one page of the pick-list (at most 4). Provide one unless you genuinely have several distinct choices to collect in sequence.",items:{type:"object",properties:{header:{type:"string",description:'Optional short eyebrow label categorizing the question (1-2 words, e.g. "Account", "Period").'},question:{type:"string",description:'The question, shown as the card title (e.g. "Which bank account should I inspect?").'},options:{type:"array",description:"2-4 concrete choices (hard cap \u2014 curate to the most likely; the user can still type a different answer if none fit).",items:{type:"object",properties:{label:{type:"string",description:"The choice shown on the row and relayed verbatim as the user's answer when picked \u2014 keep it self-contained and unambiguous."},description:{type:"string",description:'Optional one-line detail under the label (e.g. "554 unreconciled records").'}},required:["label"]}},multiSelect:{type:"boolean",description:"Set true to let the user select multiple options for this question; omit or false for a single pick."}},required:["question","options"]}}},required:["questions"],group:"interaction",alwaysLoaded:!0,interactive:!0,readOnly:!0,isConcurrencySafe:!0,searchHint:"present questions options choices pick select ask user interactive widget",maxResultSizeChars:2e4,execute:async(t,e)=>{let n=(Array.isArray(e?.questions)?e.questions:[]).filter(o=>typeof o=="object"&&o!==null).map(o=>{let s=(Array.isArray(o.options)?o.options:[]).filter(c=>typeof c=="object"&&c!==null).map(c=>{let u=String(c.label??"").trim();return c.description?{label:u,description:String(c.description)}:{label:u}}).filter(c=>c.label),a=String(o.question??"").trim();return{...o.header?{header:String(o.header)}:{},question:a,options:s,multiSelect:!!o.multiSelect}}).filter(o=>o.question&&o.options.length>=2);if(n.length===0)return{error:"present_questions needs at least one question with non-empty question text and \u22652 labeled options (a single-option pick-list is not a choice).",hint:"Provide questions: [{ question, options: [{ label }, { label }] }]. For open-ended input, ask in prose instead."};if(n.length>4)return{error:`present_questions renders at most 4 questions (got ${n.length}).`,hint:"Ask the 4 most important now; collect the rest on a later turn."};let i=n.find(o=>o.options.length>4);return i?{error:`Each question may offer at most 4 options ("${i.question}" has ${i.options.length}).`,hint:"Curate to the 4 most likely choices \u2014 the user can still type a different answer if none fit."}:{questions:n}}},{name:"navigate",description:'Dashboard navigation: discover destinations, then build deep links. Without `destination`: lists valid destinations as { key, label, kind } \u2014 filter with `query` (substring over key + label), `resource` (e.g. "sales"), or `kind` ("screen" | "modal"); results are capped, narrow if `truncated`. With `destination`: builds the URL to hand the user \u2014 a screen (e.g. "reports.profit-and-loss") or a record modal (e.g. "sales.modal.view-sale"); pass `resourceId` only for a record-specific modal (view/edit one record), never for screens or create/"new" modals. Returns { url, kind, label }; the link opens in the user\'s current org. Never write dashboard URLs or destination keys from memory \u2014 call with no destination to discover keys first.',params:{destination:{type:"string",description:'Destination key to link to, e.g. "reports.profit-and-loss" or "sales.modal.view-sale". Omit to discover valid keys instead.'},resourceId:{type:"string",description:"Jaz resourceId of the record to focus \u2014 only with a record-modal destination (view/edit a specific record). Omit for screens and create modals."},query:{type:"string",description:'Discovery only: case-insensitive substring over destination keys and labels (e.g. "invoice", "p&l", "bank").'},resource:{type:"string",description:'Discovery only: restrict to one resource namespace, e.g. "sales", "purchases", "reports", "settings".'},kind:{type:"string",description:'Discovery only: restrict to "screen" (list/report pages) or "modal" (record view/create/edit).',enum:["screen","modal"]}},required:[],group:"navigation",alwaysLoaded:!0,readOnly:!0,isConcurrencySafe:!0,aliases:["find_dashboard_destinations","get_dashboard_url"],searchHint:"dashboard url deep link navigate go to open screen record modal page share shareable list destinations keys catalog",maxResultSizeChars:16e3,execute:async(t,e)=>{let r=typeof e.destination=="string"&&e.destination?e.destination:void 0,n=typeof e.resourceId=="string"&&e.resourceId?e.resourceId:void 0;if(!r){if(n)return{error:"resourceId given without destination - pass the record-modal destination key, or omit resourceId to discover destinations."};let o=e.kind==="screen"||e.kind==="modal"?e.kind:void 0,s=gQe({query:typeof e.query=="string"?e.query:void 0,resource:typeof e.resource=="string"?e.resource:void 0,kind:o});return s.truncated?{...s,hint:`Showing ${s.results.length} of ${s.total} matches. Narrow with a more specific query, resource, or kind.`}:s.results.length===0?{...s,hint:'No matches. Destinations are named by product area, not task wording \u2014 retry with a broader or synonym term (e.g. "billing" not "card", "sales" not "invoice payment", "settings", "reports", "bank") before concluding the destination does not exist.'}:s}let{dashboardUrl:i}=dQe(t.platform??"jaz");try{return AQe(r,n,{dashboardUrl:i,orgResourceId:t.org?.resourceId})}catch(o){return{error:o instanceof Error?o.message:String(o)}}}}];lQe(Mc)});function OCr(){if(!Iv){Iv=new Map;for(let t of Mc)Iv.set(t.name,t);for(let t of Mc)for(let e of t.aliases??[])Iv.has(e)||Iv.set(e,t)}return Iv}function uf(t){return OCr().get(t)}function sT(){return Kue||(Kue=Mc.filter(t=>!t.disabled&&t.channels===void 0)),Kue}function QCr(){return Xue||(Xue=sT().filter(t=>!t.interactive)),Xue}function LCr(){return ede||(ede=Mc.filter(t=>!t.disabled&&t.channels!==void 0)),ede}function Fnt(t){let e=t!==void 0&&FCr.has(t)?sT():QCr();if(t===void 0)return e;let r=LCr().filter(i=>i.channels.includes(t));if(r.length===0)return e;let n=Ont.get(t);return n||(n=[...e,...r],Ont.set(t,n)),n}function Gh(t){return sT().filter(e=>e.group===t)}var Iv,Kue,FCr,Xue,ede,Ont,py=X(()=>{"use strict";oT();Iv=null,Kue=null;FCr=new Set(["chat"]),Xue=null;ede=null;Ont=new Map});function Sct(t,e=5){let r=t.trim().toLowerCase();if(!r)return[];let n=r.split(/[\s_-]+/).filter(o=>o.length>=2&&!wwr.has(o));return n.length===0?[]:qc.map(o=>{let s=0,a=o.name.toLowerCase(),c=o.description.toLowerCase();(a===r||a===r.replace(/\s+/g,"_"))&&(s+=5),a.includes(r)&&(s+=3),c.includes(r)&&(s+=1);for(let u of n)a.includes(u)&&(s+=2),c.includes(u)&&(s+=1);return{ns:o,score:s}}).filter(o=>o.score>0).sort((o,s)=>s.score-o.score).slice(0,e).map(o=>o.ns)}var qc,wwr,NT=X(()=>{"use strict";qc=[{name:"invoices",description:"Sales invoices (INV/SI). Create, search, get, update, delete, pay, finalize, apply credits, download PDF. Also: receivables, AR, AR aging, billing, overdue invoices, dunning, recurring invoices. To create from an uploaded invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["invoices"]},{name:"customer_credit_notes",description:"Customer credit notes (CN). Create, search, update, delete, finalize, refund, download PDF. Also: sales returns, customer CN.",groups:["customer_credit_notes"]},{name:"bills",description:"Purchase bills (PO/PI). Create, search, get, update, delete, pay, finalize, apply credits. Also: payables, AP, vendor invoices, supplier bills. To create from an uploaded bill/invoice file/PDF/image, use the document_ai namespace (AI extraction), not manual entry.",groups:["bills"]},{name:"supplier_credit_notes",description:"Supplier credit notes. Create, search, update, delete, finalize, refund. Also: purchase returns, debit notes, supplier CN.",groups:["supplier_credit_notes"]},{name:"sale_orders",description:"Sales order documents: Sale Quotes (estimates/quotations) and Sale Orders. Create, get, search, update, and transition (accept a quote, confirm an order, void, delete). A Sale Order links to its quote via saleQuoteResourceId; the quote must be accepted first. Tracks fulfillment via orderState. Pipeline: quote \u2192 order \u2192 invoice (raise the invoice separately).",groups:["sale_orders"]},{name:"purchase_orders",description:"Purchase order documents: Purchase Requests (requisitions) and Purchase Orders (POs). Create, get, search, update, and transition (accept a request, confirm an order, void, delete). A Purchase Order links to its request via purchaseRequestResourceId; the request must be accepted first. Tracks fulfillment via orderState. Pipeline: request \u2192 order \u2192 bill (raise the bill separately).",groups:["purchase_orders"]},{name:"journals",description:"Journal entries (JE). Create, search, update, delete manual journals. Also: adjusting entries, accruals, reclassifications, corrections.",groups:["journals"]},{name:"cash_entries",description:"Cash-in receipts and cash-out disbursements for external cash movements. WHEN TO USE: money received from customers/external \u2192 cash-in. Money paid to suppliers/external \u2192 cash-out. For internal account-to-account transfers, use cash_transfers namespace.",groups:["cash_entries"]},{name:"cash_transfers",description:"Cash transfers between your own bank/cash accounts and cashflow transaction search. WHEN TO USE: moving funds between own accounts (main bank \u2192 petty cash, USD \u2192 SGD). For external receipts/payments, use cash_entries namespace.",groups:["cash_transfers"]},{name:"bank_accounts",description:"Bank accounts, bank statement imports (CSV/OFX), bank records search, auto-reconciliation. For unreconciled queries: ALWAYS search bank records with status UNRECONCILED after listing accounts. Also: bank feeds, bank balance.",groups:["bank"]},{name:"bank_rules",description:"Bank reconciliation rules (action shortcuts). Create, search, update, delete bank rules. Configure auto-matching rules for bank records.",groups:["bank_rules"]},{name:"reconciliations",description:"Apply a reconciliation decision to a bank statement entry \u2014 write side. Match bank records to EXISTING open bills/invoices/payments (reconcile_with_payments \u2014 the primary path, creates the payment for you), or to journals, cash entries, or transfers, or CREATE new bills/invoices (invoice_receipt/bill_receipt). Distinct from bank_accounts/bank_rules (which configure auto-reconciliation) and view_auto_reconciliation (which queries suggestions). Eleven endpoints: quick_reconcile + apply_bank_rule + magic_match (bulk), and direct_cash_entry / cash_journal / manual_journal / cash_transfer / invoice_receipt / bill_receipt / with_payments / learned_prediction (per-entry). Match-to-existing is preferred over create-new to avoid duplicates. Most fields prefill from the bank entry when omitted; FX is resolved server-side.",groups:["reconciliations"]},{name:"financial_reports",description:"Core financial statements: trial balance (TB), balance sheet (BS/B/S), profit & loss (PnL/P&L/income statement), cash flow, general ledger (GL), cash balance/position, equity movement, VAT/GST ledger. Also: how profitable, what is the balance. XLSX/PDF file exports of any of these statements are produced via download_export (lives in operational_reports namespace \u2014 switch there or call by name).",groups:["financial_reports"]},{name:"operational_reports",description:"Aging and operational reports: aged receivables (AR aging), aged payables (AP aging), AR report, bank balance summary, bank reconciliation reports, fixed asset (FA) summary, FA reconciliation. Data exports (CSV/Excel/XLSX). Anomaly detection and audit analysis: anomalous invoices, anomalous bills, cashflow anomalies, GL journal audit, exchange rate audit, receivables customer risk, cash expense health. Also: overdue analysis, how much owed, suspicious transactions, audit trail.",groups:["operational_reports","exports"]},{name:"pseudo_sql",description:"Pseudo-SQL ad-hoc read-only queries against the curated reporting schema (custom select, custom report, query data, run sql). Includes live schema introspection (get_pseudo_sql_schema) + sync preview (\u2264100 rows) + async CSV export. Use when search_* / download_export canonical reports don't cover the question.",groups:["pseudo_sql"]},{name:"contacts",description:"Contacts (customers/suppliers/vendors), contact groups, customer segmentation. Create, search, get, update, delete contacts. Bulk upsert contacts from CSV / spreadsheet imports \u2014 async, returns jobId, poll background_jobs. List/create contact groups.",groups:["contacts","contact_groups"]},{name:"items_and_inventory",description:"Products, services, inventory items. Create, search, get, update, delete items. Check inventory balance. List/search purchase-side catalog items. Also: SKU, catalog, stock.",groups:["items","inventory","purchase_items"]},{name:"catalogs",description:"Catalogs \u2014 named groupings of products/services, optionally scoped to contact groups. Create, search, get, update, delete catalogs.",groups:["catalogs"]},{name:"tags_and_custom_fields",description:"Tags for categorizing transactions. Custom fields for adding metadata (text, date, dropdown). Create, search, delete tags and custom fields.",groups:["tags","custom_fields"]},{name:"nano_classifiers",description:"Nano classifiers (tracking categories/dimensions). List, search, create, update, delete classifiers and their classes. Used for line-item tagging and dimensional reporting. Also: tracking categories, cost centers, departments, projects.",groups:["nano_classifiers"]},{name:"chart_of_accounts",description:"Chart of accounts (COA/GL accounts). Create, search, update accounts \u2014 including setting or removing an account's period lock date (lock / unlock a period, lock date: block recording or editing transactions on the account dated on or before a date). Bookmarks (favorites/shortcuts). Also: ledger codes, account types.",groups:["accounts","bookmarks"]},{name:"currencies",description:"Currencies, exchange rates (FX/forex). List/add org currencies. Set, update, import currency rates. Also: multi-currency, FX rates.",groups:["currencies"]},{name:"tax_profiles",description:"Tax profiles (GST/VAT/sales tax), withholding tax codes (WHT/ATC). Search, create, update tax profiles. List WHT codes.",groups:["tax_profiles"]},{name:"claim_settings",description:"Employee-expense claim configuration (Settings -> Claim Settings): claim types (expense categories) and claim profiles (per-employee policy: approver, limits, visible types, balance account). Full CRUD + search on each.",groups:["claim_types","claim_profiles"]},{name:"posting_rules",description:"Claim posting rules \u2014 how approved employee-expense claims group into journals at conversion (outer/inner grouping axes, line templates, default reimbursement bank). Full CRUD + search.",groups:["posting_rules"]},{name:"claims",description:'Employee-expense claims (the Claims area / Employees). Search, get, update DRAFT claims (line items, employee, vendor), and drive the lifecycle: submit, approve, reject, cancel, unpost (reverse conversion), delete. Status flow DRAFT \u2192 SUBMITTED \u2192 APPROVED \u2192 CONVERTED ("Processed"), or REJECTED / CANCELLED. Claims are born via document attachment / conversion (no bare create); the server enforces legal transitions.',groups:["claims"]},{name:"claim_processing",description:"Process employee-expense claims: convert APPROVED claims into journal entries (preview + commit, books-only \u2014 no real-money disburse), record books-only employee payouts (reimbursements / advances) and search them, run bulk claim actions (submit / approve / reject / cancel / delete many at once \u2014 asynchronous, returns a background-job handle to poll), plus the claim tracking-tag and custom-field-value pickers.",groups:["claim_processing"]},{name:"employees",description:"Employees (expense-claim members): create, update, get, delete, and search employees; search the employee-balance directory (reimbursement balances owed); bind a login user to an employee (permanent); and bulk-import employees from a sheet (preprocess preview \u2192 async import). Archive an employee with update active=false rather than deleting.",groups:["employees"]},{name:"capsules_and_recipes",description:"Capsules (transaction groupings/capsule types). Financial recipes: amortization, depreciation, deferred revenue, IFRS 16 leases, hire purchase, fixed deposits, FX revaluation, loan schedules, ECL/expected credit loss, IAS 37 provisions, asset disposal. Two recipe execution paths: offline (plan_recipe + execute_recipe \u2014 client-side calculators, no API key) and server-side (list/get/preview/resume/rollback_capsule_recipe \u2014 produce real capsule entities via Jaz API). Plus capsuleRecipe payload on trigger mutations (create_bill, create_journal, create_cash_in, etc.) to create and trigger a recipe in one shot, with optional templateOverrides to customize the generated text (Customize Recipe). Keywords: calculate, provision, schedule, expected credit loss, revaluation, amortize, rollback recipe, customize template overrides slots.",groups:["capsules","recipes","capsule_recipes"]},{name:"scheduled_transactions",description:"Scheduled/recurring invoices, bills, journals. Create scheduled invoices/bills/journals, search scheduled transactions. Also: recurring, auto-generate.",groups:["schedulers"]},{name:"subscriptions",description:"Subscriptions (recurring billing/payment plans). Create, update, cancel, search subscriptions. Also: recurring charges, subscription schedules.",groups:["subscriptions"]},{name:"organization",description:"Organization info (name, currency, country, fiscal year). User management: invite, update, remove, search org users. Bulk invite. List enabled modules (org features/capabilities). List/search saved report templates.",groups:["organization","org_users","modules","report_templates"]},{name:"document_ai",description:'File attachments, spreadsheets, and document AI. Read and parse rows from attached spreadsheets \u2014 CSV, Excel, XLSX. Scan a single invoice / bill / receipt PDF or image to create a draft bill or invoice via AI extraction (create_bt_from_attachment, with the file or a sourceUrl). Auto-sort a whole FOLDER, a .zip, or a Dropbox / Google Drive / OneDrive folder share link of mixed paperwork \u2014 "create docs from this Dropbox folder link", a pile/batch of invoices and bills \u2014 into invoices, bills, credit notes, and bank statements with classify_documents, then create the drafts with extract_documents. Upload and list attachments; track extraction workflows.',groups:["attachments","magic"]},{name:"fixed_assets",description:"Fixed assets (PP&E/property, plant, equipment). Search, create, update, discard, sell, transfer, undo disposal. Also: depreciation, asset register.",groups:["fixed_assets"]},{name:"payments_and_search",description:"Payment records: get, update, delete individual payments. List payments/credits on invoices and bills. Reverse credit applications. Cashflow transaction search. Universal cross-entity search. Also: payment run, batch payment, payment matching, void payment, payment history, credit note applications.",groups:["payments","cashflow","search"]},{name:"quick_fix",description:"Quick Fix: bulk-update multiple transactions or line items in one call. Change dates, contacts, tags, accounts, tax profiles, custom fields across many invoices/bills/journals/credit-notes/cash-entries/schedulers at once. Also: batch update, mass edit.",groups:["quick_fix"]},{name:"export_records",description:"Export records to XLSX. List available columns, preview export scope (row count + sample), generate export file with pre-signed download URL. Supports any entity type: invoices, bills, contacts, items, journals, bank records, cashflow, fixed assets, etc. Pass query (structured search syntax) or filter (JSON), never both.",groups:["export_records"]},{name:"background_jobs",description:"Background job tracking. Poll any async operation by jobId (contacts bulk-upsert, items bulk-upsert, bank import, magic file processing, etc.). Filter by resourceId field to look up a specific job. Poll until status is SUCCESS, FAILED, or PARTIAL_SUCCESS.",groups:["background_jobs"]},{name:"drafts",description:"Draft business transactions \u2014 both local payload validation (invoices, bills, journals, credit notes) AND BULK-FRIENDLY server-side lifecycle: validate_drafts (sync eligibility check), convert_drafts_to_active (async promote to ACTIVE), submit_drafts_for_approval (async route to approval). The lifecycle tools are GENERIC and BULK \u2014 one call accepts up to 500 items mixing any combination of {btResourceId, btType: SALE|PURCHASE|SALE_CREDIT_NOTE|PURCHASE_CREDIT_NOTE}. No need for per-entity tools when promoting/submitting drafts at scale. NOT idempotent on already-promoted drafts.",groups:["drafts"]},{name:"help_center",description:"Search the Jaz help center for how-to articles, feature guides, accounting concepts, and troubleshooting. Returns top matches with title, section, snippet, and source URL. Works without an API key.",groups:["help_center"]},{name:"jots",description:"The judgment journal. jot records a judgment call (chose among real alternatives and wrote, or deliberately held a write); recall looks up prior judgments and precedents by entity, kind, or freetext. Also: decision log, rationale, why.",groups:["jots"]},{name:"navigation",description:"Dashboard navigation deep links. Build a URL to any dashboard screen or record for the user \u2014 including the view link for a record just created or updated (a reply reporting on a record carries its link, and dashboard URLs always come from this tool, never written from memory). Also: open, go to, take me to, link, deep link, share a link, url, navigate, show me the page/screen, where can I see \u2014 for invoices, bills, reports, settings, or a specific transaction.",groups:["navigation"]}],wwr=new Set(["a","an","and","are","at","be","by","can","do","does","for","how","i","in","is","it","me","my","of","on","or","our","please","that","the","this","to","us","we","what","when","where","which","with","you","your"])});function N8(t){let e={type:t.type};if(t.description&&(e.description=t.description),t.enum&&(e.enum=t.enum),t.type==="array"&&t.items&&(e.items=N8(t.items)),t.type==="object"&&t.properties){let r={};for(let[n,i]of Object.entries(t.properties))r[n]=N8(i);e.properties=r,t.required?.length&&(e.required=t.required)}return e}function pf(t,e){let r={};for(let[n,i]of Object.entries(t))r[n]=N8(i);return{type:"object",properties:r,...e.length>0?{required:e}:{}}}function gy(t){return{name:t.name,description:t.description,input_schema:pf(t.params,t.required),...t.searchHint?{searchHint:t.searchHint}:{}}}var OT=X(()=>{"use strict"});function FT(t){if(typeof t!="string")return t.isDestructive??!1;let e=t;return e.startsWith("delete_")||e.startsWith("pay_")||e.startsWith("finalize_")||e.includes("refund")||e==="remove_org_user"}function O8(t){return{readOnlyHint:t.readOnly,destructiveHint:!t.readOnly&&FT(t),idempotentHint:t.readOnly,openWorldHint:t.openWorld??!1}}function Rct(t){if(!t.trim())return{namespaces:qc.map(i=>{let o=i.groups.flatMap(s=>Gh(s));return{name:i.name,description:i.description,toolCount:o.length,tools:o.map(s=>s.name)}}),hint:"Call describe_tools with specific tool names to get full schemas before executing."};let e=Sct(t,5);if(e.length===0)return{matches:[],hint:`No tools match "${t}". Try broader terms or call search_tools with empty query to see all namespaces.`};let n=t.toLowerCase().split(/\s+/).filter(Boolean);return{matches:e.map(i=>{let o=i.groups.flatMap(u=>Gh(u)),s=o.map(u=>`${u.name} ${(u.aliases??[]).join(" ")} ${u.searchHint??""} ${u.description}`.toLowerCase()),a=new Map(n.map(u=>{let d=s.filter(f=>f.includes(u)).length;return[u,Math.log((o.length+1)/(d+1))]})),c=o.map((u,d)=>{let f=s[d],p=n.reduce((h,m)=>f.includes(m)?h+(a.get(m)??0):h,0);return{tool:u,score:p}}).sort((u,d)=>d.score-u.score);return{namespace:i.name,description:i.description,tools:c.map(u=>({name:u.tool.name,description:u.tool.description.split(`
|
|
868
868
|
`)[0],...u.tool.searchHint?{searchHint:u.tool.searchHint}:{}}))}}),hint:"Call describe_tools with the tool names you need, then execute_tool to run them."}}function Bct(t){if(!Array.isArray(t)||!t.every(n=>typeof n=="string"))return{error:"Invalid `tools` parameter. Expected string[]."};if(t.length===0)return{error:"Provide at least one tool name. Use search_tools first to discover tool names."};let e=[],r=[];for(let n of t){let i=uf(n);if(!i){r.push(n);continue}e.push({...gy(i),readOnly:i.readOnly,isDestructive:i.isDestructive??!1,isConcurrencySafe:i.isConcurrencySafe??!1,destructiveHint:!i.readOnly&&FT(i),group:i.group})}return{tools:e,...r.length>0?{notFound:r,hint:`Tools not found: ${r.join(", ")}. Use search_tools to find correct names.`}:{}}}var _wr,Dwr,Swr,Zh,hf,QT=X(()=>{"use strict";NT();py();OT();_wr={name:"search_tools",description:"Search for available Jaz accounting tools by keyword. Returns matching tool namespaces with tool names and descriptions. Call with empty query to list all namespaces. ALWAYS call this first to discover what tools are available.",inputSchema:pf({query:{type:"string",description:'Search keyword (e.g. "invoice", "bank recon", "depreciation"). Empty string lists all namespaces.'}},[])};Dwr={name:"describe_tools",description:"Get full JSON Schema (parameters, types, required fields) for specific tools. Call this after search_tools to get the exact input format before calling execute_tool.",inputSchema:pf({tools:{type:"array",items:{type:"string"},description:'Tool names to describe (e.g. ["create_invoice", "search_contacts"])'}},["tools"])},Swr={name:"execute_tool",description:"Execute a Jaz accounting tool. Call describe_tools first to get the required parameters. Pass the tool name and its arguments.",inputSchema:pf({tool:{type:"string",description:'Tool name (e.g. "create_invoice")'},arguments:{type:"object",description:"Tool arguments (see describe_tools for schema)"},org_id:{type:"string",description:"Organization ID (UUID). Required in multi-org mode (PAT or multiple API keys). Call list_organizations to get available IDs."}},["tool"])},Zh={name:"list_organizations",description:"List organizations available to the current authentication. Returns org names and resource IDs for use as org_id in execute_tool calls.",inputSchema:pf({},[])},hf=[_wr,Dwr,Swr]});var UT=b(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.regexpCode=kr.getEsmExportName=kr.getProperty=kr.safeStringify=kr.stringify=kr.strConcat=kr.addCodeArg=kr.str=kr._=kr.nil=kr._Code=kr.Name=kr.IDENTIFIER=kr._CodeOrName=void 0;var MT=class{};kr._CodeOrName=MT;kr.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var yy=class extends MT{constructor(e){if(super(),!kr.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};kr.Name=yy;var jc=class extends MT{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof yy&&(r[n.str]=(r[n.str]||0)+1),r),{})}};kr._Code=jc;kr.nil=new jc("");function Nct(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Cfe(r,e[n]),r.push(t[++n]);return new jc(r)}kr._=Nct;var bfe=new jc("+");function Oct(t,...e){let r=[PT(t[0])],n=0;for(;n<e.length;)r.push(bfe),Cfe(r,e[n]),r.push(bfe,PT(t[++n]));return Owr(r),new jc(r)}kr.str=Oct;function Cfe(t,e){e instanceof jc?t.push(...e._items):e instanceof yy?t.push(e):t.push(Lwr(e))}kr.addCodeArg=Cfe;function Owr(t){let e=1;for(;e<t.length-1;){if(t[e]===bfe){let r=Fwr(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Fwr(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof yy||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof yy))return`"${t}${e.slice(1)}`}function Qwr(t,e){return e.emptyStr()?t:t.emptyStr()?e:Oct`${t}${e}`}kr.strConcat=Qwr;function Lwr(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:PT(Array.isArray(t)?t.join(","):t)}function Mwr(t){return new jc(PT(t))}kr.stringify=Mwr;function PT(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}kr.safeStringify=PT;function Pwr(t){return typeof t=="string"&&kr.IDENTIFIER.test(t)?new jc(`.${t}`):Nct`[${t}]`}kr.getProperty=Pwr;function Uwr(t){if(typeof t=="string"&&kr.IDENTIFIER.test(t))return new jc(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}kr.getEsmExportName=Uwr;function $wr(t){return new jc(t.toString())}kr.regexpCode=$wr});var wfe=b(ca=>{"use strict";Object.defineProperty(ca,"__esModule",{value:!0});ca.ValueScope=ca.ValueScopeName=ca.Scope=ca.varKinds=ca.UsedValueState=void 0;var aa=UT(),vfe=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},L8;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(L8||(ca.UsedValueState=L8={}));ca.varKinds={const:new aa.Name("const"),let:new aa.Name("let"),var:new aa.Name("var")};var M8=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof aa.Name?e:this.name(e)}name(e){return new aa.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};ca.Scope=M8;var P8=class extends aa.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,aa._)`.${new aa.Name(r)}[${n}]`}};ca.ValueScopeName=P8;var qwr=(0,aa._)`\n`,Ife=class extends M8{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?qwr:aa.nil}}get(){return this._scope}name(e){return new P8(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:o}=i,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[o];if(a){let d=a.get(s);if(d)return d}else a=this._values[o]=new Map;a.set(s,i);let c=this._scope[o]||(this._scope[o]=[]),u=c.length;return c[u]=r.ref,i.setValue(r,{property:o,itemIndex:u}),i}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,aa._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},r,n)}_reduceValues(e,r,n={},i){let o=aa.nil;for(let s in e){let a=e[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,L8.Started);let d=r(u);if(d){let f=this.opts.es5?ca.varKinds.var:ca.varKinds.const;o=(0,aa._)`${o}${f} ${u} = ${d};${this.opts._n}`}else if(d=i?.(u))o=(0,aa._)`${o}${d}${this.opts._n}`;else throw new vfe(u);c.set(u,L8.Completed)})}return o}};ca.ValueScope=Ife});var jt=b(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.or=zt.and=zt.not=zt.CodeGen=zt.operators=zt.varKinds=zt.ValueScopeName=zt.ValueScope=zt.Scope=zt.Name=zt.regexpCode=zt.stringify=zt.getProperty=zt.nil=zt.strConcat=zt.str=zt._=void 0;var mr=UT(),$l=wfe(),em=UT();Object.defineProperty(zt,"_",{enumerable:!0,get:function(){return em._}});Object.defineProperty(zt,"str",{enumerable:!0,get:function(){return em.str}});Object.defineProperty(zt,"strConcat",{enumerable:!0,get:function(){return em.strConcat}});Object.defineProperty(zt,"nil",{enumerable:!0,get:function(){return em.nil}});Object.defineProperty(zt,"getProperty",{enumerable:!0,get:function(){return em.getProperty}});Object.defineProperty(zt,"stringify",{enumerable:!0,get:function(){return em.stringify}});Object.defineProperty(zt,"regexpCode",{enumerable:!0,get:function(){return em.regexpCode}});Object.defineProperty(zt,"Name",{enumerable:!0,get:function(){return em.Name}});var j8=wfe();Object.defineProperty(zt,"Scope",{enumerable:!0,get:function(){return j8.Scope}});Object.defineProperty(zt,"ValueScope",{enumerable:!0,get:function(){return j8.ValueScope}});Object.defineProperty(zt,"ValueScopeName",{enumerable:!0,get:function(){return j8.ValueScopeName}});Object.defineProperty(zt,"varKinds",{enumerable:!0,get:function(){return j8.varKinds}});zt.operators={GT:new mr._Code(">"),GTE:new mr._Code(">="),LT:new mr._Code("<"),LTE:new mr._Code("<="),EQ:new mr._Code("==="),NEQ:new mr._Code("!=="),NOT:new mr._Code("!"),OR:new mr._Code("||"),AND:new mr._Code("&&"),ADD:new mr._Code("+")};var Af=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},_fe=class extends Af{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?$l.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Nv(this.rhs,e,r)),this}get names(){return this.rhs instanceof mr._CodeOrName?this.rhs.names:{}}},U8=class extends Af{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof mr.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Nv(this.rhs,e,r),this}get names(){let e=this.lhs instanceof mr.Name?{}:{...this.lhs.names};return q8(e,this.rhs)}},Dfe=class extends U8{constructor(e,r,n,i){super(e,n,i),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Sfe=class extends Af{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Rfe=class extends Af{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Bfe=class extends Af{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},xfe=class extends Af{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Nv(this.code,e,r),this}get names(){return this.code instanceof mr._CodeOrName?this.code.names:{}}},$T=class extends Af{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,i=n.length;for(;i--;){let o=n[i];o.optimizeNames(e,r)||(jwr(e,o.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Cy(e,r.names),{})}},gf=class extends $T{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Tfe=class extends $T{},kv=class extends gf{};kv.kind="else";var Ey=class t extends gf{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new kv(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Fct(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Nv(this.condition,e,r),this}get names(){let e=super.names;return q8(e,this.condition),this.else&&Cy(e,this.else.names),e}};Ey.kind="if";var by=class extends gf{};by.kind="for";var kfe=class extends by{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Nv(this.iteration,e,r),this}get names(){return Cy(super.names,this.iteration.names)}},Nfe=class extends by{constructor(e,r,n,i){super(),this.varKind=e,this.name=r,this.from=n,this.to=i}render(e){let r=e.es5?$l.varKinds.var:this.varKind,{name:n,from:i,to:o}=this;return`for(${r} ${n}=${i}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=q8(super.names,this.from);return q8(e,this.to)}},$8=class extends by{constructor(e,r,n,i){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Nv(this.iterable,e,r),this}get names(){return Cy(super.names,this.iterable.names)}},qT=class extends gf{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};qT.kind="func";var jT=class extends $T{render(e){return"return "+super.render(e)}};jT.kind="return";var Ofe=class extends gf{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,i;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(i=this.finally)===null||i===void 0||i.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Cy(e,this.catch.names),this.finally&&Cy(e,this.finally.names),e}},YT=class extends gf{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};YT.kind="catch";var HT=class extends gf{render(e){return"finally"+super.render(e)}};HT.kind="finally";var Ffe=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
869
869
|
`:""},this._extScope=e,this._scope=new $l.Scope({parent:e}),this._nodes=[new Tfe]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,i){let o=this._scope.toName(r);return n!==void 0&&i&&(this._constants[o.str]=n),this._leafNode(new _fe(e,o,n)),o}const(e,r,n){return this._def($l.varKinds.const,e,r,n)}let(e,r,n){return this._def($l.varKinds.let,e,r,n)}var(e,r,n){return this._def($l.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new U8(e,r,n))}add(e,r){return this._leafNode(new Dfe(e,zt.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==mr.nil&&this._leafNode(new xfe(e)),this}object(...e){let r=["{"];for(let[n,i]of e)r.length>1&&r.push(","),r.push(n),(n!==i||this.opts.es5)&&(r.push(":"),(0,mr.addCodeArg)(r,i));return r.push("}"),new mr._Code(r)}if(e,r,n){if(this._blockNode(new Ey(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Ey(e))}else(){return this._elseNode(new kv)}endIf(){return this._endBlockNode(Ey,kv)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new kfe(e),r)}forRange(e,r,n,i,o=this.opts.es5?$l.varKinds.var:$l.varKinds.let){let s=this._scope.toName(e);return this._for(new Nfe(o,s,r,n),()=>i(s))}forOf(e,r,n,i=$l.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=r instanceof mr.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,mr._)`${s}.length`,a=>{this.var(o,(0,mr._)`${s}[${a}]`),n(o)})}return this._for(new $8("of",i,o,r),()=>n(o))}forIn(e,r,n,i=this.opts.es5?$l.varKinds.var:$l.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,mr._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new $8("in",i,o,r),()=>n(o))}endFor(){return this._endBlockNode(by)}label(e){return this._leafNode(new Sfe(e))}break(e){return this._leafNode(new Rfe(e))}return(e){let r=new jT;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(jT)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Ofe;if(this._blockNode(i),this.code(e),r){let o=this.name("e");this._currNode=i.catch=new YT(o),r(o)}return n&&(this._currNode=i.finally=new HT,this.code(n)),this._endBlockNode(YT,HT)}throw(e){return this._leafNode(new Bfe(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=mr.nil,n,i){return this._blockNode(new qT(e,r,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(qT)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Ey))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};zt.CodeGen=Ffe;function Cy(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function q8(t,e){return e instanceof mr._CodeOrName?Cy(t,e.names):t}function Nv(t,e,r){if(t instanceof mr.Name)return n(t);if(!i(t))return t;return new mr._Code(t._items.reduce((o,s)=>(s instanceof mr.Name&&(s=n(s)),s instanceof mr._Code?o.push(...s._items):o.push(s),o),[]));function n(o){let s=r[o.str];return s===void 0||e[o.str]!==1?o:(delete e[o.str],s)}function i(o){return o instanceof mr._Code&&o._items.some(s=>s instanceof mr.Name&&e[s.str]===1&&r[s.str]!==void 0)}}function jwr(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Fct(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,mr._)`!${Qfe(t)}`}zt.not=Fct;var Ywr=Qct(zt.operators.AND);function Hwr(...t){return t.reduce(Ywr)}zt.and=Hwr;var zwr=Qct(zt.operators.OR);function Gwr(...t){return t.reduce(zwr)}zt.or=Gwr;function Qct(t){return(e,r)=>e===mr.nil?r:r===mr.nil?e:(0,mr._)`${Qfe(e)} ${t} ${Qfe(r)}`}function Qfe(t){return t instanceof mr.Name?t:(0,mr._)`(${t})`}});var Cr=b(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.checkStrictMode=nr.getErrorPath=nr.Type=nr.useFunc=nr.setEvaluated=nr.evaluatedPropsToName=nr.mergeEvaluated=nr.eachItem=nr.unescapeJsonPointer=nr.escapeJsonPointer=nr.escapeFragment=nr.unescapeFragment=nr.schemaRefOrVal=nr.schemaHasRulesButRef=nr.schemaHasRules=nr.checkUnknownRules=nr.alwaysValidSchema=nr.toHash=void 0;var un=jt(),Jwr=UT();function Vwr(t){let e={};for(let r of t)e[r]=!0;return e}nr.toHash=Vwr;function Wwr(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Pct(t,e),!Uct(e,t.self.RULES.all))}nr.alwaysValidSchema=Wwr;function Pct(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let o in e)i[o]||jct(t,`unknown keyword: "${o}"`)}nr.checkUnknownRules=Pct;function Uct(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}nr.schemaHasRules=Uct;function Zwr(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}nr.schemaHasRulesButRef=Zwr;function Kwr({topSchemaRef:t,schemaPath:e},r,n,i){if(!i){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,un._)`${r}`}return(0,un._)`${t}${e}${(0,un.getProperty)(n)}`}nr.schemaRefOrVal=Kwr;function Xwr(t){return $ct(decodeURIComponent(t))}nr.unescapeFragment=Xwr;function e_r(t){return encodeURIComponent(Mfe(t))}nr.escapeFragment=e_r;function Mfe(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}nr.escapeJsonPointer=Mfe;function $ct(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}nr.unescapeJsonPointer=$ct;function t_r(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}nr.eachItem=t_r;function Lct({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(i,o,s,a)=>{let c=s===void 0?o:s instanceof un.Name?(o instanceof un.Name?t(i,o,s):e(i,o,s),s):o instanceof un.Name?(e(i,s,o),o):r(o,s);return a===un.Name&&!(c instanceof un.Name)?n(i,c):c}}nr.mergeEvaluated={props:Lct({mergeNames:(t,e,r)=>t.if((0,un._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,un._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,un._)`${r} || {}`).code((0,un._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,un._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,un._)`${r} || {}`),Pfe(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:qct}),items:Lct({mergeNames:(t,e,r)=>t.if((0,un._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,un._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,un._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,un._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function qct(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,un._)`{}`);return e!==void 0&&Pfe(t,r,e),r}nr.evaluatedPropsToName=qct;function Pfe(t,e,r){Object.keys(r).forEach(n=>t.assign((0,un._)`${e}${(0,un.getProperty)(n)}`,!0))}nr.setEvaluated=Pfe;var Mct={};function r_r(t,e){return t.scopeValue("func",{ref:e,code:Mct[e.code]||(Mct[e.code]=new Jwr._Code(e.code))})}nr.useFunc=r_r;var Lfe;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Lfe||(nr.Type=Lfe={}));function n_r(t,e,r){if(t instanceof un.Name){let n=e===Lfe.Num;return r?n?(0,un._)`"[" + ${t} + "]"`:(0,un._)`"['" + ${t} + "']"`:n?(0,un._)`"/" + ${t}`:(0,un._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,un.getProperty)(t).toString():"/"+Mfe(t)}nr.getErrorPath=n_r;function jct(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}nr.checkStrictMode=jct});var yf=b(Ufe=>{"use strict";Object.defineProperty(Ufe,"__esModule",{value:!0});var as=jt(),i_r={data:new as.Name("data"),valCxt:new as.Name("valCxt"),instancePath:new as.Name("instancePath"),parentData:new as.Name("parentData"),parentDataProperty:new as.Name("parentDataProperty"),rootData:new as.Name("rootData"),dynamicAnchors:new as.Name("dynamicAnchors"),vErrors:new as.Name("vErrors"),errors:new as.Name("errors"),this:new as.Name("this"),self:new as.Name("self"),scope:new as.Name("scope"),json:new as.Name("json"),jsonPos:new as.Name("jsonPos"),jsonLen:new as.Name("jsonLen"),jsonPart:new as.Name("jsonPart")};Ufe.default=i_r});var zT=b(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});cs.extendErrors=cs.resetErrorsCount=cs.reportExtraError=cs.reportError=cs.keyword$DataError=cs.keywordError=void 0;var vr=jt(),Y8=Cr(),Fs=yf();cs.keywordError={message:({keyword:t})=>(0,vr.str)`must pass "${t}" keyword validation`};cs.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,vr.str)`"${t}" keyword must be ${e} ($data)`:(0,vr.str)`"${t}" keyword is invalid ($data)`};function o_r(t,e=cs.keywordError,r,n){let{it:i}=t,{gen:o,compositeRule:s,allErrors:a}=i,c=zct(t,e,r);n??(s||a)?Yct(o,c):Hct(i,(0,vr._)`[${c}]`)}cs.reportError=o_r;function s_r(t,e=cs.keywordError,r){let{it:n}=t,{gen:i,compositeRule:o,allErrors:s}=n,a=zct(t,e,r);Yct(i,a),o||s||Hct(n,Fs.default.vErrors)}cs.reportExtraError=s_r;function a_r(t,e){t.assign(Fs.default.errors,e),t.if((0,vr._)`${Fs.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,vr._)`${Fs.default.vErrors}.length`,e),()=>t.assign(Fs.default.vErrors,null)))}cs.resetErrorsCount=a_r;function c_r({gen:t,keyword:e,schemaValue:r,data:n,errsCount:i,it:o}){if(i===void 0)throw new Error("ajv implementation error");let s=t.name("err");t.forRange("i",i,Fs.default.errors,a=>{t.const(s,(0,vr._)`${Fs.default.vErrors}[${a}]`),t.if((0,vr._)`${s}.instancePath === undefined`,()=>t.assign((0,vr._)`${s}.instancePath`,(0,vr.strConcat)(Fs.default.instancePath,o.errorPath))),t.assign((0,vr._)`${s}.schemaPath`,(0,vr.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,vr._)`${s}.schema`,r),t.assign((0,vr._)`${s}.data`,n))})}cs.extendErrors=c_r;function Yct(t,e){let r=t.const("err",e);t.if((0,vr._)`${Fs.default.vErrors} === null`,()=>t.assign(Fs.default.vErrors,(0,vr._)`[${r}]`),(0,vr._)`${Fs.default.vErrors}.push(${r})`),t.code((0,vr._)`${Fs.default.errors}++`)}function Hct(t,e){let{gen:r,validateName:n,schemaEnv:i}=t;i.$async?r.throw((0,vr._)`new ${t.ValidationError}(${e})`):(r.assign((0,vr._)`${n}.errors`,e),r.return(!1))}var vy={keyword:new vr.Name("keyword"),schemaPath:new vr.Name("schemaPath"),params:new vr.Name("params"),propertyName:new vr.Name("propertyName"),message:new vr.Name("message"),schema:new vr.Name("schema"),parentSchema:new vr.Name("parentSchema")};function zct(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,vr._)`{}`:l_r(t,e,r)}function l_r(t,e,r={}){let{gen:n,it:i}=t,o=[u_r(i,r),d_r(t,r)];return f_r(t,e,o),n.object(...o)}function u_r({errorPath:t},{instancePath:e}){let r=e?(0,vr.str)`${t}${(0,Y8.getErrorPath)(e,Y8.Type.Str)}`:t;return[Fs.default.instancePath,(0,vr.strConcat)(Fs.default.instancePath,r)]}function d_r({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let i=n?e:(0,vr.str)`${e}/${t}`;return r&&(i=(0,vr.str)`${i}${(0,Y8.getErrorPath)(r,Y8.Type.Str)}`),[vy.schemaPath,i]}function f_r(t,{params:e,message:r},n){let{keyword:i,data:o,schemaValue:s,it:a}=t,{opts:c,propertyName:u,topSchemaRef:d,schemaPath:f}=a;n.push([vy.keyword,i],[vy.params,typeof e=="function"?e(t):e||(0,vr._)`{}`]),c.messages&&n.push([vy.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([vy.schema,s],[vy.parentSchema,(0,vr._)`${d}${f}`],[Fs.default.data,o]),u&&n.push([vy.propertyName,u])}});var Jct=b(Ov=>{"use strict";Object.defineProperty(Ov,"__esModule",{value:!0});Ov.boolOrEmptySchema=Ov.topBoolOrEmptySchema=void 0;var p_r=zT(),h_r=jt(),m_r=yf(),A_r={message:"boolean schema is false"};function g_r(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Gct(t,!1):typeof r=="object"&&r.$async===!0?e.return(m_r.default.data):(e.assign((0,h_r._)`${n}.errors`,null),e.return(!0))}Ov.topBoolOrEmptySchema=g_r;function y_r(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Gct(t)):r.var(e,!0)}Ov.boolOrEmptySchema=y_r;function Gct(t,e){let{gen:r,data:n}=t,i={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,p_r.reportError)(i,A_r,void 0,e)}});var $fe=b(Fv=>{"use strict";Object.defineProperty(Fv,"__esModule",{value:!0});Fv.getRules=Fv.isJSONType=void 0;var E_r=["string","number","integer","boolean","null","object","array"],b_r=new Set(E_r);function C_r(t){return typeof t=="string"&&b_r.has(t)}Fv.isJSONType=C_r;function v_r(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Fv.getRules=v_r});var qfe=b(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});tm.shouldUseRule=tm.shouldUseGroup=tm.schemaHasRulesForType=void 0;function I_r({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Vct(t,n)}tm.schemaHasRulesForType=I_r;function Vct(t,e){return e.rules.some(r=>Wct(t,r))}tm.shouldUseGroup=Vct;function Wct(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}tm.shouldUseRule=Wct});var GT=b(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.reportTypeError=ls.checkDataTypes=ls.checkDataType=ls.coerceAndCheckDataType=ls.getJSONTypes=ls.getSchemaTypes=ls.DataType=void 0;var w_r=$fe(),__r=qfe(),D_r=zT(),$t=jt(),Zct=Cr(),Qv;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Qv||(ls.DataType=Qv={}));function S_r(t){let e=Kct(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ls.getSchemaTypes=S_r;function Kct(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(w_r.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ls.getJSONTypes=Kct;function R_r(t,e){let{gen:r,data:n,opts:i}=t,o=B_r(e,i.coerceTypes),s=e.length>0&&!(o.length===0&&e.length===1&&(0,__r.schemaHasRulesForType)(t,e[0]));if(s){let a=Yfe(e,n,i.strictNumbers,Qv.Wrong);r.if(a,()=>{o.length?x_r(t,e,o):Hfe(t)})}return s}ls.coerceAndCheckDataType=R_r;var Xct=new Set(["string","number","integer","boolean","null"]);function B_r(t,e){return e?t.filter(r=>Xct.has(r)||e==="array"&&r==="array"):[]}function x_r(t,e,r){let{gen:n,data:i,opts:o}=t,s=n.let("dataType",(0,$t._)`typeof ${i}`),a=n.let("coerced",(0,$t._)`undefined`);o.coerceTypes==="array"&&n.if((0,$t._)`${s} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,$t._)`${i}[0]`).assign(s,(0,$t._)`typeof ${i}`).if(Yfe(e,i,o.strictNumbers),()=>n.assign(a,i))),n.if((0,$t._)`${a} !== undefined`);for(let u of r)(Xct.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),Hfe(t),n.endIf(),n.if((0,$t._)`${a} !== undefined`,()=>{n.assign(i,a),T_r(t,a)});function c(u){switch(u){case"string":n.elseIf((0,$t._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,$t._)`"" + ${i}`).elseIf((0,$t._)`${i} === null`).assign(a,(0,$t._)`""`);return;case"number":n.elseIf((0,$t._)`${s} == "boolean" || ${i} === null
|
|
870
870
|
|| (${s} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,$t._)`+${i}`);return;case"integer":n.elseIf((0,$t._)`${s} === "boolean" || ${i} === null
|