@almadar/core 10.35.0 → 10.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export { h as ANIMATION_NAMES, i as ASSET_ASPECTS, j as ASSET_DIMENSIONS, k as A
5
5
  import { S as SExpr, a as EventPayload } from './expression-DpAj1RzP.js';
6
6
  export { C as CORE_BINDINGS, b as CoreBinding, c as EvalContext, d as EventPayloadValue, E as Expression, e as ExpressionInput, f as ExpressionSchema, L as LogMeta, g as LogMetaValue, P as ParsedBinding, h as SExprAtom, i as SExprAtomSchema, j as SExprInput, k as SExprSchema, l as collectBindings, m as getArgs, n as getOperator, o as isBinding, p as isEventPayloadValue, q as isSExpr, r as isSExprAtom, s as isSExprCall, t as isValidBinding, u as parseBinding, v as sexpr, w as walkSExpr } from './expression-DpAj1RzP.js';
7
7
  import { ResolvedIR, ResolvedEntity, ResolvedPage, ResolvedTrait, ChangesetValue, SchemaChange, CategorizedRemovals, PageContentReduction, SemanticSchemaChange } from './types/index.js';
8
- export { AgentCodeSearchResult, AgentCompactResult, AgentCompactStrategy, AgentContext, AgentGenerateOptions, AgentMemoryCategory, AgentMemoryRecord, AnalysisOrbital, AnalysisOrbitalParams, AnalysisPageOverride, AnalysisRename, AnalysisResult, AnnotationTier, AppCreatedEvent, AppSummary, AssetLoadStatus, BINDING_CONTEXT_RULES, BINDING_DOCS, BINDING_ROOTS, BindingContext, BindingRoot, BindingSchema, BridgeHealth, BuilderResult, BusEvent, BusEventListener, BusEventSource, CancelledEvent, ChangeAuthor, ChangeSetDocument, ChangeSummary, ChangesetRecordedEvent, CheckStatus, Clarification, ClarificationCandidate, ClarificationLevel, CompleteEvent, ComplexityAssessment, ComposeAllResult, ComposeChildrenResult, ComposeOptions, ContextExtensions, CreateFlow, DEFAULT_INTERACTION_MODELS, DeleteFlow, DispatchUpdatesResult, EdgeType, EditFlow, EffectPayload, EffectResult, EffectTrace, ErrorEvent, EventEmit, EventKey, EventListen, EventLogEntry, EvolutionDelta, ExecutePlanResult, ExtraTraitRef, FileOperationEvent, FileWrittenEvent, GateState, GenerationLogEvent, GitHubIssue, GitHubLink, GitHubRepo, HistoryMeta, IntegrationContext, InteractionModel, InteractionModelInput, InteractionModelSchema, InterruptEvent, KNOWN_VALIDATION_ERROR_CODES, KnobPayload, KnownValidationErrorCode, LazyService, LineageEntry, ListInteraction, LivingEdge, LivingEffect, LivingEntity, LivingEvent, LivingField, LivingOrbital, LivingOrbitalSchema, LivingPage, LivingState, LivingTrait, LivingTransition, LivingValue, LivingVertex, LlmCallToolsResult, LlmContext, LlmMessage, LlmTokenUsage, LlmToolCall, LlmToolDef, LoloEmitResult, MemoryContext, MessageEvent, OrbitalAddedEvent, OrbitalSchemaCompleteEvent, OrbitalVerificationAPI, ParamsRepairEmittedEvent, ParsedDesign, ParsedDomainContext, ParsedEmitDeclaration, ParsedEntity, ParsedEvent, ParsedListenDeclaration, ParsedOrbital, ParsedPage, ParsedState, ParsedStateMachine, ParsedTrait, ParsedTraitConfig, ParsedTransition, PatternTypeSchema, PersistActionName, PlanSnapshot, PlanSnapshotStatus, PlannerResult, Probability, ProcessCompleteEvent, ProcessErrorEvent, ProcessRepairCompleteEvent, ProcessRepairEvent, ProcessStartEvent, RepairResult, ResolvedEntityBinding, ResolvedField, ResolvedNavigation, ResolvedPattern, ResolvedSection, ResolvedSectionEvent, ResolvedTraitBinding, ResolvedTraitDataEntity, ResolvedTraitEvent, ResolvedTraitGuard, ResolvedTraitListener, ResolvedTraitState, ResolvedTraitTick, ResolvedTraitTransition, ResolvedTraitUIBinding, SSEEvent, SSEEventBase, SSEEventType, SaveOptions, SaveResult, SchemaPhaseUpdateEvent, SchemaPhaseValidatedEvent, SchemaUpdateEvent, SemanticAnnotation, SemanticChangeKind, SemanticVector, ServerResponseTrace, ServiceAction, ServiceActionName, ServiceCallResult, ServiceContract, ServiceEvents, SessionContext, SessionHistoryEntry, SnapshotCreatedEvent, SnapshotDocument, SpawnResult, StartEvent, StatsView, StoreContract, StoreFilter, StoreFilterOp, SubagentCompleteEvent, SubagentEvent, SubagentProgressEvent, SubagentStartEvent, TodoActivityType, TodoDetailEvent, TodoUpdateEvent, ToolCallEvent, ToolResultEvent, TraceContext, TraitFieldRef, TraitFieldRefSchema, TraitStateSnapshot, TransitionFrom, TransitionTrace, Unsubscribe, ValidateResult, ValidationDocument, ValidationError, ValidationErrorCode, ValidationIssue, ValidationMeta, ValidationResult, ValidationResults, VerificationCheck, VerificationSnapshot, VerificationSummary, VertexId, VertexPayload, VertexType, ViewFlow, WorkspaceContext, createEmptyResolvedPage, createEmptyResolvedTrait, createLazyService, createResolvedField, createTypedEventBus, getBindingExamples, getInteractionModelForDomain, inferTsType, isKnownValidationErrorCode, isPlanSnapshot, isResolvedIR, isSessionHistoryEntry, isTraitFieldRef, toBindingRoot, validateBindingInContext, widenTier } from './types/index.js';
8
+ export { ANONYMOUS_USER, AgentCodeSearchResult, AgentCompactResult, AgentCompactStrategy, AgentContext, AgentGenerateOptions, AgentMemoryCategory, AgentMemoryRecord, AnalysisOrbital, AnalysisOrbitalParams, AnalysisPageOverride, AnalysisRename, AnalysisResult, AnnotationTier, AppCreatedEvent, AppSummary, AssetLoadStatus, BINDING_CONTEXT_RULES, BINDING_DOCS, BINDING_ROOTS, BindingContext, BindingRoot, BindingSchema, BridgeHealth, BuilderResult, BusEvent, BusEventListener, BusEventSource, CancelledEvent, ChangeAuthor, ChangeSetDocument, ChangeSummary, ChangesetRecordedEvent, CheckStatus, Clarification, ClarificationCandidate, ClarificationLevel, CompleteEvent, ComplexityAssessment, ComposeAllResult, ComposeChildrenResult, ComposeOptions, ContextExtensions, CreateFlow, DEFAULT_INTERACTION_MODELS, DEV_TOKEN_PREFIX, DeleteFlow, DispatchUpdatesResult, EdgeType, EditFlow, EffectPayload, EffectResult, EffectTrace, ErrorEvent, EventEmit, EventKey, EventListen, EventLogEntry, EvolutionDelta, ExecutePlanResult, ExtraTraitRef, FileOperationEvent, FileWrittenEvent, GateState, GenerationLogEvent, GitHubIssue, GitHubLink, GitHubRepo, HistoryMeta, IntegrationContext, InteractionModel, InteractionModelInput, InteractionModelSchema, InterruptEvent, KNOWN_VALIDATION_ERROR_CODES, KnobPayload, KnownValidationErrorCode, LazyService, LineageEntry, ListInteraction, LivingEdge, LivingEffect, LivingEntity, LivingEvent, LivingField, LivingOrbital, LivingOrbitalSchema, LivingPage, LivingState, LivingTrait, LivingTransition, LivingValue, LivingVertex, LlmCallToolsResult, LlmContext, LlmMessage, LlmTokenUsage, LlmToolCall, LlmToolDef, LoloEmitResult, MOCK_PERSONAS, MemoryContext, MessageEvent, OrbitalAddedEvent, OrbitalSchemaCompleteEvent, OrbitalVerificationAPI, ParamsRepairEmittedEvent, ParsedDesign, ParsedDomainContext, ParsedEmitDeclaration, ParsedEntity, ParsedEvent, ParsedListenDeclaration, ParsedOrbital, ParsedPage, ParsedState, ParsedStateMachine, ParsedTrait, ParsedTraitConfig, ParsedTransition, PatternTypeSchema, PersistActionName, PlanSnapshot, PlanSnapshotStatus, PlannerResult, Probability, ProcessCompleteEvent, ProcessErrorEvent, ProcessRepairCompleteEvent, ProcessRepairEvent, ProcessStartEvent, RawUserClaims, RepairResult, ResolvedEntityBinding, ResolvedField, ResolvedNavigation, ResolvedPattern, ResolvedSection, ResolvedSectionEvent, ResolvedTraitBinding, ResolvedTraitDataEntity, ResolvedTraitEvent, ResolvedTraitGuard, ResolvedTraitListener, ResolvedTraitState, ResolvedTraitTick, ResolvedTraitTransition, ResolvedTraitUIBinding, SSEEvent, SSEEventBase, SSEEventType, SaveOptions, SaveResult, SchemaPhaseUpdateEvent, SchemaPhaseValidatedEvent, SchemaUpdateEvent, SemanticAnnotation, SemanticChangeKind, SemanticVector, ServerResponseTrace, ServiceAction, ServiceActionName, ServiceCallResult, ServiceContract, ServiceEvents, SessionContext, SessionHistoryEntry, SnapshotCreatedEvent, SnapshotDocument, SpawnResult, StartEvent, StatsView, StoreContract, StoreFilter, StoreFilterOp, SubagentCompleteEvent, SubagentEvent, SubagentProgressEvent, SubagentStartEvent, TodoActivityType, TodoDetailEvent, TodoUpdateEvent, ToolCallEvent, ToolResultEvent, TraceContext, TraitFieldRef, TraitFieldRefSchema, TraitStateSnapshot, TransitionFrom, TransitionTrace, Unsubscribe, UserContext, ValidateResult, ValidationDocument, ValidationError, ValidationErrorCode, ValidationIssue, ValidationMeta, ValidationResult, ValidationResults, VerificationCheck, VerificationSnapshot, VerificationSummary, VertexId, VertexPayload, VertexType, ViewFlow, WorkspaceContext, createEmptyResolvedPage, createEmptyResolvedTrait, createLazyService, createResolvedField, createTypedEventBus, decodeDevIdentityToken, encodeDevIdentityToken, findMockPersona, getBindingExamples, getInteractionModelForDomain, inferTsType, isKnownValidationErrorCode, isPlanSnapshot, isResolvedIR, isSessionHistoryEntry, isTraitFieldRef, normalizeUserContext, resolvePersonaSpec, toBindingRoot, validateBindingInContext, widenTier } from './types/index.js';
9
9
  import { d as TraitConfig, S as State } from './trait-X5mQAMtW.js';
10
10
  export { e as CONFIG_REF_EVENT_PATTERN, C as CallSiteConfig, b as CallSiteConfigEntry, f as ConfigFieldDeclaration, g as ConfigFieldDeclarationSchema, h as ConfigFieldItemsDeclaration, i as ConfigRefEventError, D as DeclaredTraitConfig, j as DeclaredTraitConfigSchema, E as EntityFieldContract, k as EntityFieldContractSchema, l as Event, m as EventInput, n as EventPayloadField, o as EventPayloadFieldSchema, p as EventSchema, q as EventScope, r as EventScopeSchema, G as Guard, s as GuardInput, t as GuardSchema, L as ListenSource, u as ListenSourceSchema, O as OrbitalTraitRef, v as OrbitalTraitRefSchema, P as PayloadField, w as PayloadFieldSchema, x as PresentationType, R as REFERENCE_CONFIG_TYPES, y as ReferenceConfigType, z as RequiredField, A as RequiredFieldSchema, B as StateInput, F as StateMachine, H as StateMachineInput, I as StateMachineSchema, J as StateSchema, c as Trait, K as TraitCategory, M as TraitCategorySchema, N as TraitConfigObject, Q as TraitConfigSchema, U as TraitConfigValue, V as TraitConfigValueSchema, W as TraitDataEntity, X as TraitDataEntitySchema, Y as TraitEntityField, Z as TraitEntityFieldSchema, _ as TraitEventContract, $ as TraitEventContractSchema, T as TraitEventListener, a0 as TraitEventListenerSchema, a1 as TraitInput, a2 as TraitRef, a3 as TraitRefSchema, a as TraitReference, a4 as TraitReferenceInput, a5 as TraitReferenceSchema, a6 as TraitSchema, a7 as TraitTick, a8 as TraitTickSchema, a9 as TraitUIBinding, aa as Transition, ab as TransitionInput, ac as TransitionSchema, ad as configRefEventKnob, ae as getTraitConfig, af as getTraitName, ag as isCallSiteConfigDeclaration, ah as isCircuitEvent, ai as isInlineTrait, aj as isReferenceConfigType, ak as normalizeCallSiteConfigToValues, al as normalizeTraitRef, am as resolveConfigRefEventName } from './trait-X5mQAMtW.js';
11
11
  export { F as FactoryCallSite, a as FactoryCallSiteParams, b as FactoryConfigParam, c as FactoryConfigTier, d as FactoryEntitySignature, e as FactoryEventSignature, f as FactoryExposure, g as FactoryPageSignature, h as FactoryParamValue, i as FactoryProvenance, j as FactorySignature, k as FactorySignatureCatalog, l as FactorySignatureEntityField, m as FactoryTraitSignature, J as JsonSchema, n as JsonSchemaType, O as OwnershipOverlayEntry, P as PresentationNavItem, o as PresentationOverlay, R as RuleOverlay, p as RuleOverlayEntry, S as SchemaFieldType, T as TraitOverlay, q as TraitOverlayEntry, r as TraitOverlayListener } from './types-DujRcijG.js';
@@ -487,6 +487,77 @@ type ListenPayloadEvaluator = (expr: SExpr, payload: EventPayload) => unknown;
487
487
  */
488
488
  declare function applyListenPayloadMapping(payloadMapping: Record<string, SExpr> | undefined, payload: EventPayload | undefined, evaluate: ListenPayloadEvaluator): EventPayload | undefined;
489
489
 
490
+ /**
491
+ * ML contract validation — the ONE pure implementation shared by the runtime
492
+ * path (`@almadar/evaluator`'s contract/* operators) and the compiled path
493
+ * (the TypeScript shell imports `validateContract` directly, so the two
494
+ * paths cannot drift). Mirrors `contract_helpers.py` (emitted by
495
+ * `orbital-shell-python`) semantically: same contract JSON in, same
496
+ * `{valid, violations}` out.
497
+ *
498
+ * A tensor on the JS side is a plain JSON value — a number, or (possibly
499
+ * nested) arrays of numbers — exactly what a `torch.Tensor` round-trips
500
+ * to/from via `tolist()`.
501
+ *
502
+ * @packageDocumentation
503
+ */
504
+ /** A tensor on the JS path: a number, or nested arrays of numbers. */
505
+ type TensorValue = number | TensorValue[];
506
+ /** Per-dimension range bound. Missing bounds default to +-Infinity, matching contract_helpers.py's `float("-inf")`/`float("inf")`. */
507
+ interface ContractRange {
508
+ min?: number;
509
+ max?: number;
510
+ }
511
+ interface ContractFieldSpec {
512
+ name: string;
513
+ }
514
+ type ContractFieldEntry = string | ContractFieldSpec;
515
+ /**
516
+ * Canonical contract shape (matches contract_helpers.py's dict contracts
517
+ * byte-for-byte): `shape`/`ranges` drive validate/clamp/violations, `fields`
518
+ * drives the entity<->tensor mapping. A single contract object may carry
519
+ * both halves.
520
+ */
521
+ interface ContractSpec {
522
+ shape?: number[];
523
+ ranges?: Record<string, ContractRange>;
524
+ fields?: ContractFieldEntry[];
525
+ }
526
+ interface ContractViolation {
527
+ type: 'shape_mismatch' | 'range_violation' | 'not_a_tensor';
528
+ expected?: number[];
529
+ actual?: number[];
530
+ dim?: number;
531
+ min?: number;
532
+ max?: number;
533
+ actualMin?: number;
534
+ actualMax?: number;
535
+ /** `not_a_tensor` only — what arrived instead, for diagnosis. */
536
+ actualType?: string;
537
+ }
538
+ interface ContractValidationResult {
539
+ valid: boolean;
540
+ violations: ContractViolation[];
541
+ }
542
+ declare function contractFieldName(f: ContractFieldEntry): string;
543
+ /**
544
+ * A JS-path tensor is a number or nested arrays of numbers. Model output
545
+ * arrives from an untrusted service, so every contract operator guards before
546
+ * walking it — an unguarded walk throws a bare `TypeError` three frames deep,
547
+ * which stalls the transition instead of abstaining.
548
+ */
549
+ declare function isTensorValue(v: unknown): v is TensorValue;
550
+ /** What arrived instead of a tensor, for the `not_a_tensor` violation. */
551
+ declare function describeTensorMismatch(v: unknown): string;
552
+ /** Shape of a tensor value, e.g. `[[1,2],[3,4]]` -> `[2,2]`, `[1,2,3]` -> `[3]`. */
553
+ declare function tensorShape(t: TensorValue): number[];
554
+ declare function tensorLastDimSize(t: TensorValue): number;
555
+ /** All values at index `dim` along the last axis, flattened across every leading axis — mirrors `tensor[..., dim]`. */
556
+ declare function gatherTensorLastDim(t: TensorValue, dim: number): number[];
557
+ /** Replace values at index `dim` along the last axis via `fn` — mirrors in-place `result[..., dim] = ...clamp(...)`. */
558
+ declare function mapTensorLastDim(t: TensorValue, dim: number, fn: (v: number) => number): TensorValue;
559
+ declare function validateContract(tensor: unknown, contract: ContractSpec): ContractValidationResult;
560
+
490
561
  /**
491
562
  * Schema Diffing & Protection
492
563
  *
@@ -688,4 +759,4 @@ type EntityFrameState = EntityRow;
688
759
  */
689
760
  declare function mergeEntityFrame(current: EntityFrameState, orderedWrites: readonly EntityFieldWrite[]): EntityFrameState;
690
761
 
691
- export { OrbitalSchema as AppSchema, CategorizedRemovals, ChangesetValue, type EditFocus, type EditFocusLevel, type EntityFieldWrite, type EntityFrameState, EntityRow, EventPayload, FieldValue, JsonValue, type ListenPayloadEvaluator, OrbitalDefinition, OrbitalSchema, PageContentReduction, type PatternNode, type PatternValue, type RenderOverlayResult, type RenderUiPatch, type RenderUiPatchAddress, type RenderUiPatchOp, ResolvedEntity, ResolvedIR, ResolvedPage, ResolvedTrait, SExpr, SchemaChange, type SchemaDiff, type SchemaDiffAuthor, type SchemaDiffChange, type SchemaDiffChangeset, type SchemaDiffMode, type SchemaDiffOptions, type SchemaDiffSource, type SchemaDiffSummary, SemanticSchemaChange, State, ToolArgs, type TraceActivity, type TraceActivityItem, type TraceAvatarRole, type TraceChatMessage, type TraceChatMessageToolCall, type TraceDiffHunk, type TraceDiffLine, type TraceFileOperation, type TraceSubagent, type TraceSubagentMessage, TraitConfig, OrbitalDefinition as ValidatedOrbital, applyListenPayloadMapping, applyRenderOverlay, buildResolvedTraitConfigs, categorizeRemovals, classifyWorkflow, clearSchemaCache, collectEmbeddedTraitReferrers, collectTraitConfigRefAdjacency, collectTraitEmbedAdjacency, detectPageContentReduction, diffOrbitalSchemas, diffSchemaSemantics, diffSchemas, fingerprintNode, getEntity, getPage, getPages, getRemovals, getSchemaCacheStats, getTrait, hasSignificantPageReduction, insertChildAtPath, isDestructiveChange, mergeEntityFrame, navigatePatternPath, removeChildAtPath, replaceChildAtPath, requiresConfirmation, schemaToIR, setPropAtPath, summarizeOrbital, summarizeSchema };
762
+ export { OrbitalSchema as AppSchema, CategorizedRemovals, ChangesetValue, type ContractFieldEntry, type ContractFieldSpec, type ContractRange, type ContractSpec, type ContractValidationResult, type ContractViolation, type EditFocus, type EditFocusLevel, type EntityFieldWrite, type EntityFrameState, EntityRow, EventPayload, FieldValue, JsonValue, type ListenPayloadEvaluator, OrbitalDefinition, OrbitalSchema, PageContentReduction, type PatternNode, type PatternValue, type RenderOverlayResult, type RenderUiPatch, type RenderUiPatchAddress, type RenderUiPatchOp, ResolvedEntity, ResolvedIR, ResolvedPage, ResolvedTrait, SExpr, SchemaChange, type SchemaDiff, type SchemaDiffAuthor, type SchemaDiffChange, type SchemaDiffChangeset, type SchemaDiffMode, type SchemaDiffOptions, type SchemaDiffSource, type SchemaDiffSummary, SemanticSchemaChange, State, type TensorValue, ToolArgs, type TraceActivity, type TraceActivityItem, type TraceAvatarRole, type TraceChatMessage, type TraceChatMessageToolCall, type TraceDiffHunk, type TraceDiffLine, type TraceFileOperation, type TraceSubagent, type TraceSubagentMessage, TraitConfig, OrbitalDefinition as ValidatedOrbital, applyListenPayloadMapping, applyRenderOverlay, buildResolvedTraitConfigs, categorizeRemovals, classifyWorkflow, clearSchemaCache, collectEmbeddedTraitReferrers, collectTraitConfigRefAdjacency, collectTraitEmbedAdjacency, contractFieldName, describeTensorMismatch, detectPageContentReduction, diffOrbitalSchemas, diffSchemaSemantics, diffSchemas, fingerprintNode, gatherTensorLastDim, getEntity, getPage, getPages, getRemovals, getSchemaCacheStats, getTrait, hasSignificantPageReduction, insertChildAtPath, isDestructiveChange, isTensorValue, mapTensorLastDim, mergeEntityFrame, navigatePatternPath, removeChildAtPath, replaceChildAtPath, requiresConfirmation, schemaToIR, setPropAtPath, summarizeOrbital, summarizeSchema, tensorLastDimSize, tensorShape, validateContract };
package/dist/index.js CHANGED
@@ -1923,6 +1923,75 @@ function isTraitFieldRef(value) {
1923
1923
  }
1924
1924
  var TraitFieldRefSchema = z.string().regex(TRAIT_REF_PATTERN, "expected `@trait.<TraitName>` reference");
1925
1925
 
1926
+ // src/types/user.ts
1927
+ var ANONYMOUS_USER = {
1928
+ id: "anonymous",
1929
+ role: "anonymous",
1930
+ permissions: []
1931
+ };
1932
+ var DERIVED_CLAIM_KEYS = ["id", "name", "displayName", "email"];
1933
+ function normalizeUserContext(claims) {
1934
+ if (!claims) return void 0;
1935
+ const id = claims.id ?? claims.uid;
1936
+ if (typeof id !== "string" || id.length === 0) return void 0;
1937
+ const user = { id };
1938
+ for (const [key, value] of Object.entries(claims)) {
1939
+ if (value === void 0 || DERIVED_CLAIM_KEYS.includes(key)) continue;
1940
+ user[key] = value;
1941
+ }
1942
+ const name = claims.name ?? claims.displayName;
1943
+ if (typeof name === "string" && name.length > 0) user.name = name;
1944
+ if (typeof claims.email === "string" && claims.email.length > 0) user.email = claims.email;
1945
+ return user;
1946
+ }
1947
+ var MOCK_PERSONAS = [
1948
+ { id: "admin-1", name: "Ada Admin", email: "ada@example.com", role: "admin", permissions: ["read", "write", "delete"] },
1949
+ { id: "staff-1", name: "Sam Staff", email: "sam@example.com", role: "staff", permissions: ["read", "write"] },
1950
+ { id: "member-1", name: "Maya Member", email: "maya@example.com", role: "member", permissions: ["read"] },
1951
+ { id: "customer-1", name: "Cai Customer", email: "cai@example.com", role: "customer", permissions: ["read"] }
1952
+ ];
1953
+ function findMockPersona(idOrRole) {
1954
+ return MOCK_PERSONAS.find((p) => p.id === idOrRole) ?? MOCK_PERSONAS.find((p) => p.role === idOrRole);
1955
+ }
1956
+ function resolvePersonaSpec(spec) {
1957
+ const raw = spec.trim();
1958
+ if (!raw.startsWith("{")) {
1959
+ const seeded = findMockPersona(raw);
1960
+ if (!seeded) {
1961
+ throw new Error(
1962
+ `Persona "${raw}" is not a seeded persona id or role. Known: ${MOCK_PERSONAS.map((p) => `${p.id}/${p.role}`).join(", ")}`
1963
+ );
1964
+ }
1965
+ return seeded;
1966
+ }
1967
+ let claims;
1968
+ try {
1969
+ claims = JSON.parse(raw);
1970
+ } catch {
1971
+ throw new Error(`Persona is not valid JSON: ${raw}`);
1972
+ }
1973
+ const user = normalizeUserContext(claims);
1974
+ if (!user) {
1975
+ throw new Error(`Persona needs an "id" (or "uid"): ${raw}`);
1976
+ }
1977
+ return user;
1978
+ }
1979
+ var DEV_TOKEN_PREFIX = "almadar-dev.";
1980
+ function encodeDevIdentityToken(user) {
1981
+ return DEV_TOKEN_PREFIX + encodeURIComponent(JSON.stringify(user));
1982
+ }
1983
+ function decodeDevIdentityToken(token) {
1984
+ if (!token.startsWith(DEV_TOKEN_PREFIX)) return void 0;
1985
+ try {
1986
+ const claims = JSON.parse(
1987
+ decodeURIComponent(token.slice(DEV_TOKEN_PREFIX.length))
1988
+ );
1989
+ return normalizeUserContext(claims);
1990
+ } catch {
1991
+ return void 0;
1992
+ }
1993
+ }
1994
+
1926
1995
  // src/types/agent.ts
1927
1996
  function isSessionHistoryEntry(value) {
1928
1997
  if (typeof value !== "object" || value === null) return false;
@@ -47074,6 +47143,80 @@ function applyListenPayloadMapping(payloadMapping, payload, evaluate) {
47074
47143
  return mapped;
47075
47144
  }
47076
47145
 
47146
+ // src/ml-contract.ts
47147
+ function contractFieldName(f) {
47148
+ return typeof f === "string" ? f : f.name;
47149
+ }
47150
+ function isTensorValue(v) {
47151
+ if (typeof v === "number") return true;
47152
+ return Array.isArray(v) && v.every(isTensorValue);
47153
+ }
47154
+ function describeTensorMismatch(v) {
47155
+ if (v === null) return "null";
47156
+ if (Array.isArray(v)) return "array containing non-numeric values";
47157
+ return typeof v;
47158
+ }
47159
+ function tensorShape(t) {
47160
+ if (typeof t === "number") return [];
47161
+ if (t.length === 0) return [0];
47162
+ const first = t[0];
47163
+ if (typeof first === "number") return [t.length];
47164
+ return [t.length, ...tensorShape(first)];
47165
+ }
47166
+ function tensorLastDimSize(t) {
47167
+ const shape = tensorShape(t);
47168
+ return shape.length === 0 ? 0 : shape[shape.length - 1];
47169
+ }
47170
+ function arraysEqual(a, b) {
47171
+ return a.length === b.length && a.every((v, i) => v === b[i]);
47172
+ }
47173
+ function gatherTensorLastDim(t, dim) {
47174
+ if (typeof t === "number") return [];
47175
+ if (t.length === 0) return [];
47176
+ if (typeof t[0] === "number") return [t[dim]];
47177
+ const out = [];
47178
+ for (const sub of t) out.push(...gatherTensorLastDim(sub, dim));
47179
+ return out;
47180
+ }
47181
+ function mapTensorLastDim(t, dim, fn) {
47182
+ if (typeof t === "number") return t;
47183
+ if (t.length === 0) return t;
47184
+ if (typeof t[0] === "number") {
47185
+ const copy = [...t];
47186
+ copy[dim] = fn(copy[dim]);
47187
+ return copy;
47188
+ }
47189
+ return t.map((sub) => mapTensorLastDim(sub, dim, fn));
47190
+ }
47191
+ function validateContract(tensor, contract) {
47192
+ if (!isTensorValue(tensor)) {
47193
+ return {
47194
+ valid: false,
47195
+ violations: [{ type: "not_a_tensor", actualType: describeTensorMismatch(tensor) }]
47196
+ };
47197
+ }
47198
+ const violations = [];
47199
+ const shape = tensorShape(tensor);
47200
+ if (contract.shape && !arraysEqual(shape, contract.shape)) {
47201
+ violations.push({ type: "shape_mismatch", expected: contract.shape, actual: shape });
47202
+ }
47203
+ const ranges = contract.ranges ?? {};
47204
+ const size = tensorLastDimSize(tensor);
47205
+ for (const [dimStr, bounds] of Object.entries(ranges)) {
47206
+ const dim = Number(dimStr);
47207
+ if (dim >= size) continue;
47208
+ const vals = gatherTensorLastDim(tensor, dim);
47209
+ const min = bounds.min ?? -Infinity;
47210
+ const max = bounds.max ?? Infinity;
47211
+ const actualMin = Math.min(...vals);
47212
+ const actualMax = Math.max(...vals);
47213
+ if (actualMin < min || actualMax > max) {
47214
+ violations.push({ type: "range_violation", dim, min, max, actualMin, actualMax });
47215
+ }
47216
+ }
47217
+ return { valid: violations.length === 0, violations };
47218
+ }
47219
+
47077
47220
  // src/diff.ts
47078
47221
  function diffSchemas(before, after) {
47079
47222
  const changes = [];
@@ -49240,6 +49383,6 @@ function mergeEntityFrame(current, orderedWrites) {
49240
49383
  return next;
49241
49384
  }
49242
49385
 
49243
- export { AGENT_DOMAIN_CATEGORIES, ALLOWED_CUSTOM_COMPONENTS, ANIMATION_NAMES, ASSET_ASPECTS, ASSET_DIMENSIONS, AgentDomainCategorySchema, AnimationDefSchema, AnimationNameSchema, AssetAspectSchema, AssetCatalogEntrySchema, AssetCatalogSchema, AssetDimensionSchema, AssetSchema, BINDING_CONTEXT_RULES, BINDING_DOCS, BINDING_ROOTS, BindingSchema, CAMERA_MODES, COMPONENT_MAPPING, CONFIG_REF_EVENT_PATTERN, CORE_BINDINGS, CameraModeSchema, CameraSchema, ColorSliceSchema, ColorTokensSchema, ComputedEventContractSchema, ComputedEventListenerSchema, ConfigFieldDeclarationSchema, ConfigProvenanceRecordSchema, CustomPatternDefinitionSchema, CustomPatternMapSchema, DEFAULT_INTERACTION_MODELS, DeclaredTraitConfigSchema, DensitySliceSchema, DensityTokensSchema, DesignPreferencesSchema, DesignTokensSchema, DomainCategorySchema, DomainContextSchema, DomainVocabularySchema, ENTITY_ROLES, EVENT_CONTRACTS, EffectSchema, ElevationSliceSchema, ElevationTokensSchema, EntityCallSchema, EntityFieldContractSchema, EntityFieldSchema, EntityIdSchema, EntityPersistenceSchema, EntityRefSchema, EntityRefStringSchema, EntityRoleSchema, EntitySchema, EntitySemanticRoleSchema, EventIdSchema, EventListenerSchema, EventPayloadFieldSchema, EventSchema, EventScopeSchema, EventSemanticRoleSchema, EventSourceSchema, ExpressionSchema, FieldFormatSchema, FieldSchema, FieldTypeSchema, GameSubCategorySchema, GeometrySliceSchema, GeometryTokensSchema, GuardSchema, INTEGRATORS_REGISTRY, IconFamilySchema, IconographySliceSchema, IconographyTokensSchema, IdentityLedgerSchema, IllustrationSliceSchema, IllustrationStyleSchema, IllustrationTokensSchema, InteractionModelSchema, KNOWN_VALIDATION_ERROR_CODES, LedgerEntrySchema, LedgerKindSchema, ListenSourceSchema, McpServiceDefSchema, MotionDurationKeySchema, MotionDurationPaletteSchema, MotionEasingKeySchema, MotionEasingPaletteSchema, MotionIntentMapSchema, MotionIntentSchema, MotionSliceSchema, MotionTokensSchema, NodeClassificationSchema, OrbitalConfigSchema, OrbitalDefinitionSchema, OrbitalEntitySchema, OrbitalIdSchema, OrbitalPageSchema, OrbitalPageStrictSchema, OrbitalSchemaSchema, OrbitalTraitRefSchema, OrbitalUnitSchema, OrbitalSchema as OrbitalZodSchema, PATTERN_REGISTRY, PATTERN_TYPES, PageIdSchema, PageRefObjectSchema, PageRefSchema, PageRefStringSchema, PageSchema, PageTraitRefSchema, PaletteEntryIdSchema, PatternTypeSchema, PayloadFieldSchema, REFERENCE_CONFIG_TYPES, RelatedLinkSchema, RelationConfigSchema, RequiredFieldSchema, RestAuthConfigSchema, RestServiceDefSchema, SERVICE_TYPES, SExprAtomSchema, SExprSchema, SPRITE_DIRECTIONS, ScenePosSchema, SchemaMetadataSchema, SemanticAssetRefSchema, ServiceDefinitionSchema, ServiceIdSchema, ServiceRefObjectSchema, ServiceRefSchema, ServiceRefStringSchema, ServiceTypeSchema, SkinSpecSchema, SocketEventsSchema, SocketServiceDefSchema, SpacingScaleSchema, SpriteDirectionSchema, SpriteSheetAtlasSchema, StateMachineSchema, StateSchema, StateSemanticRoleSchema, SubTextureSchema, SuggestedGuardSchema, TextureAtlasSchema, ThemeDefinitionSchema, ThemeIdSchema, ThemeRefSchema, ThemeRefStringSchema, ThemeTokensSchema, ThemeVariantSchema, TilesheetSchema, TraitCategorySchema, TraitConfigSchema, TraitConfigValueSchema, TraitDataEntitySchema, TraitEntityFieldSchema, TraitEventContractSchema, TraitEventListenerSchema, TraitFieldRefSchema, TraitIdSchema, TraitRefSchema, TraitReferenceSchema, TraitSchema, TraitTickSchema, TransitionSchema, TypeIntentMapSchema, TypeIntentSchema, TypeScaleEntrySchema, TypeScaleSchema, TypeScaleTokensSchema, TypeSizeKeySchema, TypeSliceSchema, TypeSlotSchema, TypeWeightSchema, UISlotSchema, UI_SLOTS, UXHintsSchema, UseDeclarationSchema, UserPersonaSchema, VISUAL_STYLES, ViewTypeSchema, VisualStyleSchema, answerToMutations, answersToMutations, applyEventWiring, applyFactoryCallPlanMutation, applyListenPayloadMapping, applyRenderOverlay, asEntityId, asEventId, asOrbitalId, asPageId, asPaletteEntryId, asServiceId, asThemeId, asTraitId, atomic, buildEdgeCoveringWalk, buildGuardPayloads, buildRecommendationContext, buildReplayPaths, buildResolvedTraitConfigs, buildStateGraph, callService, categorizeRemovals, classifyWorkflow, clearSchemaCache, collectBindings, collectEmbeddedTraitReferrers, collectReachableStates, collectRenderUiPatternTypes, collectTraitConfigRefAdjacency, collectTraitEmbedAdjacency, component_mapping_default as componentMapping, composeBehaviors, configRefEventKnob, constTruth, createAssetKey, createEmptyResolvedPage, createEmptyResolvedTrait, createLazyService, createResolvedField, createTypedEventBus, deref, deriveCollection, deriveInputType, despawn, detectLayoutStrategy, detectPageContentReduction, diffFactoryCalls, diffOrbitalSchemas, diffSchemaSemantics, diffSchemas, doEffects, emit, event_contracts_default as eventContracts, extractPayloadFieldRef, findCompatiblePatterns, findService, fingerprintNode, formatRecommendationsForPrompt, generatePatternDescription, generateQuestions, getAllPatternTypes, getArgs, getBindingExamples, getComponentForPattern, getDefaultAnimationsForRole, getEmittedEvents, getEntity, getEntityCardinality, getInteractionModelForDomain, getOperator, getOrbAllowedPatterns, getOrbAllowedPatternsCompact, getOrbAllowedPatternsFiltered, getOrbAllowedPatternsSlim, getPage, getPages, getPatternActionsRef, getPatternDefinition, getPatternMetadata, getPatternPropsCompact, getPatternsGroupedByCategory, getRemovals, getSchemaCacheStats, getServiceNames, getTrait, getTraitConfig, getTraitName, hasService, hasSignificantPageReduction, idKindOf, idPrefix, inferTsType, insertChildAtPath, integrators_registry_default as integratorsRegistry, isBinding, isCallSiteConfigDeclaration, isCircuitEvent, isContentBodyPattern, isContentBodyPatternType, isDestructiveChange, isDrawHostPattern, isDrawablePattern, isEffect, isEntityAwarePattern, isEntityCall, isEntityId, isEntityReference, isEntityReferenceAny, isEventId, isEventPayloadValue, isFieldValue, isImportedTraitRef, isInlineTrait, isJsonArray, isJsonObject, isJsonPrimitive, isKnownValidationErrorCode, isMainSlotRenderUi, isMcpService, isOrbitalDefinition, isOrbitalId, isPageId, isPageReference, isPageReferenceObject, isPageReferenceString, isPaletteEntryId, isPlanSnapshot, isReferenceConfigType, isResolvedIR, isRestService, isRuntimeEntity, isSExpr, isSExprAtom, isSExprCall, isSExprEffect, isServiceId, isServiceReference, isServiceReferenceObject, isSessionHistoryEntry, isSocketService, isThemeId, isThemeReference, isTraitFieldRef, isTraitId, isValidBinding, isValidPatternType, ledgerCurName, ledgerRename, ledgerResolveName, mergeEntityFrame, mintId, navigate, navigatePatternPath, normalizeCallSiteConfigToValues, normalizeTraitRef, notify, parseAssetKey, parseBinding, parseEntityRef, parseImportedTraitRef, parseOrbitalSchema, parsePageRef, parseServiceRef, patterns_registry_default as patternsRegistry, persist, persistenceModeAllowsOverrides, recommendPatterns, ref, registry, removeChildAtPath, renderUI, renderUiPatternTypesOf, replaceChildAtPath, requiresConfirmation, resolveConfigRefEventName, safeParseOrbitalSchema, schemaToIR, set, setPropAtPath, sexpr, spawn, summarizeOrbital, summarizeSchema, swap, toBindingRoot, translateOverlaysToParams, validateAssetAnimations, validateBindingInContext, walkSExpr, walkStatePairs, watch, widenTier };
49386
+ export { AGENT_DOMAIN_CATEGORIES, ALLOWED_CUSTOM_COMPONENTS, ANIMATION_NAMES, ANONYMOUS_USER, ASSET_ASPECTS, ASSET_DIMENSIONS, AgentDomainCategorySchema, AnimationDefSchema, AnimationNameSchema, AssetAspectSchema, AssetCatalogEntrySchema, AssetCatalogSchema, AssetDimensionSchema, AssetSchema, BINDING_CONTEXT_RULES, BINDING_DOCS, BINDING_ROOTS, BindingSchema, CAMERA_MODES, COMPONENT_MAPPING, CONFIG_REF_EVENT_PATTERN, CORE_BINDINGS, CameraModeSchema, CameraSchema, ColorSliceSchema, ColorTokensSchema, ComputedEventContractSchema, ComputedEventListenerSchema, ConfigFieldDeclarationSchema, ConfigProvenanceRecordSchema, CustomPatternDefinitionSchema, CustomPatternMapSchema, DEFAULT_INTERACTION_MODELS, DEV_TOKEN_PREFIX, DeclaredTraitConfigSchema, DensitySliceSchema, DensityTokensSchema, DesignPreferencesSchema, DesignTokensSchema, DomainCategorySchema, DomainContextSchema, DomainVocabularySchema, ENTITY_ROLES, EVENT_CONTRACTS, EffectSchema, ElevationSliceSchema, ElevationTokensSchema, EntityCallSchema, EntityFieldContractSchema, EntityFieldSchema, EntityIdSchema, EntityPersistenceSchema, EntityRefSchema, EntityRefStringSchema, EntityRoleSchema, EntitySchema, EntitySemanticRoleSchema, EventIdSchema, EventListenerSchema, EventPayloadFieldSchema, EventSchema, EventScopeSchema, EventSemanticRoleSchema, EventSourceSchema, ExpressionSchema, FieldFormatSchema, FieldSchema, FieldTypeSchema, GameSubCategorySchema, GeometrySliceSchema, GeometryTokensSchema, GuardSchema, INTEGRATORS_REGISTRY, IconFamilySchema, IconographySliceSchema, IconographyTokensSchema, IdentityLedgerSchema, IllustrationSliceSchema, IllustrationStyleSchema, IllustrationTokensSchema, InteractionModelSchema, KNOWN_VALIDATION_ERROR_CODES, LedgerEntrySchema, LedgerKindSchema, ListenSourceSchema, MOCK_PERSONAS, McpServiceDefSchema, MotionDurationKeySchema, MotionDurationPaletteSchema, MotionEasingKeySchema, MotionEasingPaletteSchema, MotionIntentMapSchema, MotionIntentSchema, MotionSliceSchema, MotionTokensSchema, NodeClassificationSchema, OrbitalConfigSchema, OrbitalDefinitionSchema, OrbitalEntitySchema, OrbitalIdSchema, OrbitalPageSchema, OrbitalPageStrictSchema, OrbitalSchemaSchema, OrbitalTraitRefSchema, OrbitalUnitSchema, OrbitalSchema as OrbitalZodSchema, PATTERN_REGISTRY, PATTERN_TYPES, PageIdSchema, PageRefObjectSchema, PageRefSchema, PageRefStringSchema, PageSchema, PageTraitRefSchema, PaletteEntryIdSchema, PatternTypeSchema, PayloadFieldSchema, REFERENCE_CONFIG_TYPES, RelatedLinkSchema, RelationConfigSchema, RequiredFieldSchema, RestAuthConfigSchema, RestServiceDefSchema, SERVICE_TYPES, SExprAtomSchema, SExprSchema, SPRITE_DIRECTIONS, ScenePosSchema, SchemaMetadataSchema, SemanticAssetRefSchema, ServiceDefinitionSchema, ServiceIdSchema, ServiceRefObjectSchema, ServiceRefSchema, ServiceRefStringSchema, ServiceTypeSchema, SkinSpecSchema, SocketEventsSchema, SocketServiceDefSchema, SpacingScaleSchema, SpriteDirectionSchema, SpriteSheetAtlasSchema, StateMachineSchema, StateSchema, StateSemanticRoleSchema, SubTextureSchema, SuggestedGuardSchema, TextureAtlasSchema, ThemeDefinitionSchema, ThemeIdSchema, ThemeRefSchema, ThemeRefStringSchema, ThemeTokensSchema, ThemeVariantSchema, TilesheetSchema, TraitCategorySchema, TraitConfigSchema, TraitConfigValueSchema, TraitDataEntitySchema, TraitEntityFieldSchema, TraitEventContractSchema, TraitEventListenerSchema, TraitFieldRefSchema, TraitIdSchema, TraitRefSchema, TraitReferenceSchema, TraitSchema, TraitTickSchema, TransitionSchema, TypeIntentMapSchema, TypeIntentSchema, TypeScaleEntrySchema, TypeScaleSchema, TypeScaleTokensSchema, TypeSizeKeySchema, TypeSliceSchema, TypeSlotSchema, TypeWeightSchema, UISlotSchema, UI_SLOTS, UXHintsSchema, UseDeclarationSchema, UserPersonaSchema, VISUAL_STYLES, ViewTypeSchema, VisualStyleSchema, answerToMutations, answersToMutations, applyEventWiring, applyFactoryCallPlanMutation, applyListenPayloadMapping, applyRenderOverlay, asEntityId, asEventId, asOrbitalId, asPageId, asPaletteEntryId, asServiceId, asThemeId, asTraitId, atomic, buildEdgeCoveringWalk, buildGuardPayloads, buildRecommendationContext, buildReplayPaths, buildResolvedTraitConfigs, buildStateGraph, callService, categorizeRemovals, classifyWorkflow, clearSchemaCache, collectBindings, collectEmbeddedTraitReferrers, collectReachableStates, collectRenderUiPatternTypes, collectTraitConfigRefAdjacency, collectTraitEmbedAdjacency, component_mapping_default as componentMapping, composeBehaviors, configRefEventKnob, constTruth, contractFieldName, createAssetKey, createEmptyResolvedPage, createEmptyResolvedTrait, createLazyService, createResolvedField, createTypedEventBus, decodeDevIdentityToken, deref, deriveCollection, deriveInputType, describeTensorMismatch, despawn, detectLayoutStrategy, detectPageContentReduction, diffFactoryCalls, diffOrbitalSchemas, diffSchemaSemantics, diffSchemas, doEffects, emit, encodeDevIdentityToken, event_contracts_default as eventContracts, extractPayloadFieldRef, findCompatiblePatterns, findMockPersona, findService, fingerprintNode, formatRecommendationsForPrompt, gatherTensorLastDim, generatePatternDescription, generateQuestions, getAllPatternTypes, getArgs, getBindingExamples, getComponentForPattern, getDefaultAnimationsForRole, getEmittedEvents, getEntity, getEntityCardinality, getInteractionModelForDomain, getOperator, getOrbAllowedPatterns, getOrbAllowedPatternsCompact, getOrbAllowedPatternsFiltered, getOrbAllowedPatternsSlim, getPage, getPages, getPatternActionsRef, getPatternDefinition, getPatternMetadata, getPatternPropsCompact, getPatternsGroupedByCategory, getRemovals, getSchemaCacheStats, getServiceNames, getTrait, getTraitConfig, getTraitName, hasService, hasSignificantPageReduction, idKindOf, idPrefix, inferTsType, insertChildAtPath, integrators_registry_default as integratorsRegistry, isBinding, isCallSiteConfigDeclaration, isCircuitEvent, isContentBodyPattern, isContentBodyPatternType, isDestructiveChange, isDrawHostPattern, isDrawablePattern, isEffect, isEntityAwarePattern, isEntityCall, isEntityId, isEntityReference, isEntityReferenceAny, isEventId, isEventPayloadValue, isFieldValue, isImportedTraitRef, isInlineTrait, isJsonArray, isJsonObject, isJsonPrimitive, isKnownValidationErrorCode, isMainSlotRenderUi, isMcpService, isOrbitalDefinition, isOrbitalId, isPageId, isPageReference, isPageReferenceObject, isPageReferenceString, isPaletteEntryId, isPlanSnapshot, isReferenceConfigType, isResolvedIR, isRestService, isRuntimeEntity, isSExpr, isSExprAtom, isSExprCall, isSExprEffect, isServiceId, isServiceReference, isServiceReferenceObject, isSessionHistoryEntry, isSocketService, isTensorValue, isThemeId, isThemeReference, isTraitFieldRef, isTraitId, isValidBinding, isValidPatternType, ledgerCurName, ledgerRename, ledgerResolveName, mapTensorLastDim, mergeEntityFrame, mintId, navigate, navigatePatternPath, normalizeCallSiteConfigToValues, normalizeTraitRef, normalizeUserContext, notify, parseAssetKey, parseBinding, parseEntityRef, parseImportedTraitRef, parseOrbitalSchema, parsePageRef, parseServiceRef, patterns_registry_default as patternsRegistry, persist, persistenceModeAllowsOverrides, recommendPatterns, ref, registry, removeChildAtPath, renderUI, renderUiPatternTypesOf, replaceChildAtPath, requiresConfirmation, resolveConfigRefEventName, resolvePersonaSpec, safeParseOrbitalSchema, schemaToIR, set, setPropAtPath, sexpr, spawn, summarizeOrbital, summarizeSchema, swap, tensorLastDimSize, tensorShape, toBindingRoot, translateOverlaysToParams, validateAssetAnimations, validateBindingInContext, validateContract, walkSExpr, walkStatePairs, watch, widenTier };
49244
49387
  //# sourceMappingURL=index.js.map
49245
49388
  //# sourceMappingURL=index.js.map