@stndrds/schema 1.0.0-alpha.321 → 1.0.0-alpha.323
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/{chunk-MXZ3AF5X.js → chunk-2FJ45VYQ.js} +1 -1
- package/dist/{chunk-OGFEFOJQ.mjs → chunk-WUFUIJRX.mjs} +1 -1
- package/dist/index.d.mts +45 -10
- package/dist/index.d.ts +45 -10
- package/dist/index.js +14 -14
- package/dist/index.mjs +14 -14
- package/dist/validation/all.js +1 -1
- package/dist/validation/all.mjs +1 -1
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {b as b$3,j as j$2}from'./chunk-YJSVWV3Z.mjs';export{a as NonJsonValueError,f as asTenantId,g as asUserId,b as canonicalStringify,j as deepEqual,h as generateId,i as indexBy,e as sameStableValue,d as serializeCanonicalJson,c as serializeStableJson}from'./chunk-YJSVWV3Z.mjs';import {d,K,N as N$1,W as W$1,n as n$1,j as j$1,_,X as X$1,Y,g,h as h$2,C as C$1,B,z as z$1,v as v$2,Z as Z$1}from'./chunk-
|
|
2
|
-
var ko=["fyi","task","question","handoff","system"],jo=["low","normal","high","urgent"],_o=["public","internal","sensitive"],Po=["unread","read","archived","snoozed"],Mo=["none","pending","processing","completed","dismissed","expired","failed"],Wc="agent.session.waiting_human",Gc="agent.task.assigned",Kc="agent.question.requested",jg=[Wc,Gc,Kc];var Pg=["name","type"],Mg=["required","hidden","archived","deprecated","defaultValue","config","order","unique"],Fg=["label","description","placeholder","icon"];var Ht=["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"],ae="*";function Lg(e){return e.type!=="relation"||!Array.isArray(e.targets)?[]:e.targets.map(t=>t.object).filter(t=>t!==ae)}a(Lg,"relationTargetsOf");function Fo(e){return e.targets.length===1&&e.targets[0].object===ae}a(Fo,"isUniversalRelation");function $g(e){return e.bilateral!==void 0}a($g,"isBilateralRelation");function Vo(e){return "many"}a(Vo,"inferInverseCardinality");function Ug(e){return n$1(e)}a(Ug,"isAttributeSortable");var Wg=["record","object","attribute","view","user","role","settings","file","agent","schema_source"],Gg=["record.created","record.updated","record.deleted","record.restored","record.purged","object.created","object.updated","object.deleted","attribute.created","attribute.updated","attribute.deleted","view.created","view.updated","view.deleted","schema_source.applied","schema_source.removed","user.created","user.invited","user.updated","user.deleted","user.login","user.logout","role.created","role.updated","role.deleted","role.assigned","role.revoked","settings.updated","file.uploaded","file.updated","file.deleted"];function Hg(e){return e.phase==="terminal"}a(Hg,"isTerminalState");function Jg(e){switch(e.phase){case "running":return "active";case "queued":return "idle";case "parked":if(e.parkedOn===void 0)throw new b$1("parked state without parkedOn",a$2.INVARIANT_VIOLATION);return e.parkedOn==="agents"?"waiting_agents":"waiting_human";case "terminal":if(e.outcome===void 0)throw new b$1("terminal state without outcome",a$2.INVARIANT_VIOLATION);return e.outcome}}a(Jg,"sessionStateToLegacyStatus");function Qg(e){switch(e){case "active":return {phase:"running"};case "idle":return {phase:"queued"};case "waiting_human":return {phase:"parked",parkedOn:"human",humanRequestIds:[]};case "waiting_agents":return {phase:"parked",parkedOn:"agents"};default:return {phase:"terminal",outcome:e}}}a(Qg,"legacyStatusToSessionState");var Yc=["completed","failed","cancelled","timeout","expired"];function Zg(e){return Yc.includes(e)}a(Zg,"isTerminalSessionStatus");var Hc=["idle","completed","waiting_human","waiting_agents","cancelled","failed","timeout"];function Xg(e){return Hc.includes(e)}a(Xg,"isClaimableSessionStatus");var Bo=Object.freeze({mutation:"ask",destructive:"ask",outward:"ask"}),ey=["active","completed","abandoned"],Lo=["openai","anthropic","google","spacexai","deepseek","moonshotai","alibaba","mistral","minimax","meta","zai"],$o=["standard","fast"],Uo=["none","minimal","low","medium","high","xhigh"];function ty(e){return e.label?.trim()||e.name}a(ty,"agentDisplayName");var qo=["approval-requested","approval-responded","approval-dispatched"],Jc=["streaming","running","pending",...qo];function ny(e){return Jc.includes(e)}a(ny,"isOpenToolPartState");function ry(e){return qo.includes(e)}a(ry,"isToolApprovalState");var zn=["CREDITS_EXHAUSTED"];function iy(e){return typeof e=="string"&&zn.includes(e)}a(iy,"isSystemPartCode");function Qc(e,t){let n=e.createdAt.getTime()-t.createdAt.getTime();return n===0?e.id.localeCompare(t.id):n}a(Qc,"compareAgentSessionMessages");function oy(e){return [...e].sort(Qc)}a(oy,"orderAgentSessionMessages");var ay=["pending","in_progress","completed","blocked"],sy=50,cy=80,uy=500;var my="session-state",Zc="__stndrdsNativeUiPartIds",Xc=1,eu="Native agent UI part IDs metadata is invalid";function Ue(){throw new h$1(eu,[])}a(Ue,"invalidNativePartIds");function zo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}a(zo,"isPlainRecord");function tu(e,t){if(e.type==="text"||e.type==="reasoning")return `${e.type}:${t}`;if(e.type==="tool")return `tool:${e.toolCallId}`}a(tu,"nativeAgentUIPartIdMetadataKey");function fy(e){let t=e.metadata?.[Zc];zo(t)||Ue(),(Object.keys(t).length!==2||t.schemaVersion!==Xc||!zo(t.partIds))&&Ue();let n=new Map;for(let[s,c]of e.parts.entries()){let u=tu(c,s);if(!u||n.has(u)){u&&Ue();continue}n.set(u,c);}let r=Object.entries(t.partIds);r.length!==n.size&&Ue();let o=new Map,a={};for(let[s,c]of r){let u=n.get(s);u&&typeof c=="string"&&c.length>0||Ue();let l=o.get(c);l&&(u.type==="tool"||l!==u.type)&&Ue(),u.type==="tool"&&c!==u.toolCallId&&Ue(),o.set(c,u.type),a[s]=c;}return a}a(fy,"parseNativeAgentUIPartIdsMetadata");var yy=16e3,hy=3200,Ay=6400,xy=16e3,Ty=65536,wy=15e3,Sy=1e4,Iy=5e3,Ry="google/gemini-3.5-transcribe-live",Cy={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2};var Ey=["web","presentation","document","spreadsheet","image","code","other"],Ny=["ephemeral","conversation","persistent"],Dy=["source","preview","entrypoint","asset"];var Wo=5;function jy(e){return e instanceof Error?e.message:typeof e=="string"?e:e&&typeof e=="object"?"message"in e&&typeof e.message=="string"?e.message:JSON.stringify(e):String(e)}a(jy,"getErrorMessage");function Fy(e){return typeof e=="object"&&e!==null&&"slots"in e&&"steps"in e&&"name"in e&&typeof e.name=="string"&&Array.isArray(e.slots)&&Array.isArray(e.steps)}a(Fy,"isFormDefinition");var Wn=["relation","multiRelation","formula","rollup","document","richtext","user"];function Go(e){return e.type==="slot"}a(Go,"isFormSlotFieldRef");function Gn(e){return e.type==="free"}a(Gn,"isFormFreeFieldRef");function Ly(e){return e.fieldRequired!==void 0?e.fieldRequired:e.slotMode==="create"&&e.attributeRequired===true}a(Ly,"resolveFieldRequired");function Ko(e){return e.additionalSlotIds?.length?[e.slotId,...e.additionalSlotIds]:[e.slotId]}a(Ko,"getSlotFieldTargets");function nu(e){return Go(e)?`${e.slotId}.${e.attribute}`:`free.${e.attribute.name}`}a(nu,"formFieldKey");function ru(e){return Go(e)?e.attribute:e.attribute.name}a(ru,"formFieldFlatKey");function $y(e,t){return e[nu(t)]??e[ru(t)]}a($y,"readFormFieldValue");function Jt(e){return e.type==="fields"}a(Jt,"isFormFieldsRow");function zy(e){return e.type==="heading"}a(zy,"isFormHeadingRow");function Wy(e){return e.type==="separator"}a(Wy,"isFormSeparatorRow");function Gy(e){return e.type==="text"}a(Gy,"isFormTextRow");var Kn=class Kn{async autocomplete(){return await Promise.resolve([])}async reverse(){return await Promise.resolve(null)}async geocode(){return await Promise.resolve(null)}};a(Kn,"NoopGeocodingAdapter");var Yo=Kn;var Yn=["read","create","update","delete","manage"];function Xy(e){return e.length===0?"none":e.length===1&&e[0]==="read"?"read-only":e.length===Yn.length&&Yn.every(t=>e.includes(t))?"full":"custom"}a(Xy,"actionsToAccessLevel");function eh(e){switch(e){case "full":return [...Yn];case "read-only":return ["read"];case "none":return []}}a(eh,"accessLevelToActions");function Qt(e){let t=e.properties;if(!t)return [];if(Array.isArray(t))return t;let n=t;return Array.isArray(n.definitions)?n.definitions:[]}a(Qt,"resolvePropertyDefinitions");function rh(e){return e.type==="select"||e.type==="status"||e.type==="multiselect"}a(rh,"hasOptions");var iu="Notetaker",ah={systemPrompt:null,meetingRecordingPolicy:"none",meetingBotDisplayName:iu};var ch=["active","suspended"],uh=["architect","manual","auto"];var dh=["square","landscape","portrait"];var Ho=["none","estimated","exact"];function ou(e){if(typeof e=="string"&&Ho.includes(e))return e;throw new h$1(`countMode must be one of: ${Ho.join(", ")} (received: ${String(e)})`,[])}a(ou,"parseCountMode");function fh(e){return e===void 0?void 0:ou(e)}a(fh,"parseOptionalCountMode");var bh=1e4;var hh=["storage.bytes","members.seats","data.live_records"];function au(e){return e==null?true:typeof e!="object"?false:Object.keys(e).length===0}a(au,"isEmptyObject");function Jo(e){return e!=null&&typeof e=="object"&&Object.keys(e).length>0}a(Jo,"isNotEmpty");function su(e){return Jo(e)?e:void 0}a(su,"toUndefinedIfEmpty");function cu(e){if(e<=0)return {value:0,unitIndex:0};let t=1e3,n=Math.min(4,Math.floor(Math.log(e)/Math.log(t)));return {value:Number.parseFloat((e/t**n).toFixed(1)),unitIndex:n}}a(cu,"computeByteMagnitude");var uu=["B","KB","MB","GB","TB"];function lA(e){let{value:t,unitIndex:n}=cu(e);return `${t} ${uu[n]}`}a(lA,"formatByteSize");var mA={ATTACHMENTS:"attachments"};function fA(e){return e.type==="document"}a(fA,"isDocumentAttribute");function bA(e,t){if(!t||t.length===0)return true;let n=e.name.toLowerCase();return t.some(r=>r.endsWith("/*")?e.mimeType.startsWith(r.slice(0,-1)):r.startsWith(".")?n.endsWith(r.toLowerCase()):e.mimeType===r)}a(bA,"matchesAccepts");var Qo=Object.freeze(["text","number","checkbox","date","phone","currency","status","select","multiselect","location"]);function Zt(e){let t=[];for(let n of e){let r=n.build();if(!Qo.includes(r.type))throw new Error(`Property type "${r.type}" is not supported in .qualifyWith()`);t.push(r);}return {definitions:t}}a(Zt,"buildPropertySchema");var xA="__";function TA(e){let t=e.indexOf("__");return t<=0||t+2>=e.length?{kind:"scalar",attribute:e}:{kind:"qualified",root:e.slice(0,t),property:e.slice(t+2)}}a(TA,"parseQualifiedAttribute");function wA(e,t){return `${e}__${t}`}a(wA,"buildQualifiedAttribute");function Oe(e){return typeof e=="object"&&e!==null&&typeof e.start=="string"}a(Oe,"isDateRangeValue");function lu(e,t){return a$1(e)?null:Oe(e)?t.endDate?{start:e.start,end:e.end??null}:e.start:typeof e=="string"?t.endDate?{start:e,end:null}:e:null}a(lu,"normalizeDateValue");function tt(e){return typeof e=="string"&&e!==""?e:Oe(e)&&e.start!==""?e.start:null}a(tt,"dateValueStart");var Xt="\u2014";function du(e){return String(e)}a(du,"formatText");function pu(e){return e?"Yes":"No"}a(pu,"formatCheckbox");function mu(e,t){if(typeof e!="number")return String(e);if(t.renderAs==="rating")return `${e}/${t.max??5}`;let n=t.decimals;return t.unit==="integer"?e.toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:0}):t.unit==="percentage"?(e/100).toLocaleString(void 0,{style:"percent",minimumFractionDigits:n,maximumFractionDigits:n}):e.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})}a(mu,"formatNumber");function fu(e,t){if(typeof e!="object"||e===null)return String(e);let n=e;return "value"in n&&"code"in n?`${n.value.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})} ${n.code}`:String(e)}a(fu,"formatCurrency");function Hn(e){if(Oe(e)){let t=Hn(e.start);return e.end?`${t} \u2192 ${Hn(e.end)}`:t}if(e instanceof Date)return e.toISOString().split("T")[0];if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString().split("T")[0]}return String(e)}a(Hn,"formatDate");function bu(e){if(typeof e!="object"||e===null)return String(e);let t=e;return "phoneNumber"in t?t.phoneNumber?t.countryCode?c(t):t.phoneNumber:"":String(e)}a(bu,"formatPhone");function gu(e,t="full"){if(typeof e!="object"||e===null)return "";let n=e,r=[];switch(t){case "country":n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "state":n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "city":n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "coordinates":n.latitude!==void 0&&n.longitude!==void 0&&r.push(`${n.latitude}, ${n.longitude}`);break;case "address":n.address&&r.push(n.address),n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;default:n.address&&r.push(n.address),n.address2&&r.push(n.address2),n.city&&r.push(n.city),n.state&&r.push(n.state),n.postalCode&&r.push(n.postalCode),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break}return r.join(", ")}a(gu,"formatLocationValue");function yu(e,t){return typeof e!="object"||e===null?String(e):gu(e,t.granularity??"full")||Xt}a(yu,"formatLocation");function hu(e,t){return typeof e!="string"?String(e):t.options?.find(r=>r.value===e)?.label??String(e)}a(hu,"formatSelect");function Au(e,t){return Array.isArray(e)?t.options?e.map(r=>t.options.find(o=>o.value===r)?.label).filter(Boolean).join(", "):e.join(", "):String(e)}a(Au,"formatMultiselect");function Zo(e,t){if(a$1(e))return Xt;switch(t.type){case "text":return du(e);case "checkbox":return pu(e);case "number":return mu(e,t);case "currency":return fu(e);case "date":return Hn(e);case "phone":return bu(e);case "location":return yu(e,t);case "select":case "status":return hu(e,t);case "multiselect":return Au(e,t);case "user":case "relation":return Array.isArray(e)?e.join(", "):String(e);default:return Array.isArray(e)?e.join(", "):String(e)}}a(Zo,"formatAttributeValue");var Tu=["UPPER","LOWER","capitalize","trim"],wu=["prefix","suffix","wrap","default"],en=[...Tu,...wu],nt=z.string().min(1,"labelExpression cannot be empty").refine(e=>tn(e),{message:"labelExpression must contain at least one {{ attribute }} interpolation"}).refine(e=>!/\{\{\s*\}\}/.test(e),{message:"labelExpression contains empty {{ }} interpolation"}).refine(e=>{let t=/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g,n;for(;(n=t.exec(e))!==null;){let r=n[1];if(!en.includes(r))return false}return true},{message:`Invalid pipe name. Valid pipes: ${en.join(", ")}`});function Su(e){let t=nt.safeParse(e);return t.success?{success:true,attributes:wt(e)}:{success:false,error:t.error.issues[0]?.message??"Invalid labelExpression"}}a(Su,"validateLabelExpression");function Iu(e,t){let{name:n,args:r}=Cu(t);switch(n){case "UPPER":return e.toUpperCase();case "LOWER":return e.toLowerCase();case "capitalize":return e.replace(/(^|\s)\S/g,o=>o.toUpperCase());case "trim":return e.trim();case "prefix":return e?`${r[0]??""}${e}`:"";case "suffix":return e?`${e}${r[0]??""}`:"";case "wrap":return e?`${r[0]??""}${e}${r[1]??""}`:"";case "default":return e||r[0]||"";default:return e}}a(Iu,"applyPipe");function Xo(e,t){let n=e;for(let r of t)n=Iu(n,r);return n}a(Xo,"applyPipes");function Ru(e,t){return t.split(".").reduce((n,r)=>{if(!(n==null||typeof n!="object"))return n[r]},e)}a(Ru,"getValue");var ea="(Untitled)";function Cu(e){let t=e.match(/^(\w+)(?::(.*))?$/);if(!t)return {name:e,args:[]};let n=t[1],r=t[2];if(!r)return {name:n,args:[]};let o=[],a=/["']([^"']*?)["']/g,s;for(;(s=a.exec(r))!==null;)o.push(s[1]);return {name:n,args:o}}a(Cu,"parsePipeExpression");function*ta(e){let t=0;for(;t<e.length;){let n=e.indexOf("{{",t);if(n<0)return;let r=e.indexOf("}",n+2);if(r<0)return;if(e[r+1]!=="}"){t=r+1;continue}t=r+2;let o=e.slice(n+2,r);o.length>0&&(yield {start:n,end:t,expr:o});}}a(ta,"templateBlocks");function vu(e,t){let n=e.split("||").map(u=>u.trim()),o=n[n.length-1].split("|").map(u=>u.trim());n[n.length-1]=o[0];let a=o.slice(1).filter(Boolean),s=n.filter(Boolean),c="";for(let u of s){let l=na(Ru(t,u));if(l!==""){c=l;break}}return Xo(c,a)}a(vu,"resolveLabelBlock");function Jn(e,t,n=ea){let r=[],o=0;for(let s of ta(e))r.push(e.slice(o,s.start),vu(s.expr,t)),o=s.end;return r.push(e.slice(o)),r.join("").trim()||n}a(Jn,"renderLabelExpression");function na(e){if(e==null||typeof e=="function")return "";if(typeof e!="object")return String(e);if(Array.isArray(e))return e.map(na).filter(Boolean).join(",");let t=e.toString;return typeof t=="function"&&t!==Object.prototype.toString?String(e):""}a(na,"toText");function tn(e){let t=0;for(;t<e.length;){let n=e.indexOf("{{",t);if(n<0)return false;let r=e.indexOf("}}",n+2);if(r<0)return false;if(e.slice(n+2,r).trim().length>0)return true;t=r+2;}return false}a(tn,"isLabelExpression");function wt(e){let t=[];for(let n of ta(e)){let r=n.expr.trim();if(!r)continue;let o=r.split("||").map(s=>s.trim()),a=o[o.length-1];o[o.length-1]=a.split("|")[0].trim();for(let s of o){if(!s)continue;let c=s.split(".")[0];c&&!t.includes(c)&&t.push(c);}}return t}a(wt,"extractAttributeNames");var Eu=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function ra(e){let t=e.trim().match(Eu);return t?t[1]:null}a(ra,"getSingleAttributeFromExpression");function Nu(e,t){let n=ra(e);if(n===null)return null;let r=t.find(o=>o.name===n);return !r||r.type!=="text"||j$1(r).authoring.readOnly?null:r}a(Nu,"getEditableLabelAttribute");var Du=/\{\{\s*props\./;function Ou(e,t,n){if(!Du.test(e))return e;let r={},o=new Map(n?.map(s=>[s.name,s]));if(t)for(let[s,c]of Object.entries(t)){if(c==null)continue;let u=o.get(s);if(u){let l=Zo(c,u);r[s]=l===Xt?"":l;}else r[s]=c;}return Jn(e,{props:r},"").replace(/\(\s*\)/g,"").replace(/\[\s*\]/g,"").replace(/\s*[-—|:]\s*$/g,"").replace(/\s{2,}/g," ").trim()}a(Ou,"applyRelationProps");function ku(e){if(e?.type==="relation")return e.properties?.definitions}a(ku,"relationPropertyDefs");function ju(e){if(e?.type==="relation"||e?.type==="document")return e.properties?.definitions}a(ju,"qualifiedPropertyDefs");function ia(e){if(a$1(e))return [];if(typeof e=="string")return [{id:e}];if(Array.isArray(e))return e.flatMap(t=>ia(t));if(typeof e=="object"&&"id"in e){let t=e;if(typeof t.id=="string")return [{id:t.id,props:t.props}]}return []}a(ia,"extractValueRefs");function _u(e){let t=[e.firstName,e.lastName].map(n=>n?.trim()).filter(Boolean).join(" ");return t!==""?t:e.email?.split("@")[0]??""}a(_u,"getUserDisplayName");var Pu=/\p{L}|\p{N}/u;function Mu(e,t){let n=e?.trim()??"";if(n==="")return t;let r=n.split(/\s+/),a=(r.length===1?n.split("@")[0].split(/[._-]/):r).map(s=>{let c=s.match(Pu)?.[0];return c===void 0?"":[...c.toUpperCase()][0]??""}).filter(Boolean).slice(0,2).join("");return a===""?t:a}a(Mu,"deriveInitials");var oa="__creatorRootActorId";function Fu(e){let t=e.metadata?.[oa];return typeof t=="string"&&t.length>0?t:e.createdBy}a(Fu,"getRecordCreatorPrincipalId");function rt(e,t){return e?.includes("*")===true||e?.includes(t)===true}a(rt,"includesAction");function Vu(e){return {canRead:rt(e,"read"),canCreate:rt(e,"create"),canUpdate:rt(e,"update"),canDelete:rt(e,"delete"),canManage:rt(e,"manage")}}a(Vu,"buildPermissionFlags");var HA=new Set(["id","name","label","type","required","system","unique","order"]);var te={PEOPLE:"people",WORKSPACE:"workspace",ARCHITECT:"architect",FEATURE_FLAGS:"feature-flags",FILES:"files",VIEWS:"views",FORMS:"forms",DOCUMENTS:"documents",AUDIT:"audit",API_KEYS:"api-keys",CONNECTORS:"connectors",ENV_VARS:"env-vars",SESSION:"session"},QA=[te.PEOPLE,te.WORKSPACE,te.ARCHITECT,te.FEATURE_FLAGS,te.FILES,te.VIEWS,te.FORMS,te.DOCUMENTS,te.AUDIT,te.API_KEYS,te.CONNECTORS,te.ENV_VARS,te.SESSION],ZA={people:"People",workspace:"Workspace",architect:"Architect","feature-flags":"Feature flags",files:"Files",views:"Views",forms:"Forms",documents:"Documents",audit:"Audit","api-keys":"API keys",connectors:"Connected accounts","env-vars":"Environment variables",session:"Agent sessions"},Bu={OWNER:"owner",MEMBER:"member",AGENT_DEFAULT:"agent_default",REFLEX_DEFAULT:"reflex_default"},XA={owner:"Owner",member:"Member",agent_default:"Agent Default",reflex_default:"Reflex Default"},ex={owner:"Full access to all platform features and data",member:"Can view, create, edit and delete business data",agent_default:"Default role for AI agents \u2014 CRUD on records plus documents and files",reflex_default:"Default role for reflexes \u2014 no data access; each reflex is granted exactly what its rehearsal showed it uses"},Qn=["read","create","update","delete","manage"],Lu=["read","create","update","delete"],aa=["read","create","update","delete"],tx={owner:{system:[{target:"*",actions:Qn}],object:[{target:"*",actions:Qn}]},member:{system:[{target:"people",actions:["read"]},{target:"workspace",actions:["read"]},{target:"connectors",actions:Lu},{target:"files",actions:aa},{target:"documents",actions:aa}],object:[{target:"*",actions:Qn}]},agent_default:{system:[{target:"documents",actions:["read","create","update"]},{target:"files",actions:["read","create","update"]},{target:"env-vars",actions:["read"]},{target:"session",actions:["observe"]}],object:[{target:"*",actions:["read","create","update","delete"]}]},reflex_default:{system:[],object:[]}};function nx(e){return Object.values(Bu).includes(e)}a(nx,"isDefaultRole");var sa={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2},timeoutMs:3e5},Xn=class Xn{constructor(t){if(!t.name||t.name.trim().length===0)throw new h$1("Agent name is required",[]);this.bp={name:t.name,system:true,visibility:"workspace",triggers:[]};}description(t){return this.bp.description=t,this}label(t){return this.bp.label=t,this}icon(t){return this.bp.icon=t,this}systemPrompt(t){return this.bp.systemPrompt=t,this}model(t,n,r){return this.bp.model={provider:t,model:n,...r},this}tools(t){return this.bp.tools=[...t],this}schedule(t){return this.bp.schedule={...t,enabled:t.enabled??true},this}config(t){let n=this.bp.config??sa,r=t.inference===void 0?n.inference:{...n.inference,...t.inference};return this.bp.config={...n,...t,...r===void 0?{}:{inference:r}},this}delegation(t){return Object.assign(this.bp,t),this}mcpServers(t){return this.bp.mcpServers=Array.isArray(t)?[...t]:t,this}approval(t){return this.bp.approval={...Bo,...this.bp.approval,...t},this}visibility(t){return this.bp.visibility=t,this}requiresPermission(t,n){return this.bp.requiredPermission={resource:t,action:n},this}trigger(t,n,r){return this.bp.triggers.push({name:t,eventType:n,...r,enabled:r?.enabled??true}),this}runtime(){return this.bp.system=false,this}build(){if(!this.bp.systemPrompt)throw new h$1(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new h$1(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility==="private")throw new h$1(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return l(this.bp.triggers,t=>t.name,t=>new h$1(`Agent "${this.bp.name}": duplicate trigger name "${t}"`,[])),{...this.bp,visibility:this.bp.visibility??"workspace",config:this.bp.config??sa,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};a(Xn,"AgentBuilder");var Zn=Xn;function cx(e){return new Zn(e)}a(cx,"agent");var $u="@stndrds/schema";function nn(e){return {version:1,vendor:$u,validate:a(t=>{let n=e.safeParse(t);return n.success?{value:n.data}:{issues:n.error.issues.map(r=>({message:r.message,path:r.path}))}},"validate")}}a(nn,"createStandardSchemaProps");function dx(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"].version===1}a(dx,"isStandardSchema");var yr=class yr{get"~standard"(){let t=c$1(this.build());return nn(t)}constructor(t,n$1,r){n(n$1),o(r),this.attr={name:n$1,label:r,type:t,required:false,system:true};}setRequired(t){this.attr.required=t;}asRequiredState(){return this}asPhantomState(){return this}runtime(){return this.attr.system=false,this}hidden(){return this.attr.hidden=true,this}placeholder(t){return this.attr.placeholder=t,this}description(t){return this.attr.description=t,this}icon(t){return p(t,`attribute "${this.attr.name}"`),this.attr.icon=t,this}order(t){return this.attr.order=t,this}defaultValue(t){return ("defaultValue"in this.attr||!["formula","rollup"].includes(this.attr.type))&&(this.attr.defaultValue=t),this}metadata(t){return this.attr.metadata=t,this}build(){return this.attr}};a(yr,"BaseAttributeBuilder");var L=yr,hr=class hr extends L{constructor(t,n){super("text",t,n);}minLength(t){return this.attr.minLength=t,this}maxLength(t){return this.attr.maxLength=t,this}pattern(t){return this.attr.pattern=t,this.attr.format=void 0,this}multiline(t=true){return this.attr.multiline=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}email(){return this.attr.format="email",this.attr.pattern=void 0,this}url(){return this.attr.format="url",this.attr.pattern=void 0,this}slug(){return this.attr.format="slug",this.attr.pattern=void 0,this}};a(hr,"TextAttributeBuilder");var er=hr;function S(e){return new er(e.name,e.label)}a(S,"text");var Ar=class Ar extends L{constructor(t,n){super("richtext",t,n);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Ar,"RichtextAttributeBuilder");var tr=Ar;function ke(e){return new tr(e.name,e.label)}a(ke,"richtext");var xr=class xr extends L{constructor(t,n){super("number",t,n);}min(t){return this.attr.min=t,this}max(t){return this.attr.max=t,this}integer(){return this.attr.unit="integer",this.attr.decimals=0,this}decimal(t=2){return this.attr.unit="decimal",this.attr.decimals=t,this}percentage(){return this.attr.unit="percentage",this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(xr,"NumberAttributeBuilder");var nr=xr;function on(e){return new nr(e.name,e.label)}a(on,"number");var Tr=class Tr extends L{constructor(t,n){super("checkbox",t,n);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Tr,"CheckboxAttributeBuilder");var rr=Tr;function ca(e){return new rr(e.name,e.label)}a(ca,"checkbox");var wr=class wr extends L{constructor(t,n){super("date",t,n);}format(t){return this.attr.dateFormat=t,this}minDate(t){return this.attr.minDate=t,this}maxDate(t){return this.attr.maxDate=t,this}endDate(){return this.attr.endDate=true,this.asPhantomState()}includeTime(){return this.attr.includeTime=true,this}timeFormat(t){return this.attr.timeFormat=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(wr,"DateAttributeBuilder");var ir=wr;function se(e){return new ir(e.name,e.label)}a(se,"date");var Sr=class Sr extends L{constructor(t,n){super("phone",t,n);}defaultCountry(t){return this.attr.defaultCountryCode=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Sr,"PhoneAttributeBuilder");var or=Sr;function xx(e){return new or(e.name,e.label)}a(xx,"phone");var Ir=class Ir extends L{constructor(t,n){super("currency",t,n);}defaultCurrency(t){return this.attr.defaultCurrency=t,this}allowedCurrencies(t){return this.attr.allowedCurrencies=t,this}allowNegative(t=true){return this.attr.allowNegative=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Ir,"CurrencyAttributeBuilder");var ar=Ir;function Tx(e){return new ar(e.name,e.label)}a(Tx,"currency");var Rr=class Rr extends L{constructor(t,n){super("status",t,n);}options(t){let n=t;return q$1(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return q$1(this.attr.name??"unknown",n),this.attr.options.push(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Rr,"StatusAttributeBuilder");var sr=Rr;function wx(e){return new sr(e.name,e.label)}a(wx,"status");var Cr=class Cr extends L{constructor(t,n){super("select",t,n);}options(t){let n=t;return q$1(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return q$1(this.attr.name??"unknown",n),this.attr.options.push(t),this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Cr,"SelectAttributeBuilder");var cr=Cr;function fe(e){return new cr(e.name,e.label)}a(fe,"select");var vr=class vr extends L{constructor(t,n){super("multiselect",t,n);}options(t){let n=t;return q$1(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return q$1(this.attr.name??"unknown",n),this.attr.options.push(t),this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(vr,"MultiselectAttributeBuilder");var ur=vr;function Sx(e){return new ur(e.name,e.label)}a(Sx,"multiselect");var Er=class Er extends L{constructor(t,n){super("location",t,n);}granularity(t){return this.attr.granularity=t,this}defaultCountry(t){return this.attr.defaultCountry=t,this}allowedCountries(t){return this.attr.allowedCountries=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Er,"LocationAttributeBuilder");var lr=Er;function Ix(e){return new lr(e.name,e.label)}a(Ix,"location");var Nr=class Nr extends L{constructor(t,n){super("user",t,n),this.attr.types=["user","agent"];}types(t){let n=[...new Set(t)];if(n.length===0)throw new Error("[AttributeBuilder] user.types must contain at least one type.");return this.attr.types=n,this}multiple(){return this.attr.multiple=true,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Nr,"UserAttributeBuilder");var dr=Nr;function Rx(e){return new dr(e.name,e.label)}a(Rx,"user");var Dr=class Dr extends L{to(t,n){let r={object:t,...n};return this.attr.targets?.push(r),this}toAny(){return this.attr.targets=[{object:ae}],this}qualifyWith(...t){let n=this.attr.targets;if(!n||n.length===0)throw new Error('.qualifyWith() must be called AFTER .to(). Example: relation({ name: "companies" }).to("companies").qualifyWith(...)');return this.attr.properties=Zt(t),this}bilateral(t){let n=this.attr.targets;if(!n||n.length===0)throw new Error('.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })');if(n.length>1)throw new Error("Bilateral relations are not supported for polymorphic relations (multiple .to() targets).");if(Fo(this.attr))throw new Error("Bilateral relations are not supported for universal relations (.toAny()).");let r=n[0]?.object;if(!r)throw new h$1("Bilateral relation requires one target object",[{path:["bilateral","object"],message:"Bilateral relation requires one target object"}]);if(t.object&&t.object!==r){let o=`Bilateral inverse object ${t.object} must match relation target ${r}`;throw new h$1(o,[{path:["bilateral","object"],message:o}])}return this.attr.bilateral={...t,object:r},this}};a(Dr,"BaseRelationAttributeBuilder");var rn=Dr,Or=class Or extends rn{constructor(t,n){super("relation",t,n),this.attr.cardinality="one",this.attr.targets=[];}many(){let t=new mr(this.attr.name,this.attr.label??"",{targets:this.attr.targets,isRequired:this.attr.required});return this.attr.system===false&&t.runtime(),this.attr.hidden&&t.hidden(),this.attr.placeholder&&t.placeholder(this.attr.placeholder),this.attr.description&&t.description(this.attr.description),this.attr.icon&&t.icon(this.attr.icon),this.attr.order!==void 0&&t.order(this.attr.order),this.attr.metadata&&t.metadata(this.attr.metadata),t}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Or,"SingleRelationAttributeBuilder");var pr=Or,kr=class kr extends rn{constructor(t,n,r){super("relation",t,n),this.attr.cardinality="many",this.attr.targets=r?.targets??[],this.attr.defaultValue=[],r?.isRequired&&this.setRequired(true);}maxItems(t){return this.attr.maxItems=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(kr,"MultiRelationAttributeBuilder");var mr=kr;function it(e){return new pr(e.name,e.label)}a(it,"relation");var jr=class jr extends L{constructor(t,n){super("formula",t,n),this.attr.required=false;}expression(t){return this.attr.expression=t,this}returns(t){return this.attr.returnType=t,this}decimals(t){return this.attr.decimals=t,this}required(){throw new Error("Formula attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.")}optional(){return this}};a(jr,"FormulaAttributeBuilder");var fr=jr;function Cx(e){return new fr(e.name,e.label)}a(Cx,"formula");var _r=class _r extends L{constructor(t,n){super("rollup",t,n),this.attr.required=false;}from(t){return this.attr.relationAttribute=t,this}aggregate(t){return this.attr.targetAttribute=t,this}using(t){return this.attr.function=t,this}decimals(t){return this.attr.decimals=t,this}path(t){return this.attr.relationPath=t,this}targetType(t){return this.attr.targetAttributeType=t,this}targetOptions(t){return this.attr.targetAttributeOptions=t,this}targetCurrency(t){return this.attr.targetCurrencyCode=t,this}build(){let t=this.attr.function,n=this.attr.targetAttributeType;if(t==="original"&&n!==void 0&&n!=="select"&&n!=="status"&&n!=="multiselect"){let r=this.attr.relationAttribute??"relation",o=this.attr.targetAttribute??"field";throw new b$1(`Rollup "${this.attr.name}": .using("original") only supports a "select", "status", or "multiselect" target, but .targetType("${n}") was given. To surface a plain ${n} value from a related record, use a formula instead \u2014 e.g. formula({ name: "${this.attr.name}", label: "\u2026" }).expression("${r}.${o}").`,a$2.VALIDATION_FAILED)}return super.build()}required(){throw new Error("Rollup attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.")}optional(){return this}};a(_r,"RollupAttributeBuilder");var br=_r;function vx(e){return new br(e.name,e.label)}a(vx,"rollup");var Pr=class Pr extends L{constructor(t,n){super("document",t,n);}accepts(t){return this.attr.accepts=t,this}maxFileSize(t){return this.attr.maxFileSize=t,this}qualifyWith(...t){return this.attr.properties=Zt(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Pr,"DocumentAttributeBuilder");var gr=Pr;function ua(e){return new gr(e.name,e.label)}a(ua,"document");function da(e,t,n){let r=Array.isArray(e)?e:[e],[o,...a]=r;return {type:"slot",slotId:o,additionalSlotIds:a.length>0?a:void 0,attribute:t,label:n?.label,required:n?.required,tooltip:n?.tooltip}}a(da,"buildSlotFieldRef");var Br=class Br{constructor(t,n,r){this._finalized=false;this.stepBuilder=t,this.rowData={id:n,order:r,type:"fields",fields:[]};}field(t,n,r){return this.rowData.fields.push(da(t,n,r)),this}freeField(t,n){let o={type:"free",attribute:t.build(),label:n?.label,required:n?.required,prefillExpression:n?.prefillExpression};return this.rowData.fields.push(o),this}row(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).row(t)}heading(t,n){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).heading(t,n)}separator(){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).separator()}text(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).text(t)}endRow(){return this._finalized?this.stepBuilder:(this._finalized=true,this.stepBuilder._finalizeRow(this.rowData))}};a(Br,"FormRowBuilder");var Mr=Br,Lr=class Lr{constructor(t,n,r){this.rowOrder=0;this.formBuilder=t,this.stepData={id:n,label:r,rows:[]};}description(t){return this.stepData.description=t,this}field(t,n,r){this.rowOrder++;let o=`row-${this.stepData.id}-${this.rowOrder}`,a=da(t,n,r),s={id:o,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}freeField(t,n){this.rowOrder++;let r=`row-${this.stepData.id}-${this.rowOrder}`,a={type:"free",attribute:t.build(),label:n?.label,required:n?.required,prefillExpression:n?.prefillExpression},s={id:r,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}row(t){return this.rowOrder++,new Mr(this,t,this.rowOrder)}heading(t,n){this.rowOrder++;let r={id:`heading-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"heading",content:t,level:n};return this.stepData.rows.push(r),this}separator(){this.rowOrder++;let t={id:`sep-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"separator"};return this.stepData.rows.push(t),this}text(t){this.rowOrder++;let n={id:`text-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"text",content:t};return this.stepData.rows.push(n),this}step(t,n){return this.formBuilder._finalizeStep(this.stepData).step(t,n)}build(){return this.formBuilder._finalizeStep(this.stepData).build()}_finalizeRow(t){return t.fields.length>0&&this.stepData.rows.push(t),this}_getData(){return this.stepData}};a(Lr,"FormStepBuilder");var Fr=Lr,$r=class $r{constructor(t,n){this.data={slots:[],steps:[],status:"draft",version:1};this.validateName(t),this.data.name=t,this.data.label=n;}description(t){return this.data.description=t,this}icon(t){return this.data.icon=t,this}status(t){return this.data.status=t,this}metadata(t){return this.data.metadata=t,this}slot(t,n,r){if(this.data.slots.some(a=>a.id===t))throw new Error(`[FormBuilder] Duplicate slot id: "${t}"`);let o={id:t,objectName:n,label:r.label,mode:r.mode??"create",color:r.color,icon:r.icon};return this.data.slots.push(o),this}step(t,n){if(this.data.steps.some(r=>r.id===t))throw new Error(`[FormBuilder] Duplicate step id: "${t}"`);return new Fr(this,t,n)}build(){return this.validateRequiredData(),this.validateSlotReferences(),this.validateFreeFields(),this.validatePrefillExpressions(),this.data}_finalizeStep(t){return this.data.steps.push(t),this}validateName(t){let n=z.string().min(1,"Form name cannot be empty").max(63,"Form name is too long (max 63 characters)").regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,{message:"Invalid form name format. Name must be in kebab-case: 'client-onboarding', 'contact-creation'"});try{n.parse(t);}catch(r){throw r instanceof z.ZodError?new Error(`[FormBuilder] ${r.issues[0].message}`):r}}validateRequiredData(){if(this.data.slots.length===0)throw new Error("[FormBuilder] At least one slot is required. Use .slot() to add slots.");if(this.data.steps.length===0)throw new Error("[FormBuilder] At least one step is required. Use .step() to add steps.")}validateSlotReferences(){let t=new Map(this.data.slots.map(n=>[n.id,n.objectName]));for(let n of this.data.steps)for(let r of n.rows)if(Jt(r))for(let o of r.fields){if(o.type!=="slot")continue;let a=Ko(o);for(let c of a)if(!t.has(c))throw new Error(`[FormBuilder] Step "${n.id}" references unknown slot "${c}". Declare it with .slot("${c}", ...) first.`);let s=new Set(a.map(c=>t.get(c)));if(s.size>1)throw new Error(`[FormBuilder] Step "${n.id}" field on attribute "${o.attribute}" targets slots of different objects (${[...s].join(", ")}). A multi-slot field must target slots of the same object.`)}}validatePrefillExpressions(){let t=[...en,"join"];for(let n of this.data.steps)for(let r of n.rows)if(Jt(r))for(let o of r.fields){if(!Gn(o)||!o.prefillExpression)continue;let a=o.prefillExpression,s=`prefillExpression on free field "${o.attribute.name}" in step "${n.id}"`;if(!tn(a))throw new Error(`[FormBuilder] ${s} must contain at least one {{ attribute }} interpolation.`);if(/\{\{\s*\}\}/.test(a))throw new Error(`[FormBuilder] ${s} contains empty {{ }} interpolation.`);for(let c of a.matchAll(/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g)){let u=c[1];if(!t.includes(u))throw new Error(`[FormBuilder] ${s} uses invalid pipe "${u}". Valid pipes: ${t.join(", ")}`)}}}validateFreeFields(){let t=new Set(Wn);for(let n of this.data.steps)for(let r of n.rows)if(Jt(r)){for(let o of r.fields)if(Gn(o)){let a=o.attribute.type;if(t.has(a))throw new Error(`[FormBuilder] Free field in step "${n.id}" uses forbidden attribute type "${a}". Forbidden types: ${Wn.join(", ")}`)}}}};a($r,"FormBuilder");var Vr=$r;function _x(e,t){return new Vr(e,t)}a(_x,"form");function Uu(e){return {text:"toString",richtext:"toString",number:"toNumber",currency:"toNumber",date:"toDate",checkbox:"toBoolean"}[e]}a(Uu,"resolveBuiltInTransform");var Ur=class Ur{constructor(t){this.operations=[];this.touchedAttributes=new Set;this.version=t;}assertNotTouched(t,n){if(this.touchedAttributes.has(t))throw new h$1(`[MigrationBuilder] Conflicting operations on attribute "${t}": it was already modified earlier in this migration (attempted: ${n}).`,[])}renameAttribute(t,n){return this.assertNotTouched(t,"rename_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"rename_attribute",from:t,to:n}),this}changeType(t,n,r,o){this.assertNotTouched(t,"change_type"),this.touchedAttributes.add(t);let a=o?.transform?Uu(r):void 0;return this.operations.push({type:"change_type",name:t,from:n,to:r,transform:a}),this}removeAttribute(t){return this.assertNotTouched(t,"remove_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"remove_attribute",name:t}),this}addAttribute(t){return this.assertNotTouched(t.name,"add_attribute"),this.touchedAttributes.add(t.name),this.operations.push({type:"add_attribute",attribute:t}),this}updateConfig(t,n){return this.assertNotTouched(t,"update_config"),this.touchedAttributes.add(t),this.operations.push({type:"update_config",name:t,from:{},to:n}),this}build(){return {version:this.version,operations:[...this.operations]}}};a(Ur,"MigrationBuilder");var an=Ur;function qu(e){let{name:t,labelExpression:n,embeddingExpression:r}=e;if(!n)throw new b$1(`Object "${t}" must have a labelExpression. The labelExpression defines how records are displayed in lists and relations (e.g. "{{ name }}").`,a$2.VALIDATION_FAILED);let o=nt.safeParse(n);if(!o.success){let a=o.error.issues[0]?.message??"Invalid labelExpression";throw new b$1(`Invalid labelExpression for "${t}": ${a}`,a$2.VALIDATION_FAILED)}if(r!==void 0){let a=nt.safeParse(r);if(!a.success){let s=a.error.issues[0]?.message??"Invalid embeddingExpression";throw new b$1(`Invalid embeddingExpression for "${t}": ${s}`,a$2.VALIDATION_FAILED)}}}a(qu,"validateObjectExpressions");var qr=class qr{constructor(t){this._migrations=[];this._sealed=false;this._toleratedAttributes=[];this.validateName(t.name),this.obj={name:t.name,label:t.label,attributes:[],system:true},t.id&&(this.obj.id=t.id);}get"~standard"(){let t=e(this.build());return nn(t)}description(t){return this.obj.description=t,this}pluralLabel(t){return this._pluralLabel=t,this}icon(t){return this.obj.icon=t,this}runtime(){return this.obj.system=false,this}sealed(){return this._sealed=true,this}tolerate(t){return this._toleratedAttributes=[...this._toleratedAttributes,...t],this}attribute(t){return this.pushAttributes([t]),this}attributes(t){return this.pushAttributes(t),this}pushAttributes(t){let n=t.map(r=>"build"in r&&typeof r.build=="function"?r.build():r);l([...this.obj.attributes,...n],r=>r.name,r$1=>new r("attribute",r$1,`Object "${this.obj.name}": duplicate attribute name "${r$1}"`)),this.obj.attributes.push(...n);}metadata(t){return this.obj.metadata={...this.obj.metadata,...t},this}order(t){return this.obj.metadata={...this.obj.metadata,order:t},this}hidden(){return this.obj.metadata={...this.obj.metadata,hidden:true},this}labelExpression(t){return this._labelExpression=t,this}embeddingExpression(t){return this._embeddingExpression=t,this}documentLayout(t){if(t.presets)for(let n of t.presets)pa(n.id,n.structure,1);return this.obj.documentLayout=t,this}migration(t,n){if(t<2)throw new Error(`[ObjectBuilder] Migration version must be >= 2 (version 1 is implicit). Got: ${t}`);if(this._migrations.some(a=>a.version===t))throw new Error(`[ObjectBuilder] Duplicate migration version: ${t}`);let o=new an(t);return n(o),this._migrations.push(o.build()),this}build(){if(!this.obj.name)throw new h$1("[ObjectBuilder] Missing required field: name",[{path:["name"],message:"name is required"}]);if(!this.obj.label)throw new h$1("[ObjectBuilder] Missing required field: label",[{path:["label"],message:"label is required"}]);qu({name:this.obj.name,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression});let t=[...this._migrations].sort((r,o)=>r.version-o.version);for(let r=0;r<t.length;r++){let o=r+2;if(t[r].version!==o)throw new Error(`[ObjectBuilder] Migration versions must be sequential starting at 2. Expected version ${o}, got ${t[r].version}.`)}let n=t.length>0?t[t.length-1].version:1;return {...this.obj,pluralLabel:this._pluralLabel,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression,schema_version:n,migrations:t,sealed:this._sealed,toleratedAttributes:this._toleratedAttributes}}validateName(t){t!==void 0&&j(t);}};a(qr,"ObjectBuilder");var St=qr;function Kx(e){if(b(e.name))throw new s(e.name,"builder");return new St(e)}a(Kx,"object");function pa(e,t,n){let r=a((a,s)=>{throw new h$1(a,[{path:["documentLayout","presets",e],message:s}])},"fail");n>5&&r(`Preset structure exceeds max depth of ${5}`,"Preset structure too deep");let o=new Set;for(let a of t){let s=a.title.trim();s.length===0&&r("Folder preset node title is required","Empty folder title"),s.includes("/")&&r("Folder preset node title cannot contain /",`Folder title contains /: "${s}"`),o.has(s)&&r("Folder preset sibling titles must be unique",`Duplicate folder title: "${s}"`),o.add(s),a.children&&a.children.length>0&&pa(e,a.children,n+1);}}a(pa,"validatePresetStructure");function be(e,t){try{return structuredClone(e)}catch{let n="Builder configuration must contain cloneable data";throw new h$1(n,[{path:t,message:n}])}}a(be,"cloneBuilderValue");function Ce(e,t){if(typeof e!="string"||e.trim().length===0)throw new h$1("Name must not be blank",[{path:t,message:"Name must not be blank"}])}a(Ce,"requireBuilderName");function ot(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new h$1("Invalid content configuration",[{path:t,message:"Expected content configuration"}]);for(let c of ["name","label","placement"])if(Object.hasOwn(e,c)){let u=`Independent content configuration cannot define ${c}`;throw new h$1(u,[{path:[...t,c],message:u}])}let n=W$1.safeParse({...e,name:"content",placement:"main"});if(!n.success)throw h$1.fromZodErrors(n.error.issues.map(c=>({path:[...t,...c.path.map(String)],message:c.message})));n.data.type==="form"&&n.data.groups.forEach((c,u)=>Ce(c.name,[...t,"groups",String(u),"name"]));let{name:r,label:o,placement:a,...s}=n.data;return be(s,t)}a(ot,"validateContentConfiguration");function zr(e,t){return ot(e,t),be(e,t)}a(zr,"validateLiteralContent");function qe(e){return e.relation===void 0?{kind:"object",object:e.object}:e.object===void 0?{kind:"related",relation:e.relation}:{kind:"relatedFrom",object:e.object,relation:e.relation}}a(qe,"collectionSourceAddress");function Wr(e){if(!e||typeof e!="object")return;let t="object"in e?e.object:void 0,n="relation"in e?e.relation:void 0;if(typeof t=="string"&&typeof n=="string")return {kind:"relatedFrom",object:t,relation:n};if(typeof t=="string"&&n===void 0)return {kind:"object",object:t};if(typeof n=="string"&&t===void 0)return {kind:"related",relation:n}}a(Wr,"collectionSourceAddressOf");function It(e,t,n){if(t!=="record"){let r=`Content "${e}" requires record context. In a collection view only a collection that lists a whole object, or a custom content that does not require a record, is allowed.`;throw new h$1(r,[{path:n,message:r}])}}a(It,"requireRecordContentContext");function zu(e){let t=e.openMode??"page";return {openMode:t,createMode:e.createMode??t}}a(zu,"resolveContentNavigation");function Wu(e,t){return [...new Set(t)].filter(n=>e.actions===void 0||e.actions.includes(n))}a(Wu,"resolveCollectionActions");var je=class je{constructor(t,n=[]){this.kind="view";this.data=be(t,["views","0"]),this.extensions=n.map(r=>r&&{...r});}for(t){return new je({...this.data,object:t},this.extensions)}default(){return new je({...this.data,default:true},this.extensions)}description(t){return new je({...this.data,description:t},this.extensions)}icon(t){return new je({...this.data,icon:t},this.extensions)}place(t,n,r,o){let a=["views","0","contents",String(this.data.contents.length)],s,c;try{r!==null&&typeof r=="object"&&"build"in r&&typeof r.build=="function"?(s=ot(r.build(),a),c=r.extension):s=ot(r,a);}catch(m){throw m instanceof h$1?new h$1(m.message,m.errors.map(d=>({...d,path:d.path[0]==="content"?[...a,...d.path.slice(1)]:d.path}))):m}let u={...s,name:t,label:n,placement:o},l=[...this.data.contents,u];return new je({...this.data,contents:l},[...this.extensions,c])}tab(t,n,r){return this.place(t,n,r,"main")}aside(t,n,r){return this.place(t,n,r,"aside")}build(){let t=["views","0"];Ce(this.data.name,[...t,"name"]),Ce(this.data.object,[...t,"object"]);let n=_.safeParse(this.data);if(!n.success)throw h$1.fromZodErrors(n.error.issues.map(r=>({path:[...t,...r.path.map(String)],message:r.message})));return this.data.contents.forEach((r,o)=>{let a=[...t,"contents",String(o)];Ce(r.name,[...a,"name"]),r.type==="form"&&r.groups.forEach((c,u)=>Ce(c.name,[...a,"groups",String(u),"name"])),(r.type==="custom"?this.extensions[o]?.requiresRecord:r.type==="collection"?qe(r.source).kind!=="object":true)&&It(r.name,this.data.context,a);}),{kind:"view",definition:be(this.data,t)}}};a(je,"ViewBuilder");var sn=je;function ge(e,t){return new sn({name:e,label:t,object:void 0,context:"record",contents:[]})}a(ge,"detailView");function ye(e,t){return new sn({name:e,label:t,object:void 0,context:"collection",contents:[]})}a(ye,"listView");function fT(e){return Ce(e,["relationProperty"]),{relationProperty:e}}a(fT,"relationProperty");var Rt=class Rt{constructor(t,n){this.data=be(t,["content"]),this.extension=n===void 0?void 0:Object.freeze({name:n.name,requiresRecord:n.requiresRecord,parameters:n.parameters});}set(t){return new Rt({...this.data,...t},this.extension)}icon(t){return this.set({icon:t})}object(t){return this.data.type==="forms"?this.set({objectName:t}):this.set({source:{object:t}})}related(t){return this.set({source:{relation:t}})}relatedFrom(t,n){return this.set({source:{object:t,relation:n}})}layout(t){let{layout:n,groupByAttribute:r,columnSizing:o,kanbanColumnOrder:a,kanbanColumnVisibility:s,kanbanPinnedColumns:c,...u}={...this.data,layout:void 0,groupByAttribute:void 0,columnSizing:void 0,kanbanColumnOrder:void 0,kanbanColumnVisibility:void 0,kanbanPinnedColumns:void 0};return new Rt({...u,...t},this.extension)}table(){return this.layout({layout:"table"})}list(){return this.layout({layout:"list"})}kanban(t){return this.layout({layout:"kanban",groupByAttribute:t})}columns(...t){return this.set({columns:t})}filter(t){return this.set({filters:t})}sort(t,n="asc"){let o=[..."sorts"in this.data&&Array.isArray(this.data.sorts)?this.data.sorts:[],{attribute:t,direction:n}];return this.set({sorts:o})}actions(...t){return this.set({actions:t})}openMode(t){return this.set({openMode:t})}createMode(t){return this.set({createMode:t})}visibility(t){return this.set({visibility:t})}descriptionAttribute(t){return this.set({descriptionAttribute:t})}displayAttributes(...t){return this.set({displayAttributes:t})}columnSizing(t){return this.set({columnSizing:t})}kanbanColumnOrder(...t){return this.set({kanbanColumnOrder:t})}kanbanColumnVisibility(t){return this.set({kanbanColumnVisibility:t})}kanbanPinnedColumns(...t){return this.set({kanbanPinnedColumns:t})}formColumns(t){return this.set({formColumns:t})}density(t){return this.set({density:t})}titleAttribute(t){return this.set({titleAttribute:t})}allowUpload(t){return this.set({allowUpload:t})}allowRemove(t){return this.set({allowRemove:t})}hideAttachments(t){return this.set({hideAttachments:t})}relations(...t){return this.set({relations:t})}build(){let t=zr(this.data,["content"]);if(this.extension&&t.type==="custom"){let n=this.extension.parameters.safeParse(be(t.parameters??{},["content","parameters"]));if(!n.success)throw h$1.fromZodErrors(n.error.issues.map(r=>({path:["content","parameters",...r.path.map(String)],message:r.message})))}return t}};a(Rt,"ContentBuilder");var ce=Rt,ze=class ze{constructor(t,n,r,o={}){this.data=be({name:t,label:n,fields:r,...o},["group"]);}field(t,n){let{name:r,label:o,fields:a,...s}=this.data;return new ze(r,o,[...a,{attribute:t,...n}],s)}fields(...t){let{name:n,label:r,fields:o,...a}=this.data;return new ze(n,r,[...o,...t.map(s=>({attribute:s}))],a)}description(t){return new ze(this.data.name,this.data.label,this.data.fields,{...this.presentation(),description:t})}collapsible(t=false){return new ze(this.data.name,this.data.label,this.data.fields,{...this.presentation(),collapsible:true,collapsed:t})}presentation(){let{name:t,label:n,fields:r,...o}=this.data;return o}build(){Ce(this.data.name,["group","name"]);try{zr({type:"form",groups:[this.data]},["group"]);}catch(t){throw t instanceof h$1?new h$1(t.message,t.errors.map(n=>({...n,path:n.path[1]==="groups"?["group",...n.path.slice(3)]:n.path}))):t}return be(this.data,["group"])}};a(ze,"GroupBuilder");var Gr=ze;function he(e,t){return new Gr(e,t,[])}a(he,"group");function Gu(){return new ce({type:"collection"})}a(Gu,"collection");function Ku(...e){let t=e.map(n=>"build"in n?n.build():n);return new ce({type:"form",groups:t})}a(Ku,"form");function Yu(){return new ce({type:"activity"})}a(Yu,"activity");function Hu(e){return new ce({type:"richtext",attribute:e})}a(Hu,"richtext");function Ju(){return new ce({type:"documents"})}a(Ju,"documents");function Qu(){return new ce({type:"forms"})}a(Qu,"forms");function Zu(...e){return new ce({type:"emails",emailAttributes:e})}a(Zu,"emails");function Xu(...e){return new ce({type:"meetings",emailAttributes:e})}a(Xu,"meetings");function el(e,t){if(typeof e!="object"||e===null||typeof e.name!="string")throw new h$1("Expected registered extension declaration",[{path:["content","extension"],message:"Expected registered extension declaration"}]);let n=ot({type:"custom",extension:e.name,parameters:t},["content"]);if(n.type!=="custom")throw new h$1("Expected custom content",[]);let r=new ce({...n,extension:e.name},e);return r.build(),r}a(el,"custom");var E={collection:Gu,form:Ku,activity:Yu,richtext:Hu,documents:Ju,forms:Qu,emails:Zu,meetings:Xu,custom:el};function tl(e){if(!/^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$/.test(e))throw new Error(`Invalid flag name "${e}". Flag names must be kebab-case (e.g., "architect-mode", "ai-features").`)}a(tl,"validateFlagName");var Qr=class Qr{constructor(t,n,r){tl(t),this.flag={name:t,valueType:n,defaultValue:r,allowedLevels:["global","tenant","user"]};}label(t){return this.flag.label=t,this}description(t){return this.flag.description=t,this}category(t){return this.flag.category=t,this}system(){return this.flag.system=true,this}tenantScoped(){return this.flag.allowedLevels=["global","tenant"],this}globalOnly(){return this.flag.allowedLevels=["global"],this}allowedLevels(t){return this.flag.allowedLevels=[...t],this}build(){if(!this.flag.label?.trim())throw new Error(`Flag "${this.flag.name}" must have a label. Use .label("Human-readable label").`);return {...this.flag,allowedLevels:[...this.flag.allowedLevels||[]]}}};a(Qr,"BaseFlagBuilder");var at=Qr,Zr=class Zr extends at{constructor(t){super(t,"boolean",false);}defaultValue(t){return this.flag.defaultValue=t,this}enabledByDefault(){return this.flag.defaultValue=true,this}};a(Zr,"BooleanFlagBuilder");var Kr=Zr,Xr=class Xr extends at{constructor(t){super(t,"string","");}defaultValue(t){return this.flag.defaultValue=t,this}};a(Xr,"StringFlagBuilder");var Yr=Xr,ei=class ei extends at{constructor(t){super(t,"number",0);}defaultValue(t){return this.flag.defaultValue=t,this}};a(ei,"NumberFlagBuilder");var Hr=ei,ti=class ti extends at{constructor(t,n){super(t,"json",n);}defaultValue(t){return this.flag.defaultValue=t,this}};a(ti,"JsonFlagBuilder");var Jr=ti;function nl(e){return new Kr(e)}a(nl,"booleanFlag");function rl(e){return new Yr(e)}a(rl,"stringFlag");function il(e){return new Hr(e)}a(il,"numberFlag");function ol(e,t){return new Jr(e,t)}a(ol,"jsonFlag");function ni(e){return new r("feature flag",e,`Flag "${e}" is already registered. Each flag name must be unique.`)}a(ni,"duplicateFlagError");function ri(e){return {...e,allowedLevels:[...e.allowedLevels]}}a(ri,"cloneFlagDefinition");var ii=class ii{constructor(){this.flags=new Map;}register(t){if(this.flags.has(t.name))throw ni(t.name);this.flags.set(t.name,ri(t));}registerAll(t){let n=new Set;for(let r of t){if(this.flags.has(r.name)||n.has(r.name))throw ni(r.name);n.add(r.name);}for(let r of t)this.register(r);}get(t){let n=this.flags.get(t);return n?ri(n):void 0}getOrThrow(t){let n=this.get(t);if(!n)throw new c$2("Feature flag",t,void 0,`Flag "${t}" is not registered. Available flags: ${this.listNames().join(", ")}`);return n}has(t){return this.flags.has(t)}list(){return Array.from(this.flags.values(),ri)}listNames(){return Array.from(this.flags.keys())}unregister(t){return this.flags.delete(t)}clear(){this.flags.clear();}get size(){return this.flags.size}};a(ii,"FlagRegistry");var Ct=ii,al=new Ct;function sl(){return new Ct}a(sl,"createFlagRegistry");function cn(){return {global:new Map,tenant:new Map,user:new Map}}a(cn,"emptyOverrides");function cl(e,t){return e.expiresAt===void 0||e.expiresAt.getTime()>t}a(cl,"isActiveOverride");function oi(e,t){let n=new Map;for(let r of e){if(!cl(r,t))continue;let o=r.flagName;n.has(o)||n.set(o,r);}return n}a(oi,"indexOverrides");var ai=class ai{constructor(t){this.repository=t.repository,this.registry=t.registry,this.staticDefaults=new Map(t.staticDefaults?.map(n=>[n.name,n.value])??[]);}async resolveAll(t={}){let n=this.collectFlagNames(),r=this.repository&&n.size>0?await this.getAllOverrides(t,[...n]):cn();return this.resolveNames(n,r,t)}resolveAllStatic(){return this.resolveNames(this.collectFlagNames(),cn(),{})}collectFlagNames(){let t=new Set;for(let n of this.registry.listNames())t.add(n);for(let n of this.staticDefaults.keys())t.add(n);return t}resolveNames(t,n,r){let o=new Map;for(let a of t)o.set(a,this.resolveValue(a,n,r));return o}async resolve(t,n={}){let r=this.repository?await this.getAllOverrides(n,[t]):cn();return this.resolveWithSource(t,r,n)}async isEnabled(t,n={}){return (await this.resolve(t,n)).value===true}async getValue(t,n={}){return (await this.resolve(t,n)).value}async setOverride(t,n,r,o={}){if(!this.repository)throw new b$1("Cannot set override: no FeatureFlagsRepository configured. Add featureFlags to your DatabaseAdapter to enable runtime overrides.",a$2.CONFIGURATION_REQUIRED);let a=this.registry.get(t);if(a&&!a.allowedLevels.includes(n)){let s=`Flag "${t}" does not allow ${n}-level overrides. Allowed levels: ${a.allowedLevels.join(", ")}`;throw new h$1(s,[{path:["level"],message:s}])}if(a?.system){let s=`Flag "${t}" is a system flag and cannot be overridden via API.`;throw new h$1(s,[{path:["flagName"],message:s}])}await this.repository.setOverride({flagName:t,level:n,value:r,targetId:o.targetId,expiresAt:o.expiresAt,createdBy:o.createdBy});}async deleteOverride(t,n,r){if(!this.repository)throw new b$1("Cannot delete override: no FeatureFlagsRepository configured.",a$2.CONFIGURATION_REQUIRED);await this.repository.deleteOverride(t,n,r);}async getAllOverrides(t,n){if(!this.repository)return cn();let[r,o,a]=await Promise.all([this.repository.getOverrides({level:"global",flagNames:n}),t.tenantId?this.repository.getOverrides({level:"tenant",targetId:t.tenantId,flagNames:n}):Promise.resolve([]),t.userId?this.repository.getOverrides({level:"user",targetId:t.userId,flagNames:n}):Promise.resolve([])]),s=Date.now();return {global:oi(r,s),tenant:oi(o,s),user:oi(a,s)}}resolveValue(t,n,r){return this.resolveWithSource(t,n,r).value}resolveWithSource(t,n,r){let o=this.registry.get(t),a=o?.allowedLevels??["global","tenant","user"];if(r.userId&&a.includes("user")){let s=n.user.get(t);if(s)return {name:t,value:s.value,source:"user",sourceId:r.userId}}if(r.tenantId&&a.includes("tenant")){let s=n.tenant.get(t);if(s)return {name:t,value:s.value,source:"tenant",sourceId:r.tenantId}}if(a.includes("global")){let s=n.global.get(t);if(s)return {name:t,value:s.value,source:"global"}}return this.staticDefaults.has(t)?{name:t,value:this.staticDefaults.get(t),source:"default"}:{name:t,value:o?.defaultValue??void 0,source:"default"}}};a(ai,"FlagService");var un=ai;function ul(e){return new un(e)}a(ul,"createFlagService");var ma=Symbol("stndrds.native-object");function ci(e){return Object.defineProperty(e,ma,{value:true,enumerable:false}),e}a(ci,"markNativeDefinition");var li=class li extends St{build(){return ci(super.build())}};a(li,"NativeObjectBuilder");var si=li;function Ae(e){return new si(e)}a(Ae,"nativeObject");function ui(e){return e[ma]===true}a(ui,"isNativeDefinition");function di(e){let t=structuredClone(e);return ui(e)?ci(t):t}a(di,"cloneObjectDefinition");var mi=class mi{constructor(){this.objects=new Map;}register(t){let r$1=(Array.isArray(t)?t:[t]).map(a=>"build"in a&&typeof a.build=="function"?a.build():a),o=new Set;for(let a of r$1){if(this.validate(a),o.has(a.name))throw new r("object",a.name,`[NativeObjectRegistry] Duplicate object name "${a.name}" within a single register() batch.`);o.add(a.name);}for(let a of r$1)this.objects.set(a.name,di(a));return this}validate(t){if(!t.system){let n=`[NativeObjectRegistry] Cannot register object "${t.name}" (id: ${t.id}): missing system flag.
|
|
3
|
-
Native objects must have system=true. Did you call .runtime() on the builder? Remove that call \u2014 objects are system:true by default.`;throw new h$1(n,[])}if(b(t.name)&&!
|
|
1
|
+
import {b as b$3,j as j$2}from'./chunk-YJSVWV3Z.mjs';export{a as NonJsonValueError,f as asTenantId,g as asUserId,b as canonicalStringify,j as deepEqual,h as generateId,i as indexBy,e as sameStableValue,d as serializeCanonicalJson,c as serializeStableJson}from'./chunk-YJSVWV3Z.mjs';import {d,K,N as N$1,W as W$1,n as n$1,j as j$1,_,X as X$1,Y,g,h as h$2,C as C$1,B,z as z$1,v as v$2,Z as Z$1}from'./chunk-WUFUIJRX.mjs';export{i as ATTRIBUTE_FILTER_OPERATORS,f as LOCATION_FILTER_PROPERTIES,s as NO_VALUE_OPERATORS,r as OPERATORS_BY_TYPE,O as REMOVED_OPERATOR_REPLACEMENTS,G as SYNONYM_ALIASES,c as SYSTEM_ATTRIBUTES,a as SYSTEM_ATTRIBUTE_I18N_KEYS,N as SYSTEM_FILTER_ATTRIBUTE_TYPES,F as canonicalizeFilterValue,P as collectQualifiedRuleIssues,V as collectionContentSourceSchema,R as columnsSchema,_ as contentViewDefinitionSchema,Y as contentViewDefinitionSchemaFor,w as currentActor,S as displayAttributesSchema,Z as draftContentViewDefinitionSchema,X as draftContentViewDefinitionSchemaFor,z as extractCurrencyFilterValue,A as extractFilterValue,U as filterStateSchema,j as getAttributeCapabilities,k as getAttributeFilterOperators,B as getOperatorPolarity,u as getRollupFilterOperators,b as getSystemAttributeI18nKey,d as getSystemAttributeList,l as isAttributeFilterable,o as isAttributeGroupable,p as isAttributeKanbanGroupable,m as isAttributeSearchable,v as isDynamicValue,g as isLocationFilterProperty,h as isLocationPartOperator,e as isManagedSystemAttribute,t as isNoValueOperator,J as isRelativeDateValue,E as isSetMembershipOperator,I as normalizeFilterRule,C as normalizeForEdgeRpc,H as normalizeOperator,y as now,W as publishedViewContentDefinitionSchema,q as resolveEffectiveFilterType,K as resolveIsWithinBounds,L as resolveUtcDayBounds,T as sortsSchema,D as toMultiValueOperator,M as toUtcDayString,x as today,Q as validateQualifiedRule}from'./chunk-WUFUIJRX.mjs';import {n,b,h,j,t,i,m,w,K as K$1,x,l,o,p,q as q$1,v as v$1,L as L$1,G as G$1,I as I$1}from'./chunk-EZCWO4XV.mjs';export{u as ComputedFormulaParseError,d as LIST_VIEW_TAB_VISIBILITIES,a as NATIVE_OBJECT_NAMES,i as OBJECT_NAME_SCHEMA,g as RESERVED_ATTRIBUTE_NAMES,h as RESERVED_OBJECT_NAMES,c as RESOURCE_VISIBILITIES,r as SCHEMA_LIMITS,C as SIMPLE_PROPERTY_TYPES,f as SYSTEM_FIELD_NAMES,w as WIRE_OMITTED_CONFIG_KEYS,H as attributeConfigSchemas,s as colorIdSchema,t as iconNameSchema,b as isNativeObjectName,A as multiselectOptionWriteSchema,J as parseAttributeConfig,L as parseAttributeConfigForCreate,M as parseAttributeConfigForUpdate,v as parseComputedFormula,e as parseResourceVisibility,D as propertyAttributeSchema,F as propertyAttributeWireSchema,E as propertySchemaSchema,G as propertySchemaWireSchema,x as refuseForeignKeys,z as selectOptionWriteSchema,y as statusGroupSchema,B as statusOptionWriteSchema,n as validateAttributeName,j as validateObjectName,k as validateViewName}from'./chunk-EZCWO4XV.mjs';import {a as a$1,c as c$1,e,g as g$1}from'./chunk-XAVRKIBE.mjs';export{d as createFormAttributeValidator,a as isNullishOrEmptyString,b as isValuePresent,l as rejectUnknownAttributesOrThrow,j as validateDraft,k as validateDraftOrThrow,h as validateObject,i as validateObjectOrThrow}from'./chunk-XAVRKIBE.mjs';import'./chunk-GKXTXH4Y.mjs';import'./chunk-Q7TQCRSD.mjs';import'./chunk-WMQRTFOP.mjs';export{a as createCheckboxValidator}from'./chunk-4VCADZK4.mjs';export{a as createDateValidator}from'./chunk-KYPEBOPW.mjs';import {c,a as a$3,b as b$2}from'./chunk-LB4TNMZU.mjs';import'./chunk-PFO7NWQW.mjs';import'./chunk-XMQV2WFY.mjs';import'./chunk-VKFLXFPP.mjs';import'./chunk-YIXNAWH6.mjs';import'./chunk-XRDP2Y4J.mjs';import {h as h$1,b as b$1,a as a$2,r,s,c as c$2}from'./chunk-XRWRECDA.mjs';export{C as AccessDeniedError,I as AttributeInUseError,e as AttributeNotFoundError,q as ChangeTypeNotSupportedError,A as ConcurrentModificationError,o as DestructiveSyncNotAllowedError,r as DuplicateError,x as ForbiddenError,G as MemoryNotFoundError,p as MigrationTimeoutError,c as NotFoundError,F as NotImplementedError,d as ObjectNotFoundError,J as ObjectReferencedError,n as OrphanSystemAttributeError,i as ProtectedResourceError,y as ProtectedRoleError,f as RecordNotFoundError,H as RecordReferencedError,D as RepositoryError,s as ReservedObjectNameError,z as RoleNotFoundError,b as SchemaError,a as SchemaErrorCode,g as SchemaPlanNotFoundError,E as SearchBackendError,B as StorageError,m as SyncCascadeError,l as SyncConflictError,j as SyncError,k as SystemEntityImmutableError,h as ValidationError,L as isAttributeInUseError,u as isNotFoundError,M as isObjectReferencedError,w as isProtectedResourceError,K as isRecordReferencedError,t as isSchemaError,v as isValidationError}from'./chunk-XRWRECDA.mjs';export{a as TEXT_FORMAT_PATTERNS,c as createTextValidator,b as resolveTextPattern}from'./chunk-O34B5KOW.mjs';export{a as createNumberValidator}from'./chunk-KG2ADZG6.mjs';export{a as DEFAULT_VALIDATION_MESSAGES,b as formatZodErrors}from'./chunk-4OTKOCGB.mjs';import {a}from'./chunk-KSPJP74K.mjs';import {SKILL_NAME_MAX_LENGTH,SKILL_DESCRIPTION_MAX_LENGTH,MEMORY_NAME_MAX_LENGTH,MEMORY_DESCRIPTION_MAX_LENGTH,getCountryDisplayNameByIso3}from'@stndrds/constants';import {z}from'zod';/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
+
var ko=["fyi","task","question","handoff","system"],_o=["low","normal","high","urgent"],Po=["public","internal","sensitive"],Mo=["unread","read","archived","snoozed"],Fo=["none","pending","processing","completed","dismissed","expired","failed"],Kc="agent.session.waiting_human",Yc="agent.task.assigned",Hc="agent.question.requested",Fg=[Kc,Yc,Hc];var Bg=["name","type"],Lg=["required","hidden","archived","deprecated","defaultValue","config","order","unique"],$g=["label","description","placeholder","icon"];var Qt=["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"],ae="*";function zg(e){return e.type!=="relation"||!Array.isArray(e.targets)?[]:e.targets.map(t=>t.object).filter(t=>t!==ae)}a(zg,"relationTargetsOf");function Vo(e){return e.targets.length===1&&e.targets[0].object===ae}a(Vo,"isUniversalRelation");function Wg(e){return e.bilateral!==void 0}a(Wg,"isBilateralRelation");function Bo(e){return "many"}a(Bo,"inferInverseCardinality");function Gg(e){return n$1(e)}a(Gg,"isAttributeSortable");var Hg=["record","object","attribute","view","user","role","settings","file","agent","schema_source"],Jg=["record.created","record.updated","record.deleted","record.restored","record.purged","object.created","object.updated","object.deleted","attribute.created","attribute.updated","attribute.deleted","view.created","view.updated","view.deleted","schema_source.applied","schema_source.removed","user.created","user.invited","user.updated","user.deleted","user.login","user.logout","role.created","role.updated","role.deleted","role.assigned","role.revoked","settings.updated","file.uploaded","file.updated","file.deleted"];function Xg(e){return e.phase==="terminal"}a(Xg,"isTerminalState");function ey(e){switch(e.phase){case "running":return "active";case "queued":return "idle";case "parked":if(e.parkedOn===void 0)throw new b$1("parked state without parkedOn",a$2.INVARIANT_VIOLATION);return e.parkedOn==="agents"?"waiting_agents":"waiting_human";case "terminal":if(e.outcome===void 0)throw new b$1("terminal state without outcome",a$2.INVARIANT_VIOLATION);return e.outcome}}a(ey,"sessionStateToLegacyStatus");function ty(e){switch(e){case "active":return {phase:"running"};case "idle":return {phase:"queued"};case "waiting_human":return {phase:"parked",parkedOn:"human",humanRequestIds:[]};case "waiting_agents":return {phase:"parked",parkedOn:"agents"};default:return {phase:"terminal",outcome:e}}}a(ty,"legacyStatusToSessionState");var Jc=["completed","failed","cancelled","timeout","expired"];function ny(e){return Jc.includes(e)}a(ny,"isTerminalSessionStatus");var Qc=["idle","completed","waiting_human","waiting_agents","cancelled","failed","timeout"];function ry(e){return Qc.includes(e)}a(ry,"isClaimableSessionStatus");var Lo=Object.freeze({mutation:"ask",destructive:"ask",outward:"ask"}),iy=["active","completed","abandoned"],$o=["openai","anthropic","google","spacexai","deepseek","moonshotai","alibaba","mistral","minimax","meta","zai"],Uo=["standard","fast"],qo=["none","minimal","low","medium","high","xhigh"];function oy(e){return e.label?.trim()||e.name}a(oy,"agentDisplayName");var zo=["approval-requested","approval-responded","approval-dispatched"],Zc=["streaming","running","pending",...zo];function ay(e){return Zc.includes(e)}a(ay,"isOpenToolPartState");function sy(e){return zo.includes(e)}a(sy,"isToolApprovalState");var Gn=["CREDITS_EXHAUSTED"];function cy(e){return typeof e=="string"&&Gn.includes(e)}a(cy,"isSystemPartCode");function Xc(e,t){let n=e.createdAt.getTime()-t.createdAt.getTime();return n===0?e.id.localeCompare(t.id):n}a(Xc,"compareAgentSessionMessages");function uy(e){return [...e].sort(Xc)}a(uy,"orderAgentSessionMessages");var ly=["pending","in_progress","completed","blocked"],dy=50,py=80,my=500;var yy="session-state",eu="__stndrdsNativeUiPartIds",tu=1,nu="Native agent UI part IDs metadata is invalid";function qe(){throw new h$1(nu,[])}a(qe,"invalidNativePartIds");function Wo(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}a(Wo,"isPlainRecord");function ru(e,t){if(e.type==="text"||e.type==="reasoning")return `${e.type}:${t}`;if(e.type==="tool")return `tool:${e.toolCallId}`}a(ru,"nativeAgentUIPartIdMetadataKey");function hy(e){let t=e.metadata?.[eu];Wo(t)||qe(),(Object.keys(t).length!==2||t.schemaVersion!==tu||!Wo(t.partIds))&&qe();let n=new Map;for(let[s,c]of e.parts.entries()){let u=ru(c,s);if(!u||n.has(u)){u&&qe();continue}n.set(u,c);}let r=Object.entries(t.partIds);r.length!==n.size&&qe();let o=new Map,a={};for(let[s,c]of r){let u=n.get(s);u&&typeof c=="string"&&c.length>0||qe();let l=o.get(c);l&&(u.type==="tool"||l!==u.type)&&qe(),u.type==="tool"&&c!==u.toolCallId&&qe(),o.set(c,u.type),a[s]=c;}return a}a(hy,"parseNativeAgentUIPartIdsMetadata");var Ty=16e3,wy=3200,Sy=6400,Iy=16e3,Ry=65536,Cy=15e3,vy=1e4,Ny=5e3,Ey="google/gemini-3.5-transcribe-live",Dy={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2};var jy=["web","presentation","document","spreadsheet","image","code","other"],ky=["ephemeral","conversation","persistent"],_y=["source","preview","entrypoint","asset"];var Go=5;function Fy(e){return e instanceof Error?e.message:typeof e=="string"?e:e&&typeof e=="object"?"message"in e&&typeof e.message=="string"?e.message:JSON.stringify(e):String(e)}a(Fy,"getErrorMessage");function $y(e){return typeof e=="object"&&e!==null&&"slots"in e&&"steps"in e&&"name"in e&&typeof e.name=="string"&&Array.isArray(e.slots)&&Array.isArray(e.steps)}a($y,"isFormDefinition");var Kn=["relation","multiRelation","formula","rollup","document","richtext","user"];function Ko(e){return e.type==="slot"}a(Ko,"isFormSlotFieldRef");function Yn(e){return e.type==="free"}a(Yn,"isFormFreeFieldRef");function zy(e){return e.fieldRequired!==void 0?e.fieldRequired:e.slotMode==="create"&&e.attributeRequired===true}a(zy,"resolveFieldRequired");function Yo(e){return e.additionalSlotIds?.length?[e.slotId,...e.additionalSlotIds]:[e.slotId]}a(Yo,"getSlotFieldTargets");function iu(e){return Ko(e)?`${e.slotId}.${e.attribute}`:`free.${e.attribute.name}`}a(iu,"formFieldKey");function ou(e){return Ko(e)?e.attribute:e.attribute.name}a(ou,"formFieldFlatKey");function Wy(e,t){return e[iu(t)]??e[ou(t)]}a(Wy,"readFormFieldValue");function Zt(e){return e.type==="fields"}a(Zt,"isFormFieldsRow");function Yy(e){return e.type==="heading"}a(Yy,"isFormHeadingRow");function Hy(e){return e.type==="separator"}a(Hy,"isFormSeparatorRow");function Jy(e){return e.type==="text"}a(Jy,"isFormTextRow");var Hn=class Hn{async autocomplete(){return await Promise.resolve([])}async reverse(){return await Promise.resolve(null)}async geocode(){return await Promise.resolve(null)}};a(Hn,"NoopGeocodingAdapter");var Ho=Hn;var Jn=["read","create","update","delete","manage"];function rh(e){return e.length===0?"none":e.length===1&&e[0]==="read"?"read-only":e.length===Jn.length&&Jn.every(t=>e.includes(t))?"full":"custom"}a(rh,"actionsToAccessLevel");function ih(e){switch(e){case "full":return [...Jn];case "read-only":return ["read"];case "none":return []}}a(ih,"accessLevelToActions");function Xt(e){let t=e.properties;if(!t)return [];if(Array.isArray(t))return t;let n=t;return Array.isArray(n.definitions)?n.definitions:[]}a(Xt,"resolvePropertyDefinitions");function sh(e){return e.type==="select"||e.type==="status"||e.type==="multiselect"}a(sh,"hasOptions");var au="Notetaker",lh={systemPrompt:null,meetingRecordingPolicy:"none",meetingBotDisplayName:au};var ph=["active","suspended"],mh=["architect","manual","auto"];var bh=["square","landscape","portrait"];var Jo=["none","estimated","exact"];function su(e){if(typeof e=="string"&&Jo.includes(e))return e;throw new h$1(`countMode must be one of: ${Jo.join(", ")} (received: ${String(e)})`,[])}a(su,"parseCountMode");function hh(e){return e===void 0?void 0:su(e)}a(hh,"parseOptionalCountMode");var Ah=1e4;var wh=["storage.bytes","members.seats","data.live_records"];function cu(e){return e==null?true:typeof e!="object"?false:Object.keys(e).length===0}a(cu,"isEmptyObject");function Qo(e){return e!=null&&typeof e=="object"&&Object.keys(e).length>0}a(Qo,"isNotEmpty");function uu(e){return Qo(e)?e:void 0}a(uu,"toUndefinedIfEmpty");function lu(e){if(e<=0)return {value:0,unitIndex:0};let t=1e3,n=Math.min(4,Math.floor(Math.log(e)/Math.log(t)));return {value:Number.parseFloat((e/t**n).toFixed(1)),unitIndex:n}}a(lu,"computeByteMagnitude");var du=["B","KB","MB","GB","TB"];function fA(e){let{value:t,unitIndex:n}=lu(e);return `${t} ${du[n]}`}a(fA,"formatByteSize");var yA={ATTACHMENTS:"attachments"};function hA(e){return e.type==="document"}a(hA,"isDocumentAttribute");function AA(e,t){if(!t||t.length===0)return true;let n=e.name.toLowerCase();return t.some(r=>r.endsWith("/*")?e.mimeType.startsWith(r.slice(0,-1)):r.startsWith(".")?n.endsWith(r.toLowerCase()):e.mimeType===r)}a(AA,"matchesAccepts");var Zo=Object.freeze(["text","number","checkbox","date","phone","currency","status","select","multiselect","location"]);function en(e){let t=[];for(let n of e){let r=n.build();if(!Zo.includes(r.type))throw new Error(`Property type "${r.type}" is not supported in .qualifyWith()`);t.push(r);}return {definitions:t}}a(en,"buildPropertySchema");var IA="__";function RA(e){let t=e.indexOf("__");return t<=0||t+2>=e.length?{kind:"scalar",attribute:e}:{kind:"qualified",root:e.slice(0,t),property:e.slice(t+2)}}a(RA,"parseQualifiedAttribute");function CA(e,t){return `${e}__${t}`}a(CA,"buildQualifiedAttribute");function Oe(e){return typeof e=="object"&&e!==null&&typeof e.start=="string"}a(Oe,"isDateRangeValue");function pu(e,t){return a$1(e)?null:Oe(e)?t.endDate?{start:e.start,end:e.end??null}:e.start:typeof e=="string"?t.endDate?{start:e,end:null}:e:null}a(pu,"normalizeDateValue");function nt(e){return typeof e=="string"&&e!==""?e:Oe(e)&&e.start!==""?e.start:null}a(nt,"dateValueStart");var tn="\u2014";function mu(e){return String(e)}a(mu,"formatText");function fu(e){return e?"Yes":"No"}a(fu,"formatCheckbox");function bu(e,t){if(typeof e!="number")return String(e);if(t.renderAs==="rating")return `${e}/${t.max??5}`;let n=t.decimals;return t.unit==="integer"?e.toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:0}):t.unit==="percentage"?(e/100).toLocaleString(void 0,{style:"percent",minimumFractionDigits:n,maximumFractionDigits:n}):e.toLocaleString(void 0,{minimumFractionDigits:n,maximumFractionDigits:n})}a(bu,"formatNumber");function gu(e,t){if(typeof e!="object"||e===null)return String(e);let n=e;return "value"in n&&"code"in n?`${n.value.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})} ${n.code}`:String(e)}a(gu,"formatCurrency");function Qn(e){if(Oe(e)){let t=Qn(e.start);return e.end?`${t} \u2192 ${Qn(e.end)}`:t}if(e instanceof Date)return e.toISOString().split("T")[0];if(typeof e=="string"){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t.toISOString().split("T")[0]}return String(e)}a(Qn,"formatDate");function yu(e){if(typeof e!="object"||e===null)return String(e);let t=e;return "phoneNumber"in t?t.phoneNumber?t.countryCode?c(t):t.phoneNumber:"":String(e)}a(yu,"formatPhone");function hu(e,t="full"){if(typeof e!="object"||e===null)return "";let n=e,r=[];switch(t){case "country":n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "state":n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "city":n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;case "coordinates":n.latitude!==void 0&&n.longitude!==void 0&&r.push(`${n.latitude}, ${n.longitude}`);break;case "address":n.address&&r.push(n.address),n.city&&r.push(n.city),n.state&&r.push(n.state),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break;default:n.address&&r.push(n.address),n.address2&&r.push(n.address2),n.city&&r.push(n.city),n.state&&r.push(n.state),n.postalCode&&r.push(n.postalCode),n.country&&r.push(getCountryDisplayNameByIso3(n.country));break}return r.join(", ")}a(hu,"formatLocationValue");function Au(e,t){return typeof e!="object"||e===null?String(e):hu(e,t.granularity??"full")||tn}a(Au,"formatLocation");function xu(e,t){return typeof e!="string"?String(e):t.options?.find(r=>r.value===e)?.label??String(e)}a(xu,"formatSelect");function Tu(e,t){return Array.isArray(e)?t.options?e.map(r=>t.options.find(o=>o.value===r)?.label).filter(Boolean).join(", "):e.join(", "):String(e)}a(Tu,"formatMultiselect");function Xo(e,t){if(a$1(e))return tn;switch(t.type){case "text":return mu(e);case "checkbox":return fu(e);case "number":return bu(e,t);case "currency":return gu(e);case "date":return Qn(e);case "phone":return yu(e);case "location":return Au(e,t);case "select":case "status":return xu(e,t);case "multiselect":return Tu(e,t);case "user":case "relation":return Array.isArray(e)?e.join(", "):String(e);default:return Array.isArray(e)?e.join(", "):String(e)}}a(Xo,"formatAttributeValue");var Su=["UPPER","LOWER","capitalize","trim"],Iu=["prefix","suffix","wrap","default"],nn=[...Su,...Iu],rt=z.string().min(1,"labelExpression cannot be empty").refine(e=>rn(e),{message:"labelExpression must contain at least one {{ attribute }} interpolation"}).refine(e=>!/\{\{\s*\}\}/.test(e),{message:"labelExpression contains empty {{ }} interpolation"}).refine(e=>{let t=/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g,n;for(;(n=t.exec(e))!==null;){let r=n[1];if(!nn.includes(r))return false}return true},{message:`Invalid pipe name. Valid pipes: ${nn.join(", ")}`});function Ru(e){let t=rt.safeParse(e);return t.success?{success:true,attributes:St(e)}:{success:false,error:t.error.issues[0]?.message??"Invalid labelExpression"}}a(Ru,"validateLabelExpression");function Cu(e,t){let{name:n,args:r}=Nu(t);switch(n){case "UPPER":return e.toUpperCase();case "LOWER":return e.toLowerCase();case "capitalize":return e.replace(/(^|\s)\S/g,o=>o.toUpperCase());case "trim":return e.trim();case "prefix":return e?`${r[0]??""}${e}`:"";case "suffix":return e?`${e}${r[0]??""}`:"";case "wrap":return e?`${r[0]??""}${e}${r[1]??""}`:"";case "default":return e||r[0]||"";default:return e}}a(Cu,"applyPipe");function ea(e,t){let n=e;for(let r of t)n=Cu(n,r);return n}a(ea,"applyPipes");function vu(e,t){return t.split(".").reduce((n,r)=>{if(!(n==null||typeof n!="object"))return n[r]},e)}a(vu,"getValue");var ta="(Untitled)";function Nu(e){let t=e.match(/^(\w+)(?::(.*))?$/);if(!t)return {name:e,args:[]};let n=t[1],r=t[2];if(!r)return {name:n,args:[]};let o=[],a=/["']([^"']*?)["']/g,s;for(;(s=a.exec(r))!==null;)o.push(s[1]);return {name:n,args:o}}a(Nu,"parsePipeExpression");function*na(e){let t=0;for(;t<e.length;){let n=e.indexOf("{{",t);if(n<0)return;let r=e.indexOf("}",n+2);if(r<0)return;if(e[r+1]!=="}"){t=r+1;continue}t=r+2;let o=e.slice(n+2,r);o.length>0&&(yield {start:n,end:t,expr:o});}}a(na,"templateBlocks");function Eu(e,t){let n=e.split("||").map(u=>u.trim()),o=n[n.length-1].split("|").map(u=>u.trim());n[n.length-1]=o[0];let a=o.slice(1).filter(Boolean),s=n.filter(Boolean),c="";for(let u of s){let l=ra(vu(t,u));if(l!==""){c=l;break}}return ea(c,a)}a(Eu,"resolveLabelBlock");function Zn(e,t,n=ta){let r=[],o=0;for(let s of na(e))r.push(e.slice(o,s.start),Eu(s.expr,t)),o=s.end;return r.push(e.slice(o)),r.join("").trim()||n}a(Zn,"renderLabelExpression");function ra(e){if(e==null||typeof e=="function")return "";if(typeof e!="object")return String(e);if(Array.isArray(e))return e.map(ra).filter(Boolean).join(",");let t=e.toString;return typeof t=="function"&&t!==Object.prototype.toString?String(e):""}a(ra,"toText");function rn(e){let t=0;for(;t<e.length;){let n=e.indexOf("{{",t);if(n<0)return false;let r=e.indexOf("}}",n+2);if(r<0)return false;if(e.slice(n+2,r).trim().length>0)return true;t=r+2;}return false}a(rn,"isLabelExpression");function St(e){let t=[];for(let n of na(e)){let r=n.expr.trim();if(!r)continue;let o=r.split("||").map(s=>s.trim()),a=o[o.length-1];o[o.length-1]=a.split("|")[0].trim();for(let s of o){if(!s)continue;let c=s.split(".")[0];c&&!t.includes(c)&&t.push(c);}}return t}a(St,"extractAttributeNames");var Du=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function ia(e){let t=e.trim().match(Du);return t?t[1]:null}a(ia,"getSingleAttributeFromExpression");function Ou(e,t){let n=ia(e);if(n===null)return null;let r=t.find(o=>o.name===n);return !r||r.type!=="text"||j$1(r).authoring.readOnly?null:r}a(Ou,"getEditableLabelAttribute");var ju=/\{\{\s*props\./;function ku(e,t,n){if(!ju.test(e))return e;let r={},o=new Map(n?.map(s=>[s.name,s]));if(t)for(let[s,c]of Object.entries(t)){if(c==null)continue;let u=o.get(s);if(u){let l=Xo(c,u);r[s]=l===tn?"":l;}else r[s]=c;}return Zn(e,{props:r},"").replace(/\(\s*\)/g,"").replace(/\[\s*\]/g,"").replace(/\s*[-—|:]\s*$/g,"").replace(/\s{2,}/g," ").trim()}a(ku,"applyRelationProps");function _u(e){if(e?.type==="relation")return e.properties?.definitions}a(_u,"relationPropertyDefs");function Pu(e){if(e?.type==="relation"||e?.type==="document")return e.properties?.definitions}a(Pu,"qualifiedPropertyDefs");function oa(e){if(a$1(e))return [];if(typeof e=="string")return [{id:e}];if(Array.isArray(e))return e.flatMap(t=>oa(t));if(typeof e=="object"&&"id"in e){let t=e;if(typeof t.id=="string")return [{id:t.id,props:t.props}]}return []}a(oa,"extractValueRefs");function Mu(e){let t=[e.firstName,e.lastName].map(n=>n?.trim()).filter(Boolean).join(" ");return t!==""?t:e.email?.split("@")[0]??""}a(Mu,"getUserDisplayName");var Fu=/\p{L}|\p{N}/u;function Vu(e,t){let n=e?.trim()??"";if(n==="")return t;let r=n.split(/\s+/),a=(r.length===1?n.split("@")[0].split(/[._-]/):r).map(s=>{let c=s.match(Fu)?.[0];return c===void 0?"":[...c.toUpperCase()][0]??""}).filter(Boolean).slice(0,2).join("");return a===""?t:a}a(Vu,"deriveInitials");var aa="__creatorRootActorId";function Bu(e){let t=e.metadata?.[aa];return typeof t=="string"&&t.length>0?t:e.createdBy}a(Bu,"getRecordCreatorPrincipalId");function it(e,t){return e?.includes("*")===true||e?.includes(t)===true}a(it,"includesAction");function Lu(e){return {canRead:it(e,"read"),canCreate:it(e,"create"),canUpdate:it(e,"update"),canDelete:it(e,"delete"),canManage:it(e,"manage")}}a(Lu,"buildPermissionFlags");var XA=new Set(["id","name","label","type","required","system","unique","order"]);var te={PEOPLE:"people",WORKSPACE:"workspace",ARCHITECT:"architect",FEATURE_FLAGS:"feature-flags",FILES:"files",VIEWS:"views",FORMS:"forms",DOCUMENTS:"documents",AUDIT:"audit",API_KEYS:"api-keys",CONNECTORS:"connectors",ENV_VARS:"env-vars",SESSION:"session"},tx=[te.PEOPLE,te.WORKSPACE,te.ARCHITECT,te.FEATURE_FLAGS,te.FILES,te.VIEWS,te.FORMS,te.DOCUMENTS,te.AUDIT,te.API_KEYS,te.CONNECTORS,te.ENV_VARS,te.SESSION],nx={people:"People",workspace:"Workspace",architect:"Architect","feature-flags":"Feature flags",files:"Files",views:"Views",forms:"Forms",documents:"Documents",audit:"Audit","api-keys":"API keys",connectors:"Connected accounts","env-vars":"Environment variables",session:"Agent sessions"},$u={OWNER:"owner",MEMBER:"member",AGENT_DEFAULT:"agent_default",REFLEX_DEFAULT:"reflex_default"},rx={owner:"Owner",member:"Member",agent_default:"Agent Default",reflex_default:"Reflex Default"},ix={owner:"Full access to all platform features and data",member:"Can view, create, edit and delete business data",agent_default:"Default role for AI agents \u2014 CRUD on records plus documents and files",reflex_default:"Default role for reflexes \u2014 no data access; each reflex is granted exactly what its rehearsal showed it uses"},Xn=["read","create","update","delete","manage"],Uu=["read","create","update","delete"],sa=["read","create","update","delete"],ox={owner:{system:[{target:"*",actions:Xn}],object:[{target:"*",actions:Xn}]},member:{system:[{target:"people",actions:["read"]},{target:"workspace",actions:["read"]},{target:"connectors",actions:Uu},{target:"files",actions:sa},{target:"documents",actions:sa}],object:[{target:"*",actions:Xn}]},agent_default:{system:[{target:"documents",actions:["read","create","update"]},{target:"files",actions:["read","create","update"]},{target:"env-vars",actions:["read"]},{target:"session",actions:["observe"]}],object:[{target:"*",actions:["read","create","update","delete"]}]},reflex_default:{system:[],object:[]}};function ax(e){return Object.values($u).includes(e)}a(ax,"isDefaultRole");var ca={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2},timeoutMs:3e5},tr=class tr{constructor(t){if(!t.name||t.name.trim().length===0)throw new h$1("Agent name is required",[]);this.bp={name:t.name,system:true,visibility:"workspace",triggers:[]};}description(t){return this.bp.description=t,this}label(t){return this.bp.label=t,this}icon(t){return this.bp.icon=t,this}systemPrompt(t){return this.bp.systemPrompt=t,this}model(t,n,r){return this.bp.model={provider:t,model:n,...r},this}tools(t){return this.bp.tools=[...t],this}schedule(t){return this.bp.schedule={...t,enabled:t.enabled??true},this}config(t){let n=this.bp.config??ca,r=t.inference===void 0?n.inference:{...n.inference,...t.inference};return this.bp.config={...n,...t,...r===void 0?{}:{inference:r}},this}delegation(t){return Object.assign(this.bp,t),this}mcpServers(t){return this.bp.mcpServers=Array.isArray(t)?[...t]:t,this}approval(t){return this.bp.approval={...Lo,...this.bp.approval,...t},this}visibility(t){return this.bp.visibility=t,this}requiresPermission(t,n){return this.bp.requiredPermission={resource:t,action:n},this}trigger(t,n,r){return this.bp.triggers.push({name:t,eventType:n,...r,enabled:r?.enabled??true}),this}runtime(){return this.bp.system=false,this}build(){if(!this.bp.systemPrompt)throw new h$1(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new h$1(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility==="private")throw new h$1(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return l(this.bp.triggers,t=>t.name,t=>new h$1(`Agent "${this.bp.name}": duplicate trigger name "${t}"`,[])),{...this.bp,visibility:this.bp.visibility??"workspace",config:this.bp.config??ca,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};a(tr,"AgentBuilder");var er=tr;function px(e){return new er(e)}a(px,"agent");var qu="@stndrds/schema";function on(e){return {version:1,vendor:qu,validate:a(t=>{let n=e.safeParse(t);return n.success?{value:n.data}:{issues:n.error.issues.map(r=>({message:r.message,path:r.path}))}},"validate")}}a(on,"createStandardSchemaProps");function bx(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"].version===1}a(bx,"isStandardSchema");var Ar=class Ar{get"~standard"(){let t=c$1(this.build());return on(t)}constructor(t,n$1,r){n(n$1),o(r),this.attr={name:n$1,label:r,type:t,required:false,system:true};}setRequired(t){this.attr.required=t;}asRequiredState(){return this}asPhantomState(){return this}runtime(){return this.attr.system=false,this}hidden(){return this.attr.hidden=true,this}placeholder(t){return this.attr.placeholder=t,this}description(t){return this.attr.description=t,this}icon(t){return p(t,`attribute "${this.attr.name}"`),this.attr.icon=t,this}order(t){return this.attr.order=t,this}defaultValue(t){return ("defaultValue"in this.attr||!["formula","rollup"].includes(this.attr.type))&&(this.attr.defaultValue=t),this}metadata(t){return this.attr.metadata=t,this}build(){return this.attr}};a(Ar,"BaseAttributeBuilder");var L=Ar,xr=class xr extends L{constructor(t,n){super("text",t,n);}minLength(t){return this.attr.minLength=t,this}maxLength(t){return this.attr.maxLength=t,this}pattern(t){return this.attr.pattern=t,this.attr.format=void 0,this}multiline(t=true){return this.attr.multiline=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}email(){return this.attr.format="email",this.attr.pattern=void 0,this}url(){return this.attr.format="url",this.attr.pattern=void 0,this}slug(){return this.attr.format="slug",this.attr.pattern=void 0,this}};a(xr,"TextAttributeBuilder");var nr=xr;function S(e){return new nr(e.name,e.label)}a(S,"text");var Tr=class Tr extends L{constructor(t,n){super("richtext",t,n);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Tr,"RichtextAttributeBuilder");var rr=Tr;function je(e){return new rr(e.name,e.label)}a(je,"richtext");var wr=class wr extends L{constructor(t,n){super("number",t,n);}min(t){return this.attr.min=t,this}max(t){return this.attr.max=t,this}integer(){return this.attr.unit="integer",this.attr.decimals=0,this}decimal(t=2){return this.attr.unit="decimal",this.attr.decimals=t,this}percentage(){return this.attr.unit="percentage",this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(wr,"NumberAttributeBuilder");var ir=wr;function sn(e){return new ir(e.name,e.label)}a(sn,"number");var Sr=class Sr extends L{constructor(t,n){super("checkbox",t,n);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Sr,"CheckboxAttributeBuilder");var or=Sr;function ua(e){return new or(e.name,e.label)}a(ua,"checkbox");var Ir=class Ir extends L{constructor(t,n){super("date",t,n);}format(t){return this.attr.dateFormat=t,this}minDate(t){return this.attr.minDate=t,this}maxDate(t){return this.attr.maxDate=t,this}endDate(){return this.attr.endDate=true,this.asPhantomState()}includeTime(){return this.attr.includeTime=true,this}timeFormat(t){return this.attr.timeFormat=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Ir,"DateAttributeBuilder");var ar=Ir;function se(e){return new ar(e.name,e.label)}a(se,"date");var Rr=class Rr extends L{constructor(t,n){super("phone",t,n);}defaultCountry(t){return this.attr.defaultCountryCode=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Rr,"PhoneAttributeBuilder");var sr=Rr;function Ix(e){return new sr(e.name,e.label)}a(Ix,"phone");var Cr=class Cr extends L{constructor(t,n){super("currency",t,n);}defaultCurrency(t){return this.attr.defaultCurrency=t,this}allowedCurrencies(t){return this.attr.allowedCurrencies=t,this}allowNegative(t=true){return this.attr.allowNegative=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Cr,"CurrencyAttributeBuilder");var cr=Cr;function Rx(e){return new cr(e.name,e.label)}a(Rx,"currency");var vr=class vr extends L{constructor(t,n){super("status",t,n);}options(t){let n=t;return q$1(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return q$1(this.attr.name??"unknown",n),this.attr.options.push(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(vr,"StatusAttributeBuilder");var ur=vr;function Cx(e){return new ur(e.name,e.label)}a(Cx,"status");var Nr=class Nr extends L{constructor(t,n){super("select",t,n);}options(t){let n=t;return q$1(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return q$1(this.attr.name??"unknown",n),this.attr.options.push(t),this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Nr,"SelectAttributeBuilder");var lr=Nr;function fe(e){return new lr(e.name,e.label)}a(fe,"select");var Er=class Er extends L{constructor(t,n){super("multiselect",t,n);}options(t){let n=t;return q$1(this.attr.name??"unknown",n),this.attr.options=n,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let n=[...this.attr.options,t];return q$1(this.attr.name??"unknown",n),this.attr.options.push(t),this}renderAs(t){return this.attr.renderAs=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Er,"MultiselectAttributeBuilder");var dr=Er;function vx(e){return new dr(e.name,e.label)}a(vx,"multiselect");var Dr=class Dr extends L{constructor(t,n){super("location",t,n);}granularity(t){return this.attr.granularity=t,this}defaultCountry(t){return this.attr.defaultCountry=t,this}allowedCountries(t){return this.attr.allowedCountries=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Dr,"LocationAttributeBuilder");var pr=Dr;function Nx(e){return new pr(e.name,e.label)}a(Nx,"location");var Or=class Or extends L{constructor(t,n){super("user",t,n),this.attr.types=["user","agent"];}types(t){let n=[...new Set(t)];if(n.length===0)throw new Error("[AttributeBuilder] user.types must contain at least one type.");return this.attr.types=n,this}multiple(){return this.attr.multiple=true,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Or,"UserAttributeBuilder");var mr=Or;function Ex(e){return new mr(e.name,e.label)}a(Ex,"user");var jr=class jr extends L{to(t,n){let r={object:t,...n};return this.attr.targets?.push(r),this}toAny(){return this.attr.targets=[{object:ae}],this}qualifyWith(...t){let n=this.attr.targets;if(!n||n.length===0)throw new Error('.qualifyWith() must be called AFTER .to(). Example: relation({ name: "companies" }).to("companies").qualifyWith(...)');return this.attr.properties=en(t),this}bilateral(t){let n=this.attr.targets;if(!n||n.length===0)throw new Error('.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })');if(n.length>1)throw new Error("Bilateral relations are not supported for polymorphic relations (multiple .to() targets).");if(Vo(this.attr))throw new Error("Bilateral relations are not supported for universal relations (.toAny()).");let r=n[0]?.object;if(!r)throw new h$1("Bilateral relation requires one target object",[{path:["bilateral","object"],message:"Bilateral relation requires one target object"}]);if(t.object&&t.object!==r){let o=`Bilateral inverse object ${t.object} must match relation target ${r}`;throw new h$1(o,[{path:["bilateral","object"],message:o}])}return this.attr.bilateral={...t,object:r},this}};a(jr,"BaseRelationAttributeBuilder");var an=jr,kr=class kr extends an{constructor(t,n){super("relation",t,n),this.attr.cardinality="one",this.attr.targets=[];}many(){let t=new br(this.attr.name,this.attr.label??"",{targets:this.attr.targets,isRequired:this.attr.required});return this.attr.system===false&&t.runtime(),this.attr.hidden&&t.hidden(),this.attr.placeholder&&t.placeholder(this.attr.placeholder),this.attr.description&&t.description(this.attr.description),this.attr.icon&&t.icon(this.attr.icon),this.attr.order!==void 0&&t.order(this.attr.order),this.attr.metadata&&t.metadata(this.attr.metadata),t}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(kr,"SingleRelationAttributeBuilder");var fr=kr,_r=class _r extends an{constructor(t,n,r){super("relation",t,n),this.attr.cardinality="many",this.attr.targets=r?.targets??[],this.attr.defaultValue=[],r?.isRequired&&this.setRequired(true);}maxItems(t){return this.attr.maxItems=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(_r,"MultiRelationAttributeBuilder");var br=_r;function ot(e){return new fr(e.name,e.label)}a(ot,"relation");var Pr=class Pr extends L{constructor(t,n){super("formula",t,n),this.attr.required=false;}expression(t){return this.attr.expression=t,this}returns(t){return this.attr.returnType=t,this}decimals(t){return this.attr.decimals=t,this}required(){throw new Error("Formula attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.")}optional(){return this}};a(Pr,"FormulaAttributeBuilder");var gr=Pr;function Dx(e){return new gr(e.name,e.label)}a(Dx,"formula");var Mr=class Mr extends L{constructor(t,n){super("rollup",t,n),this.attr.required=false;}from(t){return this.attr.relationAttribute=t,this}aggregate(t){return this.attr.targetAttribute=t,this}using(t){return this.attr.function=t,this}decimals(t){return this.attr.decimals=t,this}path(t){return this.attr.relationPath=t,this}targetType(t){return this.attr.targetAttributeType=t,this}targetOptions(t){return this.attr.targetAttributeOptions=t,this}targetCurrency(t){return this.attr.targetCurrencyCode=t,this}build(){let t=this.attr.function,n=this.attr.targetAttributeType;if(t==="original"&&n!==void 0&&n!=="select"&&n!=="status"&&n!=="multiselect"){let r=this.attr.relationAttribute??"relation",o=this.attr.targetAttribute??"field";throw new b$1(`Rollup "${this.attr.name}": .using("original") only supports a "select", "status", or "multiselect" target, but .targetType("${n}") was given. To surface a plain ${n} value from a related record, use a formula instead \u2014 e.g. formula({ name: "${this.attr.name}", label: "\u2026" }).expression("${r}.${o}").`,a$2.VALIDATION_FAILED)}return super.build()}required(){throw new Error("Rollup attributes cannot be required: they are computed read-only values. Remove .required() from this attribute definition.")}optional(){return this}};a(Mr,"RollupAttributeBuilder");var yr=Mr;function Ox(e){return new yr(e.name,e.label)}a(Ox,"rollup");var Fr=class Fr extends L{constructor(t,n){super("document",t,n);}accepts(t){return this.attr.accepts=t,this}maxFileSize(t){return this.attr.maxFileSize=t,this}qualifyWith(...t){return this.attr.properties=en(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Fr,"DocumentAttributeBuilder");var hr=Fr;function la(e){return new hr(e.name,e.label)}a(la,"document");function pa(e,t,n){let r=Array.isArray(e)?e:[e],[o,...a]=r;return {type:"slot",slotId:o,additionalSlotIds:a.length>0?a:void 0,attribute:t,label:n?.label,required:n?.required,tooltip:n?.tooltip}}a(pa,"buildSlotFieldRef");var $r=class $r{constructor(t,n,r){this._finalized=false;this.stepBuilder=t,this.rowData={id:n,order:r,type:"fields",fields:[]};}field(t,n,r){return this.rowData.fields.push(pa(t,n,r)),this}freeField(t,n){let o={type:"free",attribute:t.build(),label:n?.label,required:n?.required,prefillExpression:n?.prefillExpression};return this.rowData.fields.push(o),this}row(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).row(t)}heading(t,n){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).heading(t,n)}separator(){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).separator()}text(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).text(t)}endRow(){return this._finalized?this.stepBuilder:(this._finalized=true,this.stepBuilder._finalizeRow(this.rowData))}};a($r,"FormRowBuilder");var Vr=$r,Ur=class Ur{constructor(t,n,r){this.rowOrder=0;this.formBuilder=t,this.stepData={id:n,label:r,rows:[]};}description(t){return this.stepData.description=t,this}field(t,n,r){this.rowOrder++;let o=`row-${this.stepData.id}-${this.rowOrder}`,a=pa(t,n,r),s={id:o,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}freeField(t,n){this.rowOrder++;let r=`row-${this.stepData.id}-${this.rowOrder}`,a={type:"free",attribute:t.build(),label:n?.label,required:n?.required,prefillExpression:n?.prefillExpression},s={id:r,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}row(t){return this.rowOrder++,new Vr(this,t,this.rowOrder)}heading(t,n){this.rowOrder++;let r={id:`heading-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"heading",content:t,level:n};return this.stepData.rows.push(r),this}separator(){this.rowOrder++;let t={id:`sep-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"separator"};return this.stepData.rows.push(t),this}text(t){this.rowOrder++;let n={id:`text-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"text",content:t};return this.stepData.rows.push(n),this}step(t,n){return this.formBuilder._finalizeStep(this.stepData).step(t,n)}build(){return this.formBuilder._finalizeStep(this.stepData).build()}_finalizeRow(t){return t.fields.length>0&&this.stepData.rows.push(t),this}_getData(){return this.stepData}};a(Ur,"FormStepBuilder");var Br=Ur,qr=class qr{constructor(t,n){this.data={slots:[],steps:[],status:"draft",version:1};this.validateName(t),this.data.name=t,this.data.label=n;}description(t){return this.data.description=t,this}icon(t){return this.data.icon=t,this}status(t){return this.data.status=t,this}metadata(t){return this.data.metadata=t,this}slot(t,n,r){if(this.data.slots.some(a=>a.id===t))throw new Error(`[FormBuilder] Duplicate slot id: "${t}"`);let o={id:t,objectName:n,label:r.label,mode:r.mode??"create",color:r.color,icon:r.icon};return this.data.slots.push(o),this}step(t,n){if(this.data.steps.some(r=>r.id===t))throw new Error(`[FormBuilder] Duplicate step id: "${t}"`);return new Br(this,t,n)}build(){return this.validateRequiredData(),this.validateSlotReferences(),this.validateFreeFields(),this.validatePrefillExpressions(),this.data}_finalizeStep(t){return this.data.steps.push(t),this}validateName(t){let n=z.string().min(1,"Form name cannot be empty").max(63,"Form name is too long (max 63 characters)").regex(/^[a-z0-9]+(-[a-z0-9]+)*$/,{message:"Invalid form name format. Name must be in kebab-case: 'client-onboarding', 'contact-creation'"});try{n.parse(t);}catch(r){throw r instanceof z.ZodError?new Error(`[FormBuilder] ${r.issues[0].message}`):r}}validateRequiredData(){if(this.data.slots.length===0)throw new Error("[FormBuilder] At least one slot is required. Use .slot() to add slots.");if(this.data.steps.length===0)throw new Error("[FormBuilder] At least one step is required. Use .step() to add steps.")}validateSlotReferences(){let t=new Map(this.data.slots.map(n=>[n.id,n.objectName]));for(let n of this.data.steps)for(let r of n.rows)if(Zt(r))for(let o of r.fields){if(o.type!=="slot")continue;let a=Yo(o);for(let c of a)if(!t.has(c))throw new Error(`[FormBuilder] Step "${n.id}" references unknown slot "${c}". Declare it with .slot("${c}", ...) first.`);let s=new Set(a.map(c=>t.get(c)));if(s.size>1)throw new Error(`[FormBuilder] Step "${n.id}" field on attribute "${o.attribute}" targets slots of different objects (${[...s].join(", ")}). A multi-slot field must target slots of the same object.`)}}validatePrefillExpressions(){let t=[...nn,"join"];for(let n of this.data.steps)for(let r of n.rows)if(Zt(r))for(let o of r.fields){if(!Yn(o)||!o.prefillExpression)continue;let a=o.prefillExpression,s=`prefillExpression on free field "${o.attribute.name}" in step "${n.id}"`;if(!rn(a))throw new Error(`[FormBuilder] ${s} must contain at least one {{ attribute }} interpolation.`);if(/\{\{\s*\}\}/.test(a))throw new Error(`[FormBuilder] ${s} contains empty {{ }} interpolation.`);for(let c of a.matchAll(/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g)){let u=c[1];if(!t.includes(u))throw new Error(`[FormBuilder] ${s} uses invalid pipe "${u}". Valid pipes: ${t.join(", ")}`)}}}validateFreeFields(){let t=new Set(Kn);for(let n of this.data.steps)for(let r of n.rows)if(Zt(r)){for(let o of r.fields)if(Yn(o)){let a=o.attribute.type;if(t.has(a))throw new Error(`[FormBuilder] Free field in step "${n.id}" uses forbidden attribute type "${a}". Forbidden types: ${Kn.join(", ")}`)}}}};a(qr,"FormBuilder");var Lr=qr;function Vx(e,t){return new Lr(e,t)}a(Vx,"form");function zu(e){return {text:"toString",richtext:"toString",number:"toNumber",currency:"toNumber",date:"toDate",checkbox:"toBoolean"}[e]}a(zu,"resolveBuiltInTransform");var zr=class zr{constructor(t){this.operations=[];this.touchedAttributes=new Set;this.version=t;}assertNotTouched(t,n){if(this.touchedAttributes.has(t))throw new h$1(`[MigrationBuilder] Conflicting operations on attribute "${t}": it was already modified earlier in this migration (attempted: ${n}).`,[])}renameAttribute(t,n){return this.assertNotTouched(t,"rename_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"rename_attribute",from:t,to:n}),this}changeType(t,n,r,o){this.assertNotTouched(t,"change_type"),this.touchedAttributes.add(t);let a=o?.transform?zu(r):void 0;return this.operations.push({type:"change_type",name:t,from:n,to:r,transform:a}),this}removeAttribute(t){return this.assertNotTouched(t,"remove_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"remove_attribute",name:t}),this}addAttribute(t){return this.assertNotTouched(t.name,"add_attribute"),this.touchedAttributes.add(t.name),this.operations.push({type:"add_attribute",attribute:t}),this}updateConfig(t,n){return this.assertNotTouched(t,"update_config"),this.touchedAttributes.add(t),this.operations.push({type:"update_config",name:t,from:{},to:n}),this}build(){return {version:this.version,operations:[...this.operations]}}};a(zr,"MigrationBuilder");var cn=zr;function Wu(e){let{name:t,labelExpression:n,embeddingExpression:r}=e;if(!n)throw new b$1(`Object "${t}" must have a labelExpression. The labelExpression defines how records are displayed in lists and relations (e.g. "{{ name }}").`,a$2.VALIDATION_FAILED);let o=rt.safeParse(n);if(!o.success){let a=o.error.issues[0]?.message??"Invalid labelExpression";throw new b$1(`Invalid labelExpression for "${t}": ${a}`,a$2.VALIDATION_FAILED)}if(r!==void 0){let a=rt.safeParse(r);if(!a.success){let s=a.error.issues[0]?.message??"Invalid embeddingExpression";throw new b$1(`Invalid embeddingExpression for "${t}": ${s}`,a$2.VALIDATION_FAILED)}}}a(Wu,"validateObjectExpressions");var Wr=class Wr{constructor(t){this._migrations=[];this._sealed=false;this._toleratedAttributes=[];this.validateName(t.name),this.obj={name:t.name,label:t.label,attributes:[],system:true},t.id&&(this.obj.id=t.id);}get"~standard"(){let t=e(this.build());return on(t)}description(t){return this.obj.description=t,this}pluralLabel(t){return this._pluralLabel=t,this}icon(t){return this.obj.icon=t,this}runtime(){return this.obj.system=false,this}sealed(){return this._sealed=true,this}tolerate(t){return this._toleratedAttributes=[...this._toleratedAttributes,...t],this}attribute(t){return this.pushAttributes([t]),this}attributes(t){return this.pushAttributes(t),this}pushAttributes(t){let n=t.map(r=>"build"in r&&typeof r.build=="function"?r.build():r);l([...this.obj.attributes,...n],r=>r.name,r$1=>new r("attribute",r$1,`Object "${this.obj.name}": duplicate attribute name "${r$1}"`)),this.obj.attributes.push(...n);}metadata(t){return this.obj.metadata={...this.obj.metadata,...t},this}order(t){return this.obj.metadata={...this.obj.metadata,order:t},this}hidden(){return this.obj.metadata={...this.obj.metadata,hidden:true},this}labelExpression(t){return this._labelExpression=t,this}embeddingExpression(t){return this._embeddingExpression=t,this}documentLayout(t){if(t.presets)for(let n of t.presets)ma(n.id,n.structure,1);return this.obj.documentLayout=t,this}migration(t,n){if(t<2)throw new Error(`[ObjectBuilder] Migration version must be >= 2 (version 1 is implicit). Got: ${t}`);if(this._migrations.some(a=>a.version===t))throw new Error(`[ObjectBuilder] Duplicate migration version: ${t}`);let o=new cn(t);return n(o),this._migrations.push(o.build()),this}build(){if(!this.obj.name)throw new h$1("[ObjectBuilder] Missing required field: name",[{path:["name"],message:"name is required"}]);if(!this.obj.label)throw new h$1("[ObjectBuilder] Missing required field: label",[{path:["label"],message:"label is required"}]);Wu({name:this.obj.name,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression});let t=[...this._migrations].sort((r,o)=>r.version-o.version);for(let r=0;r<t.length;r++){let o=r+2;if(t[r].version!==o)throw new Error(`[ObjectBuilder] Migration versions must be sequential starting at 2. Expected version ${o}, got ${t[r].version}.`)}let n=t.length>0?t[t.length-1].version:1;return {...this.obj,pluralLabel:this._pluralLabel,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression,schema_version:n,migrations:t,sealed:this._sealed,toleratedAttributes:this._toleratedAttributes}}validateName(t){t!==void 0&&j(t);}};a(Wr,"ObjectBuilder");var It=Wr;function Qx(e){if(b(e.name))throw new s(e.name,"builder");return new It(e)}a(Qx,"object");function ma(e,t,n){let r=a((a,s)=>{throw new h$1(a,[{path:["documentLayout","presets",e],message:s}])},"fail");n>5&&r(`Preset structure exceeds max depth of ${5}`,"Preset structure too deep");let o=new Set;for(let a of t){let s=a.title.trim();s.length===0&&r("Folder preset node title is required","Empty folder title"),s.includes("/")&&r("Folder preset node title cannot contain /",`Folder title contains /: "${s}"`),o.has(s)&&r("Folder preset sibling titles must be unique",`Duplicate folder title: "${s}"`),o.add(s),a.children&&a.children.length>0&&ma(e,a.children,n+1);}}a(ma,"validatePresetStructure");function be(e,t){try{return structuredClone(e)}catch{let n="Builder configuration must contain cloneable data";throw new h$1(n,[{path:t,message:n}])}}a(be,"cloneBuilderValue");function Ce(e,t){if(typeof e!="string"||e.trim().length===0)throw new h$1("Name must not be blank",[{path:t,message:"Name must not be blank"}])}a(Ce,"requireBuilderName");function at(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new h$1("Invalid content configuration",[{path:t,message:"Expected content configuration"}]);for(let c of ["name","label","placement"])if(Object.hasOwn(e,c)){let u=`Independent content configuration cannot define ${c}`;throw new h$1(u,[{path:[...t,c],message:u}])}let n=W$1.safeParse({...e,name:"content",placement:"main"});if(!n.success)throw h$1.fromZodErrors(n.error.issues.map(c=>({path:[...t,...c.path.map(String)],message:c.message})));n.data.type==="form"&&n.data.groups.forEach((c,u)=>Ce(c.name,[...t,"groups",String(u),"name"]));let{name:r,label:o,placement:a,...s}=n.data;return be(s,t)}a(at,"validateContentConfiguration");function Gr(e,t){return at(e,t),be(e,t)}a(Gr,"validateLiteralContent");function ze(e){return e.relation===void 0?{kind:"object",object:e.object}:e.object===void 0?{kind:"related",relation:e.relation}:{kind:"relatedFrom",object:e.object,relation:e.relation}}a(ze,"collectionSourceAddress");function Kr(e){if(!e||typeof e!="object")return;let t="object"in e?e.object:void 0,n="relation"in e?e.relation:void 0;if(typeof t=="string"&&typeof n=="string")return {kind:"relatedFrom",object:t,relation:n};if(typeof t=="string"&&n===void 0)return {kind:"object",object:t};if(typeof n=="string"&&t===void 0)return {kind:"related",relation:n}}a(Kr,"collectionSourceAddressOf");function Rt(e,t,n){if(t!=="record"){let r=`Content "${e}" requires record context. In a collection view only a collection that lists a whole object, or a custom content that does not require a record, is allowed.`;throw new h$1(r,[{path:n,message:r}])}}a(Rt,"requireRecordContentContext");function Gu(e){let t=e.openMode??"page";return {openMode:t,createMode:e.createMode??t}}a(Gu,"resolveContentNavigation");function Ku(e,t){return [...new Set(t)].filter(n=>e.actions===void 0||e.actions.includes(n))}a(Ku,"resolveCollectionActions");var ke=class ke{constructor(t,n=[]){this.kind="view";this.data=be(t,["views","0"]),this.extensions=n.map(r=>r&&{...r});}for(t){return new ke({...this.data,object:t},this.extensions)}default(){return new ke({...this.data,default:true},this.extensions)}description(t){return new ke({...this.data,description:t},this.extensions)}icon(t){return new ke({...this.data,icon:t},this.extensions)}place(t,n,r,o){let a=["views","0","contents",String(this.data.contents.length)],s,c;try{r!==null&&typeof r=="object"&&"build"in r&&typeof r.build=="function"?(s=at(r.build(),a),c=r.extension):s=at(r,a);}catch(m){throw m instanceof h$1?new h$1(m.message,m.errors.map(d=>({...d,path:d.path[0]==="content"?[...a,...d.path.slice(1)]:d.path}))):m}let u={...s,name:t,label:n,placement:o},l=[...this.data.contents,u];return new ke({...this.data,contents:l},[...this.extensions,c])}tab(t,n,r){return this.place(t,n,r,"main")}aside(t,n,r){return this.place(t,n,r,"aside")}build(){let t=["views","0"];Ce(this.data.name,[...t,"name"]),Ce(this.data.object,[...t,"object"]);let n=_.safeParse(this.data);if(!n.success)throw h$1.fromZodErrors(n.error.issues.map(r=>({path:[...t,...r.path.map(String)],message:r.message})));return this.data.contents.forEach((r,o)=>{let a=[...t,"contents",String(o)];Ce(r.name,[...a,"name"]),r.type==="form"&&r.groups.forEach((c,u)=>Ce(c.name,[...a,"groups",String(u),"name"])),(r.type==="custom"?this.extensions[o]?.requiresRecord:r.type==="collection"?ze(r.source).kind!=="object":true)&&Rt(r.name,this.data.context,a);}),{kind:"view",definition:be(this.data,t)}}};a(ke,"ViewBuilder");var un=ke;function ge(e,t){return new un({name:e,label:t,object:void 0,context:"record",contents:[]})}a(ge,"detailView");function ye(e,t){return new un({name:e,label:t,object:void 0,context:"collection",contents:[]})}a(ye,"listView");function hT(e){return Ce(e,["relationProperty"]),{relationProperty:e}}a(hT,"relationProperty");var Ct=class Ct{constructor(t,n){this.data=be(t,["content"]),this.extension=n===void 0?void 0:Object.freeze({name:n.name,requiresRecord:n.requiresRecord,parameters:n.parameters});}set(t){return new Ct({...this.data,...t},this.extension)}icon(t){return this.set({icon:t})}object(t){return this.data.type==="forms"?this.set({objectName:t}):this.set({source:{object:t}})}related(t){return this.set({source:{relation:t}})}relatedFrom(t,n){return this.set({source:{object:t,relation:n}})}layout(t){let{layout:n,groupByAttribute:r,columnSizing:o,kanbanColumnOrder:a,kanbanColumnVisibility:s,kanbanPinnedColumns:c,...u}={...this.data,layout:void 0,groupByAttribute:void 0,columnSizing:void 0,kanbanColumnOrder:void 0,kanbanColumnVisibility:void 0,kanbanPinnedColumns:void 0};return new Ct({...u,...t},this.extension)}table(){return this.layout({layout:"table"})}list(){return this.layout({layout:"list"})}kanban(t){return this.layout({layout:"kanban",groupByAttribute:t})}columns(...t){return this.set({columns:t})}filter(t){return this.set({filters:t})}sort(t,n="asc"){let o=[..."sorts"in this.data&&Array.isArray(this.data.sorts)?this.data.sorts:[],{attribute:t,direction:n}];return this.set({sorts:o})}actions(...t){return this.set({actions:t})}openMode(t){return this.set({openMode:t})}createMode(t){return this.set({createMode:t})}visibility(t){return this.set({visibility:t})}descriptionAttribute(t){return this.set({descriptionAttribute:t})}displayAttributes(...t){return this.set({displayAttributes:t})}columnSizing(t){return this.set({columnSizing:t})}kanbanColumnOrder(...t){return this.set({kanbanColumnOrder:t})}kanbanColumnVisibility(t){return this.set({kanbanColumnVisibility:t})}kanbanPinnedColumns(...t){return this.set({kanbanPinnedColumns:t})}formColumns(t){return this.set({formColumns:t})}density(t){return this.set({density:t})}titleAttribute(t){return this.set({titleAttribute:t})}allowUpload(t){return this.set({allowUpload:t})}allowRemove(t){return this.set({allowRemove:t})}hideAttachments(t){return this.set({hideAttachments:t})}relations(...t){return this.set({relations:t})}build(){let t=Gr(this.data,["content"]);if(this.extension&&t.type==="custom"){let n=this.extension.parameters.safeParse(be(t.parameters??{},["content","parameters"]));if(!n.success)throw h$1.fromZodErrors(n.error.issues.map(r=>({path:["content","parameters",...r.path.map(String)],message:r.message})))}return t}};a(Ct,"ContentBuilder");var ce=Ct,We=class We{constructor(t,n,r,o={}){this.data=be({name:t,label:n,fields:r,...o},["group"]);}field(t,n){let{name:r,label:o,fields:a,...s}=this.data;return new We(r,o,[...a,{attribute:t,...n}],s)}fields(...t){let{name:n,label:r,fields:o,...a}=this.data;return new We(n,r,[...o,...t.map(s=>({attribute:s}))],a)}description(t){return new We(this.data.name,this.data.label,this.data.fields,{...this.presentation(),description:t})}collapsible(t=false){return new We(this.data.name,this.data.label,this.data.fields,{...this.presentation(),collapsible:true,collapsed:t})}presentation(){let{name:t,label:n,fields:r,...o}=this.data;return o}build(){Ce(this.data.name,["group","name"]);try{Gr({type:"form",groups:[this.data]},["group"]);}catch(t){throw t instanceof h$1?new h$1(t.message,t.errors.map(n=>({...n,path:n.path[1]==="groups"?["group",...n.path.slice(3)]:n.path}))):t}return be(this.data,["group"])}};a(We,"GroupBuilder");var Yr=We;function he(e,t){return new Yr(e,t,[])}a(he,"group");function Yu(){return new ce({type:"collection"})}a(Yu,"collection");function Hu(...e){let t=e.map(n=>"build"in n?n.build():n);return new ce({type:"form",groups:t})}a(Hu,"form");function Ju(){return new ce({type:"activity"})}a(Ju,"activity");function Qu(e){return new ce({type:"richtext",attribute:e})}a(Qu,"richtext");function Zu(){return new ce({type:"documents"})}a(Zu,"documents");function Xu(){return new ce({type:"forms"})}a(Xu,"forms");function el(...e){return new ce({type:"emails",emailAttributes:e})}a(el,"emails");function tl(...e){return new ce({type:"meetings",emailAttributes:e})}a(tl,"meetings");function nl(e,t){if(typeof e!="object"||e===null||typeof e.name!="string")throw new h$1("Expected registered extension declaration",[{path:["content","extension"],message:"Expected registered extension declaration"}]);let n=at({type:"custom",extension:e.name,parameters:t},["content"]);if(n.type!=="custom")throw new h$1("Expected custom content",[]);let r=new ce({...n,extension:e.name},e);return r.build(),r}a(nl,"custom");var N={collection:Yu,form:Hu,activity:Ju,richtext:Qu,documents:Zu,forms:Xu,emails:el,meetings:tl,custom:nl};function rl(e){if(!/^[a-z][a-z0-9-]*[a-z0-9]$|^[a-z]$/.test(e))throw new Error(`Invalid flag name "${e}". Flag names must be kebab-case (e.g., "architect-mode", "ai-features").`)}a(rl,"validateFlagName");var Xr=class Xr{constructor(t,n,r){rl(t),this.flag={name:t,valueType:n,defaultValue:r,allowedLevels:["global","tenant","user"]};}label(t){return this.flag.label=t,this}description(t){return this.flag.description=t,this}category(t){return this.flag.category=t,this}system(){return this.flag.system=true,this}tenantScoped(){return this.flag.allowedLevels=["global","tenant"],this}globalOnly(){return this.flag.allowedLevels=["global"],this}allowedLevels(t){return this.flag.allowedLevels=[...t],this}build(){if(!this.flag.label?.trim())throw new Error(`Flag "${this.flag.name}" must have a label. Use .label("Human-readable label").`);return {...this.flag,allowedLevels:[...this.flag.allowedLevels||[]]}}};a(Xr,"BaseFlagBuilder");var st=Xr,ei=class ei extends st{constructor(t){super(t,"boolean",false);}defaultValue(t){return this.flag.defaultValue=t,this}enabledByDefault(){return this.flag.defaultValue=true,this}};a(ei,"BooleanFlagBuilder");var Hr=ei,ti=class ti extends st{constructor(t){super(t,"string","");}defaultValue(t){return this.flag.defaultValue=t,this}};a(ti,"StringFlagBuilder");var Jr=ti,ni=class ni extends st{constructor(t){super(t,"number",0);}defaultValue(t){return this.flag.defaultValue=t,this}};a(ni,"NumberFlagBuilder");var Qr=ni,ri=class ri extends st{constructor(t,n){super(t,"json",n);}defaultValue(t){return this.flag.defaultValue=t,this}};a(ri,"JsonFlagBuilder");var Zr=ri;function il(e){return new Hr(e)}a(il,"booleanFlag");function ol(e){return new Jr(e)}a(ol,"stringFlag");function al(e){return new Qr(e)}a(al,"numberFlag");function sl(e,t){return new Zr(e,t)}a(sl,"jsonFlag");function ii(e){return new r("feature flag",e,`Flag "${e}" is already registered. Each flag name must be unique.`)}a(ii,"duplicateFlagError");function oi(e){return {...e,allowedLevels:[...e.allowedLevels]}}a(oi,"cloneFlagDefinition");var ai=class ai{constructor(){this.flags=new Map;}register(t){if(this.flags.has(t.name))throw ii(t.name);this.flags.set(t.name,oi(t));}registerAll(t){let n=new Set;for(let r of t){if(this.flags.has(r.name)||n.has(r.name))throw ii(r.name);n.add(r.name);}for(let r of t)this.register(r);}get(t){let n=this.flags.get(t);return n?oi(n):void 0}getOrThrow(t){let n=this.get(t);if(!n)throw new c$2("Feature flag",t,void 0,`Flag "${t}" is not registered. Available flags: ${this.listNames().join(", ")}`);return n}has(t){return this.flags.has(t)}list(){return Array.from(this.flags.values(),oi)}listNames(){return Array.from(this.flags.keys())}unregister(t){return this.flags.delete(t)}clear(){this.flags.clear();}get size(){return this.flags.size}};a(ai,"FlagRegistry");var vt=ai,cl=new vt;function ul(){return new vt}a(ul,"createFlagRegistry");function ln(){return {global:new Map,tenant:new Map,user:new Map}}a(ln,"emptyOverrides");function ll(e,t){return e.expiresAt===void 0||e.expiresAt.getTime()>t}a(ll,"isActiveOverride");function si(e,t){let n=new Map;for(let r of e){if(!ll(r,t))continue;let o=r.flagName;n.has(o)||n.set(o,r);}return n}a(si,"indexOverrides");var ci=class ci{constructor(t){this.repository=t.repository,this.registry=t.registry,this.staticDefaults=new Map(t.staticDefaults?.map(n=>[n.name,n.value])??[]);}async resolveAll(t={}){let n=this.collectFlagNames(),r=this.repository&&n.size>0?await this.getAllOverrides(t,[...n]):ln();return this.resolveNames(n,r,t)}resolveAllStatic(){return this.resolveNames(this.collectFlagNames(),ln(),{})}collectFlagNames(){let t=new Set;for(let n of this.registry.listNames())t.add(n);for(let n of this.staticDefaults.keys())t.add(n);return t}resolveNames(t,n,r){let o=new Map;for(let a of t)o.set(a,this.resolveValue(a,n,r));return o}async resolve(t,n={}){let r=this.repository?await this.getAllOverrides(n,[t]):ln();return this.resolveWithSource(t,r,n)}async isEnabled(t,n={}){return (await this.resolve(t,n)).value===true}async getValue(t,n={}){return (await this.resolve(t,n)).value}async setOverride(t,n,r,o={}){if(!this.repository)throw new b$1("Cannot set override: no FeatureFlagsRepository configured. Add featureFlags to your DatabaseAdapter to enable runtime overrides.",a$2.CONFIGURATION_REQUIRED);let a=this.registry.get(t);if(a&&!a.allowedLevels.includes(n)){let s=`Flag "${t}" does not allow ${n}-level overrides. Allowed levels: ${a.allowedLevels.join(", ")}`;throw new h$1(s,[{path:["level"],message:s}])}if(a?.system){let s=`Flag "${t}" is a system flag and cannot be overridden via API.`;throw new h$1(s,[{path:["flagName"],message:s}])}await this.repository.setOverride({flagName:t,level:n,value:r,targetId:o.targetId,expiresAt:o.expiresAt,createdBy:o.createdBy});}async deleteOverride(t,n,r){if(!this.repository)throw new b$1("Cannot delete override: no FeatureFlagsRepository configured.",a$2.CONFIGURATION_REQUIRED);await this.repository.deleteOverride(t,n,r);}async getAllOverrides(t,n){if(!this.repository)return ln();let[r,o,a]=await Promise.all([this.repository.getOverrides({level:"global",flagNames:n}),t.tenantId?this.repository.getOverrides({level:"tenant",targetId:t.tenantId,flagNames:n}):Promise.resolve([]),t.userId?this.repository.getOverrides({level:"user",targetId:t.userId,flagNames:n}):Promise.resolve([])]),s=Date.now();return {global:si(r,s),tenant:si(o,s),user:si(a,s)}}resolveValue(t,n,r){return this.resolveWithSource(t,n,r).value}resolveWithSource(t,n,r){let o=this.registry.get(t),a=o?.allowedLevels??["global","tenant","user"];if(r.userId&&a.includes("user")){let s=n.user.get(t);if(s)return {name:t,value:s.value,source:"user",sourceId:r.userId}}if(r.tenantId&&a.includes("tenant")){let s=n.tenant.get(t);if(s)return {name:t,value:s.value,source:"tenant",sourceId:r.tenantId}}if(a.includes("global")){let s=n.global.get(t);if(s)return {name:t,value:s.value,source:"global"}}return this.staticDefaults.has(t)?{name:t,value:this.staticDefaults.get(t),source:"default"}:{name:t,value:o?.defaultValue??void 0,source:"default"}}};a(ci,"FlagService");var dn=ci;function dl(e){return new dn(e)}a(dl,"createFlagService");var fa=Symbol("stndrds.native-object");function li(e){return Object.defineProperty(e,fa,{value:true,enumerable:false}),e}a(li,"markNativeDefinition");var pi=class pi extends It{build(){return li(super.build())}};a(pi,"NativeObjectBuilder");var ui=pi;function Ae(e){return new ui(e)}a(Ae,"nativeObject");function di(e){return e[fa]===true}a(di,"isNativeDefinition");function mi(e){let t=structuredClone(e);return di(e)?li(t):t}a(mi,"cloneObjectDefinition");var bi=class bi{constructor(){this.objects=new Map;}register(t){let r$1=(Array.isArray(t)?t:[t]).map(a=>"build"in a&&typeof a.build=="function"?a.build():a),o=new Set;for(let a of r$1){if(this.validate(a),o.has(a.name))throw new r("object",a.name,`[NativeObjectRegistry] Duplicate object name "${a.name}" within a single register() batch.`);o.add(a.name);}for(let a of r$1)this.objects.set(a.name,mi(a));return this}validate(t){if(!t.system){let n=`[NativeObjectRegistry] Cannot register object "${t.name}" (id: ${t.id}): missing system flag.
|
|
3
|
+
Native objects must have system=true. Did you call .runtime() on the builder? Remove that call \u2014 objects are system:true by default.`;throw new h$1(n,[])}if(b(t.name)&&!di(t))throw new s(t.name,"registry");if(this.objects.has(t.name)){let n=this.objects.get(t.name),r$1=`[NativeObjectRegistry] Duplicate object name "${t.name}":
|
|
4
4
|
- Existing: "${n?.label}" (id: ${n?.id})
|
|
5
5
|
- New: "${t.label}" (id: ${t.id})
|
|
6
|
-
Please use unique names for each native object.`;throw new r("object",t.name,r$1)}}getByName(t){let n=this.objects.get(t);return n?
|
|
7
|
-
Available objects: ${this.listNames().join(", ")}`;throw new c$2("Native object",t,a$2.OBJECT_NOT_FOUND,r)}return n}getAll(){return Array.from(this.objects.values(),
|
|
8
|
-
`)}debug(t){let n=this.summary();return t?.(n),n}};a(
|
|
6
|
+
Please use unique names for each native object.`;throw new r("object",t.name,r$1)}}getByName(t){let n=this.objects.get(t);return n?mi(n):void 0}getByNameOrThrow(t){let n=this.getByName(t);if(!n){let r=`[NativeObjectRegistry] Native object "${t}" not found.
|
|
7
|
+
Available objects: ${this.listNames().join(", ")}`;throw new c$2("Native object",t,a$2.OBJECT_NOT_FOUND,r)}return n}getAll(){return Array.from(this.objects.values(),mi)}listNames(){return Array.from(this.objects.keys())}has(t){return this.objects.has(t)}get size(){return this.objects.size}clear(){this.objects.clear();}summary(){let t=this.getAll();return [`[NativeObjectRegistry] ${this.size} native object(s) registered:`,...t.map(n=>` - ${n.name}: "${n.label}" (${n.attributes.length} attributes)`)].join(`
|
|
8
|
+
`)}debug(t){let n=this.summary();return t?.(n),n}};a(bi,"NativeObjectRegistryClass");var fi=bi,KT=new fi;var ba=new WeakSet;function W(e){return ba.add(e.definition),e}a(W,"markSystemView");function ga(e){return typeof e=="object"&&e!==null&&ba.has(e)}a(ga,"isSystemViewDefinition");var ya=`## Overview
|
|
9
9
|
|
|
10
10
|
Describe in one or two sentences what this skill does and the outcome it produces. The agent reads this page when it uses the skill \u2014 write instructions for the agent, not documentation for people.
|
|
11
11
|
|
|
@@ -36,15 +36,15 @@ Show at least one concrete example of the skill applied well.
|
|
|
36
36
|
|
|
37
37
|
- Never \u2026
|
|
38
38
|
- Do not \u2026
|
|
39
|
-
`,
|
|
39
|
+
`,fl=Ae({name:"skill",label:"Skill"}).sealed().icon("book-open").order(Number.MAX_SAFE_INTEGER).pluralLabel("Skills").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
40
40
|
{{ description }}
|
|
41
|
-
{{ content }}`).attribute(S({name:"name",label:"Name"}).maxLength(SKILL_NAME_MAX_LENGTH).required()).attribute(S({name:"description",label:"Description"}).multiline().maxLength(SKILL_DESCRIPTION_MAX_LENGTH).required().placeholder('What this skill does and when to use it \u2014 e.g. "Drafts replies to customer complaints. Use when asked to answer an unhappy customer."')).attribute(
|
|
41
|
+
{{ content }}`).attribute(S({name:"name",label:"Name"}).maxLength(SKILL_NAME_MAX_LENGTH).required()).attribute(S({name:"description",label:"Description"}).multiline().maxLength(SKILL_DESCRIPTION_MAX_LENGTH).required().placeholder('What this skill does and when to use it \u2014 e.g. "Drafts replies to customer complaints. Use when asked to answer an unhappy customer."')).attribute(je({name:"content",label:"Content"}).defaultValue(ya)).build(),bl=W(ge("skill-detail","Skill").for("skill").default().tab("content","Content",N.richtext("content").titleAttribute("name")).tab("files","Files",N.documents()).tab("activity","Activity",N.activity()).aside("details","Details",N.form(he("details","Details").fields("name","description"))).build()),gl=W(ye("skill-list","Skills").for("skill").default().tab("workspace","Skills",N.collection().object("skill").list().icon("list").visibility("workspace").columns("name","description").descriptionAttribute("description").displayAttributes("createdBy","updatedAt").sort("name")).tab("mine","My skills",N.collection().object("skill").list().icon("lock").visibility("private").columns("name","description").descriptionAttribute("description").displayAttributes("createdBy","updatedAt").sort("name")).build());var Al=Ae({name:"memory",label:"Memory"}).sealed().icon("database").order(Number.MAX_SAFE_INTEGER).pluralLabel("Memories").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
42
42
|
{{ description }}
|
|
43
|
-
{{ content }}`).migration(2,e=>e.changeType("content","text","richtext")).attribute(S({name:"name",label:"Name"}).maxLength(MEMORY_NAME_MAX_LENGTH).required()).attribute(S({name:"description",label:"Description"}).multiline().maxLength(MEMORY_DESCRIPTION_MAX_LENGTH).required()).attribute(
|
|
44
|
-
{{ description }}`).attribute(S({name:"name",label:"Name"}).required()).attribute(S({name:"description",label:"Description"}).multiline()).build(),
|
|
45
|
-
{{ description }}`).attribute(S({name:"name",label:"Name"}).required()).attribute(S({name:"description",label:"Description"}).multiline()).attribute(fe({name:"kind",label:"Kind"}).options([{value:"web",label:"Web",color:"blue"},{value:"presentation",label:"Presentation",color:"purple"},{value:"document",label:"Document",color:"sky"},{value:"spreadsheet",label:"Spreadsheet",color:"green"},{value:"image",label:"Image",color:"pink"},{value:"code",label:"Code",color:"slate"},{value:"other",label:"Other",color:"gray"}]).required()).attribute(fe({name:"retention",label:"Retention"}).options([{value:"ephemeral",label:"Ephemeral",color:"gray"},{value:"conversation",label:"Conversation",color:"blue"},{value:"persistent",label:"Persistent",color:"green"}]).defaultValue("conversation").required()).attribute(
|
|
43
|
+
{{ content }}`).migration(2,e=>e.changeType("content","text","richtext")).attribute(S({name:"name",label:"Name"}).maxLength(MEMORY_NAME_MAX_LENGTH).required()).attribute(S({name:"description",label:"Description"}).multiline().maxLength(MEMORY_DESCRIPTION_MAX_LENGTH).required()).attribute(je({name:"content",label:"Content"})).attribute(fe({name:"kind",label:"Kind"}).options([{value:"fact",label:"Fact"},{value:"preference",label:"Preference"},{value:"feedback",label:"Feedback"},{value:"reference",label:"Reference"}])).attribute(ot({name:"subjects",label:"Subjects"}).toAny().many()).attribute(ot({name:"links",label:"Links"}).to("memory").many()).attribute(fe({name:"source",label:"Source"}).options([{value:"explicit",label:"Saved by an agent"},{value:"extracted",label:"Extracted from a session"},{value:"corroborated",label:"Corroborated across users"},{value:"curated",label:"Curated by Dreamer"}])).attribute(se({name:"validFrom",label:"Valid from"}).includeTime()).attribute(se({name:"invalidAt",label:"Invalid at"}).includeTime()).attribute(ot({name:"supersededBy",label:"Superseded by"}).to("memory")).attribute(S({name:"provenance",label:"Provenance"}).multiline()).attribute(fe({name:"reviewState",label:"Review state"}).options([{value:"needs_review",label:"Needs review"},{value:"skill_candidate",label:"Skill candidate"}])).attribute(S({name:"reviewReason",label:"Review reason"}).multiline()).attribute(se({name:"curatedAt",label:"Curated at"}).includeTime()).attribute(se({name:"reviewAfter",label:"Review after"}).includeTime()).attribute(S({name:"curationFingerprint",label:"Curation fingerprint"})).build(),ha={combinator:"and",rules:[{attribute:"invalidAt",operator:"is_empty",value:null},{attribute:"reviewState",operator:"is_empty",value:null}]},xl=W(ge("memory-detail","Memory").for("memory").default().tab("content","Content",N.richtext("content").titleAttribute("name")).aside("details","Details",N.form(he("details","Details").fields("description","kind","source","provenance","reviewState","reviewReason","validFrom","invalidAt","supersededBy","curatedAt","reviewAfter","subjects","links"))).build()),Tl=W(ye("memory-list","Memories").for("memory").default().tab("workspace","Memories",N.collection().object("memory").list().icon("list").visibility("workspace").columns("name","kind","description","createdAt").descriptionAttribute("description").displayAttributes("kind","subjects","createdAt").filter(ha).sort("name")).tab("mine","My memories",N.collection().object("memory").list().icon("lock").visibility("private").columns("name","kind","description","createdAt").descriptionAttribute("description").displayAttributes("kind","subjects","createdAt").filter(ha).sort("name")).tab("review","To review",N.collection().object("memory").table().icon("question-circle").columns("name","reviewState","reviewReason","updatedAt").filter({combinator:"and",rules:[{attribute:"invalidAt",operator:"is_empty",value:null},{attribute:"reviewState",operator:"is_not_empty",value:null}]}).sort("updatedAt","desc")).tab("history","History",N.collection().object("memory").table().icon("archive").columns("name","kind","invalidAt","supersededBy").filter({combinator:"and",rules:[{attribute:"invalidAt",operator:"is_not_empty",value:null}]}).sort("invalidAt","desc")).build());var ct="drives",wl=Ae({name:ct,label:"Drive"}).sealed().icon("folder").hidden().pluralLabel("Drives").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
44
|
+
{{ description }}`).attribute(S({name:"name",label:"Name"}).required()).attribute(S({name:"description",label:"Description"}).multiline()).build(),Sl=W(ge("drive-detail","Drive").for(ct).default().tab("documents","Documents",N.documents()).aside("details","Details",N.form(he("details","Details").field("description"))).build()),Il=W(ye("drive-list","Drives").for(ct).default().tab("workspace","Shared",N.collection().object(ct).table().icon("users").visibility("workspace").columns("name","description","updatedAt").sort("name")).tab("mine","My drives",N.collection().object(ct).table().icon("lock").visibility("private").columns("name","description","updatedAt").sort("name")).build());var ut="artifact",Cl=Ae({name:ut,label:"Artifact"}).sealed().icon("package").pluralLabel("Artifacts").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
45
|
+
{{ description }}`).attribute(S({name:"name",label:"Name"}).required()).attribute(S({name:"description",label:"Description"}).multiline()).attribute(fe({name:"kind",label:"Kind"}).options([{value:"web",label:"Web",color:"blue"},{value:"presentation",label:"Presentation",color:"purple"},{value:"document",label:"Document",color:"sky"},{value:"spreadsheet",label:"Spreadsheet",color:"green"},{value:"image",label:"Image",color:"pink"},{value:"code",label:"Code",color:"slate"},{value:"other",label:"Other",color:"gray"}]).required()).attribute(fe({name:"retention",label:"Retention"}).options([{value:"ephemeral",label:"Ephemeral",color:"gray"},{value:"conversation",label:"Conversation",color:"blue"},{value:"persistent",label:"Persistent",color:"green"}]).defaultValue("conversation").required()).attribute(sn({name:"currentRevision",label:"Current revision"}).integer().min(1)).attribute(se({name:"expiresAt",label:"Expires at"}).includeTime().hidden()).attribute(S({name:"sourceSessionId",label:"Source session"}).hidden()).attribute(S({name:"sourceMessageId",label:"Source message"}).hidden()).attribute(S({name:"initialToolCallId",label:"Initial tool call"}).hidden()).attribute(la({name:"versions",label:"Versions"}).qualifyWith(sn({name:"revision",label:"Revision"}).integer().min(1).required(),S({name:"toolCallId",label:"Tool call"}).hidden(),S({name:"sourceFileId",label:"Source file"}).hidden(),S({name:"previewFileId",label:"Preview file"}).hidden(),S({name:"fileIds",label:"File manifest"}).hidden(),S({name:"entrypoint",label:"Entrypoint"}).hidden(),S({name:"sourceMessageId",label:"Source message"}).hidden(),S({name:"artifactName",label:"Artifact name"}).hidden(),S({name:"artifactDescription",label:"Artifact description"}).hidden(),S({name:"artifactKind",label:"Artifact kind"}).hidden(),S({name:"displayMode",label:"Display mode"}).hidden(),S({name:"displayInteraction",label:"Display interaction"}).hidden(),S({name:"displaySize",label:"Display size"}).hidden(),sn({name:"displayAspectRatio",label:"Display aspect ratio"}).hidden())).build(),Aa={name:"artifact_preview",requiresRecord:true,parameters:z.object({}).strict()},vl=W(ge("artifact-detail","Artifact").for(ut).default().tab("preview","Preview",N.custom(Aa,{})).tab("versions","Versions",N.documents().allowUpload(false).allowRemove(false).hideAttachments(true)).tab("activity","Activity",N.activity()).aside("details","Details",N.form(he("details","Details").field("description",{readOnly:true}).field("kind",{readOnly:true}).field("retention",{readOnly:true}).field("currentRevision",{readOnly:true}).field("createdBy",{readOnly:true}).field("updatedAt",{readOnly:true}))).build()),Nl=W(ye("artifact-list","Artifacts").for(ut).default().tab("mine","My artifacts",N.collection().object(ut).list().icon("lock").visibility("private").actions().columns("name","kind","currentRevision","updatedAt").descriptionAttribute("description").displayAttributes("kind","currentRevision","updatedAt").sort("updatedAt","desc")).tab("workspace","Workspace",N.collection().object(ut).list().icon("list").visibility("workspace").actions().columns("name","kind","currentRevision","updatedAt").descriptionAttribute("description").displayAttributes("kind","currentRevision","updatedAt").sort("updatedAt","desc")).build());var lt="meeting",C={title:"title",description:"description",location:"location",startsAt:"startsAt",endsAt:"endsAt",isAllDay:"isAllDay",status:"status",organizerAddress:"organizerAddress",organizerName:"organizerName",conferenceProvider:"conferenceProvider",conferenceJoinUrl:"conferenceJoinUrl",htmlLink:"htmlLink",participants:"participants",providerEventId:"providerEventId",icalUid:"icalUid",recurringEventId:"recurringEventId",connectionId:"connectionId",recordingOverride:"recordingOverride",endedAnnouncedAt:"endedAnnouncedAt",summary:"summary",transcript:"transcript",linkedRecords:"linkedRecords"},Ta="meeting-list",wa="calendar-sync",Sa="meeting-detail",xa=[C.title,C.startsAt,C.endsAt,C.status],El=Ae({name:lt,label:"Meeting"}).sealed().hidden().metadata({platformOwned:{editable:[C.linkedRecords],source:wa}}).icon("calendar").pluralLabel("Meetings").labelExpression("{{ title }}").embeddingExpression(`{{ title }}
|
|
46
46
|
{{ description }}
|
|
47
47
|
{{ participants }}
|
|
48
|
-
{{ summary }}`).attribute(S({name:C.title,label:"Title"}).required()).attribute(
|
|
49
|
-
Available views: ${a}`)}getAll(){return Array.from(this.views.values()).flatMap(t=>Array.from(t.values(),
|
|
50
|
-
`)}debug(t){let n=this.summary();return t?.(n),n}throwDuplicate(t,n){let r$1=fi(t,n);throw new r("view",r$1,`[ViewRegistry] Duplicate view: "${n}" for object "${t}"`)}};a(gi,"ViewRegistry");var bi=gi,Dl=new bi;function Sa(e,t){if(t.suppressed)return null;let n=t.workspaceDefinition??t.sourceDefinition;return n===null?null:{...structuredClone(n),name:e}}a(Sa,"contentDefinition");function vt(e){let{name:t,...n}=e;return structuredClone(n)}a(vt,"storedContentDefinition");function Et(e){let t={main:0,aside:0};return {origin:"runtime",mainOrderCustomized:false,asideOrderCustomized:false,contents:Object.fromEntries(e.map(n=>[n.name,{sourceDefinition:null,workspaceDefinition:vt(n),suppressed:false,sourcePosition:null,workspacePosition:t[n.placement]++}]))}}a(Et,"workspaceViewAuthoring");function yi(e){let t=Object.entries(e.contents).flatMap(([n,r])=>{let o=Sa(n,r);return o?[{definition:o,...r}]:[]});return ["main","aside"].flatMap(n=>{let r=n==="main"?e.mainOrderCustomized:e.asideOrderCustomized;return t.filter(o=>o.definition.placement===n).sort((o,a)=>{let s=r?o.workspacePosition:o.sourcePosition,c=r?a.workspacePosition:a.sourcePosition;if(s!==null&&c!==null&&s!==c)return s-c;if(s!==null&&c===null)return -1;if(c!==null&&s===null)return 1;let u=o.sourcePosition??o.workspacePosition,l=a.sourcePosition??a.workspacePosition;return u!==null&&l!==null&&u!==l?u-l:u!==null&&l===null?-1:l!==null&&u===null?1:o.definition.name.localeCompare(a.definition.name)}).map(o=>o.definition)})}a(yi,"resolveViewContents");function Ia(e,t){return e.attributes.find(n=>n.name===t&&n.type==="relation")}a(Ia,"findRelationAttribute");function hi(e,t){return e.targets.some(n=>n.object===t||n.object===ae)}a(hi,"relationAcceptsObject");function Ra(e,t=[e.name,"targets"]){if(e.targets.length!==1||e.targets[0].object==="*"){let n=`Relation "${e.name}" requires one concrete collection target`;throw new h$1(n,[{path:t,message:n}])}return e.targets[0].object}a(Ra,"requireSingleRelationTarget");var Ol=new Map(d().map(e=>[e.name,e]));function ue(e,t){throw new h$1(t,[{path:e,message:t}])}a(ue,"reject");function _e(e,t){e.trim().length===0&&ue(t,"API name must not be empty");}a(_e,"requireName");function Ca(e,t,n){let r$1=new Map;return e.forEach((o,a)=>{if(_e(o.name,[...n,String(a),"name"]),r$1.has(o.name))throw new r(t,o.name);r$1.set(o.name,o);}),r$1}a(Ca,"indexUnique");function ne(e,t,n,r,o){if(_e(t,n),!e)return;let a=e.attributes?.get(t)??Ol.get(t);if(!a){if(!e.attributes)return;let s=[...e.attributes.keys()].slice(0,30),c=s.length===0?`Object "${e.name}" has no attributes yet.`:`Attributes of "${e.name}": ${s.join(", ")}`;ue(n,`Unknown attribute "${e.name}.${t}". ${c}${o?.()??""}`);}return r&&a.type!==r&&ue(n,`Attribute "${e.name}.${t}" must have type ${r}`),a}a(ne,"requireAttribute");function Ai(e){let t=e.mode??"published",n=new Map;e.objects.forEach((b,g)=>{if(_e(b.name,["objects",String(g),"name"]),n.has(b.name))throw new r("object",b.name);n.set(b.name,{name:b.name,attributes:Ca(b.attributes,"attribute",["objects",String(g),"attributes"])});});let r$1=new Set;(e.reservedObjects??[]).forEach((b,g)=>{let y=["reservedObjects",String(g)];_e(b,y),!n.has(b)&&(t!=="draft"&&ue(y,`Unresolved reserved object "${b}"`),r$1.add(b),n.set(b,{name:b}));});let o=Ca(e.extensions??[],"extension",["extensions"]);function a$1(b,g){_e(b,g);let y=n.get(b);return y||ue(g,`Unknown object "${b}"`),y}a(a$1,"resolveObject");function s(b){let g=[];for(let[y,A]of n)if(y!==b)for(let h of A.attributes?.values()??[])h.type==="relation"&&hi(h,b)&&g.push(`relatedFrom("${y}", "${h.name}")`);return g.sort().slice(0,3)}a(s,"inverseAddresses");let c=e.asideRule??"enforce",u=t==="draft"?X$1({asideRule:c}):Y({asideRule:c}),l=new Map,m=new Map;return {views:e.views.map((b,g)=>{let y=["views",String(g)],A=u.safeParse(b);if(!A.success)throw new h$1("Invalid content view",A.error.issues.map(O=>({path:[...y,...O.path.map(String)],message:O.message,code:O.code})));let h=A.data;_e(h.name,[...y,"name"]);let j=a$1(h.object,[...y,"object"]),_=l.get(h.object)??new Set;if(_.has(h.name))throw new r("view",`${h.object}.${h.name}`);if(_.add(h.name),l.set(h.object,_),h.default){let O=m.get(h.object)??new Set;if(O.has(h.context))throw new r("default view",`${h.object}.${h.context}`);O.add(h.context),m.set(h.object,O);}return h.contents.forEach((O,B)=>{let Se=[...y,"contents",String(B)];_e(O.name,[...Se,"name"]),kl(O,Se,j,h.context,o,a$1,s);}),h}),unresolvedObjects:[...r$1].sort()}}a(Ai,"validateContentViewCatalogue");function kl(e,t,n,r,o,a$1,s){function c(){It(e.name,r,t);}if(a(c,"requireRecord"),e.type==="custom"){let u=o.get(e.extension);u||ue([...t,"extension"],`Unknown extension "${e.extension}"`),u.requiresRecord&&c();let l=u.parameters.safeParse(structuredClone(e.parameters??{}));if(!l.success)throw new h$1("Invalid extension parameters",l.error.issues.map(m=>({path:[...t,"parameters",...m.path.map(String)],message:m.message,code:m.code})));return}if(e.type==="collection"){let u=qe(e.source),l,m;if(u.kind==="object")l=a$1(u.object,[...t,"source","object"]);else if(u.kind==="related"){c();let d=[...t,"source","relation"],b=a(()=>{if(!n)return "";let y=s(n.name);return y.length===0?"":`. Records pointing at "${n.name}" are addressed from the other side: ${y.join(", ")}`},"hint"),g=ne(n,u.relation,d,"relation",b);g?.type==="relation"&&(m=g,l=a$1(Ra(g,d),d));}else {c(),l=a$1(u.object,[...t,"source","object"]);let d=[...t,"source","relation"],b=ne(l,u.relation,d,"relation");if(b?.type==="relation"&&n&&!hi(b,n.name)){let g=b.targets.map(y=>`"${y.object}"`).join(", ");ue(d,`Relation "${u.object}.${u.relation}" targets ${g}, not "${n.name}"`);}e.filters?.combinator==="or"&&ue([...t,"filters","combinator"],`Collection "${e.name}" addresses "${u.object}" from the far side, so its filters must use the "and" combinator`);}e.columns?.forEach((d,b)=>{let g=[...t,"columns",String(b)];if(typeof d=="string"){ne(l,d,g);return}let y=[...g,"relationProperty"];m||ue(y,"Relation property columns require a relation source"),m.properties?.definitions.some(A=>A.name===d.relationProperty)||ue(y,`Unknown relation property "${d.relationProperty}"`);}),e.displayAttributes?.forEach((d,b)=>ne(l,d,[...t,"displayAttributes",String(b)])),e.sorts?.forEach((d,b)=>ne(l,d.attribute,[...t,"sorts",String(b),"attribute"])),e.filters?.rules.forEach((d,b)=>ne(l,d.attribute,[...t,"filters","rules",String(b),"attribute"])),e.descriptionAttribute!==void 0&&ne(l,e.descriptionAttribute,[...t,"descriptionAttribute"]),e.layout==="kanban"&&e.groupByAttribute!==void 0&&ne(l,e.groupByAttribute,[...t,"groupByAttribute"]);return}switch(c(),e.type){case "form":e.groups.forEach((u,l)=>{let m=[...t,"groups",String(l)];_e(u.name,[...m,"name"]),u.fields.forEach((d,b)=>ne(n,d.attribute,[...m,"fields",String(b),"attribute"]));});break;case "richtext":ne(n,e.attribute,[...t,"attribute"],"richtext"),e.titleAttribute!==void 0&&ne(n,e.titleAttribute,[...t,"titleAttribute"],"text");break;case "emails":case "meetings":e.emailAttributes.forEach((u,l)=>ne(n,u,[...t,"emailAttributes",String(l)],"text"));break;case "documents":e.relations?.forEach((u,l)=>ne(n,u,[...t,"relations",String(l)],"relation"));break;case "forms":e.objectName!==void 0&&a$1(e.objectName,[...t,"objectName"]);break;case "activity":break;default:ue(t,`Unknown content type: ${String(e)}`);}}a(kl,"validateContent");function xi(e){return structuredClone(e)}a(xi,"cloneFormDefinition");var Ti=class Ti{constructor(){this.forms=new Map;}register(t){let n=Array.isArray(t)?t:[t];for(let r$1 of n){if(this.forms.has(r$1.name))throw new r("form",r$1.name,`[FormRegistry] Duplicate form: "${r$1.name}"`);this.forms.set(r$1.name,xi(r$1));}return this}get(t){let n=this.forms.get(t);return n?xi(n):void 0}getAll(){return Array.from(this.forms.values(),xi)}listNames(){return Array.from(this.forms.keys())}};a(Ti,"FormRegistry");var Nt=Ti;var va=new Nt;function nS(e,t){return `${e}:${t}`}a(nS,"formatAgentStreamFrameId");function rS(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}}a(rS,"parseAgentStreamFrameId");var aS=204800,sS=256;function Si(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Si,"isRecord");function Ii(e,t){let n=Object.keys(e);return n.length===t.length&&n.every(r=>t.includes(r))}a(Ii,"hasExactKeys");function wi(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}a(wi,"isPositiveInteger");function Ea(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}a(Ea,"isNonNegativeInteger");function jl(e){return Si(e)&&Ii(e,["kind","startOffset","endOffset"])?(e.kind==="text"||e.kind==="reasoning")&&Ea(e.startOffset)&&Ea(e.endOffset)&&e.endOffset>=e.startOffset:false}a(jl,"isContentRange");function _l(e){if(!Si(e))return false;let t=e.content===void 0?["sequence","chunk"]:["sequence","content","chunk"];return Ii(e,t)&&wi(e.sequence)&&e.chunk!==void 0&&(e.content===void 0||jl(e.content))}a(_l,"isBatchItem");function Pl(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return}}a(Pl,"encodedSize");function cS(e){if(!(Si(e)&&Ii(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()===""||!wi(e.sequenceStart)||!wi(e.sequenceEnd)||!Array.isArray(e.items)||e.items.length===0||e.items.length>256||!e.items.every(_l))return false;let t=0;for(let r of e.items){if(r.sequence<=t)return false;t=r.sequence;}if(e.items[0]?.sequence!==e.sequenceStart||e.items.at(-1)?.sequence!==e.sequenceEnd)return false;let n=Pl(e);return n!==void 0&&n<=204800}a(cS,"isAgentUIMessageBatch");function Na(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)}`}}a(Na,"liveChannelKey");function dS(e){return e.sessionId?Na({kind:"architect-draft",scope:"session",sessionId:e.sessionId}):e.actorId?Na({kind:"architect-draft",scope:"actor",actorId:e.actorId}):null}a(dS,"architectDraftChannelKey");function Pe(e){try{return decodeURIComponent(e)}catch{return null}}a(Pe,"decodeLiveChannelPart");function Da(e){let t=e.split(":");if(t[0]==="workspace"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"workspace",tenantId:n}:null}if(t[0]==="object"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"object",objectId:n}:null}if(t[0]==="record"&&t.length===3&&t[1]&&t[2]){let n=Pe(t[1]),r=Pe(t[2]);return n&&r?{kind:"record",objectId:n,recordId:r}:null}if(t[0]==="view"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"view",viewId:n}:null}if(t[0]==="user"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"user",actorId:n}:null}if(t[0]==="architect-draft"&&t.length===3&&t[2]){let n=Pe(t[2]);return n?t[1]==="actor"?{kind:"architect-draft",scope:"actor",actorId:n}:t[1]==="session"?{kind:"architect-draft",scope:"session",sessionId:n}:null:null}if(t[0]==="conversation"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"conversation",sessionId:n}:null}return null}a(Da,"parseLiveChannelKey");var Ml={"record.patch":true,"record.deleted":true,"record.removed":true,"record.created":true,"view.projection.stale":true,"agent.session.patch":true,"notification.created":true,"notification.recipient.patch":true,"notification.count.patch":true,"notification.inbox.archived":true,"reflex.state.changed":true,"reflex.run.completed":true,"reflex.authoring.progress":true,"architect.draft.updated":true,"meeting.recording.patch":true,"wallet.state":true,"channel.revoked":true},Fl=Object.keys(Ml),Vl=["membership-unknown","sort-unknown","permissions-changed"],Bl=["permission-revoked","workspace-left","object-deleted"],Ll=["inboxState","workState","lockedAt","lockedByActorId","readAt","archivedAt","snoozedUntil","completedAt","dismissedAt","updatedAt"],$l=["type","objectId","recordId","recordVersion"],Ul=["type","objectId","recordId","recordVersion","record"],ql=["id","objectId","visibility","ownedBy","label","values","metadata","createdAt","updatedAt","createdBy","lastUpdatedBy","schemaVersion"],zl=["type","targetActorId","archivedCount","version","updatedAt"];function Wl(e){return typeof e=="string"&&Fl.includes(e)}a(Wl,"isLiveEventType");function bS(e){return U(e)&&Wl(e.type)?Gl(e.type,e):false}a(bS,"isLiveEventPayload");function Gl(e,t){if(!U(t))return false;switch(e){case "record.patch":return Xl(t);case "record.deleted":return ed(t);case "record.removed":return td(t);case "record.created":return rd(t);case "view.projection.stale":return id(t);case "agent.session.patch":return od(t);case "notification.created":return ud(t);case "notification.recipient.patch":return ld(t);case "notification.count.patch":return dd(t);case "notification.inbox.archived":return pd(t);case "reflex.state.changed":return hd(t);case "reflex.run.completed":return Ad(t);case "reflex.authoring.progress":return xd(t);case "architect.draft.updated":return gd(t);case "meeting.recording.patch":return wd(t);case "wallet.state":return Rd(t);case "channel.revoked":return Cd(t);default:return false}}a(Gl,"isLiveEventPayloadForType");function U(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(U,"isRecord");function H(e){return typeof e=="string"}a(H,"isString");function Dt(e){return H(e)&&e.length>0}a(Dt,"isNonEmptyString");function Ri(e){return e===null||H(e)}a(Ri,"isNullableString");function Kl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}a(Kl,"isVersion");function xe(e){if(!H(e))return false;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}a(xe,"isIsoDateString");function lt(e){return e===null||xe(e)}a(lt,"isNullableIsoDateString");function D(e,t){return H(e[t])}a(D,"hasString");function le(e,t){return Dt(e[t])}a(le,"hasNonEmptyString");function q(e,t){return Kl(e[t])}a(q,"hasVersion");function G(e,t){return xe(e[t])}a(G,"hasIsoDateString");function N(e,t,n){return !Object.hasOwn(e,t)||n(e[t])}a(N,"hasOptional");function dn(e,t){return Object.keys(e).every(n=>t.includes(n))}a(dn,"hasOnlyKeys");function J(e,t){return typeof e=="string"&&t.includes(e)}a(J,"isOneOf");function Yl(e){return J(e,ko)}a(Yl,"isNotificationKind");function Hl(e){return J(e,jo)}a(Hl,"isNotificationPriority");function Jl(e){return J(e,_o)}a(Jl,"isNotificationSensitivity");function Oa(e){return J(e,Po)}a(Oa,"isNotificationInboxState");function ka(e){return J(e,Mo)}a(ka,"isNotificationWorkState");function Ql(e){return U(e)&&D(e,"type")&&D(e,"id")}a(Ql,"isNotificationSubject");function Zl(e){return U(e)&&D(e,"fieldKey")&&Object.hasOwn(e,"value")&&q(e,"version")}a(Zl,"isRecordFieldPatch");function Xl(e){return e.type==="record.patch"&&D(e,"objectId")&&D(e,"recordId")&&q(e,"recordVersion")&&N(e,"label",H)&&N(e,"metadata",U)&&N(e,"fieldsWithheld",t=>t===true)&&Array.isArray(e.fieldPatches)&&e.fieldPatches.every(Zl)&&D(e,"updatedAt")}a(Xl,"isRecordPatchPayload");function ed(e){return e.type==="record.deleted"&&D(e,"objectId")&&D(e,"recordId")&&q(e,"recordVersion")&&D(e,"deletedAt")}a(ed,"isRecordDeletedPayload");function td(e){return e.type==="record.removed"&&dn(e,$l)&&D(e,"objectId")&&D(e,"recordId")&&q(e,"recordVersion")}a(td,"isRecordRemovedPayload");function nd(e){return U(e)&&dn(e,ql)&&D(e,"id")&&D(e,"objectId")&&J(e.visibility,["workspace","private"])&&Ri(e.ownedBy)&&(e.visibility==="workspace"&&e.ownedBy===null||e.visibility==="private"&&Dt(e.ownedBy))&&D(e,"label")&&U(e.values)&&N(e,"metadata",U)&&G(e,"createdAt")&&G(e,"updatedAt")&&N(e,"createdBy",H)&&N(e,"lastUpdatedBy",H)&&q(e,"schemaVersion")}a(nd,"isRecordLiveSnapshot");function rd(e){return e.type==="record.created"&&dn(e,Ul)&&D(e,"objectId")&&D(e,"recordId")&&q(e,"recordVersion")&&nd(e.record)&&e.record.id===e.recordId&&e.record.objectId===e.objectId}a(rd,"isRecordCreatedPayload");function id(e){return e.type==="view.projection.stale"&&D(e,"viewId")&&J(e.reason,Vl)}a(id,"isViewProjectionStalePayload");function od(e){return e.type==="agent.session.patch"&&D(e,"sessionId")&&U(e.patch)&&q(e,"version")&&D(e,"updatedAt")}a(od,"isAgentSessionPatchPayload");function ad(e){return U(e)&&D(e,"id")&&D(e,"tenantId")&&N(e,"senderActorId",H)&&N(e,"rootActorId",H)&&N(e,"triggeredByActorId",H)&&Yl(e.kind)&&D(e,"type")&&N(e,"subject",Ql)&&D(e,"title")&&N(e,"summary",H)&&U(e.payload)&&Hl(e.priority)&&Jl(e.sensitivity)&&N(e,"threadKey",H)&&N(e,"idempotencyKey",H)&&N(e,"expiresAt",xe)&&G(e,"createdAt")&&G(e,"updatedAt")}a(ad,"isLiveNotification");function sd(e){return U(e)&&D(e,"id")&&D(e,"tenantId")&&D(e,"notificationId")&&D(e,"recipientActorId")&&Oa(e.inboxState)&&ka(e.workState)&&N(e,"lockedAt",xe)&&N(e,"lockedByActorId",H)&&N(e,"readAt",xe)&&N(e,"archivedAt",xe)&&N(e,"snoozedUntil",xe)&&N(e,"completedAt",xe)&&N(e,"dismissedAt",xe)&&G(e,"createdAt")&&G(e,"updatedAt")}a(sd,"isLiveNotificationRecipient");function cd(e){return U(e)?Object.keys(e).every(t=>Ll.includes(t))&&N(e,"inboxState",Oa)&&N(e,"workState",ka)&&N(e,"lockedAt",lt)&&N(e,"lockedByActorId",Ri)&&N(e,"readAt",lt)&&N(e,"archivedAt",lt)&&N(e,"snoozedUntil",lt)&&N(e,"completedAt",lt)&&N(e,"dismissedAt",lt)&&N(e,"updatedAt",xe):false}a(cd,"isNotificationRecipientPatch");function ud(e){let t=ad(e.notification)?e.notification:null;return e.type==="notification.created"&&t!==null&&Array.isArray(e.recipients)&&e.recipients.length>0&&e.recipients.every(n=>sd(n)&&n.notificationId===t.id)&&q(e,"version")&&G(e,"updatedAt")}a(ud,"isNotificationCreatedPayload");function ld(e){return e.type==="notification.recipient.patch"&&D(e,"recipientId")&&D(e,"recipientActorId")&&cd(e.patch)&&q(e,"version")&&G(e,"updatedAt")}a(ld,"isNotificationRecipientPatchPayload");function dd(e){return e.type==="notification.count.patch"&&D(e,"targetActorId")&&q(e,"unread")&&q(e,"pendingWork")&&q(e,"version")&&G(e,"updatedAt")}a(dd,"isNotificationCountPatchPayload");function pd(e){return e.type==="notification.inbox.archived"&&dn(e,zl)&&le(e,"targetActorId")&&q(e,"archivedCount")&&q(e,"version")&&G(e,"updatedAt")}a(pd,"isNotificationInboxArchivedPayload");var md=["armed","disarmed"],fd=["authoring","compiling","replaying","promoted","failed"],bd=["promoted","lkg"];function gd(e){if(e.type!=="architect.draft.updated"||!U(e.receipt))return false;let t=e.receipt;return Array.isArray(t.operationIds)&&t.operationIds.every(Dt)&&U(t.revision)&&le(t.revision,"draftId")&&q(t.revision,"version")&&Array.isArray(t.changedTargets)&&t.changedTargets.every(n=>U(n)&&Dt(n.token)&&yd(n.target))}a(gd,"isArchitectDraftUpdatedPayload");function yd(e){if(!U(e))return false;let t=Object.keys(e);return t.every(n=>Dt(e[n]))?le(e,"viewName")?le(e,"objectName")&&t.every(n=>["objectName","viewName","contentName"].includes(n)):le(e,"objectName")?t.length===1:le(e,"objectId")&&t.length<=2&&t.every(n=>["objectId","attributeName","attributeId","recordId"].includes(n)):false}a(yd,"isNamedTarget");function hd(e){return e.type==="reflex.state.changed"&&le(e,"reflexId")&&J(e.state,md)&&G(e,"updatedAt")}a(hd,"isReflexStateChangedPayload");function Ad(e){return e.type==="reflex.run.completed"&&le(e,"reflexId")&&le(e,"runId")&&J(e.served,bd)&&q(e,"version")&&q(e,"wallMs")&&G(e,"completedAt")}a(Ad,"isReflexRunCompletedPayload");function xd(e){return e.type==="reflex.authoring.progress"&&le(e,"reflexId")&&J(e.status,fd)&&G(e,"updatedAt")}a(xd,"isReflexAuthoringProgressPayload");var Td=["none","scheduled","recording","completed","failed"];function wd(e){return e.type==="meeting.recording.patch"&&le(e,"meetingId")&&J(e.status,Td)&&Ri(e.failureReason)&&G(e,"updatedAt")}a(wd,"isMeetingRecordingPatchPayload");var Sd=["ok","low","exhausted","paused"],Id=["metering-only","contract","wallet"];function Rd(e){return e.type==="wallet.state"&&J(e.status,Sd)&&J(e.mode,Id)&&G(e,"updatedAt")}a(Rd,"isWalletStatePayload");function Cd(e){return e.type==="channel.revoked"&&D(e,"channel")&&J(e.reason,Bl)}a(Cd,"isChannelRevokedPayload");function Ci(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Ci,"isRecord");function vd(e){let{channel:t}=e;return typeof t=="string"&&Da(t)?t:null}a(vd,"payloadChannel");function AS(e){return Ci(e)?vd(e):null}a(AS,"getLiveProtocolPayloadChannel");function xS(e){return Ci(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"&&Ci(e.payload):false}a(xS,"isLiveEventEnvelope");var SS=["if","concat","sum","avg","count","min","max","earliest","latest","unique","first","percent_empty","percent_not_empty","count_empty","count_not_empty","count_unique"],Ot={if:{name:"if",returnType:"branch",minArgs:3,maxArgs:3},concat:{name:"concat",returnType:{kind:"scalar",type:"text"},minArgs:1},sum:{name:"sum",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},avg:{name:"avg",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count:{name:"count",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},min:{name:"min",returnType:"source_item",minArgs:1,maxArgs:1},max:{name:"max",returnType:"source_item",minArgs:1,maxArgs:1},earliest:{name:"earliest",returnType:{kind:"scalar",type:"date"},minArgs:1,maxArgs:1},latest:{name:"latest",returnType:{kind:"scalar",type:"date"},minArgs:1,maxArgs:1},unique:{name:"unique",returnType:"argument",minArgs:1,maxArgs:1},first:{name:"first",returnType:"source_item",minArgs:1,maxArgs:1},percent_empty:{name:"percent_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},percent_not_empty:{name:"percent_not_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_empty:{name:"count_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_not_empty:{name:"count_not_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_unique:{name:"count_unique",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1}};function pn(e){return Object.hasOwn(Ot,e)}a(pn,"isComputedFunctionName");var Di=class Di extends Error{constructor(t){super(t),this.name="ComputedFormulaCompileError";}};a(Di,"ComputedFormulaCompileError");var I=Di;function fn(e){let t=Ed(e.expression),n=mn(t,e.schema),r=Jd(n.valueType);if(r!==e.returnType)throw new I(`Computed formula "${e.attributeName}" returns "${r}", expected "${e.returnType}"`);if(Ba(e.returnType)&&n.optionsSource===void 0)throw new I(`Computed formula "${e.attributeName}" returns "${e.returnType}" without optionsSource`);let o=n.optionsSource===void 0?[]:[{kind:"options",source:n.optionsSource}],a=Ni([...n.dependencies,...o]);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:Qd({expression:e.expression,returnType:e.returnType,dependencies:a})}}a(fn,"compileComputedFormula");function Va(e){let t=new Map(e.map(o=>[o.attributeName,o])),n=new Set,r=a((o,a)=>{let s=a.indexOf(o);if(s!==-1){let l=[...a.slice(s),o];throw new I(`Computed field cycle detected: ${l.join(" -> ")}`)}if(n.has(o))return;let c=t.get(o);if(c===void 0)return;let u=[...a,o];for(let l of c.dependencies)l.kind==="computed"&&r(l.attributeName,u);n.add(o);},"visit");for(let o of e)r(o.attributeName,[]);}a(Va,"assertAcyclicComputedDependencies");function Ed(e){try{return v$1(e)}catch(t){throw t instanceof Error?new I(t.message):t}}a(Ed,"parseCompileFormula");function mn(e,t){switch(e.kind){case "literal":return {valueType:Nd(e.value),dependencies:[],...typeof e.value=="string"?{literalString:e.value}:{}};case "path":return Dd(e.parts,t);case "call":return Md(e.functionName,e.args,t);case "binary":return $d(e.operator,mn(e.left,t),mn(e.right,t));default:return e}}a(mn,"inferNode");function Nd(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}}a(Nd,"literalToValueType");function Dd(e,t){if(e.length===1){let n=e[0],r=vi(t,n);if(r===void 0)throw new I(`Unknown attribute "${n}" on object "${t.objectName}"`);return r.type==="relation"?{valueType:jd(),dependencies:[{kind:"relation",relationName:r.name,cardinality:ja(r)}],targetAttributeType:r.type}:{valueType:_a(r),dependencies:[kd(r)],optionsSource:Pa(t.objectName,r),targetAttributeType:r.type}}if(e.length===2){let[n,r]=e,o=vi(t,n);if(o===void 0)throw new I(`Unknown attribute "${n}" on object "${t.objectName}"`);if(o.type!=="relation")throw new I(`Attribute "${n}" on object "${t.objectName}" is not a relation`);let a=Od(o);if(a===void 0)throw new I(`Relation "${n}" on object "${t.objectName}" is missing targetObjectName`);let s=t.relatedObjects?.[a];if(s===void 0)throw new I(`Unknown related object "${a}"`);let c=vi(s,r);if(c===void 0)throw new I(`Unknown attribute "${r}" on object "${s.objectName}"`);let u=_a(c);return {valueType:o.cardinality==="many"?Pd(u):u,dependencies:[{kind:"relation",relationName:n,targetAttributeName:r,cardinality:ja(o)}],optionsSource:Pa(s.objectName,c),targetAttributeType:c.type}}throw new I("Computed paths support at most one relation hop")}a(Dd,"inferPath");function vi(e,t){return e.attributes.find(n=>n.name===t)}a(vi,"findAttribute");function Od(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}}a(Od,"getRelationTargetObjectName");function ja(e){return e.cardinality??"one"}a(ja,"relationCardinality");function kd(e){return e.type==="formula"||e.type==="rollup"?{kind:"computed",attributeName:e.name}:{kind:"local",attributeName:e.name}}a(kd,"localDependencyFor");function _a(e){if(e.type==="formula"||e.type==="rollup"){if(e.returnType===void 0)throw new I(`Computed attribute "${e.name}" is missing returnType`);return _d(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}}a(_a,"attributeToValueType");function jd(){return {kind:"collection",itemType:"text"}}a(jd,"relationToValueType");function _d(e){return e==="multiselect"?{kind:"collection",itemType:"select"}:{kind:"scalar",type:e}}a(_d,"returnTypeToValueType");function Pd(e){return e.kind==="collection"?e:{kind:"collection",itemType:e.type}}a(Pd,"asCollectionValueType");function Pa(e,t){if(t.type==="formula"||t.type==="rollup")return Ba(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}:{}}}a(Pa,"optionsSourceForAttribute");function Md(e,t,n){if(!pn(e))throw new I(`Unknown computed function "${e}"`);let r=Ot[e];if(t.length<r.minArgs||r.maxArgs!==void 0&&t.length>r.maxArgs){let a=r.maxArgs===void 0||r.maxArgs===r.minArgs?String(r.minArgs):`${r.minArgs}-${r.maxArgs}`;throw new I(`Function "${e}" expects ${a} arguments, received ${t.length}`)}let o=t.map(a=>mn(a,n));return Fd(e,o)}a(Md,"inferCall");function Fd(e,t){let n=Ni(t.flatMap(r=>r.dependencies));switch(e){case "if":return Vd(t,n);case "concat":return Ud(t,`Function "${e}" does not accept collection values`),{valueType:{kind:"scalar",type:"text"},dependencies:n};case "sum":case "avg":return Ma(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 zd(e,t[0]),{valueType:{kind:"scalar",type:"number"},dependencies:n};case "min":case "max":return qd(e,t[0]),{valueType:Wd(t[0]),dependencies:n,optionsSource:t[0].optionsSource,targetAttributeType:t[0].targetAttributeType};case "earliest":case "latest":return Ma(e,t[0],"date"),{valueType:{kind:"scalar",type:"date"},dependencies:n,targetAttributeType:t[0].targetAttributeType};case "unique":return Bd(t[0],n);case "first":return Ld(t[0],n);default:return e}}a(Fd,"inferFunctionReturn");function Vd(e,t){Ei(e[0].valueType,"boolean",'Function "if" condition must be boolean');let n=e[1],r=e[2],o=Kd(n,r),a=Yd(n,r);if(o===void 0)throw new I('Function "if" branches must return the same type');return {valueType:o,dependencies:t,...a?{optionsSource:a}:{},targetAttributeType:n.targetAttributeType??r.targetAttributeType}}a(Vd,"inferIfFunction");function Bd(e,t){if(e.valueType.kind!=="collection"||e.valueType.itemType!=="select")throw new I('Function "unique" expects a select collection');return {valueType:{kind:"collection",itemType:"select"},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a(Bd,"inferUniqueFunction");function Ld(e,t){if(e.valueType.kind!=="collection")throw new I('Function "first" expects a collection');return {valueType:{kind:"scalar",type:e.valueType.itemType},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a(Ld,"inferFirstFunction");function $d(e,t,n){let r=Ni([...t.dependencies,...n.dependencies]),o=e==="+"||e==="-"||e==="*"||e==="/";if(t.valueType.kind==="collection"||n.valueType.kind==="collection")throw new I(`Cannot use collection values with ${o?"arithmetic":"comparison"} operator "${e}"`);if(o)return e==="+"&&(t.valueType.type==="text"||n.valueType.type==="text")?{valueType:{kind:"scalar",type:"text"},dependencies:r}:(Ei(t.valueType,"number",`Operator "${e}" expects number operands`),Ei(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 I(`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 I(`Operator "${e}" expects number or date operands of the same type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:r}}a($d,"inferBinary");function Ud(e,t){for(let n of e)if(n.valueType.kind==="collection")throw new I(t)}a(Ud,"ensureNoCollections");function Ma(e,t,n){if((t.valueType.kind==="collection"?t.valueType.itemType:t.valueType.type)!==n)throw new I(`Function "${e}" expects ${n} values`)}a(Ma,"ensureCollectionOrScalarType");function qd(e,t){if(t.valueType.kind!=="collection")throw new I(`Function "${e}" expects a collection`);let n=t.valueType.itemType;if(n!=="number"&&n!=="date")throw new I(`Function "${e}" expects number or date values`)}a(qd,"ensureMinMaxSource");function zd(e,t){if(t.valueType.kind!=="collection")throw new I(`Function "${e}" expects a collection`)}a(zd,"ensureCollectionSource");function Ei(e,t,n){if(e.kind!=="scalar"||e.type!==t)throw new I(n)}a(Ei,"ensureScalarType");function Wd(e){return e.valueType.kind==="scalar"?e.valueType:{kind:"scalar",type:e.valueType.itemType}}a(Wd,"sourceItemValueType");function Gd(e,t){return e.kind==="scalar"?t.kind==="scalar"&&e.type===t.type:t.kind==="collection"&&e.itemType===t.itemType}a(Gd,"sameValueType");function Kd(e,t){if(Gd(e.valueType,t.valueType)||Fa(e,t))return e.valueType;if(Fa(t,e))return t.valueType}a(Kd,"resolveIfBranchValueType");function Fa(e,t){return e.valueType.kind==="scalar"&&e.valueType.type==="select"&&t.valueType.kind==="scalar"&&t.valueType.type==="text"&&t.literalString!==void 0}a(Fa,"isSelectScalarWithStringLiteral");function Yd(e,t){let n=e.optionsSource,r=t.optionsSource;if(n!==void 0&&r!==void 0&&!Hd(n,r))throw new I('Function "if" branches use incompatible options sources');return n??r}a(Yd,"resolveIfOptionsSource");function Hd(e,t){return e.objectName===t.objectName&&e.attributeName===t.attributeName&&e.attributeId===t.attributeId}a(Hd,"sameOptionsSource");function Ba(e){return e==="select"||e==="multiselect"}a(Ba,"isSelectLikeReturnType");function Jd(e){if(e.kind==="scalar")return e.type;if(e.itemType==="select")return "multiselect";throw new I(`Collection item type "${e.itemType}" cannot be used as a computed return type`)}a(Jd,"valueTypeToReturnType");function Ni(e){let t=new Set,n=[];for(let r of e){let o=JSON.stringify(kt(r));t.has(o)||(t.add(o),n.push(r));}return n}a(Ni,"uniqueDependencies");function Qd(e){let t=e.dependencies.map(n=>kt(n)).sort((n,r)=>La(JSON.stringify(n),JSON.stringify(r)));return JSON.stringify(kt({expression:e.expression,returnType:e.returnType,dependencies:t}))}a(Qd,"createDependenciesHash");function kt(e){return Array.isArray(e)?e.map(t=>kt(t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>La(t,n)).map(([t,n])=>[t,kt(n)])):e}a(kt,"stableNormalize");function La(e,t){return e<t?-1:e>t?1:0}a(La,"compareStrings");function Zd(e){return e.function==="count"?`count(${e.relationAttribute})`:`${tp(e.function)}(${e.relationAttribute}.${e.targetAttribute})`}a(Zd,"rollupToFormulaExpression");function Xd(e,t){if(e.function==="count")return "number";let n=np(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(!ip(n.type))throw new I('Rollup "original" requires a select, status, or multiselect target');return "multiselect";default:return e.function}}a(Xd,"inferRollupReturnType");function Ua(e,t){let n=Zd(e),r=Xd(e,t);return {...fn({attributeName:e.name,expression:n,returnType:r,schema:ep(e,t)}),kind:"rollup"}}a(Ua,"compileRollupAttribute");function ep(e,t){return {...t,attributes:t.attributes.map(n=>n.name===e.relationAttribute&&n.type==="relation"?{...n,cardinality:"many"}:n)}}a(ep,"schemaWithRollupRelationAsMany");function tp(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}}a(tp,"rollupFunctionToFormulaFunction");function np(e,t){let n=$a(t,e.relationAttribute);if(n===void 0)throw new I(`Unknown relation attribute "${e.relationAttribute}" on object "${t.objectName}"`);if(n.type!=="relation")throw new I(`Attribute "${e.relationAttribute}" on object "${t.objectName}" is not a relation`);let r=rp(n);if(r===void 0)throw new I(`Relation "${e.relationAttribute}" on object "${t.objectName}" is missing targetObjectName`);let o=t.relatedObjects?.[r];if(o===void 0)throw new I(`Unknown related object "${r}"`);let a=$a(o,e.targetAttribute);if(a===void 0)throw new I(`Unknown attribute "${e.targetAttribute}" on object "${o.objectName}"`);return a}a(np,"findRollupTargetAttribute");function $a(e,t){return e.attributes.find(n=>n.name===t)}a($a,"findAttribute");function rp(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}}a(rp,"getRelationTargetObjectName");function ip(e){return e==="select"||e==="status"||e==="multiselect"}a(ip,"isSelectLikeAttributeType");function ve(e,t){switch(e.kind){case "literal":return e.value;case "path":return ap(t,e.parts);case "binary":return sp(e.operator,ve(e.left,t),ve(e.right,t));case "call":return op(e.functionName,e.args,t);default:return e}}a(ve,"evaluateAst");function op(e,t,n){if(up(e),lp(e,t.length),e==="if"){let r=ve(t[0],n);return r===null?null:ve(r?t[1]:t[2],n)}return dp(e,t.map(r=>ve(r,n)))}a(op,"evaluateCallNode");function ap(e,t){return t.reduce((n,r)=>Ya(n,r),e)}a(ap,"resolvePath");function Ya(e,t){if(Array.isArray(e))return e.map(r=>Ya(r,t));if(!Ka(e))return null;if(Object.hasOwn(e,t))return e[t]??null;let n=e.values;return Ka(n)&&Object.hasOwn(n,t)?n[t]??null:null}a(Ya,"resolvePathPart");function sp(e,t,n){switch(e){case "+":return cp(t,n);case "-":return gn(t,n,(r,o)=>r-o);case "*":return gn(t,n,(r,o)=>r*o);case "/":return gn(t,n,(r,o)=>r/o);case ">":return bn(t,n,r=>r>0);case "<":return bn(t,n,r=>r<0);case ">=":return bn(t,n,r=>r>=0);case "<=":return bn(t,n,r=>r<=0);case "==":return qa(t,n);case "!=":{let r=qa(t,n);return r===null?null:!r}default:return e}}a(sp,"evaluateBinary");function cp(e,t){return typeof e=="string"||typeof t=="string"?`${e??""}${t??""}`:gn(e,t,(n,r)=>n+r)}a(cp,"add");function bn(e,t,n){let r=Ha(e,t);return r===null?null:n(r)}a(bn,"compareWith");function Ha(e,t){if(!dt([e,t]))return null;let n=pt(e),r=pt(t);if(n!==null&&r!==null)return n-r;let o=ji(e),a=ji(t);return o&&a?o.getTime()-a.getTime():null}a(Ha,"compare");function qa(e,t){return e===t?true:e==null||t===null||t===void 0?false:dt([e,t])?Ha(e,t)===0:null}a(qa,"equalScalar");function up(e){if(!pn(e))throw new Error(`Unknown computed function "${e}"`)}a(up,"assertComputedFunctionName");function lp(e,t){let{minArgs:n,maxArgs:r}=Ot[e];if(t>=n&&t<=(r??Number.POSITIVE_INFINITY))return;let o=r===void 0?`at least ${n}`:`between ${n} and ${r}`;throw new Error(`Function "${e}" expects ${o} arguments, received ${t}`)}a(lp,"validateArity");function dp(e,t){switch(e){case "concat":return t.filter(n=>n!=null).map(String).join("");case "sum":return dt(t)?Oi(t).reduce((n,r)=>n+r,0):null;case "avg":{if(!dt(t))return null;let n=Oi(t);return n.length>0?n.reduce((r,o)=>r+o,0)/n.length:null}case "count":return We(t[0]).length;case "min":return za(t,"min");case "max":return za(t,"max");case "earliest":return ki(t,"min");case "latest":return ki(t,"max");case "unique":return Ga(We(t[0]));case "first":return We(t[0]).find(n=>n!=null)??null;case "percent_empty":return Wa(t[0],true);case "percent_not_empty":return Wa(t[0],false);case "count_empty":return We(t[0]).filter(a$1).length;case "count_not_empty":return We(t[0]).filter(n=>!a$1(n)).length;case "count_unique":return Ga(We(t[0])).length;default:return e}}a(dp,"evaluateCall");function Oi(e){return yn(e).map(pt).filter(t=>t!==null)}a(Oi,"numericValues");function dt(e){let t=new Set;for(let n of yn(e))_i(n)&&t.add(Ja(n));return t.size<=1}a(dt,"areCommensurable");function Ja(e){return e.code.toUpperCase()}a(Ja,"currencyCode");function gn(e,t,n){if(!dt([e,t]))return null;let r=pt(e),o=pt(t);if(r===null||o===null)return null;let a=n(r,o);return Number.isFinite(a)?a:null}a(gn,"numericBinary");function za(e,t){if(!dt(e))return null;let n=Oi(e);return n.length>0?t==="min"?Math.min(...n):Math.max(...n):ki(e,t)}a(za,"minMax");function ki(e,t){let n=yn(e).map(ji).filter(a=>a!==null);if(n.length===0)return null;let r=n.map(a=>a.getTime()),o=t==="min"?Math.min(...r):Math.max(...r);return new Date(o).toISOString()}a(ki,"dateMinMax");function Wa(e,t){let n=We(e);return n.length===0?0:n.filter(o=>a$1(o)===t).length/n.length}a(Wa,"percentByEmptyState");function Ga(e){let t=new Set,n=[];for(let r of e){if(a$1(r))continue;let o=pp(r);t.has(o)||(t.add(o),n.push(r));}return n}a(Ga,"uniqueNonEmpty");function We(e){return e==null?[]:Array.isArray(e)?yn(e):[e]}a(We,"collectionItems");function yn(e){return e.flat(Number.POSITIVE_INFINITY)}a(yn,"flatten");function pt(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&e.trim()!==""){let t=Number(e);return Number.isFinite(t)?t:null}return _i(e)&&Number.isFinite(e.value)?e.value:null}a(pt,"toFiniteNumber");function _i(e){return typeof e=="object"&&e!==null&&typeof e.value=="number"&&typeof e.code=="string"}a(_i,"isCurrencyValue");function ji(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e!="string"){let n=tt(e);if(n===null)return null;let r=new Date(n);return Number.isNaN(r.getTime())?null:r}let t=new Date(e);return Number.isNaN(t.getTime())?null:t}a(ji,"toDate");function pp(e){if(_i(e))return `currency:${Ja(e)}:${e.value}`;let t=pt(e);return t!==null?`number:${t}`:e instanceof Date?`date:${e.toISOString()}`:`${typeof e}:${JSON.stringify(e)}`}a(pp,"uniqueKey");function Ka(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Ka,"isPlainRecord");function mp(e,t,n){if(e==null)return null;let r=a(o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean"||o instanceof Date?String(o):null,"stringifyScalar");switch(t){case "number":{let o=typeof e=="number"?e:Number(e);return Number.isNaN(o)?null:n!==void 0?Number(o.toFixed(n)):o}case "boolean":return !!e;case "date":return e instanceof Date?e.toISOString():typeof e=="string"?e:null;case "text":return String(e);case "select":if(Array.isArray(e)){for(let o of e){if(o==null)continue;let a=r(o);if(a!==null)return a}return null}return r(e);case "multiselect":return Array.isArray(e)?e.flatMap(o=>{if(o==null)return [];let a=r(o);return a===null?[]:[a]}):r(e)===null?[]:[String(e)];default:{let o=t;throw new Error(`Unsupported computed return type: ${o}`)}}}a(mp,"formatComputedResult");function FS(e,t){return ve(e,t)}a(FS,"evaluateComputedAst");function VS(e,t){return ve(v$1(e),t)}a(VS,"evaluateComputedFormula");function BS(e,t,n,r){try{let o=ve(v$1(e),t);return {value:n?mp(o,n,r):o}}catch(o){return {value:null,error:o instanceof Error?o.message:String(o)}}}a(BS,"evaluateComputedFormulaWithResult");var US=[{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)"}];var Qa=a(e=>a$1(e)||Array.isArray(e)&&e.length===0,"isEmpty"),Q=a(e=>e==null?"":String(e),"toStr"),xn=a(e=>{if(a$1(e))return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null},"toNum"),Tn=a(e=>{if(e==null)return null;let t=e instanceof Date?e:new Date(String(e));return Number.isNaN(t.getTime())?null:t},"toDate"),hn=a(e=>Array.isArray(e)?e:e==null?[]:[e],"toArr"),fp=a((e,t,n)=>{let r=xn(e),o=xn(t);return r!==null&&o!==null&&n(r,o)},"compareNumbers"),bp=a((e,t,n)=>{let r=Tn(e),o=Tn(t);return r!==null&&o!==null&&n(r.getTime(),o.getTime())},"compareDates"),Za=a((e,t,n)=>{if(n.type==="number"||n.type==="currency"){let r=xn(e),o=xn(t);if(r!==null&&o!==null)return r===o}return Q(e)===Q(t)},"equalsForAttr");function GS(e,t){return e?e==="checkbox":typeof t=="boolean"}a(GS,"isCheckboxEquality");var An=a(e=>({appliesTo:["number","currency","date","formula"],evaluateInMemory:a((t,n,r)=>r.type==="date"?bp(t,n,e):fp(t,n,e),"evaluateInMemory")}),"orderingSpec"),wn={is:{appliesTo:["text","phone","number","currency","checkbox","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,n)=>n.type==="checkbox"?e===true==(t===true):Za(e,t,n),"evaluateInMemory")},is_not:{appliesTo:["text","phone","number","currency","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,n)=>!Za(e,t,n),"evaluateInMemory")},contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>Q(e).toLowerCase().includes(Q(t).toLowerCase()),"evaluateInMemory")},not_contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>!Q(e).toLowerCase().includes(Q(t).toLowerCase()),"evaluateInMemory")},starts_with:{appliesTo:["text","phone"],evaluateInMemory:a((e,t)=>Q(e).toLowerCase().startsWith(Q(t).toLowerCase()),"evaluateInMemory")},ends_with:{appliesTo:["text"],evaluateInMemory:a((e,t)=>Q(e).toLowerCase().endsWith(Q(t).toLowerCase()),"evaluateInMemory")},is_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>Qa(e),"evaluateInMemory")},is_not_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>!Qa(e),"evaluateInMemory")},less_than:An((e,t)=>e<t),greater_than:An((e,t)=>e>t),less_or_equal:An((e,t)=>e<=t),greater_or_equal:An((e,t)=>e>=t),is_within:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let n=Tn(e),r=K(t);return n&&r?n.getTime()>=r.startMs&&n.getTime()<r.endMs:false},"evaluateInMemory")},on_day_month:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let n=Tn(e);if(!n)return false;let r=t;return n.getMonth()+1===r.month&&n.getDate()===r.day},"evaluateInMemory")},any_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let n=hn(t).map(Q);return hn(e).map(Q).some(o=>n.includes(o))},"evaluateInMemory")},none_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let n=hn(t).map(Q);return !hn(e).map(Q).some(o=>n.includes(o))},"evaluateInMemory")}};var gp=a((e,t)=>({id:`system:${e}`,name:e,label:e,type:t,system:true}),"systemAttribute"),yp=[...Object.entries(N$1).map(([e,t])=>gp(e,t))];function rI(e,t,n){let r=t;return hp(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,...yp])}a(rI,"evaluateRecordFilterState");function hp(e,t,n){if(e.rules.length===0)return true;let r=new Map(n.map(a=>[a.name,a])),o=e.combinator==="or"?"some":"every";return e.rules[o](a=>Ap(a,t,r))}a(hp,"evaluateFilterState");function Ap(e,t,n){let r=n.get(e.attribute);if(!r)return false;if(e.property&&r.type==="location"){if(!(g(e.property)&&h$2(e.operator)))return false;let c=wn[e.operator];if(!c)return false;let u=t[e.attribute],l=typeof u=="object"&&u!==null?u[e.property]:void 0;return Pi(c,"text",e.operator,l,e.value,r)}if(e.property){let c=Qt(r).find(g=>g.name===e.property);if(!c)return false;let u=C$1(e.operator),l=wn[u];if(!l?.appliesTo.includes(c.type))return false;let m=t[e.attribute],b=(Array.isArray(m)?m:m==null?[]:[m]).some(g=>{if(typeof g!="object"||g===null)return false;let y=g.props;return typeof y!="object"||y===null?false:Pi(l,c.type,u,y[e.property],e.value,c)});return (e.quantifier??B(e.operator))==="none"?!b:b}let o=wn[e.operator];if(!o||!o.appliesTo.includes(r.type))return false;let a=t[e.attribute],s=r.type==="relation"||r.type==="document"||r.type==="user"?wp(a):a;return Pi(o,r.type,e.operator,s,e.value,r)}a(Ap,"evaluateRule");function Pi(e,t,n,r,o,a){let[s,c]=xp(t,n,r,o);return t==="phone"&&c===""&&n==="contains"?false:t==="phone"&&c===""&&n==="not_contains"?true:e.evaluateInMemory(s,c,a)}a(Pi,"evaluateNormalizedComparands");function xp(e,t,n,r){return e==="date"&&(t==="is"||t==="is_not")?[Xa(n),Xa(r)]:e==="phone"?Tp(n,r):[es(e,n),es(e,r)]}a(xp,"normalizeOperatorComparands");function Xa(e){let t=Oe(e)?tt(e):e;if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.toISOString().slice(0,10);if(typeof t!="string"||t==="")return null;if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let n=new Date(t);return Number.isNaN(n.getTime())?null:n.toISOString().slice(0,10)}a(Xa,"normalizeUtcCalendarDay");function Tp(e,t){let n=typeof t=="object"&&t!==null?t:{},r=typeof n.countryCode=="string"?n.countryCode:void 0,o=a(a=>{let s=typeof a=="object"&&a!==null?a:{phoneNumber:a};if(typeof s.phoneNumber!="string")return null;if(!r)return a$3(s.phoneNumber);let c=typeof s.countryCode=="string"?s.countryCode:r;return `${c}:${b$2(s.phoneNumber,c)}`},"normalizeOne");return [o(e),o(t)]}a(Tp,"normalizePhoneComparands");function es(e,t){return e==="currency"?z$1(t):e==="date"?Oe(t)?tt(t):t instanceof Date?Number.isNaN(t.getTime())?null:t.toISOString():t:t}a(es,"normalizeComparableValue");function wp(e){let t=a(n=>typeof n!="object"||n===null?n:n.id,"normalizeOne");return Array.isArray(e)?e.map(t):t(e)}a(wp,"normalizeReferenceIds");var ts="today";function Sn(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}a(Sn,"dateInTimezone");function Sp(e,t){if(!("defaultValue"in e))return;let{defaultValue:n}=e;return e.type!=="date"||n!==ts?n:e.includeTime?t.now.toISOString():Sn(t.now,t.timezone)}a(Sp,"resolveAttributeDefaultValue");function dI(e,t,n){if(e.combinator==="or"&&e.rules.length>1)return {};let r=new Map(t.map(a=>[a.name,a])),o={};for(let a of e.rules){if(a.property!==void 0||Object.hasOwn(o,a.attribute))continue;let s=r.get(a.attribute);if(!s)continue;let c=Ip(a,n);c!==void 0&&(o[a.attribute]=j$1(s).storage.cardinality==="many"?[c]:c);}return o}a(dI,"deriveCreateDefaultsFromFilters");function Ip(e,t){if(e.operator==="is")return v$2(e.value)?ns(e.value,t):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator==="any_of"){if(!Array.isArray(e.value)||e.value.length!==1)return;let n=e.value[0];return v$2(n)?ns(n,t):n}}a(Ip,"extractDeterministicValue");function ns(e,t){if(t){if(e.dynamic==="actor")return t.userId;if(e.anchor==="today")return Sn(t.now,t.timezone);if(e.anchor==="now")return t.now.toISOString()}}a(ns,"resolveDynamicValue");function fI(e){let t=[];return e.canModify&&t.push("modify"),e.canSend&&t.push("send"),t}a(fI,"requestedCapabilities");var bI={status:"connector_status",error:"connector_error",provider:"connector_provider"};var Rp=(t=>(t.Desktop="desktop",t))(Rp||{});function AI(e){return e==="gmail"||e==="outlook"}a(AI,"isMailProvider");var Cp=["threads","messages"];function xI(e){return Cp.includes(e)}a(xI,"isMailboxListMode");var vp=["reply","reply_all"];function TI(e){return vp.includes(e)}a(TI,"isReplyMode");var wI=2e5,SI=998;var CI=["force","skip"],vI=["none","all","external_only"],EI="x-fake-signature",NI={override:null,status:"none",failureReason:null,botId:null};var Ep=/^Session \d+$/;function rs(e){let t=e.replace(/\s+/g," ").trim().replace(/[.!?]+$/,"");return t?t.length>60?`${t.slice(0,59).trimEnd()}...`:t:"New conversation"}a(rs,"buildAgentFallbackTitle");function Np(e){let t=e.generated?.trim();return t&&!Ep.test(t)?t:e.firstUserText?rs(e.firstUserText):e.emptyLabel}a(Np,"conversationDisplayTitle");var Mi=/^[a-z0-9][a-z0-9-]{0,62}$/;function Dp(e){if(!Mi.test(e))throw new h$1(`Invalid schema source id "${e}": expected a lowercase slug matching ${Mi}`,[])}a(Dp,"assertSchemaSourceId");function MI(e){let{attributeRemovals:t,objectRemovals:n,renames:r}=e.destructive;return t.length>0||n.length>0||r.length>0}a(MI,"hasDestructiveEntries");var de={objectAdditions:20,totalMutations:500,serializedBytes:512*1024};function Vi(e){return e instanceof Error?e.message:String(e)}a(Vi,"errorMessage");var Op=z.enum(["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"]).describe('The attribute\'s data type. Determines which keys `config` accepts and requires: `status`/`select`/`multiselect` need a non-empty `options` array (each `status` option carrying its own `group`); `relation` needs `targets` (non-empty) and `cardinality` ("one" or "many"); `formula` needs `expression` and `returnType`; `rollup` needs `targetAttribute` and `function`. Every other type accepts only the shared presentation keys (`placeholder`, `defaultValue`, `icon`, ...) plus a few type-specific optionals (e.g. `number.decimals`, `date.dateFormat`). An attribute\'s type can never be changed later through this tool \u2014 only through a code migration \u2014 so pick it correctly now.');var os=z.string().min(1).superRefine((e,t)=>{try{n(e);}catch(n){t.addIssue({code:z.ZodIssueCode.custom,message:Vi(n)});}}).describe('The attribute\'s machine name \u2014 the record\'s field key, and what `{{ name }}` refers to in a labelExpression. Must be a valid identifier: starts with a letter or underscore, then only letters/digits/underscores ("montantHt", "first_name", "FIRST_NAME" are valid; "first-name", "first name", "123name" are not). Max 63 characters. Cannot be a name reserved by the record shape itself (id, createdAt, updatedAt, createdBy, lastUpdatedBy, objectId, label, embeddingText, values, metadata, deletedAt, deletedBy, schemaVersion).'),kp=z.string().min(1).superRefine((e,t)=>{b(e)&&t.addIssue({code:z.ZodIssueCode.custom,message:`"${e}" is a reserved object name (${h.join(", ")}) and cannot be used for a new object.`});try{j(e);}catch(n){t.addIssue({code:z.ZodIssueCode.custom,message:Vi(n)});}}).describe(`The new object's machine name: kebab-case slug, lowercase letters/digits/hyphens only, starting with a letter ("products", "user-profiles", "order-items" are valid; "Products", "userProfiles", "user_profiles" are not). Max 63 characters. Cannot be a name the platform reserves for its own system objects, and cannot already exist.`);function as(e){return e.superRefine((t,n)=>{try{let r=L$1(t.type,{...t.config??{},description:t.description}),o=Object.keys(t.config??{}).filter(a=>!Object.hasOwn(r,a));o.length>0&&n.addIssue({code:"unrecognized_keys",keys:o,path:["config"],message:`Unrecognized attribute config key${o.length===1?"":"s"}: ${o.join(", ")}`});}catch(r){if(r instanceof h$1){for(let o of r.errors)n.addIssue({code:z.ZodIssueCode.custom,path:["config",...o.path.map(a=>/^\d+$/.test(a)?Number(a):a)],message:`Config for type "${t.type}" is invalid or incomplete: ${o.message}`});return}n.addIssue({code:z.ZodIssueCode.custom,path:["config"],message:`Config for type "${t.type}" is invalid or incomplete: ${Vi(r)}`});}})}a(as,"withConfigCheck");var ss=z.object({objectName:z.string().min(1).describe("Name of the existing (or, elsewhere in the same plan, newly created) object this attribute is added to. Ignored for an attribute declared inline in `additive.objects[].attributes` \u2014 there the parent object's own `name` is used instead."),name:os,label:z.string().min(1).max(128).describe("Human-readable display label shown in the UI. 1-128 characters, cannot be empty."),type:Op,config:z.record(z.string(),z.unknown()).optional().describe('Type-specific configuration; required keys depend on `type` (see `type`\'s description). Shared optional keys on every type: `placeholder`, `defaultValue`, `icon`, `order`, `hidden`, `archived`, `deprecated`, `metadata`. Per-type keys: `text` \u2014 `multiline`, `minLength`, `maxLength`, `pattern`, `format` ("email"|"url"|"slug"); `number` \u2014 `renderAs` ("number"|"rating"), `min`, `max`, `unit`, `decimals`; `date` \u2014 `dateFormat`, `minDate`, `maxDate`, `includeTime`, `endDate`, `timeFormat` ("12h"|"24h"); `phone` \u2014 `defaultCountryCode` (3-letter); `currency` \u2014 `defaultCurrency`, `allowedCurrencies`, `allowNegative`; `status`/`select`/`multiselect` \u2014 `options` (REQUIRED, non-empty array of `{ value, label, color }`, unique `value`s; for `status` every OPTION also carries `group` as idle|in_progress|finished \u2014 `group` belongs on each option, never on `config` itself; select/multiselect accept `renderAs: "badges"`); `location` \u2014 `granularity`, `defaultCountry`, `allowedCountries`; `user` \u2014 `types` ("user"|"agent"), `multiple`; `relation` \u2014 `targets` (REQUIRED, non-empty array of `{ object }`) and `cardinality` (REQUIRED, "one"|"many"); `formula` \u2014 `expression` (REQUIRED formula string) and `returnType` (REQUIRED); `rollup` \u2014 `targetAttribute` (REQUIRED) and `function` (REQUIRED, e.g. "sum"|"avg"|"count"); `document` \u2014 `properties`, `accepts`, `maxFileSize`. Omit entirely for `richtext`/`checkbox`, which take no type-specific keys.'),required:z.boolean().optional().describe("Whether the attribute must have a value on every record. Defaults to false (optional)."),description:z.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),jp=as(ss),_p=as(ss.omit({objectName:true})),Pp=z.object({name:kp,label:z.string().min(1).describe('Human-readable singular display label (e.g. "Devis").'),pluralLabel:z.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:z.string().optional().describe("Help text describing what this object represents."),icon:t.describe("Required icon name for the object. Must be a catalogue value \u2014 call `search_icons` and use a name it returns verbatim. A name that is not in the catalogue is rejected without any hint as to what would have worked, so never guess one."),labelExpression:nt.describe('Template used to render a human-readable label for every record of this object \u2014 e.g. shown in relations, search results, and breadcrumbs. MUST contain at least one `{{ attributeName }}` interpolation referencing an attribute this object will actually have (either declared in this same `attributes` array, or an existing attribute if this is an update) \u2014 a plain string with no `{{ }}` at all (e.g. "Devis") is rejected. Interpolations cannot be empty (`{{ }}` is rejected) and only these pipes are allowed: UPPER, LOWER, capitalize, trim, prefix:"...", suffix:"...", wrap:"..." "...", default:"...". `{{ a || b }}` falls back to `b` when `a` is empty. Examples: "{{ firstName }} {{ lastName }}", "{{ numero | UPPER }}", "{{ name || reference }}".'),attributes:z.array(_p).default([]).describe("Attributes to create on this new object, inline. Same rules as a standalone entry in `additive.attributes`, minus `objectName` (implied by this object). At least one attribute referenced by `labelExpression` should be included here.")}).strict(),cs=z.object({attributeRemovals:z.array(z.object({objectName:z.string().min(1).describe("Object the attribute is removed from."),attributeName:z.string().min(1).describe("Attribute to delete, together with every record's stored value for it. Must not be a system (code-declared) attribute, and must not be referenced by the object's own `labelExpression` or `embeddingExpression` \u2014 update those first.")}).strict()).default([]).describe("Attributes to permanently delete. Irreversible: record values for the attribute are purged."),objectRemovals:z.array(z.object({objectName:z.string().min(1).describe("Object to delete entirely, together with all its records. Must not be a system (code-declared) object, and must not still be targeted by a `relation` attribute on another object \u2014 retarget or remove that relation first.")}).strict()).default([]).describe("Objects to permanently delete, records included. Irreversible."),renames:z.array(z.object({objectName:z.string().min(1).describe("Object the renamed attribute belongs to."),from:z.string().min(1).describe("Current attribute name. Must already exist and not be a system attribute."),to:os.describe("New attribute name \u2014 same identifier rules as any attribute `name` (see `name` on a planned attribute), and must not collide with another name already on the object, including one added elsewhere in this same plan.")}).strict()).default([]).describe("Attribute renames. Every reference to the old name (labelExpression, views, formulas) must be updated separately \u2014 a rename does not follow references automatically.")}).strict().default({attributeRemovals:[],objectRemovals:[],renames:[]}),us=z.string().min(1).describe("ONE sentence naming the intent of the change \u2014 what it is for, not what it contains. The human approving it has already watched every entry land in the preview window and can read every row of the plan itself, so a recap tells them nothing they do not have. A second sentence is warranted only when `destructive` is non-empty: say plainly what will be lost (e.g. 'deletes the \"ancienMontant\" column and its data on every devis'). Never restate the plan \u2014 explain intent."),ls=z.object({objects:z.array(Pp).default([]),attributes:z.array(jp).default([])}).strict().default({objects:[],attributes:[]});function Fi(e,t=[],n=new WeakSet){if(e===null||typeof e=="string"||typeof e=="boolean")return null;if(typeof e=="number")return Number.isFinite(e)?null:{path:t,message:"Plan input contains a non-finite number"};if(typeof e!="object")return {path:t,message:"Plan input must contain only JSON-safe values"};if(n.has(e))return {path:t,message:"Plan input cannot contain circular references"};if(Array.isArray(e)){n.add(e);for(let s of Reflect.ownKeys(e))if(s!=="length"&&(typeof s=="symbol"||!/^(0|[1-9]\d*)$/.test(s)))return n.delete(e),{path:[...t,s],message:"Plan input arrays cannot contain non-index JSON properties"};for(let s=0;s<e.length;s++){if(!Object.hasOwn(e,s))return n.delete(e),{path:[...t,s],message:"Plan input cannot contain sparse arrays"};let c=Fi(e[s],[...t,s],n);if(c)return n.delete(e),c}return n.delete(e),null}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return {path:t,message:"Plan input must contain only plain JSON objects"};n.add(e);let o=e,a=Reflect.ownKeys(o);for(let s of a){let c=Object.getOwnPropertyDescriptor(o,s);if(typeof s=="symbol"||!(c?.enumerable&&"value"in c))return n.delete(e),{path:[...t,s],message:"Plan input objects must contain enumerable JSON data properties only"}}for(let s of a.sort()){let c=Fi(o[s],[...t,s],n);if(c)return n.delete(e),c}return n.delete(e),null}a(Fi,"findJsonSafetyIssue");function Mp(e){let t=[];return e.additive.objects.forEach((n,r)=>{t.push(["additive","objects",r]),n.attributes.forEach((o,a)=>{t.push(["additive","objects",r,"attributes",a]);});}),e.additive.attributes.forEach((n,r)=>{t.push(["additive","attributes",r]);}),e.destructive.attributeRemovals.forEach((n,r)=>{t.push(["destructive","attributeRemovals",r]);}),e.destructive.objectRemovals.forEach((n,r)=>{t.push(["destructive","objectRemovals",r]);}),e.destructive.renames.forEach((n,r)=>{t.push(["destructive","renames",r]);}),t}a(Mp,"mutationPaths");function ds(e,t){e.additive.objects.length>de.objectAdditions&&t.addIssue({code:"too_big",origin:"array",maximum:de.objectAdditions,inclusive:true,path:["additive","objects",de.objectAdditions],message:`A schema plan can add at most ${de.objectAdditions} objects`});let n=Mp(e);n.length>de.totalMutations&&t.addIssue({code:"too_big",origin:"array",maximum:de.totalMutations,inclusive:true,path:n[de.totalMutations],message:`A schema plan can contain at most ${de.totalMutations} mutations; received ${n.length}`});}a(ds,"addPlanLimitIssues");function ps(e,t){let n=Fi(e);if(n)return t.addIssue({code:"custom",path:n.path,message:n.message}),z.NEVER;let r=new TextEncoder().encode(b$3(e)).byteLength;return r>de.serializedBytes?(t.addIssue({code:"too_big",origin:"string",maximum:de.serializedBytes,inclusive:true,path:[],message:`A schema plan can serialize to at most ${de.serializedBytes} UTF-8 bytes; received ${r}`}),z.NEVER):e}a(ps,"boundSerializedPlanInput");var is=z.object({schemaPlanVersion:z.literal(2).describe("Required proposal contract version."),summary:us,additive:ls,destructive:cs}).strict().superRefine(ds),YI=Object.assign(z.preprocess(ps,is),{shape:is.shape}),Fp=z.object({schemaPlanVersion:z.literal(2),summary:us,additive:ls,destructive:cs}).strict().superRefine(ds),HI=z.preprocess(ps,Fp);function mt(e,t){throw new h$1(t,[{path:e,message:t}])}a(mt,"reject");function In(e){throw new h$1(`Unsupported schema reference variant ${String(e)}`,[])}a(In,"exhaustive");function rR(e){let t=new Map(e.objects.map(s=>[s.name,s])),n=[];function r(s,c,u){function l(y,A,h){(y.kind==="object"?t.has(y.object):y.kind==="attribute"?t.get(y.object)?.attributes.some(_=>_.name===y.attribute):true)||mt([...c,...h],`Unknown schema reference ${JSON.stringify(y)}`),n.push({owner:s,target:y,category:A,path:h,...u===void 0?{}:{layer:u}});}a(l,"add");function m(y,A,h,j){l({kind:"attribute",object:y,attribute:A},h,j);}a(m,"attribute");function d(y,A,h,j,_){m(y,A,h,j);let O=t.get(y)?.attributes.find(B=>B.name===A);return O?.type!=="relation"&&mt([...c,...j],`Invalid schema reference path "${_}"`),(O.targets.length!==1||O.targets[0].object==="*")&&mt([...c,...j],`Ambiguous schema reference path "${_}"`),O.targets[0].object}a(d,"traverse");function b(y,A,h,j){let _=y;for(let[O,B]of A.entries())O===A.length-1?m(_,B,h,j):_=d(_,B,h,j,A.join("."));}a(b,"attributePath");function g(y,A,h){switch(A.kind){case "literal":return;case "path":b(y,A.parts,"computed",h);return;case "call":for(let j of A.args)g(y,j,h);return;case "binary":g(y,A.left,h),g(y,A.right,h);return;default:In(A);}}return a(g,"formula"),{add:l,attribute:m,traverse:d,attributePath:b,formula:g}}a(r,"visitor"),e.objects.forEach((s,c)=>{let u=["objects",String(c)],l=r({kind:"object",object:s.name},u);for(let m of ["labelExpression","embeddingExpression"]){let d=s[m];if(d)for(let b of wt(d))l.attributePath(s.name,b.split("."),"business",[m]);}s.attributes.forEach((m,d)=>{let b=[...u,"attributes",String(d)],g=r({kind:"attribute",object:s.name,attribute:m.name},b);switch(m.type){case "relation":m.targets.forEach((y,A)=>{if(y.object!=="*"&&g.add({kind:"object",object:y.object},"structural",["targets",String(A),"object"]),y.displayTemplate)for(let h of wt(y.displayTemplate))g.attributePath(y.object,h.split("."),"business",["targets",String(A),"displayTemplate"]);for(let h of Object.keys(y.filter??{}))g.attribute(y.object,h,"business",["targets",String(A),"filter",h]);});break;case "formula":{let y;try{y=v$1(m.expression);}catch(A){mt([...b,"expression"],A instanceof Error?A.message:String(A));}g.formula(s.name,y,["expression"]),o(m,g);break}case "rollup":{let y=m.relationPath??m.relationAttribute,A=s.name;for(let h of y.split("."))A=g.traverse(A,h,"computed",[m.relationPath===void 0?"relationAttribute":"relationPath"],y);g.attributePath(A,m.targetAttribute.split("."),"computed",["targetAttribute"]),o(m,g);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:In(m);}});});function o(s,c){s.optionsSource&&(c.add({kind:"object",object:s.optionsSource.objectName},"computed",["optionsSource","objectName"]),c.attribute(s.optionsSource.objectName,s.optionsSource.attributeName,"computed",["optionsSource","attributeName"]));}a(o,"visitOptions");function a$1(s,c,u){r({kind:"view",object:s.object,view:s.name},c,u).add({kind:"object",object:s.object},"structural",["object"]),s.contents.forEach((l,m)=>{let d=r({kind:"content",object:s.object,view:s.name,content:l.name},[...c,"contents",String(m)],u);function b(g,y,A,h){g?.forEach((j,_)=>d.attribute(y,j,A,[h,String(_)]));}switch(a(b,"names"),l.type){case "collection":{let g=qe(l.source),y;switch(g.kind==="object"?(y=g.object,d.add({kind:"object",object:y},"source",["source","object"])):g.kind==="relatedFrom"?(y=g.object,d.add({kind:"object",object:y},"source",["source","object"]),d.attribute(y,g.relation,"source",["source","relation"])):y=d.traverse(s.object,g.relation,"source",["source","relation"],g.relation),l.columns?.forEach((A,h)=>{if(typeof A=="string"){d.attribute(y,A,"display",["columns",String(h)]);return}let j=t.get(s.object),_=g.kind!=="related"||!j?void 0:Ia(j,g.relation),O=["columns",String(h),"relationProperty"];_||mt([...c,"contents",String(m),...O],"Relation property columns require a relation source"),_.properties?.definitions.some(B=>B.name===A.relationProperty)||mt([...c,"contents",String(m),...O],`Unknown relation property "${A.relationProperty}"`),d.add({kind:"attribute",object:s.object,attribute:_.name},"display",O);}),b(l.displayAttributes,y,"display","displayAttributes"),l.descriptionAttribute!==void 0&&d.attribute(y,l.descriptionAttribute,"display",["descriptionAttribute"]),l.filters?.rules.forEach((A,h)=>d.attribute(y,A.attribute,"business",["filters","rules",String(h),"attribute"])),l.sorts?.forEach((A,h)=>d.attribute(y,A.attribute,"business",["sorts",String(h),"attribute"])),l.layout){case "table":case "list":if(l.columnSizing)for(let A of Object.keys(l.columnSizing))d.attribute(y,A,"display",["columnSizing",A]);break;case "kanban":l.groupByAttribute!==void 0&&d.attribute(y,l.groupByAttribute,"business",["groupByAttribute"]);break;default:In(l.layout);}break}case "form":l.groups.forEach((g,y)=>g.fields.forEach((A,h)=>d.attribute(s.object,A.attribute,"display",["groups",String(y),"fields",String(h),"attribute"])));break;case "richtext":d.attribute(s.object,l.attribute,"source",["attribute"]),l.titleAttribute!==void 0&&d.attribute(s.object,l.titleAttribute,"display",["titleAttribute"]);break;case "documents":b(l.relations,s.object,"business","relations");break;case "forms":l.objectName!==void 0&&d.add({kind:"object",object:l.objectName},"source",["objectName"]);break;case "emails":case "meetings":b(l.emailAttributes,s.object,"business","emailAttributes");break;case "activity":case "custom":break;default:In(l);}});}return a(a$1,"viewReferences"),e.views.forEach((s,c)=>a$1(s,["views",String(c)])),e.retainedViews?.forEach(({definition:s,layer:c},u)=>a$1(s,["retainedViews",String(u),"definition"],c)),n}a(rR,"collectSchemaReferences");var ms=/^[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 $(e,t,n){throw new h$1(n,[{path:[...e.split("."),t],message:n}])}a($,"reject");function Bi(e){return e.join("|")}a(Bi,"pairKey");function Li(e,t){return [e,t].sort()}a(Li,"pairedAddresses");function Vp(e){let t=new Map,n=new Map,r=new Set;for(let o of e){let a=Bi(o.addresses);(!ms.test(o.id)||o.addresses[0]===o.addresses[1]!=(o.symmetric===true))&&$(o.addresses[0],"pair",`Invalid stored pair identity for ${a}`),(t.has(a)||n.has(o.id)&&n.get(o.id)!==a||o.addresses.some(s=>r.has(s)))&&$(o.addresses[0],"pair",`Duplicate stored pair identity for ${a}`),o.addresses.includes(o.ownerAddress)||$(o.addresses[0],"pair",`Invalid property owner for ${a}`),t.set(a,o),n.set(o.id,a);for(let s of o.addresses)r.add(s);}return t}a(Vp,"validateExistingPairs");function Bp(e,t){let n=new Set(e.flatMap(s=>s.addresses)),r=new Map,o=new Set;for(let{from:s,to:c}of t)(!n.has(s)||s===c||r.has(s)||o.has(c))&&$(s,"rename",`Invalid or duplicate relation attribute rename ${s} to ${c}`),r.set(s,c),o.add(c);let a$1=a(s=>r.get(s)??s,"mapped");return e.map(s=>({...s,addresses:Li(a$1(s.addresses[0]),a$1(s.addresses[1])),ownerAddress:a$1(s.ownerAddress),generatedAddresses:s.generatedAddresses.map(a$1)}))}a(Bp,"remapExistingPairs");function Lp(e,t,n){return e.type==="relation"&&e.bilateral?.object===t&&e.bilateral.attribute===n&&e.targets.length===1&&e.targets[0]?.object===t}a(Lp,"isReciprocal");function $p(e,t,n){let r=e.bilateral;r||$(`${t}.${e.name}`,"bilateral","Missing inverse address");let o={type:"relation",name:r.attribute,label:r.label??r.attribute,required:false,targets:[{object:t}],bilateral:{object:t,attribute:e.name,cardinality:e.cardinality},order:n};return (r.cardinality??Vo(e.cardinality))==="one"?{...o,cardinality:"one"}:{...o,cardinality:"many"}}a($p,"generateInverse");function Up(e,t,n,r,o){e.bilateral?.cardinality&&e.bilateral.cardinality!==t.cardinality&&$(r,"cardinality",`${n} declares ${r} as ${e.bilateral.cardinality}, but ${r} declares ${t.cardinality}`),t.bilateral?.cardinality&&t.bilateral.cardinality!==e.cardinality&&$(n,"cardinality",`${r} declares ${n} as ${t.bilateral.cardinality}, but ${n} declares ${e.cardinality}`),e.bilateral?.label&&e.bilateral.label!==t.label&&$(r,"label",`${n} declares a different label for ${r}`),t.bilateral?.label&&t.bilateral.label!==e.label&&$(n,"label",`${r} declares a different label for ${n}`),e.properties&&t.properties&&!j$2(e.properties,t.properties)&&!o&&$(r,"properties",`${n} and ${r} declare different qualified properties`),e.bilateral?.storageOwner===t.bilateral?.storageOwner&&e.bilateral?.storageOwner!==void 0&&$(r,"storageOwner",`${n} and ${r} cannot both own or both disown qualified properties`);}a(Up,"checkExplicitDeclarations");function qp(e,t,n,r,o,a){return o?o.ownerAddress:e.bilateral?.storageOwner===true||t.bilateral?.storageOwner===false?n:e.bilateral?.storageOwner===false||t.bilateral?.storageOwner===true?r:a?n:Li(n,r)[0]}a(qp,"chooseOwner");function zp(e){if(!e.metadata)return;let{relationPairId:t,relationGenerated:n,...r}=e.metadata;e.metadata=Object.keys(r).length>0?r:void 0;}a(zp,"stripUntrustedPairMetadata");function Wp(e,t,n,r,o,a){a.has(n)&&a.has(r)&&!j$2(e.properties,t.properties)&&$(r,"properties",`${n} and ${r} edit different qualified properties`);let s=a.has(n)||o.has(n)&&!o.has(r)&&!a.has(r),c=a.has(r)||o.has(r)&&!o.has(n)&&!a.has(n),u=s?e.properties:c?t.properties:e.properties??t.properties;u?(e.properties=structuredClone(u),t.properties=structuredClone(u)):(delete e.properties,delete t.properties);}a(Wp,"reconcileProperties");function $i(e){let t=structuredClone(e.objects),n=new Map;for(let d of t){if(n.has(d.name))throw new r("object",d.name);n.set(d.name,d);let b=new Set;for(let g of d.attributes){if(b.has(g.name))throw new r("attribute",g.name);b.add(g.name),zp(g);}}let r$1=Bp(e.existingPairs??[],e.addressRenames??[]),o=Vp(r$1),a=new Set(r$1.flatMap(d=>d.generatedAddresses)),s=new Set(e.propertyEditAddresses??[]),c=new Set(e.explicitAddresses??t.flatMap(d=>d.attributes.filter(b=>!a.has(`${d.name}.${b.name}`)).map(b=>`${d.name}.${b.name}`))),u=t.flatMap(d=>d.attributes.filter(b=>b.type==="relation"&&!!b.bilateral).map(b=>({object:d,attribute:b,address:`${d.name}.${b.name}`}))).sort((d,b)=>d.address.localeCompare(b.address)),l=new Map,m=new Map;for(let{object:d,attribute:b,address:g}of u){let y=b.bilateral?.object;(!y||y==="*"||b.targets.length!==1||b.targets[0]?.object!==y)&&$(g,"targets",`Bilateral target of ${g} must be one concrete object`);let A=n.get(y);A||$(g,"bilateral",`Unknown inverse object ${y} for ${g}`);let h=`${y}.${b.bilateral?.attribute}`,j=g===h;j&&b.cardinality!=="many"&&$(g,"cardinality",`Symmetric self relation ${g} must be many`),j&&b.bilateral?.cardinality&&b.bilateral.cardinality!==b.cardinality&&$(g,"bilateral",`Symmetric self relation ${g} needs matching cardinality`);let _=Li(g,h),O=Bi(_);if(l.has(O))continue;let B=A.attributes.find(Ie=>Ie.name===b.bilateral?.attribute);if(B&&!Lp(B,d.name,b.name))throw new r("attribute",h);let Se=!(B&&c.has(h));B||(B=$p(b,d.name,A.attributes.length),A.attributes.push(B));let K=B;!j&&c.has(g)&&c.has(h)&&Up(b,K,g,h,s.has(g)!==s.has(h));let k=o.get(O),M=k?.id??e.nextPairId(_),oe=r$1.find(Ie=>Ie.id===M&&Bi(Ie.addresses)!==O);(!ms.test(M)||oe||m.has(M)&&m.get(M)!==O)&&$(g,"pair",`Invalid or duplicate pair identity for ${g} and ${h}`),m.set(M,O);let ee=j?g:qp(b,K,g,h,k,Se);b.bilateral&&K.bilateral||$(g,"bilateral",`Missing reciprocal configuration for ${g} and ${h}`),b.bilateral={...b.bilateral,cardinality:K.cardinality,label:K.label,storageOwner:ee===g},K.bilateral={...K.bilateral,cardinality:b.cardinality,label:b.label,storageOwner:ee===h},Wp(b,K,g,h,c,s),b.metadata={...b.metadata,relationPairId:M},K.metadata={...K.metadata,relationPairId:M},l.set(O,{id:M,addresses:_,ownerAddress:ee,generatedAddresses:_.filter(Ie=>!c.has(Ie)),...j?{symmetric:true}:{}});}return {objects:t,pairs:[...l.values()].sort((d,b)=>d.addresses[0].localeCompare(b.addresses[0]))}}a($i,"reconcileRelationAttributes");var v=z.number().finite().nonnegative(),bs=z.enum(Lo),Ui=z.enum($o),qi=z.enum(Uo),gs=z.object({provider:bs,model:z.string().min(1)}).strict(),fR=z.object({speed:Ui.optional(),reasoning:qi.optional()}).strict(),ys=z.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),Gp=z.object({model:gs.optional(),speed:Ui.optional(),reasoning:qi.optional(),imageModel:ys.optional()}).strict(),bR=Gp.refine(e=>e.model!==void 0||e.speed!==void 0||e.reasoning!==void 0||e.imageModel!==void 0,{message:"At least one inference override is required"}),gR=z.object({model:gs.nullable().optional(),speed:Ui.nullable().optional(),reasoning:qi.nullable().optional(),imageModel:ys.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0&&Object.values(e).every(t=>t!==void 0),{message:"At least one inference override is required"}),hs=z.object({label:z.string(),denied:z.boolean().optional(),deletion:z.object({target:z.string().optional(),count:v.optional(),restorableDays:v.optional()}).strict().optional(),counts:z.record(z.string(),v).optional(),warnings:z.array(z.string()).optional()}).strict(),Kp=z.union([z.object({type:z.literal("text"),text:z.string()}).strict(),z.object({type:z.literal("reasoning"),text:z.string()}).strict(),z.object({type:z.literal("system"),code:z.enum(zn)}).strict(),z.object({type:z.literal("error"),error:z.string(),errorClass:z.string().optional()}).strict(),z.object({type:z.literal("tool"),toolCallId:z.string(),name:z.string(),args:z.record(z.string(),z.unknown()),result:z.unknown().optional(),error:z.string().optional(),errorCode:z.enum(["output_limit_reached","interrupted"]).optional(),state:z.enum(["streaming","running","completed","error","pending","approval-requested","approval-responded","approval-dispatched"]),durationMs:v.optional(),approvalId:z.string().optional(),approvalImpact:hs.optional(),approved:z.boolean().optional(),approvalReason:z.string().optional(),approvalRelaxableByAuto:z.boolean().optional()}).strict(),z.object({type:z.literal("file"),fileId:z.string(),name:z.string(),mimeType:z.string()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("in-progress"),reason:z.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:v.optional(),reportedTokens:v.optional()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("completed"),tokensBefore:v,tokensAfter:v,tokensSaved:v,strategy:z.enum(["no-op","summary","truncation"]),durationMs:v,summary:z.string().optional()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("failed"),reason:z.string(),durationMs:v.optional()}).strict()]),Yp=z.object({id:z.string(),name:z.string(),mimeType:z.string(),size:v}).strict(),Hp=z.object({id:z.string(),type:z.string().transform(e=>e),entityId:z.string(),label:z.string(),objectName:z.string().optional(),startIndex:v,endIndex:v}).strict(),Jp=z.object({provider:bs,model:z.string(),maxTokens:v.optional(),contextWindow:v.optional()}).strict(),Qp=z.union([z.date(),z.string().datetime({offset:true}).transform(e=>new Date(e))]),fs=z.object({id:z.string(),sessionId:z.string(),tenantId:z.string().optional(),runId:z.string().optional(),role:z.enum(["user","assistant","system","tool"]),parts:z.array(Kp),attachments:z.array(Yp).optional(),mentions:z.array(Hp).optional(),model:Jp.optional(),tokenUsage:z.object({input:v,output:v}).strict().optional(),metadata:z.record(z.string(),z.unknown()).optional(),createdAt:Qp}).strict(),Zp=z.object({id:z.string(),description:z.string(),status:z.enum(["pending","in_progress","completed","blocked"]),result:z.string().optional(),updatedAt:v.optional()}).strict(),Xp=z.object({id:z.string(),sessionId:z.string(),status:z.enum(["active","completed","abandoned"]),todos:z.array(Zp),version:v,createdAt:z.string(),updatedAt:z.string(),completedAt:z.string().optional()}).strict(),As={"session-named":z.object({name:z.string()}).strict(),"compaction-start":z.object({reason:z.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:v.optional(),reportedTokens:v.optional()}).strict(),"compaction-end":z.object({tokensBefore:v,tokensAfter:v,tokensSaved:v,strategy:z.enum(["no-op","summary","truncation"]),durationMs:v,summary:z.string().optional()}).strict(),"compaction-failed":z.object({reason:z.string()}).strict(),usage:z.object({messageId:z.string().min(1).optional(),inputTokens:v,outputTokens:v,totalTokens:v,cacheReadTokens:v.optional(),cacheCreationTokens:v.optional(),contextWindow:v,residentTokens:v,utilization:z.number().finite().min(0).max(1),costUsd:v.optional()}).strict(),"message-persisted":z.object({message:fs}).strict(),"message-updated":z.object({message:fs}).strict(),"todo-plan-update":z.object({plan:Xp}).strict(),"approval-context":z.object({approvalId:z.string(),toolCallId:z.string(),impact:hs.optional(),relaxableByAuto:z.boolean().optional()}).strict(),"session-state":z.object({state:z.object({phase:z.enum(["queued","running","parked","terminal"]),parkedOn:z.enum(["human","agents"]).optional(),humanRequestIds:z.array(z.string()).optional(),outcome:z.enum(["completed","failed","cancelled","timeout","expired"]).optional()}).strict(),version:z.number().int().positive(),updatedAt:z.string().datetime({offset:true})}).strict()};function em(e){return e in As}a(em,"isAgentUIDataName");function tm(e){return new h$1("Invalid agent UI message chunk",e.map(t=>({path:t.path.map(String),message:t.message,code:t.code})))}a(tm,"agentUIValidationError");function nm(e){if(typeof e!="object"||e===null||typeof e.type!="string")throw new h$1("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 h$1("Invalid agent UI message chunk",[{path:["type"],message:"Expected agent data chunk type",code:"invalid_value"}]);let n=t.slice(5);if(!em(n))throw new h$1("Invalid agent UI message chunk",[{path:["type"],message:`Unknown agent UI data type: ${n}`,code:"invalid_value"}]);let r=z.object({type:z.literal(`data-${n}`),id:z.string().optional(),data:As[n],transient:z.boolean().optional()}).strict().safeParse(e);if(!r.success)throw tm(r.error.issues);return r.data}a(nm,"assertCustomAgentUIMessageChunk");function yR(e,t,n){return nm({type:`data-${e}`,...n?.id!==void 0?{id:n.id}:{},data:t,...n?.transient!==void 0?{transient:n.transient}:{}})}a(yR,"agentDataChunk");function zi(e){return e}a(zi,"defineOperation");function V(e,t,n){let r=t==="atomic"?"none":t==="local"?"if-not-visible":"follow";return o=>{let a=n?.(o);return {impact:t,navigation:r,focus:{...e(o),...a===void 0?{}:{propertyPath:a}}}}}a(V,"definePresentation");function rm(e){return {id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon}}}a(rm,"toDraftableObject");function im(e){let t=e.id??e.name;return (e.attributes??[]).map(n=>Wi(n,t))}a(im,"toDraftableAttributes");function Z(e){return {id:e.id,name:e.name,label:e.label,type:e.attributeType,...e.config}}a(Z,"toAttribute");function Wi(e,t){let{id:n,name:r,label:o,type:a,...s}=e;return {id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:s}}a(Wi,"toDraftableAttribute");function xs(e){let t=e[0];return t?`{{ ${t.name} }}`:"{{ id }}"}a(xs,"draftedLabelExpression");function Gi(e,t){let n=t.filter(r=>r.objectId===e.id);return {id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},labelExpression:xs(n),attributes:n.map((r,o)=>{let a=Z(r);return a.order===void 0?{...a,order:o}:a})}}a(Gi,"draftedObjectDefinition");function om(e,t,n=Et(e.contents)){return structuredClone({...e,...t,authoring:n})}a(om,"toDraftableView");function ft(e){let{id:t,revision:n,contentIds:r,contentRevisions:o,derived:a,authoring:s,...c}=e;return structuredClone(c)}a(ft,"draftedViewDefinition");function am(e,t){return {...e,...ft(t)}}a(am,"fromDraftableView");var jt={id:z.string().min(1).describe("Your id, echoed back"),objectName:z.string().min(1).describe("Object"),viewName:z.string().min(1).describe("View API name")},bt={...jt,contentName:z.string().min(1).describe("Content API name")},Is=z.union([z.object({before:z.string().min(1).describe("Place immediately before this content name")}).strict(),z.object({after:z.string().min(1).describe("Place immediately after this content name")}).strict(),z.object({end:z.literal(true).describe("Place at the end of the placement zone")}).strict()]),Ge=a(e=>({objectName:e.objectName,viewName:e.viewName}),"viewFocus"),Me=a(e=>({...Ge(e),contentName:e.contentName}),"contentFocus");function pe(e,t){throw new h$1(t,[{path:e,message:t}])}a(pe,"invalid");function Ee(e,t,n,r){let o=e.views.findIndex(u=>u.object===t.objectName&&u.name===t.viewName);o<0&&pe(["viewName"],"View is not in the draftable state"),e.views[o].authoring||pe(["authoring"],"Missing view authoring baseline");let{derived:a,...s}=r(structuredClone(e.views[o]));s.contents=yi(s.authoring);let c=e.views.map((u,l)=>l===o?s:u);return Ai({extensions:[...n.extensions],objects:e.objects.map(u=>Gi(u,e.attributes.filter(l=>l.objectId===u.id))),views:c.map(ft)}),{...e,views:c}}a(Ee,"change");function Ke(e,t){let n=Object.hasOwn(e.authoring.contents,t)?e.authoring.contents[t]:void 0;return n||pe(["contentName"],"Content is not in the draftable state"),n}a(Ke,"contentState");function Ki(e,t,n){for(let r of n)e.authoring[r==="main"?"mainOrderCustomized":"asideOrderCustomized"]=true,t.filter(o=>o.placement===r).forEach((o,a)=>{Ke(e,o.name).workspacePosition=a;});}a(Ki,"setOrder");function Yi(e,t){let n=e.contents.find(r=>r.name===t);return n||pe(["contentName"],"Content is not in the draftable state"),n}a(Yi,"find");function Rs(e,t,n){let r=e.filter(s=>s.name!==t.name),o=r.filter(s=>s.placement===t.placement),a=o.length;if(!("end"in n)){let s="before"in n?n.before:n.after;a=o.findIndex(c=>c.name===s),a<0&&pe(["target"],"Order target is not in this placement"),"after"in n&&a++;}return o.splice(a,0,t),t.placement==="main"?[...o,...r.filter(s=>s.placement==="aside")]:[...r.filter(s=>s.placement==="main"),...o]}a(Rs,"placed");var sm=z.unknown().transform((e,t)=>{let n=W$1.safeParse(typeof e=="object"&&e!==null?{...e,name:"candidate"}:e);if(!n.success){for(let o of n.error.issues)t.addIssue({code:"custom",path:o.path,message:o.message});return z.NEVER}let r=typeof e=="object"&&e!==null&&"name"in e?e.name:void 0;return {...n.data,name:r}}),Cs=z.object({...bt,type:z.literal("replace_view_content"),definition:sm}).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}}),vs=W$1.describe("The whole content definition."),cm=z.object({...bt,type:z.literal("replace_view_content"),definition:vs}).strict().describe("definition.name, if sent, must equal contentName \u2014 the operation's own target; a different name is refused."),um={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:Cs,wire:cm,focus:Me,presentation:V(Me,"local"),describe:a(e=>`Replace ${e.objectName}.${e.viewName}.${e.contentName}`,"describe"),apply:a((e,t,n)=>Ee(e,t,n,r=>(Yi(r,t.contentName).placement!==t.definition.placement&&pe(["definition","placement"],"Use move_view_content to change placement"),Ke(r,t.contentName).workspaceDefinition=structuredClone(t.definition),{...r,contents:r.contents.map(a=>a.name===t.contentName?{...t.definition,name:t.contentName}:a),contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}})),"apply")},Es=z.object({...jt,type:z.literal("add_view_content"),content:vs,target:Is.describe("Where to place the new content within its placement zone")}).strict(),Ts=a(e=>({...Ge(e),contentName:e.content.name}),"addFocus"),lm={type:"add_view_content",summary:"Adds a content; content.name unique; collection view needs collection with source.object; aside holds one content, a form; target positions it among siblings.",schema:Es,focus:Ts,presentation:V(Ts,"structural"),describe:a(e=>`Add ${e.content.name}`,"describe"),apply:a((e,t,n)=>Ee(e,t,n,r$1=>{if(Object.hasOwn(r$1.authoring.contents,t.content.name))throw new r("content",t.content.name);r$1.authoring.contents={...r$1.authoring.contents,[t.content.name]:{sourceDefinition:null,workspaceDefinition:vt(t.content),suppressed:false,sourcePosition:null,workspacePosition:0}};let o=Rs(r$1.contents,t.content,t.target);return Ki(r$1,o,[t.content.placement]),{...r$1,revision:r$1.revision+1,contents:o,contentIds:{...r$1.contentIds,[t.content.name]:JSON.stringify(["draft-content",t.id])},contentRevisions:{...r$1.contentRevisions,[t.content.name]:1}}}),"apply")},Ns=z.object({...bt,type:z.literal("remove_view_content")}).strict(),dm={type:"remove_view_content",summary:"Removes a content; a published view keeps \u22651 main content; a code-declared content is hidden, not deleted.",schema:Ns,focus:Me,presentation:V(Me,"structural"),describe:a(e=>`Remove ${e.contentName}`,"describe"),apply:a((e,t,n)=>Ee(e,t,n,r=>{let o=Yi(r,t.contentName),a=Ke(r,t.contentName),s=r.contents.filter(d=>d.name!==t.contentName);if(Ki(r,s,[o.placement]),a.sourceDefinition!==null)return a.workspaceDefinition=null,a.suppressed=true,{...r,revision:r.revision+1,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}};delete r.authoring.contents[t.contentName];let{[t.contentName]:c,...u}=r.contentIds,{[t.contentName]:l,...m}=r.contentRevisions;return {...r,revision:r.revision+1,contents:r.contents.filter(d=>d.name!==t.contentName),contentIds:u,contentRevisions:m}}),"apply")},Ds=z.object({...bt,type:z.literal("move_view_content"),placement:z.enum(["main","aside"]).describe("The placement zone to move the content into"),target:Is.describe("Where to place the content within that placement zone")}).strict(),pm={type:"move_view_content",summary:"Reorders or moves a content to a different placement; the aside rule applies.",schema:Ds,focus:Me,presentation:V(Me,"structural"),describe:a(e=>`Move ${e.contentName}`,"describe"),apply:a((e,t,n)=>Ee(e,t,n,r=>{let o=Yi(r,t.contentName);o.placement!==t.placement&&(Ke(r,t.contentName).workspaceDefinition={...vt(o),placement:t.placement});let a=Rs(r.contents,{...o,placement:t.placement},t.target);return Ki(r,a,[...new Set([o.placement,t.placement])]),{...r,revision:r.revision+1,contents:a,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+ +(o.placement!==t.placement)}}}),"apply")},Os=z.object({...jt,type:z.literal("update_view_metadata"),changes:z.object({label:z.string().min(1).optional().describe("New label for the view"),description:z.string().optional().describe("New description for the view"),icon:t.nullable().optional().describe("New icon; null clears it")}).strict().refine(e=>Object.keys(e).length>0).describe("\u22651 change")}).strict(),mm={type:"update_view_metadata",summary:"Updates a view's label, description, or icon (null clears the icon).",schema:Os,focus:Ge,presentation:V(Ge,"atomic"),describe:a(e=>`Update ${e.viewName}`,"describe"),apply:a((e,t,n)=>Ee(e,t,n,r=>{let{icon:o,...a}=t.changes,s={...r,...a,revision:r.revision+1};if(o===null){let{icon:c,...u}=s;return u}return o===void 0?s:{...s,icon:o}}),"apply")},ks=z.string().refine(e=>e.trim().length>0,"API name must not be blank"),js=z.object({...jt,type:z.literal("rename_view"),newName:ks.describe("New API name for the view")}).strict(),ws=a(e=>({objectName:e.objectName,viewName:e.newName}),"renameViewFocus"),fm={type:"rename_view",summary:"Renames a view; refused on a code-declared name \u2014 change it in the declaration.",schema:js,focus:ws,presentation:V(ws,"structural"),describe:a(e=>`Rename view ${e.viewName} to ${e.newName}`,"describe"),apply:a((e,t,n)=>Ee(e,t,n,r=>t.newName===r.name?r:(r.authoring.origin==="code"&&pe(["newName"],"Source-owned API names must be changed in their declaration"),e.views.some(o=>o.object===t.objectName&&o.name===t.newName)&&pe(["newName"],"View API name is already used"),{...r,name:t.newName,revision:r.revision+1})),"apply")},_s=z.object({...bt,type:z.literal("rename_view_content"),newName:ks.describe("New API name for the content")}).strict(),Ss=a(e=>({...Ge(e),contentName:e.newName}),"renameContentFocus"),bm={type:"rename_view_content",summary:"Renames a content; refused on a code-declared name \u2014 change it in the declaration.",schema:_s,focus:Ss,presentation:V(Ss,"structural"),describe:a(e=>`Rename content ${e.contentName} to ${e.newName}`,"describe"),apply:a((e,t,n)=>Ee(e,t,n,r=>{let o=Ke(r,t.contentName);if(t.newName===t.contentName)return r;o.sourceDefinition!==null&&pe(["newName"],"Source-owned API names must be changed in their declaration"),Object.hasOwn(r.authoring.contents,t.newName)&&pe(["newName"],"Content API name is already used");let a=r.contentIds[t.contentName],s=r.contentRevisions[t.contentName];return delete r.authoring.contents[t.contentName],delete r.contentIds[t.contentName],delete r.contentRevisions[t.contentName],r.authoring.contents={...r.authoring.contents,[t.newName]:o},{...r,revision:r.revision+1,contentIds:{...r.contentIds,[t.newName]:a},contentRevisions:{...r.contentRevisions,[t.newName]:s+1}}}),"apply")},Ps=z.object({...bt,type:z.literal("reset_view_content")}).strict(),gm={type:"reset_view_content",summary:"Resets a content back to its code-declared source; only works when one exists.",schema:Ps,focus:Me,presentation:V(Me,"structural"),describe:a(e=>`Reset ${e.contentName} to source`,"describe"),apply:a((e,t,n)=>Ee(e,t,n,r=>{let o=Ke(r,t.contentName);return o.sourceDefinition===null&&pe(["contentName"],"Content has no source to reset to"),o.workspaceDefinition===null&&!o.suppressed&&o.workspacePosition===null?r:(o.workspaceDefinition=null,o.suppressed=false,o.workspacePosition=null,{...r,revision:r.revision+1,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}})}),"apply")},Ms=z.object({...jt,type:z.literal("reset_view_order"),placement:z.enum(["main","aside"]).describe("The placement zone to reset to source order")}).strict(),ym={type:"reset_view_order",summary:"Resets a placement zone's order to its code-declared source, if one exists.",schema:Ms,focus:Ge,presentation:V(Ge,"structural"),describe:a(e=>`Reset ${e.placement} order`,"describe"),apply:a((e,t,n)=>Ee(e,t,n,r=>{let o=t.placement==="main"?"mainOrderCustomized":"asideOrderCustomized";if(!r.authoring[o])return r;r.authoring[o]=false;for(let a of r.contents.filter(s=>s.placement===t.placement)){let s=Ke(r,a.name);s.sourceDefinition!==null&&(s.workspacePosition=null);}return {...r,revision:r.revision+1}}),"apply")},Hi=z.discriminatedUnion("type",[Cs,Es,Ns,Ds,Os,js,_s,Ps,Ms]),Ye=[um,lm,dm,pm,mm,fm,bm,gm,ym];function Fs(e,t){return e.objects.find(n=>n.id===t)}a(Fs,"findObject");var hm=new Set(["formula","rollup"]);function gt(e){return hm.has(e.attributeType)}a(gt,"isComputedAttribute");var Vs={sum:"number",avg:"number",count:"number",countValues:"number",countUniqueValues:"number",countEmpty:"number",percentEmpty:"number",percentNotEmpty:"number",earliest:"date",latest:"date",original:"multiselect"};function Am(e){return typeof e=="string"&&e in Vs?Vs[e]:void 0}a(Am,"rollupReturnTypeOf");function Ls(e,t){let n=Fs(e,t);if(!n)throw new h$1(`Object "${t}" is not in the draftable state`,[]);return n}a(Ls,"requireObject");function Rn(e){return e.config??{}}a(Rn,"configOf");function X(e){let t=Rn(e).targets;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.object=="string"):[]}a(X,"relationTargets");function yt(e){let t=X(e).filter(n=>n.object!==ae);return t.length===1?t[0]?.object:void 0}a(yt,"relationTargetObjectName");function xm(e){let t=Rn(e),n=e.attributeType,r={name:e.name,type:n,id:e.id},o=t.optionsSource;if(n==="relation"){let a=yt(e);return {...r,...t.cardinality==="one"||t.cardinality==="many"?{cardinality:t.cardinality}:{},...a===void 0?{}:{targetObjectName:a},targets:X(e)}}if(n==="formula")return {...r,...t.returnType===void 0?{}:{returnType:t.returnType},...o===void 0?{}:{optionsSource:o}};if(n==="rollup"){let a=Am(t.function);return {...r,...a===void 0?{}:{returnType:a},...o===void 0?{}:{optionsSource:o}}}return n==="select"||n==="status"||n==="multiselect"?{...r,...Array.isArray(t.options)?{options:t.options}:{}}:r}a(xm,"toCompileAttribute");function Bs(e,t){return {objectName:e.name,attributes:t.filter(n=>n.objectId===e.id).map(xm)}}a(Bs,"toCompileObject");function Ji(e,t){let n=Ls(e,t);return {...Bs(n,e.attributes),relatedObjects:Object.fromEntries(e.objects.map(r=>[r.name,Bs(r,e.attributes)]))}}a(Ji,"computedCompileSchemaOf");function Tm(e){return {id:e.id,name:e.name,label:e.label,type:"rollup",...Rn(e)}}a(Tm,"toRollupAttribute");function $s(e){try{return e()}catch(t){throw t instanceof I?new h$1(t.message,[]):t}}a($s,"asValidationError");function Cn(e,t){let n=Ji(e,t.objectId);return $s(()=>Us(t,n))}a(Cn,"computedPlanOf");function Us(e,t){if(e.attributeType==="rollup")return Ua(Tm(e),t);let n=Rn(e);return fn({attributeName:e.name,expression:String(n.expression??""),returnType:n.returnType,schema:t})}a(Us,"compilePlan");function Qi(e){$s(()=>Va(e.map(t=>({attributeName:t.attributeName,dependencies:t.dependencies}))));}a(Qi,"assertAcyclicComputed");function wm(e,t){switch(e.kind){case "local":case "computed":return e.attributeName===t;case "relation":return e.relationName===t;case "options":return false;default:return e}}a(wm,"dependencyNames");function _t(e,t){let n=Ji(e,t),r=[];for(let o of e.attributes)if(!(o.objectId!==t||!gt(o)))try{r.push(Us(o,n));}catch(a){if(!(a instanceof I))throw a}return r}a(_t,"compilablePlansOf");function Zi(e,t,n){let r=Ls(e,t),o=[];for(let a of _t(e,t))a.attributeName!==n&&a.dependencies.some(s=>wm(s,n))&&o.push(a.attributeName);for(let a of e.objects)if(a.id!==t)for(let s of _t(e,a.id))s.dependencies.some(u=>{if(u.kind!=="relation"||u.targetAttributeName!==n)return false;let l=e.attributes.find(m=>m.objectId===a.id&&m.name===u.relationName&&m.attributeType==="relation");return l!==void 0&&yt(l)===r.name})&&o.push(`${a.name}.${s.attributeName}`);return o}a(Zi,"dependentsOf");function Te(e){let t=e.config?.bilateral;if(typeof t!="object"||t===null)return;let{object:n,attribute:r}=t;return typeof n=="string"&&typeof r=="string"?{object:n,attribute:r}:void 0}a(Te,"bilateralDeclarationOf");function Sm(e,t){return t!==void 0&&e.attributeType===t.attributeType&&Im(e,t)}a(Sm,"sameAttribute");function Im(e,t){return JSON.stringify(e.config??{})===JSON.stringify(t.config??{})}a(Im,"sameConfig");function Rm(e,t){let n=a(r=>Sm(r,e.attributes.find(o=>o.id===r.id)),"untouched");for(let r of t.attributes){if(r.attributeType!=="relation")continue;let o=Te(r);if(o===void 0||n(r))continue;let s=t.objects.find(g=>g.id===r.objectId)?.name??r.objectId,c=t.objects.find(g=>g.name===o.object),u=t.attributes.find(g=>g.objectId===c?.id&&g.name===o.attribute),l=`relation "${s}.${r.name}" declares inverse "${o.object}.${o.attribute}"`;if(u===void 0)throw new h$1(`${l}, which object "${o.object}" does not have; draft it first`,[]);if(u.attributeType!=="relation")throw new h$1(`${l}, which is not a relation`,[]);let m=Te(u);if(!(X(u).some(g=>g.object===s)&&(n(u)?m===void 0||m.object===s&&m.attribute===r.name:m?.object===s&&m.attribute===r.name)))throw new h$1(`${l}, which does not point back to "${s}.${r.name}"`,[])}}a(Rm,"assertBilateralPairs");var Cm=0x100000001b3n,vm=0xffffffffffffffffn;function qs(e,t){let n=t;for(let r of new TextEncoder().encode(e))n^=BigInt(r),n=n*Cm&vm;return n}a(qs,"fnv1a64");function Xi(e,t){return vn(t,e.toLowerCase())}a(Xi,"viewIdFor");function vn(e,t){let n=`${t}:${e}`,r=qs(n,0xcbf29ce484222325n).toString(16).padStart(16,"0"),o=qs(`${e}:${n}`,0x84222325cbf29ce4n).toString(16).padStart(16,"0"),a=r+o,s=(Number.parseInt(a[16],16)&3|8).toString(16);return [a.slice(0,8),a.slice(8,12),`8${a.slice(13,16)}`,`${s}${a.slice(17,20)}`,a.slice(20,32)].join("-")}a(vn,"draftEntityIdFor");function He(e){return {list:Xi(e,"list"),detail:Xi(e,"detail")}}a(He,"defaultViewIdsFor");function eo(e,t,n,r){let a=r.filter(c=>c.objectId===n.id).filter(c=>j$1(Z(c)).presentation.formField).map(c=>({attribute:c.name})),s=e==="collection"?[{name:"all",type:"collection",placement:"main",label:"All",layout:"table",source:{object:n.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:t,object:n.name,name:e==="collection"?"default_list":"default_detail",label:n.label,context:e,default:true,contents:s,authoring:Et(s),revision:1,contentIds:Object.fromEntries(s.map(c=>[c.name,JSON.stringify(["draft-content",t,c.name])])),contentRevisions:Object.fromEntries(s.map(c=>[c.name,1])),derived:true}}a(eo,"derivedView");function to(e,t){let n=He(e.id);return [eo("collection",n.list,e,t),eo("record",n.detail,e,t)]}a(to,"defaultViewsFor");function Pt(e,t,n){return eo(e.context,e.id,t,n)}a(Pt,"regenerateDerived");function no(e){return e.attributeType==="relation"&&Z(e).metadata?.relationGenerated===true}a(no,"isGeneratedDraftRelation");function zs(e,t){let n=Te(t);if(!n)return [t];let r=e.objects.find(c=>c.id===t.objectId),o=e.objects.find(c=>c.name===n.object),a=e.attributes.find(c=>c.objectId===o?.id&&c.name===n.attribute);if(!a||a===t)return [t];let s=Te(a);return s&&s.object===r?.name&&s.attribute===t.name?[t,a]:[t]}a(zs,"pairedDraftAttributes");function ro(e,t,n,r,o=false){let a$1=Z(t),s=r&&Z(r),c=r&&Te(r),u=Te(t);if(c&&(c.object!==u?.object||c.attribute!==u?.attribute))throw new h$1("Changing a bilateral address requires removing the existing pair first",[]);if(a$1.type!=="relation"||!a$1.bilateral)return e;let l=e.objects.find(k=>k.id===t.objectId),m=e.objects.find(k=>k.name===a$1.bilateral?.object);if(!(l&&m))throw new h$1("Both objects must exist before materializing a relation pair",[]);let d=`${l.name}.${t.name}`,b=a$1.bilateral.attribute,g=`${m.name}.${b}`,y=e.attributes.find(k=>k.objectId===m.id&&k.name===b),A=s?.metadata?.relationPairId,h=typeof A=="string"?A:vn("relation-pair",`${n}:${t.id}`),j=[d,g].sort(),_=typeof A=="string"?{id:h,addresses:j,ownerAddress:s?.type==="relation"&&s.bilateral?.storageOwner===false?g:d,generatedAddresses:[],...d===g?{symmetric:true}:{}}:void 0,O=[...new Map([l,m].map(k=>[k.id,k])).values()].map(k=>({name:k.name,attributes:[t,...y&&y.id!==t.id?[y]:[]].filter(M=>M.objectId===k.id).map(Z)})),B=$i({objects:O,existingPairs:_?[_]:[],...r&&!o?{explicitAddresses:[d],propertyEditAddresses:[d]}:{},nextPairId:a(()=>h,"nextPairId")}),Se=new Map;for(let k of B.objects){let M=k.name===l.name?l.id:m.id;for(let oe of k.attributes){let ee=e.attributes.find($t=>$t.objectId===M&&$t.name===oe.name),Ie=ee?.id===t.id?r??ee:ee,pc={...Em(oe,ee&&Z(ee)),metadata:{...oe.metadata,...Ie&&no(Ie)&&!(o&&ee?.id===t.id)||!ee?{relationGenerated:true}:{}},id:ee?.id??vn("relation-attribute",`${h}:${M}:${oe.name}`),...ee?{}:{order:e.attributes.filter($t=>$t.objectId===M).length}};Se.set(`${M}.${oe.name}`,Wi(pc,M));}}let K=e.attributes.map(k=>{let M=`${k.objectId}.${k.name}`,oe=Se.get(M);return Se.delete(M),oe??k});return K.push(...Se.values()),{...e,attributes:K,views:e.views.map(k=>{let M=[l,m].find(oe=>oe.name===k.object);return k.derived&&M?Pt(k,M,K):k})}}a(ro,"reconcileDraftRelationAttribute");function Em(e,t){if(e.type!=="relation"||!e.bilateral||t?.type!=="relation"||!t.bilateral)return e;let{label:n,cardinality:r,...o}=e.bilateral;return {...e,bilateral:{...o,...t.bilateral.label===void 0?{}:{label:n},...t.bilateral.cardinality===void 0?{}:{cardinality:r}}}}a(Em,"preserveDeclarationHints");var io={id:z.string().min(1).describe("Your id, echoed back")};function Fe(e,t){let n=e.objects.find(r=>r.id===t);if(!n)throw new h$1(`Object "${t}" is not in the draftable state`,[]);return n}a(Fe,"requireObject");function oo(e,t,n){return {...e,attributes:[...n],views:e.views.map(r=>r.derived&&r.object===t.name?Pt(r,t,n):r)}}a(oo,"withDerivedViews");function En(e){return {objectId:e.objectId}}a(En,"objectFocus");function Nn(e){return {objectId:e.objectId,recordId:e.recordId}}a(Nn,"recordFocus");function Ws(e){return {objectId:e.objectId,attributeName:e.name}}a(Ws,"attributeFocus");function Dn(e){return {objectId:e.objectId,attributeName:e.attribute}}a(Dn,"existingAttributeFocus");function Dm(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}a(Dm,"firstChangedProperty");function Om(e,t){if(!e.derived)for(let n of e.contents){if(n.type==="collection"&&(n.columns?.includes(t)||n.displayAttributes?.includes(t)||n.sorts?.some(r=>r.attribute===t)))return `content "${n.name}"`;if(n.type==="form"&&n.groups.some(r=>r.fields.some(o=>o.attribute===t)))return `content "${n.name}"`;if(n.type==="richtext"&&(n.attribute===t||n.titleAttribute===t))return `content "${n.name}"`}}a(Om,"handShapedUse");function km(e,t,n){let r=n.config??{},o=n.name;if(r.relationPath!==void 0)throw new h$1(`rollup "${o}": relationPath is not supported yet`,[]);let a=r.relationAttribute;if(typeof a!="string"||a.length===0)throw new h$1(`rollup "${o}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let s=e.attributes.find(d=>d.objectId===t.id&&d.name===a&&d.attributeType==="relation");if(!s)throw new h$1(`rollup "${o}" needs a relation attribute; "${a}" is not a relation of object "${t.name}"`,[]);let c=yt(s);if(c===void 0){let d=X(s).filter(b=>b.object!=="*").length;throw new h$1(`rollup "${o}" needs a relation with one target object; "${a}" targets ${d}`,[])}if(r.function==="count")return;let u=e.objects.find(d=>d.name===c),l=r.targetAttribute;if(!(u!==void 0&&e.attributes.some(d=>d.objectId===u.id&&d.name===l)))throw new h$1(`rollup "${o}" targets attribute "${l}", which object "${c}" does not have`,[])}a(km,"assertRollupShape");function jm(e,t){let n=e.config??{};if(e.attributeType==="rollup")return n.relationAttribute===t;let r=typeof n.expression=="string"?n.expression:"";return new RegExp(`(^|[^A-Za-z0-9_])${t}\\.`).test(r)}a(jm,"traversesRelation");function Ys(e,t){let n=Fe(e,t.objectId);if(t.attributeType==="relation"){for(let o of X(t))if(o.object!==ae&&!e.objects.some(a=>a.name===o.object))throw new h$1(`object "${o.object}" is unknown; create it first`,[]);let r=Te(t)?.object;if(r!==void 0&&r!==ae&&!e.objects.some(o=>o.name===r))throw new h$1(`object "${r}" is unknown; create it first`,[]);for(let o of e.attributes)o.objectId!==t.objectId||!gt(o)||jm(o,t.name)&&Cn(e,o);}else if(gt(t))t.attributeType==="rollup"&&km(e,n,t),Cn(e,t);else return;Qi(_t(e,t.objectId));}a(Ys,"assertConfigFolds");var Je={...io,objectId:z.string().uuid().describe("The object this operation acts on")},_m=z.object({...Je,objectId:z.string().uuid().describe("Stable id for the new object; the server mints one when omitted"),type:z.literal("add_object"),name:i.describe("kebab-case plural API name (`purchase-orders`)"),label:z.string().min(1).describe("Label people see"),icon:z.string().min(1).optional().describe("Icon name")}),Pm={type:"add_object",summary:"Creates an object: kebab-case plural name, icon from search_icons; folds in default_list/default_detail; reserved names are native objects.",schema:_m,apply:a((e,t)=>{if(e.objects.some(r=>r.name===t.name))throw new h$1(`Object "${t.name}" already exists`,[]);if(e.objects.some(r=>r.id===t.objectId))throw new h$1(`Object id "${t.objectId}" is already taken`,[]);let n={id:t.objectId,name:t.name,label:t.label,...t.icon===void 0?{}:{icon:t.icon}};return {...e,objects:[...e.objects,n],views:[...e.views,...to(n,e.attributes)]}},"apply"),focus:En,presentation:V(En,"structural"),describe:a(e=>`Cr\xE9e l'objet \xAB ${e.label} \xBB`,"describe")},Mm=z.object({...Je,type:z.literal("update_object"),changes:z.object({label:z.string().min(1).optional().describe("New label"),icon:z.string().min(1).optional().describe("New icon name from search_icons")}).refine(e=>Object.keys(e).length>0,"update_object needs at least one change").describe("\u22651 change")}),Gs=a(e=>({objectId:e.objectId}),"updateObjectFocus"),Fm={type:"update_object",summary:"Updates an object's label and/or icon \u2014 no other field.",schema:Mm,apply:a((e,t)=>(Fe(e,t.objectId),{...e,objects:e.objects.map(n=>n.id===t.objectId?{...n,...t.changes}:n)}),"apply"),focus:Gs,presentation:V(Gs,"atomic",Dm),describe:a(e=>e.changes.label?`Renomme l'objet en \xAB ${e.changes.label} \xBB`:"Modifie l'objet","describe")},Vm=z.object({...Je,type:z.literal("remove_object")}),Bm={type:"remove_object",summary:"Removes an object; refused while a relation attribute targets it \u2014 remove it first.",schema:Vm,apply:a((e,t)=>{Fe(e,t.objectId);let n=e.objects.find(r=>r.id===t.objectId)?.name;for(let r of e.attributes){if(r.objectId===t.objectId||r.attributeType!=="relation"||!X(r).some(a=>a.object===n))continue;let o=e.objects.find(a=>a.id===r.objectId);throw new h$1(`object "${n}" is targeted by attribute "${o?.name}.${r.name}"; remove that attribute first`,[])}return {...e,objects:e.objects.filter(r=>r.id!==t.objectId),attributes:e.attributes.filter(r=>r.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(r=>r.objectId!==t.objectId),views:e.views.filter(r=>r.object!==n)}},"apply"),focus:En,presentation:V(En,"structural"),describe:a(e=>`Supprime l'objet ${e.objectId}`,"describe")},ao=Ht;function Hs(e,t){try{L$1(e,t);}catch(n){throw n instanceof h$1?new h$1(n.message,n.errors.map(r=>({...r,path:["config",...r.path??[]]}))):n}}a(Hs,"assertConfigParses");var Lm=z.object({...Je,type:z.literal("add_attribute"),attributeId:z.string().min(1),name:m,label:z.string().min(1),attributeType:z.enum(ao),config:z.record(z.string(),z.unknown()).optional()}).superRefine((e,t)=>{try{Hs(e.attributeType,e.config??{});}catch(n){if(n instanceof h$1){for(let r of n.errors)t.addIssue({code:"custom",message:r.message,path:[...r.path]});return}throw n}}),Ks={...io,type:z.literal("add_attribute"),attributeId:z.string().min(1).describe("Stable attribute id"),name:m.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),label:z.string().min(1).describe("Label people see")},so=Object.fromEntries(w.map(e=>[e,true])),On=["text","richtext","number","checkbox","date","phone","currency","location","user"],$m=z.object(On.reduce((e,t)=>(Object.assign(e,K$1(t).omit(so).shape),e),{})).strict(),Um=ao.filter(e=>!On.includes(e)),qm=Object.fromEntries(On.map(e=>[e,new Set(Object.keys(K$1(e).omit(so).shape))])),zm=x(qm,"config key");function Wm(e,t){zm(e.attributeType,e.config,t,["config"]);}a(Wm,"refuseForeignSimpleConfigKeys");function Gm(e){let t=K$1(e).omit(so);return (e==="relation"||e==="document"?t.extend({properties:G$1.optional()}):t).strict()}a(Gm,"wireConfigFor");var Km=z.discriminatedUnion("attributeType",[z.object({...Ks,objectId:z.string().uuid(),attributeType:z.enum(On).describe("Attribute type"),config:$m.optional().describe("Configuration of a simple attribute (text, number, date\u2026)")}).strict().superRefine(Wm),...Um.map(e=>z.object({...Ks,objectId:z.string().uuid(),attributeType:z.literal(e).describe("Attribute type"),config:Gm(e).optional().describe(`Configuration of a ${e} attribute`)}).strict())]),Ym={type:"add_attribute",summary:"Adds an attribute; relation/bilateral/rollup targets must pre-exist; no relationPath; formula needs returnType; cover new required attrs.",schema:Lm,wire:Km,apply:a((e,t)=>{let n=Fe(e,t.objectId),r=e.attributes.find(c=>c.objectId===t.objectId&&c.name===t.name);if(r&&!no(r))throw new h$1(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let o={id:r?.id??t.attributeId,objectId:t.objectId,name:t.name,label:t.label,attributeType:t.attributeType,...t.config===void 0?{}:{config:t.config}};for(let c of e.sampleRecords)c.objectId===t.objectId&&Zs(c.id,o,c.values);let a=r?e.attributes.map(c=>c===r?o:c):[...e.attributes,o],s=oo(e,n,a);return Ys(s,o),ro(s,o,t.id,r,true)},"apply"),focus:Ws,presentation:V(Ws,"local"),describe:a(e=>`Ajoute l'attribut \xAB ${e.label} \xBB`,"describe")},Js={...Je,attribute:m.describe("The attribute's API name on this object")};function Qs(e,t,n,r){let o=Fe(e,t);if(n===void 0)throw new h$1(`${r} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let a=e.attributes.find(s=>s.objectId===t&&s.name===n);if(!a)throw new h$1(`Attribute "${n}" is not on object "${t}"`,[]);return {object:o,attribute:a}}a(Qs,"requireAttribute");var Hm=z.object({...Js,type:z.literal("update_attribute"),changes:z.object({label:z.string().min(1).optional().describe("New label"),config:z.record(z.string(),z.unknown()).optional().describe("Whole config, replaced \u2014 same shape as add_attribute")}).refine(e=>Object.keys(e).length>0,"update_attribute needs at least one change").describe("\u22651 change")}),Jm={type:"update_attribute",summary:"Updates an attribute's label, or replaces its whole config; a published config can't change \u2014 add a new attribute and migrate values.",schema:Hm,apply:a((e,t)=>{let{object:n,attribute:r}=Qs(e,t.objectId,t.attribute,"update_attribute");t.changes.config!==void 0&&Hs(r.attributeType,t.changes.config);let o={...r,...t.changes},a=e.attributes.map(c=>c===r?o:c),s=oo(e,n,a);return Ys(s,o),ro(s,o,t.id,r)},"apply"),focus:Dn,presentation:V(Dn,"atomic"),describe:a(e=>e.changes.label?`Renomme l'attribut \xAB ${e.attribute} \xBB en \xAB ${e.changes.label} \xBB`:`Modifie l'attribut \xAB ${e.attribute} \xBB`,"describe")},Qm=z.object({...Js,type:z.literal("remove_attribute")}),Zm={type:"remove_attribute",summary:"Removes an attribute; refused while a sample carries its value, a content names it, or a formula/rollup depends on it \u2014 remove those first.",schema:Qm,apply:a((e,t)=>{let{attribute:n}=Qs(e,t.objectId,t.attribute,"remove_attribute"),r=zs(e,n);for(let s of r){let c=Fe(e,s.objectId),[u]=Zi(e,s.objectId,s.name);if(u!==void 0)throw new h$1(`attribute "${s.name}" is used by "${u}"; remove that first`,[]);for(let m of e.views){if(m.object!==c.name)continue;let d=Om(m,s.name);if(d!==void 0)throw new h$1(`attribute "${s.name}" is used by view "${m.id}" (${d}); remove it from the view first`,[])}let l=e.sampleRecords.find(m=>m.objectId===s.objectId&&s.name in m.values);if(l)throw new h$1(`Attribute "${s.name}" is still used by sample record "${l.id}"`,[])}let o=e.attributes.filter(s=>!r.includes(s)),a={...e,views:e.views.map(s=>s)};return r.reduce((s,c)=>oo(s,Fe(e,c.objectId),o),a)},"apply"),focus:Dn,presentation:V(Dn,"local"),describe:a(e=>`Supprime l'attribut \xAB ${e.attribute} \xBB`,"describe")};function Xm(e,t,n,r){let o=Z(n);try{c$1(o);}catch{return}let a=g$1(o,r);if(a.success)return;let s=a.errors??[],c=s.map(u=>u.path.length>1?`${u.path.join(".")}: ${u.message}`:u.message).join(", ");throw new h$1(`Sample record "${e}" has an invalid value for "${t}": ${c}`,s.map(u=>({path:u.path,message:u.message})))}a(Xm,"assertSampleValue");function Zs(e,t,n){if(t.config?.required===true&&t.config?.defaultValue===void 0&&!(t.name in n&&n[t.name]!==void 0))throw new h$1(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}a(Zs,"assertRequiredCovered");function co(e){return (Array.isArray(e)?e:[e]).flatMap(n=>{if(typeof n=="string")return [n];if(typeof n=="object"&&n!==null){let r=n.id;if(typeof r=="string")return [r]}return []})}a(co,"relationValueIds");function ef(e,t,n,r){n.attributeType!=="relation"||r===void 0||r===null||tf(e,t,yt(n),r);}a(ef,"assertUnknownSampleReference");function tf(e,t,n,r){let o=e.objects.find(s=>s.name===n);if(!o)return;let a=e.views.some(s=>s.id===He(o.id).list);for(let s of co(r)){let c=e.sampleRecords.find(l=>l.id===s);if(c?.objectId!==o.id&&(c!==void 0||a))throw new h$1(`sample record "${t}" references unknown sample "${s}"`,[])}}a(tf,"assertSampleTarget");var nf=z.object({...Je,type:z.literal("add_sample_record"),recordId:z.string().uuid().describe("Minted by the server when omitted"),values:z.record(z.string(),z.unknown()).describe("Attribute name \u2192 value; currency is `{code,value}`, relation is a record id or name minted here"),publication:z.enum(["preview","requested-data"]).optional().describe("preview = display-only; requested-data = real records asked for")}),rf={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:nf,apply:a((e,t)=>{if(Fe(e,t.objectId),e.sampleRecords.some(r=>r.id===t.recordId))throw new h$1(`Sample record "${t.recordId}" already exists`,[]);let n=new Map(e.attributes.filter(r=>r.objectId===t.objectId).map(r=>[r.name,r]));for(let[r,o]of Object.entries(t.values)){let a=n.get(r);if(!a)throw new h$1(`Sample record "${t.recordId}" uses unknown attribute "${r}"`,[]);if(gt(a))throw new h$1(`attribute "${a.name}" is computed and cannot be set on a sample record`,[]);ef(e,t.recordId,a,o),Xm(t.recordId,r,a,o);}for(let r of n.values())Zs(t.recordId,r,t.values);return {...e,sampleRecords:[...e.sampleRecords,{id:t.recordId,objectId:t.objectId,values:t.values,...t.publication===void 0?{}:{publication:t.publication}}]}},"apply"),focus:Nn,presentation:V(Nn,"local"),describe:a(()=>"Ajoute un exemple","describe")};function of(e,t){return new Set([...e.attributes.filter(n=>n.objectId===t&&n.attributeType==="relation").map(n=>n.name)])}a(of,"relationNamesOf");function af(e,t){for(let n of e.sampleRecords){if(n.id===t)continue;let r=of(e,n.objectId);for(let[o,a]of Object.entries(n.values))if(r.has(o)&&co(a).includes(t))throw new h$1(`sample record "${t}" is referenced by sample record "${n.id}"; remove that first`,[])}}a(af,"assertSampleNotReferenced");var sf=z.object({...Je,type:z.literal("remove_sample_record"),recordId:z.string().min(1).describe("recordId of the sample to remove")}),cf={type:"remove_sample_record",summary:"Removes a sample record; refused while another sample still references it.",schema:sf,apply:a((e,t)=>{if(!e.sampleRecords.some(n=>n.id===t.recordId&&n.objectId===t.objectId))throw new h$1(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,[]);return af(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(n=>n.id!==t.recordId)}},"apply"),focus:Nn,presentation:V(Nn,"local"),describe:a(()=>"Retire un exemple","describe")},Qe=[Pm,Fm,Bm,Ym,Jm,Zm,rf,cf];function uf(){let e=new Map;for(let t of [...Qe,...Ye]){if(e.has(t.type))throw new r("architect operation",t.type);e.set(t.type,t);}return e}a(uf,"build");var Mt=uf(),lf=[...Mt.keys()];function Ft(e){let t=Mt.get(e.type);if(!t)throw new h$1(`Operation "${e.id}" has unknown type "${e.type}"`,[]);return t}a(Ft,"defOf");function uo(e,t,n={extensions:[]}){return t.reduce((r,o)=>Ft(o).apply(r,o,n),e)}a(uo,"applyOperations");function lo(e){return Ft(e).focus(e)}a(lo,"focusOf");function df(e,t){return e.map(n=>Ft(n).describe(n,t))}a(df,"describeOperations");function pf(e){if(typeof e!="object"||e===null||!("type"in e))throw new h$1("An operation must be an object carrying a type",[]);let t=e.type;if(typeof t!="string")throw new h$1("An operation's type must be a string",[]);let n=Mt.get(t);if(!n)throw new h$1(`Unknown operation type "${t}"`,[]);let r=n.schema.safeParse(e);if(!r.success)throw new h$1(`Operation "${t}" is invalid: ${r.error.issues.map(o=>`${o.path.join(".")} ${o.message}`).join("; ")}`,[]);return r.data}a(pf,"parseOperation");var Vt=a(e=>z.tuple([z.literal(e),z.string()]),"pair"),mf=z.union([z.tuple([z.literal("content"),z.string(),z.string(),z.string()]),z.tuple([z.literal("view"),z.string(),z.string()]),z.tuple([z.literal("attribute"),z.string(),z.string()]),z.tuple([z.literal("sample"),z.string(),z.string()]),Vt("object"),Vt("object-name"),Vt("object-schema"),Vt("object-tree"),Vt("attribute-id")]);function Bt(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}a(Bt,"proposalTargetKey");function Xs(e,t,n,r){if(n&&typeof n=="object")if("source"in n&&n.source&&typeof n.source=="object"){let o=Wr(n.source);if(o&&o.kind!=="related"&&r(o.object),o?.kind==="related"){let a=o.relation;r(t);let s=e.objects.find(u=>u.name===t),c=e.attributes.find(u=>u.objectId===s?.id&&u.name===a);if(c?.attributeType==="relation"&&Array.isArray(c.config?.targets))for(let u of c.config.targets)u&&typeof u.object=="string"&&u.object!=="*"&&r(u.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);}a(Xs,"addContentDependencies");function ff(e,t,n,r,o){if(["add_attribute","update_attribute","remove_attribute"].includes(t.type)){let a=e.attributes.find(c=>c.objectId===n.objectId&&c.name===n.attributeName),s=r&&typeof r=="object"&&"bilateral"in r?r.bilateral:a?.config?.bilateral;if((t.attributeType==="relation"||a?.attributeType==="relation")&&s&&typeof s=="object"&&"object"in s&&typeof s.object=="string"){n.objectId&&o("object-tree",n.objectId);let c=e.objects.find(u=>u.name===s.object);c?o("object-tree",c.id):o("object-name",s.object);}}}a(ff,"addBilateralDependencies");function bf(e,t){let n=new Set,r=a((...a)=>n.add(JSON.stringify(a)),"add"),o=a(a=>{let s=e.objects.find(c=>c.name===a);s?r("object-schema",s.id):r("object-name",a);},"schemaFor");for(let a of t){let s=lo(a);if(a.type==="rename_view"||a.type==="rename_view_content"){let m=Hi.parse(a),d=Bt({objectName:m.objectName,viewName:m.viewName,...m.type==="rename_view_content"?{contentName:m.contentName}:{}});d&&n.add(d);}let c=Bt(s);if(c&&n.add(c),s.viewName&&s.objectName){a.type!=="replace_view_content"&&r("view",s.objectName,s.viewName);let m=e.objects.find(d=>d.name===s.objectName);if(m?r("object",m.id):r("object-name",s.objectName),Xs(e,s.objectName,a.definition??a.content,o),a.type==="reset_view_content"&&typeof a.contentName=="string"){let d=e.views.find(b=>b.object===a.objectName&&b.name===a.viewName);Xs(e,s.objectName,d?.authoring.contents[a.contentName]?.sourceDefinition,o);}}s.objectId&&r("object",s.objectId),s.objectId&&(a.type==="remove_object"||a.type.includes("sample_record"))&&r("object-tree",s.objectId),a.type==="add_object"&&typeof a.name=="string"&&r("object-name",a.name);let u=a.changes&&typeof a.changes=="object"?a.changes:null,l=a.type==="add_attribute"?a.config:u&&"config"in u?u.config:null;if(ff(e,a,s,l,r),l&&typeof l=="object"&&"targets"in l&&Array.isArray(l.targets))for(let m of l.targets)m&&typeof m.object=="string"&&m.object!=="*"&&r("object-name",m.object);}return [...n]}a(bf,"requiredTargetKeys");function gf(e,t){return Object.fromEntries(t.map(n=>[n,b$3(kn(e,n))]))}a(gf,"targetTokensFor");function kn(e,t){let n;try{n=JSON.parse(t);}catch{throw new h$1(`Invalid proposal target key "${t}"`,[])}let r=mf.safeParse(n);if(!r.success)throw new h$1(`Invalid proposal target key "${t}"`,[]);let[o,a,s,c]=r.data,u=e.objects.find(d=>d.id===a);if(o==="object")return u??null;if(o==="object-name")return e.objects.find(d=>d.name===a)??null;if(o==="attribute-id")return e.attributes.find(d=>d.id===a)??null;if(o==="attribute")return e.attributes.find(d=>d.objectId===a&&d.name===s)??null;if(o==="sample")return e.sampleRecords.find(d=>d.objectId===a&&d.id===s)??null;if(o==="object-schema"||o==="object-tree"){if(!u)return null;let d=e.attributes.filter(b=>b.objectId===a);return o==="object-schema"?{object:u,attributes:d.toSorted((b,g)=>b.name.localeCompare(g.name))}:{object:u,attributes:d,views:e.views.filter(b=>b.object===u.name),sampleRecords:e.sampleRecords.filter(b=>b.objectId===a)}}let l=e.views.find(d=>d.object===a&&d.name===s);if(!l)return null;if(o==="view")return {id:l.id,revision:l.revision,definition:{...ft(l),contents:l.contents.map(({name:d,placement:b})=>({name:d,placement:b}))}};let m=l.contents.find(d=>d.name===c);return c!==void 0&&Object.hasOwn(l.contentIds,c)?{id:l.contentIds[c],revision:l.contentRevisions[c],definition:m??null}:null}a(kn,"targetSnapshot");function Lt(e){return Ft(e).presentation(e)}a(Lt,"presentationOf");function yf(e){let t=e.map(Lt);return new Set(t.map(({focus:r})=>r.viewName?JSON.stringify([r.objectName,r.viewName]):r.objectId).filter(r=>r!==void 0)).size>1||t.some(({impact:r})=>r==="structural")?"structural":t.some(({impact:r})=>r==="local")?"local":"atomic"}a(yf,"episodeImpactOf");function ec(e,t){let n=Bt(t);return n===null?null:kn(e,n)}a(ec,"snapshotArchitectTarget");function hf(e,t,n={extensions:[]}){let r=e;return t.map(o=>{let a=Lt(o),s=ec(r,a.focus);r=uo(r,[o],n);let c=ec(r,a.focus);return {operationId:o.id,operationType:o.type,presentation:a,before:s,after:c}})}a(hf,"deriveArchitectChanges");var me=z.string().min(1),tc=z.union([z.object({objectName:me,viewName:me,contentName:me.optional()}).strict().describe("Full configuration of a view, or of one content when contentName is given"),z.object({objectId:me}).strict().describe("An object with its attributes, by id"),z.object({objectName:me}).strict().describe("An object with its attributes"),z.object({objectId:me,attributeName:me}).strict().describe("One attribute's config, by name"),z.object({objectId:me,attributeId:me}).strict().describe("One attribute's config, by id"),z.object({objectId:me,recordId:me}).strict().describe("One sample record")]);function Af(e){let t=tc.safeParse(e);if(!t.success)throw new h$1("Invalid scoped target",[{path:["target"],message:"Expected exactly one named target branch"}]);return t.data}a(Af,"parseNamedTarget");var po=z.object({type:z.literal("remove_operation"),operationId:z.string().min(1).describe("The id of a stored operation to drop from the draft")});function rc(e,t=[]){return [...e.map(n=>n.schema),...t].map(ic)}a(rc,"membersOf");function xf(e,t){return _n(e,n=>n.describe(t))}a(xf,"describeMember");function nc(e,t=[]){return [...e.map(o=>o.wire??o.schema),...t].map(ic).map(If).map(Cf).map((o,a)=>{let s=e[a];return s===void 0?o:xf(o,s.summary)})}a(nc,"wireMembersOf");function jn(e){return z.discriminatedUnion("type",e)}a(jn,"unionOf");function Tf(e){return e instanceof z.ZodString&&e.format==="uuid"}a(Tf,"isUuidString");function wf(e){let t=e;return !Array.isArray(t.options)||typeof t.def?.discriminator!="string"?null:{discriminator:t.def.discriminator,options:t.options}}a(wf,"asUnionMember");function _n(e,t){let n=wf(e);return n===null?t(e):z.discriminatedUnion(n.discriminator,n.options.map(t))}a(_n,"mapMember");function ic(e){return _n(e,t=>{let n={};for(let[r,o]of Object.entries(t.shape)){if(!Tf(o))continue;let a=z.string().min(1);n[r]=o.description===void 0?a:a.describe(o.description);}return Object.keys(n).length===0?t:t.safeExtend(n)})}a(ic,"relaxUuidKeys");var Sf={add_object:["objectId"],add_sample_record:["recordId"]};function If(e){return _n(e,t=>{let n={};for(let r of Sf[t.shape.type.value]??[]){let o=t.shape[r];o instanceof z.ZodString&&(n[r]=o.optional());}return Object.keys(n).length===0?t:t.safeExtend(n)})}a(If,"relaxMintedKeys");function Rf(e,t){let n=e._zod.def.checks;return !n||n.length===0?t:t.check(...n)}a(Rf,"withOriginalChecks");function Cf(e){return _n(e,t=>{if(t.shape.type.value==="add_object"||!("objectId"in t.shape))return t;let{objectId:n,...r}=t.shape,o=z.object({...r,objectName:z.string().min(1).describe("Object")}).strict();return Rf(t,o)})}a(Cf,"addressByName");var vf=rc(Qe,[po]),Ef=rc(Ye),oc=jn(vf),ac=jn(Ef),Nf={schema:oc,view:ac},Df={schema:jn(nc(Qe,[po])),view:jn(nc(Ye))},Of=new Map([...Qe.map(e=>[e.type,"schema"]),["remove_operation","schema"],...Ye.map(e=>[e.type,"view"])]);function kf(e){return Of.get(e)??null}a(kf,"familyOf");function Pn(e,t,n){return e.views.filter(r=>r.object===t.name&&r.context===n)}a(Pn,"viewsOf");function cc(e,t){return Pn(e,t,"collection").flatMap(n=>n.contents).filter(n=>n.type==="collection")}a(cc,"collectionContentsOf");function uc(e,t){return e.attributes.filter(n=>n.objectId===t.id)}a(uc,"ownAttributes");function jf(e){return j$1(Z(e)).presentation.tableCell}a(jf,"isTableCell");function sc(e,t,n){return Pn(e,t,"record").some(r=>r.contents.some(o=>o.type===n))}a(sc,"hasRecordContent");function lc(e,t){return e===2&&t<=5}a(lc,"isEdgePayload");function _f(e,t){let n=uc(e,t),r=n.filter(o=>o.attributeType==="relation");return lc(r.length,n.length)?!e.attributes.some(o=>o.attributeType==="relation"&&o.objectId!==t.id&&X(o).some(a=>a.object===t.name)):false}a(_f,"looksLikeEdge");function Pf(e,t,n){return Pn(e,n,"record").some(r=>r.contents.some(o=>o.type==="collection"&&o.source.relation===t.name))}a(Pf,"reciprocalExists");function Mf(e,t){let n=[],r=t?e.objects.filter(o=>t.has(o.id)):e.objects;for(let o of r){if(_f(e,o)){n.push(`Object "${o.label}" is an edge (two relations plus scalars): qualify a relation with config.properties.definitions instead of an object.`);continue}let a=cc(e,o);a.length===0&&n.push(`Object "${o.label}" has no collection content: add_view_content.`);for(let s of uc(e,o))if(jf(s)&&a.length&&!a.some(c=>c.columns===void 0||c.columns.includes(s.name))&&n.push(`Attribute "${s.label}" on "${o.label}" is in no collection column set: replace_view_content.`),s.attributeType==="document"&&!sc(e,o,"documents")&&n.push(`Object "${o.label}" has no documents content: add_view_content.`),s.attributeType==="relation")for(let{object:c}of X(s)){let u=e.objects.find(l=>l.name===c);u&&!Pf(e,s,u)&&n.push(`Relation "${s.label}" on "${o.label}" has no reciprocal collection on "${u.label}": add_view_content with source.relation.`);}Pn(e,o,"record").length&&!sc(e,o,"activity")&&n.push(`Object "${o.label}" has no activity content on its record view: add_view_content.`),a.length===1&&n.push(`Object "${o.label}" has a single collection content; a person would add one to three that answer a question: add_view_content.`);}return n}a(Mf,"stillMissing");function Ff(e,t){let n=new Set(t.flatMap(r=>r.type==="add_attribute"&&typeof r.attributeId=="string"?[r.attributeId]:[]));return e.attributes.filter(r=>n.has(r.id))}a(Ff,"addedAttributes");function Vf(e,t){let n={next:[],needsColumns:[],regenerated:[]},r=new Set;for(let o of Ff(e,t)){let a=e.objects.find(l=>l.id===o.objectId);if(!a)continue;let s=e.views.filter(l=>l.object===a.name);if(!r.has(a.id)){r.add(a.id);for(let l of s.filter(m=>m.derived))for(let m of l.contents)n.regenerated.push(`${l.name}.${m.name}`);}for(let l of s.filter(m=>!m.derived&&m.context==="collection"))for(let m of l.contents)m.type==="collection"&&m.columns!==void 0&&!m.columns.includes(o.name)&&n.needsColumns.push({view:l.name,content:m.name,attribute:o.name});let c=s.some(l=>l.context==="record"&&l.contents.some(m=>m.type==="documents")),u=s.find(l=>l.context==="record");o.attributeType==="document"&&u&&!c&&n.next.push({type:"add_view_content",objectName:a.name,viewName:u.name,content:{name:"documents",type:"documents",placement:"main",label:"Documents"},target:{end:true}});}return n}a(Vf,"guidanceForBatch");function Bf(e,t){let n=new Map(e.objects.map(o=>[o.name,o.id])),r=new Set;for(let o of t){let{focus:a}=Lt(o),s=a.objectId??(a.objectName?n.get(a.objectName):void 0);s!==void 0&&r.add(s);}return r}a(Bf,"touchedObjectIds");function Lf(e){let t=e.config??{};if(e.attributeType==="relation")return `\u2192 ${X(e).map(n=>n.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})`}a(Lf,"attributeDetail");function $f(e){let t=Qt({properties:e.config?.properties});if(t.length!==0)return t.map(n=>`${n.name}: ${n.type}`)}a($f,"propertyLines");function Uf(e){let t=e.config?.options,n=Lf(e),r=$f(e);return {name:e.name,label:e.label,type:e.attributeType,...Array.isArray(t)?{options:t.map(o=>o.value)}:{},...n===void 0?{}:{detail:n},...r===void 0?{}:{properties:r}}}a(Uf,"summarizeAttribute");function qf(e,t,n){let r=He(e.id),o=n.some(a=>a.id===r.list);return {id:e.id,name:e.name,label:e.label,attributes:t.filter(a=>a.objectId===e.id).map(Uf),...o?{viewIds:r}:{}}}a(qf,"summarizeObject");function zf(e,t){if(!t.some(n=>n.name===e.object))throw new h$1(`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===true,contents:e.contents.map(({name:n,type:r,placement:o,label:a})=>({name:n,type:r,placement:o,label:a}))}}a(zf,"summarizeView");function Wf(e,t){let n=new Map;for(let r of e.sampleRecords)n.set(r.objectId,(n.get(r.objectId)??0)+1);return {objects:e.objects.map(r=>qf(r,e.attributes,e.views)),views:e.views.map(r=>zf(r,e.objects)),sampleRecords:[...n.entries()].map(([r,o])=>({objectId:r,count:o})),operationCount:t}}a(Wf,"summarizeDraft");var Gf=["draft_schema"],Kf="publish_architect_draft",Yf="discard_architect_draft",Hf="request_design_review",Jf="get_architect_draft";var Qf=[{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\xE9",color:"blue"},{value:"accepted",label:"Accept\xE9",color:"green"}]}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:"add_view_content",id:"op-open",objectName:"devis",viewName:"default_list",content:{name:"open",label:"\xC0 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:true}}],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:{}}}}];var re=z.string().refine(e=>e.trim().length>0,"Must not be blank"),dc=z.union([z.tuple([z.literal("object"),re]),z.tuple([z.literal("attribute"),re,re]),z.tuple([z.literal("view"),re,re]),z.tuple([z.literal("content"),re,re,re])]),Zf=z.object({label:re,pluralLabel:z.string().optional(),description:z.string().optional(),icon:t.optional(),labelExpression:z.string(),embeddingExpression:z.string().optional(),sealed:z.boolean().optional(),toleratedAttributes:z.array(re).optional(),metadata:z.record(z.string(),z.unknown()).optional(),schema_version:z.number().int().nonnegative(),migrations:z.array(z.record(z.string(),z.unknown())),documentLayout:z.record(z.string(),z.unknown()).optional()}).strict();function Ze(e){throw new h$1(e,[])}a(Ze,"failure");function Xf(e){return z.custom(t$1=>{let n=z.record(z.string(),z.unknown()).parse(t$1);for(let r of e[0]==="view"?["object","name"]:["name"])Object.hasOwn(n,r)&&Ze(`Invalid schema state: unrecognized definition key ${r}`);switch(e[0]){case "object":Zf.parse(n);break;case "attribute":{let r=z.enum(Ht).parse(n.type);I$1(r).extend({type:z.literal(r),label:re,required:z.boolean().optional(),unique:z.boolean().optional(),icon:t.optional()}).strict().parse(n);break}case "view":{let{contents:r,...o}=n,a=z.array(re).parse(r);new Set(a).size!==a.length&&Ze("Invalid schema state: duplicate content membership"),Z$1.parse({...o,object:e[1],name:e[2],contents:[]});break}case "content":W$1.parse({...n,name:e[3]});break}return true})}a(Xf,"definitionSchema");function Mn(e,t){let n=JSON.stringify(e.address),r=JSON.stringify(t.address);return n<r?-1:n>r?1:0}a(Mn,"compareSchemaStateEntries");function eb(e){return {modelVersion:1,hashVersion:1,entries:[...e].sort(Mn).filter(t=>t.source!==null).map(({address:t,source:n})=>({address:t,source:n}))}}a(eb,"schemaStateSourcePayload");function tb(e){let t=z.record(z.string(),z.unknown()).parse(e);for(let[a,s]of [["modelVersion","model"],["hashVersion","hash"]])t[a]!==1&&Ze(`Unsupported schema ${s} version: expected 1, received ${t[a]===void 0?"missing":String(t[a])}`);let n=z.object({modelVersion:z.literal(1),hashVersion:z.literal(1),tenant:re,sourceFingerprint:z.string().regex(/^[a-f0-9]{64}$/),entries:z.array(z.unknown())}).strict().safeParse(e);if(!n.success){let a=n.error.issues.find(s=>s.code==="unrecognized_keys");throw a?.code==="unrecognized_keys"&&Ze(`Invalid schema state: unrecognized key ${a.keys[0]}`),h$1.fromZodErrors(n.error.issues.map(s=>({path:s.path.map(String),message:s.message})))}let r=new Set,o=n.data.entries.map(a=>{let s=dc.parse(z.object({address:z.unknown()}).parse(a).address),c=JSON.stringify(s);r.has(c)&&Ze(`Invalid schema state: duplicate address ${c}`),r.add(c);let u=Xf(s).nullable(),l=s[0]==="object"||s[0]==="attribute"?z.object({id:z.string().uuid(),updatedAt:z.string().datetime()}).strict():z.object({id:z.string().uuid(),revision:z.number().int().nonnegative()}).strict(),m=z.object({address:dc,source:u,effective:u,status:z.enum(["source","runtime","copy","suppressed"]),sourceOwner:z.union([z.literal("core"),z.string().regex(/^(bundle|source):.+$/)]).nullable(),guard:l.nullable()}).strict().parse(a);(m.status==="runtime"&&(m.source!==null||m.effective===null||m.sourceOwner!==null)||m.status==="suppressed"&&(s[0]!=="content"||m.source===null||m.effective!==null||m.guard===null)||m.status==="copy"&&(m.source===null||m.effective===null)||m.effective!==null&&m.guard===null||m.source===null&&m.effective===null)&&Ze(`Invalid schema state: inconsistent status at ${c}`);let d=m.sourceOwner;d!==null&&d!=="core"&&!d.startsWith("bundle:")&&!d.startsWith("source:")&&Ze("Invalid source owner");let b=d===null||d==="core"?d:d.startsWith("bundle:")?`bundle:${d.slice(7)}`:`source:${d.slice(7)}`;return {...m,sourceOwner:b}});return {...n.data,entries:o.sort(Mn)}}a(tb,"parseState");function nb(e){try{return tb(e)}catch(t){throw t instanceof z.ZodError?h$1.fromZodErrors(t.issues.map(n=>({path:n.path.map(String),message:n.message}))):t}}a(nb,"parseSchemaState");function rb(e){let t=[];for(let n of [...e.entries].sort(Mn)){let r=n.source===null?"added":n.status==="suppressed"?"suppressed":n.effective===null?"removed":b$3(n.source)!==b$3(n.effective)?"changed":n.status==="copy"?"copied":null;r&&t.push({...n,change:r});}return {modelVersion:1,tenant:e.tenant,sourceFingerprint:e.sourceFingerprint,changes:t}}a(rb,"diffSchemaState");export{aS as AGENT_UI_BATCH_MAX_BYTES,sS as AGENT_UI_BATCH_MAX_ITEMS,Qo as ALLOWED_PROPERTY_TYPES,Yn as ALL_ACTIONS,lf as ALL_OPERATION_TYPES,QA as ALL_SYSTEM_RESOURCES,Dy as ARTIFACT_FILE_ROLES,Ey as ARTIFACT_KINDS,Cl as ARTIFACT_LIST_VIEW,Il as ARTIFACT_OBJECT,ct as ARTIFACT_OBJECT_NAME,ha as ARTIFACT_PREVIEW_EXTENSION,Ny as ARTIFACT_RETENTIONS,Rl as ARTIFACT_VIEW,Ht as ATTRIBUTE_TYPES,Gg as AUDIT_ACTIONS,Wg as AUDIT_RESOURCE_TYPES,Zn as AgentBuilder,Mg as BEHAVIOR_PROPERTIES,uu as BYTE_UNIT_LABELS,Hc as CLAIMABLE_SESSION_STATUSES,Ot as COMPUTED_FUNCTIONS,US as COMPUTED_FUNCTION_METADATA,SS as COMPUTED_FUNCTION_NAMES,bI as CONNECTOR_CALLBACK_PARAM,Ho as COUNT_MODES,I as ComputedFormulaCompileError,ce as ContentBuilder,HA as DB_COLUMN_FIELDS,sa as DEFAULT_AGENT_EXECUTION_CONFIG,Bo as DEFAULT_APPROVAL_POLICY,Cy as DEFAULT_DICTATION_LIMITS,ea as DEFAULT_LABEL_FALLBACK,iu as DEFAULT_MEETING_BOT_DISPLAY_NAME,Bu as DEFAULT_ROLES,ex as DEFAULT_ROLE_DESCRIPTIONS,XA as DEFAULT_ROLE_LABELS,tx as DEFAULT_ROLE_PERMISSIONS,ah as DEFAULT_TENANT_SETTINGS,Iy as DICTATION_FINALIZATION_TIMEOUT_MS,hy as DICTATION_FRAME_BYTES,xy as DICTATION_MAX_BUFFER_BYTES,Ay as DICTATION_MAX_FRAME_BYTES,Ty as DICTATION_MAX_TRANSCRIPT_BYTES,Ry as DICTATION_MODEL_ID,Sy as DICTATION_PREPARATION_TIMEOUT_MS,yy as DICTATION_SAMPLE_RATE,wy as DICTATION_TICKET_TTL_MS,Yf as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,mA as DOCUMENT_SYSTEM_ATTRIBUTES,ao as DRAFTABLE_ATTRIBUTE_TYPES,Qf as DRAFT_SCHEMA_INPUT_EXAMPLES,Gf as DRAFT_WRITE_TOOL_NAMES,wl as DRIVE_LIST_VIEW,xl as DRIVE_OBJECT,st as DRIVE_OBJECT_NAME,Tl as DRIVE_VIEW,Xt as EMPTY_VALUE_PLACEHOLDER,bh as ESTIMATED_COUNT_CAP,EI as FAKE_MEETING_BOT_SIGNATURE_HEADER,Nf as FAMILY_INPUTS,Df as FAMILY_WIRE_INPUTS,Wn as FORM_FORBIDDEN_ATTRIBUTE_TYPES,Ct as FlagRegistry,un as FlagService,Vr as FormBuilder,Nt as FormRegistry,Mr as FormRowBuilder,Fr as FormStepBuilder,Jf as GET_ARCHITECT_DRAFT_TOOL_NAME,Gr as GroupBuilder,Pg as IDENTITY_PROPERTIES,dh as IMAGE_FORMATS,Uo as INFERENCE_REASONING_OPTIONS,$o as INFERENCE_SPEEDS,Fl as LIVE_EVENT_TYPES,Cp as MAILBOX_LIST_MODES,wI as MAIL_DRAFT_BODY_MAX_CHARS,SI as MAIL_SUBJECT_MAX_CHARS,Wo as MAX_PRESET_DEPTH,sy as MAX_TODOS,uy as MAX_TODO_DESCRIPTION_CHARS,cy as MAX_TODO_ID_CHARS,C as MEETING_ATTRIBUTES,wa as MEETING_DETAIL_VIEW_ID,Nl as MEETING_LIST_VIEW,xa as MEETING_LIST_VIEW_ID,vl as MEETING_OBJECT,ut as MEETING_OBJECT_NAME,El as MEETING_VIEW,Ta as MEETING_WRITE_SOURCE,Al as MEMORY_LIST_VIEW,yl as MEMORY_OBJECT,hl as MEMORY_VIEW,Rp as McpOAuthCompletionMode,mr as MultiRelationAttributeBuilder,Zc as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,Xc as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,Po as NOTIFICATION_INBOX_STATES,ko as NOTIFICATION_KINDS,jo as NOTIFICATION_PRIORITIES,_o as NOTIFICATION_SENSITIVITIES,jg as NOTIFICATION_TYPES_V1,Kc as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,Wc as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,Gc as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,Mo as NOTIFICATION_WORK_STATES,NI as NO_RECORDING,Yo as NoopGeocodingAdapter,Jc as OPEN_TOOL_PART_STATES,Mt as OPERATION_REGISTRY,wn as OPERATOR_SPECS,St as ObjectBuilder,Fg as PRESENTATION_PROPERTIES,Lo as PROVIDER_NAMES,Kf as PUBLISH_ARCHITECT_DRAFT_TOOL_NAME,xA as QUALIFIED_SEPARATOR,hh as QUOTA_KEYS,CI as RECORDING_OVERRIDES,vI as RECORDING_POLICIES,oa as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,ae as RELATION_TARGET_ANY,po as REMOVE_OPERATION_SCHEMA,vp as REPLY_MODES,Hf as REQUEST_DESIGN_REVIEW_TOOL_NAME,Qe as SCHEMA_OPERATIONS,oc as SCHEMA_OPERATION_INPUT,de as SCHEMA_PLAN_LIMITS,Mi as SCHEMA_SOURCE_ID_PATTERN,my as SESSION_STATE_STREAM_ID,Yc as SESSION_TERMINAL_STATUSES,ga as SKILL_CONTENT_TEMPLATE,fl as SKILL_LIST_VIEW,pl as SKILL_OBJECT,ml as SKILL_VIEW,$u as STANDARD_SCHEMA_VENDOR,zn as SYSTEM_PART_CODES,te as SYSTEM_RESOURCES,ZA as SYSTEM_RESOURCE_LABELS,pr as SingleRelationAttributeBuilder,ts as TODAY_DEFAULT,ey as TODO_PLAN_STATUSES,ay as TODO_STATUSES,qo as TOOL_APPROVAL_STATES,ch as USER_STATUSES,uh as USER_WORK_POSTURES,Ye as VIEW_OPERATIONS,ac as VIEW_OPERATION_INPUT,sn as ViewBuilder,eh as accessLevelToActions,Xy as actionsToAccessLevel,cx as agent,yR as agentDataChunk,ty as agentDisplayName,fR as agentInferencePreferencesSchema,Yp as agentMessageAttachmentSchema,Kp as agentMessagePartSchema,Gp as agentSessionInferenceOverridesInputSchema,bR as agentSessionInferenceOverridesSchema,fs as agentSessionMessageSchema,tm as agentUIValidationError,uo as applyOperations,Xo as applyPipes,Ou as applyRelationProps,dS as architectDraftChannelKey,Qi as assertAcyclicComputed,Va as assertAcyclicComputedDependencies,Rm as assertBilateralPairs,nm as assertCustomAgentUIMessageChunk,Dp as assertSchemaSourceId,Te as bilateralDeclarationOf,nl as booleanFlag,rs as buildAgentFallbackTitle,Vu as buildPermissionFlags,Zt as buildPropertySchema,wA as buildQualifiedAttribute,Hi as canonicalViewOperationSchema,ca as checkbox,rR as collectSchemaReferences,cc as collectionContentsOf,qe as collectionSourceAddress,Wr as collectionSourceAddressOf,Qc as compareAgentSessionMessages,Mn as compareSchemaStateEntries,_t as compilablePlansOf,fn as compileComputedFormula,Ua as compileRollupAttribute,cu as computeByteMagnitude,Ji as computedCompileSchemaOf,Cn as computedPlanOf,E as content,Sa as contentDefinition,Np as conversationDisplayTitle,sl as createFlagRegistry,ul as createFlagService,nn as createStandardSchemaProps,Tx as currency,As as customDataChunkSchemas,se as date,Sn as dateInTimezone,tt as dateValueStart,He as defaultViewIdsFor,to as defaultViewsFor,zi as defineOperation,V as definePresentation,Zi as dependentsOf,hf as deriveArchitectChanges,dI as deriveCreateDefaultsFromFilters,Mu as deriveInitials,df as describeOperations,cs as destructiveSchema,ge as detailView,rb as diffSchemaState,ua as document,xs as draftedLabelExpression,Gi as draftedObjectDefinition,ft as draftedViewDefinition,Qp as durableDateSchema,yf as episodeImpactOf,FS as evaluateComputedAst,VS as evaluateComputedFormula,BS as evaluateComputedFormulaWithResult,hp as evaluateFilterState,rI as evaluateRecordFilterState,wt as extractAttributeNames,ia as extractValueRefs,kf as familyOf,Ia as findRelationAttribute,al as flagRegistry,lo as focusOf,_x as form,ru as formFieldFlatKey,nu as formFieldKey,va as formRegistry,nS as formatAgentStreamFrameId,Zo as formatAttributeValue,lA as formatByteSize,mp as formatComputedResult,gu as formatLocationValue,Cx as formula,am as fromDraftableView,Nu as getEditableLabelAttribute,jy as getErrorMessage,AS as getLiveProtocolPayloadChannel,Fu as getRecordCreatorPrincipalId,ra as getSingleAttributeFromExpression,Ko as getSlotFieldTargets,_u as getUserDisplayName,he as group,Vf as guidanceForBatch,MI as hasDestructiveEntries,rh as hasOptions,ys as imageModelIdSchema,rt as includesAction,Vo as inferInverseCardinality,Xd as inferRollupReturnType,qi as inferenceReasoningSchema,Ui as inferenceSpeedSchema,em as isAgentUIDataName,cS as isAgentUIMessageBatch,Ug as isAttributeSortable,$g as isBilateralRelation,GS as isCheckboxEquality,Xg as isClaimableSessionStatus,gt as isComputedAttribute,pn as isComputedFunctionName,Oe as isDateRangeValue,nx as isDefaultRole,fA as isDocumentAttribute,lc as isEdgePayload,au as isEmptyObject,Fy as isFormDefinition,Jt as isFormFieldsRow,Gn as isFormFreeFieldRef,zy as isFormHeadingRow,Wy as isFormSeparatorRow,Go as isFormSlotFieldRef,Gy as isFormTextRow,tn as isLabelExpression,xS as isLiveEventEnvelope,bS as isLiveEventPayload,Gl as isLiveEventPayloadForType,Wl as isLiveEventType,AI as isMailProvider,xI as isMailboxListMode,Jo as isNotEmpty,ny as isOpenToolPartState,Ka as isPlainRecord,TI as isReplyMode,dx as isStandardSchema,iy as isSystemPartCode,Zg as isTerminalSessionStatus,Hg as isTerminalState,ry as isToolApprovalState,Fo as isUniversalRelation,ol as jsonFlag,Qg as legacyStatusToSessionState,ye as listView,Na as liveChannelKey,Ix as location,bA as matchesAccepts,Hp as mentionReferenceSchema,Jp as modelDefinitionSchema,gs as modelReferenceSchema,Sx as multiselect,tc as namedTargetSchema,tu as nativeAgentUIPartIdMetadataKey,lu as normalizeDateValue,on as number,il as numberFlag,Kx as object,oy as orderAgentSessionMessages,rS as parseAgentStreamFrameId,ou as parseCountMode,Da as parseLiveChannelKey,Af as parseNamedTarget,fy as parseNativeAgentUIPartIdsMetadata,pf as parseOperation,fh as parseOptionalCountMode,TA as parseQualifiedAttribute,nb as parseSchemaState,HI as persistedSchemaPlanSchema,xx as phone,jp as plannedAttributeSchema,_p as plannedInlineAttributeSchema,Pp as plannedObjectSchema,Lt as presentationOf,Bt as proposalTargetKey,bs as providerNameSchema,ju as qualifiedPropertyDefs,$y as readFormFieldValue,$i as reconcileRelationAttributes,Pt as regenerateDerived,qT as registry,it as relation,hi as relationAcceptsObject,fT as relationProperty,ku as relationPropertyDefs,yt as relationTargetObjectName,X as relationTargets,Lg as relationTargetsOf,co as relationValueIds,Jn as renderLabelExpression,fI as requestedCapabilities,It as requireRecordContentContext,Ra as requireSingleRelationTarget,bf as requiredTargetKeys,Sp as resolveAttributeDefaultValue,Wu as resolveCollectionActions,zu as resolveContentNavigation,Ly as resolveFieldRequired,Qt as resolvePropertyDefinitions,yi as resolveViewContents,ke as richtext,vx as rollup,Zd as rollupToFormulaExpression,YI as schemaPlanSchema,eb as schemaStateSourcePayload,fe as select,gR as sessionInferencePatchSchema,Jg as sessionStateToLegacyStatus,wx as status,Mf as stillMissing,vt as storedContentDefinition,rl as stringFlag,Wf as summarizeDraft,kn as targetSnapshot,gf as targetTokensFor,S as text,Z as toAttribute,im as toDraftableAttributes,rm as toDraftableObject,om as toDraftableView,su as toUndefinedIfEmpty,Zp as todoItemSchema,Xp as todoPlanSchema,hs as toolImpactSchema,Bf as touchedObjectIds,Rx as user,Ai as validateContentViewCatalogue,Su as validateLabelExpression,qu as validateObjectExpressions,Xi as viewIdFor,fi as viewIdentityKey,Dl as viewRegistry,Et as workspaceViewAuthoring};
|
|
48
|
+
{{ summary }}`).attribute(S({name:C.title,label:"Title"}).required()).attribute(je({name:C.description,label:"Description"})).attribute(je({name:C.summary,label:"Summary"}).hidden()).attribute(je({name:C.transcript,label:"Transcript"}).hidden()).attribute(S({name:C.location,label:"Location"})).attribute(se({name:C.startsAt,label:"Starts at"}).includeTime()).attribute(se({name:C.endsAt,label:"Ends at"}).includeTime()).attribute(ua({name:C.isAllDay,label:"All day"})).attribute(fe({name:C.status,label:"Status"}).options([{value:"confirmed",label:"Confirmed"},{value:"tentative",label:"Tentative"},{value:"cancelled",label:"Cancelled"}])).attribute(S({name:C.organizerAddress,label:"Organizer address"}).email()).attribute(S({name:C.organizerName,label:"Organizer"})).attribute(S({name:C.conferenceProvider,label:"Conference provider"})).attribute(S({name:C.conferenceJoinUrl,label:"Join link"}).url()).attribute(S({name:C.htmlLink,label:"Open in calendar"}).url()).attribute(S({name:C.participants,label:"Participants"}).multiline()).attribute(S({name:C.providerEventId,label:"Provider event id"}).hidden()).attribute(S({name:C.icalUid,label:"iCal UID"}).hidden()).attribute(S({name:C.recurringEventId,label:"Recurring event id"}).hidden()).attribute(S({name:C.connectionId,label:"Connection id"})).attribute(fe({name:C.recordingOverride,label:"Recording"}).options([{value:"force",label:"Force"},{value:"skip",label:"Skip"}]).hidden()).attribute(se({name:C.endedAnnouncedAt,label:"Ended announced at"}).includeTime().hidden()).attribute(ot({name:C.linkedRecords,label:"Linked records"}).toAny().many().qualifyWith(S({name:"source",label:"Source"}).hidden())).build(),Dl=W(ge(Sa,"Meeting").for(lt).default().tab("description","Description",N.richtext(C.description).titleAttribute(C.title)).tab("summary","Summary",N.richtext(C.summary)).tab("transcript","Transcript",N.richtext(C.transcript)).aside("details","Details",N.form(he("details","Details").fields(C.startsAt,C.endsAt,C.linkedRecords))).build()),Ol=W(ye(Ta,"Meetings").for(lt).default().tab("workspace","Shared",N.collection().object(lt).table().icon("users").visibility("workspace").columns(...xa).sort(C.startsAt,"desc")).tab("mine","My meetings",N.collection().object(lt).table().icon("lock").visibility("private").columns(...xa).sort(C.startsAt,"desc")).build());function gi(e,t){return JSON.stringify([e,t])}a(gi,"viewIdentityKey");function pn(e){return structuredClone(e)}a(pn,"cloneDeclaration");var hi=class hi{constructor(){this.views=new Map;this.systemNames=new Map;}register(t){let r$1=(Array.isArray(t)?t:[t]).map((s,c)=>this.prepare(s,c)),o=new Map,a=new Set;for(let{declaration:s}of r$1){let{object:c,name:u,context:l,default:m}=s.definition,d=o.get(c)??new Set;if((this.views.get(c)?.has(u)||d.has(u))&&this.throwDuplicate(c,u),d.add(u),o.set(c,d),!m)continue;let b=JSON.stringify([c,l]);if(this.getByObjectNameAndContext(c,l).some(y=>y.definition.default)||a.has(b))throw new r("default view",b,`[ViewRegistry] Duplicate default view for object "${c}" in context "${l}"`);a.add(b);}for(let s of r$1)this.commit(s);return this}prepare(t,n){if(typeof t!="object"||t===null||t.kind!=="view"||Object.keys(t).some(o=>o!=="kind"&&o!=="definition")){let o="Expected an exact view declaration";throw new h$1(o,[{path:["views",String(n)],message:o}])}let r=_.safeParse(t.definition);if(!r.success)throw h$1.fromZodErrors(r.error.issues.map(o=>({path:["views",String(n),"definition",...o.path.map(String)],message:o.message})));return {declaration:pn(t),system:ga(t.definition)}}commit({declaration:t,system:n}){let{object:r,name:o}=t.definition,a=this.views.get(r)??new Map;if(a.set(o,t),this.views.set(r,a),n){let s=this.systemNames.get(r)??new Set;s.add(o),this.systemNames.set(r,s);}}getByObjectName(t){return Array.from(this.views.get(t)?.values()??[],pn)}getByObjectNameAndContext(t,n){return this.getByObjectName(t).filter(r=>r.definition.context===n)}get(t,n){let r=this.views.get(t)?.get(n);return r&&pn(r)}getOrThrow(t,n){let r=this.get(t,n);if(r)return r;let a=this.getByObjectName(t).map(({definition:s})=>`${s.name} (${s.context})`).join(", ")||"(none)";throw new c$2("View",`${t}:${n}`,void 0,`[ViewRegistry] View "${n}" not found for object "${t}".
|
|
49
|
+
Available views: ${a}`)}getAll(){return Array.from(this.views.values()).flatMap(t=>Array.from(t.values(),pn))}has(t,n){return this.views.get(t)?.has(n)??false}hasObject(t){return this.views.has(t)}get size(){let t=0;for(let n of this.views.values())t+=n.size;return t}listObjectNames(){return Array.from(this.views.keys())}getDefault(t,n){let r=this.getByObjectNameAndContext(t,n);return r.find(o=>o.definition.default)??r[0]}isSystem(t,n){return this.systemNames.get(t)?.has(n)??false}isSystemDeclaration(t){return this.isSystem(t.definition.object,t.definition.name)}clear(){this.views.clear(),this.systemNames.clear();}summary(){let t=[`[ViewRegistry] ${this.size} view(s) registered:`];for(let n of this.listObjectNames()){let r=this.getByObjectName(n).map(({definition:o})=>{let a=o.default?" (default)":"";return `${o.name}:${o.context}${a}`});t.push(` ${n}: ${r.join(", ")}`);}return t.join(`
|
|
50
|
+
`)}debug(t){let n=this.summary();return t?.(n),n}throwDuplicate(t,n){let r$1=gi(t,n);throw new r("view",r$1,`[ViewRegistry] Duplicate view: "${n}" for object "${t}"`)}};a(hi,"ViewRegistry");var yi=hi,jl=new yi;function Ia(e,t){if(t.suppressed)return null;let n=t.workspaceDefinition??t.sourceDefinition;return n===null?null:{...structuredClone(n),name:e}}a(Ia,"contentDefinition");function Nt(e){let{name:t,...n}=e;return structuredClone(n)}a(Nt,"storedContentDefinition");function Et(e){let t={main:0,aside:0};return {origin:"runtime",mainOrderCustomized:false,asideOrderCustomized:false,contents:Object.fromEntries(e.map(n=>[n.name,{sourceDefinition:null,workspaceDefinition:Nt(n),suppressed:false,sourcePosition:null,workspacePosition:t[n.placement]++}]))}}a(Et,"workspaceViewAuthoring");function Ai(e){let t=Object.entries(e.contents).flatMap(([n,r])=>{let o=Ia(n,r);return o?[{definition:o,...r}]:[]});return ["main","aside"].flatMap(n=>{let r=n==="main"?e.mainOrderCustomized:e.asideOrderCustomized;return t.filter(o=>o.definition.placement===n).sort((o,a)=>{let s=r?o.workspacePosition:o.sourcePosition,c=r?a.workspacePosition:a.sourcePosition;if(s!==null&&c!==null&&s!==c)return s-c;if(s!==null&&c===null)return -1;if(c!==null&&s===null)return 1;let u=o.sourcePosition??o.workspacePosition,l=a.sourcePosition??a.workspacePosition;return u!==null&&l!==null&&u!==l?u-l:u!==null&&l===null?-1:l!==null&&u===null?1:o.definition.name.localeCompare(a.definition.name)}).map(o=>o.definition)})}a(Ai,"resolveViewContents");function Ra(e,t){return e.attributes.find(n=>n.name===t&&n.type==="relation")}a(Ra,"findRelationAttribute");function xi(e,t){return e.targets.some(n=>n.object===t||n.object===ae)}a(xi,"relationAcceptsObject");function Ca(e,t=[e.name,"targets"]){if(e.targets.length!==1||e.targets[0].object==="*"){let n=`Relation "${e.name}" requires one concrete collection target`;throw new h$1(n,[{path:t,message:n}])}return e.targets[0].object}a(Ca,"requireSingleRelationTarget");var kl=new Map(d().map(e=>[e.name,e]));function ue(e,t){throw new h$1(t,[{path:e,message:t}])}a(ue,"reject");function _e(e,t){e.trim().length===0&&ue(t,"API name must not be empty");}a(_e,"requireName");function va(e,t,n){let r$1=new Map;return e.forEach((o,a)=>{if(_e(o.name,[...n,String(a),"name"]),r$1.has(o.name))throw new r(t,o.name);r$1.set(o.name,o);}),r$1}a(va,"indexUnique");function ne(e,t,n,r,o){if(_e(t,n),!e)return;let a=e.attributes?.get(t)??kl.get(t);if(!a){if(!e.attributes)return;let s=[...e.attributes.keys()].slice(0,30),c=s.length===0?`Object "${e.name}" has no attributes yet.`:`Attributes of "${e.name}": ${s.join(", ")}`;ue(n,`Unknown attribute "${e.name}.${t}". ${c}${o?.()??""}`);}return r&&a.type!==r&&ue(n,`Attribute "${e.name}.${t}" must have type ${r}`),a}a(ne,"requireAttribute");function Ti(e){let t=e.mode??"published",n=new Map;e.objects.forEach((b,g)=>{if(_e(b.name,["objects",String(g),"name"]),n.has(b.name))throw new r("object",b.name);n.set(b.name,{name:b.name,attributes:va(b.attributes,"attribute",["objects",String(g),"attributes"])});});let r$1=new Set;(e.reservedObjects??[]).forEach((b,g)=>{let y=["reservedObjects",String(g)];_e(b,y),!n.has(b)&&(t!=="draft"&&ue(y,`Unresolved reserved object "${b}"`),r$1.add(b),n.set(b,{name:b}));});let o=va(e.extensions??[],"extension",["extensions"]);function a$1(b,g){_e(b,g);let y=n.get(b);return y||ue(g,`Unknown object "${b}"`),y}a(a$1,"resolveObject");function s(b){let g=[];for(let[y,A]of n)if(y!==b)for(let h of A.attributes?.values()??[])h.type==="relation"&&xi(h,b)&&g.push(`relatedFrom("${y}", "${h.name}")`);return g.sort().slice(0,3)}a(s,"inverseAddresses");let c=e.asideRule??"enforce",u=t==="draft"?X$1({asideRule:c}):Y({asideRule:c}),l=new Map,m=new Map;return {views:e.views.map((b,g)=>{let y=["views",String(g)],A=u.safeParse(b);if(!A.success)throw new h$1("Invalid content view",A.error.issues.map(O=>({path:[...y,...O.path.map(String)],message:O.message,code:O.code})));let h=A.data;_e(h.name,[...y,"name"]);let k=a$1(h.object,[...y,"object"]),_=l.get(h.object)??new Set;if(_.has(h.name))throw new r("view",`${h.object}.${h.name}`);if(_.add(h.name),l.set(h.object,_),h.default){let O=m.get(h.object)??new Set;if(O.has(h.context))throw new r("default view",`${h.object}.${h.context}`);O.add(h.context),m.set(h.object,O);}return h.contents.forEach((O,B)=>{let Se=[...y,"contents",String(B)];_e(O.name,[...Se,"name"]),_l(O,Se,k,h.context,o,a$1,s);}),h}),unresolvedObjects:[...r$1].sort()}}a(Ti,"validateContentViewCatalogue");function _l(e,t,n,r,o,a$1,s){function c(){Rt(e.name,r,t);}if(a(c,"requireRecord"),e.type==="custom"){let u=o.get(e.extension);u||ue([...t,"extension"],`Unknown extension "${e.extension}"`),u.requiresRecord&&c();let l=u.parameters.safeParse(structuredClone(e.parameters??{}));if(!l.success)throw new h$1("Invalid extension parameters",l.error.issues.map(m=>({path:[...t,"parameters",...m.path.map(String)],message:m.message,code:m.code})));return}if(e.type==="collection"){let u=ze(e.source),l,m;if(u.kind==="object")l=a$1(u.object,[...t,"source","object"]);else if(u.kind==="related"){c();let d=[...t,"source","relation"],b=a(()=>{if(!n)return "";let y=s(n.name);return y.length===0?"":`. Records pointing at "${n.name}" are addressed from the other side: ${y.join(", ")}`},"hint"),g=ne(n,u.relation,d,"relation",b);g?.type==="relation"&&(m=g,l=a$1(Ca(g,d),d));}else {c(),l=a$1(u.object,[...t,"source","object"]);let d=[...t,"source","relation"],b=ne(l,u.relation,d,"relation");if(b?.type==="relation"&&n&&!xi(b,n.name)){let g=b.targets.map(y=>`"${y.object}"`).join(", ");ue(d,`Relation "${u.object}.${u.relation}" targets ${g}, not "${n.name}"`);}e.filters?.combinator==="or"&&ue([...t,"filters","combinator"],`Collection "${e.name}" addresses "${u.object}" from the far side, so its filters must use the "and" combinator`);}e.columns?.forEach((d,b)=>{let g=[...t,"columns",String(b)];if(typeof d=="string"){ne(l,d,g);return}let y=[...g,"relationProperty"];m||ue(y,"Relation property columns require a relation source"),m.properties?.definitions.some(A=>A.name===d.relationProperty)||ue(y,`Unknown relation property "${d.relationProperty}"`);}),e.displayAttributes?.forEach((d,b)=>ne(l,d,[...t,"displayAttributes",String(b)])),e.sorts?.forEach((d,b)=>ne(l,d.attribute,[...t,"sorts",String(b),"attribute"])),e.filters?.rules.forEach((d,b)=>ne(l,d.attribute,[...t,"filters","rules",String(b),"attribute"])),e.descriptionAttribute!==void 0&&ne(l,e.descriptionAttribute,[...t,"descriptionAttribute"]),e.layout==="kanban"&&e.groupByAttribute!==void 0&&ne(l,e.groupByAttribute,[...t,"groupByAttribute"]);return}switch(c(),e.type){case "form":e.groups.forEach((u,l)=>{let m=[...t,"groups",String(l)];_e(u.name,[...m,"name"]),u.fields.forEach((d,b)=>ne(n,d.attribute,[...m,"fields",String(b),"attribute"]));});break;case "richtext":ne(n,e.attribute,[...t,"attribute"],"richtext"),e.titleAttribute!==void 0&&ne(n,e.titleAttribute,[...t,"titleAttribute"],"text");break;case "emails":case "meetings":e.emailAttributes.forEach((u,l)=>ne(n,u,[...t,"emailAttributes",String(l)],"text"));break;case "documents":e.relations?.forEach((u,l)=>ne(n,u,[...t,"relations",String(l)],"relation"));break;case "forms":e.objectName!==void 0&&a$1(e.objectName,[...t,"objectName"]);break;case "activity":break;default:ue(t,`Unknown content type: ${String(e)}`);}}a(_l,"validateContent");function wi(e){return structuredClone(e)}a(wi,"cloneFormDefinition");var Si=class Si{constructor(){this.forms=new Map;}register(t){let n=Array.isArray(t)?t:[t];for(let r$1 of n){if(this.forms.has(r$1.name))throw new r("form",r$1.name,`[FormRegistry] Duplicate form: "${r$1.name}"`);this.forms.set(r$1.name,wi(r$1));}return this}get(t){let n=this.forms.get(t);return n?wi(n):void 0}getAll(){return Array.from(this.forms.values(),wi)}listNames(){return Array.from(this.forms.keys())}};a(Si,"FormRegistry");var Dt=Si;var Na=new Dt;function aS(e,t){return `${e}:${t}`}a(aS,"formatAgentStreamFrameId");function sS(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}}a(sS,"parseAgentStreamFrameId");var lS=204800,dS=256;function Ri(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Ri,"isRecord");function Ci(e,t){let n=Object.keys(e);return n.length===t.length&&n.every(r=>t.includes(r))}a(Ci,"hasExactKeys");function Ii(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}a(Ii,"isPositiveInteger");function Ea(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}a(Ea,"isNonNegativeInteger");function Pl(e){return Ri(e)&&Ci(e,["kind","startOffset","endOffset"])?(e.kind==="text"||e.kind==="reasoning")&&Ea(e.startOffset)&&Ea(e.endOffset)&&e.endOffset>=e.startOffset:false}a(Pl,"isContentRange");function Ml(e){if(!Ri(e))return false;let t=e.content===void 0?["sequence","chunk"]:["sequence","content","chunk"];return Ci(e,t)&&Ii(e.sequence)&&e.chunk!==void 0&&(e.content===void 0||Pl(e.content))}a(Ml,"isBatchItem");function Fl(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return}}a(Fl,"encodedSize");function pS(e){if(!(Ri(e)&&Ci(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()===""||!Ii(e.sequenceStart)||!Ii(e.sequenceEnd)||!Array.isArray(e.items)||e.items.length===0||e.items.length>256||!e.items.every(Ml))return false;let t=0;for(let r of e.items){if(r.sequence<=t)return false;t=r.sequence;}if(e.items[0]?.sequence!==e.sequenceStart||e.items.at(-1)?.sequence!==e.sequenceEnd)return false;let n=Fl(e);return n!==void 0&&n<=204800}a(pS,"isAgentUIMessageBatch");function Da(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)}`}}a(Da,"liveChannelKey");function bS(e){return e.sessionId?Da({kind:"architect-draft",scope:"session",sessionId:e.sessionId}):e.actorId?Da({kind:"architect-draft",scope:"actor",actorId:e.actorId}):null}a(bS,"architectDraftChannelKey");function Pe(e){try{return decodeURIComponent(e)}catch{return null}}a(Pe,"decodeLiveChannelPart");function Oa(e){let t=e.split(":");if(t[0]==="workspace"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"workspace",tenantId:n}:null}if(t[0]==="object"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"object",objectId:n}:null}if(t[0]==="record"&&t.length===3&&t[1]&&t[2]){let n=Pe(t[1]),r=Pe(t[2]);return n&&r?{kind:"record",objectId:n,recordId:r}:null}if(t[0]==="view"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"view",viewId:n}:null}if(t[0]==="user"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"user",actorId:n}:null}if(t[0]==="architect-draft"&&t.length===3&&t[2]){let n=Pe(t[2]);return n?t[1]==="actor"?{kind:"architect-draft",scope:"actor",actorId:n}:t[1]==="session"?{kind:"architect-draft",scope:"session",sessionId:n}:null:null}if(t[0]==="conversation"&&t.length===2&&t[1]){let n=Pe(t[1]);return n?{kind:"conversation",sessionId:n}:null}return null}a(Oa,"parseLiveChannelKey");var Vl={"record.patch":true,"record.deleted":true,"record.removed":true,"record.created":true,"view.projection.stale":true,"agent.session.patch":true,"notification.created":true,"notification.recipient.patch":true,"notification.count.patch":true,"notification.inbox.archived":true,"reflex.state.changed":true,"reflex.run.completed":true,"reflex.authoring.progress":true,"architect.draft.updated":true,"meeting.recording.patch":true,"wallet.state":true,"channel.revoked":true},Bl=Object.keys(Vl),Ll=["membership-unknown","sort-unknown","permissions-changed"],$l=["permission-revoked","workspace-left","object-deleted"],Ul=["inboxState","workState","lockedAt","lockedByActorId","readAt","archivedAt","snoozedUntil","completedAt","dismissedAt","updatedAt"],ql=["type","objectId","recordId","recordVersion"],zl=["type","objectId","recordId","recordVersion","record"],Wl=["id","objectId","visibility","ownedBy","label","values","metadata","createdAt","updatedAt","createdBy","lastUpdatedBy","schemaVersion"],Gl=["type","targetActorId","archivedCount","version","updatedAt"];function Kl(e){return typeof e=="string"&&Bl.includes(e)}a(Kl,"isLiveEventType");function AS(e){return U(e)&&Kl(e.type)?Yl(e.type,e):false}a(AS,"isLiveEventPayload");function Yl(e,t){if(!U(t))return false;switch(e){case "record.patch":return td(t);case "record.deleted":return nd(t);case "record.removed":return rd(t);case "record.created":return od(t);case "view.projection.stale":return ad(t);case "agent.session.patch":return sd(t);case "notification.created":return dd(t);case "notification.recipient.patch":return pd(t);case "notification.count.patch":return md(t);case "notification.inbox.archived":return fd(t);case "reflex.state.changed":return xd(t);case "reflex.run.completed":return Td(t);case "reflex.authoring.progress":return wd(t);case "architect.draft.updated":return hd(t);case "meeting.recording.patch":return Id(t);case "wallet.state":return vd(t);case "channel.revoked":return Nd(t);default:return false}}a(Yl,"isLiveEventPayloadForType");function U(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(U,"isRecord");function H(e){return typeof e=="string"}a(H,"isString");function Ot(e){return H(e)&&e.length>0}a(Ot,"isNonEmptyString");function vi(e){return e===null||H(e)}a(vi,"isNullableString");function Hl(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}a(Hl,"isVersion");function xe(e){if(!H(e))return false;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}a(xe,"isIsoDateString");function dt(e){return e===null||xe(e)}a(dt,"isNullableIsoDateString");function D(e,t){return H(e[t])}a(D,"hasString");function le(e,t){return Ot(e[t])}a(le,"hasNonEmptyString");function q(e,t){return Hl(e[t])}a(q,"hasVersion");function G(e,t){return xe(e[t])}a(G,"hasIsoDateString");function E(e,t,n){return !Object.hasOwn(e,t)||n(e[t])}a(E,"hasOptional");function mn(e,t){return Object.keys(e).every(n=>t.includes(n))}a(mn,"hasOnlyKeys");function J(e,t){return typeof e=="string"&&t.includes(e)}a(J,"isOneOf");function Jl(e){return J(e,ko)}a(Jl,"isNotificationKind");function Ql(e){return J(e,_o)}a(Ql,"isNotificationPriority");function Zl(e){return J(e,Po)}a(Zl,"isNotificationSensitivity");function ja(e){return J(e,Mo)}a(ja,"isNotificationInboxState");function ka(e){return J(e,Fo)}a(ka,"isNotificationWorkState");function Xl(e){return U(e)&&D(e,"type")&&D(e,"id")}a(Xl,"isNotificationSubject");function ed(e){return U(e)&&D(e,"fieldKey")&&Object.hasOwn(e,"value")&&q(e,"version")}a(ed,"isRecordFieldPatch");function td(e){return e.type==="record.patch"&&D(e,"objectId")&&D(e,"recordId")&&q(e,"recordVersion")&&E(e,"label",H)&&E(e,"metadata",U)&&E(e,"fieldsWithheld",t=>t===true)&&Array.isArray(e.fieldPatches)&&e.fieldPatches.every(ed)&&D(e,"updatedAt")}a(td,"isRecordPatchPayload");function nd(e){return e.type==="record.deleted"&&D(e,"objectId")&&D(e,"recordId")&&q(e,"recordVersion")&&D(e,"deletedAt")}a(nd,"isRecordDeletedPayload");function rd(e){return e.type==="record.removed"&&mn(e,ql)&&D(e,"objectId")&&D(e,"recordId")&&q(e,"recordVersion")}a(rd,"isRecordRemovedPayload");function id(e){return U(e)&&mn(e,Wl)&&D(e,"id")&&D(e,"objectId")&&J(e.visibility,["workspace","private"])&&vi(e.ownedBy)&&(e.visibility==="workspace"&&e.ownedBy===null||e.visibility==="private"&&Ot(e.ownedBy))&&D(e,"label")&&U(e.values)&&E(e,"metadata",U)&&G(e,"createdAt")&&G(e,"updatedAt")&&E(e,"createdBy",H)&&E(e,"lastUpdatedBy",H)&&q(e,"schemaVersion")}a(id,"isRecordLiveSnapshot");function od(e){return e.type==="record.created"&&mn(e,zl)&&D(e,"objectId")&&D(e,"recordId")&&q(e,"recordVersion")&&id(e.record)&&e.record.id===e.recordId&&e.record.objectId===e.objectId}a(od,"isRecordCreatedPayload");function ad(e){return e.type==="view.projection.stale"&&D(e,"viewId")&&J(e.reason,Ll)}a(ad,"isViewProjectionStalePayload");function sd(e){return e.type==="agent.session.patch"&&D(e,"sessionId")&&U(e.patch)&&q(e,"version")&&D(e,"updatedAt")}a(sd,"isAgentSessionPatchPayload");function cd(e){return U(e)&&D(e,"id")&&D(e,"tenantId")&&E(e,"senderActorId",H)&&E(e,"rootActorId",H)&&E(e,"triggeredByActorId",H)&&Jl(e.kind)&&D(e,"type")&&E(e,"subject",Xl)&&D(e,"title")&&E(e,"summary",H)&&U(e.payload)&&Ql(e.priority)&&Zl(e.sensitivity)&&E(e,"threadKey",H)&&E(e,"idempotencyKey",H)&&E(e,"expiresAt",xe)&&G(e,"createdAt")&&G(e,"updatedAt")}a(cd,"isLiveNotification");function ud(e){return U(e)&&D(e,"id")&&D(e,"tenantId")&&D(e,"notificationId")&&D(e,"recipientActorId")&&ja(e.inboxState)&&ka(e.workState)&&E(e,"lockedAt",xe)&&E(e,"lockedByActorId",H)&&E(e,"readAt",xe)&&E(e,"archivedAt",xe)&&E(e,"snoozedUntil",xe)&&E(e,"completedAt",xe)&&E(e,"dismissedAt",xe)&&G(e,"createdAt")&&G(e,"updatedAt")}a(ud,"isLiveNotificationRecipient");function ld(e){return U(e)?Object.keys(e).every(t=>Ul.includes(t))&&E(e,"inboxState",ja)&&E(e,"workState",ka)&&E(e,"lockedAt",dt)&&E(e,"lockedByActorId",vi)&&E(e,"readAt",dt)&&E(e,"archivedAt",dt)&&E(e,"snoozedUntil",dt)&&E(e,"completedAt",dt)&&E(e,"dismissedAt",dt)&&E(e,"updatedAt",xe):false}a(ld,"isNotificationRecipientPatch");function dd(e){let t=cd(e.notification)?e.notification:null;return e.type==="notification.created"&&t!==null&&Array.isArray(e.recipients)&&e.recipients.length>0&&e.recipients.every(n=>ud(n)&&n.notificationId===t.id)&&q(e,"version")&&G(e,"updatedAt")}a(dd,"isNotificationCreatedPayload");function pd(e){return e.type==="notification.recipient.patch"&&D(e,"recipientId")&&D(e,"recipientActorId")&&ld(e.patch)&&q(e,"version")&&G(e,"updatedAt")}a(pd,"isNotificationRecipientPatchPayload");function md(e){return e.type==="notification.count.patch"&&D(e,"targetActorId")&&q(e,"unread")&&q(e,"pendingWork")&&q(e,"version")&&G(e,"updatedAt")}a(md,"isNotificationCountPatchPayload");function fd(e){return e.type==="notification.inbox.archived"&&mn(e,Gl)&&le(e,"targetActorId")&&q(e,"archivedCount")&&q(e,"version")&&G(e,"updatedAt")}a(fd,"isNotificationInboxArchivedPayload");var bd=["armed","disarmed"],gd=["authoring","compiling","replaying","promoted","failed"],yd=["promoted","lkg"];function hd(e){if(e.type!=="architect.draft.updated"||!U(e.receipt))return false;let t=e.receipt;return Array.isArray(t.operationIds)&&t.operationIds.every(Ot)&&U(t.revision)&&le(t.revision,"draftId")&&q(t.revision,"version")&&Array.isArray(t.changedTargets)&&t.changedTargets.every(n=>U(n)&&Ot(n.token)&&Ad(n.target))}a(hd,"isArchitectDraftUpdatedPayload");function Ad(e){if(!U(e))return false;let t=Object.keys(e);return t.every(n=>Ot(e[n]))?le(e,"viewName")?le(e,"objectName")&&t.every(n=>["objectName","viewName","contentName"].includes(n)):le(e,"objectName")?t.length===1:le(e,"objectId")&&t.length<=2&&t.every(n=>["objectId","attributeName","attributeId","recordId"].includes(n)):false}a(Ad,"isNamedTarget");function xd(e){return e.type==="reflex.state.changed"&&le(e,"reflexId")&&J(e.state,bd)&&G(e,"updatedAt")}a(xd,"isReflexStateChangedPayload");function Td(e){return e.type==="reflex.run.completed"&&le(e,"reflexId")&&le(e,"runId")&&J(e.served,yd)&&q(e,"version")&&q(e,"wallMs")&&G(e,"completedAt")}a(Td,"isReflexRunCompletedPayload");function wd(e){return e.type==="reflex.authoring.progress"&&le(e,"reflexId")&&J(e.status,gd)&&G(e,"updatedAt")}a(wd,"isReflexAuthoringProgressPayload");var Sd=["none","scheduled","recording","completed","failed"];function Id(e){return e.type==="meeting.recording.patch"&&le(e,"meetingId")&&J(e.status,Sd)&&vi(e.failureReason)&&G(e,"updatedAt")}a(Id,"isMeetingRecordingPatchPayload");var Rd=["ok","low","exhausted","paused"],Cd=["metering-only","contract","wallet"];function vd(e){return e.type==="wallet.state"&&J(e.status,Rd)&&J(e.mode,Cd)&&G(e,"updatedAt")}a(vd,"isWalletStatePayload");function Nd(e){return e.type==="channel.revoked"&&D(e,"channel")&&J(e.reason,$l)}a(Nd,"isChannelRevokedPayload");function Ni(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Ni,"isRecord");function Ed(e){let{channel:t}=e;return typeof t=="string"&&Oa(t)?t:null}a(Ed,"payloadChannel");function SS(e){return Ni(e)?Ed(e):null}a(SS,"getLiveProtocolPayloadChannel");function IS(e){return Ni(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"&&Ni(e.payload):false}a(IS,"isLiveEventEnvelope");var vS=["if","concat","sum","avg","count","min","max","earliest","latest","unique","first","percent_empty","percent_not_empty","count_empty","count_not_empty","count_unique"],jt={if:{name:"if",returnType:"branch",minArgs:3,maxArgs:3},concat:{name:"concat",returnType:{kind:"scalar",type:"text"},minArgs:1},sum:{name:"sum",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},avg:{name:"avg",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count:{name:"count",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},min:{name:"min",returnType:"source_item",minArgs:1,maxArgs:1},max:{name:"max",returnType:"source_item",minArgs:1,maxArgs:1},earliest:{name:"earliest",returnType:{kind:"scalar",type:"date"},minArgs:1,maxArgs:1},latest:{name:"latest",returnType:{kind:"scalar",type:"date"},minArgs:1,maxArgs:1},unique:{name:"unique",returnType:"argument",minArgs:1,maxArgs:1},first:{name:"first",returnType:"source_item",minArgs:1,maxArgs:1},percent_empty:{name:"percent_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},percent_not_empty:{name:"percent_not_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_empty:{name:"count_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_not_empty:{name:"count_not_empty",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1},count_unique:{name:"count_unique",returnType:{kind:"scalar",type:"number"},minArgs:1,maxArgs:1}};function fn(e){return Object.hasOwn(jt,e)}a(fn,"isComputedFunctionName");var ji=class ji extends Error{constructor(t){super(t),this.name="ComputedFormulaCompileError";}};a(ji,"ComputedFormulaCompileError");var I=ji;function gn(e){let t=Dd(e.expression),n=bn(t,e.schema),r=Zd(n.valueType);if(r!==e.returnType)throw new I(`Computed formula "${e.attributeName}" returns "${r}", expected "${e.returnType}"`);if(La(e.returnType)&&n.optionsSource===void 0)throw new I(`Computed formula "${e.attributeName}" returns "${e.returnType}" without optionsSource`);let o=n.optionsSource===void 0?[]:[{kind:"options",source:n.optionsSource}],a=Oi([...n.dependencies,...o]);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:Xd({expression:e.expression,returnType:e.returnType,dependencies:a})}}a(gn,"compileComputedFormula");function Ba(e){let t=new Map(e.map(o=>[o.attributeName,o])),n=new Set,r=a((o,a)=>{let s=a.indexOf(o);if(s!==-1){let l=[...a.slice(s),o];throw new I(`Computed field cycle detected: ${l.join(" -> ")}`)}if(n.has(o))return;let c=t.get(o);if(c===void 0)return;let u=[...a,o];for(let l of c.dependencies)l.kind==="computed"&&r(l.attributeName,u);n.add(o);},"visit");for(let o of e)r(o.attributeName,[]);}a(Ba,"assertAcyclicComputedDependencies");function Dd(e){try{return v$1(e)}catch(t){throw t instanceof Error?new I(t.message):t}}a(Dd,"parseCompileFormula");function bn(e,t){switch(e.kind){case "literal":return {valueType:Od(e.value),dependencies:[],...typeof e.value=="string"?{literalString:e.value}:{}};case "path":return jd(e.parts,t);case "call":return Vd(e.functionName,e.args,t);case "binary":return qd(e.operator,bn(e.left,t),bn(e.right,t));default:return e}}a(bn,"inferNode");function Od(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}}a(Od,"literalToValueType");function jd(e,t){if(e.length===1){let n=e[0],r=Ei(t,n);if(r===void 0)throw new I(`Unknown attribute "${n}" on object "${t.objectName}"`);return r.type==="relation"?{valueType:Pd(),dependencies:[{kind:"relation",relationName:r.name,cardinality:_a(r)}],targetAttributeType:r.type}:{valueType:Pa(r),dependencies:[_d(r)],optionsSource:Ma(t.objectName,r),targetAttributeType:r.type}}if(e.length===2){let[n,r]=e,o=Ei(t,n);if(o===void 0)throw new I(`Unknown attribute "${n}" on object "${t.objectName}"`);if(o.type!=="relation")throw new I(`Attribute "${n}" on object "${t.objectName}" is not a relation`);let a=kd(o);if(a===void 0)throw new I(`Relation "${n}" on object "${t.objectName}" is missing targetObjectName`);let s=t.relatedObjects?.[a];if(s===void 0)throw new I(`Unknown related object "${a}"`);let c=Ei(s,r);if(c===void 0)throw new I(`Unknown attribute "${r}" on object "${s.objectName}"`);let u=Pa(c);return {valueType:o.cardinality==="many"?Fd(u):u,dependencies:[{kind:"relation",relationName:n,targetAttributeName:r,cardinality:_a(o)}],optionsSource:Ma(s.objectName,c),targetAttributeType:c.type}}throw new I("Computed paths support at most one relation hop")}a(jd,"inferPath");function Ei(e,t){return e.attributes.find(n=>n.name===t)}a(Ei,"findAttribute");function kd(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}}a(kd,"getRelationTargetObjectName");function _a(e){return e.cardinality??"one"}a(_a,"relationCardinality");function _d(e){return e.type==="formula"||e.type==="rollup"?{kind:"computed",attributeName:e.name}:{kind:"local",attributeName:e.name}}a(_d,"localDependencyFor");function Pa(e){if(e.type==="formula"||e.type==="rollup"){if(e.returnType===void 0)throw new I(`Computed attribute "${e.name}" is missing returnType`);return Md(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}}a(Pa,"attributeToValueType");function Pd(){return {kind:"collection",itemType:"text"}}a(Pd,"relationToValueType");function Md(e){return e==="multiselect"?{kind:"collection",itemType:"select"}:{kind:"scalar",type:e}}a(Md,"returnTypeToValueType");function Fd(e){return e.kind==="collection"?e:{kind:"collection",itemType:e.type}}a(Fd,"asCollectionValueType");function Ma(e,t){if(t.type==="formula"||t.type==="rollup")return La(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}:{}}}a(Ma,"optionsSourceForAttribute");function Vd(e,t,n){if(!fn(e))throw new I(`Unknown computed function "${e}"`);let r=jt[e];if(t.length<r.minArgs||r.maxArgs!==void 0&&t.length>r.maxArgs){let a=r.maxArgs===void 0||r.maxArgs===r.minArgs?String(r.minArgs):`${r.minArgs}-${r.maxArgs}`;throw new I(`Function "${e}" expects ${a} arguments, received ${t.length}`)}let o=t.map(a=>bn(a,n));return Bd(e,o)}a(Vd,"inferCall");function Bd(e,t){let n=Oi(t.flatMap(r=>r.dependencies));switch(e){case "if":return Ld(t,n);case "concat":return zd(t,`Function "${e}" does not accept collection values`),{valueType:{kind:"scalar",type:"text"},dependencies:n};case "sum":case "avg":return Fa(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 Gd(e,t[0]),{valueType:{kind:"scalar",type:"number"},dependencies:n};case "min":case "max":return Wd(e,t[0]),{valueType:Kd(t[0]),dependencies:n,optionsSource:t[0].optionsSource,targetAttributeType:t[0].targetAttributeType};case "earliest":case "latest":return Fa(e,t[0],"date"),{valueType:{kind:"scalar",type:"date"},dependencies:n,targetAttributeType:t[0].targetAttributeType};case "unique":return $d(t[0],n);case "first":return Ud(t[0],n);default:return e}}a(Bd,"inferFunctionReturn");function Ld(e,t){Di(e[0].valueType,"boolean",'Function "if" condition must be boolean');let n=e[1],r=e[2],o=Hd(n,r),a=Jd(n,r);if(o===void 0)throw new I('Function "if" branches must return the same type');return {valueType:o,dependencies:t,...a?{optionsSource:a}:{},targetAttributeType:n.targetAttributeType??r.targetAttributeType}}a(Ld,"inferIfFunction");function $d(e,t){if(e.valueType.kind!=="collection"||e.valueType.itemType!=="select")throw new I('Function "unique" expects a select collection');return {valueType:{kind:"collection",itemType:"select"},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a($d,"inferUniqueFunction");function Ud(e,t){if(e.valueType.kind!=="collection")throw new I('Function "first" expects a collection');return {valueType:{kind:"scalar",type:e.valueType.itemType},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a(Ud,"inferFirstFunction");function qd(e,t,n){let r=Oi([...t.dependencies,...n.dependencies]),o=e==="+"||e==="-"||e==="*"||e==="/";if(t.valueType.kind==="collection"||n.valueType.kind==="collection")throw new I(`Cannot use collection values with ${o?"arithmetic":"comparison"} operator "${e}"`);if(o)return e==="+"&&(t.valueType.type==="text"||n.valueType.type==="text")?{valueType:{kind:"scalar",type:"text"},dependencies:r}:(Di(t.valueType,"number",`Operator "${e}" expects number operands`),Di(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 I(`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 I(`Operator "${e}" expects number or date operands of the same type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:r}}a(qd,"inferBinary");function zd(e,t){for(let n of e)if(n.valueType.kind==="collection")throw new I(t)}a(zd,"ensureNoCollections");function Fa(e,t,n){if((t.valueType.kind==="collection"?t.valueType.itemType:t.valueType.type)!==n)throw new I(`Function "${e}" expects ${n} values`)}a(Fa,"ensureCollectionOrScalarType");function Wd(e,t){if(t.valueType.kind!=="collection")throw new I(`Function "${e}" expects a collection`);let n=t.valueType.itemType;if(n!=="number"&&n!=="date")throw new I(`Function "${e}" expects number or date values`)}a(Wd,"ensureMinMaxSource");function Gd(e,t){if(t.valueType.kind!=="collection")throw new I(`Function "${e}" expects a collection`)}a(Gd,"ensureCollectionSource");function Di(e,t,n){if(e.kind!=="scalar"||e.type!==t)throw new I(n)}a(Di,"ensureScalarType");function Kd(e){return e.valueType.kind==="scalar"?e.valueType:{kind:"scalar",type:e.valueType.itemType}}a(Kd,"sourceItemValueType");function Yd(e,t){return e.kind==="scalar"?t.kind==="scalar"&&e.type===t.type:t.kind==="collection"&&e.itemType===t.itemType}a(Yd,"sameValueType");function Hd(e,t){if(Yd(e.valueType,t.valueType)||Va(e,t))return e.valueType;if(Va(t,e))return t.valueType}a(Hd,"resolveIfBranchValueType");function Va(e,t){return e.valueType.kind==="scalar"&&e.valueType.type==="select"&&t.valueType.kind==="scalar"&&t.valueType.type==="text"&&t.literalString!==void 0}a(Va,"isSelectScalarWithStringLiteral");function Jd(e,t){let n=e.optionsSource,r=t.optionsSource;if(n!==void 0&&r!==void 0&&!Qd(n,r))throw new I('Function "if" branches use incompatible options sources');return n??r}a(Jd,"resolveIfOptionsSource");function Qd(e,t){return e.objectName===t.objectName&&e.attributeName===t.attributeName&&e.attributeId===t.attributeId}a(Qd,"sameOptionsSource");function La(e){return e==="select"||e==="multiselect"}a(La,"isSelectLikeReturnType");function Zd(e){if(e.kind==="scalar")return e.type;if(e.itemType==="select")return "multiselect";throw new I(`Collection item type "${e.itemType}" cannot be used as a computed return type`)}a(Zd,"valueTypeToReturnType");function Oi(e){let t=new Set,n=[];for(let r of e){let o=JSON.stringify(kt(r));t.has(o)||(t.add(o),n.push(r));}return n}a(Oi,"uniqueDependencies");function Xd(e){let t=e.dependencies.map(n=>kt(n)).sort((n,r)=>$a(JSON.stringify(n),JSON.stringify(r)));return JSON.stringify(kt({expression:e.expression,returnType:e.returnType,dependencies:t}))}a(Xd,"createDependenciesHash");function kt(e){return Array.isArray(e)?e.map(t=>kt(t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>$a(t,n)).map(([t,n])=>[t,kt(n)])):e}a(kt,"stableNormalize");function $a(e,t){return e<t?-1:e>t?1:0}a($a,"compareStrings");function ep(e){return e.function==="count"?`count(${e.relationAttribute})`:`${rp(e.function)}(${e.relationAttribute}.${e.targetAttribute})`}a(ep,"rollupToFormulaExpression");function tp(e,t){if(e.function==="count")return "number";let n=ip(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(!ap(n.type))throw new I('Rollup "original" requires a select, status, or multiselect target');return "multiselect";default:return e.function}}a(tp,"inferRollupReturnType");function qa(e,t){let n=ep(e),r=tp(e,t);return {...gn({attributeName:e.name,expression:n,returnType:r,schema:np(e,t)}),kind:"rollup"}}a(qa,"compileRollupAttribute");function np(e,t){return {...t,attributes:t.attributes.map(n=>n.name===e.relationAttribute&&n.type==="relation"?{...n,cardinality:"many"}:n)}}a(np,"schemaWithRollupRelationAsMany");function rp(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}}a(rp,"rollupFunctionToFormulaFunction");function ip(e,t){let n=Ua(t,e.relationAttribute);if(n===void 0)throw new I(`Unknown relation attribute "${e.relationAttribute}" on object "${t.objectName}"`);if(n.type!=="relation")throw new I(`Attribute "${e.relationAttribute}" on object "${t.objectName}" is not a relation`);let r=op(n);if(r===void 0)throw new I(`Relation "${e.relationAttribute}" on object "${t.objectName}" is missing targetObjectName`);let o=t.relatedObjects?.[r];if(o===void 0)throw new I(`Unknown related object "${r}"`);let a=Ua(o,e.targetAttribute);if(a===void 0)throw new I(`Unknown attribute "${e.targetAttribute}" on object "${o.objectName}"`);return a}a(ip,"findRollupTargetAttribute");function Ua(e,t){return e.attributes.find(n=>n.name===t)}a(Ua,"findAttribute");function op(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}}a(op,"getRelationTargetObjectName");function ap(e){return e==="select"||e==="status"||e==="multiselect"}a(ap,"isSelectLikeAttributeType");function ve(e,t){switch(e.kind){case "literal":return e.value;case "path":return cp(t,e.parts);case "binary":return up(e.operator,ve(e.left,t),ve(e.right,t));case "call":return sp(e.functionName,e.args,t);default:return e}}a(ve,"evaluateAst");function sp(e,t,n){if(dp(e),pp(e,t.length),e==="if"){let r=ve(t[0],n);return r===null?null:ve(r?t[1]:t[2],n)}return mp(e,t.map(r=>ve(r,n)))}a(sp,"evaluateCallNode");function cp(e,t){return t.reduce((n,r)=>Ha(n,r),e)}a(cp,"resolvePath");function Ha(e,t){if(Array.isArray(e))return e.map(r=>Ha(r,t));if(!Ya(e))return null;if(Object.hasOwn(e,t))return e[t]??null;let n=e.values;return Ya(n)&&Object.hasOwn(n,t)?n[t]??null:null}a(Ha,"resolvePathPart");function up(e,t,n){switch(e){case "+":return lp(t,n);case "-":return hn(t,n,(r,o)=>r-o);case "*":return hn(t,n,(r,o)=>r*o);case "/":return hn(t,n,(r,o)=>r/o);case ">":return yn(t,n,r=>r>0);case "<":return yn(t,n,r=>r<0);case ">=":return yn(t,n,r=>r>=0);case "<=":return yn(t,n,r=>r<=0);case "==":return za(t,n);case "!=":{let r=za(t,n);return r===null?null:!r}default:return e}}a(up,"evaluateBinary");function lp(e,t){return typeof e=="string"||typeof t=="string"?`${e??""}${t??""}`:hn(e,t,(n,r)=>n+r)}a(lp,"add");function yn(e,t,n){let r=Ja(e,t);return r===null?null:n(r)}a(yn,"compareWith");function Ja(e,t){if(!pt([e,t]))return null;let n=mt(e),r=mt(t);if(n!==null&&r!==null)return n-r;let o=Pi(e),a=Pi(t);return o&&a?o.getTime()-a.getTime():null}a(Ja,"compare");function za(e,t){return e===t?true:e==null||t===null||t===void 0?false:pt([e,t])?Ja(e,t)===0:null}a(za,"equalScalar");function dp(e){if(!fn(e))throw new Error(`Unknown computed function "${e}"`)}a(dp,"assertComputedFunctionName");function pp(e,t){let{minArgs:n,maxArgs:r}=jt[e];if(t>=n&&t<=(r??Number.POSITIVE_INFINITY))return;let o=r===void 0?`at least ${n}`:`between ${n} and ${r}`;throw new Error(`Function "${e}" expects ${o} arguments, received ${t}`)}a(pp,"validateArity");function mp(e,t){switch(e){case "concat":return t.filter(n=>n!=null).map(String).join("");case "sum":return pt(t)?ki(t).reduce((n,r)=>n+r,0):null;case "avg":{if(!pt(t))return null;let n=ki(t);return n.length>0?n.reduce((r,o)=>r+o,0)/n.length:null}case "count":return Ge(t[0]).length;case "min":return Wa(t,"min");case "max":return Wa(t,"max");case "earliest":return _i(t,"min");case "latest":return _i(t,"max");case "unique":return Ka(Ge(t[0]));case "first":return Ge(t[0]).find(n=>n!=null)??null;case "percent_empty":return Ga(t[0],true);case "percent_not_empty":return Ga(t[0],false);case "count_empty":return Ge(t[0]).filter(a$1).length;case "count_not_empty":return Ge(t[0]).filter(n=>!a$1(n)).length;case "count_unique":return Ka(Ge(t[0])).length;default:return e}}a(mp,"evaluateCall");function ki(e){return An(e).map(mt).filter(t=>t!==null)}a(ki,"numericValues");function pt(e){let t=new Set;for(let n of An(e))Mi(n)&&t.add(Qa(n));return t.size<=1}a(pt,"areCommensurable");function Qa(e){return e.code.toUpperCase()}a(Qa,"currencyCode");function hn(e,t,n){if(!pt([e,t]))return null;let r=mt(e),o=mt(t);if(r===null||o===null)return null;let a=n(r,o);return Number.isFinite(a)?a:null}a(hn,"numericBinary");function Wa(e,t){if(!pt(e))return null;let n=ki(e);return n.length>0?t==="min"?Math.min(...n):Math.max(...n):_i(e,t)}a(Wa,"minMax");function _i(e,t){let n=An(e).map(Pi).filter(a=>a!==null);if(n.length===0)return null;let r=n.map(a=>a.getTime()),o=t==="min"?Math.min(...r):Math.max(...r);return new Date(o).toISOString()}a(_i,"dateMinMax");function Ga(e,t){let n=Ge(e);return n.length===0?0:n.filter(o=>a$1(o)===t).length/n.length}a(Ga,"percentByEmptyState");function Ka(e){let t=new Set,n=[];for(let r of e){if(a$1(r))continue;let o=fp(r);t.has(o)||(t.add(o),n.push(r));}return n}a(Ka,"uniqueNonEmpty");function Ge(e){return e==null?[]:Array.isArray(e)?An(e):[e]}a(Ge,"collectionItems");function An(e){return e.flat(Number.POSITIVE_INFINITY)}a(An,"flatten");function mt(e){if(typeof e=="number")return Number.isFinite(e)?e:null;if(typeof e=="string"&&e.trim()!==""){let t=Number(e);return Number.isFinite(t)?t:null}return Mi(e)&&Number.isFinite(e.value)?e.value:null}a(mt,"toFiniteNumber");function Mi(e){return typeof e=="object"&&e!==null&&typeof e.value=="number"&&typeof e.code=="string"}a(Mi,"isCurrencyValue");function Pi(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e!="string"){let n=nt(e);if(n===null)return null;let r=new Date(n);return Number.isNaN(r.getTime())?null:r}let t=new Date(e);return Number.isNaN(t.getTime())?null:t}a(Pi,"toDate");function fp(e){if(Mi(e))return `currency:${Qa(e)}:${e.value}`;let t=mt(e);return t!==null?`number:${t}`:e instanceof Date?`date:${e.toISOString()}`:`${typeof e}:${JSON.stringify(e)}`}a(fp,"uniqueKey");function Ya(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Ya,"isPlainRecord");function bp(e,t,n){if(e==null)return null;let r=a(o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean"||o instanceof Date?String(o):null,"stringifyScalar");switch(t){case "number":{let o=typeof e=="number"?e:Number(e);return Number.isNaN(o)?null:n!==void 0?Number(o.toFixed(n)):o}case "boolean":return !!e;case "date":return e instanceof Date?e.toISOString():typeof e=="string"?e:null;case "text":return String(e);case "select":if(Array.isArray(e)){for(let o of e){if(o==null)continue;let a=r(o);if(a!==null)return a}return null}return r(e);case "multiselect":return Array.isArray(e)?e.flatMap(o=>{if(o==null)return [];let a=r(o);return a===null?[]:[a]}):r(e)===null?[]:[String(e)];default:{let o=t;throw new Error(`Unsupported computed return type: ${o}`)}}}a(bp,"formatComputedResult");function $S(e,t){return ve(e,t)}a($S,"evaluateComputedAst");function US(e,t){return ve(v$1(e),t)}a(US,"evaluateComputedFormula");function qS(e,t,n,r){try{let o=ve(v$1(e),t);return {value:n?bp(o,n,r):o}}catch(o){return {value:null,error:o instanceof Error?o.message:String(o)}}}a(qS,"evaluateComputedFormulaWithResult");var GS=[{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)"}];var Za=a(e=>a$1(e)||Array.isArray(e)&&e.length===0,"isEmpty"),Q=a(e=>e==null?"":String(e),"toStr"),wn=a(e=>{if(a$1(e))return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null},"toNum"),Sn=a(e=>{if(e==null)return null;let t=e instanceof Date?e:new Date(String(e));return Number.isNaN(t.getTime())?null:t},"toDate"),xn=a(e=>Array.isArray(e)?e:e==null?[]:[e],"toArr"),gp=a((e,t,n)=>{let r=wn(e),o=wn(t);return r!==null&&o!==null&&n(r,o)},"compareNumbers"),yp=a((e,t,n)=>{let r=Sn(e),o=Sn(t);return r!==null&&o!==null&&n(r.getTime(),o.getTime())},"compareDates"),Xa=a((e,t,n)=>{if(n.type==="number"||n.type==="currency"){let r=wn(e),o=wn(t);if(r!==null&&o!==null)return r===o}return Q(e)===Q(t)},"equalsForAttr");function JS(e,t){return e?e==="checkbox":typeof t=="boolean"}a(JS,"isCheckboxEquality");var Tn=a(e=>({appliesTo:["number","currency","date","formula"],evaluateInMemory:a((t,n,r)=>r.type==="date"?yp(t,n,e):gp(t,n,e),"evaluateInMemory")}),"orderingSpec"),In={is:{appliesTo:["text","phone","number","currency","checkbox","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,n)=>n.type==="checkbox"?e===true==(t===true):Xa(e,t,n),"evaluateInMemory")},is_not:{appliesTo:["text","phone","number","currency","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,n)=>!Xa(e,t,n),"evaluateInMemory")},contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>Q(e).toLowerCase().includes(Q(t).toLowerCase()),"evaluateInMemory")},not_contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>!Q(e).toLowerCase().includes(Q(t).toLowerCase()),"evaluateInMemory")},starts_with:{appliesTo:["text","phone"],evaluateInMemory:a((e,t)=>Q(e).toLowerCase().startsWith(Q(t).toLowerCase()),"evaluateInMemory")},ends_with:{appliesTo:["text"],evaluateInMemory:a((e,t)=>Q(e).toLowerCase().endsWith(Q(t).toLowerCase()),"evaluateInMemory")},is_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>Za(e),"evaluateInMemory")},is_not_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>!Za(e),"evaluateInMemory")},less_than:Tn((e,t)=>e<t),greater_than:Tn((e,t)=>e>t),less_or_equal:Tn((e,t)=>e<=t),greater_or_equal:Tn((e,t)=>e>=t),is_within:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let n=Sn(e),r=K(t);return n&&r?n.getTime()>=r.startMs&&n.getTime()<r.endMs:false},"evaluateInMemory")},on_day_month:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let n=Sn(e);if(!n)return false;let r=t;return n.getMonth()+1===r.month&&n.getDate()===r.day},"evaluateInMemory")},any_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let n=xn(t).map(Q);return xn(e).map(Q).some(o=>n.includes(o))},"evaluateInMemory")},none_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let n=xn(t).map(Q);return !xn(e).map(Q).some(o=>n.includes(o))},"evaluateInMemory")}};var hp=a((e,t)=>({id:`system:${e}`,name:e,label:e,type:t,system:true}),"systemAttribute"),Ap=[...Object.entries(N$1).map(([e,t])=>hp(e,t))];function sI(e,t,n){let r=t;return xp(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,...Ap])}a(sI,"evaluateRecordFilterState");function xp(e,t,n){if(e.rules.length===0)return true;let r=new Map(n.map(a=>[a.name,a])),o=e.combinator==="or"?"some":"every";return e.rules[o](a=>Tp(a,t,r))}a(xp,"evaluateFilterState");function Tp(e,t,n){let r=n.get(e.attribute);if(!r)return false;if(e.property&&r.type==="location"){if(!(g(e.property)&&h$2(e.operator)))return false;let c=In[e.operator];if(!c)return false;let u=t[e.attribute],l=typeof u=="object"&&u!==null?u[e.property]:void 0;return Fi(c,"text",e.operator,l,e.value,r)}if(e.property){let c=Xt(r).find(g=>g.name===e.property);if(!c)return false;let u=C$1(e.operator),l=In[u];if(!l?.appliesTo.includes(c.type))return false;let m=t[e.attribute],b=(Array.isArray(m)?m:m==null?[]:[m]).some(g=>{if(typeof g!="object"||g===null)return false;let y=g.props;return typeof y!="object"||y===null?false:Fi(l,c.type,u,y[e.property],e.value,c)});return (e.quantifier??B(e.operator))==="none"?!b:b}let o=In[e.operator];if(!o||!o.appliesTo.includes(r.type))return false;let a=t[e.attribute],s=r.type==="relation"||r.type==="document"||r.type==="user"?Ip(a):a;return Fi(o,r.type,e.operator,s,e.value,r)}a(Tp,"evaluateRule");function Fi(e,t,n,r,o,a){let[s,c]=wp(t,n,r,o);return t==="phone"&&c===""&&n==="contains"?false:t==="phone"&&c===""&&n==="not_contains"?true:e.evaluateInMemory(s,c,a)}a(Fi,"evaluateNormalizedComparands");function wp(e,t,n,r){return e==="date"&&(t==="is"||t==="is_not")?[es(n),es(r)]:e==="phone"?Sp(n,r):[ts(e,n),ts(e,r)]}a(wp,"normalizeOperatorComparands");function es(e){let t=Oe(e)?nt(e):e;if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.toISOString().slice(0,10);if(typeof t!="string"||t==="")return null;if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;let n=new Date(t);return Number.isNaN(n.getTime())?null:n.toISOString().slice(0,10)}a(es,"normalizeUtcCalendarDay");function Sp(e,t){let n=typeof t=="object"&&t!==null?t:{},r=typeof n.countryCode=="string"?n.countryCode:void 0,o=a(a=>{let s=typeof a=="object"&&a!==null?a:{phoneNumber:a};if(typeof s.phoneNumber!="string")return null;if(!r)return a$3(s.phoneNumber);let c=typeof s.countryCode=="string"?s.countryCode:r;return `${c}:${b$2(s.phoneNumber,c)}`},"normalizeOne");return [o(e),o(t)]}a(Sp,"normalizePhoneComparands");function ts(e,t){return e==="currency"?z$1(t):e==="date"?Oe(t)?nt(t):t instanceof Date?Number.isNaN(t.getTime())?null:t.toISOString():t:t}a(ts,"normalizeComparableValue");function Ip(e){let t=a(n=>typeof n!="object"||n===null?n:n.id,"normalizeOne");return Array.isArray(e)?e.map(t):t(e)}a(Ip,"normalizeReferenceIds");var ns="today";function Rn(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}a(Rn,"dateInTimezone");function Rp(e,t){if(!("defaultValue"in e))return;let{defaultValue:n}=e;return e.type!=="date"||n!==ns?n:e.includeTime?t.now.toISOString():Rn(t.now,t.timezone)}a(Rp,"resolveAttributeDefaultValue");function bI(e,t,n){if(e.combinator==="or"&&e.rules.length>1)return {};let r=new Map(t.map(a=>[a.name,a])),o={};for(let a of e.rules){if(a.property!==void 0||Object.hasOwn(o,a.attribute))continue;let s=r.get(a.attribute);if(!s)continue;let c=Cp(a,n);c!==void 0&&(o[a.attribute]=j$1(s).storage.cardinality==="many"?[c]:c);}return o}a(bI,"deriveCreateDefaultsFromFilters");function Cp(e,t){if(e.operator==="is")return v$2(e.value)?rs(e.value,t):e.value===null||Array.isArray(e.value)?void 0:e.value;if(e.operator==="any_of"){if(!Array.isArray(e.value)||e.value.length!==1)return;let n=e.value[0];return v$2(n)?rs(n,t):n}}a(Cp,"extractDeterministicValue");function rs(e,t){if(t){if(e.dynamic==="actor")return t.userId;if(e.anchor==="today")return Rn(t.now,t.timezone);if(e.anchor==="now")return t.now.toISOString()}}a(rs,"resolveDynamicValue");function hI(e){let t=[];return e.canModify&&t.push("modify"),e.canSend&&t.push("send"),t}a(hI,"requestedCapabilities");var AI={status:"connector_status",error:"connector_error",provider:"connector_provider"};var vp=(t=>(t.Desktop="desktop",t))(vp||{});function SI(e){return e==="gmail"||e==="outlook"}a(SI,"isMailProvider");var Np=["threads","messages"];function II(e){return Np.includes(e)}a(II,"isMailboxListMode");var Ep=["reply","reply_all"];function RI(e){return Ep.includes(e)}a(RI,"isReplyMode");var CI=2e5,vI=998;var DI=["force","skip"],OI=["none","all","external_only"],jI="x-fake-signature",kI={override:null,status:"none",failureReason:null,botId:null};var Dp=/^Session \d+$/;function is(e){let t=e.replace(/\s+/g," ").trim().replace(/[.!?]+$/,"");return t?t.length>60?`${t.slice(0,59).trimEnd()}...`:t:"New conversation"}a(is,"buildAgentFallbackTitle");function Op(e){let t=e.generated?.trim();return t&&!Dp.test(t)?t:e.firstUserText?is(e.firstUserText):e.emptyLabel}a(Op,"conversationDisplayTitle");var Vi=/^[a-z0-9][a-z0-9-]{0,62}$/;function jp(e){if(!Vi.test(e))throw new h$1(`Invalid schema source id "${e}": expected a lowercase slug matching ${Vi}`,[])}a(jp,"assertSchemaSourceId");function LI(e){let{attributeRemovals:t,objectRemovals:n,renames:r}=e.destructive;return t.length>0||n.length>0||r.length>0}a(LI,"hasDestructiveEntries");var de={objectAdditions:20,totalMutations:500,serializedBytes:512*1024};function Li(e){return e instanceof Error?e.message:String(e)}a(Li,"errorMessage");var kp=z.enum(["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"]).describe('The attribute\'s data type. Determines which keys `config` accepts and requires: `status`/`select`/`multiselect` need a non-empty `options` array (each `status` option carrying its own `group`); `relation` needs `targets` (non-empty) and `cardinality` ("one" or "many"); `formula` needs `expression` and `returnType`; `rollup` needs `targetAttribute` and `function`. Every other type accepts only the shared presentation keys (`placeholder`, `defaultValue`, `icon`, ...) plus a few type-specific optionals (e.g. `number.decimals`, `date.dateFormat`). An attribute\'s type can never be changed later through this tool \u2014 only through a code migration \u2014 so pick it correctly now.');var as=z.string().min(1).superRefine((e,t)=>{try{n(e);}catch(n){t.addIssue({code:z.ZodIssueCode.custom,message:Li(n)});}}).describe('The attribute\'s machine name \u2014 the record\'s field key, and what `{{ name }}` refers to in a labelExpression. Must be a valid identifier: starts with a letter or underscore, then only letters/digits/underscores ("montantHt", "first_name", "FIRST_NAME" are valid; "first-name", "first name", "123name" are not). Max 63 characters. Cannot be a name reserved by the record shape itself (id, createdAt, updatedAt, createdBy, lastUpdatedBy, objectId, label, embeddingText, values, metadata, deletedAt, deletedBy, schemaVersion).'),_p=z.string().min(1).superRefine((e,t)=>{b(e)&&t.addIssue({code:z.ZodIssueCode.custom,message:`"${e}" is a reserved object name (${h.join(", ")}) and cannot be used for a new object.`});try{j(e);}catch(n){t.addIssue({code:z.ZodIssueCode.custom,message:Li(n)});}}).describe(`The new object's machine name: kebab-case slug, lowercase letters/digits/hyphens only, starting with a letter ("products", "user-profiles", "order-items" are valid; "Products", "userProfiles", "user_profiles" are not). Max 63 characters. Cannot be a name the platform reserves for its own system objects, and cannot already exist.`);function ss(e){return e.superRefine((t,n)=>{try{let r=L$1(t.type,{...t.config??{},description:t.description}),o=Object.keys(t.config??{}).filter(a=>!Object.hasOwn(r,a));o.length>0&&n.addIssue({code:"unrecognized_keys",keys:o,path:["config"],message:`Unrecognized attribute config key${o.length===1?"":"s"}: ${o.join(", ")}`});}catch(r){if(r instanceof h$1){for(let o of r.errors)n.addIssue({code:z.ZodIssueCode.custom,path:["config",...o.path.map(a=>/^\d+$/.test(a)?Number(a):a)],message:`Config for type "${t.type}" is invalid or incomplete: ${o.message}`});return}n.addIssue({code:z.ZodIssueCode.custom,path:["config"],message:`Config for type "${t.type}" is invalid or incomplete: ${Li(r)}`});}})}a(ss,"withConfigCheck");var cs=z.object({objectName:z.string().min(1).describe("Name of the existing (or, elsewhere in the same plan, newly created) object this attribute is added to. Ignored for an attribute declared inline in `additive.objects[].attributes` \u2014 there the parent object's own `name` is used instead."),name:as,label:z.string().min(1).max(128).describe("Human-readable display label shown in the UI. 1-128 characters, cannot be empty."),type:kp,config:z.record(z.string(),z.unknown()).optional().describe('Type-specific configuration; required keys depend on `type` (see `type`\'s description). Shared optional keys on every type: `placeholder`, `defaultValue`, `icon`, `order`, `hidden`, `archived`, `deprecated`, `metadata`. Per-type keys: `text` \u2014 `multiline`, `minLength`, `maxLength`, `pattern`, `format` ("email"|"url"|"slug"); `number` \u2014 `renderAs` ("number"|"rating"), `min`, `max`, `unit`, `decimals`; `date` \u2014 `dateFormat`, `minDate`, `maxDate`, `includeTime`, `endDate`, `timeFormat` ("12h"|"24h"); `phone` \u2014 `defaultCountryCode` (3-letter); `currency` \u2014 `defaultCurrency`, `allowedCurrencies`, `allowNegative`; `status`/`select`/`multiselect` \u2014 `options` (REQUIRED, non-empty array of `{ value, label, color }`, unique `value`s; for `status` every OPTION also carries `group` as idle|in_progress|finished \u2014 `group` belongs on each option, never on `config` itself; select/multiselect accept `renderAs: "badges"`); `location` \u2014 `granularity`, `defaultCountry`, `allowedCountries`; `user` \u2014 `types` ("user"|"agent"), `multiple`; `relation` \u2014 `targets` (REQUIRED, non-empty array of `{ object }`) and `cardinality` (REQUIRED, "one"|"many"); `formula` \u2014 `expression` (REQUIRED formula string) and `returnType` (REQUIRED); `rollup` \u2014 `targetAttribute` (REQUIRED) and `function` (REQUIRED, e.g. "sum"|"avg"|"count"); `document` \u2014 `properties`, `accepts`, `maxFileSize`. Omit entirely for `richtext`/`checkbox`, which take no type-specific keys.'),required:z.boolean().optional().describe("Whether the attribute must have a value on every record. Defaults to false (optional)."),description:z.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),Pp=ss(cs),Mp=ss(cs.omit({objectName:true})),Fp=z.object({name:_p,label:z.string().min(1).describe('Human-readable singular display label (e.g. "Devis").'),pluralLabel:z.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:z.string().optional().describe("Help text describing what this object represents."),icon:t.describe("Required icon name for the object. Must be a catalogue value \u2014 call `search_icons` and use a name it returns verbatim. A name that is not in the catalogue is rejected without any hint as to what would have worked, so never guess one."),labelExpression:rt.describe('Template used to render a human-readable label for every record of this object \u2014 e.g. shown in relations, search results, and breadcrumbs. MUST contain at least one `{{ attributeName }}` interpolation referencing an attribute this object will actually have (either declared in this same `attributes` array, or an existing attribute if this is an update) \u2014 a plain string with no `{{ }}` at all (e.g. "Devis") is rejected. Interpolations cannot be empty (`{{ }}` is rejected) and only these pipes are allowed: UPPER, LOWER, capitalize, trim, prefix:"...", suffix:"...", wrap:"..." "...", default:"...". `{{ a || b }}` falls back to `b` when `a` is empty. Examples: "{{ firstName }} {{ lastName }}", "{{ numero | UPPER }}", "{{ name || reference }}".'),attributes:z.array(Mp).default([]).describe("Attributes to create on this new object, inline. Same rules as a standalone entry in `additive.attributes`, minus `objectName` (implied by this object). At least one attribute referenced by `labelExpression` should be included here.")}).strict(),us=z.object({attributeRemovals:z.array(z.object({objectName:z.string().min(1).describe("Object the attribute is removed from."),attributeName:z.string().min(1).describe("Attribute to delete, together with every record's stored value for it. Must not be a system (code-declared) attribute, and must not be referenced by the object's own `labelExpression` or `embeddingExpression` \u2014 update those first.")}).strict()).default([]).describe("Attributes to permanently delete. Irreversible: record values for the attribute are purged."),objectRemovals:z.array(z.object({objectName:z.string().min(1).describe("Object to delete entirely, together with all its records. Must not be a system (code-declared) object, and must not still be targeted by a `relation` attribute on another object \u2014 retarget or remove that relation first.")}).strict()).default([]).describe("Objects to permanently delete, records included. Irreversible."),renames:z.array(z.object({objectName:z.string().min(1).describe("Object the renamed attribute belongs to."),from:z.string().min(1).describe("Current attribute name. Must already exist and not be a system attribute."),to:as.describe("New attribute name \u2014 same identifier rules as any attribute `name` (see `name` on a planned attribute), and must not collide with another name already on the object, including one added elsewhere in this same plan.")}).strict()).default([]).describe("Attribute renames. Every reference to the old name (labelExpression, views, formulas) must be updated separately \u2014 a rename does not follow references automatically.")}).strict().default({attributeRemovals:[],objectRemovals:[],renames:[]}),ls=z.string().min(1).describe("ONE sentence naming the intent of the change \u2014 what it is for, not what it contains. The human approving it has already watched every entry land in the preview window and can read every row of the plan itself, so a recap tells them nothing they do not have. A second sentence is warranted only when `destructive` is non-empty: say plainly what will be lost (e.g. 'deletes the \"ancienMontant\" column and its data on every devis'). Never restate the plan \u2014 explain intent."),ds=z.object({objects:z.array(Fp).default([]),attributes:z.array(Pp).default([])}).strict().default({objects:[],attributes:[]});function Bi(e,t=[],n=new WeakSet){if(e===null||typeof e=="string"||typeof e=="boolean")return null;if(typeof e=="number")return Number.isFinite(e)?null:{path:t,message:"Plan input contains a non-finite number"};if(typeof e!="object")return {path:t,message:"Plan input must contain only JSON-safe values"};if(n.has(e))return {path:t,message:"Plan input cannot contain circular references"};if(Array.isArray(e)){n.add(e);for(let s of Reflect.ownKeys(e))if(s!=="length"&&(typeof s=="symbol"||!/^(0|[1-9]\d*)$/.test(s)))return n.delete(e),{path:[...t,s],message:"Plan input arrays cannot contain non-index JSON properties"};for(let s=0;s<e.length;s++){if(!Object.hasOwn(e,s))return n.delete(e),{path:[...t,s],message:"Plan input cannot contain sparse arrays"};let c=Bi(e[s],[...t,s],n);if(c)return n.delete(e),c}return n.delete(e),null}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return {path:t,message:"Plan input must contain only plain JSON objects"};n.add(e);let o=e,a=Reflect.ownKeys(o);for(let s of a){let c=Object.getOwnPropertyDescriptor(o,s);if(typeof s=="symbol"||!(c?.enumerable&&"value"in c))return n.delete(e),{path:[...t,s],message:"Plan input objects must contain enumerable JSON data properties only"}}for(let s of a.sort()){let c=Bi(o[s],[...t,s],n);if(c)return n.delete(e),c}return n.delete(e),null}a(Bi,"findJsonSafetyIssue");function Vp(e){let t=[];return e.additive.objects.forEach((n,r)=>{t.push(["additive","objects",r]),n.attributes.forEach((o,a)=>{t.push(["additive","objects",r,"attributes",a]);});}),e.additive.attributes.forEach((n,r)=>{t.push(["additive","attributes",r]);}),e.destructive.attributeRemovals.forEach((n,r)=>{t.push(["destructive","attributeRemovals",r]);}),e.destructive.objectRemovals.forEach((n,r)=>{t.push(["destructive","objectRemovals",r]);}),e.destructive.renames.forEach((n,r)=>{t.push(["destructive","renames",r]);}),t}a(Vp,"mutationPaths");function ps(e,t){e.additive.objects.length>de.objectAdditions&&t.addIssue({code:"too_big",origin:"array",maximum:de.objectAdditions,inclusive:true,path:["additive","objects",de.objectAdditions],message:`A schema plan can add at most ${de.objectAdditions} objects`});let n=Vp(e);n.length>de.totalMutations&&t.addIssue({code:"too_big",origin:"array",maximum:de.totalMutations,inclusive:true,path:n[de.totalMutations],message:`A schema plan can contain at most ${de.totalMutations} mutations; received ${n.length}`});}a(ps,"addPlanLimitIssues");function ms(e,t){let n=Bi(e);if(n)return t.addIssue({code:"custom",path:n.path,message:n.message}),z.NEVER;let r=new TextEncoder().encode(b$3(e)).byteLength;return r>de.serializedBytes?(t.addIssue({code:"too_big",origin:"string",maximum:de.serializedBytes,inclusive:true,path:[],message:`A schema plan can serialize to at most ${de.serializedBytes} UTF-8 bytes; received ${r}`}),z.NEVER):e}a(ms,"boundSerializedPlanInput");var os=z.object({schemaPlanVersion:z.literal(2).describe("Required proposal contract version."),summary:ls,additive:ds,destructive:us}).strict().superRefine(ps),ZI=Object.assign(z.preprocess(ms,os),{shape:os.shape}),Bp=z.object({schemaPlanVersion:z.literal(2),summary:ls,additive:ds,destructive:us}).strict().superRefine(ps),XI=z.preprocess(ms,Bp);function ft(e,t){throw new h$1(t,[{path:e,message:t}])}a(ft,"reject");function Cn(e){throw new h$1(`Unsupported schema reference variant ${String(e)}`,[])}a(Cn,"exhaustive");function sR(e){let t=new Map(e.objects.map(s=>[s.name,s])),n=[];function r(s,c,u){function l(y,A,h){(y.kind==="object"?t.has(y.object):y.kind==="attribute"?t.get(y.object)?.attributes.some(_=>_.name===y.attribute):true)||ft([...c,...h],`Unknown schema reference ${JSON.stringify(y)}`),n.push({owner:s,target:y,category:A,path:h,...u===void 0?{}:{layer:u}});}a(l,"add");function m(y,A,h,k){l({kind:"attribute",object:y,attribute:A},h,k);}a(m,"attribute");function d(y,A,h,k,_){m(y,A,h,k);let O=t.get(y)?.attributes.find(B=>B.name===A);return O?.type!=="relation"&&ft([...c,...k],`Invalid schema reference path "${_}"`),(O.targets.length!==1||O.targets[0].object==="*")&&ft([...c,...k],`Ambiguous schema reference path "${_}"`),O.targets[0].object}a(d,"traverse");function b(y,A,h,k){let _=y;for(let[O,B]of A.entries())O===A.length-1?m(_,B,h,k):_=d(_,B,h,k,A.join("."));}a(b,"attributePath");function g(y,A,h){switch(A.kind){case "literal":return;case "path":b(y,A.parts,"computed",h);return;case "call":for(let k of A.args)g(y,k,h);return;case "binary":g(y,A.left,h),g(y,A.right,h);return;default:Cn(A);}}return a(g,"formula"),{add:l,attribute:m,traverse:d,attributePath:b,formula:g}}a(r,"visitor"),e.objects.forEach((s,c)=>{let u=["objects",String(c)],l=r({kind:"object",object:s.name},u);for(let m of ["labelExpression","embeddingExpression"]){let d=s[m];if(d)for(let b of St(d))l.attributePath(s.name,b.split("."),"business",[m]);}s.attributes.forEach((m,d)=>{let b=[...u,"attributes",String(d)],g=r({kind:"attribute",object:s.name,attribute:m.name},b);switch(m.type){case "relation":m.targets.forEach((y,A)=>{if(y.object!=="*"&&g.add({kind:"object",object:y.object},"structural",["targets",String(A),"object"]),y.displayTemplate)for(let h of St(y.displayTemplate))g.attributePath(y.object,h.split("."),"business",["targets",String(A),"displayTemplate"]);for(let h of Object.keys(y.filter??{}))g.attribute(y.object,h,"business",["targets",String(A),"filter",h]);});break;case "formula":{let y;try{y=v$1(m.expression);}catch(A){ft([...b,"expression"],A instanceof Error?A.message:String(A));}g.formula(s.name,y,["expression"]),o(m,g);break}case "rollup":{let y=m.relationPath??m.relationAttribute,A=s.name;for(let h of y.split("."))A=g.traverse(A,h,"computed",[m.relationPath===void 0?"relationAttribute":"relationPath"],y);g.attributePath(A,m.targetAttribute.split("."),"computed",["targetAttribute"]),o(m,g);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:Cn(m);}});});function o(s,c){s.optionsSource&&(c.add({kind:"object",object:s.optionsSource.objectName},"computed",["optionsSource","objectName"]),c.attribute(s.optionsSource.objectName,s.optionsSource.attributeName,"computed",["optionsSource","attributeName"]));}a(o,"visitOptions");function a$1(s,c,u){r({kind:"view",object:s.object,view:s.name},c,u).add({kind:"object",object:s.object},"structural",["object"]),s.contents.forEach((l,m)=>{let d=r({kind:"content",object:s.object,view:s.name,content:l.name},[...c,"contents",String(m)],u);function b(g,y,A,h){g?.forEach((k,_)=>d.attribute(y,k,A,[h,String(_)]));}switch(a(b,"names"),l.type){case "collection":{let g=ze(l.source),y;switch(g.kind==="object"?(y=g.object,d.add({kind:"object",object:y},"source",["source","object"])):g.kind==="relatedFrom"?(y=g.object,d.add({kind:"object",object:y},"source",["source","object"]),d.attribute(y,g.relation,"source",["source","relation"])):y=d.traverse(s.object,g.relation,"source",["source","relation"],g.relation),l.columns?.forEach((A,h)=>{if(typeof A=="string"){d.attribute(y,A,"display",["columns",String(h)]);return}let k=t.get(s.object),_=g.kind!=="related"||!k?void 0:Ra(k,g.relation),O=["columns",String(h),"relationProperty"];_||ft([...c,"contents",String(m),...O],"Relation property columns require a relation source"),_.properties?.definitions.some(B=>B.name===A.relationProperty)||ft([...c,"contents",String(m),...O],`Unknown relation property "${A.relationProperty}"`),d.add({kind:"attribute",object:s.object,attribute:_.name},"display",O);}),b(l.displayAttributes,y,"display","displayAttributes"),l.descriptionAttribute!==void 0&&d.attribute(y,l.descriptionAttribute,"display",["descriptionAttribute"]),l.filters?.rules.forEach((A,h)=>d.attribute(y,A.attribute,"business",["filters","rules",String(h),"attribute"])),l.sorts?.forEach((A,h)=>d.attribute(y,A.attribute,"business",["sorts",String(h),"attribute"])),l.layout){case "table":case "list":if(l.columnSizing)for(let A of Object.keys(l.columnSizing))d.attribute(y,A,"display",["columnSizing",A]);break;case "kanban":l.groupByAttribute!==void 0&&d.attribute(y,l.groupByAttribute,"business",["groupByAttribute"]);break;default:Cn(l.layout);}break}case "form":l.groups.forEach((g,y)=>g.fields.forEach((A,h)=>d.attribute(s.object,A.attribute,"display",["groups",String(y),"fields",String(h),"attribute"])));break;case "richtext":d.attribute(s.object,l.attribute,"source",["attribute"]),l.titleAttribute!==void 0&&d.attribute(s.object,l.titleAttribute,"display",["titleAttribute"]);break;case "documents":b(l.relations,s.object,"business","relations");break;case "forms":l.objectName!==void 0&&d.add({kind:"object",object:l.objectName},"source",["objectName"]);break;case "emails":case "meetings":b(l.emailAttributes,s.object,"business","emailAttributes");break;case "activity":case "custom":break;default:Cn(l);}});}return a(a$1,"viewReferences"),e.views.forEach((s,c)=>a$1(s,["views",String(c)])),e.retainedViews?.forEach(({definition:s,layer:c},u)=>a$1(s,["retainedViews",String(u),"definition"],c)),n}a(sR,"collectSchemaReferences");var fs=/^[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 $(e,t,n){throw new h$1(n,[{path:[...e.split("."),t],message:n}])}a($,"reject");function $i(e){return e.join("|")}a($i,"pairKey");function Ui(e,t){return [e,t].sort()}a(Ui,"pairedAddresses");function Lp(e){let t=new Map,n=new Map,r=new Set;for(let o of e){let a=$i(o.addresses);(!fs.test(o.id)||o.addresses[0]===o.addresses[1]!=(o.symmetric===true))&&$(o.addresses[0],"pair",`Invalid stored pair identity for ${a}`),(t.has(a)||n.has(o.id)&&n.get(o.id)!==a||o.addresses.some(s=>r.has(s)))&&$(o.addresses[0],"pair",`Duplicate stored pair identity for ${a}`),o.addresses.includes(o.ownerAddress)||$(o.addresses[0],"pair",`Invalid property owner for ${a}`),t.set(a,o),n.set(o.id,a);for(let s of o.addresses)r.add(s);}return t}a(Lp,"validateExistingPairs");function $p(e,t){let n=new Set(e.flatMap(s=>s.addresses)),r=new Map,o=new Set;for(let{from:s,to:c}of t)(!n.has(s)||s===c||r.has(s)||o.has(c))&&$(s,"rename",`Invalid or duplicate relation attribute rename ${s} to ${c}`),r.set(s,c),o.add(c);let a$1=a(s=>r.get(s)??s,"mapped");return e.map(s=>({...s,addresses:Ui(a$1(s.addresses[0]),a$1(s.addresses[1])),ownerAddress:a$1(s.ownerAddress),generatedAddresses:s.generatedAddresses.map(a$1)}))}a($p,"remapExistingPairs");function Up(e,t,n){return e.type==="relation"&&e.bilateral?.object===t&&e.bilateral.attribute===n&&e.targets.length===1&&e.targets[0]?.object===t}a(Up,"isReciprocal");function qp(e,t,n){let r=e.bilateral;r||$(`${t}.${e.name}`,"bilateral","Missing inverse address");let o={type:"relation",name:r.attribute,label:r.label??r.attribute,required:false,targets:[{object:t}],bilateral:{object:t,attribute:e.name,cardinality:e.cardinality},order:n};return (r.cardinality??Bo(e.cardinality))==="one"?{...o,cardinality:"one"}:{...o,cardinality:"many"}}a(qp,"generateInverse");function zp(e,t,n,r,o){e.bilateral?.cardinality&&e.bilateral.cardinality!==t.cardinality&&$(r,"cardinality",`${n} declares ${r} as ${e.bilateral.cardinality}, but ${r} declares ${t.cardinality}`),t.bilateral?.cardinality&&t.bilateral.cardinality!==e.cardinality&&$(n,"cardinality",`${r} declares ${n} as ${t.bilateral.cardinality}, but ${n} declares ${e.cardinality}`),e.bilateral?.label&&e.bilateral.label!==t.label&&$(r,"label",`${n} declares a different label for ${r}`),t.bilateral?.label&&t.bilateral.label!==e.label&&$(n,"label",`${r} declares a different label for ${n}`),e.properties&&t.properties&&!j$2(e.properties,t.properties)&&!o&&$(r,"properties",`${n} and ${r} declare different qualified properties`),e.bilateral?.storageOwner===t.bilateral?.storageOwner&&e.bilateral?.storageOwner!==void 0&&$(r,"storageOwner",`${n} and ${r} cannot both own or both disown qualified properties`);}a(zp,"checkExplicitDeclarations");function Wp(e,t,n,r,o,a){return o?o.ownerAddress:e.bilateral?.storageOwner===true||t.bilateral?.storageOwner===false?n:e.bilateral?.storageOwner===false||t.bilateral?.storageOwner===true?r:a?n:Ui(n,r)[0]}a(Wp,"chooseOwner");function Gp(e){if(!e.metadata)return;let{relationPairId:t,relationGenerated:n,...r}=e.metadata;e.metadata=Object.keys(r).length>0?r:void 0;}a(Gp,"stripUntrustedPairMetadata");function Kp(e,t,n,r,o,a){a.has(n)&&a.has(r)&&!j$2(e.properties,t.properties)&&$(r,"properties",`${n} and ${r} edit different qualified properties`);let s=a.has(n)||o.has(n)&&!o.has(r)&&!a.has(r),c=a.has(r)||o.has(r)&&!o.has(n)&&!a.has(n),u=s?e.properties:c?t.properties:e.properties??t.properties;u?(e.properties=structuredClone(u),t.properties=structuredClone(u)):(delete e.properties,delete t.properties);}a(Kp,"reconcileProperties");function qi(e){let t=structuredClone(e.objects),n=new Map;for(let d of t){if(n.has(d.name))throw new r("object",d.name);n.set(d.name,d);let b=new Set;for(let g of d.attributes){if(b.has(g.name))throw new r("attribute",g.name);b.add(g.name),Gp(g);}}let r$1=$p(e.existingPairs??[],e.addressRenames??[]),o=Lp(r$1),a=new Set(r$1.flatMap(d=>d.generatedAddresses)),s=new Set(e.propertyEditAddresses??[]),c=new Set(e.explicitAddresses??t.flatMap(d=>d.attributes.filter(b=>!a.has(`${d.name}.${b.name}`)).map(b=>`${d.name}.${b.name}`))),u=t.flatMap(d=>d.attributes.filter(b=>b.type==="relation"&&!!b.bilateral).map(b=>({object:d,attribute:b,address:`${d.name}.${b.name}`}))).sort((d,b)=>d.address.localeCompare(b.address)),l=new Map,m=new Map;for(let{object:d,attribute:b,address:g}of u){let y=b.bilateral?.object;(!y||y==="*"||b.targets.length!==1||b.targets[0]?.object!==y)&&$(g,"targets",`Bilateral target of ${g} must be one concrete object`);let A=n.get(y);A||$(g,"bilateral",`Unknown inverse object ${y} for ${g}`);let h=`${y}.${b.bilateral?.attribute}`,k=g===h;k&&b.cardinality!=="many"&&$(g,"cardinality",`Symmetric self relation ${g} must be many`),k&&b.bilateral?.cardinality&&b.bilateral.cardinality!==b.cardinality&&$(g,"bilateral",`Symmetric self relation ${g} needs matching cardinality`);let _=Ui(g,h),O=$i(_);if(l.has(O))continue;let B=A.attributes.find(Ie=>Ie.name===b.bilateral?.attribute);if(B&&!Up(B,d.name,b.name))throw new r("attribute",h);let Se=!(B&&c.has(h));B||(B=qp(b,d.name,A.attributes.length),A.attributes.push(B));let K=B;!k&&c.has(g)&&c.has(h)&&zp(b,K,g,h,s.has(g)!==s.has(h));let j=o.get(O),M=j?.id??e.nextPairId(_),oe=r$1.find(Ie=>Ie.id===M&&$i(Ie.addresses)!==O);(!fs.test(M)||oe||m.has(M)&&m.get(M)!==O)&&$(g,"pair",`Invalid or duplicate pair identity for ${g} and ${h}`),m.set(M,O);let ee=k?g:Wp(b,K,g,h,j,Se);b.bilateral&&K.bilateral||$(g,"bilateral",`Missing reciprocal configuration for ${g} and ${h}`),b.bilateral={...b.bilateral,cardinality:K.cardinality,label:K.label,storageOwner:ee===g},K.bilateral={...K.bilateral,cardinality:b.cardinality,label:b.label,storageOwner:ee===h},Kp(b,K,g,h,c,s),b.metadata={...b.metadata,relationPairId:M},K.metadata={...K.metadata,relationPairId:M},l.set(O,{id:M,addresses:_,ownerAddress:ee,generatedAddresses:_.filter(Ie=>!c.has(Ie)),...k?{symmetric:true}:{}});}return {objects:t,pairs:[...l.values()].sort((d,b)=>d.addresses[0].localeCompare(b.addresses[0]))}}a(qi,"reconcileRelationAttributes");var v=z.number().finite().nonnegative(),gs=z.enum($o),zi=z.enum(Uo),Wi=z.enum(qo),ys=z.object({provider:gs,model:z.string().min(1)}).strict(),hR=z.object({speed:zi.optional(),reasoning:Wi.optional()}).strict(),hs=z.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),Yp=z.object({model:ys.optional(),speed:zi.optional(),reasoning:Wi.optional(),imageModel:hs.optional()}).strict(),AR=Yp.refine(e=>e.model!==void 0||e.speed!==void 0||e.reasoning!==void 0||e.imageModel!==void 0,{message:"At least one inference override is required"}),xR=z.object({model:ys.nullable().optional(),speed:zi.nullable().optional(),reasoning:Wi.nullable().optional(),imageModel:hs.nullable().optional()}).strict().refine(e=>Object.keys(e).length>0&&Object.values(e).every(t=>t!==void 0),{message:"At least one inference override is required"}),As=z.object({label:z.string(),denied:z.boolean().optional(),deletion:z.object({target:z.string().optional(),count:v.optional(),restorableDays:v.optional()}).strict().optional(),counts:z.record(z.string(),v).optional(),warnings:z.array(z.string()).optional()}).strict(),Hp=z.union([z.object({type:z.literal("text"),text:z.string()}).strict(),z.object({type:z.literal("reasoning"),text:z.string()}).strict(),z.object({type:z.literal("system"),code:z.enum(Gn)}).strict(),z.object({type:z.literal("error"),error:z.string(),errorClass:z.string().optional()}).strict(),z.object({type:z.literal("tool"),toolCallId:z.string(),name:z.string(),args:z.record(z.string(),z.unknown()),result:z.unknown().optional(),error:z.string().optional(),errorCode:z.enum(["output_limit_reached","interrupted"]).optional(),state:z.enum(["streaming","running","completed","error","pending","approval-requested","approval-responded","approval-dispatched"]),durationMs:v.optional(),approvalId:z.string().optional(),approvalImpact:As.optional(),approved:z.boolean().optional(),approvalReason:z.string().optional(),approvalRelaxableByAuto:z.boolean().optional()}).strict(),z.object({type:z.literal("file"),fileId:z.string(),name:z.string(),mimeType:z.string()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("in-progress"),reason:z.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:v.optional(),reportedTokens:v.optional()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("completed"),tokensBefore:v,tokensAfter:v,tokensSaved:v,strategy:z.enum(["no-op","summary","truncation"]),durationMs:v,summary:z.string().optional()}).strict(),z.object({type:z.literal("compaction"),state:z.literal("failed"),reason:z.string(),durationMs:v.optional()}).strict()]),Jp=z.object({id:z.string(),name:z.string(),mimeType:z.string(),size:v}).strict(),Qp=z.object({id:z.string(),type:z.string().transform(e=>e),entityId:z.string(),label:z.string(),objectName:z.string().optional(),startIndex:v,endIndex:v}).strict(),Zp=z.object({provider:gs,model:z.string(),maxTokens:v.optional(),contextWindow:v.optional()}).strict(),Xp=z.union([z.date(),z.string().datetime({offset:true}).transform(e=>new Date(e))]),bs=z.object({id:z.string(),sessionId:z.string(),tenantId:z.string().optional(),runId:z.string().optional(),role:z.enum(["user","assistant","system","tool"]),parts:z.array(Hp),attachments:z.array(Jp).optional(),mentions:z.array(Qp).optional(),model:Zp.optional(),tokenUsage:z.object({input:v,output:v}).strict().optional(),metadata:z.record(z.string(),z.unknown()).optional(),createdAt:Xp}).strict(),em=z.object({id:z.string(),description:z.string(),status:z.enum(["pending","in_progress","completed","blocked"]),result:z.string().optional(),updatedAt:v.optional()}).strict(),tm=z.object({id:z.string(),sessionId:z.string(),status:z.enum(["active","completed","abandoned"]),todos:z.array(em),version:v,createdAt:z.string(),updatedAt:z.string(),completedAt:z.string().optional()}).strict(),xs={"session-named":z.object({name:z.string()}).strict(),"compaction-start":z.object({reason:z.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:v.optional(),reportedTokens:v.optional()}).strict(),"compaction-end":z.object({tokensBefore:v,tokensAfter:v,tokensSaved:v,strategy:z.enum(["no-op","summary","truncation"]),durationMs:v,summary:z.string().optional()}).strict(),"compaction-failed":z.object({reason:z.string()}).strict(),usage:z.object({messageId:z.string().min(1).optional(),inputTokens:v,outputTokens:v,totalTokens:v,cacheReadTokens:v.optional(),cacheCreationTokens:v.optional(),contextWindow:v,residentTokens:v,utilization:z.number().finite().min(0).max(1),costUsd:v.optional()}).strict(),"message-persisted":z.object({message:bs}).strict(),"message-updated":z.object({message:bs}).strict(),"todo-plan-update":z.object({plan:tm}).strict(),"approval-context":z.object({approvalId:z.string(),toolCallId:z.string(),impact:As.optional(),relaxableByAuto:z.boolean().optional()}).strict(),"session-state":z.object({state:z.object({phase:z.enum(["queued","running","parked","terminal"]),parkedOn:z.enum(["human","agents"]).optional(),humanRequestIds:z.array(z.string()).optional(),outcome:z.enum(["completed","failed","cancelled","timeout","expired"]).optional()}).strict(),version:z.number().int().positive(),updatedAt:z.string().datetime({offset:true})}).strict()};function nm(e){return e in xs}a(nm,"isAgentUIDataName");function rm(e){return new h$1("Invalid agent UI message chunk",e.map(t=>({path:t.path.map(String),message:t.message,code:t.code})))}a(rm,"agentUIValidationError");function im(e){if(typeof e!="object"||e===null||typeof e.type!="string")throw new h$1("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 h$1("Invalid agent UI message chunk",[{path:["type"],message:"Expected agent data chunk type",code:"invalid_value"}]);let n=t.slice(5);if(!nm(n))throw new h$1("Invalid agent UI message chunk",[{path:["type"],message:`Unknown agent UI data type: ${n}`,code:"invalid_value"}]);let r=z.object({type:z.literal(`data-${n}`),id:z.string().optional(),data:xs[n],transient:z.boolean().optional()}).strict().safeParse(e);if(!r.success)throw rm(r.error.issues);return r.data}a(im,"assertCustomAgentUIMessageChunk");function TR(e,t,n){return im({type:`data-${e}`,...n?.id!==void 0?{id:n.id}:{},data:t,...n?.transient!==void 0?{transient:n.transient}:{}})}a(TR,"agentDataChunk");function Gi(e){return e}a(Gi,"defineOperation");function V(e,t,n){let r=t==="atomic"?"none":t==="local"?"if-not-visible":"follow";return o=>{let a=n?.(o);return {impact:t,navigation:r,focus:{...e(o),...a===void 0?{}:{propertyPath:a}}}}}a(V,"definePresentation");function om(e){return {id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon}}}a(om,"toDraftableObject");function am(e){let t=e.id??e.name;return (e.attributes??[]).map(n=>Ki(n,t))}a(am,"toDraftableAttributes");function Z(e){return {id:e.id,name:e.name,label:e.label,type:e.attributeType,...e.config}}a(Z,"toAttribute");function Ki(e,t){let{id:n,name:r,label:o,type:a,...s}=e;return {id:e.id??e.name,objectId:t,name:e.name,label:e.label??e.name,attributeType:e.type,config:s}}a(Ki,"toDraftableAttribute");function Ts(e){let t=e[0];return t?`{{ ${t.name} }}`:"{{ id }}"}a(Ts,"draftedLabelExpression");function Yi(e,t){let n=t.filter(r=>r.objectId===e.id);return {id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},labelExpression:Ts(n),attributes:n.map((r,o)=>{let a=Z(r);return a.order===void 0?{...a,order:o}:a})}}a(Yi,"draftedObjectDefinition");function sm(e,t,n=Et(e.contents)){return structuredClone({...e,...t,authoring:n})}a(sm,"toDraftableView");function bt(e){let{id:t,revision:n,contentIds:r,contentRevisions:o,derived:a,authoring:s,...c}=e;return structuredClone(c)}a(bt,"draftedViewDefinition");function cm(e,t){return {...e,...bt(t)}}a(cm,"fromDraftableView");var _t={id:z.string().min(1).describe("Your id, echoed back"),note:z.string().trim().min(1).max(160).optional().describe("Why, in the person's words, \u2264160 chars")};var Pt={..._t,objectName:z.string().min(1).describe("Object"),viewName:z.string().min(1).describe("View API name")},gt={...Pt,contentName:z.string().min(1).describe("Content API name")},Cs=z.union([z.object({before:z.string().min(1).describe("Place immediately before this content name")}).strict(),z.object({after:z.string().min(1).describe("Place immediately after this content name")}).strict(),z.object({end:z.literal(true).describe("Place at the end of the placement zone")}).strict()]),Ke=a(e=>({objectName:e.objectName,viewName:e.viewName}),"viewFocus"),Me=a(e=>({...Ke(e),contentName:e.contentName}),"contentFocus");function pe(e,t){throw new h$1(t,[{path:e,message:t}])}a(pe,"invalid");function Ne(e,t,n,r){let o=e.views.findIndex(u=>u.object===t.objectName&&u.name===t.viewName);o<0&&pe(["viewName"],"View is not in the draftable state"),e.views[o].authoring||pe(["authoring"],"Missing view authoring baseline");let{derived:a,...s}=r(structuredClone(e.views[o]));s.contents=Ai(s.authoring);let c=e.views.map((u,l)=>l===o?s:u);return Ti({extensions:[...n.extensions],objects:e.objects.map(u=>Yi(u,e.attributes.filter(l=>l.objectId===u.id))),views:c.map(bt)}),{...e,views:c}}a(Ne,"change");function Ye(e,t){let n=Object.hasOwn(e.authoring.contents,t)?e.authoring.contents[t]:void 0;return n||pe(["contentName"],"Content is not in the draftable state"),n}a(Ye,"contentState");function Hi(e,t,n){for(let r of n)e.authoring[r==="main"?"mainOrderCustomized":"asideOrderCustomized"]=true,t.filter(o=>o.placement===r).forEach((o,a)=>{Ye(e,o.name).workspacePosition=a;});}a(Hi,"setOrder");function Ji(e,t){let n=e.contents.find(r=>r.name===t);return n||pe(["contentName"],"Content is not in the draftable state"),n}a(Ji,"find");function vs(e,t,n){let r=e.filter(s=>s.name!==t.name),o=r.filter(s=>s.placement===t.placement),a=o.length;if(!("end"in n)){let s="before"in n?n.before:n.after;a=o.findIndex(c=>c.name===s),a<0&&pe(["target"],"Order target is not in this placement"),"after"in n&&a++;}return o.splice(a,0,t),t.placement==="main"?[...o,...r.filter(s=>s.placement==="aside")]:[...r.filter(s=>s.placement==="main"),...o]}a(vs,"placed");var um=z.unknown().transform((e,t)=>{let n=W$1.safeParse(typeof e=="object"&&e!==null?{...e,name:"candidate"}:e);if(!n.success){for(let o of n.error.issues)t.addIssue({code:"custom",path:o.path,message:o.message});return z.NEVER}let r=typeof e=="object"&&e!==null&&"name"in e?e.name:void 0;return {...n.data,name:r}}),Ns=z.object({...gt,type:z.literal("replace_view_content"),definition:um}).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}}),Es=W$1.describe("The whole content definition."),lm=z.object({...gt,type:z.literal("replace_view_content"),definition:Es}).strict().describe("definition.name, if sent, must equal contentName \u2014 the operation's own target; a different name is refused."),dm={type:"replace_view_content",summary:"Replaces a content's whole definition; placement can't change here (use move_view_content); first content op freezes derived views.",schema:Ns,wire:lm,focus:Me,presentation:V(Me,"local"),describe:a(e=>`Replace ${e.objectName}.${e.viewName}.${e.contentName}`,"describe"),apply:a((e,t,n)=>Ne(e,t,n,r=>(Ji(r,t.contentName).placement!==t.definition.placement&&pe(["definition","placement"],"Use move_view_content to change placement"),Ye(r,t.contentName).workspaceDefinition=structuredClone(t.definition),{...r,contents:r.contents.map(a=>a.name===t.contentName?{...t.definition,name:t.contentName}:a),contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}})),"apply")},Ds=z.object({...Pt,type:z.literal("add_view_content"),content:Es,target:Cs.describe("Where to place the new content within its placement zone")}).strict(),Ss=a(e=>({...Ke(e),contentName:e.content.name}),"addFocus"),pm={type:"add_view_content",summary:"Adds a content; content.name unique; collection view needs collection with source.object; aside holds one content, a form; target positions it among siblings.",schema:Ds,focus:Ss,presentation:V(Ss,"structural"),describe:a(e=>`Add ${e.content.name}`,"describe"),apply:a((e,t,n)=>Ne(e,t,n,r$1=>{if(Object.hasOwn(r$1.authoring.contents,t.content.name))throw new r("content",t.content.name);r$1.authoring.contents={...r$1.authoring.contents,[t.content.name]:{sourceDefinition:null,workspaceDefinition:Nt(t.content),suppressed:false,sourcePosition:null,workspacePosition:0}};let o=vs(r$1.contents,t.content,t.target);return Hi(r$1,o,[t.content.placement]),{...r$1,revision:r$1.revision+1,contents:o,contentIds:{...r$1.contentIds,[t.content.name]:JSON.stringify(["draft-content",t.id])},contentRevisions:{...r$1.contentRevisions,[t.content.name]:1}}}),"apply")},Os=z.object({...gt,type:z.literal("remove_view_content")}).strict(),mm={type:"remove_view_content",summary:"Removes a content; a published view keeps \u22651 main content; a code-declared content is hidden, not deleted.",schema:Os,focus:Me,presentation:V(Me,"structural"),describe:a(e=>`Remove ${e.contentName}`,"describe"),apply:a((e,t,n)=>Ne(e,t,n,r=>{let o=Ji(r,t.contentName),a=Ye(r,t.contentName),s=r.contents.filter(d=>d.name!==t.contentName);if(Hi(r,s,[o.placement]),a.sourceDefinition!==null)return a.workspaceDefinition=null,a.suppressed=true,{...r,revision:r.revision+1,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}};delete r.authoring.contents[t.contentName];let{[t.contentName]:c,...u}=r.contentIds,{[t.contentName]:l,...m}=r.contentRevisions;return {...r,revision:r.revision+1,contents:r.contents.filter(d=>d.name!==t.contentName),contentIds:u,contentRevisions:m}}),"apply")},js=z.object({...gt,type:z.literal("move_view_content"),placement:z.enum(["main","aside"]).describe("The placement zone to move the content into"),target:Cs.describe("Where to place the content within that placement zone")}).strict(),fm={type:"move_view_content",summary:"Reorders or moves a content to a different placement; the aside rule applies.",schema:js,focus:Me,presentation:V(Me,"structural"),describe:a(e=>`Move ${e.contentName}`,"describe"),apply:a((e,t,n)=>Ne(e,t,n,r=>{let o=Ji(r,t.contentName);o.placement!==t.placement&&(Ye(r,t.contentName).workspaceDefinition={...Nt(o),placement:t.placement});let a=vs(r.contents,{...o,placement:t.placement},t.target);return Hi(r,a,[...new Set([o.placement,t.placement])]),{...r,revision:r.revision+1,contents:a,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+ +(o.placement!==t.placement)}}}),"apply")},ks=z.object({...Pt,type:z.literal("update_view_metadata"),changes:z.object({label:z.string().min(1).optional().describe("New label for the view"),description:z.string().optional().describe("New description for the view"),icon:t.nullable().optional().describe("New icon; null clears it")}).strict().refine(e=>Object.keys(e).length>0).describe("\u22651 change")}).strict(),bm={type:"update_view_metadata",summary:"Updates a view's label, description, or icon (null clears the icon).",schema:ks,focus:Ke,presentation:V(Ke,"atomic"),describe:a(e=>`Update ${e.viewName}`,"describe"),apply:a((e,t,n)=>Ne(e,t,n,r=>{let{icon:o,...a}=t.changes,s={...r,...a,revision:r.revision+1};if(o===null){let{icon:c,...u}=s;return u}return o===void 0?s:{...s,icon:o}}),"apply")},_s=z.string().refine(e=>e.trim().length>0,"API name must not be blank"),Ps=z.object({...Pt,type:z.literal("rename_view"),newName:_s.describe("New API name for the view")}).strict(),Is=a(e=>({objectName:e.objectName,viewName:e.newName}),"renameViewFocus"),gm={type:"rename_view",summary:"Renames a view; refused on a code-declared name \u2014 change it in the declaration.",schema:Ps,focus:Is,presentation:V(Is,"structural"),describe:a(e=>`Rename view ${e.viewName} to ${e.newName}`,"describe"),apply:a((e,t,n)=>Ne(e,t,n,r=>t.newName===r.name?r:(r.authoring.origin==="code"&&pe(["newName"],"Source-owned API names must be changed in their declaration"),e.views.some(o=>o.object===t.objectName&&o.name===t.newName)&&pe(["newName"],"View API name is already used"),{...r,name:t.newName,revision:r.revision+1})),"apply")},Ms=z.object({...gt,type:z.literal("rename_view_content"),newName:_s.describe("New API name for the content")}).strict(),Rs=a(e=>({...Ke(e),contentName:e.newName}),"renameContentFocus"),ym={type:"rename_view_content",summary:"Renames a content; refused on a code-declared name \u2014 change it in the declaration.",schema:Ms,focus:Rs,presentation:V(Rs,"structural"),describe:a(e=>`Rename content ${e.contentName} to ${e.newName}`,"describe"),apply:a((e,t,n)=>Ne(e,t,n,r=>{let o=Ye(r,t.contentName);if(t.newName===t.contentName)return r;o.sourceDefinition!==null&&pe(["newName"],"Source-owned API names must be changed in their declaration"),Object.hasOwn(r.authoring.contents,t.newName)&&pe(["newName"],"Content API name is already used");let a=r.contentIds[t.contentName],s=r.contentRevisions[t.contentName];return delete r.authoring.contents[t.contentName],delete r.contentIds[t.contentName],delete r.contentRevisions[t.contentName],r.authoring.contents={...r.authoring.contents,[t.newName]:o},{...r,revision:r.revision+1,contentIds:{...r.contentIds,[t.newName]:a},contentRevisions:{...r.contentRevisions,[t.newName]:s+1}}}),"apply")},Fs=z.object({...gt,type:z.literal("reset_view_content")}).strict(),hm={type:"reset_view_content",summary:"Resets a content back to its code-declared source; only works when one exists.",schema:Fs,focus:Me,presentation:V(Me,"structural"),describe:a(e=>`Reset ${e.contentName} to source`,"describe"),apply:a((e,t,n)=>Ne(e,t,n,r=>{let o=Ye(r,t.contentName);return o.sourceDefinition===null&&pe(["contentName"],"Content has no source to reset to"),o.workspaceDefinition===null&&!o.suppressed&&o.workspacePosition===null?r:(o.workspaceDefinition=null,o.suppressed=false,o.workspacePosition=null,{...r,revision:r.revision+1,contentRevisions:{...r.contentRevisions,[t.contentName]:r.contentRevisions[t.contentName]+1}})}),"apply")},Vs=z.object({...Pt,type:z.literal("reset_view_order"),placement:z.enum(["main","aside"]).describe("The placement zone to reset to source order")}).strict(),Am={type:"reset_view_order",summary:"Resets a placement zone's order to its code-declared source, if one exists.",schema:Vs,focus:Ke,presentation:V(Ke,"structural"),describe:a(e=>`Reset ${e.placement} order`,"describe"),apply:a((e,t,n)=>Ne(e,t,n,r=>{let o=t.placement==="main"?"mainOrderCustomized":"asideOrderCustomized";if(!r.authoring[o])return r;r.authoring[o]=false;for(let a of r.contents.filter(s=>s.placement===t.placement)){let s=Ye(r,a.name);s.sourceDefinition!==null&&(s.workspacePosition=null);}return {...r,revision:r.revision+1}}),"apply")},Qi=z.discriminatedUnion("type",[Ns,Ds,Os,js,ks,Ps,Ms,Fs,Vs]),He=[dm,pm,mm,fm,bm,gm,ym,hm,Am];function Bs(e,t){return e.objects.find(n=>n.id===t)}a(Bs,"findObject");var xm=new Set(["formula","rollup"]);function yt(e){return xm.has(e.attributeType)}a(yt,"isComputedAttribute");var Ls={sum:"number",avg:"number",count:"number",countValues:"number",countUniqueValues:"number",countEmpty:"number",percentEmpty:"number",percentNotEmpty:"number",earliest:"date",latest:"date",original:"multiselect"};function Tm(e){return typeof e=="string"&&e in Ls?Ls[e]:void 0}a(Tm,"rollupReturnTypeOf");function Us(e,t){let n=Bs(e,t);if(!n)throw new h$1(`Object "${t}" is not in the draftable state`,[]);return n}a(Us,"requireObject");function vn(e){return e.config??{}}a(vn,"configOf");function X(e){let t=vn(e).targets;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.object=="string"):[]}a(X,"relationTargets");function ht(e){let t=X(e).filter(n=>n.object!==ae);return t.length===1?t[0]?.object:void 0}a(ht,"relationTargetObjectName");function wm(e){let t=vn(e),n=e.attributeType,r={name:e.name,type:n,id:e.id},o=t.optionsSource;if(n==="relation"){let a=ht(e);return {...r,...t.cardinality==="one"||t.cardinality==="many"?{cardinality:t.cardinality}:{},...a===void 0?{}:{targetObjectName:a},targets:X(e)}}if(n==="formula")return {...r,...t.returnType===void 0?{}:{returnType:t.returnType},...o===void 0?{}:{optionsSource:o}};if(n==="rollup"){let a=Tm(t.function);return {...r,...a===void 0?{}:{returnType:a},...o===void 0?{}:{optionsSource:o}}}return n==="select"||n==="status"||n==="multiselect"?{...r,...Array.isArray(t.options)?{options:t.options}:{}}:r}a(wm,"toCompileAttribute");function $s(e,t){return {objectName:e.name,attributes:t.filter(n=>n.objectId===e.id).map(wm)}}a($s,"toCompileObject");function Zi(e,t){let n=Us(e,t);return {...$s(n,e.attributes),relatedObjects:Object.fromEntries(e.objects.map(r=>[r.name,$s(r,e.attributes)]))}}a(Zi,"computedCompileSchemaOf");function Sm(e){return {id:e.id,name:e.name,label:e.label,type:"rollup",...vn(e)}}a(Sm,"toRollupAttribute");function qs(e){try{return e()}catch(t){throw t instanceof I?new h$1(t.message,[]):t}}a(qs,"asValidationError");function Nn(e,t){let n=Zi(e,t.objectId);return qs(()=>zs(t,n))}a(Nn,"computedPlanOf");function zs(e,t){if(e.attributeType==="rollup")return qa(Sm(e),t);let n=vn(e);return gn({attributeName:e.name,expression:String(n.expression??""),returnType:n.returnType,schema:t})}a(zs,"compilePlan");function Xi(e){qs(()=>Ba(e.map(t=>({attributeName:t.attributeName,dependencies:t.dependencies}))));}a(Xi,"assertAcyclicComputed");function Im(e,t){switch(e.kind){case "local":case "computed":return e.attributeName===t;case "relation":return e.relationName===t;case "options":return false;default:return e}}a(Im,"dependencyNames");function Mt(e,t){let n=Zi(e,t),r=[];for(let o of e.attributes)if(!(o.objectId!==t||!yt(o)))try{r.push(zs(o,n));}catch(a){if(!(a instanceof I))throw a}return r}a(Mt,"compilablePlansOf");function eo(e,t,n){let r=Us(e,t),o=[];for(let a of Mt(e,t))a.attributeName!==n&&a.dependencies.some(s=>Im(s,n))&&o.push(a.attributeName);for(let a of e.objects)if(a.id!==t)for(let s of Mt(e,a.id))s.dependencies.some(u=>{if(u.kind!=="relation"||u.targetAttributeName!==n)return false;let l=e.attributes.find(m=>m.objectId===a.id&&m.name===u.relationName&&m.attributeType==="relation");return l!==void 0&&ht(l)===r.name})&&o.push(`${a.name}.${s.attributeName}`);return o}a(eo,"dependentsOf");function Te(e){let t=e.config?.bilateral;if(typeof t!="object"||t===null)return;let{object:n,attribute:r}=t;return typeof n=="string"&&typeof r=="string"?{object:n,attribute:r}:void 0}a(Te,"bilateralDeclarationOf");function Rm(e,t){return t!==void 0&&e.attributeType===t.attributeType&&Cm(e,t)}a(Rm,"sameAttribute");function Cm(e,t){return JSON.stringify(e.config??{})===JSON.stringify(t.config??{})}a(Cm,"sameConfig");function vm(e,t){let n=a(r=>Rm(r,e.attributes.find(o=>o.id===r.id)),"untouched");for(let r of t.attributes){if(r.attributeType!=="relation")continue;let o=Te(r);if(o===void 0||n(r))continue;let s=t.objects.find(g=>g.id===r.objectId)?.name??r.objectId,c=t.objects.find(g=>g.name===o.object),u=t.attributes.find(g=>g.objectId===c?.id&&g.name===o.attribute),l=`relation "${s}.${r.name}" declares inverse "${o.object}.${o.attribute}"`;if(u===void 0)throw new h$1(`${l}, which object "${o.object}" does not have; draft it first`,[]);if(u.attributeType!=="relation")throw new h$1(`${l}, which is not a relation`,[]);let m=Te(u);if(!(X(u).some(g=>g.object===s)&&(n(u)?m===void 0||m.object===s&&m.attribute===r.name:m?.object===s&&m.attribute===r.name)))throw new h$1(`${l}, which does not point back to "${s}.${r.name}"`,[])}}a(vm,"assertBilateralPairs");var Nm=0x100000001b3n,Em=0xffffffffffffffffn;function Ws(e,t){let n=t;for(let r of new TextEncoder().encode(e))n^=BigInt(r),n=n*Nm&Em;return n}a(Ws,"fnv1a64");function to(e,t){return En(t,e.toLowerCase())}a(to,"viewIdFor");function En(e,t){let n=`${t}:${e}`,r=Ws(n,0xcbf29ce484222325n).toString(16).padStart(16,"0"),o=Ws(`${e}:${n}`,0x84222325cbf29ce4n).toString(16).padStart(16,"0"),a=r+o,s=(Number.parseInt(a[16],16)&3|8).toString(16);return [a.slice(0,8),a.slice(8,12),`8${a.slice(13,16)}`,`${s}${a.slice(17,20)}`,a.slice(20,32)].join("-")}a(En,"draftEntityIdFor");function Je(e){return {list:to(e,"list"),detail:to(e,"detail")}}a(Je,"defaultViewIdsFor");function no(e,t,n,r){let a=r.filter(c=>c.objectId===n.id).filter(c=>j$1(Z(c)).presentation.formField).map(c=>({attribute:c.name})),s=e==="collection"?[{name:"all",type:"collection",placement:"main",label:"All",layout:"table",source:{object:n.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:t,object:n.name,name:e==="collection"?"default_list":"default_detail",label:n.label,context:e,default:true,contents:s,authoring:Et(s),revision:1,contentIds:Object.fromEntries(s.map(c=>[c.name,JSON.stringify(["draft-content",t,c.name])])),contentRevisions:Object.fromEntries(s.map(c=>[c.name,1])),derived:true}}a(no,"derivedView");function ro(e,t){let n=Je(e.id);return [no("collection",n.list,e,t),no("record",n.detail,e,t)]}a(ro,"defaultViewsFor");function Ft(e,t,n){return no(e.context,e.id,t,n)}a(Ft,"regenerateDerived");function io(e){return e.attributeType==="relation"&&Z(e).metadata?.relationGenerated===true}a(io,"isGeneratedDraftRelation");function Gs(e,t){let n=Te(t);if(!n)return [t];let r=e.objects.find(c=>c.id===t.objectId),o=e.objects.find(c=>c.name===n.object),a=e.attributes.find(c=>c.objectId===o?.id&&c.name===n.attribute);if(!a||a===t)return [t];let s=Te(a);return s&&s.object===r?.name&&s.attribute===t.name?[t,a]:[t]}a(Gs,"pairedDraftAttributes");function oo(e,t,n,r,o=false){let a$1=Z(t),s=r&&Z(r),c=r&&Te(r),u=Te(t);if(c&&(c.object!==u?.object||c.attribute!==u?.attribute))throw new h$1("Changing a bilateral address requires removing the existing pair first",[]);if(a$1.type!=="relation"||!a$1.bilateral)return e;let l=e.objects.find(j=>j.id===t.objectId),m=e.objects.find(j=>j.name===a$1.bilateral?.object);if(!(l&&m))throw new h$1("Both objects must exist before materializing a relation pair",[]);let d=`${l.name}.${t.name}`,b=a$1.bilateral.attribute,g=`${m.name}.${b}`,y=e.attributes.find(j=>j.objectId===m.id&&j.name===b),A=s?.metadata?.relationPairId,h=typeof A=="string"?A:En("relation-pair",`${n}:${t.id}`),k=[d,g].sort(),_=typeof A=="string"?{id:h,addresses:k,ownerAddress:s?.type==="relation"&&s.bilateral?.storageOwner===false?g:d,generatedAddresses:[],...d===g?{symmetric:true}:{}}:void 0,O=[...new Map([l,m].map(j=>[j.id,j])).values()].map(j=>({name:j.name,attributes:[t,...y&&y.id!==t.id?[y]:[]].filter(M=>M.objectId===j.id).map(Z)})),B=qi({objects:O,existingPairs:_?[_]:[],...r&&!o?{explicitAddresses:[d],propertyEditAddresses:[d]}:{},nextPairId:a(()=>h,"nextPairId")}),Se=new Map;for(let j of B.objects){let M=j.name===l.name?l.id:m.id;for(let oe of j.attributes){let ee=e.attributes.find(qt=>qt.objectId===M&&qt.name===oe.name),Ie=ee?.id===t.id?r??ee:ee,fc={...Dm(oe,ee&&Z(ee)),metadata:{...oe.metadata,...Ie&&io(Ie)&&!(o&&ee?.id===t.id)||!ee?{relationGenerated:true}:{}},id:ee?.id??En("relation-attribute",`${h}:${M}:${oe.name}`),...ee?{}:{order:e.attributes.filter(qt=>qt.objectId===M).length}};Se.set(`${M}.${oe.name}`,Ki(fc,M));}}let K=e.attributes.map(j=>{let M=`${j.objectId}.${j.name}`,oe=Se.get(M);return Se.delete(M),oe??j});return K.push(...Se.values()),{...e,attributes:K,views:e.views.map(j=>{let M=[l,m].find(oe=>oe.name===j.object);return j.derived&&M?Ft(j,M,K):j})}}a(oo,"reconcileDraftRelationAttribute");function Dm(e,t){if(e.type!=="relation"||!e.bilateral||t?.type!=="relation"||!t.bilateral)return e;let{label:n,cardinality:r,...o}=e.bilateral;return {...e,bilateral:{...o,...t.bilateral.label===void 0?{}:{label:n},...t.bilateral.cardinality===void 0?{}:{cardinality:r}}}}a(Dm,"preserveDeclarationHints");function Fe(e,t){let n=e.objects.find(r=>r.id===t);if(!n)throw new h$1(`Object "${t}" is not in the draftable state`,[]);return n}a(Fe,"requireObject");function ao(e,t,n){return {...e,attributes:[...n],views:e.views.map(r=>r.derived&&r.object===t.name?Ft(r,t,n):r)}}a(ao,"withDerivedViews");function Dn(e){return {objectId:e.objectId}}a(Dn,"objectFocus");function On(e){return {objectId:e.objectId,recordId:e.recordId}}a(On,"recordFocus");function Ks(e){return {objectId:e.objectId,attributeName:e.name}}a(Ks,"attributeFocus");function jn(e){return {objectId:e.objectId,attributeName:e.attribute}}a(jn,"existingAttributeFocus");function Om(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}a(Om,"firstChangedProperty");function jm(e,t){if(!e.derived)for(let n of e.contents){if(n.type==="collection"&&(n.columns?.includes(t)||n.displayAttributes?.includes(t)||n.sorts?.some(r=>r.attribute===t)))return `content "${n.name}"`;if(n.type==="form"&&n.groups.some(r=>r.fields.some(o=>o.attribute===t)))return `content "${n.name}"`;if(n.type==="richtext"&&(n.attribute===t||n.titleAttribute===t))return `content "${n.name}"`}}a(jm,"handShapedUse");function km(e,t,n){let r=n.config??{},o=n.name;if(r.relationPath!==void 0)throw new h$1(`rollup "${o}": relationPath is not supported yet`,[]);let a=r.relationAttribute;if(typeof a!="string"||a.length===0)throw new h$1(`rollup "${o}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let s=e.attributes.find(d=>d.objectId===t.id&&d.name===a&&d.attributeType==="relation");if(!s)throw new h$1(`rollup "${o}" needs a relation attribute; "${a}" is not a relation of object "${t.name}"`,[]);let c=ht(s);if(c===void 0){let d=X(s).filter(b=>b.object!=="*").length;throw new h$1(`rollup "${o}" needs a relation with one target object; "${a}" targets ${d}`,[])}if(r.function==="count")return;let u=e.objects.find(d=>d.name===c),l=r.targetAttribute;if(!(u!==void 0&&e.attributes.some(d=>d.objectId===u.id&&d.name===l)))throw new h$1(`rollup "${o}" targets attribute "${l}", which object "${c}" does not have`,[])}a(km,"assertRollupShape");function _m(e,t){let n=e.config??{};if(e.attributeType==="rollup")return n.relationAttribute===t;let r=typeof n.expression=="string"?n.expression:"";return new RegExp(`(^|[^A-Za-z0-9_])${t}\\.`).test(r)}a(_m,"traversesRelation");function Js(e,t){let n=Fe(e,t.objectId);if(t.attributeType==="relation"){for(let o of X(t))if(o.object!==ae&&!e.objects.some(a=>a.name===o.object))throw new h$1(`object "${o.object}" is unknown; create it first`,[]);let r=Te(t)?.object;if(r!==void 0&&r!==ae&&!e.objects.some(o=>o.name===r))throw new h$1(`object "${r}" is unknown; create it first`,[]);for(let o of e.attributes)o.objectId!==t.objectId||!yt(o)||_m(o,t.name)&&Nn(e,o);}else if(yt(t))t.attributeType==="rollup"&&km(e,n,t),Nn(e,t);else return;Xi(Mt(e,t.objectId));}a(Js,"assertConfigFolds");var Qe={..._t,objectId:z.string().uuid().describe("The object this operation acts on")},Pm=z.object({...Qe,objectId:z.string().uuid().describe("Stable id for the new object; the server mints one when omitted"),type:z.literal("add_object"),name:i.describe("kebab-case plural API name (`purchase-orders`)"),label:z.string().min(1).describe("Label people see"),icon:z.string().min(1).optional().describe("Icon name")}),Mm={type:"add_object",summary:"Creates an object: kebab-case plural name, icon from search_icons; folds in default_list/default_detail; reserved names are native objects.",schema:Pm,apply:a((e,t)=>{if(e.objects.some(r=>r.name===t.name))throw new h$1(`Object "${t.name}" already exists`,[]);if(e.objects.some(r=>r.id===t.objectId))throw new h$1(`Object id "${t.objectId}" is already taken`,[]);let n={id:t.objectId,name:t.name,label:t.label,...t.icon===void 0?{}:{icon:t.icon}};return {...e,objects:[...e.objects,n],views:[...e.views,...ro(n,e.attributes)]}},"apply"),focus:Dn,presentation:V(Dn,"structural"),describe:a(e=>`Cr\xE9e l'objet \xAB ${e.label} \xBB`,"describe")},Fm=z.object({...Qe,type:z.literal("update_object"),changes:z.object({label:z.string().min(1).optional().describe("New label"),icon:z.string().min(1).optional().describe("New icon name from search_icons")}).refine(e=>Object.keys(e).length>0,"update_object needs at least one change").describe("\u22651 change")}),Ys=a(e=>({objectId:e.objectId}),"updateObjectFocus"),Vm={type:"update_object",summary:"Updates an object's label and/or icon \u2014 no other field.",schema:Fm,apply:a((e,t)=>(Fe(e,t.objectId),{...e,objects:e.objects.map(n=>n.id===t.objectId?{...n,...t.changes}:n)}),"apply"),focus:Ys,presentation:V(Ys,"atomic",Om),describe:a(e=>e.changes.label?`Renomme l'objet en \xAB ${e.changes.label} \xBB`:"Modifie l'objet","describe")},Bm=z.object({...Qe,type:z.literal("remove_object")}),Lm={type:"remove_object",summary:"Removes an object; refused while a relation attribute targets it \u2014 remove it first.",schema:Bm,apply:a((e,t)=>{Fe(e,t.objectId);let n=e.objects.find(r=>r.id===t.objectId)?.name;for(let r of e.attributes){if(r.objectId===t.objectId||r.attributeType!=="relation"||!X(r).some(a=>a.object===n))continue;let o=e.objects.find(a=>a.id===r.objectId);throw new h$1(`object "${n}" is targeted by attribute "${o?.name}.${r.name}"; remove that attribute first`,[])}return {...e,objects:e.objects.filter(r=>r.id!==t.objectId),attributes:e.attributes.filter(r=>r.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(r=>r.objectId!==t.objectId),views:e.views.filter(r=>r.object!==n)}},"apply"),focus:Dn,presentation:V(Dn,"structural"),describe:a(e=>`Supprime l'objet ${e.objectId}`,"describe")},so=Qt;function Qs(e,t){try{L$1(e,t);}catch(n){throw n instanceof h$1?new h$1(n.message,n.errors.map(r=>({...r,path:["config",...r.path??[]]}))):n}}a(Qs,"assertConfigParses");var $m=z.object({...Qe,type:z.literal("add_attribute"),attributeId:z.string().min(1),name:m,label:z.string().min(1),attributeType:z.enum(so),config:z.record(z.string(),z.unknown()).optional()}).superRefine((e,t)=>{try{Qs(e.attributeType,e.config??{});}catch(n){if(n instanceof h$1){for(let r of n.errors)t.addIssue({code:"custom",message:r.message,path:[...r.path]});return}throw n}}),Hs={..._t,type:z.literal("add_attribute"),attributeId:z.string().min(1).describe("Stable attribute id"),name:m.describe("API name, camelCase or snake_case, no hyphen; the title attribute is `title`"),label:z.string().min(1).describe("Label people see")},co=Object.fromEntries(w.map(e=>[e,true])),kn=["text","richtext","number","checkbox","date","phone","currency","location","user"],Um=z.object(kn.reduce((e,t)=>(Object.assign(e,K$1(t).omit(co).shape),e),{})).strict(),qm=so.filter(e=>!kn.includes(e)),zm=Object.fromEntries(kn.map(e=>[e,new Set(Object.keys(K$1(e).omit(co).shape))])),Wm=x(zm,"config key");function Gm(e,t){Wm(e.attributeType,e.config,t,["config"]);}a(Gm,"refuseForeignSimpleConfigKeys");function Km(e){let t=K$1(e).omit(co);return (e==="relation"||e==="document"?t.extend({properties:G$1.optional()}):t).strict()}a(Km,"wireConfigFor");var Ym=z.discriminatedUnion("attributeType",[z.object({...Hs,objectId:z.string().uuid(),attributeType:z.enum(kn).describe("Attribute type"),config:Um.optional().describe("Configuration of a simple attribute (text, number, date\u2026)")}).strict().superRefine(Gm),...qm.map(e=>z.object({...Hs,objectId:z.string().uuid(),attributeType:z.literal(e).describe("Attribute type"),config:Km(e).optional().describe(`Configuration of a ${e} attribute`)}).strict())]),Hm={type:"add_attribute",summary:"Adds an attribute; relation/bilateral/rollup targets must pre-exist; no relationPath; formula needs returnType; cover new required attrs.",schema:$m,wire:Ym,apply:a((e,t)=>{let n=Fe(e,t.objectId),r=e.attributes.find(c=>c.objectId===t.objectId&&c.name===t.name);if(r&&!io(r))throw new h$1(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let o={id:r?.id??t.attributeId,objectId:t.objectId,name:t.name,label:t.label,attributeType:t.attributeType,...t.config===void 0?{}:{config:t.config}};for(let c of e.sampleRecords)c.objectId===t.objectId&&ec(c.id,o,c.values);let a=r?e.attributes.map(c=>c===r?o:c):[...e.attributes,o],s=ao(e,n,a);return Js(s,o),oo(s,o,t.id,r,true)},"apply"),focus:Ks,presentation:V(Ks,"local"),describe:a(e=>`Ajoute l'attribut \xAB ${e.label} \xBB`,"describe")},Zs={...Qe,attribute:m.describe("The attribute's API name on this object")};function Xs(e,t,n,r){let o=Fe(e,t);if(n===void 0)throw new h$1(`${r} now addresses the attribute by name; remove this operation and append it again with "attribute"`,[]);let a=e.attributes.find(s=>s.objectId===t&&s.name===n);if(!a)throw new h$1(`Attribute "${n}" is not on object "${t}"`,[]);return {object:o,attribute:a}}a(Xs,"requireAttribute");var Jm=z.object({...Zs,type:z.literal("update_attribute"),changes:z.object({label:z.string().min(1).optional().describe("New label"),config:z.record(z.string(),z.unknown()).optional().describe("Whole config, replaced \u2014 same shape as add_attribute")}).refine(e=>Object.keys(e).length>0,"update_attribute needs at least one change").describe("\u22651 change")}),Qm={type:"update_attribute",summary:"Updates an attribute's label, or replaces its whole config; a published config can't change \u2014 add a new attribute and migrate values.",schema:Jm,apply:a((e,t)=>{let{object:n,attribute:r}=Xs(e,t.objectId,t.attribute,"update_attribute");t.changes.config!==void 0&&Qs(r.attributeType,t.changes.config);let o={...r,...t.changes},a=e.attributes.map(c=>c===r?o:c),s=ao(e,n,a);return Js(s,o),oo(s,o,t.id,r)},"apply"),focus:jn,presentation:V(jn,"atomic"),describe:a(e=>e.changes.label?`Renomme l'attribut \xAB ${e.attribute} \xBB en \xAB ${e.changes.label} \xBB`:`Modifie l'attribut \xAB ${e.attribute} \xBB`,"describe")},Zm=z.object({...Zs,type:z.literal("remove_attribute")}),Xm={type:"remove_attribute",summary:"Removes an attribute; refused while a sample carries its value, a content names it, or a formula/rollup depends on it \u2014 remove those first.",schema:Zm,apply:a((e,t)=>{let{attribute:n}=Xs(e,t.objectId,t.attribute,"remove_attribute"),r=Gs(e,n);for(let s of r){let c=Fe(e,s.objectId),[u]=eo(e,s.objectId,s.name);if(u!==void 0)throw new h$1(`attribute "${s.name}" is used by "${u}"; remove that first`,[]);for(let m of e.views){if(m.object!==c.name)continue;let d=jm(m,s.name);if(d!==void 0)throw new h$1(`attribute "${s.name}" is used by view "${m.id}" (${d}); remove it from the view first`,[])}let l=e.sampleRecords.find(m=>m.objectId===s.objectId&&s.name in m.values);if(l)throw new h$1(`Attribute "${s.name}" is still used by sample record "${l.id}"`,[])}let o=e.attributes.filter(s=>!r.includes(s)),a={...e,views:e.views.map(s=>s)};return r.reduce((s,c)=>ao(s,Fe(e,c.objectId),o),a)},"apply"),focus:jn,presentation:V(jn,"local"),describe:a(e=>`Supprime l'attribut \xAB ${e.attribute} \xBB`,"describe")};function ef(e,t,n,r){let o=Z(n);try{c$1(o);}catch{return}let a=g$1(o,r);if(a.success)return;let s=a.errors??[],c=s.map(u=>u.path.length>1?`${u.path.join(".")}: ${u.message}`:u.message).join(", ");throw new h$1(`Sample record "${e}" has an invalid value for "${t}": ${c}`,s.map(u=>({path:u.path,message:u.message})))}a(ef,"assertSampleValue");function ec(e,t,n){if(t.config?.required===true&&t.config?.defaultValue===void 0&&!(t.name in n&&n[t.name]!==void 0))throw new h$1(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}a(ec,"assertRequiredCovered");function uo(e){return (Array.isArray(e)?e:[e]).flatMap(n=>{if(typeof n=="string")return [n];if(typeof n=="object"&&n!==null){let r=n.id;if(typeof r=="string")return [r]}return []})}a(uo,"relationValueIds");function tf(e,t,n,r){n.attributeType!=="relation"||r===void 0||r===null||nf(e,t,ht(n),r);}a(tf,"assertUnknownSampleReference");function nf(e,t,n,r){let o=e.objects.find(s=>s.name===n);if(!o)return;let a=e.views.some(s=>s.id===Je(o.id).list);for(let s of uo(r)){let c=e.sampleRecords.find(l=>l.id===s);if(c?.objectId!==o.id&&(c!==void 0||a))throw new h$1(`sample record "${t}" references unknown sample "${s}"`,[])}}a(nf,"assertSampleTarget");var rf=z.object({...Qe,type:z.literal("add_sample_record"),recordId:z.string().uuid().describe("Minted by the server when omitted"),values:z.record(z.string(),z.unknown()).describe("Attribute name \u2192 value; currency is `{code,value}`, relation is a record id or name minted here"),publication:z.enum(["preview","requested-data"]).optional().describe("preview = display-only; requested-data = real records asked for")}),of={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:rf,apply:a((e,t)=>{if(Fe(e,t.objectId),e.sampleRecords.some(r=>r.id===t.recordId))throw new h$1(`Sample record "${t.recordId}" already exists`,[]);let n=new Map(e.attributes.filter(r=>r.objectId===t.objectId).map(r=>[r.name,r]));for(let[r,o]of Object.entries(t.values)){let a=n.get(r);if(!a)throw new h$1(`Sample record "${t.recordId}" uses unknown attribute "${r}"`,[]);if(yt(a))throw new h$1(`attribute "${a.name}" is computed and cannot be set on a sample record`,[]);tf(e,t.recordId,a,o),ef(t.recordId,r,a,o);}for(let r of n.values())ec(t.recordId,r,t.values);return {...e,sampleRecords:[...e.sampleRecords,{id:t.recordId,objectId:t.objectId,values:t.values,...t.publication===void 0?{}:{publication:t.publication}}]}},"apply"),focus:On,presentation:V(On,"local"),describe:a(()=>"Ajoute un exemple","describe")};function af(e,t){return new Set([...e.attributes.filter(n=>n.objectId===t&&n.attributeType==="relation").map(n=>n.name)])}a(af,"relationNamesOf");function sf(e,t){for(let n of e.sampleRecords){if(n.id===t)continue;let r=af(e,n.objectId);for(let[o,a]of Object.entries(n.values))if(r.has(o)&&uo(a).includes(t))throw new h$1(`sample record "${t}" is referenced by sample record "${n.id}"; remove that first`,[])}}a(sf,"assertSampleNotReferenced");var cf=z.object({...Qe,type:z.literal("remove_sample_record"),recordId:z.string().min(1).describe("recordId of the sample to remove")}),uf={type:"remove_sample_record",summary:"Removes a sample record; refused while another sample still references it.",schema:cf,apply:a((e,t)=>{if(!e.sampleRecords.some(n=>n.id===t.recordId&&n.objectId===t.objectId))throw new h$1(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,[]);return sf(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(n=>n.id!==t.recordId)}},"apply"),focus:On,presentation:V(On,"local"),describe:a(()=>"Retire un exemple","describe")},Ze=[Mm,Vm,Lm,Hm,Qm,Xm,of,uf];function lf(){let e=new Map;for(let t of [...Ze,...He]){if(e.has(t.type))throw new r("architect operation",t.type);e.set(t.type,t);}return e}a(lf,"build");var Vt=lf(),df=[...Vt.keys()];function Bt(e){let t=Vt.get(e.type);if(!t)throw new h$1(`Operation "${e.id}" has unknown type "${e.type}"`,[]);return t}a(Bt,"defOf");function lo(e,t,n={extensions:[]}){return t.reduce((r,o)=>Bt(o).apply(r,o,n),e)}a(lo,"applyOperations");function po(e){return Bt(e).focus(e)}a(po,"focusOf");function pf(e,t){return e.map(n=>Bt(n).describe(n,t))}a(pf,"describeOperations");function mf(e){if(typeof e!="object"||e===null||!("type"in e))throw new h$1("An operation must be an object carrying a type",[]);let t=e.type;if(typeof t!="string")throw new h$1("An operation's type must be a string",[]);let n=Vt.get(t);if(!n)throw new h$1(`Unknown operation type "${t}"`,[]);let r=n.schema.safeParse(e);if(!r.success)throw new h$1(`Operation "${t}" is invalid: ${r.error.issues.map(o=>`${o.path.join(".")} ${o.message}`).join("; ")}`,[]);return r.data}a(mf,"parseOperation");var Lt=a(e=>z.tuple([z.literal(e),z.string()]),"pair"),ff=z.union([z.tuple([z.literal("content"),z.string(),z.string(),z.string()]),z.tuple([z.literal("view"),z.string(),z.string()]),z.tuple([z.literal("attribute"),z.string(),z.string()]),z.tuple([z.literal("sample"),z.string(),z.string()]),Lt("object"),Lt("object-name"),Lt("object-schema"),Lt("object-tree"),Lt("attribute-id")]);function $t(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}a($t,"proposalTargetKey");function tc(e,t,n,r){if(n&&typeof n=="object")if("source"in n&&n.source&&typeof n.source=="object"){let o=Kr(n.source);if(o&&o.kind!=="related"&&r(o.object),o?.kind==="related"){let a=o.relation;r(t);let s=e.objects.find(u=>u.name===t),c=e.attributes.find(u=>u.objectId===s?.id&&u.name===a);if(c?.attributeType==="relation"&&Array.isArray(c.config?.targets))for(let u of c.config.targets)u&&typeof u.object=="string"&&u.object!=="*"&&r(u.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);}a(tc,"addContentDependencies");function bf(e,t,n,r,o){if(["add_attribute","update_attribute","remove_attribute"].includes(t.type)){let a=e.attributes.find(c=>c.objectId===n.objectId&&c.name===n.attributeName),s=r&&typeof r=="object"&&"bilateral"in r?r.bilateral:a?.config?.bilateral;if((t.attributeType==="relation"||a?.attributeType==="relation")&&s&&typeof s=="object"&&"object"in s&&typeof s.object=="string"){n.objectId&&o("object-tree",n.objectId);let c=e.objects.find(u=>u.name===s.object);c?o("object-tree",c.id):o("object-name",s.object);}}}a(bf,"addBilateralDependencies");function gf(e,t){let n=new Set,r=a((...a)=>n.add(JSON.stringify(a)),"add"),o=a(a=>{let s=e.objects.find(c=>c.name===a);s?r("object-schema",s.id):r("object-name",a);},"schemaFor");for(let a of t){let s=po(a);if(a.type==="rename_view"||a.type==="rename_view_content"){let m=Qi.parse(a),d=$t({objectName:m.objectName,viewName:m.viewName,...m.type==="rename_view_content"?{contentName:m.contentName}:{}});d&&n.add(d);}let c=$t(s);if(c&&n.add(c),s.viewName&&s.objectName){a.type!=="replace_view_content"&&r("view",s.objectName,s.viewName);let m=e.objects.find(d=>d.name===s.objectName);if(m?r("object",m.id):r("object-name",s.objectName),tc(e,s.objectName,a.definition??a.content,o),a.type==="reset_view_content"&&typeof a.contentName=="string"){let d=e.views.find(b=>b.object===a.objectName&&b.name===a.viewName);tc(e,s.objectName,d?.authoring.contents[a.contentName]?.sourceDefinition,o);}}s.objectId&&r("object",s.objectId),s.objectId&&(a.type==="remove_object"||a.type.includes("sample_record"))&&r("object-tree",s.objectId),a.type==="add_object"&&typeof a.name=="string"&&r("object-name",a.name);let u=a.changes&&typeof a.changes=="object"?a.changes:null,l=a.type==="add_attribute"?a.config:u&&"config"in u?u.config:null;if(bf(e,a,s,l,r),l&&typeof l=="object"&&"targets"in l&&Array.isArray(l.targets))for(let m of l.targets)m&&typeof m.object=="string"&&m.object!=="*"&&r("object-name",m.object);}return [...n]}a(gf,"requiredTargetKeys");function yf(e,t){return Object.fromEntries(t.map(n=>[n,b$3(_n(e,n))]))}a(yf,"targetTokensFor");function _n(e,t){let n;try{n=JSON.parse(t);}catch{throw new h$1(`Invalid proposal target key "${t}"`,[])}let r=ff.safeParse(n);if(!r.success)throw new h$1(`Invalid proposal target key "${t}"`,[]);let[o,a,s,c]=r.data,u=e.objects.find(d=>d.id===a);if(o==="object")return u??null;if(o==="object-name")return e.objects.find(d=>d.name===a)??null;if(o==="attribute-id")return e.attributes.find(d=>d.id===a)??null;if(o==="attribute")return e.attributes.find(d=>d.objectId===a&&d.name===s)??null;if(o==="sample")return e.sampleRecords.find(d=>d.objectId===a&&d.id===s)??null;if(o==="object-schema"||o==="object-tree"){if(!u)return null;let d=e.attributes.filter(b=>b.objectId===a);return o==="object-schema"?{object:u,attributes:d.toSorted((b,g)=>b.name.localeCompare(g.name))}:{object:u,attributes:d,views:e.views.filter(b=>b.object===u.name),sampleRecords:e.sampleRecords.filter(b=>b.objectId===a)}}let l=e.views.find(d=>d.object===a&&d.name===s);if(!l)return null;if(o==="view")return {id:l.id,revision:l.revision,definition:{...bt(l),contents:l.contents.map(({name:d,placement:b})=>({name:d,placement:b}))}};let m=l.contents.find(d=>d.name===c);return c!==void 0&&Object.hasOwn(l.contentIds,c)?{id:l.contentIds[c],revision:l.contentRevisions[c],definition:m??null}:null}a(_n,"targetSnapshot");function Ut(e){return Bt(e).presentation(e)}a(Ut,"presentationOf");function hf(e){let t=e.map(Ut);return new Set(t.map(({focus:r})=>r.viewName?JSON.stringify([r.objectName,r.viewName]):r.objectId).filter(r=>r!==void 0)).size>1||t.some(({impact:r})=>r==="structural")?"structural":t.some(({impact:r})=>r==="local")?"local":"atomic"}a(hf,"episodeImpactOf");function nc(e,t){let n=$t(t);return n===null?null:_n(e,n)}a(nc,"snapshotArchitectTarget");function Af(e,t,n={extensions:[]}){let r=e;return t.map(o=>{let a=Ut(o),s=nc(r,a.focus);r=lo(r,[o],n);let c=nc(r,a.focus);return {operationId:o.id,operationType:o.type,presentation:a,before:s,after:c,...o.note===void 0?{}:{note:o.note}}})}a(Af,"deriveArchitectChanges");function Ve(e){return e.replace(/[%:/.]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}a(Ve,"part");function xf(e){let t=Tf(e);if(t===null)return null;let n=e.propertyPath??[];return n.length===0?t:`${t}/${n.map(Ve).join(".")}`}a(xf,"architectFocusKey");function Tf(e){return e.viewName&&e.objectName?e.contentName?["content",e.objectName,e.viewName,e.contentName].map(Ve).join(":"):["view",e.objectName,e.viewName].map(Ve).join(":"):e.attributeName&&e.objectId?["attribute",e.objectId,e.attributeName].map(Ve).join(":"):e.attributeId?["attribute-id",e.attributeId].map(Ve).join(":"):e.recordId&&e.objectId?["sample",e.objectId,e.recordId].map(Ve).join(":"):e.objectId?["object",e.objectId].map(Ve).join(":"):e.objectName?["object-name",e.objectName].map(Ve).join(":"):null}a(Tf,"headOf");var me=z.string().min(1),rc=z.union([z.object({objectName:me,viewName:me,contentName:me.optional()}).strict().describe("Full configuration of a view, or of one content when contentName is given"),z.object({objectId:me}).strict().describe("An object with its attributes, by id"),z.object({objectName:me}).strict().describe("An object with its attributes"),z.object({objectId:me,attributeName:me}).strict().describe("One attribute's config, by name"),z.object({objectId:me,attributeId:me}).strict().describe("One attribute's config, by id"),z.object({objectId:me,recordId:me}).strict().describe("One sample record")]);function wf(e){let t=rc.safeParse(e);if(!t.success)throw new h$1("Invalid scoped target",[{path:["target"],message:"Expected exactly one named target branch"}]);return t.data}a(wf,"parseNamedTarget");var mo=z.object({type:z.literal("remove_operation"),operationId:z.string().min(1).describe("The id of a stored operation to drop from the draft")}),Sf=12;function oc(e,t=[]){return [...e.map(n=>n.schema),...t].map(ac)}a(oc,"membersOf");function If(e,t){return Mn(e,n=>n.describe(t))}a(If,"describeMember");function ic(e,t=[]){return [...e.map(o=>o.wire??o.schema),...t].map(ac).map(Nf).map(Df).map((o,a)=>{let s=e[a];return s===void 0?o:If(o,s.summary)})}a(ic,"wireMembersOf");function Pn(e){return z.discriminatedUnion("type",e)}a(Pn,"unionOf");function Rf(e){return e instanceof z.ZodString&&e.format==="uuid"}a(Rf,"isUuidString");function Cf(e){let t=e;return !Array.isArray(t.options)||typeof t.def?.discriminator!="string"?null:{discriminator:t.def.discriminator,options:t.options}}a(Cf,"asUnionMember");function Mn(e,t){let n=Cf(e);return n===null?t(e):z.discriminatedUnion(n.discriminator,n.options.map(t))}a(Mn,"mapMember");function ac(e){return Mn(e,t=>{let n={};for(let[r,o]of Object.entries(t.shape)){if(!Rf(o))continue;let a=z.string().min(1);n[r]=o.description===void 0?a:a.describe(o.description);}return Object.keys(n).length===0?t:t.safeExtend(n)})}a(ac,"relaxUuidKeys");var vf={add_object:["objectId"],add_sample_record:["recordId"]};function Nf(e){return Mn(e,t=>{let n={};for(let r of vf[t.shape.type.value]??[]){let o=t.shape[r];o instanceof z.ZodString&&(n[r]=o.optional());}return Object.keys(n).length===0?t:t.safeExtend(n)})}a(Nf,"relaxMintedKeys");function Ef(e,t){let n=e._zod.def.checks;return !n||n.length===0?t:t.check(...n)}a(Ef,"withOriginalChecks");function Df(e){return Mn(e,t=>{if(t.shape.type.value==="add_object"||!("objectId"in t.shape))return t;let{objectId:n,...r}=t.shape,o=z.object({...r,objectName:z.string().min(1).describe("Object")}).strict();return Ef(t,o)})}a(Df,"addressByName");var Of=oc(Ze,[mo]),jf=oc(He),sc=Pn(Of),cc=Pn(jf),kf={schema:sc,view:cc},_f={schema:Pn(ic(Ze,[mo])),view:Pn(ic(He))},Pf=new Map([...Ze.map(e=>[e.type,"schema"]),["remove_operation","schema"],...He.map(e=>[e.type,"view"])]);function Mf(e){return Pf.get(e)??null}a(Mf,"familyOf");function Fn(e,t,n){return e.views.filter(r=>r.object===t.name&&r.context===n)}a(Fn,"viewsOf");function lc(e,t){return Fn(e,t,"collection").flatMap(n=>n.contents).filter(n=>n.type==="collection")}a(lc,"collectionContentsOf");function dc(e,t){return e.attributes.filter(n=>n.objectId===t.id)}a(dc,"ownAttributes");function Ff(e){return j$1(Z(e)).presentation.tableCell}a(Ff,"isTableCell");function uc(e,t,n){return Fn(e,t,"record").some(r=>r.contents.some(o=>o.type===n))}a(uc,"hasRecordContent");function pc(e,t){return e===2&&t<=5}a(pc,"isEdgePayload");function Vf(e,t){let n=dc(e,t),r=n.filter(o=>o.attributeType==="relation");return pc(r.length,n.length)?!e.attributes.some(o=>o.attributeType==="relation"&&o.objectId!==t.id&&X(o).some(a=>a.object===t.name)):false}a(Vf,"looksLikeEdge");function Bf(e,t,n){return Fn(e,n,"record").some(r=>r.contents.some(o=>o.type==="collection"&&o.source.relation===t.name))}a(Bf,"reciprocalExists");function Lf(e,t){let n=[],r=t?e.objects.filter(o=>t.has(o.id)):e.objects;for(let o of r){if(Vf(e,o)){n.push(`Object "${o.label}" is an edge (two relations plus scalars): qualify a relation with config.properties.definitions instead of an object.`);continue}let a=lc(e,o);a.length===0&&n.push(`Object "${o.label}" has no collection content: add_view_content.`);for(let s of dc(e,o))if(Ff(s)&&a.length&&!a.some(c=>c.columns===void 0||c.columns.includes(s.name))&&n.push(`Attribute "${s.label}" on "${o.label}" is in no collection column set: replace_view_content.`),s.attributeType==="document"&&!uc(e,o,"documents")&&n.push(`Object "${o.label}" has no documents content: add_view_content.`),s.attributeType==="relation")for(let{object:c}of X(s)){let u=e.objects.find(l=>l.name===c);u&&!Bf(e,s,u)&&n.push(`Relation "${s.label}" on "${o.label}" has no reciprocal collection on "${u.label}": add_view_content with source.relation.`);}Fn(e,o,"record").length&&!uc(e,o,"activity")&&n.push(`Object "${o.label}" has no activity content on its record view: add_view_content.`),a.length===1&&n.push(`Object "${o.label}" has a single collection content; a person would add one to three that answer a question: add_view_content.`);}return n}a(Lf,"stillMissing");function $f(e,t){let n=new Set(t.flatMap(r=>r.type==="add_attribute"&&typeof r.attributeId=="string"?[r.attributeId]:[]));return e.attributes.filter(r=>n.has(r.id))}a($f,"addedAttributes");function Uf(e,t){let n={next:[],needsColumns:[],regenerated:[]},r=new Set;for(let o of $f(e,t)){let a=e.objects.find(l=>l.id===o.objectId);if(!a)continue;let s=e.views.filter(l=>l.object===a.name);if(!r.has(a.id)){r.add(a.id);for(let l of s.filter(m=>m.derived))for(let m of l.contents)n.regenerated.push(`${l.name}.${m.name}`);}for(let l of s.filter(m=>!m.derived&&m.context==="collection"))for(let m of l.contents)m.type==="collection"&&m.columns!==void 0&&!m.columns.includes(o.name)&&n.needsColumns.push({view:l.name,content:m.name,attribute:o.name});let c=s.some(l=>l.context==="record"&&l.contents.some(m=>m.type==="documents")),u=s.find(l=>l.context==="record");o.attributeType==="document"&&u&&!c&&n.next.push({type:"add_view_content",objectName:a.name,viewName:u.name,content:{name:"documents",type:"documents",placement:"main",label:"Documents"},target:{end:true}});}return n}a(Uf,"guidanceForBatch");function qf(e,t){let n=new Map(e.objects.map(o=>[o.name,o.id])),r=new Set;for(let o of t){let{focus:a}=Ut(o),s=a.objectId??(a.objectName?n.get(a.objectName):void 0);s!==void 0&&r.add(s);}return r}a(qf,"touchedObjectIds");function zf(e){let t=e.config??{};if(e.attributeType==="relation")return `\u2192 ${X(e).map(n=>n.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})`}a(zf,"attributeDetail");function Wf(e){let t=Xt({properties:e.config?.properties});if(t.length!==0)return t.map(n=>`${n.name}: ${n.type}`)}a(Wf,"propertyLines");function Gf(e){let t=e.config?.options,n=zf(e),r=Wf(e);return {name:e.name,label:e.label,type:e.attributeType,...Array.isArray(t)?{options:t.map(o=>o.value)}:{},...n===void 0?{}:{detail:n},...r===void 0?{}:{properties:r}}}a(Gf,"summarizeAttribute");function Kf(e,t,n){let r=Je(e.id),o=n.some(a=>a.id===r.list);return {id:e.id,name:e.name,label:e.label,attributes:t.filter(a=>a.objectId===e.id).map(Gf),...o?{viewIds:r}:{}}}a(Kf,"summarizeObject");function Yf(e,t){if(!t.some(n=>n.name===e.object))throw new h$1(`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===true,contents:e.contents.map(({name:n,type:r,placement:o,label:a})=>({name:n,type:r,placement:o,label:a}))}}a(Yf,"summarizeView");function Hf(e,t){let n=new Map;for(let r of e.sampleRecords)n.set(r.objectId,(n.get(r.objectId)??0)+1);return {objects:e.objects.map(r=>Kf(r,e.attributes,e.views)),views:e.views.map(r=>Yf(r,e.objects)),sampleRecords:[...n.entries()].map(([r,o])=>({objectId:r,count:o})),operationCount:t}}a(Hf,"summarizeDraft");var Jf=["draft_schema"],Qf="publish_architect_draft",Zf="discard_architect_draft",Xf="request_design_review",eb="get_architect_draft";var tb=[{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\xE9",color:"blue"},{value:"accepted",label:"Accept\xE9",color:"green"}]}}],guard:{revision:null,targetTokens:{}}}},{input:{operations:[{type:"add_view_content",id:"op-open",objectName:"devis",viewName:"default_list",content:{name:"open",label:"\xC0 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:true}}],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:{}}}}];var re=z.string().refine(e=>e.trim().length>0,"Must not be blank"),mc=z.union([z.tuple([z.literal("object"),re]),z.tuple([z.literal("attribute"),re,re]),z.tuple([z.literal("view"),re,re]),z.tuple([z.literal("content"),re,re,re])]),nb=z.object({label:re,pluralLabel:z.string().optional(),description:z.string().optional(),icon:t.optional(),labelExpression:z.string(),embeddingExpression:z.string().optional(),sealed:z.boolean().optional(),toleratedAttributes:z.array(re).optional(),metadata:z.record(z.string(),z.unknown()).optional(),schema_version:z.number().int().nonnegative(),migrations:z.array(z.record(z.string(),z.unknown())),documentLayout:z.record(z.string(),z.unknown()).optional()}).strict();function Xe(e){throw new h$1(e,[])}a(Xe,"failure");function rb(e){return z.custom(t$1=>{let n=z.record(z.string(),z.unknown()).parse(t$1);for(let r of e[0]==="view"?["object","name"]:["name"])Object.hasOwn(n,r)&&Xe(`Invalid schema state: unrecognized definition key ${r}`);switch(e[0]){case "object":nb.parse(n);break;case "attribute":{let r=z.enum(Qt).parse(n.type);I$1(r).extend({type:z.literal(r),label:re,required:z.boolean().optional(),unique:z.boolean().optional(),icon:t.optional()}).strict().parse(n);break}case "view":{let{contents:r,...o}=n,a=z.array(re).parse(r);new Set(a).size!==a.length&&Xe("Invalid schema state: duplicate content membership"),Z$1.parse({...o,object:e[1],name:e[2],contents:[]});break}case "content":W$1.parse({...n,name:e[3]});break}return true})}a(rb,"definitionSchema");function Vn(e,t){let n=JSON.stringify(e.address),r=JSON.stringify(t.address);return n<r?-1:n>r?1:0}a(Vn,"compareSchemaStateEntries");function ib(e){return {modelVersion:1,hashVersion:1,entries:[...e].sort(Vn).filter(t=>t.source!==null).map(({address:t,source:n})=>({address:t,source:n}))}}a(ib,"schemaStateSourcePayload");function ob(e){let t=z.record(z.string(),z.unknown()).parse(e);for(let[a,s]of [["modelVersion","model"],["hashVersion","hash"]])t[a]!==1&&Xe(`Unsupported schema ${s} version: expected 1, received ${t[a]===void 0?"missing":String(t[a])}`);let n=z.object({modelVersion:z.literal(1),hashVersion:z.literal(1),tenant:re,sourceFingerprint:z.string().regex(/^[a-f0-9]{64}$/),entries:z.array(z.unknown())}).strict().safeParse(e);if(!n.success){let a=n.error.issues.find(s=>s.code==="unrecognized_keys");throw a?.code==="unrecognized_keys"&&Xe(`Invalid schema state: unrecognized key ${a.keys[0]}`),h$1.fromZodErrors(n.error.issues.map(s=>({path:s.path.map(String),message:s.message})))}let r=new Set,o=n.data.entries.map(a=>{let s=mc.parse(z.object({address:z.unknown()}).parse(a).address),c=JSON.stringify(s);r.has(c)&&Xe(`Invalid schema state: duplicate address ${c}`),r.add(c);let u=rb(s).nullable(),l=s[0]==="object"||s[0]==="attribute"?z.object({id:z.string().uuid(),updatedAt:z.string().datetime()}).strict():z.object({id:z.string().uuid(),revision:z.number().int().nonnegative()}).strict(),m=z.object({address:mc,source:u,effective:u,status:z.enum(["source","runtime","copy","suppressed"]),sourceOwner:z.union([z.literal("core"),z.string().regex(/^(bundle|source):.+$/)]).nullable(),guard:l.nullable()}).strict().parse(a);(m.status==="runtime"&&(m.source!==null||m.effective===null||m.sourceOwner!==null)||m.status==="suppressed"&&(s[0]!=="content"||m.source===null||m.effective!==null||m.guard===null)||m.status==="copy"&&(m.source===null||m.effective===null)||m.effective!==null&&m.guard===null||m.source===null&&m.effective===null)&&Xe(`Invalid schema state: inconsistent status at ${c}`);let d=m.sourceOwner;d!==null&&d!=="core"&&!d.startsWith("bundle:")&&!d.startsWith("source:")&&Xe("Invalid source owner");let b=d===null||d==="core"?d:d.startsWith("bundle:")?`bundle:${d.slice(7)}`:`source:${d.slice(7)}`;return {...m,sourceOwner:b}});return {...n.data,entries:o.sort(Vn)}}a(ob,"parseState");function ab(e){try{return ob(e)}catch(t){throw t instanceof z.ZodError?h$1.fromZodErrors(t.issues.map(n=>({path:n.path.map(String),message:n.message}))):t}}a(ab,"parseSchemaState");function sb(e){let t=[];for(let n of [...e.entries].sort(Vn)){let r=n.source===null?"added":n.status==="suppressed"?"suppressed":n.effective===null?"removed":b$3(n.source)!==b$3(n.effective)?"changed":n.status==="copy"?"copied":null;r&&t.push({...n,change:r});}return {modelVersion:1,tenant:e.tenant,sourceFingerprint:e.sourceFingerprint,changes:t}}a(sb,"diffSchemaState");export{lS as AGENT_UI_BATCH_MAX_BYTES,dS as AGENT_UI_BATCH_MAX_ITEMS,Zo as ALLOWED_PROPERTY_TYPES,Jn as ALL_ACTIONS,df as ALL_OPERATION_TYPES,tx as ALL_SYSTEM_RESOURCES,_y as ARTIFACT_FILE_ROLES,jy as ARTIFACT_KINDS,Nl as ARTIFACT_LIST_VIEW,Cl as ARTIFACT_OBJECT,ut as ARTIFACT_OBJECT_NAME,Aa as ARTIFACT_PREVIEW_EXTENSION,ky as ARTIFACT_RETENTIONS,vl as ARTIFACT_VIEW,Qt as ATTRIBUTE_TYPES,Jg as AUDIT_ACTIONS,Hg as AUDIT_RESOURCE_TYPES,er as AgentBuilder,Lg as BEHAVIOR_PROPERTIES,du as BYTE_UNIT_LABELS,Qc as CLAIMABLE_SESSION_STATUSES,jt as COMPUTED_FUNCTIONS,GS as COMPUTED_FUNCTION_METADATA,vS as COMPUTED_FUNCTION_NAMES,AI as CONNECTOR_CALLBACK_PARAM,Jo as COUNT_MODES,I as ComputedFormulaCompileError,ce as ContentBuilder,XA as DB_COLUMN_FIELDS,ca as DEFAULT_AGENT_EXECUTION_CONFIG,Lo as DEFAULT_APPROVAL_POLICY,Dy as DEFAULT_DICTATION_LIMITS,ta as DEFAULT_LABEL_FALLBACK,au as DEFAULT_MEETING_BOT_DISPLAY_NAME,$u as DEFAULT_ROLES,ix as DEFAULT_ROLE_DESCRIPTIONS,rx as DEFAULT_ROLE_LABELS,ox as DEFAULT_ROLE_PERMISSIONS,lh as DEFAULT_TENANT_SETTINGS,Ny as DICTATION_FINALIZATION_TIMEOUT_MS,wy as DICTATION_FRAME_BYTES,Iy as DICTATION_MAX_BUFFER_BYTES,Sy as DICTATION_MAX_FRAME_BYTES,Ry as DICTATION_MAX_TRANSCRIPT_BYTES,Ey as DICTATION_MODEL_ID,vy as DICTATION_PREPARATION_TIMEOUT_MS,Ty as DICTATION_SAMPLE_RATE,Cy as DICTATION_TICKET_TTL_MS,Zf as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,yA as DOCUMENT_SYSTEM_ATTRIBUTES,so as DRAFTABLE_ATTRIBUTE_TYPES,Sf as DRAFT_BATCH_LIMIT,tb as DRAFT_SCHEMA_INPUT_EXAMPLES,Jf as DRAFT_WRITE_TOOL_NAMES,Il as DRIVE_LIST_VIEW,wl as DRIVE_OBJECT,ct as DRIVE_OBJECT_NAME,Sl as DRIVE_VIEW,tn as EMPTY_VALUE_PLACEHOLDER,Ah as ESTIMATED_COUNT_CAP,jI as FAKE_MEETING_BOT_SIGNATURE_HEADER,kf as FAMILY_INPUTS,_f as FAMILY_WIRE_INPUTS,Kn as FORM_FORBIDDEN_ATTRIBUTE_TYPES,vt as FlagRegistry,dn as FlagService,Lr as FormBuilder,Dt as FormRegistry,Vr as FormRowBuilder,Br as FormStepBuilder,eb as GET_ARCHITECT_DRAFT_TOOL_NAME,Yr as GroupBuilder,Bg as IDENTITY_PROPERTIES,bh as IMAGE_FORMATS,qo as INFERENCE_REASONING_OPTIONS,Uo as INFERENCE_SPEEDS,Bl as LIVE_EVENT_TYPES,Np as MAILBOX_LIST_MODES,CI as MAIL_DRAFT_BODY_MAX_CHARS,vI as MAIL_SUBJECT_MAX_CHARS,Go as MAX_PRESET_DEPTH,dy as MAX_TODOS,my as MAX_TODO_DESCRIPTION_CHARS,py as MAX_TODO_ID_CHARS,C as MEETING_ATTRIBUTES,Sa as MEETING_DETAIL_VIEW_ID,Ol as MEETING_LIST_VIEW,Ta as MEETING_LIST_VIEW_ID,El as MEETING_OBJECT,lt as MEETING_OBJECT_NAME,Dl as MEETING_VIEW,wa as MEETING_WRITE_SOURCE,Tl as MEMORY_LIST_VIEW,Al as MEMORY_OBJECT,xl as MEMORY_VIEW,vp as McpOAuthCompletionMode,br as MultiRelationAttributeBuilder,eu as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,tu as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,Mo as NOTIFICATION_INBOX_STATES,ko as NOTIFICATION_KINDS,_o as NOTIFICATION_PRIORITIES,Po as NOTIFICATION_SENSITIVITIES,Fg as NOTIFICATION_TYPES_V1,Hc as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,Kc as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,Yc as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,Fo as NOTIFICATION_WORK_STATES,kI as NO_RECORDING,Ho as NoopGeocodingAdapter,Zc as OPEN_TOOL_PART_STATES,Vt as OPERATION_REGISTRY,In as OPERATOR_SPECS,It as ObjectBuilder,$g as PRESENTATION_PROPERTIES,$o as PROVIDER_NAMES,Qf as PUBLISH_ARCHITECT_DRAFT_TOOL_NAME,IA as QUALIFIED_SEPARATOR,wh as QUOTA_KEYS,DI as RECORDING_OVERRIDES,OI as RECORDING_POLICIES,aa as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,ae as RELATION_TARGET_ANY,mo as REMOVE_OPERATION_SCHEMA,Ep as REPLY_MODES,Xf as REQUEST_DESIGN_REVIEW_TOOL_NAME,Ze as SCHEMA_OPERATIONS,sc as SCHEMA_OPERATION_INPUT,de as SCHEMA_PLAN_LIMITS,Vi as SCHEMA_SOURCE_ID_PATTERN,yy as SESSION_STATE_STREAM_ID,Jc as SESSION_TERMINAL_STATUSES,ya as SKILL_CONTENT_TEMPLATE,gl as SKILL_LIST_VIEW,fl as SKILL_OBJECT,bl as SKILL_VIEW,qu as STANDARD_SCHEMA_VENDOR,Gn as SYSTEM_PART_CODES,te as SYSTEM_RESOURCES,nx as SYSTEM_RESOURCE_LABELS,fr as SingleRelationAttributeBuilder,ns as TODAY_DEFAULT,iy as TODO_PLAN_STATUSES,ly as TODO_STATUSES,zo as TOOL_APPROVAL_STATES,ph as USER_STATUSES,mh as USER_WORK_POSTURES,He as VIEW_OPERATIONS,cc as VIEW_OPERATION_INPUT,un as ViewBuilder,ih as accessLevelToActions,rh as actionsToAccessLevel,px as agent,TR as agentDataChunk,oy as agentDisplayName,hR as agentInferencePreferencesSchema,Jp as agentMessageAttachmentSchema,Hp as agentMessagePartSchema,Yp as agentSessionInferenceOverridesInputSchema,AR as agentSessionInferenceOverridesSchema,bs as agentSessionMessageSchema,rm as agentUIValidationError,lo as applyOperations,ea as applyPipes,ku as applyRelationProps,bS as architectDraftChannelKey,xf as architectFocusKey,Xi as assertAcyclicComputed,Ba as assertAcyclicComputedDependencies,vm as assertBilateralPairs,im as assertCustomAgentUIMessageChunk,jp as assertSchemaSourceId,Te as bilateralDeclarationOf,il as booleanFlag,is as buildAgentFallbackTitle,Lu as buildPermissionFlags,en as buildPropertySchema,CA as buildQualifiedAttribute,Qi as canonicalViewOperationSchema,ua as checkbox,sR as collectSchemaReferences,lc as collectionContentsOf,ze as collectionSourceAddress,Kr as collectionSourceAddressOf,Xc as compareAgentSessionMessages,Vn as compareSchemaStateEntries,Mt as compilablePlansOf,gn as compileComputedFormula,qa as compileRollupAttribute,lu as computeByteMagnitude,Zi as computedCompileSchemaOf,Nn as computedPlanOf,N as content,Ia as contentDefinition,Op as conversationDisplayTitle,ul as createFlagRegistry,dl as createFlagService,on as createStandardSchemaProps,Rx as currency,xs as customDataChunkSchemas,se as date,Rn as dateInTimezone,nt as dateValueStart,Je as defaultViewIdsFor,ro as defaultViewsFor,Gi as defineOperation,V as definePresentation,eo as dependentsOf,Af as deriveArchitectChanges,bI as deriveCreateDefaultsFromFilters,Vu as deriveInitials,pf as describeOperations,us as destructiveSchema,ge as detailView,sb as diffSchemaState,la as document,Ts as draftedLabelExpression,Yi as draftedObjectDefinition,bt as draftedViewDefinition,Xp as durableDateSchema,hf as episodeImpactOf,$S as evaluateComputedAst,US as evaluateComputedFormula,qS as evaluateComputedFormulaWithResult,xp as evaluateFilterState,sI as evaluateRecordFilterState,St as extractAttributeNames,oa as extractValueRefs,Mf as familyOf,Ra as findRelationAttribute,cl as flagRegistry,po as focusOf,Vx as form,ou as formFieldFlatKey,iu as formFieldKey,Na as formRegistry,aS as formatAgentStreamFrameId,Xo as formatAttributeValue,fA as formatByteSize,bp as formatComputedResult,hu as formatLocationValue,Dx as formula,cm as fromDraftableView,Ou as getEditableLabelAttribute,Fy as getErrorMessage,SS as getLiveProtocolPayloadChannel,Bu as getRecordCreatorPrincipalId,ia as getSingleAttributeFromExpression,Yo as getSlotFieldTargets,Mu as getUserDisplayName,he as group,Uf as guidanceForBatch,LI as hasDestructiveEntries,sh as hasOptions,hs as imageModelIdSchema,it as includesAction,Bo as inferInverseCardinality,tp as inferRollupReturnType,Wi as inferenceReasoningSchema,zi as inferenceSpeedSchema,nm as isAgentUIDataName,pS as isAgentUIMessageBatch,Gg as isAttributeSortable,Wg as isBilateralRelation,JS as isCheckboxEquality,ry as isClaimableSessionStatus,yt as isComputedAttribute,fn as isComputedFunctionName,Oe as isDateRangeValue,ax as isDefaultRole,hA as isDocumentAttribute,pc as isEdgePayload,cu as isEmptyObject,$y as isFormDefinition,Zt as isFormFieldsRow,Yn as isFormFreeFieldRef,Yy as isFormHeadingRow,Hy as isFormSeparatorRow,Ko as isFormSlotFieldRef,Jy as isFormTextRow,rn as isLabelExpression,IS as isLiveEventEnvelope,AS as isLiveEventPayload,Yl as isLiveEventPayloadForType,Kl as isLiveEventType,SI as isMailProvider,II as isMailboxListMode,Qo as isNotEmpty,ay as isOpenToolPartState,Ya as isPlainRecord,RI as isReplyMode,bx as isStandardSchema,cy as isSystemPartCode,ny as isTerminalSessionStatus,Xg as isTerminalState,sy as isToolApprovalState,Vo as isUniversalRelation,sl as jsonFlag,ty as legacyStatusToSessionState,ye as listView,Da as liveChannelKey,Nx as location,AA as matchesAccepts,Qp as mentionReferenceSchema,Zp as modelDefinitionSchema,ys as modelReferenceSchema,vx as multiselect,rc as namedTargetSchema,ru as nativeAgentUIPartIdMetadataKey,pu as normalizeDateValue,sn as number,al as numberFlag,Qx as object,uy as orderAgentSessionMessages,sS as parseAgentStreamFrameId,su as parseCountMode,Oa as parseLiveChannelKey,wf as parseNamedTarget,hy as parseNativeAgentUIPartIdsMetadata,mf as parseOperation,hh as parseOptionalCountMode,RA as parseQualifiedAttribute,ab as parseSchemaState,XI as persistedSchemaPlanSchema,Ix as phone,Pp as plannedAttributeSchema,Mp as plannedInlineAttributeSchema,Fp as plannedObjectSchema,Ut as presentationOf,$t as proposalTargetKey,gs as providerNameSchema,Pu as qualifiedPropertyDefs,Wy as readFormFieldValue,qi as reconcileRelationAttributes,Ft as regenerateDerived,KT as registry,ot as relation,xi as relationAcceptsObject,hT as relationProperty,_u as relationPropertyDefs,ht as relationTargetObjectName,X as relationTargets,zg as relationTargetsOf,uo as relationValueIds,Zn as renderLabelExpression,hI as requestedCapabilities,Rt as requireRecordContentContext,Ca as requireSingleRelationTarget,gf as requiredTargetKeys,Rp as resolveAttributeDefaultValue,Ku as resolveCollectionActions,Gu as resolveContentNavigation,zy as resolveFieldRequired,Xt as resolvePropertyDefinitions,Ai as resolveViewContents,je as richtext,Ox as rollup,ep as rollupToFormulaExpression,ZI as schemaPlanSchema,ib as schemaStateSourcePayload,fe as select,xR as sessionInferencePatchSchema,ey as sessionStateToLegacyStatus,Cx as status,Lf as stillMissing,Nt as storedContentDefinition,ol as stringFlag,Hf as summarizeDraft,_n as targetSnapshot,yf as targetTokensFor,S as text,Z as toAttribute,am as toDraftableAttributes,om as toDraftableObject,sm as toDraftableView,uu as toUndefinedIfEmpty,em as todoItemSchema,tm as todoPlanSchema,As as toolImpactSchema,qf as touchedObjectIds,Ex as user,Ti as validateContentViewCatalogue,Ru as validateLabelExpression,Wu as validateObjectExpressions,to as viewIdFor,gi as viewIdentityKey,jl as viewRegistry,Et as workspaceViewAuthoring};
|