@stndrds/schema 1.0.0-alpha.309 → 1.0.0-alpha.311
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{all-B9NmPJ-u.d.mts → all-DWs4Lt_e.d.mts} +22 -22
- package/dist/{all-ByffBHfA.d.ts → all-DfGOQgHT.d.ts} +22 -22
- package/dist/index.d.mts +8 -8
- package/dist/index.d.ts +8 -8
- package/dist/index.js +13 -13
- package/dist/index.mjs +13 -13
- package/dist/validation/all.d.mts +1 -1
- package/dist/validation/all.d.ts +1 -1
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
import {h as h$1,b as b$3}from'./chunk-KBGHKQMA.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-KBGHKQMA.mjs';import {B,S as S$1,V,w as w$1,C,ma as ma$1,na as na$1,ka as ka$1,fa as fa$1,ea as ea$1,$ as $$1,aa as aa$1,Z,ia as ia$1,la as la$1,y,ba as ba$1,_ as _$1,n,j as j$1,g as g$1,h as h$2,K as K$1,J as J$1,H as H$1,D as D$1,sa as sa$1,ra as ra$1}from'./chunk-SN2CUVKH.mjs';export{i as ATTRIBUTE_FILTER_OPERATORS,sa as LIST_TAB_KANBAN_KEYS,ra as LIST_TAB_TABLE_KEYS,y as LIST_VIEW_TAB_VISIBILITIES,f as LOCATION_FILTER_PROPERTIES,v as NATIVE_OBJECT_NAMES,s as NO_VALUE_OPERATORS,r as OPERATORS_BY_TYPE,W as REMOVED_OPERATOR_REPLACEMENTS,B as RESERVED_ATTRIBUTE_NAMES,C as RESERVED_OBJECT_NAMES,x as RESOURCE_VISIBILITIES,O as SYNONYM_ALIASES,c as SYSTEM_ATTRIBUTES,a as SYSTEM_ATTRIBUTE_I18N_KEYS,A as SYSTEM_FIELD_NAMES,V as SYSTEM_FILTER_ATTRIBUTE_TYPES,N as canonicalizeFilterValue,X as collectQualifiedRuleIssues,Z as columnsSchema,E as currentActor,ka as detailTabDraftSchema,ja as detailTabSchema,na as detailViewConfigSchema,_ as displayAttributesSchema,H as extractCurrencyFilterValue,I as extractFilterValue,da as fieldSchema,ca as fieldShape,ea as fieldSlotSchema,ba as filterGroupSchema,aa as filterStateSchema,j as getAttributeCapabilities,k as getAttributeFilterOperators,J as getOperatorPolarity,u as getRollupFilterOperators,b as getSystemAttributeI18nKey,d as getSystemAttributeList,fa as groupWriteSchema,ha as inverseSourceSchema,l as isAttributeFilterable,o as isAttributeGroupable,p as isAttributeKanbanGroupable,m as isAttributeSearchable,D as isDynamicValue,g as isLocationFilterProperty,h as isLocationPartOperator,e as isManagedSystemAttribute,w as isNativeObjectName,t as isNoValueOperator,R as isRelativeDateValue,M as isSetMembershipOperator,ma as listViewConfigSchema,la as listViewTabSchema,Q as normalizeFilterRule,K as normalizeForEdgeRpc,P as normalizeOperator,G as now,z as parseResourceVisibility,qa as parseViewConfig,ga as relationSourceSchema,q as resolveEffectiveFilterType,S as resolveIsWithinBounds,T as resolveUtcDayBounds,$ as sortsSchema,ia as tableSourceSchema,L as toMultiValueOperator,U as toUtcDayString,F as today,Y as validateQualifiedRule,pa as viewConfigByTypeSchema,oa as viewTypeSchema}from'./chunk-SN2CUVKH.mjs';import {c,e as e$1,n as n$1}from'./chunk-XB3VOCHA.mjs';export{d as ComputedFormulaParseError,a as SCHEMA_LIMITS,b as colorIdSchema,c as iconNameSchema,h as multiselectOptionWriteSchema,l as parseAttributeConfig,n as parseAttributeConfigForCreate,o as parseAttributeConfigForUpdate,e as parseComputedFormula,g as selectOptionWriteSchema,f as statusGroupSchema,i as statusOptionWriteSchema}from'./chunk-XB3VOCHA.mjs';import {a as a$1,c as c$2,e,g as g$2}from'./chunk-JBXPLCBH.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-JBXPLCBH.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 as c$1,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,b as b$1,a as a$2,r,s,c as c$3}from'./chunk-LDK7LMOY.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-LDK7LMOY.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 {ICONS,SKILL_NAME_MAX_LENGTH,SKILL_DESCRIPTION_MAX_LENGTH,MEMORY_NAME_MAX_LENGTH,MEMORY_DESCRIPTION_MAX_LENGTH,getCountryDisplayNameByIso3}from'@stndrds/constants';import wr,{z as z$1}from'zod';/*! © 2025-2026 AND YOU CREATE SAS (RCS Paris 940 190 614). Proprietary — see LICENSE (Standards SDK License 1.0). */
|
|
2
|
-
var po=["fyi","task","question","handoff","system"],mo=["low","normal","high","urgent"],fo=["public","internal","sensitive"],bo=["unread","read","archived","snoozed"],go=["none","pending","processing","completed","dismissed","expired","failed"],Au="agent.session.waiting_human",Tu="agent.task.assigned",wu="agent.question.requested",Pg=[Au,Tu,wu];var Fg=["name","type"],Vg=["required","hidden","archived","deprecated","defaultValue","config","order","unique"],Mg=["label","description","placeholder","icon"];var yo=["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"],ee="*";function $g(e){return e.type!=="relation"||!Array.isArray(e.targets)?[]:e.targets.map(t=>t.object).filter(t=>t!==ee)}a($g,"relationTargetsOf");function ho(e){return e.targets.length===1&&e.targets[0].object===ee}a(ho,"isUniversalRelation");function Ug(e){return e.bilateral!==void 0}a(Ug,"isBilateralRelation");function qg(e){return "many"}a(qg,"inferInverseCardinality");function zg(e){return n(e)}a(zg,"isAttributeSortable");var Kg=["record","object","attribute","view","user","role","settings","file","agent","schema_source"],Hg=["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 Jg(e){return e.phase==="terminal"}a(Jg,"isTerminalState");function Xg(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(Xg,"sessionStateToLegacyStatus");function Zg(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(Zg,"legacyStatusToSessionState");var xu=["completed","failed","cancelled","timeout","expired"];function ey(e){return xu.includes(e)}a(ey,"isTerminalSessionStatus");var Iu=["idle","completed","waiting_human","waiting_agents","cancelled","failed","timeout"];function ty(e){return Iu.includes(e)}a(ty,"isClaimableSessionStatus");var Ao=Object.freeze({mutation:"ask",destructive:"ask",outward:"ask"}),ry=["active","completed","abandoned"],To=["openai","anthropic","google","spacexai","deepseek","moonshotai","alibaba","mistral","minimax","meta","zai"],wo=["standard","fast"],xo=["none","minimal","low","medium","high","xhigh"];function ny(e){return e.label?.trim()||e.name}a(ny,"agentDisplayName");var Io=["approval-requested","approval-responded","approval-dispatched"],Su=["streaming","running","pending",...Io];function iy(e){return Su.includes(e)}a(iy,"isOpenToolPartState");function oy(e){return Io.includes(e)}a(oy,"isToolApprovalState");var mr=["CREDITS_EXHAUSTED"];function ay(e){return typeof e=="string"&&mr.includes(e)}a(ay,"isSystemPartCode");function vu(e,t){let r=e.createdAt.getTime()-t.createdAt.getTime();return r===0?e.id.localeCompare(t.id):r}a(vu,"compareAgentSessionMessages");function sy(e){return [...e].sort(vu)}a(sy,"orderAgentSessionMessages");var uy=["pending","in_progress","completed","blocked"],ly=50,dy=80,cy=500,py=2e3;var gy="session-state",Ru="__stndrdsNativeUiPartIds",Du=1,Eu="Native agent UI part IDs metadata is invalid";function le(){throw new h(Eu,[])}a(le,"invalidNativePartIds");function So(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}a(So,"isPlainRecord");function Cu(e,t){if(e.type==="text"||e.type==="reasoning")return `${e.type}:${t}`;if(e.type==="tool")return `tool:${e.toolCallId}`}a(Cu,"nativeAgentUIPartIdMetadataKey");function yy(e){let t=e.metadata?.[Ru];So(t)||le(),(Object.keys(t).length!==2||t.schemaVersion!==Du||!So(t.partIds))&&le();let r=new Map;for(let[s,l]of e.parts.entries()){let c=Cu(l,s);if(!c||r.has(c)){c&&le();continue}r.set(c,l);}let n=Object.entries(t.partIds);n.length!==r.size&&le();let o=new Map,a={};for(let[s,l]of n){let c=r.get(s);c&&typeof l=="string"&&l.length>0||le();let f=o.get(l);f&&(c.type==="tool"||f!==c.type)&&le(),c.type==="tool"&&l!==c.toolCallId&&le(),o.set(l,c.type),a[s]=l;}return a}a(yy,"parseNativeAgentUIPartIdsMetadata");var Ty=16e3,wy=3200,xy=6400,Iy=16e3,Sy=65536,vy=15e3,Ry=1e4,Dy=5e3,Ey="google/gemini-3.5-transcribe-live",Cy={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2};var _y=["web","presentation","document","spreadsheet","image","code","other"],Ny=["ephemeral","conversation","persistent"],ky=["source","preview","entrypoint","asset"];var vo=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 By(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(By,"isFormDefinition");var fr=["relation","multiRelation","formula","rollup","document","richtext","user"];function Ro(e){return e.type==="slot"}a(Ro,"isFormSlotFieldRef");function br(e){return e.type==="free"}a(br,"isFormFreeFieldRef");function qy(e){return e.fieldRequired!==void 0?e.fieldRequired:e.slotMode==="create"&&e.attributeRequired===true}a(qy,"resolveFieldRequired");function Do(e){return e.additionalSlotIds?.length?[e.slotId,...e.additionalSlotIds]:[e.slotId]}a(Do,"getSlotFieldTargets");function Ou(e){return Ro(e)?`${e.slotId}.${e.attribute}`:`free.${e.attribute.name}`}a(Ou,"formFieldKey");function _u(e){return Ro(e)?e.attribute:e.attribute.name}a(_u,"formFieldFlatKey");function zy(e,t){return e[Ou(t)]??e[_u(t)]}a(zy,"readFormFieldValue");function ct(e){return e.type==="fields"}a(ct,"isFormFieldsRow");function Ky(e){return e.type==="heading"}a(Ky,"isFormHeadingRow");function Hy(e){return e.type==="separator"}a(Hy,"isFormSeparatorRow");function Yy(e){return e.type==="text"}a(Yy,"isFormTextRow");var gr=class gr{async autocomplete(){return await Promise.resolve([])}async reverse(){return await Promise.resolve(null)}async geocode(){return await Promise.resolve(null)}};a(gr,"NoopGeocodingAdapter");var Eo=gr;var yr=["read","create","update","delete","manage"];function rh(e){return e.length===0?"none":e.length===1&&e[0]==="read"?"read-only":e.length===yr.length&&yr.every(t=>e.includes(t))?"full":"custom"}a(rh,"actionsToAccessLevel");function nh(e){switch(e){case "full":return [...yr];case "read-only":return ["read"];case "none":return []}}a(nh,"accessLevelToActions");function Co(e){let t=e.properties;if(!t)return [];if(Array.isArray(t))return t;let r=t;return Array.isArray(r.definitions)?r.definitions:[]}a(Co,"resolvePropertyDefinitions");function ah(e){return e.type==="select"||e.type==="status"||e.type==="multiselect"}a(ah,"hasOptions");var Nu="Notetaker",lh={systemPrompt:null,meetingRecordingPolicy:"none",meetingBotDisplayName:Nu};var ch=["active","suspended"],ph=["architect","manual","auto"];function fh(e){return `${e.object}:${e.name}:${e.type}`}a(fh,"viewStateKey");function pt(e){return e.type==="detail"}a(pt,"isDetailView");function Oo(e){return e.type==="list"}a(Oo,"isListView");function ku(e){return e.type==="fields"}a(ku,"isFieldGroup");var Ah=["square","landscape","portrait"];var _o=["none","estimated","exact"];function Pu(e){if(typeof e=="string"&&_o.includes(e))return e;throw new h(`countMode must be one of: ${_o.join(", ")} (received: ${String(e)})`,[])}a(Pu,"parseCountMode");function xh(e){return e===void 0?void 0:Pu(e)}a(xh,"parseOptionalCountMode");var Ih=1e4;var Rh=["storage.bytes","members.seats","data.live_records"];function ju(e){return e==null?true:typeof e!="object"?false:Object.keys(e).length===0}a(ju,"isEmptyObject");function No(e){return e!=null&&typeof e=="object"&&Object.keys(e).length>0}a(No,"isNotEmpty");function Fu(e){return No(e)?e:void 0}a(Fu,"toUndefinedIfEmpty");function Vu(e){if(e<=0)return {value:0,unitIndex:0};let t=1e3,r=Math.min(4,Math.floor(Math.log(e)/Math.log(t)));return {value:Number.parseFloat((e/t**r).toFixed(1)),unitIndex:r}}a(Vu,"computeByteMagnitude");var Mu=["B","KB","MB","GB","TB"];function AA(e){let{value:t,unitIndex:r}=Vu(e);return `${t} ${Mu[r]}`}a(AA,"formatByteSize");function Lu(e){return e.displayAttributes!==void 0?[...e.displayAttributes]:[...new Set([e.cardUserAttribute,e.cardDateAttribute].filter(t=>t!==void 0))]}a(Lu,"getListViewDisplayAttributeNames");var SA={ATTACHMENTS:"attachments"};function vA(e){return e.type==="document"}a(vA,"isDocumentAttribute");function RA(e,t){if(!t||t.length===0)return true;let r=e.name.toLowerCase();return t.some(n=>n.endsWith("/*")?e.mimeType.startsWith(n.slice(0,-1)):n.startsWith(".")?r.endsWith(n.toLowerCase()):e.mimeType===n)}a(RA,"matchesAccepts");var ko=Object.freeze(["text","number","checkbox","date","phone","currency","status","select","multiselect","location"]);function mt(e){let t=[];for(let r of e){let n=r.build();if(!ko.includes(n.type))throw new Error(`Property type "${n.type}" is not supported in .qualifyWith()`);t.push(n);}return {definitions:t}}a(mt,"buildPropertySchema");var _A="__";function NA(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(NA,"parseQualifiedAttribute");function kA(e,t){return `${e}__${t}`}a(kA,"buildQualifiedAttribute");function ne(e){return typeof e=="object"&&e!==null&&typeof e.start=="string"}a(ne,"isDateRangeValue");function Bu(e,t){return a$1(e)?null:ne(e)?t.endDate?{start:e.start,end:e.end??null}:e.start:typeof e=="string"?t.endDate?{start:e,end:null}:e:null}a(Bu,"normalizeDateValue");function he(e){return typeof e=="string"&&e!==""?e:ne(e)&&e.start!==""?e.start:null}a(he,"dateValueStart");var ft="\u2014";function $u(e){return String(e)}a($u,"formatText");function Uu(e){return e?"Yes":"No"}a(Uu,"formatCheckbox");function qu(e,t){if(typeof e!="number")return String(e);if(t.renderAs==="rating")return `${e}/${t.max??5}`;let r=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:r,maximumFractionDigits:r}):e.toLocaleString(void 0,{minimumFractionDigits:r,maximumFractionDigits:r})}a(qu,"formatNumber");function zu(e,t){if(typeof e!="object"||e===null)return String(e);let r=e;return "value"in r&&"code"in r?`${r.value.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})} ${r.code}`:String(e)}a(zu,"formatCurrency");function hr(e){if(ne(e)){let t=hr(e.start);return e.end?`${t} \u2192 ${hr(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(hr,"formatDate");function Gu(e){if(typeof e!="object"||e===null)return String(e);let t=e;return "phoneNumber"in t?t.phoneNumber?t.countryCode?c$1(t):t.phoneNumber:"":String(e)}a(Gu,"formatPhone");function Wu(e,t="full"){if(typeof e!="object"||e===null)return "";let r=e,n=[];switch(t){case "country":r.country&&n.push(getCountryDisplayNameByIso3(r.country));break;case "state":r.state&&n.push(r.state),r.country&&n.push(getCountryDisplayNameByIso3(r.country));break;case "city":r.city&&n.push(r.city),r.state&&n.push(r.state),r.country&&n.push(getCountryDisplayNameByIso3(r.country));break;case "coordinates":r.latitude!==void 0&&r.longitude!==void 0&&n.push(`${r.latitude}, ${r.longitude}`);break;case "address":r.address&&n.push(r.address),r.city&&n.push(r.city),r.state&&n.push(r.state),r.country&&n.push(getCountryDisplayNameByIso3(r.country));break;default:r.address&&n.push(r.address),r.address2&&n.push(r.address2),r.city&&n.push(r.city),r.state&&n.push(r.state),r.postalCode&&n.push(r.postalCode),r.country&&n.push(getCountryDisplayNameByIso3(r.country));break}return n.join(", ")}a(Wu,"formatLocationValue");function Ku(e,t){return typeof e!="object"||e===null?String(e):Wu(e,t.granularity??"full")||ft}a(Ku,"formatLocation");function Hu(e,t){return typeof e!="string"?String(e):t.options?.find(n=>n.value===e)?.label??String(e)}a(Hu,"formatSelect");function Yu(e,t){return Array.isArray(e)?t.options?e.map(n=>t.options.find(o=>o.value===n)?.label).filter(Boolean).join(", "):e.join(", "):String(e)}a(Yu,"formatMultiselect");function Po(e,t){if(a$1(e))return ft;switch(t.type){case "text":return $u(e);case "checkbox":return Uu(e);case "number":return qu(e,t);case "currency":return zu(e);case "date":return hr(e);case "phone":return Gu(e);case "location":return Ku(e,t);case "select":case "status":return Hu(e,t);case "multiselect":return Yu(e,t);case "user":case "relation":return Array.isArray(e)?e.join(", "):String(e);default:return Array.isArray(e)?e.join(", "):String(e)}}a(Po,"formatAttributeValue");var Ju=["UPPER","LOWER","capitalize","trim"],Xu=["prefix","suffix","wrap","default"],bt=[...Ju,...Xu],Ae=z$1.string().min(1,"labelExpression cannot be empty").refine(e=>gt(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,r;for(;(r=t.exec(e))!==null;){let n=r[1];if(!bt.includes(n))return false}return true},{message:`Invalid pipe name. Valid pipes: ${bt.join(", ")}`});function Zu(e){let t=Ae.safeParse(e);return t.success?{success:true,attributes:Bo(e)}:{success:false,error:t.error.issues[0]?.message??"Invalid labelExpression"}}a(Zu,"validateLabelExpression");var jo={UPPER:a(e=>String(e).toUpperCase(),"UPPER"),LOWER:a(e=>String(e).toLowerCase(),"LOWER"),capitalize:a(e=>String(e).replace(/(^|\s)\S/g,t=>t.toUpperCase()),"capitalize"),trim:a(e=>String(e).trim(),"trim")},Fo={prefix:a((e,t="")=>e?`${t}${e}`:"","prefix"),suffix:a((e,t="")=>e?`${e}${t}`:"","suffix"),wrap:a((e,t="",r="")=>e?`${t}${e}${r}`:"","wrap"),default:a((e,t="")=>e||t,"default")};function el(e,t){let r=e;for(let n of t){let{name:o,args:a}=Mo(n),s=jo[o];if(s)r!==""&&(r=s(r));else {let l=Fo[o];l&&(r=l(r,...a));}}return r}a(el,"applyPipes");function tl(e,t){return t.split(".").reduce((r,n)=>{if(!(r==null||typeof r!="object"))return r[n]},e)}a(tl,"getValue");var Vo="(Untitled)";function Mo(e){let t=e.match(/^(\w+)(?::(.*))?$/);if(!t)return {name:e,args:[]};let r=t[1],n=t[2];if(!n)return {name:r,args:[]};let o=[],a=/["']([^"']*?)["']/g,s;for(;(s=a.exec(n))!==null;)o.push(s[1]);return {name:r,args:o}}a(Mo,"parsePipeExpression");function Ar(e,t,r=Vo){return e.replace(/\{\{\s*([^}]+)\s*\}\}/g,(o,a)=>{let s=a.split("||").map(R=>R.trim()),c=s[s.length-1].split("|").map(R=>R.trim());s[s.length-1]=c[0];let f=c.slice(1).filter(Boolean),x=s.filter(Boolean),v="";for(let R of x){let X=Lo(tl(t,R));if(X!==""){v=X;break}}if(a$1(v)&&f.length===0)return "";for(let R of f){let{name:X,args:Js}=Mo(R),$i=jo[X];if($i)v!==""&&(v=$i(v));else {let Ui=Fo[X];Ui&&(v=Ui(v,...Js));}}return v}).trim()||r}a(Ar,"renderLabelExpression");function Lo(e){if(e==null||typeof e=="function")return "";if(typeof e!="object")return String(e);if(Array.isArray(e))return e.map(Lo).filter(Boolean).join(",");let t=e.toString;return typeof t=="function"&&t!==Object.prototype.toString?String(e):""}a(Lo,"toText");function gt(e){return /\{\{\s*\S+.*\}\}/.test(e)}a(gt,"isLabelExpression");function Bo(e){let t=[],r=/\{\{\s*([^}]+)\s*\}\}/g,n;for(;(n=r.exec(e))!==null;){let a=n[1].trim().split("||").map(l=>l.trim()),s=a[a.length-1];a[a.length-1]=s.split("|")[0].trim();for(let l of a){if(!l)continue;let c=l.split(".")[0];c&&!t.includes(c)&&t.push(c);}}return t}a(Bo,"extractAttributeNames");var rl=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function $o(e){let t=e.trim().match(rl);return t?t[1]:null}a($o,"getSingleAttributeFromExpression");function nl(e,t){let r=$o(e);if(r===null)return null;let n=t.find(o=>o.name===r);return !n||n.type!=="text"||j$1(n).authoring.readOnly?null:n}a(nl,"getEditableLabelAttribute");var il=/\{\{\s*props\./;function ol(e,t,r){if(!il.test(e))return e;let n={},o=new Map(r?.map(s=>[s.name,s]));if(t)for(let[s,l]of Object.entries(t)){if(l==null)continue;let c=o.get(s);if(c){let f=Po(l,c);n[s]=f===ft?"":f;}else n[s]=l;}return Ar(e,{props:n},"").replace(/\(\s*\)/g,"").replace(/\[\s*\]/g,"").replace(/\s*[-—|:]\s*$/g,"").replace(/\s{2,}/g," ").trim()}a(ol,"applyRelationProps");function al(e){if(e?.type==="relation")return e.properties?.definitions}a(al,"relationPropertyDefs");function sl(e){if(e?.type==="relation"||e?.type==="document")return e.properties?.definitions}a(sl,"qualifiedPropertyDefs");function Uo(e){if(a$1(e))return [];if(typeof e=="string")return [{id:e}];if(Array.isArray(e))return e.flatMap(t=>Uo(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(Uo,"extractValueRefs");function ul(e){let t=[e.firstName,e.lastName].map(r=>r?.trim()).filter(Boolean).join(" ");return t!==""?t:e.email?.split("@")[0]??""}a(ul,"getUserDisplayName");var ll=/\p{L}|\p{N}/u;function dl(e,t){let r=e?.trim()??"";if(r==="")return t;let n=r.split(/\s+/),a=(n.length===1?r.split("@")[0].split(/[._-]/):n).map(s=>{let l=s.match(ll)?.[0];return l===void 0?"":[...l.toUpperCase()][0]??""}).filter(Boolean).slice(0,2).join("");return a===""?t:a}a(dl,"deriveInitials");var qo="__creatorRootActorId";function cl(e){let t=e.metadata?.[qo];return typeof t=="string"&&t.length>0?t:e.createdBy}a(cl,"getRecordCreatorPrincipalId");function Te(e,t){return e?.includes("*")===true||e?.includes(t)===true}a(Te,"includesAction");function pl(e){return {canRead:Te(e,"read"),canCreate:Te(e,"create"),canUpdate:Te(e,"update"),canDelete:Te(e,"delete"),canManage:Te(e,"manage")}}a(pl,"buildPermissionFlags");var sT=new Set(["id","name","label","type","required","system","unique","order"]);var $={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"},lT=[$.PEOPLE,$.WORKSPACE,$.ARCHITECT,$.FEATURE_FLAGS,$.FILES,$.VIEWS,$.FORMS,$.DOCUMENTS,$.AUDIT,$.API_KEYS,$.CONNECTORS,$.ENV_VARS,$.SESSION],dT={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"},ml={OWNER:"owner",MEMBER:"member",AGENT_DEFAULT:"agent_default",REFLEX_DEFAULT:"reflex_default"},cT={owner:"Owner",member:"Member",agent_default:"Agent Default",reflex_default:"Reflex Default"},pT={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"},Tr=["read","create","update","delete","manage"],fl=["read","create","delete"],mT={owner:{system:[{target:"*",actions:Tr}],object:[{target:"*",actions:Tr}]},member:{system:[{target:"people",actions:["read"]},{target:"workspace",actions:["read"]},{target:"connectors",actions:fl},{target:"files",actions:["read","create","update"]}],object:[{target:"*",actions:Tr}]},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 fT(e){return Object.values(ml).includes(e)}a(fT,"isDefaultRole");var gl=new Set(ICONS),Go=/^[a-zA-Z_][a-zA-Z0-9_]*$/,yl=/^[a-z][a-z0-9-]*$/,we=63,zo=128,yt=wr.string().min(1,"Object name cannot be empty").max(63,"Object name is too long (max 63 characters)").regex(/^[a-z][a-z0-9-]*$/,{message:`Invalid object name format.
|
|
2
|
+
var po=["fyi","task","question","handoff","system"],mo=["low","normal","high","urgent"],fo=["public","internal","sensitive"],bo=["unread","read","archived","snoozed"],go=["none","pending","processing","completed","dismissed","expired","failed"],Tu="agent.session.waiting_human",wu="agent.task.assigned",xu="agent.question.requested",jg=[Tu,wu,xu];var Vg=["name","type"],Mg=["required","hidden","archived","deprecated","defaultValue","config","order","unique"],Lg=["label","description","placeholder","icon"];var yo=["text","richtext","number","checkbox","date","phone","currency","status","location","select","multiselect","user","relation","formula","rollup","document"],ee="*";function Ug(e){return e.type!=="relation"||!Array.isArray(e.targets)?[]:e.targets.map(t=>t.object).filter(t=>t!==ee)}a(Ug,"relationTargetsOf");function ho(e){return e.targets.length===1&&e.targets[0].object===ee}a(ho,"isUniversalRelation");function qg(e){return e.bilateral!==void 0}a(qg,"isBilateralRelation");function zg(e){return "many"}a(zg,"inferInverseCardinality");function Gg(e){return n(e)}a(Gg,"isAttributeSortable");var Hg=["record","object","attribute","view","user","role","settings","file","agent","schema_source"],Yg=["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 Zg(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(Zg,"sessionStateToLegacyStatus");function ey(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(ey,"legacyStatusToSessionState");var Iu=["completed","failed","cancelled","timeout","expired"];function ty(e){return Iu.includes(e)}a(ty,"isTerminalSessionStatus");var Su=["idle","completed","waiting_human","waiting_agents","cancelled","failed","timeout"];function ry(e){return Su.includes(e)}a(ry,"isClaimableSessionStatus");var Ao=Object.freeze({mutation:"ask",destructive:"ask",outward:"ask"}),ny=["active","completed","abandoned"],To=["openai","anthropic","google","spacexai","deepseek","moonshotai","alibaba","mistral","minimax","meta","zai"],wo=["standard","fast"],xo=["none","minimal","low","medium","high","xhigh"];function iy(e){return e.label?.trim()||e.name}a(iy,"agentDisplayName");var Io=["approval-requested","approval-responded","approval-dispatched"],vu=["streaming","running","pending",...Io];function oy(e){return vu.includes(e)}a(oy,"isOpenToolPartState");function ay(e){return Io.includes(e)}a(ay,"isToolApprovalState");var mr=["CREDITS_EXHAUSTED"];function sy(e){return typeof e=="string"&&mr.includes(e)}a(sy,"isSystemPartCode");function Ru(e,t){let r=e.createdAt.getTime()-t.createdAt.getTime();return r===0?e.id.localeCompare(t.id):r}a(Ru,"compareAgentSessionMessages");function uy(e){return [...e].sort(Ru)}a(uy,"orderAgentSessionMessages");var ly=["pending","in_progress","completed","blocked"],dy=50,cy=80,py=500,my=2e3;var yy="session-state",Du="__stndrdsNativeUiPartIds",Eu=1,Cu="Native agent UI part IDs metadata is invalid";function le(){throw new h(Cu,[])}a(le,"invalidNativePartIds");function So(e){if(e===null||typeof e!="object"||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}a(So,"isPlainRecord");function Ou(e,t){if(e.type==="text"||e.type==="reasoning")return `${e.type}:${t}`;if(e.type==="tool")return `tool:${e.toolCallId}`}a(Ou,"nativeAgentUIPartIdMetadataKey");function hy(e){let t=e.metadata?.[Du];So(t)||le(),(Object.keys(t).length!==2||t.schemaVersion!==Eu||!So(t.partIds))&&le();let r=new Map;for(let[s,l]of e.parts.entries()){let c=Ou(l,s);if(!c||r.has(c)){c&&le();continue}r.set(c,l);}let n=Object.entries(t.partIds);n.length!==r.size&&le();let o=new Map,a={};for(let[s,l]of n){let c=r.get(s);c&&typeof l=="string"&&l.length>0||le();let f=o.get(l);f&&(c.type==="tool"||f!==c.type)&&le(),c.type==="tool"&&l!==c.toolCallId&&le(),o.set(l,c.type),a[s]=l;}return a}a(hy,"parseNativeAgentUIPartIdsMetadata");var wy=16e3,xy=3200,Iy=6400,Sy=16e3,vy=65536,Ry=15e3,Dy=1e4,Ey=5e3,Cy="google/gemini-3.5-transcribe-live",Oy={maxDurationMs:3e5,dailyDurationMs:36e5,monthlyDurationMs:72e6,tenantMonthlyBudgetMicrousd:5e7,globalMonthlyBudgetMicrousd:5e7,estimatedMicrousdPerSecond:150,reservationMultiplier:2};var Ny=["web","presentation","document","spreadsheet","image","code","other"],ky=["ephemeral","conversation","persistent"],Py=["source","preview","entrypoint","asset"];var vo=5;function Vy(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(Vy,"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 fr=["relation","multiRelation","formula","rollup","document","richtext","user"];function Ro(e){return e.type==="slot"}a(Ro,"isFormSlotFieldRef");function br(e){return e.type==="free"}a(br,"isFormFreeFieldRef");function zy(e){return e.fieldRequired!==void 0?e.fieldRequired:e.slotMode==="create"&&e.attributeRequired===true}a(zy,"resolveFieldRequired");function Do(e){return e.additionalSlotIds?.length?[e.slotId,...e.additionalSlotIds]:[e.slotId]}a(Do,"getSlotFieldTargets");function _u(e){return Ro(e)?`${e.slotId}.${e.attribute}`:`free.${e.attribute.name}`}a(_u,"formFieldKey");function Nu(e){return Ro(e)?e.attribute:e.attribute.name}a(Nu,"formFieldFlatKey");function Gy(e,t){return e[_u(t)]??e[Nu(t)]}a(Gy,"readFormFieldValue");function ct(e){return e.type==="fields"}a(ct,"isFormFieldsRow");function Hy(e){return e.type==="heading"}a(Hy,"isFormHeadingRow");function Yy(e){return e.type==="separator"}a(Yy,"isFormSeparatorRow");function Qy(e){return e.type==="text"}a(Qy,"isFormTextRow");var gr=class gr{async autocomplete(){return await Promise.resolve([])}async reverse(){return await Promise.resolve(null)}async geocode(){return await Promise.resolve(null)}};a(gr,"NoopGeocodingAdapter");var Eo=gr;var yr=["read","create","update","delete","manage"];function nh(e){return e.length===0?"none":e.length===1&&e[0]==="read"?"read-only":e.length===yr.length&&yr.every(t=>e.includes(t))?"full":"custom"}a(nh,"actionsToAccessLevel");function ih(e){switch(e){case "full":return [...yr];case "read-only":return ["read"];case "none":return []}}a(ih,"accessLevelToActions");function Co(e){let t=e.properties;if(!t)return [];if(Array.isArray(t))return t;let r=t;return Array.isArray(r.definitions)?r.definitions:[]}a(Co,"resolvePropertyDefinitions");function sh(e){return e.type==="select"||e.type==="status"||e.type==="multiselect"}a(sh,"hasOptions");var ku="Notetaker",dh={systemPrompt:null,meetingRecordingPolicy:"none",meetingBotDisplayName:ku};var ph=["active","suspended"],mh=["architect","manual","auto"];function bh(e){return `${e.object}:${e.name}:${e.type}`}a(bh,"viewStateKey");function pt(e){return e.type==="detail"}a(pt,"isDetailView");function Oo(e){return e.type==="list"}a(Oo,"isListView");function Pu(e){return e.type==="fields"}a(Pu,"isFieldGroup");var Th=["square","landscape","portrait"];var _o=["none","estimated","exact"];function ju(e){if(typeof e=="string"&&_o.includes(e))return e;throw new h(`countMode must be one of: ${_o.join(", ")} (received: ${String(e)})`,[])}a(ju,"parseCountMode");function Ih(e){return e===void 0?void 0:ju(e)}a(Ih,"parseOptionalCountMode");var Sh=1e4;var Dh=["storage.bytes","members.seats","data.live_records"];function Fu(e){return e==null?true:typeof e!="object"?false:Object.keys(e).length===0}a(Fu,"isEmptyObject");function No(e){return e!=null&&typeof e=="object"&&Object.keys(e).length>0}a(No,"isNotEmpty");function Vu(e){return No(e)?e:void 0}a(Vu,"toUndefinedIfEmpty");function Mu(e){if(e<=0)return {value:0,unitIndex:0};let t=1e3,r=Math.min(4,Math.floor(Math.log(e)/Math.log(t)));return {value:Number.parseFloat((e/t**r).toFixed(1)),unitIndex:r}}a(Mu,"computeByteMagnitude");var Lu=["B","KB","MB","GB","TB"];function TA(e){let{value:t,unitIndex:r}=Mu(e);return `${t} ${Lu[r]}`}a(TA,"formatByteSize");function Bu(e){return e.displayAttributes!==void 0?[...e.displayAttributes]:[...new Set([e.cardUserAttribute,e.cardDateAttribute].filter(t=>t!==void 0))]}a(Bu,"getListViewDisplayAttributeNames");var vA={ATTACHMENTS:"attachments"};function RA(e){return e.type==="document"}a(RA,"isDocumentAttribute");function DA(e,t){if(!t||t.length===0)return true;let r=e.name.toLowerCase();return t.some(n=>n.endsWith("/*")?e.mimeType.startsWith(n.slice(0,-1)):n.startsWith(".")?r.endsWith(n.toLowerCase()):e.mimeType===n)}a(DA,"matchesAccepts");var ko=Object.freeze(["text","number","checkbox","date","phone","currency","status","select","multiselect","location"]);function mt(e){let t=[];for(let r of e){let n=r.build();if(!ko.includes(n.type))throw new Error(`Property type "${n.type}" is not supported in .qualifyWith()`);t.push(n);}return {definitions:t}}a(mt,"buildPropertySchema");var NA="__";function kA(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(kA,"parseQualifiedAttribute");function PA(e,t){return `${e}__${t}`}a(PA,"buildQualifiedAttribute");function ne(e){return typeof e=="object"&&e!==null&&typeof e.start=="string"}a(ne,"isDateRangeValue");function $u(e,t){return a$1(e)?null:ne(e)?t.endDate?{start:e.start,end:e.end??null}:e.start:typeof e=="string"?t.endDate?{start:e,end:null}:e:null}a($u,"normalizeDateValue");function he(e){return typeof e=="string"&&e!==""?e:ne(e)&&e.start!==""?e.start:null}a(he,"dateValueStart");var ft="\u2014";function Uu(e){return String(e)}a(Uu,"formatText");function qu(e){return e?"Yes":"No"}a(qu,"formatCheckbox");function zu(e,t){if(typeof e!="number")return String(e);if(t.renderAs==="rating")return `${e}/${t.max??5}`;let r=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:r,maximumFractionDigits:r}):e.toLocaleString(void 0,{minimumFractionDigits:r,maximumFractionDigits:r})}a(zu,"formatNumber");function Gu(e,t){if(typeof e!="object"||e===null)return String(e);let r=e;return "value"in r&&"code"in r?`${r.value.toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})} ${r.code}`:String(e)}a(Gu,"formatCurrency");function hr(e){if(ne(e)){let t=hr(e.start);return e.end?`${t} \u2192 ${hr(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(hr,"formatDate");function Wu(e){if(typeof e!="object"||e===null)return String(e);let t=e;return "phoneNumber"in t?t.phoneNumber?t.countryCode?c$1(t):t.phoneNumber:"":String(e)}a(Wu,"formatPhone");function Ku(e,t="full"){if(typeof e!="object"||e===null)return "";let r=e,n=[];switch(t){case "country":r.country&&n.push(getCountryDisplayNameByIso3(r.country));break;case "state":r.state&&n.push(r.state),r.country&&n.push(getCountryDisplayNameByIso3(r.country));break;case "city":r.city&&n.push(r.city),r.state&&n.push(r.state),r.country&&n.push(getCountryDisplayNameByIso3(r.country));break;case "coordinates":r.latitude!==void 0&&r.longitude!==void 0&&n.push(`${r.latitude}, ${r.longitude}`);break;case "address":r.address&&n.push(r.address),r.city&&n.push(r.city),r.state&&n.push(r.state),r.country&&n.push(getCountryDisplayNameByIso3(r.country));break;default:r.address&&n.push(r.address),r.address2&&n.push(r.address2),r.city&&n.push(r.city),r.state&&n.push(r.state),r.postalCode&&n.push(r.postalCode),r.country&&n.push(getCountryDisplayNameByIso3(r.country));break}return n.join(", ")}a(Ku,"formatLocationValue");function Hu(e,t){return typeof e!="object"||e===null?String(e):Ku(e,t.granularity??"full")||ft}a(Hu,"formatLocation");function Yu(e,t){return typeof e!="string"?String(e):t.options?.find(n=>n.value===e)?.label??String(e)}a(Yu,"formatSelect");function Qu(e,t){return Array.isArray(e)?t.options?e.map(n=>t.options.find(o=>o.value===n)?.label).filter(Boolean).join(", "):e.join(", "):String(e)}a(Qu,"formatMultiselect");function Po(e,t){if(a$1(e))return ft;switch(t.type){case "text":return Uu(e);case "checkbox":return qu(e);case "number":return zu(e,t);case "currency":return Gu(e);case "date":return hr(e);case "phone":return Wu(e);case "location":return Hu(e,t);case "select":case "status":return Yu(e,t);case "multiselect":return Qu(e,t);case "user":case "relation":return Array.isArray(e)?e.join(", "):String(e);default:return Array.isArray(e)?e.join(", "):String(e)}}a(Po,"formatAttributeValue");var Xu=["UPPER","LOWER","capitalize","trim"],Zu=["prefix","suffix","wrap","default"],bt=[...Xu,...Zu],Ae=z$1.string().min(1,"labelExpression cannot be empty").refine(e=>gt(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,r;for(;(r=t.exec(e))!==null;){let n=r[1];if(!bt.includes(n))return false}return true},{message:`Invalid pipe name. Valid pipes: ${bt.join(", ")}`});function el(e){let t=Ae.safeParse(e);return t.success?{success:true,attributes:Bo(e)}:{success:false,error:t.error.issues[0]?.message??"Invalid labelExpression"}}a(el,"validateLabelExpression");var jo={UPPER:a(e=>String(e).toUpperCase(),"UPPER"),LOWER:a(e=>String(e).toLowerCase(),"LOWER"),capitalize:a(e=>String(e).replace(/(^|\s)\S/g,t=>t.toUpperCase()),"capitalize"),trim:a(e=>String(e).trim(),"trim")},Fo={prefix:a((e,t="")=>e?`${t}${e}`:"","prefix"),suffix:a((e,t="")=>e?`${e}${t}`:"","suffix"),wrap:a((e,t="",r="")=>e?`${t}${e}${r}`:"","wrap"),default:a((e,t="")=>e||t,"default")};function tl(e,t){let r=e;for(let n of t){let{name:o,args:a}=Mo(n),s=jo[o];if(s)r!==""&&(r=s(r));else {let l=Fo[o];l&&(r=l(r,...a));}}return r}a(tl,"applyPipes");function rl(e,t){return t.split(".").reduce((r,n)=>{if(!(r==null||typeof r!="object"))return r[n]},e)}a(rl,"getValue");var Vo="(Untitled)";function Mo(e){let t=e.match(/^(\w+)(?::(.*))?$/);if(!t)return {name:e,args:[]};let r=t[1],n=t[2];if(!n)return {name:r,args:[]};let o=[],a=/["']([^"']*?)["']/g,s;for(;(s=a.exec(n))!==null;)o.push(s[1]);return {name:r,args:o}}a(Mo,"parsePipeExpression");function Ar(e,t,r=Vo){return e.replace(/\{\{\s*([^}]+)\s*\}\}/g,(o,a)=>{let s=a.split("||").map(R=>R.trim()),c=s[s.length-1].split("|").map(R=>R.trim());s[s.length-1]=c[0];let f=c.slice(1).filter(Boolean),x=s.filter(Boolean),v="";for(let R of x){let X=Lo(rl(t,R));if(X!==""){v=X;break}}if(a$1(v)&&f.length===0)return "";for(let R of f){let{name:X,args:Xs}=Mo(R),$i=jo[X];if($i)v!==""&&(v=$i(v));else {let Ui=Fo[X];Ui&&(v=Ui(v,...Xs));}}return v}).trim()||r}a(Ar,"renderLabelExpression");function Lo(e){if(e==null||typeof e=="function")return "";if(typeof e!="object")return String(e);if(Array.isArray(e))return e.map(Lo).filter(Boolean).join(",");let t=e.toString;return typeof t=="function"&&t!==Object.prototype.toString?String(e):""}a(Lo,"toText");function gt(e){return /\{\{\s*\S+.*\}\}/.test(e)}a(gt,"isLabelExpression");function Bo(e){let t=[],r=/\{\{\s*([^}]+)\s*\}\}/g,n;for(;(n=r.exec(e))!==null;){let a=n[1].trim().split("||").map(l=>l.trim()),s=a[a.length-1];a[a.length-1]=s.split("|")[0].trim();for(let l of a){if(!l)continue;let c=l.split(".")[0];c&&!t.includes(c)&&t.push(c);}}return t}a(Bo,"extractAttributeNames");var nl=/^\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}$/;function $o(e){let t=e.trim().match(nl);return t?t[1]:null}a($o,"getSingleAttributeFromExpression");function il(e,t){let r=$o(e);if(r===null)return null;let n=t.find(o=>o.name===r);return !n||n.type!=="text"||j$1(n).authoring.readOnly?null:n}a(il,"getEditableLabelAttribute");var ol=/\{\{\s*props\./;function al(e,t,r){if(!ol.test(e))return e;let n={},o=new Map(r?.map(s=>[s.name,s]));if(t)for(let[s,l]of Object.entries(t)){if(l==null)continue;let c=o.get(s);if(c){let f=Po(l,c);n[s]=f===ft?"":f;}else n[s]=l;}return Ar(e,{props:n},"").replace(/\(\s*\)/g,"").replace(/\[\s*\]/g,"").replace(/\s*[-—|:]\s*$/g,"").replace(/\s{2,}/g," ").trim()}a(al,"applyRelationProps");function sl(e){if(e?.type==="relation")return e.properties?.definitions}a(sl,"relationPropertyDefs");function ul(e){if(e?.type==="relation"||e?.type==="document")return e.properties?.definitions}a(ul,"qualifiedPropertyDefs");function Uo(e){if(a$1(e))return [];if(typeof e=="string")return [{id:e}];if(Array.isArray(e))return e.flatMap(t=>Uo(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(Uo,"extractValueRefs");function ll(e){let t=[e.firstName,e.lastName].map(r=>r?.trim()).filter(Boolean).join(" ");return t!==""?t:e.email?.split("@")[0]??""}a(ll,"getUserDisplayName");var dl=/\p{L}|\p{N}/u;function cl(e,t){let r=e?.trim()??"";if(r==="")return t;let n=r.split(/\s+/),a=(n.length===1?r.split("@")[0].split(/[._-]/):n).map(s=>{let l=s.match(dl)?.[0];return l===void 0?"":[...l.toUpperCase()][0]??""}).filter(Boolean).slice(0,2).join("");return a===""?t:a}a(cl,"deriveInitials");var qo="__creatorRootActorId";function pl(e){let t=e.metadata?.[qo];return typeof t=="string"&&t.length>0?t:e.createdBy}a(pl,"getRecordCreatorPrincipalId");function Te(e,t){return e?.includes("*")===true||e?.includes(t)===true}a(Te,"includesAction");function ml(e){return {canRead:Te(e,"read"),canCreate:Te(e,"create"),canUpdate:Te(e,"update"),canDelete:Te(e,"delete"),canManage:Te(e,"manage")}}a(ml,"buildPermissionFlags");var uT=new Set(["id","name","label","type","required","system","unique","order"]);var $={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"},dT=[$.PEOPLE,$.WORKSPACE,$.ARCHITECT,$.FEATURE_FLAGS,$.FILES,$.VIEWS,$.FORMS,$.DOCUMENTS,$.AUDIT,$.API_KEYS,$.CONNECTORS,$.ENV_VARS,$.SESSION],cT={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"},fl={OWNER:"owner",MEMBER:"member",AGENT_DEFAULT:"agent_default",REFLEX_DEFAULT:"reflex_default"},pT={owner:"Owner",member:"Member",agent_default:"Agent Default",reflex_default:"Reflex Default"},mT={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"},Tr=["read","create","update","delete","manage"],bl=["read","create","update","delete"],zo=["read","create","update","delete"],fT={owner:{system:[{target:"*",actions:Tr}],object:[{target:"*",actions:Tr}]},member:{system:[{target:"people",actions:["read"]},{target:"workspace",actions:["read"]},{target:"connectors",actions:bl},{target:"files",actions:zo},{target:"documents",actions:zo}],object:[{target:"*",actions:Tr}]},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 bT(e){return Object.values(fl).includes(e)}a(bT,"isDefaultRole");var yl=new Set(ICONS),Wo=/^[a-zA-Z_][a-zA-Z0-9_]*$/,hl=/^[a-z][a-z0-9-]*$/,we=63,Go=128,yt=wr.string().min(1,"Object name cannot be empty").max(63,"Object name is too long (max 63 characters)").regex(/^[a-z][a-z0-9-]*$/,{message:`Invalid object name format.
|
|
3
3
|
Name must be in kebab-case (slug format):
|
|
4
4
|
\u2705 Valid: 'products', 'user-profiles', 'order-items'
|
|
5
|
-
\u274C Invalid: 'Products', 'userProfiles', 'user_profiles'`});function Le(e){try{yt.parse(e);}catch(t){throw t instanceof wr.ZodError?new b$1(t.issues[0].message,a$2.INVALID_OBJECT_NAME):t}}a(Le,"validateObjectName");function ht(e){if(!e||e.length===0)throw new h("View name cannot be empty",[{path:["name"],message:"View name cannot be empty"}]);if(e.length>we)throw new h("View name is too long",[{path:["name"],message:`View name is too long (max ${we} characters)`}]);if(!
|
|
5
|
+
\u274C Invalid: 'Products', 'userProfiles', 'user_profiles'`});function Le(e){try{yt.parse(e);}catch(t){throw t instanceof wr.ZodError?new b$1(t.issues[0].message,a$2.INVALID_OBJECT_NAME):t}}a(Le,"validateObjectName");function ht(e){if(!e||e.length===0)throw new h("View name cannot be empty",[{path:["name"],message:"View name cannot be empty"}]);if(e.length>we)throw new h("View name is too long",[{path:["name"],message:`View name is too long (max ${we} characters)`}]);if(!hl.test(e))throw new h("Invalid view name format",[{path:["name"],message:"View name must be in kebab-case (e.g., 'detail', 'list-view')"}])}a(ht,"validateViewName");function de(e,t,r){let n=new Set;for(let o of e){let a=t(o);if(n.has(a))throw r(a);n.add(a);}}a(de,"assertUniqueBy");var xr=wr.string().min(1,"Attribute name cannot be empty").max(we,`Attribute name is too long (max ${we} characters)`).regex(Wo,{message:`Invalid attribute name format.
|
|
6
6
|
Name must be a valid variable identifier:
|
|
7
7
|
\u2705 Valid: 'firstName', 'first_name', 'FirstName', 'FIRST_NAME'
|
|
8
|
-
\u274C Invalid: 'first-name', 'first name', '123name', 'first.name'`}).refine(e=>!B.includes(e),{message:"This is a reserved attribute name"});function Be(e){if(!e||e.length===0)throw new Error("[AttributeBuilder] Attribute name cannot be empty");if(e.length>we)throw new Error(`[AttributeBuilder] Attribute name is too long (max ${we} characters)`);if(!
|
|
8
|
+
\u274C Invalid: 'first-name', 'first name', '123name', 'first.name'`}).refine(e=>!B.includes(e),{message:"This is a reserved attribute name"});function Be(e){if(!e||e.length===0)throw new Error("[AttributeBuilder] Attribute name cannot be empty");if(e.length>we)throw new Error(`[AttributeBuilder] Attribute name is too long (max ${we} characters)`);if(!Wo.test(e))throw new Error(`[AttributeBuilder] Invalid attribute name format.
|
|
9
9
|
Name must be a valid variable identifier:
|
|
10
10
|
\u2705 Valid: 'firstName', 'first_name', 'FirstName', 'FIRST_NAME'
|
|
11
11
|
\u274C Invalid: 'first-name', 'first name', '123name', 'first.name'`);if(B.includes(e))throw new Error(`[AttributeBuilder] "${e}" is a reserved name and cannot be used as an attribute name.
|
|
12
|
-
Reserved names: ${B.join(", ")}`)}a(Be,"validateAttributeName");function
|
|
13
|
-
Icon must be one of the predefined icons from @stndrds/constants.`)}a(Ko,"validateIconName");function ce(e,t){let r=new Set;for(let n of t){if(!n.value?.trim())throw new Error(`[AttributeBuilder] Option in "${e}" has an empty or missing value.`);if(!n.label?.trim())throw new Error(`[AttributeBuilder] Option "${n.value}" in "${e}" has an empty or missing label.`);if(r.has(n.value))throw new Error(`[AttributeBuilder] Duplicate option value "${n.value}" in "${e}".`);r.add(n.value);}for(let n of t){if(n.inverse===void 0)continue;let o=t.find(a=>a.value===n.inverse);if(!o)throw new Error(`[AttributeBuilder] Option "${n.value}" in "${e}" has inverse "${n.inverse}" which does not match any option value.`);if(o.inverse!==n.value)throw new Error(`[AttributeBuilder] Inverse mismatch in "${e}": "${n.value}" points to "${n.inverse}", but "${n.inverse}" points to "${o.inverse??"(none)"}". Inverse pairs must be symmetric.`)}}a(ce,"validateOptions");var Ho={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2},timeoutMs:3e5},Sr=class Sr{constructor(t){if(!t.name||t.name.trim().length===0)throw new h("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,r,n){return this.bp.model={provider:t,model:r,...n},this}tools(t){return this.bp.tools=[...t],this}schedule(t){return this.bp.schedule={...t,enabled:t.enabled??true},this}config(t){let r=this.bp.config??Ho,n=t.inference===void 0?r.inference:{...r.inference,...t.inference};return this.bp.config={...r,...t,...n===void 0?{}:{inference:n}},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={...Ao,...this.bp.approval,...t},this}visibility(t){return this.bp.visibility=t,this}requiresPermission(t,r){return this.bp.requiredPermission={resource:t,action:r},this}trigger(t,r,n){return this.bp.triggers.push({name:t,eventType:r,...n,enabled:n?.enabled??true}),this}runtime(){return this.bp.system=false,this}build(){if(!this.bp.systemPrompt)throw new h(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new h(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility==="private")throw new h(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return de(this.bp.triggers,t=>t.name,t=>new h(`Agent "${this.bp.name}": duplicate trigger name "${t}"`,[])),{...this.bp,visibility:this.bp.visibility??"workspace",config:this.bp.config??Ho,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};a(Sr,"AgentBuilder");var Ir=Sr;function RT(e){return new Ir(e)}a(RT,"agent");var hl="@stndrds/schema";function At(e){return {version:1,vendor:hl,validate:a(t=>{let r=e.safeParse(t);return r.success?{value:r.data}:{issues:r.error.issues.map(n=>({message:n.message,path:n.path}))}},"validate")}}a(At,"createStandardSchemaProps");function CT(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"].version===1}a(CT,"isStandardSchema");var Ur=class Ur{get"~standard"(){let t=c$2(this.build());return At(t)}constructor(t,r,n){Be(r),Wo(n),this.attr={name:r,label:n,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 Ko(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(Ur,"BaseAttributeBuilder");var E=Ur,qr=class qr extends E{constructor(t,r){super("text",t,r);}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(qr,"TextAttributeBuilder");var vr=qr;function b(e){return new vr(e.name,e.label)}a(b,"text");var zr=class zr extends E{constructor(t,r){super("richtext",t,r);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(zr,"RichtextAttributeBuilder");var Rr=zr;function xe(e){return new Rr(e.name,e.label)}a(xe,"richtext");var Gr=class Gr extends E{constructor(t,r){super("number",t,r);}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(Gr,"NumberAttributeBuilder");var Dr=Gr;function wt(e){return new Dr(e.name,e.label)}a(wt,"number");var Wr=class Wr extends E{constructor(t,r){super("checkbox",t,r);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Wr,"CheckboxAttributeBuilder");var Er=Wr;function Yo(e){return new Er(e.name,e.label)}a(Yo,"checkbox");var Kr=class Kr extends E{constructor(t,r){super("date",t,r);}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(Kr,"DateAttributeBuilder");var Cr=Kr;function U(e){return new Cr(e.name,e.label)}a(U,"date");var Hr=class Hr extends E{constructor(t,r){super("phone",t,r);}defaultCountry(t){return this.attr.defaultCountryCode=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Hr,"PhoneAttributeBuilder");var Or=Hr;function MT(e){return new Or(e.name,e.label)}a(MT,"phone");var Yr=class Yr extends E{constructor(t,r){super("currency",t,r);}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(Yr,"CurrencyAttributeBuilder");var _r=Yr;function LT(e){return new _r(e.name,e.label)}a(LT,"currency");var Qr=class Qr extends E{constructor(t,r){super("status",t,r);}options(t){let r=t;return ce(this.attr.name??"unknown",r),this.attr.options=r,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let r=[...this.attr.options,t];return ce(this.attr.name??"unknown",r),this.attr.options.push(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Qr,"StatusAttributeBuilder");var Nr=Qr;function BT(e){return new Nr(e.name,e.label)}a(BT,"status");var Jr=class Jr extends E{constructor(t,r){super("select",t,r);}options(t){let r=t;return ce(this.attr.name??"unknown",r),this.attr.options=r,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let r=[...this.attr.options,t];return ce(this.attr.name??"unknown",r),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(Jr,"SelectAttributeBuilder");var kr=Jr;function K(e){return new kr(e.name,e.label)}a(K,"select");var Xr=class Xr extends E{constructor(t,r){super("multiselect",t,r);}options(t){let r=t;return ce(this.attr.name??"unknown",r),this.attr.options=r,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let r=[...this.attr.options,t];return ce(this.attr.name??"unknown",r),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(Xr,"MultiselectAttributeBuilder");var Pr=Xr;function $T(e){return new Pr(e.name,e.label)}a($T,"multiselect");var Zr=class Zr extends E{constructor(t,r){super("location",t,r);}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(Zr,"LocationAttributeBuilder");var jr=Zr;function UT(e){return new jr(e.name,e.label)}a(UT,"location");var en=class en extends E{constructor(t,r){super("user",t,r),this.attr.types=["user","agent"];}types(t){let r=[...new Set(t)];if(r.length===0)throw new Error("[AttributeBuilder] user.types must contain at least one type.");return this.attr.types=r,this}multiple(){return this.attr.multiple=true,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(en,"UserAttributeBuilder");var Fr=en;function qT(e){return new Fr(e.name,e.label)}a(qT,"user");var tn=class tn extends E{to(t,r){let n={object:t,...r};return this.attr.targets?.push(n),this}toAny(){return this.attr.targets=[{object:ee}],this}qualifyWith(...t){let r=this.attr.targets;if(!r||r.length===0)throw new Error('.qualifyWith() must be called AFTER .to(). Example: relation({ name: "companies" }).to("companies").qualifyWith(...)');return this.attr.properties=mt(t),this}bilateral(t){let r=this.attr.targets;if(!r||r.length===0)throw new Error('.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })');if(r.length>1)throw new Error("Bilateral relations are not supported for polymorphic relations (multiple .to() targets).");if(ho(this.attr))throw new Error("Bilateral relations are not supported for universal relations (.toAny()).");return this.attr.bilateral=t,this}};a(tn,"BaseRelationAttributeBuilder");var Tt=tn,rn=class rn extends Tt{constructor(t,r){super("relation",t,r),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(rn,"SingleRelationAttributeBuilder");var Vr=rn,nn=class nn extends Tt{constructor(t,r,n){super("relation",t,r),this.attr.cardinality="many",this.attr.targets=n?.targets??[],this.attr.defaultValue=[],n?.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(nn,"MultiRelationAttributeBuilder");var Mr=nn;function Ie(e){return new Vr(e.name,e.label)}a(Ie,"relation");var on=class on extends E{constructor(t,r){super("formula",t,r),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(on,"FormulaAttributeBuilder");var Lr=on;function zT(e){return new Lr(e.name,e.label)}a(zT,"formula");var an=class an extends E{constructor(t,r){super("rollup",t,r),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,r=this.attr.targetAttributeType;if(t==="original"&&r!==void 0&&r!=="select"&&r!=="status"&&r!=="multiselect"){let n=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("${r}") was given. To surface a plain ${r} value from a related record, use a formula instead \u2014 e.g. formula({ name: "${this.attr.name}", label: "\u2026" }).expression("${n}.${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(an,"RollupAttributeBuilder");var Br=an;function GT(e){return new Br(e.name,e.label)}a(GT,"rollup");var sn=class sn extends E{constructor(t,r){super("document",t,r);}accepts(t){return this.attr.accepts=t,this}maxFileSize(t){return this.attr.maxFileSize=t,this}qualifyWith(...t){return this.attr.properties=mt(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(sn,"DocumentAttributeBuilder");var $r=sn;function Qo(e){return new $r(e.name,e.label)}a(Qo,"document");function Xo(e,t,r){let n=Array.isArray(e)?e:[e],[o,...a]=n;return {type:"slot",slotId:o,additionalSlotIds:a.length>0?a:void 0,attribute:t,label:r?.label,required:r?.required,tooltip:r?.tooltip}}a(Xo,"buildSlotFieldRef");var cn=class cn{constructor(t,r,n){this._finalized=false;this.stepBuilder=t,this.rowData={id:r,order:n,type:"fields",fields:[]};}field(t,r,n){return this.rowData.fields.push(Xo(t,r,n)),this}freeField(t,r){let o={type:"free",attribute:t.build(),label:r?.label,required:r?.required,prefillExpression:r?.prefillExpression};return this.rowData.fields.push(o),this}row(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).row(t)}heading(t,r){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).heading(t,r)}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(cn,"FormRowBuilder");var un=cn,pn=class pn{constructor(t,r,n){this.rowOrder=0;this.formBuilder=t,this.stepData={id:r,label:n,rows:[]};}description(t){return this.stepData.description=t,this}field(t,r,n){this.rowOrder++;let o=`row-${this.stepData.id}-${this.rowOrder}`,a=Xo(t,r,n),s={id:o,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}freeField(t,r){this.rowOrder++;let n=`row-${this.stepData.id}-${this.rowOrder}`,a={type:"free",attribute:t.build(),label:r?.label,required:r?.required,prefillExpression:r?.prefillExpression},s={id:n,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}row(t){return this.rowOrder++,new un(this,t,this.rowOrder)}heading(t,r){this.rowOrder++;let n={id:`heading-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"heading",content:t,level:r};return this.stepData.rows.push(n),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 r={id:`text-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"text",content:t};return this.stepData.rows.push(r),this}step(t,r){return this.formBuilder._finalizeStep(this.stepData).step(t,r)}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(pn,"FormStepBuilder");var ln=pn,mn=class mn{constructor(t,r){this.data={slots:[],steps:[],status:"draft",version:1};this.validateName(t),this.data.name=t,this.data.label=r;}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,r,n){if(this.data.slots.some(a=>a.id===t))throw new Error(`[FormBuilder] Duplicate slot id: "${t}"`);let o={id:t,objectName:r,label:n.label,mode:n.mode??"create",color:n.color,icon:n.icon};return this.data.slots.push(o),this}step(t,r){if(this.data.steps.some(n=>n.id===t))throw new Error(`[FormBuilder] Duplicate step id: "${t}"`);return new ln(this,t,r)}build(){return this.validateRequiredData(),this.validateSlotReferences(),this.validateFreeFields(),this.validatePrefillExpressions(),this.data}_finalizeStep(t){return this.data.steps.push(t),this}validateName(t){let r=z$1.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{r.parse(t);}catch(n){throw n instanceof z$1.ZodError?new Error(`[FormBuilder] ${n.issues[0].message}`):n}}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(r=>[r.id,r.objectName]));for(let r of this.data.steps)for(let n of r.rows)if(ct(n))for(let o of n.fields){if(o.type!=="slot")continue;let a=Do(o);for(let l of a)if(!t.has(l))throw new Error(`[FormBuilder] Step "${r.id}" references unknown slot "${l}". Declare it with .slot("${l}", ...) first.`);let s=new Set(a.map(l=>t.get(l)));if(s.size>1)throw new Error(`[FormBuilder] Step "${r.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=[...bt,"join"];for(let r of this.data.steps)for(let n of r.rows)if(ct(n))for(let o of n.fields){if(!br(o)||!o.prefillExpression)continue;let a=o.prefillExpression,s=`prefillExpression on free field "${o.attribute.name}" in step "${r.id}"`;if(!gt(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 l of a.matchAll(/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g)){let c=l[1];if(!t.includes(c))throw new Error(`[FormBuilder] ${s} uses invalid pipe "${c}". Valid pipes: ${t.join(", ")}`)}}}validateFreeFields(){let t=new Set(fr);for(let r of this.data.steps)for(let n of r.rows)if(ct(n)){for(let o of n.fields)if(br(o)){let a=o.attribute.type;if(t.has(a))throw new Error(`[FormBuilder] Free field in step "${r.id}" uses forbidden attribute type "${a}". Forbidden types: ${fr.join(", ")}`)}}}};a(mn,"FormBuilder");var dn=mn;function XT(e,t){return new dn(e,t)}a(XT,"form");function Al(e){return {text:"toString",richtext:"toString",number:"toNumber",currency:"toNumber",date:"toDate",checkbox:"toBoolean"}[e]}a(Al,"resolveBuiltInTransform");var fn=class fn{constructor(t){this.operations=[];this.touchedAttributes=new Set;this.version=t;}assertNotTouched(t,r){if(this.touchedAttributes.has(t))throw new Error(`[MigrationBuilder] Conflicting operations on attribute "${t}": it was already modified earlier in this migration (attempted: ${r}).`)}renameAttribute(t,r){return this.assertNotTouched(t,"rename_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"rename_attribute",from:t,to:r}),this}changeType(t,r,n,o){this.assertNotTouched(t,"change_type"),this.touchedAttributes.add(t);let a=o?.transform?Al(n):void 0;return this.operations.push({type:"change_type",name:t,from:r,to:n,transform:a}),this}removeAttribute(t){return this.assertNotTouched(t,"remove_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"remove_attribute",name:t,backup_config:{}}),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,r){return this.assertNotTouched(t,"update_config"),this.touchedAttributes.add(t),this.operations.push({type:"update_config",name:t,from:{},to:r}),this}build(){return {version:this.version,operations:[...this.operations]}}};a(fn,"MigrationBuilder");var xt=fn;function Tl(e){let{name:t,labelExpression:r,embeddingExpression:n}=e;if(!r)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=Ae.safeParse(r);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(n!==void 0){let a=Ae.safeParse(n);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(Tl,"validateObjectExpressions");var bn=class bn{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 At(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 r$1=t.map(n=>"build"in n&&typeof n.build=="function"?n.build():n);de([...this.obj.attributes,...r$1],n=>n.name,n=>new r("attribute",n,`Object "${this.obj.name}": duplicate attribute name "${n}"`)),this.obj.attributes.push(...r$1);}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 r of t.presets)Zo(r.id,r.structure,1);return this.obj.documentLayout=t,this}migration(t,r){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 xt(t);return r(o),this._migrations.push(o.build()),this}build(){if(!this.obj.name)throw new h("[ObjectBuilder] Missing required field: name",[{path:["name"],message:"name is required"}]);if(!this.obj.label)throw new h("[ObjectBuilder] Missing required field: label",[{path:["label"],message:"label is required"}]);Tl({name:this.obj.name,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression});let t=[...this._migrations].sort((n,o)=>n.version-o.version);for(let n=0;n<t.length;n++){let o=n+2;if(t[n].version!==o)throw new Error(`[ObjectBuilder] Migration versions must be sequential starting at 2. Expected version ${o}, got ${t[n].version}.`)}let r=t.length>0?t[t.length-1].version:1;return {...this.obj,pluralLabel:this._pluralLabel,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression,schema_version:r,migrations:t,sealed:this._sealed,toleratedAttributes:this._toleratedAttributes}}validateName(t){t!==void 0&&Le(t);}};a(bn,"ObjectBuilder");var $e=bn;function dw(e){if(w$1(e.name))throw new s(e.name,"builder");return new $e(e)}a(dw,"object");function Zo(e,t,r){let n=a((a,s)=>{throw new h(a,[{path:["documentLayout","presets",e],message:s}])},"fail");r>5&&n(`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&&n("Folder preset node title is required","Empty folder title"),s.includes("/")&&n("Folder preset node title cannot contain /",`Folder title contains /: "${s}"`),o.has(s)&&n("Folder preset sibling titles must be unique",`Duplicate folder title: "${s}"`),o.add(s),a.children&&a.children.length>0&&Zo(e,a.children,r+1);}}a(Zo,"validatePresetStructure");var vn=class vn{constructor(t,r){this.data={type:"fields",fields:[]};this.data.id=t,this.data.label=r;}description(t){return this.data.description=t,this}collapsible(t=false){return this.data.collapsible=true,this.data.collapsed=t,this}order(t){return this.data.order=t,this}fields(...t){for(let r of t)this.data.fields?.push({attribute:r});return this}field(t,r){return this.data.fields?.push({attribute:t,...r}),this}attributeGroup(t,r){return this.data.fields?.push({attributeGroup:t,...r}),this}build(){if(!this.data.id)throw new Error("[GroupBuilder] id is required");if(!this.data.label)throw new Error("[GroupBuilder] label is required");if(!this.data.fields||this.data.fields.length===0)throw new Error("[GroupBuilder] At least one field is required");return this.data}};a(vn,"GroupBuilder");var St=vn,Rn=class Rn{constructor(t,r){this.view=t,this.tabData=r;}columns(...t){return this.tabData.columns=t,this}create(t){return this.tabData.allowCreate=true,t?.mode&&(this.tabData.createMode=t.mode),this}createMode(t){return this.tabData.createMode=t,this}openMode(t){return this.tabData.openMode=t,this}edit(){return this.tabData.allowEdit=true,this}delete(){return this.tabData.allowDelete=true,this}crud(){return this.tabData.allowCreate=true,this.tabData.allowEdit=true,this.tabData.allowDelete=true,this}filters(t){return this.tabData.filters=t,this}sorts(t){return this.tabData.sorts=t,this}sort(t,r="asc"){return this.tabData.sorts||(this.tabData.sorts=[]),this.tabData.sorts.push({attribute:t,direction:r}),this}tab(t,r){return this.finalize(),new te(this.view,t,r)}done(){return this.finalize(),this.view}build(){return this.finalize(),this.view.build()}finalize(){if(!this.tabData.columns||this.tabData.columns.length===0)throw new Error(`[TableTabConfig] columns() is required for tab "${this.tabData.name}"`);this.view._addTab(this.tabData);}};a(Rn,"TableTabConfig");var vt=Rn,Dn=class Dn{constructor(t,r,n){this.view=t,this.tabData={...r,type:"custom",component:n};}props(t){return this.tabData.props=t,this}tab(t,r){return this.view._addTab(this.tabData),new te(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(Dn,"CustomTabConfig");var gn=Dn,En=class En{constructor(t,r,n){this.view=t,this.tabData={...r,type:"richtext",attribute:n};}titleAttribute(t){return this.tabData.titleAttribute=t,this}tab(t,r){return this.view._addTab(this.tabData),new te(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(En,"RichtextTabConfig");var yn=En,Cn=class Cn{constructor(t,r){this.view=t,this.tabData={...r,type:"activity"};}limit(t){return this.tabData.limit=t,this}tab(t,r){return this.view._addTab(this.tabData),new te(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(Cn,"ActivityTabConfig");var hn=Cn,On=class On{constructor(t,r,n){this.view=t,this.tabData={...r,type:n,emailAttributeIds:[]};}emailAttributes(...t){return this.tabData.emailAttributeIds=t,this}tab(t,r){return this.view._addTab(this.tabData),new te(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(On,"AddressMatchedTabConfig");var Rt=On,_n=class _n extends Rt{constructor(t,r){super(t,r,"emails");}};a(_n,"EmailsTabConfig");var An=_n,Nn=class Nn extends Rt{constructor(t,r){super(t,r,"meetings");}};a(Nn,"MeetingsTabConfig");var Tn=Nn,kn=class kn{constructor(t,r){this.view=t,this.tabData={...r,type:"documents",allowUpload:true,allowRemove:true,hideAttachments:false};}disableUpload(){return this.tabData.allowUpload=false,this}disableRemove(){return this.tabData.allowRemove=false,this}hideAttachments(){return this.tabData.hideAttachments=true,this}from(...t){return this.tabData.relations=[...this.tabData.relations??[],...t],this}tab(t,r){return this.view._addTab(this.tabData),new te(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(kn,"DocumentsTabConfig");var wn=kn,Pn=class Pn{constructor(t,r,n){this.view=t,this.base={id:r,name:r,label:n};}icon(t){return this.base.icon=t,this}order(t){return this.base.order=t,this}form(...t){if(t.length===0)throw new Error(`[TabBuilder] form() requires at least one group for tab "${this.base.name}"`);let r={...this.base,type:"form",groups:t.map(n=>n instanceof St?n.build():n)};return this.view._addTab(r)}table(t){return new vt(this.view,{...this.base,type:"table",source:{type:"relation",attribute:t},columns:[]})}tableFrom(t,r){return new vt(this.view,{...this.base,type:"table",source:{type:"inverse",object:t,attribute:r},columns:[]})}custom(t){return new gn(this.view,this.base,t)}richtext(t){return new yn(this.view,this.base,t)}activity(){return new hn(this.view,this.base)}documents(){return new wn(this.view,this.base)}emails(){return new An(this.view,this.base)}meetings(){return new Tn(this.view,this.base)}forms(t){let r={...this.base,type:"forms",...t};return this.view._addTab(r)}};a(Pn,"TabBuilder");var te=Pn,jn=class jn{constructor(t,r){ht(t),this.data={name:t,label:r,tabs:[]};}description(t){return this.data.description=t,this}icon(t){return this.data.icon=t,this}for(t){return this.data.object=t,this}default(){return this.data.default=true,this}metadata(t){return this.data.metadata=t,this}sidePanel(t){return this.data.sidePanel=t,this}readOnly(){return this.data.readOnly=true,this}tab(t,r){return new te(this,t,r)}addTab(t){return this.data.tabs.push(t),this}_addTab(t){return this.data.tabs.push(t),this}build(){if(!this.data.object)throw new Error("[DetailViewBuilder] for() is required - specify the target object");if(this.data.tabs.length===0)throw new Error("[DetailViewBuilder] At least one tab is required");de(this.data.tabs,r=>r.name,r=>new Error(`[DetailViewBuilder] Duplicate tab name "${r}"`));let t={tabs:this.data.tabs,sidePanel:this.data.sidePanel,...this.data.readOnly?{readOnly:true}:{}};return {name:this.data.name,label:this.data.label,description:this.data.description,icon:this.data.icon,object:this.data.object,type:"detail",config:t,default:this.data.default,metadata:this.data.metadata}}};a(jn,"DetailViewBuilder");var xn=jn;function H(e,t){return new xn(e,t)}a(H,"detailView");function It(e){if(Array.isArray(e))return e.map(It).find(r=>r!==void 0);if(e===null||typeof e!="object")return;let t=e;return t.attribute==="visibility"||t.attribute==="ownedBy"?t.attribute:It(t.rules)??It(t.groups)}a(It,"findProtectedTabFilterAttribute");var Fn=class Fn{constructor(t,r){ht(t),this.data={name:t,label:r,tabs:[]};}description(t){return this.data.description=t,this}icon(t){return this.data.icon=t,this}for(t){return this.data.object=t,this}default(){return this.data.default=true,this}metadata(t){return this.data.metadata=t,this}baseFilter(t){return this.data.defaultFilters=t,this}allowPresentationCustomization(){return this.data.allowPresentationCustomization=true,this}tab(t,r){return new Sn(this,t,r)}_addTab(t){return this.data.tabs.push(t),this}build(){if(!this.data.object)throw new Error("[ListViewBuilder] for() is required - specify the target object");if(this.data.tabs.length===0)throw new Error("[ListViewBuilder] At least one tab is required");if(de(this.data.tabs,n=>n.id,n=>new Error(`[ListViewBuilder] Duplicate tab id "${n}"`)),this.data.tabs.filter(n=>n.default).length>1)throw new Error("[ListViewBuilder] Only one tab can be marked as default");for(let n of this.data.tabs){if(n.layout==="table"&&n.columns.length===0)throw new h(`[ListViewBuilder] Tab "${n.id}" must have at least one column`,[]);if(n.layout==="kanban"&&!n.groupByAttribute)throw new h(`[ListViewBuilder] Kanban tab "${n.id}" requires a groupByAttribute`,[]);if(n.descriptionAttribute!==void 0&&n.descriptionAttribute.length===0)throw new h(`[ListViewBuilder] Tab "${n.id}" requires a nonempty description attribute name`,[]);if(n.displayAttributes!==void 0){let o=_$1.safeParse(n.displayAttributes);if(!o.success)throw new h(`[ListViewBuilder] Tab "${n.id}" has invalid display attributes`,o.error.issues.map(a=>({path:["tabs",n.id,"displayAttributes",...a.path.map(String)],message:a.message})))}}let r={allowPresentationCustomization:this.data.allowPresentationCustomization,defaultFilters:this.data.defaultFilters?{id:h$1(),combinator:this.data.defaultFilters.combinator,rules:this.data.defaultFilters.rules}:void 0,tabs:this.data.tabs.map(n=>{let o={id:n.id,label:n.label,icon:n.icon,default:n.default,visibility:n.visibility,columns:n.columns,descriptionAttribute:n.descriptionAttribute,displayAttributes:n.displayAttributes,filters:n.filters?{id:h$1(),combinator:n.filters.combinator,rules:n.filters.rules}:void 0,sorts:n.sorts,readOnly:n.readOnly,createMode:n.createMode,openMode:n.openMode};return n.layout==="kanban"?{...o,layout:"kanban",groupByAttribute:n.groupByAttribute,cardUserAttribute:n.cardUserAttribute,cardDateAttribute:n.cardDateAttribute,kanbanColumnOrder:n.kanbanColumnOrder,kanbanColumnVisibility:n.kanbanColumnVisibility,kanbanPinnedColumns:n.kanbanPinnedColumns}:{...o,layout:n.layout,columnSizing:n.columnSizing}})};return {name:this.data.name,label:this.data.label,description:this.data.description,icon:this.data.icon,object:this.data.object,type:"list",config:r,default:this.data.default,metadata:this.data.metadata}}};a(Fn,"ListViewBuilder");var In=Fn,Dt=class Dt{constructor(t,r,n){this.view=t,this.tabData={id:r,label:n,visibility:"all",layout:"table",columns:[]};}icon(t){return this.tabData.icon=t,this}default(){return this.tabData.default=true,this}readOnly(){return this.tabData.readOnly=true,this}visibility(t){return this.tabData.visibility=t,this}table(){return this.tabData.layout="table",this}list(){return this.tabData.layout="list",this}descriptionAttribute(t){return this.tabData.descriptionAttribute=t,this}displayAttributes(...t){return this.tabData.displayAttributes=t,this}kanban(t){return this.tabData.layout="kanban",this.tabData.groupByAttribute=t,this}cardUserAttribute(t){return this.tabData.cardUserAttribute=t,this}cardDateAttribute(t){return this.tabData.cardDateAttribute=t,this}kanbanColumnOrder(t){return this.tabData.kanbanColumnOrder=t,this}kanbanColumnVisibility(t){return this.tabData.kanbanColumnVisibility=t,this}kanbanPinnedColumns(t){return this.tabData.kanbanPinnedColumns=t,this}createMode(t){return this.tabData.createMode=t,this}openMode(t){return this.tabData.openMode=t,this}columns(...t){return this.tabData.columns=t,this}columnWidth(t,r){return this.tabData.columnSizing||(this.tabData.columnSizing={}),this.tabData.columnSizing[t]=r,this}filter(t){let r=It(t);if(r){let n=`Tab filters cannot target "${r}". Use .visibility("private")`;throw new h(n,[{path:["filters"],message:n}])}return this.tabData.filters=t,this}sort(t,r="asc"){return this.tabData.sorts||(this.tabData.sorts=[]),this.tabData.sorts.push({attribute:t,direction:r}),this}sorts(t){return this.tabData.sorts=t,this}tab(t,r){return this.view._addTab(this.tabData),new Dt(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(Dt,"ListViewTabConfigBuilder");var Sn=Dt;function Y(e,t){return new In(e,t)}a(Y,"listView");function yw(e,t){return new St(e,t)}a(yw,"group");function wl(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(wl,"validateFlagName");var $n=class $n{constructor(t,r,n){wl(t),this.flag={name:t,valueType:r,defaultValue:n,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($n,"BaseFlagBuilder");var Se=$n,Un=class Un extends Se{constructor(t){super(t,"boolean",false);}defaultValue(t){return this.flag.defaultValue=t,this}enabledByDefault(){return this.flag.defaultValue=true,this}};a(Un,"BooleanFlagBuilder");var Vn=Un,qn=class qn extends Se{constructor(t){super(t,"string","");}defaultValue(t){return this.flag.defaultValue=t,this}};a(qn,"StringFlagBuilder");var Mn=qn,zn=class zn extends Se{constructor(t){super(t,"number",0);}defaultValue(t){return this.flag.defaultValue=t,this}};a(zn,"NumberFlagBuilder");var Ln=zn,Gn=class Gn extends Se{constructor(t,r){super(t,"json",r);}defaultValue(t){return this.flag.defaultValue=t,this}};a(Gn,"JsonFlagBuilder");var Bn=Gn;function xl(e){return new Vn(e)}a(xl,"booleanFlag");function Il(e){return new Mn(e)}a(Il,"stringFlag");function Sl(e){return new Ln(e)}a(Sl,"numberFlag");function vl(e,t){return new Bn(e,t)}a(vl,"jsonFlag");function Wn(e){return new r("feature flag",e,`Flag "${e}" is already registered. Each flag name must be unique.`)}a(Wn,"duplicateFlagError");function Kn(e){return {...e,allowedLevels:[...e.allowedLevels]}}a(Kn,"cloneFlagDefinition");var Hn=class Hn{constructor(){this.flags=new Map;}register(t){if(this.flags.has(t.name))throw Wn(t.name);this.flags.set(t.name,Kn(t));}registerAll(t){let r=new Set;for(let n of t){if(this.flags.has(n.name)||r.has(n.name))throw Wn(n.name);r.add(n.name);}for(let n of t)this.register(n);}get(t){let r=this.flags.get(t);return r?Kn(r):void 0}getOrThrow(t){let r=this.get(t);if(!r)throw new c$3("Feature flag",t,void 0,`Flag "${t}" is not registered. Available flags: ${this.listNames().join(", ")}`);return r}has(t){return this.flags.has(t)}list(){return Array.from(this.flags.values(),Kn)}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(Hn,"FlagRegistry");var Ue=Hn,Rl=new Ue;function Dl(){return new Ue}a(Dl,"createFlagRegistry");function Et(){return {global:new Map,tenant:new Map,user:new Map}}a(Et,"emptyOverrides");function El(e,t){return e.expiresAt===void 0||e.expiresAt.getTime()>t}a(El,"isActiveOverride");function Yn(e,t){let r=new Map;for(let n of e){if(!El(n,t))continue;let o=n.flagName;r.has(o)||r.set(o,n);}return r}a(Yn,"indexOverrides");var Qn=class Qn{constructor(t){this.repository=t.repository,this.registry=t.registry,this.staticDefaults=new Map(t.staticDefaults?.map(r=>[r.name,r.value])??[]);}async resolveAll(t={}){let r=this.collectFlagNames(),n=this.repository&&r.size>0?await this.getAllOverrides(t,[...r]):Et();return this.resolveNames(r,n,t)}resolveAllStatic(){return this.resolveNames(this.collectFlagNames(),Et(),{})}collectFlagNames(){let t=new Set;for(let r of this.registry.listNames())t.add(r);for(let r of this.staticDefaults.keys())t.add(r);return t}resolveNames(t,r,n){let o=new Map;for(let a of t)o.set(a,this.resolveValue(a,r,n));return o}async resolve(t,r={}){let n=this.repository?await this.getAllOverrides(r,[t]):Et();return this.resolveWithSource(t,n,r)}async isEnabled(t,r={}){return (await this.resolve(t,r)).value===true}async getValue(t,r={}){return (await this.resolve(t,r)).value}async setOverride(t,r,n,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(r)){let s=`Flag "${t}" does not allow ${r}-level overrides. Allowed levels: ${a.allowedLevels.join(", ")}`;throw new h(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(s,[{path:["flagName"],message:s}])}await this.repository.setOverride({flagName:t,level:r,value:n,targetId:o.targetId,expiresAt:o.expiresAt,createdBy:o.createdBy});}async deleteOverride(t,r,n){if(!this.repository)throw new b$1("Cannot delete override: no FeatureFlagsRepository configured.",a$2.CONFIGURATION_REQUIRED);await this.repository.deleteOverride(t,r,n);}async getAllOverrides(t,r){if(!this.repository)return Et();let[n,o,a]=await Promise.all([this.repository.getOverrides({level:"global",flagNames:r}),t.tenantId?this.repository.getOverrides({level:"tenant",targetId:t.tenantId,flagNames:r}):Promise.resolve([]),t.userId?this.repository.getOverrides({level:"user",targetId:t.userId,flagNames:r}):Promise.resolve([])]),s=Date.now();return {global:Yn(n,s),tenant:Yn(o,s),user:Yn(a,s)}}resolveValue(t,r,n){return this.resolveWithSource(t,r,n).value}resolveWithSource(t,r,n){let o=this.registry.get(t),a=o?.allowedLevels??["global","tenant","user"];if(n.userId&&a.includes("user")){let s=r.user.get(t);if(s)return {name:t,value:s.value,source:"user",sourceId:n.userId}}if(n.tenantId&&a.includes("tenant")){let s=r.tenant.get(t);if(s)return {name:t,value:s.value,source:"tenant",sourceId:n.tenantId}}if(a.includes("global")){let s=r.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(Qn,"FlagService");var Ct=Qn;function Cl(e){return new Ct(e)}a(Cl,"createFlagService");var ea=Symbol("stndrds.native-object");function Xn(e){return Object.defineProperty(e,ea,{value:true,enumerable:false}),e}a(Xn,"markNativeDefinition");var ei=class ei extends $e{build(){return Xn(super.build())}};a(ei,"NativeObjectBuilder");var Jn=ei;function Q(e){return new Jn(e)}a(Q,"nativeObject");function Zn(e){return e[ea]===true}a(Zn,"isNativeDefinition");function ti(e){let t=structuredClone(e);return Zn(e)?Xn(t):t}a(ti,"cloneObjectDefinition");var ni=class ni{constructor(){this.objects=new Map;}register(t){let n=(Array.isArray(t)?t:[t]).map(a=>"build"in a&&typeof a.build=="function"?a.build():a),o=new Set;for(let a of n){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 n)this.objects.set(a.name,ti(a));return this}validate(t){if(!t.system){let r=`[NativeObjectRegistry] Cannot register object "${t.name}" (id: ${t.id}): missing system flag.
|
|
12
|
+
Reserved names: ${B.join(", ")}`)}a(Be,"validateAttributeName");function Ko(e){if(!e||e.length===0)throw new Error("[AttributeBuilder] Attribute label cannot be empty");if(e.length>Go)throw new Error(`[AttributeBuilder] Attribute label is too long (max ${Go} characters)`)}a(Ko,"validateLabel");function Ho(e,t){if(!yl.has(e))throw new Error(`[AttributeBuilder] Invalid icon "${e}" in ${t}.
|
|
13
|
+
Icon must be one of the predefined icons from @stndrds/constants.`)}a(Ho,"validateIconName");function ce(e,t){let r=new Set;for(let n of t){if(!n.value?.trim())throw new Error(`[AttributeBuilder] Option in "${e}" has an empty or missing value.`);if(!n.label?.trim())throw new Error(`[AttributeBuilder] Option "${n.value}" in "${e}" has an empty or missing label.`);if(r.has(n.value))throw new Error(`[AttributeBuilder] Duplicate option value "${n.value}" in "${e}".`);r.add(n.value);}for(let n of t){if(n.inverse===void 0)continue;let o=t.find(a=>a.value===n.inverse);if(!o)throw new Error(`[AttributeBuilder] Option "${n.value}" in "${e}" has inverse "${n.inverse}" which does not match any option value.`);if(o.inverse!==n.value)throw new Error(`[AttributeBuilder] Inverse mismatch in "${e}": "${n.value}" points to "${n.inverse}", but "${n.inverse}" points to "${o.inverse??"(none)"}". Inverse pairs must be symmetric.`)}}a(ce,"validateOptions");var Yo={maxConcurrentRuns:3,retryPolicy:{maxRetries:3,backoffMs:1e3,backoffMultiplier:2},timeoutMs:3e5},Sr=class Sr{constructor(t){if(!t.name||t.name.trim().length===0)throw new h("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,r,n){return this.bp.model={provider:t,model:r,...n},this}tools(t){return this.bp.tools=[...t],this}schedule(t){return this.bp.schedule={...t,enabled:t.enabled??true},this}config(t){let r=this.bp.config??Yo,n=t.inference===void 0?r.inference:{...r.inference,...t.inference};return this.bp.config={...r,...t,...n===void 0?{}:{inference:n}},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={...Ao,...this.bp.approval,...t},this}visibility(t){return this.bp.visibility=t,this}requiresPermission(t,r){return this.bp.requiredPermission={resource:t,action:r},this}trigger(t,r,n){return this.bp.triggers.push({name:t,eventType:r,...n,enabled:n?.enabled??true}),this}runtime(){return this.bp.system=false,this}build(){if(!this.bp.systemPrompt)throw new h(`Agent "${this.bp.name}": systemPrompt is required`,[]);if(!this.bp.model)throw new h(`Agent "${this.bp.name}": model is required`,[]);if(this.bp.system&&this.bp.visibility==="private")throw new h(`Agent "${this.bp.name}": system agents must use workspace visibility`,[]);return de(this.bp.triggers,t=>t.name,t=>new h(`Agent "${this.bp.name}": duplicate trigger name "${t}"`,[])),{...this.bp,visibility:this.bp.visibility??"workspace",config:this.bp.config??Yo,systemPrompt:this.bp.systemPrompt,model:this.bp.model}}};a(Sr,"AgentBuilder");var Ir=Sr;function DT(e){return new Ir(e)}a(DT,"agent");var Al="@stndrds/schema";function At(e){return {version:1,vendor:Al,validate:a(t=>{let r=e.safeParse(t);return r.success?{value:r.data}:{issues:r.error.issues.map(n=>({message:n.message,path:n.path}))}},"validate")}}a(At,"createStandardSchemaProps");function OT(e){return typeof e=="object"&&e!==null&&"~standard"in e&&typeof e["~standard"]=="object"&&e["~standard"].version===1}a(OT,"isStandardSchema");var Ur=class Ur{get"~standard"(){let t=c$2(this.build());return At(t)}constructor(t,r,n){Be(r),Ko(n),this.attr={name:r,label:n,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 Ho(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(Ur,"BaseAttributeBuilder");var E=Ur,qr=class qr extends E{constructor(t,r){super("text",t,r);}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(qr,"TextAttributeBuilder");var vr=qr;function b(e){return new vr(e.name,e.label)}a(b,"text");var zr=class zr extends E{constructor(t,r){super("richtext",t,r);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(zr,"RichtextAttributeBuilder");var Rr=zr;function xe(e){return new Rr(e.name,e.label)}a(xe,"richtext");var Gr=class Gr extends E{constructor(t,r){super("number",t,r);}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(Gr,"NumberAttributeBuilder");var Dr=Gr;function wt(e){return new Dr(e.name,e.label)}a(wt,"number");var Wr=class Wr extends E{constructor(t,r){super("checkbox",t,r);}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Wr,"CheckboxAttributeBuilder");var Er=Wr;function Qo(e){return new Er(e.name,e.label)}a(Qo,"checkbox");var Kr=class Kr extends E{constructor(t,r){super("date",t,r);}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(Kr,"DateAttributeBuilder");var Cr=Kr;function U(e){return new Cr(e.name,e.label)}a(U,"date");var Hr=class Hr extends E{constructor(t,r){super("phone",t,r);}defaultCountry(t){return this.attr.defaultCountryCode=t,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Hr,"PhoneAttributeBuilder");var Or=Hr;function LT(e){return new Or(e.name,e.label)}a(LT,"phone");var Yr=class Yr extends E{constructor(t,r){super("currency",t,r);}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(Yr,"CurrencyAttributeBuilder");var _r=Yr;function BT(e){return new _r(e.name,e.label)}a(BT,"currency");var Qr=class Qr extends E{constructor(t,r){super("status",t,r);}options(t){let r=t;return ce(this.attr.name??"unknown",r),this.attr.options=r,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let r=[...this.attr.options,t];return ce(this.attr.name??"unknown",r),this.attr.options.push(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(Qr,"StatusAttributeBuilder");var Nr=Qr;function $T(e){return new Nr(e.name,e.label)}a($T,"status");var Jr=class Jr extends E{constructor(t,r){super("select",t,r);}options(t){let r=t;return ce(this.attr.name??"unknown",r),this.attr.options=r,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let r=[...this.attr.options,t];return ce(this.attr.name??"unknown",r),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(Jr,"SelectAttributeBuilder");var kr=Jr;function K(e){return new kr(e.name,e.label)}a(K,"select");var Xr=class Xr extends E{constructor(t,r){super("multiselect",t,r);}options(t){let r=t;return ce(this.attr.name??"unknown",r),this.attr.options=r,this.asPhantomState()}option(t){this.attr.options||(this.attr.options=[]);let r=[...this.attr.options,t];return ce(this.attr.name??"unknown",r),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(Xr,"MultiselectAttributeBuilder");var Pr=Xr;function UT(e){return new Pr(e.name,e.label)}a(UT,"multiselect");var Zr=class Zr extends E{constructor(t,r){super("location",t,r);}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(Zr,"LocationAttributeBuilder");var jr=Zr;function qT(e){return new jr(e.name,e.label)}a(qT,"location");var en=class en extends E{constructor(t,r){super("user",t,r),this.attr.types=["user","agent"];}types(t){let r=[...new Set(t)];if(r.length===0)throw new Error("[AttributeBuilder] user.types must contain at least one type.");return this.attr.types=r,this}multiple(){return this.attr.multiple=true,this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(en,"UserAttributeBuilder");var Fr=en;function zT(e){return new Fr(e.name,e.label)}a(zT,"user");var tn=class tn extends E{to(t,r){let n={object:t,...r};return this.attr.targets?.push(n),this}toAny(){return this.attr.targets=[{object:ee}],this}qualifyWith(...t){let r=this.attr.targets;if(!r||r.length===0)throw new Error('.qualifyWith() must be called AFTER .to(). Example: relation({ name: "companies" }).to("companies").qualifyWith(...)');return this.attr.properties=mt(t),this}bilateral(t){let r=this.attr.targets;if(!r||r.length===0)throw new Error('.bilateral() must be called AFTER .to(). Example: relation({ name: "company" }).to("companies").bilateral({ ... })');if(r.length>1)throw new Error("Bilateral relations are not supported for polymorphic relations (multiple .to() targets).");if(ho(this.attr))throw new Error("Bilateral relations are not supported for universal relations (.toAny()).");return this.attr.bilateral=t,this}};a(tn,"BaseRelationAttributeBuilder");var Tt=tn,rn=class rn extends Tt{constructor(t,r){super("relation",t,r),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(rn,"SingleRelationAttributeBuilder");var Vr=rn,nn=class nn extends Tt{constructor(t,r,n){super("relation",t,r),this.attr.cardinality="many",this.attr.targets=n?.targets??[],this.attr.defaultValue=[],n?.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(nn,"MultiRelationAttributeBuilder");var Mr=nn;function Ie(e){return new Vr(e.name,e.label)}a(Ie,"relation");var on=class on extends E{constructor(t,r){super("formula",t,r),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(on,"FormulaAttributeBuilder");var Lr=on;function GT(e){return new Lr(e.name,e.label)}a(GT,"formula");var an=class an extends E{constructor(t,r){super("rollup",t,r),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,r=this.attr.targetAttributeType;if(t==="original"&&r!==void 0&&r!=="select"&&r!=="status"&&r!=="multiselect"){let n=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("${r}") was given. To surface a plain ${r} value from a related record, use a formula instead \u2014 e.g. formula({ name: "${this.attr.name}", label: "\u2026" }).expression("${n}.${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(an,"RollupAttributeBuilder");var Br=an;function WT(e){return new Br(e.name,e.label)}a(WT,"rollup");var sn=class sn extends E{constructor(t,r){super("document",t,r);}accepts(t){return this.attr.accepts=t,this}maxFileSize(t){return this.attr.maxFileSize=t,this}qualifyWith(...t){return this.attr.properties=mt(t),this}required(){return this.setRequired(true),this.asRequiredState()}optional(){return this.setRequired(false),this.asRequiredState()}};a(sn,"DocumentAttributeBuilder");var $r=sn;function Jo(e){return new $r(e.name,e.label)}a(Jo,"document");function Zo(e,t,r){let n=Array.isArray(e)?e:[e],[o,...a]=n;return {type:"slot",slotId:o,additionalSlotIds:a.length>0?a:void 0,attribute:t,label:r?.label,required:r?.required,tooltip:r?.tooltip}}a(Zo,"buildSlotFieldRef");var cn=class cn{constructor(t,r,n){this._finalized=false;this.stepBuilder=t,this.rowData={id:r,order:n,type:"fields",fields:[]};}field(t,r,n){return this.rowData.fields.push(Zo(t,r,n)),this}freeField(t,r){let o={type:"free",attribute:t.build(),label:r?.label,required:r?.required,prefillExpression:r?.prefillExpression};return this.rowData.fields.push(o),this}row(t){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).row(t)}heading(t,r){return this._finalized=true,this.stepBuilder._finalizeRow(this.rowData).heading(t,r)}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(cn,"FormRowBuilder");var un=cn,pn=class pn{constructor(t,r,n){this.rowOrder=0;this.formBuilder=t,this.stepData={id:r,label:n,rows:[]};}description(t){return this.stepData.description=t,this}field(t,r,n){this.rowOrder++;let o=`row-${this.stepData.id}-${this.rowOrder}`,a=Zo(t,r,n),s={id:o,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}freeField(t,r){this.rowOrder++;let n=`row-${this.stepData.id}-${this.rowOrder}`,a={type:"free",attribute:t.build(),label:r?.label,required:r?.required,prefillExpression:r?.prefillExpression},s={id:n,order:this.rowOrder,type:"fields",fields:[a]};return this.stepData.rows.push(s),this}row(t){return this.rowOrder++,new un(this,t,this.rowOrder)}heading(t,r){this.rowOrder++;let n={id:`heading-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"heading",content:t,level:r};return this.stepData.rows.push(n),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 r={id:`text-${this.stepData.id}-${this.rowOrder}`,order:this.rowOrder,type:"text",content:t};return this.stepData.rows.push(r),this}step(t,r){return this.formBuilder._finalizeStep(this.stepData).step(t,r)}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(pn,"FormStepBuilder");var ln=pn,mn=class mn{constructor(t,r){this.data={slots:[],steps:[],status:"draft",version:1};this.validateName(t),this.data.name=t,this.data.label=r;}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,r,n){if(this.data.slots.some(a=>a.id===t))throw new Error(`[FormBuilder] Duplicate slot id: "${t}"`);let o={id:t,objectName:r,label:n.label,mode:n.mode??"create",color:n.color,icon:n.icon};return this.data.slots.push(o),this}step(t,r){if(this.data.steps.some(n=>n.id===t))throw new Error(`[FormBuilder] Duplicate step id: "${t}"`);return new ln(this,t,r)}build(){return this.validateRequiredData(),this.validateSlotReferences(),this.validateFreeFields(),this.validatePrefillExpressions(),this.data}_finalizeStep(t){return this.data.steps.push(t),this}validateName(t){let r=z$1.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{r.parse(t);}catch(n){throw n instanceof z$1.ZodError?new Error(`[FormBuilder] ${n.issues[0].message}`):n}}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(r=>[r.id,r.objectName]));for(let r of this.data.steps)for(let n of r.rows)if(ct(n))for(let o of n.fields){if(o.type!=="slot")continue;let a=Do(o);for(let l of a)if(!t.has(l))throw new Error(`[FormBuilder] Step "${r.id}" references unknown slot "${l}". Declare it with .slot("${l}", ...) first.`);let s=new Set(a.map(l=>t.get(l)));if(s.size>1)throw new Error(`[FormBuilder] Step "${r.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=[...bt,"join"];for(let r of this.data.steps)for(let n of r.rows)if(ct(n))for(let o of n.fields){if(!br(o)||!o.prefillExpression)continue;let a=o.prefillExpression,s=`prefillExpression on free field "${o.attribute.name}" in step "${r.id}"`;if(!gt(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 l of a.matchAll(/(?<!\|)\|(?!\|)\s*(\w+)(?::[^|}]*)?/g)){let c=l[1];if(!t.includes(c))throw new Error(`[FormBuilder] ${s} uses invalid pipe "${c}". Valid pipes: ${t.join(", ")}`)}}}validateFreeFields(){let t=new Set(fr);for(let r of this.data.steps)for(let n of r.rows)if(ct(n)){for(let o of n.fields)if(br(o)){let a=o.attribute.type;if(t.has(a))throw new Error(`[FormBuilder] Free field in step "${r.id}" uses forbidden attribute type "${a}". Forbidden types: ${fr.join(", ")}`)}}}};a(mn,"FormBuilder");var dn=mn;function ZT(e,t){return new dn(e,t)}a(ZT,"form");function Tl(e){return {text:"toString",richtext:"toString",number:"toNumber",currency:"toNumber",date:"toDate",checkbox:"toBoolean"}[e]}a(Tl,"resolveBuiltInTransform");var fn=class fn{constructor(t){this.operations=[];this.touchedAttributes=new Set;this.version=t;}assertNotTouched(t,r){if(this.touchedAttributes.has(t))throw new Error(`[MigrationBuilder] Conflicting operations on attribute "${t}": it was already modified earlier in this migration (attempted: ${r}).`)}renameAttribute(t,r){return this.assertNotTouched(t,"rename_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"rename_attribute",from:t,to:r}),this}changeType(t,r,n,o){this.assertNotTouched(t,"change_type"),this.touchedAttributes.add(t);let a=o?.transform?Tl(n):void 0;return this.operations.push({type:"change_type",name:t,from:r,to:n,transform:a}),this}removeAttribute(t){return this.assertNotTouched(t,"remove_attribute"),this.touchedAttributes.add(t),this.operations.push({type:"remove_attribute",name:t,backup_config:{}}),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,r){return this.assertNotTouched(t,"update_config"),this.touchedAttributes.add(t),this.operations.push({type:"update_config",name:t,from:{},to:r}),this}build(){return {version:this.version,operations:[...this.operations]}}};a(fn,"MigrationBuilder");var xt=fn;function wl(e){let{name:t,labelExpression:r,embeddingExpression:n}=e;if(!r)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=Ae.safeParse(r);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(n!==void 0){let a=Ae.safeParse(n);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(wl,"validateObjectExpressions");var bn=class bn{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 At(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 r$1=t.map(n=>"build"in n&&typeof n.build=="function"?n.build():n);de([...this.obj.attributes,...r$1],n=>n.name,n=>new r("attribute",n,`Object "${this.obj.name}": duplicate attribute name "${n}"`)),this.obj.attributes.push(...r$1);}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 r of t.presets)ea(r.id,r.structure,1);return this.obj.documentLayout=t,this}migration(t,r){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 xt(t);return r(o),this._migrations.push(o.build()),this}build(){if(!this.obj.name)throw new h("[ObjectBuilder] Missing required field: name",[{path:["name"],message:"name is required"}]);if(!this.obj.label)throw new h("[ObjectBuilder] Missing required field: label",[{path:["label"],message:"label is required"}]);wl({name:this.obj.name,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression});let t=[...this._migrations].sort((n,o)=>n.version-o.version);for(let n=0;n<t.length;n++){let o=n+2;if(t[n].version!==o)throw new Error(`[ObjectBuilder] Migration versions must be sequential starting at 2. Expected version ${o}, got ${t[n].version}.`)}let r=t.length>0?t[t.length-1].version:1;return {...this.obj,pluralLabel:this._pluralLabel,labelExpression:this._labelExpression,embeddingExpression:this._embeddingExpression,schema_version:r,migrations:t,sealed:this._sealed,toleratedAttributes:this._toleratedAttributes}}validateName(t){t!==void 0&&Le(t);}};a(bn,"ObjectBuilder");var $e=bn;function cw(e){if(w$1(e.name))throw new s(e.name,"builder");return new $e(e)}a(cw,"object");function ea(e,t,r){let n=a((a,s)=>{throw new h(a,[{path:["documentLayout","presets",e],message:s}])},"fail");r>5&&n(`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&&n("Folder preset node title is required","Empty folder title"),s.includes("/")&&n("Folder preset node title cannot contain /",`Folder title contains /: "${s}"`),o.has(s)&&n("Folder preset sibling titles must be unique",`Duplicate folder title: "${s}"`),o.add(s),a.children&&a.children.length>0&&ea(e,a.children,r+1);}}a(ea,"validatePresetStructure");var vn=class vn{constructor(t,r){this.data={type:"fields",fields:[]};this.data.id=t,this.data.label=r;}description(t){return this.data.description=t,this}collapsible(t=false){return this.data.collapsible=true,this.data.collapsed=t,this}order(t){return this.data.order=t,this}fields(...t){for(let r of t)this.data.fields?.push({attribute:r});return this}field(t,r){return this.data.fields?.push({attribute:t,...r}),this}attributeGroup(t,r){return this.data.fields?.push({attributeGroup:t,...r}),this}build(){if(!this.data.id)throw new Error("[GroupBuilder] id is required");if(!this.data.label)throw new Error("[GroupBuilder] label is required");if(!this.data.fields||this.data.fields.length===0)throw new Error("[GroupBuilder] At least one field is required");return this.data}};a(vn,"GroupBuilder");var St=vn,Rn=class Rn{constructor(t,r){this.view=t,this.tabData=r;}columns(...t){return this.tabData.columns=t,this}create(t){return this.tabData.allowCreate=true,t?.mode&&(this.tabData.createMode=t.mode),this}createMode(t){return this.tabData.createMode=t,this}openMode(t){return this.tabData.openMode=t,this}edit(){return this.tabData.allowEdit=true,this}delete(){return this.tabData.allowDelete=true,this}crud(){return this.tabData.allowCreate=true,this.tabData.allowEdit=true,this.tabData.allowDelete=true,this}filters(t){return this.tabData.filters=t,this}sorts(t){return this.tabData.sorts=t,this}sort(t,r="asc"){return this.tabData.sorts||(this.tabData.sorts=[]),this.tabData.sorts.push({attribute:t,direction:r}),this}tab(t,r){return this.finalize(),new te(this.view,t,r)}done(){return this.finalize(),this.view}build(){return this.finalize(),this.view.build()}finalize(){if(!this.tabData.columns||this.tabData.columns.length===0)throw new Error(`[TableTabConfig] columns() is required for tab "${this.tabData.name}"`);this.view._addTab(this.tabData);}};a(Rn,"TableTabConfig");var vt=Rn,Dn=class Dn{constructor(t,r,n){this.view=t,this.tabData={...r,type:"custom",component:n};}props(t){return this.tabData.props=t,this}tab(t,r){return this.view._addTab(this.tabData),new te(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(Dn,"CustomTabConfig");var gn=Dn,En=class En{constructor(t,r,n){this.view=t,this.tabData={...r,type:"richtext",attribute:n};}titleAttribute(t){return this.tabData.titleAttribute=t,this}tab(t,r){return this.view._addTab(this.tabData),new te(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(En,"RichtextTabConfig");var yn=En,Cn=class Cn{constructor(t,r){this.view=t,this.tabData={...r,type:"activity"};}limit(t){return this.tabData.limit=t,this}tab(t,r){return this.view._addTab(this.tabData),new te(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(Cn,"ActivityTabConfig");var hn=Cn,On=class On{constructor(t,r,n){this.view=t,this.tabData={...r,type:n,emailAttributeIds:[]};}emailAttributes(...t){return this.tabData.emailAttributeIds=t,this}tab(t,r){return this.view._addTab(this.tabData),new te(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(On,"AddressMatchedTabConfig");var Rt=On,_n=class _n extends Rt{constructor(t,r){super(t,r,"emails");}};a(_n,"EmailsTabConfig");var An=_n,Nn=class Nn extends Rt{constructor(t,r){super(t,r,"meetings");}};a(Nn,"MeetingsTabConfig");var Tn=Nn,kn=class kn{constructor(t,r){this.view=t,this.tabData={...r,type:"documents",allowUpload:true,allowRemove:true,hideAttachments:false};}disableUpload(){return this.tabData.allowUpload=false,this}disableRemove(){return this.tabData.allowRemove=false,this}hideAttachments(){return this.tabData.hideAttachments=true,this}from(...t){return this.tabData.relations=[...this.tabData.relations??[],...t],this}tab(t,r){return this.view._addTab(this.tabData),new te(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(kn,"DocumentsTabConfig");var wn=kn,Pn=class Pn{constructor(t,r,n){this.view=t,this.base={id:r,name:r,label:n};}icon(t){return this.base.icon=t,this}order(t){return this.base.order=t,this}form(...t){if(t.length===0)throw new Error(`[TabBuilder] form() requires at least one group for tab "${this.base.name}"`);let r={...this.base,type:"form",groups:t.map(n=>n instanceof St?n.build():n)};return this.view._addTab(r)}table(t){return new vt(this.view,{...this.base,type:"table",source:{type:"relation",attribute:t},columns:[]})}tableFrom(t,r){return new vt(this.view,{...this.base,type:"table",source:{type:"inverse",object:t,attribute:r},columns:[]})}custom(t){return new gn(this.view,this.base,t)}richtext(t){return new yn(this.view,this.base,t)}activity(){return new hn(this.view,this.base)}documents(){return new wn(this.view,this.base)}emails(){return new An(this.view,this.base)}meetings(){return new Tn(this.view,this.base)}forms(t){let r={...this.base,type:"forms",...t};return this.view._addTab(r)}};a(Pn,"TabBuilder");var te=Pn,jn=class jn{constructor(t,r){ht(t),this.data={name:t,label:r,tabs:[]};}description(t){return this.data.description=t,this}icon(t){return this.data.icon=t,this}for(t){return this.data.object=t,this}default(){return this.data.default=true,this}metadata(t){return this.data.metadata=t,this}sidePanel(t){return this.data.sidePanel=t,this}readOnly(){return this.data.readOnly=true,this}tab(t,r){return new te(this,t,r)}addTab(t){return this.data.tabs.push(t),this}_addTab(t){return this.data.tabs.push(t),this}build(){if(!this.data.object)throw new Error("[DetailViewBuilder] for() is required - specify the target object");if(this.data.tabs.length===0)throw new Error("[DetailViewBuilder] At least one tab is required");de(this.data.tabs,r=>r.name,r=>new Error(`[DetailViewBuilder] Duplicate tab name "${r}"`));let t={tabs:this.data.tabs,sidePanel:this.data.sidePanel,...this.data.readOnly?{readOnly:true}:{}};return {name:this.data.name,label:this.data.label,description:this.data.description,icon:this.data.icon,object:this.data.object,type:"detail",config:t,default:this.data.default,metadata:this.data.metadata}}};a(jn,"DetailViewBuilder");var xn=jn;function H(e,t){return new xn(e,t)}a(H,"detailView");function It(e){if(Array.isArray(e))return e.map(It).find(r=>r!==void 0);if(e===null||typeof e!="object")return;let t=e;return t.attribute==="visibility"||t.attribute==="ownedBy"?t.attribute:It(t.rules)??It(t.groups)}a(It,"findProtectedTabFilterAttribute");var Fn=class Fn{constructor(t,r){ht(t),this.data={name:t,label:r,tabs:[]};}description(t){return this.data.description=t,this}icon(t){return this.data.icon=t,this}for(t){return this.data.object=t,this}default(){return this.data.default=true,this}metadata(t){return this.data.metadata=t,this}baseFilter(t){return this.data.defaultFilters=t,this}allowPresentationCustomization(){return this.data.allowPresentationCustomization=true,this}tab(t,r){return new Sn(this,t,r)}_addTab(t){return this.data.tabs.push(t),this}build(){if(!this.data.object)throw new Error("[ListViewBuilder] for() is required - specify the target object");if(this.data.tabs.length===0)throw new Error("[ListViewBuilder] At least one tab is required");if(de(this.data.tabs,n=>n.id,n=>new Error(`[ListViewBuilder] Duplicate tab id "${n}"`)),this.data.tabs.filter(n=>n.default).length>1)throw new Error("[ListViewBuilder] Only one tab can be marked as default");for(let n of this.data.tabs){if(n.layout==="table"&&n.columns.length===0)throw new h(`[ListViewBuilder] Tab "${n.id}" must have at least one column`,[]);if(n.layout==="kanban"&&!n.groupByAttribute)throw new h(`[ListViewBuilder] Kanban tab "${n.id}" requires a groupByAttribute`,[]);if(n.descriptionAttribute!==void 0&&n.descriptionAttribute.length===0)throw new h(`[ListViewBuilder] Tab "${n.id}" requires a nonempty description attribute name`,[]);if(n.displayAttributes!==void 0){let o=_$1.safeParse(n.displayAttributes);if(!o.success)throw new h(`[ListViewBuilder] Tab "${n.id}" has invalid display attributes`,o.error.issues.map(a=>({path:["tabs",n.id,"displayAttributes",...a.path.map(String)],message:a.message})))}}let r={allowPresentationCustomization:this.data.allowPresentationCustomization,defaultFilters:this.data.defaultFilters?{id:h$1(),combinator:this.data.defaultFilters.combinator,rules:this.data.defaultFilters.rules}:void 0,tabs:this.data.tabs.map(n=>{let o={id:n.id,label:n.label,icon:n.icon,default:n.default,visibility:n.visibility,columns:n.columns,descriptionAttribute:n.descriptionAttribute,displayAttributes:n.displayAttributes,filters:n.filters?{id:h$1(),combinator:n.filters.combinator,rules:n.filters.rules}:void 0,sorts:n.sorts,readOnly:n.readOnly,createMode:n.createMode,openMode:n.openMode};return n.layout==="kanban"?{...o,layout:"kanban",groupByAttribute:n.groupByAttribute,cardUserAttribute:n.cardUserAttribute,cardDateAttribute:n.cardDateAttribute,kanbanColumnOrder:n.kanbanColumnOrder,kanbanColumnVisibility:n.kanbanColumnVisibility,kanbanPinnedColumns:n.kanbanPinnedColumns}:{...o,layout:n.layout,columnSizing:n.columnSizing}})};return {name:this.data.name,label:this.data.label,description:this.data.description,icon:this.data.icon,object:this.data.object,type:"list",config:r,default:this.data.default,metadata:this.data.metadata}}};a(Fn,"ListViewBuilder");var In=Fn,Dt=class Dt{constructor(t,r,n){this.view=t,this.tabData={id:r,label:n,visibility:"all",layout:"table",columns:[]};}icon(t){return this.tabData.icon=t,this}default(){return this.tabData.default=true,this}readOnly(){return this.tabData.readOnly=true,this}visibility(t){return this.tabData.visibility=t,this}table(){return this.tabData.layout="table",this}list(){return this.tabData.layout="list",this}descriptionAttribute(t){return this.tabData.descriptionAttribute=t,this}displayAttributes(...t){return this.tabData.displayAttributes=t,this}kanban(t){return this.tabData.layout="kanban",this.tabData.groupByAttribute=t,this}cardUserAttribute(t){return this.tabData.cardUserAttribute=t,this}cardDateAttribute(t){return this.tabData.cardDateAttribute=t,this}kanbanColumnOrder(t){return this.tabData.kanbanColumnOrder=t,this}kanbanColumnVisibility(t){return this.tabData.kanbanColumnVisibility=t,this}kanbanPinnedColumns(t){return this.tabData.kanbanPinnedColumns=t,this}createMode(t){return this.tabData.createMode=t,this}openMode(t){return this.tabData.openMode=t,this}columns(...t){return this.tabData.columns=t,this}columnWidth(t,r){return this.tabData.columnSizing||(this.tabData.columnSizing={}),this.tabData.columnSizing[t]=r,this}filter(t){let r=It(t);if(r){let n=`Tab filters cannot target "${r}". Use .visibility("private")`;throw new h(n,[{path:["filters"],message:n}])}return this.tabData.filters=t,this}sort(t,r="asc"){return this.tabData.sorts||(this.tabData.sorts=[]),this.tabData.sorts.push({attribute:t,direction:r}),this}sorts(t){return this.tabData.sorts=t,this}tab(t,r){return this.view._addTab(this.tabData),new Dt(this.view,t,r)}done(){return this.view._addTab(this.tabData),this.view}build(){return this.view._addTab(this.tabData),this.view.build()}};a(Dt,"ListViewTabConfigBuilder");var Sn=Dt;function Y(e,t){return new In(e,t)}a(Y,"listView");function hw(e,t){return new St(e,t)}a(hw,"group");function xl(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(xl,"validateFlagName");var $n=class $n{constructor(t,r,n){xl(t),this.flag={name:t,valueType:r,defaultValue:n,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($n,"BaseFlagBuilder");var Se=$n,Un=class Un extends Se{constructor(t){super(t,"boolean",false);}defaultValue(t){return this.flag.defaultValue=t,this}enabledByDefault(){return this.flag.defaultValue=true,this}};a(Un,"BooleanFlagBuilder");var Vn=Un,qn=class qn extends Se{constructor(t){super(t,"string","");}defaultValue(t){return this.flag.defaultValue=t,this}};a(qn,"StringFlagBuilder");var Mn=qn,zn=class zn extends Se{constructor(t){super(t,"number",0);}defaultValue(t){return this.flag.defaultValue=t,this}};a(zn,"NumberFlagBuilder");var Ln=zn,Gn=class Gn extends Se{constructor(t,r){super(t,"json",r);}defaultValue(t){return this.flag.defaultValue=t,this}};a(Gn,"JsonFlagBuilder");var Bn=Gn;function Il(e){return new Vn(e)}a(Il,"booleanFlag");function Sl(e){return new Mn(e)}a(Sl,"stringFlag");function vl(e){return new Ln(e)}a(vl,"numberFlag");function Rl(e,t){return new Bn(e,t)}a(Rl,"jsonFlag");function Wn(e){return new r("feature flag",e,`Flag "${e}" is already registered. Each flag name must be unique.`)}a(Wn,"duplicateFlagError");function Kn(e){return {...e,allowedLevels:[...e.allowedLevels]}}a(Kn,"cloneFlagDefinition");var Hn=class Hn{constructor(){this.flags=new Map;}register(t){if(this.flags.has(t.name))throw Wn(t.name);this.flags.set(t.name,Kn(t));}registerAll(t){let r=new Set;for(let n of t){if(this.flags.has(n.name)||r.has(n.name))throw Wn(n.name);r.add(n.name);}for(let n of t)this.register(n);}get(t){let r=this.flags.get(t);return r?Kn(r):void 0}getOrThrow(t){let r=this.get(t);if(!r)throw new c$3("Feature flag",t,void 0,`Flag "${t}" is not registered. Available flags: ${this.listNames().join(", ")}`);return r}has(t){return this.flags.has(t)}list(){return Array.from(this.flags.values(),Kn)}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(Hn,"FlagRegistry");var Ue=Hn,Dl=new Ue;function El(){return new Ue}a(El,"createFlagRegistry");function Et(){return {global:new Map,tenant:new Map,user:new Map}}a(Et,"emptyOverrides");function Cl(e,t){return e.expiresAt===void 0||e.expiresAt.getTime()>t}a(Cl,"isActiveOverride");function Yn(e,t){let r=new Map;for(let n of e){if(!Cl(n,t))continue;let o=n.flagName;r.has(o)||r.set(o,n);}return r}a(Yn,"indexOverrides");var Qn=class Qn{constructor(t){this.repository=t.repository,this.registry=t.registry,this.staticDefaults=new Map(t.staticDefaults?.map(r=>[r.name,r.value])??[]);}async resolveAll(t={}){let r=this.collectFlagNames(),n=this.repository&&r.size>0?await this.getAllOverrides(t,[...r]):Et();return this.resolveNames(r,n,t)}resolveAllStatic(){return this.resolveNames(this.collectFlagNames(),Et(),{})}collectFlagNames(){let t=new Set;for(let r of this.registry.listNames())t.add(r);for(let r of this.staticDefaults.keys())t.add(r);return t}resolveNames(t,r,n){let o=new Map;for(let a of t)o.set(a,this.resolveValue(a,r,n));return o}async resolve(t,r={}){let n=this.repository?await this.getAllOverrides(r,[t]):Et();return this.resolveWithSource(t,n,r)}async isEnabled(t,r={}){return (await this.resolve(t,r)).value===true}async getValue(t,r={}){return (await this.resolve(t,r)).value}async setOverride(t,r,n,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(r)){let s=`Flag "${t}" does not allow ${r}-level overrides. Allowed levels: ${a.allowedLevels.join(", ")}`;throw new h(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(s,[{path:["flagName"],message:s}])}await this.repository.setOverride({flagName:t,level:r,value:n,targetId:o.targetId,expiresAt:o.expiresAt,createdBy:o.createdBy});}async deleteOverride(t,r,n){if(!this.repository)throw new b$1("Cannot delete override: no FeatureFlagsRepository configured.",a$2.CONFIGURATION_REQUIRED);await this.repository.deleteOverride(t,r,n);}async getAllOverrides(t,r){if(!this.repository)return Et();let[n,o,a]=await Promise.all([this.repository.getOverrides({level:"global",flagNames:r}),t.tenantId?this.repository.getOverrides({level:"tenant",targetId:t.tenantId,flagNames:r}):Promise.resolve([]),t.userId?this.repository.getOverrides({level:"user",targetId:t.userId,flagNames:r}):Promise.resolve([])]),s=Date.now();return {global:Yn(n,s),tenant:Yn(o,s),user:Yn(a,s)}}resolveValue(t,r,n){return this.resolveWithSource(t,r,n).value}resolveWithSource(t,r,n){let o=this.registry.get(t),a=o?.allowedLevels??["global","tenant","user"];if(n.userId&&a.includes("user")){let s=r.user.get(t);if(s)return {name:t,value:s.value,source:"user",sourceId:n.userId}}if(n.tenantId&&a.includes("tenant")){let s=r.tenant.get(t);if(s)return {name:t,value:s.value,source:"tenant",sourceId:n.tenantId}}if(a.includes("global")){let s=r.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(Qn,"FlagService");var Ct=Qn;function Ol(e){return new Ct(e)}a(Ol,"createFlagService");var ta=Symbol("stndrds.native-object");function Xn(e){return Object.defineProperty(e,ta,{value:true,enumerable:false}),e}a(Xn,"markNativeDefinition");var ei=class ei extends $e{build(){return Xn(super.build())}};a(ei,"NativeObjectBuilder");var Jn=ei;function Q(e){return new Jn(e)}a(Q,"nativeObject");function Zn(e){return e[ta]===true}a(Zn,"isNativeDefinition");function ti(e){let t=structuredClone(e);return Zn(e)?Xn(t):t}a(ti,"cloneObjectDefinition");var ni=class ni{constructor(){this.objects=new Map;}register(t){let n=(Array.isArray(t)?t:[t]).map(a=>"build"in a&&typeof a.build=="function"?a.build():a),o=new Set;for(let a of n){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 n)this.objects.set(a.name,ti(a));return this}validate(t){if(!t.system){let r=`[NativeObjectRegistry] Cannot register object "${t.name}" (id: ${t.id}): missing system flag.
|
|
14
14
|
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(r,[])}if(w$1(t.name)&&!Zn(t))throw new s(t.name,"registry");if(this.objects.has(t.name)){let r$1=this.objects.get(t.name),n=`[NativeObjectRegistry] Duplicate object name "${t.name}":
|
|
15
15
|
- Existing: "${r$1?.label}" (id: ${r$1?.id})
|
|
16
16
|
- New: "${t.label}" (id: ${t.id})
|
|
17
17
|
Please use unique names for each native object.`;throw new r("object",t.name,n)}}getByName(t){let r=this.objects.get(t);return r?ti(r):void 0}getByNameOrThrow(t){let r=this.getByName(t);if(!r){let n=`[NativeObjectRegistry] Native object "${t}" not found.
|
|
18
18
|
Available objects: ${this.listNames().join(", ")}`;throw new c$3("Native object",t,a$2.OBJECT_NOT_FOUND,n)}return r}getAll(){return Array.from(this.objects.values(),ti)}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(r=>` - ${r.name}: "${r.label}" (${r.attributes.length} attributes)`)].join(`
|
|
19
|
-
`)}debug(t){let r=this.summary();return t?.(r),r}};a(ni,"NativeObjectRegistryClass");var ri=ni,
|
|
19
|
+
`)}debug(t){let r=this.summary();return t?.(r),r}};a(ni,"NativeObjectRegistryClass");var ri=ni,Ww=new ri;function k(e){return {...e,system:true}}a(k,"markSystemView");var ra=`## Overview
|
|
20
20
|
|
|
21
21
|
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.
|
|
22
22
|
|
|
@@ -47,14 +47,14 @@ Show at least one concrete example of the skill applied well.
|
|
|
47
47
|
|
|
48
48
|
- Never \u2026
|
|
49
49
|
- Do not \u2026
|
|
50
|
-
`,
|
|
50
|
+
`,kl=Q({name:"skill",label:"Skill"}).sealed().icon("book-open").order(Number.MAX_SAFE_INTEGER).pluralLabel("Skills").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
51
51
|
{{ description }}
|
|
52
|
-
{{ content }}`).attribute(b({name:"name",label:"Name"}).maxLength(SKILL_NAME_MAX_LENGTH).required()).attribute(b({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(xe({name:"content",label:"Content"}).defaultValue(
|
|
52
|
+
{{ content }}`).attribute(b({name:"name",label:"Name"}).maxLength(SKILL_NAME_MAX_LENGTH).required()).attribute(b({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(xe({name:"content",label:"Content"}).defaultValue(ra)).build(),Pl=k(H("skill-detail","Skill").for("skill").default().sidePanel({attributes:["name","description"]}).tab("content","Content").richtext("content").titleAttribute("name").done().tab("files","Files").documents().done().tab("activity","Activity").activity().done().build()),jl=k(Y("skill-list","Skills").for("skill").default().allowPresentationCustomization().tab("workspace","Skills").default().icon("list").visibility("workspace").list().columns("name","description").descriptionAttribute("description").displayAttributes("createdBy","updatedAt").sort("name","asc").tab("mine","My skills").icon("lock").visibility("private").list().columns("name","description").descriptionAttribute("description").displayAttributes("createdBy","updatedAt").sort("name","asc").build());var Ml=Q({name:"memory",label:"Memory"}).sealed().icon("database").order(Number.MAX_SAFE_INTEGER).pluralLabel("Memories").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
53
53
|
{{ description }}
|
|
54
|
-
{{ content }}`).migration(2,e=>e.changeType("content","text","richtext")).attribute(b({name:"name",label:"Name"}).maxLength(MEMORY_NAME_MAX_LENGTH).required()).attribute(b({name:"description",label:"Description"}).multiline().maxLength(MEMORY_DESCRIPTION_MAX_LENGTH).required()).attribute(xe({name:"content",label:"Content"})).attribute(K({name:"kind",label:"Kind"}).options([{value:"fact",label:"Fact"},{value:"preference",label:"Preference"},{value:"feedback",label:"Feedback"},{value:"reference",label:"Reference"}])).attribute(Ie({name:"subjects",label:"Subjects"}).toAny().many()).attribute(Ie({name:"links",label:"Links"}).to("memory").many()).attribute(K({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(U({name:"validFrom",label:"Valid from"}).includeTime()).attribute(U({name:"invalidAt",label:"Invalid at"}).includeTime()).attribute(Ie({name:"supersededBy",label:"Superseded by"}).to("memory")).attribute(b({name:"provenance",label:"Provenance"}).multiline()).attribute(K({name:"reviewState",label:"Review state"}).options([{value:"needs_review",label:"Needs review"},{value:"skill_candidate",label:"Skill candidate"}])).attribute(b({name:"reviewReason",label:"Review reason"}).multiline()).attribute(U({name:"curatedAt",label:"Curated at"}).includeTime()).attribute(U({name:"reviewAfter",label:"Review after"}).includeTime()).attribute(b({name:"curationFingerprint",label:"Curation fingerprint"})).build(),
|
|
55
|
-
{{ description }}`).attribute(b({name:"name",label:"Name"}).required()).attribute(b({name:"description",label:"Description"}).multiline()).build()
|
|
56
|
-
{{ description }}`).attribute(b({name:"name",label:"Name"}).required()).attribute(b({name:"description",label:"Description"}).multiline()).attribute(K({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(K({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(wt({name:"currentRevision",label:"Current revision"}).integer().min(1)).attribute(U({name:"expiresAt",label:"Expires at"}).includeTime().hidden()).attribute(b({name:"sourceSessionId",label:"Source session"}).hidden()).attribute(b({name:"sourceMessageId",label:"Source message"}).hidden()).attribute(b({name:"initialToolCallId",label:"Initial tool call"}).hidden()).attribute(
|
|
54
|
+
{{ content }}`).migration(2,e=>e.changeType("content","text","richtext")).attribute(b({name:"name",label:"Name"}).maxLength(MEMORY_NAME_MAX_LENGTH).required()).attribute(b({name:"description",label:"Description"}).multiline().maxLength(MEMORY_DESCRIPTION_MAX_LENGTH).required()).attribute(xe({name:"content",label:"Content"})).attribute(K({name:"kind",label:"Kind"}).options([{value:"fact",label:"Fact"},{value:"preference",label:"Preference"},{value:"feedback",label:"Feedback"},{value:"reference",label:"Reference"}])).attribute(Ie({name:"subjects",label:"Subjects"}).toAny().many()).attribute(Ie({name:"links",label:"Links"}).to("memory").many()).attribute(K({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(U({name:"validFrom",label:"Valid from"}).includeTime()).attribute(U({name:"invalidAt",label:"Invalid at"}).includeTime()).attribute(Ie({name:"supersededBy",label:"Superseded by"}).to("memory")).attribute(b({name:"provenance",label:"Provenance"}).multiline()).attribute(K({name:"reviewState",label:"Review state"}).options([{value:"needs_review",label:"Needs review"},{value:"skill_candidate",label:"Skill candidate"}])).attribute(b({name:"reviewReason",label:"Review reason"}).multiline()).attribute(U({name:"curatedAt",label:"Curated at"}).includeTime()).attribute(U({name:"reviewAfter",label:"Review after"}).includeTime()).attribute(b({name:"curationFingerprint",label:"Curation fingerprint"})).build(),na={combinator:"and",rules:[{attribute:"invalidAt",operator:"is_empty",value:null},{attribute:"reviewState",operator:"is_empty",value:null}]},Ll=k(H("memory-detail","Memory").for("memory").default().sidePanel({attributes:["description","kind","source","provenance","reviewState","reviewReason","validFrom","invalidAt","supersededBy","curatedAt","reviewAfter","subjects","links"]}).tab("content","Content").richtext("content").titleAttribute("name").build()),Bl=k(Y("memory-list","Memories").for("memory").default().allowPresentationCustomization().tab("workspace","Memories").default().icon("list").visibility("workspace").list().columns("name","kind","description","createdAt").descriptionAttribute("description").displayAttributes("kind","subjects","createdAt").filter(na).sort("name","asc").tab("mine","My memories").icon("lock").visibility("private").list().columns("name","kind","description","createdAt").descriptionAttribute("description").displayAttributes("kind","subjects","createdAt").filter(na).sort("name","asc").tab("review","To review").icon("question-circle").table().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").icon("archive").table().columns("name","kind","invalidAt","supersededBy").filter({combinator:"and",rules:[{attribute:"invalidAt",operator:"is_not_empty",value:null}]}).sort("invalidAt","desc").build());var Ot="drives",$l=Q({name:Ot,label:"Drive"}).sealed().icon("folder").hidden().pluralLabel("Drives").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
55
|
+
{{ description }}`).attribute(b({name:"name",label:"Name"}).required()).attribute(b({name:"description",label:"Description"}).multiline()).build(),Ul=k(H("drive-detail","Drive").for(Ot).default().sidePanel({attributes:["description"]}).tab("documents","Documents").documents().build()),ql=k(Y("drive-list","Drives").for(Ot).default().tab("workspace","Shared").default().icon("users").visibility("workspace").table().columns("name","description","updatedAt").sort("name","asc").tab("mine","My drives").icon("lock").visibility("private").table().columns("name","description","updatedAt").sort("name","asc").build());var _t="artifact",zl=Q({name:_t,label:"Artifact"}).sealed().icon("package").pluralLabel("Artifacts").labelExpression("{{ name }}").embeddingExpression(`{{ name }}
|
|
56
|
+
{{ description }}`).attribute(b({name:"name",label:"Name"}).required()).attribute(b({name:"description",label:"Description"}).multiline()).attribute(K({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(K({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(wt({name:"currentRevision",label:"Current revision"}).integer().min(1)).attribute(U({name:"expiresAt",label:"Expires at"}).includeTime().hidden()).attribute(b({name:"sourceSessionId",label:"Source session"}).hidden()).attribute(b({name:"sourceMessageId",label:"Source message"}).hidden()).attribute(b({name:"initialToolCallId",label:"Initial tool call"}).hidden()).attribute(Jo({name:"versions",label:"Versions"}).qualifyWith(wt({name:"revision",label:"Revision"}).integer().min(1).required(),b({name:"toolCallId",label:"Tool call"}).hidden(),b({name:"sourceFileId",label:"Source file"}).hidden(),b({name:"previewFileId",label:"Preview file"}).hidden(),b({name:"fileIds",label:"File manifest"}).hidden(),b({name:"entrypoint",label:"Entrypoint"}).hidden(),b({name:"sourceMessageId",label:"Source message"}).hidden(),b({name:"artifactName",label:"Artifact name"}).hidden(),b({name:"artifactDescription",label:"Artifact description"}).hidden(),b({name:"artifactKind",label:"Artifact kind"}).hidden(),b({name:"displayMode",label:"Display mode"}).hidden(),b({name:"displayInteraction",label:"Display interaction"}).hidden(),b({name:"displaySize",label:"Display size"}).hidden(),wt({name:"displayAspectRatio",label:"Display aspect ratio"}).hidden())).build(),Gl=k(H("artifact-detail","Artifact").for(_t).default().readOnly().sidePanel({attributes:["description","kind","retention","currentRevision","createdBy","updatedAt"]}).tab("preview","Preview").custom("ArtifactPreview").done().tab("versions","Versions").documents().disableUpload().disableRemove().hideAttachments().done().tab("activity","Activity").activity().done().build());function Wl(){let e=Y("artifact-list","Artifacts").for(_t).default().allowPresentationCustomization().tab("mine","My artifacts").default().icon("lock").visibility("private").readOnly().list().columns("name","kind","currentRevision","updatedAt").descriptionAttribute("description").displayAttributes("kind","currentRevision","updatedAt").sort("updatedAt","desc").tab("workspace","Workspace").icon("list").visibility("workspace").readOnly().list().columns("name","kind","currentRevision","updatedAt").descriptionAttribute("description").displayAttributes("kind","currentRevision","updatedAt").sort("updatedAt","desc").build();return {...e,config:{...e.config,tabs:e.config.tabs.map(t=>({...t,default:t.default??false}))}}}a(Wl,"buildArtifactListView");var Kl=k(Wl());var Nt="meeting",w={title:"title",description:"description",location:"location",startsAt:"startsAt",endsAt:"endsAt",isAllDay:"isAllDay",status:"status",organizerAddress:"organizerAddress",organizerName:"organizerName",conferenceProvider:"conferenceProvider",conferenceJoinUrl:"conferenceJoinUrl",htmlLink:"htmlLink",participants:"participants",providerEventId:"providerEventId",icalUid:"icalUid",recurringEventId:"recurringEventId",connectionId:"connectionId",recordingOverride:"recordingOverride",endedAnnouncedAt:"endedAnnouncedAt",linkedRecords:"linkedRecords"},oa="meeting-list",aa="calendar-sync",sa="meeting-detail",ia=[w.title,w.startsAt,w.endsAt,w.status],Hl=Q({name:Nt,label:"Meeting"}).sealed().hidden().metadata({platformOwned:{editable:[w.linkedRecords],source:aa}}).icon("calendar").pluralLabel("Meetings").labelExpression("{{ title }}").embeddingExpression(`{{ title }}
|
|
57
57
|
{{ description }}
|
|
58
|
-
{{ participants }}`).attribute(b({name:w.title,label:"Title"}).required()).attribute(xe({name:w.description,label:"Description"})).attribute(b({name:w.location,label:"Location"})).attribute(U({name:w.startsAt,label:"Starts at"}).includeTime()).attribute(U({name:w.endsAt,label:"Ends at"}).includeTime()).attribute(
|
|
58
|
+
{{ participants }}`).attribute(b({name:w.title,label:"Title"}).required()).attribute(xe({name:w.description,label:"Description"})).attribute(b({name:w.location,label:"Location"})).attribute(U({name:w.startsAt,label:"Starts at"}).includeTime()).attribute(U({name:w.endsAt,label:"Ends at"}).includeTime()).attribute(Qo({name:w.isAllDay,label:"All day"})).attribute(K({name:w.status,label:"Status"}).options([{value:"confirmed",label:"Confirmed"},{value:"tentative",label:"Tentative"},{value:"cancelled",label:"Cancelled"}])).attribute(b({name:w.organizerAddress,label:"Organizer address"}).email()).attribute(b({name:w.organizerName,label:"Organizer"})).attribute(b({name:w.conferenceProvider,label:"Conference provider"})).attribute(b({name:w.conferenceJoinUrl,label:"Join link"}).url()).attribute(b({name:w.htmlLink,label:"Open in calendar"}).url()).attribute(b({name:w.participants,label:"Participants"}).multiline()).attribute(b({name:w.providerEventId,label:"Provider event id"}).hidden()).attribute(b({name:w.icalUid,label:"iCal UID"}).hidden()).attribute(b({name:w.recurringEventId,label:"Recurring event id"}).hidden()).attribute(b({name:w.connectionId,label:"Connection id"}).hidden()).attribute(K({name:w.recordingOverride,label:"Recording"}).options([{value:"force",label:"Force"},{value:"skip",label:"Skip"}]).hidden()).attribute(U({name:w.endedAnnouncedAt,label:"Ended announced at"}).includeTime().hidden()).attribute(Ie({name:w.linkedRecords,label:"Linked records"}).toAny().many().qualifyWith(b({name:"source",label:"Source"}).hidden())).build(),Yl=k(H(sa,"Meeting").for(Nt).default().sidePanel({attributes:[w.startsAt,w.endsAt,w.linkedRecords]}).tab("description","Description").richtext(w.description).titleAttribute(w.title).build()),Ql=k(Y(oa,"Meetings").for(Nt).default().tab("workspace","Shared").default().icon("users").visibility("workspace").table().columns(...ia).sort(w.startsAt,"desc").tab("mine","My meetings").icon("lock").visibility("private").table().columns(...ia).sort(w.startsAt,"desc").build());function qe(e){return structuredClone(e)}a(qe,"cloneViewDefinition");var oi=class oi{constructor(){this.views=new Map;this.byObject=new Map;this.byObjectAndType=new Map;}register(t){let r=Array.isArray(t)?t:[t];for(let n of r)this.registerSingle(n);return this}registerSingle(t){let r$1=this.makeKey(t.object,t.name,t.type);if(this.views.has(r$1)){let l=`[ViewRegistry] Duplicate view: "${t.name}" (${t.type}) for object "${t.object}"`;throw new r("view",r$1,l)}let n=qe(t);this.views.set(r$1,n);let o=this.byObject.get(n.object)??[];o.push(n),this.byObject.set(n.object,o);let a=`${n.object}:${n.type}`,s=this.byObjectAndType.get(a)??[];s.push(n),this.byObjectAndType.set(a,s);}getByObjectName(t){return Array.from(this.byObject.get(t)??[],qe)}getByObjectNameAndType(t,r){return Array.from(this.byObjectAndType.get(`${t}:${r}`)??[],qe)}get(t,r,n){if(n){let a=this.views.get(this.makeKey(t,r,n));return a?qe(a):void 0}return this.getByObjectName(t).find(a=>a.name===r)}getOrThrow(t,r,n){let o=this.get(t,r,n);if(!o){let s=this.getByObjectName(t).map(c=>`${c.name} (${c.type})`).join(", ")||"(none)",l=`[ViewRegistry] View "${r}" not found for object "${t}".
|
|
59
59
|
Available views: ${s}`;throw new c$3("View",`${t}:${r}`,void 0,l)}return o}getAll(){return Array.from(this.views.values(),qe)}has(t,r,n){return n?this.views.has(this.makeKey(t,r,n)):this.getByObjectName(t).some(a=>a.name===r)}hasObject(t){return this.byObject.has(t)}get size(){return this.views.size}listObjectNames(){return Array.from(this.byObject.keys())}getDefault(t,r){let n=this.getByObjectNameAndType(t,r);return n.find(o=>o.default)??n[0]}clear(){this.views.clear(),this.byObject.clear(),this.byObjectAndType.clear();}summary(){let t=[];t.push(`[ViewRegistry] ${this.size} view(s) registered:`);for(let r of this.listObjectNames()){let o=this.getByObjectName(r).map(a=>{let s=[];a.default&&s.push("default");let l=s.length>0?` (${s.join(", ")})`:"";return `${a.name}:${a.type}${l}`});t.push(` ${r}: ${o.join(", ")}`);}return t.join(`
|
|
60
|
-
`)}debug(t){let r=this.summary();return t?.(r),r}makeKey(t,r,n){return `${t}:${r}:${n}`}};a(oi,"ViewRegistry");var ii=oi,Ql=new ii;function sa(e,t=[]){return e.filter(r=>!(!j$1(r).lifecycle.visibleInRuntime||r.system||t.includes(r.name)))}a(sa,"getRuntimeAttributes");function ua(e){return [...e].sort((t,r)=>{let n=t.order??999,o=r.order??999;return n!==o?n-o:t.name.localeCompare(r.name)})}a(ua,"sortAttributes");function Jl(e){if(e.type==="text"&&e.multiline)return 12;switch(e.type){case "richtext":case "location":return 12;case "checkbox":return 4;default:return 6}}a(Jl,"getDefaultFieldSpan");function Xl(e){return {attribute:e.name,span:Jl(e)}}a(Xl,"attributeToField");var kt="all",ze="form",Pt="general";function Ge(e,t={}){let{includeActivityTab:r=true,includeDocumentsTab:n=true,excludeAttributes:o=[]}=t,a=sa(e.attributes,o),s=ua(a.filter(W=>j$1(W).presentation.formField)),c=[{id:ze,name:ze,label:"Details",type:"form",groups:[{id:Pt,label:"General",type:"fields",fields:s.map(Xl),order:0}],order:0}],f=1,x=e.attributes.some(W=>W.type==="document");n&&x&&c.push({id:"documents",name:"documents",label:"Documents",type:"documents",order:f++,allowUpload:true,allowRemove:true}),r&&c.push({id:"activity",name:"activity",label:"Activity",type:"activity",order:f++});let v={tabs:c};return {name:"default",label:"Default View",object:e.name,type:"detail",config:v,default:true}}a(Ge,"generateDefaultDetailView");function We(e,t={}){let{excludeAttributes:r=[],maxListColumns:n=5}=t,o=sa(e.attributes,r),s=ua(o.filter(c=>j$1(c).presentation.defaultColumn)).slice(0,n).map(c=>c.name),l={tabs:[{id:kt,label:"All",default:true,visibility:"workspace",layout:"table",columns:s}]};return {name:"default",label:"All Records",object:e.name,type:"list",config:l,default:true}}a(We,"generateDefaultListView");function Zl(e,t){let{preserveCustomTabs:r=true,preserveTableTabs:n=true}=t,o=[];for(let a of e.config.tabs)r&&a.type==="custom"&&o.push(a),n&&a.type==="table"&&o.push(a);return o}a(Zl,"getPreservedDetailTabs");function ed(e,t){if(t.length===0)return e;let r=e.find(s=>s.type==="form"),n=e.filter(s=>s.type!=="form"),o=[];r&&o.push(r);let a=1;for(let s of t)o.push({...s,order:a++});for(let s of n)o.push({...s,order:a++});return o}a(ed,"mergeDetailTabs");function td(e,t,r){let{preserveMetadata:n=true,...o}=r,a=Ge(t,o),s=Zl(e,r),l=ed(a.config.tabs,s),c={...a.config,tabs:l},f={...a,config:c};return n&&(f.id=e.id,f.name=e.name,f.label=e.label,f.description=e.description,f.icon=e.icon),f}a(td,"resetDetailViewToDefault");function rd(e,t,r){let{preserveMetadata:n=true,...o}=r,s={...We(t,o)};return n&&(s.id=e.id,s.name=e.name,s.label=e.label,s.description=e.description,s.icon=e.icon),s}a(rd,"resetListViewToDefault");function nd(e,t,r={}){if(pt(e))return td(e,t,r);if(Oo(e))return rd(e,t,r);throw new Error(`Reset not supported for view type: ${e.type}`)}a(nd,"resetViewToDefault");function Cx(e,t){if(t){let r=e.tabs.find(n=>n.id===t);if(r)return r}return e.tabs.find(r=>r.default)??e.tabs[0]}a(Cx,"getActiveTab");function ai(e){return structuredClone(e)}a(ai,"cloneFormDefinition");var si=class si{constructor(){this.forms=new Map;}register(t){let r$1=Array.isArray(t)?t:[t];for(let n of r$1){if(this.forms.has(n.name))throw new r("form",n.name,`[FormRegistry] Duplicate form: "${n.name}"`);this.forms.set(n.name,ai(n));}return this}get(t){let r=this.forms.get(t);return r?ai(r):void 0}getAll(){return Array.from(this.forms.values(),ai)}listNames(){return Array.from(this.forms.keys())}};a(si,"FormRegistry");var Ke=si;var la=new Ke;function Bx(e,t){return `${e}:${t}`}a(Bx,"formatAgentStreamFrameId");function $x(e){let t=e.lastIndexOf(":");if(t<=0)return null;let r=e.slice(0,t),n=Number(e.slice(t+1));return !Number.isInteger(n)||n<=0?null:{streamId:r,sequence:n}}a($x,"parseAgentStreamFrameId");var zx=204800,Gx=256;function li(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(li,"isRecord");function di(e,t){let r=Object.keys(e);return r.length===t.length&&r.every(n=>t.includes(n))}a(di,"hasExactKeys");function ui(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}a(ui,"isPositiveInteger");function da(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}a(da,"isNonNegativeInteger");function id(e){return li(e)&&di(e,["kind","startOffset","endOffset"])?(e.kind==="text"||e.kind==="reasoning")&&da(e.startOffset)&&da(e.endOffset)&&e.endOffset>=e.startOffset:false}a(id,"isContentRange");function od(e){if(!li(e))return false;let t=e.content===void 0?["sequence","chunk"]:["sequence","content","chunk"];return di(e,t)&&ui(e.sequence)&&e.chunk!==void 0&&(e.content===void 0||id(e.content))}a(od,"isBatchItem");function ad(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return}}a(ad,"encodedSize");function Wx(e){if(!(li(e)&&di(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()===""||!ui(e.sequenceStart)||!ui(e.sequenceEnd)||!Array.isArray(e.items)||e.items.length===0||e.items.length>256||!e.items.every(od))return false;let t=0;for(let n of e.items){if(n.sequence<=t)return false;t=n.sequence;}if(e.items[0]?.sequence!==e.sequenceStart||e.items.at(-1)?.sequence!==e.sequenceEnd)return false;let r=ad(e);return r!==void 0&&r<=204800}a(Wx,"isAgentUIMessageBatch");function ca(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(ca,"liveChannelKey");function Yx(e){return e.sessionId?ca({kind:"architect-draft",scope:"session",sessionId:e.sessionId}):e.actorId?ca({kind:"architect-draft",scope:"actor",actorId:e.actorId}):null}a(Yx,"architectDraftChannelKey");function ie(e){try{return decodeURIComponent(e)}catch{return null}}a(ie,"decodeLiveChannelPart");function pa(e){let t=e.split(":");if(t[0]==="workspace"&&t.length===2&&t[1]){let r=ie(t[1]);return r?{kind:"workspace",tenantId:r}:null}if(t[0]==="object"&&t.length===2&&t[1]){let r=ie(t[1]);return r?{kind:"object",objectId:r}:null}if(t[0]==="record"&&t.length===3&&t[1]&&t[2]){let r=ie(t[1]),n=ie(t[2]);return r&&n?{kind:"record",objectId:r,recordId:n}:null}if(t[0]==="view"&&t.length===2&&t[1]){let r=ie(t[1]);return r?{kind:"view",viewId:r}:null}if(t[0]==="user"&&t.length===2&&t[1]){let r=ie(t[1]);return r?{kind:"user",actorId:r}:null}if(t[0]==="architect-draft"&&t.length===3&&t[2]){let r=ie(t[2]);return r?t[1]==="actor"?{kind:"architect-draft",scope:"actor",actorId:r}:t[1]==="session"?{kind:"architect-draft",scope:"session",sessionId:r}:null:null}if(t[0]==="conversation"&&t.length===2&&t[1]){let r=ie(t[1]);return r?{kind:"conversation",sessionId:r}:null}return null}a(pa,"parseLiveChannelKey");var sd={"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},ud=Object.keys(sd),ld=["membership-unknown","sort-unknown","permissions-changed"],dd=["permission-revoked","workspace-left","object-deleted"],cd=["inboxState","workState","lockedAt","lockedByActorId","readAt","archivedAt","snoozedUntil","completedAt","dismissedAt","updatedAt"],pd=["type","objectId","recordId","recordVersion"],md=["type","objectId","recordId","recordVersion","record"],fd=["id","objectId","visibility","ownedBy","label","values","metadata","createdAt","updatedAt","createdBy","lastUpdatedBy","schemaVersion"],bd=["type","targetActorId","archivedCount","version","updatedAt"];function gd(e){return typeof e=="string"&&ud.includes(e)}a(gd,"isLiveEventType");function Zx(e){return _(e)&&gd(e.type)?yd(e.type,e):false}a(Zx,"isLiveEventPayload");function yd(e,t){if(!_(t))return false;switch(e){case "record.patch":return Sd(t);case "record.deleted":return vd(t);case "record.removed":return Rd(t);case "record.created":return Ed(t);case "view.projection.stale":return Cd(t);case "agent.session.patch":return Od(t);case "notification.created":return Pd(t);case "notification.recipient.patch":return jd(t);case "notification.count.patch":return Fd(t);case "notification.inbox.archived":return Vd(t);case "reflex.state.changed":return qd(t);case "reflex.run.completed":return zd(t);case "reflex.authoring.progress":return Gd(t);case "architect.draft.updated":return Ud(t);case "meeting.recording.patch":return Kd(t);case "wallet.state":return Qd(t);case "channel.revoked":return Jd(t);default:return false}}a(yd,"isLiveEventPayloadForType");function _(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(_,"isRecord");function M(e){return typeof e=="string"}a(M,"isString");function ma(e){return M(e)&&e.length>0}a(ma,"isNonEmptyString");function jt(e){return e===null||M(e)}a(jt,"isNullableString");function hd(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}a(hd,"isVersion");function J(e){if(!M(e))return false;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}a(J,"isIsoDateString");function ve(e){return e===null||J(e)}a(ve,"isNullableIsoDateString");function S(e,t){return M(e[t])}a(S,"hasString");function oe(e,t){return ma(e[t])}a(oe,"hasNonEmptyString");function N(e,t){return hd(e[t])}a(N,"hasVersion");function P(e,t){return J(e[t])}a(P,"hasIsoDateString");function I(e,t,r){return !Object.hasOwn(e,t)||r(e[t])}a(I,"hasOptional");function Ft(e,t){return Object.keys(e).every(r=>t.includes(r))}a(Ft,"hasOnlyKeys");function j(e,t){return typeof e=="string"&&t.includes(e)}a(j,"isOneOf");function Ad(e){return j(e,po)}a(Ad,"isNotificationKind");function Td(e){return j(e,mo)}a(Td,"isNotificationPriority");function wd(e){return j(e,fo)}a(wd,"isNotificationSensitivity");function fa(e){return j(e,bo)}a(fa,"isNotificationInboxState");function ba(e){return j(e,go)}a(ba,"isNotificationWorkState");function xd(e){return _(e)&&S(e,"type")&&S(e,"id")}a(xd,"isNotificationSubject");function Id(e){return _(e)&&S(e,"fieldKey")&&Object.hasOwn(e,"value")&&N(e,"version")}a(Id,"isRecordFieldPatch");function Sd(e){return e.type==="record.patch"&&S(e,"objectId")&&S(e,"recordId")&&N(e,"recordVersion")&&I(e,"label",M)&&I(e,"metadata",_)&&I(e,"fieldsWithheld",t=>t===true)&&Array.isArray(e.fieldPatches)&&e.fieldPatches.every(Id)&&S(e,"updatedAt")}a(Sd,"isRecordPatchPayload");function vd(e){return e.type==="record.deleted"&&S(e,"objectId")&&S(e,"recordId")&&N(e,"recordVersion")&&S(e,"deletedAt")}a(vd,"isRecordDeletedPayload");function Rd(e){return e.type==="record.removed"&&Ft(e,pd)&&S(e,"objectId")&&S(e,"recordId")&&N(e,"recordVersion")}a(Rd,"isRecordRemovedPayload");function Dd(e){return _(e)&&Ft(e,fd)&&S(e,"id")&&S(e,"objectId")&&j(e.visibility,["workspace","private"])&&jt(e.ownedBy)&&(e.visibility==="workspace"&&e.ownedBy===null||e.visibility==="private"&&ma(e.ownedBy))&&S(e,"label")&&_(e.values)&&I(e,"metadata",_)&&P(e,"createdAt")&&P(e,"updatedAt")&&I(e,"createdBy",M)&&I(e,"lastUpdatedBy",M)&&N(e,"schemaVersion")}a(Dd,"isRecordLiveSnapshot");function Ed(e){return e.type==="record.created"&&Ft(e,md)&&S(e,"objectId")&&S(e,"recordId")&&N(e,"recordVersion")&&Dd(e.record)&&e.record.id===e.recordId&&e.record.objectId===e.objectId}a(Ed,"isRecordCreatedPayload");function Cd(e){return e.type==="view.projection.stale"&&S(e,"viewId")&&j(e.reason,ld)}a(Cd,"isViewProjectionStalePayload");function Od(e){return e.type==="agent.session.patch"&&S(e,"sessionId")&&_(e.patch)&&N(e,"version")&&S(e,"updatedAt")}a(Od,"isAgentSessionPatchPayload");function _d(e){return _(e)&&S(e,"id")&&S(e,"tenantId")&&I(e,"senderActorId",M)&&I(e,"rootActorId",M)&&I(e,"triggeredByActorId",M)&&Ad(e.kind)&&S(e,"type")&&I(e,"subject",xd)&&S(e,"title")&&I(e,"summary",M)&&_(e.payload)&&Td(e.priority)&&wd(e.sensitivity)&&I(e,"threadKey",M)&&I(e,"idempotencyKey",M)&&I(e,"expiresAt",J)&&P(e,"createdAt")&&P(e,"updatedAt")}a(_d,"isLiveNotification");function Nd(e){return _(e)&&S(e,"id")&&S(e,"tenantId")&&S(e,"notificationId")&&S(e,"recipientActorId")&&fa(e.inboxState)&&ba(e.workState)&&I(e,"lockedAt",J)&&I(e,"lockedByActorId",M)&&I(e,"readAt",J)&&I(e,"archivedAt",J)&&I(e,"snoozedUntil",J)&&I(e,"completedAt",J)&&I(e,"dismissedAt",J)&&P(e,"createdAt")&&P(e,"updatedAt")}a(Nd,"isLiveNotificationRecipient");function kd(e){return _(e)?Object.keys(e).every(t=>cd.includes(t))&&I(e,"inboxState",fa)&&I(e,"workState",ba)&&I(e,"lockedAt",ve)&&I(e,"lockedByActorId",jt)&&I(e,"readAt",ve)&&I(e,"archivedAt",ve)&&I(e,"snoozedUntil",ve)&&I(e,"completedAt",ve)&&I(e,"dismissedAt",ve)&&I(e,"updatedAt",J):false}a(kd,"isNotificationRecipientPatch");function Pd(e){let t=_d(e.notification)?e.notification:null;return e.type==="notification.created"&&t!==null&&Array.isArray(e.recipients)&&e.recipients.length>0&&e.recipients.every(r=>Nd(r)&&r.notificationId===t.id)&&N(e,"version")&&P(e,"updatedAt")}a(Pd,"isNotificationCreatedPayload");function jd(e){return e.type==="notification.recipient.patch"&&S(e,"recipientId")&&S(e,"recipientActorId")&&kd(e.patch)&&N(e,"version")&&P(e,"updatedAt")}a(jd,"isNotificationRecipientPatchPayload");function Fd(e){return e.type==="notification.count.patch"&&S(e,"targetActorId")&&N(e,"unread")&&N(e,"pendingWork")&&N(e,"version")&&P(e,"updatedAt")}a(Fd,"isNotificationCountPatchPayload");function Vd(e){return e.type==="notification.inbox.archived"&&Ft(e,bd)&&oe(e,"targetActorId")&&N(e,"archivedCount")&&N(e,"version")&&P(e,"updatedAt")}a(Vd,"isNotificationInboxArchivedPayload");var Md=["armed","disarmed"],Ld=["authoring","compiling","replaying","promoted","failed"],Bd=["promoted","lkg"],$d=["composing","published","discarded"];function Ud(e){if(e.type!=="architect.draft.updated"||!_(e.draft))return false;let t=e.draft;return oe(t,"id")&&oe(t,"actorId")&&jt(t.agentSessionId)&&Array.isArray(t.operations)&&t.operations.every(_)&&_(t.baselines)&&j(t.status,$d)}a(Ud,"isArchitectDraftUpdatedPayload");function qd(e){return e.type==="reflex.state.changed"&&oe(e,"reflexId")&&j(e.state,Md)&&P(e,"updatedAt")}a(qd,"isReflexStateChangedPayload");function zd(e){return e.type==="reflex.run.completed"&&oe(e,"reflexId")&&oe(e,"runId")&&j(e.served,Bd)&&N(e,"version")&&N(e,"wallMs")&&P(e,"completedAt")}a(zd,"isReflexRunCompletedPayload");function Gd(e){return e.type==="reflex.authoring.progress"&&oe(e,"reflexId")&&j(e.status,Ld)&&P(e,"updatedAt")}a(Gd,"isReflexAuthoringProgressPayload");var Wd=["none","scheduled","recording","completed","failed"];function Kd(e){return e.type==="meeting.recording.patch"&&oe(e,"meetingId")&&j(e.status,Wd)&&jt(e.failureReason)&&P(e,"updatedAt")}a(Kd,"isMeetingRecordingPatchPayload");var Hd=["ok","low","exhausted","paused"],Yd=["metering-only","contract","wallet"];function Qd(e){return e.type==="wallet.state"&&j(e.status,Hd)&&j(e.mode,Yd)&&P(e,"updatedAt")}a(Qd,"isWalletStatePayload");function Jd(e){return e.type==="channel.revoked"&&S(e,"channel")&&j(e.reason,dd)}a(Jd,"isChannelRevokedPayload");function ci(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(ci,"isRecord");function Xd(e){let{channel:t}=e;return typeof t=="string"&&pa(t)?t:null}a(Xd,"payloadChannel");function nI(e){return ci(e)?Xd(e):null}a(nI,"getLiveProtocolPayloadChannel");function iI(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(iI,"isLiveEventEnvelope");var sI=["if","concat","sum","avg","count","min","max","earliest","latest","unique","first","percent_empty","percent_not_empty","count_empty","count_not_empty","count_unique"],He={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 Vt(e){return Object.hasOwn(He,e)}a(Vt,"isComputedFunctionName");var bi=class bi extends Error{constructor(t){super(t),this.name="ComputedFormulaCompileError";}};a(bi,"ComputedFormulaCompileError");var g=bi;function Lt(e){let t=Zd(e.expression),r=Mt(t,e.schema),n=wc(r.valueType);if(n!==e.returnType)throw new g(`Computed formula "${e.attributeName}" returns "${n}", expected "${e.returnType}"`);if(xa(e.returnType)&&r.optionsSource===void 0)throw new g(`Computed formula "${e.attributeName}" returns "${e.returnType}" without optionsSource`);let o=r.optionsSource===void 0?[]:[{kind:"options",source:r.optionsSource}],a=fi([...r.dependencies,...o]);return {kind:"formula",attributeName:e.attributeName,expression:e.expression,returnType:e.returnType,valueType:r.valueType,dependencies:a,ast:t,...r.optionsSource?{optionsSource:r.optionsSource}:{},...r.targetAttributeType?{targetAttributeType:r.targetAttributeType}:{},dependenciesHash:xc({expression:e.expression,returnType:e.returnType,dependencies:a})}}a(Lt,"compileComputedFormula");function wa(e){let t=new Map(e.map(o=>[o.attributeName,o])),r=new Set,n=a((o,a)=>{let s=a.indexOf(o);if(s!==-1){let f=[...a.slice(s),o];throw new g(`Computed field cycle detected: ${f.join(" -> ")}`)}if(r.has(o))return;let l=t.get(o);if(l===void 0)return;let c=[...a,o];for(let f of l.dependencies)f.kind==="computed"&&n(f.attributeName,c);r.add(o);},"visit");for(let o of e)n(o.attributeName,[]);}a(wa,"assertAcyclicComputedDependencies");function Zd(e){try{return e$1(e)}catch(t){throw t instanceof Error?new g(t.message):t}}a(Zd,"parseCompileFormula");function Mt(e,t){switch(e.kind){case "literal":return {valueType:ec(e.value),dependencies:[],...typeof e.value=="string"?{literalString:e.value}:{}};case "path":return tc(e.parts,t);case "call":return sc(e.functionName,e.args,t);case "binary":return pc(e.operator,Mt(e.left,t),Mt(e.right,t));default:return e}}a(Mt,"inferNode");function ec(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(ec,"literalToValueType");function tc(e,t){if(e.length===1){let r=e[0],n=pi(t,r);if(n===void 0)throw new g(`Unknown attribute "${r}" on object "${t.objectName}"`);return n.type==="relation"?{valueType:ic(),dependencies:[{kind:"relation",relationName:n.name,cardinality:ga(n)}],targetAttributeType:n.type}:{valueType:ya(n),dependencies:[nc(n)],optionsSource:ha(t.objectName,n),targetAttributeType:n.type}}if(e.length===2){let[r,n]=e,o=pi(t,r);if(o===void 0)throw new g(`Unknown attribute "${r}" on object "${t.objectName}"`);if(o.type!=="relation")throw new g(`Attribute "${r}" on object "${t.objectName}" is not a relation`);let a=rc(o);if(a===void 0)throw new g(`Relation "${r}" on object "${t.objectName}" is missing targetObjectName`);let s=t.relatedObjects?.[a];if(s===void 0)throw new g(`Unknown related object "${a}"`);let l=pi(s,n);if(l===void 0)throw new g(`Unknown attribute "${n}" on object "${s.objectName}"`);let c=ya(l);return {valueType:o.cardinality==="many"?ac(c):c,dependencies:[{kind:"relation",relationName:r,targetAttributeName:n,cardinality:ga(o)}],optionsSource:ha(s.objectName,l),targetAttributeType:l.type}}throw new g("Computed paths support at most one relation hop")}a(tc,"inferPath");function pi(e,t){return e.attributes.find(r=>r.name===t)}a(pi,"findAttribute");function rc(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(rc,"getRelationTargetObjectName");function ga(e){return e.cardinality??"one"}a(ga,"relationCardinality");function nc(e){return e.type==="formula"||e.type==="rollup"?{kind:"computed",attributeName:e.name}:{kind:"local",attributeName:e.name}}a(nc,"localDependencyFor");function ya(e){if(e.type==="formula"||e.type==="rollup"){if(e.returnType===void 0)throw new g(`Computed attribute "${e.name}" is missing returnType`);return oc(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(ya,"attributeToValueType");function ic(){return {kind:"collection",itemType:"text"}}a(ic,"relationToValueType");function oc(e){return e==="multiselect"?{kind:"collection",itemType:"select"}:{kind:"scalar",type:e}}a(oc,"returnTypeToValueType");function ac(e){return e.kind==="collection"?e:{kind:"collection",itemType:e.type}}a(ac,"asCollectionValueType");function ha(e,t){if(t.type==="formula"||t.type==="rollup")return xa(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(ha,"optionsSourceForAttribute");function sc(e,t,r){if(!Vt(e))throw new g(`Unknown computed function "${e}"`);let n=He[e];if(t.length<n.minArgs||n.maxArgs!==void 0&&t.length>n.maxArgs){let a=n.maxArgs===void 0||n.maxArgs===n.minArgs?String(n.minArgs):`${n.minArgs}-${n.maxArgs}`;throw new g(`Function "${e}" expects ${a} arguments, received ${t.length}`)}let o=t.map(a=>Mt(a,r));return uc(e,o)}a(sc,"inferCall");function uc(e,t){let r=fi(t.flatMap(n=>n.dependencies));switch(e){case "if":return lc(t,r);case "concat":return mc(t,`Function "${e}" does not accept collection values`),{valueType:{kind:"scalar",type:"text"},dependencies:r};case "sum":case "avg":return Aa(e,t[0],"number"),{valueType:{kind:"scalar",type:"number"},dependencies:r};case "count":case "count_empty":case "count_not_empty":case "count_unique":case "percent_empty":case "percent_not_empty":return bc(e,t[0]),{valueType:{kind:"scalar",type:"number"},dependencies:r};case "min":case "max":return fc(e,t[0]),{valueType:gc(t[0]),dependencies:r,optionsSource:t[0].optionsSource,targetAttributeType:t[0].targetAttributeType};case "earliest":case "latest":return Aa(e,t[0],"date"),{valueType:{kind:"scalar",type:"date"},dependencies:r,targetAttributeType:t[0].targetAttributeType};case "unique":return dc(t[0],r);case "first":return cc(t[0],r);default:return e}}a(uc,"inferFunctionReturn");function lc(e,t){mi(e[0].valueType,"boolean",'Function "if" condition must be boolean');let r=e[1],n=e[2],o=hc(r,n),a=Ac(r,n);if(o===void 0)throw new g('Function "if" branches must return the same type');return {valueType:o,dependencies:t,...a?{optionsSource:a}:{},targetAttributeType:r.targetAttributeType??n.targetAttributeType}}a(lc,"inferIfFunction");function dc(e,t){if(e.valueType.kind!=="collection"||e.valueType.itemType!=="select")throw new g('Function "unique" expects a select collection');return {valueType:{kind:"collection",itemType:"select"},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a(dc,"inferUniqueFunction");function cc(e,t){if(e.valueType.kind!=="collection")throw new g('Function "first" expects a collection');return {valueType:{kind:"scalar",type:e.valueType.itemType},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a(cc,"inferFirstFunction");function pc(e,t,r){let n=fi([...t.dependencies,...r.dependencies]),o=e==="+"||e==="-"||e==="*"||e==="/";if(t.valueType.kind==="collection"||r.valueType.kind==="collection")throw new g(`Cannot use collection values with ${o?"arithmetic":"comparison"} operator "${e}"`);if(o)return e==="+"&&(t.valueType.type==="text"||r.valueType.type==="text")?{valueType:{kind:"scalar",type:"text"},dependencies:n}:(mi(t.valueType,"number",`Operator "${e}" expects number operands`),mi(r.valueType,"number",`Operator "${e}" expects number operands`),{valueType:{kind:"scalar",type:"number"},dependencies:n});if(e==="=="||e==="!="){if(t.valueType.type!==r.valueType.type)throw new g(`Operator "${e}" expects operands with the same scalar type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:n}}if((t.valueType.type!=="number"||r.valueType.type!=="number")&&(t.valueType.type!=="date"||r.valueType.type!=="date"))throw new g(`Operator "${e}" expects number or date operands of the same type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:n}}a(pc,"inferBinary");function mc(e,t){for(let r of e)if(r.valueType.kind==="collection")throw new g(t)}a(mc,"ensureNoCollections");function Aa(e,t,r){if((t.valueType.kind==="collection"?t.valueType.itemType:t.valueType.type)!==r)throw new g(`Function "${e}" expects ${r} values`)}a(Aa,"ensureCollectionOrScalarType");function fc(e,t){if(t.valueType.kind!=="collection")throw new g(`Function "${e}" expects a collection`);let r=t.valueType.itemType;if(r!=="number"&&r!=="date")throw new g(`Function "${e}" expects number or date values`)}a(fc,"ensureMinMaxSource");function bc(e,t){if(t.valueType.kind!=="collection")throw new g(`Function "${e}" expects a collection`)}a(bc,"ensureCollectionSource");function mi(e,t,r){if(e.kind!=="scalar"||e.type!==t)throw new g(r)}a(mi,"ensureScalarType");function gc(e){return e.valueType.kind==="scalar"?e.valueType:{kind:"scalar",type:e.valueType.itemType}}a(gc,"sourceItemValueType");function yc(e,t){return e.kind==="scalar"?t.kind==="scalar"&&e.type===t.type:t.kind==="collection"&&e.itemType===t.itemType}a(yc,"sameValueType");function hc(e,t){if(yc(e.valueType,t.valueType)||Ta(e,t))return e.valueType;if(Ta(t,e))return t.valueType}a(hc,"resolveIfBranchValueType");function Ta(e,t){return e.valueType.kind==="scalar"&&e.valueType.type==="select"&&t.valueType.kind==="scalar"&&t.valueType.type==="text"&&t.literalString!==void 0}a(Ta,"isSelectScalarWithStringLiteral");function Ac(e,t){let r=e.optionsSource,n=t.optionsSource;if(r!==void 0&&n!==void 0&&!Tc(r,n))throw new g('Function "if" branches use incompatible options sources');return r??n}a(Ac,"resolveIfOptionsSource");function Tc(e,t){return e.objectName===t.objectName&&e.attributeName===t.attributeName&&e.attributeId===t.attributeId}a(Tc,"sameOptionsSource");function xa(e){return e==="select"||e==="multiselect"}a(xa,"isSelectLikeReturnType");function wc(e){if(e.kind==="scalar")return e.type;if(e.itemType==="select")return "multiselect";throw new g(`Collection item type "${e.itemType}" cannot be used as a computed return type`)}a(wc,"valueTypeToReturnType");function fi(e){let t=new Set,r=[];for(let n of e){let o=JSON.stringify(Ye(n));t.has(o)||(t.add(o),r.push(n));}return r}a(fi,"uniqueDependencies");function xc(e){let t=e.dependencies.map(r=>Ye(r)).sort((r,n)=>Ia(JSON.stringify(r),JSON.stringify(n)));return JSON.stringify(Ye({expression:e.expression,returnType:e.returnType,dependencies:t}))}a(xc,"createDependenciesHash");function Ye(e){return Array.isArray(e)?e.map(t=>Ye(t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>Ia(t,r)).map(([t,r])=>[t,Ye(r)])):e}a(Ye,"stableNormalize");function Ia(e,t){return e<t?-1:e>t?1:0}a(Ia,"compareStrings");function Ic(e){return e.function==="count"?`count(${e.relationAttribute})`:`${Rc(e.function)}(${e.relationAttribute}.${e.targetAttribute})`}a(Ic,"rollupToFormulaExpression");function Sc(e,t){if(e.function==="count")return "number";let r=Dc(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(!Cc(r.type))throw new g('Rollup "original" requires a select, status, or multiselect target');return "multiselect";default:return e.function}}a(Sc,"inferRollupReturnType");function va(e,t){let r=Ic(e),n=Sc(e,t);return {...Lt({attributeName:e.name,expression:r,returnType:n,schema:vc(e,t)}),kind:"rollup"}}a(va,"compileRollupAttribute");function vc(e,t){return {...t,attributes:t.attributes.map(r=>r.name===e.relationAttribute&&r.type==="relation"?{...r,cardinality:"many"}:r)}}a(vc,"schemaWithRollupRelationAsMany");function Rc(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(Rc,"rollupFunctionToFormulaFunction");function Dc(e,t){let r=Sa(t,e.relationAttribute);if(r===void 0)throw new g(`Unknown relation attribute "${e.relationAttribute}" on object "${t.objectName}"`);if(r.type!=="relation")throw new g(`Attribute "${e.relationAttribute}" on object "${t.objectName}" is not a relation`);let n=Ec(r);if(n===void 0)throw new g(`Relation "${e.relationAttribute}" on object "${t.objectName}" is missing targetObjectName`);let o=t.relatedObjects?.[n];if(o===void 0)throw new g(`Unknown related object "${n}"`);let a=Sa(o,e.targetAttribute);if(a===void 0)throw new g(`Unknown attribute "${e.targetAttribute}" on object "${o.objectName}"`);return a}a(Dc,"findRollupTargetAttribute");function Sa(e,t){return e.attributes.find(r=>r.name===t)}a(Sa,"findAttribute");function Ec(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(Ec,"getRelationTargetObjectName");function Cc(e){return e==="select"||e==="status"||e==="multiselect"}a(Cc,"isSelectLikeAttributeType");function re(e,t){switch(e.kind){case "literal":return e.value;case "path":return _c(t,e.parts);case "binary":return Nc(e.operator,re(e.left,t),re(e.right,t));case "call":return Oc(e.functionName,e.args,t);default:return e}}a(re,"evaluateAst");function Oc(e,t,r){if(Pc(e),jc(e,t.length),e==="if"){let n=re(t[0],r);return n===null?null:re(n?t[1]:t[2],r)}return Fc(e,t.map(n=>re(n,r)))}a(Oc,"evaluateCallNode");function _c(e,t){return t.reduce((r,n)=>_a(r,n),e)}a(_c,"resolvePath");function _a(e,t){if(Array.isArray(e))return e.map(n=>_a(n,t));if(!Oa(e))return null;if(Object.hasOwn(e,t))return e[t]??null;let r=e.values;return Oa(r)&&Object.hasOwn(r,t)?r[t]??null:null}a(_a,"resolvePathPart");function Nc(e,t,r){switch(e){case "+":return kc(t,r);case "-":return $t(t,r,(n,o)=>n-o);case "*":return $t(t,r,(n,o)=>n*o);case "/":return $t(t,r,(n,o)=>n/o);case ">":return Bt(t,r,n=>n>0);case "<":return Bt(t,r,n=>n<0);case ">=":return Bt(t,r,n=>n>=0);case "<=":return Bt(t,r,n=>n<=0);case "==":return Ra(t,r);case "!=":{let n=Ra(t,r);return n===null?null:!n}default:return e}}a(Nc,"evaluateBinary");function kc(e,t){return typeof e=="string"||typeof t=="string"?`${e??""}${t??""}`:$t(e,t,(r,n)=>r+n)}a(kc,"add");function Bt(e,t,r){let n=Na(e,t);return n===null?null:r(n)}a(Bt,"compareWith");function Na(e,t){if(!Re([e,t]))return null;let r=De(e),n=De(t);if(r!==null&&n!==null)return r-n;let o=hi(e),a=hi(t);return o&&a?o.getTime()-a.getTime():null}a(Na,"compare");function Ra(e,t){return e===t?true:e==null||t===null||t===void 0?false:Re([e,t])?Na(e,t)===0:null}a(Ra,"equalScalar");function Pc(e){if(!Vt(e))throw new Error(`Unknown computed function "${e}"`)}a(Pc,"assertComputedFunctionName");function jc(e,t){let{minArgs:r,maxArgs:n}=He[e];if(t>=r&&t<=(n??Number.POSITIVE_INFINITY))return;let o=n===void 0?`at least ${r}`:`between ${r} and ${n}`;throw new Error(`Function "${e}" expects ${o} arguments, received ${t}`)}a(jc,"validateArity");function Fc(e,t){switch(e){case "concat":return t.filter(r=>r!=null).map(String).join("");case "sum":return Re(t)?gi(t).reduce((r,n)=>r+n,0):null;case "avg":{if(!Re(t))return null;let r=gi(t);return r.length>0?r.reduce((n,o)=>n+o,0)/r.length:null}case "count":return pe(t[0]).length;case "min":return Da(t,"min");case "max":return Da(t,"max");case "earliest":return yi(t,"min");case "latest":return yi(t,"max");case "unique":return Ca(pe(t[0]));case "first":return pe(t[0]).find(r=>r!=null)??null;case "percent_empty":return Ea(t[0],true);case "percent_not_empty":return Ea(t[0],false);case "count_empty":return pe(t[0]).filter(a$1).length;case "count_not_empty":return pe(t[0]).filter(r=>!a$1(r)).length;case "count_unique":return Ca(pe(t[0])).length;default:return e}}a(Fc,"evaluateCall");function gi(e){return Ut(e).map(De).filter(t=>t!==null)}a(gi,"numericValues");function Re(e){let t=new Set;for(let r of Ut(e))Ai(r)&&t.add(ka(r));return t.size<=1}a(Re,"areCommensurable");function ka(e){return e.code.toUpperCase()}a(ka,"currencyCode");function $t(e,t,r){if(!Re([e,t]))return null;let n=De(e),o=De(t);if(n===null||o===null)return null;let a=r(n,o);return Number.isFinite(a)?a:null}a($t,"numericBinary");function Da(e,t){if(!Re(e))return null;let r=gi(e);return r.length>0?t==="min"?Math.min(...r):Math.max(...r):yi(e,t)}a(Da,"minMax");function yi(e,t){let r=Ut(e).map(hi).filter(a=>a!==null);if(r.length===0)return null;let n=r.map(a=>a.getTime()),o=t==="min"?Math.min(...n):Math.max(...n);return new Date(o).toISOString()}a(yi,"dateMinMax");function Ea(e,t){let r=pe(e);return r.length===0?0:r.filter(o=>a$1(o)===t).length/r.length}a(Ea,"percentByEmptyState");function Ca(e){let t=new Set,r=[];for(let n of e){if(a$1(n))continue;let o=Vc(n);t.has(o)||(t.add(o),r.push(n));}return r}a(Ca,"uniqueNonEmpty");function pe(e){return e==null?[]:Array.isArray(e)?Ut(e):[e]}a(pe,"collectionItems");function Ut(e){return e.flat(Number.POSITIVE_INFINITY)}a(Ut,"flatten");function De(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 Ai(e)&&Number.isFinite(e.value)?e.value:null}a(De,"toFiniteNumber");function Ai(e){return typeof e=="object"&&e!==null&&typeof e.value=="number"&&typeof e.code=="string"}a(Ai,"isCurrencyValue");function hi(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e!="string"){let r=he(e);if(r===null)return null;let n=new Date(r);return Number.isNaN(n.getTime())?null:n}let t=new Date(e);return Number.isNaN(t.getTime())?null:t}a(hi,"toDate");function Vc(e){if(Ai(e))return `currency:${ka(e)}:${e.value}`;let t=De(e);return t!==null?`number:${t}`:e instanceof Date?`date:${e.toISOString()}`:`${typeof e}:${JSON.stringify(e)}`}a(Vc,"uniqueKey");function Oa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(Oa,"isPlainRecord");function Mc(e,t,r){if(e==null)return null;let n=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:r!==void 0?Number(o.toFixed(r)):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=n(o);if(a!==null)return a}return null}return n(e);case "multiselect":return Array.isArray(e)?e.flatMap(o=>{if(o==null)return [];let a=n(o);return a===null?[]:[a]}):n(e)===null?[]:[String(e)];default:{let o=t;throw new Error(`Unsupported computed return type: ${o}`)}}}a(Mc,"formatComputedResult");function wI(e,t){return re(e,t)}a(wI,"evaluateComputedAst");function xI(e,t){return re(e$1(e),t)}a(xI,"evaluateComputedFormula");function II(e,t,r,n){try{let o=re(e$1(e),t);return {value:r?Mc(o,r,n):o}}catch(o){return {value:null,error:o instanceof Error?o.message:String(o)}}}a(II,"evaluateComputedFormulaWithResult");var RI=[{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 Pa=a(e=>a$1(e)||Array.isArray(e)&&e.length===0,"isEmpty"),L=a(e=>e==null?"":String(e),"toStr"),Gt=a(e=>{if(a$1(e))return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null},"toNum"),Wt=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"),qt=a(e=>Array.isArray(e)?e:e==null?[]:[e],"toArr"),Lc=a((e,t,r)=>{let n=Gt(e),o=Gt(t);return n!==null&&o!==null&&r(n,o)},"compareNumbers"),Bc=a((e,t,r)=>{let n=Wt(e),o=Wt(t);return n!==null&&o!==null&&r(n.getTime(),o.getTime())},"compareDates"),ja=a((e,t,r)=>{if(r.type==="number"||r.type==="currency"){let n=Gt(e),o=Gt(t);if(n!==null&&o!==null)return n===o}return L(e)===L(t)},"equalsForAttr");function OI(e,t){return e?e==="checkbox":typeof t=="boolean"}a(OI,"isCheckboxEquality");var zt=a(e=>({appliesTo:["number","currency","date","formula"],evaluateInMemory:a((t,r,n)=>n.type==="date"?Bc(t,r,e):Lc(t,r,e),"evaluateInMemory")}),"orderingSpec"),Kt={is:{appliesTo:["text","phone","number","currency","checkbox","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,r)=>r.type==="checkbox"?e===true==(t===true):ja(e,t,r),"evaluateInMemory")},is_not:{appliesTo:["text","phone","number","currency","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,r)=>!ja(e,t,r),"evaluateInMemory")},contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>L(e).toLowerCase().includes(L(t).toLowerCase()),"evaluateInMemory")},not_contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>!L(e).toLowerCase().includes(L(t).toLowerCase()),"evaluateInMemory")},starts_with:{appliesTo:["text","phone"],evaluateInMemory:a((e,t)=>L(e).toLowerCase().startsWith(L(t).toLowerCase()),"evaluateInMemory")},ends_with:{appliesTo:["text"],evaluateInMemory:a((e,t)=>L(e).toLowerCase().endsWith(L(t).toLowerCase()),"evaluateInMemory")},is_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>Pa(e),"evaluateInMemory")},is_not_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>!Pa(e),"evaluateInMemory")},less_than:zt((e,t)=>e<t),greater_than:zt((e,t)=>e>t),less_or_equal:zt((e,t)=>e<=t),greater_or_equal:zt((e,t)=>e>=t),is_within:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let r=Wt(e),n=S$1(t);return r&&n?r.getTime()>=n.startMs&&r.getTime()<n.endMs:false},"evaluateInMemory")},on_day_month:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let r=Wt(e);if(!r)return false;let n=t;return r.getMonth()+1===n.month&&r.getDate()===n.day},"evaluateInMemory")},any_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let r=qt(t).map(L);return qt(e).map(L).some(o=>r.includes(o))},"evaluateInMemory")},none_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let r=qt(t).map(L);return !qt(e).map(L).some(o=>r.includes(o))},"evaluateInMemory")}};var $c=a((e,t)=>({id:`system:${e}`,name:e,label:e,type:t,system:true}),"systemAttribute"),Uc=[...Object.entries(V).map(([e,t])=>$c(e,t))];function $I(e,t,r){let n=t;return qc(e,{...t.values,id:t.id,objectId:t.objectId,objectName:n.objectName,tenantId:n.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},[...r,...Uc])}a($I,"evaluateRecordFilterState");function qc(e,t,r){if(e.rules.length===0)return true;let n=new Map(r.map(a=>[a.name,a])),o=e.combinator==="or"?"some":"every";return e.rules[o](a=>zc(a,t,n))}a(qc,"evaluateFilterState");function zc(e,t,r){let n=r.get(e.attribute);if(!n)return false;if(e.property&&n.type==="location"){if(!(g$1(e.property)&&h$2(e.operator)))return false;let l=Kt[e.operator];if(!l)return false;let c=t[e.attribute],f=typeof c=="object"&&c!==null?c[e.property]:void 0;return Ti(l,"text",e.operator,f,e.value,n)}if(e.property){let l=Co(n).find(R=>R.name===e.property);if(!l)return false;let c=K$1(e.operator),f=Kt[c];if(!f?.appliesTo.includes(l.type))return false;let x=t[e.attribute],W=(Array.isArray(x)?x:x==null?[]:[x]).some(R=>{if(typeof R!="object"||R===null)return false;let X=R.props;return typeof X!="object"||X===null?false:Ti(f,l.type,c,X[e.property],e.value,l)});return (e.quantifier??J$1(e.operator))==="none"?!W:W}let o=Kt[e.operator];if(!o||!o.appliesTo.includes(n.type))return false;let a=t[e.attribute],s=n.type==="relation"||n.type==="document"||n.type==="user"?Kc(a):a;return Ti(o,n.type,e.operator,s,e.value,n)}a(zc,"evaluateRule");function Ti(e,t,r,n,o,a){let[s,l]=Gc(t,r,n,o);return t==="phone"&&l===""&&r==="contains"?false:t==="phone"&&l===""&&r==="not_contains"?true:e.evaluateInMemory(s,l,a)}a(Ti,"evaluateNormalizedComparands");function Gc(e,t,r,n){return e==="date"&&(t==="is"||t==="is_not")?[Fa(r),Fa(n)]:e==="phone"?Wc(r,n):[Va(e,r),Va(e,n)]}a(Gc,"normalizeOperatorComparands");function Fa(e){let t=ne(e)?he(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 r=new Date(t);return Number.isNaN(r.getTime())?null:r.toISOString().slice(0,10)}a(Fa,"normalizeUtcCalendarDay");function Wc(e,t){let r=typeof t=="object"&&t!==null?t:{},n=typeof r.countryCode=="string"?r.countryCode:void 0,o=a(a=>{let s=typeof a=="object"&&a!==null?a:{phoneNumber:a};if(typeof s.phoneNumber!="string")return null;if(!n)return a$3(s.phoneNumber);let l=typeof s.countryCode=="string"?s.countryCode:n;return `${l}:${b$2(s.phoneNumber,l)}`},"normalizeOne");return [o(e),o(t)]}a(Wc,"normalizePhoneComparands");function Va(e,t){return e==="currency"?H$1(t):e==="date"?ne(t)?he(t):t instanceof Date?Number.isNaN(t.getTime())?null:t.toISOString():t:t}a(Va,"normalizeComparableValue");function Kc(e){let t=a(r=>typeof r!="object"||r===null?r:r.id,"normalizeOne");return Array.isArray(e)?e.map(t):t(e)}a(Kc,"normalizeReferenceIds");var Ma="today";function Ht(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}a(Ht,"dateInTimezone");function Hc(e,t){if(!("defaultValue"in e))return;let{defaultValue:r}=e;return e.type!=="date"||r!==Ma?r:e.includeTime?t.now.toISOString():Ht(t.now,t.timezone)}a(Hc,"resolveAttributeDefaultValue");function YI(e,t,r){if(e.combinator==="or"&&e.rules.length>1)return {};let n=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=n.get(a.attribute);if(!s)continue;let l=Yc(a,r);l!==void 0&&(o[a.attribute]=j$1(s).storage.cardinality==="many"?[l]:l);}return o}a(YI,"deriveCreateDefaultsFromFilters");function Yc(e,t){if(e.operator==="is")return D$1(e.value)?La(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 r=e.value[0];return D$1(r)?La(r,t):r}}a(Yc,"extractDeterministicValue");function La(e,t){if(t){if(e.dynamic==="actor")return t.userId;if(e.anchor==="today")return Ht(t.now,t.timezone);if(e.anchor==="now")return t.now.toISOString()}}a(La,"resolveDynamicValue");var XI={status:"connector_status",error:"connector_error",provider:"connector_provider"};var Qc=(t=>(t.Desktop="desktop",t))(Qc||{});var tS=["force","skip"],rS=["none","all","external_only"],nS="x-fake-signature",iS={override:null,status:"none",failureReason:null,botId:null};var Jc=/^Session \d+$/;function Ba(e){let t=e.replace(/\s+/g," ").trim().replace(/[.!?]+$/,"");return t?t.length>60?`${t.slice(0,59).trimEnd()}...`:t:"New conversation"}a(Ba,"buildAgentFallbackTitle");function Xc(e){let t=e.generated?.trim();return t&&!Jc.test(t)?t:e.firstUserText?Ba(e.firstUserText):e.emptyLabel}a(Xc,"conversationDisplayTitle");var wi=/^[a-z0-9][a-z0-9-]{0,62}$/;function Zc(e){if(!wi.test(e))throw new h(`Invalid schema source id "${e}": expected a lowercase slug matching ${wi}`,[])}a(Zc,"assertSchemaSourceId");function ep(e){return {label:e.label,description:e.description??null,icon:e.icon??null,config:e.config,default:e.default??false,metadata:e.metadata??null}}a(ep,"viewSyncPayload");function mS(e){let{attributeRemovals:t,objectRemovals:r,renames:n}=e.destructive;return t.length>0||r.length>0||n.length>0}a(mS,"hasDestructiveEntries");var q={objectAdditions:20,totalMutations:500,serializedBytes:512*1024};function Ii(e){return e instanceof Error?e.message:String(e)}a(Ii,"errorMessage");var tp=z$1.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 Ka=z$1.string().min(1).superRefine((e,t)=>{try{Be(e);}catch(r){t.addIssue({code:z$1.ZodIssueCode.custom,message:Ii(r)});}}).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).'),rp=z$1.string().min(1).superRefine((e,t)=>{w$1(e)&&t.addIssue({code:z$1.ZodIssueCode.custom,message:`"${e}" is a reserved object name (${C.join(", ")}) and cannot be used for a new object.`});try{Le(e);}catch(r){t.addIssue({code:z$1.ZodIssueCode.custom,message:Ii(r)});}}).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 Ha(e){return e.superRefine((t,r)=>{try{let n=n$1(t.type,{...t.config??{},description:t.description}),o=Object.keys(t.config??{}).filter(a=>!Object.hasOwn(n,a));o.length>0&&r.addIssue({code:"unrecognized_keys",keys:o,path:["config"],message:`Unrecognized attribute config key${o.length===1?"":"s"}: ${o.join(", ")}`});}catch(n){if(n instanceof h){for(let o of n.errors)r.addIssue({code:z$1.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}r.addIssue({code:z$1.ZodIssueCode.custom,path:["config"],message:`Config for type "${t.type}" is invalid or incomplete: ${Ii(n)}`});}})}a(Ha,"withConfigCheck");var Ya=z$1.object({objectName:z$1.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:Ka,label:z$1.string().min(1).max(128).describe("Human-readable display label shown in the UI. 1-128 characters, cannot be empty."),type:tp,config:z$1.record(z$1.string(),z$1.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$1.boolean().optional().describe("Whether the attribute must have a value on every record. Defaults to false (optional)."),description:z$1.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),np=Ha(Ya),ip=Ha(Ya.omit({objectName:true})),op=z$1.object({name:rp,label:z$1.string().min(1).describe('Human-readable singular display label (e.g. "Devis").'),pluralLabel:z$1.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:z$1.string().optional().describe("Help text describing what this object represents."),icon:c.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:Ae.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$1.array(ip).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(),Qa=z$1.object({attributeRemovals:z$1.array(z$1.object({objectName:z$1.string().min(1).describe("Object the attribute is removed from."),attributeName:z$1.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$1.array(z$1.object({objectName:z$1.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$1.array(z$1.object({objectName:z$1.string().min(1).describe("Object the renamed attribute belongs to."),from:z$1.string().min(1).describe("Current attribute name. Must already exist and not be a system attribute."),to:Ka.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:[]}),Ja=z$1.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."),$a="The COMPLETE config this view should end up with \u2014 not a patch. Copy the baseline returned by get_default_view and edit it, preserving every tab and setting you are not changing: anything you omit is dropped. To change the columns shown, set `tabs[].columns` (an array of attribute names) \u2014 there is no top-level `columns` on either view type. For a detail view's side panel, set `sidePanel.attributes`. Every attribute name listed must already exist on the object, or be created earlier in this same plan. ONE EXCEPTION to omit-is-dropped: a tab with `type: \"custom\"` renders a component belonging to the application, which you cannot describe or recreate. Copy every such tab through from the baseline exactly as it came, `name`, `component` and `props` untouched \u2014 dropping one, inventing one, or altering any of those three is rejected rather than applied (`name` is the tab's address in links, not its wording). Its `label` and `icon` you may change.",Ua="Opaque token returned by get_default_view alongside the baseline you edited. REQUIRED when the object already exists \u2014 it proves you authored against the baseline that is still current. Must be OMITTED when this plan creates the object, which has no baseline yet.",qa=z$1.string().min(1).describe("Name of the object whose default view of this type is replaced. Not a view name \u2014 a plan can only replace an object's deterministic default view, never create a view or target a non-default one."),ap=z$1.discriminatedUnion("viewType",[z$1.object({objectName:qa,viewType:z$1.literal("list").describe("Targets the object's default list view (the grid)."),canonicalConfig:ma$1.describe($a),baselineToken:z$1.string().min(1).optional().describe(Ua)}).strict(),z$1.object({objectName:qa,viewType:z$1.literal("detail").describe("Targets the object's default detail view (the single-record view)."),canonicalConfig:na$1.describe($a),baselineToken:z$1.string().min(1).optional().describe(Ua)}).strict()]);var za=z$1.string().regex(/^[0-9a-f]{64}$/,"Expected a lowercase SHA-256 hash"),Ga={baseConfigHash:za.nullable(),targetConfigHash:za,baselineOrigin:z$1.enum(["persisted","generated","absent"])},sp=z$1.discriminatedUnion("viewType",[z$1.object({objectName:z$1.string().min(1),viewType:z$1.literal("list"),canonicalConfig:ma$1,...Ga}).strict(),z$1.object({objectName:z$1.string().min(1),viewType:z$1.literal("detail"),canonicalConfig:na$1,...Ga}).strict()]).superRefine((e,t)=>{let r=e.baselineOrigin!=="absent";r!==(e.baseConfigHash!==null)&&t.addIssue({code:"custom",path:["baseConfigHash"],message:r?`A ${e.baselineOrigin} baseline requires baseConfigHash`:"An absent baseline requires baseConfigHash to be null"});});function Xa(e){return z$1.object({objects:z$1.array(op).default([]).describe("New objects to create, with their attributes inline."),attributes:z$1.array(np).default([]).describe("Attributes to add to existing or same-plan objects."),viewUpdates:z$1.array(e).default([]).describe("Complete target configs for deterministic default views; never view names.")}).strict().default({objects:[],attributes:[],viewUpdates:[]})}a(Xa,"buildAdditiveSchema");function xi(e,t=[],r=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(r.has(e))return {path:t,message:"Plan input cannot contain circular references"};if(Array.isArray(e)){r.add(e);for(let s of Reflect.ownKeys(e))if(s!=="length"&&(typeof s=="symbol"||!/^(0|[1-9]\d*)$/.test(s)))return r.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 r.delete(e),{path:[...t,s],message:"Plan input cannot contain sparse arrays"};let l=xi(e[s],[...t,s],r);if(l)return r.delete(e),l}return r.delete(e),null}let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return {path:t,message:"Plan input must contain only plain JSON objects"};r.add(e);let o=e,a=Reflect.ownKeys(o);for(let s of a){let l=Object.getOwnPropertyDescriptor(o,s);if(typeof s=="symbol"||!(l?.enumerable&&"value"in l))return r.delete(e),{path:[...t,s],message:"Plan input objects must contain enumerable JSON data properties only"}}for(let s of a.sort()){let l=xi(o[s],[...t,s],r);if(l)return r.delete(e),l}return r.delete(e),null}a(xi,"findJsonSafetyIssue");function up(e){let t=[];return e.additive.objects.forEach((r,n)=>{t.push(["additive","objects",n]),r.attributes.forEach((o,a)=>{t.push(["additive","objects",n,"attributes",a]);});}),e.additive.attributes.forEach((r,n)=>{t.push(["additive","attributes",n]);}),e.additive.viewUpdates.forEach((r,n)=>{t.push(["additive","viewUpdates",n]);}),e.destructive.attributeRemovals.forEach((r,n)=>{t.push(["destructive","attributeRemovals",n]);}),e.destructive.objectRemovals.forEach((r,n)=>{t.push(["destructive","objectRemovals",n]);}),e.destructive.renames.forEach((r,n)=>{t.push(["destructive","renames",n]);}),t}a(up,"mutationPaths");function Za(e,t){e.additive.objects.length>q.objectAdditions&&t.addIssue({code:"too_big",origin:"array",maximum:q.objectAdditions,inclusive:true,path:["additive","objects",q.objectAdditions],message:`A schema plan can add at most ${q.objectAdditions} objects`});let r=up(e);r.length>q.totalMutations&&t.addIssue({code:"too_big",origin:"array",maximum:q.totalMutations,inclusive:true,path:r[q.totalMutations],message:`A schema plan can contain at most ${q.totalMutations} mutations; received ${r.length}`});}a(Za,"addPlanLimitIssues");function es(e,t){let r=xi(e);if(r)return t.addIssue({code:"custom",path:r.path,message:r.message}),z$1.NEVER;let n=new TextEncoder().encode(b$3(e)).byteLength;return n>q.serializedBytes?(t.addIssue({code:"too_big",origin:"string",maximum:q.serializedBytes,inclusive:true,path:[],message:`A schema plan can serialize to at most ${q.serializedBytes} UTF-8 bytes; received ${n}`}),z$1.NEVER):e}a(es,"boundSerializedPlanInput");var lp=Xa(ap),dp=Xa(sp),Wa=z$1.object({schemaPlanVersion:z$1.literal(2).describe("Required proposal contract version."),summary:Ja,additive:lp,destructive:Qa}).strict().superRefine((e,t)=>{let r=new Set(e.additive.objects.map(n=>n.name));e.additive.viewUpdates.forEach((n,o)=>{let a=["additive","viewUpdates",o,"baselineToken"];if(r.has(n.objectName)){n.baselineToken!==void 0&&t.addIssue({code:"custom",path:a,message:"A view target for an object added by this plan must not include baselineToken"});return}n.baselineToken===void 0&&t.addIssue({code:"custom",path:a,message:"A view target for an existing object requires baselineToken"});}),Za(e,t);}),RS=Object.assign(z$1.preprocess(es,Wa),{shape:Wa.shape}),cp=z$1.object({schemaPlanVersion:z$1.literal(2),summary:Ja,additive:dp,destructive:Qa}).strict().superRefine(Za),DS=z$1.preprocess(es,cp);var T=z$1.number().finite().nonnegative(),rs=z$1.enum(To),Si=z$1.enum(wo),vi=z$1.enum(xo),ns=z$1.object({provider:rs,model:z$1.string().min(1)}).strict(),kS=z$1.object({speed:Si.optional(),reasoning:vi.optional()}).strict(),is=z$1.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),pp=z$1.object({model:ns.optional(),speed:Si.optional(),reasoning:vi.optional(),imageModel:is.optional()}).strict(),PS=pp.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"}),jS=z$1.object({model:ns.nullable().optional(),speed:Si.nullable().optional(),reasoning:vi.nullable().optional(),imageModel:is.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"}),os=z$1.object({label:z$1.string(),denied:z$1.boolean().optional(),deletion:z$1.object({target:z$1.string().optional(),count:T.optional(),restorableDays:T.optional()}).strict().optional(),counts:z$1.record(z$1.string(),T).optional(),warnings:z$1.array(z$1.string()).optional()}).strict(),mp=z$1.union([z$1.object({type:z$1.literal("text"),text:z$1.string()}).strict(),z$1.object({type:z$1.literal("reasoning"),text:z$1.string()}).strict(),z$1.object({type:z$1.literal("system"),code:z$1.enum(mr)}).strict(),z$1.object({type:z$1.literal("error"),error:z$1.string(),errorClass:z$1.string().optional()}).strict(),z$1.object({type:z$1.literal("tool"),toolCallId:z$1.string(),name:z$1.string(),args:z$1.record(z$1.string(),z$1.unknown()),result:z$1.unknown().optional(),error:z$1.string().optional(),errorCode:z$1.enum(["output_limit_reached","interrupted"]).optional(),state:z$1.enum(["streaming","running","completed","error","pending","approval-requested","approval-responded","approval-dispatched"]),durationMs:T.optional(),approvalId:z$1.string().optional(),approvalImpact:os.optional(),approved:z$1.boolean().optional(),approvalReason:z$1.string().optional(),approvalRelaxableByAuto:z$1.boolean().optional()}).strict(),z$1.object({type:z$1.literal("file"),fileId:z$1.string(),name:z$1.string(),mimeType:z$1.string()}).strict(),z$1.object({type:z$1.literal("compaction"),state:z$1.literal("in-progress"),reason:z$1.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:T.optional(),reportedTokens:T.optional()}).strict(),z$1.object({type:z$1.literal("compaction"),state:z$1.literal("completed"),tokensBefore:T,tokensAfter:T,tokensSaved:T,strategy:z$1.enum(["no-op","summary","truncation"]),durationMs:T,summary:z$1.string().optional()}).strict(),z$1.object({type:z$1.literal("compaction"),state:z$1.literal("failed"),reason:z$1.string(),durationMs:T.optional()}).strict()]),fp=z$1.object({id:z$1.string(),name:z$1.string(),mimeType:z$1.string(),size:T}).strict(),bp=z$1.object({id:z$1.string(),type:z$1.string().transform(e=>e),entityId:z$1.string(),label:z$1.string(),objectName:z$1.string().optional(),startIndex:T,endIndex:T}).strict(),gp=z$1.object({provider:rs,model:z$1.string(),maxTokens:T.optional(),contextWindow:T.optional()}).strict(),yp=z$1.union([z$1.date(),z$1.string().datetime({offset:true}).transform(e=>new Date(e))]),ts=z$1.object({id:z$1.string(),sessionId:z$1.string(),tenantId:z$1.string().optional(),runId:z$1.string().optional(),role:z$1.enum(["user","assistant","system","tool"]),parts:z$1.array(mp),attachments:z$1.array(fp).optional(),mentions:z$1.array(bp).optional(),model:gp.optional(),tokenUsage:z$1.object({input:T,output:T}).strict().optional(),metadata:z$1.record(z$1.string(),z$1.unknown()).optional(),createdAt:yp}).strict(),hp=z$1.object({id:z$1.string(),description:z$1.string(),status:z$1.enum(["pending","in_progress","completed","blocked"]),result:z$1.string().optional(),updatedAt:T.optional()}).strict(),Ap=z$1.object({id:z$1.string(),sessionId:z$1.string(),status:z$1.enum(["active","completed","abandoned"]),todos:z$1.array(hp),version:T,createdAt:z$1.string(),updatedAt:z$1.string(),completedAt:z$1.string().optional()}).strict(),as={"session-named":z$1.object({name:z$1.string()}).strict(),"compaction-start":z$1.object({reason:z$1.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:T.optional(),reportedTokens:T.optional()}).strict(),"compaction-end":z$1.object({tokensBefore:T,tokensAfter:T,tokensSaved:T,strategy:z$1.enum(["no-op","summary","truncation"]),durationMs:T,summary:z$1.string().optional()}).strict(),"compaction-failed":z$1.object({reason:z$1.string()}).strict(),usage:z$1.object({messageId:z$1.string().min(1).optional(),inputTokens:T,outputTokens:T,totalTokens:T,cacheReadTokens:T.optional(),cacheCreationTokens:T.optional(),contextWindow:T,residentTokens:T,utilization:z$1.number().finite().min(0).max(1),costUsd:T.optional()}).strict(),"message-persisted":z$1.object({message:ts}).strict(),"message-updated":z$1.object({message:ts}).strict(),"todo-plan-update":z$1.object({plan:Ap}).strict(),"approval-context":z$1.object({approvalId:z$1.string(),toolCallId:z$1.string(),impact:os.optional(),relaxableByAuto:z$1.boolean().optional()}).strict(),"session-state":z$1.object({state:z$1.object({phase:z$1.enum(["queued","running","parked","terminal"]),parkedOn:z$1.enum(["human","agents"]).optional(),humanRequestIds:z$1.array(z$1.string()).optional(),outcome:z$1.enum(["completed","failed","cancelled","timeout","expired"]).optional()}).strict(),version:z$1.number().int().positive(),updatedAt:z$1.string().datetime({offset:true})}).strict()};function Tp(e){return e in as}a(Tp,"isAgentUIDataName");function wp(e){return new h("Invalid agent UI message chunk",e.map(t=>({path:t.path.map(String),message:t.message,code:t.code})))}a(wp,"agentUIValidationError");function xp(e){if(typeof e!="object"||e===null||typeof e.type!="string")throw new h("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("Invalid agent UI message chunk",[{path:["type"],message:"Expected agent data chunk type",code:"invalid_value"}]);let r=t.slice(5);if(!Tp(r))throw new h("Invalid agent UI message chunk",[{path:["type"],message:`Unknown agent UI data type: ${r}`,code:"invalid_value"}]);let n=z$1.object({type:z$1.literal(`data-${r}`),id:z$1.string().optional(),data:as[r],transient:z$1.boolean().optional()}).strict().safeParse(e);if(!n.success)throw wp(n.error.issues);return n.data}a(xp,"assertCustomAgentUIMessageChunk");function FS(e,t,r){return xp({type:`data-${e}`,...r?.id!==void 0?{id:r.id}:{},data:t,...r?.transient!==void 0?{transient:r.transient}:{}})}a(FS,"agentDataChunk");function Yt(e){return e}a(Yt,"defineOperation");function A(e,t,r){let n=t==="atomic"?"none":t==="local"?"if-not-visible":"follow";return o=>{let a=r?.(o);return {impact:t,navigation:n,focus:{...e(o),...a===void 0?{}:{propertyPath:a}}}}}a(A,"definePresentation");var Ri={id:z$1.string().min(1)},D={...Ri,viewId:z$1.string().min(1)},Ip={add_tab:"add_list_tab",add_list_tab:"add_tab"};function ae(e,t,r,n,o){let a=e.views.find(s=>s.id===t);if(!a)throw new h(`View "${t}" is not in the draftable state`,[]);if(a.type!==r){let s=Ip[o]??`a ${a.type}-view operation`;throw new h(`${o} targets ${a.type} view "${t}"; use ${s}`,[])}return {...e,views:e.views.map(s=>{if(s.id!==t)return s;let{derived:l,...c}=n(s);return c})}}a(ae,"mapView");function us(e,t,r){let n=[...e],[o]=n.splice(t,1);return n.splice(r,0,o),n}a(us,"moveWithin");function Qe(e,t,r){if(t.length!==e.length)throw new h(`${r} order lists ${t.length} ids for ${e.length} items`,[]);return t.map(n=>{let o=e.find(a=>a.id===n);if(!o)throw new h(`${r} "${n}" is not in this collection`,[]);return o})}a(Qe,"reorderById");function F(e,t,r,n){return ae(e,t,"detail",r,n)}a(F,"mapDetailView");function se(e,t,r){let n=e.tabs.find(o=>o.id===t);if(!n)throw new h(`Tab "${t}" is not in view "${e.id}"`,[]);if(n.type!=="form")throw new h(`Tab "${t}" is not a form tab`,[]);return {...e,tabs:e.tabs.map(o=>o.id===t?r(n):o)}}a(se,"mapFormTab");function Xt(e,t){let r=e.groups.find(n=>n.id===t);if(!r)throw new h(`Group "${t}" is not in tab "${e.id}"`,[]);return r}a(Xt,"requireGroup");function Di(e,t){for(let r of e.groups){let n=r.fields.find(o=>o.id===t);if(n)return {group:r,field:n}}throw new h(`Field slot "${t}" is not in tab "${e.id}"`,[])}a(Di,"locateField");function Qt(e){return {viewId:e.viewId}}a(Qt,"viewFocus");function Jt(e){return {viewId:e.viewId,tabId:e.tabId}}a(Jt,"tabFocus");function ls(e){return {viewId:e.viewId,tabId:e.tabId,groupId:e.groupId}}a(ls,"groupFocus");function ds(e){return {viewId:e.viewId,tabId:e.tabId,fieldId:e.fieldId}}a(ds,"fieldFocus");function cs(e){return {viewId:e.viewId,tabId:e.tab.id}}a(cs,"addTabFocus");function ps(e){return {viewId:e.viewId,tabId:e.tabId,groupId:e.group.id}}a(ps,"addGroupFocus");function ms(e){return {viewId:e.viewId,tabId:e.tabId,groupId:e.groupId,fieldId:e.field.id}}a(ms,"addFieldFocus");function fs(e){return {viewId:e.viewId,tabId:e.tabId,groupId:e.toGroupId,fieldId:e.fieldId}}a(fs,"moveFieldFocus");function Je(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}a(Je,"firstChangedProperty");var Sp=ka$1,vp=fa$1,Rp=ea$1,Dp=z$1.object({...D,type:z$1.literal("add_tab"),tab:Sp}),Ep={type:"add_tab",schema:Dp,apply:a((e,t)=>F(e,t.viewId,r=>{if(r.tabs.some(n=>n.id===t.tab.id))throw new h(`Tab "${t.tab.id}" already exists in view "${t.viewId}"`,[]);return {...r,tabs:[...r.tabs,t.tab]}},"add_tab"),"apply"),focus:cs,presentation:A(cs,"local"),describe:a(e=>`Ajoute l'onglet \xAB ${e.tab.label} \xBB`,"describe")},Cp=z$1.object({...D,type:z$1.literal("remove_tab"),tabId:z$1.string().min(1)}),Op={type:"remove_tab",schema:Cp,apply:a((e,t)=>F(e,t.viewId,r=>{if(!r.tabs.some(n=>n.id===t.tabId))throw new h(`Tab "${t.tabId}" is not in view "${t.viewId}"`,[]);return {...r,tabs:r.tabs.filter(n=>n.id!==t.tabId)}},"remove_tab"),"apply"),focus:Jt,presentation:A(Jt,"local"),describe:a(e=>`Supprime l'onglet ${e.tabId}`,"describe")},Ts=z$1.object({label:z$1.string().min(1).optional(),icon:c.optional(),order:z$1.number().int().optional()}),_p=Object.keys(Ts.shape),Np=z$1.object({...D,type:z$1.literal("update_tab"),tabId:z$1.string().min(1),changes:Ts.refine(e=>Object.keys(e).length>0,"update_tab needs at least one change")}),bs=a(e=>({viewId:e.viewId,tabId:e.tabId}),"updateTabFocus"),kp={type:"update_tab",schema:Np,apply:a((e,t)=>F(e,t.viewId,r=>{if(!r.tabs.some(n=>n.id===t.tabId))throw new h(`Tab "${t.tabId}" is not in view "${t.viewId}"`,[]);return {...r,tabs:r.tabs.map(n=>n.id===t.tabId?{...n,...t.changes}:n)}},"update_tab"),"apply"),focus:bs,presentation:A(bs,"atomic",Je),describe:a(e=>e.changes.label?`Renomme l'onglet en \xAB ${e.changes.label} \xBB`:`Modifie l'onglet ${e.tabId}`,"describe")},Pp=z$1.object({...D,type:z$1.literal("reorder_tabs"),tabOrder:z$1.array(z$1.string().min(1))}),jp={type:"reorder_tabs",schema:Pp,apply:a((e,t)=>F(e,t.viewId,r=>({...r,tabs:Qe(r.tabs,t.tabOrder,"Tab")}),"reorder_tabs"),"apply"),focus:Qt,presentation:A(Qt,"local"),describe:a(()=>"R\xE9ordonne les onglets","describe")},Fp=z$1.object({...D,type:z$1.literal("add_group"),tabId:z$1.string().min(1),group:vp}),Vp={type:"add_group",schema:Fp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>{if(n.groups.some(o=>o.id===t.group.id))throw new h(`Group "${t.group.id}" already exists in tab "${t.tabId}"`,[]);return {...n,groups:[...n.groups,t.group]}}),"add_group"),"apply"),focus:ps,presentation:A(ps,"local"),describe:a(e=>`Ajoute le groupe \xAB ${e.group.label} \xBB`,"describe")},Mp=z$1.object({...D,type:z$1.literal("remove_group"),tabId:z$1.string().min(1),groupId:z$1.string().min(1)}),Lp={type:"remove_group",schema:Mp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>(Xt(n,t.groupId),{...n,groups:n.groups.filter(o=>o.id!==t.groupId)})),"remove_group"),"apply"),focus:ls,presentation:A(ls,"local"),describe:a(e=>`Supprime le groupe ${e.groupId}`,"describe")},Bp=z$1.object({...D,type:z$1.literal("update_group"),tabId:z$1.string().min(1),groupId:z$1.string().min(1),changes:z$1.object({label:z$1.string().min(1).optional(),description:z$1.string().optional(),collapsible:z$1.boolean().optional(),collapsed:z$1.boolean().optional(),order:z$1.number().int().optional()}).refine(e=>Object.keys(e).length>0,"update_group needs at least one change")}),gs=a(e=>({viewId:e.viewId,tabId:e.tabId,groupId:e.groupId}),"updateGroupFocus"),$p={type:"update_group",schema:Bp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>(Xt(n,t.groupId),{...n,groups:n.groups.map(o=>o.id===t.groupId?{...o,...t.changes}:o)})),"update_group"),"apply"),focus:gs,presentation:A(gs,"atomic",Je),describe:a(e=>e.changes.label?`Renomme le groupe en \xAB ${e.changes.label} \xBB`:"Modifie le groupe","describe")},Up=z$1.object({...D,type:z$1.literal("reorder_groups"),tabId:z$1.string().min(1),groupOrder:z$1.array(z$1.string().min(1))}),qp={type:"reorder_groups",schema:Up,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>({...n,groups:Qe(n.groups,t.groupOrder,"Group")})),"reorder_groups"),"apply"),focus:Jt,presentation:A(Jt,"local"),describe:a(()=>"R\xE9ordonne les groupes","describe")},zp=z$1.object({...D,type:z$1.literal("add_field"),tabId:z$1.string().min(1),groupId:z$1.string().min(1),field:Rp,index:z$1.number().int().min(0).optional()}),Gp={type:"add_field",schema:zp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>{if(Xt(n,t.groupId),n.groups.some(o=>o.fields.some(a=>a.id===t.field.id)))throw new h(`Field slot "${t.field.id}" already exists in tab "${t.tabId}"`,[]);return {...n,groups:n.groups.map(o=>{if(o.id!==t.groupId)return o;let a=t.index??o.fields.length;return {...o,fields:[...o.fields.slice(0,a),t.field,...o.fields.slice(a)]}})}}),"add_field"),"apply"),focus:ms,presentation:A(ms,"local"),describe:a(e=>`Ajoute le champ ${e.field.attribute??e.field.attributeGroup?.label??e.field.id}`,"describe")},Wp=z$1.object({...D,type:z$1.literal("remove_field"),tabId:z$1.string().min(1),fieldId:z$1.string().min(1)}),Kp={type:"remove_field",schema:Wp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>{let{group:o}=Di(n,t.fieldId);return {...n,groups:n.groups.map(a=>a.id===o.id?{...a,fields:a.fields.filter(s=>s.id!==t.fieldId)}:a)}}),"remove_field"),"apply"),focus:ds,presentation:A(ds,"local"),describe:a(e=>`Retire le champ ${e.fieldId}`,"describe")},Hp=z$1.object({...D,type:z$1.literal("move_field"),tabId:z$1.string().min(1),fieldId:z$1.string().min(1),toGroupId:z$1.string().min(1),toIndex:z$1.number().int().min(0)}),Yp={type:"move_field",schema:Hp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>{let{group:o,field:a}=Di(n,t.fieldId),s=Xt(n,t.toGroupId);if(o.id===s.id){let l=o.fields.findIndex(c=>c.id===t.fieldId);return {...n,groups:n.groups.map(c=>c.id===o.id?{...c,fields:us(c.fields,l,t.toIndex)}:c)}}return {...n,groups:n.groups.map(l=>l.id===o.id?{...l,fields:l.fields.filter(c=>c.id!==t.fieldId)}:l.id===s.id?{...l,fields:[...l.fields.slice(0,t.toIndex),a,...l.fields.slice(t.toIndex)]}:l)}}),"move_field"),"apply"),focus:fs,presentation:A(fs,"local"),describe:a(e=>`D\xE9place le champ ${e.fieldId} vers le groupe ${e.toGroupId}`,"describe")},Qp=z$1.object({...D,type:z$1.literal("update_field"),tabId:z$1.string().min(1),fieldId:z$1.string().min(1),changes:z$1.object({label:z$1.string().optional(),readOnly:z$1.boolean().optional(),span:z$1.number().int().min(1).max(12).optional()}).refine(e=>Object.keys(e).length>0,"update_field needs at least one change")}),ys=a(e=>({viewId:e.viewId,tabId:e.tabId,fieldId:e.fieldId}),"updateFieldFocus"),Jp={type:"update_field",schema:Qp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>(Di(n,t.fieldId),{...n,groups:n.groups.map(o=>({...o,fields:o.fields.map(a=>a.id===t.fieldId?{...a,...t.changes}:a)}))})),"update_field"),"apply"),focus:ys,presentation:A(ys,"atomic",Je),describe:a(e=>`Modifie le champ ${e.fieldId}`,"describe")},ws=z$1.object({source:ia$1.optional(),columns:Z.optional(),filters:aa$1.nullable().optional(),sorts:$$1.nullable().optional(),allowCreate:z$1.boolean().optional(),allowEdit:z$1.boolean().optional(),allowDelete:z$1.boolean().optional(),createMode:z$1.enum(["redirect","inline","peek"]).optional()}),Xp=Object.keys(ws.shape),xs=z$1.object({emailAttributeIds:z$1.array(z$1.string().min(1)).optional(),attribute:z$1.string().min(1).optional(),titleAttribute:z$1.string().min(1).nullable().optional(),component:z$1.string().nullable().optional(),props:z$1.record(z$1.string(),z$1.unknown()).nullable().optional()}),Zp=Object.keys(xs.shape),em={emailAttributeIds:["emails","meetings"],attribute:["richtext"],titleAttribute:["richtext"],component:["custom"],props:["custom"]},tm=z$1.object({...D,type:z$1.literal("update_tab_config"),tabId:z$1.string().min(1),changes:xs.refine(e=>Object.keys(e).length>0,"update_tab_config needs at least one change")}),hs=a(e=>({viewId:e.viewId,tabId:e.tabId}),"updateTabConfigFocus"),rm={type:"update_tab_config",schema:tm,apply:a((e,t)=>F(e,t.viewId,r=>{let n=r.tabs.find(o=>o.id===t.tabId);if(!n)throw new h(`Tab "${t.tabId}" is not in view "${r.id}"`,[]);for(let o of Object.keys(t.changes)){let a=em[o];if(a&&!a.includes(n.type))throw new h(`"${o}" is not a setting of a "${n.type}" tab`,[])}return {...r,tabs:r.tabs.map(o=>o.id===t.tabId?{...o,...t.changes}:o)}},"update_tab_config"),"apply"),focus:hs,presentation:A(hs,"atomic",Je),describe:a(e=>`Configure ${Object.keys(e.changes).join(", ")} sur l'onglet ${e.tabId}`,"describe")},nm=z$1.object({...D,type:z$1.literal("update_table_tab"),tabId:z$1.string().min(1),changes:ws.refine(e=>Object.keys(e).length>0,"update_table_tab needs at least one change")}),As=a(e=>({viewId:e.viewId,tabId:e.tabId}),"updateTableTabFocus"),im={type:"update_table_tab",schema:nm,apply:a((e,t)=>F(e,t.viewId,r=>{let n=r.tabs.find(l=>l.id===t.tabId);if(!n)throw new h(`Tab "${t.tabId}" is not in view "${r.id}"`,[]);if(n.type!=="table")throw new h(`Tab "${t.tabId}" is not a table tab`,[]);let o=Object.entries(t.changes),a=Object.fromEntries(o.filter(([,l])=>l!==null)),s=new Set(o.filter(([,l])=>l===null).map(([l])=>l));return {...r,tabs:r.tabs.map(l=>l.id===t.tabId?Object.fromEntries(Object.entries({...l,...a}).filter(([c])=>!s.has(c))):l)}},"update_table_tab"),"apply"),focus:As,presentation:A(As,"atomic",Je),describe:a(e=>e.changes.columns?`Affiche ${e.changes.columns.length} colonne(s) dans l'onglet ${e.tabId}`:`Modifie l'onglet ${e.tabId}`,"describe")},om=z$1.object({...D,type:z$1.literal("set_side_panel"),sidePanel:z$1.object({attributes:z$1.array(z$1.string().min(1)),width:z$1.number().int().min(1).optional()}).nullable()}),am={type:"set_side_panel",schema:om,apply:a((e,t)=>F(e,t.viewId,r=>({...r,config:{...r.config,sidePanel:t.sidePanel??void 0}}),"set_side_panel"),"apply"),focus:Qt,presentation:A(Qt,"atomic",()=>["config","sidePanel"]),describe:a(e=>e.sidePanel?"Active le panneau lat\xE9ral":"Retire le panneau lat\xE9ral","describe")},Ee=[Ep,Op,kp,jp,Vp,Lp,$p,qp,Gp,Kp,Yp,Jp,im,rm,am];var Xe={...D,tabId:z$1.string().min(1)};function Zt(e){return {viewId:e.viewId}}a(Zt,"viewFocus");function ue(e){return {viewId:e.viewId,tabId:e.tabId}}a(ue,"tabFocus");function Is(e){return {viewId:e.viewId,tabId:e.tab.id}}a(Is,"addTabFocus");function sm(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}a(sm,"firstChangedProperty");function vs(e){let t={...e};for(let r of sa$1)delete t[r];return t}a(vs,"withoutKanbanKeys");function Rs(e){let t={...e};for(let r of ra$1)delete t[r];return t}a(Rs,"withoutTableKeys");function um(e,t,r,n){let o=la$1.safeParse(t);if(!o.success){if(!la$1.safeParse(e).success)return t;let a=o.error.issues.map(s=>s.path.length?`${s.path.join(".")}: ${s.message}`:s.message).join(", ");throw new h(`List tab "${n}" in view "${r}" would no longer be publishable: ${a}`,[])}return t}a(um,"assertStillPublishableTab");function er(e,t,r,n,o){return ae(e,t,"list",a=>{let s=a.config.tabs??[];if(!s.some(l=>l.id===r))throw new h(`List tab "${r}" is not in view "${t}"`,[]);return {...a,config:{...a.config,tabs:s.map(l=>l.id===r?um(l,n(l),t,r):l)}}},o)}a(er,"mapListTab");var lm=la$1,Ds=ba$1,dm=$$1;function z(e,t,r,n){let o=z$1.object({...Xe,type:z$1.literal(e),value:r});return {type:e,schema:o,apply:a((a,s)=>er(a,s.viewId,s.tabId,l=>{if(s.value===null){let{[t]:c,...f}=l;return f}return {...l,[t]:s.value}},e),"apply"),focus:ue,presentation:A(ue,"atomic",()=>[String(t)]),describe:a(a=>n(a.value),"describe")}}a(z,"setOnTab");var cm=z$1.object({...D,type:z$1.literal("add_list_tab"),tab:lm}),pm={type:"add_list_tab",schema:cm,apply:a((e,t)=>ae(e,t.viewId,"list",r=>{let n=r.config.tabs??[];if(n.some(o=>o.id===t.tab.id))throw new h(`List tab "${t.tab.id}" already exists in view "${t.viewId}"`,[]);return {...r,config:{...r.config,tabs:[...n,t.tab]}}},"add_list_tab"),"apply"),focus:Is,presentation:A(Is,"local"),describe:a(e=>`Ajoute l'onglet \xAB ${e.tab.label} \xBB`,"describe")},mm=z$1.object({...Xe,type:z$1.literal("remove_list_tab")}),fm={type:"remove_list_tab",schema:mm,apply:a((e,t)=>ae(e,t.viewId,"list",r=>{let n=r.config.tabs??[];if(!n.some(o=>o.id===t.tabId))throw new h(`List tab "${t.tabId}" is not in view "${t.viewId}"`,[]);return {...r,config:{...r.config,tabs:n.filter(o=>o.id!==t.tabId)}}},"remove_list_tab"),"apply"),focus:ue,presentation:A(ue,"local"),describe:a(e=>`Supprime l'onglet ${e.tabId}`,"describe")},bm=z$1.object({...Xe,type:z$1.literal("update_list_tab"),changes:z$1.object({label:z$1.string().min(1).optional(),icon:c.optional(),default:z$1.boolean().optional(),visibility:z$1.enum(y).optional()}).refine(e=>Object.keys(e).length>0,"update_list_tab needs at least one change")}),Ss=a(e=>({viewId:e.viewId,tabId:e.tabId}),"updateListTabFocus"),gm={type:"update_list_tab",schema:bm,apply:a((e,t)=>er(e,t.viewId,t.tabId,r=>({...r,...t.changes}),"update_list_tab"),"apply"),focus:Ss,presentation:A(Ss,"atomic",sm),describe:a(e=>e.changes.label?`Renomme l'onglet en \xAB ${e.changes.label} \xBB`:`Modifie l'onglet ${e.tabId}`,"describe")},ym=z$1.object({...D,type:z$1.literal("reorder_list_tabs"),tabOrder:z$1.array(z$1.string().min(1))}),hm={type:"reorder_list_tabs",schema:ym,apply:a((e,t)=>ae(e,t.viewId,"list",r=>({...r,config:{...r.config,tabs:Qe(r.config.tabs??[],t.tabOrder,"List tab")}}),"reorder_list_tabs"),"apply"),focus:Zt,presentation:A(Zt,"local"),describe:a(()=>"R\xE9ordonne les onglets","describe")},Am=z("set_columns","columns",z$1.array(z$1.string().min(1)),e=>`Affiche ${Array.isArray(e)?e.length:0} colonne(s)`),Tm=z("set_column_sizing","columnSizing",z$1.record(z$1.string(),z$1.number().int().positive()),()=>"Ajuste la largeur des colonnes"),wm=z$1.object({...Xe,type:z$1.literal("set_layout"),value:z$1.enum(["table","list","kanban"])}),xm={type:"set_layout",schema:wm,apply:a((e,t)=>er(e,t.viewId,t.tabId,r=>{if(t.value!=="kanban")return {...vs(r),layout:t.value};if(r.groupByAttribute===void 0)throw new h(`List tab "${t.tabId}" cannot switch to kanban without a group attribute \u2014 use set_group_by, which switches the layout itself`,[]);return {...Rs(r),layout:"kanban"}},"set_layout"),"apply"),focus:ue,presentation:A(ue,"atomic",()=>["layout"]),describe:a(e=>`Passe en affichage ${e.value}`,"describe")},Im=z$1.object({...Xe,type:z$1.literal("set_group_by"),value:z$1.string().min(1).nullable()}),Sm={type:"set_group_by",schema:Im,apply:a((e,t)=>er(e,t.viewId,t.tabId,r=>t.value===null?{...vs(r),layout:"table"}:{...Rs(r),layout:"kanban",groupByAttribute:t.value},"set_group_by"),"apply"),focus:ue,presentation:A(ue,"atomic",()=>["groupByAttribute"]),describe:a(e=>e.value?`Regroupe par ${e.value} en kanban`:"Retire le regroupement, retour en table","describe")},vm=z("set_filters","filters",Ds.nullable(),e=>e?"Modifie les filtres":"Retire les filtres"),Rm=z("set_sorts","sorts",dm.nullable(),e=>e?"Modifie le tri":"Retire le tri"),Dm=z("set_create_mode","createMode",z$1.enum(["redirect","inline","peek"]),e=>`Cr\xE9ation en mode ${e}`),Em=z("set_open_mode","openMode",z$1.enum(["side","page"]),e=>e==="side"?"Ouvre les fiches en c\xF4t\xE9":"Ouvre les fiches en pleine page"),Cm=z("set_read_only","readOnly",z$1.boolean(),e=>e?"Passe l'onglet en lecture seule":"Rend l'onglet modifiable"),Om=z("set_card_user_attribute","cardUserAttribute",z$1.string().min(1).nullable(),e=>e?`Affiche ${e} sur les cartes`:"Retire l'utilisateur des cartes"),_m=z("set_card_date_attribute","cardDateAttribute",z$1.string().min(1).nullable(),e=>e?`Affiche ${e} sur les cartes`:"Retire la date des cartes"),Nm=z("set_description_attribute","descriptionAttribute",z$1.string().min(1).nullable(),e=>e?`Affiche ${e} en description`:"Retire la description"),km=z("set_display_attributes","displayAttributes",_$1.nullable(),e=>`Affiche ${Array.isArray(e)?e.length:0} attribut(s)`),Pm=z$1.object({...D,type:z$1.literal("set_default_filters"),filters:Ds.nullable()}),jm={type:"set_default_filters",schema:Pm,apply:a((e,t)=>ae(e,t.viewId,"list",r=>{if(t.filters===null){let{defaultFilters:n,...o}=r.config;return {...r,config:o}}return {...r,config:{...r.config,defaultFilters:t.filters}}},"set_default_filters"),"apply"),focus:Zt,presentation:A(Zt,"atomic",()=>["config","defaultFilters"]),describe:a(e=>e.filters?"Modifie les filtres de la vue":"Retire les filtres de la vue","describe")},Ce=[jm,pm,fm,gm,hm,Am,Tm,xm,Sm,vm,Rm,Dm,Em,Cm,Om,_m,Nm,km];var Fm=new Set(["formula","rollup"]);function Oe(e){return Fm.has(e.attributeType)}a(Oe,"isComputedAttribute");var Es={sum:"number",avg:"number",count:"number",countValues:"number",countUniqueValues:"number",countEmpty:"number",percentEmpty:"number",percentNotEmpty:"number",earliest:"date",latest:"date",original:"multiselect"};function Vm(e){return typeof e=="string"&&e in Es?Es[e]:void 0}a(Vm,"rollupReturnTypeOf");function Os(e,t){let r=e.objects.find(n=>n.id===t);if(!r)throw new h(`Object "${t}" is not in the draftable state`,[]);return r}a(Os,"requireObject");function tr(e){return e.config??{}}a(tr,"configOf");function G(e){let t=tr(e).targets;return Array.isArray(t)?t.filter(r=>typeof r=="object"&&r!==null&&typeof r.object=="string"):[]}a(G,"relationTargets");function _e(e){let t=G(e).filter(r=>r.object!==ee);return t.length===1?t[0]?.object:void 0}a(_e,"relationTargetObjectName");function Mm(e){let t=tr(e),r=e.attributeType,n={name:e.name,type:r,id:e.id},o=t.optionsSource;if(r==="relation"){let a=_e(e);return {...n,...t.cardinality==="one"||t.cardinality==="many"?{cardinality:t.cardinality}:{},...a===void 0?{}:{targetObjectName:a},targets:G(e)}}if(r==="formula")return {...n,...t.returnType===void 0?{}:{returnType:t.returnType},...o===void 0?{}:{optionsSource:o}};if(r==="rollup"){let a=Vm(t.function);return {...n,...a===void 0?{}:{returnType:a},...o===void 0?{}:{optionsSource:o}}}return r==="select"||r==="status"||r==="multiselect"?{...n,...Array.isArray(t.options)?{options:t.options}:{}}:n}a(Mm,"toCompileAttribute");function Cs(e,t){return {objectName:e.name,attributes:t.filter(r=>r.objectId===e.id).map(Mm)}}a(Cs,"toCompileObject");function Ei(e,t){let r=Os(e,t);return {...Cs(r,e.attributes),relatedObjects:Object.fromEntries(e.objects.map(n=>[n.name,Cs(n,e.attributes)]))}}a(Ei,"computedCompileSchemaOf");function Lm(e){return {id:e.id,name:e.name,label:e.label,type:"rollup",...tr(e)}}a(Lm,"toRollupAttribute");function _s(e){try{return e()}catch(t){throw t instanceof g?new h(t.message,[]):t}}a(_s,"asValidationError");function rr(e,t){let r=Ei(e,t.objectId);return _s(()=>Ns(t,r))}a(rr,"computedPlanOf");function Ns(e,t){if(e.attributeType==="rollup")return va(Lm(e),t);let r=tr(e);return Lt({attributeName:e.name,expression:String(r.expression??""),returnType:r.returnType,schema:t})}a(Ns,"compilePlan");function Ci(e){_s(()=>wa(e.map(t=>({attributeName:t.attributeName,dependencies:t.dependencies}))));}a(Ci,"assertAcyclicComputed");function Bm(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(Bm,"dependencyNames");function Ze(e,t){let r=Ei(e,t),n=[];for(let o of e.attributes)if(!(o.objectId!==t||!Oe(o)))try{n.push(Ns(o,r));}catch(a){if(!(a instanceof g))throw a}return n}a(Ze,"compilablePlansOf");function Oi(e,t,r){let n=Os(e,t),o=[];for(let a of Ze(e,t))a.attributeName!==r&&a.dependencies.some(s=>Bm(s,r))&&o.push(a.attributeName);for(let a of e.objects)if(a.id!==t)for(let s of Ze(e,a.id))s.dependencies.some(c=>{if(c.kind!=="relation"||c.targetAttributeName!==r)return false;let f=e.attributes.find(x=>x.objectId===a.id&&x.name===c.relationName&&x.attributeType==="relation");return f!==void 0&&_e(f)===n.name})&&o.push(`${a.name}.${s.attributeName}`);return o}a(Oi,"dependentsOf");function et(e){let t=e.config?.bilateral;if(typeof t!="object"||t===null)return;let{object:r,attribute:n}=t;return typeof r=="string"&&typeof n=="string"?{object:r,attribute:n}:void 0}a(et,"bilateralDeclarationOf");function $m(e,t){return t!==void 0&&e.attributeType===t.attributeType&&Um(e,t)}a($m,"sameAttribute");function Um(e,t){return JSON.stringify(e.config??{})===JSON.stringify(t.config??{})}a(Um,"sameConfig");function qm(e,t){let r=a(n=>$m(n,e.attributes.find(o=>o.id===n.id)),"untouched");for(let n of t.attributes){if(n.attributeType!=="relation")continue;let o=et(n);if(o===void 0||r(n))continue;let s=t.objects.find(R=>R.id===n.objectId)?.name??n.objectId,l=t.objects.find(R=>R.name===o.object),c=t.attributes.find(R=>R.objectId===l?.id&&R.name===o.attribute),f=`relation "${s}.${n.name}" declares inverse "${o.object}.${o.attribute}"`;if(c===void 0)throw new h(`${f}, which object "${o.object}" does not have; draft it first`,[]);if(c.attributeType!=="relation")throw new h(`${f}, which is not a relation`,[]);let x=et(c);if(!(G(c).some(R=>R.object===s)&&(r(c)?x===void 0||x.object===s&&x.attribute===n.name:x?.object===s&&x.attribute===n.name)))throw new h(`${f}, which does not point back to "${s}.${n.name}"`,[])}}a(qm,"assertBilateralPairs");function ks(e,t,r){let n=`fld_${e}_${t}`;return r===0?n:`${n}_${r}`}a(ks,"makeFieldId");function zm(e,t){return e.attributeGroup?e.attributeGroup.id:e.attribute?e.attribute:`slot${t}`}a(zm,"seedOf");function Gm(e){let t=new Map,r=e.fields.map((n,o)=>{if(n.id)return n;let a=zm(n,o),s=t.get(a)??0;return t.set(a,s+1),{...n,id:ks(e.id,a,s)}});return {...e,fields:r}}a(Gm,"withIds");function _i(e){return e.map(t=>t.type==="form"?{...t,groups:t.groups.map(Gm)}:t)}a(_i,"ensureFieldIds");function Wm(e){return {id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon}}}a(Wm,"toDraftableObject");function Km(e){let t=e.id??e.name;return (e.attributes??[]).map(r=>Hm(r,t))}a(Km,"toDraftableAttributes");function nr(e){return {id:e.id,name:e.name,label:e.label,type:e.attributeType,...e.config}}a(nr,"toAttribute");function Hm(e,t){let{id:r,name:n,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(Hm,"toDraftableAttribute");function Ps(e){let t=e[0];return t?`{{ ${t.name} }}`:"{{ id }}"}a(Ps,"draftedLabelExpression");function ir(e,t){let r=t.filter(n=>n.objectId===e.id);return {id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},labelExpression:Ps(r),attributes:r.map((n,o)=>{let a=nr(n);return a.order===void 0?{...a,order:o}:a})}}a(ir,"draftedObjectDefinition");var Ym=0x100000001b3n,Qm=0xffffffffffffffffn;function js(e,t){let r=t;for(let n of new TextEncoder().encode(e))r^=BigInt(n),r=r*Ym&Qm;return r}a(js,"fnv1a64");function Ni(e,t){let r=`${e.toLowerCase()}:${t}`,n=js(r,0xcbf29ce484222325n).toString(16).padStart(16,"0"),o=js(`${t}:${r}`,0x84222325cbf29ce4n).toString(16).padStart(16,"0"),a=n+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(Ni,"viewIdFor");function me(e){return {list:Ni(e,"list"),detail:Ni(e,"detail")}}a(me,"defaultViewIdsFor");function Fs(e,t,r){if(e==="list"){let s=We(r);return {id:t,objectName:s.object,type:"list",label:s.label,tabs:[],config:s.config,derived:true}}let n=Ge(r),{tabs:o,...a}=n.config;return {id:t,objectName:n.object,type:"detail",label:n.label,tabs:_i(o??[]),config:a,derived:true}}a(Fs,"derivedView");function ki(e,t){let r=ir(e,t),n=me(e.id);return ["list","detail"].map(o=>Fs(o,n[o],r))}a(ki,"defaultViewsFor");function Pi(e,t,r){return Fs(e.type,e.id,ir(t,r))}a(Pi,"regenerateDerived");function Ne(e,t){let r=e.objects.find(n=>n.id===t);if(!r)throw new h(`Object "${t}" is not in the draftable state`,[]);return r}a(Ne,"requireObject");function ji(e,t,r){return {...e,attributes:[...r],views:e.views.map(n=>n.derived&&n.objectName===t.name?Pi(n,t,r):n)}}a(ji,"withDerivedViews");function or(e){return {objectId:e.objectId}}a(or,"objectFocus");function ar(e){return {objectId:e.objectId,recordId:e.recordId}}a(ar,"recordFocus");function Vs(e){return {objectId:e.objectId,attributeId:e.attributeId}}a(Vs,"attributeFocus");function sr(e){return {objectId:e.objectId,attributeName:e.attribute}}a(sr,"existingAttributeFocus");function Jm(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}a(Jm,"firstChangedProperty");function Xm(e,t){if(e.type==="list"){let r=(e.config.tabs??[]).find(n=>n.id!==kt&&(n.columns??[]).includes(t));return r===void 0?void 0:`tab "${r.id}"`}for(let r of e.tabs){let n="groups"in r?r.groups:[];for(let o of n)if(o.fields.some(a=>a.attribute===t)&&!(r.id===ze&&o.id===Pt))return `group "${o.id}"`}}a(Xm,"handShapedUse");function Zm(e,t){if(e.type==="list"){let r=(e.config.tabs??[]).map(n=>n.id===kt&&n.columns!==void 0?{...n,columns:n.columns.filter(o=>o!==t)}:n);return {...e,config:{...e.config,tabs:r}}}return {...e,tabs:e.tabs.map(r=>{if(r.id!==ze||!("groups"in r))return r;let n=r.groups.map(o=>o.id===Pt?{...o,fields:o.fields.filter(a=>a.attribute!==t)}:o);return {...r,groups:n}})}}a(Zm,"withoutGeneratedUse");function ef(e,t,r){let n=r.config??{},o=r.name;if(n.relationPath!==void 0)throw new h(`rollup "${o}": relationPath is not supported yet`,[]);let a=n.relationAttribute;if(typeof a!="string"||a.length===0)throw new h(`rollup "${o}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let s=e.attributes.find(v=>v.objectId===t.id&&v.name===a&&v.attributeType==="relation");if(!s)throw new h(`rollup "${o}" needs a relation attribute; "${a}" is not a relation of object "${t.name}"`,[]);let l=_e(s);if(l===void 0){let v=G(s).filter(W=>W.object!=="*").length;throw new h(`rollup "${o}" needs a relation with one target object; "${a}" targets ${v}`,[])}if(n.function==="count")return;let c=e.objects.find(v=>v.name===l),f=n.targetAttribute;if(!(c!==void 0&&e.attributes.some(v=>v.objectId===c.id&&v.name===f)))throw new h(`rollup "${o}" targets attribute "${f}", which object "${l}" does not have`,[])}a(ef,"assertRollupShape");function tf(e,t){let r=e.config??{};if(e.attributeType==="rollup")return r.relationAttribute===t;let n=typeof r.expression=="string"?r.expression:"";return new RegExp(`(^|[^A-Za-z0-9_])${t}\\.`).test(n)}a(tf,"traversesRelation");function Ls(e,t){let r=Ne(e,t.objectId);if(t.attributeType==="relation"){for(let o of G(t))if(o.object!==ee&&!e.objects.some(a=>a.name===o.object))throw new h(`object "${o.object}" is unknown; create it first`,[]);let n=et(t)?.object;if(n!==void 0&&n!==ee&&!e.objects.some(o=>o.name===n))throw new h(`object "${n}" is unknown; create it first`,[]);for(let o of e.attributes)o.objectId!==t.objectId||!Oe(o)||tf(o,t.name)&&rr(e,o);}else if(Oe(t))t.attributeType==="rollup"&&ef(e,r,t),rr(e,t);else return;Ci(Ze(e,t.objectId));}a(Ls,"assertConfigFolds");var fe={...Ri,objectId:z$1.string().uuid()},rf=z$1.object({...fe,type:z$1.literal("add_object"),name:yt,label:z$1.string().min(1),icon:z$1.string().min(1).optional()}),nf={type:"add_object",schema:rf,apply:a((e,t)=>{if(e.objects.some(n=>n.name===t.name))throw new h(`Object "${t.name}" already exists`,[]);if(e.objects.some(n=>n.id===t.objectId))throw new h(`Object id "${t.objectId}" is already taken`,[]);let r={id:t.objectId,name:t.name,label:t.label,...t.icon===void 0?{}:{icon:t.icon}};return {...e,objects:[...e.objects,r],views:[...e.views,...ki(r,e.attributes)]}},"apply"),focus:or,presentation:A(or,"structural"),describe:a(e=>`Cr\xE9e l'objet \xAB ${e.label} \xBB`,"describe")},of=z$1.object({...fe,type:z$1.literal("update_object"),changes:z$1.object({label:z$1.string().min(1).optional(),icon:z$1.string().min(1).optional()}).refine(e=>Object.keys(e).length>0,"update_object needs at least one change")}),Ms=a(e=>({objectId:e.objectId}),"updateObjectFocus"),af={type:"update_object",schema:of,apply:a((e,t)=>(Ne(e,t.objectId),{...e,objects:e.objects.map(r=>r.id===t.objectId?{...r,...t.changes}:r)}),"apply"),focus:Ms,presentation:A(Ms,"atomic",Jm),describe:a(e=>e.changes.label?`Renomme l'objet en \xAB ${e.changes.label} \xBB`:"Modifie l'objet","describe")},sf=z$1.object({...fe,type:z$1.literal("remove_object")}),uf={type:"remove_object",schema:sf,apply:a((e,t)=>{Ne(e,t.objectId);let r=e.objects.find(n=>n.id===t.objectId)?.name;for(let n of e.attributes){if(n.objectId===t.objectId||n.attributeType!=="relation"||!G(n).some(a=>a.object===r))continue;let o=e.objects.find(a=>a.id===n.objectId);throw new h(`object "${r}" is targeted by attribute "${o?.name}.${n.name}"; remove that attribute first`,[])}return {...e,objects:e.objects.filter(n=>n.id!==t.objectId),attributes:e.attributes.filter(n=>n.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(n=>n.objectId!==t.objectId),views:e.views.filter(n=>n.objectName!==r)}},"apply"),focus:or,presentation:A(or,"structural"),describe:a(e=>`Supprime l'objet ${e.objectId}`,"describe")},Bs=yo;function $s(e,t){try{n$1(e,t);}catch(r){throw r instanceof h?new h(r.message,r.errors.map(n=>({...n,path:["config",...n.path??[]]}))):r}}a($s,"assertConfigParses");var lf=z$1.object({...fe,type:z$1.literal("add_attribute"),attributeId:z$1.string().min(1),name:xr,label:z$1.string().min(1),attributeType:z$1.enum(Bs),config:z$1.record(z$1.string(),z$1.unknown()).optional()}).superRefine((e,t)=>{try{$s(e.attributeType,e.config??{});}catch(r){if(r instanceof h){for(let n of r.errors)t.addIssue({code:"custom",message:n.message,path:[...n.path]});return}throw r}}),df={type:"add_attribute",schema:lf,apply:a((e,t)=>{let r=Ne(e,t.objectId);if(e.attributes.some(s=>s.objectId===t.objectId&&s.name===t.name))throw new h(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let n={id:t.attributeId,objectId:t.objectId,name:t.name,label:t.label,attributeType:t.attributeType,...t.config===void 0?{}:{config:t.config}};for(let s of e.sampleRecords)s.objectId===t.objectId&&zs(s.id,n,s.values);let o=[...e.attributes,n],a=ji(e,r,o);return Ls(a,n),a},"apply"),focus:Vs,presentation:A(Vs,"local"),describe:a(e=>`Ajoute l'attribut \xAB ${e.label} \xBB`,"describe")},Us={...fe,attribute:xr};function qs(e,t,r,n){let o=Ne(e,t);if(r===void 0)throw new h(`${n} 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===r);if(!a)throw new h(`Attribute "${r}" is not on object "${t}"`,[]);return {object:o,attribute:a}}a(qs,"requireAttribute");var cf=z$1.object({...Us,type:z$1.literal("update_attribute"),changes:z$1.object({label:z$1.string().min(1).optional(),config:z$1.record(z$1.string(),z$1.unknown()).optional()}).refine(e=>Object.keys(e).length>0,"update_attribute needs at least one change")}),pf={type:"update_attribute",schema:cf,apply:a((e,t)=>{let{object:r,attribute:n}=qs(e,t.objectId,t.attribute,"update_attribute");t.changes.config!==void 0&&$s(n.attributeType,t.changes.config);let o={...n,...t.changes},a=e.attributes.map(l=>l===n?o:l),s=ji(e,r,a);return Ls(s,o),s},"apply"),focus:sr,presentation:A(sr,"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")},mf=z$1.object({...Us,type:z$1.literal("remove_attribute")}),ff={type:"remove_attribute",schema:mf,apply:a((e,t)=>{let{object:r,attribute:n}=qs(e,t.objectId,t.attribute,"remove_attribute"),[o]=Oi(e,t.objectId,n.name);if(o!==void 0)throw new h(`attribute "${n.name}" is used by "${o}"; remove that first`,[]);for(let c of e.views){if(c.objectName!==r.name)continue;let f=Xm(c,n.name);if(f!==void 0)throw new h(`attribute "${n.name}" is used by view "${c.id}" (${f}); remove it from the view first`,[])}let a=e.sampleRecords.find(c=>c.objectId===n.objectId&&n.name in c.values);if(a)throw new h(`Attribute "${n.name}" is still used by sample record "${a.id}"`,[]);let s=e.attributes.filter(c=>c!==n),l={...e,views:e.views.map(c=>c.objectName===r.name?Zm(c,n.name):c)};return ji(l,r,s)},"apply"),focus:sr,presentation:A(sr,"local"),describe:a(e=>`Supprime l'attribut \xAB ${e.attribute} \xBB`,"describe")};function bf(e,t,r,n){let o=nr(r);try{c$2(o);}catch{return}let a=g$2(o,n);if(a.success)return;let s=a.errors??[],l=s.map(c=>c.path.length>1?`${c.path.join(".")}: ${c.message}`:c.message).join(", ");throw new h(`Sample record "${e}" has an invalid value for "${t}": ${l}`,s.map(c=>({path:c.path,message:c.message})))}a(bf,"assertSampleValue");function zs(e,t,r){if(t.config?.required===true&&t.config?.defaultValue===void 0&&!(t.name in r&&r[t.name]!==void 0))throw new h(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}a(zs,"assertRequiredCovered");function Fi(e){return (Array.isArray(e)?e:[e]).flatMap(r=>{if(typeof r=="string")return [r];if(typeof r=="object"&&r!==null){let n=r.id;if(typeof n=="string")return [n]}return []})}a(Fi,"relationValueIds");function gf(e,t,r,n){if(r.attributeType!=="relation"||n===void 0||n===null)return;let o=_e(r),a=e.objects.find(l=>l.name===o);if(!a)return;let s=e.views.some(l=>l.id===me(a.id).list);for(let l of Fi(n)){let c=e.sampleRecords.find(x=>x.id===l);if(c?.objectId!==a.id&&(c!==void 0||s))throw new h(`sample record "${t}" references unknown sample "${l}"`,[])}}a(gf,"assertUnknownSampleReference");var yf=z$1.object({...fe,type:z$1.literal("add_sample_record"),recordId:z$1.string().uuid(),values:z$1.record(z$1.string(),z$1.unknown()),publication:z$1.enum(["preview","requested-data"]).optional()}),hf={type:"add_sample_record",schema:yf,apply:a((e,t)=>{if(Ne(e,t.objectId),e.sampleRecords.some(n=>n.id===t.recordId))throw new h(`Sample record "${t.recordId}" already exists`,[]);let r=new Map(e.attributes.filter(n=>n.objectId===t.objectId).map(n=>[n.name,n]));for(let[n,o]of Object.entries(t.values)){let a=r.get(n);if(!a)throw new h(`Sample record "${t.recordId}" uses unknown attribute "${n}"`,[]);if(Oe(a))throw new h(`attribute "${a.name}" is computed and cannot be set on a sample record`,[]);gf(e,t.recordId,a,o),bf(t.recordId,n,a,o);}for(let n of r.values())zs(t.recordId,n,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:ar,presentation:A(ar,"local"),describe:a(()=>"Ajoute un exemple","describe")};function Af(e,t){return new Set(e.attributes.filter(r=>r.objectId===t&&r.attributeType==="relation").map(r=>r.name))}a(Af,"relationNamesOf");function Tf(e,t){for(let r of e.sampleRecords){if(r.id===t)continue;let n=Af(e,r.objectId);for(let[o,a]of Object.entries(r.values))if(n.has(o)&&Fi(a).includes(t))throw new h(`sample record "${t}" is referenced by sample record "${r.id}"; remove that first`,[])}}a(Tf,"assertSampleNotReferenced");var wf=z$1.object({...fe,type:z$1.literal("remove_sample_record"),recordId:z$1.string().min(1)}),xf={type:"remove_sample_record",schema:wf,apply:a((e,t)=>{if(!e.sampleRecords.some(r=>r.id===t.recordId&&r.objectId===t.objectId))throw new h(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,[]);return Tf(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(r=>r.id!==t.recordId)}},"apply"),focus:ar,presentation:A(ar,"local"),describe:a(()=>"Retire un exemple","describe")},ke=[nf,af,uf,df,pf,ff,hf,xf];function If(){let e=new Map;for(let t of [...ke,...Ee,...Ce]){if(e.has(t.type))throw new r("architect operation",t.type);e.set(t.type,t);}return e}a(If,"build");var tt=If(),Sf=[...tt.keys()];function rt(e){let t=tt.get(e.type);if(!t)throw new h(`Operation "${e.id}" has unknown type "${e.type}"`,[]);return t}a(rt,"defOf");function Vi(e,t){return t.reduce((r,n)=>rt(n).apply(r,n),e)}a(Vi,"applyOperations");function Mi(e){return rt(e).focus(e)}a(Mi,"focusOf");function vf(e,t){return e.map(r=>rt(r).describe(r,t))}a(vf,"describeOperations");function Rf(e){if(typeof e!="object"||e===null||!("type"in e))throw new h("An operation must be an object carrying a type",[]);let t=e.type;if(typeof t!="string")throw new h("An operation's type must be a string",[]);let r=tt.get(t);if(!r)throw new h(`Unknown operation type "${t}"`,[]);let n=r.schema.safeParse(e);if(!n.success)throw new h(`Operation "${t}" is invalid: ${n.error.issues.map(o=>`${o.path.join(".")} ${o.message}`).join("; ")}`,[]);return n.data}a(Rf,"parseOperation");function Li(e){return rt(e).presentation(e)}a(Li,"presentationOf");function Df(e){let t=e.map(Li);return new Set(t.map(({focus:n})=>n.viewId??n.objectId).filter(n=>n!==void 0)).size>1||t.some(({impact:n})=>n==="structural")?"structural":t.some(({impact:n})=>n==="local")?"local":"atomic"}a(Df,"episodeImpactOf");function Ef(e,t){return e.config.tabs?.find(r=>r.id===t)}a(Ef,"listTabOf");function Gs(e,t){let r=t.viewId?e.views.find(o=>o.id===t.viewId):void 0,n=t.tabId?r?.tabs.find(o=>o.id===t.tabId):void 0;if(t.attributeId)return e.attributes.find(o=>o.id===t.attributeId);if(t.attributeName)return e.attributes.find(o=>o.objectId===t.objectId&&o.name===t.attributeName);if(t.fieldId){if(n?.type!=="form")return;for(let o of n.groups){let a=o.fields.find(s=>s.id===t.fieldId);if(a)return a}return}if(t.groupId)return n?.type!=="form"?void 0:n.groups.find(o=>o.id===t.groupId);if(t.tabId)return r?n??Ef(r,t.tabId):void 0;if(t.recordId)return e.sampleRecords.find(o=>o.id===t.recordId);if(r)return r;if(t.objectId)return e.objects.find(o=>o.id===t.objectId)}a(Gs,"snapshotArchitectTarget");function Cf(e,t){let r=e;return t.map(n=>{let o=Li(n),a=Gs(r,o.focus);r=Vi(r,[n]);let s=Gs(r,o.focus);return {operationId:n.id,operationType:n.type,presentation:o,before:a,after:s}})}a(Cf,"deriveArchitectChanges");function Ws(e){return e.attributeName&&e.objectId?`attribute:${e.objectId}:${e.attributeName}`:e.attributeId?`attribute-id:${e.attributeId}`:e.tabId&&e.viewId?`tab:${e.viewId}:${e.tabId}`:e.viewId?`view:${e.viewId}`:e.objectId?`object:${e.objectId}`:null}a(Ws,"proposalTargetKey");function Of(e,t){let r=new Set;for(let n of t){let o=Mi(n),a=Ws(o);a&&r.add(a),o.objectId&&r.add(`object:${o.objectId}`),o.viewId&&r.add(`view:${o.viewId}`);let s=e.views.find(x=>x.id===o.viewId),l=e.objects.find(x=>x.name===s?.objectName);l&&r.add(`object:${l.id}`),(n.type==="remove_object"||n.type.includes("sample_record"))&&o.objectId&&r.add(`object-tree:${o.objectId}`),n.type==="add_object"&&typeof n.name=="string"&&r.add(`object-name:${n.name}`);let c=n.type==="update_attribute"&&typeof n.changes=="object"&&n.changes!==null?n.changes:null,f=n.type==="add_attribute"?n.config:c&&"config"in c?c.config:void 0;if(f&&typeof f=="object"&&"targets"in f&&Array.isArray(f.targets))for(let x of f.targets)typeof x=="object"&&x!==null&&"object"in x&&typeof x.object=="string"&&x.object!=="*"&&r.add(`object-name:${x.object}`);}return [...r]}a(Of,"requiredTargetKeys");function _f(e,t){return Object.fromEntries(t.map(r=>[r,b$3(Nf(e,r))]))}a(_f,"targetTokensFor");function Nf(e,t){if(t.startsWith("object:"))return e.objects.find(r=>r.id===t.slice(7))??null;if(t.startsWith("object-name:"))return e.objects.find(r=>r.name===t.slice(12))??null;if(t.startsWith("object-tree:")){let r=t.slice(12),n=e.objects.find(o=>o.id===r);return n?{object:n,attributes:e.attributes.filter(o=>o.objectId===r),views:e.views.filter(o=>o.objectName===n.name),sampleRecords:e.sampleRecords.filter(o=>o.objectId===r)}:null}if(t.startsWith("attribute-id:"))return e.attributes.find(r=>r.id===t.slice(13))??null;if(t.startsWith("attribute:")){let r=t.slice(10),n=r.indexOf(":");if(n<0)throw new h(`Invalid proposal target key "${t}"`,[]);return e.attributes.find(o=>o.objectId===r.slice(0,n)&&o.name===r.slice(n+1))??null}if(t.startsWith("view:"))return e.views.find(r=>r.id===t.slice(5))??null;if(t.startsWith("tab:")){let r=t.slice(4),n=e.views.find(a=>r.startsWith(`${a.id}:`));if(!n)return null;let o=r.slice(n.id.length+1);return (n.type==="list"?n.config.tabs:n.tabs)?.find(a=>a.id===o)??null}throw new h(`Unknown proposal target key "${t}"`,[])}a(Nf,"targetSnapshot");function kf(e){return {id:e.id??"",objectName:e.object,type:e.type,label:e.label,tabs:pt(e)?e.config.tabs??[]:[],config:e.config}}a(kf,"toDraftableView");function nt(e){return e.type==="detail"?{...e.config,tabs:e.tabs}:e.config}a(nt,"persistedViewConfig");function Pf(e,t){return e.type==="detail"?{...e,label:t.label,config:nt(t)}:{...e,label:t.label,config:nt(t)}}a(Pf,"fromDraftableView");function jf(e){let t={id:e.id,name:"default",label:e.label,object:e.objectName,default:true};return e.type==="detail"?{...t,type:"detail",config:nt(e)}:{...t,type:"list",config:nt(e)}}a(jf,"draftedViewDefinition");var Ks=z$1.object({type:z$1.literal("remove_operation"),operationId:z$1.string().min(1).describe("The id of a stored operation to drop from the draft")});function Bi(e,t=[]){let r=[...e.map(n=>n.schema),...t].map(Vf);return z$1.discriminatedUnion("type",r)}a(Bi,"union");function Ff(e){return e instanceof z$1.ZodString&&e.format==="uuid"}a(Ff,"isUuidString");function Vf(e){let t={};for(let[r,n]of Object.entries(e.shape)){if(!Ff(n))continue;let o=z$1.string().min(1);t[r]=n.description===void 0?o:o.describe(n.description);}return Object.keys(t).length===0?e:e.safeExtend(t)}a(Vf,"relaxUuidKeys");var Hs=Bi(ke,[Ks]),Ys=Bi(Ce),Qs=Bi(Ee),Mf={schema:Hs,"list-view":Ys,"detail-view":Qs},Lf=new Map([...ke.map(e=>[e.type,"schema"]),["remove_operation","schema"],...Ce.map(e=>[e.type,"list-view"]),...Ee.map(e=>[e.type,"detail-view"])]);function Bf(e){return Lf.get(e)??null}a(Bf,"familyOf");function $f(e){let t=e.config??{};if(e.attributeType==="relation")return `\u2192 ${G(e).map(r=>r.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($f,"attributeDetail");function Uf(e){let t=e.config?.options,r=$f(e);return {name:e.name,label:e.label,type:e.attributeType,...Array.isArray(t)?{options:t.map(n=>n.value)}:{},...r===void 0?{}:{detail:r}}}a(Uf,"summarizeAttribute");function qf(e,t,r){let n=me(e.id),o=r.some(a=>a.id===n.list);return {id:e.id,name:e.name,label:e.label,attributes:t.filter(a=>a.objectId===e.id).map(Uf),...o?{viewIds:n}:{}}}a(qf,"summarizeObject");function zf(e){return e.attribute??e.attributeGroup?.id??""}a(zf,"fieldName");function Gf(e){return e.type==="list"?(e.config.tabs??[]).map(r=>({id:r.id,label:r.label,columns:r.columns})):e.tabs.map(t=>{let r="groups"in t?t.groups:void 0;return {id:t.id,label:t.label,...r===void 0?{}:{groups:r.map(n=>({id:n.id,label:n.label,fields:n.fields.map(zf)}))}}})}a(Gf,"summarizeTab");function Wf(e,t){let r=t.find(n=>n.name===e.objectName)?.id;if(r===void 0)throw new h(`View "${e.id}" names object "${e.objectName}", which is not in the draft scope`,[]);return {id:e.id,type:e.type,objectId:r,label:e.label,derived:e.derived===true,tabs:Gf(e)}}a(Wf,"summarizeView");function Kf(e,t){let r=new Map;for(let n of e.sampleRecords)r.set(n.objectId,(r.get(n.objectId)??0)+1);return {objects:e.objects.map(n=>qf(n,e.attributes,e.views)),views:e.views.map(n=>Wf(n,e.objects)),sampleRecords:[...r.entries()].map(([n,o])=>({objectId:n,count:o})),operationCount:t}}a(Kf,"summarizeDraft");var Hf=["draft_schema","draft_list_view","draft_detail_view"],Yf="publish_architect_draft",Qf="discard_architect_draft",Jf="request_design_review",Xf="get_architect_draft";export{zx as AGENT_UI_BATCH_MAX_BYTES,Gx as AGENT_UI_BATCH_MAX_ITEMS,ko as ALLOWED_PROPERTY_TYPES,yr as ALL_ACTIONS,Sf as ALL_OPERATION_TYPES,lT as ALL_SYSTEM_RESOURCES,ky as ARTIFACT_FILE_ROLES,_y as ARTIFACT_KINDS,Wl as ARTIFACT_LIST_VIEW,ql as ARTIFACT_OBJECT,_t as ARTIFACT_OBJECT_NAME,Ny as ARTIFACT_RETENTIONS,zl as ARTIFACT_VIEW,yo as ATTRIBUTE_TYPES,Hg as AUDIT_ACTIONS,Kg as AUDIT_RESOURCE_TYPES,hn as ActivityTabConfig,Ir as AgentBuilder,Vg as BEHAVIOR_PROPERTIES,Mu as BYTE_UNIT_LABELS,Iu as CLAIMABLE_SESSION_STATUSES,He as COMPUTED_FUNCTIONS,RI as COMPUTED_FUNCTION_METADATA,sI as COMPUTED_FUNCTION_NAMES,XI as CONNECTOR_CALLBACK_PARAM,_o as COUNT_MODES,g as ComputedFormulaCompileError,gn as CustomTabConfig,sT as DB_COLUMN_FIELDS,Ho as DEFAULT_AGENT_EXECUTION_CONFIG,Ao as DEFAULT_APPROVAL_POLICY,Cy as DEFAULT_DICTATION_LIMITS,Vo as DEFAULT_LABEL_FALLBACK,Nu as DEFAULT_MEETING_BOT_DISPLAY_NAME,ml as DEFAULT_ROLES,pT as DEFAULT_ROLE_DESCRIPTIONS,cT as DEFAULT_ROLE_LABELS,mT as DEFAULT_ROLE_PERMISSIONS,lh as DEFAULT_TENANT_SETTINGS,Ee as DETAIL_VIEW_OPERATIONS,Qs as DETAIL_VIEW_OPERATION_INPUT,Dy as DICTATION_FINALIZATION_TIMEOUT_MS,wy as DICTATION_FRAME_BYTES,Iy as DICTATION_MAX_BUFFER_BYTES,xy as DICTATION_MAX_FRAME_BYTES,Sy as DICTATION_MAX_TRANSCRIPT_BYTES,Ey as DICTATION_MODEL_ID,Ry as DICTATION_PREPARATION_TIMEOUT_MS,Ty as DICTATION_SAMPLE_RATE,vy as DICTATION_TICKET_TTL_MS,Qf as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,SA as DOCUMENT_SYSTEM_ATTRIBUTES,Bs as DRAFTABLE_ATTRIBUTE_TYPES,Hf as DRAFT_WRITE_TOOL_NAMES,Ul as DRIVE_LIST_VIEW,Bl as DRIVE_OBJECT,Ot as DRIVE_OBJECT_NAME,$l as DRIVE_VIEW,xn as DetailViewBuilder,wn as DocumentsTabConfig,ft as EMPTY_VALUE_PLACEHOLDER,Ih as ESTIMATED_COUNT_CAP,An as EmailsTabConfig,nS as FAKE_MEETING_BOT_SIGNATURE_HEADER,Mf as FAMILY_INPUTS,fr as FORM_FORBIDDEN_ATTRIBUTE_TYPES,Ue as FlagRegistry,Ct as FlagService,dn as FormBuilder,Ke as FormRegistry,un as FormRowBuilder,ln as FormStepBuilder,Xf as GET_ARCHITECT_DRAFT_TOOL_NAME,St as GroupBuilder,Fg as IDENTITY_PROPERTIES,Ah as IMAGE_FORMATS,xo as INFERENCE_REASONING_OPTIONS,wo as INFERENCE_SPEEDS,Ce as LIST_VIEW_OPERATIONS,Ys as LIST_VIEW_OPERATION_INPUT,ud as LIVE_EVENT_TYPES,In as ListViewBuilder,Sn as ListViewTabConfigBuilder,vo as MAX_PRESET_DEPTH,ly as MAX_TODOS,cy as MAX_TODO_DESCRIPTION_CHARS,dy as MAX_TODO_ID_CHARS,py as MAX_TODO_RESULT_CHARS,w as MEETING_ATTRIBUTES,aa as MEETING_DETAIL_VIEW_ID,Yl as MEETING_LIST_VIEW,ia as MEETING_LIST_VIEW_ID,Kl as MEETING_OBJECT,Nt as MEETING_OBJECT_NAME,Hl as MEETING_VIEW,oa as MEETING_WRITE_SOURCE,Ll as MEMORY_LIST_VIEW,Vl as MEMORY_OBJECT,Ml as MEMORY_VIEW,Qc as McpOAuthCompletionMode,Tn as MeetingsTabConfig,Ru as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,Du as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,bo as NOTIFICATION_INBOX_STATES,po as NOTIFICATION_KINDS,mo as NOTIFICATION_PRIORITIES,fo as NOTIFICATION_SENSITIVITIES,Pg as NOTIFICATION_TYPES_V1,wu as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,Au as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,Tu as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,go as NOTIFICATION_WORK_STATES,iS as NO_RECORDING,Eo as NoopGeocodingAdapter,yt as OBJECT_NAME_SCHEMA,Su as OPEN_TOOL_PART_STATES,tt as OPERATION_REGISTRY,Kt as OPERATOR_SPECS,$e as ObjectBuilder,Mg as PRESENTATION_PROPERTIES,To as PROVIDER_NAMES,Yf as PUBLISH_ARCHITECT_DRAFT_TOOL_NAME,_A as QUALIFIED_SEPARATOR,Rh as QUOTA_KEYS,tS as RECORDING_OVERRIDES,rS as RECORDING_POLICIES,qo as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,ee as RELATION_TARGET_ANY,Ks as REMOVE_OPERATION_SCHEMA,Jf as REQUEST_DESIGN_REVIEW_TOOL_NAME,yn as RichtextTabConfig,ke as SCHEMA_OPERATIONS,Hs as SCHEMA_OPERATION_INPUT,q as SCHEMA_PLAN_LIMITS,wi as SCHEMA_SOURCE_ID_PATTERN,gy as SESSION_STATE_STREAM_ID,xu as SESSION_TERMINAL_STATUSES,ta as SKILL_CONTENT_TEMPLATE,Pl as SKILL_LIST_VIEW,Nl as SKILL_OBJECT,kl as SKILL_VIEW,hl as STANDARD_SCHEMA_VENDOR,mr as SYSTEM_PART_CODES,$ as SYSTEM_RESOURCES,dT as SYSTEM_RESOURCE_LABELS,Ma as TODAY_DEFAULT,ry as TODO_PLAN_STATUSES,uy as TODO_STATUSES,Io as TOOL_APPROVAL_STATES,te as TabBuilder,vt as TableTabConfig,Xp as UPDATE_TABLE_TAB_CHANGE_KEYS,_p as UPDATE_TAB_CHANGE_KEYS,Zp as UPDATE_TAB_CONFIG_CHANGE_KEYS,ch as USER_STATUSES,ph as USER_WORK_POSTURES,nh as accessLevelToActions,rh as actionsToAccessLevel,RT as agent,FS as agentDataChunk,ny as agentDisplayName,kS as agentInferencePreferencesSchema,fp as agentMessageAttachmentSchema,mp as agentMessagePartSchema,pp as agentSessionInferenceOverridesInputSchema,PS as agentSessionInferenceOverridesSchema,ts as agentSessionMessageSchema,wp as agentUIValidationError,Vi as applyOperations,el as applyPipes,ol as applyRelationProps,Yx as architectDraftChannelKey,Ci as assertAcyclicComputed,wa as assertAcyclicComputedDependencies,qm as assertBilateralPairs,xp as assertCustomAgentUIMessageChunk,Zc as assertSchemaSourceId,et as bilateralDeclarationOf,xl as booleanFlag,Ba as buildAgentFallbackTitle,pl as buildPermissionFlags,mt as buildPropertySchema,kA as buildQualifiedAttribute,Yo as checkbox,vu as compareAgentSessionMessages,Ze as compilablePlansOf,Lt as compileComputedFormula,va as compileRollupAttribute,Vu as computeByteMagnitude,Ei as computedCompileSchemaOf,rr as computedPlanOf,Xc as conversationDisplayTitle,Dl as createFlagRegistry,Cl as createFlagService,At as createStandardSchemaProps,LT as currency,as as customDataChunkSchemas,U as date,Ht as dateInTimezone,he as dateValueStart,me as defaultViewIdsFor,ki as defaultViewsFor,Yt as defineOperation,A as definePresentation,Oi as dependentsOf,Cf as deriveArchitectChanges,YI as deriveCreateDefaultsFromFilters,dl as deriveInitials,vf as describeOperations,Qa as destructiveSchema,H as detailView,Qo as document,Ps as draftedLabelExpression,ir as draftedObjectDefinition,jf as draftedViewDefinition,yp as durableDateSchema,_i as ensureFieldIds,Df as episodeImpactOf,wI as evaluateComputedAst,xI as evaluateComputedFormula,II as evaluateComputedFormulaWithResult,qc as evaluateFilterState,$I as evaluateRecordFilterState,Bo as extractAttributeNames,Uo as extractValueRefs,Bf as familyOf,Rl as flagRegistry,Mi as focusOf,XT as form,_u as formFieldFlatKey,Ou as formFieldKey,la as formRegistry,Bx as formatAgentStreamFrameId,Po as formatAttributeValue,AA as formatByteSize,Mc as formatComputedResult,Wu as formatLocationValue,zT as formula,Pf as fromDraftableView,Ge as generateDefaultDetailView,We as generateDefaultListView,Cx as getActiveTab,nl as getEditableLabelAttribute,Fy as getErrorMessage,Lu as getListViewDisplayAttributeNames,nI as getLiveProtocolPayloadChannel,cl as getRecordCreatorPrincipalId,$o as getSingleAttributeFromExpression,Do as getSlotFieldTargets,ul as getUserDisplayName,yw as group,mS as hasDestructiveEntries,ah as hasOptions,is as imageModelIdSchema,Te as includesAction,qg as inferInverseCardinality,Sc as inferRollupReturnType,vi as inferenceReasoningSchema,Si as inferenceSpeedSchema,Tp as isAgentUIDataName,Wx as isAgentUIMessageBatch,zg as isAttributeSortable,Ug as isBilateralRelation,OI as isCheckboxEquality,ty as isClaimableSessionStatus,Oe as isComputedAttribute,Vt as isComputedFunctionName,ne as isDateRangeValue,fT as isDefaultRole,pt as isDetailView,vA as isDocumentAttribute,ju as isEmptyObject,ku as isFieldGroup,By as isFormDefinition,ct as isFormFieldsRow,br as isFormFreeFieldRef,Ky as isFormHeadingRow,Hy as isFormSeparatorRow,Ro as isFormSlotFieldRef,Yy as isFormTextRow,gt as isLabelExpression,Oo as isListView,iI as isLiveEventEnvelope,Zx as isLiveEventPayload,yd as isLiveEventPayloadForType,gd as isLiveEventType,No as isNotEmpty,iy as isOpenToolPartState,Oa as isPlainRecord,CT as isStandardSchema,ay as isSystemPartCode,ey as isTerminalSessionStatus,Jg as isTerminalState,oy as isToolApprovalState,ho as isUniversalRelation,vl as jsonFlag,Zg as legacyStatusToSessionState,Y as listView,ca as liveChannelKey,UT as location,ks as makeFieldId,RA as matchesAccepts,bp as mentionReferenceSchema,gp as modelDefinitionSchema,ns as modelReferenceSchema,$T as multiselect,Cu as nativeAgentUIPartIdMetadataKey,Bu as normalizeDateValue,wt as number,Sl as numberFlag,dw as object,sy as orderAgentSessionMessages,$x as parseAgentStreamFrameId,Pu as parseCountMode,pa as parseLiveChannelKey,yy as parseNativeAgentUIPartIdsMetadata,Rf as parseOperation,xh as parseOptionalCountMode,NA as parseQualifiedAttribute,sp as persistedDefaultViewTargetSchema,DS as persistedSchemaPlanSchema,nt as persistedViewConfig,MT as phone,np as plannedAttributeSchema,ip as plannedInlineAttributeSchema,op as plannedObjectSchema,Li as presentationOf,Ws as proposalTargetKey,ap as proposedDefaultViewTargetSchema,rs as providerNameSchema,sl as qualifiedPropertyDefs,zy as readFormFieldValue,Pi as regenerateDerived,Gw as registry,Ie as relation,al as relationPropertyDefs,_e as relationTargetObjectName,G as relationTargets,$g as relationTargetsOf,Fi as relationValueIds,Ar as renderLabelExpression,Of as requiredTargetKeys,nd as resetViewToDefault,Hc as resolveAttributeDefaultValue,qy as resolveFieldRequired,Co as resolvePropertyDefinitions,xe as richtext,GT as rollup,Ic as rollupToFormulaExpression,RS as schemaPlanSchema,K as select,jS as sessionInferencePatchSchema,Xg as sessionStateToLegacyStatus,BT as status,Il as stringFlag,Kf as summarizeDraft,_f as targetTokensFor,b as text,nr as toAttribute,Km as toDraftableAttributes,Wm as toDraftableObject,kf as toDraftableView,Fu as toUndefinedIfEmpty,hp as todoItemSchema,Ap as todoPlanSchema,os as toolImpactSchema,qT as user,Be as validateAttributeName,Zu as validateLabelExpression,Tl as validateObjectExpressions,Le as validateObjectName,ht as validateViewName,Ni as viewIdFor,Ql as viewRegistry,fh as viewStateKey,ep as viewSyncPayload};
|
|
60
|
+
`)}debug(t){let r=this.summary();return t?.(r),r}makeKey(t,r,n){return `${t}:${r}:${n}`}};a(oi,"ViewRegistry");var ii=oi,Jl=new ii;function ua(e,t=[]){return e.filter(r=>!(!j$1(r).lifecycle.visibleInRuntime||r.system||t.includes(r.name)))}a(ua,"getRuntimeAttributes");function la(e){return [...e].sort((t,r)=>{let n=t.order??999,o=r.order??999;return n!==o?n-o:t.name.localeCompare(r.name)})}a(la,"sortAttributes");function Xl(e){if(e.type==="text"&&e.multiline)return 12;switch(e.type){case "richtext":case "location":return 12;case "checkbox":return 4;default:return 6}}a(Xl,"getDefaultFieldSpan");function Zl(e){return {attribute:e.name,span:Xl(e)}}a(Zl,"attributeToField");var kt="all",ze="form",Pt="general";function Ge(e,t={}){let{includeActivityTab:r=true,includeDocumentsTab:n=true,excludeAttributes:o=[]}=t,a=ua(e.attributes,o),s=la(a.filter(W=>j$1(W).presentation.formField)),c=[{id:ze,name:ze,label:"Details",type:"form",groups:[{id:Pt,label:"General",type:"fields",fields:s.map(Zl),order:0}],order:0}],f=1,x=e.attributes.some(W=>W.type==="document");n&&x&&c.push({id:"documents",name:"documents",label:"Documents",type:"documents",order:f++,allowUpload:true,allowRemove:true}),r&&c.push({id:"activity",name:"activity",label:"Activity",type:"activity",order:f++});let v={tabs:c};return {name:"default",label:"Default View",object:e.name,type:"detail",config:v,default:true}}a(Ge,"generateDefaultDetailView");function We(e,t={}){let{excludeAttributes:r=[],maxListColumns:n=5}=t,o=ua(e.attributes,r),s=la(o.filter(c=>j$1(c).presentation.defaultColumn)).slice(0,n).map(c=>c.name),l={tabs:[{id:kt,label:"All",default:true,visibility:"workspace",layout:"table",columns:s}]};return {name:"default",label:"All Records",object:e.name,type:"list",config:l,default:true}}a(We,"generateDefaultListView");function ed(e,t){let{preserveCustomTabs:r=true,preserveTableTabs:n=true}=t,o=[];for(let a of e.config.tabs)r&&a.type==="custom"&&o.push(a),n&&a.type==="table"&&o.push(a);return o}a(ed,"getPreservedDetailTabs");function td(e,t){if(t.length===0)return e;let r=e.find(s=>s.type==="form"),n=e.filter(s=>s.type!=="form"),o=[];r&&o.push(r);let a=1;for(let s of t)o.push({...s,order:a++});for(let s of n)o.push({...s,order:a++});return o}a(td,"mergeDetailTabs");function rd(e,t,r){let{preserveMetadata:n=true,...o}=r,a=Ge(t,o),s=ed(e,r),l=td(a.config.tabs,s),c={...a.config,tabs:l},f={...a,config:c};return n&&(f.id=e.id,f.name=e.name,f.label=e.label,f.description=e.description,f.icon=e.icon),f}a(rd,"resetDetailViewToDefault");function nd(e,t,r){let{preserveMetadata:n=true,...o}=r,s={...We(t,o)};return n&&(s.id=e.id,s.name=e.name,s.label=e.label,s.description=e.description,s.icon=e.icon),s}a(nd,"resetListViewToDefault");function id(e,t,r={}){if(pt(e))return rd(e,t,r);if(Oo(e))return nd(e,t,r);throw new Error(`Reset not supported for view type: ${e.type}`)}a(id,"resetViewToDefault");function Ox(e,t){if(t){let r=e.tabs.find(n=>n.id===t);if(r)return r}return e.tabs.find(r=>r.default)??e.tabs[0]}a(Ox,"getActiveTab");function ai(e){return structuredClone(e)}a(ai,"cloneFormDefinition");var si=class si{constructor(){this.forms=new Map;}register(t){let r$1=Array.isArray(t)?t:[t];for(let n of r$1){if(this.forms.has(n.name))throw new r("form",n.name,`[FormRegistry] Duplicate form: "${n.name}"`);this.forms.set(n.name,ai(n));}return this}get(t){let r=this.forms.get(t);return r?ai(r):void 0}getAll(){return Array.from(this.forms.values(),ai)}listNames(){return Array.from(this.forms.keys())}};a(si,"FormRegistry");var Ke=si;var da=new Ke;function $x(e,t){return `${e}:${t}`}a($x,"formatAgentStreamFrameId");function Ux(e){let t=e.lastIndexOf(":");if(t<=0)return null;let r=e.slice(0,t),n=Number(e.slice(t+1));return !Number.isInteger(n)||n<=0?null:{streamId:r,sequence:n}}a(Ux,"parseAgentStreamFrameId");var Gx=204800,Wx=256;function li(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(li,"isRecord");function di(e,t){let r=Object.keys(e);return r.length===t.length&&r.every(n=>t.includes(n))}a(di,"hasExactKeys");function ui(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}a(ui,"isPositiveInteger");function ca(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0}a(ca,"isNonNegativeInteger");function od(e){return li(e)&&di(e,["kind","startOffset","endOffset"])?(e.kind==="text"||e.kind==="reasoning")&&ca(e.startOffset)&&ca(e.endOffset)&&e.endOffset>=e.startOffset:false}a(od,"isContentRange");function ad(e){if(!li(e))return false;let t=e.content===void 0?["sequence","chunk"]:["sequence","content","chunk"];return di(e,t)&&ui(e.sequence)&&e.chunk!==void 0&&(e.content===void 0||od(e.content))}a(ad,"isBatchItem");function sd(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return}}a(sd,"encodedSize");function Kx(e){if(!(li(e)&&di(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()===""||!ui(e.sequenceStart)||!ui(e.sequenceEnd)||!Array.isArray(e.items)||e.items.length===0||e.items.length>256||!e.items.every(ad))return false;let t=0;for(let n of e.items){if(n.sequence<=t)return false;t=n.sequence;}if(e.items[0]?.sequence!==e.sequenceStart||e.items.at(-1)?.sequence!==e.sequenceEnd)return false;let r=sd(e);return r!==void 0&&r<=204800}a(Kx,"isAgentUIMessageBatch");function pa(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(pa,"liveChannelKey");function Qx(e){return e.sessionId?pa({kind:"architect-draft",scope:"session",sessionId:e.sessionId}):e.actorId?pa({kind:"architect-draft",scope:"actor",actorId:e.actorId}):null}a(Qx,"architectDraftChannelKey");function ie(e){try{return decodeURIComponent(e)}catch{return null}}a(ie,"decodeLiveChannelPart");function ma(e){let t=e.split(":");if(t[0]==="workspace"&&t.length===2&&t[1]){let r=ie(t[1]);return r?{kind:"workspace",tenantId:r}:null}if(t[0]==="object"&&t.length===2&&t[1]){let r=ie(t[1]);return r?{kind:"object",objectId:r}:null}if(t[0]==="record"&&t.length===3&&t[1]&&t[2]){let r=ie(t[1]),n=ie(t[2]);return r&&n?{kind:"record",objectId:r,recordId:n}:null}if(t[0]==="view"&&t.length===2&&t[1]){let r=ie(t[1]);return r?{kind:"view",viewId:r}:null}if(t[0]==="user"&&t.length===2&&t[1]){let r=ie(t[1]);return r?{kind:"user",actorId:r}:null}if(t[0]==="architect-draft"&&t.length===3&&t[2]){let r=ie(t[2]);return r?t[1]==="actor"?{kind:"architect-draft",scope:"actor",actorId:r}:t[1]==="session"?{kind:"architect-draft",scope:"session",sessionId:r}:null:null}if(t[0]==="conversation"&&t.length===2&&t[1]){let r=ie(t[1]);return r?{kind:"conversation",sessionId:r}:null}return null}a(ma,"parseLiveChannelKey");var ud={"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},ld=Object.keys(ud),dd=["membership-unknown","sort-unknown","permissions-changed"],cd=["permission-revoked","workspace-left","object-deleted"],pd=["inboxState","workState","lockedAt","lockedByActorId","readAt","archivedAt","snoozedUntil","completedAt","dismissedAt","updatedAt"],md=["type","objectId","recordId","recordVersion"],fd=["type","objectId","recordId","recordVersion","record"],bd=["id","objectId","visibility","ownedBy","label","values","metadata","createdAt","updatedAt","createdBy","lastUpdatedBy","schemaVersion"],gd=["type","targetActorId","archivedCount","version","updatedAt"];function yd(e){return typeof e=="string"&&ld.includes(e)}a(yd,"isLiveEventType");function eI(e){return _(e)&&yd(e.type)?hd(e.type,e):false}a(eI,"isLiveEventPayload");function hd(e,t){if(!_(t))return false;switch(e){case "record.patch":return vd(t);case "record.deleted":return Rd(t);case "record.removed":return Dd(t);case "record.created":return Cd(t);case "view.projection.stale":return Od(t);case "agent.session.patch":return _d(t);case "notification.created":return jd(t);case "notification.recipient.patch":return Fd(t);case "notification.count.patch":return Vd(t);case "notification.inbox.archived":return Md(t);case "reflex.state.changed":return zd(t);case "reflex.run.completed":return Gd(t);case "reflex.authoring.progress":return Wd(t);case "architect.draft.updated":return qd(t);case "meeting.recording.patch":return Hd(t);case "wallet.state":return Jd(t);case "channel.revoked":return Xd(t);default:return false}}a(hd,"isLiveEventPayloadForType");function _(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(_,"isRecord");function M(e){return typeof e=="string"}a(M,"isString");function fa(e){return M(e)&&e.length>0}a(fa,"isNonEmptyString");function jt(e){return e===null||M(e)}a(jt,"isNullableString");function Ad(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}a(Ad,"isVersion");function J(e){if(!M(e))return false;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}a(J,"isIsoDateString");function ve(e){return e===null||J(e)}a(ve,"isNullableIsoDateString");function S(e,t){return M(e[t])}a(S,"hasString");function oe(e,t){return fa(e[t])}a(oe,"hasNonEmptyString");function N(e,t){return Ad(e[t])}a(N,"hasVersion");function P(e,t){return J(e[t])}a(P,"hasIsoDateString");function I(e,t,r){return !Object.hasOwn(e,t)||r(e[t])}a(I,"hasOptional");function Ft(e,t){return Object.keys(e).every(r=>t.includes(r))}a(Ft,"hasOnlyKeys");function j(e,t){return typeof e=="string"&&t.includes(e)}a(j,"isOneOf");function Td(e){return j(e,po)}a(Td,"isNotificationKind");function wd(e){return j(e,mo)}a(wd,"isNotificationPriority");function xd(e){return j(e,fo)}a(xd,"isNotificationSensitivity");function ba(e){return j(e,bo)}a(ba,"isNotificationInboxState");function ga(e){return j(e,go)}a(ga,"isNotificationWorkState");function Id(e){return _(e)&&S(e,"type")&&S(e,"id")}a(Id,"isNotificationSubject");function Sd(e){return _(e)&&S(e,"fieldKey")&&Object.hasOwn(e,"value")&&N(e,"version")}a(Sd,"isRecordFieldPatch");function vd(e){return e.type==="record.patch"&&S(e,"objectId")&&S(e,"recordId")&&N(e,"recordVersion")&&I(e,"label",M)&&I(e,"metadata",_)&&I(e,"fieldsWithheld",t=>t===true)&&Array.isArray(e.fieldPatches)&&e.fieldPatches.every(Sd)&&S(e,"updatedAt")}a(vd,"isRecordPatchPayload");function Rd(e){return e.type==="record.deleted"&&S(e,"objectId")&&S(e,"recordId")&&N(e,"recordVersion")&&S(e,"deletedAt")}a(Rd,"isRecordDeletedPayload");function Dd(e){return e.type==="record.removed"&&Ft(e,md)&&S(e,"objectId")&&S(e,"recordId")&&N(e,"recordVersion")}a(Dd,"isRecordRemovedPayload");function Ed(e){return _(e)&&Ft(e,bd)&&S(e,"id")&&S(e,"objectId")&&j(e.visibility,["workspace","private"])&&jt(e.ownedBy)&&(e.visibility==="workspace"&&e.ownedBy===null||e.visibility==="private"&&fa(e.ownedBy))&&S(e,"label")&&_(e.values)&&I(e,"metadata",_)&&P(e,"createdAt")&&P(e,"updatedAt")&&I(e,"createdBy",M)&&I(e,"lastUpdatedBy",M)&&N(e,"schemaVersion")}a(Ed,"isRecordLiveSnapshot");function Cd(e){return e.type==="record.created"&&Ft(e,fd)&&S(e,"objectId")&&S(e,"recordId")&&N(e,"recordVersion")&&Ed(e.record)&&e.record.id===e.recordId&&e.record.objectId===e.objectId}a(Cd,"isRecordCreatedPayload");function Od(e){return e.type==="view.projection.stale"&&S(e,"viewId")&&j(e.reason,dd)}a(Od,"isViewProjectionStalePayload");function _d(e){return e.type==="agent.session.patch"&&S(e,"sessionId")&&_(e.patch)&&N(e,"version")&&S(e,"updatedAt")}a(_d,"isAgentSessionPatchPayload");function Nd(e){return _(e)&&S(e,"id")&&S(e,"tenantId")&&I(e,"senderActorId",M)&&I(e,"rootActorId",M)&&I(e,"triggeredByActorId",M)&&Td(e.kind)&&S(e,"type")&&I(e,"subject",Id)&&S(e,"title")&&I(e,"summary",M)&&_(e.payload)&&wd(e.priority)&&xd(e.sensitivity)&&I(e,"threadKey",M)&&I(e,"idempotencyKey",M)&&I(e,"expiresAt",J)&&P(e,"createdAt")&&P(e,"updatedAt")}a(Nd,"isLiveNotification");function kd(e){return _(e)&&S(e,"id")&&S(e,"tenantId")&&S(e,"notificationId")&&S(e,"recipientActorId")&&ba(e.inboxState)&&ga(e.workState)&&I(e,"lockedAt",J)&&I(e,"lockedByActorId",M)&&I(e,"readAt",J)&&I(e,"archivedAt",J)&&I(e,"snoozedUntil",J)&&I(e,"completedAt",J)&&I(e,"dismissedAt",J)&&P(e,"createdAt")&&P(e,"updatedAt")}a(kd,"isLiveNotificationRecipient");function Pd(e){return _(e)?Object.keys(e).every(t=>pd.includes(t))&&I(e,"inboxState",ba)&&I(e,"workState",ga)&&I(e,"lockedAt",ve)&&I(e,"lockedByActorId",jt)&&I(e,"readAt",ve)&&I(e,"archivedAt",ve)&&I(e,"snoozedUntil",ve)&&I(e,"completedAt",ve)&&I(e,"dismissedAt",ve)&&I(e,"updatedAt",J):false}a(Pd,"isNotificationRecipientPatch");function jd(e){let t=Nd(e.notification)?e.notification:null;return e.type==="notification.created"&&t!==null&&Array.isArray(e.recipients)&&e.recipients.length>0&&e.recipients.every(r=>kd(r)&&r.notificationId===t.id)&&N(e,"version")&&P(e,"updatedAt")}a(jd,"isNotificationCreatedPayload");function Fd(e){return e.type==="notification.recipient.patch"&&S(e,"recipientId")&&S(e,"recipientActorId")&&Pd(e.patch)&&N(e,"version")&&P(e,"updatedAt")}a(Fd,"isNotificationRecipientPatchPayload");function Vd(e){return e.type==="notification.count.patch"&&S(e,"targetActorId")&&N(e,"unread")&&N(e,"pendingWork")&&N(e,"version")&&P(e,"updatedAt")}a(Vd,"isNotificationCountPatchPayload");function Md(e){return e.type==="notification.inbox.archived"&&Ft(e,gd)&&oe(e,"targetActorId")&&N(e,"archivedCount")&&N(e,"version")&&P(e,"updatedAt")}a(Md,"isNotificationInboxArchivedPayload");var Ld=["armed","disarmed"],Bd=["authoring","compiling","replaying","promoted","failed"],$d=["promoted","lkg"],Ud=["composing","published","discarded"];function qd(e){if(e.type!=="architect.draft.updated"||!_(e.draft))return false;let t=e.draft;return oe(t,"id")&&oe(t,"actorId")&&jt(t.agentSessionId)&&Array.isArray(t.operations)&&t.operations.every(_)&&_(t.baselines)&&j(t.status,Ud)}a(qd,"isArchitectDraftUpdatedPayload");function zd(e){return e.type==="reflex.state.changed"&&oe(e,"reflexId")&&j(e.state,Ld)&&P(e,"updatedAt")}a(zd,"isReflexStateChangedPayload");function Gd(e){return e.type==="reflex.run.completed"&&oe(e,"reflexId")&&oe(e,"runId")&&j(e.served,$d)&&N(e,"version")&&N(e,"wallMs")&&P(e,"completedAt")}a(Gd,"isReflexRunCompletedPayload");function Wd(e){return e.type==="reflex.authoring.progress"&&oe(e,"reflexId")&&j(e.status,Bd)&&P(e,"updatedAt")}a(Wd,"isReflexAuthoringProgressPayload");var Kd=["none","scheduled","recording","completed","failed"];function Hd(e){return e.type==="meeting.recording.patch"&&oe(e,"meetingId")&&j(e.status,Kd)&&jt(e.failureReason)&&P(e,"updatedAt")}a(Hd,"isMeetingRecordingPatchPayload");var Yd=["ok","low","exhausted","paused"],Qd=["metering-only","contract","wallet"];function Jd(e){return e.type==="wallet.state"&&j(e.status,Yd)&&j(e.mode,Qd)&&P(e,"updatedAt")}a(Jd,"isWalletStatePayload");function Xd(e){return e.type==="channel.revoked"&&S(e,"channel")&&j(e.reason,cd)}a(Xd,"isChannelRevokedPayload");function ci(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(ci,"isRecord");function Zd(e){let{channel:t}=e;return typeof t=="string"&&ma(t)?t:null}a(Zd,"payloadChannel");function iI(e){return ci(e)?Zd(e):null}a(iI,"getLiveProtocolPayloadChannel");function oI(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(oI,"isLiveEventEnvelope");var uI=["if","concat","sum","avg","count","min","max","earliest","latest","unique","first","percent_empty","percent_not_empty","count_empty","count_not_empty","count_unique"],He={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 Vt(e){return Object.hasOwn(He,e)}a(Vt,"isComputedFunctionName");var bi=class bi extends Error{constructor(t){super(t),this.name="ComputedFormulaCompileError";}};a(bi,"ComputedFormulaCompileError");var g=bi;function Lt(e){let t=ec(e.expression),r=Mt(t,e.schema),n=xc(r.valueType);if(n!==e.returnType)throw new g(`Computed formula "${e.attributeName}" returns "${n}", expected "${e.returnType}"`);if(Ia(e.returnType)&&r.optionsSource===void 0)throw new g(`Computed formula "${e.attributeName}" returns "${e.returnType}" without optionsSource`);let o=r.optionsSource===void 0?[]:[{kind:"options",source:r.optionsSource}],a=fi([...r.dependencies,...o]);return {kind:"formula",attributeName:e.attributeName,expression:e.expression,returnType:e.returnType,valueType:r.valueType,dependencies:a,ast:t,...r.optionsSource?{optionsSource:r.optionsSource}:{},...r.targetAttributeType?{targetAttributeType:r.targetAttributeType}:{},dependenciesHash:Ic({expression:e.expression,returnType:e.returnType,dependencies:a})}}a(Lt,"compileComputedFormula");function xa(e){let t=new Map(e.map(o=>[o.attributeName,o])),r=new Set,n=a((o,a)=>{let s=a.indexOf(o);if(s!==-1){let f=[...a.slice(s),o];throw new g(`Computed field cycle detected: ${f.join(" -> ")}`)}if(r.has(o))return;let l=t.get(o);if(l===void 0)return;let c=[...a,o];for(let f of l.dependencies)f.kind==="computed"&&n(f.attributeName,c);r.add(o);},"visit");for(let o of e)n(o.attributeName,[]);}a(xa,"assertAcyclicComputedDependencies");function ec(e){try{return e$1(e)}catch(t){throw t instanceof Error?new g(t.message):t}}a(ec,"parseCompileFormula");function Mt(e,t){switch(e.kind){case "literal":return {valueType:tc(e.value),dependencies:[],...typeof e.value=="string"?{literalString:e.value}:{}};case "path":return rc(e.parts,t);case "call":return uc(e.functionName,e.args,t);case "binary":return mc(e.operator,Mt(e.left,t),Mt(e.right,t));default:return e}}a(Mt,"inferNode");function tc(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(tc,"literalToValueType");function rc(e,t){if(e.length===1){let r=e[0],n=pi(t,r);if(n===void 0)throw new g(`Unknown attribute "${r}" on object "${t.objectName}"`);return n.type==="relation"?{valueType:oc(),dependencies:[{kind:"relation",relationName:n.name,cardinality:ya(n)}],targetAttributeType:n.type}:{valueType:ha(n),dependencies:[ic(n)],optionsSource:Aa(t.objectName,n),targetAttributeType:n.type}}if(e.length===2){let[r,n]=e,o=pi(t,r);if(o===void 0)throw new g(`Unknown attribute "${r}" on object "${t.objectName}"`);if(o.type!=="relation")throw new g(`Attribute "${r}" on object "${t.objectName}" is not a relation`);let a=nc(o);if(a===void 0)throw new g(`Relation "${r}" on object "${t.objectName}" is missing targetObjectName`);let s=t.relatedObjects?.[a];if(s===void 0)throw new g(`Unknown related object "${a}"`);let l=pi(s,n);if(l===void 0)throw new g(`Unknown attribute "${n}" on object "${s.objectName}"`);let c=ha(l);return {valueType:o.cardinality==="many"?sc(c):c,dependencies:[{kind:"relation",relationName:r,targetAttributeName:n,cardinality:ya(o)}],optionsSource:Aa(s.objectName,l),targetAttributeType:l.type}}throw new g("Computed paths support at most one relation hop")}a(rc,"inferPath");function pi(e,t){return e.attributes.find(r=>r.name===t)}a(pi,"findAttribute");function nc(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(nc,"getRelationTargetObjectName");function ya(e){return e.cardinality??"one"}a(ya,"relationCardinality");function ic(e){return e.type==="formula"||e.type==="rollup"?{kind:"computed",attributeName:e.name}:{kind:"local",attributeName:e.name}}a(ic,"localDependencyFor");function ha(e){if(e.type==="formula"||e.type==="rollup"){if(e.returnType===void 0)throw new g(`Computed attribute "${e.name}" is missing returnType`);return ac(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(ha,"attributeToValueType");function oc(){return {kind:"collection",itemType:"text"}}a(oc,"relationToValueType");function ac(e){return e==="multiselect"?{kind:"collection",itemType:"select"}:{kind:"scalar",type:e}}a(ac,"returnTypeToValueType");function sc(e){return e.kind==="collection"?e:{kind:"collection",itemType:e.type}}a(sc,"asCollectionValueType");function Aa(e,t){if(t.type==="formula"||t.type==="rollup")return Ia(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(Aa,"optionsSourceForAttribute");function uc(e,t,r){if(!Vt(e))throw new g(`Unknown computed function "${e}"`);let n=He[e];if(t.length<n.minArgs||n.maxArgs!==void 0&&t.length>n.maxArgs){let a=n.maxArgs===void 0||n.maxArgs===n.minArgs?String(n.minArgs):`${n.minArgs}-${n.maxArgs}`;throw new g(`Function "${e}" expects ${a} arguments, received ${t.length}`)}let o=t.map(a=>Mt(a,r));return lc(e,o)}a(uc,"inferCall");function lc(e,t){let r=fi(t.flatMap(n=>n.dependencies));switch(e){case "if":return dc(t,r);case "concat":return fc(t,`Function "${e}" does not accept collection values`),{valueType:{kind:"scalar",type:"text"},dependencies:r};case "sum":case "avg":return Ta(e,t[0],"number"),{valueType:{kind:"scalar",type:"number"},dependencies:r};case "count":case "count_empty":case "count_not_empty":case "count_unique":case "percent_empty":case "percent_not_empty":return gc(e,t[0]),{valueType:{kind:"scalar",type:"number"},dependencies:r};case "min":case "max":return bc(e,t[0]),{valueType:yc(t[0]),dependencies:r,optionsSource:t[0].optionsSource,targetAttributeType:t[0].targetAttributeType};case "earliest":case "latest":return Ta(e,t[0],"date"),{valueType:{kind:"scalar",type:"date"},dependencies:r,targetAttributeType:t[0].targetAttributeType};case "unique":return cc(t[0],r);case "first":return pc(t[0],r);default:return e}}a(lc,"inferFunctionReturn");function dc(e,t){mi(e[0].valueType,"boolean",'Function "if" condition must be boolean');let r=e[1],n=e[2],o=Ac(r,n),a=Tc(r,n);if(o===void 0)throw new g('Function "if" branches must return the same type');return {valueType:o,dependencies:t,...a?{optionsSource:a}:{},targetAttributeType:r.targetAttributeType??n.targetAttributeType}}a(dc,"inferIfFunction");function cc(e,t){if(e.valueType.kind!=="collection"||e.valueType.itemType!=="select")throw new g('Function "unique" expects a select collection');return {valueType:{kind:"collection",itemType:"select"},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a(cc,"inferUniqueFunction");function pc(e,t){if(e.valueType.kind!=="collection")throw new g('Function "first" expects a collection');return {valueType:{kind:"scalar",type:e.valueType.itemType},dependencies:t,optionsSource:e.optionsSource,targetAttributeType:e.targetAttributeType}}a(pc,"inferFirstFunction");function mc(e,t,r){let n=fi([...t.dependencies,...r.dependencies]),o=e==="+"||e==="-"||e==="*"||e==="/";if(t.valueType.kind==="collection"||r.valueType.kind==="collection")throw new g(`Cannot use collection values with ${o?"arithmetic":"comparison"} operator "${e}"`);if(o)return e==="+"&&(t.valueType.type==="text"||r.valueType.type==="text")?{valueType:{kind:"scalar",type:"text"},dependencies:n}:(mi(t.valueType,"number",`Operator "${e}" expects number operands`),mi(r.valueType,"number",`Operator "${e}" expects number operands`),{valueType:{kind:"scalar",type:"number"},dependencies:n});if(e==="=="||e==="!="){if(t.valueType.type!==r.valueType.type)throw new g(`Operator "${e}" expects operands with the same scalar type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:n}}if((t.valueType.type!=="number"||r.valueType.type!=="number")&&(t.valueType.type!=="date"||r.valueType.type!=="date"))throw new g(`Operator "${e}" expects number or date operands of the same type`);return {valueType:{kind:"scalar",type:"boolean"},dependencies:n}}a(mc,"inferBinary");function fc(e,t){for(let r of e)if(r.valueType.kind==="collection")throw new g(t)}a(fc,"ensureNoCollections");function Ta(e,t,r){if((t.valueType.kind==="collection"?t.valueType.itemType:t.valueType.type)!==r)throw new g(`Function "${e}" expects ${r} values`)}a(Ta,"ensureCollectionOrScalarType");function bc(e,t){if(t.valueType.kind!=="collection")throw new g(`Function "${e}" expects a collection`);let r=t.valueType.itemType;if(r!=="number"&&r!=="date")throw new g(`Function "${e}" expects number or date values`)}a(bc,"ensureMinMaxSource");function gc(e,t){if(t.valueType.kind!=="collection")throw new g(`Function "${e}" expects a collection`)}a(gc,"ensureCollectionSource");function mi(e,t,r){if(e.kind!=="scalar"||e.type!==t)throw new g(r)}a(mi,"ensureScalarType");function yc(e){return e.valueType.kind==="scalar"?e.valueType:{kind:"scalar",type:e.valueType.itemType}}a(yc,"sourceItemValueType");function hc(e,t){return e.kind==="scalar"?t.kind==="scalar"&&e.type===t.type:t.kind==="collection"&&e.itemType===t.itemType}a(hc,"sameValueType");function Ac(e,t){if(hc(e.valueType,t.valueType)||wa(e,t))return e.valueType;if(wa(t,e))return t.valueType}a(Ac,"resolveIfBranchValueType");function wa(e,t){return e.valueType.kind==="scalar"&&e.valueType.type==="select"&&t.valueType.kind==="scalar"&&t.valueType.type==="text"&&t.literalString!==void 0}a(wa,"isSelectScalarWithStringLiteral");function Tc(e,t){let r=e.optionsSource,n=t.optionsSource;if(r!==void 0&&n!==void 0&&!wc(r,n))throw new g('Function "if" branches use incompatible options sources');return r??n}a(Tc,"resolveIfOptionsSource");function wc(e,t){return e.objectName===t.objectName&&e.attributeName===t.attributeName&&e.attributeId===t.attributeId}a(wc,"sameOptionsSource");function Ia(e){return e==="select"||e==="multiselect"}a(Ia,"isSelectLikeReturnType");function xc(e){if(e.kind==="scalar")return e.type;if(e.itemType==="select")return "multiselect";throw new g(`Collection item type "${e.itemType}" cannot be used as a computed return type`)}a(xc,"valueTypeToReturnType");function fi(e){let t=new Set,r=[];for(let n of e){let o=JSON.stringify(Ye(n));t.has(o)||(t.add(o),r.push(n));}return r}a(fi,"uniqueDependencies");function Ic(e){let t=e.dependencies.map(r=>Ye(r)).sort((r,n)=>Sa(JSON.stringify(r),JSON.stringify(n)));return JSON.stringify(Ye({expression:e.expression,returnType:e.returnType,dependencies:t}))}a(Ic,"createDependenciesHash");function Ye(e){return Array.isArray(e)?e.map(t=>Ye(t)):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[r])=>Sa(t,r)).map(([t,r])=>[t,Ye(r)])):e}a(Ye,"stableNormalize");function Sa(e,t){return e<t?-1:e>t?1:0}a(Sa,"compareStrings");function Sc(e){return e.function==="count"?`count(${e.relationAttribute})`:`${Dc(e.function)}(${e.relationAttribute}.${e.targetAttribute})`}a(Sc,"rollupToFormulaExpression");function vc(e,t){if(e.function==="count")return "number";let r=Ec(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(!Oc(r.type))throw new g('Rollup "original" requires a select, status, or multiselect target');return "multiselect";default:return e.function}}a(vc,"inferRollupReturnType");function Ra(e,t){let r=Sc(e),n=vc(e,t);return {...Lt({attributeName:e.name,expression:r,returnType:n,schema:Rc(e,t)}),kind:"rollup"}}a(Ra,"compileRollupAttribute");function Rc(e,t){return {...t,attributes:t.attributes.map(r=>r.name===e.relationAttribute&&r.type==="relation"?{...r,cardinality:"many"}:r)}}a(Rc,"schemaWithRollupRelationAsMany");function Dc(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(Dc,"rollupFunctionToFormulaFunction");function Ec(e,t){let r=va(t,e.relationAttribute);if(r===void 0)throw new g(`Unknown relation attribute "${e.relationAttribute}" on object "${t.objectName}"`);if(r.type!=="relation")throw new g(`Attribute "${e.relationAttribute}" on object "${t.objectName}" is not a relation`);let n=Cc(r);if(n===void 0)throw new g(`Relation "${e.relationAttribute}" on object "${t.objectName}" is missing targetObjectName`);let o=t.relatedObjects?.[n];if(o===void 0)throw new g(`Unknown related object "${n}"`);let a=va(o,e.targetAttribute);if(a===void 0)throw new g(`Unknown attribute "${e.targetAttribute}" on object "${o.objectName}"`);return a}a(Ec,"findRollupTargetAttribute");function va(e,t){return e.attributes.find(r=>r.name===t)}a(va,"findAttribute");function Cc(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(Cc,"getRelationTargetObjectName");function Oc(e){return e==="select"||e==="status"||e==="multiselect"}a(Oc,"isSelectLikeAttributeType");function re(e,t){switch(e.kind){case "literal":return e.value;case "path":return Nc(t,e.parts);case "binary":return kc(e.operator,re(e.left,t),re(e.right,t));case "call":return _c(e.functionName,e.args,t);default:return e}}a(re,"evaluateAst");function _c(e,t,r){if(jc(e),Fc(e,t.length),e==="if"){let n=re(t[0],r);return n===null?null:re(n?t[1]:t[2],r)}return Vc(e,t.map(n=>re(n,r)))}a(_c,"evaluateCallNode");function Nc(e,t){return t.reduce((r,n)=>Na(r,n),e)}a(Nc,"resolvePath");function Na(e,t){if(Array.isArray(e))return e.map(n=>Na(n,t));if(!_a(e))return null;if(Object.hasOwn(e,t))return e[t]??null;let r=e.values;return _a(r)&&Object.hasOwn(r,t)?r[t]??null:null}a(Na,"resolvePathPart");function kc(e,t,r){switch(e){case "+":return Pc(t,r);case "-":return $t(t,r,(n,o)=>n-o);case "*":return $t(t,r,(n,o)=>n*o);case "/":return $t(t,r,(n,o)=>n/o);case ">":return Bt(t,r,n=>n>0);case "<":return Bt(t,r,n=>n<0);case ">=":return Bt(t,r,n=>n>=0);case "<=":return Bt(t,r,n=>n<=0);case "==":return Da(t,r);case "!=":{let n=Da(t,r);return n===null?null:!n}default:return e}}a(kc,"evaluateBinary");function Pc(e,t){return typeof e=="string"||typeof t=="string"?`${e??""}${t??""}`:$t(e,t,(r,n)=>r+n)}a(Pc,"add");function Bt(e,t,r){let n=ka(e,t);return n===null?null:r(n)}a(Bt,"compareWith");function ka(e,t){if(!Re([e,t]))return null;let r=De(e),n=De(t);if(r!==null&&n!==null)return r-n;let o=hi(e),a=hi(t);return o&&a?o.getTime()-a.getTime():null}a(ka,"compare");function Da(e,t){return e===t?true:e==null||t===null||t===void 0?false:Re([e,t])?ka(e,t)===0:null}a(Da,"equalScalar");function jc(e){if(!Vt(e))throw new Error(`Unknown computed function "${e}"`)}a(jc,"assertComputedFunctionName");function Fc(e,t){let{minArgs:r,maxArgs:n}=He[e];if(t>=r&&t<=(n??Number.POSITIVE_INFINITY))return;let o=n===void 0?`at least ${r}`:`between ${r} and ${n}`;throw new Error(`Function "${e}" expects ${o} arguments, received ${t}`)}a(Fc,"validateArity");function Vc(e,t){switch(e){case "concat":return t.filter(r=>r!=null).map(String).join("");case "sum":return Re(t)?gi(t).reduce((r,n)=>r+n,0):null;case "avg":{if(!Re(t))return null;let r=gi(t);return r.length>0?r.reduce((n,o)=>n+o,0)/r.length:null}case "count":return pe(t[0]).length;case "min":return Ea(t,"min");case "max":return Ea(t,"max");case "earliest":return yi(t,"min");case "latest":return yi(t,"max");case "unique":return Oa(pe(t[0]));case "first":return pe(t[0]).find(r=>r!=null)??null;case "percent_empty":return Ca(t[0],true);case "percent_not_empty":return Ca(t[0],false);case "count_empty":return pe(t[0]).filter(a$1).length;case "count_not_empty":return pe(t[0]).filter(r=>!a$1(r)).length;case "count_unique":return Oa(pe(t[0])).length;default:return e}}a(Vc,"evaluateCall");function gi(e){return Ut(e).map(De).filter(t=>t!==null)}a(gi,"numericValues");function Re(e){let t=new Set;for(let r of Ut(e))Ai(r)&&t.add(Pa(r));return t.size<=1}a(Re,"areCommensurable");function Pa(e){return e.code.toUpperCase()}a(Pa,"currencyCode");function $t(e,t,r){if(!Re([e,t]))return null;let n=De(e),o=De(t);if(n===null||o===null)return null;let a=r(n,o);return Number.isFinite(a)?a:null}a($t,"numericBinary");function Ea(e,t){if(!Re(e))return null;let r=gi(e);return r.length>0?t==="min"?Math.min(...r):Math.max(...r):yi(e,t)}a(Ea,"minMax");function yi(e,t){let r=Ut(e).map(hi).filter(a=>a!==null);if(r.length===0)return null;let n=r.map(a=>a.getTime()),o=t==="min"?Math.min(...n):Math.max(...n);return new Date(o).toISOString()}a(yi,"dateMinMax");function Ca(e,t){let r=pe(e);return r.length===0?0:r.filter(o=>a$1(o)===t).length/r.length}a(Ca,"percentByEmptyState");function Oa(e){let t=new Set,r=[];for(let n of e){if(a$1(n))continue;let o=Mc(n);t.has(o)||(t.add(o),r.push(n));}return r}a(Oa,"uniqueNonEmpty");function pe(e){return e==null?[]:Array.isArray(e)?Ut(e):[e]}a(pe,"collectionItems");function Ut(e){return e.flat(Number.POSITIVE_INFINITY)}a(Ut,"flatten");function De(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 Ai(e)&&Number.isFinite(e.value)?e.value:null}a(De,"toFiniteNumber");function Ai(e){return typeof e=="object"&&e!==null&&typeof e.value=="number"&&typeof e.code=="string"}a(Ai,"isCurrencyValue");function hi(e){if(e instanceof Date)return Number.isNaN(e.getTime())?null:e;if(typeof e!="string"){let r=he(e);if(r===null)return null;let n=new Date(r);return Number.isNaN(n.getTime())?null:n}let t=new Date(e);return Number.isNaN(t.getTime())?null:t}a(hi,"toDate");function Mc(e){if(Ai(e))return `currency:${Pa(e)}:${e.value}`;let t=De(e);return t!==null?`number:${t}`:e instanceof Date?`date:${e.toISOString()}`:`${typeof e}:${JSON.stringify(e)}`}a(Mc,"uniqueKey");function _a(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}a(_a,"isPlainRecord");function Lc(e,t,r){if(e==null)return null;let n=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:r!==void 0?Number(o.toFixed(r)):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=n(o);if(a!==null)return a}return null}return n(e);case "multiselect":return Array.isArray(e)?e.flatMap(o=>{if(o==null)return [];let a=n(o);return a===null?[]:[a]}):n(e)===null?[]:[String(e)];default:{let o=t;throw new Error(`Unsupported computed return type: ${o}`)}}}a(Lc,"formatComputedResult");function xI(e,t){return re(e,t)}a(xI,"evaluateComputedAst");function II(e,t){return re(e$1(e),t)}a(II,"evaluateComputedFormula");function SI(e,t,r,n){try{let o=re(e$1(e),t);return {value:r?Lc(o,r,n):o}}catch(o){return {value:null,error:o instanceof Error?o.message:String(o)}}}a(SI,"evaluateComputedFormulaWithResult");var DI=[{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 ja=a(e=>a$1(e)||Array.isArray(e)&&e.length===0,"isEmpty"),L=a(e=>e==null?"":String(e),"toStr"),Gt=a(e=>{if(a$1(e))return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null},"toNum"),Wt=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"),qt=a(e=>Array.isArray(e)?e:e==null?[]:[e],"toArr"),Bc=a((e,t,r)=>{let n=Gt(e),o=Gt(t);return n!==null&&o!==null&&r(n,o)},"compareNumbers"),$c=a((e,t,r)=>{let n=Wt(e),o=Wt(t);return n!==null&&o!==null&&r(n.getTime(),o.getTime())},"compareDates"),Fa=a((e,t,r)=>{if(r.type==="number"||r.type==="currency"){let n=Gt(e),o=Gt(t);if(n!==null&&o!==null)return n===o}return L(e)===L(t)},"equalsForAttr");function _I(e,t){return e?e==="checkbox":typeof t=="boolean"}a(_I,"isCheckboxEquality");var zt=a(e=>({appliesTo:["number","currency","date","formula"],evaluateInMemory:a((t,r,n)=>n.type==="date"?$c(t,r,e):Bc(t,r,e),"evaluateInMemory")}),"orderingSpec"),Kt={is:{appliesTo:["text","phone","number","currency","checkbox","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,r)=>r.type==="checkbox"?e===true==(t===true):Fa(e,t,r),"evaluateInMemory")},is_not:{appliesTo:["text","phone","number","currency","status","select","date","user","relation","formula"],evaluateInMemory:a((e,t,r)=>!Fa(e,t,r),"evaluateInMemory")},contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>L(e).toLowerCase().includes(L(t).toLowerCase()),"evaluateInMemory")},not_contains:{appliesTo:["text","phone","formula"],evaluateInMemory:a((e,t)=>!L(e).toLowerCase().includes(L(t).toLowerCase()),"evaluateInMemory")},starts_with:{appliesTo:["text","phone"],evaluateInMemory:a((e,t)=>L(e).toLowerCase().startsWith(L(t).toLowerCase()),"evaluateInMemory")},ends_with:{appliesTo:["text"],evaluateInMemory:a((e,t)=>L(e).toLowerCase().endsWith(L(t).toLowerCase()),"evaluateInMemory")},is_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>ja(e),"evaluateInMemory")},is_not_empty:{appliesTo:["text","richtext","number","phone","currency","status","select","date","multiselect","location","user","relation","formula","document"],evaluateInMemory:a(e=>!ja(e),"evaluateInMemory")},less_than:zt((e,t)=>e<t),greater_than:zt((e,t)=>e>t),less_or_equal:zt((e,t)=>e<=t),greater_or_equal:zt((e,t)=>e>=t),is_within:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let r=Wt(e),n=S$1(t);return r&&n?r.getTime()>=n.startMs&&r.getTime()<n.endMs:false},"evaluateInMemory")},on_day_month:{appliesTo:["date"],evaluateInMemory:a((e,t)=>{let r=Wt(e);if(!r)return false;let n=t;return r.getMonth()+1===n.month&&r.getDate()===n.day},"evaluateInMemory")},any_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let r=qt(t).map(L);return qt(e).map(L).some(o=>r.includes(o))},"evaluateInMemory")},none_of:{appliesTo:["status","select","multiselect","user","relation"],evaluateInMemory:a((e,t)=>{let r=qt(t).map(L);return !qt(e).map(L).some(o=>r.includes(o))},"evaluateInMemory")}};var Uc=a((e,t)=>({id:`system:${e}`,name:e,label:e,type:t,system:true}),"systemAttribute"),qc=[...Object.entries(V).map(([e,t])=>Uc(e,t))];function UI(e,t,r){let n=t;return zc(e,{...t.values,id:t.id,objectId:t.objectId,objectName:n.objectName,tenantId:n.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},[...r,...qc])}a(UI,"evaluateRecordFilterState");function zc(e,t,r){if(e.rules.length===0)return true;let n=new Map(r.map(a=>[a.name,a])),o=e.combinator==="or"?"some":"every";return e.rules[o](a=>Gc(a,t,n))}a(zc,"evaluateFilterState");function Gc(e,t,r){let n=r.get(e.attribute);if(!n)return false;if(e.property&&n.type==="location"){if(!(g$1(e.property)&&h$2(e.operator)))return false;let l=Kt[e.operator];if(!l)return false;let c=t[e.attribute],f=typeof c=="object"&&c!==null?c[e.property]:void 0;return Ti(l,"text",e.operator,f,e.value,n)}if(e.property){let l=Co(n).find(R=>R.name===e.property);if(!l)return false;let c=K$1(e.operator),f=Kt[c];if(!f?.appliesTo.includes(l.type))return false;let x=t[e.attribute],W=(Array.isArray(x)?x:x==null?[]:[x]).some(R=>{if(typeof R!="object"||R===null)return false;let X=R.props;return typeof X!="object"||X===null?false:Ti(f,l.type,c,X[e.property],e.value,l)});return (e.quantifier??J$1(e.operator))==="none"?!W:W}let o=Kt[e.operator];if(!o||!o.appliesTo.includes(n.type))return false;let a=t[e.attribute],s=n.type==="relation"||n.type==="document"||n.type==="user"?Hc(a):a;return Ti(o,n.type,e.operator,s,e.value,n)}a(Gc,"evaluateRule");function Ti(e,t,r,n,o,a){let[s,l]=Wc(t,r,n,o);return t==="phone"&&l===""&&r==="contains"?false:t==="phone"&&l===""&&r==="not_contains"?true:e.evaluateInMemory(s,l,a)}a(Ti,"evaluateNormalizedComparands");function Wc(e,t,r,n){return e==="date"&&(t==="is"||t==="is_not")?[Va(r),Va(n)]:e==="phone"?Kc(r,n):[Ma(e,r),Ma(e,n)]}a(Wc,"normalizeOperatorComparands");function Va(e){let t=ne(e)?he(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 r=new Date(t);return Number.isNaN(r.getTime())?null:r.toISOString().slice(0,10)}a(Va,"normalizeUtcCalendarDay");function Kc(e,t){let r=typeof t=="object"&&t!==null?t:{},n=typeof r.countryCode=="string"?r.countryCode:void 0,o=a(a=>{let s=typeof a=="object"&&a!==null?a:{phoneNumber:a};if(typeof s.phoneNumber!="string")return null;if(!n)return a$3(s.phoneNumber);let l=typeof s.countryCode=="string"?s.countryCode:n;return `${l}:${b$2(s.phoneNumber,l)}`},"normalizeOne");return [o(e),o(t)]}a(Kc,"normalizePhoneComparands");function Ma(e,t){return e==="currency"?H$1(t):e==="date"?ne(t)?he(t):t instanceof Date?Number.isNaN(t.getTime())?null:t.toISOString():t:t}a(Ma,"normalizeComparableValue");function Hc(e){let t=a(r=>typeof r!="object"||r===null?r:r.id,"normalizeOne");return Array.isArray(e)?e.map(t):t(e)}a(Hc,"normalizeReferenceIds");var La="today";function Ht(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}a(Ht,"dateInTimezone");function Yc(e,t){if(!("defaultValue"in e))return;let{defaultValue:r}=e;return e.type!=="date"||r!==La?r:e.includeTime?t.now.toISOString():Ht(t.now,t.timezone)}a(Yc,"resolveAttributeDefaultValue");function QI(e,t,r){if(e.combinator==="or"&&e.rules.length>1)return {};let n=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=n.get(a.attribute);if(!s)continue;let l=Qc(a,r);l!==void 0&&(o[a.attribute]=j$1(s).storage.cardinality==="many"?[l]:l);}return o}a(QI,"deriveCreateDefaultsFromFilters");function Qc(e,t){if(e.operator==="is")return D$1(e.value)?Ba(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 r=e.value[0];return D$1(r)?Ba(r,t):r}}a(Qc,"extractDeterministicValue");function Ba(e,t){if(t){if(e.dynamic==="actor")return t.userId;if(e.anchor==="today")return Ht(t.now,t.timezone);if(e.anchor==="now")return t.now.toISOString()}}a(Ba,"resolveDynamicValue");var ZI={status:"connector_status",error:"connector_error",provider:"connector_provider"};var Jc=(t=>(t.Desktop="desktop",t))(Jc||{});var rS=["force","skip"],nS=["none","all","external_only"],iS="x-fake-signature",oS={override:null,status:"none",failureReason:null,botId:null};var Xc=/^Session \d+$/;function $a(e){let t=e.replace(/\s+/g," ").trim().replace(/[.!?]+$/,"");return t?t.length>60?`${t.slice(0,59).trimEnd()}...`:t:"New conversation"}a($a,"buildAgentFallbackTitle");function Zc(e){let t=e.generated?.trim();return t&&!Xc.test(t)?t:e.firstUserText?$a(e.firstUserText):e.emptyLabel}a(Zc,"conversationDisplayTitle");var wi=/^[a-z0-9][a-z0-9-]{0,62}$/;function ep(e){if(!wi.test(e))throw new h(`Invalid schema source id "${e}": expected a lowercase slug matching ${wi}`,[])}a(ep,"assertSchemaSourceId");function tp(e){return {label:e.label,description:e.description??null,icon:e.icon??null,config:e.config,default:e.default??false,metadata:e.metadata??null}}a(tp,"viewSyncPayload");function fS(e){let{attributeRemovals:t,objectRemovals:r,renames:n}=e.destructive;return t.length>0||r.length>0||n.length>0}a(fS,"hasDestructiveEntries");var q={objectAdditions:20,totalMutations:500,serializedBytes:512*1024};function Ii(e){return e instanceof Error?e.message:String(e)}a(Ii,"errorMessage");var rp=z$1.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 Ha=z$1.string().min(1).superRefine((e,t)=>{try{Be(e);}catch(r){t.addIssue({code:z$1.ZodIssueCode.custom,message:Ii(r)});}}).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).'),np=z$1.string().min(1).superRefine((e,t)=>{w$1(e)&&t.addIssue({code:z$1.ZodIssueCode.custom,message:`"${e}" is a reserved object name (${C.join(", ")}) and cannot be used for a new object.`});try{Le(e);}catch(r){t.addIssue({code:z$1.ZodIssueCode.custom,message:Ii(r)});}}).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 Ya(e){return e.superRefine((t,r)=>{try{let n=n$1(t.type,{...t.config??{},description:t.description}),o=Object.keys(t.config??{}).filter(a=>!Object.hasOwn(n,a));o.length>0&&r.addIssue({code:"unrecognized_keys",keys:o,path:["config"],message:`Unrecognized attribute config key${o.length===1?"":"s"}: ${o.join(", ")}`});}catch(n){if(n instanceof h){for(let o of n.errors)r.addIssue({code:z$1.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}r.addIssue({code:z$1.ZodIssueCode.custom,path:["config"],message:`Config for type "${t.type}" is invalid or incomplete: ${Ii(n)}`});}})}a(Ya,"withConfigCheck");var Qa=z$1.object({objectName:z$1.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:Ha,label:z$1.string().min(1).max(128).describe("Human-readable display label shown in the UI. 1-128 characters, cannot be empty."),type:rp,config:z$1.record(z$1.string(),z$1.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$1.boolean().optional().describe("Whether the attribute must have a value on every record. Defaults to false (optional)."),description:z$1.string().optional().describe("Help text shown under the field in the UI. Not the same as the plan's `summary`.")}).strict(),ip=Ya(Qa),op=Ya(Qa.omit({objectName:true})),ap=z$1.object({name:np,label:z$1.string().min(1).describe('Human-readable singular display label (e.g. "Devis").'),pluralLabel:z$1.string().optional().describe('Human-readable plural display label (e.g. "Devis"/"Invoices"). Defaults from `label` if omitted.'),description:z$1.string().optional().describe("Help text describing what this object represents."),icon:c.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:Ae.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$1.array(op).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(),Ja=z$1.object({attributeRemovals:z$1.array(z$1.object({objectName:z$1.string().min(1).describe("Object the attribute is removed from."),attributeName:z$1.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$1.array(z$1.object({objectName:z$1.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$1.array(z$1.object({objectName:z$1.string().min(1).describe("Object the renamed attribute belongs to."),from:z$1.string().min(1).describe("Current attribute name. Must already exist and not be a system attribute."),to:Ha.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:[]}),Xa=z$1.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."),Ua="The COMPLETE config this view should end up with \u2014 not a patch. Copy the baseline returned by get_default_view and edit it, preserving every tab and setting you are not changing: anything you omit is dropped. To change the columns shown, set `tabs[].columns` (an array of attribute names) \u2014 there is no top-level `columns` on either view type. For a detail view's side panel, set `sidePanel.attributes`. Every attribute name listed must already exist on the object, or be created earlier in this same plan. ONE EXCEPTION to omit-is-dropped: a tab with `type: \"custom\"` renders a component belonging to the application, which you cannot describe or recreate. Copy every such tab through from the baseline exactly as it came, `name`, `component` and `props` untouched \u2014 dropping one, inventing one, or altering any of those three is rejected rather than applied (`name` is the tab's address in links, not its wording). Its `label` and `icon` you may change.",qa="Opaque token returned by get_default_view alongside the baseline you edited. REQUIRED when the object already exists \u2014 it proves you authored against the baseline that is still current. Must be OMITTED when this plan creates the object, which has no baseline yet.",za=z$1.string().min(1).describe("Name of the object whose default view of this type is replaced. Not a view name \u2014 a plan can only replace an object's deterministic default view, never create a view or target a non-default one."),sp=z$1.discriminatedUnion("viewType",[z$1.object({objectName:za,viewType:z$1.literal("list").describe("Targets the object's default list view (the grid)."),canonicalConfig:ma$1.describe(Ua),baselineToken:z$1.string().min(1).optional().describe(qa)}).strict(),z$1.object({objectName:za,viewType:z$1.literal("detail").describe("Targets the object's default detail view (the single-record view)."),canonicalConfig:na$1.describe(Ua),baselineToken:z$1.string().min(1).optional().describe(qa)}).strict()]);var Ga=z$1.string().regex(/^[0-9a-f]{64}$/,"Expected a lowercase SHA-256 hash"),Wa={baseConfigHash:Ga.nullable(),targetConfigHash:Ga,baselineOrigin:z$1.enum(["persisted","generated","absent"])},up=z$1.discriminatedUnion("viewType",[z$1.object({objectName:z$1.string().min(1),viewType:z$1.literal("list"),canonicalConfig:ma$1,...Wa}).strict(),z$1.object({objectName:z$1.string().min(1),viewType:z$1.literal("detail"),canonicalConfig:na$1,...Wa}).strict()]).superRefine((e,t)=>{let r=e.baselineOrigin!=="absent";r!==(e.baseConfigHash!==null)&&t.addIssue({code:"custom",path:["baseConfigHash"],message:r?`A ${e.baselineOrigin} baseline requires baseConfigHash`:"An absent baseline requires baseConfigHash to be null"});});function Za(e){return z$1.object({objects:z$1.array(ap).default([]).describe("New objects to create, with their attributes inline."),attributes:z$1.array(ip).default([]).describe("Attributes to add to existing or same-plan objects."),viewUpdates:z$1.array(e).default([]).describe("Complete target configs for deterministic default views; never view names.")}).strict().default({objects:[],attributes:[],viewUpdates:[]})}a(Za,"buildAdditiveSchema");function xi(e,t=[],r=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(r.has(e))return {path:t,message:"Plan input cannot contain circular references"};if(Array.isArray(e)){r.add(e);for(let s of Reflect.ownKeys(e))if(s!=="length"&&(typeof s=="symbol"||!/^(0|[1-9]\d*)$/.test(s)))return r.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 r.delete(e),{path:[...t,s],message:"Plan input cannot contain sparse arrays"};let l=xi(e[s],[...t,s],r);if(l)return r.delete(e),l}return r.delete(e),null}let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return {path:t,message:"Plan input must contain only plain JSON objects"};r.add(e);let o=e,a=Reflect.ownKeys(o);for(let s of a){let l=Object.getOwnPropertyDescriptor(o,s);if(typeof s=="symbol"||!(l?.enumerable&&"value"in l))return r.delete(e),{path:[...t,s],message:"Plan input objects must contain enumerable JSON data properties only"}}for(let s of a.sort()){let l=xi(o[s],[...t,s],r);if(l)return r.delete(e),l}return r.delete(e),null}a(xi,"findJsonSafetyIssue");function lp(e){let t=[];return e.additive.objects.forEach((r,n)=>{t.push(["additive","objects",n]),r.attributes.forEach((o,a)=>{t.push(["additive","objects",n,"attributes",a]);});}),e.additive.attributes.forEach((r,n)=>{t.push(["additive","attributes",n]);}),e.additive.viewUpdates.forEach((r,n)=>{t.push(["additive","viewUpdates",n]);}),e.destructive.attributeRemovals.forEach((r,n)=>{t.push(["destructive","attributeRemovals",n]);}),e.destructive.objectRemovals.forEach((r,n)=>{t.push(["destructive","objectRemovals",n]);}),e.destructive.renames.forEach((r,n)=>{t.push(["destructive","renames",n]);}),t}a(lp,"mutationPaths");function es(e,t){e.additive.objects.length>q.objectAdditions&&t.addIssue({code:"too_big",origin:"array",maximum:q.objectAdditions,inclusive:true,path:["additive","objects",q.objectAdditions],message:`A schema plan can add at most ${q.objectAdditions} objects`});let r=lp(e);r.length>q.totalMutations&&t.addIssue({code:"too_big",origin:"array",maximum:q.totalMutations,inclusive:true,path:r[q.totalMutations],message:`A schema plan can contain at most ${q.totalMutations} mutations; received ${r.length}`});}a(es,"addPlanLimitIssues");function ts(e,t){let r=xi(e);if(r)return t.addIssue({code:"custom",path:r.path,message:r.message}),z$1.NEVER;let n=new TextEncoder().encode(b$3(e)).byteLength;return n>q.serializedBytes?(t.addIssue({code:"too_big",origin:"string",maximum:q.serializedBytes,inclusive:true,path:[],message:`A schema plan can serialize to at most ${q.serializedBytes} UTF-8 bytes; received ${n}`}),z$1.NEVER):e}a(ts,"boundSerializedPlanInput");var dp=Za(sp),cp=Za(up),Ka=z$1.object({schemaPlanVersion:z$1.literal(2).describe("Required proposal contract version."),summary:Xa,additive:dp,destructive:Ja}).strict().superRefine((e,t)=>{let r=new Set(e.additive.objects.map(n=>n.name));e.additive.viewUpdates.forEach((n,o)=>{let a=["additive","viewUpdates",o,"baselineToken"];if(r.has(n.objectName)){n.baselineToken!==void 0&&t.addIssue({code:"custom",path:a,message:"A view target for an object added by this plan must not include baselineToken"});return}n.baselineToken===void 0&&t.addIssue({code:"custom",path:a,message:"A view target for an existing object requires baselineToken"});}),es(e,t);}),DS=Object.assign(z$1.preprocess(ts,Ka),{shape:Ka.shape}),pp=z$1.object({schemaPlanVersion:z$1.literal(2),summary:Xa,additive:cp,destructive:Ja}).strict().superRefine(es),ES=z$1.preprocess(ts,pp);var T=z$1.number().finite().nonnegative(),ns=z$1.enum(To),Si=z$1.enum(wo),vi=z$1.enum(xo),is=z$1.object({provider:ns,model:z$1.string().min(1)}).strict(),PS=z$1.object({speed:Si.optional(),reasoning:vi.optional()}).strict(),os=z$1.string().regex(/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9._-]*$/),mp=z$1.object({model:is.optional(),speed:Si.optional(),reasoning:vi.optional(),imageModel:os.optional()}).strict(),jS=mp.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"}),FS=z$1.object({model:is.nullable().optional(),speed:Si.nullable().optional(),reasoning:vi.nullable().optional(),imageModel:os.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$1.object({label:z$1.string(),denied:z$1.boolean().optional(),deletion:z$1.object({target:z$1.string().optional(),count:T.optional(),restorableDays:T.optional()}).strict().optional(),counts:z$1.record(z$1.string(),T).optional(),warnings:z$1.array(z$1.string()).optional()}).strict(),fp=z$1.union([z$1.object({type:z$1.literal("text"),text:z$1.string()}).strict(),z$1.object({type:z$1.literal("reasoning"),text:z$1.string()}).strict(),z$1.object({type:z$1.literal("system"),code:z$1.enum(mr)}).strict(),z$1.object({type:z$1.literal("error"),error:z$1.string(),errorClass:z$1.string().optional()}).strict(),z$1.object({type:z$1.literal("tool"),toolCallId:z$1.string(),name:z$1.string(),args:z$1.record(z$1.string(),z$1.unknown()),result:z$1.unknown().optional(),error:z$1.string().optional(),errorCode:z$1.enum(["output_limit_reached","interrupted"]).optional(),state:z$1.enum(["streaming","running","completed","error","pending","approval-requested","approval-responded","approval-dispatched"]),durationMs:T.optional(),approvalId:z$1.string().optional(),approvalImpact:as.optional(),approved:z$1.boolean().optional(),approvalReason:z$1.string().optional(),approvalRelaxableByAuto:z$1.boolean().optional()}).strict(),z$1.object({type:z$1.literal("file"),fileId:z$1.string(),name:z$1.string(),mimeType:z$1.string()}).strict(),z$1.object({type:z$1.literal("compaction"),state:z$1.literal("in-progress"),reason:z$1.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:T.optional(),reportedTokens:T.optional()}).strict(),z$1.object({type:z$1.literal("compaction"),state:z$1.literal("completed"),tokensBefore:T,tokensAfter:T,tokensSaved:T,strategy:z$1.enum(["no-op","summary","truncation"]),durationMs:T,summary:z$1.string().optional()}).strict(),z$1.object({type:z$1.literal("compaction"),state:z$1.literal("failed"),reason:z$1.string(),durationMs:T.optional()}).strict()]),bp=z$1.object({id:z$1.string(),name:z$1.string(),mimeType:z$1.string(),size:T}).strict(),gp=z$1.object({id:z$1.string(),type:z$1.string().transform(e=>e),entityId:z$1.string(),label:z$1.string(),objectName:z$1.string().optional(),startIndex:T,endIndex:T}).strict(),yp=z$1.object({provider:ns,model:z$1.string(),maxTokens:T.optional(),contextWindow:T.optional()}).strict(),hp=z$1.union([z$1.date(),z$1.string().datetime({offset:true}).transform(e=>new Date(e))]),rs=z$1.object({id:z$1.string(),sessionId:z$1.string(),tenantId:z$1.string().optional(),runId:z$1.string().optional(),role:z$1.enum(["user","assistant","system","tool"]),parts:z$1.array(fp),attachments:z$1.array(bp).optional(),mentions:z$1.array(gp).optional(),model:yp.optional(),tokenUsage:z$1.object({input:T,output:T}).strict().optional(),metadata:z$1.record(z$1.string(),z$1.unknown()).optional(),createdAt:hp}).strict(),Ap=z$1.object({id:z$1.string(),description:z$1.string(),status:z$1.enum(["pending","in_progress","completed","blocked"]),result:z$1.string().optional(),updatedAt:T.optional()}).strict(),Tp=z$1.object({id:z$1.string(),sessionId:z$1.string(),status:z$1.enum(["active","completed","abandoned"]),todos:z$1.array(Ap),version:T,createdAt:z$1.string(),updatedAt:z$1.string(),completedAt:z$1.string().optional()}).strict(),ss={"session-named":z$1.object({name:z$1.string()}).strict(),"compaction-start":z$1.object({reason:z$1.enum(["preflight_threshold","overflow_recovery"]),estimatedTokens:T.optional(),reportedTokens:T.optional()}).strict(),"compaction-end":z$1.object({tokensBefore:T,tokensAfter:T,tokensSaved:T,strategy:z$1.enum(["no-op","summary","truncation"]),durationMs:T,summary:z$1.string().optional()}).strict(),"compaction-failed":z$1.object({reason:z$1.string()}).strict(),usage:z$1.object({messageId:z$1.string().min(1).optional(),inputTokens:T,outputTokens:T,totalTokens:T,cacheReadTokens:T.optional(),cacheCreationTokens:T.optional(),contextWindow:T,residentTokens:T,utilization:z$1.number().finite().min(0).max(1),costUsd:T.optional()}).strict(),"message-persisted":z$1.object({message:rs}).strict(),"message-updated":z$1.object({message:rs}).strict(),"todo-plan-update":z$1.object({plan:Tp}).strict(),"approval-context":z$1.object({approvalId:z$1.string(),toolCallId:z$1.string(),impact:as.optional(),relaxableByAuto:z$1.boolean().optional()}).strict(),"session-state":z$1.object({state:z$1.object({phase:z$1.enum(["queued","running","parked","terminal"]),parkedOn:z$1.enum(["human","agents"]).optional(),humanRequestIds:z$1.array(z$1.string()).optional(),outcome:z$1.enum(["completed","failed","cancelled","timeout","expired"]).optional()}).strict(),version:z$1.number().int().positive(),updatedAt:z$1.string().datetime({offset:true})}).strict()};function wp(e){return e in ss}a(wp,"isAgentUIDataName");function xp(e){return new h("Invalid agent UI message chunk",e.map(t=>({path:t.path.map(String),message:t.message,code:t.code})))}a(xp,"agentUIValidationError");function Ip(e){if(typeof e!="object"||e===null||typeof e.type!="string")throw new h("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("Invalid agent UI message chunk",[{path:["type"],message:"Expected agent data chunk type",code:"invalid_value"}]);let r=t.slice(5);if(!wp(r))throw new h("Invalid agent UI message chunk",[{path:["type"],message:`Unknown agent UI data type: ${r}`,code:"invalid_value"}]);let n=z$1.object({type:z$1.literal(`data-${r}`),id:z$1.string().optional(),data:ss[r],transient:z$1.boolean().optional()}).strict().safeParse(e);if(!n.success)throw xp(n.error.issues);return n.data}a(Ip,"assertCustomAgentUIMessageChunk");function VS(e,t,r){return Ip({type:`data-${e}`,...r?.id!==void 0?{id:r.id}:{},data:t,...r?.transient!==void 0?{transient:r.transient}:{}})}a(VS,"agentDataChunk");function Yt(e){return e}a(Yt,"defineOperation");function A(e,t,r){let n=t==="atomic"?"none":t==="local"?"if-not-visible":"follow";return o=>{let a=r?.(o);return {impact:t,navigation:n,focus:{...e(o),...a===void 0?{}:{propertyPath:a}}}}}a(A,"definePresentation");var Ri={id:z$1.string().min(1)},D={...Ri,viewId:z$1.string().min(1)},Sp={add_tab:"add_list_tab",add_list_tab:"add_tab"};function ae(e,t,r,n,o){let a=e.views.find(s=>s.id===t);if(!a)throw new h(`View "${t}" is not in the draftable state`,[]);if(a.type!==r){let s=Sp[o]??`a ${a.type}-view operation`;throw new h(`${o} targets ${a.type} view "${t}"; use ${s}`,[])}return {...e,views:e.views.map(s=>{if(s.id!==t)return s;let{derived:l,...c}=n(s);return c})}}a(ae,"mapView");function ls(e,t,r){let n=[...e],[o]=n.splice(t,1);return n.splice(r,0,o),n}a(ls,"moveWithin");function Qe(e,t,r){if(t.length!==e.length)throw new h(`${r} order lists ${t.length} ids for ${e.length} items`,[]);return t.map(n=>{let o=e.find(a=>a.id===n);if(!o)throw new h(`${r} "${n}" is not in this collection`,[]);return o})}a(Qe,"reorderById");function F(e,t,r,n){return ae(e,t,"detail",r,n)}a(F,"mapDetailView");function se(e,t,r){let n=e.tabs.find(o=>o.id===t);if(!n)throw new h(`Tab "${t}" is not in view "${e.id}"`,[]);if(n.type!=="form")throw new h(`Tab "${t}" is not a form tab`,[]);return {...e,tabs:e.tabs.map(o=>o.id===t?r(n):o)}}a(se,"mapFormTab");function Xt(e,t){let r=e.groups.find(n=>n.id===t);if(!r)throw new h(`Group "${t}" is not in tab "${e.id}"`,[]);return r}a(Xt,"requireGroup");function Di(e,t){for(let r of e.groups){let n=r.fields.find(o=>o.id===t);if(n)return {group:r,field:n}}throw new h(`Field slot "${t}" is not in tab "${e.id}"`,[])}a(Di,"locateField");function Qt(e){return {viewId:e.viewId}}a(Qt,"viewFocus");function Jt(e){return {viewId:e.viewId,tabId:e.tabId}}a(Jt,"tabFocus");function ds(e){return {viewId:e.viewId,tabId:e.tabId,groupId:e.groupId}}a(ds,"groupFocus");function cs(e){return {viewId:e.viewId,tabId:e.tabId,fieldId:e.fieldId}}a(cs,"fieldFocus");function ps(e){return {viewId:e.viewId,tabId:e.tab.id}}a(ps,"addTabFocus");function ms(e){return {viewId:e.viewId,tabId:e.tabId,groupId:e.group.id}}a(ms,"addGroupFocus");function fs(e){return {viewId:e.viewId,tabId:e.tabId,groupId:e.groupId,fieldId:e.field.id}}a(fs,"addFieldFocus");function bs(e){return {viewId:e.viewId,tabId:e.tabId,groupId:e.toGroupId,fieldId:e.fieldId}}a(bs,"moveFieldFocus");function Je(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}a(Je,"firstChangedProperty");var vp=ka$1,Rp=fa$1,Dp=ea$1,Ep=z$1.object({...D,type:z$1.literal("add_tab"),tab:vp}),Cp={type:"add_tab",schema:Ep,apply:a((e,t)=>F(e,t.viewId,r=>{if(r.tabs.some(n=>n.id===t.tab.id))throw new h(`Tab "${t.tab.id}" already exists in view "${t.viewId}"`,[]);return {...r,tabs:[...r.tabs,t.tab]}},"add_tab"),"apply"),focus:ps,presentation:A(ps,"local"),describe:a(e=>`Ajoute l'onglet \xAB ${e.tab.label} \xBB`,"describe")},Op=z$1.object({...D,type:z$1.literal("remove_tab"),tabId:z$1.string().min(1)}),_p={type:"remove_tab",schema:Op,apply:a((e,t)=>F(e,t.viewId,r=>{if(!r.tabs.some(n=>n.id===t.tabId))throw new h(`Tab "${t.tabId}" is not in view "${t.viewId}"`,[]);return {...r,tabs:r.tabs.filter(n=>n.id!==t.tabId)}},"remove_tab"),"apply"),focus:Jt,presentation:A(Jt,"local"),describe:a(e=>`Supprime l'onglet ${e.tabId}`,"describe")},ws=z$1.object({label:z$1.string().min(1).optional(),icon:c.optional(),order:z$1.number().int().optional()}),Np=Object.keys(ws.shape),kp=z$1.object({...D,type:z$1.literal("update_tab"),tabId:z$1.string().min(1),changes:ws.refine(e=>Object.keys(e).length>0,"update_tab needs at least one change")}),gs=a(e=>({viewId:e.viewId,tabId:e.tabId}),"updateTabFocus"),Pp={type:"update_tab",schema:kp,apply:a((e,t)=>F(e,t.viewId,r=>{if(!r.tabs.some(n=>n.id===t.tabId))throw new h(`Tab "${t.tabId}" is not in view "${t.viewId}"`,[]);return {...r,tabs:r.tabs.map(n=>n.id===t.tabId?{...n,...t.changes}:n)}},"update_tab"),"apply"),focus:gs,presentation:A(gs,"atomic",Je),describe:a(e=>e.changes.label?`Renomme l'onglet en \xAB ${e.changes.label} \xBB`:`Modifie l'onglet ${e.tabId}`,"describe")},jp=z$1.object({...D,type:z$1.literal("reorder_tabs"),tabOrder:z$1.array(z$1.string().min(1))}),Fp={type:"reorder_tabs",schema:jp,apply:a((e,t)=>F(e,t.viewId,r=>({...r,tabs:Qe(r.tabs,t.tabOrder,"Tab")}),"reorder_tabs"),"apply"),focus:Qt,presentation:A(Qt,"local"),describe:a(()=>"R\xE9ordonne les onglets","describe")},Vp=z$1.object({...D,type:z$1.literal("add_group"),tabId:z$1.string().min(1),group:Rp}),Mp={type:"add_group",schema:Vp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>{if(n.groups.some(o=>o.id===t.group.id))throw new h(`Group "${t.group.id}" already exists in tab "${t.tabId}"`,[]);return {...n,groups:[...n.groups,t.group]}}),"add_group"),"apply"),focus:ms,presentation:A(ms,"local"),describe:a(e=>`Ajoute le groupe \xAB ${e.group.label} \xBB`,"describe")},Lp=z$1.object({...D,type:z$1.literal("remove_group"),tabId:z$1.string().min(1),groupId:z$1.string().min(1)}),Bp={type:"remove_group",schema:Lp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>(Xt(n,t.groupId),{...n,groups:n.groups.filter(o=>o.id!==t.groupId)})),"remove_group"),"apply"),focus:ds,presentation:A(ds,"local"),describe:a(e=>`Supprime le groupe ${e.groupId}`,"describe")},$p=z$1.object({...D,type:z$1.literal("update_group"),tabId:z$1.string().min(1),groupId:z$1.string().min(1),changes:z$1.object({label:z$1.string().min(1).optional(),description:z$1.string().optional(),collapsible:z$1.boolean().optional(),collapsed:z$1.boolean().optional(),order:z$1.number().int().optional()}).refine(e=>Object.keys(e).length>0,"update_group needs at least one change")}),ys=a(e=>({viewId:e.viewId,tabId:e.tabId,groupId:e.groupId}),"updateGroupFocus"),Up={type:"update_group",schema:$p,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>(Xt(n,t.groupId),{...n,groups:n.groups.map(o=>o.id===t.groupId?{...o,...t.changes}:o)})),"update_group"),"apply"),focus:ys,presentation:A(ys,"atomic",Je),describe:a(e=>e.changes.label?`Renomme le groupe en \xAB ${e.changes.label} \xBB`:"Modifie le groupe","describe")},qp=z$1.object({...D,type:z$1.literal("reorder_groups"),tabId:z$1.string().min(1),groupOrder:z$1.array(z$1.string().min(1))}),zp={type:"reorder_groups",schema:qp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>({...n,groups:Qe(n.groups,t.groupOrder,"Group")})),"reorder_groups"),"apply"),focus:Jt,presentation:A(Jt,"local"),describe:a(()=>"R\xE9ordonne les groupes","describe")},Gp=z$1.object({...D,type:z$1.literal("add_field"),tabId:z$1.string().min(1),groupId:z$1.string().min(1),field:Dp,index:z$1.number().int().min(0).optional()}),Wp={type:"add_field",schema:Gp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>{if(Xt(n,t.groupId),n.groups.some(o=>o.fields.some(a=>a.id===t.field.id)))throw new h(`Field slot "${t.field.id}" already exists in tab "${t.tabId}"`,[]);return {...n,groups:n.groups.map(o=>{if(o.id!==t.groupId)return o;let a=t.index??o.fields.length;return {...o,fields:[...o.fields.slice(0,a),t.field,...o.fields.slice(a)]}})}}),"add_field"),"apply"),focus:fs,presentation:A(fs,"local"),describe:a(e=>`Ajoute le champ ${e.field.attribute??e.field.attributeGroup?.label??e.field.id}`,"describe")},Kp=z$1.object({...D,type:z$1.literal("remove_field"),tabId:z$1.string().min(1),fieldId:z$1.string().min(1)}),Hp={type:"remove_field",schema:Kp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>{let{group:o}=Di(n,t.fieldId);return {...n,groups:n.groups.map(a=>a.id===o.id?{...a,fields:a.fields.filter(s=>s.id!==t.fieldId)}:a)}}),"remove_field"),"apply"),focus:cs,presentation:A(cs,"local"),describe:a(e=>`Retire le champ ${e.fieldId}`,"describe")},Yp=z$1.object({...D,type:z$1.literal("move_field"),tabId:z$1.string().min(1),fieldId:z$1.string().min(1),toGroupId:z$1.string().min(1),toIndex:z$1.number().int().min(0)}),Qp={type:"move_field",schema:Yp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>{let{group:o,field:a}=Di(n,t.fieldId),s=Xt(n,t.toGroupId);if(o.id===s.id){let l=o.fields.findIndex(c=>c.id===t.fieldId);return {...n,groups:n.groups.map(c=>c.id===o.id?{...c,fields:ls(c.fields,l,t.toIndex)}:c)}}return {...n,groups:n.groups.map(l=>l.id===o.id?{...l,fields:l.fields.filter(c=>c.id!==t.fieldId)}:l.id===s.id?{...l,fields:[...l.fields.slice(0,t.toIndex),a,...l.fields.slice(t.toIndex)]}:l)}}),"move_field"),"apply"),focus:bs,presentation:A(bs,"local"),describe:a(e=>`D\xE9place le champ ${e.fieldId} vers le groupe ${e.toGroupId}`,"describe")},Jp=z$1.object({...D,type:z$1.literal("update_field"),tabId:z$1.string().min(1),fieldId:z$1.string().min(1),changes:z$1.object({label:z$1.string().optional(),readOnly:z$1.boolean().optional(),span:z$1.number().int().min(1).max(12).optional()}).refine(e=>Object.keys(e).length>0,"update_field needs at least one change")}),hs=a(e=>({viewId:e.viewId,tabId:e.tabId,fieldId:e.fieldId}),"updateFieldFocus"),Xp={type:"update_field",schema:Jp,apply:a((e,t)=>F(e,t.viewId,r=>se(r,t.tabId,n=>(Di(n,t.fieldId),{...n,groups:n.groups.map(o=>({...o,fields:o.fields.map(a=>a.id===t.fieldId?{...a,...t.changes}:a)}))})),"update_field"),"apply"),focus:hs,presentation:A(hs,"atomic",Je),describe:a(e=>`Modifie le champ ${e.fieldId}`,"describe")},xs=z$1.object({source:ia$1.optional(),columns:Z.optional(),filters:aa$1.nullable().optional(),sorts:$$1.nullable().optional(),allowCreate:z$1.boolean().optional(),allowEdit:z$1.boolean().optional(),allowDelete:z$1.boolean().optional(),createMode:z$1.enum(["redirect","inline","peek"]).optional()}),Zp=Object.keys(xs.shape),Is=z$1.object({emailAttributeIds:z$1.array(z$1.string().min(1)).optional(),attribute:z$1.string().min(1).optional(),titleAttribute:z$1.string().min(1).nullable().optional(),component:z$1.string().nullable().optional(),props:z$1.record(z$1.string(),z$1.unknown()).nullable().optional()}),em=Object.keys(Is.shape),tm={emailAttributeIds:["emails","meetings"],attribute:["richtext"],titleAttribute:["richtext"],component:["custom"],props:["custom"]},rm=z$1.object({...D,type:z$1.literal("update_tab_config"),tabId:z$1.string().min(1),changes:Is.refine(e=>Object.keys(e).length>0,"update_tab_config needs at least one change")}),As=a(e=>({viewId:e.viewId,tabId:e.tabId}),"updateTabConfigFocus"),nm={type:"update_tab_config",schema:rm,apply:a((e,t)=>F(e,t.viewId,r=>{let n=r.tabs.find(o=>o.id===t.tabId);if(!n)throw new h(`Tab "${t.tabId}" is not in view "${r.id}"`,[]);for(let o of Object.keys(t.changes)){let a=tm[o];if(a&&!a.includes(n.type))throw new h(`"${o}" is not a setting of a "${n.type}" tab`,[])}return {...r,tabs:r.tabs.map(o=>o.id===t.tabId?{...o,...t.changes}:o)}},"update_tab_config"),"apply"),focus:As,presentation:A(As,"atomic",Je),describe:a(e=>`Configure ${Object.keys(e.changes).join(", ")} sur l'onglet ${e.tabId}`,"describe")},im=z$1.object({...D,type:z$1.literal("update_table_tab"),tabId:z$1.string().min(1),changes:xs.refine(e=>Object.keys(e).length>0,"update_table_tab needs at least one change")}),Ts=a(e=>({viewId:e.viewId,tabId:e.tabId}),"updateTableTabFocus"),om={type:"update_table_tab",schema:im,apply:a((e,t)=>F(e,t.viewId,r=>{let n=r.tabs.find(l=>l.id===t.tabId);if(!n)throw new h(`Tab "${t.tabId}" is not in view "${r.id}"`,[]);if(n.type!=="table")throw new h(`Tab "${t.tabId}" is not a table tab`,[]);let o=Object.entries(t.changes),a=Object.fromEntries(o.filter(([,l])=>l!==null)),s=new Set(o.filter(([,l])=>l===null).map(([l])=>l));return {...r,tabs:r.tabs.map(l=>l.id===t.tabId?Object.fromEntries(Object.entries({...l,...a}).filter(([c])=>!s.has(c))):l)}},"update_table_tab"),"apply"),focus:Ts,presentation:A(Ts,"atomic",Je),describe:a(e=>e.changes.columns?`Affiche ${e.changes.columns.length} colonne(s) dans l'onglet ${e.tabId}`:`Modifie l'onglet ${e.tabId}`,"describe")},am=z$1.object({...D,type:z$1.literal("set_side_panel"),sidePanel:z$1.object({attributes:z$1.array(z$1.string().min(1)),width:z$1.number().int().min(1).optional()}).nullable()}),sm={type:"set_side_panel",schema:am,apply:a((e,t)=>F(e,t.viewId,r=>({...r,config:{...r.config,sidePanel:t.sidePanel??void 0}}),"set_side_panel"),"apply"),focus:Qt,presentation:A(Qt,"atomic",()=>["config","sidePanel"]),describe:a(e=>e.sidePanel?"Active le panneau lat\xE9ral":"Retire le panneau lat\xE9ral","describe")},Ee=[Cp,_p,Pp,Fp,Mp,Bp,Up,zp,Wp,Hp,Qp,Xp,om,nm,sm];var Xe={...D,tabId:z$1.string().min(1)};function Zt(e){return {viewId:e.viewId}}a(Zt,"viewFocus");function ue(e){return {viewId:e.viewId,tabId:e.tabId}}a(ue,"tabFocus");function Ss(e){return {viewId:e.viewId,tabId:e.tab.id}}a(Ss,"addTabFocus");function um(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}a(um,"firstChangedProperty");function Rs(e){let t={...e};for(let r of sa$1)delete t[r];return t}a(Rs,"withoutKanbanKeys");function Ds(e){let t={...e};for(let r of ra$1)delete t[r];return t}a(Ds,"withoutTableKeys");function lm(e,t,r,n){let o=la$1.safeParse(t);if(!o.success){if(!la$1.safeParse(e).success)return t;let a=o.error.issues.map(s=>s.path.length?`${s.path.join(".")}: ${s.message}`:s.message).join(", ");throw new h(`List tab "${n}" in view "${r}" would no longer be publishable: ${a}`,[])}return t}a(lm,"assertStillPublishableTab");function er(e,t,r,n,o){return ae(e,t,"list",a=>{let s=a.config.tabs??[];if(!s.some(l=>l.id===r))throw new h(`List tab "${r}" is not in view "${t}"`,[]);return {...a,config:{...a.config,tabs:s.map(l=>l.id===r?lm(l,n(l),t,r):l)}}},o)}a(er,"mapListTab");var dm=la$1,Es=ba$1,cm=$$1;function z(e,t,r,n){let o=z$1.object({...Xe,type:z$1.literal(e),value:r});return {type:e,schema:o,apply:a((a,s)=>er(a,s.viewId,s.tabId,l=>{if(s.value===null){let{[t]:c,...f}=l;return f}return {...l,[t]:s.value}},e),"apply"),focus:ue,presentation:A(ue,"atomic",()=>[String(t)]),describe:a(a=>n(a.value),"describe")}}a(z,"setOnTab");var pm=z$1.object({...D,type:z$1.literal("add_list_tab"),tab:dm}),mm={type:"add_list_tab",schema:pm,apply:a((e,t)=>ae(e,t.viewId,"list",r=>{let n=r.config.tabs??[];if(n.some(o=>o.id===t.tab.id))throw new h(`List tab "${t.tab.id}" already exists in view "${t.viewId}"`,[]);return {...r,config:{...r.config,tabs:[...n,t.tab]}}},"add_list_tab"),"apply"),focus:Ss,presentation:A(Ss,"local"),describe:a(e=>`Ajoute l'onglet \xAB ${e.tab.label} \xBB`,"describe")},fm=z$1.object({...Xe,type:z$1.literal("remove_list_tab")}),bm={type:"remove_list_tab",schema:fm,apply:a((e,t)=>ae(e,t.viewId,"list",r=>{let n=r.config.tabs??[];if(!n.some(o=>o.id===t.tabId))throw new h(`List tab "${t.tabId}" is not in view "${t.viewId}"`,[]);return {...r,config:{...r.config,tabs:n.filter(o=>o.id!==t.tabId)}}},"remove_list_tab"),"apply"),focus:ue,presentation:A(ue,"local"),describe:a(e=>`Supprime l'onglet ${e.tabId}`,"describe")},gm=z$1.object({...Xe,type:z$1.literal("update_list_tab"),changes:z$1.object({label:z$1.string().min(1).optional(),icon:c.optional(),default:z$1.boolean().optional(),visibility:z$1.enum(y).optional()}).refine(e=>Object.keys(e).length>0,"update_list_tab needs at least one change")}),vs=a(e=>({viewId:e.viewId,tabId:e.tabId}),"updateListTabFocus"),ym={type:"update_list_tab",schema:gm,apply:a((e,t)=>er(e,t.viewId,t.tabId,r=>({...r,...t.changes}),"update_list_tab"),"apply"),focus:vs,presentation:A(vs,"atomic",um),describe:a(e=>e.changes.label?`Renomme l'onglet en \xAB ${e.changes.label} \xBB`:`Modifie l'onglet ${e.tabId}`,"describe")},hm=z$1.object({...D,type:z$1.literal("reorder_list_tabs"),tabOrder:z$1.array(z$1.string().min(1))}),Am={type:"reorder_list_tabs",schema:hm,apply:a((e,t)=>ae(e,t.viewId,"list",r=>({...r,config:{...r.config,tabs:Qe(r.config.tabs??[],t.tabOrder,"List tab")}}),"reorder_list_tabs"),"apply"),focus:Zt,presentation:A(Zt,"local"),describe:a(()=>"R\xE9ordonne les onglets","describe")},Tm=z("set_columns","columns",z$1.array(z$1.string().min(1)),e=>`Affiche ${Array.isArray(e)?e.length:0} colonne(s)`),wm=z("set_column_sizing","columnSizing",z$1.record(z$1.string(),z$1.number().int().positive()),()=>"Ajuste la largeur des colonnes"),xm=z$1.object({...Xe,type:z$1.literal("set_layout"),value:z$1.enum(["table","list","kanban"])}),Im={type:"set_layout",schema:xm,apply:a((e,t)=>er(e,t.viewId,t.tabId,r=>{if(t.value!=="kanban")return {...Rs(r),layout:t.value};if(r.groupByAttribute===void 0)throw new h(`List tab "${t.tabId}" cannot switch to kanban without a group attribute \u2014 use set_group_by, which switches the layout itself`,[]);return {...Ds(r),layout:"kanban"}},"set_layout"),"apply"),focus:ue,presentation:A(ue,"atomic",()=>["layout"]),describe:a(e=>`Passe en affichage ${e.value}`,"describe")},Sm=z$1.object({...Xe,type:z$1.literal("set_group_by"),value:z$1.string().min(1).nullable()}),vm={type:"set_group_by",schema:Sm,apply:a((e,t)=>er(e,t.viewId,t.tabId,r=>t.value===null?{...Rs(r),layout:"table"}:{...Ds(r),layout:"kanban",groupByAttribute:t.value},"set_group_by"),"apply"),focus:ue,presentation:A(ue,"atomic",()=>["groupByAttribute"]),describe:a(e=>e.value?`Regroupe par ${e.value} en kanban`:"Retire le regroupement, retour en table","describe")},Rm=z("set_filters","filters",Es.nullable(),e=>e?"Modifie les filtres":"Retire les filtres"),Dm=z("set_sorts","sorts",cm.nullable(),e=>e?"Modifie le tri":"Retire le tri"),Em=z("set_create_mode","createMode",z$1.enum(["redirect","inline","peek"]),e=>`Cr\xE9ation en mode ${e}`),Cm=z("set_open_mode","openMode",z$1.enum(["side","page"]),e=>e==="side"?"Ouvre les fiches en c\xF4t\xE9":"Ouvre les fiches en pleine page"),Om=z("set_read_only","readOnly",z$1.boolean(),e=>e?"Passe l'onglet en lecture seule":"Rend l'onglet modifiable"),_m=z("set_card_user_attribute","cardUserAttribute",z$1.string().min(1).nullable(),e=>e?`Affiche ${e} sur les cartes`:"Retire l'utilisateur des cartes"),Nm=z("set_card_date_attribute","cardDateAttribute",z$1.string().min(1).nullable(),e=>e?`Affiche ${e} sur les cartes`:"Retire la date des cartes"),km=z("set_description_attribute","descriptionAttribute",z$1.string().min(1).nullable(),e=>e?`Affiche ${e} en description`:"Retire la description"),Pm=z("set_display_attributes","displayAttributes",_$1.nullable(),e=>`Affiche ${Array.isArray(e)?e.length:0} attribut(s)`),jm=z$1.object({...D,type:z$1.literal("set_default_filters"),filters:Es.nullable()}),Fm={type:"set_default_filters",schema:jm,apply:a((e,t)=>ae(e,t.viewId,"list",r=>{if(t.filters===null){let{defaultFilters:n,...o}=r.config;return {...r,config:o}}return {...r,config:{...r.config,defaultFilters:t.filters}}},"set_default_filters"),"apply"),focus:Zt,presentation:A(Zt,"atomic",()=>["config","defaultFilters"]),describe:a(e=>e.filters?"Modifie les filtres de la vue":"Retire les filtres de la vue","describe")},Ce=[Fm,mm,bm,ym,Am,Tm,wm,Im,vm,Rm,Dm,Em,Cm,Om,_m,Nm,km,Pm];var Vm=new Set(["formula","rollup"]);function Oe(e){return Vm.has(e.attributeType)}a(Oe,"isComputedAttribute");var Cs={sum:"number",avg:"number",count:"number",countValues:"number",countUniqueValues:"number",countEmpty:"number",percentEmpty:"number",percentNotEmpty:"number",earliest:"date",latest:"date",original:"multiselect"};function Mm(e){return typeof e=="string"&&e in Cs?Cs[e]:void 0}a(Mm,"rollupReturnTypeOf");function _s(e,t){let r=e.objects.find(n=>n.id===t);if(!r)throw new h(`Object "${t}" is not in the draftable state`,[]);return r}a(_s,"requireObject");function tr(e){return e.config??{}}a(tr,"configOf");function G(e){let t=tr(e).targets;return Array.isArray(t)?t.filter(r=>typeof r=="object"&&r!==null&&typeof r.object=="string"):[]}a(G,"relationTargets");function _e(e){let t=G(e).filter(r=>r.object!==ee);return t.length===1?t[0]?.object:void 0}a(_e,"relationTargetObjectName");function Lm(e){let t=tr(e),r=e.attributeType,n={name:e.name,type:r,id:e.id},o=t.optionsSource;if(r==="relation"){let a=_e(e);return {...n,...t.cardinality==="one"||t.cardinality==="many"?{cardinality:t.cardinality}:{},...a===void 0?{}:{targetObjectName:a},targets:G(e)}}if(r==="formula")return {...n,...t.returnType===void 0?{}:{returnType:t.returnType},...o===void 0?{}:{optionsSource:o}};if(r==="rollup"){let a=Mm(t.function);return {...n,...a===void 0?{}:{returnType:a},...o===void 0?{}:{optionsSource:o}}}return r==="select"||r==="status"||r==="multiselect"?{...n,...Array.isArray(t.options)?{options:t.options}:{}}:n}a(Lm,"toCompileAttribute");function Os(e,t){return {objectName:e.name,attributes:t.filter(r=>r.objectId===e.id).map(Lm)}}a(Os,"toCompileObject");function Ei(e,t){let r=_s(e,t);return {...Os(r,e.attributes),relatedObjects:Object.fromEntries(e.objects.map(n=>[n.name,Os(n,e.attributes)]))}}a(Ei,"computedCompileSchemaOf");function Bm(e){return {id:e.id,name:e.name,label:e.label,type:"rollup",...tr(e)}}a(Bm,"toRollupAttribute");function Ns(e){try{return e()}catch(t){throw t instanceof g?new h(t.message,[]):t}}a(Ns,"asValidationError");function rr(e,t){let r=Ei(e,t.objectId);return Ns(()=>ks(t,r))}a(rr,"computedPlanOf");function ks(e,t){if(e.attributeType==="rollup")return Ra(Bm(e),t);let r=tr(e);return Lt({attributeName:e.name,expression:String(r.expression??""),returnType:r.returnType,schema:t})}a(ks,"compilePlan");function Ci(e){Ns(()=>xa(e.map(t=>({attributeName:t.attributeName,dependencies:t.dependencies}))));}a(Ci,"assertAcyclicComputed");function $m(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($m,"dependencyNames");function Ze(e,t){let r=Ei(e,t),n=[];for(let o of e.attributes)if(!(o.objectId!==t||!Oe(o)))try{n.push(ks(o,r));}catch(a){if(!(a instanceof g))throw a}return n}a(Ze,"compilablePlansOf");function Oi(e,t,r){let n=_s(e,t),o=[];for(let a of Ze(e,t))a.attributeName!==r&&a.dependencies.some(s=>$m(s,r))&&o.push(a.attributeName);for(let a of e.objects)if(a.id!==t)for(let s of Ze(e,a.id))s.dependencies.some(c=>{if(c.kind!=="relation"||c.targetAttributeName!==r)return false;let f=e.attributes.find(x=>x.objectId===a.id&&x.name===c.relationName&&x.attributeType==="relation");return f!==void 0&&_e(f)===n.name})&&o.push(`${a.name}.${s.attributeName}`);return o}a(Oi,"dependentsOf");function et(e){let t=e.config?.bilateral;if(typeof t!="object"||t===null)return;let{object:r,attribute:n}=t;return typeof r=="string"&&typeof n=="string"?{object:r,attribute:n}:void 0}a(et,"bilateralDeclarationOf");function Um(e,t){return t!==void 0&&e.attributeType===t.attributeType&&qm(e,t)}a(Um,"sameAttribute");function qm(e,t){return JSON.stringify(e.config??{})===JSON.stringify(t.config??{})}a(qm,"sameConfig");function zm(e,t){let r=a(n=>Um(n,e.attributes.find(o=>o.id===n.id)),"untouched");for(let n of t.attributes){if(n.attributeType!=="relation")continue;let o=et(n);if(o===void 0||r(n))continue;let s=t.objects.find(R=>R.id===n.objectId)?.name??n.objectId,l=t.objects.find(R=>R.name===o.object),c=t.attributes.find(R=>R.objectId===l?.id&&R.name===o.attribute),f=`relation "${s}.${n.name}" declares inverse "${o.object}.${o.attribute}"`;if(c===void 0)throw new h(`${f}, which object "${o.object}" does not have; draft it first`,[]);if(c.attributeType!=="relation")throw new h(`${f}, which is not a relation`,[]);let x=et(c);if(!(G(c).some(R=>R.object===s)&&(r(c)?x===void 0||x.object===s&&x.attribute===n.name:x?.object===s&&x.attribute===n.name)))throw new h(`${f}, which does not point back to "${s}.${n.name}"`,[])}}a(zm,"assertBilateralPairs");function Ps(e,t,r){let n=`fld_${e}_${t}`;return r===0?n:`${n}_${r}`}a(Ps,"makeFieldId");function Gm(e,t){return e.attributeGroup?e.attributeGroup.id:e.attribute?e.attribute:`slot${t}`}a(Gm,"seedOf");function Wm(e){let t=new Map,r=e.fields.map((n,o)=>{if(n.id)return n;let a=Gm(n,o),s=t.get(a)??0;return t.set(a,s+1),{...n,id:Ps(e.id,a,s)}});return {...e,fields:r}}a(Wm,"withIds");function _i(e){return e.map(t=>t.type==="form"?{...t,groups:t.groups.map(Wm)}:t)}a(_i,"ensureFieldIds");function Km(e){return {id:e.id??e.name,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon}}}a(Km,"toDraftableObject");function Hm(e){let t=e.id??e.name;return (e.attributes??[]).map(r=>Ym(r,t))}a(Hm,"toDraftableAttributes");function nr(e){return {id:e.id,name:e.name,label:e.label,type:e.attributeType,...e.config}}a(nr,"toAttribute");function Ym(e,t){let{id:r,name:n,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(Ym,"toDraftableAttribute");function js(e){let t=e[0];return t?`{{ ${t.name} }}`:"{{ id }}"}a(js,"draftedLabelExpression");function ir(e,t){let r=t.filter(n=>n.objectId===e.id);return {id:e.id,name:e.name,label:e.label,...e.icon===void 0?{}:{icon:e.icon},labelExpression:js(r),attributes:r.map((n,o)=>{let a=nr(n);return a.order===void 0?{...a,order:o}:a})}}a(ir,"draftedObjectDefinition");var Qm=0x100000001b3n,Jm=0xffffffffffffffffn;function Fs(e,t){let r=t;for(let n of new TextEncoder().encode(e))r^=BigInt(n),r=r*Qm&Jm;return r}a(Fs,"fnv1a64");function Ni(e,t){let r=`${e.toLowerCase()}:${t}`,n=Fs(r,0xcbf29ce484222325n).toString(16).padStart(16,"0"),o=Fs(`${t}:${r}`,0x84222325cbf29ce4n).toString(16).padStart(16,"0"),a=n+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(Ni,"viewIdFor");function me(e){return {list:Ni(e,"list"),detail:Ni(e,"detail")}}a(me,"defaultViewIdsFor");function Vs(e,t,r){if(e==="list"){let s=We(r);return {id:t,objectName:s.object,type:"list",label:s.label,tabs:[],config:s.config,derived:true}}let n=Ge(r),{tabs:o,...a}=n.config;return {id:t,objectName:n.object,type:"detail",label:n.label,tabs:_i(o??[]),config:a,derived:true}}a(Vs,"derivedView");function ki(e,t){let r=ir(e,t),n=me(e.id);return ["list","detail"].map(o=>Vs(o,n[o],r))}a(ki,"defaultViewsFor");function Pi(e,t,r){return Vs(e.type,e.id,ir(t,r))}a(Pi,"regenerateDerived");function Ne(e,t){let r=e.objects.find(n=>n.id===t);if(!r)throw new h(`Object "${t}" is not in the draftable state`,[]);return r}a(Ne,"requireObject");function ji(e,t,r){return {...e,attributes:[...r],views:e.views.map(n=>n.derived&&n.objectName===t.name?Pi(n,t,r):n)}}a(ji,"withDerivedViews");function or(e){return {objectId:e.objectId}}a(or,"objectFocus");function ar(e){return {objectId:e.objectId,recordId:e.recordId}}a(ar,"recordFocus");function Ms(e){return {objectId:e.objectId,attributeId:e.attributeId}}a(Ms,"attributeFocus");function sr(e){return {objectId:e.objectId,attributeName:e.attribute}}a(sr,"existingAttributeFocus");function Xm(e){let t=Object.keys(e.changes).sort();return t.length===1?[t[0]]:void 0}a(Xm,"firstChangedProperty");function Zm(e,t){if(e.type==="list"){let r=(e.config.tabs??[]).find(n=>n.id!==kt&&(n.columns??[]).includes(t));return r===void 0?void 0:`tab "${r.id}"`}for(let r of e.tabs){let n="groups"in r?r.groups:[];for(let o of n)if(o.fields.some(a=>a.attribute===t)&&!(r.id===ze&&o.id===Pt))return `group "${o.id}"`}}a(Zm,"handShapedUse");function ef(e,t){if(e.type==="list"){let r=(e.config.tabs??[]).map(n=>n.id===kt&&n.columns!==void 0?{...n,columns:n.columns.filter(o=>o!==t)}:n);return {...e,config:{...e.config,tabs:r}}}return {...e,tabs:e.tabs.map(r=>{if(r.id!==ze||!("groups"in r))return r;let n=r.groups.map(o=>o.id===Pt?{...o,fields:o.fields.filter(a=>a.attribute!==t)}:o);return {...r,groups:n}})}}a(ef,"withoutGeneratedUse");function tf(e,t,r){let n=r.config??{},o=r.name;if(n.relationPath!==void 0)throw new h(`rollup "${o}": relationPath is not supported yet`,[]);let a=n.relationAttribute;if(typeof a!="string"||a.length===0)throw new h(`rollup "${o}" needs a relation attribute; none is configured on object "${t.name}"`,[]);let s=e.attributes.find(v=>v.objectId===t.id&&v.name===a&&v.attributeType==="relation");if(!s)throw new h(`rollup "${o}" needs a relation attribute; "${a}" is not a relation of object "${t.name}"`,[]);let l=_e(s);if(l===void 0){let v=G(s).filter(W=>W.object!=="*").length;throw new h(`rollup "${o}" needs a relation with one target object; "${a}" targets ${v}`,[])}if(n.function==="count")return;let c=e.objects.find(v=>v.name===l),f=n.targetAttribute;if(!(c!==void 0&&e.attributes.some(v=>v.objectId===c.id&&v.name===f)))throw new h(`rollup "${o}" targets attribute "${f}", which object "${l}" does not have`,[])}a(tf,"assertRollupShape");function rf(e,t){let r=e.config??{};if(e.attributeType==="rollup")return r.relationAttribute===t;let n=typeof r.expression=="string"?r.expression:"";return new RegExp(`(^|[^A-Za-z0-9_])${t}\\.`).test(n)}a(rf,"traversesRelation");function Bs(e,t){let r=Ne(e,t.objectId);if(t.attributeType==="relation"){for(let o of G(t))if(o.object!==ee&&!e.objects.some(a=>a.name===o.object))throw new h(`object "${o.object}" is unknown; create it first`,[]);let n=et(t)?.object;if(n!==void 0&&n!==ee&&!e.objects.some(o=>o.name===n))throw new h(`object "${n}" is unknown; create it first`,[]);for(let o of e.attributes)o.objectId!==t.objectId||!Oe(o)||rf(o,t.name)&&rr(e,o);}else if(Oe(t))t.attributeType==="rollup"&&tf(e,r,t),rr(e,t);else return;Ci(Ze(e,t.objectId));}a(Bs,"assertConfigFolds");var fe={...Ri,objectId:z$1.string().uuid()},nf=z$1.object({...fe,type:z$1.literal("add_object"),name:yt,label:z$1.string().min(1),icon:z$1.string().min(1).optional()}),of={type:"add_object",schema:nf,apply:a((e,t)=>{if(e.objects.some(n=>n.name===t.name))throw new h(`Object "${t.name}" already exists`,[]);if(e.objects.some(n=>n.id===t.objectId))throw new h(`Object id "${t.objectId}" is already taken`,[]);let r={id:t.objectId,name:t.name,label:t.label,...t.icon===void 0?{}:{icon:t.icon}};return {...e,objects:[...e.objects,r],views:[...e.views,...ki(r,e.attributes)]}},"apply"),focus:or,presentation:A(or,"structural"),describe:a(e=>`Cr\xE9e l'objet \xAB ${e.label} \xBB`,"describe")},af=z$1.object({...fe,type:z$1.literal("update_object"),changes:z$1.object({label:z$1.string().min(1).optional(),icon:z$1.string().min(1).optional()}).refine(e=>Object.keys(e).length>0,"update_object needs at least one change")}),Ls=a(e=>({objectId:e.objectId}),"updateObjectFocus"),sf={type:"update_object",schema:af,apply:a((e,t)=>(Ne(e,t.objectId),{...e,objects:e.objects.map(r=>r.id===t.objectId?{...r,...t.changes}:r)}),"apply"),focus:Ls,presentation:A(Ls,"atomic",Xm),describe:a(e=>e.changes.label?`Renomme l'objet en \xAB ${e.changes.label} \xBB`:"Modifie l'objet","describe")},uf=z$1.object({...fe,type:z$1.literal("remove_object")}),lf={type:"remove_object",schema:uf,apply:a((e,t)=>{Ne(e,t.objectId);let r=e.objects.find(n=>n.id===t.objectId)?.name;for(let n of e.attributes){if(n.objectId===t.objectId||n.attributeType!=="relation"||!G(n).some(a=>a.object===r))continue;let o=e.objects.find(a=>a.id===n.objectId);throw new h(`object "${r}" is targeted by attribute "${o?.name}.${n.name}"; remove that attribute first`,[])}return {...e,objects:e.objects.filter(n=>n.id!==t.objectId),attributes:e.attributes.filter(n=>n.objectId!==t.objectId),sampleRecords:e.sampleRecords.filter(n=>n.objectId!==t.objectId),views:e.views.filter(n=>n.objectName!==r)}},"apply"),focus:or,presentation:A(or,"structural"),describe:a(e=>`Supprime l'objet ${e.objectId}`,"describe")},$s=yo;function Us(e,t){try{n$1(e,t);}catch(r){throw r instanceof h?new h(r.message,r.errors.map(n=>({...n,path:["config",...n.path??[]]}))):r}}a(Us,"assertConfigParses");var df=z$1.object({...fe,type:z$1.literal("add_attribute"),attributeId:z$1.string().min(1),name:xr,label:z$1.string().min(1),attributeType:z$1.enum($s),config:z$1.record(z$1.string(),z$1.unknown()).optional()}).superRefine((e,t)=>{try{Us(e.attributeType,e.config??{});}catch(r){if(r instanceof h){for(let n of r.errors)t.addIssue({code:"custom",message:n.message,path:[...n.path]});return}throw r}}),cf={type:"add_attribute",schema:df,apply:a((e,t)=>{let r=Ne(e,t.objectId);if(e.attributes.some(s=>s.objectId===t.objectId&&s.name===t.name))throw new h(`Attribute "${t.name}" already exists on object "${t.objectId}"`,[]);let n={id:t.attributeId,objectId:t.objectId,name:t.name,label:t.label,attributeType:t.attributeType,...t.config===void 0?{}:{config:t.config}};for(let s of e.sampleRecords)s.objectId===t.objectId&&Gs(s.id,n,s.values);let o=[...e.attributes,n],a=ji(e,r,o);return Bs(a,n),a},"apply"),focus:Ms,presentation:A(Ms,"local"),describe:a(e=>`Ajoute l'attribut \xAB ${e.label} \xBB`,"describe")},qs={...fe,attribute:xr};function zs(e,t,r,n){let o=Ne(e,t);if(r===void 0)throw new h(`${n} 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===r);if(!a)throw new h(`Attribute "${r}" is not on object "${t}"`,[]);return {object:o,attribute:a}}a(zs,"requireAttribute");var pf=z$1.object({...qs,type:z$1.literal("update_attribute"),changes:z$1.object({label:z$1.string().min(1).optional(),config:z$1.record(z$1.string(),z$1.unknown()).optional()}).refine(e=>Object.keys(e).length>0,"update_attribute needs at least one change")}),mf={type:"update_attribute",schema:pf,apply:a((e,t)=>{let{object:r,attribute:n}=zs(e,t.objectId,t.attribute,"update_attribute");t.changes.config!==void 0&&Us(n.attributeType,t.changes.config);let o={...n,...t.changes},a=e.attributes.map(l=>l===n?o:l),s=ji(e,r,a);return Bs(s,o),s},"apply"),focus:sr,presentation:A(sr,"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")},ff=z$1.object({...qs,type:z$1.literal("remove_attribute")}),bf={type:"remove_attribute",schema:ff,apply:a((e,t)=>{let{object:r,attribute:n}=zs(e,t.objectId,t.attribute,"remove_attribute"),[o]=Oi(e,t.objectId,n.name);if(o!==void 0)throw new h(`attribute "${n.name}" is used by "${o}"; remove that first`,[]);for(let c of e.views){if(c.objectName!==r.name)continue;let f=Zm(c,n.name);if(f!==void 0)throw new h(`attribute "${n.name}" is used by view "${c.id}" (${f}); remove it from the view first`,[])}let a=e.sampleRecords.find(c=>c.objectId===n.objectId&&n.name in c.values);if(a)throw new h(`Attribute "${n.name}" is still used by sample record "${a.id}"`,[]);let s=e.attributes.filter(c=>c!==n),l={...e,views:e.views.map(c=>c.objectName===r.name?ef(c,n.name):c)};return ji(l,r,s)},"apply"),focus:sr,presentation:A(sr,"local"),describe:a(e=>`Supprime l'attribut \xAB ${e.attribute} \xBB`,"describe")};function gf(e,t,r,n){let o=nr(r);try{c$2(o);}catch{return}let a=g$2(o,n);if(a.success)return;let s=a.errors??[],l=s.map(c=>c.path.length>1?`${c.path.join(".")}: ${c.message}`:c.message).join(", ");throw new h(`Sample record "${e}" has an invalid value for "${t}": ${l}`,s.map(c=>({path:c.path,message:c.message})))}a(gf,"assertSampleValue");function Gs(e,t,r){if(t.config?.required===true&&t.config?.defaultValue===void 0&&!(t.name in r&&r[t.name]!==void 0))throw new h(`Sample record "${e}" is missing a value for required attribute "${t.name}"`,[])}a(Gs,"assertRequiredCovered");function Fi(e){return (Array.isArray(e)?e:[e]).flatMap(r=>{if(typeof r=="string")return [r];if(typeof r=="object"&&r!==null){let n=r.id;if(typeof n=="string")return [n]}return []})}a(Fi,"relationValueIds");function yf(e,t,r,n){if(r.attributeType!=="relation"||n===void 0||n===null)return;let o=_e(r),a=e.objects.find(l=>l.name===o);if(!a)return;let s=e.views.some(l=>l.id===me(a.id).list);for(let l of Fi(n)){let c=e.sampleRecords.find(x=>x.id===l);if(c?.objectId!==a.id&&(c!==void 0||s))throw new h(`sample record "${t}" references unknown sample "${l}"`,[])}}a(yf,"assertUnknownSampleReference");var hf=z$1.object({...fe,type:z$1.literal("add_sample_record"),recordId:z$1.string().uuid(),values:z$1.record(z$1.string(),z$1.unknown()),publication:z$1.enum(["preview","requested-data"]).optional()}),Af={type:"add_sample_record",schema:hf,apply:a((e,t)=>{if(Ne(e,t.objectId),e.sampleRecords.some(n=>n.id===t.recordId))throw new h(`Sample record "${t.recordId}" already exists`,[]);let r=new Map(e.attributes.filter(n=>n.objectId===t.objectId).map(n=>[n.name,n]));for(let[n,o]of Object.entries(t.values)){let a=r.get(n);if(!a)throw new h(`Sample record "${t.recordId}" uses unknown attribute "${n}"`,[]);if(Oe(a))throw new h(`attribute "${a.name}" is computed and cannot be set on a sample record`,[]);yf(e,t.recordId,a,o),gf(t.recordId,n,a,o);}for(let n of r.values())Gs(t.recordId,n,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:ar,presentation:A(ar,"local"),describe:a(()=>"Ajoute un exemple","describe")};function Tf(e,t){return new Set(e.attributes.filter(r=>r.objectId===t&&r.attributeType==="relation").map(r=>r.name))}a(Tf,"relationNamesOf");function wf(e,t){for(let r of e.sampleRecords){if(r.id===t)continue;let n=Tf(e,r.objectId);for(let[o,a]of Object.entries(r.values))if(n.has(o)&&Fi(a).includes(t))throw new h(`sample record "${t}" is referenced by sample record "${r.id}"; remove that first`,[])}}a(wf,"assertSampleNotReferenced");var xf=z$1.object({...fe,type:z$1.literal("remove_sample_record"),recordId:z$1.string().min(1)}),If={type:"remove_sample_record",schema:xf,apply:a((e,t)=>{if(!e.sampleRecords.some(r=>r.id===t.recordId&&r.objectId===t.objectId))throw new h(`Sample record "${t.recordId}" is not in object "${t.objectId}"`,[]);return wf(e,t.recordId),{...e,sampleRecords:e.sampleRecords.filter(r=>r.id!==t.recordId)}},"apply"),focus:ar,presentation:A(ar,"local"),describe:a(()=>"Retire un exemple","describe")},ke=[of,sf,lf,cf,mf,bf,Af,If];function Sf(){let e=new Map;for(let t of [...ke,...Ee,...Ce]){if(e.has(t.type))throw new r("architect operation",t.type);e.set(t.type,t);}return e}a(Sf,"build");var tt=Sf(),vf=[...tt.keys()];function rt(e){let t=tt.get(e.type);if(!t)throw new h(`Operation "${e.id}" has unknown type "${e.type}"`,[]);return t}a(rt,"defOf");function Vi(e,t){return t.reduce((r,n)=>rt(n).apply(r,n),e)}a(Vi,"applyOperations");function Mi(e){return rt(e).focus(e)}a(Mi,"focusOf");function Rf(e,t){return e.map(r=>rt(r).describe(r,t))}a(Rf,"describeOperations");function Df(e){if(typeof e!="object"||e===null||!("type"in e))throw new h("An operation must be an object carrying a type",[]);let t=e.type;if(typeof t!="string")throw new h("An operation's type must be a string",[]);let r=tt.get(t);if(!r)throw new h(`Unknown operation type "${t}"`,[]);let n=r.schema.safeParse(e);if(!n.success)throw new h(`Operation "${t}" is invalid: ${n.error.issues.map(o=>`${o.path.join(".")} ${o.message}`).join("; ")}`,[]);return n.data}a(Df,"parseOperation");function Li(e){return rt(e).presentation(e)}a(Li,"presentationOf");function Ef(e){let t=e.map(Li);return new Set(t.map(({focus:n})=>n.viewId??n.objectId).filter(n=>n!==void 0)).size>1||t.some(({impact:n})=>n==="structural")?"structural":t.some(({impact:n})=>n==="local")?"local":"atomic"}a(Ef,"episodeImpactOf");function Cf(e,t){return e.config.tabs?.find(r=>r.id===t)}a(Cf,"listTabOf");function Ws(e,t){let r=t.viewId?e.views.find(o=>o.id===t.viewId):void 0,n=t.tabId?r?.tabs.find(o=>o.id===t.tabId):void 0;if(t.attributeId)return e.attributes.find(o=>o.id===t.attributeId);if(t.attributeName)return e.attributes.find(o=>o.objectId===t.objectId&&o.name===t.attributeName);if(t.fieldId){if(n?.type!=="form")return;for(let o of n.groups){let a=o.fields.find(s=>s.id===t.fieldId);if(a)return a}return}if(t.groupId)return n?.type!=="form"?void 0:n.groups.find(o=>o.id===t.groupId);if(t.tabId)return r?n??Cf(r,t.tabId):void 0;if(t.recordId)return e.sampleRecords.find(o=>o.id===t.recordId);if(r)return r;if(t.objectId)return e.objects.find(o=>o.id===t.objectId)}a(Ws,"snapshotArchitectTarget");function Of(e,t){let r=e;return t.map(n=>{let o=Li(n),a=Ws(r,o.focus);r=Vi(r,[n]);let s=Ws(r,o.focus);return {operationId:n.id,operationType:n.type,presentation:o,before:a,after:s}})}a(Of,"deriveArchitectChanges");function Ks(e){return e.attributeName&&e.objectId?`attribute:${e.objectId}:${e.attributeName}`:e.attributeId?`attribute-id:${e.attributeId}`:e.tabId&&e.viewId?`tab:${e.viewId}:${e.tabId}`:e.viewId?`view:${e.viewId}`:e.objectId?`object:${e.objectId}`:null}a(Ks,"proposalTargetKey");function _f(e,t){let r=new Set;for(let n of t){let o=Mi(n),a=Ks(o);a&&r.add(a),o.objectId&&r.add(`object:${o.objectId}`),o.viewId&&r.add(`view:${o.viewId}`);let s=e.views.find(x=>x.id===o.viewId),l=e.objects.find(x=>x.name===s?.objectName);l&&r.add(`object:${l.id}`),(n.type==="remove_object"||n.type.includes("sample_record"))&&o.objectId&&r.add(`object-tree:${o.objectId}`),n.type==="add_object"&&typeof n.name=="string"&&r.add(`object-name:${n.name}`);let c=n.type==="update_attribute"&&typeof n.changes=="object"&&n.changes!==null?n.changes:null,f=n.type==="add_attribute"?n.config:c&&"config"in c?c.config:void 0;if(f&&typeof f=="object"&&"targets"in f&&Array.isArray(f.targets))for(let x of f.targets)typeof x=="object"&&x!==null&&"object"in x&&typeof x.object=="string"&&x.object!=="*"&&r.add(`object-name:${x.object}`);}return [...r]}a(_f,"requiredTargetKeys");function Nf(e,t){return Object.fromEntries(t.map(r=>[r,b$3(kf(e,r))]))}a(Nf,"targetTokensFor");function kf(e,t){if(t.startsWith("object:"))return e.objects.find(r=>r.id===t.slice(7))??null;if(t.startsWith("object-name:"))return e.objects.find(r=>r.name===t.slice(12))??null;if(t.startsWith("object-tree:")){let r=t.slice(12),n=e.objects.find(o=>o.id===r);return n?{object:n,attributes:e.attributes.filter(o=>o.objectId===r),views:e.views.filter(o=>o.objectName===n.name),sampleRecords:e.sampleRecords.filter(o=>o.objectId===r)}:null}if(t.startsWith("attribute-id:"))return e.attributes.find(r=>r.id===t.slice(13))??null;if(t.startsWith("attribute:")){let r=t.slice(10),n=r.indexOf(":");if(n<0)throw new h(`Invalid proposal target key "${t}"`,[]);return e.attributes.find(o=>o.objectId===r.slice(0,n)&&o.name===r.slice(n+1))??null}if(t.startsWith("view:"))return e.views.find(r=>r.id===t.slice(5))??null;if(t.startsWith("tab:")){let r=t.slice(4),n=e.views.find(a=>r.startsWith(`${a.id}:`));if(!n)return null;let o=r.slice(n.id.length+1);return (n.type==="list"?n.config.tabs:n.tabs)?.find(a=>a.id===o)??null}throw new h(`Unknown proposal target key "${t}"`,[])}a(kf,"targetSnapshot");function Pf(e){return {id:e.id??"",objectName:e.object,type:e.type,label:e.label,tabs:pt(e)?e.config.tabs??[]:[],config:e.config}}a(Pf,"toDraftableView");function nt(e){return e.type==="detail"?{...e.config,tabs:e.tabs}:e.config}a(nt,"persistedViewConfig");function jf(e,t){return e.type==="detail"?{...e,label:t.label,config:nt(t)}:{...e,label:t.label,config:nt(t)}}a(jf,"fromDraftableView");function Ff(e){let t={id:e.id,name:"default",label:e.label,object:e.objectName,default:true};return e.type==="detail"?{...t,type:"detail",config:nt(e)}:{...t,type:"list",config:nt(e)}}a(Ff,"draftedViewDefinition");var Hs=z$1.object({type:z$1.literal("remove_operation"),operationId:z$1.string().min(1).describe("The id of a stored operation to drop from the draft")});function Bi(e,t=[]){let r=[...e.map(n=>n.schema),...t].map(Mf);return z$1.discriminatedUnion("type",r)}a(Bi,"union");function Vf(e){return e instanceof z$1.ZodString&&e.format==="uuid"}a(Vf,"isUuidString");function Mf(e){let t={};for(let[r,n]of Object.entries(e.shape)){if(!Vf(n))continue;let o=z$1.string().min(1);t[r]=n.description===void 0?o:o.describe(n.description);}return Object.keys(t).length===0?e:e.safeExtend(t)}a(Mf,"relaxUuidKeys");var Ys=Bi(ke,[Hs]),Qs=Bi(Ce),Js=Bi(Ee),Lf={schema:Ys,"list-view":Qs,"detail-view":Js},Bf=new Map([...ke.map(e=>[e.type,"schema"]),["remove_operation","schema"],...Ce.map(e=>[e.type,"list-view"]),...Ee.map(e=>[e.type,"detail-view"])]);function $f(e){return Bf.get(e)??null}a($f,"familyOf");function Uf(e){let t=e.config??{};if(e.attributeType==="relation")return `\u2192 ${G(e).map(r=>r.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(Uf,"attributeDetail");function qf(e){let t=e.config?.options,r=Uf(e);return {name:e.name,label:e.label,type:e.attributeType,...Array.isArray(t)?{options:t.map(n=>n.value)}:{},...r===void 0?{}:{detail:r}}}a(qf,"summarizeAttribute");function zf(e,t,r){let n=me(e.id),o=r.some(a=>a.id===n.list);return {id:e.id,name:e.name,label:e.label,attributes:t.filter(a=>a.objectId===e.id).map(qf),...o?{viewIds:n}:{}}}a(zf,"summarizeObject");function Gf(e){return e.attribute??e.attributeGroup?.id??""}a(Gf,"fieldName");function Wf(e){return e.type==="list"?(e.config.tabs??[]).map(r=>({id:r.id,label:r.label,columns:r.columns})):e.tabs.map(t=>{let r="groups"in t?t.groups:void 0;return {id:t.id,label:t.label,...r===void 0?{}:{groups:r.map(n=>({id:n.id,label:n.label,fields:n.fields.map(Gf)}))}}})}a(Wf,"summarizeTab");function Kf(e,t){let r=t.find(n=>n.name===e.objectName)?.id;if(r===void 0)throw new h(`View "${e.id}" names object "${e.objectName}", which is not in the draft scope`,[]);return {id:e.id,type:e.type,objectId:r,label:e.label,derived:e.derived===true,tabs:Wf(e)}}a(Kf,"summarizeView");function Hf(e,t){let r=new Map;for(let n of e.sampleRecords)r.set(n.objectId,(r.get(n.objectId)??0)+1);return {objects:e.objects.map(n=>zf(n,e.attributes,e.views)),views:e.views.map(n=>Kf(n,e.objects)),sampleRecords:[...r.entries()].map(([n,o])=>({objectId:n,count:o})),operationCount:t}}a(Hf,"summarizeDraft");var Yf=["draft_schema","draft_list_view","draft_detail_view"],Qf="publish_architect_draft",Jf="discard_architect_draft",Xf="request_design_review",Zf="get_architect_draft";export{Gx as AGENT_UI_BATCH_MAX_BYTES,Wx as AGENT_UI_BATCH_MAX_ITEMS,ko as ALLOWED_PROPERTY_TYPES,yr as ALL_ACTIONS,vf as ALL_OPERATION_TYPES,dT as ALL_SYSTEM_RESOURCES,Py as ARTIFACT_FILE_ROLES,Ny as ARTIFACT_KINDS,Kl as ARTIFACT_LIST_VIEW,zl as ARTIFACT_OBJECT,_t as ARTIFACT_OBJECT_NAME,ky as ARTIFACT_RETENTIONS,Gl as ARTIFACT_VIEW,yo as ATTRIBUTE_TYPES,Yg as AUDIT_ACTIONS,Hg as AUDIT_RESOURCE_TYPES,hn as ActivityTabConfig,Ir as AgentBuilder,Mg as BEHAVIOR_PROPERTIES,Lu as BYTE_UNIT_LABELS,Su as CLAIMABLE_SESSION_STATUSES,He as COMPUTED_FUNCTIONS,DI as COMPUTED_FUNCTION_METADATA,uI as COMPUTED_FUNCTION_NAMES,ZI as CONNECTOR_CALLBACK_PARAM,_o as COUNT_MODES,g as ComputedFormulaCompileError,gn as CustomTabConfig,uT as DB_COLUMN_FIELDS,Yo as DEFAULT_AGENT_EXECUTION_CONFIG,Ao as DEFAULT_APPROVAL_POLICY,Oy as DEFAULT_DICTATION_LIMITS,Vo as DEFAULT_LABEL_FALLBACK,ku as DEFAULT_MEETING_BOT_DISPLAY_NAME,fl as DEFAULT_ROLES,mT as DEFAULT_ROLE_DESCRIPTIONS,pT as DEFAULT_ROLE_LABELS,fT as DEFAULT_ROLE_PERMISSIONS,dh as DEFAULT_TENANT_SETTINGS,Ee as DETAIL_VIEW_OPERATIONS,Js as DETAIL_VIEW_OPERATION_INPUT,Ey as DICTATION_FINALIZATION_TIMEOUT_MS,xy as DICTATION_FRAME_BYTES,Sy as DICTATION_MAX_BUFFER_BYTES,Iy as DICTATION_MAX_FRAME_BYTES,vy as DICTATION_MAX_TRANSCRIPT_BYTES,Cy as DICTATION_MODEL_ID,Dy as DICTATION_PREPARATION_TIMEOUT_MS,wy as DICTATION_SAMPLE_RATE,Ry as DICTATION_TICKET_TTL_MS,Jf as DISCARD_ARCHITECT_DRAFT_TOOL_NAME,vA as DOCUMENT_SYSTEM_ATTRIBUTES,$s as DRAFTABLE_ATTRIBUTE_TYPES,Yf as DRAFT_WRITE_TOOL_NAMES,ql as DRIVE_LIST_VIEW,$l as DRIVE_OBJECT,Ot as DRIVE_OBJECT_NAME,Ul as DRIVE_VIEW,xn as DetailViewBuilder,wn as DocumentsTabConfig,ft as EMPTY_VALUE_PLACEHOLDER,Sh as ESTIMATED_COUNT_CAP,An as EmailsTabConfig,iS as FAKE_MEETING_BOT_SIGNATURE_HEADER,Lf as FAMILY_INPUTS,fr as FORM_FORBIDDEN_ATTRIBUTE_TYPES,Ue as FlagRegistry,Ct as FlagService,dn as FormBuilder,Ke as FormRegistry,un as FormRowBuilder,ln as FormStepBuilder,Zf as GET_ARCHITECT_DRAFT_TOOL_NAME,St as GroupBuilder,Vg as IDENTITY_PROPERTIES,Th as IMAGE_FORMATS,xo as INFERENCE_REASONING_OPTIONS,wo as INFERENCE_SPEEDS,Ce as LIST_VIEW_OPERATIONS,Qs as LIST_VIEW_OPERATION_INPUT,ld as LIVE_EVENT_TYPES,In as ListViewBuilder,Sn as ListViewTabConfigBuilder,vo as MAX_PRESET_DEPTH,dy as MAX_TODOS,py as MAX_TODO_DESCRIPTION_CHARS,cy as MAX_TODO_ID_CHARS,my as MAX_TODO_RESULT_CHARS,w as MEETING_ATTRIBUTES,sa as MEETING_DETAIL_VIEW_ID,Ql as MEETING_LIST_VIEW,oa as MEETING_LIST_VIEW_ID,Hl as MEETING_OBJECT,Nt as MEETING_OBJECT_NAME,Yl as MEETING_VIEW,aa as MEETING_WRITE_SOURCE,Bl as MEMORY_LIST_VIEW,Ml as MEMORY_OBJECT,Ll as MEMORY_VIEW,Jc as McpOAuthCompletionMode,Tn as MeetingsTabConfig,Du as NATIVE_AGENT_UI_PART_IDS_METADATA_KEY,Eu as NATIVE_AGENT_UI_PART_IDS_METADATA_SCHEMA_VERSION,bo as NOTIFICATION_INBOX_STATES,po as NOTIFICATION_KINDS,mo as NOTIFICATION_PRIORITIES,fo as NOTIFICATION_SENSITIVITIES,jg as NOTIFICATION_TYPES_V1,xu as NOTIFICATION_TYPE_AGENT_QUESTION_REQUESTED,Tu as NOTIFICATION_TYPE_AGENT_SESSION_WAITING_HUMAN,wu as NOTIFICATION_TYPE_AGENT_TASK_ASSIGNED,go as NOTIFICATION_WORK_STATES,oS as NO_RECORDING,Eo as NoopGeocodingAdapter,yt as OBJECT_NAME_SCHEMA,vu as OPEN_TOOL_PART_STATES,tt as OPERATION_REGISTRY,Kt as OPERATOR_SPECS,$e as ObjectBuilder,Lg as PRESENTATION_PROPERTIES,To as PROVIDER_NAMES,Qf as PUBLISH_ARCHITECT_DRAFT_TOOL_NAME,NA as QUALIFIED_SEPARATOR,Dh as QUOTA_KEYS,rS as RECORDING_OVERRIDES,nS as RECORDING_POLICIES,qo as RECORD_CREATOR_ROOT_ACTOR_METADATA_KEY,ee as RELATION_TARGET_ANY,Hs as REMOVE_OPERATION_SCHEMA,Xf as REQUEST_DESIGN_REVIEW_TOOL_NAME,yn as RichtextTabConfig,ke as SCHEMA_OPERATIONS,Ys as SCHEMA_OPERATION_INPUT,q as SCHEMA_PLAN_LIMITS,wi as SCHEMA_SOURCE_ID_PATTERN,yy as SESSION_STATE_STREAM_ID,Iu as SESSION_TERMINAL_STATUSES,ra as SKILL_CONTENT_TEMPLATE,jl as SKILL_LIST_VIEW,kl as SKILL_OBJECT,Pl as SKILL_VIEW,Al as STANDARD_SCHEMA_VENDOR,mr as SYSTEM_PART_CODES,$ as SYSTEM_RESOURCES,cT as SYSTEM_RESOURCE_LABELS,La as TODAY_DEFAULT,ny as TODO_PLAN_STATUSES,ly as TODO_STATUSES,Io as TOOL_APPROVAL_STATES,te as TabBuilder,vt as TableTabConfig,Zp as UPDATE_TABLE_TAB_CHANGE_KEYS,Np as UPDATE_TAB_CHANGE_KEYS,em as UPDATE_TAB_CONFIG_CHANGE_KEYS,ph as USER_STATUSES,mh as USER_WORK_POSTURES,ih as accessLevelToActions,nh as actionsToAccessLevel,DT as agent,VS as agentDataChunk,iy as agentDisplayName,PS as agentInferencePreferencesSchema,bp as agentMessageAttachmentSchema,fp as agentMessagePartSchema,mp as agentSessionInferenceOverridesInputSchema,jS as agentSessionInferenceOverridesSchema,rs as agentSessionMessageSchema,xp as agentUIValidationError,Vi as applyOperations,tl as applyPipes,al as applyRelationProps,Qx as architectDraftChannelKey,Ci as assertAcyclicComputed,xa as assertAcyclicComputedDependencies,zm as assertBilateralPairs,Ip as assertCustomAgentUIMessageChunk,ep as assertSchemaSourceId,et as bilateralDeclarationOf,Il as booleanFlag,$a as buildAgentFallbackTitle,ml as buildPermissionFlags,mt as buildPropertySchema,PA as buildQualifiedAttribute,Qo as checkbox,Ru as compareAgentSessionMessages,Ze as compilablePlansOf,Lt as compileComputedFormula,Ra as compileRollupAttribute,Mu as computeByteMagnitude,Ei as computedCompileSchemaOf,rr as computedPlanOf,Zc as conversationDisplayTitle,El as createFlagRegistry,Ol as createFlagService,At as createStandardSchemaProps,BT as currency,ss as customDataChunkSchemas,U as date,Ht as dateInTimezone,he as dateValueStart,me as defaultViewIdsFor,ki as defaultViewsFor,Yt as defineOperation,A as definePresentation,Oi as dependentsOf,Of as deriveArchitectChanges,QI as deriveCreateDefaultsFromFilters,cl as deriveInitials,Rf as describeOperations,Ja as destructiveSchema,H as detailView,Jo as document,js as draftedLabelExpression,ir as draftedObjectDefinition,Ff as draftedViewDefinition,hp as durableDateSchema,_i as ensureFieldIds,Ef as episodeImpactOf,xI as evaluateComputedAst,II as evaluateComputedFormula,SI as evaluateComputedFormulaWithResult,zc as evaluateFilterState,UI as evaluateRecordFilterState,Bo as extractAttributeNames,Uo as extractValueRefs,$f as familyOf,Dl as flagRegistry,Mi as focusOf,ZT as form,Nu as formFieldFlatKey,_u as formFieldKey,da as formRegistry,$x as formatAgentStreamFrameId,Po as formatAttributeValue,TA as formatByteSize,Lc as formatComputedResult,Ku as formatLocationValue,GT as formula,jf as fromDraftableView,Ge as generateDefaultDetailView,We as generateDefaultListView,Ox as getActiveTab,il as getEditableLabelAttribute,Vy as getErrorMessage,Bu as getListViewDisplayAttributeNames,iI as getLiveProtocolPayloadChannel,pl as getRecordCreatorPrincipalId,$o as getSingleAttributeFromExpression,Do as getSlotFieldTargets,ll as getUserDisplayName,hw as group,fS as hasDestructiveEntries,sh as hasOptions,os as imageModelIdSchema,Te as includesAction,zg as inferInverseCardinality,vc as inferRollupReturnType,vi as inferenceReasoningSchema,Si as inferenceSpeedSchema,wp as isAgentUIDataName,Kx as isAgentUIMessageBatch,Gg as isAttributeSortable,qg as isBilateralRelation,_I as isCheckboxEquality,ry as isClaimableSessionStatus,Oe as isComputedAttribute,Vt as isComputedFunctionName,ne as isDateRangeValue,bT as isDefaultRole,pt as isDetailView,RA as isDocumentAttribute,Fu as isEmptyObject,Pu as isFieldGroup,$y as isFormDefinition,ct as isFormFieldsRow,br as isFormFreeFieldRef,Hy as isFormHeadingRow,Yy as isFormSeparatorRow,Ro as isFormSlotFieldRef,Qy as isFormTextRow,gt as isLabelExpression,Oo as isListView,oI as isLiveEventEnvelope,eI as isLiveEventPayload,hd as isLiveEventPayloadForType,yd as isLiveEventType,No as isNotEmpty,oy as isOpenToolPartState,_a as isPlainRecord,OT as isStandardSchema,sy as isSystemPartCode,ty as isTerminalSessionStatus,Xg as isTerminalState,ay as isToolApprovalState,ho as isUniversalRelation,Rl as jsonFlag,ey as legacyStatusToSessionState,Y as listView,pa as liveChannelKey,qT as location,Ps as makeFieldId,DA as matchesAccepts,gp as mentionReferenceSchema,yp as modelDefinitionSchema,is as modelReferenceSchema,UT as multiselect,Ou as nativeAgentUIPartIdMetadataKey,$u as normalizeDateValue,wt as number,vl as numberFlag,cw as object,uy as orderAgentSessionMessages,Ux as parseAgentStreamFrameId,ju as parseCountMode,ma as parseLiveChannelKey,hy as parseNativeAgentUIPartIdsMetadata,Df as parseOperation,Ih as parseOptionalCountMode,kA as parseQualifiedAttribute,up as persistedDefaultViewTargetSchema,ES as persistedSchemaPlanSchema,nt as persistedViewConfig,LT as phone,ip as plannedAttributeSchema,op as plannedInlineAttributeSchema,ap as plannedObjectSchema,Li as presentationOf,Ks as proposalTargetKey,sp as proposedDefaultViewTargetSchema,ns as providerNameSchema,ul as qualifiedPropertyDefs,Gy as readFormFieldValue,Pi as regenerateDerived,Ww as registry,Ie as relation,sl as relationPropertyDefs,_e as relationTargetObjectName,G as relationTargets,Ug as relationTargetsOf,Fi as relationValueIds,Ar as renderLabelExpression,_f as requiredTargetKeys,id as resetViewToDefault,Yc as resolveAttributeDefaultValue,zy as resolveFieldRequired,Co as resolvePropertyDefinitions,xe as richtext,WT as rollup,Sc as rollupToFormulaExpression,DS as schemaPlanSchema,K as select,FS as sessionInferencePatchSchema,Zg as sessionStateToLegacyStatus,$T as status,Sl as stringFlag,Hf as summarizeDraft,Nf as targetTokensFor,b as text,nr as toAttribute,Hm as toDraftableAttributes,Km as toDraftableObject,Pf as toDraftableView,Vu as toUndefinedIfEmpty,Ap as todoItemSchema,Tp as todoPlanSchema,as as toolImpactSchema,zT as user,Be as validateAttributeName,el as validateLabelExpression,wl as validateObjectExpressions,Le as validateObjectName,ht as validateViewName,Ni as viewIdFor,Jl as viewRegistry,bh as viewStateKey,tp as viewSyncPayload};
|