@stndrds/schema 1.0.0-alpha.357 → 1.0.0-alpha.358
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-WEAw-zHa.d.ts → all-BUkjHo7X.d.ts} +38 -38
- package/dist/{all-SkbqeVsR.d.mts → all-D0YeMcgV.d.mts} +38 -38
- package/dist/{attributes-0MFN3D1T.d.mts → attributes-DPIr_qX6.d.mts} +1 -1
- package/dist/{attributes-D3wn8qoZ.d.ts → attributes-yTXr35kT.d.ts} +1 -1
- package/dist/{checkbox-DbL9Kc0_.d.ts → checkbox-BaYw6r_H.d.ts} +2 -2
- package/dist/{checkbox-DO1Komkk.d.mts → checkbox-CMt-PoRb.d.mts} +2 -2
- package/dist/{date-BYjdx-FS.d.mts → date-D_QyMR4H.d.mts} +2 -2
- package/dist/{date-D1M2lsRo.d.ts → date-Db8kyXe9.d.ts} +2 -2
- package/dist/{exceptions-BG2LUDOt.d.mts → exceptions-DStnjN6V.d.mts} +1 -3
- package/dist/{exceptions-BG2LUDOt.d.ts → exceptions-DStnjN6V.d.ts} +1 -3
- package/dist/exceptions.d.mts +1 -1
- package/dist/exceptions.d.ts +1 -1
- package/dist/exceptions.js +1 -1
- package/dist/exceptions.mjs +1 -1
- package/dist/{index-BRGf8Pj9.d.mts → index-3l917IWo.d.mts} +1 -1
- package/dist/{index-BT21OFT0.d.mts → index-B7Aho10z.d.mts} +3 -3
- package/dist/{index-BQ7N0iEr.d.ts → index-BCmWG1tK.d.ts} +1 -1
- package/dist/{index-BxM_oMmi.d.ts → index-Depp4oSL.d.ts} +1 -1
- package/dist/{index-B8VLnf0C.d.ts → index-DfTkjIMo.d.ts} +3 -3
- package/dist/{index-D9Zkc3Zp.d.mts → index-IgE3Rdnx.d.mts} +1 -1
- package/dist/index.d.mts +143 -134
- package/dist/index.d.ts +143 -134
- package/dist/index.js +9 -9
- package/dist/index.mjs +9 -9
- package/dist/{number-B6nCPYSp.d.ts → number-DtPI_bh3.d.ts} +2 -2
- package/dist/{number-Bz2mxDQV.d.mts → number-apkFAzPf.d.mts} +2 -2
- package/dist/{text-CbUS9lxj.d.ts → text-BXJbSNCV.d.ts} +2 -2
- package/dist/{text-BWe-JTsH.d.mts → text-CUVnXevv.d.mts} +2 -2
- package/dist/{utils-DiHsvBLK.d.ts → utils-70uWAevF.d.ts} +1 -1
- package/dist/{utils-ByfbrMxt.d.mts → utils-Db_Py4G6.d.mts} +1 -1
- package/dist/utils.d.mts +1 -1
- package/dist/utils.d.ts +1 -1
- package/dist/validation/all.d.mts +4 -4
- package/dist/validation/all.d.ts +4 -4
- 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/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 +1 -1
- package/dist/validation/config/index.d.ts +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/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/webhooks.d.mts +18 -0
- package/dist/webhooks.d.ts +18 -0
- package/dist/webhooks.js +2 -0
- package/dist/webhooks.mjs +2 -0
- package/package.json +12 -2
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as ee,S as v,T as y,U as b,V as te,W as ne,X as re,Y as ie,Z as ae,_ as oe,a as se,at as ce,b as le,c as ue,ct as de,d as fe,dt as pe,et as me,f as he,ft as ge,g as _e,h as ve,ht as ye,i as be,it as xe,j as Se,k as Ce,l as x,lt as we,m as Te,mt as Ee,n as De,nt as Oe,o as ke,ot as Ae,p as je,pt as Me,q as Ne,r as Pe,rt as S,s as Fe,st as Ie,t as Le,tt as Re,u as ze,ut as Be,v as Ve,w as He,x as Ue,y as We,z as Ge}from"./view-config.schema-DbDc6VTO.mjs";import{AccessDeniedError as Ke,AmbiguousSchemaChangeError as qe,AttributeInUseError as Je,AttributeNotFoundError as Ye,ConcurrentModificationError as Xe,DuplicateError as C,ForbiddenError as Ze,InvalidPermissionGrantError as Qe,MemoryNotFoundError as $e,NotFoundError as w,NotImplementedError as et,ObjectNotFoundError as tt,ObjectReferencedError as nt,OrphanSystemAttributeError as rt,ProtectedResourceError as it,ProtectedRoleError as at,RealtimeDeliveryError as ot,RealtimeRateLimitedError as st,RealtimeSubscriptionError as ct,RecordNotFoundError as lt,RecordReferencedError as ut,RepositoryError as dt,ReservedObjectNameError as ft,RoleNotFoundError as pt,SchemaError as T,SchemaErrorCode as E,SearchBackendError as mt,StorageError as ht,SyncCascadeError as gt,SyncConflictError as _t,SyncError as vt,SystemEntityImmutableError as yt,ValidationError as D,isAttributeInUseError as bt,isNotFoundError as xt,isObjectReferencedError as St,isProtectedResourceError as Ct,isRecordReferencedError as wt,isSchemaError as Tt,isValidationError as Et}from"./exceptions.mjs";import{$ as Dt,A as Ot,B as kt,C as At,D as jt,E as Mt,F as Nt,G as Pt,H as Ft,I as It,J as Lt,K as Rt,L as zt,M as Bt,N as Vt,O as Ht,P as Ut,Q as Wt,R as O,S as Gt,T as Kt,U as qt,V as Jt,W as k,X as Yt,Y as Xt,Z as Zt,_ as Qt,a as $t,b as en,c as tn,d as nn,f as rn,g as an,h as on,i as sn,j as cn,k as ln,l as un,m as dn,n as fn,o as pn,p as mn,q as hn,r as gn,s as _n,t as vn,u as yn,v as bn,w as xn,x as Sn,y as Cn,z as wn}from"./config-BkMUw1Ho.mjs";import{n as Tn,r as En,t as Dn}from"./text-C8Lb-NFo.mjs";import{n as On,t as kn}from"./core-BLHhNykL.mjs";import{createNumberValidator as An}from"./validation/primitives/number.mjs";import{createCheckboxValidator as jn}from"./validation/primitives/checkbox.mjs";import{createDateValidator as Mn}from"./validation/primitives/date.mjs";import{a as Nn,c as Pn,i as Fn,l as In,n as Ln,o as Rn,r as zn,s as A,t as Bn,u as Vn}from"./utils-fXIvFFl6.mjs";import{n as Hn,t as j}from"./empty-BgAwlO54.mjs";import{a as Un,i as Wn,n as Gn,r as Kn}from"./phone-CRbCvH20.mjs";import{a as qn,c as Jn,d as Yn,f as Xn,i as Zn,o as Qn,r as $n,s as er,u as tr}from"./object-sbH7KtsH.mjs";import{z as M}from"zod";import{AVATAR_COLOR_IDS as nr,MEMORY_DESCRIPTION_MAX_LENGTH as rr,MEMORY_NAME_MAX_LENGTH as ir,SKILL_DESCRIPTION_MAX_LENGTH as ar,SKILL_NAME_MAX_LENGTH as or,getCountryByIso2 as sr,getCountryDisplayNameByIso3 as N,isValidCurrencyCode as cr,isValidIso3 as lr}from"@stndrds/constants";import{parsePhoneNumberFromString as ur}from"libphonenumber-js";const dr=[`fyi`,`task`,`question`,`handoff`,`system`],fr=[`low`,`normal`,`high`,`urgent`],pr=[`public`,`internal`,`sensitive`],mr=[`unread`,`read`,`archived`,`snoozed`],hr=[`none`,`pending`,`processing`,`completed`,`dismissed`,`expired`,`failed`],gr=`agent.session.waiting_human`,_r=`agent.task.assigned`,vr=`agent.question.requested`,yr=[gr,_r,vr],br=[`name`,`type`],xr=[`required`,`hidden`,`archived`,`deprecated`,`defaultValue`,`config`,`order`,`unique`],Sr=[`label`,`description`,`placeholder`,`icon`],Cr=[`record`,`object`,`attribute`,`view`,`user`,`role`,`settings`,`file`,`agent`,`schema_source`,`tenant_invitation`,`api_key`],wr=`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(`,`),Tr=`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 Er=[`completed`,`failed`,`cancelled`,`timeout`,`expired`];function isTerminalSessionStatus(e){return Er.includes(e)}const Dr=[`idle`,`completed`,`waiting_human`,`waiting_agents`,`cancelled`,`failed`,`timeout`];function isClaimableSessionStatus(e){return Dr.includes(e)}const Or=Object.freeze({mutation:`ask`,destructive:`ask`,outward:`ask`}),kr=[`active`,`completed`,`abandoned`],Ar=[`openai`,`anthropic`,`google`,`spacexai`,`deepseek`,`moonshotai`,`alibaba`,`mistral`,`minimax`,`meta`,`zai`],jr=[`standard`,`fast`],Mr=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],Nr=[`conversation`,`writing`,`coding`,`analysis`,`extraction`],Pr=[`light`,`standard`,`heavy`],Fr=[`manual`,`auto`],Ir={interactive:{inputPerMillionUsd:5,outputPerMillionUsd:25},delegated:{inputPerMillionUsd:2,outputPerMillionUsd:12}},Lr=[`model`,`speed`,`reasoning`,`imageModel`,`routing`];function isRoutineActorMetadata(e){return e?.kind===`routine`}const Rr=[`octopus`,`clover`,`flower`,`triangle`,`square`,`blob`,`circle`,`drop`,`hexagon`,`pill`,`pebble`,`puddle`],zr=[`relaxed`,`neutral`],Br=4,Vr=200;function agentDisplayName(e){return e.label?.trim()||e.name}const Hr=[`approval-requested`,`approval-responded`,`approval-dispatched`],Ur=[`streaming`,`running`,`pending`,...Hr];function isOpenToolPartState(e){return Ur.includes(e)}function isToolApprovalState(e){return Hr.includes(e)}const Wr=[`CREDITS_EXHAUSTED`];function isSystemPartCode(e){return typeof e==`string`&&Wr.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 Gr=200,Kr=182,qr=366,Jr=`agent-notification`;function isAgentNotificationMetadata(e){return e?.kind===Jr}const Yr=`agent-message`;function isAgentMessageMetadata(e){return e?.kind===Yr}const Xr=[`pending`,`in_progress`,`completed`,`blocked`],Zr=50,Qr=80,$r=500,ei=`session-state`,ti=`__stndrdsNativeUiPartIds`,ni=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?.[ti];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 ri=16e3,ii=3200,ai=6400,oi=16e3,si=65536,ci=15e3,li=1e4,ui=5e3,di=`google/gemini-3.5-transcribe-live`,fi={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2},pi=`/v1/device-worker/channel`,mi=262144,hi=15e4,gi=1e4,_i=2e3,vi=2e3,yi=2e4,bi=4008,xi={initialMs:1e3,maxMs:3e4};function deviceChannelUrl(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${pi}`}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,xi)}const Si=[`worker_disconnected`,`cancelled`,`timed_out`,`execution_failed`,`stale_reference`,`tab_unavailable`,`debugger_unavailable`,`blocked_by_user`,`not_actionable`,`javascript_error`,`batch_cap_exceeded`,`no_reference_screenshot`],Ci=`UPGRADE_REQUIRED`;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)},wi=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+$/),protocol:M.number().int().positive().optional()}),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(Si).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`])}),protocol:M.number().int().positive().optional()}),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 Ti=defineDeviceChannelFrames({action:wi,result:wi}),Ei=Ti.worker,Di=Ti.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(Ei,e)}function parseServerFrame(e){return parseDeviceChannelFrame(Di,e)}const Oi=[`web`,`presentation`,`document`,`spreadsheet`,`image`,`code`,`other`],ki=[`ephemeral`,`conversation`,`persistent`],Ai=[`source`,`preview`,`entrypoint`,`asset`],ji=5,Mi=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 Ni=[`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.readOnly===!0?!1: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 Pi=[`reader`,`editor`],Fi=[`manual`,`meeting_attendee`];function parseRecordAccessRole(e){if(typeof e==`string`&&Pi.includes(e))return e;let t=`role must be one of: ${Pi.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 Ii=`Notetaker`,Li={meetingRecordingPolicy:`none`,meetingBotDisplayName:Ii},Ri=6048e5,zi=36e5,Bi=2592e6,Vi=6e4,Hi=[`active`,`suspended`],Ui=[`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>Pt.labelLength&&refuse$2(`label`,`Label is too long (max ${Pt.labelLength} characters)`),n.label=t}}if(t.icon!==void 0){let e=t.icon;if(e===null)n.icon=null;else{let t=k.safeParse(e);t.success||refuse$2(`icon`,`Invalid icon name`),n.icon=t.data}}return n}const Wi=[`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 Gi=[`none`,`estimated`,`exact`];function parseCountMode(e){if(typeof e==`string`&&Gi.includes(e))return e;throw new D(`countMode must be one of: ${Gi.join(`, `)} (received: ${String(e)})`,[])}function parseOptionalCountMode(e){return e===void 0?void 0:parseCountMode(e)}const Ki=1e4,qi=[`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 Ji=[`B`,`KB`,`MB`,`GB`,`TB`];function formatByteSize(e){let{value:t,unitIndex:n}=computeByteMagnitude(e);return`${t} ${Ji[n]}`}const Yi={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 Xi=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(!Xi.includes(e.type))throw Error(`Property type "${e.type}" is not supported in .qualifyWith()`);t.push(e)}return{definitions:t}}const Zi=`__`;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 Qi=/\\([!-/:-@[-`{-~])/g,$i=57344;function markdownToPlainText(e){if(e.length===0)return``;let t=[];return e.replace(Qi,(e,n)=>(t.push(n),String.fromCharCode($i+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)-$i]??e)}const ea=`—`;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(Jt(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?Gn(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 ta=[`UPPER`,`LOWER`,`capitalize`,`trim`],na=[`prefix`,`suffix`,`wrap`,`default`],ra=[...ta,...na],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(!ra.includes(e))return!1}return!0},{message:`Invalid pipe name. Valid pipes: ${ra.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 ia=`(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=ia){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 aa=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function getSingleAttributeFromExpression(e){let t=e.trim().match(aa);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`||S(r).authoring.readOnly?null:r}const oa=/\{\{\s*props\./;function applyRelationProps(e,t,n){if(!oa.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 sa=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 ca=/\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(ca)?.[0];return t===void 0?``:[...t.toUpperCase()][0]??``}).filter(Boolean).slice(0,2).join(``);return i===``?t:i}const la=`__creatorRootActorId`;function getRecordCreatorPrincipalId(e){let t=e.metadata?.[la];return typeof t==`string`&&t.length>0?t:e.createdBy}const ua=[{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`]}]}]}],da=`none`,fa=`custom`,I={actions:[`read`,`create`,`update`,`delete`],purge:`manage`,levels:[{id:`read`,add:[`read`]},{id:`edit`,add:[`create`,`update`]},{id:`full`,add:[`delete`]}]},L=ua.flatMap(e=>e.capabilities),pa=L.flatMap(e=>e.resources),ma=new Map(L.flatMap(e=>e.resources.map(t=>[t,e])));function isCatalogResource(e){return ma.has(e)}function capabilityForResource(e){let t=ma.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 da;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 fa}const ha=[`read`,`create`,`update`,`delete`,`manage`],ga=M.object({scope:M.enum([`object`,`system`]),target:M.string().min(1),actions:M.array(M.enum(ha))}).strict();function findGrantIssues(e,t){let n=[],r=new Map;for(let i of e){let e=ga.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===`*`?[...ha]: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 _a=`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:fa}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=ua.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:_a}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 va=new Set([`id`,`name`,`label`,`type`,`required`,`system`,`unique`,`order`]),ya={OWNER:`owner`,MEMBER:`member`,AGENT_DEFAULT:`agent_default`},ba={owner:`Owner`,member:`Member`,agent_default:`Agent Default`},xa={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],Sa=[...ha],Ca={owner:{system:[{target:`*`,actions:Sa}],object:[{target:`*`,actions:Sa}]},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}]}},wa=[{role:`member`,scope:`object`,target:`*`,actions:[`manage`]}];function isDefaultRole(e){return Object.values(ya).includes(e)}const Ta=[{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`],provider:`anthropic`,apiKeyEnv:{anthropic:`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:!0,loginCommand:`codex login --device-auth`,credentialPaths:[`~/.codex/auth.json`],provider:`openai`,apiKeyEnv:{openai:`OPENAI_API_KEY`},models:[{id:`gpt-6-sol`,label:`GPT-6 Sol`},{id:`gpt-6-luna`,label:`GPT-6 Luna`},{id:`gpt-5.5`,label:`GPT-5.5`}],defaultModel:`gpt-6-sol`},{id:`opencode`,label:`OpenCode`,available:!0,credentialPaths:[`~/.local/share/opencode/auth.json`],apiKeyEnv:{anthropic:`ANTHROPIC_API_KEY`,openai:`OPENAI_API_KEY`},models:[{id:`anthropic/claude-sonnet-5`,label:`Claude Sonnet 5`},{id:`anthropic/claude-opus-5-5`,label:`Claude Opus 5.5`},{id:`openai/gpt-6-sol`,label:`GPT-6 Sol`},{id:`openai/gpt-6-luna`,label:`GPT-6 Luna`}],defaultModel:`anthropic/claude-sonnet-5`},{id:`cursor`,label:`Cursor`,available:!1,loginCommand:`cursor-agent login`,credentialPaths:[`~/.config/cursor/auth.json`],provider:`anthropic`,apiKeyEnv:{anthropic:`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`],provider:`spacexai`,apiKeyEnv:{spacexai:`XAI_API_KEY`},models:[{id:`grok-code-fast-1`,label:`Grok Code Fast 1`}],defaultModel:`grok-code-fast-1`}],Ea=new Map(Ta.map(e=>[e.id,e]));function isWorkstationHarnessId(e){return Ea.has(e)}function findWorkstationHarness(e){return Ea.get(e)}function workstationModelProvider(e,t){if(e.provider)return e.provider;let n=t.split(`/`,1)[0];return Object.keys(e.apiKeyEnv).find(e=>e===n)}const Da={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2}};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??Da,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={...Or,...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 Vt(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??Da,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};function agent(e){return new AgentBuilder(e)}const Oa=`@stndrds/schema`;function createStandardSchemaProps(e){return{version:1,vendor:Oa,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(Yn(this.build()))}constructor(e,t,n){Ut(t),It(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 Nt(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(t){let n=this.attr.targets;if(!n||n.length===0)throw Error(`.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })`);if(n.length>1)throw Error(`Bilateral relations are not supported for polymorphic relations (multiple .to() targets).`);if(e(this.attr))throw Error(`Bilateral relations are not supported for universal relations (.toAny()).`);let r=n[0]?.object;if(!r)throw new D(`Bilateral relation requires one target object`,[{path:[`bilateral`,`object`],message:`Bilateral relation requires one target object`}]);if(t.object&&t.object!==r){let e=`Bilateral inverse object ${t.object} must match relation target ${r}`;throw new D(e,[{path:[`bilateral`,`object`],message:e}])}return this.attr.bilateral={...t,object:r},this}},SingleRelationAttributeBuilder=class extends BaseRelationAttributeBuilder{constructor(e,t){super(`relation`,e,t),this.attr.cardinality=`one`,this.attr.targets=[]}many(){let e=new MultiRelationAttributeBuilder(this.attr.name,this.attr.label??``,{targets:this.attr.targets,isRequired:this.attr.required});return this.attr.system===!1&&e.runtime(),this.attr.hidden&&e.hidden(),this.attr.placeholder&&e.placeholder(this.attr.placeholder),this.attr.description&&e.description(this.attr.description),this.attr.icon&&e.icon(this.attr.icon),this.attr.order!==void 0&&e.order(this.attr.order),this.attr.metadata&&e.metadata(this.attr.metadata),e}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}},MultiRelationAttributeBuilder=class extends BaseRelationAttributeBuilder{constructor(e,t,n){super(`relation`,e,t),this.attr.cardinality=`many`,this.attr.targets=n?.targets??[],this.attr.defaultValue=[],n?.isRequired&&this.setRequired(!0)}maxItems(e){return this.attr.maxItems=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function relation(e){return new SingleRelationAttributeBuilder(e.name,e.label)}var FormulaAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`formula`,e,t),this.attr.required=!1}expression(e){return this.attr.expression=e,this}returns(e){return this.attr.returnType=e,this}decimals(e){return this.attr.decimals=e,this}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 readOnlyOption(e){return e?.readOnly===void 0?{}:{readOnly:e.readOnly}}function buildFreeFieldRef(e,t){return{type:`free`,attribute:e.build(),label:t?.label,required:t?.required,prefillExpression:t?.prefillExpression,...readOnlyOption(t)}}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,...readOnlyOption(n)}}const ka=M.boolean().optional();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){return this.rowData.fields.push(buildFreeFieldRef(e,t)),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=buildFreeFieldRef(e,t),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.validateReadOnly(),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=[...ra,`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(`, `)}`)}}}validateReadOnly(){for(let e of this.data.steps)for(let t of e.rows)if(isFormFieldsRow(t))for(let n of t.fields){if(ka.safeParse(n.readOnly).success)continue;let t=isFormFreeFieldRef(n)?n.attribute.name:n.attribute,r=isFormFreeFieldRef(n)?`free field`:`field`;throw new D(`[FormBuilder] readOnly on ${r} "${t}" in step "${e.id}" must be a boolean.`,[{path:[e.id,t,`readOnly`],message:`Expected a boolean`}])}}validateFreeFields(){let e=new Set(Ni);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: ${Ni.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(tr(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);Vt([...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 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&&zt(e)}};function object(e){if(Dt(e.name))throw new ft(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=x.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 Aa=class ViewBuilder{constructor(e,t=[]){this.kind=`view`,this.data=cloneBuilderValue(e,[`views`,`0`]),this.extensions=t.map(e=>e&&{...e})}for(e){return new ViewBuilder({...this.data,object:e},this.extensions)}default(){return new ViewBuilder({...this.data,default:!0},this.extensions)}description(e){return new ViewBuilder({...this.data,description:e},this.extensions)}icon(e){return new ViewBuilder({...this.data,icon:e},this.extensions)}place(e,t,n,r){let i=[`views`,`0`,`contents`,String(this.data.contents.length)],a,o;try{typeof n==`object`&&n&&`build`in n&&typeof n.build==`function`?(a=validateContentConfiguration(n.build(),i),o=n.extension):a=validateContentConfiguration(n,i)}catch(e){throw e instanceof D?new D(e.message,e.errors.map(e=>({...e,path:e.path[0]===`content`?[...i,...e.path.slice(1)]:e.path}))):e}let s={...a,name:e,label:t,placement:r},c=[...this.data.contents,s];return new ViewBuilder({...this.data,contents:c},[...this.extensions,o])}tab(e,t,n){return this.place(e,t,n,`main`)}aside(e,t,n){return this.place(e,t,n,`aside`)}build(){let e=[`views`,`0`];requireBuilderName(this.data.name,[...e,`name`]),requireBuilderName(this.data.object,[...e,`object`]);let t=Pe.safeParse(this.data);if(!t.success)throw D.fromZodErrors(t.error.issues.map(t=>({path:[...e,...t.path.map(String)],message:t.message})));return this.data.contents.forEach((t,n)=>{let r=[...e,`contents`,String(n)];requireBuilderName(t.name,[...r,`name`]),t.type===`form`&&t.groups.forEach((e,t)=>requireBuilderName(e.name,[...r,`groups`,String(t),`name`])),(t.type===`custom`?this.extensions[n]?.requiresRecord:t.type!==`collection`||collectionSourceAddress(t.source).kind!==`object`)&&requireRecordContentContext(t.name,this.data.context,r)}),{kind:`view`,definition:cloneBuilderValue(this.data,e)}}};function detailView(e,t){return new Aa({name:e,label:t,object:void 0,context:`record`,contents:[]})}function listView(e,t){return new Aa({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}},ja=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 ja(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 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 w(`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 Ma=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 Na=Symbol(`stndrds.native-object`);function markNativeDefinition(e){return Object.defineProperty(e,Na,{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[Na]===!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 D(t,[])}if(Dt(e.name)&&!isNativeDefinition(e))throw new ft(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 w(`Native object`,e,E.OBJECT_NOT_FOUND,t)}return t}getAll(){return Array.from(this.objects.values(),cloneObjectDefinition)}listNames(){return Array.from(this.objects.keys())}has(e){return this.objects.has(e)}get size(){return this.objects.size}clear(){this.objects.clear()}summary(){let e=this.getAll();return[`[NativeObjectRegistry] ${this.size} native object(s) registered:`,...e.map(e=>` - ${e.name}: "${e.label}" (${e.attributes.length} attributes)`)].join(`
|
|
3
|
-
`)}debug(e){let t=this.summary();return e?.(t),t}};const
|
|
2
|
+
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as v,S as y,T as b,U as x,V as ee,W as te,X as ne,Y as re,Z as ie,_ as ae,a as oe,at as se,b as ce,c as le,ct as ue,d as de,dt as fe,et as pe,f as me,ft as he,g as ge,h as _e,ht as ve,i as ye,it as be,j as xe,k as Se,l as S,lt as Ce,m as we,mt as Te,n as Ee,nt as De,o as Oe,ot as ke,p as Ae,pt as je,q as Me,r as Ne,rt as C,s as Pe,st as Fe,t as Ie,tt as Le,u as Re,ut as ze,v as Be,w as Ve,x as He,y as Ue,z as We}from"./view-config.schema-DbDc6VTO.mjs";import{AccessDeniedError as Ge,AmbiguousSchemaChangeError as Ke,AttributeInUseError as qe,AttributeNotFoundError as Je,ConcurrentModificationError as Ye,DuplicateError as w,ForbiddenError as Xe,InvalidPermissionGrantError as Ze,MemoryNotFoundError as Qe,NotFoundError as $e,NotImplementedError as et,ObjectNotFoundError as tt,ObjectReferencedError as nt,OrphanSystemAttributeError as rt,ProtectedResourceError as it,ProtectedRoleError as at,RealtimeDeliveryError as ot,RealtimeRateLimitedError as st,RealtimeSubscriptionError as ct,RecordNotFoundError as lt,RecordReferencedError as ut,RepositoryError as dt,ReservedObjectNameError as ft,RoleNotFoundError as pt,SchemaError as T,SchemaErrorCode as E,SearchBackendError as mt,StorageError as ht,SyncCascadeError as gt,SyncConflictError as _t,SyncError as vt,SystemEntityImmutableError as yt,ValidationError as D,isAttributeInUseError as bt,isNotFoundError as xt,isObjectReferencedError as St,isProtectedResourceError as Ct,isRecordReferencedError as wt,isSchemaError as Tt,isValidationError as Et}from"./exceptions.mjs";import{$ as Dt,A as Ot,B as kt,C as At,D as jt,E as Mt,F as Nt,G as Pt,H as Ft,I as It,J as Lt,K as Rt,L as zt,M as Bt,N as Vt,O as Ht,P as Ut,Q as Wt,R as O,S as Gt,T as Kt,U as qt,V as Jt,W as k,X as Yt,Y as Xt,Z as Zt,_ as Qt,a as $t,b as en,c as tn,d as nn,f as rn,g as an,h as on,i as sn,j as cn,k as ln,l as un,m as dn,n as fn,o as pn,p as mn,q as hn,r as gn,s as _n,t as vn,u as yn,v as bn,w as xn,x as Sn,y as Cn,z as wn}from"./config-BkMUw1Ho.mjs";import{n as Tn,r as En,t as Dn}from"./text-C8Lb-NFo.mjs";import{n as On,t as kn}from"./core-BLHhNykL.mjs";import{createNumberValidator as An}from"./validation/primitives/number.mjs";import{createCheckboxValidator as jn}from"./validation/primitives/checkbox.mjs";import{createDateValidator as Mn}from"./validation/primitives/date.mjs";import{a as Nn,c as Pn,i as Fn,l as In,n as Ln,o as Rn,r as zn,s as A,t as Bn,u as Vn}from"./utils-fXIvFFl6.mjs";import{n as Hn,t as j}from"./empty-BgAwlO54.mjs";import{a as Un,i as Wn,n as Gn,r as Kn}from"./phone-CRbCvH20.mjs";import{a as qn,c as Jn,d as Yn,f as Xn,i as Zn,o as Qn,r as $n,s as er,u as tr}from"./object-sbH7KtsH.mjs";import{z as M}from"zod";import{AVATAR_COLOR_IDS as nr,MEMORY_DESCRIPTION_MAX_LENGTH as rr,MEMORY_NAME_MAX_LENGTH as ir,SKILL_DESCRIPTION_MAX_LENGTH as ar,SKILL_NAME_MAX_LENGTH as or,getCountryByIso2 as sr,getCountryDisplayNameByIso3 as N,isValidCurrencyCode as cr,isValidIso3 as lr}from"@stndrds/constants";import{parsePhoneNumberFromString as ur}from"libphonenumber-js";const dr=[`fyi`,`task`,`question`,`handoff`,`system`],fr=[`low`,`normal`,`high`,`urgent`],pr=[`public`,`internal`,`sensitive`],mr=[`unread`,`read`,`archived`,`snoozed`],hr=[`none`,`pending`,`processing`,`completed`,`dismissed`,`expired`,`failed`],gr=`agent.session.waiting_human`,_r=`agent.task.assigned`,vr=`agent.question.requested`,yr=`agent.routine_run.failed`,br=`agent.routine_run.timeout`,xr=[gr,_r,vr,yr,br],Sr=[`name`,`type`],Cr=[`required`,`hidden`,`archived`,`deprecated`,`defaultValue`,`config`,`order`,`unique`],wr=[`label`,`description`,`placeholder`,`icon`],Tr=[`record`,`object`,`attribute`,`view`,`user`,`role`,`settings`,`file`,`agent`,`schema_source`,`tenant_invitation`,`api_key`],Er=`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 Or=[`completed`,`failed`,`cancelled`,`timeout`,`expired`];function isTerminalSessionStatus(e){return Or.includes(e)}const kr=[`idle`,`completed`,`waiting_human`,`waiting_agents`,`cancelled`,`failed`,`timeout`];function isClaimableSessionStatus(e){return kr.includes(e)}const Ar=Object.freeze({mutation:`ask`,destructive:`ask`,outward:`ask`}),jr=[`active`,`completed`,`abandoned`],Mr=[`openai`,`anthropic`,`google`,`spacexai`,`deepseek`,`moonshotai`,`alibaba`,`mistral`,`minimax`,`meta`,`zai`],Nr=[`standard`,`fast`],Pr=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],Fr=[`conversation`,`writing`,`coding`,`analysis`,`extraction`],Ir=[`light`,`standard`,`heavy`],Lr=[`manual`,`auto`],Rr={interactive:{inputPerMillionUsd:5,outputPerMillionUsd:25},delegated:{inputPerMillionUsd:2,outputPerMillionUsd:12}},zr=[`model`,`speed`,`reasoning`,`imageModel`,`routing`];function isRoutineActorMetadata(e){return e?.kind===`routine`}const Br=[`octopus`,`clover`,`flower`,`triangle`,`square`,`blob`,`circle`,`drop`,`hexagon`,`pill`,`pebble`,`puddle`],Vr=[`relaxed`,`neutral`],Hr=4,Ur=200;function agentDisplayName(e){return e.label?.trim()||e.name}const Wr=[`approval-requested`,`approval-responded`,`approval-dispatched`],Gr=[`streaming`,`running`,`pending`,...Wr];function isOpenToolPartState(e){return Gr.includes(e)}function isToolApprovalState(e){return Wr.includes(e)}const Kr=[`CREDITS_EXHAUSTED`];function isSystemPartCode(e){return typeof e==`string`&&Kr.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 qr=200,Jr=182,Yr=366,Xr=`agent-notification`;function isAgentNotificationMetadata(e){return e?.kind===Xr}const Zr=`agent-message`;function isAgentMessageMetadata(e){return e?.kind===Zr}const Qr=[`pending`,`in_progress`,`completed`,`blocked`],$r=50,ei=80,ti=500,ni=`session-state`,ri=`__stndrdsNativeUiPartIds`,ii=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?.[ri];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 ai=16e3,oi=3200,si=6400,ci=16e3,li=65536,ui=15e3,di=1e4,fi=5e3,pi=`google/gemini-3.5-transcribe-live`,mi={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2},hi=`/v1/device-worker/channel`,gi=262144,_i=15e4,vi=1e4,yi=2e3,bi=2e3,xi=2e4,Si=4008,Ci={initialMs:1e3,maxMs:3e4};function deviceChannelUrl(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${hi}`}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,Ci)}const wi=[`worker_disconnected`,`cancelled`,`timed_out`,`execution_failed`,`stale_reference`,`tab_unavailable`,`debugger_unavailable`,`blocked_by_user`,`not_actionable`,`javascript_error`,`batch_cap_exceeded`,`no_reference_screenshot`],Ti=`UPGRADE_REQUIRED`;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)},Ei=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+$/),protocol:M.number().int().positive().optional()}),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(wi).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`])}),protocol:M.number().int().positive().optional()}),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 Di=defineDeviceChannelFrames({action:Ei,result:Ei}),Oi=Di.worker,ki=Di.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(Oi,e)}function parseServerFrame(e){return parseDeviceChannelFrame(ki,e)}const Ai=[`web`,`presentation`,`document`,`spreadsheet`,`image`,`code`,`other`],ji=[`ephemeral`,`conversation`,`persistent`],Mi=[`source`,`preview`,`entrypoint`,`asset`],Ni=5,Pi=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 Fi=[`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.readOnly===!0?!1: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 Ii=[`reader`,`editor`],Li=[`manual`,`meeting_attendee`];function parseRecordAccessRole(e){if(typeof e==`string`&&Ii.includes(e))return e;let t=`role must be one of: ${Ii.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 Ri=`Notetaker`,zi={meetingRecordingPolicy:`none`,meetingBotDisplayName:Ri},Bi=6048e5,Vi=36e5,Hi=2592e6,Ui=6e4,Wi=[`active`,`suspended`],Gi=[`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>Pt.labelLength&&refuse$2(`label`,`Label is too long (max ${Pt.labelLength} characters)`),n.label=t}}if(t.icon!==void 0){let e=t.icon;if(e===null)n.icon=null;else{let t=k.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 qi=[`none`,`estimated`,`exact`];function parseCountMode(e){if(typeof e==`string`&&qi.includes(e))return e;throw new D(`countMode must be one of: ${qi.join(`, `)} (received: ${String(e)})`,[])}function parseOptionalCountMode(e){return e===void 0?void 0:parseCountMode(e)}const Ji=1e4,Yi=[`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 Xi=[`B`,`KB`,`MB`,`GB`,`TB`];function formatByteSize(e){let{value:t,unitIndex:n}=computeByteMagnitude(e);return`${t} ${Xi[n]}`}const Zi={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 Qi=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(!Qi.includes(e.type))throw Error(`Property type "${e.type}" is not supported in .qualifyWith()`);t.push(e)}return{definitions:t}}const $i=`__`;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 ea=/\\([!-/:-@[-`{-~])/g,ta=57344;function markdownToPlainText(e){if(e.length===0)return``;let t=[];return e.replace(ea,(e,n)=>(t.push(n),String.fromCharCode(ta+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)-ta]??e)}const na=`—`;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(Jt(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?Gn(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 ra=[`UPPER`,`LOWER`,`capitalize`,`trim`],ia=[`prefix`,`suffix`,`wrap`,`default`],aa=[...ra,...ia],oa=/^\s*where\s*(?::(.*))?$/s,sa=`[A-Za-z_][A-Za-z0-9_]*`,ca=/^[^\s,()|{}="']+$/,la=RegExp(`^(${sa})\\s*=\\s*(.*)$`),ua=RegExp(`^(${sa})\\s+in\\s*\\(([^()]*)\\)$`);function isWherePipe(e){return oa.test(e)}function parseWherePipe(e){let t=e.match(oa)?.[1]?.trim();if(!t)return null;let n=t.match(ua);if(n){let e=n[2].split(`,`).map(e=>e.trim());return e.every(e=>ca.test(e))?{property:n[1],values:e}:null}let r=t.match(la);return r&&ca.test(r[2])?{property:r[1],values:[r[2]]}:null}const 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(!aa.includes(e))return!1}return!0},{message:`Invalid pipe name. Valid pipes: ${aa.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 da=`(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=da){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 fa=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function getSingleAttributeFromExpression(e){let t=e.trim().match(fa);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`||C(r).authoring.readOnly?null:r}const pa=/\{\{\s*props\./;function applyRelationProps(e,t,n){if(!pa.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 ma=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 ha=/\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(ha)?.[0];return t===void 0?``:[...t.toUpperCase()][0]??``}).filter(Boolean).slice(0,2).join(``);return i===``?t:i}const ga=`__creatorRootActorId`;function getRecordCreatorPrincipalId(e){let t=e.metadata?.[ga];return typeof t==`string`&&t.length>0?t:e.createdBy}const _a=[{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`]}]}]}],va=`none`,ya=`custom`,I={actions:[`read`,`create`,`update`,`delete`],purge:`manage`,levels:[{id:`read`,add:[`read`]},{id:`edit`,add:[`create`,`update`]},{id:`full`,add:[`delete`]}]},L=_a.flatMap(e=>e.capabilities),ba=L.flatMap(e=>e.resources),xa=new Map(L.flatMap(e=>e.resources.map(t=>[t,e])));function isCatalogResource(e){return xa.has(e)}function capabilityForResource(e){let t=xa.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 va;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 ya}const Sa=[`read`,`create`,`update`,`delete`,`manage`],Ca=M.object({scope:M.enum([`object`,`system`]),target:M.string().min(1),actions:M.array(M.enum(Sa))}).strict();function findGrantIssues(e,t){let n=[],r=new Map;for(let i of e){let e=Ca.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===`*`?[...Sa]: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 wa=`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:ya}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=_a.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:wa}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 Ta=new Set([`id`,`name`,`label`,`type`,`required`,`system`,`unique`,`order`]),Ea={OWNER:`owner`,MEMBER:`member`,AGENT_DEFAULT:`agent_default`},Da={owner:`Owner`,member:`Member`,agent_default:`Agent Default`},Oa={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],ka=[...Sa],Aa={owner:{system:[{target:`*`,actions:ka}],object:[{target:`*`,actions:ka}]},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}]}},ja=[{role:`member`,scope:`object`,target:`*`,actions:[`manage`]}];function isDefaultRole(e){return Object.values(Ea).includes(e)}const Ma=[{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`],provider:`anthropic`,apiKeyEnv:{anthropic:`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:!0,loginCommand:`codex login --device-auth`,credentialPaths:[`~/.codex/auth.json`],provider:`openai`,apiKeyEnv:{openai:`OPENAI_API_KEY`},models:[{id:`gpt-6-sol`,label:`GPT-6 Sol`},{id:`gpt-6-luna`,label:`GPT-6 Luna`},{id:`gpt-5.5`,label:`GPT-5.5`}],defaultModel:`gpt-6-sol`},{id:`opencode`,label:`OpenCode`,available:!0,credentialPaths:[`~/.local/share/opencode/auth.json`],apiKeyEnv:{anthropic:`ANTHROPIC_API_KEY`,openai:`OPENAI_API_KEY`},models:[{id:`anthropic/claude-sonnet-5`,label:`Claude Sonnet 5`},{id:`anthropic/claude-opus-5-5`,label:`Claude Opus 5.5`},{id:`openai/gpt-6-sol`,label:`GPT-6 Sol`},{id:`openai/gpt-6-luna`,label:`GPT-6 Luna`}],defaultModel:`anthropic/claude-sonnet-5`},{id:`cursor`,label:`Cursor`,available:!1,loginCommand:`cursor-agent login`,credentialPaths:[`~/.config/cursor/auth.json`],provider:`anthropic`,apiKeyEnv:{anthropic:`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`],provider:`spacexai`,apiKeyEnv:{spacexai:`XAI_API_KEY`},models:[{id:`grok-code-fast-1`,label:`Grok Code Fast 1`}],defaultModel:`grok-code-fast-1`}],Na=new Map(Ma.map(e=>[e.id,e]));function isWorkstationHarnessId(e){return Na.has(e)}function findWorkstationHarness(e){return Na.get(e)}function workstationModelProvider(e,t){if(e.provider)return e.provider;let n=t.split(`/`,1)[0];return Object.keys(e.apiKeyEnv).find(e=>e===n)}const Pa={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2}};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={...Ar,...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 Vt(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 Fa=`@stndrds/schema`;function createStandardSchemaProps(e){return{version:1,vendor:Fa,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(Yn(this.build()))}constructor(e,t,n){Ut(t),It(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 Nt(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(t){let n=this.attr.targets;if(!n||n.length===0)throw Error(`.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })`);if(n.length>1)throw Error(`Bilateral relations are not supported for polymorphic relations (multiple .to() targets).`);if(e(this.attr))throw Error(`Bilateral relations are not supported for universal relations (.toAny()).`);let r=n[0]?.object;if(!r)throw new D(`Bilateral relation requires one target object`,[{path:[`bilateral`,`object`],message:`Bilateral relation requires one target object`}]);if(t.object&&t.object!==r){let e=`Bilateral inverse object ${t.object} must match relation target ${r}`;throw new D(e,[{path:[`bilateral`,`object`],message:e}])}return this.attr.bilateral={...t,object:r},this}},SingleRelationAttributeBuilder=class extends BaseRelationAttributeBuilder{constructor(e,t){super(`relation`,e,t),this.attr.cardinality=`one`,this.attr.targets=[]}many(){let e=new MultiRelationAttributeBuilder(this.attr.name,this.attr.label??``,{targets:this.attr.targets,isRequired:this.attr.required});return this.attr.system===!1&&e.runtime(),this.attr.hidden&&e.hidden(),this.attr.placeholder&&e.placeholder(this.attr.placeholder),this.attr.description&&e.description(this.attr.description),this.attr.icon&&e.icon(this.attr.icon),this.attr.order!==void 0&&e.order(this.attr.order),this.attr.metadata&&e.metadata(this.attr.metadata),e}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}},MultiRelationAttributeBuilder=class extends BaseRelationAttributeBuilder{constructor(e,t,n){super(`relation`,e,t),this.attr.cardinality=`many`,this.attr.targets=n?.targets??[],this.attr.defaultValue=[],n?.isRequired&&this.setRequired(!0)}maxItems(e){return this.attr.maxItems=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function relation(e){return new SingleRelationAttributeBuilder(e.name,e.label)}var FormulaAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`formula`,e,t),this.attr.required=!1}expression(e){return this.attr.expression=e,this}returns(e){return this.attr.returnType=e,this}decimals(e){return this.attr.decimals=e,this}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 readOnlyOption(e){return e?.readOnly===void 0?{}:{readOnly:e.readOnly}}function buildFreeFieldRef(e,t){return{type:`free`,attribute:e.build(),label:t?.label,required:t?.required,prefillExpression:t?.prefillExpression,...readOnlyOption(t)}}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,...readOnlyOption(n)}}const Ia=M.boolean().optional();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){return this.rowData.fields.push(buildFreeFieldRef(e,t)),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=buildFreeFieldRef(e,t),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.validateReadOnly(),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=[...aa,`join`,`where`];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 a of n.matchAll(/(?<!\|)\|(?!\|)\s*(\w+)(?:\s*:[^|}]*)?/g)){let n=a[1];if(!e.includes(n))throw Error(`[FormBuilder] ${i} uses invalid pipe "${n}". Valid pipes: ${e.join(`, `)}`);let o=a[0].replace(/^\|/,``);if(isWherePipe(o)&&!parseWherePipe(o))throw new D(`[FormBuilder] ${i} has a malformed where: pipe "${o.trim()}". Write where:property=value or where:property in (a,b).`,[{path:[t.id,r.attribute.name,`prefillExpression`],message:`Malformed where: pipe`}])}}}validateReadOnly(){for(let e of this.data.steps)for(let t of e.rows)if(isFormFieldsRow(t))for(let n of t.fields){if(Ia.safeParse(n.readOnly).success)continue;let t=isFormFreeFieldRef(n)?n.attribute.name:n.attribute,r=isFormFreeFieldRef(n)?`free field`:`field`;throw new D(`[FormBuilder] readOnly on ${r} "${t}" in step "${e.id}" must be a boolean.`,[{path:[e.id,t,`readOnly`],message:`Expected a boolean`}])}}validateFreeFields(){let e=new Set(Fi);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: ${Fi.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(tr(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);Vt([...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&&zt(e)}};function object(e){if(Dt(e.name))throw new ft(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=S.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 La=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=Ne.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 La({name:e,label:t,object:void 0,context:`record`,contents:[]})}function listView(e,t){return new La({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}},Ra=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 Ra(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 $e(`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 za=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 Ba=Symbol(`stndrds.native-object`);function markNativeDefinition(e){return Object.defineProperty(e,Ba,{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[Ba]===!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(Dt(e.name)&&!isNativeDefinition(e))throw new ft(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 $e(`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 Va=new NativeObjectRegistryClass,Ha=new WeakSet;function markSystemView(e){return Ha.add(e.definition),e}function isSystemViewDefinition(e){return typeof e==`object`&&!!e&&Ha.has(e)}const Ua=`## 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
|
+
`,Wa=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(or).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(ar).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(
|
|
36
|
+
{{ content }}`).attribute(text({name:`name`,label:`Name`}).maxLength(or).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(ar).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(Ua)).build(),Ga=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()),Ka=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()),qa=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(ir).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(rr).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(),
|
|
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(ir).required()).attribute(text({name:`description`,label:`Description`}).multiline().maxLength(rr).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(),Ja={combinator:`and`,rules:[{attribute:`invalidAt`,operator:`is_empty`,value:null},{attribute:`reviewState`,operator:`is_empty`,value:null}]},Ya=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()),Xa=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(Ja).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(Ja).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`,Za=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(),Qa=markSystemView(detailView(`drive-detail`,`Drive`).for(V).default().tab(`documents`,`Documents`,B.documents()).aside(`details`,`Details`,B.form(group(`details`,`Details`).field(`description`))).build()),$a=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()),eo={name:`artifact_preview`,requiresRecord:!0,parameters:M.object({}).strict()},H=`artifact`,to=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(),no=markSystemView(detailView(`artifact-detail`,`Artifact`).for(H).default().tab(`preview`,`Preview`,B.custom(eo,{})).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()),ro=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`},io=`meeting-list`,ao=`calendar-sync`,oo=`meeting-detail`,so=[W.title,W.startsAt,W.endsAt,W.status],co=nativeObject({name:U,label:`Meeting`}).sealed().hidden().metadata({platformOwned:{editable:[W.linkedRecords],source:ao}}).icon(`calendar`).pluralLabel(`Meetings`).labelExpression(`{{ title }}`).embeddingExpression(`{{ title }}
|
|
41
41
|
{{ description }}
|
|
42
42
|
{{ participants }}
|
|
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(),
|
|
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 io=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 ao=new Map(Ee().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 C(t,e.name);r.set(e.name,e)}),r}const oo=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)??ao.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`?Fe():be(),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 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 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 so=[Object.freeze(qa)];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 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 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 so)this.extensions.set(e.name,e)}};const co=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 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 lo=new FormRegistry,uo=[`attestorIdentity`,`evidenceDigest`,`maintenanceEpoch`,`observedZeroAt`,`resumeRevision`,`version`,`workloadInventoryDigest`],fo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,po=/^[0-9a-f]{40}$/,mo=/^[0-9a-f]{64}$/,ho=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/,go=/^(\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=go.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!==uo.length||n.some((e,t)=>e!==uo[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`,fo,`must be a lowercase canonical UUID`),i=requirePattern(e,`resumeRevision`,po,`must be a lowercase 40-character Git SHA`),a=requireCanonicalTimestamp(e),o=requirePattern(e,`attestorIdentity`,ho,`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`,mo,`must be exactly 64 lowercase hexadecimal characters`),evidenceDigest:requirePattern(e,`evidenceDigest`,mo,`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 _o=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 vo=204800,yo=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 bo=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}),xo=[`membership-unknown`,`sort-unknown`,`permissions-changed`],So=[`permission-revoked`,`workspace-left`,`object-deleted`],Co=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],wo=[`type`,`objectId`,`recordId`,`recordVersion`],To=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],Eo=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],Do=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&bo.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,dr)}function isNotificationPriority(e){return isOneOf(e,fr)}function isNotificationSensitivity(e){return isOneOf(e,pr)}function isNotificationInboxState(e){return isOneOf(e,mr)}function isNotificationWorkState(e){return isOneOf(e,hr)}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,wo)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$2(e)&&hasOnlyKeys(e,Eo)&&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,To)&&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,xo)}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=>Co.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,Do)&&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 Oo=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,Oo)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const ko=[`ok`,`low`,`exhausted`,`paused`],Ao=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,ko)&&isOneOf(e.mode,Ao)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,So)}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 jt(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(!Ot(e))throw new ComputedFormulaCompileError(`Unknown computed function "${e}"`);let r=Ht[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 jo=[{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)`}],Mo=new Date(0).setUTCFullYear(1,0,1),No=/^\d{4}-\d{2}-\d{2}$/,Po=new Set([`createdAt`,`updatedAt`,`deletedAt`]),Fo=/^(\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=Fo.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<Mo?null:m}function unwrapRange(e){return Jt(e)?kt(e):e}function hasTime(e){return e.type===`date`&&e.includeTime===!0}function isSystemTimestamp(e){return Po.has(e.name)}function instantWindow(e){let t=parseFilterInstant(e);return t===null?null:{startMs:t,endMs:t+(typeof e==`string`&&No.test(e)?864e5:1)}}function storedUtcDay(e){let t=unwrapRange(e);if(t instanceof Date)return Number.isNaN(t.getTime())?null:Ve(t.getTime());if(typeof t!=`string`||t===``)return null;if(No.test(t))return t;let n=new Date(t);return Number.isNaN(n.getTime())?null:Ve(n.getTime())}function comparandDay(e){return e instanceof Date?Number.isNaN(e.getTime())?null:Ve(e.getTime()):typeof e==`string`?No.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)}),Io={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=_e(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}),Lo=[...Object.entries(he).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,...Lo])}function evaluateFilterState(e,t,n){if(e.rules.length===0)return!0;let r=new Map(n.map(e=>[e.name,e])),i=e.combinator===`or`?`some`:`every`;return e.rules[i](e=>evaluateRule(e,t,r))}function evaluateRule(e,n,r){let i=r.get(e.attribute);if(!i)return!1;if(e.property&&i.type===`location`){if(!(we(e.property)&&a(e.operator)))return!1;let t=Io[e.operator];if(!t)return!1;let r=n[e.attribute],o=typeof r==`object`&&r?r[e.property]:void 0;return evaluateNormalizedComparands(t,`text`,e.operator,o,e.value,i)}if(e.property){let r=resolvePropertyDefinitions(i).find(t=>t.name===e.property);if(!r)return!1;let a=p(e.operator),o=Io[a];if(!o?.appliesTo.includes(r.type))return!1;let s=n[e.attribute],c=(Array.isArray(s)?s:s==null?[]:[s]).some(t=>{if(typeof t!=`object`||!t)return!1;let n=t.props;return typeof n!=`object`||!n?!1:evaluateNormalizedComparands(o,r.type,a,n[e.property],e.value,r)});return(e.quantifier??t(e.operator))===`none`?!c:c}let o=Io[e.operator];if(!o||!o.appliesTo.includes(i.type))return!1;let s=n[e.attribute],c=i.type===`relation`||i.type===`document`||i.type===`user`?normalizeReferenceIds(s):s;return evaluateNormalizedComparands(o,i.type,e.operator,c,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 Wn(t.phoneNumber);let n=typeof t.countryCode==`string`?t.countryCode:r;return`${n}:${Un(t.phoneNumber,n)}`};return[normalizeOne(e),normalizeOne(t)]}function normalizeComparableValue(e,t){return e===`currency`?g(t):e===`date`?Jt(t)?kt(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 Ro=`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]=S(e).storage.cardinality===`many`?[a]:a)}return i}function extractDeterministicValue(e,t){if(e.operator===`is`)return f(e.value)?resolveDynamicValue(e.value,t):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator===`any_of`){if(!Array.isArray(e.value)||e.value.length!==1)return;let n=e.value[0];return f(n)?resolveDynamicValue(n,t):n}}function resolveDynamicValue(e,t){if(t){if(e.dynamic===`actor`)return t.userId;if(e.anchor===`today`)return dateInTimezone(t.now,t.timezone);if(e.anchor===`now`)return t.now.toISOString()}}function requestedCapabilities(e){let t=[];return e.canModify&&t.push(`modify`),e.canSend&&t.push(`send`),t}const zo={status:`connector_status`,error:`connector_error`,provider:`connector_provider`},Bo=100;let Vo=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const Ho=`DRAFT`;function isProviderDraft(e){return e.includes(Ho)}const Uo=[`threads`,`messages`];function isMailboxListMode(e){return Uo.includes(e)}const Wo=[`reply`,`reply_all`];function isReplyMode(e){return Wo.includes(e)}const Go=2e5,Ko=998,qo=[`force`,`skip`],Jo=[`none`,`all`,`external_only`],Yo=`x-fake-signature`,Xo={override:null,status:`none`,failureReason:null,botId:null},Zo=/^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&&!Zo.test(t)?t:e.firstUserText?buildAgentFallbackTitle(e.firstUserText):e.emptyLabel}const Qo=/^[a-z0-9][a-z0-9-]{0,62}$/;function assertSchemaSourceId(e){if(!Qo.test(e))throw new D(`Invalid schema source id "${e}": expected a lowercase slug matching ${Qo}`,[])}const $o={phone:`text`,currency:`number`},es={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(Kt(t)||refuse$1(e,void 0,`Resolution ${e} must be an object`),t.kind===`rename`){assertKeys(e,t,es.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,es[t.to]),t.to===`phone`){let n=t.defaultCountryCode;/^[A-Z]{3}$/.test(n)&&lr(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)&&cr(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=ur(n,Kn(t));if(!r?.isPossible()||r.country===void 0||r.ext!==void 0)return;let i=sr(r.country)?.iso3;if(i!==void 0)return{value:{countryCode:i,phoneNumber:Un(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 ts=M.object({mode:M.enum([`inline`,`window`]),interaction:M.enum([`static`,`interactive`]),size:M.enum([`compact`,`regular`]),aspectRatio:M.number().positive().finite().optional()}).strict(),ns=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(ki),display:ts}).strict();function readArtifactResult(e){let t=ns.safeParse(e);return t.success?t.data:null}const rs=M.string().regex(/^[^/\s]+\/[^/\s]+$/),is=M.object({kind:M.literal(`generated-image`),artifact:M.unknown(),generation:M.object({attemptId:M.uuid(),requestedModelId:rs,executedModelId:rs.nullable(),format:M.enum(Wi),mimeType:M.enum([`image/png`,`image/jpeg`,`image/webp`])}).strict()}).strict();function readGeneratedImageResult(e){let t=is.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 as={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,as)}}return[...t.values()]}const os={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,os)}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,os)}}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=jt(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 compareByRecommendation(e,t){return(e.recommendationRank??2**53-1)-(t.recommendationRank??2**53-1)||e.label.localeCompare(t.label)}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 ss=/^[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);(!ss.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??re(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&&!zn(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)&&!zn(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),te=r.find(e=>e.id===b&&pairKey(e.addresses)!==g);(!ss.test(b)||te||u.has(b)&&u.get(b)!==g)&&reject(d,`pair`,`Invalid or duplicate pair identity for ${d} and ${p}`),u.set(b,g);let ne=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:ne===d},v.bilateral={...v.bilateral,cardinality:a.cardinality,label:a.label,storageOwner:ne===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:ne,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(),cs=M.enum(Ar),ls=M.enum(jr),us=M.enum(Mr),ds=M.enum(Fr),fs=M.object({provider:cs,model:M.string().min(1)}).strict(),ps=M.object({speed:ls.optional(),reasoning:us.optional(),routing:ds.optional()}).strict(),ms=M.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),hs=M.object({model:fs.optional(),speed:ls.optional(),reasoning:us.optional(),imageModel:ms.optional(),routing:ds.optional()}).strict(),gs=hs.refine(e=>Lr.some(t=>e[t]!==void 0),{message:`At least one inference override is required`}),_s=M.object({model:fs.nullable().optional(),speed:ls.nullable().optional(),reasoning:us.nullable().optional(),imageModel:ms.nullable().optional(),routing:ds.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`}),vs=M.object({model:M.string().min(1),routing:M.object({mode:M.literal(`auto`),tasks:M.array(M.enum(Nr)).optional(),demand:M.enum(Pr).optional(),reason:M.enum([`selected`,`retained`,`fallback`]).optional(),relation:M.enum([`continue`,`modify`,`new`,`aside`,`unknown`]).optional(),anchorMessageId:M.string().min(1).optional()})}),ys=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(),bs=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(Wr)}).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:ys.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()]),xs=M.object({id:M.string(),name:M.string(),mimeType:M.string(),size:G}).strict(),Ss=M.object({id:M.string(),artifactId:M.string(),revision:M.number().int().min(1),selectedText:M.string()}).strict(),Cs=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(),ws=M.object({provider:cs,model:M.string(),maxTokens:G.optional(),contextWindow:G.optional()}).strict(),Ts=M.union([M.date(),M.string().datetime({offset:!0}).transform(e=>new Date(e))]),Es=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(bs),attachments:M.array(xs).optional(),mentions:M.array(Cs).optional(),quotes:M.array(Ss).optional(),model:ws.optional(),tokenUsage:M.object({input:G,output:G}).strict().optional(),metadata:M.record(M.string(),M.unknown()).optional(),createdAt:Ts}).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(),Os=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(),ks={"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:Es}).strict(),"message-persisted-ref":M.object({messageId:M.string().min(1)}).strict(),"message-updated":M.object({message:Es}).strict(),"todo-plan-update":M.object({plan:Os}).strict(),"approval-context":M.object({approvalId:M.string(),toolCallId:M.string(),impact:ys.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 ks}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:ks[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 As=M.object({type:M.enum(Rr),color:M.enum(nr),expression:M.enum(zr).default(`relaxed`)}).strict(),js=M.array(M.string().trim().min(1).max(200)).max(4);function agentAvatarFromMetadata(e){let t=As.safeParse(e);return t.success?t.data:void 0}const Ms=[`record.created`,`record.updated`,`record.deleted`,`form.submitted`,`agent.completed`,`webhook`],Ns=new Set([`record.created`,`record.updated`,`record.deleted`]),Ps=/^[A-Z_][A-Z0-9_]*$/,Fs=M.object({cron:M.string().min(9),timezone:M.string().optional(),enabled:M.boolean(),input:M.record(M.string(),M.unknown()).optional()}),Is=M.object({name:M.string().max(120).optional(),eventType:M.enum(Ms),objectId:M.guid().optional(),watchedFields:M.array(M.string()).max(50).optional(),debounceMs:M.number().int().min(0).max(3e5).optional(),filter:M.object({combinator:M.enum([`and`,`or`]).default(`and`),rules:M.array(M.object({attribute:M.string(),operator:M.string(),value:M.unknown().optional()}))}).optional(),formDefinitionId:M.string().optional(),sourceAgentId:M.guid().optional(),enabled:M.boolean().optional()});function refineTrigger(e){return e.refine(e=>!e.watchedFields?.length||e.eventType===`record.updated`,{message:`watchedFields requires eventType=record.updated`,path:[`watchedFields`]}).refine(e=>!(e.eventType&&Ns.has(e.eventType))||!!e.objectId,{message:`objectId is required for record.* triggers`,path:[`objectId`]})}const Ls=[`Very economical`,`Balanced`,`Powerful`,`Very powerful`],Rs=[`unsupported`,`effort`,`toggle`,`budget`,`model-controlled`],zs=[`text`,`image`,`audio`,`video`,`pdf`],Bs=/^\d+x\d+$/,Vs=/^\d+:\d+$/,Hs=/^[a-z0-9][a-z0-9-]*$/,Us=.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>Us?`implausible`:n===0&&!t?`undeclared-zero`:null}const Ws=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(Ws).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 ${Us} 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(Ar,{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(Ls,{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(Mr)).optional(),reasoningMode:M.enum(Rs).optional(),inputModalities:M.array(M.enum(zs)).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(Nr),M.enum(Pr)).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=>Bs.test(String(e)))}),M.looseObject({aspectRatio:M.custom(e=>Vs.test(String(e)))})],{error})}function catalogImageModelSchema(e){let t=`image model "${e}"`,n=`${t} has no usable formats`;return M.looseObject({id:ms,name:nonEmptyString(`${t} has no usable name`),provider:nonEmptyString(`${t} has no usable provider`).regex(Hs,{error:`${t} names an unusable provider`}),formats:M.array(M.enum(Wi,{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 Gs=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 Ks=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`||!Ks.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(Gs,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 qs=[`pluralLabel`,`description`,`labelExpression`,`embeddingExpression`];function draftObjectSettings(e){return Object.fromEntries(qs.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 Js={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={...Js,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`)},Ys=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 Xs=M.unknown().transform((e,t)=>{let n=x.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}}),Zs=M.object({...J,type:M.literal(`replace_view_content`),definition:Xs}).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}}),Qs=x.describe(`The whole content definition.`),$s=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:Zs,wire:M.object({...J,type:M.literal(`replace_view_content`),definition:Qs}).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}}))}),ec=M.object({...q,type:M.literal(`add_view_content`),content:Qs,target:Ys.describe(`Where to place the new content within its placement zone`)}).strict(),addFocus=e=>({...viewFocus(e),contentName:e.content.name}),tc=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:ec,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}}})}),nc=M.object({...J,type:M.literal(`remove_view_content`)}).strict(),rc=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:nc,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 ic=M.object({...J,type:M.literal(`move_view_content`),placement:M.enum([`main`,`aside`]).describe(`The placement zone to move the content into`),target:Ys.describe(`Where to place the content within that placement zone`)}).strict(),ac=defineOperation({type:`move_view_content`,summary:`Reorders or moves a content to a different placement; the aside rule applies.`,schema:ic,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)}}})}),oc=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:k.nullable().optional().describe(`New icon; null clears it`)}).strict().refine(e=>Object.keys(e).length>0).describe(`≥1 change`)}).strict(),sc=defineOperation({type:`update_view_metadata`,summary:`Updates a view's label, description, or icon (null clears the icon).`,schema:oc,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}})}),cc=M.string().refine(e=>e.trim().length>0,`API name must not be blank`),lc=M.object({...q,type:M.literal(`rename_view`),newName:cc.describe(`New API name for the view`)}).strict(),renameViewFocus=e=>({objectName:e.objectName,viewName:e.newName}),uc=defineOperation({type:`rename_view`,summary:`Renames a view; refused on a code-declared name — change it in the declaration.`,schema:lc,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}))}),dc=M.object({...J,type:M.literal(`rename_view_content`),newName:cc.describe(`New API name for the content`)}).strict(),renameContentFocus=e=>({...viewFocus(e),contentName:e.newName}),fc=defineOperation({type:`rename_view_content`,summary:`Renames a content; refused on a code-declared name — change it in the declaration.`,schema:dc,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}}})}),pc=M.object({...J,type:M.literal(`reset_view_content`)}).strict(),mc=defineOperation({type:`reset_view_content`,summary:`Resets a content to its code-declared source, if one exists.`,schema:pc,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}})})}),hc=M.object({...q,type:M.literal(`reset_view_order`),placement:M.enum([`main`,`aside`]).describe(`The placement zone to reset to source order`)}).strict(),gc=defineOperation({type:`reset_view_order`,summary:`Resets a placement zone's order to its code-declared source, if one exists.`,schema:hc,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}})}),_c=M.discriminatedUnion(`type`,[Zs,ec,nc,ic,oc,lc,dc,pc,hc]),Y=[$s,tc,rc,ac,sc,uc,fc,mc,gc];function findObject(e,t){return e.objects.find(e=>e.id===t)}const vc=new Set([`formula`,`rollup`]);function isComputedAttribute(e){return vc.has(e.attributeType)}const yc={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 yc?yc[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 bc={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,bc,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=>S(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={...Js,objectId:M.string().uuid().describe(`The object this operation acts on`)},xc=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:Bt.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} »`}),Sc=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}),Cc=defineOperation({type:`update_object`,summary:`Updates an object's label, icon, pluralLabel, description, labelExpression, embeddingExpression.`,schema:Sc,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)}),wc={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])=>wc[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 Tc=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}`}),Ec=u;function assertConfigParses(e,t){try{un(e,t)}catch(e){throw e instanceof D?new D(e.message,e.errors.map(e=>({...e,path:[`config`,...e.path??[]]}))):e}}const Dc=M.object({...X,type:M.literal(`add_attribute`),attributeId:M.string().min(1),name:cn,label:M.string().min(1),attributeType:M.enum(Ec),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}}),Oc=cn.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),kc={...Js,type:M.literal(`add_attribute`),attributeId:M.string().min(1).describe(`Stable attribute id`),name:Oc,label:M.string().min(1).describe(`Label people see`)},Ac=Object.fromEntries(gn.map(e=>[e,!0]));function wireWriteConfigOf(e){let t=pn(e).omit(Ac),n=fn[e];return n===void 0?t:t.extend(n)}const jc=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],Mc=M.object(jc.reduce((e,t)=>(Object.assign(e,wireWriteConfigOf(t).shape),e),{})).strict(),Nc=Ec.filter(e=>!jc.includes(e)),Pc=Object.fromEntries(jc.map(e=>[e,new Set(Object.keys(wireWriteConfigOf(e).shape))])),Fc=on(Pc,`config key`);function refuseForeignSimpleConfigKeys(e,t){Fc(e.attributeType,e.config,t,[`config`])}function wireConfigFor(e){let t=wireWriteConfigOf(e);return(e===`relation`||e===`document`?t.extend({properties:dn.optional()}):t).strict()}const Ic=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:Dc,wire:M.discriminatedUnion(`attributeType`,[M.object({...kc,objectId:M.string().uuid(),attributeType:M.enum(jc).describe(`Attribute type`),config:Mc.optional().describe(`Configuration of a simple attribute (text, number, date…)`)}).strict().superRefine(refuseForeignSimpleConfigKeys),...Nc.map(e=>M.object({...kc,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} »`}),Lc={...X,attribute:cn.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 Rc=M.object({...Lc,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`),icon:k.nullable().optional().describe(`Relation only: icon from search_icons; null clears it`)}).refine(e=>Object.keys(e).length>0,`update_attribute needs at least one change`).describe(`≥1 change`)});function updatedAttributeConfig(e,t){let n=t.config??e;if(t.icon===void 0)return n;let{icon:r,...i}=n??{};return t.icon===null?i:{...i,icon:t.icon}}const zc=defineOperation({type:`update_attribute`,summary:"Updates label, a relation's icon, or the whole config (replaced). A published config is frozen, except `bilateral` alone (all else identical) to pair a published relation with its inverse; else add a new attribute and migrate values.",schema:Rc,apply:(e,t)=>{let{object:n,attribute:r}=requireAttribute(e,t.objectId,t.attribute,`update_attribute`),{icon:i,config:a,...o}=t.changes;if(i!==void 0&&r.attributeType!==`relation`){let e=`icon is only for relation attributes; "${r.name}" is a ${r.attributeType} attribute`;throw new D(e,[{path:[`changes`,`icon`],message:e}])}a!==void 0&&assertConfigParses(r.attributeType,a);let s=updatedAttributeConfig(r.config,{config:a,icon:i}),c={...r,...o,...s===void 0?{}:{config:s}},l=withDerivedViews(e,n,e.attributes.map(e=>e===r?c:e));return assertConfigFolds(l,c),reconcileDraftRelationAttribute(l,c,t.id,r)},focus:existingAttributeFocus,presentation:definePresentation(existingAttributeFocus,`atomic`),describe:e=>e.changes.label?`Renomme l'attribut « ${e.attribute} » en « ${e.changes.label} »`:e.changes.config===void 0&&e.changes.icon===null?`Retire l'icône de l'attribut « ${e.attribute} »`:e.changes.config===void 0&&e.changes.icon!==void 0?`Change l'icône de l'attribut « ${e.attribute} » en « ${e.changes.icon} »`:`Modifie l'attribut « ${e.attribute} »`}),Bc=M.object({...Lc,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 Vc=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:Bc,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} »`}),Hc=M.object({...Lc,type:M.literal(`rename_draft_attribute`),name:Oc});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 Uc=defineOperation({type:`rename_draft_attribute`,summary:`Renames a draft-added attribute; views and samples follow.`,schema:Hc,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{Yn(i)}catch{return}let a=Zn(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 Wc=M.guid();function carriesNonRecordId(e){let t=Array.isArray(e)?e:[e],n=relationValueIds(e);return n.length<t.length||n.some(e=>!Wc.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 Gc=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=[xc,Cc,Tc,Ic,zc,Vc,Uc,Gc,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 Kc=build(),qc=[...Kc.keys()];function defOf(e){let t=Kc.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=Kc.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 Jc=`bilateral`;function frozenPart(e){if(!e||typeof e!=`object`)return A({});let{[Jc]: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()]),Yc=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=_c.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 Xc=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=Yc.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 Zc={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`},Qc=`normal`;function operationPace(e){return Object.hasOwn(Zc,e)?Zc[e]:Qc}const $c={major:{replay:4e3,live:2500},normal:{replay:2600,live:1800},minor:{replay:1400,live:1100}};function dwellForStep(e,t,n){let r=($c[e]??$c[Qc])[t],i=900+40*(n||0);return Math.min(6e3,Math.max(r,i))}const Q=M.string().min(1),el=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=el.safeParse(e);if(!t.success)throw new D(`Invalid scoped target`,[{path:[`target`],message:`Expected exactly one named target branch`}]);return t.data}const tl=M.object({type:M.literal(`remove_operation`),operationId:M.string().min(1).describe(`The id of a stored operation to drop from the draft`)}),nl=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 rl={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of rl[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 il=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:il}).strict())})}const al=membersOf(Z,[tl]),ol=membersOf(Y),sl=unionOf(al),cl=unionOf(ol),ll={schema:sl,view:cl},ul={schema:unionOf(wireMembersOf(Z,[tl])),view:unionOf(wireMembersOf(Y))},dl=new Map([...Z.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...Y.map(e=>[e.type,`view`])]);function familyOf(e){return dl.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 S(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 fl=[`draft_schema`],pl=`discard_architect_draft`,ml=`request_design_review`,hl=`get_architect_draft`,gl=[{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`),_l=M.union([M.tuple([M.literal(`object`),$]),M.tuple([M.literal(`attribute`),$,$]),M.tuple([M.literal(`view`),$,$]),M.tuple([M.literal(`content`),$,$,$])]),vl=M.object({label:$,pluralLabel:M.string().optional(),description:M.string().optional(),icon:k.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`:vl.parse(n);break;case`attribute`:{let e=M.enum(u).parse(n.type);$t(e).extend({type:M.literal(e),label:$,required:M.boolean().optional(),unique:M.boolean().optional(),icon:k.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`),ke.parse({...r,object:e[1],name:e[2],contents:[]});break}case`content`:x.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=_l.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:_l,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{Xc as ABSENT_TARGET_TOKEN,zr as AGENT_AVATAR_EXPRESSIONS,Rr as AGENT_AVATAR_TYPES,Yr as AGENT_MESSAGE_KIND,Jr as AGENT_NOTIFICATION_KIND,Br as AGENT_STARTERS_MAX,Vr as AGENT_STARTER_MAX_LENGTH,Nr as AGENT_TASK_KINDS,vo as AGENT_UI_BATCH_MAX_BYTES,yo as AGENT_UI_BATCH_MAX_ITEMS,Xi as ALLOWED_PROPERTY_TYPES,qc as ALL_OPERATION_TYPES,ra as ALL_PIPES,Ai as ARTIFACT_FILE_ROLES,Oi as ARTIFACT_KINDS,Xa as ARTIFACT_LIST_VIEW,Ja as ARTIFACT_OBJECT,H as ARTIFACT_OBJECT_NAME,qa as ARTIFACT_PREVIEW_EXTENSION,ki as ARTIFACT_RETENTIONS,Ya as ARTIFACT_VIEW,Re as ATTRIBUTE_FILTER_OPERATORS,u as ATTRIBUTE_TYPES,wr as AUDIT_ACTIONS,Tr as AUDIT_AGENT_SESSION_METADATA_KEY,Cr as AUDIT_RESOURCE_TYPES,Ke as AccessDeniedError,AgentBuilder,qe as AmbiguousSchemaChangeError,Je as AttributeInUseError,Ye as AttributeNotFoundError,xr as BEHAVIOR_PROPERTIES,hi as BROWSER_IMAGE_MAX_BYTES,Ji as BYTE_UNIT_LABELS,pa as CATALOG_RESOURCES,Dr as CLAIMABLE_SESSION_STATUSES,Ht as COMPUTED_FUNCTIONS,jo as COMPUTED_FUNCTION_METADATA,ln as COMPUTED_FUNCTION_NAMES,zo as CONNECTOR_CALLBACK_PARAM,Gi as COUNT_MODES,fa as CUSTOM_LEVEL,ComputedFormulaCompileError,Mt as ComputedFormulaParseError,Xe as ConcurrentModificationError,z as ContentBuilder,va as DB_COLUMN_FIELDS,Da as DEFAULT_AGENT_EXECUTION_CONFIG,Or as DEFAULT_APPROVAL_POLICY,Kr as DEFAULT_DAILY_ACTIVITY_DAYS,fi as DEFAULT_DICTATION_LIMITS,ia as DEFAULT_LABEL_FALLBACK,Ii as DEFAULT_MEETING_BOT_DISPLAY_NAME,ya as DEFAULT_ROLES,xa as DEFAULT_ROLE_DESCRIPTIONS,ba as DEFAULT_ROLE_LABELS,Ca as DEFAULT_ROLE_PERMISSIONS,wa as DEFAULT_ROLE_REVOCATIONS,Li as DEFAULT_TENANT_SETTINGS,On as DEFAULT_VALIDATION_MESSAGES,gi as DEVICE_CHANNEL_AUTHENTICATE_TIMEOUT_MS,_i as DEVICE_CHANNEL_IDLE_POLL_MS,yi as DEVICE_CHANNEL_KEEPALIVE_MS,mi as DEVICE_CHANNEL_MAX_FRAME_BYTES,pi as DEVICE_CHANNEL_PATH,vi as DEVICE_CHANNEL_PRESENCE_MS,Ci as DEVICE_CHANNEL_UPGRADE_REQUIRED_REASON,bi as DEVICE_CHANNEL_WORKER_CLOSE_PROTOCOL_VIOLATION,Si as DEVICE_COMMAND_ERROR_CODES,ui as DICTATION_FINALIZATION_TIMEOUT_MS,ii as DICTATION_FRAME_BYTES,oi as DICTATION_MAX_BUFFER_BYTES,ai as DICTATION_MAX_FRAME_BYTES,si as DICTATION_MAX_TRANSCRIPT_BYTES,di as DICTATION_MODEL_ID,li as DICTATION_PREPARATION_TIMEOUT_MS,ri as DICTATION_SAMPLE_RATE,ci as DICTATION_TICKET_TTL_MS,pl as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,Yi as DOCUMENT_SYSTEM_ATTRIBUTES,Ec as DRAFTABLE_ATTRIBUTE_TYPES,nl as DRAFT_BATCH_LIMIT,qs as DRAFT_OBJECT_SETTINGS,gl as DRAFT_SCHEMA_INPUT_EXAMPLES,fl as DRAFT_WRITE_TOOL_NAMES,Ka as DRIVE_LIST_VIEW,Wa as DRIVE_OBJECT,V as DRIVE_OBJECT_NAME,Ga as DRIVE_VIEW,DeviceChannelProtocolError,Di as DeviceChannelServerFrameSchema,Ei as DeviceChannelWorkerFrameSchema,DraftRefusalError,C as DuplicateError,ea as EMPTY_VALUE_PLACEHOLDER,Ps as ENV_VAR_KEY_PATTERN,Ki as ESTIMATED_COUNT_CAP,Yo as FAKE_MEETING_BOT_SIGNATURE_HEADER,ll as FAMILY_INPUTS,ul as FAMILY_WIRE_INPUTS,Ni as FORM_FORBIDDEN_ATTRIBUTE_TYPES,FlagRegistry,FlagService,Ze as ForbiddenError,FormBuilder,FormRegistry,FormRowBuilder,FormStepBuilder,hl as GET_ARCHITECT_DRAFT_TOOL_NAME,ja as GroupBuilder,br as IDENTITY_PROPERTIES,Wi as IMAGE_FORMATS,Mr as INFERENCE_REASONING_OPTIONS,Fr as INFERENCE_ROUTING_MODES,jr as INFERENCE_SPEEDS,oo as INVENTORY_LIMIT,Qe as InvalidPermissionGrantError,Gr as LAST_RUN_ERROR_MAX_LENGTH,Rt as LIST_VIEW_TAB_VISIBILITIES,bo as LIVE_EVENT_TYPES,Oe as LOCATION_FILTER_PROPERTIES,Uo as MAILBOX_LIST_MODES,Go as MAIL_DRAFT_BODY_MAX_CHARS,Ko as MAIL_SUBJECT_MAX_CHARS,qr as MAX_DAILY_ACTIVITY_DAYS,ji as MAX_PRESET_DEPTH,Zr as MAX_TODOS,$r as MAX_TODO_DESCRIPTION_CHARS,Qr as MAX_TODO_ID_CHARS,Bo as MCP_SERVER_NAME_MAX_LENGTH,W as MEETING_ATTRIBUTES,$a as MEETING_DETAIL_VIEW_ID,ro as MEETING_LIST_VIEW,Za as MEETING_LIST_VIEW_ID,to as MEETING_OBJECT,U as MEETING_OBJECT_NAME,no as MEETING_VIEW,Qa as MEETING_WRITE_SOURCE,Ua as MEMORY_LIST_VIEW,Ba as MEMORY_OBJECT,Ha as MEMORY_VIEW,_a as MIXED_LEVEL,Vo as McpOAuthCompletionMode,$e as MemoryNotFoundError,MultiRelationAttributeBuilder,ti as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,ni as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,Wt as NATIVE_OBJECT_NAMES,mr as NOTIFICATION_INBOX_STATES,dr as NOTIFICATION_KINDS,fr as NOTIFICATION_PRIORITIES,pr as NOTIFICATION_SENSITIVITIES,yr as NOTIFICATION_TYPES_V1,vr as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,gr as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,_r as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,hr as NOTIFICATION_WORK_STATES,da as NO_ACCESS,Xo as NO_RECORDING,ne as NO_VALUE_OPERATORS,Rn as NonJsonValueError,NoopGeocodingAdapter,w as NotFoundError,et as NotImplementedError,I as OBJECT_GRANT,Bt as OBJECT_NAME_SCHEMA,Ur as OPEN_TOOL_PART_STATES,Zc as OPERATION_PACE,Kc as OPERATION_REGISTRY,s as OPERATORS_BY_TYPE,Io as OPERATOR_SPECS,ObjectBuilder,tt as ObjectNotFoundError,nt as ObjectReferencedError,rt as OrphanSystemAttributeError,$c as PACE_DWELL_MS,ha as PERMISSION_ACTIONS,L as PERMISSION_CAPABILITIES,ua as PERMISSION_CATALOG,na as PIPES_WITH_ARGS,sa as PREFERRED_NAME_MAX_LENGTH,Sr as PRESENTATION_PROPERTIES,Ho as PROVIDER_DRAFT_LABEL,Ar as PROVIDER_NAMES,Jc as PUBLISHED_CONFIG_EXCEPTION,it as ProtectedResourceError,at as ProtectedRoleError,te as QUALIFIED_SEPARATOR,qi as QUOTA_KEYS,Mi as RECENT_ACTIVITY_LEDGER_LIMIT,qo as RECORDING_OVERRIDES,Jo as RECORDING_POLICIES,Pi as RECORD_ACCESS_ROLES,Fi as RECORD_ACCESS_SOURCES,la as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,ie as RELATION_TARGET_ANY,fe as REMOVED_OPERATOR_REPLACEMENTS,tl as REMOVE_OPERATION_SCHEMA,Wo as REPLY_MODES,ml as REQUEST_DESIGN_REVIEW_TOOL_NAME,hn as RESERVED_ATTRIBUTE_NAMES,Lt as RESERVED_OBJECT_NAMES,Xt as RESOURCE_VISIBILITIES,Ir as ROUTING_PRICE_CEILINGS,ot as RealtimeDeliveryError,st as RealtimeRateLimitedError,ct as RealtimeSubscriptionError,lt as RecordNotFoundError,ut as RecordReferencedError,dt as RepositoryError,ft as ReservedObjectNameError,pt as RoleNotFoundError,Pt as SCHEMA_LIMITS,Z as SCHEMA_OPERATIONS,sl as SCHEMA_OPERATION_INPUT,Qo as SCHEMA_SOURCE_ID_PATTERN,$o as SCHEMA_SOURCE_RETYPE_FROM,Lr as SESSION_INFERENCE_PATCH_KEYS,ei as SESSION_STATE_STREAM_ID,Er as SESSION_TERMINAL_STATUSES,ta as SIMPLE_PIPES,vn as SIMPLE_PROPERTY_TYPES,Ia as SKILL_CONTENT_TEMPLATE,za as SKILL_LIST_VIEW,La as SKILL_OBJECT,Ra as SKILL_VIEW,Oa as STANDARD_SCHEMA_VENDOR,We as SYNONYM_ALIASES,pe as SYSTEM_ATTRIBUTES,ge as SYSTEM_ATTRIBUTE_I18N_KEYS,Yt as SYSTEM_FIELD_NAMES,he as SYSTEM_FILTER_ATTRIBUTE_TYPES,Wr as SYSTEM_PART_CODES,T as SchemaError,E as SchemaErrorCode,mt as SearchBackendError,SingleRelationAttributeBuilder,ht as StorageError,gt as SyncCascadeError,_t as SyncConflictError,vt as SyncError,yt as SystemEntityImmutableError,Pr as TASK_DEMAND_LEVELS,Ri as TENANT_INVITATION_DEFAULT_TTL_MS,Bi as TENANT_INVITATION_MAX_TTL_MS,zi as TENANT_INVITATION_MIN_TTL_MS,Vi as TENANT_INVITATION_RESEND_INTERVAL_MS,Tn as TEXT_FORMAT_PATTERNS,Ro as TODAY_DEFAULT,kr as TODO_PLAN_STATUSES,Xr as TODO_STATUSES,Hr as TOOL_APPROVAL_STATES,Zi as TOOL_NAME_SEPARATOR,Ms as TRIGGER_EVENT_TYPES,Hi as USER_STATUSES,Ui as USER_WORK_POSTURES,Y as VIEW_OPERATIONS,cl as VIEW_OPERATION_INPUT,D as ValidationError,Aa as ViewBuilder,gn as WIRE_OMITTED_CONFIG_KEYS,Ta as WORKSTATION_HARNESSES,agent,agentAvatarFromMetadata,As as agentAvatarSchema,agentDataChunk,agentDisplayName,ps as agentInferencePreferencesSchema,xs as agentMessageAttachmentSchema,bs as agentMessagePartSchema,Fs as agentScheduleSchema,hs as agentSessionInferenceOverridesInputSchema,gs as agentSessionInferenceOverridesSchema,Es as agentSessionMessageSchema,js as agentStartersSchema,Is as agentTriggerBaseSchema,agentUIValidationError,applyOperations,applyPipes,applyRelationProps,architectContentBodyKey,architectDraftChannelKey,architectFocusCandidates,architectFocusKey,Ss as artifactQuoteSchema,Bn as asTenantId,Ln as asUserId,assertAcyclicComputed,assertAcyclicComputedDependencies,assertBilateralPairs,assertCustomAgentUIMessageChunk,assertSchemaSourceId,assertSchemaSourceResolutions,sn as attributeConfigSchemas,v as attributeFilterTarget,attributeInventory,bilateralDeclarationOf,booleanFlag,buildAgentFallbackTitle,buildPermissionFlags,buildPropertySchema,c as buildQualifiedAttribute,canCopyRole,canGrantLevel,canGrantPurge,A as canonicalStringify,_c as canonicalViewOperationSchema,Ce as canonicalizeFilterValue,capabilityForResource,capped,Gs as catalogEmbeddingSchema,catalogImageModelSchema,catalogTextModelSchema,checkbox,chosenUserName,cleanContent,collectContentViewCatalogue,je as collectQualifiedRuleIssues,collectSchemaReferences,Le as collectionContentSourceSchema,collectionContentsOf,collectionSourceAddress,collectionSourceAddressOf,qt as colorIdSchema,De as columnsSchema,compareAgentSessionMessages,compareByRecommendation,compareSchemaStateEntries,compilablePlansOf,compileComputedFormula,compileRollupAttribute,computeByteMagnitude,computeReconnectDelay,computeRetryDelay,computedCompileSchemaOf,computedPlanOf,B as content,contentDefinition,co as contentExtensionRegistry,contentNamesAttribute,Pe as contentViewDefinitionSchema,be as contentViewDefinitionSchemaFor,conversationDisplayTitle,convertRetypedValue,jn as createCheckboxValidator,Mn as createDateValidator,createFlagRegistry,createFlagService,Xn as createFormAttributeValidator,An as createNumberValidator,createStandardSchemaProps,Dn as createTextValidator,currency,l as currentActor,ks as customDataChunkSchemas,date,dateInTimezone,kt as dateValueStart,declaredImageRequests,decodeDeploymentBarrierAttestationV1,zn as deepEqual,defaultViewIdsFor,defaultViewsFor,defineDeviceChannelFrames,defineOperation,definePresentation,dependentsOf,deriveArchitectChanges,deriveCreateDefaultsFromFilters,deriveInitials,deriveViewerAccess,describeOperations,detailView,deviceChannelUrl,diffSchemaState,se as displayAttributesSchema,document,ke as draftContentViewDefinitionSchema,Fe as draftContentViewDefinitionSchemaFor,draftListedObjectResolver,draftObjectSettings,draftedLabelExpression,draftedObjectDefinition,draftedViewDefinition,Ts as durableDateSchema,dwellForStep,r as edgePropertyFilterTarget,episodeImpactOf,Sn as evaluateComputedAst,Gt as evaluateComputedFormula,At as evaluateComputedFormulaWithResult,evaluateFilterState,evaluateRecordFilterState,exceptionLevels,extractAttributeNames,g as extractCurrencyFilterValue,o as extractFilterValue,extractTouchedArtifacts,extractTouchedDocuments,extractTouchedRecords,extractValueRefs,familyOf,He as filterOperatorsOfType,ue as filterStateSchema,y as filterTargetsOf,findGrantIssues,findModelByReference,findRelationAttribute,findWorkstationHarness,Ma as flagRegistry,focusOf,form,formFieldFlatKey,formFieldKey,lo as formRegistry,formatAgentStreamFrameId,formatAttributeValue,formatByteSize,xn as formatComputedResult,formatLocationValue,kn as formatZodErrors,formula,fromDraftableView,Fn as generateId,S as getAttributeCapabilities,xe as getAttributeFilterOperators,getEditableLabelAttribute,getErrorMessage,getLiveProtocolPayloadChannel,t as getOperatorPolarity,getRecordCreatorPrincipalId,d as getRollupFilterOperators,getSingleAttributeFromExpression,getSlotFieldTargets,Me as getSystemAttributeI18nKey,Ee as getSystemAttributeList,getUserDisplayName,grantCovers,grantsFromLevels,group,guidanceForBatch,hasOptions,k as iconNameSchema,imageModelFormatDefect,ms as imageModelIdSchema,inboundRelationAttributes,includesAction,Nn as indexBy,re as inferInverseCardinality,inferRollupReturnType,us as inferenceReasoningSchema,ds as inferenceRoutingSchema,ls as inferenceSpeedSchema,isAgentMessageMetadata,isAgentNotificationMetadata,isAgentUIDataName,isAgentUIMessageBatch,isAgentWrittenAuditEntry,ce as isAttributeFilterable,Ae as isAttributeGroupable,bt as isAttributeInUseError,Ie as isAttributeKanbanGroupable,de as isAttributeSearchable,ae as isAttributeSortable,_ as isBilateralRelation,n as isCalendarDay,isCatalogResource,isCheckboxEquality,isClaimableSessionStatus,isComputedAttribute,Ot as isComputedFunctionName,isCurrentTargetToken,Jt as isDateRangeValue,isDefaultRole,isDocumentAttribute,f as isDynamicValue,isEdgePayload,isEmptyObject,isFormDefinition,isFormFieldsRow,isFormFreeFieldRef,isFormHeadingRow,isFormSeparatorRow,isFormSlotFieldRef,isFormTextRow,isLabelExpression,isLiveEventEnvelope,isLiveEventPayload,isLiveEventPayloadForType,isLiveEventType,we as isLocationFilterProperty,a as isLocationPartOperator,isMailProvider,isMailboxListMode,ye as isManagedSystemAttribute,Dt as isNativeObjectName,Ne as isNoValueOperator,isNotEmpty,xt as isNotFoundError,j as isNullishOrEmptyString,St as isObjectReferencedError,isOpenToolPartState,Kt as isPlainRecord,Ct as isProtectedResourceError,isProviderDraft,isPublishedConfigChangeAllowed,wt as isRecordReferencedError,ve as isRelativeDateValue,isReplyMode,isRoleLabelTaken,isRoutableModel,isRoutineActorMetadata,Tt as isSchemaError,Se as isSetMembershipOperator,isStandardSchema,isSystemPartCode,isTerminalSessionStatus,isTerminalState,isToolApprovalState,isUnderRoutingCeiling,e as isUniversalRelation,Et as isValidationError,Hn as isValuePresent,isWorkstationHarnessId,jsonFlag,legacyStatusToSessionState,levelActions,levelOf,listView,listedObjectWithoutCatalogue,liveChannelKey,location,i as locationPartFilterTarget,markdownToPlainText,matchesAccepts,Cs as mentionReferenceSchema,ws as modelDefinitionSchema,fs as modelReferenceSchema,modelReferenceSpellings,multiselect,_n as multiselectOptionWriteSchema,el as namedTargetSchema,nativeAgentUIPartIdMetadataKey,_o as nonOperationalDeploymentBarrierAttestorV1,Ft as normalizeDateValue,le as normalizeFilterRule,p as normalizeForEdgeRpc,Ue as normalizeOperator,normalizePricing,normalizeRoleGrants,normalizeRoleLabel,ee as now,number,numberFlag,object,objectPermissionFlags,operationPace,orderAgentSessionMessages,parseAgentStreamFrameId,tn as parseAttributeConfig,un as parseAttributeConfigForCreate,yn as parseAttributeConfigForUpdate,jt as parseComputedFormula,parseCountMode,parseDeviceChannelFrame,parseFilterInstant,parseLiveChannelKey,parseModelCatalog,parseNamedTarget,parseNativeAgentUIPartIdsMetadata,parseOperation,parseOptionalCountMode,b as parseQualifiedAttribute,parseQualifiedToolName,parseRecordAccessRole,Zt as parseResourceVisibility,parseSchemaGroupPresentation,parseSchemaState,parseServerFrame,parseWorkerFrame,ga as permissionGrantSchema,phone,planAttributeRemoval,presentationOf,pricePerMillion,nn as propertyAttributeSchema,rn as propertyAttributeWireSchema,mn as propertySchemaSchema,dn as propertySchemaWireSchema,proposalTargetKey,cs as providerNameSchema,x as publishedViewContentDefinitionSchema,qualifiedPropertyDefs,qualifiedToolName,readAccessLevels,readArtifactResult,readFormFieldValue,readGeneratedImageResult,readRoleLevels,recentActivityEntryKey,reconcileRelationAttributes,refineTrigger,on as refuseForeignKeys,regenerateDerived,Pa as registry,$n as rejectUnknownAttributesOrThrow,relation,relationAcceptsObject,relationProperty,relationPropertyDefs,relationTargetObjectName,relationTargets,me as relationTargetsOf,relationValueIds,removeObjectException,renameAttributeInContent,renamedFromTarget,renderLabelExpression,requestedCapabilities,requireRecordContentContext,requireSingleRelationTarget,requiredTargetKeys,resolveAttributeDefaultValue,resolveCollectionActions,resolveContentNavigation,Be as resolveEffectiveFilterType,resolveFieldRequired,_e as resolveIsWithinBounds,resolvePropertyDefinitions,En as resolveTextPattern,oe as resolveUtcDayBounds,resolveViewContents,richtext,roleNameFromLabel,rollup,rollupToFormulaExpression,vs as routedMessageInferenceSchema,routingPrice,sameActions,Pn as sameStableValue,schemaGroupKey,schemaStateSourcePayload,select,an as selectOptionWriteSchema,In as serializeCanonicalJson,Vn as serializeStableJson,_s as sessionInferencePatchSchema,sessionStateToLegacyStatus,setCapabilityLevel,setDefaultObjectLevel,setObjectException,setPurge,singleRelationTarget,ze as sortsSchema,status,Qt as statusGroupSchema,bn as statusOptionWriteSchema,stillMissing,storedContentDefinition,stringFlag,summarizeDraft,summarizeGroup,h as systemColumnFilterTarget,systemPermissionFlags,targetSnapshot,targetTokenOf,targetTokensFor,text,toAttribute,toDraftableAttribute,toDraftableAttributes,toDraftableObject,toDraftableView,m as toMultiValueOperator,toUndefinedIfEmpty,Ve as toUtcDayString,Ge as today,Ds as todoItemSchema,Os as todoPlanSchema,ys as toolImpactSchema,touchedObjectIds,uncoveredGrants,updatedAttributeConfig,user,Ut as validateAttributeName,validateContentViewCatalogue,qn as validateDraft,Qn as validateDraftOrThrow,validateLabelExpression,er as validateObject,validateObjectExpressions,zt as validateObjectName,Jn as validateObjectOrThrow,Te as validateQualifiedRule,validateStoredViews,wn as validateViewName,verifyDeploymentBarrierAttestationV1,viewIdFor,viewIdentityKey,viewNamesAttribute,io as viewRegistry,Cn as wireOmittedConfigKeysFor,en as withoutUnknownOptionKeys,workspaceViewAuthoring,workstationModelProvider};
|
|
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(),lo=markSystemView(detailView(oo,`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()),uo=markSystemView(listView(io,`Meetings`).for(U).default().tab(`workspace`,`Shared`,B.collection().object(U).table().icon(`users`).visibility(`workspace`).columns(...so).sort(W.startsAt,`desc`)).tab(`mine`,`My meetings`,B.collection().object(U).table().icon(`lock`).visibility(`private`).columns(...so).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=Ne.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 $e(`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 fo=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 po=new Map(Te().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 mo=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)??po.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`?Pe():ye(),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 ho=[Object.freeze(eo)];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 ho)this.extensions.set(e.name,e)}};const go=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 _o=new FormRegistry;function formatAgentStreamFrameId(e,t){return`${e}:${t}`}function parseAgentStreamFrameId(e){let t=e.lastIndexOf(`:`);if(t<=0)return null;let n=e.slice(0,t),r=Number(e.slice(t+1));return!Number.isInteger(r)||r<=0?null:{streamId:n,sequence:r}}const vo=204800,yo=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 bo=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}),xo=[`membership-unknown`,`sort-unknown`,`permissions-changed`],So=[`permission-revoked`,`workspace-left`,`object-deleted`],Co=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],wo=[`type`,`objectId`,`recordId`,`recordVersion`],To=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],Eo=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],Do=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&bo.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,dr)}function isNotificationPriority(e){return isOneOf(e,fr)}function isNotificationSensitivity(e){return isOneOf(e,pr)}function isNotificationInboxState(e){return isOneOf(e,mr)}function isNotificationWorkState(e){return isOneOf(e,hr)}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,wo)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$2(e)&&hasOnlyKeys(e,Eo)&&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,To)&&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,xo)}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=>Co.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,Do)&&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 Oo=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,Oo)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const ko=[`ok`,`low`,`exhausted`,`paused`],Ao=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,ko)&&isOneOf(e.mode,Ao)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,So)}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 jt(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(!Ot(e))throw new ComputedFormulaCompileError(`Unknown computed function "${e}"`);let r=Ht[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 jo=[{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)`}],Mo=new Date(0).setUTCFullYear(1,0,1),No=/^\d{4}-\d{2}-\d{2}$/,Po=new Set([`createdAt`,`updatedAt`,`deletedAt`]),Fo=/^(\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=Fo.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<Mo?null:m}function unwrapRange(e){return Jt(e)?kt(e):e}function hasTime(e){return e.type===`date`&&e.includeTime===!0}function isSystemTimestamp(e){return Po.has(e.name)}function instantWindow(e){let t=parseFilterInstant(e);return t===null?null:{startMs:t,endMs:t+(typeof e==`string`&&No.test(e)?864e5:1)}}function storedUtcDay(e){let t=unwrapRange(e);if(t instanceof Date)return Number.isNaN(t.getTime())?null:Be(t.getTime());if(typeof t!=`string`||t===``)return null;if(No.test(t))return t;let n=new Date(t);return Number.isNaN(n.getTime())?null:Be(n.getTime())}function comparandDay(e){return e instanceof Date?Number.isNaN(e.getTime())?null:Be(e.getTime()):typeof e==`string`?No.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)}),Io={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=ge(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}),Lo=[...Object.entries(me).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,...Lo])}function evaluateFilterState(e,t,n){if(e.rules.length===0)return!0;let r=new Map(n.map(e=>[e.name,e])),i=e.combinator===`or`?`some`:`every`;return e.rules[i](e=>evaluateRule(e,t,r))}function evaluateRule(e,n,r){let i=r.get(e.attribute);if(!i)return!1;if(e.property&&i.type===`location`){if(!(Ce(e.property)&&a(e.operator)))return!1;let t=Io[e.operator];if(!t)return!1;let r=n[e.attribute],o=typeof r==`object`&&r?r[e.property]:void 0;return evaluateNormalizedComparands(t,`text`,e.operator,o,e.value,i)}if(e.property){let r=resolvePropertyDefinitions(i).find(t=>t.name===e.property);if(!r)return!1;let a=p(e.operator),o=Io[a];if(!o?.appliesTo.includes(r.type))return!1;let s=n[e.attribute],c=(Array.isArray(s)?s:s==null?[]:[s]).some(t=>{if(typeof t!=`object`||!t)return!1;let n=t.props;return typeof n!=`object`||!n?!1:evaluateNormalizedComparands(o,r.type,a,n[e.property],e.value,r)});return(e.quantifier??t(e.operator))===`none`?!c:c}let o=Io[e.operator];if(!o||!o.appliesTo.includes(i.type))return!1;let s=n[e.attribute],c=i.type===`relation`||i.type===`document`||i.type===`user`?normalizeReferenceIds(s):s;return evaluateNormalizedComparands(o,i.type,e.operator,c,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 Wn(t.phoneNumber);let n=typeof t.countryCode==`string`?t.countryCode:r;return`${n}:${Un(t.phoneNumber,n)}`};return[normalizeOne(e),normalizeOne(t)]}function normalizeComparableValue(e,t){return e===`currency`?g(t):e===`date`?Jt(t)?kt(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 Ro=`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]=C(e).storage.cardinality===`many`?[a]:a)}return i}function extractDeterministicValue(e,t){if(e.operator===`is`)return f(e.value)?resolveDynamicValue(e.value,t):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator===`any_of`){if(!Array.isArray(e.value)||e.value.length!==1)return;let n=e.value[0];return f(n)?resolveDynamicValue(n,t):n}}function resolveDynamicValue(e,t){if(t){if(e.dynamic===`actor`)return t.userId;if(e.anchor===`today`)return dateInTimezone(t.now,t.timezone);if(e.anchor===`now`)return t.now.toISOString()}}function requestedCapabilities(e){let t=[];return e.canModify&&t.push(`modify`),e.canSend&&t.push(`send`),t}const zo={status:`connector_status`,error:`connector_error`,provider:`connector_provider`},Bo=100;let Vo=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const Ho=`DRAFT`;function isProviderDraft(e){return e.includes(Ho)}const Uo=[`threads`,`messages`];function isMailboxListMode(e){return Uo.includes(e)}const Wo=[`reply`,`reply_all`];function isReplyMode(e){return Wo.includes(e)}const Go=2e5,Ko=998,qo=[`force`,`skip`],Jo=[`none`,`all`,`external_only`],Yo={override:null,status:`none`,failureReason:null,botId:null},Xo=M.object({speaker:M.string().nullable(),startsAtMs:M.number(),endsAtMs:M.number(),text:M.string()}),Zo=M.object({fullText:M.string(),segments:M.array(Xo),language:M.string().nullable(),startedAt:M.string().nullable(),endedAt:M.string().nullable()}),Qo=M.object({conferenceJoinUrl:M.string().min(1),botDisplayName:M.string().min(1),startsAt:M.string().nullable(),callbackUrl:M.url()}),$o=M.object({botId:M.string().min(1)}),es=M.discriminatedUnion(`kind`,[M.object({kind:M.literal(`transcript-ready`),botId:M.string().min(1)}),M.object({kind:M.literal(`failure`),botId:M.string().min(1),reason:M.string()})]),ts=/^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&&!ts.test(t)?t:e.firstUserText?buildAgentFallbackTitle(e.firstUserText):e.emptyLabel}const ns=/^[a-z0-9][a-z0-9-]{0,62}$/;function assertSchemaSourceId(e){if(!ns.test(e))throw new D(`Invalid schema source id "${e}": expected a lowercase slug matching ${ns}`,[])}const rs={phone:`text`,currency:`number`},is={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(Kt(t)||refuse$1(e,void 0,`Resolution ${e} must be an object`),t.kind===`rename`){assertKeys(e,t,is.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,is[t.to]),t.to===`phone`){let n=t.defaultCountryCode;/^[A-Z]{3}$/.test(n)&&lr(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)&&cr(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=ur(n,Kn(t));if(!r?.isPossible()||r.country===void 0||r.ext!==void 0)return;let i=sr(r.country)?.iso3;if(i!==void 0)return{value:{countryCode:i,phoneNumber:Un(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 as=M.object({mode:M.enum([`inline`,`window`]),interaction:M.enum([`static`,`interactive`]),size:M.enum([`compact`,`regular`]),aspectRatio:M.number().positive().finite().optional()}).strict(),os=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(ji),display:as}).strict();function readArtifactResult(e){let t=os.safeParse(e);return t.success?t.data:null}const ss=M.string().regex(/^[^/\s]+\/[^/\s]+$/),cs=M.object({kind:M.literal(`generated-image`),artifact:M.unknown(),generation:M.object({attemptId:M.uuid(),requestedModelId:ss,executedModelId:ss.nullable(),format:M.enum(Ki),mimeType:M.enum([`image/png`,`image/jpeg`,`image/webp`])}).strict()}).strict();function readGeneratedImageResult(e){let t=cs.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 ls={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,ls)}}return[...t.values()]}const us={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,us)}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,us)}}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 shellQuote(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}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=jt(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 compareByRecommendation(e,t){return(e.recommendationRank??2**53-1)-(t.recommendationRank??2**53-1)||e.label.localeCompare(t.label)}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 ds=/^[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);(!ds.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??ne(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&&!zn(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)&&!zn(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 v=!(_&&s.has(p));_||(_=generateInverse(a,t.name,f.attributes.length),f.attributes.push(_));let y=_;!m&&s.has(d)&&s.has(p)&&checkExplicitDeclarations(a,y,d,p,o.has(d)!==o.has(p));let b=i.get(g),x=b?.id??e.nextPairId(h),ee=r.find(e=>e.id===x&&pairKey(e.addresses)!==g);(!ds.test(x)||ee||u.has(x)&&u.get(x)!==g)&&reject(d,`pair`,`Invalid or duplicate pair identity for ${d} and ${p}`),u.set(x,g);let te=m?d:chooseOwner(a,y,d,p,b,v);a.bilateral&&y.bilateral||reject(d,`bilateral`,`Missing reciprocal configuration for ${d} and ${p}`),a.bilateral={...a.bilateral,cardinality:y.cardinality,label:y.label,storageOwner:te===d},y.bilateral={...y.bilateral,cardinality:a.cardinality,label:a.label,storageOwner:te===p},reconcileProperties(a,y,d,p,s,o),a.metadata={...a.metadata,relationPairId:x},y.metadata={...y.metadata,relationPairId:x},l.set(g,{id:x,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(),fs=M.enum(Mr),ps=M.enum(Nr),ms=M.enum(Pr),hs=M.enum(Lr),gs=M.object({provider:fs,model:M.string().min(1)}).strict(),_s=M.object({speed:ps.optional(),reasoning:ms.optional(),routing:hs.optional()}).strict(),vs=M.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),ys=M.object({model:gs.optional(),speed:ps.optional(),reasoning:ms.optional(),imageModel:vs.optional(),routing:hs.optional()}).strict(),bs=ys.refine(e=>zr.some(t=>e[t]!==void 0),{message:`At least one inference override is required`}),xs=M.object({model:gs.nullable().optional(),speed:ps.nullable().optional(),reasoning:ms.nullable().optional(),imageModel:vs.nullable().optional(),routing:hs.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`}),Ss=M.object({model:M.string().min(1),routing:M.object({mode:M.literal(`auto`),tasks:M.array(M.enum(Fr)).optional(),demand:M.enum(Ir).optional(),reason:M.enum([`selected`,`retained`,`fallback`]).optional(),relation:M.enum([`continue`,`modify`,`new`,`aside`,`unknown`]).optional(),anchorMessageId:M.string().min(1).optional()})}),Cs=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(),ws=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(Kr)}).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:Cs.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()]),Ts=M.object({id:M.string(),name:M.string(),mimeType:M.string(),size:G}).strict(),Es=M.object({id:M.string(),artifactId:M.string(),revision:M.number().int().min(1),selectedText:M.string()}).strict(),Ds=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(),Os=M.object({provider:fs,model:M.string(),maxTokens:G.optional(),contextWindow:G.optional()}).strict(),ks=M.union([M.date(),M.string().datetime({offset:!0}).transform(e=>new Date(e))]),As=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(ws),attachments:M.array(Ts).optional(),mentions:M.array(Ds).optional(),quotes:M.array(Es).optional(),model:Os.optional(),tokenUsage:M.object({input:G,output:G}).strict().optional(),metadata:M.record(M.string(),M.unknown()).optional(),createdAt:ks}).strict(),js=M.object({id:M.string(),description:M.string(),status:M.enum([`pending`,`in_progress`,`completed`,`blocked`]),result:M.string().optional(),updatedAt:G.optional()}).strict(),Ms=M.object({id:M.string(),sessionId:M.string(),status:M.enum([`active`,`completed`,`abandoned`]),todos:M.array(js),version:G,createdAt:M.string(),updatedAt:M.string(),completedAt:M.string().optional()}).strict(),Ns={"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:As}).strict(),"message-persisted-ref":M.object({messageId:M.string().min(1)}).strict(),"message-updated":M.object({message:As}).strict(),"todo-plan-update":M.object({plan:Ms}).strict(),"approval-context":M.object({approvalId:M.string(),toolCallId:M.string(),impact:Cs.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 Ns}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:Ns[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 Ps=M.object({type:M.enum(Br),color:M.enum(nr),expression:M.enum(Vr).default(`relaxed`)}).strict(),Fs=M.array(M.string().trim().min(1).max(200)).max(4);function agentAvatarFromMetadata(e){let t=Ps.safeParse(e);return t.success?t.data:void 0}const Is=[`record.created`,`record.updated`,`record.deleted`,`form.submitted`,`agent.completed`,`webhook`],Ls=new Set([`record.created`,`record.updated`,`record.deleted`]),Rs=/^[A-Z_][A-Z0-9_]*$/,zs=M.object({cron:M.string().min(9),timezone:M.string().optional(),enabled:M.boolean(),input:M.record(M.string(),M.unknown()).optional()}),Bs=M.object({name:M.string().max(120).optional(),eventType:M.enum(Is),objectId:M.guid().optional(),watchedFields:M.array(M.string()).max(50).optional(),debounceMs:M.number().int().min(0).max(3e5).optional(),filter:M.object({combinator:M.enum([`and`,`or`]).default(`and`),rules:M.array(M.object({attribute:M.string(),operator:M.string(),value:M.unknown().optional()}))}).optional(),formDefinitionId:M.string().optional(),sourceAgentId:M.guid().optional(),enabled:M.boolean().optional()});function refineTrigger(e){return e.refine(e=>!e.watchedFields?.length||e.eventType===`record.updated`,{message:`watchedFields requires eventType=record.updated`,path:[`watchedFields`]}).refine(e=>!(e.eventType&&Ls.has(e.eventType))||!!e.objectId,{message:`objectId is required for record.* triggers`,path:[`objectId`]})}const Vs=[`Very economical`,`Balanced`,`Powerful`,`Very powerful`],Hs=[`unsupported`,`effort`,`toggle`,`budget`,`model-controlled`],Us=[`text`,`image`,`audio`,`video`,`pdf`],Ws=/^\d+x\d+$/,Gs=/^\d+:\d+$/,Ks=/^[a-z0-9][a-z0-9-]*$/,qs=.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>qs?`implausible`:n===0&&!t?`undeclared-zero`:null}const Js=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(Js).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 ${qs} 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(Mr,{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(Vs,{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(Pr)).optional(),reasoningMode:M.enum(Hs).optional(),inputModalities:M.array(M.enum(Us)).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(Fr),M.enum(Ir)).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=>Ws.test(String(e)))}),M.looseObject({aspectRatio:M.custom(e=>Gs.test(String(e)))})],{error})}function catalogImageModelSchema(e){let t=`image model "${e}"`,n=`${t} has no usable formats`;return M.looseObject({id:vs,name:nonEmptyString(`${t} has no usable name`),provider:nonEmptyString(`${t} has no usable provider`).regex(Ks,{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 Ys=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 Xs=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`||!Xs.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(Ys,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 Zs=[`pluralLabel`,`description`,`labelExpression`,`embeddingExpression`];function draftObjectSettings(e){return Object.fromEntries(Zs.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 Qs={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={...Qs,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`)},$s=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 ec=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}}),tc=M.object({...J,type:M.literal(`replace_view_content`),definition:ec}).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}}),nc=S.describe(`The whole content definition.`),rc=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:tc,wire:M.object({...J,type:M.literal(`replace_view_content`),definition:nc}).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}}))}),ic=M.object({...q,type:M.literal(`add_view_content`),content:nc,target:$s.describe(`Where to place the new content within its placement zone`)}).strict(),addFocus=e=>({...viewFocus(e),contentName:e.content.name}),ac=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:ic,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}}})}),oc=M.object({...J,type:M.literal(`remove_view_content`)}).strict(),sc=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:oc,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 cc=M.object({...J,type:M.literal(`move_view_content`),placement:M.enum([`main`,`aside`]).describe(`The placement zone to move the content into`),target:$s.describe(`Where to place the content within that placement zone`)}).strict(),lc=defineOperation({type:`move_view_content`,summary:`Reorders or moves a content to a different placement; the aside rule applies.`,schema:cc,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)}}})}),uc=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:k.nullable().optional().describe(`New icon; null clears it`)}).strict().refine(e=>Object.keys(e).length>0).describe(`≥1 change`)}).strict(),dc=defineOperation({type:`update_view_metadata`,summary:`Updates a view's label, description, or icon (null clears the icon).`,schema:uc,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}})}),fc=M.string().refine(e=>e.trim().length>0,`API name must not be blank`),pc=M.object({...q,type:M.literal(`rename_view`),newName:fc.describe(`New API name for the view`)}).strict(),renameViewFocus=e=>({objectName:e.objectName,viewName:e.newName}),mc=defineOperation({type:`rename_view`,summary:`Renames a view; refused on a code-declared name — change it in the declaration.`,schema:pc,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}))}),hc=M.object({...J,type:M.literal(`rename_view_content`),newName:fc.describe(`New API name for the content`)}).strict(),renameContentFocus=e=>({...viewFocus(e),contentName:e.newName}),gc=defineOperation({type:`rename_view_content`,summary:`Renames a content; refused on a code-declared name — change it in the declaration.`,schema:hc,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}}})}),_c=M.object({...J,type:M.literal(`reset_view_content`)}).strict(),vc=defineOperation({type:`reset_view_content`,summary:`Resets a content to its code-declared source, if one exists.`,schema:_c,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}})})}),yc=M.object({...q,type:M.literal(`reset_view_order`),placement:M.enum([`main`,`aside`]).describe(`The placement zone to reset to source order`)}).strict(),bc=defineOperation({type:`reset_view_order`,summary:`Resets a placement zone's order to its code-declared source, if one exists.`,schema:yc,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}})}),xc=M.discriminatedUnion(`type`,[tc,ic,oc,cc,uc,pc,hc,_c,yc]),Y=[rc,ac,sc,lc,dc,mc,gc,vc,bc];function findObject(e,t){return e.objects.find(e=>e.id===t)}const Sc=new Set([`formula`,`rollup`]);function isComputedAttribute(e){return Sc.has(e.attributeType)}const Cc={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 Cc?Cc[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 wc={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,wc,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=>C(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(),v=typeof h==`string`?{id:g,addresses:_,ownerAddress:o?.type===`relation`&&o.bilateral?.storageOwner===!1?p:d,generatedAddresses:[],...d===p?{symmetric:!0}:{}}:void 0,y=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:v?[v]:[],...r&&!i?{explicitAddresses:[d],propertyEditAddresses:[d]}:{},nextPairId:()=>g}),b=new Map;for(let n of y.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}};b.set(`${a}.${o.name}`,toDraftableAttribute(c,a))}}let x=e.attributes.map(e=>{let t=`${e.objectId}.${e.name}`,n=b.get(t);return b.delete(t),n??e});return x.push(...b.values()),{...e,attributes:x,views:e.views.map(e=>{let t=[l,u].find(t=>t.name===e.object);return e.derived&&t?regenerateDerived(e,t,x):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={...Qs,objectId:M.string().uuid().describe(`The object this operation acts on`)},Tc=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:Bt.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} »`}),Ec=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}),Dc=defineOperation({type:`update_object`,summary:`Updates an object's label, icon, pluralLabel, description, labelExpression, embeddingExpression.`,schema:Ec,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)}),Oc={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])=>Oc[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 kc=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=u;function assertConfigParses(e,t){try{un(e,t)}catch(e){throw e instanceof D?new D(e.message,e.errors.map(e=>({...e,path:[`config`,...e.path??[]]}))):e}}const jc=M.object({...X,type:M.literal(`add_attribute`),attributeId:M.string().min(1),name:cn,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}}),Mc=cn.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),Nc={...Qs,type:M.literal(`add_attribute`),attributeId:M.string().min(1).describe(`Stable attribute id`),name:Mc,label:M.string().min(1).describe(`Label people see`)},Pc=Object.fromEntries(gn.map(e=>[e,!0]));function wireWriteConfigOf(e){let t=pn(e).omit(Pc),n=fn[e];return n===void 0?t:t.extend(n)}const Fc=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],Ic=M.object(Fc.reduce((e,t)=>(Object.assign(e,wireWriteConfigOf(t).shape),e),{})).strict(),Lc=Ac.filter(e=>!Fc.includes(e)),Rc=Object.fromEntries(Fc.map(e=>[e,new Set(Object.keys(wireWriteConfigOf(e).shape))])),zc=on(Rc,`config key`);function refuseForeignSimpleConfigKeys(e,t){zc(e.attributeType,e.config,t,[`config`])}function wireConfigFor(e){let t=wireWriteConfigOf(e);return(e===`relation`||e===`document`?t.extend({properties:dn.optional()}):t).strict()}const Bc=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:jc,wire:M.discriminatedUnion(`attributeType`,[M.object({...Nc,objectId:M.string().uuid(),attributeType:M.enum(Fc).describe(`Attribute type`),config:Ic.optional().describe(`Configuration of a simple attribute (text, number, date…)`)}).strict().superRefine(refuseForeignSimpleConfigKeys),...Lc.map(e=>M.object({...Nc,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} »`}),Vc={...X,attribute:cn.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 Hc=M.object({...Vc,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`),icon:k.nullable().optional().describe(`Relation only: icon from search_icons; null clears it`)}).refine(e=>Object.keys(e).length>0,`update_attribute needs at least one change`).describe(`≥1 change`)});function updatedAttributeConfig(e,t){let n=t.config??e;if(t.icon===void 0)return n;let{icon:r,...i}=n??{};return t.icon===null?i:{...i,icon:t.icon}}const Uc=defineOperation({type:`update_attribute`,summary:"Updates label, a relation's icon, or the whole config (replaced). A published config is frozen, except `bilateral` alone (all else identical) to pair a published relation with its inverse; else add a new attribute and migrate values.",schema:Hc,apply:(e,t)=>{let{object:n,attribute:r}=requireAttribute(e,t.objectId,t.attribute,`update_attribute`),{icon:i,config:a,...o}=t.changes;if(i!==void 0&&r.attributeType!==`relation`){let e=`icon is only for relation attributes; "${r.name}" is a ${r.attributeType} attribute`;throw new D(e,[{path:[`changes`,`icon`],message:e}])}a!==void 0&&assertConfigParses(r.attributeType,a);let s=updatedAttributeConfig(r.config,{config:a,icon:i}),c={...r,...o,...s===void 0?{}:{config:s}},l=withDerivedViews(e,n,e.attributes.map(e=>e===r?c:e));return assertConfigFolds(l,c),reconcileDraftRelationAttribute(l,c,t.id,r)},focus:existingAttributeFocus,presentation:definePresentation(existingAttributeFocus,`atomic`),describe:e=>e.changes.label?`Renomme l'attribut « ${e.attribute} » en « ${e.changes.label} »`:e.changes.config===void 0&&e.changes.icon===null?`Retire l'icône de l'attribut « ${e.attribute} »`:e.changes.config===void 0&&e.changes.icon!==void 0?`Change l'icône de l'attribut « ${e.attribute} » en « ${e.changes.icon} »`:`Modifie l'attribut « ${e.attribute} »`}),Wc=M.object({...Vc,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 Gc=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:Wc,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} »`}),Kc=M.object({...Vc,type:M.literal(`rename_draft_attribute`),name:Mc});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 qc=defineOperation({type:`rename_draft_attribute`,summary:`Renames a draft-added attribute; views and samples follow.`,schema:Kc,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{Yn(i)}catch{return}let a=Zn(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 Jc=M.guid();function carriesNonRecordId(e){let t=Array.isArray(e)?e:[e],n=relationValueIds(e);return n.length<t.length||n.some(e=>!Jc.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 Yc=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=[Tc,Dc,kc,Bc,Uc,Gc,qc,Yc,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 Xc=build(),Zc=[...Xc.keys()];function defOf(e){let t=Xc.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=Xc.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 Qc=`bilateral`;function frozenPart(e){if(!e||typeof e!=`object`)return A({});let{[Qc]: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()]),$c=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=xc.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 el=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=$c.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 tl={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`},nl=`normal`;function operationPace(e){return Object.hasOwn(tl,e)?tl[e]:nl}const rl={major:{replay:4e3,live:2500},normal:{replay:2600,live:1800},minor:{replay:1400,live:1100}};function dwellForStep(e,t,n){let r=(rl[e]??rl[nl])[t],i=900+40*(n||0);return Math.min(6e3,Math.max(r,i))}const Q=M.string().min(1),il=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=il.safeParse(e);if(!t.success)throw new D(`Invalid scoped target`,[{path:[`target`],message:`Expected exactly one named target branch`}]);return t.data}const al=M.object({type:M.literal(`remove_operation`),operationId:M.string().min(1).describe(`The id of a stored operation to drop from the draft`)}),ol=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 sl={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of sl[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 cl=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:cl}).strict())})}const ll=membersOf(Z,[al]),ul=membersOf(Y),dl=unionOf(ll),fl=unionOf(ul),pl={schema:dl,view:fl},ml={schema:unionOf(wireMembersOf(Z,[al])),view:unionOf(wireMembersOf(Y))},hl=new Map([...Z.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...Y.map(e=>[e.type,`view`])]);function familyOf(e){return hl.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 C(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 gl=[`draft_schema`],_l=`discard_architect_draft`,vl=`request_design_review`,yl=`get_architect_draft`,bl=[{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`),xl=M.union([M.tuple([M.literal(`object`),$]),M.tuple([M.literal(`attribute`),$,$]),M.tuple([M.literal(`view`),$,$]),M.tuple([M.literal(`content`),$,$,$])]),Sl=M.object({label:$,pluralLabel:M.string().optional(),description:M.string().optional(),icon:k.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`:Sl.parse(n);break;case`attribute`:{let e=M.enum(u).parse(n.type);$t(e).extend({type:M.literal(e),label:$,required:M.boolean().optional(),unique:M.boolean().optional(),icon:k.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`),Oe.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]}`),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=xl.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:xl,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{el as ABSENT_TARGET_TOKEN,Vr as AGENT_AVATAR_EXPRESSIONS,Br as AGENT_AVATAR_TYPES,Zr as AGENT_MESSAGE_KIND,Xr as AGENT_NOTIFICATION_KIND,Hr as AGENT_STARTERS_MAX,Ur as AGENT_STARTER_MAX_LENGTH,Fr as AGENT_TASK_KINDS,vo as AGENT_UI_BATCH_MAX_BYTES,yo as AGENT_UI_BATCH_MAX_ITEMS,Qi as ALLOWED_PROPERTY_TYPES,Zc as ALL_OPERATION_TYPES,aa as ALL_PIPES,Mi as ARTIFACT_FILE_ROLES,Ai as ARTIFACT_KINDS,ro as ARTIFACT_LIST_VIEW,to as ARTIFACT_OBJECT,H as ARTIFACT_OBJECT_NAME,eo as ARTIFACT_PREVIEW_EXTENSION,ji as ARTIFACT_RETENTIONS,no as ARTIFACT_VIEW,Le as ATTRIBUTE_FILTER_OPERATORS,u as ATTRIBUTE_TYPES,Er as AUDIT_ACTIONS,Dr as AUDIT_AGENT_SESSION_METADATA_KEY,Tr as AUDIT_RESOURCE_TYPES,Ge as AccessDeniedError,AgentBuilder,Ke as AmbiguousSchemaChangeError,qe as AttributeInUseError,Je as AttributeNotFoundError,Cr as BEHAVIOR_PROPERTIES,_i as BROWSER_IMAGE_MAX_BYTES,Xi as BYTE_UNIT_LABELS,ba as CATALOG_RESOURCES,kr as CLAIMABLE_SESSION_STATUSES,Ht as COMPUTED_FUNCTIONS,jo as COMPUTED_FUNCTION_METADATA,ln as COMPUTED_FUNCTION_NAMES,zo as CONNECTOR_CALLBACK_PARAM,qi as COUNT_MODES,ya as CUSTOM_LEVEL,ComputedFormulaCompileError,Mt as ComputedFormulaParseError,Ye as ConcurrentModificationError,z as ContentBuilder,Ta as DB_COLUMN_FIELDS,Pa as DEFAULT_AGENT_EXECUTION_CONFIG,Ar as DEFAULT_APPROVAL_POLICY,Jr as DEFAULT_DAILY_ACTIVITY_DAYS,mi as DEFAULT_DICTATION_LIMITS,da as DEFAULT_LABEL_FALLBACK,Ri as DEFAULT_MEETING_BOT_DISPLAY_NAME,Ea as DEFAULT_ROLES,Oa as DEFAULT_ROLE_DESCRIPTIONS,Da as DEFAULT_ROLE_LABELS,Aa as DEFAULT_ROLE_PERMISSIONS,ja as DEFAULT_ROLE_REVOCATIONS,zi as DEFAULT_TENANT_SETTINGS,On as DEFAULT_VALIDATION_MESSAGES,vi as DEVICE_CHANNEL_AUTHENTICATE_TIMEOUT_MS,yi as DEVICE_CHANNEL_IDLE_POLL_MS,xi as DEVICE_CHANNEL_KEEPALIVE_MS,gi as DEVICE_CHANNEL_MAX_FRAME_BYTES,hi as DEVICE_CHANNEL_PATH,bi as DEVICE_CHANNEL_PRESENCE_MS,Ti as DEVICE_CHANNEL_UPGRADE_REQUIRED_REASON,Si as DEVICE_CHANNEL_WORKER_CLOSE_PROTOCOL_VIOLATION,wi as DEVICE_COMMAND_ERROR_CODES,fi as DICTATION_FINALIZATION_TIMEOUT_MS,oi as DICTATION_FRAME_BYTES,ci as DICTATION_MAX_BUFFER_BYTES,si as DICTATION_MAX_FRAME_BYTES,li as DICTATION_MAX_TRANSCRIPT_BYTES,pi as DICTATION_MODEL_ID,di as DICTATION_PREPARATION_TIMEOUT_MS,ai as DICTATION_SAMPLE_RATE,ui as DICTATION_TICKET_TTL_MS,_l as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,Zi as DOCUMENT_SYSTEM_ATTRIBUTES,Ac as DRAFTABLE_ATTRIBUTE_TYPES,ol as DRAFT_BATCH_LIMIT,Zs as DRAFT_OBJECT_SETTINGS,bl as DRAFT_SCHEMA_INPUT_EXAMPLES,gl as DRAFT_WRITE_TOOL_NAMES,$a as DRIVE_LIST_VIEW,Za as DRIVE_OBJECT,V as DRIVE_OBJECT_NAME,Qa as DRIVE_VIEW,DeviceChannelProtocolError,ki as DeviceChannelServerFrameSchema,Oi as DeviceChannelWorkerFrameSchema,DraftRefusalError,w as DuplicateError,na as EMPTY_VALUE_PLACEHOLDER,Rs as ENV_VAR_KEY_PATTERN,Ji as ESTIMATED_COUNT_CAP,pl as FAMILY_INPUTS,ml as FAMILY_WIRE_INPUTS,Fi as FORM_FORBIDDEN_ATTRIBUTE_TYPES,FlagRegistry,FlagService,Xe as ForbiddenError,FormBuilder,FormRegistry,FormRowBuilder,FormStepBuilder,yl as GET_ARCHITECT_DRAFT_TOOL_NAME,Ra as GroupBuilder,Sr as IDENTITY_PROPERTIES,Ki as IMAGE_FORMATS,Pr as INFERENCE_REASONING_OPTIONS,Lr as INFERENCE_ROUTING_MODES,Nr as INFERENCE_SPEEDS,mo as INVENTORY_LIMIT,Ze as InvalidPermissionGrantError,qr as LAST_RUN_ERROR_MAX_LENGTH,Rt as LIST_VIEW_TAB_VISIBILITIES,bo as LIVE_EVENT_TYPES,De as LOCATION_FILTER_PROPERTIES,Uo as MAILBOX_LIST_MODES,Go as MAIL_DRAFT_BODY_MAX_CHARS,Ko as MAIL_SUBJECT_MAX_CHARS,Yr as MAX_DAILY_ACTIVITY_DAYS,Ni as MAX_PRESET_DEPTH,$r as MAX_TODOS,ti as MAX_TODO_DESCRIPTION_CHARS,ei as MAX_TODO_ID_CHARS,Bo as MCP_SERVER_NAME_MAX_LENGTH,W as MEETING_ATTRIBUTES,oo as MEETING_DETAIL_VIEW_ID,uo as MEETING_LIST_VIEW,io as MEETING_LIST_VIEW_ID,co as MEETING_OBJECT,U as MEETING_OBJECT_NAME,lo as MEETING_VIEW,ao as MEETING_WRITE_SOURCE,Xa as MEMORY_LIST_VIEW,qa as MEMORY_OBJECT,Ya as MEMORY_VIEW,wa as MIXED_LEVEL,Vo as McpOAuthCompletionMode,Qe as MemoryNotFoundError,MultiRelationAttributeBuilder,ri as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,ii as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,Wt as NATIVE_OBJECT_NAMES,mr as NOTIFICATION_INBOX_STATES,dr as NOTIFICATION_KINDS,fr as NOTIFICATION_PRIORITIES,pr as NOTIFICATION_SENSITIVITIES,xr as NOTIFICATION_TYPES_V1,vr as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,yr as NOTIFICATION_TYPE_AGENT_ROUTINE_RUN_FAILED,br as NOTIFICATION_TYPE_AGENT_ROUTINE_RUN_TIMED_OUT,gr as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,_r as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,hr as NOTIFICATION_WORK_STATES,va as NO_ACCESS,Yo as NO_RECORDING,te as NO_VALUE_OPERATORS,Rn as NonJsonValueError,NoopGeocodingAdapter,$e as NotFoundError,et as NotImplementedError,I as OBJECT_GRANT,Bt as OBJECT_NAME_SCHEMA,Gr as OPEN_TOOL_PART_STATES,tl as OPERATION_PACE,Xc as OPERATION_REGISTRY,s as OPERATORS_BY_TYPE,Io as OPERATOR_SPECS,ObjectBuilder,tt as ObjectNotFoundError,nt as ObjectReferencedError,rt as OrphanSystemAttributeError,rl as PACE_DWELL_MS,Sa as PERMISSION_ACTIONS,L as PERMISSION_CAPABILITIES,_a as PERMISSION_CATALOG,ia as PIPES_WITH_ARGS,ma as PREFERRED_NAME_MAX_LENGTH,wr as PRESENTATION_PROPERTIES,Ho as PROVIDER_DRAFT_LABEL,Mr as PROVIDER_NAMES,Qc as PUBLISHED_CONFIG_EXCEPTION,it as ProtectedResourceError,at as ProtectedRoleError,ee as QUALIFIED_SEPARATOR,Yi as QUOTA_KEYS,Pi as RECENT_ACTIVITY_LEDGER_LIMIT,qo as RECORDING_OVERRIDES,Jo as RECORDING_POLICIES,Ii as RECORD_ACCESS_ROLES,Li as RECORD_ACCESS_SOURCES,ga as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,re as RELATION_TARGET_ANY,de as REMOVED_OPERATOR_REPLACEMENTS,al as REMOVE_OPERATION_SCHEMA,Wo as REPLY_MODES,vl as REQUEST_DESIGN_REVIEW_TOOL_NAME,hn as RESERVED_ATTRIBUTE_NAMES,Lt as RESERVED_OBJECT_NAMES,Xt as RESOURCE_VISIBILITIES,Rr as ROUTING_PRICE_CEILINGS,ot as RealtimeDeliveryError,st as RealtimeRateLimitedError,ct as RealtimeSubscriptionError,lt as RecordNotFoundError,ut as RecordReferencedError,dt as RepositoryError,ft as ReservedObjectNameError,pt as RoleNotFoundError,Pt as SCHEMA_LIMITS,Z as SCHEMA_OPERATIONS,dl as SCHEMA_OPERATION_INPUT,ns as SCHEMA_SOURCE_ID_PATTERN,rs as SCHEMA_SOURCE_RETYPE_FROM,zr as SESSION_INFERENCE_PATCH_KEYS,ni as SESSION_STATE_STREAM_ID,Or as SESSION_TERMINAL_STATUSES,ra as SIMPLE_PIPES,vn as SIMPLE_PROPERTY_TYPES,Ua as SKILL_CONTENT_TEMPLATE,Ka as SKILL_LIST_VIEW,Wa as SKILL_OBJECT,Ga as SKILL_VIEW,Fa as STANDARD_SCHEMA_VENDOR,Ue as SYNONYM_ALIASES,fe as SYSTEM_ATTRIBUTES,he as SYSTEM_ATTRIBUTE_I18N_KEYS,Yt as SYSTEM_FIELD_NAMES,me as SYSTEM_FILTER_ATTRIBUTE_TYPES,Kr as SYSTEM_PART_CODES,T as SchemaError,E as SchemaErrorCode,mt as SearchBackendError,SingleRelationAttributeBuilder,ht as StorageError,gt as SyncCascadeError,_t as SyncConflictError,vt as SyncError,yt as SystemEntityImmutableError,Ir as TASK_DEMAND_LEVELS,Bi as TENANT_INVITATION_DEFAULT_TTL_MS,Hi as TENANT_INVITATION_MAX_TTL_MS,Vi as TENANT_INVITATION_MIN_TTL_MS,Ui as TENANT_INVITATION_RESEND_INTERVAL_MS,Tn as TEXT_FORMAT_PATTERNS,Ro as TODAY_DEFAULT,jr as TODO_PLAN_STATUSES,Qr as TODO_STATUSES,Wr as TOOL_APPROVAL_STATES,$i as TOOL_NAME_SEPARATOR,Is as TRIGGER_EVENT_TYPES,Wi as USER_STATUSES,Gi as USER_WORK_POSTURES,Y as VIEW_OPERATIONS,fl as VIEW_OPERATION_INPUT,D as ValidationError,La as ViewBuilder,gn as WIRE_OMITTED_CONFIG_KEYS,Ma as WORKSTATION_HARNESSES,agent,agentAvatarFromMetadata,Ps as agentAvatarSchema,agentDataChunk,agentDisplayName,_s as agentInferencePreferencesSchema,Ts as agentMessageAttachmentSchema,ws as agentMessagePartSchema,zs as agentScheduleSchema,ys as agentSessionInferenceOverridesInputSchema,bs as agentSessionInferenceOverridesSchema,As as agentSessionMessageSchema,Fs as agentStartersSchema,Bs as agentTriggerBaseSchema,agentUIValidationError,applyOperations,applyPipes,applyRelationProps,architectContentBodyKey,architectDraftChannelKey,architectFocusCandidates,architectFocusKey,Es as artifactQuoteSchema,Bn as asTenantId,Ln as asUserId,assertAcyclicComputed,assertAcyclicComputedDependencies,assertBilateralPairs,assertCustomAgentUIMessageChunk,assertSchemaSourceId,assertSchemaSourceResolutions,sn as attributeConfigSchemas,y as attributeFilterTarget,attributeInventory,bilateralDeclarationOf,booleanFlag,buildAgentFallbackTitle,buildPermissionFlags,buildPropertySchema,c as buildQualifiedAttribute,canCopyRole,canGrantLevel,canGrantPurge,A as canonicalStringify,xc as canonicalViewOperationSchema,Se as canonicalizeFilterValue,capabilityForResource,capped,Ys as catalogEmbeddingSchema,catalogImageModelSchema,catalogTextModelSchema,checkbox,chosenUserName,cleanContent,collectContentViewCatalogue,Ae as collectQualifiedRuleIssues,collectSchemaReferences,Ie as collectionContentSourceSchema,collectionContentsOf,collectionSourceAddress,collectionSourceAddressOf,qt as colorIdSchema,Ee as columnsSchema,compareAgentSessionMessages,compareByRecommendation,compareSchemaStateEntries,compilablePlansOf,compileComputedFormula,compileRollupAttribute,computeByteMagnitude,computeReconnectDelay,computeRetryDelay,computedCompileSchemaOf,computedPlanOf,B as content,contentDefinition,go as contentExtensionRegistry,contentNamesAttribute,Ne as contentViewDefinitionSchema,ye as contentViewDefinitionSchemaFor,conversationDisplayTitle,convertRetypedValue,jn as createCheckboxValidator,Mn as createDateValidator,createFlagRegistry,createFlagService,Xn as createFormAttributeValidator,An as createNumberValidator,createStandardSchemaProps,Dn as createTextValidator,currency,l as currentActor,Ns as customDataChunkSchemas,date,dateInTimezone,kt as dateValueStart,declaredImageRequests,zn as deepEqual,defaultViewIdsFor,defaultViewsFor,defineDeviceChannelFrames,defineOperation,definePresentation,dependentsOf,deriveArchitectChanges,deriveCreateDefaultsFromFilters,deriveInitials,deriveViewerAccess,describeOperations,detailView,deviceChannelUrl,diffSchemaState,oe as displayAttributesSchema,document,Oe as draftContentViewDefinitionSchema,Pe as draftContentViewDefinitionSchemaFor,draftListedObjectResolver,draftObjectSettings,draftedLabelExpression,draftedObjectDefinition,draftedViewDefinition,ks as durableDateSchema,dwellForStep,r as edgePropertyFilterTarget,episodeImpactOf,Sn as evaluateComputedAst,Gt as evaluateComputedFormula,At as evaluateComputedFormulaWithResult,evaluateFilterState,evaluateRecordFilterState,exceptionLevels,extractAttributeNames,g as extractCurrencyFilterValue,o as extractFilterValue,extractTouchedArtifacts,extractTouchedDocuments,extractTouchedRecords,extractValueRefs,familyOf,Ve as filterOperatorsOfType,le as filterStateSchema,b as filterTargetsOf,findGrantIssues,findModelByReference,findRelationAttribute,findWorkstationHarness,za as flagRegistry,focusOf,form,formFieldFlatKey,formFieldKey,_o as formRegistry,formatAgentStreamFrameId,formatAttributeValue,formatByteSize,xn as formatComputedResult,formatLocationValue,kn as formatZodErrors,formula,fromDraftableView,Fn as generateId,C as getAttributeCapabilities,be as getAttributeFilterOperators,getEditableLabelAttribute,getErrorMessage,getLiveProtocolPayloadChannel,t as getOperatorPolarity,getRecordCreatorPrincipalId,d as getRollupFilterOperators,getSingleAttributeFromExpression,getSlotFieldTargets,je as getSystemAttributeI18nKey,Te as getSystemAttributeList,getUserDisplayName,grantCovers,grantsFromLevels,group,guidanceForBatch,hasOptions,k as iconNameSchema,imageModelFormatDefect,vs as imageModelIdSchema,inboundRelationAttributes,includesAction,Nn as indexBy,ne as inferInverseCardinality,inferRollupReturnType,ms as inferenceReasoningSchema,hs as inferenceRoutingSchema,ps as inferenceSpeedSchema,isAgentMessageMetadata,isAgentNotificationMetadata,isAgentUIDataName,isAgentUIMessageBatch,isAgentWrittenAuditEntry,se as isAttributeFilterable,ke as isAttributeGroupable,bt as isAttributeInUseError,Fe as isAttributeKanbanGroupable,ue as isAttributeSearchable,ie as isAttributeSortable,_ as isBilateralRelation,n as isCalendarDay,isCatalogResource,isCheckboxEquality,isClaimableSessionStatus,isComputedAttribute,Ot as isComputedFunctionName,isCurrentTargetToken,Jt as isDateRangeValue,isDefaultRole,isDocumentAttribute,f as isDynamicValue,isEdgePayload,isEmptyObject,isFormDefinition,isFormFieldsRow,isFormFreeFieldRef,isFormHeadingRow,isFormSeparatorRow,isFormSlotFieldRef,isFormTextRow,isLabelExpression,isLiveEventEnvelope,isLiveEventPayload,isLiveEventPayloadForType,isLiveEventType,Ce as isLocationFilterProperty,a as isLocationPartOperator,isMailProvider,isMailboxListMode,ve as isManagedSystemAttribute,Dt as isNativeObjectName,Me as isNoValueOperator,isNotEmpty,xt as isNotFoundError,j as isNullishOrEmptyString,St as isObjectReferencedError,isOpenToolPartState,Kt as isPlainRecord,Ct as isProtectedResourceError,isProviderDraft,isPublishedConfigChangeAllowed,wt as isRecordReferencedError,_e as isRelativeDateValue,isReplyMode,isRoleLabelTaken,isRoutableModel,isRoutineActorMetadata,Tt as isSchemaError,xe as isSetMembershipOperator,isStandardSchema,isSystemPartCode,isTerminalSessionStatus,isTerminalState,isToolApprovalState,isUnderRoutingCeiling,e as isUniversalRelation,Et as isValidationError,Hn as isValuePresent,isWherePipe,isWorkstationHarnessId,jsonFlag,legacyStatusToSessionState,levelActions,levelOf,listView,listedObjectWithoutCatalogue,liveChannelKey,location,i as locationPartFilterTarget,markdownToPlainText,matchesAccepts,Qo as meetingBotDispatchRequestSchema,$o as meetingBotDispatchResponseSchema,es as meetingBotNotificationSchema,Xo as meetingTranscriptSegmentSchema,Ds as mentionReferenceSchema,Os as modelDefinitionSchema,gs as modelReferenceSchema,modelReferenceSpellings,multiselect,_n as multiselectOptionWriteSchema,il as namedTargetSchema,nativeAgentUIPartIdMetadataKey,Ft as normalizeDateValue,ce as normalizeFilterRule,p as normalizeForEdgeRpc,He as normalizeOperator,normalizePricing,normalizeRoleGrants,normalizeRoleLabel,Zo as normalizedMeetingTranscriptSchema,v as now,number,numberFlag,object,objectPermissionFlags,operationPace,orderAgentSessionMessages,parseAgentStreamFrameId,tn as parseAttributeConfig,un as parseAttributeConfigForCreate,yn as parseAttributeConfigForUpdate,jt as parseComputedFormula,parseCountMode,parseDeviceChannelFrame,parseFilterInstant,parseLiveChannelKey,parseModelCatalog,parseNamedTarget,parseNativeAgentUIPartIdsMetadata,parseOperation,parseOptionalCountMode,x as parseQualifiedAttribute,parseQualifiedToolName,parseRecordAccessRole,Zt as parseResourceVisibility,parseSchemaGroupPresentation,parseSchemaState,parseServerFrame,parseWherePipe,parseWorkerFrame,Ca as permissionGrantSchema,phone,planAttributeRemoval,presentationOf,pricePerMillion,nn as propertyAttributeSchema,rn as propertyAttributeWireSchema,mn as propertySchemaSchema,dn as propertySchemaWireSchema,proposalTargetKey,fs as providerNameSchema,S as publishedViewContentDefinitionSchema,qualifiedPropertyDefs,qualifiedToolName,readAccessLevels,readArtifactResult,readFormFieldValue,readGeneratedImageResult,readRoleLevels,recentActivityEntryKey,reconcileRelationAttributes,refineTrigger,on as refuseForeignKeys,regenerateDerived,Va as registry,$n as rejectUnknownAttributesOrThrow,relation,relationAcceptsObject,relationProperty,relationPropertyDefs,relationTargetObjectName,relationTargets,pe as relationTargetsOf,relationValueIds,removeObjectException,renameAttributeInContent,renamedFromTarget,renderLabelExpression,requestedCapabilities,requireRecordContentContext,requireSingleRelationTarget,requiredTargetKeys,resolveAttributeDefaultValue,resolveCollectionActions,resolveContentNavigation,ze as resolveEffectiveFilterType,resolveFieldRequired,ge as resolveIsWithinBounds,resolvePropertyDefinitions,En as resolveTextPattern,ae as resolveUtcDayBounds,resolveViewContents,richtext,roleNameFromLabel,rollup,rollupToFormulaExpression,Ss as routedMessageInferenceSchema,routingPrice,sameActions,Pn as sameStableValue,schemaGroupKey,schemaStateSourcePayload,select,an as selectOptionWriteSchema,In as serializeCanonicalJson,Vn as serializeStableJson,xs as sessionInferencePatchSchema,sessionStateToLegacyStatus,setCapabilityLevel,setDefaultObjectLevel,setObjectException,setPurge,shellQuote,singleRelationTarget,Re as sortsSchema,status,Qt as statusGroupSchema,bn as statusOptionWriteSchema,stillMissing,storedContentDefinition,stringFlag,summarizeDraft,summarizeGroup,h as systemColumnFilterTarget,systemPermissionFlags,targetSnapshot,targetTokenOf,targetTokensFor,text,toAttribute,toDraftableAttribute,toDraftableAttributes,toDraftableObject,toDraftableView,m as toMultiValueOperator,toUndefinedIfEmpty,Be as toUtcDayString,We as today,js as todoItemSchema,Ms as todoPlanSchema,Cs as toolImpactSchema,touchedObjectIds,uncoveredGrants,updatedAttributeConfig,user,Ut as validateAttributeName,validateContentViewCatalogue,qn as validateDraft,Qn as validateDraftOrThrow,validateLabelExpression,er as validateObject,validateObjectExpressions,zt as validateObjectName,Jn as validateObjectOrThrow,we as validateQualifiedRule,validateStoredViews,wn as validateViewName,viewIdFor,viewIdentityKey,viewNamesAttribute,fo as viewRegistry,Cn as wireOmittedConfigKeysFor,en as withoutUnknownOptionKeys,workspaceViewAuthoring,workstationModelProvider};
|