@stndrds/schema 1.0.0-alpha.356 → 1.0.0-alpha.357
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/index.d.mts +13 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +1 -1
- package/dist/index.mjs +9 -9
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -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(),Xt=markSystemView(detailView(qt,`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()),Zt=markSystemView(listView(Gt,`Meetings`).for(F).default().tab(`workspace`,`Shared`,M.collection().object(F).table().icon(`users`).visibility(`workspace`).columns(...Jt).sort(I.startsAt,`desc`)).tab(`mine`,`My meetings`,M.collection().object(F).table().icon(`lock`).visibility(`private`).columns(...Jt).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 Qt=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 $t=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)??$t.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 en=[Object.freeze(Vt)];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 en)this.extensions.set(e.name,e)}};const tn=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 nn=new FormRegistry,rn=[`attestorIdentity`,`evidenceDigest`,`maintenanceEpoch`,`observedZeroAt`,`resumeRevision`,`version`,`workloadInventoryDigest`],an=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,on=/^[0-9a-f]{40}$/,sn=/^[0-9a-f]{64}$/,cn=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/,ln=/^(\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=ln.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!==rn.length||r.some((e,t)=>e!==rn[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`,an,`must be a lowercase canonical UUID`),a=requirePattern(e,`resumeRevision`,on,`must be a lowercase 40-character Git SHA`),o=requireCanonicalTimestamp(e),s=requirePattern(e,`attestorIdentity`,cn,`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`,sn,`must be exactly 64 lowercase hexadecimal characters`),evidenceDigest:requirePattern(e,`evidenceDigest`,sn,`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 un=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 dn=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}),fn=[`membership-unknown`,`sort-unknown`,`permissions-changed`],pn=[`permission-revoked`,`workspace-left`,`object-deleted`],mn=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],hn=[`type`,`objectId`,`recordId`,`recordVersion`],gn=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],_n=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],vn=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&dn.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,hn)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$2(e)&&hasOnlyKeys(e,_n)&&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,gn)&&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,fn)}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=>mn.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,vn)&&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 yn=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,yn)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const bn=[`ok`,`low`,`exhausted`,`paused`],xn=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,bn)&&isOneOf(e.mode,xn)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,pn)}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 Sn=[{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)`}],Cn=new Date(0).setUTCFullYear(1,0,1),wn=/^\d{4}-\d{2}-\d{2}$/,Tn=new Set([`createdAt`,`updatedAt`,`deletedAt`]),En=/^(\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=En.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<Cn?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 Tn.has(e.name)}function instantWindow(e){let t=parseFilterInstant(e);return t===null?null:{startMs:t,endMs:t+(typeof e==`string`&&wn.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(wn.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`?wn.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}),Dn=[...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,...Dn])}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 On={status:`connector_status`,error:`connector_error`,provider:`connector_provider`};let kn=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const An=`DRAFT`;function isProviderDraft(e){return e.includes(An)}const jn=[`threads`,`messages`];function isMailboxListMode(e){return jn.includes(e)}const Mn=[`reply`,`reply_all`];function isReplyMode(e){return Mn.includes(e)}const Nn=[`force`,`skip`],Pn=[`none`,`all`,`external_only`],Fn={override:null,status:`none`,failureReason:null,botId:null},In=/^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&&!In.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 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 z=f.z.number().finite().nonnegative(),Kn=f.z.enum(le),B=f.z.enum(ue),V=f.z.enum(de),H=f.z.enum(me),qn=f.z.object({provider:Kn,model:f.z.string().min(1)}).strict(),Jn=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._-]*$/),Yn=f.z.object({model:qn.optional(),speed:B.optional(),reasoning:V.optional(),imageModel:U.optional(),routing:H.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: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`}),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: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(),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:z.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: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()]),tr=f.z.object({id:f.z.string(),name:f.z.string(),mimeType:f.z.string(),size:z}).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:z,endIndex:z}).strict(),ir=f.z.object({provider:Kn,model:f.z.string(),maxTokens:z.optional(),contextWindow:z.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:z,output:z}).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:z.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:z,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: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: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:U,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 W={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`)},G={...Or,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`)},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`,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 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({...K,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({...K,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({...G,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({...K,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({...K,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({...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(),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({...G,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({...K,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({...K,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({...G,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]),q=[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`,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 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 J={...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({...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} »`}),ni=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}),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({...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}`}),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({...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(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 Y=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],di=f.z.object(Y.reduce((e,t)=>(Object.assign(e,wireWriteConfigOf(t).shape),e),{})).strict(),fi=oi.filter(e=>!Y.includes(e)),pi=Object.fromEntries(Y.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(Y).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} »`}),gi={...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 _i=f.z.object({...gi,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 vi=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:_i,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} »`}),yi=f.z.object({...gi,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 bi=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:yi,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} »`}),xi=f.z.object({...gi,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 Si=defineOperation({type:`rename_draft_attribute`,summary:`Renames a draft-added attribute; views and samples follow.`,schema:xi,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 Ci=f.z.guid();function carriesNonRecordId(e){let t=Array.isArray(e)?e:[e],n=relationValueIds(e);return n.length<t.length||n.some(e=>!Ci.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 wi=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=[ti,ri,ai,hi,vi,bi,Si,wi,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(),Ti=[...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 Ei=`bilateral`;function frozenPart(e){if(!e||typeof e!=`object`)return c.s({});let{[Ei]: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()]),Di=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 Oi=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=Di.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 ki={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`},Ai=`normal`;function operationPace(e){return Object.hasOwn(ki,e)?ki[e]:Ai}const ji={major:{replay:4e3,live:2500},normal:{replay:2600,live:1800},minor:{replay:1400,live:1100}};function dwellForStep(e,t,n){let r=(ji[e]??ji[Ai])[t],i=900+40*(n||0);return Math.min(6e3,Math.max(r,i))}const Q=f.z.string().min(1),Mi=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=Mi.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 Ni=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 Pi={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of Pi[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 Fi=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:Fi}).strict())})}const Ii=membersOf(X,[Ni]),Li=membersOf(q),Ri=unionOf(Ii),zi=unionOf(Li),Bi={schema:Ri,view:zi},Vi={schema:unionOf(wireMembersOf(X,[Ni])),view:unionOf(wireMembersOf(q))},Hi=new Map([...X.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...q.map(e=>[e.type,`view`])]);function familyOf(e){return Hi.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 Ui=[`draft_schema`],Wi=[{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`),Gi=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`),$,$,$])]),Ki=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`:Ki.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=Gi.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:Gi,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=Oi,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=Ti,exports.ALL_PIPES=T,exports.ARTIFACT_FILE_ROLES=Ie,exports.ARTIFACT_KINDS=Pe,exports.ARTIFACT_LIST_VIEW=Wt,exports.ARTIFACT_OBJECT=Ht,exports.ARTIFACT_OBJECT_NAME=P,exports.ARTIFACT_PREVIEW_EXTENSION=Vt,exports.ARTIFACT_RETENTIONS=Fe,exports.ARTIFACT_VIEW=Ut,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=Sn,exports.COMPUTED_FUNCTION_NAMES=e.k,exports.CONNECTOR_CALLBACK_PARAM=On,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=Wi,exports.DRAFT_WRITE_TOOL_NAMES=Ui,exports.DRIVE_LIST_VIEW=Bt,exports.DRIVE_OBJECT=Rt,exports.DRIVE_OBJECT_NAME=N,exports.DRIVE_VIEW=zt,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=Bi,exports.FAMILY_WIRE_INPUTS=Vi,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=Tt,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=dn,exports.LOCATION_FILTER_PROPERTIES=t.nt,exports.MAILBOX_LIST_MODES=jn,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=qt,exports.MEETING_LIST_VIEW=Zt,exports.MEETING_LIST_VIEW_ID=Gt,exports.MEETING_OBJECT=Yt,exports.MEETING_OBJECT_NAME=F,exports.MEETING_VIEW=Xt,exports.MEETING_WRITE_SOURCE=Kt,exports.MEMORY_LIST_VIEW=Lt,exports.MEMORY_OBJECT=Pt,exports.MEMORY_VIEW=It,exports.MIXED_LEVEL=dt,exports.McpOAuthCompletionMode=kn,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=Fn,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=ki,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=ji,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=An,exports.PROVIDER_NAMES=le,exports.PUBLISHED_CONFIG_EXCEPTION=Ei,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=Nn,exports.RECORDING_POLICIES=Pn,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=Ni,exports.REPLY_MODES=Mn,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=Ri,exports.SCHEMA_SOURCE_ID_PATTERN=R,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=At,exports.SKILL_LIST_VIEW=Nt,exports.SKILL_OBJECT=jt,exports.SKILL_VIEW=Mt,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=q,exports.VIEW_OPERATION_INPUT=zi,exports.ValidationError=n.ValidationError,exports.ViewBuilder=wt,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=tn,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=Et,exports.focusOf=focusOf,exports.form=form,exports.formFieldFlatKey=formFieldFlatKey,exports.formFieldKey=formFieldKey,exports.formRegistry=nn,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=rr,exports.modelDefinitionSchema=ir,exports.modelReferenceSchema=qn,exports.modelReferenceSpellings=modelReferenceSpellings,exports.multiselect=multiselect,exports.multiselectOptionWriteSchema=e.s,exports.namedTargetSchema=Mi,exports.nativeAgentUIPartIdMetadataKey=nativeAgentUIPartIdMetadataKey,exports.nonOperationalDeploymentBarrierAttestorV1=un,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=Ot,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=Qt,exports.wireOmittedConfigKeysFor=e.y,exports.withoutUnknownOptionKeys=e.b,exports.workspaceViewAuthoring=workspaceViewAuthoring,exports.workstationModelProvider=workstationModelProvider;
|
|
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 Qt=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 $t=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)??$t.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 en=[Object.freeze(Vt)];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 en)this.extensions.set(e.name,e)}};const tn=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 nn=new FormRegistry,rn=[`attestorIdentity`,`evidenceDigest`,`maintenanceEpoch`,`observedZeroAt`,`resumeRevision`,`version`,`workloadInventoryDigest`],an=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,on=/^[0-9a-f]{40}$/,sn=/^[0-9a-f]{64}$/,cn=/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/,ln=/^(\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=ln.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!==rn.length||r.some((e,t)=>e!==rn[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`,an,`must be a lowercase canonical UUID`),a=requirePattern(e,`resumeRevision`,on,`must be a lowercase 40-character Git SHA`),o=requireCanonicalTimestamp(e),s=requirePattern(e,`attestorIdentity`,cn,`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`,sn,`must be exactly 64 lowercase hexadecimal characters`),evidenceDigest:requirePattern(e,`evidenceDigest`,sn,`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 un=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 dn=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}),fn=[`membership-unknown`,`sort-unknown`,`permissions-changed`],pn=[`permission-revoked`,`workspace-left`,`object-deleted`],mn=[`inboxState`,`workState`,`lockedAt`,`lockedByActorId`,`readAt`,`archivedAt`,`snoozedUntil`,`completedAt`,`dismissedAt`,`updatedAt`],hn=[`type`,`objectId`,`recordId`,`recordVersion`],gn=[`type`,`objectId`,`recordId`,`recordVersion`,`record`],_n=[`id`,`objectId`,`visibility`,`ownedBy`,`label`,`values`,`metadata`,`createdAt`,`updatedAt`,`createdBy`,`lastUpdatedBy`,`schemaVersion`],vn=[`type`,`targetActorId`,`archivedCount`,`version`,`updatedAt`];function isLiveEventType(e){return typeof e==`string`&&dn.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,hn)&&hasString(e,`objectId`)&&hasString(e,`recordId`)&&hasVersion(e,`recordVersion`)}function isRecordLiveSnapshot(e){return isRecord$2(e)&&hasOnlyKeys(e,_n)&&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,gn)&&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,fn)}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=>mn.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,vn)&&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 yn=[`none`,`scheduled`,`recording`,`completed`,`failed`];function isMeetingRecordingPatchPayload(e){return e.type===`meeting.recording.patch`&&hasNonEmptyString(e,`meetingId`)&&isOneOf(e.status,yn)&&isNullableString(e.failureReason)&&hasIsoDateString(e,`updatedAt`)}const bn=[`ok`,`low`,`exhausted`,`paused`],xn=[`metering-only`,`contract`,`wallet`];function isWalletStatePayload(e){return e.type===`wallet.state`&&isOneOf(e.status,bn)&&isOneOf(e.mode,xn)&&hasIsoDateString(e,`updatedAt`)}function isChannelRevokedPayload(e){return e.type===`channel.revoked`&&hasString(e,`channel`)&&isOneOf(e.reason,pn)}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 Sn=[{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)`}],Cn=new Date(0).setUTCFullYear(1,0,1),wn=/^\d{4}-\d{2}-\d{2}$/,Tn=new Set([`createdAt`,`updatedAt`,`deletedAt`]),En=/^(\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=En.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<Cn?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 Tn.has(e.name)}function instantWindow(e){let t=parseFilterInstant(e);return t===null?null:{startMs:t,endMs:t+(typeof e==`string`&&wn.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(wn.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`?wn.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}),Dn=[...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,...Dn])}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 On={status:`connector_status`,error:`connector_error`,provider:`connector_provider`};let kn=function(e){return e.Desktop=`desktop`,e}({});function isMailProvider(e){return e===`gmail`||e===`outlook`}const An=`DRAFT`;function isProviderDraft(e){return e.includes(An)}const jn=[`threads`,`messages`];function isMailboxListMode(e){return jn.includes(e)}const Mn=[`reply`,`reply_all`];function isReplyMode(e){return Mn.includes(e)}const Nn=[`force`,`skip`],Pn=[`none`,`all`,`external_only`],Fn={override:null,status:`none`,failureReason:null,botId:null},In=/^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&&!In.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 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 z=f.z.number().finite().nonnegative(),Kn=f.z.enum(le),B=f.z.enum(ue),V=f.z.enum(de),H=f.z.enum(me),qn=f.z.object({provider:Kn,model:f.z.string().min(1)}).strict(),Jn=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._-]*$/),Yn=f.z.object({model:qn.optional(),speed:B.optional(),reasoning:V.optional(),imageModel:U.optional(),routing:H.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: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`}),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: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(),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:z.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: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()]),tr=f.z.object({id:f.z.string(),name:f.z.string(),mimeType:f.z.string(),size:z}).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:z,endIndex:z}).strict(),ir=f.z.object({provider:Kn,model:f.z.string(),maxTokens:z.optional(),contextWindow:z.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:z,output:z}).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:z.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:z,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: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: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:U,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 W={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`)},G={...Or,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`)},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`,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 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({...K,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({...K,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({...G,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({...K,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({...K,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({...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(),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({...G,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({...K,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({...K,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({...G,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]),q=[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`,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 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 J={...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({...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} »`}),ni=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}),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({...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}`}),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({...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(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 Y=[`text`,`richtext`,`number`,`checkbox`,`date`,`phone`,`currency`,`location`,`user`],di=f.z.object(Y.reduce((e,t)=>(Object.assign(e,wireWriteConfigOf(t).shape),e),{})).strict(),fi=oi.filter(e=>!Y.includes(e)),pi=Object.fromEntries(Y.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(Y).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} »`}),gi={...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 _i=f.z.object({...gi,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 vi=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:_i,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} »`}),yi=f.z.object({...gi,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 bi=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:yi,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} »`}),xi=f.z.object({...gi,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 Si=defineOperation({type:`rename_draft_attribute`,summary:`Renames a draft-added attribute; views and samples follow.`,schema:xi,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 Ci=f.z.guid();function carriesNonRecordId(e){let t=Array.isArray(e)?e:[e],n=relationValueIds(e);return n.length<t.length||n.some(e=>!Ci.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 wi=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=[ti,ri,ai,hi,vi,bi,Si,wi,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(),Ti=[...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 Ei=`bilateral`;function frozenPart(e){if(!e||typeof e!=`object`)return c.s({});let{[Ei]: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()]),Di=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 Oi=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=Di.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 ki={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`},Ai=`normal`;function operationPace(e){return Object.hasOwn(ki,e)?ki[e]:Ai}const ji={major:{replay:4e3,live:2500},normal:{replay:2600,live:1800},minor:{replay:1400,live:1100}};function dwellForStep(e,t,n){let r=(ji[e]??ji[Ai])[t],i=900+40*(n||0);return Math.min(6e3,Math.max(r,i))}const Q=f.z.string().min(1),Mi=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=Mi.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 Ni=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 Pi={add_object:[`objectId`],add_sample_record:[`recordId`]};function relaxMintedKeys(e){return mapMember(e,e=>{let t={};for(let n of Pi[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 Fi=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:Fi}).strict())})}const Ii=membersOf(X,[Ni]),Li=membersOf(q),Ri=unionOf(Ii),zi=unionOf(Li),Bi={schema:Ri,view:zi},Vi={schema:unionOf(wireMembersOf(X,[Ni])),view:unionOf(wireMembersOf(q))},Hi=new Map([...X.map(e=>[e.type,`schema`]),[`remove_operation`,`schema`],...q.map(e=>[e.type,`view`])]);function familyOf(e){return Hi.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 Ui=[`draft_schema`],Wi=[{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`),Gi=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`),$,$,$])]),Ki=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`:Ki.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=Gi.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:Gi,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=Oi,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=Ti,exports.ALL_PIPES=T,exports.ARTIFACT_FILE_ROLES=Ie,exports.ARTIFACT_KINDS=Pe,exports.ARTIFACT_LIST_VIEW=Wt,exports.ARTIFACT_OBJECT=Ht,exports.ARTIFACT_OBJECT_NAME=P,exports.ARTIFACT_PREVIEW_EXTENSION=Vt,exports.ARTIFACT_RETENTIONS=Fe,exports.ARTIFACT_VIEW=Ut,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=Sn,exports.COMPUTED_FUNCTION_NAMES=e.k,exports.CONNECTOR_CALLBACK_PARAM=On,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=Wi,exports.DRAFT_WRITE_TOOL_NAMES=Ui,exports.DRIVE_LIST_VIEW=Bt,exports.DRIVE_OBJECT=Rt,exports.DRIVE_OBJECT_NAME=N,exports.DRIVE_VIEW=zt,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=Bi,exports.FAMILY_WIRE_INPUTS=Vi,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=Tt,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=dn,exports.LOCATION_FILTER_PROPERTIES=t.nt,exports.MAILBOX_LIST_MODES=jn,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.MCP_SERVER_NAME_MAX_LENGTH=100,exports.MEETING_ATTRIBUTES=I,exports.MEETING_DETAIL_VIEW_ID=qt,exports.MEETING_LIST_VIEW=Zt,exports.MEETING_LIST_VIEW_ID=Gt,exports.MEETING_OBJECT=Yt,exports.MEETING_OBJECT_NAME=F,exports.MEETING_VIEW=Xt,exports.MEETING_WRITE_SOURCE=Kt,exports.MEMORY_LIST_VIEW=Lt,exports.MEMORY_OBJECT=Pt,exports.MEMORY_VIEW=It,exports.MIXED_LEVEL=dt,exports.McpOAuthCompletionMode=kn,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=Fn,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=ki,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=ji,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=An,exports.PROVIDER_NAMES=le,exports.PUBLISHED_CONFIG_EXCEPTION=Ei,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=Nn,exports.RECORDING_POLICIES=Pn,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=Ni,exports.REPLY_MODES=Mn,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=Ri,exports.SCHEMA_SOURCE_ID_PATTERN=R,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=At,exports.SKILL_LIST_VIEW=Nt,exports.SKILL_OBJECT=jt,exports.SKILL_VIEW=Mt,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=q,exports.VIEW_OPERATION_INPUT=zi,exports.ValidationError=n.ValidationError,exports.ViewBuilder=wt,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=tn,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=Et,exports.focusOf=focusOf,exports.form=form,exports.formFieldFlatKey=formFieldFlatKey,exports.formFieldKey=formFieldKey,exports.formRegistry=nn,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=rr,exports.modelDefinitionSchema=ir,exports.modelReferenceSchema=qn,exports.modelReferenceSpellings=modelReferenceSpellings,exports.multiselect=multiselect,exports.multiselectOptionWriteSchema=e.s,exports.namedTargetSchema=Mi,exports.nativeAgentUIPartIdMetadataKey=nativeAgentUIPartIdMetadataKey,exports.nonOperationalDeploymentBarrierAttestorV1=un,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=Ot,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=Qt,exports.wireOmittedConfigKeysFor=e.y,exports.withoutUnknownOptionKeys=e.b,exports.workspaceViewAuthoring=workspaceViewAuthoring,exports.workstationModelProvider=workstationModelProvider;
|