@stndrds/schema 1.0.0-alpha.329 → 1.0.0-alpha.331

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.
Files changed (165) hide show
  1. package/dist/all-CWDgBPuS.d.ts +1186 -0
  2. package/dist/all-DilIWUev.d.mts +1186 -0
  3. package/dist/capabilities.d.mts +94 -94
  4. package/dist/capabilities.d.ts +94 -94
  5. package/dist/capabilities.js +2 -2
  6. package/dist/capabilities.mjs +2 -2
  7. package/dist/checkbox-CjnTd8DE.d.ts +11 -0
  8. package/dist/checkbox-preO352q.d.mts +11 -0
  9. package/dist/config-BQJJHopR.js +13 -0
  10. package/dist/config-_sOeudpS.mjs +13 -0
  11. package/dist/core-397tQy5q.js +2 -0
  12. package/dist/core-BLHhNykL.mjs +2 -0
  13. package/dist/date-BL3UHIXs.d.mts +24 -0
  14. package/dist/date-CxwHkbid.d.ts +24 -0
  15. package/dist/exceptions-DGCzCc9t.d.mts +1405 -0
  16. package/dist/exceptions-DGCzCc9t.d.ts +1405 -0
  17. package/dist/exceptions.d.mts +3 -2
  18. package/dist/exceptions.d.ts +3 -2
  19. package/dist/exceptions.js +3 -1
  20. package/dist/exceptions.mjs +3 -1
  21. package/dist/index-B7HmBsUS.d.ts +53 -0
  22. package/dist/{helpers-qMMFwD1I.d.ts → index-BoUwfrDH.d.mts} +172 -145
  23. package/dist/index-C8M7Amy9.d.mts +254 -0
  24. package/dist/{helpers-lqSDjgQ1.d.mts → index-DqwNrDSp.d.ts} +172 -145
  25. package/dist/index-Uwy7CTKo.d.ts +254 -0
  26. package/dist/index-XtmC-C7J.d.mts +53 -0
  27. package/dist/index.d.mts +9151 -9136
  28. package/dist/index.d.ts +9151 -9136
  29. package/dist/index.js +21 -27
  30. package/dist/index.mjs +21 -27
  31. package/dist/number-Ddi_YYfm.d.mts +11 -0
  32. package/dist/number-GmD5PM5s.d.ts +11 -0
  33. package/dist/object-DGu0m2Y1.js +4 -0
  34. package/dist/object-DSRy1coV.mjs +4 -0
  35. package/dist/phone-BawtTYVi.mjs +2 -0
  36. package/dist/phone-DVaELsa3.js +2 -0
  37. package/dist/text-A9AJ1wUO.js +2 -0
  38. package/dist/text-C8Lb-NFo.mjs +2 -0
  39. package/dist/text-CxwF5K4k.d.mts +11 -0
  40. package/dist/text-D6UypN8p.d.ts +11 -0
  41. package/dist/utils-fXIvFFl6.mjs +2 -0
  42. package/dist/utils-gY3d9Dwp.js +2 -0
  43. package/dist/utils.d.mts +3 -2
  44. package/dist/utils.d.ts +3 -2
  45. package/dist/utils.js +2 -1
  46. package/dist/utils.mjs +2 -1
  47. package/dist/validation/all.d.mts +6 -8
  48. package/dist/validation/all.d.ts +6 -8
  49. package/dist/validation/all.js +2 -1
  50. package/dist/validation/all.mjs +2 -1
  51. package/dist/validation/complex/currency.d.mts +8 -9
  52. package/dist/validation/complex/currency.d.ts +8 -9
  53. package/dist/validation/complex/currency.js +2 -1
  54. package/dist/validation/complex/currency.mjs +2 -1
  55. package/dist/validation/complex/location.d.mts +14 -15
  56. package/dist/validation/complex/location.d.ts +14 -15
  57. package/dist/validation/complex/location.js +2 -1
  58. package/dist/validation/complex/location.mjs +2 -1
  59. package/dist/validation/complex/phone.d.mts +8 -9
  60. package/dist/validation/complex/phone.d.ts +8 -9
  61. package/dist/validation/complex/phone.js +2 -1
  62. package/dist/validation/complex/phone.mjs +2 -1
  63. package/dist/validation/complex/relation.d.mts +8 -9
  64. package/dist/validation/complex/relation.d.ts +8 -9
  65. package/dist/validation/complex/relation.js +2 -1
  66. package/dist/validation/complex/relation.mjs +2 -1
  67. package/dist/validation/complex/richtext.d.mts +6 -7
  68. package/dist/validation/complex/richtext.d.ts +6 -7
  69. package/dist/validation/complex/richtext.js +2 -1
  70. package/dist/validation/complex/richtext.mjs +2 -1
  71. package/dist/validation/complex/select.d.mts +8 -9
  72. package/dist/validation/complex/select.d.ts +8 -9
  73. package/dist/validation/complex/select.js +2 -1
  74. package/dist/validation/complex/select.mjs +2 -1
  75. package/dist/validation/complex/user.d.mts +6 -7
  76. package/dist/validation/complex/user.d.ts +6 -7
  77. package/dist/validation/complex/user.js +2 -1
  78. package/dist/validation/complex/user.mjs +2 -1
  79. package/dist/validation/computed/formula.d.mts +6 -7
  80. package/dist/validation/computed/formula.d.ts +6 -7
  81. package/dist/validation/computed/formula.js +2 -1
  82. package/dist/validation/computed/formula.mjs +2 -1
  83. package/dist/validation/computed/rollup.d.mts +6 -7
  84. package/dist/validation/computed/rollup.d.ts +6 -7
  85. package/dist/validation/computed/rollup.js +2 -1
  86. package/dist/validation/computed/rollup.mjs +2 -1
  87. package/dist/validation/config/index.d.mts +3 -4
  88. package/dist/validation/config/index.d.ts +3 -4
  89. package/dist/validation/config/index.js +2 -1
  90. package/dist/validation/config/index.mjs +2 -1
  91. package/dist/validation/core/index.d.mts +2 -17
  92. package/dist/validation/core/index.d.ts +2 -17
  93. package/dist/validation/core/index.js +2 -1
  94. package/dist/validation/core/index.mjs +2 -1
  95. package/dist/validation/object/index.d.mts +2 -29
  96. package/dist/validation/object/index.d.ts +2 -29
  97. package/dist/validation/object/index.js +2 -1
  98. package/dist/validation/object/index.mjs +2 -1
  99. package/dist/validation/primitives/checkbox.d.mts +2 -10
  100. package/dist/validation/primitives/checkbox.d.ts +2 -10
  101. package/dist/validation/primitives/checkbox.js +2 -1
  102. package/dist/validation/primitives/checkbox.mjs +2 -1
  103. package/dist/validation/primitives/date.d.mts +2 -23
  104. package/dist/validation/primitives/date.d.ts +2 -23
  105. package/dist/validation/primitives/date.js +2 -1
  106. package/dist/validation/primitives/date.mjs +2 -1
  107. package/dist/validation/primitives/number.d.mts +2 -10
  108. package/dist/validation/primitives/number.d.ts +2 -10
  109. package/dist/validation/primitives/number.js +2 -1
  110. package/dist/validation/primitives/number.mjs +2 -1
  111. package/dist/validation/primitives/text.d.mts +2 -10
  112. package/dist/validation/primitives/text.d.ts +2 -10
  113. package/dist/validation/primitives/text.js +2 -1
  114. package/dist/validation/primitives/text.mjs +2 -1
  115. package/dist/view-config.schema-B4AkqLKQ.mjs +2 -0
  116. package/dist/view-config.schema-to6p1m8L.js +2 -0
  117. package/package.json +7 -6
  118. package/dist/all-BgP-bB0i.d.mts +0 -1178
  119. package/dist/all-Cq8ZMfM4.d.ts +0 -1178
  120. package/dist/attributes-Cv6IP8-a.d.mts +0 -1365
  121. package/dist/attributes-Cv6IP8-a.d.ts +0 -1365
  122. package/dist/chunk-23KPS33D.js +0 -2
  123. package/dist/chunk-2M4YXNYZ.js +0 -15
  124. package/dist/chunk-47KVYDKG.js +0 -2
  125. package/dist/chunk-4OTKOCGB.mjs +0 -2
  126. package/dist/chunk-4VCADZK4.mjs +0 -2
  127. package/dist/chunk-53RAH3XB.mjs +0 -2
  128. package/dist/chunk-DPD6ZWL2.js +0 -2
  129. package/dist/chunk-EZCWO4XV.mjs +0 -15
  130. package/dist/chunk-GKXTXH4Y.mjs +0 -2
  131. package/dist/chunk-GXSNLYRR.js +0 -2
  132. package/dist/chunk-IBM4ID4Y.js +0 -6
  133. package/dist/chunk-JFSQ24XR.js +0 -2
  134. package/dist/chunk-JOS2XMXY.js +0 -2
  135. package/dist/chunk-JSKLP4GI.js +0 -12
  136. package/dist/chunk-JVLH3DVZ.js +0 -2
  137. package/dist/chunk-KG2ADZG6.mjs +0 -2
  138. package/dist/chunk-KLR22JMC.js +0 -2
  139. package/dist/chunk-KSPJP74K.mjs +0 -2
  140. package/dist/chunk-KYPEBOPW.mjs +0 -2
  141. package/dist/chunk-LB4TNMZU.mjs +0 -2
  142. package/dist/chunk-LSCBR4VS.js +0 -2
  143. package/dist/chunk-LWSOKXPF.js +0 -2
  144. package/dist/chunk-O34B5KOW.mjs +0 -2
  145. package/dist/chunk-PFO7NWQW.mjs +0 -2
  146. package/dist/chunk-Q7TQCRSD.mjs +0 -2
  147. package/dist/chunk-RTHLB6T6.js +0 -2
  148. package/dist/chunk-SLYRQ72J.js +0 -2
  149. package/dist/chunk-UKFOBZX2.js +0 -2
  150. package/dist/chunk-UXISKZ5Y.js +0 -2
  151. package/dist/chunk-VKFLXFPP.mjs +0 -2
  152. package/dist/chunk-WMQRTFOP.mjs +0 -2
  153. package/dist/chunk-XAVRKIBE.mjs +0 -6
  154. package/dist/chunk-XHEBV2HE.js +0 -2
  155. package/dist/chunk-XMQV2WFY.mjs +0 -2
  156. package/dist/chunk-XRDP2Y4J.mjs +0 -2
  157. package/dist/chunk-XRWRECDA.mjs +0 -12
  158. package/dist/chunk-XUAP7KWK.js +0 -2
  159. package/dist/chunk-XXTKNIBK.js +0 -2
  160. package/dist/chunk-YIXNAWH6.mjs +0 -2
  161. package/dist/chunk-YJSVWV3Z.mjs +0 -2
  162. package/dist/index-Comy7znP.d.ts +0 -252
  163. package/dist/index-D4XlMkLV.d.mts +0 -252
  164. package/dist/types-C5Bqalr9.d.ts +0 -38
  165. package/dist/types-CILLmEj-.d.mts +0 -38
package/dist/index.js CHANGED
@@ -1,50 +1,44 @@
1
- 'use strict';var chunkRTHLB6T6_js=require('./chunk-RTHLB6T6.js'),chunkUKFOBZX2_js=require('./chunk-UKFOBZX2.js'),chunk2M4YXNYZ_js=require('./chunk-2M4YXNYZ.js'),chunkIBM4ID4Y_js=require('./chunk-IBM4ID4Y.js');require('./chunk-LWSOKXPF.js'),require('./chunk-XXTKNIBK.js'),require('./chunk-JOS2XMXY.js');var chunk47KVYDKG_js=require('./chunk-47KVYDKG.js'),chunkKLR22JMC_js=require('./chunk-KLR22JMC.js'),chunkGXSNLYRR_js=require('./chunk-GXSNLYRR.js');require('./chunk-UXISKZ5Y.js'),require('./chunk-XUAP7KWK.js'),require('./chunk-JVLH3DVZ.js'),require('./chunk-LSCBR4VS.js'),require('./chunk-23KPS33D.js');var chunkJSKLP4GI_js=require('./chunk-JSKLP4GI.js'),chunkXHEBV2HE_js=require('./chunk-XHEBV2HE.js'),chunkSLYRQ72J_js=require('./chunk-SLYRQ72J.js'),chunkJFSQ24XR_js=require('./chunk-JFSQ24XR.js'),chunkDPD6ZWL2_js=require('./chunk-DPD6ZWL2.js'),constants=require('@stndrds/constants'),zod=require('zod');/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
- var Bo=["fyi","task","question","handoff","system"],Lo=["low","normal","high","urgent"],$o=["public","internal","sensitive"],Uo=["unread","read","archived","snoozed"],qo=["none","pending","processing","completed","dismissed","expired","failed"],Zc="agent.session.waiting_human",Xc="agent.task.assigned",eu="agent.question.requested",Wg=[Zc,Xc,eu];var Kg=["name","type"],Yg=["required","hidden","archived","deprecated","defaultValue","config","order","unique"],Hg=["label","description","placeholder","icon"];var Qt=["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"],ae="*";function Zg(e){return e.type!=="relation"||!Array.isArray(e.targets)?[]:e.targets.map(t=>t.object).filter(t=>t!==ae)}chunkDPD6ZWL2_js.a(Zg,"relationTargetsOf");function zo(e){return e.targets.length===1&&e.targets[0].object===ae}chunkDPD6ZWL2_js.a(zo,"isUniversalRelation");function Xg(e){return e.bilateral!==void 0}chunkDPD6ZWL2_js.a(Xg,"isBilateralRelation");function Wo(e){return "many"}chunkDPD6ZWL2_js.a(Wo,"inferInverseCardinality");function ey(e){return chunkUKFOBZX2_js.n(e)}chunkDPD6ZWL2_js.a(ey,"isAttributeSortable");var ry=["record","object","attribute","view","user","role","settings","file","agent","schema_source"],iy=["record.created","record.updated","record.deleted","record.restored","record.purged","object.created","object.updated","object.deleted","attribute.created","attribute.updated","attribute.deleted","view.created","view.updated","view.deleted","schema_source.applied","schema_source.removed","user.created","user.invited","user.updated","user.deleted","user.login","user.logout","role.created","role.updated","role.deleted","role.assigned","role.revoked","settings.updated","file.uploaded","file.updated","file.deleted"];function sy(e){return e.phase==="terminal"}chunkDPD6ZWL2_js.a(sy,"isTerminalState");function cy(e){switch(e.phase){case "running":return "active";case "queued":return "idle";case "parked":if(e.parkedOn===void 0)throw new chunkJSKLP4GI_js.b("parked state without parkedOn",chunkJSKLP4GI_js.a.INVARIANT_VIOLATION);return e.parkedOn==="agents"?"waiting_agents":"waiting_human";case "terminal":if(e.outcome===void 0)throw new chunkJSKLP4GI_js.b("terminal state without outcome",chunkJSKLP4GI_js.a.INVARIANT_VIOLATION);return e.outcome}}chunkDPD6ZWL2_js.a(cy,"sessionStateToLegacyStatus");function uy(e){switch(e){case "active":return {phase:"running"};case "idle":return {phase:"queued"};case "waiting_human":return {phase:"parked",parkedOn:"human",humanRequestIds:[]};case "waiting_agents":return {phase:"parked",parkedOn:"agents"};default:return {phase:"terminal",outcome:e}}}chunkDPD6ZWL2_js.a(uy,"legacyStatusToSessionState");var tu=["completed","failed","cancelled","timeout","expired"];function ly(e){return tu.includes(e)}chunkDPD6ZWL2_js.a(ly,"isTerminalSessionStatus");var nu=["idle","completed","waiting_human","waiting_agents","cancelled","failed","timeout"];function dy(e){return nu.includes(e)}chunkDPD6ZWL2_js.a(dy,"isClaimableSessionStatus");var Go=Object.freeze({mutation:"ask",destructive:"ask",outward:"ask"}),py=["active","completed","abandoned"],Ko=["openai","anthropic","google","spacexai","deepseek","moonshotai","alibaba","mistral","minimax","meta","zai"],Yo=["standard","fast"],Ho=["none","minimal","low","medium","high","xhigh"];function my(e){return e.label?.trim()||e.name}chunkDPD6ZWL2_js.a(my,"agentDisplayName");var Jo=["approval-requested","approval-responded","approval-dispatched"],ru=["streaming","running","pending",...Jo];function fy(e){return ru.includes(e)}chunkDPD6ZWL2_js.a(fy,"isOpenToolPartState");function by(e){return Jo.includes(e)}chunkDPD6ZWL2_js.a(by,"isToolApprovalState");var Kn=["CREDITS_EXHAUSTED"];function gy(e){return typeof e=="string"&&Kn.includes(e)}chunkDPD6ZWL2_js.a(gy,"isSystemPartCode");function iu(e,t){let n=e.createdAt.getTime()-t.createdAt.getTime();return n===0?e.id.localeCompare(t.id):n}chunkDPD6ZWL2_js.a(iu,"compareAgentSessionMessages");function yy(e){return [...e].sort(iu)}chunkDPD6ZWL2_js.a(yy,"orderAgentSessionMessages");var hy=["pending","in_progress","completed","blocked"],Ay=50,xy=80,Ty=500;var Ry="session-state",ou="__stndrdsNativeUiPartIds",au=1,su="Native agent UI part IDs metadata is invalid";function qe(){throw new chunkJSKLP4GI_js.h(su,[])}chunkDPD6ZWL2_js.a(qe,"invalidNativePartIds");function Qo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}chunkDPD6ZWL2_js.a(Qo,"isPlainRecord");function cu(e,t){if(e.type==="text"||e.type==="reasoning")return `${e.type}:${t}`;if(e.type==="tool")return `tool:${e.toolCallId}`}chunkDPD6ZWL2_js.a(cu,"nativeAgentUIPartIdMetadataKey");function Cy(e){let t=e.metadata?.[ou];Qo(t)||qe(),(Object.keys(t).length!==2||t.schemaVersion!==au||!Qo(t.partIds))&&qe();let n=new Map;for(let[s,c]of e.parts.entries()){let u=cu(c,s);if(!u||n.has(u)){u&&qe();continue}n.set(u,c);}let r=Object.entries(t.partIds);r.length!==n.size&&qe();let o=new Map,a={};for(let[s,c]of r){let u=n.get(s);u&&typeof c=="string"&&c.length>0||qe();let l=o.get(c);l&&(u.type==="tool"||l!==u.type)&&qe(),u.type==="tool"&&c!==u.toolCallId&&qe(),o.set(c,u.type),a[s]=c;}return a}chunkDPD6ZWL2_js.a(Cy,"parseNativeAgentUIPartIdsMetadata");var Ny=16e3,Dy=3200,Oy=6400,jy=16e3,ky=65536,_y=15e3,Py=1e4,My=5e3,Fy="google/gemini-3.5-transcribe-live",Vy={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2};var Ly=["web","presentation","document","spreadsheet","image","code","other"],$y=["ephemeral","conversation","persistent"],Uy=["source","preview","entrypoint","asset"];var Zo=5;function Wy(e){return e instanceof Error?e.message:typeof e=="string"?e:e&&typeof e=="object"?"message"in e&&typeof e.message=="string"?e.message:JSON.stringify(e):String(e)}chunkDPD6ZWL2_js.a(Wy,"getErrorMessage");function Hy(e){return typeof e=="object"&&e!==null&&"slots"in e&&"steps"in e&&"name"in e&&typeof e.name=="string"&&Array.isArray(e.slots)&&Array.isArray(e.steps)}chunkDPD6ZWL2_js.a(Hy,"isFormDefinition");var Yn=["relation","multiRelation","formula","rollup","document","richtext","user"];function Xo(e){return e.type==="slot"}chunkDPD6ZWL2_js.a(Xo,"isFormSlotFieldRef");function Hn(e){return e.type==="free"}chunkDPD6ZWL2_js.a(Hn,"isFormFreeFieldRef");function Zy(e){return e.fieldRequired!==void 0?e.fieldRequired:e.slotMode==="create"&&e.attributeRequired===true}chunkDPD6ZWL2_js.a(Zy,"resolveFieldRequired");function ea(e){return e.additionalSlotIds?.length?[e.slotId,...e.additionalSlotIds]:[e.slotId]}chunkDPD6ZWL2_js.a(ea,"getSlotFieldTargets");function uu(e){return Xo(e)?`${e.slotId}.${e.attribute}`:`free.${e.attribute.name}`}chunkDPD6ZWL2_js.a(uu,"formFieldKey");function lu(e){return Xo(e)?e.attribute:e.attribute.name}chunkDPD6ZWL2_js.a(lu,"formFieldFlatKey");function Xy(e,t){return e[uu(t)]??e[lu(t)]}chunkDPD6ZWL2_js.a(Xy,"readFormFieldValue");function Zt(e){return e.type==="fields"}chunkDPD6ZWL2_js.a(Zt,"isFormFieldsRow");function nh(e){return e.type==="heading"}chunkDPD6ZWL2_js.a(nh,"isFormHeadingRow");function rh(e){return e.type==="separator"}chunkDPD6ZWL2_js.a(rh,"isFormSeparatorRow");function ih(e){return e.type==="text"}chunkDPD6ZWL2_js.a(ih,"isFormTextRow");var Jn=class Jn{async autocomplete(){return await Promise.resolve([])}async reverse(){return await Promise.resolve(null)}async geocode(){return await Promise.resolve(null)}};chunkDPD6ZWL2_js.a(Jn,"NoopGeocodingAdapter");var ta=Jn;var Qn=["read","create","update","delete","manage"];function dh(e){return e.length===0?"none":e.length===1&&e[0]==="read"?"read-only":e.length===Qn.length&&Qn.every(t=>e.includes(t))?"full":"custom"}chunkDPD6ZWL2_js.a(dh,"actionsToAccessLevel");function ph(e){switch(e){case "full":return [...Qn];case "read-only":return ["read"];case "none":return []}}chunkDPD6ZWL2_js.a(ph,"accessLevelToActions");function Xt(e){let t=e.properties;if(!t)return [];if(Array.isArray(t))return t;let n=t;return Array.isArray(n.definitions)?n.definitions:[]}chunkDPD6ZWL2_js.a(Xt,"resolvePropertyDefinitions");function bh(e){return e.type==="select"||e.type==="status"||e.type==="multiselect"}chunkDPD6ZWL2_js.a(bh,"hasOptions");var du="Notetaker",hh={systemPrompt:null,meetingRecordingPolicy:"none",meetingBotDisplayName:du};var xh=["active","suspended"],Th=["architect","manual","auto"];var Sh=["square","landscape","portrait"];var na=["none","estimated","exact"];function pu(e){if(typeof e=="string"&&na.includes(e))return e;throw new chunkJSKLP4GI_js.h(`countMode must be one of: ${na.join(", ")} (received: ${String(e)})`,[])}chunkDPD6ZWL2_js.a(pu,"parseCountMode");function Ch(e){return e===void 0?void 0:pu(e)}chunkDPD6ZWL2_js.a(Ch,"parseOptionalCountMode");var vh=1e4;var Dh=["storage.bytes","members.seats","data.live_records"];function mu(e){return e==null?true:typeof e!="object"?false:Object.keys(e).length===0}chunkDPD6ZWL2_js.a(mu,"isEmptyObject");function ra(e){return e!=null&&typeof e=="object"&&Object.keys(e).length>0}chunkDPD6ZWL2_js.a(ra,"isNotEmpty");function fu(e){return ra(e)?e:void 0}chunkDPD6ZWL2_js.a(fu,"toUndefinedIfEmpty");function bu(e){if(e<=0)return {value:0,unitIndex:0};let t=1e3,n=Math.min(4,Math.floor(Math.log(e)/Math.log(t)));return {value:Number.parseFloat((e/t**n).toFixed(1)),unitIndex:n}}chunkDPD6ZWL2_js.a(bu,"computeByteMagnitude");var gu=["B","KB","MB","GB","TB"];function wA(e){let{value:t,unitIndex:n}=bu(e);return `${t} ${gu[n]}`}chunkDPD6ZWL2_js.a(wA,"formatByteSize");var RA={ATTACHMENTS:"attachments"};function CA(e){return e.type==="document"}chunkDPD6ZWL2_js.a(CA,"isDocumentAttribute");function vA(e,t){if(!t||t.length===0)return true;let n=e.name.toLowerCase();return t.some(r=>r.endsWith("/*")?e.mimeType.startsWith(r.slice(0,-1)):r.startsWith(".")?n.endsWith(r.toLowerCase()):e.mimeType===r)}chunkDPD6ZWL2_js.a(vA,"matchesAccepts");var ia=Object.freeze(["text","number","checkbox","date","phone","currency","status","select","multiselect","location"]);function en(e){let t=[];for(let n of e){let r=n.build();if(!ia.includes(r.type))throw new Error(`Property type "${r.type}" is not supported in .qualifyWith()`);t.push(r);}return {definitions:t}}chunkDPD6ZWL2_js.a(en,"buildPropertySchema");var jA="__";function kA(e){let t=e.indexOf("__");return t<=0||t+2>=e.length?{kind:"scalar",attribute:e}:{kind:"qualified",root:e.slice(0,t),property:e.slice(t+2)}}chunkDPD6ZWL2_js.a(kA,"parseQualifiedAttribute");function _A(e,t){return `${e}__${t}`}chunkDPD6ZWL2_js.a(_A,"buildQualifiedAttribute");function Oe(e){return typeof e=="object"&&e!==null&&typeof e.start=="string"}chunkDPD6ZWL2_js.a(Oe,"isDateRangeValue");function yu(e,t){return chunkIBM4ID4Y_js.a(e)?null:Oe(e)?t.endDate?{start:e.start,end:e.end??null}:e.start:typeof e=="string"?t.endDate?{start:e,end:null}:e:null}chunkDPD6ZWL2_js.a(yu,"normalizeDateValue");function nt(e){return typeof e=="string"&&e!==""?e:Oe(e)&&e.start!==""?e.start:null}chunkDPD6ZWL2_js.a(nt,"dateValueStart");var tn="\u2014";function hu(e){return String(e)}chunkDPD6ZWL2_js.a(hu,"formatText");function Au(e){return e?"Yes":"No"}chunkDPD6ZWL2_js.a(Au,"formatCheckbox");function xu(e,t){if(typeof e!="number")return String(e);if(t.renderAs==="rating")return `${e}/${t.max??5}`;let n=t.decimals;return t.unit==="integer"?e.toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:0}):t.unit==="percentage"?(e/100).toLocaleString(void 0,{style:"percent",minimumFractionDigits:n,maximumFractionDigits:n}):e.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})}chunkDPD6ZWL2_js.a(xu,"formatNumber");function Tu(e,t){if(typeof e!="object"||e===null)return String(e);let n=e;return "value"in n&&"code"in n?`${n.value.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})} ${n.code}`:String(e)}chunkDPD6ZWL2_js.a(Tu,"formatCurrency");function Zn(e){if(Oe(e)){let t=Zn(e.start);return e.end?`${t} \u2192 ${Zn(e.end)}`:t}if(e instanceof Date)return e.toISOString().split("T")[0];if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString().split("T")[0]}return String(e)}chunkDPD6ZWL2_js.a(Zn,"formatDate");function wu(e){if(typeof e!="object"||e===null)return String(e);let t=e;return "phoneNumber"in t?t.phoneNumber?t.countryCode?chunkGXSNLYRR_js.c(t):t.phoneNumber:"":String(e)}chunkDPD6ZWL2_js.a(wu,"formatPhone");function Su(e,t="full"){if(typeof e!="object"||e===null)return "";let n=e,r=[];switch(t){case "country":n.country&&r.push(constants.getCountryDisplayNameByIso3(n.country));break;case "state":n.state&&r.push(n.state),n.country&&r.push(constants.getCountryDisplayNameByIso3(n.country));break;case "city":n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(constants.getCountryDisplayNameByIso3(n.country));break;case "coordinates":n.latitude!==void 0&&n.longitude!==void 0&&r.push(`${n.latitude}, ${n.longitude}`);break;case "address":n.address&&r.push(n.address),n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(constants.getCountryDisplayNameByIso3(n.country));break;default:n.address&&r.push(n.address),n.address2&&r.push(n.address2),n.city&&r.push(n.city),n.state&&r.push(n.state),n.postalCode&&r.push(n.postalCode),n.country&&r.push(constants.getCountryDisplayNameByIso3(n.country));break}return r.join(", ")}chunkDPD6ZWL2_js.a(Su,"formatLocationValue");function Iu(e,t){return typeof e!="object"||e===null?String(e):Su(e,t.granularity??"full")||tn}chunkDPD6ZWL2_js.a(Iu,"formatLocation");function Ru(e,t){return typeof e!="string"?String(e):t.options?.find(r=>r.value===e)?.label??String(e)}chunkDPD6ZWL2_js.a(Ru,"formatSelect");function Cu(e,t){return Array.isArray(e)?t.options?e.map(r=>t.options.find(o=>o.value===r)?.label).filter(Boolean).join(", "):e.join(", "):String(e)}chunkDPD6ZWL2_js.a(Cu,"formatMultiselect");function oa(e,t){if(chunkIBM4ID4Y_js.a(e))return tn;switch(t.type){case "text":return hu(e);case "checkbox":return Au(e);case "number":return xu(e,t);case "currency":return Tu(e);case "date":return Zn(e);case "phone":return wu(e);case "location":return Iu(e,t);case "select":case "status":return Ru(e,t);case "multiselect":return Cu(e,t);case "user":case "relation":return Array.isArray(e)?e.join(", "):String(e);default:return Array.isArray(e)?e.join(", "):String(e)}}chunkDPD6ZWL2_js.a(oa,"formatAttributeValue");var Eu=["UPPER","LOWER","capitalize","trim"],Nu=["prefix","suffix","wrap","default"],nn=[...Eu,...Nu],rt=zod.z.string().min(1,"labelExpression cannot be empty").refine(e=>rn(e),{message:"labelExpression must contain at least one {{ attribute }} interpolation"}).refine(e=>!/\{\{\s*\}\}/.test(e),{message:"labelExpression contains empty {{ }} interpolation"}).refine(e=>{let t=/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g,n;for(;(n=t.exec(e))!==null;){let r=n[1];if(!nn.includes(r))return false}return true},{message:`Invalid pipe name. Valid pipes: ${nn.join(", ")}`});function Du(e){let t=rt.safeParse(e);return t.success?{success:true,attributes:St(e)}:{success:false,error:t.error.issues[0]?.message??"Invalid labelExpression"}}chunkDPD6ZWL2_js.a(Du,"validateLabelExpression");function Ou(e,t){let{name:n,args:r}=ku(t);switch(n){case "UPPER":return e.toUpperCase();case "LOWER":return e.toLowerCase();case "capitalize":return e.replace(/(^|\s)\S/g,o=>o.toUpperCase());case "trim":return e.trim();case "prefix":return e?`${r[0]??""}${e}`:"";case "suffix":return e?`${e}${r[0]??""}`:"";case "wrap":return e?`${r[0]??""}${e}${r[1]??""}`:"";case "default":return e||r[0]||"";default:return e}}chunkDPD6ZWL2_js.a(Ou,"applyPipe");function aa(e,t){let n=e;for(let r of t)n=Ou(n,r);return n}chunkDPD6ZWL2_js.a(aa,"applyPipes");function ju(e,t){return t.split(".").reduce((n,r)=>{if(!(n==null||typeof n!="object"))return n[r]},e)}chunkDPD6ZWL2_js.a(ju,"getValue");var sa="(Untitled)";function ku(e){let t=e.match(/^(\w+)(?::(.*))?$/);if(!t)return {name:e,args:[]};let n=t[1],r=t[2];if(!r)return {name:n,args:[]};let o=[],a=/["']([^"']*?)["']/g,s;for(;(s=a.exec(r))!==null;)o.push(s[1]);return {name:n,args:o}}chunkDPD6ZWL2_js.a(ku,"parsePipeExpression");function*ca(e){let t=0;for(;t<e.length;){let n=e.indexOf("{{",t);if(n<0)return;let r=e.indexOf("}",n+2);if(r<0)return;if(e[r+1]!=="}"){t=r+1;continue}t=r+2;let o=e.slice(n+2,r);o.length>0&&(yield {start:n,end:t,expr:o});}}chunkDPD6ZWL2_js.a(ca,"templateBlocks");function _u(e,t){let n=e.split("||").map(u=>u.trim()),o=n[n.length-1].split("|").map(u=>u.trim());n[n.length-1]=o[0];let a=o.slice(1).filter(Boolean),s=n.filter(Boolean),c="";for(let u of s){let l=ua(ju(t,u));if(l!==""){c=l;break}}return aa(c,a)}chunkDPD6ZWL2_js.a(_u,"resolveLabelBlock");function Xn(e,t,n=sa){let r=[],o=0;for(let s of ca(e))r.push(e.slice(o,s.start),_u(s.expr,t)),o=s.end;return r.push(e.slice(o)),r.join("").trim()||n}chunkDPD6ZWL2_js.a(Xn,"renderLabelExpression");function ua(e){if(e==null||typeof e=="function")return "";if(typeof e!="object")return String(e);if(Array.isArray(e))return e.map(ua).filter(Boolean).join(",");let t=e.toString;return typeof t=="function"&&t!==Object.prototype.toString?String(e):""}chunkDPD6ZWL2_js.a(ua,"toText");function rn(e){let t=0;for(;t<e.length;){let n=e.indexOf("{{",t);if(n<0)return false;let r=e.indexOf("}}",n+2);if(r<0)return false;if(e.slice(n+2,r).trim().length>0)return true;t=r+2;}return false}chunkDPD6ZWL2_js.a(rn,"isLabelExpression");function St(e){let t=[];for(let n of ca(e)){let r=n.expr.trim();if(!r)continue;let o=r.split("||").map(s=>s.trim()),a=o[o.length-1];o[o.length-1]=a.split("|")[0].trim();for(let s of o){if(!s)continue;let c=s.split(".")[0];c&&!t.includes(c)&&t.push(c);}}return t}chunkDPD6ZWL2_js.a(St,"extractAttributeNames");var Pu=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function la(e){let t=e.trim().match(Pu);return t?t[1]:null}chunkDPD6ZWL2_js.a(la,"getSingleAttributeFromExpression");function Mu(e,t){let n=la(e);if(n===null)return null;let r=t.find(o=>o.name===n);return !r||r.type!=="text"||chunkUKFOBZX2_js.j(r).authoring.readOnly?null:r}chunkDPD6ZWL2_js.a(Mu,"getEditableLabelAttribute");var Fu=/\{\{\s*props\./;function Vu(e,t,n){if(!Fu.test(e))return e;let r={},o=new Map(n?.map(s=>[s.name,s]));if(t)for(let[s,c]of Object.entries(t)){if(c==null)continue;let u=o.get(s);if(u){let l=oa(c,u);r[s]=l===tn?"":l;}else r[s]=c;}return Xn(e,{props:r},"").replace(/\(\s*\)/g,"").replace(/\[\s*\]/g,"").replace(/\s*[-—|:]\s*$/g,"").replace(/\s{2,}/g," ").trim()}chunkDPD6ZWL2_js.a(Vu,"applyRelationProps");function Bu(e){if(e?.type==="relation")return e.properties?.definitions}chunkDPD6ZWL2_js.a(Bu,"relationPropertyDefs");function Lu(e){if(e?.type==="relation"||e?.type==="document")return e.properties?.definitions}chunkDPD6ZWL2_js.a(Lu,"qualifiedPropertyDefs");function da(e){if(chunkIBM4ID4Y_js.a(e))return [];if(typeof e=="string")return [{id:e}];if(Array.isArray(e))return e.flatMap(t=>da(t));if(typeof e=="object"&&"id"in e){let t=e;if(typeof t.id=="string")return [{id:t.id,props:t.props}]}return []}chunkDPD6ZWL2_js.a(da,"extractValueRefs");function $u(e){let t=[e.firstName,e.lastName].map(n=>n?.trim()).filter(Boolean).join(" ");return t!==""?t:e.email?.split("@")[0]??""}chunkDPD6ZWL2_js.a($u,"getUserDisplayName");var Uu=/\p{L}|\p{N}/u;function qu(e,t){let n=e?.trim()??"";if(n==="")return t;let r=n.split(/\s+/),a=(r.length===1?n.split("@")[0].split(/[._-]/):r).map(s=>{let c=s.match(Uu)?.[0];return c===void 0?"":[...c.toUpperCase()][0]??""}).filter(Boolean).slice(0,2).join("");return a===""?t:a}chunkDPD6ZWL2_js.a(qu,"deriveInitials");var pa="__creatorRootActorId";function zu(e){let t=e.metadata?.[pa];return typeof t=="string"&&t.length>0?t:e.createdBy}chunkDPD6ZWL2_js.a(zu,"getRecordCreatorPrincipalId");function it(e,t){return e?.includes("*")===true||e?.includes(t)===true}chunkDPD6ZWL2_js.a(it,"includesAction");function Wu(e){return {canRead:it(e,"read"),canCreate:it(e,"create"),canUpdate:it(e,"update"),canDelete:it(e,"delete"),canManage:it(e,"manage")}}chunkDPD6ZWL2_js.a(Wu,"buildPermissionFlags");var sx=new Set(["id","name","label","type","required","system","unique","order"]);var ne={PEOPLE:"people",WORKSPACE:"workspace",ARCHITECT:"architect",FEATURE_FLAGS:"feature-flags",FILES:"files",VIEWS:"views",FORMS:"forms",DOCUMENTS:"documents",AUDIT:"audit",API_KEYS:"api-keys",CONNECTORS:"connectors",ENV_VARS:"env-vars",SESSION:"session"},ux=[ne.PEOPLE,ne.WORKSPACE,ne.ARCHITECT,ne.FEATURE_FLAGS,ne.FILES,ne.VIEWS,ne.FORMS,ne.DOCUMENTS,ne.AUDIT,ne.API_KEYS,ne.CONNECTORS,ne.ENV_VARS,ne.SESSION],lx={people:"People",workspace:"Workspace",architect:"Architect","feature-flags":"Feature flags",files:"Files",views:"Views",forms:"Forms",documents:"Documents",audit:"Audit","api-keys":"API keys",connectors:"Connected accounts","env-vars":"Environment variables",session:"Agent sessions"},Gu={OWNER:"owner",MEMBER:"member",AGENT_DEFAULT:"agent_default",REFLEX_DEFAULT:"reflex_default"},dx={owner:"Owner",member:"Member",agent_default:"Agent Default",reflex_default:"Reflex Default"},px={owner:"Full access to all platform features and data",member:"Can view, create, edit and delete business data",agent_default:"Default role for AI agents \u2014 CRUD on records plus documents and files",reflex_default:"Default role for reflexes \u2014 no data access; each reflex is granted exactly what its rehearsal showed it uses"},er=["read","create","update","delete","manage"],Ku=["read","create","update","delete"],ma=["read","create","update","delete"],mx={owner:{system:[{target:"*",actions:er}],object:[{target:"*",actions:er}]},member:{system:[{target:"people",actions:["read"]},{target:"workspace",actions:["read"]},{target:"connectors",actions:Ku},{target:"files",actions:ma},{target:"documents",actions:ma}],object:[{target:"*",actions:er}]},agent_default:{system:[{target:"documents",actions:["read","create","update"]},{target:"files",actions:["read","create","update"]},{target:"env-vars",actions:["read"]},{target:"session",actions:["observe"]}],object:[{target:"*",actions:["read","create","update","delete"]}]},reflex_default:{system:[],object:[]}};function fx(e){return Object.values(Gu).includes(e)}chunkDPD6ZWL2_js.a(fx,"isDefaultRole");var fa={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2},timeoutMs:3e5},nr=class nr{constructor(t){if(!t.name||t.name.trim().length===0)throw new chunkJSKLP4GI_js.h("Agent name is required",[]);this.bp={name:t.name,system:true,visibility:"workspace",triggers:[]};}description(t){return this.bp.description=t,this}label(t){return this.bp.label=t,this}icon(t){return this.bp.icon=t,this}systemPrompt(t){return this.bp.systemPrompt=t,this}model(t,n,r){return this.bp.model={provider:t,model:n,...r},this}tools(t){return this.bp.tools=[...t],this}schedule(t){return this.bp.schedule={...t,enabled:t.enabled??true},this}config(t){let n=this.bp.config??fa,r=t.inference===void 0?n.inference:{...n.inference,...t.inference};return this.bp.config={...n,...t,...r===void 0?{}:{inference:r}},this}delegation(t){return Object.assign(this.bp,t),this}mcpServers(t){return this.bp.mcpServers=Array.isArray(t)?[...t]:t,this}approval(t){return this.bp.approval={...Go,...this.bp.approval,...t},this}visibility(t){return this.bp.visibility=t,this}requiresPermission(t,n){return this.bp.requiredPermission={resource:t,action:n},this}trigger(t,n,r){return this.bp.triggers.push({name:t,eventType:n,...r,enabled:r?.enabled??true}),this}runtime(){return this.bp.system=false,this}build(){if(!this.bp.systemPrompt)throw new chunkJSKLP4GI_js.h(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new chunkJSKLP4GI_js.h(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility==="private")throw new chunkJSKLP4GI_js.h(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return chunk2M4YXNYZ_js.l(this.bp.triggers,t=>t.name,t=>new chunkJSKLP4GI_js.h(`Agent "${this.bp.name}": duplicate trigger name "${t}"`,[])),{...this.bp,visibility:this.bp.visibility??"workspace",config:this.bp.config??fa,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};chunkDPD6ZWL2_js.a(nr,"AgentBuilder");var tr=nr;function xx(e){return new tr(e)}chunkDPD6ZWL2_js.a(xx,"agent");var Yu="@stndrds/schema";function on(e){return {version:1,vendor:Yu,validate:chunkDPD6ZWL2_js.a(t=>{let n=e.safeParse(t);return n.success?{value:n.data}:{issues:n.error.issues.map(r=>({message:r.message,path:r.path}))}},"validate")}}chunkDPD6ZWL2_js.a(on,"createStandardSchemaProps");function Sx(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"].version===1}chunkDPD6ZWL2_js.a(Sx,"isStandardSchema");var xr=class xr{get"~standard"(){let t=chunkIBM4ID4Y_js.c(this.build());return on(t)}constructor(t,n,r){chunk2M4YXNYZ_js.n(n),chunk2M4YXNYZ_js.o(r),this.attr={name:n,label:r,type:t,required:false,system:true};}setRequired(t){this.attr.required=t;}asRequiredState(){return this}asPhantomState(){return this}runtime(){return this.attr.system=false,this}hidden(){return this.attr.hidden=true,this}placeholder(t){return this.attr.placeholder=t,this}description(t){return this.attr.description=t,this}icon(t){return chunk2M4YXNYZ_js.p(t,`attribute "${this.attr.name}"`),this.attr.icon=t,this}order(t){return this.attr.order=t,this}defaultValue(t){return ("defaultValue"in this.attr||!["formula","rollup"].includes(this.attr.type))&&(this.attr.defaultValue=t),this}metadata(t){return this.attr.metadata=t,this}build(){return this.attr}};chunkDPD6ZWL2_js.a(xr,"BaseAttributeBuilder");var $=xr,Tr=class Tr extends ${constructor(t,n){super("text",t,n);}minLength(t){return this.attr.minLength=t,this}maxLength(t){return this.attr.maxLength=t,this}pattern(t){return this.attr.pattern=t,this.attr.format=void 0,this}multiline(t=true){return this.attr.multiline=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}email(){return this.attr.format="email",this.attr.pattern=void 0,this}url(){return this.attr.format="url",this.attr.pattern=void 0,this}slug(){return this.attr.format="slug",this.attr.pattern=void 0,this}};chunkDPD6ZWL2_js.a(Tr,"TextAttributeBuilder");var rr=Tr;function S(e){return new rr(e.name,e.label)}chunkDPD6ZWL2_js.a(S,"text");var wr=class wr extends ${constructor(t,n){super("richtext",t,n);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(wr,"RichtextAttributeBuilder");var ir=wr;function je(e){return new ir(e.name,e.label)}chunkDPD6ZWL2_js.a(je,"richtext");var Sr=class Sr extends ${constructor(t,n){super("number",t,n);}min(t){return this.attr.min=t,this}max(t){return this.attr.max=t,this}integer(){return this.attr.unit="integer",this.attr.decimals=0,this}decimal(t=2){return this.attr.unit="decimal",this.attr.decimals=t,this}percentage(){return this.attr.unit="percentage",this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(Sr,"NumberAttributeBuilder");var or=Sr;function sn(e){return new or(e.name,e.label)}chunkDPD6ZWL2_js.a(sn,"number");var Ir=class Ir extends ${constructor(t,n){super("checkbox",t,n);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(Ir,"CheckboxAttributeBuilder");var ar=Ir;function ba(e){return new ar(e.name,e.label)}chunkDPD6ZWL2_js.a(ba,"checkbox");var Rr=class Rr extends ${constructor(t,n){super("date",t,n);}format(t){return this.attr.dateFormat=t,this}minDate(t){return this.attr.minDate=t,this}maxDate(t){return this.attr.maxDate=t,this}endDate(){return this.attr.endDate=true,this.asPhantomState()}includeTime(){return this.attr.includeTime=true,this}timeFormat(t){return this.attr.timeFormat=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(Rr,"DateAttributeBuilder");var sr=Rr;function se(e){return new sr(e.name,e.label)}chunkDPD6ZWL2_js.a(se,"date");var Cr=class Cr extends ${constructor(t,n){super("phone",t,n);}defaultCountry(t){return this.attr.defaultCountryCode=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(Cr,"PhoneAttributeBuilder");var cr=Cr;function jx(e){return new cr(e.name,e.label)}chunkDPD6ZWL2_js.a(jx,"phone");var vr=class vr extends ${constructor(t,n){super("currency",t,n);}defaultCurrency(t){return this.attr.defaultCurrency=t,this}allowedCurrencies(t){return this.attr.allowedCurrencies=t,this}allowNegative(t=true){return this.attr.allowNegative=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(vr,"CurrencyAttributeBuilder");var ur=vr;function kx(e){return new ur(e.name,e.label)}chunkDPD6ZWL2_js.a(kx,"currency");var Er=class Er extends ${constructor(t,n){super("status",t,n);}options(t){let n=t;return chunk2M4YXNYZ_js.q(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return chunk2M4YXNYZ_js.q(this.attr.name??"unknown",n),this.attr.options.push(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(Er,"StatusAttributeBuilder");var lr=Er;function _x(e){return new lr(e.name,e.label)}chunkDPD6ZWL2_js.a(_x,"status");var Nr=class Nr extends ${constructor(t,n){super("select",t,n);}options(t){let n=t;return chunk2M4YXNYZ_js.q(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return chunk2M4YXNYZ_js.q(this.attr.name??"unknown",n),this.attr.options.push(t),this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(Nr,"SelectAttributeBuilder");var dr=Nr;function be(e){return new dr(e.name,e.label)}chunkDPD6ZWL2_js.a(be,"select");var Dr=class Dr extends ${constructor(t,n){super("multiselect",t,n);}options(t){let n=t;return chunk2M4YXNYZ_js.q(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return chunk2M4YXNYZ_js.q(this.attr.name??"unknown",n),this.attr.options.push(t),this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(Dr,"MultiselectAttributeBuilder");var pr=Dr;function Px(e){return new pr(e.name,e.label)}chunkDPD6ZWL2_js.a(Px,"multiselect");var Or=class Or extends ${constructor(t,n){super("location",t,n);}granularity(t){return this.attr.granularity=t,this}defaultCountry(t){return this.attr.defaultCountry=t,this}allowedCountries(t){return this.attr.allowedCountries=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(Or,"LocationAttributeBuilder");var mr=Or;function Mx(e){return new mr(e.name,e.label)}chunkDPD6ZWL2_js.a(Mx,"location");var jr=class jr extends ${constructor(t,n){super("user",t,n),this.attr.types=["user","agent"];}types(t){let n=[...new Set(t)];if(n.length===0)throw new Error("[AttributeBuilder] user.types must contain at least one type.");return this.attr.types=n,this}multiple(){return this.attr.multiple=true,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(jr,"UserAttributeBuilder");var fr=jr;function Fx(e){return new fr(e.name,e.label)}chunkDPD6ZWL2_js.a(Fx,"user");var kr=class kr extends ${to(t,n){let r={object:t,...n};return this.attr.targets?.push(r),this}toAny(){return this.attr.targets=[{object:ae}],this}qualifyWith(...t){let n=this.attr.targets;if(!n||n.length===0)throw new Error('.qualifyWith() must be called AFTER .to(). Example: relation({ name: "companies" }).to("companies").qualifyWith(...)');return this.attr.properties=en(t),this}bilateral(t){let n=this.attr.targets;if(!n||n.length===0)throw new Error('.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })');if(n.length>1)throw new Error("Bilateral relations are not supported for polymorphic relations (multiple .to() targets).");if(zo(this.attr))throw new Error("Bilateral relations are not supported for universal relations (.toAny()).");let r=n[0]?.object;if(!r)throw new chunkJSKLP4GI_js.h("Bilateral relation requires one target object",[{path:["bilateral","object"],message:"Bilateral relation requires one target object"}]);if(t.object&&t.object!==r){let o=`Bilateral inverse object ${t.object} must match relation target ${r}`;throw new chunkJSKLP4GI_js.h(o,[{path:["bilateral","object"],message:o}])}return this.attr.bilateral={...t,object:r},this}};chunkDPD6ZWL2_js.a(kr,"BaseRelationAttributeBuilder");var an=kr,_r=class _r extends an{constructor(t,n){super("relation",t,n),this.attr.cardinality="one",this.attr.targets=[];}many(){let t=new gr(this.attr.name,this.attr.label??"",{targets:this.attr.targets,isRequired:this.attr.required});return this.attr.system===false&&t.runtime(),this.attr.hidden&&t.hidden(),this.attr.placeholder&&t.placeholder(this.attr.placeholder),this.attr.description&&t.description(this.attr.description),this.attr.icon&&t.icon(this.attr.icon),this.attr.order!==void 0&&t.order(this.attr.order),this.attr.metadata&&t.metadata(this.attr.metadata),t}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(_r,"SingleRelationAttributeBuilder");var br=_r,Pr=class Pr extends an{constructor(t,n,r){super("relation",t,n),this.attr.cardinality="many",this.attr.targets=r?.targets??[],this.attr.defaultValue=[],r?.isRequired&&this.setRequired(true);}maxItems(t){return this.attr.maxItems=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(Pr,"MultiRelationAttributeBuilder");var gr=Pr;function ot(e){return new br(e.name,e.label)}chunkDPD6ZWL2_js.a(ot,"relation");var Mr=class Mr extends ${constructor(t,n){super("formula",t,n),this.attr.required=false;}expression(t){return this.attr.expression=t,this}returns(t){return this.attr.returnType=t,this}decimals(t){return this.attr.decimals=t,this}required(){throw new Error("Formula attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.")}optional(){return this}};chunkDPD6ZWL2_js.a(Mr,"FormulaAttributeBuilder");var yr=Mr;function Vx(e){return new yr(e.name,e.label)}chunkDPD6ZWL2_js.a(Vx,"formula");var Fr=class Fr extends ${constructor(t,n){super("rollup",t,n),this.attr.required=false;}from(t){return this.attr.relationAttribute=t,this}aggregate(t){return this.attr.targetAttribute=t,this}using(t){return this.attr.function=t,this}decimals(t){return this.attr.decimals=t,this}path(t){return this.attr.relationPath=t,this}targetType(t){return this.attr.targetAttributeType=t,this}targetOptions(t){return this.attr.targetAttributeOptions=t,this}targetCurrency(t){return this.attr.targetCurrencyCode=t,this}build(){let t=this.attr.function,n=this.attr.targetAttributeType;if(t==="original"&&n!==void 0&&n!=="select"&&n!=="status"&&n!=="multiselect"){let r=this.attr.relationAttribute??"relation",o=this.attr.targetAttribute??"field";throw new chunkJSKLP4GI_js.b(`Rollup "${this.attr.name}": .using("original") only supports a "select", "status", or "multiselect" target, but .targetType("${n}") was given. To surface a plain ${n} value from a related record, use a formula instead \u2014 e.g. formula({ name: "${this.attr.name}", label: "\u2026" }).expression("${r}.${o}").`,chunkJSKLP4GI_js.a.VALIDATION_FAILED)}return super.build()}required(){throw new Error("Rollup attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.")}optional(){return this}};chunkDPD6ZWL2_js.a(Fr,"RollupAttributeBuilder");var hr=Fr;function Bx(e){return new hr(e.name,e.label)}chunkDPD6ZWL2_js.a(Bx,"rollup");var Vr=class Vr extends ${constructor(t,n){super("document",t,n);}accepts(t){return this.attr.accepts=t,this}maxFileSize(t){return this.attr.maxFileSize=t,this}qualifyWith(...t){return this.attr.properties=en(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};chunkDPD6ZWL2_js.a(Vr,"DocumentAttributeBuilder");var Ar=Vr;function ga(e){return new Ar(e.name,e.label)}chunkDPD6ZWL2_js.a(ga,"document");function ha(e,t,n){let r=Array.isArray(e)?e:[e],[o,...a]=r;return {type:"slot",slotId:o,additionalSlotIds:a.length>0?a:void 0,attribute:t,label:n?.label,required:n?.required,tooltip:n?.tooltip}}chunkDPD6ZWL2_js.a(ha,"buildSlotFieldRef");var Ur=class Ur{constructor(t,n,r){this._finalized=false;this.stepBuilder=t,this.rowData={id:n,order:r,type:"fields",fields:[]};}field(t,n,r){return this.rowData.fields.push(ha(t,n,r)),this}freeField(t,n){let o={type:"free",attribute:t.build(),label:n?.label,required:n?.required,prefillExpression:n?.prefillExpression};return this.rowData.fields.push(o),this}row(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).row(t)}heading(t,n){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).heading(t,n)}separator(){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).separator()}text(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).text(t)}endRow(){return this._finalized?this.stepBuilder:(this._finalized=true,this.stepBuilder._finalizeRow(this.rowData))}};chunkDPD6ZWL2_js.a(Ur,"FormRowBuilder");var Br=Ur,qr=class qr{constructor(t,n,r){this.rowOrder=0;this.formBuilder=t,this.stepData={id:n,label:r,rows:[]};}description(t){return this.stepData.description=t,this}field(t,n,r){this.rowOrder++;let o=`row-${this.stepData.id}-${this.rowOrder}`,a=ha(t,n,r),s={id:o,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}freeField(t,n){this.rowOrder++;let r=`row-${this.stepData.id}-${this.rowOrder}`,a={type:"free",attribute:t.build(),label:n?.label,required:n?.required,prefillExpression:n?.prefillExpression},s={id:r,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}row(t){return this.rowOrder++,new Br(this,t,this.rowOrder)}heading(t,n){this.rowOrder++;let r={id:`heading-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"heading",content:t,level:n};return this.stepData.rows.push(r),this}separator(){this.rowOrder++;let t={id:`sep-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"separator"};return this.stepData.rows.push(t),this}text(t){this.rowOrder++;let n={id:`text-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"text",content:t};return this.stepData.rows.push(n),this}step(t,n){return this.formBuilder._finalizeStep(this.stepData).step(t,n)}build(){return this.formBuilder._finalizeStep(this.stepData).build()}_finalizeRow(t){return t.fields.length>0&&this.stepData.rows.push(t),this}_getData(){return this.stepData}};chunkDPD6ZWL2_js.a(qr,"FormStepBuilder");var Lr=qr,zr=class zr{constructor(t,n){this.data={slots:[],steps:[],status:"draft",version:1};this.validateName(t),this.data.name=t,this.data.label=n;}description(t){return this.data.description=t,this}icon(t){return this.data.icon=t,this}status(t){return this.data.status=t,this}metadata(t){return this.data.metadata=t,this}slot(t,n,r){if(this.data.slots.some(a=>a.id===t))throw new Error(`[FormBuilder] Duplicate slot id: "${t}"`);let o={id:t,objectName:n,label:r.label,mode:r.mode??"create",color:r.color,icon:r.icon};return this.data.slots.push(o),this}step(t,n){if(this.data.steps.some(r=>r.id===t))throw new Error(`[FormBuilder] Duplicate step id: "${t}"`);return new Lr(this,t,n)}build(){return this.validateRequiredData(),this.validateSlotReferences(),this.validateFreeFields(),this.validatePrefillExpressions(),this.data}_finalizeStep(t){return this.data.steps.push(t),this}validateName(t){let n=zod.z.string().min(1,"Form name cannot be empty").max(63,"Form name is too long (max 63 characters)").regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,{message:"Invalid form name format. Name must be in kebab-case: 'client-onboarding', 'contact-creation'"});try{n.parse(t);}catch(r){throw r instanceof zod.z.ZodError?new Error(`[FormBuilder] ${r.issues[0].message}`):r}}validateRequiredData(){if(this.data.slots.length===0)throw new Error("[FormBuilder] At least one slot is required. Use .slot() to add slots.");if(this.data.steps.length===0)throw new Error("[FormBuilder] At least one step is required. Use .step() to add steps.")}validateSlotReferences(){let t=new Map(this.data.slots.map(n=>[n.id,n.objectName]));for(let n of this.data.steps)for(let r of n.rows)if(Zt(r))for(let o of r.fields){if(o.type!=="slot")continue;let a=ea(o);for(let c of a)if(!t.has(c))throw new Error(`[FormBuilder] Step "${n.id}" references unknown slot "${c}". Declare it with .slot("${c}", ...) first.`);let s=new Set(a.map(c=>t.get(c)));if(s.size>1)throw new Error(`[FormBuilder] Step "${n.id}" field on attribute "${o.attribute}" targets slots of different objects (${[...s].join(", ")}). A multi-slot field must target slots of the same object.`)}}validatePrefillExpressions(){let t=[...nn,"join"];for(let n of this.data.steps)for(let r of n.rows)if(Zt(r))for(let o of r.fields){if(!Hn(o)||!o.prefillExpression)continue;let a=o.prefillExpression,s=`prefillExpression on free field "${o.attribute.name}" in step "${n.id}"`;if(!rn(a))throw new Error(`[FormBuilder] ${s} must contain at least one {{ attribute }} interpolation.`);if(/\{\{\s*\}\}/.test(a))throw new Error(`[FormBuilder] ${s} contains empty {{ }} interpolation.`);for(let c of a.matchAll(/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g)){let u=c[1];if(!t.includes(u))throw new Error(`[FormBuilder] ${s} uses invalid pipe "${u}". Valid pipes: ${t.join(", ")}`)}}}validateFreeFields(){let t=new Set(Yn);for(let n of this.data.steps)for(let r of n.rows)if(Zt(r)){for(let o of r.fields)if(Hn(o)){let a=o.attribute.type;if(t.has(a))throw new Error(`[FormBuilder] Free field in step "${n.id}" uses forbidden attribute type "${a}". Forbidden types: ${Yn.join(", ")}`)}}}};chunkDPD6ZWL2_js.a(zr,"FormBuilder");var $r=zr;function Gx(e,t){return new $r(e,t)}chunkDPD6ZWL2_js.a(Gx,"form");function Hu(e){return {text:"toString",richtext:"toString",number:"toNumber",currency:"toNumber",date:"toDate",checkbox:"toBoolean"}[e]}chunkDPD6ZWL2_js.a(Hu,"resolveBuiltInTransform");var Wr=class Wr{constructor(t){this.operations=[];this.touchedAttributes=new Set;this.version=t;}assertNotTouched(t,n){if(this.touchedAttributes.has(t))throw new chunkJSKLP4GI_js.h(`[MigrationBuilder] Conflicting operations on attribute "${t}": it was already modified earlier in this migration (attempted: ${n}).`,[])}renameAttribute(t,n){return this.assertNotTouched(t,"rename_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"rename_attribute",from:t,to:n}),this}changeType(t,n,r,o){this.assertNotTouched(t,"change_type"),this.touchedAttributes.add(t);let a=o?.transform?Hu(r):void 0;return this.operations.push({type:"change_type",name:t,from:n,to:r,transform:a}),this}removeAttribute(t){return this.assertNotTouched(t,"remove_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"remove_attribute",name:t}),this}addAttribute(t){return this.assertNotTouched(t.name,"add_attribute"),this.touchedAttributes.add(t.name),this.operations.push({type:"add_attribute",attribute:t}),this}updateConfig(t,n){return this.assertNotTouched(t,"update_config"),this.touchedAttributes.add(t),this.operations.push({type:"update_config",name:t,from:{},to:n}),this}build(){return {version:this.version,operations:[...this.operations]}}};chunkDPD6ZWL2_js.a(Wr,"MigrationBuilder");var cn=Wr;function Ju(e){let{name:t,labelExpression:n,embeddingExpression:r}=e;if(!n)throw new chunkJSKLP4GI_js.b(`Object "${t}" must have a labelExpression. The labelExpression defines how records are displayed in lists and relations (e.g. "{{ name }}").`,chunkJSKLP4GI_js.a.VALIDATION_FAILED);let o=rt.safeParse(n);if(!o.success){let a=o.error.issues[0]?.message??"Invalid labelExpression";throw new chunkJSKLP4GI_js.b(`Invalid labelExpression for "${t}": ${a}`,chunkJSKLP4GI_js.a.VALIDATION_FAILED)}if(r!==void 0){let a=rt.safeParse(r);if(!a.success){let s=a.error.issues[0]?.message??"Invalid embeddingExpression";throw new chunkJSKLP4GI_js.b(`Invalid embeddingExpression for "${t}": ${s}`,chunkJSKLP4GI_js.a.VALIDATION_FAILED)}}}chunkDPD6ZWL2_js.a(Ju,"validateObjectExpressions");var Gr=class Gr{constructor(t){this._migrations=[];this._sealed=false;this._toleratedAttributes=[];this.validateName(t.name),this.obj={name:t.name,label:t.label,attributes:[],system:true},t.id&&(this.obj.id=t.id);}get"~standard"(){let t=chunkIBM4ID4Y_js.e(this.build());return on(t)}description(t){return this.obj.description=t,this}pluralLabel(t){return this._pluralLabel=t,this}icon(t){return this.obj.icon=t,this}runtime(){return this.obj.system=false,this}sealed(){return this._sealed=true,this}tolerate(t){return this._toleratedAttributes=[...this._toleratedAttributes,...t],this}attribute(t){return this.pushAttributes([t]),this}attributes(t){return this.pushAttributes(t),this}pushAttributes(t){let n=t.map(r=>"build"in r&&typeof r.build=="function"?r.build():r);chunk2M4YXNYZ_js.l([...this.obj.attributes,...n],r=>r.name,r=>new chunkJSKLP4GI_js.r("attribute",r,`Object "${this.obj.name}": duplicate attribute name "${r}"`)),this.obj.attributes.push(...n);}metadata(t){return this.obj.metadata={...this.obj.metadata,...t},this}order(t){return this.obj.metadata={...this.obj.metadata,order:t},this}hidden(){return this.obj.metadata={...this.obj.metadata,hidden:true},this}labelExpression(t){return this._labelExpression=t,this}embeddingExpression(t){return this._embeddingExpression=t,this}documentLayout(t){if(t.presets)for(let n of t.presets)Aa(n.id,n.structure,1);return this.obj.documentLayout=t,this}migration(t,n){if(t<2)throw new Error(`[ObjectBuilder] Migration version must be >= 2 (version 1 is implicit). Got: ${t}`);if(this._migrations.some(a=>a.version===t))throw new Error(`[ObjectBuilder] Duplicate migration version: ${t}`);let o=new cn(t);return n(o),this._migrations.push(o.build()),this}build(){if(!this.obj.name)throw new chunkJSKLP4GI_js.h("[ObjectBuilder] Missing required field: name",[{path:["name"],message:"name is required"}]);if(!this.obj.label)throw new chunkJSKLP4GI_js.h("[ObjectBuilder] Missing required field: label",[{path:["label"],message:"label is required"}]);Ju({name:this.obj.name,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression});let t=[...this._migrations].sort((r,o)=>r.version-o.version);for(let r=0;r<t.length;r++){let o=r+2;if(t[r].version!==o)throw new Error(`[ObjectBuilder] Migration versions must be sequential starting at 2. Expected version ${o}, got ${t[r].version}.`)}let n=t.length>0?t[t.length-1].version:1;return {...this.obj,pluralLabel:this._pluralLabel,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression,schema_version:n,migrations:t,sealed:this._sealed,toleratedAttributes:this._toleratedAttributes}}validateName(t){t!==void 0&&chunk2M4YXNYZ_js.j(t);}};chunkDPD6ZWL2_js.a(Gr,"ObjectBuilder");var It=Gr;function oT(e){if(chunk2M4YXNYZ_js.b(e.name))throw new chunkJSKLP4GI_js.s(e.name,"builder");return new It(e)}chunkDPD6ZWL2_js.a(oT,"object");function Aa(e,t,n){let r=chunkDPD6ZWL2_js.a((a,s)=>{throw new chunkJSKLP4GI_js.h(a,[{path:["documentLayout","presets",e],message:s}])},"fail");n>5&&r(`Preset structure exceeds max depth of ${5}`,"Preset structure too deep");let o=new Set;for(let a of t){let s=a.title.trim();s.length===0&&r("Folder preset node title is required","Empty folder title"),s.includes("/")&&r("Folder preset node title cannot contain /",`Folder title contains /: "${s}"`),o.has(s)&&r("Folder preset sibling titles must be unique",`Duplicate folder title: "${s}"`),o.add(s),a.children&&a.children.length>0&&Aa(e,a.children,n+1);}}chunkDPD6ZWL2_js.a(Aa,"validatePresetStructure");function ge(e,t){try{return structuredClone(e)}catch{let n="Builder configuration must contain cloneable data";throw new chunkJSKLP4GI_js.h(n,[{path:t,message:n}])}}chunkDPD6ZWL2_js.a(ge,"cloneBuilderValue");function Ce(e,t){if(typeof e!="string"||e.trim().length===0)throw new chunkJSKLP4GI_js.h("Name must not be blank",[{path:t,message:"Name must not be blank"}])}chunkDPD6ZWL2_js.a(Ce,"requireBuilderName");function at(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new chunkJSKLP4GI_js.h("Invalid content configuration",[{path:t,message:"Expected content configuration"}]);for(let c of ["name","label","placement"])if(Object.hasOwn(e,c)){let u=`Independent content configuration cannot define ${c}`;throw new chunkJSKLP4GI_js.h(u,[{path:[...t,c],message:u}])}let n=chunkUKFOBZX2_js.W.safeParse({...e,name:"content",placement:"main"});if(!n.success)throw chunkJSKLP4GI_js.h.fromZodErrors(n.error.issues.map(c=>({path:[...t,...c.path.map(String)],message:c.message})));n.data.type==="form"&&n.data.groups.forEach((c,u)=>Ce(c.name,[...t,"groups",String(u),"name"]));let{name:r,label:o,placement:a,...s}=n.data;return ge(s,t)}chunkDPD6ZWL2_js.a(at,"validateContentConfiguration");function Kr(e,t){return at(e,t),ge(e,t)}chunkDPD6ZWL2_js.a(Kr,"validateLiteralContent");function ze(e){return e.relation===void 0?{kind:"object",object:e.object}:e.object===void 0?{kind:"related",relation:e.relation}:{kind:"relatedFrom",object:e.object,relation:e.relation}}chunkDPD6ZWL2_js.a(ze,"collectionSourceAddress");function Yr(e){if(!e||typeof e!="object")return;let t="object"in e?e.object:void 0,n="relation"in e?e.relation:void 0;if(typeof t=="string"&&typeof n=="string")return {kind:"relatedFrom",object:t,relation:n};if(typeof t=="string"&&n===void 0)return {kind:"object",object:t};if(typeof n=="string"&&t===void 0)return {kind:"related",relation:n}}chunkDPD6ZWL2_js.a(Yr,"collectionSourceAddressOf");function Rt(e,t,n){if(t!=="record"){let r=`Content "${e}" requires record context. In a collection view only a collection that lists a whole object, or a custom content that does not require a record, is allowed.`;throw new chunkJSKLP4GI_js.h(r,[{path:n,message:r}])}}chunkDPD6ZWL2_js.a(Rt,"requireRecordContentContext");function Qu(e){let t=e.openMode??"page";return {openMode:t,createMode:e.createMode??t}}chunkDPD6ZWL2_js.a(Qu,"resolveContentNavigation");function Zu(e,t){return [...new Set(t)].filter(n=>e.actions===void 0||e.actions.includes(n))}chunkDPD6ZWL2_js.a(Zu,"resolveCollectionActions");var ke=class ke{constructor(t,n=[]){this.kind="view";this.data=ge(t,["views","0"]),this.extensions=n.map(r=>r&&{...r});}for(t){return new ke({...this.data,object:t},this.extensions)}default(){return new ke({...this.data,default:true},this.extensions)}description(t){return new ke({...this.data,description:t},this.extensions)}icon(t){return new ke({...this.data,icon:t},this.extensions)}place(t,n,r,o){let a=["views","0","contents",String(this.data.contents.length)],s,c;try{r!==null&&typeof r=="object"&&"build"in r&&typeof r.build=="function"?(s=at(r.build(),a),c=r.extension):s=at(r,a);}catch(m){throw m instanceof chunkJSKLP4GI_js.h?new chunkJSKLP4GI_js.h(m.message,m.errors.map(d=>({...d,path:d.path[0]==="content"?[...a,...d.path.slice(1)]:d.path}))):m}let u={...s,name:t,label:n,placement:o},l=[...this.data.contents,u];return new ke({...this.data,contents:l},[...this.extensions,c])}tab(t,n,r){return this.place(t,n,r,"main")}aside(t,n,r){return this.place(t,n,r,"aside")}build(){let t=["views","0"];Ce(this.data.name,[...t,"name"]),Ce(this.data.object,[...t,"object"]);let n=chunkUKFOBZX2_js.$.safeParse(this.data);if(!n.success)throw chunkJSKLP4GI_js.h.fromZodErrors(n.error.issues.map(r=>({path:[...t,...r.path.map(String)],message:r.message})));return this.data.contents.forEach((r,o)=>{let a=[...t,"contents",String(o)];Ce(r.name,[...a,"name"]),r.type==="form"&&r.groups.forEach((c,u)=>Ce(c.name,[...a,"groups",String(u),"name"])),(r.type==="custom"?this.extensions[o]?.requiresRecord:r.type==="collection"?ze(r.source).kind!=="object":true)&&Rt(r.name,this.data.context,a);}),{kind:"view",definition:ge(this.data,t)}}};chunkDPD6ZWL2_js.a(ke,"ViewBuilder");var un=ke;function ye(e,t){return new un({name:e,label:t,object:void 0,context:"record",contents:[]})}chunkDPD6ZWL2_js.a(ye,"detailView");function he(e,t){return new un({name:e,label:t,object:void 0,context:"collection",contents:[]})}chunkDPD6ZWL2_js.a(he,"listView");function CT(e){return Ce(e,["relationProperty"]),{relationProperty:e}}chunkDPD6ZWL2_js.a(CT,"relationProperty");var Ct=class Ct{constructor(t,n){this.data=ge(t,["content"]),this.extension=n===void 0?void 0:Object.freeze({name:n.name,requiresRecord:n.requiresRecord,parameters:n.parameters});}set(t){return new Ct({...this.data,...t},this.extension)}icon(t){return this.set({icon:t})}object(t){return this.data.type==="forms"?this.set({objectName:t}):this.set({source:{object:t}})}related(t){return this.set({source:{relation:t}})}relatedFrom(t,n){return this.set({source:{object:t,relation:n}})}layout(t){let{layout:n,groupByAttribute:r,columnSizing:o,kanbanColumnOrder:a,kanbanColumnVisibility:s,kanbanPinnedColumns:c,...u}={...this.data,layout:void 0,groupByAttribute:void 0,columnSizing:void 0,kanbanColumnOrder:void 0,kanbanColumnVisibility:void 0,kanbanPinnedColumns:void 0};return new Ct({...u,...t},this.extension)}table(){return this.layout({layout:"table"})}list(){return this.layout({layout:"list"})}kanban(t){return this.layout({layout:"kanban",groupByAttribute:t})}columns(...t){return this.set({columns:t})}filter(t){return this.set({filters:t})}sort(t,n="asc"){let o=[..."sorts"in this.data&&Array.isArray(this.data.sorts)?this.data.sorts:[],{attribute:t,direction:n}];return this.set({sorts:o})}actions(...t){return this.set({actions:t})}openMode(t){return this.set({openMode:t})}createMode(t){return this.set({createMode:t})}visibility(t){return this.set({visibility:t})}descriptionAttribute(t){return this.set({descriptionAttribute:t})}displayAttributes(...t){return this.set({displayAttributes:t})}columnSizing(t){return this.set({columnSizing:t})}kanbanColumnOrder(...t){return this.set({kanbanColumnOrder:t})}kanbanColumnVisibility(t){return this.set({kanbanColumnVisibility:t})}kanbanPinnedColumns(...t){return this.set({kanbanPinnedColumns:t})}formColumns(t){return this.set({formColumns:t})}density(t){return this.set({density:t})}titleAttribute(t){return this.set({titleAttribute:t})}allowUpload(t){return this.set({allowUpload:t})}allowRemove(t){return this.set({allowRemove:t})}hideAttachments(t){return this.set({hideAttachments:t})}relations(...t){return this.set({relations:t})}build(){let t=Kr(this.data,["content"]);if(this.extension&&t.type==="custom"){let n=this.extension.parameters.safeParse(ge(t.parameters??{},["content","parameters"]));if(!n.success)throw chunkJSKLP4GI_js.h.fromZodErrors(n.error.issues.map(r=>({path:["content","parameters",...r.path.map(String)],message:r.message})))}return t}};chunkDPD6ZWL2_js.a(Ct,"ContentBuilder");var ce=Ct,We=class We{constructor(t,n,r,o={}){this.data=ge({name:t,label:n,fields:r,...o},["group"]);}field(t,n){let{name:r,label:o,fields:a,...s}=this.data;return new We(r,o,[...a,{attribute:t,...n}],s)}fields(...t){let{name:n,label:r,fields:o,...a}=this.data;return new We(n,r,[...o,...t.map(s=>({attribute:s}))],a)}description(t){return new We(this.data.name,this.data.label,this.data.fields,{...this.presentation(),description:t})}collapsible(t=false){return new We(this.data.name,this.data.label,this.data.fields,{...this.presentation(),collapsible:true,collapsed:t})}presentation(){let{name:t,label:n,fields:r,...o}=this.data;return o}build(){Ce(this.data.name,["group","name"]);try{Kr({type:"form",groups:[this.data]},["group"]);}catch(t){throw t instanceof chunkJSKLP4GI_js.h?new chunkJSKLP4GI_js.h(t.message,t.errors.map(n=>({...n,path:n.path[1]==="groups"?["group",...n.path.slice(3)]:n.path}))):t}return ge(this.data,["group"])}};chunkDPD6ZWL2_js.a(We,"GroupBuilder");var Hr=We;function Ae(e,t){return new Hr(e,t,[])}chunkDPD6ZWL2_js.a(Ae,"group");function Xu(){return new ce({type:"collection"})}chunkDPD6ZWL2_js.a(Xu,"collection");function el(...e){let t=e.map(n=>"build"in n?n.build():n);return new ce({type:"form",groups:t})}chunkDPD6ZWL2_js.a(el,"form");function tl(){return new ce({type:"activity"})}chunkDPD6ZWL2_js.a(tl,"activity");function nl(e){return new ce({type:"richtext",attribute:e})}chunkDPD6ZWL2_js.a(nl,"richtext");function rl(){return new ce({type:"documents"})}chunkDPD6ZWL2_js.a(rl,"documents");function il(){return new ce({type:"forms"})}chunkDPD6ZWL2_js.a(il,"forms");function ol(...e){return new ce({type:"emails",emailAttributes:e})}chunkDPD6ZWL2_js.a(ol,"emails");function al(...e){return new ce({type:"meetings",emailAttributes:e})}chunkDPD6ZWL2_js.a(al,"meetings");function sl(e,t){if(typeof e!="object"||e===null||typeof e.name!="string")throw new chunkJSKLP4GI_js.h("Expected registered extension declaration",[{path:["content","extension"],message:"Expected registered extension declaration"}]);let n=at({type:"custom",extension:e.name,parameters:t},["content"]);if(n.type!=="custom")throw new chunkJSKLP4GI_js.h("Expected custom content",[]);let r=new ce({...n,extension:e.name},e);return r.build(),r}chunkDPD6ZWL2_js.a(sl,"custom");var D={collection:Xu,form:el,activity:tl,richtext:nl,documents:rl,forms:il,emails:ol,meetings:al,custom:sl};function cl(e){if(!/^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$/.test(e))throw new Error(`Invalid flag name "${e}". Flag names must be kebab-case (e.g., "architect-mode", "ai-features").`)}chunkDPD6ZWL2_js.a(cl,"validateFlagName");var ei=class ei{constructor(t,n,r){cl(t),this.flag={name:t,valueType:n,defaultValue:r,allowedLevels:["global","tenant","user"]};}label(t){return this.flag.label=t,this}description(t){return this.flag.description=t,this}category(t){return this.flag.category=t,this}system(){return this.flag.system=true,this}tenantScoped(){return this.flag.allowedLevels=["global","tenant"],this}globalOnly(){return this.flag.allowedLevels=["global"],this}allowedLevels(t){return this.flag.allowedLevels=[...t],this}build(){if(!this.flag.label?.trim())throw new Error(`Flag "${this.flag.name}" must have a label. Use .label("Human-readable label").`);return {...this.flag,allowedLevels:[...this.flag.allowedLevels||[]]}}};chunkDPD6ZWL2_js.a(ei,"BaseFlagBuilder");var st=ei,ti=class ti extends st{constructor(t){super(t,"boolean",false);}defaultValue(t){return this.flag.defaultValue=t,this}enabledByDefault(){return this.flag.defaultValue=true,this}};chunkDPD6ZWL2_js.a(ti,"BooleanFlagBuilder");var Jr=ti,ni=class ni extends st{constructor(t){super(t,"string","");}defaultValue(t){return this.flag.defaultValue=t,this}};chunkDPD6ZWL2_js.a(ni,"StringFlagBuilder");var Qr=ni,ri=class ri extends st{constructor(t){super(t,"number",0);}defaultValue(t){return this.flag.defaultValue=t,this}};chunkDPD6ZWL2_js.a(ri,"NumberFlagBuilder");var Zr=ri,ii=class ii extends st{constructor(t,n){super(t,"json",n);}defaultValue(t){return this.flag.defaultValue=t,this}};chunkDPD6ZWL2_js.a(ii,"JsonFlagBuilder");var Xr=ii;function ul(e){return new Jr(e)}chunkDPD6ZWL2_js.a(ul,"booleanFlag");function ll(e){return new Qr(e)}chunkDPD6ZWL2_js.a(ll,"stringFlag");function dl(e){return new Zr(e)}chunkDPD6ZWL2_js.a(dl,"numberFlag");function pl(e,t){return new Xr(e,t)}chunkDPD6ZWL2_js.a(pl,"jsonFlag");function oi(e){return new chunkJSKLP4GI_js.r("feature flag",e,`Flag "${e}" is already registered. Each flag name must be unique.`)}chunkDPD6ZWL2_js.a(oi,"duplicateFlagError");function ai(e){return {...e,allowedLevels:[...e.allowedLevels]}}chunkDPD6ZWL2_js.a(ai,"cloneFlagDefinition");var si=class si{constructor(){this.flags=new Map;}register(t){if(this.flags.has(t.name))throw oi(t.name);this.flags.set(t.name,ai(t));}registerAll(t){let n=new Set;for(let r of t){if(this.flags.has(r.name)||n.has(r.name))throw oi(r.name);n.add(r.name);}for(let r of t)this.register(r);}get(t){let n=this.flags.get(t);return n?ai(n):void 0}getOrThrow(t){let n=this.get(t);if(!n)throw new chunkJSKLP4GI_js.c("Feature flag",t,void 0,`Flag "${t}" is not registered. Available flags: ${this.listNames().join(", ")}`);return n}has(t){return this.flags.has(t)}list(){return Array.from(this.flags.values(),ai)}listNames(){return Array.from(this.flags.keys())}unregister(t){return this.flags.delete(t)}clear(){this.flags.clear();}get size(){return this.flags.size}};chunkDPD6ZWL2_js.a(si,"FlagRegistry");var vt=si,ml=new vt;function fl(){return new vt}chunkDPD6ZWL2_js.a(fl,"createFlagRegistry");function ln(){return {global:new Map,tenant:new Map,user:new Map}}chunkDPD6ZWL2_js.a(ln,"emptyOverrides");function bl(e,t){return e.expiresAt===void 0||e.expiresAt.getTime()>t}chunkDPD6ZWL2_js.a(bl,"isActiveOverride");function ci(e,t){let n=new Map;for(let r of e){if(!bl(r,t))continue;let o=r.flagName;n.has(o)||n.set(o,r);}return n}chunkDPD6ZWL2_js.a(ci,"indexOverrides");var ui=class ui{constructor(t){this.repository=t.repository,this.registry=t.registry,this.staticDefaults=new Map(t.staticDefaults?.map(n=>[n.name,n.value])??[]);}async resolveAll(t={}){let n=this.collectFlagNames(),r=this.repository&&n.size>0?await this.getAllOverrides(t,[...n]):ln();return this.resolveNames(n,r,t)}resolveAllStatic(){return this.resolveNames(this.collectFlagNames(),ln(),{})}collectFlagNames(){let t=new Set;for(let n of this.registry.listNames())t.add(n);for(let n of this.staticDefaults.keys())t.add(n);return t}resolveNames(t,n,r){let o=new Map;for(let a of t)o.set(a,this.resolveValue(a,n,r));return o}async resolve(t,n={}){let r=this.repository?await this.getAllOverrides(n,[t]):ln();return this.resolveWithSource(t,r,n)}async isEnabled(t,n={}){return (await this.resolve(t,n)).value===true}async getValue(t,n={}){return (await this.resolve(t,n)).value}async setOverride(t,n,r,o={}){if(!this.repository)throw new chunkJSKLP4GI_js.b("Cannot set override: no FeatureFlagsRepository configured. Add featureFlags to your DatabaseAdapter to enable runtime overrides.",chunkJSKLP4GI_js.a.CONFIGURATION_REQUIRED);let a=this.registry.get(t);if(a&&!a.allowedLevels.includes(n)){let s=`Flag "${t}" does not allow ${n}-level overrides. Allowed levels: ${a.allowedLevels.join(", ")}`;throw new chunkJSKLP4GI_js.h(s,[{path:["level"],message:s}])}if(a?.system){let s=`Flag "${t}" is a system flag and cannot be overridden via API.`;throw new chunkJSKLP4GI_js.h(s,[{path:["flagName"],message:s}])}await this.repository.setOverride({flagName:t,level:n,value:r,targetId:o.targetId,expiresAt:o.expiresAt,createdBy:o.createdBy});}async deleteOverride(t,n,r){if(!this.repository)throw new chunkJSKLP4GI_js.b("Cannot delete override: no FeatureFlagsRepository configured.",chunkJSKLP4GI_js.a.CONFIGURATION_REQUIRED);await this.repository.deleteOverride(t,n,r);}async getAllOverrides(t,n){if(!this.repository)return ln();let[r,o,a]=await Promise.all([this.repository.getOverrides({level:"global",flagNames:n}),t.tenantId?this.repository.getOverrides({level:"tenant",targetId:t.tenantId,flagNames:n}):Promise.resolve([]),t.userId?this.repository.getOverrides({level:"user",targetId:t.userId,flagNames:n}):Promise.resolve([])]),s=Date.now();return {global:ci(r,s),tenant:ci(o,s),user:ci(a,s)}}resolveValue(t,n,r){return this.resolveWithSource(t,n,r).value}resolveWithSource(t,n,r){let o=this.registry.get(t),a=o?.allowedLevels??["global","tenant","user"];if(r.userId&&a.includes("user")){let s=n.user.get(t);if(s)return {name:t,value:s.value,source:"user",sourceId:r.userId}}if(r.tenantId&&a.includes("tenant")){let s=n.tenant.get(t);if(s)return {name:t,value:s.value,source:"tenant",sourceId:r.tenantId}}if(a.includes("global")){let s=n.global.get(t);if(s)return {name:t,value:s.value,source:"global"}}return this.staticDefaults.has(t)?{name:t,value:this.staticDefaults.get(t),source:"default"}:{name:t,value:o?.defaultValue??void 0,source:"default"}}};chunkDPD6ZWL2_js.a(ui,"FlagService");var dn=ui;function gl(e){return new dn(e)}chunkDPD6ZWL2_js.a(gl,"createFlagService");var xa=Symbol("stndrds.native-object");function di(e){return Object.defineProperty(e,xa,{value:true,enumerable:false}),e}chunkDPD6ZWL2_js.a(di,"markNativeDefinition");var mi=class mi extends It{build(){return di(super.build())}};chunkDPD6ZWL2_js.a(mi,"NativeObjectBuilder");var li=mi;function xe(e){return new li(e)}chunkDPD6ZWL2_js.a(xe,"nativeObject");function pi(e){return e[xa]===true}chunkDPD6ZWL2_js.a(pi,"isNativeDefinition");function fi(e){let t=structuredClone(e);return pi(e)?di(t):t}chunkDPD6ZWL2_js.a(fi,"cloneObjectDefinition");var gi=class gi{constructor(){this.objects=new Map;}register(t){let r=(Array.isArray(t)?t:[t]).map(a=>"build"in a&&typeof a.build=="function"?a.build():a),o=new Set;for(let a of r){if(this.validate(a),o.has(a.name))throw new chunkJSKLP4GI_js.r("object",a.name,`[NativeObjectRegistry] Duplicate object name "${a.name}" within a single register() batch.`);o.add(a.name);}for(let a of r)this.objects.set(a.name,fi(a));return this}validate(t){if(!t.system){let n=`[NativeObjectRegistry] Cannot register object "${t.name}" (id: ${t.id}): missing system flag.
3
- Native objects must have system=true. Did you call .runtime() on the builder? Remove that call \u2014 objects are system:true by default.`;throw new chunkJSKLP4GI_js.h(n,[])}if(chunk2M4YXNYZ_js.b(t.name)&&!pi(t))throw new chunkJSKLP4GI_js.s(t.name,"registry");if(this.objects.has(t.name)){let n=this.objects.get(t.name),r=`[NativeObjectRegistry] Duplicate object name "${t.name}":
4
- - Existing: "${n?.label}" (id: ${n?.id})
5
- - New: "${t.label}" (id: ${t.id})
6
- Please use unique names for each native object.`;throw new chunkJSKLP4GI_js.r("object",t.name,r)}}getByName(t){let n=this.objects.get(t);return n?fi(n):void 0}getByNameOrThrow(t){let n=this.getByName(t);if(!n){let r=`[NativeObjectRegistry] Native object "${t}" not found.
7
- Available objects: ${this.listNames().join(", ")}`;throw new chunkJSKLP4GI_js.c("Native object",t,chunkJSKLP4GI_js.a.OBJECT_NOT_FOUND,r)}return n}getAll(){return Array.from(this.objects.values(),fi)}listNames(){return Array.from(this.objects.keys())}has(t){return this.objects.has(t)}get size(){return this.objects.size}clear(){this.objects.clear();}summary(){let t=this.getAll();return [`[NativeObjectRegistry] ${this.size} native object(s) registered:`,...t.map(n=>` - ${n.name}: "${n.label}" (${n.attributes.length} attributes)`)].join(`
8
- `)}debug(t){let n=this.summary();return t?.(n),n}};chunkDPD6ZWL2_js.a(gi,"NativeObjectRegistryClass");var bi=gi,tw=new bi;var Ta=new WeakSet;function G(e){return Ta.add(e.definition),e}chunkDPD6ZWL2_js.a(G,"markSystemView");function wa(e){return typeof e=="object"&&e!==null&&Ta.has(e)}chunkDPD6ZWL2_js.a(wa,"isSystemViewDefinition");var Sa=`## Overview
1
+ /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./config-BQJJHopR.js"),t=require("./view-config.schema-to6p1m8L.js"),n=require("./exceptions.js"),r=require("./utils-gY3d9Dwp.js"),i=require("./object-DGu0m2Y1.js"),a=require("./text-A9AJ1wUO.js"),o=require("./phone-DVaELsa3.js"),s=require("./core-397tQy5q.js"),c=require("./validation/primitives/checkbox.js"),l=require("./validation/primitives/date.js"),u=require("./validation/primitives/number.js");let d=require("@stndrds/constants"),f=require("zod");const p=[`fyi`,`task`,`question`,`handoff`,`system`],m=[`low`,`normal`,`high`,`urgent`],h=[`public`,`internal`,`sensitive`],g=[`unread`,`read`,`archived`,`snoozed`],_=[`none`,`pending`,`processing`,`completed`,`dismissed`,`expired`,`failed`],v=`agent.session.waiting_human`,y=`agent.task.assigned`,b=`agent.question.requested`,x=[v,y,b],S=[`name`,`type`],ee=[`required`,`hidden`,`archived`,`deprecated`,`defaultValue`,`config`,`order`,`unique`],C=[`label`,`description`,`placeholder`,`icon`],w=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`status`,`location`,`select`,`multiselect`,`user`,`relation`,`formula`,`rollup`,`document`];function relationTargetsOf(e){return e.type!==`relation`||!Array.isArray(e.targets)?[]:e.targets.map(e=>e.object).filter(e=>e!==`*`)}function isUniversalRelation(e){return e.targets.length===1&&e.targets[0].object===`*`}function isBilateralRelation(e){return e.bilateral!==void 0}function inferInverseCardinality(e){return`many`}function isAttributeSortable(e){return t.K(e)}const te=[`record`,`object`,`attribute`,`view`,`user`,`role`,`settings`,`file`,`agent`,`schema_source`],ne=`record.created,record.updated,record.deleted,record.restored,record.purged,object.created,object.updated,object.deleted,attribute.created,attribute.updated,attribute.deleted,view.created,view.updated,view.deleted,schema_source.applied,schema_source.removed,user.created,user.invited,user.updated,user.deleted,user.login,user.logout,role.created,role.updated,role.deleted,role.assigned,role.revoked,settings.updated,file.uploaded,file.updated,file.deleted`.split(`,`);function isTerminalState(e){return e.phase===`terminal`}function sessionStateToLegacyStatus(e){switch(e.phase){case`running`:return`active`;case`queued`:return`idle`;case`parked`:if(e.parkedOn===void 0)throw new n.SchemaError(`parked state without parkedOn`,n.SchemaErrorCode.INVARIANT_VIOLATION);return e.parkedOn===`agents`?`waiting_agents`:`waiting_human`;case`terminal`:if(e.outcome===void 0)throw new n.SchemaError(`terminal state without outcome`,n.SchemaErrorCode.INVARIANT_VIOLATION);return e.outcome}}function legacyStatusToSessionState(e){switch(e){case`active`:return{phase:`running`};case`idle`:return{phase:`queued`};case`waiting_human`:return{phase:`parked`,parkedOn:`human`,humanRequestIds:[]};case`waiting_agents`:return{phase:`parked`,parkedOn:`agents`};default:return{phase:`terminal`,outcome:e}}}const re=[`completed`,`failed`,`cancelled`,`timeout`,`expired`];function isTerminalSessionStatus(e){return re.includes(e)}const ie=[`idle`,`completed`,`waiting_human`,`waiting_agents`,`cancelled`,`failed`,`timeout`];function isClaimableSessionStatus(e){return ie.includes(e)}const ae=Object.freeze({mutation:`ask`,destructive:`ask`,outward:`ask`}),oe=[`active`,`completed`,`abandoned`],se=[`openai`,`anthropic`,`google`,`spacexai`,`deepseek`,`moonshotai`,`alibaba`,`mistral`,`minimax`,`meta`,`zai`],ce=[`standard`,`fast`],le=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`];function agentDisplayName(e){return e.label?.trim()||e.name}const ue=[`approval-requested`,`approval-responded`,`approval-dispatched`],de=[`streaming`,`running`,`pending`,...ue];function isOpenToolPartState(e){return de.includes(e)}function isToolApprovalState(e){return ue.includes(e)}const fe=[`CREDITS_EXHAUSTED`];function isSystemPartCode(e){return typeof e==`string`&&fe.includes(e)}function compareAgentSessionMessages(e,t){let n=e.createdAt.getTime()-t.createdAt.getTime();return n===0?e.id.localeCompare(t.id):n}function orderAgentSessionMessages(e){return[...e].sort(compareAgentSessionMessages)}const pe=[`pending`,`in_progress`,`completed`,`blocked`],me=`__stndrdsNativeUiPartIds`;function invalidNativePartIds(){throw new n.ValidationError(`Native agent UI part IDs metadata is invalid`,[])}function isPlainRecord$1(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function nativeAgentUIPartIdMetadataKey(e,t){if(e.type===`text`||e.type===`reasoning`)return`${e.type}:${t}`;if(e.type===`tool`)return`tool:${e.toolCallId}`}function parseNativeAgentUIPartIdsMetadata(e){let t=e.metadata?.[me];isPlainRecord$1(t)||invalidNativePartIds(),(Object.keys(t).length!==2||t.schemaVersion!==1||!isPlainRecord$1(t.partIds))&&invalidNativePartIds();let n=new Map;for(let[t,r]of e.parts.entries()){let e=nativeAgentUIPartIdMetadataKey(r,t);if(!e||n.has(e)){e&&invalidNativePartIds();continue}n.set(e,r)}let r=Object.entries(t.partIds);r.length!==n.size&&invalidNativePartIds();let i=new Map,a={};for(let[e,t]of r){let r=n.get(e);r&&typeof t==`string`&&t.length>0||invalidNativePartIds();let o=i.get(t);o&&(r.type===`tool`||o!==r.type)&&invalidNativePartIds(),r.type===`tool`&&t!==r.toolCallId&&invalidNativePartIds(),i.set(t,r.type),a[e]=t}return a}const he={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2},ge=[`web`,`presentation`,`document`,`spreadsheet`,`image`,`code`,`other`],_e=[`ephemeral`,`conversation`,`persistent`],ve=[`source`,`preview`,`entrypoint`,`asset`];function getErrorMessage(e){return e instanceof Error?e.message:typeof e==`string`?e:e&&typeof e==`object`?`message`in e&&typeof e.message==`string`?e.message:JSON.stringify(e):String(e)}function isFormDefinition(e){return typeof e==`object`&&!!e&&`slots`in e&&`steps`in e&&`name`in e&&typeof e.name==`string`&&Array.isArray(e.slots)&&Array.isArray(e.steps)}const ye=[`relation`,`multiRelation`,`formula`,`rollup`,`document`,`richtext`,`user`];function isFormSlotFieldRef(e){return e.type===`slot`}function isFormFreeFieldRef(e){return e.type===`free`}function resolveFieldRequired(e){return e.fieldRequired===void 0?e.slotMode===`create`&&e.attributeRequired===!0:e.fieldRequired}function getSlotFieldTargets(e){return e.additionalSlotIds?.length?[e.slotId,...e.additionalSlotIds]:[e.slotId]}function formFieldKey(e){return isFormSlotFieldRef(e)?`${e.slotId}.${e.attribute}`:`free.${e.attribute.name}`}function formFieldFlatKey(e){return isFormSlotFieldRef(e)?e.attribute:e.attribute.name}function readFormFieldValue(e,t){return e[formFieldKey(t)]??e[formFieldFlatKey(t)]}function isFormFieldsRow(e){return e.type===`fields`}function isFormHeadingRow(e){return e.type===`heading`}function isFormSeparatorRow(e){return e.type===`separator`}function isFormTextRow(e){return e.type===`text`}var NoopGeocodingAdapter=class{async autocomplete(){return await Promise.resolve([])}async reverse(){return await Promise.resolve(null)}async geocode(){return await Promise.resolve(null)}};const T=[`read`,`create`,`update`,`delete`,`manage`];function actionsToAccessLevel(e){return e.length===0?`none`:e.length===1&&e[0]===`read`?`read-only`:e.length===T.length&&T.every(t=>e.includes(t))?`full`:`custom`}function accessLevelToActions(e){switch(e){case`full`:return[...T];case`read-only`:return[`read`];case`none`:return[]}}function resolvePropertyDefinitions(e){let t=e.properties;if(!t)return[];if(Array.isArray(t))return t;let n=t;return Array.isArray(n.definitions)?n.definitions:[]}function hasOptions(e){return e.type===`select`||e.type===`status`||e.type===`multiselect`}const be=`Notetaker`,xe={systemPrompt:null,meetingRecordingPolicy:`none`,meetingBotDisplayName:be},Se=[`active`,`suspended`],Ce=[`architect`,`manual`,`auto`],we=[`square`,`landscape`,`portrait`],Te=[`none`,`estimated`,`exact`];function parseCountMode(e){if(typeof e==`string`&&Te.includes(e))return e;throw new n.ValidationError(`countMode must be one of: ${Te.join(`, `)} (received: ${String(e)})`,[])}function parseOptionalCountMode(e){return e===void 0?void 0:parseCountMode(e)}const Ee=[`storage.bytes`,`members.seats`,`data.live_records`];function isEmptyObject(e){return e==null||typeof e==`object`&&Object.keys(e).length===0}function isNotEmpty(e){return typeof e==`object`&&!!e&&Object.keys(e).length>0}function toUndefinedIfEmpty(e){return isNotEmpty(e)?e:void 0}function computeByteMagnitude(e){if(e<=0)return{value:0,unitIndex:0};let t=1e3,n=Math.min(4,Math.floor(Math.log(e)/Math.log(t)));return{value:Number.parseFloat((e/t**n).toFixed(1)),unitIndex:n}}const De=[`B`,`KB`,`MB`,`GB`,`TB`];function formatByteSize(e){let{value:t,unitIndex:n}=computeByteMagnitude(e);return`${t} ${De[n]}`}const Oe={ATTACHMENTS:`attachments`};function isDocumentAttribute(e){return e.type===`document`}function matchesAccepts(e,t){if(!t||t.length===0)return!0;let n=e.name.toLowerCase();return t.some(t=>t.endsWith(`/*`)?e.mimeType.startsWith(t.slice(0,-1)):t.startsWith(`.`)?n.endsWith(t.toLowerCase()):e.mimeType===t)}const ke=Object.freeze([`text`,`number`,`checkbox`,`date`,`phone`,`currency`,`status`,`select`,`multiselect`,`location`]);function buildPropertySchema(e){let t=[];for(let n of e){let e=n.build();if(!ke.includes(e.type))throw Error(`Property type "${e.type}" is not supported in .qualifyWith()`);t.push(e)}return{definitions:t}}function parseQualifiedAttribute(e){let t=e.indexOf(`__`);return t<=0||t+2>=e.length?{kind:`scalar`,attribute:e}:{kind:`qualified`,root:e.slice(0,t),property:e.slice(t+2)}}function buildQualifiedAttribute(e,t){return`${e}__${t}`}function isDateRangeValue(e){return typeof e==`object`&&!!e&&typeof e.start==`string`}function normalizeDateValue(e,t){return i.p(e)?null:isDateRangeValue(e)?t.endDate?{start:e.start,end:e.end??null}:e.start:typeof e==`string`?t.endDate?{start:e,end:null}:e:null}function dateValueStart(e){return typeof e==`string`&&e!==``?e:isDateRangeValue(e)&&e.start!==``?e.start:null}function formatText(e){return String(e)}function formatCheckbox(e){return e?`Yes`:`No`}function formatNumber(e,t){if(typeof e!=`number`)return String(e);if(t.renderAs===`rating`)return`${e}/${t.max??5}`;let n=t.decimals;return t.unit===`integer`?e.toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:0}):t.unit===`percentage`?(e/100).toLocaleString(void 0,{style:`percent`,minimumFractionDigits:n,maximumFractionDigits:n}):e.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})}function formatCurrency(e,t){if(typeof e!=`object`||!e)return String(e);let n=e;return`value`in n&&`code`in n?`${n.value.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})} ${n.code}`:String(e)}function formatDate(e){if(isDateRangeValue(e)){let t=formatDate(e.start);return e.end?`${t} → ${formatDate(e.end)}`:t}if(e instanceof Date)return e.toISOString().split(`T`)[0];if(typeof e==`string`){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString().split(`T`)[0]}return String(e)}function formatPhone(e){if(typeof e!=`object`||!e)return String(e);let t=e;return`phoneNumber`in t?t.phoneNumber?t.countryCode?o.n(t):t.phoneNumber:``:String(e)}function formatLocationValue(e,t=`full`){if(typeof e!=`object`||!e)return``;let n=e,r=[];switch(t){case`country`:n.country&&r.push((0,d.getCountryDisplayNameByIso3)(n.country));break;case`state`:n.state&&r.push(n.state),n.country&&r.push((0,d.getCountryDisplayNameByIso3)(n.country));break;case`city`:n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push((0,d.getCountryDisplayNameByIso3)(n.country));break;case`coordinates`:n.latitude!==void 0&&n.longitude!==void 0&&r.push(`${n.latitude}, ${n.longitude}`);break;case`address`:n.address&&r.push(n.address),n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push((0,d.getCountryDisplayNameByIso3)(n.country));break;default:n.address&&r.push(n.address),n.address2&&r.push(n.address2),n.city&&r.push(n.city),n.state&&r.push(n.state),n.postalCode&&r.push(n.postalCode),n.country&&r.push((0,d.getCountryDisplayNameByIso3)(n.country))}return r.join(`, `)}function formatLocation(e,t){return typeof e!=`object`||!e?String(e):formatLocationValue(e,t.granularity??`full`)||`—`}function formatSelect(e,t){return typeof e==`string`?t.options?.find(t=>t.value===e)?.label??String(e):String(e)}function formatMultiselect(e,t){return Array.isArray(e)?t.options?e.map(e=>t.options.find(t=>t.value===e)?.label).filter(Boolean).join(`, `):e.join(`, `):String(e)}function formatAttributeValue(e,t){if(i.p(e))return`—`;switch(t.type){case`text`:return formatText(e);case`checkbox`:return formatCheckbox(e);case`number`:return formatNumber(e,t);case`currency`:return formatCurrency(e,t);case`date`:return formatDate(e);case`phone`:return formatPhone(e);case`location`:return formatLocation(e,t);case`select`:case`status`:return formatSelect(e,t);case`multiselect`:return formatMultiselect(e,t);case`user`:case`relation`:return Array.isArray(e)?e.join(`, `):String(e);default:return Array.isArray(e)?e.join(`, `):String(e)}}const Ae=[`UPPER`,`LOWER`,`capitalize`,`trim`],je=[`prefix`,`suffix`,`wrap`,`default`],E=[...Ae,...je],D=f.z.string().min(1,`labelExpression cannot be empty`).refine(e=>isLabelExpression(e),{message:`labelExpression must contain at least one {{ attribute }} interpolation`}).refine(e=>!/\{\{\s*\}\}/.test(e),{message:`labelExpression contains empty {{ }} interpolation`}).refine(e=>{let t=/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g,n;for(;(n=t.exec(e))!==null;){let e=n[1];if(!E.includes(e))return!1}return!0},{message:`Invalid pipe name. Valid pipes: ${E.join(`, `)}`});function validateLabelExpression(e){let t=D.safeParse(e);return t.success?{success:!0,attributes:extractAttributeNames(e)}:{success:!1,error:t.error.issues[0]?.message??`Invalid labelExpression`}}function applyPipe(e,t){let{name:n,args:r}=parsePipeExpression(t);switch(n){case`UPPER`:return e.toUpperCase();case`LOWER`:return e.toLowerCase();case`capitalize`:return e.replace(/(^|\s)\S/g,e=>e.toUpperCase());case`trim`:return e.trim();case`prefix`:return e?`${r[0]??``}${e}`:``;case`suffix`:return e?`${e}${r[0]??``}`:``;case`wrap`:return e?`${r[0]??``}${e}${r[1]??``}`:``;case`default`:return e||r[0]||``;default:return e}}function applyPipes(e,t){let n=e;for(let e of t)n=applyPipe(n,e);return n}function getValue(e,t){return t.split(`.`).reduce((e,t)=>{if(typeof e==`object`&&e)return e[t]},e)}const Me=`(Untitled)`;function parsePipeExpression(e){let t=e.match(/^(\w+)(?::(.*))?$/);if(!t)return{name:e,args:[]};let n=t[1],r=t[2];if(!r)return{name:n,args:[]};let i=[],a=/["']([^"']*?)["']/g,o;for(;(o=a.exec(r))!==null;)i.push(o[1]);return{name:n,args:i}}function*templateBlocks(e){let t=0;for(;t<e.length;){let n=e.indexOf(`{{`,t);if(n<0)return;let r=e.indexOf(`}`,n+2);if(r<0)return;if(e[r+1]!==`}`){t=r+1;continue}t=r+2;let i=e.slice(n+2,r);i.length>0&&(yield{start:n,end:t,expr:i})}}function resolveLabelBlock(e,t){let n=e.split(`||`).map(e=>e.trim()),r=n[n.length-1].split(`|`).map(e=>e.trim());n[n.length-1]=r[0];let i=r.slice(1).filter(Boolean),a=n.filter(Boolean),o=``;for(let e of a){let n=toText(getValue(t,e));if(n!==``){o=n;break}}return applyPipes(o,i)}function renderLabelExpression(e,t,n=Me){let r=[],i=0;for(let n of templateBlocks(e))r.push(e.slice(i,n.start),resolveLabelBlock(n.expr,t)),i=n.end;return r.push(e.slice(i)),r.join(``).trim()||n}function toText(e){if(e==null||typeof e==`function`)return``;if(typeof e!=`object`)return String(e);if(Array.isArray(e))return e.map(toText).filter(Boolean).join(`,`);let t=e.toString;return typeof t==`function`&&t!==Object.prototype.toString?String(e):``}function isLabelExpression(e){let t=0;for(;t<e.length;){let n=e.indexOf(`{{`,t);if(n<0)return!1;let r=e.indexOf(`}}`,n+2);if(r<0)return!1;if(e.slice(n+2,r).trim().length>0)return!0;t=r+2}return!1}function extractAttributeNames(e){let t=[];for(let n of templateBlocks(e)){let e=n.expr.trim();if(!e)continue;let r=e.split(`||`).map(e=>e.trim()),i=r[r.length-1];r[r.length-1]=i.split(`|`)[0].trim();for(let e of r){if(!e)continue;let n=e.split(`.`)[0];n&&!t.includes(n)&&t.push(n)}}return t}const Ne=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function getSingleAttributeFromExpression(e){let t=e.trim().match(Ne);return t?t[1]:null}function getEditableLabelAttribute(e,n){let r=getSingleAttributeFromExpression(e);if(r===null)return null;let i=n.find(e=>e.name===r);return!i||i.type!==`text`||t.B(i).authoring.readOnly?null:i}const Pe=/\{\{\s*props\./;function applyRelationProps(e,t,n){if(!Pe.test(e))return e;let r={},i=new Map(n?.map(e=>[e.name,e]));if(t)for(let[e,n]of Object.entries(t)){if(n==null)continue;let t=i.get(e);if(t){let i=formatAttributeValue(n,t);r[e]=i===`—`?``:i}else r[e]=n}return renderLabelExpression(e,{props:r},``).replace(/\(\s*\)/g,``).replace(/\[\s*\]/g,``).replace(/\s*[-—|:]\s*$/g,``).replace(/\s{2,}/g,` `).trim()}function relationPropertyDefs(e){if(e?.type===`relation`)return e.properties?.definitions}function qualifiedPropertyDefs(e){if(e?.type===`relation`||e?.type===`document`)return e.properties?.definitions}function extractValueRefs(e){if(i.p(e))return[];if(typeof e==`string`)return[{id:e}];if(Array.isArray(e))return e.flatMap(e=>extractValueRefs(e));if(typeof e==`object`&&`id`in e){let t=e;if(typeof t.id==`string`)return[{id:t.id,props:t.props}]}return[]}function getUserDisplayName(e){let t=[e.firstName,e.lastName].map(e=>e?.trim()).filter(Boolean).join(` `);return t===``?e.email?.split(`@`)[0]??``:t}const Fe=/\p{L}|\p{N}/u;function deriveInitials(e,t){let n=e?.trim()??``;if(n===``)return t;let r=n.split(/\s+/),i=(r.length===1?n.split(`@`)[0].split(/[._-]/):r).map(e=>{let t=e.match(Fe)?.[0];return t===void 0?``:[...t.toUpperCase()][0]??``}).filter(Boolean).slice(0,2).join(``);return i===``?t:i}const Ie=`__creatorRootActorId`;function getRecordCreatorPrincipalId(e){let t=e.metadata?.[Ie];return typeof t==`string`&&t.length>0?t:e.createdBy}function includesAction(e,t){return e?.includes(`*`)===!0||e?.includes(t)===!0}function buildPermissionFlags(e){return{canRead:includesAction(e,`read`),canCreate:includesAction(e,`create`),canUpdate:includesAction(e,`update`),canDelete:includesAction(e,`delete`),canManage:includesAction(e,`manage`)}}const Le=new Set([`id`,`name`,`label`,`type`,`required`,`system`,`unique`,`order`]),O={PEOPLE:`people`,WORKSPACE:`workspace`,ARCHITECT:`architect`,FEATURE_FLAGS:`feature-flags`,FILES:`files`,VIEWS:`views`,FORMS:`forms`,DOCUMENTS:`documents`,AUDIT:`audit`,API_KEYS:`api-keys`,CONNECTORS:`connectors`,ENV_VARS:`env-vars`,SESSION:`session`},Re=[O.PEOPLE,O.WORKSPACE,O.ARCHITECT,O.FEATURE_FLAGS,O.FILES,O.VIEWS,O.FORMS,O.DOCUMENTS,O.AUDIT,O.API_KEYS,O.CONNECTORS,O.ENV_VARS,O.SESSION],ze={people:`People`,workspace:`Workspace`,architect:`Architect`,"feature-flags":`Feature flags`,files:`Files`,views:`Views`,forms:`Forms`,documents:`Documents`,audit:`Audit`,"api-keys":`API keys`,connectors:`Connected accounts`,"env-vars":`Environment variables`,session:`Agent sessions`},Be={OWNER:`owner`,MEMBER:`member`,AGENT_DEFAULT:`agent_default`,REFLEX_DEFAULT:`reflex_default`},Ve={owner:`Owner`,member:`Member`,agent_default:`Agent Default`,reflex_default:`Reflex Default`},He={owner:`Full access to all platform features and data`,member:`Can view, create, edit and delete business data`,agent_default:`Default role for AI agents — CRUD on records plus documents and files`,reflex_default:`Default role for reflexes — no data access; each reflex is granted exactly what its rehearsal showed it uses`},k=[`read`,`create`,`update`,`delete`,`manage`],Ue=[`read`,`create`,`update`,`delete`],We=[`read`,`create`,`update`,`delete`],Ge={owner:{system:[{target:`*`,actions:k}],object:[{target:`*`,actions:k}]},member:{system:[{target:`people`,actions:[`read`]},{target:`workspace`,actions:[`read`]},{target:`connectors`,actions:Ue},{target:`files`,actions:We},{target:`documents`,actions:We}],object:[{target:`*`,actions:k}]},agent_default:{system:[{target:`documents`,actions:[`read`,`create`,`update`]},{target:`files`,actions:[`read`,`create`,`update`]},{target:`env-vars`,actions:[`read`]},{target:`session`,actions:[`observe`]}],object:[{target:`*`,actions:[`read`,`create`,`update`,`delete`]}]},reflex_default:{system:[],object:[]}};function isDefaultRole(e){return Object.values(Be).includes(e)}const A={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2},timeoutMs:3e5};var AgentBuilder=class{constructor(e){if(!e.name||e.name.trim().length===0)throw new n.ValidationError(`Agent name is required`,[]);this.bp={name:e.name,system:!0,visibility:`workspace`,triggers:[]}}description(e){return this.bp.description=e,this}label(e){return this.bp.label=e,this}icon(e){return this.bp.icon=e,this}systemPrompt(e){return this.bp.systemPrompt=e,this}model(e,t,n){return this.bp.model={provider:e,model:t,...n},this}tools(e){return this.bp.tools=[...e],this}schedule(e){return this.bp.schedule={...e,enabled:e.enabled??!0},this}config(e){let t=this.bp.config??A,n=e.inference===void 0?t.inference:{...t.inference,...e.inference};return this.bp.config={...t,...e,...n===void 0?{}:{inference:n}},this}delegation(e){return Object.assign(this.bp,e),this}mcpServers(e){return this.bp.mcpServers=Array.isArray(e)?[...e]:e,this}approval(e){return this.bp.approval={...ae,...this.bp.approval,...e},this}visibility(e){return this.bp.visibility=e,this}requiresPermission(e,t){return this.bp.requiredPermission={resource:e,action:t},this}trigger(e,t,n){return this.bp.triggers.push({name:e,eventType:t,...n,enabled:n?.enabled??!0}),this}runtime(){return this.bp.system=!1,this}build(){if(!this.bp.systemPrompt)throw new n.ValidationError(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new n.ValidationError(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility===`private`)throw new n.ValidationError(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return e.T(this.bp.triggers,e=>e.name,e=>new n.ValidationError(`Agent "${this.bp.name}": duplicate trigger name "${e}"`,[])),{...this.bp,visibility:this.bp.visibility??`workspace`,config:this.bp.config??A,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};function agent(e){return new AgentBuilder(e)}const Ke=`@stndrds/schema`;function createStandardSchemaProps(e){return{version:1,vendor:Ke,validate:t=>{let n=e.safeParse(t);return n.success?{value:n.data}:{issues:n.error.issues.map(e=>({message:e.message,path:e.path}))}}}}function isStandardSchema(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`&&e[`~standard`].version===1}function asMutableArray(e){return e}var BaseAttributeBuilder=class{get"~standard"(){return createStandardSchemaProps(i.d(this.build()))}constructor(t,n,r){e.E(n),e.O(r),this.attr={name:n,label:r,type:t,required:!1,system:!0}}setRequired(e){this.attr.required=e}asRequiredState(){return this}asPhantomState(){return this}runtime(){return this.attr.system=!1,this}hidden(){return this.attr.hidden=!0,this}placeholder(e){return this.attr.placeholder=e,this}description(e){return this.attr.description=e,this}icon(t){return e.D(t,`attribute "${this.attr.name}"`),this.attr.icon=t,this}order(e){return this.attr.order=e,this}defaultValue(e){return(`defaultValue`in this.attr||![`formula`,`rollup`].includes(this.attr.type))&&(this.attr.defaultValue=e),this}metadata(e){return this.attr.metadata=e,this}build(){return this.attr}},TextAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`text`,e,t)}minLength(e){return this.attr.minLength=e,this}maxLength(e){return this.attr.maxLength=e,this}pattern(e){return this.attr.pattern=e,this.attr.format=void 0,this}multiline(e=!0){return this.attr.multiline=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}email(){return this.attr.format=`email`,this.attr.pattern=void 0,this}url(){return this.attr.format=`url`,this.attr.pattern=void 0,this}slug(){return this.attr.format=`slug`,this.attr.pattern=void 0,this}};function text(e){return new TextAttributeBuilder(e.name,e.label)}var RichtextAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`richtext`,e,t)}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function richtext(e){return new RichtextAttributeBuilder(e.name,e.label)}var NumberAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`number`,e,t)}min(e){return this.attr.min=e,this}max(e){return this.attr.max=e,this}integer(){return this.attr.unit=`integer`,this.attr.decimals=0,this}decimal(e=2){return this.attr.unit=`decimal`,this.attr.decimals=e,this}percentage(){return this.attr.unit=`percentage`,this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function number(e){return new NumberAttributeBuilder(e.name,e.label)}var CheckboxAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`checkbox`,e,t)}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function checkbox(e){return new CheckboxAttributeBuilder(e.name,e.label)}var DateAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`date`,e,t)}format(e){return this.attr.dateFormat=e,this}minDate(e){return this.attr.minDate=e,this}maxDate(e){return this.attr.maxDate=e,this}endDate(){return this.attr.endDate=!0,this.asPhantomState()}includeTime(){return this.attr.includeTime=!0,this}timeFormat(e){return this.attr.timeFormat=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function date(e){return new DateAttributeBuilder(e.name,e.label)}var PhoneAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`phone`,e,t)}defaultCountry(e){return this.attr.defaultCountryCode=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function phone(e){return new PhoneAttributeBuilder(e.name,e.label)}var CurrencyAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`currency`,e,t)}defaultCurrency(e){return this.attr.defaultCurrency=e,this}allowedCurrencies(e){return this.attr.allowedCurrencies=e,this}allowNegative(e=!0){return this.attr.allowNegative=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function currency(e){return new CurrencyAttributeBuilder(e.name,e.label)}var StatusAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`status`,e,t)}options(t){let n=asMutableArray(t);return e.A(this.attr.name??`unknown`,n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return e.A(this.attr.name??`unknown`,n),this.attr.options.push(t),this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function status(e){return new StatusAttributeBuilder(e.name,e.label)}var SelectAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`select`,e,t)}options(t){let n=asMutableArray(t);return e.A(this.attr.name??`unknown`,n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return e.A(this.attr.name??`unknown`,n),this.attr.options.push(t),this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function select(e){return new SelectAttributeBuilder(e.name,e.label)}var MultiselectAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`multiselect`,e,t)}options(t){let n=asMutableArray(t);return e.A(this.attr.name??`unknown`,n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return e.A(this.attr.name??`unknown`,n),this.attr.options.push(t),this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function multiselect(e){return new MultiselectAttributeBuilder(e.name,e.label)}var LocationAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`location`,e,t)}granularity(e){return this.attr.granularity=e,this}defaultCountry(e){return this.attr.defaultCountry=e,this}allowedCountries(e){return this.attr.allowedCountries=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function location(e){return new LocationAttributeBuilder(e.name,e.label)}var UserAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`user`,e,t),this.attr.types=[`user`,`agent`]}types(e){let t=[...new Set(e)];if(t.length===0)throw Error(`[AttributeBuilder] user.types must contain at least one type.`);return this.attr.types=t,this}multiple(){return this.attr.multiple=!0,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function user(e){return new UserAttributeBuilder(e.name,e.label)}var BaseRelationAttributeBuilder=class extends BaseAttributeBuilder{to(e,t){let n={object:e,...t};return this.attr.targets?.push(n),this}toAny(){return this.attr.targets=[{object:`*`}],this}qualifyWith(...e){let t=this.attr.targets;if(!t||t.length===0)throw Error(`.qualifyWith() must be called AFTER .to(). Example: relation({ name: "companies" }).to("companies").qualifyWith(...)`);return this.attr.properties=buildPropertySchema(e),this}bilateral(e){let t=this.attr.targets;if(!t||t.length===0)throw Error(`.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })`);if(t.length>1)throw Error(`Bilateral relations are not supported for polymorphic relations (multiple .to() targets).`);if(isUniversalRelation(this.attr))throw Error(`Bilateral relations are not supported for universal relations (.toAny()).`);let r=t[0]?.object;if(!r)throw new n.ValidationError(`Bilateral relation requires one target object`,[{path:[`bilateral`,`object`],message:`Bilateral relation requires one target object`}]);if(e.object&&e.object!==r){let t=`Bilateral inverse object ${e.object} must match relation target ${r}`;throw new n.ValidationError(t,[{path:[`bilateral`,`object`],message:t}])}return this.attr.bilateral={...e,object:r},this}},SingleRelationAttributeBuilder=class extends BaseRelationAttributeBuilder{constructor(e,t){super(`relation`,e,t),this.attr.cardinality=`one`,this.attr.targets=[]}many(){let e=new MultiRelationAttributeBuilder(this.attr.name,this.attr.label??``,{targets:this.attr.targets,isRequired:this.attr.required});return this.attr.system===!1&&e.runtime(),this.attr.hidden&&e.hidden(),this.attr.placeholder&&e.placeholder(this.attr.placeholder),this.attr.description&&e.description(this.attr.description),this.attr.icon&&e.icon(this.attr.icon),this.attr.order!==void 0&&e.order(this.attr.order),this.attr.metadata&&e.metadata(this.attr.metadata),e}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}},MultiRelationAttributeBuilder=class extends BaseRelationAttributeBuilder{constructor(e,t,n){super(`relation`,e,t),this.attr.cardinality=`many`,this.attr.targets=n?.targets??[],this.attr.defaultValue=[],n?.isRequired&&this.setRequired(!0)}maxItems(e){return this.attr.maxItems=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function relation(e){return new SingleRelationAttributeBuilder(e.name,e.label)}var FormulaAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`formula`,e,t),this.attr.required=!1}expression(e){return this.attr.expression=e,this}returns(e){return this.attr.returnType=e,this}decimals(e){return this.attr.decimals=e,this}required(){throw Error(`Formula attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.`)}optional(){return this}};function formula(e){return new FormulaAttributeBuilder(e.name,e.label)}var RollupAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`rollup`,e,t),this.attr.required=!1}from(e){return this.attr.relationAttribute=e,this}aggregate(e){return this.attr.targetAttribute=e,this}using(e){return this.attr.function=e,this}decimals(e){return this.attr.decimals=e,this}path(e){return this.attr.relationPath=e,this}targetType(e){return this.attr.targetAttributeType=e,this}targetOptions(e){return this.attr.targetAttributeOptions=e,this}targetCurrency(e){return this.attr.targetCurrencyCode=e,this}build(){let e=this.attr.function,t=this.attr.targetAttributeType;if(e===`original`&&t!==void 0&&t!==`select`&&t!==`status`&&t!==`multiselect`){let e=this.attr.relationAttribute??`relation`,r=this.attr.targetAttribute??`field`;throw new n.SchemaError(`Rollup "${this.attr.name}": .using("original") only supports a "select", "status", or "multiselect" target, but .targetType("${t}") was given. To surface a plain ${t} value from a related record, use a formula instead — e.g. formula({ name: "${this.attr.name}", label: "…" }).expression("${e}.${r}").`,n.SchemaErrorCode.VALIDATION_FAILED)}return super.build()}required(){throw Error(`Rollup attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.`)}optional(){return this}};function rollup(e){return new RollupAttributeBuilder(e.name,e.label)}var DocumentAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`document`,e,t)}accepts(e){return this.attr.accepts=e,this}maxFileSize(e){return this.attr.maxFileSize=e,this}qualifyWith(...e){return this.attr.properties=buildPropertySchema(e),this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function document(e){return new DocumentAttributeBuilder(e.name,e.label)}function buildSlotFieldRef(e,t,n){let[r,...i]=Array.isArray(e)?e:[e];return{type:`slot`,slotId:r,additionalSlotIds:i.length>0?i:void 0,attribute:t,label:n?.label,required:n?.required,tooltip:n?.tooltip}}var FormRowBuilder=class{constructor(e,t,n){this._finalized=!1,this.stepBuilder=e,this.rowData={id:t,order:n,type:`fields`,fields:[]}}field(e,t,n){return this.rowData.fields.push(buildSlotFieldRef(e,t,n)),this}freeField(e,t){let n={type:`free`,attribute:e.build(),label:t?.label,required:t?.required,prefillExpression:t?.prefillExpression};return this.rowData.fields.push(n),this}row(e){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).row(e)}heading(e,t){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).heading(e,t)}separator(){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).separator()}text(e){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).text(e)}endRow(){return this._finalized?this.stepBuilder:(this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData))}},FormStepBuilder=class{constructor(e,t,n){this.rowOrder=0,this.formBuilder=e,this.stepData={id:t,label:n,rows:[]}}description(e){return this.stepData.description=e,this}field(e,t,n){this.rowOrder++;let r=`row-${this.stepData.id}-${this.rowOrder}`,i=buildSlotFieldRef(e,t,n),a={id:r,order:this.rowOrder,type:`fields`,fields:[i]};return this.stepData.rows.push(a),this}freeField(e,t){this.rowOrder++;let n=`row-${this.stepData.id}-${this.rowOrder}`,r={type:`free`,attribute:e.build(),label:t?.label,required:t?.required,prefillExpression:t?.prefillExpression},i={id:n,order:this.rowOrder,type:`fields`,fields:[r]};return this.stepData.rows.push(i),this}row(e){return this.rowOrder++,new FormRowBuilder(this,e,this.rowOrder)}heading(e,t){this.rowOrder++;let n={id:`heading-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:`heading`,content:e,level:t};return this.stepData.rows.push(n),this}separator(){this.rowOrder++;let e={id:`sep-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:`separator`};return this.stepData.rows.push(e),this}text(e){this.rowOrder++;let t={id:`text-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:`text`,content:e};return this.stepData.rows.push(t),this}step(e,t){return this.formBuilder._finalizeStep(this.stepData).step(e,t)}build(){return this.formBuilder._finalizeStep(this.stepData).build()}_finalizeRow(e){return e.fields.length>0&&this.stepData.rows.push(e),this}_getData(){return this.stepData}},FormBuilder=class{constructor(e,t){this.data={slots:[],steps:[],status:`draft`,version:1},this.validateName(e),this.data.name=e,this.data.label=t}description(e){return this.data.description=e,this}icon(e){return this.data.icon=e,this}status(e){return this.data.status=e,this}metadata(e){return this.data.metadata=e,this}slot(e,t,n){if(this.data.slots.some(t=>t.id===e))throw Error(`[FormBuilder] Duplicate slot id: "${e}"`);let r={id:e,objectName:t,label:n.label,mode:n.mode??`create`,color:n.color,icon:n.icon};return this.data.slots.push(r),this}step(e,t){if(this.data.steps.some(t=>t.id===e))throw Error(`[FormBuilder] Duplicate step id: "${e}"`);return new FormStepBuilder(this,e,t)}build(){return this.validateRequiredData(),this.validateSlotReferences(),this.validateFreeFields(),this.validatePrefillExpressions(),this.data}_finalizeStep(e){return this.data.steps.push(e),this}validateName(e){let t=f.z.string().min(1,`Form name cannot be empty`).max(63,`Form name is too long (max 63 characters)`).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,{message:`Invalid form name format. Name must be in kebab-case: 'client-onboarding', 'contact-creation'`});try{t.parse(e)}catch(e){throw e instanceof f.z.ZodError?Error(`[FormBuilder] ${e.issues[0].message}`):e}}validateRequiredData(){if(this.data.slots.length===0)throw Error(`[FormBuilder] At least one slot is required. Use .slot() to add slots.`);if(this.data.steps.length===0)throw Error(`[FormBuilder] At least one step is required. Use .step() to add steps.`)}validateSlotReferences(){let e=new Map(this.data.slots.map(e=>[e.id,e.objectName]));for(let t of this.data.steps)for(let n of t.rows)if(isFormFieldsRow(n))for(let r of n.fields){if(r.type!==`slot`)continue;let n=getSlotFieldTargets(r);for(let r of n)if(!e.has(r))throw Error(`[FormBuilder] Step "${t.id}" references unknown slot "${r}". Declare it with .slot("${r}", ...) first.`);let i=new Set(n.map(t=>e.get(t)));if(i.size>1)throw Error(`[FormBuilder] Step "${t.id}" field on attribute "${r.attribute}" targets slots of different objects (${[...i].join(`, `)}). A multi-slot field must target slots of the same object.`)}}validatePrefillExpressions(){let e=[...E,`join`];for(let t of this.data.steps)for(let n of t.rows)if(isFormFieldsRow(n))for(let r of n.fields){if(!isFormFreeFieldRef(r)||!r.prefillExpression)continue;let n=r.prefillExpression,i=`prefillExpression on free field "${r.attribute.name}" in step "${t.id}"`;if(!isLabelExpression(n))throw Error(`[FormBuilder] ${i} must contain at least one {{ attribute }} interpolation.`);if(/\{\{\s*\}\}/.test(n))throw Error(`[FormBuilder] ${i} contains empty {{ }} interpolation.`);for(let t of n.matchAll(/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g)){let n=t[1];if(!e.includes(n))throw Error(`[FormBuilder] ${i} uses invalid pipe "${n}". Valid pipes: ${e.join(`, `)}`)}}}validateFreeFields(){let e=new Set(ye);for(let t of this.data.steps)for(let n of t.rows)if(isFormFieldsRow(n)){for(let r of n.fields)if(isFormFreeFieldRef(r)){let n=r.attribute.type;if(e.has(n))throw Error(`[FormBuilder] Free field in step "${t.id}" uses forbidden attribute type "${n}". Forbidden types: ${ye.join(`, `)}`)}}}};function form(e,t){return new FormBuilder(e,t)}function resolveBuiltInTransform(e){return{text:`toString`,richtext:`toString`,number:`toNumber`,currency:`toNumber`,date:`toDate`,checkbox:`toBoolean`}[e]}var MigrationBuilder=class{constructor(e){this.operations=[],this.touchedAttributes=new Set,this.version=e}assertNotTouched(e,t){if(this.touchedAttributes.has(e))throw new n.ValidationError(`[MigrationBuilder] Conflicting operations on attribute "${e}": it was already modified earlier in this migration (attempted: ${t}).`,[])}renameAttribute(e,t){return this.assertNotTouched(e,`rename_attribute`),this.touchedAttributes.add(e),this.operations.push({type:`rename_attribute`,from:e,to:t}),this}changeType(e,t,n,r){this.assertNotTouched(e,`change_type`),this.touchedAttributes.add(e);let i=r?.transform?resolveBuiltInTransform(n):void 0;return this.operations.push({type:`change_type`,name:e,from:t,to:n,transform:i}),this}removeAttribute(e){return this.assertNotTouched(e,`remove_attribute`),this.touchedAttributes.add(e),this.operations.push({type:`remove_attribute`,name:e}),this}addAttribute(e){return this.assertNotTouched(e.name,`add_attribute`),this.touchedAttributes.add(e.name),this.operations.push({type:`add_attribute`,attribute:e}),this}updateConfig(e,t){return this.assertNotTouched(e,`update_config`),this.touchedAttributes.add(e),this.operations.push({type:`update_config`,name:e,from:{},to:t}),this}build(){return{version:this.version,operations:[...this.operations]}}};function validateObjectExpressions(e){let{name:t,labelExpression:r,embeddingExpression:i}=e;if(!r)throw new n.SchemaError(`Object "${t}" must have a labelExpression. The labelExpression defines how records are displayed in lists and relations (e.g. "{{ name }}").`,n.SchemaErrorCode.VALIDATION_FAILED);let a=D.safeParse(r);if(!a.success){let e=a.error.issues[0]?.message??`Invalid labelExpression`;throw new n.SchemaError(`Invalid labelExpression for "${t}": ${e}`,n.SchemaErrorCode.VALIDATION_FAILED)}if(i!==void 0){let e=D.safeParse(i);if(!e.success){let r=e.error.issues[0]?.message??`Invalid embeddingExpression`;throw new n.SchemaError(`Invalid embeddingExpression for "${t}": ${r}`,n.SchemaErrorCode.VALIDATION_FAILED)}}}var ObjectBuilder=class{get"~standard"(){return createStandardSchemaProps(i.u(this.build()))}constructor(e){this._migrations=[],this._sealed=!1,this._toleratedAttributes=[],this.validateName(e.name),this.obj={name:e.name,label:e.label,attributes:[],system:!0},e.id&&(this.obj.id=e.id)}description(e){return this.obj.description=e,this}pluralLabel(e){return this._pluralLabel=e,this}icon(e){return this.obj.icon=e,this}runtime(){return this.obj.system=!1,this}sealed(){return this._sealed=!0,this}tolerate(e){return this._toleratedAttributes=[...this._toleratedAttributes,...e],this}attribute(e){return this.pushAttributes([e]),this}attributes(e){return this.pushAttributes(e),this}pushAttributes(t){let r=t.map(e=>`build`in e&&typeof e.build==`function`?e.build():e);e.T([...this.obj.attributes,...r],e=>e.name,e=>new n.DuplicateError(`attribute`,e,`Object "${this.obj.name}": duplicate attribute name "${e}"`)),this.obj.attributes.push(...r)}metadata(e){return this.obj.metadata={...this.obj.metadata,...e},this}order(e){return this.obj.metadata={...this.obj.metadata,order:e},this}hidden(){return this.obj.metadata={...this.obj.metadata,hidden:!0},this}labelExpression(e){return this._labelExpression=e,this}embeddingExpression(e){return this._embeddingExpression=e,this}documentLayout(e){if(e.presets)for(let t of e.presets)validatePresetStructure(t.id,t.structure,1);return this.obj.documentLayout=e,this}migration(e,t){if(e<2)throw Error(`[ObjectBuilder] Migration version must be >= 2 (version 1 is implicit). Got: ${e}`);if(this._migrations.some(t=>t.version===e))throw Error(`[ObjectBuilder] Duplicate migration version: ${e}`);let n=new MigrationBuilder(e);return t(n),this._migrations.push(n.build()),this}build(){if(!this.obj.name)throw new n.ValidationError(`[ObjectBuilder] Missing required field: name`,[{path:[`name`],message:`name is required`}]);if(!this.obj.label)throw new n.ValidationError(`[ObjectBuilder] Missing required field: label`,[{path:[`label`],message:`label is required`}]);validateObjectExpressions({name:this.obj.name,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression});let e=[...this._migrations].sort((e,t)=>e.version-t.version);for(let t=0;t<e.length;t++){let n=t+2;if(e[t].version!==n)throw Error(`[ObjectBuilder] Migration versions must be sequential starting at 2. Expected version ${n}, got ${e[t].version}.`)}let t=e.length>0?e[e.length-1].version:1;return{...this.obj,pluralLabel:this._pluralLabel,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression,schema_version:t,migrations:e,sealed:this._sealed,toleratedAttributes:this._toleratedAttributes}}validateName(t){t!==void 0&&e.k(t)}};function object(t){if(e.z(t.name))throw new n.ReservedObjectNameError(t.name,`builder`);return new ObjectBuilder(t)}function validatePresetStructure(e,t,r){let fail=(t,r)=>{throw new n.ValidationError(t,[{path:[`documentLayout`,`presets`,e],message:r}])};r>5&&fail(`Preset structure exceeds max depth of 5`,`Preset structure too deep`);let i=new Set;for(let n of t){let t=n.title.trim();t.length===0&&fail(`Folder preset node title is required`,`Empty folder title`),t.includes(`/`)&&fail(`Folder preset node title cannot contain /`,`Folder title contains /: "${t}"`),i.has(t)&&fail(`Folder preset sibling titles must be unique`,`Duplicate folder title: "${t}"`),i.add(t),n.children&&n.children.length>0&&validatePresetStructure(e,n.children,r+1)}}function cloneBuilderValue(e,t){try{return structuredClone(e)}catch{let e=`Builder configuration must contain cloneable data`;throw new n.ValidationError(e,[{path:t,message:e}])}}function requireBuilderName(e,t){if(typeof e!=`string`||e.trim().length===0)throw new n.ValidationError(`Name must not be blank`,[{path:t,message:`Name must not be blank`}])}function validateContentConfiguration(e,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new n.ValidationError(`Invalid content configuration`,[{path:r,message:`Expected content configuration`}]);for(let t of[`name`,`label`,`placement`])if(Object.hasOwn(e,t)){let e=`Independent content configuration cannot define ${t}`;throw new n.ValidationError(e,[{path:[...r,t],message:e}])}let i=t.u.safeParse({...e,name:`content`,placement:`main`});if(!i.success)throw n.ValidationError.fromZodErrors(i.error.issues.map(e=>({path:[...r,...e.path.map(String)],message:e.message})));i.data.type===`form`&&i.data.groups.forEach((e,t)=>requireBuilderName(e.name,[...r,`groups`,String(t),`name`]));let{name:a,label:o,placement:s,...c}=i.data;return cloneBuilderValue(c,r)}function validateLiteralContent(e,t){return validateContentConfiguration(e,t),cloneBuilderValue(e,t)}function collectionSourceAddress(e){return e.relation===void 0?{kind:`object`,object:e.object}:e.object===void 0?{kind:`related`,relation:e.relation}:{kind:`relatedFrom`,object:e.object,relation:e.relation}}function collectionSourceAddressOf(e){if(!e||typeof e!=`object`)return;let t=`object`in e?e.object:void 0,n=`relation`in e?e.relation:void 0;if(typeof t==`string`&&typeof n==`string`)return{kind:`relatedFrom`,object:t,relation:n};if(typeof t==`string`&&n===void 0)return{kind:`object`,object:t};if(typeof n==`string`&&t===void 0)return{kind:`related`,relation:n}}function requireRecordContentContext(e,t,r){if(t!==`record`){let t=`Content "${e}" requires record context. In a collection view only a collection that lists a whole object, or a custom content that does not require a record, is allowed.`;throw new n.ValidationError(t,[{path:r,message:t}])}}function resolveContentNavigation(e){let t=e.openMode??`page`;return{openMode:t,createMode:e.createMode??t}}function resolveCollectionActions(e,t){return[...new Set(t)].filter(t=>e.actions===void 0||e.actions.includes(t))}var qe=class ViewBuilder{constructor(e,t=[]){this.kind=`view`,this.data=cloneBuilderValue(e,[`views`,`0`]),this.extensions=t.map(e=>e&&{...e})}for(e){return new ViewBuilder({...this.data,object:e},this.extensions)}default(){return new ViewBuilder({...this.data,default:!0},this.extensions)}description(e){return new ViewBuilder({...this.data,description:e},this.extensions)}icon(e){return new ViewBuilder({...this.data,icon:e},this.extensions)}place(e,t,r,i){let a=[`views`,`0`,`contents`,String(this.data.contents.length)],o,s;try{typeof r==`object`&&r&&`build`in r&&typeof r.build==`function`?(o=validateContentConfiguration(r.build(),a),s=r.extension):o=validateContentConfiguration(r,a)}catch(e){throw e instanceof n.ValidationError?new n.ValidationError(e.message,e.errors.map(e=>({...e,path:e.path[0]===`content`?[...a,...e.path.slice(1)]:e.path}))):e}let c={...o,name:e,label:t,placement:i},l=[...this.data.contents,c];return new ViewBuilder({...this.data,contents:l},[...this.extensions,s])}tab(e,t,n){return this.place(e,t,n,`main`)}aside(e,t,n){return this.place(e,t,n,`aside`)}build(){let e=[`views`,`0`];requireBuilderName(this.data.name,[...e,`name`]),requireBuilderName(this.data.object,[...e,`object`]);let r=t.i.safeParse(this.data);if(!r.success)throw n.ValidationError.fromZodErrors(r.error.issues.map(t=>({path:[...e,...t.path.map(String)],message:t.message})));return this.data.contents.forEach((t,n)=>{let r=[...e,`contents`,String(n)];requireBuilderName(t.name,[...r,`name`]),t.type===`form`&&t.groups.forEach((e,t)=>requireBuilderName(e.name,[...r,`groups`,String(t),`name`])),(t.type===`custom`?this.extensions[n]?.requiresRecord:t.type!==`collection`||collectionSourceAddress(t.source).kind!==`object`)&&requireRecordContentContext(t.name,this.data.context,r)}),{kind:`view`,definition:cloneBuilderValue(this.data,e)}}};function detailView(e,t){return new qe({name:e,label:t,object:void 0,context:`record`,contents:[]})}function listView(e,t){return new qe({name:e,label:t,object:void 0,context:`collection`,contents:[]})}function relationProperty(e){return requireBuilderName(e,[`relationProperty`]),{relationProperty:e}}var j=class ContentBuilder{constructor(e,t){this.data=cloneBuilderValue(e,[`content`]),this.extension=t===void 0?void 0:Object.freeze({name:t.name,requiresRecord:t.requiresRecord,parameters:t.parameters})}set(e){return new ContentBuilder({...this.data,...e},this.extension)}icon(e){return this.set({icon:e})}object(e){return this.data.type===`forms`?this.set({objectName:e}):this.set({source:{object:e}})}related(e){return this.set({source:{relation:e}})}relatedFrom(e,t){return this.set({source:{object:e,relation:t}})}layout(e){let{layout:t,groupByAttribute:n,columnSizing:r,kanbanColumnOrder:i,kanbanColumnVisibility:a,kanbanPinnedColumns:o,...s}={...this.data,layout:void 0,groupByAttribute:void 0,columnSizing:void 0,kanbanColumnOrder:void 0,kanbanColumnVisibility:void 0,kanbanPinnedColumns:void 0};return new ContentBuilder({...s,...e},this.extension)}table(){return this.layout({layout:`table`})}list(){return this.layout({layout:`list`})}kanban(e){return this.layout({layout:`kanban`,groupByAttribute:e})}columns(...e){return this.set({columns:e})}filter(e){return this.set({filters:e})}sort(e,t=`asc`){let n=[...`sorts`in this.data&&Array.isArray(this.data.sorts)?this.data.sorts:[],{attribute:e,direction:t}];return this.set({sorts:n})}actions(...e){return this.set({actions:e})}openMode(e){return this.set({openMode:e})}createMode(e){return this.set({createMode:e})}visibility(e){return this.set({visibility:e})}descriptionAttribute(e){return this.set({descriptionAttribute:e})}displayAttributes(...e){return this.set({displayAttributes:e})}columnSizing(e){return this.set({columnSizing:e})}kanbanColumnOrder(...e){return this.set({kanbanColumnOrder:e})}kanbanColumnVisibility(e){return this.set({kanbanColumnVisibility:e})}kanbanPinnedColumns(...e){return this.set({kanbanPinnedColumns:e})}formColumns(e){return this.set({formColumns:e})}density(e){return this.set({density:e})}titleAttribute(e){return this.set({titleAttribute:e})}allowUpload(e){return this.set({allowUpload:e})}allowRemove(e){return this.set({allowRemove:e})}hideAttachments(e){return this.set({hideAttachments:e})}relations(...e){return this.set({relations:e})}build(){let e=validateLiteralContent(this.data,[`content`]);if(this.extension&&e.type===`custom`){let t=this.extension.parameters.safeParse(cloneBuilderValue(e.parameters??{},[`content`,`parameters`]));if(!t.success)throw n.ValidationError.fromZodErrors(t.error.issues.map(e=>({path:[`content`,`parameters`,...e.path.map(String)],message:e.message})))}return e}},Je=class GroupBuilder{constructor(e,t,n,r={}){this.data=cloneBuilderValue({name:e,label:t,fields:n,...r},[`group`])}field(e,t){let{name:n,label:r,fields:i,...a}=this.data;return new GroupBuilder(n,r,[...i,{attribute:e,...t}],a)}fields(...e){let{name:t,label:n,fields:r,...i}=this.data;return new GroupBuilder(t,n,[...r,...e.map(e=>({attribute:e}))],i)}description(e){return new GroupBuilder(this.data.name,this.data.label,this.data.fields,{...this.presentation(),description:e})}collapsible(e=!1){return new GroupBuilder(this.data.name,this.data.label,this.data.fields,{...this.presentation(),collapsible:!0,collapsed:e})}presentation(){let{name:e,label:t,fields:n,...r}=this.data;return r}build(){requireBuilderName(this.data.name,[`group`,`name`]);try{validateLiteralContent({type:`form`,groups:[this.data]},[`group`])}catch(e){throw e instanceof n.ValidationError?new n.ValidationError(e.message,e.errors.map(e=>({...e,path:e.path[1]===`groups`?[`group`,...e.path.slice(3)]:e.path}))):e}return cloneBuilderValue(this.data,[`group`])}};function group(e,t){return new Je(e,t,[])}function collection(){return new j({type:`collection`})}function form$1(...e){return new j({type:`form`,groups:e.map(e=>`build`in e?e.build():e)})}function activity(){return new j({type:`activity`})}function richtext$1(e){return new j({type:`richtext`,attribute:e})}function documents(){return new j({type:`documents`})}function forms(){return new j({type:`forms`})}function emails(...e){return new j({type:`emails`,emailAttributes:e})}function meetings(...e){return new j({type:`meetings`,emailAttributes:e})}function custom(e,t){if(typeof e!=`object`||!e||typeof e.name!=`string`)throw new n.ValidationError(`Expected registered extension declaration`,[{path:[`content`,`extension`],message:`Expected registered extension declaration`}]);let r=validateContentConfiguration({type:`custom`,extension:e.name,parameters:t},[`content`]);if(r.type!==`custom`)throw new n.ValidationError(`Expected custom content`,[]);let i=new j({...r,extension:e.name},e);return i.build(),i}const M={collection,form:form$1,activity,richtext:richtext$1,documents,forms,emails,meetings,custom};function validateFlagName(e){if(!/^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$/.test(e))throw Error(`Invalid flag name "${e}". Flag names must be kebab-case (e.g., "architect-mode", "ai-features").`)}var BaseFlagBuilder=class{constructor(e,t,n){validateFlagName(e),this.flag={name:e,valueType:t,defaultValue:n,allowedLevels:[`global`,`tenant`,`user`]}}label(e){return this.flag.label=e,this}description(e){return this.flag.description=e,this}category(e){return this.flag.category=e,this}system(){return this.flag.system=!0,this}tenantScoped(){return this.flag.allowedLevels=[`global`,`tenant`],this}globalOnly(){return this.flag.allowedLevels=[`global`],this}allowedLevels(e){return this.flag.allowedLevels=[...e],this}build(){if(!this.flag.label?.trim())throw Error(`Flag "${this.flag.name}" must have a label. Use .label("Human-readable label").`);return{...this.flag,allowedLevels:[...this.flag.allowedLevels||[]]}}},BooleanFlagBuilder=class extends BaseFlagBuilder{constructor(e){super(e,`boolean`,!1)}defaultValue(e){return this.flag.defaultValue=e,this}enabledByDefault(){return this.flag.defaultValue=!0,this}},StringFlagBuilder=class extends BaseFlagBuilder{constructor(e){super(e,`string`,``)}defaultValue(e){return this.flag.defaultValue=e,this}},NumberFlagBuilder=class extends BaseFlagBuilder{constructor(e){super(e,`number`,0)}defaultValue(e){return this.flag.defaultValue=e,this}},JsonFlagBuilder=class extends BaseFlagBuilder{constructor(e,t){super(e,`json`,t)}defaultValue(e){return this.flag.defaultValue=e,this}};function booleanFlag(e){return new BooleanFlagBuilder(e)}function stringFlag(e){return new StringFlagBuilder(e)}function numberFlag(e){return new NumberFlagBuilder(e)}function jsonFlag(e,t){return new JsonFlagBuilder(e,t)}function duplicateFlagError(e){return new n.DuplicateError(`feature flag`,e,`Flag "${e}" is already registered. Each flag name must be unique.`)}function cloneFlagDefinition(e){return{...e,allowedLevels:[...e.allowedLevels]}}var FlagRegistry=class{constructor(){this.flags=new Map}register(e){if(this.flags.has(e.name))throw duplicateFlagError(e.name);this.flags.set(e.name,cloneFlagDefinition(e))}registerAll(e){let t=new Set;for(let n of e){if(this.flags.has(n.name)||t.has(n.name))throw duplicateFlagError(n.name);t.add(n.name)}for(let t of e)this.register(t)}get(e){let t=this.flags.get(e);return t?cloneFlagDefinition(t):void 0}getOrThrow(e){let t=this.get(e);if(!t)throw new n.NotFoundError(`Feature flag`,e,void 0,`Flag "${e}" is not registered. Available flags: ${this.listNames().join(`, `)}`);return t}has(e){return this.flags.has(e)}list(){return Array.from(this.flags.values(),cloneFlagDefinition)}listNames(){return Array.from(this.flags.keys())}unregister(e){return this.flags.delete(e)}clear(){this.flags.clear()}get size(){return this.flags.size}};const Ye=new FlagRegistry;function createFlagRegistry(){return new FlagRegistry}function emptyOverrides(){return{global:new Map,tenant:new Map,user:new Map}}function isActiveOverride(e,t){return e.expiresAt===void 0||e.expiresAt.getTime()>t}function indexOverrides(e,t){let n=new Map;for(let r of e){if(!isActiveOverride(r,t))continue;let e=r.flagName;n.has(e)||n.set(e,r)}return n}var FlagService=class{constructor(e){this.repository=e.repository,this.registry=e.registry,this.staticDefaults=new Map(e.staticDefaults?.map(e=>[e.name,e.value])??[])}async resolveAll(e={}){let t=this.collectFlagNames(),n=this.repository&&t.size>0?await this.getAllOverrides(e,[...t]):emptyOverrides();return this.resolveNames(t,n,e)}resolveAllStatic(){return this.resolveNames(this.collectFlagNames(),emptyOverrides(),{})}collectFlagNames(){let e=new Set;for(let t of this.registry.listNames())e.add(t);for(let t of this.staticDefaults.keys())e.add(t);return e}resolveNames(e,t,n){let r=new Map;for(let i of e)r.set(i,this.resolveValue(i,t,n));return r}async resolve(e,t={}){let n=this.repository?await this.getAllOverrides(t,[e]):emptyOverrides();return this.resolveWithSource(e,n,t)}async isEnabled(e,t={}){return(await this.resolve(e,t)).value===!0}async getValue(e,t={}){return(await this.resolve(e,t)).value}async setOverride(e,t,r,i={}){if(!this.repository)throw new n.SchemaError(`Cannot set override: no FeatureFlagsRepository configured. Add featureFlags to your DatabaseAdapter to enable runtime overrides.`,n.SchemaErrorCode.CONFIGURATION_REQUIRED);let a=this.registry.get(e);if(a&&!a.allowedLevels.includes(t)){let r=`Flag "${e}" does not allow ${t}-level overrides. Allowed levels: ${a.allowedLevels.join(`, `)}`;throw new n.ValidationError(r,[{path:[`level`],message:r}])}if(a?.system){let t=`Flag "${e}" is a system flag and cannot be overridden via API.`;throw new n.ValidationError(t,[{path:[`flagName`],message:t}])}await this.repository.setOverride({flagName:e,level:t,value:r,targetId:i.targetId,expiresAt:i.expiresAt,createdBy:i.createdBy})}async deleteOverride(e,t,r){if(!this.repository)throw new n.SchemaError(`Cannot delete override: no FeatureFlagsRepository configured.`,n.SchemaErrorCode.CONFIGURATION_REQUIRED);await this.repository.deleteOverride(e,t,r)}async getAllOverrides(e,t){if(!this.repository)return emptyOverrides();let[n,r,i]=await Promise.all([this.repository.getOverrides({level:`global`,flagNames:t}),e.tenantId?this.repository.getOverrides({level:`tenant`,targetId:e.tenantId,flagNames:t}):Promise.resolve([]),e.userId?this.repository.getOverrides({level:`user`,targetId:e.userId,flagNames:t}):Promise.resolve([])]),a=Date.now();return{global:indexOverrides(n,a),tenant:indexOverrides(r,a),user:indexOverrides(i,a)}}resolveValue(e,t,n){return this.resolveWithSource(e,t,n).value}resolveWithSource(e,t,n){let r=this.registry.get(e),i=r?.allowedLevels??[`global`,`tenant`,`user`];if(n.userId&&i.includes(`user`)){let r=t.user.get(e);if(r)return{name:e,value:r.value,source:`user`,sourceId:n.userId}}if(n.tenantId&&i.includes(`tenant`)){let r=t.tenant.get(e);if(r)return{name:e,value:r.value,source:`tenant`,sourceId:n.tenantId}}if(i.includes(`global`)){let n=t.global.get(e);if(n)return{name:e,value:n.value,source:`global`}}return this.staticDefaults.has(e)?{name:e,value:this.staticDefaults.get(e),source:`default`}:{name:e,value:r?.defaultValue??void 0,source:`default`}}};function createFlagService(e){return new FlagService(e)}const Xe=Symbol(`stndrds.native-object`);function markNativeDefinition(e){return Object.defineProperty(e,Xe,{value:!0,enumerable:!1}),e}var NativeObjectBuilder=class extends ObjectBuilder{build(){return markNativeDefinition(super.build())}};function nativeObject(e){return new NativeObjectBuilder(e)}function isNativeDefinition(e){return e[Xe]===!0}function cloneObjectDefinition(e){let t=structuredClone(e);return isNativeDefinition(e)?markNativeDefinition(t):t}var NativeObjectRegistryClass=class{constructor(){this.objects=new Map}register(e){let t=(Array.isArray(e)?e:[e]).map(e=>`build`in e&&typeof e.build==`function`?e.build():e),r=new Set;for(let e of t){if(this.validate(e),r.has(e.name))throw new n.DuplicateError(`object`,e.name,`[NativeObjectRegistry] Duplicate object name "${e.name}" within a single register() batch.`);r.add(e.name)}for(let e of t)this.objects.set(e.name,cloneObjectDefinition(e));return this}validate(t){if(!t.system){let e=`[NativeObjectRegistry] Cannot register object "${t.name}" (id: ${t.id}): missing system flag.\nNative objects must have system=true. Did you call .runtime() on the builder? Remove that call — objects are system:true by default.`;throw new n.ValidationError(e,[])}if(e.z(t.name)&&!isNativeDefinition(t))throw new n.ReservedObjectNameError(t.name,`registry`);if(this.objects.has(t.name)){let e=this.objects.get(t.name),r=`[NativeObjectRegistry] Duplicate object name "${t.name}":\n - Existing: "${e?.label}" (id: ${e?.id})\n - New: "${t.label}" (id: ${t.id})\nPlease use unique names for each native object.`;throw new n.DuplicateError(`object`,t.name,r)}}getByName(e){let t=this.objects.get(e);return t?cloneObjectDefinition(t):void 0}getByNameOrThrow(e){let t=this.getByName(e);if(!t){let t=`[NativeObjectRegistry] Native object "${e}" not found.\nAvailable objects: ${this.listNames().join(`, `)}`;throw new n.NotFoundError(`Native object`,e,n.SchemaErrorCode.OBJECT_NOT_FOUND,t)}return t}getAll(){return Array.from(this.objects.values(),cloneObjectDefinition)}listNames(){return Array.from(this.objects.keys())}has(e){return this.objects.has(e)}get size(){return this.objects.size}clear(){this.objects.clear()}summary(){let e=this.getAll();return[`[NativeObjectRegistry] ${this.size} native object(s) registered:`,...e.map(e=>` - ${e.name}: "${e.label}" (${e.attributes.length} attributes)`)].join(`
3
+ `)}debug(e){let t=this.summary();return e?.(t),t}};const Ze=new NativeObjectRegistryClass,Qe=new WeakSet;function markSystemView(e){return Qe.add(e.definition),e}function isSystemViewDefinition(e){return typeof e==`object`&&!!e&&Qe.has(e)}const $e=`## Overview
9
4
 
10
- Describe in one or two sentences what this skill does and the outcome it produces. The agent reads this page when it uses the skill \u2014 write instructions for the agent, not documentation for people.
5
+ Describe in one or two sentences what this skill does and the outcome it produces. The agent reads this page when it uses the skill — write instructions for the agent, not documentation for people.
11
6
 
12
7
  ## When to use
13
8
 
14
9
  List the situations or requests that should trigger this skill. Concrete phrases beat vague categories.
15
10
 
16
- - When asked to \u2026
17
- - When a record of \u2026 needs \u2026
11
+ - When asked to …
12
+ - When a record of … needs …
18
13
 
19
14
  ## Instructions
20
15
 
21
- Write imperative, step-by-step directions. Name the exact objects, documents, or tools involved \u2014 the agent follows these literally.
16
+ Write imperative, step-by-step directions. Name the exact objects, documents, or tools involved — the agent follows these literally.
22
17
 
23
- 1. First, \u2026
24
- 2. Then, \u2026
25
- 3. Finally, \u2026
18
+ 1. First, …
19
+ 2. Then, …
20
+ 3. Finally, …
26
21
 
27
22
  ## Examples
28
23
 
29
24
  Show at least one concrete example of the skill applied well.
30
25
 
31
- **Request:** "\u2026"
26
+ **Request:** "…"
32
27
 
33
- **Expected result:** \u2026
28
+ **Expected result:** …
34
29
 
35
30
  ## What to avoid
36
31
 
37
- - Never \u2026
38
- - Do not \u2026
39
- `,Al=xe({name:"skill",label:"Skill"}).sealed().icon("book-open").order(Number.MAX_SAFE_INTEGER).pluralLabel("Skills").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
32
+ - Never …
33
+ - Do not …
34
+ `,et=nativeObject({name:`skill`,label:`Skill`}).sealed().icon(`book-open`).order(2**53-1).pluralLabel(`Skills`).labelExpression(`{{ name }}`).embeddingExpression(`{{ name }}
40
35
  {{ description }}
41
- {{ content }}`).attribute(S({name:"name",label:"Name"}).maxLength(constants.SKILL_NAME_MAX_LENGTH).required()).attribute(S({name:"description",label:"Description"}).multiline().maxLength(constants.SKILL_DESCRIPTION_MAX_LENGTH).required().placeholder('What this skill does and when to use it \u2014 e.g. "Drafts replies to customer complaints. Use when asked to answer an unhappy customer."')).attribute(je({name:"content",label:"Content"}).defaultValue(Sa)).build(),xl=G(ye("skill-detail","Skill").for("skill").default().tab("content","Content",D.richtext("content").titleAttribute("name")).tab("files","Files",D.documents()).tab("activity","Activity",D.activity()).aside("details","Details",D.form(Ae("details","Details").fields("name","description"))).build()),Tl=G(he("skill-list","Skills").for("skill").default().tab("workspace","Skills",D.collection().object("skill").list().icon("list").visibility("workspace").columns("name","description").descriptionAttribute("description").displayAttributes("createdBy","updatedAt").sort("name")).tab("mine","My skills",D.collection().object("skill").list().icon("lock").visibility("private").columns("name","description").descriptionAttribute("description").displayAttributes("createdBy","updatedAt").sort("name")).build());var Il=xe({name:"memory",label:"Memory"}).sealed().icon("database").order(Number.MAX_SAFE_INTEGER).pluralLabel("Memories").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
36
+ {{ content }}`).attribute(text({name:`name`,label:`Name`}).maxLength(d.SKILL_NAME_MAX_LENGTH).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(d.SKILL_DESCRIPTION_MAX_LENGTH).required().placeholder(`What this skill does and when to use it — e.g. "Drafts replies to customer complaints. Use when asked to answer an unhappy customer."`)).attribute(richtext({name:`content`,label:`Content`}).defaultValue($e)).build(),tt=markSystemView(detailView(`skill-detail`,`Skill`).for(`skill`).default().tab(`content`,`Content`,M.richtext(`content`).titleAttribute(`name`)).tab(`files`,`Files`,M.documents()).tab(`activity`,`Activity`,M.activity()).aside(`details`,`Details`,M.form(group(`details`,`Details`).fields(`name`,`description`))).build()),nt=markSystemView(listView(`skill-list`,`Skills`).for(`skill`).default().tab(`workspace`,`Skills`,M.collection().object(`skill`).list().icon(`list`).visibility(`workspace`).columns(`name`,`description`).descriptionAttribute(`description`).displayAttributes(`createdBy`,`updatedAt`).sort(`name`)).tab(`mine`,`My skills`,M.collection().object(`skill`).list().icon(`lock`).visibility(`private`).columns(`name`,`description`).descriptionAttribute(`description`).displayAttributes(`createdBy`,`updatedAt`).sort(`name`)).build()),rt=nativeObject({name:`memory`,label:`Memory`}).sealed().icon(`database`).order(2**53-1).pluralLabel(`Memories`).labelExpression(`{{ name }}`).embeddingExpression(`{{ name }}
42
37
  {{ description }}
43
- {{ content }}`).migration(2,e=>e.changeType("content","text","richtext")).attribute(S({name:"name",label:"Name"}).maxLength(constants.MEMORY_NAME_MAX_LENGTH).required()).attribute(S({name:"description",label:"Description"}).multiline().maxLength(constants.MEMORY_DESCRIPTION_MAX_LENGTH).required()).attribute(je({name:"content",label:"Content"})).attribute(be({name:"kind",label:"Kind"}).options([{value:"fact",label:"Fact"},{value:"preference",label:"Preference"},{value:"feedback",label:"Feedback"},{value:"reference",label:"Reference"}])).attribute(ot({name:"subjects",label:"Subjects"}).toAny().many()).attribute(ot({name:"links",label:"Links"}).to("memory").many()).attribute(be({name:"source",label:"Source"}).options([{value:"explicit",label:"Saved by an agent"},{value:"extracted",label:"Extracted from a session"},{value:"corroborated",label:"Corroborated across users"},{value:"curated",label:"Curated by Dreamer"}])).attribute(se({name:"validFrom",label:"Valid from"}).includeTime()).attribute(se({name:"invalidAt",label:"Invalid at"}).includeTime()).attribute(ot({name:"supersededBy",label:"Superseded by"}).to("memory")).attribute(S({name:"provenance",label:"Provenance"}).multiline()).attribute(be({name:"reviewState",label:"Review state"}).options([{value:"needs_review",label:"Needs review"},{value:"skill_candidate",label:"Skill candidate"}])).attribute(S({name:"reviewReason",label:"Review reason"}).multiline()).attribute(se({name:"curatedAt",label:"Curated at"}).includeTime()).attribute(se({name:"reviewAfter",label:"Review after"}).includeTime()).attribute(S({name:"curationFingerprint",label:"Curation fingerprint"})).build(),Ia={combinator:"and",rules:[{attribute:"invalidAt",operator:"is_empty",value:null},{attribute:"reviewState",operator:"is_empty",value:null}]},Rl=G(ye("memory-detail","Memory").for("memory").default().tab("content","Content",D.richtext("content").titleAttribute("name")).aside("details","Details",D.form(Ae("details","Details").fields("description","kind","source","provenance","reviewState","reviewReason","validFrom","invalidAt","supersededBy","curatedAt","reviewAfter","subjects","links"))).build()),Cl=G(he("memory-list","Memories").for("memory").default().tab("workspace","Memories",D.collection().object("memory").list().icon("list").visibility("workspace").columns("name","kind","description","createdAt").descriptionAttribute("description").displayAttributes("kind","subjects","createdAt").filter(Ia).sort("name")).tab("mine","My memories",D.collection().object("memory").list().icon("lock").visibility("private").columns("name","kind","description","createdAt").descriptionAttribute("description").displayAttributes("kind","subjects","createdAt").filter(Ia).sort("name")).tab("review","To review",D.collection().object("memory").table().icon("question-circle").columns("name","reviewState","reviewReason","updatedAt").filter({combinator:"and",rules:[{attribute:"invalidAt",operator:"is_empty",value:null},{attribute:"reviewState",operator:"is_not_empty",value:null}]}).sort("updatedAt","desc")).tab("history","History",D.collection().object("memory").table().icon("archive").columns("name","kind","invalidAt","supersededBy").filter({combinator:"and",rules:[{attribute:"invalidAt",operator:"is_not_empty",value:null}]}).sort("invalidAt","desc")).build());var ct="drives",vl=xe({name:ct,label:"Drive"}).sealed().icon("folder").hidden().pluralLabel("Drives").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
44
- {{ description }}`).attribute(S({name:"name",label:"Name"}).required()).attribute(S({name:"description",label:"Description"}).multiline()).build(),El=G(ye("drive-detail","Drive").for(ct).default().tab("documents","Documents",D.documents()).aside("details","Details",D.form(Ae("details","Details").field("description"))).build()),Nl=G(he("drive-list","Drives").for(ct).default().tab("workspace","Shared",D.collection().object(ct).table().icon("users").visibility("workspace").columns("name","description","updatedAt").sort("name")).tab("mine","My drives",D.collection().object(ct).table().icon("lock").visibility("private").columns("name","description","updatedAt").sort("name")).build());var pn={name:"artifact_preview",requiresRecord:true,parameters:zod.z.object({}).strict()},ut="artifact",Ol=xe({name:ut,label:"Artifact"}).sealed().icon("package").pluralLabel("Artifacts").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
45
- {{ description }}`).attribute(S({name:"name",label:"Name"}).required()).attribute(S({name:"description",label:"Description"}).multiline()).attribute(be({name:"kind",label:"Kind"}).options([{value:"web",label:"Web",color:"blue"},{value:"presentation",label:"Presentation",color:"purple"},{value:"document",label:"Document",color:"sky"},{value:"spreadsheet",label:"Spreadsheet",color:"green"},{value:"image",label:"Image",color:"pink"},{value:"code",label:"Code",color:"slate"},{value:"other",label:"Other",color:"gray"}]).required()).attribute(be({name:"retention",label:"Retention"}).options([{value:"ephemeral",label:"Ephemeral",color:"gray"},{value:"conversation",label:"Conversation",color:"blue"},{value:"persistent",label:"Persistent",color:"green"}]).defaultValue("conversation").required()).attribute(sn({name:"currentRevision",label:"Current revision"}).integer().min(1)).attribute(se({name:"expiresAt",label:"Expires at"}).includeTime().hidden()).attribute(S({name:"sourceSessionId",label:"Source session"}).hidden()).attribute(S({name:"sourceMessageId",label:"Source message"}).hidden()).attribute(S({name:"initialToolCallId",label:"Initial tool call"}).hidden()).attribute(ga({name:"versions",label:"Versions"}).qualifyWith(sn({name:"revision",label:"Revision"}).integer().min(1).required(),S({name:"toolCallId",label:"Tool call"}).hidden(),S({name:"sourceFileId",label:"Source file"}).hidden(),S({name:"previewFileId",label:"Preview file"}).hidden(),S({name:"fileIds",label:"File manifest"}).hidden(),S({name:"entrypoint",label:"Entrypoint"}).hidden(),S({name:"sourceMessageId",label:"Source message"}).hidden(),S({name:"artifactName",label:"Artifact name"}).hidden(),S({name:"artifactDescription",label:"Artifact description"}).hidden(),S({name:"artifactKind",label:"Artifact kind"}).hidden(),S({name:"displayMode",label:"Display mode"}).hidden(),S({name:"displayInteraction",label:"Display interaction"}).hidden(),S({name:"displaySize",label:"Display size"}).hidden(),sn({name:"displayAspectRatio",label:"Display aspect ratio"}).hidden())).build(),jl=G(ye("artifact-detail","Artifact").for(ut).default().tab("preview","Preview",D.custom(pn,{})).tab("versions","Versions",D.documents().allowUpload(false).allowRemove(false).hideAttachments(true)).tab("activity","Activity",D.activity()).aside("details","Details",D.form(Ae("details","Details").field("description",{readOnly:true}).field("kind",{readOnly:true}).field("retention",{readOnly:true}).field("currentRevision",{readOnly:true}).field("createdBy",{readOnly:true}).field("updatedAt",{readOnly:true}))).build()),kl=G(he("artifact-list","Artifacts").for(ut).default().tab("mine","My artifacts",D.collection().object(ut).list().icon("lock").visibility("private").actions().columns("name","kind","currentRevision","updatedAt").descriptionAttribute("description").displayAttributes("kind","currentRevision","updatedAt").sort("updatedAt","desc")).tab("workspace","Workspace",D.collection().object(ut).list().icon("list").visibility("workspace").actions().columns("name","kind","currentRevision","updatedAt").descriptionAttribute("description").displayAttributes("kind","currentRevision","updatedAt").sort("updatedAt","desc")).build());var lt="meeting",v={title:"title",description:"description",location:"location",startsAt:"startsAt",endsAt:"endsAt",isAllDay:"isAllDay",status:"status",organizerAddress:"organizerAddress",organizerName:"organizerName",conferenceProvider:"conferenceProvider",conferenceJoinUrl:"conferenceJoinUrl",htmlLink:"htmlLink",participants:"participants",providerEventId:"providerEventId",icalUid:"icalUid",recurringEventId:"recurringEventId",connectionId:"connectionId",recordingOverride:"recordingOverride",endedAnnouncedAt:"endedAnnouncedAt",summary:"summary",transcript:"transcript",linkedRecords:"linkedRecords"},Ca="meeting-list",va="calendar-sync",Ea="meeting-detail",Ra=[v.title,v.startsAt,v.endsAt,v.status],_l=xe({name:lt,label:"Meeting"}).sealed().hidden().metadata({platformOwned:{editable:[v.linkedRecords],source:va}}).icon("calendar").pluralLabel("Meetings").labelExpression("{{ title }}").embeddingExpression(`{{ title }}
38
+ {{ content }}`).migration(2,e=>e.changeType(`content`,`text`,`richtext`)).attribute(text({name:`name`,label:`Name`}).maxLength(d.MEMORY_NAME_MAX_LENGTH).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(d.MEMORY_DESCRIPTION_MAX_LENGTH).required()).attribute(richtext({name:`content`,label:`Content`})).attribute(select({name:`kind`,label:`Kind`}).options([{value:`fact`,label:`Fact`},{value:`preference`,label:`Preference`},{value:`feedback`,label:`Feedback`},{value:`reference`,label:`Reference`}])).attribute(relation({name:`subjects`,label:`Subjects`}).toAny().many()).attribute(relation({name:`links`,label:`Links`}).to(`memory`).many()).attribute(select({name:`source`,label:`Source`}).options([{value:`explicit`,label:`Saved by an agent`},{value:`extracted`,label:`Extracted from a session`},{value:`corroborated`,label:`Corroborated across users`},{value:`curated`,label:`Curated by Dreamer`}])).attribute(date({name:`validFrom`,label:`Valid from`}).includeTime()).attribute(date({name:`invalidAt`,label:`Invalid at`}).includeTime()).attribute(relation({name:`supersededBy`,label:`Superseded by`}).to(`memory`)).attribute(text({name:`provenance`,label:`Provenance`}).multiline()).attribute(select({name:`reviewState`,label:`Review state`}).options([{value:`needs_review`,label:`Needs review`},{value:`skill_candidate`,label:`Skill candidate`}])).attribute(text({name:`reviewReason`,label:`Review reason`}).multiline()).attribute(date({name:`curatedAt`,label:`Curated at`}).includeTime()).attribute(date({name:`reviewAfter`,label:`Review after`}).includeTime()).attribute(text({name:`curationFingerprint`,label:`Curation fingerprint`})).build(),it={combinator:`and`,rules:[{attribute:`invalidAt`,operator:`is_empty`,value:null},{attribute:`reviewState`,operator:`is_empty`,value:null}]},at=markSystemView(detailView(`memory-detail`,`Memory`).for(`memory`).default().tab(`content`,`Content`,M.richtext(`content`).titleAttribute(`name`)).aside(`details`,`Details`,M.form(group(`details`,`Details`).fields(`description`,`kind`,`source`,`provenance`,`reviewState`,`reviewReason`,`validFrom`,`invalidAt`,`supersededBy`,`curatedAt`,`reviewAfter`,`subjects`,`links`))).build()),ot=markSystemView(listView(`memory-list`,`Memories`).for(`memory`).default().tab(`workspace`,`Memories`,M.collection().object(`memory`).list().icon(`list`).visibility(`workspace`).columns(`name`,`kind`,`description`,`createdAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`subjects`,`createdAt`).filter(it).sort(`name`)).tab(`mine`,`My memories`,M.collection().object(`memory`).list().icon(`lock`).visibility(`private`).columns(`name`,`kind`,`description`,`createdAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`subjects`,`createdAt`).filter(it).sort(`name`)).tab(`review`,`To review`,M.collection().object(`memory`).table().icon(`question-circle`).columns(`name`,`reviewState`,`reviewReason`,`updatedAt`).filter({combinator:`and`,rules:[{attribute:`invalidAt`,operator:`is_empty`,value:null},{attribute:`reviewState`,operator:`is_not_empty`,value:null}]}).sort(`updatedAt`,`desc`)).tab(`history`,`History`,M.collection().object(`memory`).table().icon(`archive`).columns(`name`,`kind`,`invalidAt`,`supersededBy`).filter({combinator:`and`,rules:[{attribute:`invalidAt`,operator:`is_not_empty`,value:null}]}).sort(`invalidAt`,`desc`)).build()),N=`drives`,st=nativeObject({name:N,label:`Drive`}).sealed().icon(`folder`).hidden().pluralLabel(`Drives`).labelExpression(`{{ name }}`).embeddingExpression(`{{ name }}
39
+ {{ description }}`).attribute(text({name:`name`,label:`Name`}).required()).attribute(text({name:`description`,label:`Description`}).multiline()).build(),ct=markSystemView(detailView(`drive-detail`,`Drive`).for(N).default().tab(`documents`,`Documents`,M.documents()).aside(`details`,`Details`,M.form(group(`details`,`Details`).field(`description`))).build()),lt=markSystemView(listView(`drive-list`,`Drives`).for(N).default().tab(`workspace`,`Shared`,M.collection().object(N).table().icon(`users`).visibility(`workspace`).columns(`name`,`description`,`updatedAt`).sort(`name`)).tab(`mine`,`My drives`,M.collection().object(N).table().icon(`lock`).visibility(`private`).columns(`name`,`description`,`updatedAt`).sort(`name`)).build()),ut={name:`artifact_preview`,requiresRecord:!0,parameters:f.z.object({}).strict()},P=`artifact`,dt=nativeObject({name:P,label:`Artifact`}).sealed().icon(`package`).pluralLabel(`Artifacts`).labelExpression(`{{ name }}`).embeddingExpression(`{{ name }}
40
+ {{ description }}`).attribute(text({name:`name`,label:`Name`}).required()).attribute(text({name:`description`,label:`Description`}).multiline()).attribute(select({name:`kind`,label:`Kind`}).options([{value:`web`,label:`Web`,color:`blue`},{value:`presentation`,label:`Presentation`,color:`purple`},{value:`document`,label:`Document`,color:`sky`},{value:`spreadsheet`,label:`Spreadsheet`,color:`green`},{value:`image`,label:`Image`,color:`pink`},{value:`code`,label:`Code`,color:`slate`},{value:`other`,label:`Other`,color:`gray`}]).required()).attribute(select({name:`retention`,label:`Retention`}).options([{value:`ephemeral`,label:`Ephemeral`,color:`gray`},{value:`conversation`,label:`Conversation`,color:`blue`},{value:`persistent`,label:`Persistent`,color:`green`}]).defaultValue(`conversation`).required()).attribute(number({name:`currentRevision`,label:`Current revision`}).integer().min(1)).attribute(date({name:`expiresAt`,label:`Expires at`}).includeTime().hidden()).attribute(text({name:`sourceSessionId`,label:`Source session`}).hidden()).attribute(text({name:`sourceMessageId`,label:`Source message`}).hidden()).attribute(text({name:`initialToolCallId`,label:`Initial tool call`}).hidden()).attribute(document({name:`versions`,label:`Versions`}).qualifyWith(number({name:`revision`,label:`Revision`}).integer().min(1).required(),text({name:`toolCallId`,label:`Tool call`}).hidden(),text({name:`sourceFileId`,label:`Source file`}).hidden(),text({name:`previewFileId`,label:`Preview file`}).hidden(),text({name:`fileIds`,label:`File manifest`}).hidden(),text({name:`entrypoint`,label:`Entrypoint`}).hidden(),text({name:`sourceMessageId`,label:`Source message`}).hidden(),text({name:`artifactName`,label:`Artifact name`}).hidden(),text({name:`artifactDescription`,label:`Artifact description`}).hidden(),text({name:`artifactKind`,label:`Artifact kind`}).hidden(),text({name:`displayMode`,label:`Display mode`}).hidden(),text({name:`displayInteraction`,label:`Display interaction`}).hidden(),text({name:`displaySize`,label:`Display size`}).hidden(),number({name:`displayAspectRatio`,label:`Display aspect ratio`}).hidden())).build(),ft=markSystemView(detailView(`artifact-detail`,`Artifact`).for(P).default().tab(`preview`,`Preview`,M.custom(ut,{})).tab(`versions`,`Versions`,M.documents().allowUpload(!1).allowRemove(!1).hideAttachments(!0)).tab(`activity`,`Activity`,M.activity()).aside(`details`,`Details`,M.form(group(`details`,`Details`).field(`description`,{readOnly:!0}).field(`kind`,{readOnly:!0}).field(`retention`,{readOnly:!0}).field(`currentRevision`,{readOnly:!0}).field(`createdBy`,{readOnly:!0}).field(`updatedAt`,{readOnly:!0}))).build()),pt=markSystemView(listView(`artifact-list`,`Artifacts`).for(P).default().tab(`mine`,`My artifacts`,M.collection().object(P).list().icon(`lock`).visibility(`private`).actions().columns(`name`,`kind`,`currentRevision`,`updatedAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`currentRevision`,`updatedAt`).sort(`updatedAt`,`desc`)).tab(`workspace`,`Workspace`,M.collection().object(P).list().icon(`list`).visibility(`workspace`).actions().columns(`name`,`kind`,`currentRevision`,`updatedAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`currentRevision`,`updatedAt`).sort(`updatedAt`,`desc`)).build()),F=`meeting`,I={title:`title`,description:`description`,location:`location`,startsAt:`startsAt`,endsAt:`endsAt`,isAllDay:`isAllDay`,status:`status`,organizerAddress:`organizerAddress`,organizerName:`organizerName`,conferenceProvider:`conferenceProvider`,conferenceJoinUrl:`conferenceJoinUrl`,htmlLink:`htmlLink`,participants:`participants`,providerEventId:`providerEventId`,icalUid:`icalUid`,recurringEventId:`recurringEventId`,connectionId:`connectionId`,recordingOverride:`recordingOverride`,endedAnnouncedAt:`endedAnnouncedAt`,summary:`summary`,transcript:`transcript`,linkedRecords:`linkedRecords`},mt=`meeting-list`,ht=`calendar-sync`,gt=`meeting-detail`,_t=[I.title,I.startsAt,I.endsAt,I.status],vt=nativeObject({name:F,label:`Meeting`}).sealed().hidden().metadata({platformOwned:{editable:[I.linkedRecords],source:ht}}).icon(`calendar`).pluralLabel(`Meetings`).labelExpression(`{{ title }}`).embeddingExpression(`{{ title }}
46
41
  {{ description }}
47
42
  {{ participants }}
48
- {{ summary }}`).attribute(S({name:v.title,label:"Title"}).required()).attribute(je({name:v.description,label:"Description"})).attribute(je({name:v.summary,label:"Summary"}).hidden()).attribute(je({name:v.transcript,label:"Transcript"}).hidden()).attribute(S({name:v.location,label:"Location"})).attribute(se({name:v.startsAt,label:"Starts at"}).includeTime()).attribute(se({name:v.endsAt,label:"Ends at"}).includeTime()).attribute(ba({name:v.isAllDay,label:"All day"})).attribute(be({name:v.status,label:"Status"}).options([{value:"confirmed",label:"Confirmed"},{value:"tentative",label:"Tentative"},{value:"cancelled",label:"Cancelled"}])).attribute(S({name:v.organizerAddress,label:"Organizer address"}).email()).attribute(S({name:v.organizerName,label:"Organizer"})).attribute(S({name:v.conferenceProvider,label:"Conference provider"})).attribute(S({name:v.conferenceJoinUrl,label:"Join link"}).url()).attribute(S({name:v.htmlLink,label:"Open in calendar"}).url()).attribute(S({name:v.participants,label:"Participants"}).multiline()).attribute(S({name:v.providerEventId,label:"Provider event id"}).hidden()).attribute(S({name:v.icalUid,label:"iCal UID"}).hidden()).attribute(S({name:v.recurringEventId,label:"Recurring event id"}).hidden()).attribute(S({name:v.connectionId,label:"Connection id"})).attribute(be({name:v.recordingOverride,label:"Recording"}).options([{value:"force",label:"Force"},{value:"skip",label:"Skip"}]).hidden()).attribute(se({name:v.endedAnnouncedAt,label:"Ended announced at"}).includeTime().hidden()).attribute(ot({name:v.linkedRecords,label:"Linked records"}).toAny().many().qualifyWith(S({name:"source",label:"Source"}).hidden())).build(),Pl=G(ye(Ea,"Meeting").for(lt).default().tab("description","Description",D.richtext(v.description).titleAttribute(v.title)).tab("summary","Summary",D.richtext(v.summary)).tab("transcript","Transcript",D.richtext(v.transcript)).aside("details","Details",D.form(Ae("details","Details").fields(v.startsAt,v.endsAt,v.linkedRecords))).build()),Ml=G(he(Ca,"Meetings").for(lt).default().tab("workspace","Shared",D.collection().object(lt).table().icon("users").visibility("workspace").columns(...Ra).sort(v.startsAt,"desc")).tab("mine","My meetings",D.collection().object(lt).table().icon("lock").visibility("private").columns(...Ra).sort(v.startsAt,"desc")).build());function yi(e,t){return JSON.stringify([e,t])}chunkDPD6ZWL2_js.a(yi,"viewIdentityKey");function mn(e){return structuredClone(e)}chunkDPD6ZWL2_js.a(mn,"cloneDeclaration");var Ai=class Ai{constructor(){this.views=new Map;this.systemNames=new Map;}register(t){let r=(Array.isArray(t)?t:[t]).map((s,c)=>this.prepare(s,c)),o=new Map,a=new Set;for(let{declaration:s}of r){let{object:c,name:u,context:l,default:m}=s.definition,d=o.get(c)??new Set;if((this.views.get(c)?.has(u)||d.has(u))&&this.throwDuplicate(c,u),d.add(u),o.set(c,d),!m)continue;let g=JSON.stringify([c,l]);if(this.getByObjectNameAndContext(c,l).some(y=>y.definition.default)||a.has(g))throw new chunkJSKLP4GI_js.r("default view",g,`[ViewRegistry] Duplicate default view for object "${c}" in context "${l}"`);a.add(g);}for(let s of r)this.commit(s);return this}prepare(t,n){if(typeof t!="object"||t===null||t.kind!=="view"||Object.keys(t).some(o=>o!=="kind"&&o!=="definition")){let o="Expected an exact view declaration";throw new chunkJSKLP4GI_js.h(o,[{path:["views",String(n)],message:o}])}let r=chunkUKFOBZX2_js.$.safeParse(t.definition);if(!r.success)throw chunkJSKLP4GI_js.h.fromZodErrors(r.error.issues.map(o=>({path:["views",String(n),"definition",...o.path.map(String)],message:o.message})));return {declaration:mn(t),system:wa(t.definition)}}commit({declaration:t,system:n}){let{object:r,name:o}=t.definition,a=this.views.get(r)??new Map;if(a.set(o,t),this.views.set(r,a),n){let s=this.systemNames.get(r)??new Set;s.add(o),this.systemNames.set(r,s);}}getByObjectName(t){return Array.from(this.views.get(t)?.values()??[],mn)}getByObjectNameAndContext(t,n){return this.getByObjectName(t).filter(r=>r.definition.context===n)}get(t,n){let r=this.views.get(t)?.get(n);return r&&mn(r)}getOrThrow(t,n){let r=this.get(t,n);if(r)return r;let a=this.getByObjectName(t).map(({definition:s})=>`${s.name} (${s.context})`).join(", ")||"(none)";throw new chunkJSKLP4GI_js.c("View",`${t}:${n}`,void 0,`[ViewRegistry] View "${n}" not found for object "${t}".
49
- Available views: ${a}`)}getAll(){return Array.from(this.views.values()).flatMap(t=>Array.from(t.values(),mn))}has(t,n){return this.views.get(t)?.has(n)??false}hasObject(t){return this.views.has(t)}get size(){let t=0;for(let n of this.views.values())t+=n.size;return t}listObjectNames(){return Array.from(this.views.keys())}getDefault(t,n){let r=this.getByObjectNameAndContext(t,n);return r.find(o=>o.definition.default)??r[0]}isSystem(t,n){return this.systemNames.get(t)?.has(n)??false}isSystemDeclaration(t){return this.isSystem(t.definition.object,t.definition.name)}clear(){this.views.clear(),this.systemNames.clear();}summary(){let t=[`[ViewRegistry] ${this.size} view(s) registered:`];for(let n of this.listObjectNames()){let r=this.getByObjectName(n).map(({definition:o})=>{let a=o.default?" (default)":"";return `${o.name}:${o.context}${a}`});t.push(` ${n}: ${r.join(", ")}`);}return t.join(`
50
- `)}debug(t){let n=this.summary();return t?.(n),n}throwDuplicate(t,n){let r=yi(t,n);throw new chunkJSKLP4GI_js.r("view",r,`[ViewRegistry] Duplicate view: "${n}" for object "${t}"`)}};chunkDPD6ZWL2_js.a(Ai,"ViewRegistry");var hi=Ai,Fl=new hi;function Na(e,t){if(t.suppressed)return null;let n=t.workspaceDefinition??t.sourceDefinition;return n===null?null:{...structuredClone(n),name:e}}chunkDPD6ZWL2_js.a(Na,"contentDefinition");function Et(e){let{name:t,...n}=e;return structuredClone(n)}chunkDPD6ZWL2_js.a(Et,"storedContentDefinition");function Nt(e){let t={main:0,aside:0};return {origin:"runtime",mainOrderCustomized:false,asideOrderCustomized:false,contents:Object.fromEntries(e.map(n=>[n.name,{sourceDefinition:null,workspaceDefinition:Et(n),suppressed:false,sourcePosition:null,workspacePosition:t[n.placement]++}]))}}chunkDPD6ZWL2_js.a(Nt,"workspaceViewAuthoring");function xi(e){let t=Object.entries(e.contents).flatMap(([n,r])=>{let o=Na(n,r);return o?[{definition:o,...r}]:[]});return ["main","aside"].flatMap(n=>{let r=n==="main"?e.mainOrderCustomized:e.asideOrderCustomized;return t.filter(o=>o.definition.placement===n).sort((o,a)=>{let s=r?o.workspacePosition:o.sourcePosition,c=r?a.workspacePosition:a.sourcePosition;if(s!==null&&c!==null&&s!==c)return s-c;if(s!==null&&c===null)return -1;if(c!==null&&s===null)return 1;let u=o.sourcePosition??o.workspacePosition,l=a.sourcePosition??a.workspacePosition;return u!==null&&l!==null&&u!==l?u-l:u!==null&&l===null?-1:l!==null&&u===null?1:o.definition.name.localeCompare(a.definition.name)}).map(o=>o.definition)})}chunkDPD6ZWL2_js.a(xi,"resolveViewContents");function Da(e,t){return e.attributes.find(n=>n.name===t&&n.type==="relation")}chunkDPD6ZWL2_js.a(Da,"findRelationAttribute");function Ti(e,t){return e.targets.some(n=>n.object===t||n.object===ae)}chunkDPD6ZWL2_js.a(Ti,"relationAcceptsObject");function Oa(e,t=[e.name,"targets"]){if(e.targets.length!==1||e.targets[0].object==="*"){let n=`Relation "${e.name}" requires one concrete collection target`;throw new chunkJSKLP4GI_js.h(n,[{path:t,message:n}])}return e.targets[0].object}chunkDPD6ZWL2_js.a(Oa,"requireSingleRelationTarget");function wi(e,t,n,r,o="catalogue"){if(!(e instanceof chunkJSKLP4GI_js.b))throw e;let a=e instanceof chunkJSKLP4GI_js.h?e.errors[0]:void 0;return {key:JSON.stringify([t,n,e.code,e.message]),rule:o,contentName:n,path:a?.path??r,message:e.message,code:e.code,error:e}}chunkDPD6ZWL2_js.a(wi,"violationOf");var Vl=new Map(chunkUKFOBZX2_js.d().map(e=>[e.name,e]));function ue(e,t){throw new chunkJSKLP4GI_js.h(t,[{path:e,message:t}])}chunkDPD6ZWL2_js.a(ue,"reject");function _e(e,t){e.trim().length===0&&ue(t,"API name must not be empty");}chunkDPD6ZWL2_js.a(_e,"requireName");function ja(e,t,n){let r=new Map;return e.forEach((o,a)=>{if(_e(o.name,[...n,String(a),"name"]),r.has(o.name))throw new chunkJSKLP4GI_js.r(t,o.name);r.set(o.name,o);}),r}chunkDPD6ZWL2_js.a(ja,"indexUnique");function re(e,t,n,r,o){if(_e(t,n),!e)return;let a=e.attributes?.get(t)??Vl.get(t);if(!a){if(!e.attributes)return;let s=[...e.attributes.keys()].slice(0,30),c=s.length===0?`Object "${e.name}" has no attributes yet.`:`Attributes of "${e.name}": ${s.join(", ")}`;ue(n,`Unknown attribute "${e.name}.${t}". ${c}${o?.()??""}`);}return r&&a.type!==r&&ue(n,`Attribute "${e.name}.${t}" must have type ${r}`),a}chunkDPD6ZWL2_js.a(re,"requireAttribute");function Si(e){let t=e.mode??"published",n=new Map;e.objects.forEach((b,y)=>{if(_e(b.name,["objects",String(y),"name"]),n.has(b.name))throw new chunkJSKLP4GI_js.r("object",b.name);n.set(b.name,{name:b.name,attributes:ja(b.attributes,"attribute",["objects",String(y),"attributes"])});});let r=new Set;(e.reservedObjects??[]).forEach((b,y)=>{let h=["reservedObjects",String(y)];_e(b,h),!n.has(b)&&(t!=="draft"&&ue(h,`Unresolved reserved object "${b}"`),r.add(b),n.set(b,{name:b}));});let o=ja(e.extensions??[],"extension",["extensions"]);function a(b,y){_e(b,y);let h=n.get(b);return h||ue(y,`Unknown object "${b}"`),h}chunkDPD6ZWL2_js.a(a,"resolveObject");function s(b){let y=[];for(let[h,A]of n)if(h!==b)for(let E of A.attributes?.values()??[])E.type==="relation"&&Ti(E,b)&&y.push(`relatedFrom("${h}", "${E.name}")`);return y.sort().slice(0,3)}chunkDPD6ZWL2_js.a(s,"inverseAddresses");let c=t==="draft"?chunkUKFOBZX2_js.Y({asideRule:"tolerate"}):chunkUKFOBZX2_js.Z({asideRule:"tolerate"}),u=new Map,l=new Map,m=[],d=[];function g(b,y){let h=c.safeParse(b);if(!h.success)throw new chunkJSKLP4GI_js.h("Invalid content view",h.error.issues.map(C=>({path:[...y,...C.path.map(String)],message:C.message,code:C.code})));let A=h.data;_e(A.name,[...y,"name"]);let E=u.get(A.object)??new Set;if(E.has(A.name))throw new chunkJSKLP4GI_js.r("view",`${A.object}.${A.name}`);if(E.add(A.name),u.set(A.object,E),A.default){let C=l.get(A.object)??new Set;if(C.has(A.context))throw new chunkJSKLP4GI_js.r("default view",`${A.object}.${A.context}`);C.add(A.context),l.set(A.object,C);}return A}return chunkDPD6ZWL2_js.a(g,"parseView"),e.views.forEach((b,y)=>{let h=["views",String(y)],A=b,E=`${String(A?.object??"?")}.${String(A?.name??y)}`,C,M;try{C=g(b,h),M=a(C.object,[...h,"object"]);}catch(P){m.push(wi(P,E,null,h));return}for(let P of chunkUKFOBZX2_js.X(C)){let fe=new chunkJSKLP4GI_js.h(P.message,[{path:[...h,...P.path.map(String)],message:P.message}]);m.push(wi(fe,E,P.contentName,h,"aside"));}C.contents.forEach((P,fe)=>{let L=[...h,"contents",String(fe)];try{_e(P.name,[...L,"name"]),Ll(P,L,M,C.context,o,a,s);}catch(k){m.push(wi(k,E,P.name,L));}}),d.push(C);}),{views:d,unresolvedObjects:[...r].sort(),violations:m}}chunkDPD6ZWL2_js.a(Si,"collectContentViewCatalogue");function Bl(e){let t=Si(e).violations.find(n=>n.rule!=="aside");if(t)throw t.error}chunkDPD6ZWL2_js.a(Bl,"validateStoredViews");function Ii(e){let{views:t,unresolvedObjects:n,violations:r}=Si(e),o=r[0];if(o)throw o.error;return {views:t,unresolvedObjects:n}}chunkDPD6ZWL2_js.a(Ii,"validateContentViewCatalogue");function Ll(e,t,n,r,o,a,s){function c(){Rt(e.name,r,t);}if(chunkDPD6ZWL2_js.a(c,"requireRecord"),e.type==="custom"){let u=o.get(e.extension);u||ue([...t,"extension"],`Unknown extension "${e.extension}"`),u.requiresRecord&&c();let l=u.parameters.safeParse(structuredClone(e.parameters??{}));if(!l.success)throw new chunkJSKLP4GI_js.h("Invalid extension parameters",l.error.issues.map(m=>({path:[...t,"parameters",...m.path.map(String)],message:m.message,code:m.code})));return}if(e.type==="collection"){let u=ze(e.source),l,m;if(u.kind==="object")l=a(u.object,[...t,"source","object"]);else if(u.kind==="related"){c();let d=[...t,"source","relation"],g=chunkDPD6ZWL2_js.a(()=>{if(!n)return "";let y=s(n.name);return y.length===0?"":`. Records pointing at "${n.name}" are addressed from the other side: ${y.join(", ")}`},"hint"),b=re(n,u.relation,d,"relation",g);b?.type==="relation"&&(m=b,l=a(Oa(b,d),d));}else {c(),l=a(u.object,[...t,"source","object"]);let d=[...t,"source","relation"],g=re(l,u.relation,d,"relation");if(g?.type==="relation"&&n&&!Ti(g,n.name)){let b=g.targets.map(y=>`"${y.object}"`).join(", ");ue(d,`Relation "${u.object}.${u.relation}" targets ${b}, not "${n.name}"`);}e.filters?.combinator==="or"&&ue([...t,"filters","combinator"],`Collection "${e.name}" addresses "${u.object}" from the far side, so its filters must use the "and" combinator`);}e.columns?.forEach((d,g)=>{let b=[...t,"columns",String(g)];if(typeof d=="string"){re(l,d,b);return}let y=[...b,"relationProperty"];m||ue(y,"Relation property columns require a relation source"),m.properties?.definitions.some(h=>h.name===d.relationProperty)||ue(y,`Unknown relation property "${d.relationProperty}"`);}),e.displayAttributes?.forEach((d,g)=>re(l,d,[...t,"displayAttributes",String(g)])),e.sorts?.forEach((d,g)=>re(l,d.attribute,[...t,"sorts",String(g),"attribute"])),e.filters?.rules.forEach((d,g)=>re(l,d.attribute,[...t,"filters","rules",String(g),"attribute"])),e.descriptionAttribute!==void 0&&re(l,e.descriptionAttribute,[...t,"descriptionAttribute"]),e.layout==="kanban"&&e.groupByAttribute!==void 0&&re(l,e.groupByAttribute,[...t,"groupByAttribute"]);return}switch(c(),e.type){case "form":e.groups.forEach((u,l)=>{let m=[...t,"groups",String(l)];_e(u.name,[...m,"name"]),u.fields.forEach((d,g)=>re(n,d.attribute,[...m,"fields",String(g),"attribute"]));});break;case "richtext":re(n,e.attribute,[...t,"attribute"],"richtext"),e.titleAttribute!==void 0&&re(n,e.titleAttribute,[...t,"titleAttribute"],"text");break;case "emails":case "meetings":e.emailAttributes.forEach((u,l)=>re(n,u,[...t,"emailAttributes",String(l)],"text"));break;case "documents":e.relations?.forEach((u,l)=>re(n,u,[...t,"relations",String(l)],"relation"));break;case "forms":e.objectName!==void 0&&a(e.objectName,[...t,"objectName"]);break;case "activity":break;default:ue(t,`Unknown content type: ${String(e)}`);}}chunkDPD6ZWL2_js.a(Ll,"validateContent");var $l=[Object.freeze(pn)],Ci=class Ci{constructor(){this.extensions=new Map;this.seed();}register(t){let n=Array.isArray(t)?t:[t],r=new Set;n.forEach((o,a)=>{if(this.prepare(o,a),r.has(o.name))throw new chunkJSKLP4GI_js.r("content extension",o.name);r.add(o.name);});for(let o of n)this.extensions.set(o.name,o);return this}prepare(t,n){let r=["extensions",String(n)],o=chunkDPD6ZWL2_js.a(a=>{throw new chunkJSKLP4GI_js.h(a,[{path:r,message:a}])},"reject");if((typeof t!="object"||t===null||Array.isArray(t))&&o("Expected a content extension declaration"),Object.keys(t).some(a=>a!=="name"&&a!=="parameters"&&a!=="requiresRecord")&&o("Expected exactly name, parameters and requiresRecord"),(typeof t.name!="string"||t.name.trim().length===0)&&o("API name must not be empty"),typeof t.requiresRecord!="boolean"&&o("requiresRecord must be a boolean"),typeof t.parameters?.safeParse!="function"&&o("parameters must be a Zod schema"),this.extensions.has(t.name))throw new chunkJSKLP4GI_js.r("content extension",t.name)}get(t){return this.extensions.get(t)}has(t){return this.extensions.has(t)}getAll(){return [...this.extensions.values()]}get size(){return this.extensions.size}clear(){this.extensions.clear(),this.seed();}seed(){for(let t of $l)this.extensions.set(t.name,t);}};chunkDPD6ZWL2_js.a(Ci,"ContentExtensionRegistry");var Ri=Ci,Ul=new Ri;function vi(e){return structuredClone(e)}chunkDPD6ZWL2_js.a(vi,"cloneFormDefinition");var Ei=class Ei{constructor(){this.forms=new Map;}register(t){let n=Array.isArray(t)?t:[t];for(let r of n){if(this.forms.has(r.name))throw new chunkJSKLP4GI_js.r("form",r.name,`[FormRegistry] Duplicate form: "${r.name}"`);this.forms.set(r.name,vi(r));}return this}get(t){let n=this.forms.get(t);return n?vi(n):void 0}getAll(){return Array.from(this.forms.values(),vi)}listNames(){return Array.from(this.forms.keys())}};chunkDPD6ZWL2_js.a(Ei,"FormRegistry");var Dt=Ei;var ka=new Dt;function AS(e,t){return `${e}:${t}`}chunkDPD6ZWL2_js.a(AS,"formatAgentStreamFrameId");function xS(e){let t=e.lastIndexOf(":");if(t<=0)return null;let n=e.slice(0,t),r=Number(e.slice(t+1));return !Number.isInteger(r)||r<=0?null:{streamId:n,sequence:r}}chunkDPD6ZWL2_js.a(xS,"parseAgentStreamFrameId");var SS=204800,IS=256;function Di(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}chunkDPD6ZWL2_js.a(Di,"isRecord");function Oi(e,t){let n=Object.keys(e);return n.length===t.length&&n.every(r=>t.includes(r))}chunkDPD6ZWL2_js.a(Oi,"hasExactKeys");function Ni(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}chunkDPD6ZWL2_js.a(Ni,"isPositiveInteger");function _a(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}chunkDPD6ZWL2_js.a(_a,"isNonNegativeInteger");function ql(e){return Di(e)&&Oi(e,["kind","startOffset","endOffset"])?(e.kind==="text"||e.kind==="reasoning")&&_a(e.startOffset)&&_a(e.endOffset)&&e.endOffset>=e.startOffset:false}chunkDPD6ZWL2_js.a(ql,"isContentRange");function zl(e){if(!Di(e))return false;let t=e.content===void 0?["sequence","chunk"]:["sequence","content","chunk"];return Oi(e,t)&&Ni(e.sequence)&&e.chunk!==void 0&&(e.content===void 0||ql(e.content))}chunkDPD6ZWL2_js.a(zl,"isBatchItem");function Wl(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return}}chunkDPD6ZWL2_js.a(Wl,"encodedSize");function RS(e){if(!(Di(e)&&Oi(e,["schemaVersion","batchId","tenantId","sessionId","streamId","sequenceStart","sequenceEnd","items"]))||e.schemaVersion!==1||typeof e.batchId!="string"||e.batchId.trim()===""||typeof e.tenantId!="string"||e.tenantId.trim()===""||typeof e.sessionId!="string"||e.sessionId.trim()===""||typeof e.streamId!="string"||e.streamId.trim()===""||!Ni(e.sequenceStart)||!Ni(e.sequenceEnd)||!Array.isArray(e.items)||e.items.length===0||e.items.length>256||!e.items.every(zl))return false;let t=0;for(let r of e.items){if(r.sequence<=t)return false;t=r.sequence;}if(e.items[0]?.sequence!==e.sequenceStart||e.items.at(-1)?.sequence!==e.sequenceEnd)return false;let n=Wl(e);return n!==void 0&&n<=204800}chunkDPD6ZWL2_js.a(RS,"isAgentUIMessageBatch");function Pa(e){switch(e.kind){case "workspace":return `workspace:${encodeURIComponent(e.tenantId)}`;case "object":return `object:${encodeURIComponent(e.objectId)}`;case "record":return `record:${encodeURIComponent(e.objectId)}:${encodeURIComponent(e.recordId)}`;case "view":return `view:${encodeURIComponent(e.viewId)}`;case "user":return `user:${encodeURIComponent(e.actorId)}`;case "conversation":return `conversation:${encodeURIComponent(e.sessionId)}`;case "architect-draft":return e.scope==="actor"?`architect-draft:actor:${encodeURIComponent(e.actorId)}`:`architect-draft:session:${encodeURIComponent(e.sessionId)}`}}chunkDPD6ZWL2_js.a(Pa,"liveChannelKey");function ES(e){return e.sessionId?Pa({kind:"architect-draft",scope:"session",sessionId:e.sessionId}):e.actorId?Pa({kind:"architect-draft",scope:"actor",actorId:e.actorId}):null}chunkDPD6ZWL2_js.a(ES,"architectDraftChannelKey");function Pe(e){try{return decodeURIComponent(e)}catch{return null}}chunkDPD6ZWL2_js.a(Pe,"decodeLiveChannelPart");function Ma(e){let t=e.split(":");if(t[0]==="workspace"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"workspace",tenantId:n}:null}if(t[0]==="object"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"object",objectId:n}:null}if(t[0]==="record"&&t.length===3&&t[1]&&t[2]){let n=Pe(t[1]),r=Pe(t[2]);return n&&r?{kind:"record",objectId:n,recordId:r}:null}if(t[0]==="view"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"view",viewId:n}:null}if(t[0]==="user"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"user",actorId:n}:null}if(t[0]==="architect-draft"&&t.length===3&&t[2]){let n=Pe(t[2]);return n?t[1]==="actor"?{kind:"architect-draft",scope:"actor",actorId:n}:t[1]==="session"?{kind:"architect-draft",scope:"session",sessionId:n}:null:null}if(t[0]==="conversation"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"conversation",sessionId:n}:null}return null}chunkDPD6ZWL2_js.a(Ma,"parseLiveChannelKey");var Gl={"record.patch":true,"record.deleted":true,"record.removed":true,"record.created":true,"view.projection.stale":true,"agent.session.patch":true,"notification.created":true,"notification.recipient.patch":true,"notification.count.patch":true,"notification.inbox.archived":true,"reflex.state.changed":true,"reflex.run.completed":true,"reflex.authoring.progress":true,"architect.draft.updated":true,"meeting.recording.patch":true,"wallet.state":true,"channel.revoked":true},Kl=Object.keys(Gl),Yl=["membership-unknown","sort-unknown","permissions-changed"],Hl=["permission-revoked","workspace-left","object-deleted"],Jl=["inboxState","workState","lockedAt","lockedByActorId","readAt","archivedAt","snoozedUntil","completedAt","dismissedAt","updatedAt"],Ql=["type","objectId","recordId","recordVersion"],Zl=["type","objectId","recordId","recordVersion","record"],Xl=["id","objectId","visibility","ownedBy","label","values","metadata","createdAt","updatedAt","createdBy","lastUpdatedBy","schemaVersion"],ed=["type","targetActorId","archivedCount","version","updatedAt"];function td(e){return typeof e=="string"&&Kl.includes(e)}chunkDPD6ZWL2_js.a(td,"isLiveEventType");function jS(e){return q(e)&&td(e.type)?nd(e.type,e):false}chunkDPD6ZWL2_js.a(jS,"isLiveEventPayload");function nd(e,t){if(!q(t))return false;switch(e){case "record.patch":return ud(t);case "record.deleted":return ld(t);case "record.removed":return dd(t);case "record.created":return md(t);case "view.projection.stale":return fd(t);case "agent.session.patch":return bd(t);case "notification.created":return Ad(t);case "notification.recipient.patch":return xd(t);case "notification.count.patch":return Td(t);case "notification.inbox.archived":return wd(t);case "reflex.state.changed":return Ed(t);case "reflex.run.completed":return Nd(t);case "reflex.authoring.progress":return Dd(t);case "architect.draft.updated":return Cd(t);case "meeting.recording.patch":return jd(t);case "wallet.state":return Pd(t);case "channel.revoked":return Md(t);default:return false}}chunkDPD6ZWL2_js.a(nd,"isLiveEventPayloadForType");function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}chunkDPD6ZWL2_js.a(q,"isRecord");function J(e){return typeof e=="string"}chunkDPD6ZWL2_js.a(J,"isString");function Ot(e){return J(e)&&e.length>0}chunkDPD6ZWL2_js.a(Ot,"isNonEmptyString");function ji(e){return e===null||J(e)}chunkDPD6ZWL2_js.a(ji,"isNullableString");function rd(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}chunkDPD6ZWL2_js.a(rd,"isVersion");function Te(e){if(!J(e))return false;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}chunkDPD6ZWL2_js.a(Te,"isIsoDateString");function dt(e){return e===null||Te(e)}chunkDPD6ZWL2_js.a(dt,"isNullableIsoDateString");function j(e,t){return J(e[t])}chunkDPD6ZWL2_js.a(j,"hasString");function le(e,t){return Ot(e[t])}chunkDPD6ZWL2_js.a(le,"hasNonEmptyString");function z(e,t){return rd(e[t])}chunkDPD6ZWL2_js.a(z,"hasVersion");function K(e,t){return Te(e[t])}chunkDPD6ZWL2_js.a(K,"hasIsoDateString");function O(e,t,n){return !Object.hasOwn(e,t)||n(e[t])}chunkDPD6ZWL2_js.a(O,"hasOptional");function fn(e,t){return Object.keys(e).every(n=>t.includes(n))}chunkDPD6ZWL2_js.a(fn,"hasOnlyKeys");function Q(e,t){return typeof e=="string"&&t.includes(e)}chunkDPD6ZWL2_js.a(Q,"isOneOf");function id(e){return Q(e,Bo)}chunkDPD6ZWL2_js.a(id,"isNotificationKind");function od(e){return Q(e,Lo)}chunkDPD6ZWL2_js.a(od,"isNotificationPriority");function ad(e){return Q(e,$o)}chunkDPD6ZWL2_js.a(ad,"isNotificationSensitivity");function Fa(e){return Q(e,Uo)}chunkDPD6ZWL2_js.a(Fa,"isNotificationInboxState");function Va(e){return Q(e,qo)}chunkDPD6ZWL2_js.a(Va,"isNotificationWorkState");function sd(e){return q(e)&&j(e,"type")&&j(e,"id")}chunkDPD6ZWL2_js.a(sd,"isNotificationSubject");function cd(e){return q(e)&&j(e,"fieldKey")&&Object.hasOwn(e,"value")&&z(e,"version")}chunkDPD6ZWL2_js.a(cd,"isRecordFieldPatch");function ud(e){return e.type==="record.patch"&&j(e,"objectId")&&j(e,"recordId")&&z(e,"recordVersion")&&O(e,"label",J)&&O(e,"metadata",q)&&O(e,"fieldsWithheld",t=>t===true)&&Array.isArray(e.fieldPatches)&&e.fieldPatches.every(cd)&&j(e,"updatedAt")}chunkDPD6ZWL2_js.a(ud,"isRecordPatchPayload");function ld(e){return e.type==="record.deleted"&&j(e,"objectId")&&j(e,"recordId")&&z(e,"recordVersion")&&j(e,"deletedAt")}chunkDPD6ZWL2_js.a(ld,"isRecordDeletedPayload");function dd(e){return e.type==="record.removed"&&fn(e,Ql)&&j(e,"objectId")&&j(e,"recordId")&&z(e,"recordVersion")}chunkDPD6ZWL2_js.a(dd,"isRecordRemovedPayload");function pd(e){return q(e)&&fn(e,Xl)&&j(e,"id")&&j(e,"objectId")&&Q(e.visibility,["workspace","private"])&&ji(e.ownedBy)&&(e.visibility==="workspace"&&e.ownedBy===null||e.visibility==="private"&&Ot(e.ownedBy))&&j(e,"label")&&q(e.values)&&O(e,"metadata",q)&&K(e,"createdAt")&&K(e,"updatedAt")&&O(e,"createdBy",J)&&O(e,"lastUpdatedBy",J)&&z(e,"schemaVersion")}chunkDPD6ZWL2_js.a(pd,"isRecordLiveSnapshot");function md(e){return e.type==="record.created"&&fn(e,Zl)&&j(e,"objectId")&&j(e,"recordId")&&z(e,"recordVersion")&&pd(e.record)&&e.record.id===e.recordId&&e.record.objectId===e.objectId}chunkDPD6ZWL2_js.a(md,"isRecordCreatedPayload");function fd(e){return e.type==="view.projection.stale"&&j(e,"viewId")&&Q(e.reason,Yl)}chunkDPD6ZWL2_js.a(fd,"isViewProjectionStalePayload");function bd(e){return e.type==="agent.session.patch"&&j(e,"sessionId")&&q(e.patch)&&z(e,"version")&&j(e,"updatedAt")}chunkDPD6ZWL2_js.a(bd,"isAgentSessionPatchPayload");function gd(e){return q(e)&&j(e,"id")&&j(e,"tenantId")&&O(e,"senderActorId",J)&&O(e,"rootActorId",J)&&O(e,"triggeredByActorId",J)&&id(e.kind)&&j(e,"type")&&O(e,"subject",sd)&&j(e,"title")&&O(e,"summary",J)&&q(e.payload)&&od(e.priority)&&ad(e.sensitivity)&&O(e,"threadKey",J)&&O(e,"idempotencyKey",J)&&O(e,"expiresAt",Te)&&K(e,"createdAt")&&K(e,"updatedAt")}chunkDPD6ZWL2_js.a(gd,"isLiveNotification");function yd(e){return q(e)&&j(e,"id")&&j(e,"tenantId")&&j(e,"notificationId")&&j(e,"recipientActorId")&&Fa(e.inboxState)&&Va(e.workState)&&O(e,"lockedAt",Te)&&O(e,"lockedByActorId",J)&&O(e,"readAt",Te)&&O(e,"archivedAt",Te)&&O(e,"snoozedUntil",Te)&&O(e,"completedAt",Te)&&O(e,"dismissedAt",Te)&&K(e,"createdAt")&&K(e,"updatedAt")}chunkDPD6ZWL2_js.a(yd,"isLiveNotificationRecipient");function hd(e){return q(e)?Object.keys(e).every(t=>Jl.includes(t))&&O(e,"inboxState",Fa)&&O(e,"workState",Va)&&O(e,"lockedAt",dt)&&O(e,"lockedByActorId",ji)&&O(e,"readAt",dt)&&O(e,"archivedAt",dt)&&O(e,"snoozedUntil",dt)&&O(e,"completedAt",dt)&&O(e,"dismissedAt",dt)&&O(e,"updatedAt",Te):false}chunkDPD6ZWL2_js.a(hd,"isNotificationRecipientPatch");function Ad(e){let t=gd(e.notification)?e.notification:null;return e.type==="notification.created"&&t!==null&&Array.isArray(e.recipients)&&e.recipients.length>0&&e.recipients.every(n=>yd(n)&&n.notificationId===t.id)&&z(e,"version")&&K(e,"updatedAt")}chunkDPD6ZWL2_js.a(Ad,"isNotificationCreatedPayload");function xd(e){return e.type==="notification.recipient.patch"&&j(e,"recipientId")&&j(e,"recipientActorId")&&hd(e.patch)&&z(e,"version")&&K(e,"updatedAt")}chunkDPD6ZWL2_js.a(xd,"isNotificationRecipientPatchPayload");function Td(e){return e.type==="notification.count.patch"&&j(e,"targetActorId")&&z(e,"unread")&&z(e,"pendingWork")&&z(e,"version")&&K(e,"updatedAt")}chunkDPD6ZWL2_js.a(Td,"isNotificationCountPatchPayload");function wd(e){return e.type==="notification.inbox.archived"&&fn(e,ed)&&le(e,"targetActorId")&&z(e,"archivedCount")&&z(e,"version")&&K(e,"updatedAt")}chunkDPD6ZWL2_js.a(wd,"isNotificationInboxArchivedPayload");var Sd=["armed","disarmed"],Id=["authoring","compiling","replaying","promoted","failed"],Rd=["promoted","lkg"];function Cd(e){if(e.type!=="architect.draft.updated"||!q(e.receipt))return false;let t=e.receipt;return Array.isArray(t.operationIds)&&t.operationIds.every(Ot)&&q(t.revision)&&le(t.revision,"draftId")&&z(t.revision,"version")&&Array.isArray(t.changedTargets)&&t.changedTargets.every(n=>q(n)&&Ot(n.token)&&vd(n.target))}chunkDPD6ZWL2_js.a(Cd,"isArchitectDraftUpdatedPayload");function vd(e){if(!q(e))return false;let t=Object.keys(e);return t.every(n=>Ot(e[n]))?le(e,"viewName")?le(e,"objectName")&&t.every(n=>["objectName","viewName","contentName"].includes(n)):le(e,"objectName")?t.length===1:le(e,"objectId")&&t.length<=2&&t.every(n=>["objectId","attributeName","attributeId","recordId"].includes(n)):false}chunkDPD6ZWL2_js.a(vd,"isNamedTarget");function Ed(e){return e.type==="reflex.state.changed"&&le(e,"reflexId")&&Q(e.state,Sd)&&K(e,"updatedAt")}chunkDPD6ZWL2_js.a(Ed,"isReflexStateChangedPayload");function Nd(e){return e.type==="reflex.run.completed"&&le(e,"reflexId")&&le(e,"runId")&&Q(e.served,Rd)&&z(e,"version")&&z(e,"wallMs")&&K(e,"completedAt")}chunkDPD6ZWL2_js.a(Nd,"isReflexRunCompletedPayload");function Dd(e){return e.type==="reflex.authoring.progress"&&le(e,"reflexId")&&Q(e.status,Id)&&K(e,"updatedAt")}chunkDPD6ZWL2_js.a(Dd,"isReflexAuthoringProgressPayload");var Od=["none","scheduled","recording","completed","failed"];function jd(e){return e.type==="meeting.recording.patch"&&le(e,"meetingId")&&Q(e.status,Od)&&ji(e.failureReason)&&K(e,"updatedAt")}chunkDPD6ZWL2_js.a(jd,"isMeetingRecordingPatchPayload");var kd=["ok","low","exhausted","paused"],_d=["metering-only","contract","wallet"];function Pd(e){return e.type==="wallet.state"&&Q(e.status,kd)&&Q(e.mode,_d)&&K(e,"updatedAt")}chunkDPD6ZWL2_js.a(Pd,"isWalletStatePayload");function Md(e){return e.type==="channel.revoked"&&j(e,"channel")&&Q(e.reason,Hl)}chunkDPD6ZWL2_js.a(Md,"isChannelRevokedPayload");function ki(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}chunkDPD6ZWL2_js.a(ki,"isRecord");function Fd(e){let{channel:t}=e;return typeof t=="string"&&Ma(t)?t:null}chunkDPD6ZWL2_js.a(Fd,"payloadChannel");function MS(e){return ki(e)?Fd(e):null}chunkDPD6ZWL2_js.a(MS,"getLiveProtocolPayloadChannel");function FS(e){return ki(e)?typeof e.id=="string"&&e.id.length>0&&typeof e.channel=="string"&&typeof e.type=="string"&&typeof e.tenantId=="string"&&e.tenantId.length>0&&typeof e.occurredAt=="string"&&ki(e.payload):false}chunkDPD6ZWL2_js.a(FS,"isLiveEventEnvelope");var LS=["if","concat","sum","avg","count","min","max","earliest","latest","unique","first","percent_empty","percent_not_empty","count_empty","count_not_empty","count_unique"],jt={if:{name:"if",returnType:"branch",minArgs:3,maxArgs:3},concat:{name:"concat",returnType:{kind:"scalar",type:"text"},minArgs:1},sum:{name:"sum",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},avg:{name:"avg",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count:{name:"count",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},min:{name:"min",returnType:"source_item",minArgs:1,maxArgs:1},max:{name:"max",returnType:"source_item",minArgs:1,maxArgs:1},earliest:{name:"earliest",returnType:{kind:"scalar",type:"date"},minArgs:1,maxArgs:1},latest:{name:"latest",returnType:{kind:"scalar",type:"date"},minArgs:1,maxArgs:1},unique:{name:"unique",returnType:"argument",minArgs:1,maxArgs:1},first:{name:"first",returnType:"source_item",minArgs:1,maxArgs:1},percent_empty:{name:"percent_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},percent_not_empty:{name:"percent_not_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_empty:{name:"count_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_not_empty:{name:"count_not_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_unique:{name:"count_unique",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1}};function bn(e){return Object.hasOwn(jt,e)}chunkDPD6ZWL2_js.a(bn,"isComputedFunctionName");var Fi=class Fi extends Error{constructor(t){super(t),this.name="ComputedFormulaCompileError";}};chunkDPD6ZWL2_js.a(Fi,"ComputedFormulaCompileError");var I=Fi;function yn(e){let t=Vd(e.expression),n=gn(t,e.schema),r=ap(n.valueType);if(r!==e.returnType)throw new I(`Computed formula "${e.attributeName}" returns "${r}", expected "${e.returnType}"`);if(Wa(e.returnType)&&n.optionsSource===void 0)throw new I(`Computed formula "${e.attributeName}" returns "${e.returnType}" without optionsSource`);let o=n.optionsSource===void 0?[]:[{kind:"options",source:n.optionsSource}],a=Mi([...n.dependencies,...o]);return {kind:"formula",attributeName:e.attributeName,expression:e.expression,returnType:e.returnType,valueType:n.valueType,dependencies:a,ast:t,...n.optionsSource?{optionsSource:n.optionsSource}:{},...n.targetAttributeType?{targetAttributeType:n.targetAttributeType}:{},dependenciesHash:sp({expression:e.expression,returnType:e.returnType,dependencies:a})}}chunkDPD6ZWL2_js.a(yn,"compileComputedFormula");function za(e){let t=new Map(e.map(o=>[o.attributeName,o])),n=new Set,r=chunkDPD6ZWL2_js.a((o,a)=>{let s=a.indexOf(o);if(s!==-1){let l=[...a.slice(s),o];throw new I(`Computed field cycle detected: ${l.join(" -> ")}`)}if(n.has(o))return;let c=t.get(o);if(c===void 0)return;let u=[...a,o];for(let l of c.dependencies)l.kind==="computed"&&r(l.attributeName,u);n.add(o);},"visit");for(let o of e)r(o.attributeName,[]);}chunkDPD6ZWL2_js.a(za,"assertAcyclicComputedDependencies");function Vd(e){try{return chunk2M4YXNYZ_js.v(e)}catch(t){throw t instanceof Error?new I(t.message):t}}chunkDPD6ZWL2_js.a(Vd,"parseCompileFormula");function gn(e,t){switch(e.kind){case "literal":return {valueType:Bd(e.value),dependencies:[],...typeof e.value=="string"?{literalString:e.value}:{}};case "path":return Ld(e.parts,t);case "call":return Gd(e.functionName,e.args,t);case "binary":return Qd(e.operator,gn(e.left,t),gn(e.right,t));default:return e}}chunkDPD6ZWL2_js.a(gn,"inferNode");function Bd(e){switch(typeof e){case "string":return {kind:"scalar",type:"text"};case "number":return {kind:"scalar",type:"number"};case "boolean":return {kind:"scalar",type:"boolean"};case "object":return {kind:"scalar",type:"text"};default:return e}}chunkDPD6ZWL2_js.a(Bd,"literalToValueType");function Ld(e,t){if(e.length===1){let n=e[0],r=_i(t,n);if(r===void 0)throw new I(`Unknown attribute "${n}" on object "${t.objectName}"`);return r.type==="relation"?{valueType:qd(),dependencies:[{kind:"relation",relationName:r.name,cardinality:Ba(r)}],targetAttributeType:r.type}:{valueType:La(r),dependencies:[Ud(r)],optionsSource:$a(t.objectName,r),targetAttributeType:r.type}}if(e.length===2){let[n,r]=e,o=_i(t,n);if(o===void 0)throw new I(`Unknown attribute "${n}" on object "${t.objectName}"`);if(o.type!=="relation")throw new I(`Attribute "${n}" on object "${t.objectName}" is not a relation`);let a=$d(o);if(a===void 0)throw new I(`Relation "${n}" on object "${t.objectName}" is missing targetObjectName`);let s=t.relatedObjects?.[a];if(s===void 0)throw new I(`Unknown related object "${a}"`);let c=_i(s,r);if(c===void 0)throw new I(`Unknown attribute "${r}" on object "${s.objectName}"`);let u=La(c);return {valueType:o.cardinality==="many"?Wd(u):u,dependencies:[{kind:"relation",relationName:n,targetAttributeName:r,cardinality:Ba(o)}],optionsSource:$a(s.objectName,c),targetAttributeType:c.type}}throw new I("Computed paths support at most one relation hop")}chunkDPD6ZWL2_js.a(Ld,"inferPath");function _i(e,t){return e.attributes.find(n=>n.name===t)}chunkDPD6ZWL2_js.a(_i,"findAttribute");function $d(e){if(e.targetObjectName!==void 0)return e.targetObjectName;if(e.targets?.length===1){let[t]=e.targets;return t?.object==="*"?void 0:t?.object}}chunkDPD6ZWL2_js.a($d,"getRelationTargetObjectName");function Ba(e){return e.cardinality??"one"}chunkDPD6ZWL2_js.a(Ba,"relationCardinality");function Ud(e){return e.type==="formula"||e.type==="rollup"?{kind:"computed",attributeName:e.name}:{kind:"local",attributeName:e.name}}chunkDPD6ZWL2_js.a(Ud,"localDependencyFor");function La(e){if(e.type==="formula"||e.type==="rollup"){if(e.returnType===void 0)throw new I(`Computed attribute "${e.name}" is missing returnType`);return zd(e.returnType)}switch(e.type){case "number":case "currency":return {kind:"scalar",type:"number"};case "checkbox":return {kind:"scalar",type:"boolean"};case "date":return {kind:"scalar",type:"date"};case "select":case "status":return {kind:"scalar",type:"select"};case "multiselect":return {kind:"collection",itemType:"select"};case "text":case "richtext":case "phone":case "user":case "location":case "relation":case "document":return {kind:"scalar",type:"text"};default:return e.type}}chunkDPD6ZWL2_js.a(La,"attributeToValueType");function qd(){return {kind:"collection",itemType:"text"}}chunkDPD6ZWL2_js.a(qd,"relationToValueType");function zd(e){return e==="multiselect"?{kind:"collection",itemType:"select"}:{kind:"scalar",type:e}}chunkDPD6ZWL2_js.a(zd,"returnTypeToValueType");function Wd(e){return e.kind==="collection"?e:{kind:"collection",itemType:e.type}}chunkDPD6ZWL2_js.a(Wd,"asCollectionValueType");function $a(e,t){if(t.type==="formula"||t.type==="rollup")return Wa(t.returnType)?t.optionsSource:void 0;if(!(t.type!=="select"&&t.type!=="status"&&t.type!=="multiselect"))return t.optionsSource??{objectName:e,attributeName:t.name,...t.id?{attributeId:t.id}:{}}}chunkDPD6ZWL2_js.a($a,"optionsSourceForAttribute");function Gd(e,t,n){if(!bn(e))throw new I(`Unknown computed function "${e}"`);let r=jt[e];if(t.length<r.minArgs||r.maxArgs!==void 0&&t.length>r.maxArgs){let a=r.maxArgs===void 0||r.maxArgs===r.minArgs?String(r.minArgs):`${r.minArgs}-${r.maxArgs}`;throw new I(`Function "${e}" expects ${a} arguments, received ${t.length}`)}let o=t.map(a=>gn(a,n));return Kd(e,o)}chunkDPD6ZWL2_js.a(Gd,"inferCall");function Kd(e,t){let n=Mi(t.flatMap(r=>r.dependencies));switch(e){case "if":return Yd(t,n);case "concat":return Zd(t,`Function "${e}" does not accept collection values`),{valueType:{kind:"scalar",type:"text"},dependencies:n};case "sum":case "avg":return Ua(e,t[0],"number"),{valueType:{kind:"scalar",type:"number"},dependencies:n};case "count":case "count_empty":case "count_not_empty":case "count_unique":case "percent_empty":case "percent_not_empty":return ep(e,t[0]),{valueType:{kind:"scalar",type:"number"},dependencies:n};case "min":case "max":return Xd(e,t[0]),{valueType:tp(t[0]),dependencies:n,optionsSource:t[0].optionsSource,targetAttributeType:t[0].targetAttributeType};case "earliest":case "latest":return Ua(e,t[0],"date"),{valueType:{kind:"scalar",type:"date"},dependencies:n,targetAttributeType:t[0].targetAttributeType};case "unique":return Hd(t[0],n);case "first":return Jd(t[0],n);default:return e}}chunkDPD6ZWL2_js.a(Kd,"inferFunctionReturn");function Yd(e,t){Pi(e[0].valueType,"boolean",'Function "if" condition must be boolean');let n=e[1],r=e[2],o=rp(n,r),a=ip(n,r);if(o===void 0)throw new I('Function "if" branches must return the same type');return {valueType:o,dependencies:t,...a?{optionsSource:a}:{},targetAttributeType:n.targetAttributeType??r.targetAttributeType}}chunkDPD6ZWL2_js.a(Yd,"inferIfFunction");function Hd(e,t){if(e.valueType.kind!=="collection"||e.valueType.itemType!=="select")throw new I('Function "unique" expects a select collection');return {valueType:{kind:"collection",itemType:"select"},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}chunkDPD6ZWL2_js.a(Hd,"inferUniqueFunction");function Jd(e,t){if(e.valueType.kind!=="collection")throw new I('Function "first" expects a collection');return {valueType:{kind:"scalar",type:e.valueType.itemType},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}chunkDPD6ZWL2_js.a(Jd,"inferFirstFunction");function Qd(e,t,n){let r=Mi([...t.dependencies,...n.dependencies]),o=e==="+"||e==="-"||e==="*"||e==="/";if(t.valueType.kind==="collection"||n.valueType.kind==="collection")throw new I(`Cannot use collection values with ${o?"arithmetic":"comparison"} operator "${e}"`);if(o)return e==="+"&&(t.valueType.type==="text"||n.valueType.type==="text")?{valueType:{kind:"scalar",type:"text"},dependencies:r}:(Pi(t.valueType,"number",`Operator "${e}" expects number operands`),Pi(n.valueType,"number",`Operator "${e}" expects number operands`),{valueType:{kind:"scalar",type:"number"},dependencies:r});if(e==="=="||e==="!="){if(t.valueType.type!==n.valueType.type)throw new I(`Operator "${e}" expects operands with the same scalar type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:r}}if((t.valueType.type!=="number"||n.valueType.type!=="number")&&(t.valueType.type!=="date"||n.valueType.type!=="date"))throw new I(`Operator "${e}" expects number or date operands of the same type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:r}}chunkDPD6ZWL2_js.a(Qd,"inferBinary");function Zd(e,t){for(let n of e)if(n.valueType.kind==="collection")throw new I(t)}chunkDPD6ZWL2_js.a(Zd,"ensureNoCollections");function Ua(e,t,n){if((t.valueType.kind==="collection"?t.valueType.itemType:t.valueType.type)!==n)throw new I(`Function "${e}" expects ${n} values`)}chunkDPD6ZWL2_js.a(Ua,"ensureCollectionOrScalarType");function Xd(e,t){if(t.valueType.kind!=="collection")throw new I(`Function "${e}" expects a collection`);let n=t.valueType.itemType;if(n!=="number"&&n!=="date")throw new I(`Function "${e}" expects number or date values`)}chunkDPD6ZWL2_js.a(Xd,"ensureMinMaxSource");function ep(e,t){if(t.valueType.kind!=="collection")throw new I(`Function "${e}" expects a collection`)}chunkDPD6ZWL2_js.a(ep,"ensureCollectionSource");function Pi(e,t,n){if(e.kind!=="scalar"||e.type!==t)throw new I(n)}chunkDPD6ZWL2_js.a(Pi,"ensureScalarType");function tp(e){return e.valueType.kind==="scalar"?e.valueType:{kind:"scalar",type:e.valueType.itemType}}chunkDPD6ZWL2_js.a(tp,"sourceItemValueType");function np(e,t){return e.kind==="scalar"?t.kind==="scalar"&&e.type===t.type:t.kind==="collection"&&e.itemType===t.itemType}chunkDPD6ZWL2_js.a(np,"sameValueType");function rp(e,t){if(np(e.valueType,t.valueType)||qa(e,t))return e.valueType;if(qa(t,e))return t.valueType}chunkDPD6ZWL2_js.a(rp,"resolveIfBranchValueType");function qa(e,t){return e.valueType.kind==="scalar"&&e.valueType.type==="select"&&t.valueType.kind==="scalar"&&t.valueType.type==="text"&&t.literalString!==void 0}chunkDPD6ZWL2_js.a(qa,"isSelectScalarWithStringLiteral");function ip(e,t){let n=e.optionsSource,r=t.optionsSource;if(n!==void 0&&r!==void 0&&!op(n,r))throw new I('Function "if" branches use incompatible options sources');return n??r}chunkDPD6ZWL2_js.a(ip,"resolveIfOptionsSource");function op(e,t){return e.objectName===t.objectName&&e.attributeName===t.attributeName&&e.attributeId===t.attributeId}chunkDPD6ZWL2_js.a(op,"sameOptionsSource");function Wa(e){return e==="select"||e==="multiselect"}chunkDPD6ZWL2_js.a(Wa,"isSelectLikeReturnType");function ap(e){if(e.kind==="scalar")return e.type;if(e.itemType==="select")return "multiselect";throw new I(`Collection item type "${e.itemType}" cannot be used as a computed return type`)}chunkDPD6ZWL2_js.a(ap,"valueTypeToReturnType");function Mi(e){let t=new Set,n=[];for(let r of e){let o=JSON.stringify(kt(r));t.has(o)||(t.add(o),n.push(r));}return n}chunkDPD6ZWL2_js.a(Mi,"uniqueDependencies");function sp(e){let t=e.dependencies.map(n=>kt(n)).sort((n,r)=>Ga(JSON.stringify(n),JSON.stringify(r)));return JSON.stringify(kt({expression:e.expression,returnType:e.returnType,dependencies:t}))}chunkDPD6ZWL2_js.a(sp,"createDependenciesHash");function kt(e){return Array.isArray(e)?e.map(t=>kt(t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>Ga(t,n)).map(([t,n])=>[t,kt(n)])):e}chunkDPD6ZWL2_js.a(kt,"stableNormalize");function Ga(e,t){return e<t?-1:e>t?1:0}chunkDPD6ZWL2_js.a(Ga,"compareStrings");function cp(e){return e.function==="count"?`count(${e.relationAttribute})`:`${dp(e.function)}(${e.relationAttribute}.${e.targetAttribute})`}chunkDPD6ZWL2_js.a(cp,"rollupToFormulaExpression");function up(e,t){if(e.function==="count")return "number";let n=pp(e,t);switch(e.function){case "countValues":case "countEmpty":case "percentEmpty":case "percentNotEmpty":case "countUniqueValues":return "number";case "sum":case "avg":return "number";case "earliest":case "latest":return "date";case "original":if(!fp(n.type))throw new I('Rollup "original" requires a select, status, or multiselect target');return "multiselect";default:return e.function}}chunkDPD6ZWL2_js.a(up,"inferRollupReturnType");function Ya(e,t){let n=cp(e),r=up(e,t);return {...yn({attributeName:e.name,expression:n,returnType:r,schema:lp(e,t)}),kind:"rollup"}}chunkDPD6ZWL2_js.a(Ya,"compileRollupAttribute");function lp(e,t){return {...t,attributes:t.attributes.map(n=>n.name===e.relationAttribute&&n.type==="relation"?{...n,cardinality:"many"}:n)}}chunkDPD6ZWL2_js.a(lp,"schemaWithRollupRelationAsMany");function dp(e){switch(e){case "sum":case "avg":case "earliest":case "latest":return e;case "original":return "unique";case "countValues":return "count_not_empty";case "countEmpty":return "count_empty";case "percentEmpty":return "percent_empty";case "percentNotEmpty":return "percent_not_empty";case "countUniqueValues":return "count_unique";default:return e}}chunkDPD6ZWL2_js.a(dp,"rollupFunctionToFormulaFunction");function pp(e,t){let n=Ka(t,e.relationAttribute);if(n===void 0)throw new I(`Unknown relation attribute "${e.relationAttribute}" on object "${t.objectName}"`);if(n.type!=="relation")throw new I(`Attribute "${e.relationAttribute}" on object "${t.objectName}" is not a relation`);let r=mp(n);if(r===void 0)throw new I(`Relation "${e.relationAttribute}" on object "${t.objectName}" is missing targetObjectName`);let o=t.relatedObjects?.[r];if(o===void 0)throw new I(`Unknown related object "${r}"`);let a=Ka(o,e.targetAttribute);if(a===void 0)throw new I(`Unknown attribute "${e.targetAttribute}" on object "${o.objectName}"`);return a}chunkDPD6ZWL2_js.a(pp,"findRollupTargetAttribute");function Ka(e,t){return e.attributes.find(n=>n.name===t)}chunkDPD6ZWL2_js.a(Ka,"findAttribute");function mp(e){if(e.targetObjectName!==void 0)return e.targetObjectName;if(e.targets?.length===1){let[t]=e.targets;return t?.object==="*"?void 0:t?.object}}chunkDPD6ZWL2_js.a(mp,"getRelationTargetObjectName");function fp(e){return e==="select"||e==="status"||e==="multiselect"}chunkDPD6ZWL2_js.a(fp,"isSelectLikeAttributeType");function ve(e,t){switch(e.kind){case "literal":return e.value;case "path":return gp(t,e.parts);case "binary":return yp(e.operator,ve(e.left,t),ve(e.right,t));case "call":return bp(e.functionName,e.args,t);default:return e}}chunkDPD6ZWL2_js.a(ve,"evaluateAst");function bp(e,t,n){if(Ap(e),xp(e,t.length),e==="if"){let r=ve(t[0],n);return r===null?null:ve(r?t[1]:t[2],n)}return Tp(e,t.map(r=>ve(r,n)))}chunkDPD6ZWL2_js.a(bp,"evaluateCallNode");function gp(e,t){return t.reduce((n,r)=>es(n,r),e)}chunkDPD6ZWL2_js.a(gp,"resolvePath");function es(e,t){if(Array.isArray(e))return e.map(r=>es(r,t));if(!Xa(e))return null;if(Object.hasOwn(e,t))return e[t]??null;let n=e.values;return Xa(n)&&Object.hasOwn(n,t)?n[t]??null:null}chunkDPD6ZWL2_js.a(es,"resolvePathPart");function yp(e,t,n){switch(e){case "+":return hp(t,n);case "-":return An(t,n,(r,o)=>r-o);case "*":return An(t,n,(r,o)=>r*o);case "/":return An(t,n,(r,o)=>r/o);case ">":return hn(t,n,r=>r>0);case "<":return hn(t,n,r=>r<0);case ">=":return hn(t,n,r=>r>=0);case "<=":return hn(t,n,r=>r<=0);case "==":return Ha(t,n);case "!=":{let r=Ha(t,n);return r===null?null:!r}default:return e}}chunkDPD6ZWL2_js.a(yp,"evaluateBinary");function hp(e,t){return typeof e=="string"||typeof t=="string"?`${e??""}${t??""}`:An(e,t,(n,r)=>n+r)}chunkDPD6ZWL2_js.a(hp,"add");function hn(e,t,n){let r=ts(e,t);return r===null?null:n(r)}chunkDPD6ZWL2_js.a(hn,"compareWith");function ts(e,t){if(!pt([e,t]))return null;let n=mt(e),r=mt(t);if(n!==null&&r!==null)return n-r;let o=Li(e),a=Li(t);return o&&a?o.getTime()-a.getTime():null}chunkDPD6ZWL2_js.a(ts,"compare");function Ha(e,t){return e===t?true:e==null||t===null||t===void 0?false:pt([e,t])?ts(e,t)===0:null}chunkDPD6ZWL2_js.a(Ha,"equalScalar");function Ap(e){if(!bn(e))throw new Error(`Unknown computed function "${e}"`)}chunkDPD6ZWL2_js.a(Ap,"assertComputedFunctionName");function xp(e,t){let{minArgs:n,maxArgs:r}=jt[e];if(t>=n&&t<=(r??Number.POSITIVE_INFINITY))return;let o=r===void 0?`at least ${n}`:`between ${n} and ${r}`;throw new Error(`Function "${e}" expects ${o} arguments, received ${t}`)}chunkDPD6ZWL2_js.a(xp,"validateArity");function Tp(e,t){switch(e){case "concat":return t.filter(n=>n!=null).map(String).join("");case "sum":return pt(t)?Vi(t).reduce((n,r)=>n+r,0):null;case "avg":{if(!pt(t))return null;let n=Vi(t);return n.length>0?n.reduce((r,o)=>r+o,0)/n.length:null}case "count":return Ge(t[0]).length;case "min":return Ja(t,"min");case "max":return Ja(t,"max");case "earliest":return Bi(t,"min");case "latest":return Bi(t,"max");case "unique":return Za(Ge(t[0]));case "first":return Ge(t[0]).find(n=>n!=null)??null;case "percent_empty":return Qa(t[0],true);case "percent_not_empty":return Qa(t[0],false);case "count_empty":return Ge(t[0]).filter(chunkIBM4ID4Y_js.a).length;case "count_not_empty":return Ge(t[0]).filter(n=>!chunkIBM4ID4Y_js.a(n)).length;case "count_unique":return Za(Ge(t[0])).length;default:return e}}chunkDPD6ZWL2_js.a(Tp,"evaluateCall");function Vi(e){return xn(e).map(mt).filter(t=>t!==null)}chunkDPD6ZWL2_js.a(Vi,"numericValues");function pt(e){let t=new Set;for(let n of xn(e))$i(n)&&t.add(ns(n));return t.size<=1}chunkDPD6ZWL2_js.a(pt,"areCommensurable");function ns(e){return e.code.toUpperCase()}chunkDPD6ZWL2_js.a(ns,"currencyCode");function An(e,t,n){if(!pt([e,t]))return null;let r=mt(e),o=mt(t);if(r===null||o===null)return null;let a=n(r,o);return Number.isFinite(a)?a:null}chunkDPD6ZWL2_js.a(An,"numericBinary");function Ja(e,t){if(!pt(e))return null;let n=Vi(e);return n.length>0?t==="min"?Math.min(...n):Math.max(...n):Bi(e,t)}chunkDPD6ZWL2_js.a(Ja,"minMax");function Bi(e,t){let n=xn(e).map(Li).filter(a=>a!==null);if(n.length===0)return null;let r=n.map(a=>a.getTime()),o=t==="min"?Math.min(...r):Math.max(...r);return new Date(o).toISOString()}chunkDPD6ZWL2_js.a(Bi,"dateMinMax");function Qa(e,t){let n=Ge(e);return n.length===0?0:n.filter(o=>chunkIBM4ID4Y_js.a(o)===t).length/n.length}chunkDPD6ZWL2_js.a(Qa,"percentByEmptyState");function Za(e){let t=new Set,n=[];for(let r of e){if(chunkIBM4ID4Y_js.a(r))continue;let o=wp(r);t.has(o)||(t.add(o),n.push(r));}return n}chunkDPD6ZWL2_js.a(Za,"uniqueNonEmpty");function Ge(e){return e==null?[]:Array.isArray(e)?xn(e):[e]}chunkDPD6ZWL2_js.a(Ge,"collectionItems");function xn(e){return e.flat(Number.POSITIVE_INFINITY)}chunkDPD6ZWL2_js.a(xn,"flatten");function mt(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&e.trim()!==""){let t=Number(e);return Number.isFinite(t)?t:null}return $i(e)&&Number.isFinite(e.value)?e.value:null}chunkDPD6ZWL2_js.a(mt,"toFiniteNumber");function $i(e){return typeof e=="object"&&e!==null&&typeof e.value=="number"&&typeof e.code=="string"}chunkDPD6ZWL2_js.a($i,"isCurrencyValue");function Li(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e!="string"){let n=nt(e);if(n===null)return null;let r=new Date(n);return Number.isNaN(r.getTime())?null:r}let t=new Date(e);return Number.isNaN(t.getTime())?null:t}chunkDPD6ZWL2_js.a(Li,"toDate");function wp(e){if($i(e))return `currency:${ns(e)}:${e.value}`;let t=mt(e);return t!==null?`number:${t}`:e instanceof Date?`date:${e.toISOString()}`:`${typeof e}:${JSON.stringify(e)}`}chunkDPD6ZWL2_js.a(wp,"uniqueKey");function Xa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}chunkDPD6ZWL2_js.a(Xa,"isPlainRecord");function Sp(e,t,n){if(e==null)return null;let r=chunkDPD6ZWL2_js.a(o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean"||o instanceof Date?String(o):null,"stringifyScalar");switch(t){case "number":{let o=typeof e=="number"?e:Number(e);return Number.isNaN(o)?null:n!==void 0?Number(o.toFixed(n)):o}case "boolean":return !!e;case "date":return e instanceof Date?e.toISOString():typeof e=="string"?e:null;case "text":return String(e);case "select":if(Array.isArray(e)){for(let o of e){if(o==null)continue;let a=r(o);if(a!==null)return a}return null}return r(e);case "multiselect":return Array.isArray(e)?e.flatMap(o=>{if(o==null)return [];let a=r(o);return a===null?[]:[a]}):r(e)===null?[]:[String(e)];default:{let o=t;throw new Error(`Unsupported computed return type: ${o}`)}}}chunkDPD6ZWL2_js.a(Sp,"formatComputedResult");function eI(e,t){return ve(e,t)}chunkDPD6ZWL2_js.a(eI,"evaluateComputedAst");function tI(e,t){return ve(chunk2M4YXNYZ_js.v(e),t)}chunkDPD6ZWL2_js.a(tI,"evaluateComputedFormula");function nI(e,t,n,r){try{let o=ve(chunk2M4YXNYZ_js.v(e),t);return {value:n?Sp(o,n,r):o}}catch(o){return {value:null,error:o instanceof Error?o.message:String(o)}}}chunkDPD6ZWL2_js.a(nI,"evaluateComputedFormulaWithResult");var oI=[{name:"if",signature:"if(condition, then, else)",description:"Conditional value",category:"logic",example:"if(amount > 100, 'big', 'small')"},{name:"concat",signature:"concat(a, b, ...)",description:"Join values into text",category:"text",example:"concat(firstName, ' ', lastName)"},{name:"sum",signature:"sum(collection)",description:"Total of values",category:"number",example:"sum(orders.amount)"},{name:"avg",signature:"avg(collection)",description:"Average of values",category:"number",example:"avg(orders.amount)"},{name:"min",signature:"min(collection)",description:"Smallest value",category:"number",example:"min(orders.amount)"},{name:"max",signature:"max(collection)",description:"Largest value",category:"number",example:"max(orders.amount)"},{name:"count",signature:"count(collection)",description:"Number of items",category:"collection",example:"count(orders)"},{name:"count_empty",signature:"count_empty(collection)",description:"Items with no value",category:"collection",example:"count_empty(orders.note)"},{name:"count_not_empty",signature:"count_not_empty(collection)",description:"Items with a value",category:"collection",example:"count_not_empty(orders.note)"},{name:"count_unique",signature:"count_unique(collection)",description:"Distinct values",category:"collection",example:"count_unique(orders.status)"},{name:"percent_empty",signature:"percent_empty(collection)",description:"Fraction with no value",category:"collection",example:"percent_empty(orders.note)"},{name:"percent_not_empty",signature:"percent_not_empty(collection)",description:"Fraction with a value",category:"collection",example:"percent_not_empty(orders.note)"},{name:"unique",signature:"unique(collection)",description:"Distinct values as a list",category:"collection",example:"unique(orders.status)"},{name:"first",signature:"first(collection)",description:"First non-empty value",category:"collection",example:"first(orders.status)"},{name:"earliest",signature:"earliest(collection)",description:"Earliest date",category:"date",example:"earliest(orders.closeDate)"},{name:"latest",signature:"latest(collection)",description:"Latest date",category:"date",example:"latest(orders.closeDate)"}];var rs=chunkDPD6ZWL2_js.a(e=>chunkIBM4ID4Y_js.a(e)||Array.isArray(e)&&e.length===0,"isEmpty"),Z=chunkDPD6ZWL2_js.a(e=>e==null?"":String(e),"toStr"),Sn=chunkDPD6ZWL2_js.a(e=>{if(chunkIBM4ID4Y_js.a(e))return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null},"toNum"),In=chunkDPD6ZWL2_js.a(e=>{if(e==null)return null;let t=e instanceof Date?e:new Date(String(e));return Number.isNaN(t.getTime())?null:t},"toDate"),Tn=chunkDPD6ZWL2_js.a(e=>Array.isArray(e)?e:e==null?[]:[e],"toArr"),Ip=chunkDPD6ZWL2_js.a((e,t,n)=>{let r=Sn(e),o=Sn(t);return r!==null&&o!==null&&n(r,o)},"compareNumbers"),Rp=chunkDPD6ZWL2_js.a((e,t,n)=>{let r=In(e),o=In(t);return r!==null&&o!==null&&n(r.getTime(),o.getTime())},"compareDates"),is=chunkDPD6ZWL2_js.a((e,t,n)=>{if(n.type==="number"||n.type==="currency"){let r=Sn(e),o=Sn(t);if(r!==null&&o!==null)return r===o}return Z(e)===Z(t)},"equalsForAttr");function uI(e,t){return e?e==="checkbox":typeof t=="boolean"}chunkDPD6ZWL2_js.a(uI,"isCheckboxEquality");var wn=chunkDPD6ZWL2_js.a(e=>({appliesTo:["number","currency","date","formula"],evaluateInMemory:chunkDPD6ZWL2_js.a((t,n,r)=>r.type==="date"?Rp(t,n,e):Ip(t,n,e),"evaluateInMemory")}),"orderingSpec"),Rn={is:{appliesTo:["text","phone","number","currency","checkbox","status","select","date","user","relation","formula"],evaluateInMemory:chunkDPD6ZWL2_js.a((e,t,n)=>n.type==="checkbox"?e===true==(t===true):is(e,t,n),"evaluateInMemory")},is_not:{appliesTo:["text","phone","number","currency","status","select","date","user","relation","formula"],evaluateInMemory:chunkDPD6ZWL2_js.a((e,t,n)=>!is(e,t,n),"evaluateInMemory")},contains:{appliesTo:["text","phone","formula"],evaluateInMemory:chunkDPD6ZWL2_js.a((e,t)=>Z(e).toLowerCase().includes(Z(t).toLowerCase()),"evaluateInMemory")},not_contains:{appliesTo:["text","phone","formula"],evaluateInMemory:chunkDPD6ZWL2_js.a((e,t)=>!Z(e).toLowerCase().includes(Z(t).toLowerCase()),"evaluateInMemory")},starts_with:{appliesTo:["text","phone"],evaluateInMemory:chunkDPD6ZWL2_js.a((e,t)=>Z(e).toLowerCase().startsWith(Z(t).toLowerCase()),"evaluateInMemory")},ends_with:{appliesTo:["text"],evaluateInMemory:chunkDPD6ZWL2_js.a((e,t)=>Z(e).toLowerCase().endsWith(Z(t).toLowerCase()),"evaluateInMemory")},is_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:chunkDPD6ZWL2_js.a(e=>rs(e),"evaluateInMemory")},is_not_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:chunkDPD6ZWL2_js.a(e=>!rs(e),"evaluateInMemory")},less_than:wn((e,t)=>e<t),greater_than:wn((e,t)=>e>t),less_or_equal:wn((e,t)=>e<=t),greater_or_equal:wn((e,t)=>e>=t),is_within:{appliesTo:["date"],evaluateInMemory:chunkDPD6ZWL2_js.a((e,t)=>{let n=In(e),r=chunkUKFOBZX2_js.K(t);return n&&r?n.getTime()>=r.startMs&&n.getTime()<r.endMs:false},"evaluateInMemory")},on_day_month:{appliesTo:["date"],evaluateInMemory:chunkDPD6ZWL2_js.a((e,t)=>{let n=In(e);if(!n)return false;let r=t;return n.getMonth()+1===r.month&&n.getDate()===r.day},"evaluateInMemory")},any_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:chunkDPD6ZWL2_js.a((e,t)=>{let n=Tn(t).map(Z);return Tn(e).map(Z).some(o=>n.includes(o))},"evaluateInMemory")},none_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:chunkDPD6ZWL2_js.a((e,t)=>{let n=Tn(t).map(Z);return !Tn(e).map(Z).some(o=>n.includes(o))},"evaluateInMemory")}};var Cp=chunkDPD6ZWL2_js.a((e,t)=>({id:`system:${e}`,name:e,label:e,type:t,system:true}),"systemAttribute"),vp=[...Object.entries(chunkUKFOBZX2_js.N).map(([e,t])=>Cp(e,t))];function xI(e,t,n){let r=t;return Ep(e,{...t.values,id:t.id,objectId:t.objectId,objectName:r.objectName,tenantId:r.tenantId,label:t.label,createdAt:t.createdAt,updatedAt:t.updatedAt,createdBy:t.createdBy,lastUpdatedBy:t.lastUpdatedBy,deletedAt:t.deletedAt,deletedBy:t.deletedBy,visibility:t.visibility,ownedBy:t.ownedBy},[...n,...vp])}chunkDPD6ZWL2_js.a(xI,"evaluateRecordFilterState");function Ep(e,t,n){if(e.rules.length===0)return true;let r=new Map(n.map(a=>[a.name,a])),o=e.combinator==="or"?"some":"every";return e.rules[o](a=>Np(a,t,r))}chunkDPD6ZWL2_js.a(Ep,"evaluateFilterState");function Np(e,t,n){let r=n.get(e.attribute);if(!r)return false;if(e.property&&r.type==="location"){if(!(chunkUKFOBZX2_js.g(e.property)&&chunkUKFOBZX2_js.h(e.operator)))return false;let c=Rn[e.operator];if(!c)return false;let u=t[e.attribute],l=typeof u=="object"&&u!==null?u[e.property]:void 0;return Ui(c,"text",e.operator,l,e.value,r)}if(e.property){let c=Xt(r).find(b=>b.name===e.property);if(!c)return false;let u=chunkUKFOBZX2_js.C(e.operator),l=Rn[u];if(!l?.appliesTo.includes(c.type))return false;let m=t[e.attribute],g=(Array.isArray(m)?m:m==null?[]:[m]).some(b=>{if(typeof b!="object"||b===null)return false;let y=b.props;return typeof y!="object"||y===null?false:Ui(l,c.type,u,y[e.property],e.value,c)});return (e.quantifier??chunkUKFOBZX2_js.B(e.operator))==="none"?!g:g}let o=Rn[e.operator];if(!o||!o.appliesTo.includes(r.type))return false;let a=t[e.attribute],s=r.type==="relation"||r.type==="document"||r.type==="user"?jp(a):a;return Ui(o,r.type,e.operator,s,e.value,r)}chunkDPD6ZWL2_js.a(Np,"evaluateRule");function Ui(e,t,n,r,o,a){let[s,c]=Dp(t,n,r,o);return t==="phone"&&c===""&&n==="contains"?false:t==="phone"&&c===""&&n==="not_contains"?true:e.evaluateInMemory(s,c,a)}chunkDPD6ZWL2_js.a(Ui,"evaluateNormalizedComparands");function Dp(e,t,n,r){return e==="date"&&(t==="is"||t==="is_not")?[os(n),os(r)]:e==="phone"?Op(n,r):[as(e,n),as(e,r)]}chunkDPD6ZWL2_js.a(Dp,"normalizeOperatorComparands");function os(e){let t=Oe(e)?nt(e):e;if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.toISOString().slice(0,10);if(typeof t!="string"||t==="")return null;if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let n=new Date(t);return Number.isNaN(n.getTime())?null:n.toISOString().slice(0,10)}chunkDPD6ZWL2_js.a(os,"normalizeUtcCalendarDay");function Op(e,t){let n=typeof t=="object"&&t!==null?t:{},r=typeof n.countryCode=="string"?n.countryCode:void 0,o=chunkDPD6ZWL2_js.a(a=>{let s=typeof a=="object"&&a!==null?a:{phoneNumber:a};if(typeof s.phoneNumber!="string")return null;if(!r)return chunkGXSNLYRR_js.a(s.phoneNumber);let c=typeof s.countryCode=="string"?s.countryCode:r;return `${c}:${chunkGXSNLYRR_js.b(s.phoneNumber,c)}`},"normalizeOne");return [o(e),o(t)]}chunkDPD6ZWL2_js.a(Op,"normalizePhoneComparands");function as(e,t){return e==="currency"?chunkUKFOBZX2_js.z(t):e==="date"?Oe(t)?nt(t):t instanceof Date?Number.isNaN(t.getTime())?null:t.toISOString():t:t}chunkDPD6ZWL2_js.a(as,"normalizeComparableValue");function jp(e){let t=chunkDPD6ZWL2_js.a(n=>typeof n!="object"||n===null?n:n.id,"normalizeOne");return Array.isArray(e)?e.map(t):t(e)}chunkDPD6ZWL2_js.a(jp,"normalizeReferenceIds");var ss="today";function Cn(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}chunkDPD6ZWL2_js.a(Cn,"dateInTimezone");function kp(e,t){if(!("defaultValue"in e))return;let{defaultValue:n}=e;return e.type!=="date"||n!==ss?n:e.includeTime?t.now.toISOString():Cn(t.now,t.timezone)}chunkDPD6ZWL2_js.a(kp,"resolveAttributeDefaultValue");function EI(e,t,n){if(e.combinator==="or"&&e.rules.length>1)return {};let r=new Map(t.map(a=>[a.name,a])),o={};for(let a of e.rules){if(a.property!==void 0||Object.hasOwn(o,a.attribute))continue;let s=r.get(a.attribute);if(!s)continue;let c=_p(a,n);c!==void 0&&(o[a.attribute]=chunkUKFOBZX2_js.j(s).storage.cardinality==="many"?[c]:c);}return o}chunkDPD6ZWL2_js.a(EI,"deriveCreateDefaultsFromFilters");function _p(e,t){if(e.operator==="is")return chunkUKFOBZX2_js.v(e.value)?cs(e.value,t):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator==="any_of"){if(!Array.isArray(e.value)||e.value.length!==1)return;let n=e.value[0];return chunkUKFOBZX2_js.v(n)?cs(n,t):n}}chunkDPD6ZWL2_js.a(_p,"extractDeterministicValue");function cs(e,t){if(t){if(e.dynamic==="actor")return t.userId;if(e.anchor==="today")return Cn(t.now,t.timezone);if(e.anchor==="now")return t.now.toISOString()}}chunkDPD6ZWL2_js.a(cs,"resolveDynamicValue");function OI(e){let t=[];return e.canModify&&t.push("modify"),e.canSend&&t.push("send"),t}chunkDPD6ZWL2_js.a(OI,"requestedCapabilities");var jI={status:"connector_status",error:"connector_error",provider:"connector_provider"};var Pp=(t=>(t.Desktop="desktop",t))(Pp||{});function MI(e){return e==="gmail"||e==="outlook"}chunkDPD6ZWL2_js.a(MI,"isMailProvider");var Mp=["threads","messages"];function FI(e){return Mp.includes(e)}chunkDPD6ZWL2_js.a(FI,"isMailboxListMode");var Fp=["reply","reply_all"];function VI(e){return Fp.includes(e)}chunkDPD6ZWL2_js.a(VI,"isReplyMode");var BI=2e5,LI=998;var qI=["force","skip"],zI=["none","all","external_only"],WI="x-fake-signature",GI={override:null,status:"none",failureReason:null,botId:null};var Vp=/^Session \d+$/;function us(e){let t=e.replace(/\s+/g," ").trim().replace(/[.!?]+$/,"");return t?t.length>60?`${t.slice(0,59).trimEnd()}...`:t:"New conversation"}chunkDPD6ZWL2_js.a(us,"buildAgentFallbackTitle");function Bp(e){let t=e.generated?.trim();return t&&!Vp.test(t)?t:e.firstUserText?us(e.firstUserText):e.emptyLabel}chunkDPD6ZWL2_js.a(Bp,"conversationDisplayTitle");var qi=/^[a-z0-9][a-z0-9-]{0,62}$/;function Lp(e){if(!qi.test(e))throw new chunkJSKLP4GI_js.h(`Invalid schema source id "${e}": expected a lowercase slug matching ${qi}`,[])}chunkDPD6ZWL2_js.a(Lp,"assertSchemaSourceId");function XI(e){let{attributeRemovals:t,objectRemovals:n,renames:r}=e.destructive;return t.length>0||n.length>0||r.length>0}chunkDPD6ZWL2_js.a(XI,"hasDestructiveEntries");var de={objectAdditions:20,totalMutations:500,serializedBytes:512*1024};function Wi(e){return e instanceof Error?e.message:String(e)}chunkDPD6ZWL2_js.a(Wi,"errorMessage");var $p=zod.z.enum(["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"]).describe('The attribute\'s data type. Determines which keys `config` accepts and requires: `status`/`select`/`multiselect` need a non-empty `options` array (each `status` option carrying its own `group`); `relation` needs `targets` (non-empty) and `cardinality` ("one" or "many"); `formula` needs `expression` and `returnType`; `rollup` needs `targetAttribute` and `function`. Every other type accepts only the shared presentation keys (`placeholder`, `defaultValue`, `icon`, ...) plus a few type-specific optionals (e.g. `number.decimals`, `date.dateFormat`). An attribute\'s type can never be changed later through this tool \u2014 only through a code migration \u2014 so pick it correctly now.');var ds=zod.z.string().min(1).superRefine((e,t)=>{try{chunk2M4YXNYZ_js.n(e);}catch(n){t.addIssue({code:zod.z.ZodIssueCode.custom,message:Wi(n)});}}).describe('The attribute\'s machine name \u2014 the record\'s field key, and what `{{ name }}` refers to in a labelExpression. Must be a valid identifier: starts with a letter or underscore, then only letters/digits/underscores ("montantHt", "first_name", "FIRST_NAME" are valid; "first-name", "first name", "123name" are not). Max 63 characters. Cannot be a name reserved by the record shape itself (id, createdAt, updatedAt, createdBy, lastUpdatedBy, objectId, label, embeddingText, values, metadata, deletedAt, deletedBy, schemaVersion).'),Up=zod.z.string().min(1).superRefine((e,t)=>{chunk2M4YXNYZ_js.b(e)&&t.addIssue({code:zod.z.ZodIssueCode.custom,message:`"${e}" is a reserved object name (${chunk2M4YXNYZ_js.h.join(", ")}) and cannot be used for a new object.`});try{chunk2M4YXNYZ_js.j(e);}catch(n){t.addIssue({code:zod.z.ZodIssueCode.custom,message:Wi(n)});}}).describe(`The new object's machine name: kebab-case slug, lowercase letters/digits/hyphens only, starting with a letter ("products", "user-profiles", "order-items" are valid; "Products", "userProfiles", "user_profiles" are not). Max 63 characters. Cannot be a name the platform reserves for its own system objects, and cannot already exist.`);function ps(e){return e.superRefine((t,n)=>{try{let r=chunk2M4YXNYZ_js.L(t.type,{...t.config??{},description:t.description}),o=Object.keys(t.config??{}).filter(a=>!Object.hasOwn(r,a));o.length>0&&n.addIssue({code:"unrecognized_keys",keys:o,path:["config"],message:`Unrecognized attribute config key${o.length===1?"":"s"}: ${o.join(", ")}`});}catch(r){if(r instanceof chunkJSKLP4GI_js.h){for(let o of r.errors)n.addIssue({code:zod.z.ZodIssueCode.custom,path:["config",...o.path.map(a=>/^\d+$/.test(a)?Number(a):a)],message:`Config for type "${t.type}" is invalid or incomplete: ${o.message}`});return}n.addIssue({code:zod.z.ZodIssueCode.custom,path:["config"],message:`Config for type "${t.type}" is invalid or incomplete: ${Wi(r)}`});}})}chunkDPD6ZWL2_js.a(ps,"withConfigCheck");var ms=zod.z.object({objectName:zod.z.string().min(1).describe("Name of the existing (or, elsewhere in the same plan, newly created) object this attribute is added to. Ignored for an attribute declared inline in `additive.objects[].attributes` \u2014 there the parent object's own `name` is used instead."),name:ds,label:zod.z.string().min(1).max(128).describe("Human-readable display label shown in the UI. 1-128 characters, cannot be empty."),type:$p,config:zod.z.record(zod.z.string(),zod.z.unknown()).optional().describe('Type-specific configuration; required keys depend on `type` (see `type`\'s description). Shared optional keys on every type: `placeholder`, `defaultValue`, `icon`, `order`, `hidden`, `archived`, `deprecated`, `metadata`. Per-type keys: `text` \u2014 `multiline`, `minLength`, `maxLength`, `pattern`, `format` ("email"|"url"|"slug"); `number` \u2014 `renderAs` ("number"|"rating"), `min`, `max`, `unit`, `decimals`; `date` \u2014 `dateFormat`, `minDate`, `maxDate`, `includeTime`, `endDate`, `timeFormat` ("12h"|"24h"); `phone` \u2014 `defaultCountryCode` (3-letter); `currency` \u2014 `defaultCurrency`, `allowedCurrencies`, `allowNegative`; `status`/`select`/`multiselect` \u2014 `options` (REQUIRED, non-empty array of `{ value, label, color }`, unique `value`s; for `status` every OPTION also carries `group` as idle|in_progress|finished \u2014 `group` belongs on each option, never on `config` itself; select/multiselect accept `renderAs: "badges"`); `location` \u2014 `granularity`, `defaultCountry`, `allowedCountries`; `user` \u2014 `types` ("user"|"agent"), `multiple`; `relation` \u2014 `targets` (REQUIRED, non-empty array of `{ object }`) and `cardinality` (REQUIRED, "one"|"many"); `formula` \u2014 `expression` (REQUIRED formula string) and `returnType` (REQUIRED); `rollup` \u2014 `targetAttribute` (REQUIRED) and `function` (REQUIRED, e.g. "sum"|"avg"|"count"); `document` \u2014 `properties`, `accepts`, `maxFileSize`. Omit entirely for `richtext`/`checkbox`, which take no type-specific keys.'),required:zod.z.boolean().optional().describe("Whether the attribute must have a value on every record. Defaults to false (optional)."),description:zod.z.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),qp=ps(ms),zp=ps(ms.omit({objectName:true})),Wp=zod.z.object({name:Up,label:zod.z.string().min(1).describe('Human-readable singular display label (e.g. "Devis").'),pluralLabel:zod.z.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:zod.z.string().optional().describe("Help text describing what this object represents."),icon:chunk2M4YXNYZ_js.t.describe("Required icon name for the object. Must be a catalogue value \u2014 call `search_icons` and use a name it returns verbatim. A name that is not in the catalogue is rejected without any hint as to what would have worked, so never guess one."),labelExpression:rt.describe('Template used to render a human-readable label for every record of this object \u2014 e.g. shown in relations, search results, and breadcrumbs. MUST contain at least one `{{ attributeName }}` interpolation referencing an attribute this object will actually have (either declared in this same `attributes` array, or an existing attribute if this is an update) \u2014 a plain string with no `{{ }}` at all (e.g. "Devis") is rejected. Interpolations cannot be empty (`{{ }}` is rejected) and only these pipes are allowed: UPPER, LOWER, capitalize, trim, prefix:"...", suffix:"...", wrap:"..." "...", default:"...". `{{ a || b }}` falls back to `b` when `a` is empty. Examples: "{{ firstName }} {{ lastName }}", "{{ numero | UPPER }}", "{{ name || reference }}".'),attributes:zod.z.array(zp).default([]).describe("Attributes to create on this new object, inline. Same rules as a standalone entry in `additive.attributes`, minus `objectName` (implied by this object). At least one attribute referenced by `labelExpression` should be included here.")}).strict(),fs=zod.z.object({attributeRemovals:zod.z.array(zod.z.object({objectName:zod.z.string().min(1).describe("Object the attribute is removed from."),attributeName:zod.z.string().min(1).describe("Attribute to delete, together with every record's stored value for it. Must not be a system (code-declared) attribute, and must not be referenced by the object's own `labelExpression` or `embeddingExpression` \u2014 update those first.")}).strict()).default([]).describe("Attributes to permanently delete. Irreversible: record values for the attribute are purged."),objectRemovals:zod.z.array(zod.z.object({objectName:zod.z.string().min(1).describe("Object to delete entirely, together with all its records. Must not be a system (code-declared) object, and must not still be targeted by a `relation` attribute on another object \u2014 retarget or remove that relation first.")}).strict()).default([]).describe("Objects to permanently delete, records included. Irreversible."),renames:zod.z.array(zod.z.object({objectName:zod.z.string().min(1).describe("Object the renamed attribute belongs to."),from:zod.z.string().min(1).describe("Current attribute name. Must already exist and not be a system attribute."),to:ds.describe("New attribute name \u2014 same identifier rules as any attribute `name` (see `name` on a planned attribute), and must not collide with another name already on the object, including one added elsewhere in this same plan.")}).strict()).default([]).describe("Attribute renames. Every reference to the old name (labelExpression, views, formulas) must be updated separately \u2014 a rename does not follow references automatically.")}).strict().default({attributeRemovals:[],objectRemovals:[],renames:[]}),bs=zod.z.string().min(1).describe("ONE sentence naming the intent of the change \u2014 what it is for, not what it contains. The human approving it has already watched every entry land in the preview window and can read every row of the plan itself, so a recap tells them nothing they do not have. A second sentence is warranted only when `destructive` is non-empty: say plainly what will be lost (e.g. 'deletes the \"ancienMontant\" column and its data on every devis'). Never restate the plan \u2014 explain intent."),gs=zod.z.object({objects:zod.z.array(Wp).default([]),attributes:zod.z.array(qp).default([])}).strict().default({objects:[],attributes:[]});function zi(e,t=[],n=new WeakSet){if(e===null||typeof e=="string"||typeof e=="boolean")return null;if(typeof e=="number")return Number.isFinite(e)?null:{path:t,message:"Plan input contains a non-finite number"};if(typeof e!="object")return {path:t,message:"Plan input must contain only JSON-safe values"};if(n.has(e))return {path:t,message:"Plan input cannot contain circular references"};if(Array.isArray(e)){n.add(e);for(let s of Reflect.ownKeys(e))if(s!=="length"&&(typeof s=="symbol"||!/^(0|[1-9]\d*)$/.test(s)))return n.delete(e),{path:[...t,s],message:"Plan input arrays cannot contain non-index JSON properties"};for(let s=0;s<e.length;s++){if(!Object.hasOwn(e,s))return n.delete(e),{path:[...t,s],message:"Plan input cannot contain sparse arrays"};let c=zi(e[s],[...t,s],n);if(c)return n.delete(e),c}return n.delete(e),null}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return {path:t,message:"Plan input must contain only plain JSON objects"};n.add(e);let o=e,a=Reflect.ownKeys(o);for(let s of a){let c=Object.getOwnPropertyDescriptor(o,s);if(typeof s=="symbol"||!(c?.enumerable&&"value"in c))return n.delete(e),{path:[...t,s],message:"Plan input objects must contain enumerable JSON data properties only"}}for(let s of a.sort()){let c=zi(o[s],[...t,s],n);if(c)return n.delete(e),c}return n.delete(e),null}chunkDPD6ZWL2_js.a(zi,"findJsonSafetyIssue");function Gp(e){let t=[];return e.additive.objects.forEach((n,r)=>{t.push(["additive","objects",r]),n.attributes.forEach((o,a)=>{t.push(["additive","objects",r,"attributes",a]);});}),e.additive.attributes.forEach((n,r)=>{t.push(["additive","attributes",r]);}),e.destructive.attributeRemovals.forEach((n,r)=>{t.push(["destructive","attributeRemovals",r]);}),e.destructive.objectRemovals.forEach((n,r)=>{t.push(["destructive","objectRemovals",r]);}),e.destructive.renames.forEach((n,r)=>{t.push(["destructive","renames",r]);}),t}chunkDPD6ZWL2_js.a(Gp,"mutationPaths");function ys(e,t){e.additive.objects.length>de.objectAdditions&&t.addIssue({code:"too_big",origin:"array",maximum:de.objectAdditions,inclusive:true,path:["additive","objects",de.objectAdditions],message:`A schema plan can add at most ${de.objectAdditions} objects`});let n=Gp(e);n.length>de.totalMutations&&t.addIssue({code:"too_big",origin:"array",maximum:de.totalMutations,inclusive:true,path:n[de.totalMutations],message:`A schema plan can contain at most ${de.totalMutations} mutations; received ${n.length}`});}chunkDPD6ZWL2_js.a(ys,"addPlanLimitIssues");function hs(e,t){let n=zi(e);if(n)return t.addIssue({code:"custom",path:n.path,message:n.message}),zod.z.NEVER;let r=new TextEncoder().encode(chunkRTHLB6T6_js.b(e)).byteLength;return r>de.serializedBytes?(t.addIssue({code:"too_big",origin:"string",maximum:de.serializedBytes,inclusive:true,path:[],message:`A schema plan can serialize to at most ${de.serializedBytes} UTF-8 bytes; received ${r}`}),zod.z.NEVER):e}chunkDPD6ZWL2_js.a(hs,"boundSerializedPlanInput");var ls=zod.z.object({schemaPlanVersion:zod.z.literal(2).describe("Required proposal contract version."),summary:bs,additive:gs,destructive:fs}).strict().superRefine(ys),dR=Object.assign(zod.z.preprocess(hs,ls),{shape:ls.shape}),Kp=zod.z.object({schemaPlanVersion:zod.z.literal(2),summary:bs,additive:gs,destructive:fs}).strict().superRefine(ys),pR=zod.z.preprocess(hs,Kp);function ft(e,t){throw new chunkJSKLP4GI_js.h(t,[{path:e,message:t}])}chunkDPD6ZWL2_js.a(ft,"reject");function vn(e){throw new chunkJSKLP4GI_js.h(`Unsupported schema reference variant ${String(e)}`,[])}chunkDPD6ZWL2_js.a(vn,"exhaustive");function xR(e){let t=new Map(e.objects.map(s=>[s.name,s])),n=[];function r(s,c,u){function l(y,h,A){(y.kind==="object"?t.has(y.object):y.kind==="attribute"?t.get(y.object)?.attributes.some(C=>C.name===y.attribute):true)||ft([...c,...A],`Unknown schema reference ${JSON.stringify(y)}`),n.push({owner:s,target:y,category:h,path:A,...u===void 0?{}:{layer:u}});}chunkDPD6ZWL2_js.a(l,"add");function m(y,h,A,E){l({kind:"attribute",object:y,attribute:h},A,E);}chunkDPD6ZWL2_js.a(m,"attribute");function d(y,h,A,E,C){m(y,h,A,E);let M=t.get(y)?.attributes.find(P=>P.name===h);return M?.type!=="relation"&&ft([...c,...E],`Invalid schema reference path "${C}"`),(M.targets.length!==1||M.targets[0].object==="*")&&ft([...c,...E],`Ambiguous schema reference path "${C}"`),M.targets[0].object}chunkDPD6ZWL2_js.a(d,"traverse");function g(y,h,A,E){let C=y;for(let[M,P]of h.entries())M===h.length-1?m(C,P,A,E):C=d(C,P,A,E,h.join("."));}chunkDPD6ZWL2_js.a(g,"attributePath");function b(y,h,A){switch(h.kind){case "literal":return;case "path":g(y,h.parts,"computed",A);return;case "call":for(let E of h.args)b(y,E,A);return;case "binary":b(y,h.left,A),b(y,h.right,A);return;default:vn(h);}}return chunkDPD6ZWL2_js.a(b,"formula"),{add:l,attribute:m,traverse:d,attributePath:g,formula:b}}chunkDPD6ZWL2_js.a(r,"visitor"),e.objects.forEach((s,c)=>{let u=["objects",String(c)],l=r({kind:"object",object:s.name},u);for(let m of ["labelExpression","embeddingExpression"]){let d=s[m];if(d)for(let g of St(d))l.attributePath(s.name,g.split("."),"business",[m]);}s.attributes.forEach((m,d)=>{let g=[...u,"attributes",String(d)],b=r({kind:"attribute",object:s.name,attribute:m.name},g);switch(m.type){case "relation":m.targets.forEach((y,h)=>{if(y.object!=="*"&&b.add({kind:"object",object:y.object},"structural",["targets",String(h),"object"]),y.displayTemplate)for(let A of St(y.displayTemplate))b.attributePath(y.object,A.split("."),"business",["targets",String(h),"displayTemplate"]);for(let A of Object.keys(y.filter??{}))b.attribute(y.object,A,"business",["targets",String(h),"filter",A]);});break;case "formula":{let y;try{y=chunk2M4YXNYZ_js.v(m.expression);}catch(h){ft([...g,"expression"],h instanceof Error?h.message:String(h));}b.formula(s.name,y,["expression"]),o(m,b);break}case "rollup":{let y=m.relationPath??m.relationAttribute,h=s.name;for(let A of y.split("."))h=b.traverse(h,A,"computed",[m.relationPath===void 0?"relationAttribute":"relationPath"],y);b.attributePath(h,m.targetAttribute.split("."),"computed",["targetAttribute"]),o(m,b);break}case "text":case "richtext":case "number":case "checkbox":case "date":case "phone":case "currency":case "status":case "location":case "select":case "multiselect":case "user":case "document":break;default:vn(m);}});});function o(s,c){s.optionsSource&&(c.add({kind:"object",object:s.optionsSource.objectName},"computed",["optionsSource","objectName"]),c.attribute(s.optionsSource.objectName,s.optionsSource.attributeName,"computed",["optionsSource","attributeName"]));}chunkDPD6ZWL2_js.a(o,"visitOptions");function a(s,c,u){r({kind:"view",object:s.object,view:s.name},c,u).add({kind:"object",object:s.object},"structural",["object"]),s.contents.forEach((l,m)=>{let d=r({kind:"content",object:s.object,view:s.name,content:l.name},[...c,"contents",String(m)],u);function g(b,y,h,A){b?.forEach((E,C)=>d.attribute(y,E,h,[A,String(C)]));}switch(chunkDPD6ZWL2_js.a(g,"names"),l.type){case "collection":{let b=ze(l.source),y;switch(b.kind==="object"?(y=b.object,d.add({kind:"object",object:y},"source",["source","object"])):b.kind==="relatedFrom"?(y=b.object,d.add({kind:"object",object:y},"source",["source","object"]),d.attribute(y,b.relation,"source",["source","relation"])):y=d.traverse(s.object,b.relation,"source",["source","relation"],b.relation),l.columns?.forEach((h,A)=>{if(typeof h=="string"){d.attribute(y,h,"display",["columns",String(A)]);return}let E=t.get(s.object),C=b.kind!=="related"||!E?void 0:Da(E,b.relation),M=["columns",String(A),"relationProperty"];C||ft([...c,"contents",String(m),...M],"Relation property columns require a relation source"),C.properties?.definitions.some(P=>P.name===h.relationProperty)||ft([...c,"contents",String(m),...M],`Unknown relation property "${h.relationProperty}"`),d.add({kind:"attribute",object:s.object,attribute:C.name},"display",M);}),g(l.displayAttributes,y,"display","displayAttributes"),l.descriptionAttribute!==void 0&&d.attribute(y,l.descriptionAttribute,"display",["descriptionAttribute"]),l.filters?.rules.forEach((h,A)=>d.attribute(y,h.attribute,"business",["filters","rules",String(A),"attribute"])),l.sorts?.forEach((h,A)=>d.attribute(y,h.attribute,"business",["sorts",String(A),"attribute"])),l.layout){case "table":case "list":if(l.columnSizing)for(let h of Object.keys(l.columnSizing))d.attribute(y,h,"display",["columnSizing",h]);break;case "kanban":l.groupByAttribute!==void 0&&d.attribute(y,l.groupByAttribute,"business",["groupByAttribute"]);break;default:vn(l.layout);}break}case "form":l.groups.forEach((b,y)=>b.fields.forEach((h,A)=>d.attribute(s.object,h.attribute,"display",["groups",String(y),"fields",String(A),"attribute"])));break;case "richtext":d.attribute(s.object,l.attribute,"source",["attribute"]),l.titleAttribute!==void 0&&d.attribute(s.object,l.titleAttribute,"display",["titleAttribute"]);break;case "documents":g(l.relations,s.object,"business","relations");break;case "forms":l.objectName!==void 0&&d.add({kind:"object",object:l.objectName},"source",["objectName"]);break;case "emails":case "meetings":g(l.emailAttributes,s.object,"business","emailAttributes");break;case "activity":case "custom":break;default:vn(l);}});}return chunkDPD6ZWL2_js.a(a,"viewReferences"),e.views.forEach((s,c)=>a(s,["views",String(c)])),e.retainedViews?.forEach(({definition:s,layer:c},u)=>a(s,["retainedViews",String(u),"definition"],c)),n}chunkDPD6ZWL2_js.a(xR,"collectSchemaReferences");var As=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function U(e,t,n){throw new chunkJSKLP4GI_js.h(n,[{path:[...e.split("."),t],message:n}])}chunkDPD6ZWL2_js.a(U,"reject");function Gi(e){return e.join("|")}chunkDPD6ZWL2_js.a(Gi,"pairKey");function Ki(e,t){return [e,t].sort()}chunkDPD6ZWL2_js.a(Ki,"pairedAddresses");function Yp(e){let t=new Map,n=new Map,r=new Set;for(let o of e){let a=Gi(o.addresses);(!As.test(o.id)||o.addresses[0]===o.addresses[1]!=(o.symmetric===true))&&U(o.addresses[0],"pair",`Invalid stored pair identity for ${a}`),(t.has(a)||n.has(o.id)&&n.get(o.id)!==a||o.addresses.some(s=>r.has(s)))&&U(o.addresses[0],"pair",`Duplicate stored pair identity for ${a}`),o.addresses.includes(o.ownerAddress)||U(o.addresses[0],"pair",`Invalid property owner for ${a}`),t.set(a,o),n.set(o.id,a);for(let s of o.addresses)r.add(s);}return t}chunkDPD6ZWL2_js.a(Yp,"validateExistingPairs");function Hp(e,t){let n=new Set(e.flatMap(s=>s.addresses)),r=new Map,o=new Set;for(let{from:s,to:c}of t)(!n.has(s)||s===c||r.has(s)||o.has(c))&&U(s,"rename",`Invalid or duplicate relation attribute rename ${s} to ${c}`),r.set(s,c),o.add(c);let a=chunkDPD6ZWL2_js.a(s=>r.get(s)??s,"mapped");return e.map(s=>({...s,addresses:Ki(a(s.addresses[0]),a(s.addresses[1])),ownerAddress:a(s.ownerAddress),generatedAddresses:s.generatedAddresses.map(a)}))}chunkDPD6ZWL2_js.a(Hp,"remapExistingPairs");function Jp(e,t,n){return e.type==="relation"&&e.bilateral?.object===t&&e.bilateral.attribute===n&&e.targets.length===1&&e.targets[0]?.object===t}chunkDPD6ZWL2_js.a(Jp,"isReciprocal");function Qp(e,t,n){let r=e.bilateral;r||U(`${t}.${e.name}`,"bilateral","Missing inverse address");let o={type:"relation",name:r.attribute,label:r.label??r.attribute,required:false,targets:[{object:t}],bilateral:{object:t,attribute:e.name,cardinality:e.cardinality},order:n};return (r.cardinality??Wo(e.cardinality))==="one"?{...o,cardinality:"one"}:{...o,cardinality:"many"}}chunkDPD6ZWL2_js.a(Qp,"generateInverse");function Zp(e,t,n,r,o){e.bilateral?.cardinality&&e.bilateral.cardinality!==t.cardinality&&U(r,"cardinality",`${n} declares ${r} as ${e.bilateral.cardinality}, but ${r} declares ${t.cardinality}`),t.bilateral?.cardinality&&t.bilateral.cardinality!==e.cardinality&&U(n,"cardinality",`${r} declares ${n} as ${t.bilateral.cardinality}, but ${n} declares ${e.cardinality}`),e.bilateral?.label&&e.bilateral.label!==t.label&&U(r,"label",`${n} declares a different label for ${r}`),t.bilateral?.label&&t.bilateral.label!==e.label&&U(n,"label",`${r} declares a different label for ${n}`),e.properties&&t.properties&&!chunkRTHLB6T6_js.j(e.properties,t.properties)&&!o&&U(r,"properties",`${n} and ${r} declare different qualified properties`),e.bilateral?.storageOwner===t.bilateral?.storageOwner&&e.bilateral?.storageOwner!==void 0&&U(r,"storageOwner",`${n} and ${r} cannot both own or both disown qualified properties`);}chunkDPD6ZWL2_js.a(Zp,"checkExplicitDeclarations");function Xp(e,t,n,r,o,a){return o?o.ownerAddress:e.bilateral?.storageOwner===true||t.bilateral?.storageOwner===false?n:e.bilateral?.storageOwner===false||t.bilateral?.storageOwner===true?r:a?n:Ki(n,r)[0]}chunkDPD6ZWL2_js.a(Xp,"chooseOwner");function em(e){if(!e.metadata)return;let{relationPairId:t,relationGenerated:n,...r}=e.metadata;e.metadata=Object.keys(r).length>0?r:void 0;}chunkDPD6ZWL2_js.a(em,"stripUntrustedPairMetadata");function tm(e,t,n,r,o,a){a.has(n)&&a.has(r)&&!chunkRTHLB6T6_js.j(e.properties,t.properties)&&U(r,"properties",`${n} and ${r} edit different qualified properties`);let s=a.has(n)||o.has(n)&&!o.has(r)&&!a.has(r),c=a.has(r)||o.has(r)&&!o.has(n)&&!a.has(n),u=s?e.properties:c?t.properties:e.properties??t.properties;u?(e.properties=structuredClone(u),t.properties=structuredClone(u)):(delete e.properties,delete t.properties);}chunkDPD6ZWL2_js.a(tm,"reconcileProperties");function Yi(e){let t=structuredClone(e.objects),n=new Map;for(let d of t){if(n.has(d.name))throw new chunkJSKLP4GI_js.r("object",d.name);n.set(d.name,d);let g=new Set;for(let b of d.attributes){if(g.has(b.name))throw new chunkJSKLP4GI_js.r("attribute",b.name);g.add(b.name),em(b);}}let r=Hp(e.existingPairs??[],e.addressRenames??[]),o=Yp(r),a=new Set(r.flatMap(d=>d.generatedAddresses)),s=new Set(e.propertyEditAddresses??[]),c=new Set(e.explicitAddresses??t.flatMap(d=>d.attributes.filter(g=>!a.has(`${d.name}.${g.name}`)).map(g=>`${d.name}.${g.name}`))),u=t.flatMap(d=>d.attributes.filter(g=>g.type==="relation"&&!!g.bilateral).map(g=>({object:d,attribute:g,address:`${d.name}.${g.name}`}))).sort((d,g)=>d.address.localeCompare(g.address)),l=new Map,m=new Map;for(let{object:d,attribute:g,address:b}of u){let y=g.bilateral?.object;(!y||y==="*"||g.targets.length!==1||g.targets[0]?.object!==y)&&U(b,"targets",`Bilateral target of ${b} must be one concrete object`);let h=n.get(y);h||U(b,"bilateral",`Unknown inverse object ${y} for ${b}`);let A=`${y}.${g.bilateral?.attribute}`,E=b===A;E&&g.cardinality!=="many"&&U(b,"cardinality",`Symmetric self relation ${b} must be many`),E&&g.bilateral?.cardinality&&g.bilateral.cardinality!==g.cardinality&&U(b,"bilateral",`Symmetric self relation ${b} needs matching cardinality`);let C=Ki(b,A),M=Gi(C);if(l.has(M))continue;let P=h.attributes.find(Ie=>Ie.name===g.bilateral?.attribute);if(P&&!Jp(P,d.name,g.name))throw new chunkJSKLP4GI_js.r("attribute",A);let fe=!(P&&c.has(A));P||(P=Qp(g,d.name,h.attributes.length),h.attributes.push(P));let L=P;!E&&c.has(b)&&c.has(A)&&Zp(g,L,b,A,s.has(b)!==s.has(A));let k=o.get(M),F=k?.id??e.nextPairId(C),oe=r.find(Ie=>Ie.id===F&&Gi(Ie.addresses)!==M);(!As.test(F)||oe||m.has(F)&&m.get(F)!==M)&&U(b,"pair",`Invalid or duplicate pair identity for ${b} and ${A}`),m.set(F,M);let te=E?b:Xp(g,L,b,A,k,fe);g.bilateral&&L.bilateral||U(b,"bilateral",`Missing reciprocal configuration for ${b} and ${A}`),g.bilateral={...g.bilateral,cardinality:L.cardinality,label:L.label,storageOwner:te===b},L.bilateral={...L.bilateral,cardinality:g.cardinality,label:g.label,storageOwner:te===A},tm(g,L,b,A,c,s),g.metadata={...g.metadata,relationPairId:F},L.metadata={...L.metadata,relationPairId:F},l.set(M,{id:F,addresses:C,ownerAddress:te,generatedAddresses:C.filter(Ie=>!c.has(Ie)),...E?{symmetric:true}:{}});}return {objects:t,pairs:[...l.values()].sort((d,g)=>d.addresses[0].localeCompare(g.addresses[0]))}}chunkDPD6ZWL2_js.a(Yi,"reconcileRelationAttributes");var N=zod.z.number().finite().nonnegative(),Ts=zod.z.enum(Ko),Hi=zod.z.enum(Yo),Ji=zod.z.enum(Ho),ws=zod.z.object({provider:Ts,model:zod.z.string().min(1)}).strict(),OR=zod.z.object({speed:Hi.optional(),reasoning:Ji.optional()}).strict(),Ss=zod.z.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),nm=zod.z.object({model:ws.optional(),speed:Hi.optional(),reasoning:Ji.optional(),imageModel:Ss.optional()}).strict(),jR=nm.refine(e=>e.model!==void 0||e.speed!==void 0||e.reasoning!==void 0||e.imageModel!==void 0,{message:"At least one inference override is required"}),kR=zod.z.object({model:ws.nullable().optional(),speed:Hi.nullable().optional(),reasoning:Ji.nullable().optional(),imageModel:Ss.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0&&Object.values(e).every(t=>t!==void 0),{message:"At least one inference override is required"}),Is=zod.z.object({label:zod.z.string(),denied:zod.z.boolean().optional(),deletion:zod.z.object({target:zod.z.string().optional(),count:N.optional(),restorableDays:N.optional()}).strict().optional(),counts:zod.z.record(zod.z.string(),N).optional(),warnings:zod.z.array(zod.z.string()).optional()}).strict(),rm=zod.z.union([zod.z.object({type:zod.z.literal("text"),text:zod.z.string()}).strict(),zod.z.object({type:zod.z.literal("reasoning"),text:zod.z.string()}).strict(),zod.z.object({type:zod.z.literal("system"),code:zod.z.enum(Kn)}).strict(),zod.z.object({type:zod.z.literal("error"),error:zod.z.string(),errorClass:zod.z.string().optional()}).strict(),zod.z.object({type:zod.z.literal("tool"),toolCallId:zod.z.string(),name:zod.z.string(),args:zod.z.record(zod.z.string(),zod.z.unknown()),result:zod.z.unknown().optional(),error:zod.z.string().optional(),errorCode:zod.z.enum(["output_limit_reached","interrupted"]).optional(),state:zod.z.enum(["streaming","running","completed","error","pending","approval-requested","approval-responded","approval-dispatched"]),durationMs:N.optional(),approvalId:zod.z.string().optional(),approvalImpact:Is.optional(),approved:zod.z.boolean().optional(),approvalReason:zod.z.string().optional(),approvalRelaxableByAuto:zod.z.boolean().optional()}).strict(),zod.z.object({type:zod.z.literal("file"),fileId:zod.z.string(),name:zod.z.string(),mimeType:zod.z.string()}).strict(),zod.z.object({type:zod.z.literal("compaction"),state:zod.z.literal("in-progress"),reason:zod.z.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:N.optional(),reportedTokens:N.optional()}).strict(),zod.z.object({type:zod.z.literal("compaction"),state:zod.z.literal("completed"),tokensBefore:N,tokensAfter:N,tokensSaved:N,strategy:zod.z.enum(["no-op","summary","truncation"]),durationMs:N,summary:zod.z.string().optional()}).strict(),zod.z.object({type:zod.z.literal("compaction"),state:zod.z.literal("failed"),reason:zod.z.string(),durationMs:N.optional()}).strict()]),im=zod.z.object({id:zod.z.string(),name:zod.z.string(),mimeType:zod.z.string(),size:N}).strict(),om=zod.z.object({id:zod.z.string(),type:zod.z.string().transform(e=>e),entityId:zod.z.string(),label:zod.z.string(),objectName:zod.z.string().optional(),startIndex:N,endIndex:N}).strict(),am=zod.z.object({provider:Ts,model:zod.z.string(),maxTokens:N.optional(),contextWindow:N.optional()}).strict(),sm=zod.z.union([zod.z.date(),zod.z.string().datetime({offset:true}).transform(e=>new Date(e))]),xs=zod.z.object({id:zod.z.string(),sessionId:zod.z.string(),tenantId:zod.z.string().optional(),runId:zod.z.string().optional(),role:zod.z.enum(["user","assistant","system","tool"]),parts:zod.z.array(rm),attachments:zod.z.array(im).optional(),mentions:zod.z.array(om).optional(),model:am.optional(),tokenUsage:zod.z.object({input:N,output:N}).strict().optional(),metadata:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),createdAt:sm}).strict(),cm=zod.z.object({id:zod.z.string(),description:zod.z.string(),status:zod.z.enum(["pending","in_progress","completed","blocked"]),result:zod.z.string().optional(),updatedAt:N.optional()}).strict(),um=zod.z.object({id:zod.z.string(),sessionId:zod.z.string(),status:zod.z.enum(["active","completed","abandoned"]),todos:zod.z.array(cm),version:N,createdAt:zod.z.string(),updatedAt:zod.z.string(),completedAt:zod.z.string().optional()}).strict(),Rs={"session-named":zod.z.object({name:zod.z.string()}).strict(),"compaction-start":zod.z.object({reason:zod.z.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:N.optional(),reportedTokens:N.optional()}).strict(),"compaction-end":zod.z.object({tokensBefore:N,tokensAfter:N,tokensSaved:N,strategy:zod.z.enum(["no-op","summary","truncation"]),durationMs:N,summary:zod.z.string().optional()}).strict(),"compaction-failed":zod.z.object({reason:zod.z.string()}).strict(),usage:zod.z.object({messageId:zod.z.string().min(1).optional(),inputTokens:N,outputTokens:N,totalTokens:N,cacheReadTokens:N.optional(),cacheCreationTokens:N.optional(),contextWindow:N,residentTokens:N,utilization:zod.z.number().finite().min(0).max(1),costUsd:N.optional()}).strict(),"message-persisted":zod.z.object({message:xs}).strict(),"message-updated":zod.z.object({message:xs}).strict(),"todo-plan-update":zod.z.object({plan:um}).strict(),"approval-context":zod.z.object({approvalId:zod.z.string(),toolCallId:zod.z.string(),impact:Is.optional(),relaxableByAuto:zod.z.boolean().optional()}).strict(),"session-state":zod.z.object({state:zod.z.object({phase:zod.z.enum(["queued","running","parked","terminal"]),parkedOn:zod.z.enum(["human","agents"]).optional(),humanRequestIds:zod.z.array(zod.z.string()).optional(),outcome:zod.z.enum(["completed","failed","cancelled","timeout","expired"]).optional()}).strict(),version:zod.z.number().int().positive(),updatedAt:zod.z.string().datetime({offset:true})}).strict()};function lm(e){return e in Rs}chunkDPD6ZWL2_js.a(lm,"isAgentUIDataName");function dm(e){return new chunkJSKLP4GI_js.h("Invalid agent UI message chunk",e.map(t=>({path:t.path.map(String),message:t.message,code:t.code})))}chunkDPD6ZWL2_js.a(dm,"agentUIValidationError");function pm(e){if(typeof e!="object"||e===null||typeof e.type!="string")throw new chunkJSKLP4GI_js.h("Invalid agent UI message chunk",[{path:["type"],message:"Expected UI message chunk type",code:"invalid_type"}]);let t=e.type;if(!t.startsWith("data-"))throw new chunkJSKLP4GI_js.h("Invalid agent UI message chunk",[{path:["type"],message:"Expected agent data chunk type",code:"invalid_value"}]);let n=t.slice(5);if(!lm(n))throw new chunkJSKLP4GI_js.h("Invalid agent UI message chunk",[{path:["type"],message:`Unknown agent UI data type: ${n}`,code:"invalid_value"}]);let r=zod.z.object({type:zod.z.literal(`data-${n}`),id:zod.z.string().optional(),data:Rs[n],transient:zod.z.boolean().optional()}).strict().safeParse(e);if(!r.success)throw dm(r.error.issues);return r.data}chunkDPD6ZWL2_js.a(pm,"assertCustomAgentUIMessageChunk");function _R(e,t,n){return pm({type:`data-${e}`,...n?.id!==void 0?{id:n.id}:{},data:t,...n?.transient!==void 0?{transient:n.transient}:{}})}chunkDPD6ZWL2_js.a(_R,"agentDataChunk");function Qi(e){return e}chunkDPD6ZWL2_js.a(Qi,"defineOperation");function B(e,t,n){let r=t==="atomic"?"none":t==="local"?"if-not-visible":"follow";return o=>{let a=n?.(o);return {impact:t,navigation:r,focus:{...e(o),...a===void 0?{}:{propertyPath:a}}}}}chunkDPD6ZWL2_js.a(B,"definePresentation");function mm(e){return {id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon}}}chunkDPD6ZWL2_js.a(mm,"toDraftableObject");function fm(e){let t=e.id??e.name;return (e.attributes??[]).map(n=>Zi(n,t))}chunkDPD6ZWL2_js.a(fm,"toDraftableAttributes");function X(e){return {id:e.id,name:e.name,label:e.label,type:e.attributeType,...e.config}}chunkDPD6ZWL2_js.a(X,"toAttribute");function Zi(e,t){let{id:n,name:r,label:o,type:a,...s}=e;return {id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:s}}chunkDPD6ZWL2_js.a(Zi,"toDraftableAttribute");function Cs(e){let t=e[0];return t?`{{ ${t.name} }}`:"{{ id }}"}chunkDPD6ZWL2_js.a(Cs,"draftedLabelExpression");function Xi(e,t){let n=t.filter(r=>r.objectId===e.id);return {id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},labelExpression:Cs(n),attributes:n.map((r,o)=>{let a=X(r);return a.order===void 0?{...a,order:o}:a})}}chunkDPD6ZWL2_js.a(Xi,"draftedObjectDefinition");function bm(e,t,n=Nt(e.contents)){return structuredClone({...e,...t,authoring:n})}chunkDPD6ZWL2_js.a(bm,"toDraftableView");function bt(e){let{id:t,revision:n,contentIds:r,contentRevisions:o,derived:a,authoring:s,...c}=e;return structuredClone(c)}chunkDPD6ZWL2_js.a(bt,"draftedViewDefinition");function gm(e,t){return {...e,...bt(t)}}chunkDPD6ZWL2_js.a(gm,"fromDraftableView");var _t={id:zod.z.string().min(1).describe("Your id, echoed back"),note:zod.z.string().trim().min(1).max(160).optional().describe("Why, in the person's words, \u2264160 chars")};var Pt={..._t,objectName:zod.z.string().min(1).describe("Object"),viewName:zod.z.string().min(1).describe("View API name")},gt={...Pt,contentName:zod.z.string().min(1).describe("Content API name")},Os=zod.z.union([zod.z.object({before:zod.z.string().min(1).describe("Place immediately before this content name")}).strict(),zod.z.object({after:zod.z.string().min(1).describe("Place immediately after this content name")}).strict(),zod.z.object({end:zod.z.literal(true).describe("Place at the end of the placement zone")}).strict()]),Ke=chunkDPD6ZWL2_js.a(e=>({objectName:e.objectName,viewName:e.viewName}),"viewFocus"),Me=chunkDPD6ZWL2_js.a(e=>({...Ke(e),contentName:e.contentName}),"contentFocus");function pe(e,t){throw new chunkJSKLP4GI_js.h(t,[{path:e,message:t}])}chunkDPD6ZWL2_js.a(pe,"invalid");function Ee(e,t,n,r){let o=e.views.findIndex(u=>u.object===t.objectName&&u.name===t.viewName);o<0&&pe(["viewName"],"View is not in the draftable state"),e.views[o].authoring||pe(["authoring"],"Missing view authoring baseline");let{derived:a,...s}=r(structuredClone(e.views[o]));s.contents=xi(s.authoring);let c=e.views.map((u,l)=>l===o?s:u);return Ii({extensions:[...n.extensions],objects:e.objects.map(u=>Xi(u,e.attributes.filter(l=>l.objectId===u.id))),views:c.map(bt)}),{...e,views:c}}chunkDPD6ZWL2_js.a(Ee,"change");function Ye(e,t){let n=Object.hasOwn(e.authoring.contents,t)?e.authoring.contents[t]:void 0;return n||pe(["contentName"],"Content is not in the draftable state"),n}chunkDPD6ZWL2_js.a(Ye,"contentState");function eo(e,t,n){for(let r of n)e.authoring[r==="main"?"mainOrderCustomized":"asideOrderCustomized"]=true,t.filter(o=>o.placement===r).forEach((o,a)=>{Ye(e,o.name).workspacePosition=a;});}chunkDPD6ZWL2_js.a(eo,"setOrder");function to(e,t){let n=e.contents.find(r=>r.name===t);return n||pe(["contentName"],"Content is not in the draftable state"),n}chunkDPD6ZWL2_js.a(to,"find");function js(e,t,n){let r=e.filter(s=>s.name!==t.name),o=r.filter(s=>s.placement===t.placement),a=o.length;if(!("end"in n)){let s="before"in n?n.before:n.after;a=o.findIndex(c=>c.name===s),a<0&&pe(["target"],"Order target is not in this placement"),"after"in n&&a++;}return o.splice(a,0,t),t.placement==="main"?[...o,...r.filter(s=>s.placement==="aside")]:[...r.filter(s=>s.placement==="main"),...o]}chunkDPD6ZWL2_js.a(js,"placed");var ym=zod.z.unknown().transform((e,t)=>{let n=chunkUKFOBZX2_js.W.safeParse(typeof e=="object"&&e!==null?{...e,name:"candidate"}:e);if(!n.success){for(let o of n.error.issues)t.addIssue({code:"custom",path:o.path,message:o.message});return zod.z.NEVER}let r=typeof e=="object"&&e!==null&&"name"in e?e.name:void 0;return {...n.data,name:r}}),ks=zod.z.object({...gt,type:zod.z.literal("replace_view_content"),definition:ym}).strict().superRefine((e,t)=>{e.definition.name!==void 0&&e.definition.name!==e.contentName&&t.addIssue({code:"custom",path:["definition","name"],message:"must equal the target contentName, or be omitted"});}).overwrite(e=>{let{name:t,...n}=e.definition;return {...e,definition:n}}),_s=chunkUKFOBZX2_js.W.describe("The whole content definition."),hm=zod.z.object({...gt,type:zod.z.literal("replace_view_content"),definition:_s}).strict().describe("definition.name, if sent, must equal contentName \u2014 the operation's own target; a different name is refused."),Am={type:"replace_view_content",summary:"Replaces a content's whole definition; placement can't change here (use move_view_content); first content op freezes derived views.",schema:ks,wire:hm,focus:Me,presentation:B(Me,"local"),describe:chunkDPD6ZWL2_js.a(e=>`Replace ${e.objectName}.${e.viewName}.${e.contentName}`,"describe"),apply:chunkDPD6ZWL2_js.a((e,t,n)=>Ee(e,t,n,r=>(to(r,t.contentName).placement!==t.definition.placement&&pe(["definition","placement"],"Use move_view_content to change placement"),Ye(r,t.contentName).workspaceDefinition=structuredClone(t.definition),{...r,contents:r.contents.map(a=>a.name===t.contentName?{...t.definition,name:t.contentName}:a),contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}})),"apply")},Ps=zod.z.object({...Pt,type:zod.z.literal("add_view_content"),content:_s,target:Os.describe("Where to place the new content within its placement zone")}).strict(),Es=chunkDPD6ZWL2_js.a(e=>({...Ke(e),contentName:e.content.name}),"addFocus"),xm={type:"add_view_content",summary:"Adds a content; content.name unique; collection view needs collection with source.object; aside holds one content, a form; target positions it among siblings.",schema:Ps,focus:Es,presentation:B(Es,"structural"),describe:chunkDPD6ZWL2_js.a(e=>`Add ${e.content.name}`,"describe"),apply:chunkDPD6ZWL2_js.a((e,t,n)=>Ee(e,t,n,r=>{if(Object.hasOwn(r.authoring.contents,t.content.name))throw new chunkJSKLP4GI_js.r("content",t.content.name);r.authoring.contents={...r.authoring.contents,[t.content.name]:{sourceDefinition:null,workspaceDefinition:Et(t.content),suppressed:false,sourcePosition:null,workspacePosition:0}};let o=js(r.contents,t.content,t.target);return eo(r,o,[t.content.placement]),{...r,revision:r.revision+1,contents:o,contentIds:{...r.contentIds,[t.content.name]:JSON.stringify(["draft-content",t.id])},contentRevisions:{...r.contentRevisions,[t.content.name]:1}}}),"apply")},Ms=zod.z.object({...gt,type:zod.z.literal("remove_view_content")}).strict(),Tm={type:"remove_view_content",summary:"Removes a content; a published view keeps \u22651 main content; a code-declared content is hidden, not deleted.",schema:Ms,focus:Me,presentation:B(Me,"structural"),describe:chunkDPD6ZWL2_js.a(e=>`Remove ${e.contentName}`,"describe"),apply:chunkDPD6ZWL2_js.a((e,t,n)=>Ee(e,t,n,r=>{let o=to(r,t.contentName),a=Ye(r,t.contentName),s=r.contents.filter(d=>d.name!==t.contentName);if(eo(r,s,[o.placement]),a.sourceDefinition!==null)return a.workspaceDefinition=null,a.suppressed=true,{...r,revision:r.revision+1,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}};delete r.authoring.contents[t.contentName];let{[t.contentName]:c,...u}=r.contentIds,{[t.contentName]:l,...m}=r.contentRevisions;return {...r,revision:r.revision+1,contents:r.contents.filter(d=>d.name!==t.contentName),contentIds:u,contentRevisions:m}}),"apply")},Fs=zod.z.object({...gt,type:zod.z.literal("move_view_content"),placement:zod.z.enum(["main","aside"]).describe("The placement zone to move the content into"),target:Os.describe("Where to place the content within that placement zone")}).strict(),wm={type:"move_view_content",summary:"Reorders or moves a content to a different placement; the aside rule applies.",schema:Fs,focus:Me,presentation:B(Me,"structural"),describe:chunkDPD6ZWL2_js.a(e=>`Move ${e.contentName}`,"describe"),apply:chunkDPD6ZWL2_js.a((e,t,n)=>Ee(e,t,n,r=>{let o=to(r,t.contentName);o.placement!==t.placement&&(Ye(r,t.contentName).workspaceDefinition={...Et(o),placement:t.placement});let a=js(r.contents,{...o,placement:t.placement},t.target);return eo(r,a,[...new Set([o.placement,t.placement])]),{...r,revision:r.revision+1,contents:a,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+ +(o.placement!==t.placement)}}}),"apply")},Vs=zod.z.object({...Pt,type:zod.z.literal("update_view_metadata"),changes:zod.z.object({label:zod.z.string().min(1).optional().describe("New label for the view"),description:zod.z.string().optional().describe("New description for the view"),icon:chunk2M4YXNYZ_js.t.nullable().optional().describe("New icon; null clears it")}).strict().refine(e=>Object.keys(e).length>0).describe("\u22651 change")}).strict(),Sm={type:"update_view_metadata",summary:"Updates a view's label, description, or icon (null clears the icon).",schema:Vs,focus:Ke,presentation:B(Ke,"atomic"),describe:chunkDPD6ZWL2_js.a(e=>`Update ${e.viewName}`,"describe"),apply:chunkDPD6ZWL2_js.a((e,t,n)=>Ee(e,t,n,r=>{let{icon:o,...a}=t.changes,s={...r,...a,revision:r.revision+1};if(o===null){let{icon:c,...u}=s;return u}return o===void 0?s:{...s,icon:o}}),"apply")},Bs=zod.z.string().refine(e=>e.trim().length>0,"API name must not be blank"),Ls=zod.z.object({...Pt,type:zod.z.literal("rename_view"),newName:Bs.describe("New API name for the view")}).strict(),Ns=chunkDPD6ZWL2_js.a(e=>({objectName:e.objectName,viewName:e.newName}),"renameViewFocus"),Im={type:"rename_view",summary:"Renames a view; refused on a code-declared name \u2014 change it in the declaration.",schema:Ls,focus:Ns,presentation:B(Ns,"structural"),describe:chunkDPD6ZWL2_js.a(e=>`Rename view ${e.viewName} to ${e.newName}`,"describe"),apply:chunkDPD6ZWL2_js.a((e,t,n)=>Ee(e,t,n,r=>t.newName===r.name?r:(r.authoring.origin==="code"&&pe(["newName"],"Source-owned API names must be changed in their declaration"),e.views.some(o=>o.object===t.objectName&&o.name===t.newName)&&pe(["newName"],"View API name is already used"),{...r,name:t.newName,revision:r.revision+1})),"apply")},$s=zod.z.object({...gt,type:zod.z.literal("rename_view_content"),newName:Bs.describe("New API name for the content")}).strict(),Ds=chunkDPD6ZWL2_js.a(e=>({...Ke(e),contentName:e.newName}),"renameContentFocus"),Rm={type:"rename_view_content",summary:"Renames a content; refused on a code-declared name \u2014 change it in the declaration.",schema:$s,focus:Ds,presentation:B(Ds,"structural"),describe:chunkDPD6ZWL2_js.a(e=>`Rename content ${e.contentName} to ${e.newName}`,"describe"),apply:chunkDPD6ZWL2_js.a((e,t,n)=>Ee(e,t,n,r=>{let o=Ye(r,t.contentName);if(t.newName===t.contentName)return r;o.sourceDefinition!==null&&pe(["newName"],"Source-owned API names must be changed in their declaration"),Object.hasOwn(r.authoring.contents,t.newName)&&pe(["newName"],"Content API name is already used");let a=r.contentIds[t.contentName],s=r.contentRevisions[t.contentName];return delete r.authoring.contents[t.contentName],delete r.contentIds[t.contentName],delete r.contentRevisions[t.contentName],r.authoring.contents={...r.authoring.contents,[t.newName]:o},{...r,revision:r.revision+1,contentIds:{...r.contentIds,[t.newName]:a},contentRevisions:{...r.contentRevisions,[t.newName]:s+1}}}),"apply")},Us=zod.z.object({...gt,type:zod.z.literal("reset_view_content")}).strict(),Cm={type:"reset_view_content",summary:"Resets a content back to its code-declared source; only works when one exists.",schema:Us,focus:Me,presentation:B(Me,"structural"),describe:chunkDPD6ZWL2_js.a(e=>`Reset ${e.contentName} to source`,"describe"),apply:chunkDPD6ZWL2_js.a((e,t,n)=>Ee(e,t,n,r=>{let o=Ye(r,t.contentName);return o.sourceDefinition===null&&pe(["contentName"],"Content has no source to reset to"),o.workspaceDefinition===null&&!o.suppressed&&o.workspacePosition===null?r:(o.workspaceDefinition=null,o.suppressed=false,o.workspacePosition=null,{...r,revision:r.revision+1,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}})}),"apply")},qs=zod.z.object({...Pt,type:zod.z.literal("reset_view_order"),placement:zod.z.enum(["main","aside"]).describe("The placement zone to reset to source order")}).strict(),vm={type:"reset_view_order",summary:"Resets a placement zone's order to its code-declared source, if one exists.",schema:qs,focus:Ke,presentation:B(Ke,"structural"),describe:chunkDPD6ZWL2_js.a(e=>`Reset ${e.placement} order`,"describe"),apply:chunkDPD6ZWL2_js.a((e,t,n)=>Ee(e,t,n,r=>{let o=t.placement==="main"?"mainOrderCustomized":"asideOrderCustomized";if(!r.authoring[o])return r;r.authoring[o]=false;for(let a of r.contents.filter(s=>s.placement===t.placement)){let s=Ye(r,a.name);s.sourceDefinition!==null&&(s.workspacePosition=null);}return {...r,revision:r.revision+1}}),"apply")},no=zod.z.discriminatedUnion("type",[ks,Ps,Ms,Fs,Vs,Ls,$s,Us,qs]),He=[Am,xm,Tm,wm,Sm,Im,Rm,Cm,vm];function zs(e,t){return e.objects.find(n=>n.id===t)}chunkDPD6ZWL2_js.a(zs,"findObject");var Em=new Set(["formula","rollup"]);function yt(e){return Em.has(e.attributeType)}chunkDPD6ZWL2_js.a(yt,"isComputedAttribute");var Ws={sum:"number",avg:"number",count:"number",countValues:"number",countUniqueValues:"number",countEmpty:"number",percentEmpty:"number",percentNotEmpty:"number",earliest:"date",latest:"date",original:"multiselect"};function Nm(e){return typeof e=="string"&&e in Ws?Ws[e]:void 0}chunkDPD6ZWL2_js.a(Nm,"rollupReturnTypeOf");function Ks(e,t){let n=zs(e,t);if(!n)throw new chunkJSKLP4GI_js.h(`Object "${t}" is not in the draftable state`,[]);return n}chunkDPD6ZWL2_js.a(Ks,"requireObject");function En(e){return e.config??{}}chunkDPD6ZWL2_js.a(En,"configOf");function ee(e){let t=En(e).targets;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.object=="string"):[]}chunkDPD6ZWL2_js.a(ee,"relationTargets");function ht(e){let t=ee(e).filter(n=>n.object!==ae);return t.length===1?t[0]?.object:void 0}chunkDPD6ZWL2_js.a(ht,"relationTargetObjectName");function Dm(e){let t=En(e),n=e.attributeType,r={name:e.name,type:n,id:e.id},o=t.optionsSource;if(n==="relation"){let a=ht(e);return {...r,...t.cardinality==="one"||t.cardinality==="many"?{cardinality:t.cardinality}:{},...a===void 0?{}:{targetObjectName:a},targets:ee(e)}}if(n==="formula")return {...r,...t.returnType===void 0?{}:{returnType:t.returnType},...o===void 0?{}:{optionsSource:o}};if(n==="rollup"){let a=Nm(t.function);return {...r,...a===void 0?{}:{returnType:a},...o===void 0?{}:{optionsSource:o}}}return n==="select"||n==="status"||n==="multiselect"?{...r,...Array.isArray(t.options)?{options:t.options}:{}}:r}chunkDPD6ZWL2_js.a(Dm,"toCompileAttribute");function Gs(e,t){return {objectName:e.name,attributes:t.filter(n=>n.objectId===e.id).map(Dm)}}chunkDPD6ZWL2_js.a(Gs,"toCompileObject");function ro(e,t){let n=Ks(e,t);return {...Gs(n,e.attributes),relatedObjects:Object.fromEntries(e.objects.map(r=>[r.name,Gs(r,e.attributes)]))}}chunkDPD6ZWL2_js.a(ro,"computedCompileSchemaOf");function Om(e){return {id:e.id,name:e.name,label:e.label,type:"rollup",...En(e)}}chunkDPD6ZWL2_js.a(Om,"toRollupAttribute");function Ys(e){try{return e()}catch(t){throw t instanceof I?new chunkJSKLP4GI_js.h(t.message,[]):t}}chunkDPD6ZWL2_js.a(Ys,"asValidationError");function Nn(e,t){let n=ro(e,t.objectId);return Ys(()=>Hs(t,n))}chunkDPD6ZWL2_js.a(Nn,"computedPlanOf");function Hs(e,t){if(e.attributeType==="rollup")return Ya(Om(e),t);let n=En(e);return yn({attributeName:e.name,expression:String(n.expression??""),returnType:n.returnType,schema:t})}chunkDPD6ZWL2_js.a(Hs,"compilePlan");function io(e){Ys(()=>za(e.map(t=>({attributeName:t.attributeName,dependencies:t.dependencies}))));}chunkDPD6ZWL2_js.a(io,"assertAcyclicComputed");function jm(e,t){switch(e.kind){case "local":case "computed":return e.attributeName===t;case "relation":return e.relationName===t;case "options":return false;default:return e}}chunkDPD6ZWL2_js.a(jm,"dependencyNames");function Mt(e,t){let n=ro(e,t),r=[];for(let o of e.attributes)if(!(o.objectId!==t||!yt(o)))try{r.push(Hs(o,n));}catch(a){if(!(a instanceof I))throw a}return r}chunkDPD6ZWL2_js.a(Mt,"compilablePlansOf");function oo(e,t,n){let r=Ks(e,t),o=[];for(let a of Mt(e,t))a.attributeName!==n&&a.dependencies.some(s=>jm(s,n))&&o.push(a.attributeName);for(let a of e.objects)if(a.id!==t)for(let s of Mt(e,a.id))s.dependencies.some(u=>{if(u.kind!=="relation"||u.targetAttributeName!==n)return false;let l=e.attributes.find(m=>m.objectId===a.id&&m.name===u.relationName&&m.attributeType==="relation");return l!==void 0&&ht(l)===r.name})&&o.push(`${a.name}.${s.attributeName}`);return o}chunkDPD6ZWL2_js.a(oo,"dependentsOf");function we(e){let t=e.config?.bilateral;if(typeof t!="object"||t===null)return;let{object:n,attribute:r}=t;return typeof n=="string"&&typeof r=="string"?{object:n,attribute:r}:void 0}chunkDPD6ZWL2_js.a(we,"bilateralDeclarationOf");function km(e,t){return t!==void 0&&e.attributeType===t.attributeType&&_m(e,t)}chunkDPD6ZWL2_js.a(km,"sameAttribute");function _m(e,t){return JSON.stringify(e.config??{})===JSON.stringify(t.config??{})}chunkDPD6ZWL2_js.a(_m,"sameConfig");function Pm(e,t){let n=chunkDPD6ZWL2_js.a(r=>km(r,e.attributes.find(o=>o.id===r.id)),"untouched");for(let r of t.attributes){if(r.attributeType!=="relation")continue;let o=we(r);if(o===void 0||n(r))continue;let s=t.objects.find(b=>b.id===r.objectId)?.name??r.objectId,c=t.objects.find(b=>b.name===o.object),u=t.attributes.find(b=>b.objectId===c?.id&&b.name===o.attribute),l=`relation "${s}.${r.name}" declares inverse "${o.object}.${o.attribute}"`;if(u===void 0)throw new chunkJSKLP4GI_js.h(`${l}, which object "${o.object}" does not have; draft it first`,[]);if(u.attributeType!=="relation")throw new chunkJSKLP4GI_js.h(`${l}, which is not a relation`,[]);let m=we(u);if(!(ee(u).some(b=>b.object===s)&&(n(u)?m===void 0||m.object===s&&m.attribute===r.name:m?.object===s&&m.attribute===r.name)))throw new chunkJSKLP4GI_js.h(`${l}, which does not point back to "${s}.${r.name}"`,[])}}chunkDPD6ZWL2_js.a(Pm,"assertBilateralPairs");var Mm=0x100000001b3n,Fm=0xffffffffffffffffn;function Js(e,t){let n=t;for(let r of new TextEncoder().encode(e))n^=BigInt(r),n=n*Mm&Fm;return n}chunkDPD6ZWL2_js.a(Js,"fnv1a64");function ao(e,t){return Dn(t,e.toLowerCase())}chunkDPD6ZWL2_js.a(ao,"viewIdFor");function Dn(e,t){let n=`${t}:${e}`,r=Js(n,0xcbf29ce484222325n).toString(16).padStart(16,"0"),o=Js(`${e}:${n}`,0x84222325cbf29ce4n).toString(16).padStart(16,"0"),a=r+o,s=(Number.parseInt(a[16],16)&3|8).toString(16);return [a.slice(0,8),a.slice(8,12),`8${a.slice(13,16)}`,`${s}${a.slice(17,20)}`,a.slice(20,32)].join("-")}chunkDPD6ZWL2_js.a(Dn,"draftEntityIdFor");function Je(e){return {list:ao(e,"list"),detail:ao(e,"detail")}}chunkDPD6ZWL2_js.a(Je,"defaultViewIdsFor");function so(e,t,n,r){let a=r.filter(c=>c.objectId===n.id).filter(c=>chunkUKFOBZX2_js.j(X(c)).presentation.formField).map(c=>({attribute:c.name})),s=e==="collection"?[{name:"all",type:"collection",placement:"main",label:"All",layout:"table",source:{object:n.name}}]:a.length?[{name:"form",type:"form",placement:"main",label:"Details",groups:[{name:"general",label:"General",fields:a}]}]:[{name:"activity",type:"activity",placement:"main",label:"Activity"}];return {id:t,object:n.name,name:e==="collection"?"default_list":"default_detail",label:n.label,context:e,default:true,contents:s,authoring:Nt(s),revision:1,contentIds:Object.fromEntries(s.map(c=>[c.name,JSON.stringify(["draft-content",t,c.name])])),contentRevisions:Object.fromEntries(s.map(c=>[c.name,1])),derived:true}}chunkDPD6ZWL2_js.a(so,"derivedView");function co(e,t){let n=Je(e.id);return [so("collection",n.list,e,t),so("record",n.detail,e,t)]}chunkDPD6ZWL2_js.a(co,"defaultViewsFor");function Ft(e,t,n){return so(e.context,e.id,t,n)}chunkDPD6ZWL2_js.a(Ft,"regenerateDerived");function uo(e){return e.attributeType==="relation"&&X(e).metadata?.relationGenerated===true}chunkDPD6ZWL2_js.a(uo,"isGeneratedDraftRelation");function Qs(e,t){let n=we(t);if(!n)return [t];let r=e.objects.find(c=>c.id===t.objectId),o=e.objects.find(c=>c.name===n.object),a=e.attributes.find(c=>c.objectId===o?.id&&c.name===n.attribute);if(!a||a===t)return [t];let s=we(a);return s&&s.object===r?.name&&s.attribute===t.name?[t,a]:[t]}chunkDPD6ZWL2_js.a(Qs,"pairedDraftAttributes");function lo(e,t,n,r,o=false){let a=X(t),s=r&&X(r),c=r&&we(r),u=we(t);if(c&&(c.object!==u?.object||c.attribute!==u?.attribute))throw new chunkJSKLP4GI_js.h("Changing a bilateral address requires removing the existing pair first",[]);if(a.type!=="relation"||!a.bilateral)return e;let l=e.objects.find(k=>k.id===t.objectId),m=e.objects.find(k=>k.name===a.bilateral?.object);if(!(l&&m))throw new chunkJSKLP4GI_js.h("Both objects must exist before materializing a relation pair",[]);let d=`${l.name}.${t.name}`,g=a.bilateral.attribute,b=`${m.name}.${g}`,y=e.attributes.find(k=>k.objectId===m.id&&k.name===g),h=s?.metadata?.relationPairId,A=typeof h=="string"?h:Dn("relation-pair",`${n}:${t.id}`),E=[d,b].sort(),C=typeof h=="string"?{id:A,addresses:E,ownerAddress:s?.type==="relation"&&s.bilateral?.storageOwner===false?b:d,generatedAddresses:[],...d===b?{symmetric:true}:{}}:void 0,M=[...new Map([l,m].map(k=>[k.id,k])).values()].map(k=>({name:k.name,attributes:[t,...y&&y.id!==t.id?[y]:[]].filter(F=>F.objectId===k.id).map(X)})),P=Yi({objects:M,existingPairs:C?[C]:[],...r&&!o?{explicitAddresses:[d],propertyEditAddresses:[d]}:{},nextPairId:chunkDPD6ZWL2_js.a(()=>A,"nextPairId")}),fe=new Map;for(let k of P.objects){let F=k.name===l.name?l.id:m.id;for(let oe of k.attributes){let te=e.attributes.find(qt=>qt.objectId===F&&qt.name===oe.name),Ie=te?.id===t.id?r??te:te,Ac={...Vm(oe,te&&X(te)),metadata:{...oe.metadata,...Ie&&uo(Ie)&&!(o&&te?.id===t.id)||!te?{relationGenerated:true}:{}},id:te?.id??Dn("relation-attribute",`${A}:${F}:${oe.name}`),...te?{}:{order:e.attributes.filter(qt=>qt.objectId===F).length}};fe.set(`${F}.${oe.name}`,Zi(Ac,F));}}let L=e.attributes.map(k=>{let F=`${k.objectId}.${k.name}`,oe=fe.get(F);return fe.delete(F),oe??k});return L.push(...fe.values()),{...e,attributes:L,views:e.views.map(k=>{let F=[l,m].find(oe=>oe.name===k.object);return k.derived&&F?Ft(k,F,L):k})}}chunkDPD6ZWL2_js.a(lo,"reconcileDraftRelationAttribute");function Vm(e,t){if(e.type!=="relation"||!e.bilateral||t?.type!=="relation"||!t.bilateral)return e;let{label:n,cardinality:r,...o}=e.bilateral;return {...e,bilateral:{...o,...t.bilateral.label===void 0?{}:{label:n},...t.bilateral.cardinality===void 0?{}:{cardinality:r}}}}chunkDPD6ZWL2_js.a(Vm,"preserveDeclarationHints");function Fe(e,t){let n=e.objects.find(r=>r.id===t);if(!n)throw new chunkJSKLP4GI_js.h(`Object "${t}" is not in the draftable state`,[]);return n}chunkDPD6ZWL2_js.a(Fe,"requireObject");function po(e,t,n){return {...e,attributes:[...n],views:e.views.map(r=>r.derived&&r.object===t.name?Ft(r,t,n):r)}}chunkDPD6ZWL2_js.a(po,"withDerivedViews");function On(e){return {objectId:e.objectId}}chunkDPD6ZWL2_js.a(On,"objectFocus");function jn(e){return {objectId:e.objectId,recordId:e.recordId}}chunkDPD6ZWL2_js.a(jn,"recordFocus");function Zs(e){return {objectId:e.objectId,attributeName:e.name}}chunkDPD6ZWL2_js.a(Zs,"attributeFocus");function kn(e){return {objectId:e.objectId,attributeName:e.attribute}}chunkDPD6ZWL2_js.a(kn,"existingAttributeFocus");function Bm(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}chunkDPD6ZWL2_js.a(Bm,"firstChangedProperty");function Lm(e,t){if(!e.derived)for(let n of e.contents){if(n.type==="collection"&&(n.columns?.includes(t)||n.displayAttributes?.includes(t)||n.sorts?.some(r=>r.attribute===t)))return `content "${n.name}"`;if(n.type==="form"&&n.groups.some(r=>r.fields.some(o=>o.attribute===t)))return `content "${n.name}"`;if(n.type==="richtext"&&(n.attribute===t||n.titleAttribute===t))return `content "${n.name}"`}}chunkDPD6ZWL2_js.a(Lm,"handShapedUse");function $m(e,t,n){let r=n.config??{},o=n.name;if(r.relationPath!==void 0)throw new chunkJSKLP4GI_js.h(`rollup "${o}": relationPath is not supported yet`,[]);let a=r.relationAttribute;if(typeof a!="string"||a.length===0)throw new chunkJSKLP4GI_js.h(`rollup "${o}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let s=e.attributes.find(d=>d.objectId===t.id&&d.name===a&&d.attributeType==="relation");if(!s)throw new chunkJSKLP4GI_js.h(`rollup "${o}" needs a relation attribute; "${a}" is not a relation of object "${t.name}"`,[]);let c=ht(s);if(c===void 0){let d=ee(s).filter(g=>g.object!=="*").length;throw new chunkJSKLP4GI_js.h(`rollup "${o}" needs a relation with one target object; "${a}" targets ${d}`,[])}if(r.function==="count")return;let u=e.objects.find(d=>d.name===c),l=r.targetAttribute;if(!(u!==void 0&&e.attributes.some(d=>d.objectId===u.id&&d.name===l)))throw new chunkJSKLP4GI_js.h(`rollup "${o}" targets attribute "${l}", which object "${c}" does not have`,[])}chunkDPD6ZWL2_js.a($m,"assertRollupShape");function Um(e,t){let n=e.config??{};if(e.attributeType==="rollup")return n.relationAttribute===t;let r=typeof n.expression=="string"?n.expression:"";return new RegExp(`(^|[^A-Za-z0-9_])${t}\\.`).test(r)}chunkDPD6ZWL2_js.a(Um,"traversesRelation");function tc(e,t){let n=Fe(e,t.objectId);if(t.attributeType==="relation"){for(let o of ee(t))if(o.object!==ae&&!e.objects.some(a=>a.name===o.object))throw new chunkJSKLP4GI_js.h(`object "${o.object}" is unknown; create it first`,[]);let r=we(t)?.object;if(r!==void 0&&r!==ae&&!e.objects.some(o=>o.name===r))throw new chunkJSKLP4GI_js.h(`object "${r}" is unknown; create it first`,[]);for(let o of e.attributes)o.objectId!==t.objectId||!yt(o)||Um(o,t.name)&&Nn(e,o);}else if(yt(t))t.attributeType==="rollup"&&$m(e,n,t),Nn(e,t);else return;io(Mt(e,t.objectId));}chunkDPD6ZWL2_js.a(tc,"assertConfigFolds");var Qe={..._t,objectId:zod.z.string().uuid().describe("The object this operation acts on")},qm=zod.z.object({...Qe,objectId:zod.z.string().uuid().describe("Stable id for the new object; the server mints one when omitted"),type:zod.z.literal("add_object"),name:chunk2M4YXNYZ_js.i.describe("kebab-case plural API name (`purchase-orders`)"),label:zod.z.string().min(1).describe("Label people see"),icon:zod.z.string().min(1).optional().describe("Icon name")}),zm={type:"add_object",summary:"Creates an object: kebab-case plural name, icon from search_icons; folds in default_list/default_detail; reserved names are native objects.",schema:qm,apply:chunkDPD6ZWL2_js.a((e,t)=>{if(e.objects.some(r=>r.name===t.name))throw new chunkJSKLP4GI_js.h(`Object "${t.name}" already exists`,[]);if(e.objects.some(r=>r.id===t.objectId))throw new chunkJSKLP4GI_js.h(`Object id "${t.objectId}" is already taken`,[]);let n={id:t.objectId,name:t.name,label:t.label,...t.icon===void 0?{}:{icon:t.icon}};return {...e,objects:[...e.objects,n],views:[...e.views,...co(n,e.attributes)]}},"apply"),focus:On,presentation:B(On,"structural"),describe:chunkDPD6ZWL2_js.a(e=>`Cr\xE9e l'objet \xAB ${e.label} \xBB`,"describe")},Wm=zod.z.object({...Qe,type:zod.z.literal("update_object"),changes:zod.z.object({label:zod.z.string().min(1).optional().describe("New label"),icon:zod.z.string().min(1).optional().describe("New icon name from search_icons")}).refine(e=>Object.keys(e).length>0,"update_object needs at least one change").describe("\u22651 change")}),Xs=chunkDPD6ZWL2_js.a(e=>({objectId:e.objectId}),"updateObjectFocus"),Gm={type:"update_object",summary:"Updates an object's label and/or icon \u2014 no other field.",schema:Wm,apply:chunkDPD6ZWL2_js.a((e,t)=>(Fe(e,t.objectId),{...e,objects:e.objects.map(n=>n.id===t.objectId?{...n,...t.changes}:n)}),"apply"),focus:Xs,presentation:B(Xs,"atomic",Bm),describe:chunkDPD6ZWL2_js.a(e=>e.changes.label?`Renomme l'objet en \xAB ${e.changes.label} \xBB`:"Modifie l'objet","describe")},Km=zod.z.object({...Qe,type:zod.z.literal("remove_object")}),Ym={type:"remove_object",summary:"Removes an object; refused while a relation attribute targets it \u2014 remove it first.",schema:Km,apply:chunkDPD6ZWL2_js.a((e,t)=>{Fe(e,t.objectId);let n=e.objects.find(r=>r.id===t.objectId)?.name;for(let r of e.attributes){if(r.objectId===t.objectId||r.attributeType!=="relation"||!ee(r).some(a=>a.object===n))continue;let o=e.objects.find(a=>a.id===r.objectId);throw new chunkJSKLP4GI_js.h(`object "${n}" is targeted by attribute "${o?.name}.${r.name}"; remove that attribute first`,[])}return {...e,objects:e.objects.filter(r=>r.id!==t.objectId),attributes:e.attributes.filter(r=>r.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(r=>r.objectId!==t.objectId),views:e.views.filter(r=>r.object!==n)}},"apply"),focus:On,presentation:B(On,"structural"),describe:chunkDPD6ZWL2_js.a(e=>`Supprime l'objet ${e.objectId}`,"describe")},mo=Qt;function nc(e,t){try{chunk2M4YXNYZ_js.L(e,t);}catch(n){throw n instanceof chunkJSKLP4GI_js.h?new chunkJSKLP4GI_js.h(n.message,n.errors.map(r=>({...r,path:["config",...r.path??[]]}))):n}}chunkDPD6ZWL2_js.a(nc,"assertConfigParses");var Hm=zod.z.object({...Qe,type:zod.z.literal("add_attribute"),attributeId:zod.z.string().min(1),name:chunk2M4YXNYZ_js.m,label:zod.z.string().min(1),attributeType:zod.z.enum(mo),config:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}).superRefine((e,t)=>{try{nc(e.attributeType,e.config??{});}catch(n){if(n instanceof chunkJSKLP4GI_js.h){for(let r of n.errors)t.addIssue({code:"custom",message:r.message,path:[...r.path]});return}throw n}}),ec={..._t,type:zod.z.literal("add_attribute"),attributeId:zod.z.string().min(1).describe("Stable attribute id"),name:chunk2M4YXNYZ_js.m.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),label:zod.z.string().min(1).describe("Label people see")},fo=Object.fromEntries(chunk2M4YXNYZ_js.w.map(e=>[e,true])),_n=["text","richtext","number","checkbox","date","phone","currency","location","user"],Jm=zod.z.object(_n.reduce((e,t)=>(Object.assign(e,chunk2M4YXNYZ_js.K(t).omit(fo).shape),e),{})).strict(),Qm=mo.filter(e=>!_n.includes(e)),Zm=Object.fromEntries(_n.map(e=>[e,new Set(Object.keys(chunk2M4YXNYZ_js.K(e).omit(fo).shape))])),Xm=chunk2M4YXNYZ_js.x(Zm,"config key");function ef(e,t){Xm(e.attributeType,e.config,t,["config"]);}chunkDPD6ZWL2_js.a(ef,"refuseForeignSimpleConfigKeys");function tf(e){let t=chunk2M4YXNYZ_js.K(e).omit(fo);return (e==="relation"||e==="document"?t.extend({properties:chunk2M4YXNYZ_js.G.optional()}):t).strict()}chunkDPD6ZWL2_js.a(tf,"wireConfigFor");var nf=zod.z.discriminatedUnion("attributeType",[zod.z.object({...ec,objectId:zod.z.string().uuid(),attributeType:zod.z.enum(_n).describe("Attribute type"),config:Jm.optional().describe("Configuration of a simple attribute (text, number, date\u2026)")}).strict().superRefine(ef),...Qm.map(e=>zod.z.object({...ec,objectId:zod.z.string().uuid(),attributeType:zod.z.literal(e).describe("Attribute type"),config:tf(e).optional().describe(`Configuration of a ${e} attribute`)}).strict())]),rf={type:"add_attribute",summary:"Adds an attribute; relation/bilateral/rollup targets must pre-exist; no relationPath; formula needs returnType; cover new required attrs.",schema:Hm,wire:nf,apply:chunkDPD6ZWL2_js.a((e,t)=>{let n=Fe(e,t.objectId),r=e.attributes.find(c=>c.objectId===t.objectId&&c.name===t.name);if(r&&!uo(r))throw new chunkJSKLP4GI_js.h(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let o={id:r?.id??t.attributeId,objectId:t.objectId,name:t.name,label:t.label,attributeType:t.attributeType,...t.config===void 0?{}:{config:t.config}};for(let c of e.sampleRecords)c.objectId===t.objectId&&oc(c.id,o,c.values);let a=r?e.attributes.map(c=>c===r?o:c):[...e.attributes,o],s=po(e,n,a);return tc(s,o),lo(s,o,t.id,r,true)},"apply"),focus:Zs,presentation:B(Zs,"local"),describe:chunkDPD6ZWL2_js.a(e=>`Ajoute l'attribut \xAB ${e.label} \xBB`,"describe")},rc={...Qe,attribute:chunk2M4YXNYZ_js.m.describe("The attribute's API name on this object")};function ic(e,t,n,r){let o=Fe(e,t);if(n===void 0)throw new chunkJSKLP4GI_js.h(`${r} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let a=e.attributes.find(s=>s.objectId===t&&s.name===n);if(!a)throw new chunkJSKLP4GI_js.h(`Attribute "${n}" is not on object "${t}"`,[]);return {object:o,attribute:a}}chunkDPD6ZWL2_js.a(ic,"requireAttribute");var of=zod.z.object({...rc,type:zod.z.literal("update_attribute"),changes:zod.z.object({label:zod.z.string().min(1).optional().describe("New label"),config:zod.z.record(zod.z.string(),zod.z.unknown()).optional().describe("Whole config, replaced \u2014 same shape as add_attribute")}).refine(e=>Object.keys(e).length>0,"update_attribute needs at least one change").describe("\u22651 change")}),af={type:"update_attribute",summary:"Updates an attribute's label, or replaces its whole config; a published config can't change \u2014 add a new attribute and migrate values.",schema:of,apply:chunkDPD6ZWL2_js.a((e,t)=>{let{object:n,attribute:r}=ic(e,t.objectId,t.attribute,"update_attribute");t.changes.config!==void 0&&nc(r.attributeType,t.changes.config);let o={...r,...t.changes},a=e.attributes.map(c=>c===r?o:c),s=po(e,n,a);return tc(s,o),lo(s,o,t.id,r)},"apply"),focus:kn,presentation:B(kn,"atomic"),describe:chunkDPD6ZWL2_js.a(e=>e.changes.label?`Renomme l'attribut \xAB ${e.attribute} \xBB en \xAB ${e.changes.label} \xBB`:`Modifie l'attribut \xAB ${e.attribute} \xBB`,"describe")},sf=zod.z.object({...rc,type:zod.z.literal("remove_attribute")}),cf={type:"remove_attribute",summary:"Removes an attribute; refused while a sample carries its value, a content names it, or a formula/rollup depends on it \u2014 remove those first.",schema:sf,apply:chunkDPD6ZWL2_js.a((e,t)=>{let{attribute:n}=ic(e,t.objectId,t.attribute,"remove_attribute"),r=Qs(e,n);for(let s of r){let c=Fe(e,s.objectId),[u]=oo(e,s.objectId,s.name);if(u!==void 0)throw new chunkJSKLP4GI_js.h(`attribute "${s.name}" is used by "${u}"; remove that first`,[]);for(let m of e.views){if(m.object!==c.name)continue;let d=Lm(m,s.name);if(d!==void 0)throw new chunkJSKLP4GI_js.h(`attribute "${s.name}" is used by view "${m.id}" (${d}); remove it from the view first`,[])}let l=e.sampleRecords.find(m=>m.objectId===s.objectId&&s.name in m.values);if(l)throw new chunkJSKLP4GI_js.h(`Attribute "${s.name}" is still used by sample record "${l.id}"`,[])}let o=e.attributes.filter(s=>!r.includes(s)),a={...e,views:e.views.map(s=>s)};return r.reduce((s,c)=>po(s,Fe(e,c.objectId),o),a)},"apply"),focus:kn,presentation:B(kn,"local"),describe:chunkDPD6ZWL2_js.a(e=>`Supprime l'attribut \xAB ${e.attribute} \xBB`,"describe")};function uf(e,t,n,r){let o=X(n);try{chunkIBM4ID4Y_js.c(o);}catch{return}let a=chunkIBM4ID4Y_js.g(o,r);if(a.success)return;let s=a.errors??[],c=s.map(u=>u.path.length>1?`${u.path.join(".")}: ${u.message}`:u.message).join(", ");throw new chunkJSKLP4GI_js.h(`Sample record "${e}" has an invalid value for "${t}": ${c}`,s.map(u=>({path:u.path,message:u.message})))}chunkDPD6ZWL2_js.a(uf,"assertSampleValue");function oc(e,t,n){if(t.config?.required===true&&t.config?.defaultValue===void 0&&!(t.name in n&&n[t.name]!==void 0))throw new chunkJSKLP4GI_js.h(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}chunkDPD6ZWL2_js.a(oc,"assertRequiredCovered");function bo(e){return (Array.isArray(e)?e:[e]).flatMap(n=>{if(typeof n=="string")return [n];if(typeof n=="object"&&n!==null){let r=n.id;if(typeof r=="string")return [r]}return []})}chunkDPD6ZWL2_js.a(bo,"relationValueIds");function lf(e,t,n,r){n.attributeType!=="relation"||r===void 0||r===null||df(e,t,ht(n),r);}chunkDPD6ZWL2_js.a(lf,"assertUnknownSampleReference");function df(e,t,n,r){let o=e.objects.find(s=>s.name===n);if(!o)return;let a=e.views.some(s=>s.id===Je(o.id).list);for(let s of bo(r)){let c=e.sampleRecords.find(l=>l.id===s);if(c?.objectId!==o.id&&(c!==void 0||a))throw new chunkJSKLP4GI_js.h(`sample record "${t}" references unknown sample "${s}"`,[])}}chunkDPD6ZWL2_js.a(df,"assertSampleTarget");var pf=zod.z.object({...Qe,type:zod.z.literal("add_sample_record"),recordId:zod.z.string().uuid().describe("Minted by the server when omitted"),values:zod.z.record(zod.z.string(),zod.z.unknown()).describe("Attribute name \u2192 value; currency is `{code,value}`, relation is a record id or name minted here"),publication:zod.z.enum(["preview","requested-data"]).optional().describe("preview = display-only; requested-data = real records asked for")}),mf={type:"add_sample_record",summary:"Adds a sample record; keys are attribute names, required covered, computed never set; relation value is a minted/published recordId; publication is preview or requested-data.",schema:pf,apply:chunkDPD6ZWL2_js.a((e,t)=>{if(Fe(e,t.objectId),e.sampleRecords.some(r=>r.id===t.recordId))throw new chunkJSKLP4GI_js.h(`Sample record "${t.recordId}" already exists`,[]);let n=new Map(e.attributes.filter(r=>r.objectId===t.objectId).map(r=>[r.name,r]));for(let[r,o]of Object.entries(t.values)){let a=n.get(r);if(!a)throw new chunkJSKLP4GI_js.h(`Sample record "${t.recordId}" uses unknown attribute "${r}"`,[]);if(yt(a))throw new chunkJSKLP4GI_js.h(`attribute "${a.name}" is computed and cannot be set on a sample record`,[]);lf(e,t.recordId,a,o),uf(t.recordId,r,a,o);}for(let r of n.values())oc(t.recordId,r,t.values);return {...e,sampleRecords:[...e.sampleRecords,{id:t.recordId,objectId:t.objectId,values:t.values,...t.publication===void 0?{}:{publication:t.publication}}]}},"apply"),focus:jn,presentation:B(jn,"local"),describe:chunkDPD6ZWL2_js.a(()=>"Ajoute un exemple","describe")};function ff(e,t){return new Set([...e.attributes.filter(n=>n.objectId===t&&n.attributeType==="relation").map(n=>n.name)])}chunkDPD6ZWL2_js.a(ff,"relationNamesOf");function bf(e,t){for(let n of e.sampleRecords){if(n.id===t)continue;let r=ff(e,n.objectId);for(let[o,a]of Object.entries(n.values))if(r.has(o)&&bo(a).includes(t))throw new chunkJSKLP4GI_js.h(`sample record "${t}" is referenced by sample record "${n.id}"; remove that first`,[])}}chunkDPD6ZWL2_js.a(bf,"assertSampleNotReferenced");var gf=zod.z.object({...Qe,type:zod.z.literal("remove_sample_record"),recordId:zod.z.string().min(1).describe("recordId of the sample to remove")}),yf={type:"remove_sample_record",summary:"Removes a sample record; refused while another sample still references it.",schema:gf,apply:chunkDPD6ZWL2_js.a((e,t)=>{if(!e.sampleRecords.some(n=>n.id===t.recordId&&n.objectId===t.objectId))throw new chunkJSKLP4GI_js.h(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,[]);return bf(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(n=>n.id!==t.recordId)}},"apply"),focus:jn,presentation:B(jn,"local"),describe:chunkDPD6ZWL2_js.a(()=>"Retire un exemple","describe")},Ze=[zm,Gm,Ym,rf,af,cf,mf,yf];function hf(){let e=new Map;for(let t of [...Ze,...He]){if(e.has(t.type))throw new chunkJSKLP4GI_js.r("architect operation",t.type);e.set(t.type,t);}return e}chunkDPD6ZWL2_js.a(hf,"build");var Vt=hf(),Af=[...Vt.keys()];function Bt(e){let t=Vt.get(e.type);if(!t)throw new chunkJSKLP4GI_js.h(`Operation "${e.id}" has unknown type "${e.type}"`,[]);return t}chunkDPD6ZWL2_js.a(Bt,"defOf");function go(e,t,n={extensions:[]}){return t.reduce((r,o)=>Bt(o).apply(r,o,n),e)}chunkDPD6ZWL2_js.a(go,"applyOperations");function yo(e){return Bt(e).focus(e)}chunkDPD6ZWL2_js.a(yo,"focusOf");function xf(e,t){return e.map(n=>Bt(n).describe(n,t))}chunkDPD6ZWL2_js.a(xf,"describeOperations");function Tf(e){if(typeof e!="object"||e===null||!("type"in e))throw new chunkJSKLP4GI_js.h("An operation must be an object carrying a type",[]);let t=e.type;if(typeof t!="string")throw new chunkJSKLP4GI_js.h("An operation's type must be a string",[]);let n=Vt.get(t);if(!n)throw new chunkJSKLP4GI_js.h(`Unknown operation type "${t}"`,[]);let r=n.schema.safeParse(e);if(!r.success)throw new chunkJSKLP4GI_js.h(`Operation "${t}" is invalid: ${r.error.issues.map(o=>`${o.path.join(".")} ${o.message}`).join("; ")}`,[]);return r.data}chunkDPD6ZWL2_js.a(Tf,"parseOperation");var Lt=chunkDPD6ZWL2_js.a(e=>zod.z.tuple([zod.z.literal(e),zod.z.string()]),"pair"),wf=zod.z.union([zod.z.tuple([zod.z.literal("content"),zod.z.string(),zod.z.string(),zod.z.string()]),zod.z.tuple([zod.z.literal("view"),zod.z.string(),zod.z.string()]),zod.z.tuple([zod.z.literal("attribute"),zod.z.string(),zod.z.string()]),zod.z.tuple([zod.z.literal("sample"),zod.z.string(),zod.z.string()]),Lt("object"),Lt("object-name"),Lt("object-schema"),Lt("object-tree"),Lt("attribute-id")]);function $t(e){return e.viewName&&e.objectName?JSON.stringify(e.contentName?["content",e.objectName,e.viewName,e.contentName]:["view",e.objectName,e.viewName]):e.attributeName&&e.objectId?JSON.stringify(["attribute",e.objectId,e.attributeName]):e.attributeId?JSON.stringify(["attribute-id",e.attributeId]):e.recordId&&e.objectId?JSON.stringify(["sample",e.objectId,e.recordId]):e.objectId?JSON.stringify(["object",e.objectId]):e.objectName?JSON.stringify(["object-name",e.objectName]):null}chunkDPD6ZWL2_js.a($t,"proposalTargetKey");function ac(e,t,n,r){if(n&&typeof n=="object")if("source"in n&&n.source&&typeof n.source=="object"){let o=Yr(n.source);if(o&&o.kind!=="related"&&r(o.object),o?.kind==="related"){let a=o.relation;r(t);let s=e.objects.find(u=>u.name===t),c=e.attributes.find(u=>u.objectId===s?.id&&u.name===a);if(c?.attributeType==="relation"&&Array.isArray(c.config?.targets))for(let u of c.config.targets)u&&typeof u.object=="string"&&u.object!=="*"&&r(u.object);}}else "type"in n&&n.type==="forms"?r("objectName"in n&&typeof n.objectName=="string"?n.objectName:t):"type"in n&&["form","richtext","emails","meetings","documents"].includes(String(n.type))&&r(t);}chunkDPD6ZWL2_js.a(ac,"addContentDependencies");function Sf(e,t,n,r,o){if(["add_attribute","update_attribute","remove_attribute"].includes(t.type)){let a=e.attributes.find(c=>c.objectId===n.objectId&&c.name===n.attributeName),s=r&&typeof r=="object"&&"bilateral"in r?r.bilateral:a?.config?.bilateral;if((t.attributeType==="relation"||a?.attributeType==="relation")&&s&&typeof s=="object"&&"object"in s&&typeof s.object=="string"){n.objectId&&o("object-tree",n.objectId);let c=e.objects.find(u=>u.name===s.object);c?o("object-tree",c.id):o("object-name",s.object);}}}chunkDPD6ZWL2_js.a(Sf,"addBilateralDependencies");function If(e,t){let n=new Set,r=chunkDPD6ZWL2_js.a((...a)=>n.add(JSON.stringify(a)),"add"),o=chunkDPD6ZWL2_js.a(a=>{let s=e.objects.find(c=>c.name===a);s?r("object-schema",s.id):r("object-name",a);},"schemaFor");for(let a of t){let s=yo(a);if(a.type==="rename_view"||a.type==="rename_view_content"){let m=no.parse(a),d=$t({objectName:m.objectName,viewName:m.viewName,...m.type==="rename_view_content"?{contentName:m.contentName}:{}});d&&n.add(d);}let c=$t(s);if(c&&n.add(c),s.viewName&&s.objectName){a.type!=="replace_view_content"&&r("view",s.objectName,s.viewName);let m=e.objects.find(d=>d.name===s.objectName);if(m?r("object",m.id):r("object-name",s.objectName),ac(e,s.objectName,a.definition??a.content,o),a.type==="reset_view_content"&&typeof a.contentName=="string"){let d=e.views.find(g=>g.object===a.objectName&&g.name===a.viewName);ac(e,s.objectName,d?.authoring.contents[a.contentName]?.sourceDefinition,o);}}s.objectId&&r("object",s.objectId),s.objectId&&(a.type==="remove_object"||a.type.includes("sample_record"))&&r("object-tree",s.objectId),a.type==="add_object"&&typeof a.name=="string"&&r("object-name",a.name);let u=a.changes&&typeof a.changes=="object"?a.changes:null,l=a.type==="add_attribute"?a.config:u&&"config"in u?u.config:null;if(Sf(e,a,s,l,r),l&&typeof l=="object"&&"targets"in l&&Array.isArray(l.targets))for(let m of l.targets)m&&typeof m.object=="string"&&m.object!=="*"&&r("object-name",m.object);}return [...n]}chunkDPD6ZWL2_js.a(If,"requiredTargetKeys");function Rf(e,t){return Object.fromEntries(t.map(n=>[n,chunkRTHLB6T6_js.b(Pn(e,n))]))}chunkDPD6ZWL2_js.a(Rf,"targetTokensFor");function Pn(e,t){let n;try{n=JSON.parse(t);}catch{throw new chunkJSKLP4GI_js.h(`Invalid proposal target key "${t}"`,[])}let r=wf.safeParse(n);if(!r.success)throw new chunkJSKLP4GI_js.h(`Invalid proposal target key "${t}"`,[]);let[o,a,s,c]=r.data,u=e.objects.find(d=>d.id===a);if(o==="object")return u??null;if(o==="object-name")return e.objects.find(d=>d.name===a)??null;if(o==="attribute-id")return e.attributes.find(d=>d.id===a)??null;if(o==="attribute")return e.attributes.find(d=>d.objectId===a&&d.name===s)??null;if(o==="sample")return e.sampleRecords.find(d=>d.objectId===a&&d.id===s)??null;if(o==="object-schema"||o==="object-tree"){if(!u)return null;let d=e.attributes.filter(g=>g.objectId===a);return o==="object-schema"?{object:u,attributes:d.toSorted((g,b)=>g.name.localeCompare(b.name))}:{object:u,attributes:d,views:e.views.filter(g=>g.object===u.name),sampleRecords:e.sampleRecords.filter(g=>g.objectId===a)}}let l=e.views.find(d=>d.object===a&&d.name===s);if(!l)return null;if(o==="view")return {id:l.id,revision:l.revision,definition:{...bt(l),contents:l.contents.map(({name:d,placement:g})=>({name:d,placement:g}))}};let m=l.contents.find(d=>d.name===c);return c!==void 0&&Object.hasOwn(l.contentIds,c)?{id:l.contentIds[c],revision:l.contentRevisions[c],definition:m??null}:null}chunkDPD6ZWL2_js.a(Pn,"targetSnapshot");function Ut(e){return Bt(e).presentation(e)}chunkDPD6ZWL2_js.a(Ut,"presentationOf");function Cf(e){let t=e.map(Ut);return new Set(t.map(({focus:r})=>r.viewName?JSON.stringify([r.objectName,r.viewName]):r.objectId).filter(r=>r!==void 0)).size>1||t.some(({impact:r})=>r==="structural")?"structural":t.some(({impact:r})=>r==="local")?"local":"atomic"}chunkDPD6ZWL2_js.a(Cf,"episodeImpactOf");function sc(e,t){let n=$t(t);return n===null?null:Pn(e,n)}chunkDPD6ZWL2_js.a(sc,"snapshotArchitectTarget");function vf(e,t,n={extensions:[]}){let r=e;return t.map(o=>{let a=Ut(o),s=sc(r,a.focus);r=go(r,[o],n);let c=sc(r,a.focus);return {operationId:o.id,operationType:o.type,presentation:a,before:s,after:c,...o.note===void 0?{}:{note:o.note}}})}chunkDPD6ZWL2_js.a(vf,"deriveArchitectChanges");function Ve(e){return e.replace(/[%:/.]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}chunkDPD6ZWL2_js.a(Ve,"part");function Ef(e){let t=Nf(e);if(t===null)return null;let n=e.propertyPath??[];return n.length===0?t:`${t}/${n.map(Ve).join(".")}`}chunkDPD6ZWL2_js.a(Ef,"architectFocusKey");function Nf(e){return e.viewName&&e.objectName?e.contentName?["content",e.objectName,e.viewName,e.contentName].map(Ve).join(":"):["view",e.objectName,e.viewName].map(Ve).join(":"):e.attributeName&&e.objectId?["attribute",e.objectId,e.attributeName].map(Ve).join(":"):e.attributeId?["attribute-id",e.attributeId].map(Ve).join(":"):e.recordId&&e.objectId?["sample",e.objectId,e.recordId].map(Ve).join(":"):e.objectId?["object",e.objectId].map(Ve).join(":"):e.objectName?["object-name",e.objectName].map(Ve).join(":"):null}chunkDPD6ZWL2_js.a(Nf,"headOf");var me=zod.z.string().min(1),cc=zod.z.union([zod.z.object({objectName:me,viewName:me,contentName:me.optional()}).strict().describe("Full configuration of a view, or of one content when contentName is given"),zod.z.object({objectId:me}).strict().describe("An object with its attributes, by id"),zod.z.object({objectName:me}).strict().describe("An object with its attributes"),zod.z.object({objectId:me,attributeName:me}).strict().describe("One attribute's config, by name"),zod.z.object({objectId:me,attributeId:me}).strict().describe("One attribute's config, by id"),zod.z.object({objectId:me,recordId:me}).strict().describe("One sample record")]);function Df(e){let t=cc.safeParse(e);if(!t.success)throw new chunkJSKLP4GI_js.h("Invalid scoped target",[{path:["target"],message:"Expected exactly one named target branch"}]);return t.data}chunkDPD6ZWL2_js.a(Df,"parseNamedTarget");var ho=zod.z.object({type:zod.z.literal("remove_operation"),operationId:zod.z.string().min(1).describe("The id of a stored operation to drop from the draft")}),Of=12;function lc(e,t=[]){return [...e.map(n=>n.schema),...t].map(dc)}chunkDPD6ZWL2_js.a(lc,"membersOf");function jf(e,t){return Fn(e,n=>n.describe(t))}chunkDPD6ZWL2_js.a(jf,"describeMember");function uc(e,t=[]){return [...e.map(o=>o.wire??o.schema),...t].map(dc).map(Mf).map(Vf).map((o,a)=>{let s=e[a];return s===void 0?o:jf(o,s.summary)})}chunkDPD6ZWL2_js.a(uc,"wireMembersOf");function Mn(e){return zod.z.discriminatedUnion("type",e)}chunkDPD6ZWL2_js.a(Mn,"unionOf");function kf(e){return e instanceof zod.z.ZodString&&e.format==="uuid"}chunkDPD6ZWL2_js.a(kf,"isUuidString");function _f(e){let t=e;return !Array.isArray(t.options)||typeof t.def?.discriminator!="string"?null:{discriminator:t.def.discriminator,options:t.options}}chunkDPD6ZWL2_js.a(_f,"asUnionMember");function Fn(e,t){let n=_f(e);return n===null?t(e):zod.z.discriminatedUnion(n.discriminator,n.options.map(t))}chunkDPD6ZWL2_js.a(Fn,"mapMember");function dc(e){return Fn(e,t=>{let n={};for(let[r,o]of Object.entries(t.shape)){if(!kf(o))continue;let a=zod.z.string().min(1);n[r]=o.description===void 0?a:a.describe(o.description);}return Object.keys(n).length===0?t:t.safeExtend(n)})}chunkDPD6ZWL2_js.a(dc,"relaxUuidKeys");var Pf={add_object:["objectId"],add_sample_record:["recordId"]};function Mf(e){return Fn(e,t=>{let n={};for(let r of Pf[t.shape.type.value]??[]){let o=t.shape[r];o instanceof zod.z.ZodString&&(n[r]=o.optional());}return Object.keys(n).length===0?t:t.safeExtend(n)})}chunkDPD6ZWL2_js.a(Mf,"relaxMintedKeys");function Ff(e,t){let n=e._zod.def.checks;return !n||n.length===0?t:t.check(...n)}chunkDPD6ZWL2_js.a(Ff,"withOriginalChecks");function Vf(e){return Fn(e,t=>{if(t.shape.type.value==="add_object"||!("objectId"in t.shape))return t;let{objectId:n,...r}=t.shape,o=zod.z.object({...r,objectName:zod.z.string().min(1).describe("Object")}).strict();return Ff(t,o)})}chunkDPD6ZWL2_js.a(Vf,"addressByName");var Bf=lc(Ze,[ho]),Lf=lc(He),pc=Mn(Bf),mc=Mn(Lf),$f={schema:pc,view:mc},Uf={schema:Mn(uc(Ze,[ho])),view:Mn(uc(He))},qf=new Map([...Ze.map(e=>[e.type,"schema"]),["remove_operation","schema"],...He.map(e=>[e.type,"view"])]);function zf(e){return qf.get(e)??null}chunkDPD6ZWL2_js.a(zf,"familyOf");function Vn(e,t,n){return e.views.filter(r=>r.object===t.name&&r.context===n)}chunkDPD6ZWL2_js.a(Vn,"viewsOf");function bc(e,t){return Vn(e,t,"collection").flatMap(n=>n.contents).filter(n=>n.type==="collection")}chunkDPD6ZWL2_js.a(bc,"collectionContentsOf");function gc(e,t){return e.attributes.filter(n=>n.objectId===t.id)}chunkDPD6ZWL2_js.a(gc,"ownAttributes");function Wf(e){return chunkUKFOBZX2_js.j(X(e)).presentation.tableCell}chunkDPD6ZWL2_js.a(Wf,"isTableCell");function fc(e,t,n){return Vn(e,t,"record").some(r=>r.contents.some(o=>o.type===n))}chunkDPD6ZWL2_js.a(fc,"hasRecordContent");function yc(e,t){return e===2&&t<=5}chunkDPD6ZWL2_js.a(yc,"isEdgePayload");function Gf(e,t){let n=gc(e,t),r=n.filter(o=>o.attributeType==="relation");return yc(r.length,n.length)?!e.attributes.some(o=>o.attributeType==="relation"&&o.objectId!==t.id&&ee(o).some(a=>a.object===t.name)):false}chunkDPD6ZWL2_js.a(Gf,"looksLikeEdge");function Kf(e,t,n){return Vn(e,n,"record").some(r=>r.contents.some(o=>o.type==="collection"&&o.source.relation===t.name))}chunkDPD6ZWL2_js.a(Kf,"reciprocalExists");function Yf(e,t){let n=[],r=t?e.objects.filter(o=>t.has(o.id)):e.objects;for(let o of r){if(Gf(e,o)){n.push(`Object "${o.label}" is an edge (two relations plus scalars): qualify a relation with config.properties.definitions instead of an object.`);continue}let a=bc(e,o);a.length===0&&n.push(`Object "${o.label}" has no collection content: add_view_content.`);for(let s of gc(e,o))if(Wf(s)&&a.length&&!a.some(c=>c.columns===void 0||c.columns.includes(s.name))&&n.push(`Attribute "${s.label}" on "${o.label}" is in no collection column set: replace_view_content.`),s.attributeType==="document"&&!fc(e,o,"documents")&&n.push(`Object "${o.label}" has no documents content: add_view_content.`),s.attributeType==="relation")for(let{object:c}of ee(s)){let u=e.objects.find(l=>l.name===c);u&&!Kf(e,s,u)&&n.push(`Relation "${s.label}" on "${o.label}" has no reciprocal collection on "${u.label}": add_view_content with source.relation.`);}Vn(e,o,"record").length&&!fc(e,o,"activity")&&n.push(`Object "${o.label}" has no activity content on its record view: add_view_content.`),a.length===1&&n.push(`Object "${o.label}" has a single collection content; a person would add one to three that answer a question: add_view_content.`);}return n}chunkDPD6ZWL2_js.a(Yf,"stillMissing");function Hf(e,t){let n=new Set(t.flatMap(r=>r.type==="add_attribute"&&typeof r.attributeId=="string"?[r.attributeId]:[]));return e.attributes.filter(r=>n.has(r.id))}chunkDPD6ZWL2_js.a(Hf,"addedAttributes");function Jf(e,t){let n={next:[],needsColumns:[],regenerated:[]},r=new Set;for(let o of Hf(e,t)){let a=e.objects.find(l=>l.id===o.objectId);if(!a)continue;let s=e.views.filter(l=>l.object===a.name);if(!r.has(a.id)){r.add(a.id);for(let l of s.filter(m=>m.derived))for(let m of l.contents)n.regenerated.push(`${l.name}.${m.name}`);}for(let l of s.filter(m=>!m.derived&&m.context==="collection"))for(let m of l.contents)m.type==="collection"&&m.columns!==void 0&&!m.columns.includes(o.name)&&n.needsColumns.push({view:l.name,content:m.name,attribute:o.name});let c=s.some(l=>l.context==="record"&&l.contents.some(m=>m.type==="documents")),u=s.find(l=>l.context==="record");o.attributeType==="document"&&u&&!c&&n.next.push({type:"add_view_content",objectName:a.name,viewName:u.name,content:{name:"documents",type:"documents",placement:"main",label:"Documents"},target:{end:true}});}return n}chunkDPD6ZWL2_js.a(Jf,"guidanceForBatch");function Qf(e,t){let n=new Map(e.objects.map(o=>[o.name,o.id])),r=new Set;for(let o of t){let{focus:a}=Ut(o),s=a.objectId??(a.objectName?n.get(a.objectName):void 0);s!==void 0&&r.add(s);}return r}chunkDPD6ZWL2_js.a(Qf,"touchedObjectIds");function Zf(e){let t=e.config??{};if(e.attributeType==="relation")return `\u2192 ${ee(e).map(n=>n.object).join("|")}`;if(e.attributeType==="formula")return typeof t.expression=="string"?t.expression:void 0;if(e.attributeType==="rollup")return t.function==="count"?`count(${t.relationAttribute})`:`${t.function}(${t.relationAttribute}.${t.targetAttribute})`}chunkDPD6ZWL2_js.a(Zf,"attributeDetail");function Xf(e){let t=Xt({properties:e.config?.properties});if(t.length!==0)return t.map(n=>`${n.name}: ${n.type}`)}chunkDPD6ZWL2_js.a(Xf,"propertyLines");function eb(e){let t=e.config?.options,n=Zf(e),r=Xf(e);return {name:e.name,label:e.label,type:e.attributeType,...Array.isArray(t)?{options:t.map(o=>o.value)}:{},...n===void 0?{}:{detail:n},...r===void 0?{}:{properties:r}}}chunkDPD6ZWL2_js.a(eb,"summarizeAttribute");function tb(e,t,n){let r=Je(e.id),o=n.some(a=>a.id===r.list);return {id:e.id,name:e.name,label:e.label,attributes:t.filter(a=>a.objectId===e.id).map(eb),...o?{viewIds:r}:{}}}chunkDPD6ZWL2_js.a(tb,"summarizeObject");function nb(e,t){if(!t.some(n=>n.name===e.object))throw new chunkJSKLP4GI_js.h(`View "${e.name}" names an object outside the draft scope`,[]);return {id:e.id,name:e.name,context:e.context,objectName:e.object,label:e.label,derived:e.derived===true,contents:e.contents.map(({name:n,type:r,placement:o,label:a})=>({name:n,type:r,placement:o,label:a}))}}chunkDPD6ZWL2_js.a(nb,"summarizeView");function rb(e,t){let n=new Map;for(let r of e.sampleRecords)n.set(r.objectId,(n.get(r.objectId)??0)+1);return {objects:e.objects.map(r=>tb(r,e.attributes,e.views)),views:e.views.map(r=>nb(r,e.objects)),sampleRecords:[...n.entries()].map(([r,o])=>({objectId:r,count:o})),operationCount:t}}chunkDPD6ZWL2_js.a(rb,"summarizeDraft");var ib=["draft_schema"],ob="publish_architect_draft",ab="discard_architect_draft",sb="request_design_review",cb="get_architect_draft";var ub=[{input:{operations:[{type:"add_attribute",id:"op-statut",objectName:"devis",attributeId:"attr-statut",name:"statut",label:"Statut",attributeType:"select",config:{options:[{value:"draft",label:"Brouillon",color:"gray"},{value:"sent",label:"Envoy\xE9",color:"blue"},{value:"accepted",label:"Accept\xE9",color:"green"}]}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:"add_view_content",id:"op-open",objectName:"devis",viewName:"default_list",content:{name:"open",label:"\xC0 traiter",type:"collection",placement:"main",layout:"table",source:{object:"devis"},columns:["title","client","montant","statut"],filters:{combinator:"and",rules:[{attribute:"statut",operator:"is",value:"sent"}]},sorts:[{attribute:"montant",direction:"desc"}]},target:{end:true}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:"replace_view_content",id:"op-all",objectName:"devis",viewName:"default_list",contentName:"all",definition:{name:"all",type:"collection",placement:"main",layout:"table",source:{object:"devis"},columns:["title","client","montant","statut"]}}],guard:{revision:null,targetTokens:{}}}}];var ie=zod.z.string().refine(e=>e.trim().length>0,"Must not be blank"),hc=zod.z.union([zod.z.tuple([zod.z.literal("object"),ie]),zod.z.tuple([zod.z.literal("attribute"),ie,ie]),zod.z.tuple([zod.z.literal("view"),ie,ie]),zod.z.tuple([zod.z.literal("content"),ie,ie,ie])]),lb=zod.z.object({label:ie,pluralLabel:zod.z.string().optional(),description:zod.z.string().optional(),icon:chunk2M4YXNYZ_js.t.optional(),labelExpression:zod.z.string(),embeddingExpression:zod.z.string().optional(),sealed:zod.z.boolean().optional(),toleratedAttributes:zod.z.array(ie).optional(),metadata:zod.z.record(zod.z.string(),zod.z.unknown()).optional(),schema_version:zod.z.number().int().nonnegative(),migrations:zod.z.array(zod.z.record(zod.z.string(),zod.z.unknown())),documentLayout:zod.z.record(zod.z.string(),zod.z.unknown()).optional()}).strict();function Xe(e){throw new chunkJSKLP4GI_js.h(e,[])}chunkDPD6ZWL2_js.a(Xe,"failure");function db(e){return zod.z.custom(t=>{let n=zod.z.record(zod.z.string(),zod.z.unknown()).parse(t);for(let r of e[0]==="view"?["object","name"]:["name"])Object.hasOwn(n,r)&&Xe(`Invalid schema state: unrecognized definition key ${r}`);switch(e[0]){case "object":lb.parse(n);break;case "attribute":{let r=zod.z.enum(Qt).parse(n.type);chunk2M4YXNYZ_js.I(r).extend({type:zod.z.literal(r),label:ie,required:zod.z.boolean().optional(),unique:zod.z.boolean().optional(),icon:chunk2M4YXNYZ_js.t.optional()}).strict().parse(n);break}case "view":{let{contents:r,...o}=n,a=zod.z.array(ie).parse(r);new Set(a).size!==a.length&&Xe("Invalid schema state: duplicate content membership"),chunkUKFOBZX2_js._.parse({...o,object:e[1],name:e[2],contents:[]});break}case "content":chunkUKFOBZX2_js.W.parse({...n,name:e[3]});break}return true})}chunkDPD6ZWL2_js.a(db,"definitionSchema");function Bn(e,t){let n=JSON.stringify(e.address),r=JSON.stringify(t.address);return n<r?-1:n>r?1:0}chunkDPD6ZWL2_js.a(Bn,"compareSchemaStateEntries");function pb(e){return {modelVersion:1,hashVersion:1,entries:[...e].sort(Bn).filter(t=>t.source!==null).map(({address:t,source:n})=>({address:t,source:n}))}}chunkDPD6ZWL2_js.a(pb,"schemaStateSourcePayload");function mb(e){let t=zod.z.record(zod.z.string(),zod.z.unknown()).parse(e);for(let[a,s]of [["modelVersion","model"],["hashVersion","hash"]])t[a]!==1&&Xe(`Unsupported schema ${s} version: expected 1, received ${t[a]===void 0?"missing":String(t[a])}`);let n=zod.z.object({modelVersion:zod.z.literal(1),hashVersion:zod.z.literal(1),tenant:ie,sourceFingerprint:zod.z.string().regex(/^[a-f0-9]{64}$/),entries:zod.z.array(zod.z.unknown())}).strict().safeParse(e);if(!n.success){let a=n.error.issues.find(s=>s.code==="unrecognized_keys");throw a?.code==="unrecognized_keys"&&Xe(`Invalid schema state: unrecognized key ${a.keys[0]}`),chunkJSKLP4GI_js.h.fromZodErrors(n.error.issues.map(s=>({path:s.path.map(String),message:s.message})))}let r=new Set,o=n.data.entries.map(a=>{let s=hc.parse(zod.z.object({address:zod.z.unknown()}).parse(a).address),c=JSON.stringify(s);r.has(c)&&Xe(`Invalid schema state: duplicate address ${c}`),r.add(c);let u=db(s).nullable(),l=s[0]==="object"||s[0]==="attribute"?zod.z.object({id:zod.z.string().uuid(),updatedAt:zod.z.string().datetime()}).strict():zod.z.object({id:zod.z.string().uuid(),revision:zod.z.number().int().nonnegative()}).strict(),m=zod.z.object({address:hc,source:u,effective:u,status:zod.z.enum(["source","runtime","copy","suppressed"]),sourceOwner:zod.z.union([zod.z.literal("core"),zod.z.string().regex(/^(bundle|source):.+$/)]).nullable(),guard:l.nullable()}).strict().parse(a);(m.status==="runtime"&&(m.source!==null||m.effective===null||m.sourceOwner!==null)||m.status==="suppressed"&&(s[0]!=="content"||m.source===null||m.effective!==null||m.guard===null)||m.status==="copy"&&(m.source===null||m.effective===null)||m.effective!==null&&m.guard===null||m.source===null&&m.effective===null)&&Xe(`Invalid schema state: inconsistent status at ${c}`);let d=m.sourceOwner;d!==null&&d!=="core"&&!d.startsWith("bundle:")&&!d.startsWith("source:")&&Xe("Invalid source owner");let g=d===null||d==="core"?d:d.startsWith("bundle:")?`bundle:${d.slice(7)}`:`source:${d.slice(7)}`;return {...m,sourceOwner:g}});return {...n.data,entries:o.sort(Bn)}}chunkDPD6ZWL2_js.a(mb,"parseState");function fb(e){try{return mb(e)}catch(t){throw t instanceof zod.z.ZodError?chunkJSKLP4GI_js.h.fromZodErrors(t.issues.map(n=>({path:n.path.map(String),message:n.message}))):t}}chunkDPD6ZWL2_js.a(fb,"parseSchemaState");function bb(e){let t=[];for(let n of [...e.entries].sort(Bn)){let r=n.source===null?"added":n.status==="suppressed"?"suppressed":n.effective===null?"removed":chunkRTHLB6T6_js.b(n.source)!==chunkRTHLB6T6_js.b(n.effective)?"changed":n.status==="copy"?"copied":null;r&&t.push({...n,change:r});}return {modelVersion:1,tenant:e.tenant,sourceFingerprint:e.sourceFingerprint,changes:t}}chunkDPD6ZWL2_js.a(bb,"diffSchemaState");Object.defineProperty(exports,"NonJsonValueError",{enumerable:true,get:function(){return chunkRTHLB6T6_js.a}});Object.defineProperty(exports,"asTenantId",{enumerable:true,get:function(){return chunkRTHLB6T6_js.f}});Object.defineProperty(exports,"asUserId",{enumerable:true,get:function(){return chunkRTHLB6T6_js.g}});Object.defineProperty(exports,"canonicalStringify",{enumerable:true,get:function(){return chunkRTHLB6T6_js.b}});Object.defineProperty(exports,"deepEqual",{enumerable:true,get:function(){return chunkRTHLB6T6_js.j}});Object.defineProperty(exports,"generateId",{enumerable:true,get:function(){return chunkRTHLB6T6_js.h}});Object.defineProperty(exports,"indexBy",{enumerable:true,get:function(){return chunkRTHLB6T6_js.i}});Object.defineProperty(exports,"sameStableValue",{enumerable:true,get:function(){return chunkRTHLB6T6_js.e}});Object.defineProperty(exports,"serializeCanonicalJson",{enumerable:true,get:function(){return chunkRTHLB6T6_js.d}});Object.defineProperty(exports,"serializeStableJson",{enumerable:true,get:function(){return chunkRTHLB6T6_js.c}});Object.defineProperty(exports,"ATTRIBUTE_FILTER_OPERATORS",{enumerable:true,get:function(){return chunkUKFOBZX2_js.i}});Object.defineProperty(exports,"LOCATION_FILTER_PROPERTIES",{enumerable:true,get:function(){return chunkUKFOBZX2_js.f}});Object.defineProperty(exports,"NO_VALUE_OPERATORS",{enumerable:true,get:function(){return chunkUKFOBZX2_js.s}});Object.defineProperty(exports,"OPERATORS_BY_TYPE",{enumerable:true,get:function(){return chunkUKFOBZX2_js.r}});Object.defineProperty(exports,"REMOVED_OPERATOR_REPLACEMENTS",{enumerable:true,get:function(){return chunkUKFOBZX2_js.O}});Object.defineProperty(exports,"SYNONYM_ALIASES",{enumerable:true,get:function(){return chunkUKFOBZX2_js.G}});Object.defineProperty(exports,"SYSTEM_ATTRIBUTES",{enumerable:true,get:function(){return chunkUKFOBZX2_js.c}});Object.defineProperty(exports,"SYSTEM_ATTRIBUTE_I18N_KEYS",{enumerable:true,get:function(){return chunkUKFOBZX2_js.a}});Object.defineProperty(exports,"SYSTEM_FILTER_ATTRIBUTE_TYPES",{enumerable:true,get:function(){return chunkUKFOBZX2_js.N}});Object.defineProperty(exports,"canonicalizeFilterValue",{enumerable:true,get:function(){return chunkUKFOBZX2_js.F}});Object.defineProperty(exports,"collectQualifiedRuleIssues",{enumerable:true,get:function(){return chunkUKFOBZX2_js.P}});Object.defineProperty(exports,"collectionContentSourceSchema",{enumerable:true,get:function(){return chunkUKFOBZX2_js.V}});Object.defineProperty(exports,"columnsSchema",{enumerable:true,get:function(){return chunkUKFOBZX2_js.R}});Object.defineProperty(exports,"contentViewDefinitionSchema",{enumerable:true,get:function(){return chunkUKFOBZX2_js.$}});Object.defineProperty(exports,"contentViewDefinitionSchemaFor",{enumerable:true,get:function(){return chunkUKFOBZX2_js.Z}});Object.defineProperty(exports,"currentActor",{enumerable:true,get:function(){return chunkUKFOBZX2_js.w}});Object.defineProperty(exports,"displayAttributesSchema",{enumerable:true,get:function(){return chunkUKFOBZX2_js.S}});Object.defineProperty(exports,"draftContentViewDefinitionSchema",{enumerable:true,get:function(){return chunkUKFOBZX2_js._}});Object.defineProperty(exports,"draftContentViewDefinitionSchemaFor",{enumerable:true,get:function(){return chunkUKFOBZX2_js.Y}});Object.defineProperty(exports,"extractCurrencyFilterValue",{enumerable:true,get:function(){return chunkUKFOBZX2_js.z}});Object.defineProperty(exports,"extractFilterValue",{enumerable:true,get:function(){return chunkUKFOBZX2_js.A}});Object.defineProperty(exports,"filterStateSchema",{enumerable:true,get:function(){return chunkUKFOBZX2_js.U}});Object.defineProperty(exports,"getAttributeCapabilities",{enumerable:true,get:function(){return chunkUKFOBZX2_js.j}});Object.defineProperty(exports,"getAttributeFilterOperators",{enumerable:true,get:function(){return chunkUKFOBZX2_js.k}});Object.defineProperty(exports,"getOperatorPolarity",{enumerable:true,get:function(){return chunkUKFOBZX2_js.B}});Object.defineProperty(exports,"getRollupFilterOperators",{enumerable:true,get:function(){return chunkUKFOBZX2_js.u}});Object.defineProperty(exports,"getSystemAttributeI18nKey",{enumerable:true,get:function(){return chunkUKFOBZX2_js.b}});Object.defineProperty(exports,"getSystemAttributeList",{enumerable:true,get:function(){return chunkUKFOBZX2_js.d}});Object.defineProperty(exports,"isAttributeFilterable",{enumerable:true,get:function(){return chunkUKFOBZX2_js.l}});Object.defineProperty(exports,"isAttributeGroupable",{enumerable:true,get:function(){return chunkUKFOBZX2_js.o}});Object.defineProperty(exports,"isAttributeKanbanGroupable",{enumerable:true,get:function(){return chunkUKFOBZX2_js.p}});Object.defineProperty(exports,"isAttributeSearchable",{enumerable:true,get:function(){return chunkUKFOBZX2_js.m}});Object.defineProperty(exports,"isDynamicValue",{enumerable:true,get:function(){return chunkUKFOBZX2_js.v}});Object.defineProperty(exports,"isLocationFilterProperty",{enumerable:true,get:function(){return chunkUKFOBZX2_js.g}});Object.defineProperty(exports,"isLocationPartOperator",{enumerable:true,get:function(){return chunkUKFOBZX2_js.h}});Object.defineProperty(exports,"isManagedSystemAttribute",{enumerable:true,get:function(){return chunkUKFOBZX2_js.e}});Object.defineProperty(exports,"isNoValueOperator",{enumerable:true,get:function(){return chunkUKFOBZX2_js.t}});Object.defineProperty(exports,"isRelativeDateValue",{enumerable:true,get:function(){return chunkUKFOBZX2_js.J}});Object.defineProperty(exports,"isSetMembershipOperator",{enumerable:true,get:function(){return chunkUKFOBZX2_js.E}});Object.defineProperty(exports,"normalizeFilterRule",{enumerable:true,get:function(){return chunkUKFOBZX2_js.I}});Object.defineProperty(exports,"normalizeForEdgeRpc",{enumerable:true,get:function(){return chunkUKFOBZX2_js.C}});Object.defineProperty(exports,"normalizeOperator",{enumerable:true,get:function(){return chunkUKFOBZX2_js.H}});Object.defineProperty(exports,"now",{enumerable:true,get:function(){return chunkUKFOBZX2_js.y}});Object.defineProperty(exports,"publishedViewContentDefinitionSchema",{enumerable:true,get:function(){return chunkUKFOBZX2_js.W}});Object.defineProperty(exports,"resolveEffectiveFilterType",{enumerable:true,get:function(){return chunkUKFOBZX2_js.q}});Object.defineProperty(exports,"resolveIsWithinBounds",{enumerable:true,get:function(){return chunkUKFOBZX2_js.K}});Object.defineProperty(exports,"resolveUtcDayBounds",{enumerable:true,get:function(){return chunkUKFOBZX2_js.L}});Object.defineProperty(exports,"sortsSchema",{enumerable:true,get:function(){return chunkUKFOBZX2_js.T}});Object.defineProperty(exports,"toMultiValueOperator",{enumerable:true,get:function(){return chunkUKFOBZX2_js.D}});Object.defineProperty(exports,"toUtcDayString",{enumerable:true,get:function(){return chunkUKFOBZX2_js.M}});Object.defineProperty(exports,"today",{enumerable:true,get:function(){return chunkUKFOBZX2_js.x}});Object.defineProperty(exports,"validateQualifiedRule",{enumerable:true,get:function(){return chunkUKFOBZX2_js.Q}});Object.defineProperty(exports,"ComputedFormulaParseError",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.u}});Object.defineProperty(exports,"LIST_VIEW_TAB_VISIBILITIES",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.d}});Object.defineProperty(exports,"NATIVE_OBJECT_NAMES",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.a}});Object.defineProperty(exports,"OBJECT_NAME_SCHEMA",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.i}});Object.defineProperty(exports,"RESERVED_ATTRIBUTE_NAMES",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.g}});Object.defineProperty(exports,"RESERVED_OBJECT_NAMES",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.h}});Object.defineProperty(exports,"RESOURCE_VISIBILITIES",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.c}});Object.defineProperty(exports,"SCHEMA_LIMITS",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.r}});Object.defineProperty(exports,"SIMPLE_PROPERTY_TYPES",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.C}});Object.defineProperty(exports,"SYSTEM_FIELD_NAMES",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.f}});Object.defineProperty(exports,"WIRE_OMITTED_CONFIG_KEYS",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.w}});Object.defineProperty(exports,"attributeConfigSchemas",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.H}});Object.defineProperty(exports,"colorIdSchema",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.s}});Object.defineProperty(exports,"iconNameSchema",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.t}});Object.defineProperty(exports,"isNativeObjectName",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.b}});Object.defineProperty(exports,"multiselectOptionWriteSchema",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.A}});Object.defineProperty(exports,"parseAttributeConfig",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.J}});Object.defineProperty(exports,"parseAttributeConfigForCreate",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.L}});Object.defineProperty(exports,"parseAttributeConfigForUpdate",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.M}});Object.defineProperty(exports,"parseComputedFormula",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.v}});Object.defineProperty(exports,"parseResourceVisibility",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.e}});Object.defineProperty(exports,"propertyAttributeSchema",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.D}});Object.defineProperty(exports,"propertyAttributeWireSchema",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.F}});Object.defineProperty(exports,"propertySchemaSchema",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.E}});Object.defineProperty(exports,"propertySchemaWireSchema",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.G}});Object.defineProperty(exports,"refuseForeignKeys",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.x}});Object.defineProperty(exports,"selectOptionWriteSchema",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.z}});Object.defineProperty(exports,"statusGroupSchema",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.y}});Object.defineProperty(exports,"statusOptionWriteSchema",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.B}});Object.defineProperty(exports,"validateAttributeName",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.n}});Object.defineProperty(exports,"validateObjectName",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.j}});Object.defineProperty(exports,"validateViewName",{enumerable:true,get:function(){return chunk2M4YXNYZ_js.k}});Object.defineProperty(exports,"createFormAttributeValidator",{enumerable:true,get:function(){return chunkIBM4ID4Y_js.d}});Object.defineProperty(exports,"isNullishOrEmptyString",{enumerable:true,get:function(){return chunkIBM4ID4Y_js.a}});Object.defineProperty(exports,"isValuePresent",{enumerable:true,get:function(){return chunkIBM4ID4Y_js.b}});Object.defineProperty(exports,"rejectUnknownAttributesOrThrow",{enumerable:true,get:function(){return chunkIBM4ID4Y_js.l}});Object.defineProperty(exports,"validateDraft",{enumerable:true,get:function(){return chunkIBM4ID4Y_js.j}});Object.defineProperty(exports,"validateDraftOrThrow",{enumerable:true,get:function(){return chunkIBM4ID4Y_js.k}});Object.defineProperty(exports,"validateObject",{enumerable:true,get:function(){return chunkIBM4ID4Y_js.h}});Object.defineProperty(exports,"validateObjectOrThrow",{enumerable:true,get:function(){return chunkIBM4ID4Y_js.i}});Object.defineProperty(exports,"createCheckboxValidator",{enumerable:true,get:function(){return chunk47KVYDKG_js.a}});Object.defineProperty(exports,"createDateValidator",{enumerable:true,get:function(){return chunkKLR22JMC_js.a}});Object.defineProperty(exports,"AccessDeniedError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.C}});Object.defineProperty(exports,"AttributeInUseError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.I}});Object.defineProperty(exports,"AttributeNotFoundError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.e}});Object.defineProperty(exports,"ChangeTypeNotSupportedError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.q}});Object.defineProperty(exports,"ConcurrentModificationError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.A}});Object.defineProperty(exports,"DestructiveSyncNotAllowedError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.o}});Object.defineProperty(exports,"DuplicateError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.r}});Object.defineProperty(exports,"ForbiddenError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.x}});Object.defineProperty(exports,"MemoryNotFoundError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.G}});Object.defineProperty(exports,"MigrationTimeoutError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.p}});Object.defineProperty(exports,"NotFoundError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.c}});Object.defineProperty(exports,"NotImplementedError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.F}});Object.defineProperty(exports,"ObjectNotFoundError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.d}});Object.defineProperty(exports,"ObjectReferencedError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.J}});Object.defineProperty(exports,"OrphanSystemAttributeError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.n}});Object.defineProperty(exports,"ProtectedResourceError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.i}});Object.defineProperty(exports,"ProtectedRoleError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.y}});Object.defineProperty(exports,"RecordNotFoundError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.f}});Object.defineProperty(exports,"RecordReferencedError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.H}});Object.defineProperty(exports,"RepositoryError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.D}});Object.defineProperty(exports,"ReservedObjectNameError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.s}});Object.defineProperty(exports,"RoleNotFoundError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.z}});Object.defineProperty(exports,"SchemaError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.b}});Object.defineProperty(exports,"SchemaErrorCode",{enumerable:true,get:function(){return chunkJSKLP4GI_js.a}});Object.defineProperty(exports,"SchemaPlanNotFoundError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.g}});Object.defineProperty(exports,"SearchBackendError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.E}});Object.defineProperty(exports,"StorageError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.B}});Object.defineProperty(exports,"SyncCascadeError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.m}});Object.defineProperty(exports,"SyncConflictError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.l}});Object.defineProperty(exports,"SyncError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.j}});Object.defineProperty(exports,"SystemEntityImmutableError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.k}});Object.defineProperty(exports,"ValidationError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.h}});Object.defineProperty(exports,"isAttributeInUseError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.L}});Object.defineProperty(exports,"isNotFoundError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.u}});Object.defineProperty(exports,"isObjectReferencedError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.M}});Object.defineProperty(exports,"isProtectedResourceError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.w}});Object.defineProperty(exports,"isRecordReferencedError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.K}});Object.defineProperty(exports,"isSchemaError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.t}});Object.defineProperty(exports,"isValidationError",{enumerable:true,get:function(){return chunkJSKLP4GI_js.v}});Object.defineProperty(exports,"TEXT_FORMAT_PATTERNS",{enumerable:true,get:function(){return chunkXHEBV2HE_js.a}});Object.defineProperty(exports,"createTextValidator",{enumerable:true,get:function(){return chunkXHEBV2HE_js.c}});Object.defineProperty(exports,"resolveTextPattern",{enumerable:true,get:function(){return chunkXHEBV2HE_js.b}});Object.defineProperty(exports,"createNumberValidator",{enumerable:true,get:function(){return chunkSLYRQ72J_js.a}});Object.defineProperty(exports,"DEFAULT_VALIDATION_MESSAGES",{enumerable:true,get:function(){return chunkJFSQ24XR_js.a}});Object.defineProperty(exports,"formatZodErrors",{enumerable:true,get:function(){return chunkJFSQ24XR_js.b}});exports.AGENT_UI_BATCH_MAX_BYTES=SS;exports.AGENT_UI_BATCH_MAX_ITEMS=IS;exports.ALLOWED_PROPERTY_TYPES=ia;exports.ALL_ACTIONS=Qn;exports.ALL_OPERATION_TYPES=Af;exports.ALL_SYSTEM_RESOURCES=ux;exports.ARTIFACT_FILE_ROLES=Uy;exports.ARTIFACT_KINDS=Ly;exports.ARTIFACT_LIST_VIEW=kl;exports.ARTIFACT_OBJECT=Ol;exports.ARTIFACT_OBJECT_NAME=ut;exports.ARTIFACT_PREVIEW_EXTENSION=pn;exports.ARTIFACT_RETENTIONS=$y;exports.ARTIFACT_VIEW=jl;exports.ATTRIBUTE_TYPES=Qt;exports.AUDIT_ACTIONS=iy;exports.AUDIT_RESOURCE_TYPES=ry;exports.AgentBuilder=tr;exports.BEHAVIOR_PROPERTIES=Yg;exports.BYTE_UNIT_LABELS=gu;exports.CLAIMABLE_SESSION_STATUSES=nu;exports.COMPUTED_FUNCTIONS=jt;exports.COMPUTED_FUNCTION_METADATA=oI;exports.COMPUTED_FUNCTION_NAMES=LS;exports.CONNECTOR_CALLBACK_PARAM=jI;exports.COUNT_MODES=na;exports.ComputedFormulaCompileError=I;exports.ContentBuilder=ce;exports.DB_COLUMN_FIELDS=sx;exports.DEFAULT_AGENT_EXECUTION_CONFIG=fa;exports.DEFAULT_APPROVAL_POLICY=Go;exports.DEFAULT_DICTATION_LIMITS=Vy;exports.DEFAULT_LABEL_FALLBACK=sa;exports.DEFAULT_MEETING_BOT_DISPLAY_NAME=du;exports.DEFAULT_ROLES=Gu;exports.DEFAULT_ROLE_DESCRIPTIONS=px;exports.DEFAULT_ROLE_LABELS=dx;exports.DEFAULT_ROLE_PERMISSIONS=mx;exports.DEFAULT_TENANT_SETTINGS=hh;exports.DICTATION_FINALIZATION_TIMEOUT_MS=My;exports.DICTATION_FRAME_BYTES=Dy;exports.DICTATION_MAX_BUFFER_BYTES=jy;exports.DICTATION_MAX_FRAME_BYTES=Oy;exports.DICTATION_MAX_TRANSCRIPT_BYTES=ky;exports.DICTATION_MODEL_ID=Fy;exports.DICTATION_PREPARATION_TIMEOUT_MS=Py;exports.DICTATION_SAMPLE_RATE=Ny;exports.DICTATION_TICKET_TTL_MS=_y;exports.DISCARD_ARCHITECT_DRAFT_TOOL_NAME=ab;exports.DOCUMENT_SYSTEM_ATTRIBUTES=RA;exports.DRAFTABLE_ATTRIBUTE_TYPES=mo;exports.DRAFT_BATCH_LIMIT=Of;exports.DRAFT_SCHEMA_INPUT_EXAMPLES=ub;exports.DRAFT_WRITE_TOOL_NAMES=ib;exports.DRIVE_LIST_VIEW=Nl;exports.DRIVE_OBJECT=vl;exports.DRIVE_OBJECT_NAME=ct;exports.DRIVE_VIEW=El;exports.EMPTY_VALUE_PLACEHOLDER=tn;exports.ESTIMATED_COUNT_CAP=vh;exports.FAKE_MEETING_BOT_SIGNATURE_HEADER=WI;exports.FAMILY_INPUTS=$f;exports.FAMILY_WIRE_INPUTS=Uf;exports.FORM_FORBIDDEN_ATTRIBUTE_TYPES=Yn;exports.FlagRegistry=vt;exports.FlagService=dn;exports.FormBuilder=$r;exports.FormRegistry=Dt;exports.FormRowBuilder=Br;exports.FormStepBuilder=Lr;exports.GET_ARCHITECT_DRAFT_TOOL_NAME=cb;exports.GroupBuilder=Hr;exports.IDENTITY_PROPERTIES=Kg;exports.IMAGE_FORMATS=Sh;exports.INFERENCE_REASONING_OPTIONS=Ho;exports.INFERENCE_SPEEDS=Yo;exports.LIVE_EVENT_TYPES=Kl;exports.MAILBOX_LIST_MODES=Mp;exports.MAIL_DRAFT_BODY_MAX_CHARS=BI;exports.MAIL_SUBJECT_MAX_CHARS=LI;exports.MAX_PRESET_DEPTH=Zo;exports.MAX_TODOS=Ay;exports.MAX_TODO_DESCRIPTION_CHARS=Ty;exports.MAX_TODO_ID_CHARS=xy;exports.MEETING_ATTRIBUTES=v;exports.MEETING_DETAIL_VIEW_ID=Ea;exports.MEETING_LIST_VIEW=Ml;exports.MEETING_LIST_VIEW_ID=Ca;exports.MEETING_OBJECT=_l;exports.MEETING_OBJECT_NAME=lt;exports.MEETING_VIEW=Pl;exports.MEETING_WRITE_SOURCE=va;exports.MEMORY_LIST_VIEW=Cl;exports.MEMORY_OBJECT=Il;exports.MEMORY_VIEW=Rl;exports.McpOAuthCompletionMode=Pp;exports.MultiRelationAttributeBuilder=gr;exports.NATIVE_AGENT_UI_PART_IDS_METADATA_KEY=ou;exports.NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION=au;exports.NOTIFICATION_INBOX_STATES=Uo;exports.NOTIFICATION_KINDS=Bo;exports.NOTIFICATION_PRIORITIES=Lo;exports.NOTIFICATION_SENSITIVITIES=$o;exports.NOTIFICATION_TYPES_V1=Wg;exports.NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED=eu;exports.NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN=Zc;exports.NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED=Xc;exports.NOTIFICATION_WORK_STATES=qo;exports.NO_RECORDING=GI;exports.NoopGeocodingAdapter=ta;exports.OPEN_TOOL_PART_STATES=ru;exports.OPERATION_REGISTRY=Vt;exports.OPERATOR_SPECS=Rn;exports.ObjectBuilder=It;exports.PRESENTATION_PROPERTIES=Hg;exports.PROVIDER_NAMES=Ko;exports.PUBLISH_ARCHITECT_DRAFT_TOOL_NAME=ob;exports.QUALIFIED_SEPARATOR=jA;exports.QUOTA_KEYS=Dh;exports.RECORDING_OVERRIDES=qI;exports.RECORDING_POLICIES=zI;exports.RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY=pa;exports.RELATION_TARGET_ANY=ae;exports.REMOVE_OPERATION_SCHEMA=ho;exports.REPLY_MODES=Fp;exports.REQUEST_DESIGN_REVIEW_TOOL_NAME=sb;exports.SCHEMA_OPERATIONS=Ze;exports.SCHEMA_OPERATION_INPUT=pc;exports.SCHEMA_PLAN_LIMITS=de;exports.SCHEMA_SOURCE_ID_PATTERN=qi;exports.SESSION_STATE_STREAM_ID=Ry;exports.SESSION_TERMINAL_STATUSES=tu;exports.SKILL_CONTENT_TEMPLATE=Sa;exports.SKILL_LIST_VIEW=Tl;exports.SKILL_OBJECT=Al;exports.SKILL_VIEW=xl;exports.STANDARD_SCHEMA_VENDOR=Yu;exports.SYSTEM_PART_CODES=Kn;exports.SYSTEM_RESOURCES=ne;exports.SYSTEM_RESOURCE_LABELS=lx;exports.SingleRelationAttributeBuilder=br;exports.TODAY_DEFAULT=ss;exports.TODO_PLAN_STATUSES=py;exports.TODO_STATUSES=hy;exports.TOOL_APPROVAL_STATES=Jo;exports.USER_STATUSES=xh;exports.USER_WORK_POSTURES=Th;exports.VIEW_OPERATIONS=He;exports.VIEW_OPERATION_INPUT=mc;exports.ViewBuilder=un;exports.accessLevelToActions=ph;exports.actionsToAccessLevel=dh;exports.agent=xx;exports.agentDataChunk=_R;exports.agentDisplayName=my;exports.agentInferencePreferencesSchema=OR;exports.agentMessageAttachmentSchema=im;exports.agentMessagePartSchema=rm;exports.agentSessionInferenceOverridesInputSchema=nm;exports.agentSessionInferenceOverridesSchema=jR;exports.agentSessionMessageSchema=xs;exports.agentUIValidationError=dm;exports.applyOperations=go;exports.applyPipes=aa;exports.applyRelationProps=Vu;exports.architectDraftChannelKey=ES;exports.architectFocusKey=Ef;exports.assertAcyclicComputed=io;exports.assertAcyclicComputedDependencies=za;exports.assertBilateralPairs=Pm;exports.assertCustomAgentUIMessageChunk=pm;exports.assertSchemaSourceId=Lp;exports.bilateralDeclarationOf=we;exports.booleanFlag=ul;exports.buildAgentFallbackTitle=us;exports.buildPermissionFlags=Wu;exports.buildPropertySchema=en;exports.buildQualifiedAttribute=_A;exports.canonicalViewOperationSchema=no;exports.checkbox=ba;exports.collectContentViewCatalogue=Si;exports.collectSchemaReferences=xR;exports.collectionContentsOf=bc;exports.collectionSourceAddress=ze;exports.collectionSourceAddressOf=Yr;exports.compareAgentSessionMessages=iu;exports.compareSchemaStateEntries=Bn;exports.compilablePlansOf=Mt;exports.compileComputedFormula=yn;exports.compileRollupAttribute=Ya;exports.computeByteMagnitude=bu;exports.computedCompileSchemaOf=ro;exports.computedPlanOf=Nn;exports.content=D;exports.contentDefinition=Na;exports.contentExtensionRegistry=Ul;exports.conversationDisplayTitle=Bp;exports.createFlagRegistry=fl;exports.createFlagService=gl;exports.createStandardSchemaProps=on;exports.currency=kx;exports.customDataChunkSchemas=Rs;exports.date=se;exports.dateInTimezone=Cn;exports.dateValueStart=nt;exports.defaultViewIdsFor=Je;exports.defaultViewsFor=co;exports.defineOperation=Qi;exports.definePresentation=B;exports.dependentsOf=oo;exports.deriveArchitectChanges=vf;exports.deriveCreateDefaultsFromFilters=EI;exports.deriveInitials=qu;exports.describeOperations=xf;exports.destructiveSchema=fs;exports.detailView=ye;exports.diffSchemaState=bb;exports.document=ga;exports.draftedLabelExpression=Cs;exports.draftedObjectDefinition=Xi;exports.draftedViewDefinition=bt;exports.durableDateSchema=sm;exports.episodeImpactOf=Cf;exports.evaluateComputedAst=eI;exports.evaluateComputedFormula=tI;exports.evaluateComputedFormulaWithResult=nI;exports.evaluateFilterState=Ep;exports.evaluateRecordFilterState=xI;exports.extractAttributeNames=St;exports.extractValueRefs=da;exports.familyOf=zf;exports.findRelationAttribute=Da;exports.flagRegistry=ml;exports.focusOf=yo;exports.form=Gx;exports.formFieldFlatKey=lu;exports.formFieldKey=uu;exports.formRegistry=ka;exports.formatAgentStreamFrameId=AS;exports.formatAttributeValue=oa;exports.formatByteSize=wA;exports.formatComputedResult=Sp;exports.formatLocationValue=Su;exports.formula=Vx;exports.fromDraftableView=gm;exports.getEditableLabelAttribute=Mu;exports.getErrorMessage=Wy;exports.getLiveProtocolPayloadChannel=MS;exports.getRecordCreatorPrincipalId=zu;exports.getSingleAttributeFromExpression=la;exports.getSlotFieldTargets=ea;exports.getUserDisplayName=$u;exports.group=Ae;exports.guidanceForBatch=Jf;exports.hasDestructiveEntries=XI;exports.hasOptions=bh;exports.imageModelIdSchema=Ss;exports.includesAction=it;exports.inferInverseCardinality=Wo;exports.inferRollupReturnType=up;exports.inferenceReasoningSchema=Ji;exports.inferenceSpeedSchema=Hi;exports.isAgentUIDataName=lm;exports.isAgentUIMessageBatch=RS;exports.isAttributeSortable=ey;exports.isBilateralRelation=Xg;exports.isCheckboxEquality=uI;exports.isClaimableSessionStatus=dy;exports.isComputedAttribute=yt;exports.isComputedFunctionName=bn;exports.isDateRangeValue=Oe;exports.isDefaultRole=fx;exports.isDocumentAttribute=CA;exports.isEdgePayload=yc;exports.isEmptyObject=mu;exports.isFormDefinition=Hy;exports.isFormFieldsRow=Zt;exports.isFormFreeFieldRef=Hn;exports.isFormHeadingRow=nh;exports.isFormSeparatorRow=rh;exports.isFormSlotFieldRef=Xo;exports.isFormTextRow=ih;exports.isLabelExpression=rn;exports.isLiveEventEnvelope=FS;exports.isLiveEventPayload=jS;exports.isLiveEventPayloadForType=nd;exports.isLiveEventType=td;exports.isMailProvider=MI;exports.isMailboxListMode=FI;exports.isNotEmpty=ra;exports.isOpenToolPartState=fy;exports.isPlainRecord=Xa;exports.isReplyMode=VI;exports.isStandardSchema=Sx;exports.isSystemPartCode=gy;exports.isTerminalSessionStatus=ly;exports.isTerminalState=sy;exports.isToolApprovalState=by;exports.isUniversalRelation=zo;exports.jsonFlag=pl;exports.legacyStatusToSessionState=uy;exports.listView=he;exports.liveChannelKey=Pa;exports.location=Mx;exports.matchesAccepts=vA;exports.mentionReferenceSchema=om;exports.modelDefinitionSchema=am;exports.modelReferenceSchema=ws;exports.multiselect=Px;exports.namedTargetSchema=cc;exports.nativeAgentUIPartIdMetadataKey=cu;exports.normalizeDateValue=yu;exports.number=sn;exports.numberFlag=dl;exports.object=oT;exports.orderAgentSessionMessages=yy;exports.parseAgentStreamFrameId=xS;exports.parseCountMode=pu;exports.parseLiveChannelKey=Ma;exports.parseNamedTarget=Df;exports.parseNativeAgentUIPartIdsMetadata=Cy;exports.parseOperation=Tf;exports.parseOptionalCountMode=Ch;exports.parseQualifiedAttribute=kA;exports.parseSchemaState=fb;exports.persistedSchemaPlanSchema=pR;exports.phone=jx;exports.plannedAttributeSchema=qp;exports.plannedInlineAttributeSchema=zp;exports.plannedObjectSchema=Wp;exports.presentationOf=Ut;exports.proposalTargetKey=$t;exports.providerNameSchema=Ts;exports.qualifiedPropertyDefs=Lu;exports.readFormFieldValue=Xy;exports.reconcileRelationAttributes=Yi;exports.regenerateDerived=Ft;exports.registry=tw;exports.relation=ot;exports.relationAcceptsObject=Ti;exports.relationProperty=CT;exports.relationPropertyDefs=Bu;exports.relationTargetObjectName=ht;exports.relationTargets=ee;exports.relationTargetsOf=Zg;exports.relationValueIds=bo;exports.renderLabelExpression=Xn;exports.requestedCapabilities=OI;exports.requireRecordContentContext=Rt;exports.requireSingleRelationTarget=Oa;exports.requiredTargetKeys=If;exports.resolveAttributeDefaultValue=kp;exports.resolveCollectionActions=Zu;exports.resolveContentNavigation=Qu;exports.resolveFieldRequired=Zy;exports.resolvePropertyDefinitions=Xt;exports.resolveViewContents=xi;exports.richtext=je;exports.rollup=Bx;exports.rollupToFormulaExpression=cp;exports.schemaPlanSchema=dR;exports.schemaStateSourcePayload=pb;exports.select=be;exports.sessionInferencePatchSchema=kR;exports.sessionStateToLegacyStatus=cy;exports.status=_x;exports.stillMissing=Yf;exports.storedContentDefinition=Et;exports.stringFlag=ll;exports.summarizeDraft=rb;exports.targetSnapshot=Pn;exports.targetTokensFor=Rf;exports.text=S;exports.toAttribute=X;exports.toDraftableAttributes=fm;exports.toDraftableObject=mm;exports.toDraftableView=bm;exports.toUndefinedIfEmpty=fu;exports.todoItemSchema=cm;exports.todoPlanSchema=um;exports.toolImpactSchema=Is;exports.touchedObjectIds=Qf;exports.user=Fx;exports.validateContentViewCatalogue=Ii;exports.validateLabelExpression=Du;exports.validateObjectExpressions=Ju;exports.validateStoredViews=Bl;exports.viewIdFor=ao;exports.viewIdentityKey=yi;exports.viewRegistry=Fl;exports.workspaceViewAuthoring=Nt;
43
+ {{ summary }}`).attribute(text({name:I.title,label:`Title`}).required()).attribute(richtext({name:I.description,label:`Description`})).attribute(richtext({name:I.summary,label:`Summary`}).hidden()).attribute(richtext({name:I.transcript,label:`Transcript`}).hidden()).attribute(text({name:I.location,label:`Location`})).attribute(date({name:I.startsAt,label:`Starts at`}).includeTime()).attribute(date({name:I.endsAt,label:`Ends at`}).includeTime()).attribute(checkbox({name:I.isAllDay,label:`All day`})).attribute(select({name:I.status,label:`Status`}).options([{value:`confirmed`,label:`Confirmed`},{value:`tentative`,label:`Tentative`},{value:`cancelled`,label:`Cancelled`}])).attribute(text({name:I.organizerAddress,label:`Organizer address`}).email()).attribute(text({name:I.organizerName,label:`Organizer`})).attribute(text({name:I.conferenceProvider,label:`Conference provider`})).attribute(text({name:I.conferenceJoinUrl,label:`Join link`}).url()).attribute(text({name:I.htmlLink,label:`Open in calendar`}).url()).attribute(text({name:I.participants,label:`Participants`}).multiline()).attribute(text({name:I.providerEventId,label:`Provider event id`}).hidden()).attribute(text({name:I.icalUid,label:`iCal UID`}).hidden()).attribute(text({name:I.recurringEventId,label:`Recurring event id`}).hidden()).attribute(text({name:I.connectionId,label:`Connection id`})).attribute(select({name:I.recordingOverride,label:`Recording`}).options([{value:`force`,label:`Force`},{value:`skip`,label:`Skip`}]).hidden()).attribute(date({name:I.endedAnnouncedAt,label:`Ended announced at`}).includeTime().hidden()).attribute(relation({name:I.linkedRecords,label:`Linked records`}).toAny().many().qualifyWith(text({name:`source`,label:`Source`}).hidden())).build(),yt=markSystemView(detailView(gt,`Meeting`).for(F).default().tab(`description`,`Description`,M.richtext(I.description).titleAttribute(I.title)).tab(`summary`,`Summary`,M.richtext(I.summary)).tab(`transcript`,`Transcript`,M.richtext(I.transcript)).aside(`details`,`Details`,M.form(group(`details`,`Details`).fields(I.startsAt,I.endsAt,I.linkedRecords))).build()),bt=markSystemView(listView(mt,`Meetings`).for(F).default().tab(`workspace`,`Shared`,M.collection().object(F).table().icon(`users`).visibility(`workspace`).columns(..._t).sort(I.startsAt,`desc`)).tab(`mine`,`My meetings`,M.collection().object(F).table().icon(`lock`).visibility(`private`).columns(..._t).sort(I.startsAt,`desc`)).build());function viewIdentityKey(e,t){return JSON.stringify([e,t])}function cloneDeclaration(e){return structuredClone(e)}var ViewRegistry=class{constructor(){this.views=new Map,this.systemNames=new Map}register(e){let t=(Array.isArray(e)?e:[e]).map((e,t)=>this.prepare(e,t)),r=new Map,i=new Set;for(let{declaration:e}of t){let{object:t,name:a,context:o,default:s}=e.definition,c=r.get(t)??new Set;if((this.views.get(t)?.has(a)||c.has(a))&&this.throwDuplicate(t,a),c.add(a),r.set(t,c),!s)continue;let l=JSON.stringify([t,o]);if(this.getByObjectNameAndContext(t,o).some(e=>e.definition.default)||i.has(l))throw new n.DuplicateError(`default view`,l,`[ViewRegistry] Duplicate default view for object "${t}" in context "${o}"`);i.add(l)}for(let e of t)this.commit(e);return this}prepare(e,r){if(typeof e!=`object`||!e||e.kind!==`view`||Object.keys(e).some(e=>e!==`kind`&&e!==`definition`)){let e=`Expected an exact view declaration`;throw new n.ValidationError(e,[{path:[`views`,String(r)],message:e}])}let i=t.i.safeParse(e.definition);if(!i.success)throw n.ValidationError.fromZodErrors(i.error.issues.map(e=>({path:[`views`,String(r),`definition`,...e.path.map(String)],message:e.message})));return{declaration:cloneDeclaration(e),system:isSystemViewDefinition(e.definition)}}commit({declaration:e,system:t}){let{object:n,name:r}=e.definition,i=this.views.get(n)??new Map;if(i.set(r,e),this.views.set(n,i),t){let e=this.systemNames.get(n)??new Set;e.add(r),this.systemNames.set(n,e)}}getByObjectName(e){return Array.from(this.views.get(e)?.values()??[],cloneDeclaration)}getByObjectNameAndContext(e,t){return this.getByObjectName(e).filter(e=>e.definition.context===t)}get(e,t){let n=this.views.get(e)?.get(t);return n&&cloneDeclaration(n)}getOrThrow(e,t){let r=this.get(e,t);if(r)return r;let i=this.getByObjectName(e).map(({definition:e})=>`${e.name} (${e.context})`).join(`, `)||`(none)`;throw new n.NotFoundError(`View`,`${e}:${t}`,void 0,`[ViewRegistry] View "${t}" not found for object "${e}".\nAvailable views: ${i}`)}getAll(){return Array.from(this.views.values()).flatMap(e=>Array.from(e.values(),cloneDeclaration))}has(e,t){return this.views.get(e)?.has(t)??!1}hasObject(e){return this.views.has(e)}get size(){let e=0;for(let t of this.views.values())e+=t.size;return e}listObjectNames(){return Array.from(this.views.keys())}getDefault(e,t){let n=this.getByObjectNameAndContext(e,t);return n.find(e=>e.definition.default)??n[0]}isSystem(e,t){return this.systemNames.get(e)?.has(t)??!1}isSystemDeclaration(e){return this.isSystem(e.definition.object,e.definition.name)}clear(){this.views.clear(),this.systemNames.clear()}summary(){let e=[`[ViewRegistry] ${this.size} view(s) registered:`];for(let t of this.listObjectNames()){let n=this.getByObjectName(t).map(({definition:e})=>{let t=e.default?` (default)`:``;return`${e.name}:${e.context}${t}`});e.push(` ${t}: ${n.join(`, `)}`)}return e.join(`
44
+ `)}debug(e){let t=this.summary();return e?.(t),t}throwDuplicate(e,t){let r=viewIdentityKey(e,t);throw new n.DuplicateError(`view`,r,`[ViewRegistry] Duplicate view: "${t}" for object "${e}"`)}};const xt=new ViewRegistry;function contentDefinition(e,t){if(t.suppressed)return null;let n=t.workspaceDefinition??t.sourceDefinition;return n===null?null:{...structuredClone(n),name:e}}function storedContentDefinition(e){let{name:t,...n}=e;return structuredClone(n)}function workspaceViewAuthoring(e){let t={main:0,aside:0};return{origin:`runtime`,mainOrderCustomized:!1,asideOrderCustomized:!1,contents:Object.fromEntries(e.map(e=>[e.name,{sourceDefinition:null,workspaceDefinition:storedContentDefinition(e),suppressed:!1,sourcePosition:null,workspacePosition:t[e.placement]++}]))}}function resolveViewContents(e){let t=Object.entries(e.contents).flatMap(([e,t])=>{let n=contentDefinition(e,t);return n?[{definition:n,...t}]:[]});return[`main`,`aside`].flatMap(n=>{let r=n===`main`?e.mainOrderCustomized:e.asideOrderCustomized;return t.filter(e=>e.definition.placement===n).sort((e,t)=>{let n=r?e.workspacePosition:e.sourcePosition,i=r?t.workspacePosition:t.sourcePosition;if(n!==null&&i!==null&&n!==i)return n-i;if(n!==null&&i===null)return-1;if(i!==null&&n===null)return 1;let a=e.sourcePosition??e.workspacePosition,o=t.sourcePosition??t.workspacePosition;return a!==null&&o!==null&&a!==o?a-o:a!==null&&o===null?-1:o!==null&&a===null?1:e.definition.name.localeCompare(t.definition.name)}).map(e=>e.definition)})}function findRelationAttribute(e,t){return e.attributes.find(e=>e.name===t&&e.type===`relation`)}function relationAcceptsObject(e,t){return e.targets.some(e=>e.object===t||e.object===`*`)}function requireSingleRelationTarget(e,t=[e.name,`targets`]){if(e.targets.length!==1||e.targets[0].object===`*`){let r=`Relation "${e.name}" requires one concrete collection target`;throw new n.ValidationError(r,[{path:t,message:r}])}return e.targets[0].object}function violationOf(e,t,r,i,a=`catalogue`){if(!(e instanceof n.SchemaError))throw e;let o=e instanceof n.ValidationError?e.errors[0]:void 0;return{key:JSON.stringify([t,r,e.code,e.message]),rule:a,contentName:r,path:o?.path??i,message:e.message,code:e.code,error:e}}const St=new Map(t.$().map(e=>[e.name,e]));function reject$2(e,t){throw new n.ValidationError(t,[{path:e,message:t}])}function requireName(e,t){e.trim().length===0&&reject$2(t,`API name must not be empty`)}function indexUnique(e,t,r){let i=new Map;return e.forEach((e,a)=>{if(requireName(e.name,[...r,String(a),`name`]),i.has(e.name))throw new n.DuplicateError(t,e.name);i.set(e.name,e)}),i}function requireAttribute$1(e,t,n,r,i){if(requireName(t,n),!e)return;let a=e.attributes?.get(t)??St.get(t);if(!a){if(!e.attributes)return;let r=[...e.attributes.keys()].slice(0,30),a=r.length===0?`Object "${e.name}" has no attributes yet.`:`Attributes of "${e.name}": ${r.join(`, `)}`;reject$2(n,`Unknown attribute "${e.name}.${t}". ${a}${i?.()??``}`)}return r&&a.type!==r&&reject$2(n,`Attribute "${e.name}.${t}" must have type ${r}`),a}function collectContentViewCatalogue(e){let r=e.mode??`published`,i=new Map;e.objects.forEach((e,t)=>{if(requireName(e.name,[`objects`,String(t),`name`]),i.has(e.name))throw new n.DuplicateError(`object`,e.name);i.set(e.name,{name:e.name,attributes:indexUnique(e.attributes,`attribute`,[`objects`,String(t),`attributes`])})});let a=new Set;(e.reservedObjects??[]).forEach((e,t)=>{let n=[`reservedObjects`,String(t)];requireName(e,n),!i.has(e)&&(r!==`draft`&&reject$2(n,`Unresolved reserved object "${e}"`),a.add(e),i.set(e,{name:e}))});let o=indexUnique(e.extensions??[],`extension`,[`extensions`]);function resolveObject(e,t){requireName(e,t);let n=i.get(e);return n||reject$2(t,`Unknown object "${e}"`),n}function inverseAddresses(e){let t=[];for(let[n,r]of i)if(n!==e)for(let i of r.attributes?.values()??[])i.type===`relation`&&relationAcceptsObject(i,e)&&t.push(`relatedFrom("${n}", "${i.name}")`);return t.sort().slice(0,3)}let s=r===`draft`?t.c({asideRule:`tolerate`}):t.a({asideRule:`tolerate`}),c=new Map,l=new Map,u=[],d=[];function parseView(e,t){let r=s.safeParse(e);if(!r.success)throw new n.ValidationError(`Invalid content view`,r.error.issues.map(e=>({path:[...t,...e.path.map(String)],message:e.message,code:e.code})));let i=r.data;requireName(i.name,[...t,`name`]);let a=c.get(i.object)??new Set;if(a.has(i.name))throw new n.DuplicateError(`view`,`${i.object}.${i.name}`);if(a.add(i.name),c.set(i.object,a),i.default){let e=l.get(i.object)??new Set;if(e.has(i.context))throw new n.DuplicateError(`default view`,`${i.object}.${i.context}`);e.add(i.context),l.set(i.object,e)}return i}return e.views.forEach((e,r)=>{let i=[`views`,String(r)],a=e,s=`${String(a?.object??`?`)}.${String(a?.name??r)}`,c,l;try{c=parseView(e,i),l=resolveObject(c.object,[...i,`object`])}catch(e){u.push(violationOf(e,s,null,i));return}for(let e of t.t(c)){let t=new n.ValidationError(e.message,[{path:[...i,...e.path.map(String)],message:e.message}]);u.push(violationOf(t,s,e.contentName,i,`aside`))}c.contents.forEach((e,t)=>{let n=[...i,`contents`,String(t)];try{requireName(e.name,[...n,`name`]),validateContent(e,n,l,c.context,o,resolveObject,inverseAddresses)}catch(t){u.push(violationOf(t,s,e.name,n))}}),d.push(c)}),{views:d,unresolvedObjects:[...a].sort(),violations:u}}function validateStoredViews(e){let t=collectContentViewCatalogue(e).violations.find(e=>e.rule!==`aside`);if(t)throw t.error}function validateContentViewCatalogue(e){let{views:t,unresolvedObjects:n,violations:r}=collectContentViewCatalogue(e),i=r[0];if(i)throw i.error;return{views:t,unresolvedObjects:n}}function validateContent(e,t,r,i,a,o,s){function requireRecord(){requireRecordContentContext(e.name,i,t)}if(e.type===`custom`){let r=a.get(e.extension);r||reject$2([...t,`extension`],`Unknown extension "${e.extension}"`),r.requiresRecord&&requireRecord();let i=r.parameters.safeParse(structuredClone(e.parameters??{}));if(!i.success)throw new n.ValidationError(`Invalid extension parameters`,i.error.issues.map(e=>({path:[...t,`parameters`,...e.path.map(String)],message:e.message,code:e.code})));return}if(e.type===`collection`){let n=collectionSourceAddress(e.source),i,a;if(n.kind===`object`)i=o(n.object,[...t,`source`,`object`]);else if(n.kind===`related`){requireRecord();let e=[...t,`source`,`relation`],hint=()=>{if(!r)return``;let e=s(r.name);return e.length===0?``:`. Records pointing at "${r.name}" are addressed from the other side: ${e.join(`, `)}`},c=requireAttribute$1(r,n.relation,e,`relation`,hint);c?.type===`relation`&&(a=c,i=o(requireSingleRelationTarget(c,e),e))}else{requireRecord(),i=o(n.object,[...t,`source`,`object`]);let a=[...t,`source`,`relation`],s=requireAttribute$1(i,n.relation,a,`relation`);if(s?.type===`relation`&&r&&!relationAcceptsObject(s,r.name)){let e=s.targets.map(e=>`"${e.object}"`).join(`, `);reject$2(a,`Relation "${n.object}.${n.relation}" targets ${e}, not "${r.name}"`)}e.filters?.combinator===`or`&&reject$2([...t,`filters`,`combinator`],`Collection "${e.name}" addresses "${n.object}" from the far side, so its filters must use the "and" combinator`)}e.columns?.forEach((e,n)=>{let r=[...t,`columns`,String(n)];if(typeof e==`string`){requireAttribute$1(i,e,r);return}let o=[...r,`relationProperty`];a||reject$2(o,`Relation property columns require a relation source`),a.properties?.definitions.some(t=>t.name===e.relationProperty)||reject$2(o,`Unknown relation property "${e.relationProperty}"`)}),e.displayAttributes?.forEach((e,n)=>requireAttribute$1(i,e,[...t,`displayAttributes`,String(n)])),e.sorts?.forEach((e,n)=>requireAttribute$1(i,e.attribute,[...t,`sorts`,String(n),`attribute`])),e.filters?.rules.forEach((e,n)=>requireAttribute$1(i,e.attribute,[...t,`filters`,`rules`,String(n),`attribute`])),e.descriptionAttribute!==void 0&&requireAttribute$1(i,e.descriptionAttribute,[...t,`descriptionAttribute`]),e.layout===`kanban`&&e.groupByAttribute!==void 0&&requireAttribute$1(i,e.groupByAttribute,[...t,`groupByAttribute`]);return}switch(requireRecord(),e.type){case`form`:e.groups.forEach((e,n)=>{let i=[...t,`groups`,String(n)];requireName(e.name,[...i,`name`]),e.fields.forEach((e,t)=>requireAttribute$1(r,e.attribute,[...i,`fields`,String(t),`attribute`]))});break;case`richtext`:requireAttribute$1(r,e.attribute,[...t,`attribute`],`richtext`),e.titleAttribute!==void 0&&requireAttribute$1(r,e.titleAttribute,[...t,`titleAttribute`],`text`);break;case`emails`:case`meetings`:e.emailAttributes.forEach((e,n)=>requireAttribute$1(r,e,[...t,`emailAttributes`,String(n)],`text`));break;case`documents`:e.relations?.forEach((e,n)=>requireAttribute$1(r,e,[...t,`relations`,String(n)],`relation`));break;case`forms`:e.objectName!==void 0&&o(e.objectName,[...t,`objectName`]);break;case`activity`:break;default:reject$2(t,`Unknown content type: ${String(e)}`)}}const Ct=[Object.freeze(ut)];var ContentExtensionRegistry=class{constructor(){this.extensions=new Map,this.seed()}register(e){let t=Array.isArray(e)?e:[e],r=new Set;t.forEach((e,t)=>{if(this.prepare(e,t),r.has(e.name))throw new n.DuplicateError(`content extension`,e.name);r.add(e.name)});for(let e of t)this.extensions.set(e.name,e);return this}prepare(e,t){let r=[`extensions`,String(t)],reject=e=>{throw new n.ValidationError(e,[{path:r,message:e}])};if((typeof e!=`object`||!e||Array.isArray(e))&&reject(`Expected a content extension declaration`),Object.keys(e).some(e=>e!==`name`&&e!==`parameters`&&e!==`requiresRecord`)&&reject(`Expected exactly name, parameters and requiresRecord`),(typeof e.name!=`string`||e.name.trim().length===0)&&reject(`API name must not be empty`),typeof e.requiresRecord!=`boolean`&&reject(`requiresRecord must be a boolean`),typeof e.parameters?.safeParse!=`function`&&reject(`parameters must be a Zod schema`),this.extensions.has(e.name))throw new n.DuplicateError(`content extension`,e.name)}get(e){return this.extensions.get(e)}has(e){return this.extensions.has(e)}getAll(){return[...this.extensions.values()]}get size(){return this.extensions.size}clear(){this.extensions.clear(),this.seed()}seed(){for(let e of Ct)this.extensions.set(e.name,e)}};const wt=new ContentExtensionRegistry;function cloneFormDefinition(e){return structuredClone(e)}var FormRegistry=class{constructor(){this.forms=new Map}register(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.forms.has(e.name))throw new n.DuplicateError(`form`,e.name,`[FormRegistry] Duplicate form: "${e.name}"`);this.forms.set(e.name,cloneFormDefinition(e))}return this}get(e){let t=this.forms.get(e);return t?cloneFormDefinition(t):void 0}getAll(){return Array.from(this.forms.values(),cloneFormDefinition)}listNames(){return Array.from(this.forms.keys())}};const Tt=new FormRegistry;function formatAgentStreamFrameId(e,t){return`${e}:${t}`}function parseAgentStreamFrameId(e){let t=e.lastIndexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=Number(e.slice(t+1));return!Number.isInteger(r)||r<=0?null:{streamId:n,sequence:r}}function isRecord$2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hasExactKeys(e,t){let n=Object.keys(e);return n.length===t.length&&n.every(e=>t.includes(e))}function isPositiveInteger(e){return typeof e==`number`&&Number.isInteger(e)&&e>0}function isNonNegativeInteger(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}function isContentRange(e){return isRecord$2(e)&&hasExactKeys(e,[`kind`,`startOffset`,`endOffset`])?(e.kind===`text`||e.kind===`reasoning`)&&isNonNegativeInteger(e.startOffset)&&isNonNegativeInteger(e.endOffset)&&e.endOffset>=e.startOffset:!1}function isBatchItem(e){return isRecord$2(e)?hasExactKeys(e,e.content===void 0?[`sequence`,`chunk`]:[`sequence`,`content`,`chunk`])&&isPositiveInteger(e.sequence)&&e.chunk!==void 0&&(e.content===void 0||isContentRange(e.content)):!1}function encodedSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return}}function isAgentUIMessageBatch(e){if(!(isRecord$2(e)&&hasExactKeys(e,[`schemaVersion`,`batchId`,`tenantId`,`sessionId`,`streamId`,`sequenceStart`,`sequenceEnd`,`items`]))||e.schemaVersion!==1||typeof e.batchId!=`string`||e.batchId.trim()===``||typeof e.tenantId!=`string`||e.tenantId.trim()===``||typeof e.sessionId!=`string`||e.sessionId.trim()===``||typeof e.streamId!=`string`||e.streamId.trim()===``||!isPositiveInteger(e.sequenceStart)||!isPositiveInteger(e.sequenceEnd)||!Array.isArray(e.items)||e.items.length===0||e.items.length>256||!e.items.every(isBatchItem))return!1;let t=0;for(let n of e.items){if(n.sequence<=t)return!1;t=n.sequence}if(e.items[0]?.sequence!==e.sequenceStart||e.items.at(-1)?.sequence!==e.sequenceEnd)return!1;let n=encodedSize(e);return n!==void 0&&n<=204800}function liveChannelKey(e){switch(e.kind){case`workspace`:return`workspace:${encodeURIComponent(e.tenantId)}`;case`object`:return`object:${encodeURIComponent(e.objectId)}`;case`record`:return`record:${encodeURIComponent(e.objectId)}:${encodeURIComponent(e.recordId)}`;case`view`:return`view:${encodeURIComponent(e.viewId)}`;case`user`:return`user:${encodeURIComponent(e.actorId)}`;case`conversation`:return`conversation:${encodeURIComponent(e.sessionId)}`;case`architect-draft`:return e.scope===`actor`?`architect-draft:actor:${encodeURIComponent(e.actorId)}`:`architect-draft:session:${encodeURIComponent(e.sessionId)}`}}function architectDraftChannelKey(e){return e.sessionId?liveChannelKey({kind:`architect-draft`,scope:`session`,sessionId:e.sessionId}):e.actorId?liveChannelKey({kind:`architect-draft`,scope:`actor`,actorId:e.actorId}):null}function decodeLiveChannelPart(e){try{return decodeURIComponent(e)}catch{return null}}function parseLiveChannelKey(e){let t=e.split(`:`);if(t[0]===`workspace`&&t.length===2&&t[1]){let e=decodeLiveChannelPart(t[1]);return e?{kind:`workspace`,tenantId:e}:null}if(t[0]===`object`&&t.length===2&&t[1]){let e=decodeLiveChannelPart(t[1]);return e?{kind:`object`,objectId:e}:null}if(t[0]===`record`&&t.length===3&&t[1]&&t[2]){let e=decodeLiveChannelPart(t[1]),n=decodeLiveChannelPart(t[2]);return e&&n?{kind:`record`,objectId:e,recordId:n}:null}if(t[0]===`view`&&t.length===2&&t[1]){let e=decodeLiveChannelPart(t[1]);return e?{kind:`view`,viewId:e}:null}if(t[0]===`user`&&t.length===2&&t[1]){let e=decodeLiveChannelPart(t[1]);return e?{kind:`user`,actorId:e}:null}if(t[0]===`architect-draft`&&t.length===3&&t[2]){let e=decodeLiveChannelPart(t[2]);return e?t[1]===`actor`?{kind:`architect-draft`,scope:`actor`,actorId:e}:t[1]===`session`?{kind:`architect-draft`,scope:`session`,sessionId:e}:null:null}if(t[0]===`conversation`&&t.length===2&&t[1]){let e=decodeLiveChannelPart(t[1]);return e?{kind:`conversation`,sessionId:e}:null}return null}const Et=Object.keys({"record.patch":!0,"record.deleted":!0,"record.removed":!0,"record.created":!0,"view.projection.stale":!0,"agent.session.patch":!0,"notification.created":!0,"notification.recipient.patch":!0,"notification.count.patch":!0,"notification.inbox.archived":!0,"reflex.state.changed":!0,"reflex.run.completed":!0,"reflex.authoring.progress":!0,"architect.draft.updated":!0,"meeting.recording.patch":!0,"wallet.state":!0,"channel.revoked":!0}),Dt=[`membership-unknown`,`sort-unknown`,`permissions-changed`],Ot=[`permission-revoked`,`workspace-left`,`object-deleted`],kt=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],At=[`type`,`objectId`,`recordId`,`recordVersion`],jt=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],Mt=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],Nt=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&Et.includes(e)}function isLiveEventPayload(e){return isRecord$1(e)&&isLiveEventType(e.type)?isLiveEventPayloadForType(e.type,e):!1}function isLiveEventPayloadForType(e,t){if(!isRecord$1(t))return!1;switch(e){case`record.patch`:return isRecordPatchPayload(t);case`record.deleted`:return isRecordDeletedPayload(t);case`record.removed`:return isRecordRemovedPayload(t);case`record.created`:return isRecordCreatedPayload(t);case`view.projection.stale`:return isViewProjectionStalePayload(t);case`agent.session.patch`:return isAgentSessionPatchPayload(t);case`notification.created`:return isNotificationCreatedPayload(t);case`notification.recipient.patch`:return isNotificationRecipientPatchPayload(t);case`notification.count.patch`:return isNotificationCountPatchPayload(t);case`notification.inbox.archived`:return isNotificationInboxArchivedPayload(t);case`reflex.state.changed`:return isReflexStateChangedPayload(t);case`reflex.run.completed`:return isReflexRunCompletedPayload(t);case`reflex.authoring.progress`:return isReflexAuthoringProgressPayload(t);case`architect.draft.updated`:return isArchitectDraftUpdatedPayload(t);case`meeting.recording.patch`:return isMeetingRecordingPatchPayload(t);case`wallet.state`:return isWalletStatePayload(t);case`channel.revoked`:return isChannelRevokedPayload(t);default:return!1}}function isRecord$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function isString(e){return typeof e==`string`}function isNonEmptyString(e){return isString(e)&&e.length>0}function isNullableString(e){return e===null||isString(e)}function isVersion(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function isIsoDateString(e){if(!isString(e))return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function isNullableIsoDateString(e){return e===null||isIsoDateString(e)}function hasString(e,t){return isString(e[t])}function hasNonEmptyString(e,t){return isNonEmptyString(e[t])}function hasVersion(e,t){return isVersion(e[t])}function hasIsoDateString(e,t){return isIsoDateString(e[t])}function hasOptional(e,t,n){return!Object.hasOwn(e,t)||n(e[t])}function hasOnlyKeys(e,t){return Object.keys(e).every(e=>t.includes(e))}function isOneOf(e,t){return typeof e==`string`&&t.includes(e)}function isNotificationKind(e){return isOneOf(e,p)}function isNotificationPriority(e){return isOneOf(e,m)}function isNotificationSensitivity(e){return isOneOf(e,h)}function isNotificationInboxState(e){return isOneOf(e,g)}function isNotificationWorkState(e){return isOneOf(e,_)}function isNotificationSubject(e){return isRecord$1(e)&&hasString(e,`type`)&&hasString(e,`id`)}function isRecordFieldPatch(e){return isRecord$1(e)&&hasString(e,`fieldKey`)&&Object.hasOwn(e,`value`)&&hasVersion(e,`version`)}function isRecordPatchPayload(e){return e.type===`record.patch`&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)&&hasOptional(e,`label`,isString)&&hasOptional(e,`metadata`,isRecord$1)&&hasOptional(e,`fieldsWithheld`,e=>e===!0)&&Array.isArray(e.fieldPatches)&&e.fieldPatches.every(isRecordFieldPatch)&&hasString(e,`updatedAt`)}function isRecordDeletedPayload(e){return e.type===`record.deleted`&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)&&hasString(e,`deletedAt`)}function isRecordRemovedPayload(e){return e.type===`record.removed`&&hasOnlyKeys(e,At)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$1(e)&&hasOnlyKeys(e,Mt)&&hasString(e,`id`)&&hasString(e,`objectId`)&&isOneOf(e.visibility,[`workspace`,`private`])&&isNullableString(e.ownedBy)&&(e.visibility===`workspace`&&e.ownedBy===null||e.visibility===`private`&&isNonEmptyString(e.ownedBy))&&hasString(e,`label`)&&isRecord$1(e.values)&&hasOptional(e,`metadata`,isRecord$1)&&hasIsoDateString(e,`createdAt`)&&hasIsoDateString(e,`updatedAt`)&&hasOptional(e,`createdBy`,isString)&&hasOptional(e,`lastUpdatedBy`,isString)&&hasVersion(e,`schemaVersion`)}function isRecordCreatedPayload(e){return e.type===`record.created`&&hasOnlyKeys(e,jt)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)&&isRecordLiveSnapshot(e.record)&&e.record.id===e.recordId&&e.record.objectId===e.objectId}function isViewProjectionStalePayload(e){return e.type===`view.projection.stale`&&hasString(e,`viewId`)&&isOneOf(e.reason,Dt)}function isAgentSessionPatchPayload(e){return e.type===`agent.session.patch`&&hasString(e,`sessionId`)&&isRecord$1(e.patch)&&hasVersion(e,`version`)&&hasString(e,`updatedAt`)}function isLiveNotification(e){return isRecord$1(e)&&hasString(e,`id`)&&hasString(e,`tenantId`)&&hasOptional(e,`senderActorId`,isString)&&hasOptional(e,`rootActorId`,isString)&&hasOptional(e,`triggeredByActorId`,isString)&&isNotificationKind(e.kind)&&hasString(e,`type`)&&hasOptional(e,`subject`,isNotificationSubject)&&hasString(e,`title`)&&hasOptional(e,`summary`,isString)&&isRecord$1(e.payload)&&isNotificationPriority(e.priority)&&isNotificationSensitivity(e.sensitivity)&&hasOptional(e,`threadKey`,isString)&&hasOptional(e,`idempotencyKey`,isString)&&hasOptional(e,`expiresAt`,isIsoDateString)&&hasIsoDateString(e,`createdAt`)&&hasIsoDateString(e,`updatedAt`)}function isLiveNotificationRecipient(e){return isRecord$1(e)&&hasString(e,`id`)&&hasString(e,`tenantId`)&&hasString(e,`notificationId`)&&hasString(e,`recipientActorId`)&&isNotificationInboxState(e.inboxState)&&isNotificationWorkState(e.workState)&&hasOptional(e,`lockedAt`,isIsoDateString)&&hasOptional(e,`lockedByActorId`,isString)&&hasOptional(e,`readAt`,isIsoDateString)&&hasOptional(e,`archivedAt`,isIsoDateString)&&hasOptional(e,`snoozedUntil`,isIsoDateString)&&hasOptional(e,`completedAt`,isIsoDateString)&&hasOptional(e,`dismissedAt`,isIsoDateString)&&hasIsoDateString(e,`createdAt`)&&hasIsoDateString(e,`updatedAt`)}function isNotificationRecipientPatch(e){return isRecord$1(e)?Object.keys(e).every(e=>kt.includes(e))&&hasOptional(e,`inboxState`,isNotificationInboxState)&&hasOptional(e,`workState`,isNotificationWorkState)&&hasOptional(e,`lockedAt`,isNullableIsoDateString)&&hasOptional(e,`lockedByActorId`,isNullableString)&&hasOptional(e,`readAt`,isNullableIsoDateString)&&hasOptional(e,`archivedAt`,isNullableIsoDateString)&&hasOptional(e,`snoozedUntil`,isNullableIsoDateString)&&hasOptional(e,`completedAt`,isNullableIsoDateString)&&hasOptional(e,`dismissedAt`,isNullableIsoDateString)&&hasOptional(e,`updatedAt`,isIsoDateString):!1}function isNotificationCreatedPayload(e){let t=isLiveNotification(e.notification)?e.notification:null;return e.type===`notification.created`&&t!==null&&Array.isArray(e.recipients)&&e.recipients.length>0&&e.recipients.every(e=>isLiveNotificationRecipient(e)&&e.notificationId===t.id)&&hasVersion(e,`version`)&&hasIsoDateString(e,`updatedAt`)}function isNotificationRecipientPatchPayload(e){return e.type===`notification.recipient.patch`&&hasString(e,`recipientId`)&&hasString(e,`recipientActorId`)&&isNotificationRecipientPatch(e.patch)&&hasVersion(e,`version`)&&hasIsoDateString(e,`updatedAt`)}function isNotificationCountPatchPayload(e){return e.type===`notification.count.patch`&&hasString(e,`targetActorId`)&&hasVersion(e,`unread`)&&hasVersion(e,`pendingWork`)&&hasVersion(e,`version`)&&hasIsoDateString(e,`updatedAt`)}function isNotificationInboxArchivedPayload(e){return e.type===`notification.inbox.archived`&&hasOnlyKeys(e,Nt)&&hasNonEmptyString(e,`targetActorId`)&&hasVersion(e,`archivedCount`)&&hasVersion(e,`version`)&&hasIsoDateString(e,`updatedAt`)}const Pt=[`armed`,`disarmed`],Ft=[`authoring`,`compiling`,`replaying`,`promoted`,`failed`],It=[`promoted`,`lkg`];function isArchitectDraftUpdatedPayload(e){if(e.type!==`architect.draft.updated`||!isRecord$1(e.receipt))return!1;let t=e.receipt;return Array.isArray(t.operationIds)&&t.operationIds.every(isNonEmptyString)&&isRecord$1(t.revision)&&hasNonEmptyString(t.revision,`draftId`)&&hasVersion(t.revision,`version`)&&Array.isArray(t.changedTargets)&&t.changedTargets.every(e=>isRecord$1(e)&&isNonEmptyString(e.token)&&isNamedTarget(e.target))}function isNamedTarget(e){if(!isRecord$1(e))return!1;let t=Object.keys(e);return t.every(t=>isNonEmptyString(e[t]))?hasNonEmptyString(e,`viewName`)?hasNonEmptyString(e,`objectName`)&&t.every(e=>[`objectName`,`viewName`,`contentName`].includes(e)):hasNonEmptyString(e,`objectName`)?t.length===1:hasNonEmptyString(e,`objectId`)&&t.length<=2&&t.every(e=>[`objectId`,`attributeName`,`attributeId`,`recordId`].includes(e)):!1}function isReflexStateChangedPayload(e){return e.type===`reflex.state.changed`&&hasNonEmptyString(e,`reflexId`)&&isOneOf(e.state,Pt)&&hasIsoDateString(e,`updatedAt`)}function isReflexRunCompletedPayload(e){return e.type===`reflex.run.completed`&&hasNonEmptyString(e,`reflexId`)&&hasNonEmptyString(e,`runId`)&&isOneOf(e.served,It)&&hasVersion(e,`version`)&&hasVersion(e,`wallMs`)&&hasIsoDateString(e,`completedAt`)}function isReflexAuthoringProgressPayload(e){return e.type===`reflex.authoring.progress`&&hasNonEmptyString(e,`reflexId`)&&isOneOf(e.status,Ft)&&hasIsoDateString(e,`updatedAt`)}const Lt=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,Lt)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const Rt=[`ok`,`low`,`exhausted`,`paused`],zt=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,Rt)&&isOneOf(e.mode,zt)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,Ot)}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function payloadChannel(e){let{channel:t}=e;return typeof t==`string`&&parseLiveChannelKey(t)?t:null}function getLiveProtocolPayloadChannel(e){return isRecord(e)?payloadChannel(e):null}function isLiveEventEnvelope(e){return isRecord(e)?typeof e.id==`string`&&e.id.length>0&&typeof e.channel==`string`&&typeof e.type==`string`&&typeof e.tenantId==`string`&&e.tenantId.length>0&&typeof e.occurredAt==`string`&&isRecord(e.payload):!1}const Bt=[`if`,`concat`,`sum`,`avg`,`count`,`min`,`max`,`earliest`,`latest`,`unique`,`first`,`percent_empty`,`percent_not_empty`,`count_empty`,`count_not_empty`,`count_unique`],L={if:{name:`if`,returnType:`branch`,minArgs:3,maxArgs:3},concat:{name:`concat`,returnType:{kind:`scalar`,type:`text`},minArgs:1},sum:{name:`sum`,returnType:{kind:`scalar`,type:`number`},minArgs:1,maxArgs:1},avg:{name:`avg`,returnType:{kind:`scalar`,type:`number`},minArgs:1,maxArgs:1},count:{name:`count`,returnType:{kind:`scalar`,type:`number`},minArgs:1,maxArgs:1},min:{name:`min`,returnType:`source_item`,minArgs:1,maxArgs:1},max:{name:`max`,returnType:`source_item`,minArgs:1,maxArgs:1},earliest:{name:`earliest`,returnType:{kind:`scalar`,type:`date`},minArgs:1,maxArgs:1},latest:{name:`latest`,returnType:{kind:`scalar`,type:`date`},minArgs:1,maxArgs:1},unique:{name:`unique`,returnType:`argument`,minArgs:1,maxArgs:1},first:{name:`first`,returnType:`source_item`,minArgs:1,maxArgs:1},percent_empty:{name:`percent_empty`,returnType:{kind:`scalar`,type:`number`},minArgs:1,maxArgs:1},percent_not_empty:{name:`percent_not_empty`,returnType:{kind:`scalar`,type:`number`},minArgs:1,maxArgs:1},count_empty:{name:`count_empty`,returnType:{kind:`scalar`,type:`number`},minArgs:1,maxArgs:1},count_not_empty:{name:`count_not_empty`,returnType:{kind:`scalar`,type:`number`},minArgs:1,maxArgs:1},count_unique:{name:`count_unique`,returnType:{kind:`scalar`,type:`number`},minArgs:1,maxArgs:1}};function isComputedFunctionName(e){return Object.hasOwn(L,e)}var ComputedFormulaCompileError=class extends Error{constructor(e){super(e),this.name=`ComputedFormulaCompileError`}};function compileComputedFormula(e){let t=parseCompileFormula(e.expression),n=inferNode(t,e.schema),r=valueTypeToReturnType(n.valueType);if(r!==e.returnType)throw new ComputedFormulaCompileError(`Computed formula "${e.attributeName}" returns "${r}", expected "${e.returnType}"`);if(isSelectLikeReturnType(e.returnType)&&n.optionsSource===void 0)throw new ComputedFormulaCompileError(`Computed formula "${e.attributeName}" returns "${e.returnType}" without optionsSource`);let i=n.optionsSource===void 0?[]:[{kind:`options`,source:n.optionsSource}],a=uniqueDependencies([...n.dependencies,...i]);return{kind:`formula`,attributeName:e.attributeName,expression:e.expression,returnType:e.returnType,valueType:n.valueType,dependencies:a,ast:t,...n.optionsSource?{optionsSource:n.optionsSource}:{},...n.targetAttributeType?{targetAttributeType:n.targetAttributeType}:{},dependenciesHash:createDependenciesHash({expression:e.expression,returnType:e.returnType,dependencies:a})}}function assertAcyclicComputedDependencies(e){let t=new Map(e.map(e=>[e.attributeName,e])),n=new Set,visit=(e,r)=>{let i=r.indexOf(e);if(i!==-1)throw new ComputedFormulaCompileError(`Computed field cycle detected: ${[...r.slice(i),e].join(` -> `)}`);if(n.has(e))return;let a=t.get(e);if(a===void 0)return;let o=[...r,e];for(let e of a.dependencies)e.kind===`computed`&&visit(e.attributeName,o);n.add(e)};for(let t of e)visit(t.attributeName,[])}function parseCompileFormula(t){try{return e.y(t)}catch(e){throw e instanceof Error?new ComputedFormulaCompileError(e.message):e}}function inferNode(e,t){switch(e.kind){case`literal`:return{valueType:literalToValueType(e.value),dependencies:[],...typeof e.value==`string`?{literalString:e.value}:{}};case`path`:return inferPath(e.parts,t);case`call`:return inferCall(e.functionName,e.args,t);case`binary`:return inferBinary(e.operator,inferNode(e.left,t),inferNode(e.right,t));default:return e}}function literalToValueType(e){switch(typeof e){case`string`:return{kind:`scalar`,type:`text`};case`number`:return{kind:`scalar`,type:`number`};case`boolean`:return{kind:`scalar`,type:`boolean`};case`object`:return{kind:`scalar`,type:`text`};default:return e}}function inferPath(e,t){if(e.length===1){let n=e[0],r=findAttribute$1(t,n);if(r===void 0)throw new ComputedFormulaCompileError(`Unknown attribute "${n}" on object "${t.objectName}"`);return r.type===`relation`?{valueType:relationToValueType(),dependencies:[{kind:`relation`,relationName:r.name,cardinality:relationCardinality(r)}],targetAttributeType:r.type}:{valueType:attributeToValueType(r),dependencies:[localDependencyFor(r)],optionsSource:optionsSourceForAttribute(t.objectName,r),targetAttributeType:r.type}}if(e.length===2){let[n,r]=e,i=findAttribute$1(t,n);if(i===void 0)throw new ComputedFormulaCompileError(`Unknown attribute "${n}" on object "${t.objectName}"`);if(i.type!==`relation`)throw new ComputedFormulaCompileError(`Attribute "${n}" on object "${t.objectName}" is not a relation`);let a=getRelationTargetObjectName$1(i);if(a===void 0)throw new ComputedFormulaCompileError(`Relation "${n}" on object "${t.objectName}" is missing targetObjectName`);let o=t.relatedObjects?.[a];if(o===void 0)throw new ComputedFormulaCompileError(`Unknown related object "${a}"`);let s=findAttribute$1(o,r);if(s===void 0)throw new ComputedFormulaCompileError(`Unknown attribute "${r}" on object "${o.objectName}"`);let c=attributeToValueType(s);return{valueType:i.cardinality===`many`?asCollectionValueType(c):c,dependencies:[{kind:`relation`,relationName:n,targetAttributeName:r,cardinality:relationCardinality(i)}],optionsSource:optionsSourceForAttribute(o.objectName,s),targetAttributeType:s.type}}throw new ComputedFormulaCompileError(`Computed paths support at most one relation hop`)}function findAttribute$1(e,t){return e.attributes.find(e=>e.name===t)}function getRelationTargetObjectName$1(e){if(e.targetObjectName!==void 0)return e.targetObjectName;if(e.targets?.length===1){let[t]=e.targets;return t?.object===`*`?void 0:t?.object}}function relationCardinality(e){return e.cardinality??`one`}function localDependencyFor(e){return e.type===`formula`||e.type===`rollup`?{kind:`computed`,attributeName:e.name}:{kind:`local`,attributeName:e.name}}function attributeToValueType(e){if(e.type===`formula`||e.type===`rollup`){if(e.returnType===void 0)throw new ComputedFormulaCompileError(`Computed attribute "${e.name}" is missing returnType`);return returnTypeToValueType(e.returnType)}switch(e.type){case`number`:case`currency`:return{kind:`scalar`,type:`number`};case`checkbox`:return{kind:`scalar`,type:`boolean`};case`date`:return{kind:`scalar`,type:`date`};case`select`:case`status`:return{kind:`scalar`,type:`select`};case`multiselect`:return{kind:`collection`,itemType:`select`};case`text`:case`richtext`:case`phone`:case`user`:case`location`:case`relation`:case`document`:return{kind:`scalar`,type:`text`};default:return e.type}}function relationToValueType(){return{kind:`collection`,itemType:`text`}}function returnTypeToValueType(e){return e===`multiselect`?{kind:`collection`,itemType:`select`}:{kind:`scalar`,type:e}}function asCollectionValueType(e){return e.kind===`collection`?e:{kind:`collection`,itemType:e.type}}function optionsSourceForAttribute(e,t){if(t.type===`formula`||t.type===`rollup`)return isSelectLikeReturnType(t.returnType)?t.optionsSource:void 0;if(t.type===`select`||t.type===`status`||t.type===`multiselect`)return t.optionsSource??{objectName:e,attributeName:t.name,...t.id?{attributeId:t.id}:{}}}function inferCall(e,t,n){if(!isComputedFunctionName(e))throw new ComputedFormulaCompileError(`Unknown computed function "${e}"`);let r=L[e];if(t.length<r.minArgs||r.maxArgs!==void 0&&t.length>r.maxArgs)throw new ComputedFormulaCompileError(`Function "${e}" expects ${r.maxArgs===void 0||r.maxArgs===r.minArgs?String(r.minArgs):`${r.minArgs}-${r.maxArgs}`} arguments, received ${t.length}`);return inferFunctionReturn(e,t.map(e=>inferNode(e,n)))}function inferFunctionReturn(e,t){let n=uniqueDependencies(t.flatMap(e=>e.dependencies));switch(e){case`if`:return inferIfFunction(t,n);case`concat`:return ensureNoCollections(t,`Function "${e}" does not accept collection values`),{valueType:{kind:`scalar`,type:`text`},dependencies:n};case`sum`:case`avg`:return ensureCollectionOrScalarType(e,t[0],`number`),{valueType:{kind:`scalar`,type:`number`},dependencies:n};case`count`:case`count_empty`:case`count_not_empty`:case`count_unique`:case`percent_empty`:case`percent_not_empty`:return ensureCollectionSource(e,t[0]),{valueType:{kind:`scalar`,type:`number`},dependencies:n};case`min`:case`max`:return ensureMinMaxSource(e,t[0]),{valueType:sourceItemValueType(t[0]),dependencies:n,optionsSource:t[0].optionsSource,targetAttributeType:t[0].targetAttributeType};case`earliest`:case`latest`:return ensureCollectionOrScalarType(e,t[0],`date`),{valueType:{kind:`scalar`,type:`date`},dependencies:n,targetAttributeType:t[0].targetAttributeType};case`unique`:return inferUniqueFunction(t[0],n);case`first`:return inferFirstFunction(t[0],n);default:return e}}function inferIfFunction(e,t){ensureScalarType(e[0].valueType,`boolean`,`Function "if" condition must be boolean`);let n=e[1],r=e[2],i=resolveIfBranchValueType(n,r),a=resolveIfOptionsSource(n,r);if(i===void 0)throw new ComputedFormulaCompileError(`Function "if" branches must return the same type`);return{valueType:i,dependencies:t,...a?{optionsSource:a}:{},targetAttributeType:n.targetAttributeType??r.targetAttributeType}}function inferUniqueFunction(e,t){if(e.valueType.kind!==`collection`||e.valueType.itemType!==`select`)throw new ComputedFormulaCompileError(`Function "unique" expects a select collection`);return{valueType:{kind:`collection`,itemType:`select`},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}function inferFirstFunction(e,t){if(e.valueType.kind!==`collection`)throw new ComputedFormulaCompileError(`Function "first" expects a collection`);return{valueType:{kind:`scalar`,type:e.valueType.itemType},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}function inferBinary(e,t,n){let r=uniqueDependencies([...t.dependencies,...n.dependencies]),i=e===`+`||e===`-`||e===`*`||e===`/`;if(t.valueType.kind===`collection`||n.valueType.kind===`collection`)throw new ComputedFormulaCompileError(`Cannot use collection values with ${i?`arithmetic`:`comparison`} operator "${e}"`);if(i)return e===`+`&&(t.valueType.type===`text`||n.valueType.type===`text`)?{valueType:{kind:`scalar`,type:`text`},dependencies:r}:(ensureScalarType(t.valueType,`number`,`Operator "${e}" expects number operands`),ensureScalarType(n.valueType,`number`,`Operator "${e}" expects number operands`),{valueType:{kind:`scalar`,type:`number`},dependencies:r});if(e===`==`||e===`!=`){if(t.valueType.type!==n.valueType.type)throw new ComputedFormulaCompileError(`Operator "${e}" expects operands with the same scalar type`);return{valueType:{kind:`scalar`,type:`boolean`},dependencies:r}}if((t.valueType.type!==`number`||n.valueType.type!==`number`)&&(t.valueType.type!==`date`||n.valueType.type!==`date`))throw new ComputedFormulaCompileError(`Operator "${e}" expects number or date operands of the same type`);return{valueType:{kind:`scalar`,type:`boolean`},dependencies:r}}function ensureNoCollections(e,t){for(let n of e)if(n.valueType.kind===`collection`)throw new ComputedFormulaCompileError(t)}function ensureCollectionOrScalarType(e,t,n){if((t.valueType.kind===`collection`?t.valueType.itemType:t.valueType.type)!==n)throw new ComputedFormulaCompileError(`Function "${e}" expects ${n} values`)}function ensureMinMaxSource(e,t){if(t.valueType.kind!==`collection`)throw new ComputedFormulaCompileError(`Function "${e}" expects a collection`);let n=t.valueType.itemType;if(n!==`number`&&n!==`date`)throw new ComputedFormulaCompileError(`Function "${e}" expects number or date values`)}function ensureCollectionSource(e,t){if(t.valueType.kind!==`collection`)throw new ComputedFormulaCompileError(`Function "${e}" expects a collection`)}function ensureScalarType(e,t,n){if(e.kind!==`scalar`||e.type!==t)throw new ComputedFormulaCompileError(n)}function sourceItemValueType(e){return e.valueType.kind===`scalar`?e.valueType:{kind:`scalar`,type:e.valueType.itemType}}function sameValueType(e,t){return e.kind===`scalar`?t.kind===`scalar`&&e.type===t.type:t.kind===`collection`&&e.itemType===t.itemType}function resolveIfBranchValueType(e,t){if(sameValueType(e.valueType,t.valueType)||isSelectScalarWithStringLiteral(e,t))return e.valueType;if(isSelectScalarWithStringLiteral(t,e))return t.valueType}function isSelectScalarWithStringLiteral(e,t){return e.valueType.kind===`scalar`&&e.valueType.type===`select`&&t.valueType.kind===`scalar`&&t.valueType.type===`text`&&t.literalString!==void 0}function resolveIfOptionsSource(e,t){let n=e.optionsSource,r=t.optionsSource;if(n!==void 0&&r!==void 0&&!sameOptionsSource(n,r))throw new ComputedFormulaCompileError(`Function "if" branches use incompatible options sources`);return n??r}function sameOptionsSource(e,t){return e.objectName===t.objectName&&e.attributeName===t.attributeName&&e.attributeId===t.attributeId}function isSelectLikeReturnType(e){return e===`select`||e===`multiselect`}function valueTypeToReturnType(e){if(e.kind===`scalar`)return e.type;if(e.itemType===`select`)return`multiselect`;throw new ComputedFormulaCompileError(`Collection item type "${e.itemType}" cannot be used as a computed return type`)}function uniqueDependencies(e){let t=new Set,n=[];for(let r of e){let e=JSON.stringify(stableNormalize(r));t.has(e)||(t.add(e),n.push(r))}return n}function createDependenciesHash(e){let t=e.dependencies.map(e=>stableNormalize(e)).sort((e,t)=>compareStrings(JSON.stringify(e),JSON.stringify(t)));return JSON.stringify(stableNormalize({expression:e.expression,returnType:e.returnType,dependencies:t}))}function stableNormalize(e){return Array.isArray(e)?e.map(e=>stableNormalize(e)):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>compareStrings(e,t)).map(([e,t])=>[e,stableNormalize(t)])):e}function compareStrings(e,t){return e<t?-1:+(e>t)}function rollupToFormulaExpression(e){return e.function===`count`?`count(${e.relationAttribute})`:`${rollupFunctionToFormulaFunction(e.function)}(${e.relationAttribute}.${e.targetAttribute})`}function inferRollupReturnType(e,t){if(e.function===`count`)return`number`;let n=findRollupTargetAttribute(e,t);switch(e.function){case`countValues`:case`countEmpty`:case`percentEmpty`:case`percentNotEmpty`:case`countUniqueValues`:return`number`;case`sum`:case`avg`:return`number`;case`earliest`:case`latest`:return`date`;case`original`:if(!isSelectLikeAttributeType(n.type))throw new ComputedFormulaCompileError(`Rollup "original" requires a select, status, or multiselect target`);return`multiselect`;default:return e.function}}function compileRollupAttribute(e,t){let n=rollupToFormulaExpression(e),r=inferRollupReturnType(e,t);return{...compileComputedFormula({attributeName:e.name,expression:n,returnType:r,schema:schemaWithRollupRelationAsMany(e,t)}),kind:`rollup`}}function schemaWithRollupRelationAsMany(e,t){return{...t,attributes:t.attributes.map(t=>t.name===e.relationAttribute&&t.type===`relation`?{...t,cardinality:`many`}:t)}}function rollupFunctionToFormulaFunction(e){switch(e){case`sum`:case`avg`:case`earliest`:case`latest`:return e;case`original`:return`unique`;case`countValues`:return`count_not_empty`;case`countEmpty`:return`count_empty`;case`percentEmpty`:return`percent_empty`;case`percentNotEmpty`:return`percent_not_empty`;case`countUniqueValues`:return`count_unique`;default:return e}}function findRollupTargetAttribute(e,t){let n=findAttribute(t,e.relationAttribute);if(n===void 0)throw new ComputedFormulaCompileError(`Unknown relation attribute "${e.relationAttribute}" on object "${t.objectName}"`);if(n.type!==`relation`)throw new ComputedFormulaCompileError(`Attribute "${e.relationAttribute}" on object "${t.objectName}" is not a relation`);let r=getRelationTargetObjectName(n);if(r===void 0)throw new ComputedFormulaCompileError(`Relation "${e.relationAttribute}" on object "${t.objectName}" is missing targetObjectName`);let i=t.relatedObjects?.[r];if(i===void 0)throw new ComputedFormulaCompileError(`Unknown related object "${r}"`);let a=findAttribute(i,e.targetAttribute);if(a===void 0)throw new ComputedFormulaCompileError(`Unknown attribute "${e.targetAttribute}" on object "${i.objectName}"`);return a}function findAttribute(e,t){return e.attributes.find(e=>e.name===t)}function getRelationTargetObjectName(e){if(e.targetObjectName!==void 0)return e.targetObjectName;if(e.targets?.length===1){let[t]=e.targets;return t?.object===`*`?void 0:t?.object}}function isSelectLikeAttributeType(e){return e===`select`||e===`status`||e===`multiselect`}function evaluateAst(e,t){switch(e.kind){case`literal`:return e.value;case`path`:return resolvePath(t,e.parts);case`binary`:return evaluateBinary(e.operator,evaluateAst(e.left,t),evaluateAst(e.right,t));case`call`:return evaluateCallNode(e.functionName,e.args,t);default:return unreachable(e)}}function evaluateCallNode(e,t,n){if(assertComputedFunctionName(e),validateArity(e,t.length),e===`if`){let e=evaluateAst(t[0],n);return e===null?null:evaluateAst(e?t[1]:t[2],n)}return evaluateCall(e,t.map(e=>evaluateAst(e,n)))}function resolvePath(e,t){return t.reduce((e,t)=>resolvePathPart(e,t),e)}function resolvePathPart(e,t){if(Array.isArray(e))return e.map(e=>resolvePathPart(e,t));if(!isPlainRecord(e))return null;if(Object.hasOwn(e,t))return e[t]??null;let n=e.values;return isPlainRecord(n)&&Object.hasOwn(n,t)?n[t]??null:null}function evaluateBinary(e,t,n){switch(e){case`+`:return add(t,n);case`-`:return numericBinary(t,n,(e,t)=>e-t);case`*`:return numericBinary(t,n,(e,t)=>e*t);case`/`:return numericBinary(t,n,(e,t)=>e/t);case`>`:return compareWith(t,n,e=>e>0);case`<`:return compareWith(t,n,e=>e<0);case`>=`:return compareWith(t,n,e=>e>=0);case`<=`:return compareWith(t,n,e=>e<=0);case`==`:return equalScalar(t,n);case`!=`:{let e=equalScalar(t,n);return e===null?null:!e}default:return unreachable(e)}}function add(e,t){return typeof e==`string`||typeof t==`string`?`${e??``}${t??``}`:numericBinary(e,t,(e,t)=>e+t)}function compareWith(e,t,n){let r=compare(e,t);return r===null?null:n(r)}function compare(e,t){if(!areCommensurable([e,t]))return null;let n=toFiniteNumber(e),r=toFiniteNumber(t);if(n!==null&&r!==null)return n-r;let i=toDate$1(e),a=toDate$1(t);return i&&a?i.getTime()-a.getTime():null}function equalScalar(e,t){return e===t?!0:e==null||t==null?!1:areCommensurable([e,t])?compare(e,t)===0:null}function assertComputedFunctionName(e){if(!isComputedFunctionName(e))throw Error(`Unknown computed function "${e}"`)}function validateArity(e,t){let{minArgs:n,maxArgs:r}=L[e];if(t>=n&&t<=(r??1/0))return;let i=r===void 0?`at least ${n}`:`between ${n} and ${r}`;throw Error(`Function "${e}" expects ${i} arguments, received ${t}`)}function evaluateCall(e,t){switch(e){case`concat`:return t.filter(e=>e!=null).map(String).join(``);case`sum`:return areCommensurable(t)?numericValues(t).reduce((e,t)=>e+t,0):null;case`avg`:{if(!areCommensurable(t))return null;let e=numericValues(t);return e.length>0?e.reduce((e,t)=>e+t,0)/e.length:null}case`count`:return collectionItems(t[0]).length;case`min`:return minMax(t,`min`);case`max`:return minMax(t,`max`);case`earliest`:return dateMinMax(t,`min`);case`latest`:return dateMinMax(t,`max`);case`unique`:return uniqueNonEmpty(collectionItems(t[0]));case`first`:return collectionItems(t[0]).find(e=>e!=null)??null;case`percent_empty`:return percentByEmptyState(t[0],!0);case`percent_not_empty`:return percentByEmptyState(t[0],!1);case`count_empty`:return collectionItems(t[0]).filter(i.p).length;case`count_not_empty`:return collectionItems(t[0]).filter(e=>!i.p(e)).length;case`count_unique`:return uniqueNonEmpty(collectionItems(t[0])).length;default:return unreachable(e)}}function unreachable(e){return e}function numericValues(e){return flatten(e).map(toFiniteNumber).filter(e=>e!==null)}function areCommensurable(e){let t=new Set;for(let n of flatten(e))isCurrencyValue(n)&&t.add(currencyCode(n));return t.size<=1}function currencyCode(e){return e.code.toUpperCase()}function numericBinary(e,t,n){if(!areCommensurable([e,t]))return null;let r=toFiniteNumber(e),i=toFiniteNumber(t);if(r===null||i===null)return null;let a=n(r,i);return Number.isFinite(a)?a:null}function minMax(e,t){if(!areCommensurable(e))return null;let n=numericValues(e);return n.length>0?t===`min`?Math.min(...n):Math.max(...n):dateMinMax(e,t)}function dateMinMax(e,t){let n=flatten(e).map(toDate$1).filter(e=>e!==null);if(n.length===0)return null;let r=n.map(e=>e.getTime()),i=t===`min`?Math.min(...r):Math.max(...r);return new Date(i).toISOString()}function percentByEmptyState(e,t){let n=collectionItems(e);return n.length===0?0:n.filter(e=>i.p(e)===t).length/n.length}function uniqueNonEmpty(e){let t=new Set,n=[];for(let r of e){if(i.p(r))continue;let e=uniqueKey(r);t.has(e)||(t.add(e),n.push(r))}return n}function collectionItems(e){return e==null?[]:Array.isArray(e)?flatten(e):[e]}function flatten(e){return e.flat(1/0)}function toFiniteNumber(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:null}return isCurrencyValue(e)&&Number.isFinite(e.value)?e.value:null}function isCurrencyValue(e){return typeof e==`object`&&!!e&&typeof e.value==`number`&&typeof e.code==`string`}function toDate$1(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e!=`string`){let t=dateValueStart(e);if(t===null)return null;let n=new Date(t);return Number.isNaN(n.getTime())?null:n}let t=new Date(e);return Number.isNaN(t.getTime())?null:t}function uniqueKey(e){if(isCurrencyValue(e))return`currency:${currencyCode(e)}:${e.value}`;let t=toFiniteNumber(e);return t===null?e instanceof Date?`date:${e.toISOString()}`:`${typeof e}:${JSON.stringify(e)}`:`number:${t}`}function isPlainRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function formatComputedResult(e,t,n){if(e==null)return null;let stringifyScalar=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e instanceof Date?String(e):null;switch(t){case`number`:{let t=typeof e==`number`?e:Number(e);return Number.isNaN(t)?null:n===void 0?t:Number(t.toFixed(n))}case`boolean`:return!!e;case`date`:return e instanceof Date?e.toISOString():typeof e==`string`?e:null;case`text`:return String(e);case`select`:if(Array.isArray(e)){for(let t of e){if(t==null)continue;let e=stringifyScalar(t);if(e!==null)return e}return null}return stringifyScalar(e);case`multiselect`:return Array.isArray(e)?e.flatMap(e=>{if(e==null)return[];let t=stringifyScalar(e);return t===null?[]:[t]}):stringifyScalar(e)===null?[]:[String(e)];default:throw Error(`Unsupported computed return type: ${t}`)}}function evaluateComputedAst(e,t){return evaluateAst(e,t)}function evaluateComputedFormula(t,n){return evaluateAst(e.y(t),n)}function evaluateComputedFormulaWithResult(t,n,r,i){try{let a=evaluateAst(e.y(t),n);return{value:r?formatComputedResult(a,r,i):a}}catch(e){return{value:null,error:e instanceof Error?e.message:String(e)}}}const Vt=[{name:`if`,signature:`if(condition, then, else)`,description:`Conditional value`,category:`logic`,example:`if(amount > 100, 'big', 'small')`},{name:`concat`,signature:`concat(a, b, ...)`,description:`Join values into text`,category:`text`,example:`concat(firstName, ' ', lastName)`},{name:`sum`,signature:`sum(collection)`,description:`Total of values`,category:`number`,example:`sum(orders.amount)`},{name:`avg`,signature:`avg(collection)`,description:`Average of values`,category:`number`,example:`avg(orders.amount)`},{name:`min`,signature:`min(collection)`,description:`Smallest value`,category:`number`,example:`min(orders.amount)`},{name:`max`,signature:`max(collection)`,description:`Largest value`,category:`number`,example:`max(orders.amount)`},{name:`count`,signature:`count(collection)`,description:`Number of items`,category:`collection`,example:`count(orders)`},{name:`count_empty`,signature:`count_empty(collection)`,description:`Items with no value`,category:`collection`,example:`count_empty(orders.note)`},{name:`count_not_empty`,signature:`count_not_empty(collection)`,description:`Items with a value`,category:`collection`,example:`count_not_empty(orders.note)`},{name:`count_unique`,signature:`count_unique(collection)`,description:`Distinct values`,category:`collection`,example:`count_unique(orders.status)`},{name:`percent_empty`,signature:`percent_empty(collection)`,description:`Fraction with no value`,category:`collection`,example:`percent_empty(orders.note)`},{name:`percent_not_empty`,signature:`percent_not_empty(collection)`,description:`Fraction with a value`,category:`collection`,example:`percent_not_empty(orders.note)`},{name:`unique`,signature:`unique(collection)`,description:`Distinct values as a list`,category:`collection`,example:`unique(orders.status)`},{name:`first`,signature:`first(collection)`,description:`First non-empty value`,category:`collection`,example:`first(orders.status)`},{name:`earliest`,signature:`earliest(collection)`,description:`Earliest date`,category:`date`,example:`earliest(orders.closeDate)`},{name:`latest`,signature:`latest(collection)`,description:`Latest date`,category:`date`,example:`latest(orders.closeDate)`}],isEmpty=e=>i.p(e)||Array.isArray(e)&&e.length===0,toStr=e=>e==null?``:String(e),toNum=e=>{if(i.p(e))return null;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null},toDate=e=>{if(e==null)return null;let t=e instanceof Date?e:new Date(String(e));return Number.isNaN(t.getTime())?null:t},toArr=e=>Array.isArray(e)?e:e==null?[]:[e],compareNumbers=(e,t,n)=>{let r=toNum(e),i=toNum(t);return r!==null&&i!==null&&n(r,i)},compareDates=(e,t,n)=>{let r=toDate(e),i=toDate(t);return r!==null&&i!==null&&n(r.getTime(),i.getTime())},equalsForAttr=(e,t,n)=>{if(n.type===`number`||n.type===`currency`){let n=toNum(e),r=toNum(t);if(n!==null&&r!==null)return n===r}return toStr(e)===toStr(t)};function isCheckboxEquality(e,t){return e?e===`checkbox`:typeof t==`boolean`}const orderingSpec=e=>({appliesTo:[`number`,`currency`,`date`,`formula`],evaluateInMemory:(t,n,r)=>r.type===`date`?compareDates(t,n,e):compareNumbers(t,n,e)}),R={is:{appliesTo:[`text`,`phone`,`number`,`currency`,`checkbox`,`status`,`select`,`date`,`user`,`relation`,`formula`],evaluateInMemory:(e,t,n)=>n.type===`checkbox`?e===!0==(t===!0):equalsForAttr(e,t,n)},is_not:{appliesTo:[`text`,`phone`,`number`,`currency`,`status`,`select`,`date`,`user`,`relation`,`formula`],evaluateInMemory:(e,t,n)=>!equalsForAttr(e,t,n)},contains:{appliesTo:[`text`,`phone`,`formula`],evaluateInMemory:(e,t)=>toStr(e).toLowerCase().includes(toStr(t).toLowerCase())},not_contains:{appliesTo:[`text`,`phone`,`formula`],evaluateInMemory:(e,t)=>!toStr(e).toLowerCase().includes(toStr(t).toLowerCase())},starts_with:{appliesTo:[`text`,`phone`],evaluateInMemory:(e,t)=>toStr(e).toLowerCase().startsWith(toStr(t).toLowerCase())},ends_with:{appliesTo:[`text`],evaluateInMemory:(e,t)=>toStr(e).toLowerCase().endsWith(toStr(t).toLowerCase())},is_empty:{appliesTo:[`text`,`richtext`,`number`,`phone`,`currency`,`status`,`select`,`date`,`multiselect`,`location`,`user`,`relation`,`formula`,`document`],evaluateInMemory:e=>isEmpty(e)},is_not_empty:{appliesTo:[`text`,`richtext`,`number`,`phone`,`currency`,`status`,`select`,`date`,`multiselect`,`location`,`user`,`relation`,`formula`,`document`],evaluateInMemory:e=>!isEmpty(e)},less_than:orderingSpec((e,t)=>e<t),greater_than:orderingSpec((e,t)=>e>t),less_or_equal:orderingSpec((e,t)=>e<=t),greater_or_equal:orderingSpec((e,t)=>e>=t),is_within:{appliesTo:[`date`],evaluateInMemory:(e,n)=>{let r=toDate(e),i=t._(n);return r&&i?r.getTime()>=i.startMs&&r.getTime()<i.endMs:!1}},on_day_month:{appliesTo:[`date`],evaluateInMemory:(e,t)=>{let n=toDate(e);if(!n)return!1;let r=t;return n.getMonth()+1===r.month&&n.getDate()===r.day}},any_of:{appliesTo:[`status`,`select`,`multiselect`,`user`,`relation`],evaluateInMemory:(e,t)=>{let n=toArr(t).map(toStr);return toArr(e).map(toStr).some(e=>n.includes(e))}},none_of:{appliesTo:[`status`,`select`,`multiselect`,`user`,`relation`],evaluateInMemory:(e,t)=>{let n=toArr(t).map(toStr);return!toArr(e).map(toStr).some(e=>n.includes(e))}}},systemAttribute=(e,t)=>({id:`system:${e}`,name:e,label:e,type:t,system:!0}),Ht=[...Object.entries(t.p).map(([e,t])=>systemAttribute(e,t))];function evaluateRecordFilterState(e,t,n){let r=t;return evaluateFilterState(e,{...t.values,id:t.id,objectId:t.objectId,objectName:r.objectName,tenantId:r.tenantId,label:t.label,createdAt:t.createdAt,updatedAt:t.updatedAt,createdBy:t.createdBy,lastUpdatedBy:t.lastUpdatedBy,deletedAt:t.deletedAt,deletedBy:t.deletedBy,visibility:t.visibility,ownedBy:t.ownedBy},[...n,...Ht])}function evaluateFilterState(e,t,n){if(e.rules.length===0)return!0;let r=new Map(n.map(e=>[e.name,e])),i=e.combinator===`or`?`some`:`every`;return e.rules[i](e=>evaluateRule(e,t,r))}function evaluateRule(e,n,r){let i=r.get(e.attribute);if(!i)return!1;if(e.property&&i.type===`location`){if(!(t.q(e.property)&&t.J(e.operator)))return!1;let r=R[e.operator];if(!r)return!1;let a=n[e.attribute],o=typeof a==`object`&&a?a[e.property]:void 0;return evaluateNormalizedComparands(r,`text`,e.operator,o,e.value,i)}if(e.property){let r=resolvePropertyDefinitions(i).find(t=>t.name===e.property);if(!r)return!1;let a=t.E(e.operator),o=R[a];if(!o?.appliesTo.includes(r.type))return!1;let s=n[e.attribute],c=(Array.isArray(s)?s:s==null?[]:[s]).some(t=>{if(typeof t!=`object`||!t)return!1;let n=t.props;return typeof n!=`object`||!n?!1:evaluateNormalizedComparands(o,r.type,a,n[e.property],e.value,r)});return(e.quantifier??t.w(e.operator))===`none`?!c:c}let a=R[e.operator];if(!a||!a.appliesTo.includes(i.type))return!1;let o=n[e.attribute],s=i.type===`relation`||i.type===`document`||i.type===`user`?normalizeReferenceIds(o):o;return evaluateNormalizedComparands(a,i.type,e.operator,s,e.value,i)}function evaluateNormalizedComparands(e,t,n,r,i,a){let[o,s]=normalizeOperatorComparands(t,n,r,i);return t===`phone`&&s===``&&n===`contains`?!1:t===`phone`&&s===``&&n===`not_contains`||e.evaluateInMemory(o,s,a)}function normalizeOperatorComparands(e,t,n,r){return e===`date`&&(t===`is`||t===`is_not`)?[normalizeUtcCalendarDay(n),normalizeUtcCalendarDay(r)]:e===`phone`?normalizePhoneComparands(n,r):[normalizeComparableValue(e,n),normalizeComparableValue(e,r)]}function normalizeUtcCalendarDay(e){let t=isDateRangeValue(e)?dateValueStart(e):e;if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.toISOString().slice(0,10);if(typeof t!=`string`||t===``)return null;if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let n=new Date(t);return Number.isNaN(n.getTime())?null:n.toISOString().slice(0,10)}function normalizePhoneComparands(e,t){let n=typeof t==`object`&&t?t:{phoneNumber:t},r=typeof n.countryCode==`string`?n.countryCode:void 0,normalizeOne=e=>{let t=typeof e==`object`&&e?e:{phoneNumber:e};if(typeof t.phoneNumber!=`string`)return null;if(!r)return o.r(t.phoneNumber);let n=typeof t.countryCode==`string`?t.countryCode:r;return`${n}:${o.i(t.phoneNumber,n)}`};return[normalizeOne(e),normalizeOne(t)]}function normalizeComparableValue(e,n){return e===`currency`?t.O(n):e===`date`?isDateRangeValue(n)?dateValueStart(n):n instanceof Date?Number.isNaN(n.getTime())?null:n.toISOString():n:n}function normalizeReferenceIds(e){let normalizeOne=e=>typeof e!=`object`||!e?e:e.id;return Array.isArray(e)?e.map(normalizeOne):normalizeOne(e)}function dateInTimezone(e,t){return new Intl.DateTimeFormat(`en-CA`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`}).format(e)}function resolveAttributeDefaultValue(e,t){if(!(`defaultValue`in e))return;let{defaultValue:n}=e;return e.type!==`date`||n!==`today`?n:e.includeTime?t.now.toISOString():dateInTimezone(t.now,t.timezone)}function deriveCreateDefaultsFromFilters(e,n,r){if(e.combinator===`or`&&e.rules.length>1)return{};let i=new Map(n.map(e=>[e.name,e])),a={};for(let n of e.rules){if(n.property!==void 0||Object.hasOwn(a,n.attribute))continue;let e=i.get(n.attribute);if(!e)continue;let o=extractDeterministicValue(n,r);o!==void 0&&(a[n.attribute]=t.B(e).storage.cardinality===`many`?[o]:o)}return a}function extractDeterministicValue(e,n){if(e.operator===`is`)return t.j(e.value)?resolveDynamicValue(e.value,n):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator===`any_of`){if(!Array.isArray(e.value)||e.value.length!==1)return;let r=e.value[0];return t.j(r)?resolveDynamicValue(r,n):r}}function resolveDynamicValue(e,t){if(t){if(e.dynamic===`actor`)return t.userId;if(e.anchor===`today`)return dateInTimezone(t.now,t.timezone);if(e.anchor===`now`)return t.now.toISOString()}}function requestedCapabilities(e){let t=[];return e.canModify&&t.push(`modify`),e.canSend&&t.push(`send`),t}const Ut={status:`connector_status`,error:`connector_error`,provider:`connector_provider`};let Wt=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const Gt=[`threads`,`messages`];function isMailboxListMode(e){return Gt.includes(e)}const Kt=[`reply`,`reply_all`];function isReplyMode(e){return Kt.includes(e)}const qt=[`force`,`skip`],Jt=[`none`,`all`,`external_only`],Yt={override:null,status:`none`,failureReason:null,botId:null},Xt=/^Session \d+$/;function buildAgentFallbackTitle(e){let t=e.replace(/\s+/g,` `).trim().replace(/[.!?]+$/,``);return t?t.length>60?`${t.slice(0,59).trimEnd()}...`:t:`New conversation`}function conversationDisplayTitle(e){let t=e.generated?.trim();return t&&!Xt.test(t)?t:e.firstUserText?buildAgentFallbackTitle(e.firstUserText):e.emptyLabel}const Zt=/^[a-z0-9][a-z0-9-]{0,62}$/;function assertSchemaSourceId(e){if(!Zt.test(e))throw new n.ValidationError(`Invalid schema source id "${e}": expected a lowercase slug matching ${Zt}`,[])}function hasDestructiveEntries(e){let{attributeRemovals:t,objectRemovals:n,renames:r}=e.destructive;return t.length>0||n.length>0||r.length>0}const z={objectAdditions:20,totalMutations:500,serializedBytes:524288};function errorMessage(e){return e instanceof Error?e.message:String(e)}const Qt=f.z.enum([`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`status`,`location`,`select`,`multiselect`,`user`,`relation`,`formula`,`rollup`,`document`]).describe('The attribute\'s data type. Determines which keys `config` accepts and requires: `status`/`select`/`multiselect` need a non-empty `options` array (each `status` option carrying its own `group`); `relation` needs `targets` (non-empty) and `cardinality` ("one" or "many"); `formula` needs `expression` and `returnType`; `rollup` needs `targetAttribute` and `function`. Every other type accepts only the shared presentation keys (`placeholder`, `defaultValue`, `icon`, ...) plus a few type-specific optionals (e.g. `number.decimals`, `date.dateFormat`). An attribute\'s type can never be changed later through this tool — only through a code migration — so pick it correctly now.'),$t=f.z.string().min(1).superRefine((t,n)=>{try{e.E(t)}catch(e){n.addIssue({code:f.z.ZodIssueCode.custom,message:errorMessage(e)})}}).describe(`The attribute's machine name — the record's field key, and what \`{{ name }}\` refers to in a labelExpression. Must be a valid identifier: starts with a letter or underscore, then only letters/digits/underscores ("montantHt", "first_name", "FIRST_NAME" are valid; "first-name", "first name", "123name" are not). Max 63 characters. Cannot be a name reserved by the record shape itself (id, createdAt, updatedAt, createdBy, lastUpdatedBy, objectId, label, embeddingText, values, metadata, deletedAt, deletedBy, schemaVersion).`),en=f.z.string().min(1).superRefine((t,n)=>{e.z(t)&&n.addIssue({code:f.z.ZodIssueCode.custom,message:`"${t}" is a reserved object name (${e.P.join(`, `)}) and cannot be used for a new object.`});try{e.k(t)}catch(e){n.addIssue({code:f.z.ZodIssueCode.custom,message:errorMessage(e)})}}).describe(`The new object's machine name: kebab-case slug, lowercase letters/digits/hyphens only, starting with a letter ("products", "user-profiles", "order-items" are valid; "Products", "userProfiles", "user_profiles" are not). Max 63 characters. Cannot be a name the platform reserves for its own system objects, and cannot already exist.`);function withConfigCheck(t){return t.superRefine((t,r)=>{try{let n=e.c(t.type,{...t.config??{},description:t.description}),i=Object.keys(t.config??{}).filter(e=>!Object.hasOwn(n,e));i.length>0&&r.addIssue({code:`unrecognized_keys`,keys:i,path:[`config`],message:`Unrecognized attribute config key${i.length===1?``:`s`}: ${i.join(`, `)}`})}catch(e){if(e instanceof n.ValidationError){for(let n of e.errors)r.addIssue({code:f.z.ZodIssueCode.custom,path:[`config`,...n.path.map(e=>/^\d+$/.test(e)?Number(e):e)],message:`Config for type "${t.type}" is invalid or incomplete: ${n.message}`});return}r.addIssue({code:f.z.ZodIssueCode.custom,path:[`config`],message:`Config for type "${t.type}" is invalid or incomplete: ${errorMessage(e)}`})}})}const tn=f.z.object({objectName:f.z.string().min(1).describe("Name of the existing (or, elsewhere in the same plan, newly created) object this attribute is added to. Ignored for an attribute declared inline in `additive.objects[].attributes` — there the parent object's own `name` is used instead."),name:$t,label:f.z.string().min(1).max(128).describe(`Human-readable display label shown in the UI. 1-128 characters, cannot be empty.`),type:Qt,config:f.z.record(f.z.string(),f.z.unknown()).optional().describe('Type-specific configuration; required keys depend on `type` (see `type`\'s description). Shared optional keys on every type: `placeholder`, `defaultValue`, `icon`, `order`, `hidden`, `archived`, `deprecated`, `metadata`. Per-type keys: `text` — `multiline`, `minLength`, `maxLength`, `pattern`, `format` ("email"|"url"|"slug"); `number` — `renderAs` ("number"|"rating"), `min`, `max`, `unit`, `decimals`; `date` — `dateFormat`, `minDate`, `maxDate`, `includeTime`, `endDate`, `timeFormat` ("12h"|"24h"); `phone` — `defaultCountryCode` (3-letter); `currency` — `defaultCurrency`, `allowedCurrencies`, `allowNegative`; `status`/`select`/`multiselect` — `options` (REQUIRED, non-empty array of `{ value, label, color }`, unique `value`s; for `status` every OPTION also carries `group` as idle|in_progress|finished — `group` belongs on each option, never on `config` itself; select/multiselect accept `renderAs: "badges"`); `location` — `granularity`, `defaultCountry`, `allowedCountries`; `user` — `types` ("user"|"agent"), `multiple`; `relation` — `targets` (REQUIRED, non-empty array of `{ object }`) and `cardinality` (REQUIRED, "one"|"many"); `formula` — `expression` (REQUIRED formula string) and `returnType` (REQUIRED); `rollup` — `targetAttribute` (REQUIRED) and `function` (REQUIRED, e.g. "sum"|"avg"|"count"); `document` — `properties`, `accepts`, `maxFileSize`. Omit entirely for `richtext`/`checkbox`, which take no type-specific keys.'),required:f.z.boolean().optional().describe(`Whether the attribute must have a value on every record. Defaults to false (optional).`),description:f.z.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),nn=withConfigCheck(tn),rn=withConfigCheck(tn.omit({objectName:!0})),an=f.z.object({name:en,label:f.z.string().min(1).describe(`Human-readable singular display label (e.g. "Devis").`),pluralLabel:f.z.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:f.z.string().optional().describe(`Help text describing what this object represents.`),icon:e.x.describe("Required icon name for the object. Must be a catalogue value — call `search_icons` and use a name it returns verbatim. A name that is not in the catalogue is rejected without any hint as to what would have worked, so never guess one."),labelExpression:D.describe("Titles every record of this object; syntax in <expressions>. Each attribute it interpolates must exist on the object — declared in this same `attributes` array, or already on it when this is an update."),attributes:f.z.array(rn).default([]).describe("Attributes to create on this new object, inline. Same rules as a standalone entry in `additive.attributes`, minus `objectName` (implied by this object). At least one attribute referenced by `labelExpression` should be included here.")}).strict(),on=f.z.object({attributeRemovals:f.z.array(f.z.object({objectName:f.z.string().min(1).describe(`Object the attribute is removed from.`),attributeName:f.z.string().min(1).describe("Attribute to delete, together with every record's stored value for it. Must not be a system (code-declared) attribute, and must not be referenced by the object's own `labelExpression` or `embeddingExpression` — update those first.")}).strict()).default([]).describe(`Attributes to permanently delete. Irreversible: record values for the attribute are purged.`),objectRemovals:f.z.array(f.z.object({objectName:f.z.string().min(1).describe("Object to delete entirely, together with all its records. Must not be a system (code-declared) object, and must not still be targeted by a `relation` attribute on another object — retarget or remove that relation first.")}).strict()).default([]).describe(`Objects to permanently delete, records included. Irreversible.`),renames:f.z.array(f.z.object({objectName:f.z.string().min(1).describe(`Object the renamed attribute belongs to.`),from:f.z.string().min(1).describe(`Current attribute name. Must already exist and not be a system attribute.`),to:$t.describe("New attribute name — same identifier rules as any attribute `name` (see `name` on a planned attribute), and must not collide with another name already on the object, including one added elsewhere in this same plan.")}).strict()).default([]).describe(`Attribute renames. Every reference to the old name (labelExpression, views, formulas) must be updated separately — a rename does not follow references automatically.`)}).strict().default({attributeRemovals:[],objectRemovals:[],renames:[]}),sn=f.z.string().min(1).describe(`ONE sentence naming the intent of the change — what it is for, not what it contains. The human approving it has already watched every entry land in the preview window and can read every row of the plan itself, so a recap tells them nothing they do not have. A second sentence is warranted only when \`destructive\` is non-empty: say plainly what will be lost (e.g. 'deletes the "ancienMontant" column and its data on every devis'). Never restate the plan — explain intent.`),cn=f.z.object({objects:f.z.array(an).default([]),attributes:f.z.array(nn).default([])}).strict().default({objects:[],attributes:[]});function findJsonSafetyIssue(e,t=[],n=new WeakSet){if(e===null||typeof e==`string`||typeof e==`boolean`)return null;if(typeof e==`number`)return Number.isFinite(e)?null:{path:t,message:`Plan input contains a non-finite number`};if(typeof e!=`object`)return{path:t,message:`Plan input must contain only JSON-safe values`};if(n.has(e))return{path:t,message:`Plan input cannot contain circular references`};if(Array.isArray(e)){n.add(e);for(let r of Reflect.ownKeys(e))if(r!==`length`&&(typeof r==`symbol`||!/^(0|[1-9]\d*)$/.test(r)))return n.delete(e),{path:[...t,r],message:`Plan input arrays cannot contain non-index JSON properties`};for(let r=0;r<e.length;r++){if(!Object.hasOwn(e,r))return n.delete(e),{path:[...t,r],message:`Plan input cannot contain sparse arrays`};let i=findJsonSafetyIssue(e[r],[...t,r],n);if(i)return n.delete(e),i}return n.delete(e),null}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return{path:t,message:`Plan input must contain only plain JSON objects`};n.add(e);let i=e,a=Reflect.ownKeys(i);for(let r of a){let a=Object.getOwnPropertyDescriptor(i,r);if(typeof r==`symbol`||!(a?.enumerable&&`value`in a))return n.delete(e),{path:[...t,r],message:`Plan input objects must contain enumerable JSON data properties only`}}for(let r of a.sort()){let a=findJsonSafetyIssue(i[r],[...t,r],n);if(a)return n.delete(e),a}return n.delete(e),null}function mutationPaths(e){let t=[];return e.additive.objects.forEach((e,n)=>{t.push([`additive`,`objects`,n]),e.attributes.forEach((e,r)=>{t.push([`additive`,`objects`,n,`attributes`,r])})}),e.additive.attributes.forEach((e,n)=>{t.push([`additive`,`attributes`,n])}),e.destructive.attributeRemovals.forEach((e,n)=>{t.push([`destructive`,`attributeRemovals`,n])}),e.destructive.objectRemovals.forEach((e,n)=>{t.push([`destructive`,`objectRemovals`,n])}),e.destructive.renames.forEach((e,n)=>{t.push([`destructive`,`renames`,n])}),t}function addPlanLimitIssues(e,t){e.additive.objects.length>z.objectAdditions&&t.addIssue({code:`too_big`,origin:`array`,maximum:z.objectAdditions,inclusive:!0,path:[`additive`,`objects`,z.objectAdditions],message:`A schema plan can add at most ${z.objectAdditions} objects`});let n=mutationPaths(e);n.length>z.totalMutations&&t.addIssue({code:`too_big`,origin:`array`,maximum:z.totalMutations,inclusive:!0,path:n[z.totalMutations],message:`A schema plan can contain at most ${z.totalMutations} mutations; received ${n.length}`})}function boundSerializedPlanInput(e,t){let n=findJsonSafetyIssue(e);if(n)return t.addIssue({code:`custom`,path:n.path,message:n.message}),f.z.NEVER;let i=new TextEncoder().encode(r.s(e)).byteLength;return i>z.serializedBytes?(t.addIssue({code:`too_big`,origin:`string`,maximum:z.serializedBytes,inclusive:!0,path:[],message:`A schema plan can serialize to at most ${z.serializedBytes} UTF-8 bytes; received ${i}`}),f.z.NEVER):e}const ln=f.z.object({schemaPlanVersion:f.z.literal(2).describe(`Required proposal contract version.`),summary:sn,additive:cn,destructive:on}).strict().superRefine(addPlanLimitIssues),un=Object.assign(f.z.preprocess(boundSerializedPlanInput,ln),{shape:ln.shape}),dn=f.z.object({schemaPlanVersion:f.z.literal(2),summary:sn,additive:cn,destructive:on}).strict().superRefine(addPlanLimitIssues),fn=f.z.preprocess(boundSerializedPlanInput,dn);function reject$1(e,t){throw new n.ValidationError(t,[{path:e,message:t}])}function exhaustive(e){throw new n.ValidationError(`Unsupported schema reference variant ${String(e)}`,[])}function collectSchemaReferences(t){let n=new Map(t.objects.map(e=>[e.name,e])),r=[];function visitor(e,t,i){function add(a,o,s){(a.kind===`object`?n.has(a.object):a.kind!==`attribute`||n.get(a.object)?.attributes.some(e=>e.name===a.attribute))||reject$1([...t,...s],`Unknown schema reference ${JSON.stringify(a)}`),r.push({owner:e,target:a,category:o,path:s,...i===void 0?{}:{layer:i}})}function attribute(e,t,n,r){add({kind:`attribute`,object:e,attribute:t},n,r)}function traverse(e,r,i,a,o){attribute(e,r,i,a);let s=n.get(e)?.attributes.find(e=>e.name===r);return s?.type!==`relation`&&reject$1([...t,...a],`Invalid schema reference path "${o}"`),(s.targets.length!==1||s.targets[0].object===`*`)&&reject$1([...t,...a],`Ambiguous schema reference path "${o}"`),s.targets[0].object}function attributePath(e,t,n,r){let i=e;for(let[e,a]of t.entries())e===t.length-1?attribute(i,a,n,r):i=traverse(i,a,n,r,t.join(`.`))}function formula(e,t,n){switch(t.kind){case`literal`:return;case`path`:attributePath(e,t.parts,`computed`,n);return;case`call`:for(let r of t.args)formula(e,r,n);return;case`binary`:formula(e,t.left,n),formula(e,t.right,n);return;default:exhaustive(t)}}return{add,attribute,traverse,attributePath,formula}}t.objects.forEach((t,n)=>{let r=[`objects`,String(n)],i=visitor({kind:`object`,object:t.name},r);for(let e of[`labelExpression`,`embeddingExpression`]){let n=t[e];if(n)for(let r of extractAttributeNames(n))i.attributePath(t.name,r.split(`.`),`business`,[e])}t.attributes.forEach((n,i)=>{let a=[...r,`attributes`,String(i)],o=visitor({kind:`attribute`,object:t.name,attribute:n.name},a);switch(n.type){case`relation`:n.targets.forEach((e,t)=>{if(e.object!==`*`&&o.add({kind:`object`,object:e.object},`structural`,[`targets`,String(t),`object`]),e.displayTemplate)for(let n of extractAttributeNames(e.displayTemplate))o.attributePath(e.object,n.split(`.`),`business`,[`targets`,String(t),`displayTemplate`]);for(let n of Object.keys(e.filter??{}))o.attribute(e.object,n,`business`,[`targets`,String(t),`filter`,n])});break;case`formula`:{let r;try{r=e.y(n.expression)}catch(e){reject$1([...a,`expression`],e instanceof Error?e.message:String(e))}o.formula(t.name,r,[`expression`]),visitOptions(n,o);break}case`rollup`:{let e=n.relationPath??n.relationAttribute,r=t.name;for(let t of e.split(`.`))r=o.traverse(r,t,`computed`,[n.relationPath===void 0?`relationAttribute`:`relationPath`],e);o.attributePath(r,n.targetAttribute.split(`.`),`computed`,[`targetAttribute`]),visitOptions(n,o);break}case`text`:case`richtext`:case`number`:case`checkbox`:case`date`:case`phone`:case`currency`:case`status`:case`location`:case`select`:case`multiselect`:case`user`:case`document`:break;default:exhaustive(n)}})});function visitOptions(e,t){e.optionsSource&&(t.add({kind:`object`,object:e.optionsSource.objectName},`computed`,[`optionsSource`,`objectName`]),t.attribute(e.optionsSource.objectName,e.optionsSource.attributeName,`computed`,[`optionsSource`,`attributeName`]))}function viewReferences(e,t,r){visitor({kind:`view`,object:e.object,view:e.name},t,r).add({kind:`object`,object:e.object},`structural`,[`object`]),e.contents.forEach((i,a)=>{let o=visitor({kind:`content`,object:e.object,view:e.name,content:i.name},[...t,`contents`,String(a)],r);function names(e,t,n,r){e?.forEach((e,i)=>o.attribute(t,e,n,[r,String(i)]))}switch(i.type){case`collection`:{let r=collectionSourceAddress(i.source),s;switch(r.kind===`object`?(s=r.object,o.add({kind:`object`,object:s},`source`,[`source`,`object`])):r.kind===`relatedFrom`?(s=r.object,o.add({kind:`object`,object:s},`source`,[`source`,`object`]),o.attribute(s,r.relation,`source`,[`source`,`relation`])):s=o.traverse(e.object,r.relation,`source`,[`source`,`relation`],r.relation),i.columns?.forEach((i,c)=>{if(typeof i==`string`){o.attribute(s,i,`display`,[`columns`,String(c)]);return}let l=n.get(e.object),u=r.kind!==`related`||!l?void 0:findRelationAttribute(l,r.relation),d=[`columns`,String(c),`relationProperty`];u||reject$1([...t,`contents`,String(a),...d],`Relation property columns require a relation source`),u.properties?.definitions.some(e=>e.name===i.relationProperty)||reject$1([...t,`contents`,String(a),...d],`Unknown relation property "${i.relationProperty}"`),o.add({kind:`attribute`,object:e.object,attribute:u.name},`display`,d)}),names(i.displayAttributes,s,`display`,`displayAttributes`),i.descriptionAttribute!==void 0&&o.attribute(s,i.descriptionAttribute,`display`,[`descriptionAttribute`]),i.filters?.rules.forEach((e,t)=>o.attribute(s,e.attribute,`business`,[`filters`,`rules`,String(t),`attribute`])),i.sorts?.forEach((e,t)=>o.attribute(s,e.attribute,`business`,[`sorts`,String(t),`attribute`])),i.layout){case`table`:case`list`:if(i.columnSizing)for(let e of Object.keys(i.columnSizing))o.attribute(s,e,`display`,[`columnSizing`,e]);break;case`kanban`:i.groupByAttribute!==void 0&&o.attribute(s,i.groupByAttribute,`business`,[`groupByAttribute`]);break;default:exhaustive(i.layout)}break}case`form`:i.groups.forEach((t,n)=>t.fields.forEach((t,r)=>o.attribute(e.object,t.attribute,`display`,[`groups`,String(n),`fields`,String(r),`attribute`])));break;case`richtext`:o.attribute(e.object,i.attribute,`source`,[`attribute`]),i.titleAttribute!==void 0&&o.attribute(e.object,i.titleAttribute,`display`,[`titleAttribute`]);break;case`documents`:names(i.relations,e.object,`business`,`relations`);break;case`forms`:i.objectName!==void 0&&o.add({kind:`object`,object:i.objectName},`source`,[`objectName`]);break;case`emails`:case`meetings`:names(i.emailAttributes,e.object,`business`,`emailAttributes`);break;case`activity`:case`custom`:break;default:exhaustive(i)}})}return t.views.forEach((e,t)=>viewReferences(e,[`views`,String(t)])),t.retainedViews?.forEach(({definition:e,layer:t},n)=>viewReferences(e,[`retainedViews`,String(n),`definition`],t)),r}const pn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function reject(e,t,r){throw new n.ValidationError(r,[{path:[...e.split(`.`),t],message:r}])}function pairKey(e){return e.join(`|`)}function pairedAddresses(e,t){return[e,t].sort()}function validateExistingPairs(e){let t=new Map,n=new Map,r=new Set;for(let i of e){let e=pairKey(i.addresses);(!pn.test(i.id)||i.addresses[0]===i.addresses[1]!=(i.symmetric===!0))&&reject(i.addresses[0],`pair`,`Invalid stored pair identity for ${e}`),(t.has(e)||n.has(i.id)&&n.get(i.id)!==e||i.addresses.some(e=>r.has(e)))&&reject(i.addresses[0],`pair`,`Duplicate stored pair identity for ${e}`),i.addresses.includes(i.ownerAddress)||reject(i.addresses[0],`pair`,`Invalid property owner for ${e}`),t.set(e,i),n.set(i.id,e);for(let e of i.addresses)r.add(e)}return t}function remapExistingPairs(e,t){let n=new Set(e.flatMap(e=>e.addresses)),r=new Map,i=new Set;for(let{from:e,to:a}of t)(!n.has(e)||e===a||r.has(e)||i.has(a))&&reject(e,`rename`,`Invalid or duplicate relation attribute rename ${e} to ${a}`),r.set(e,a),i.add(a);let mapped=e=>r.get(e)??e;return e.map(e=>({...e,addresses:pairedAddresses(mapped(e.addresses[0]),mapped(e.addresses[1])),ownerAddress:mapped(e.ownerAddress),generatedAddresses:e.generatedAddresses.map(mapped)}))}function isReciprocal(e,t,n){return e.type===`relation`&&e.bilateral?.object===t&&e.bilateral.attribute===n&&e.targets.length===1&&e.targets[0]?.object===t}function generateInverse(e,t,n){let r=e.bilateral;r||reject(`${t}.${e.name}`,`bilateral`,`Missing inverse address`);let i={type:`relation`,name:r.attribute,label:r.label??r.attribute,required:!1,targets:[{object:t}],bilateral:{object:t,attribute:e.name,cardinality:e.cardinality},order:n};return(r.cardinality??inferInverseCardinality(e.cardinality))===`one`?{...i,cardinality:`one`}:{...i,cardinality:`many`}}function checkExplicitDeclarations(e,t,n,i,a){e.bilateral?.cardinality&&e.bilateral.cardinality!==t.cardinality&&reject(i,`cardinality`,`${n} declares ${i} as ${e.bilateral.cardinality}, but ${i} declares ${t.cardinality}`),t.bilateral?.cardinality&&t.bilateral.cardinality!==e.cardinality&&reject(n,`cardinality`,`${i} declares ${n} as ${t.bilateral.cardinality}, but ${n} declares ${e.cardinality}`),e.bilateral?.label&&e.bilateral.label!==t.label&&reject(i,`label`,`${n} declares a different label for ${i}`),t.bilateral?.label&&t.bilateral.label!==e.label&&reject(n,`label`,`${i} declares a different label for ${n}`),e.properties&&t.properties&&!r.r(e.properties,t.properties)&&!a&&reject(i,`properties`,`${n} and ${i} declare different qualified properties`),e.bilateral?.storageOwner===t.bilateral?.storageOwner&&e.bilateral?.storageOwner!==void 0&&reject(i,`storageOwner`,`${n} and ${i} cannot both own or both disown qualified properties`)}function chooseOwner(e,t,n,r,i,a){return i?i.ownerAddress:e.bilateral?.storageOwner===!0||t.bilateral?.storageOwner===!1?n:e.bilateral?.storageOwner===!1||t.bilateral?.storageOwner===!0?r:a?n:pairedAddresses(n,r)[0]}function stripUntrustedPairMetadata(e){if(!e.metadata)return;let{relationPairId:t,relationGenerated:n,...r}=e.metadata;e.metadata=Object.keys(r).length>0?r:void 0}function reconcileProperties(e,t,n,i,a,o){o.has(n)&&o.has(i)&&!r.r(e.properties,t.properties)&&reject(i,`properties`,`${n} and ${i} edit different qualified properties`);let s=o.has(n)||a.has(n)&&!a.has(i)&&!o.has(i),c=o.has(i)||a.has(i)&&!a.has(n)&&!o.has(n),l=s?e.properties:c?t.properties:e.properties??t.properties;l?(e.properties=structuredClone(l),t.properties=structuredClone(l)):(delete e.properties,delete t.properties)}function reconcileRelationAttributes(e){let t=structuredClone(e.objects),r=new Map;for(let e of t){if(r.has(e.name))throw new n.DuplicateError(`object`,e.name);r.set(e.name,e);let t=new Set;for(let r of e.attributes){if(t.has(r.name))throw new n.DuplicateError(`attribute`,r.name);t.add(r.name),stripUntrustedPairMetadata(r)}}let i=remapExistingPairs(e.existingPairs??[],e.addressRenames??[]),a=validateExistingPairs(i),o=new Set(i.flatMap(e=>e.generatedAddresses)),s=new Set(e.propertyEditAddresses??[]),c=new Set(e.explicitAddresses??t.flatMap(e=>e.attributes.filter(t=>!o.has(`${e.name}.${t.name}`)).map(t=>`${e.name}.${t.name}`))),l=t.flatMap(e=>e.attributes.filter(e=>e.type===`relation`&&!!e.bilateral).map(t=>({object:e,attribute:t,address:`${e.name}.${t.name}`}))).sort((e,t)=>e.address.localeCompare(t.address)),u=new Map,d=new Map;for(let{object:t,attribute:o,address:f}of l){let l=o.bilateral?.object;(!l||l===`*`||o.targets.length!==1||o.targets[0]?.object!==l)&&reject(f,`targets`,`Bilateral target of ${f} must be one concrete object`);let p=r.get(l);p||reject(f,`bilateral`,`Unknown inverse object ${l} for ${f}`);let m=`${l}.${o.bilateral?.attribute}`,h=f===m;h&&o.cardinality!==`many`&&reject(f,`cardinality`,`Symmetric self relation ${f} must be many`),h&&o.bilateral?.cardinality&&o.bilateral.cardinality!==o.cardinality&&reject(f,`bilateral`,`Symmetric self relation ${f} needs matching cardinality`);let g=pairedAddresses(f,m),_=pairKey(g);if(u.has(_))continue;let v=p.attributes.find(e=>e.name===o.bilateral?.attribute);if(v&&!isReciprocal(v,t.name,o.name))throw new n.DuplicateError(`attribute`,m);let y=!(v&&c.has(m));v||(v=generateInverse(o,t.name,p.attributes.length),p.attributes.push(v));let b=v;!h&&c.has(f)&&c.has(m)&&checkExplicitDeclarations(o,b,f,m,s.has(f)!==s.has(m));let x=a.get(_),S=x?.id??e.nextPairId(g),ee=i.find(e=>e.id===S&&pairKey(e.addresses)!==_);(!pn.test(S)||ee||d.has(S)&&d.get(S)!==_)&&reject(f,`pair`,`Invalid or duplicate pair identity for ${f} and ${m}`),d.set(S,_);let C=h?f:chooseOwner(o,b,f,m,x,y);o.bilateral&&b.bilateral||reject(f,`bilateral`,`Missing reciprocal configuration for ${f} and ${m}`),o.bilateral={...o.bilateral,cardinality:b.cardinality,label:b.label,storageOwner:C===f},b.bilateral={...b.bilateral,cardinality:o.cardinality,label:o.label,storageOwner:C===m},reconcileProperties(o,b,f,m,c,s),o.metadata={...o.metadata,relationPairId:S},b.metadata={...b.metadata,relationPairId:S},u.set(_,{id:S,addresses:g,ownerAddress:C,generatedAddresses:g.filter(e=>!c.has(e)),...h?{symmetric:!0}:{}})}return{objects:t,pairs:[...u.values()].sort((e,t)=>e.addresses[0].localeCompare(t.addresses[0]))}}const B=f.z.number().finite().nonnegative(),mn=f.z.enum(se),V=f.z.enum(ce),H=f.z.enum(le),hn=f.z.object({provider:mn,model:f.z.string().min(1)}).strict(),gn=f.z.object({speed:V.optional(),reasoning:H.optional()}).strict(),_n=f.z.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),vn=f.z.object({model:hn.optional(),speed:V.optional(),reasoning:H.optional(),imageModel:_n.optional()}).strict(),yn=vn.refine(e=>e.model!==void 0||e.speed!==void 0||e.reasoning!==void 0||e.imageModel!==void 0,{message:`At least one inference override is required`}),bn=f.z.object({model:hn.nullable().optional(),speed:V.nullable().optional(),reasoning:H.nullable().optional(),imageModel:_n.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0&&Object.values(e).every(e=>e!==void 0),{message:`At least one inference override is required`}),xn=f.z.object({label:f.z.string(),denied:f.z.boolean().optional(),deletion:f.z.object({target:f.z.string().optional(),count:B.optional(),restorableDays:B.optional()}).strict().optional(),counts:f.z.record(f.z.string(),B).optional(),warnings:f.z.array(f.z.string()).optional()}).strict(),Sn=f.z.union([f.z.object({type:f.z.literal(`text`),text:f.z.string()}).strict(),f.z.object({type:f.z.literal(`reasoning`),text:f.z.string()}).strict(),f.z.object({type:f.z.literal(`system`),code:f.z.enum(fe)}).strict(),f.z.object({type:f.z.literal(`error`),error:f.z.string(),errorClass:f.z.string().optional()}).strict(),f.z.object({type:f.z.literal(`tool`),toolCallId:f.z.string(),name:f.z.string(),args:f.z.record(f.z.string(),f.z.unknown()),result:f.z.unknown().optional(),error:f.z.string().optional(),errorCode:f.z.enum([`output_limit_reached`,`interrupted`]).optional(),state:f.z.enum([`streaming`,`running`,`completed`,`error`,`pending`,`approval-requested`,`approval-responded`,`approval-dispatched`]),durationMs:B.optional(),approvalId:f.z.string().optional(),approvalImpact:xn.optional(),approved:f.z.boolean().optional(),approvalReason:f.z.string().optional(),approvalRelaxableByAuto:f.z.boolean().optional()}).strict(),f.z.object({type:f.z.literal(`file`),fileId:f.z.string(),name:f.z.string(),mimeType:f.z.string()}).strict(),f.z.object({type:f.z.literal(`compaction`),state:f.z.literal(`in-progress`),reason:f.z.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:B.optional(),reportedTokens:B.optional()}).strict(),f.z.object({type:f.z.literal(`compaction`),state:f.z.literal(`completed`),tokensBefore:B,tokensAfter:B,tokensSaved:B,strategy:f.z.enum([`no-op`,`summary`,`truncation`]),durationMs:B,summary:f.z.string().optional()}).strict(),f.z.object({type:f.z.literal(`compaction`),state:f.z.literal(`failed`),reason:f.z.string(),durationMs:B.optional()}).strict()]),Cn=f.z.object({id:f.z.string(),name:f.z.string(),mimeType:f.z.string(),size:B}).strict(),wn=f.z.object({id:f.z.string(),type:f.z.string().transform(e=>e),entityId:f.z.string(),label:f.z.string(),objectName:f.z.string().optional(),startIndex:B,endIndex:B}).strict(),Tn=f.z.object({provider:mn,model:f.z.string(),maxTokens:B.optional(),contextWindow:B.optional()}).strict(),En=f.z.union([f.z.date(),f.z.string().datetime({offset:!0}).transform(e=>new Date(e))]),Dn=f.z.object({id:f.z.string(),sessionId:f.z.string(),tenantId:f.z.string().optional(),runId:f.z.string().optional(),role:f.z.enum([`user`,`assistant`,`system`,`tool`]),parts:f.z.array(Sn),attachments:f.z.array(Cn).optional(),mentions:f.z.array(wn).optional(),model:Tn.optional(),tokenUsage:f.z.object({input:B,output:B}).strict().optional(),metadata:f.z.record(f.z.string(),f.z.unknown()).optional(),createdAt:En}).strict(),On=f.z.object({id:f.z.string(),description:f.z.string(),status:f.z.enum([`pending`,`in_progress`,`completed`,`blocked`]),result:f.z.string().optional(),updatedAt:B.optional()}).strict(),kn=f.z.object({id:f.z.string(),sessionId:f.z.string(),status:f.z.enum([`active`,`completed`,`abandoned`]),todos:f.z.array(On),version:B,createdAt:f.z.string(),updatedAt:f.z.string(),completedAt:f.z.string().optional()}).strict(),An={"session-named":f.z.object({name:f.z.string()}).strict(),"compaction-start":f.z.object({reason:f.z.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:B.optional(),reportedTokens:B.optional()}).strict(),"compaction-end":f.z.object({tokensBefore:B,tokensAfter:B,tokensSaved:B,strategy:f.z.enum([`no-op`,`summary`,`truncation`]),durationMs:B,summary:f.z.string().optional()}).strict(),"compaction-failed":f.z.object({reason:f.z.string()}).strict(),usage:f.z.object({messageId:f.z.string().min(1).optional(),inputTokens:B,outputTokens:B,totalTokens:B,cacheReadTokens:B.optional(),cacheCreationTokens:B.optional(),contextWindow:B,residentTokens:B,utilization:f.z.number().finite().min(0).max(1),costUsd:B.optional()}).strict(),"message-persisted":f.z.object({message:Dn}).strict(),"message-updated":f.z.object({message:Dn}).strict(),"todo-plan-update":f.z.object({plan:kn}).strict(),"approval-context":f.z.object({approvalId:f.z.string(),toolCallId:f.z.string(),impact:xn.optional(),relaxableByAuto:f.z.boolean().optional()}).strict(),"session-state":f.z.object({state:f.z.object({phase:f.z.enum([`queued`,`running`,`parked`,`terminal`]),parkedOn:f.z.enum([`human`,`agents`]).optional(),humanRequestIds:f.z.array(f.z.string()).optional(),outcome:f.z.enum([`completed`,`failed`,`cancelled`,`timeout`,`expired`]).optional()}).strict(),version:f.z.number().int().positive(),updatedAt:f.z.string().datetime({offset:!0})}).strict()};function isAgentUIDataName(e){return e in An}function agentUIValidationError(e){return new n.ValidationError(`Invalid agent UI message chunk`,e.map(e=>({path:e.path.map(String),message:e.message,code:e.code})))}function assertCustomAgentUIMessageChunk(e){if(typeof e!=`object`||!e||typeof e.type!=`string`)throw new n.ValidationError(`Invalid agent UI message chunk`,[{path:[`type`],message:`Expected UI message chunk type`,code:`invalid_type`}]);let t=e.type;if(!t.startsWith(`data-`))throw new n.ValidationError(`Invalid agent UI message chunk`,[{path:[`type`],message:`Expected agent data chunk type`,code:`invalid_value`}]);let r=t.slice(5);if(!isAgentUIDataName(r))throw new n.ValidationError(`Invalid agent UI message chunk`,[{path:[`type`],message:`Unknown agent UI data type: ${r}`,code:`invalid_value`}]);let i=f.z.object({type:f.z.literal(`data-${r}`),id:f.z.string().optional(),data:An[r],transient:f.z.boolean().optional()}).strict().safeParse(e);if(!i.success)throw agentUIValidationError(i.error.issues);return i.data}function agentDataChunk(e,t,n){return assertCustomAgentUIMessageChunk({type:`data-${e}`,...n?.id===void 0?{}:{id:n.id},data:t,...n?.transient===void 0?{}:{transient:n.transient}})}function defineOperation(e){return e}function definePresentation(e,t,n){let r=t===`atomic`?`none`:t===`local`?`if-not-visible`:`follow`;return i=>{let a=n?.(i);return{impact:t,navigation:r,focus:{...e(i),...a===void 0?{}:{propertyPath:a}}}}}const jn=[`pluralLabel`,`description`,`labelExpression`,`embeddingExpression`];function draftObjectSettings(e){return Object.fromEntries(jn.filter(t=>e[t]!==void 0).map(t=>[t,e[t]]))}function toDraftableObject(e){return{id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},...draftObjectSettings(e)}}function toDraftableAttributes(e){let t=e.id??e.name;return(e.attributes??[]).map(e=>toDraftableAttribute(e,t))}function toAttribute(e){return{id:e.id,name:e.name,label:e.label,type:e.attributeType,...e.config}}function toDraftableAttribute(e,t){let{id:n,name:r,label:i,type:a,...o}=e;return{id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:o}}function draftedLabelExpression(e){let t=e[0];return t?`{{ ${t.name} }}`:`{{ id }}`}function draftedObjectDefinition(e,t){let n=t.filter(t=>t.objectId===e.id);return{id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},...draftObjectSettings(e),labelExpression:e.labelExpression??draftedLabelExpression(n),attributes:n.map((e,t)=>{let n=toAttribute(e);return n.order===void 0?{...n,order:t}:n})}}function toDraftableView(e,t,n=workspaceViewAuthoring(e.contents)){return structuredClone({...e,...t,authoring:n})}function draftedViewDefinition(e){let{id:t,revision:n,contentIds:r,contentRevisions:i,derived:a,authoring:o,...s}=e;return structuredClone(s)}function fromDraftableView(e,t){return{...e,...draftedViewDefinition(t)}}const Mn={id:f.z.string().min(1).describe(`Your id, echoed back`),note:f.z.string().trim().min(1).max(160).optional().describe(`Why, in the person's words, ≤160 chars`)},U={...Mn,objectName:f.z.string().min(1).describe(`Object`),viewName:f.z.string().min(1).describe(`View API name`)},W={...U,contentName:f.z.string().min(1).describe(`Content API name`)},Nn=f.z.union([f.z.object({before:f.z.string().min(1).describe(`Place immediately before this content name`)}).strict(),f.z.object({after:f.z.string().min(1).describe(`Place immediately after this content name`)}).strict(),f.z.object({end:f.z.literal(!0).describe(`Place at the end of the placement zone`)}).strict()]),viewFocus=e=>({objectName:e.objectName,viewName:e.viewName}),contentFocus=e=>({...viewFocus(e),contentName:e.contentName});function invalid(e,t){throw new n.ValidationError(t,[{path:e,message:t}])}function change(e,t,n,r){let i=e.views.findIndex(e=>e.object===t.objectName&&e.name===t.viewName);i<0&&invalid([`viewName`],`View is not in the draftable state`),e.views[i].authoring||invalid([`authoring`],`Missing view authoring baseline`);let{derived:a,...o}=r(structuredClone(e.views[i]));o.contents=resolveViewContents(o.authoring);let s=e.views.map((e,t)=>t===i?o:e);return validateContentViewCatalogue({extensions:[...n.extensions],objects:e.objects.map(t=>draftedObjectDefinition(t,e.attributes.filter(e=>e.objectId===t.id))),views:s.map(draftedViewDefinition)}),{...e,views:s}}function contentState(e,t){let n=Object.hasOwn(e.authoring.contents,t)?e.authoring.contents[t]:void 0;return n||invalid([`contentName`],`Content is not in the draftable state`),n}function setOrder(e,t,n){for(let r of n)e.authoring[r===`main`?`mainOrderCustomized`:`asideOrderCustomized`]=!0,t.filter(e=>e.placement===r).forEach((t,n)=>{contentState(e,t.name).workspacePosition=n})}function find(e,t){let n=e.contents.find(e=>e.name===t);return n||invalid([`contentName`],`Content is not in the draftable state`),n}function placed(e,t,n){let r=e.filter(e=>e.name!==t.name),i=r.filter(e=>e.placement===t.placement),a=i.length;if(!(`end`in n)){let e=`before`in n?n.before:n.after;a=i.findIndex(t=>t.name===e),a<0&&invalid([`target`],`Order target is not in this placement`),`after`in n&&a++}return i.splice(a,0,t),t.placement===`main`?[...i,...r.filter(e=>e.placement===`aside`)]:[...r.filter(e=>e.placement===`main`),...i]}const Pn=f.z.unknown().transform((e,n)=>{let r=t.u.safeParse(typeof e==`object`&&e?{...e,name:`candidate`}:e);if(!r.success){for(let e of r.error.issues)n.addIssue({code:`custom`,path:e.path,message:e.message});return f.z.NEVER}let i=typeof e==`object`&&e&&`name`in e?e.name:void 0;return{...r.data,name:i}}),Fn=f.z.object({...W,type:f.z.literal(`replace_view_content`),definition:Pn}).strict().superRefine((e,t)=>{e.definition.name!==void 0&&e.definition.name!==e.contentName&&t.addIssue({code:`custom`,path:[`definition`,`name`],message:`must equal the target contentName, or be omitted`})}).overwrite(e=>{let{name:t,...n}=e.definition;return{...e,definition:n}}),In=t.u.describe(`The whole content definition.`),Ln=defineOperation({type:`replace_view_content`,summary:`Replaces a content's whole definition; placement can't change here (use move_view_content); first content op freezes derived views.`,schema:Fn,wire:f.z.object({...W,type:f.z.literal(`replace_view_content`),definition:In}).strict().describe(`definition.name, if sent, must equal contentName — the operation's own target; a different name is refused.`),focus:contentFocus,presentation:definePresentation(contentFocus,`local`),describe:e=>`Replace ${e.objectName}.${e.viewName}.${e.contentName}`,apply:(e,t,n)=>change(e,t,n,e=>(find(e,t.contentName).placement!==t.definition.placement&&invalid([`definition`,`placement`],`Use move_view_content to change placement`),contentState(e,t.contentName).workspaceDefinition=structuredClone(t.definition),{...e,contents:e.contents.map(e=>e.name===t.contentName?{...t.definition,name:t.contentName}:e),contentRevisions:{...e.contentRevisions,[t.contentName]:e.contentRevisions[t.contentName]+1}}))}),Rn=f.z.object({...U,type:f.z.literal(`add_view_content`),content:In,target:Nn.describe(`Where to place the new content within its placement zone`)}).strict(),addFocus=e=>({...viewFocus(e),contentName:e.content.name}),zn=defineOperation({type:`add_view_content`,summary:`Adds a content; content.name unique; collection view needs collection with source.object; aside holds one content, a form; target positions it among siblings.`,schema:Rn,focus:addFocus,presentation:definePresentation(addFocus,`structural`),describe:e=>`Add ${e.content.name}`,apply:(e,t,r)=>change(e,t,r,e=>{if(Object.hasOwn(e.authoring.contents,t.content.name))throw new n.DuplicateError(`content`,t.content.name);e.authoring.contents={...e.authoring.contents,[t.content.name]:{sourceDefinition:null,workspaceDefinition:storedContentDefinition(t.content),suppressed:!1,sourcePosition:null,workspacePosition:0}};let r=placed(e.contents,t.content,t.target);return setOrder(e,r,[t.content.placement]),{...e,revision:e.revision+1,contents:r,contentIds:{...e.contentIds,[t.content.name]:JSON.stringify([`draft-content`,t.id])},contentRevisions:{...e.contentRevisions,[t.content.name]:1}}})}),Bn=f.z.object({...W,type:f.z.literal(`remove_view_content`)}).strict(),Vn=defineOperation({type:`remove_view_content`,summary:`Removes a content; a published view keeps ≥1 main content; a code-declared content is hidden, not deleted.`,schema:Bn,focus:contentFocus,presentation:definePresentation(contentFocus,`structural`),describe:e=>`Remove ${e.contentName}`,apply:(e,t,n)=>change(e,t,n,e=>{let n=find(e,t.contentName),r=contentState(e,t.contentName);if(setOrder(e,e.contents.filter(e=>e.name!==t.contentName),[n.placement]),r.sourceDefinition!==null)return r.workspaceDefinition=null,r.suppressed=!0,{...e,revision:e.revision+1,contentRevisions:{...e.contentRevisions,[t.contentName]:e.contentRevisions[t.contentName]+1}};delete e.authoring.contents[t.contentName];let{[t.contentName]:i,...a}=e.contentIds,{[t.contentName]:o,...s}=e.contentRevisions;return{...e,revision:e.revision+1,contents:e.contents.filter(e=>e.name!==t.contentName),contentIds:a,contentRevisions:s}})}),Hn=f.z.object({...W,type:f.z.literal(`move_view_content`),placement:f.z.enum([`main`,`aside`]).describe(`The placement zone to move the content into`),target:Nn.describe(`Where to place the content within that placement zone`)}).strict(),Un=defineOperation({type:`move_view_content`,summary:`Reorders or moves a content to a different placement; the aside rule applies.`,schema:Hn,focus:contentFocus,presentation:definePresentation(contentFocus,`structural`),describe:e=>`Move ${e.contentName}`,apply:(e,t,n)=>change(e,t,n,e=>{let n=find(e,t.contentName);n.placement!==t.placement&&(contentState(e,t.contentName).workspaceDefinition={...storedContentDefinition(n),placement:t.placement});let r=placed(e.contents,{...n,placement:t.placement},t.target);return setOrder(e,r,[...new Set([n.placement,t.placement])]),{...e,revision:e.revision+1,contents:r,contentRevisions:{...e.contentRevisions,[t.contentName]:e.contentRevisions[t.contentName]+Number(n.placement!==t.placement)}}})}),Wn=f.z.object({...U,type:f.z.literal(`update_view_metadata`),changes:f.z.object({label:f.z.string().min(1).optional().describe(`New label for the view`),description:f.z.string().optional().describe(`New description for the view`),icon:e.x.nullable().optional().describe(`New icon; null clears it`)}).strict().refine(e=>Object.keys(e).length>0).describe(`≥1 change`)}).strict(),Gn=defineOperation({type:`update_view_metadata`,summary:`Updates a view's label, description, or icon (null clears the icon).`,schema:Wn,focus:viewFocus,presentation:definePresentation(viewFocus,`atomic`),describe:e=>`Update ${e.viewName}`,apply:(e,t,n)=>change(e,t,n,e=>{let{icon:n,...r}=t.changes,i={...e,...r,revision:e.revision+1};if(n===null){let{icon:e,...t}=i;return t}return n===void 0?i:{...i,icon:n}})}),Kn=f.z.string().refine(e=>e.trim().length>0,`API name must not be blank`),qn=f.z.object({...U,type:f.z.literal(`rename_view`),newName:Kn.describe(`New API name for the view`)}).strict(),renameViewFocus=e=>({objectName:e.objectName,viewName:e.newName}),Jn=defineOperation({type:`rename_view`,summary:`Renames a view; refused on a code-declared name — change it in the declaration.`,schema:qn,focus:renameViewFocus,presentation:definePresentation(renameViewFocus,`structural`),describe:e=>`Rename view ${e.viewName} to ${e.newName}`,apply:(e,t,n)=>change(e,t,n,n=>t.newName===n.name?n:(n.authoring.origin===`code`&&invalid([`newName`],`Source-owned API names must be changed in their declaration`),e.views.some(e=>e.object===t.objectName&&e.name===t.newName)&&invalid([`newName`],`View API name is already used`),{...n,name:t.newName,revision:n.revision+1}))}),Yn=f.z.object({...W,type:f.z.literal(`rename_view_content`),newName:Kn.describe(`New API name for the content`)}).strict(),renameContentFocus=e=>({...viewFocus(e),contentName:e.newName}),Xn=defineOperation({type:`rename_view_content`,summary:`Renames a content; refused on a code-declared name — change it in the declaration.`,schema:Yn,focus:renameContentFocus,presentation:definePresentation(renameContentFocus,`structural`),describe:e=>`Rename content ${e.contentName} to ${e.newName}`,apply:(e,t,n)=>change(e,t,n,e=>{let n=contentState(e,t.contentName);if(t.newName===t.contentName)return e;n.sourceDefinition!==null&&invalid([`newName`],`Source-owned API names must be changed in their declaration`),Object.hasOwn(e.authoring.contents,t.newName)&&invalid([`newName`],`Content API name is already used`);let r=e.contentIds[t.contentName],i=e.contentRevisions[t.contentName];return delete e.authoring.contents[t.contentName],delete e.contentIds[t.contentName],delete e.contentRevisions[t.contentName],e.authoring.contents={...e.authoring.contents,[t.newName]:n},{...e,revision:e.revision+1,contentIds:{...e.contentIds,[t.newName]:r},contentRevisions:{...e.contentRevisions,[t.newName]:i+1}}})}),Zn=f.z.object({...W,type:f.z.literal(`reset_view_content`)}).strict(),Qn=defineOperation({type:`reset_view_content`,summary:`Resets a content back to its code-declared source; only works when one exists.`,schema:Zn,focus:contentFocus,presentation:definePresentation(contentFocus,`structural`),describe:e=>`Reset ${e.contentName} to source`,apply:(e,t,n)=>change(e,t,n,e=>{let n=contentState(e,t.contentName);return n.sourceDefinition===null&&invalid([`contentName`],`Content has no source to reset to`),n.workspaceDefinition===null&&!n.suppressed&&n.workspacePosition===null?e:(n.workspaceDefinition=null,n.suppressed=!1,n.workspacePosition=null,{...e,revision:e.revision+1,contentRevisions:{...e.contentRevisions,[t.contentName]:e.contentRevisions[t.contentName]+1}})})}),$n=f.z.object({...U,type:f.z.literal(`reset_view_order`),placement:f.z.enum([`main`,`aside`]).describe(`The placement zone to reset to source order`)}).strict(),er=defineOperation({type:`reset_view_order`,summary:`Resets a placement zone's order to its code-declared source, if one exists.`,schema:$n,focus:viewFocus,presentation:definePresentation(viewFocus,`structural`),describe:e=>`Reset ${e.placement} order`,apply:(e,t,n)=>change(e,t,n,e=>{let n=t.placement===`main`?`mainOrderCustomized`:`asideOrderCustomized`;if(!e.authoring[n])return e;e.authoring[n]=!1;for(let n of e.contents.filter(e=>e.placement===t.placement)){let t=contentState(e,n.name);t.sourceDefinition!==null&&(t.workspacePosition=null)}return{...e,revision:e.revision+1}})}),tr=f.z.discriminatedUnion(`type`,[Fn,Rn,Bn,Hn,Wn,qn,Yn,Zn,$n]),G=[Ln,zn,Vn,Un,Gn,Jn,Xn,Qn,er];function findObject(e,t){return e.objects.find(e=>e.id===t)}const nr=new Set([`formula`,`rollup`]);function isComputedAttribute(e){return nr.has(e.attributeType)}const rr={sum:`number`,avg:`number`,count:`number`,countValues:`number`,countUniqueValues:`number`,countEmpty:`number`,percentEmpty:`number`,percentNotEmpty:`number`,earliest:`date`,latest:`date`,original:`multiselect`};function rollupReturnTypeOf(e){return typeof e==`string`&&e in rr?rr[e]:void 0}function requireObject$1(e,t){let r=findObject(e,t);if(!r)throw new n.ValidationError(`Object "${t}" is not in the draftable state`,[]);return r}function configOf(e){return e.config??{}}function relationTargets(e){let t=configOf(e).targets;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.object==`string`):[]}function relationTargetObjectName(e){let t=relationTargets(e).filter(e=>e.object!==`*`);return t.length===1?t[0]?.object:void 0}function toCompileAttribute(e){let t=configOf(e),n=e.attributeType,r={name:e.name,type:n,id:e.id},i=t.optionsSource;if(n===`relation`){let n=relationTargetObjectName(e);return{...r,...t.cardinality===`one`||t.cardinality===`many`?{cardinality:t.cardinality}:{},...n===void 0?{}:{targetObjectName:n},targets:relationTargets(e)}}if(n===`formula`)return{...r,...t.returnType===void 0?{}:{returnType:t.returnType},...i===void 0?{}:{optionsSource:i}};if(n===`rollup`){let e=rollupReturnTypeOf(t.function);return{...r,...e===void 0?{}:{returnType:e},...i===void 0?{}:{optionsSource:i}}}return n===`select`||n===`status`||n===`multiselect`?{...r,...Array.isArray(t.options)?{options:t.options}:{}}:r}function toCompileObject(e,t){return{objectName:e.name,attributes:t.filter(t=>t.objectId===e.id).map(toCompileAttribute)}}function computedCompileSchemaOf(e,t){return{...toCompileObject(requireObject$1(e,t),e.attributes),relatedObjects:Object.fromEntries(e.objects.map(t=>[t.name,toCompileObject(t,e.attributes)]))}}function toRollupAttribute(e){return{id:e.id,name:e.name,label:e.label,type:`rollup`,...configOf(e)}}function asValidationError(e){try{return e()}catch(e){throw e instanceof ComputedFormulaCompileError?new n.ValidationError(e.message,[]):e}}function computedPlanOf(e,t){let n=computedCompileSchemaOf(e,t.objectId);return asValidationError(()=>compilePlan(t,n))}function compilePlan(e,t){if(e.attributeType===`rollup`)return compileRollupAttribute(toRollupAttribute(e),t);let n=configOf(e);return compileComputedFormula({attributeName:e.name,expression:String(n.expression??``),returnType:n.returnType,schema:t})}function assertAcyclicComputed(e){asValidationError(()=>assertAcyclicComputedDependencies(e.map(e=>({attributeName:e.attributeName,dependencies:e.dependencies}))))}function dependencyNames(e,t){switch(e.kind){case`local`:case`computed`:return e.attributeName===t;case`relation`:return e.relationName===t;case`options`:return!1;default:return e}}function compilablePlansOf(e,t){let n=computedCompileSchemaOf(e,t),r=[];for(let i of e.attributes)if(i.objectId===t&&isComputedAttribute(i))try{r.push(compilePlan(i,n))}catch(e){if(!(e instanceof ComputedFormulaCompileError))throw e}return r}function dependentsOf(e,t,n){let r=requireObject$1(e,t),i=[];for(let r of compilablePlansOf(e,t))r.attributeName!==n&&r.dependencies.some(e=>dependencyNames(e,n))&&i.push(r.attributeName);for(let a of e.objects)if(a.id!==t)for(let t of compilablePlansOf(e,a.id))t.dependencies.some(t=>{if(t.kind!==`relation`||t.targetAttributeName!==n)return!1;let i=e.attributes.find(e=>e.objectId===a.id&&e.name===t.relationName&&e.attributeType===`relation`);return i!==void 0&&relationTargetObjectName(i)===r.name})&&i.push(`${a.name}.${t.attributeName}`);return i}function bilateralDeclarationOf(e){let t=e.config?.bilateral;if(typeof t!=`object`||!t)return;let{object:n,attribute:r}=t;return typeof n==`string`&&typeof r==`string`?{object:n,attribute:r}:void 0}function sameAttribute(e,t){return t!==void 0&&e.attributeType===t.attributeType&&sameConfig(e,t)}function sameConfig(e,t){return JSON.stringify(e.config??{})===JSON.stringify(t.config??{})}function assertBilateralPairs(e,t){let untouched=t=>sameAttribute(t,e.attributes.find(e=>e.id===t.id));for(let e of t.attributes){if(e.attributeType!==`relation`)continue;let r=bilateralDeclarationOf(e);if(r===void 0||untouched(e))continue;let i=t.objects.find(t=>t.id===e.objectId)?.name??e.objectId,a=t.objects.find(e=>e.name===r.object),o=t.attributes.find(e=>e.objectId===a?.id&&e.name===r.attribute),s=`relation "${i}.${e.name}" declares inverse "${r.object}.${r.attribute}"`;if(o===void 0)throw new n.ValidationError(`${s}, which object "${r.object}" does not have; draft it first`,[]);if(o.attributeType!==`relation`)throw new n.ValidationError(`${s}, which is not a relation`,[]);let c=bilateralDeclarationOf(o);if(!(relationTargets(o).some(e=>e.object===i)&&(untouched(o)?c===void 0||c.object===i&&c.attribute===e.name:c?.object===i&&c.attribute===e.name)))throw new n.ValidationError(`${s}, which does not point back to "${i}.${e.name}"`,[])}}function fnv1a64(e,t){let n=t;for(let t of new TextEncoder().encode(e))n^=BigInt(t),n=n*1099511628211n&18446744073709551615n;return n}function viewIdFor(e,t){return draftEntityIdFor(t,e.toLowerCase())}function draftEntityIdFor(e,t){let n=`${t}:${e}`,r=fnv1a64(n,14695981039346656037n).toString(16).padStart(16,`0`)+fnv1a64(`${e}:${n}`,9521211207457086692n).toString(16).padStart(16,`0`),i=(Number.parseInt(r[16],16)&3|8).toString(16);return[r.slice(0,8),r.slice(8,12),`8${r.slice(13,16)}`,`${i}${r.slice(17,20)}`,r.slice(20,32)].join(`-`)}function defaultViewIdsFor(e){return{list:viewIdFor(e,`list`),detail:viewIdFor(e,`detail`)}}function derivedView(e,n,r,i){let a=i.filter(e=>e.objectId===r.id).filter(e=>t.B(toAttribute(e)).presentation.formField).map(e=>({attribute:e.name})),o=e===`collection`?[{name:`all`,type:`collection`,placement:`main`,label:`All`,layout:`table`,source:{object:r.name}}]:a.length?[{name:`form`,type:`form`,placement:`main`,label:`Details`,groups:[{name:`general`,label:`General`,fields:a}]}]:[{name:`activity`,type:`activity`,placement:`main`,label:`Activity`}];return{id:n,object:r.name,name:e===`collection`?`default_list`:`default_detail`,label:r.label,context:e,default:!0,contents:o,authoring:workspaceViewAuthoring(o),revision:1,contentIds:Object.fromEntries(o.map(e=>[e.name,JSON.stringify([`draft-content`,n,e.name])])),contentRevisions:Object.fromEntries(o.map(e=>[e.name,1])),derived:!0}}function defaultViewsFor(e,t){let n=defaultViewIdsFor(e.id);return[derivedView(`collection`,n.list,e,t),derivedView(`record`,n.detail,e,t)]}function regenerateDerived(e,t,n){return derivedView(e.context,e.id,t,n)}function isGeneratedDraftRelation(e){return e.attributeType===`relation`&&toAttribute(e).metadata?.relationGenerated===!0}function pairedDraftAttributes(e,t){let n=bilateralDeclarationOf(t);if(!n)return[t];let r=e.objects.find(e=>e.id===t.objectId),i=e.objects.find(e=>e.name===n.object),a=e.attributes.find(e=>e.objectId===i?.id&&e.name===n.attribute);if(!a||a===t)return[t];let o=bilateralDeclarationOf(a);return o&&o.object===r?.name&&o.attribute===t.name?[t,a]:[t]}function reconcileDraftRelationAttribute(e,t,r,i,a=!1){let o=toAttribute(t),s=i&&toAttribute(i),c=i&&bilateralDeclarationOf(i),l=bilateralDeclarationOf(t);if(c&&(c.object!==l?.object||c.attribute!==l?.attribute))throw new n.ValidationError(`Changing a bilateral address requires removing the existing pair first`,[]);if(o.type!==`relation`||!o.bilateral)return e;let u=e.objects.find(e=>e.id===t.objectId),d=e.objects.find(e=>e.name===o.bilateral?.object);if(!(u&&d))throw new n.ValidationError(`Both objects must exist before materializing a relation pair`,[]);let f=`${u.name}.${t.name}`,p=o.bilateral.attribute,m=`${d.name}.${p}`,h=e.attributes.find(e=>e.objectId===d.id&&e.name===p),g=s?.metadata?.relationPairId,_=typeof g==`string`?g:draftEntityIdFor(`relation-pair`,`${r}:${t.id}`),v=[f,m].sort(),y=typeof g==`string`?{id:_,addresses:v,ownerAddress:s?.type===`relation`&&s.bilateral?.storageOwner===!1?m:f,generatedAddresses:[],...f===m?{symmetric:!0}:{}}:void 0,b=reconcileRelationAttributes({objects:[...new Map([u,d].map(e=>[e.id,e])).values()].map(e=>({name:e.name,attributes:[t,...h&&h.id!==t.id?[h]:[]].filter(t=>t.objectId===e.id).map(toAttribute)})),existingPairs:y?[y]:[],...i&&!a?{explicitAddresses:[f],propertyEditAddresses:[f]}:{},nextPairId:()=>_}),x=new Map;for(let n of b.objects){let r=n.name===u.name?u.id:d.id;for(let o of n.attributes){let n=e.attributes.find(e=>e.objectId===r&&e.name===o.name),s=n?.id===t.id?i??n:n,c={...preserveDeclarationHints(o,n&&toAttribute(n)),metadata:{...o.metadata,...s&&isGeneratedDraftRelation(s)&&!(a&&n?.id===t.id)||!n?{relationGenerated:!0}:{}},id:n?.id??draftEntityIdFor(`relation-attribute`,`${_}:${r}:${o.name}`),...n?{}:{order:e.attributes.filter(e=>e.objectId===r).length}};x.set(`${r}.${o.name}`,toDraftableAttribute(c,r))}}let S=e.attributes.map(e=>{let t=`${e.objectId}.${e.name}`,n=x.get(t);return x.delete(t),n??e});return S.push(...x.values()),{...e,attributes:S,views:e.views.map(e=>{let t=[u,d].find(t=>t.name===e.object);return e.derived&&t?regenerateDerived(e,t,S):e})}}function preserveDeclarationHints(e,t){if(e.type!==`relation`||!e.bilateral||t?.type!==`relation`||!t.bilateral)return e;let{label:n,cardinality:r,...i}=e.bilateral;return{...e,bilateral:{...i,...t.bilateral.label===void 0?{}:{label:n},...t.bilateral.cardinality===void 0?{}:{cardinality:r}}}}function requireObject(e,t){let r=e.objects.find(e=>e.id===t);if(!r)throw new n.ValidationError(`Object "${t}" is not in the draftable state`,[]);return r}function withDerivedViews(e,t,n){return{...e,attributes:[...n],views:e.views.map(e=>e.derived&&e.object===t.name?regenerateDerived(e,t,n):e)}}function objectFocus(e){return{objectId:e.objectId}}function recordFocus(e){return{objectId:e.objectId,recordId:e.recordId}}function attributeFocus(e){return{objectId:e.objectId,attributeName:e.name}}function existingAttributeFocus(e){return{objectId:e.objectId,attributeName:e.attribute}}function firstChangedProperty(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}function handShapedUse(e,t){if(!e.derived){for(let n of e.contents)if(n.type===`collection`&&(n.columns?.includes(t)||n.displayAttributes?.includes(t)||n.sorts?.some(e=>e.attribute===t))||n.type===`form`&&n.groups.some(e=>e.fields.some(e=>e.attribute===t))||n.type===`richtext`&&(n.attribute===t||n.titleAttribute===t))return`content "${n.name}"`}}function assertRollupShape(e,t,r){let i=r.config??{},a=r.name;if(i.relationPath!==void 0)throw new n.ValidationError(`rollup "${a}": relationPath is not supported yet`,[]);let o=i.relationAttribute;if(typeof o!=`string`||o.length===0)throw new n.ValidationError(`rollup "${a}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let s=e.attributes.find(e=>e.objectId===t.id&&e.name===o&&e.attributeType===`relation`);if(!s)throw new n.ValidationError(`rollup "${a}" needs a relation attribute; "${o}" is not a relation of object "${t.name}"`,[]);let c=relationTargetObjectName(s);if(c===void 0){let e=relationTargets(s).filter(e=>e.object!==`*`).length;throw new n.ValidationError(`rollup "${a}" needs a relation with one target object; "${o}" targets ${e}`,[])}if(i.function===`count`)return;let l=e.objects.find(e=>e.name===c),u=i.targetAttribute;if(!(l!==void 0&&e.attributes.some(e=>e.objectId===l.id&&e.name===u)))throw new n.ValidationError(`rollup "${a}" targets attribute "${u}", which object "${c}" does not have`,[])}function traversesRelation(e,t){let n=e.config??{};if(e.attributeType===`rollup`)return n.relationAttribute===t;let r=typeof n.expression==`string`?n.expression:``;return RegExp(`(^|[^A-Za-z0-9_])${t}\\.`).test(r)}function assertConfigFolds(e,t){let r=requireObject(e,t.objectId);if(t.attributeType===`relation`){for(let r of relationTargets(t))if(r.object!==`*`&&!e.objects.some(e=>e.name===r.object))throw new n.ValidationError(`object "${r.object}" is unknown; create it first`,[]);let r=bilateralDeclarationOf(t)?.object;if(r!==void 0&&r!==`*`&&!e.objects.some(e=>e.name===r))throw new n.ValidationError(`object "${r}" is unknown; create it first`,[]);for(let n of e.attributes)n.objectId===t.objectId&&isComputedAttribute(n)&&traversesRelation(n,t.name)&&computedPlanOf(e,n)}else if(isComputedAttribute(t))t.attributeType===`rollup`&&assertRollupShape(e,r,t),computedPlanOf(e,t);else return;assertAcyclicComputed(compilablePlansOf(e,t.objectId))}const K={...Mn,objectId:f.z.string().uuid().describe(`The object this operation acts on`)},ir=defineOperation({type:`add_object`,summary:`Creates an object: kebab-case plural name, icon from search_icons; folds in default_list/default_detail; reserved names are native objects.`,schema:f.z.object({...K,objectId:f.z.string().uuid().describe(`Stable id for the new object; the server mints one when omitted`),type:f.z.literal(`add_object`),name:e.w.describe("kebab-case plural API name (`purchase-orders`)"),label:f.z.string().min(1).describe(`Label people see`),icon:f.z.string().min(1).optional().describe(`Icon name`)}),apply:(e,t)=>{if(e.objects.some(e=>e.name===t.name))throw new n.ValidationError(`Object "${t.name}" already exists`,[]);if(e.objects.some(e=>e.id===t.objectId))throw new n.ValidationError(`Object id "${t.objectId}" is already taken`,[]);let r={id:t.objectId,name:t.name,label:t.label,...t.icon===void 0?{}:{icon:t.icon}};return{...e,objects:[...e.objects,r],views:[...e.views,...defaultViewsFor(r,e.attributes)]}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Crée l'objet « ${e.label} »`}),ar=f.z.object({...K,type:f.z.literal(`update_object`),changes:f.z.object({label:f.z.string().min(1).optional().describe(`New label`),icon:f.z.string().min(1).optional().describe(`New icon name from search_icons`),pluralLabel:f.z.string().optional().describe(`New label for many records; "" clears it`),description:f.z.string().optional().describe(`What this object holds`),labelExpression:D.optional().describe(`Titles every record; syntax in <expressions>`),embeddingExpression:f.z.literal(``).or(D).optional().describe(`Expression vector search indexes — <expressions> block; "" clears it`)}).refine(e=>Object.keys(e).length>0,`update_object needs at least one change`).describe(`≥1 change`)}),updateObjectFocus=e=>({objectId:e.objectId}),or=defineOperation({type:`update_object`,summary:`Updates an object's settings: label, icon, pluralLabel, description, labelExpression, embeddingExpression.`,schema:ar,apply:(e,t)=>(requireObject(e,t.objectId),{...e,objects:e.objects.map(e=>e.id===t.objectId?{...e,...t.changes}:e)}),focus:updateObjectFocus,presentation:definePresentation(updateObjectFocus,`atomic`,firstChangedProperty),describe:e=>describeObjectChanges(e.changes)}),sr={label:e=>`Renomme l'objet en « ${e} »`,icon:e=>`Change l'icône de l'objet en « ${e} »`,pluralLabel:e=>`Change le libellé au pluriel en « ${e} »`,description:e=>`Change la description de l'objet en « ${e} »`,labelExpression:e=>`Change l'expression du libellé de record en « ${e} »`,embeddingExpression:e=>e===``?`Efface l'expression d'indexation de l'objet`:`Change l'expression d'indexation en « ${e} »`};function describeObjectChanges(e){let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>sr[e]?.(String(t))).filter(e=>e!==void 0);return t.length>0?t.join(` · `):`Modifie l'objet`}const cr=defineOperation({type:`remove_object`,summary:`Removes an object; refused while a relation attribute targets it — remove it first.`,schema:f.z.object({...K,type:f.z.literal(`remove_object`)}),apply:(e,t)=>{requireObject(e,t.objectId);let r=e.objects.find(e=>e.id===t.objectId)?.name;for(let i of e.attributes){if(i.objectId===t.objectId||i.attributeType!==`relation`||!relationTargets(i).some(e=>e.object===r))continue;let a=e.objects.find(e=>e.id===i.objectId);throw new n.ValidationError(`object "${r}" is targeted by attribute "${a?.name}.${i.name}"; remove that attribute first`,[])}return{...e,objects:e.objects.filter(e=>e.id!==t.objectId),attributes:e.attributes.filter(e=>e.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(e=>e.objectId!==t.objectId),views:e.views.filter(e=>e.object!==r)}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Supprime l'objet ${e.objectId}`}),q=w;function assertConfigParses(t,r){try{e.c(t,r)}catch(e){throw e instanceof n.ValidationError?new n.ValidationError(e.message,e.errors.map(e=>({...e,path:[`config`,...e.path??[]]}))):e}}const lr=f.z.object({...K,type:f.z.literal(`add_attribute`),attributeId:f.z.string().min(1),name:e.C,label:f.z.string().min(1),attributeType:f.z.enum(q),config:f.z.record(f.z.string(),f.z.unknown()).optional()}).superRefine((e,t)=>{try{assertConfigParses(e.attributeType,e.config??{})}catch(e){if(e instanceof n.ValidationError){for(let n of e.errors)t.addIssue({code:`custom`,message:n.message,path:[...n.path]});return}throw e}}),ur={...Mn,type:f.z.literal(`add_attribute`),attributeId:f.z.string().min(1).describe(`Stable attribute id`),name:e.C.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),label:f.z.string().min(1).describe(`Label people see`)},dr=Object.fromEntries(e.n.map(e=>[e,!0])),J=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],fr=f.z.object(J.reduce((t,n)=>(Object.assign(t,e.a(n).omit(dr).shape),t),{})).strict(),pr=q.filter(e=>!J.includes(e)),mr=Object.fromEntries(J.map(t=>[t,new Set(Object.keys(e.a(t).omit(dr).shape))])),hr=e.m(mr,`config key`);function refuseForeignSimpleConfigKeys(e,t){hr(e.attributeType,e.config,t,[`config`])}function wireConfigFor(t){let n=e.a(t).omit(dr);return(t===`relation`||t===`document`?n.extend({properties:e.p.optional()}):n).strict()}const gr=defineOperation({type:`add_attribute`,summary:`Adds an attribute; relation/bilateral/rollup targets must pre-exist; no relationPath; formula needs returnType; cover new required attrs.`,schema:lr,wire:f.z.discriminatedUnion(`attributeType`,[f.z.object({...ur,objectId:f.z.string().uuid(),attributeType:f.z.enum(J).describe(`Attribute type`),config:fr.optional().describe(`Configuration of a simple attribute (text, number, date…)`)}).strict().superRefine(refuseForeignSimpleConfigKeys),...pr.map(e=>f.z.object({...ur,objectId:f.z.string().uuid(),attributeType:f.z.literal(e).describe(`Attribute type`),config:wireConfigFor(e).optional().describe(`Configuration of a ${e} attribute`)}).strict())]),apply:(e,t)=>{let r=requireObject(e,t.objectId),i=e.attributes.find(e=>e.objectId===t.objectId&&e.name===t.name);if(i&&!isGeneratedDraftRelation(i))throw new n.ValidationError(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let a={id:i?.id??t.attributeId,objectId:t.objectId,name:t.name,label:t.label,attributeType:t.attributeType,...t.config===void 0?{}:{config:t.config}};for(let n of e.sampleRecords)n.objectId===t.objectId&&assertRequiredCovered(n.id,a,n.values);let o=withDerivedViews(e,r,i?e.attributes.map(e=>e===i?a:e):[...e.attributes,a]);return assertConfigFolds(o,a),reconcileDraftRelationAttribute(o,a,t.id,i,!0)},focus:attributeFocus,presentation:definePresentation(attributeFocus,`local`),describe:e=>`Ajoute l'attribut « ${e.label} »`}),_r={...K,attribute:e.C.describe(`The attribute's API name on this object`)};function requireAttribute(e,t,r,i){let a=requireObject(e,t);if(r===void 0)throw new n.ValidationError(`${i} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let o=e.attributes.find(e=>e.objectId===t&&e.name===r);if(!o)throw new n.ValidationError(`Attribute "${r}" is not on object "${t}"`,[]);return{object:a,attribute:o}}const vr=defineOperation({type:`update_attribute`,summary:`Updates an attribute's label, or replaces its whole config; a published config can't change — add a new attribute and migrate values.`,schema:f.z.object({..._r,type:f.z.literal(`update_attribute`),changes:f.z.object({label:f.z.string().min(1).optional().describe(`New label`),config:f.z.record(f.z.string(),f.z.unknown()).optional().describe(`Whole config, replaced — same shape as add_attribute`)}).refine(e=>Object.keys(e).length>0,`update_attribute needs at least one change`).describe(`≥1 change`)}),apply:(e,t)=>{let{object:n,attribute:r}=requireAttribute(e,t.objectId,t.attribute,`update_attribute`);t.changes.config!==void 0&&assertConfigParses(r.attributeType,t.changes.config);let i={...r,...t.changes},a=withDerivedViews(e,n,e.attributes.map(e=>e===r?i:e));return assertConfigFolds(a,i),reconcileDraftRelationAttribute(a,i,t.id,r)},focus:existingAttributeFocus,presentation:definePresentation(existingAttributeFocus,`atomic`),describe:e=>e.changes.label?`Renomme l'attribut « ${e.attribute} » en « ${e.changes.label} »`:`Modifie l'attribut « ${e.attribute} »`}),yr=defineOperation({type:`remove_attribute`,summary:`Removes an attribute; refused while a sample carries its value, a content names it, or a formula/rollup depends on it — remove those first.`,schema:f.z.object({..._r,type:f.z.literal(`remove_attribute`)}),apply:(e,t)=>{let{attribute:r}=requireAttribute(e,t.objectId,t.attribute,`remove_attribute`),i=pairedDraftAttributes(e,r);for(let t of i){let r=requireObject(e,t.objectId),[i]=dependentsOf(e,t.objectId,t.name);if(i!==void 0)throw new n.ValidationError(`attribute "${t.name}" is used by "${i}"; remove that first`,[]);for(let i of e.views){if(i.object!==r.name)continue;let e=handShapedUse(i,t.name);if(e!==void 0)throw new n.ValidationError(`attribute "${t.name}" is used by view "${i.id}" (${e}); remove it from the view first`,[])}let a=e.sampleRecords.find(e=>e.objectId===t.objectId&&t.name in e.values);if(a)throw new n.ValidationError(`Attribute "${t.name}" is still used by sample record "${a.id}"`,[])}let a=e.attributes.filter(e=>!i.includes(e)),o={...e,views:e.views.map(e=>e)};return i.reduce((t,n)=>withDerivedViews(t,requireObject(e,n.objectId),a),o)},focus:existingAttributeFocus,presentation:definePresentation(existingAttributeFocus,`local`),describe:e=>`Supprime l'attribut « ${e.attribute} »`});function assertSampleValue(e,t,r,a){let o=toAttribute(r);try{i.d(o)}catch{return}let s=i.i(o,a);if(s.success)return;let c=s.errors??[],l=c.map(e=>e.path.length>1?`${e.path.join(`.`)}: ${e.message}`:e.message).join(`, `);throw new n.ValidationError(`Sample record "${e}" has an invalid value for "${t}": ${l}`,c.map(e=>({path:e.path,message:e.message})))}function assertRequiredCovered(e,t,r){if(t.config?.required===!0&&t.config?.defaultValue===void 0&&!(t.name in r&&r[t.name]!==void 0))throw new n.ValidationError(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}function relationValueIds(e){return(Array.isArray(e)?e:[e]).flatMap(e=>{if(typeof e==`string`)return[e];if(typeof e==`object`&&e){let t=e.id;if(typeof t==`string`)return[t]}return[]})}function assertUnknownSampleReference(e,t,n,r){n.attributeType===`relation`&&r!=null&&assertSampleTarget(e,t,relationTargetObjectName(n),r)}function assertSampleTarget(e,t,r,i){let a=e.objects.find(e=>e.name===r);if(!a)return;let o=e.views.some(e=>e.id===defaultViewIdsFor(a.id).list);for(let r of relationValueIds(i)){let i=e.sampleRecords.find(e=>e.id===r);if(i?.objectId!==a.id&&(i!==void 0||o))throw new n.ValidationError(`sample record "${t}" references unknown sample "${r}"`,[])}}const br=defineOperation({type:`add_sample_record`,summary:`Adds a sample record; keys are attribute names, required covered, computed never set; relation value is a minted/published recordId; publication is preview or requested-data.`,schema:f.z.object({...K,type:f.z.literal(`add_sample_record`),recordId:f.z.string().uuid().describe(`Minted by the server when omitted`),values:f.z.record(f.z.string(),f.z.unknown()).describe("Attribute name → value; currency is `{code,value}`, relation is a record id or name minted here"),publication:f.z.enum([`preview`,`requested-data`]).optional().describe(`preview = display-only; requested-data = real records asked for`)}),apply:(e,t)=>{if(requireObject(e,t.objectId),e.sampleRecords.some(e=>e.id===t.recordId))throw new n.ValidationError(`Sample record "${t.recordId}" already exists`,[]);let r=new Map(e.attributes.filter(e=>e.objectId===t.objectId).map(e=>[e.name,e]));for(let[i,a]of Object.entries(t.values)){let o=r.get(i);if(!o)throw new n.ValidationError(`Sample record "${t.recordId}" uses unknown attribute "${i}"`,[]);if(isComputedAttribute(o))throw new n.ValidationError(`attribute "${o.name}" is computed and cannot be set on a sample record`,[]);assertUnknownSampleReference(e,t.recordId,o,a),assertSampleValue(t.recordId,i,o,a)}for(let e of r.values())assertRequiredCovered(t.recordId,e,t.values);return{...e,sampleRecords:[...e.sampleRecords,{id:t.recordId,objectId:t.objectId,values:t.values,...t.publication===void 0?{}:{publication:t.publication}}]}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Ajoute un exemple`});function relationNamesOf(e,t){return new Set([...e.attributes.filter(e=>e.objectId===t&&e.attributeType===`relation`).map(e=>e.name)])}function assertSampleNotReferenced(e,t){for(let r of e.sampleRecords){if(r.id===t)continue;let i=relationNamesOf(e,r.objectId);for(let[e,a]of Object.entries(r.values))if(i.has(e)&&relationValueIds(a).includes(t))throw new n.ValidationError(`sample record "${t}" is referenced by sample record "${r.id}"; remove that first`,[])}}const Y=[ir,or,cr,gr,vr,yr,br,defineOperation({type:`remove_sample_record`,summary:`Removes a sample record; refused while another sample still references it.`,schema:f.z.object({...K,type:f.z.literal(`remove_sample_record`),recordId:f.z.string().min(1).describe(`recordId of the sample to remove`)}),apply:(e,t)=>{if(!e.sampleRecords.some(e=>e.id===t.recordId&&e.objectId===t.objectId))throw new n.ValidationError(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,[]);return assertSampleNotReferenced(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(e=>e.id!==t.recordId)}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Retire un exemple`})];function build(){let e=new Map;for(let t of[...Y,...G]){if(e.has(t.type))throw new n.DuplicateError(`architect operation`,t.type);e.set(t.type,t)}return e}const X=build(),xr=[...X.keys()];function defOf(e){let t=X.get(e.type);if(!t)throw new n.ValidationError(`Operation "${e.id}" has unknown type "${e.type}"`,[]);return t}function applyOperations(e,t,n={extensions:[]}){return t.reduce((e,t)=>defOf(t).apply(e,t,n),e)}function focusOf(e){return defOf(e).focus(e)}function describeOperations(e,t){return e.map(e=>defOf(e).describe(e,t))}function parseOperation(e){if(typeof e!=`object`||!e||!(`type`in e))throw new n.ValidationError(`An operation must be an object carrying a type`,[]);let t=e.type;if(typeof t!=`string`)throw new n.ValidationError(`An operation's type must be a string`,[]);let r=X.get(t);if(!r)throw new n.ValidationError(`Unknown operation type "${t}"`,[]);let i=r.schema.safeParse(e);if(!i.success)throw new n.ValidationError(`Operation "${t}" is invalid: ${i.error.issues.map(e=>`${e.path.join(`.`)} ${e.message}`).join(`; `)}`,[]);return i.data}const pair=e=>f.z.tuple([f.z.literal(e),f.z.string()]),Sr=f.z.union([f.z.tuple([f.z.literal(`content`),f.z.string(),f.z.string(),f.z.string()]),f.z.tuple([f.z.literal(`view`),f.z.string(),f.z.string()]),f.z.tuple([f.z.literal(`attribute`),f.z.string(),f.z.string()]),f.z.tuple([f.z.literal(`sample`),f.z.string(),f.z.string()]),pair(`object`),pair(`object-name`),pair(`object-schema`),pair(`object-tree`),pair(`attribute-id`)]);function proposalTargetKey(e){return e.viewName&&e.objectName?JSON.stringify(e.contentName?[`content`,e.objectName,e.viewName,e.contentName]:[`view`,e.objectName,e.viewName]):e.attributeName&&e.objectId?JSON.stringify([`attribute`,e.objectId,e.attributeName]):e.attributeId?JSON.stringify([`attribute-id`,e.attributeId]):e.recordId&&e.objectId?JSON.stringify([`sample`,e.objectId,e.recordId]):e.objectId?JSON.stringify([`object`,e.objectId]):e.objectName?JSON.stringify([`object-name`,e.objectName]):null}function addContentDependencies(e,t,n,r){if(n&&typeof n==`object`){if(`source`in n&&n.source&&typeof n.source==`object`){let i=collectionSourceAddressOf(n.source);if(i&&i.kind!==`related`&&r(i.object),i?.kind===`related`){let n=i.relation;r(t);let a=e.objects.find(e=>e.name===t),o=e.attributes.find(e=>e.objectId===a?.id&&e.name===n);if(o?.attributeType===`relation`&&Array.isArray(o.config?.targets))for(let e of o.config.targets)e&&typeof e.object==`string`&&e.object!==`*`&&r(e.object)}}else`type`in n&&n.type===`forms`?r(`objectName`in n&&typeof n.objectName==`string`?n.objectName:t):`type`in n&&[`form`,`richtext`,`emails`,`meetings`,`documents`].includes(String(n.type))&&r(t)}}function addBilateralDependencies(e,t,n,r,i){if([`add_attribute`,`update_attribute`,`remove_attribute`].includes(t.type)){let a=e.attributes.find(e=>e.objectId===n.objectId&&e.name===n.attributeName),o=r&&typeof r==`object`&&`bilateral`in r?r.bilateral:a?.config?.bilateral;if((t.attributeType===`relation`||a?.attributeType===`relation`)&&o&&typeof o==`object`&&`object`in o&&typeof o.object==`string`){n.objectId&&i(`object-tree`,n.objectId);let t=e.objects.find(e=>e.name===o.object);t?i(`object-tree`,t.id):i(`object-name`,o.object)}}}function requiredTargetKeys(e,t){let n=new Set,add=(...e)=>n.add(JSON.stringify(e)),schemaFor=t=>{let n=e.objects.find(e=>e.name===t);n?add(`object-schema`,n.id):add(`object-name`,t)};for(let r of t){let t=focusOf(r);if(r.type===`rename_view`||r.type===`rename_view_content`){let e=tr.parse(r),t=proposalTargetKey({objectName:e.objectName,viewName:e.viewName,...e.type===`rename_view_content`?{contentName:e.contentName}:{}});t&&n.add(t)}let i=proposalTargetKey(t);if(i&&n.add(i),t.viewName&&t.objectName){r.type!==`replace_view_content`&&add(`view`,t.objectName,t.viewName);let n=e.objects.find(e=>e.name===t.objectName);if(n?add(`object`,n.id):add(`object-name`,t.objectName),addContentDependencies(e,t.objectName,r.definition??r.content,schemaFor),r.type===`reset_view_content`&&typeof r.contentName==`string`){let n=e.views.find(e=>e.object===r.objectName&&e.name===r.viewName);addContentDependencies(e,t.objectName,n?.authoring.contents[r.contentName]?.sourceDefinition,schemaFor)}}t.objectId&&add(`object`,t.objectId),t.objectId&&(r.type===`remove_object`||r.type.includes(`sample_record`))&&add(`object-tree`,t.objectId),r.type===`add_object`&&typeof r.name==`string`&&add(`object-name`,r.name);let a=r.changes&&typeof r.changes==`object`?r.changes:null,o=r.type===`add_attribute`?r.config:a&&`config`in a?a.config:null;if(addBilateralDependencies(e,r,t,o,add),o&&typeof o==`object`&&`targets`in o&&Array.isArray(o.targets))for(let e of o.targets)e&&typeof e.object==`string`&&e.object!==`*`&&add(`object-name`,e.object)}return[...n]}function targetTokenOf(e){return`v2:${r.s(e)}`}const Cr=targetTokenOf(null);function isCurrentTargetToken(e){return e?.startsWith(`v2:`)??!1}function targetTokensFor(e,t){return Object.fromEntries(t.map(t=>[t,targetTokenOf(targetSnapshot(e,t))]))}function targetSnapshot(e,t){let r;try{r=JSON.parse(t)}catch{throw new n.ValidationError(`Invalid proposal target key "${t}"`,[])}let i=Sr.safeParse(r);if(!i.success)throw new n.ValidationError(`Invalid proposal target key "${t}"`,[]);let[a,o,s,c]=i.data,l=e.objects.find(e=>e.id===o);if(a===`object`)return l??null;if(a===`object-name`)return e.objects.find(e=>e.name===o)??null;if(a===`attribute-id`)return e.attributes.find(e=>e.id===o)??null;if(a===`attribute`)return e.attributes.find(e=>e.objectId===o&&e.name===s)??null;if(a===`sample`)return e.sampleRecords.find(e=>e.objectId===o&&e.id===s)??null;if(a===`object-schema`||a===`object-tree`){if(!l)return null;let t=e.attributes.filter(e=>e.objectId===o);return a===`object-schema`?{object:l,attributes:t.toSorted((e,t)=>e.name.localeCompare(t.name))}:{object:l,attributes:t,views:e.views.filter(e=>e.object===l.name),sampleRecords:e.sampleRecords.filter(e=>e.objectId===o)}}let u=e.views.find(e=>e.object===o&&e.name===s);if(!u)return null;if(a===`view`)return{id:u.id,revision:u.revision,definition:{...draftedViewDefinition(u),contents:u.contents.map(({name:e,placement:t})=>({name:e,placement:t}))}};let d=u.contents.find(e=>e.name===c);return c!==void 0&&Object.hasOwn(u.contentIds,c)?{id:u.contentIds[c],revision:u.contentRevisions[c],definition:d??null}:null}function presentationOf(e){return defOf(e).presentation(e)}function episodeImpactOf(e){let t=e.map(presentationOf);return new Set(t.map(({focus:e})=>e.viewName?JSON.stringify([e.objectName,e.viewName]):e.objectId).filter(e=>e!==void 0)).size>1||t.some(({impact:e})=>e===`structural`)?`structural`:t.some(({impact:e})=>e===`local`)?`local`:`atomic`}function snapshotArchitectTarget(e,t){let n=proposalTargetKey(t);return n===null?null:targetSnapshot(e,n)}function deriveArchitectChanges(e,t,n={extensions:[]}){let r=e;return t.map(e=>{let t=presentationOf(e),i=snapshotArchitectTarget(r,t.focus);r=applyOperations(r,[e],n);let a=snapshotArchitectTarget(r,t.focus);return{operationId:e.id,operationType:e.type,presentation:t,before:i,after:a,...e.note===void 0?{}:{note:e.note}}})}function part(e){return e.replace(/[%:/.]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function architectFocusKey(e){let t=headOf(e);if(t===null)return null;let n=e.propertyPath??[];return n.length===0?t:`${t}/${n.map(part).join(`.`)}`}function headOf(e){return e.viewName&&e.objectName?e.contentName?[`content`,e.objectName,e.viewName,e.contentName].map(part).join(`:`):[`view`,e.objectName,e.viewName].map(part).join(`:`):e.attributeName&&e.objectId?[`attribute`,e.objectId,e.attributeName].map(part).join(`:`):e.attributeId?[`attribute-id`,e.attributeId].map(part).join(`:`):e.recordId&&e.objectId?[`sample`,e.objectId,e.recordId].map(part).join(`:`):e.objectId?[`object`,e.objectId].map(part).join(`:`):e.objectName?[`object-name`,e.objectName].map(part).join(`:`):null}const Z=f.z.string().min(1),wr=f.z.union([f.z.object({objectName:Z,viewName:Z,contentName:Z.optional()}).strict().describe(`Full configuration of a view, or of one content when contentName is given`),f.z.object({objectId:Z}).strict().describe(`An object with its attributes, by id`),f.z.object({objectName:Z}).strict().describe(`An object with its attributes`),f.z.object({objectId:Z,attributeName:Z}).strict().describe(`One attribute's config, by name`),f.z.object({objectId:Z,attributeId:Z}).strict().describe(`One attribute's config, by id`),f.z.object({objectId:Z,recordId:Z}).strict().describe(`One sample record`)]);function parseNamedTarget(e){let t=wr.safeParse(e);if(!t.success)throw new n.ValidationError(`Invalid scoped target`,[{path:[`target`],message:`Expected exactly one named target branch`}]);return t.data}const Q=f.z.object({type:f.z.literal(`remove_operation`),operationId:f.z.string().min(1).describe(`The id of a stored operation to drop from the draft`)});function membersOf(e,t=[]){return[...e.map(e=>e.schema),...t].map(relaxUuidKeys)}function describeMember(e,t){return mapMember(e,e=>e.describe(t))}function wireMembersOf(e,t=[]){return[...e.map(e=>e.wire??e.schema),...t].map(relaxUuidKeys).map(relaxMintedKeys).map(addressByName).map((t,n)=>{let r=e[n];return r===void 0?t:describeMember(t,r.summary)})}function unionOf(e){return f.z.discriminatedUnion(`type`,e)}function isUuidString(e){return e instanceof f.z.ZodString&&e.format===`uuid`}function asUnionMember(e){let t=e;return!Array.isArray(t.options)||typeof t.def?.discriminator!=`string`?null:{discriminator:t.def.discriminator,options:t.options}}function mapMember(e,t){let n=asUnionMember(e);return n===null?t(e):f.z.discriminatedUnion(n.discriminator,n.options.map(t))}function relaxUuidKeys(e){return mapMember(e,e=>{let t={};for(let[n,r]of Object.entries(e.shape)){if(!isUuidString(r))continue;let e=f.z.string().min(1);t[n]=r.description===void 0?e:e.describe(r.description)}return Object.keys(t).length===0?e:e.safeExtend(t)})}const Tr={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of Tr[e.shape.type.value]??[]){let r=e.shape[n];r instanceof f.z.ZodString&&(t[n]=r.optional())}return Object.keys(t).length===0?e:e.safeExtend(t)})}function withOriginalChecks(e,t){let n=e._zod.def.checks;return!n||n.length===0?t:t.check(...n)}function addressByName(e){return mapMember(e,e=>{if(e.shape.type.value===`add_object`||!(`objectId`in e.shape))return e;let{objectId:t,...n}=e.shape;return withOriginalChecks(e,f.z.object({...n,objectName:f.z.string().min(1).describe(`Object`)}).strict())})}const Er=membersOf(Y,[Q]),Dr=membersOf(G),Or=unionOf(Er),kr=unionOf(Dr),Ar={schema:Or,view:kr},jr={schema:unionOf(wireMembersOf(Y,[Q])),view:unionOf(wireMembersOf(G))},Mr=new Map([...Y.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...G.map(e=>[e.type,`view`])]);function familyOf(e){return Mr.get(e)??null}function viewsOf(e,t,n){return e.views.filter(e=>e.object===t.name&&e.context===n)}function collectionContentsOf(e,t){return viewsOf(e,t,`collection`).flatMap(e=>e.contents).filter(e=>e.type===`collection`)}function ownAttributes(e,t){return e.attributes.filter(e=>e.objectId===t.id)}function isTableCell(e){return t.B(toAttribute(e)).presentation.tableCell}function hasRecordContent(e,t,n){return viewsOf(e,t,`record`).some(e=>e.contents.some(e=>e.type===n))}function isEdgePayload(e,t){return e===2&&t<=5}function looksLikeEdge(e,t){let n=ownAttributes(e,t);return isEdgePayload(n.filter(e=>e.attributeType===`relation`).length,n.length)?!e.attributes.some(e=>e.attributeType===`relation`&&e.objectId!==t.id&&relationTargets(e).some(e=>e.object===t.name)):!1}function reciprocalExists(e,t,n){return viewsOf(e,n,`record`).some(e=>e.contents.some(e=>e.type===`collection`&&e.source.relation===t.name))}function stillMissing(e,t){let n=[],r=t?e.objects.filter(e=>t.has(e.id)):e.objects;for(let t of r){if(looksLikeEdge(e,t)){n.push(`Object "${t.label}" is an edge (two relations plus scalars): qualify a relation with config.properties.definitions instead of an object.`);continue}let r=collectionContentsOf(e,t);r.length===0&&n.push(`Object "${t.label}" has no collection content: add_view_content.`);for(let i of ownAttributes(e,t))if(isTableCell(i)&&r.length&&!r.some(e=>e.columns===void 0||e.columns.includes(i.name))&&n.push(`Attribute "${i.label}" on "${t.label}" is in no collection column set: replace_view_content.`),i.attributeType===`document`&&!hasRecordContent(e,t,`documents`)&&n.push(`Object "${t.label}" has no documents content: add_view_content.`),i.attributeType===`relation`)for(let{object:r}of relationTargets(i)){let a=e.objects.find(e=>e.name===r);a&&!reciprocalExists(e,i,a)&&n.push(`Relation "${i.label}" on "${t.label}" has no reciprocal collection on "${a.label}": add_view_content with source.relation.`)}viewsOf(e,t,`record`).length&&!hasRecordContent(e,t,`activity`)&&n.push(`Object "${t.label}" has no activity content on its record view: add_view_content.`),r.length===1&&n.push(`Object "${t.label}" has a single collection content; a person would add one to three that answer a question: add_view_content.`)}return n}function addedAttributes(e,t){let n=new Set(t.flatMap(e=>e.type===`add_attribute`&&typeof e.attributeId==`string`?[e.attributeId]:[]));return e.attributes.filter(e=>n.has(e.id))}function guidanceForBatch(e,t){let n={next:[],needsColumns:[],regenerated:[]},r=new Set;for(let i of addedAttributes(e,t)){let t=e.objects.find(e=>e.id===i.objectId);if(!t)continue;let a=e.views.filter(e=>e.object===t.name);if(!r.has(t.id)){r.add(t.id);for(let e of a.filter(e=>e.derived))for(let t of e.contents)n.regenerated.push(`${e.name}.${t.name}`)}for(let e of a.filter(e=>!e.derived&&e.context===`collection`))for(let t of e.contents)t.type===`collection`&&t.columns!==void 0&&!t.columns.includes(i.name)&&n.needsColumns.push({view:e.name,content:t.name,attribute:i.name});let o=a.some(e=>e.context===`record`&&e.contents.some(e=>e.type===`documents`)),s=a.find(e=>e.context===`record`);i.attributeType===`document`&&s&&!o&&n.next.push({type:`add_view_content`,objectName:t.name,viewName:s.name,content:{name:`documents`,type:`documents`,placement:`main`,label:`Documents`},target:{end:!0}})}return n}function touchedObjectIds(e,t){let n=new Map(e.objects.map(e=>[e.name,e.id])),r=new Set;for(let e of t){let{focus:t}=presentationOf(e),i=t.objectId??(t.objectName?n.get(t.objectName):void 0);i!==void 0&&r.add(i)}return r}function attributeDetail(e){let t=e.config??{};if(e.attributeType===`relation`)return`→ ${relationTargets(e).map(e=>e.object).join(`|`)}`;if(e.attributeType===`formula`)return typeof t.expression==`string`?t.expression:void 0;if(e.attributeType===`rollup`)return t.function===`count`?`count(${t.relationAttribute})`:`${t.function}(${t.relationAttribute}.${t.targetAttribute})`}function propertyLines(e){let t=resolvePropertyDefinitions({properties:e.config?.properties});if(t.length!==0)return t.map(e=>`${e.name}: ${e.type}`)}function summarizeAttribute(e){let t=e.config?.options,n=attributeDetail(e),r=propertyLines(e);return{name:e.name,label:e.label,type:e.attributeType,...Array.isArray(t)?{options:t.map(e=>e.value)}:{},...n===void 0?{}:{detail:n},...r===void 0?{}:{properties:r}}}function summarizeObject(e,t,n){let r=defaultViewIdsFor(e.id),i=n.some(e=>e.id===r.list);return{id:e.id,name:e.name,label:e.label,attributes:t.filter(t=>t.objectId===e.id).map(summarizeAttribute),...i?{viewIds:r}:{}}}function summarizeView(e,t){if(!t.some(t=>t.name===e.object))throw new n.ValidationError(`View "${e.name}" names an object outside the draft scope`,[]);return{id:e.id,name:e.name,context:e.context,objectName:e.object,label:e.label,derived:e.derived===!0,contents:e.contents.map(({name:e,type:t,placement:n,label:r})=>({name:e,type:t,placement:n,label:r}))}}function summarizeDraft(e,t){let n=new Map;for(let t of e.sampleRecords)n.set(t.objectId,(n.get(t.objectId)??0)+1);return{objects:e.objects.map(t=>summarizeObject(t,e.attributes,e.views)),views:e.views.map(t=>summarizeView(t,e.objects)),sampleRecords:[...n.entries()].map(([e,t])=>({objectId:e,count:t})),operationCount:t}}const Nr=[`draft_schema`],Pr=[{input:{operations:[{type:`add_attribute`,id:`op-statut`,objectName:`devis`,attributeId:`attr-statut`,name:`statut`,label:`Statut`,attributeType:`select`,config:{options:[{value:`draft`,label:`Brouillon`,color:`gray`},{value:`sent`,label:`Envoyé`,color:`blue`},{value:`accepted`,label:`Accepté`,color:`green`}]}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:`add_view_content`,id:`op-open`,objectName:`devis`,viewName:`default_list`,content:{name:`open`,label:`À traiter`,type:`collection`,placement:`main`,layout:`table`,source:{object:`devis`},columns:[`title`,`client`,`montant`,`statut`],filters:{combinator:`and`,rules:[{attribute:`statut`,operator:`is`,value:`sent`}]},sorts:[{attribute:`montant`,direction:`desc`}]},target:{end:!0}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:`replace_view_content`,id:`op-all`,objectName:`devis`,viewName:`default_list`,contentName:`all`,definition:{name:`all`,type:`collection`,placement:`main`,layout:`table`,source:{object:`devis`},columns:[`title`,`client`,`montant`,`statut`]}}],guard:{revision:null,targetTokens:{}}}}],$=f.z.string().refine(e=>e.trim().length>0,`Must not be blank`),Fr=f.z.union([f.z.tuple([f.z.literal(`object`),$]),f.z.tuple([f.z.literal(`attribute`),$,$]),f.z.tuple([f.z.literal(`view`),$,$]),f.z.tuple([f.z.literal(`content`),$,$,$])]),Ir=f.z.object({label:$,pluralLabel:f.z.string().optional(),description:f.z.string().optional(),icon:e.x.optional(),labelExpression:f.z.string(),embeddingExpression:f.z.string().optional(),sealed:f.z.boolean().optional(),toleratedAttributes:f.z.array($).optional(),metadata:f.z.record(f.z.string(),f.z.unknown()).optional(),schema_version:f.z.number().int().nonnegative(),migrations:f.z.array(f.z.record(f.z.string(),f.z.unknown())),documentLayout:f.z.record(f.z.string(),f.z.unknown()).optional()}).strict();function failure(e){throw new n.ValidationError(e,[])}function definitionSchema(n){return f.z.custom(r=>{let i=f.z.record(f.z.string(),f.z.unknown()).parse(r);for(let e of n[0]===`view`?[`object`,`name`]:[`name`])Object.hasOwn(i,e)&&failure(`Invalid schema state: unrecognized definition key ${e}`);switch(n[0]){case`object`:Ir.parse(i);break;case`attribute`:{let t=f.z.enum(w).parse(i.type);e.i(t).extend({type:f.z.literal(t),label:$,required:f.z.boolean().optional(),unique:f.z.boolean().optional(),icon:e.x.optional()}).strict().parse(i);break}case`view`:{let{contents:e,...r}=i,a=f.z.array($).parse(e);new Set(a).size!==a.length&&failure(`Invalid schema state: duplicate content membership`),t.s.parse({...r,object:n[1],name:n[2],contents:[]});break}case`content`:t.u.parse({...i,name:n[3]})}return!0})}function compareSchemaStateEntries(e,t){let n=JSON.stringify(e.address),r=JSON.stringify(t.address);return n<r?-1:+(n>r)}function schemaStateSourcePayload(e){return{modelVersion:1,hashVersion:1,entries:[...e].sort(compareSchemaStateEntries).filter(e=>e.source!==null).map(({address:e,source:t})=>({address:e,source:t}))}}function parseState(e){let t=f.z.record(f.z.string(),f.z.unknown()).parse(e);for(let[e,n]of[[`modelVersion`,`model`],[`hashVersion`,`hash`]])t[e]!==1&&failure(`Unsupported schema ${n} version: expected 1, received ${t[e]===void 0?`missing`:String(t[e])}`);let r=f.z.object({modelVersion:f.z.literal(1),hashVersion:f.z.literal(1),tenant:$,sourceFingerprint:f.z.string().regex(/^[a-f0-9]{64}$/),entries:f.z.array(f.z.unknown())}).strict().safeParse(e);if(!r.success){let e=r.error.issues.find(e=>e.code===`unrecognized_keys`);throw e?.code===`unrecognized_keys`&&failure(`Invalid schema state: unrecognized key ${e.keys[0]}`),n.ValidationError.fromZodErrors(r.error.issues.map(e=>({path:e.path.map(String),message:e.message})))}let i=new Set,a=r.data.entries.map(e=>{let t=Fr.parse(f.z.object({address:f.z.unknown()}).parse(e).address),n=JSON.stringify(t);i.has(n)&&failure(`Invalid schema state: duplicate address ${n}`),i.add(n);let r=definitionSchema(t).nullable(),a=t[0]===`object`||t[0]===`attribute`?f.z.object({id:f.z.string().uuid(),updatedAt:f.z.string().datetime()}).strict():f.z.object({id:f.z.string().uuid(),revision:f.z.number().int().nonnegative()}).strict(),o=f.z.object({address:Fr,source:r,effective:r,status:f.z.enum([`source`,`runtime`,`copy`,`suppressed`]),sourceOwner:f.z.union([f.z.literal(`core`),f.z.string().regex(/^(bundle|source):.+$/)]).nullable(),guard:a.nullable()}).strict().parse(e);(o.status===`runtime`&&(o.source!==null||o.effective===null||o.sourceOwner!==null)||o.status===`suppressed`&&(t[0]!==`content`||o.source===null||o.effective!==null||o.guard===null)||o.status===`copy`&&(o.source===null||o.effective===null)||o.effective!==null&&o.guard===null||o.source===null&&o.effective===null)&&failure(`Invalid schema state: inconsistent status at ${n}`);let s=o.sourceOwner;s!==null&&s!==`core`&&!s.startsWith(`bundle:`)&&!s.startsWith(`source:`)&&failure(`Invalid source owner`);let c=s===null||s===`core`?s:s.startsWith(`bundle:`)?`bundle:${s.slice(7)}`:`source:${s.slice(7)}`;return{...o,sourceOwner:c}});return{...r.data,entries:a.sort(compareSchemaStateEntries)}}function parseSchemaState(e){try{return parseState(e)}catch(e){throw e instanceof f.z.ZodError?n.ValidationError.fromZodErrors(e.issues.map(e=>({path:e.path.map(String),message:e.message}))):e}}function diffSchemaState(e){let t=[];for(let n of[...e.entries].sort(compareSchemaStateEntries)){let e=n.source===null?`added`:n.status===`suppressed`?`suppressed`:n.effective===null?`removed`:r.s(n.source)===r.s(n.effective)?n.status===`copy`?`copied`:null:`changed`;e&&t.push({...n,change:e})}return{modelVersion:1,tenant:e.tenant,sourceFingerprint:e.sourceFingerprint,changes:t}}exports.ABSENT_TARGET_TOKEN=Cr,exports.AGENT_UI_BATCH_MAX_BYTES=204800,exports.AGENT_UI_BATCH_MAX_ITEMS=256,exports.ALLOWED_PROPERTY_TYPES=ke,exports.ALL_ACTIONS=T,exports.ALL_OPERATION_TYPES=xr,exports.ALL_PIPES=E,exports.ALL_SYSTEM_RESOURCES=Re,exports.ARTIFACT_FILE_ROLES=ve,exports.ARTIFACT_KINDS=ge,exports.ARTIFACT_LIST_VIEW=pt,exports.ARTIFACT_OBJECT=dt,exports.ARTIFACT_OBJECT_NAME=P,exports.ARTIFACT_PREVIEW_EXTENSION=ut,exports.ARTIFACT_RETENTIONS=_e,exports.ARTIFACT_VIEW=ft,exports.ATTRIBUTE_FILTER_OPERATORS=t.R,exports.ATTRIBUTE_TYPES=w,exports.AUDIT_ACTIONS=ne,exports.AUDIT_RESOURCE_TYPES=te,exports.AccessDeniedError=n.AccessDeniedError,exports.AgentBuilder=AgentBuilder,exports.AttributeInUseError=n.AttributeInUseError,exports.AttributeNotFoundError=n.AttributeNotFoundError,exports.BEHAVIOR_PROPERTIES=ee,exports.BYTE_UNIT_LABELS=De,exports.CLAIMABLE_SESSION_STATUSES=ie,exports.COMPUTED_FUNCTIONS=L,exports.COMPUTED_FUNCTION_METADATA=Vt,exports.COMPUTED_FUNCTION_NAMES=Bt,exports.CONNECTOR_CALLBACK_PARAM=Ut,exports.COUNT_MODES=Te,exports.ChangeTypeNotSupportedError=n.ChangeTypeNotSupportedError,exports.ComputedFormulaCompileError=ComputedFormulaCompileError,exports.ComputedFormulaParseError=e.v,exports.ConcurrentModificationError=n.ConcurrentModificationError,exports.ContentBuilder=j,exports.DB_COLUMN_FIELDS=Le,exports.DEFAULT_AGENT_EXECUTION_CONFIG=A,exports.DEFAULT_APPROVAL_POLICY=ae,exports.DEFAULT_DICTATION_LIMITS=he,exports.DEFAULT_LABEL_FALLBACK=Me,exports.DEFAULT_MEETING_BOT_DISPLAY_NAME=be,exports.DEFAULT_ROLES=Be,exports.DEFAULT_ROLE_DESCRIPTIONS=He,exports.DEFAULT_ROLE_LABELS=Ve,exports.DEFAULT_ROLE_PERMISSIONS=Ge,exports.DEFAULT_TENANT_SETTINGS=xe,exports.DEFAULT_VALIDATION_MESSAGES=s.n,exports.DICTATION_FINALIZATION_TIMEOUT_MS=5e3,exports.DICTATION_FRAME_BYTES=3200,exports.DICTATION_MAX_BUFFER_BYTES=16e3,exports.DICTATION_MAX_FRAME_BYTES=6400,exports.DICTATION_MAX_TRANSCRIPT_BYTES=65536,exports.DICTATION_MODEL_ID=`google/gemini-3.5-transcribe-live`,exports.DICTATION_PREPARATION_TIMEOUT_MS=1e4,exports.DICTATION_SAMPLE_RATE=16e3,exports.DICTATION_TICKET_TTL_MS=15e3,exports.DISCARD_ARCHITECT_DRAFT_TOOL_NAME=`discard_architect_draft`,exports.DOCUMENT_SYSTEM_ATTRIBUTES=Oe,exports.DRAFTABLE_ATTRIBUTE_TYPES=q,exports.DRAFT_BATCH_LIMIT=12,exports.DRAFT_OBJECT_SETTINGS=jn,exports.DRAFT_SCHEMA_INPUT_EXAMPLES=Pr,exports.DRAFT_WRITE_TOOL_NAMES=Nr,exports.DRIVE_LIST_VIEW=lt,exports.DRIVE_OBJECT=st,exports.DRIVE_OBJECT_NAME=N,exports.DRIVE_VIEW=ct,exports.DestructiveSyncNotAllowedError=n.DestructiveSyncNotAllowedError,exports.DuplicateError=n.DuplicateError,exports.EMPTY_VALUE_PLACEHOLDER=`—`,exports.ESTIMATED_COUNT_CAP=1e4,exports.FAKE_MEETING_BOT_SIGNATURE_HEADER=`x-fake-signature`,exports.FAMILY_INPUTS=Ar,exports.FAMILY_WIRE_INPUTS=jr,exports.FORM_FORBIDDEN_ATTRIBUTE_TYPES=ye,exports.FlagRegistry=FlagRegistry,exports.FlagService=FlagService,exports.ForbiddenError=n.ForbiddenError,exports.FormBuilder=FormBuilder,exports.FormRegistry=FormRegistry,exports.FormRowBuilder=FormRowBuilder,exports.FormStepBuilder=FormStepBuilder,exports.GET_ARCHITECT_DRAFT_TOOL_NAME=`get_architect_draft`,exports.GroupBuilder=Je,exports.IDENTITY_PROPERTIES=S,exports.IMAGE_FORMATS=we,exports.INFERENCE_REASONING_OPTIONS=le,exports.INFERENCE_SPEEDS=ce,exports.LIST_VIEW_TAB_VISIBILITIES=e.M,exports.LIVE_EVENT_TYPES=Et,exports.LOCATION_FILTER_PROPERTIES=t.z,exports.MAILBOX_LIST_MODES=Gt,exports.MAIL_DRAFT_BODY_MAX_CHARS=2e5,exports.MAIL_SUBJECT_MAX_CHARS=998,exports.MAX_PRESET_DEPTH=5,exports.MAX_TODOS=50,exports.MAX_TODO_DESCRIPTION_CHARS=500,exports.MAX_TODO_ID_CHARS=80,exports.MEETING_ATTRIBUTES=I,exports.MEETING_DETAIL_VIEW_ID=gt,exports.MEETING_LIST_VIEW=bt,exports.MEETING_LIST_VIEW_ID=mt,exports.MEETING_OBJECT=vt,exports.MEETING_OBJECT_NAME=F,exports.MEETING_VIEW=yt,exports.MEETING_WRITE_SOURCE=ht,exports.MEMORY_LIST_VIEW=ot,exports.MEMORY_OBJECT=rt,exports.MEMORY_VIEW=at,exports.McpOAuthCompletionMode=Wt,exports.MemoryNotFoundError=n.MemoryNotFoundError,exports.MigrationTimeoutError=n.MigrationTimeoutError,exports.MultiRelationAttributeBuilder=MultiRelationAttributeBuilder,exports.NATIVE_AGENT_UI_PART_IDS_METADATA_KEY=me,exports.NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION=1,exports.NATIVE_OBJECT_NAMES=e.R,exports.NOTIFICATION_INBOX_STATES=g,exports.NOTIFICATION_KINDS=p,exports.NOTIFICATION_PRIORITIES=m,exports.NOTIFICATION_SENSITIVITIES=h,exports.NOTIFICATION_TYPES_V1=x,exports.NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED=b,exports.NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN=v,exports.NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED=y,exports.NOTIFICATION_WORK_STATES=_,exports.NO_RECORDING=Yt,exports.NO_VALUE_OPERATORS=t.P,exports.NonJsonValueError=r.o,exports.NoopGeocodingAdapter=NoopGeocodingAdapter,exports.NotFoundError=n.NotFoundError,exports.NotImplementedError=n.NotImplementedError,exports.OBJECT_NAME_SCHEMA=e.w,exports.OPEN_TOOL_PART_STATES=de,exports.OPERATION_REGISTRY=X,exports.OPERATORS_BY_TYPE=t.F,exports.OPERATOR_SPECS=R,exports.ObjectBuilder=ObjectBuilder,exports.ObjectNotFoundError=n.ObjectNotFoundError,exports.ObjectReferencedError=n.ObjectReferencedError,exports.OrphanSystemAttributeError=n.OrphanSystemAttributeError,exports.PIPES_WITH_ARGS=je,exports.PRESENTATION_PROPERTIES=C,exports.PROVIDER_NAMES=se,exports.PUBLISH_ARCHITECT_DRAFT_TOOL_NAME=`publish_architect_draft`,exports.ProtectedResourceError=n.ProtectedResourceError,exports.ProtectedRoleError=n.ProtectedRoleError,exports.QUALIFIED_SEPARATOR=`__`,exports.QUOTA_KEYS=Ee,exports.RECORDING_OVERRIDES=qt,exports.RECORDING_POLICIES=Jt,exports.RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY=Ie,exports.RELATION_TARGET_ANY=`*`,exports.REMOVED_OPERATOR_REPLACEMENTS=t.f,exports.REMOVE_OPERATION_SCHEMA=Q,exports.REPLY_MODES=Kt,exports.REQUEST_DESIGN_REVIEW_TOOL_NAME=`request_design_review`,exports.RESERVED_ATTRIBUTE_NAMES=e.N,exports.RESERVED_OBJECT_NAMES=e.P,exports.RESOURCE_VISIBILITIES=e.F,exports.RecordNotFoundError=n.RecordNotFoundError,exports.RecordReferencedError=n.RecordReferencedError,exports.RepositoryError=n.RepositoryError,exports.ReservedObjectNameError=n.ReservedObjectNameError,exports.RoleNotFoundError=n.RoleNotFoundError,exports.SCHEMA_LIMITS=e.S,exports.SCHEMA_OPERATIONS=Y,exports.SCHEMA_OPERATION_INPUT=Or,exports.SCHEMA_PLAN_LIMITS=z,exports.SCHEMA_SOURCE_ID_PATTERN=Zt,exports.SESSION_STATE_STREAM_ID=`session-state`,exports.SESSION_TERMINAL_STATUSES=re,exports.SIMPLE_PIPES=Ae,exports.SIMPLE_PROPERTY_TYPES=e.t,exports.SKILL_CONTENT_TEMPLATE=$e,exports.SKILL_LIST_VIEW=nt,exports.SKILL_OBJECT=et,exports.SKILL_VIEW=tt,exports.STANDARD_SCHEMA_VENDOR=Ke,exports.SYNONYM_ALIASES=t.b,exports.SYSTEM_ATTRIBUTES=t.X,exports.SYSTEM_ATTRIBUTE_I18N_KEYS=t.Z,exports.SYSTEM_FIELD_NAMES=e.I,exports.SYSTEM_FILTER_ATTRIBUTE_TYPES=t.p,exports.SYSTEM_PART_CODES=fe,exports.SYSTEM_RESOURCES=O,exports.SYSTEM_RESOURCE_LABELS=ze,exports.SchemaError=n.SchemaError,exports.SchemaErrorCode=n.SchemaErrorCode,exports.SchemaPlanNotFoundError=n.SchemaPlanNotFoundError,exports.SearchBackendError=n.SearchBackendError,exports.SingleRelationAttributeBuilder=SingleRelationAttributeBuilder,exports.StorageError=n.StorageError,exports.SyncCascadeError=n.SyncCascadeError,exports.SyncConflictError=n.SyncConflictError,exports.SyncError=n.SyncError,exports.SystemEntityImmutableError=n.SystemEntityImmutableError,exports.TEXT_FORMAT_PATTERNS=a.n,exports.TODAY_DEFAULT=`today`,exports.TODO_PLAN_STATUSES=oe,exports.TODO_STATUSES=pe,exports.TOOL_APPROVAL_STATES=ue,exports.USER_STATUSES=Se,exports.USER_WORK_POSTURES=Ce,exports.VIEW_OPERATIONS=G,exports.VIEW_OPERATION_INPUT=kr,exports.ValidationError=n.ValidationError,exports.ViewBuilder=qe,exports.WIRE_OMITTED_CONFIG_KEYS=e.n,exports.accessLevelToActions=accessLevelToActions,exports.actionsToAccessLevel=actionsToAccessLevel,exports.agent=agent,exports.agentDataChunk=agentDataChunk,exports.agentDisplayName=agentDisplayName,exports.agentInferencePreferencesSchema=gn,exports.agentMessageAttachmentSchema=Cn,exports.agentMessagePartSchema=Sn,exports.agentSessionInferenceOverridesInputSchema=vn,exports.agentSessionInferenceOverridesSchema=yn,exports.agentSessionMessageSchema=Dn,exports.agentUIValidationError=agentUIValidationError,exports.applyOperations=applyOperations,exports.applyPipes=applyPipes,exports.applyRelationProps=applyRelationProps,exports.architectDraftChannelKey=architectDraftChannelKey,exports.architectFocusKey=architectFocusKey,exports.asTenantId=r.t,exports.asUserId=r.n,exports.assertAcyclicComputed=assertAcyclicComputed,exports.assertAcyclicComputedDependencies=assertAcyclicComputedDependencies,exports.assertBilateralPairs=assertBilateralPairs,exports.assertCustomAgentUIMessageChunk=assertCustomAgentUIMessageChunk,exports.assertSchemaSourceId=assertSchemaSourceId,exports.attributeConfigSchemas=e.r,exports.bilateralDeclarationOf=bilateralDeclarationOf,exports.booleanFlag=booleanFlag,exports.buildAgentFallbackTitle=buildAgentFallbackTitle,exports.buildPermissionFlags=buildPermissionFlags,exports.buildPropertySchema=buildPropertySchema,exports.buildQualifiedAttribute=buildQualifiedAttribute,exports.canonicalStringify=r.s,exports.canonicalViewOperationSchema=tr,exports.canonicalizeFilterValue=t.C,exports.checkbox=checkbox,exports.collectContentViewCatalogue=collectContentViewCatalogue,exports.collectQualifiedRuleIssues=t.m,exports.collectSchemaReferences=collectSchemaReferences,exports.collectionContentSourceSchema=t.n,exports.collectionContentsOf=collectionContentsOf,exports.collectionSourceAddress=collectionSourceAddress,exports.collectionSourceAddressOf=collectionSourceAddressOf,exports.colorIdSchema=e.b,exports.columnsSchema=t.r,exports.compareAgentSessionMessages=compareAgentSessionMessages,exports.compareSchemaStateEntries=compareSchemaStateEntries,exports.compilablePlansOf=compilablePlansOf,exports.compileComputedFormula=compileComputedFormula,exports.compileRollupAttribute=compileRollupAttribute,exports.computeByteMagnitude=computeByteMagnitude,exports.computedCompileSchemaOf=computedCompileSchemaOf,exports.computedPlanOf=computedPlanOf,exports.content=M,exports.contentDefinition=contentDefinition,exports.contentExtensionRegistry=wt,exports.contentViewDefinitionSchema=t.i,exports.contentViewDefinitionSchemaFor=t.a,exports.conversationDisplayTitle=conversationDisplayTitle,exports.createCheckboxValidator=c.createCheckboxValidator,exports.createDateValidator=l.createDateValidator,exports.createFlagRegistry=createFlagRegistry,exports.createFlagService=createFlagService,exports.createFormAttributeValidator=i.f,exports.createNumberValidator=u.createNumberValidator,exports.createStandardSchemaProps=createStandardSchemaProps,exports.createTextValidator=a.t,exports.currency=currency,exports.currentActor=t.A,exports.customDataChunkSchemas=An,exports.date=date,exports.dateInTimezone=dateInTimezone,exports.dateValueStart=dateValueStart,exports.deepEqual=r.r,exports.defaultViewIdsFor=defaultViewIdsFor,exports.defaultViewsFor=defaultViewsFor,exports.defineOperation=defineOperation,exports.definePresentation=definePresentation,exports.dependentsOf=dependentsOf,exports.deriveArchitectChanges=deriveArchitectChanges,exports.deriveCreateDefaultsFromFilters=deriveCreateDefaultsFromFilters,exports.deriveInitials=deriveInitials,exports.describeOperations=describeOperations,exports.destructiveSchema=on,exports.detailView=detailView,exports.diffSchemaState=diffSchemaState,exports.displayAttributesSchema=t.o,exports.document=document,exports.draftContentViewDefinitionSchema=t.s,exports.draftContentViewDefinitionSchemaFor=t.c,exports.draftObjectSettings=draftObjectSettings,exports.draftedLabelExpression=draftedLabelExpression,exports.draftedObjectDefinition=draftedObjectDefinition,exports.draftedViewDefinition=draftedViewDefinition,exports.durableDateSchema=En,exports.episodeImpactOf=episodeImpactOf,exports.evaluateComputedAst=evaluateComputedAst,exports.evaluateComputedFormula=evaluateComputedFormula,exports.evaluateComputedFormulaWithResult=evaluateComputedFormulaWithResult,exports.evaluateFilterState=evaluateFilterState,exports.evaluateRecordFilterState=evaluateRecordFilterState,exports.extractAttributeNames=extractAttributeNames,exports.extractCurrencyFilterValue=t.O,exports.extractFilterValue=t.k,exports.extractValueRefs=extractValueRefs,exports.familyOf=familyOf,exports.filterStateSchema=t.l,exports.findRelationAttribute=findRelationAttribute,exports.flagRegistry=Ye,exports.focusOf=focusOf,exports.form=form,exports.formFieldFlatKey=formFieldFlatKey,exports.formFieldKey=formFieldKey,exports.formRegistry=Tt,exports.formatAgentStreamFrameId=formatAgentStreamFrameId,exports.formatAttributeValue=formatAttributeValue,exports.formatByteSize=formatByteSize,exports.formatComputedResult=formatComputedResult,exports.formatLocationValue=formatLocationValue,exports.formatZodErrors=s.t,exports.formula=formula,exports.fromDraftableView=fromDraftableView,exports.generateId=r.i,exports.getAttributeCapabilities=t.B,exports.getAttributeFilterOperators=t.V,exports.getEditableLabelAttribute=getEditableLabelAttribute,exports.getErrorMessage=getErrorMessage,exports.getLiveProtocolPayloadChannel=getLiveProtocolPayloadChannel,exports.getOperatorPolarity=t.w,exports.getRecordCreatorPrincipalId=getRecordCreatorPrincipalId,exports.getRollupFilterOperators=t.I,exports.getSingleAttributeFromExpression=getSingleAttributeFromExpression,exports.getSlotFieldTargets=getSlotFieldTargets,exports.getSystemAttributeI18nKey=t.Q,exports.getSystemAttributeList=t.$,exports.getUserDisplayName=getUserDisplayName,exports.group=group,exports.guidanceForBatch=guidanceForBatch,exports.hasDestructiveEntries=hasDestructiveEntries,exports.hasOptions=hasOptions,exports.iconNameSchema=e.x,exports.imageModelIdSchema=_n,exports.includesAction=includesAction,exports.indexBy=r.a,exports.inferInverseCardinality=inferInverseCardinality,exports.inferRollupReturnType=inferRollupReturnType,exports.inferenceReasoningSchema=H,exports.inferenceSpeedSchema=V,exports.isAgentUIDataName=isAgentUIDataName,exports.isAgentUIMessageBatch=isAgentUIMessageBatch,exports.isAttributeFilterable=t.H,exports.isAttributeGroupable=t.U,exports.isAttributeInUseError=n.isAttributeInUseError,exports.isAttributeKanbanGroupable=t.W,exports.isAttributeSearchable=t.G,exports.isAttributeSortable=isAttributeSortable,exports.isBilateralRelation=isBilateralRelation,exports.isCheckboxEquality=isCheckboxEquality,exports.isClaimableSessionStatus=isClaimableSessionStatus,exports.isComputedAttribute=isComputedAttribute,exports.isComputedFunctionName=isComputedFunctionName,exports.isCurrentTargetToken=isCurrentTargetToken,exports.isDateRangeValue=isDateRangeValue,exports.isDefaultRole=isDefaultRole,exports.isDocumentAttribute=isDocumentAttribute,exports.isDynamicValue=t.j,exports.isEdgePayload=isEdgePayload,exports.isEmptyObject=isEmptyObject,exports.isFormDefinition=isFormDefinition,exports.isFormFieldsRow=isFormFieldsRow,exports.isFormFreeFieldRef=isFormFreeFieldRef,exports.isFormHeadingRow=isFormHeadingRow,exports.isFormSeparatorRow=isFormSeparatorRow,exports.isFormSlotFieldRef=isFormSlotFieldRef,exports.isFormTextRow=isFormTextRow,exports.isLabelExpression=isLabelExpression,exports.isLiveEventEnvelope=isLiveEventEnvelope,exports.isLiveEventPayload=isLiveEventPayload,exports.isLiveEventPayloadForType=isLiveEventPayloadForType,exports.isLiveEventType=isLiveEventType,exports.isLocationFilterProperty=t.q,exports.isLocationPartOperator=t.J,exports.isMailProvider=isMailProvider,exports.isMailboxListMode=isMailboxListMode,exports.isManagedSystemAttribute=t.et,exports.isNativeObjectName=e.z,exports.isNoValueOperator=t.L,exports.isNotEmpty=isNotEmpty,exports.isNotFoundError=n.isNotFoundError,exports.isNullishOrEmptyString=i.p,exports.isObjectReferencedError=n.isObjectReferencedError,exports.isOpenToolPartState=isOpenToolPartState,exports.isPlainRecord=isPlainRecord,exports.isProtectedResourceError=n.isProtectedResourceError,exports.isRecordReferencedError=n.isRecordReferencedError,exports.isRelativeDateValue=t.g,exports.isReplyMode=isReplyMode,exports.isSchemaError=n.isSchemaError,exports.isSetMembershipOperator=t.T,exports.isStandardSchema=isStandardSchema,exports.isSystemPartCode=isSystemPartCode,exports.isTerminalSessionStatus=isTerminalSessionStatus,exports.isTerminalState=isTerminalState,exports.isToolApprovalState=isToolApprovalState,exports.isUniversalRelation=isUniversalRelation,exports.isValidationError=n.isValidationError,exports.isValuePresent=i.m,exports.jsonFlag=jsonFlag,exports.legacyStatusToSessionState=legacyStatusToSessionState,exports.listView=listView,exports.liveChannelKey=liveChannelKey,exports.location=location,exports.matchesAccepts=matchesAccepts,exports.mentionReferenceSchema=wn,exports.modelDefinitionSchema=Tn,exports.modelReferenceSchema=hn,exports.multiselect=multiselect,exports.multiselectOptionWriteSchema=e.o,exports.namedTargetSchema=wr,exports.nativeAgentUIPartIdMetadataKey=nativeAgentUIPartIdMetadataKey,exports.normalizeDateValue=normalizeDateValue,exports.normalizeFilterRule=t.x,exports.normalizeForEdgeRpc=t.E,exports.normalizeOperator=t.S,exports.now=t.M,exports.number=number,exports.numberFlag=numberFlag,exports.object=object,exports.orderAgentSessionMessages=orderAgentSessionMessages,exports.parseAgentStreamFrameId=parseAgentStreamFrameId,exports.parseAttributeConfig=e.s,exports.parseAttributeConfigForCreate=e.c,exports.parseAttributeConfigForUpdate=e.l,exports.parseComputedFormula=e.y,exports.parseCountMode=parseCountMode,exports.parseLiveChannelKey=parseLiveChannelKey,exports.parseNamedTarget=parseNamedTarget,exports.parseNativeAgentUIPartIdsMetadata=parseNativeAgentUIPartIdsMetadata,exports.parseOperation=parseOperation,exports.parseOptionalCountMode=parseOptionalCountMode,exports.parseQualifiedAttribute=parseQualifiedAttribute,exports.parseResourceVisibility=e.L,exports.parseSchemaState=parseSchemaState,exports.persistedSchemaPlanSchema=fn,exports.phone=phone,exports.plannedAttributeSchema=nn,exports.plannedInlineAttributeSchema=rn,exports.plannedObjectSchema=an,exports.presentationOf=presentationOf,exports.propertyAttributeSchema=e.u,exports.propertyAttributeWireSchema=e.d,exports.propertySchemaSchema=e.f,exports.propertySchemaWireSchema=e.p,exports.proposalTargetKey=proposalTargetKey,exports.providerNameSchema=mn,exports.publishedViewContentDefinitionSchema=t.u,exports.qualifiedPropertyDefs=qualifiedPropertyDefs,exports.readFormFieldValue=readFormFieldValue,exports.reconcileRelationAttributes=reconcileRelationAttributes,exports.refuseForeignKeys=e.m,exports.regenerateDerived=regenerateDerived,exports.registry=Ze,exports.rejectUnknownAttributesOrThrow=i.r,exports.relation=relation,exports.relationAcceptsObject=relationAcceptsObject,exports.relationProperty=relationProperty,exports.relationPropertyDefs=relationPropertyDefs,exports.relationTargetObjectName=relationTargetObjectName,exports.relationTargets=relationTargets,exports.relationTargetsOf=relationTargetsOf,exports.relationValueIds=relationValueIds,exports.renderLabelExpression=renderLabelExpression,exports.requestedCapabilities=requestedCapabilities,exports.requireRecordContentContext=requireRecordContentContext,exports.requireSingleRelationTarget=requireSingleRelationTarget,exports.requiredTargetKeys=requiredTargetKeys,exports.resolveAttributeDefaultValue=resolveAttributeDefaultValue,exports.resolveCollectionActions=resolveCollectionActions,exports.resolveContentNavigation=resolveContentNavigation,exports.resolveEffectiveFilterType=t.Y,exports.resolveFieldRequired=resolveFieldRequired,exports.resolveIsWithinBounds=t._,exports.resolvePropertyDefinitions=resolvePropertyDefinitions,exports.resolveTextPattern=a.r,exports.resolveUtcDayBounds=t.v,exports.resolveViewContents=resolveViewContents,exports.richtext=richtext,exports.rollup=rollup,exports.rollupToFormulaExpression=rollupToFormulaExpression,exports.sameStableValue=r.c,exports.schemaPlanSchema=un,exports.schemaStateSourcePayload=schemaStateSourcePayload,exports.select=select,exports.selectOptionWriteSchema=e.h,exports.serializeCanonicalJson=r.l,exports.serializeStableJson=r.u,exports.sessionInferencePatchSchema=bn,exports.sessionStateToLegacyStatus=sessionStateToLegacyStatus,exports.sortsSchema=t.d,exports.status=status,exports.statusGroupSchema=e.g,exports.statusOptionWriteSchema=e._,exports.stillMissing=stillMissing,exports.storedContentDefinition=storedContentDefinition,exports.stringFlag=stringFlag,exports.summarizeDraft=summarizeDraft,exports.targetSnapshot=targetSnapshot,exports.targetTokenOf=targetTokenOf,exports.targetTokensFor=targetTokensFor,exports.text=text,exports.toAttribute=toAttribute,exports.toDraftableAttributes=toDraftableAttributes,exports.toDraftableObject=toDraftableObject,exports.toDraftableView=toDraftableView,exports.toMultiValueOperator=t.D,exports.toUndefinedIfEmpty=toUndefinedIfEmpty,exports.toUtcDayString=t.y,exports.today=t.N,exports.todoItemSchema=On,exports.todoPlanSchema=kn,exports.toolImpactSchema=xn,exports.touchedObjectIds=touchedObjectIds,exports.user=user,exports.validateAttributeName=e.E,exports.validateContentViewCatalogue=validateContentViewCatalogue,exports.validateDraft=i.a,exports.validateDraftOrThrow=i.o,exports.validateLabelExpression=validateLabelExpression,exports.validateObject=i.s,exports.validateObjectExpressions=validateObjectExpressions,exports.validateObjectName=e.k,exports.validateObjectOrThrow=i.c,exports.validateQualifiedRule=t.h,exports.validateStoredViews=validateStoredViews,exports.validateViewName=e.j,exports.viewIdFor=viewIdFor,exports.viewIdentityKey=viewIdentityKey,exports.viewRegistry=xt,exports.workspaceViewAuthoring=workspaceViewAuthoring;