@stndrds/schema 1.0.0-alpha.342 → 1.0.0-alpha.343

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 (80) hide show
  1. package/dist/{all-BWBHE8zC.d.ts → all-BjBPrd9V.d.ts} +8 -8
  2. package/dist/{all-C1AF2SKY.d.mts → all-BrEKv8xR.d.mts} +9 -9
  3. package/dist/{checkbox-BJiVPQKC.d.ts → checkbox-D8nK0oIO.d.ts} +2 -2
  4. package/dist/{checkbox-C1oY-AXS.d.mts → checkbox-DSzn5epa.d.mts} +2 -2
  5. package/dist/{config-aeELOnWd.mjs → config-6uO9OYWQ.mjs} +3 -3
  6. package/dist/{config-BvijG1IN.js → config-DIBMi8S_.js} +3 -3
  7. package/dist/{date-DJzdIygB.d.ts → date-BGULTVlX.d.ts} +2 -2
  8. package/dist/{date-pUpneFTR.d.mts → date-CteDw_88.d.mts} +2 -2
  9. package/dist/{exceptions-CHlIXRKP.d.mts → exceptions-BCfkN2ct.d.mts} +3 -0
  10. package/dist/{exceptions-CHlIXRKP.d.ts → exceptions-BCfkN2ct.d.ts} +3 -0
  11. package/dist/exceptions.d.mts +1 -1
  12. package/dist/exceptions.d.ts +1 -1
  13. package/dist/exceptions.js +1 -1
  14. package/dist/exceptions.mjs +1 -1
  15. package/dist/{index-CJYpJqEh.d.ts → index-BKv7a08I.d.ts} +1 -1
  16. package/dist/{index-CUEwuqCj.d.ts → index-CLEwI8GE.d.ts} +2 -2
  17. package/dist/{index-DX1EILel.d.mts → index-Ds0DxPHk.d.mts} +3 -3
  18. package/dist/{index-BAW8p4U_.d.ts → index-DyeLYnEc.d.ts} +1 -1
  19. package/dist/{index-BilM1Dnp.d.mts → index-DzEWbzP-.d.mts} +1 -1
  20. package/dist/{index-B-LzvZZe.d.mts → index-_gdqRN1W.d.mts} +2 -2
  21. package/dist/index.d.mts +223 -11
  22. package/dist/index.d.ts +222 -10
  23. package/dist/index.js +9 -9
  24. package/dist/index.mjs +9 -9
  25. package/dist/{number-BZ9pUAob.d.ts → number-BcMYyg8j.d.ts} +2 -2
  26. package/dist/{number-D6UXWPnL.d.mts → number-U7UMAXKt.d.mts} +2 -2
  27. package/dist/{object-BfGtzS7g.js → object-BA3vKFl0.js} +1 -1
  28. package/dist/{object-D-aDCAHn.mjs → object-C92B0Oei.mjs} +1 -1
  29. package/dist/phone-CsV9QNwF.mjs +2 -0
  30. package/dist/{phone-CUgSbH-z.js → phone-MN6Li5Wx.js} +1 -1
  31. package/dist/{text-D4mEL9hl.d.ts → text-C4EAE9Ap.d.ts} +2 -2
  32. package/dist/{text-_dBcTPGm.d.mts → text-CjhjkBXJ.d.mts} +2 -2
  33. package/dist/utils.d.mts +1 -1
  34. package/dist/utils.d.ts +1 -1
  35. package/dist/validation/all.d.mts +4 -4
  36. package/dist/validation/all.d.ts +4 -4
  37. package/dist/validation/all.js +1 -1
  38. package/dist/validation/all.mjs +1 -1
  39. package/dist/validation/complex/currency.d.mts +2 -2
  40. package/dist/validation/complex/currency.d.ts +2 -2
  41. package/dist/validation/complex/location.d.mts +2 -2
  42. package/dist/validation/complex/location.d.ts +2 -2
  43. package/dist/validation/complex/phone.d.mts +2 -2
  44. package/dist/validation/complex/phone.d.ts +2 -2
  45. package/dist/validation/complex/phone.js +1 -1
  46. package/dist/validation/complex/phone.mjs +1 -1
  47. package/dist/validation/complex/relation.d.mts +2 -2
  48. package/dist/validation/complex/relation.d.ts +2 -2
  49. package/dist/validation/complex/richtext.d.mts +2 -2
  50. package/dist/validation/complex/richtext.d.ts +2 -2
  51. package/dist/validation/complex/select.d.mts +2 -2
  52. package/dist/validation/complex/select.d.ts +2 -2
  53. package/dist/validation/complex/user.d.mts +2 -2
  54. package/dist/validation/complex/user.d.ts +2 -2
  55. package/dist/validation/computed/formula.d.mts +2 -2
  56. package/dist/validation/computed/formula.d.ts +2 -2
  57. package/dist/validation/computed/rollup.d.mts +2 -2
  58. package/dist/validation/computed/rollup.d.ts +2 -2
  59. package/dist/validation/config/index.d.mts +1 -1
  60. package/dist/validation/config/index.d.ts +1 -1
  61. package/dist/validation/config/index.js +1 -1
  62. package/dist/validation/config/index.mjs +1 -1
  63. package/dist/validation/core/index.d.mts +1 -1
  64. package/dist/validation/core/index.d.ts +1 -1
  65. package/dist/validation/object/index.d.mts +1 -1
  66. package/dist/validation/object/index.d.ts +1 -1
  67. package/dist/validation/object/index.js +1 -1
  68. package/dist/validation/object/index.mjs +1 -1
  69. package/dist/validation/primitives/checkbox.d.mts +1 -1
  70. package/dist/validation/primitives/checkbox.d.ts +1 -1
  71. package/dist/validation/primitives/date.d.mts +1 -1
  72. package/dist/validation/primitives/date.d.ts +1 -1
  73. package/dist/validation/primitives/number.d.mts +1 -1
  74. package/dist/validation/primitives/number.d.ts +1 -1
  75. package/dist/validation/primitives/text.d.mts +1 -1
  76. package/dist/validation/primitives/text.d.ts +1 -1
  77. package/dist/{view-config.schema-CMjVNRCh.mjs → view-config.schema-CupkOK1m.mjs} +1 -1
  78. package/dist/{view-config.schema-4QhPV9el.js → view-config.schema-D6b67GQM.js} +1 -1
  79. package/package.json +2 -2
  80. package/dist/phone-X_nKo0qe.mjs +0 -2
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
2
- import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as ee,S as v,T as y,U as b,V as x,W as te,X as ne,Y as re,Z as ie,_ as ae,a as oe,b as se,c as ce,d as le,et as ue,f as de,g as fe,h as pe,i as me,j as he,k as ge,l as _e,m as ve,n as ye,o as be,p as xe,q as Se,r as Ce,s as we,t as Te,tt as Ee,u as S,v as De,w as Oe,x as ke,y as Ae,z as je}from"./view-config.schema-CMjVNRCh.mjs";import{AccessDeniedError as Me,AttributeInUseError as Ne,AttributeNotFoundError as Pe,ChangeTypeNotSupportedError as Fe,ConcurrentModificationError as Ie,DestructiveSyncNotAllowedError as Le,DuplicateError as C,ForbiddenError as Re,MemoryNotFoundError as ze,MigrationTimeoutError as Be,NotFoundError as Ve,NotImplementedError as He,ObjectNotFoundError as Ue,ObjectReferencedError as We,OrphanSystemAttributeError as Ge,ProtectedResourceError as Ke,ProtectedRoleError as qe,RecordNotFoundError as Je,RecordReferencedError as Ye,RepositoryError as Xe,ReservedObjectNameError as Ze,RoleNotFoundError as Qe,SchemaError as w,SchemaErrorCode as T,SchemaPlanNotFoundError as $e,SearchBackendError as et,StorageError as tt,SyncCascadeError as nt,SyncConflictError as rt,SyncError as it,SystemEntityImmutableError as at,ValidationError as E,isAttributeInUseError as ot,isNotFoundError as st,isObjectReferencedError as ct,isProtectedResourceError as lt,isRecordReferencedError as ut,isSchemaError as dt,isValidationError as ft}from"./exceptions.mjs";import{A as D,C as pt,D as O,E as mt,F as ht,I as gt,L as _t,M as vt,N as yt,O as bt,P as xt,R as St,S as Ct,T as wt,_ as Tt,a as Et,b as Dt,c as Ot,d as kt,f as At,g as jt,h as Mt,i as Nt,j as Pt,k as Ft,l as It,m as Lt,n as Rt,o as zt,p as Bt,r as Vt,s as Ht,t as Ut,u as Wt,v as Gt,w as Kt,x as qt,y as k,z as Jt}from"./config-aeELOnWd.mjs";import{n as Yt,r as Xt,t as Zt}from"./text-C8Lb-NFo.mjs";import{n as Qt,t as $t}from"./core-BLHhNykL.mjs";import{createNumberValidator as en}from"./validation/primitives/number.mjs";import{createCheckboxValidator as tn}from"./validation/primitives/checkbox.mjs";import{createDateValidator as nn}from"./validation/primitives/date.mjs";import{a as rn,c as an,i as on,l as sn,n as cn,o as ln,r as un,s as A,t as dn,u as fn}from"./utils-fXIvFFl6.mjs";import{a as pn,c as mn,d as hn,f as gn,i as _n,m as vn,o as yn,p as j,r as bn,s as xn,u as Sn}from"./object-D-aDCAHn.mjs";import{i as Cn,n as wn,r as Tn}from"./phone-X_nKo0qe.mjs";import{MEMORY_DESCRIPTION_MAX_LENGTH as En,MEMORY_NAME_MAX_LENGTH as Dn,SKILL_DESCRIPTION_MAX_LENGTH as On,SKILL_NAME_MAX_LENGTH as kn,getCountryDisplayNameByIso3 as M}from"@stndrds/constants";import{z as N}from"zod";const An=[`fyi`,`task`,`question`,`handoff`,`system`],jn=[`low`,`normal`,`high`,`urgent`],Mn=[`public`,`internal`,`sensitive`],Nn=[`unread`,`read`,`archived`,`snoozed`],Pn=[`none`,`pending`,`processing`,`completed`,`dismissed`,`expired`,`failed`],Fn=`agent.session.waiting_human`,In=`agent.task.assigned`,Ln=`agent.question.requested`,Rn=[Fn,In,Ln],zn=[`name`,`type`],Bn=[`required`,`hidden`,`archived`,`deprecated`,`defaultValue`,`config`,`order`,`unique`],Vn=[`label`,`description`,`placeholder`,`icon`],Hn=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`status`,`location`,`select`,`multiselect`,`user`,`relation`,`formula`,`rollup`,`document`],Un=`*`;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 Se(e)}const Wn=[`record`,`object`,`attribute`,`view`,`user`,`role`,`settings`,`file`,`agent`,`schema_source`,`tenant_invitation`],Gn=`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.presented,schema_source.removed,user.created,user.invited,user.updated,user.deleted,user.login,user.logout,tenant_invitation.created,tenant_invitation.delivery_failed,tenant_invitation.resent,tenant_invitation.revoked,tenant_invitation.accepted,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 w(`parked state without parkedOn`,T.INVARIANT_VIOLATION);return e.parkedOn===`agents`?`waiting_agents`:`waiting_human`;case`terminal`:if(e.outcome===void 0)throw new w(`terminal state without outcome`,T.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 Kn=[`completed`,`failed`,`cancelled`,`timeout`,`expired`];function isTerminalSessionStatus(e){return Kn.includes(e)}const qn=[`idle`,`completed`,`waiting_human`,`waiting_agents`,`cancelled`,`failed`,`timeout`];function isClaimableSessionStatus(e){return qn.includes(e)}const Jn=Object.freeze({mutation:`ask`,destructive:`ask`,outward:`ask`}),Yn=[`active`,`completed`,`abandoned`],Xn=[`openai`,`anthropic`,`google`,`spacexai`,`deepseek`,`moonshotai`,`alibaba`,`mistral`,`minimax`,`meta`,`zai`],Zn=[`standard`,`fast`],Qn=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`];function agentDisplayName(e){return e.label?.trim()||e.name}const $n=[`approval-requested`,`approval-responded`,`approval-dispatched`],er=[`streaming`,`running`,`pending`,...$n];function isOpenToolPartState(e){return er.includes(e)}function isToolApprovalState(e){return $n.includes(e)}const tr=[`CREDITS_EXHAUSTED`];function isSystemPartCode(e){return typeof e==`string`&&tr.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 nr=`agent-notification`;function isAgentNotificationMetadata(e){return e?.kind===nr}const rr=[`pending`,`in_progress`,`completed`,`blocked`],ir=50,ar=80,or=500,sr=`session-state`,cr=`__stndrdsNativeUiPartIds`,lr=1;function invalidNativePartIds(){throw new E(`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?.[cr];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 ur=16e3,dr=3200,fr=6400,pr=16e3,mr=65536,hr=15e3,gr=1e4,_r=5e3,vr=`google/gemini-3.5-transcribe-live`,yr={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2},br=[`web`,`presentation`,`document`,`spreadsheet`,`image`,`code`,`other`],xr=[`ephemeral`,`conversation`,`persistent`],Sr=[`source`,`preview`,`entrypoint`,`asset`],Cr=5;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 wr=[`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 Tr=[`read`,`create`,`update`,`delete`,`manage`];function actionsToAccessLevel(e){return e.length===0?`none`:e.length===1&&e[0]===`read`?`read-only`:e.length===Tr.length&&Tr.every(t=>e.includes(t))?`full`:`custom`}function accessLevelToActions(e){switch(e){case`full`:return[...Tr];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 Er=`Notetaker`,Dr={systemPrompt:null,meetingRecordingPolicy:`none`,meetingBotDisplayName:Er},Or=6048e5,kr=36e5,Ar=2592e6,jr=6e4,Mr=[`active`,`suspended`],Nr=[`architect`,`manual`,`auto`];function schemaGroupKey(e){return`${e.kind}:${e.id}`}function refuse(e,t){throw new E(t,[{path:[e],message:t}])}function parseSchemaGroupPresentation(e){let t=e??{},n={};if(t.label!==void 0){let e=t.label;if(e===null)n.label=null;else if(typeof e!=`string`)refuse(`label`,`Label must be a string`);else{let t=e.trim();t.length===0&&refuse(`label`,`Label must not be empty`),t.length>Pt.labelLength&&refuse(`label`,`Label is too long (max ${Pt.labelLength} characters)`),n.label=t}}if(t.icon!==void 0){let e=t.icon;if(e===null)n.icon=null;else{let t=D.safeParse(e);t.success||refuse(`icon`,`Invalid icon name`),n.icon=t.data}}return n}const Pr=[`square`,`landscape`,`portrait`],Fr=[`none`,`estimated`,`exact`];function parseCountMode(e){if(typeof e==`string`&&Fr.includes(e))return e;throw new E(`countMode must be one of: ${Fr.join(`, `)} (received: ${String(e)})`,[])}function parseOptionalCountMode(e){return e===void 0?void 0:parseCountMode(e)}const Ir=1e4,Lr=[`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 Rr=[`B`,`KB`,`MB`,`GB`,`TB`];function formatByteSize(e){let{value:t,unitIndex:n}=computeByteMagnitude(e);return`${t} ${Rr[n]}`}const zr={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 Br=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(!Br.includes(e.type))throw Error(`Property type "${e.type}" is not supported in .qualifyWith()`);t.push(e)}return{definitions:t}}const Vr=`__`;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 j(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}const Hr=`—`;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?wn(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(M(n.country));break;case`state`:n.state&&r.push(n.state),n.country&&r.push(M(n.country));break;case`city`:n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(M(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(M(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(M(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(j(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 Ur=[`UPPER`,`LOWER`,`capitalize`,`trim`],Wr=[`prefix`,`suffix`,`wrap`,`default`],Gr=[...Ur,...Wr],P=N.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(!Gr.includes(e))return!1}return!0},{message:`Invalid pipe name. Valid pipes: ${Gr.join(`, `)}`});function validateLabelExpression(e){let t=P.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 Kr=`(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=Kr){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 qr=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function getSingleAttributeFromExpression(e){let t=e.trim().match(qr);return t?t[1]:null}function getEditableLabelAttribute(e,t){let n=getSingleAttributeFromExpression(e);if(n===null)return null;let r=t.find(e=>e.name===n);return!r||r.type!==`text`||x(r).authoring.readOnly?null:r}const Jr=/\{\{\s*props\./;function applyRelationProps(e,t,n){if(!Jr.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(j(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 Yr=/\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(Yr)?.[0];return t===void 0?``:[...t.toUpperCase()][0]??``}).filter(Boolean).slice(0,2).join(``);return i===``?t:i}const Xr=`__creatorRootActorId`;function getRecordCreatorPrincipalId(e){let t=e.metadata?.[Xr];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 Zr=new Set([`id`,`name`,`label`,`type`,`required`,`system`,`unique`,`order`]),F={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`},Qr=[F.PEOPLE,F.WORKSPACE,F.ARCHITECT,F.FEATURE_FLAGS,F.FILES,F.VIEWS,F.FORMS,F.DOCUMENTS,F.AUDIT,F.API_KEYS,F.CONNECTORS,F.ENV_VARS,F.SESSION],$r={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`},ei={OWNER:`owner`,MEMBER:`member`,AGENT_DEFAULT:`agent_default`,REFLEX_DEFAULT:`reflex_default`},ti={owner:`Owner`,member:`Member`,agent_default:`Agent Default`,reflex_default:`Reflex Default`},ni={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`},ri=[`read`,`create`,`update`,`delete`,`manage`],ii=[`read`,`create`,`update`,`delete`],ai=[`read`,`create`,`update`,`delete`],oi={owner:{system:[{target:`*`,actions:ri}],object:[{target:`*`,actions:ri}]},member:{system:[{target:`people`,actions:[`read`]},{target:`workspace`,actions:[`read`]},{target:`connectors`,actions:ii},{target:`files`,actions:ai},{target:`documents`,actions:ai}],object:[{target:`*`,actions:ri}]},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(ei).includes(e)}const si={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 E(`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??si,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={...Jn,...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 E(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new E(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility===`private`)throw new E(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return Ct(this.bp.triggers,e=>e.name,e=>new E(`Agent "${this.bp.name}": duplicate trigger name "${e}"`,[])),{...this.bp,visibility:this.bp.visibility??`workspace`,config:this.bp.config??si,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};function agent(e){return new AgentBuilder(e)}const ci=`@stndrds/schema`;function createStandardSchemaProps(e){return{version:1,vendor:ci,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(hn(this.build()))}constructor(e,t,n){pt(t),wt(n),this.attr={name:t,label:n,type:e,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(e){return Kt(e,`attribute "${this.attr.name}"`),this.attr.icon=e,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(e){let t=asMutableArray(e);return O(this.attr.name??`unknown`,t),this.attr.options=t,this.asPhantomState()}option(e){this.attr.options||(this.attr.options=[]);let t=[...this.attr.options,e];return O(this.attr.name??`unknown`,t),this.attr.options.push(e),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(e){let t=asMutableArray(e);return O(this.attr.name??`unknown`,t),this.attr.options=t,this.asPhantomState()}option(e){this.attr.options||(this.attr.options=[]);let t=[...this.attr.options,e];return O(this.attr.name??`unknown`,t),this.attr.options.push(e),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(e){let t=asMutableArray(e);return O(this.attr.name??`unknown`,t),this.attr.options=t,this.asPhantomState()}option(e){this.attr.options||(this.attr.options=[]);let t=[...this.attr.options,e];return O(this.attr.name??`unknown`,t),this.attr.options.push(e),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 n=t[0]?.object;if(!n)throw new E(`Bilateral relation requires one target object`,[{path:[`bilateral`,`object`],message:`Bilateral relation requires one target object`}]);if(e.object&&e.object!==n){let t=`Bilateral inverse object ${e.object} must match relation target ${n}`;throw new E(t,[{path:[`bilateral`,`object`],message:t}])}return this.attr.bilateral={...e,object:n},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`,n=this.attr.targetAttribute??`field`;throw new w(`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}.${n}").`,T.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=N.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 N.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=[...Gr,`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(wr);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: ${wr.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 E(`[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:n,embeddingExpression:r}=e;if(!n)throw new w(`Object "${t}" must have a labelExpression. The labelExpression defines how records are displayed in lists and relations (e.g. "{{ name }}").`,T.VALIDATION_FAILED);let i=P.safeParse(n);if(!i.success){let e=i.error.issues[0]?.message??`Invalid labelExpression`;throw new w(`Invalid labelExpression for "${t}": ${e}`,T.VALIDATION_FAILED)}if(r!==void 0){let e=P.safeParse(r);if(!e.success){let n=e.error.issues[0]?.message??`Invalid embeddingExpression`;throw new w(`Invalid embeddingExpression for "${t}": ${n}`,T.VALIDATION_FAILED)}}}var ObjectBuilder=class{get"~standard"(){return createStandardSchemaProps(Sn(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(e){let t=e.map(e=>`build`in e&&typeof e.build==`function`?e.build():e);Ct([...this.obj.attributes,...t],e=>e.name,e=>new C(`attribute`,e,`Object "${this.obj.name}": duplicate attribute name "${e}"`)),this.obj.attributes.push(...t)}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 E(`[ObjectBuilder] Missing required field: name`,[{path:[`name`],message:`name is required`}]);if(!this.obj.label)throw new E(`[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(e){e!==void 0&&mt(e)}};function object(e){if(Jt(e.name))throw new Ze(e.name,`builder`);return new ObjectBuilder(e)}function validatePresetStructure(e,t,n){let fail=(t,n)=>{throw new E(t,[{path:[`documentLayout`,`presets`,e],message:n}])};n>5&&fail(`Preset structure exceeds max depth of 5`,`Preset structure too deep`);let r=new Set;for(let i of t){let t=i.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}"`),r.has(t)&&fail(`Folder preset sibling titles must be unique`,`Duplicate folder title: "${t}"`),r.add(t),i.children&&i.children.length>0&&validatePresetStructure(e,i.children,n+1)}}function cloneBuilderValue(e,t){try{return structuredClone(e)}catch{let e=`Builder configuration must contain cloneable data`;throw new E(e,[{path:t,message:e}])}}function requireBuilderName(e,t){if(typeof e!=`string`||e.trim().length===0)throw new E(`Name must not be blank`,[{path:t,message:`Name must not be blank`}])}function validateContentConfiguration(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new E(`Invalid content configuration`,[{path:t,message:`Expected content configuration`}]);for(let n of[`name`,`label`,`placement`])if(Object.hasOwn(e,n)){let e=`Independent content configuration cannot define ${n}`;throw new E(e,[{path:[...t,n],message:e}])}let n=S.safeParse({...e,name:`content`,placement:`main`});if(!n.success)throw E.fromZodErrors(n.error.issues.map(e=>({path:[...t,...e.path.map(String)],message:e.message})));n.data.type===`form`&&n.data.groups.forEach((e,n)=>requireBuilderName(e.name,[...t,`groups`,String(n),`name`]));let{name:r,label:i,placement:a,...o}=n.data;return cloneBuilderValue(o,t)}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,n){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 E(t,[{path:n,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 li=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,n,r){let i=[`views`,`0`,`contents`,String(this.data.contents.length)],a,o;try{typeof n==`object`&&n&&`build`in n&&typeof n.build==`function`?(a=validateContentConfiguration(n.build(),i),o=n.extension):a=validateContentConfiguration(n,i)}catch(e){throw e instanceof E?new E(e.message,e.errors.map(e=>({...e,path:e.path[0]===`content`?[...i,...e.path.slice(1)]:e.path}))):e}let s={...a,name:e,label:t,placement:r},c=[...this.data.contents,s];return new ViewBuilder({...this.data,contents:c},[...this.extensions,o])}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 t=me.safeParse(this.data);if(!t.success)throw E.fromZodErrors(t.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 li({name:e,label:t,object:void 0,context:`record`,contents:[]})}function listView(e,t){return new li({name:e,label:t,object:void 0,context:`collection`,contents:[]})}function relationProperty(e){return requireBuilderName(e,[`relationProperty`]),{relationProperty:e}}var I=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 E.fromZodErrors(t.error.issues.map(e=>({path:[`content`,`parameters`,...e.path.map(String)],message:e.message})))}return e}},ui=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 E?new E(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 ui(e,t,[])}function collection(){return new I({type:`collection`})}function form$1(...e){return new I({type:`form`,groups:e.map(e=>`build`in e?e.build():e)})}function activity(){return new I({type:`activity`})}function richtext$1(e){return new I({type:`richtext`,attribute:e})}function documents(){return new I({type:`documents`})}function forms(){return new I({type:`forms`})}function emails(...e){return new I({type:`emails`,emailAttributes:e})}function meetings(...e){return new I({type:`meetings`,emailAttributes:e})}function custom(e,t){if(typeof e!=`object`||!e||typeof e.name!=`string`)throw new E(`Expected registered extension declaration`,[{path:[`content`,`extension`],message:`Expected registered extension declaration`}]);let n=validateContentConfiguration({type:`custom`,extension:e.name,parameters:t},[`content`]);if(n.type!==`custom`)throw new E(`Expected custom content`,[]);let r=new I({...n,extension:e.name},e);return r.build(),r}const L={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 C(`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 Ve(`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 di=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,n,r={}){if(!this.repository)throw new w(`Cannot set override: no FeatureFlagsRepository configured. Add featureFlags to your DatabaseAdapter to enable runtime overrides.`,T.CONFIGURATION_REQUIRED);let i=this.registry.get(e);if(i&&!i.allowedLevels.includes(t)){let n=`Flag "${e}" does not allow ${t}-level overrides. Allowed levels: ${i.allowedLevels.join(`, `)}`;throw new E(n,[{path:[`level`],message:n}])}if(i?.system){let t=`Flag "${e}" is a system flag and cannot be overridden via API.`;throw new E(t,[{path:[`flagName`],message:t}])}await this.repository.setOverride({flagName:e,level:t,value:n,targetId:r.targetId,expiresAt:r.expiresAt,createdBy:r.createdBy})}async deleteOverride(e,t,n){if(!this.repository)throw new w(`Cannot delete override: no FeatureFlagsRepository configured.`,T.CONFIGURATION_REQUIRED);await this.repository.deleteOverride(e,t,n)}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 fi=Symbol(`stndrds.native-object`);function markNativeDefinition(e){return Object.defineProperty(e,fi,{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[fi]===!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),n=new Set;for(let e of t){if(this.validate(e),n.has(e.name))throw new C(`object`,e.name,`[NativeObjectRegistry] Duplicate object name "${e.name}" within a single register() batch.`);n.add(e.name)}for(let e of t)this.objects.set(e.name,cloneObjectDefinition(e));return this}validate(e){if(!e.system){let t=`[NativeObjectRegistry] Cannot register object "${e.name}" (id: ${e.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 E(t,[])}if(Jt(e.name)&&!isNativeDefinition(e))throw new Ze(e.name,`registry`);if(this.objects.has(e.name)){let t=this.objects.get(e.name),n=`[NativeObjectRegistry] Duplicate object name "${e.name}":\n - Existing: "${t?.label}" (id: ${t?.id})\n - New: "${e.label}" (id: ${e.id})\nPlease use unique names for each native object.`;throw new C(`object`,e.name,n)}}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 Ve(`Native object`,e,T.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 pi=new NativeObjectRegistryClass,mi=new WeakSet;function markSystemView(e){return mi.add(e.definition),e}function isSystemViewDefinition(e){return typeof e==`object`&&!!e&&mi.has(e)}const hi=`## Overview
2
+ import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as ee,S as v,T as y,U as b,V as x,W as S,X as te,Y as ne,Z as re,_ as ie,a as ae,b as oe,c as se,d as ce,et as le,f as ue,g as de,h as fe,i as pe,j as me,k as he,l as ge,m as _e,n as ve,o as ye,p as be,q as xe,r as Se,s as Ce,t as we,tt as Te,u as C,v as Ee,w as De,x as Oe,y as ke,z as Ae}from"./view-config.schema-CupkOK1m.mjs";import{AccessDeniedError as je,AttributeInUseError as Me,AttributeNotFoundError as Ne,ChangeTypeNotSupportedError as Pe,ConcurrentModificationError as Fe,DestructiveSyncNotAllowedError as Ie,DuplicateError as w,ForbiddenError as Le,MemoryNotFoundError as Re,MigrationTimeoutError as ze,NotFoundError as Be,NotImplementedError as Ve,ObjectNotFoundError as He,ObjectReferencedError as Ue,OrphanSystemAttributeError as We,ProtectedResourceError as Ge,ProtectedRoleError as Ke,RecordNotFoundError as qe,RecordReferencedError as Je,RepositoryError as Ye,ReservedObjectNameError as Xe,RoleNotFoundError as Ze,SchemaError as T,SchemaErrorCode as E,SchemaPlanNotFoundError as Qe,SearchBackendError as $e,StorageError as et,SyncCascadeError as tt,SyncConflictError as nt,SyncError as rt,SystemEntityImmutableError as it,ValidationError as D,isAttributeInUseError as at,isNotFoundError as ot,isObjectReferencedError as st,isProtectedResourceError as ct,isRecordReferencedError as lt,isSchemaError as ut,isValidationError as dt}from"./exceptions.mjs";import{A as O,C as ft,D as k,E as pt,F as mt,I as ht,L as gt,M as _t,N as vt,O as yt,P as bt,R as xt,S as St,T as Ct,_ as wt,a as Tt,b as Et,c as Dt,d as Ot,f as kt,g as At,h as jt,i as Mt,j as Nt,k as Pt,l as Ft,m as It,n as Lt,o as Rt,p as zt,r as Bt,s as Vt,t as Ht,u as Ut,v as Wt,w as Gt,x as Kt,y as A,z as qt}from"./config-6uO9OYWQ.mjs";import{n as Jt,r as Yt,t as Xt}from"./text-C8Lb-NFo.mjs";import{n as Zt,t as Qt}from"./core-BLHhNykL.mjs";import{createNumberValidator as $t}from"./validation/primitives/number.mjs";import{createCheckboxValidator as en}from"./validation/primitives/checkbox.mjs";import{createDateValidator as tn}from"./validation/primitives/date.mjs";import{a as nn,c as rn,i as an,l as on,n as sn,o as cn,r as ln,s as j,t as un,u as dn}from"./utils-fXIvFFl6.mjs";import{a as fn,c as pn,d as mn,f as hn,i as gn,m as _n,o as vn,p as M,r as yn,s as bn,u as xn}from"./object-C92B0Oei.mjs";import{i as Sn,n as Cn,r as wn}from"./phone-CsV9QNwF.mjs";import{z as N}from"zod";import{MEMORY_DESCRIPTION_MAX_LENGTH as Tn,MEMORY_NAME_MAX_LENGTH as En,SKILL_DESCRIPTION_MAX_LENGTH as Dn,SKILL_NAME_MAX_LENGTH as On,getCountryDisplayNameByIso3 as P}from"@stndrds/constants";const kn=[`fyi`,`task`,`question`,`handoff`,`system`],An=[`low`,`normal`,`high`,`urgent`],jn=[`public`,`internal`,`sensitive`],Mn=[`unread`,`read`,`archived`,`snoozed`],Nn=[`none`,`pending`,`processing`,`completed`,`dismissed`,`expired`,`failed`],Pn=`agent.session.waiting_human`,Fn=`agent.task.assigned`,In=`agent.question.requested`,Ln=[Pn,Fn,In],Rn=[`name`,`type`],zn=[`required`,`hidden`,`archived`,`deprecated`,`defaultValue`,`config`,`order`,`unique`],Bn=[`label`,`description`,`placeholder`,`icon`],Vn=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`status`,`location`,`select`,`multiselect`,`user`,`relation`,`formula`,`rollup`,`document`],Hn=`*`;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 xe(e)}const Un=[`record`,`object`,`attribute`,`view`,`user`,`role`,`settings`,`file`,`agent`,`schema_source`,`tenant_invitation`],Wn=`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.presented,schema_source.removed,user.created,user.invited,user.updated,user.deleted,user.login,user.logout,tenant_invitation.created,tenant_invitation.delivery_failed,tenant_invitation.resent,tenant_invitation.revoked,tenant_invitation.accepted,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 T(`parked state without parkedOn`,E.INVARIANT_VIOLATION);return e.parkedOn===`agents`?`waiting_agents`:`waiting_human`;case`terminal`:if(e.outcome===void 0)throw new T(`terminal state without outcome`,E.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 Gn=[`completed`,`failed`,`cancelled`,`timeout`,`expired`];function isTerminalSessionStatus(e){return Gn.includes(e)}const Kn=[`idle`,`completed`,`waiting_human`,`waiting_agents`,`cancelled`,`failed`,`timeout`];function isClaimableSessionStatus(e){return Kn.includes(e)}const qn=Object.freeze({mutation:`ask`,destructive:`ask`,outward:`ask`}),Jn=[`active`,`completed`,`abandoned`],Yn=[`openai`,`anthropic`,`google`,`spacexai`,`deepseek`,`moonshotai`,`alibaba`,`mistral`,`minimax`,`meta`,`zai`],Xn=[`standard`,`fast`],Zn=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`];function agentDisplayName(e){return e.label?.trim()||e.name}const Qn=[`approval-requested`,`approval-responded`,`approval-dispatched`],$n=[`streaming`,`running`,`pending`,...Qn];function isOpenToolPartState(e){return $n.includes(e)}function isToolApprovalState(e){return Qn.includes(e)}const er=[`CREDITS_EXHAUSTED`];function isSystemPartCode(e){return typeof e==`string`&&er.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 tr=`agent-notification`;function isAgentNotificationMetadata(e){return e?.kind===tr}const nr=`agent-message`;function isAgentMessageMetadata(e){return e?.kind===nr}const rr=[`pending`,`in_progress`,`completed`,`blocked`],ir=50,ar=80,or=500,sr=`session-state`,cr=`__stndrdsNativeUiPartIds`,lr=1;function invalidNativePartIds(){throw new D(`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?.[cr];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 ur=16e3,dr=3200,fr=6400,pr=16e3,mr=65536,hr=15e3,gr=1e4,_r=5e3,vr=`google/gemini-3.5-transcribe-live`,yr={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2},br=`/v1/device-worker/channel`,xr=262144,Sr=1e4,Cr=2e3,wr=2e3,Tr=2e4,Er=[`worker_disconnected`,`cancelled`,`timed_out`,`execution_failed`,`stale_reference`,`tab_unavailable`,`debugger_unavailable`,`blocked_by_user`];var DeviceChannelProtocolError=class extends T{constructor(e){super(e,E.DEVICE_CHANNEL_PROTOCOL),this._tag=`DeviceChannelProtocolError`,this.name=`DeviceChannelProtocolError`}};const F={id:N.uuid(),leaseToken:N.string().min(1)},Dr=N.record(N.string(),N.unknown());function defineDeviceChannelFrames(e){return{worker:N.discriminatedUnion(`type`,[N.strictObject({type:N.literal(`authenticate`),credential:N.string().regex(/^(Device|Bearer) \S+$/)}),N.strictObject({type:N.literal(`running`),...F}),N.strictObject({type:N.literal(`heartbeat`),...F}),N.strictObject({type:N.literal(`output`),...F,stdout:N.string().optional(),stderr:N.string().optional()}),N.strictObject({type:N.literal(`complete`),...F,result:N.strictObject({stdout:N.string().optional(),stderr:N.string().optional(),exitCode:N.number().int(),success:N.boolean(),errorCode:N.enum(Er).optional(),result:e.result.optional()})}),N.strictObject({type:N.literal(`pong`)})]),server:N.discriminatedUnion(`type`,[N.strictObject({type:N.literal(`ready`),device:N.strictObject({id:N.string(),name:N.string(),capability:N.enum([`shell`,`browser`])})}),N.strictObject({type:N.literal(`command`),...F,kind:N.enum([`shell`,`browser`]),intent:N.string(),timeoutMs:N.number().int(),command:N.string().optional(),cwd:N.string().nullable().optional(),action:e.action.optional()}),N.strictObject({type:N.literal(`cancel`),id:N.uuid(),reason:N.enum([`cancelled`,`timed_out`,`revoked`])}),N.strictObject({type:N.literal(`reauthenticate`)}),N.strictObject({type:N.literal(`revoked`)}),N.strictObject({type:N.literal(`ping`)})])}}const Or=defineDeviceChannelFrames({action:Dr,result:Dr}),kr=Or.worker,Ar=Or.server;function parseDeviceChannelFrame(e,t){let n;try{n=JSON.parse(t)}catch{throw new DeviceChannelProtocolError(`Frame is not JSON`)}let r=e.safeParse(n);if(!r.success)throw new DeviceChannelProtocolError(`Frame does not match the channel protocol`);return r.data}function parseWorkerFrame(e){return parseDeviceChannelFrame(kr,e)}function parseServerFrame(e){return parseDeviceChannelFrame(Ar,e)}const jr=[`web`,`presentation`,`document`,`spreadsheet`,`image`,`code`,`other`],Mr=[`ephemeral`,`conversation`,`persistent`],Nr=[`source`,`preview`,`entrypoint`,`asset`],Pr=5;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 Fr=[`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 Ir=[`read`,`create`,`update`,`delete`,`manage`];function actionsToAccessLevel(e){return e.length===0?`none`:e.length===1&&e[0]===`read`?`read-only`:e.length===Ir.length&&Ir.every(t=>e.includes(t))?`full`:`custom`}function accessLevelToActions(e){switch(e){case`full`:return[...Ir];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 Lr=`Notetaker`,Rr={systemPrompt:null,meetingRecordingPolicy:`none`,meetingBotDisplayName:Lr},zr=6048e5,Br=36e5,Vr=2592e6,Hr=6e4,Ur=[`active`,`suspended`],Wr=[`architect`,`manual`,`auto`];function schemaGroupKey(e){return`${e.kind}:${e.id}`}function refuse(e,t){throw new D(t,[{path:[e],message:t}])}function parseSchemaGroupPresentation(e){let t=e??{},n={};if(t.label!==void 0){let e=t.label;if(e===null)n.label=null;else if(typeof e!=`string`)refuse(`label`,`Label must be a string`);else{let t=e.trim();t.length===0&&refuse(`label`,`Label must not be empty`),t.length>Nt.labelLength&&refuse(`label`,`Label is too long (max ${Nt.labelLength} characters)`),n.label=t}}if(t.icon!==void 0){let e=t.icon;if(e===null)n.icon=null;else{let t=O.safeParse(e);t.success||refuse(`icon`,`Invalid icon name`),n.icon=t.data}}return n}const Gr=[`square`,`landscape`,`portrait`],Kr=[`none`,`estimated`,`exact`];function parseCountMode(e){if(typeof e==`string`&&Kr.includes(e))return e;throw new D(`countMode must be one of: ${Kr.join(`, `)} (received: ${String(e)})`,[])}function parseOptionalCountMode(e){return e===void 0?void 0:parseCountMode(e)}const qr=1e4,Jr=[`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 Yr=[`B`,`KB`,`MB`,`GB`,`TB`];function formatByteSize(e){let{value:t,unitIndex:n}=computeByteMagnitude(e);return`${t} ${Yr[n]}`}const Xr={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 Zr=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(!Zr.includes(e.type))throw Error(`Property type "${e.type}" is not supported in .qualifyWith()`);t.push(e)}return{definitions:t}}const Qr=`__`;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 M(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}const $r=`—`;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?Cn(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(P(n.country));break;case`state`:n.state&&r.push(n.state),n.country&&r.push(P(n.country));break;case`city`:n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(P(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(P(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(P(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(M(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 ei=[`UPPER`,`LOWER`,`capitalize`,`trim`],ti=[`prefix`,`suffix`,`wrap`,`default`],ni=[...ei,...ti],I=N.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(!ni.includes(e))return!1}return!0},{message:`Invalid pipe name. Valid pipes: ${ni.join(`, `)}`});function validateLabelExpression(e){let t=I.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 ri=`(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=ri){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 ii=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function getSingleAttributeFromExpression(e){let t=e.trim().match(ii);return t?t[1]:null}function getEditableLabelAttribute(e,t){let n=getSingleAttributeFromExpression(e);if(n===null)return null;let r=t.find(e=>e.name===n);return!r||r.type!==`text`||x(r).authoring.readOnly?null:r}const ai=/\{\{\s*props\./;function applyRelationProps(e,t,n){if(!ai.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(M(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 oi=/\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(oi)?.[0];return t===void 0?``:[...t.toUpperCase()][0]??``}).filter(Boolean).slice(0,2).join(``);return i===``?t:i}const si=`__creatorRootActorId`;function getRecordCreatorPrincipalId(e){let t=e.metadata?.[si];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 ci=new Set([`id`,`name`,`label`,`type`,`required`,`system`,`unique`,`order`]),L={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`},li=[L.PEOPLE,L.WORKSPACE,L.ARCHITECT,L.FEATURE_FLAGS,L.FILES,L.VIEWS,L.FORMS,L.DOCUMENTS,L.AUDIT,L.API_KEYS,L.CONNECTORS,L.ENV_VARS,L.SESSION],ui={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`},di={OWNER:`owner`,MEMBER:`member`,AGENT_DEFAULT:`agent_default`,REFLEX_DEFAULT:`reflex_default`},fi={owner:`Owner`,member:`Member`,agent_default:`Agent Default`,reflex_default:`Reflex Default`},pi={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`},mi=[`read`,`create`,`update`,`delete`,`manage`],hi=[`read`,`create`,`update`,`delete`],gi=[`read`,`create`,`update`,`delete`],_i={owner:{system:[{target:`*`,actions:mi}],object:[{target:`*`,actions:mi}]},member:{system:[{target:`people`,actions:[`read`]},{target:`workspace`,actions:[`read`]},{target:`connectors`,actions:hi},{target:`files`,actions:gi},{target:`documents`,actions:gi}],object:[{target:`*`,actions:mi}]},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(di).includes(e)}const vi={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 D(`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??vi,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={...qn,...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 D(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new D(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility===`private`)throw new D(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return St(this.bp.triggers,e=>e.name,e=>new D(`Agent "${this.bp.name}": duplicate trigger name "${e}"`,[])),{...this.bp,visibility:this.bp.visibility??`workspace`,config:this.bp.config??vi,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};function agent(e){return new AgentBuilder(e)}const yi=`@stndrds/schema`;function createStandardSchemaProps(e){return{version:1,vendor:yi,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(mn(this.build()))}constructor(e,t,n){ft(t),Ct(n),this.attr={name:t,label:n,type:e,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(e){return Gt(e,`attribute "${this.attr.name}"`),this.attr.icon=e,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(e){let t=asMutableArray(e);return k(this.attr.name??`unknown`,t),this.attr.options=t,this.asPhantomState()}option(e){this.attr.options||(this.attr.options=[]);let t=[...this.attr.options,e];return k(this.attr.name??`unknown`,t),this.attr.options.push(e),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(e){let t=asMutableArray(e);return k(this.attr.name??`unknown`,t),this.attr.options=t,this.asPhantomState()}option(e){this.attr.options||(this.attr.options=[]);let t=[...this.attr.options,e];return k(this.attr.name??`unknown`,t),this.attr.options.push(e),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(e){let t=asMutableArray(e);return k(this.attr.name??`unknown`,t),this.attr.options=t,this.asPhantomState()}option(e){this.attr.options||(this.attr.options=[]);let t=[...this.attr.options,e];return k(this.attr.name??`unknown`,t),this.attr.options.push(e),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 n=t[0]?.object;if(!n)throw new D(`Bilateral relation requires one target object`,[{path:[`bilateral`,`object`],message:`Bilateral relation requires one target object`}]);if(e.object&&e.object!==n){let t=`Bilateral inverse object ${e.object} must match relation target ${n}`;throw new D(t,[{path:[`bilateral`,`object`],message:t}])}return this.attr.bilateral={...e,object:n},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`,n=this.attr.targetAttribute??`field`;throw new T(`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}.${n}").`,E.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=N.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 N.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=[...ni,`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(Fr);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: ${Fr.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 D(`[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:n,embeddingExpression:r}=e;if(!n)throw new T(`Object "${t}" must have a labelExpression. The labelExpression defines how records are displayed in lists and relations (e.g. "{{ name }}").`,E.VALIDATION_FAILED);let i=I.safeParse(n);if(!i.success){let e=i.error.issues[0]?.message??`Invalid labelExpression`;throw new T(`Invalid labelExpression for "${t}": ${e}`,E.VALIDATION_FAILED)}if(r!==void 0){let e=I.safeParse(r);if(!e.success){let n=e.error.issues[0]?.message??`Invalid embeddingExpression`;throw new T(`Invalid embeddingExpression for "${t}": ${n}`,E.VALIDATION_FAILED)}}}var ObjectBuilder=class{get"~standard"(){return createStandardSchemaProps(xn(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(e){let t=e.map(e=>`build`in e&&typeof e.build==`function`?e.build():e);St([...this.obj.attributes,...t],e=>e.name,e=>new w(`attribute`,e,`Object "${this.obj.name}": duplicate attribute name "${e}"`)),this.obj.attributes.push(...t)}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 D(`[ObjectBuilder] Missing required field: name`,[{path:[`name`],message:`name is required`}]);if(!this.obj.label)throw new D(`[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(e){e!==void 0&&pt(e)}};function object(e){if(qt(e.name))throw new Xe(e.name,`builder`);return new ObjectBuilder(e)}function validatePresetStructure(e,t,n){let fail=(t,n)=>{throw new D(t,[{path:[`documentLayout`,`presets`,e],message:n}])};n>5&&fail(`Preset structure exceeds max depth of 5`,`Preset structure too deep`);let r=new Set;for(let i of t){let t=i.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}"`),r.has(t)&&fail(`Folder preset sibling titles must be unique`,`Duplicate folder title: "${t}"`),r.add(t),i.children&&i.children.length>0&&validatePresetStructure(e,i.children,n+1)}}function cloneBuilderValue(e,t){try{return structuredClone(e)}catch{let e=`Builder configuration must contain cloneable data`;throw new D(e,[{path:t,message:e}])}}function requireBuilderName(e,t){if(typeof e!=`string`||e.trim().length===0)throw new D(`Name must not be blank`,[{path:t,message:`Name must not be blank`}])}function validateContentConfiguration(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new D(`Invalid content configuration`,[{path:t,message:`Expected content configuration`}]);for(let n of[`name`,`label`,`placement`])if(Object.hasOwn(e,n)){let e=`Independent content configuration cannot define ${n}`;throw new D(e,[{path:[...t,n],message:e}])}let n=C.safeParse({...e,name:`content`,placement:`main`});if(!n.success)throw D.fromZodErrors(n.error.issues.map(e=>({path:[...t,...e.path.map(String)],message:e.message})));n.data.type===`form`&&n.data.groups.forEach((e,n)=>requireBuilderName(e.name,[...t,`groups`,String(n),`name`]));let{name:r,label:i,placement:a,...o}=n.data;return cloneBuilderValue(o,t)}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,n){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 D(t,[{path:n,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 bi=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,n,r){let i=[`views`,`0`,`contents`,String(this.data.contents.length)],a,o;try{typeof n==`object`&&n&&`build`in n&&typeof n.build==`function`?(a=validateContentConfiguration(n.build(),i),o=n.extension):a=validateContentConfiguration(n,i)}catch(e){throw e instanceof D?new D(e.message,e.errors.map(e=>({...e,path:e.path[0]===`content`?[...i,...e.path.slice(1)]:e.path}))):e}let s={...a,name:e,label:t,placement:r},c=[...this.data.contents,s];return new ViewBuilder({...this.data,contents:c},[...this.extensions,o])}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 t=pe.safeParse(this.data);if(!t.success)throw D.fromZodErrors(t.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 bi({name:e,label:t,object:void 0,context:`record`,contents:[]})}function listView(e,t){return new bi({name:e,label:t,object:void 0,context:`collection`,contents:[]})}function relationProperty(e){return requireBuilderName(e,[`relationProperty`]),{relationProperty:e}}var R=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 D.fromZodErrors(t.error.issues.map(e=>({path:[`content`,`parameters`,...e.path.map(String)],message:e.message})))}return e}},xi=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 D?new D(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 xi(e,t,[])}function collection(){return new R({type:`collection`})}function form$1(...e){return new R({type:`form`,groups:e.map(e=>`build`in e?e.build():e)})}function activity(){return new R({type:`activity`})}function richtext$1(e){return new R({type:`richtext`,attribute:e})}function documents(){return new R({type:`documents`})}function forms(){return new R({type:`forms`})}function emails(...e){return new R({type:`emails`,emailAttributes:e})}function meetings(...e){return new R({type:`meetings`,emailAttributes:e})}function custom(e,t){if(typeof e!=`object`||!e||typeof e.name!=`string`)throw new D(`Expected registered extension declaration`,[{path:[`content`,`extension`],message:`Expected registered extension declaration`}]);let n=validateContentConfiguration({type:`custom`,extension:e.name,parameters:t},[`content`]);if(n.type!==`custom`)throw new D(`Expected custom content`,[]);let r=new R({...n,extension:e.name},e);return r.build(),r}const z={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 w(`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 Be(`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 Si=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,n,r={}){if(!this.repository)throw new T(`Cannot set override: no FeatureFlagsRepository configured. Add featureFlags to your DatabaseAdapter to enable runtime overrides.`,E.CONFIGURATION_REQUIRED);let i=this.registry.get(e);if(i&&!i.allowedLevels.includes(t)){let n=`Flag "${e}" does not allow ${t}-level overrides. Allowed levels: ${i.allowedLevels.join(`, `)}`;throw new D(n,[{path:[`level`],message:n}])}if(i?.system){let t=`Flag "${e}" is a system flag and cannot be overridden via API.`;throw new D(t,[{path:[`flagName`],message:t}])}await this.repository.setOverride({flagName:e,level:t,value:n,targetId:r.targetId,expiresAt:r.expiresAt,createdBy:r.createdBy})}async deleteOverride(e,t,n){if(!this.repository)throw new T(`Cannot delete override: no FeatureFlagsRepository configured.`,E.CONFIGURATION_REQUIRED);await this.repository.deleteOverride(e,t,n)}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 Ci=Symbol(`stndrds.native-object`);function markNativeDefinition(e){return Object.defineProperty(e,Ci,{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[Ci]===!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),n=new Set;for(let e of t){if(this.validate(e),n.has(e.name))throw new w(`object`,e.name,`[NativeObjectRegistry] Duplicate object name "${e.name}" within a single register() batch.`);n.add(e.name)}for(let e of t)this.objects.set(e.name,cloneObjectDefinition(e));return this}validate(e){if(!e.system){let t=`[NativeObjectRegistry] Cannot register object "${e.name}" (id: ${e.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 D(t,[])}if(qt(e.name)&&!isNativeDefinition(e))throw new Xe(e.name,`registry`);if(this.objects.has(e.name)){let t=this.objects.get(e.name),n=`[NativeObjectRegistry] Duplicate object name "${e.name}":\n - Existing: "${t?.label}" (id: ${t?.id})\n - New: "${e.label}" (id: ${e.id})\nPlease use unique names for each native object.`;throw new w(`object`,e.name,n)}}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 Be(`Native object`,e,E.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 wi=new NativeObjectRegistryClass,Ti=new WeakSet;function markSystemView(e){return Ti.add(e.definition),e}function isSystemViewDefinition(e){return typeof e==`object`&&!!e&&Ti.has(e)}const Ei=`## Overview
4
4
 
5
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.
6
6
 
@@ -31,14 +31,14 @@ Show at least one concrete example of the skill applied well.
31
31
 
32
32
  - Never …
33
33
  - Do not …
34
- `,gi=nativeObject({name:`skill`,label:`Skill`}).sealed().icon(`book-open`).order(2**53-1).pluralLabel(`Skills`).labelExpression(`{{ name }}`).embeddingExpression(`{{ name }}
34
+ `,Di=nativeObject({name:`skill`,label:`Skill`}).sealed().icon(`book-open`).order(2**53-1).pluralLabel(`Skills`).labelExpression(`{{ name }}`).embeddingExpression(`{{ name }}
35
35
  {{ description }}
36
- {{ content }}`).attribute(text({name:`name`,label:`Name`}).maxLength(kn).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(On).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(hi)).build(),_i=markSystemView(detailView(`skill-detail`,`Skill`).for(`skill`).default().tab(`content`,`Content`,L.richtext(`content`).titleAttribute(`name`)).tab(`files`,`Files`,L.documents()).tab(`activity`,`Activity`,L.activity()).aside(`details`,`Details`,L.form(group(`details`,`Details`).fields(`name`,`description`))).build()),vi=markSystemView(listView(`skill-list`,`Skills`).for(`skill`).default().tab(`workspace`,`Skills`,L.collection().object(`skill`).list().icon(`list`).visibility(`workspace`).columns(`name`,`description`).descriptionAttribute(`description`).displayAttributes(`createdBy`,`updatedAt`).sort(`name`)).tab(`mine`,`My skills`,L.collection().object(`skill`).list().icon(`lock`).visibility(`private`).columns(`name`,`description`).descriptionAttribute(`description`).displayAttributes(`createdBy`,`updatedAt`).sort(`name`)).build()),yi=nativeObject({name:`memory`,label:`Memory`}).sealed().icon(`database`).order(2**53-1).pluralLabel(`Memories`).labelExpression(`{{ name }}`).embeddingExpression(`{{ name }}
36
+ {{ content }}`).attribute(text({name:`name`,label:`Name`}).maxLength(On).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(Dn).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(Ei)).build(),Oi=markSystemView(detailView(`skill-detail`,`Skill`).for(`skill`).default().tab(`content`,`Content`,z.richtext(`content`).titleAttribute(`name`)).tab(`files`,`Files`,z.documents()).tab(`activity`,`Activity`,z.activity()).aside(`details`,`Details`,z.form(group(`details`,`Details`).fields(`name`,`description`))).build()),ki=markSystemView(listView(`skill-list`,`Skills`).for(`skill`).default().tab(`workspace`,`Skills`,z.collection().object(`skill`).list().icon(`list`).visibility(`workspace`).columns(`name`,`description`).descriptionAttribute(`description`).displayAttributes(`createdBy`,`updatedAt`).sort(`name`)).tab(`mine`,`My skills`,z.collection().object(`skill`).list().icon(`lock`).visibility(`private`).columns(`name`,`description`).descriptionAttribute(`description`).displayAttributes(`createdBy`,`updatedAt`).sort(`name`)).build()),Ai=nativeObject({name:`memory`,label:`Memory`}).sealed().icon(`database`).order(2**53-1).pluralLabel(`Memories`).labelExpression(`{{ name }}`).embeddingExpression(`{{ name }}
37
37
  {{ description }}
38
- {{ content }}`).migration(2,e=>e.changeType(`content`,`text`,`richtext`)).attribute(text({name:`name`,label:`Name`}).maxLength(Dn).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(En).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(),bi={combinator:`and`,rules:[{attribute:`invalidAt`,operator:`is_empty`,value:null},{attribute:`reviewState`,operator:`is_empty`,value:null}]},xi=markSystemView(detailView(`memory-detail`,`Memory`).for(`memory`).default().tab(`content`,`Content`,L.richtext(`content`).titleAttribute(`name`)).aside(`details`,`Details`,L.form(group(`details`,`Details`).fields(`description`,`kind`,`source`,`provenance`,`reviewState`,`reviewReason`,`validFrom`,`invalidAt`,`supersededBy`,`curatedAt`,`reviewAfter`,`subjects`,`links`))).build()),Si=markSystemView(listView(`memory-list`,`Memories`).for(`memory`).default().tab(`workspace`,`Memories`,L.collection().object(`memory`).list().icon(`list`).visibility(`workspace`).columns(`name`,`kind`,`description`,`createdAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`subjects`,`createdAt`).filter(bi).sort(`name`)).tab(`mine`,`My memories`,L.collection().object(`memory`).list().icon(`lock`).visibility(`private`).columns(`name`,`kind`,`description`,`createdAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`subjects`,`createdAt`).filter(bi).sort(`name`)).tab(`review`,`To review`,L.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`,L.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()),R=`drives`,Ci=nativeObject({name:R,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(),wi=markSystemView(detailView(`drive-detail`,`Drive`).for(R).default().tab(`documents`,`Documents`,L.documents()).aside(`details`,`Details`,L.form(group(`details`,`Details`).field(`description`))).build()),Ti=markSystemView(listView(`drive-list`,`Drives`).for(R).default().tab(`workspace`,`Shared`,L.collection().object(R).table().icon(`users`).visibility(`workspace`).columns(`name`,`description`,`updatedAt`).sort(`name`)).tab(`mine`,`My drives`,L.collection().object(R).table().icon(`lock`).visibility(`private`).columns(`name`,`description`,`updatedAt`).sort(`name`)).build()),Ei={name:`artifact_preview`,requiresRecord:!0,parameters:N.object({}).strict()},z=`artifact`,Di=nativeObject({name:z,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(),Oi=markSystemView(detailView(`artifact-detail`,`Artifact`).for(z).default().tab(`preview`,`Preview`,L.custom(Ei,{})).tab(`versions`,`Versions`,L.documents().allowUpload(!1).allowRemove(!1).hideAttachments(!0)).tab(`activity`,`Activity`,L.activity()).aside(`details`,`Details`,L.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()),ki=markSystemView(listView(`artifact-list`,`Artifacts`).for(z).default().tab(`mine`,`My artifacts`,L.collection().object(z).list().icon(`lock`).visibility(`private`).actions().columns(`name`,`kind`,`currentRevision`,`updatedAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`currentRevision`,`updatedAt`).sort(`updatedAt`,`desc`)).tab(`workspace`,`Workspace`,L.collection().object(z).list().icon(`list`).visibility(`workspace`).actions().columns(`name`,`kind`,`currentRevision`,`updatedAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`currentRevision`,`updatedAt`).sort(`updatedAt`,`desc`)).build()),B=`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`},Ai=`meeting-list`,ji=`calendar-sync`,Mi=`meeting-detail`,Ni=[V.title,V.startsAt,V.endsAt,V.status],Pi=nativeObject({name:B,label:`Meeting`}).sealed().hidden().metadata({platformOwned:{editable:[V.linkedRecords],source:ji}}).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(En).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(Tn).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(),ji={combinator:`and`,rules:[{attribute:`invalidAt`,operator:`is_empty`,value:null},{attribute:`reviewState`,operator:`is_empty`,value:null}]},Mi=markSystemView(detailView(`memory-detail`,`Memory`).for(`memory`).default().tab(`content`,`Content`,z.richtext(`content`).titleAttribute(`name`)).aside(`details`,`Details`,z.form(group(`details`,`Details`).fields(`description`,`kind`,`source`,`provenance`,`reviewState`,`reviewReason`,`validFrom`,`invalidAt`,`supersededBy`,`curatedAt`,`reviewAfter`,`subjects`,`links`))).build()),Ni=markSystemView(listView(`memory-list`,`Memories`).for(`memory`).default().tab(`workspace`,`Memories`,z.collection().object(`memory`).list().icon(`list`).visibility(`workspace`).columns(`name`,`kind`,`description`,`createdAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`subjects`,`createdAt`).filter(ji).sort(`name`)).tab(`mine`,`My memories`,z.collection().object(`memory`).list().icon(`lock`).visibility(`private`).columns(`name`,`kind`,`description`,`createdAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`subjects`,`createdAt`).filter(ji).sort(`name`)).tab(`review`,`To review`,z.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`,z.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()),B=`drives`,Pi=nativeObject({name:B,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(),Fi=markSystemView(detailView(`drive-detail`,`Drive`).for(B).default().tab(`documents`,`Documents`,z.documents()).aside(`details`,`Details`,z.form(group(`details`,`Details`).field(`description`))).build()),Ii=markSystemView(listView(`drive-list`,`Drives`).for(B).default().tab(`workspace`,`Shared`,z.collection().object(B).table().icon(`users`).visibility(`workspace`).columns(`name`,`description`,`updatedAt`).sort(`name`)).tab(`mine`,`My drives`,z.collection().object(B).table().icon(`lock`).visibility(`private`).columns(`name`,`description`,`updatedAt`).sort(`name`)).build()),Li={name:`artifact_preview`,requiresRecord:!0,parameters:N.object({}).strict()},V=`artifact`,Ri=nativeObject({name:V,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(),zi=markSystemView(detailView(`artifact-detail`,`Artifact`).for(V).default().tab(`preview`,`Preview`,z.custom(Li,{})).tab(`versions`,`Versions`,z.documents().allowUpload(!1).allowRemove(!1).hideAttachments(!0)).tab(`activity`,`Activity`,z.activity()).aside(`details`,`Details`,z.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()),Bi=markSystemView(listView(`artifact-list`,`Artifacts`).for(V).default().tab(`mine`,`My artifacts`,z.collection().object(V).list().icon(`lock`).visibility(`private`).actions().columns(`name`,`kind`,`currentRevision`,`updatedAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`currentRevision`,`updatedAt`).sort(`updatedAt`,`desc`)).tab(`workspace`,`Workspace`,z.collection().object(V).list().icon(`list`).visibility(`workspace`).actions().columns(`name`,`kind`,`currentRevision`,`updatedAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`currentRevision`,`updatedAt`).sort(`updatedAt`,`desc`)).build()),H=`meeting`,U={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`},Vi=`meeting-list`,Hi=`calendar-sync`,Ui=`meeting-detail`,Wi=[U.title,U.startsAt,U.endsAt,U.status],Gi=nativeObject({name:H,label:`Meeting`}).sealed().hidden().metadata({platformOwned:{editable:[U.linkedRecords],source:Hi}}).icon(`calendar`).pluralLabel(`Meetings`).labelExpression(`{{ title }}`).embeddingExpression(`{{ title }}
41
41
  {{ description }}
42
42
  {{ participants }}
43
- {{ summary }}`).attribute(text({name:V.title,label:`Title`}).required()).attribute(richtext({name:V.description,label:`Description`})).attribute(richtext({name:V.summary,label:`Summary`}).hidden()).attribute(richtext({name:V.transcript,label:`Transcript`}).hidden()).attribute(text({name:V.location,label:`Location`})).attribute(date({name:V.startsAt,label:`Starts at`}).includeTime()).attribute(date({name:V.endsAt,label:`Ends at`}).includeTime()).attribute(checkbox({name:V.isAllDay,label:`All day`})).attribute(select({name:V.status,label:`Status`}).options([{value:`confirmed`,label:`Confirmed`},{value:`tentative`,label:`Tentative`},{value:`cancelled`,label:`Cancelled`}])).attribute(text({name:V.organizerAddress,label:`Organizer address`}).email()).attribute(text({name:V.organizerName,label:`Organizer`})).attribute(text({name:V.conferenceProvider,label:`Conference provider`})).attribute(text({name:V.conferenceJoinUrl,label:`Join link`}).url()).attribute(text({name:V.htmlLink,label:`Open in calendar`}).url()).attribute(text({name:V.participants,label:`Participants`}).multiline()).attribute(text({name:V.providerEventId,label:`Provider event id`}).hidden()).attribute(text({name:V.icalUid,label:`iCal UID`}).hidden()).attribute(text({name:V.recurringEventId,label:`Recurring event id`}).hidden()).attribute(text({name:V.connectionId,label:`Connection id`})).attribute(select({name:V.recordingOverride,label:`Recording`}).options([{value:`force`,label:`Force`},{value:`skip`,label:`Skip`}]).hidden()).attribute(date({name:V.endedAnnouncedAt,label:`Ended announced at`}).includeTime().hidden()).attribute(relation({name:V.linkedRecords,label:`Linked records`}).toAny().many().qualifyWith(text({name:`source`,label:`Source`}).hidden())).build(),Fi=markSystemView(detailView(Mi,`Meeting`).for(B).default().tab(`description`,`Description`,L.richtext(V.description).titleAttribute(V.title)).tab(`summary`,`Summary`,L.richtext(V.summary)).tab(`transcript`,`Transcript`,L.richtext(V.transcript)).aside(`details`,`Details`,L.form(group(`details`,`Details`).fields(V.startsAt,V.endsAt,V.linkedRecords))).build()),Ii=markSystemView(listView(Ai,`Meetings`).for(B).default().tab(`workspace`,`Shared`,L.collection().object(B).table().icon(`users`).visibility(`workspace`).columns(...Ni).sort(V.startsAt,`desc`)).tab(`mine`,`My meetings`,L.collection().object(B).table().icon(`lock`).visibility(`private`).columns(...Ni).sort(V.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)),n=new Map,r=new Set;for(let{declaration:e}of t){let{object:t,name:i,context:a,default:o}=e.definition,s=n.get(t)??new Set;if((this.views.get(t)?.has(i)||s.has(i))&&this.throwDuplicate(t,i),s.add(i),n.set(t,s),!o)continue;let c=JSON.stringify([t,a]);if(this.getByObjectNameAndContext(t,a).some(e=>e.definition.default)||r.has(c))throw new C(`default view`,c,`[ViewRegistry] Duplicate default view for object "${t}" in context "${a}"`);r.add(c)}for(let e of t)this.commit(e);return this}prepare(e,t){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 E(e,[{path:[`views`,String(t)],message:e}])}let n=me.safeParse(e.definition);if(!n.success)throw E.fromZodErrors(n.error.issues.map(e=>({path:[`views`,String(t),`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 n=this.get(e,t);if(n)return n;let r=this.getByObjectName(e).map(({definition:e})=>`${e.name} (${e.context})`).join(`, `)||`(none)`;throw new Ve(`View`,`${e}:${t}`,void 0,`[ViewRegistry] View "${t}" not found for object "${e}".\nAvailable views: ${r}`)}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 n=viewIdentityKey(e,t);throw new C(`view`,n,`[ViewRegistry] Duplicate view: "${t}" for object "${e}"`)}};const Li=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 n=`Relation "${e.name}" requires one concrete collection target`;throw new E(n,[{path:t,message:n}])}return e.targets[0].object}function violationOf(e,t,n,r,i=`catalogue`){if(!(e instanceof w))throw e;let a=e instanceof E?e.errors[0]:void 0;return{key:JSON.stringify([t,n,e.code,e.message]),rule:i,contentName:n,path:a?.path??r,message:e.message,code:e.code,error:e}}const Ri=new Map(ue().map(e=>[e.name,e]));function reject$2(e,t){throw new E(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,n){let r=new Map;return e.forEach((e,i)=>{if(requireName(e.name,[...n,String(i),`name`]),r.has(e.name))throw new C(t,e.name);r.set(e.name,e)}),r}const zi=30;function capped(e,t){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} … and ${e.length-t} more`:n}function attributeInventory(e,t){return t.length===0?`Object "${e}" has no attributes yet.`:`Attributes of "${e}": ${capped(t,30)}`}function requireAttribute$1(e,t,n,r,i){if(requireName(t,n),!e)return;let a=e.attributes?.get(t)??Ri.get(t);if(!a){if(!e.attributes)return;let r=attributeInventory(e.name,[...e.attributes.keys()]);reject$2(n,`Unknown attribute "${e.name}.${t}". ${r}${i?.()??``}`)}return r&&a.type!==r&&reject$2(n,`Attribute "${e.name}.${t}" must have type ${r}`),a}function collectContentViewCatalogue(e){let t=e.mode??`published`,n=new Map;e.objects.forEach((e,t)=>{if(requireName(e.name,[`objects`,String(t),`name`]),n.has(e.name))throw new C(`object`,e.name);n.set(e.name,{name:e.name,attributes:indexUnique(e.attributes,`attribute`,[`objects`,String(t),`attributes`])})});let r=new Set;(e.reservedObjects??[]).forEach((e,i)=>{let a=[`reservedObjects`,String(i)];requireName(e,a),!n.has(e)&&(t!==`draft`&&reject$2(a,`Unresolved reserved object "${e}"`),r.add(e),n.set(e,{name:e}))});let i=indexUnique(e.extensions??[],`extension`,[`extensions`]);function resolveObject(e,t){requireName(e,t);let r=n.get(e);return r||reject$2(t,`Unknown object "${e}"`),r}function inverseAddresses(e){let t=[];for(let[r,i]of n)if(r!==e)for(let n of i.attributes?.values()??[])n.type===`relation`&&relationAcceptsObject(n,e)&&t.push(`relatedFrom("${r}", "${n.name}")`);return t.sort().slice(0,3)}let a=t===`draft`?ce({asideRule:`tolerate`}):oe({asideRule:`tolerate`}),o=new Map,s=new Map,c=[],l=[];function parseView(e,t){let n=a.safeParse(e);if(!n.success)throw new E(`Invalid content view`,n.error.issues.map(e=>({path:[...t,...e.path.map(String)],message:e.message,code:e.code})));let r=n.data;requireName(r.name,[...t,`name`]);let i=o.get(r.object)??new Set;if(i.has(r.name))throw new C(`view`,`${r.object}.${r.name}`);if(i.add(r.name),o.set(r.object,i),r.default){let e=s.get(r.object)??new Set;if(e.has(r.context))throw new C(`default view`,`${r.object}.${r.context}`);e.add(r.context),s.set(r.object,e)}return r}return e.views.forEach((e,t)=>{let n=[`views`,String(t)],r=e,a=`${String(r?.object??`?`)}.${String(r?.name??t)}`,o,s;try{o=parseView(e,n),s=resolveObject(o.object,[...n,`object`])}catch(e){c.push(violationOf(e,a,null,n));return}for(let e of Te(o)){let t=new E(e.message,[{path:[...n,...e.path.map(String)],message:e.message}]);c.push(violationOf(t,a,e.contentName,n,`aside`))}o.contents.forEach((e,t)=>{let r=[...n,`contents`,String(t)];try{requireName(e.name,[...r,`name`]),validateContent(e,r,s,o.context,i,resolveObject,inverseAddresses)}catch(t){c.push(violationOf(t,a,e.name,r))}}),l.push(o)}),{views:l,unresolvedObjects:[...r].sort(),violations:c}}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,n,r,i,a,o){function requireRecord(){requireRecordContentContext(e.name,r,t)}if(e.type===`custom`){let n=i.get(e.extension);n||reject$2([...t,`extension`],`Unknown extension "${e.extension}"`),n.requiresRecord&&requireRecord();let r=n.parameters.safeParse(structuredClone(e.parameters??{}));if(!r.success)throw new E(`Invalid extension parameters`,r.error.issues.map(e=>({path:[...t,`parameters`,...e.path.map(String)],message:e.message,code:e.code})));return}if(e.type===`collection`){let r=collectionSourceAddress(e.source),i,s;if(r.kind===`object`)i=a(r.object,[...t,`source`,`object`]);else if(r.kind===`related`){requireRecord();let e=[...t,`source`,`relation`],hint=()=>{if(!n)return``;let e=o(n.name);return e.length===0?``:`. Records pointing at "${n.name}" are addressed from the other side: ${e.join(`, `)}`},c=requireAttribute$1(n,r.relation,e,`relation`,hint);c?.type===`relation`&&(s=c,i=a(requireSingleRelationTarget(c,e),e))}else{requireRecord(),i=a(r.object,[...t,`source`,`object`]);let o=[...t,`source`,`relation`],s=requireAttribute$1(i,r.relation,o,`relation`);if(s?.type===`relation`&&n&&!relationAcceptsObject(s,n.name)){let e=s.targets.map(e=>`"${e.object}"`).join(`, `);reject$2(o,`Relation "${r.object}.${r.relation}" targets ${e}, not "${n.name}"`)}e.filters?.combinator===`or`&&reject$2([...t,`filters`,`combinator`],`Collection "${e.name}" addresses "${r.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 a=[...r,`relationProperty`];s||reject$2(a,`Relation property columns require a relation source`),s.properties?.definitions.some(t=>t.name===e.relationProperty)||reject$2(a,`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,r)=>{let i=[...t,`groups`,String(r)];requireName(e.name,[...i,`name`]),e.fields.forEach((e,t)=>requireAttribute$1(n,e.attribute,[...i,`fields`,String(t),`attribute`]))});break;case`richtext`:requireAttribute$1(n,e.attribute,[...t,`attribute`],`richtext`),e.titleAttribute!==void 0&&requireAttribute$1(n,e.titleAttribute,[...t,`titleAttribute`],`text`);break;case`emails`:case`meetings`:e.emailAttributes.forEach((e,r)=>requireAttribute$1(n,e,[...t,`emailAttributes`,String(r)],`text`));break;case`documents`:e.relations?.forEach((e,r)=>requireAttribute$1(n,e,[...t,`relations`,String(r)],`relation`));break;case`forms`:e.objectName!==void 0&&a(e.objectName,[...t,`objectName`]);break;case`activity`:break;default:reject$2(t,`Unknown content type: ${String(e)}`)}}const Bi=[Object.freeze(Ei)];var ContentExtensionRegistry=class{constructor(){this.extensions=new Map,this.seed()}register(e){let t=Array.isArray(e)?e:[e],n=new Set;t.forEach((e,t)=>{if(this.prepare(e,t),n.has(e.name))throw new C(`content extension`,e.name);n.add(e.name)});for(let e of t)this.extensions.set(e.name,e);return this}prepare(e,t){let n=[`extensions`,String(t)],reject=e=>{throw new E(e,[{path:n,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 C(`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 Bi)this.extensions.set(e.name,e)}};const Vi=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 C(`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 Hi=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}}const Ui=204800,Wi=256;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 Gi=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}),Ki=[`membership-unknown`,`sort-unknown`,`permissions-changed`],qi=[`permission-revoked`,`workspace-left`,`object-deleted`],Ji=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],Yi=[`type`,`objectId`,`recordId`,`recordVersion`],Xi=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],Zi=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],Qi=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&Gi.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,An)}function isNotificationPriority(e){return isOneOf(e,jn)}function isNotificationSensitivity(e){return isOneOf(e,Mn)}function isNotificationInboxState(e){return isOneOf(e,Nn)}function isNotificationWorkState(e){return isOneOf(e,Pn)}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,Yi)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$1(e)&&hasOnlyKeys(e,Zi)&&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,Xi)&&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,Ki)}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=>Ji.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,Qi)&&hasNonEmptyString(e,`targetActorId`)&&hasVersion(e,`archivedCount`)&&hasVersion(e,`version`)&&hasIsoDateString(e,`updatedAt`)}const $i=[`armed`,`disarmed`],ea=[`authoring`,`compiling`,`replaying`,`promoted`,`failed`],ta=[`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,$i)&&hasIsoDateString(e,`updatedAt`)}function isReflexRunCompletedPayload(e){return e.type===`reflex.run.completed`&&hasNonEmptyString(e,`reflexId`)&&hasNonEmptyString(e,`runId`)&&isOneOf(e.served,ta)&&hasVersion(e,`version`)&&hasVersion(e,`wallMs`)&&hasIsoDateString(e,`completedAt`)}function isReflexAuthoringProgressPayload(e){return e.type===`reflex.authoring.progress`&&hasNonEmptyString(e,`reflexId`)&&isOneOf(e.status,ea)&&hasIsoDateString(e,`updatedAt`)}const na=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,na)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const ra=[`ok`,`low`,`exhausted`,`paused`],ia=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,ra)&&isOneOf(e.mode,ia)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,qi)}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 aa=[`if`,`concat`,`sum`,`avg`,`count`,`min`,`max`,`earliest`,`latest`,`unique`,`first`,`percent_empty`,`percent_not_empty`,`count_empty`,`count_not_empty`,`count_unique`],oa={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(oa,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(e){try{return k(e)}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=oa[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}"`);if(e.targetAttribute===void 0)throw new ComputedFormulaCompileError(`Rollup "${e.function}" on object "${t.objectName}" needs a targetAttribute`);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}=oa[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(j).length;case`count_not_empty`:return collectionItems(t[0]).filter(e=>!j(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=>j(e)===t).length/n.length}function uniqueNonEmpty(e){let t=new Set,n=[];for(let r of e){if(j(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(e,t){return evaluateAst(k(e),t)}function evaluateComputedFormulaWithResult(e,t,n,r){try{let i=evaluateAst(k(e),t);return{value:n?formatComputedResult(i,n,r):i}}catch(e){return{value:null,error:e instanceof Error?e.message:String(e)}}}const sa=[{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=>j(e)||Array.isArray(e)&&e.length===0,toStr=e=>e==null?``:String(e),toNum=e=>{if(j(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)}),ca={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,t)=>{let n=toDate(e),r=ae(t);return n&&r?n.getTime()>=r.startMs&&n.getTime()<r.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}),la=[...Object.entries(xe).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,...la])}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,t,n){let r=n.get(e.attribute);if(!r)return!1;if(e.property&&r.type===`location`){if(!(u(e.property)&&re(e.operator)))return!1;let n=ca[e.operator];if(!n)return!1;let i=t[e.attribute],a=typeof i==`object`&&i?i[e.property]:void 0;return evaluateNormalizedComparands(n,`text`,e.operator,a,e.value,r)}if(e.property){let n=resolvePropertyDefinitions(r).find(t=>t.name===e.property);if(!n)return!1;let i=a(e.operator),o=ca[i];if(!o?.appliesTo.includes(n.type))return!1;let s=t[e.attribute],c=(Array.isArray(s)?s:s==null?[]:[s]).some(t=>{if(typeof t!=`object`||!t)return!1;let r=t.props;return typeof r!=`object`||!r?!1:evaluateNormalizedComparands(o,n.type,i,r[e.property],e.value,n)});return(e.quantifier??Oe(e.operator))===`none`?!c:c}let i=ca[e.operator];if(!i||!i.appliesTo.includes(r.type))return!1;let o=t[e.attribute],s=r.type===`relation`||r.type===`document`||r.type===`user`?normalizeReferenceIds(o):o;return evaluateNormalizedComparands(i,r.type,e.operator,s,e.value,r)}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 Tn(t.phoneNumber);let n=typeof t.countryCode==`string`?t.countryCode:r;return`${n}:${Cn(t.phoneNumber,n)}`};return[normalizeOne(e),normalizeOne(t)]}function normalizeComparableValue(e,t){return e===`currency`?h(t):e===`date`?isDateRangeValue(t)?dateValueStart(t):t instanceof Date?Number.isNaN(t.getTime())?null:t.toISOString():t:t}function normalizeReferenceIds(e){let normalizeOne=e=>typeof e!=`object`||!e?e:e.id;return Array.isArray(e)?e.map(normalizeOne):normalizeOne(e)}const ua=`today`;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,t,n){if(e.combinator===`or`&&e.rules.length>1)return{};let r=new Map(t.map(e=>[e.name,e])),i={};for(let t of e.rules){if(t.property!==void 0||Object.hasOwn(i,t.attribute))continue;let e=r.get(t.attribute);if(!e)continue;let a=extractDeterministicValue(t,n);a!==void 0&&(i[t.attribute]=x(e).storage.cardinality===`many`?[a]:a)}return i}function extractDeterministicValue(e,t){if(e.operator===`is`)return he(e.value)?resolveDynamicValue(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 he(n)?resolveDynamicValue(n,t):n}}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 da={status:`connector_status`,error:`connector_error`,provider:`connector_provider`};let fa=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const pa=[`threads`,`messages`];function isMailboxListMode(e){return pa.includes(e)}const ma=[`reply`,`reply_all`];function isReplyMode(e){return ma.includes(e)}const ha=2e5,ga=998,_a=[`force`,`skip`],va=[`none`,`all`,`external_only`],ya=`x-fake-signature`,ba={override:null,status:`none`,failureReason:null,botId:null},xa=/^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&&!xa.test(t)?t:e.firstUserText?buildAgentFallbackTitle(e.firstUserText):e.emptyLabel}const Sa=/^[a-z0-9][a-z0-9-]{0,62}$/;function assertSchemaSourceId(e){if(!Sa.test(e))throw new E(`Invalid schema source id "${e}": expected a lowercase slug matching ${Sa}`,[])}function hasDestructiveEntries(e){let{attributeRemovals:t,objectRemovals:n,renames:r}=e.destructive;return t.length>0||n.length>0||r.length>0}const H={objectAdditions:20,totalMutations:500,serializedBytes:524288};function errorMessage(e){return e instanceof Error?e.message:String(e)}const Ca=N.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.'),wa=N.string().min(1).superRefine((e,t)=>{try{pt(e)}catch(e){t.addIssue({code:N.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).`),Ta=N.string().min(1).superRefine((e,t)=>{Jt(e)&&t.addIssue({code:N.ZodIssueCode.custom,message:`"${e}" is a reserved object name (${xt.join(`, `)}) and cannot be used for a new object.`});try{mt(e)}catch(e){t.addIssue({code:N.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(e){return e.superRefine((e,t)=>{try{let n=Ot(e.type,{...e.config??{},description:e.description}),r=Object.keys(e.config??{}).filter(e=>!Object.hasOwn(n,e));r.length>0&&t.addIssue({code:`unrecognized_keys`,keys:r,path:[`config`],message:`Unrecognized attribute config key${r.length===1?``:`s`}: ${r.join(`, `)}`})}catch(n){if(n instanceof E){for(let r of n.errors)t.addIssue({code:N.ZodIssueCode.custom,path:[`config`,...r.path.map(e=>/^\d+$/.test(e)?Number(e):e)],message:`Config for type "${e.type}" is invalid or incomplete: ${r.message}`});return}t.addIssue({code:N.ZodIssueCode.custom,path:[`config`],message:`Config for type "${e.type}" is invalid or incomplete: ${errorMessage(n)}`})}})}const Ea=N.object({objectName:N.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:wa,label:N.string().min(1).max(128).describe(`Human-readable display label shown in the UI. 1-128 characters, cannot be empty.`),type:Ca,config:N.record(N.string(),N.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:N.boolean().optional().describe(`Whether the attribute must have a value on every record. Defaults to false (optional).`),description:N.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),Da=withConfigCheck(Ea),Oa=withConfigCheck(Ea.omit({objectName:!0})),ka=N.object({name:Ta,label:N.string().min(1).describe(`Human-readable singular display label (e.g. "Devis").`),pluralLabel:N.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:N.string().optional().describe(`Help text describing what this object represents.`),icon:D.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:P.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:N.array(Oa).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(),Aa=N.object({attributeRemovals:N.array(N.object({objectName:N.string().min(1).describe(`Object the attribute is removed from.`),attributeName:N.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:N.array(N.object({objectName:N.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:N.array(N.object({objectName:N.string().min(1).describe(`Object the renamed attribute belongs to.`),from:N.string().min(1).describe(`Current attribute name. Must already exist and not be a system attribute.`),to:wa.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:[]}),ja=N.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.`),Ma=N.object({objects:N.array(ka).default([]),attributes:N.array(Da).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>H.objectAdditions&&t.addIssue({code:`too_big`,origin:`array`,maximum:H.objectAdditions,inclusive:!0,path:[`additive`,`objects`,H.objectAdditions],message:`A schema plan can add at most ${H.objectAdditions} objects`});let n=mutationPaths(e);n.length>H.totalMutations&&t.addIssue({code:`too_big`,origin:`array`,maximum:H.totalMutations,inclusive:!0,path:n[H.totalMutations],message:`A schema plan can contain at most ${H.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}),N.NEVER;let r=new TextEncoder().encode(A(e)).byteLength;return r>H.serializedBytes?(t.addIssue({code:`too_big`,origin:`string`,maximum:H.serializedBytes,inclusive:!0,path:[],message:`A schema plan can serialize to at most ${H.serializedBytes} UTF-8 bytes; received ${r}`}),N.NEVER):e}const Na=N.object({schemaPlanVersion:N.literal(2).describe(`Required proposal contract version.`),summary:ja,additive:Ma,destructive:Aa}).strict().superRefine(addPlanLimitIssues),Pa=Object.assign(N.preprocess(boundSerializedPlanInput,Na),{shape:Na.shape}),Fa=N.object({schemaPlanVersion:N.literal(2),summary:ja,additive:Ma,destructive:Aa}).strict().superRefine(addPlanLimitIssues),Ia=N.preprocess(boundSerializedPlanInput,Fa);function reject$1(e,t){throw new E(t,[{path:e,message:t}])}function exhaustive(e){throw new E(`Unsupported schema reference variant ${String(e)}`,[])}function collectSchemaReferences(e){let t=new Map(e.objects.map(e=>[e.name,e])),n=[];function visitor(e,r,i){function add(a,o,s){(a.kind===`object`?t.has(a.object):a.kind!==`attribute`||t.get(a.object)?.attributes.some(e=>e.name===a.attribute))||reject$1([...r,...s],`Unknown schema reference ${JSON.stringify(a)}`),n.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,n,i,a,o){attribute(e,n,i,a);let s=t.get(e)?.attributes.find(e=>e.name===n);return s?.type!==`relation`&&reject$1([...r,...a],`Invalid schema reference path "${o}"`),(s.targets.length!==1||s.targets[0].object===`*`)&&reject$1([...r,...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}}e.objects.forEach((e,t)=>{let n=[`objects`,String(t)],r=visitor({kind:`object`,object:e.name},n);for(let t of[`labelExpression`,`embeddingExpression`]){let n=e[t];if(n)for(let i of extractAttributeNames(n))r.attributePath(e.name,i.split(`.`),`business`,[t])}e.attributes.forEach((t,r)=>{let i=[...n,`attributes`,String(r)],a=visitor({kind:`attribute`,object:e.name,attribute:t.name},i);switch(t.type){case`relation`:t.targets.forEach((e,t)=>{if(e.object!==`*`&&a.add({kind:`object`,object:e.object},`structural`,[`targets`,String(t),`object`]),e.displayTemplate)for(let n of extractAttributeNames(e.displayTemplate))a.attributePath(e.object,n.split(`.`),`business`,[`targets`,String(t),`displayTemplate`]);for(let n of Object.keys(e.filter??{}))a.attribute(e.object,n,`business`,[`targets`,String(t),`filter`,n])});break;case`formula`:{let n;try{n=k(t.expression)}catch(e){reject$1([...i,`expression`],e instanceof Error?e.message:String(e))}a.formula(e.name,n,[`expression`]),visitOptions(t,a);break}case`rollup`:{let n=t.relationPath??t.relationAttribute,r=e.name;for(let e of n.split(`.`))r=a.traverse(r,e,`computed`,[t.relationPath===void 0?`relationAttribute`:`relationPath`],n);t.targetAttribute!==void 0&&a.attributePath(r,t.targetAttribute.split(`.`),`computed`,[`targetAttribute`]),visitOptions(t,a);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(t)}})});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,n,r){visitor({kind:`view`,object:e.object,view:e.name},n,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},[...n,`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=t.get(e.object),u=r.kind!==`related`||!l?void 0:findRelationAttribute(l,r.relation),d=[`columns`,String(c),`relationProperty`];u||reject$1([...n,`contents`,String(a),...d],`Relation property columns require a relation source`),u.properties?.definitions.some(e=>e.name===i.relationProperty)||reject$1([...n,`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 e.views.forEach((e,t)=>viewReferences(e,[`views`,String(t)])),e.retainedViews?.forEach(({definition:e,layer:t},n)=>viewReferences(e,[`retainedViews`,String(n),`definition`],t)),n}const La=/^[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,n){throw new E(n,[{path:[...e.split(`.`),t],message:n}])}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);(!La.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,r,i){e.bilateral?.cardinality&&e.bilateral.cardinality!==t.cardinality&&reject(r,`cardinality`,`${n} declares ${r} as ${e.bilateral.cardinality}, but ${r} declares ${t.cardinality}`),t.bilateral?.cardinality&&t.bilateral.cardinality!==e.cardinality&&reject(n,`cardinality`,`${r} declares ${n} as ${t.bilateral.cardinality}, but ${n} declares ${e.cardinality}`),e.bilateral?.label&&e.bilateral.label!==t.label&&reject(r,`label`,`${n} declares a different label for ${r}`),t.bilateral?.label&&t.bilateral.label!==e.label&&reject(n,`label`,`${r} declares a different label for ${n}`),e.properties&&t.properties&&!un(e.properties,t.properties)&&!i&&reject(r,`properties`,`${n} and ${r} declare different qualified properties`),e.bilateral?.storageOwner===t.bilateral?.storageOwner&&e.bilateral?.storageOwner!==void 0&&reject(r,`storageOwner`,`${n} and ${r} 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,r,i,a){a.has(n)&&a.has(r)&&!un(e.properties,t.properties)&&reject(r,`properties`,`${n} and ${r} edit different qualified properties`);let o=a.has(n)||i.has(n)&&!i.has(r)&&!a.has(r),s=a.has(r)||i.has(r)&&!i.has(n)&&!a.has(n),c=o?e.properties:s?t.properties:e.properties??t.properties;c?(e.properties=structuredClone(c),t.properties=structuredClone(c)):(delete e.properties,delete t.properties)}function reconcileRelationAttributes(e){let t=structuredClone(e.objects),n=new Map;for(let e of t){if(n.has(e.name))throw new C(`object`,e.name);n.set(e.name,e);let t=new Set;for(let n of e.attributes){if(t.has(n.name))throw new C(`attribute`,n.name);t.add(n.name),stripUntrustedPairMetadata(n)}}let r=remapExistingPairs(e.existingPairs??[],e.addressRenames??[]),i=validateExistingPairs(r),a=new Set(r.flatMap(e=>e.generatedAddresses)),o=new Set(e.propertyEditAddresses??[]),s=new Set(e.explicitAddresses??t.flatMap(e=>e.attributes.filter(t=>!a.has(`${e.name}.${t.name}`)).map(t=>`${e.name}.${t.name}`))),c=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)),l=new Map,u=new Map;for(let{object:t,attribute:a,address:d}of c){let c=a.bilateral?.object;(!c||c===`*`||a.targets.length!==1||a.targets[0]?.object!==c)&&reject(d,`targets`,`Bilateral target of ${d} must be one concrete object`);let f=n.get(c);f||reject(d,`bilateral`,`Unknown inverse object ${c} for ${d}`);let p=`${c}.${a.bilateral?.attribute}`,m=d===p;m&&a.cardinality!==`many`&&reject(d,`cardinality`,`Symmetric self relation ${d} must be many`),m&&a.bilateral?.cardinality&&a.bilateral.cardinality!==a.cardinality&&reject(d,`bilateral`,`Symmetric self relation ${d} needs matching cardinality`);let h=pairedAddresses(d,p),g=pairKey(h);if(l.has(g))continue;let _=f.attributes.find(e=>e.name===a.bilateral?.attribute);if(_&&!isReciprocal(_,t.name,a.name))throw new C(`attribute`,p);let ee=!(_&&s.has(p));_||(_=generateInverse(a,t.name,f.attributes.length),f.attributes.push(_));let v=_;!m&&s.has(d)&&s.has(p)&&checkExplicitDeclarations(a,v,d,p,o.has(d)!==o.has(p));let y=i.get(g),b=y?.id??e.nextPairId(h),x=r.find(e=>e.id===b&&pairKey(e.addresses)!==g);(!La.test(b)||x||u.has(b)&&u.get(b)!==g)&&reject(d,`pair`,`Invalid or duplicate pair identity for ${d} and ${p}`),u.set(b,g);let te=m?d:chooseOwner(a,v,d,p,y,ee);a.bilateral&&v.bilateral||reject(d,`bilateral`,`Missing reciprocal configuration for ${d} and ${p}`),a.bilateral={...a.bilateral,cardinality:v.cardinality,label:v.label,storageOwner:te===d},v.bilateral={...v.bilateral,cardinality:a.cardinality,label:a.label,storageOwner:te===p},reconcileProperties(a,v,d,p,s,o),a.metadata={...a.metadata,relationPairId:b},v.metadata={...v.metadata,relationPairId:b},l.set(g,{id:b,addresses:h,ownerAddress:te,generatedAddresses:h.filter(e=>!s.has(e)),...m?{symmetric:!0}:{}})}return{objects:t,pairs:[...l.values()].sort((e,t)=>e.addresses[0].localeCompare(t.addresses[0]))}}const U=N.number().finite().nonnegative(),Ra=N.enum(Xn),za=N.enum(Zn),Ba=N.enum(Qn),Va=N.object({provider:Ra,model:N.string().min(1)}).strict(),Ha=N.object({speed:za.optional(),reasoning:Ba.optional()}).strict(),Ua=N.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),Wa=N.object({model:Va.optional(),speed:za.optional(),reasoning:Ba.optional(),imageModel:Ua.optional()}).strict(),Ga=Wa.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`}),Ka=N.object({model:Va.nullable().optional(),speed:za.nullable().optional(),reasoning:Ba.nullable().optional(),imageModel:Ua.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`}),qa=N.object({label:N.string(),denied:N.boolean().optional(),deletion:N.object({target:N.string().optional(),count:U.optional(),restorableDays:U.optional()}).strict().optional(),counts:N.record(N.string(),U).optional(),warnings:N.array(N.string()).optional()}).strict(),Ja=N.union([N.object({type:N.literal(`text`),text:N.string()}).strict(),N.object({type:N.literal(`reasoning`),text:N.string()}).strict(),N.object({type:N.literal(`system`),code:N.enum(tr)}).strict(),N.object({type:N.literal(`error`),error:N.string(),errorClass:N.string().optional()}).strict(),N.object({type:N.literal(`tool`),toolCallId:N.string(),name:N.string(),args:N.record(N.string(),N.unknown()),result:N.unknown().optional(),error:N.string().optional(),errorCode:N.enum([`output_limit_reached`,`interrupted`,T.INVALID_TOOL_INPUT]).optional(),state:N.enum([`streaming`,`running`,`completed`,`error`,`pending`,`approval-requested`,`approval-responded`,`approval-dispatched`]),durationMs:U.optional(),approvalId:N.string().optional(),approvalImpact:qa.optional(),approved:N.boolean().optional(),approvalReason:N.string().optional(),approvalRelaxableByAuto:N.boolean().optional()}).strict(),N.object({type:N.literal(`file`),fileId:N.string(),name:N.string(),mimeType:N.string()}).strict(),N.object({type:N.literal(`compaction`),state:N.literal(`in-progress`),reason:N.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:U.optional(),reportedTokens:U.optional()}).strict(),N.object({type:N.literal(`compaction`),state:N.literal(`completed`),tokensBefore:U,tokensAfter:U,tokensSaved:U,strategy:N.enum([`no-op`,`summary`,`truncation`]),durationMs:U,summary:N.string().optional()}).strict(),N.object({type:N.literal(`compaction`),state:N.literal(`failed`),reason:N.string(),durationMs:U.optional()}).strict()]),Ya=N.object({id:N.string(),name:N.string(),mimeType:N.string(),size:U}).strict(),Xa=N.object({id:N.string(),type:N.string().transform(e=>e),entityId:N.string(),label:N.string(),objectName:N.string().optional(),startIndex:U,endIndex:U}).strict(),Za=N.object({provider:Ra,model:N.string(),maxTokens:U.optional(),contextWindow:U.optional()}).strict(),Qa=N.union([N.date(),N.string().datetime({offset:!0}).transform(e=>new Date(e))]),$a=N.object({id:N.string(),sessionId:N.string(),tenantId:N.string().optional(),runId:N.string().optional(),role:N.enum([`user`,`assistant`,`system`,`tool`]),parts:N.array(Ja),attachments:N.array(Ya).optional(),mentions:N.array(Xa).optional(),model:Za.optional(),tokenUsage:N.object({input:U,output:U}).strict().optional(),metadata:N.record(N.string(),N.unknown()).optional(),createdAt:Qa}).strict(),eo=N.object({id:N.string(),description:N.string(),status:N.enum([`pending`,`in_progress`,`completed`,`blocked`]),result:N.string().optional(),updatedAt:U.optional()}).strict(),to=N.object({id:N.string(),sessionId:N.string(),status:N.enum([`active`,`completed`,`abandoned`]),todos:N.array(eo),version:U,createdAt:N.string(),updatedAt:N.string(),completedAt:N.string().optional()}).strict(),no={"session-named":N.object({name:N.string()}).strict(),"compaction-start":N.object({reason:N.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:U.optional(),reportedTokens:U.optional()}).strict(),"compaction-end":N.object({tokensBefore:U,tokensAfter:U,tokensSaved:U,strategy:N.enum([`no-op`,`summary`,`truncation`]),durationMs:U,summary:N.string().optional()}).strict(),"compaction-failed":N.object({reason:N.string()}).strict(),usage:N.object({messageId:N.string().min(1).optional(),inputTokens:U,outputTokens:U,totalTokens:U,cacheReadTokens:U.optional(),cacheCreationTokens:U.optional(),contextWindow:U,residentTokens:U,utilization:N.number().finite().min(0).max(1),costUsd:U.optional()}).strict(),"message-persisted":N.object({message:$a}).strict(),"message-updated":N.object({message:$a}).strict(),"todo-plan-update":N.object({plan:to}).strict(),"approval-context":N.object({approvalId:N.string(),toolCallId:N.string(),impact:qa.optional(),relaxableByAuto:N.boolean().optional()}).strict(),"session-state":N.object({state:N.object({phase:N.enum([`queued`,`running`,`parked`,`terminal`]),parkedOn:N.enum([`human`,`agents`]).optional(),humanRequestIds:N.array(N.string()).optional(),outcome:N.enum([`completed`,`failed`,`cancelled`,`timeout`,`expired`]).optional()}).strict(),version:N.number().int().positive(),updatedAt:N.string().datetime({offset:!0})}).strict()};function isAgentUIDataName(e){return e in no}function agentUIValidationError(e){return new E(`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 E(`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 E(`Invalid agent UI message chunk`,[{path:[`type`],message:`Expected agent data chunk type`,code:`invalid_value`}]);let n=t.slice(5);if(!isAgentUIDataName(n))throw new E(`Invalid agent UI message chunk`,[{path:[`type`],message:`Unknown agent UI data type: ${n}`,code:`invalid_value`}]);let r=N.object({type:N.literal(`data-${n}`),id:N.string().optional(),data:no[n],transient:N.boolean().optional()}).strict().safeParse(e);if(!r.success)throw agentUIValidationError(r.error.issues);return r.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 W={kind:`target-missing`};var DraftRefusalError=class extends E{constructor(e,t,n=[]){super(e,n),this.refusal=t}};const ro=[`pluralLabel`,`description`,`labelExpression`,`embeddingExpression`];function draftObjectSettings(e){return Object.fromEntries(ro.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{...e.config,id:e.id,objectId:e.objectId,name:e.name,label:e.label,type:e.attributeType}}function toDraftableAttribute(e,t){let{id:n,objectId:r,name:i,label:a,type:o,...s}=e;return{id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:s}}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 io={id:N.string().min(1).describe(`Your id, echoed back`),note:N.string().trim().min(1).max(160).optional().describe(`One first-person sentence, in the person's language: what you do and why, ≤160 chars`)},G={...io,objectName:N.string().min(1).describe(`Object`),viewName:N.string().min(1).describe(`View API name`)},K={...G,contentName:N.string().min(1).describe(`Content API name`)},ao=N.union([N.object({before:N.string().min(1).describe(`Place immediately before this content name`)}).strict(),N.object({after:N.string().min(1).describe(`Place immediately after this content name`)}).strict(),N.object({end:N.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,n){let r=[{path:e,message:t}];throw n?new DraftRefusalError(t,n,r):new E(t,r)}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`,{kind:`view-missing`,objectName:t.objectName,viewNames:e.views.filter(e=>e.object===t.objectName).map(e=>e.name)}),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`,W),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`,W),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 oo=N.unknown().transform((e,t)=>{let n=S.safeParse(typeof e==`object`&&e?{...e,name:`candidate`}:e);if(!n.success){for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message});return N.NEVER}let r=typeof e==`object`&&e&&`name`in e?e.name:void 0;return{...n.data,name:r}}),so=N.object({...K,type:N.literal(`replace_view_content`),definition:oo}).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}}),co=S.describe(`The whole content definition.`),lo=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:so,wire:N.object({...K,type:N.literal(`replace_view_content`),definition:co}).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}}))}),uo=N.object({...G,type:N.literal(`add_view_content`),content:co,target:ao.describe(`Where to place the new content within its placement zone`)}).strict(),addFocus=e=>({...viewFocus(e),contentName:e.content.name}),fo=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:uo,focus:addFocus,presentation:definePresentation(addFocus,`structural`),describe:e=>`Add ${e.content.name}`,apply:(e,t,n)=>change(e,t,n,e=>{if(Object.hasOwn(e.authoring.contents,t.content.name))throw new C(`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 n=placed(e.contents,t.content,t.target);return setOrder(e,n,[t.content.placement]),{...e,revision:e.revision+1,contents:n,contentIds:{...e.contentIds,[t.content.name]:JSON.stringify([`draft-content`,t.id])},contentRevisions:{...e.contentRevisions,[t.content.name]:1}}})}),po=N.object({...K,type:N.literal(`remove_view_content`)}).strict(),mo=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:po,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}})}),ho=N.object({...K,type:N.literal(`move_view_content`),placement:N.enum([`main`,`aside`]).describe(`The placement zone to move the content into`),target:ao.describe(`Where to place the content within that placement zone`)}).strict(),go=defineOperation({type:`move_view_content`,summary:`Reorders or moves a content to a different placement; the aside rule applies.`,schema:ho,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)}}})}),_o=N.object({...G,type:N.literal(`update_view_metadata`),changes:N.object({label:N.string().min(1).optional().describe(`New label for the view`),description:N.string().optional().describe(`New description for the view`),icon:D.nullable().optional().describe(`New icon; null clears it`)}).strict().refine(e=>Object.keys(e).length>0).describe(`≥1 change`)}).strict(),vo=defineOperation({type:`update_view_metadata`,summary:`Updates a view's label, description, or icon (null clears the icon).`,schema:_o,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}})}),yo=N.string().refine(e=>e.trim().length>0,`API name must not be blank`),bo=N.object({...G,type:N.literal(`rename_view`),newName:yo.describe(`New API name for the view`)}).strict(),renameViewFocus=e=>({objectName:e.objectName,viewName:e.newName}),xo=defineOperation({type:`rename_view`,summary:`Renames a view; refused on a code-declared name — change it in the declaration.`,schema:bo,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}))}),So=N.object({...K,type:N.literal(`rename_view_content`),newName:yo.describe(`New API name for the content`)}).strict(),renameContentFocus=e=>({...viewFocus(e),contentName:e.newName}),Co=defineOperation({type:`rename_view_content`,summary:`Renames a content; refused on a code-declared name — change it in the declaration.`,schema:So,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}}})}),wo=N.object({...K,type:N.literal(`reset_view_content`)}).strict(),To=defineOperation({type:`reset_view_content`,summary:`Resets a content back to its code-declared source; only works when one exists.`,schema:wo,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}})})}),Eo=N.object({...G,type:N.literal(`reset_view_order`),placement:N.enum([`main`,`aside`]).describe(`The placement zone to reset to source order`)}).strict(),Do=defineOperation({type:`reset_view_order`,summary:`Resets a placement zone's order to its code-declared source, if one exists.`,schema:Eo,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}})}),Oo=N.discriminatedUnion(`type`,[so,uo,po,ho,_o,bo,So,wo,Eo]),q=[lo,fo,mo,go,vo,xo,Co,To,Do];function findObject(e,t){return e.objects.find(e=>e.id===t)}const ko=new Set([`formula`,`rollup`]);function isComputedAttribute(e){return ko.has(e.attributeType)}const Ao={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 Ao?Ao[e]:void 0}function requireObject(e,t){let n=findObject(e,t);if(!n)throw new DraftRefusalError(`Object "${t}" is not in the draftable state`,W);return n}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(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 E(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(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 n=bilateralDeclarationOf(e);if(n===void 0||untouched(e))continue;let r=t.objects.find(t=>t.id===e.objectId)?.name??e.objectId,i=t.objects.find(e=>e.name===n.object),a=t.attributes.find(e=>e.objectId===i?.id&&e.name===n.attribute),o=`relation "${r}.${e.name}" declares inverse "${n.object}.${n.attribute}"`;if(a===void 0)throw new E(`${o}, which object "${n.object}" does not have; draft it first`,[]);if(a.attributeType!==`relation`)throw new E(`${o}, which is not a relation`,[]);let s=bilateralDeclarationOf(a);if(!(relationTargets(a).some(e=>e.object===r)&&(untouched(a)?s===void 0||s.object===r&&s.attribute===e.name:s?.object===r&&s.attribute===e.name)))throw new E(`${o}, which does not point back to "${r}.${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,t,n,r){let i=r.filter(e=>e.objectId===n.id).filter(e=>x(toAttribute(e)).presentation.formField).map(e=>({attribute:e.name})),a=e===`collection`?[{name:`all`,type:`collection`,placement:`main`,label:`All`,layout:`table`,source:{object:n.name}}]:i.length?[{name:`form`,type:`form`,placement:`main`,label:`Details`,groups:[{name:`general`,label:`General`,fields:i}]}]:[{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:!0,contents:a,authoring:workspaceViewAuthoring(a),revision:1,contentIds:Object.fromEntries(a.map(e=>[e.name,JSON.stringify([`draft-content`,t,e.name])])),contentRevisions:Object.fromEntries(a.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,n,r,i=!1){let a=toAttribute(t),o=r&&toAttribute(r),s=r&&bilateralDeclarationOf(r),c=bilateralDeclarationOf(t);if(s&&(s.object!==c?.object||s.attribute!==c?.attribute))throw new E(`Changing a bilateral address requires removing the existing pair first`,[]);if(a.type!==`relation`||!a.bilateral)return e;let l=e.objects.find(e=>e.id===t.objectId),u=e.objects.find(e=>e.name===a.bilateral?.object);if(!(l&&u))throw new E(`Both objects must exist before materializing a relation pair`,[]);let d=`${l.name}.${t.name}`,f=a.bilateral.attribute,p=`${u.name}.${f}`,m=e.attributes.find(e=>e.objectId===u.id&&e.name===f),h=o?.metadata?.relationPairId,g=typeof h==`string`?h:draftEntityIdFor(`relation-pair`,`${n}:${t.id}`),_=[d,p].sort(),ee=typeof h==`string`?{id:g,addresses:_,ownerAddress:o?.type===`relation`&&o.bilateral?.storageOwner===!1?p:d,generatedAddresses:[],...d===p?{symmetric:!0}:{}}:void 0,v=reconcileRelationAttributes({objects:[...new Map([l,u].map(e=>[e.id,e])).values()].map(e=>({name:e.name,attributes:[t,...m&&m.id!==t.id?[m]:[]].filter(t=>t.objectId===e.id).map(toAttribute)})),existingPairs:ee?[ee]:[],...r&&!i?{explicitAddresses:[d],propertyEditAddresses:[d]}:{},nextPairId:()=>g}),y=new Map;for(let n of v.objects){let a=n.name===l.name?l.id:u.id;for(let o of n.attributes){let n=e.attributes.find(e=>e.objectId===a&&e.name===o.name),s=n?.id===t.id?r??n:n,c={...preserveDeclarationHints(o,n&&toAttribute(n)),metadata:{...o.metadata,...s&&isGeneratedDraftRelation(s)&&!(i&&n?.id===t.id)||!n?{relationGenerated:!0}:{}},id:n?.id??draftEntityIdFor(`relation-attribute`,`${g}:${a}:${o.name}`),...n?{}:{order:e.attributes.filter(e=>e.objectId===a).length}};y.set(`${a}.${o.name}`,toDraftableAttribute(c,a))}}let b=e.attributes.map(e=>{let t=`${e.objectId}.${e.name}`,n=y.get(t);return y.delete(t),n??e});return b.push(...y.values()),{...e,attributes:b,views:e.views.map(e=>{let t=[l,u].find(t=>t.name===e.object);return e.derived&&t?regenerateDerived(e,t,b):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 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,n){let r=n.config??{},i=n.name;if(r.relationPath!==void 0)throw new E(`rollup "${i}": relationPath is not supported yet`,[]);let a=r.relationAttribute;if(typeof a!=`string`||a.length===0)throw new E(`rollup "${i}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let o=e.attributes.find(e=>e.objectId===t.id&&e.name===a&&e.attributeType===`relation`);if(!o)throw new E(`rollup "${i}" needs a relation attribute; "${a}" is not a relation of object "${t.name}"`,[]);let s=relationTargetObjectName(o);if(s===void 0){let e=relationTargets(o).filter(e=>e.object!==`*`).length;throw new E(`rollup "${i}" needs a relation with one target object; "${a}" targets ${e}`,[])}if(r.function===`count`)return;let c=e.objects.find(e=>e.name===s),l=r.targetAttribute;if(l===void 0)throw new E(`rollup "${i}" needs a targetAttribute: "${r.function}" aggregates one attribute of object "${s}"`,[]);if(!(c!==void 0&&e.attributes.some(e=>e.objectId===c.id&&e.name===l)))throw new E(`rollup "${i}" targets attribute "${l}", which object "${s}" 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 n=requireObject(e,t.objectId);if(t.attributeType===`relation`){for(let n of relationTargets(t))if(n.object!==`*`&&!e.objects.some(e=>e.name===n.object))throw new E(`object "${n.object}" is unknown; create it first`,[]);let n=bilateralDeclarationOf(t)?.object;if(n!==void 0&&n!==`*`&&!e.objects.some(e=>e.name===n))throw new E(`object "${n}" 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,n,t),computedPlanOf(e,t);else return;assertAcyclicComputed(compilablePlansOf(e,t.objectId))}const J={...io,objectId:N.string().uuid().describe(`The object this operation acts on`)},jo=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:N.object({...J,objectId:N.string().uuid().describe(`Stable id for the new object; the server mints one when omitted`),type:N.literal(`add_object`),name:qt.describe("kebab-case plural API name (`purchase-orders`)"),label:N.string().min(1).describe(`Label people see`),icon:N.string().min(1).optional().describe(`Icon name`)}),apply:(e,t)=>{if(e.objects.some(e=>e.name===t.name))throw new E(`Object "${t.name}" already exists`,[]);if(e.objects.some(e=>e.id===t.objectId))throw new E(`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,...defaultViewsFor(n,e.attributes)]}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Crée l'objet « ${e.label} »`}),Mo=N.object({...J,type:N.literal(`update_object`),changes:N.object({label:N.string().min(1).optional().describe(`New label`),icon:N.string().min(1).optional().describe(`New icon name from search_icons`),pluralLabel:N.string().optional().describe(`New label for many records; "" clears it`),description:N.string().optional().describe(`What this object holds`),labelExpression:P.optional().describe(`Titles every record; syntax in <expressions>`),embeddingExpression:N.literal(``).or(P).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}),No=defineOperation({type:`update_object`,summary:`Updates an object's settings: label, icon, pluralLabel, description, labelExpression, embeddingExpression.`,schema:Mo,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)}),Po={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])=>Po[e]?.(String(t))).filter(e=>e!==void 0);return t.length>0?t.join(` · `):`Modifie l'objet`}const Fo=defineOperation({type:`remove_object`,summary:`Removes an object; refused while a relation attribute targets it — remove it first.`,schema:N.object({...J,type:N.literal(`remove_object`)}),apply:(e,t)=>{requireObject(e,t.objectId);let n=e.objects.find(e=>e.id===t.objectId)?.name,r=e.attributes.filter(e=>e.objectId!==t.objectId&&e.attributeType===`relation`&&relationTargets(e).some(e=>e.object===n));if(r.length>0){let ownerOf=t=>e.objects.find(e=>e.id===t.objectId)?.name;throw new DraftRefusalError(`object "${n}" is targeted by attribute "${ownerOf(r[0])}.${r[0].name}"; remove that attribute first`,{kind:`object-targeted`,blockers:r.flatMap(e=>{let t=ownerOf(e);return t?[{ownerObjectName:t,attribute:e.name}]:[]})})}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!==n)}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Supprime l'objet ${e.objectId}`}),Io=Hn;function assertConfigParses(e,t){try{Ot(e,t)}catch(e){throw e instanceof E?new E(e.message,e.errors.map(e=>({...e,path:[`config`,...e.path??[]]}))):e}}const Lo=N.object({...J,type:N.literal(`add_attribute`),attributeId:N.string().min(1),name:Dt,label:N.string().min(1),attributeType:N.enum(Io),config:N.record(N.string(),N.unknown()).optional()}).superRefine((e,t)=>{try{assertConfigParses(e.attributeType,e.config??{})}catch(e){if(e instanceof E){for(let n of e.errors)t.addIssue({code:`custom`,message:n.message,path:[...n.path]});return}throw e}}),Ro={...io,type:N.literal(`add_attribute`),attributeId:N.string().min(1).describe(`Stable attribute id`),name:Dt.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),label:N.string().min(1).describe(`Label people see`)},zo=Object.fromEntries(Rt.map(e=>[e,!0])),Y=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],Bo=N.object(Y.reduce((e,t)=>(Object.assign(e,Et(t).omit(zo).shape),e),{})).strict(),Vo=Io.filter(e=>!Y.includes(e)),Ho=Object.fromEntries(Y.map(e=>[e,new Set(Object.keys(Et(e).omit(zo).shape))])),Uo=Lt(Ho,`config key`);function refuseForeignSimpleConfigKeys(e,t){Uo(e.attributeType,e.config,t,[`config`])}function wireConfigFor(e){let t=Et(e).omit(zo);return(e===`relation`||e===`document`?t.extend({properties:Bt.optional()}):t).strict()}const Wo=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:Lo,wire:N.discriminatedUnion(`attributeType`,[N.object({...Ro,objectId:N.string().uuid(),attributeType:N.enum(Y).describe(`Attribute type`),config:Bo.optional().describe(`Configuration of a simple attribute (text, number, date…)`)}).strict().superRefine(refuseForeignSimpleConfigKeys),...Vo.map(e=>N.object({...Ro,objectId:N.string().uuid(),attributeType:N.literal(e).describe(`Attribute type`),config:wireConfigFor(e).optional().describe(`Configuration of a ${e} attribute`)}).strict())]),apply:(e,t)=>{let n=requireObject(e,t.objectId),r=e.attributes.find(e=>e.objectId===t.objectId&&e.name===t.name);if(r&&!isGeneratedDraftRelation(r))throw new E(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let i={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 n of e.sampleRecords)n.objectId===t.objectId&&assertRequiredCovered(n.id,i,n.values);let a=withDerivedViews(e,n,r?e.attributes.map(e=>e===r?i:e):[...e.attributes,i]);return assertConfigFolds(a,i),reconcileDraftRelationAttribute(a,i,t.id,r,!0)},focus:attributeFocus,presentation:definePresentation(attributeFocus,`local`),describe:e=>`Ajoute l'attribut « ${e.label} »`}),Go={...J,attribute:Dt.describe(`The attribute's API name on this object`)};function requireAttribute(e,t,n,r){let i=requireObject(e,t);if(n===void 0)throw new E(`${r} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let a=e.attributes.find(e=>e.objectId===t&&e.name===n);if(!a)throw new DraftRefusalError(`Attribute "${n}" is not on object "${t}"`,W);return{object:i,attribute:a}}const Ko=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:N.object({...Go,type:N.literal(`update_attribute`),changes:N.object({label:N.string().min(1).optional().describe(`New label`),config:N.record(N.string(),N.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} »`}),qo=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:N.object({...Go,type:N.literal(`remove_attribute`)}),apply:(e,t)=>{let{attribute:n}=requireAttribute(e,t.objectId,t.attribute,`remove_attribute`),r=pairedDraftAttributes(e,n);for(let t of r){let n=requireObject(e,t.objectId),[r]=dependentsOf(e,t.objectId,t.name);if(r!==void 0)throw new E(`attribute "${t.name}" is used by "${r}"; remove that first`,[]);for(let r of e.views){if(r.object!==n.name)continue;let e=handShapedUse(r,t.name);if(e!==void 0)throw new E(`attribute "${t.name}" is used by view "${r.id}" (${e}); remove it from the view first`,[])}let i=e.sampleRecords.find(e=>e.objectId===t.objectId&&t.name in e.values);if(i)throw new E(`Attribute "${t.name}" is still used by sample record "${i.id}"`,[])}let i=e.attributes.filter(e=>!r.includes(e)),a={...e,views:e.views.map(e=>e)};return r.reduce((t,n)=>withDerivedViews(t,requireObject(e,n.objectId),i),a)},focus:existingAttributeFocus,presentation:definePresentation(existingAttributeFocus,`local`),describe:e=>`Supprime l'attribut « ${e.attribute} »`});function assertSampleValue(e,t,n,r){let i=toAttribute(n);try{hn(i)}catch{return}let a=_n(i,r);if(a.success)return;let o=a.errors??[],s=`Sample record "${e}" has an invalid value for "${t}": ${o.map(e=>e.path.length>1?`${e.path.join(`.`)}: ${e.message}`:e.message).join(`, `)}`,c=o.map(e=>({path:e.path,message:e.message}));throw n.attributeType===`relation`&&carriesNonRecordId(r)?new DraftRefusalError(s,{kind:`sample-relation-value`},c):new E(s,c)}function assertRequiredCovered(e,t,n){if(t.config?.required===!0&&t.config?.defaultValue===void 0&&!(t.name in n&&n[t.name]!==void 0))throw new E(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}const Jo=N.guid();function carriesNonRecordId(e){let t=Array.isArray(e)?e:[e],n=relationValueIds(e);return n.length<t.length||n.some(e=>!Jo.safeParse(e).success)}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,n,r){let i=e.objects.find(e=>e.name===n);if(!i)return;let a=e.views.some(e=>e.id===defaultViewIdsFor(i.id).list);for(let n of relationValueIds(r)){let r=e.sampleRecords.find(e=>e.id===n);if(r?.objectId!==i.id&&(r!==void 0||a))throw new DraftRefusalError(`sample record "${t}" references unknown sample "${n}"`,{kind:`sample-relation-value`})}}const Yo=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:N.object({...J,type:N.literal(`add_sample_record`),recordId:N.string().uuid().describe(`Minted by the server when omitted`),values:N.record(N.string(),N.unknown()).describe("Attribute name → value; currency is `{code,value}`, relation is a record id or name minted here"),publication:N.enum([`preview`,`requested-data`]).optional().describe(`preview = display-only; requested-data = real records asked for`)}),apply:(e,t)=>{let n=requireObject(e,t.objectId);if(e.sampleRecords.some(e=>e.id===t.recordId))throw new E(`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 DraftRefusalError(`Sample record "${t.recordId}" uses unknown attribute "${i}"`,{kind:`sample-unknown-attribute`,objectName:n.name,attributeNames:[...r.keys()]});if(isComputedAttribute(o))throw new E(`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 n of e.sampleRecords){if(n.id===t)continue;let r=relationNamesOf(e,n.objectId);for(let[e,i]of Object.entries(n.values))if(r.has(e)&&relationValueIds(i).includes(t))throw new E(`sample record "${t}" is referenced by sample record "${n.id}"; remove that first`,[])}}const X=[jo,No,Fo,Wo,Ko,qo,Yo,defineOperation({type:`remove_sample_record`,summary:`Removes a sample record; refused while another sample still references it.`,schema:N.object({...J,type:N.literal(`remove_sample_record`),recordId:N.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 DraftRefusalError(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,W);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[...X,...q]){if(e.has(t.type))throw new C(`architect operation`,t.type);e.set(t.type,t)}return e}const Z=build(),Xo=[...Z.keys()];function defOf(e){let t=Z.get(e.type);if(!t)throw new E(`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 E(`An operation must be an object carrying a type`,[]);let t=e.type;if(typeof t!=`string`)throw new E(`An operation's type must be a string`,[]);let n=Z.get(t);if(!n)throw new E(`Unknown operation type "${t}"`,[]);let r=n.schema.safeParse(e);if(!r.success)throw new E(`Operation "${t}" is invalid: ${r.error.issues.map(e=>`${e.path.join(`.`)} ${e.message}`).join(`; `)}`,[]);return r.data}const pair=e=>N.tuple([N.literal(e),N.string()]),Zo=N.union([N.tuple([N.literal(`content`),N.string(),N.string(),N.string()]),N.tuple([N.literal(`view`),N.string(),N.string()]),N.tuple([N.literal(`attribute`),N.string(),N.string()]),N.tuple([N.literal(`sample`),N.string(),N.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=Oo.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:${A(e)}`}const Qo=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 n;try{n=JSON.parse(t)}catch{throw new E(`Invalid proposal target key "${t}"`,[])}let r=Zo.safeParse(n);if(!r.success)throw new E(`Invalid proposal target key "${t}"`,[]);let[i,a,o,s]=r.data,c=e.objects.find(e=>e.id===a);if(i===`object`)return c??null;if(i===`object-name`)return e.objects.find(e=>e.name===a)??null;if(i===`attribute-id`)return e.attributes.find(e=>e.id===a)??null;if(i===`attribute`)return e.attributes.find(e=>e.objectId===a&&e.name===o)??null;if(i===`sample`)return e.sampleRecords.find(e=>e.objectId===a&&e.id===o)??null;if(i===`object-schema`||i===`object-tree`){if(!c)return null;let t=e.attributes.filter(e=>e.objectId===a);return i===`object-schema`?{object:c,attributes:t.toSorted((e,t)=>e.name.localeCompare(t.name))}:{object:c,attributes:t,views:e.views.filter(e=>e.object===c.name),sampleRecords:e.sampleRecords.filter(e=>e.objectId===a)}}let l=e.views.find(e=>e.object===a&&e.name===o);if(!l)return null;if(i===`view`)return{id:l.id,revision:l.revision,definition:{...draftedViewDefinition(l),contents:l.contents.map(({name:e,placement:t})=>({name:e,placement:t}))}};let u=l.contents.find(e=>e.name===s);return s!==void 0&&Object.hasOwn(l.contentIds,s)?{id:l.contentIds[s],revision:l.contentRevisions[s],definition:u??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 architectContentBodyKey(e){let t=architectFocusKey(e);return t===null?null:`body/${t}`}function architectFocusCandidates(e){let t=architectFocusKey(e);if(t===null)return[];let n=e.contentName?architectContentBodyKey(e):null;return n===null?[t]:[t,n]}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 $o={add_object:`major`,remove_object:`major`,add_view_content:`major`,replace_view_content:`major`,reset_view_content:`major`,add_attribute:`normal`,remove_attribute:`normal`,remove_view_content:`normal`,add_sample_record:`normal`,update_object:`minor`,update_attribute:`minor`,update_view_metadata:`minor`,rename_view:`minor`,rename_view_content:`minor`,move_view_content:`minor`,reset_view_order:`minor`,remove_sample_record:`minor`},es=`normal`;function operationPace(e){return Object.hasOwn($o,e)?$o[e]:es}const ts={major:{replay:4e3,live:2500},normal:{replay:2600,live:1800},minor:{replay:1400,live:1100}};function dwellForStep(e,t,n){let r=(ts[e]??ts[es])[t],i=900+40*(n||0);return Math.min(6e3,Math.max(r,i))}const Q=N.string().min(1),ns=N.union([N.object({objectName:Q,viewName:Q,contentName:Q.optional()}).strict().describe(`Full configuration of a view, or of one content when contentName is given`),N.object({objectId:Q}).strict().describe(`An object with its attributes, by id`),N.object({objectName:Q}).strict().describe(`An object with its attributes`),N.object({objectId:Q,attributeName:Q}).strict().describe(`One attribute's config, by name`),N.object({objectId:Q,attributeId:Q}).strict().describe(`One attribute's config, by id`),N.object({objectId:Q,recordId:Q}).strict().describe(`One sample record`)]);function parseNamedTarget(e){let t=ns.safeParse(e);if(!t.success)throw new E(`Invalid scoped target`,[{path:[`target`],message:`Expected exactly one named target branch`}]);return t.data}const rs=N.object({type:N.literal(`remove_operation`),operationId:N.string().min(1).describe(`The id of a stored operation to drop from the draft`)}),is=12;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 N.discriminatedUnion(`type`,e)}function isUuidString(e){return e instanceof N.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):N.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=N.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 as={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of as[e.shape.type.value]??[]){let r=e.shape[n];r instanceof N.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,N.object({...n,objectName:N.string().min(1).describe(`Object`)}).strict())})}const os=membersOf(X,[rs]),ss=membersOf(q),cs=unionOf(os),ls=unionOf(ss),us={schema:cs,view:ls},ds={schema:unionOf(wireMembersOf(X,[rs])),view:unionOf(wireMembersOf(q))},fs=new Map([...X.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...q.map(e=>[e.type,`view`])]);function familyOf(e){return fs.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 x(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,r){let i=new Set(ownAttributes(e,r).filter(e=>e.attributeType===`relation`&&relationTargets(e).some(e=>e.object===t.name)).map(e=>e.name));return viewsOf(e,r,`record`).some(e=>e.contents.some(e=>{if(e.type!==`collection`)return!1;let r=collectionSourceAddress(e.source);return r.kind===`relatedFrom`?r.object===t.name&&r.relation===n.name:r.kind===`related`&&i.has(r.relation)}))}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,t,i,a)&&n.push(`Relation "${i.label}" on "${t.label}" has no reciprocal collection on "${a.label}": add_view_content with source { object: "${t.name}", relation: "${i.name}" } (relatedFrom).`)}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 E(`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 ps=[`draft_schema`],ms=`discard_architect_draft`,hs=`request_design_review`,gs=`get_architect_draft`,_s=[{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:{}}}}],$=N.string().refine(e=>e.trim().length>0,`Must not be blank`),vs=N.union([N.tuple([N.literal(`object`),$]),N.tuple([N.literal(`attribute`),$,$]),N.tuple([N.literal(`view`),$,$]),N.tuple([N.literal(`content`),$,$,$])]),ys=N.object({label:$,pluralLabel:N.string().optional(),description:N.string().optional(),icon:D.optional(),labelExpression:N.string(),embeddingExpression:N.string().optional(),sealed:N.boolean().optional(),toleratedAttributes:N.array($).optional(),metadata:N.record(N.string(),N.unknown()).optional(),schema_version:N.number().int().nonnegative(),migrations:N.array(N.record(N.string(),N.unknown())),documentLayout:N.record(N.string(),N.unknown()).optional()}).strict();function failure(e){throw new E(e,[])}function definitionSchema(e){return N.custom(t=>{let n=N.record(N.string(),N.unknown()).parse(t);for(let t of e[0]===`view`?[`object`,`name`]:[`name`])Object.hasOwn(n,t)&&failure(`Invalid schema state: unrecognized definition key ${t}`);switch(e[0]){case`object`:ys.parse(n);break;case`attribute`:{let e=N.enum(Hn).parse(n.type);Nt(e).extend({type:N.literal(e),label:$,required:N.boolean().optional(),unique:N.boolean().optional(),icon:D.optional()}).strict().parse(n);break}case`view`:{let{contents:t,...r}=n,i=N.array($).parse(t);new Set(i).size!==i.length&&failure(`Invalid schema state: duplicate content membership`),we.parse({...r,object:e[1],name:e[2],contents:[]});break}case`content`:S.parse({...n,name:e[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=N.record(N.string(),N.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 n=N.object({modelVersion:N.literal(1),hashVersion:N.literal(1),tenant:$,sourceFingerprint:N.string().regex(/^[a-f0-9]{64}$/),entries:N.array(N.unknown())}).strict().safeParse(e);if(!n.success){let e=n.error.issues.find(e=>e.code===`unrecognized_keys`);throw e?.code===`unrecognized_keys`&&failure(`Invalid schema state: unrecognized key ${e.keys[0]}`),E.fromZodErrors(n.error.issues.map(e=>({path:e.path.map(String),message:e.message})))}let r=new Set,i=n.data.entries.map(e=>{let t=vs.parse(N.object({address:N.unknown()}).parse(e).address),n=JSON.stringify(t);r.has(n)&&failure(`Invalid schema state: duplicate address ${n}`),r.add(n);let i=definitionSchema(t).nullable(),a=t[0]===`object`||t[0]===`attribute`?N.object({id:N.string().uuid(),updatedAt:N.string().datetime()}).strict():N.object({id:N.string().uuid(),revision:N.number().int().nonnegative()}).strict(),o=N.object({address:vs,source:i,effective:i,status:N.enum([`source`,`runtime`,`copy`,`suppressed`]),sourceOwner:N.union([N.literal(`core`),N.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{...n.data,entries:i.sort(compareSchemaStateEntries)}}function parseSchemaState(e){try{return parseState(e)}catch(e){throw e instanceof N.ZodError?E.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`:A(n.source)===A(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}}export{Qo as ABSENT_TARGET_TOKEN,nr as AGENT_NOTIFICATION_KIND,Ui as AGENT_UI_BATCH_MAX_BYTES,Wi as AGENT_UI_BATCH_MAX_ITEMS,Br as ALLOWED_PROPERTY_TYPES,Tr as ALL_ACTIONS,Xo as ALL_OPERATION_TYPES,Gr as ALL_PIPES,Qr as ALL_SYSTEM_RESOURCES,Sr as ARTIFACT_FILE_ROLES,br as ARTIFACT_KINDS,ki as ARTIFACT_LIST_VIEW,Di as ARTIFACT_OBJECT,z as ARTIFACT_OBJECT_NAME,Ei as ARTIFACT_PREVIEW_EXTENSION,xr as ARTIFACT_RETENTIONS,Oi as ARTIFACT_VIEW,je as ATTRIBUTE_FILTER_OPERATORS,Hn as ATTRIBUTE_TYPES,Gn as AUDIT_ACTIONS,Wn as AUDIT_RESOURCE_TYPES,Me as AccessDeniedError,AgentBuilder,Ne as AttributeInUseError,Pe as AttributeNotFoundError,Bn as BEHAVIOR_PROPERTIES,Rr as BYTE_UNIT_LABELS,qn as CLAIMABLE_SESSION_STATUSES,oa as COMPUTED_FUNCTIONS,sa as COMPUTED_FUNCTION_METADATA,aa as COMPUTED_FUNCTION_NAMES,da as CONNECTOR_CALLBACK_PARAM,Fr as COUNT_MODES,Fe as ChangeTypeNotSupportedError,ComputedFormulaCompileError,Gt as ComputedFormulaParseError,Ie as ConcurrentModificationError,I as ContentBuilder,Zr as DB_COLUMN_FIELDS,si as DEFAULT_AGENT_EXECUTION_CONFIG,Jn as DEFAULT_APPROVAL_POLICY,yr as DEFAULT_DICTATION_LIMITS,Kr as DEFAULT_LABEL_FALLBACK,Er as DEFAULT_MEETING_BOT_DISPLAY_NAME,ei as DEFAULT_ROLES,ni as DEFAULT_ROLE_DESCRIPTIONS,ti as DEFAULT_ROLE_LABELS,oi as DEFAULT_ROLE_PERMISSIONS,Dr as DEFAULT_TENANT_SETTINGS,Qt as DEFAULT_VALIDATION_MESSAGES,_r as DICTATION_FINALIZATION_TIMEOUT_MS,dr as DICTATION_FRAME_BYTES,pr as DICTATION_MAX_BUFFER_BYTES,fr as DICTATION_MAX_FRAME_BYTES,mr as DICTATION_MAX_TRANSCRIPT_BYTES,vr as DICTATION_MODEL_ID,gr as DICTATION_PREPARATION_TIMEOUT_MS,ur as DICTATION_SAMPLE_RATE,hr as DICTATION_TICKET_TTL_MS,ms as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,zr as DOCUMENT_SYSTEM_ATTRIBUTES,Io as DRAFTABLE_ATTRIBUTE_TYPES,is as DRAFT_BATCH_LIMIT,ro as DRAFT_OBJECT_SETTINGS,_s as DRAFT_SCHEMA_INPUT_EXAMPLES,ps as DRAFT_WRITE_TOOL_NAMES,Ti as DRIVE_LIST_VIEW,Ci as DRIVE_OBJECT,R as DRIVE_OBJECT_NAME,wi as DRIVE_VIEW,Le as DestructiveSyncNotAllowedError,DraftRefusalError,C as DuplicateError,Hr as EMPTY_VALUE_PLACEHOLDER,Ir as ESTIMATED_COUNT_CAP,ya as FAKE_MEETING_BOT_SIGNATURE_HEADER,us as FAMILY_INPUTS,ds as FAMILY_WIRE_INPUTS,wr as FORM_FORBIDDEN_ATTRIBUTE_TYPES,FlagRegistry,FlagService,Re as ForbiddenError,FormBuilder,FormRegistry,FormRowBuilder,FormStepBuilder,gs as GET_ARCHITECT_DRAFT_TOOL_NAME,ui as GroupBuilder,zn as IDENTITY_PROPERTIES,Pr as IMAGE_FORMATS,Qn as INFERENCE_REASONING_OPTIONS,Zn as INFERENCE_SPEEDS,zi as INVENTORY_LIMIT,vt as LIST_VIEW_TAB_VISIBILITIES,Gi as LIVE_EVENT_TYPES,n as LOCATION_FILTER_PROPERTIES,pa as MAILBOX_LIST_MODES,ha as MAIL_DRAFT_BODY_MAX_CHARS,ga as MAIL_SUBJECT_MAX_CHARS,Cr as MAX_PRESET_DEPTH,ir as MAX_TODOS,or as MAX_TODO_DESCRIPTION_CHARS,ar as MAX_TODO_ID_CHARS,V as MEETING_ATTRIBUTES,Mi as MEETING_DETAIL_VIEW_ID,Ii as MEETING_LIST_VIEW,Ai as MEETING_LIST_VIEW_ID,Pi as MEETING_OBJECT,B as MEETING_OBJECT_NAME,Fi as MEETING_VIEW,ji as MEETING_WRITE_SOURCE,Si as MEMORY_LIST_VIEW,yi as MEMORY_OBJECT,xi as MEMORY_VIEW,fa as McpOAuthCompletionMode,ze as MemoryNotFoundError,Be as MigrationTimeoutError,MultiRelationAttributeBuilder,cr as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,lr as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,St as NATIVE_OBJECT_NAMES,Nn as NOTIFICATION_INBOX_STATES,An as NOTIFICATION_KINDS,jn as NOTIFICATION_PRIORITIES,Mn as NOTIFICATION_SENSITIVITIES,Rn as NOTIFICATION_TYPES_V1,Ln as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,Fn as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,In as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,Pn as NOTIFICATION_WORK_STATES,ba as NO_RECORDING,g as NO_VALUE_OPERATORS,ln as NonJsonValueError,NoopGeocodingAdapter,Ve as NotFoundError,He as NotImplementedError,qt as OBJECT_NAME_SCHEMA,er as OPEN_TOOL_PART_STATES,$o as OPERATION_PACE,Z as OPERATION_REGISTRY,o as OPERATORS_BY_TYPE,ca as OPERATOR_SPECS,ObjectBuilder,Ue as ObjectNotFoundError,We as ObjectReferencedError,Ge as OrphanSystemAttributeError,ts as PACE_DWELL_MS,Wr as PIPES_WITH_ARGS,Vn as PRESENTATION_PROPERTIES,Xn as PROVIDER_NAMES,Ke as ProtectedResourceError,qe as ProtectedRoleError,Vr as QUALIFIED_SEPARATOR,Lr as QUOTA_KEYS,_a as RECORDING_OVERRIDES,va as RECORDING_POLICIES,Xr as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,Un as RELATION_TARGET_ANY,de as REMOVED_OPERATOR_REPLACEMENTS,rs as REMOVE_OPERATION_SCHEMA,ma as REPLY_MODES,hs as REQUEST_DESIGN_REVIEW_TOOL_NAME,yt as RESERVED_ATTRIBUTE_NAMES,xt as RESERVED_OBJECT_NAMES,ht as RESOURCE_VISIBILITIES,Je as RecordNotFoundError,Ye as RecordReferencedError,Xe as RepositoryError,Ze as ReservedObjectNameError,Qe as RoleNotFoundError,Pt as SCHEMA_LIMITS,X as SCHEMA_OPERATIONS,cs as SCHEMA_OPERATION_INPUT,H as SCHEMA_PLAN_LIMITS,Sa as SCHEMA_SOURCE_ID_PATTERN,sr as SESSION_STATE_STREAM_ID,Kn as SESSION_TERMINAL_STATUSES,Ur as SIMPLE_PIPES,Ut as SIMPLE_PROPERTY_TYPES,hi as SKILL_CONTENT_TEMPLATE,vi as SKILL_LIST_VIEW,gi as SKILL_OBJECT,_i as SKILL_VIEW,ci as STANDARD_SCHEMA_VENDOR,se as SYNONYM_ALIASES,ie as SYSTEM_ATTRIBUTES,_ as SYSTEM_ATTRIBUTE_I18N_KEYS,gt as SYSTEM_FIELD_NAMES,xe as SYSTEM_FILTER_ATTRIBUTE_TYPES,tr as SYSTEM_PART_CODES,F as SYSTEM_RESOURCES,$r as SYSTEM_RESOURCE_LABELS,w as SchemaError,T as SchemaErrorCode,$e as SchemaPlanNotFoundError,et as SearchBackendError,SingleRelationAttributeBuilder,tt as StorageError,nt as SyncCascadeError,rt as SyncConflictError,it as SyncError,at as SystemEntityImmutableError,Or as TENANT_INVITATION_DEFAULT_TTL_MS,Ar as TENANT_INVITATION_MAX_TTL_MS,kr as TENANT_INVITATION_MIN_TTL_MS,jr as TENANT_INVITATION_RESEND_INTERVAL_MS,Yt as TEXT_FORMAT_PATTERNS,ua as TODAY_DEFAULT,Yn as TODO_PLAN_STATUSES,rr as TODO_STATUSES,$n as TOOL_APPROVAL_STATES,Mr as USER_STATUSES,Nr as USER_WORK_POSTURES,q as VIEW_OPERATIONS,ls as VIEW_OPERATION_INPUT,E as ValidationError,li as ViewBuilder,Rt as WIRE_OMITTED_CONFIG_KEYS,accessLevelToActions,actionsToAccessLevel,agent,agentDataChunk,agentDisplayName,Ha as agentInferencePreferencesSchema,Ya as agentMessageAttachmentSchema,Ja as agentMessagePartSchema,Wa as agentSessionInferenceOverridesInputSchema,Ga as agentSessionInferenceOverridesSchema,$a as agentSessionMessageSchema,agentUIValidationError,applyOperations,applyPipes,applyRelationProps,architectContentBodyKey,architectDraftChannelKey,architectFocusCandidates,architectFocusKey,dn as asTenantId,cn as asUserId,assertAcyclicComputed,assertAcyclicComputedDependencies,assertBilateralPairs,assertCustomAgentUIMessageChunk,assertSchemaSourceId,Vt as attributeConfigSchemas,attributeInventory,bilateralDeclarationOf,booleanFlag,buildAgentFallbackTitle,buildPermissionFlags,buildPropertySchema,buildQualifiedAttribute,A as canonicalStringify,Oo as canonicalViewOperationSchema,r as canonicalizeFilterValue,capped,checkbox,collectContentViewCatalogue,ve as collectQualifiedRuleIssues,collectSchemaReferences,ye as collectionContentSourceSchema,collectionContentsOf,collectionSourceAddress,collectionSourceAddressOf,Ft as colorIdSchema,Ce as columnsSchema,compareAgentSessionMessages,compareSchemaStateEntries,compilablePlansOf,compileComputedFormula,compileRollupAttribute,computeByteMagnitude,computedCompileSchemaOf,computedPlanOf,L as content,contentDefinition,Vi as contentExtensionRegistry,me as contentViewDefinitionSchema,oe as contentViewDefinitionSchemaFor,conversationDisplayTitle,tn as createCheckboxValidator,nn as createDateValidator,createFlagRegistry,createFlagService,gn as createFormAttributeValidator,en as createNumberValidator,createStandardSchemaProps,Zt as createTextValidator,currency,t as currentActor,no as customDataChunkSchemas,date,dateInTimezone,dateValueStart,un as deepEqual,defaultViewIdsFor,defaultViewsFor,defineOperation,definePresentation,dependentsOf,deriveArchitectChanges,deriveCreateDefaultsFromFilters,deriveInitials,describeOperations,Aa as destructiveSchema,detailView,diffSchemaState,be as displayAttributesSchema,document,we as draftContentViewDefinitionSchema,ce as draftContentViewDefinitionSchemaFor,draftObjectSettings,draftedLabelExpression,draftedObjectDefinition,draftedViewDefinition,Qa as durableDateSchema,dwellForStep,episodeImpactOf,evaluateComputedAst,evaluateComputedFormula,evaluateComputedFormulaWithResult,evaluateFilterState,evaluateRecordFilterState,extractAttributeNames,h as extractCurrencyFilterValue,ge as extractFilterValue,extractValueRefs,familyOf,l as filterOperatorsByTypeForGeneration,_e as filterStateSchema,findRelationAttribute,di as flagRegistry,focusOf,form,formFieldFlatKey,formFieldKey,Hi as formRegistry,formatAgentStreamFrameId,formatAttributeValue,formatByteSize,formatComputedResult,formatLocationValue,$t as formatZodErrors,formula,fromDraftableView,on as generateId,x as getAttributeCapabilities,c as getAttributeFilterOperators,getEditableLabelAttribute,getErrorMessage,getLiveProtocolPayloadChannel,Oe as getOperatorPolarity,getRecordCreatorPrincipalId,f as getRollupFilterOperators,getSingleAttributeFromExpression,getSlotFieldTargets,e as getSystemAttributeI18nKey,ue as getSystemAttributeList,getUserDisplayName,group,guidanceForBatch,hasDestructiveEntries,hasOptions,D as iconNameSchema,Ua as imageModelIdSchema,includesAction,rn as indexBy,inferInverseCardinality,inferRollupReturnType,Ba as inferenceReasoningSchema,za as inferenceSpeedSchema,isAgentNotificationMetadata,isAgentUIDataName,isAgentUIMessageBatch,b as isAttributeFilterable,te as isAttributeGroupable,ot as isAttributeInUseError,s as isAttributeKanbanGroupable,d as isAttributeSearchable,isAttributeSortable,isBilateralRelation,isCheckboxEquality,isClaimableSessionStatus,isComputedAttribute,isComputedFunctionName,isCurrentTargetToken,isDateRangeValue,isDefaultRole,isDocumentAttribute,he as isDynamicValue,isEdgePayload,isEmptyObject,isFormDefinition,isFormFieldsRow,isFormFreeFieldRef,isFormHeadingRow,isFormSeparatorRow,isFormSlotFieldRef,isFormTextRow,isLabelExpression,isLiveEventEnvelope,isLiveEventPayload,isLiveEventPayloadForType,isLiveEventType,u as isLocationFilterProperty,re as isLocationPartOperator,isMailProvider,isMailboxListMode,Ee as isManagedSystemAttribute,Jt as isNativeObjectName,ee as isNoValueOperator,isNotEmpty,st as isNotFoundError,j as isNullishOrEmptyString,ct as isObjectReferencedError,isOpenToolPartState,isPlainRecord,lt as isProtectedResourceError,ut as isRecordReferencedError,fe as isRelativeDateValue,isReplyMode,dt as isSchemaError,y as isSetMembershipOperator,isStandardSchema,isSystemPartCode,isTerminalSessionStatus,isTerminalState,isToolApprovalState,isUniversalRelation,ft as isValidationError,vn as isValuePresent,jsonFlag,legacyStatusToSessionState,listView,liveChannelKey,location,matchesAccepts,Xa as mentionReferenceSchema,Za as modelDefinitionSchema,Va as modelReferenceSchema,multiselect,zt as multiselectOptionWriteSchema,ns as namedTargetSchema,nativeAgentUIPartIdMetadataKey,normalizeDateValue,ke as normalizeFilterRule,a as normalizeForEdgeRpc,v as normalizeOperator,p as now,number,numberFlag,object,operationPace,orderAgentSessionMessages,parseAgentStreamFrameId,Ht as parseAttributeConfig,Ot as parseAttributeConfigForCreate,It as parseAttributeConfigForUpdate,k as parseComputedFormula,parseCountMode,parseLiveChannelKey,parseNamedTarget,parseNativeAgentUIPartIdsMetadata,parseOperation,parseOptionalCountMode,parseQualifiedAttribute,_t as parseResourceVisibility,parseSchemaGroupPresentation,parseSchemaState,Ia as persistedSchemaPlanSchema,phone,Da as plannedAttributeSchema,Oa as plannedInlineAttributeSchema,ka as plannedObjectSchema,presentationOf,Wt as propertyAttributeSchema,kt as propertyAttributeWireSchema,At as propertySchemaSchema,Bt as propertySchemaWireSchema,proposalTargetKey,Ra as providerNameSchema,S as publishedViewContentDefinitionSchema,qualifiedPropertyDefs,readFormFieldValue,reconcileRelationAttributes,Lt as refuseForeignKeys,regenerateDerived,pi as registry,bn as rejectUnknownAttributesOrThrow,relation,relationAcceptsObject,relationProperty,relationPropertyDefs,relationTargetObjectName,relationTargets,relationTargetsOf,relationValueIds,renderLabelExpression,requestedCapabilities,requireRecordContentContext,requireSingleRelationTarget,requiredTargetKeys,resolveAttributeDefaultValue,resolveCollectionActions,resolveContentNavigation,ne as resolveEffectiveFilterType,resolveFieldRequired,ae as resolveIsWithinBounds,resolvePropertyDefinitions,Xt as resolveTextPattern,De as resolveUtcDayBounds,resolveViewContents,richtext,rollup,rollupToFormulaExpression,an as sameStableValue,schemaGroupKey,Pa as schemaPlanSchema,schemaStateSourcePayload,select,Mt as selectOptionWriteSchema,sn as serializeCanonicalJson,fn as serializeStableJson,Ka as sessionInferencePatchSchema,sessionStateToLegacyStatus,le as sortsSchema,status,jt as statusGroupSchema,Tt as statusOptionWriteSchema,stillMissing,storedContentDefinition,stringFlag,summarizeDraft,targetSnapshot,targetTokenOf,targetTokensFor,text,toAttribute,toDraftableAttributes,toDraftableObject,toDraftableView,i as toMultiValueOperator,toUndefinedIfEmpty,Ae as toUtcDayString,m as today,eo as todoItemSchema,to as todoPlanSchema,qa as toolImpactSchema,touchedObjectIds,user,pt as validateAttributeName,validateContentViewCatalogue,pn as validateDraft,yn as validateDraftOrThrow,validateLabelExpression,xn as validateObject,validateObjectExpressions,mt as validateObjectName,mn as validateObjectOrThrow,pe as validateQualifiedRule,validateStoredViews,bt as validateViewName,viewIdFor,viewIdentityKey,Li as viewRegistry,workspaceViewAuthoring};
43
+ {{ summary }}`).attribute(text({name:U.title,label:`Title`}).required()).attribute(richtext({name:U.description,label:`Description`})).attribute(richtext({name:U.summary,label:`Summary`}).hidden()).attribute(richtext({name:U.transcript,label:`Transcript`}).hidden()).attribute(text({name:U.location,label:`Location`})).attribute(date({name:U.startsAt,label:`Starts at`}).includeTime()).attribute(date({name:U.endsAt,label:`Ends at`}).includeTime()).attribute(checkbox({name:U.isAllDay,label:`All day`})).attribute(select({name:U.status,label:`Status`}).options([{value:`confirmed`,label:`Confirmed`},{value:`tentative`,label:`Tentative`},{value:`cancelled`,label:`Cancelled`}])).attribute(text({name:U.organizerAddress,label:`Organizer address`}).email()).attribute(text({name:U.organizerName,label:`Organizer`})).attribute(text({name:U.conferenceProvider,label:`Conference provider`})).attribute(text({name:U.conferenceJoinUrl,label:`Join link`}).url()).attribute(text({name:U.htmlLink,label:`Open in calendar`}).url()).attribute(text({name:U.participants,label:`Participants`}).multiline()).attribute(text({name:U.providerEventId,label:`Provider event id`}).hidden()).attribute(text({name:U.icalUid,label:`iCal UID`}).hidden()).attribute(text({name:U.recurringEventId,label:`Recurring event id`}).hidden()).attribute(text({name:U.connectionId,label:`Connection id`})).attribute(select({name:U.recordingOverride,label:`Recording`}).options([{value:`force`,label:`Force`},{value:`skip`,label:`Skip`}]).hidden()).attribute(date({name:U.endedAnnouncedAt,label:`Ended announced at`}).includeTime().hidden()).attribute(relation({name:U.linkedRecords,label:`Linked records`}).toAny().many().qualifyWith(text({name:`source`,label:`Source`}).hidden())).build(),Ki=markSystemView(detailView(Ui,`Meeting`).for(H).default().tab(`description`,`Description`,z.richtext(U.description).titleAttribute(U.title)).tab(`summary`,`Summary`,z.richtext(U.summary)).tab(`transcript`,`Transcript`,z.richtext(U.transcript)).aside(`details`,`Details`,z.form(group(`details`,`Details`).fields(U.startsAt,U.endsAt,U.linkedRecords))).build()),qi=markSystemView(listView(Vi,`Meetings`).for(H).default().tab(`workspace`,`Shared`,z.collection().object(H).table().icon(`users`).visibility(`workspace`).columns(...Wi).sort(U.startsAt,`desc`)).tab(`mine`,`My meetings`,z.collection().object(H).table().icon(`lock`).visibility(`private`).columns(...Wi).sort(U.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)),n=new Map,r=new Set;for(let{declaration:e}of t){let{object:t,name:i,context:a,default:o}=e.definition,s=n.get(t)??new Set;if((this.views.get(t)?.has(i)||s.has(i))&&this.throwDuplicate(t,i),s.add(i),n.set(t,s),!o)continue;let c=JSON.stringify([t,a]);if(this.getByObjectNameAndContext(t,a).some(e=>e.definition.default)||r.has(c))throw new w(`default view`,c,`[ViewRegistry] Duplicate default view for object "${t}" in context "${a}"`);r.add(c)}for(let e of t)this.commit(e);return this}prepare(e,t){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 D(e,[{path:[`views`,String(t)],message:e}])}let n=pe.safeParse(e.definition);if(!n.success)throw D.fromZodErrors(n.error.issues.map(e=>({path:[`views`,String(t),`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 n=this.get(e,t);if(n)return n;let r=this.getByObjectName(e).map(({definition:e})=>`${e.name} (${e.context})`).join(`, `)||`(none)`;throw new Be(`View`,`${e}:${t}`,void 0,`[ViewRegistry] View "${t}" not found for object "${e}".\nAvailable views: ${r}`)}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 n=viewIdentityKey(e,t);throw new w(`view`,n,`[ViewRegistry] Duplicate view: "${t}" for object "${e}"`)}};const Ji=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 n=`Relation "${e.name}" requires one concrete collection target`;throw new D(n,[{path:t,message:n}])}return e.targets[0].object}function violationOf(e,t,n,r,i=`catalogue`){if(!(e instanceof T))throw e;let a=e instanceof D?e.errors[0]:void 0;return{key:JSON.stringify([t,n,e.code,e.message]),rule:i,contentName:n,path:a?.path??r,message:e.message,code:e.code,error:e}}const Yi=new Map(le().map(e=>[e.name,e]));function reject$2(e,t){throw new D(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,n){let r=new Map;return e.forEach((e,i)=>{if(requireName(e.name,[...n,String(i),`name`]),r.has(e.name))throw new w(t,e.name);r.set(e.name,e)}),r}const Xi=30;function capped(e,t){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} … and ${e.length-t} more`:n}function attributeInventory(e,t){return t.length===0?`Object "${e}" has no attributes yet.`:`Attributes of "${e}": ${capped(t,30)}`}function requireAttribute$1(e,t,n,r,i){if(requireName(t,n),!e)return;let a=e.attributes?.get(t)??Yi.get(t);if(!a){if(!e.attributes)return;let r=attributeInventory(e.name,[...e.attributes.keys()]);reject$2(n,`Unknown attribute "${e.name}.${t}". ${r}${i?.()??``}`)}return r&&a.type!==r&&reject$2(n,`Attribute "${e.name}.${t}" must have type ${r}`),a}function collectContentViewCatalogue(e){let t=e.mode??`published`,n=new Map;e.objects.forEach((e,t)=>{if(requireName(e.name,[`objects`,String(t),`name`]),n.has(e.name))throw new w(`object`,e.name);n.set(e.name,{name:e.name,attributes:indexUnique(e.attributes,`attribute`,[`objects`,String(t),`attributes`])})});let r=new Set;(e.reservedObjects??[]).forEach((e,i)=>{let a=[`reservedObjects`,String(i)];requireName(e,a),!n.has(e)&&(t!==`draft`&&reject$2(a,`Unresolved reserved object "${e}"`),r.add(e),n.set(e,{name:e}))});let i=indexUnique(e.extensions??[],`extension`,[`extensions`]);function resolveObject(e,t){requireName(e,t);let r=n.get(e);return r||reject$2(t,`Unknown object "${e}"`),r}function inverseAddresses(e){let t=[];for(let[r,i]of n)if(r!==e)for(let n of i.attributes?.values()??[])n.type===`relation`&&relationAcceptsObject(n,e)&&t.push(`relatedFrom("${r}", "${n.name}")`);return t.sort().slice(0,3)}let a=t===`draft`?se({asideRule:`tolerate`}):ae({asideRule:`tolerate`}),o=new Map,s=new Map,c=[],l=[];function parseView(e,t){let n=a.safeParse(e);if(!n.success)throw new D(`Invalid content view`,n.error.issues.map(e=>({path:[...t,...e.path.map(String)],message:e.message,code:e.code})));let r=n.data;requireName(r.name,[...t,`name`]);let i=o.get(r.object)??new Set;if(i.has(r.name))throw new w(`view`,`${r.object}.${r.name}`);if(i.add(r.name),o.set(r.object,i),r.default){let e=s.get(r.object)??new Set;if(e.has(r.context))throw new w(`default view`,`${r.object}.${r.context}`);e.add(r.context),s.set(r.object,e)}return r}return e.views.forEach((e,t)=>{let n=[`views`,String(t)],r=e,a=`${String(r?.object??`?`)}.${String(r?.name??t)}`,o,s;try{o=parseView(e,n),s=resolveObject(o.object,[...n,`object`])}catch(e){c.push(violationOf(e,a,null,n));return}for(let e of we(o)){let t=new D(e.message,[{path:[...n,...e.path.map(String)],message:e.message}]);c.push(violationOf(t,a,e.contentName,n,`aside`))}o.contents.forEach((e,t)=>{let r=[...n,`contents`,String(t)];try{requireName(e.name,[...r,`name`]),validateContent(e,r,s,o.context,i,resolveObject,inverseAddresses)}catch(t){c.push(violationOf(t,a,e.name,r))}}),l.push(o)}),{views:l,unresolvedObjects:[...r].sort(),violations:c}}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,n,r,i,a,o){function requireRecord(){requireRecordContentContext(e.name,r,t)}if(e.type===`custom`){let n=i.get(e.extension);n||reject$2([...t,`extension`],`Unknown extension "${e.extension}"`),n.requiresRecord&&requireRecord();let r=n.parameters.safeParse(structuredClone(e.parameters??{}));if(!r.success)throw new D(`Invalid extension parameters`,r.error.issues.map(e=>({path:[...t,`parameters`,...e.path.map(String)],message:e.message,code:e.code})));return}if(e.type===`collection`){let r=collectionSourceAddress(e.source),i,s;if(r.kind===`object`)i=a(r.object,[...t,`source`,`object`]);else if(r.kind===`related`){requireRecord();let e=[...t,`source`,`relation`],hint=()=>{if(!n)return``;let e=o(n.name);return e.length===0?``:`. Records pointing at "${n.name}" are addressed from the other side: ${e.join(`, `)}`},c=requireAttribute$1(n,r.relation,e,`relation`,hint);c?.type===`relation`&&(s=c,i=a(requireSingleRelationTarget(c,e),e))}else{requireRecord(),i=a(r.object,[...t,`source`,`object`]);let o=[...t,`source`,`relation`],s=requireAttribute$1(i,r.relation,o,`relation`);if(s?.type===`relation`&&n&&!relationAcceptsObject(s,n.name)){let e=s.targets.map(e=>`"${e.object}"`).join(`, `);reject$2(o,`Relation "${r.object}.${r.relation}" targets ${e}, not "${n.name}"`)}e.filters?.combinator===`or`&&reject$2([...t,`filters`,`combinator`],`Collection "${e.name}" addresses "${r.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 a=[...r,`relationProperty`];s||reject$2(a,`Relation property columns require a relation source`),s.properties?.definitions.some(t=>t.name===e.relationProperty)||reject$2(a,`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,r)=>{let i=[...t,`groups`,String(r)];requireName(e.name,[...i,`name`]),e.fields.forEach((e,t)=>requireAttribute$1(n,e.attribute,[...i,`fields`,String(t),`attribute`]))});break;case`richtext`:requireAttribute$1(n,e.attribute,[...t,`attribute`],`richtext`),e.titleAttribute!==void 0&&requireAttribute$1(n,e.titleAttribute,[...t,`titleAttribute`],`text`);break;case`emails`:case`meetings`:e.emailAttributes.forEach((e,r)=>requireAttribute$1(n,e,[...t,`emailAttributes`,String(r)],`text`));break;case`documents`:e.relations?.forEach((e,r)=>requireAttribute$1(n,e,[...t,`relations`,String(r)],`relation`));break;case`forms`:e.objectName!==void 0&&a(e.objectName,[...t,`objectName`]);break;case`activity`:break;default:reject$2(t,`Unknown content type: ${String(e)}`)}}const Zi=[Object.freeze(Li)];var ContentExtensionRegistry=class{constructor(){this.extensions=new Map,this.seed()}register(e){let t=Array.isArray(e)?e:[e],n=new Set;t.forEach((e,t)=>{if(this.prepare(e,t),n.has(e.name))throw new w(`content extension`,e.name);n.add(e.name)});for(let e of t)this.extensions.set(e.name,e);return this}prepare(e,t){let n=[`extensions`,String(t)],reject=e=>{throw new D(e,[{path:n,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 w(`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 Zi)this.extensions.set(e.name,e)}};const Qi=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 w(`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 $i=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}}const ea=204800,ta=256;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 na=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}),ra=[`membership-unknown`,`sort-unknown`,`permissions-changed`],ia=[`permission-revoked`,`workspace-left`,`object-deleted`],aa=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],oa=[`type`,`objectId`,`recordId`,`recordVersion`],sa=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],ca=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],la=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&na.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,kn)}function isNotificationPriority(e){return isOneOf(e,An)}function isNotificationSensitivity(e){return isOneOf(e,jn)}function isNotificationInboxState(e){return isOneOf(e,Mn)}function isNotificationWorkState(e){return isOneOf(e,Nn)}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,oa)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$1(e)&&hasOnlyKeys(e,ca)&&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,sa)&&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,ra)}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=>aa.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,la)&&hasNonEmptyString(e,`targetActorId`)&&hasVersion(e,`archivedCount`)&&hasVersion(e,`version`)&&hasIsoDateString(e,`updatedAt`)}const ua=[`armed`,`disarmed`],da=[`authoring`,`compiling`,`replaying`,`promoted`,`failed`],fa=[`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,ua)&&hasIsoDateString(e,`updatedAt`)}function isReflexRunCompletedPayload(e){return e.type===`reflex.run.completed`&&hasNonEmptyString(e,`reflexId`)&&hasNonEmptyString(e,`runId`)&&isOneOf(e.served,fa)&&hasVersion(e,`version`)&&hasVersion(e,`wallMs`)&&hasIsoDateString(e,`completedAt`)}function isReflexAuthoringProgressPayload(e){return e.type===`reflex.authoring.progress`&&hasNonEmptyString(e,`reflexId`)&&isOneOf(e.status,da)&&hasIsoDateString(e,`updatedAt`)}const pa=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,pa)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const ma=[`ok`,`low`,`exhausted`,`paused`],ha=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,ma)&&isOneOf(e.mode,ha)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,ia)}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 ga=[`if`,`concat`,`sum`,`avg`,`count`,`min`,`max`,`earliest`,`latest`,`unique`,`first`,`percent_empty`,`percent_not_empty`,`count_empty`,`count_not_empty`,`count_unique`],_a={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(_a,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(e){try{return A(e)}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=_a[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}"`);if(e.targetAttribute===void 0)throw new ComputedFormulaCompileError(`Rollup "${e.function}" on object "${t.objectName}" needs a targetAttribute`);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}=_a[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(M).length;case`count_not_empty`:return collectionItems(t[0]).filter(e=>!M(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=>M(e)===t).length/n.length}function uniqueNonEmpty(e){let t=new Set,n=[];for(let r of e){if(M(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(e,t){return evaluateAst(A(e),t)}function evaluateComputedFormulaWithResult(e,t,n,r){try{let i=evaluateAst(A(e),t);return{value:n?formatComputedResult(i,n,r):i}}catch(e){return{value:null,error:e instanceof Error?e.message:String(e)}}}const va=[{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=>M(e)||Array.isArray(e)&&e.length===0,toStr=e=>e==null?``:String(e),toNum=e=>{if(M(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)}),ya={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,t)=>{let n=toDate(e),r=ie(t);return n&&r?n.getTime()>=r.startMs&&n.getTime()<r.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}),ba=[...Object.entries(be).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,...ba])}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,t,n){let r=n.get(e.attribute);if(!r)return!1;if(e.property&&r.type===`location`){if(!(u(e.property)&&ne(e.operator)))return!1;let n=ya[e.operator];if(!n)return!1;let i=t[e.attribute],a=typeof i==`object`&&i?i[e.property]:void 0;return evaluateNormalizedComparands(n,`text`,e.operator,a,e.value,r)}if(e.property){let n=resolvePropertyDefinitions(r).find(t=>t.name===e.property);if(!n)return!1;let i=a(e.operator),o=ya[i];if(!o?.appliesTo.includes(n.type))return!1;let s=t[e.attribute],c=(Array.isArray(s)?s:s==null?[]:[s]).some(t=>{if(typeof t!=`object`||!t)return!1;let r=t.props;return typeof r!=`object`||!r?!1:evaluateNormalizedComparands(o,n.type,i,r[e.property],e.value,n)});return(e.quantifier??De(e.operator))===`none`?!c:c}let i=ya[e.operator];if(!i||!i.appliesTo.includes(r.type))return!1;let o=t[e.attribute],s=r.type===`relation`||r.type===`document`||r.type===`user`?normalizeReferenceIds(o):o;return evaluateNormalizedComparands(i,r.type,e.operator,s,e.value,r)}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 wn(t.phoneNumber);let n=typeof t.countryCode==`string`?t.countryCode:r;return`${n}:${Sn(t.phoneNumber,n)}`};return[normalizeOne(e),normalizeOne(t)]}function normalizeComparableValue(e,t){return e===`currency`?h(t):e===`date`?isDateRangeValue(t)?dateValueStart(t):t instanceof Date?Number.isNaN(t.getTime())?null:t.toISOString():t:t}function normalizeReferenceIds(e){let normalizeOne=e=>typeof e!=`object`||!e?e:e.id;return Array.isArray(e)?e.map(normalizeOne):normalizeOne(e)}const xa=`today`;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,t,n){if(e.combinator===`or`&&e.rules.length>1)return{};let r=new Map(t.map(e=>[e.name,e])),i={};for(let t of e.rules){if(t.property!==void 0||Object.hasOwn(i,t.attribute))continue;let e=r.get(t.attribute);if(!e)continue;let a=extractDeterministicValue(t,n);a!==void 0&&(i[t.attribute]=x(e).storage.cardinality===`many`?[a]:a)}return i}function extractDeterministicValue(e,t){if(e.operator===`is`)return me(e.value)?resolveDynamicValue(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 me(n)?resolveDynamicValue(n,t):n}}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 Sa={status:`connector_status`,error:`connector_error`,provider:`connector_provider`};let Ca=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const wa=[`threads`,`messages`];function isMailboxListMode(e){return wa.includes(e)}const Ta=[`reply`,`reply_all`];function isReplyMode(e){return Ta.includes(e)}const Ea=2e5,Da=998,Oa=[`force`,`skip`],ka=[`none`,`all`,`external_only`],Aa=`x-fake-signature`,ja={override:null,status:`none`,failureReason:null,botId:null},Ma=/^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&&!Ma.test(t)?t:e.firstUserText?buildAgentFallbackTitle(e.firstUserText):e.emptyLabel}const Na=/^[a-z0-9][a-z0-9-]{0,62}$/;function assertSchemaSourceId(e){if(!Na.test(e))throw new D(`Invalid schema source id "${e}": expected a lowercase slug matching ${Na}`,[])}function hasDestructiveEntries(e){let{attributeRemovals:t,objectRemovals:n,renames:r}=e.destructive;return t.length>0||n.length>0||r.length>0}const W={objectAdditions:20,totalMutations:500,serializedBytes:524288};function errorMessage(e){return e instanceof Error?e.message:String(e)}const Pa=N.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.'),Fa=N.string().min(1).superRefine((e,t)=>{try{ft(e)}catch(e){t.addIssue({code:N.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).`),Ia=N.string().min(1).superRefine((e,t)=>{qt(e)&&t.addIssue({code:N.ZodIssueCode.custom,message:`"${e}" is a reserved object name (${bt.join(`, `)}) and cannot be used for a new object.`});try{pt(e)}catch(e){t.addIssue({code:N.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(e){return e.superRefine((e,t)=>{try{let n=Dt(e.type,{...e.config??{},description:e.description}),r=Object.keys(e.config??{}).filter(e=>!Object.hasOwn(n,e));r.length>0&&t.addIssue({code:`unrecognized_keys`,keys:r,path:[`config`],message:`Unrecognized attribute config key${r.length===1?``:`s`}: ${r.join(`, `)}`})}catch(n){if(n instanceof D){for(let r of n.errors)t.addIssue({code:N.ZodIssueCode.custom,path:[`config`,...r.path.map(e=>/^\d+$/.test(e)?Number(e):e)],message:`Config for type "${e.type}" is invalid or incomplete: ${r.message}`});return}t.addIssue({code:N.ZodIssueCode.custom,path:[`config`],message:`Config for type "${e.type}" is invalid or incomplete: ${errorMessage(n)}`})}})}const La=N.object({objectName:N.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:Fa,label:N.string().min(1).max(128).describe(`Human-readable display label shown in the UI. 1-128 characters, cannot be empty.`),type:Pa,config:N.record(N.string(),N.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:N.boolean().optional().describe(`Whether the attribute must have a value on every record. Defaults to false (optional).`),description:N.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),Ra=withConfigCheck(La),za=withConfigCheck(La.omit({objectName:!0})),Ba=N.object({name:Ia,label:N.string().min(1).describe(`Human-readable singular display label (e.g. "Devis").`),pluralLabel:N.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:N.string().optional().describe(`Help text describing what this object represents.`),icon:O.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:I.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:N.array(za).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(),Va=N.object({attributeRemovals:N.array(N.object({objectName:N.string().min(1).describe(`Object the attribute is removed from.`),attributeName:N.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:N.array(N.object({objectName:N.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:N.array(N.object({objectName:N.string().min(1).describe(`Object the renamed attribute belongs to.`),from:N.string().min(1).describe(`Current attribute name. Must already exist and not be a system attribute.`),to:Fa.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:[]}),Ha=N.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.`),Ua=N.object({objects:N.array(Ba).default([]),attributes:N.array(Ra).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>W.objectAdditions&&t.addIssue({code:`too_big`,origin:`array`,maximum:W.objectAdditions,inclusive:!0,path:[`additive`,`objects`,W.objectAdditions],message:`A schema plan can add at most ${W.objectAdditions} objects`});let n=mutationPaths(e);n.length>W.totalMutations&&t.addIssue({code:`too_big`,origin:`array`,maximum:W.totalMutations,inclusive:!0,path:n[W.totalMutations],message:`A schema plan can contain at most ${W.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}),N.NEVER;let r=new TextEncoder().encode(j(e)).byteLength;return r>W.serializedBytes?(t.addIssue({code:`too_big`,origin:`string`,maximum:W.serializedBytes,inclusive:!0,path:[],message:`A schema plan can serialize to at most ${W.serializedBytes} UTF-8 bytes; received ${r}`}),N.NEVER):e}const Wa=N.object({schemaPlanVersion:N.literal(2).describe(`Required proposal contract version.`),summary:Ha,additive:Ua,destructive:Va}).strict().superRefine(addPlanLimitIssues),Ga=Object.assign(N.preprocess(boundSerializedPlanInput,Wa),{shape:Wa.shape}),Ka=N.object({schemaPlanVersion:N.literal(2),summary:Ha,additive:Ua,destructive:Va}).strict().superRefine(addPlanLimitIssues),qa=N.preprocess(boundSerializedPlanInput,Ka);function reject$1(e,t){throw new D(t,[{path:e,message:t}])}function exhaustive(e){throw new D(`Unsupported schema reference variant ${String(e)}`,[])}function collectSchemaReferences(e){let t=new Map(e.objects.map(e=>[e.name,e])),n=[];function visitor(e,r,i){function add(a,o,s){(a.kind===`object`?t.has(a.object):a.kind!==`attribute`||t.get(a.object)?.attributes.some(e=>e.name===a.attribute))||reject$1([...r,...s],`Unknown schema reference ${JSON.stringify(a)}`),n.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,n,i,a,o){attribute(e,n,i,a);let s=t.get(e)?.attributes.find(e=>e.name===n);return s?.type!==`relation`&&reject$1([...r,...a],`Invalid schema reference path "${o}"`),(s.targets.length!==1||s.targets[0].object===`*`)&&reject$1([...r,...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}}e.objects.forEach((e,t)=>{let n=[`objects`,String(t)],r=visitor({kind:`object`,object:e.name},n);for(let t of[`labelExpression`,`embeddingExpression`]){let n=e[t];if(n)for(let i of extractAttributeNames(n))r.attributePath(e.name,i.split(`.`),`business`,[t])}e.attributes.forEach((t,r)=>{let i=[...n,`attributes`,String(r)],a=visitor({kind:`attribute`,object:e.name,attribute:t.name},i);switch(t.type){case`relation`:t.targets.forEach((e,t)=>{if(e.object!==`*`&&a.add({kind:`object`,object:e.object},`structural`,[`targets`,String(t),`object`]),e.displayTemplate)for(let n of extractAttributeNames(e.displayTemplate))a.attributePath(e.object,n.split(`.`),`business`,[`targets`,String(t),`displayTemplate`]);for(let n of Object.keys(e.filter??{}))a.attribute(e.object,n,`business`,[`targets`,String(t),`filter`,n])});break;case`formula`:{let n;try{n=A(t.expression)}catch(e){reject$1([...i,`expression`],e instanceof Error?e.message:String(e))}a.formula(e.name,n,[`expression`]),visitOptions(t,a);break}case`rollup`:{let n=t.relationPath??t.relationAttribute,r=e.name;for(let e of n.split(`.`))r=a.traverse(r,e,`computed`,[t.relationPath===void 0?`relationAttribute`:`relationPath`],n);t.targetAttribute!==void 0&&a.attributePath(r,t.targetAttribute.split(`.`),`computed`,[`targetAttribute`]),visitOptions(t,a);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(t)}})});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,n,r){visitor({kind:`view`,object:e.object,view:e.name},n,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},[...n,`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=t.get(e.object),u=r.kind!==`related`||!l?void 0:findRelationAttribute(l,r.relation),d=[`columns`,String(c),`relationProperty`];u||reject$1([...n,`contents`,String(a),...d],`Relation property columns require a relation source`),u.properties?.definitions.some(e=>e.name===i.relationProperty)||reject$1([...n,`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 e.views.forEach((e,t)=>viewReferences(e,[`views`,String(t)])),e.retainedViews?.forEach(({definition:e,layer:t},n)=>viewReferences(e,[`retainedViews`,String(n),`definition`],t)),n}const Ja=/^[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,n){throw new D(n,[{path:[...e.split(`.`),t],message:n}])}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);(!Ja.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,r,i){e.bilateral?.cardinality&&e.bilateral.cardinality!==t.cardinality&&reject(r,`cardinality`,`${n} declares ${r} as ${e.bilateral.cardinality}, but ${r} declares ${t.cardinality}`),t.bilateral?.cardinality&&t.bilateral.cardinality!==e.cardinality&&reject(n,`cardinality`,`${r} declares ${n} as ${t.bilateral.cardinality}, but ${n} declares ${e.cardinality}`),e.bilateral?.label&&e.bilateral.label!==t.label&&reject(r,`label`,`${n} declares a different label for ${r}`),t.bilateral?.label&&t.bilateral.label!==e.label&&reject(n,`label`,`${r} declares a different label for ${n}`),e.properties&&t.properties&&!ln(e.properties,t.properties)&&!i&&reject(r,`properties`,`${n} and ${r} declare different qualified properties`),e.bilateral?.storageOwner===t.bilateral?.storageOwner&&e.bilateral?.storageOwner!==void 0&&reject(r,`storageOwner`,`${n} and ${r} 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,r,i,a){a.has(n)&&a.has(r)&&!ln(e.properties,t.properties)&&reject(r,`properties`,`${n} and ${r} edit different qualified properties`);let o=a.has(n)||i.has(n)&&!i.has(r)&&!a.has(r),s=a.has(r)||i.has(r)&&!i.has(n)&&!a.has(n),c=o?e.properties:s?t.properties:e.properties??t.properties;c?(e.properties=structuredClone(c),t.properties=structuredClone(c)):(delete e.properties,delete t.properties)}function reconcileRelationAttributes(e){let t=structuredClone(e.objects),n=new Map;for(let e of t){if(n.has(e.name))throw new w(`object`,e.name);n.set(e.name,e);let t=new Set;for(let n of e.attributes){if(t.has(n.name))throw new w(`attribute`,n.name);t.add(n.name),stripUntrustedPairMetadata(n)}}let r=remapExistingPairs(e.existingPairs??[],e.addressRenames??[]),i=validateExistingPairs(r),a=new Set(r.flatMap(e=>e.generatedAddresses)),o=new Set(e.propertyEditAddresses??[]),s=new Set(e.explicitAddresses??t.flatMap(e=>e.attributes.filter(t=>!a.has(`${e.name}.${t.name}`)).map(t=>`${e.name}.${t.name}`))),c=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)),l=new Map,u=new Map;for(let{object:t,attribute:a,address:d}of c){let c=a.bilateral?.object;(!c||c===`*`||a.targets.length!==1||a.targets[0]?.object!==c)&&reject(d,`targets`,`Bilateral target of ${d} must be one concrete object`);let f=n.get(c);f||reject(d,`bilateral`,`Unknown inverse object ${c} for ${d}`);let p=`${c}.${a.bilateral?.attribute}`,m=d===p;m&&a.cardinality!==`many`&&reject(d,`cardinality`,`Symmetric self relation ${d} must be many`),m&&a.bilateral?.cardinality&&a.bilateral.cardinality!==a.cardinality&&reject(d,`bilateral`,`Symmetric self relation ${d} needs matching cardinality`);let h=pairedAddresses(d,p),g=pairKey(h);if(l.has(g))continue;let _=f.attributes.find(e=>e.name===a.bilateral?.attribute);if(_&&!isReciprocal(_,t.name,a.name))throw new w(`attribute`,p);let ee=!(_&&s.has(p));_||(_=generateInverse(a,t.name,f.attributes.length),f.attributes.push(_));let v=_;!m&&s.has(d)&&s.has(p)&&checkExplicitDeclarations(a,v,d,p,o.has(d)!==o.has(p));let y=i.get(g),b=y?.id??e.nextPairId(h),x=r.find(e=>e.id===b&&pairKey(e.addresses)!==g);(!Ja.test(b)||x||u.has(b)&&u.get(b)!==g)&&reject(d,`pair`,`Invalid or duplicate pair identity for ${d} and ${p}`),u.set(b,g);let S=m?d:chooseOwner(a,v,d,p,y,ee);a.bilateral&&v.bilateral||reject(d,`bilateral`,`Missing reciprocal configuration for ${d} and ${p}`),a.bilateral={...a.bilateral,cardinality:v.cardinality,label:v.label,storageOwner:S===d},v.bilateral={...v.bilateral,cardinality:a.cardinality,label:a.label,storageOwner:S===p},reconcileProperties(a,v,d,p,s,o),a.metadata={...a.metadata,relationPairId:b},v.metadata={...v.metadata,relationPairId:b},l.set(g,{id:b,addresses:h,ownerAddress:S,generatedAddresses:h.filter(e=>!s.has(e)),...m?{symmetric:!0}:{}})}return{objects:t,pairs:[...l.values()].sort((e,t)=>e.addresses[0].localeCompare(t.addresses[0]))}}const G=N.number().finite().nonnegative(),Ya=N.enum(Yn),Xa=N.enum(Xn),Za=N.enum(Zn),Qa=N.object({provider:Ya,model:N.string().min(1)}).strict(),$a=N.object({speed:Xa.optional(),reasoning:Za.optional()}).strict(),eo=N.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),to=N.object({model:Qa.optional(),speed:Xa.optional(),reasoning:Za.optional(),imageModel:eo.optional()}).strict(),no=to.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`}),ro=N.object({model:Qa.nullable().optional(),speed:Xa.nullable().optional(),reasoning:Za.nullable().optional(),imageModel:eo.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`}),io=N.object({label:N.string(),denied:N.boolean().optional(),deletion:N.object({target:N.string().optional(),count:G.optional(),restorableDays:G.optional()}).strict().optional(),counts:N.record(N.string(),G).optional(),warnings:N.array(N.string()).optional()}).strict(),ao=N.union([N.object({type:N.literal(`text`),text:N.string()}).strict(),N.object({type:N.literal(`reasoning`),text:N.string()}).strict(),N.object({type:N.literal(`system`),code:N.enum(er)}).strict(),N.object({type:N.literal(`error`),error:N.string(),errorClass:N.string().optional()}).strict(),N.object({type:N.literal(`tool`),toolCallId:N.string(),name:N.string(),args:N.record(N.string(),N.unknown()),result:N.unknown().optional(),error:N.string().optional(),errorCode:N.enum([`output_limit_reached`,`interrupted`,E.INVALID_TOOL_INPUT]).optional(),state:N.enum([`streaming`,`running`,`completed`,`error`,`pending`,`approval-requested`,`approval-responded`,`approval-dispatched`]),durationMs:G.optional(),approvalId:N.string().optional(),approvalImpact:io.optional(),approved:N.boolean().optional(),approvalReason:N.string().optional(),approvalRelaxableByAuto:N.boolean().optional()}).strict(),N.object({type:N.literal(`file`),fileId:N.string(),name:N.string(),mimeType:N.string()}).strict(),N.object({type:N.literal(`compaction`),state:N.literal(`in-progress`),reason:N.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:G.optional(),reportedTokens:G.optional()}).strict(),N.object({type:N.literal(`compaction`),state:N.literal(`completed`),tokensBefore:G,tokensAfter:G,tokensSaved:G,strategy:N.enum([`no-op`,`summary`,`truncation`]),durationMs:G,summary:N.string().optional()}).strict(),N.object({type:N.literal(`compaction`),state:N.literal(`failed`),reason:N.string(),durationMs:G.optional()}).strict()]),oo=N.object({id:N.string(),name:N.string(),mimeType:N.string(),size:G}).strict(),so=N.object({id:N.string(),type:N.string().transform(e=>e),entityId:N.string(),label:N.string(),objectName:N.string().optional(),startIndex:G,endIndex:G}).strict(),co=N.object({provider:Ya,model:N.string(),maxTokens:G.optional(),contextWindow:G.optional()}).strict(),lo=N.union([N.date(),N.string().datetime({offset:!0}).transform(e=>new Date(e))]),uo=N.object({id:N.string(),sessionId:N.string(),tenantId:N.string().optional(),runId:N.string().optional(),role:N.enum([`user`,`assistant`,`system`,`tool`]),parts:N.array(ao),attachments:N.array(oo).optional(),mentions:N.array(so).optional(),model:co.optional(),tokenUsage:N.object({input:G,output:G}).strict().optional(),metadata:N.record(N.string(),N.unknown()).optional(),createdAt:lo}).strict(),fo=N.object({id:N.string(),description:N.string(),status:N.enum([`pending`,`in_progress`,`completed`,`blocked`]),result:N.string().optional(),updatedAt:G.optional()}).strict(),po=N.object({id:N.string(),sessionId:N.string(),status:N.enum([`active`,`completed`,`abandoned`]),todos:N.array(fo),version:G,createdAt:N.string(),updatedAt:N.string(),completedAt:N.string().optional()}).strict(),mo={"session-named":N.object({name:N.string()}).strict(),"compaction-start":N.object({reason:N.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:G.optional(),reportedTokens:G.optional()}).strict(),"compaction-end":N.object({tokensBefore:G,tokensAfter:G,tokensSaved:G,strategy:N.enum([`no-op`,`summary`,`truncation`]),durationMs:G,summary:N.string().optional()}).strict(),"compaction-failed":N.object({reason:N.string()}).strict(),usage:N.object({messageId:N.string().min(1).optional(),inputTokens:G,outputTokens:G,totalTokens:G,cacheReadTokens:G.optional(),cacheCreationTokens:G.optional(),contextWindow:G,residentTokens:G,utilization:N.number().finite().min(0).max(1),costUsd:G.optional()}).strict(),"message-persisted":N.object({message:uo}).strict(),"message-updated":N.object({message:uo}).strict(),"todo-plan-update":N.object({plan:po}).strict(),"approval-context":N.object({approvalId:N.string(),toolCallId:N.string(),impact:io.optional(),relaxableByAuto:N.boolean().optional()}).strict(),"session-state":N.object({state:N.object({phase:N.enum([`queued`,`running`,`parked`,`terminal`]),parkedOn:N.enum([`human`,`agents`]).optional(),humanRequestIds:N.array(N.string()).optional(),outcome:N.enum([`completed`,`failed`,`cancelled`,`timeout`,`expired`]).optional()}).strict(),version:N.number().int().positive(),updatedAt:N.string().datetime({offset:!0})}).strict()};function isAgentUIDataName(e){return e in mo}function agentUIValidationError(e){return new D(`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 D(`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 D(`Invalid agent UI message chunk`,[{path:[`type`],message:`Expected agent data chunk type`,code:`invalid_value`}]);let n=t.slice(5);if(!isAgentUIDataName(n))throw new D(`Invalid agent UI message chunk`,[{path:[`type`],message:`Unknown agent UI data type: ${n}`,code:`invalid_value`}]);let r=N.object({type:N.literal(`data-${n}`),id:N.string().optional(),data:mo[n],transient:N.boolean().optional()}).strict().safeParse(e);if(!r.success)throw agentUIValidationError(r.error.issues);return r.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 K={kind:`target-missing`};var DraftRefusalError=class extends D{constructor(e,t,n=[]){super(e,n),this.refusal=t}};const ho=[`pluralLabel`,`description`,`labelExpression`,`embeddingExpression`];function draftObjectSettings(e){return Object.fromEntries(ho.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{...e.config,id:e.id,objectId:e.objectId,name:e.name,label:e.label,type:e.attributeType}}function toDraftableAttribute(e,t){let{id:n,objectId:r,name:i,label:a,type:o,...s}=e;return{id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:s}}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 go={id:N.string().min(1).describe(`Your id, echoed back`),note:N.string().trim().min(1).max(160).optional().describe(`One first-person sentence, in the person's language: what you do and why, ≤160 chars`)},q={...go,objectName:N.string().min(1).describe(`Object`),viewName:N.string().min(1).describe(`View API name`)},J={...q,contentName:N.string().min(1).describe(`Content API name`)},_o=N.union([N.object({before:N.string().min(1).describe(`Place immediately before this content name`)}).strict(),N.object({after:N.string().min(1).describe(`Place immediately after this content name`)}).strict(),N.object({end:N.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,n){let r=[{path:e,message:t}];throw n?new DraftRefusalError(t,n,r):new D(t,r)}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`,{kind:`view-missing`,objectName:t.objectName,viewNames:e.views.filter(e=>e.object===t.objectName).map(e=>e.name)}),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`,K),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`,K),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 vo=N.unknown().transform((e,t)=>{let n=C.safeParse(typeof e==`object`&&e?{...e,name:`candidate`}:e);if(!n.success){for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message});return N.NEVER}let r=typeof e==`object`&&e&&`name`in e?e.name:void 0;return{...n.data,name:r}}),yo=N.object({...J,type:N.literal(`replace_view_content`),definition:vo}).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}}),bo=C.describe(`The whole content definition.`),xo=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:yo,wire:N.object({...J,type:N.literal(`replace_view_content`),definition:bo}).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}}))}),So=N.object({...q,type:N.literal(`add_view_content`),content:bo,target:_o.describe(`Where to place the new content within its placement zone`)}).strict(),addFocus=e=>({...viewFocus(e),contentName:e.content.name}),Co=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:So,focus:addFocus,presentation:definePresentation(addFocus,`structural`),describe:e=>`Add ${e.content.name}`,apply:(e,t,n)=>change(e,t,n,e=>{if(Object.hasOwn(e.authoring.contents,t.content.name))throw new w(`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 n=placed(e.contents,t.content,t.target);return setOrder(e,n,[t.content.placement]),{...e,revision:e.revision+1,contents:n,contentIds:{...e.contentIds,[t.content.name]:JSON.stringify([`draft-content`,t.id])},contentRevisions:{...e.contentRevisions,[t.content.name]:1}}})}),wo=N.object({...J,type:N.literal(`remove_view_content`)}).strict(),To=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:wo,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}})}),Eo=N.object({...J,type:N.literal(`move_view_content`),placement:N.enum([`main`,`aside`]).describe(`The placement zone to move the content into`),target:_o.describe(`Where to place the content within that placement zone`)}).strict(),Do=defineOperation({type:`move_view_content`,summary:`Reorders or moves a content to a different placement; the aside rule applies.`,schema:Eo,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)}}})}),Oo=N.object({...q,type:N.literal(`update_view_metadata`),changes:N.object({label:N.string().min(1).optional().describe(`New label for the view`),description:N.string().optional().describe(`New description for the view`),icon:O.nullable().optional().describe(`New icon; null clears it`)}).strict().refine(e=>Object.keys(e).length>0).describe(`≥1 change`)}).strict(),ko=defineOperation({type:`update_view_metadata`,summary:`Updates a view's label, description, or icon (null clears the icon).`,schema:Oo,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}})}),Ao=N.string().refine(e=>e.trim().length>0,`API name must not be blank`),jo=N.object({...q,type:N.literal(`rename_view`),newName:Ao.describe(`New API name for the view`)}).strict(),renameViewFocus=e=>({objectName:e.objectName,viewName:e.newName}),Mo=defineOperation({type:`rename_view`,summary:`Renames a view; refused on a code-declared name — change it in the declaration.`,schema:jo,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}))}),No=N.object({...J,type:N.literal(`rename_view_content`),newName:Ao.describe(`New API name for the content`)}).strict(),renameContentFocus=e=>({...viewFocus(e),contentName:e.newName}),Po=defineOperation({type:`rename_view_content`,summary:`Renames a content; refused on a code-declared name — change it in the declaration.`,schema:No,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}}})}),Fo=N.object({...J,type:N.literal(`reset_view_content`)}).strict(),Io=defineOperation({type:`reset_view_content`,summary:`Resets a content back to its code-declared source; only works when one exists.`,schema:Fo,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}})})}),Lo=N.object({...q,type:N.literal(`reset_view_order`),placement:N.enum([`main`,`aside`]).describe(`The placement zone to reset to source order`)}).strict(),Ro=defineOperation({type:`reset_view_order`,summary:`Resets a placement zone's order to its code-declared source, if one exists.`,schema:Lo,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}})}),zo=N.discriminatedUnion(`type`,[yo,So,wo,Eo,Oo,jo,No,Fo,Lo]),Y=[xo,Co,To,Do,ko,Mo,Po,Io,Ro];function findObject(e,t){return e.objects.find(e=>e.id===t)}const Bo=new Set([`formula`,`rollup`]);function isComputedAttribute(e){return Bo.has(e.attributeType)}const Vo={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 Vo?Vo[e]:void 0}function requireObject(e,t){let n=findObject(e,t);if(!n)throw new DraftRefusalError(`Object "${t}" is not in the draftable state`,K);return n}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(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 D(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(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 n=bilateralDeclarationOf(e);if(n===void 0||untouched(e))continue;let r=t.objects.find(t=>t.id===e.objectId)?.name??e.objectId,i=t.objects.find(e=>e.name===n.object),a=t.attributes.find(e=>e.objectId===i?.id&&e.name===n.attribute),o=`relation "${r}.${e.name}" declares inverse "${n.object}.${n.attribute}"`;if(a===void 0)throw new D(`${o}, which object "${n.object}" does not have; draft it first`,[]);if(a.attributeType!==`relation`)throw new D(`${o}, which is not a relation`,[]);let s=bilateralDeclarationOf(a);if(!(relationTargets(a).some(e=>e.object===r)&&(untouched(a)?s===void 0||s.object===r&&s.attribute===e.name:s?.object===r&&s.attribute===e.name)))throw new D(`${o}, which does not point back to "${r}.${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,t,n,r){let i=r.filter(e=>e.objectId===n.id).filter(e=>x(toAttribute(e)).presentation.formField).map(e=>({attribute:e.name})),a=e===`collection`?[{name:`all`,type:`collection`,placement:`main`,label:`All`,layout:`table`,source:{object:n.name}}]:i.length?[{name:`form`,type:`form`,placement:`main`,label:`Details`,groups:[{name:`general`,label:`General`,fields:i}]}]:[{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:!0,contents:a,authoring:workspaceViewAuthoring(a),revision:1,contentIds:Object.fromEntries(a.map(e=>[e.name,JSON.stringify([`draft-content`,t,e.name])])),contentRevisions:Object.fromEntries(a.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,n,r,i=!1){let a=toAttribute(t),o=r&&toAttribute(r),s=r&&bilateralDeclarationOf(r),c=bilateralDeclarationOf(t);if(s&&(s.object!==c?.object||s.attribute!==c?.attribute))throw new D(`Changing a bilateral address requires removing the existing pair first`,[]);if(a.type!==`relation`||!a.bilateral)return e;let l=e.objects.find(e=>e.id===t.objectId),u=e.objects.find(e=>e.name===a.bilateral?.object);if(!(l&&u))throw new D(`Both objects must exist before materializing a relation pair`,[]);let d=`${l.name}.${t.name}`,f=a.bilateral.attribute,p=`${u.name}.${f}`,m=e.attributes.find(e=>e.objectId===u.id&&e.name===f),h=o?.metadata?.relationPairId,g=typeof h==`string`?h:draftEntityIdFor(`relation-pair`,`${n}:${t.id}`),_=[d,p].sort(),ee=typeof h==`string`?{id:g,addresses:_,ownerAddress:o?.type===`relation`&&o.bilateral?.storageOwner===!1?p:d,generatedAddresses:[],...d===p?{symmetric:!0}:{}}:void 0,v=reconcileRelationAttributes({objects:[...new Map([l,u].map(e=>[e.id,e])).values()].map(e=>({name:e.name,attributes:[t,...m&&m.id!==t.id?[m]:[]].filter(t=>t.objectId===e.id).map(toAttribute)})),existingPairs:ee?[ee]:[],...r&&!i?{explicitAddresses:[d],propertyEditAddresses:[d]}:{},nextPairId:()=>g}),y=new Map;for(let n of v.objects){let a=n.name===l.name?l.id:u.id;for(let o of n.attributes){let n=e.attributes.find(e=>e.objectId===a&&e.name===o.name),s=n?.id===t.id?r??n:n,c={...preserveDeclarationHints(o,n&&toAttribute(n)),metadata:{...o.metadata,...s&&isGeneratedDraftRelation(s)&&!(i&&n?.id===t.id)||!n?{relationGenerated:!0}:{}},id:n?.id??draftEntityIdFor(`relation-attribute`,`${g}:${a}:${o.name}`),...n?{}:{order:e.attributes.filter(e=>e.objectId===a).length}};y.set(`${a}.${o.name}`,toDraftableAttribute(c,a))}}let b=e.attributes.map(e=>{let t=`${e.objectId}.${e.name}`,n=y.get(t);return y.delete(t),n??e});return b.push(...y.values()),{...e,attributes:b,views:e.views.map(e=>{let t=[l,u].find(t=>t.name===e.object);return e.derived&&t?regenerateDerived(e,t,b):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 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,n){let r=n.config??{},i=n.name;if(r.relationPath!==void 0)throw new D(`rollup "${i}": relationPath is not supported yet`,[]);let a=r.relationAttribute;if(typeof a!=`string`||a.length===0)throw new D(`rollup "${i}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let o=e.attributes.find(e=>e.objectId===t.id&&e.name===a&&e.attributeType===`relation`);if(!o)throw new D(`rollup "${i}" needs a relation attribute; "${a}" is not a relation of object "${t.name}"`,[]);let s=relationTargetObjectName(o);if(s===void 0){let e=relationTargets(o).filter(e=>e.object!==`*`).length;throw new D(`rollup "${i}" needs a relation with one target object; "${a}" targets ${e}`,[])}if(r.function===`count`)return;let c=e.objects.find(e=>e.name===s),l=r.targetAttribute;if(l===void 0)throw new D(`rollup "${i}" needs a targetAttribute: "${r.function}" aggregates one attribute of object "${s}"`,[]);if(!(c!==void 0&&e.attributes.some(e=>e.objectId===c.id&&e.name===l)))throw new D(`rollup "${i}" targets attribute "${l}", which object "${s}" 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 n=requireObject(e,t.objectId);if(t.attributeType===`relation`){for(let n of relationTargets(t))if(n.object!==`*`&&!e.objects.some(e=>e.name===n.object))throw new D(`object "${n.object}" is unknown; create it first`,[]);let n=bilateralDeclarationOf(t)?.object;if(n!==void 0&&n!==`*`&&!e.objects.some(e=>e.name===n))throw new D(`object "${n}" 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,n,t),computedPlanOf(e,t);else return;assertAcyclicComputed(compilablePlansOf(e,t.objectId))}const X={...go,objectId:N.string().uuid().describe(`The object this operation acts on`)},Ho=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:N.object({...X,objectId:N.string().uuid().describe(`Stable id for the new object; the server mints one when omitted`),type:N.literal(`add_object`),name:Kt.describe("kebab-case plural API name (`purchase-orders`)"),label:N.string().min(1).describe(`Label people see`),icon:N.string().min(1).optional().describe(`Icon name`)}),apply:(e,t)=>{if(e.objects.some(e=>e.name===t.name))throw new D(`Object "${t.name}" already exists`,[]);if(e.objects.some(e=>e.id===t.objectId))throw new D(`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,...defaultViewsFor(n,e.attributes)]}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Crée l'objet « ${e.label} »`}),Uo=N.object({...X,type:N.literal(`update_object`),changes:N.object({label:N.string().min(1).optional().describe(`New label`),icon:N.string().min(1).optional().describe(`New icon name from search_icons`),pluralLabel:N.string().optional().describe(`New label for many records; "" clears it`),description:N.string().optional().describe(`What this object holds`),labelExpression:I.optional().describe(`Titles every record; syntax in <expressions>`),embeddingExpression:N.literal(``).or(I).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}),Wo=defineOperation({type:`update_object`,summary:`Updates an object's settings: label, icon, pluralLabel, description, labelExpression, embeddingExpression.`,schema:Uo,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)}),Go={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])=>Go[e]?.(String(t))).filter(e=>e!==void 0);return t.length>0?t.join(` · `):`Modifie l'objet`}const Ko=defineOperation({type:`remove_object`,summary:`Removes an object; refused while a relation attribute targets it — remove it first.`,schema:N.object({...X,type:N.literal(`remove_object`)}),apply:(e,t)=>{requireObject(e,t.objectId);let n=e.objects.find(e=>e.id===t.objectId)?.name,r=e.attributes.filter(e=>e.objectId!==t.objectId&&e.attributeType===`relation`&&relationTargets(e).some(e=>e.object===n));if(r.length>0){let ownerOf=t=>e.objects.find(e=>e.id===t.objectId)?.name;throw new DraftRefusalError(`object "${n}" is targeted by attribute "${ownerOf(r[0])}.${r[0].name}"; remove that attribute first`,{kind:`object-targeted`,blockers:r.flatMap(e=>{let t=ownerOf(e);return t?[{ownerObjectName:t,attribute:e.name}]:[]})})}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!==n)}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Supprime l'objet ${e.objectId}`}),qo=Vn;function assertConfigParses(e,t){try{Dt(e,t)}catch(e){throw e instanceof D?new D(e.message,e.errors.map(e=>({...e,path:[`config`,...e.path??[]]}))):e}}const Jo=N.object({...X,type:N.literal(`add_attribute`),attributeId:N.string().min(1),name:Et,label:N.string().min(1),attributeType:N.enum(qo),config:N.record(N.string(),N.unknown()).optional()}).superRefine((e,t)=>{try{assertConfigParses(e.attributeType,e.config??{})}catch(e){if(e instanceof D){for(let n of e.errors)t.addIssue({code:`custom`,message:n.message,path:[...n.path]});return}throw e}}),Yo={...go,type:N.literal(`add_attribute`),attributeId:N.string().min(1).describe(`Stable attribute id`),name:Et.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),label:N.string().min(1).describe(`Label people see`)},Xo=Object.fromEntries(Lt.map(e=>[e,!0])),Zo=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],Qo=N.object(Zo.reduce((e,t)=>(Object.assign(e,Tt(t).omit(Xo).shape),e),{})).strict(),$o=qo.filter(e=>!Zo.includes(e)),es=Object.fromEntries(Zo.map(e=>[e,new Set(Object.keys(Tt(e).omit(Xo).shape))])),ts=It(es,`config key`);function refuseForeignSimpleConfigKeys(e,t){ts(e.attributeType,e.config,t,[`config`])}function wireConfigFor(e){let t=Tt(e).omit(Xo);return(e===`relation`||e===`document`?t.extend({properties:zt.optional()}):t).strict()}const ns=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:Jo,wire:N.discriminatedUnion(`attributeType`,[N.object({...Yo,objectId:N.string().uuid(),attributeType:N.enum(Zo).describe(`Attribute type`),config:Qo.optional().describe(`Configuration of a simple attribute (text, number, date…)`)}).strict().superRefine(refuseForeignSimpleConfigKeys),...$o.map(e=>N.object({...Yo,objectId:N.string().uuid(),attributeType:N.literal(e).describe(`Attribute type`),config:wireConfigFor(e).optional().describe(`Configuration of a ${e} attribute`)}).strict())]),apply:(e,t)=>{let n=requireObject(e,t.objectId),r=e.attributes.find(e=>e.objectId===t.objectId&&e.name===t.name);if(r&&!isGeneratedDraftRelation(r))throw new D(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let i={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 n of e.sampleRecords)n.objectId===t.objectId&&assertRequiredCovered(n.id,i,n.values);let a=withDerivedViews(e,n,r?e.attributes.map(e=>e===r?i:e):[...e.attributes,i]);return assertConfigFolds(a,i),reconcileDraftRelationAttribute(a,i,t.id,r,!0)},focus:attributeFocus,presentation:definePresentation(attributeFocus,`local`),describe:e=>`Ajoute l'attribut « ${e.label} »`}),rs={...X,attribute:Et.describe(`The attribute's API name on this object`)};function requireAttribute(e,t,n,r){let i=requireObject(e,t);if(n===void 0)throw new D(`${r} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let a=e.attributes.find(e=>e.objectId===t&&e.name===n);if(!a)throw new DraftRefusalError(`Attribute "${n}" is not on object "${t}"`,K);return{object:i,attribute:a}}const is=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:N.object({...rs,type:N.literal(`update_attribute`),changes:N.object({label:N.string().min(1).optional().describe(`New label`),config:N.record(N.string(),N.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} »`}),as=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:N.object({...rs,type:N.literal(`remove_attribute`)}),apply:(e,t)=>{let{attribute:n}=requireAttribute(e,t.objectId,t.attribute,`remove_attribute`),r=pairedDraftAttributes(e,n);for(let t of r){let n=requireObject(e,t.objectId),[r]=dependentsOf(e,t.objectId,t.name);if(r!==void 0)throw new D(`attribute "${t.name}" is used by "${r}"; remove that first`,[]);for(let r of e.views){if(r.object!==n.name)continue;let e=handShapedUse(r,t.name);if(e!==void 0)throw new D(`attribute "${t.name}" is used by view "${r.id}" (${e}); remove it from the view first`,[])}let i=e.sampleRecords.find(e=>e.objectId===t.objectId&&t.name in e.values);if(i)throw new D(`Attribute "${t.name}" is still used by sample record "${i.id}"`,[])}let i=e.attributes.filter(e=>!r.includes(e)),a={...e,views:e.views.map(e=>e)};return r.reduce((t,n)=>withDerivedViews(t,requireObject(e,n.objectId),i),a)},focus:existingAttributeFocus,presentation:definePresentation(existingAttributeFocus,`local`),describe:e=>`Supprime l'attribut « ${e.attribute} »`});function assertSampleValue(e,t,n,r){let i=toAttribute(n);try{mn(i)}catch{return}let a=gn(i,r);if(a.success)return;let o=a.errors??[],s=`Sample record "${e}" has an invalid value for "${t}": ${o.map(e=>e.path.length>1?`${e.path.join(`.`)}: ${e.message}`:e.message).join(`, `)}`,c=o.map(e=>({path:e.path,message:e.message}));throw n.attributeType===`relation`&&carriesNonRecordId(r)?new DraftRefusalError(s,{kind:`sample-relation-value`},c):new D(s,c)}function assertRequiredCovered(e,t,n){if(t.config?.required===!0&&t.config?.defaultValue===void 0&&!(t.name in n&&n[t.name]!==void 0))throw new D(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}const os=N.guid();function carriesNonRecordId(e){let t=Array.isArray(e)?e:[e],n=relationValueIds(e);return n.length<t.length||n.some(e=>!os.safeParse(e).success)}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,n,r){let i=e.objects.find(e=>e.name===n);if(!i)return;let a=e.views.some(e=>e.id===defaultViewIdsFor(i.id).list);for(let n of relationValueIds(r)){let r=e.sampleRecords.find(e=>e.id===n);if(r?.objectId!==i.id&&(r!==void 0||a))throw new DraftRefusalError(`sample record "${t}" references unknown sample "${n}"`,{kind:`sample-relation-value`})}}const ss=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:N.object({...X,type:N.literal(`add_sample_record`),recordId:N.string().uuid().describe(`Minted by the server when omitted`),values:N.record(N.string(),N.unknown()).describe("Attribute name → value; currency is `{code,value}`, relation is a record id or name minted here"),publication:N.enum([`preview`,`requested-data`]).optional().describe(`preview = display-only; requested-data = real records asked for`)}),apply:(e,t)=>{let n=requireObject(e,t.objectId);if(e.sampleRecords.some(e=>e.id===t.recordId))throw new D(`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 DraftRefusalError(`Sample record "${t.recordId}" uses unknown attribute "${i}"`,{kind:`sample-unknown-attribute`,objectName:n.name,attributeNames:[...r.keys()]});if(isComputedAttribute(o))throw new D(`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 n of e.sampleRecords){if(n.id===t)continue;let r=relationNamesOf(e,n.objectId);for(let[e,i]of Object.entries(n.values))if(r.has(e)&&relationValueIds(i).includes(t))throw new D(`sample record "${t}" is referenced by sample record "${n.id}"; remove that first`,[])}}const Z=[Ho,Wo,Ko,ns,is,as,ss,defineOperation({type:`remove_sample_record`,summary:`Removes a sample record; refused while another sample still references it.`,schema:N.object({...X,type:N.literal(`remove_sample_record`),recordId:N.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 DraftRefusalError(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,K);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[...Z,...Y]){if(e.has(t.type))throw new w(`architect operation`,t.type);e.set(t.type,t)}return e}const cs=build(),ls=[...cs.keys()];function defOf(e){let t=cs.get(e.type);if(!t)throw new D(`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 D(`An operation must be an object carrying a type`,[]);let t=e.type;if(typeof t!=`string`)throw new D(`An operation's type must be a string`,[]);let n=cs.get(t);if(!n)throw new D(`Unknown operation type "${t}"`,[]);let r=n.schema.safeParse(e);if(!r.success)throw new D(`Operation "${t}" is invalid: ${r.error.issues.map(e=>`${e.path.join(`.`)} ${e.message}`).join(`; `)}`,[]);return r.data}const pair=e=>N.tuple([N.literal(e),N.string()]),us=N.union([N.tuple([N.literal(`content`),N.string(),N.string(),N.string()]),N.tuple([N.literal(`view`),N.string(),N.string()]),N.tuple([N.literal(`attribute`),N.string(),N.string()]),N.tuple([N.literal(`sample`),N.string(),N.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=zo.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:${j(e)}`}const ds=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 n;try{n=JSON.parse(t)}catch{throw new D(`Invalid proposal target key "${t}"`,[])}let r=us.safeParse(n);if(!r.success)throw new D(`Invalid proposal target key "${t}"`,[]);let[i,a,o,s]=r.data,c=e.objects.find(e=>e.id===a);if(i===`object`)return c??null;if(i===`object-name`)return e.objects.find(e=>e.name===a)??null;if(i===`attribute-id`)return e.attributes.find(e=>e.id===a)??null;if(i===`attribute`)return e.attributes.find(e=>e.objectId===a&&e.name===o)??null;if(i===`sample`)return e.sampleRecords.find(e=>e.objectId===a&&e.id===o)??null;if(i===`object-schema`||i===`object-tree`){if(!c)return null;let t=e.attributes.filter(e=>e.objectId===a);return i===`object-schema`?{object:c,attributes:t.toSorted((e,t)=>e.name.localeCompare(t.name))}:{object:c,attributes:t,views:e.views.filter(e=>e.object===c.name),sampleRecords:e.sampleRecords.filter(e=>e.objectId===a)}}let l=e.views.find(e=>e.object===a&&e.name===o);if(!l)return null;if(i===`view`)return{id:l.id,revision:l.revision,definition:{...draftedViewDefinition(l),contents:l.contents.map(({name:e,placement:t})=>({name:e,placement:t}))}};let u=l.contents.find(e=>e.name===s);return s!==void 0&&Object.hasOwn(l.contentIds,s)?{id:l.contentIds[s],revision:l.contentRevisions[s],definition:u??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 architectContentBodyKey(e){let t=architectFocusKey(e);return t===null?null:`body/${t}`}function architectFocusCandidates(e){let t=architectFocusKey(e);if(t===null)return[];let n=e.contentName?architectContentBodyKey(e):null;return n===null?[t]:[t,n]}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 fs={add_object:`major`,remove_object:`major`,add_view_content:`major`,replace_view_content:`major`,reset_view_content:`major`,add_attribute:`normal`,remove_attribute:`normal`,remove_view_content:`normal`,add_sample_record:`normal`,update_object:`minor`,update_attribute:`minor`,update_view_metadata:`minor`,rename_view:`minor`,rename_view_content:`minor`,move_view_content:`minor`,reset_view_order:`minor`,remove_sample_record:`minor`},ps=`normal`;function operationPace(e){return Object.hasOwn(fs,e)?fs[e]:ps}const ms={major:{replay:4e3,live:2500},normal:{replay:2600,live:1800},minor:{replay:1400,live:1100}};function dwellForStep(e,t,n){let r=(ms[e]??ms[ps])[t],i=900+40*(n||0);return Math.min(6e3,Math.max(r,i))}const Q=N.string().min(1),hs=N.union([N.object({objectName:Q,viewName:Q,contentName:Q.optional()}).strict().describe(`Full configuration of a view, or of one content when contentName is given`),N.object({objectId:Q}).strict().describe(`An object with its attributes, by id`),N.object({objectName:Q}).strict().describe(`An object with its attributes`),N.object({objectId:Q,attributeName:Q}).strict().describe(`One attribute's config, by name`),N.object({objectId:Q,attributeId:Q}).strict().describe(`One attribute's config, by id`),N.object({objectId:Q,recordId:Q}).strict().describe(`One sample record`)]);function parseNamedTarget(e){let t=hs.safeParse(e);if(!t.success)throw new D(`Invalid scoped target`,[{path:[`target`],message:`Expected exactly one named target branch`}]);return t.data}const gs=N.object({type:N.literal(`remove_operation`),operationId:N.string().min(1).describe(`The id of a stored operation to drop from the draft`)}),_s=12;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 N.discriminatedUnion(`type`,e)}function isUuidString(e){return e instanceof N.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):N.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=N.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 vs={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of vs[e.shape.type.value]??[]){let r=e.shape[n];r instanceof N.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,N.object({...n,objectName:N.string().min(1).describe(`Object`)}).strict())})}const ys=membersOf(Z,[gs]),bs=membersOf(Y),xs=unionOf(ys),Ss=unionOf(bs),Cs={schema:xs,view:Ss},ws={schema:unionOf(wireMembersOf(Z,[gs])),view:unionOf(wireMembersOf(Y))},Ts=new Map([...Z.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...Y.map(e=>[e.type,`view`])]);function familyOf(e){return Ts.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 x(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,r){let i=new Set(ownAttributes(e,r).filter(e=>e.attributeType===`relation`&&relationTargets(e).some(e=>e.object===t.name)).map(e=>e.name));return viewsOf(e,r,`record`).some(e=>e.contents.some(e=>{if(e.type!==`collection`)return!1;let r=collectionSourceAddress(e.source);return r.kind===`relatedFrom`?r.object===t.name&&r.relation===n.name:r.kind===`related`&&i.has(r.relation)}))}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,t,i,a)&&n.push(`Relation "${i.label}" on "${t.label}" has no reciprocal collection on "${a.label}": add_view_content with source { object: "${t.name}", relation: "${i.name}" } (relatedFrom).`)}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 D(`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 Es=[`draft_schema`],Ds=`discard_architect_draft`,Os=`request_design_review`,ks=`get_architect_draft`,As=[{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:{}}}}],$=N.string().refine(e=>e.trim().length>0,`Must not be blank`),js=N.union([N.tuple([N.literal(`object`),$]),N.tuple([N.literal(`attribute`),$,$]),N.tuple([N.literal(`view`),$,$]),N.tuple([N.literal(`content`),$,$,$])]),Ms=N.object({label:$,pluralLabel:N.string().optional(),description:N.string().optional(),icon:O.optional(),labelExpression:N.string(),embeddingExpression:N.string().optional(),sealed:N.boolean().optional(),toleratedAttributes:N.array($).optional(),metadata:N.record(N.string(),N.unknown()).optional(),schema_version:N.number().int().nonnegative(),migrations:N.array(N.record(N.string(),N.unknown())),documentLayout:N.record(N.string(),N.unknown()).optional()}).strict();function failure(e){throw new D(e,[])}function definitionSchema(e){return N.custom(t=>{let n=N.record(N.string(),N.unknown()).parse(t);for(let t of e[0]===`view`?[`object`,`name`]:[`name`])Object.hasOwn(n,t)&&failure(`Invalid schema state: unrecognized definition key ${t}`);switch(e[0]){case`object`:Ms.parse(n);break;case`attribute`:{let e=N.enum(Vn).parse(n.type);Mt(e).extend({type:N.literal(e),label:$,required:N.boolean().optional(),unique:N.boolean().optional(),icon:O.optional()}).strict().parse(n);break}case`view`:{let{contents:t,...r}=n,i=N.array($).parse(t);new Set(i).size!==i.length&&failure(`Invalid schema state: duplicate content membership`),Ce.parse({...r,object:e[1],name:e[2],contents:[]});break}case`content`:C.parse({...n,name:e[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=N.record(N.string(),N.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 n=N.object({modelVersion:N.literal(1),hashVersion:N.literal(1),tenant:$,sourceFingerprint:N.string().regex(/^[a-f0-9]{64}$/),entries:N.array(N.unknown())}).strict().safeParse(e);if(!n.success){let e=n.error.issues.find(e=>e.code===`unrecognized_keys`);throw e?.code===`unrecognized_keys`&&failure(`Invalid schema state: unrecognized key ${e.keys[0]}`),D.fromZodErrors(n.error.issues.map(e=>({path:e.path.map(String),message:e.message})))}let r=new Set,i=n.data.entries.map(e=>{let t=js.parse(N.object({address:N.unknown()}).parse(e).address),n=JSON.stringify(t);r.has(n)&&failure(`Invalid schema state: duplicate address ${n}`),r.add(n);let i=definitionSchema(t).nullable(),a=t[0]===`object`||t[0]===`attribute`?N.object({id:N.string().uuid(),updatedAt:N.string().datetime()}).strict():N.object({id:N.string().uuid(),revision:N.number().int().nonnegative()}).strict(),o=N.object({address:js,source:i,effective:i,status:N.enum([`source`,`runtime`,`copy`,`suppressed`]),sourceOwner:N.union([N.literal(`core`),N.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{...n.data,entries:i.sort(compareSchemaStateEntries)}}function parseSchemaState(e){try{return parseState(e)}catch(e){throw e instanceof N.ZodError?D.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`:j(n.source)===j(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}}export{ds as ABSENT_TARGET_TOKEN,nr as AGENT_MESSAGE_KIND,tr as AGENT_NOTIFICATION_KIND,ea as AGENT_UI_BATCH_MAX_BYTES,ta as AGENT_UI_BATCH_MAX_ITEMS,Zr as ALLOWED_PROPERTY_TYPES,Ir as ALL_ACTIONS,ls as ALL_OPERATION_TYPES,ni as ALL_PIPES,li as ALL_SYSTEM_RESOURCES,Nr as ARTIFACT_FILE_ROLES,jr as ARTIFACT_KINDS,Bi as ARTIFACT_LIST_VIEW,Ri as ARTIFACT_OBJECT,V as ARTIFACT_OBJECT_NAME,Li as ARTIFACT_PREVIEW_EXTENSION,Mr as ARTIFACT_RETENTIONS,zi as ARTIFACT_VIEW,Ae as ATTRIBUTE_FILTER_OPERATORS,Vn as ATTRIBUTE_TYPES,Wn as AUDIT_ACTIONS,Un as AUDIT_RESOURCE_TYPES,je as AccessDeniedError,AgentBuilder,Me as AttributeInUseError,Ne as AttributeNotFoundError,zn as BEHAVIOR_PROPERTIES,Yr as BYTE_UNIT_LABELS,Kn as CLAIMABLE_SESSION_STATUSES,_a as COMPUTED_FUNCTIONS,va as COMPUTED_FUNCTION_METADATA,ga as COMPUTED_FUNCTION_NAMES,Sa as CONNECTOR_CALLBACK_PARAM,Kr as COUNT_MODES,Pe as ChangeTypeNotSupportedError,ComputedFormulaCompileError,Wt as ComputedFormulaParseError,Fe as ConcurrentModificationError,R as ContentBuilder,ci as DB_COLUMN_FIELDS,vi as DEFAULT_AGENT_EXECUTION_CONFIG,qn as DEFAULT_APPROVAL_POLICY,yr as DEFAULT_DICTATION_LIMITS,ri as DEFAULT_LABEL_FALLBACK,Lr as DEFAULT_MEETING_BOT_DISPLAY_NAME,di as DEFAULT_ROLES,pi as DEFAULT_ROLE_DESCRIPTIONS,fi as DEFAULT_ROLE_LABELS,_i as DEFAULT_ROLE_PERMISSIONS,Rr as DEFAULT_TENANT_SETTINGS,Zt as DEFAULT_VALIDATION_MESSAGES,Sr as DEVICE_CHANNEL_AUTHENTICATE_TIMEOUT_MS,Cr as DEVICE_CHANNEL_IDLE_POLL_MS,Tr as DEVICE_CHANNEL_KEEPALIVE_MS,xr as DEVICE_CHANNEL_MAX_FRAME_BYTES,br as DEVICE_CHANNEL_PATH,wr as DEVICE_CHANNEL_PRESENCE_MS,Er as DEVICE_COMMAND_ERROR_CODES,_r as DICTATION_FINALIZATION_TIMEOUT_MS,dr as DICTATION_FRAME_BYTES,pr as DICTATION_MAX_BUFFER_BYTES,fr as DICTATION_MAX_FRAME_BYTES,mr as DICTATION_MAX_TRANSCRIPT_BYTES,vr as DICTATION_MODEL_ID,gr as DICTATION_PREPARATION_TIMEOUT_MS,ur as DICTATION_SAMPLE_RATE,hr as DICTATION_TICKET_TTL_MS,Ds as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,Xr as DOCUMENT_SYSTEM_ATTRIBUTES,qo as DRAFTABLE_ATTRIBUTE_TYPES,_s as DRAFT_BATCH_LIMIT,ho as DRAFT_OBJECT_SETTINGS,As as DRAFT_SCHEMA_INPUT_EXAMPLES,Es as DRAFT_WRITE_TOOL_NAMES,Ii as DRIVE_LIST_VIEW,Pi as DRIVE_OBJECT,B as DRIVE_OBJECT_NAME,Fi as DRIVE_VIEW,Ie as DestructiveSyncNotAllowedError,DeviceChannelProtocolError,Ar as DeviceChannelServerFrameSchema,kr as DeviceChannelWorkerFrameSchema,DraftRefusalError,w as DuplicateError,$r as EMPTY_VALUE_PLACEHOLDER,qr as ESTIMATED_COUNT_CAP,Aa as FAKE_MEETING_BOT_SIGNATURE_HEADER,Cs as FAMILY_INPUTS,ws as FAMILY_WIRE_INPUTS,Fr as FORM_FORBIDDEN_ATTRIBUTE_TYPES,FlagRegistry,FlagService,Le as ForbiddenError,FormBuilder,FormRegistry,FormRowBuilder,FormStepBuilder,ks as GET_ARCHITECT_DRAFT_TOOL_NAME,xi as GroupBuilder,Rn as IDENTITY_PROPERTIES,Gr as IMAGE_FORMATS,Zn as INFERENCE_REASONING_OPTIONS,Xn as INFERENCE_SPEEDS,Xi as INVENTORY_LIMIT,_t as LIST_VIEW_TAB_VISIBILITIES,na as LIVE_EVENT_TYPES,n as LOCATION_FILTER_PROPERTIES,wa as MAILBOX_LIST_MODES,Ea as MAIL_DRAFT_BODY_MAX_CHARS,Da as MAIL_SUBJECT_MAX_CHARS,Pr as MAX_PRESET_DEPTH,ir as MAX_TODOS,or as MAX_TODO_DESCRIPTION_CHARS,ar as MAX_TODO_ID_CHARS,U as MEETING_ATTRIBUTES,Ui as MEETING_DETAIL_VIEW_ID,qi as MEETING_LIST_VIEW,Vi as MEETING_LIST_VIEW_ID,Gi as MEETING_OBJECT,H as MEETING_OBJECT_NAME,Ki as MEETING_VIEW,Hi as MEETING_WRITE_SOURCE,Ni as MEMORY_LIST_VIEW,Ai as MEMORY_OBJECT,Mi as MEMORY_VIEW,Ca as McpOAuthCompletionMode,Re as MemoryNotFoundError,ze as MigrationTimeoutError,MultiRelationAttributeBuilder,cr as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,lr as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,xt as NATIVE_OBJECT_NAMES,Mn as NOTIFICATION_INBOX_STATES,kn as NOTIFICATION_KINDS,An as NOTIFICATION_PRIORITIES,jn as NOTIFICATION_SENSITIVITIES,Ln as NOTIFICATION_TYPES_V1,In as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,Pn as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,Fn as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,Nn as NOTIFICATION_WORK_STATES,ja as NO_RECORDING,g as NO_VALUE_OPERATORS,cn as NonJsonValueError,NoopGeocodingAdapter,Be as NotFoundError,Ve as NotImplementedError,Kt as OBJECT_NAME_SCHEMA,$n as OPEN_TOOL_PART_STATES,fs as OPERATION_PACE,cs as OPERATION_REGISTRY,o as OPERATORS_BY_TYPE,ya as OPERATOR_SPECS,ObjectBuilder,He as ObjectNotFoundError,Ue as ObjectReferencedError,We as OrphanSystemAttributeError,ms as PACE_DWELL_MS,ti as PIPES_WITH_ARGS,Bn as PRESENTATION_PROPERTIES,Yn as PROVIDER_NAMES,Ge as ProtectedResourceError,Ke as ProtectedRoleError,Qr as QUALIFIED_SEPARATOR,Jr as QUOTA_KEYS,Oa as RECORDING_OVERRIDES,ka as RECORDING_POLICIES,si as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,Hn as RELATION_TARGET_ANY,ue as REMOVED_OPERATOR_REPLACEMENTS,gs as REMOVE_OPERATION_SCHEMA,Ta as REPLY_MODES,Os as REQUEST_DESIGN_REVIEW_TOOL_NAME,vt as RESERVED_ATTRIBUTE_NAMES,bt as RESERVED_OBJECT_NAMES,mt as RESOURCE_VISIBILITIES,qe as RecordNotFoundError,Je as RecordReferencedError,Ye as RepositoryError,Xe as ReservedObjectNameError,Ze as RoleNotFoundError,Nt as SCHEMA_LIMITS,Z as SCHEMA_OPERATIONS,xs as SCHEMA_OPERATION_INPUT,W as SCHEMA_PLAN_LIMITS,Na as SCHEMA_SOURCE_ID_PATTERN,sr as SESSION_STATE_STREAM_ID,Gn as SESSION_TERMINAL_STATUSES,ei as SIMPLE_PIPES,Ht as SIMPLE_PROPERTY_TYPES,Ei as SKILL_CONTENT_TEMPLATE,ki as SKILL_LIST_VIEW,Di as SKILL_OBJECT,Oi as SKILL_VIEW,yi as STANDARD_SCHEMA_VENDOR,oe as SYNONYM_ALIASES,re as SYSTEM_ATTRIBUTES,_ as SYSTEM_ATTRIBUTE_I18N_KEYS,ht as SYSTEM_FIELD_NAMES,be as SYSTEM_FILTER_ATTRIBUTE_TYPES,er as SYSTEM_PART_CODES,L as SYSTEM_RESOURCES,ui as SYSTEM_RESOURCE_LABELS,T as SchemaError,E as SchemaErrorCode,Qe as SchemaPlanNotFoundError,$e as SearchBackendError,SingleRelationAttributeBuilder,et as StorageError,tt as SyncCascadeError,nt as SyncConflictError,rt as SyncError,it as SystemEntityImmutableError,zr as TENANT_INVITATION_DEFAULT_TTL_MS,Vr as TENANT_INVITATION_MAX_TTL_MS,Br as TENANT_INVITATION_MIN_TTL_MS,Hr as TENANT_INVITATION_RESEND_INTERVAL_MS,Jt as TEXT_FORMAT_PATTERNS,xa as TODAY_DEFAULT,Jn as TODO_PLAN_STATUSES,rr as TODO_STATUSES,Qn as TOOL_APPROVAL_STATES,Ur as USER_STATUSES,Wr as USER_WORK_POSTURES,Y as VIEW_OPERATIONS,Ss as VIEW_OPERATION_INPUT,D as ValidationError,bi as ViewBuilder,Lt as WIRE_OMITTED_CONFIG_KEYS,accessLevelToActions,actionsToAccessLevel,agent,agentDataChunk,agentDisplayName,$a as agentInferencePreferencesSchema,oo as agentMessageAttachmentSchema,ao as agentMessagePartSchema,to as agentSessionInferenceOverridesInputSchema,no as agentSessionInferenceOverridesSchema,uo as agentSessionMessageSchema,agentUIValidationError,applyOperations,applyPipes,applyRelationProps,architectContentBodyKey,architectDraftChannelKey,architectFocusCandidates,architectFocusKey,un as asTenantId,sn as asUserId,assertAcyclicComputed,assertAcyclicComputedDependencies,assertBilateralPairs,assertCustomAgentUIMessageChunk,assertSchemaSourceId,Bt as attributeConfigSchemas,attributeInventory,bilateralDeclarationOf,booleanFlag,buildAgentFallbackTitle,buildPermissionFlags,buildPropertySchema,buildQualifiedAttribute,j as canonicalStringify,zo as canonicalViewOperationSchema,r as canonicalizeFilterValue,capped,checkbox,collectContentViewCatalogue,_e as collectQualifiedRuleIssues,collectSchemaReferences,ve as collectionContentSourceSchema,collectionContentsOf,collectionSourceAddress,collectionSourceAddressOf,Pt as colorIdSchema,Se as columnsSchema,compareAgentSessionMessages,compareSchemaStateEntries,compilablePlansOf,compileComputedFormula,compileRollupAttribute,computeByteMagnitude,computedCompileSchemaOf,computedPlanOf,z as content,contentDefinition,Qi as contentExtensionRegistry,pe as contentViewDefinitionSchema,ae as contentViewDefinitionSchemaFor,conversationDisplayTitle,en as createCheckboxValidator,tn as createDateValidator,createFlagRegistry,createFlagService,hn as createFormAttributeValidator,$t as createNumberValidator,createStandardSchemaProps,Xt as createTextValidator,currency,t as currentActor,mo as customDataChunkSchemas,date,dateInTimezone,dateValueStart,ln as deepEqual,defaultViewIdsFor,defaultViewsFor,defineDeviceChannelFrames,defineOperation,definePresentation,dependentsOf,deriveArchitectChanges,deriveCreateDefaultsFromFilters,deriveInitials,describeOperations,Va as destructiveSchema,detailView,diffSchemaState,ye as displayAttributesSchema,document,Ce as draftContentViewDefinitionSchema,se as draftContentViewDefinitionSchemaFor,draftObjectSettings,draftedLabelExpression,draftedObjectDefinition,draftedViewDefinition,lo as durableDateSchema,dwellForStep,episodeImpactOf,evaluateComputedAst,evaluateComputedFormula,evaluateComputedFormulaWithResult,evaluateFilterState,evaluateRecordFilterState,extractAttributeNames,h as extractCurrencyFilterValue,he as extractFilterValue,extractValueRefs,familyOf,l as filterOperatorsByTypeForGeneration,ge as filterStateSchema,findRelationAttribute,Si as flagRegistry,focusOf,form,formFieldFlatKey,formFieldKey,$i as formRegistry,formatAgentStreamFrameId,formatAttributeValue,formatByteSize,formatComputedResult,formatLocationValue,Qt as formatZodErrors,formula,fromDraftableView,an as generateId,x as getAttributeCapabilities,c as getAttributeFilterOperators,getEditableLabelAttribute,getErrorMessage,getLiveProtocolPayloadChannel,De as getOperatorPolarity,getRecordCreatorPrincipalId,f as getRollupFilterOperators,getSingleAttributeFromExpression,getSlotFieldTargets,e as getSystemAttributeI18nKey,le as getSystemAttributeList,getUserDisplayName,group,guidanceForBatch,hasDestructiveEntries,hasOptions,O as iconNameSchema,eo as imageModelIdSchema,includesAction,nn as indexBy,inferInverseCardinality,inferRollupReturnType,Za as inferenceReasoningSchema,Xa as inferenceSpeedSchema,isAgentMessageMetadata,isAgentNotificationMetadata,isAgentUIDataName,isAgentUIMessageBatch,b as isAttributeFilterable,S as isAttributeGroupable,at as isAttributeInUseError,s as isAttributeKanbanGroupable,d as isAttributeSearchable,isAttributeSortable,isBilateralRelation,isCheckboxEquality,isClaimableSessionStatus,isComputedAttribute,isComputedFunctionName,isCurrentTargetToken,isDateRangeValue,isDefaultRole,isDocumentAttribute,me as isDynamicValue,isEdgePayload,isEmptyObject,isFormDefinition,isFormFieldsRow,isFormFreeFieldRef,isFormHeadingRow,isFormSeparatorRow,isFormSlotFieldRef,isFormTextRow,isLabelExpression,isLiveEventEnvelope,isLiveEventPayload,isLiveEventPayloadForType,isLiveEventType,u as isLocationFilterProperty,ne as isLocationPartOperator,isMailProvider,isMailboxListMode,Te as isManagedSystemAttribute,qt as isNativeObjectName,ee as isNoValueOperator,isNotEmpty,ot as isNotFoundError,M as isNullishOrEmptyString,st as isObjectReferencedError,isOpenToolPartState,isPlainRecord,ct as isProtectedResourceError,lt as isRecordReferencedError,de as isRelativeDateValue,isReplyMode,ut as isSchemaError,y as isSetMembershipOperator,isStandardSchema,isSystemPartCode,isTerminalSessionStatus,isTerminalState,isToolApprovalState,isUniversalRelation,dt as isValidationError,_n as isValuePresent,jsonFlag,legacyStatusToSessionState,listView,liveChannelKey,location,matchesAccepts,so as mentionReferenceSchema,co as modelDefinitionSchema,Qa as modelReferenceSchema,multiselect,Rt as multiselectOptionWriteSchema,hs as namedTargetSchema,nativeAgentUIPartIdMetadataKey,normalizeDateValue,Oe as normalizeFilterRule,a as normalizeForEdgeRpc,v as normalizeOperator,p as now,number,numberFlag,object,operationPace,orderAgentSessionMessages,parseAgentStreamFrameId,Vt as parseAttributeConfig,Dt as parseAttributeConfigForCreate,Ft as parseAttributeConfigForUpdate,A as parseComputedFormula,parseCountMode,parseDeviceChannelFrame,parseLiveChannelKey,parseNamedTarget,parseNativeAgentUIPartIdsMetadata,parseOperation,parseOptionalCountMode,parseQualifiedAttribute,gt as parseResourceVisibility,parseSchemaGroupPresentation,parseSchemaState,parseServerFrame,parseWorkerFrame,qa as persistedSchemaPlanSchema,phone,Ra as plannedAttributeSchema,za as plannedInlineAttributeSchema,Ba as plannedObjectSchema,presentationOf,Ut as propertyAttributeSchema,Ot as propertyAttributeWireSchema,kt as propertySchemaSchema,zt as propertySchemaWireSchema,proposalTargetKey,Ya as providerNameSchema,C as publishedViewContentDefinitionSchema,qualifiedPropertyDefs,readFormFieldValue,reconcileRelationAttributes,It as refuseForeignKeys,regenerateDerived,wi as registry,yn as rejectUnknownAttributesOrThrow,relation,relationAcceptsObject,relationProperty,relationPropertyDefs,relationTargetObjectName,relationTargets,relationTargetsOf,relationValueIds,renderLabelExpression,requestedCapabilities,requireRecordContentContext,requireSingleRelationTarget,requiredTargetKeys,resolveAttributeDefaultValue,resolveCollectionActions,resolveContentNavigation,te as resolveEffectiveFilterType,resolveFieldRequired,ie as resolveIsWithinBounds,resolvePropertyDefinitions,Yt as resolveTextPattern,Ee as resolveUtcDayBounds,resolveViewContents,richtext,rollup,rollupToFormulaExpression,rn as sameStableValue,schemaGroupKey,Ga as schemaPlanSchema,schemaStateSourcePayload,select,jt as selectOptionWriteSchema,on as serializeCanonicalJson,dn as serializeStableJson,ro as sessionInferencePatchSchema,sessionStateToLegacyStatus,ce as sortsSchema,status,At as statusGroupSchema,wt as statusOptionWriteSchema,stillMissing,storedContentDefinition,stringFlag,summarizeDraft,targetSnapshot,targetTokenOf,targetTokensFor,text,toAttribute,toDraftableAttributes,toDraftableObject,toDraftableView,i as toMultiValueOperator,toUndefinedIfEmpty,ke as toUtcDayString,m as today,fo as todoItemSchema,po as todoPlanSchema,io as toolImpactSchema,touchedObjectIds,user,ft as validateAttributeName,validateContentViewCatalogue,fn as validateDraft,vn as validateDraftOrThrow,validateLabelExpression,bn as validateObject,validateObjectExpressions,pt as validateObjectName,pn as validateObjectOrThrow,fe as validateQualifiedRule,validateStoredViews,yt as validateViewName,viewIdFor,viewIdentityKey,Ji as viewRegistry,workspaceViewAuthoring};