@stndrds/schema 1.0.0-alpha.350 → 1.0.0-alpha.352
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-Dk8PLu1y.d.mts → all-BmVuO_vv.d.mts} +38 -38
- package/dist/{all-CPMOHYla.d.ts → all-Bv-5hu8j.d.ts} +38 -38
- package/dist/{attributes-mMmH-WOx.d.mts → attributes-Cft68n4u.d.mts} +1 -1
- package/dist/{attributes-C2gm0hUJ.d.ts → attributes-gEcJp-WP.d.ts} +1 -1
- package/dist/capabilities.d.mts +5 -13
- package/dist/capabilities.d.ts +5 -13
- package/dist/capabilities.js +1 -1
- package/dist/capabilities.mjs +1 -1
- package/dist/{checkbox-DO6Mkloc.d.mts → checkbox-C-kdNm3A.d.mts} +2 -2
- package/dist/{checkbox-Ce8gAyQf.d.ts → checkbox-C7ctkYoQ.d.ts} +2 -2
- package/dist/config-CYuFravl.js +13 -0
- package/dist/config-CiAtjzem.mjs +13 -0
- package/dist/{date-DikDGfre.d.ts → date-CY4L11B_.d.ts} +2 -2
- package/dist/{date-CMS-GYRM.d.mts → date-mQ8gxU85.d.mts} +2 -2
- package/dist/empty-BgAwlO54.mjs +2 -0
- package/dist/empty-CRCKZcwK.js +2 -0
- package/dist/{exceptions-DxzT8POW.d.ts → exceptions-704MxF-j.d.mts} +98 -34
- package/dist/{exceptions-DxzT8POW.d.mts → exceptions-704MxF-j.d.ts} +98 -34
- package/dist/exceptions.d.mts +2 -2
- package/dist/exceptions.d.ts +2 -2
- package/dist/exceptions.js +1 -1
- package/dist/exceptions.mjs +1 -1
- package/dist/{index-D26ob_vF.d.mts → index-BV_w2VTh.d.mts} +15 -2
- package/dist/{index-BL7EA39F.d.ts → index-Bbc3qfJ3.d.ts} +1 -1
- package/dist/{index-BV4yNsr7.d.mts → index-Cga9i2js.d.mts} +1 -1
- package/dist/{index-D9OhYX-t.d.ts → index-DQ4cGca2.d.mts} +50 -11
- package/dist/{index-B-mUjnh9.d.mts → index-DmS-DtU4.d.ts} +50 -11
- package/dist/{index-CRtiKFTH.d.ts → index-UYQmTrEG.d.ts} +15 -2
- package/dist/index.d.mts +1313 -1245
- package/dist/index.d.ts +1313 -1245
- package/dist/index.js +9 -9
- package/dist/index.mjs +9 -9
- package/dist/{number-Ck0PPSkK.d.ts → number-CAAAb8Wz.d.ts} +2 -2
- package/dist/{number-r6bOZ9jd.d.mts → number-eNEdOtC3.d.mts} +2 -2
- package/dist/object-sbH7KtsH.mjs +4 -0
- package/dist/object-xwmmQZ8z.js +4 -0
- package/dist/{phone-MN6Li5Wx.js → phone-BXTenBvF.js} +1 -1
- package/dist/{phone-CsV9QNwF.mjs → phone-CRbCvH20.mjs} +1 -1
- package/dist/{text-B1Vwj7fS.d.mts → text-BKyAPMGX.d.mts} +2 -2
- package/dist/{text-DHg2cmFd.d.ts → text-CP1eHBEv.d.ts} +2 -2
- package/dist/{utils-Du-He6Ct.d.ts → utils-C6VEXia7.d.ts} +3 -3
- package/dist/{utils-r53z9KnF.d.mts → utils-CnhbUWev.d.mts} +3 -3
- package/dist/utils.d.mts +1 -1
- package/dist/utils.d.ts +1 -1
- package/dist/validation/all.d.mts +5 -5
- package/dist/validation/all.d.ts +5 -5
- package/dist/validation/all.js +1 -1
- package/dist/validation/all.mjs +1 -1
- package/dist/validation/complex/currency.d.mts +2 -2
- package/dist/validation/complex/currency.d.ts +2 -2
- package/dist/validation/complex/location.d.mts +2 -2
- package/dist/validation/complex/location.d.ts +2 -2
- package/dist/validation/complex/phone.d.mts +2 -2
- package/dist/validation/complex/phone.d.ts +2 -2
- package/dist/validation/complex/phone.js +1 -1
- package/dist/validation/complex/phone.mjs +1 -1
- package/dist/validation/complex/relation.d.mts +2 -2
- package/dist/validation/complex/relation.d.ts +2 -2
- package/dist/validation/complex/richtext.d.mts +2 -2
- package/dist/validation/complex/richtext.d.ts +2 -2
- package/dist/validation/complex/select.d.mts +2 -2
- package/dist/validation/complex/select.d.ts +2 -2
- package/dist/validation/complex/user.d.mts +2 -2
- package/dist/validation/complex/user.d.ts +2 -2
- package/dist/validation/computed/formula.d.mts +2 -2
- package/dist/validation/computed/formula.d.ts +2 -2
- package/dist/validation/computed/rollup.d.mts +2 -2
- package/dist/validation/computed/rollup.d.ts +2 -2
- package/dist/validation/config/index.d.mts +2 -2
- package/dist/validation/config/index.d.ts +2 -2
- package/dist/validation/config/index.js +1 -1
- package/dist/validation/config/index.mjs +1 -1
- package/dist/validation/core/index.d.mts +1 -1
- package/dist/validation/core/index.d.ts +1 -1
- package/dist/validation/object/index.d.mts +1 -1
- package/dist/validation/object/index.d.ts +1 -1
- package/dist/validation/object/index.js +1 -1
- package/dist/validation/object/index.mjs +1 -1
- package/dist/validation/primitives/checkbox.d.mts +1 -1
- package/dist/validation/primitives/checkbox.d.ts +1 -1
- package/dist/validation/primitives/date.d.mts +1 -1
- package/dist/validation/primitives/date.d.ts +1 -1
- package/dist/validation/primitives/number.d.mts +1 -1
- package/dist/validation/primitives/number.d.ts +1 -1
- package/dist/validation/primitives/text.d.mts +1 -1
- package/dist/validation/primitives/text.d.ts +1 -1
- package/dist/{view-config.schema-c8LvH8WE.mjs → view-config.schema-CCrM5b-O.mjs} +1 -1
- package/dist/{view-config.schema-QmnihdGp.js → view-config.schema-CgU86fLj.js} +1 -1
- package/package.json +2 -2
- package/dist/config-BiQGgy7f.mjs +0 -13
- package/dist/config-WUWITOeW.js +0 -13
- package/dist/object-BA3vKFl0.js +0 -4
- package/dist/object-C92B0Oei.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 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 S,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 Ee,v as De,w as Oe,x as ke,y as Ae,z as je}from"./view-config.schema-c8LvH8WE.mjs";import{AccessDeniedError as Me,AmbiguousSchemaChangeError as Ne,AttributeInUseError as Pe,AttributeNotFoundError as Fe,ConcurrentModificationError as Ie,DuplicateError as C,ForbiddenError as Le,MemoryNotFoundError as Re,NotFoundError as ze,NotImplementedError as Be,ObjectNotFoundError as Ve,ObjectReferencedError as He,OrphanSystemAttributeError as Ue,ProtectedResourceError as We,ProtectedRoleError as Ge,RealtimeDeliveryError as Ke,RealtimeRateLimitedError as qe,RealtimeSubscriptionError as Je,RecordNotFoundError as Ye,RecordReferencedError as Xe,RepositoryError as Ze,ReservedObjectNameError as Qe,RoleNotFoundError as $e,SchemaError as w,SchemaErrorCode as T,SchemaPlanNotFoundError as et,SearchBackendError as tt,StorageError as nt,SyncCascadeError as rt,SyncConflictError as it,SyncError as at,SystemEntityImmutableError as ot,ValidationError as E,isAttributeInUseError as st,isNotFoundError as ct,isObjectReferencedError as lt,isProtectedResourceError as ut,isRecordReferencedError as dt,isSchemaError as ft,isValidationError as pt}from"./exceptions.mjs";import{A as D,C as mt,D as O,E as ht,F as gt,I as _t,L as vt,M as yt,N as bt,O as xt,P as St,R as Ct,S as wt,T as Tt,_ as Et,a as Dt,b as Ot,c as kt,d as At,f as jt,g as Mt,h as Nt,i as Pt,j as Ft,k as It,l as Lt,m as Rt,n as zt,o as Bt,p as Vt,r as Ht,s as Ut,t as Wt,u as Gt,v as Kt,w as qt,x as Jt,y as k,z as Yt}from"./config-BiQGgy7f.mjs";import{n as Xt,r as Zt,t as Qt}from"./text-C8Lb-NFo.mjs";import{n as $t,t as en}from"./core-BLHhNykL.mjs";import{createNumberValidator as tn}from"./validation/primitives/number.mjs";import{createCheckboxValidator as nn}from"./validation/primitives/checkbox.mjs";import{createDateValidator as rn}from"./validation/primitives/date.mjs";import{a as an,c as on,i as sn,l as cn,n as ln,o as un,r as dn,s as A,t as fn,u as pn}from"./utils-fXIvFFl6.mjs";import{a as mn,c as hn,d as gn,f as _n,i as vn,m as yn,o as bn,p as j,r as xn,s as Sn,u as Cn}from"./object-C92B0Oei.mjs";import{i as wn,n as Tn,r as En}from"./phone-CsV9QNwF.mjs";import{z as M}from"zod";import{MEMORY_DESCRIPTION_MAX_LENGTH as Dn,MEMORY_NAME_MAX_LENGTH as On,SKILL_DESCRIPTION_MAX_LENGTH as kn,SKILL_NAME_MAX_LENGTH as An,getCountryDisplayNameByIso3 as N}from"@stndrds/constants";const jn=[`fyi`,`task`,`question`,`handoff`,`system`],Mn=[`low`,`normal`,`high`,`urgent`],Nn=[`public`,`internal`,`sensitive`],Pn=[`unread`,`read`,`archived`,`snoozed`],Fn=[`none`,`pending`,`processing`,`completed`,`dismissed`,`expired`,`failed`],In=`agent.session.waiting_human`,Ln=`agent.task.assigned`,Rn=`agent.question.requested`,zn=[In,Ln,Rn],Bn=[`name`,`type`],Vn=[`required`,`hidden`,`archived`,`deprecated`,`defaultValue`,`config`,`order`,`unique`],Hn=[`label`,`description`,`placeholder`,`icon`],Un=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`status`,`location`,`select`,`multiselect`,`user`,`relation`,`formula`,`rollup`,`document`],Wn=`*`;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 Gn=[`record`,`object`,`attribute`,`view`,`user`,`role`,`settings`,`file`,`agent`,`schema_source`,`tenant_invitation`],Kn=`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(`,`),qn=`agentSessionId`;function isAgentWrittenAuditEntry(e){return e.actorType===`agent`||typeof e.metadata?.agentSessionId==`string`}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 Jn=[`completed`,`failed`,`cancelled`,`timeout`,`expired`];function isTerminalSessionStatus(e){return Jn.includes(e)}const Yn=[`idle`,`completed`,`waiting_human`,`waiting_agents`,`cancelled`,`failed`,`timeout`];function isClaimableSessionStatus(e){return Yn.includes(e)}const Xn=Object.freeze({mutation:`ask`,destructive:`ask`,outward:`ask`}),Zn=[`active`,`completed`,`abandoned`],Qn=[`openai`,`anthropic`,`google`,`spacexai`,`deepseek`,`moonshotai`,`alibaba`,`mistral`,`minimax`,`meta`,`zai`],$n=[`standard`,`fast`],er=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],tr=[`conversation`,`writing`,`coding`,`analysis`,`extraction`],nr=[`light`,`standard`,`heavy`],rr=[`manual`,`auto`],ir={interactive:{inputPerMillionUsd:5,outputPerMillionUsd:25},delegated:{inputPerMillionUsd:2,outputPerMillionUsd:12}},ar=[`model`,`speed`,`reasoning`,`imageModel`,`routing`];function agentDisplayName(e){return e.label?.trim()||e.name}const or=[`approval-requested`,`approval-responded`,`approval-dispatched`],sr=[`streaming`,`running`,`pending`,...or];function isOpenToolPartState(e){return sr.includes(e)}function isToolApprovalState(e){return or.includes(e)}const cr=[`CREDITS_EXHAUSTED`];function isSystemPartCode(e){return typeof e==`string`&&cr.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 lr=`agent-notification`;function isAgentNotificationMetadata(e){return e?.kind===lr}const ur=`agent-message`;function isAgentMessageMetadata(e){return e?.kind===ur}const dr=[`pending`,`in_progress`,`completed`,`blocked`],fr=50,pr=80,mr=500,hr=`session-state`,gr=`__stndrdsNativeUiPartIds`,_r=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?.[gr];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 vr=16e3,yr=3200,br=6400,xr=16e3,Sr=65536,Cr=15e3,wr=1e4,Tr=5e3,Er=`google/gemini-3.5-transcribe-live`,Dr={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2},Or=`/v1/device-worker/channel`,kr=262144,Ar=1e4,jr=2e3,Mr=2e3,Nr=2e4,Pr=4008,Fr={initialMs:1e3,maxMs:3e4};function deviceChannelUrl(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${Or}`}function computeRetryDelay(e,t,n){return Math.min(n.initialMs*2**e,n.maxMs)+Math.floor(t()*250)}function computeReconnectDelay(e,t=Math.random){return computeRetryDelay(e,t,Fr)}const Ir=[`worker_disconnected`,`cancelled`,`timed_out`,`execution_failed`,`stale_reference`,`tab_unavailable`,`debugger_unavailable`,`blocked_by_user`];var DeviceChannelProtocolError=class extends w{constructor(e){super(e,T.DEVICE_CHANNEL_PROTOCOL),this._tag=`DeviceChannelProtocolError`,this.name=`DeviceChannelProtocolError`}};const P={id:M.uuid(),leaseToken:M.string().min(1)},Lr=M.record(M.string(),M.unknown());function defineDeviceChannelFrames(e){return{worker:M.discriminatedUnion(`type`,[M.strictObject({type:M.literal(`authenticate`),credential:M.string().regex(/^(Device|Bearer) \S+$/)}),M.strictObject({type:M.literal(`running`),...P}),M.strictObject({type:M.literal(`heartbeat`),...P}),M.strictObject({type:M.literal(`output`),...P,stdout:M.string().optional(),stderr:M.string().optional()}),M.strictObject({type:M.literal(`complete`),...P,result:M.strictObject({stdout:M.string().optional(),stderr:M.string().optional(),exitCode:M.number().int(),success:M.boolean(),errorCode:M.enum(Ir).optional(),result:e.result.optional()})}),M.strictObject({type:M.literal(`pong`)})]),server:M.discriminatedUnion(`type`,[M.strictObject({type:M.literal(`ready`),device:M.strictObject({id:M.string(),name:M.string(),capability:M.enum([`shell`,`browser`])})}),M.strictObject({type:M.literal(`command`),...P,kind:M.enum([`shell`,`browser`]),intent:M.string(),timeoutMs:M.number().int(),command:M.string().optional(),cwd:M.string().nullable().optional(),action:e.action.optional()}),M.strictObject({type:M.literal(`cancel`),id:M.uuid(),reason:M.enum([`cancelled`,`timed_out`,`revoked`])}),M.strictObject({type:M.literal(`reauthenticate`)}),M.strictObject({type:M.literal(`revoked`)}),M.strictObject({type:M.literal(`ping`)})])}}const Rr=defineDeviceChannelFrames({action:Lr,result:Lr}),zr=Rr.worker,Br=Rr.server;function parseDeviceChannelFrame(e,t){let n;try{n=JSON.parse(t)}catch{throw new DeviceChannelProtocolError(`Frame is not JSON`)}let r=e.safeParse(n);if(!r.success)throw new DeviceChannelProtocolError(`Frame does not match the channel protocol`);return r.data}function parseWorkerFrame(e){return parseDeviceChannelFrame(zr,e)}function parseServerFrame(e){return parseDeviceChannelFrame(Br,e)}const Vr=[`web`,`presentation`,`document`,`spreadsheet`,`image`,`code`,`other`],Hr=[`ephemeral`,`conversation`,`persistent`],Ur=[`source`,`preview`,`entrypoint`,`asset`],Wr=5,Gr=50;function recentActivityEntryKey(e){return e.kind===`record`?JSON.stringify([`record`,e.objectName,e.recordId]):JSON.stringify([`conversation`,`sessionId`in e?e.sessionId:e.session.id])}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 Kr=[`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 qr=[`read`,`create`,`update`,`delete`,`manage`];function actionsToAccessLevel(e){return e.length===0?`none`:e.length===1&&e[0]===`read`?`read-only`:e.length===qr.length&&qr.every(t=>e.includes(t))?`full`:`custom`}function accessLevelToActions(e){switch(e){case`full`:return[...qr];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 Jr=`Notetaker`,Yr={meetingRecordingPolicy:`none`,meetingBotDisplayName:Jr},Xr=6048e5,Zr=36e5,Qr=2592e6,$r=6e4,ei=[`active`,`suspended`],ti=[`architect`,`manual`,`auto`];function schemaGroupKey(e){return`${e.kind}:${e.id}`}function refuse$1(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$1(`label`,`Label must be a string`);else{let t=e.trim();t.length===0&&refuse$1(`label`,`Label must not be empty`),t.length>Ft.labelLength&&refuse$1(`label`,`Label is too long (max ${Ft.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$1(`icon`,`Invalid icon name`),n.icon=t.data}}return n}const ni=[`square`,`landscape`,`portrait`];function imageModelFormatDefect(e){if(e.formats.length===0)return`declares no output format`;for(let t of e.formats)if(e.requests[t]===void 0)return`declares the format "${t}" without a request`;for(let t of Object.keys(e.requests))if(!e.formats.includes(t))return`carries a request for the undeclared format "${t}"`}function declaredImageRequests(e){let t={};for(let n of e.formats){let r=e.requests[n];r!==void 0&&(t[n]=r)}return t}const ri=[`none`,`estimated`,`exact`];function parseCountMode(e){if(typeof e==`string`&&ri.includes(e))return e;throw new E(`countMode must be one of: ${ri.join(`, `)} (received: ${String(e)})`,[])}function parseOptionalCountMode(e){return e===void 0?void 0:parseCountMode(e)}const ii=1e4,ai=[`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 oi=[`B`,`KB`,`MB`,`GB`,`TB`];function formatByteSize(e){let{value:t,unitIndex:n}=computeByteMagnitude(e);return`${t} ${oi[n]}`}const si={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 ci=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(!ci.includes(e.type))throw Error(`Property type "${e.type}" is not supported in .qualifyWith()`);t.push(e)}return{definitions:t}}const li=`__`;function parseQualifiedAttribute(e){let t=e.indexOf(`__`);return t<=0||t+2>=e.length?{kind:`scalar`,attribute:e}:{kind:`qualified`,root:e.slice(0,t),property:e.slice(t+2)}}function buildQualifiedAttribute(e,t){return`${e}__${t}`}function isDateRangeValue(e){return typeof e==`object`&&!!e&&typeof e.start==`string`}function normalizeDateValue(e,t){return j(e)?null:isDateRangeValue(e)?t.endDate?{start:e.start,end:e.end??null}:e.start:typeof e==`string`?t.endDate?{start:e,end:null}:e:null}function dateValueStart(e){return typeof e==`string`&&e!==``?e:isDateRangeValue(e)&&e.start!==``?e.start:null}const ui=/\\([!-/:-@[-`{-~])/g,di=57344;function markdownToPlainText(e){if(e.length===0)return``;let t=[];return e.replace(ui,(e,n)=>(t.push(n),String.fromCharCode(di+t.length-1))).replace(/^[ \t]*```[^\n]*$/gm,``).replace(/<[^>\n]+>/g,` `).replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`).replace(/^[ \t]*\|?[ \t]*:?-{2,}:?[ \t]*(\|[ \t]*:?-{2,}:?[ \t]*)*\|?[ \t]*$/gm,``).replace(/\|/g,` `).replace(/^[ \t]*(#{1,6}[ \t]+|>[ \t]?|[-*+][ \t]+|\d+[.)][ \t]+)/gm,``).replace(/\[[ xX]\][ \t]+/g,``).replace(/(\*\*|__|\*|_|~~|`)/g,``).replace(/^[ \t]*([-*_][ \t]*){3,}$/gm,``).replace(/\s+/g,` `).trim().replace(/[\ue000-\uf8ff]/g,e=>t[e.charCodeAt(0)-di]??e)}const fi=`—`;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?Tn(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(j(e))return`—`;switch(t.type){case`text`:return formatText(e);case`richtext`:return typeof e==`string`?markdownToPlainText(e):String(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 pi=[`UPPER`,`LOWER`,`capitalize`,`trim`],mi=[`prefix`,`suffix`,`wrap`,`default`],hi=[...pi,...mi],F=M.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(!hi.includes(e))return!1}return!0},{message:`Invalid pipe name. Valid pipes: ${hi.join(`, `)}`});function validateLabelExpression(e){let t=F.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 gi=`(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=gi){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 _i=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function getSingleAttributeFromExpression(e){let t=e.trim().match(_i);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 vi=/\{\{\s*props\./;function applyRelationProps(e,t,n){if(!vi.test(e))return e;let r={},i=new Map(n?.map(e=>[e.name,e]));if(t)for(let[e,n]of Object.entries(t)){if(n==null)continue;let t=i.get(e);if(t){let i=formatAttributeValue(n,t);r[e]=i===`—`?``:i}else r[e]=n}return renderLabelExpression(e,{props:r},``).replace(/\(\s*\)/g,``).replace(/\[\s*\]/g,``).replace(/\s*[-—|:]\s*$/g,``).replace(/\s{2,}/g,` `).trim()}function relationPropertyDefs(e){if(e?.type===`relation`)return e.properties?.definitions}function qualifiedPropertyDefs(e){if(e?.type===`relation`||e?.type===`document`)return e.properties?.definitions}function extractValueRefs(e){if(j(e))return[];if(typeof e==`string`)return[{id:e}];if(Array.isArray(e))return e.flatMap(e=>extractValueRefs(e));if(typeof e==`object`&&`id`in e){let t=e;if(typeof t.id==`string`)return[{id:t.id,props:t.props}]}return[]}function getUserDisplayName(e){let t=[e.firstName,e.lastName].map(e=>e?.trim()).filter(Boolean).join(` `);return t===``?e.email?.split(`@`)[0]??``:t}const yi=/\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(yi)?.[0];return t===void 0?``:[...t.toUpperCase()][0]??``}).filter(Boolean).slice(0,2).join(``);return i===``?t:i}const bi=`__creatorRootActorId`;function getRecordCreatorPrincipalId(e){let t=e.metadata?.[bi];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 xi=new Set([`id`,`name`,`label`,`type`,`required`,`system`,`unique`,`order`]),I={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`},Si=[I.PEOPLE,I.WORKSPACE,I.ARCHITECT,I.FEATURE_FLAGS,I.FILES,I.VIEWS,I.FORMS,I.DOCUMENTS,I.AUDIT,I.API_KEYS,I.CONNECTORS,I.ENV_VARS,I.SESSION],Ci={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`},wi={OWNER:`owner`,MEMBER:`member`,AGENT_DEFAULT:`agent_default`,REFLEX_DEFAULT:`reflex_default`},Ti={owner:`Owner`,member:`Member`,agent_default:`Agent Default`,reflex_default:`Reflex Default`},Ei={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`},Di=[`read`,`create`,`update`,`delete`,`manage`],Oi=[`read`,`create`,`update`,`delete`],ki=[`read`,`create`,`update`,`delete`],Ai={owner:{system:[{target:`*`,actions:Di}],object:[{target:`*`,actions:Di}]},member:{system:[{target:`people`,actions:[`read`]},{target:`workspace`,actions:[`read`]},{target:`connectors`,actions:Oi},{target:`files`,actions:ki},{target:`documents`,actions:ki}],object:[{target:`*`,actions:Di}]},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(wi).includes(e)}const ji={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??ji,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={...Xn,...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 wt(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??ji,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};function agent(e){return new AgentBuilder(e)}const Mi=`@stndrds/schema`;function createStandardSchemaProps(e){return{version:1,vendor:Mi,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(gn(this.build()))}constructor(e,t,n){mt(t),Tt(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 qt(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}currency(e){return this.attr.currencyCode=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=M.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 M.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=[...hi,`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(Kr);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: ${Kr.join(`, `)}`)}}}};function form(e,t){return new FormBuilder(e,t)}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=F.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=F.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(Cn(this.build()))}constructor(e){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 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}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`}]);return validateObjectExpressions({name:this.obj.name,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression}),{...this.obj,pluralLabel:this._pluralLabel,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression,sealed:this._sealed,toleratedAttributes:this._toleratedAttributes}}validateName(e){e!==void 0&&ht(e)}};function object(e){if(Yt(e.name))throw new Qe(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 sourcedAttributeOf(e,t){if(t.type===`richtext`)return typeof t.attribute==`string`?{object:e,attribute:t.attribute}:void 0;if(t.type!==`collection`)return;let n=collectionSourceAddressOf(t.source);if(n?.kind===`related`)return{object:e,attribute:n.relation};if(n?.kind===`relatedFrom`)return{object:n.object,attribute:n.relation}}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 Ni=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=Se.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 Ni({name:e,label:t,object:void 0,context:`record`,contents:[]})}function listView(e,t){return new Ni({name:e,label:t,object:void 0,context:`collection`,contents:[]})}function relationProperty(e){return requireBuilderName(e,[`relationProperty`]),{relationProperty:e}}var L=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}},Pi=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 Pi(e,t,[])}function collection(){return new L({type:`collection`})}function form$1(...e){return new L({type:`form`,groups:e.map(e=>`build`in e?e.build():e)})}function activity(){return new L({type:`activity`})}function richtext$1(e){return new L({type:`richtext`,attribute:e})}function documents(){return new L({type:`documents`})}function forms(){return new L({type:`forms`})}function emails(...e){return new L({type:`emails`,emailAttributes:e})}function meetings(...e){return new L({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 L({...n,extension:e.name},e);return r.build(),r}const R={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 ze(`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 Fi=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 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 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(Yt(e.name)&&!isNativeDefinition(e))throw new Qe(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 ze(`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
|
|
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 C,m as ge,n as _e,o as ve,p as ye,q as be,r as xe,s as Se,t as Ce,tt as we,u as Te,v as Ee,w as De,x as Oe,y as ke,z as Ae}from"./view-config.schema-CCrM5b-O.mjs";import{AccessDeniedError as je,AmbiguousSchemaChangeError as Me,AttributeInUseError as Ne,AttributeNotFoundError as Pe,ConcurrentModificationError as Fe,DuplicateError as w,ForbiddenError as Ie,InvalidPermissionGrantError as Le,MemoryNotFoundError as Re,NotFoundError as ze,NotImplementedError as Be,ObjectNotFoundError as Ve,ObjectReferencedError as He,OrphanSystemAttributeError as Ue,ProtectedResourceError as We,ProtectedRoleError as Ge,RealtimeDeliveryError as Ke,RealtimeRateLimitedError as qe,RealtimeSubscriptionError as Je,RecordNotFoundError as Ye,RecordReferencedError as Xe,RepositoryError as Ze,ReservedObjectNameError as Qe,RoleNotFoundError as $e,SchemaError as T,SchemaErrorCode as E,SearchBackendError as et,StorageError as tt,SyncCascadeError as nt,SyncConflictError as rt,SyncError as it,SystemEntityImmutableError as at,ValidationError as D,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 pt,B as mt,C as ht,D as gt,E as _t,F as vt,G as yt,H as O,I as k,J as bt,K as xt,L as St,M as Ct,N as wt,O as Tt,P as Et,R as Dt,S as Ot,T as kt,U as At,V as jt,W as Mt,X as Nt,Y as Pt,Z as Ft,_ as It,a as Lt,b as Rt,c as zt,d as Bt,f as Vt,g as Ht,h as Ut,i as Wt,j as Gt,k as Kt,l as qt,m as Jt,n as Yt,o as Xt,p as Zt,q as Qt,r as $t,s as en,t as tn,u as nn,v as rn,w as an,x as on,y as sn,z as cn}from"./config-CiAtjzem.mjs";import{n as ln,r as un,t as dn}from"./text-C8Lb-NFo.mjs";import{n as fn,t as pn}from"./core-BLHhNykL.mjs";import{createNumberValidator as mn}from"./validation/primitives/number.mjs";import{createCheckboxValidator as hn}from"./validation/primitives/checkbox.mjs";import{createDateValidator as gn}from"./validation/primitives/date.mjs";import{a as _n,c as vn,i as yn,l as bn,n as xn,o as Sn,r as Cn,s as A,t as wn,u as Tn}from"./utils-fXIvFFl6.mjs";import{n as En,t as j}from"./empty-BgAwlO54.mjs";import{a as Dn,i as On,n as kn,r as An}from"./phone-CRbCvH20.mjs";import{a as jn,c as Mn,d as Nn,f as Pn,i as Fn,o as In,r as Ln,s as Rn,u as zn}from"./object-sbH7KtsH.mjs";import{z as M}from"zod";import{AVATAR_COLOR_IDS as Bn,MEMORY_DESCRIPTION_MAX_LENGTH as Vn,MEMORY_NAME_MAX_LENGTH as Hn,SKILL_DESCRIPTION_MAX_LENGTH as Un,SKILL_NAME_MAX_LENGTH as Wn,getCountryByIso2 as Gn,getCountryDisplayNameByIso3 as N,isValidCurrencyCode as Kn,isValidIso3 as qn}from"@stndrds/constants";import{parsePhoneNumberFromString as Jn}from"libphonenumber-js";const Yn=[`fyi`,`task`,`question`,`handoff`,`system`],Xn=[`low`,`normal`,`high`,`urgent`],Zn=[`public`,`internal`,`sensitive`],Qn=[`unread`,`read`,`archived`,`snoozed`],$n=[`none`,`pending`,`processing`,`completed`,`dismissed`,`expired`,`failed`],er=`agent.session.waiting_human`,tr=`agent.task.assigned`,nr=`agent.question.requested`,rr=[er,tr,nr],ir=[`name`,`type`],ar=[`required`,`hidden`,`archived`,`deprecated`,`defaultValue`,`config`,`order`,`unique`],or=[`label`,`description`,`placeholder`,`icon`],sr=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`status`,`location`,`select`,`multiselect`,`user`,`relation`,`formula`,`rollup`,`document`],cr=`*`;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 be(e)}const lr=[`record`,`object`,`attribute`,`view`,`user`,`role`,`settings`,`file`,`agent`,`schema_source`,`tenant_invitation`,`api_key`],ur=`record.created,record.updated,record.deleted,record.restored,record.purged,record.access_changed,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,api_key.detached,settings.updated,file.uploaded,file.updated,file.deleted`.split(`,`),dr=`agentSessionId`;function isAgentWrittenAuditEntry(e){return e.actorType===`agent`||typeof e.metadata?.agentSessionId==`string`}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 fr=[`completed`,`failed`,`cancelled`,`timeout`,`expired`];function isTerminalSessionStatus(e){return fr.includes(e)}const pr=[`idle`,`completed`,`waiting_human`,`waiting_agents`,`cancelled`,`failed`,`timeout`];function isClaimableSessionStatus(e){return pr.includes(e)}const mr=Object.freeze({mutation:`ask`,destructive:`ask`,outward:`ask`}),hr=[`active`,`completed`,`abandoned`],gr=[`openai`,`anthropic`,`google`,`spacexai`,`deepseek`,`moonshotai`,`alibaba`,`mistral`,`minimax`,`meta`,`zai`],_r=[`standard`,`fast`],vr=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],yr=[`conversation`,`writing`,`coding`,`analysis`,`extraction`],br=[`light`,`standard`,`heavy`],xr=[`manual`,`auto`],Sr={interactive:{inputPerMillionUsd:5,outputPerMillionUsd:25},delegated:{inputPerMillionUsd:2,outputPerMillionUsd:12}},Cr=[`model`,`speed`,`reasoning`,`imageModel`,`routing`];function isRoutineActorMetadata(e){return e?.kind===`routine`}const wr=[`octopus`,`clover`,`flower`,`triangle`,`square`,`blob`,`circle`,`drop`,`hexagon`,`pill`,`pebble`,`puddle`],Tr=[`relaxed`,`neutral`],Er=4,Dr=200;function agentDisplayName(e){return e.label?.trim()||e.name}const Or=[`approval-requested`,`approval-responded`,`approval-dispatched`],kr=[`streaming`,`running`,`pending`,...Or];function isOpenToolPartState(e){return kr.includes(e)}function isToolApprovalState(e){return Or.includes(e)}const Ar=[`CREDITS_EXHAUSTED`];function isSystemPartCode(e){return typeof e==`string`&&Ar.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 jr=200,Mr=182,Nr=366,Pr=`agent-notification`;function isAgentNotificationMetadata(e){return e?.kind===Pr}const Fr=`agent-message`;function isAgentMessageMetadata(e){return e?.kind===Fr}const Ir=[`pending`,`in_progress`,`completed`,`blocked`],Lr=50,Rr=80,zr=500,Br=`session-state`,Vr=`__stndrdsNativeUiPartIds`,Hr=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?.[Vr];isPlainRecord$1(t)||invalidNativePartIds(),(Object.keys(t).length!==2||t.schemaVersion!==1||!isPlainRecord$1(t.partIds))&&invalidNativePartIds();let n=new Map;for(let[t,r]of e.parts.entries()){let e=nativeAgentUIPartIdMetadataKey(r,t);if(!e||n.has(e)){e&&invalidNativePartIds();continue}n.set(e,r)}let r=Object.entries(t.partIds);r.length!==n.size&&invalidNativePartIds();let i=new Map,a={};for(let[e,t]of r){let r=n.get(e);r&&typeof t==`string`&&t.length>0||invalidNativePartIds();let o=i.get(t);o&&(r.type===`tool`||o!==r.type)&&invalidNativePartIds(),r.type===`tool`&&t!==r.toolCallId&&invalidNativePartIds(),i.set(t,r.type),a[e]=t}return a}const Ur=16e3,Wr=3200,Gr=6400,Kr=16e3,qr=65536,Jr=15e3,Yr=1e4,Xr=5e3,Zr=`google/gemini-3.5-transcribe-live`,Qr={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2},$r=`/v1/device-worker/channel`,ei=262144,ti=15e4,ni=1e4,ri=2e3,ii=2e3,ai=2e4,oi=4008,si={initialMs:1e3,maxMs:3e4};function deviceChannelUrl(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${$r}`}function computeRetryDelay(e,t,n){return Math.min(n.initialMs*2**e,n.maxMs)+Math.floor(t()*250)}function computeReconnectDelay(e,t=Math.random){return computeRetryDelay(e,t,si)}const ci=[`worker_disconnected`,`cancelled`,`timed_out`,`execution_failed`,`stale_reference`,`tab_unavailable`,`debugger_unavailable`,`blocked_by_user`];var DeviceChannelProtocolError=class extends T{constructor(e){super(e,E.DEVICE_CHANNEL_PROTOCOL),this._tag=`DeviceChannelProtocolError`,this.name=`DeviceChannelProtocolError`}};const P={id:M.uuid(),leaseToken:M.string().min(1)},li=M.record(M.string(),M.unknown());function defineDeviceChannelFrames(e){return{worker:M.discriminatedUnion(`type`,[M.strictObject({type:M.literal(`authenticate`),credential:M.string().regex(/^(Device|Bearer) \S+$/)}),M.strictObject({type:M.literal(`running`),...P}),M.strictObject({type:M.literal(`heartbeat`),...P}),M.strictObject({type:M.literal(`output`),...P,stdout:M.string().optional(),stderr:M.string().optional()}),M.strictObject({type:M.literal(`complete`),...P,result:M.strictObject({stdout:M.string().optional(),stderr:M.string().optional(),exitCode:M.number().int(),success:M.boolean(),errorCode:M.enum(ci).optional(),result:e.result.optional()})}),M.strictObject({type:M.literal(`pong`)})]),server:M.discriminatedUnion(`type`,[M.strictObject({type:M.literal(`ready`),device:M.strictObject({id:M.string(),name:M.string(),capability:M.enum([`shell`,`browser`])})}),M.strictObject({type:M.literal(`command`),...P,kind:M.enum([`shell`,`browser`]),intent:M.string(),timeoutMs:M.number().int(),command:M.string().optional(),cwd:M.string().nullable().optional(),action:e.action.optional()}),M.strictObject({type:M.literal(`cancel`),id:M.uuid(),reason:M.enum([`cancelled`,`timed_out`,`revoked`])}),M.strictObject({type:M.literal(`reauthenticate`)}),M.strictObject({type:M.literal(`revoked`)}),M.strictObject({type:M.literal(`ping`)})])}}const ui=defineDeviceChannelFrames({action:li,result:li}),di=ui.worker,fi=ui.server;function parseDeviceChannelFrame(e,t){let n;try{n=JSON.parse(t)}catch{throw new DeviceChannelProtocolError(`Frame is not JSON`)}let r=e.safeParse(n);if(!r.success)throw new DeviceChannelProtocolError(`Frame does not match the channel protocol`);return r.data}function parseWorkerFrame(e){return parseDeviceChannelFrame(di,e)}function parseServerFrame(e){return parseDeviceChannelFrame(fi,e)}const pi=[`web`,`presentation`,`document`,`spreadsheet`,`image`,`code`,`other`],mi=[`ephemeral`,`conversation`,`persistent`],hi=[`source`,`preview`,`entrypoint`,`asset`],gi=5,_i=50;function recentActivityEntryKey(e){return e.kind===`record`?JSON.stringify([`record`,e.objectName,e.recordId]):JSON.stringify([`conversation`,`sessionId`in e?e.sessionId:e.session.id])}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 vi=[`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 geocode(){return await Promise.resolve(null)}};const yi=[`reader`,`editor`],bi=[`manual`,`meeting_attendee`];function parseRecordAccessRole(e){if(typeof e==`string`&&yi.includes(e))return e;let t=`role must be one of: ${yi.join(`, `)}`;throw new D(t,[{path:[`role`],message:t}])}function deriveViewerAccess(e,t){return e.visibility===`workspace`?`workspace`:e.ownedBy!==null&&t.includes(e.ownedBy)?`owner`:e.viewerGrant===`editor`?`editor`:`reader`}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 xi=`Notetaker`,Si={meetingRecordingPolicy:`none`,meetingBotDisplayName:xi},Ci=6048e5,wi=36e5,Ti=2592e6,Ei=6e4,Di=[`active`,`suspended`],Oi=[`architect`,`manual`,`auto`];function schemaGroupKey(e){return`${e.kind}:${e.id}`}function refuse$2(e,t){throw new D(t,[{path:[e],message:t}])}function parseSchemaGroupPresentation(e){let t=e??{},n={};if(t.label!==void 0){let e=t.label;if(e===null)n.label=null;else if(typeof e!=`string`)refuse$2(`label`,`Label must be a string`);else{let t=e.trim();t.length===0&&refuse$2(`label`,`Label must not be empty`),t.length>At.labelLength&&refuse$2(`label`,`Label is too long (max ${At.labelLength} characters)`),n.label=t}}if(t.icon!==void 0){let e=t.icon;if(e===null)n.icon=null;else{let t=O.safeParse(e);t.success||refuse$2(`icon`,`Invalid icon name`),n.icon=t.data}}return n}const ki=[`square`,`landscape`,`portrait`];function imageModelFormatDefect(e){if(e.formats.length===0)return`declares no output format`;for(let t of e.formats)if(e.requests[t]===void 0)return`declares the format "${t}" without a request`;for(let t of Object.keys(e.requests))if(!e.formats.includes(t))return`carries a request for the undeclared format "${t}"`}function declaredImageRequests(e){let t={};for(let n of e.formats){let r=e.requests[n];r!==void 0&&(t[n]=r)}return t}function modelReferenceSpellings(e){let t=e.apiModelId??e.id;return{display:[`${e.provider}/${e.id}`,e.id],upstream:[`${e.provider}/${t}`,t]}}function splitReference(e){let t=e.indexOf(`/`);return t<=0?void 0:{provider:e.slice(0,t),model:e.slice(t+1)}}function findModelByReference(e,t,n={}){let r=typeof t==`string`?splitReference(t):t,i=typeof t==`string`&&n.allowBare===!0?t:void 0;function names(e,t){return r!==void 0&&e.provider===r.provider&&t===r.model||t===i}return e.find(e=>names(e,e.id))??e.find(e=>names(e,e.apiModelId??e.id))}const Ai=[`none`,`estimated`,`exact`];function parseCountMode(e){if(typeof e==`string`&&Ai.includes(e))return e;throw new D(`countMode must be one of: ${Ai.join(`, `)} (received: ${String(e)})`,[])}function parseOptionalCountMode(e){return e===void 0?void 0:parseCountMode(e)}const ji=1e4,Mi=[`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 Ni=[`B`,`KB`,`MB`,`GB`,`TB`];function formatByteSize(e){let{value:t,unitIndex:n}=computeByteMagnitude(e);return`${t} ${Ni[n]}`}const Pi={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 Fi=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(!Fi.includes(e.type))throw Error(`Property type "${e.type}" is not supported in .qualifyWith()`);t.push(e)}return{definitions:t}}const Ii=`__`;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}`}const Li=`__`;function qualifiedToolName(e,t,n){return`${e}__${t}__${n}`}function parseQualifiedToolName(e,t){let n=`${e}__`;if(!t.startsWith(n))return null;let r=t.slice(n.length),i=r.indexOf(`__`);if(i<=0)return null;let a=r.slice(i+2);return a===``?null:{namespace:r.slice(0,i),tool:a}}const Ri=/\\([!-/:-@[-`{-~])/g,zi=57344;function markdownToPlainText(e){if(e.length===0)return``;let t=[];return e.replace(Ri,(e,n)=>(t.push(n),String.fromCharCode(zi+t.length-1))).replace(/^[ \t]*```[^\n]*$/gm,``).replace(/<[^>\n]+>/g,` `).replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`).replace(/^[ \t]*\|?[ \t]*:?-{2,}:?[ \t]*(\|[ \t]*:?-{2,}:?[ \t]*)*\|?[ \t]*$/gm,``).replace(/\|/g,` `).replace(/^[ \t]*(#{1,6}[ \t]+|>[ \t]?|[-*+][ \t]+|\d+[.)][ \t]+)/gm,``).replace(/\[[ xX]\][ \t]+/g,``).replace(/(\*\*|__|\*|_|~~|`)/g,``).replace(/^[ \t]*([-*_][ \t]*){3,}$/gm,``).replace(/\s+/g,` `).trim().replace(/[\ue000-\uf8ff]/g,e=>t[e.charCodeAt(0)-zi]??e)}const Bi=`—`;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(cn(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?kn(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(j(e))return`—`;switch(t.type){case`text`:return formatText(e);case`richtext`:return typeof e==`string`?markdownToPlainText(e):String(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 Vi=[`UPPER`,`LOWER`,`capitalize`,`trim`],Hi=[`prefix`,`suffix`,`wrap`,`default`],Ui=[...Vi,...Hi],F=M.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(!Ui.includes(e))return!1}return!0},{message:`Invalid pipe name. Valid pipes: ${Ui.join(`, `)}`});function validateLabelExpression(e){let t=F.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 Wi=`(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=Wi){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 Gi=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function getSingleAttributeFromExpression(e){let t=e.trim().match(Gi);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 Ki=/\{\{\s*props\./;function applyRelationProps(e,t,n){if(!Ki.test(e))return e;let r={},i=new Map(n?.map(e=>[e.name,e]));if(t)for(let[e,n]of Object.entries(t)){if(n==null)continue;let t=i.get(e);if(t){let i=formatAttributeValue(n,t);r[e]=i===`—`?``:i}else r[e]=n}return renderLabelExpression(e,{props:r},``).replace(/\(\s*\)/g,``).replace(/\[\s*\]/g,``).replace(/\s*[-—|:]\s*$/g,``).replace(/\s{2,}/g,` `).trim()}function relationPropertyDefs(e){if(e?.type===`relation`)return e.properties?.definitions}function qualifiedPropertyDefs(e){if(e?.type===`relation`||e?.type===`document`)return e.properties?.definitions}function extractValueRefs(e){if(j(e))return[];if(typeof e==`string`)return[{id:e}];if(Array.isArray(e))return e.flatMap(e=>extractValueRefs(e));if(typeof e==`object`&&`id`in e){let t=e;if(typeof t.id==`string`)return[{id:t.id,props:t.props}]}return[]}const qi=80;function chosenUserName(e){return e.preferredName?.trim()||void 0}function getUserDisplayName(e){let t=chosenUserName(e);if(t!==void 0)return t;let n=[e.firstName,e.lastName].map(e=>e?.trim()).filter(Boolean).join(` `);return n===``?e.email?.split(`@`)[0]??``:n}const Ji=/\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(Ji)?.[0];return t===void 0?``:[...t.toUpperCase()][0]??``}).filter(Boolean).slice(0,2).join(``);return i===``?t:i}const Yi=`__creatorRootActorId`;function getRecordCreatorPrincipalId(e){let t=e.metadata?.[Yi];return typeof t==`string`&&t.length>0?t:e.createdBy}const Xi=[{id:`data`,capabilities:[{id:`forms`,resources:[`forms`],levels:[{id:`fill`,add:[`read`]},{id:`edit`,add:[`create`,`update`,`delete`]},{id:`manage`,add:[`manage`]}]}]},{id:`structure`,capabilities:[{id:`schema`,resources:[`architect`],levels:[{id:`use`,add:[`read`]},{id:`edit`,add:[`create`,`update`,`delete`]}]}]},{id:`ai`,capabilities:[{id:`agents`,resources:[`agents`],levels:[{id:`chat`,add:[`read`]},{id:`build`,add:[`create`,`update`,`delete`]},{id:`manage`,add:[`manage`]}]},{id:`workstations`,resources:[`workstations`],levels:[{id:`use`,add:[`create`]}]}]},{id:`files`,capabilities:[{id:`files`,resources:[`files`,`documents`],levels:[{id:`read`,add:[`read`]},{id:`edit`,add:[`create`,`update`]},{id:`full`,add:[`delete`]}]}]},{id:`team`,capabilities:[{id:`people`,resources:[`people`],levels:[{id:`view`,add:[`read`]},{id:`invite`,add:[`create`]},{id:`manage`,add:[`update`,`delete`]}]}]},{id:`integrations`,capabilities:[{id:`connectors`,resources:[`connectors`],levels:[{id:`use`,add:[`read`,`create`,`update`,`delete`]}]},{id:`api-keys`,resources:[`api-keys`],levels:[{id:`view`,add:[`read`]},{id:`manage`,add:[`create`,`delete`]}]},{id:`env-vars`,resources:[`env-vars`],levels:[{id:`view`,add:[`read`]},{id:`manage`,add:[`create`,`delete`]}]}]},{id:`administration`,capabilities:[{id:`settings`,resources:[`settings`],levels:[{id:`view`,add:[`read`]},{id:`manage`,add:[`update`,`delete`,`manage`]}]},{id:`audit`,resources:[`audit`],levels:[{id:`view`,add:[`read`]}]},{id:`billing`,resources:[`billing`],levels:[{id:`view`,add:[`read`]}]}]}],Zi=`none`,Qi=`custom`,I={actions:[`read`,`create`,`update`,`delete`],purge:`manage`,levels:[{id:`read`,add:[`read`]},{id:`edit`,add:[`create`,`update`]},{id:`full`,add:[`delete`]}]},L=Xi.flatMap(e=>e.capabilities),$i=L.flatMap(e=>e.resources),ea=new Map(L.flatMap(e=>e.resources.map(t=>[t,e])));function isCatalogResource(e){return ea.has(e)}function capabilityForResource(e){let t=ea.get(e);if(!t)throw new T(`Unknown catalog resource "${e}"`,E.INVARIANT_VIOLATION);return t}function sameActions(e,t){let n=new Set(e),r=new Set(t);return n.size===r.size&&[...n].every(e=>r.has(e))}function levelActions(e,t){let n=new Set;for(let r of e.levels){for(let e of r.add)n.add(e);if(r.id===t)return[...n]}return[]}function levelOf(e,t){if(t.length===0)return Zi;let n=e.levels[e.levels.length-1];if(t.includes(`*`)&&n)return n.id;let r=new Set(t),i=new Set;for(let t of e.levels){for(let e of t.add)i.add(e);if(i.size===r.size&&[...r].every(e=>i.has(e)))return t.id}return Qi}const ta=[`read`,`create`,`update`,`delete`,`manage`],na=M.object({scope:M.enum([`object`,`system`]),target:M.string().min(1),actions:M.array(M.enum(ta))}).strict();function findGrantIssues(e,t){let n=[],r=new Map;for(let i of e){let e=na.safeParse(i);if(!e.success){let e=typeof i==`object`&&i&&`target`in i?String(i.target):`?`;n.push({target:e,reason:`shape`});continue}let a=e.data;if(a.scope===`system`){if(!isCatalogResource(a.target)){n.push({target:a.target,reason:`unknown-resource`});continue}if(levelOf(capabilityForResource(a.target),a.actions)===`custom`){n.push({target:a.target,reason:`off-level`});continue}r.set(a.target,a.actions);continue}if(a.target!==`*`&&!t.objectNames.has(a.target)){n.push({target:a.target,reason:`unknown-object`});continue}let o=a.target===`*`?[...I.actions,I.purge]:I.actions;a.actions.every(e=>o.includes(e))||n.push({target:a.target,reason:`object-action`})}let i=new Set;for(let[e,t]of r){let a=capabilityForResource(e);if(!i.has(a)){for(let o of a.resources)if(!sameActions(t,r.get(o)??[])){n.push({target:e,reason:`split-capability`}),i.add(a);break}}}return n}function includesAction(e,t){return e?.includes(`*`)===!0||e?.includes(t)===!0}function grantCovers(e,t,n){return includesAction(e?.[`*`],n)||includesAction(e?.[t],n)}function buildPermissionFlags(e){return{canRead:includesAction(e,`read`),canCreate:includesAction(e,`create`),canUpdate:includesAction(e,`update`),canDelete:includesAction(e,`delete`),canManage:includesAction(e,`manage`)}}function isInertLegacyGrant(e){return e.scope===`system`&&e.target!==`*`&&!isCatalogResource(e.target)}function uncoveredGrants(e,t){let n=[];for(let r of t){if(isInertLegacyGrant(r))continue;let t=r.scope===`object`?e.objectPermissions:e.systemPermissions??{},i=r.actions.flatMap(e=>e===`*`?[...ta]:e===`observe`?[]:[e]);for(let e of i)grantCovers(t,r.target,e)||n.push({scope:r.scope,target:r.target,action:e})}return n}function sliceFlags(e,t){return buildPermissionFlags([...e?.[`*`]??[],...e?.[t]??[]])}function objectPermissionFlags(e,t){return sliceFlags(e.objectPermissions,t)}function systemPermissionFlags(e,t){return sliceFlags(e.systemPermissions,t)}const ra=`mixed`;function levelWithin(e,t){let n=new Set(e.levels.flatMap(e=>e.add));return levelOf(e,t.filter(e=>e===`*`||n.has(e)))}function grantsToPermissions(e){let t={},n={};for(let r of e){let e=r.scope===`object`?t:n;e[r.target]=[...new Set([...e[r.target]??[],...r.actions])]}return{objectPermissions:t,systemPermissions:n}}function readAccessLevels(e){let t=e.systemPermissions??{},n=e.objectPermissions??{},r={};for(let e of L){let n=new Set(e.resources.map(n=>levelWithin(e,[...t[n]??[],...t[`*`]??[]]))),[i]=n;r[e.id]=n.size===1&&i!==void 0?i:Qi}let i=n[`*`]??[],a=levelWithin(I,i),o=[];for(let[e,t]of Object.entries(n)){if(e===`*`)continue;let n=levelWithin(I,[...i,...t]);n!==a&&o.push({objectName:e,level:n})}return{capabilities:r,defaultObjectLevel:a,exceptions:o,purge:includesAction(i,I.purge)}}function readRoleLevels(e){return readAccessLevels(grantsToPermissions(e))}function summarizeGroup(e,t){let n=Xi.find(e=>e.id===t);if(!n)throw new T(`Unknown permission group "${t}"`,E.INVARIANT_VIOLATION);let{capabilities:r}=readRoleLevels(e),i=new Set(n.capabilities.map(e=>r[e.id]??`none`)),[a]=i;return i.size===1&&a!==void 0?a:ra}function knownActions(e,t){let n=[...new Set(e.levels.flatMap(e=>e.add))];return t.includes(`*`)?n:n.filter(e=>t.includes(e))}function storedActions(e,t,n){return e.filter(e=>e.scope===t&&e.target===n).flatMap(e=>e.actions)}function isSubset(e,t){return e.every(e=>t.includes(e))}function isLevelOf(e,t){return t===`none`||e.levels.some(e=>e.id===t)}function defaultObjectActions(e,t){return e.defaultObjectLevel===`custom`?knownActions(I,storedActions(t,`object`,`*`)):levelActions(I,e.defaultObjectLevel)}function grantsFromLevels(e,t){let n=[];for(let r of L){let i=e.capabilities[r.id]??`none`;if(i!==`none`)for(let e of r.resources){let a=i===`custom`?knownActions(r,[...storedActions(t,`system`,e),...storedActions(t,`system`,`*`)]):levelActions(r,i);a.length>0&&n.push({scope:`system`,target:e,actions:a})}}let r=defaultObjectActions(e,t),i=e.purge?[...r,I.purge]:r;i.length>0&&n.push({scope:`object`,target:`*`,actions:i});for(let{objectName:i,level:a}of e.exceptions){let e=a===`custom`?knownActions(I,storedActions(t,`object`,i)):levelActions(I,a);isSubset(e,r)||n.push({scope:`object`,target:i,actions:e})}return n}function withLevels(e,t){return grantsFromLevels(t(readRoleLevels(e)),e)}function normalizeRoleGrants(e){return withLevels(e,e=>e)}function setCapabilityLevel(e,t,n){let r=L.find(e=>e.id===t);return r&&isLevelOf(r,n)?withLevels(e,e=>({...e,capabilities:{...e.capabilities,[t]:n}})):e}function setDefaultObjectLevel(e,t){return isLevelOf(I,t)?withLevels(e,e=>({...e,defaultObjectLevel:t})):e}function exceptionLevels(e){let t=defaultObjectActions(readRoleLevels(e),e);return I.levels.map(e=>e.id).filter(e=>!isSubset(levelActions(I,e),t))}function setObjectException(e,t,n){return t===`*`||!exceptionLevels(e).includes(n)?e:withLevels(e,e=>{let r=e.exceptions.some(e=>e.objectName===t);return{...e,exceptions:r?e.exceptions.map(e=>e.objectName===t?{objectName:t,level:n}:e):[...e.exceptions,{objectName:t,level:n}]}})}function removeObjectException(e,t){return withLevels(e,e=>({...e,exceptions:e.exceptions.filter(e=>e.objectName!==t)}))}function setPurge(e,t){return withLevels(e,e=>({...e,purge:t}))}function canCopyRole(e,t){return uncoveredGrants(e,normalizeRoleGrants(t)).length===0}function canGrantLevel(e,t,n,r=!1){if(`objectName`in t){if(!isLevelOf(I,n))return!1;let i=levelActions(I,n),a=t.objectName===`*`&&r?[...i,I.purge]:i;return uncoveredGrants(e,[{scope:`object`,target:t.objectName,actions:a}]).length===0}let i=L.find(e=>e.id===t.capabilityId);if(!i||!isLevelOf(i,n))return!1;let a=levelActions(i,n);return uncoveredGrants(e,i.resources.map(e=>({scope:`system`,target:e,actions:a}))).length===0}function canGrantPurge(e){return uncoveredGrants(e,[{scope:`object`,target:`*`,actions:[I.purge]}]).length===0}function normalizeRoleLabel(e){return e.trim().toLowerCase()}function isRoleLabelTaken(e,t,n){let r=normalizeRoleLabel(t);return e.some(e=>e.id!==n&&normalizeRoleLabel(e.label)===r)}function roleNameFromLabel(e,t){let n=e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_+|_+$/g,``),r=n===``?`role`:/^[a-z]/.test(n)?n:`role_${n}`,i=r.slice(0,63);if(!t.has(i))return i;let a=2;for(;;){let e=`_${a}`,n=`${r.slice(0,63-e.length)}${e}`;if(!t.has(n))return n;a+=1}}const ia=new Set([`id`,`name`,`label`,`type`,`required`,`system`,`unique`,`order`]),aa={OWNER:`owner`,MEMBER:`member`,AGENT_DEFAULT:`agent_default`},oa={owner:`Owner`,member:`Member`,agent_default:`Agent Default`},sa={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, files, and read access to the audit trail`},R=[...I.actions],ca=[...ta],la={owner:{system:[{target:`*`,actions:ca}],object:[{target:`*`,actions:ca}]},member:{system:[{target:`people`,actions:[`read`]},{target:`architect`,actions:[`read`]},{target:`agents`,actions:[`read`]},{target:`settings`,actions:[`read`]},{target:`audit`,actions:[`read`]},{target:`forms`,actions:[`read`]},{target:`workstations`,actions:[`create`]},{target:`connectors`,actions:R},{target:`files`,actions:R},{target:`documents`,actions:R}],object:[{target:`*`,actions:R}]},agent_default:{system:[{target:`documents`,actions:[`read`,`create`,`update`]},{target:`files`,actions:[`read`,`create`,`update`]},{target:`env-vars`,actions:[`read`]},{target:`audit`,actions:[`read`]}],object:[{target:`*`,actions:R}]}},ua=[{role:`member`,scope:`object`,target:`*`,actions:[`manage`]}];function isDefaultRole(e){return Object.values(aa).includes(e)}const da=[{id:`claude-code`,label:`Claude Code`,available:!0,loginCommand:`claude setup-token 2>&1 | tee ~/.standards/login.log`,credentialPaths:[`~/.standards/login.log`,`~/.claude/.credentials.json`],apiKeyEnv:[`ANTHROPIC_API_KEY`],models:[{id:`sonnet`,label:`Claude Sonnet`},{id:`opus`,label:`Claude Opus`},{id:`haiku`,label:`Claude Haiku`}],defaultModel:`sonnet`},{id:`codex`,label:`Codex`,available:!1,loginCommand:`codex login --device-auth`,credentialPaths:[`~/.codex/auth.json`],apiKeyEnv:[`OPENAI_API_KEY`],models:[{id:`gpt-5-codex`,label:`GPT-5 Codex`}],defaultModel:`gpt-5-codex`},{id:`opencode`,label:`OpenCode`,available:!1,loginCommand:`opencode auth login`,credentialPaths:[`~/.local/share/opencode/auth.json`],apiKeyEnv:[`ANTHROPIC_API_KEY`,`OPENAI_API_KEY`],models:[{id:`anthropic/claude-sonnet-4-5`,label:`Claude Sonnet 4.5`}],defaultModel:`anthropic/claude-sonnet-4-5`},{id:`cursor`,label:`Cursor`,available:!1,loginCommand:`cursor-agent login`,credentialPaths:[`~/.config/cursor/auth.json`],apiKeyEnv:[`CURSOR_API_KEY`],models:[{id:`auto`,label:`Auto`}],defaultModel:`auto`},{id:`grok-build`,label:`Grok Build`,available:!1,loginCommand:`grok login`,credentialPaths:[`~/.grok/auth.json`],apiKeyEnv:[`XAI_API_KEY`],models:[{id:`grok-code-fast-1`,label:`Grok Code Fast 1`}],defaultModel:`grok-code-fast-1`}],fa=new Map(da.map(e=>[e.id,e]));function isWorkstationHarnessId(e){return fa.has(e)}function findWorkstationHarness(e){return fa.get(e)}const pa={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}avatar(e){return this.bp.avatar={type:e.type,color:e.color,expression:e.expression??`relaxed`},this}starters(e){return e.length===0?delete this.bp.starters:this.bp.starters=[...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??pa,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={...mr,...this.bp.approval,...e},this}visibility(e){return this.bp.visibility=e,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 Gt(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??pa,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};function agent(e){return new AgentBuilder(e)}const ma=`@stndrds/schema`;function createStandardSchemaProps(e){return{version:1,vendor:ma,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(Nn(this.build()))}constructor(e,t,n){Ct(t),Et(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 wt(e,`attribute "${this.attr.name}"`),this.attr.icon=e,this}order(e){return this.attr.order=e,this}defaultValue(e){return(`defaultValue`in this.attr||![`formula`,`rollup`].includes(this.attr.type))&&(this.attr.defaultValue=e),this}metadata(e){return this.attr.metadata=e,this}build(){return this.attr}},TextAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`text`,e,t)}minLength(e){return this.attr.minLength=e,this}maxLength(e){return this.attr.maxLength=e,this}pattern(e){return this.attr.pattern=e,this.attr.format=void 0,this}multiline(e=!0){return this.attr.multiline=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}email(){return this.attr.format=`email`,this.attr.pattern=void 0,this}url(){return this.attr.format=`url`,this.attr.pattern=void 0,this}slug(){return this.attr.format=`slug`,this.attr.pattern=void 0,this}};function text(e){return new TextAttributeBuilder(e.name,e.label)}var RichtextAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`richtext`,e,t)}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function richtext(e){return new RichtextAttributeBuilder(e.name,e.label)}var NumberAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`number`,e,t)}min(e){return this.attr.min=e,this}max(e){return this.attr.max=e,this}integer(){return this.attr.unit=`integer`,this.attr.decimals=0,this}decimal(e=2){return this.attr.unit=`decimal`,this.attr.decimals=e,this}percentage(){return this.attr.unit=`percentage`,this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function number(e){return new NumberAttributeBuilder(e.name,e.label)}var CheckboxAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`checkbox`,e,t)}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function checkbox(e){return new CheckboxAttributeBuilder(e.name,e.label)}var DateAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`date`,e,t)}format(e){return this.attr.dateFormat=e,this}minDate(e){return this.attr.minDate=e,this}maxDate(e){return this.attr.maxDate=e,this}endDate(){return this.attr.endDate=!0,this.asPhantomState()}includeTime(){return this.attr.includeTime=!0,this}timeFormat(e){return this.attr.timeFormat=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function date(e){return new DateAttributeBuilder(e.name,e.label)}var PhoneAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`phone`,e,t)}defaultCountry(e){return this.attr.defaultCountryCode=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function phone(e){return new PhoneAttributeBuilder(e.name,e.label)}var CurrencyAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`currency`,e,t)}defaultCurrency(e){return this.attr.defaultCurrency=e,this}allowedCurrencies(e){return this.attr.allowedCurrencies=e,this}allowNegative(e=!0){return this.attr.allowNegative=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function currency(e){return new CurrencyAttributeBuilder(e.name,e.label)}var StatusAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`status`,e,t)}options(e){let t=asMutableArray(e);return k(this.attr.name??`unknown`,t),this.attr.options=t,this.asPhantomState()}option(e){this.attr.options||(this.attr.options=[]);let t=[...this.attr.options,e];return k(this.attr.name??`unknown`,t),this.attr.options.push(e),this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function status(e){return new StatusAttributeBuilder(e.name,e.label)}var SelectAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`select`,e,t)}options(e){let t=asMutableArray(e);return k(this.attr.name??`unknown`,t),this.attr.options=t,this.asPhantomState()}option(e){this.attr.options||(this.attr.options=[]);let t=[...this.attr.options,e];return k(this.attr.name??`unknown`,t),this.attr.options.push(e),this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function select(e){return new SelectAttributeBuilder(e.name,e.label)}var MultiselectAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`multiselect`,e,t)}options(e){let t=asMutableArray(e);return k(this.attr.name??`unknown`,t),this.attr.options=t,this.asPhantomState()}option(e){this.attr.options||(this.attr.options=[]);let t=[...this.attr.options,e];return k(this.attr.name??`unknown`,t),this.attr.options.push(e),this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function multiselect(e){return new MultiselectAttributeBuilder(e.name,e.label)}var LocationAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`location`,e,t)}granularity(e){return this.attr.granularity=e,this}defaultCountry(e){return this.attr.defaultCountry=e,this}allowedCountries(e){return this.attr.allowedCountries=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function location(e){return new LocationAttributeBuilder(e.name,e.label)}var UserAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`user`,e,t),this.attr.types=[`user`,`agent`]}types(e){let t=[...new Set(e)];if(t.length===0)throw Error(`[AttributeBuilder] user.types must contain at least one type.`);return this.attr.types=t,this}multiple(){return this.attr.multiple=!0,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function user(e){return new UserAttributeBuilder(e.name,e.label)}var BaseRelationAttributeBuilder=class extends BaseAttributeBuilder{to(e,t){let n={object:e,...t};return this.attr.targets?.push(n),this}toAny(){return this.attr.targets=[{object:`*`}],this}qualifyWith(...e){let t=this.attr.targets;if(!t||t.length===0)throw Error(`.qualifyWith() must be called AFTER .to(). Example: relation({ name: "companies" }).to("companies").qualifyWith(...)`);return this.attr.properties=buildPropertySchema(e),this}bilateral(e){let t=this.attr.targets;if(!t||t.length===0)throw Error(`.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })`);if(t.length>1)throw Error(`Bilateral relations are not supported for polymorphic relations (multiple .to() targets).`);if(isUniversalRelation(this.attr))throw Error(`Bilateral relations are not supported for universal relations (.toAny()).`);let n=t[0]?.object;if(!n)throw new D(`Bilateral relation requires one target object`,[{path:[`bilateral`,`object`],message:`Bilateral relation requires one target object`}]);if(e.object&&e.object!==n){let t=`Bilateral inverse object ${e.object} must match relation target ${n}`;throw new D(t,[{path:[`bilateral`,`object`],message:t}])}return this.attr.bilateral={...e,object:n},this}},SingleRelationAttributeBuilder=class extends BaseRelationAttributeBuilder{constructor(e,t){super(`relation`,e,t),this.attr.cardinality=`one`,this.attr.targets=[]}many(){let e=new MultiRelationAttributeBuilder(this.attr.name,this.attr.label??``,{targets:this.attr.targets,isRequired:this.attr.required});return this.attr.system===!1&&e.runtime(),this.attr.hidden&&e.hidden(),this.attr.placeholder&&e.placeholder(this.attr.placeholder),this.attr.description&&e.description(this.attr.description),this.attr.icon&&e.icon(this.attr.icon),this.attr.order!==void 0&&e.order(this.attr.order),this.attr.metadata&&e.metadata(this.attr.metadata),e}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}},MultiRelationAttributeBuilder=class extends BaseRelationAttributeBuilder{constructor(e,t,n){super(`relation`,e,t),this.attr.cardinality=`many`,this.attr.targets=n?.targets??[],this.attr.defaultValue=[],n?.isRequired&&this.setRequired(!0)}maxItems(e){return this.attr.maxItems=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function relation(e){return new SingleRelationAttributeBuilder(e.name,e.label)}var FormulaAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`formula`,e,t),this.attr.required=!1}expression(e){return this.attr.expression=e,this}returns(e){return this.attr.returnType=e,this}decimals(e){return this.attr.decimals=e,this}currency(e){return this.attr.currencyCode=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=asMutableArray(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=M.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 M.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=[...Ui,`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(vi);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: ${vi.join(`, `)}`)}}}};function form(e,t){return new FormBuilder(e,t)}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=F.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=F.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(zn(this.build()))}constructor(e){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);Gt([...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}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`}]);return validateObjectExpressions({name:this.obj.name,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression}),{...this.obj,pluralLabel:this._pluralLabel,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression,sealed:this._sealed,toleratedAttributes:this._toleratedAttributes}}validateName(e){e!==void 0&&vt(e)}};function object(e){if(Ft(e.name))throw new Qe(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 sourcedAttributeOf(e,t){if(t.type===`richtext`)return typeof t.attribute==`string`?{object:e,attribute:t.attribute}:void 0;if(t.type!==`collection`)return;let n=collectionSourceAddressOf(t.source);if(n?.kind===`related`)return{object:e,attribute:n.relation};if(n?.kind===`relatedFrom`)return{object:n.object,attribute:n.relation}}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 ha=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=xe.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 ha({name:e,label:t,object:void 0,context:`record`,contents:[]})}function listView(e,t){return new ha({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}},ga=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 ga(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 ze(`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 _a=new FlagRegistry;function createFlagRegistry(){return new FlagRegistry}var FlagService=class{constructor(e){this.registry=e.registry,this.staticDefaults=new Map(e.staticDefaults?.map(e=>[e.name,e.value])??[])}resolveAll(){let e=new Map;for(let t of this.registry.listNames())e.set(t,this.getValue(t));for(let t of this.staticDefaults.keys())e.set(t,this.getValue(t));return e}getValue(e){return this.staticDefaults.has(e)?this.staticDefaults.get(e):this.registry.get(e)?.defaultValue}isEnabled(e){return this.getValue(e)===!0}};function createFlagService(e){return new FlagService(e)}const va=Symbol(`stndrds.native-object`);function markNativeDefinition(e){return Object.defineProperty(e,va,{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[va]===!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(Ft(e.name)&&!isNativeDefinition(e))throw new Qe(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 ze(`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 ya=new NativeObjectRegistryClass,ba=new WeakSet;function markSystemView(e){return ba.add(e.definition),e}function isSystemViewDefinition(e){return typeof e==`object`&&!!e&&ba.has(e)}const xa=`## 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
|
+
`,Sa=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(Wn).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(Un).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(xa)).build(),Ca=markSystemView(detailView(`skill-detail`,`Skill`).for(`skill`).default().tab(`content`,`Content`,B.richtext(`content`).titleAttribute(`name`)).tab(`files`,`Files`,B.documents()).tab(`activity`,`Activity`,B.activity()).aside(`details`,`Details`,B.form(group(`details`,`Details`).fields(`name`,`description`))).build()),wa=markSystemView(listView(`skill-list`,`Skills`).for(`skill`).default().tab(`workspace`,`Skills`,B.collection().object(`skill`).list().icon(`list`).visibility(`workspace`).columns(`name`,`description`).descriptionAttribute(`description`).displayAttributes(`createdBy`,`updatedAt`).sort(`name`)).tab(`mine`,`My skills`,B.collection().object(`skill`).list().icon(`lock`).visibility(`private`).columns(`name`,`description`).descriptionAttribute(`description`).displayAttributes(`createdBy`,`updatedAt`).sort(`name`)).build()),Ta=nativeObject({name:`memory`,label:`Memory`}).sealed().icon(`database`).order(2**53-1).pluralLabel(`Memories`).labelExpression(`{{ name }}`).embeddingExpression(`{{ name }}
|
|
37
37
|
{{ description }}
|
|
38
|
-
{{ content }}`).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 }}`).attribute(text({name:`name`,label:`Name`}).maxLength(Hn).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(Vn).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(),Ea={combinator:`and`,rules:[{attribute:`invalidAt`,operator:`is_empty`,value:null},{attribute:`reviewState`,operator:`is_empty`,value:null}]},Da=markSystemView(detailView(`memory-detail`,`Memory`).for(`memory`).default().tab(`content`,`Content`,B.richtext(`content`).titleAttribute(`name`)).aside(`details`,`Details`,B.form(group(`details`,`Details`).fields(`description`,`kind`,`source`,`provenance`,`reviewState`,`reviewReason`,`validFrom`,`invalidAt`,`supersededBy`,`curatedAt`,`reviewAfter`,`subjects`,`links`))).build()),Oa=markSystemView(listView(`memory-list`,`Memories`).for(`memory`).default().tab(`workspace`,`Memories`,B.collection().object(`memory`).list().icon(`list`).visibility(`workspace`).columns(`name`,`kind`,`description`,`createdAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`subjects`,`createdAt`).filter(Ea).sort(`name`)).tab(`mine`,`My memories`,B.collection().object(`memory`).list().icon(`lock`).visibility(`private`).columns(`name`,`kind`,`description`,`createdAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`subjects`,`createdAt`).filter(Ea).sort(`name`)).tab(`review`,`To review`,B.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`,B.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()),V=`drives`,ka=nativeObject({name:V,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(),Aa=markSystemView(detailView(`drive-detail`,`Drive`).for(V).default().tab(`documents`,`Documents`,B.documents()).aside(`details`,`Details`,B.form(group(`details`,`Details`).field(`description`))).build()),ja=markSystemView(listView(`drive-list`,`Drives`).for(V).default().tab(`workspace`,`Shared`,B.collection().object(V).table().icon(`users`).visibility(`workspace`).columns(`name`,`description`,`updatedAt`).sort(`name`)).tab(`mine`,`My drives`,B.collection().object(V).table().icon(`lock`).visibility(`private`).columns(`name`,`description`,`updatedAt`).sort(`name`)).build()),Ma={name:`artifact_preview`,requiresRecord:!0,parameters:M.object({}).strict()},H=`artifact`,Na=nativeObject({name:H,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(),Pa=markSystemView(detailView(`artifact-detail`,`Artifact`).for(H).default().tab(`preview`,`Preview`,B.custom(Ma,{})).tab(`versions`,`Versions`,B.documents().allowUpload(!1).allowRemove(!1).hideAttachments(!0)).tab(`activity`,`Activity`,B.activity()).aside(`details`,`Details`,B.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()),Fa=markSystemView(listView(`artifact-list`,`Artifacts`).for(H).default().tab(`mine`,`My artifacts`,B.collection().object(H).list().icon(`lock`).visibility(`private`).actions().columns(`name`,`kind`,`currentRevision`,`updatedAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`currentRevision`,`updatedAt`).sort(`updatedAt`,`desc`)).tab(`workspace`,`Workspace`,B.collection().object(H).list().icon(`list`).visibility(`workspace`).actions().columns(`name`,`kind`,`currentRevision`,`updatedAt`).descriptionAttribute(`description`).displayAttributes(`kind`,`currentRevision`,`updatedAt`).sort(`updatedAt`,`desc`)).build()),U=`meeting`,W={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`},Ia=`meeting-list`,La=`calendar-sync`,Ra=`meeting-detail`,za=[W.title,W.startsAt,W.endsAt,W.status],Ba=nativeObject({name:U,label:`Meeting`}).sealed().hidden().metadata({platformOwned:{editable:[W.linkedRecords],source:La}}).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 C(`view`,n,`[ViewRegistry] Duplicate view: "${t}" for object "${e}"`)}};const sa=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 singleRelationTarget(e){let[t,...n]=e.targets;return t&&n.length===0&&t.object!==`*`?t.object:void 0}function requireSingleRelationTarget(e,t=[e.name,`targets`]){let n=singleRelationTarget(e);if(n===void 0){let n=`Relation "${e.name}" requires one concrete collection target`;throw new E(n,[{path:t,message:n}])}return n}function violationOf(e,t,n,r){if(!(e instanceof w))throw e;let i=e instanceof E?e.errors[0]:void 0;return{key:JSON.stringify([t,n,e.code,e.message]),contentName:n,path:i?.path??r,message:e.message,code:e.code,error:e}}const ca=new Map(ue().map(e=>[e.name,e]));function reject$2(e,t){throw new E(t,[{path:e,message:t}])}function requireName(e,t){e.trim().length===0&&reject$2(t,`API name must not be empty`)}function indexUnique(e,t,n){let r=new Map;return e.forEach((e,i)=>{if(requireName(e.name,[...n,String(i),`name`]),r.has(e.name))throw new C(t,e.name);r.set(e.name,e)}),r}const la=30;function capped(e,t){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} … and ${e.length-t} more`:n}function attributeInventory(e,t){return t.length===0?`Object "${e}" has no attributes yet.`:`Attributes of "${e}": ${capped(t,30)}`}function requireAttribute$1(e,t,n,r,i){if(requireName(t,n),!e)return;let a=e.attributes?.get(t)??ca.get(t);if(!a){if(!e.attributes)return;let r=attributeInventory(e.name,[...e.attributes.keys()]);reject$2(n,`Unknown attribute "${e.name}.${t}". ${r}${i?.()??``}`)}return r&&a.type!==r&&reject$2(n,`Attribute "${e.name}.${t}" must have type ${r}`),a}function collectContentViewCatalogue(e){let t=e.mode??`published`,n=new Map;e.objects.forEach((e,t)=>{if(requireName(e.name,[`objects`,String(t),`name`]),n.has(e.name))throw new C(`object`,e.name);n.set(e.name,{name:e.name,attributes:indexUnique(e.attributes,`attribute`,[`objects`,String(t),`attributes`])})});let r=new Set;(e.reservedObjects??[]).forEach((e,i)=>{let a=[`reservedObjects`,String(i)];requireName(e,a),!n.has(e)&&(t!==`draft`&&reject$2(a,`Unresolved reserved object "${e}"`),r.add(e),n.set(e,{name:e}))});let i=indexUnique(e.extensions??[],`extension`,[`extensions`]);function resolveObject(e,t){requireName(e,t);let r=n.get(e);return r||reject$2(t,`Unknown object "${e}"`),r}function inverseAddresses(e){let t=[];for(let[r,i]of n)if(r!==e)for(let n of i.attributes?.values()??[])n.type===`relation`&&relationAcceptsObject(n,e)&&t.push(`relatedFrom("${r}", "${n.name}")`);return t.sort().slice(0,3)}let a=t===`draft`?Ce():me(),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}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[0];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 ua=[Object.freeze(Xi)];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 ua)this.extensions.set(e.name,e)}};const da=new ContentExtensionRegistry;function cleanContent(e,t){let n=structuredClone(e),r=new Set(t.map(e=>JSON.stringify(e.path))),remove=(...e)=>r.has(JSON.stringify(e));switch(n.type){case`form`:return n.groups.forEach((e,t)=>{e.fields=e.fields.filter((e,n)=>!remove(`groups`,String(t),`fields`,String(n),`attribute`))}),n;case`collection`:{if(n.columns&&=n.columns.filter((e,t)=>!remove(`columns`,String(t))),n.displayAttributes&&=n.displayAttributes.filter((e,t)=>!remove(`displayAttributes`,String(t))),n.layout!==`kanban`&&n.columnSizing)for(let e of Object.keys(n.columnSizing))remove(`columnSizing`,e)&&delete n.columnSizing[e];let e=n.filters?.rules.filter((e,t)=>!remove(`filters`,`rules`,String(t),`attribute`)),t=n.sorts?.filter((e,t)=>!remove(`sorts`,String(t),`attribute`)),emptied=(e,t)=>e!==void 0&&e.length===0&&t!==void 0&&t.length>0,{filters:r,sorts:i,descriptionAttribute:a,...o}=n;return{...o,...n.filters&&e&&!emptied(e,n.filters.rules)?{filters:{...n.filters,rules:e}}:{},...t&&!emptied(t,n.sorts)?{sorts:t}:{},...a===void 0||remove(`descriptionAttribute`)?{}:{descriptionAttribute:a}}}case`richtext`:if(remove(`titleAttribute`)){let{titleAttribute:e,...t}=n;return t}return n;case`activity`:case`custom`:case`documents`:case`forms`:case`emails`:case`meetings`:return n;default:throw new E(`Unsupported content ${String(n)}`,[])}}function listedObjectWithoutCatalogue(e,t){if(t.type!==`collection`)return e.object;let n=collectionSourceAddressOf(t.source);return n===void 0||n.kind===`related`?void 0:n.object}function namedBy(e){return t=>typeof t==`string`&&!t.includes(`.`)&&e.has(t)}function scrubPathsFor(e,t){let n=[],r=namedBy(t);switch(e.type){case`form`:return e.groups.forEach((e,t)=>e.fields.forEach((e,i)=>{r(e.attribute)&&n.push([`groups`,String(t),`fields`,String(i),`attribute`])})),n;case`collection`:if(e.columns?.forEach((e,t)=>{r(e)&&n.push([`columns`,String(t)])}),e.displayAttributes?.forEach((e,t)=>{r(e)&&n.push([`displayAttributes`,String(t)])}),e.layout!==`kanban`&&e.columnSizing)for(let t of Object.keys(e.columnSizing))r(t)&&n.push([`columnSizing`,t]);return r(e.descriptionAttribute)&&n.push([`descriptionAttribute`]),e.filters?.rules.forEach((e,t)=>{r(e.attribute)&&n.push([`filters`,`rules`,String(t),`attribute`])}),e.sorts?.forEach((e,t)=>{r(e.attribute)&&n.push([`sorts`,String(t),`attribute`])}),n;case`richtext`:return r(e.titleAttribute)&&n.push([`titleAttribute`]),n;default:return n}}function removedSource(e,t,n){let r=sourcedAttributeOf(e.object,t);return r&&n(r.object,r.attribute)?r.attribute:void 0}function planAttributeRemoval(e,t,n=listedObjectWithoutCatalogue){let r=new Map;for(let e of t){let t=r.get(e.object)??new Set;t.add(e.attribute),r.set(e.object,t)}let removed=(e,t)=>typeof t==`string`&&r.get(e)?.has(t)===!0,i={scrubbed:[],dropped:[],blocked:[]};for(let t of e){let e=!1,a;for(let o of t.contents){let s={object:t.object,view:t.name,content:o.name},c=o.placement===`main`,l=removedSource(t,o,removed);if(l!==void 0){let e={...s,attribute:l};i.dropped.push(e),c&&(a??=e);continue}e||=c;let u=n(t,o),d=u===void 0?void 0:r.get(u);if(!d)continue;if(o.type===`collection`&&o.layout===`kanban`&&namedBy(d)(o.groupByAttribute)){i.blocked.push({...s,attribute:o.groupByAttribute,reason:`kanban-grouping`});continue}let f=scrubPathsFor(o,d);if(f.length===0)continue;let p=cleanContent(o,f.map(e=>({path:e})));A(p)!==A(o)&&i.scrubbed.push({...s,definition:p})}!e&&a!==void 0&&i.blocked.push({...a,reason:`last-main-content`})}return i}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 fa=new FormRegistry,pa=[`attestorIdentity`,`evidenceDigest`,`maintenanceEpoch`,`observedZeroAt`,`resumeRevision`,`version`,`workloadInventoryDigest`],ma=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ha=/^[0-9a-f]{40}$/,ga=/^[0-9a-f]{64}$/,_a=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/,va=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?Z$/;function invalid$1(e,t){throw new E(`Invalid DeploymentBarrierAttestorV1`,[{path:[e],message:t}])}function isRecord$4(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function requirePattern(e,t,n,r){let i=e[t];return(typeof i!=`string`||!n.test(i))&&invalid$1(t,r),i}function requireCanonicalTimestamp(e){let t=e.observedZeroAt;typeof t!=`string`&&invalid$1(`observedZeroAt`,`must be a UTC timestamp string`);let n=va.exec(t);n||invalid$1(`observedZeroAt`,`must be a canonical ISO UTC timestamp`);let[,r,i,a,o,s,c]=n,l=new Date(t);return(!Number.isFinite(l.getTime())||l.getUTCFullYear()!==Number(r)||l.getUTCMonth()+1!==Number(i)||l.getUTCDate()!==Number(a)||l.getUTCHours()!==Number(o)||l.getUTCMinutes()!==Number(s)||l.getUTCSeconds()!==Number(c))&&invalid$1(`observedZeroAt`,`must name a real UTC instant`),t}function decodeDeploymentBarrierAttestationV1(e,t){isRecord$4(e)||invalid$1(`$`,`must be an object`);let n=Object.keys(e).sort();(n.length!==pa.length||n.some((e,t)=>e!==pa[t]))&&invalid$1(`$`,`must contain exactly the V1 attestation keys`),e.version!==1&&invalid$1(`version`,`must equal numeric 1`);let r=requirePattern(e,`maintenanceEpoch`,ma,`must be a lowercase canonical UUID`),i=requirePattern(e,`resumeRevision`,ha,`must be a lowercase 40-character Git SHA`),a=requireCanonicalTimestamp(e),o=requirePattern(e,`attestorIdentity`,_a,`must be a lowercase slug`);if(o.length>64&&invalid$1(`attestorIdentity`,`must be at most 64 characters`),o!==t.allowedAttestorIdentity)throw new E(`Deployment barrier attestor identity mismatch`,[{path:[`attestorIdentity`],message:`does not equal the configured identity`}]);return{version:1,maintenanceEpoch:r,resumeRevision:i,observedZeroAt:a,attestorIdentity:o,workloadInventoryDigest:requirePattern(e,`workloadInventoryDigest`,ga,`must be exactly 64 lowercase hexadecimal characters`),evidenceDigest:requirePattern(e,`evidenceDigest`,ga,`must be exactly 64 lowercase hexadecimal characters`)}}function verifyDeploymentBarrierAttestationV1(e,t){let n=decodeDeploymentBarrierAttestationV1(e,t);if(n.maintenanceEpoch!==t.maintenanceEpoch)throw new E(`Deployment barrier maintenance epoch mismatch`,[{path:[`maintenanceEpoch`],message:`does not equal the current maintenance epoch`}]);if(n.resumeRevision!==t.resumeRevision)throw new E(`Deployment barrier resume revision mismatch`,[{path:[`resumeRevision`],message:`does not equal the requested revision`}]);let r=t.now.getTime()-new Date(n.observedZeroAt).getTime();if(!Number.isFinite(t.now.getTime())||r>9e5||r<-6e4)throw new E(`Deployment barrier attestation is stale`,[{path:[`observedZeroAt`],message:`must be within the database freshness window`}]);return n}const ya=Object.freeze({attest(){return Promise.reject(new w(`DeploymentBarrierAttestorV1 requires a host implementation that observes the deployment control plane`,T.CONFIGURATION_REQUIRED))}});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 ba=204800,xa=256;function isRecord$3(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$3(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$3(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$3(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 Sa=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}),Ca=[`membership-unknown`,`sort-unknown`,`permissions-changed`],wa=[`permission-revoked`,`workspace-left`,`object-deleted`],Ta=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],Ea=[`type`,`objectId`,`recordId`,`recordVersion`],Da=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],Oa=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],ka=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&Sa.includes(e)}function isLiveEventPayload(e){return isRecord$2(e)&&isLiveEventType(e.type)?isLiveEventPayloadForType(e.type,e):!1}function isLiveEventPayloadForType(e,t){if(!isRecord$2(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$2(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,jn)}function isNotificationPriority(e){return isOneOf(e,Mn)}function isNotificationSensitivity(e){return isOneOf(e,Nn)}function isNotificationInboxState(e){return isOneOf(e,Pn)}function isNotificationWorkState(e){return isOneOf(e,Fn)}function isNotificationSubject(e){return isRecord$2(e)&&hasString(e,`type`)&&hasString(e,`id`)}function isRecordFieldPatch(e){return isRecord$2(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$2)&&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,Ea)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$2(e)&&hasOnlyKeys(e,Oa)&&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$2(e.values)&&hasOptional(e,`metadata`,isRecord$2)&&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,Da)&&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,Ca)}function isAgentSessionPatchPayload(e){return e.type===`agent.session.patch`&&hasString(e,`sessionId`)&&isRecord$2(e.patch)&&hasVersion(e,`version`)&&hasString(e,`updatedAt`)}function isLiveNotification(e){return isRecord$2(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$2(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$2(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$2(e)?Object.keys(e).every(e=>Ta.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,ka)&&hasNonEmptyString(e,`targetActorId`)&&hasVersion(e,`archivedCount`)&&hasVersion(e,`version`)&&hasIsoDateString(e,`updatedAt`)}const Aa=[`armed`,`disarmed`],ja=[`authoring`,`compiling`,`replaying`,`promoted`,`failed`],Ma=[`promoted`,`lkg`];function isArchitectDraftUpdatedPayload(e){if(e.type!==`architect.draft.updated`||!isRecord$2(e.receipt))return!1;let t=e.receipt;return Array.isArray(t.operationIds)&&t.operationIds.every(isNonEmptyString)&&isRecord$2(t.revision)&&hasNonEmptyString(t.revision,`draftId`)&&hasVersion(t.revision,`version`)&&Array.isArray(t.changedTargets)&&t.changedTargets.every(e=>isRecord$2(e)&&isNonEmptyString(e.token)&&isNamedTarget(e.target))}function isNamedTarget(e){if(!isRecord$2(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,Aa)&&hasIsoDateString(e,`updatedAt`)}function isReflexRunCompletedPayload(e){return e.type===`reflex.run.completed`&&hasNonEmptyString(e,`reflexId`)&&hasNonEmptyString(e,`runId`)&&isOneOf(e.served,Ma)&&hasVersion(e,`version`)&&hasVersion(e,`wallMs`)&&hasIsoDateString(e,`completedAt`)}function isReflexAuthoringProgressPayload(e){return e.type===`reflex.authoring.progress`&&hasNonEmptyString(e,`reflexId`)&&isOneOf(e.status,ja)&&hasIsoDateString(e,`updatedAt`)}const Na=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,Na)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const Pa=[`ok`,`low`,`exhausted`,`paused`],Fa=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,Pa)&&isOneOf(e.mode,Fa)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,wa)}function isRecord$1(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$1(e)?payloadChannel(e):null}function isLiveEventEnvelope(e){return isRecord$1(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$1(e.payload):!1}const Ia=[`if`,`concat`,`sum`,`avg`,`count`,`min`,`max`,`earliest`,`latest`,`unique`,`first`,`percent_empty`,`percent_not_empty`,`count_empty`,`count_not_empty`,`count_unique`],La={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(La,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=La[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}=La[e];if(t>=n&&t<=(r??1/0))return;let i=r===void 0?`at least ${n}`:`between ${n} and ${r}`;throw Error(`Function "${e}" expects ${i} arguments, received ${t}`)}function evaluateCall(e,t){switch(e){case`concat`:return t.filter(e=>e!=null).map(String).join(``);case`sum`:return areCommensurable(t)?numericValues(t).reduce((e,t)=>e+t,0):null;case`avg`:{if(!areCommensurable(t))return null;let e=numericValues(t);return e.length>0?e.reduce((e,t)=>e+t,0)/e.length:null}case`count`:return collectionItems(t[0]).length;case`min`:return minMax(t,`min`);case`max`:return minMax(t,`max`);case`earliest`:return dateMinMax(t,`min`);case`latest`:return dateMinMax(t,`max`);case`unique`:return uniqueNonEmpty(collectionItems(t[0]));case`first`:return collectionItems(t[0]).find(e=>e!=null)??null;case`percent_empty`:return percentByEmptyState(t[0],!0);case`percent_not_empty`:return percentByEmptyState(t[0],!1);case`count_empty`:return collectionItems(t[0]).filter(j).length;case`count_not_empty`:return collectionItems(t[0]).filter(e=>!j(e)).length;case`count_unique`:return uniqueNonEmpty(collectionItems(t[0])).length;default:return unreachable(e)}}function unreachable(e){return e}function numericValues(e){return flatten(e).map(toFiniteNumber).filter(e=>e!==null)}function areCommensurable(e){let t=new Set;for(let n of flatten(e))isCurrencyValue(n)&&t.add(currencyCode(n));return t.size<=1}function currencyCode(e){return e.code.toUpperCase()}function numericBinary(e,t,n){if(!areCommensurable([e,t]))return null;let r=toFiniteNumber(e),i=toFiniteNumber(t);if(r===null||i===null)return null;let a=n(r,i);return Number.isFinite(a)?a:null}function minMax(e,t){if(!areCommensurable(e))return null;let n=numericValues(e);return n.length>0?t===`min`?Math.min(...n):Math.max(...n):dateMinMax(e,t)}function dateMinMax(e,t){let n=flatten(e).map(toDate$1).filter(e=>e!==null);if(n.length===0)return null;let r=n.map(e=>e.getTime()),i=t===`min`?Math.min(...r):Math.max(...r);return new Date(i).toISOString()}function percentByEmptyState(e,t){let n=collectionItems(e);return n.length===0?0:n.filter(e=>j(e)===t).length/n.length}function uniqueNonEmpty(e){let t=new Set,n=[];for(let r of e){if(j(r))continue;let e=uniqueKey(r);t.has(e)||(t.add(e),n.push(r))}return n}function collectionItems(e){return e==null?[]:Array.isArray(e)?flatten(e):[e]}function flatten(e){return e.flat(1/0)}function toFiniteNumber(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:null}return isCurrencyValue(e)&&Number.isFinite(e.value)?e.value:null}function isCurrencyValue(e){return typeof e==`object`&&!!e&&typeof e.value==`number`&&typeof e.code==`string`}function toDate$1(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e!=`string`){let t=dateValueStart(e);if(t===null)return null;let n=new Date(t);return Number.isNaN(n.getTime())?null:n}let t=new Date(e);return Number.isNaN(t.getTime())?null:t}function uniqueKey(e){if(isCurrencyValue(e))return`currency:${currencyCode(e)}:${e.value}`;let t=toFiniteNumber(e);return t===null?e instanceof Date?`date:${e.toISOString()}`:`${typeof e}:${JSON.stringify(e)}`:`number:${t}`}function isPlainRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function formatComputedResult(e,t,n){if(e==null)return null;let stringifyScalar=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e instanceof Date?String(e):null;switch(t){case`number`:{let t=typeof e==`number`?e:Number(e);return Number.isNaN(t)?null:n===void 0?t:Number(t.toFixed(n))}case`boolean`:return!!e;case`date`:return e instanceof Date?e.toISOString():typeof e==`string`?e:null;case`text`:return String(e);case`select`:if(Array.isArray(e)){for(let t of e){if(t==null)continue;let e=stringifyScalar(t);if(e!==null)return e}return null}return stringifyScalar(e);case`multiselect`:return Array.isArray(e)?e.flatMap(e=>{if(e==null)return[];let t=stringifyScalar(e);return t===null?[]:[t]}):stringifyScalar(e)===null?[]:[String(e)];default:throw Error(`Unsupported computed return type: ${t}`)}}function evaluateComputedAst(e,t){return evaluateAst(e,t)}function evaluateComputedFormula(e,t){return evaluateAst(k(e),t)}function evaluateComputedFormulaWithResult(e,t,n,r){try{let i=evaluateAst(k(e),t);return{value:n?formatComputedResult(i,n,r):i}}catch(e){return{value:null,error:e instanceof Error?e.message:String(e)}}}const 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)`}],za=new Date(0).setUTCFullYear(1,0,1),Ba=/^\d{4}-\d{2}-\d{2}$/,Va=new Set([`createdAt`,`updatedAt`,`deletedAt`]),Ha=/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])(?:[T ]([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d)(?:\.(\d{1,6}))?)?(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;function offsetMinutes(e){if(e===void 0||e===`Z`)return 0;let t=e.startsWith(`-`)?-1:1,n=e.slice(1).replace(`:`,``);return t*(Number(n.slice(0,2))*60+Number(n.slice(2,4)||`0`))}function parseFilterInstant(e){if(e instanceof Date){let t=e.getTime();return Number.isNaN(t)?null:t}if(typeof e!=`string`)return null;let t=Ha.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l]=t,u=Number(n),d=Number(r),f=Number(i),p=new Date(0);if(p.setUTCFullYear(u,d-1,f),u===0||p.getUTCDate()!==f)return null;p.setUTCHours(Number(a??`0`),Number(o??`0`),Number(s??`0`),Number((c??``).padEnd(3,`0`).slice(0,3)));let m=p.getTime()-offsetMinutes(l)*6e4;return m<za?null:m}function unwrapRange(e){return isDateRangeValue(e)?dateValueStart(e):e}function hasTime(e){return e.type===`date`&&e.includeTime===!0}function isSystemTimestamp(e){return Va.has(e.name)}function instantWindow(e){let t=parseFilterInstant(e);return t===null?null:{startMs:t,endMs:t+(typeof e==`string`&&Ba.test(e)?864e5:1)}}function storedUtcDay(e){let t=unwrapRange(e);if(t instanceof Date)return Number.isNaN(t.getTime())?null:De(t.getTime());if(typeof t!=`string`||t===``)return null;if(Ba.test(t))return t;let n=new Date(t);return Number.isNaN(n.getTime())?null:De(n.getTime())}function comparandDay(e){return e instanceof Date?Number.isNaN(e.getTime())?null:De(e.getTime()):typeof e==`string`?Ba.test(e)?e:parseFilterInstant(e)===null?null:e.slice(0,10):null}function toDate(e){if(e==null)return null;let t=e instanceof Date?e:new Date(String(e));return Number.isNaN(t.getTime())?null:t}function dateEquals(e,t,n,r){if(isSystemTimestamp(r)){let r=(storedUtcDay(t)??``)===(storedUtcDay(n)??``);return e===`is`?r:!r}if(hasTime(r)){let r=instantWindow(n);if(!r)return!1;let i=parseFilterInstant(unwrapRange(t)),a=i!==null&&i>=r.startMs&&i<r.endMs;return e===`is`?a:!a}let i=comparandDay(n);if(i===null)return!1;let a=storedUtcDay(t)===i;return e===`is`?a:!a}function orderAgainst(e,t,n){switch(e){case`greater_than`:return t>=n.endMs;case`greater_or_equal`:return t>=n.startMs;case`less_than`:return t<n.startMs;case`less_or_equal`:return t<n.endMs}}function dateOrdering(e,t,n,r){if(isSystemTimestamp(r)){let r=toDate(unwrapRange(t))?.getTime(),i=toDate(n)?.getTime();return r!==void 0&&i!==void 0&&orderAgainst(e,r,{startMs:i,endMs:i+1})}if(hasTime(r)){let r=instantWindow(n),i=parseFilterInstant(unwrapRange(t));return r!==null&&i!==null&&orderAgainst(e,i,r)}let i=comparandDay(n),a=i===null?null:instantWindow(i),o=toDate(unwrapRange(t))?.getTime();return a!==null&&o!==void 0&&orderAgainst(e,o,a)}const isEmpty=e=>j(e)||Array.isArray(e)&&e.length===0,toStr=e=>e==null?``:String(e),toNum=e=>{if(j(e))return null;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null},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)},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,t)=>({appliesTo:[`number`,`currency`,`date`,`formula`],evaluateInMemory:(n,r,i)=>i.type===`date`?dateOrdering(e,n,r,i):compareNumbers(n,r,t)}),U={is:{appliesTo:[`text`,`phone`,`number`,`currency`,`checkbox`,`status`,`select`,`date`,`user`,`relation`,`formula`],evaluateInMemory:(e,t,n)=>n.type===`checkbox`?e===!0==(t===!0):n.type===`date`?dateEquals(`is`,e,t,n):equalsForAttr(e,t,n)},is_not:{appliesTo:[`text`,`phone`,`number`,`currency`,`status`,`select`,`date`,`user`,`relation`,`formula`],evaluateInMemory:(e,t,n)=>n.type===`date`?dateEquals(`is_not`,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(`less_than`,(e,t)=>e<t),greater_than:orderingSpec(`greater_than`,(e,t)=>e>t),less_or_equal:orderingSpec(`less_or_equal`,(e,t)=>e<=t),greater_or_equal:orderingSpec(`greater_or_equal`,(e,t)=>e>=t),is_within:{appliesTo:[`date`],evaluateInMemory:(e,t)=>{let n=toDate(e),r=fe(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}),Ua=[...Object.entries(de).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,...Ua])}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 i=n.get(e.attribute);if(!i)return!1;if(e.property&&i.type===`location`){if(!(u(e.property)&&re(e.operator)))return!1;let n=U[e.operator];if(!n)return!1;let r=t[e.attribute],a=typeof r==`object`&&r?r[e.property]:void 0;return evaluateNormalizedComparands(n,`text`,e.operator,a,e.value,i)}if(e.property){let n=resolvePropertyDefinitions(i).find(t=>t.name===e.property);if(!n)return!1;let a=y(e.operator),o=U[a];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,a,r[e.property],e.value,n)});return(e.quantifier??r(e.operator))===`none`?!c:c}let a=U[e.operator];if(!a||!a.appliesTo.includes(i.type))return!1;let o=t[e.attribute],s=i.type===`relation`||i.type===`document`||i.type===`user`?normalizeReferenceIds(o):o;return evaluateNormalizedComparands(a,i.type,e.operator,s,e.value,i)}function evaluateNormalizedComparands(e,t,n,r,i,a){let[o,s]=normalizeOperatorComparands(t,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){return e===`phone`?normalizePhoneComparands(t,n):[normalizeComparableValue(e,t),normalizeComparableValue(e,n)]}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 En(t.phoneNumber);let n=typeof t.countryCode==`string`?t.countryCode:r;return`${n}:${wn(t.phoneNumber,n)}`};return[normalizeOne(e),normalizeOne(t)]}function normalizeComparableValue(e,t){return e===`currency`?i(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 Wa=`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,n){if(e.operator===`is`)return t(e.value)?resolveDynamicValue(e.value,n):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator===`any_of`){if(!Array.isArray(e.value)||e.value.length!==1)return;let r=e.value[0];return t(r)?resolveDynamicValue(r,n):r}}function resolveDynamicValue(e,t){if(t){if(e.dynamic===`actor`)return t.userId;if(e.anchor===`today`)return dateInTimezone(t.now,t.timezone);if(e.anchor===`now`)return t.now.toISOString()}}function requestedCapabilities(e){let t=[];return e.canModify&&t.push(`modify`),e.canSend&&t.push(`send`),t}const Ga={status:`connector_status`,error:`connector_error`,provider:`connector_provider`};let Ka=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const qa=[`threads`,`messages`];function isMailboxListMode(e){return qa.includes(e)}const Ja=[`reply`,`reply_all`];function isReplyMode(e){return Ja.includes(e)}const Ya=2e5,Xa=998,Za=[`force`,`skip`],Qa=[`none`,`all`,`external_only`],$a=`x-fake-signature`,eo={override:null,status:`none`,failureReason:null,botId:null},to=/^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&&!to.test(t)?t:e.firstUserText?buildAgentFallbackTitle(e.firstUserText):e.emptyLabel}const no=/^[a-z0-9][a-z0-9-]{0,62}$/;function assertSchemaSourceId(e){if(!no.test(e))throw new E(`Invalid schema source id "${e}": expected a lowercase slug matching ${no}`,[])}function pricePerMillion(e){let t=[...e?.perToken===void 0?[]:[e.perToken],...(e?.tiers??[]).map(e=>e.cost)],n=[];for(let e of t){let t=perTokenToPerMillion(e);if(t===void 0)return;n.push(t)}return n.length===0?void 0:Math.max(...n)}function perTokenToPerMillion(e){if(e.trim()===``)return;let t=Number(e)*1e6;return Number.isFinite(t)?Math.round(t*1e6)/1e6:void 0}function routingPrice(e,t){let n=t===`fast`&&e.pricing?.fast?e.pricing.fast:e.pricing,r=pricePerMillion(n?.input),i=pricePerMillion(n?.output);if(r!==void 0&&i!==void 0)return{inputPerMillionUsd:Math.max(r,e.listPricing?.inputPerMillionUsd??0),outputPerMillionUsd:Math.max(i,e.listPricing?.outputPerMillionUsd??0)}}function isUnderRoutingCeiling(e,t){return e!==void 0&&e.inputPerMillionUsd<=t.inputPerMillionUsd&&e.outputPerMillionUsd<=t.outputPerMillionUsd}function isRoutableModel(e){return e.tasks!==void 0&&Object.keys(e.tasks).length>0}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 ro=M.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 SQL migration — so pick it correctly now.'),io=M.string().min(1).superRefine((e,t)=>{try{mt(e)}catch(e){t.addIssue({code:M.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).`),ao=M.string().min(1).superRefine((e,t)=>{Yt(e)&&t.addIssue({code:M.ZodIssueCode.custom,message:`"${e}" is a reserved object name (${St.join(`, `)}) and cannot be used for a new object.`});try{ht(e)}catch(e){t.addIssue({code:M.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=kt(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:M.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:M.ZodIssueCode.custom,path:[`config`],message:`Config for type "${e.type}" is invalid or incomplete: ${errorMessage(n)}`})}})}const oo=M.object({objectName:M.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:io,label:M.string().min(1).max(128).describe(`Human-readable display label shown in the UI. 1-128 characters, cannot be empty.`),type:ro,config:M.record(M.string(),M.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:M.boolean().optional().describe(`Whether the attribute must have a value on every record. Defaults to false (optional).`),description:M.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),so=withConfigCheck(oo),co=withConfigCheck(oo.omit({objectName:!0})),lo=M.object({name:ao,label:M.string().min(1).describe(`Human-readable singular display label (e.g. "Devis").`),pluralLabel:M.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:M.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:F.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:M.array(co).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(),uo=M.object({attributeRemovals:M.array(M.object({objectName:M.string().min(1).describe(`Object the attribute is removed from.`),attributeName:M.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:M.array(M.object({objectName:M.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:M.array(M.object({objectName:M.string().min(1).describe(`Object the renamed attribute belongs to.`),from:M.string().min(1).describe(`Current attribute name. Must already exist and not be a system attribute.`),to:io.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:[]}),fo=M.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.`),po=M.object({objects:M.array(lo).default([]),attributes:M.array(so).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}),M.NEVER;let r=new TextEncoder().encode(A(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}`}),M.NEVER):e}const mo=M.object({schemaPlanVersion:M.literal(2).describe(`Required proposal contract version.`),summary:fo,additive:po,destructive:uo}).strict().superRefine(addPlanLimitIssues),ho=Object.assign(M.preprocess(boundSerializedPlanInput,mo),{shape:mo.shape}),go=M.object({schemaPlanVersion:M.literal(2),summary:fo,additive:po,destructive:uo}).strict().superRefine(addPlanLimitIssues),_o=M.preprocess(boundSerializedPlanInput,go);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}function priceDimension(e,t){return{...e===void 0?{}:{perToken:e},...t===void 0?{}:{tiers:t.map(e=>({cost:e.cost,min:e.min??0,...e.max===void 0?{}:{max:e.max}}))}}}function normalizeFastPricing(e){return{input:priceDimension(e.input,e.input_tiers),output:priceDimension(e.output,e.output_tiers),...e.input_cache_read!==void 0||e.input_cache_read_tiers!==void 0?{cacheRead:priceDimension(e.input_cache_read,e.input_cache_read_tiers)}:{},...e.input_cache_write!==void 0||e.input_cache_write_tiers!==void 0?{cacheWrite:priceDimension(e.input_cache_write,e.input_cache_write_tiers)}:{}}}function normalizePricing(e){return{...normalizeFastPricing(e),...e.fast===void 0?{}:{fast:normalizeFastPricing(e.fast)}}}const vo=/^[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);(!vo.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&&!dn(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)&&!dn(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);(!vo.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=M.number().finite().nonnegative(),yo=M.enum(Qn),bo=M.enum($n),xo=M.enum(er),So=M.enum(rr),Co=M.object({provider:yo,model:M.string().min(1)}).strict(),wo=M.object({speed:bo.optional(),reasoning:xo.optional(),routing:So.optional()}).strict(),To=M.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),Eo=M.object({model:Co.optional(),speed:bo.optional(),reasoning:xo.optional(),imageModel:To.optional(),routing:So.optional()}).strict(),Do=Eo.refine(e=>ar.some(t=>e[t]!==void 0),{message:`At least one inference override is required`}),Oo=M.object({model:Co.nullable().optional(),speed:bo.nullable().optional(),reasoning:xo.nullable().optional(),imageModel:To.nullable().optional(),routing:So.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`}),ko=M.object({model:M.string().min(1),routing:M.object({mode:M.literal(`auto`),tasks:M.array(M.enum(tr)).optional(),demand:M.enum(nr).optional(),reason:M.enum([`selected`,`retained`,`fallback`]).optional(),relation:M.enum([`continue`,`modify`,`new`,`aside`,`unknown`]).optional(),anchorMessageId:M.string().min(1).optional()})}),Ao=M.object({label:M.string(),denied:M.boolean().optional(),deletion:M.object({target:M.string().optional(),count:G.optional(),restorableDays:G.optional()}).strict().optional(),counts:M.record(M.string(),G).optional(),warnings:M.array(M.string()).optional()}).strict(),jo=M.union([M.object({type:M.literal(`text`),text:M.string()}).strict(),M.object({type:M.literal(`reasoning`),text:M.string()}).strict(),M.object({type:M.literal(`system`),code:M.enum(cr)}).strict(),M.object({type:M.literal(`error`),error:M.string(),errorClass:M.string().optional()}).strict(),M.object({type:M.literal(`tool`),toolCallId:M.string(),name:M.string(),args:M.record(M.string(),M.unknown()),result:M.unknown().optional(),error:M.string().optional(),errorCode:M.enum([`output_limit_reached`,`interrupted`,T.INVALID_TOOL_INPUT,`external_outcome_unknown`,`external_not_dispatched`]).optional(),state:M.enum([`streaming`,`running`,`completed`,`error`,`pending`,`approval-requested`,`approval-responded`,`approval-dispatched`]),durationMs:G.optional(),approvalId:M.string().optional(),approvalImpact:Ao.optional(),approved:M.boolean().optional(),approvalReason:M.string().optional(),approvalRelaxableByAuto:M.boolean().optional()}).strict(),M.object({type:M.literal(`file`),fileId:M.string(),name:M.string(),mimeType:M.string()}).strict(),M.object({type:M.literal(`compaction`),state:M.literal(`in-progress`),reason:M.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:G.optional(),reportedTokens:G.optional()}).strict(),M.object({type:M.literal(`compaction`),state:M.literal(`completed`),tokensBefore:G,tokensAfter:G,tokensSaved:G,strategy:M.enum([`no-op`,`summary`,`truncation`]),durationMs:G,summary:M.string().optional()}).strict(),M.object({type:M.literal(`compaction`),state:M.literal(`failed`),reason:M.string(),durationMs:G.optional()}).strict()]),Mo=M.object({id:M.string(),name:M.string(),mimeType:M.string(),size:G}).strict(),No=M.object({id:M.string(),artifactId:M.string(),revision:M.number().int().min(1),selectedText:M.string()}).strict(),Po=M.object({id:M.string(),type:M.string().transform(e=>e),entityId:M.string(),label:M.string(),objectName:M.string().optional(),startIndex:G,endIndex:G}).strict(),Fo=M.object({provider:yo,model:M.string(),maxTokens:G.optional(),contextWindow:G.optional()}).strict(),Io=M.union([M.date(),M.string().datetime({offset:!0}).transform(e=>new Date(e))]),Lo=M.object({id:M.string(),sessionId:M.string(),tenantId:M.string().optional(),runId:M.string().optional(),role:M.enum([`user`,`assistant`,`system`,`tool`]),parts:M.array(jo),attachments:M.array(Mo).optional(),mentions:M.array(Po).optional(),quotes:M.array(No).optional(),model:Fo.optional(),tokenUsage:M.object({input:G,output:G}).strict().optional(),metadata:M.record(M.string(),M.unknown()).optional(),createdAt:Io}).strict(),Ro=M.object({id:M.string(),description:M.string(),status:M.enum([`pending`,`in_progress`,`completed`,`blocked`]),result:M.string().optional(),updatedAt:G.optional()}).strict(),zo=M.object({id:M.string(),sessionId:M.string(),status:M.enum([`active`,`completed`,`abandoned`]),todos:M.array(Ro),version:G,createdAt:M.string(),updatedAt:M.string(),completedAt:M.string().optional()}).strict(),Bo={"session-named":M.object({name:M.string()}).strict(),"compaction-start":M.object({reason:M.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:G.optional(),reportedTokens:G.optional()}).strict(),"compaction-end":M.object({tokensBefore:G,tokensAfter:G,tokensSaved:G,strategy:M.enum([`no-op`,`summary`,`truncation`]),durationMs:G,summary:M.string().optional()}).strict(),"compaction-failed":M.object({reason:M.string()}).strict(),usage:M.object({messageId:M.string().min(1).optional(),inputTokens:G,outputTokens:G,totalTokens:G,cacheReadTokens:G.optional(),cacheCreationTokens:G.optional(),contextWindow:G,residentTokens:G,utilization:M.number().finite().min(0).max(1),costUsd:G.optional()}).strict(),"message-persisted":M.object({message:Lo}).strict(),"message-updated":M.object({message:Lo}).strict(),"todo-plan-update":M.object({plan:zo}).strict(),"approval-context":M.object({approvalId:M.string(),toolCallId:M.string(),impact:Ao.optional(),relaxableByAuto:M.boolean().optional()}).strict(),"session-state":M.object({state:M.object({phase:M.enum([`queued`,`running`,`parked`,`terminal`]),parkedOn:M.enum([`human`,`agents`]).optional(),humanRequestIds:M.array(M.string()).optional(),outcome:M.enum([`completed`,`failed`,`cancelled`,`timeout`,`expired`]).optional()}).strict(),version:M.number().int().positive(),updatedAt:M.string().datetime({offset:!0})}).strict()};function isAgentUIDataName(e){return e in Bo}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=M.object({type:M.literal(`data-${n}`),id:M.string().optional(),data:Bo[n],transient:M.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}})}const Vo=[`Very economical`,`Balanced`,`Powerful`,`Very powerful`],Ho=[`unsupported`,`effort`,`toggle`,`budget`,`model-controlled`],Uo=[`text`,`image`,`audio`,`video`,`pdf`],Wo=[`character`,`word`],Go=/^\d+x\d+$/,Ko=/^\d+:\d+$/,qo=/^[a-z0-9][a-z0-9-]*$/,Jo=.01;function refuse(e){throw new E(`Model catalogue: ${e}`,[])}function refuseZodIssues(e){let[t]=e.issues;throw new E(`Model catalogue: ${t?.message??`the payload is invalid`}`,e.issues.map(e=>({path:e.path.map(String),message:e.message,code:e.code})))}function parseOrRefuse(e,t){let n=e.safeParse(t);return n.success||refuseZodIssues(n.error),n.data}function nonEmptyString(e){return M.string({error:e}).min(1,{error:e})}function positiveIntegerSchema(e,t){let error=n=>`${e} has a ${t} that is not a positive integer, got ${String(n.input)}`;return M.number({error}).int({error}).positive({error})}function priceDefect(e,t){let n=Number(e.trim());return e.trim().length===0||!Number.isFinite(n)?`unreadable`:n<0||n>Jo?`implausible`:n===0&&!t?`undeclared-zero`:null}const Yo=M.looseObject({cost:M.string(),min:M.number(),max:M.number().optional()});function priceDimensionSchema(e,t,n){let r=`model "${e}" has an unreadable ${t} price`;return M.looseObject({perToken:M.string().optional(),tiers:M.array(Yo).optional()},{error:r}).superRefine((i,a)=>{let o=i.tiers;if(i.perToken===void 0&&(o===void 0||o.length===0)){a.addIssue({code:`custom`,message:r});return}let s=[...i.perToken===void 0?[]:[i.perToken],...(o??[]).map(e=>e.cost)];for(let i of s){let o=priceDefect(i,n);if(o===`unreadable`){a.addIssue({code:`custom`,message:`${r} "${i}"`});return}if(o===`implausible`){a.addIssue({code:`custom`,message:`model "${e}" has an implausible ${t} price "${i}", above the ${Jo} per-token ceiling`});return}if(o===`undeclared-zero`){a.addIssue({code:`custom`,message:`model "${e}" has a zero ${t} price without declaring "free": true`});return}}if(i.perToken===void 0&&o!==void 0){let n=`model "${e}" ${t} price tiers must cover every token count from zero without gaps`,r=0;for(let[e,t]of o.entries()){if(!Number.isInteger(t.min)||t.min!==r){a.addIssue({code:`custom`,message:n});return}if(t.max===void 0){if(e===o.length-1)break;a.addIssue({code:`custom`,message:n});return}if(!Number.isInteger(t.max)||t.max<=t.min){a.addIssue({code:`custom`,message:n});return}r=t.max}if(o.at(-1)?.max!==void 0){a.addIssue({code:`custom`,message:n});return}}})}function pricingSchema(e,t){let dimensions=n=>({input:priceDimensionSchema(e,`${n}input`,t),output:priceDimensionSchema(e,`${n}output`,t),cacheRead:priceDimensionSchema(e,`${n}cacheRead`,!0).optional(),cacheWrite:priceDimensionSchema(e,`${n}cacheWrite`,!0).optional()}),n=`model "${e}" has no usable pricing`;return M.looseObject({...dimensions(``),fast:M.looseObject(dimensions(`fast `),{error:n}).optional()},{error:n})}function catalogTextModelSchema(e,t){let n=`model "${e}"`;return M.looseObject({id:nonEmptyString(`${n} has no usable id`),apiModelId:nonEmptyString(`${n} has no usable apiModelId`).optional(),provider:M.enum(Qn,{error:e=>`${n} names an unknown provider "${String(e.input)}"`}),label:nonEmptyString(`${n} has no usable label`),description:M.string().optional(),recommended:M.boolean().optional(),recommendationRank:M.number().optional(),profile:M.looseObject({position:M.number(),label:M.enum(Vo,{error:e=>`${n} has an unknown profile label "${String(e.input)}"`}),guidance:M.string()},{error:`profile of ${n} must be an object`}).optional(),pricing:pricingSchema(e,t),free:M.boolean().optional(),reasoningOptions:M.array(M.enum(er)).optional(),reasoningMode:M.enum(Ho).optional(),inputModalities:M.array(M.enum(Uo)).optional(),supportedParameters:M.array(M.string()).optional(),supportsTools:M.boolean().optional(),supportsStructuredOutput:M.boolean().optional(),isDefault:M.boolean().optional(),contextWindow:positiveIntegerSchema(n,`contextWindow`),maxOutputTokens:positiveIntegerSchema(n,`maxOutputTokens`),unverified:M.boolean().optional(),isCompactionModel:M.boolean().optional(),isUtilityModel:M.boolean().optional(),revealStyle:M.enum(Wo).optional(),tasks:M.partialRecord(M.enum(tr),M.enum(nr)).optional(),listPricing:M.object({inputPerMillionUsd:M.number(),outputPerMillionUsd:M.number()}).optional()}).superRefine((e,t)=>{for(let r of[`id`,`apiModelId`]){let i=e[r];i!==void 0&&i.includes(`/`)&&t.addIssue({code:`custom`,path:[r],message:i.startsWith(`${e.provider}/`)?`${n} has a ${r} that already starts with its provider "${e.provider}/"`:`${n} has a ${r} that is not bare: a text model id carries no provider, which belongs in "provider"`})}})}function imageRequestSchema(e,t){let error=n=>n.input===void 0?`image model "${e}" has no "${t}" request`:`image model "${e}" has an unusable "${t}" request`;return M.union([M.looseObject({size:M.custom(e=>Go.test(String(e)))}),M.looseObject({aspectRatio:M.custom(e=>Ko.test(String(e)))})],{error})}function catalogImageModelSchema(e){let t=`image model "${e}"`,n=`${t} has no usable formats`;return M.looseObject({id:To,name:nonEmptyString(`${t} has no usable name`),provider:nonEmptyString(`${t} has no usable provider`).regex(qo,{error:`${t} names an unusable provider`}),formats:M.array(M.enum(ni,{error:e=>`${t} declares an unknown format "${String(e.input)}"`}),{error:n}).min(1,{error:n}),requests:M.looseObject({square:imageRequestSchema(e,`square`).optional(),landscape:imageRequestSchema(e,`landscape`).optional(),portrait:imageRequestSchema(e,`portrait`).optional()},{error:`requests of ${t} must be an object`}),isDefault:M.boolean().optional()}).superRefine((e,n)=>{e.id.startsWith(`${e.provider}/`)||n.addIssue({code:`custom`,message:`${t} has an id that does not start with its provider "${e.provider}/"`})}).transform((e,n)=>{let r={...e,requests:declaredImageRequests(e)},i=imageModelFormatDefect(r);return i&&n.addIssue({code:`custom`,message:`${t} ${i}`}),r})}const Xo=M.looseObject({model:nonEmptyString(`model "embedding" has no usable model`),dimensions:positiveIntegerSchema(`embedding`,`dimensions`)},{error:`embedding must be an object`});function parseTextModel(e){let t=e,n=typeof t?.id==`string`&&t.id.length>0?t.id:void 0;return n===void 0&&refuse(`a text model has no id`),parseOrRefuse(catalogTextModelSchema(n,t?.free===!0),e)}function parseImageModel(e){let t=e,n=typeof t?.id==`string`&&t.id.length>0?t.id:void 0;return n===void 0&&refuse(`an image model has no id`),parseOrRefuse(catalogImageModelSchema(n),e)}function refuseDuplicates(e,t){let n=new Set;for(let r of e)n.has(r)&&refuse(`duplicate ${t} id "${r}"`),n.add(r)}function refuseUnlessOneDefault(e,t){let n=e.filter(e=>e.isDefault===!0).map(e=>e.id);n.length!==1&&refuse(`exactly one default ${t} is required, found ${n.length}${n.length>0?` (${n.join(`, `)})`:``}`)}function refuseBadRoleCounts(e){refuseUnlessOneDefault(e,`model`);let t=e.filter(e=>e.isUtilityModel===!0).map(e=>e.id);t.length>1&&refuse(`at most one utility model is allowed, found ${t.join(`, `)}`);let n=e.filter(e=>e.isCompactionModel===!0).map(e=>e.id);n.length>1&&refuse(`at most one compaction model is allowed, found ${n.join(`, `)}`)}function refuseUnlessRoutable(e){e.some(isRoutableModel)||refuse(`no text model carries a "tasks" entry, so none is even a candidate for Auto — ${e.length} model(s) read`)}const Zo=M.iso.datetime({offset:!0});function parseModelCatalog(e){(typeof e!=`object`||!e||Array.isArray(e))&&refuse(`payload must be an object`);let t=e;(typeof t.publishedAt!=`string`||!Zo.safeParse(t.publishedAt).success)&&refuse(`publishedAt must be an ISO 8601 string`),Array.isArray(t.text)||refuse(`text must be an array`),Array.isArray(t.image)||refuse(`image must be an array`),t.text.length===0&&refuse(`at least one text model is required`);let n=t.text.map(parseTextModel),r=t.image.map(parseImageModel);refuseDuplicates(n.map(e=>e.id),`text model`),refuseDuplicates(r.map(e=>e.id),`image model`),refuseBadRoleCounts(n),refuseUnlessRoutable(n),r.length>0&&refuseUnlessOneDefault(r,`image model`);let i=t.embedding===void 0?void 0:parseOrRefuse(Xo,t.embedding);return{...t,publishedAt:t.publishedAt,text:n,image:r,...i===void 0?{}:{embedding:i}}}function defineOperation(e){return e}function definePresentation(e,t,n){let r=t===`atomic`?`none`:t===`local`?`if-not-visible`:`follow`;return i=>{let a=n?.(i);return{impact:t,navigation:r,focus:{...e(i),...a===void 0?{}:{propertyPath:a}}}}}const K={kind:`target-missing`};var DraftRefusalError=class extends E{constructor(e,t,n=[]){super(e,n),this.refusal=t}};const Qo=[`pluralLabel`,`description`,`labelExpression`,`embeddingExpression`];function draftObjectSettings(e){return Object.fromEntries(Qo.filter(t=>e[t]!==void 0).map(t=>[t,e[t]]))}function toDraftableObject(e){return{id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},...draftObjectSettings(e)}}function toDraftableAttributes(e){let t=e.id??e.name;return(e.attributes??[]).map(e=>toDraftableAttribute(e,t))}function toAttribute(e){return{...e.config,id:e.id,objectId:e.objectId,name:e.name,label:e.label,type:e.attributeType}}function toDraftableAttribute(e,t){let{id:n,objectId:r,name:i,label:a,type:o,...s}=e;return{id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:s}}function draftedLabelExpression(e){let t=e[0];return t?`{{ ${t.name} }}`:`{{ id }}`}function draftedObjectDefinition(e,t){let n=t.filter(t=>t.objectId===e.id);return{id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},...draftObjectSettings(e),labelExpression:e.labelExpression??draftedLabelExpression(n),attributes:n.map((e,t)=>{let n=toAttribute(e);return n.order===void 0?{...n,order:t}:n})}}function toDraftableView(e,t,n=workspaceViewAuthoring(e.contents)){return structuredClone({...e,...t,authoring:n})}function draftedViewDefinition(e){let{id:t,revision:n,contentIds:r,contentRevisions:i,derived:a,authoring:o,...s}=e;return structuredClone(s)}function fromDraftableView(e,t){return{...e,...draftedViewDefinition(t)}}const $o={id:M.string().min(1).describe(`Your id, echoed back`),note:M.string().trim().min(1).max(160).optional().describe(`One first-person sentence, in the person's language: what you do and why, ≤160 chars`)},q={...$o,objectName:M.string().min(1).describe(`Object`),viewName:M.string().min(1).describe(`View API name`)},J={...q,contentName:M.string().min(1).describe(`Content API name`)},es=M.union([M.object({before:M.string().min(1).describe(`Place immediately before this content name`)}).strict(),M.object({after:M.string().min(1).describe(`Place immediately after this content name`)}).strict(),M.object({end:M.literal(!0).describe(`Place at the end of the placement zone`)}).strict()]),viewFocus=e=>({objectName:e.objectName,viewName:e.viewName}),contentFocus=e=>({...viewFocus(e),contentName:e.contentName});function invalid(e,t,n){let r=[{path:e,message:t}];throw n?new DraftRefusalError(t,n,r):new E(t,r)}function change(e,t,n,r){let i=e.views.findIndex(e=>e.object===t.objectName&&e.name===t.viewName);i<0&&invalid([`viewName`],`View is not in the draftable state`,{kind:`view-missing`,objectName:t.objectName,viewNames:e.views.filter(e=>e.object===t.objectName).map(e=>e.name)}),e.views[i].authoring||invalid([`authoring`],`Missing view authoring baseline`);let{derived:a,...o}=r(structuredClone(e.views[i]));o.contents=resolveViewContents(o.authoring);let s=e.views.map((e,t)=>t===i?o:e);return validateContentViewCatalogue({extensions:[...n.extensions],objects:e.objects.map(t=>draftedObjectDefinition(t,e.attributes.filter(e=>e.objectId===t.id))),views:s.filter(e=>!e.derived||e.contents.length>0).map(draftedViewDefinition)}),{...e,views:s}}function contentState(e,t){let n=Object.hasOwn(e.authoring.contents,t)?e.authoring.contents[t]:void 0;return n||invalid([`contentName`],`Content is not in the draftable state`,K),n}function setOrder(e,t,n){for(let r of n)e.authoring[r===`main`?`mainOrderCustomized`:`asideOrderCustomized`]=!0,t.filter(e=>e.placement===r).forEach((t,n)=>{contentState(e,t.name).workspacePosition=n})}function find(e,t){let n=e.contents.find(e=>e.name===t);return n||invalid([`contentName`],`Content is not in the draftable state`,K),n}function placed(e,t,n){let r=e.filter(e=>e.name!==t.name),i=r.filter(e=>e.placement===t.placement),a=i.length;if(!(`end`in n)){let e=`before`in n?n.before:n.after;a=i.findIndex(t=>t.name===e),a<0&&invalid([`target`],`Order target is not in this placement`),`after`in n&&a++}return i.splice(a,0,t),t.placement===`main`?[...i,...r.filter(e=>e.placement===`aside`)]:[...r.filter(e=>e.placement===`main`),...i]}const ts=M.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 M.NEVER}let r=typeof e==`object`&&e&&`name`in e?e.name:void 0;return{...n.data,name:r}}),ns=M.object({...J,type:M.literal(`replace_view_content`),definition:ts}).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}}),rs=S.describe(`The whole content definition.`),is=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:ns,wire:M.object({...J,type:M.literal(`replace_view_content`),definition:rs}).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}}))}),as=M.object({...q,type:M.literal(`add_view_content`),content:rs,target:es.describe(`Where to place the new content within its placement zone`)}).strict(),addFocus=e=>({...viewFocus(e),contentName:e.content.name}),os=defineOperation({type:`add_view_content`,summary:`Adds a content; content.name unique; the collection-view and aside rules apply; target positions it among siblings.`,schema:as,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}}})}),ss=M.object({...J,type:M.literal(`remove_view_content`)}).strict(),cs=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:ss,focus:contentFocus,presentation:definePresentation(contentFocus,`structural`),describe:e=>`Remove ${e.contentName}`,apply:(e,t,n)=>change(e,t,n,e=>({...dropViewContent(e,t.contentName),revision:e.revision+1}))});function dropViewContent(e,t){let n=find(e,t),r=contentState(e,t);if(setOrder(e,e.contents.filter(e=>e.name!==t),[n.placement]),r.sourceDefinition!==null)r.workspaceDefinition=null,r.suppressed=!0,e.contentRevisions={...e.contentRevisions,[t]:e.contentRevisions[t]+1};else{delete e.authoring.contents[t];let{[t]:n,...r}=e.contentIds,{[t]:i,...a}=e.contentRevisions;e.contentIds=r,e.contentRevisions=a}return e.contents=resolveViewContents(e.authoring),e}const ls=M.object({...J,type:M.literal(`move_view_content`),placement:M.enum([`main`,`aside`]).describe(`The placement zone to move the content into`),target:es.describe(`Where to place the content within that placement zone`)}).strict(),us=defineOperation({type:`move_view_content`,summary:`Reorders or moves a content to a different placement; the aside rule applies.`,schema:ls,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)}}})}),ds=M.object({...q,type:M.literal(`update_view_metadata`),changes:M.object({label:M.string().min(1).optional().describe(`New label for the view`),description:M.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(),fs=defineOperation({type:`update_view_metadata`,summary:`Updates a view's label, description, or icon (null clears the icon).`,schema:ds,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}})}),ps=M.string().refine(e=>e.trim().length>0,`API name must not be blank`),ms=M.object({...q,type:M.literal(`rename_view`),newName:ps.describe(`New API name for the view`)}).strict(),renameViewFocus=e=>({objectName:e.objectName,viewName:e.newName}),hs=defineOperation({type:`rename_view`,summary:`Renames a view; refused on a code-declared name — change it in the declaration.`,schema:ms,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}))}),gs=M.object({...J,type:M.literal(`rename_view_content`),newName:ps.describe(`New API name for the content`)}).strict(),renameContentFocus=e=>({...viewFocus(e),contentName:e.newName}),_s=defineOperation({type:`rename_view_content`,summary:`Renames a content; refused on a code-declared name — change it in the declaration.`,schema:gs,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}}})}),vs=M.object({...J,type:M.literal(`reset_view_content`)}).strict(),ys=defineOperation({type:`reset_view_content`,summary:`Resets a content to its code-declared source, if one exists.`,schema:vs,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}})})}),bs=M.object({...q,type:M.literal(`reset_view_order`),placement:M.enum([`main`,`aside`]).describe(`The placement zone to reset to source order`)}).strict(),xs=defineOperation({type:`reset_view_order`,summary:`Resets a placement zone's order to its code-declared source, if one exists.`,schema:bs,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}})}),Ss=M.discriminatedUnion(`type`,[ns,as,ss,ls,ds,ms,gs,vs,bs]),Y=[is,os,cs,us,fs,hs,_s,ys,xs];function findObject(e,t){return e.objects.find(e=>e.id===t)}const Cs=new Set([`formula`,`rollup`]);function isComputedAttribute(e){return Cs.has(e.attributeType)}const ws={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 ws?ws[e]:void 0}function requireObject(e,t){let n=findObject(e,t);if(!n)throw new DraftRefusalError(`Object "${t}" is not in the draftable state`,K);return n}function configOf(e){return e.config??{}}function relationTargets(e){let t=configOf(e).targets;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.object==`string`):[]}function relationTargetObjectName(e){let t=relationTargets(e).filter(e=>e.object!==`*`);return t.length===1?t[0]?.object:void 0}function toCompileAttribute(e){let t=configOf(e),n=e.attributeType,r={name:e.name,type:n,id:e.id},i=t.optionsSource;if(n===`relation`){let n=relationTargetObjectName(e);return{...r,...t.cardinality===`one`||t.cardinality===`many`?{cardinality:t.cardinality}:{},...n===void 0?{}:{targetObjectName:n},targets:relationTargets(e)}}if(n===`formula`)return{...r,...t.returnType===void 0?{}:{returnType:t.returnType},...i===void 0?{}:{optionsSource:i}};if(n===`rollup`){let e=rollupReturnTypeOf(t.function);return{...r,...e===void 0?{}:{returnType:e},...i===void 0?{}:{optionsSource:i}}}return n===`select`||n===`status`||n===`multiselect`?{...r,...Array.isArray(t.options)?{options:t.options}:{}}:r}function toCompileObject(e,t){return{objectName:e.name,attributes:t.filter(t=>t.objectId===e.id).map(toCompileAttribute)}}function computedCompileSchemaOf(e,t){return{...toCompileObject(requireObject(e,t),e.attributes),relatedObjects:Object.fromEntries(e.objects.map(t=>[t.name,toCompileObject(t,e.attributes)]))}}function toRollupAttribute(e){return{id:e.id,name:e.name,label:e.label,type:`rollup`,...configOf(e)}}function asValidationError(e){try{return e()}catch(e){throw e instanceof ComputedFormulaCompileError?new E(e.message,[]):e}}function computedPlanOf(e,t){let n=computedCompileSchemaOf(e,t.objectId);return asValidationError(()=>compilePlan(t,n))}function compilePlan(e,t){if(e.attributeType===`rollup`)return compileRollupAttribute(toRollupAttribute(e),t);let n=configOf(e);return compileComputedFormula({attributeName:e.name,expression:String(n.expression??``),returnType:n.returnType,schema:t})}function assertAcyclicComputed(e){asValidationError(()=>assertAcyclicComputedDependencies(e.map(e=>({attributeName:e.attributeName,dependencies:e.dependencies}))))}function dependencyNames(e,t){switch(e.kind){case`local`:case`computed`:return e.attributeName===t;case`relation`:return e.relationName===t;case`options`:return!1;default:return e}}function compilablePlansOf(e,t){let n=computedCompileSchemaOf(e,t),r=[];for(let i of e.attributes)if(i.objectId===t&&isComputedAttribute(i))try{r.push(compilePlan(i,n))}catch(e){if(!(e instanceof ComputedFormulaCompileError))throw e}return r}function dependentsOf(e,t,n){let r=requireObject(e,t),i=[];for(let r of compilablePlansOf(e,t))r.attributeName!==n&&r.dependencies.some(e=>dependencyNames(e,n))&&i.push(r.attributeName);for(let a of e.objects)if(a.id!==t)for(let t of compilablePlansOf(e,a.id))t.dependencies.some(t=>{if(t.kind!==`relation`||t.targetAttributeName!==n)return!1;let i=e.attributes.find(e=>e.objectId===a.id&&e.name===t.relationName&&e.attributeType===`relation`);return i!==void 0&&relationTargetObjectName(i)===r.name})&&i.push(`${a.name}.${t.attributeName}`);return i}const Ts={listed:!0,host:!0};function arrayOf(e){return Array.isArray(e)?e:[]}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rewriteAttributeNames(e,t,n){let r=!1,swap=e=>{if(typeof e!=`string`)return e;let t=n(e);return t!==e&&(r=!0),t},swapKey=e=>{if(!isRecord(e)||typeof e.attribute!=`string`)return e;let t=swap(e.attribute);return t===e.attribute?e:{...e,attribute:t}};if(e.type===`collection`&&t.listed){let t={...e};return Array.isArray(e.columns)&&(t.columns=e.columns.map(e=>typeof e==`string`?swap(e):e)),Array.isArray(e.displayAttributes)&&(t.displayAttributes=e.displayAttributes.map(swap)),Array.isArray(e.sorts)&&(t.sorts=e.sorts.map(swapKey)),typeof e.descriptionAttribute==`string`&&(t.descriptionAttribute=swap(e.descriptionAttribute)),typeof e.groupByAttribute==`string`&&(t.groupByAttribute=swap(e.groupByAttribute)),isRecord(e.columnSizing)&&(t.columnSizing=Object.fromEntries(Object.entries(e.columnSizing).map(([e,t])=>[swap(e),t]))),isRecord(e.filters)&&Array.isArray(e.filters.rules)&&(t.filters={...e.filters,rules:e.filters.rules.map(swapKey)}),r?t:e}if(e.type===`form`&&t.host){let t=arrayOf(e.groups).map(e=>isRecord(e)&&Array.isArray(e.fields)?{...e,fields:e.fields.map(swapKey)}:e);return r?{...e,groups:t}:e}if(e.type===`richtext`&&t.host){let t={...e,attribute:swap(e.attribute)};return e.titleAttribute!==void 0&&(t.titleAttribute=swap(e.titleAttribute)),r?t:e}return e}function namesIn(e,t,n){let r=!1;return rewriteAttributeNames(e,t,e=>(e===n&&(r=!0),e)),r}function namesReachedThrough(e){switch(e.type){case`collection`:return isRecord(e.source)?[e.source.relation]:[];case`documents`:return arrayOf(e.relations);case`emails`:case`meetings`:return arrayOf(e.emailAttributes);default:return[]}}function contentNamesAttribute(e,t){if(!isRecord(e)||typeof e.type!=`string`)return!1;let n=e;return namesIn(n,Ts,t)||namesReachedThrough(n).includes(t)}function listedObjectName(e,t,n){let r=collectionSourceAddressOf(n);if(r===void 0)return;if(r.kind!==`related`)return r.object;let i=hostRelation(e,t,r.relation);return i===void 0?void 0:relationTargetObjectName(i)}function hostRelation(e,t,n){let r=e.objects.find(e=>e.name===t);return e.attributes.find(e=>e.objectId===r?.id&&e.name===n&&e.attributeType===`relation`)}function partsOf(e,t,n,r){return{listed:n.type===`collection`&&listedObjectName(e,t.object,n.source)===r,host:t.object===r}}function viewNamesAttribute(e,t,n,r){return!t.derived&&Object.values(t.authoring.contents).some(i=>[i.sourceDefinition,i.workspaceDefinition].some(i=>i!==null&&namesIn(i,partsOf(e,t,i,n),r)))}function renameAttributeInView(e,t,n,r,i){if(t.derived)return t;let map=e=>e===r?i:e,rewrite=r=>r===null?null:rewriteAttributeNames(r,partsOf(e,t,r,n),map),a={...t.contentRevisions},o=!1,s=Object.fromEntries(Object.entries(t.authoring.contents).map(([e,t])=>{let n=rewrite(t.sourceDefinition),r=rewrite(t.workspaceDefinition);return n===t.sourceDefinition&&r===t.workspaceDefinition?[e,t]:(o=!0,Object.hasOwn(a,e)&&(a[e]+=1),[e,{...t,sourceDefinition:n,workspaceDefinition:r}])}));if(!o)return t;let c={...t.authoring,contents:s};return{...t,authoring:c,contents:resolveViewContents(c),revision:t.revision+1,contentRevisions:a}}function unrenamableUse(e,t,n,r){if(t.derived)return;let i=t.object===n;for(let[a,o]of Object.entries(t.authoring.contents))for(let s of[o.sourceDefinition,o.workspaceDefinition])if(s!==null&&(s.type===`collection`?reachesThrough(t.object,s,n,r)||mayList(e,t,s,n,r):i&&namesReachedThrough(s).includes(r)))return`content "${a}"`}function reachesThrough(e,t,n,r){let i=sourcedAttributeOf(e,t);return i?.object===n&&i.attribute===r}function mayList(e,t,n,r,i){if(n.type!==`collection`)return!1;let a=collectionSourceAddressOf(n.source);if(a?.kind!==`related`)return!1;let o=hostRelation(e,t.object,a.relation);return o===void 0||relationTargetObjectName(o)!==void 0?!1:relationTargets(o).some(e=>e.object===r||e.object===`*`)&&namesIn(n,{listed:!0,host:!1},i)}function refusalFor(e,t){let n=e.reason===`kanban-grouping`?`attribute "${e.attribute}" groups kanban content "${e.content}" of view "${t}"; change its grouping or remove the content first`:`removing attribute "${e.attribute}" would leave view "${t}" without a main content (content "${e.content}" is sourced on it); add another main content first`;return new E(n,[])}function draftListedObjectResolver(e){return(t,n)=>n.type===`collection`?listedObjectName(e,t.object,n.source):t.object}function cascadeAttributeRemoval(e,t){let n=e.views.filter(e=>!e.derived),r=planAttributeRemoval(n,t.map(t=>({object:requireObject(e,t.objectId).name,attribute:t.name})),draftListedObjectResolver(e)),viewOf=e=>n.find(t=>t.object===e.object&&t.name===e.view),[i]=r.blocked;if(i!==void 0)throw refusalFor(i,viewOf(i)?.id??i.view);let a=new Map,cloneOf=e=>{let t=viewOf(e);if(t===void 0)return;let n=a.get(t)??structuredClone(t);return a.set(t,n),n};for(let e of r.scrubbed){let t=cloneOf(e),n=t?.authoring.contents[e.content];t&&n&&(n.workspaceDefinition=storedContentDefinition(e.definition),Object.hasOwn(t.contentRevisions,e.content)&&(t.contentRevisions[e.content]+=1))}for(let e of r.dropped){let t=cloneOf(e);t&&dropViewContent(t,e.content)}return e.views.map(e=>{let t=a.get(e);return t===void 0?e:{...t,contents:resolveViewContents(t.authoring),revision:e.revision+1}})}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 emptyDraftViewsFor(e){let[t,n]=defaultViewsFor(e,[]),empty=e=>({...e,contents:[],authoring:workspaceViewAuthoring([]),contentIds:{},contentRevisions:{}});return[empty(t),empty(n)]}function regenerateDerived(e,t,n){return e.contents.length===0?e:derivedView(e.context,e.id,t,n)}function isGeneratedDraftRelation(e){return e.attributeType===`relation`&&toAttribute(e).metadata?.relationGenerated===!0}function pairedDraftAttributes(e,t){let n=bilateralDeclarationOf(t);if(!n)return[t];let r=e.objects.find(e=>e.id===t.objectId),i=e.objects.find(e=>e.name===n.object),a=e.attributes.find(e=>e.objectId===i?.id&&e.name===n.attribute);if(!a||a===t)return[t];let o=bilateralDeclarationOf(a);return o&&o.object===r?.name&&o.attribute===t.name?[t,a]:[t]}function reconcileDraftRelationAttribute(e,t,n,r,i=!1){let a=toAttribute(t),o=r&&toAttribute(r),s=r&&bilateralDeclarationOf(r),c=bilateralDeclarationOf(t);if(s&&(s.object!==c?.object||s.attribute!==c?.attribute))throw new E(`Changing a bilateral address requires removing the existing pair first`,[]);if(a.type!==`relation`||!a.bilateral)return e;let l=e.objects.find(e=>e.id===t.objectId),u=e.objects.find(e=>e.name===a.bilateral?.object);if(!(l&&u))throw new E(`Both objects must exist before materializing a relation pair`,[]);let d=`${l.name}.${t.name}`,f=a.bilateral.attribute,p=`${u.name}.${f}`,m=e.attributes.find(e=>e.objectId===u.id&&e.name===f),h=o?.metadata?.relationPairId,g=typeof h==`string`?h:draftEntityIdFor(`relation-pair`,`${n}:${t.id}`),_=[d,p].sort(),ee=typeof h==`string`?{id:g,addresses:_,ownerAddress:o?.type===`relation`&&o.bilateral?.storageOwner===!1?p:d,generatedAddresses:[],...d===p?{symmetric:!0}:{}}:void 0,v=reconcileRelationAttributes({objects:[...new Map([l,u].map(e=>[e.id,e])).values()].map(e=>({name:e.name,attributes:[t,...m&&m.id!==t.id?[m]:[]].filter(t=>t.objectId===e.id).map(toAttribute)})),existingPairs:ee?[ee]:[],...r&&!i?{explicitAddresses:[d],propertyEditAddresses:[d]}:{},nextPairId:()=>g}),y=new Map;for(let n of v.objects){let a=n.name===l.name?l.id:u.id;for(let o of n.attributes){let n=e.attributes.find(e=>e.objectId===a&&e.name===o.name),s=n?.id===t.id?r??n:n,c={...preserveDeclarationHints(o,n&&toAttribute(n)),metadata:{...o.metadata,...s&&isGeneratedDraftRelation(s)&&!(i&&n?.id===t.id)||!n?{relationGenerated:!0}:{}},id:n?.id??draftEntityIdFor(`relation-attribute`,`${g}:${a}:${o.name}`),...n?{}:{order:e.attributes.filter(e=>e.objectId===a).length}};y.set(`${a}.${o.name}`,toDraftableAttribute(c,a))}}let b=e.attributes.map(e=>{let t=`${e.objectId}.${e.name}`,n=y.get(t);return y.delete(t),n??e});return b.push(...y.values()),{...e,attributes:b,views:e.views.map(e=>{let t=[l,u].find(t=>t.name===e.object);return e.derived&&t?regenerateDerived(e,t,b):e})}}function preserveDeclarationHints(e,t){if(e.type!==`relation`||!e.bilateral||t?.type!==`relation`||!t.bilateral)return e;let{label:n,cardinality:r,...i}=e.bilateral;return{...e,bilateral:{...i,...t.bilateral.label===void 0?{}:{label:n},...t.bilateral.cardinality===void 0?{}:{cardinality:r}}}}function withDerivedViews(e,t,n){return{...e,attributes:[...n],views:e.views.map(e=>e.derived&&e.object===t.name?regenerateDerived(e,t,n):e)}}function objectFocus(e){return{objectId:e.objectId}}function recordFocus(e){return{objectId:e.objectId,recordId:e.recordId}}function attributeFocus(e){return{objectId:e.objectId,attributeName:e.name}}function existingAttributeFocus(e){return{objectId:e.objectId,attributeName:e.attribute}}function firstChangedProperty(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}function 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 X={...$o,objectId:M.string().uuid().describe(`The object this operation acts on`)},Es=defineOperation({type:`add_object`,summary:`Creates an object: kebab-case plural name, icon from search_icons; folds in empty default_list/default_detail views for explicit content; reserved names are native objects.`,schema:M.object({...X,objectId:M.string().uuid().describe(`Stable id for the new object; the server mints one when omitted`),type:M.literal(`add_object`),name:Jt.describe("kebab-case plural API name (`purchase-orders`)"),label:M.string().min(1).describe(`Label people see`),icon:M.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,...emptyDraftViewsFor(n)]}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Crée l'objet « ${e.label} »`}),Ds=M.object({...X,type:M.literal(`update_object`),changes:M.object({label:M.string().min(1).optional().describe(`New label`),icon:M.string().min(1).optional().describe(`New icon name from search_icons`),pluralLabel:M.string().optional().describe(`New label for many records; "" clears it`),description:M.string().optional().describe(`What this object holds`),labelExpression:F.optional().describe(`Titles every record; syntax in <expressions>`),embeddingExpression:M.literal(``).or(F).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}),Os=defineOperation({type:`update_object`,summary:`Updates an object's label, icon, pluralLabel, description, labelExpression, embeddingExpression.`,schema:Ds,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)}),ks={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])=>ks[e]?.(String(t))).filter(e=>e!==void 0);return t.length>0?t.join(` · `):`Modifie l'objet`}const As=defineOperation({type:`remove_object`,summary:`Removes an object; refused while a relation attribute targets it — remove it first.`,schema:M.object({...X,type:M.literal(`remove_object`)}),apply:(e,t)=>{requireObject(e,t.objectId);let n=e.objects.find(e=>e.id===t.objectId)?.name,r=e.attributes.filter(e=>e.objectId!==t.objectId&&e.attributeType===`relation`&&relationTargets(e).some(e=>e.object===n));if(r.length>0){let ownerOf=t=>e.objects.find(e=>e.id===t.objectId)?.name;throw new DraftRefusalError(`object "${n}" is targeted by attribute "${ownerOf(r[0])}.${r[0].name}"; remove that attribute first`,{kind:`object-targeted`,blockers:r.flatMap(e=>{let t=ownerOf(e);return t?[{ownerObjectName:t,attribute:e.name}]:[]})})}return{...e,objects:e.objects.filter(e=>e.id!==t.objectId),attributes:e.attributes.filter(e=>e.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(e=>e.objectId!==t.objectId),views:e.views.filter(e=>e.object!==n)}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Supprime l'objet ${e.objectId}`}),js=Un;function assertConfigParses(e,t){try{kt(e,t)}catch(e){throw e instanceof E?new E(e.message,e.errors.map(e=>({...e,path:[`config`,...e.path??[]]}))):e}}const Ms=M.object({...X,type:M.literal(`add_attribute`),attributeId:M.string().min(1),name:Ot,label:M.string().min(1),attributeType:M.enum(js),config:M.record(M.string(),M.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}}),Ns=Ot.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),Ps={...$o,type:M.literal(`add_attribute`),attributeId:M.string().min(1).describe(`Stable attribute id`),name:Ns,label:M.string().min(1).describe(`Label people see`)},Fs=Object.fromEntries(zt.map(e=>[e,!0])),Is=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],Ls=M.object(Is.reduce((e,t)=>(Object.assign(e,Dt(t).omit(Fs).shape),e),{})).strict(),Rs=js.filter(e=>!Is.includes(e)),zs=Object.fromEntries(Is.map(e=>[e,new Set(Object.keys(Dt(e).omit(Fs).shape))])),Bs=Rt(zs,`config key`);function refuseForeignSimpleConfigKeys(e,t){Bs(e.attributeType,e.config,t,[`config`])}function wireConfigFor(e){let t=Dt(e).omit(Fs);return(e===`relation`||e===`document`?t.extend({properties:Vt.optional()}):t).strict()}const Vs=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:Ms,wire:M.discriminatedUnion(`attributeType`,[M.object({...Ps,objectId:M.string().uuid(),attributeType:M.enum(Is).describe(`Attribute type`),config:Ls.optional().describe(`Configuration of a simple attribute (text, number, date…)`)}).strict().superRefine(refuseForeignSimpleConfigKeys),...Rs.map(e=>M.object({...Ps,objectId:M.string().uuid(),attributeType:M.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} »`}),Hs={...X,attribute:Ot.describe(`The attribute's API name on this object`)};function requireAttribute(e,t,n,r){let i=requireObject(e,t);if(n===void 0)throw new E(`${r} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let a=e.attributes.find(e=>e.objectId===t&&e.name===n);if(!a)throw new DraftRefusalError(`Attribute "${n}" is not on object "${t}"`,K);return{object:i,attribute:a}}const Us=defineOperation({type:`update_attribute`,summary:"Updates an attribute's label, or replaces its whole config. A published config can't change, except `bilateral` alone (every other key identical) to pair a published relation with its inverse; otherwise add a new attribute and migrate values.",schema:M.object({...Hs,type:M.literal(`update_attribute`),changes:M.object({label:M.string().min(1).optional().describe(`New label`),config:M.record(M.string(),M.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} »`}),Ws=defineOperation({type:`remove_attribute`,summary:`Removes an attribute and view contents sourced on it; refused on samples, formula/rollup dependents, kanban grouping or last main content.`,schema:M.object({...Hs,type:M.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]=dependentsOf(e,t.objectId,t.name);if(n!==void 0)throw new E(`attribute "${t.name}" is used by "${n}"; remove that first`,[]);let r=e.sampleRecords.find(e=>e.objectId===t.objectId&&t.name in e.values);if(r)throw new E(`Attribute "${t.name}" is still used by sample record "${r.id}"`,[])}let i=e.attributes.filter(e=>!r.includes(e)),a={...e,views:cascadeAttributeRemoval(e,r)};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} »`}),Gs=M.object({...Hs,type:M.literal(`rename_draft_attribute`),name:Ns});function assertRenamable(e,t,n){let r=n.name,[i]=dependentsOf(e,t.id,r),a=e.attributes.find(e=>{let n=e.config?.optionsSource;return n?.objectName===t.name&&n.attributeName===r}),o=i??(a&&`${e.objects.find(e=>e.id===a.objectId)?.name}.${a.name}`);if(o!==void 0)throw new E(`attribute "${r}" is used by "${o}"; it cannot be renamed while in use`,[]);let s=bilateralDeclarationOf(n),c=e.attributes.find(e=>{let n=bilateralDeclarationOf(e);return n?.object===t.name&&n.attribute===r}),l=s===void 0?c&&`${e.objects.find(e=>e.id===c.objectId)?.name}.${c.name}`:`${s.object}.${s.attribute}`;if(l!==void 0)throw new E(`attribute "${r}" is paired with "${l}"; unpair it first`,[]);let u=[[`label expression`,t.labelExpression],[`embedding expression`,t.embeddingExpression]];for(let[e,n]of u)if(n&&extractAttributeNames(n).includes(r))throw new E(`attribute "${r}" is used by the ${e} of "${t.name}"; change it first`,[]);for(let n of e.views){let i=unrenamableUse(e,n,t.name,r);if(i!==void 0)throw new E(`attribute "${r}" is used by view "${n.id}" (${i}); rename it before using it there`,[])}}const Ks=defineOperation({type:`rename_draft_attribute`,summary:`Renames a draft-added attribute; views and samples follow.`,schema:Gs,apply:(e,t)=>{let{object:n,attribute:r}=requireAttribute(e,t.objectId,t.attribute,`rename_draft_attribute`);if(t.name===r.name)throw new E(`attribute "${t.attribute}" is already named "${t.name}"`,[]);if(e.attributes.some(e=>e.objectId===t.objectId&&e.name===t.name))throw new E(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);assertRenamable(e,n,r);let i={...r,name:t.name},a=e.attributes.map(e=>e===r?i:e);return withDerivedViews({...e,views:e.views.map(r=>renameAttributeInView(e,r,n.name,t.attribute,t.name)),sampleRecords:e.sampleRecords.map(e=>{if(e.objectId!==t.objectId||!Object.hasOwn(e.values,t.attribute))return e;let n=Object.fromEntries(Object.entries(e.values).map(([e,n])=>[e===t.attribute?t.name:e,n]));return{...e,values:n}})},n,a)},focus:attributeFocus,presentation:definePresentation(attributeFocus,`local`),describe:e=>`Renomme le nom technique « ${e.attribute} » en « ${e.name} »`});function assertSampleValue(e,t,n,r){let i=toAttribute(n);try{gn(i)}catch{return}let a=vn(i,r);if(a.success)return;let o=a.errors??[],s=`Sample record "${e}" has an invalid value for "${t}": ${o.map(e=>e.path.length>1?`${e.path.join(`.`)}: ${e.message}`:e.message).join(`, `)}`,c=o.map(e=>({path:e.path,message:e.message}));throw n.attributeType===`relation`&&carriesNonRecordId(r)?new DraftRefusalError(s,{kind:`sample-relation-value`},c):new E(s,c)}function assertRequiredCovered(e,t,n){if(t.config?.required===!0&&t.config?.defaultValue===void 0&&!(t.name in n&&n[t.name]!==void 0))throw new E(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}const qs=M.guid();function carriesNonRecordId(e){let t=Array.isArray(e)?e:[e],n=relationValueIds(e);return n.length<t.length||n.some(e=>!qs.safeParse(e).success)}function relationValueIds(e){return(Array.isArray(e)?e:[e]).flatMap(e=>{if(typeof e==`string`)return[e];if(typeof e==`object`&&e){let t=e.id;if(typeof t==`string`)return[t]}return[]})}function assertUnknownSampleReference(e,t,n,r){n.attributeType===`relation`&&r!=null&&assertSampleTarget(e,t,relationTargetObjectName(n),r)}function assertSampleTarget(e,t,n,r){let i=e.objects.find(e=>e.name===n);if(!i)return;let a=e.views.some(e=>e.id===defaultViewIdsFor(i.id).list);for(let n of relationValueIds(r)){let r=e.sampleRecords.find(e=>e.id===n);if(r?.objectId!==i.id&&(r!==void 0||a))throw new DraftRefusalError(`sample record "${t}" references unknown sample "${n}"`,{kind:`sample-relation-value`})}}const Js=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:M.object({...X,type:M.literal(`add_sample_record`),recordId:M.string().uuid().describe(`Minted by the server when omitted`),values:M.record(M.string(),M.unknown()).describe("Attribute name → value; currency is `{code,value}`, relation is a record id or name minted here"),publication:M.enum([`preview`,`requested-data`]).optional().describe(`preview = display-only; requested-data = real records asked for`)}),apply:(e,t)=>{let n=requireObject(e,t.objectId);if(e.sampleRecords.some(e=>e.id===t.recordId))throw new E(`Sample record "${t.recordId}" already exists`,[]);let r=new Map(e.attributes.filter(e=>e.objectId===t.objectId).map(e=>[e.name,e]));for(let[i,a]of Object.entries(t.values)){let o=r.get(i);if(!o)throw new DraftRefusalError(`Sample record "${t.recordId}" uses unknown attribute "${i}"`,{kind:`sample-unknown-attribute`,objectName:n.name,attributeNames:[...r.keys()]});if(isComputedAttribute(o))throw new E(`attribute "${o.name}" is computed and cannot be set on a sample record`,[]);assertUnknownSampleReference(e,t.recordId,o,a),assertSampleValue(t.recordId,i,o,a)}for(let e of r.values())assertRequiredCovered(t.recordId,e,t.values);return{...e,sampleRecords:[...e.sampleRecords,{id:t.recordId,objectId:t.objectId,values:t.values,...t.publication===void 0?{}:{publication:t.publication}}]}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Ajoute un exemple`});function relationNamesOf(e,t){return new Set([...e.attributes.filter(e=>e.objectId===t&&e.attributeType===`relation`).map(e=>e.name)])}function assertSampleNotReferenced(e,t){for(let n of e.sampleRecords){if(n.id===t)continue;let r=relationNamesOf(e,n.objectId);for(let[e,i]of Object.entries(n.values))if(r.has(e)&&relationValueIds(i).includes(t))throw new E(`sample record "${t}" is referenced by sample record "${n.id}"; remove that first`,[])}}const Z=[Es,Os,As,Vs,Us,Ws,Ks,Js,defineOperation({type:`remove_sample_record`,summary:`Removes a sample record; refused while another sample references it.`,schema:M.object({...X,type:M.literal(`remove_sample_record`),recordId:M.string().min(1).describe(`recordId of the sample to remove`)}),apply:(e,t)=>{if(!e.sampleRecords.some(e=>e.id===t.recordId&&e.objectId===t.objectId))throw new DraftRefusalError(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,K);return assertSampleNotReferenced(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(e=>e.id!==t.recordId)}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Retire un exemple`})];function build(){let e=new Map;for(let t of[...Z,...Y]){if(e.has(t.type))throw new C(`architect operation`,t.type);e.set(t.type,t)}return e}const Ys=build(),Xs=[...Ys.keys()];function defOf(e){let t=Ys.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=Ys.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 Zs=`bilateral`;function frozenPart(e){if(!e||typeof e!=`object`)return A({});let{[Zs]:t,...n}=e;return A(n)}function isPublishedConfigChangeAllowed(e,t){return frozenPart(e)===frozenPart(t)}const pair=e=>M.tuple([M.literal(e),M.string()]),Qs=M.union([M.tuple([M.literal(`content`),M.string(),M.string(),M.string()]),M.tuple([M.literal(`view`),M.string(),M.string()]),M.tuple([M.literal(`attribute`),M.string(),M.string()]),M.tuple([M.literal(`sample`),M.string(),M.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 renamedFromTarget(e){return e.type!==`rename_draft_attribute`||typeof e.objectId!=`string`||typeof e.attribute!=`string`?null:{objectId:e.objectId,attributeName:e.attribute}}function renamedAttributeKey(e){let t=renamedFromTarget(e);return t===null?null:proposalTargetKey(t)}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=Ss.parse(r),t=proposalTargetKey({objectName:e.objectName,viewName:e.viewName,...e.type===`rename_view_content`?{contentName:e.contentName}:{}});t&&n.add(t)}let i=renamedAttributeKey(r);i&&n.add(i);let a=proposalTargetKey(t);if(a&&n.add(a),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 o=r.changes&&typeof r.changes==`object`?r.changes:null,s=r.type===`add_attribute`?r.config:o&&`config`in o?o.config:null;if(addBilateralDependencies(e,r,t,s,add),s&&typeof s==`object`&&`targets`in s&&Array.isArray(s.targets))for(let e of s.targets)e&&typeof e.object==`string`&&e.object!==`*`&&add(`object-name`,e.object)}return[...n]}function targetTokenOf(e){return`v2:${A(e)}`}const $s=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=Qs.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 ec={add_object:`major`,remove_object:`major`,add_view_content:`major`,replace_view_content:`major`,reset_view_content:`major`,add_attribute:`normal`,remove_attribute:`normal`,remove_view_content:`normal`,add_sample_record:`normal`,update_object:`minor`,update_attribute:`minor`,rename_draft_attribute:`minor`,update_view_metadata:`minor`,rename_view:`minor`,rename_view_content:`minor`,move_view_content:`minor`,reset_view_order:`minor`,remove_sample_record:`minor`},tc=`normal`;function operationPace(e){return Object.hasOwn(ec,e)?ec[e]:tc}const nc={major:{replay:4e3,live:2500},normal:{replay:2600,live:1800},minor:{replay:1400,live:1100}};function dwellForStep(e,t,n){let r=(nc[e]??nc[tc])[t],i=900+40*(n||0);return Math.min(6e3,Math.max(r,i))}const Q=M.string().min(1),rc=M.union([M.object({objectName:Q,viewName:Q,contentName:Q.optional()}).strict().describe(`Full configuration of a view, or of one content when contentName is given`),M.object({objectId:Q}).strict().describe(`An object with its attributes, by id`),M.object({objectName:Q}).strict().describe(`An object with its attributes`),M.object({objectId:Q,attributeName:Q}).strict().describe(`One attribute's config, by name`),M.object({objectId:Q,attributeId:Q}).strict().describe(`One attribute's config, by id`),M.object({objectId:Q,recordId:Q}).strict().describe(`One sample record`)]);function parseNamedTarget(e){let t=rc.safeParse(e);if(!t.success)throw new E(`Invalid scoped target`,[{path:[`target`],message:`Expected exactly one named target branch`}]);return t.data}const ic=M.object({type:M.literal(`remove_operation`),operationId:M.string().min(1).describe(`The id of a stored operation to drop from the draft`)}),ac=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 M.discriminatedUnion(`type`,e)}function isUuidString(e){return e instanceof M.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):M.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=M.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 oc={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of oc[e.shape.type.value]??[]){let r=e.shape[n];r instanceof M.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)}const sc=M.string().min(1).describe(`Object`);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,M.object({...n,objectName:sc}).strict())})}const cc=membersOf(Z,[ic]),lc=membersOf(Y),uc=unionOf(cc),dc=unionOf(lc),fc={schema:uc,view:dc},pc={schema:unionOf(wireMembersOf(Z,[ic])),view:unionOf(wireMembersOf(Y))},mc=new Map([...Z.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...Y.map(e=>[e.type,`view`])]);function familyOf(e){return mc.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.`);let i=viewsOf(e,t,`record`);i.length>0&&i.every(e=>e.contents.length===0)&&n.push(`Object "${t.label}" has no record 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).`)}}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 hc=[`draft_schema`],gc=`discard_architect_draft`,_c=`request_design_review`,vc=`get_architect_draft`,yc=[{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:{}}}}],$=M.string().refine(e=>e.trim().length>0,`Must not be blank`),bc=M.union([M.tuple([M.literal(`object`),$]),M.tuple([M.literal(`attribute`),$,$]),M.tuple([M.literal(`view`),$,$]),M.tuple([M.literal(`content`),$,$,$])]),xc=M.object({label:$,pluralLabel:M.string().optional(),description:M.string().optional(),icon:D.optional(),labelExpression:M.string(),embeddingExpression:M.string().optional(),sealed:M.boolean().optional(),toleratedAttributes:M.array($).optional(),metadata:M.record(M.string(),M.unknown()).optional(),documentLayout:M.record(M.string(),M.unknown()).optional()}).strict();function failure(e){throw new E(e,[])}function definitionSchema(e){return M.custom(t=>{let n=M.record(M.string(),M.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`:xc.parse(n);break;case`attribute`:{let e=M.enum(Un).parse(n.type);Pt(e).extend({type:M.literal(e),label:$,required:M.boolean().optional(),unique:M.boolean().optional(),icon:D.optional()}).strict().parse(n);break}case`view`:{let{contents:t,...r}=n,i=M.array($).parse(t);new Set(i).size!==i.length&&failure(`Invalid schema state: duplicate content membership`),ye.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=M.record(M.string(),M.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=M.object({modelVersion:M.literal(1),hashVersion:M.literal(1),tenant:$,sourceFingerprint:M.string().regex(/^[a-f0-9]{64}$/),entries:M.array(M.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=bc.parse(M.object({address:M.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`?M.object({id:M.string().uuid(),updatedAt:M.string().datetime()}).strict():M.object({id:M.string().uuid(),revision:M.number().int().nonnegative()}).strict(),o=M.object({address:bc,source:i,effective:i,status:M.enum([`source`,`runtime`,`copy`,`suppressed`]),sourceOwner:M.union([M.literal(`core`),M.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 M.ZodError?E.fromZodErrors(e.issues.map(e=>({path:e.path.map(String),message:e.message}))):e}}function diffSchemaState(e){let t=[];for(let n of[...e.entries].sort(compareSchemaStateEntries)){let e=n.source===null?`added`:n.status===`suppressed`?`suppressed`:n.effective===null?`removed`:A(n.source)===A(n.effective)?n.status===`copy`?`copied`:null:`changed`;e&&t.push({...n,change:e})}return{modelVersion:1,tenant:e.tenant,sourceFingerprint:e.sourceFingerprint,changes:t}}export{$s as ABSENT_TARGET_TOKEN,ur as AGENT_MESSAGE_KIND,lr as AGENT_NOTIFICATION_KIND,tr as AGENT_TASK_KINDS,ba as AGENT_UI_BATCH_MAX_BYTES,xa as AGENT_UI_BATCH_MAX_ITEMS,ci as ALLOWED_PROPERTY_TYPES,qr as ALL_ACTIONS,Xs as ALL_OPERATION_TYPES,hi as ALL_PIPES,Si as ALL_SYSTEM_RESOURCES,Ur as ARTIFACT_FILE_ROLES,Vr as ARTIFACT_KINDS,$i as ARTIFACT_LIST_VIEW,Zi as ARTIFACT_OBJECT,B as ARTIFACT_OBJECT_NAME,Xi as ARTIFACT_PREVIEW_EXTENSION,Hr as ARTIFACT_RETENTIONS,Qi as ARTIFACT_VIEW,je as ATTRIBUTE_FILTER_OPERATORS,Un as ATTRIBUTE_TYPES,Kn as AUDIT_ACTIONS,qn as AUDIT_AGENT_SESSION_METADATA_KEY,Gn as AUDIT_RESOURCE_TYPES,Me as AccessDeniedError,AgentBuilder,Ne as AmbiguousSchemaChangeError,Pe as AttributeInUseError,Fe as AttributeNotFoundError,Vn as BEHAVIOR_PROPERTIES,oi as BYTE_UNIT_LABELS,Yn as CLAIMABLE_SESSION_STATUSES,La as COMPUTED_FUNCTIONS,Ra as COMPUTED_FUNCTION_METADATA,Ia as COMPUTED_FUNCTION_NAMES,Ga as CONNECTOR_CALLBACK_PARAM,ri as COUNT_MODES,ComputedFormulaCompileError,Kt as ComputedFormulaParseError,Ie as ConcurrentModificationError,L as ContentBuilder,xi as DB_COLUMN_FIELDS,ji as DEFAULT_AGENT_EXECUTION_CONFIG,Xn as DEFAULT_APPROVAL_POLICY,Dr as DEFAULT_DICTATION_LIMITS,gi as DEFAULT_LABEL_FALLBACK,Jr as DEFAULT_MEETING_BOT_DISPLAY_NAME,wi as DEFAULT_ROLES,Ei as DEFAULT_ROLE_DESCRIPTIONS,Ti as DEFAULT_ROLE_LABELS,Ai as DEFAULT_ROLE_PERMISSIONS,Yr as DEFAULT_TENANT_SETTINGS,$t as DEFAULT_VALIDATION_MESSAGES,Ar as DEVICE_CHANNEL_AUTHENTICATE_TIMEOUT_MS,jr as DEVICE_CHANNEL_IDLE_POLL_MS,Nr as DEVICE_CHANNEL_KEEPALIVE_MS,kr as DEVICE_CHANNEL_MAX_FRAME_BYTES,Or as DEVICE_CHANNEL_PATH,Mr as DEVICE_CHANNEL_PRESENCE_MS,Pr as DEVICE_CHANNEL_WORKER_CLOSE_PROTOCOL_VIOLATION,Ir as DEVICE_COMMAND_ERROR_CODES,Tr as DICTATION_FINALIZATION_TIMEOUT_MS,yr as DICTATION_FRAME_BYTES,xr as DICTATION_MAX_BUFFER_BYTES,br as DICTATION_MAX_FRAME_BYTES,Sr as DICTATION_MAX_TRANSCRIPT_BYTES,Er as DICTATION_MODEL_ID,wr as DICTATION_PREPARATION_TIMEOUT_MS,vr as DICTATION_SAMPLE_RATE,Cr as DICTATION_TICKET_TTL_MS,gc as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,si as DOCUMENT_SYSTEM_ATTRIBUTES,js as DRAFTABLE_ATTRIBUTE_TYPES,ac as DRAFT_BATCH_LIMIT,Qo as DRAFT_OBJECT_SETTINGS,yc as DRAFT_SCHEMA_INPUT_EXAMPLES,hc as DRAFT_WRITE_TOOL_NAMES,Yi as DRIVE_LIST_VIEW,qi as DRIVE_OBJECT,z as DRIVE_OBJECT_NAME,Ji as DRIVE_VIEW,DeviceChannelProtocolError,Br as DeviceChannelServerFrameSchema,zr as DeviceChannelWorkerFrameSchema,DraftRefusalError,C as DuplicateError,fi as EMPTY_VALUE_PLACEHOLDER,ii as ESTIMATED_COUNT_CAP,$a as FAKE_MEETING_BOT_SIGNATURE_HEADER,fc as FAMILY_INPUTS,pc as FAMILY_WIRE_INPUTS,Kr as FORM_FORBIDDEN_ATTRIBUTE_TYPES,FlagRegistry,FlagService,Le as ForbiddenError,FormBuilder,FormRegistry,FormRowBuilder,FormStepBuilder,vc as GET_ARCHITECT_DRAFT_TOOL_NAME,Pi as GroupBuilder,Bn as IDENTITY_PROPERTIES,ni as IMAGE_FORMATS,er as INFERENCE_REASONING_OPTIONS,rr as INFERENCE_ROUTING_MODES,$n as INFERENCE_SPEEDS,la as INVENTORY_LIMIT,yt as LIST_VIEW_TAB_VISIBILITIES,Sa as LIVE_EVENT_TYPES,n as LOCATION_FILTER_PROPERTIES,qa as MAILBOX_LIST_MODES,Ya as MAIL_DRAFT_BODY_MAX_CHARS,Xa as MAIL_SUBJECT_MAX_CHARS,Wr as MAX_PRESET_DEPTH,fr as MAX_TODOS,mr as MAX_TODO_DESCRIPTION_CHARS,pr as MAX_TODO_ID_CHARS,H as MEETING_ATTRIBUTES,na as MEETING_DETAIL_VIEW_ID,oa as MEETING_LIST_VIEW,ea as MEETING_LIST_VIEW_ID,ia as MEETING_OBJECT,V as MEETING_OBJECT_NAME,aa as MEETING_VIEW,ta as MEETING_WRITE_SOURCE,Ki as MEMORY_LIST_VIEW,Ui as MEMORY_OBJECT,Gi as MEMORY_VIEW,Ka as McpOAuthCompletionMode,Re as MemoryNotFoundError,MultiRelationAttributeBuilder,gr as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,_r as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,Ct as NATIVE_OBJECT_NAMES,Pn as NOTIFICATION_INBOX_STATES,jn as NOTIFICATION_KINDS,Mn as NOTIFICATION_PRIORITIES,Nn as NOTIFICATION_SENSITIVITIES,zn as NOTIFICATION_TYPES_V1,Rn as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,In as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,Ln as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,Fn as NOTIFICATION_WORK_STATES,eo as NO_RECORDING,g as NO_VALUE_OPERATORS,un as NonJsonValueError,NoopGeocodingAdapter,ze as NotFoundError,Be as NotImplementedError,Jt as OBJECT_NAME_SCHEMA,sr as OPEN_TOOL_PART_STATES,ec as OPERATION_PACE,Ys as OPERATION_REGISTRY,o as OPERATORS_BY_TYPE,U as OPERATOR_SPECS,ObjectBuilder,Ve as ObjectNotFoundError,He as ObjectReferencedError,Ue as OrphanSystemAttributeError,nc as PACE_DWELL_MS,mi as PIPES_WITH_ARGS,Hn as PRESENTATION_PROPERTIES,Qn as PROVIDER_NAMES,Zs as PUBLISHED_CONFIG_EXCEPTION,We as ProtectedResourceError,Ge as ProtectedRoleError,li as QUALIFIED_SEPARATOR,ai as QUOTA_KEYS,Gr as RECENT_ACTIVITY_LEDGER_LIMIT,Za as RECORDING_OVERRIDES,Qa as RECORDING_POLICIES,bi as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,Wn as RELATION_TARGET_ANY,le as REMOVED_OPERATOR_REPLACEMENTS,ic as REMOVE_OPERATION_SCHEMA,Ja as REPLY_MODES,_c as REQUEST_DESIGN_REVIEW_TOOL_NAME,bt as RESERVED_ATTRIBUTE_NAMES,St as RESERVED_OBJECT_NAMES,gt as RESOURCE_VISIBILITIES,ir as ROUTING_PRICE_CEILINGS,Ke as RealtimeDeliveryError,qe as RealtimeRateLimitedError,Je as RealtimeSubscriptionError,Ye as RecordNotFoundError,Xe as RecordReferencedError,Ze as RepositoryError,Qe as ReservedObjectNameError,$e as RoleNotFoundError,Ft as SCHEMA_LIMITS,Z as SCHEMA_OPERATIONS,uc as SCHEMA_OPERATION_INPUT,W as SCHEMA_PLAN_LIMITS,no as SCHEMA_SOURCE_ID_PATTERN,ar as SESSION_INFERENCE_PATCH_KEYS,hr as SESSION_STATE_STREAM_ID,Jn as SESSION_TERMINAL_STATUSES,pi as SIMPLE_PIPES,Wt as SIMPLE_PROPERTY_TYPES,zi as SKILL_CONTENT_TEMPLATE,Hi as SKILL_LIST_VIEW,Bi as SKILL_OBJECT,Vi as SKILL_VIEW,Mi as STANDARD_SCHEMA_VENDOR,Ae as SYNONYM_ALIASES,ie as SYSTEM_ATTRIBUTES,_ as SYSTEM_ATTRIBUTE_I18N_KEYS,_t as SYSTEM_FIELD_NAMES,de as SYSTEM_FILTER_ATTRIBUTE_TYPES,cr as SYSTEM_PART_CODES,I as SYSTEM_RESOURCES,Ci as SYSTEM_RESOURCE_LABELS,w as SchemaError,T as SchemaErrorCode,et as SchemaPlanNotFoundError,tt as SearchBackendError,SingleRelationAttributeBuilder,nt as StorageError,rt as SyncCascadeError,it as SyncConflictError,at as SyncError,ot as SystemEntityImmutableError,nr as TASK_DEMAND_LEVELS,Xr as TENANT_INVITATION_DEFAULT_TTL_MS,Qr as TENANT_INVITATION_MAX_TTL_MS,Zr as TENANT_INVITATION_MIN_TTL_MS,$r as TENANT_INVITATION_RESEND_INTERVAL_MS,Xt as TEXT_FORMAT_PATTERNS,Wa as TODAY_DEFAULT,Zn as TODO_PLAN_STATUSES,dr as TODO_STATUSES,or as TOOL_APPROVAL_STATES,ei as USER_STATUSES,ti as USER_WORK_POSTURES,Y as VIEW_OPERATIONS,dc as VIEW_OPERATION_INPUT,E as ValidationError,Ni as ViewBuilder,zt as WIRE_OMITTED_CONFIG_KEYS,accessLevelToActions,actionsToAccessLevel,agent,agentDataChunk,agentDisplayName,wo as agentInferencePreferencesSchema,Mo as agentMessageAttachmentSchema,jo as agentMessagePartSchema,Eo as agentSessionInferenceOverridesInputSchema,Do as agentSessionInferenceOverridesSchema,Lo as agentSessionMessageSchema,agentUIValidationError,applyOperations,applyPipes,applyRelationProps,architectContentBodyKey,architectDraftChannelKey,architectFocusCandidates,architectFocusKey,No as artifactQuoteSchema,fn as asTenantId,ln as asUserId,assertAcyclicComputed,assertAcyclicComputedDependencies,assertBilateralPairs,assertCustomAgentUIMessageChunk,assertSchemaSourceId,Ht as attributeConfigSchemas,attributeInventory,bilateralDeclarationOf,booleanFlag,buildAgentFallbackTitle,buildPermissionFlags,buildPropertySchema,buildQualifiedAttribute,A as canonicalStringify,Ss as canonicalViewOperationSchema,v as canonicalizeFilterValue,capped,Xo as catalogEmbeddingSchema,catalogImageModelSchema,catalogTextModelSchema,checkbox,cleanContent,collectContentViewCatalogue,be as collectQualifiedRuleIssues,collectSchemaReferences,we as collectionContentSourceSchema,collectionContentsOf,collectionSourceAddress,collectionSourceAddressOf,It as colorIdSchema,ve as columnsSchema,compareAgentSessionMessages,compareSchemaStateEntries,compilablePlansOf,compileComputedFormula,compileRollupAttribute,computeByteMagnitude,computeReconnectDelay,computeRetryDelay,computedCompileSchemaOf,computedPlanOf,R as content,contentDefinition,da as contentExtensionRegistry,contentNamesAttribute,Se as contentViewDefinitionSchema,me as contentViewDefinitionSchemaFor,conversationDisplayTitle,nn as createCheckboxValidator,rn as createDateValidator,createFlagRegistry,createFlagService,_n as createFormAttributeValidator,tn as createNumberValidator,createStandardSchemaProps,Qt as createTextValidator,currency,ge as currentActor,Bo as customDataChunkSchemas,date,dateInTimezone,dateValueStart,declaredImageRequests,decodeDeploymentBarrierAttestationV1,dn as deepEqual,defaultViewIdsFor,defaultViewsFor,defineDeviceChannelFrames,defineOperation,definePresentation,dependentsOf,deriveArchitectChanges,deriveCreateDefaultsFromFilters,deriveInitials,describeOperations,uo as destructiveSchema,detailView,deviceChannelUrl,diffSchemaState,oe as displayAttributesSchema,document,ye as draftContentViewDefinitionSchema,Ce as draftContentViewDefinitionSchemaFor,draftListedObjectResolver,draftObjectSettings,draftedLabelExpression,draftedObjectDefinition,draftedViewDefinition,Io as durableDateSchema,dwellForStep,episodeImpactOf,evaluateComputedAst,evaluateComputedFormula,evaluateComputedFormulaWithResult,evaluateFilterState,evaluateRecordFilterState,extractAttributeNames,i as extractCurrencyFilterValue,h as extractFilterValue,extractValueRefs,familyOf,l as filterOperatorsByTypeForGeneration,ce as filterStateSchema,findRelationAttribute,Fi as flagRegistry,focusOf,form,formFieldFlatKey,formFieldKey,fa as formRegistry,formatAgentStreamFrameId,formatAttributeValue,formatByteSize,formatComputedResult,formatLocationValue,en as formatZodErrors,formula,fromDraftableView,sn as generateId,x as getAttributeCapabilities,c as getAttributeFilterOperators,getEditableLabelAttribute,getErrorMessage,getLiveProtocolPayloadChannel,r as getOperatorPolarity,getRecordCreatorPrincipalId,f as getRollupFilterOperators,getSingleAttributeFromExpression,getSlotFieldTargets,e as getSystemAttributeI18nKey,ue as getSystemAttributeList,getUserDisplayName,group,guidanceForBatch,hasDestructiveEntries,hasOptions,D as iconNameSchema,imageModelFormatDefect,To as imageModelIdSchema,includesAction,an as indexBy,inferInverseCardinality,inferRollupReturnType,xo as inferenceReasoningSchema,So as inferenceRoutingSchema,bo as inferenceSpeedSchema,isAgentMessageMetadata,isAgentNotificationMetadata,isAgentUIDataName,isAgentUIMessageBatch,isAgentWrittenAuditEntry,b as isAttributeFilterable,te as isAttributeGroupable,st as isAttributeInUseError,s as isAttributeKanbanGroupable,d as isAttributeSearchable,isAttributeSortable,isBilateralRelation,m as isCalendarDay,isCheckboxEquality,isClaimableSessionStatus,isComputedAttribute,isComputedFunctionName,isCurrentTargetToken,isDateRangeValue,isDefaultRole,isDocumentAttribute,t as isDynamicValue,isEdgePayload,isEmptyObject,isFormDefinition,isFormFieldsRow,isFormFreeFieldRef,isFormHeadingRow,isFormSeparatorRow,isFormSlotFieldRef,isFormTextRow,isLabelExpression,isLiveEventEnvelope,isLiveEventPayload,isLiveEventPayloadForType,isLiveEventType,u as isLocationFilterProperty,re as isLocationPartOperator,isMailProvider,isMailboxListMode,Te as isManagedSystemAttribute,Yt as isNativeObjectName,ee as isNoValueOperator,isNotEmpty,ct as isNotFoundError,j as isNullishOrEmptyString,lt as isObjectReferencedError,isOpenToolPartState,isPlainRecord,ut as isProtectedResourceError,isPublishedConfigChangeAllowed,dt as isRecordReferencedError,pe as isRelativeDateValue,isReplyMode,isRoutableModel,ft as isSchemaError,Oe as isSetMembershipOperator,isStandardSchema,isSystemPartCode,isTerminalSessionStatus,isTerminalState,isToolApprovalState,isUnderRoutingCeiling,isUniversalRelation,pt as isValidationError,yn as isValuePresent,jsonFlag,legacyStatusToSessionState,listView,listedObjectWithoutCatalogue,liveChannelKey,location,markdownToPlainText,matchesAccepts,Po as mentionReferenceSchema,Fo as modelDefinitionSchema,Co as modelReferenceSchema,multiselect,Bt as multiselectOptionWriteSchema,rc as namedTargetSchema,nativeAgentUIPartIdMetadataKey,ya as nonOperationalDeploymentBarrierAttestorV1,normalizeDateValue,se as normalizeFilterRule,y as normalizeForEdgeRpc,ke as normalizeOperator,normalizePricing,he as now,number,numberFlag,object,operationPace,orderAgentSessionMessages,parseAgentStreamFrameId,Ut as parseAttributeConfig,kt as parseAttributeConfigForCreate,Lt as parseAttributeConfigForUpdate,k as parseComputedFormula,parseCountMode,parseDeviceChannelFrame,parseFilterInstant,parseLiveChannelKey,parseModelCatalog,parseNamedTarget,parseNativeAgentUIPartIdsMetadata,parseOperation,parseOptionalCountMode,parseQualifiedAttribute,vt as parseResourceVisibility,parseSchemaGroupPresentation,parseSchemaState,parseServerFrame,parseWorkerFrame,_o as persistedSchemaPlanSchema,phone,planAttributeRemoval,so as plannedAttributeSchema,co as plannedInlineAttributeSchema,lo as plannedObjectSchema,presentationOf,pricePerMillion,Gt as propertyAttributeSchema,At as propertyAttributeWireSchema,jt as propertySchemaSchema,Vt as propertySchemaWireSchema,proposalTargetKey,yo as providerNameSchema,S as publishedViewContentDefinitionSchema,qualifiedPropertyDefs,readFormFieldValue,recentActivityEntryKey,reconcileRelationAttributes,Rt as refuseForeignKeys,regenerateDerived,Li as registry,xn as rejectUnknownAttributesOrThrow,relation,relationAcceptsObject,relationProperty,relationPropertyDefs,relationTargetObjectName,relationTargets,relationTargetsOf,relationValueIds,renamedFromTarget,renderLabelExpression,requestedCapabilities,requireRecordContentContext,requireSingleRelationTarget,requiredTargetKeys,resolveAttributeDefaultValue,resolveCollectionActions,resolveContentNavigation,ne as resolveEffectiveFilterType,resolveFieldRequired,fe as resolveIsWithinBounds,resolvePropertyDefinitions,Zt as resolveTextPattern,ae as resolveUtcDayBounds,resolveViewContents,richtext,rollup,rollupToFormulaExpression,ko as routedMessageInferenceSchema,routingPrice,on as sameStableValue,schemaGroupKey,ho as schemaPlanSchema,schemaStateSourcePayload,select,Nt as selectOptionWriteSchema,cn as serializeCanonicalJson,pn as serializeStableJson,Oo as sessionInferencePatchSchema,sessionStateToLegacyStatus,singleRelationTarget,Ee as sortsSchema,status,Mt as statusGroupSchema,Et as statusOptionWriteSchema,stillMissing,storedContentDefinition,stringFlag,summarizeDraft,targetSnapshot,targetTokenOf,targetTokensFor,text,toAttribute,toDraftableAttribute,toDraftableAttributes,toDraftableObject,toDraftableView,a as toMultiValueOperator,toUndefinedIfEmpty,De as toUtcDayString,p as today,Ro as todoItemSchema,zo as todoPlanSchema,Ao as toolImpactSchema,touchedObjectIds,user,mt as validateAttributeName,validateContentViewCatalogue,mn as validateDraft,bn as validateDraftOrThrow,validateLabelExpression,Sn as validateObject,validateObjectExpressions,ht as validateObjectName,hn as validateObjectOrThrow,_e as validateQualifiedRule,validateStoredViews,xt as validateViewName,verifyDeploymentBarrierAttestationV1,viewIdFor,viewIdentityKey,viewNamesAttribute,sa as viewRegistry,workspaceViewAuthoring};
|
|
43
|
+
{{ summary }}`).attribute(text({name:W.title,label:`Title`}).required()).attribute(richtext({name:W.description,label:`Description`})).attribute(richtext({name:W.summary,label:`Summary`}).hidden()).attribute(richtext({name:W.transcript,label:`Transcript`}).hidden()).attribute(text({name:W.location,label:`Location`})).attribute(date({name:W.startsAt,label:`Starts at`}).includeTime()).attribute(date({name:W.endsAt,label:`Ends at`}).includeTime()).attribute(checkbox({name:W.isAllDay,label:`All day`})).attribute(select({name:W.status,label:`Status`}).options([{value:`confirmed`,label:`Confirmed`},{value:`tentative`,label:`Tentative`},{value:`cancelled`,label:`Cancelled`}])).attribute(text({name:W.organizerAddress,label:`Organizer address`}).email()).attribute(text({name:W.organizerName,label:`Organizer`})).attribute(text({name:W.conferenceProvider,label:`Conference provider`})).attribute(text({name:W.conferenceJoinUrl,label:`Join link`}).url()).attribute(text({name:W.htmlLink,label:`Open in calendar`}).url()).attribute(text({name:W.participants,label:`Participants`}).multiline()).attribute(text({name:W.providerEventId,label:`Provider event id`}).hidden()).attribute(text({name:W.icalUid,label:`iCal UID`}).hidden()).attribute(text({name:W.recurringEventId,label:`Recurring event id`}).hidden()).attribute(text({name:W.connectionId,label:`Connection id`})).attribute(select({name:W.recordingOverride,label:`Recording`}).options([{value:`force`,label:`Force`},{value:`skip`,label:`Skip`}]).hidden()).attribute(date({name:W.endedAnnouncedAt,label:`Ended announced at`}).includeTime().hidden()).attribute(relation({name:W.linkedRecords,label:`Linked records`}).toAny().many().qualifyWith(text({name:`source`,label:`Source`}).hidden())).build(),Va=markSystemView(detailView(Ra,`Meeting`).for(U).default().tab(`description`,`Description`,B.richtext(W.description).titleAttribute(W.title)).tab(`summary`,`Summary`,B.richtext(W.summary)).tab(`transcript`,`Transcript`,B.richtext(W.transcript)).aside(`details`,`Details`,B.form(group(`details`,`Details`).fields(W.startsAt,W.endsAt))).build()),Ha=markSystemView(listView(Ia,`Meetings`).for(U).default().tab(`workspace`,`Shared`,B.collection().object(U).table().icon(`users`).visibility(`workspace`).columns(...za).sort(W.startsAt,`desc`)).tab(`mine`,`My meetings`,B.collection().object(U).table().icon(`lock`).visibility(`private`).columns(...za).sort(W.startsAt,`desc`)).build());function viewIdentityKey(e,t){return JSON.stringify([e,t])}function cloneDeclaration(e){return structuredClone(e)}var ViewRegistry=class{constructor(){this.views=new Map,this.systemNames=new Map}register(e){let t=(Array.isArray(e)?e:[e]).map((e,t)=>this.prepare(e,t)),n=new Map,r=new Set;for(let{declaration:e}of t){let{object:t,name:i,context:a,default:o}=e.definition,s=n.get(t)??new Set;if((this.views.get(t)?.has(i)||s.has(i))&&this.throwDuplicate(t,i),s.add(i),n.set(t,s),!o)continue;let c=JSON.stringify([t,a]);if(this.getByObjectNameAndContext(t,a).some(e=>e.definition.default)||r.has(c))throw new w(`default view`,c,`[ViewRegistry] Duplicate default view for object "${t}" in context "${a}"`);r.add(c)}for(let e of t)this.commit(e);return this}prepare(e,t){if(typeof e!=`object`||!e||e.kind!==`view`||Object.keys(e).some(e=>e!==`kind`&&e!==`definition`)){let e=`Expected an exact view declaration`;throw new D(e,[{path:[`views`,String(t)],message:e}])}let n=xe.safeParse(e.definition);if(!n.success)throw D.fromZodErrors(n.error.issues.map(e=>({path:[`views`,String(t),`definition`,...e.path.map(String)],message:e.message})));return{declaration:cloneDeclaration(e),system:isSystemViewDefinition(e.definition)}}commit({declaration:e,system:t}){let{object:n,name:r}=e.definition,i=this.views.get(n)??new Map;if(i.set(r,e),this.views.set(n,i),t){let e=this.systemNames.get(n)??new Set;e.add(r),this.systemNames.set(n,e)}}getByObjectName(e){return Array.from(this.views.get(e)?.values()??[],cloneDeclaration)}getByObjectNameAndContext(e,t){return this.getByObjectName(e).filter(e=>e.definition.context===t)}get(e,t){let n=this.views.get(e)?.get(t);return n&&cloneDeclaration(n)}getOrThrow(e,t){let n=this.get(e,t);if(n)return n;let r=this.getByObjectName(e).map(({definition:e})=>`${e.name} (${e.context})`).join(`, `)||`(none)`;throw new ze(`View`,`${e}:${t}`,void 0,`[ViewRegistry] View "${t}" not found for object "${e}".\nAvailable views: ${r}`)}getAll(){return Array.from(this.views.values()).flatMap(e=>Array.from(e.values(),cloneDeclaration))}has(e,t){return this.views.get(e)?.has(t)??!1}hasObject(e){return this.views.has(e)}get size(){let e=0;for(let t of this.views.values())e+=t.size;return e}listObjectNames(){return Array.from(this.views.keys())}getDefault(e,t){let n=this.getByObjectNameAndContext(e,t);return n.find(e=>e.definition.default)??n[0]}isSystem(e,t){return this.systemNames.get(e)?.has(t)??!1}isSystemDeclaration(e){return this.isSystem(e.definition.object,e.definition.name)}clear(){this.views.clear(),this.systemNames.clear()}summary(){let e=[`[ViewRegistry] ${this.size} view(s) registered:`];for(let t of this.listObjectNames()){let n=this.getByObjectName(t).map(({definition:e})=>{let t=e.default?` (default)`:``;return`${e.name}:${e.context}${t}`});e.push(` ${t}: ${n.join(`, `)}`)}return e.join(`
|
|
44
|
+
`)}debug(e){let t=this.summary();return e?.(t),t}throwDuplicate(e,t){let n=viewIdentityKey(e,t);throw new w(`view`,n,`[ViewRegistry] Duplicate view: "${t}" for object "${e}"`)}};const Ua=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 singleRelationTarget(e){let[t,...n]=e.targets;return t&&n.length===0&&t.object!==`*`?t.object:void 0}function requireSingleRelationTarget(e,t=[e.name,`targets`]){let n=singleRelationTarget(e);if(n===void 0){let n=`Relation "${e.name}" requires one concrete collection target`;throw new D(n,[{path:t,message:n}])}return n}function violationOf(e,t,n,r){if(!(e instanceof T))throw e;let i=e instanceof D?e.errors[0]:void 0;return{key:JSON.stringify([t,n,e.code,e.message]),contentName:n,path:i?.path??r,message:e.message,code:e.code,error:e}}const Wa=new Map(le().map(e=>[e.name,e]));function reject$2(e,t){throw new D(t,[{path:e,message:t}])}function requireName(e,t){e.trim().length===0&&reject$2(t,`API name must not be empty`)}function indexUnique(e,t,n){let r=new Map;return e.forEach((e,i)=>{if(requireName(e.name,[...n,String(i),`name`]),r.has(e.name))throw new w(t,e.name);r.set(e.name,e)}),r}const Ga=30;function capped(e,t){let n=e.slice(0,t).join(`, `);return e.length>t?`${n} … and ${e.length-t} more`:n}function attributeInventory(e,t){return t.length===0?`Object "${e}" has no attributes yet.`:`Attributes of "${e}": ${capped(t,30)}`}function requireAttribute$1(e,t,n,r,i){if(requireName(t,n),!e)return;let a=e.attributes?.get(t)??Wa.get(t);if(!a){if(!e.attributes)return;let r=attributeInventory(e.name,[...e.attributes.keys()]);reject$2(n,`Unknown attribute "${e.name}.${t}". ${r}${i?.()??``}`)}return r&&a.type!==r&&reject$2(n,`Attribute "${e.name}.${t}" must have type ${r}`),a}function collectContentViewCatalogue(e){let t=e.mode??`published`,n=new Map;e.objects.forEach((e,t)=>{if(requireName(e.name,[`objects`,String(t),`name`]),n.has(e.name))throw new w(`object`,e.name);n.set(e.name,{name:e.name,attributes:indexUnique(e.attributes,`attribute`,[`objects`,String(t),`attributes`])})});let r=new Set;(e.reservedObjects??[]).forEach((e,i)=>{let a=[`reservedObjects`,String(i)];requireName(e,a),!n.has(e)&&(t!==`draft`&&reject$2(a,`Unresolved reserved object "${e}"`),r.add(e),n.set(e,{name:e}))});let i=indexUnique(e.extensions??[],`extension`,[`extensions`]);function resolveObject(e,t){requireName(e,t);let r=n.get(e);return r||reject$2(t,`Unknown object "${e}"`),r}function inverseAddresses(e){let t=[];for(let[r,i]of n)if(r!==e)for(let n of i.attributes?.values()??[])n.type===`relation`&&relationAcceptsObject(n,e)&&t.push(`relatedFrom("${r}", "${n.name}")`);return t.sort().slice(0,3)}let a=t===`draft`?Se():pe(),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}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[0];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 Ka=[Object.freeze(Ma)];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 Ka)this.extensions.set(e.name,e)}};const qa=new ContentExtensionRegistry;function cleanContent(e,t){let n=structuredClone(e),r=new Set(t.map(e=>JSON.stringify(e.path))),remove=(...e)=>r.has(JSON.stringify(e));switch(n.type){case`form`:return n.groups.forEach((e,t)=>{e.fields=e.fields.filter((e,n)=>!remove(`groups`,String(t),`fields`,String(n),`attribute`))}),n;case`collection`:{if(n.columns&&=n.columns.filter((e,t)=>!remove(`columns`,String(t))),n.displayAttributes&&=n.displayAttributes.filter((e,t)=>!remove(`displayAttributes`,String(t))),n.layout!==`kanban`&&n.columnSizing)for(let e of Object.keys(n.columnSizing))remove(`columnSizing`,e)&&delete n.columnSizing[e];let e=n.filters?.rules.filter((e,t)=>!remove(`filters`,`rules`,String(t),`attribute`)),t=n.sorts?.filter((e,t)=>!remove(`sorts`,String(t),`attribute`)),emptied=(e,t)=>e!==void 0&&e.length===0&&t!==void 0&&t.length>0,{filters:r,sorts:i,descriptionAttribute:a,...o}=n;return{...o,...n.filters&&e&&!emptied(e,n.filters.rules)?{filters:{...n.filters,rules:e}}:{},...t&&!emptied(t,n.sorts)?{sorts:t}:{},...a===void 0||remove(`descriptionAttribute`)?{}:{descriptionAttribute:a}}}case`richtext`:if(remove(`titleAttribute`)){let{titleAttribute:e,...t}=n;return t}return n;case`activity`:case`custom`:case`documents`:case`forms`:case`emails`:case`meetings`:return n;default:throw new D(`Unsupported content ${String(n)}`,[])}}function listedObjectWithoutCatalogue(e,t){if(t.type!==`collection`)return e.object;let n=collectionSourceAddressOf(t.source);return n===void 0||n.kind===`related`?void 0:n.object}function namedBy(e){return t=>typeof t==`string`&&!t.includes(`.`)&&e.has(t)}function scrubPathsFor(e,t){let n=[],r=namedBy(t);switch(e.type){case`form`:return e.groups.forEach((e,t)=>e.fields.forEach((e,i)=>{r(e.attribute)&&n.push([`groups`,String(t),`fields`,String(i),`attribute`])})),n;case`collection`:if(e.columns?.forEach((e,t)=>{r(e)&&n.push([`columns`,String(t)])}),e.displayAttributes?.forEach((e,t)=>{r(e)&&n.push([`displayAttributes`,String(t)])}),e.layout!==`kanban`&&e.columnSizing)for(let t of Object.keys(e.columnSizing))r(t)&&n.push([`columnSizing`,t]);return r(e.descriptionAttribute)&&n.push([`descriptionAttribute`]),e.filters?.rules.forEach((e,t)=>{r(e.attribute)&&n.push([`filters`,`rules`,String(t),`attribute`])}),e.sorts?.forEach((e,t)=>{r(e.attribute)&&n.push([`sorts`,String(t),`attribute`])}),n;case`richtext`:return r(e.titleAttribute)&&n.push([`titleAttribute`]),n;default:return n}}function removedSource(e,t,n){let r=sourcedAttributeOf(e.object,t);return r&&n(r.object,r.attribute)?r.attribute:void 0}function planAttributeRemoval(e,t,n=listedObjectWithoutCatalogue){let r=new Map;for(let e of t){let t=r.get(e.object)??new Set;t.add(e.attribute),r.set(e.object,t)}let removed=(e,t)=>typeof t==`string`&&r.get(e)?.has(t)===!0,i={scrubbed:[],dropped:[],blocked:[]};for(let t of e){let e=!1,a;for(let o of t.contents){let s={object:t.object,view:t.name,content:o.name},c=o.placement===`main`,l=removedSource(t,o,removed);if(l!==void 0){let e={...s,attribute:l};i.dropped.push(e),c&&(a??=e);continue}e||=c;let u=n(t,o),d=u===void 0?void 0:r.get(u);if(!d)continue;if(o.type===`collection`&&o.layout===`kanban`&&namedBy(d)(o.groupByAttribute)){i.blocked.push({...s,attribute:o.groupByAttribute,reason:`kanban-grouping`});continue}let f=scrubPathsFor(o,d);if(f.length===0)continue;let p=cleanContent(o,f.map(e=>({path:e})));A(p)!==A(o)&&i.scrubbed.push({...s,definition:p})}!e&&a!==void 0&&i.blocked.push({...a,reason:`last-main-content`})}return i}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 Ja=new FormRegistry,Ya=[`attestorIdentity`,`evidenceDigest`,`maintenanceEpoch`,`observedZeroAt`,`resumeRevision`,`version`,`workloadInventoryDigest`],Xa=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Za=/^[0-9a-f]{40}$/,Qa=/^[0-9a-f]{64}$/,$a=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/,eo=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?Z$/;function invalid$1(e,t){throw new D(`Invalid DeploymentBarrierAttestorV1`,[{path:[e],message:t}])}function isRecord$4(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function requirePattern(e,t,n,r){let i=e[t];return(typeof i!=`string`||!n.test(i))&&invalid$1(t,r),i}function requireCanonicalTimestamp(e){let t=e.observedZeroAt;typeof t!=`string`&&invalid$1(`observedZeroAt`,`must be a UTC timestamp string`);let n=eo.exec(t);n||invalid$1(`observedZeroAt`,`must be a canonical ISO UTC timestamp`);let[,r,i,a,o,s,c]=n,l=new Date(t);return(!Number.isFinite(l.getTime())||l.getUTCFullYear()!==Number(r)||l.getUTCMonth()+1!==Number(i)||l.getUTCDate()!==Number(a)||l.getUTCHours()!==Number(o)||l.getUTCMinutes()!==Number(s)||l.getUTCSeconds()!==Number(c))&&invalid$1(`observedZeroAt`,`must name a real UTC instant`),t}function decodeDeploymentBarrierAttestationV1(e,t){isRecord$4(e)||invalid$1(`$`,`must be an object`);let n=Object.keys(e).sort();(n.length!==Ya.length||n.some((e,t)=>e!==Ya[t]))&&invalid$1(`$`,`must contain exactly the V1 attestation keys`),e.version!==1&&invalid$1(`version`,`must equal numeric 1`);let r=requirePattern(e,`maintenanceEpoch`,Xa,`must be a lowercase canonical UUID`),i=requirePattern(e,`resumeRevision`,Za,`must be a lowercase 40-character Git SHA`),a=requireCanonicalTimestamp(e),o=requirePattern(e,`attestorIdentity`,$a,`must be a lowercase slug`);if(o.length>64&&invalid$1(`attestorIdentity`,`must be at most 64 characters`),o!==t.allowedAttestorIdentity)throw new D(`Deployment barrier attestor identity mismatch`,[{path:[`attestorIdentity`],message:`does not equal the configured identity`}]);return{version:1,maintenanceEpoch:r,resumeRevision:i,observedZeroAt:a,attestorIdentity:o,workloadInventoryDigest:requirePattern(e,`workloadInventoryDigest`,Qa,`must be exactly 64 lowercase hexadecimal characters`),evidenceDigest:requirePattern(e,`evidenceDigest`,Qa,`must be exactly 64 lowercase hexadecimal characters`)}}function verifyDeploymentBarrierAttestationV1(e,t){let n=decodeDeploymentBarrierAttestationV1(e,t);if(n.maintenanceEpoch!==t.maintenanceEpoch)throw new D(`Deployment barrier maintenance epoch mismatch`,[{path:[`maintenanceEpoch`],message:`does not equal the current maintenance epoch`}]);if(n.resumeRevision!==t.resumeRevision)throw new D(`Deployment barrier resume revision mismatch`,[{path:[`resumeRevision`],message:`does not equal the requested revision`}]);let r=t.now.getTime()-new Date(n.observedZeroAt).getTime();if(!Number.isFinite(t.now.getTime())||r>9e5||r<-6e4)throw new D(`Deployment barrier attestation is stale`,[{path:[`observedZeroAt`],message:`must be within the database freshness window`}]);return n}const to=Object.freeze({attest(){return Promise.reject(new T(`DeploymentBarrierAttestorV1 requires a host implementation that observes the deployment control plane`,E.CONFIGURATION_REQUIRED))}});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 no=204800,ro=256;function isRecord$3(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$3(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$3(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$3(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 io=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,"architect.draft.updated":!0,"meeting.recording.patch":!0,"wallet.state":!0,"channel.revoked":!0}),ao=[`membership-unknown`,`sort-unknown`,`permissions-changed`],oo=[`permission-revoked`,`workspace-left`,`object-deleted`],so=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],co=[`type`,`objectId`,`recordId`,`recordVersion`],lo=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],uo=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],fo=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&io.includes(e)}function isLiveEventPayload(e){return isRecord$2(e)&&isLiveEventType(e.type)?isLiveEventPayloadForType(e.type,e):!1}function isLiveEventPayloadForType(e,t){if(!isRecord$2(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`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$2(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,Yn)}function isNotificationPriority(e){return isOneOf(e,Xn)}function isNotificationSensitivity(e){return isOneOf(e,Zn)}function isNotificationInboxState(e){return isOneOf(e,Qn)}function isNotificationWorkState(e){return isOneOf(e,$n)}function isNotificationSubject(e){return isRecord$2(e)&&hasString(e,`type`)&&hasString(e,`id`)}function isRecordFieldPatch(e){return isRecord$2(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$2)&&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,co)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$2(e)&&hasOnlyKeys(e,uo)&&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$2(e.values)&&hasOptional(e,`metadata`,isRecord$2)&&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,lo)&&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,ao)}function isAgentSessionPatchPayload(e){return e.type===`agent.session.patch`&&hasString(e,`sessionId`)&&isRecord$2(e.patch)&&hasVersion(e,`version`)&&hasString(e,`updatedAt`)}function isLiveNotification(e){return isRecord$2(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$2(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$2(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$2(e)?Object.keys(e).every(e=>so.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,fo)&&hasNonEmptyString(e,`targetActorId`)&&hasVersion(e,`archivedCount`)&&hasVersion(e,`version`)&&hasIsoDateString(e,`updatedAt`)}function isArchitectDraftUpdatedPayload(e){if(e.type!==`architect.draft.updated`||!isRecord$2(e.receipt))return!1;let t=e.receipt;return Array.isArray(t.operationIds)&&t.operationIds.every(isNonEmptyString)&&isRecord$2(t.revision)&&hasNonEmptyString(t.revision,`draftId`)&&hasVersion(t.revision,`version`)&&Array.isArray(t.changedTargets)&&t.changedTargets.every(e=>isRecord$2(e)&&isNonEmptyString(e.token)&&isNamedTarget(e.target))}function isNamedTarget(e){if(!isRecord$2(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}const po=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,po)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const mo=[`ok`,`low`,`exhausted`,`paused`],ho=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,mo)&&isOneOf(e.mode,ho)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,oo)}function isRecord$1(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$1(e)?payloadChannel(e):null}function isLiveEventEnvelope(e){return isRecord$1(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$1(e.payload):!1}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 kt(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(!Tt(e))throw new ComputedFormulaCompileError(`Unknown computed function "${e}"`);let r=_t[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`}const go=[{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)`}],_o=new Date(0).setUTCFullYear(1,0,1),vo=/^\d{4}-\d{2}-\d{2}$/,yo=new Set([`createdAt`,`updatedAt`,`deletedAt`]),bo=/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])(?:[T ]([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d)(?:\.(\d{1,6}))?)?(Z|[+-](?:0\d|1[0-4])(?::?[0-5]\d)?)?)?$/;function offsetMinutes(e){if(e===void 0||e===`Z`)return 0;let t=e.startsWith(`-`)?-1:1,n=e.slice(1).replace(`:`,``);return t*(Number(n.slice(0,2))*60+Number(n.slice(2,4)||`0`))}function parseFilterInstant(e){if(e instanceof Date){let t=e.getTime();return Number.isNaN(t)?null:t}if(typeof e!=`string`)return null;let t=bo.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l]=t,u=Number(n),d=Number(r),f=Number(i),p=new Date(0);if(p.setUTCFullYear(u,d-1,f),u===0||p.getUTCDate()!==f)return null;p.setUTCHours(Number(a??`0`),Number(o??`0`),Number(s??`0`),Number((c??``).padEnd(3,`0`).slice(0,3)));let m=p.getTime()-offsetMinutes(l)*6e4;return m<_o?null:m}function unwrapRange(e){return cn(e)?Dt(e):e}function hasTime(e){return e.type===`date`&&e.includeTime===!0}function isSystemTimestamp(e){return yo.has(e.name)}function instantWindow(e){let t=parseFilterInstant(e);return t===null?null:{startMs:t,endMs:t+(typeof e==`string`&&vo.test(e)?864e5:1)}}function storedUtcDay(e){let t=unwrapRange(e);if(t instanceof Date)return Number.isNaN(t.getTime())?null:Ee(t.getTime());if(typeof t!=`string`||t===``)return null;if(vo.test(t))return t;let n=new Date(t);return Number.isNaN(n.getTime())?null:Ee(n.getTime())}function comparandDay(e){return e instanceof Date?Number.isNaN(e.getTime())?null:Ee(e.getTime()):typeof e==`string`?vo.test(e)?e:parseFilterInstant(e)===null?null:e.slice(0,10):null}function toDate(e){if(e==null)return null;let t=e instanceof Date?e:new Date(String(e));return Number.isNaN(t.getTime())?null:t}function dateEquals(e,t,n,r){if(isSystemTimestamp(r)){let r=(storedUtcDay(t)??``)===(storedUtcDay(n)??``);return e===`is`?r:!r}if(hasTime(r)){let r=instantWindow(n);if(!r)return!1;let i=parseFilterInstant(unwrapRange(t)),a=i!==null&&i>=r.startMs&&i<r.endMs;return e===`is`?a:!a}let i=comparandDay(n);if(i===null)return!1;let a=storedUtcDay(t)===i;return e===`is`?a:!a}function orderAgainst(e,t,n){switch(e){case`greater_than`:return t>=n.endMs;case`greater_or_equal`:return t>=n.startMs;case`less_than`:return t<n.startMs;case`less_or_equal`:return t<n.endMs}}function dateOrdering(e,t,n,r){if(isSystemTimestamp(r)){let r=toDate(unwrapRange(t))?.getTime(),i=toDate(n)?.getTime();return r!==void 0&&i!==void 0&&orderAgainst(e,r,{startMs:i,endMs:i+1})}if(hasTime(r)){let r=instantWindow(n),i=parseFilterInstant(unwrapRange(t));return r!==null&&i!==null&&orderAgainst(e,i,r)}let i=comparandDay(n),a=i===null?null:instantWindow(i),o=toDate(unwrapRange(t))?.getTime();return a!==null&&o!==void 0&&orderAgainst(e,o,a)}const isEmpty=e=>j(e)||Array.isArray(e)&&e.length===0,toStr=e=>e==null?``:String(e),toNum=e=>{if(j(e))return null;let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)?t:null},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)},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,t)=>({appliesTo:[`number`,`currency`,`date`,`formula`],evaluateInMemory:(n,r,i)=>i.type===`date`?dateOrdering(e,n,r,i):compareNumbers(n,r,t)}),xo={is:{appliesTo:[`text`,`phone`,`number`,`currency`,`checkbox`,`status`,`select`,`date`,`user`,`relation`,`formula`],evaluateInMemory:(e,t,n)=>n.type===`checkbox`?e===!0==(t===!0):n.type===`date`?dateEquals(`is`,e,t,n):equalsForAttr(e,t,n)},is_not:{appliesTo:[`text`,`phone`,`number`,`currency`,`status`,`select`,`date`,`user`,`relation`,`formula`],evaluateInMemory:(e,t,n)=>n.type===`date`?dateEquals(`is_not`,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(`less_than`,(e,t)=>e<t),greater_than:orderingSpec(`greater_than`,(e,t)=>e>t),less_or_equal:orderingSpec(`less_or_equal`,(e,t)=>e<=t),greater_or_equal:orderingSpec(`greater_or_equal`,(e,t)=>e>=t),is_within:{appliesTo:[`date`],evaluateInMemory:(e,t)=>{let n=toDate(e),r=de(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}),So=[...Object.entries(ue).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,...So])}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 i=n.get(e.attribute);if(!i)return!1;if(e.property&&i.type===`location`){if(!(u(e.property)&&ne(e.operator)))return!1;let n=xo[e.operator];if(!n)return!1;let r=t[e.attribute],a=typeof r==`object`&&r?r[e.property]:void 0;return evaluateNormalizedComparands(n,`text`,e.operator,a,e.value,i)}if(e.property){let n=resolvePropertyDefinitions(i).find(t=>t.name===e.property);if(!n)return!1;let a=y(e.operator),o=xo[a];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,a,r[e.property],e.value,n)});return(e.quantifier??r(e.operator))===`none`?!c:c}let a=xo[e.operator];if(!a||!a.appliesTo.includes(i.type))return!1;let o=t[e.attribute],s=i.type===`relation`||i.type===`document`||i.type===`user`?normalizeReferenceIds(o):o;return evaluateNormalizedComparands(a,i.type,e.operator,s,e.value,i)}function evaluateNormalizedComparands(e,t,n,r,i,a){let[o,s]=normalizeOperatorComparands(t,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){return e===`phone`?normalizePhoneComparands(t,n):[normalizeComparableValue(e,t),normalizeComparableValue(e,n)]}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 On(t.phoneNumber);let n=typeof t.countryCode==`string`?t.countryCode:r;return`${n}:${Dn(t.phoneNumber,n)}`};return[normalizeOne(e),normalizeOne(t)]}function normalizeComparableValue(e,t){return e===`currency`?i(t):e===`date`?cn(t)?Dt(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 Co=`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,n){if(e.operator===`is`)return t(e.value)?resolveDynamicValue(e.value,n):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator===`any_of`){if(!Array.isArray(e.value)||e.value.length!==1)return;let r=e.value[0];return t(r)?resolveDynamicValue(r,n):r}}function resolveDynamicValue(e,t){if(t){if(e.dynamic===`actor`)return t.userId;if(e.anchor===`today`)return dateInTimezone(t.now,t.timezone);if(e.anchor===`now`)return t.now.toISOString()}}function requestedCapabilities(e){let t=[];return e.canModify&&t.push(`modify`),e.canSend&&t.push(`send`),t}const wo={status:`connector_status`,error:`connector_error`,provider:`connector_provider`};let To=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const Eo=`DRAFT`;function isProviderDraft(e){return e.includes(Eo)}const Do=[`threads`,`messages`];function isMailboxListMode(e){return Do.includes(e)}const Oo=[`reply`,`reply_all`];function isReplyMode(e){return Oo.includes(e)}const ko=2e5,Ao=998,jo=[`force`,`skip`],Mo=[`none`,`all`,`external_only`],No=`x-fake-signature`,Po={override:null,status:`none`,failureReason:null,botId:null},Fo=/^Session \d+$/;function stripTrailingPunctuation(e){let t=e.length;for(;t>0&&`.!?`.includes(e.charAt(t-1));)--t;return e.slice(0,t)}function buildAgentFallbackTitle(e){let t=stripTrailingPunctuation(e.replace(/\s+/g,` `).trim());return t?t.length>60?`${t.slice(0,59).trimEnd()}...`:t:`New conversation`}function conversationDisplayTitle(e){let t=e.generated?.trim();return t&&!Fo.test(t)?t:e.firstUserText?buildAgentFallbackTitle(e.firstUserText):e.emptyLabel}const Io=/^[a-z0-9][a-z0-9-]{0,62}$/;function assertSchemaSourceId(e){if(!Io.test(e))throw new D(`Invalid schema source id "${e}": expected a lowercase slug matching ${Io}`,[])}const Lo={phone:`text`,currency:`number`},Ro={rename:[`kind`,`object`,`from`,`to`],phone:[`kind`,`object`,`attribute`,`to`,`defaultCountryCode`],currency:[`kind`,`object`,`attribute`,`to`,`currencyCode`]};function refuse$1(e,t,n){throw new D(n,[{path:t===void 0?[`resolutions`,String(e)]:[`resolutions`,String(e),t],message:n}])}function assertKeys(e,t,n){for(let r of n)(typeof t[r]!=`string`||t[r]===``)&&refuse$1(e,r,`Resolution ${e} needs a non-empty string \`${r}\``);let r=Object.keys(t).find(e=>!n.includes(e));r!==void 0&&refuse$1(e,r,`Resolution ${e} has an unknown field \`${r}\``)}function assertResolution(e,t){if(ht(t)||refuse$1(e,void 0,`Resolution ${e} must be an object`),t.kind===`rename`){assertKeys(e,t,Ro.rename),t.from===t.to&&refuse$1(e,`to`,`Resolution ${e} renames "${t.from}" to itself`);return}if(t.kind!==`retype`&&refuse$1(e,`kind`,`Unknown resolution kind ${JSON.stringify(t.kind)}: expected "rename" or "retype"`),t.to!==`phone`&&t.to!==`currency`&&refuse$1(e,`to`,`Unsupported retype to ${JSON.stringify(t.to)}: a push converts text → phone and number → currency only`),assertKeys(e,t,Ro[t.to]),t.to===`phone`){let n=t.defaultCountryCode;/^[A-Z]{3}$/.test(n)&&qn(n)||refuse$1(e,`defaultCountryCode`,`Resolution ${e}: "${n}" is not an ISO 3166-1 alpha-3 country code`);return}let n=t.currencyCode;/^[A-Z]{3}$/.test(n)&&Kn(n)||refuse$1(e,`currencyCode`,`Resolution ${e}: "${n}" is not a supported ISO 4217 currency code`)}function addressesOf(e){return e.kind===`rename`?{reads:e.from,lands:e.to}:{reads:e.attribute,lands:e.attribute}}function assertSchemaSourceResolutions(e){if(!Array.isArray(e))throw new D("`resolutions` must be an array",[{path:[`resolutions`],message:"`resolutions` must be an array"}]);if(e.length>100)throw new D(`A push carries ${e.length} resolutions; the limit is 100`,[]);let t=new Set;for(let[n,r]of e.entries()){assertResolution(n,r);let{reads:e,lands:i}=addressesOf(r);for(let[a,o]of[[`${r.kind}:${r.object}.${e}`,`of "${r.object}.${e}"`],[`${r.kind}>${r.object}.${i}`,`onto "${r.object}.${i}"`]])t.has(a)&&refuse$1(n,void 0,`Resolution ${n} repeats a ${r.kind} ${o}`),t.add(a)}}function phoneFromText(e,t){let n=e.trim();if(n===``)return{value:null};let r=Jn(n,An(t));if(!r?.isPossible()||r.country===void 0||r.ext!==void 0)return;let i=Gn(r.country)?.iso3;if(i!==void 0)return{value:{countryCode:i,phoneNumber:Dn(n,i)}}}function convertRetypedValue(e,t,n={}){if(t===null)return{value:null};if(e.to===`phone`)return typeof t==`string`?phoneFromText(t,e.defaultCountryCode):void 0;if(typeof t==`number`&&Math.abs(t)<=2**53-1&&!(t<0&&n.allowNegative!==!0))return{value:{code:e.currencyCode,value:t}}}const zo=M.object({mode:M.enum([`inline`,`window`]),interaction:M.enum([`static`,`interactive`]),size:M.enum([`compact`,`regular`]),aspectRatio:M.number().positive().finite().optional()}).strict(),Bo=M.object({artifactId:M.string().min(1),revision:M.number().int().positive(),name:M.string().min(1),kind:M.string().min(1),retention:M.enum(mi),display:zo}).strict();function readArtifactResult(e){let t=Bo.safeParse(e);return t.success?t.data:null}const Vo=M.string().regex(/^[^/\s]+\/[^/\s]+$/),Ho=M.object({kind:M.literal(`generated-image`),artifact:M.unknown(),generation:M.object({attemptId:M.uuid(),requestedModelId:Vo,executedModelId:Vo.nullable(),format:M.enum(ki),mimeType:M.enum([`image/png`,`image/jpeg`,`image/webp`])}).strict()}).strict();function readGeneratedImageResult(e){let t=Ho.safeParse(e);if(!t.success)return null;let n=readArtifactResult(t.data.artifact);return!n||n.kind!==`image`?null:{...t.data,artifact:{...n,kind:`image`}}}function isCompletedToolPart(e){return e.type===`tool`&&e.state===`completed`}function readString(e,t){let n=e[t];return typeof n==`string`?n:void 0}function upsertWithPrecedence(e,t,n,r){let i=e.get(t),a=i&&r[i.kind]>r[n.kind]?i:n;e.delete(t),e.set(t,a)}const Uo={created:1,modified:0};function readSingleRecordEntry(e){if(typeof e!=`object`||!e)return null;let t=e,n=typeof t.record==`object`&&t.record!==null?t.record:void 0,r=(n&&readString(n,`id`))??readString(t,`recordId`);return r?{id:r,label:(n&&readString(n,`label`))??r,objectName:(n&&readString(n,`objectName`))??``}:null}function readBulkRecordEntries(e,t,n){if(typeof e!=`object`||!e)return[];let r=e[t];if(!Array.isArray(r))return[];let i=[];for(let e of r){if(typeof e!=`object`||!e)continue;let t=e,r=readString(t,`id`);r&&i.push({id:r,label:readString(t,`label`)??r,objectName:readString(t,`objectName`)??n})}return i}function extractTouchedRecords(e){let t=new Map;for(let n of e)if(n.role===`assistant`)for(let e of n.parts){if(!isCompletedToolPart(e))continue;let n=[],r;if(e.name===`create_record`||e.name===`update_record`||e.name===`edit_content`){let t=readSingleRecordEntry(e.result);n=t?[t]:[],r=e.name===`create_record`?`created`:`modified`}else if(e.name===`bulk_create_records`||e.name===`bulk_update_records`){let t=readString(e.args,`objectId`)??``,i=e.name===`bulk_create_records`?`created`:`updated`;n=readBulkRecordEntries(e.result,i,t),r=e.name===`bulk_create_records`?`created`:`modified`}else continue;for(let e of n){let n={recordId:e.id,objectName:e.objectName,label:e.label,kind:r};upsertWithPrecedence(t,e.id,n,Uo)}}return[...t.values()]}const Wo={modified:1,consulted:0};function isFilePart(e){return e.type===`file`}function entryFromDocumentMutation(e){if(typeof e.result!=`object`||e.result===null)return null;let t=e.result,n=readString(t,`documentId`)??readString(t,`folderId`);return n?{id:n,title:readString(e.args,`name`)??readString(e.args,`title`)??n,kind:`modified`}:null}function entryFromReadDocument(e){let t=readString(e.args,`documentId`);return t?{id:t,title:t,kind:`consulted`}:null}function entryFromSandboxUpload(e){if(typeof e.result!=`object`||e.result===null)return null;let t=e.result,n=readString(t,`fileId`);return n?{id:n,fileId:n,title:readString(t,`title`)??n,kind:`modified`,mimeType:readString(t,`mimeType`)}:null}function entryFromToolPart(e){switch(e.name){case`update_document`:case`attach_file`:case`create_folder`:return entryFromDocumentMutation(e);case`read_document`:return entryFromReadDocument(e);case`sandbox_upload_file`:return entryFromSandboxUpload(e);default:return null}}function extractTouchedDocuments(e){let t=new Map;for(let n of e)if(n.role===`assistant`){for(let e of n.parts)if(isCompletedToolPart(e)){let n=entryFromToolPart(e);n&&upsertWithPrecedence(t,n.id,n,Wo)}else if(isFilePart(e)&&e.fileId){let n={id:e.fileId,fileId:e.fileId,title:e.name||e.fileId,kind:`modified`,mimeType:e.mimeType};upsertWithPrecedence(t,n.id,n,Wo)}}return[...t.values()]}function extractTouchedArtifacts(e){let t=new Map;for(let n of e)if(n.role===`assistant`)for(let e of n.parts){if(!isCompletedToolPart(e)||e.error)continue;let n=e.name===`generate_image`?readGeneratedImageResult(e.result)?.artifact:e.name===`publish_artifact`?readArtifactResult(e.result):null;if(!n)continue;let r=`${n.artifactId}:${n.revision}`;t.delete(r),t.set(r,n)}return[...t.values()]}function pricePerMillion(e){let t=[...e?.perToken===void 0?[]:[e.perToken],...(e?.tiers??[]).map(e=>e.cost)],n=[];for(let e of t){let t=perTokenToPerMillion(e);if(t===void 0)return;n.push(t)}return n.length===0?void 0:Math.max(...n)}function perTokenToPerMillion(e){if(e.trim()===``)return;let t=Number(e)*1e6;return Number.isFinite(t)?Math.round(t*1e6)/1e6:void 0}function routingPrice(e,t){let n=t===`fast`&&e.pricing?.fast?e.pricing.fast:e.pricing,r=pricePerMillion(n?.input),i=pricePerMillion(n?.output);if(r!==void 0&&i!==void 0)return{inputPerMillionUsd:Math.max(r,e.listPricing?.inputPerMillionUsd??0),outputPerMillionUsd:Math.max(i,e.listPricing?.outputPerMillionUsd??0)}}function isUnderRoutingCeiling(e,t){return e!==void 0&&e.inputPerMillionUsd<=t.inputPerMillionUsd&&e.outputPerMillionUsd<=t.outputPerMillionUsd}function isRoutableModel(e){return e.tasks!==void 0&&Object.keys(e.tasks).length>0}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=kt(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}function priceDimension(e,t){return{...e===void 0?{}:{perToken:e},...t===void 0?{}:{tiers:t.map(e=>({cost:e.cost,min:e.min??0,...e.max===void 0?{}:{max:e.max}}))}}}function normalizeFastPricing(e){return{input:priceDimension(e.input,e.input_tiers),output:priceDimension(e.output,e.output_tiers),...e.input_cache_read!==void 0||e.input_cache_read_tiers!==void 0?{cacheRead:priceDimension(e.input_cache_read,e.input_cache_read_tiers)}:{},...e.input_cache_write!==void 0||e.input_cache_write_tiers!==void 0?{cacheWrite:priceDimension(e.input_cache_write,e.input_cache_write_tiers)}:{}}}function normalizePricing(e){return{...normalizeFastPricing(e),...e.fast===void 0?{}:{fast:normalizeFastPricing(e.fast)}}}const Go=/^[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);(!Go.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&&!Cn(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)&&!Cn(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);(!Go.test(b)||x||u.has(b)&&u.get(b)!==g)&&reject(d,`pair`,`Invalid or duplicate pair identity for ${d} and ${p}`),u.set(b,g);let S=m?d:chooseOwner(a,v,d,p,y,ee);a.bilateral&&v.bilateral||reject(d,`bilateral`,`Missing reciprocal configuration for ${d} and ${p}`),a.bilateral={...a.bilateral,cardinality:v.cardinality,label:v.label,storageOwner:S===d},v.bilateral={...v.bilateral,cardinality:a.cardinality,label:a.label,storageOwner:S===p},reconcileProperties(a,v,d,p,s,o),a.metadata={...a.metadata,relationPairId:b},v.metadata={...v.metadata,relationPairId:b},l.set(g,{id:b,addresses:h,ownerAddress:S,generatedAddresses:h.filter(e=>!s.has(e)),...m?{symmetric:!0}:{}})}return{objects:t,pairs:[...l.values()].sort((e,t)=>e.addresses[0].localeCompare(t.addresses[0]))}}const G=M.number().finite().nonnegative(),Ko=M.enum(gr),qo=M.enum(_r),Jo=M.enum(vr),Yo=M.enum(xr),Xo=M.object({provider:Ko,model:M.string().min(1)}).strict(),Zo=M.object({speed:qo.optional(),reasoning:Jo.optional(),routing:Yo.optional()}).strict(),Qo=M.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),$o=M.object({model:Xo.optional(),speed:qo.optional(),reasoning:Jo.optional(),imageModel:Qo.optional(),routing:Yo.optional()}).strict(),es=$o.refine(e=>Cr.some(t=>e[t]!==void 0),{message:`At least one inference override is required`}),ts=M.object({model:Xo.nullable().optional(),speed:qo.nullable().optional(),reasoning:Jo.nullable().optional(),imageModel:Qo.nullable().optional(),routing:Yo.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`}),ns=M.object({model:M.string().min(1),routing:M.object({mode:M.literal(`auto`),tasks:M.array(M.enum(yr)).optional(),demand:M.enum(br).optional(),reason:M.enum([`selected`,`retained`,`fallback`]).optional(),relation:M.enum([`continue`,`modify`,`new`,`aside`,`unknown`]).optional(),anchorMessageId:M.string().min(1).optional()})}),rs=M.object({label:M.string(),denied:M.boolean().optional(),deletion:M.object({target:M.string().optional(),count:G.optional(),restorableDays:G.optional()}).strict().optional(),counts:M.record(M.string(),G).optional(),warnings:M.array(M.string()).optional()}).strict(),is=M.union([M.object({type:M.literal(`text`),text:M.string()}).strict(),M.object({type:M.literal(`reasoning`),text:M.string()}).strict(),M.object({type:M.literal(`system`),code:M.enum(Ar)}).strict(),M.object({type:M.literal(`error`),error:M.string(),errorClass:M.string().optional()}).strict(),M.object({type:M.literal(`tool`),toolCallId:M.string(),name:M.string(),args:M.record(M.string(),M.unknown()),result:M.unknown().optional(),error:M.string().optional(),errorCode:M.enum([`output_limit_reached`,`interrupted`,E.INVALID_TOOL_INPUT,`external_outcome_unknown`,`external_not_dispatched`]).optional(),state:M.enum([`streaming`,`running`,`completed`,`error`,`pending`,`approval-requested`,`approval-responded`,`approval-dispatched`]),durationMs:G.optional(),approvalId:M.string().optional(),approvalImpact:rs.optional(),approved:M.boolean().optional(),approvalReason:M.string().optional(),approvalRelaxableByAuto:M.boolean().optional()}).strict(),M.object({type:M.literal(`file`),fileId:M.string(),name:M.string(),mimeType:M.string()}).strict(),M.object({type:M.literal(`compaction`),state:M.literal(`in-progress`),reason:M.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:G.optional(),reportedTokens:G.optional()}).strict(),M.object({type:M.literal(`compaction`),state:M.literal(`completed`),tokensBefore:G,tokensAfter:G,tokensSaved:G,strategy:M.enum([`no-op`,`summary`,`truncation`]),durationMs:G,summary:M.string().optional()}).strict(),M.object({type:M.literal(`compaction`),state:M.literal(`failed`),reason:M.string(),durationMs:G.optional()}).strict()]),as=M.object({id:M.string(),name:M.string(),mimeType:M.string(),size:G}).strict(),os=M.object({id:M.string(),artifactId:M.string(),revision:M.number().int().min(1),selectedText:M.string()}).strict(),ss=M.object({id:M.string(),type:M.string().transform(e=>e),entityId:M.string(),label:M.string(),objectName:M.string().optional(),startIndex:G,endIndex:G}).strict(),cs=M.object({provider:Ko,model:M.string(),maxTokens:G.optional(),contextWindow:G.optional()}).strict(),ls=M.union([M.date(),M.string().datetime({offset:!0}).transform(e=>new Date(e))]),us=M.object({id:M.string(),sessionId:M.string(),tenantId:M.string().optional(),runId:M.string().optional(),role:M.enum([`user`,`assistant`,`system`,`tool`]),parts:M.array(is),attachments:M.array(as).optional(),mentions:M.array(ss).optional(),quotes:M.array(os).optional(),model:cs.optional(),tokenUsage:M.object({input:G,output:G}).strict().optional(),metadata:M.record(M.string(),M.unknown()).optional(),createdAt:ls}).strict(),ds=M.object({id:M.string(),description:M.string(),status:M.enum([`pending`,`in_progress`,`completed`,`blocked`]),result:M.string().optional(),updatedAt:G.optional()}).strict(),fs=M.object({id:M.string(),sessionId:M.string(),status:M.enum([`active`,`completed`,`abandoned`]),todos:M.array(ds),version:G,createdAt:M.string(),updatedAt:M.string(),completedAt:M.string().optional()}).strict(),ps={"session-named":M.object({name:M.string()}).strict(),"compaction-start":M.object({reason:M.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:G.optional(),reportedTokens:G.optional()}).strict(),"compaction-end":M.object({tokensBefore:G,tokensAfter:G,tokensSaved:G,strategy:M.enum([`no-op`,`summary`,`truncation`]),durationMs:G,summary:M.string().optional()}).strict(),"compaction-failed":M.object({reason:M.string()}).strict(),usage:M.object({messageId:M.string().min(1).optional(),inputTokens:G,outputTokens:G,totalTokens:G,cacheReadTokens:G.optional(),cacheCreationTokens:G.optional(),contextWindow:G,residentTokens:G,utilization:M.number().finite().min(0).max(1),costUsd:G.optional()}).strict(),"message-persisted":M.object({message:us}).strict(),"message-persisted-ref":M.object({messageId:M.string().min(1)}).strict(),"message-updated":M.object({message:us}).strict(),"todo-plan-update":M.object({plan:fs}).strict(),"approval-context":M.object({approvalId:M.string(),toolCallId:M.string(),impact:rs.optional(),relaxableByAuto:M.boolean().optional()}).strict(),"session-state":M.object({state:M.object({phase:M.enum([`queued`,`running`,`parked`,`terminal`]),parkedOn:M.enum([`human`,`agents`]).optional(),humanRequestIds:M.array(M.string()).optional(),outcome:M.enum([`completed`,`failed`,`cancelled`,`timeout`,`expired`]).optional()}).strict(),version:M.number().int().positive(),updatedAt:M.string().datetime({offset:!0})}).strict()};function isAgentUIDataName(e){return e in ps}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=M.object({type:M.literal(`data-${n}`),id:M.string().optional(),data:ps[n],transient:M.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}})}const ms=M.object({type:M.enum(wr),color:M.enum(Bn),expression:M.enum(Tr).default(`relaxed`)}).strict(),hs=M.array(M.string().trim().min(1).max(200)).max(4);function agentAvatarFromMetadata(e){let t=ms.safeParse(e);return t.success?t.data:void 0}const gs=[`Very economical`,`Balanced`,`Powerful`,`Very powerful`],_s=[`unsupported`,`effort`,`toggle`,`budget`,`model-controlled`],vs=[`text`,`image`,`audio`,`video`,`pdf`],ys=/^\d+x\d+$/,bs=/^\d+:\d+$/,xs=/^[a-z0-9][a-z0-9-]*$/,Ss=.01;function refuse(e){throw new D(`Model catalogue: ${e}`,[])}function refuseZodIssues(e){let[t]=e.issues;throw new D(`Model catalogue: ${t?.message??`the payload is invalid`}`,e.issues.map(e=>({path:e.path.map(String),message:e.message,code:e.code})))}function parseOrRefuse(e,t){let n=e.safeParse(t);return n.success||refuseZodIssues(n.error),n.data}function nonEmptyString(e){return M.string({error:e}).min(1,{error:e})}function positiveIntegerSchema(e,t){let error=n=>`${e} has a ${t} that is not a positive integer, got ${String(n.input)}`;return M.number({error}).int({error}).positive({error})}function priceDefect(e,t){let n=Number(e.trim());return e.trim().length===0||!Number.isFinite(n)?`unreadable`:n<0||n>Ss?`implausible`:n===0&&!t?`undeclared-zero`:null}const Cs=M.looseObject({cost:M.string(),min:M.number(),max:M.number().optional()});function priceDimensionSchema(e,t,n){let r=`model "${e}" has an unreadable ${t} price`;return M.looseObject({perToken:M.string().optional(),tiers:M.array(Cs).optional()},{error:r}).superRefine((i,a)=>{let o=i.tiers;if(i.perToken===void 0&&(o===void 0||o.length===0)){a.addIssue({code:`custom`,message:r});return}let s=[...i.perToken===void 0?[]:[i.perToken],...(o??[]).map(e=>e.cost)];for(let i of s){let o=priceDefect(i,n);if(o===`unreadable`){a.addIssue({code:`custom`,message:`${r} "${i}"`});return}if(o===`implausible`){a.addIssue({code:`custom`,message:`model "${e}" has an implausible ${t} price "${i}", above the ${Ss} per-token ceiling`});return}if(o===`undeclared-zero`){a.addIssue({code:`custom`,message:`model "${e}" has a zero ${t} price without declaring "free": true`});return}}if(i.perToken===void 0&&o!==void 0){let n=`model "${e}" ${t} price tiers must cover every token count from zero without gaps`,r=0;for(let[e,t]of o.entries()){if(!Number.isInteger(t.min)||t.min!==r){a.addIssue({code:`custom`,message:n});return}if(t.max===void 0){if(e===o.length-1)break;a.addIssue({code:`custom`,message:n});return}if(!Number.isInteger(t.max)||t.max<=t.min){a.addIssue({code:`custom`,message:n});return}r=t.max}if(o.at(-1)?.max!==void 0){a.addIssue({code:`custom`,message:n});return}}})}function pricingSchema(e,t){let dimensions=n=>({input:priceDimensionSchema(e,`${n}input`,t),output:priceDimensionSchema(e,`${n}output`,t),cacheRead:priceDimensionSchema(e,`${n}cacheRead`,!0).optional(),cacheWrite:priceDimensionSchema(e,`${n}cacheWrite`,!0).optional()}),n=`model "${e}" has no usable pricing`;return M.looseObject({...dimensions(``),fast:M.looseObject(dimensions(`fast `),{error:n}).optional()},{error:n})}function catalogTextModelSchema(e,t){let n=`model "${e}"`;return M.looseObject({id:nonEmptyString(`${n} has no usable id`),apiModelId:nonEmptyString(`${n} has no usable apiModelId`).optional(),provider:M.enum(gr,{error:e=>`${n} names an unknown provider "${String(e.input)}"`}),label:nonEmptyString(`${n} has no usable label`),description:M.string().optional(),recommended:M.boolean().optional(),recommendationRank:M.number().optional(),profile:M.looseObject({position:M.number(),label:M.enum(gs,{error:e=>`${n} has an unknown profile label "${String(e.input)}"`}),guidance:M.string()},{error:`profile of ${n} must be an object`}).optional(),pricing:pricingSchema(e,t),free:M.boolean().optional(),reasoningOptions:M.array(M.enum(vr)).optional(),reasoningMode:M.enum(_s).optional(),inputModalities:M.array(M.enum(vs)).optional(),supportedParameters:M.array(M.string()).optional(),supportsTools:M.boolean().optional(),supportsStructuredOutput:M.boolean().optional(),isDefault:M.boolean().optional(),contextWindow:positiveIntegerSchema(n,`contextWindow`),maxOutputTokens:positiveIntegerSchema(n,`maxOutputTokens`),unverified:M.boolean().optional(),isCompactionModel:M.boolean().optional(),isUtilityModel:M.boolean().optional(),tasks:M.partialRecord(M.enum(yr),M.enum(br)).optional(),listPricing:M.object({inputPerMillionUsd:M.number(),outputPerMillionUsd:M.number()}).optional()}).superRefine((e,t)=>{for(let r of[`id`,`apiModelId`]){let i=e[r];i!==void 0&&i.includes(`/`)&&t.addIssue({code:`custom`,path:[r],message:i.startsWith(`${e.provider}/`)?`${n} has a ${r} that already starts with its provider "${e.provider}/"`:`${n} has a ${r} that is not bare: a text model id carries no provider, which belongs in "provider"`})}})}function imageRequestSchema(e,t){let error=n=>n.input===void 0?`image model "${e}" has no "${t}" request`:`image model "${e}" has an unusable "${t}" request`;return M.union([M.looseObject({size:M.custom(e=>ys.test(String(e)))}),M.looseObject({aspectRatio:M.custom(e=>bs.test(String(e)))})],{error})}function catalogImageModelSchema(e){let t=`image model "${e}"`,n=`${t} has no usable formats`;return M.looseObject({id:Qo,name:nonEmptyString(`${t} has no usable name`),provider:nonEmptyString(`${t} has no usable provider`).regex(xs,{error:`${t} names an unusable provider`}),formats:M.array(M.enum(ki,{error:e=>`${t} declares an unknown format "${String(e.input)}"`}),{error:n}).min(1,{error:n}),requests:M.looseObject({square:imageRequestSchema(e,`square`).optional(),landscape:imageRequestSchema(e,`landscape`).optional(),portrait:imageRequestSchema(e,`portrait`).optional()},{error:`requests of ${t} must be an object`}),isDefault:M.boolean().optional()}).superRefine((e,n)=>{e.id.startsWith(`${e.provider}/`)||n.addIssue({code:`custom`,message:`${t} has an id that does not start with its provider "${e.provider}/"`})}).transform((e,n)=>{let r={...e,requests:declaredImageRequests(e)},i=imageModelFormatDefect(r);return i&&n.addIssue({code:`custom`,message:`${t} ${i}`}),r})}const ws=M.looseObject({model:nonEmptyString(`model "embedding" has no usable model`),dimensions:positiveIntegerSchema(`embedding`,`dimensions`)},{error:`embedding must be an object`});function parseTextModel(e){let t=e,n=typeof t?.id==`string`&&t.id.length>0?t.id:void 0;return n===void 0&&refuse(`a text model has no id`),parseOrRefuse(catalogTextModelSchema(n,t?.free===!0),e)}function parseImageModel(e){let t=e,n=typeof t?.id==`string`&&t.id.length>0?t.id:void 0;return n===void 0&&refuse(`an image model has no id`),parseOrRefuse(catalogImageModelSchema(n),e)}function refuseDuplicates(e,t){let n=new Set;for(let r of e)n.has(r)&&refuse(`duplicate ${t} id "${r}"`),n.add(r)}function refuseUnlessOneDefault(e,t){let n=e.filter(e=>e.isDefault===!0).map(e=>e.id);n.length!==1&&refuse(`exactly one default ${t} is required, found ${n.length}${n.length>0?` (${n.join(`, `)})`:``}`)}function refuseBadRoleCounts(e){refuseUnlessOneDefault(e,`model`);let t=e.filter(e=>e.isUtilityModel===!0).map(e=>e.id);t.length>1&&refuse(`at most one utility model is allowed, found ${t.join(`, `)}`);let n=e.filter(e=>e.isCompactionModel===!0).map(e=>e.id);n.length>1&&refuse(`at most one compaction model is allowed, found ${n.join(`, `)}`)}function refuseUnlessRoutable(e){e.some(isRoutableModel)||refuse(`no text model carries a "tasks" entry, so none is even a candidate for Auto — ${e.length} model(s) read`)}const Ts=M.iso.datetime({offset:!0});function parseModelCatalog(e){(typeof e!=`object`||!e||Array.isArray(e))&&refuse(`payload must be an object`);let t=e;(typeof t.publishedAt!=`string`||!Ts.safeParse(t.publishedAt).success)&&refuse(`publishedAt must be an ISO 8601 string`),Array.isArray(t.text)||refuse(`text must be an array`),Array.isArray(t.image)||refuse(`image must be an array`),t.text.length===0&&refuse(`at least one text model is required`);let n=t.text.map(parseTextModel),r=t.image.map(parseImageModel);refuseDuplicates(n.map(e=>e.id),`text model`),refuseDuplicates(r.map(e=>e.id),`image model`),refuseBadRoleCounts(n),refuseUnlessRoutable(n),r.length>0&&refuseUnlessOneDefault(r,`image model`);let i=t.embedding===void 0?void 0:parseOrRefuse(ws,t.embedding);return{...t,publishedAt:t.publishedAt,text:n,image:r,...i===void 0?{}:{embedding:i}}}function defineOperation(e){return e}function definePresentation(e,t,n){let r=t===`atomic`?`none`:t===`local`?`if-not-visible`:`follow`;return i=>{let a=n?.(i);return{impact:t,navigation:r,focus:{...e(i),...a===void 0?{}:{propertyPath:a}}}}}const K={kind:`target-missing`};var DraftRefusalError=class extends D{constructor(e,t,n=[]){super(e,n),this.refusal=t}};const Es=[`pluralLabel`,`description`,`labelExpression`,`embeddingExpression`];function draftObjectSettings(e){return Object.fromEntries(Es.filter(t=>e[t]!==void 0).map(t=>[t,e[t]]))}function toDraftableObject(e){return{id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},...draftObjectSettings(e)}}function toDraftableAttributes(e){let t=e.id??e.name;return(e.attributes??[]).map(e=>toDraftableAttribute(e,t))}function toAttribute(e){return{...e.config,id:e.id,objectId:e.objectId,name:e.name,label:e.label,type:e.attributeType}}function toDraftableAttribute(e,t){let{id:n,objectId:r,name:i,label:a,type:o,...s}=e;return{id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:s}}function draftedLabelExpression(e){let t=e[0];return t?`{{ ${t.name} }}`:`{{ id }}`}function draftedObjectDefinition(e,t){let n=t.filter(t=>t.objectId===e.id);return{id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},...draftObjectSettings(e),labelExpression:e.labelExpression??draftedLabelExpression(n),attributes:n.map((e,t)=>{let n=toAttribute(e);return n.order===void 0?{...n,order:t}:n})}}function toDraftableView(e,t,n=workspaceViewAuthoring(e.contents)){return structuredClone({...e,...t,authoring:n})}function draftedViewDefinition(e){let{id:t,revision:n,contentIds:r,contentRevisions:i,derived:a,authoring:o,...s}=e;return structuredClone(s)}function fromDraftableView(e,t){return{...e,...draftedViewDefinition(t)}}const Ds={id:M.string().min(1).describe(`Your id, echoed back`),note:M.string().trim().min(1).max(160).optional().describe(`One first-person sentence, in the person's language: what you do and why, ≤160 chars`)},q={...Ds,objectName:M.string().min(1).describe(`Object`),viewName:M.string().min(1).describe(`View API name`)},J={...q,contentName:M.string().min(1).describe(`Content API name`)},Os=M.union([M.object({before:M.string().min(1).describe(`Place immediately before this content name`)}).strict(),M.object({after:M.string().min(1).describe(`Place immediately after this content name`)}).strict(),M.object({end:M.literal(!0).describe(`Place at the end of the placement zone`)}).strict()]),viewFocus=e=>({objectName:e.objectName,viewName:e.viewName}),contentFocus=e=>({...viewFocus(e),contentName:e.contentName});function invalid(e,t,n){let r=[{path:e,message:t}];throw n?new DraftRefusalError(t,n,r):new D(t,r)}function change(e,t,n,r){let i=e.views.findIndex(e=>e.object===t.objectName&&e.name===t.viewName);i<0&&invalid([`viewName`],`View is not in the draftable state`,{kind:`view-missing`,objectName:t.objectName,viewNames:e.views.filter(e=>e.object===t.objectName).map(e=>e.name)}),e.views[i].authoring||invalid([`authoring`],`Missing view authoring baseline`);let{derived:a,...o}=r(structuredClone(e.views[i]));o.contents=resolveViewContents(o.authoring);let s=e.views.map((e,t)=>t===i?o:e);return validateContentViewCatalogue({extensions:[...n.extensions],objects:e.objects.map(t=>draftedObjectDefinition(t,e.attributes.filter(e=>e.objectId===t.id))),views:s.filter(e=>!e.derived||e.contents.length>0).map(draftedViewDefinition)}),{...e,views:s}}function contentState(e,t){let n=Object.hasOwn(e.authoring.contents,t)?e.authoring.contents[t]:void 0;return n||invalid([`contentName`],`Content is not in the draftable state`,K),n}function setOrder(e,t,n){for(let r of n)e.authoring[r===`main`?`mainOrderCustomized`:`asideOrderCustomized`]=!0,t.filter(e=>e.placement===r).forEach((t,n)=>{contentState(e,t.name).workspacePosition=n})}function find(e,t){let n=e.contents.find(e=>e.name===t);return n||invalid([`contentName`],`Content is not in the draftable state`,K),n}function placed(e,t,n){let r=e.filter(e=>e.name!==t.name),i=r.filter(e=>e.placement===t.placement),a=i.length;if(!(`end`in n)){let e=`before`in n?n.before:n.after;a=i.findIndex(t=>t.name===e),a<0&&invalid([`target`],`Order target is not in this placement`),`after`in n&&a++}return i.splice(a,0,t),t.placement===`main`?[...i,...r.filter(e=>e.placement===`aside`)]:[...r.filter(e=>e.placement===`main`),...i]}const ks=M.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 M.NEVER}let r=typeof e==`object`&&e&&`name`in e?e.name:void 0;return{...n.data,name:r}}),As=M.object({...J,type:M.literal(`replace_view_content`),definition:ks}).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}}),js=C.describe(`The whole content definition.`),Ms=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:As,wire:M.object({...J,type:M.literal(`replace_view_content`),definition:js}).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}}))}),Ns=M.object({...q,type:M.literal(`add_view_content`),content:js,target:Os.describe(`Where to place the new content within its placement zone`)}).strict(),addFocus=e=>({...viewFocus(e),contentName:e.content.name}),Ps=defineOperation({type:`add_view_content`,summary:`Adds a content; content.name unique; the collection-view and aside rules apply; target positions it among siblings.`,schema:Ns,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}}})}),Fs=M.object({...J,type:M.literal(`remove_view_content`)}).strict(),Is=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:Fs,focus:contentFocus,presentation:definePresentation(contentFocus,`structural`),describe:e=>`Remove ${e.contentName}`,apply:(e,t,n)=>change(e,t,n,e=>({...dropViewContent(e,t.contentName),revision:e.revision+1}))});function dropViewContent(e,t){let n=find(e,t),r=contentState(e,t);if(setOrder(e,e.contents.filter(e=>e.name!==t),[n.placement]),r.sourceDefinition!==null)r.workspaceDefinition=null,r.suppressed=!0,e.contentRevisions={...e.contentRevisions,[t]:e.contentRevisions[t]+1};else{delete e.authoring.contents[t];let{[t]:n,...r}=e.contentIds,{[t]:i,...a}=e.contentRevisions;e.contentIds=r,e.contentRevisions=a}return e.contents=resolveViewContents(e.authoring),e}const Ls=M.object({...J,type:M.literal(`move_view_content`),placement:M.enum([`main`,`aside`]).describe(`The placement zone to move the content into`),target:Os.describe(`Where to place the content within that placement zone`)}).strict(),Rs=defineOperation({type:`move_view_content`,summary:`Reorders or moves a content to a different placement; the aside rule applies.`,schema:Ls,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)}}})}),zs=M.object({...q,type:M.literal(`update_view_metadata`),changes:M.object({label:M.string().min(1).optional().describe(`New label for the view`),description:M.string().optional().describe(`New description for the view`),icon:O.nullable().optional().describe(`New icon; null clears it`)}).strict().refine(e=>Object.keys(e).length>0).describe(`≥1 change`)}).strict(),Bs=defineOperation({type:`update_view_metadata`,summary:`Updates a view's label, description, or icon (null clears the icon).`,schema:zs,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}})}),Vs=M.string().refine(e=>e.trim().length>0,`API name must not be blank`),Hs=M.object({...q,type:M.literal(`rename_view`),newName:Vs.describe(`New API name for the view`)}).strict(),renameViewFocus=e=>({objectName:e.objectName,viewName:e.newName}),Us=defineOperation({type:`rename_view`,summary:`Renames a view; refused on a code-declared name — change it in the declaration.`,schema:Hs,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}))}),Ws=M.object({...J,type:M.literal(`rename_view_content`),newName:Vs.describe(`New API name for the content`)}).strict(),renameContentFocus=e=>({...viewFocus(e),contentName:e.newName}),Gs=defineOperation({type:`rename_view_content`,summary:`Renames a content; refused on a code-declared name — change it in the declaration.`,schema:Ws,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}}})}),Ks=M.object({...J,type:M.literal(`reset_view_content`)}).strict(),qs=defineOperation({type:`reset_view_content`,summary:`Resets a content to its code-declared source, if one exists.`,schema:Ks,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}})})}),Js=M.object({...q,type:M.literal(`reset_view_order`),placement:M.enum([`main`,`aside`]).describe(`The placement zone to reset to source order`)}).strict(),Ys=defineOperation({type:`reset_view_order`,summary:`Resets a placement zone's order to its code-declared source, if one exists.`,schema:Js,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}})}),Xs=M.discriminatedUnion(`type`,[As,Ns,Fs,Ls,zs,Hs,Ws,Ks,Js]),Y=[Ms,Ps,Is,Rs,Bs,Us,Gs,qs,Ys];function findObject(e,t){return e.objects.find(e=>e.id===t)}const Zs=new Set([`formula`,`rollup`]);function isComputedAttribute(e){return Zs.has(e.attributeType)}const Qs={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 Qs?Qs[e]:void 0}function requireObject(e,t){let n=findObject(e,t);if(!n)throw new DraftRefusalError(`Object "${t}" is not in the draftable state`,K);return n}function configOf(e){return e.config??{}}function relationTargets(e){let t=configOf(e).targets;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.object==`string`):[]}function relationTargetObjectName(e){let t=relationTargets(e).filter(e=>e.object!==`*`);return t.length===1?t[0]?.object:void 0}function toCompileAttribute(e){let t=configOf(e),n=e.attributeType,r={name:e.name,type:n,id:e.id},i=t.optionsSource;if(n===`relation`){let n=relationTargetObjectName(e);return{...r,...t.cardinality===`one`||t.cardinality===`many`?{cardinality:t.cardinality}:{},...n===void 0?{}:{targetObjectName:n},targets:relationTargets(e)}}if(n===`formula`)return{...r,...t.returnType===void 0?{}:{returnType:t.returnType},...i===void 0?{}:{optionsSource:i}};if(n===`rollup`){let e=rollupReturnTypeOf(t.function);return{...r,...e===void 0?{}:{returnType:e},...i===void 0?{}:{optionsSource:i}}}return n===`select`||n===`status`||n===`multiselect`?{...r,...Array.isArray(t.options)?{options:t.options}:{}}:r}function toCompileObject(e,t){return{objectName:e.name,attributes:t.filter(t=>t.objectId===e.id).map(toCompileAttribute)}}function computedCompileSchemaOf(e,t){return{...toCompileObject(requireObject(e,t),e.attributes),relatedObjects:Object.fromEntries(e.objects.map(t=>[t.name,toCompileObject(t,e.attributes)]))}}function toRollupAttribute(e){return{id:e.id,name:e.name,label:e.label,type:`rollup`,...configOf(e)}}function asValidationError(e){try{return e()}catch(e){throw e instanceof ComputedFormulaCompileError?new D(e.message,[]):e}}function computedPlanOf(e,t){let n=computedCompileSchemaOf(e,t.objectId);return asValidationError(()=>compilePlan(t,n))}function compilePlan(e,t){if(e.attributeType===`rollup`)return compileRollupAttribute(toRollupAttribute(e),t);let n=configOf(e);return compileComputedFormula({attributeName:e.name,expression:String(n.expression??``),returnType:n.returnType,schema:t})}function assertAcyclicComputed(e){asValidationError(()=>assertAcyclicComputedDependencies(e.map(e=>({attributeName:e.attributeName,dependencies:e.dependencies}))))}function dependencyNames(e,t){switch(e.kind){case`local`:case`computed`:return e.attributeName===t;case`relation`:return e.relationName===t;case`options`:return!1;default:return e}}function compilablePlansOf(e,t){let n=computedCompileSchemaOf(e,t),r=[];for(let i of e.attributes)if(i.objectId===t&&isComputedAttribute(i))try{r.push(compilePlan(i,n))}catch(e){if(!(e instanceof ComputedFormulaCompileError))throw e}return r}function dependentsOf(e,t,n){let r=requireObject(e,t),i=[];for(let r of compilablePlansOf(e,t))r.attributeName!==n&&r.dependencies.some(e=>dependencyNames(e,n))&&i.push(r.attributeName);for(let a of e.objects)if(a.id!==t)for(let t of compilablePlansOf(e,a.id))t.dependencies.some(t=>{if(t.kind!==`relation`||t.targetAttributeName!==n)return!1;let i=e.attributes.find(e=>e.objectId===a.id&&e.name===t.relationName&&e.attributeType===`relation`);return i!==void 0&&relationTargetObjectName(i)===r.name})&&i.push(`${a.name}.${t.attributeName}`);return i}const $s={listed:!0,host:!0};function arrayOf(e){return Array.isArray(e)?e:[]}function isRecord(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rewriteAttributeNames(e,t,n){let r=!1,swap=e=>{if(typeof e!=`string`)return e;let t=n(e);return t!==e&&(r=!0),t},swapKey=e=>{if(!isRecord(e)||typeof e.attribute!=`string`)return e;let t=swap(e.attribute);return t===e.attribute?e:{...e,attribute:t}};if(e.type===`collection`&&t.listed){let t={...e};return Array.isArray(e.columns)&&(t.columns=e.columns.map(e=>typeof e==`string`?swap(e):e)),Array.isArray(e.displayAttributes)&&(t.displayAttributes=e.displayAttributes.map(swap)),Array.isArray(e.sorts)&&(t.sorts=e.sorts.map(swapKey)),typeof e.descriptionAttribute==`string`&&(t.descriptionAttribute=swap(e.descriptionAttribute)),typeof e.groupByAttribute==`string`&&(t.groupByAttribute=swap(e.groupByAttribute)),isRecord(e.columnSizing)&&(t.columnSizing=Object.fromEntries(Object.entries(e.columnSizing).map(([e,t])=>[swap(e),t]))),isRecord(e.filters)&&Array.isArray(e.filters.rules)&&(t.filters={...e.filters,rules:e.filters.rules.map(swapKey)}),r?t:e}if(e.type===`form`&&t.host){let t=arrayOf(e.groups).map(e=>isRecord(e)&&Array.isArray(e.fields)?{...e,fields:e.fields.map(swapKey)}:e);return r?{...e,groups:t}:e}if(e.type===`richtext`&&t.host){let t={...e,attribute:swap(e.attribute)};return e.titleAttribute!==void 0&&(t.titleAttribute=swap(e.titleAttribute)),r?t:e}return e}function namesIn(e,t,n){let r=!1;return rewriteAttributeNames(e,t,e=>(e===n&&(r=!0),e)),r}function namesReachedThrough(e){switch(e.type){case`collection`:return isRecord(e.source)?[e.source.relation]:[];case`documents`:return arrayOf(e.relations);case`emails`:case`meetings`:return arrayOf(e.emailAttributes);default:return[]}}function contentNamesAttribute(e,t){if(!isRecord(e)||typeof e.type!=`string`)return!1;let n=e;return namesIn(n,$s,t)||namesReachedThrough(n).includes(t)}function listedObjectName(e,t,n){let r=collectionSourceAddressOf(n);if(r===void 0)return;if(r.kind!==`related`)return r.object;let i=hostRelation(e,t,r.relation);return i===void 0?void 0:relationTargetObjectName(i)}function hostRelation(e,t,n){let r=e.objects.find(e=>e.name===t);return e.attributes.find(e=>e.objectId===r?.id&&e.name===n&&e.attributeType===`relation`)}function partsOf(e,t,n,r){return namingParts(n,t.object,n.type===`collection`?listedObjectName(e,t.object,n.source):void 0,r)}function namingParts(e,t,n,r){return{listed:e.type===`collection`&&n===r,host:t===r}}function renameAttributeInContent(e,t,n,r){return rewriteAttributeNames(e,namingParts(e,t,n,r.object),e=>e===r.from?r.to:e)}function viewNamesAttribute(e,t,n,r){return!t.derived&&Object.values(t.authoring.contents).some(i=>[i.sourceDefinition,i.workspaceDefinition].some(i=>i!==null&&namesIn(i,partsOf(e,t,i,n),r)))}function renameAttributeInView(e,t,n,r,i){if(t.derived)return t;let map=e=>e===r?i:e,rewrite=r=>r===null?null:rewriteAttributeNames(r,partsOf(e,t,r,n),map),a={...t.contentRevisions},o=!1,s=Object.fromEntries(Object.entries(t.authoring.contents).map(([e,t])=>{let n=rewrite(t.sourceDefinition),r=rewrite(t.workspaceDefinition);return n===t.sourceDefinition&&r===t.workspaceDefinition?[e,t]:(o=!0,Object.hasOwn(a,e)&&(a[e]+=1),[e,{...t,sourceDefinition:n,workspaceDefinition:r}])}));if(!o)return t;let c={...t.authoring,contents:s};return{...t,authoring:c,contents:resolveViewContents(c),revision:t.revision+1,contentRevisions:a}}function unrenamableUse(e,t,n,r){if(t.derived)return;let i=t.object===n;for(let[a,o]of Object.entries(t.authoring.contents))for(let s of[o.sourceDefinition,o.workspaceDefinition])if(s!==null&&(s.type===`collection`?reachesThrough(t.object,s,n,r)||mayList(e,t,s,n,r):i&&namesReachedThrough(s).includes(r)))return`content "${a}"`}function reachesThrough(e,t,n,r){let i=sourcedAttributeOf(e,t);return i?.object===n&&i.attribute===r}function mayList(e,t,n,r,i){if(n.type!==`collection`)return!1;let a=collectionSourceAddressOf(n.source);if(a?.kind!==`related`)return!1;let o=hostRelation(e,t.object,a.relation);return o===void 0||relationTargetObjectName(o)!==void 0?!1:relationTargets(o).some(e=>e.object===r||e.object===`*`)&&namesIn(n,{listed:!0,host:!1},i)}function refusalFor(e,t){let n=e.reason===`kanban-grouping`?`attribute "${e.attribute}" groups kanban content "${e.content}" of view "${t}"; change its grouping or remove the content first`:`removing attribute "${e.attribute}" would leave view "${t}" without a main content (content "${e.content}" is sourced on it); add another main content first`;return new D(n,[])}function draftListedObjectResolver(e){return(t,n)=>n.type===`collection`?listedObjectName(e,t.object,n.source):t.object}function cascadeAttributeRemoval(e,t){let n=e.views.filter(e=>!e.derived),r=planAttributeRemoval(n,t.map(t=>({object:requireObject(e,t.objectId).name,attribute:t.name})),draftListedObjectResolver(e)),viewOf=e=>n.find(t=>t.object===e.object&&t.name===e.view),[i]=r.blocked;if(i!==void 0)throw refusalFor(i,viewOf(i)?.id??i.view);let a=new Map,cloneOf=e=>{let t=viewOf(e);if(t===void 0)return;let n=a.get(t)??structuredClone(t);return a.set(t,n),n};for(let e of r.scrubbed){let t=cloneOf(e),n=t?.authoring.contents[e.content];t&&n&&(n.workspaceDefinition=storedContentDefinition(e.definition),Object.hasOwn(t.contentRevisions,e.content)&&(t.contentRevisions[e.content]+=1))}for(let e of r.dropped){let t=cloneOf(e);t&&dropViewContent(t,e.content)}return e.views.map(e=>{let t=a.get(e);return t===void 0?e:{...t,contents:resolveViewContents(t.authoring),revision:e.revision+1}})}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 emptyDraftViewsFor(e){let[t,n]=defaultViewsFor(e,[]),empty=e=>({...e,contents:[],authoring:workspaceViewAuthoring([]),contentIds:{},contentRevisions:{}});return[empty(t),empty(n)]}function regenerateDerived(e,t,n){return e.contents.length===0?e:derivedView(e.context,e.id,t,n)}function isGeneratedDraftRelation(e){return e.attributeType===`relation`&&toAttribute(e).metadata?.relationGenerated===!0}function pairedDraftAttributes(e,t){let n=bilateralDeclarationOf(t);if(!n)return[t];let r=e.objects.find(e=>e.id===t.objectId),i=e.objects.find(e=>e.name===n.object),a=e.attributes.find(e=>e.objectId===i?.id&&e.name===n.attribute);if(!a||a===t)return[t];let o=bilateralDeclarationOf(a);return o&&o.object===r?.name&&o.attribute===t.name?[t,a]:[t]}function reconcileDraftRelationAttribute(e,t,n,r,i=!1){let a=toAttribute(t),o=r&&toAttribute(r),s=r&&bilateralDeclarationOf(r),c=bilateralDeclarationOf(t);if(s&&(s.object!==c?.object||s.attribute!==c?.attribute))throw new D(`Changing a bilateral address requires removing the existing pair first`,[]);if(a.type!==`relation`||!a.bilateral)return e;let l=e.objects.find(e=>e.id===t.objectId),u=e.objects.find(e=>e.name===a.bilateral?.object);if(!(l&&u))throw new D(`Both objects must exist before materializing a relation pair`,[]);let d=`${l.name}.${t.name}`,f=a.bilateral.attribute,p=`${u.name}.${f}`,m=e.attributes.find(e=>e.objectId===u.id&&e.name===f),h=o?.metadata?.relationPairId,g=typeof h==`string`?h:draftEntityIdFor(`relation-pair`,`${n}:${t.id}`),_=[d,p].sort(),ee=typeof h==`string`?{id:g,addresses:_,ownerAddress:o?.type===`relation`&&o.bilateral?.storageOwner===!1?p:d,generatedAddresses:[],...d===p?{symmetric:!0}:{}}:void 0,v=reconcileRelationAttributes({objects:[...new Map([l,u].map(e=>[e.id,e])).values()].map(e=>({name:e.name,attributes:[t,...m&&m.id!==t.id?[m]:[]].filter(t=>t.objectId===e.id).map(toAttribute)})),existingPairs:ee?[ee]:[],...r&&!i?{explicitAddresses:[d],propertyEditAddresses:[d]}:{},nextPairId:()=>g}),y=new Map;for(let n of v.objects){let a=n.name===l.name?l.id:u.id;for(let o of n.attributes){let n=e.attributes.find(e=>e.objectId===a&&e.name===o.name),s=n?.id===t.id?r??n:n,c={...preserveDeclarationHints(o,n&&toAttribute(n)),metadata:{...o.metadata,...s&&isGeneratedDraftRelation(s)&&!(i&&n?.id===t.id)||!n?{relationGenerated:!0}:{}},id:n?.id??draftEntityIdFor(`relation-attribute`,`${g}:${a}:${o.name}`),...n?{}:{order:e.attributes.filter(e=>e.objectId===a).length}};y.set(`${a}.${o.name}`,toDraftableAttribute(c,a))}}let b=e.attributes.map(e=>{let t=`${e.objectId}.${e.name}`,n=y.get(t);return y.delete(t),n??e});return b.push(...y.values()),{...e,attributes:b,views:e.views.map(e=>{let t=[l,u].find(t=>t.name===e.object);return e.derived&&t?regenerateDerived(e,t,b):e})}}function preserveDeclarationHints(e,t){if(e.type!==`relation`||!e.bilateral||t?.type!==`relation`||!t.bilateral)return e;let{label:n,cardinality:r,...i}=e.bilateral;return{...e,bilateral:{...i,...t.bilateral.label===void 0?{}:{label:n},...t.bilateral.cardinality===void 0?{}:{cardinality:r}}}}function withDerivedViews(e,t,n){return{...e,attributes:[...n],views:e.views.map(e=>e.derived&&e.object===t.name?regenerateDerived(e,t,n):e)}}function objectFocus(e){return{objectId:e.objectId}}function recordFocus(e){return{objectId:e.objectId,recordId:e.recordId}}function attributeFocus(e){return{objectId:e.objectId,attributeName:e.name}}function existingAttributeFocus(e){return{objectId:e.objectId,attributeName:e.attribute}}function firstChangedProperty(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}function 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={...Ds,objectId:M.string().uuid().describe(`The object this operation acts on`)},ec=defineOperation({type:`add_object`,summary:`Creates an object: kebab-case plural name, icon from search_icons; folds in empty default_list/default_detail views for explicit content; reserved names are native objects.`,schema:M.object({...X,objectId:M.string().uuid().describe(`Stable id for the new object; the server mints one when omitted`),type:M.literal(`add_object`),name:pt.describe("kebab-case plural API name (`purchase-orders`)"),label:M.string().min(1).describe(`Label people see`),icon:M.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,...emptyDraftViewsFor(n)]}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Crée l'objet « ${e.label} »`}),tc=M.object({...X,type:M.literal(`update_object`),changes:M.object({label:M.string().min(1).optional().describe(`New label`),icon:M.string().min(1).optional().describe(`New icon name from search_icons`),pluralLabel:M.string().optional().describe(`New label for many records; "" clears it`),description:M.string().optional().describe(`What this object holds`),labelExpression:F.optional().describe(`Titles every record; syntax in <expressions>`),embeddingExpression:M.literal(``).or(F).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}),nc=defineOperation({type:`update_object`,summary:`Updates an object's label, icon, pluralLabel, description, labelExpression, embeddingExpression.`,schema:tc,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)}),rc={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])=>rc[e]?.(String(t))).filter(e=>e!==void 0);return t.length>0?t.join(` · `):`Modifie l'objet`}function inboundRelationAttributes(e,t){let n=e.objects.find(e=>e.id===t)?.name;return n===void 0?[]:e.attributes.filter(e=>e.objectId!==t&&e.attributeType===`relation`&&relationTargets(e).some(e=>e.object===n))}const ic=defineOperation({type:`remove_object`,summary:`Removes an object; refused while a relation attribute targets it — remove it first.`,schema:M.object({...X,type:M.literal(`remove_object`)}),apply:(e,t)=>{requireObject(e,t.objectId);let n=e.objects.find(e=>e.id===t.objectId)?.name,r=inboundRelationAttributes(e,t.objectId);if(r.length>0){let ownerOf=t=>e.objects.find(e=>e.id===t.objectId)?.name;throw new DraftRefusalError(`object "${n}" is targeted by attribute "${ownerOf(r[0])}.${r[0].name}"; remove that attribute first`,{kind:`object-targeted`,blockers:r.flatMap(e=>{let t=ownerOf(e);return t?[{ownerObjectName:t,attribute:e.name}]:[]})})}return{...e,objects:e.objects.filter(e=>e.id!==t.objectId),attributes:e.attributes.filter(e=>e.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(e=>e.objectId!==t.objectId),views:e.views.filter(e=>e.object!==n)}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Supprime l'objet ${e.objectId}`}),ac=sr;function assertConfigParses(e,t){try{zt(e,t)}catch(e){throw e instanceof D?new D(e.message,e.errors.map(e=>({...e,path:[`config`,...e.path??[]]}))):e}}const oc=M.object({...X,type:M.literal(`add_attribute`),attributeId:M.string().min(1),name:Kt,label:M.string().min(1),attributeType:M.enum(ac),config:M.record(M.string(),M.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}}),sc=Kt.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),cc={...Ds,type:M.literal(`add_attribute`),attributeId:M.string().min(1).describe(`Stable attribute id`),name:sc,label:M.string().min(1).describe(`Label people see`)},lc=Object.fromEntries(Yt.map(e=>[e,!0])),uc=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],dc=M.object(uc.reduce((e,t)=>(Object.assign(e,Lt(t).omit(lc).shape),e),{})).strict(),fc=ac.filter(e=>!uc.includes(e)),pc=Object.fromEntries(uc.map(e=>[e,new Set(Object.keys(Lt(e).omit(lc).shape))])),mc=Jt(pc,`config key`);function refuseForeignSimpleConfigKeys(e,t){mc(e.attributeType,e.config,t,[`config`])}function wireConfigFor(e){let t=Lt(e).omit(lc);return(e===`relation`||e===`document`?t.extend({properties:Zt.optional()}):t).strict()}const hc=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:oc,wire:M.discriminatedUnion(`attributeType`,[M.object({...cc,objectId:M.string().uuid(),attributeType:M.enum(uc).describe(`Attribute type`),config:dc.optional().describe(`Configuration of a simple attribute (text, number, date…)`)}).strict().superRefine(refuseForeignSimpleConfigKeys),...fc.map(e=>M.object({...cc,objectId:M.string().uuid(),attributeType:M.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} »`}),gc={...X,attribute:Kt.describe(`The attribute's API name on this object`)};function requireAttribute(e,t,n,r){let i=requireObject(e,t);if(n===void 0)throw new D(`${r} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let a=e.attributes.find(e=>e.objectId===t&&e.name===n);if(!a)throw new DraftRefusalError(`Attribute "${n}" is not on object "${t}"`,K);return{object:i,attribute:a}}const _c=defineOperation({type:`update_attribute`,summary:"Updates an attribute's label, or replaces its whole config. A published config can't change, except `bilateral` alone (every other key identical) to pair a published relation with its inverse; otherwise add a new attribute and migrate values.",schema:M.object({...gc,type:M.literal(`update_attribute`),changes:M.object({label:M.string().min(1).optional().describe(`New label`),config:M.record(M.string(),M.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} »`}),vc=M.object({...gc,type:M.literal(`remove_attribute`),dropSampleValues:M.literal(!0).optional().describe(`true clears the removed key from this object's sample records instead of refusing on them`)});function withoutRemovedValues(e,t){let n=t.filter(t=>t.objectId===e.objectId);if(!n.some(t=>t.name in e.values))return e;let r={...e.values};for(let e of n)delete r[e.name];return{...e,values:r}}const yc=defineOperation({type:`remove_attribute`,summary:`Removes an attribute and view contents sourced on it; refused on samples, formula/rollup dependents, kanban grouping or last main content.`,schema:vc,apply:(e,t)=>{let{attribute:n}=requireAttribute(e,t.objectId,t.attribute,`remove_attribute`),r=pairedDraftAttributes(e,n);for(let n of r){let[r]=dependentsOf(e,n.objectId,n.name);if(r!==void 0)throw new D(`attribute "${n.name}" is used by "${r}"; remove that first`,[]);let i=e.sampleRecords.find(e=>e.objectId===n.objectId&&n.name in e.values);if(i&&!t.dropSampleValues)throw new D(`Attribute "${n.name}" is still used by sample record "${i.id}" — resend with dropSampleValues: true to clear it from the samples`,[])}let i=e.attributes.filter(e=>!r.includes(e)),a={...e,views:cascadeAttributeRemoval(e,r),sampleRecords:t.dropSampleValues?e.sampleRecords.map(e=>withoutRemovedValues(e,r)):e.sampleRecords};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} »`}),bc=M.object({...gc,type:M.literal(`rename_draft_attribute`),name:sc});function assertRenamable(e,t,n){let r=n.name,[i]=dependentsOf(e,t.id,r),a=e.attributes.find(e=>{let n=e.config?.optionsSource;return n?.objectName===t.name&&n.attributeName===r}),o=i??(a&&`${e.objects.find(e=>e.id===a.objectId)?.name}.${a.name}`);if(o!==void 0)throw new D(`attribute "${r}" is used by "${o}"; it cannot be renamed while in use`,[]);let s=bilateralDeclarationOf(n),c=e.attributes.find(e=>{let n=bilateralDeclarationOf(e);return n?.object===t.name&&n.attribute===r}),l=s===void 0?c&&`${e.objects.find(e=>e.id===c.objectId)?.name}.${c.name}`:`${s.object}.${s.attribute}`;if(l!==void 0)throw new D(`attribute "${r}" is paired with "${l}"; unpair it first`,[]);let u=[[`label expression`,t.labelExpression],[`embedding expression`,t.embeddingExpression]];for(let[e,n]of u)if(n&&extractAttributeNames(n).includes(r))throw new D(`attribute "${r}" is used by the ${e} of "${t.name}"; change it first`,[]);for(let n of e.views){let i=unrenamableUse(e,n,t.name,r);if(i!==void 0)throw new D(`attribute "${r}" is used by view "${n.id}" (${i}); rename it before using it there`,[])}}const xc=defineOperation({type:`rename_draft_attribute`,summary:`Renames a draft-added attribute; views and samples follow.`,schema:bc,apply:(e,t)=>{let{object:n,attribute:r}=requireAttribute(e,t.objectId,t.attribute,`rename_draft_attribute`);if(t.name===r.name)throw new D(`attribute "${t.attribute}" is already named "${t.name}"`,[]);if(e.attributes.some(e=>e.objectId===t.objectId&&e.name===t.name))throw new D(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);assertRenamable(e,n,r);let i={...r,name:t.name},a=e.attributes.map(e=>e===r?i:e);return withDerivedViews({...e,views:e.views.map(r=>renameAttributeInView(e,r,n.name,t.attribute,t.name)),sampleRecords:e.sampleRecords.map(e=>{if(e.objectId!==t.objectId||!Object.hasOwn(e.values,t.attribute))return e;let n=Object.fromEntries(Object.entries(e.values).map(([e,n])=>[e===t.attribute?t.name:e,n]));return{...e,values:n}})},n,a)},focus:attributeFocus,presentation:definePresentation(attributeFocus,`local`),describe:e=>`Renomme le nom technique « ${e.attribute} » en « ${e.name} »`});function assertSampleValue(e,t,n,r){let i=toAttribute(n);try{Nn(i)}catch{return}let a=Fn(i,r);if(a.success)return;let o=a.errors??[],s=`Sample record "${e}" has an invalid value for "${t}": ${o.map(e=>e.path.length>1?`${e.path.join(`.`)}: ${e.message}`:e.message).join(`, `)}`,c=o.map(e=>({path:e.path,message:e.message}));throw n.attributeType===`relation`&&carriesNonRecordId(r)?new DraftRefusalError(s,{kind:`sample-relation-value`},c):new D(s,c)}function assertRequiredCovered(e,t,n){if(t.config?.required===!0&&t.config?.defaultValue===void 0&&!(t.name in n&&n[t.name]!==void 0))throw new D(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}const Sc=M.guid();function carriesNonRecordId(e){let t=Array.isArray(e)?e:[e],n=relationValueIds(e);return n.length<t.length||n.some(e=>!Sc.safeParse(e).success)}function relationValueIds(e){return(Array.isArray(e)?e:[e]).flatMap(e=>{if(typeof e==`string`)return[e];if(typeof e==`object`&&e){let t=e.id;if(typeof t==`string`)return[t]}return[]})}function assertUnknownSampleReference(e,t,n,r){n.attributeType===`relation`&&r!=null&&assertSampleTarget(e,t,relationTargetObjectName(n),r)}function assertSampleTarget(e,t,n,r){let i=e.objects.find(e=>e.name===n);if(!i)return;let a=e.views.some(e=>e.id===defaultViewIdsFor(i.id).list);for(let n of relationValueIds(r)){let r=e.sampleRecords.find(e=>e.id===n);if(r?.objectId!==i.id&&(r!==void 0||a))throw new DraftRefusalError(`sample record "${t}" references unknown sample "${n}"`,{kind:`sample-relation-value`})}}const Cc=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:M.object({...X,type:M.literal(`add_sample_record`),recordId:M.string().uuid().describe(`Minted by the server when omitted`),values:M.record(M.string(),M.unknown()).describe("Attribute name → value; currency is `{code,value}`, relation is a record id or name minted here"),publication:M.enum([`preview`,`requested-data`]).optional().describe(`preview = display-only; requested-data = real records asked for`)}),apply:(e,t)=>{let n=requireObject(e,t.objectId);if(e.sampleRecords.some(e=>e.id===t.recordId))throw new D(`Sample record "${t.recordId}" already exists`,[]);let r=new Map(e.attributes.filter(e=>e.objectId===t.objectId).map(e=>[e.name,e]));for(let[i,a]of Object.entries(t.values)){let o=r.get(i);if(!o)throw new DraftRefusalError(`Sample record "${t.recordId}" uses unknown attribute "${i}"`,{kind:`sample-unknown-attribute`,objectName:n.name,attributeNames:[...r.keys()]});if(isComputedAttribute(o))throw new D(`attribute "${o.name}" is computed and cannot be set on a sample record`,[]);assertUnknownSampleReference(e,t.recordId,o,a),assertSampleValue(t.recordId,i,o,a)}for(let e of r.values())assertRequiredCovered(t.recordId,e,t.values);return{...e,sampleRecords:[...e.sampleRecords,{id:t.recordId,objectId:t.objectId,values:t.values,...t.publication===void 0?{}:{publication:t.publication}}]}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Ajoute un exemple`});function relationNamesOf(e,t){return new Set([...e.attributes.filter(e=>e.objectId===t&&e.attributeType===`relation`).map(e=>e.name)])}function assertSampleNotReferenced(e,t){for(let n of e.sampleRecords){if(n.id===t)continue;let r=relationNamesOf(e,n.objectId);for(let[e,i]of Object.entries(n.values))if(r.has(e)&&relationValueIds(i).includes(t))throw new D(`sample record "${t}" is referenced by sample record "${n.id}"; remove that first`,[])}}const Z=[ec,nc,ic,hc,_c,yc,xc,Cc,defineOperation({type:`remove_sample_record`,summary:`Removes a sample record; refused while another sample references it.`,schema:M.object({...X,type:M.literal(`remove_sample_record`),recordId:M.string().min(1).describe(`recordId of the sample to remove`)}),apply:(e,t)=>{if(!e.sampleRecords.some(e=>e.id===t.recordId&&e.objectId===t.objectId))throw new DraftRefusalError(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,K);return assertSampleNotReferenced(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(e=>e.id!==t.recordId)}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Retire un exemple`})];function build(){let e=new Map;for(let t of[...Z,...Y]){if(e.has(t.type))throw new w(`architect operation`,t.type);e.set(t.type,t)}return e}const wc=build(),Tc=[...wc.keys()];function defOf(e){let t=wc.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=wc.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 Ec=`bilateral`;function frozenPart(e){if(!e||typeof e!=`object`)return A({});let{[Ec]:t,...n}=e;return A(n)}function isPublishedConfigChangeAllowed(e,t){return frozenPart(e)===frozenPart(t)}const pair=e=>M.tuple([M.literal(e),M.string()]),Dc=M.union([M.tuple([M.literal(`content`),M.string(),M.string(),M.string()]),M.tuple([M.literal(`view`),M.string(),M.string()]),M.tuple([M.literal(`attribute`),M.string(),M.string()]),M.tuple([M.literal(`sample`),M.string(),M.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 renamedFromTarget(e){return e.type!==`rename_draft_attribute`||typeof e.objectId!=`string`||typeof e.attribute!=`string`?null:{objectId:e.objectId,attributeName:e.attribute}}function renamedAttributeKey(e){let t=renamedFromTarget(e);return t===null?null:proposalTargetKey(t)}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=Xs.parse(r),t=proposalTargetKey({objectName:e.objectName,viewName:e.viewName,...e.type===`rename_view_content`?{contentName:e.contentName}:{}});t&&n.add(t)}let i=renamedAttributeKey(r);i&&n.add(i);let a=proposalTargetKey(t);if(a&&n.add(a),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 o=r.changes&&typeof r.changes==`object`?r.changes:null,s=r.type===`add_attribute`?r.config:o&&`config`in o?o.config:null;if(addBilateralDependencies(e,r,t,s,add),s&&typeof s==`object`&&`targets`in s&&Array.isArray(s.targets))for(let e of s.targets)e&&typeof e.object==`string`&&e.object!==`*`&&add(`object-name`,e.object)}return[...n]}function targetTokenOf(e){return`v2:${A(e)}`}const Oc=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=Dc.safeParse(n);if(!r.success)throw new D(`Invalid proposal target key "${t}"`,[]);let[i,a,o,s]=r.data,c=e.objects.find(e=>e.id===a);if(i===`object`)return c??null;if(i===`object-name`)return e.objects.find(e=>e.name===a)??null;if(i===`attribute-id`)return e.attributes.find(e=>e.id===a)??null;if(i===`attribute`)return e.attributes.find(e=>e.objectId===a&&e.name===o)??null;if(i===`sample`)return e.sampleRecords.find(e=>e.objectId===a&&e.id===o)??null;if(i===`object-schema`||i===`object-tree`){if(!c)return null;let t=e.attributes.filter(e=>e.objectId===a);return i===`object-schema`?{object:c,attributes:t.toSorted((e,t)=>e.name.localeCompare(t.name))}:{object:c,attributes:t,views:e.views.filter(e=>e.object===c.name),sampleRecords:e.sampleRecords.filter(e=>e.objectId===a)}}let l=e.views.find(e=>e.object===a&&e.name===o);if(!l)return null;if(i===`view`)return{id:l.id,revision:l.revision,definition:{...draftedViewDefinition(l),contents:l.contents.map(({name:e,placement:t})=>({name:e,placement:t}))}};let u=l.contents.find(e=>e.name===s);return s!==void 0&&Object.hasOwn(l.contentIds,s)?{id:l.contentIds[s],revision:l.contentRevisions[s],definition:u??null}:null}function presentationOf(e){return defOf(e).presentation(e)}function episodeImpactOf(e){let t=e.map(presentationOf);return new Set(t.map(({focus:e})=>e.viewName?JSON.stringify([e.objectName,e.viewName]):e.objectId).filter(e=>e!==void 0)).size>1||t.some(({impact:e})=>e===`structural`)?`structural`:t.some(({impact:e})=>e===`local`)?`local`:`atomic`}function snapshotArchitectTarget(e,t){let n=proposalTargetKey(t);return n===null?null:targetSnapshot(e,n)}function deriveArchitectChanges(e,t,n={extensions:[]}){let r=e;return t.map(e=>{let t=presentationOf(e),i=snapshotArchitectTarget(r,t.focus);r=applyOperations(r,[e],n);let a=snapshotArchitectTarget(r,t.focus);return{operationId:e.id,operationType:e.type,presentation:t,before:i,after:a,...e.note===void 0?{}:{note:e.note}}})}function part(e){return e.replace(/[%:/.]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function architectFocusKey(e){let t=headOf(e);if(t===null)return null;let n=e.propertyPath??[];return n.length===0?t:`${t}/${n.map(part).join(`.`)}`}function architectContentBodyKey(e){let t=architectFocusKey(e);return t===null?null:`body/${t}`}function architectFocusCandidates(e){let t=architectFocusKey(e);if(t===null)return[];let n=e.contentName?architectContentBodyKey(e):null;return n===null?[t]:[t,n]}function headOf(e){return e.viewName&&e.objectName?e.contentName?[`content`,e.objectName,e.viewName,e.contentName].map(part).join(`:`):[`view`,e.objectName,e.viewName].map(part).join(`:`):e.attributeName&&e.objectId?[`attribute`,e.objectId,e.attributeName].map(part).join(`:`):e.attributeId?[`attribute-id`,e.attributeId].map(part).join(`:`):e.recordId&&e.objectId?[`sample`,e.objectId,e.recordId].map(part).join(`:`):e.objectId?[`object`,e.objectId].map(part).join(`:`):e.objectName?[`object-name`,e.objectName].map(part).join(`:`):null}const kc={add_object:`major`,remove_object:`major`,add_view_content:`major`,replace_view_content:`major`,reset_view_content:`major`,add_attribute:`normal`,remove_attribute:`normal`,remove_view_content:`normal`,add_sample_record:`normal`,update_object:`minor`,update_attribute:`minor`,rename_draft_attribute:`minor`,update_view_metadata:`minor`,rename_view:`minor`,rename_view_content:`minor`,move_view_content:`minor`,reset_view_order:`minor`,remove_sample_record:`minor`},Ac=`normal`;function operationPace(e){return Object.hasOwn(kc,e)?kc[e]:Ac}const jc={major:{replay:4e3,live:2500},normal:{replay:2600,live:1800},minor:{replay:1400,live:1100}};function dwellForStep(e,t,n){let r=(jc[e]??jc[Ac])[t],i=900+40*(n||0);return Math.min(6e3,Math.max(r,i))}const Q=M.string().min(1),Mc=M.union([M.object({objectName:Q,viewName:Q,contentName:Q.optional()}).strict().describe(`Full configuration of a view, or of one content when contentName is given`),M.object({objectId:Q}).strict().describe(`An object with its attributes, by id`),M.object({objectName:Q}).strict().describe(`An object with its attributes`),M.object({objectId:Q,attributeName:Q}).strict().describe(`One attribute's config, by name`),M.object({objectId:Q,attributeId:Q}).strict().describe(`One attribute's config, by id`),M.object({objectId:Q,recordId:Q}).strict().describe(`One sample record`)]);function parseNamedTarget(e){let t=Mc.safeParse(e);if(!t.success)throw new D(`Invalid scoped target`,[{path:[`target`],message:`Expected exactly one named target branch`}]);return t.data}const Nc=M.object({type:M.literal(`remove_operation`),operationId:M.string().min(1).describe(`The id of a stored operation to drop from the draft`)}),Pc=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 M.discriminatedUnion(`type`,e)}function isUuidString(e){return e instanceof M.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):M.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=M.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 Fc={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of Fc[e.shape.type.value]??[]){let r=e.shape[n];r instanceof M.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)}const Ic=M.string().min(1).describe(`Object`);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,M.object({...n,objectName:Ic}).strict())})}const Lc=membersOf(Z,[Nc]),Rc=membersOf(Y),zc=unionOf(Lc),Bc=unionOf(Rc),Vc={schema:zc,view:Bc},Hc={schema:unionOf(wireMembersOf(Z,[Nc])),view:unionOf(wireMembersOf(Y))},Uc=new Map([...Z.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...Y.map(e=>[e.type,`view`])]);function familyOf(e){return Uc.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.`);let i=viewsOf(e,t,`record`);i.length>0&&i.every(e=>e.contents.length===0)&&n.push(`Object "${t.label}" has no record 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).`)}}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 Wc=[`draft_schema`],Gc=`discard_architect_draft`,Kc=`request_design_review`,qc=`get_architect_draft`,Jc=[{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:{}}}}],$=M.string().refine(e=>e.trim().length>0,`Must not be blank`),Yc=M.union([M.tuple([M.literal(`object`),$]),M.tuple([M.literal(`attribute`),$,$]),M.tuple([M.literal(`view`),$,$]),M.tuple([M.literal(`content`),$,$,$])]),Xc=M.object({label:$,pluralLabel:M.string().optional(),description:M.string().optional(),icon:O.optional(),labelExpression:M.string(),embeddingExpression:M.string().optional(),sealed:M.boolean().optional(),toleratedAttributes:M.array($).optional(),metadata:M.record(M.string(),M.unknown()).optional(),documentLayout:M.record(M.string(),M.unknown()).optional()}).strict();function failure(e){throw new D(e,[])}function definitionSchema(e){return M.custom(t=>{let n=M.record(M.string(),M.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`:Xc.parse(n);break;case`attribute`:{let e=M.enum(sr).parse(n.type);Wt(e).extend({type:M.literal(e),label:$,required:M.boolean().optional(),unique:M.boolean().optional(),icon:O.optional()}).strict().parse(n);break}case`view`:{let{contents:t,...r}=n,i=M.array($).parse(t);new Set(i).size!==i.length&&failure(`Invalid schema state: duplicate content membership`),ve.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=M.record(M.string(),M.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=M.object({modelVersion:M.literal(1),hashVersion:M.literal(1),tenant:$,sourceFingerprint:M.string().regex(/^[a-f0-9]{64}$/),entries:M.array(M.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=Yc.parse(M.object({address:M.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`?M.object({id:M.string().uuid(),updatedAt:M.string().datetime()}).strict():M.object({id:M.string().uuid(),revision:M.number().int().nonnegative()}).strict(),o=M.object({address:Yc,source:i,effective:i,status:M.enum([`source`,`runtime`,`copy`,`suppressed`]),sourceOwner:M.union([M.literal(`core`),M.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 M.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`:A(n.source)===A(n.effective)?n.status===`copy`?`copied`:null:`changed`;e&&t.push({...n,change:e})}return{modelVersion:1,tenant:e.tenant,sourceFingerprint:e.sourceFingerprint,changes:t}}export{Oc as ABSENT_TARGET_TOKEN,Tr as AGENT_AVATAR_EXPRESSIONS,wr as AGENT_AVATAR_TYPES,Fr as AGENT_MESSAGE_KIND,Pr as AGENT_NOTIFICATION_KIND,Er as AGENT_STARTERS_MAX,Dr as AGENT_STARTER_MAX_LENGTH,yr as AGENT_TASK_KINDS,no as AGENT_UI_BATCH_MAX_BYTES,ro as AGENT_UI_BATCH_MAX_ITEMS,Fi as ALLOWED_PROPERTY_TYPES,Tc as ALL_OPERATION_TYPES,Ui as ALL_PIPES,hi as ARTIFACT_FILE_ROLES,pi as ARTIFACT_KINDS,Fa as ARTIFACT_LIST_VIEW,Na as ARTIFACT_OBJECT,H as ARTIFACT_OBJECT_NAME,Ma as ARTIFACT_PREVIEW_EXTENSION,mi as ARTIFACT_RETENTIONS,Pa as ARTIFACT_VIEW,Ae as ATTRIBUTE_FILTER_OPERATORS,sr as ATTRIBUTE_TYPES,ur as AUDIT_ACTIONS,dr as AUDIT_AGENT_SESSION_METADATA_KEY,lr as AUDIT_RESOURCE_TYPES,je as AccessDeniedError,AgentBuilder,Me as AmbiguousSchemaChangeError,Ne as AttributeInUseError,Pe as AttributeNotFoundError,ar as BEHAVIOR_PROPERTIES,ti as BROWSER_IMAGE_MAX_BYTES,Ni as BYTE_UNIT_LABELS,$i as CATALOG_RESOURCES,pr as CLAIMABLE_SESSION_STATUSES,_t as COMPUTED_FUNCTIONS,go as COMPUTED_FUNCTION_METADATA,gt as COMPUTED_FUNCTION_NAMES,wo as CONNECTOR_CALLBACK_PARAM,Ai as COUNT_MODES,Qi as CUSTOM_LEVEL,ComputedFormulaCompileError,an as ComputedFormulaParseError,Fe as ConcurrentModificationError,z as ContentBuilder,ia as DB_COLUMN_FIELDS,pa as DEFAULT_AGENT_EXECUTION_CONFIG,mr as DEFAULT_APPROVAL_POLICY,Mr as DEFAULT_DAILY_ACTIVITY_DAYS,Qr as DEFAULT_DICTATION_LIMITS,Wi as DEFAULT_LABEL_FALLBACK,xi as DEFAULT_MEETING_BOT_DISPLAY_NAME,aa as DEFAULT_ROLES,sa as DEFAULT_ROLE_DESCRIPTIONS,oa as DEFAULT_ROLE_LABELS,la as DEFAULT_ROLE_PERMISSIONS,ua as DEFAULT_ROLE_REVOCATIONS,Si as DEFAULT_TENANT_SETTINGS,fn as DEFAULT_VALIDATION_MESSAGES,ni as DEVICE_CHANNEL_AUTHENTICATE_TIMEOUT_MS,ri as DEVICE_CHANNEL_IDLE_POLL_MS,ai as DEVICE_CHANNEL_KEEPALIVE_MS,ei as DEVICE_CHANNEL_MAX_FRAME_BYTES,$r as DEVICE_CHANNEL_PATH,ii as DEVICE_CHANNEL_PRESENCE_MS,oi as DEVICE_CHANNEL_WORKER_CLOSE_PROTOCOL_VIOLATION,ci as DEVICE_COMMAND_ERROR_CODES,Xr as DICTATION_FINALIZATION_TIMEOUT_MS,Wr as DICTATION_FRAME_BYTES,Kr as DICTATION_MAX_BUFFER_BYTES,Gr as DICTATION_MAX_FRAME_BYTES,qr as DICTATION_MAX_TRANSCRIPT_BYTES,Zr as DICTATION_MODEL_ID,Yr as DICTATION_PREPARATION_TIMEOUT_MS,Ur as DICTATION_SAMPLE_RATE,Jr as DICTATION_TICKET_TTL_MS,Gc as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,Pi as DOCUMENT_SYSTEM_ATTRIBUTES,ac as DRAFTABLE_ATTRIBUTE_TYPES,Pc as DRAFT_BATCH_LIMIT,Es as DRAFT_OBJECT_SETTINGS,Jc as DRAFT_SCHEMA_INPUT_EXAMPLES,Wc as DRAFT_WRITE_TOOL_NAMES,ja as DRIVE_LIST_VIEW,ka as DRIVE_OBJECT,V as DRIVE_OBJECT_NAME,Aa as DRIVE_VIEW,DeviceChannelProtocolError,fi as DeviceChannelServerFrameSchema,di as DeviceChannelWorkerFrameSchema,DraftRefusalError,w as DuplicateError,Bi as EMPTY_VALUE_PLACEHOLDER,ji as ESTIMATED_COUNT_CAP,No as FAKE_MEETING_BOT_SIGNATURE_HEADER,Vc as FAMILY_INPUTS,Hc as FAMILY_WIRE_INPUTS,vi as FORM_FORBIDDEN_ATTRIBUTE_TYPES,FlagRegistry,FlagService,Ie as ForbiddenError,FormBuilder,FormRegistry,FormRowBuilder,FormStepBuilder,qc as GET_ARCHITECT_DRAFT_TOOL_NAME,ga as GroupBuilder,ir as IDENTITY_PROPERTIES,ki as IMAGE_FORMATS,vr as INFERENCE_REASONING_OPTIONS,xr as INFERENCE_ROUTING_MODES,_r as INFERENCE_SPEEDS,Ga as INVENTORY_LIMIT,Le as InvalidPermissionGrantError,jr as LAST_RUN_ERROR_MAX_LENGTH,Mt as LIST_VIEW_TAB_VISIBILITIES,io as LIVE_EVENT_TYPES,n as LOCATION_FILTER_PROPERTIES,Do as MAILBOX_LIST_MODES,ko as MAIL_DRAFT_BODY_MAX_CHARS,Ao as MAIL_SUBJECT_MAX_CHARS,Nr as MAX_DAILY_ACTIVITY_DAYS,gi as MAX_PRESET_DEPTH,Lr as MAX_TODOS,zr as MAX_TODO_DESCRIPTION_CHARS,Rr as MAX_TODO_ID_CHARS,W as MEETING_ATTRIBUTES,Ra as MEETING_DETAIL_VIEW_ID,Ha as MEETING_LIST_VIEW,Ia as MEETING_LIST_VIEW_ID,Ba as MEETING_OBJECT,U as MEETING_OBJECT_NAME,Va as MEETING_VIEW,La as MEETING_WRITE_SOURCE,Oa as MEMORY_LIST_VIEW,Ta as MEMORY_OBJECT,Da as MEMORY_VIEW,ra as MIXED_LEVEL,To as McpOAuthCompletionMode,Re as MemoryNotFoundError,MultiRelationAttributeBuilder,Vr as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,Hr as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,Nt as NATIVE_OBJECT_NAMES,Qn as NOTIFICATION_INBOX_STATES,Yn as NOTIFICATION_KINDS,Xn as NOTIFICATION_PRIORITIES,Zn as NOTIFICATION_SENSITIVITIES,rr as NOTIFICATION_TYPES_V1,nr as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,er as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,tr as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,$n as NOTIFICATION_WORK_STATES,Zi as NO_ACCESS,Po as NO_RECORDING,g as NO_VALUE_OPERATORS,Sn as NonJsonValueError,NoopGeocodingAdapter,ze as NotFoundError,Be as NotImplementedError,I as OBJECT_GRANT,pt as OBJECT_NAME_SCHEMA,kr as OPEN_TOOL_PART_STATES,kc as OPERATION_PACE,wc as OPERATION_REGISTRY,o as OPERATORS_BY_TYPE,xo as OPERATOR_SPECS,ObjectBuilder,Ve as ObjectNotFoundError,He as ObjectReferencedError,Ue as OrphanSystemAttributeError,jc as PACE_DWELL_MS,ta as PERMISSION_ACTIONS,L as PERMISSION_CAPABILITIES,Xi as PERMISSION_CATALOG,Hi as PIPES_WITH_ARGS,qi as PREFERRED_NAME_MAX_LENGTH,or as PRESENTATION_PROPERTIES,Eo as PROVIDER_DRAFT_LABEL,gr as PROVIDER_NAMES,Ec as PUBLISHED_CONFIG_EXCEPTION,We as ProtectedResourceError,Ge as ProtectedRoleError,Ii as QUALIFIED_SEPARATOR,Mi as QUOTA_KEYS,_i as RECENT_ACTIVITY_LEDGER_LIMIT,jo as RECORDING_OVERRIDES,Mo as RECORDING_POLICIES,yi as RECORD_ACCESS_ROLES,bi as RECORD_ACCESS_SOURCES,Yi as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,cr as RELATION_TARGET_ANY,ce as REMOVED_OPERATOR_REPLACEMENTS,Nc as REMOVE_OPERATION_SCHEMA,Oo as REPLY_MODES,Kc as REQUEST_DESIGN_REVIEW_TOOL_NAME,yt as RESERVED_ATTRIBUTE_NAMES,xt as RESERVED_OBJECT_NAMES,Qt as RESOURCE_VISIBILITIES,Sr as ROUTING_PRICE_CEILINGS,Ke as RealtimeDeliveryError,qe as RealtimeRateLimitedError,Je as RealtimeSubscriptionError,Ye as RecordNotFoundError,Xe as RecordReferencedError,Ze as RepositoryError,Qe as ReservedObjectNameError,$e as RoleNotFoundError,At as SCHEMA_LIMITS,Z as SCHEMA_OPERATIONS,zc as SCHEMA_OPERATION_INPUT,Io as SCHEMA_SOURCE_ID_PATTERN,Lo as SCHEMA_SOURCE_RETYPE_FROM,Cr as SESSION_INFERENCE_PATCH_KEYS,Br as SESSION_STATE_STREAM_ID,fr as SESSION_TERMINAL_STATUSES,Vi as SIMPLE_PIPES,tn as SIMPLE_PROPERTY_TYPES,xa as SKILL_CONTENT_TEMPLATE,wa as SKILL_LIST_VIEW,Sa as SKILL_OBJECT,Ca as SKILL_VIEW,ma as STANDARD_SCHEMA_VENDOR,ke as SYNONYM_ALIASES,re as SYSTEM_ATTRIBUTES,_ as SYSTEM_ATTRIBUTE_I18N_KEYS,bt as SYSTEM_FIELD_NAMES,ue as SYSTEM_FILTER_ATTRIBUTE_TYPES,Ar as SYSTEM_PART_CODES,T as SchemaError,E as SchemaErrorCode,et as SearchBackendError,SingleRelationAttributeBuilder,tt as StorageError,nt as SyncCascadeError,rt as SyncConflictError,it as SyncError,at as SystemEntityImmutableError,br as TASK_DEMAND_LEVELS,Ci as TENANT_INVITATION_DEFAULT_TTL_MS,Ti as TENANT_INVITATION_MAX_TTL_MS,wi as TENANT_INVITATION_MIN_TTL_MS,Ei as TENANT_INVITATION_RESEND_INTERVAL_MS,ln as TEXT_FORMAT_PATTERNS,Co as TODAY_DEFAULT,hr as TODO_PLAN_STATUSES,Ir as TODO_STATUSES,Or as TOOL_APPROVAL_STATES,Li as TOOL_NAME_SEPARATOR,Di as USER_STATUSES,Oi as USER_WORK_POSTURES,Y as VIEW_OPERATIONS,Bc as VIEW_OPERATION_INPUT,D as ValidationError,ha as ViewBuilder,Yt as WIRE_OMITTED_CONFIG_KEYS,da as WORKSTATION_HARNESSES,agent,agentAvatarFromMetadata,ms as agentAvatarSchema,agentDataChunk,agentDisplayName,Zo as agentInferencePreferencesSchema,as as agentMessageAttachmentSchema,is as agentMessagePartSchema,$o as agentSessionInferenceOverridesInputSchema,es as agentSessionInferenceOverridesSchema,us as agentSessionMessageSchema,hs as agentStartersSchema,agentUIValidationError,applyOperations,applyPipes,applyRelationProps,architectContentBodyKey,architectDraftChannelKey,architectFocusCandidates,architectFocusKey,os as artifactQuoteSchema,wn as asTenantId,xn as asUserId,assertAcyclicComputed,assertAcyclicComputedDependencies,assertBilateralPairs,assertCustomAgentUIMessageChunk,assertSchemaSourceId,assertSchemaSourceResolutions,$t as attributeConfigSchemas,attributeInventory,bilateralDeclarationOf,booleanFlag,buildAgentFallbackTitle,buildPermissionFlags,buildPropertySchema,buildQualifiedAttribute,canCopyRole,canGrantLevel,canGrantPurge,A as canonicalStringify,Xs as canonicalViewOperationSchema,v as canonicalizeFilterValue,capabilityForResource,capped,ws as catalogEmbeddingSchema,catalogImageModelSchema,catalogTextModelSchema,checkbox,chosenUserName,cleanContent,collectContentViewCatalogue,ye as collectQualifiedRuleIssues,collectSchemaReferences,Ce as collectionContentSourceSchema,collectionContentsOf,collectionSourceAddress,collectionSourceAddressOf,jt as colorIdSchema,_e as columnsSchema,compareAgentSessionMessages,compareSchemaStateEntries,compilablePlansOf,compileComputedFormula,compileRollupAttribute,computeByteMagnitude,computeReconnectDelay,computeRetryDelay,computedCompileSchemaOf,computedPlanOf,B as content,contentDefinition,qa as contentExtensionRegistry,contentNamesAttribute,xe as contentViewDefinitionSchema,pe as contentViewDefinitionSchemaFor,conversationDisplayTitle,convertRetypedValue,hn as createCheckboxValidator,gn as createDateValidator,createFlagRegistry,createFlagService,Pn as createFormAttributeValidator,mn as createNumberValidator,createStandardSchemaProps,dn as createTextValidator,currency,he as currentActor,ps as customDataChunkSchemas,date,dateInTimezone,Dt as dateValueStart,declaredImageRequests,decodeDeploymentBarrierAttestationV1,Cn as deepEqual,defaultViewIdsFor,defaultViewsFor,defineDeviceChannelFrames,defineOperation,definePresentation,dependentsOf,deriveArchitectChanges,deriveCreateDefaultsFromFilters,deriveInitials,deriveViewerAccess,describeOperations,detailView,deviceChannelUrl,diffSchemaState,ae as displayAttributesSchema,document,ve as draftContentViewDefinitionSchema,Se as draftContentViewDefinitionSchemaFor,draftListedObjectResolver,draftObjectSettings,draftedLabelExpression,draftedObjectDefinition,draftedViewDefinition,ls as durableDateSchema,dwellForStep,episodeImpactOf,sn as evaluateComputedAst,Rt as evaluateComputedFormula,on as evaluateComputedFormulaWithResult,evaluateFilterState,evaluateRecordFilterState,exceptionLevels,extractAttributeNames,i as extractCurrencyFilterValue,h as extractFilterValue,extractTouchedArtifacts,extractTouchedDocuments,extractTouchedRecords,extractValueRefs,familyOf,l as filterOperatorsByTypeForGeneration,se as filterStateSchema,findGrantIssues,findModelByReference,findRelationAttribute,findWorkstationHarness,_a as flagRegistry,focusOf,form,formFieldFlatKey,formFieldKey,Ja as formRegistry,formatAgentStreamFrameId,formatAttributeValue,formatByteSize,Ot as formatComputedResult,formatLocationValue,pn as formatZodErrors,formula,fromDraftableView,yn as generateId,x as getAttributeCapabilities,c as getAttributeFilterOperators,getEditableLabelAttribute,getErrorMessage,getLiveProtocolPayloadChannel,r as getOperatorPolarity,getRecordCreatorPrincipalId,f as getRollupFilterOperators,getSingleAttributeFromExpression,getSlotFieldTargets,e as getSystemAttributeI18nKey,le as getSystemAttributeList,getUserDisplayName,grantCovers,grantsFromLevels,group,guidanceForBatch,hasOptions,O as iconNameSchema,imageModelFormatDefect,Qo as imageModelIdSchema,inboundRelationAttributes,includesAction,_n as indexBy,inferInverseCardinality,inferRollupReturnType,Jo as inferenceReasoningSchema,Yo as inferenceRoutingSchema,qo as inferenceSpeedSchema,isAgentMessageMetadata,isAgentNotificationMetadata,isAgentUIDataName,isAgentUIMessageBatch,isAgentWrittenAuditEntry,b as isAttributeFilterable,S as isAttributeGroupable,ot as isAttributeInUseError,s as isAttributeKanbanGroupable,d as isAttributeSearchable,isAttributeSortable,isBilateralRelation,m as isCalendarDay,isCatalogResource,isCheckboxEquality,isClaimableSessionStatus,isComputedAttribute,Tt as isComputedFunctionName,isCurrentTargetToken,cn as isDateRangeValue,isDefaultRole,isDocumentAttribute,t as isDynamicValue,isEdgePayload,isEmptyObject,isFormDefinition,isFormFieldsRow,isFormFreeFieldRef,isFormHeadingRow,isFormSeparatorRow,isFormSlotFieldRef,isFormTextRow,isLabelExpression,isLiveEventEnvelope,isLiveEventPayload,isLiveEventPayloadForType,isLiveEventType,u as isLocationFilterProperty,ne as isLocationPartOperator,isMailProvider,isMailboxListMode,we as isManagedSystemAttribute,Ft as isNativeObjectName,ee as isNoValueOperator,isNotEmpty,st as isNotFoundError,j as isNullishOrEmptyString,ct as isObjectReferencedError,isOpenToolPartState,ht as isPlainRecord,lt as isProtectedResourceError,isProviderDraft,isPublishedConfigChangeAllowed,ut as isRecordReferencedError,fe as isRelativeDateValue,isReplyMode,isRoleLabelTaken,isRoutableModel,isRoutineActorMetadata,dt as isSchemaError,De as isSetMembershipOperator,isStandardSchema,isSystemPartCode,isTerminalSessionStatus,isTerminalState,isToolApprovalState,isUnderRoutingCeiling,isUniversalRelation,ft as isValidationError,En as isValuePresent,isWorkstationHarnessId,jsonFlag,legacyStatusToSessionState,levelActions,levelOf,listView,listedObjectWithoutCatalogue,liveChannelKey,location,markdownToPlainText,matchesAccepts,ss as mentionReferenceSchema,cs as modelDefinitionSchema,Xo as modelReferenceSchema,modelReferenceSpellings,multiselect,Xt as multiselectOptionWriteSchema,Mc as namedTargetSchema,nativeAgentUIPartIdMetadataKey,to as nonOperationalDeploymentBarrierAttestorV1,mt as normalizeDateValue,oe as normalizeFilterRule,y as normalizeForEdgeRpc,Oe as normalizeOperator,normalizePricing,normalizeRoleGrants,normalizeRoleLabel,me as now,number,numberFlag,object,objectPermissionFlags,operationPace,orderAgentSessionMessages,parseAgentStreamFrameId,en as parseAttributeConfig,zt as parseAttributeConfigForCreate,qt as parseAttributeConfigForUpdate,kt as parseComputedFormula,parseCountMode,parseDeviceChannelFrame,parseFilterInstant,parseLiveChannelKey,parseModelCatalog,parseNamedTarget,parseNativeAgentUIPartIdsMetadata,parseOperation,parseOptionalCountMode,parseQualifiedAttribute,parseQualifiedToolName,parseRecordAccessRole,Pt as parseResourceVisibility,parseSchemaGroupPresentation,parseSchemaState,parseServerFrame,parseWorkerFrame,na as permissionGrantSchema,phone,planAttributeRemoval,presentationOf,pricePerMillion,nn as propertyAttributeSchema,Bt as propertyAttributeWireSchema,Vt as propertySchemaSchema,Zt as propertySchemaWireSchema,proposalTargetKey,Ko as providerNameSchema,C as publishedViewContentDefinitionSchema,qualifiedPropertyDefs,qualifiedToolName,readAccessLevels,readArtifactResult,readFormFieldValue,readGeneratedImageResult,readRoleLevels,recentActivityEntryKey,reconcileRelationAttributes,Jt as refuseForeignKeys,regenerateDerived,ya as registry,Ln as rejectUnknownAttributesOrThrow,relation,relationAcceptsObject,relationProperty,relationPropertyDefs,relationTargetObjectName,relationTargets,relationTargetsOf,relationValueIds,removeObjectException,renameAttributeInContent,renamedFromTarget,renderLabelExpression,requestedCapabilities,requireRecordContentContext,requireSingleRelationTarget,requiredTargetKeys,resolveAttributeDefaultValue,resolveCollectionActions,resolveContentNavigation,te as resolveEffectiveFilterType,resolveFieldRequired,de as resolveIsWithinBounds,resolvePropertyDefinitions,un as resolveTextPattern,ie as resolveUtcDayBounds,resolveViewContents,richtext,roleNameFromLabel,rollup,rollupToFormulaExpression,ns as routedMessageInferenceSchema,routingPrice,sameActions,vn as sameStableValue,schemaGroupKey,schemaStateSourcePayload,select,Ut as selectOptionWriteSchema,bn as serializeCanonicalJson,Tn as serializeStableJson,ts as sessionInferencePatchSchema,sessionStateToLegacyStatus,setCapabilityLevel,setDefaultObjectLevel,setObjectException,setPurge,singleRelationTarget,Te as sortsSchema,status,Ht as statusGroupSchema,It as statusOptionWriteSchema,stillMissing,storedContentDefinition,stringFlag,summarizeDraft,summarizeGroup,systemPermissionFlags,targetSnapshot,targetTokenOf,targetTokensFor,text,toAttribute,toDraftableAttribute,toDraftableAttributes,toDraftableObject,toDraftableView,a as toMultiValueOperator,toUndefinedIfEmpty,Ee as toUtcDayString,p as today,ds as todoItemSchema,fs as todoPlanSchema,rs as toolImpactSchema,touchedObjectIds,uncoveredGrants,user,Ct as validateAttributeName,validateContentViewCatalogue,jn as validateDraft,In as validateDraftOrThrow,validateLabelExpression,Rn as validateObject,validateObjectExpressions,vt as validateObjectName,Mn as validateObjectOrThrow,ge as validateQualifiedRule,validateStoredViews,St as validateViewName,verifyDeploymentBarrierAttestationV1,viewIdFor,viewIdentityKey,viewNamesAttribute,Ua as viewRegistry,rn as withoutUnknownOptionKeys,workspaceViewAuthoring};
|