@stndrds/schema 1.0.0-alpha.333 → 1.0.0-alpha.335
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{all-BLytyk5I.d.mts → all-hyIoY9Y2.d.mts} +1 -0
- package/dist/{all-Cf6oNz9y.d.ts → all-m7G8bXjY.d.ts} +1 -0
- package/dist/config-BvijG1IN.js +13 -0
- package/dist/{config-CHSqDLhx.mjs → config-aeELOnWd.mjs} +5 -5
- package/dist/index.d.mts +92 -3
- package/dist/index.d.ts +92 -3
- package/dist/index.js +2 -2
- package/dist/index.mjs +9 -9
- package/dist/{object-CUkTFj0u.js → object-BfGtzS7g.js} +2 -2
- package/dist/object-D-aDCAHn.mjs +4 -0
- package/dist/{phone-CLsxU8tv.js → phone-CUgSbH-z.js} +1 -1
- package/dist/{phone-DfXAzPpD.mjs → phone-X_nKo0qe.mjs} +1 -1
- package/dist/validation/all.d.mts +1 -1
- package/dist/validation/all.d.ts +1 -1
- package/dist/validation/all.js +1 -1
- package/dist/validation/all.mjs +1 -1
- package/dist/validation/complex/phone.js +1 -1
- package/dist/validation/complex/phone.mjs +1 -1
- package/dist/validation/config/index.js +1 -1
- package/dist/validation/config/index.mjs +1 -1
- package/dist/validation/object/index.js +1 -1
- package/dist/validation/object/index.mjs +1 -1
- package/dist/{view-config.schema-D-TbyG6j.js → view-config.schema-4QhPV9el.js} +1 -1
- package/dist/{view-config.schema-CcfExWMt.mjs → view-config.schema-CMjVNRCh.mjs} +1 -1
- package/package.json +2 -2
- package/dist/config-CFYxsRcx.js +0 -13
- package/dist/object-B9V5JZzh.mjs +0 -4
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 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-CcfExWMt.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 pt,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 k,y as A,z as j}from"./config-CHSqDLhx.mjs";import{a as qt,c as Jt,i as Yt,l as Xt,n as Zt,o as Qt,r as $t,s as M,t as en,u as tn}from"./utils-fXIvFFl6.mjs";import{a as nn,c as rn,d as an,f as on,i as sn,m as cn,o as ln,p as N,r as un,s as dn,u as fn}from"./object-B9V5JZzh.mjs";import{n as pn,r as mn,t as hn}from"./text-C8Lb-NFo.mjs";import{i as gn,n as _n,r as vn}from"./phone-DfXAzPpD.mjs";import{n as yn,t as bn}from"./core-BLHhNykL.mjs";import{createCheckboxValidator as xn}from"./validation/primitives/checkbox.mjs";import{createDateValidator as Sn}from"./validation/primitives/date.mjs";import{createNumberValidator as Cn}from"./validation/primitives/number.mjs";import{MEMORY_DESCRIPTION_MAX_LENGTH as wn,MEMORY_NAME_MAX_LENGTH as Tn,SKILL_DESCRIPTION_MAX_LENGTH as En,SKILL_NAME_MAX_LENGTH as Dn,getCountryDisplayNameByIso3 as P}from"@stndrds/constants";import{z as F}from"zod";const On=[`fyi`,`task`,`question`,`handoff`,`system`],kn=[`low`,`normal`,`high`,`urgent`],An=[`public`,`internal`,`sensitive`],jn=[`unread`,`read`,`archived`,`snoozed`],Mn=[`none`,`pending`,`processing`,`completed`,`dismissed`,`expired`,`failed`],Nn=`agent.session.waiting_human`,Pn=`agent.task.assigned`,Fn=`agent.question.requested`,In=[Nn,Pn,Fn],Ln=[`name`,`type`],Rn=[`required`,`hidden`,`archived`,`deprecated`,`defaultValue`,`config`,`order`,`unique`],zn=[`label`,`description`,`placeholder`,`icon`],Bn=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`status`,`location`,`select`,`multiselect`,`user`,`relation`,`formula`,`rollup`,`document`],Vn=`*`;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 Hn=[`record`,`object`,`attribute`,`view`,`user`,`role`,`settings`,`file`,`agent`,`schema_source`],Un=`record.created,record.updated,record.deleted,record.restored,record.purged,object.created,object.updated,object.deleted,attribute.created,attribute.updated,attribute.deleted,view.created,view.updated,view.deleted,schema_source.applied,schema_source.removed,user.created,user.invited,user.updated,user.deleted,user.login,user.logout,role.created,role.updated,role.deleted,role.assigned,role.revoked,settings.updated,file.uploaded,file.updated,file.deleted`.split(`,`);function isTerminalState(e){return e.phase===`terminal`}function sessionStateToLegacyStatus(e){switch(e.phase){case`running`:return`active`;case`queued`:return`idle`;case`parked`:if(e.parkedOn===void 0)throw new 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 Wn=[`completed`,`failed`,`cancelled`,`timeout`,`expired`];function isTerminalSessionStatus(e){return Wn.includes(e)}const Gn=[`idle`,`completed`,`waiting_human`,`waiting_agents`,`cancelled`,`failed`,`timeout`];function isClaimableSessionStatus(e){return Gn.includes(e)}const Kn=Object.freeze({mutation:`ask`,destructive:`ask`,outward:`ask`}),qn=[`active`,`completed`,`abandoned`],Jn=[`openai`,`anthropic`,`google`,`spacexai`,`deepseek`,`moonshotai`,`alibaba`,`mistral`,`minimax`,`meta`,`zai`],Yn=[`standard`,`fast`],Xn=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`];function agentDisplayName(e){return e.label?.trim()||e.name}const Zn=[`approval-requested`,`approval-responded`,`approval-dispatched`],Qn=[`streaming`,`running`,`pending`,...Zn];function isOpenToolPartState(e){return Qn.includes(e)}function isToolApprovalState(e){return Zn.includes(e)}const $n=[`CREDITS_EXHAUSTED`];function isSystemPartCode(e){return typeof e==`string`&&$n.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 er=[`pending`,`in_progress`,`completed`,`blocked`],tr=50,nr=80,rr=500,ir=`session-state`,ar=`__stndrdsNativeUiPartIds`,or=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?.[ar];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 sr=16e3,cr=3200,lr=6400,ur=16e3,dr=65536,fr=15e3,pr=1e4,mr=5e3,hr=`google/gemini-3.5-transcribe-live`,gr={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2},_r=[`web`,`presentation`,`document`,`spreadsheet`,`image`,`code`,`other`],vr=[`ephemeral`,`conversation`,`persistent`],yr=[`source`,`preview`,`entrypoint`,`asset`],br=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 xr=[`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 I=[`read`,`create`,`update`,`delete`,`manage`];function actionsToAccessLevel(e){return e.length===0?`none`:e.length===1&&e[0]===`read`?`read-only`:e.length===I.length&&I.every(t=>e.includes(t))?`full`:`custom`}function accessLevelToActions(e){switch(e){case`full`:return[...I];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 Sr=`Notetaker`,Cr={systemPrompt:null,meetingRecordingPolicy:`none`,meetingBotDisplayName:Sr},wr=[`active`,`suspended`],Tr=[`architect`,`manual`,`auto`],Er=[`square`,`landscape`,`portrait`],Dr=[`none`,`estimated`,`exact`];function parseCountMode(e){if(typeof e==`string`&&Dr.includes(e))return e;throw new D(`countMode must be one of: ${Dr.join(`, `)} (received: ${String(e)})`,[])}function parseOptionalCountMode(e){return e===void 0?void 0:parseCountMode(e)}const Or=1e4,kr=[`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 Ar=[`B`,`KB`,`MB`,`GB`,`TB`];function formatByteSize(e){let{value:t,unitIndex:n}=computeByteMagnitude(e);return`${t} ${Ar[n]}`}const jr={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 Mr=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(!Mr.includes(e.type))throw Error(`Property type "${e.type}" is not supported in .qualifyWith()`);t.push(e)}return{definitions:t}}const Nr=`__`;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 N(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 Pr=`—`;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?_n(t):t.phoneNumber:``:String(e)}function formatLocationValue(e,t=`full`){if(typeof e!=`object`||!e)return``;let n=e,r=[];switch(t){case`country`:n.country&&r.push(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(N(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 Fr=[`UPPER`,`LOWER`,`capitalize`,`trim`],Ir=[`prefix`,`suffix`,`wrap`,`default`],Lr=[...Fr,...Ir],L=F.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(!Lr.includes(e))return!1}return!0},{message:`Invalid pipe name. Valid pipes: ${Lr.join(`, `)}`});function validateLabelExpression(e){let t=L.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 Rr=`(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=Rr){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 zr=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function getSingleAttributeFromExpression(e){let t=e.trim().match(zr);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 Br=/\{\{\s*props\./;function applyRelationProps(e,t,n){if(!Br.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(N(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 Vr=/\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(Vr)?.[0];return t===void 0?``:[...t.toUpperCase()][0]??``}).filter(Boolean).slice(0,2).join(``);return i===``?t:i}const Hr=`__creatorRootActorId`;function getRecordCreatorPrincipalId(e){let t=e.metadata?.[Hr];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 Ur=new Set([`id`,`name`,`label`,`type`,`required`,`system`,`unique`,`order`]),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:`connectors`,ENV_VARS:`env-vars`,SESSION:`session`},Wr=[R.PEOPLE,R.WORKSPACE,R.ARCHITECT,R.FEATURE_FLAGS,R.FILES,R.VIEWS,R.FORMS,R.DOCUMENTS,R.AUDIT,R.API_KEYS,R.CONNECTORS,R.ENV_VARS,R.SESSION],Gr={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`},Kr={OWNER:`owner`,MEMBER:`member`,AGENT_DEFAULT:`agent_default`,REFLEX_DEFAULT:`reflex_default`},qr={owner:`Owner`,member:`Member`,agent_default:`Agent Default`,reflex_default:`Reflex Default`},Jr={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`},Yr=[`read`,`create`,`update`,`delete`,`manage`],Xr=[`read`,`create`,`update`,`delete`],Zr=[`read`,`create`,`update`,`delete`],Qr={owner:{system:[{target:`*`,actions:Yr}],object:[{target:`*`,actions:Yr}]},member:{system:[{target:`people`,actions:[`read`]},{target:`workspace`,actions:[`read`]},{target:`connectors`,actions:Xr},{target:`files`,actions:Zr},{target:`documents`,actions:Zr}],object:[{target:`*`,actions:Yr}]},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(Kr).includes(e)}const $r={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??$r,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={...Kn,...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 wt(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??$r,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};function agent(e){return new AgentBuilder(e)}const ei=`@stndrds/schema`;function createStandardSchemaProps(e){return{version:1,vendor:ei,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(an(this.build()))}constructor(e,t,n){mt(t),bt(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 pt(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 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=F.string().min(1,`Form name cannot be empty`).max(63,`Form name is too long (max 63 characters)`).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,{message:`Invalid form name format. Name must be in kebab-case: 'client-onboarding', 'contact-creation'`});try{t.parse(e)}catch(e){throw e instanceof F.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=[...Lr,`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(xr);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: ${xr.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=L.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=L.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(fn(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);wt([...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&&Ft(e)}};function object(e){if(j(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 ti=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 ti({name:e,label:t,object:void 0,context:`record`,contents:[]})}function listView(e,t){return new ti({name:e,label:t,object:void 0,context:`collection`,contents:[]})}function relationProperty(e){return requireBuilderName(e,[`relationProperty`]),{relationProperty:e}}var z=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}},ni=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 ni(e,t,[])}function collection(){return new z({type:`collection`})}function form$1(...e){return new z({type:`form`,groups:e.map(e=>`build`in e?e.build():e)})}function activity(){return new z({type:`activity`})}function richtext$1(e){return new z({type:`richtext`,attribute:e})}function documents(){return new z({type:`documents`})}function forms(){return new z({type:`forms`})}function emails(...e){return new z({type:`emails`,emailAttributes:e})}function meetings(...e){return new z({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 z({...n,extension:e.name},e);return r.build(),r}const B={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 ri=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 ii=Symbol(`stndrds.native-object`);function markNativeDefinition(e){return Object.defineProperty(e,ii,{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[ii]===!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(j(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
|
|
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 A}from"./config-aeELOnWd.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-D-aDCAHn.mjs";import{i as Sn,n as Cn,r as wn}from"./phone-X_nKo0qe.mjs";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 N}from"@stndrds/constants";import{z as P}from"zod";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 Se(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 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 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=[`pending`,`in_progress`,`completed`,`blocked`],nr=50,rr=80,ir=500,ar=`session-state`,or=`__stndrdsNativeUiPartIds`,sr=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?.[or];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 cr=16e3,lr=3200,ur=6400,dr=16e3,fr=65536,pr=15e3,mr=1e4,hr=5e3,gr=`google/gemini-3.5-transcribe-live`,_r={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2},vr=[`web`,`presentation`,`document`,`spreadsheet`,`image`,`code`,`other`],yr=[`ephemeral`,`conversation`,`persistent`],br=[`source`,`preview`,`entrypoint`,`asset`],xr=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 Sr=[`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 F=[`read`,`create`,`update`,`delete`,`manage`];function actionsToAccessLevel(e){return e.length===0?`none`:e.length===1&&e[0]===`read`?`read-only`:e.length===F.length&&F.every(t=>e.includes(t))?`full`:`custom`}function accessLevelToActions(e){switch(e){case`full`:return[...F];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 Cr=`Notetaker`,wr={systemPrompt:null,meetingRecordingPolicy:`none`,meetingBotDisplayName:Cr},Tr=6048e5,Er=36e5,Dr=2592e6,Or=6e4,kr=[`active`,`suspended`],Ar=[`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 jr=[`square`,`landscape`,`portrait`],Mr=[`none`,`estimated`,`exact`];function parseCountMode(e){if(typeof e==`string`&&Mr.includes(e))return e;throw new E(`countMode must be one of: ${Mr.join(`, `)} (received: ${String(e)})`,[])}function parseOptionalCountMode(e){return e===void 0?void 0:parseCountMode(e)}const Nr=1e4,Pr=[`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 Fr=[`B`,`KB`,`MB`,`GB`,`TB`];function formatByteSize(e){let{value:t,unitIndex:n}=computeByteMagnitude(e);return`${t} ${Fr[n]}`}const Ir={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 Lr=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(!Lr.includes(e.type))throw Error(`Property type "${e.type}" is not supported in .qualifyWith()`);t.push(e)}return{definitions:t}}const Rr=`__`;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 zr=`—`;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(N(n.country));break;case`state`:n.state&&r.push(n.state),n.country&&r.push(N(n.country));break;case`city`:n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(N(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(N(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(N(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 Br=[`UPPER`,`LOWER`,`capitalize`,`trim`],Vr=[`prefix`,`suffix`,`wrap`,`default`],Hr=[...Br,...Vr],I=P.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(!Hr.includes(e))return!1}return!0},{message:`Invalid pipe name. Valid pipes: ${Hr.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 Ur=`(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=Ur){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 Wr=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function getSingleAttributeFromExpression(e){let t=e.trim().match(Wr);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 Gr=/\{\{\s*props\./;function applyRelationProps(e,t,n){if(!Gr.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 Kr=/\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(Kr)?.[0];return t===void 0?``:[...t.toUpperCase()][0]??``}).filter(Boolean).slice(0,2).join(``);return i===``?t:i}const qr=`__creatorRootActorId`;function getRecordCreatorPrincipalId(e){let t=e.metadata?.[qr];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 Jr=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`},Yr=[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],Xr={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`},Zr={OWNER:`owner`,MEMBER:`member`,AGENT_DEFAULT:`agent_default`,REFLEX_DEFAULT:`reflex_default`},Qr={owner:`Owner`,member:`Member`,agent_default:`Agent Default`,reflex_default:`Reflex Default`},$r={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`},ei=[`read`,`create`,`update`,`delete`,`manage`],ti=[`read`,`create`,`update`,`delete`],ni=[`read`,`create`,`update`,`delete`],ri={owner:{system:[{target:`*`,actions:ei}],object:[{target:`*`,actions:ei}]},member:{system:[{target:`people`,actions:[`read`]},{target:`workspace`,actions:[`read`]},{target:`connectors`,actions:ti},{target:`files`,actions:ni},{target:`documents`,actions:ni}],object:[{target:`*`,actions:ei}]},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(Zr).includes(e)}const ii={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??ii,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 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??ii,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};function agent(e){return new AgentBuilder(e)}const ai=`@stndrds/schema`;function createStandardSchemaProps(e){return{version:1,vendor:ai,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){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=P.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 P.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=[...Hr,`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(Sr);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: ${Sr.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=I.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=I.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(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);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(A(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 oi=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 oi({name:e,label:t,object:void 0,context:`record`,contents:[]})}function listView(e,t){return new oi({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 E.fromZodErrors(t.error.issues.map(e=>({path:[`content`,`parameters`,...e.path.map(String)],message:e.message})))}return e}},si=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 si(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 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 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 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 ci=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 li=Symbol(`stndrds.native-object`);function markNativeDefinition(e){return Object.defineProperty(e,li,{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[li]===!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(A(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 ui=new NativeObjectRegistryClass,di=new WeakSet;function markSystemView(e){return di.add(e.definition),e}function isSystemViewDefinition(e){return typeof e==`object`&&!!e&&di.has(e)}const fi=`## 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
|
-
`,
|
|
34
|
+
`,pi=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(
|
|
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(fi)).build(),mi=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()),hi=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()),gi=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(
|
|
39
|
-
{{ description }}`).attribute(text({name:`name`,label:`Name`}).required()).attribute(text({name:`description`,label:`Description`}).multiline()).build(),
|
|
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(),
|
|
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(),_i={combinator:`and`,rules:[{attribute:`invalidAt`,operator:`is_empty`,value:null},{attribute:`reviewState`,operator:`is_empty`,value:null}]},vi=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()),yi=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(_i).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(_i).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`,bi=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(),xi=markSystemView(detailView(`drive-detail`,`Drive`).for(B).default().tab(`documents`,`Documents`,z.documents()).aside(`details`,`Details`,z.form(group(`details`,`Details`).field(`description`))).build()),Si=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()),Ci={name:`artifact_preview`,requiresRecord:!0,parameters:P.object({}).strict()},V=`artifact`,wi=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(),Ti=markSystemView(detailView(`artifact-detail`,`Artifact`).for(V).default().tab(`preview`,`Preview`,z.custom(Ci,{})).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()),Ei=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`},Di=`meeting-list`,Oi=`calendar-sync`,ki=`meeting-detail`,Ai=[U.title,U.startsAt,U.endsAt,U.status],ji=nativeObject({name:H,label:`Meeting`}).sealed().hidden().metadata({platformOwned:{editable:[U.linkedRecords],source:Oi}}).icon(`calendar`).pluralLabel(`Meetings`).labelExpression(`{{ title }}`).embeddingExpression(`{{ title }}
|
|
41
41
|
{{ description }}
|
|
42
42
|
{{ participants }}
|
|
43
|
-
{{ summary }}`).attribute(text({name:
|
|
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 ki=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 Ai=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}function requireAttribute$1(e,t,n,r,i){if(requireName(t,n),!e)return;let a=e.attributes?.get(t)??Ai.get(t);if(!a){if(!e.attributes)return;let r=[...e.attributes.keys()].slice(0,30),a=r.length===0?`Object "${e.name}" has no attributes yet.`:`Attributes of "${e.name}": ${r.join(`, `)}`;reject$2(n,`Unknown attribute "${e.name}.${t}". ${a}${i?.()??``}`)}return r&&a.type!==r&&reject$2(n,`Attribute "${e.name}.${t}" must have type ${r}`),a}function collectContentViewCatalogue(e){let 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 ji=[Object.freeze(vi)];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 ji)this.extensions.set(e.name,e)}};const Mi=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 Ni=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 Pi=204800,Fi=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 Ii=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}),Li=[`membership-unknown`,`sort-unknown`,`permissions-changed`],Ri=[`permission-revoked`,`workspace-left`,`object-deleted`],zi=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],Bi=[`type`,`objectId`,`recordId`,`recordVersion`],Vi=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],Hi=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],Ui=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&Ii.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,On)}function isNotificationPriority(e){return isOneOf(e,kn)}function isNotificationSensitivity(e){return isOneOf(e,An)}function isNotificationInboxState(e){return isOneOf(e,jn)}function isNotificationWorkState(e){return isOneOf(e,Mn)}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,Bi)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$1(e)&&hasOnlyKeys(e,Hi)&&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,Vi)&&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,Li)}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=>zi.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,Ui)&&hasNonEmptyString(e,`targetActorId`)&&hasVersion(e,`archivedCount`)&&hasVersion(e,`version`)&&hasIsoDateString(e,`updatedAt`)}const Wi=[`armed`,`disarmed`],Gi=[`authoring`,`compiling`,`replaying`,`promoted`,`failed`],Ki=[`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,Wi)&&hasIsoDateString(e,`updatedAt`)}function isReflexRunCompletedPayload(e){return e.type===`reflex.run.completed`&&hasNonEmptyString(e,`reflexId`)&&hasNonEmptyString(e,`runId`)&&isOneOf(e.served,Ki)&&hasVersion(e,`version`)&&hasVersion(e,`wallMs`)&&hasIsoDateString(e,`completedAt`)}function isReflexAuthoringProgressPayload(e){return e.type===`reflex.authoring.progress`&&hasNonEmptyString(e,`reflexId`)&&isOneOf(e.status,Gi)&&hasIsoDateString(e,`updatedAt`)}const qi=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,qi)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const Ji=[`ok`,`low`,`exhausted`,`paused`],Yi=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,Ji)&&isOneOf(e.mode,Yi)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,Ri)}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 Xi=[`if`,`concat`,`sum`,`avg`,`count`,`min`,`max`,`earliest`,`latest`,`unique`,`first`,`percent_empty`,`percent_not_empty`,`count_empty`,`count_not_empty`,`count_unique`],Zi={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(Zi,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=Zi[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}=Zi[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(N).length;case`count_not_empty`:return collectionItems(t[0]).filter(e=>!N(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=>N(e)===t).length/n.length}function uniqueNonEmpty(e){let t=new Set,n=[];for(let r of e){if(N(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 Qi=[{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=>N(e)||Array.isArray(e)&&e.length===0,toStr=e=>e==null?``:String(e),toNum=e=>{if(N(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)}),$i={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}),ea=[...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,...ea])}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=$i[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=$i[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=$i[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 vn(t.phoneNumber);let n=typeof t.countryCode==`string`?t.countryCode:r;return`${n}:${gn(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 ta=`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 na={status:`connector_status`,error:`connector_error`,provider:`connector_provider`};let ra=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const ia=[`threads`,`messages`];function isMailboxListMode(e){return ia.includes(e)}const aa=[`reply`,`reply_all`];function isReplyMode(e){return aa.includes(e)}const oa=2e5,sa=998,ca=[`force`,`skip`],la=[`none`,`all`,`external_only`],ua=`x-fake-signature`,da={override:null,status:`none`,failureReason:null,botId:null},fa=/^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&&!fa.test(t)?t:e.firstUserText?buildAgentFallbackTitle(e.firstUserText):e.emptyLabel}const pa=/^[a-z0-9][a-z0-9-]{0,62}$/;function assertSchemaSourceId(e){if(!pa.test(e))throw new D(`Invalid schema source id "${e}": expected a lowercase slug matching ${pa}`,[])}function hasDestructiveEntries(e){let{attributeRemovals:t,objectRemovals:n,renames:r}=e.destructive;return t.length>0||n.length>0||r.length>0}const G={objectAdditions:20,totalMutations:500,serializedBytes:524288};function errorMessage(e){return e instanceof Error?e.message:String(e)}const ma=F.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.'),ha=F.string().min(1).superRefine((e,t)=>{try{mt(e)}catch(e){t.addIssue({code:F.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).`),ga=F.string().min(1).superRefine((e,t)=>{j(e)&&t.addIssue({code:F.ZodIssueCode.custom,message:`"${e}" is a reserved object name (${xt.join(`, `)}) and cannot be used for a new object.`});try{Ft(e)}catch(e){t.addIssue({code:F.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 D){for(let r of n.errors)t.addIssue({code:F.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:F.ZodIssueCode.custom,path:[`config`],message:`Config for type "${e.type}" is invalid or incomplete: ${errorMessage(n)}`})}})}const _a=F.object({objectName:F.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:ha,label:F.string().min(1).max(128).describe(`Human-readable display label shown in the UI. 1-128 characters, cannot be empty.`),type:ma,config:F.record(F.string(),F.unknown()).optional().describe('Type-specific configuration; required keys depend on `type` (see `type`\'s description). Shared optional keys on every type: `placeholder`, `defaultValue`, `icon`, `order`, `hidden`, `archived`, `deprecated`, `metadata`. Per-type keys: `text` — `multiline`, `minLength`, `maxLength`, `pattern`, `format` ("email"|"url"|"slug"); `number` — `renderAs` ("number"|"rating"), `min`, `max`, `unit`, `decimals`; `date` — `dateFormat`, `minDate`, `maxDate`, `includeTime`, `endDate`, `timeFormat` ("12h"|"24h"); `phone` — `defaultCountryCode` (3-letter); `currency` — `defaultCurrency`, `allowedCurrencies`, `allowNegative`; `status`/`select`/`multiselect` — `options` (REQUIRED, non-empty array of `{ value, label, color }`, unique `value`s; for `status` every OPTION also carries `group` as idle|in_progress|finished — `group` belongs on each option, never on `config` itself; select/multiselect accept `renderAs: "badges"`); `location` — `granularity`, `defaultCountry`, `allowedCountries`; `user` — `types` ("user"|"agent"), `multiple`; `relation` — `targets` (REQUIRED, non-empty array of `{ object }`) and `cardinality` (REQUIRED, "one"|"many"); `formula` — `expression` (REQUIRED formula string) and `returnType` (REQUIRED); `rollup` — `targetAttribute` (REQUIRED) and `function` (REQUIRED, e.g. "sum"|"avg"|"count"); `document` — `properties`, `accepts`, `maxFileSize`. Omit entirely for `richtext`/`checkbox`, which take no type-specific keys.'),required:F.boolean().optional().describe(`Whether the attribute must have a value on every record. Defaults to false (optional).`),description:F.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),va=withConfigCheck(_a),ya=withConfigCheck(_a.omit({objectName:!0})),ba=F.object({name:ga,label:F.string().min(1).describe(`Human-readable singular display label (e.g. "Devis").`),pluralLabel:F.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:F.string().optional().describe(`Help text describing what this object represents.`),icon:k.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:L.describe("Titles every record of this object; syntax in <expressions>. Each attribute it interpolates must exist on the object — declared in this same `attributes` array, or already on it when this is an update."),attributes:F.array(ya).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(),xa=F.object({attributeRemovals:F.array(F.object({objectName:F.string().min(1).describe(`Object the attribute is removed from.`),attributeName:F.string().min(1).describe("Attribute to delete, together with every record's stored value for it. Must not be a system (code-declared) attribute, and must not be referenced by the object's own `labelExpression` or `embeddingExpression` — update those first.")}).strict()).default([]).describe(`Attributes to permanently delete. Irreversible: record values for the attribute are purged.`),objectRemovals:F.array(F.object({objectName:F.string().min(1).describe("Object to delete entirely, together with all its records. Must not be a system (code-declared) object, and must not still be targeted by a `relation` attribute on another object — retarget or remove that relation first.")}).strict()).default([]).describe(`Objects to permanently delete, records included. Irreversible.`),renames:F.array(F.object({objectName:F.string().min(1).describe(`Object the renamed attribute belongs to.`),from:F.string().min(1).describe(`Current attribute name. Must already exist and not be a system attribute.`),to:ha.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:[]}),Sa=F.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.`),Ca=F.object({objects:F.array(ba).default([]),attributes:F.array(va).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>G.objectAdditions&&t.addIssue({code:`too_big`,origin:`array`,maximum:G.objectAdditions,inclusive:!0,path:[`additive`,`objects`,G.objectAdditions],message:`A schema plan can add at most ${G.objectAdditions} objects`});let n=mutationPaths(e);n.length>G.totalMutations&&t.addIssue({code:`too_big`,origin:`array`,maximum:G.totalMutations,inclusive:!0,path:n[G.totalMutations],message:`A schema plan can contain at most ${G.totalMutations} mutations; received ${n.length}`})}function boundSerializedPlanInput(e,t){let n=findJsonSafetyIssue(e);if(n)return t.addIssue({code:`custom`,path:n.path,message:n.message}),F.NEVER;let r=new TextEncoder().encode(M(e)).byteLength;return r>G.serializedBytes?(t.addIssue({code:`too_big`,origin:`string`,maximum:G.serializedBytes,inclusive:!0,path:[],message:`A schema plan can serialize to at most ${G.serializedBytes} UTF-8 bytes; received ${r}`}),F.NEVER):e}const wa=F.object({schemaPlanVersion:F.literal(2).describe(`Required proposal contract version.`),summary:Sa,additive:Ca,destructive:xa}).strict().superRefine(addPlanLimitIssues),Ta=Object.assign(F.preprocess(boundSerializedPlanInput,wa),{shape:wa.shape}),Ea=F.object({schemaPlanVersion:F.literal(2),summary:Sa,additive:Ca,destructive:xa}).strict().superRefine(addPlanLimitIssues),Da=F.preprocess(boundSerializedPlanInput,Ea);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 Oa=/^[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);(!Oa.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&&!$t(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)&&!$t(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);(!Oa.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 K=F.number().finite().nonnegative(),ka=F.enum(Jn),Aa=F.enum(Yn),ja=F.enum(Xn),Ma=F.object({provider:ka,model:F.string().min(1)}).strict(),Na=F.object({speed:Aa.optional(),reasoning:ja.optional()}).strict(),Pa=F.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),Fa=F.object({model:Ma.optional(),speed:Aa.optional(),reasoning:ja.optional(),imageModel:Pa.optional()}).strict(),Ia=Fa.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`}),La=F.object({model:Ma.nullable().optional(),speed:Aa.nullable().optional(),reasoning:ja.nullable().optional(),imageModel:Pa.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`}),Ra=F.object({label:F.string(),denied:F.boolean().optional(),deletion:F.object({target:F.string().optional(),count:K.optional(),restorableDays:K.optional()}).strict().optional(),counts:F.record(F.string(),K).optional(),warnings:F.array(F.string()).optional()}).strict(),za=F.union([F.object({type:F.literal(`text`),text:F.string()}).strict(),F.object({type:F.literal(`reasoning`),text:F.string()}).strict(),F.object({type:F.literal(`system`),code:F.enum($n)}).strict(),F.object({type:F.literal(`error`),error:F.string(),errorClass:F.string().optional()}).strict(),F.object({type:F.literal(`tool`),toolCallId:F.string(),name:F.string(),args:F.record(F.string(),F.unknown()),result:F.unknown().optional(),error:F.string().optional(),errorCode:F.enum([`output_limit_reached`,`interrupted`]).optional(),state:F.enum([`streaming`,`running`,`completed`,`error`,`pending`,`approval-requested`,`approval-responded`,`approval-dispatched`]),durationMs:K.optional(),approvalId:F.string().optional(),approvalImpact:Ra.optional(),approved:F.boolean().optional(),approvalReason:F.string().optional(),approvalRelaxableByAuto:F.boolean().optional()}).strict(),F.object({type:F.literal(`file`),fileId:F.string(),name:F.string(),mimeType:F.string()}).strict(),F.object({type:F.literal(`compaction`),state:F.literal(`in-progress`),reason:F.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:K.optional(),reportedTokens:K.optional()}).strict(),F.object({type:F.literal(`compaction`),state:F.literal(`completed`),tokensBefore:K,tokensAfter:K,tokensSaved:K,strategy:F.enum([`no-op`,`summary`,`truncation`]),durationMs:K,summary:F.string().optional()}).strict(),F.object({type:F.literal(`compaction`),state:F.literal(`failed`),reason:F.string(),durationMs:K.optional()}).strict()]),Ba=F.object({id:F.string(),name:F.string(),mimeType:F.string(),size:K}).strict(),Va=F.object({id:F.string(),type:F.string().transform(e=>e),entityId:F.string(),label:F.string(),objectName:F.string().optional(),startIndex:K,endIndex:K}).strict(),Ha=F.object({provider:ka,model:F.string(),maxTokens:K.optional(),contextWindow:K.optional()}).strict(),Ua=F.union([F.date(),F.string().datetime({offset:!0}).transform(e=>new Date(e))]),Wa=F.object({id:F.string(),sessionId:F.string(),tenantId:F.string().optional(),runId:F.string().optional(),role:F.enum([`user`,`assistant`,`system`,`tool`]),parts:F.array(za),attachments:F.array(Ba).optional(),mentions:F.array(Va).optional(),model:Ha.optional(),tokenUsage:F.object({input:K,output:K}).strict().optional(),metadata:F.record(F.string(),F.unknown()).optional(),createdAt:Ua}).strict(),Ga=F.object({id:F.string(),description:F.string(),status:F.enum([`pending`,`in_progress`,`completed`,`blocked`]),result:F.string().optional(),updatedAt:K.optional()}).strict(),Ka=F.object({id:F.string(),sessionId:F.string(),status:F.enum([`active`,`completed`,`abandoned`]),todos:F.array(Ga),version:K,createdAt:F.string(),updatedAt:F.string(),completedAt:F.string().optional()}).strict(),qa={"session-named":F.object({name:F.string()}).strict(),"compaction-start":F.object({reason:F.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:K.optional(),reportedTokens:K.optional()}).strict(),"compaction-end":F.object({tokensBefore:K,tokensAfter:K,tokensSaved:K,strategy:F.enum([`no-op`,`summary`,`truncation`]),durationMs:K,summary:F.string().optional()}).strict(),"compaction-failed":F.object({reason:F.string()}).strict(),usage:F.object({messageId:F.string().min(1).optional(),inputTokens:K,outputTokens:K,totalTokens:K,cacheReadTokens:K.optional(),cacheCreationTokens:K.optional(),contextWindow:K,residentTokens:K,utilization:F.number().finite().min(0).max(1),costUsd:K.optional()}).strict(),"message-persisted":F.object({message:Wa}).strict(),"message-updated":F.object({message:Wa}).strict(),"todo-plan-update":F.object({plan:Ka}).strict(),"approval-context":F.object({approvalId:F.string(),toolCallId:F.string(),impact:Ra.optional(),relaxableByAuto:F.boolean().optional()}).strict(),"session-state":F.object({state:F.object({phase:F.enum([`queued`,`running`,`parked`,`terminal`]),parkedOn:F.enum([`human`,`agents`]).optional(),humanRequestIds:F.array(F.string()).optional(),outcome:F.enum([`completed`,`failed`,`cancelled`,`timeout`,`expired`]).optional()}).strict(),version:F.number().int().positive(),updatedAt:F.string().datetime({offset:!0})}).strict()};function isAgentUIDataName(e){return e in qa}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=F.object({type:F.literal(`data-${n}`),id:F.string().optional(),data:qa[n],transient:F.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 Ja=[`pluralLabel`,`description`,`labelExpression`,`embeddingExpression`];function draftObjectSettings(e){return Object.fromEntries(Ja.filter(t=>e[t]!==void 0).map(t=>[t,e[t]]))}function toDraftableObject(e){return{id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},...draftObjectSettings(e)}}function toDraftableAttributes(e){let t=e.id??e.name;return(e.attributes??[]).map(e=>toDraftableAttribute(e,t))}function toAttribute(e){return{id:e.id,name:e.name,label:e.label,type:e.attributeType,...e.config}}function toDraftableAttribute(e,t){let{id:n,name:r,label:i,type:a,...o}=e;return{id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:o}}function draftedLabelExpression(e){let t=e[0];return t?`{{ ${t.name} }}`:`{{ id }}`}function draftedObjectDefinition(e,t){let n=t.filter(t=>t.objectId===e.id);return{id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},...draftObjectSettings(e),labelExpression:e.labelExpression??draftedLabelExpression(n),attributes:n.map((e,t)=>{let n=toAttribute(e);return n.order===void 0?{...n,order:t}:n})}}function toDraftableView(e,t,n=workspaceViewAuthoring(e.contents)){return structuredClone({...e,...t,authoring:n})}function draftedViewDefinition(e){let{id:t,revision:n,contentIds:r,contentRevisions:i,derived:a,authoring:o,...s}=e;return structuredClone(s)}function fromDraftableView(e,t){return{...e,...draftedViewDefinition(t)}}const Ya={id:F.string().min(1).describe(`Your id, echoed back`),note:F.string().trim().min(1).max(160).optional().describe(`Why, in the person's words, ≤160 chars`)},q={...Ya,objectName:F.string().min(1).describe(`Object`),viewName:F.string().min(1).describe(`View API name`)},J={...q,contentName:F.string().min(1).describe(`Content API name`)},Xa=F.union([F.object({before:F.string().min(1).describe(`Place immediately before this content name`)}).strict(),F.object({after:F.string().min(1).describe(`Place immediately after this content name`)}).strict(),F.object({end:F.literal(!0).describe(`Place at the end of the placement zone`)}).strict()]),viewFocus=e=>({objectName:e.objectName,viewName:e.viewName}),contentFocus=e=>({...viewFocus(e),contentName:e.contentName});function invalid(e,t){throw new D(t,[{path:e,message:t}])}function change(e,t,n,r){let i=e.views.findIndex(e=>e.object===t.objectName&&e.name===t.viewName);i<0&&invalid([`viewName`],`View is not in the draftable state`),e.views[i].authoring||invalid([`authoring`],`Missing view authoring baseline`);let{derived:a,...o}=r(structuredClone(e.views[i]));o.contents=resolveViewContents(o.authoring);let s=e.views.map((e,t)=>t===i?o:e);return validateContentViewCatalogue({extensions:[...n.extensions],objects:e.objects.map(t=>draftedObjectDefinition(t,e.attributes.filter(e=>e.objectId===t.id))),views:s.map(draftedViewDefinition)}),{...e,views:s}}function contentState(e,t){let n=Object.hasOwn(e.authoring.contents,t)?e.authoring.contents[t]:void 0;return n||invalid([`contentName`],`Content is not in the draftable state`),n}function setOrder(e,t,n){for(let r of n)e.authoring[r===`main`?`mainOrderCustomized`:`asideOrderCustomized`]=!0,t.filter(e=>e.placement===r).forEach((t,n)=>{contentState(e,t.name).workspacePosition=n})}function find(e,t){let n=e.contents.find(e=>e.name===t);return n||invalid([`contentName`],`Content is not in the draftable state`),n}function placed(e,t,n){let r=e.filter(e=>e.name!==t.name),i=r.filter(e=>e.placement===t.placement),a=i.length;if(!(`end`in n)){let e=`before`in n?n.before:n.after;a=i.findIndex(t=>t.name===e),a<0&&invalid([`target`],`Order target is not in this placement`),`after`in n&&a++}return i.splice(a,0,t),t.placement===`main`?[...i,...r.filter(e=>e.placement===`aside`)]:[...r.filter(e=>e.placement===`main`),...i]}const Za=F.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 F.NEVER}let r=typeof e==`object`&&e&&`name`in e?e.name:void 0;return{...n.data,name:r}}),Qa=F.object({...J,type:F.literal(`replace_view_content`),definition:Za}).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}}),$a=C.describe(`The whole content definition.`),eo=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:Qa,wire:F.object({...J,type:F.literal(`replace_view_content`),definition:$a}).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}}))}),to=F.object({...q,type:F.literal(`add_view_content`),content:$a,target:Xa.describe(`Where to place the new content within its placement zone`)}).strict(),addFocus=e=>({...viewFocus(e),contentName:e.content.name}),no=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:to,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}}})}),ro=F.object({...J,type:F.literal(`remove_view_content`)}).strict(),io=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:ro,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}})}),ao=F.object({...J,type:F.literal(`move_view_content`),placement:F.enum([`main`,`aside`]).describe(`The placement zone to move the content into`),target:Xa.describe(`Where to place the content within that placement zone`)}).strict(),oo=defineOperation({type:`move_view_content`,summary:`Reorders or moves a content to a different placement; the aside rule applies.`,schema:ao,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)}}})}),so=F.object({...q,type:F.literal(`update_view_metadata`),changes:F.object({label:F.string().min(1).optional().describe(`New label for the view`),description:F.string().optional().describe(`New description for the view`),icon:k.nullable().optional().describe(`New icon; null clears it`)}).strict().refine(e=>Object.keys(e).length>0).describe(`≥1 change`)}).strict(),co=defineOperation({type:`update_view_metadata`,summary:`Updates a view's label, description, or icon (null clears the icon).`,schema:so,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}})}),lo=F.string().refine(e=>e.trim().length>0,`API name must not be blank`),uo=F.object({...q,type:F.literal(`rename_view`),newName:lo.describe(`New API name for the view`)}).strict(),renameViewFocus=e=>({objectName:e.objectName,viewName:e.newName}),fo=defineOperation({type:`rename_view`,summary:`Renames a view; refused on a code-declared name — change it in the declaration.`,schema:uo,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}))}),po=F.object({...J,type:F.literal(`rename_view_content`),newName:lo.describe(`New API name for the content`)}).strict(),renameContentFocus=e=>({...viewFocus(e),contentName:e.newName}),mo=defineOperation({type:`rename_view_content`,summary:`Renames a content; refused on a code-declared name — change it in the declaration.`,schema:po,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}}})}),ho=F.object({...J,type:F.literal(`reset_view_content`)}).strict(),go=defineOperation({type:`reset_view_content`,summary:`Resets a content back to its code-declared source; only works when one exists.`,schema:ho,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}})})}),_o=F.object({...q,type:F.literal(`reset_view_order`),placement:F.enum([`main`,`aside`]).describe(`The placement zone to reset to source order`)}).strict(),vo=defineOperation({type:`reset_view_order`,summary:`Resets a placement zone's order to its code-declared source, if one exists.`,schema:_o,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}})}),yo=F.discriminatedUnion(`type`,[Qa,to,ro,ao,so,uo,po,ho,_o]),Y=[eo,no,io,oo,co,fo,mo,go,vo];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 xo={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 xo?xo[e]:void 0}function requireObject$1(e,t){let n=findObject(e,t);if(!n)throw new D(`Object "${t}" is not in the draftable state`,[]);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$1(e,t),e.attributes),relatedObjects:Object.fromEntries(e.objects.map(t=>[t.name,toCompileObject(t,e.attributes)]))}}function toRollupAttribute(e){return{id:e.id,name:e.name,label:e.label,type:`rollup`,...configOf(e)}}function asValidationError(e){try{return e()}catch(e){throw e instanceof ComputedFormulaCompileError?new 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$1(e,t),i=[];for(let r of compilablePlansOf(e,t))r.attributeName!==n&&r.dependencies.some(e=>dependencyNames(e,n))&&i.push(r.attributeName);for(let a of e.objects)if(a.id!==t)for(let t of compilablePlansOf(e,a.id))t.dependencies.some(t=>{if(t.kind!==`relation`||t.targetAttributeName!==n)return!1;let i=e.attributes.find(e=>e.objectId===a.id&&e.name===t.relationName&&e.attributeType===`relation`);return i!==void 0&&relationTargetObjectName(i)===r.name})&&i.push(`${a.name}.${t.attributeName}`);return i}function bilateralDeclarationOf(e){let t=e.config?.bilateral;if(typeof t!=`object`||!t)return;let{object:n,attribute:r}=t;return typeof n==`string`&&typeof r==`string`?{object:n,attribute:r}:void 0}function sameAttribute(e,t){return t!==void 0&&e.attributeType===t.attributeType&&sameConfig(e,t)}function sameConfig(e,t){return JSON.stringify(e.config??{})===JSON.stringify(t.config??{})}function assertBilateralPairs(e,t){let untouched=t=>sameAttribute(t,e.attributes.find(e=>e.id===t.id));for(let e of t.attributes){if(e.attributeType!==`relation`)continue;let 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 requireObject(e,t){let n=e.objects.find(e=>e.id===t);if(!n)throw new D(`Object "${t}" is not in the draftable state`,[]);return n}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={...Ya,objectId:F.string().uuid().describe(`The object this operation acts on`)},So=defineOperation({type:`add_object`,summary:`Creates an object: kebab-case plural name, icon from search_icons; folds in default_list/default_detail; reserved names are native objects.`,schema:F.object({...X,objectId:F.string().uuid().describe(`Stable id for the new object; the server mints one when omitted`),type:F.literal(`add_object`),name:Kt.describe("kebab-case plural API name (`purchase-orders`)"),label:F.string().min(1).describe(`Label people see`),icon:F.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} »`}),Co=F.object({...X,type:F.literal(`update_object`),changes:F.object({label:F.string().min(1).optional().describe(`New label`),icon:F.string().min(1).optional().describe(`New icon name from search_icons`),pluralLabel:F.string().optional().describe(`New label for many records; "" clears it`),description:F.string().optional().describe(`What this object holds`),labelExpression:L.optional().describe(`Titles every record; syntax in <expressions>`),embeddingExpression:F.literal(``).or(L).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:Co,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)}),To={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])=>To[e]?.(String(t))).filter(e=>e!==void 0);return t.length>0?t.join(` · `):`Modifie l'objet`}const Eo=defineOperation({type:`remove_object`,summary:`Removes an object; refused while a relation attribute targets it — remove it first.`,schema:F.object({...X,type:F.literal(`remove_object`)}),apply:(e,t)=>{requireObject(e,t.objectId);let n=e.objects.find(e=>e.id===t.objectId)?.name;for(let r of e.attributes){if(r.objectId===t.objectId||r.attributeType!==`relation`||!relationTargets(r).some(e=>e.object===n))continue;let i=e.objects.find(e=>e.id===r.objectId);throw new D(`object "${n}" is targeted by attribute "${i?.name}.${r.name}"; remove that attribute first`,[])}return{...e,objects:e.objects.filter(e=>e.id!==t.objectId),attributes:e.attributes.filter(e=>e.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(e=>e.objectId!==t.objectId),views:e.views.filter(e=>e.object!==n)}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Supprime l'objet ${e.objectId}`}),Do=Bn;function assertConfigParses(e,t){try{Ot(e,t)}catch(e){throw e instanceof D?new D(e.message,e.errors.map(e=>({...e,path:[`config`,...e.path??[]]}))):e}}const Oo=F.object({...X,type:F.literal(`add_attribute`),attributeId:F.string().min(1),name:ft,label:F.string().min(1),attributeType:F.enum(Do),config:F.record(F.string(),F.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}}),ko={...Ya,type:F.literal(`add_attribute`),attributeId:F.string().min(1).describe(`Stable attribute id`),name:ft.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),label:F.string().min(1).describe(`Label people see`)},Ao=Object.fromEntries(Rt.map(e=>[e,!0])),jo=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],Mo=F.object(jo.reduce((e,t)=>(Object.assign(e,Et(t).omit(Ao).shape),e),{})).strict(),No=Do.filter(e=>!jo.includes(e)),Po=Object.fromEntries(jo.map(e=>[e,new Set(Object.keys(Et(e).omit(Ao).shape))])),Fo=Lt(Po,`config key`);function refuseForeignSimpleConfigKeys(e,t){Fo(e.attributeType,e.config,t,[`config`])}function wireConfigFor(e){let t=Et(e).omit(Ao);return(e===`relation`||e===`document`?t.extend({properties:Bt.optional()}):t).strict()}const Io=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:Oo,wire:F.discriminatedUnion(`attributeType`,[F.object({...ko,objectId:F.string().uuid(),attributeType:F.enum(jo).describe(`Attribute type`),config:Mo.optional().describe(`Configuration of a simple attribute (text, number, date…)`)}).strict().superRefine(refuseForeignSimpleConfigKeys),...No.map(e=>F.object({...ko,objectId:F.string().uuid(),attributeType:F.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} »`}),Lo={...X,attribute:ft.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 D(`Attribute "${n}" is not on object "${t}"`,[]);return{object:i,attribute:a}}const Ro=defineOperation({type:`update_attribute`,summary:`Updates an attribute's label, or replaces its whole config; a published config can't change — add a new attribute and migrate values.`,schema:F.object({...Lo,type:F.literal(`update_attribute`),changes:F.object({label:F.string().min(1).optional().describe(`New label`),config:F.record(F.string(),F.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} »`}),zo=defineOperation({type:`remove_attribute`,summary:`Removes an attribute; refused while a sample carries its value, a content names it, or a formula/rollup depends on it — remove those first.`,schema:F.object({...Lo,type:F.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{an(i)}catch{return}let a=sn(i,r);if(a.success)return;let o=a.errors??[],s=o.map(e=>e.path.length>1?`${e.path.join(`.`)}: ${e.message}`:e.message).join(`, `);throw new D(`Sample record "${e}" has an invalid value for "${t}": ${s}`,o.map(e=>({path:e.path,message:e.message})))}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}"`,[])}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 D(`sample record "${t}" references unknown sample "${n}"`,[])}}const Bo=defineOperation({type:`add_sample_record`,summary:`Adds a sample record; keys are attribute names, required covered, computed never set; relation value is a minted/published recordId; publication is preview or requested-data.`,schema:F.object({...X,type:F.literal(`add_sample_record`),recordId:F.string().uuid().describe(`Minted by the server when omitted`),values:F.record(F.string(),F.unknown()).describe("Attribute name → value; currency is `{code,value}`, relation is a record id or name minted here"),publication:F.enum([`preview`,`requested-data`]).optional().describe(`preview = display-only; requested-data = real records asked for`)}),apply:(e,t)=>{if(requireObject(e,t.objectId),e.sampleRecords.some(e=>e.id===t.recordId))throw new D(`Sample record "${t.recordId}" already exists`,[]);let n=new Map(e.attributes.filter(e=>e.objectId===t.objectId).map(e=>[e.name,e]));for(let[r,i]of Object.entries(t.values)){let a=n.get(r);if(!a)throw new D(`Sample record "${t.recordId}" uses unknown attribute "${r}"`,[]);if(isComputedAttribute(a))throw new D(`attribute "${a.name}" is computed and cannot be set on a sample record`,[]);assertUnknownSampleReference(e,t.recordId,a,i),assertSampleValue(t.recordId,r,a,i)}for(let e of n.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=[So,wo,Eo,Io,Ro,zo,Bo,defineOperation({type:`remove_sample_record`,summary:`Removes a sample record; refused while another sample still references it.`,schema:F.object({...X,type:F.literal(`remove_sample_record`),recordId:F.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 D(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,[]);return assertSampleNotReferenced(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(e=>e.id!==t.recordId)}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Retire un exemple`})];function build(){let e=new Map;for(let t of[...Z,...Y]){if(e.has(t.type))throw new w(`architect operation`,t.type);e.set(t.type,t)}return e}const Vo=build(),Ho=[...Vo.keys()];function defOf(e){let t=Vo.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=Vo.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=>F.tuple([F.literal(e),F.string()]),Uo=F.union([F.tuple([F.literal(`content`),F.string(),F.string(),F.string()]),F.tuple([F.literal(`view`),F.string(),F.string()]),F.tuple([F.literal(`attribute`),F.string(),F.string()]),F.tuple([F.literal(`sample`),F.string(),F.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=yo.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:${M(e)}`}const Wo=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=Uo.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 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 Q=F.string().min(1),Go=F.union([F.object({objectName:Q,viewName:Q,contentName:Q.optional()}).strict().describe(`Full configuration of a view, or of one content when contentName is given`),F.object({objectId:Q}).strict().describe(`An object with its attributes, by id`),F.object({objectName:Q}).strict().describe(`An object with its attributes`),F.object({objectId:Q,attributeName:Q}).strict().describe(`One attribute's config, by name`),F.object({objectId:Q,attributeId:Q}).strict().describe(`One attribute's config, by id`),F.object({objectId:Q,recordId:Q}).strict().describe(`One sample record`)]);function parseNamedTarget(e){let t=Go.safeParse(e);if(!t.success)throw new D(`Invalid scoped target`,[{path:[`target`],message:`Expected exactly one named target branch`}]);return t.data}const Ko=F.object({type:F.literal(`remove_operation`),operationId:F.string().min(1).describe(`The id of a stored operation to drop from the draft`)}),qo=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 F.discriminatedUnion(`type`,e)}function isUuidString(e){return e instanceof F.ZodString&&e.format===`uuid`}function asUnionMember(e){let t=e;return!Array.isArray(t.options)||typeof t.def?.discriminator!=`string`?null:{discriminator:t.def.discriminator,options:t.options}}function mapMember(e,t){let n=asUnionMember(e);return n===null?t(e):F.discriminatedUnion(n.discriminator,n.options.map(t))}function relaxUuidKeys(e){return mapMember(e,e=>{let t={};for(let[n,r]of Object.entries(e.shape)){if(!isUuidString(r))continue;let e=F.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 Jo={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of Jo[e.shape.type.value]??[]){let r=e.shape[n];r instanceof F.ZodString&&(t[n]=r.optional())}return Object.keys(t).length===0?e:e.safeExtend(t)})}function withOriginalChecks(e,t){let n=e._zod.def.checks;return!n||n.length===0?t:t.check(...n)}function addressByName(e){return mapMember(e,e=>{if(e.shape.type.value===`add_object`||!(`objectId`in e.shape))return e;let{objectId:t,...n}=e.shape;return withOriginalChecks(e,F.object({...n,objectName:F.string().min(1).describe(`Object`)}).strict())})}const Yo=membersOf(Z,[Ko]),Xo=membersOf(Y),Zo=unionOf(Yo),Qo=unionOf(Xo),$o={schema:Zo,view:Qo},es={schema:unionOf(wireMembersOf(Z,[Ko])),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 ns=[`draft_schema`],rs=`publish_architect_draft`,is=`discard_architect_draft`,as=`request_design_review`,os=`get_architect_draft`,ss=[{input:{operations:[{type:`add_attribute`,id:`op-statut`,objectName:`devis`,attributeId:`attr-statut`,name:`statut`,label:`Statut`,attributeType:`select`,config:{options:[{value:`draft`,label:`Brouillon`,color:`gray`},{value:`sent`,label:`Envoyé`,color:`blue`},{value:`accepted`,label:`Accepté`,color:`green`}]}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:`add_view_content`,id:`op-open`,objectName:`devis`,viewName:`default_list`,content:{name:`open`,label:`À traiter`,type:`collection`,placement:`main`,layout:`table`,source:{object:`devis`},columns:[`title`,`client`,`montant`,`statut`],filters:{combinator:`and`,rules:[{attribute:`statut`,operator:`is`,value:`sent`}]},sorts:[{attribute:`montant`,direction:`desc`}]},target:{end:!0}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:`replace_view_content`,id:`op-all`,objectName:`devis`,viewName:`default_list`,contentName:`all`,definition:{name:`all`,type:`collection`,placement:`main`,layout:`table`,source:{object:`devis`},columns:[`title`,`client`,`montant`,`statut`]}}],guard:{revision:null,targetTokens:{}}}}],$=F.string().refine(e=>e.trim().length>0,`Must not be blank`),cs=F.union([F.tuple([F.literal(`object`),$]),F.tuple([F.literal(`attribute`),$,$]),F.tuple([F.literal(`view`),$,$]),F.tuple([F.literal(`content`),$,$,$])]),ls=F.object({label:$,pluralLabel:F.string().optional(),description:F.string().optional(),icon:k.optional(),labelExpression:F.string(),embeddingExpression:F.string().optional(),sealed:F.boolean().optional(),toleratedAttributes:F.array($).optional(),metadata:F.record(F.string(),F.unknown()).optional(),schema_version:F.number().int().nonnegative(),migrations:F.array(F.record(F.string(),F.unknown())),documentLayout:F.record(F.string(),F.unknown()).optional()}).strict();function failure(e){throw new D(e,[])}function definitionSchema(e){return F.custom(t=>{let n=F.record(F.string(),F.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`:ls.parse(n);break;case`attribute`:{let e=F.enum(Bn).parse(n.type);Nt(e).extend({type:F.literal(e),label:$,required:F.boolean().optional(),unique:F.boolean().optional(),icon:k.optional()}).strict().parse(n);break}case`view`:{let{contents:t,...r}=n,i=F.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=F.record(F.string(),F.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=F.object({modelVersion:F.literal(1),hashVersion:F.literal(1),tenant:$,sourceFingerprint:F.string().regex(/^[a-f0-9]{64}$/),entries:F.array(F.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=cs.parse(F.object({address:F.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`?F.object({id:F.string().uuid(),updatedAt:F.string().datetime()}).strict():F.object({id:F.string().uuid(),revision:F.number().int().nonnegative()}).strict(),o=F.object({address:cs,source:i,effective:i,status:F.enum([`source`,`runtime`,`copy`,`suppressed`]),sourceOwner:F.union([F.literal(`core`),F.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 F.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`:M(n.source)===M(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{Wo as ABSENT_TARGET_TOKEN,Pi as AGENT_UI_BATCH_MAX_BYTES,Fi as AGENT_UI_BATCH_MAX_ITEMS,Mr as ALLOWED_PROPERTY_TYPES,I as ALL_ACTIONS,Ho as ALL_OPERATION_TYPES,Lr as ALL_PIPES,Wr as ALL_SYSTEM_RESOURCES,yr as ARTIFACT_FILE_ROLES,_r as ARTIFACT_KINDS,xi as ARTIFACT_LIST_VIEW,yi as ARTIFACT_OBJECT,H as ARTIFACT_OBJECT_NAME,vi as ARTIFACT_PREVIEW_EXTENSION,vr as ARTIFACT_RETENTIONS,bi as ARTIFACT_VIEW,Ae as ATTRIBUTE_FILTER_OPERATORS,Bn as ATTRIBUTE_TYPES,Un as AUDIT_ACTIONS,Hn as AUDIT_RESOURCE_TYPES,je as AccessDeniedError,AgentBuilder,Me as AttributeInUseError,Ne as AttributeNotFoundError,Rn as BEHAVIOR_PROPERTIES,Ar as BYTE_UNIT_LABELS,Gn as CLAIMABLE_SESSION_STATUSES,Zi as COMPUTED_FUNCTIONS,Qi as COMPUTED_FUNCTION_METADATA,Xi as COMPUTED_FUNCTION_NAMES,na as CONNECTOR_CALLBACK_PARAM,Dr as COUNT_MODES,Pe as ChangeTypeNotSupportedError,ComputedFormulaCompileError,Gt as ComputedFormulaParseError,Fe as ConcurrentModificationError,z as ContentBuilder,Ur as DB_COLUMN_FIELDS,$r as DEFAULT_AGENT_EXECUTION_CONFIG,Kn as DEFAULT_APPROVAL_POLICY,gr as DEFAULT_DICTATION_LIMITS,Rr as DEFAULT_LABEL_FALLBACK,Sr as DEFAULT_MEETING_BOT_DISPLAY_NAME,Kr as DEFAULT_ROLES,Jr as DEFAULT_ROLE_DESCRIPTIONS,qr as DEFAULT_ROLE_LABELS,Qr as DEFAULT_ROLE_PERMISSIONS,Cr as DEFAULT_TENANT_SETTINGS,yn as DEFAULT_VALIDATION_MESSAGES,mr as DICTATION_FINALIZATION_TIMEOUT_MS,cr as DICTATION_FRAME_BYTES,ur as DICTATION_MAX_BUFFER_BYTES,lr as DICTATION_MAX_FRAME_BYTES,dr as DICTATION_MAX_TRANSCRIPT_BYTES,hr as DICTATION_MODEL_ID,pr as DICTATION_PREPARATION_TIMEOUT_MS,sr as DICTATION_SAMPLE_RATE,fr as DICTATION_TICKET_TTL_MS,is as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,jr as DOCUMENT_SYSTEM_ATTRIBUTES,Do as DRAFTABLE_ATTRIBUTE_TYPES,qo as DRAFT_BATCH_LIMIT,Ja as DRAFT_OBJECT_SETTINGS,ss as DRAFT_SCHEMA_INPUT_EXAMPLES,ns as DRAFT_WRITE_TOOL_NAMES,_i as DRIVE_LIST_VIEW,hi as DRIVE_OBJECT,V as DRIVE_OBJECT_NAME,gi as DRIVE_VIEW,Ie as DestructiveSyncNotAllowedError,w as DuplicateError,Pr as EMPTY_VALUE_PLACEHOLDER,Or as ESTIMATED_COUNT_CAP,ua as FAKE_MEETING_BOT_SIGNATURE_HEADER,$o as FAMILY_INPUTS,es as FAMILY_WIRE_INPUTS,xr as FORM_FORBIDDEN_ATTRIBUTE_TYPES,FlagRegistry,FlagService,Le as ForbiddenError,FormBuilder,FormRegistry,FormRowBuilder,FormStepBuilder,os as GET_ARCHITECT_DRAFT_TOOL_NAME,ni as GroupBuilder,Ln as IDENTITY_PROPERTIES,Er as IMAGE_FORMATS,Xn as INFERENCE_REASONING_OPTIONS,Yn as INFERENCE_SPEEDS,vt as LIST_VIEW_TAB_VISIBILITIES,Ii as LIVE_EVENT_TYPES,n as LOCATION_FILTER_PROPERTIES,ia as MAILBOX_LIST_MODES,oa as MAIL_DRAFT_BODY_MAX_CHARS,sa as MAIL_SUBJECT_MAX_CHARS,br as MAX_PRESET_DEPTH,tr as MAX_TODOS,rr as MAX_TODO_DESCRIPTION_CHARS,nr as MAX_TODO_ID_CHARS,W as MEETING_ATTRIBUTES,wi as MEETING_DETAIL_VIEW_ID,Oi as MEETING_LIST_VIEW,Si as MEETING_LIST_VIEW_ID,Ei as MEETING_OBJECT,U as MEETING_OBJECT_NAME,Di as MEETING_VIEW,Ci as MEETING_WRITE_SOURCE,mi as MEMORY_LIST_VIEW,di as MEMORY_OBJECT,pi as MEMORY_VIEW,ra as McpOAuthCompletionMode,Re as MemoryNotFoundError,ze as MigrationTimeoutError,MultiRelationAttributeBuilder,ar as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,or as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,St as NATIVE_OBJECT_NAMES,jn as NOTIFICATION_INBOX_STATES,On as NOTIFICATION_KINDS,kn as NOTIFICATION_PRIORITIES,An as NOTIFICATION_SENSITIVITIES,In as NOTIFICATION_TYPES_V1,Fn as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,Nn as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,Pn as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,Mn as NOTIFICATION_WORK_STATES,da as NO_RECORDING,g as NO_VALUE_OPERATORS,Qt as NonJsonValueError,NoopGeocodingAdapter,Be as NotFoundError,Ve as NotImplementedError,Kt as OBJECT_NAME_SCHEMA,Qn as OPEN_TOOL_PART_STATES,Vo as OPERATION_REGISTRY,o as OPERATORS_BY_TYPE,$i as OPERATOR_SPECS,ObjectBuilder,He as ObjectNotFoundError,Ue as ObjectReferencedError,We as OrphanSystemAttributeError,Ir as PIPES_WITH_ARGS,zn as PRESENTATION_PROPERTIES,Jn as PROVIDER_NAMES,rs as PUBLISH_ARCHITECT_DRAFT_TOOL_NAME,Ge as ProtectedResourceError,Ke as ProtectedRoleError,Nr as QUALIFIED_SEPARATOR,kr as QUOTA_KEYS,ca as RECORDING_OVERRIDES,la as RECORDING_POLICIES,Hr as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,Vn as RELATION_TARGET_ANY,ue as REMOVED_OPERATOR_REPLACEMENTS,Ko as REMOVE_OPERATION_SCHEMA,aa as REPLY_MODES,as as REQUEST_DESIGN_REVIEW_TOOL_NAME,yt as RESERVED_ATTRIBUTE_NAMES,xt as RESERVED_OBJECT_NAMES,ht as RESOURCE_VISIBILITIES,qe as RecordNotFoundError,Je as RecordReferencedError,Ye as RepositoryError,Xe as ReservedObjectNameError,Ze as RoleNotFoundError,Ct as SCHEMA_LIMITS,Z as SCHEMA_OPERATIONS,Zo as SCHEMA_OPERATION_INPUT,G as SCHEMA_PLAN_LIMITS,pa as SCHEMA_SOURCE_ID_PATTERN,ir as SESSION_STATE_STREAM_ID,Wn as SESSION_TERMINAL_STATUSES,Fr as SIMPLE_PIPES,Ut as SIMPLE_PROPERTY_TYPES,si as SKILL_CONTENT_TEMPLATE,ui as SKILL_LIST_VIEW,ci as SKILL_OBJECT,li as SKILL_VIEW,ei as STANDARD_SCHEMA_VENDOR,oe as SYNONYM_ALIASES,re as SYSTEM_ATTRIBUTES,_ as SYSTEM_ATTRIBUTE_I18N_KEYS,gt as SYSTEM_FIELD_NAMES,be as SYSTEM_FILTER_ATTRIBUTE_TYPES,$n as SYSTEM_PART_CODES,R as SYSTEM_RESOURCES,Gr 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,pn as TEXT_FORMAT_PATTERNS,ta as TODAY_DEFAULT,qn as TODO_PLAN_STATUSES,er as TODO_STATUSES,Zn as TOOL_APPROVAL_STATES,wr as USER_STATUSES,Tr as USER_WORK_POSTURES,Y as VIEW_OPERATIONS,Qo as VIEW_OPERATION_INPUT,D as ValidationError,ti as ViewBuilder,Rt as WIRE_OMITTED_CONFIG_KEYS,accessLevelToActions,actionsToAccessLevel,agent,agentDataChunk,agentDisplayName,Na as agentInferencePreferencesSchema,Ba as agentMessageAttachmentSchema,za as agentMessagePartSchema,Fa as agentSessionInferenceOverridesInputSchema,Ia as agentSessionInferenceOverridesSchema,Wa as agentSessionMessageSchema,agentUIValidationError,applyOperations,applyPipes,applyRelationProps,architectDraftChannelKey,architectFocusKey,en as asTenantId,Zt as asUserId,assertAcyclicComputed,assertAcyclicComputedDependencies,assertBilateralPairs,assertCustomAgentUIMessageChunk,assertSchemaSourceId,Vt as attributeConfigSchemas,bilateralDeclarationOf,booleanFlag,buildAgentFallbackTitle,buildPermissionFlags,buildPropertySchema,buildQualifiedAttribute,M as canonicalStringify,yo as canonicalViewOperationSchema,r as canonicalizeFilterValue,checkbox,collectContentViewCatalogue,_e as collectQualifiedRuleIssues,collectSchemaReferences,ve as collectionContentSourceSchema,collectionContentsOf,collectionSourceAddress,collectionSourceAddressOf,Dt as colorIdSchema,Se as columnsSchema,compareAgentSessionMessages,compareSchemaStateEntries,compilablePlansOf,compileComputedFormula,compileRollupAttribute,computeByteMagnitude,computedCompileSchemaOf,computedPlanOf,B as content,contentDefinition,Mi as contentExtensionRegistry,pe as contentViewDefinitionSchema,ae as contentViewDefinitionSchemaFor,conversationDisplayTitle,xn as createCheckboxValidator,Sn as createDateValidator,createFlagRegistry,createFlagService,on as createFormAttributeValidator,Cn as createNumberValidator,createStandardSchemaProps,hn as createTextValidator,currency,t as currentActor,qa as customDataChunkSchemas,date,dateInTimezone,dateValueStart,$t as deepEqual,defaultViewIdsFor,defaultViewsFor,defineOperation,definePresentation,dependentsOf,deriveArchitectChanges,deriveCreateDefaultsFromFilters,deriveInitials,describeOperations,xa as destructiveSchema,detailView,diffSchemaState,ye as displayAttributesSchema,document,Ce as draftContentViewDefinitionSchema,se as draftContentViewDefinitionSchemaFor,draftObjectSettings,draftedLabelExpression,draftedObjectDefinition,draftedViewDefinition,Ua as durableDateSchema,episodeImpactOf,evaluateComputedAst,evaluateComputedFormula,evaluateComputedFormulaWithResult,evaluateFilterState,evaluateRecordFilterState,extractAttributeNames,h as extractCurrencyFilterValue,he as extractFilterValue,extractValueRefs,familyOf,l as filterOperatorsByTypeForGeneration,ge as filterStateSchema,findRelationAttribute,ri as flagRegistry,focusOf,form,formFieldFlatKey,formFieldKey,Ni as formRegistry,formatAgentStreamFrameId,formatAttributeValue,formatByteSize,formatComputedResult,formatLocationValue,bn as formatZodErrors,formula,fromDraftableView,Yt 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,k as iconNameSchema,Pa as imageModelIdSchema,includesAction,qt as indexBy,inferInverseCardinality,inferRollupReturnType,ja as inferenceReasoningSchema,Aa as inferenceSpeedSchema,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,j as isNativeObjectName,ee as isNoValueOperator,isNotEmpty,ot as isNotFoundError,N 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,cn as isValuePresent,jsonFlag,legacyStatusToSessionState,listView,liveChannelKey,location,matchesAccepts,Va as mentionReferenceSchema,Ha as modelDefinitionSchema,Ma as modelReferenceSchema,multiselect,zt as multiselectOptionWriteSchema,Go as namedTargetSchema,nativeAgentUIPartIdMetadataKey,normalizeDateValue,Oe as normalizeFilterRule,a as normalizeForEdgeRpc,v as normalizeOperator,p as now,number,numberFlag,object,orderAgentSessionMessages,parseAgentStreamFrameId,Ht as parseAttributeConfig,Ot as parseAttributeConfigForCreate,It as parseAttributeConfigForUpdate,A as parseComputedFormula,parseCountMode,parseLiveChannelKey,parseNamedTarget,parseNativeAgentUIPartIdsMetadata,parseOperation,parseOptionalCountMode,parseQualifiedAttribute,_t as parseResourceVisibility,parseSchemaState,Da as persistedSchemaPlanSchema,phone,va as plannedAttributeSchema,ya as plannedInlineAttributeSchema,ba as plannedObjectSchema,presentationOf,Wt as propertyAttributeSchema,kt as propertyAttributeWireSchema,At as propertySchemaSchema,Bt as propertySchemaWireSchema,proposalTargetKey,ka as providerNameSchema,C as publishedViewContentDefinitionSchema,qualifiedPropertyDefs,readFormFieldValue,reconcileRelationAttributes,Lt as refuseForeignKeys,regenerateDerived,ai as registry,un 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,mn as resolveTextPattern,Ee as resolveUtcDayBounds,resolveViewContents,richtext,rollup,rollupToFormulaExpression,Jt as sameStableValue,Ta as schemaPlanSchema,schemaStateSourcePayload,select,Mt as selectOptionWriteSchema,Xt as serializeCanonicalJson,tn as serializeStableJson,La as sessionInferencePatchSchema,sessionStateToLegacyStatus,ce 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,ke as toUtcDayString,m as today,Ga as todoItemSchema,Ka as todoPlanSchema,Ra as toolImpactSchema,touchedObjectIds,user,mt as validateAttributeName,validateContentViewCatalogue,nn as validateDraft,ln as validateDraftOrThrow,validateLabelExpression,dn as validateObject,validateObjectExpressions,Ft as validateObjectName,rn as validateObjectOrThrow,fe as validateQualifiedRule,validateStoredViews,Pt as validateViewName,viewIdFor,viewIdentityKey,ki 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(),Mi=markSystemView(detailView(ki,`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()),Ni=markSystemView(listView(Di,`Meetings`).for(H).default().tab(`workspace`,`Shared`,z.collection().object(H).table().icon(`users`).visibility(`workspace`).columns(...Ai).sort(U.startsAt,`desc`)).tab(`mine`,`My meetings`,z.collection().object(H).table().icon(`lock`).visibility(`private`).columns(...Ai).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 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 Pi=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 Fi=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}function requireAttribute$1(e,t,n,r,i){if(requireName(t,n),!e)return;let a=e.attributes?.get(t)??Fi.get(t);if(!a){if(!e.attributes)return;let r=[...e.attributes.keys()].slice(0,30),a=r.length===0?`Object "${e.name}" has no attributes yet.`:`Attributes of "${e.name}": ${r.join(`, `)}`;reject$2(n,`Unknown attribute "${e.name}.${t}". ${a}${i?.()??``}`)}return r&&a.type!==r&&reject$2(n,`Attribute "${e.name}.${t}" must have type ${r}`),a}function collectContentViewCatalogue(e){let 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 Ii=[Object.freeze(Ci)];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 Ii)this.extensions.set(e.name,e)}};const Li=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 Ri=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 zi=204800,Bi=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 Vi=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}),Hi=[`membership-unknown`,`sort-unknown`,`permissions-changed`],Ui=[`permission-revoked`,`workspace-left`,`object-deleted`],Wi=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],Gi=[`type`,`objectId`,`recordId`,`recordVersion`],Ki=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],qi=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],Ji=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&Vi.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,Gi)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$1(e)&&hasOnlyKeys(e,qi)&&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,Ki)&&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,Hi)}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=>Wi.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,Ji)&&hasNonEmptyString(e,`targetActorId`)&&hasVersion(e,`archivedCount`)&&hasVersion(e,`version`)&&hasIsoDateString(e,`updatedAt`)}const Yi=[`armed`,`disarmed`],Xi=[`authoring`,`compiling`,`replaying`,`promoted`,`failed`],Zi=[`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,Yi)&&hasIsoDateString(e,`updatedAt`)}function isReflexRunCompletedPayload(e){return e.type===`reflex.run.completed`&&hasNonEmptyString(e,`reflexId`)&&hasNonEmptyString(e,`runId`)&&isOneOf(e.served,Zi)&&hasVersion(e,`version`)&&hasVersion(e,`wallMs`)&&hasIsoDateString(e,`completedAt`)}function isReflexAuthoringProgressPayload(e){return e.type===`reflex.authoring.progress`&&hasNonEmptyString(e,`reflexId`)&&isOneOf(e.status,Xi)&&hasIsoDateString(e,`updatedAt`)}const Qi=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,Qi)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const $i=[`ok`,`low`,`exhausted`,`paused`],ea=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,$i)&&isOneOf(e.mode,ea)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,Ui)}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 ta=[`if`,`concat`,`sum`,`avg`,`count`,`min`,`max`,`earliest`,`latest`,`unique`,`first`,`percent_empty`,`percent_not_empty`,`count_empty`,`count_not_empty`,`count_unique`],na={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(na,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=na[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}=na[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(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 ra=[{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)}),ia={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}),aa=[...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,...aa])}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=ia[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=ia[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=ia[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 oa=`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 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 la=[`threads`,`messages`];function isMailboxListMode(e){return la.includes(e)}const ua=[`reply`,`reply_all`];function isReplyMode(e){return ua.includes(e)}const da=2e5,fa=998,pa=[`force`,`skip`],ma=[`none`,`all`,`external_only`],ha=`x-fake-signature`,ga={override:null,status:`none`,failureReason:null,botId:null},_a=/^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&&!_a.test(t)?t:e.firstUserText?buildAgentFallbackTitle(e.firstUserText):e.emptyLabel}const va=/^[a-z0-9][a-z0-9-]{0,62}$/;function assertSchemaSourceId(e){if(!va.test(e))throw new E(`Invalid schema source id "${e}": expected a lowercase slug matching ${va}`,[])}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 ya=P.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.'),ba=P.string().min(1).superRefine((e,t)=>{try{pt(e)}catch(e){t.addIssue({code:P.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).`),xa=P.string().min(1).superRefine((e,t)=>{A(e)&&t.addIssue({code:P.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:P.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:P.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:P.ZodIssueCode.custom,path:[`config`],message:`Config for type "${e.type}" is invalid or incomplete: ${errorMessage(n)}`})}})}const Sa=P.object({objectName:P.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:ba,label:P.string().min(1).max(128).describe(`Human-readable display label shown in the UI. 1-128 characters, cannot be empty.`),type:ya,config:P.record(P.string(),P.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:P.boolean().optional().describe(`Whether the attribute must have a value on every record. Defaults to false (optional).`),description:P.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),Ca=withConfigCheck(Sa),wa=withConfigCheck(Sa.omit({objectName:!0})),Ta=P.object({name:xa,label:P.string().min(1).describe(`Human-readable singular display label (e.g. "Devis").`),pluralLabel:P.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:P.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: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:P.array(wa).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(),Ea=P.object({attributeRemovals:P.array(P.object({objectName:P.string().min(1).describe(`Object the attribute is removed from.`),attributeName:P.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:P.array(P.object({objectName:P.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:P.array(P.object({objectName:P.string().min(1).describe(`Object the renamed attribute belongs to.`),from:P.string().min(1).describe(`Current attribute name. Must already exist and not be a system attribute.`),to:ba.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:[]}),Da=P.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.`),Oa=P.object({objects:P.array(Ta).default([]),attributes:P.array(Ca).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}),P.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}`}),P.NEVER):e}const ka=P.object({schemaPlanVersion:P.literal(2).describe(`Required proposal contract version.`),summary:Da,additive:Oa,destructive:Ea}).strict().superRefine(addPlanLimitIssues),Aa=Object.assign(P.preprocess(boundSerializedPlanInput,ka),{shape:ka.shape}),ja=P.object({schemaPlanVersion:P.literal(2),summary:Da,additive:Oa,destructive:Ea}).strict().superRefine(addPlanLimitIssues),Ma=P.preprocess(boundSerializedPlanInput,ja);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 Na=/^[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);(!Na.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 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);(!Na.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 G=P.number().finite().nonnegative(),Pa=P.enum(Yn),Fa=P.enum(Xn),Ia=P.enum(Zn),La=P.object({provider:Pa,model:P.string().min(1)}).strict(),Ra=P.object({speed:Fa.optional(),reasoning:Ia.optional()}).strict(),za=P.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),Ba=P.object({model:La.optional(),speed:Fa.optional(),reasoning:Ia.optional(),imageModel:za.optional()}).strict(),Va=Ba.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`}),Ha=P.object({model:La.nullable().optional(),speed:Fa.nullable().optional(),reasoning:Ia.nullable().optional(),imageModel:za.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`}),Ua=P.object({label:P.string(),denied:P.boolean().optional(),deletion:P.object({target:P.string().optional(),count:G.optional(),restorableDays:G.optional()}).strict().optional(),counts:P.record(P.string(),G).optional(),warnings:P.array(P.string()).optional()}).strict(),Wa=P.union([P.object({type:P.literal(`text`),text:P.string()}).strict(),P.object({type:P.literal(`reasoning`),text:P.string()}).strict(),P.object({type:P.literal(`system`),code:P.enum(er)}).strict(),P.object({type:P.literal(`error`),error:P.string(),errorClass:P.string().optional()}).strict(),P.object({type:P.literal(`tool`),toolCallId:P.string(),name:P.string(),args:P.record(P.string(),P.unknown()),result:P.unknown().optional(),error:P.string().optional(),errorCode:P.enum([`output_limit_reached`,`interrupted`]).optional(),state:P.enum([`streaming`,`running`,`completed`,`error`,`pending`,`approval-requested`,`approval-responded`,`approval-dispatched`]),durationMs:G.optional(),approvalId:P.string().optional(),approvalImpact:Ua.optional(),approved:P.boolean().optional(),approvalReason:P.string().optional(),approvalRelaxableByAuto:P.boolean().optional()}).strict(),P.object({type:P.literal(`file`),fileId:P.string(),name:P.string(),mimeType:P.string()}).strict(),P.object({type:P.literal(`compaction`),state:P.literal(`in-progress`),reason:P.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:G.optional(),reportedTokens:G.optional()}).strict(),P.object({type:P.literal(`compaction`),state:P.literal(`completed`),tokensBefore:G,tokensAfter:G,tokensSaved:G,strategy:P.enum([`no-op`,`summary`,`truncation`]),durationMs:G,summary:P.string().optional()}).strict(),P.object({type:P.literal(`compaction`),state:P.literal(`failed`),reason:P.string(),durationMs:G.optional()}).strict()]),Ga=P.object({id:P.string(),name:P.string(),mimeType:P.string(),size:G}).strict(),Ka=P.object({id:P.string(),type:P.string().transform(e=>e),entityId:P.string(),label:P.string(),objectName:P.string().optional(),startIndex:G,endIndex:G}).strict(),qa=P.object({provider:Pa,model:P.string(),maxTokens:G.optional(),contextWindow:G.optional()}).strict(),Ja=P.union([P.date(),P.string().datetime({offset:!0}).transform(e=>new Date(e))]),Ya=P.object({id:P.string(),sessionId:P.string(),tenantId:P.string().optional(),runId:P.string().optional(),role:P.enum([`user`,`assistant`,`system`,`tool`]),parts:P.array(Wa),attachments:P.array(Ga).optional(),mentions:P.array(Ka).optional(),model:qa.optional(),tokenUsage:P.object({input:G,output:G}).strict().optional(),metadata:P.record(P.string(),P.unknown()).optional(),createdAt:Ja}).strict(),Xa=P.object({id:P.string(),description:P.string(),status:P.enum([`pending`,`in_progress`,`completed`,`blocked`]),result:P.string().optional(),updatedAt:G.optional()}).strict(),Za=P.object({id:P.string(),sessionId:P.string(),status:P.enum([`active`,`completed`,`abandoned`]),todos:P.array(Xa),version:G,createdAt:P.string(),updatedAt:P.string(),completedAt:P.string().optional()}).strict(),Qa={"session-named":P.object({name:P.string()}).strict(),"compaction-start":P.object({reason:P.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:G.optional(),reportedTokens:G.optional()}).strict(),"compaction-end":P.object({tokensBefore:G,tokensAfter:G,tokensSaved:G,strategy:P.enum([`no-op`,`summary`,`truncation`]),durationMs:G,summary:P.string().optional()}).strict(),"compaction-failed":P.object({reason:P.string()}).strict(),usage:P.object({messageId:P.string().min(1).optional(),inputTokens:G,outputTokens:G,totalTokens:G,cacheReadTokens:G.optional(),cacheCreationTokens:G.optional(),contextWindow:G,residentTokens:G,utilization:P.number().finite().min(0).max(1),costUsd:G.optional()}).strict(),"message-persisted":P.object({message:Ya}).strict(),"message-updated":P.object({message:Ya}).strict(),"todo-plan-update":P.object({plan:Za}).strict(),"approval-context":P.object({approvalId:P.string(),toolCallId:P.string(),impact:Ua.optional(),relaxableByAuto:P.boolean().optional()}).strict(),"session-state":P.object({state:P.object({phase:P.enum([`queued`,`running`,`parked`,`terminal`]),parkedOn:P.enum([`human`,`agents`]).optional(),humanRequestIds:P.array(P.string()).optional(),outcome:P.enum([`completed`,`failed`,`cancelled`,`timeout`,`expired`]).optional()}).strict(),version:P.number().int().positive(),updatedAt:P.string().datetime({offset:!0})}).strict()};function isAgentUIDataName(e){return e in Qa}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=P.object({type:P.literal(`data-${n}`),id:P.string().optional(),data:Qa[n],transient:P.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 $a=[`pluralLabel`,`description`,`labelExpression`,`embeddingExpression`];function draftObjectSettings(e){return Object.fromEntries($a.filter(t=>e[t]!==void 0).map(t=>[t,e[t]]))}function toDraftableObject(e){return{id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},...draftObjectSettings(e)}}function toDraftableAttributes(e){let t=e.id??e.name;return(e.attributes??[]).map(e=>toDraftableAttribute(e,t))}function toAttribute(e){return{id:e.id,name:e.name,label:e.label,type:e.attributeType,...e.config}}function toDraftableAttribute(e,t){let{id:n,name:r,label:i,type:a,...o}=e;return{id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:o}}function draftedLabelExpression(e){let t=e[0];return t?`{{ ${t.name} }}`:`{{ id }}`}function draftedObjectDefinition(e,t){let n=t.filter(t=>t.objectId===e.id);return{id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},...draftObjectSettings(e),labelExpression:e.labelExpression??draftedLabelExpression(n),attributes:n.map((e,t)=>{let n=toAttribute(e);return n.order===void 0?{...n,order:t}:n})}}function toDraftableView(e,t,n=workspaceViewAuthoring(e.contents)){return structuredClone({...e,...t,authoring:n})}function draftedViewDefinition(e){let{id:t,revision:n,contentIds:r,contentRevisions:i,derived:a,authoring:o,...s}=e;return structuredClone(s)}function fromDraftableView(e,t){return{...e,...draftedViewDefinition(t)}}const eo={id:P.string().min(1).describe(`Your id, echoed back`),note:P.string().trim().min(1).max(160).optional().describe(`Why, in the person's words, ≤160 chars`)},K={...eo,objectName:P.string().min(1).describe(`Object`),viewName:P.string().min(1).describe(`View API name`)},q={...K,contentName:P.string().min(1).describe(`Content API name`)},to=P.union([P.object({before:P.string().min(1).describe(`Place immediately before this content name`)}).strict(),P.object({after:P.string().min(1).describe(`Place immediately after this content name`)}).strict(),P.object({end:P.literal(!0).describe(`Place at the end of the placement zone`)}).strict()]),viewFocus=e=>({objectName:e.objectName,viewName:e.viewName}),contentFocus=e=>({...viewFocus(e),contentName:e.contentName});function invalid(e,t){throw new E(t,[{path:e,message:t}])}function change(e,t,n,r){let i=e.views.findIndex(e=>e.object===t.objectName&&e.name===t.viewName);i<0&&invalid([`viewName`],`View is not in the draftable state`),e.views[i].authoring||invalid([`authoring`],`Missing view authoring baseline`);let{derived:a,...o}=r(structuredClone(e.views[i]));o.contents=resolveViewContents(o.authoring);let s=e.views.map((e,t)=>t===i?o:e);return validateContentViewCatalogue({extensions:[...n.extensions],objects:e.objects.map(t=>draftedObjectDefinition(t,e.attributes.filter(e=>e.objectId===t.id))),views:s.map(draftedViewDefinition)}),{...e,views:s}}function contentState(e,t){let n=Object.hasOwn(e.authoring.contents,t)?e.authoring.contents[t]:void 0;return n||invalid([`contentName`],`Content is not in the draftable state`),n}function setOrder(e,t,n){for(let r of n)e.authoring[r===`main`?`mainOrderCustomized`:`asideOrderCustomized`]=!0,t.filter(e=>e.placement===r).forEach((t,n)=>{contentState(e,t.name).workspacePosition=n})}function find(e,t){let n=e.contents.find(e=>e.name===t);return n||invalid([`contentName`],`Content is not in the draftable state`),n}function placed(e,t,n){let r=e.filter(e=>e.name!==t.name),i=r.filter(e=>e.placement===t.placement),a=i.length;if(!(`end`in n)){let e=`before`in n?n.before:n.after;a=i.findIndex(t=>t.name===e),a<0&&invalid([`target`],`Order target is not in this placement`),`after`in n&&a++}return i.splice(a,0,t),t.placement===`main`?[...i,...r.filter(e=>e.placement===`aside`)]:[...r.filter(e=>e.placement===`main`),...i]}const no=P.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 P.NEVER}let r=typeof e==`object`&&e&&`name`in e?e.name:void 0;return{...n.data,name:r}}),ro=P.object({...q,type:P.literal(`replace_view_content`),definition:no}).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}}),io=S.describe(`The whole content definition.`),ao=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:ro,wire:P.object({...q,type:P.literal(`replace_view_content`),definition:io}).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}}))}),oo=P.object({...K,type:P.literal(`add_view_content`),content:io,target:to.describe(`Where to place the new content within its placement zone`)}).strict(),addFocus=e=>({...viewFocus(e),contentName:e.content.name}),so=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:oo,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}}})}),co=P.object({...q,type:P.literal(`remove_view_content`)}).strict(),lo=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:co,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}})}),uo=P.object({...q,type:P.literal(`move_view_content`),placement:P.enum([`main`,`aside`]).describe(`The placement zone to move the content into`),target:to.describe(`Where to place the content within that placement zone`)}).strict(),fo=defineOperation({type:`move_view_content`,summary:`Reorders or moves a content to a different placement; the aside rule applies.`,schema:uo,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)}}})}),po=P.object({...K,type:P.literal(`update_view_metadata`),changes:P.object({label:P.string().min(1).optional().describe(`New label for the view`),description:P.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(),mo=defineOperation({type:`update_view_metadata`,summary:`Updates a view's label, description, or icon (null clears the icon).`,schema:po,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}})}),ho=P.string().refine(e=>e.trim().length>0,`API name must not be blank`),go=P.object({...K,type:P.literal(`rename_view`),newName:ho.describe(`New API name for the view`)}).strict(),renameViewFocus=e=>({objectName:e.objectName,viewName:e.newName}),_o=defineOperation({type:`rename_view`,summary:`Renames a view; refused on a code-declared name — change it in the declaration.`,schema:go,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}))}),vo=P.object({...q,type:P.literal(`rename_view_content`),newName:ho.describe(`New API name for the content`)}).strict(),renameContentFocus=e=>({...viewFocus(e),contentName:e.newName}),yo=defineOperation({type:`rename_view_content`,summary:`Renames a content; refused on a code-declared name — change it in the declaration.`,schema:vo,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}}})}),bo=P.object({...q,type:P.literal(`reset_view_content`)}).strict(),xo=defineOperation({type:`reset_view_content`,summary:`Resets a content back to its code-declared source; only works when one exists.`,schema:bo,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}})})}),So=P.object({...K,type:P.literal(`reset_view_order`),placement:P.enum([`main`,`aside`]).describe(`The placement zone to reset to source order`)}).strict(),Co=defineOperation({type:`reset_view_order`,summary:`Resets a placement zone's order to its code-declared source, if one exists.`,schema:So,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}})}),wo=P.discriminatedUnion(`type`,[ro,oo,co,uo,po,go,vo,bo,So]),J=[ao,so,lo,fo,mo,_o,yo,xo,Co];function findObject(e,t){return e.objects.find(e=>e.id===t)}const To=new Set([`formula`,`rollup`]);function isComputedAttribute(e){return To.has(e.attributeType)}const Eo={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 Eo?Eo[e]:void 0}function requireObject$1(e,t){let n=findObject(e,t);if(!n)throw new E(`Object "${t}" is not in the draftable state`,[]);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$1(e,t),e.attributes),relatedObjects:Object.fromEntries(e.objects.map(t=>[t.name,toCompileObject(t,e.attributes)]))}}function toRollupAttribute(e){return{id:e.id,name:e.name,label:e.label,type:`rollup`,...configOf(e)}}function asValidationError(e){try{return e()}catch(e){throw e instanceof ComputedFormulaCompileError?new 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$1(e,t),i=[];for(let r of compilablePlansOf(e,t))r.attributeName!==n&&r.dependencies.some(e=>dependencyNames(e,n))&&i.push(r.attributeName);for(let a of e.objects)if(a.id!==t)for(let t of compilablePlansOf(e,a.id))t.dependencies.some(t=>{if(t.kind!==`relation`||t.targetAttributeName!==n)return!1;let i=e.attributes.find(e=>e.objectId===a.id&&e.name===t.relationName&&e.attributeType===`relation`);return i!==void 0&&relationTargetObjectName(i)===r.name})&&i.push(`${a.name}.${t.attributeName}`);return i}function bilateralDeclarationOf(e){let t=e.config?.bilateral;if(typeof t!=`object`||!t)return;let{object:n,attribute:r}=t;return typeof n==`string`&&typeof r==`string`?{object:n,attribute:r}:void 0}function sameAttribute(e,t){return t!==void 0&&e.attributeType===t.attributeType&&sameConfig(e,t)}function sameConfig(e,t){return JSON.stringify(e.config??{})===JSON.stringify(t.config??{})}function assertBilateralPairs(e,t){let untouched=t=>sameAttribute(t,e.attributes.find(e=>e.id===t.id));for(let e of t.attributes){if(e.attributeType!==`relation`)continue;let 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 requireObject(e,t){let n=e.objects.find(e=>e.id===t);if(!n)throw new E(`Object "${t}" is not in the draftable state`,[]);return n}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 Y={...eo,objectId:P.string().uuid().describe(`The object this operation acts on`)},Do=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:P.object({...Y,objectId:P.string().uuid().describe(`Stable id for the new object; the server mints one when omitted`),type:P.literal(`add_object`),name:qt.describe("kebab-case plural API name (`purchase-orders`)"),label:P.string().min(1).describe(`Label people see`),icon:P.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} »`}),Oo=P.object({...Y,type:P.literal(`update_object`),changes:P.object({label:P.string().min(1).optional().describe(`New label`),icon:P.string().min(1).optional().describe(`New icon name from search_icons`),pluralLabel:P.string().optional().describe(`New label for many records; "" clears it`),description:P.string().optional().describe(`What this object holds`),labelExpression:I.optional().describe(`Titles every record; syntax in <expressions>`),embeddingExpression:P.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}),ko=defineOperation({type:`update_object`,summary:`Updates an object's settings: label, icon, pluralLabel, description, labelExpression, embeddingExpression.`,schema:Oo,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)}),Ao={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])=>Ao[e]?.(String(t))).filter(e=>e!==void 0);return t.length>0?t.join(` · `):`Modifie l'objet`}const jo=defineOperation({type:`remove_object`,summary:`Removes an object; refused while a relation attribute targets it — remove it first.`,schema:P.object({...Y,type:P.literal(`remove_object`)}),apply:(e,t)=>{requireObject(e,t.objectId);let n=e.objects.find(e=>e.id===t.objectId)?.name;for(let r of e.attributes){if(r.objectId===t.objectId||r.attributeType!==`relation`||!relationTargets(r).some(e=>e.object===n))continue;let i=e.objects.find(e=>e.id===r.objectId);throw new E(`object "${n}" is targeted by attribute "${i?.name}.${r.name}"; remove that attribute first`,[])}return{...e,objects:e.objects.filter(e=>e.id!==t.objectId),attributes:e.attributes.filter(e=>e.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(e=>e.objectId!==t.objectId),views:e.views.filter(e=>e.object!==n)}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Supprime l'objet ${e.objectId}`}),Mo=Vn;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 No=P.object({...Y,type:P.literal(`add_attribute`),attributeId:P.string().min(1),name:Dt,label:P.string().min(1),attributeType:P.enum(Mo),config:P.record(P.string(),P.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}}),Po={...eo,type:P.literal(`add_attribute`),attributeId:P.string().min(1).describe(`Stable attribute id`),name:Dt.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),label:P.string().min(1).describe(`Label people see`)},Fo=Object.fromEntries(Rt.map(e=>[e,!0])),Io=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],Lo=P.object(Io.reduce((e,t)=>(Object.assign(e,Et(t).omit(Fo).shape),e),{})).strict(),Ro=Mo.filter(e=>!Io.includes(e)),zo=Object.fromEntries(Io.map(e=>[e,new Set(Object.keys(Et(e).omit(Fo).shape))])),Bo=Lt(zo,`config key`);function refuseForeignSimpleConfigKeys(e,t){Bo(e.attributeType,e.config,t,[`config`])}function wireConfigFor(e){let t=Et(e).omit(Fo);return(e===`relation`||e===`document`?t.extend({properties:Bt.optional()}):t).strict()}const Vo=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:No,wire:P.discriminatedUnion(`attributeType`,[P.object({...Po,objectId:P.string().uuid(),attributeType:P.enum(Io).describe(`Attribute type`),config:Lo.optional().describe(`Configuration of a simple attribute (text, number, date…)`)}).strict().superRefine(refuseForeignSimpleConfigKeys),...Ro.map(e=>P.object({...Po,objectId:P.string().uuid(),attributeType:P.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} »`}),Ho={...Y,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 E(`Attribute "${n}" is not on object "${t}"`,[]);return{object:i,attribute:a}}const Uo=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:P.object({...Ho,type:P.literal(`update_attribute`),changes:P.object({label:P.string().min(1).optional().describe(`New label`),config:P.record(P.string(),P.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} »`}),Wo=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:P.object({...Ho,type:P.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{mn(i)}catch{return}let a=gn(i,r);if(a.success)return;let o=a.errors??[],s=o.map(e=>e.path.length>1?`${e.path.join(`.`)}: ${e.message}`:e.message).join(`, `);throw new E(`Sample record "${e}" has an invalid value for "${t}": ${s}`,o.map(e=>({path:e.path,message:e.message})))}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}"`,[])}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 E(`sample record "${t}" references unknown sample "${n}"`,[])}}const Go=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:P.object({...Y,type:P.literal(`add_sample_record`),recordId:P.string().uuid().describe(`Minted by the server when omitted`),values:P.record(P.string(),P.unknown()).describe("Attribute name → value; currency is `{code,value}`, relation is a record id or name minted here"),publication:P.enum([`preview`,`requested-data`]).optional().describe(`preview = display-only; requested-data = real records asked for`)}),apply:(e,t)=>{if(requireObject(e,t.objectId),e.sampleRecords.some(e=>e.id===t.recordId))throw new E(`Sample record "${t.recordId}" already exists`,[]);let n=new Map(e.attributes.filter(e=>e.objectId===t.objectId).map(e=>[e.name,e]));for(let[r,i]of Object.entries(t.values)){let a=n.get(r);if(!a)throw new E(`Sample record "${t.recordId}" uses unknown attribute "${r}"`,[]);if(isComputedAttribute(a))throw new E(`attribute "${a.name}" is computed and cannot be set on a sample record`,[]);assertUnknownSampleReference(e,t.recordId,a,i),assertSampleValue(t.recordId,r,a,i)}for(let e of n.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=[Do,ko,jo,Vo,Uo,Wo,Go,defineOperation({type:`remove_sample_record`,summary:`Removes a sample record; refused while another sample still references it.`,schema:P.object({...Y,type:P.literal(`remove_sample_record`),recordId:P.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 E(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,[]);return assertSampleNotReferenced(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(e=>e.id!==t.recordId)}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Retire un exemple`})];function build(){let e=new Map;for(let t of[...X,...J]){if(e.has(t.type))throw new C(`architect operation`,t.type);e.set(t.type,t)}return e}const Z=build(),Ko=[...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=>P.tuple([P.literal(e),P.string()]),qo=P.union([P.tuple([P.literal(`content`),P.string(),P.string(),P.string()]),P.tuple([P.literal(`view`),P.string(),P.string()]),P.tuple([P.literal(`attribute`),P.string(),P.string()]),P.tuple([P.literal(`sample`),P.string(),P.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=wo.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 Jo=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=qo.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 Q=P.string().min(1),Yo=P.union([P.object({objectName:Q,viewName:Q,contentName:Q.optional()}).strict().describe(`Full configuration of a view, or of one content when contentName is given`),P.object({objectId:Q}).strict().describe(`An object with its attributes, by id`),P.object({objectName:Q}).strict().describe(`An object with its attributes`),P.object({objectId:Q,attributeName:Q}).strict().describe(`One attribute's config, by name`),P.object({objectId:Q,attributeId:Q}).strict().describe(`One attribute's config, by id`),P.object({objectId:Q,recordId:Q}).strict().describe(`One sample record`)]);function parseNamedTarget(e){let t=Yo.safeParse(e);if(!t.success)throw new E(`Invalid scoped target`,[{path:[`target`],message:`Expected exactly one named target branch`}]);return t.data}const Xo=P.object({type:P.literal(`remove_operation`),operationId:P.string().min(1).describe(`The id of a stored operation to drop from the draft`)}),Zo=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 P.discriminatedUnion(`type`,e)}function isUuidString(e){return e instanceof P.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):P.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=P.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 Qo={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of Qo[e.shape.type.value]??[]){let r=e.shape[n];r instanceof P.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,P.object({...n,objectName:P.string().min(1).describe(`Object`)}).strict())})}const $o=membersOf(X,[Xo]),es=membersOf(J),ts=unionOf($o),ns=unionOf(es),rs={schema:ts,view:ns},is={schema:unionOf(wireMembersOf(X,[Xo])),view:unionOf(wireMembersOf(J))},as=new Map([...X.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...J.map(e=>[e.type,`view`])]);function familyOf(e){return as.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 os=[`draft_schema`],ss=`publish_architect_draft`,cs=`discard_architect_draft`,ls=`request_design_review`,us=`get_architect_draft`,ds=[{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:{}}}}],$=P.string().refine(e=>e.trim().length>0,`Must not be blank`),fs=P.union([P.tuple([P.literal(`object`),$]),P.tuple([P.literal(`attribute`),$,$]),P.tuple([P.literal(`view`),$,$]),P.tuple([P.literal(`content`),$,$,$])]),ps=P.object({label:$,pluralLabel:P.string().optional(),description:P.string().optional(),icon:D.optional(),labelExpression:P.string(),embeddingExpression:P.string().optional(),sealed:P.boolean().optional(),toleratedAttributes:P.array($).optional(),metadata:P.record(P.string(),P.unknown()).optional(),schema_version:P.number().int().nonnegative(),migrations:P.array(P.record(P.string(),P.unknown())),documentLayout:P.record(P.string(),P.unknown()).optional()}).strict();function failure(e){throw new E(e,[])}function definitionSchema(e){return P.custom(t=>{let n=P.record(P.string(),P.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`:ps.parse(n);break;case`attribute`:{let e=P.enum(Vn).parse(n.type);Nt(e).extend({type:P.literal(e),label:$,required:P.boolean().optional(),unique:P.boolean().optional(),icon:D.optional()}).strict().parse(n);break}case`view`:{let{contents:t,...r}=n,i=P.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=P.record(P.string(),P.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=P.object({modelVersion:P.literal(1),hashVersion:P.literal(1),tenant:$,sourceFingerprint:P.string().regex(/^[a-f0-9]{64}$/),entries:P.array(P.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=fs.parse(P.object({address:P.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`?P.object({id:P.string().uuid(),updatedAt:P.string().datetime()}).strict():P.object({id:P.string().uuid(),revision:P.number().int().nonnegative()}).strict(),o=P.object({address:fs,source:i,effective:i,status:P.enum([`source`,`runtime`,`copy`,`suppressed`]),sourceOwner:P.union([P.literal(`core`),P.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 P.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`: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{Jo as ABSENT_TARGET_TOKEN,zi as AGENT_UI_BATCH_MAX_BYTES,Bi as AGENT_UI_BATCH_MAX_ITEMS,Lr as ALLOWED_PROPERTY_TYPES,F as ALL_ACTIONS,Ko as ALL_OPERATION_TYPES,Hr as ALL_PIPES,Yr as ALL_SYSTEM_RESOURCES,br as ARTIFACT_FILE_ROLES,vr as ARTIFACT_KINDS,Ei as ARTIFACT_LIST_VIEW,wi as ARTIFACT_OBJECT,V as ARTIFACT_OBJECT_NAME,Ci as ARTIFACT_PREVIEW_EXTENSION,yr as ARTIFACT_RETENTIONS,Ti as ARTIFACT_VIEW,je as ATTRIBUTE_FILTER_OPERATORS,Vn as ATTRIBUTE_TYPES,Wn as AUDIT_ACTIONS,Un as AUDIT_RESOURCE_TYPES,Me as AccessDeniedError,AgentBuilder,Ne as AttributeInUseError,Pe as AttributeNotFoundError,zn as BEHAVIOR_PROPERTIES,Fr as BYTE_UNIT_LABELS,Kn as CLAIMABLE_SESSION_STATUSES,na as COMPUTED_FUNCTIONS,ra as COMPUTED_FUNCTION_METADATA,ta as COMPUTED_FUNCTION_NAMES,sa as CONNECTOR_CALLBACK_PARAM,Mr as COUNT_MODES,Fe as ChangeTypeNotSupportedError,ComputedFormulaCompileError,Gt as ComputedFormulaParseError,Ie as ConcurrentModificationError,R as ContentBuilder,Jr as DB_COLUMN_FIELDS,ii as DEFAULT_AGENT_EXECUTION_CONFIG,qn as DEFAULT_APPROVAL_POLICY,_r as DEFAULT_DICTATION_LIMITS,Ur as DEFAULT_LABEL_FALLBACK,Cr as DEFAULT_MEETING_BOT_DISPLAY_NAME,Zr as DEFAULT_ROLES,$r as DEFAULT_ROLE_DESCRIPTIONS,Qr as DEFAULT_ROLE_LABELS,ri as DEFAULT_ROLE_PERMISSIONS,wr as DEFAULT_TENANT_SETTINGS,Zt as DEFAULT_VALIDATION_MESSAGES,hr as DICTATION_FINALIZATION_TIMEOUT_MS,lr as DICTATION_FRAME_BYTES,dr as DICTATION_MAX_BUFFER_BYTES,ur as DICTATION_MAX_FRAME_BYTES,fr as DICTATION_MAX_TRANSCRIPT_BYTES,gr as DICTATION_MODEL_ID,mr as DICTATION_PREPARATION_TIMEOUT_MS,cr as DICTATION_SAMPLE_RATE,pr as DICTATION_TICKET_TTL_MS,cs as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,Ir as DOCUMENT_SYSTEM_ATTRIBUTES,Mo as DRAFTABLE_ATTRIBUTE_TYPES,Zo as DRAFT_BATCH_LIMIT,$a as DRAFT_OBJECT_SETTINGS,ds as DRAFT_SCHEMA_INPUT_EXAMPLES,os as DRAFT_WRITE_TOOL_NAMES,Si as DRIVE_LIST_VIEW,bi as DRIVE_OBJECT,B as DRIVE_OBJECT_NAME,xi as DRIVE_VIEW,Le as DestructiveSyncNotAllowedError,C as DuplicateError,zr as EMPTY_VALUE_PLACEHOLDER,Nr as ESTIMATED_COUNT_CAP,ha as FAKE_MEETING_BOT_SIGNATURE_HEADER,rs as FAMILY_INPUTS,is as FAMILY_WIRE_INPUTS,Sr as FORM_FORBIDDEN_ATTRIBUTE_TYPES,FlagRegistry,FlagService,Re as ForbiddenError,FormBuilder,FormRegistry,FormRowBuilder,FormStepBuilder,us as GET_ARCHITECT_DRAFT_TOOL_NAME,si as GroupBuilder,Rn as IDENTITY_PROPERTIES,jr as IMAGE_FORMATS,Zn as INFERENCE_REASONING_OPTIONS,Xn as INFERENCE_SPEEDS,vt as LIST_VIEW_TAB_VISIBILITIES,Vi as LIVE_EVENT_TYPES,n as LOCATION_FILTER_PROPERTIES,la as MAILBOX_LIST_MODES,da as MAIL_DRAFT_BODY_MAX_CHARS,fa as MAIL_SUBJECT_MAX_CHARS,xr as MAX_PRESET_DEPTH,nr as MAX_TODOS,ir as MAX_TODO_DESCRIPTION_CHARS,rr as MAX_TODO_ID_CHARS,U as MEETING_ATTRIBUTES,ki as MEETING_DETAIL_VIEW_ID,Ni as MEETING_LIST_VIEW,Di as MEETING_LIST_VIEW_ID,ji as MEETING_OBJECT,H as MEETING_OBJECT_NAME,Mi as MEETING_VIEW,Oi as MEETING_WRITE_SOURCE,yi as MEMORY_LIST_VIEW,gi as MEMORY_OBJECT,vi as MEMORY_VIEW,ca as McpOAuthCompletionMode,ze as MemoryNotFoundError,Be as MigrationTimeoutError,MultiRelationAttributeBuilder,or as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,sr as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,St 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,ga as NO_RECORDING,g as NO_VALUE_OPERATORS,cn as NonJsonValueError,NoopGeocodingAdapter,Ve as NotFoundError,He as NotImplementedError,qt as OBJECT_NAME_SCHEMA,$n as OPEN_TOOL_PART_STATES,Z as OPERATION_REGISTRY,o as OPERATORS_BY_TYPE,ia as OPERATOR_SPECS,ObjectBuilder,Ue as ObjectNotFoundError,We as ObjectReferencedError,Ge as OrphanSystemAttributeError,Vr as PIPES_WITH_ARGS,Bn as PRESENTATION_PROPERTIES,Yn as PROVIDER_NAMES,ss as PUBLISH_ARCHITECT_DRAFT_TOOL_NAME,Ke as ProtectedResourceError,qe as ProtectedRoleError,Rr as QUALIFIED_SEPARATOR,Pr as QUOTA_KEYS,pa as RECORDING_OVERRIDES,ma as RECORDING_POLICIES,qr as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,Hn as RELATION_TARGET_ANY,de as REMOVED_OPERATOR_REPLACEMENTS,Xo as REMOVE_OPERATION_SCHEMA,ua as REPLY_MODES,ls 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,ts as SCHEMA_OPERATION_INPUT,W as SCHEMA_PLAN_LIMITS,va as SCHEMA_SOURCE_ID_PATTERN,ar as SESSION_STATE_STREAM_ID,Gn as SESSION_TERMINAL_STATUSES,Br as SIMPLE_PIPES,Ut as SIMPLE_PROPERTY_TYPES,fi as SKILL_CONTENT_TEMPLATE,hi as SKILL_LIST_VIEW,pi as SKILL_OBJECT,mi as SKILL_VIEW,ai 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,er as SYSTEM_PART_CODES,L as SYSTEM_RESOURCES,Xr 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,Tr as TENANT_INVITATION_DEFAULT_TTL_MS,Dr as TENANT_INVITATION_MAX_TTL_MS,Er as TENANT_INVITATION_MIN_TTL_MS,Or as TENANT_INVITATION_RESEND_INTERVAL_MS,Jt as TEXT_FORMAT_PATTERNS,oa as TODAY_DEFAULT,Jn as TODO_PLAN_STATUSES,tr as TODO_STATUSES,Qn as TOOL_APPROVAL_STATES,kr as USER_STATUSES,Ar as USER_WORK_POSTURES,J as VIEW_OPERATIONS,ns as VIEW_OPERATION_INPUT,E as ValidationError,oi as ViewBuilder,Rt as WIRE_OMITTED_CONFIG_KEYS,accessLevelToActions,actionsToAccessLevel,agent,agentDataChunk,agentDisplayName,Ra as agentInferencePreferencesSchema,Ga as agentMessageAttachmentSchema,Wa as agentMessagePartSchema,Ba as agentSessionInferenceOverridesInputSchema,Va as agentSessionInferenceOverridesSchema,Ya as agentSessionMessageSchema,agentUIValidationError,applyOperations,applyPipes,applyRelationProps,architectContentBodyKey,architectDraftChannelKey,architectFocusCandidates,architectFocusKey,un as asTenantId,sn as asUserId,assertAcyclicComputed,assertAcyclicComputedDependencies,assertBilateralPairs,assertCustomAgentUIMessageChunk,assertSchemaSourceId,Vt as attributeConfigSchemas,bilateralDeclarationOf,booleanFlag,buildAgentFallbackTitle,buildPermissionFlags,buildPropertySchema,buildQualifiedAttribute,j as canonicalStringify,wo as canonicalViewOperationSchema,r as canonicalizeFilterValue,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,z as content,contentDefinition,Li as contentExtensionRegistry,me as contentViewDefinitionSchema,oe 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,Qa as customDataChunkSchemas,date,dateInTimezone,dateValueStart,ln as deepEqual,defaultViewIdsFor,defaultViewsFor,defineOperation,definePresentation,dependentsOf,deriveArchitectChanges,deriveCreateDefaultsFromFilters,deriveInitials,describeOperations,Ea as destructiveSchema,detailView,diffSchemaState,be as displayAttributesSchema,document,we as draftContentViewDefinitionSchema,ce as draftContentViewDefinitionSchemaFor,draftObjectSettings,draftedLabelExpression,draftedObjectDefinition,draftedViewDefinition,Ja as durableDateSchema,episodeImpactOf,evaluateComputedAst,evaluateComputedFormula,evaluateComputedFormulaWithResult,evaluateFilterState,evaluateRecordFilterState,extractAttributeNames,h as extractCurrencyFilterValue,ge as extractFilterValue,extractValueRefs,familyOf,l as filterOperatorsByTypeForGeneration,_e as filterStateSchema,findRelationAttribute,ci as flagRegistry,focusOf,form,formFieldFlatKey,formFieldKey,Ri as formRegistry,formatAgentStreamFrameId,formatAttributeValue,formatByteSize,formatComputedResult,formatLocationValue,Qt as formatZodErrors,formula,fromDraftableView,an 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,za as imageModelIdSchema,includesAction,nn as indexBy,inferInverseCardinality,inferRollupReturnType,Ia as inferenceReasoningSchema,Fa as inferenceSpeedSchema,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,A as isNativeObjectName,ee as isNoValueOperator,isNotEmpty,st as isNotFoundError,M 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,_n as isValuePresent,jsonFlag,legacyStatusToSessionState,listView,liveChannelKey,location,matchesAccepts,Ka as mentionReferenceSchema,qa as modelDefinitionSchema,La as modelReferenceSchema,multiselect,zt as multiselectOptionWriteSchema,Yo as namedTargetSchema,nativeAgentUIPartIdMetadataKey,normalizeDateValue,ke as normalizeFilterRule,a as normalizeForEdgeRpc,v as normalizeOperator,p as now,number,numberFlag,object,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,Ma as persistedSchemaPlanSchema,phone,Ca as plannedAttributeSchema,wa as plannedInlineAttributeSchema,Ta as plannedObjectSchema,presentationOf,Wt as propertyAttributeSchema,kt as propertyAttributeWireSchema,At as propertySchemaSchema,Bt as propertySchemaWireSchema,proposalTargetKey,Pa as providerNameSchema,S as publishedViewContentDefinitionSchema,qualifiedPropertyDefs,readFormFieldValue,reconcileRelationAttributes,Lt as refuseForeignKeys,regenerateDerived,ui as registry,yn 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,Yt as resolveTextPattern,De as resolveUtcDayBounds,resolveViewContents,richtext,rollup,rollupToFormulaExpression,rn as sameStableValue,schemaGroupKey,Aa as schemaPlanSchema,schemaStateSourcePayload,select,Mt as selectOptionWriteSchema,on as serializeCanonicalJson,dn as serializeStableJson,Ha 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,Xa as todoItemSchema,Za as todoPlanSchema,Ua as toolImpactSchema,touchedObjectIds,user,pt as validateAttributeName,validateContentViewCatalogue,fn as validateDraft,vn as validateDraftOrThrow,validateLabelExpression,bn as validateObject,validateObjectExpressions,mt as validateObjectName,pn as validateObjectOrThrow,pe as validateQualifiedRule,validateStoredViews,bt as validateViewName,viewIdFor,viewIdentityKey,Pi as viewRegistry,workspaceViewAuthoring};
|