@stndrds/schema 1.0.0-alpha.353 → 1.0.0-alpha.354
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-0XBkyLI_.d.mts → all-SkbqeVsR.d.mts} +1 -1
- package/dist/{all-PHJaq-9U.d.ts → all-WEAw-zHa.d.ts} +1 -1
- package/dist/{index-DcLDUWZd.d.ts → index-B8VLnf0C.d.ts} +1 -1
- package/dist/{index-C9eOBRL6.d.mts → index-BT21OFT0.d.mts} +1 -1
- package/dist/index.d.mts +3188 -3105
- package/dist/index.d.ts +3188 -3105
- package/dist/index.js +2 -2
- package/dist/index.mjs +3 -3
- package/dist/validation/all.d.mts +2 -2
- package/dist/validation/all.d.ts +2 -2
- package/dist/validation/all.js +1 -1
- package/dist/validation/all.mjs +1 -1
- package/dist/validation/object/index.d.mts +1 -1
- package/dist/validation/object/index.d.ts +1 -1
- package/dist/view-config.schema-CLY7xK9f.js +2 -0
- package/dist/{view-config.schema-CvT5GfbA.mjs → view-config.schema-DbDc6VTO.mjs} +1 -1
- package/package.json +2 -2
- package/dist/view-config.schema-Cn3vLXu0.js +0 -2
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./config-CQj1KDVm.js"),t=require("./view-config.schema-Cn3vLXu0.js"),n=require("./exceptions.js"),r=require("./text-A9AJ1wUO.js"),i=require("./core-397tQy5q.js"),a=require("./validation/primitives/number.js"),o=require("./validation/primitives/checkbox.js"),s=require("./validation/primitives/date.js"),c=require("./utils-gY3d9Dwp.js"),l=require("./empty-CRCKZcwK.js"),u=require("./phone-BXTenBvF.js"),d=require("./object-xwmmQZ8z.js");let f=require("zod"),p=require("@stndrds/constants"),m=require("libphonenumber-js");const h=[`fyi`,`task`,`question`,`handoff`,`system`],g=[`low`,`normal`,`high`,`urgent`],_=[`public`,`internal`,`sensitive`],v=[`unread`,`read`,`archived`,`snoozed`],y=[`none`,`pending`,`processing`,`completed`,`dismissed`,`expired`,`failed`],b=`agent.session.waiting_human`,x=`agent.task.assigned`,S=`agent.question.requested`,ee=[b,x,S],C=[`name`,`type`],te=[`required`,`hidden`,`archived`,`deprecated`,`defaultValue`,`config`,`order`,`unique`],ne=[`label`,`description`,`placeholder`,`icon`],re=[`record`,`object`,`attribute`,`view`,`user`,`role`,`settings`,`file`,`agent`,`schema_source`,`tenant_invitation`,`api_key`],ie=`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(`,`);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 n.SchemaError(`parked state without parkedOn`,n.SchemaErrorCode.INVARIANT_VIOLATION);return e.parkedOn===`agents`?`waiting_agents`:`waiting_human`;case`terminal`:if(e.outcome===void 0)throw new n.SchemaError(`terminal state without outcome`,n.SchemaErrorCode.INVARIANT_VIOLATION);return e.outcome}}function legacyStatusToSessionState(e){switch(e){case`active`:return{phase:`running`};case`idle`:return{phase:`queued`};case`waiting_human`:return{phase:`parked`,parkedOn:`human`,humanRequestIds:[]};case`waiting_agents`:return{phase:`parked`,parkedOn:`agents`};default:return{phase:`terminal`,outcome:e}}}const ae=[`completed`,`failed`,`cancelled`,`timeout`,`expired`];function isTerminalSessionStatus(e){return ae.includes(e)}const oe=[`idle`,`completed`,`waiting_human`,`waiting_agents`,`cancelled`,`failed`,`timeout`];function isClaimableSessionStatus(e){return oe.includes(e)}const se=Object.freeze({mutation:`ask`,destructive:`ask`,outward:`ask`}),ce=[`active`,`completed`,`abandoned`],le=[`openai`,`anthropic`,`google`,`spacexai`,`deepseek`,`moonshotai`,`alibaba`,`mistral`,`minimax`,`meta`,`zai`],ue=[`standard`,`fast`],de=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],fe=[`conversation`,`writing`,`coding`,`analysis`,`extraction`],pe=[`light`,`standard`,`heavy`],me=[`manual`,`auto`],he={interactive:{inputPerMillionUsd:5,outputPerMillionUsd:25},delegated:{inputPerMillionUsd:2,outputPerMillionUsd:12}},ge=[`model`,`speed`,`reasoning`,`imageModel`,`routing`];function isRoutineActorMetadata(e){return e?.kind===`routine`}const _e=[`octopus`,`clover`,`flower`,`triangle`,`square`,`blob`,`circle`,`drop`,`hexagon`,`pill`,`pebble`,`puddle`],ve=[`relaxed`,`neutral`];function agentDisplayName(e){return e.label?.trim()||e.name}const ye=[`approval-requested`,`approval-responded`,`approval-dispatched`],be=[`streaming`,`running`,`pending`,...ye];function isOpenToolPartState(e){return be.includes(e)}function isToolApprovalState(e){return ye.includes(e)}const xe=[`CREDITS_EXHAUSTED`];function isSystemPartCode(e){return typeof e==`string`&&xe.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 Se=`agent-notification`;function isAgentNotificationMetadata(e){return e?.kind===Se}const Ce=`agent-message`;function isAgentMessageMetadata(e){return e?.kind===Ce}const we=[`pending`,`in_progress`,`completed`,`blocked`],Te=`__stndrdsNativeUiPartIds`;function invalidNativePartIds(){throw new n.ValidationError(`Native agent UI part IDs metadata is invalid`,[])}function isPlainRecord$1(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function nativeAgentUIPartIdMetadataKey(e,t){if(e.type===`text`||e.type===`reasoning`)return`${e.type}:${t}`;if(e.type===`tool`)return`tool:${e.toolCallId}`}function parseNativeAgentUIPartIdsMetadata(e){let t=e.metadata?.[Te];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 Ee={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2},De=`/v1/device-worker/channel`,Oe={initialMs:1e3,maxMs:3e4};function deviceChannelUrl(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${De}`}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,Oe)}const ke=[`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`];var DeviceChannelProtocolError=class extends n.SchemaError{constructor(e){super(e,n.SchemaErrorCode.DEVICE_CHANNEL_PROTOCOL),this._tag=`DeviceChannelProtocolError`,this.name=`DeviceChannelProtocolError`}};const w={id:f.z.uuid(),leaseToken:f.z.string().min(1)},Ae=f.z.record(f.z.string(),f.z.unknown());function defineDeviceChannelFrames(e){return{worker:f.z.discriminatedUnion(`type`,[f.z.strictObject({type:f.z.literal(`authenticate`),credential:f.z.string().regex(/^(Device|Bearer) \S+$/),protocol:f.z.number().int().positive().optional()}),f.z.strictObject({type:f.z.literal(`running`),...w}),f.z.strictObject({type:f.z.literal(`heartbeat`),...w}),f.z.strictObject({type:f.z.literal(`output`),...w,stdout:f.z.string().optional(),stderr:f.z.string().optional()}),f.z.strictObject({type:f.z.literal(`complete`),...w,result:f.z.strictObject({stdout:f.z.string().optional(),stderr:f.z.string().optional(),exitCode:f.z.number().int(),success:f.z.boolean(),errorCode:f.z.enum(ke).optional(),result:e.result.optional()})}),f.z.strictObject({type:f.z.literal(`pong`)})]),server:f.z.discriminatedUnion(`type`,[f.z.strictObject({type:f.z.literal(`ready`),device:f.z.strictObject({id:f.z.string(),name:f.z.string(),capability:f.z.enum([`shell`,`browser`])}),protocol:f.z.number().int().positive().optional()}),f.z.strictObject({type:f.z.literal(`command`),...w,kind:f.z.enum([`shell`,`browser`]),intent:f.z.string(),timeoutMs:f.z.number().int(),command:f.z.string().optional(),cwd:f.z.string().nullable().optional(),action:e.action.optional()}),f.z.strictObject({type:f.z.literal(`cancel`),id:f.z.uuid(),reason:f.z.enum([`cancelled`,`timed_out`,`revoked`])}),f.z.strictObject({type:f.z.literal(`reauthenticate`)}),f.z.strictObject({type:f.z.literal(`revoked`)}),f.z.strictObject({type:f.z.literal(`ping`)})])}}const je=defineDeviceChannelFrames({action:Ae,result:Ae}),Me=je.worker,Ne=je.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(Me,e)}function parseServerFrame(e){return parseDeviceChannelFrame(Ne,e)}const Pe=[`web`,`presentation`,`document`,`spreadsheet`,`image`,`code`,`other`],Fe=[`ephemeral`,`conversation`,`persistent`],Ie=[`source`,`preview`,`entrypoint`,`asset`];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 Le=[`relation`,`multiRelation`,`formula`,`rollup`,`document`,`richtext`,`user`];function isFormSlotFieldRef(e){return e.type===`slot`}function isFormFreeFieldRef(e){return e.type===`free`}function resolveFieldRequired(e){return e.fieldRequired===void 0?e.slotMode===`create`&&e.attributeRequired===!0:e.fieldRequired}function getSlotFieldTargets(e){return e.additionalSlotIds?.length?[e.slotId,...e.additionalSlotIds]:[e.slotId]}function formFieldKey(e){return isFormSlotFieldRef(e)?`${e.slotId}.${e.attribute}`:`free.${e.attribute.name}`}function formFieldFlatKey(e){return isFormSlotFieldRef(e)?e.attribute:e.attribute.name}function readFormFieldValue(e,t){return e[formFieldKey(t)]??e[formFieldFlatKey(t)]}function isFormFieldsRow(e){return e.type===`fields`}function isFormHeadingRow(e){return e.type===`heading`}function isFormSeparatorRow(e){return e.type===`separator`}function isFormTextRow(e){return e.type===`text`}var NoopGeocodingAdapter=class{async autocomplete(){return await Promise.resolve([])}async geocode(){return await Promise.resolve(null)}};const Re=[`reader`,`editor`],ze=[`manual`,`meeting_attendee`];function parseRecordAccessRole(e){if(typeof e==`string`&&Re.includes(e))return e;let t=`role must be one of: ${Re.join(`, `)}`;throw new n.ValidationError(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 Be=`Notetaker`,Ve={meetingRecordingPolicy:`none`,meetingBotDisplayName:Be},He=[`active`,`suspended`],Ue=[`architect`,`manual`,`auto`];function schemaGroupKey(e){return`${e.kind}:${e.id}`}function refuse$2(e,t){throw new n.ValidationError(t,[{path:[e],message:t}])}function parseSchemaGroupPresentation(t){let n=t??{},r={};if(n.label!==void 0){let t=n.label;if(t===null)r.label=null;else if(typeof t!=`string`)refuse$2(`label`,`Label must be a string`);else{let n=t.trim();n.length===0&&refuse$2(`label`,`Label must not be empty`),n.length>e.G.labelLength&&refuse$2(`label`,`Label is too long (max ${e.G.labelLength} characters)`),r.label=n}}if(n.icon!==void 0){let t=n.icon;if(t===null)r.icon=null;else{let n=e.W.safeParse(t);n.success||refuse$2(`icon`,`Invalid icon name`),r.icon=n.data}}return r}const We=[`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 Ge=[`none`,`estimated`,`exact`];function parseCountMode(e){if(typeof e==`string`&&Ge.includes(e))return e;throw new n.ValidationError(`countMode must be one of: ${Ge.join(`, `)} (received: ${String(e)})`,[])}function parseOptionalCountMode(e){return e===void 0?void 0:parseCountMode(e)}const Ke=[`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 qe=[`B`,`KB`,`MB`,`GB`,`TB`];function formatByteSize(e){let{value:t,unitIndex:n}=computeByteMagnitude(e);return`${t} ${qe[n]}`}const Je={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 Ye=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(!Ye.includes(e.type))throw Error(`Property type "${e.type}" is not supported in .qualifyWith()`);t.push(e)}return{definitions:t}}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 Xe=/\\([!-/:-@[-`{-~])/g,Ze=57344;function markdownToPlainText(e){if(e.length===0)return``;let t=[];return e.replace(Xe,(e,n)=>(t.push(n),String.fromCharCode(Ze+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)-Ze]??e)}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(t){if(e.V(t)){let e=formatDate(t.start);return t.end?`${e} → ${formatDate(t.end)}`:e}if(t instanceof Date)return t.toISOString().split(`T`)[0];if(typeof t==`string`){let e=new Date(t);if(!Number.isNaN(e.getTime()))return e.toISOString().split(`T`)[0]}return String(t)}function formatPhone(e){if(typeof e!=`object`||!e)return String(e);let t=e;return`phoneNumber`in t?t.phoneNumber?t.countryCode?u.n(t):t.phoneNumber:``:String(e)}function formatLocationValue(e,t=`full`){if(typeof e!=`object`||!e)return``;let n=e,r=[];switch(t){case`country`:n.country&&r.push((0,p.getCountryDisplayNameByIso3)(n.country));break;case`state`:n.state&&r.push(n.state),n.country&&r.push((0,p.getCountryDisplayNameByIso3)(n.country));break;case`city`:n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push((0,p.getCountryDisplayNameByIso3)(n.country));break;case`coordinates`:n.latitude!==void 0&&n.longitude!==void 0&&r.push(`${n.latitude}, ${n.longitude}`);break;case`address`:n.address&&r.push(n.address),n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push((0,p.getCountryDisplayNameByIso3)(n.country));break;default:n.address&&r.push(n.address),n.address2&&r.push(n.address2),n.city&&r.push(n.city),n.state&&r.push(n.state),n.postalCode&&r.push(n.postalCode),n.country&&r.push((0,p.getCountryDisplayNameByIso3)(n.country))}return r.join(`, `)}function formatLocation(e,t){return typeof e!=`object`||!e?String(e):formatLocationValue(e,t.granularity??`full`)||`—`}function formatSelect(e,t){return typeof e==`string`?t.options?.find(t=>t.value===e)?.label??String(e):String(e)}function formatMultiselect(e,t){return Array.isArray(e)?t.options?e.map(e=>t.options.find(t=>t.value===e)?.label).filter(Boolean).join(`, `):e.join(`, `):String(e)}function formatAttributeValue(e,t){if(l.t(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 Qe=[`UPPER`,`LOWER`,`capitalize`,`trim`],$e=[`prefix`,`suffix`,`wrap`,`default`],T=[...Qe,...$e],E=f.z.string().min(1,`labelExpression cannot be empty`).refine(e=>isLabelExpression(e),{message:`labelExpression must contain at least one {{ attribute }} interpolation`}).refine(e=>!/\{\{\s*\}\}/.test(e),{message:`labelExpression contains empty {{ }} interpolation`}).refine(e=>{let t=/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g,n;for(;(n=t.exec(e))!==null;){let e=n[1];if(!T.includes(e))return!1}return!0},{message:`Invalid pipe name. Valid pipes: ${T.join(`, `)}`});function validateLabelExpression(e){let t=E.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 et=`(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=et){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 tt=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function getSingleAttributeFromExpression(e){let t=e.trim().match(tt);return t?t[1]:null}function getEditableLabelAttribute(e,n){let r=getSingleAttributeFromExpression(e);if(r===null)return null;let i=n.find(e=>e.name===r);return!i||i.type!==`text`||t.rt(i).authoring.readOnly?null:i}const nt=/\{\{\s*props\./;function applyRelationProps(e,t,n){if(!nt.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(l.t(e))return[];if(typeof e==`string`)return[{id:e}];if(Array.isArray(e))return e.flatMap(e=>extractValueRefs(e));if(typeof e==`object`&&`id`in e){let t=e;if(typeof t.id==`string`)return[{id:t.id,props:t.props}]}return[]}function 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 rt=/\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(rt)?.[0];return t===void 0?``:[...t.toUpperCase()][0]??``}).filter(Boolean).slice(0,2).join(``);return i===``?t:i}const it=`__creatorRootActorId`;function getRecordCreatorPrincipalId(e){let t=e.metadata?.[it];return typeof t==`string`&&t.length>0?t:e.createdBy}const at=[{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`]}]}]}],ot=`none`,st=`custom`,D={actions:[`read`,`create`,`update`,`delete`],purge:`manage`,levels:[{id:`read`,add:[`read`]},{id:`edit`,add:[`create`,`update`]},{id:`full`,add:[`delete`]}]},O=at.flatMap(e=>e.capabilities),ct=O.flatMap(e=>e.resources),lt=new Map(O.flatMap(e=>e.resources.map(t=>[t,e])));function isCatalogResource(e){return lt.has(e)}function capabilityForResource(e){let t=lt.get(e);if(!t)throw new n.SchemaError(`Unknown catalog resource "${e}"`,n.SchemaErrorCode.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 ot;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 st}const k=[`read`,`create`,`update`,`delete`,`manage`],ut=f.z.object({scope:f.z.enum([`object`,`system`]),target:f.z.string().min(1),actions:f.z.array(f.z.enum(k))}).strict();function findGrantIssues(e,t){let n=[],r=new Map;for(let i of e){let e=ut.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===`*`?[...D.actions,D.purge]:D.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===`*`?[...k]: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 dt=`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 O){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:st}let i=n[`*`]??[],a=levelWithin(D,i),o=[];for(let[e,t]of Object.entries(n)){if(e===`*`)continue;let n=levelWithin(D,[...i,...t]);n!==a&&o.push({objectName:e,level:n})}return{capabilities:r,defaultObjectLevel:a,exceptions:o,purge:includesAction(i,D.purge)}}function readRoleLevels(e){return readAccessLevels(grantsToPermissions(e))}function summarizeGroup(e,t){let r=at.find(e=>e.id===t);if(!r)throw new n.SchemaError(`Unknown permission group "${t}"`,n.SchemaErrorCode.INVARIANT_VIOLATION);let{capabilities:i}=readRoleLevels(e),a=new Set(r.capabilities.map(e=>i[e.id]??`none`)),[o]=a;return a.size===1&&o!==void 0?o:dt}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(D,storedActions(t,`object`,`*`)):levelActions(D,e.defaultObjectLevel)}function grantsFromLevels(e,t){let n=[];for(let r of O){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,D.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(D,storedActions(t,`object`,i)):levelActions(D,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=O.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(D,t)?withLevels(e,e=>({...e,defaultObjectLevel:t})):e}function exceptionLevels(e){let t=defaultObjectActions(readRoleLevels(e),e);return D.levels.map(e=>e.id).filter(e=>!isSubset(levelActions(D,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(D,n))return!1;let i=levelActions(D,n),a=t.objectName===`*`&&r?[...i,D.purge]:i;return uncoveredGrants(e,[{scope:`object`,target:t.objectName,actions:a}]).length===0}let i=O.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:[D.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 ft=new Set([`id`,`name`,`label`,`type`,`required`,`system`,`unique`,`order`]),pt={OWNER:`owner`,MEMBER:`member`,AGENT_DEFAULT:`agent_default`},mt={owner:`Owner`,member:`Member`,agent_default:`Agent Default`},ht={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`},A=[...D.actions],gt=[...k],_t={owner:{system:[{target:`*`,actions:gt}],object:[{target:`*`,actions:gt}]},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:A},{target:`files`,actions:A},{target:`documents`,actions:A}],object:[{target:`*`,actions:A}]},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:A}]}},vt=[{role:`member`,scope:`object`,target:`*`,actions:[`manage`]}];function isDefaultRole(e){return Object.values(pt).includes(e)}const yt=[{id:`claude-code`,label:`Claude Code`,available:!0,loginCommand:`claude setup-token 2>&1 | tee ~/.standards/login.log`,credentialPaths:[`~/.standards/login.log`,`~/.claude/.credentials.json`],apiKeyEnv:[`ANTHROPIC_API_KEY`],models:[{id:`sonnet`,label:`Claude Sonnet`},{id:`opus`,label:`Claude Opus`},{id:`haiku`,label:`Claude Haiku`}],defaultModel:`sonnet`},{id:`codex`,label:`Codex`,available:!1,loginCommand:`codex login --device-auth`,credentialPaths:[`~/.codex/auth.json`],apiKeyEnv:[`OPENAI_API_KEY`],models:[{id:`gpt-5-codex`,label:`GPT-5 Codex`}],defaultModel:`gpt-5-codex`},{id:`opencode`,label:`OpenCode`,available:!1,loginCommand:`opencode auth login`,credentialPaths:[`~/.local/share/opencode/auth.json`],apiKeyEnv:[`ANTHROPIC_API_KEY`,`OPENAI_API_KEY`],models:[{id:`anthropic/claude-sonnet-4-5`,label:`Claude Sonnet 4.5`}],defaultModel:`anthropic/claude-sonnet-4-5`},{id:`cursor`,label:`Cursor`,available:!1,loginCommand:`cursor-agent login`,credentialPaths:[`~/.config/cursor/auth.json`],apiKeyEnv:[`CURSOR_API_KEY`],models:[{id:`auto`,label:`Auto`}],defaultModel:`auto`},{id:`grok-build`,label:`Grok Build`,available:!1,loginCommand:`grok login`,credentialPaths:[`~/.grok/auth.json`],apiKeyEnv:[`XAI_API_KEY`],models:[{id:`grok-code-fast-1`,label:`Grok Code Fast 1`}],defaultModel:`grok-code-fast-1`}],bt=new Map(yt.map(e=>[e.id,e]));function isWorkstationHarnessId(e){return bt.has(e)}function findWorkstationHarness(e){return bt.get(e)}const xt={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2},timeoutMs:3e5};var AgentBuilder=class{constructor(e){if(!e.name||e.name.trim().length===0)throw new n.ValidationError(`Agent name is required`,[]);this.bp={name:e.name,system:!0,visibility:`workspace`,triggers:[]}}description(e){return this.bp.description=e,this}label(e){return this.bp.label=e,this}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??xt,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={...se,...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 n.ValidationError(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new n.ValidationError(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility===`private`)throw new n.ValidationError(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return e.N(this.bp.triggers,e=>e.name,e=>new n.ValidationError(`Agent "${this.bp.name}": duplicate trigger name "${e}"`,[])),{...this.bp,visibility:this.bp.visibility??`workspace`,config:this.bp.config??xt,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};function agent(e){return new AgentBuilder(e)}const St=`@stndrds/schema`;function createStandardSchemaProps(e){return{version:1,vendor:St,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(d.d(this.build()))}constructor(t,n,r){e.P(n),e.I(r),this.attr={name:n,label:r,type:t,required:!1,system:!0}}setRequired(e){this.attr.required=e}asRequiredState(){return this}asPhantomState(){return this}runtime(){return this.attr.system=!1,this}hidden(){return this.attr.hidden=!0,this}placeholder(e){return this.attr.placeholder=e,this}description(e){return this.attr.description=e,this}icon(t){return e.F(t,`attribute "${this.attr.name}"`),this.attr.icon=t,this}order(e){return this.attr.order=e,this}defaultValue(e){return(`defaultValue`in this.attr||![`formula`,`rollup`].includes(this.attr.type))&&(this.attr.defaultValue=e),this}metadata(e){return this.attr.metadata=e,this}build(){return this.attr}},TextAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`text`,e,t)}minLength(e){return this.attr.minLength=e,this}maxLength(e){return this.attr.maxLength=e,this}pattern(e){return this.attr.pattern=e,this.attr.format=void 0,this}multiline(e=!0){return this.attr.multiline=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}email(){return this.attr.format=`email`,this.attr.pattern=void 0,this}url(){return this.attr.format=`url`,this.attr.pattern=void 0,this}slug(){return this.attr.format=`slug`,this.attr.pattern=void 0,this}};function text(e){return new TextAttributeBuilder(e.name,e.label)}var RichtextAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`richtext`,e,t)}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function richtext(e){return new RichtextAttributeBuilder(e.name,e.label)}var NumberAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`number`,e,t)}min(e){return this.attr.min=e,this}max(e){return this.attr.max=e,this}integer(){return this.attr.unit=`integer`,this.attr.decimals=0,this}decimal(e=2){return this.attr.unit=`decimal`,this.attr.decimals=e,this}percentage(){return this.attr.unit=`percentage`,this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function number(e){return new NumberAttributeBuilder(e.name,e.label)}var CheckboxAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`checkbox`,e,t)}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function checkbox(e){return new CheckboxAttributeBuilder(e.name,e.label)}var DateAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`date`,e,t)}format(e){return this.attr.dateFormat=e,this}minDate(e){return this.attr.minDate=e,this}maxDate(e){return this.attr.maxDate=e,this}endDate(){return this.attr.endDate=!0,this.asPhantomState()}includeTime(){return this.attr.includeTime=!0,this}timeFormat(e){return this.attr.timeFormat=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function date(e){return new DateAttributeBuilder(e.name,e.label)}var PhoneAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`phone`,e,t)}defaultCountry(e){return this.attr.defaultCountryCode=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function phone(e){return new PhoneAttributeBuilder(e.name,e.label)}var CurrencyAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`currency`,e,t)}defaultCurrency(e){return this.attr.defaultCurrency=e,this}allowedCurrencies(e){return this.attr.allowedCurrencies=e,this}allowNegative(e=!0){return this.attr.allowNegative=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function currency(e){return new CurrencyAttributeBuilder(e.name,e.label)}var StatusAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`status`,e,t)}options(t){let n=asMutableArray(t);return e.R(this.attr.name??`unknown`,n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return e.R(this.attr.name??`unknown`,n),this.attr.options.push(t),this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function status(e){return new StatusAttributeBuilder(e.name,e.label)}var SelectAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`select`,e,t)}options(t){let n=asMutableArray(t);return e.R(this.attr.name??`unknown`,n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return e.R(this.attr.name??`unknown`,n),this.attr.options.push(t),this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function select(e){return new SelectAttributeBuilder(e.name,e.label)}var MultiselectAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`multiselect`,e,t)}options(t){let n=asMutableArray(t);return e.R(this.attr.name??`unknown`,n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return e.R(this.attr.name??`unknown`,n),this.attr.options.push(t),this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function multiselect(e){return new MultiselectAttributeBuilder(e.name,e.label)}var LocationAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`location`,e,t)}granularity(e){return this.attr.granularity=e,this}defaultCountry(e){return this.attr.defaultCountry=e,this}allowedCountries(e){return this.attr.allowedCountries=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function location(e){return new LocationAttributeBuilder(e.name,e.label)}var UserAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`user`,e,t),this.attr.types=[`user`,`agent`]}types(e){let t=[...new Set(e)];if(t.length===0)throw Error(`[AttributeBuilder] user.types must contain at least one type.`);return this.attr.types=t,this}multiple(){return this.attr.multiple=!0,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function user(e){return new UserAttributeBuilder(e.name,e.label)}var BaseRelationAttributeBuilder=class extends BaseAttributeBuilder{to(e,t){let n={object:e,...t};return this.attr.targets?.push(n),this}toAny(){return this.attr.targets=[{object:`*`}],this}qualifyWith(...e){let t=this.attr.targets;if(!t||t.length===0)throw Error(`.qualifyWith() must be called AFTER .to(). Example: relation({ name: "companies" }).to("companies").qualifyWith(...)`);return this.attr.properties=buildPropertySchema(e),this}bilateral(e){let r=this.attr.targets;if(!r||r.length===0)throw Error(`.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })`);if(r.length>1)throw Error(`Bilateral relations are not supported for polymorphic relations (multiple .to() targets).`);if(t.$(this.attr))throw Error(`Bilateral relations are not supported for universal relations (.toAny()).`);let i=r[0]?.object;if(!i)throw new n.ValidationError(`Bilateral relation requires one target object`,[{path:[`bilateral`,`object`],message:`Bilateral relation requires one target object`}]);if(e.object&&e.object!==i){let t=`Bilateral inverse object ${e.object} must match relation target ${i}`;throw new n.ValidationError(t,[{path:[`bilateral`,`object`],message:t}])}return this.attr.bilateral={...e,object:i},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`,r=this.attr.targetAttribute??`field`;throw new n.SchemaError(`Rollup "${this.attr.name}": .using("original") only supports a "select", "status", or "multiselect" target, but .targetType("${t}") was given. To surface a plain ${t} value from a related record, use a formula instead — e.g. formula({ name: "${this.attr.name}", label: "…" }).expression("${e}.${r}").`,n.SchemaErrorCode.VALIDATION_FAILED)}return super.build()}required(){throw Error(`Rollup attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.`)}optional(){return this}};function rollup(e){return new RollupAttributeBuilder(e.name,e.label)}var DocumentAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`document`,e,t)}accepts(e){return this.attr.accepts=e,this}maxFileSize(e){return this.attr.maxFileSize=e,this}qualifyWith(...e){return this.attr.properties=buildPropertySchema(e),this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function document(e){return new DocumentAttributeBuilder(e.name,e.label)}function buildSlotFieldRef(e,t,n){let[r,...i]=Array.isArray(e)?e:[e];return{type:`slot`,slotId:r,additionalSlotIds:i.length>0?i:void 0,attribute:t,label:n?.label,required:n?.required,tooltip:n?.tooltip}}var FormRowBuilder=class{constructor(e,t,n){this._finalized=!1,this.stepBuilder=e,this.rowData={id:t,order:n,type:`fields`,fields:[]}}field(e,t,n){return this.rowData.fields.push(buildSlotFieldRef(e,t,n)),this}freeField(e,t){let n={type:`free`,attribute:e.build(),label:t?.label,required:t?.required,prefillExpression:t?.prefillExpression};return this.rowData.fields.push(n),this}row(e){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).row(e)}heading(e,t){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).heading(e,t)}separator(){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).separator()}text(e){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).text(e)}endRow(){return this._finalized?this.stepBuilder:(this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData))}},FormStepBuilder=class{constructor(e,t,n){this.rowOrder=0,this.formBuilder=e,this.stepData={id:t,label:n,rows:[]}}description(e){return this.stepData.description=e,this}field(e,t,n){this.rowOrder++;let r=`row-${this.stepData.id}-${this.rowOrder}`,i=buildSlotFieldRef(e,t,n),a={id:r,order:this.rowOrder,type:`fields`,fields:[i]};return this.stepData.rows.push(a),this}freeField(e,t){this.rowOrder++;let n=`row-${this.stepData.id}-${this.rowOrder}`,r={type:`free`,attribute:e.build(),label:t?.label,required:t?.required,prefillExpression:t?.prefillExpression},i={id:n,order:this.rowOrder,type:`fields`,fields:[r]};return this.stepData.rows.push(i),this}row(e){return this.rowOrder++,new FormRowBuilder(this,e,this.rowOrder)}heading(e,t){this.rowOrder++;let n={id:`heading-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:`heading`,content:e,level:t};return this.stepData.rows.push(n),this}separator(){this.rowOrder++;let e={id:`sep-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:`separator`};return this.stepData.rows.push(e),this}text(e){this.rowOrder++;let t={id:`text-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:`text`,content:e};return this.stepData.rows.push(t),this}step(e,t){return this.formBuilder._finalizeStep(this.stepData).step(e,t)}build(){return this.formBuilder._finalizeStep(this.stepData).build()}_finalizeRow(e){return e.fields.length>0&&this.stepData.rows.push(e),this}_getData(){return this.stepData}},FormBuilder=class{constructor(e,t){this.data={slots:[],steps:[],status:`draft`,version:1},this.validateName(e),this.data.name=e,this.data.label=t}description(e){return this.data.description=e,this}icon(e){return this.data.icon=e,this}status(e){return this.data.status=e,this}metadata(e){return this.data.metadata=e,this}slot(e,t,n){if(this.data.slots.some(t=>t.id===e))throw Error(`[FormBuilder] Duplicate slot id: "${e}"`);let r={id:e,objectName:t,label:n.label,mode:n.mode??`create`,color:n.color,icon:n.icon};return this.data.slots.push(r),this}step(e,t){if(this.data.steps.some(t=>t.id===e))throw Error(`[FormBuilder] Duplicate step id: "${e}"`);return new FormStepBuilder(this,e,t)}build(){return this.validateRequiredData(),this.validateSlotReferences(),this.validateFreeFields(),this.validatePrefillExpressions(),this.data}_finalizeStep(e){return this.data.steps.push(e),this}validateName(e){let t=f.z.string().min(1,`Form name cannot be empty`).max(63,`Form name is too long (max 63 characters)`).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,{message:`Invalid form name format. Name must be in kebab-case: 'client-onboarding', 'contact-creation'`});try{t.parse(e)}catch(e){throw e instanceof f.z.ZodError?Error(`[FormBuilder] ${e.issues[0].message}`):e}}validateRequiredData(){if(this.data.slots.length===0)throw Error(`[FormBuilder] At least one slot is required. Use .slot() to add slots.`);if(this.data.steps.length===0)throw Error(`[FormBuilder] At least one step is required. Use .step() to add steps.`)}validateSlotReferences(){let e=new Map(this.data.slots.map(e=>[e.id,e.objectName]));for(let t of this.data.steps)for(let n of t.rows)if(isFormFieldsRow(n))for(let r of n.fields){if(r.type!==`slot`)continue;let n=getSlotFieldTargets(r);for(let r of n)if(!e.has(r))throw Error(`[FormBuilder] Step "${t.id}" references unknown slot "${r}". Declare it with .slot("${r}", ...) first.`);let i=new Set(n.map(t=>e.get(t)));if(i.size>1)throw Error(`[FormBuilder] Step "${t.id}" field on attribute "${r.attribute}" targets slots of different objects (${[...i].join(`, `)}). A multi-slot field must target slots of the same object.`)}}validatePrefillExpressions(){let e=[...T,`join`];for(let t of this.data.steps)for(let n of t.rows)if(isFormFieldsRow(n))for(let r of n.fields){if(!isFormFreeFieldRef(r)||!r.prefillExpression)continue;let n=r.prefillExpression,i=`prefillExpression on free field "${r.attribute.name}" in step "${t.id}"`;if(!isLabelExpression(n))throw Error(`[FormBuilder] ${i} must contain at least one {{ attribute }} interpolation.`);if(/\{\{\s*\}\}/.test(n))throw Error(`[FormBuilder] ${i} contains empty {{ }} interpolation.`);for(let t of n.matchAll(/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g)){let n=t[1];if(!e.includes(n))throw Error(`[FormBuilder] ${i} uses invalid pipe "${n}". Valid pipes: ${e.join(`, `)}`)}}}validateFreeFields(){let e=new Set(Le);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: ${Le.join(`, `)}`)}}}};function form(e,t){return new FormBuilder(e,t)}function validateObjectExpressions(e){let{name:t,labelExpression:r,embeddingExpression:i}=e;if(!r)throw new n.SchemaError(`Object "${t}" must have a labelExpression. The labelExpression defines how records are displayed in lists and relations (e.g. "{{ name }}").`,n.SchemaErrorCode.VALIDATION_FAILED);let a=E.safeParse(r);if(!a.success){let e=a.error.issues[0]?.message??`Invalid labelExpression`;throw new n.SchemaError(`Invalid labelExpression for "${t}": ${e}`,n.SchemaErrorCode.VALIDATION_FAILED)}if(i!==void 0){let e=E.safeParse(i);if(!e.success){let r=e.error.issues[0]?.message??`Invalid embeddingExpression`;throw new n.SchemaError(`Invalid embeddingExpression for "${t}": ${r}`,n.SchemaErrorCode.VALIDATION_FAILED)}}}var ObjectBuilder=class{get"~standard"(){return createStandardSchemaProps(d.u(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(t){let r=t.map(e=>`build`in e&&typeof e.build==`function`?e.build():e);e.N([...this.obj.attributes,...r],e=>e.name,e=>new n.DuplicateError(`attribute`,e,`Object "${this.obj.name}": duplicate attribute name "${e}"`)),this.obj.attributes.push(...r)}metadata(e){return this.obj.metadata={...this.obj.metadata,...e},this}order(e){return this.obj.metadata={...this.obj.metadata,order:e},this}hidden(){return this.obj.metadata={...this.obj.metadata,hidden:!0},this}labelExpression(e){return this._labelExpression=e,this}embeddingExpression(e){return this._embeddingExpression=e,this}documentLayout(e){if(e.presets)for(let t of e.presets)validatePresetStructure(t.id,t.structure,1);return this.obj.documentLayout=e,this}build(){if(!this.obj.name)throw new n.ValidationError(`[ObjectBuilder] Missing required field: name`,[{path:[`name`],message:`name is required`}]);if(!this.obj.label)throw new n.ValidationError(`[ObjectBuilder] Missing required field: label`,[{path:[`label`],message:`label is required`}]);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(t){t!==void 0&&e.L(t)}};function object(t){if(e.$(t.name))throw new n.ReservedObjectNameError(t.name,`builder`);return new ObjectBuilder(t)}function validatePresetStructure(e,t,r){let fail=(t,r)=>{throw new n.ValidationError(t,[{path:[`documentLayout`,`presets`,e],message:r}])};r>5&&fail(`Preset structure exceeds max depth of 5`,`Preset structure too deep`);let i=new Set;for(let n of t){let t=n.title.trim();t.length===0&&fail(`Folder preset node title is required`,`Empty folder title`),t.includes(`/`)&&fail(`Folder preset node title cannot contain /`,`Folder title contains /: "${t}"`),i.has(t)&&fail(`Folder preset sibling titles must be unique`,`Duplicate folder title: "${t}"`),i.add(t),n.children&&n.children.length>0&&validatePresetStructure(e,n.children,r+1)}}function cloneBuilderValue(e,t){try{return structuredClone(e)}catch{let e=`Builder configuration must contain cloneable data`;throw new n.ValidationError(e,[{path:t,message:e}])}}function requireBuilderName(e,t){if(typeof e!=`string`||e.trim().length===0)throw new n.ValidationError(`Name must not be blank`,[{path:t,message:`Name must not be blank`}])}function validateContentConfiguration(e,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new n.ValidationError(`Invalid content configuration`,[{path:r,message:`Expected content configuration`}]);for(let t of[`name`,`label`,`placement`])if(Object.hasOwn(e,t)){let e=`Independent content configuration cannot define ${t}`;throw new n.ValidationError(e,[{path:[...r,t],message:e}])}let i=t.l.safeParse({...e,name:`content`,placement:`main`});if(!i.success)throw n.ValidationError.fromZodErrors(i.error.issues.map(e=>({path:[...r,...e.path.map(String)],message:e.message})));i.data.type===`form`&&i.data.groups.forEach((e,t)=>requireBuilderName(e.name,[...r,`groups`,String(t),`name`]));let{name:a,label:o,placement:s,...c}=i.data;return cloneBuilderValue(c,r)}function validateLiteralContent(e,t){return validateContentConfiguration(e,t),cloneBuilderValue(e,t)}function collectionSourceAddress(e){return e.relation===void 0?{kind:`object`,object:e.object}:e.object===void 0?{kind:`related`,relation:e.relation}:{kind:`relatedFrom`,object:e.object,relation:e.relation}}function collectionSourceAddressOf(e){if(!e||typeof e!=`object`)return;let t=`object`in e?e.object:void 0,n=`relation`in e?e.relation:void 0;if(typeof t==`string`&&typeof n==`string`)return{kind:`relatedFrom`,object:t,relation:n};if(typeof t==`string`&&n===void 0)return{kind:`object`,object:t};if(typeof n==`string`&&t===void 0)return{kind:`related`,relation:n}}function 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,r){if(t!==`record`){let t=`Content "${e}" requires record context. In a collection view only a collection that lists a whole object, or a custom content that does not require a record, is allowed.`;throw new n.ValidationError(t,[{path:r,message:t}])}}function resolveContentNavigation(e){let t=e.openMode??`page`;return{openMode:t,createMode:e.createMode??t}}function resolveCollectionActions(e,t){return[...new Set(t)].filter(t=>e.actions===void 0||e.actions.includes(t))}var Ct=class ViewBuilder{constructor(e,t=[]){this.kind=`view`,this.data=cloneBuilderValue(e,[`views`,`0`]),this.extensions=t.map(e=>e&&{...e})}for(e){return new ViewBuilder({...this.data,object:e},this.extensions)}default(){return new ViewBuilder({...this.data,default:!0},this.extensions)}description(e){return new ViewBuilder({...this.data,description:e},this.extensions)}icon(e){return new ViewBuilder({...this.data,icon:e},this.extensions)}place(e,t,r,i){let a=[`views`,`0`,`contents`,String(this.data.contents.length)],o,s;try{typeof r==`object`&&r&&`build`in r&&typeof r.build==`function`?(o=validateContentConfiguration(r.build(),a),s=r.extension):o=validateContentConfiguration(r,a)}catch(e){throw e instanceof n.ValidationError?new n.ValidationError(e.message,e.errors.map(e=>({...e,path:e.path[0]===`content`?[...a,...e.path.slice(1)]:e.path}))):e}let c={...o,name:e,label:t,placement:i},l=[...this.data.contents,c];return new ViewBuilder({...this.data,contents:l},[...this.extensions,s])}tab(e,t,n){return this.place(e,t,n,`main`)}aside(e,t,n){return this.place(e,t,n,`aside`)}build(){let e=[`views`,`0`];requireBuilderName(this.data.name,[...e,`name`]),requireBuilderName(this.data.object,[...e,`object`]);let r=t.r.safeParse(this.data);if(!r.success)throw n.ValidationError.fromZodErrors(r.error.issues.map(t=>({path:[...e,...t.path.map(String)],message:t.message})));return this.data.contents.forEach((t,n)=>{let r=[...e,`contents`,String(n)];requireBuilderName(t.name,[...r,`name`]),t.type===`form`&&t.groups.forEach((e,t)=>requireBuilderName(e.name,[...r,`groups`,String(t),`name`])),(t.type===`custom`?this.extensions[n]?.requiresRecord:t.type!==`collection`||collectionSourceAddress(t.source).kind!==`object`)&&requireRecordContentContext(t.name,this.data.context,r)}),{kind:`view`,definition:cloneBuilderValue(this.data,e)}}};function detailView(e,t){return new Ct({name:e,label:t,object:void 0,context:`record`,contents:[]})}function listView(e,t){return new Ct({name:e,label:t,object:void 0,context:`collection`,contents:[]})}function relationProperty(e){return requireBuilderName(e,[`relationProperty`]),{relationProperty:e}}var j=class ContentBuilder{constructor(e,t){this.data=cloneBuilderValue(e,[`content`]),this.extension=t===void 0?void 0:Object.freeze({name:t.name,requiresRecord:t.requiresRecord,parameters:t.parameters})}set(e){return new ContentBuilder({...this.data,...e},this.extension)}icon(e){return this.set({icon:e})}object(e){return this.data.type===`forms`?this.set({objectName:e}):this.set({source:{object:e}})}related(e){return this.set({source:{relation:e}})}relatedFrom(e,t){return this.set({source:{object:e,relation:t}})}layout(e){let{layout:t,groupByAttribute:n,columnSizing:r,kanbanColumnOrder:i,kanbanColumnVisibility:a,kanbanPinnedColumns:o,...s}={...this.data,layout:void 0,groupByAttribute:void 0,columnSizing:void 0,kanbanColumnOrder:void 0,kanbanColumnVisibility:void 0,kanbanPinnedColumns:void 0};return new ContentBuilder({...s,...e},this.extension)}table(){return this.layout({layout:`table`})}list(){return this.layout({layout:`list`})}kanban(e){return this.layout({layout:`kanban`,groupByAttribute:e})}columns(...e){return this.set({columns:e})}filter(e){return this.set({filters:e})}sort(e,t=`asc`){let n=[...`sorts`in this.data&&Array.isArray(this.data.sorts)?this.data.sorts:[],{attribute:e,direction:t}];return this.set({sorts:n})}actions(...e){return this.set({actions:e})}openMode(e){return this.set({openMode:e})}createMode(e){return this.set({createMode:e})}visibility(e){return this.set({visibility:e})}descriptionAttribute(e){return this.set({descriptionAttribute:e})}displayAttributes(...e){return this.set({displayAttributes:e})}columnSizing(e){return this.set({columnSizing:e})}kanbanColumnOrder(...e){return this.set({kanbanColumnOrder:e})}kanbanColumnVisibility(e){return this.set({kanbanColumnVisibility:e})}kanbanPinnedColumns(...e){return this.set({kanbanPinnedColumns:e})}formColumns(e){return this.set({formColumns:e})}density(e){return this.set({density:e})}titleAttribute(e){return this.set({titleAttribute:e})}allowUpload(e){return this.set({allowUpload:e})}allowRemove(e){return this.set({allowRemove:e})}hideAttachments(e){return this.set({hideAttachments:e})}relations(...e){return this.set({relations:e})}build(){let e=validateLiteralContent(this.data,[`content`]);if(this.extension&&e.type===`custom`){let t=this.extension.parameters.safeParse(cloneBuilderValue(e.parameters??{},[`content`,`parameters`]));if(!t.success)throw n.ValidationError.fromZodErrors(t.error.issues.map(e=>({path:[`content`,`parameters`,...e.path.map(String)],message:e.message})))}return e}},wt=class GroupBuilder{constructor(e,t,n,r={}){this.data=cloneBuilderValue({name:e,label:t,fields:n,...r},[`group`])}field(e,t){let{name:n,label:r,fields:i,...a}=this.data;return new GroupBuilder(n,r,[...i,{attribute:e,...t}],a)}fields(...e){let{name:t,label:n,fields:r,...i}=this.data;return new GroupBuilder(t,n,[...r,...e.map(e=>({attribute:e}))],i)}description(e){return new GroupBuilder(this.data.name,this.data.label,this.data.fields,{...this.presentation(),description:e})}collapsible(e=!1){return new GroupBuilder(this.data.name,this.data.label,this.data.fields,{...this.presentation(),collapsible:!0,collapsed:e})}presentation(){let{name:e,label:t,fields:n,...r}=this.data;return r}build(){requireBuilderName(this.data.name,[`group`,`name`]);try{validateLiteralContent({type:`form`,groups:[this.data]},[`group`])}catch(e){throw e instanceof n.ValidationError?new n.ValidationError(e.message,e.errors.map(e=>({...e,path:e.path[1]===`groups`?[`group`,...e.path.slice(3)]:e.path}))):e}return cloneBuilderValue(this.data,[`group`])}};function group(e,t){return new wt(e,t,[])}function collection(){return new j({type:`collection`})}function form$1(...e){return new j({type:`form`,groups:e.map(e=>`build`in e?e.build():e)})}function activity(){return new j({type:`activity`})}function richtext$1(e){return new j({type:`richtext`,attribute:e})}function documents(){return new j({type:`documents`})}function forms(){return new j({type:`forms`})}function emails(...e){return new j({type:`emails`,emailAttributes:e})}function meetings(...e){return new j({type:`meetings`,emailAttributes:e})}function custom(e,t){if(typeof e!=`object`||!e||typeof e.name!=`string`)throw new n.ValidationError(`Expected registered extension declaration`,[{path:[`content`,`extension`],message:`Expected registered extension declaration`}]);let r=validateContentConfiguration({type:`custom`,extension:e.name,parameters:t},[`content`]);if(r.type!==`custom`)throw new n.ValidationError(`Expected custom content`,[]);let i=new j({...r,extension:e.name},e);return i.build(),i}const M={collection,form:form$1,activity,richtext:richtext$1,documents,forms,emails,meetings,custom};function validateFlagName(e){if(!/^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$/.test(e))throw Error(`Invalid flag name "${e}". Flag names must be kebab-case (e.g., "architect-mode", "ai-features").`)}var BaseFlagBuilder=class{constructor(e,t,n){validateFlagName(e),this.flag={name:e,valueType:t,defaultValue:n,allowedLevels:[`global`,`tenant`,`user`]}}label(e){return this.flag.label=e,this}description(e){return this.flag.description=e,this}category(e){return this.flag.category=e,this}system(){return this.flag.system=!0,this}tenantScoped(){return this.flag.allowedLevels=[`global`,`tenant`],this}globalOnly(){return this.flag.allowedLevels=[`global`],this}allowedLevels(e){return this.flag.allowedLevels=[...e],this}build(){if(!this.flag.label?.trim())throw Error(`Flag "${this.flag.name}" must have a label. Use .label("Human-readable label").`);return{...this.flag,allowedLevels:[...this.flag.allowedLevels||[]]}}},BooleanFlagBuilder=class extends BaseFlagBuilder{constructor(e){super(e,`boolean`,!1)}defaultValue(e){return this.flag.defaultValue=e,this}enabledByDefault(){return this.flag.defaultValue=!0,this}},StringFlagBuilder=class extends BaseFlagBuilder{constructor(e){super(e,`string`,``)}defaultValue(e){return this.flag.defaultValue=e,this}},NumberFlagBuilder=class extends BaseFlagBuilder{constructor(e){super(e,`number`,0)}defaultValue(e){return this.flag.defaultValue=e,this}},JsonFlagBuilder=class extends BaseFlagBuilder{constructor(e,t){super(e,`json`,t)}defaultValue(e){return this.flag.defaultValue=e,this}};function booleanFlag(e){return new BooleanFlagBuilder(e)}function stringFlag(e){return new StringFlagBuilder(e)}function numberFlag(e){return new NumberFlagBuilder(e)}function jsonFlag(e,t){return new JsonFlagBuilder(e,t)}function duplicateFlagError(e){return new n.DuplicateError(`feature flag`,e,`Flag "${e}" is already registered. Each flag name must be unique.`)}function cloneFlagDefinition(e){return{...e,allowedLevels:[...e.allowedLevels]}}var FlagRegistry=class{constructor(){this.flags=new Map}register(e){if(this.flags.has(e.name))throw duplicateFlagError(e.name);this.flags.set(e.name,cloneFlagDefinition(e))}registerAll(e){let t=new Set;for(let n of e){if(this.flags.has(n.name)||t.has(n.name))throw duplicateFlagError(n.name);t.add(n.name)}for(let t of e)this.register(t)}get(e){let t=this.flags.get(e);return t?cloneFlagDefinition(t):void 0}getOrThrow(e){let t=this.get(e);if(!t)throw new n.NotFoundError(`Feature flag`,e,void 0,`Flag "${e}" is not registered. Available flags: ${this.listNames().join(`, `)}`);return t}has(e){return this.flags.has(e)}list(){return Array.from(this.flags.values(),cloneFlagDefinition)}listNames(){return Array.from(this.flags.keys())}unregister(e){return this.flags.delete(e)}clear(){this.flags.clear()}get size(){return this.flags.size}};const Tt=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 Et=Symbol(`stndrds.native-object`);function markNativeDefinition(e){return Object.defineProperty(e,Et,{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[Et]===!0}function cloneObjectDefinition(e){let t=structuredClone(e);return isNativeDefinition(e)?markNativeDefinition(t):t}var NativeObjectRegistryClass=class{constructor(){this.objects=new Map}register(e){let t=(Array.isArray(e)?e:[e]).map(e=>`build`in e&&typeof e.build==`function`?e.build():e),r=new Set;for(let e of t){if(this.validate(e),r.has(e.name))throw new n.DuplicateError(`object`,e.name,`[NativeObjectRegistry] Duplicate object name "${e.name}" within a single register() batch.`);r.add(e.name)}for(let e of t)this.objects.set(e.name,cloneObjectDefinition(e));return this}validate(t){if(!t.system){let e=`[NativeObjectRegistry] Cannot register object "${t.name}" (id: ${t.id}): missing system flag.\nNative objects must have system=true. Did you call .runtime() on the builder? Remove that call — objects are system:true by default.`;throw new n.ValidationError(e,[])}if(e.$(t.name)&&!isNativeDefinition(t))throw new n.ReservedObjectNameError(t.name,`registry`);if(this.objects.has(t.name)){let e=this.objects.get(t.name),r=`[NativeObjectRegistry] Duplicate object name "${t.name}":\n - Existing: "${e?.label}" (id: ${e?.id})\n - New: "${t.label}" (id: ${t.id})\nPlease use unique names for each native object.`;throw new n.DuplicateError(`object`,t.name,r)}}getByName(e){let t=this.objects.get(e);return t?cloneObjectDefinition(t):void 0}getByNameOrThrow(e){let t=this.getByName(e);if(!t){let t=`[NativeObjectRegistry] Native object "${e}" not found.\nAvailable objects: ${this.listNames().join(`, `)}`;throw new n.NotFoundError(`Native object`,e,n.SchemaErrorCode.OBJECT_NOT_FOUND,t)}return t}getAll(){return Array.from(this.objects.values(),cloneObjectDefinition)}listNames(){return Array.from(this.objects.keys())}has(e){return this.objects.has(e)}get size(){return this.objects.size}clear(){this.objects.clear()}summary(){let e=this.getAll();return[`[NativeObjectRegistry] ${this.size} native object(s) registered:`,...e.map(e=>` - ${e.name}: "${e.label}" (${e.attributes.length} attributes)`)].join(`
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./config-CQj1KDVm.js"),t=require("./view-config.schema-CLY7xK9f.js"),n=require("./exceptions.js"),r=require("./text-A9AJ1wUO.js"),i=require("./core-397tQy5q.js"),a=require("./validation/primitives/number.js"),o=require("./validation/primitives/checkbox.js"),s=require("./validation/primitives/date.js"),c=require("./utils-gY3d9Dwp.js"),l=require("./empty-CRCKZcwK.js"),u=require("./phone-BXTenBvF.js"),d=require("./object-xwmmQZ8z.js");let f=require("zod"),p=require("@stndrds/constants"),m=require("libphonenumber-js");const h=[`fyi`,`task`,`question`,`handoff`,`system`],g=[`low`,`normal`,`high`,`urgent`],_=[`public`,`internal`,`sensitive`],v=[`unread`,`read`,`archived`,`snoozed`],y=[`none`,`pending`,`processing`,`completed`,`dismissed`,`expired`,`failed`],b=`agent.session.waiting_human`,x=`agent.task.assigned`,S=`agent.question.requested`,ee=[b,x,S],C=[`name`,`type`],te=[`required`,`hidden`,`archived`,`deprecated`,`defaultValue`,`config`,`order`,`unique`],ne=[`label`,`description`,`placeholder`,`icon`],re=[`record`,`object`,`attribute`,`view`,`user`,`role`,`settings`,`file`,`agent`,`schema_source`,`tenant_invitation`,`api_key`],ie=`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(`,`);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 n.SchemaError(`parked state without parkedOn`,n.SchemaErrorCode.INVARIANT_VIOLATION);return e.parkedOn===`agents`?`waiting_agents`:`waiting_human`;case`terminal`:if(e.outcome===void 0)throw new n.SchemaError(`terminal state without outcome`,n.SchemaErrorCode.INVARIANT_VIOLATION);return e.outcome}}function legacyStatusToSessionState(e){switch(e){case`active`:return{phase:`running`};case`idle`:return{phase:`queued`};case`waiting_human`:return{phase:`parked`,parkedOn:`human`,humanRequestIds:[]};case`waiting_agents`:return{phase:`parked`,parkedOn:`agents`};default:return{phase:`terminal`,outcome:e}}}const ae=[`completed`,`failed`,`cancelled`,`timeout`,`expired`];function isTerminalSessionStatus(e){return ae.includes(e)}const oe=[`idle`,`completed`,`waiting_human`,`waiting_agents`,`cancelled`,`failed`,`timeout`];function isClaimableSessionStatus(e){return oe.includes(e)}const se=Object.freeze({mutation:`ask`,destructive:`ask`,outward:`ask`}),ce=[`active`,`completed`,`abandoned`],le=[`openai`,`anthropic`,`google`,`spacexai`,`deepseek`,`moonshotai`,`alibaba`,`mistral`,`minimax`,`meta`,`zai`],ue=[`standard`,`fast`],de=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`],fe=[`conversation`,`writing`,`coding`,`analysis`,`extraction`],pe=[`light`,`standard`,`heavy`],me=[`manual`,`auto`],he={interactive:{inputPerMillionUsd:5,outputPerMillionUsd:25},delegated:{inputPerMillionUsd:2,outputPerMillionUsd:12}},ge=[`model`,`speed`,`reasoning`,`imageModel`,`routing`];function isRoutineActorMetadata(e){return e?.kind===`routine`}const _e=[`octopus`,`clover`,`flower`,`triangle`,`square`,`blob`,`circle`,`drop`,`hexagon`,`pill`,`pebble`,`puddle`],ve=[`relaxed`,`neutral`];function agentDisplayName(e){return e.label?.trim()||e.name}const ye=[`approval-requested`,`approval-responded`,`approval-dispatched`],be=[`streaming`,`running`,`pending`,...ye];function isOpenToolPartState(e){return be.includes(e)}function isToolApprovalState(e){return ye.includes(e)}const xe=[`CREDITS_EXHAUSTED`];function isSystemPartCode(e){return typeof e==`string`&&xe.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 Se=`agent-notification`;function isAgentNotificationMetadata(e){return e?.kind===Se}const Ce=`agent-message`;function isAgentMessageMetadata(e){return e?.kind===Ce}const we=[`pending`,`in_progress`,`completed`,`blocked`],Te=`__stndrdsNativeUiPartIds`;function invalidNativePartIds(){throw new n.ValidationError(`Native agent UI part IDs metadata is invalid`,[])}function isPlainRecord$1(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function nativeAgentUIPartIdMetadataKey(e,t){if(e.type===`text`||e.type===`reasoning`)return`${e.type}:${t}`;if(e.type===`tool`)return`tool:${e.toolCallId}`}function parseNativeAgentUIPartIdsMetadata(e){let t=e.metadata?.[Te];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 Ee={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2},De=`/v1/device-worker/channel`,Oe={initialMs:1e3,maxMs:3e4};function deviceChannelUrl(e){let t=new URL(e);return`${t.protocol===`https:`?`wss:`:`ws:`}//${t.host}${De}`}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,Oe)}const ke=[`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`];var DeviceChannelProtocolError=class extends n.SchemaError{constructor(e){super(e,n.SchemaErrorCode.DEVICE_CHANNEL_PROTOCOL),this._tag=`DeviceChannelProtocolError`,this.name=`DeviceChannelProtocolError`}};const w={id:f.z.uuid(),leaseToken:f.z.string().min(1)},Ae=f.z.record(f.z.string(),f.z.unknown());function defineDeviceChannelFrames(e){return{worker:f.z.discriminatedUnion(`type`,[f.z.strictObject({type:f.z.literal(`authenticate`),credential:f.z.string().regex(/^(Device|Bearer) \S+$/),protocol:f.z.number().int().positive().optional()}),f.z.strictObject({type:f.z.literal(`running`),...w}),f.z.strictObject({type:f.z.literal(`heartbeat`),...w}),f.z.strictObject({type:f.z.literal(`output`),...w,stdout:f.z.string().optional(),stderr:f.z.string().optional()}),f.z.strictObject({type:f.z.literal(`complete`),...w,result:f.z.strictObject({stdout:f.z.string().optional(),stderr:f.z.string().optional(),exitCode:f.z.number().int(),success:f.z.boolean(),errorCode:f.z.enum(ke).optional(),result:e.result.optional()})}),f.z.strictObject({type:f.z.literal(`pong`)})]),server:f.z.discriminatedUnion(`type`,[f.z.strictObject({type:f.z.literal(`ready`),device:f.z.strictObject({id:f.z.string(),name:f.z.string(),capability:f.z.enum([`shell`,`browser`])}),protocol:f.z.number().int().positive().optional()}),f.z.strictObject({type:f.z.literal(`command`),...w,kind:f.z.enum([`shell`,`browser`]),intent:f.z.string(),timeoutMs:f.z.number().int(),command:f.z.string().optional(),cwd:f.z.string().nullable().optional(),action:e.action.optional()}),f.z.strictObject({type:f.z.literal(`cancel`),id:f.z.uuid(),reason:f.z.enum([`cancelled`,`timed_out`,`revoked`])}),f.z.strictObject({type:f.z.literal(`reauthenticate`)}),f.z.strictObject({type:f.z.literal(`revoked`)}),f.z.strictObject({type:f.z.literal(`ping`)})])}}const je=defineDeviceChannelFrames({action:Ae,result:Ae}),Me=je.worker,Ne=je.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(Me,e)}function parseServerFrame(e){return parseDeviceChannelFrame(Ne,e)}const Pe=[`web`,`presentation`,`document`,`spreadsheet`,`image`,`code`,`other`],Fe=[`ephemeral`,`conversation`,`persistent`],Ie=[`source`,`preview`,`entrypoint`,`asset`];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 Le=[`relation`,`multiRelation`,`formula`,`rollup`,`document`,`richtext`,`user`];function isFormSlotFieldRef(e){return e.type===`slot`}function isFormFreeFieldRef(e){return e.type===`free`}function resolveFieldRequired(e){return e.fieldRequired===void 0?e.slotMode===`create`&&e.attributeRequired===!0:e.fieldRequired}function getSlotFieldTargets(e){return e.additionalSlotIds?.length?[e.slotId,...e.additionalSlotIds]:[e.slotId]}function formFieldKey(e){return isFormSlotFieldRef(e)?`${e.slotId}.${e.attribute}`:`free.${e.attribute.name}`}function formFieldFlatKey(e){return isFormSlotFieldRef(e)?e.attribute:e.attribute.name}function readFormFieldValue(e,t){return e[formFieldKey(t)]??e[formFieldFlatKey(t)]}function isFormFieldsRow(e){return e.type===`fields`}function isFormHeadingRow(e){return e.type===`heading`}function isFormSeparatorRow(e){return e.type===`separator`}function isFormTextRow(e){return e.type===`text`}var NoopGeocodingAdapter=class{async autocomplete(){return await Promise.resolve([])}async geocode(){return await Promise.resolve(null)}};const Re=[`reader`,`editor`],ze=[`manual`,`meeting_attendee`];function parseRecordAccessRole(e){if(typeof e==`string`&&Re.includes(e))return e;let t=`role must be one of: ${Re.join(`, `)}`;throw new n.ValidationError(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 Be=`Notetaker`,Ve={meetingRecordingPolicy:`none`,meetingBotDisplayName:Be},He=[`active`,`suspended`],Ue=[`architect`,`manual`,`auto`];function schemaGroupKey(e){return`${e.kind}:${e.id}`}function refuse$2(e,t){throw new n.ValidationError(t,[{path:[e],message:t}])}function parseSchemaGroupPresentation(t){let n=t??{},r={};if(n.label!==void 0){let t=n.label;if(t===null)r.label=null;else if(typeof t!=`string`)refuse$2(`label`,`Label must be a string`);else{let n=t.trim();n.length===0&&refuse$2(`label`,`Label must not be empty`),n.length>e.G.labelLength&&refuse$2(`label`,`Label is too long (max ${e.G.labelLength} characters)`),r.label=n}}if(n.icon!==void 0){let t=n.icon;if(t===null)r.icon=null;else{let n=e.W.safeParse(t);n.success||refuse$2(`icon`,`Invalid icon name`),r.icon=n.data}}return r}const We=[`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 Ge=[`none`,`estimated`,`exact`];function parseCountMode(e){if(typeof e==`string`&&Ge.includes(e))return e;throw new n.ValidationError(`countMode must be one of: ${Ge.join(`, `)} (received: ${String(e)})`,[])}function parseOptionalCountMode(e){return e===void 0?void 0:parseCountMode(e)}const Ke=[`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 qe=[`B`,`KB`,`MB`,`GB`,`TB`];function formatByteSize(e){let{value:t,unitIndex:n}=computeByteMagnitude(e);return`${t} ${qe[n]}`}const Je={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 Ye=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(!Ye.includes(e.type))throw Error(`Property type "${e.type}" is not supported in .qualifyWith()`);t.push(e)}return{definitions:t}}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 Xe=/\\([!-/:-@[-`{-~])/g,Ze=57344;function markdownToPlainText(e){if(e.length===0)return``;let t=[];return e.replace(Xe,(e,n)=>(t.push(n),String.fromCharCode(Ze+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)-Ze]??e)}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(t){if(e.V(t)){let e=formatDate(t.start);return t.end?`${e} → ${formatDate(t.end)}`:e}if(t instanceof Date)return t.toISOString().split(`T`)[0];if(typeof t==`string`){let e=new Date(t);if(!Number.isNaN(e.getTime()))return e.toISOString().split(`T`)[0]}return String(t)}function formatPhone(e){if(typeof e!=`object`||!e)return String(e);let t=e;return`phoneNumber`in t?t.phoneNumber?t.countryCode?u.n(t):t.phoneNumber:``:String(e)}function formatLocationValue(e,t=`full`){if(typeof e!=`object`||!e)return``;let n=e,r=[];switch(t){case`country`:n.country&&r.push((0,p.getCountryDisplayNameByIso3)(n.country));break;case`state`:n.state&&r.push(n.state),n.country&&r.push((0,p.getCountryDisplayNameByIso3)(n.country));break;case`city`:n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push((0,p.getCountryDisplayNameByIso3)(n.country));break;case`coordinates`:n.latitude!==void 0&&n.longitude!==void 0&&r.push(`${n.latitude}, ${n.longitude}`);break;case`address`:n.address&&r.push(n.address),n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push((0,p.getCountryDisplayNameByIso3)(n.country));break;default:n.address&&r.push(n.address),n.address2&&r.push(n.address2),n.city&&r.push(n.city),n.state&&r.push(n.state),n.postalCode&&r.push(n.postalCode),n.country&&r.push((0,p.getCountryDisplayNameByIso3)(n.country))}return r.join(`, `)}function formatLocation(e,t){return typeof e!=`object`||!e?String(e):formatLocationValue(e,t.granularity??`full`)||`—`}function formatSelect(e,t){return typeof e==`string`?t.options?.find(t=>t.value===e)?.label??String(e):String(e)}function formatMultiselect(e,t){return Array.isArray(e)?t.options?e.map(e=>t.options.find(t=>t.value===e)?.label).filter(Boolean).join(`, `):e.join(`, `):String(e)}function formatAttributeValue(e,t){if(l.t(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 Qe=[`UPPER`,`LOWER`,`capitalize`,`trim`],$e=[`prefix`,`suffix`,`wrap`,`default`],T=[...Qe,...$e],E=f.z.string().min(1,`labelExpression cannot be empty`).refine(e=>isLabelExpression(e),{message:`labelExpression must contain at least one {{ attribute }} interpolation`}).refine(e=>!/\{\{\s*\}\}/.test(e),{message:`labelExpression contains empty {{ }} interpolation`}).refine(e=>{let t=/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g,n;for(;(n=t.exec(e))!==null;){let e=n[1];if(!T.includes(e))return!1}return!0},{message:`Invalid pipe name. Valid pipes: ${T.join(`, `)}`});function validateLabelExpression(e){let t=E.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 et=`(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=et){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 tt=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function getSingleAttributeFromExpression(e){let t=e.trim().match(tt);return t?t[1]:null}function getEditableLabelAttribute(e,n){let r=getSingleAttributeFromExpression(e);if(r===null)return null;let i=n.find(e=>e.name===r);return!i||i.type!==`text`||t.rt(i).authoring.readOnly?null:i}const nt=/\{\{\s*props\./;function applyRelationProps(e,t,n){if(!nt.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(l.t(e))return[];if(typeof e==`string`)return[{id:e}];if(Array.isArray(e))return e.flatMap(e=>extractValueRefs(e));if(typeof e==`object`&&`id`in e){let t=e;if(typeof t.id==`string`)return[{id:t.id,props:t.props}]}return[]}function 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 rt=/\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(rt)?.[0];return t===void 0?``:[...t.toUpperCase()][0]??``}).filter(Boolean).slice(0,2).join(``);return i===``?t:i}const it=`__creatorRootActorId`;function getRecordCreatorPrincipalId(e){let t=e.metadata?.[it];return typeof t==`string`&&t.length>0?t:e.createdBy}const at=[{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`]}]}]}],ot=`none`,st=`custom`,D={actions:[`read`,`create`,`update`,`delete`],purge:`manage`,levels:[{id:`read`,add:[`read`]},{id:`edit`,add:[`create`,`update`]},{id:`full`,add:[`delete`]}]},O=at.flatMap(e=>e.capabilities),ct=O.flatMap(e=>e.resources),lt=new Map(O.flatMap(e=>e.resources.map(t=>[t,e])));function isCatalogResource(e){return lt.has(e)}function capabilityForResource(e){let t=lt.get(e);if(!t)throw new n.SchemaError(`Unknown catalog resource "${e}"`,n.SchemaErrorCode.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 ot;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 st}const k=[`read`,`create`,`update`,`delete`,`manage`],ut=f.z.object({scope:f.z.enum([`object`,`system`]),target:f.z.string().min(1),actions:f.z.array(f.z.enum(k))}).strict();function findGrantIssues(e,t){let n=[],r=new Map;for(let i of e){let e=ut.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===`*`?[...D.actions,D.purge]:D.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===`*`?[...k]: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 dt=`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 O){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:st}let i=n[`*`]??[],a=levelWithin(D,i),o=[];for(let[e,t]of Object.entries(n)){if(e===`*`)continue;let n=levelWithin(D,[...i,...t]);n!==a&&o.push({objectName:e,level:n})}return{capabilities:r,defaultObjectLevel:a,exceptions:o,purge:includesAction(i,D.purge)}}function readRoleLevels(e){return readAccessLevels(grantsToPermissions(e))}function summarizeGroup(e,t){let r=at.find(e=>e.id===t);if(!r)throw new n.SchemaError(`Unknown permission group "${t}"`,n.SchemaErrorCode.INVARIANT_VIOLATION);let{capabilities:i}=readRoleLevels(e),a=new Set(r.capabilities.map(e=>i[e.id]??`none`)),[o]=a;return a.size===1&&o!==void 0?o:dt}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(D,storedActions(t,`object`,`*`)):levelActions(D,e.defaultObjectLevel)}function grantsFromLevels(e,t){let n=[];for(let r of O){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,D.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(D,storedActions(t,`object`,i)):levelActions(D,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=O.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(D,t)?withLevels(e,e=>({...e,defaultObjectLevel:t})):e}function exceptionLevels(e){let t=defaultObjectActions(readRoleLevels(e),e);return D.levels.map(e=>e.id).filter(e=>!isSubset(levelActions(D,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(D,n))return!1;let i=levelActions(D,n),a=t.objectName===`*`&&r?[...i,D.purge]:i;return uncoveredGrants(e,[{scope:`object`,target:t.objectName,actions:a}]).length===0}let i=O.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:[D.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 ft=new Set([`id`,`name`,`label`,`type`,`required`,`system`,`unique`,`order`]),pt={OWNER:`owner`,MEMBER:`member`,AGENT_DEFAULT:`agent_default`},mt={owner:`Owner`,member:`Member`,agent_default:`Agent Default`},ht={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`},A=[...D.actions],gt=[...k],_t={owner:{system:[{target:`*`,actions:gt}],object:[{target:`*`,actions:gt}]},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:A},{target:`files`,actions:A},{target:`documents`,actions:A}],object:[{target:`*`,actions:A}]},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:A}]}},vt=[{role:`member`,scope:`object`,target:`*`,actions:[`manage`]}];function isDefaultRole(e){return Object.values(pt).includes(e)}const yt=[{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`}],bt=new Map(yt.map(e=>[e.id,e]));function isWorkstationHarnessId(e){return bt.has(e)}function findWorkstationHarness(e){return bt.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 xt={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2},timeoutMs:3e5};var AgentBuilder=class{constructor(e){if(!e.name||e.name.trim().length===0)throw new n.ValidationError(`Agent name is required`,[]);this.bp={name:e.name,system:!0,visibility:`workspace`,triggers:[]}}description(e){return this.bp.description=e,this}label(e){return this.bp.label=e,this}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??xt,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={...se,...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 n.ValidationError(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new n.ValidationError(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility===`private`)throw new n.ValidationError(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return e.N(this.bp.triggers,e=>e.name,e=>new n.ValidationError(`Agent "${this.bp.name}": duplicate trigger name "${e}"`,[])),{...this.bp,visibility:this.bp.visibility??`workspace`,config:this.bp.config??xt,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};function agent(e){return new AgentBuilder(e)}const St=`@stndrds/schema`;function createStandardSchemaProps(e){return{version:1,vendor:St,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(d.d(this.build()))}constructor(t,n,r){e.P(n),e.I(r),this.attr={name:n,label:r,type:t,required:!1,system:!0}}setRequired(e){this.attr.required=e}asRequiredState(){return this}asPhantomState(){return this}runtime(){return this.attr.system=!1,this}hidden(){return this.attr.hidden=!0,this}placeholder(e){return this.attr.placeholder=e,this}description(e){return this.attr.description=e,this}icon(t){return e.F(t,`attribute "${this.attr.name}"`),this.attr.icon=t,this}order(e){return this.attr.order=e,this}defaultValue(e){return(`defaultValue`in this.attr||![`formula`,`rollup`].includes(this.attr.type))&&(this.attr.defaultValue=e),this}metadata(e){return this.attr.metadata=e,this}build(){return this.attr}},TextAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`text`,e,t)}minLength(e){return this.attr.minLength=e,this}maxLength(e){return this.attr.maxLength=e,this}pattern(e){return this.attr.pattern=e,this.attr.format=void 0,this}multiline(e=!0){return this.attr.multiline=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}email(){return this.attr.format=`email`,this.attr.pattern=void 0,this}url(){return this.attr.format=`url`,this.attr.pattern=void 0,this}slug(){return this.attr.format=`slug`,this.attr.pattern=void 0,this}};function text(e){return new TextAttributeBuilder(e.name,e.label)}var RichtextAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`richtext`,e,t)}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function richtext(e){return new RichtextAttributeBuilder(e.name,e.label)}var NumberAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`number`,e,t)}min(e){return this.attr.min=e,this}max(e){return this.attr.max=e,this}integer(){return this.attr.unit=`integer`,this.attr.decimals=0,this}decimal(e=2){return this.attr.unit=`decimal`,this.attr.decimals=e,this}percentage(){return this.attr.unit=`percentage`,this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function number(e){return new NumberAttributeBuilder(e.name,e.label)}var CheckboxAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`checkbox`,e,t)}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function checkbox(e){return new CheckboxAttributeBuilder(e.name,e.label)}var DateAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`date`,e,t)}format(e){return this.attr.dateFormat=e,this}minDate(e){return this.attr.minDate=e,this}maxDate(e){return this.attr.maxDate=e,this}endDate(){return this.attr.endDate=!0,this.asPhantomState()}includeTime(){return this.attr.includeTime=!0,this}timeFormat(e){return this.attr.timeFormat=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function date(e){return new DateAttributeBuilder(e.name,e.label)}var PhoneAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`phone`,e,t)}defaultCountry(e){return this.attr.defaultCountryCode=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function phone(e){return new PhoneAttributeBuilder(e.name,e.label)}var CurrencyAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`currency`,e,t)}defaultCurrency(e){return this.attr.defaultCurrency=e,this}allowedCurrencies(e){return this.attr.allowedCurrencies=e,this}allowNegative(e=!0){return this.attr.allowNegative=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function currency(e){return new CurrencyAttributeBuilder(e.name,e.label)}var StatusAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`status`,e,t)}options(t){let n=asMutableArray(t);return e.R(this.attr.name??`unknown`,n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return e.R(this.attr.name??`unknown`,n),this.attr.options.push(t),this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function status(e){return new StatusAttributeBuilder(e.name,e.label)}var SelectAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`select`,e,t)}options(t){let n=asMutableArray(t);return e.R(this.attr.name??`unknown`,n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return e.R(this.attr.name??`unknown`,n),this.attr.options.push(t),this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function select(e){return new SelectAttributeBuilder(e.name,e.label)}var MultiselectAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`multiselect`,e,t)}options(t){let n=asMutableArray(t);return e.R(this.attr.name??`unknown`,n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return e.R(this.attr.name??`unknown`,n),this.attr.options.push(t),this}renderAs(e){return this.attr.renderAs=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function multiselect(e){return new MultiselectAttributeBuilder(e.name,e.label)}var LocationAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`location`,e,t)}granularity(e){return this.attr.granularity=e,this}defaultCountry(e){return this.attr.defaultCountry=e,this}allowedCountries(e){return this.attr.allowedCountries=e,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function location(e){return new LocationAttributeBuilder(e.name,e.label)}var UserAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`user`,e,t),this.attr.types=[`user`,`agent`]}types(e){let t=[...new Set(e)];if(t.length===0)throw Error(`[AttributeBuilder] user.types must contain at least one type.`);return this.attr.types=t,this}multiple(){return this.attr.multiple=!0,this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function user(e){return new UserAttributeBuilder(e.name,e.label)}var BaseRelationAttributeBuilder=class extends BaseAttributeBuilder{to(e,t){let n={object:e,...t};return this.attr.targets?.push(n),this}toAny(){return this.attr.targets=[{object:`*`}],this}qualifyWith(...e){let t=this.attr.targets;if(!t||t.length===0)throw Error(`.qualifyWith() must be called AFTER .to(). Example: relation({ name: "companies" }).to("companies").qualifyWith(...)`);return this.attr.properties=buildPropertySchema(e),this}bilateral(e){let r=this.attr.targets;if(!r||r.length===0)throw Error(`.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })`);if(r.length>1)throw Error(`Bilateral relations are not supported for polymorphic relations (multiple .to() targets).`);if(t.$(this.attr))throw Error(`Bilateral relations are not supported for universal relations (.toAny()).`);let i=r[0]?.object;if(!i)throw new n.ValidationError(`Bilateral relation requires one target object`,[{path:[`bilateral`,`object`],message:`Bilateral relation requires one target object`}]);if(e.object&&e.object!==i){let t=`Bilateral inverse object ${e.object} must match relation target ${i}`;throw new n.ValidationError(t,[{path:[`bilateral`,`object`],message:t}])}return this.attr.bilateral={...e,object:i},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`,r=this.attr.targetAttribute??`field`;throw new n.SchemaError(`Rollup "${this.attr.name}": .using("original") only supports a "select", "status", or "multiselect" target, but .targetType("${t}") was given. To surface a plain ${t} value from a related record, use a formula instead — e.g. formula({ name: "${this.attr.name}", label: "…" }).expression("${e}.${r}").`,n.SchemaErrorCode.VALIDATION_FAILED)}return super.build()}required(){throw Error(`Rollup attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.`)}optional(){return this}};function rollup(e){return new RollupAttributeBuilder(e.name,e.label)}var DocumentAttributeBuilder=class extends BaseAttributeBuilder{constructor(e,t){super(`document`,e,t)}accepts(e){return this.attr.accepts=e,this}maxFileSize(e){return this.attr.maxFileSize=e,this}qualifyWith(...e){return this.attr.properties=buildPropertySchema(e),this}required(){return this.setRequired(!0),this.asRequiredState()}optional(){return this.setRequired(!1),this.asRequiredState()}};function document(e){return new DocumentAttributeBuilder(e.name,e.label)}function buildSlotFieldRef(e,t,n){let[r,...i]=Array.isArray(e)?e:[e];return{type:`slot`,slotId:r,additionalSlotIds:i.length>0?i:void 0,attribute:t,label:n?.label,required:n?.required,tooltip:n?.tooltip}}var FormRowBuilder=class{constructor(e,t,n){this._finalized=!1,this.stepBuilder=e,this.rowData={id:t,order:n,type:`fields`,fields:[]}}field(e,t,n){return this.rowData.fields.push(buildSlotFieldRef(e,t,n)),this}freeField(e,t){let n={type:`free`,attribute:e.build(),label:t?.label,required:t?.required,prefillExpression:t?.prefillExpression};return this.rowData.fields.push(n),this}row(e){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).row(e)}heading(e,t){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).heading(e,t)}separator(){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).separator()}text(e){return this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData).text(e)}endRow(){return this._finalized?this.stepBuilder:(this._finalized=!0,this.stepBuilder._finalizeRow(this.rowData))}},FormStepBuilder=class{constructor(e,t,n){this.rowOrder=0,this.formBuilder=e,this.stepData={id:t,label:n,rows:[]}}description(e){return this.stepData.description=e,this}field(e,t,n){this.rowOrder++;let r=`row-${this.stepData.id}-${this.rowOrder}`,i=buildSlotFieldRef(e,t,n),a={id:r,order:this.rowOrder,type:`fields`,fields:[i]};return this.stepData.rows.push(a),this}freeField(e,t){this.rowOrder++;let n=`row-${this.stepData.id}-${this.rowOrder}`,r={type:`free`,attribute:e.build(),label:t?.label,required:t?.required,prefillExpression:t?.prefillExpression},i={id:n,order:this.rowOrder,type:`fields`,fields:[r]};return this.stepData.rows.push(i),this}row(e){return this.rowOrder++,new FormRowBuilder(this,e,this.rowOrder)}heading(e,t){this.rowOrder++;let n={id:`heading-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:`heading`,content:e,level:t};return this.stepData.rows.push(n),this}separator(){this.rowOrder++;let e={id:`sep-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:`separator`};return this.stepData.rows.push(e),this}text(e){this.rowOrder++;let t={id:`text-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:`text`,content:e};return this.stepData.rows.push(t),this}step(e,t){return this.formBuilder._finalizeStep(this.stepData).step(e,t)}build(){return this.formBuilder._finalizeStep(this.stepData).build()}_finalizeRow(e){return e.fields.length>0&&this.stepData.rows.push(e),this}_getData(){return this.stepData}},FormBuilder=class{constructor(e,t){this.data={slots:[],steps:[],status:`draft`,version:1},this.validateName(e),this.data.name=e,this.data.label=t}description(e){return this.data.description=e,this}icon(e){return this.data.icon=e,this}status(e){return this.data.status=e,this}metadata(e){return this.data.metadata=e,this}slot(e,t,n){if(this.data.slots.some(t=>t.id===e))throw Error(`[FormBuilder] Duplicate slot id: "${e}"`);let r={id:e,objectName:t,label:n.label,mode:n.mode??`create`,color:n.color,icon:n.icon};return this.data.slots.push(r),this}step(e,t){if(this.data.steps.some(t=>t.id===e))throw Error(`[FormBuilder] Duplicate step id: "${e}"`);return new FormStepBuilder(this,e,t)}build(){return this.validateRequiredData(),this.validateSlotReferences(),this.validateFreeFields(),this.validatePrefillExpressions(),this.data}_finalizeStep(e){return this.data.steps.push(e),this}validateName(e){let t=f.z.string().min(1,`Form name cannot be empty`).max(63,`Form name is too long (max 63 characters)`).regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,{message:`Invalid form name format. Name must be in kebab-case: 'client-onboarding', 'contact-creation'`});try{t.parse(e)}catch(e){throw e instanceof f.z.ZodError?Error(`[FormBuilder] ${e.issues[0].message}`):e}}validateRequiredData(){if(this.data.slots.length===0)throw Error(`[FormBuilder] At least one slot is required. Use .slot() to add slots.`);if(this.data.steps.length===0)throw Error(`[FormBuilder] At least one step is required. Use .step() to add steps.`)}validateSlotReferences(){let e=new Map(this.data.slots.map(e=>[e.id,e.objectName]));for(let t of this.data.steps)for(let n of t.rows)if(isFormFieldsRow(n))for(let r of n.fields){if(r.type!==`slot`)continue;let n=getSlotFieldTargets(r);for(let r of n)if(!e.has(r))throw Error(`[FormBuilder] Step "${t.id}" references unknown slot "${r}". Declare it with .slot("${r}", ...) first.`);let i=new Set(n.map(t=>e.get(t)));if(i.size>1)throw Error(`[FormBuilder] Step "${t.id}" field on attribute "${r.attribute}" targets slots of different objects (${[...i].join(`, `)}). A multi-slot field must target slots of the same object.`)}}validatePrefillExpressions(){let e=[...T,`join`];for(let t of this.data.steps)for(let n of t.rows)if(isFormFieldsRow(n))for(let r of n.fields){if(!isFormFreeFieldRef(r)||!r.prefillExpression)continue;let n=r.prefillExpression,i=`prefillExpression on free field "${r.attribute.name}" in step "${t.id}"`;if(!isLabelExpression(n))throw Error(`[FormBuilder] ${i} must contain at least one {{ attribute }} interpolation.`);if(/\{\{\s*\}\}/.test(n))throw Error(`[FormBuilder] ${i} contains empty {{ }} interpolation.`);for(let t of n.matchAll(/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g)){let n=t[1];if(!e.includes(n))throw Error(`[FormBuilder] ${i} uses invalid pipe "${n}". Valid pipes: ${e.join(`, `)}`)}}}validateFreeFields(){let e=new Set(Le);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: ${Le.join(`, `)}`)}}}};function form(e,t){return new FormBuilder(e,t)}function validateObjectExpressions(e){let{name:t,labelExpression:r,embeddingExpression:i}=e;if(!r)throw new n.SchemaError(`Object "${t}" must have a labelExpression. The labelExpression defines how records are displayed in lists and relations (e.g. "{{ name }}").`,n.SchemaErrorCode.VALIDATION_FAILED);let a=E.safeParse(r);if(!a.success){let e=a.error.issues[0]?.message??`Invalid labelExpression`;throw new n.SchemaError(`Invalid labelExpression for "${t}": ${e}`,n.SchemaErrorCode.VALIDATION_FAILED)}if(i!==void 0){let e=E.safeParse(i);if(!e.success){let r=e.error.issues[0]?.message??`Invalid embeddingExpression`;throw new n.SchemaError(`Invalid embeddingExpression for "${t}": ${r}`,n.SchemaErrorCode.VALIDATION_FAILED)}}}var ObjectBuilder=class{get"~standard"(){return createStandardSchemaProps(d.u(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(t){let r=t.map(e=>`build`in e&&typeof e.build==`function`?e.build():e);e.N([...this.obj.attributes,...r],e=>e.name,e=>new n.DuplicateError(`attribute`,e,`Object "${this.obj.name}": duplicate attribute name "${e}"`)),this.obj.attributes.push(...r)}metadata(e){return this.obj.metadata={...this.obj.metadata,...e},this}order(e){return this.obj.metadata={...this.obj.metadata,order:e},this}hidden(){return this.obj.metadata={...this.obj.metadata,hidden:!0},this}labelExpression(e){return this._labelExpression=e,this}embeddingExpression(e){return this._embeddingExpression=e,this}documentLayout(e){if(e.presets)for(let t of e.presets)validatePresetStructure(t.id,t.structure,1);return this.obj.documentLayout=e,this}build(){if(!this.obj.name)throw new n.ValidationError(`[ObjectBuilder] Missing required field: name`,[{path:[`name`],message:`name is required`}]);if(!this.obj.label)throw new n.ValidationError(`[ObjectBuilder] Missing required field: label`,[{path:[`label`],message:`label is required`}]);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(t){t!==void 0&&e.L(t)}};function object(t){if(e.$(t.name))throw new n.ReservedObjectNameError(t.name,`builder`);return new ObjectBuilder(t)}function validatePresetStructure(e,t,r){let fail=(t,r)=>{throw new n.ValidationError(t,[{path:[`documentLayout`,`presets`,e],message:r}])};r>5&&fail(`Preset structure exceeds max depth of 5`,`Preset structure too deep`);let i=new Set;for(let n of t){let t=n.title.trim();t.length===0&&fail(`Folder preset node title is required`,`Empty folder title`),t.includes(`/`)&&fail(`Folder preset node title cannot contain /`,`Folder title contains /: "${t}"`),i.has(t)&&fail(`Folder preset sibling titles must be unique`,`Duplicate folder title: "${t}"`),i.add(t),n.children&&n.children.length>0&&validatePresetStructure(e,n.children,r+1)}}function cloneBuilderValue(e,t){try{return structuredClone(e)}catch{let e=`Builder configuration must contain cloneable data`;throw new n.ValidationError(e,[{path:t,message:e}])}}function requireBuilderName(e,t){if(typeof e!=`string`||e.trim().length===0)throw new n.ValidationError(`Name must not be blank`,[{path:t,message:`Name must not be blank`}])}function validateContentConfiguration(e,r){if(typeof e!=`object`||!e||Array.isArray(e))throw new n.ValidationError(`Invalid content configuration`,[{path:r,message:`Expected content configuration`}]);for(let t of[`name`,`label`,`placement`])if(Object.hasOwn(e,t)){let e=`Independent content configuration cannot define ${t}`;throw new n.ValidationError(e,[{path:[...r,t],message:e}])}let i=t.l.safeParse({...e,name:`content`,placement:`main`});if(!i.success)throw n.ValidationError.fromZodErrors(i.error.issues.map(e=>({path:[...r,...e.path.map(String)],message:e.message})));i.data.type===`form`&&i.data.groups.forEach((e,t)=>requireBuilderName(e.name,[...r,`groups`,String(t),`name`]));let{name:a,label:o,placement:s,...c}=i.data;return cloneBuilderValue(c,r)}function validateLiteralContent(e,t){return validateContentConfiguration(e,t),cloneBuilderValue(e,t)}function collectionSourceAddress(e){return e.relation===void 0?{kind:`object`,object:e.object}:e.object===void 0?{kind:`related`,relation:e.relation}:{kind:`relatedFrom`,object:e.object,relation:e.relation}}function collectionSourceAddressOf(e){if(!e||typeof e!=`object`)return;let t=`object`in e?e.object:void 0,n=`relation`in e?e.relation:void 0;if(typeof t==`string`&&typeof n==`string`)return{kind:`relatedFrom`,object:t,relation:n};if(typeof t==`string`&&n===void 0)return{kind:`object`,object:t};if(typeof n==`string`&&t===void 0)return{kind:`related`,relation:n}}function 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,r){if(t!==`record`){let t=`Content "${e}" requires record context. In a collection view only a collection that lists a whole object, or a custom content that does not require a record, is allowed.`;throw new n.ValidationError(t,[{path:r,message:t}])}}function resolveContentNavigation(e){let t=e.openMode??`page`;return{openMode:t,createMode:e.createMode??t}}function resolveCollectionActions(e,t){return[...new Set(t)].filter(t=>e.actions===void 0||e.actions.includes(t))}var Ct=class ViewBuilder{constructor(e,t=[]){this.kind=`view`,this.data=cloneBuilderValue(e,[`views`,`0`]),this.extensions=t.map(e=>e&&{...e})}for(e){return new ViewBuilder({...this.data,object:e},this.extensions)}default(){return new ViewBuilder({...this.data,default:!0},this.extensions)}description(e){return new ViewBuilder({...this.data,description:e},this.extensions)}icon(e){return new ViewBuilder({...this.data,icon:e},this.extensions)}place(e,t,r,i){let a=[`views`,`0`,`contents`,String(this.data.contents.length)],o,s;try{typeof r==`object`&&r&&`build`in r&&typeof r.build==`function`?(o=validateContentConfiguration(r.build(),a),s=r.extension):o=validateContentConfiguration(r,a)}catch(e){throw e instanceof n.ValidationError?new n.ValidationError(e.message,e.errors.map(e=>({...e,path:e.path[0]===`content`?[...a,...e.path.slice(1)]:e.path}))):e}let c={...o,name:e,label:t,placement:i},l=[...this.data.contents,c];return new ViewBuilder({...this.data,contents:l},[...this.extensions,s])}tab(e,t,n){return this.place(e,t,n,`main`)}aside(e,t,n){return this.place(e,t,n,`aside`)}build(){let e=[`views`,`0`];requireBuilderName(this.data.name,[...e,`name`]),requireBuilderName(this.data.object,[...e,`object`]);let r=t.r.safeParse(this.data);if(!r.success)throw n.ValidationError.fromZodErrors(r.error.issues.map(t=>({path:[...e,...t.path.map(String)],message:t.message})));return this.data.contents.forEach((t,n)=>{let r=[...e,`contents`,String(n)];requireBuilderName(t.name,[...r,`name`]),t.type===`form`&&t.groups.forEach((e,t)=>requireBuilderName(e.name,[...r,`groups`,String(t),`name`])),(t.type===`custom`?this.extensions[n]?.requiresRecord:t.type!==`collection`||collectionSourceAddress(t.source).kind!==`object`)&&requireRecordContentContext(t.name,this.data.context,r)}),{kind:`view`,definition:cloneBuilderValue(this.data,e)}}};function detailView(e,t){return new Ct({name:e,label:t,object:void 0,context:`record`,contents:[]})}function listView(e,t){return new Ct({name:e,label:t,object:void 0,context:`collection`,contents:[]})}function relationProperty(e){return requireBuilderName(e,[`relationProperty`]),{relationProperty:e}}var j=class ContentBuilder{constructor(e,t){this.data=cloneBuilderValue(e,[`content`]),this.extension=t===void 0?void 0:Object.freeze({name:t.name,requiresRecord:t.requiresRecord,parameters:t.parameters})}set(e){return new ContentBuilder({...this.data,...e},this.extension)}icon(e){return this.set({icon:e})}object(e){return this.data.type===`forms`?this.set({objectName:e}):this.set({source:{object:e}})}related(e){return this.set({source:{relation:e}})}relatedFrom(e,t){return this.set({source:{object:e,relation:t}})}layout(e){let{layout:t,groupByAttribute:n,columnSizing:r,kanbanColumnOrder:i,kanbanColumnVisibility:a,kanbanPinnedColumns:o,...s}={...this.data,layout:void 0,groupByAttribute:void 0,columnSizing:void 0,kanbanColumnOrder:void 0,kanbanColumnVisibility:void 0,kanbanPinnedColumns:void 0};return new ContentBuilder({...s,...e},this.extension)}table(){return this.layout({layout:`table`})}list(){return this.layout({layout:`list`})}kanban(e){return this.layout({layout:`kanban`,groupByAttribute:e})}columns(...e){return this.set({columns:e})}filter(e){return this.set({filters:e})}sort(e,t=`asc`){let n=[...`sorts`in this.data&&Array.isArray(this.data.sorts)?this.data.sorts:[],{attribute:e,direction:t}];return this.set({sorts:n})}actions(...e){return this.set({actions:e})}openMode(e){return this.set({openMode:e})}createMode(e){return this.set({createMode:e})}visibility(e){return this.set({visibility:e})}descriptionAttribute(e){return this.set({descriptionAttribute:e})}displayAttributes(...e){return this.set({displayAttributes:e})}columnSizing(e){return this.set({columnSizing:e})}kanbanColumnOrder(...e){return this.set({kanbanColumnOrder:e})}kanbanColumnVisibility(e){return this.set({kanbanColumnVisibility:e})}kanbanPinnedColumns(...e){return this.set({kanbanPinnedColumns:e})}formColumns(e){return this.set({formColumns:e})}density(e){return this.set({density:e})}titleAttribute(e){return this.set({titleAttribute:e})}allowUpload(e){return this.set({allowUpload:e})}allowRemove(e){return this.set({allowRemove:e})}hideAttachments(e){return this.set({hideAttachments:e})}relations(...e){return this.set({relations:e})}build(){let e=validateLiteralContent(this.data,[`content`]);if(this.extension&&e.type===`custom`){let t=this.extension.parameters.safeParse(cloneBuilderValue(e.parameters??{},[`content`,`parameters`]));if(!t.success)throw n.ValidationError.fromZodErrors(t.error.issues.map(e=>({path:[`content`,`parameters`,...e.path.map(String)],message:e.message})))}return e}},wt=class GroupBuilder{constructor(e,t,n,r={}){this.data=cloneBuilderValue({name:e,label:t,fields:n,...r},[`group`])}field(e,t){let{name:n,label:r,fields:i,...a}=this.data;return new GroupBuilder(n,r,[...i,{attribute:e,...t}],a)}fields(...e){let{name:t,label:n,fields:r,...i}=this.data;return new GroupBuilder(t,n,[...r,...e.map(e=>({attribute:e}))],i)}description(e){return new GroupBuilder(this.data.name,this.data.label,this.data.fields,{...this.presentation(),description:e})}collapsible(e=!1){return new GroupBuilder(this.data.name,this.data.label,this.data.fields,{...this.presentation(),collapsible:!0,collapsed:e})}presentation(){let{name:e,label:t,fields:n,...r}=this.data;return r}build(){requireBuilderName(this.data.name,[`group`,`name`]);try{validateLiteralContent({type:`form`,groups:[this.data]},[`group`])}catch(e){throw e instanceof n.ValidationError?new n.ValidationError(e.message,e.errors.map(e=>({...e,path:e.path[1]===`groups`?[`group`,...e.path.slice(3)]:e.path}))):e}return cloneBuilderValue(this.data,[`group`])}};function group(e,t){return new wt(e,t,[])}function collection(){return new j({type:`collection`})}function form$1(...e){return new j({type:`form`,groups:e.map(e=>`build`in e?e.build():e)})}function activity(){return new j({type:`activity`})}function richtext$1(e){return new j({type:`richtext`,attribute:e})}function documents(){return new j({type:`documents`})}function forms(){return new j({type:`forms`})}function emails(...e){return new j({type:`emails`,emailAttributes:e})}function meetings(...e){return new j({type:`meetings`,emailAttributes:e})}function custom(e,t){if(typeof e!=`object`||!e||typeof e.name!=`string`)throw new n.ValidationError(`Expected registered extension declaration`,[{path:[`content`,`extension`],message:`Expected registered extension declaration`}]);let r=validateContentConfiguration({type:`custom`,extension:e.name,parameters:t},[`content`]);if(r.type!==`custom`)throw new n.ValidationError(`Expected custom content`,[]);let i=new j({...r,extension:e.name},e);return i.build(),i}const M={collection,form:form$1,activity,richtext:richtext$1,documents,forms,emails,meetings,custom};function validateFlagName(e){if(!/^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$/.test(e))throw Error(`Invalid flag name "${e}". Flag names must be kebab-case (e.g., "architect-mode", "ai-features").`)}var BaseFlagBuilder=class{constructor(e,t,n){validateFlagName(e),this.flag={name:e,valueType:t,defaultValue:n,allowedLevels:[`global`,`tenant`,`user`]}}label(e){return this.flag.label=e,this}description(e){return this.flag.description=e,this}category(e){return this.flag.category=e,this}system(){return this.flag.system=!0,this}tenantScoped(){return this.flag.allowedLevels=[`global`,`tenant`],this}globalOnly(){return this.flag.allowedLevels=[`global`],this}allowedLevels(e){return this.flag.allowedLevels=[...e],this}build(){if(!this.flag.label?.trim())throw Error(`Flag "${this.flag.name}" must have a label. Use .label("Human-readable label").`);return{...this.flag,allowedLevels:[...this.flag.allowedLevels||[]]}}},BooleanFlagBuilder=class extends BaseFlagBuilder{constructor(e){super(e,`boolean`,!1)}defaultValue(e){return this.flag.defaultValue=e,this}enabledByDefault(){return this.flag.defaultValue=!0,this}},StringFlagBuilder=class extends BaseFlagBuilder{constructor(e){super(e,`string`,``)}defaultValue(e){return this.flag.defaultValue=e,this}},NumberFlagBuilder=class extends BaseFlagBuilder{constructor(e){super(e,`number`,0)}defaultValue(e){return this.flag.defaultValue=e,this}},JsonFlagBuilder=class extends BaseFlagBuilder{constructor(e,t){super(e,`json`,t)}defaultValue(e){return this.flag.defaultValue=e,this}};function booleanFlag(e){return new BooleanFlagBuilder(e)}function stringFlag(e){return new StringFlagBuilder(e)}function numberFlag(e){return new NumberFlagBuilder(e)}function jsonFlag(e,t){return new JsonFlagBuilder(e,t)}function duplicateFlagError(e){return new n.DuplicateError(`feature flag`,e,`Flag "${e}" is already registered. Each flag name must be unique.`)}function cloneFlagDefinition(e){return{...e,allowedLevels:[...e.allowedLevels]}}var FlagRegistry=class{constructor(){this.flags=new Map}register(e){if(this.flags.has(e.name))throw duplicateFlagError(e.name);this.flags.set(e.name,cloneFlagDefinition(e))}registerAll(e){let t=new Set;for(let n of e){if(this.flags.has(n.name)||t.has(n.name))throw duplicateFlagError(n.name);t.add(n.name)}for(let t of e)this.register(t)}get(e){let t=this.flags.get(e);return t?cloneFlagDefinition(t):void 0}getOrThrow(e){let t=this.get(e);if(!t)throw new n.NotFoundError(`Feature flag`,e,void 0,`Flag "${e}" is not registered. Available flags: ${this.listNames().join(`, `)}`);return t}has(e){return this.flags.has(e)}list(){return Array.from(this.flags.values(),cloneFlagDefinition)}listNames(){return Array.from(this.flags.keys())}unregister(e){return this.flags.delete(e)}clear(){this.flags.clear()}get size(){return this.flags.size}};const Tt=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 Et=Symbol(`stndrds.native-object`);function markNativeDefinition(e){return Object.defineProperty(e,Et,{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[Et]===!0}function cloneObjectDefinition(e){let t=structuredClone(e);return isNativeDefinition(e)?markNativeDefinition(t):t}var NativeObjectRegistryClass=class{constructor(){this.objects=new Map}register(e){let t=(Array.isArray(e)?e:[e]).map(e=>`build`in e&&typeof e.build==`function`?e.build():e),r=new Set;for(let e of t){if(this.validate(e),r.has(e.name))throw new n.DuplicateError(`object`,e.name,`[NativeObjectRegistry] Duplicate object name "${e.name}" within a single register() batch.`);r.add(e.name)}for(let e of t)this.objects.set(e.name,cloneObjectDefinition(e));return this}validate(t){if(!t.system){let e=`[NativeObjectRegistry] Cannot register object "${t.name}" (id: ${t.id}): missing system flag.\nNative objects must have system=true. Did you call .runtime() on the builder? Remove that call — objects are system:true by default.`;throw new n.ValidationError(e,[])}if(e.$(t.name)&&!isNativeDefinition(t))throw new n.ReservedObjectNameError(t.name,`registry`);if(this.objects.has(t.name)){let e=this.objects.get(t.name),r=`[NativeObjectRegistry] Duplicate object name "${t.name}":\n - Existing: "${e?.label}" (id: ${e?.id})\n - New: "${t.label}" (id: ${t.id})\nPlease use unique names for each native object.`;throw new n.DuplicateError(`object`,t.name,r)}}getByName(e){let t=this.objects.get(e);return t?cloneObjectDefinition(t):void 0}getByNameOrThrow(e){let t=this.getByName(e);if(!t){let t=`[NativeObjectRegistry] Native object "${e}" not found.\nAvailable objects: ${this.listNames().join(`, `)}`;throw new n.NotFoundError(`Native object`,e,n.SchemaErrorCode.OBJECT_NOT_FOUND,t)}return t}getAll(){return Array.from(this.objects.values(),cloneObjectDefinition)}listNames(){return Array.from(this.objects.keys())}has(e){return this.objects.has(e)}get size(){return this.objects.size}clear(){this.objects.clear()}summary(){let e=this.getAll();return[`[NativeObjectRegistry] ${this.size} native object(s) registered:`,...e.map(e=>` - ${e.name}: "${e.label}" (${e.attributes.length} attributes)`)].join(`
|
|
3
3
|
`)}debug(e){let t=this.summary();return e?.(t),t}};const Dt=new NativeObjectRegistryClass,Ot=new WeakSet;function markSystemView(e){return Ot.add(e.definition),e}function isSystemViewDefinition(e){return typeof e==`object`&&!!e&&Ot.has(e)}const kt=`## 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.
|
|
@@ -41,4 +41,4 @@ Show at least one concrete example of the skill applied well.
|
|
|
41
41
|
{{ description }}
|
|
42
42
|
{{ participants }}
|
|
43
43
|
{{ summary }}`).attribute(text({name:I.title,label:`Title`}).required()).attribute(richtext({name:I.description,label:`Description`})).attribute(richtext({name:I.summary,label:`Summary`}).hidden()).attribute(richtext({name:I.transcript,label:`Transcript`}).hidden()).attribute(text({name:I.location,label:`Location`})).attribute(date({name:I.startsAt,label:`Starts at`}).includeTime()).attribute(date({name:I.endsAt,label:`Ends at`}).includeTime()).attribute(checkbox({name:I.isAllDay,label:`All day`})).attribute(select({name:I.status,label:`Status`}).options([{value:`confirmed`,label:`Confirmed`},{value:`tentative`,label:`Tentative`},{value:`cancelled`,label:`Cancelled`}])).attribute(text({name:I.organizerAddress,label:`Organizer address`}).email()).attribute(text({name:I.organizerName,label:`Organizer`})).attribute(text({name:I.conferenceProvider,label:`Conference provider`})).attribute(text({name:I.conferenceJoinUrl,label:`Join link`}).url()).attribute(text({name:I.htmlLink,label:`Open in calendar`}).url()).attribute(text({name:I.participants,label:`Participants`}).multiline()).attribute(text({name:I.providerEventId,label:`Provider event id`}).hidden()).attribute(text({name:I.icalUid,label:`iCal UID`}).hidden()).attribute(text({name:I.recurringEventId,label:`Recurring event id`}).hidden()).attribute(text({name:I.connectionId,label:`Connection id`})).attribute(select({name:I.recordingOverride,label:`Recording`}).options([{value:`force`,label:`Force`},{value:`skip`,label:`Skip`}]).hidden()).attribute(date({name:I.endedAnnouncedAt,label:`Ended announced at`}).includeTime().hidden()).attribute(relation({name:I.linkedRecords,label:`Linked records`}).toAny().many().qualifyWith(text({name:`source`,label:`Source`}).hidden())).build(),Yt=markSystemView(detailView(Kt,`Meeting`).for(F).default().tab(`description`,`Description`,M.richtext(I.description).titleAttribute(I.title)).tab(`summary`,`Summary`,M.richtext(I.summary)).tab(`transcript`,`Transcript`,M.richtext(I.transcript)).aside(`details`,`Details`,M.form(group(`details`,`Details`).fields(I.startsAt,I.endsAt))).build()),Xt=markSystemView(listView(Wt,`Meetings`).for(F).default().tab(`workspace`,`Shared`,M.collection().object(F).table().icon(`users`).visibility(`workspace`).columns(...qt).sort(I.startsAt,`desc`)).tab(`mine`,`My meetings`,M.collection().object(F).table().icon(`lock`).visibility(`private`).columns(...qt).sort(I.startsAt,`desc`)).build());function viewIdentityKey(e,t){return JSON.stringify([e,t])}function cloneDeclaration(e){return structuredClone(e)}var ViewRegistry=class{constructor(){this.views=new Map,this.systemNames=new Map}register(e){let t=(Array.isArray(e)?e:[e]).map((e,t)=>this.prepare(e,t)),r=new Map,i=new Set;for(let{declaration:e}of t){let{object:t,name:a,context:o,default:s}=e.definition,c=r.get(t)??new Set;if((this.views.get(t)?.has(a)||c.has(a))&&this.throwDuplicate(t,a),c.add(a),r.set(t,c),!s)continue;let l=JSON.stringify([t,o]);if(this.getByObjectNameAndContext(t,o).some(e=>e.definition.default)||i.has(l))throw new n.DuplicateError(`default view`,l,`[ViewRegistry] Duplicate default view for object "${t}" in context "${o}"`);i.add(l)}for(let e of t)this.commit(e);return this}prepare(e,r){if(typeof e!=`object`||!e||e.kind!==`view`||Object.keys(e).some(e=>e!==`kind`&&e!==`definition`)){let e=`Expected an exact view declaration`;throw new n.ValidationError(e,[{path:[`views`,String(r)],message:e}])}let i=t.r.safeParse(e.definition);if(!i.success)throw n.ValidationError.fromZodErrors(i.error.issues.map(e=>({path:[`views`,String(r),`definition`,...e.path.map(String)],message:e.message})));return{declaration:cloneDeclaration(e),system:isSystemViewDefinition(e.definition)}}commit({declaration:e,system:t}){let{object:n,name:r}=e.definition,i=this.views.get(n)??new Map;if(i.set(r,e),this.views.set(n,i),t){let e=this.systemNames.get(n)??new Set;e.add(r),this.systemNames.set(n,e)}}getByObjectName(e){return Array.from(this.views.get(e)?.values()??[],cloneDeclaration)}getByObjectNameAndContext(e,t){return this.getByObjectName(e).filter(e=>e.definition.context===t)}get(e,t){let n=this.views.get(e)?.get(t);return n&&cloneDeclaration(n)}getOrThrow(e,t){let r=this.get(e,t);if(r)return r;let i=this.getByObjectName(e).map(({definition:e})=>`${e.name} (${e.context})`).join(`, `)||`(none)`;throw new n.NotFoundError(`View`,`${e}:${t}`,void 0,`[ViewRegistry] View "${t}" not found for object "${e}".\nAvailable views: ${i}`)}getAll(){return Array.from(this.views.values()).flatMap(e=>Array.from(e.values(),cloneDeclaration))}has(e,t){return this.views.get(e)?.has(t)??!1}hasObject(e){return this.views.has(e)}get size(){let e=0;for(let t of this.views.values())e+=t.size;return e}listObjectNames(){return Array.from(this.views.keys())}getDefault(e,t){let n=this.getByObjectNameAndContext(e,t);return n.find(e=>e.definition.default)??n[0]}isSystem(e,t){return this.systemNames.get(e)?.has(t)??!1}isSystemDeclaration(e){return this.isSystem(e.definition.object,e.definition.name)}clear(){this.views.clear(),this.systemNames.clear()}summary(){let e=[`[ViewRegistry] ${this.size} view(s) registered:`];for(let t of this.listObjectNames()){let n=this.getByObjectName(t).map(({definition:e})=>{let t=e.default?` (default)`:``;return`${e.name}:${e.context}${t}`});e.push(` ${t}: ${n.join(`, `)}`)}return e.join(`
|
|
44
|
-
`)}debug(e){let t=this.summary();return e?.(t),t}throwDuplicate(e,t){let r=viewIdentityKey(e,t);throw new n.DuplicateError(`view`,r,`[ViewRegistry] Duplicate view: "${t}" for object "${e}"`)}};const Zt=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 r=singleRelationTarget(e);if(r===void 0){let r=`Relation "${e.name}" requires one concrete collection target`;throw new n.ValidationError(r,[{path:t,message:r}])}return r}function violationOf(e,t,r,i){if(!(e instanceof n.SchemaError))throw e;let a=e instanceof n.ValidationError?e.errors[0]:void 0;return{key:JSON.stringify([t,r,e.code,e.message]),contentName:r,path:a?.path??i,message:e.message,code:e.code,error:e}}const Qt=new Map(t.mt().map(e=>[e.name,e]));function reject$2(e,t){throw new n.ValidationError(t,[{path:e,message:t}])}function requireName(e,t){e.trim().length===0&&reject$2(t,`API name must not be empty`)}function indexUnique(e,t,r){let i=new Map;return e.forEach((e,a)=>{if(requireName(e.name,[...r,String(a),`name`]),i.has(e.name))throw new n.DuplicateError(t,e.name);i.set(e.name,e)}),i}function 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)??Qt.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 r=e.mode??`published`,i=new Map;e.objects.forEach((e,t)=>{if(requireName(e.name,[`objects`,String(t),`name`]),i.has(e.name))throw new n.DuplicateError(`object`,e.name);i.set(e.name,{name:e.name,attributes:indexUnique(e.attributes,`attribute`,[`objects`,String(t),`attributes`])})});let a=new Set;(e.reservedObjects??[]).forEach((e,t)=>{let n=[`reservedObjects`,String(t)];requireName(e,n),!i.has(e)&&(r!==`draft`&&reject$2(n,`Unresolved reserved object "${e}"`),a.add(e),i.set(e,{name:e}))});let o=indexUnique(e.extensions??[],`extension`,[`extensions`]);function resolveObject(e,t){requireName(e,t);let n=i.get(e);return n||reject$2(t,`Unknown object "${e}"`),n}function inverseAddresses(e){let t=[];for(let[n,r]of i)if(n!==e)for(let i of r.attributes?.values()??[])i.type===`relation`&&relationAcceptsObject(i,e)&&t.push(`relatedFrom("${n}", "${i.name}")`);return t.sort().slice(0,3)}let s=r===`draft`?t.s():t.i(),c=new Map,l=new Map,u=[],d=[];function parseView(e,t){let r=s.safeParse(e);if(!r.success)throw new n.ValidationError(`Invalid content view`,r.error.issues.map(e=>({path:[...t,...e.path.map(String)],message:e.message,code:e.code})));let i=r.data;requireName(i.name,[...t,`name`]);let a=c.get(i.object)??new Set;if(a.has(i.name))throw new n.DuplicateError(`view`,`${i.object}.${i.name}`);if(a.add(i.name),c.set(i.object,a),i.default){let e=l.get(i.object)??new Set;if(e.has(i.context))throw new n.DuplicateError(`default view`,`${i.object}.${i.context}`);e.add(i.context),l.set(i.object,e)}return i}return e.views.forEach((e,t)=>{let n=[`views`,String(t)],r=e,i=`${String(r?.object??`?`)}.${String(r?.name??t)}`,a,s;try{a=parseView(e,n),s=resolveObject(a.object,[...n,`object`])}catch(e){u.push(violationOf(e,i,null,n));return}a.contents.forEach((e,t)=>{let r=[...n,`contents`,String(t)];try{requireName(e.name,[...r,`name`]),validateContent(e,r,s,a.context,o,resolveObject,inverseAddresses)}catch(t){u.push(violationOf(t,i,e.name,r))}}),d.push(a)}),{views:d,unresolvedObjects:[...a].sort(),violations:u}}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,r,i,a,o,s){function requireRecord(){requireRecordContentContext(e.name,i,t)}if(e.type===`custom`){let r=a.get(e.extension);r||reject$2([...t,`extension`],`Unknown extension "${e.extension}"`),r.requiresRecord&&requireRecord();let i=r.parameters.safeParse(structuredClone(e.parameters??{}));if(!i.success)throw new n.ValidationError(`Invalid extension parameters`,i.error.issues.map(e=>({path:[...t,`parameters`,...e.path.map(String)],message:e.message,code:e.code})));return}if(e.type===`collection`){let n=collectionSourceAddress(e.source),i,a;if(n.kind===`object`)i=o(n.object,[...t,`source`,`object`]);else if(n.kind===`related`){requireRecord();let e=[...t,`source`,`relation`],hint=()=>{if(!r)return``;let e=s(r.name);return e.length===0?``:`. Records pointing at "${r.name}" are addressed from the other side: ${e.join(`, `)}`},c=requireAttribute$1(r,n.relation,e,`relation`,hint);c?.type===`relation`&&(a=c,i=o(requireSingleRelationTarget(c,e),e))}else{requireRecord(),i=o(n.object,[...t,`source`,`object`]);let a=[...t,`source`,`relation`],s=requireAttribute$1(i,n.relation,a,`relation`);if(s?.type===`relation`&&r&&!relationAcceptsObject(s,r.name)){let e=s.targets.map(e=>`"${e.object}"`).join(`, `);reject$2(a,`Relation "${n.object}.${n.relation}" targets ${e}, not "${r.name}"`)}e.filters?.combinator===`or`&&reject$2([...t,`filters`,`combinator`],`Collection "${e.name}" addresses "${n.object}" from the far side, so its filters must use the "and" combinator`)}e.columns?.forEach((e,n)=>{let r=[...t,`columns`,String(n)];if(typeof e==`string`){requireAttribute$1(i,e,r);return}let o=[...r,`relationProperty`];a||reject$2(o,`Relation property columns require a relation source`),a.properties?.definitions.some(t=>t.name===e.relationProperty)||reject$2(o,`Unknown relation property "${e.relationProperty}"`)}),e.displayAttributes?.forEach((e,n)=>requireAttribute$1(i,e,[...t,`displayAttributes`,String(n)])),e.sorts?.forEach((e,n)=>requireAttribute$1(i,e.attribute,[...t,`sorts`,String(n),`attribute`])),e.filters?.rules.forEach((e,n)=>requireAttribute$1(i,e.attribute,[...t,`filters`,`rules`,String(n),`attribute`])),e.descriptionAttribute!==void 0&&requireAttribute$1(i,e.descriptionAttribute,[...t,`descriptionAttribute`]),e.layout===`kanban`&&e.groupByAttribute!==void 0&&requireAttribute$1(i,e.groupByAttribute,[...t,`groupByAttribute`]);return}switch(requireRecord(),e.type){case`form`:e.groups.forEach((e,n)=>{let i=[...t,`groups`,String(n)];requireName(e.name,[...i,`name`]),e.fields.forEach((e,t)=>requireAttribute$1(r,e.attribute,[...i,`fields`,String(t),`attribute`]))});break;case`richtext`:requireAttribute$1(r,e.attribute,[...t,`attribute`],`richtext`),e.titleAttribute!==void 0&&requireAttribute$1(r,e.titleAttribute,[...t,`titleAttribute`],`text`);break;case`emails`:case`meetings`:e.emailAttributes.forEach((e,n)=>requireAttribute$1(r,e,[...t,`emailAttributes`,String(n)],`text`));break;case`documents`:e.relations?.forEach((e,n)=>requireAttribute$1(r,e,[...t,`relations`,String(n)],`relation`));break;case`forms`:e.objectName!==void 0&&o(e.objectName,[...t,`objectName`]);break;case`activity`:break;default:reject$2(t,`Unknown content type: ${String(e)}`)}}const $t=[Object.freeze(Bt)];var ContentExtensionRegistry=class{constructor(){this.extensions=new Map,this.seed()}register(e){let t=Array.isArray(e)?e:[e],r=new Set;t.forEach((e,t)=>{if(this.prepare(e,t),r.has(e.name))throw new n.DuplicateError(`content extension`,e.name);r.add(e.name)});for(let e of t)this.extensions.set(e.name,e);return this}prepare(e,t){let r=[`extensions`,String(t)],reject=e=>{throw new n.ValidationError(e,[{path:r,message:e}])};if((typeof e!=`object`||!e||Array.isArray(e))&&reject(`Expected a content extension declaration`),Object.keys(e).some(e=>e!==`name`&&e!==`parameters`&&e!==`requiresRecord`)&&reject(`Expected exactly name, parameters and requiresRecord`),(typeof e.name!=`string`||e.name.trim().length===0)&&reject(`API name must not be empty`),typeof e.requiresRecord!=`boolean`&&reject(`requiresRecord must be a boolean`),typeof e.parameters?.safeParse!=`function`&&reject(`parameters must be a Zod schema`),this.extensions.has(e.name))throw new n.DuplicateError(`content extension`,e.name)}get(e){return this.extensions.get(e)}has(e){return this.extensions.has(e)}getAll(){return[...this.extensions.values()]}get size(){return this.extensions.size}clear(){this.extensions.clear(),this.seed()}seed(){for(let e of $t)this.extensions.set(e.name,e)}};const en=new ContentExtensionRegistry;function cleanContent(e,t){let r=structuredClone(e),i=new Set(t.map(e=>JSON.stringify(e.path))),remove=(...e)=>i.has(JSON.stringify(e));switch(r.type){case`form`:return r.groups.forEach((e,t)=>{e.fields=e.fields.filter((e,n)=>!remove(`groups`,String(t),`fields`,String(n),`attribute`))}),r;case`collection`:{if(r.columns&&=r.columns.filter((e,t)=>!remove(`columns`,String(t))),r.displayAttributes&&=r.displayAttributes.filter((e,t)=>!remove(`displayAttributes`,String(t))),r.layout!==`kanban`&&r.columnSizing)for(let e of Object.keys(r.columnSizing))remove(`columnSizing`,e)&&delete r.columnSizing[e];let e=r.filters?.rules.filter((e,t)=>!remove(`filters`,`rules`,String(t),`attribute`)),t=r.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:n,sorts:i,descriptionAttribute:a,...o}=r;return{...o,...r.filters&&e&&!emptied(e,r.filters.rules)?{filters:{...r.filters,rules:e}}:{},...t&&!emptied(t,r.sorts)?{sorts:t}:{},...a===void 0||remove(`descriptionAttribute`)?{}:{descriptionAttribute:a}}}case`richtext`:if(remove(`titleAttribute`)){let{titleAttribute:e,...t}=r;return t}return r;case`activity`:case`custom`:case`documents`:case`forms`:case`emails`:case`meetings`:return r;default:throw new n.ValidationError(`Unsupported content ${String(r)}`,[])}}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},l=o.placement===`main`,u=removedSource(t,o,removed);if(u!==void 0){let e={...s,attribute:u};i.dropped.push(e),l&&(a??=e);continue}e||=l;let d=n(t,o),f=d===void 0?void 0:r.get(d);if(!f)continue;if(o.type===`collection`&&o.layout===`kanban`&&namedBy(f)(o.groupByAttribute)){i.blocked.push({...s,attribute:o.groupByAttribute,reason:`kanban-grouping`});continue}let p=scrubPathsFor(o,f);if(p.length===0)continue;let m=cleanContent(o,p.map(e=>({path:e})));c.s(m)!==c.s(o)&&i.scrubbed.push({...s,definition:m})}!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 n.DuplicateError(`form`,e.name,`[FormRegistry] Duplicate form: "${e.name}"`);this.forms.set(e.name,cloneFormDefinition(e))}return this}get(e){let t=this.forms.get(e);return t?cloneFormDefinition(t):void 0}getAll(){return Array.from(this.forms.values(),cloneFormDefinition)}listNames(){return Array.from(this.forms.keys())}};const tn=new FormRegistry,nn=[`attestorIdentity`,`evidenceDigest`,`maintenanceEpoch`,`observedZeroAt`,`resumeRevision`,`version`,`workloadInventoryDigest`],rn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,an=/^[0-9a-f]{40}$/,on=/^[0-9a-f]{64}$/,sn=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/,cn=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?Z$/;function invalid$1(e,t){throw new n.ValidationError(`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=cn.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 r=Object.keys(e).sort();(r.length!==nn.length||r.some((e,t)=>e!==nn[t]))&&invalid$1(`$`,`must contain exactly the V1 attestation keys`),e.version!==1&&invalid$1(`version`,`must equal numeric 1`);let i=requirePattern(e,`maintenanceEpoch`,rn,`must be a lowercase canonical UUID`),a=requirePattern(e,`resumeRevision`,an,`must be a lowercase 40-character Git SHA`),o=requireCanonicalTimestamp(e),s=requirePattern(e,`attestorIdentity`,sn,`must be a lowercase slug`);if(s.length>64&&invalid$1(`attestorIdentity`,`must be at most 64 characters`),s!==t.allowedAttestorIdentity)throw new n.ValidationError(`Deployment barrier attestor identity mismatch`,[{path:[`attestorIdentity`],message:`does not equal the configured identity`}]);return{version:1,maintenanceEpoch:i,resumeRevision:a,observedZeroAt:o,attestorIdentity:s,workloadInventoryDigest:requirePattern(e,`workloadInventoryDigest`,on,`must be exactly 64 lowercase hexadecimal characters`),evidenceDigest:requirePattern(e,`evidenceDigest`,on,`must be exactly 64 lowercase hexadecimal characters`)}}function verifyDeploymentBarrierAttestationV1(e,t){let r=decodeDeploymentBarrierAttestationV1(e,t);if(r.maintenanceEpoch!==t.maintenanceEpoch)throw new n.ValidationError(`Deployment barrier maintenance epoch mismatch`,[{path:[`maintenanceEpoch`],message:`does not equal the current maintenance epoch`}]);if(r.resumeRevision!==t.resumeRevision)throw new n.ValidationError(`Deployment barrier resume revision mismatch`,[{path:[`resumeRevision`],message:`does not equal the requested revision`}]);let i=t.now.getTime()-new Date(r.observedZeroAt).getTime();if(!Number.isFinite(t.now.getTime())||i>9e5||i<-6e4)throw new n.ValidationError(`Deployment barrier attestation is stale`,[{path:[`observedZeroAt`],message:`must be within the database freshness window`}]);return r}const ln=Object.freeze({attest(){return Promise.reject(new n.SchemaError(`DeploymentBarrierAttestorV1 requires a host implementation that observes the deployment control plane`,n.SchemaErrorCode.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}}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 un=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}),dn=[`membership-unknown`,`sort-unknown`,`permissions-changed`],fn=[`permission-revoked`,`workspace-left`,`object-deleted`],pn=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],mn=[`type`,`objectId`,`recordId`,`recordVersion`],hn=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],gn=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],_n=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&un.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,h)}function isNotificationPriority(e){return isOneOf(e,g)}function isNotificationSensitivity(e){return isOneOf(e,_)}function isNotificationInboxState(e){return isOneOf(e,v)}function isNotificationWorkState(e){return isOneOf(e,y)}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,mn)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$2(e)&&hasOnlyKeys(e,gn)&&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,hn)&&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,dn)}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=>pn.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,_n)&&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 vn=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,vn)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const yn=[`ok`,`low`,`exhausted`,`paused`],bn=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,yn)&&isOneOf(e.mode,bn)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,fn)}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(t){try{return e.D(t)}catch(e){throw e instanceof Error?new ComputedFormulaCompileError(e.message):e}}function inferNode(e,t){switch(e.kind){case`literal`:return{valueType:literalToValueType(e.value),dependencies:[],...typeof e.value==`string`?{literalString:e.value}:{}};case`path`:return inferPath(e.parts,t);case`call`:return inferCall(e.functionName,e.args,t);case`binary`:return inferBinary(e.operator,inferNode(e.left,t),inferNode(e.right,t));default:return e}}function literalToValueType(e){switch(typeof e){case`string`:return{kind:`scalar`,type:`text`};case`number`:return{kind:`scalar`,type:`number`};case`boolean`:return{kind:`scalar`,type:`boolean`};case`object`:return{kind:`scalar`,type:`text`};default:return e}}function inferPath(e,t){if(e.length===1){let n=e[0],r=findAttribute$1(t,n);if(r===void 0)throw new ComputedFormulaCompileError(`Unknown attribute "${n}" on object "${t.objectName}"`);return r.type===`relation`?{valueType:relationToValueType(),dependencies:[{kind:`relation`,relationName:r.name,cardinality:relationCardinality(r)}],targetAttributeType:r.type}:{valueType:attributeToValueType(r),dependencies:[localDependencyFor(r)],optionsSource:optionsSourceForAttribute(t.objectName,r),targetAttributeType:r.type}}if(e.length===2){let[n,r]=e,i=findAttribute$1(t,n);if(i===void 0)throw new ComputedFormulaCompileError(`Unknown attribute "${n}" on object "${t.objectName}"`);if(i.type!==`relation`)throw new ComputedFormulaCompileError(`Attribute "${n}" on object "${t.objectName}" is not a relation`);let a=getRelationTargetObjectName$1(i);if(a===void 0)throw new ComputedFormulaCompileError(`Relation "${n}" on object "${t.objectName}" is missing targetObjectName`);let o=t.relatedObjects?.[a];if(o===void 0)throw new ComputedFormulaCompileError(`Unknown related object "${a}"`);let s=findAttribute$1(o,r);if(s===void 0)throw new ComputedFormulaCompileError(`Unknown attribute "${r}" on object "${o.objectName}"`);let c=attributeToValueType(s);return{valueType:i.cardinality===`many`?asCollectionValueType(c):c,dependencies:[{kind:`relation`,relationName:n,targetAttributeName:r,cardinality:relationCardinality(i)}],optionsSource:optionsSourceForAttribute(o.objectName,s),targetAttributeType:s.type}}throw new ComputedFormulaCompileError(`Computed paths support at most one relation hop`)}function findAttribute$1(e,t){return e.attributes.find(e=>e.name===t)}function getRelationTargetObjectName$1(e){if(e.targetObjectName!==void 0)return e.targetObjectName;if(e.targets?.length===1){let[t]=e.targets;return t?.object===`*`?void 0:t?.object}}function relationCardinality(e){return e.cardinality??`one`}function localDependencyFor(e){return e.type===`formula`||e.type===`rollup`?{kind:`computed`,attributeName:e.name}:{kind:`local`,attributeName:e.name}}function attributeToValueType(e){if(e.type===`formula`||e.type===`rollup`){if(e.returnType===void 0)throw new ComputedFormulaCompileError(`Computed attribute "${e.name}" is missing returnType`);return returnTypeToValueType(e.returnType)}switch(e.type){case`number`:case`currency`:return{kind:`scalar`,type:`number`};case`checkbox`:return{kind:`scalar`,type:`boolean`};case`date`:return{kind:`scalar`,type:`date`};case`select`:case`status`:return{kind:`scalar`,type:`select`};case`multiselect`:return{kind:`collection`,itemType:`select`};case`text`:case`richtext`:case`phone`:case`user`:case`location`:case`relation`:case`document`:return{kind:`scalar`,type:`text`};default:return e.type}}function relationToValueType(){return{kind:`collection`,itemType:`text`}}function returnTypeToValueType(e){return e===`multiselect`?{kind:`collection`,itemType:`select`}:{kind:`scalar`,type:e}}function asCollectionValueType(e){return e.kind===`collection`?e:{kind:`collection`,itemType:e.type}}function optionsSourceForAttribute(e,t){if(t.type===`formula`||t.type===`rollup`)return isSelectLikeReturnType(t.returnType)?t.optionsSource:void 0;if(t.type===`select`||t.type===`status`||t.type===`multiselect`)return t.optionsSource??{objectName:e,attributeName:t.name,...t.id?{attributeId:t.id}:{}}}function inferCall(t,n,r){if(!e.A(t))throw new ComputedFormulaCompileError(`Unknown computed function "${t}"`);let i=e.O[t];if(n.length<i.minArgs||i.maxArgs!==void 0&&n.length>i.maxArgs)throw new ComputedFormulaCompileError(`Function "${t}" expects ${i.maxArgs===void 0||i.maxArgs===i.minArgs?String(i.minArgs):`${i.minArgs}-${i.maxArgs}`} arguments, received ${n.length}`);return inferFunctionReturn(t,n.map(e=>inferNode(e,r)))}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 xn=[{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)`}],Sn=new Date(0).setUTCFullYear(1,0,1),Cn=/^\d{4}-\d{2}-\d{2}$/,wn=new Set([`createdAt`,`updatedAt`,`deletedAt`]),Tn=/^(\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=Tn.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<Sn?null:m}function unwrapRange(t){return e.V(t)?e.B(t):t}function hasTime(e){return e.type===`date`&&e.includeTime===!0}function isSystemTimestamp(e){return wn.has(e.name)}function instantWindow(e){let t=parseFilterInstant(e);return t===null?null:{startMs:t,endMs:t+(typeof e==`string`&&Cn.test(e)?864e5:1)}}function storedUtcDay(e){let n=unwrapRange(e);if(n instanceof Date)return Number.isNaN(n.getTime())?null:t.v(n.getTime());if(typeof n!=`string`||n===``)return null;if(Cn.test(n))return n;let r=new Date(n);return Number.isNaN(r.getTime())?null:t.v(r.getTime())}function comparandDay(e){return e instanceof Date?Number.isNaN(e.getTime())?null:t.v(e.getTime()):typeof e==`string`?Cn.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=>l.t(e)||Array.isArray(e)&&e.length===0,toStr=e=>e==null?``:String(e),toNum=e=>{if(l.t(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)}),L={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,n)=>{let r=toDate(e),i=t.g(n);return r&&i?r.getTime()>=i.startMs&&r.getTime()<i.endMs:!1}},on_day_month:{appliesTo:[`date`],evaluateInMemory:(e,t)=>{let n=toDate(e);if(!n)return!1;let r=t;return n.getMonth()+1===r.month&&n.getDate()===r.day}},any_of:{appliesTo:[`status`,`select`,`multiselect`,`user`,`relation`],evaluateInMemory:(e,t)=>{let n=toArr(t).map(toStr);return toArr(e).map(toStr).some(e=>n.includes(e))}},none_of:{appliesTo:[`status`,`select`,`multiselect`,`user`,`relation`],evaluateInMemory:(e,t)=>{let n=toArr(t).map(toStr);return!toArr(e).map(toStr).some(e=>n.includes(e))}}},systemAttribute=(e,t)=>({id:`system:${e}`,name:e,label:e,type:t,system:!0}),En=[...Object.entries(t.f).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,...En])}function evaluateFilterState(e,t,n){if(e.rules.length===0)return!0;let r=new Map(n.map(e=>[e.name,e])),i=e.combinator===`or`?`some`:`every`;return e.rules[i](e=>evaluateRule(e,t,r))}function evaluateRule(e,n,r){let i=r.get(e.attribute);if(!i)return!1;if(e.property&&i.type===`location`){if(!(t.lt(e.property)&&t.E(e.operator)))return!1;let r=L[e.operator];if(!r)return!1;let a=n[e.attribute],o=typeof a==`object`&&a?a[e.property]:void 0;return evaluateNormalizedComparands(r,`text`,e.operator,o,e.value,i)}if(e.property){let r=resolvePropertyDefinitions(i).find(t=>t.name===e.property);if(!r)return!1;let a=t.M(e.operator),o=L[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.A(e.operator))===`none`?!c:c}let a=L[e.operator];if(!a||!a.appliesTo.includes(i.type))return!1;let o=n[e.attribute],s=i.type===`relation`||i.type===`document`||i.type===`user`?normalizeReferenceIds(o):o;return evaluateNormalizedComparands(a,i.type,e.operator,s,e.value,i)}function evaluateNormalizedComparands(e,t,n,r,i,a){let[o,s]=normalizeOperatorComparands(t,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 u.i(t.phoneNumber);let n=typeof t.countryCode==`string`?t.countryCode:r;return`${n}:${u.a(t.phoneNumber,n)}`};return[normalizeOne(e),normalizeOne(t)]}function normalizeComparableValue(n,r){return n===`currency`?t.P(r):n===`date`?e.V(r)?e.B(r):r instanceof Date?Number.isNaN(r.getTime())?null:r.toISOString():r:r}function normalizeReferenceIds(e){let normalizeOne=e=>typeof e!=`object`||!e?e:e.id;return Array.isArray(e)?e.map(normalizeOne):normalizeOne(e)}function dateInTimezone(e,t){return new Intl.DateTimeFormat(`en-CA`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`}).format(e)}function resolveAttributeDefaultValue(e,t){if(!(`defaultValue`in e))return;let{defaultValue:n}=e;return e.type!==`date`||n!==`today`?n:e.includeTime?t.now.toISOString():dateInTimezone(t.now,t.timezone)}function deriveCreateDefaultsFromFilters(e,n,r){if(e.combinator===`or`&&e.rules.length>1)return{};let i=new Map(n.map(e=>[e.name,e])),a={};for(let n of e.rules){if(n.property!==void 0||Object.hasOwn(a,n.attribute))continue;let e=i.get(n.attribute);if(!e)continue;let o=extractDeterministicValue(n,r);o!==void 0&&(a[n.attribute]=t.rt(e).storage.cardinality===`many`?[o]:o)}return a}function extractDeterministicValue(e,n){if(e.operator===`is`)return t.L(e.value)?resolveDynamicValue(e.value,n):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator===`any_of`){if(!Array.isArray(e.value)||e.value.length!==1)return;let r=e.value[0];return t.L(r)?resolveDynamicValue(r,n):r}}function resolveDynamicValue(e,t){if(t){if(e.dynamic===`actor`)return t.userId;if(e.anchor===`today`)return dateInTimezone(t.now,t.timezone);if(e.anchor===`now`)return t.now.toISOString()}}function requestedCapabilities(e){let t=[];return e.canModify&&t.push(`modify`),e.canSend&&t.push(`send`),t}const Dn={status:`connector_status`,error:`connector_error`,provider:`connector_provider`};let On=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const kn=`DRAFT`;function isProviderDraft(e){return e.includes(kn)}const An=[`threads`,`messages`];function isMailboxListMode(e){return An.includes(e)}const jn=[`reply`,`reply_all`];function isReplyMode(e){return jn.includes(e)}const Mn=[`force`,`skip`],Nn=[`none`,`all`,`external_only`],Pn={override:null,status:`none`,failureReason:null,botId:null},Fn=/^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&&!Fn.test(t)?t:e.firstUserText?buildAgentFallbackTitle(e.firstUserText):e.emptyLabel}const R=/^[a-z0-9][a-z0-9-]{0,62}$/;function assertSchemaSourceId(e){if(!R.test(e))throw new n.ValidationError(`Invalid schema source id "${e}": expected a lowercase slug matching ${R}`,[])}const In={phone:`text`,currency:`number`},Ln={rename:[`kind`,`object`,`from`,`to`],phone:[`kind`,`object`,`attribute`,`to`,`defaultCountryCode`],currency:[`kind`,`object`,`attribute`,`to`,`currencyCode`]};function refuse$1(e,t,r){throw new n.ValidationError(r,[{path:t===void 0?[`resolutions`,String(e)]:[`resolutions`,String(e),t],message:r}])}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(t,n){if(e.T(n)||refuse$1(t,void 0,`Resolution ${t} must be an object`),n.kind===`rename`){assertKeys(t,n,Ln.rename),n.from===n.to&&refuse$1(t,`to`,`Resolution ${t} renames "${n.from}" to itself`);return}if(n.kind!==`retype`&&refuse$1(t,`kind`,`Unknown resolution kind ${JSON.stringify(n.kind)}: expected "rename" or "retype"`),n.to!==`phone`&&n.to!==`currency`&&refuse$1(t,`to`,`Unsupported retype to ${JSON.stringify(n.to)}: a push converts text → phone and number → currency only`),assertKeys(t,n,Ln[n.to]),n.to===`phone`){let e=n.defaultCountryCode;/^[A-Z]{3}$/.test(e)&&(0,p.isValidIso3)(e)||refuse$1(t,`defaultCountryCode`,`Resolution ${t}: "${e}" is not an ISO 3166-1 alpha-3 country code`);return}let r=n.currencyCode;/^[A-Z]{3}$/.test(r)&&(0,p.isValidCurrencyCode)(r)||refuse$1(t,`currencyCode`,`Resolution ${t}: "${r}" 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 n.ValidationError("`resolutions` must be an array",[{path:[`resolutions`],message:"`resolutions` must be an array"}]);if(e.length>100)throw new n.ValidationError(`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=(0,m.parsePhoneNumberFromString)(n,u.r(t));if(!r?.isPossible()||r.country===void 0||r.ext!==void 0)return;let i=(0,p.getCountryByIso2)(r.country)?.iso3;if(i!==void 0)return{value:{countryCode:i,phoneNumber:u.a(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 Rn=f.z.object({mode:f.z.enum([`inline`,`window`]),interaction:f.z.enum([`static`,`interactive`]),size:f.z.enum([`compact`,`regular`]),aspectRatio:f.z.number().positive().finite().optional()}).strict(),zn=f.z.object({artifactId:f.z.string().min(1),revision:f.z.number().int().positive(),name:f.z.string().min(1),kind:f.z.string().min(1),retention:f.z.enum(Fe),display:Rn}).strict();function readArtifactResult(e){let t=zn.safeParse(e);return t.success?t.data:null}const Bn=f.z.string().regex(/^[^/\s]+\/[^/\s]+$/),Vn=f.z.object({kind:f.z.literal(`generated-image`),artifact:f.z.unknown(),generation:f.z.object({attemptId:f.z.uuid(),requestedModelId:Bn,executedModelId:Bn.nullable(),format:f.z.enum(We),mimeType:f.z.enum([`image/png`,`image/jpeg`,`image/webp`])}).strict()}).strict();function readGeneratedImageResult(e){let t=Vn.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 Hn={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,Hn)}}return[...t.values()]}const Un={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,Un)}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,Un)}}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 n.ValidationError(t,[{path:e,message:t}])}function exhaustive(e){throw new n.ValidationError(`Unsupported schema reference variant ${String(e)}`,[])}function collectSchemaReferences(t){let n=new Map(t.objects.map(e=>[e.name,e])),r=[];function visitor(e,t,i){function add(a,o,s){(a.kind===`object`?n.has(a.object):a.kind!==`attribute`||n.get(a.object)?.attributes.some(e=>e.name===a.attribute))||reject$1([...t,...s],`Unknown schema reference ${JSON.stringify(a)}`),r.push({owner:e,target:a,category:o,path:s,...i===void 0?{}:{layer:i}})}function attribute(e,t,n,r){add({kind:`attribute`,object:e,attribute:t},n,r)}function traverse(e,r,i,a,o){attribute(e,r,i,a);let s=n.get(e)?.attributes.find(e=>e.name===r);return s?.type!==`relation`&&reject$1([...t,...a],`Invalid schema reference path "${o}"`),(s.targets.length!==1||s.targets[0].object===`*`)&&reject$1([...t,...a],`Ambiguous schema reference path "${o}"`),s.targets[0].object}function attributePath(e,t,n,r){let i=e;for(let[e,a]of t.entries())e===t.length-1?attribute(i,a,n,r):i=traverse(i,a,n,r,t.join(`.`))}function formula(e,t,n){switch(t.kind){case`literal`:return;case`path`:attributePath(e,t.parts,`computed`,n);return;case`call`:for(let r of t.args)formula(e,r,n);return;case`binary`:formula(e,t.left,n),formula(e,t.right,n);return;default:exhaustive(t)}}return{add,attribute,traverse,attributePath,formula}}t.objects.forEach((t,n)=>{let r=[`objects`,String(n)],i=visitor({kind:`object`,object:t.name},r);for(let e of[`labelExpression`,`embeddingExpression`]){let n=t[e];if(n)for(let r of extractAttributeNames(n))i.attributePath(t.name,r.split(`.`),`business`,[e])}t.attributes.forEach((n,i)=>{let a=[...r,`attributes`,String(i)],o=visitor({kind:`attribute`,object:t.name,attribute:n.name},a);switch(n.type){case`relation`:n.targets.forEach((e,t)=>{if(e.object!==`*`&&o.add({kind:`object`,object:e.object},`structural`,[`targets`,String(t),`object`]),e.displayTemplate)for(let n of extractAttributeNames(e.displayTemplate))o.attributePath(e.object,n.split(`.`),`business`,[`targets`,String(t),`displayTemplate`]);for(let n of Object.keys(e.filter??{}))o.attribute(e.object,n,`business`,[`targets`,String(t),`filter`,n])});break;case`formula`:{let r;try{r=e.D(n.expression)}catch(e){reject$1([...a,`expression`],e instanceof Error?e.message:String(e))}o.formula(t.name,r,[`expression`]),visitOptions(n,o);break}case`rollup`:{let e=n.relationPath??n.relationAttribute,r=t.name;for(let t of e.split(`.`))r=o.traverse(r,t,`computed`,[n.relationPath===void 0?`relationAttribute`:`relationPath`],e);n.targetAttribute!==void 0&&o.attributePath(r,n.targetAttribute.split(`.`),`computed`,[`targetAttribute`]),visitOptions(n,o);break}case`text`:case`richtext`:case`number`:case`checkbox`:case`date`:case`phone`:case`currency`:case`status`:case`location`:case`select`:case`multiselect`:case`user`:case`document`:break;default:exhaustive(n)}})});function visitOptions(e,t){e.optionsSource&&(t.add({kind:`object`,object:e.optionsSource.objectName},`computed`,[`optionsSource`,`objectName`]),t.attribute(e.optionsSource.objectName,e.optionsSource.attributeName,`computed`,[`optionsSource`,`attributeName`]))}function viewReferences(e,t,r){visitor({kind:`view`,object:e.object,view:e.name},t,r).add({kind:`object`,object:e.object},`structural`,[`object`]),e.contents.forEach((i,a)=>{let o=visitor({kind:`content`,object:e.object,view:e.name,content:i.name},[...t,`contents`,String(a)],r);function names(e,t,n,r){e?.forEach((e,i)=>o.attribute(t,e,n,[r,String(i)]))}switch(i.type){case`collection`:{let r=collectionSourceAddress(i.source),s;switch(r.kind===`object`?(s=r.object,o.add({kind:`object`,object:s},`source`,[`source`,`object`])):r.kind===`relatedFrom`?(s=r.object,o.add({kind:`object`,object:s},`source`,[`source`,`object`]),o.attribute(s,r.relation,`source`,[`source`,`relation`])):s=o.traverse(e.object,r.relation,`source`,[`source`,`relation`],r.relation),i.columns?.forEach((i,c)=>{if(typeof i==`string`){o.attribute(s,i,`display`,[`columns`,String(c)]);return}let l=n.get(e.object),u=r.kind!==`related`||!l?void 0:findRelationAttribute(l,r.relation),d=[`columns`,String(c),`relationProperty`];u||reject$1([...t,`contents`,String(a),...d],`Relation property columns require a relation source`),u.properties?.definitions.some(e=>e.name===i.relationProperty)||reject$1([...t,`contents`,String(a),...d],`Unknown relation property "${i.relationProperty}"`),o.add({kind:`attribute`,object:e.object,attribute:u.name},`display`,d)}),names(i.displayAttributes,s,`display`,`displayAttributes`),i.descriptionAttribute!==void 0&&o.attribute(s,i.descriptionAttribute,`display`,[`descriptionAttribute`]),i.filters?.rules.forEach((e,t)=>o.attribute(s,e.attribute,`business`,[`filters`,`rules`,String(t),`attribute`])),i.sorts?.forEach((e,t)=>o.attribute(s,e.attribute,`business`,[`sorts`,String(t),`attribute`])),i.layout){case`table`:case`list`:if(i.columnSizing)for(let e of Object.keys(i.columnSizing))o.attribute(s,e,`display`,[`columnSizing`,e]);break;case`kanban`:i.groupByAttribute!==void 0&&o.attribute(s,i.groupByAttribute,`business`,[`groupByAttribute`]);break;default:exhaustive(i.layout)}break}case`form`:i.groups.forEach((t,n)=>t.fields.forEach((t,r)=>o.attribute(e.object,t.attribute,`display`,[`groups`,String(n),`fields`,String(r),`attribute`])));break;case`richtext`:o.attribute(e.object,i.attribute,`source`,[`attribute`]),i.titleAttribute!==void 0&&o.attribute(e.object,i.titleAttribute,`display`,[`titleAttribute`]);break;case`documents`:names(i.relations,e.object,`business`,`relations`);break;case`forms`:i.objectName!==void 0&&o.add({kind:`object`,object:i.objectName},`source`,[`objectName`]);break;case`emails`:case`meetings`:names(i.emailAttributes,e.object,`business`,`emailAttributes`);break;case`activity`:case`custom`:break;default:exhaustive(i)}})}return t.views.forEach((e,t)=>viewReferences(e,[`views`,String(t)])),t.retainedViews?.forEach(({definition:e,layer:t},n)=>viewReferences(e,[`retainedViews`,String(n),`definition`],t)),r}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 Wn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function reject(e,t,r){throw new n.ValidationError(r,[{path:[...e.split(`.`),t],message:r}])}function pairKey(e){return e.join(`|`)}function pairedAddresses(e,t){return[e,t].sort()}function validateExistingPairs(e){let t=new Map,n=new Map,r=new Set;for(let i of e){let e=pairKey(i.addresses);(!Wn.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,n,r){let i=e.bilateral;i||reject(`${n}.${e.name}`,`bilateral`,`Missing inverse address`);let a={type:`relation`,name:i.attribute,label:i.label??i.attribute,required:!1,targets:[{object:n}],bilateral:{object:n,attribute:e.name,cardinality:e.cardinality},order:r};return(i.cardinality??t.X(e.cardinality))===`one`?{...a,cardinality:`one`}:{...a,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&&!c.r(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)&&!c.r(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),l=o?e.properties:s?t.properties:e.properties??t.properties;l?(e.properties=structuredClone(l),t.properties=structuredClone(l)):(delete e.properties,delete t.properties)}function reconcileRelationAttributes(e){let t=structuredClone(e.objects),r=new Map;for(let e of t){if(r.has(e.name))throw new n.DuplicateError(`object`,e.name);r.set(e.name,e);let t=new Set;for(let r of e.attributes){if(t.has(r.name))throw new n.DuplicateError(`attribute`,r.name);t.add(r.name),stripUntrustedPairMetadata(r)}}let i=remapExistingPairs(e.existingPairs??[],e.addressRenames??[]),a=validateExistingPairs(i),o=new Set(i.flatMap(e=>e.generatedAddresses)),s=new Set(e.propertyEditAddresses??[]),c=new Set(e.explicitAddresses??t.flatMap(e=>e.attributes.filter(t=>!o.has(`${e.name}.${t.name}`)).map(t=>`${e.name}.${t.name}`))),l=t.flatMap(e=>e.attributes.filter(e=>e.type===`relation`&&!!e.bilateral).map(t=>({object:e,attribute:t,address:`${e.name}.${t.name}`}))).sort((e,t)=>e.address.localeCompare(t.address)),u=new Map,d=new Map;for(let{object:t,attribute:o,address:f}of l){let l=o.bilateral?.object;(!l||l===`*`||o.targets.length!==1||o.targets[0]?.object!==l)&&reject(f,`targets`,`Bilateral target of ${f} must be one concrete object`);let p=r.get(l);p||reject(f,`bilateral`,`Unknown inverse object ${l} for ${f}`);let m=`${l}.${o.bilateral?.attribute}`,h=f===m;h&&o.cardinality!==`many`&&reject(f,`cardinality`,`Symmetric self relation ${f} must be many`),h&&o.bilateral?.cardinality&&o.bilateral.cardinality!==o.cardinality&&reject(f,`bilateral`,`Symmetric self relation ${f} needs matching cardinality`);let g=pairedAddresses(f,m),_=pairKey(g);if(u.has(_))continue;let v=p.attributes.find(e=>e.name===o.bilateral?.attribute);if(v&&!isReciprocal(v,t.name,o.name))throw new n.DuplicateError(`attribute`,m);let y=!(v&&c.has(m));v||(v=generateInverse(o,t.name,p.attributes.length),p.attributes.push(v));let b=v;!h&&c.has(f)&&c.has(m)&&checkExplicitDeclarations(o,b,f,m,s.has(f)!==s.has(m));let x=a.get(_),S=x?.id??e.nextPairId(g),ee=i.find(e=>e.id===S&&pairKey(e.addresses)!==_);(!Wn.test(S)||ee||d.has(S)&&d.get(S)!==_)&&reject(f,`pair`,`Invalid or duplicate pair identity for ${f} and ${m}`),d.set(S,_);let C=h?f:chooseOwner(o,b,f,m,x,y);o.bilateral&&b.bilateral||reject(f,`bilateral`,`Missing reciprocal configuration for ${f} and ${m}`),o.bilateral={...o.bilateral,cardinality:b.cardinality,label:b.label,storageOwner:C===f},b.bilateral={...b.bilateral,cardinality:o.cardinality,label:o.label,storageOwner:C===m},reconcileProperties(o,b,f,m,c,s),o.metadata={...o.metadata,relationPairId:S},b.metadata={...b.metadata,relationPairId:S},u.set(_,{id:S,addresses:g,ownerAddress:C,generatedAddresses:g.filter(e=>!c.has(e)),...h?{symmetric:!0}:{}})}return{objects:t,pairs:[...u.values()].sort((e,t)=>e.addresses[0].localeCompare(t.addresses[0]))}}const z=f.z.number().finite().nonnegative(),Gn=f.z.enum(le),B=f.z.enum(ue),V=f.z.enum(de),H=f.z.enum(me),Kn=f.z.object({provider:Gn,model:f.z.string().min(1)}).strict(),qn=f.z.object({speed:B.optional(),reasoning:V.optional(),routing:H.optional()}).strict(),U=f.z.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),Jn=f.z.object({model:Kn.optional(),speed:B.optional(),reasoning:V.optional(),imageModel:U.optional(),routing:H.optional()}).strict(),Yn=Jn.refine(e=>ge.some(t=>e[t]!==void 0),{message:`At least one inference override is required`}),Xn=f.z.object({model:Kn.nullable().optional(),speed:B.nullable().optional(),reasoning:V.nullable().optional(),imageModel:U.nullable().optional(),routing:H.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`}),Zn=f.z.object({model:f.z.string().min(1),routing:f.z.object({mode:f.z.literal(`auto`),tasks:f.z.array(f.z.enum(fe)).optional(),demand:f.z.enum(pe).optional(),reason:f.z.enum([`selected`,`retained`,`fallback`]).optional(),relation:f.z.enum([`continue`,`modify`,`new`,`aside`,`unknown`]).optional(),anchorMessageId:f.z.string().min(1).optional()})}),Qn=f.z.object({label:f.z.string(),denied:f.z.boolean().optional(),deletion:f.z.object({target:f.z.string().optional(),count:z.optional(),restorableDays:z.optional()}).strict().optional(),counts:f.z.record(f.z.string(),z).optional(),warnings:f.z.array(f.z.string()).optional()}).strict(),$n=f.z.union([f.z.object({type:f.z.literal(`text`),text:f.z.string()}).strict(),f.z.object({type:f.z.literal(`reasoning`),text:f.z.string()}).strict(),f.z.object({type:f.z.literal(`system`),code:f.z.enum(xe)}).strict(),f.z.object({type:f.z.literal(`error`),error:f.z.string(),errorClass:f.z.string().optional()}).strict(),f.z.object({type:f.z.literal(`tool`),toolCallId:f.z.string(),name:f.z.string(),args:f.z.record(f.z.string(),f.z.unknown()),result:f.z.unknown().optional(),error:f.z.string().optional(),errorCode:f.z.enum([`output_limit_reached`,`interrupted`,n.SchemaErrorCode.INVALID_TOOL_INPUT,`external_outcome_unknown`,`external_not_dispatched`]).optional(),state:f.z.enum([`streaming`,`running`,`completed`,`error`,`pending`,`approval-requested`,`approval-responded`,`approval-dispatched`]),durationMs:z.optional(),approvalId:f.z.string().optional(),approvalImpact:Qn.optional(),approved:f.z.boolean().optional(),approvalReason:f.z.string().optional(),approvalRelaxableByAuto:f.z.boolean().optional()}).strict(),f.z.object({type:f.z.literal(`file`),fileId:f.z.string(),name:f.z.string(),mimeType:f.z.string()}).strict(),f.z.object({type:f.z.literal(`compaction`),state:f.z.literal(`in-progress`),reason:f.z.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:z.optional(),reportedTokens:z.optional()}).strict(),f.z.object({type:f.z.literal(`compaction`),state:f.z.literal(`completed`),tokensBefore:z,tokensAfter:z,tokensSaved:z,strategy:f.z.enum([`no-op`,`summary`,`truncation`]),durationMs:z,summary:f.z.string().optional()}).strict(),f.z.object({type:f.z.literal(`compaction`),state:f.z.literal(`failed`),reason:f.z.string(),durationMs:z.optional()}).strict()]),er=f.z.object({id:f.z.string(),name:f.z.string(),mimeType:f.z.string(),size:z}).strict(),tr=f.z.object({id:f.z.string(),artifactId:f.z.string(),revision:f.z.number().int().min(1),selectedText:f.z.string()}).strict(),nr=f.z.object({id:f.z.string(),type:f.z.string().transform(e=>e),entityId:f.z.string(),label:f.z.string(),objectName:f.z.string().optional(),startIndex:z,endIndex:z}).strict(),rr=f.z.object({provider:Gn,model:f.z.string(),maxTokens:z.optional(),contextWindow:z.optional()}).strict(),ir=f.z.union([f.z.date(),f.z.string().datetime({offset:!0}).transform(e=>new Date(e))]),ar=f.z.object({id:f.z.string(),sessionId:f.z.string(),tenantId:f.z.string().optional(),runId:f.z.string().optional(),role:f.z.enum([`user`,`assistant`,`system`,`tool`]),parts:f.z.array($n),attachments:f.z.array(er).optional(),mentions:f.z.array(nr).optional(),quotes:f.z.array(tr).optional(),model:rr.optional(),tokenUsage:f.z.object({input:z,output:z}).strict().optional(),metadata:f.z.record(f.z.string(),f.z.unknown()).optional(),createdAt:ir}).strict(),or=f.z.object({id:f.z.string(),description:f.z.string(),status:f.z.enum([`pending`,`in_progress`,`completed`,`blocked`]),result:f.z.string().optional(),updatedAt:z.optional()}).strict(),sr=f.z.object({id:f.z.string(),sessionId:f.z.string(),status:f.z.enum([`active`,`completed`,`abandoned`]),todos:f.z.array(or),version:z,createdAt:f.z.string(),updatedAt:f.z.string(),completedAt:f.z.string().optional()}).strict(),cr={"session-named":f.z.object({name:f.z.string()}).strict(),"compaction-start":f.z.object({reason:f.z.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:z.optional(),reportedTokens:z.optional()}).strict(),"compaction-end":f.z.object({tokensBefore:z,tokensAfter:z,tokensSaved:z,strategy:f.z.enum([`no-op`,`summary`,`truncation`]),durationMs:z,summary:f.z.string().optional()}).strict(),"compaction-failed":f.z.object({reason:f.z.string()}).strict(),usage:f.z.object({messageId:f.z.string().min(1).optional(),inputTokens:z,outputTokens:z,totalTokens:z,cacheReadTokens:z.optional(),cacheCreationTokens:z.optional(),contextWindow:z,residentTokens:z,utilization:f.z.number().finite().min(0).max(1),costUsd:z.optional()}).strict(),"message-persisted":f.z.object({message:ar}).strict(),"message-persisted-ref":f.z.object({messageId:f.z.string().min(1)}).strict(),"message-updated":f.z.object({message:ar}).strict(),"todo-plan-update":f.z.object({plan:sr}).strict(),"approval-context":f.z.object({approvalId:f.z.string(),toolCallId:f.z.string(),impact:Qn.optional(),relaxableByAuto:f.z.boolean().optional()}).strict(),"session-state":f.z.object({state:f.z.object({phase:f.z.enum([`queued`,`running`,`parked`,`terminal`]),parkedOn:f.z.enum([`human`,`agents`]).optional(),humanRequestIds:f.z.array(f.z.string()).optional(),outcome:f.z.enum([`completed`,`failed`,`cancelled`,`timeout`,`expired`]).optional()}).strict(),version:f.z.number().int().positive(),updatedAt:f.z.string().datetime({offset:!0})}).strict()};function isAgentUIDataName(e){return e in cr}function agentUIValidationError(e){return new n.ValidationError(`Invalid agent UI message chunk`,e.map(e=>({path:e.path.map(String),message:e.message,code:e.code})))}function assertCustomAgentUIMessageChunk(e){if(typeof e!=`object`||!e||typeof e.type!=`string`)throw new n.ValidationError(`Invalid agent UI message chunk`,[{path:[`type`],message:`Expected UI message chunk type`,code:`invalid_type`}]);let t=e.type;if(!t.startsWith(`data-`))throw new n.ValidationError(`Invalid agent UI message chunk`,[{path:[`type`],message:`Expected agent data chunk type`,code:`invalid_value`}]);let r=t.slice(5);if(!isAgentUIDataName(r))throw new n.ValidationError(`Invalid agent UI message chunk`,[{path:[`type`],message:`Unknown agent UI data type: ${r}`,code:`invalid_value`}]);let i=f.z.object({type:f.z.literal(`data-${r}`),id:f.z.string().optional(),data:cr[r],transient:f.z.boolean().optional()}).strict().safeParse(e);if(!i.success)throw agentUIValidationError(i.error.issues);return i.data}function agentDataChunk(e,t,n){return assertCustomAgentUIMessageChunk({type:`data-${e}`,...n?.id===void 0?{}:{id:n.id},data:t,...n?.transient===void 0?{}:{transient:n.transient}})}const lr=f.z.object({type:f.z.enum(_e),color:f.z.enum(p.AVATAR_COLOR_IDS),expression:f.z.enum(ve).default(`relaxed`)}).strict(),ur=f.z.array(f.z.string().trim().min(1).max(200)).max(4);function agentAvatarFromMetadata(e){let t=lr.safeParse(e);return t.success?t.data:void 0}const dr=[`Very economical`,`Balanced`,`Powerful`,`Very powerful`],fr=[`unsupported`,`effort`,`toggle`,`budget`,`model-controlled`],pr=[`text`,`image`,`audio`,`video`,`pdf`],mr=/^\d+x\d+$/,hr=/^\d+:\d+$/,gr=/^[a-z0-9][a-z0-9-]*$/,_r=.01;function refuse(e){throw new n.ValidationError(`Model catalogue: ${e}`,[])}function refuseZodIssues(e){let[t]=e.issues;throw new n.ValidationError(`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 f.z.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 f.z.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>_r?`implausible`:n===0&&!t?`undeclared-zero`:null}const vr=f.z.looseObject({cost:f.z.string(),min:f.z.number(),max:f.z.number().optional()});function priceDimensionSchema(e,t,n){let r=`model "${e}" has an unreadable ${t} price`;return f.z.looseObject({perToken:f.z.string().optional(),tiers:f.z.array(vr).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 ${_r} 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 f.z.looseObject({...dimensions(``),fast:f.z.looseObject(dimensions(`fast `),{error:n}).optional()},{error:n})}function catalogTextModelSchema(e,t){let n=`model "${e}"`;return f.z.looseObject({id:nonEmptyString(`${n} has no usable id`),apiModelId:nonEmptyString(`${n} has no usable apiModelId`).optional(),provider:f.z.enum(le,{error:e=>`${n} names an unknown provider "${String(e.input)}"`}),label:nonEmptyString(`${n} has no usable label`),description:f.z.string().optional(),recommended:f.z.boolean().optional(),recommendationRank:f.z.number().optional(),profile:f.z.looseObject({position:f.z.number(),label:f.z.enum(dr,{error:e=>`${n} has an unknown profile label "${String(e.input)}"`}),guidance:f.z.string()},{error:`profile of ${n} must be an object`}).optional(),pricing:pricingSchema(e,t),free:f.z.boolean().optional(),reasoningOptions:f.z.array(f.z.enum(de)).optional(),reasoningMode:f.z.enum(fr).optional(),inputModalities:f.z.array(f.z.enum(pr)).optional(),supportedParameters:f.z.array(f.z.string()).optional(),supportsTools:f.z.boolean().optional(),supportsStructuredOutput:f.z.boolean().optional(),isDefault:f.z.boolean().optional(),contextWindow:positiveIntegerSchema(n,`contextWindow`),maxOutputTokens:positiveIntegerSchema(n,`maxOutputTokens`),unverified:f.z.boolean().optional(),isCompactionModel:f.z.boolean().optional(),isUtilityModel:f.z.boolean().optional(),tasks:f.z.partialRecord(f.z.enum(fe),f.z.enum(pe)).optional(),listPricing:f.z.object({inputPerMillionUsd:f.z.number(),outputPerMillionUsd:f.z.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 f.z.union([f.z.looseObject({size:f.z.custom(e=>mr.test(String(e)))}),f.z.looseObject({aspectRatio:f.z.custom(e=>hr.test(String(e)))})],{error})}function catalogImageModelSchema(e){let t=`image model "${e}"`,n=`${t} has no usable formats`;return f.z.looseObject({id:U,name:nonEmptyString(`${t} has no usable name`),provider:nonEmptyString(`${t} has no usable provider`).regex(gr,{error:`${t} names an unusable provider`}),formats:f.z.array(f.z.enum(We,{error:e=>`${t} declares an unknown format "${String(e.input)}"`}),{error:n}).min(1,{error:n}),requests:f.z.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:f.z.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 yr=f.z.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 br=f.z.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`||!br.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(yr,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 W={kind:`target-missing`};var DraftRefusalError=class extends n.ValidationError{constructor(e,t,n=[]){super(e,n),this.refusal=t}};const xr=[`pluralLabel`,`description`,`labelExpression`,`embeddingExpression`];function draftObjectSettings(e){return Object.fromEntries(xr.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 Sr={id:f.z.string().min(1).describe(`Your id, echoed back`),note:f.z.string().trim().min(1).max(160).optional().describe(`One first-person sentence, in the person's language: what you do and why, ≤160 chars`)},G={...Sr,objectName:f.z.string().min(1).describe(`Object`),viewName:f.z.string().min(1).describe(`View API name`)},K={...G,contentName:f.z.string().min(1).describe(`Content API name`)},Cr=f.z.union([f.z.object({before:f.z.string().min(1).describe(`Place immediately before this content name`)}).strict(),f.z.object({after:f.z.string().min(1).describe(`Place immediately after this content name`)}).strict(),f.z.object({end:f.z.literal(!0).describe(`Place at the end of the placement zone`)}).strict()]),viewFocus=e=>({objectName:e.objectName,viewName:e.viewName}),contentFocus=e=>({...viewFocus(e),contentName:e.contentName});function invalid(e,t,r){let i=[{path:e,message:t}];throw r?new DraftRefusalError(t,r,i):new n.ValidationError(t,i)}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`,W),n}function setOrder(e,t,n){for(let r of n)e.authoring[r===`main`?`mainOrderCustomized`:`asideOrderCustomized`]=!0,t.filter(e=>e.placement===r).forEach((t,n)=>{contentState(e,t.name).workspacePosition=n})}function find(e,t){let n=e.contents.find(e=>e.name===t);return n||invalid([`contentName`],`Content is not in the draftable state`,W),n}function placed(e,t,n){let r=e.filter(e=>e.name!==t.name),i=r.filter(e=>e.placement===t.placement),a=i.length;if(!(`end`in n)){let e=`before`in n?n.before:n.after;a=i.findIndex(t=>t.name===e),a<0&&invalid([`target`],`Order target is not in this placement`),`after`in n&&a++}return i.splice(a,0,t),t.placement===`main`?[...i,...r.filter(e=>e.placement===`aside`)]:[...r.filter(e=>e.placement===`main`),...i]}const wr=f.z.unknown().transform((e,n)=>{let r=t.l.safeParse(typeof e==`object`&&e?{...e,name:`candidate`}:e);if(!r.success){for(let e of r.error.issues)n.addIssue({code:`custom`,path:e.path,message:e.message});return f.z.NEVER}let i=typeof e==`object`&&e&&`name`in e?e.name:void 0;return{...r.data,name:i}}),Tr=f.z.object({...K,type:f.z.literal(`replace_view_content`),definition:wr}).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}}),Er=t.l.describe(`The whole content definition.`),Dr=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:Tr,wire:f.z.object({...K,type:f.z.literal(`replace_view_content`),definition:Er}).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}}))}),Or=f.z.object({...G,type:f.z.literal(`add_view_content`),content:Er,target:Cr.describe(`Where to place the new content within its placement zone`)}).strict(),addFocus=e=>({...viewFocus(e),contentName:e.content.name}),kr=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:Or,focus:addFocus,presentation:definePresentation(addFocus,`structural`),describe:e=>`Add ${e.content.name}`,apply:(e,t,r)=>change(e,t,r,e=>{if(Object.hasOwn(e.authoring.contents,t.content.name))throw new n.DuplicateError(`content`,t.content.name);e.authoring.contents={...e.authoring.contents,[t.content.name]:{sourceDefinition:null,workspaceDefinition:storedContentDefinition(t.content),suppressed:!1,sourcePosition:null,workspacePosition:0}};let r=placed(e.contents,t.content,t.target);return setOrder(e,r,[t.content.placement]),{...e,revision:e.revision+1,contents:r,contentIds:{...e.contentIds,[t.content.name]:JSON.stringify([`draft-content`,t.id])},contentRevisions:{...e.contentRevisions,[t.content.name]:1}}})}),Ar=f.z.object({...K,type:f.z.literal(`remove_view_content`)}).strict(),jr=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:Ar,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 Mr=f.z.object({...K,type:f.z.literal(`move_view_content`),placement:f.z.enum([`main`,`aside`]).describe(`The placement zone to move the content into`),target:Cr.describe(`Where to place the content within that placement zone`)}).strict(),Nr=defineOperation({type:`move_view_content`,summary:`Reorders or moves a content to a different placement; the aside rule applies.`,schema:Mr,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)}}})}),Pr=f.z.object({...G,type:f.z.literal(`update_view_metadata`),changes:f.z.object({label:f.z.string().min(1).optional().describe(`New label for the view`),description:f.z.string().optional().describe(`New description for the view`),icon:e.W.nullable().optional().describe(`New icon; null clears it`)}).strict().refine(e=>Object.keys(e).length>0).describe(`≥1 change`)}).strict(),Fr=defineOperation({type:`update_view_metadata`,summary:`Updates a view's label, description, or icon (null clears the icon).`,schema:Pr,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}})}),Ir=f.z.string().refine(e=>e.trim().length>0,`API name must not be blank`),Lr=f.z.object({...G,type:f.z.literal(`rename_view`),newName:Ir.describe(`New API name for the view`)}).strict(),renameViewFocus=e=>({objectName:e.objectName,viewName:e.newName}),Rr=defineOperation({type:`rename_view`,summary:`Renames a view; refused on a code-declared name — change it in the declaration.`,schema:Lr,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}))}),zr=f.z.object({...K,type:f.z.literal(`rename_view_content`),newName:Ir.describe(`New API name for the content`)}).strict(),renameContentFocus=e=>({...viewFocus(e),contentName:e.newName}),Br=defineOperation({type:`rename_view_content`,summary:`Renames a content; refused on a code-declared name — change it in the declaration.`,schema:zr,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}}})}),Vr=f.z.object({...K,type:f.z.literal(`reset_view_content`)}).strict(),Hr=defineOperation({type:`reset_view_content`,summary:`Resets a content to its code-declared source, if one exists.`,schema:Vr,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}})})}),Ur=f.z.object({...G,type:f.z.literal(`reset_view_order`),placement:f.z.enum([`main`,`aside`]).describe(`The placement zone to reset to source order`)}).strict(),Wr=defineOperation({type:`reset_view_order`,summary:`Resets a placement zone's order to its code-declared source, if one exists.`,schema:Ur,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}})}),Gr=f.z.discriminatedUnion(`type`,[Tr,Or,Ar,Mr,Pr,Lr,zr,Vr,Ur]),q=[Dr,kr,jr,Nr,Fr,Rr,Br,Hr,Wr];function findObject(e,t){return e.objects.find(e=>e.id===t)}const Kr=new Set([`formula`,`rollup`]);function isComputedAttribute(e){return Kr.has(e.attributeType)}const qr={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 qr?qr[e]:void 0}function requireObject(e,t){let n=findObject(e,t);if(!n)throw new DraftRefusalError(`Object "${t}" is not in the draftable state`,W);return n}function configOf(e){return e.config??{}}function relationTargets(e){let t=configOf(e).targets;return Array.isArray(t)?t.filter(e=>typeof e==`object`&&!!e&&typeof e.object==`string`):[]}function relationTargetObjectName(e){let t=relationTargets(e).filter(e=>e.object!==`*`);return t.length===1?t[0]?.object:void 0}function toCompileAttribute(e){let t=configOf(e),n=e.attributeType,r={name:e.name,type:n,id:e.id},i=t.optionsSource;if(n===`relation`){let n=relationTargetObjectName(e);return{...r,...t.cardinality===`one`||t.cardinality===`many`?{cardinality:t.cardinality}:{},...n===void 0?{}:{targetObjectName:n},targets:relationTargets(e)}}if(n===`formula`)return{...r,...t.returnType===void 0?{}:{returnType:t.returnType},...i===void 0?{}:{optionsSource:i}};if(n===`rollup`){let e=rollupReturnTypeOf(t.function);return{...r,...e===void 0?{}:{returnType:e},...i===void 0?{}:{optionsSource:i}}}return n===`select`||n===`status`||n===`multiselect`?{...r,...Array.isArray(t.options)?{options:t.options}:{}}:r}function toCompileObject(e,t){return{objectName:e.name,attributes:t.filter(t=>t.objectId===e.id).map(toCompileAttribute)}}function computedCompileSchemaOf(e,t){return{...toCompileObject(requireObject(e,t),e.attributes),relatedObjects:Object.fromEntries(e.objects.map(t=>[t.name,toCompileObject(t,e.attributes)]))}}function toRollupAttribute(e){return{id:e.id,name:e.name,label:e.label,type:`rollup`,...configOf(e)}}function asValidationError(e){try{return e()}catch(e){throw e instanceof ComputedFormulaCompileError?new n.ValidationError(e.message,[]):e}}function computedPlanOf(e,t){let n=computedCompileSchemaOf(e,t.objectId);return asValidationError(()=>compilePlan(t,n))}function compilePlan(e,t){if(e.attributeType===`rollup`)return compileRollupAttribute(toRollupAttribute(e),t);let n=configOf(e);return compileComputedFormula({attributeName:e.name,expression:String(n.expression??``),returnType:n.returnType,schema:t})}function assertAcyclicComputed(e){asValidationError(()=>assertAcyclicComputedDependencies(e.map(e=>({attributeName:e.attributeName,dependencies:e.dependencies}))))}function dependencyNames(e,t){switch(e.kind){case`local`:case`computed`:return e.attributeName===t;case`relation`:return e.relationName===t;case`options`:return!1;default:return e}}function compilablePlansOf(e,t){let n=computedCompileSchemaOf(e,t),r=[];for(let i of e.attributes)if(i.objectId===t&&isComputedAttribute(i))try{r.push(compilePlan(i,n))}catch(e){if(!(e instanceof ComputedFormulaCompileError))throw e}return r}function dependentsOf(e,t,n){let r=requireObject(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 Jr={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,Jr,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 r=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 n.ValidationError(r,[])}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 r=bilateralDeclarationOf(e);if(r===void 0||untouched(e))continue;let i=t.objects.find(t=>t.id===e.objectId)?.name??e.objectId,a=t.objects.find(e=>e.name===r.object),o=t.attributes.find(e=>e.objectId===a?.id&&e.name===r.attribute),s=`relation "${i}.${e.name}" declares inverse "${r.object}.${r.attribute}"`;if(o===void 0)throw new n.ValidationError(`${s}, which object "${r.object}" does not have; draft it first`,[]);if(o.attributeType!==`relation`)throw new n.ValidationError(`${s}, which is not a relation`,[]);let c=bilateralDeclarationOf(o);if(!(relationTargets(o).some(e=>e.object===i)&&(untouched(o)?c===void 0||c.object===i&&c.attribute===e.name:c?.object===i&&c.attribute===e.name)))throw new n.ValidationError(`${s}, which does not point back to "${i}.${e.name}"`,[])}}function fnv1a64(e,t){let n=t;for(let t of new TextEncoder().encode(e))n^=BigInt(t),n=n*1099511628211n&18446744073709551615n;return n}function viewIdFor(e,t){return draftEntityIdFor(t,e.toLowerCase())}function draftEntityIdFor(e,t){let n=`${t}:${e}`,r=fnv1a64(n,14695981039346656037n).toString(16).padStart(16,`0`)+fnv1a64(`${e}:${n}`,9521211207457086692n).toString(16).padStart(16,`0`),i=(Number.parseInt(r[16],16)&3|8).toString(16);return[r.slice(0,8),r.slice(8,12),`8${r.slice(13,16)}`,`${i}${r.slice(17,20)}`,r.slice(20,32)].join(`-`)}function defaultViewIdsFor(e){return{list:viewIdFor(e,`list`),detail:viewIdFor(e,`detail`)}}function derivedView(e,n,r,i){let a=i.filter(e=>e.objectId===r.id).filter(e=>t.rt(toAttribute(e)).presentation.formField).map(e=>({attribute:e.name})),o=e===`collection`?[{name:`all`,type:`collection`,placement:`main`,label:`All`,layout:`table`,source:{object:r.name}}]:a.length?[{name:`form`,type:`form`,placement:`main`,label:`Details`,groups:[{name:`general`,label:`General`,fields:a}]}]:[{name:`activity`,type:`activity`,placement:`main`,label:`Activity`}];return{id:n,object:r.name,name:e===`collection`?`default_list`:`default_detail`,label:r.label,context:e,default:!0,contents:o,authoring:workspaceViewAuthoring(o),revision:1,contentIds:Object.fromEntries(o.map(e=>[e.name,JSON.stringify([`draft-content`,n,e.name])])),contentRevisions:Object.fromEntries(o.map(e=>[e.name,1])),derived:!0}}function defaultViewsFor(e,t){let n=defaultViewIdsFor(e.id);return[derivedView(`collection`,n.list,e,t),derivedView(`record`,n.detail,e,t)]}function 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,r,i,a=!1){let o=toAttribute(t),s=i&&toAttribute(i),c=i&&bilateralDeclarationOf(i),l=bilateralDeclarationOf(t);if(c&&(c.object!==l?.object||c.attribute!==l?.attribute))throw new n.ValidationError(`Changing a bilateral address requires removing the existing pair first`,[]);if(o.type!==`relation`||!o.bilateral)return e;let u=e.objects.find(e=>e.id===t.objectId),d=e.objects.find(e=>e.name===o.bilateral?.object);if(!(u&&d))throw new n.ValidationError(`Both objects must exist before materializing a relation pair`,[]);let f=`${u.name}.${t.name}`,p=o.bilateral.attribute,m=`${d.name}.${p}`,h=e.attributes.find(e=>e.objectId===d.id&&e.name===p),g=s?.metadata?.relationPairId,_=typeof g==`string`?g:draftEntityIdFor(`relation-pair`,`${r}:${t.id}`),v=[f,m].sort(),y=typeof g==`string`?{id:_,addresses:v,ownerAddress:s?.type===`relation`&&s.bilateral?.storageOwner===!1?m:f,generatedAddresses:[],...f===m?{symmetric:!0}:{}}:void 0,b=reconcileRelationAttributes({objects:[...new Map([u,d].map(e=>[e.id,e])).values()].map(e=>({name:e.name,attributes:[t,...h&&h.id!==t.id?[h]:[]].filter(t=>t.objectId===e.id).map(toAttribute)})),existingPairs:y?[y]:[],...i&&!a?{explicitAddresses:[f],propertyEditAddresses:[f]}:{},nextPairId:()=>_}),x=new Map;for(let n of b.objects){let r=n.name===u.name?u.id:d.id;for(let o of n.attributes){let n=e.attributes.find(e=>e.objectId===r&&e.name===o.name),s=n?.id===t.id?i??n:n,c={...preserveDeclarationHints(o,n&&toAttribute(n)),metadata:{...o.metadata,...s&&isGeneratedDraftRelation(s)&&!(a&&n?.id===t.id)||!n?{relationGenerated:!0}:{}},id:n?.id??draftEntityIdFor(`relation-attribute`,`${_}:${r}:${o.name}`),...n?{}:{order:e.attributes.filter(e=>e.objectId===r).length}};x.set(`${r}.${o.name}`,toDraftableAttribute(c,r))}}let S=e.attributes.map(e=>{let t=`${e.objectId}.${e.name}`,n=x.get(t);return x.delete(t),n??e});return S.push(...x.values()),{...e,attributes:S,views:e.views.map(e=>{let t=[u,d].find(t=>t.name===e.object);return e.derived&&t?regenerateDerived(e,t,S):e})}}function preserveDeclarationHints(e,t){if(e.type!==`relation`||!e.bilateral||t?.type!==`relation`||!t.bilateral)return e;let{label:n,cardinality:r,...i}=e.bilateral;return{...e,bilateral:{...i,...t.bilateral.label===void 0?{}:{label:n},...t.bilateral.cardinality===void 0?{}:{cardinality:r}}}}function 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,r){let i=r.config??{},a=r.name;if(i.relationPath!==void 0)throw new n.ValidationError(`rollup "${a}": relationPath is not supported yet`,[]);let o=i.relationAttribute;if(typeof o!=`string`||o.length===0)throw new n.ValidationError(`rollup "${a}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let s=e.attributes.find(e=>e.objectId===t.id&&e.name===o&&e.attributeType===`relation`);if(!s)throw new n.ValidationError(`rollup "${a}" needs a relation attribute; "${o}" is not a relation of object "${t.name}"`,[]);let c=relationTargetObjectName(s);if(c===void 0){let e=relationTargets(s).filter(e=>e.object!==`*`).length;throw new n.ValidationError(`rollup "${a}" needs a relation with one target object; "${o}" targets ${e}`,[])}if(i.function===`count`)return;let l=e.objects.find(e=>e.name===c),u=i.targetAttribute;if(u===void 0)throw new n.ValidationError(`rollup "${a}" needs a targetAttribute: "${i.function}" aggregates one attribute of object "${c}"`,[]);if(!(l!==void 0&&e.attributes.some(e=>e.objectId===l.id&&e.name===u)))throw new n.ValidationError(`rollup "${a}" targets attribute "${u}", which object "${c}" does not have`,[])}function traversesRelation(e,t){let n=e.config??{};if(e.attributeType===`rollup`)return n.relationAttribute===t;let r=typeof n.expression==`string`?n.expression:``;return RegExp(`(^|[^A-Za-z0-9_])${t}\\.`).test(r)}function assertConfigFolds(e,t){let r=requireObject(e,t.objectId);if(t.attributeType===`relation`){for(let r of relationTargets(t))if(r.object!==`*`&&!e.objects.some(e=>e.name===r.object))throw new n.ValidationError(`object "${r.object}" is unknown; create it first`,[]);let r=bilateralDeclarationOf(t)?.object;if(r!==void 0&&r!==`*`&&!e.objects.some(e=>e.name===r))throw new n.ValidationError(`object "${r}" is unknown; create it first`,[]);for(let n of e.attributes)n.objectId===t.objectId&&isComputedAttribute(n)&&traversesRelation(n,t.name)&&computedPlanOf(e,n)}else if(isComputedAttribute(t))t.attributeType===`rollup`&&assertRollupShape(e,r,t),computedPlanOf(e,t);else return;assertAcyclicComputed(compilablePlansOf(e,t.objectId))}const J={...Sr,objectId:f.z.string().uuid().describe(`The object this operation acts on`)},Yr=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:f.z.object({...J,objectId:f.z.string().uuid().describe(`Stable id for the new object; the server mints one when omitted`),type:f.z.literal(`add_object`),name:e.M.describe("kebab-case plural API name (`purchase-orders`)"),label:f.z.string().min(1).describe(`Label people see`),icon:f.z.string().min(1).optional().describe(`Icon name`)}),apply:(e,t)=>{if(e.objects.some(e=>e.name===t.name))throw new n.ValidationError(`Object "${t.name}" already exists`,[]);if(e.objects.some(e=>e.id===t.objectId))throw new n.ValidationError(`Object id "${t.objectId}" is already taken`,[]);let r={id:t.objectId,name:t.name,label:t.label,...t.icon===void 0?{}:{icon:t.icon}};return{...e,objects:[...e.objects,r],views:[...e.views,...emptyDraftViewsFor(r)]}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Crée l'objet « ${e.label} »`}),Xr=f.z.object({...J,type:f.z.literal(`update_object`),changes:f.z.object({label:f.z.string().min(1).optional().describe(`New label`),icon:f.z.string().min(1).optional().describe(`New icon name from search_icons`),pluralLabel:f.z.string().optional().describe(`New label for many records; "" clears it`),description:f.z.string().optional().describe(`What this object holds`),labelExpression:E.optional().describe(`Titles every record; syntax in <expressions>`),embeddingExpression:f.z.literal(``).or(E).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}),Zr=defineOperation({type:`update_object`,summary:`Updates an object's label, icon, pluralLabel, description, labelExpression, embeddingExpression.`,schema:Xr,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)}),Qr={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])=>Qr[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 $r=defineOperation({type:`remove_object`,summary:`Removes an object; refused while a relation attribute targets it — remove it first.`,schema:f.z.object({...J,type:f.z.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}`}),ei=t.J;function assertConfigParses(t,r){try{e.l(t,r)}catch(e){throw e instanceof n.ValidationError?new n.ValidationError(e.message,e.errors.map(e=>({...e,path:[`config`,...e.path??[]]}))):e}}const ti=f.z.object({...J,type:f.z.literal(`add_attribute`),attributeId:f.z.string().min(1),name:e.j,label:f.z.string().min(1),attributeType:f.z.enum(ei),config:f.z.record(f.z.string(),f.z.unknown()).optional()}).superRefine((e,t)=>{try{assertConfigParses(e.attributeType,e.config??{})}catch(e){if(e instanceof n.ValidationError){for(let n of e.errors)t.addIssue({code:`custom`,message:n.message,path:[...n.path]});return}throw e}}),ni=e.j.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),ri={...Sr,type:f.z.literal(`add_attribute`),attributeId:f.z.string().min(1).describe(`Stable attribute id`),name:ni,label:f.z.string().min(1).describe(`Label people see`)},ii=Object.fromEntries(e.r.map(e=>[e,!0]));function wireWriteConfigOf(t){let n=e.o(t).omit(ii),r=e.n[t];return r===void 0?n:n.extend(r)}const Y=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],ai=f.z.object(Y.reduce((e,t)=>(Object.assign(e,wireWriteConfigOf(t).shape),e),{})).strict(),oi=ei.filter(e=>!Y.includes(e)),si=Object.fromEntries(Y.map(e=>[e,new Set(Object.keys(wireWriteConfigOf(e).shape))])),ci=e.h(si,`config key`);function refuseForeignSimpleConfigKeys(e,t){ci(e.attributeType,e.config,t,[`config`])}function wireConfigFor(t){let n=wireWriteConfigOf(t);return(t===`relation`||t===`document`?n.extend({properties:e.m.optional()}):n).strict()}const li=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:ti,wire:f.z.discriminatedUnion(`attributeType`,[f.z.object({...ri,objectId:f.z.string().uuid(),attributeType:f.z.enum(Y).describe(`Attribute type`),config:ai.optional().describe(`Configuration of a simple attribute (text, number, date…)`)}).strict().superRefine(refuseForeignSimpleConfigKeys),...oi.map(e=>f.z.object({...ri,objectId:f.z.string().uuid(),attributeType:f.z.literal(e).describe(`Attribute type`),config:wireConfigFor(e).optional().describe(`Configuration of a ${e} attribute`)}).strict())]),apply:(e,t)=>{let r=requireObject(e,t.objectId),i=e.attributes.find(e=>e.objectId===t.objectId&&e.name===t.name);if(i&&!isGeneratedDraftRelation(i))throw new n.ValidationError(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let a={id:i?.id??t.attributeId,objectId:t.objectId,name:t.name,label:t.label,attributeType:t.attributeType,...t.config===void 0?{}:{config:t.config}};for(let n of e.sampleRecords)n.objectId===t.objectId&&assertRequiredCovered(n.id,a,n.values);let o=withDerivedViews(e,r,i?e.attributes.map(e=>e===i?a:e):[...e.attributes,a]);return assertConfigFolds(o,a),reconcileDraftRelationAttribute(o,a,t.id,i,!0)},focus:attributeFocus,presentation:definePresentation(attributeFocus,`local`),describe:e=>`Ajoute l'attribut « ${e.label} »`}),ui={...J,attribute:e.j.describe(`The attribute's API name on this object`)};function requireAttribute(e,t,r,i){let a=requireObject(e,t);if(r===void 0)throw new n.ValidationError(`${i} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let o=e.attributes.find(e=>e.objectId===t&&e.name===r);if(!o)throw new DraftRefusalError(`Attribute "${r}" is not on object "${t}"`,W);return{object:a,attribute:o}}const di=f.z.object({...ui,type:f.z.literal(`update_attribute`),changes:f.z.object({label:f.z.string().min(1).optional().describe(`New label`),config:f.z.record(f.z.string(),f.z.unknown()).optional().describe(`Whole config, replaced — same shape as add_attribute`),icon:e.W.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 fi=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:di,apply:(e,t)=>{let{object:r,attribute:i}=requireAttribute(e,t.objectId,t.attribute,`update_attribute`),{icon:a,config:o,...s}=t.changes;if(a!==void 0&&i.attributeType!==`relation`){let e=`icon is only for relation attributes; "${i.name}" is a ${i.attributeType} attribute`;throw new n.ValidationError(e,[{path:[`changes`,`icon`],message:e}])}o!==void 0&&assertConfigParses(i.attributeType,o);let c=updatedAttributeConfig(i.config,{config:o,icon:a}),l={...i,...s,...c===void 0?{}:{config:c}},u=withDerivedViews(e,r,e.attributes.map(e=>e===i?l:e));return assertConfigFolds(u,l),reconcileDraftRelationAttribute(u,l,t.id,i)},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} »`}),pi=f.z.object({...ui,type:f.z.literal(`remove_attribute`),dropSampleValues:f.z.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 mi=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:pi,apply:(e,t)=>{let{attribute:r}=requireAttribute(e,t.objectId,t.attribute,`remove_attribute`),i=pairedDraftAttributes(e,r);for(let r of i){let[i]=dependentsOf(e,r.objectId,r.name);if(i!==void 0)throw new n.ValidationError(`attribute "${r.name}" is used by "${i}"; remove that first`,[]);let a=e.sampleRecords.find(e=>e.objectId===r.objectId&&r.name in e.values);if(a&&!t.dropSampleValues)throw new n.ValidationError(`Attribute "${r.name}" is still used by sample record "${a.id}" — resend with dropSampleValues: true to clear it from the samples`,[])}let a=e.attributes.filter(e=>!i.includes(e)),o={...e,views:cascadeAttributeRemoval(e,i),sampleRecords:t.dropSampleValues?e.sampleRecords.map(e=>withoutRemovedValues(e,i)):e.sampleRecords};return i.reduce((t,n)=>withDerivedViews(t,requireObject(e,n.objectId),a),o)},focus:existingAttributeFocus,presentation:definePresentation(existingAttributeFocus,`local`),describe:e=>`Supprime l'attribut « ${e.attribute} »`}),hi=f.z.object({...ui,type:f.z.literal(`rename_draft_attribute`),name:ni});function assertRenamable(e,t,r){let i=r.name,[a]=dependentsOf(e,t.id,i),o=e.attributes.find(e=>{let n=e.config?.optionsSource;return n?.objectName===t.name&&n.attributeName===i}),s=a??(o&&`${e.objects.find(e=>e.id===o.objectId)?.name}.${o.name}`);if(s!==void 0)throw new n.ValidationError(`attribute "${i}" is used by "${s}"; it cannot be renamed while in use`,[]);let c=bilateralDeclarationOf(r),l=e.attributes.find(e=>{let n=bilateralDeclarationOf(e);return n?.object===t.name&&n.attribute===i}),u=c===void 0?l&&`${e.objects.find(e=>e.id===l.objectId)?.name}.${l.name}`:`${c.object}.${c.attribute}`;if(u!==void 0)throw new n.ValidationError(`attribute "${i}" is paired with "${u}"; unpair it first`,[]);let d=[[`label expression`,t.labelExpression],[`embedding expression`,t.embeddingExpression]];for(let[e,r]of d)if(r&&extractAttributeNames(r).includes(i))throw new n.ValidationError(`attribute "${i}" is used by the ${e} of "${t.name}"; change it first`,[]);for(let r of e.views){let a=unrenamableUse(e,r,t.name,i);if(a!==void 0)throw new n.ValidationError(`attribute "${i}" is used by view "${r.id}" (${a}); rename it before using it there`,[])}}const gi=defineOperation({type:`rename_draft_attribute`,summary:`Renames a draft-added attribute; views and samples follow.`,schema:hi,apply:(e,t)=>{let{object:r,attribute:i}=requireAttribute(e,t.objectId,t.attribute,`rename_draft_attribute`);if(t.name===i.name)throw new n.ValidationError(`attribute "${t.attribute}" is already named "${t.name}"`,[]);if(e.attributes.some(e=>e.objectId===t.objectId&&e.name===t.name))throw new n.ValidationError(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);assertRenamable(e,r,i);let a={...i,name:t.name},o=e.attributes.map(e=>e===i?a:e);return withDerivedViews({...e,views:e.views.map(n=>renameAttributeInView(e,n,r.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}})},r,o)},focus:attributeFocus,presentation:definePresentation(attributeFocus,`local`),describe:e=>`Renomme le nom technique « ${e.attribute} » en « ${e.name} »`});function assertSampleValue(e,t,r,i){let a=toAttribute(r);try{d.d(a)}catch{return}let o=d.i(a,i);if(o.success)return;let s=o.errors??[],c=`Sample record "${e}" has an invalid value for "${t}": ${s.map(e=>e.path.length>1?`${e.path.join(`.`)}: ${e.message}`:e.message).join(`, `)}`,l=s.map(e=>({path:e.path,message:e.message}));throw r.attributeType===`relation`&&carriesNonRecordId(i)?new DraftRefusalError(c,{kind:`sample-relation-value`},l):new n.ValidationError(c,l)}function assertRequiredCovered(e,t,r){if(t.config?.required===!0&&t.config?.defaultValue===void 0&&!(t.name in r&&r[t.name]!==void 0))throw new n.ValidationError(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}const _i=f.z.guid();function carriesNonRecordId(e){let t=Array.isArray(e)?e:[e],n=relationValueIds(e);return n.length<t.length||n.some(e=>!_i.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 vi=defineOperation({type:`add_sample_record`,summary:`Adds a sample record; keys are attribute names, required covered, computed never set; relation value is a minted/published recordId; publication is preview or requested-data.`,schema:f.z.object({...J,type:f.z.literal(`add_sample_record`),recordId:f.z.string().uuid().describe(`Minted by the server when omitted`),values:f.z.record(f.z.string(),f.z.unknown()).describe("Attribute name → value; currency is `{code,value}`, relation is a record id or name minted here"),publication:f.z.enum([`preview`,`requested-data`]).optional().describe(`preview = display-only; requested-data = real records asked for`)}),apply:(e,t)=>{let r=requireObject(e,t.objectId);if(e.sampleRecords.some(e=>e.id===t.recordId))throw new n.ValidationError(`Sample record "${t.recordId}" already exists`,[]);let i=new Map(e.attributes.filter(e=>e.objectId===t.objectId).map(e=>[e.name,e]));for(let[a,o]of Object.entries(t.values)){let s=i.get(a);if(!s)throw new DraftRefusalError(`Sample record "${t.recordId}" uses unknown attribute "${a}"`,{kind:`sample-unknown-attribute`,objectName:r.name,attributeNames:[...i.keys()]});if(isComputedAttribute(s))throw new n.ValidationError(`attribute "${s.name}" is computed and cannot be set on a sample record`,[]);assertUnknownSampleReference(e,t.recordId,s,o),assertSampleValue(t.recordId,a,s,o)}for(let e of i.values())assertRequiredCovered(t.recordId,e,t.values);return{...e,sampleRecords:[...e.sampleRecords,{id:t.recordId,objectId:t.objectId,values:t.values,...t.publication===void 0?{}:{publication:t.publication}}]}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Ajoute un exemple`});function relationNamesOf(e,t){return new Set([...e.attributes.filter(e=>e.objectId===t&&e.attributeType===`relation`).map(e=>e.name)])}function assertSampleNotReferenced(e,t){for(let r of e.sampleRecords){if(r.id===t)continue;let i=relationNamesOf(e,r.objectId);for(let[e,a]of Object.entries(r.values))if(i.has(e)&&relationValueIds(a).includes(t))throw new n.ValidationError(`sample record "${t}" is referenced by sample record "${r.id}"; remove that first`,[])}}const X=[Yr,Zr,$r,li,fi,mi,gi,vi,defineOperation({type:`remove_sample_record`,summary:`Removes a sample record; refused while another sample references it.`,schema:f.z.object({...J,type:f.z.literal(`remove_sample_record`),recordId:f.z.string().min(1).describe(`recordId of the sample to remove`)}),apply:(e,t)=>{if(!e.sampleRecords.some(e=>e.id===t.recordId&&e.objectId===t.objectId))throw new DraftRefusalError(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,W);return assertSampleNotReferenced(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(e=>e.id!==t.recordId)}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Retire un exemple`})];function build(){let e=new Map;for(let t of[...X,...q]){if(e.has(t.type))throw new n.DuplicateError(`architect operation`,t.type);e.set(t.type,t)}return e}const Z=build(),yi=[...Z.keys()];function defOf(e){let t=Z.get(e.type);if(!t)throw new n.ValidationError(`Operation "${e.id}" has unknown type "${e.type}"`,[]);return t}function applyOperations(e,t,n={extensions:[]}){return t.reduce((e,t)=>defOf(t).apply(e,t,n),e)}function focusOf(e){return defOf(e).focus(e)}function describeOperations(e,t){return e.map(e=>defOf(e).describe(e,t))}function parseOperation(e){if(typeof e!=`object`||!e||!(`type`in e))throw new n.ValidationError(`An operation must be an object carrying a type`,[]);let t=e.type;if(typeof t!=`string`)throw new n.ValidationError(`An operation's type must be a string`,[]);let r=Z.get(t);if(!r)throw new n.ValidationError(`Unknown operation type "${t}"`,[]);let i=r.schema.safeParse(e);if(!i.success)throw new n.ValidationError(`Operation "${t}" is invalid: ${i.error.issues.map(e=>`${e.path.join(`.`)} ${e.message}`).join(`; `)}`,[]);return i.data}const bi=`bilateral`;function frozenPart(e){if(!e||typeof e!=`object`)return c.s({});let{[bi]:t,...n}=e;return c.s(n)}function isPublishedConfigChangeAllowed(e,t){return frozenPart(e)===frozenPart(t)}const pair=e=>f.z.tuple([f.z.literal(e),f.z.string()]),xi=f.z.union([f.z.tuple([f.z.literal(`content`),f.z.string(),f.z.string(),f.z.string()]),f.z.tuple([f.z.literal(`view`),f.z.string(),f.z.string()]),f.z.tuple([f.z.literal(`attribute`),f.z.string(),f.z.string()]),f.z.tuple([f.z.literal(`sample`),f.z.string(),f.z.string()]),pair(`object`),pair(`object-name`),pair(`object-schema`),pair(`object-tree`),pair(`attribute-id`)]);function proposalTargetKey(e){return e.viewName&&e.objectName?JSON.stringify(e.contentName?[`content`,e.objectName,e.viewName,e.contentName]:[`view`,e.objectName,e.viewName]):e.attributeName&&e.objectId?JSON.stringify([`attribute`,e.objectId,e.attributeName]):e.attributeId?JSON.stringify([`attribute-id`,e.attributeId]):e.recordId&&e.objectId?JSON.stringify([`sample`,e.objectId,e.recordId]):e.objectId?JSON.stringify([`object`,e.objectId]):e.objectName?JSON.stringify([`object-name`,e.objectName]):null}function addContentDependencies(e,t,n,r){if(n&&typeof n==`object`){if(`source`in n&&n.source&&typeof n.source==`object`){let i=collectionSourceAddressOf(n.source);if(i&&i.kind!==`related`&&r(i.object),i?.kind===`related`){let n=i.relation;r(t);let a=e.objects.find(e=>e.name===t),o=e.attributes.find(e=>e.objectId===a?.id&&e.name===n);if(o?.attributeType===`relation`&&Array.isArray(o.config?.targets))for(let e of o.config.targets)e&&typeof e.object==`string`&&e.object!==`*`&&r(e.object)}}else`type`in n&&n.type===`forms`?r(`objectName`in n&&typeof n.objectName==`string`?n.objectName:t):`type`in n&&[`form`,`richtext`,`emails`,`meetings`,`documents`].includes(String(n.type))&&r(t)}}function addBilateralDependencies(e,t,n,r,i){if([`add_attribute`,`update_attribute`,`remove_attribute`].includes(t.type)){let a=e.attributes.find(e=>e.objectId===n.objectId&&e.name===n.attributeName),o=r&&typeof r==`object`&&`bilateral`in r?r.bilateral:a?.config?.bilateral;if((t.attributeType===`relation`||a?.attributeType===`relation`)&&o&&typeof o==`object`&&`object`in o&&typeof o.object==`string`){n.objectId&&i(`object-tree`,n.objectId);let t=e.objects.find(e=>e.name===o.object);t?i(`object-tree`,t.id):i(`object-name`,o.object)}}}function 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=Gr.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:${c.s(e)}`}const Si=targetTokenOf(null);function isCurrentTargetToken(e){return e?.startsWith(`v2:`)??!1}function targetTokensFor(e,t){return Object.fromEntries(t.map(t=>[t,targetTokenOf(targetSnapshot(e,t))]))}function targetSnapshot(e,t){let r;try{r=JSON.parse(t)}catch{throw new n.ValidationError(`Invalid proposal target key "${t}"`,[])}let i=xi.safeParse(r);if(!i.success)throw new n.ValidationError(`Invalid proposal target key "${t}"`,[]);let[a,o,s,c]=i.data,l=e.objects.find(e=>e.id===o);if(a===`object`)return l??null;if(a===`object-name`)return e.objects.find(e=>e.name===o)??null;if(a===`attribute-id`)return e.attributes.find(e=>e.id===o)??null;if(a===`attribute`)return e.attributes.find(e=>e.objectId===o&&e.name===s)??null;if(a===`sample`)return e.sampleRecords.find(e=>e.objectId===o&&e.id===s)??null;if(a===`object-schema`||a===`object-tree`){if(!l)return null;let t=e.attributes.filter(e=>e.objectId===o);return a===`object-schema`?{object:l,attributes:t.toSorted((e,t)=>e.name.localeCompare(t.name))}:{object:l,attributes:t,views:e.views.filter(e=>e.object===l.name),sampleRecords:e.sampleRecords.filter(e=>e.objectId===o)}}let u=e.views.find(e=>e.object===o&&e.name===s);if(!u)return null;if(a===`view`)return{id:u.id,revision:u.revision,definition:{...draftedViewDefinition(u),contents:u.contents.map(({name:e,placement:t})=>({name:e,placement:t}))}};let d=u.contents.find(e=>e.name===c);return c!==void 0&&Object.hasOwn(u.contentIds,c)?{id:u.contentIds[c],revision:u.contentRevisions[c],definition:d??null}:null}function presentationOf(e){return defOf(e).presentation(e)}function episodeImpactOf(e){let t=e.map(presentationOf);return new Set(t.map(({focus:e})=>e.viewName?JSON.stringify([e.objectName,e.viewName]):e.objectId).filter(e=>e!==void 0)).size>1||t.some(({impact:e})=>e===`structural`)?`structural`:t.some(({impact:e})=>e===`local`)?`local`:`atomic`}function snapshotArchitectTarget(e,t){let n=proposalTargetKey(t);return n===null?null:targetSnapshot(e,n)}function deriveArchitectChanges(e,t,n={extensions:[]}){let r=e;return t.map(e=>{let t=presentationOf(e),i=snapshotArchitectTarget(r,t.focus);r=applyOperations(r,[e],n);let a=snapshotArchitectTarget(r,t.focus);return{operationId:e.id,operationType:e.type,presentation:t,before:i,after:a,...e.note===void 0?{}:{note:e.note}}})}function part(e){return e.replace(/[%:/.]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function architectFocusKey(e){let t=headOf(e);if(t===null)return null;let n=e.propertyPath??[];return n.length===0?t:`${t}/${n.map(part).join(`.`)}`}function 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 Ci={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`},wi=`normal`;function operationPace(e){return Object.hasOwn(Ci,e)?Ci[e]:wi}const Ti={major:{replay:4e3,live:2500},normal:{replay:2600,live:1800},minor:{replay:1400,live:1100}};function dwellForStep(e,t,n){let r=(Ti[e]??Ti[wi])[t],i=900+40*(n||0);return Math.min(6e3,Math.max(r,i))}const Q=f.z.string().min(1),Ei=f.z.union([f.z.object({objectName:Q,viewName:Q,contentName:Q.optional()}).strict().describe(`Full configuration of a view, or of one content when contentName is given`),f.z.object({objectId:Q}).strict().describe(`An object with its attributes, by id`),f.z.object({objectName:Q}).strict().describe(`An object with its attributes`),f.z.object({objectId:Q,attributeName:Q}).strict().describe(`One attribute's config, by name`),f.z.object({objectId:Q,attributeId:Q}).strict().describe(`One attribute's config, by id`),f.z.object({objectId:Q,recordId:Q}).strict().describe(`One sample record`)]);function parseNamedTarget(e){let t=Ei.safeParse(e);if(!t.success)throw new n.ValidationError(`Invalid scoped target`,[{path:[`target`],message:`Expected exactly one named target branch`}]);return t.data}const Di=f.z.object({type:f.z.literal(`remove_operation`),operationId:f.z.string().min(1).describe(`The id of a stored operation to drop from the draft`)});function membersOf(e,t=[]){return[...e.map(e=>e.schema),...t].map(relaxUuidKeys)}function describeMember(e,t){return mapMember(e,e=>e.describe(t))}function wireMembersOf(e,t=[]){return[...e.map(e=>e.wire??e.schema),...t].map(relaxUuidKeys).map(relaxMintedKeys).map(addressByName).map((t,n)=>{let r=e[n];return r===void 0?t:describeMember(t,r.summary)})}function unionOf(e){return f.z.discriminatedUnion(`type`,e)}function isUuidString(e){return e instanceof f.z.ZodString&&e.format===`uuid`}function asUnionMember(e){let t=e;return!Array.isArray(t.options)||typeof t.def?.discriminator!=`string`?null:{discriminator:t.def.discriminator,options:t.options}}function mapMember(e,t){let n=asUnionMember(e);return n===null?t(e):f.z.discriminatedUnion(n.discriminator,n.options.map(t))}function relaxUuidKeys(e){return mapMember(e,e=>{let t={};for(let[n,r]of Object.entries(e.shape)){if(!isUuidString(r))continue;let e=f.z.string().min(1);t[n]=r.description===void 0?e:e.describe(r.description)}return Object.keys(t).length===0?e:e.safeExtend(t)})}const Oi={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of Oi[e.shape.type.value]??[]){let r=e.shape[n];r instanceof f.z.ZodString&&(t[n]=r.optional())}return Object.keys(t).length===0?e:e.safeExtend(t)})}function withOriginalChecks(e,t){let n=e._zod.def.checks;return!n||n.length===0?t:t.check(...n)}const ki=f.z.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,f.z.object({...n,objectName:ki}).strict())})}const Ai=membersOf(X,[Di]),ji=membersOf(q),Mi=unionOf(Ai),Ni=unionOf(ji),Pi={schema:Mi,view:Ni},Fi={schema:unionOf(wireMembersOf(X,[Di])),view:unionOf(wireMembersOf(q))},Ii=new Map([...X.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...q.map(e=>[e.type,`view`])]);function familyOf(e){return Ii.get(e)??null}function viewsOf(e,t,n){return e.views.filter(e=>e.object===t.name&&e.context===n)}function collectionContentsOf(e,t){return viewsOf(e,t,`collection`).flatMap(e=>e.contents).filter(e=>e.type===`collection`)}function ownAttributes(e,t){return e.attributes.filter(e=>e.objectId===t.id)}function isTableCell(e){return t.rt(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 n.ValidationError(`View "${e.name}" names an object outside the draft scope`,[]);return{id:e.id,name:e.name,context:e.context,objectName:e.object,label:e.label,derived:e.derived===!0,contents:e.contents.map(({name:e,type:t,placement:n,label:r})=>({name:e,type:t,placement:n,label:r}))}}function summarizeDraft(e,t){let n=new Map;for(let t of e.sampleRecords)n.set(t.objectId,(n.get(t.objectId)??0)+1);return{objects:e.objects.map(t=>summarizeObject(t,e.attributes,e.views)),views:e.views.map(t=>summarizeView(t,e.objects)),sampleRecords:[...n.entries()].map(([e,t])=>({objectId:e,count:t})),operationCount:t}}const Li=[`draft_schema`],Ri=[{input:{operations:[{type:`add_attribute`,id:`op-statut`,objectName:`devis`,attributeId:`attr-statut`,name:`statut`,label:`Statut`,attributeType:`select`,config:{options:[{value:`draft`,label:`Brouillon`,color:`gray`},{value:`sent`,label:`Envoyé`,color:`blue`},{value:`accepted`,label:`Accepté`,color:`green`}]}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:`add_view_content`,id:`op-open`,objectName:`devis`,viewName:`default_list`,content:{name:`open`,label:`À traiter`,type:`collection`,placement:`main`,layout:`table`,source:{object:`devis`},columns:[`title`,`client`,`montant`,`statut`],filters:{combinator:`and`,rules:[{attribute:`statut`,operator:`is`,value:`sent`}]},sorts:[{attribute:`montant`,direction:`desc`}]},target:{end:!0}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:`replace_view_content`,id:`op-all`,objectName:`devis`,viewName:`default_list`,contentName:`all`,definition:{name:`all`,type:`collection`,placement:`main`,layout:`table`,source:{object:`devis`},columns:[`title`,`client`,`montant`,`statut`]}}],guard:{revision:null,targetTokens:{}}}}],$=f.z.string().refine(e=>e.trim().length>0,`Must not be blank`),zi=f.z.union([f.z.tuple([f.z.literal(`object`),$]),f.z.tuple([f.z.literal(`attribute`),$,$]),f.z.tuple([f.z.literal(`view`),$,$]),f.z.tuple([f.z.literal(`content`),$,$,$])]),Bi=f.z.object({label:$,pluralLabel:f.z.string().optional(),description:f.z.string().optional(),icon:e.W.optional(),labelExpression:f.z.string(),embeddingExpression:f.z.string().optional(),sealed:f.z.boolean().optional(),toleratedAttributes:f.z.array($).optional(),metadata:f.z.record(f.z.string(),f.z.unknown()).optional(),documentLayout:f.z.record(f.z.string(),f.z.unknown()).optional()}).strict();function failure(e){throw new n.ValidationError(e,[])}function definitionSchema(n){return f.z.custom(r=>{let i=f.z.record(f.z.string(),f.z.unknown()).parse(r);for(let e of n[0]===`view`?[`object`,`name`]:[`name`])Object.hasOwn(i,e)&&failure(`Invalid schema state: unrecognized definition key ${e}`);switch(n[0]){case`object`:Bi.parse(i);break;case`attribute`:{let n=f.z.enum(t.J).parse(i.type);e.a(n).extend({type:f.z.literal(n),label:$,required:f.z.boolean().optional(),unique:f.z.boolean().optional(),icon:e.W.optional()}).strict().parse(i);break}case`view`:{let{contents:e,...r}=i,a=f.z.array($).parse(e);new Set(a).size!==a.length&&failure(`Invalid schema state: duplicate content membership`),t.o.parse({...r,object:n[1],name:n[2],contents:[]});break}case`content`:t.l.parse({...i,name:n[3]})}return!0})}function compareSchemaStateEntries(e,t){let n=JSON.stringify(e.address),r=JSON.stringify(t.address);return n<r?-1:+(n>r)}function schemaStateSourcePayload(e){return{modelVersion:1,hashVersion:1,entries:[...e].sort(compareSchemaStateEntries).filter(e=>e.source!==null).map(({address:e,source:t})=>({address:e,source:t}))}}function parseState(e){let t=f.z.record(f.z.string(),f.z.unknown()).parse(e);for(let[e,n]of[[`modelVersion`,`model`],[`hashVersion`,`hash`]])t[e]!==1&&failure(`Unsupported schema ${n} version: expected 1, received ${t[e]===void 0?`missing`:String(t[e])}`);let r=f.z.object({modelVersion:f.z.literal(1),hashVersion:f.z.literal(1),tenant:$,sourceFingerprint:f.z.string().regex(/^[a-f0-9]{64}$/),entries:f.z.array(f.z.unknown())}).strict().safeParse(e);if(!r.success){let e=r.error.issues.find(e=>e.code===`unrecognized_keys`);throw e?.code===`unrecognized_keys`&&failure(`Invalid schema state: unrecognized key ${e.keys[0]}`),n.ValidationError.fromZodErrors(r.error.issues.map(e=>({path:e.path.map(String),message:e.message})))}let i=new Set,a=r.data.entries.map(e=>{let t=zi.parse(f.z.object({address:f.z.unknown()}).parse(e).address),n=JSON.stringify(t);i.has(n)&&failure(`Invalid schema state: duplicate address ${n}`),i.add(n);let r=definitionSchema(t).nullable(),a=t[0]===`object`||t[0]===`attribute`?f.z.object({id:f.z.string().uuid(),updatedAt:f.z.string().datetime()}).strict():f.z.object({id:f.z.string().uuid(),revision:f.z.number().int().nonnegative()}).strict(),o=f.z.object({address:zi,source:r,effective:r,status:f.z.enum([`source`,`runtime`,`copy`,`suppressed`]),sourceOwner:f.z.union([f.z.literal(`core`),f.z.string().regex(/^(bundle|source):.+$/)]).nullable(),guard:a.nullable()}).strict().parse(e);(o.status===`runtime`&&(o.source!==null||o.effective===null||o.sourceOwner!==null)||o.status===`suppressed`&&(t[0]!==`content`||o.source===null||o.effective!==null||o.guard===null)||o.status===`copy`&&(o.source===null||o.effective===null)||o.effective!==null&&o.guard===null||o.source===null&&o.effective===null)&&failure(`Invalid schema state: inconsistent status at ${n}`);let s=o.sourceOwner;s!==null&&s!==`core`&&!s.startsWith(`bundle:`)&&!s.startsWith(`source:`)&&failure(`Invalid source owner`);let c=s===null||s===`core`?s:s.startsWith(`bundle:`)?`bundle:${s.slice(7)}`:`source:${s.slice(7)}`;return{...o,sourceOwner:c}});return{...r.data,entries:a.sort(compareSchemaStateEntries)}}function parseSchemaState(e){try{return parseState(e)}catch(e){throw e instanceof f.z.ZodError?n.ValidationError.fromZodErrors(e.issues.map(e=>({path:e.path.map(String),message:e.message}))):e}}function diffSchemaState(e){let t=[];for(let n of[...e.entries].sort(compareSchemaStateEntries)){let e=n.source===null?`added`:n.status===`suppressed`?`suppressed`:n.effective===null?`removed`:c.s(n.source)===c.s(n.effective)?n.status===`copy`?`copied`:null:`changed`;e&&t.push({...n,change:e})}return{modelVersion:1,tenant:e.tenant,sourceFingerprint:e.sourceFingerprint,changes:t}}exports.ABSENT_TARGET_TOKEN=Si,exports.AGENT_AVATAR_EXPRESSIONS=ve,exports.AGENT_AVATAR_TYPES=_e,exports.AGENT_MESSAGE_KIND=Ce,exports.AGENT_NOTIFICATION_KIND=Se,exports.AGENT_STARTERS_MAX=4,exports.AGENT_STARTER_MAX_LENGTH=200,exports.AGENT_TASK_KINDS=fe,exports.AGENT_UI_BATCH_MAX_BYTES=204800,exports.AGENT_UI_BATCH_MAX_ITEMS=256,exports.ALLOWED_PROPERTY_TYPES=Ye,exports.ALL_OPERATION_TYPES=yi,exports.ALL_PIPES=T,exports.ARTIFACT_FILE_ROLES=Ie,exports.ARTIFACT_KINDS=Pe,exports.ARTIFACT_LIST_VIEW=Ut,exports.ARTIFACT_OBJECT=Vt,exports.ARTIFACT_OBJECT_NAME=P,exports.ARTIFACT_PREVIEW_EXTENSION=Bt,exports.ARTIFACT_RETENTIONS=Fe,exports.ARTIFACT_VIEW=Ht,exports.ATTRIBUTE_FILTER_OPERATORS=t.tt,exports.ATTRIBUTE_TYPES=t.J,exports.AUDIT_ACTIONS=ie,exports.AUDIT_AGENT_SESSION_METADATA_KEY=`agentSessionId`,exports.AUDIT_RESOURCE_TYPES=re,exports.AccessDeniedError=n.AccessDeniedError,exports.AgentBuilder=AgentBuilder,exports.AmbiguousSchemaChangeError=n.AmbiguousSchemaChangeError,exports.AttributeInUseError=n.AttributeInUseError,exports.AttributeNotFoundError=n.AttributeNotFoundError,exports.BEHAVIOR_PROPERTIES=te,exports.BROWSER_IMAGE_MAX_BYTES=15e4,exports.BYTE_UNIT_LABELS=qe,exports.CATALOG_RESOURCES=ct,exports.CLAIMABLE_SESSION_STATUSES=oe,exports.COMPUTED_FUNCTIONS=e.O,exports.COMPUTED_FUNCTION_METADATA=xn,exports.COMPUTED_FUNCTION_NAMES=e.k,exports.CONNECTOR_CALLBACK_PARAM=Dn,exports.COUNT_MODES=Ge,exports.CUSTOM_LEVEL=st,exports.ComputedFormulaCompileError=ComputedFormulaCompileError,exports.ComputedFormulaParseError=e.E,exports.ConcurrentModificationError=n.ConcurrentModificationError,exports.ContentBuilder=j,exports.DB_COLUMN_FIELDS=ft,exports.DEFAULT_AGENT_EXECUTION_CONFIG=xt,exports.DEFAULT_APPROVAL_POLICY=se,exports.DEFAULT_DAILY_ACTIVITY_DAYS=182,exports.DEFAULT_DICTATION_LIMITS=Ee,exports.DEFAULT_LABEL_FALLBACK=et,exports.DEFAULT_MEETING_BOT_DISPLAY_NAME=Be,exports.DEFAULT_ROLES=pt,exports.DEFAULT_ROLE_DESCRIPTIONS=ht,exports.DEFAULT_ROLE_LABELS=mt,exports.DEFAULT_ROLE_PERMISSIONS=_t,exports.DEFAULT_ROLE_REVOCATIONS=vt,exports.DEFAULT_TENANT_SETTINGS=Ve,exports.DEFAULT_VALIDATION_MESSAGES=i.n,exports.DEVICE_CHANNEL_AUTHENTICATE_TIMEOUT_MS=1e4,exports.DEVICE_CHANNEL_IDLE_POLL_MS=2e3,exports.DEVICE_CHANNEL_KEEPALIVE_MS=2e4,exports.DEVICE_CHANNEL_MAX_FRAME_BYTES=262144,exports.DEVICE_CHANNEL_PATH=De,exports.DEVICE_CHANNEL_PRESENCE_MS=2e3,exports.DEVICE_CHANNEL_UPGRADE_REQUIRED_REASON=`UPGRADE_REQUIRED`,exports.DEVICE_CHANNEL_WORKER_CLOSE_PROTOCOL_VIOLATION=4008,exports.DEVICE_COMMAND_ERROR_CODES=ke,exports.DICTATION_FINALIZATION_TIMEOUT_MS=5e3,exports.DICTATION_FRAME_BYTES=3200,exports.DICTATION_MAX_BUFFER_BYTES=16e3,exports.DICTATION_MAX_FRAME_BYTES=6400,exports.DICTATION_MAX_TRANSCRIPT_BYTES=65536,exports.DICTATION_MODEL_ID=`google/gemini-3.5-transcribe-live`,exports.DICTATION_PREPARATION_TIMEOUT_MS=1e4,exports.DICTATION_SAMPLE_RATE=16e3,exports.DICTATION_TICKET_TTL_MS=15e3,exports.DISCARD_ARCHITECT_DRAFT_TOOL_NAME=`discard_architect_draft`,exports.DOCUMENT_SYSTEM_ATTRIBUTES=Je,exports.DRAFTABLE_ATTRIBUTE_TYPES=ei,exports.DRAFT_BATCH_LIMIT=12,exports.DRAFT_OBJECT_SETTINGS=xr,exports.DRAFT_SCHEMA_INPUT_EXAMPLES=Ri,exports.DRAFT_WRITE_TOOL_NAMES=Li,exports.DRIVE_LIST_VIEW=zt,exports.DRIVE_OBJECT=Lt,exports.DRIVE_OBJECT_NAME=N,exports.DRIVE_VIEW=Rt,exports.DeviceChannelProtocolError=DeviceChannelProtocolError,exports.DeviceChannelServerFrameSchema=Ne,exports.DeviceChannelWorkerFrameSchema=Me,exports.DraftRefusalError=DraftRefusalError,exports.DuplicateError=n.DuplicateError,exports.EMPTY_VALUE_PLACEHOLDER=`—`,exports.ESTIMATED_COUNT_CAP=1e4,exports.FAKE_MEETING_BOT_SIGNATURE_HEADER=`x-fake-signature`,exports.FAMILY_INPUTS=Pi,exports.FAMILY_WIRE_INPUTS=Fi,exports.FORM_FORBIDDEN_ATTRIBUTE_TYPES=Le,exports.FlagRegistry=FlagRegistry,exports.FlagService=FlagService,exports.ForbiddenError=n.ForbiddenError,exports.FormBuilder=FormBuilder,exports.FormRegistry=FormRegistry,exports.FormRowBuilder=FormRowBuilder,exports.FormStepBuilder=FormStepBuilder,exports.GET_ARCHITECT_DRAFT_TOOL_NAME=`get_architect_draft`,exports.GroupBuilder=wt,exports.IDENTITY_PROPERTIES=C,exports.IMAGE_FORMATS=We,exports.INFERENCE_REASONING_OPTIONS=de,exports.INFERENCE_ROUTING_MODES=me,exports.INFERENCE_SPEEDS=ue,exports.INVENTORY_LIMIT=30,exports.InvalidPermissionGrantError=n.InvalidPermissionGrantError,exports.LAST_RUN_ERROR_MAX_LENGTH=200,exports.LIST_VIEW_TAB_VISIBILITIES=e.K,exports.LIVE_EVENT_TYPES=un,exports.LOCATION_FILTER_PROPERTIES=t.nt,exports.MAILBOX_LIST_MODES=An,exports.MAIL_DRAFT_BODY_MAX_CHARS=2e5,exports.MAIL_SUBJECT_MAX_CHARS=998,exports.MAX_DAILY_ACTIVITY_DAYS=366,exports.MAX_PRESET_DEPTH=5,exports.MAX_TODOS=50,exports.MAX_TODO_DESCRIPTION_CHARS=500,exports.MAX_TODO_ID_CHARS=80,exports.MEETING_ATTRIBUTES=I,exports.MEETING_DETAIL_VIEW_ID=Kt,exports.MEETING_LIST_VIEW=Xt,exports.MEETING_LIST_VIEW_ID=Wt,exports.MEETING_OBJECT=Jt,exports.MEETING_OBJECT_NAME=F,exports.MEETING_VIEW=Yt,exports.MEETING_WRITE_SOURCE=Gt,exports.MEMORY_LIST_VIEW=It,exports.MEMORY_OBJECT=Nt,exports.MEMORY_VIEW=Ft,exports.MIXED_LEVEL=dt,exports.McpOAuthCompletionMode=On,exports.MemoryNotFoundError=n.MemoryNotFoundError,exports.MultiRelationAttributeBuilder=MultiRelationAttributeBuilder,exports.NATIVE_AGENT_UI_PART_IDS_METADATA_KEY=Te,exports.NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION=1,exports.NATIVE_OBJECT_NAMES=e.Q,exports.NOTIFICATION_INBOX_STATES=v,exports.NOTIFICATION_KINDS=h,exports.NOTIFICATION_PRIORITIES=g,exports.NOTIFICATION_SENSITIVITIES=_,exports.NOTIFICATION_TYPES_V1=ee,exports.NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED=S,exports.NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN=b,exports.NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED=x,exports.NOTIFICATION_WORK_STATES=y,exports.NO_ACCESS=ot,exports.NO_RECORDING=Pn,exports.NO_VALUE_OPERATORS=t.W,exports.NonJsonValueError=c.o,exports.NoopGeocodingAdapter=NoopGeocodingAdapter,exports.NotFoundError=n.NotFoundError,exports.NotImplementedError=n.NotImplementedError,exports.OBJECT_GRANT=D,exports.OBJECT_NAME_SCHEMA=e.M,exports.OPEN_TOOL_PART_STATES=be,exports.OPERATION_PACE=Ci,exports.OPERATION_REGISTRY=Z,exports.OPERATORS_BY_TYPE=t.G,exports.OPERATOR_SPECS=L,exports.ObjectBuilder=ObjectBuilder,exports.ObjectNotFoundError=n.ObjectNotFoundError,exports.ObjectReferencedError=n.ObjectReferencedError,exports.OrphanSystemAttributeError=n.OrphanSystemAttributeError,exports.PACE_DWELL_MS=Ti,exports.PERMISSION_ACTIONS=k,exports.PERMISSION_CAPABILITIES=O,exports.PERMISSION_CATALOG=at,exports.PIPES_WITH_ARGS=$e,exports.PREFERRED_NAME_MAX_LENGTH=80,exports.PRESENTATION_PROPERTIES=ne,exports.PROVIDER_DRAFT_LABEL=kn,exports.PROVIDER_NAMES=le,exports.PUBLISHED_CONFIG_EXCEPTION=bi,exports.ProtectedResourceError=n.ProtectedResourceError,exports.ProtectedRoleError=n.ProtectedRoleError,exports.QUALIFIED_SEPARATOR=t.V,exports.QUOTA_KEYS=Ke,exports.RECENT_ACTIVITY_LEDGER_LIMIT=50,exports.RECORDING_OVERRIDES=Mn,exports.RECORDING_POLICIES=Nn,exports.RECORD_ACCESS_ROLES=Re,exports.RECORD_ACCESS_SOURCES=ze,exports.RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY=it,exports.RELATION_TARGET_ANY=t.Y,exports.REMOVED_OPERATOR_REPLACEMENTS=t.d,exports.REMOVE_OPERATION_SCHEMA=Di,exports.REPLY_MODES=jn,exports.REQUEST_DESIGN_REVIEW_TOOL_NAME=`request_design_review`,exports.RESERVED_ATTRIBUTE_NAMES=e.q,exports.RESERVED_OBJECT_NAMES=e.J,exports.RESOURCE_VISIBILITIES=e.Y,exports.ROUTING_PRICE_CEILINGS=he,exports.RealtimeDeliveryError=n.RealtimeDeliveryError,exports.RealtimeRateLimitedError=n.RealtimeRateLimitedError,exports.RealtimeSubscriptionError=n.RealtimeSubscriptionError,exports.RecordNotFoundError=n.RecordNotFoundError,exports.RecordReferencedError=n.RecordReferencedError,exports.RepositoryError=n.RepositoryError,exports.ReservedObjectNameError=n.ReservedObjectNameError,exports.RoleNotFoundError=n.RoleNotFoundError,exports.SCHEMA_LIMITS=e.G,exports.SCHEMA_OPERATIONS=X,exports.SCHEMA_OPERATION_INPUT=Mi,exports.SCHEMA_SOURCE_ID_PATTERN=R,exports.SCHEMA_SOURCE_RETYPE_FROM=In,exports.SESSION_INFERENCE_PATCH_KEYS=ge,exports.SESSION_STATE_STREAM_ID=`session-state`,exports.SESSION_TERMINAL_STATUSES=ae,exports.SIMPLE_PIPES=Qe,exports.SIMPLE_PROPERTY_TYPES=e.t,exports.SKILL_CONTENT_TEMPLATE=kt,exports.SKILL_LIST_VIEW=Mt,exports.SKILL_OBJECT=At,exports.SKILL_VIEW=jt,exports.STANDARD_SCHEMA_VENDOR=St,exports.SYNONYM_ALIASES=t.y,exports.SYSTEM_ATTRIBUTES=t.dt,exports.SYSTEM_ATTRIBUTE_I18N_KEYS=t.ft,exports.SYSTEM_FIELD_NAMES=e.X,exports.SYSTEM_FILTER_ATTRIBUTE_TYPES=t.f,exports.SYSTEM_PART_CODES=xe,exports.SchemaError=n.SchemaError,exports.SchemaErrorCode=n.SchemaErrorCode,exports.SearchBackendError=n.SearchBackendError,exports.SingleRelationAttributeBuilder=SingleRelationAttributeBuilder,exports.StorageError=n.StorageError,exports.SyncCascadeError=n.SyncCascadeError,exports.SyncConflictError=n.SyncConflictError,exports.SyncError=n.SyncError,exports.SystemEntityImmutableError=n.SystemEntityImmutableError,exports.TASK_DEMAND_LEVELS=pe,exports.TENANT_INVITATION_DEFAULT_TTL_MS=6048e5,exports.TENANT_INVITATION_MAX_TTL_MS=2592e6,exports.TENANT_INVITATION_MIN_TTL_MS=36e5,exports.TENANT_INVITATION_RESEND_INTERVAL_MS=6e4,exports.TEXT_FORMAT_PATTERNS=r.n,exports.TODAY_DEFAULT=`today`,exports.TODO_PLAN_STATUSES=ce,exports.TODO_STATUSES=we,exports.TOOL_APPROVAL_STATES=ye,exports.TOOL_NAME_SEPARATOR=`__`,exports.USER_STATUSES=He,exports.USER_WORK_POSTURES=Ue,exports.VIEW_OPERATIONS=q,exports.VIEW_OPERATION_INPUT=Ni,exports.ValidationError=n.ValidationError,exports.ViewBuilder=Ct,exports.WIRE_OMITTED_CONFIG_KEYS=e.r,exports.WORKSTATION_HARNESSES=yt,exports.agent=agent,exports.agentAvatarFromMetadata=agentAvatarFromMetadata,exports.agentAvatarSchema=lr,exports.agentDataChunk=agentDataChunk,exports.agentDisplayName=agentDisplayName,exports.agentInferencePreferencesSchema=qn,exports.agentMessageAttachmentSchema=er,exports.agentMessagePartSchema=$n,exports.agentSessionInferenceOverridesInputSchema=Jn,exports.agentSessionInferenceOverridesSchema=Yn,exports.agentSessionMessageSchema=ar,exports.agentStartersSchema=ur,exports.agentUIValidationError=agentUIValidationError,exports.applyOperations=applyOperations,exports.applyPipes=applyPipes,exports.applyRelationProps=applyRelationProps,exports.architectContentBodyKey=architectContentBodyKey,exports.architectDraftChannelKey=architectDraftChannelKey,exports.architectFocusCandidates=architectFocusCandidates,exports.architectFocusKey=architectFocusKey,exports.artifactQuoteSchema=tr,exports.asTenantId=c.t,exports.asUserId=c.n,exports.assertAcyclicComputed=assertAcyclicComputed,exports.assertAcyclicComputedDependencies=assertAcyclicComputedDependencies,exports.assertBilateralPairs=assertBilateralPairs,exports.assertCustomAgentUIMessageChunk=assertCustomAgentUIMessageChunk,exports.assertSchemaSourceId=assertSchemaSourceId,exports.assertSchemaSourceResolutions=assertSchemaSourceResolutions,exports.attributeConfigSchemas=e.i,exports.attributeFilterTarget=t.S,exports.attributeInventory=attributeInventory,exports.bilateralDeclarationOf=bilateralDeclarationOf,exports.booleanFlag=booleanFlag,exports.buildAgentFallbackTitle=buildAgentFallbackTitle,exports.buildPermissionFlags=buildPermissionFlags,exports.buildPropertySchema=buildPropertySchema,exports.buildQualifiedAttribute=t.H,exports.canCopyRole=canCopyRole,exports.canGrantLevel=canGrantLevel,exports.canGrantPurge=canGrantPurge,exports.canonicalStringify=c.s,exports.canonicalViewOperationSchema=Gr,exports.canonicalizeFilterValue=t.k,exports.capabilityForResource=capabilityForResource,exports.capped=capped,exports.catalogEmbeddingSchema=yr,exports.catalogImageModelSchema=catalogImageModelSchema,exports.catalogTextModelSchema=catalogTextModelSchema,exports.checkbox=checkbox,exports.chosenUserName=chosenUserName,exports.cleanContent=cleanContent,exports.collectContentViewCatalogue=collectContentViewCatalogue,exports.collectQualifiedRuleIssues=t.p,exports.collectSchemaReferences=collectSchemaReferences,exports.collectionContentSourceSchema=t.t,exports.collectionContentsOf=collectionContentsOf,exports.collectionSourceAddress=collectionSourceAddress,exports.collectionSourceAddressOf=collectionSourceAddressOf,exports.colorIdSchema=e.U,exports.columnsSchema=t.n,exports.compareAgentSessionMessages=compareAgentSessionMessages,exports.compareSchemaStateEntries=compareSchemaStateEntries,exports.compilablePlansOf=compilablePlansOf,exports.compileComputedFormula=compileComputedFormula,exports.compileRollupAttribute=compileRollupAttribute,exports.computeByteMagnitude=computeByteMagnitude,exports.computeReconnectDelay=computeReconnectDelay,exports.computeRetryDelay=computeRetryDelay,exports.computedCompileSchemaOf=computedCompileSchemaOf,exports.computedPlanOf=computedPlanOf,exports.content=M,exports.contentDefinition=contentDefinition,exports.contentExtensionRegistry=en,exports.contentNamesAttribute=contentNamesAttribute,exports.contentViewDefinitionSchema=t.r,exports.contentViewDefinitionSchemaFor=t.i,exports.conversationDisplayTitle=conversationDisplayTitle,exports.convertRetypedValue=convertRetypedValue,exports.createCheckboxValidator=o.createCheckboxValidator,exports.createDateValidator=s.createDateValidator,exports.createFlagRegistry=createFlagRegistry,exports.createFlagService=createFlagService,exports.createFormAttributeValidator=d.f,exports.createNumberValidator=a.createNumberValidator,exports.createStandardSchemaProps=createStandardSchemaProps,exports.createTextValidator=r.t,exports.currency=currency,exports.currentActor=t.I,exports.customDataChunkSchemas=cr,exports.date=date,exports.dateInTimezone=dateInTimezone,exports.dateValueStart=e.B,exports.declaredImageRequests=declaredImageRequests,exports.decodeDeploymentBarrierAttestationV1=decodeDeploymentBarrierAttestationV1,exports.deepEqual=c.r,exports.defaultViewIdsFor=defaultViewIdsFor,exports.defaultViewsFor=defaultViewsFor,exports.defineDeviceChannelFrames=defineDeviceChannelFrames,exports.defineOperation=defineOperation,exports.definePresentation=definePresentation,exports.dependentsOf=dependentsOf,exports.deriveArchitectChanges=deriveArchitectChanges,exports.deriveCreateDefaultsFromFilters=deriveCreateDefaultsFromFilters,exports.deriveInitials=deriveInitials,exports.deriveViewerAccess=deriveViewerAccess,exports.describeOperations=describeOperations,exports.detailView=detailView,exports.deviceChannelUrl=deviceChannelUrl,exports.diffSchemaState=diffSchemaState,exports.displayAttributesSchema=t.a,exports.document=document,exports.draftContentViewDefinitionSchema=t.o,exports.draftContentViewDefinitionSchemaFor=t.s,exports.draftListedObjectResolver=draftListedObjectResolver,exports.draftObjectSettings=draftObjectSettings,exports.draftedLabelExpression=draftedLabelExpression,exports.draftedObjectDefinition=draftedObjectDefinition,exports.draftedViewDefinition=draftedViewDefinition,exports.durableDateSchema=ir,exports.dwellForStep=dwellForStep,exports.edgePropertyFilterTarget=t.C,exports.episodeImpactOf=episodeImpactOf,exports.evaluateComputedAst=e.x,exports.evaluateComputedFormula=e.S,exports.evaluateComputedFormulaWithResult=e.C,exports.evaluateFilterState=evaluateFilterState,exports.evaluateRecordFilterState=evaluateRecordFilterState,exports.exceptionLevels=exceptionLevels,exports.extractAttributeNames=extractAttributeNames,exports.extractCurrencyFilterValue=t.P,exports.extractFilterValue=t.F,exports.extractTouchedArtifacts=extractTouchedArtifacts,exports.extractTouchedDocuments=extractTouchedDocuments,exports.extractTouchedRecords=extractTouchedRecords,exports.extractValueRefs=extractValueRefs,exports.familyOf=familyOf,exports.filterOperatorsOfType=t.w,exports.filterStateSchema=t.c,exports.filterTargetsOf=t.T,exports.findGrantIssues=findGrantIssues,exports.findModelByReference=findModelByReference,exports.findRelationAttribute=findRelationAttribute,exports.findWorkstationHarness=findWorkstationHarness,exports.flagRegistry=Tt,exports.focusOf=focusOf,exports.form=form,exports.formFieldFlatKey=formFieldFlatKey,exports.formFieldKey=formFieldKey,exports.formRegistry=tn,exports.formatAgentStreamFrameId=formatAgentStreamFrameId,exports.formatAttributeValue=formatAttributeValue,exports.formatByteSize=formatByteSize,exports.formatComputedResult=e.w,exports.formatLocationValue=formatLocationValue,exports.formatZodErrors=i.t,exports.formula=formula,exports.fromDraftableView=fromDraftableView,exports.generateId=c.i,exports.getAttributeCapabilities=t.rt,exports.getAttributeFilterOperators=t.it,exports.getEditableLabelAttribute=getEditableLabelAttribute,exports.getErrorMessage=getErrorMessage,exports.getLiveProtocolPayloadChannel=getLiveProtocolPayloadChannel,exports.getOperatorPolarity=t.A,exports.getRecordCreatorPrincipalId=getRecordCreatorPrincipalId,exports.getRollupFilterOperators=t.K,exports.getSingleAttributeFromExpression=getSingleAttributeFromExpression,exports.getSlotFieldTargets=getSlotFieldTargets,exports.getSystemAttributeI18nKey=t.pt,exports.getSystemAttributeList=t.mt,exports.getUserDisplayName=getUserDisplayName,exports.grantCovers=grantCovers,exports.grantsFromLevels=grantsFromLevels,exports.group=group,exports.guidanceForBatch=guidanceForBatch,exports.hasOptions=hasOptions,exports.iconNameSchema=e.W,exports.imageModelFormatDefect=imageModelFormatDefect,exports.imageModelIdSchema=U,exports.inboundRelationAttributes=inboundRelationAttributes,exports.includesAction=includesAction,exports.indexBy=c.a,exports.inferInverseCardinality=t.X,exports.inferRollupReturnType=inferRollupReturnType,exports.inferenceReasoningSchema=V,exports.inferenceRoutingSchema=H,exports.inferenceSpeedSchema=B,exports.isAgentMessageMetadata=isAgentMessageMetadata,exports.isAgentNotificationMetadata=isAgentNotificationMetadata,exports.isAgentUIDataName=isAgentUIDataName,exports.isAgentUIMessageBatch=isAgentUIMessageBatch,exports.isAgentWrittenAuditEntry=isAgentWrittenAuditEntry,exports.isAttributeFilterable=t.at,exports.isAttributeGroupable=t.ot,exports.isAttributeInUseError=n.isAttributeInUseError,exports.isAttributeKanbanGroupable=t.st,exports.isAttributeSearchable=t.ct,exports.isAttributeSortable=t.Z,exports.isBilateralRelation=t.Q,exports.isCalendarDay=t.B,exports.isCatalogResource=isCatalogResource,exports.isCheckboxEquality=isCheckboxEquality,exports.isClaimableSessionStatus=isClaimableSessionStatus,exports.isComputedAttribute=isComputedAttribute,exports.isComputedFunctionName=e.A,exports.isCurrentTargetToken=isCurrentTargetToken,exports.isDateRangeValue=e.V,exports.isDefaultRole=isDefaultRole,exports.isDocumentAttribute=isDocumentAttribute,exports.isDynamicValue=t.L,exports.isEdgePayload=isEdgePayload,exports.isEmptyObject=isEmptyObject,exports.isFormDefinition=isFormDefinition,exports.isFormFieldsRow=isFormFieldsRow,exports.isFormFreeFieldRef=isFormFreeFieldRef,exports.isFormHeadingRow=isFormHeadingRow,exports.isFormSeparatorRow=isFormSeparatorRow,exports.isFormSlotFieldRef=isFormSlotFieldRef,exports.isFormTextRow=isFormTextRow,exports.isLabelExpression=isLabelExpression,exports.isLiveEventEnvelope=isLiveEventEnvelope,exports.isLiveEventPayload=isLiveEventPayload,exports.isLiveEventPayloadForType=isLiveEventPayloadForType,exports.isLiveEventType=isLiveEventType,exports.isLocationFilterProperty=t.lt,exports.isLocationPartOperator=t.E,exports.isMailProvider=isMailProvider,exports.isMailboxListMode=isMailboxListMode,exports.isManagedSystemAttribute=t.ht,exports.isNativeObjectName=e.$,exports.isNoValueOperator=t.q,exports.isNotEmpty=isNotEmpty,exports.isNotFoundError=n.isNotFoundError,exports.isNullishOrEmptyString=l.t,exports.isObjectReferencedError=n.isObjectReferencedError,exports.isOpenToolPartState=isOpenToolPartState,exports.isPlainRecord=e.T,exports.isProtectedResourceError=n.isProtectedResourceError,exports.isProviderDraft=isProviderDraft,exports.isPublishedConfigChangeAllowed=isPublishedConfigChangeAllowed,exports.isRecordReferencedError=n.isRecordReferencedError,exports.isRelativeDateValue=t.h,exports.isReplyMode=isReplyMode,exports.isRoleLabelTaken=isRoleLabelTaken,exports.isRoutableModel=isRoutableModel,exports.isRoutineActorMetadata=isRoutineActorMetadata,exports.isSchemaError=n.isSchemaError,exports.isSetMembershipOperator=t.j,exports.isStandardSchema=isStandardSchema,exports.isSystemPartCode=isSystemPartCode,exports.isTerminalSessionStatus=isTerminalSessionStatus,exports.isTerminalState=isTerminalState,exports.isToolApprovalState=isToolApprovalState,exports.isUnderRoutingCeiling=isUnderRoutingCeiling,exports.isUniversalRelation=t.$,exports.isValidationError=n.isValidationError,exports.isValuePresent=l.n,exports.isWorkstationHarnessId=isWorkstationHarnessId,exports.jsonFlag=jsonFlag,exports.legacyStatusToSessionState=legacyStatusToSessionState,exports.levelActions=levelActions,exports.levelOf=levelOf,exports.listView=listView,exports.listedObjectWithoutCatalogue=listedObjectWithoutCatalogue,exports.liveChannelKey=liveChannelKey,exports.location=location,exports.locationPartFilterTarget=t.D,exports.markdownToPlainText=markdownToPlainText,exports.matchesAccepts=matchesAccepts,exports.mentionReferenceSchema=nr,exports.modelDefinitionSchema=rr,exports.modelReferenceSchema=Kn,exports.modelReferenceSpellings=modelReferenceSpellings,exports.multiselect=multiselect,exports.multiselectOptionWriteSchema=e.s,exports.namedTargetSchema=Ei,exports.nativeAgentUIPartIdMetadataKey=nativeAgentUIPartIdMetadataKey,exports.nonOperationalDeploymentBarrierAttestorV1=ln,exports.normalizeDateValue=e.H,exports.normalizeFilterRule=t.b,exports.normalizeForEdgeRpc=t.M,exports.normalizeOperator=t.x,exports.normalizePricing=normalizePricing,exports.normalizeRoleGrants=normalizeRoleGrants,exports.normalizeRoleLabel=normalizeRoleLabel,exports.now=t.R,exports.number=number,exports.numberFlag=numberFlag,exports.object=object,exports.objectPermissionFlags=objectPermissionFlags,exports.operationPace=operationPace,exports.orderAgentSessionMessages=orderAgentSessionMessages,exports.parseAgentStreamFrameId=parseAgentStreamFrameId,exports.parseAttributeConfig=e.c,exports.parseAttributeConfigForCreate=e.l,exports.parseAttributeConfigForUpdate=e.u,exports.parseComputedFormula=e.D,exports.parseCountMode=parseCountMode,exports.parseDeviceChannelFrame=parseDeviceChannelFrame,exports.parseFilterInstant=parseFilterInstant,exports.parseLiveChannelKey=parseLiveChannelKey,exports.parseModelCatalog=parseModelCatalog,exports.parseNamedTarget=parseNamedTarget,exports.parseNativeAgentUIPartIdsMetadata=parseNativeAgentUIPartIdsMetadata,exports.parseOperation=parseOperation,exports.parseOptionalCountMode=parseOptionalCountMode,exports.parseQualifiedAttribute=t.U,exports.parseQualifiedToolName=parseQualifiedToolName,exports.parseRecordAccessRole=parseRecordAccessRole,exports.parseResourceVisibility=e.Z,exports.parseSchemaGroupPresentation=parseSchemaGroupPresentation,exports.parseSchemaState=parseSchemaState,exports.parseServerFrame=parseServerFrame,exports.parseWorkerFrame=parseWorkerFrame,exports.permissionGrantSchema=ut,exports.phone=phone,exports.planAttributeRemoval=planAttributeRemoval,exports.presentationOf=presentationOf,exports.pricePerMillion=pricePerMillion,exports.propertyAttributeSchema=e.d,exports.propertyAttributeWireSchema=e.f,exports.propertySchemaSchema=e.p,exports.propertySchemaWireSchema=e.m,exports.proposalTargetKey=proposalTargetKey,exports.providerNameSchema=Gn,exports.publishedViewContentDefinitionSchema=t.l,exports.qualifiedPropertyDefs=qualifiedPropertyDefs,exports.qualifiedToolName=qualifiedToolName,exports.readAccessLevels=readAccessLevels,exports.readArtifactResult=readArtifactResult,exports.readFormFieldValue=readFormFieldValue,exports.readGeneratedImageResult=readGeneratedImageResult,exports.readRoleLevels=readRoleLevels,exports.recentActivityEntryKey=recentActivityEntryKey,exports.reconcileRelationAttributes=reconcileRelationAttributes,exports.refuseForeignKeys=e.h,exports.regenerateDerived=regenerateDerived,exports.registry=Dt,exports.rejectUnknownAttributesOrThrow=d.r,exports.relation=relation,exports.relationAcceptsObject=relationAcceptsObject,exports.relationProperty=relationProperty,exports.relationPropertyDefs=relationPropertyDefs,exports.relationTargetObjectName=relationTargetObjectName,exports.relationTargets=relationTargets,exports.relationTargetsOf=t.et,exports.relationValueIds=relationValueIds,exports.removeObjectException=removeObjectException,exports.renameAttributeInContent=renameAttributeInContent,exports.renamedFromTarget=renamedFromTarget,exports.renderLabelExpression=renderLabelExpression,exports.requestedCapabilities=requestedCapabilities,exports.requireRecordContentContext=requireRecordContentContext,exports.requireSingleRelationTarget=requireSingleRelationTarget,exports.requiredTargetKeys=requiredTargetKeys,exports.resolveAttributeDefaultValue=resolveAttributeDefaultValue,exports.resolveCollectionActions=resolveCollectionActions,exports.resolveContentNavigation=resolveContentNavigation,exports.resolveEffectiveFilterType=t.ut,exports.resolveFieldRequired=resolveFieldRequired,exports.resolveIsWithinBounds=t.g,exports.resolvePropertyDefinitions=resolvePropertyDefinitions,exports.resolveTextPattern=r.r,exports.resolveUtcDayBounds=t._,exports.resolveViewContents=resolveViewContents,exports.richtext=richtext,exports.roleNameFromLabel=roleNameFromLabel,exports.rollup=rollup,exports.rollupToFormulaExpression=rollupToFormulaExpression,exports.routedMessageInferenceSchema=Zn,exports.routingPrice=routingPrice,exports.sameActions=sameActions,exports.sameStableValue=c.c,exports.schemaGroupKey=schemaGroupKey,exports.schemaStateSourcePayload=schemaStateSourcePayload,exports.select=select,exports.selectOptionWriteSchema=e.g,exports.serializeCanonicalJson=c.l,exports.serializeStableJson=c.u,exports.sessionInferencePatchSchema=Xn,exports.sessionStateToLegacyStatus=sessionStateToLegacyStatus,exports.setCapabilityLevel=setCapabilityLevel,exports.setDefaultObjectLevel=setDefaultObjectLevel,exports.setObjectException=setObjectException,exports.setPurge=setPurge,exports.singleRelationTarget=singleRelationTarget,exports.sortsSchema=t.u,exports.status=status,exports.statusGroupSchema=e._,exports.statusOptionWriteSchema=e.v,exports.stillMissing=stillMissing,exports.storedContentDefinition=storedContentDefinition,exports.stringFlag=stringFlag,exports.summarizeDraft=summarizeDraft,exports.summarizeGroup=summarizeGroup,exports.systemColumnFilterTarget=t.O,exports.systemPermissionFlags=systemPermissionFlags,exports.targetSnapshot=targetSnapshot,exports.targetTokenOf=targetTokenOf,exports.targetTokensFor=targetTokensFor,exports.text=text,exports.toAttribute=toAttribute,exports.toDraftableAttribute=toDraftableAttribute,exports.toDraftableAttributes=toDraftableAttributes,exports.toDraftableObject=toDraftableObject,exports.toDraftableView=toDraftableView,exports.toMultiValueOperator=t.N,exports.toUndefinedIfEmpty=toUndefinedIfEmpty,exports.toUtcDayString=t.v,exports.today=t.z,exports.todoItemSchema=or,exports.todoPlanSchema=sr,exports.toolImpactSchema=Qn,exports.touchedObjectIds=touchedObjectIds,exports.uncoveredGrants=uncoveredGrants,exports.updatedAttributeConfig=updatedAttributeConfig,exports.user=user,exports.validateAttributeName=e.P,exports.validateContentViewCatalogue=validateContentViewCatalogue,exports.validateDraft=d.a,exports.validateDraftOrThrow=d.o,exports.validateLabelExpression=validateLabelExpression,exports.validateObject=d.s,exports.validateObjectExpressions=validateObjectExpressions,exports.validateObjectName=e.L,exports.validateObjectOrThrow=d.c,exports.validateQualifiedRule=t.m,exports.validateStoredViews=validateStoredViews,exports.validateViewName=e.z,exports.verifyDeploymentBarrierAttestationV1=verifyDeploymentBarrierAttestationV1,exports.viewIdFor=viewIdFor,exports.viewIdentityKey=viewIdentityKey,exports.viewNamesAttribute=viewNamesAttribute,exports.viewRegistry=Zt,exports.wireOmittedConfigKeysFor=e.y,exports.withoutUnknownOptionKeys=e.b,exports.workspaceViewAuthoring=workspaceViewAuthoring;
|
|
44
|
+
`)}debug(e){let t=this.summary();return e?.(t),t}throwDuplicate(e,t){let r=viewIdentityKey(e,t);throw new n.DuplicateError(`view`,r,`[ViewRegistry] Duplicate view: "${t}" for object "${e}"`)}};const Zt=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 r=singleRelationTarget(e);if(r===void 0){let r=`Relation "${e.name}" requires one concrete collection target`;throw new n.ValidationError(r,[{path:t,message:r}])}return r}function violationOf(e,t,r,i){if(!(e instanceof n.SchemaError))throw e;let a=e instanceof n.ValidationError?e.errors[0]:void 0;return{key:JSON.stringify([t,r,e.code,e.message]),contentName:r,path:a?.path??i,message:e.message,code:e.code,error:e}}const Qt=new Map(t.mt().map(e=>[e.name,e]));function reject$2(e,t){throw new n.ValidationError(t,[{path:e,message:t}])}function requireName(e,t){e.trim().length===0&&reject$2(t,`API name must not be empty`)}function indexUnique(e,t,r){let i=new Map;return e.forEach((e,a)=>{if(requireName(e.name,[...r,String(a),`name`]),i.has(e.name))throw new n.DuplicateError(t,e.name);i.set(e.name,e)}),i}function 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)??Qt.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 r=e.mode??`published`,i=new Map;e.objects.forEach((e,t)=>{if(requireName(e.name,[`objects`,String(t),`name`]),i.has(e.name))throw new n.DuplicateError(`object`,e.name);i.set(e.name,{name:e.name,attributes:indexUnique(e.attributes,`attribute`,[`objects`,String(t),`attributes`])})});let a=new Set;(e.reservedObjects??[]).forEach((e,t)=>{let n=[`reservedObjects`,String(t)];requireName(e,n),!i.has(e)&&(r!==`draft`&&reject$2(n,`Unresolved reserved object "${e}"`),a.add(e),i.set(e,{name:e}))});let o=indexUnique(e.extensions??[],`extension`,[`extensions`]);function resolveObject(e,t){requireName(e,t);let n=i.get(e);return n||reject$2(t,`Unknown object "${e}"`),n}function inverseAddresses(e){let t=[];for(let[n,r]of i)if(n!==e)for(let i of r.attributes?.values()??[])i.type===`relation`&&relationAcceptsObject(i,e)&&t.push(`relatedFrom("${n}", "${i.name}")`);return t.sort().slice(0,3)}let s=r===`draft`?t.s():t.i(),c=new Map,l=new Map,u=[],d=[];function parseView(e,t){let r=s.safeParse(e);if(!r.success)throw new n.ValidationError(`Invalid content view`,r.error.issues.map(e=>({path:[...t,...e.path.map(String)],message:e.message,code:e.code})));let i=r.data;requireName(i.name,[...t,`name`]);let a=c.get(i.object)??new Set;if(a.has(i.name))throw new n.DuplicateError(`view`,`${i.object}.${i.name}`);if(a.add(i.name),c.set(i.object,a),i.default){let e=l.get(i.object)??new Set;if(e.has(i.context))throw new n.DuplicateError(`default view`,`${i.object}.${i.context}`);e.add(i.context),l.set(i.object,e)}return i}return e.views.forEach((e,t)=>{let n=[`views`,String(t)],r=e,i=`${String(r?.object??`?`)}.${String(r?.name??t)}`,a,s;try{a=parseView(e,n),s=resolveObject(a.object,[...n,`object`])}catch(e){u.push(violationOf(e,i,null,n));return}a.contents.forEach((e,t)=>{let r=[...n,`contents`,String(t)];try{requireName(e.name,[...r,`name`]),validateContent(e,r,s,a.context,o,resolveObject,inverseAddresses)}catch(t){u.push(violationOf(t,i,e.name,r))}}),d.push(a)}),{views:d,unresolvedObjects:[...a].sort(),violations:u}}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,r,i,a,o,s){function requireRecord(){requireRecordContentContext(e.name,i,t)}if(e.type===`custom`){let r=a.get(e.extension);r||reject$2([...t,`extension`],`Unknown extension "${e.extension}"`),r.requiresRecord&&requireRecord();let i=r.parameters.safeParse(structuredClone(e.parameters??{}));if(!i.success)throw new n.ValidationError(`Invalid extension parameters`,i.error.issues.map(e=>({path:[...t,`parameters`,...e.path.map(String)],message:e.message,code:e.code})));return}if(e.type===`collection`){let n=collectionSourceAddress(e.source),i,a;if(n.kind===`object`)i=o(n.object,[...t,`source`,`object`]);else if(n.kind===`related`){requireRecord();let e=[...t,`source`,`relation`],hint=()=>{if(!r)return``;let e=s(r.name);return e.length===0?``:`. Records pointing at "${r.name}" are addressed from the other side: ${e.join(`, `)}`},c=requireAttribute$1(r,n.relation,e,`relation`,hint);c?.type===`relation`&&(a=c,i=o(requireSingleRelationTarget(c,e),e))}else{requireRecord(),i=o(n.object,[...t,`source`,`object`]);let a=[...t,`source`,`relation`],s=requireAttribute$1(i,n.relation,a,`relation`);if(s?.type===`relation`&&r&&!relationAcceptsObject(s,r.name)){let e=s.targets.map(e=>`"${e.object}"`).join(`, `);reject$2(a,`Relation "${n.object}.${n.relation}" targets ${e}, not "${r.name}"`)}e.filters?.combinator===`or`&&reject$2([...t,`filters`,`combinator`],`Collection "${e.name}" addresses "${n.object}" from the far side, so its filters must use the "and" combinator`)}e.columns?.forEach((e,n)=>{let r=[...t,`columns`,String(n)];if(typeof e==`string`){requireAttribute$1(i,e,r);return}let o=[...r,`relationProperty`];a||reject$2(o,`Relation property columns require a relation source`),a.properties?.definitions.some(t=>t.name===e.relationProperty)||reject$2(o,`Unknown relation property "${e.relationProperty}"`)}),e.displayAttributes?.forEach((e,n)=>requireAttribute$1(i,e,[...t,`displayAttributes`,String(n)])),e.sorts?.forEach((e,n)=>requireAttribute$1(i,e.attribute,[...t,`sorts`,String(n),`attribute`])),e.filters?.rules.forEach((e,n)=>requireAttribute$1(i,e.attribute,[...t,`filters`,`rules`,String(n),`attribute`])),e.descriptionAttribute!==void 0&&requireAttribute$1(i,e.descriptionAttribute,[...t,`descriptionAttribute`]),e.layout===`kanban`&&e.groupByAttribute!==void 0&&requireAttribute$1(i,e.groupByAttribute,[...t,`groupByAttribute`]);return}switch(requireRecord(),e.type){case`form`:e.groups.forEach((e,n)=>{let i=[...t,`groups`,String(n)];requireName(e.name,[...i,`name`]),e.fields.forEach((e,t)=>requireAttribute$1(r,e.attribute,[...i,`fields`,String(t),`attribute`]))});break;case`richtext`:requireAttribute$1(r,e.attribute,[...t,`attribute`],`richtext`),e.titleAttribute!==void 0&&requireAttribute$1(r,e.titleAttribute,[...t,`titleAttribute`],`text`);break;case`emails`:case`meetings`:e.emailAttributes.forEach((e,n)=>requireAttribute$1(r,e,[...t,`emailAttributes`,String(n)],`text`));break;case`documents`:e.relations?.forEach((e,n)=>requireAttribute$1(r,e,[...t,`relations`,String(n)],`relation`));break;case`forms`:e.objectName!==void 0&&o(e.objectName,[...t,`objectName`]);break;case`activity`:break;default:reject$2(t,`Unknown content type: ${String(e)}`)}}const $t=[Object.freeze(Bt)];var ContentExtensionRegistry=class{constructor(){this.extensions=new Map,this.seed()}register(e){let t=Array.isArray(e)?e:[e],r=new Set;t.forEach((e,t)=>{if(this.prepare(e,t),r.has(e.name))throw new n.DuplicateError(`content extension`,e.name);r.add(e.name)});for(let e of t)this.extensions.set(e.name,e);return this}prepare(e,t){let r=[`extensions`,String(t)],reject=e=>{throw new n.ValidationError(e,[{path:r,message:e}])};if((typeof e!=`object`||!e||Array.isArray(e))&&reject(`Expected a content extension declaration`),Object.keys(e).some(e=>e!==`name`&&e!==`parameters`&&e!==`requiresRecord`)&&reject(`Expected exactly name, parameters and requiresRecord`),(typeof e.name!=`string`||e.name.trim().length===0)&&reject(`API name must not be empty`),typeof e.requiresRecord!=`boolean`&&reject(`requiresRecord must be a boolean`),typeof e.parameters?.safeParse!=`function`&&reject(`parameters must be a Zod schema`),this.extensions.has(e.name))throw new n.DuplicateError(`content extension`,e.name)}get(e){return this.extensions.get(e)}has(e){return this.extensions.has(e)}getAll(){return[...this.extensions.values()]}get size(){return this.extensions.size}clear(){this.extensions.clear(),this.seed()}seed(){for(let e of $t)this.extensions.set(e.name,e)}};const en=new ContentExtensionRegistry;function cleanContent(e,t){let r=structuredClone(e),i=new Set(t.map(e=>JSON.stringify(e.path))),remove=(...e)=>i.has(JSON.stringify(e));switch(r.type){case`form`:return r.groups.forEach((e,t)=>{e.fields=e.fields.filter((e,n)=>!remove(`groups`,String(t),`fields`,String(n),`attribute`))}),r;case`collection`:{if(r.columns&&=r.columns.filter((e,t)=>!remove(`columns`,String(t))),r.displayAttributes&&=r.displayAttributes.filter((e,t)=>!remove(`displayAttributes`,String(t))),r.layout!==`kanban`&&r.columnSizing)for(let e of Object.keys(r.columnSizing))remove(`columnSizing`,e)&&delete r.columnSizing[e];let e=r.filters?.rules.filter((e,t)=>!remove(`filters`,`rules`,String(t),`attribute`)),t=r.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:n,sorts:i,descriptionAttribute:a,...o}=r;return{...o,...r.filters&&e&&!emptied(e,r.filters.rules)?{filters:{...r.filters,rules:e}}:{},...t&&!emptied(t,r.sorts)?{sorts:t}:{},...a===void 0||remove(`descriptionAttribute`)?{}:{descriptionAttribute:a}}}case`richtext`:if(remove(`titleAttribute`)){let{titleAttribute:e,...t}=r;return t}return r;case`activity`:case`custom`:case`documents`:case`forms`:case`emails`:case`meetings`:return r;default:throw new n.ValidationError(`Unsupported content ${String(r)}`,[])}}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},l=o.placement===`main`,u=removedSource(t,o,removed);if(u!==void 0){let e={...s,attribute:u};i.dropped.push(e),l&&(a??=e);continue}e||=l;let d=n(t,o),f=d===void 0?void 0:r.get(d);if(!f)continue;if(o.type===`collection`&&o.layout===`kanban`&&namedBy(f)(o.groupByAttribute)){i.blocked.push({...s,attribute:o.groupByAttribute,reason:`kanban-grouping`});continue}let p=scrubPathsFor(o,f);if(p.length===0)continue;let m=cleanContent(o,p.map(e=>({path:e})));c.s(m)!==c.s(o)&&i.scrubbed.push({...s,definition:m})}!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 n.DuplicateError(`form`,e.name,`[FormRegistry] Duplicate form: "${e.name}"`);this.forms.set(e.name,cloneFormDefinition(e))}return this}get(e){let t=this.forms.get(e);return t?cloneFormDefinition(t):void 0}getAll(){return Array.from(this.forms.values(),cloneFormDefinition)}listNames(){return Array.from(this.forms.keys())}};const tn=new FormRegistry,nn=[`attestorIdentity`,`evidenceDigest`,`maintenanceEpoch`,`observedZeroAt`,`resumeRevision`,`version`,`workloadInventoryDigest`],rn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,an=/^[0-9a-f]{40}$/,on=/^[0-9a-f]{64}$/,sn=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/,cn=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?Z$/;function invalid$1(e,t){throw new n.ValidationError(`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=cn.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 r=Object.keys(e).sort();(r.length!==nn.length||r.some((e,t)=>e!==nn[t]))&&invalid$1(`$`,`must contain exactly the V1 attestation keys`),e.version!==1&&invalid$1(`version`,`must equal numeric 1`);let i=requirePattern(e,`maintenanceEpoch`,rn,`must be a lowercase canonical UUID`),a=requirePattern(e,`resumeRevision`,an,`must be a lowercase 40-character Git SHA`),o=requireCanonicalTimestamp(e),s=requirePattern(e,`attestorIdentity`,sn,`must be a lowercase slug`);if(s.length>64&&invalid$1(`attestorIdentity`,`must be at most 64 characters`),s!==t.allowedAttestorIdentity)throw new n.ValidationError(`Deployment barrier attestor identity mismatch`,[{path:[`attestorIdentity`],message:`does not equal the configured identity`}]);return{version:1,maintenanceEpoch:i,resumeRevision:a,observedZeroAt:o,attestorIdentity:s,workloadInventoryDigest:requirePattern(e,`workloadInventoryDigest`,on,`must be exactly 64 lowercase hexadecimal characters`),evidenceDigest:requirePattern(e,`evidenceDigest`,on,`must be exactly 64 lowercase hexadecimal characters`)}}function verifyDeploymentBarrierAttestationV1(e,t){let r=decodeDeploymentBarrierAttestationV1(e,t);if(r.maintenanceEpoch!==t.maintenanceEpoch)throw new n.ValidationError(`Deployment barrier maintenance epoch mismatch`,[{path:[`maintenanceEpoch`],message:`does not equal the current maintenance epoch`}]);if(r.resumeRevision!==t.resumeRevision)throw new n.ValidationError(`Deployment barrier resume revision mismatch`,[{path:[`resumeRevision`],message:`does not equal the requested revision`}]);let i=t.now.getTime()-new Date(r.observedZeroAt).getTime();if(!Number.isFinite(t.now.getTime())||i>9e5||i<-6e4)throw new n.ValidationError(`Deployment barrier attestation is stale`,[{path:[`observedZeroAt`],message:`must be within the database freshness window`}]);return r}const ln=Object.freeze({attest(){return Promise.reject(new n.SchemaError(`DeploymentBarrierAttestorV1 requires a host implementation that observes the deployment control plane`,n.SchemaErrorCode.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}}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 un=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}),dn=[`membership-unknown`,`sort-unknown`,`permissions-changed`],fn=[`permission-revoked`,`workspace-left`,`object-deleted`],pn=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],mn=[`type`,`objectId`,`recordId`,`recordVersion`],hn=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],gn=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],_n=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&un.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,h)}function isNotificationPriority(e){return isOneOf(e,g)}function isNotificationSensitivity(e){return isOneOf(e,_)}function isNotificationInboxState(e){return isOneOf(e,v)}function isNotificationWorkState(e){return isOneOf(e,y)}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,mn)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$2(e)&&hasOnlyKeys(e,gn)&&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,hn)&&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,dn)}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=>pn.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,_n)&&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 vn=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,vn)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const yn=[`ok`,`low`,`exhausted`,`paused`],bn=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,yn)&&isOneOf(e.mode,bn)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,fn)}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(t){try{return e.D(t)}catch(e){throw e instanceof Error?new ComputedFormulaCompileError(e.message):e}}function inferNode(e,t){switch(e.kind){case`literal`:return{valueType:literalToValueType(e.value),dependencies:[],...typeof e.value==`string`?{literalString:e.value}:{}};case`path`:return inferPath(e.parts,t);case`call`:return inferCall(e.functionName,e.args,t);case`binary`:return inferBinary(e.operator,inferNode(e.left,t),inferNode(e.right,t));default:return e}}function literalToValueType(e){switch(typeof e){case`string`:return{kind:`scalar`,type:`text`};case`number`:return{kind:`scalar`,type:`number`};case`boolean`:return{kind:`scalar`,type:`boolean`};case`object`:return{kind:`scalar`,type:`text`};default:return e}}function inferPath(e,t){if(e.length===1){let n=e[0],r=findAttribute$1(t,n);if(r===void 0)throw new ComputedFormulaCompileError(`Unknown attribute "${n}" on object "${t.objectName}"`);return r.type===`relation`?{valueType:relationToValueType(),dependencies:[{kind:`relation`,relationName:r.name,cardinality:relationCardinality(r)}],targetAttributeType:r.type}:{valueType:attributeToValueType(r),dependencies:[localDependencyFor(r)],optionsSource:optionsSourceForAttribute(t.objectName,r),targetAttributeType:r.type}}if(e.length===2){let[n,r]=e,i=findAttribute$1(t,n);if(i===void 0)throw new ComputedFormulaCompileError(`Unknown attribute "${n}" on object "${t.objectName}"`);if(i.type!==`relation`)throw new ComputedFormulaCompileError(`Attribute "${n}" on object "${t.objectName}" is not a relation`);let a=getRelationTargetObjectName$1(i);if(a===void 0)throw new ComputedFormulaCompileError(`Relation "${n}" on object "${t.objectName}" is missing targetObjectName`);let o=t.relatedObjects?.[a];if(o===void 0)throw new ComputedFormulaCompileError(`Unknown related object "${a}"`);let s=findAttribute$1(o,r);if(s===void 0)throw new ComputedFormulaCompileError(`Unknown attribute "${r}" on object "${o.objectName}"`);let c=attributeToValueType(s);return{valueType:i.cardinality===`many`?asCollectionValueType(c):c,dependencies:[{kind:`relation`,relationName:n,targetAttributeName:r,cardinality:relationCardinality(i)}],optionsSource:optionsSourceForAttribute(o.objectName,s),targetAttributeType:s.type}}throw new ComputedFormulaCompileError(`Computed paths support at most one relation hop`)}function findAttribute$1(e,t){return e.attributes.find(e=>e.name===t)}function getRelationTargetObjectName$1(e){if(e.targetObjectName!==void 0)return e.targetObjectName;if(e.targets?.length===1){let[t]=e.targets;return t?.object===`*`?void 0:t?.object}}function relationCardinality(e){return e.cardinality??`one`}function localDependencyFor(e){return e.type===`formula`||e.type===`rollup`?{kind:`computed`,attributeName:e.name}:{kind:`local`,attributeName:e.name}}function attributeToValueType(e){if(e.type===`formula`||e.type===`rollup`){if(e.returnType===void 0)throw new ComputedFormulaCompileError(`Computed attribute "${e.name}" is missing returnType`);return returnTypeToValueType(e.returnType)}switch(e.type){case`number`:case`currency`:return{kind:`scalar`,type:`number`};case`checkbox`:return{kind:`scalar`,type:`boolean`};case`date`:return{kind:`scalar`,type:`date`};case`select`:case`status`:return{kind:`scalar`,type:`select`};case`multiselect`:return{kind:`collection`,itemType:`select`};case`text`:case`richtext`:case`phone`:case`user`:case`location`:case`relation`:case`document`:return{kind:`scalar`,type:`text`};default:return e.type}}function relationToValueType(){return{kind:`collection`,itemType:`text`}}function returnTypeToValueType(e){return e===`multiselect`?{kind:`collection`,itemType:`select`}:{kind:`scalar`,type:e}}function asCollectionValueType(e){return e.kind===`collection`?e:{kind:`collection`,itemType:e.type}}function optionsSourceForAttribute(e,t){if(t.type===`formula`||t.type===`rollup`)return isSelectLikeReturnType(t.returnType)?t.optionsSource:void 0;if(t.type===`select`||t.type===`status`||t.type===`multiselect`)return t.optionsSource??{objectName:e,attributeName:t.name,...t.id?{attributeId:t.id}:{}}}function inferCall(t,n,r){if(!e.A(t))throw new ComputedFormulaCompileError(`Unknown computed function "${t}"`);let i=e.O[t];if(n.length<i.minArgs||i.maxArgs!==void 0&&n.length>i.maxArgs)throw new ComputedFormulaCompileError(`Function "${t}" expects ${i.maxArgs===void 0||i.maxArgs===i.minArgs?String(i.minArgs):`${i.minArgs}-${i.maxArgs}`} arguments, received ${n.length}`);return inferFunctionReturn(t,n.map(e=>inferNode(e,r)))}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 xn=[{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)`}],Sn=new Date(0).setUTCFullYear(1,0,1),Cn=/^\d{4}-\d{2}-\d{2}$/,wn=new Set([`createdAt`,`updatedAt`,`deletedAt`]),Tn=/^(\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=Tn.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<Sn?null:m}function unwrapRange(t){return e.V(t)?e.B(t):t}function hasTime(e){return e.type===`date`&&e.includeTime===!0}function isSystemTimestamp(e){return wn.has(e.name)}function instantWindow(e){let t=parseFilterInstant(e);return t===null?null:{startMs:t,endMs:t+(typeof e==`string`&&Cn.test(e)?864e5:1)}}function storedUtcDay(e){let n=unwrapRange(e);if(n instanceof Date)return Number.isNaN(n.getTime())?null:t.v(n.getTime());if(typeof n!=`string`||n===``)return null;if(Cn.test(n))return n;let r=new Date(n);return Number.isNaN(r.getTime())?null:t.v(r.getTime())}function comparandDay(e){return e instanceof Date?Number.isNaN(e.getTime())?null:t.v(e.getTime()):typeof e==`string`?Cn.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=>l.t(e)||Array.isArray(e)&&e.length===0,toStr=e=>e==null?``:String(e),toNum=e=>{if(l.t(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)}),L={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,n)=>{let r=toDate(e),i=t.g(n);return r&&i?r.getTime()>=i.startMs&&r.getTime()<i.endMs:!1}},on_day_month:{appliesTo:[`date`],evaluateInMemory:(e,t)=>{let n=toDate(e);if(!n)return!1;let r=t;return n.getMonth()+1===r.month&&n.getDate()===r.day}},any_of:{appliesTo:[`status`,`select`,`multiselect`,`user`,`relation`],evaluateInMemory:(e,t)=>{let n=toArr(t).map(toStr);return toArr(e).map(toStr).some(e=>n.includes(e))}},none_of:{appliesTo:[`status`,`select`,`multiselect`,`user`,`relation`],evaluateInMemory:(e,t)=>{let n=toArr(t).map(toStr);return!toArr(e).map(toStr).some(e=>n.includes(e))}}},systemAttribute=(e,t)=>({id:`system:${e}`,name:e,label:e,type:t,system:!0}),En=[...Object.entries(t.f).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,...En])}function evaluateFilterState(e,t,n){if(e.rules.length===0)return!0;let r=new Map(n.map(e=>[e.name,e])),i=e.combinator===`or`?`some`:`every`;return e.rules[i](e=>evaluateRule(e,t,r))}function evaluateRule(e,n,r){let i=r.get(e.attribute);if(!i)return!1;if(e.property&&i.type===`location`){if(!(t.lt(e.property)&&t.E(e.operator)))return!1;let r=L[e.operator];if(!r)return!1;let a=n[e.attribute],o=typeof a==`object`&&a?a[e.property]:void 0;return evaluateNormalizedComparands(r,`text`,e.operator,o,e.value,i)}if(e.property){let r=resolvePropertyDefinitions(i).find(t=>t.name===e.property);if(!r)return!1;let a=t.M(e.operator),o=L[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.A(e.operator))===`none`?!c:c}let a=L[e.operator];if(!a||!a.appliesTo.includes(i.type))return!1;let o=n[e.attribute],s=i.type===`relation`||i.type===`document`||i.type===`user`?normalizeReferenceIds(o):o;return evaluateNormalizedComparands(a,i.type,e.operator,s,e.value,i)}function evaluateNormalizedComparands(e,t,n,r,i,a){let[o,s]=normalizeOperatorComparands(t,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 u.i(t.phoneNumber);let n=typeof t.countryCode==`string`?t.countryCode:r;return`${n}:${u.a(t.phoneNumber,n)}`};return[normalizeOne(e),normalizeOne(t)]}function normalizeComparableValue(n,r){return n===`currency`?t.P(r):n===`date`?e.V(r)?e.B(r):r instanceof Date?Number.isNaN(r.getTime())?null:r.toISOString():r:r}function normalizeReferenceIds(e){let normalizeOne=e=>typeof e!=`object`||!e?e:e.id;return Array.isArray(e)?e.map(normalizeOne):normalizeOne(e)}function dateInTimezone(e,t){return new Intl.DateTimeFormat(`en-CA`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`}).format(e)}function resolveAttributeDefaultValue(e,t){if(!(`defaultValue`in e))return;let{defaultValue:n}=e;return e.type!==`date`||n!==`today`?n:e.includeTime?t.now.toISOString():dateInTimezone(t.now,t.timezone)}function deriveCreateDefaultsFromFilters(e,n,r){if(e.combinator===`or`&&e.rules.length>1)return{};let i=new Map(n.map(e=>[e.name,e])),a={};for(let n of e.rules){if(n.property!==void 0||Object.hasOwn(a,n.attribute))continue;let e=i.get(n.attribute);if(!e)continue;let o=extractDeterministicValue(n,r);o!==void 0&&(a[n.attribute]=t.rt(e).storage.cardinality===`many`?[o]:o)}return a}function extractDeterministicValue(e,n){if(e.operator===`is`)return t.L(e.value)?resolveDynamicValue(e.value,n):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator===`any_of`){if(!Array.isArray(e.value)||e.value.length!==1)return;let r=e.value[0];return t.L(r)?resolveDynamicValue(r,n):r}}function resolveDynamicValue(e,t){if(t){if(e.dynamic===`actor`)return t.userId;if(e.anchor===`today`)return dateInTimezone(t.now,t.timezone);if(e.anchor===`now`)return t.now.toISOString()}}function requestedCapabilities(e){let t=[];return e.canModify&&t.push(`modify`),e.canSend&&t.push(`send`),t}const Dn={status:`connector_status`,error:`connector_error`,provider:`connector_provider`};let On=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const kn=`DRAFT`;function isProviderDraft(e){return e.includes(kn)}const An=[`threads`,`messages`];function isMailboxListMode(e){return An.includes(e)}const jn=[`reply`,`reply_all`];function isReplyMode(e){return jn.includes(e)}const Mn=[`force`,`skip`],Nn=[`none`,`all`,`external_only`],Pn={override:null,status:`none`,failureReason:null,botId:null},Fn=/^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&&!Fn.test(t)?t:e.firstUserText?buildAgentFallbackTitle(e.firstUserText):e.emptyLabel}const In=/^[a-z0-9][a-z0-9-]{0,62}$/;function assertSchemaSourceId(e){if(!In.test(e))throw new n.ValidationError(`Invalid schema source id "${e}": expected a lowercase slug matching ${In}`,[])}const Ln={phone:`text`,currency:`number`},Rn={rename:[`kind`,`object`,`from`,`to`],phone:[`kind`,`object`,`attribute`,`to`,`defaultCountryCode`],currency:[`kind`,`object`,`attribute`,`to`,`currencyCode`]};function refuse$1(e,t,r){throw new n.ValidationError(r,[{path:t===void 0?[`resolutions`,String(e)]:[`resolutions`,String(e),t],message:r}])}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(t,n){if(e.T(n)||refuse$1(t,void 0,`Resolution ${t} must be an object`),n.kind===`rename`){assertKeys(t,n,Rn.rename),n.from===n.to&&refuse$1(t,`to`,`Resolution ${t} renames "${n.from}" to itself`);return}if(n.kind!==`retype`&&refuse$1(t,`kind`,`Unknown resolution kind ${JSON.stringify(n.kind)}: expected "rename" or "retype"`),n.to!==`phone`&&n.to!==`currency`&&refuse$1(t,`to`,`Unsupported retype to ${JSON.stringify(n.to)}: a push converts text → phone and number → currency only`),assertKeys(t,n,Rn[n.to]),n.to===`phone`){let e=n.defaultCountryCode;/^[A-Z]{3}$/.test(e)&&(0,p.isValidIso3)(e)||refuse$1(t,`defaultCountryCode`,`Resolution ${t}: "${e}" is not an ISO 3166-1 alpha-3 country code`);return}let r=n.currencyCode;/^[A-Z]{3}$/.test(r)&&(0,p.isValidCurrencyCode)(r)||refuse$1(t,`currencyCode`,`Resolution ${t}: "${r}" 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 n.ValidationError("`resolutions` must be an array",[{path:[`resolutions`],message:"`resolutions` must be an array"}]);if(e.length>100)throw new n.ValidationError(`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=(0,m.parsePhoneNumberFromString)(n,u.r(t));if(!r?.isPossible()||r.country===void 0||r.ext!==void 0)return;let i=(0,p.getCountryByIso2)(r.country)?.iso3;if(i!==void 0)return{value:{countryCode:i,phoneNumber:u.a(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 zn=f.z.object({mode:f.z.enum([`inline`,`window`]),interaction:f.z.enum([`static`,`interactive`]),size:f.z.enum([`compact`,`regular`]),aspectRatio:f.z.number().positive().finite().optional()}).strict(),Bn=f.z.object({artifactId:f.z.string().min(1),revision:f.z.number().int().positive(),name:f.z.string().min(1),kind:f.z.string().min(1),retention:f.z.enum(Fe),display:zn}).strict();function readArtifactResult(e){let t=Bn.safeParse(e);return t.success?t.data:null}const Vn=f.z.string().regex(/^[^/\s]+\/[^/\s]+$/),Hn=f.z.object({kind:f.z.literal(`generated-image`),artifact:f.z.unknown(),generation:f.z.object({attemptId:f.z.uuid(),requestedModelId:Vn,executedModelId:Vn.nullable(),format:f.z.enum(We),mimeType:f.z.enum([`image/png`,`image/jpeg`,`image/webp`])}).strict()}).strict();function readGeneratedImageResult(e){let t=Hn.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 Un={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,Un)}}return[...t.values()]}const Wn={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,Wn)}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,Wn)}}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 n.ValidationError(t,[{path:e,message:t}])}function exhaustive(e){throw new n.ValidationError(`Unsupported schema reference variant ${String(e)}`,[])}function collectSchemaReferences(t){let n=new Map(t.objects.map(e=>[e.name,e])),r=[];function visitor(e,t,i){function add(a,o,s){(a.kind===`object`?n.has(a.object):a.kind!==`attribute`||n.get(a.object)?.attributes.some(e=>e.name===a.attribute))||reject$1([...t,...s],`Unknown schema reference ${JSON.stringify(a)}`),r.push({owner:e,target:a,category:o,path:s,...i===void 0?{}:{layer:i}})}function attribute(e,t,n,r){add({kind:`attribute`,object:e,attribute:t},n,r)}function traverse(e,r,i,a,o){attribute(e,r,i,a);let s=n.get(e)?.attributes.find(e=>e.name===r);return s?.type!==`relation`&&reject$1([...t,...a],`Invalid schema reference path "${o}"`),(s.targets.length!==1||s.targets[0].object===`*`)&&reject$1([...t,...a],`Ambiguous schema reference path "${o}"`),s.targets[0].object}function attributePath(e,t,n,r){let i=e;for(let[e,a]of t.entries())e===t.length-1?attribute(i,a,n,r):i=traverse(i,a,n,r,t.join(`.`))}function formula(e,t,n){switch(t.kind){case`literal`:return;case`path`:attributePath(e,t.parts,`computed`,n);return;case`call`:for(let r of t.args)formula(e,r,n);return;case`binary`:formula(e,t.left,n),formula(e,t.right,n);return;default:exhaustive(t)}}return{add,attribute,traverse,attributePath,formula}}t.objects.forEach((t,n)=>{let r=[`objects`,String(n)],i=visitor({kind:`object`,object:t.name},r);for(let e of[`labelExpression`,`embeddingExpression`]){let n=t[e];if(n)for(let r of extractAttributeNames(n))i.attributePath(t.name,r.split(`.`),`business`,[e])}t.attributes.forEach((n,i)=>{let a=[...r,`attributes`,String(i)],o=visitor({kind:`attribute`,object:t.name,attribute:n.name},a);switch(n.type){case`relation`:n.targets.forEach((e,t)=>{if(e.object!==`*`&&o.add({kind:`object`,object:e.object},`structural`,[`targets`,String(t),`object`]),e.displayTemplate)for(let n of extractAttributeNames(e.displayTemplate))o.attributePath(e.object,n.split(`.`),`business`,[`targets`,String(t),`displayTemplate`]);for(let n of Object.keys(e.filter??{}))o.attribute(e.object,n,`business`,[`targets`,String(t),`filter`,n])});break;case`formula`:{let r;try{r=e.D(n.expression)}catch(e){reject$1([...a,`expression`],e instanceof Error?e.message:String(e))}o.formula(t.name,r,[`expression`]),visitOptions(n,o);break}case`rollup`:{let e=n.relationPath??n.relationAttribute,r=t.name;for(let t of e.split(`.`))r=o.traverse(r,t,`computed`,[n.relationPath===void 0?`relationAttribute`:`relationPath`],e);n.targetAttribute!==void 0&&o.attributePath(r,n.targetAttribute.split(`.`),`computed`,[`targetAttribute`]),visitOptions(n,o);break}case`text`:case`richtext`:case`number`:case`checkbox`:case`date`:case`phone`:case`currency`:case`status`:case`location`:case`select`:case`multiselect`:case`user`:case`document`:break;default:exhaustive(n)}})});function visitOptions(e,t){e.optionsSource&&(t.add({kind:`object`,object:e.optionsSource.objectName},`computed`,[`optionsSource`,`objectName`]),t.attribute(e.optionsSource.objectName,e.optionsSource.attributeName,`computed`,[`optionsSource`,`attributeName`]))}function viewReferences(e,t,r){visitor({kind:`view`,object:e.object,view:e.name},t,r).add({kind:`object`,object:e.object},`structural`,[`object`]),e.contents.forEach((i,a)=>{let o=visitor({kind:`content`,object:e.object,view:e.name,content:i.name},[...t,`contents`,String(a)],r);function names(e,t,n,r){e?.forEach((e,i)=>o.attribute(t,e,n,[r,String(i)]))}switch(i.type){case`collection`:{let r=collectionSourceAddress(i.source),s;switch(r.kind===`object`?(s=r.object,o.add({kind:`object`,object:s},`source`,[`source`,`object`])):r.kind===`relatedFrom`?(s=r.object,o.add({kind:`object`,object:s},`source`,[`source`,`object`]),o.attribute(s,r.relation,`source`,[`source`,`relation`])):s=o.traverse(e.object,r.relation,`source`,[`source`,`relation`],r.relation),i.columns?.forEach((i,c)=>{if(typeof i==`string`){o.attribute(s,i,`display`,[`columns`,String(c)]);return}let l=n.get(e.object),u=r.kind!==`related`||!l?void 0:findRelationAttribute(l,r.relation),d=[`columns`,String(c),`relationProperty`];u||reject$1([...t,`contents`,String(a),...d],`Relation property columns require a relation source`),u.properties?.definitions.some(e=>e.name===i.relationProperty)||reject$1([...t,`contents`,String(a),...d],`Unknown relation property "${i.relationProperty}"`),o.add({kind:`attribute`,object:e.object,attribute:u.name},`display`,d)}),names(i.displayAttributes,s,`display`,`displayAttributes`),i.descriptionAttribute!==void 0&&o.attribute(s,i.descriptionAttribute,`display`,[`descriptionAttribute`]),i.filters?.rules.forEach((e,t)=>o.attribute(s,e.attribute,`business`,[`filters`,`rules`,String(t),`attribute`])),i.sorts?.forEach((e,t)=>o.attribute(s,e.attribute,`business`,[`sorts`,String(t),`attribute`])),i.layout){case`table`:case`list`:if(i.columnSizing)for(let e of Object.keys(i.columnSizing))o.attribute(s,e,`display`,[`columnSizing`,e]);break;case`kanban`:i.groupByAttribute!==void 0&&o.attribute(s,i.groupByAttribute,`business`,[`groupByAttribute`]);break;default:exhaustive(i.layout)}break}case`form`:i.groups.forEach((t,n)=>t.fields.forEach((t,r)=>o.attribute(e.object,t.attribute,`display`,[`groups`,String(n),`fields`,String(r),`attribute`])));break;case`richtext`:o.attribute(e.object,i.attribute,`source`,[`attribute`]),i.titleAttribute!==void 0&&o.attribute(e.object,i.titleAttribute,`display`,[`titleAttribute`]);break;case`documents`:names(i.relations,e.object,`business`,`relations`);break;case`forms`:i.objectName!==void 0&&o.add({kind:`object`,object:i.objectName},`source`,[`objectName`]);break;case`emails`:case`meetings`:names(i.emailAttributes,e.object,`business`,`emailAttributes`);break;case`activity`:case`custom`:break;default:exhaustive(i)}})}return t.views.forEach((e,t)=>viewReferences(e,[`views`,String(t)])),t.retainedViews?.forEach(({definition:e,layer:t},n)=>viewReferences(e,[`retainedViews`,String(n),`definition`],t)),r}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 Gn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function reject(e,t,r){throw new n.ValidationError(r,[{path:[...e.split(`.`),t],message:r}])}function pairKey(e){return e.join(`|`)}function pairedAddresses(e,t){return[e,t].sort()}function validateExistingPairs(e){let t=new Map,n=new Map,r=new Set;for(let i of e){let e=pairKey(i.addresses);(!Gn.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,n,r){let i=e.bilateral;i||reject(`${n}.${e.name}`,`bilateral`,`Missing inverse address`);let a={type:`relation`,name:i.attribute,label:i.label??i.attribute,required:!1,targets:[{object:n}],bilateral:{object:n,attribute:e.name,cardinality:e.cardinality},order:r};return(i.cardinality??t.X(e.cardinality))===`one`?{...a,cardinality:`one`}:{...a,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&&!c.r(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)&&!c.r(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),l=o?e.properties:s?t.properties:e.properties??t.properties;l?(e.properties=structuredClone(l),t.properties=structuredClone(l)):(delete e.properties,delete t.properties)}function reconcileRelationAttributes(e){let t=structuredClone(e.objects),r=new Map;for(let e of t){if(r.has(e.name))throw new n.DuplicateError(`object`,e.name);r.set(e.name,e);let t=new Set;for(let r of e.attributes){if(t.has(r.name))throw new n.DuplicateError(`attribute`,r.name);t.add(r.name),stripUntrustedPairMetadata(r)}}let i=remapExistingPairs(e.existingPairs??[],e.addressRenames??[]),a=validateExistingPairs(i),o=new Set(i.flatMap(e=>e.generatedAddresses)),s=new Set(e.propertyEditAddresses??[]),c=new Set(e.explicitAddresses??t.flatMap(e=>e.attributes.filter(t=>!o.has(`${e.name}.${t.name}`)).map(t=>`${e.name}.${t.name}`))),l=t.flatMap(e=>e.attributes.filter(e=>e.type===`relation`&&!!e.bilateral).map(t=>({object:e,attribute:t,address:`${e.name}.${t.name}`}))).sort((e,t)=>e.address.localeCompare(t.address)),u=new Map,d=new Map;for(let{object:t,attribute:o,address:f}of l){let l=o.bilateral?.object;(!l||l===`*`||o.targets.length!==1||o.targets[0]?.object!==l)&&reject(f,`targets`,`Bilateral target of ${f} must be one concrete object`);let p=r.get(l);p||reject(f,`bilateral`,`Unknown inverse object ${l} for ${f}`);let m=`${l}.${o.bilateral?.attribute}`,h=f===m;h&&o.cardinality!==`many`&&reject(f,`cardinality`,`Symmetric self relation ${f} must be many`),h&&o.bilateral?.cardinality&&o.bilateral.cardinality!==o.cardinality&&reject(f,`bilateral`,`Symmetric self relation ${f} needs matching cardinality`);let g=pairedAddresses(f,m),_=pairKey(g);if(u.has(_))continue;let v=p.attributes.find(e=>e.name===o.bilateral?.attribute);if(v&&!isReciprocal(v,t.name,o.name))throw new n.DuplicateError(`attribute`,m);let y=!(v&&c.has(m));v||(v=generateInverse(o,t.name,p.attributes.length),p.attributes.push(v));let b=v;!h&&c.has(f)&&c.has(m)&&checkExplicitDeclarations(o,b,f,m,s.has(f)!==s.has(m));let x=a.get(_),S=x?.id??e.nextPairId(g),ee=i.find(e=>e.id===S&&pairKey(e.addresses)!==_);(!Gn.test(S)||ee||d.has(S)&&d.get(S)!==_)&&reject(f,`pair`,`Invalid or duplicate pair identity for ${f} and ${m}`),d.set(S,_);let C=h?f:chooseOwner(o,b,f,m,x,y);o.bilateral&&b.bilateral||reject(f,`bilateral`,`Missing reciprocal configuration for ${f} and ${m}`),o.bilateral={...o.bilateral,cardinality:b.cardinality,label:b.label,storageOwner:C===f},b.bilateral={...b.bilateral,cardinality:o.cardinality,label:o.label,storageOwner:C===m},reconcileProperties(o,b,f,m,c,s),o.metadata={...o.metadata,relationPairId:S},b.metadata={...b.metadata,relationPairId:S},u.set(_,{id:S,addresses:g,ownerAddress:C,generatedAddresses:g.filter(e=>!c.has(e)),...h?{symmetric:!0}:{}})}return{objects:t,pairs:[...u.values()].sort((e,t)=>e.addresses[0].localeCompare(t.addresses[0]))}}const R=f.z.number().finite().nonnegative(),Kn=f.z.enum(le),z=f.z.enum(ue),B=f.z.enum(de),V=f.z.enum(me),qn=f.z.object({provider:Kn,model:f.z.string().min(1)}).strict(),Jn=f.z.object({speed:z.optional(),reasoning:B.optional(),routing:V.optional()}).strict(),H=f.z.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),Yn=f.z.object({model:qn.optional(),speed:z.optional(),reasoning:B.optional(),imageModel:H.optional(),routing:V.optional()}).strict(),Xn=Yn.refine(e=>ge.some(t=>e[t]!==void 0),{message:`At least one inference override is required`}),Zn=f.z.object({model:qn.nullable().optional(),speed:z.nullable().optional(),reasoning:B.nullable().optional(),imageModel:H.nullable().optional(),routing:V.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`}),Qn=f.z.object({model:f.z.string().min(1),routing:f.z.object({mode:f.z.literal(`auto`),tasks:f.z.array(f.z.enum(fe)).optional(),demand:f.z.enum(pe).optional(),reason:f.z.enum([`selected`,`retained`,`fallback`]).optional(),relation:f.z.enum([`continue`,`modify`,`new`,`aside`,`unknown`]).optional(),anchorMessageId:f.z.string().min(1).optional()})}),$n=f.z.object({label:f.z.string(),denied:f.z.boolean().optional(),deletion:f.z.object({target:f.z.string().optional(),count:R.optional(),restorableDays:R.optional()}).strict().optional(),counts:f.z.record(f.z.string(),R).optional(),warnings:f.z.array(f.z.string()).optional()}).strict(),er=f.z.union([f.z.object({type:f.z.literal(`text`),text:f.z.string()}).strict(),f.z.object({type:f.z.literal(`reasoning`),text:f.z.string()}).strict(),f.z.object({type:f.z.literal(`system`),code:f.z.enum(xe)}).strict(),f.z.object({type:f.z.literal(`error`),error:f.z.string(),errorClass:f.z.string().optional()}).strict(),f.z.object({type:f.z.literal(`tool`),toolCallId:f.z.string(),name:f.z.string(),args:f.z.record(f.z.string(),f.z.unknown()),result:f.z.unknown().optional(),error:f.z.string().optional(),errorCode:f.z.enum([`output_limit_reached`,`interrupted`,n.SchemaErrorCode.INVALID_TOOL_INPUT,`external_outcome_unknown`,`external_not_dispatched`]).optional(),state:f.z.enum([`streaming`,`running`,`completed`,`error`,`pending`,`approval-requested`,`approval-responded`,`approval-dispatched`]),durationMs:R.optional(),approvalId:f.z.string().optional(),approvalImpact:$n.optional(),approved:f.z.boolean().optional(),approvalReason:f.z.string().optional(),approvalRelaxableByAuto:f.z.boolean().optional()}).strict(),f.z.object({type:f.z.literal(`file`),fileId:f.z.string(),name:f.z.string(),mimeType:f.z.string()}).strict(),f.z.object({type:f.z.literal(`compaction`),state:f.z.literal(`in-progress`),reason:f.z.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:R.optional(),reportedTokens:R.optional()}).strict(),f.z.object({type:f.z.literal(`compaction`),state:f.z.literal(`completed`),tokensBefore:R,tokensAfter:R,tokensSaved:R,strategy:f.z.enum([`no-op`,`summary`,`truncation`]),durationMs:R,summary:f.z.string().optional()}).strict(),f.z.object({type:f.z.literal(`compaction`),state:f.z.literal(`failed`),reason:f.z.string(),durationMs:R.optional()}).strict()]),tr=f.z.object({id:f.z.string(),name:f.z.string(),mimeType:f.z.string(),size:R}).strict(),nr=f.z.object({id:f.z.string(),artifactId:f.z.string(),revision:f.z.number().int().min(1),selectedText:f.z.string()}).strict(),rr=f.z.object({id:f.z.string(),type:f.z.string().transform(e=>e),entityId:f.z.string(),label:f.z.string(),objectName:f.z.string().optional(),startIndex:R,endIndex:R}).strict(),ir=f.z.object({provider:Kn,model:f.z.string(),maxTokens:R.optional(),contextWindow:R.optional()}).strict(),ar=f.z.union([f.z.date(),f.z.string().datetime({offset:!0}).transform(e=>new Date(e))]),or=f.z.object({id:f.z.string(),sessionId:f.z.string(),tenantId:f.z.string().optional(),runId:f.z.string().optional(),role:f.z.enum([`user`,`assistant`,`system`,`tool`]),parts:f.z.array(er),attachments:f.z.array(tr).optional(),mentions:f.z.array(rr).optional(),quotes:f.z.array(nr).optional(),model:ir.optional(),tokenUsage:f.z.object({input:R,output:R}).strict().optional(),metadata:f.z.record(f.z.string(),f.z.unknown()).optional(),createdAt:ar}).strict(),sr=f.z.object({id:f.z.string(),description:f.z.string(),status:f.z.enum([`pending`,`in_progress`,`completed`,`blocked`]),result:f.z.string().optional(),updatedAt:R.optional()}).strict(),cr=f.z.object({id:f.z.string(),sessionId:f.z.string(),status:f.z.enum([`active`,`completed`,`abandoned`]),todos:f.z.array(sr),version:R,createdAt:f.z.string(),updatedAt:f.z.string(),completedAt:f.z.string().optional()}).strict(),lr={"session-named":f.z.object({name:f.z.string()}).strict(),"compaction-start":f.z.object({reason:f.z.enum([`preflight_threshold`,`overflow_recovery`]),estimatedTokens:R.optional(),reportedTokens:R.optional()}).strict(),"compaction-end":f.z.object({tokensBefore:R,tokensAfter:R,tokensSaved:R,strategy:f.z.enum([`no-op`,`summary`,`truncation`]),durationMs:R,summary:f.z.string().optional()}).strict(),"compaction-failed":f.z.object({reason:f.z.string()}).strict(),usage:f.z.object({messageId:f.z.string().min(1).optional(),inputTokens:R,outputTokens:R,totalTokens:R,cacheReadTokens:R.optional(),cacheCreationTokens:R.optional(),contextWindow:R,residentTokens:R,utilization:f.z.number().finite().min(0).max(1),costUsd:R.optional()}).strict(),"message-persisted":f.z.object({message:or}).strict(),"message-persisted-ref":f.z.object({messageId:f.z.string().min(1)}).strict(),"message-updated":f.z.object({message:or}).strict(),"todo-plan-update":f.z.object({plan:cr}).strict(),"approval-context":f.z.object({approvalId:f.z.string(),toolCallId:f.z.string(),impact:$n.optional(),relaxableByAuto:f.z.boolean().optional()}).strict(),"session-state":f.z.object({state:f.z.object({phase:f.z.enum([`queued`,`running`,`parked`,`terminal`]),parkedOn:f.z.enum([`human`,`agents`]).optional(),humanRequestIds:f.z.array(f.z.string()).optional(),outcome:f.z.enum([`completed`,`failed`,`cancelled`,`timeout`,`expired`]).optional()}).strict(),version:f.z.number().int().positive(),updatedAt:f.z.string().datetime({offset:!0})}).strict()};function isAgentUIDataName(e){return e in lr}function agentUIValidationError(e){return new n.ValidationError(`Invalid agent UI message chunk`,e.map(e=>({path:e.path.map(String),message:e.message,code:e.code})))}function assertCustomAgentUIMessageChunk(e){if(typeof e!=`object`||!e||typeof e.type!=`string`)throw new n.ValidationError(`Invalid agent UI message chunk`,[{path:[`type`],message:`Expected UI message chunk type`,code:`invalid_type`}]);let t=e.type;if(!t.startsWith(`data-`))throw new n.ValidationError(`Invalid agent UI message chunk`,[{path:[`type`],message:`Expected agent data chunk type`,code:`invalid_value`}]);let r=t.slice(5);if(!isAgentUIDataName(r))throw new n.ValidationError(`Invalid agent UI message chunk`,[{path:[`type`],message:`Unknown agent UI data type: ${r}`,code:`invalid_value`}]);let i=f.z.object({type:f.z.literal(`data-${r}`),id:f.z.string().optional(),data:lr[r],transient:f.z.boolean().optional()}).strict().safeParse(e);if(!i.success)throw agentUIValidationError(i.error.issues);return i.data}function agentDataChunk(e,t,n){return assertCustomAgentUIMessageChunk({type:`data-${e}`,...n?.id===void 0?{}:{id:n.id},data:t,...n?.transient===void 0?{}:{transient:n.transient}})}const ur=f.z.object({type:f.z.enum(_e),color:f.z.enum(p.AVATAR_COLOR_IDS),expression:f.z.enum(ve).default(`relaxed`)}).strict(),dr=f.z.array(f.z.string().trim().min(1).max(200)).max(4);function agentAvatarFromMetadata(e){let t=ur.safeParse(e);return t.success?t.data:void 0}const fr=[`record.created`,`record.updated`,`record.deleted`,`form.submitted`,`agent.completed`,`webhook`],pr=new Set([`record.created`,`record.updated`,`record.deleted`]),mr=/^[A-Z_][A-Z0-9_]*$/,hr=f.z.object({cron:f.z.string().min(9),timezone:f.z.string().optional(),enabled:f.z.boolean(),input:f.z.record(f.z.string(),f.z.unknown()).optional()}),gr=f.z.object({name:f.z.string().max(120).optional(),eventType:f.z.enum(fr),objectId:f.z.guid().optional(),watchedFields:f.z.array(f.z.string()).max(50).optional(),debounceMs:f.z.number().int().min(0).max(3e5).optional(),filter:f.z.object({combinator:f.z.enum([`and`,`or`]).default(`and`),rules:f.z.array(f.z.object({attribute:f.z.string(),operator:f.z.string(),value:f.z.unknown().optional()}))}).optional(),formDefinitionId:f.z.string().optional(),sourceAgentId:f.z.guid().optional(),enabled:f.z.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&&pr.has(e.eventType))||!!e.objectId,{message:`objectId is required for record.* triggers`,path:[`objectId`]})}const _r=[`Very economical`,`Balanced`,`Powerful`,`Very powerful`],vr=[`unsupported`,`effort`,`toggle`,`budget`,`model-controlled`],yr=[`text`,`image`,`audio`,`video`,`pdf`],br=/^\d+x\d+$/,xr=/^\d+:\d+$/,Sr=/^[a-z0-9][a-z0-9-]*$/,Cr=.01;function refuse(e){throw new n.ValidationError(`Model catalogue: ${e}`,[])}function refuseZodIssues(e){let[t]=e.issues;throw new n.ValidationError(`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 f.z.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 f.z.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>Cr?`implausible`:n===0&&!t?`undeclared-zero`:null}const wr=f.z.looseObject({cost:f.z.string(),min:f.z.number(),max:f.z.number().optional()});function priceDimensionSchema(e,t,n){let r=`model "${e}" has an unreadable ${t} price`;return f.z.looseObject({perToken:f.z.string().optional(),tiers:f.z.array(wr).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 ${Cr} 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 f.z.looseObject({...dimensions(``),fast:f.z.looseObject(dimensions(`fast `),{error:n}).optional()},{error:n})}function catalogTextModelSchema(e,t){let n=`model "${e}"`;return f.z.looseObject({id:nonEmptyString(`${n} has no usable id`),apiModelId:nonEmptyString(`${n} has no usable apiModelId`).optional(),provider:f.z.enum(le,{error:e=>`${n} names an unknown provider "${String(e.input)}"`}),label:nonEmptyString(`${n} has no usable label`),description:f.z.string().optional(),recommended:f.z.boolean().optional(),recommendationRank:f.z.number().optional(),profile:f.z.looseObject({position:f.z.number(),label:f.z.enum(_r,{error:e=>`${n} has an unknown profile label "${String(e.input)}"`}),guidance:f.z.string()},{error:`profile of ${n} must be an object`}).optional(),pricing:pricingSchema(e,t),free:f.z.boolean().optional(),reasoningOptions:f.z.array(f.z.enum(de)).optional(),reasoningMode:f.z.enum(vr).optional(),inputModalities:f.z.array(f.z.enum(yr)).optional(),supportedParameters:f.z.array(f.z.string()).optional(),supportsTools:f.z.boolean().optional(),supportsStructuredOutput:f.z.boolean().optional(),isDefault:f.z.boolean().optional(),contextWindow:positiveIntegerSchema(n,`contextWindow`),maxOutputTokens:positiveIntegerSchema(n,`maxOutputTokens`),unverified:f.z.boolean().optional(),isCompactionModel:f.z.boolean().optional(),isUtilityModel:f.z.boolean().optional(),tasks:f.z.partialRecord(f.z.enum(fe),f.z.enum(pe)).optional(),listPricing:f.z.object({inputPerMillionUsd:f.z.number(),outputPerMillionUsd:f.z.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 f.z.union([f.z.looseObject({size:f.z.custom(e=>br.test(String(e)))}),f.z.looseObject({aspectRatio:f.z.custom(e=>xr.test(String(e)))})],{error})}function catalogImageModelSchema(e){let t=`image model "${e}"`,n=`${t} has no usable formats`;return f.z.looseObject({id:H,name:nonEmptyString(`${t} has no usable name`),provider:nonEmptyString(`${t} has no usable provider`).regex(Sr,{error:`${t} names an unusable provider`}),formats:f.z.array(f.z.enum(We,{error:e=>`${t} declares an unknown format "${String(e.input)}"`}),{error:n}).min(1,{error:n}),requests:f.z.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:f.z.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 Tr=f.z.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 Er=f.z.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`||!Er.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(Tr,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 U={kind:`target-missing`};var DraftRefusalError=class extends n.ValidationError{constructor(e,t,n=[]){super(e,n),this.refusal=t}};const Dr=[`pluralLabel`,`description`,`labelExpression`,`embeddingExpression`];function draftObjectSettings(e){return Object.fromEntries(Dr.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 Or={id:f.z.string().min(1).describe(`Your id, echoed back`),note:f.z.string().trim().min(1).max(160).optional().describe(`One first-person sentence, in the person's language: what you do and why, ≤160 chars`)},W={...Or,objectName:f.z.string().min(1).describe(`Object`),viewName:f.z.string().min(1).describe(`View API name`)},G={...W,contentName:f.z.string().min(1).describe(`Content API name`)},kr=f.z.union([f.z.object({before:f.z.string().min(1).describe(`Place immediately before this content name`)}).strict(),f.z.object({after:f.z.string().min(1).describe(`Place immediately after this content name`)}).strict(),f.z.object({end:f.z.literal(!0).describe(`Place at the end of the placement zone`)}).strict()]),viewFocus=e=>({objectName:e.objectName,viewName:e.viewName}),contentFocus=e=>({...viewFocus(e),contentName:e.contentName});function invalid(e,t,r){let i=[{path:e,message:t}];throw r?new DraftRefusalError(t,r,i):new n.ValidationError(t,i)}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`,U),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`,U),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 Ar=f.z.unknown().transform((e,n)=>{let r=t.l.safeParse(typeof e==`object`&&e?{...e,name:`candidate`}:e);if(!r.success){for(let e of r.error.issues)n.addIssue({code:`custom`,path:e.path,message:e.message});return f.z.NEVER}let i=typeof e==`object`&&e&&`name`in e?e.name:void 0;return{...r.data,name:i}}),jr=f.z.object({...G,type:f.z.literal(`replace_view_content`),definition:Ar}).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}}),Mr=t.l.describe(`The whole content definition.`),Nr=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:jr,wire:f.z.object({...G,type:f.z.literal(`replace_view_content`),definition:Mr}).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}}))}),Pr=f.z.object({...W,type:f.z.literal(`add_view_content`),content:Mr,target:kr.describe(`Where to place the new content within its placement zone`)}).strict(),addFocus=e=>({...viewFocus(e),contentName:e.content.name}),Fr=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:Pr,focus:addFocus,presentation:definePresentation(addFocus,`structural`),describe:e=>`Add ${e.content.name}`,apply:(e,t,r)=>change(e,t,r,e=>{if(Object.hasOwn(e.authoring.contents,t.content.name))throw new n.DuplicateError(`content`,t.content.name);e.authoring.contents={...e.authoring.contents,[t.content.name]:{sourceDefinition:null,workspaceDefinition:storedContentDefinition(t.content),suppressed:!1,sourcePosition:null,workspacePosition:0}};let r=placed(e.contents,t.content,t.target);return setOrder(e,r,[t.content.placement]),{...e,revision:e.revision+1,contents:r,contentIds:{...e.contentIds,[t.content.name]:JSON.stringify([`draft-content`,t.id])},contentRevisions:{...e.contentRevisions,[t.content.name]:1}}})}),Ir=f.z.object({...G,type:f.z.literal(`remove_view_content`)}).strict(),Lr=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:Ir,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 Rr=f.z.object({...G,type:f.z.literal(`move_view_content`),placement:f.z.enum([`main`,`aside`]).describe(`The placement zone to move the content into`),target:kr.describe(`Where to place the content within that placement zone`)}).strict(),zr=defineOperation({type:`move_view_content`,summary:`Reorders or moves a content to a different placement; the aside rule applies.`,schema:Rr,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)}}})}),Br=f.z.object({...W,type:f.z.literal(`update_view_metadata`),changes:f.z.object({label:f.z.string().min(1).optional().describe(`New label for the view`),description:f.z.string().optional().describe(`New description for the view`),icon:e.W.nullable().optional().describe(`New icon; null clears it`)}).strict().refine(e=>Object.keys(e).length>0).describe(`≥1 change`)}).strict(),Vr=defineOperation({type:`update_view_metadata`,summary:`Updates a view's label, description, or icon (null clears the icon).`,schema:Br,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}})}),Hr=f.z.string().refine(e=>e.trim().length>0,`API name must not be blank`),Ur=f.z.object({...W,type:f.z.literal(`rename_view`),newName:Hr.describe(`New API name for the view`)}).strict(),renameViewFocus=e=>({objectName:e.objectName,viewName:e.newName}),Wr=defineOperation({type:`rename_view`,summary:`Renames a view; refused on a code-declared name — change it in the declaration.`,schema:Ur,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}))}),Gr=f.z.object({...G,type:f.z.literal(`rename_view_content`),newName:Hr.describe(`New API name for the content`)}).strict(),renameContentFocus=e=>({...viewFocus(e),contentName:e.newName}),Kr=defineOperation({type:`rename_view_content`,summary:`Renames a content; refused on a code-declared name — change it in the declaration.`,schema:Gr,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}}})}),qr=f.z.object({...G,type:f.z.literal(`reset_view_content`)}).strict(),Jr=defineOperation({type:`reset_view_content`,summary:`Resets a content to its code-declared source, if one exists.`,schema:qr,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}})})}),Yr=f.z.object({...W,type:f.z.literal(`reset_view_order`),placement:f.z.enum([`main`,`aside`]).describe(`The placement zone to reset to source order`)}).strict(),Xr=defineOperation({type:`reset_view_order`,summary:`Resets a placement zone's order to its code-declared source, if one exists.`,schema:Yr,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}})}),Zr=f.z.discriminatedUnion(`type`,[jr,Pr,Ir,Rr,Br,Ur,Gr,qr,Yr]),K=[Nr,Fr,Lr,zr,Vr,Wr,Kr,Jr,Xr];function findObject(e,t){return e.objects.find(e=>e.id===t)}const Qr=new Set([`formula`,`rollup`]);function isComputedAttribute(e){return Qr.has(e.attributeType)}const $r={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 $r?$r[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`,U);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 n.ValidationError(e.message,[]):e}}function computedPlanOf(e,t){let n=computedCompileSchemaOf(e,t.objectId);return asValidationError(()=>compilePlan(t,n))}function compilePlan(e,t){if(e.attributeType===`rollup`)return compileRollupAttribute(toRollupAttribute(e),t);let n=configOf(e);return compileComputedFormula({attributeName:e.name,expression:String(n.expression??``),returnType:n.returnType,schema:t})}function assertAcyclicComputed(e){asValidationError(()=>assertAcyclicComputedDependencies(e.map(e=>({attributeName:e.attributeName,dependencies:e.dependencies}))))}function dependencyNames(e,t){switch(e.kind){case`local`:case`computed`:return e.attributeName===t;case`relation`:return e.relationName===t;case`options`:return!1;default:return e}}function compilablePlansOf(e,t){let n=computedCompileSchemaOf(e,t),r=[];for(let i of e.attributes)if(i.objectId===t&&isComputedAttribute(i))try{r.push(compilePlan(i,n))}catch(e){if(!(e instanceof ComputedFormulaCompileError))throw e}return r}function dependentsOf(e,t,n){let r=requireObject(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 ei={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,ei,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 r=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 n.ValidationError(r,[])}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 r=bilateralDeclarationOf(e);if(r===void 0||untouched(e))continue;let i=t.objects.find(t=>t.id===e.objectId)?.name??e.objectId,a=t.objects.find(e=>e.name===r.object),o=t.attributes.find(e=>e.objectId===a?.id&&e.name===r.attribute),s=`relation "${i}.${e.name}" declares inverse "${r.object}.${r.attribute}"`;if(o===void 0)throw new n.ValidationError(`${s}, which object "${r.object}" does not have; draft it first`,[]);if(o.attributeType!==`relation`)throw new n.ValidationError(`${s}, which is not a relation`,[]);let c=bilateralDeclarationOf(o);if(!(relationTargets(o).some(e=>e.object===i)&&(untouched(o)?c===void 0||c.object===i&&c.attribute===e.name:c?.object===i&&c.attribute===e.name)))throw new n.ValidationError(`${s}, which does not point back to "${i}.${e.name}"`,[])}}function fnv1a64(e,t){let n=t;for(let t of new TextEncoder().encode(e))n^=BigInt(t),n=n*1099511628211n&18446744073709551615n;return n}function viewIdFor(e,t){return draftEntityIdFor(t,e.toLowerCase())}function draftEntityIdFor(e,t){let n=`${t}:${e}`,r=fnv1a64(n,14695981039346656037n).toString(16).padStart(16,`0`)+fnv1a64(`${e}:${n}`,9521211207457086692n).toString(16).padStart(16,`0`),i=(Number.parseInt(r[16],16)&3|8).toString(16);return[r.slice(0,8),r.slice(8,12),`8${r.slice(13,16)}`,`${i}${r.slice(17,20)}`,r.slice(20,32)].join(`-`)}function defaultViewIdsFor(e){return{list:viewIdFor(e,`list`),detail:viewIdFor(e,`detail`)}}function derivedView(e,n,r,i){let a=i.filter(e=>e.objectId===r.id).filter(e=>t.rt(toAttribute(e)).presentation.formField).map(e=>({attribute:e.name})),o=e===`collection`?[{name:`all`,type:`collection`,placement:`main`,label:`All`,layout:`table`,source:{object:r.name}}]:a.length?[{name:`form`,type:`form`,placement:`main`,label:`Details`,groups:[{name:`general`,label:`General`,fields:a}]}]:[{name:`activity`,type:`activity`,placement:`main`,label:`Activity`}];return{id:n,object:r.name,name:e===`collection`?`default_list`:`default_detail`,label:r.label,context:e,default:!0,contents:o,authoring:workspaceViewAuthoring(o),revision:1,contentIds:Object.fromEntries(o.map(e=>[e.name,JSON.stringify([`draft-content`,n,e.name])])),contentRevisions:Object.fromEntries(o.map(e=>[e.name,1])),derived:!0}}function defaultViewsFor(e,t){let n=defaultViewIdsFor(e.id);return[derivedView(`collection`,n.list,e,t),derivedView(`record`,n.detail,e,t)]}function 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,r,i,a=!1){let o=toAttribute(t),s=i&&toAttribute(i),c=i&&bilateralDeclarationOf(i),l=bilateralDeclarationOf(t);if(c&&(c.object!==l?.object||c.attribute!==l?.attribute))throw new n.ValidationError(`Changing a bilateral address requires removing the existing pair first`,[]);if(o.type!==`relation`||!o.bilateral)return e;let u=e.objects.find(e=>e.id===t.objectId),d=e.objects.find(e=>e.name===o.bilateral?.object);if(!(u&&d))throw new n.ValidationError(`Both objects must exist before materializing a relation pair`,[]);let f=`${u.name}.${t.name}`,p=o.bilateral.attribute,m=`${d.name}.${p}`,h=e.attributes.find(e=>e.objectId===d.id&&e.name===p),g=s?.metadata?.relationPairId,_=typeof g==`string`?g:draftEntityIdFor(`relation-pair`,`${r}:${t.id}`),v=[f,m].sort(),y=typeof g==`string`?{id:_,addresses:v,ownerAddress:s?.type===`relation`&&s.bilateral?.storageOwner===!1?m:f,generatedAddresses:[],...f===m?{symmetric:!0}:{}}:void 0,b=reconcileRelationAttributes({objects:[...new Map([u,d].map(e=>[e.id,e])).values()].map(e=>({name:e.name,attributes:[t,...h&&h.id!==t.id?[h]:[]].filter(t=>t.objectId===e.id).map(toAttribute)})),existingPairs:y?[y]:[],...i&&!a?{explicitAddresses:[f],propertyEditAddresses:[f]}:{},nextPairId:()=>_}),x=new Map;for(let n of b.objects){let r=n.name===u.name?u.id:d.id;for(let o of n.attributes){let n=e.attributes.find(e=>e.objectId===r&&e.name===o.name),s=n?.id===t.id?i??n:n,c={...preserveDeclarationHints(o,n&&toAttribute(n)),metadata:{...o.metadata,...s&&isGeneratedDraftRelation(s)&&!(a&&n?.id===t.id)||!n?{relationGenerated:!0}:{}},id:n?.id??draftEntityIdFor(`relation-attribute`,`${_}:${r}:${o.name}`),...n?{}:{order:e.attributes.filter(e=>e.objectId===r).length}};x.set(`${r}.${o.name}`,toDraftableAttribute(c,r))}}let S=e.attributes.map(e=>{let t=`${e.objectId}.${e.name}`,n=x.get(t);return x.delete(t),n??e});return S.push(...x.values()),{...e,attributes:S,views:e.views.map(e=>{let t=[u,d].find(t=>t.name===e.object);return e.derived&&t?regenerateDerived(e,t,S):e})}}function preserveDeclarationHints(e,t){if(e.type!==`relation`||!e.bilateral||t?.type!==`relation`||!t.bilateral)return e;let{label:n,cardinality:r,...i}=e.bilateral;return{...e,bilateral:{...i,...t.bilateral.label===void 0?{}:{label:n},...t.bilateral.cardinality===void 0?{}:{cardinality:r}}}}function 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,r){let i=r.config??{},a=r.name;if(i.relationPath!==void 0)throw new n.ValidationError(`rollup "${a}": relationPath is not supported yet`,[]);let o=i.relationAttribute;if(typeof o!=`string`||o.length===0)throw new n.ValidationError(`rollup "${a}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let s=e.attributes.find(e=>e.objectId===t.id&&e.name===o&&e.attributeType===`relation`);if(!s)throw new n.ValidationError(`rollup "${a}" needs a relation attribute; "${o}" is not a relation of object "${t.name}"`,[]);let c=relationTargetObjectName(s);if(c===void 0){let e=relationTargets(s).filter(e=>e.object!==`*`).length;throw new n.ValidationError(`rollup "${a}" needs a relation with one target object; "${o}" targets ${e}`,[])}if(i.function===`count`)return;let l=e.objects.find(e=>e.name===c),u=i.targetAttribute;if(u===void 0)throw new n.ValidationError(`rollup "${a}" needs a targetAttribute: "${i.function}" aggregates one attribute of object "${c}"`,[]);if(!(l!==void 0&&e.attributes.some(e=>e.objectId===l.id&&e.name===u)))throw new n.ValidationError(`rollup "${a}" targets attribute "${u}", which object "${c}" does not have`,[])}function traversesRelation(e,t){let n=e.config??{};if(e.attributeType===`rollup`)return n.relationAttribute===t;let r=typeof n.expression==`string`?n.expression:``;return RegExp(`(^|[^A-Za-z0-9_])${t}\\.`).test(r)}function assertConfigFolds(e,t){let r=requireObject(e,t.objectId);if(t.attributeType===`relation`){for(let r of relationTargets(t))if(r.object!==`*`&&!e.objects.some(e=>e.name===r.object))throw new n.ValidationError(`object "${r.object}" is unknown; create it first`,[]);let r=bilateralDeclarationOf(t)?.object;if(r!==void 0&&r!==`*`&&!e.objects.some(e=>e.name===r))throw new n.ValidationError(`object "${r}" is unknown; create it first`,[]);for(let n of e.attributes)n.objectId===t.objectId&&isComputedAttribute(n)&&traversesRelation(n,t.name)&&computedPlanOf(e,n)}else if(isComputedAttribute(t))t.attributeType===`rollup`&&assertRollupShape(e,r,t),computedPlanOf(e,t);else return;assertAcyclicComputed(compilablePlansOf(e,t.objectId))}const q={...Or,objectId:f.z.string().uuid().describe(`The object this operation acts on`)},ti=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:f.z.object({...q,objectId:f.z.string().uuid().describe(`Stable id for the new object; the server mints one when omitted`),type:f.z.literal(`add_object`),name:e.M.describe("kebab-case plural API name (`purchase-orders`)"),label:f.z.string().min(1).describe(`Label people see`),icon:f.z.string().min(1).optional().describe(`Icon name`)}),apply:(e,t)=>{if(e.objects.some(e=>e.name===t.name))throw new n.ValidationError(`Object "${t.name}" already exists`,[]);if(e.objects.some(e=>e.id===t.objectId))throw new n.ValidationError(`Object id "${t.objectId}" is already taken`,[]);let r={id:t.objectId,name:t.name,label:t.label,...t.icon===void 0?{}:{icon:t.icon}};return{...e,objects:[...e.objects,r],views:[...e.views,...emptyDraftViewsFor(r)]}},focus:objectFocus,presentation:definePresentation(objectFocus,`structural`),describe:e=>`Crée l'objet « ${e.label} »`}),ni=f.z.object({...q,type:f.z.literal(`update_object`),changes:f.z.object({label:f.z.string().min(1).optional().describe(`New label`),icon:f.z.string().min(1).optional().describe(`New icon name from search_icons`),pluralLabel:f.z.string().optional().describe(`New label for many records; "" clears it`),description:f.z.string().optional().describe(`What this object holds`),labelExpression:E.optional().describe(`Titles every record; syntax in <expressions>`),embeddingExpression:f.z.literal(``).or(E).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}),ri=defineOperation({type:`update_object`,summary:`Updates an object's label, icon, pluralLabel, description, labelExpression, embeddingExpression.`,schema:ni,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)}),ii={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])=>ii[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 ai=defineOperation({type:`remove_object`,summary:`Removes an object; refused while a relation attribute targets it — remove it first.`,schema:f.z.object({...q,type:f.z.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}`}),oi=t.J;function assertConfigParses(t,r){try{e.l(t,r)}catch(e){throw e instanceof n.ValidationError?new n.ValidationError(e.message,e.errors.map(e=>({...e,path:[`config`,...e.path??[]]}))):e}}const si=f.z.object({...q,type:f.z.literal(`add_attribute`),attributeId:f.z.string().min(1),name:e.j,label:f.z.string().min(1),attributeType:f.z.enum(oi),config:f.z.record(f.z.string(),f.z.unknown()).optional()}).superRefine((e,t)=>{try{assertConfigParses(e.attributeType,e.config??{})}catch(e){if(e instanceof n.ValidationError){for(let n of e.errors)t.addIssue({code:`custom`,message:n.message,path:[...n.path]});return}throw e}}),ci=e.j.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),li={...Or,type:f.z.literal(`add_attribute`),attributeId:f.z.string().min(1).describe(`Stable attribute id`),name:ci,label:f.z.string().min(1).describe(`Label people see`)},ui=Object.fromEntries(e.r.map(e=>[e,!0]));function wireWriteConfigOf(t){let n=e.o(t).omit(ui),r=e.n[t];return r===void 0?n:n.extend(r)}const J=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],di=f.z.object(J.reduce((e,t)=>(Object.assign(e,wireWriteConfigOf(t).shape),e),{})).strict(),fi=oi.filter(e=>!J.includes(e)),pi=Object.fromEntries(J.map(e=>[e,new Set(Object.keys(wireWriteConfigOf(e).shape))])),mi=e.h(pi,`config key`);function refuseForeignSimpleConfigKeys(e,t){mi(e.attributeType,e.config,t,[`config`])}function wireConfigFor(t){let n=wireWriteConfigOf(t);return(t===`relation`||t===`document`?n.extend({properties:e.m.optional()}):n).strict()}const hi=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:si,wire:f.z.discriminatedUnion(`attributeType`,[f.z.object({...li,objectId:f.z.string().uuid(),attributeType:f.z.enum(J).describe(`Attribute type`),config:di.optional().describe(`Configuration of a simple attribute (text, number, date…)`)}).strict().superRefine(refuseForeignSimpleConfigKeys),...fi.map(e=>f.z.object({...li,objectId:f.z.string().uuid(),attributeType:f.z.literal(e).describe(`Attribute type`),config:wireConfigFor(e).optional().describe(`Configuration of a ${e} attribute`)}).strict())]),apply:(e,t)=>{let r=requireObject(e,t.objectId),i=e.attributes.find(e=>e.objectId===t.objectId&&e.name===t.name);if(i&&!isGeneratedDraftRelation(i))throw new n.ValidationError(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let a={id:i?.id??t.attributeId,objectId:t.objectId,name:t.name,label:t.label,attributeType:t.attributeType,...t.config===void 0?{}:{config:t.config}};for(let n of e.sampleRecords)n.objectId===t.objectId&&assertRequiredCovered(n.id,a,n.values);let o=withDerivedViews(e,r,i?e.attributes.map(e=>e===i?a:e):[...e.attributes,a]);return assertConfigFolds(o,a),reconcileDraftRelationAttribute(o,a,t.id,i,!0)},focus:attributeFocus,presentation:definePresentation(attributeFocus,`local`),describe:e=>`Ajoute l'attribut « ${e.label} »`}),Y={...q,attribute:e.j.describe(`The attribute's API name on this object`)};function requireAttribute(e,t,r,i){let a=requireObject(e,t);if(r===void 0)throw new n.ValidationError(`${i} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let o=e.attributes.find(e=>e.objectId===t&&e.name===r);if(!o)throw new DraftRefusalError(`Attribute "${r}" is not on object "${t}"`,U);return{object:a,attribute:o}}const gi=f.z.object({...Y,type:f.z.literal(`update_attribute`),changes:f.z.object({label:f.z.string().min(1).optional().describe(`New label`),config:f.z.record(f.z.string(),f.z.unknown()).optional().describe(`Whole config, replaced — same shape as add_attribute`),icon:e.W.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 _i=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:gi,apply:(e,t)=>{let{object:r,attribute:i}=requireAttribute(e,t.objectId,t.attribute,`update_attribute`),{icon:a,config:o,...s}=t.changes;if(a!==void 0&&i.attributeType!==`relation`){let e=`icon is only for relation attributes; "${i.name}" is a ${i.attributeType} attribute`;throw new n.ValidationError(e,[{path:[`changes`,`icon`],message:e}])}o!==void 0&&assertConfigParses(i.attributeType,o);let c=updatedAttributeConfig(i.config,{config:o,icon:a}),l={...i,...s,...c===void 0?{}:{config:c}},u=withDerivedViews(e,r,e.attributes.map(e=>e===i?l:e));return assertConfigFolds(u,l),reconcileDraftRelationAttribute(u,l,t.id,i)},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} »`}),vi=f.z.object({...Y,type:f.z.literal(`remove_attribute`),dropSampleValues:f.z.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 yi=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:vi,apply:(e,t)=>{let{attribute:r}=requireAttribute(e,t.objectId,t.attribute,`remove_attribute`),i=pairedDraftAttributes(e,r);for(let r of i){let[i]=dependentsOf(e,r.objectId,r.name);if(i!==void 0)throw new n.ValidationError(`attribute "${r.name}" is used by "${i}"; remove that first`,[]);let a=e.sampleRecords.find(e=>e.objectId===r.objectId&&r.name in e.values);if(a&&!t.dropSampleValues)throw new n.ValidationError(`Attribute "${r.name}" is still used by sample record "${a.id}" — resend with dropSampleValues: true to clear it from the samples`,[])}let a=e.attributes.filter(e=>!i.includes(e)),o={...e,views:cascadeAttributeRemoval(e,i),sampleRecords:t.dropSampleValues?e.sampleRecords.map(e=>withoutRemovedValues(e,i)):e.sampleRecords};return i.reduce((t,n)=>withDerivedViews(t,requireObject(e,n.objectId),a),o)},focus:existingAttributeFocus,presentation:definePresentation(existingAttributeFocus,`local`),describe:e=>`Supprime l'attribut « ${e.attribute} »`}),bi=f.z.object({...Y,type:f.z.literal(`rename_draft_attribute`),name:ci});function assertRenamable(e,t,r){let i=r.name,[a]=dependentsOf(e,t.id,i),o=e.attributes.find(e=>{let n=e.config?.optionsSource;return n?.objectName===t.name&&n.attributeName===i}),s=a??(o&&`${e.objects.find(e=>e.id===o.objectId)?.name}.${o.name}`);if(s!==void 0)throw new n.ValidationError(`attribute "${i}" is used by "${s}"; it cannot be renamed while in use`,[]);let c=bilateralDeclarationOf(r),l=e.attributes.find(e=>{let n=bilateralDeclarationOf(e);return n?.object===t.name&&n.attribute===i}),u=c===void 0?l&&`${e.objects.find(e=>e.id===l.objectId)?.name}.${l.name}`:`${c.object}.${c.attribute}`;if(u!==void 0)throw new n.ValidationError(`attribute "${i}" is paired with "${u}"; unpair it first`,[]);let d=[[`label expression`,t.labelExpression],[`embedding expression`,t.embeddingExpression]];for(let[e,r]of d)if(r&&extractAttributeNames(r).includes(i))throw new n.ValidationError(`attribute "${i}" is used by the ${e} of "${t.name}"; change it first`,[]);for(let r of e.views){let a=unrenamableUse(e,r,t.name,i);if(a!==void 0)throw new n.ValidationError(`attribute "${i}" is used by view "${r.id}" (${a}); rename it before using it there`,[])}}const xi=defineOperation({type:`rename_draft_attribute`,summary:`Renames a draft-added attribute; views and samples follow.`,schema:bi,apply:(e,t)=>{let{object:r,attribute:i}=requireAttribute(e,t.objectId,t.attribute,`rename_draft_attribute`);if(t.name===i.name)throw new n.ValidationError(`attribute "${t.attribute}" is already named "${t.name}"`,[]);if(e.attributes.some(e=>e.objectId===t.objectId&&e.name===t.name))throw new n.ValidationError(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);assertRenamable(e,r,i);let a={...i,name:t.name},o=e.attributes.map(e=>e===i?a:e);return withDerivedViews({...e,views:e.views.map(n=>renameAttributeInView(e,n,r.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}})},r,o)},focus:attributeFocus,presentation:definePresentation(attributeFocus,`local`),describe:e=>`Renomme le nom technique « ${e.attribute} » en « ${e.name} »`});function assertSampleValue(e,t,r,i){let a=toAttribute(r);try{d.d(a)}catch{return}let o=d.i(a,i);if(o.success)return;let s=o.errors??[],c=`Sample record "${e}" has an invalid value for "${t}": ${s.map(e=>e.path.length>1?`${e.path.join(`.`)}: ${e.message}`:e.message).join(`, `)}`,l=s.map(e=>({path:e.path,message:e.message}));throw r.attributeType===`relation`&&carriesNonRecordId(i)?new DraftRefusalError(c,{kind:`sample-relation-value`},l):new n.ValidationError(c,l)}function assertRequiredCovered(e,t,r){if(t.config?.required===!0&&t.config?.defaultValue===void 0&&!(t.name in r&&r[t.name]!==void 0))throw new n.ValidationError(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}const Si=f.z.guid();function carriesNonRecordId(e){let t=Array.isArray(e)?e:[e],n=relationValueIds(e);return n.length<t.length||n.some(e=>!Si.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 Ci=defineOperation({type:`add_sample_record`,summary:`Adds a sample record; keys are attribute names, required covered, computed never set; relation value is a minted/published recordId; publication is preview or requested-data.`,schema:f.z.object({...q,type:f.z.literal(`add_sample_record`),recordId:f.z.string().uuid().describe(`Minted by the server when omitted`),values:f.z.record(f.z.string(),f.z.unknown()).describe("Attribute name → value; currency is `{code,value}`, relation is a record id or name minted here"),publication:f.z.enum([`preview`,`requested-data`]).optional().describe(`preview = display-only; requested-data = real records asked for`)}),apply:(e,t)=>{let r=requireObject(e,t.objectId);if(e.sampleRecords.some(e=>e.id===t.recordId))throw new n.ValidationError(`Sample record "${t.recordId}" already exists`,[]);let i=new Map(e.attributes.filter(e=>e.objectId===t.objectId).map(e=>[e.name,e]));for(let[a,o]of Object.entries(t.values)){let s=i.get(a);if(!s)throw new DraftRefusalError(`Sample record "${t.recordId}" uses unknown attribute "${a}"`,{kind:`sample-unknown-attribute`,objectName:r.name,attributeNames:[...i.keys()]});if(isComputedAttribute(s))throw new n.ValidationError(`attribute "${s.name}" is computed and cannot be set on a sample record`,[]);assertUnknownSampleReference(e,t.recordId,s,o),assertSampleValue(t.recordId,a,s,o)}for(let e of i.values())assertRequiredCovered(t.recordId,e,t.values);return{...e,sampleRecords:[...e.sampleRecords,{id:t.recordId,objectId:t.objectId,values:t.values,...t.publication===void 0?{}:{publication:t.publication}}]}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Ajoute un exemple`});function relationNamesOf(e,t){return new Set([...e.attributes.filter(e=>e.objectId===t&&e.attributeType===`relation`).map(e=>e.name)])}function assertSampleNotReferenced(e,t){for(let r of e.sampleRecords){if(r.id===t)continue;let i=relationNamesOf(e,r.objectId);for(let[e,a]of Object.entries(r.values))if(i.has(e)&&relationValueIds(a).includes(t))throw new n.ValidationError(`sample record "${t}" is referenced by sample record "${r.id}"; remove that first`,[])}}const X=[ti,ri,ai,hi,_i,yi,xi,Ci,defineOperation({type:`remove_sample_record`,summary:`Removes a sample record; refused while another sample references it.`,schema:f.z.object({...q,type:f.z.literal(`remove_sample_record`),recordId:f.z.string().min(1).describe(`recordId of the sample to remove`)}),apply:(e,t)=>{if(!e.sampleRecords.some(e=>e.id===t.recordId&&e.objectId===t.objectId))throw new DraftRefusalError(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,U);return assertSampleNotReferenced(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(e=>e.id!==t.recordId)}},focus:recordFocus,presentation:definePresentation(recordFocus,`local`),describe:()=>`Retire un exemple`})];function build(){let e=new Map;for(let t of[...X,...K]){if(e.has(t.type))throw new n.DuplicateError(`architect operation`,t.type);e.set(t.type,t)}return e}const Z=build(),wi=[...Z.keys()];function defOf(e){let t=Z.get(e.type);if(!t)throw new n.ValidationError(`Operation "${e.id}" has unknown type "${e.type}"`,[]);return t}function applyOperations(e,t,n={extensions:[]}){return t.reduce((e,t)=>defOf(t).apply(e,t,n),e)}function focusOf(e){return defOf(e).focus(e)}function describeOperations(e,t){return e.map(e=>defOf(e).describe(e,t))}function parseOperation(e){if(typeof e!=`object`||!e||!(`type`in e))throw new n.ValidationError(`An operation must be an object carrying a type`,[]);let t=e.type;if(typeof t!=`string`)throw new n.ValidationError(`An operation's type must be a string`,[]);let r=Z.get(t);if(!r)throw new n.ValidationError(`Unknown operation type "${t}"`,[]);let i=r.schema.safeParse(e);if(!i.success)throw new n.ValidationError(`Operation "${t}" is invalid: ${i.error.issues.map(e=>`${e.path.join(`.`)} ${e.message}`).join(`; `)}`,[]);return i.data}const Ti=`bilateral`;function frozenPart(e){if(!e||typeof e!=`object`)return c.s({});let{[Ti]:t,...n}=e;return c.s(n)}function isPublishedConfigChangeAllowed(e,t){return frozenPart(e)===frozenPart(t)}const pair=e=>f.z.tuple([f.z.literal(e),f.z.string()]),Ei=f.z.union([f.z.tuple([f.z.literal(`content`),f.z.string(),f.z.string(),f.z.string()]),f.z.tuple([f.z.literal(`view`),f.z.string(),f.z.string()]),f.z.tuple([f.z.literal(`attribute`),f.z.string(),f.z.string()]),f.z.tuple([f.z.literal(`sample`),f.z.string(),f.z.string()]),pair(`object`),pair(`object-name`),pair(`object-schema`),pair(`object-tree`),pair(`attribute-id`)]);function proposalTargetKey(e){return e.viewName&&e.objectName?JSON.stringify(e.contentName?[`content`,e.objectName,e.viewName,e.contentName]:[`view`,e.objectName,e.viewName]):e.attributeName&&e.objectId?JSON.stringify([`attribute`,e.objectId,e.attributeName]):e.attributeId?JSON.stringify([`attribute-id`,e.attributeId]):e.recordId&&e.objectId?JSON.stringify([`sample`,e.objectId,e.recordId]):e.objectId?JSON.stringify([`object`,e.objectId]):e.objectName?JSON.stringify([`object-name`,e.objectName]):null}function addContentDependencies(e,t,n,r){if(n&&typeof n==`object`){if(`source`in n&&n.source&&typeof n.source==`object`){let i=collectionSourceAddressOf(n.source);if(i&&i.kind!==`related`&&r(i.object),i?.kind===`related`){let n=i.relation;r(t);let a=e.objects.find(e=>e.name===t),o=e.attributes.find(e=>e.objectId===a?.id&&e.name===n);if(o?.attributeType===`relation`&&Array.isArray(o.config?.targets))for(let e of o.config.targets)e&&typeof e.object==`string`&&e.object!==`*`&&r(e.object)}}else`type`in n&&n.type===`forms`?r(`objectName`in n&&typeof n.objectName==`string`?n.objectName:t):`type`in n&&[`form`,`richtext`,`emails`,`meetings`,`documents`].includes(String(n.type))&&r(t)}}function addBilateralDependencies(e,t,n,r,i){if([`add_attribute`,`update_attribute`,`remove_attribute`].includes(t.type)){let a=e.attributes.find(e=>e.objectId===n.objectId&&e.name===n.attributeName),o=r&&typeof r==`object`&&`bilateral`in r?r.bilateral:a?.config?.bilateral;if((t.attributeType===`relation`||a?.attributeType===`relation`)&&o&&typeof o==`object`&&`object`in o&&typeof o.object==`string`){n.objectId&&i(`object-tree`,n.objectId);let t=e.objects.find(e=>e.name===o.object);t?i(`object-tree`,t.id):i(`object-name`,o.object)}}}function 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=Zr.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:${c.s(e)}`}const Di=targetTokenOf(null);function isCurrentTargetToken(e){return e?.startsWith(`v2:`)??!1}function targetTokensFor(e,t){return Object.fromEntries(t.map(t=>[t,targetTokenOf(targetSnapshot(e,t))]))}function targetSnapshot(e,t){let r;try{r=JSON.parse(t)}catch{throw new n.ValidationError(`Invalid proposal target key "${t}"`,[])}let i=Ei.safeParse(r);if(!i.success)throw new n.ValidationError(`Invalid proposal target key "${t}"`,[]);let[a,o,s,c]=i.data,l=e.objects.find(e=>e.id===o);if(a===`object`)return l??null;if(a===`object-name`)return e.objects.find(e=>e.name===o)??null;if(a===`attribute-id`)return e.attributes.find(e=>e.id===o)??null;if(a===`attribute`)return e.attributes.find(e=>e.objectId===o&&e.name===s)??null;if(a===`sample`)return e.sampleRecords.find(e=>e.objectId===o&&e.id===s)??null;if(a===`object-schema`||a===`object-tree`){if(!l)return null;let t=e.attributes.filter(e=>e.objectId===o);return a===`object-schema`?{object:l,attributes:t.toSorted((e,t)=>e.name.localeCompare(t.name))}:{object:l,attributes:t,views:e.views.filter(e=>e.object===l.name),sampleRecords:e.sampleRecords.filter(e=>e.objectId===o)}}let u=e.views.find(e=>e.object===o&&e.name===s);if(!u)return null;if(a===`view`)return{id:u.id,revision:u.revision,definition:{...draftedViewDefinition(u),contents:u.contents.map(({name:e,placement:t})=>({name:e,placement:t}))}};let d=u.contents.find(e=>e.name===c);return c!==void 0&&Object.hasOwn(u.contentIds,c)?{id:u.contentIds[c],revision:u.contentRevisions[c],definition:d??null}:null}function presentationOf(e){return defOf(e).presentation(e)}function episodeImpactOf(e){let t=e.map(presentationOf);return new Set(t.map(({focus:e})=>e.viewName?JSON.stringify([e.objectName,e.viewName]):e.objectId).filter(e=>e!==void 0)).size>1||t.some(({impact:e})=>e===`structural`)?`structural`:t.some(({impact:e})=>e===`local`)?`local`:`atomic`}function snapshotArchitectTarget(e,t){let n=proposalTargetKey(t);return n===null?null:targetSnapshot(e,n)}function deriveArchitectChanges(e,t,n={extensions:[]}){let r=e;return t.map(e=>{let t=presentationOf(e),i=snapshotArchitectTarget(r,t.focus);r=applyOperations(r,[e],n);let a=snapshotArchitectTarget(r,t.focus);return{operationId:e.id,operationType:e.type,presentation:t,before:i,after:a,...e.note===void 0?{}:{note:e.note}}})}function part(e){return e.replace(/[%:/.]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}function architectFocusKey(e){let t=headOf(e);if(t===null)return null;let n=e.propertyPath??[];return n.length===0?t:`${t}/${n.map(part).join(`.`)}`}function 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 Oi={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`},ki=`normal`;function operationPace(e){return Object.hasOwn(Oi,e)?Oi[e]:ki}const Ai={major:{replay:4e3,live:2500},normal:{replay:2600,live:1800},minor:{replay:1400,live:1100}};function dwellForStep(e,t,n){let r=(Ai[e]??Ai[ki])[t],i=900+40*(n||0);return Math.min(6e3,Math.max(r,i))}const Q=f.z.string().min(1),ji=f.z.union([f.z.object({objectName:Q,viewName:Q,contentName:Q.optional()}).strict().describe(`Full configuration of a view, or of one content when contentName is given`),f.z.object({objectId:Q}).strict().describe(`An object with its attributes, by id`),f.z.object({objectName:Q}).strict().describe(`An object with its attributes`),f.z.object({objectId:Q,attributeName:Q}).strict().describe(`One attribute's config, by name`),f.z.object({objectId:Q,attributeId:Q}).strict().describe(`One attribute's config, by id`),f.z.object({objectId:Q,recordId:Q}).strict().describe(`One sample record`)]);function parseNamedTarget(e){let t=ji.safeParse(e);if(!t.success)throw new n.ValidationError(`Invalid scoped target`,[{path:[`target`],message:`Expected exactly one named target branch`}]);return t.data}const Mi=f.z.object({type:f.z.literal(`remove_operation`),operationId:f.z.string().min(1).describe(`The id of a stored operation to drop from the draft`)});function membersOf(e,t=[]){return[...e.map(e=>e.schema),...t].map(relaxUuidKeys)}function describeMember(e,t){return mapMember(e,e=>e.describe(t))}function wireMembersOf(e,t=[]){return[...e.map(e=>e.wire??e.schema),...t].map(relaxUuidKeys).map(relaxMintedKeys).map(addressByName).map((t,n)=>{let r=e[n];return r===void 0?t:describeMember(t,r.summary)})}function unionOf(e){return f.z.discriminatedUnion(`type`,e)}function isUuidString(e){return e instanceof f.z.ZodString&&e.format===`uuid`}function asUnionMember(e){let t=e;return!Array.isArray(t.options)||typeof t.def?.discriminator!=`string`?null:{discriminator:t.def.discriminator,options:t.options}}function mapMember(e,t){let n=asUnionMember(e);return n===null?t(e):f.z.discriminatedUnion(n.discriminator,n.options.map(t))}function relaxUuidKeys(e){return mapMember(e,e=>{let t={};for(let[n,r]of Object.entries(e.shape)){if(!isUuidString(r))continue;let e=f.z.string().min(1);t[n]=r.description===void 0?e:e.describe(r.description)}return Object.keys(t).length===0?e:e.safeExtend(t)})}const Ni={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of Ni[e.shape.type.value]??[]){let r=e.shape[n];r instanceof f.z.ZodString&&(t[n]=r.optional())}return Object.keys(t).length===0?e:e.safeExtend(t)})}function withOriginalChecks(e,t){let n=e._zod.def.checks;return!n||n.length===0?t:t.check(...n)}const Pi=f.z.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,f.z.object({...n,objectName:Pi}).strict())})}const Fi=membersOf(X,[Mi]),Ii=membersOf(K),Li=unionOf(Fi),Ri=unionOf(Ii),zi={schema:Li,view:Ri},Bi={schema:unionOf(wireMembersOf(X,[Mi])),view:unionOf(wireMembersOf(K))},Vi=new Map([...X.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...K.map(e=>[e.type,`view`])]);function familyOf(e){return Vi.get(e)??null}function viewsOf(e,t,n){return e.views.filter(e=>e.object===t.name&&e.context===n)}function collectionContentsOf(e,t){return viewsOf(e,t,`collection`).flatMap(e=>e.contents).filter(e=>e.type===`collection`)}function ownAttributes(e,t){return e.attributes.filter(e=>e.objectId===t.id)}function isTableCell(e){return t.rt(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 n.ValidationError(`View "${e.name}" names an object outside the draft scope`,[]);return{id:e.id,name:e.name,context:e.context,objectName:e.object,label:e.label,derived:e.derived===!0,contents:e.contents.map(({name:e,type:t,placement:n,label:r})=>({name:e,type:t,placement:n,label:r}))}}function summarizeDraft(e,t){let n=new Map;for(let t of e.sampleRecords)n.set(t.objectId,(n.get(t.objectId)??0)+1);return{objects:e.objects.map(t=>summarizeObject(t,e.attributes,e.views)),views:e.views.map(t=>summarizeView(t,e.objects)),sampleRecords:[...n.entries()].map(([e,t])=>({objectId:e,count:t})),operationCount:t}}const Hi=[`draft_schema`],Ui=[{input:{operations:[{type:`add_attribute`,id:`op-statut`,objectName:`devis`,attributeId:`attr-statut`,name:`statut`,label:`Statut`,attributeType:`select`,config:{options:[{value:`draft`,label:`Brouillon`,color:`gray`},{value:`sent`,label:`Envoyé`,color:`blue`},{value:`accepted`,label:`Accepté`,color:`green`}]}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:`add_view_content`,id:`op-open`,objectName:`devis`,viewName:`default_list`,content:{name:`open`,label:`À traiter`,type:`collection`,placement:`main`,layout:`table`,source:{object:`devis`},columns:[`title`,`client`,`montant`,`statut`],filters:{combinator:`and`,rules:[{attribute:`statut`,operator:`is`,value:`sent`}]},sorts:[{attribute:`montant`,direction:`desc`}]},target:{end:!0}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:`replace_view_content`,id:`op-all`,objectName:`devis`,viewName:`default_list`,contentName:`all`,definition:{name:`all`,type:`collection`,placement:`main`,layout:`table`,source:{object:`devis`},columns:[`title`,`client`,`montant`,`statut`]}}],guard:{revision:null,targetTokens:{}}}}],$=f.z.string().refine(e=>e.trim().length>0,`Must not be blank`),Wi=f.z.union([f.z.tuple([f.z.literal(`object`),$]),f.z.tuple([f.z.literal(`attribute`),$,$]),f.z.tuple([f.z.literal(`view`),$,$]),f.z.tuple([f.z.literal(`content`),$,$,$])]),Gi=f.z.object({label:$,pluralLabel:f.z.string().optional(),description:f.z.string().optional(),icon:e.W.optional(),labelExpression:f.z.string(),embeddingExpression:f.z.string().optional(),sealed:f.z.boolean().optional(),toleratedAttributes:f.z.array($).optional(),metadata:f.z.record(f.z.string(),f.z.unknown()).optional(),documentLayout:f.z.record(f.z.string(),f.z.unknown()).optional()}).strict();function failure(e){throw new n.ValidationError(e,[])}function definitionSchema(n){return f.z.custom(r=>{let i=f.z.record(f.z.string(),f.z.unknown()).parse(r);for(let e of n[0]===`view`?[`object`,`name`]:[`name`])Object.hasOwn(i,e)&&failure(`Invalid schema state: unrecognized definition key ${e}`);switch(n[0]){case`object`:Gi.parse(i);break;case`attribute`:{let n=f.z.enum(t.J).parse(i.type);e.a(n).extend({type:f.z.literal(n),label:$,required:f.z.boolean().optional(),unique:f.z.boolean().optional(),icon:e.W.optional()}).strict().parse(i);break}case`view`:{let{contents:e,...r}=i,a=f.z.array($).parse(e);new Set(a).size!==a.length&&failure(`Invalid schema state: duplicate content membership`),t.o.parse({...r,object:n[1],name:n[2],contents:[]});break}case`content`:t.l.parse({...i,name:n[3]})}return!0})}function compareSchemaStateEntries(e,t){let n=JSON.stringify(e.address),r=JSON.stringify(t.address);return n<r?-1:+(n>r)}function schemaStateSourcePayload(e){return{modelVersion:1,hashVersion:1,entries:[...e].sort(compareSchemaStateEntries).filter(e=>e.source!==null).map(({address:e,source:t})=>({address:e,source:t}))}}function parseState(e){let t=f.z.record(f.z.string(),f.z.unknown()).parse(e);for(let[e,n]of[[`modelVersion`,`model`],[`hashVersion`,`hash`]])t[e]!==1&&failure(`Unsupported schema ${n} version: expected 1, received ${t[e]===void 0?`missing`:String(t[e])}`);let r=f.z.object({modelVersion:f.z.literal(1),hashVersion:f.z.literal(1),tenant:$,sourceFingerprint:f.z.string().regex(/^[a-f0-9]{64}$/),entries:f.z.array(f.z.unknown())}).strict().safeParse(e);if(!r.success){let e=r.error.issues.find(e=>e.code===`unrecognized_keys`);throw e?.code===`unrecognized_keys`&&failure(`Invalid schema state: unrecognized key ${e.keys[0]}`),n.ValidationError.fromZodErrors(r.error.issues.map(e=>({path:e.path.map(String),message:e.message})))}let i=new Set,a=r.data.entries.map(e=>{let t=Wi.parse(f.z.object({address:f.z.unknown()}).parse(e).address),n=JSON.stringify(t);i.has(n)&&failure(`Invalid schema state: duplicate address ${n}`),i.add(n);let r=definitionSchema(t).nullable(),a=t[0]===`object`||t[0]===`attribute`?f.z.object({id:f.z.string().uuid(),updatedAt:f.z.string().datetime()}).strict():f.z.object({id:f.z.string().uuid(),revision:f.z.number().int().nonnegative()}).strict(),o=f.z.object({address:Wi,source:r,effective:r,status:f.z.enum([`source`,`runtime`,`copy`,`suppressed`]),sourceOwner:f.z.union([f.z.literal(`core`),f.z.string().regex(/^(bundle|source):.+$/)]).nullable(),guard:a.nullable()}).strict().parse(e);(o.status===`runtime`&&(o.source!==null||o.effective===null||o.sourceOwner!==null)||o.status===`suppressed`&&(t[0]!==`content`||o.source===null||o.effective!==null||o.guard===null)||o.status===`copy`&&(o.source===null||o.effective===null)||o.effective!==null&&o.guard===null||o.source===null&&o.effective===null)&&failure(`Invalid schema state: inconsistent status at ${n}`);let s=o.sourceOwner;s!==null&&s!==`core`&&!s.startsWith(`bundle:`)&&!s.startsWith(`source:`)&&failure(`Invalid source owner`);let c=s===null||s===`core`?s:s.startsWith(`bundle:`)?`bundle:${s.slice(7)}`:`source:${s.slice(7)}`;return{...o,sourceOwner:c}});return{...r.data,entries:a.sort(compareSchemaStateEntries)}}function parseSchemaState(e){try{return parseState(e)}catch(e){throw e instanceof f.z.ZodError?n.ValidationError.fromZodErrors(e.issues.map(e=>({path:e.path.map(String),message:e.message}))):e}}function diffSchemaState(e){let t=[];for(let n of[...e.entries].sort(compareSchemaStateEntries)){let e=n.source===null?`added`:n.status===`suppressed`?`suppressed`:n.effective===null?`removed`:c.s(n.source)===c.s(n.effective)?n.status===`copy`?`copied`:null:`changed`;e&&t.push({...n,change:e})}return{modelVersion:1,tenant:e.tenant,sourceFingerprint:e.sourceFingerprint,changes:t}}exports.ABSENT_TARGET_TOKEN=Di,exports.AGENT_AVATAR_EXPRESSIONS=ve,exports.AGENT_AVATAR_TYPES=_e,exports.AGENT_MESSAGE_KIND=Ce,exports.AGENT_NOTIFICATION_KIND=Se,exports.AGENT_STARTERS_MAX=4,exports.AGENT_STARTER_MAX_LENGTH=200,exports.AGENT_TASK_KINDS=fe,exports.AGENT_UI_BATCH_MAX_BYTES=204800,exports.AGENT_UI_BATCH_MAX_ITEMS=256,exports.ALLOWED_PROPERTY_TYPES=Ye,exports.ALL_OPERATION_TYPES=wi,exports.ALL_PIPES=T,exports.ARTIFACT_FILE_ROLES=Ie,exports.ARTIFACT_KINDS=Pe,exports.ARTIFACT_LIST_VIEW=Ut,exports.ARTIFACT_OBJECT=Vt,exports.ARTIFACT_OBJECT_NAME=P,exports.ARTIFACT_PREVIEW_EXTENSION=Bt,exports.ARTIFACT_RETENTIONS=Fe,exports.ARTIFACT_VIEW=Ht,exports.ATTRIBUTE_FILTER_OPERATORS=t.tt,exports.ATTRIBUTE_TYPES=t.J,exports.AUDIT_ACTIONS=ie,exports.AUDIT_AGENT_SESSION_METADATA_KEY=`agentSessionId`,exports.AUDIT_RESOURCE_TYPES=re,exports.AccessDeniedError=n.AccessDeniedError,exports.AgentBuilder=AgentBuilder,exports.AmbiguousSchemaChangeError=n.AmbiguousSchemaChangeError,exports.AttributeInUseError=n.AttributeInUseError,exports.AttributeNotFoundError=n.AttributeNotFoundError,exports.BEHAVIOR_PROPERTIES=te,exports.BROWSER_IMAGE_MAX_BYTES=15e4,exports.BYTE_UNIT_LABELS=qe,exports.CATALOG_RESOURCES=ct,exports.CLAIMABLE_SESSION_STATUSES=oe,exports.COMPUTED_FUNCTIONS=e.O,exports.COMPUTED_FUNCTION_METADATA=xn,exports.COMPUTED_FUNCTION_NAMES=e.k,exports.CONNECTOR_CALLBACK_PARAM=Dn,exports.COUNT_MODES=Ge,exports.CUSTOM_LEVEL=st,exports.ComputedFormulaCompileError=ComputedFormulaCompileError,exports.ComputedFormulaParseError=e.E,exports.ConcurrentModificationError=n.ConcurrentModificationError,exports.ContentBuilder=j,exports.DB_COLUMN_FIELDS=ft,exports.DEFAULT_AGENT_EXECUTION_CONFIG=xt,exports.DEFAULT_APPROVAL_POLICY=se,exports.DEFAULT_DAILY_ACTIVITY_DAYS=182,exports.DEFAULT_DICTATION_LIMITS=Ee,exports.DEFAULT_LABEL_FALLBACK=et,exports.DEFAULT_MEETING_BOT_DISPLAY_NAME=Be,exports.DEFAULT_ROLES=pt,exports.DEFAULT_ROLE_DESCRIPTIONS=ht,exports.DEFAULT_ROLE_LABELS=mt,exports.DEFAULT_ROLE_PERMISSIONS=_t,exports.DEFAULT_ROLE_REVOCATIONS=vt,exports.DEFAULT_TENANT_SETTINGS=Ve,exports.DEFAULT_VALIDATION_MESSAGES=i.n,exports.DEVICE_CHANNEL_AUTHENTICATE_TIMEOUT_MS=1e4,exports.DEVICE_CHANNEL_IDLE_POLL_MS=2e3,exports.DEVICE_CHANNEL_KEEPALIVE_MS=2e4,exports.DEVICE_CHANNEL_MAX_FRAME_BYTES=262144,exports.DEVICE_CHANNEL_PATH=De,exports.DEVICE_CHANNEL_PRESENCE_MS=2e3,exports.DEVICE_CHANNEL_UPGRADE_REQUIRED_REASON=`UPGRADE_REQUIRED`,exports.DEVICE_CHANNEL_WORKER_CLOSE_PROTOCOL_VIOLATION=4008,exports.DEVICE_COMMAND_ERROR_CODES=ke,exports.DICTATION_FINALIZATION_TIMEOUT_MS=5e3,exports.DICTATION_FRAME_BYTES=3200,exports.DICTATION_MAX_BUFFER_BYTES=16e3,exports.DICTATION_MAX_FRAME_BYTES=6400,exports.DICTATION_MAX_TRANSCRIPT_BYTES=65536,exports.DICTATION_MODEL_ID=`google/gemini-3.5-transcribe-live`,exports.DICTATION_PREPARATION_TIMEOUT_MS=1e4,exports.DICTATION_SAMPLE_RATE=16e3,exports.DICTATION_TICKET_TTL_MS=15e3,exports.DISCARD_ARCHITECT_DRAFT_TOOL_NAME=`discard_architect_draft`,exports.DOCUMENT_SYSTEM_ATTRIBUTES=Je,exports.DRAFTABLE_ATTRIBUTE_TYPES=oi,exports.DRAFT_BATCH_LIMIT=12,exports.DRAFT_OBJECT_SETTINGS=Dr,exports.DRAFT_SCHEMA_INPUT_EXAMPLES=Ui,exports.DRAFT_WRITE_TOOL_NAMES=Hi,exports.DRIVE_LIST_VIEW=zt,exports.DRIVE_OBJECT=Lt,exports.DRIVE_OBJECT_NAME=N,exports.DRIVE_VIEW=Rt,exports.DeviceChannelProtocolError=DeviceChannelProtocolError,exports.DeviceChannelServerFrameSchema=Ne,exports.DeviceChannelWorkerFrameSchema=Me,exports.DraftRefusalError=DraftRefusalError,exports.DuplicateError=n.DuplicateError,exports.EMPTY_VALUE_PLACEHOLDER=`—`,exports.ENV_VAR_KEY_PATTERN=mr,exports.ESTIMATED_COUNT_CAP=1e4,exports.FAKE_MEETING_BOT_SIGNATURE_HEADER=`x-fake-signature`,exports.FAMILY_INPUTS=zi,exports.FAMILY_WIRE_INPUTS=Bi,exports.FORM_FORBIDDEN_ATTRIBUTE_TYPES=Le,exports.FlagRegistry=FlagRegistry,exports.FlagService=FlagService,exports.ForbiddenError=n.ForbiddenError,exports.FormBuilder=FormBuilder,exports.FormRegistry=FormRegistry,exports.FormRowBuilder=FormRowBuilder,exports.FormStepBuilder=FormStepBuilder,exports.GET_ARCHITECT_DRAFT_TOOL_NAME=`get_architect_draft`,exports.GroupBuilder=wt,exports.IDENTITY_PROPERTIES=C,exports.IMAGE_FORMATS=We,exports.INFERENCE_REASONING_OPTIONS=de,exports.INFERENCE_ROUTING_MODES=me,exports.INFERENCE_SPEEDS=ue,exports.INVENTORY_LIMIT=30,exports.InvalidPermissionGrantError=n.InvalidPermissionGrantError,exports.LAST_RUN_ERROR_MAX_LENGTH=200,exports.LIST_VIEW_TAB_VISIBILITIES=e.K,exports.LIVE_EVENT_TYPES=un,exports.LOCATION_FILTER_PROPERTIES=t.nt,exports.MAILBOX_LIST_MODES=An,exports.MAIL_DRAFT_BODY_MAX_CHARS=2e5,exports.MAIL_SUBJECT_MAX_CHARS=998,exports.MAX_DAILY_ACTIVITY_DAYS=366,exports.MAX_PRESET_DEPTH=5,exports.MAX_TODOS=50,exports.MAX_TODO_DESCRIPTION_CHARS=500,exports.MAX_TODO_ID_CHARS=80,exports.MEETING_ATTRIBUTES=I,exports.MEETING_DETAIL_VIEW_ID=Kt,exports.MEETING_LIST_VIEW=Xt,exports.MEETING_LIST_VIEW_ID=Wt,exports.MEETING_OBJECT=Jt,exports.MEETING_OBJECT_NAME=F,exports.MEETING_VIEW=Yt,exports.MEETING_WRITE_SOURCE=Gt,exports.MEMORY_LIST_VIEW=It,exports.MEMORY_OBJECT=Nt,exports.MEMORY_VIEW=Ft,exports.MIXED_LEVEL=dt,exports.McpOAuthCompletionMode=On,exports.MemoryNotFoundError=n.MemoryNotFoundError,exports.MultiRelationAttributeBuilder=MultiRelationAttributeBuilder,exports.NATIVE_AGENT_UI_PART_IDS_METADATA_KEY=Te,exports.NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION=1,exports.NATIVE_OBJECT_NAMES=e.Q,exports.NOTIFICATION_INBOX_STATES=v,exports.NOTIFICATION_KINDS=h,exports.NOTIFICATION_PRIORITIES=g,exports.NOTIFICATION_SENSITIVITIES=_,exports.NOTIFICATION_TYPES_V1=ee,exports.NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED=S,exports.NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN=b,exports.NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED=x,exports.NOTIFICATION_WORK_STATES=y,exports.NO_ACCESS=ot,exports.NO_RECORDING=Pn,exports.NO_VALUE_OPERATORS=t.W,exports.NonJsonValueError=c.o,exports.NoopGeocodingAdapter=NoopGeocodingAdapter,exports.NotFoundError=n.NotFoundError,exports.NotImplementedError=n.NotImplementedError,exports.OBJECT_GRANT=D,exports.OBJECT_NAME_SCHEMA=e.M,exports.OPEN_TOOL_PART_STATES=be,exports.OPERATION_PACE=Oi,exports.OPERATION_REGISTRY=Z,exports.OPERATORS_BY_TYPE=t.G,exports.OPERATOR_SPECS=L,exports.ObjectBuilder=ObjectBuilder,exports.ObjectNotFoundError=n.ObjectNotFoundError,exports.ObjectReferencedError=n.ObjectReferencedError,exports.OrphanSystemAttributeError=n.OrphanSystemAttributeError,exports.PACE_DWELL_MS=Ai,exports.PERMISSION_ACTIONS=k,exports.PERMISSION_CAPABILITIES=O,exports.PERMISSION_CATALOG=at,exports.PIPES_WITH_ARGS=$e,exports.PREFERRED_NAME_MAX_LENGTH=80,exports.PRESENTATION_PROPERTIES=ne,exports.PROVIDER_DRAFT_LABEL=kn,exports.PROVIDER_NAMES=le,exports.PUBLISHED_CONFIG_EXCEPTION=Ti,exports.ProtectedResourceError=n.ProtectedResourceError,exports.ProtectedRoleError=n.ProtectedRoleError,exports.QUALIFIED_SEPARATOR=t.V,exports.QUOTA_KEYS=Ke,exports.RECENT_ACTIVITY_LEDGER_LIMIT=50,exports.RECORDING_OVERRIDES=Mn,exports.RECORDING_POLICIES=Nn,exports.RECORD_ACCESS_ROLES=Re,exports.RECORD_ACCESS_SOURCES=ze,exports.RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY=it,exports.RELATION_TARGET_ANY=t.Y,exports.REMOVED_OPERATOR_REPLACEMENTS=t.d,exports.REMOVE_OPERATION_SCHEMA=Mi,exports.REPLY_MODES=jn,exports.REQUEST_DESIGN_REVIEW_TOOL_NAME=`request_design_review`,exports.RESERVED_ATTRIBUTE_NAMES=e.q,exports.RESERVED_OBJECT_NAMES=e.J,exports.RESOURCE_VISIBILITIES=e.Y,exports.ROUTING_PRICE_CEILINGS=he,exports.RealtimeDeliveryError=n.RealtimeDeliveryError,exports.RealtimeRateLimitedError=n.RealtimeRateLimitedError,exports.RealtimeSubscriptionError=n.RealtimeSubscriptionError,exports.RecordNotFoundError=n.RecordNotFoundError,exports.RecordReferencedError=n.RecordReferencedError,exports.RepositoryError=n.RepositoryError,exports.ReservedObjectNameError=n.ReservedObjectNameError,exports.RoleNotFoundError=n.RoleNotFoundError,exports.SCHEMA_LIMITS=e.G,exports.SCHEMA_OPERATIONS=X,exports.SCHEMA_OPERATION_INPUT=Li,exports.SCHEMA_SOURCE_ID_PATTERN=In,exports.SCHEMA_SOURCE_RETYPE_FROM=Ln,exports.SESSION_INFERENCE_PATCH_KEYS=ge,exports.SESSION_STATE_STREAM_ID=`session-state`,exports.SESSION_TERMINAL_STATUSES=ae,exports.SIMPLE_PIPES=Qe,exports.SIMPLE_PROPERTY_TYPES=e.t,exports.SKILL_CONTENT_TEMPLATE=kt,exports.SKILL_LIST_VIEW=Mt,exports.SKILL_OBJECT=At,exports.SKILL_VIEW=jt,exports.STANDARD_SCHEMA_VENDOR=St,exports.SYNONYM_ALIASES=t.y,exports.SYSTEM_ATTRIBUTES=t.dt,exports.SYSTEM_ATTRIBUTE_I18N_KEYS=t.ft,exports.SYSTEM_FIELD_NAMES=e.X,exports.SYSTEM_FILTER_ATTRIBUTE_TYPES=t.f,exports.SYSTEM_PART_CODES=xe,exports.SchemaError=n.SchemaError,exports.SchemaErrorCode=n.SchemaErrorCode,exports.SearchBackendError=n.SearchBackendError,exports.SingleRelationAttributeBuilder=SingleRelationAttributeBuilder,exports.StorageError=n.StorageError,exports.SyncCascadeError=n.SyncCascadeError,exports.SyncConflictError=n.SyncConflictError,exports.SyncError=n.SyncError,exports.SystemEntityImmutableError=n.SystemEntityImmutableError,exports.TASK_DEMAND_LEVELS=pe,exports.TENANT_INVITATION_DEFAULT_TTL_MS=6048e5,exports.TENANT_INVITATION_MAX_TTL_MS=2592e6,exports.TENANT_INVITATION_MIN_TTL_MS=36e5,exports.TENANT_INVITATION_RESEND_INTERVAL_MS=6e4,exports.TEXT_FORMAT_PATTERNS=r.n,exports.TODAY_DEFAULT=`today`,exports.TODO_PLAN_STATUSES=ce,exports.TODO_STATUSES=we,exports.TOOL_APPROVAL_STATES=ye,exports.TOOL_NAME_SEPARATOR=`__`,exports.TRIGGER_EVENT_TYPES=fr,exports.USER_STATUSES=He,exports.USER_WORK_POSTURES=Ue,exports.VIEW_OPERATIONS=K,exports.VIEW_OPERATION_INPUT=Ri,exports.ValidationError=n.ValidationError,exports.ViewBuilder=Ct,exports.WIRE_OMITTED_CONFIG_KEYS=e.r,exports.WORKSTATION_HARNESSES=yt,exports.agent=agent,exports.agentAvatarFromMetadata=agentAvatarFromMetadata,exports.agentAvatarSchema=ur,exports.agentDataChunk=agentDataChunk,exports.agentDisplayName=agentDisplayName,exports.agentInferencePreferencesSchema=Jn,exports.agentMessageAttachmentSchema=tr,exports.agentMessagePartSchema=er,exports.agentScheduleSchema=hr,exports.agentSessionInferenceOverridesInputSchema=Yn,exports.agentSessionInferenceOverridesSchema=Xn,exports.agentSessionMessageSchema=or,exports.agentStartersSchema=dr,exports.agentTriggerBaseSchema=gr,exports.agentUIValidationError=agentUIValidationError,exports.applyOperations=applyOperations,exports.applyPipes=applyPipes,exports.applyRelationProps=applyRelationProps,exports.architectContentBodyKey=architectContentBodyKey,exports.architectDraftChannelKey=architectDraftChannelKey,exports.architectFocusCandidates=architectFocusCandidates,exports.architectFocusKey=architectFocusKey,exports.artifactQuoteSchema=nr,exports.asTenantId=c.t,exports.asUserId=c.n,exports.assertAcyclicComputed=assertAcyclicComputed,exports.assertAcyclicComputedDependencies=assertAcyclicComputedDependencies,exports.assertBilateralPairs=assertBilateralPairs,exports.assertCustomAgentUIMessageChunk=assertCustomAgentUIMessageChunk,exports.assertSchemaSourceId=assertSchemaSourceId,exports.assertSchemaSourceResolutions=assertSchemaSourceResolutions,exports.attributeConfigSchemas=e.i,exports.attributeFilterTarget=t.S,exports.attributeInventory=attributeInventory,exports.bilateralDeclarationOf=bilateralDeclarationOf,exports.booleanFlag=booleanFlag,exports.buildAgentFallbackTitle=buildAgentFallbackTitle,exports.buildPermissionFlags=buildPermissionFlags,exports.buildPropertySchema=buildPropertySchema,exports.buildQualifiedAttribute=t.H,exports.canCopyRole=canCopyRole,exports.canGrantLevel=canGrantLevel,exports.canGrantPurge=canGrantPurge,exports.canonicalStringify=c.s,exports.canonicalViewOperationSchema=Zr,exports.canonicalizeFilterValue=t.k,exports.capabilityForResource=capabilityForResource,exports.capped=capped,exports.catalogEmbeddingSchema=Tr,exports.catalogImageModelSchema=catalogImageModelSchema,exports.catalogTextModelSchema=catalogTextModelSchema,exports.checkbox=checkbox,exports.chosenUserName=chosenUserName,exports.cleanContent=cleanContent,exports.collectContentViewCatalogue=collectContentViewCatalogue,exports.collectQualifiedRuleIssues=t.p,exports.collectSchemaReferences=collectSchemaReferences,exports.collectionContentSourceSchema=t.t,exports.collectionContentsOf=collectionContentsOf,exports.collectionSourceAddress=collectionSourceAddress,exports.collectionSourceAddressOf=collectionSourceAddressOf,exports.colorIdSchema=e.U,exports.columnsSchema=t.n,exports.compareAgentSessionMessages=compareAgentSessionMessages,exports.compareByRecommendation=compareByRecommendation,exports.compareSchemaStateEntries=compareSchemaStateEntries,exports.compilablePlansOf=compilablePlansOf,exports.compileComputedFormula=compileComputedFormula,exports.compileRollupAttribute=compileRollupAttribute,exports.computeByteMagnitude=computeByteMagnitude,exports.computeReconnectDelay=computeReconnectDelay,exports.computeRetryDelay=computeRetryDelay,exports.computedCompileSchemaOf=computedCompileSchemaOf,exports.computedPlanOf=computedPlanOf,exports.content=M,exports.contentDefinition=contentDefinition,exports.contentExtensionRegistry=en,exports.contentNamesAttribute=contentNamesAttribute,exports.contentViewDefinitionSchema=t.r,exports.contentViewDefinitionSchemaFor=t.i,exports.conversationDisplayTitle=conversationDisplayTitle,exports.convertRetypedValue=convertRetypedValue,exports.createCheckboxValidator=o.createCheckboxValidator,exports.createDateValidator=s.createDateValidator,exports.createFlagRegistry=createFlagRegistry,exports.createFlagService=createFlagService,exports.createFormAttributeValidator=d.f,exports.createNumberValidator=a.createNumberValidator,exports.createStandardSchemaProps=createStandardSchemaProps,exports.createTextValidator=r.t,exports.currency=currency,exports.currentActor=t.I,exports.customDataChunkSchemas=lr,exports.date=date,exports.dateInTimezone=dateInTimezone,exports.dateValueStart=e.B,exports.declaredImageRequests=declaredImageRequests,exports.decodeDeploymentBarrierAttestationV1=decodeDeploymentBarrierAttestationV1,exports.deepEqual=c.r,exports.defaultViewIdsFor=defaultViewIdsFor,exports.defaultViewsFor=defaultViewsFor,exports.defineDeviceChannelFrames=defineDeviceChannelFrames,exports.defineOperation=defineOperation,exports.definePresentation=definePresentation,exports.dependentsOf=dependentsOf,exports.deriveArchitectChanges=deriveArchitectChanges,exports.deriveCreateDefaultsFromFilters=deriveCreateDefaultsFromFilters,exports.deriveInitials=deriveInitials,exports.deriveViewerAccess=deriveViewerAccess,exports.describeOperations=describeOperations,exports.detailView=detailView,exports.deviceChannelUrl=deviceChannelUrl,exports.diffSchemaState=diffSchemaState,exports.displayAttributesSchema=t.a,exports.document=document,exports.draftContentViewDefinitionSchema=t.o,exports.draftContentViewDefinitionSchemaFor=t.s,exports.draftListedObjectResolver=draftListedObjectResolver,exports.draftObjectSettings=draftObjectSettings,exports.draftedLabelExpression=draftedLabelExpression,exports.draftedObjectDefinition=draftedObjectDefinition,exports.draftedViewDefinition=draftedViewDefinition,exports.durableDateSchema=ar,exports.dwellForStep=dwellForStep,exports.edgePropertyFilterTarget=t.C,exports.episodeImpactOf=episodeImpactOf,exports.evaluateComputedAst=e.x,exports.evaluateComputedFormula=e.S,exports.evaluateComputedFormulaWithResult=e.C,exports.evaluateFilterState=evaluateFilterState,exports.evaluateRecordFilterState=evaluateRecordFilterState,exports.exceptionLevels=exceptionLevels,exports.extractAttributeNames=extractAttributeNames,exports.extractCurrencyFilterValue=t.P,exports.extractFilterValue=t.F,exports.extractTouchedArtifacts=extractTouchedArtifacts,exports.extractTouchedDocuments=extractTouchedDocuments,exports.extractTouchedRecords=extractTouchedRecords,exports.extractValueRefs=extractValueRefs,exports.familyOf=familyOf,exports.filterOperatorsOfType=t.w,exports.filterStateSchema=t.c,exports.filterTargetsOf=t.T,exports.findGrantIssues=findGrantIssues,exports.findModelByReference=findModelByReference,exports.findRelationAttribute=findRelationAttribute,exports.findWorkstationHarness=findWorkstationHarness,exports.flagRegistry=Tt,exports.focusOf=focusOf,exports.form=form,exports.formFieldFlatKey=formFieldFlatKey,exports.formFieldKey=formFieldKey,exports.formRegistry=tn,exports.formatAgentStreamFrameId=formatAgentStreamFrameId,exports.formatAttributeValue=formatAttributeValue,exports.formatByteSize=formatByteSize,exports.formatComputedResult=e.w,exports.formatLocationValue=formatLocationValue,exports.formatZodErrors=i.t,exports.formula=formula,exports.fromDraftableView=fromDraftableView,exports.generateId=c.i,exports.getAttributeCapabilities=t.rt,exports.getAttributeFilterOperators=t.it,exports.getEditableLabelAttribute=getEditableLabelAttribute,exports.getErrorMessage=getErrorMessage,exports.getLiveProtocolPayloadChannel=getLiveProtocolPayloadChannel,exports.getOperatorPolarity=t.A,exports.getRecordCreatorPrincipalId=getRecordCreatorPrincipalId,exports.getRollupFilterOperators=t.K,exports.getSingleAttributeFromExpression=getSingleAttributeFromExpression,exports.getSlotFieldTargets=getSlotFieldTargets,exports.getSystemAttributeI18nKey=t.pt,exports.getSystemAttributeList=t.mt,exports.getUserDisplayName=getUserDisplayName,exports.grantCovers=grantCovers,exports.grantsFromLevels=grantsFromLevels,exports.group=group,exports.guidanceForBatch=guidanceForBatch,exports.hasOptions=hasOptions,exports.iconNameSchema=e.W,exports.imageModelFormatDefect=imageModelFormatDefect,exports.imageModelIdSchema=H,exports.inboundRelationAttributes=inboundRelationAttributes,exports.includesAction=includesAction,exports.indexBy=c.a,exports.inferInverseCardinality=t.X,exports.inferRollupReturnType=inferRollupReturnType,exports.inferenceReasoningSchema=B,exports.inferenceRoutingSchema=V,exports.inferenceSpeedSchema=z,exports.isAgentMessageMetadata=isAgentMessageMetadata,exports.isAgentNotificationMetadata=isAgentNotificationMetadata,exports.isAgentUIDataName=isAgentUIDataName,exports.isAgentUIMessageBatch=isAgentUIMessageBatch,exports.isAgentWrittenAuditEntry=isAgentWrittenAuditEntry,exports.isAttributeFilterable=t.at,exports.isAttributeGroupable=t.ot,exports.isAttributeInUseError=n.isAttributeInUseError,exports.isAttributeKanbanGroupable=t.st,exports.isAttributeSearchable=t.ct,exports.isAttributeSortable=t.Z,exports.isBilateralRelation=t.Q,exports.isCalendarDay=t.B,exports.isCatalogResource=isCatalogResource,exports.isCheckboxEquality=isCheckboxEquality,exports.isClaimableSessionStatus=isClaimableSessionStatus,exports.isComputedAttribute=isComputedAttribute,exports.isComputedFunctionName=e.A,exports.isCurrentTargetToken=isCurrentTargetToken,exports.isDateRangeValue=e.V,exports.isDefaultRole=isDefaultRole,exports.isDocumentAttribute=isDocumentAttribute,exports.isDynamicValue=t.L,exports.isEdgePayload=isEdgePayload,exports.isEmptyObject=isEmptyObject,exports.isFormDefinition=isFormDefinition,exports.isFormFieldsRow=isFormFieldsRow,exports.isFormFreeFieldRef=isFormFreeFieldRef,exports.isFormHeadingRow=isFormHeadingRow,exports.isFormSeparatorRow=isFormSeparatorRow,exports.isFormSlotFieldRef=isFormSlotFieldRef,exports.isFormTextRow=isFormTextRow,exports.isLabelExpression=isLabelExpression,exports.isLiveEventEnvelope=isLiveEventEnvelope,exports.isLiveEventPayload=isLiveEventPayload,exports.isLiveEventPayloadForType=isLiveEventPayloadForType,exports.isLiveEventType=isLiveEventType,exports.isLocationFilterProperty=t.lt,exports.isLocationPartOperator=t.E,exports.isMailProvider=isMailProvider,exports.isMailboxListMode=isMailboxListMode,exports.isManagedSystemAttribute=t.ht,exports.isNativeObjectName=e.$,exports.isNoValueOperator=t.q,exports.isNotEmpty=isNotEmpty,exports.isNotFoundError=n.isNotFoundError,exports.isNullishOrEmptyString=l.t,exports.isObjectReferencedError=n.isObjectReferencedError,exports.isOpenToolPartState=isOpenToolPartState,exports.isPlainRecord=e.T,exports.isProtectedResourceError=n.isProtectedResourceError,exports.isProviderDraft=isProviderDraft,exports.isPublishedConfigChangeAllowed=isPublishedConfigChangeAllowed,exports.isRecordReferencedError=n.isRecordReferencedError,exports.isRelativeDateValue=t.h,exports.isReplyMode=isReplyMode,exports.isRoleLabelTaken=isRoleLabelTaken,exports.isRoutableModel=isRoutableModel,exports.isRoutineActorMetadata=isRoutineActorMetadata,exports.isSchemaError=n.isSchemaError,exports.isSetMembershipOperator=t.j,exports.isStandardSchema=isStandardSchema,exports.isSystemPartCode=isSystemPartCode,exports.isTerminalSessionStatus=isTerminalSessionStatus,exports.isTerminalState=isTerminalState,exports.isToolApprovalState=isToolApprovalState,exports.isUnderRoutingCeiling=isUnderRoutingCeiling,exports.isUniversalRelation=t.$,exports.isValidationError=n.isValidationError,exports.isValuePresent=l.n,exports.isWorkstationHarnessId=isWorkstationHarnessId,exports.jsonFlag=jsonFlag,exports.legacyStatusToSessionState=legacyStatusToSessionState,exports.levelActions=levelActions,exports.levelOf=levelOf,exports.listView=listView,exports.listedObjectWithoutCatalogue=listedObjectWithoutCatalogue,exports.liveChannelKey=liveChannelKey,exports.location=location,exports.locationPartFilterTarget=t.D,exports.markdownToPlainText=markdownToPlainText,exports.matchesAccepts=matchesAccepts,exports.mentionReferenceSchema=rr,exports.modelDefinitionSchema=ir,exports.modelReferenceSchema=qn,exports.modelReferenceSpellings=modelReferenceSpellings,exports.multiselect=multiselect,exports.multiselectOptionWriteSchema=e.s,exports.namedTargetSchema=ji,exports.nativeAgentUIPartIdMetadataKey=nativeAgentUIPartIdMetadataKey,exports.nonOperationalDeploymentBarrierAttestorV1=ln,exports.normalizeDateValue=e.H,exports.normalizeFilterRule=t.b,exports.normalizeForEdgeRpc=t.M,exports.normalizeOperator=t.x,exports.normalizePricing=normalizePricing,exports.normalizeRoleGrants=normalizeRoleGrants,exports.normalizeRoleLabel=normalizeRoleLabel,exports.now=t.R,exports.number=number,exports.numberFlag=numberFlag,exports.object=object,exports.objectPermissionFlags=objectPermissionFlags,exports.operationPace=operationPace,exports.orderAgentSessionMessages=orderAgentSessionMessages,exports.parseAgentStreamFrameId=parseAgentStreamFrameId,exports.parseAttributeConfig=e.c,exports.parseAttributeConfigForCreate=e.l,exports.parseAttributeConfigForUpdate=e.u,exports.parseComputedFormula=e.D,exports.parseCountMode=parseCountMode,exports.parseDeviceChannelFrame=parseDeviceChannelFrame,exports.parseFilterInstant=parseFilterInstant,exports.parseLiveChannelKey=parseLiveChannelKey,exports.parseModelCatalog=parseModelCatalog,exports.parseNamedTarget=parseNamedTarget,exports.parseNativeAgentUIPartIdsMetadata=parseNativeAgentUIPartIdsMetadata,exports.parseOperation=parseOperation,exports.parseOptionalCountMode=parseOptionalCountMode,exports.parseQualifiedAttribute=t.U,exports.parseQualifiedToolName=parseQualifiedToolName,exports.parseRecordAccessRole=parseRecordAccessRole,exports.parseResourceVisibility=e.Z,exports.parseSchemaGroupPresentation=parseSchemaGroupPresentation,exports.parseSchemaState=parseSchemaState,exports.parseServerFrame=parseServerFrame,exports.parseWorkerFrame=parseWorkerFrame,exports.permissionGrantSchema=ut,exports.phone=phone,exports.planAttributeRemoval=planAttributeRemoval,exports.presentationOf=presentationOf,exports.pricePerMillion=pricePerMillion,exports.propertyAttributeSchema=e.d,exports.propertyAttributeWireSchema=e.f,exports.propertySchemaSchema=e.p,exports.propertySchemaWireSchema=e.m,exports.proposalTargetKey=proposalTargetKey,exports.providerNameSchema=Kn,exports.publishedViewContentDefinitionSchema=t.l,exports.qualifiedPropertyDefs=qualifiedPropertyDefs,exports.qualifiedToolName=qualifiedToolName,exports.readAccessLevels=readAccessLevels,exports.readArtifactResult=readArtifactResult,exports.readFormFieldValue=readFormFieldValue,exports.readGeneratedImageResult=readGeneratedImageResult,exports.readRoleLevels=readRoleLevels,exports.recentActivityEntryKey=recentActivityEntryKey,exports.reconcileRelationAttributes=reconcileRelationAttributes,exports.refineTrigger=refineTrigger,exports.refuseForeignKeys=e.h,exports.regenerateDerived=regenerateDerived,exports.registry=Dt,exports.rejectUnknownAttributesOrThrow=d.r,exports.relation=relation,exports.relationAcceptsObject=relationAcceptsObject,exports.relationProperty=relationProperty,exports.relationPropertyDefs=relationPropertyDefs,exports.relationTargetObjectName=relationTargetObjectName,exports.relationTargets=relationTargets,exports.relationTargetsOf=t.et,exports.relationValueIds=relationValueIds,exports.removeObjectException=removeObjectException,exports.renameAttributeInContent=renameAttributeInContent,exports.renamedFromTarget=renamedFromTarget,exports.renderLabelExpression=renderLabelExpression,exports.requestedCapabilities=requestedCapabilities,exports.requireRecordContentContext=requireRecordContentContext,exports.requireSingleRelationTarget=requireSingleRelationTarget,exports.requiredTargetKeys=requiredTargetKeys,exports.resolveAttributeDefaultValue=resolveAttributeDefaultValue,exports.resolveCollectionActions=resolveCollectionActions,exports.resolveContentNavigation=resolveContentNavigation,exports.resolveEffectiveFilterType=t.ut,exports.resolveFieldRequired=resolveFieldRequired,exports.resolveIsWithinBounds=t.g,exports.resolvePropertyDefinitions=resolvePropertyDefinitions,exports.resolveTextPattern=r.r,exports.resolveUtcDayBounds=t._,exports.resolveViewContents=resolveViewContents,exports.richtext=richtext,exports.roleNameFromLabel=roleNameFromLabel,exports.rollup=rollup,exports.rollupToFormulaExpression=rollupToFormulaExpression,exports.routedMessageInferenceSchema=Qn,exports.routingPrice=routingPrice,exports.sameActions=sameActions,exports.sameStableValue=c.c,exports.schemaGroupKey=schemaGroupKey,exports.schemaStateSourcePayload=schemaStateSourcePayload,exports.select=select,exports.selectOptionWriteSchema=e.g,exports.serializeCanonicalJson=c.l,exports.serializeStableJson=c.u,exports.sessionInferencePatchSchema=Zn,exports.sessionStateToLegacyStatus=sessionStateToLegacyStatus,exports.setCapabilityLevel=setCapabilityLevel,exports.setDefaultObjectLevel=setDefaultObjectLevel,exports.setObjectException=setObjectException,exports.setPurge=setPurge,exports.singleRelationTarget=singleRelationTarget,exports.sortsSchema=t.u,exports.status=status,exports.statusGroupSchema=e._,exports.statusOptionWriteSchema=e.v,exports.stillMissing=stillMissing,exports.storedContentDefinition=storedContentDefinition,exports.stringFlag=stringFlag,exports.summarizeDraft=summarizeDraft,exports.summarizeGroup=summarizeGroup,exports.systemColumnFilterTarget=t.O,exports.systemPermissionFlags=systemPermissionFlags,exports.targetSnapshot=targetSnapshot,exports.targetTokenOf=targetTokenOf,exports.targetTokensFor=targetTokensFor,exports.text=text,exports.toAttribute=toAttribute,exports.toDraftableAttribute=toDraftableAttribute,exports.toDraftableAttributes=toDraftableAttributes,exports.toDraftableObject=toDraftableObject,exports.toDraftableView=toDraftableView,exports.toMultiValueOperator=t.N,exports.toUndefinedIfEmpty=toUndefinedIfEmpty,exports.toUtcDayString=t.v,exports.today=t.z,exports.todoItemSchema=sr,exports.todoPlanSchema=cr,exports.toolImpactSchema=$n,exports.touchedObjectIds=touchedObjectIds,exports.uncoveredGrants=uncoveredGrants,exports.updatedAttributeConfig=updatedAttributeConfig,exports.user=user,exports.validateAttributeName=e.P,exports.validateContentViewCatalogue=validateContentViewCatalogue,exports.validateDraft=d.a,exports.validateDraftOrThrow=d.o,exports.validateLabelExpression=validateLabelExpression,exports.validateObject=d.s,exports.validateObjectExpressions=validateObjectExpressions,exports.validateObjectName=e.L,exports.validateObjectOrThrow=d.c,exports.validateQualifiedRule=t.m,exports.validateStoredViews=validateStoredViews,exports.validateViewName=e.z,exports.verifyDeploymentBarrierAttestationV1=verifyDeploymentBarrierAttestationV1,exports.viewIdFor=viewIdFor,exports.viewIdentityKey=viewIdentityKey,exports.viewNamesAttribute=viewNamesAttribute,exports.viewRegistry=Zt,exports.wireOmittedConfigKeysFor=e.y,exports.withoutUnknownOptionKeys=e.b,exports.workspaceViewAuthoring=workspaceViewAuthoring,exports.workstationModelProvider=workstationModelProvider;
|