@almadar/core 10.58.0 → 10.59.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.
@@ -1,3095 +1,8 @@
1
- import { b3 as PageTraitRef, O as OrbitalSchema, bh as ThemeDefinition, aa as Orbital, c as Page, N as DomainContext, a as OrbitalDefinition } from '../schema-Sk_irLOY.js';
2
- export { A as AGENT_DOMAIN_CATEGORIES, f as ALLOWED_CUSTOM_COMPONENTS, g as AgentDomainCategory, h as AgentDomainCategorySchema, i as AllowedCustomComponent, C as ColorSlice, j as ColorSliceSchema, k as ColorTokens, l as ColorTokensSchema, m as ComputedEventContract, n as ComputedEventContractSchema, o as ComputedEventListener, p as ComputedEventListenerSchema, q as ConfigProvenanceRecord, r as ConfigProvenanceRecordSchema, s as CustomPatternDefinition, t as CustomPatternDefinitionInput, u as CustomPatternDefinitionSchema, v as CustomPatternMap, w as CustomPatternMapInput, x as CustomPatternMapSchema, D as DensitySlice, y as DensitySliceSchema, z as DensityTokens, B as DensityTokensSchema, F as DesignPreferences, G as DesignPreferencesInput, H as DesignPreferencesSchema, I as DesignTokens, J as DesignTokensInput, K as DesignTokensSchema, L as DomainCategory, M as DomainCategorySchema, Q as DomainContextInput, R as DomainContextSchema, S as DomainVocabulary, T as DomainVocabularySchema, V as ElevationSlice, W as ElevationSliceSchema, X as ElevationTokens, Y as ElevationTokensSchema, Z as EntityCall, _ as EntityCallSchema, E as EntityRef, $ as EntityRefSchema, a0 as EntityRefStringSchema, a1 as EntitySemanticRole, a2 as EntitySemanticRoleSchema, a3 as EventListener, a4 as EventListenerSchema, a5 as EventSemanticRole, a6 as EventSemanticRoleSchema, a7 as EventSource, a8 as EventSourceSchema, b as ExpectDeclaration, a9 as ExpectDeclarationSchema, ab as GameSubCategory, ac as GameSubCategorySchema, ad as GeometrySlice, ae as GeometrySliceSchema, af as GeometryTokens, ag as GeometryTokensSchema, ah as IconFamily, ai as IconFamilySchema, aj as IconographySlice, ak as IconographySliceSchema, al as IconographyTokens, am as IconographyTokensSchema, an as IllustrationSlice, ao as IllustrationSliceSchema, ap as IllustrationStyle, aq as IllustrationStyleSchema, ar as IllustrationTokens, as as IllustrationTokensSchema, at as MotionDurationKey, au as MotionDurationKeySchema, av as MotionDurationPalette, aw as MotionDurationPaletteSchema, ax as MotionEasingKey, ay as MotionEasingKeySchema, az as MotionEasingPalette, aA as MotionEasingPaletteSchema, aB as MotionIntent, aC as MotionIntentMap, aD as MotionIntentMapSchema, aE as MotionIntentSchema, aF as MotionSlice, aG as MotionSliceSchema, aH as MotionTokens, aI as MotionTokensSchema, aJ as NavItem, aK as NodeClassification, aL as NodeClassificationSchema, aM as OrbitalConfig, aN as OrbitalConfigInput, aO as OrbitalConfigSchema, aP as OrbitalDefinitionSchema, aQ as OrbitalInput, e as OrbitalPage, aR as OrbitalPageInput, aS as OrbitalPageSchema, aT as OrbitalPageStrictInput, aU as OrbitalPageStrictSchema, aV as OrbitalSchemaInput, aW as OrbitalSchemaSchema, aX as OrbitalSchemaWithTraits, aY as OrbitalUnit, aZ as OrbitalUnitSchema, a_ as OrbitalZodSchema, P as PageRef, d as PageRefObject, a$ as PageRefObjectSchema, b0 as PageRefSchema, b1 as PageRefStringSchema, b2 as PageSchema, b4 as PageTraitRefSchema, b5 as RelatedLink, b6 as RelatedLinkSchema, b7 as SchemaMetadata, b8 as SchemaMetadataSchema, b9 as SkinSpec, ba as SkinSpecSchema, bb as SpacingScale, bc as SpacingScaleSchema, bd as StateSemanticRole, be as StateSemanticRoleSchema, bf as SuggestedGuard, bg as SuggestedGuardSchema, bi as ThemeDefinitionSchema, bj as ThemeRef, bk as ThemeRefSchema, bl as ThemeRefStringSchema, bm as ThemeTokens, bn as ThemeTokensSchema, bo as ThemeVariant, bp as ThemeVariantSchema, bq as TypeIntent, br as TypeIntentMap, bs as TypeIntentMapSchema, bt as TypeIntentSchema, bu as TypeScale, bv as TypeScaleEntry, bw as TypeScaleEntrySchema, bx as TypeScaleSchema, by as TypeScaleTokens, bz as TypeScaleTokensSchema, bA as TypeSizeKey, bB as TypeSizeKeySchema, bC as TypeSlice, bD as TypeSliceSchema, bE as TypeSlot, bF as TypeSlotSchema, bG as TypeWeight, bH as TypeWeightSchema, bI as UXHints, bJ as UXHintsSchema, U as UseDeclaration, bK as UseDeclarationSchema, bL as UserPersona, bM as UserPersonaInput, bN as UserPersonaSchema, bO as ViewType, bP as ViewTypeSchema, bQ as isEntityCall, bR as isEntityReference, bS as isEntityReferenceAny, bT as isImportedTraitRef, bU as isOrbitalDefinition, bV as isPageReference, bW as isPageReferenceObject, bX as isPageReferenceString, bY as isThemeReference, bZ as parseEntityRef, b_ as parseImportedTraitRef, b$ as parseOrbitalSchema, c0 as parsePageRef, c1 as safeParseOrbitalSchema } from '../schema-Sk_irLOY.js';
3
- import { F as FieldValue, E as EntityField, a as EntityPersistence, bp as ServiceParams, e as Entity, f as EntityRow, A as AnyPatternConfig, O as OrbitalId, T as TraitId, b as EventId, c as Effect } from '../effect-BH2k4oK6.js';
4
- export { j as ANIMATION_NAMES, k as ASSET_ASPECTS, l as ASSET_DIMENSIONS, m as AgentEffect, n as AnimationDef, o as AnimationDefInput, p as AnimationDefSchema, q as AnimationName, r as AnimationNameSchema, s as ApplicationEffect, t as ArrayEntityField, u as Asset, v as AssetAspect, w as AssetAspectSchema, x as AssetCatalog, y as AssetCatalogEntry, z as AssetCatalogEntryInput, B as AssetCatalogEntrySchema, C as AssetCatalogSchema, D as AssetDimension, G as AssetDimensionSchema, H as AssetSchema, J as AssetUrl, K as AtomicEffect, L as BehaviorEffect, M as CAMERA_MODES, N as CallServiceConfig, Q as CallServiceEffect, V as Camera, W as CameraMode, X as CameraModeSchema, Y as CameraSchema, Z as CheckpointLoadEffect, _ as CheckpointSaveEffect, $ as ComposeEffect, a0 as DerefEffect, a1 as DespawnEffect, a2 as DoEffect, a3 as ENTITY_ROLES, a4 as EffectInput, a5 as EffectSchema, a6 as EmitConfig, a7 as EmitEffect, a8 as EntityData, a9 as EntityFieldInput, aa as EntityFieldSchema, d as EntityId, ab as EntityIdSchema, ac as EntityPersistenceSchema, ad as EntityRole, ae as EntityRoleSchema, af as EntitySchema, ag as EntityWith, ah as EnumEntityField, ai as EvaluateConfig, aj as EvaluateEffect, ak as EventIdSchema, al as FIELD_TYPES, am as FetchEffect, an as FetchOptions, ao as FetchResult, ap as Field, aq as FieldSchema, ar as FieldType, as as FieldTypeSchema, at as ForwardConfig, au as ForwardEffect, av as IdForKind, aw as IdKind, I as IdentityLedger, ax as IdentityLedgerSchema, ay as LedgerEntry, az as LedgerEntrySchema, aA as LedgerKind, aB as LedgerKindSchema, aC as LlmEffect, aD as LogEffect, aE as McpServiceDef, aF as McpServiceDefSchema, aG as MemoryEffect, aH as NavigateEffect, aI as NnConfig, aJ as NnLayer, aK as NotifyEffect, aL as ObjectEntityField, aM as OrbitalEntity, aN as OrbitalEntityInput, aO as OrbitalEntitySchema, aP as OrbitalIdSchema, aQ as OsEffect, aR as PATTERN_TYPES, P as PageId, aS as PageIdSchema, aT as PaletteEntryId, aU as PaletteEntryIdSchema, aV as PatternConfig, aY as PatternType, aZ as PersistData, a_ as PersistEffect, a$ as PersistEmitConfig, b0 as RefEffect, R as RelationConfig, b1 as RelationConfigSchema, b2 as RelationEntityField, h as RenderBinding, b3 as RenderChildrenMap, b4 as RenderItemLambda, i as RenderUIEffect, b5 as RenderUINode, b6 as ResolvedPatternProps, b7 as RestAuthConfig, b8 as RestAuthConfigSchema, b9 as RestServiceDef, ba as RestServiceDefSchema, bb as SEMANTIC_STRING_TYPES, bc as SERVICE_TYPES, bd as SHEET_PROJECTIONS, be as SPRITE_DIRECTIONS, bf as ScalarEntityField, bg as ScenePos, bh as ScenePosSchema, bi as SemanticAssetRef, bj as SemanticAssetRefInput, bk as SemanticAssetRefSchema, bl as SemanticStringType, g as ServiceDefinition, bm as ServiceDefinitionSchema, bn as ServiceId, bo as ServiceIdSchema, bq as ServiceParamsValue, S as ServiceRef, br as ServiceRefObject, bs as ServiceRefObjectSchema, bt as ServiceRefSchema, bu as ServiceRefStringSchema, bv as ServiceType, bw as ServiceTypeSchema, bx as SessionEffect, by as SetEffect, bz as SheetProjection, bA as SheetProjectionSchema, bB as SocketEvents, bC as SocketEventsSchema, bD as SocketServiceDef, bE as SocketServiceDefSchema, bF as SpawnEffect, bG as SpriteDirection, bH as SpriteDirectionSchema, bI as SpriteSheetAtlas, bJ as SpriteSheetAtlasInput, bK as SpriteSheetAtlasSchema, bL as SubTexture, bM as SubTextureSchema, bN as SwapEffect, bO as TextureAtlas, bP as TextureAtlasSchema, bQ as ThemeId, bR as ThemeIdSchema, bS as Tilesheet, bT as TilesheetSchema, bU as TraceEffect, bV as TrainConfig, bW as TrainEffect, bX as TraitIdSchema, bY as TypedEffect, U as UISlot, bZ as UISlotSchema, b_ as UI_SLOTS, b$ as VISUAL_STYLES, c0 as ValidateEffect, c1 as VisualStyle, c2 as VisualStyleSchema, c3 as WatchEffect, c4 as WatchOptions, c5 as asEntityId, c6 as asEventId, c7 as asOrbitalId, c8 as asPageId, c9 as asPaletteEntryId, ca as asServiceId, cb as asThemeId, cc as asTraitId, cd as atomic, ce as callService, cf as createAssetKey, cg as deref, ch as deriveCollection, ci as despawn, cj as doEffects, ck as emit, cl as findService, cm as getDefaultAnimationsForRole, cn as getServiceNames, co as hasService, cp as idKindOf, cq as idPrefix, cr as isEffect, cs as isEmailValue, ct as isEntityId, cu as isEventId, cv as isFieldValue, cw as isMcpService, cx as isOrbitalId, cy as isPageId, cz as isPaletteEntryId, cA as isPhoneValue, cB as isRestService, cC as isRuntimeEntity, cD as isSExprEffect, cE as isSemanticStringType, cF as isSemanticStringValue, cG as isServiceId, cH as isServiceReference, cI as isServiceReferenceObject, cJ as isSocketService, cK as isThemeId, cL as isTraitId, cM as isUrlValue, cN as isUuidValue, cO as isValidPatternType, cP as ledgerCurName, cQ as ledgerRename, cR as ledgerResolveName, cS as mintId, cT as navigate, cU as notify, cV as parseAssetKey, cW as parseServiceRef, cX as persist, cY as persistenceModeAllowsOverrides, cZ as ref, c_ as renderUI, c$ as set, d0 as spawn, d1 as swap, d2 as validateAssetAnimations, d3 as watch } from '../effect-BH2k4oK6.js';
5
- import { S as SExpr, R as RuntimeValue, d as EventPayloadValue, J as JsonValue, a as EventPayload, L as LogMeta, g as JsonObject, T as ToolArgs, c as EvalContext } from '../expression-Fk8bQWef.js';
6
- export { C as CORE_BINDINGS, b as CoreBinding, E as Expression, e as ExpressionInput, f as ExpressionSchema, h as LogMetaValue, P as ParsedBinding, i as SExprAtom, j as SExprAtomSchema, k as SExprDataSchema, l as SExprInput, m as SExprObject, n as SExprSchema, o as collectBindings, p as getArgs, q as getOperator, r as isBinding, s as isEventPayloadValue, t as isJsonArray, u as isJsonObject, v as isJsonPrimitive, w as isSExpr, x as isSExprAtom, y as isSExprCall, z as isValidBinding, A as parseBinding, B as sexpr, D as walkSExpr } from '../expression-Fk8bQWef.js';
7
- import { z } from 'zod';
8
- import { a as TraitReference, g as Trait, L as ListenSource, D as DeclaredTraitConfig, b as TraitConfig, C as ConfigFieldDeclaration, S as State, ae as Transition, r as Event, e as TraitConfigValue, Y as TraitCategory, as as TraitScope } from '../trait-Bw4nWHu1.js';
9
- export { k as CONFIG_REF_EVENT_PATTERN, h as CallSiteConfig, i as CallSiteConfigEntry, l as ConfigFieldDeclarationSchema, m as ConfigFieldItemsDeclaration, n as ConfigRefEventError, o as DeclaredTraitConfigSchema, p as EntityFieldContract, q as EntityFieldContractSchema, s as EventInput, E as EventPayloadField, t as EventPayloadFieldSchema, u as EventSchema, v as EventScope, w as EventScopeSchema, G as Guard, x as GuardInput, y as GuardSchema, z as ListenSourceSchema, O as OrbitalTraitRef, A as OrbitalTraitRefSchema, P as PayloadField, B as PayloadFieldSchema, F as PresentationType, R as REFERENCE_CONFIG_TYPES, H as ReferenceConfigType, I as RequiredField, J as RequiredFieldSchema, K as SECRET_CONFIG_TYPES, M as SecretConfigType, N as StateInput, Q as StateMachine, U as StateMachineInput, V as StateMachineSchema, W as StateSchema, X as TickIntervalSchema, Z as TraitCategorySchema, c as TraitConfigObject, _ as TraitConfigSchema, $ as TraitConfigValueSchema, a0 as TraitDataEntity, a1 as TraitDataEntitySchema, f as TraitEntityField, a2 as TraitEntityFieldSchema, j as TraitEventContract, a3 as TraitEventContractSchema, T as TraitEventListener, a4 as TraitEventListenerSchema, a5 as TraitInput, d as TraitRef, a6 as TraitRefSchema, a7 as TraitReferenceInput, a8 as TraitReferenceSchema, a9 as TraitSchema, aa as TraitTick, ab as TraitTickSchema, ac as TraitUIBinding, ad as TraitUIBindingSchema, af as TransitionInput, ag as TransitionSchema, ah as configRefEventKnob, ai as getTraitConfig, aj as getTraitName, ak as isCallSiteConfigDeclaration, al as isCircuitEvent, am as isInlineTrait, an as isReferenceConfigType, ao as isSecretConfigType, ap as normalizeCallSiteConfigToValues, aq as normalizeTraitRef, ar as resolveConfigRefEventName } from '../trait-Bw4nWHu1.js';
10
- import { T as TraitOverlay, R as RuleOverlay, J as JsonSchema, c as FactoryConfigTier } from '../types-D71hY_4A.js';
11
- import { MakeTraitRefOpts, EventWiringEntry, LayoutStrategy } from '../builders.js';
12
-
13
- /**
14
- * S-Expression Bindings
15
- *
16
- * Defines binding types and utilities for S-expression context.
17
- * Bindings are references to values that are resolved at runtime.
18
- *
19
- * Core Bindings:
20
- * - @entity - The linked entity for this trait (e.g., @entity.health)
21
- * - @payload - Event payload data (e.g., @payload.amount)
22
- * - @state - Current state machine state
23
- * - @now - Current timestamp (Date.now())
24
- *
25
- * Entity Bindings:
26
- * - @EntityName.field - Reference to singleton/runtime entity (e.g., @GameConfig.gravity)
27
- *
28
- * @packageDocumentation
29
- */
30
-
31
- /**
32
- * Schema for a binding string.
33
- * Validates that the string starts with @ and has valid format.
34
- */
35
- declare const BindingSchema: z.ZodEffects<z.ZodString, string, string>;
36
- /**
37
- * Binding documentation for LLM prompts and validation messages.
38
- *
39
- * IMPORTANT: Keep synchronized with CORE_BINDINGS in expression.ts
40
- */
41
- declare const BINDING_DOCS: {
42
- readonly entity: {
43
- readonly description: "Reference to the linked entity for this trait";
44
- readonly examples: readonly ["@entity.health", "@entity.x", "@entity.status"];
45
- readonly requiresPath: true;
46
- };
47
- readonly payload: {
48
- readonly description: "Reference to the event payload data";
49
- readonly examples: readonly ["@payload.amount", "@payload.targetId", "@payload.action"];
50
- readonly requiresPath: true;
51
- };
52
- readonly state: {
53
- readonly description: "Current state machine state name";
54
- readonly examples: readonly ["@state"];
55
- readonly requiresPath: false;
56
- };
57
- readonly now: {
58
- readonly description: "Current timestamp in milliseconds";
59
- readonly examples: readonly ["@now"];
60
- readonly requiresPath: false;
61
- };
62
- readonly config: {
63
- readonly description: "Trait configuration values";
64
- readonly examples: readonly ["@config.apiEndpoint", "@config.theme"];
65
- readonly requiresPath: true;
66
- };
67
- readonly computed: {
68
- readonly description: "Computed/calculated values";
69
- readonly examples: readonly ["@computed.total", "@computed.isValid"];
70
- readonly requiresPath: true;
71
- };
72
- readonly trait: {
73
- readonly description: "Trait context data";
74
- readonly examples: readonly ["@trait.name", "@trait.category"];
75
- readonly requiresPath: true;
76
- };
77
- readonly user: {
78
- readonly description: "Authenticated user / agent context for ownership and role-based gating";
79
- readonly examples: readonly ["@user.id", "@user.role"];
80
- readonly requiresPath: true;
81
- };
82
- readonly callsitePayload: {
83
- readonly description: "Call-site-captured event payload — emitted by the compiler's inline-trait hoisting when an extracted render block captured @payload; resolved at the composing effect by the runtime BindingResolver";
84
- readonly examples: readonly ["@callsitePayload.error", "@callsitePayload.row"];
85
- readonly requiresPath: true;
86
- };
87
- readonly pages: {
88
- readonly description: "Render-resolved schema sigil — the host orbital's pages as a NavItem[] array (href = page.path, label = page.name). Substituted from the OrbitalSchema before codegen; never survives as a live binding.";
89
- readonly examples: readonly ["@pages"];
90
- readonly requiresPath: false;
91
- };
92
- readonly currentTheme: {
93
- readonly description: "Render-resolved schema sigil — the host orbital's active data-theme key, derived from Orbital.theme. Substituted from the OrbitalSchema before codegen; never survives as a live binding.";
94
- readonly examples: readonly ["@currentTheme"];
95
- readonly requiresPath: false;
96
- };
97
- };
98
- /**
99
- * Validation rules for bindings in different contexts.
100
- */
101
- declare const BINDING_CONTEXT_RULES: {
102
- readonly guard: {
103
- readonly allowed: readonly ["entity", "payload", "state", "now", "config", "user"];
104
- readonly description: "Guards can access entity fields, event payload, current state, time, the call-site trait config (@config.X), and the authenticated user context (@user.id, @user.role) for ownership / role gates. Config access lets atoms write mode-aware guards — e.g. std-modal's OPEN can require @payload.row only when @config.mode equals \"edit\", letting create-mode legitimately fire OPEN with no row. Like effects, @config.X is substituted at molecule/organism inline time with the literal call-site value; at atom-scope validate, @config is allowed-but-unresolved.";
105
- };
106
- readonly effect: {
107
- readonly allowed: readonly ["entity", "payload", "state", "now", "trait", "config", "user", "callsitePayload", "pages", "currentTheme"];
108
- readonly description: "Effects can access and modify entity fields, use payload data, embed another trait's live frame via @trait.X inside render-ui children, read trait config values (@config.X) for atoms parameterized by their call-site, and read the authenticated user context (@user.id, @user.role). At molecule/organism inline time, @config.X is substituted with the literal value from the call-site config block; at atom-scope validate, @config is allowed-but-unresolved. @callsitePayload.X is the call-site-captured event payload emitted by the compiler's inline-trait hoisting (a hoisted render block that captured @payload); it is resolved at the composing effect by the runtime BindingResolver.";
109
- };
110
- readonly tick: {
111
- readonly allowed: readonly ["entity", "state", "now", "config", "user"];
112
- readonly description: "Ticks can access entity fields, current state, time, trait config (@config.X) for parameterized atoms, and the authenticated user context (@user.id, @user.role). Same substitution semantics as guards/effects.";
113
- };
114
- };
115
- type BindingContext = keyof typeof BINDING_CONTEXT_RULES;
116
- /**
117
- * Tag property of a `RenderBindingMarker`. `$`-prefixed so it can never
118
- * collide with a pattern prop key (prop keys are camelCase identifiers).
119
- */
120
- declare const RENDER_BINDING_MARKER: "$renderBinding";
121
- /**
122
- * A render-ui prop leaf that is evaluated at RENDER time, not at flush time.
123
- *
124
- * The interpreted path's executor carries `@entity`-dependent leaves into
125
- * slot content as these markers instead of resolving them eagerly; the
126
- * renderer (`@almadar/ui`'s SlotContentRenderer) resolves each marker
127
- * against the live entity store on every render — the same model the
128
- * compiled shell uses (state-based JSX reading `fields?.X` per React
129
- * render). Payload-dependent leaves are never deferred: `@payload` is
130
- * event-scoped and does not exist at render time.
131
- *
132
- * A `type` (not `interface`) so it carries an implicit index signature and
133
- * stays assignable to the `SExpr` record branch at guard call sites.
134
- */
135
- type RenderBindingMarker = {
136
- readonly [RENDER_BINDING_MARKER]: true;
137
- /** The raw prop expression: a binding string (`'@entity.hp'`, embedded
138
- * form `'HP: @entity.hp'`) or an S-expression tree. */
139
- readonly expression: SExpr;
140
- };
141
- /** Narrow an arbitrary prop value to a `RenderBindingMarker`. */
142
- declare function isRenderBindingMarker(value: RuntimeValue): value is RenderBindingMarker;
143
- /**
144
- * Does this raw prop expression reference `@entity` anywhere (pure binding,
145
- * embedded-binding string, nested S-expression, or object tree)? Marker
146
- * objects count as entity-referencing by construction.
147
- */
148
- declare function containsEntityBinding(value: SExpr): boolean;
149
- /**
150
- * Does this raw prop expression reference the event payload (`@payload` /
151
- * `@callsitePayload`) anywhere? Such leaves stay flush-time evaluated —
152
- * the payload does not exist at render time.
153
- */
154
- declare function containsPayloadBinding(value: SExpr): boolean;
155
- /**
156
- * Check if a binding is valid in a given context.
157
- *
158
- * @param binding - Parsed binding
159
- * @param context - Context where binding is used
160
- * @returns Error message if invalid, null if valid
161
- */
162
- declare function validateBindingInContext(binding: {
163
- type: 'core' | 'entity';
164
- root: string;
165
- }, context: BindingContext): string | null;
166
- /**
167
- * Get all valid binding examples for a context.
168
- *
169
- * @param context - Context to get examples for
170
- * @returns Array of example binding strings
171
- */
172
- declare function getBindingExamples(context: BindingContext): string[];
173
-
174
- /**
175
- * Binding root classification
176
- *
177
- * The prefix of an `@X.path` binding expression identifies which runtime
178
- * context resolves the rest of the path. This type is the TS-side mirror
179
- * of `OirBindingRoot` in `orbital-core`'s IR; publishing it from
180
- * `@almadar/core` lets the codegen, the runtime binding resolver, and
181
- * the verifier's schema walker all refer to the same narrow union.
182
- *
183
- * Distinct from {@link ParsedBinding.root} (which is a plain string): use
184
- * `BindingRoot` whenever you need exhaustiveness over the known prefixes.
185
- *
186
- * - `entity`: `@entity.field` — the trait's linked entity (first row on
187
- * the client, `getById` result on the server).
188
- * - `payload`: `@payload.x` — the last event's payload.
189
- * - `state`: `@state.x` — the state machine's `state` slot (rare;
190
- * mostly used for guard/effect contexts).
191
- * - `config`: `@config.x` — the trait ref's merged config from the
192
- * molecule call site.
193
- * - `user`: `@user.x` — authenticated user / agent context.
194
- * - `trait`: `@trait.x` — render-time reference to another trait's
195
- * mounted view. Resolved by `<TraitFrame>` at runtime, not by the
196
- * SExpression compiler.
197
- * - `item`: `@item.x` — iterator variable inside a `map` / repeat
198
- * pattern.
199
- * - `now`: `@now` — current timestamp (ISO string).
200
- * - `computed`: `@computed.x` — evaluator-computed value (Phase 4.5).
201
- * - `other`: catch-all for unknown prefixes or entity-reference
202
- * bindings (`@User.name`, `@_item`).
203
- *
204
- * @packageDocumentation
205
- */
206
-
207
- type BindingRoot = 'entity' | 'payload' | 'state' | 'config' | 'user' | 'trait' | 'item' | 'now' | 'computed' | 'other';
208
- /** Every known binding root, in a stable order — useful for exhaustiveness checks. */
209
- declare const BINDING_ROOTS: readonly BindingRoot[];
210
- /**
211
- * Narrow a raw binding-root string (e.g. the `root` field of
212
- * `ParsedBinding` from `./expression.ts`) to a `BindingRoot`. Returns
213
- * `'other'` for entity-reference roots like `@User.name` or unknown
214
- * prefixes.
215
- */
216
- declare function toBindingRoot(root: string): BindingRoot;
217
- /**
218
- * A trait reference string of the form `@trait.<TraitName>`. Used as the
219
- * value type for `trait`-typed config fields. The runtime + compiled codegen
220
- * both substitute this with embedded trait UI at render time.
221
- *
222
- * Branded as a literal-template type so TS narrows on use; consumers should
223
- * call {@link isTraitFieldRef} to validate runtime values before assignment.
224
- */
225
- type TraitFieldRef = `@trait.${string}`;
226
- /** Type guard: narrow an unknown value to {@link TraitFieldRef}. */
227
- declare function isTraitFieldRef(value: RuntimeValue): value is TraitFieldRef;
228
- /** Zod schema for {@link TraitFieldRef} values. Useful when validating analyzer
229
- * JSON or recipe overrides at runtime boundaries. */
230
- declare const TraitFieldRefSchema: z.ZodString;
231
-
232
- /**
233
- * Authenticated user context — what `@user.x` resolves against.
234
- *
235
- * The canonical shape for the `user` binding root, shared by both execution
236
- * paths: the JS interpreter resolves `@user.id` through
237
- * `EvaluationContext.user`, and the compiled shell emits `user?.id` against the
238
- * `UserContext` its `@app/shared` re-exports from here.
239
- *
240
- * `id` is the field the behavior library reads for ownership scoping and `role`
241
- * the field it reads for capability gating. Auth providers that name the subject
242
- * `uid` must normalize at their boundary — {@link normalizeUserContext} does that.
243
- *
244
- * @packageDocumentation
245
- */
246
-
247
- /** Authenticated user / agent identity behind `@user.x` bindings. */
248
- interface UserContext {
249
- /** Stable subject identifier. `@user.id` — the ownership key. */
250
- id: string;
251
- /** `@user.email` */
252
- email?: string;
253
- /** `@user.name` — display name. */
254
- name?: string;
255
- /** `@user.role` — single role string, compared against a policy's allowed list. */
256
- role?: string;
257
- /** `@user.permissions` — fine-grained capability strings. */
258
- permissions?: string[];
259
- /** Additional provider claims, readable as `@user.<claim>`. */
260
- [key: string]: FieldValue | undefined;
261
- }
262
- /**
263
- * The identity of an unauthenticated viewer. A resolvable object rather than
264
- * `undefined` so a role predicate evaluates to a definite `false` instead of
265
- * comparing against nothing.
266
- */
267
- declare const ANONYMOUS_USER: UserContext;
268
- /** Provider-shaped identity claims, before normalization. */
269
- interface RawUserClaims {
270
- id?: string;
271
- uid?: string;
272
- email?: string | null;
273
- name?: string;
274
- displayName?: string | null;
275
- role?: string;
276
- permissions?: string[];
277
- [key: string]: FieldValue | undefined;
278
- }
279
- /**
280
- * Normalize provider claims into a {@link UserContext}.
281
- *
282
- * Firebase (and most OIDC providers) name the subject `uid` and the display name
283
- * `displayName`, while every `.lolo` behavior reads `@user.id` / `@user.name`.
284
- * Without this normalization `@user.id` is `undefined` against a fully
285
- * authenticated request and every ownership filter silently matches no rows.
286
- * `uid` is preserved so `@user.uid` keeps working.
287
- *
288
- * Returns `undefined` for absent or subject-less claims so callers can
289
- * distinguish "no auth ran" from "anonymous"; use {@link ANONYMOUS_USER} where a
290
- * definite identity is required.
291
- */
292
- declare function normalizeUserContext(claims: RawUserClaims | null | undefined): UserContext | undefined;
293
- /**
294
- * Turn a row of an app's `[identity]` entity into a viewer.
295
- *
296
- * There is no separate persona shape: an identity row IS the persona
297
- * (`Almadar_LOLO_Identity.md` §4.3), so this only guards the one field the
298
- * behavior library requires — a non-empty string `id` — and passes every other
299
- * declared field through as a `@user.<field>` claim. Rows without a usable id
300
- * yield `undefined` rather than a persona nobody can own rows as.
301
- */
302
- declare function personaFromIdentityRow(row: Record<string, FieldValue | undefined>): UserContext | undefined;
303
- /**
304
- * The viewer a host presents when nothing named one.
305
- *
306
- * Without this, `@user` is `Null` in headless verify and preview, so every
307
- * `viewerName: @user.name` binding renders blank and the account menu never
308
- * appears — an app that cannot say who you are. Worse, an ownership filter that
309
- * works and one that is broken both render an empty table.
310
- *
311
- * `role` is deliberately EMPTY, not a guess. A default of `admin` would silently
312
- * flip which branch renders at the 38 `@user.role` comparisons in the corpus;
313
- * an empty role matches no literal, exactly as `Null` did, so this fixes
314
- * "undefined at runtime" without changing a single guard outcome.
315
- */
316
- declare const DEFAULT_VIEWER: UserContext;
317
- /**
318
- * The viewer to present an app as when nothing named one.
319
- *
320
- * `DEFAULT_VIEWER` is synthetic — `viewer-1` is in no app's roster — so under it
321
- * every ownership predicate (`@entity.<owner> == @user.id`) matches zero rows and
322
- * a correctly-scoped app renders empty tables everywhere. That is indistinguishable
323
- * on screen from a broken filter, which is exactly the failure DEFAULT_VIEWER's own
324
- * comment warns about.
325
- *
326
- * So when the app declares an `[identity]` roster, the default viewer is a REAL
327
- * member of it. `DEFAULT_VIEWER` remains the fallback for apps that declare no
328
- * identity entity, where there is nobody to be.
329
- *
330
- * Both execution paths share this rule; the Rust twin is
331
- * `orbital-core::runtime::persona::resolve_default_viewer`.
332
- */
333
- declare function resolveDefaultViewer(roster: readonly UserContext[]): UserContext;
334
- /** Look a persona up in a roster by id, or by role when no id matches. */
335
- declare function findPersonaInRoster(roster: readonly UserContext[], idOrRole: string): UserContext | undefined;
336
- /**
337
- * Resolve a persona spec — a bare id/role (`Person Id 3`, `moderator`) or a full
338
- * JSON `UserContext` — into a viewer. This is the `ALMADAR_PERSONA` contract,
339
- * shared by every host that presents an app as somebody.
340
- *
341
- * The roster is the app's OWN declared personas — the seeded rows of its
342
- * `[identity]` entity (`Almadar_LOLO_Identity.md` §4.3) — supplied by the host
343
- * that has them in hand (the runtime's live store on the interpreter path, the
344
- * schema-derived seed rows on the compiled path). There is no global roster:
345
- * an app without an `[identity]` entity resolves only JSON-form specs.
346
- *
347
- * Throws on anything unresolvable rather than returning `undefined`: "no persona"
348
- * and "persona silently ignored" look identical on screen, so a bad spec must
349
- * fail at boot instead of rendering as nobody.
350
- */
351
- declare function resolvePersonaSpec(spec: string, roster: readonly UserContext[]): UserContext;
352
- /**
353
- * Marks a bearer token as a mocked dev identity rather than a real ID token.
354
- * The prefix is deliberately unmistakable: a server accepts these ONLY behind an
355
- * explicit dev opt-in, so a production deployment rejects them like any other
356
- * malformed token.
357
- */
358
- declare const DEV_TOKEN_PREFIX = "almadar-dev.";
359
- /**
360
- * Encode a viewer as a dev bearer token.
361
- *
362
- * Carries the WHOLE identity, not just the subject: real Firebase claims have no
363
- * `role`, so a server that only reads `uid` leaves every `@user.role` gate inert
364
- * even for a signed-in user. URI-encoded JSON keeps the token header-safe (no
365
- * spaces or delimiters) and works unchanged in Node and the browser.
366
- */
367
- declare function encodeDevIdentityToken(user: UserContext): string;
368
- /**
369
- * Decode a dev bearer token back into a viewer, or `undefined` if it is not one
370
- * / is malformed — callers fail closed rather than inventing an identity.
371
- */
372
- declare function decodeDevIdentityToken(token: string): UserContext | undefined;
373
-
374
- /**
375
- * Validation error types — the shape emitted by every
376
- * `.orb` / `.lolo` validator pass.
377
- *
378
- * `ValidationError` is the wire shape: `{ code, path, message, suggestion? }`.
379
- * `code` is `ValidationErrorCode`, which is an OPEN `string` to let the
380
- * Rust validator emit new codes without an `@almadar/core` rev. The
381
- * `KNOWN_VALIDATION_ERROR_CODES` const documents the codes currently
382
- * emitted by the validator + lolo lower pipeline (extracted from
383
- * `orbital-rust/crates/orbital-compiler/src/phases/validation/` +
384
- * `orbital-rust/crates/orbital-lolo/src/`).
385
- *
386
- * Consumers that want to narrow a code to the closed known set use
387
- * `KnownValidationErrorCode`:
388
- *
389
- * ```ts
390
- * if (err.code in KNOWN_VALIDATION_ERROR_CODES) {
391
- * // err.code is now narrowable to KnownValidationErrorCode for
392
- * // exhaustive switch handling.
393
- * }
394
- * ```
395
- *
396
- * @packageDocumentation
397
- */
398
- /**
399
- * One validation diagnostic emitted by the validator / lolo lower pipeline.
400
- *
401
- * - `code`: machine-readable identifier (see `KNOWN_VALIDATION_ERROR_CODES`).
402
- * - `path`: JSON pointer-like path into the failing schema location,
403
- * e.g. `'orbitals[0].traits[2].stateMachine.transitions[1].effects[0]'`.
404
- * - `message`: human-readable description of the failure.
405
- * - `suggestion`: optional hint the validator may add to help the
406
- * author / LLM fix the issue.
407
- */
408
- interface ValidationError {
409
- code: ValidationErrorCode;
410
- path: string;
411
- message: string;
412
- suggestion?: string;
413
- }
414
- /**
415
- * Validation error code — open `string` for forward-compat with the
416
- * Rust validator's evolving code set. Narrow to the closed known set
417
- * via `KnownValidationErrorCode` when exhaustive handling is needed.
418
- */
419
- type ValidationErrorCode = string;
420
- /**
421
- * The result of a single validator pass: a boolean verdict plus the errors
422
- * and warnings (the validator wire shape, `ValidationError`).
423
- *
424
- * Distinct from `ValidationResults` (app.ts): that is the Firestore-persisted
425
- * app-document shape keyed on `ValidationIssue` (with `severity` + array path
426
- * + `validatedAt`). This `ValidationResult` is the in-process pass result keyed
427
- * on `ValidationError` (code + JSON-pointer string path + `suggestion`).
428
- * `ok === true` iff there are zero errors AND zero warnings.
429
- */
430
- interface ValidationResult {
431
- ok: boolean;
432
- errors: ValidationError[];
433
- warnings: ValidationError[];
434
- }
435
- /**
436
- * Closed set of validation codes the Rust validator + lolo lower
437
- * pipeline currently emit. Source-tagged: codes are extracted from
438
- * `orbital-rust/crates/orbital-compiler/src/phases/validation/**.rs`
439
- * and `orbital-rust/crates/orbital-lolo/src/**.rs`. Keep this in sync
440
- * with the Rust side; mismatches are caught by the Rust validator's
441
- * own unit tests, which assert the emitted code-set matches an
442
- * exported manifest.
443
- *
444
- * Categories (prefix → meaning):
445
- * - `ORB_BINDING_*` — binding (`@entity.X`, `@payload.Y`, ...) issues
446
- * - `ORB_E_*` / `ORB_EFF_*` / `ORB_EMIT_*` — entity / effect / emit
447
- * - `ORB_GEN_*` — generic / cross-cutting structure
448
- * - `ORB_O_*` / `ORB_P_*` / `ORB_S_*` / `ORB_SM_*` / `ORB_T_*` —
449
- * orbital / page / schema / state-machine / trait
450
- * - `ORB_QUERY_*` — query / search behaviors
451
- * - `ORB_RUI_*` — render-UI binding + prop validation
452
- * - `ORB_SLOT_*` — UI-slot conflict / contention
453
- * - `ORB_SVC_*` / `ORB_UI_*` — service / UI primitives
454
- * - `ORB_X_*` — cross-orbital constraints (listens, emits, IDs)
455
- * - `ORB_ID_*` — V4 dual-carry id integrity (unknown ref, name/kind
456
- * mismatch, ledger orphan)
457
- */
458
- declare const KNOWN_VALIDATION_ERROR_CODES: {
459
- readonly ORB_BINDING_ENTITY_FIELD_NEVER_SET: "ORB_BINDING_ENTITY_FIELD_NEVER_SET";
460
- readonly ORB_BINDING_ENTITY_FIELD_NOT_FOUND: "ORB_BINDING_ENTITY_FIELD_NOT_FOUND";
461
- readonly ORB_BINDING_INVALID_FIELD_NAME: "ORB_BINDING_INVALID_FIELD_NAME";
462
- readonly ORB_BINDING_INVALID_FORMAT: "ORB_BINDING_INVALID_FORMAT";
463
- readonly ORB_BINDING_INVALID_PATH: "ORB_BINDING_INVALID_PATH";
464
- readonly ORB_BINDING_NOW_NO_PATH: "ORB_BINDING_NOW_NO_PATH";
465
- readonly ORB_BINDING_PAYLOAD_FIELD_UNDECLARED: "ORB_BINDING_PAYLOAD_FIELD_UNDECLARED";
466
- readonly ORB_BINDING_PAYLOAD_IN_TICK: "ORB_BINDING_PAYLOAD_IN_TICK";
467
- readonly ORB_BINDING_PAYLOAD_TYPE_INCOMPATIBLE: "ORB_BINDING_PAYLOAD_TYPE_INCOMPATIBLE";
468
- readonly ORB_BINDING_SET_TARGET_MISSING_PATH: "ORB_BINDING_SET_TARGET_MISSING_PATH";
469
- readonly ORB_BINDING_STATE_NO_PATH: "ORB_BINDING_STATE_NO_PATH";
470
- readonly ORB_BINDING_TRAIT_CYCLE: "ORB_BINDING_TRAIT_CYCLE";
471
- readonly ORB_BINDING_TRAIT_INVALID_FORMAT: "ORB_BINDING_TRAIT_INVALID_FORMAT";
472
- readonly ORB_BINDING_TRAIT_INVALID_POSITION: "ORB_BINDING_TRAIT_INVALID_POSITION";
473
- readonly ORB_BINDING_TRAIT_MISSING_NAME: "ORB_BINDING_TRAIT_MISSING_NAME";
474
- readonly ORB_BINDING_TRAIT_SELF_REFERENCE: "ORB_BINDING_TRAIT_SELF_REFERENCE";
475
- readonly ORB_BINDING_TRAIT_UNKNOWN: "ORB_BINDING_TRAIT_UNKNOWN";
476
- readonly ORB_BINDING_UNKNOWN_ENTITY: "ORB_BINDING_UNKNOWN_ENTITY";
477
- readonly ORB_BINDING_UNKNOWN_ROOT: "ORB_BINDING_UNKNOWN_ROOT";
478
- readonly ORB_E_DUPLICATE_FIELD: "ORB_E_DUPLICATE_FIELD";
479
- readonly ORB_E_EMPTY_ENUM_VALUES: "ORB_E_EMPTY_ENUM_VALUES";
480
- readonly ORB_E_INVALID_FIELD_NAME: "ORB_E_INVALID_FIELD_NAME";
481
- readonly ORB_E_INVALID_FIELD_TYPE: "ORB_E_INVALID_FIELD_TYPE";
482
- readonly ORB_E_INVALID_RELATION: "ORB_E_INVALID_RELATION";
483
- readonly ORB_E_LITERAL_UNION_DEFAULT_MISMATCH: "ORB_E_LITERAL_UNION_DEFAULT_MISMATCH";
484
- readonly ORB_E_MISSING_COLLECTION: "ORB_E_MISSING_COLLECTION";
485
- readonly ORB_E_MISSING_NAME: "ORB_E_MISSING_NAME";
486
- readonly ORB_E_NO_FIELDS: "ORB_E_NO_FIELDS";
487
- readonly ORB_EFF_CALL_SERVICE_MISSING_ACTION: "ORB_EFF_CALL_SERVICE_MISSING_ACTION";
488
- readonly ORB_EFF_CALL_SERVICE_MISSING_HANDLERS: "ORB_EFF_CALL_SERVICE_MISSING_HANDLERS";
489
- readonly ORB_EFF_CALL_SERVICE_MISSING_SERVICE: "ORB_EFF_CALL_SERVICE_MISSING_SERVICE";
490
- readonly ORB_EFF_EMIT_INVALID_NAME: "ORB_EFF_EMIT_INVALID_NAME";
491
- readonly ORB_EFF_EMIT_KEY_INVALID: "ORB_EFF_EMIT_KEY_INVALID";
492
- readonly ORB_EFF_EMIT_UNDECLARED_EVENT: "ORB_EFF_EMIT_UNDECLARED_EVENT";
493
- readonly ORB_EFF_FETCH_INVALID_ENTITY: "ORB_EFF_FETCH_INVALID_ENTITY";
494
- readonly ORB_EFF_FETCH_INVALID_INCLUDE: "ORB_EFF_FETCH_INVALID_INCLUDE";
495
- readonly ORB_EFF_MISSING_FETCH_FOR_ENTITY: "ORB_EFF_MISSING_FETCH_FOR_ENTITY";
496
- readonly ORB_EFF_MISSING_REQUIRED_EMIT: "ORB_EFF_MISSING_REQUIRED_EMIT";
497
- readonly ORB_EFF_NAVIGATE_MISSING_PAYLOAD: "ORB_EFF_NAVIGATE_MISSING_PAYLOAD";
498
- readonly ORB_EFF_NAVIGATE_TARGET_UNREACHABLE: "ORB_EFF_NAVIGATE_TARGET_UNREACHABLE";
499
- readonly ORB_EFF_SET_INVALID_BINDING: "ORB_EFF_SET_INVALID_BINDING";
500
- readonly ORB_EFF_SET_PAYLOAD_NOT_ALLOWED: "ORB_EFF_SET_PAYLOAD_NOT_ALLOWED";
501
- readonly ORB_EFF_SLOT_CONFLICT: "ORB_EFF_SLOT_CONFLICT";
502
- readonly ORB_EFF_UNKNOWN_TYPE: "ORB_EFF_UNKNOWN_TYPE";
503
- readonly ORB_EMIT_DECLARED_BUT_UNFIRED: "ORB_EMIT_DECLARED_BUT_UNFIRED";
504
- readonly ORB_EMIT_PAYLOAD_EXTRA_FIELD: "ORB_EMIT_PAYLOAD_EXTRA_FIELD";
505
- readonly ORB_EMIT_PAYLOAD_FIELD_TYPE_MISMATCH: "ORB_EMIT_PAYLOAD_FIELD_TYPE_MISMATCH";
506
- readonly ORB_EMIT_PAYLOAD_MISSING_REQUIRED: "ORB_EMIT_PAYLOAD_MISSING_REQUIRED";
507
- readonly ORB_EMIT_SUCCESS_PAYLOAD_RETURN_MISMATCH: "ORB_EMIT_SUCCESS_PAYLOAD_RETURN_MISMATCH";
508
- readonly ORB_GEN_DUPLICATE: "ORB_GEN_DUPLICATE";
509
- readonly ORB_GEN_INVALID_REFERENCE: "ORB_GEN_INVALID_REFERENCE";
510
- readonly ORB_GEN_INVALID_VALUE: "ORB_GEN_INVALID_VALUE";
511
- readonly ORB_GEN_MISSING_FIELD: "ORB_GEN_MISSING_FIELD";
512
- readonly ORB_O_MISSING_PAGES: "ORB_O_MISSING_PAGES";
513
- readonly ORB_P_DUPLICATE_PATH: "ORB_P_DUPLICATE_PATH";
514
- readonly ORB_P_EMPTY_TRAITS: "ORB_P_EMPTY_TRAITS";
515
- readonly ORB_P_INVALID_PATH: "ORB_P_INVALID_PATH";
516
- readonly ORB_P_INVALID_TRAIT_REF: "ORB_P_INVALID_TRAIT_REF";
517
- readonly ORB_P_INVALID_VIEW_TYPE: "ORB_P_INVALID_VIEW_TYPE";
518
- readonly ORB_P_MISSING_NAME: "ORB_P_MISSING_NAME";
519
- readonly ORB_P_MISSING_PATH: "ORB_P_MISSING_PATH";
520
- readonly ORB_P_MISSING_TRAITS: "ORB_P_MISSING_TRAITS";
521
- readonly ORB_P_SECTIONS_FORBIDDEN: "ORB_P_SECTIONS_FORBIDDEN";
522
- readonly ORB_QUERY_MISSING_RECOMMENDED: "ORB_QUERY_MISSING_RECOMMENDED";
523
- readonly ORB_QUERY_MISSING_SEARCH: "ORB_QUERY_MISSING_SEARCH";
524
- readonly ORB_QUERY_UNKNOWN_SINGLETON: "ORB_QUERY_UNKNOWN_SINGLETON";
525
- readonly ORB_QUERY_UNSUPPORTED_PATTERN: "ORB_QUERY_UNSUPPORTED_PATTERN";
526
- readonly ORB_QUERY_UNUSED_SINGLETON: "ORB_QUERY_UNUSED_SINGLETON";
527
- readonly ORB_RUI_BINDING_TYPE_MISMATCH: "ORB_RUI_BINDING_TYPE_MISMATCH";
528
- readonly ORB_RUI_ELEMENT_SHAPE_MISMATCH: "ORB_RUI_ELEMENT_SHAPE_MISMATCH";
529
- readonly ORB_RUI_EVENT_BINDING_PAYLOAD_MISMATCH: "ORB_RUI_EVENT_BINDING_PAYLOAD_MISMATCH";
530
- readonly ORB_RUI_INVALID_FIELD_PATH: "ORB_RUI_INVALID_FIELD_PATH";
531
- readonly ORB_RUI_INVALID_ITEM_ACTION: "ORB_RUI_INVALID_ITEM_ACTION";
532
- readonly ORB_RUI_INVALID_PATTERN: "ORB_RUI_INVALID_PATTERN";
533
- readonly ORB_RUI_INVALID_PROP: "ORB_RUI_INVALID_PROP";
534
- readonly ORB_RUI_INVALID_SLOT: "ORB_RUI_INVALID_SLOT";
535
- readonly ORB_RUI_MISSING_ACTION: "ORB_RUI_MISSING_ACTION";
536
- readonly ORB_RUI_MISSING_PATTERN_TYPE: "ORB_RUI_MISSING_PATTERN_TYPE";
537
- readonly ORB_RUI_MISSING_REQUIRED_PROP: "ORB_RUI_MISSING_REQUIRED_PROP";
538
- readonly ORB_RUI_PROP_TYPE_MISMATCH: "ORB_RUI_PROP_TYPE_MISMATCH";
539
- readonly ORB_RUI_UNKNOWN_ITEM_ACTION_PROP: "ORB_RUI_UNKNOWN_ITEM_ACTION_PROP";
540
- readonly ORB_S_EMPTY_VERSION: "ORB_S_EMPTY_VERSION";
541
- readonly ORB_S_MISSING_NAME: "ORB_S_MISSING_NAME";
542
- readonly ORB_S_NO_ORBITALS: "ORB_S_NO_ORBITALS";
543
- readonly ORB_SLOT_CONTENTION: "ORB_SLOT_CONTENTION";
544
- readonly ORB_SLOT_CONTENTION_RUNTIME: "ORB_SLOT_CONTENTION_RUNTIME";
545
- readonly ORB_SLOT_HUD_NON_GAME: "ORB_SLOT_HUD_NON_GAME";
546
- readonly ORB_SLOT_INVALID_NAME: "ORB_SLOT_INVALID_NAME";
547
- readonly ORB_SLOT_INVALID_NESTING: "ORB_SLOT_INVALID_NESTING";
548
- readonly ORB_SLOT_MAIN_NOT_COVERED: "ORB_SLOT_MAIN_NOT_COVERED";
549
- readonly ORB_SLOT_PRIORITY_CONFLICT: "ORB_SLOT_PRIORITY_CONFLICT";
550
- readonly ORB_SVC_DUPLICATE_NAME: "ORB_SVC_DUPLICATE_NAME";
551
- readonly ORB_SVC_INVALID_INTEGRATOR: "ORB_SVC_INVALID_INTEGRATOR";
552
- readonly ORB_SVC_INVALID_URL: "ORB_SVC_INVALID_URL";
553
- readonly ORB_SVC_MISSING_BASE_URL: "ORB_SVC_MISSING_BASE_URL";
554
- readonly ORB_SVC_MISSING_CAPABILITIES: "ORB_SVC_MISSING_CAPABILITIES";
555
- readonly ORB_SVC_MISSING_EVENTS: "ORB_SVC_MISSING_EVENTS";
556
- readonly ORB_SVC_MISSING_SERVER_PATH: "ORB_SVC_MISSING_SERVER_PATH";
557
- readonly ORB_SVC_RESERVED_EVENT: "ORB_SVC_RESERVED_EVENT";
558
- readonly ORB_SVC_UNKNOWN_TYPE: "ORB_SVC_UNKNOWN_TYPE";
559
- readonly ORB_T_CONFIG_OBJECT_ARRAY_FORBIDDEN: "ORB_T_CONFIG_OBJECT_ARRAY_FORBIDDEN";
560
- readonly ORB_T_CONFIG_SHAPE_MISMATCH: "ORB_T_CONFIG_SHAPE_MISMATCH";
561
- readonly ORB_T_CONFIG_TIER_INVALID: "ORB_T_CONFIG_TIER_INVALID";
562
- readonly ORB_T_DEPRECATED_UI: "ORB_T_DEPRECATED_UI";
563
- readonly ORB_T_DUPLICATE_NAME: "ORB_T_DUPLICATE_NAME";
564
- readonly ORB_T_DUPLICATE_STATE: "ORB_T_DUPLICATE_STATE";
565
- readonly ORB_T_DUPLICATE_TRANSITION: "ORB_T_DUPLICATE_TRANSITION";
566
- readonly ORB_T_ENTITY_NAME_SHADOWS_TRAIT_UNION: "ORB_T_ENTITY_NAME_SHADOWS_TRAIT_UNION";
567
- readonly ORB_T_EVENT_TYPE_WRONG_KIND: "ORB_T_EVENT_TYPE_WRONG_KIND";
568
- readonly ORB_T_EVT_DUPLICATE: "ORB_T_EVT_DUPLICATE";
569
- readonly ORB_T_EVT_EXTERNAL_MISSING_PAYLOAD: "ORB_T_EVT_EXTERNAL_MISSING_PAYLOAD";
570
- readonly ORB_T_EVT_INVALID_NAME: "ORB_T_EVT_INVALID_NAME";
571
- readonly ORB_T_EVT_SCOPE_MISMATCH: "ORB_T_EVT_SCOPE_MISMATCH";
572
- readonly ORB_T_EVT_TICK_UNDECLARED: "ORB_T_EVT_TICK_UNDECLARED";
573
- readonly ORB_T_EVT_UNDECLARED: "ORB_T_EVT_UNDECLARED";
574
- readonly ORB_T_INIT_MISSING_FETCH: "ORB_T_INIT_MISSING_FETCH";
575
- readonly ORB_T_INVALID_CATEGORY: "ORB_T_INVALID_CATEGORY";
576
- readonly ORB_T_INVALID_FORMAT: "ORB_T_INVALID_FORMAT";
577
- readonly ORB_T_INVALID_PATTERN_DEFAULT: "ORB_T_INVALID_PATTERN_DEFAULT";
578
- readonly ORB_T_INVALID_SLOT_DEFAULT: "ORB_T_INVALID_SLOT_DEFAULT";
579
- readonly ORB_T_INVALID_TRANSITION: "ORB_T_INVALID_TRANSITION";
580
- readonly ORB_T_MISSING_INIT_TRANSITION: "ORB_T_MISSING_INIT_TRANSITION";
581
- readonly ORB_T_MISSING_RENDER_UI: "ORB_T_MISSING_RENDER_UI";
582
- readonly ORB_T_MULTIPLE_INITIAL_STATES: "ORB_T_MULTIPLE_INITIAL_STATES";
583
- readonly ORB_T_NO_INITIAL_STATE: "ORB_T_NO_INITIAL_STATE";
584
- readonly ORB_T_TYPE_ANNOTATION_MISMATCH: "ORB_T_TYPE_ANNOTATION_MISMATCH";
585
- readonly ORB_T_TYPE_COMPOSITION_CONFLICT: "ORB_T_TYPE_COMPOSITION_CONFLICT";
586
- readonly ORB_T_TYPE_CYCLE: "ORB_T_TYPE_CYCLE";
587
- readonly ORB_T_TYPE_KIND_MISMATCH: "ORB_T_TYPE_KIND_MISMATCH";
588
- readonly ORB_T_TYPE_UNKNOWN: "ORB_T_TYPE_UNKNOWN";
589
- readonly ORB_T_TYPE_UNKNOWN_PARAM: "ORB_T_TYPE_UNKNOWN_PARAM";
590
- readonly ORB_T_TYPE_WRONG_ARG_COUNT: "ORB_T_TYPE_WRONG_ARG_COUNT";
591
- readonly ORB_T_UNDEFINED_EVENT: "ORB_T_UNDEFINED_EVENT";
592
- readonly ORB_T_UNDEFINED_TRAIT: "ORB_T_UNDEFINED_TRAIT";
593
- readonly ORB_UI_ICON_EMPTY: "ORB_UI_ICON_EMPTY";
594
- readonly ORB_UI_ICON_INVALID_FORMAT: "ORB_UI_ICON_INVALID_FORMAT";
595
- readonly ORB_UI_ICON_NOT_FOUND: "ORB_UI_ICON_NOT_FOUND";
596
- readonly ORB_X_CIRCULAR_DEPENDENCY: "ORB_X_CIRCULAR_DEPENDENCY";
597
- readonly ORB_X_CROSS_EMITTER_DECLARED_PAYLOAD_MISMATCH: "ORB_X_CROSS_EMITTER_DECLARED_PAYLOAD_MISMATCH";
598
- readonly ORB_X_DUPLICATE_ENTITY: "ORB_X_DUPLICATE_ENTITY";
599
- readonly ORB_X_EVENT_COLLISION: "ORB_X_EVENT_COLLISION";
600
- readonly ORB_X_INTERNAL_EVENT_EXPOSED: "ORB_X_INTERNAL_EVENT_EXPOSED";
601
- readonly ORB_X_LISTEN_SOURCE_UNRESOLVED: "ORB_X_LISTEN_SOURCE_UNRESOLVED";
602
- readonly ORB_X_MISSING_ORBITAL_NAME: "ORB_X_MISSING_ORBITAL_NAME";
603
- readonly ORB_X_ORPHAN_LISTENER: "ORB_X_ORPHAN_LISTENER";
604
- readonly ORB_X_PAYLOAD_MISMATCH: "ORB_X_PAYLOAD_MISMATCH";
605
- readonly ORB_X_RENDER_UI_EVENT_LITERAL_STALE: "ORB_X_RENDER_UI_EVENT_LITERAL_STALE";
606
- readonly ORB_X_UNRESOLVED_PATTERN_FIELD_REF: "ORB_X_UNRESOLVED_PATTERN_FIELD_REF";
607
- readonly ORB_X_UNUSED_EMISSION: "ORB_X_UNUSED_EMISSION";
608
- readonly ORB_ID_UNKNOWN_REF: "ORB_ID_UNKNOWN_REF";
609
- readonly ORB_ID_NAME_MISMATCH: "ORB_ID_NAME_MISMATCH";
610
- readonly ORB_ID_KIND_MISMATCH: "ORB_ID_KIND_MISMATCH";
611
- readonly ORB_ID_LEDGER_ORPHAN: "ORB_ID_LEDGER_ORPHAN";
612
- };
613
- /**
614
- * Narrow union of the codes documented in `KNOWN_VALIDATION_ERROR_CODES`.
615
- * Use this in exhaustive `switch` handlers; use the broader
616
- * `ValidationErrorCode` (open `string`) anywhere a fresh validator-side
617
- * code could plausibly arrive.
618
- */
619
- type KnownValidationErrorCode = typeof KNOWN_VALIDATION_ERROR_CODES[keyof typeof KNOWN_VALIDATION_ERROR_CODES];
620
- /**
621
- * Type guard: is the given code a known one? After the guard returns
622
- * true, the code can be narrowed to `KnownValidationErrorCode` via a
623
- * separate cast, because the type system can't track `in` against
624
- * `as const` records without an explicit narrowing helper.
625
- */
626
- declare function isKnownValidationErrorCode(code: ValidationErrorCode): boolean;
627
-
628
- /**
629
- * Plan & Analysis Types
630
- *
631
- * Lifted from @almadar-io/rabit's coordinator types. These are the
632
- * language-level contracts for the planner/analysis pipeline — the
633
- * session/* and workspace/* substrate operators produce and consume
634
- * these shapes. Defined here (not in rabit) so both the compiled path
635
- * (orbital-rust codegen → @almadar/server) and the interpreted path
636
- * (@almadar/runtime) reference the same types without depending on rabit.
637
- *
638
- * @packageDocumentation
639
- */
640
-
641
- type ClarificationLevel = 'organism' | 'molecule' | 'atom_trait';
642
- interface ClarificationCandidate {
643
- id: string;
644
- label: string;
645
- description: string;
646
- whyThisFits: string;
647
- }
648
- interface Clarification {
649
- level: ClarificationLevel;
650
- scope: {
651
- orbitalName?: string;
652
- traitName?: string;
653
- };
654
- question: string;
655
- candidates: ClarificationCandidate[];
656
- skipDefault: string;
657
- skippable: true;
658
- }
659
- interface AnalysisPageOverride {
660
- name: string;
661
- path?: string;
662
- linkedEntity?: string;
663
- traits?: PageTraitRef[];
664
- }
665
- interface ExtraTraitRef extends Pick<TraitReference, 'ref' | 'name' | 'linkedEntity' | 'config' | 'events' | 'listens' | 'emitsScope'> {
666
- from: string;
667
- as: string;
668
- }
669
- interface AnalysisOrbitalParams {
670
- fields?: EntityField[];
671
- pagePath?: string;
672
- persistence?: EntityPersistence;
673
- entityName?: string;
674
- collection?: string;
675
- traitOverrides?: Record<string, Pick<MakeTraitRefOpts, 'config' | 'linkedEntity' | 'events' | 'name' | 'emitsScope' | 'listens'>>;
676
- extraTraits?: ExtraTraitRef[];
677
- pages?: AnalysisPageOverride[];
678
- }
679
- interface AnalysisOrbital {
680
- orbitalName: string;
681
- suggestedBehavior: string | null;
682
- entityName?: string;
683
- pageNames?: ReadonlyArray<string>;
684
- params?: AnalysisOrbitalParams;
685
- traitOverlay?: TraitOverlay;
686
- paletteTopics?: string[];
687
- primitiveHints?: string[];
688
- }
689
- interface AnalysisRename {
690
- oldName: string;
691
- newName: string;
692
- }
693
- interface ComplexityAssessment {
694
- score: number;
695
- category: 'simple' | 'moderate' | 'complex';
696
- reasoning: string;
697
- detectedEntities?: string[];
698
- detectedFeatures?: string[];
699
- }
700
- interface AnalysisResult {
701
- userRequest: string;
702
- complexity: ComplexityAssessment;
703
- route: 'direct' | 'direct_with_questions' | 'decompose';
704
- organism: string;
705
- appName: string;
706
- organismReason: string;
707
- orbitals: AnalysisOrbital[];
708
- renames?: AnalysisRename[];
709
- deletedOrbitals?: string[];
710
- ruleOverlay?: RuleOverlay;
711
- estimatedMinutes?: number;
712
- schema: OrbitalSchema;
713
- wiring?: EventWiringEntry[];
714
- layout?: LayoutStrategy | 'detect';
715
- themeOverrides?: Partial<ThemeDefinition>;
716
- pendingClarifications?: Clarification[];
717
- }
718
- interface SpawnResult {
719
- orbitalName: string;
720
- ok: boolean;
721
- traitNames: ReadonlyArray<string>;
722
- error?: string;
723
- durationMs: number;
724
- }
725
- type PlanSnapshotStatus = 'proposed' | 'confirmed' | 'built' | 'failed';
726
- interface PlanSnapshot {
727
- schemaVersion: 1;
728
- status: PlanSnapshotStatus;
729
- builtAt: string;
730
- organism: string | null;
731
- appName: string | null;
732
- organismReason: string | null;
733
- complexity: ComplexityAssessment | null;
734
- themeOverrides: Partial<ThemeDefinition>;
735
- ruleOverlay: RuleOverlay | null;
736
- orbitals: ReadonlyArray<AnalysisOrbital>;
737
- renames: ReadonlyArray<AnalysisRename>;
738
- deletedOrbitals: ReadonlyArray<string>;
739
- priorBuiltOrbitals: ReadonlyArray<AnalysisOrbital>;
740
- spawnedOrbitalResults: ReadonlyArray<SpawnResult>;
741
- skippedOrbitalNames: ReadonlyArray<string>;
742
- pendingClarifications: ReadonlyArray<Clarification>;
743
- paletteTopics?: string[];
744
- }
745
- /**
746
- * Runtime guard for `PlanSnapshot` — narrows interpreter-produced `unknown`
747
- * values at the `WorkspaceContext.writePlan` boundary. Discriminates on the
748
- * snapshot envelope (schemaVersion, status, roster arrays), not deep contents.
749
- */
750
- declare function isPlanSnapshot(value: RuntimeValue): value is PlanSnapshot;
751
- interface ComposeOptions {
752
- appName?: string;
753
- wiring?: EventWiringEntry[];
754
- layout?: LayoutStrategy | 'auto';
755
- themeOverrides?: Partial<ThemeDefinition>;
756
- }
757
- interface GitHubRepo {
758
- id: number;
759
- name: string;
760
- full_name: string;
761
- owner: {
762
- login: string;
763
- };
764
- private: boolean;
765
- html_url: string;
766
- description: string | null;
767
- default_branch: string;
768
- clone_url: string;
769
- }
770
- interface GitHubIssue {
771
- id: number;
772
- number: number;
773
- title: string;
774
- body: string | null;
775
- state: 'open' | 'closed';
776
- html_url: string;
777
- user: {
778
- login: string;
779
- };
780
- created_at: string;
781
- updated_at: string;
782
- }
783
-
784
- /**
785
- * Agent Types
786
- *
787
- * Defines the AgentContext interface and related types for the agent/* operator namespace.
788
- * These types are the contract between operators (language) and implementation (runtime).
789
- *
790
- * @packageDocumentation
791
- */
792
-
793
- /**
794
- * Categories for agent memories.
795
- */
796
- type AgentMemoryCategory = 'preference' | 'correction' | 'pattern-affinity' | 'entity-template' | 'error-resolution';
797
- /**
798
- * A single memory record stored by the agent.
799
- */
800
- interface AgentMemoryRecord {
801
- /** Unique memory identifier */
802
- id: string;
803
- /** Memory content (natural language) */
804
- content: string;
805
- /** Memory category */
806
- category: AgentMemoryCategory;
807
- /** Strength value (0.0-1.0), decays over time unless pinned */
808
- strength: number;
809
- /** Whether this memory is pinned (immune to decay) */
810
- pinned: boolean;
811
- /** Memory scope */
812
- scope: 'global' | 'project';
813
- /** ISO timestamp of last access */
814
- lastAccessedAt: string;
815
- /** ISO timestamp of creation */
816
- createdAt: string;
817
- }
818
- /**
819
- * Strategy for context compaction.
820
- */
821
- type AgentCompactStrategy = 'hybrid' | 'summarize' | 'truncate' | 'extract';
822
- /**
823
- * Result of a context compaction operation.
824
- */
825
- interface AgentCompactResult {
826
- /** Token count before compaction */
827
- before: number;
828
- /** Token count after compaction */
829
- after: number;
830
- /** Strategy used */
831
- strategy: AgentCompactStrategy;
832
- /** Optional summary generated during compaction */
833
- summary?: string;
834
- }
835
- /**
836
- * Options for agent/generate calls.
837
- */
838
- interface AgentGenerateOptions {
839
- /** LLM provider override */
840
- provider?: string;
841
- /** Model override */
842
- model?: string;
843
- /** Maximum tokens to generate */
844
- maxTokens?: number;
845
- }
846
- /**
847
- * A message in an LLM tool-calling conversation.
848
- */
849
- interface LlmMessage {
850
- role: 'system' | 'user' | 'assistant' | 'tool';
851
- content: string;
852
- /** Present on assistant messages that called tools. */
853
- toolCalls?: ReadonlyArray<LlmToolCall>;
854
- /** Present on tool-role messages — matches the preceding toolCall's id. */
855
- toolCallId?: string;
856
- }
857
- /**
858
- * A tool call requested by the assistant.
859
- */
860
- interface LlmToolCall {
861
- id: string;
862
- name: string;
863
- /** JSON-encoded arguments string (as returned by the LLM). */
864
- arguments: string;
865
- }
866
- /**
867
- * A tool definition passed to llm/call-tools.
868
- */
869
- interface LlmToolDef {
870
- name: string;
871
- description: string;
872
- /** JSON Schema describing the tool's parameters. */
873
- parameters: JsonSchema;
874
- }
875
- /**
876
- * Result of llm/call-tools.
877
- */
878
- interface LlmCallToolsResult {
879
- /** The assistant's text response (may be empty when only tool_calls fired). */
880
- content: string;
881
- /** Tool calls the assistant requested, if any. */
882
- toolCalls?: ReadonlyArray<LlmToolCall>;
883
- /** Token usage from the call. */
884
- usage: LlmTokenUsage;
885
- }
886
- /**
887
- * Token usage from an LLM call.
888
- */
889
- interface LlmTokenUsage {
890
- prompt: number;
891
- completion: number;
892
- total: number;
893
- }
894
- /**
895
- * Result from agent/search-code.
896
- */
897
- interface AgentCodeSearchResult {
898
- /** Repository name (owner/repo) */
899
- repo: string;
900
- /** File path within the repository */
901
- path: string;
902
- /** URL to the file */
903
- url: string;
904
- }
905
- /** Result of behavior/instantiate (factory path) or subagent build. */
906
- interface BuilderResult {
907
- method: string;
908
- orbitalName: string;
909
- success: boolean;
910
- orbitalPath?: string;
911
- traitCount?: number;
912
- traitNames?: string[];
913
- transitionCount?: number;
914
- childCount?: number;
915
- error?: string;
916
- }
917
- /** Result of validate/validate for a single orbital or the composed schema. */
918
- interface ValidateResult {
919
- valid: boolean;
920
- errorCount: number;
921
- errors: ValidationError[];
922
- orbitalName?: string;
923
- }
924
- /** Result of compose/compose-all. */
925
- interface ComposeAllResult {
926
- orbitalCount: number;
927
- composedPath: string;
928
- success: boolean;
929
- layout?: string;
930
- wiringConnections?: number;
931
- }
932
- /** Result of compose/compose-children (recursive builds). */
933
- interface ComposeChildrenResult {
934
- parentName: string;
935
- childCount: number;
936
- orbitalName: string;
937
- success: boolean;
938
- }
939
- /** Result of the repair service. */
940
- interface RepairResult {
941
- orbitalName: string;
942
- success: boolean;
943
- attempt: number;
944
- paramsChanged: boolean;
945
- error?: string;
946
- }
947
- /** Result of lolo/emit-body (free-lolo path). */
948
- interface LoloEmitResult {
949
- orbitalName: string;
950
- success: boolean;
951
- loloSource: string;
952
- error?: string;
953
- }
954
- /** Result of the planner service. */
955
- interface PlannerResult {
956
- organism: string;
957
- operationCount: number;
958
- pendingQuestions: boolean;
959
- cached: boolean;
960
- success: boolean;
961
- error?: string;
962
- }
963
- /** Result of the executor (spawn-subagents). */
964
- interface ExecutePlanResult {
965
- dispatchedOrbitals: string[];
966
- noopForBuild: boolean;
967
- success: boolean;
968
- error?: string;
969
- }
970
- /** Result of dispatch-updates. */
971
- interface DispatchUpdatesResult {
972
- updatedOrbitals: string[];
973
- updateCount: number;
974
- success: boolean;
975
- }
976
- /** Discriminated union of all substrate service-call results. */
977
- type ServiceCallResult = BuilderResult | ValidateResult | ComposeAllResult | ComposeChildrenResult | RepairResult | LoloEmitResult | PlannerResult | ExecutePlanResult | DispatchUpdatesResult;
978
- /** A single entry in an orbital's session history (build/conversation log). */
979
- interface SessionHistoryEntry {
980
- /** Role of the entry's author (e.g. 'user', 'assistant', 'system') */
981
- role: string;
982
- /** Entry content (natural language or structured description) */
983
- content: string;
984
- /** Epoch milliseconds when the entry was recorded */
985
- timestamp: number;
986
- }
987
- /**
988
- * Runtime guard for `SessionHistoryEntry` — narrows interpreter-produced
989
- * `unknown` values at the `SessionContext.appendHistory` boundary.
990
- */
991
- declare function isSessionHistoryEntry(value: RuntimeValue): value is SessionHistoryEntry;
992
- /**
993
- * AgentContext is the runtime contract for agent/* operators.
994
- *
995
- * The evaluator dispatches agent/* operators to methods on this interface.
996
- * Pure methods (usable in guards) return synchronously.
997
- * Effect methods return Promises.
998
- *
999
- * When ctx.agent is undefined, operators return safe defaults ([], 0, false, "").
1000
- * Implementations live in @almadar-io/agent-runtime (Phase 2B).
1001
- */
1002
- interface AgentContext {
1003
- recall(query: string, limit?: number): AgentMemoryRecord[];
1004
- memories(category?: AgentMemoryCategory): AgentMemoryRecord[];
1005
- memoryStrength(id: string): number;
1006
- isPinned(id: string): boolean;
1007
- memorize(content: string, category: AgentMemoryCategory, scope?: 'global' | 'project'): Promise<string>;
1008
- forget(id: string): Promise<void>;
1009
- pin(id: string): Promise<void>;
1010
- reinforce(id: string): Promise<void>;
1011
- decay(): Promise<number>;
1012
- provider(): string;
1013
- model(): string;
1014
- generate(prompt: string, options?: AgentGenerateOptions): Promise<string>;
1015
- switchProvider(provider: string, model?: string): void;
1016
- tools(): string[];
1017
- invoke(toolName: string, args: ServiceParams): Promise<EventPayloadValue>;
1018
- tokenCount(): number;
1019
- contextUsage(): number;
1020
- compact(strategy?: AgentCompactStrategy): Promise<AgentCompactResult>;
1021
- sessionId(): string;
1022
- fork(label?: string): Promise<string>;
1023
- label(text: string): void;
1024
- searchCode(query: string, language?: string): Promise<AgentCodeSearchResult[]>;
1025
- }
1026
- /** Backs the llm/* operators (6 ops). */
1027
- interface LlmContext {
1028
- generate(prompt: string, options?: {
1029
- json?: boolean;
1030
- maxTokens?: number;
1031
- provider?: string;
1032
- model?: string;
1033
- }): Promise<string>;
1034
- callTools(messages: LlmMessage[], tools: LlmToolDef[]): Promise<LlmCallToolsResult>;
1035
- embed(texts: string[]): Promise<number[][]>;
1036
- tokenCount(): number;
1037
- switchProvider(provider: string, model?: string): void;
1038
- compact(strategy?: string): Promise<{
1039
- before: number;
1040
- after: number;
1041
- }>;
1042
- }
1043
- /** Backs the workspace/* operators (11 ops). */
1044
- interface WorkspaceContext {
1045
- readOrbital(name: string): Promise<Orbital>;
1046
- writeOrbital(name: string, content: Orbital): Promise<void>;
1047
- readFile(path: string): Promise<string>;
1048
- writeFile(path: string, content: string): Promise<void>;
1049
- exists(path: string): boolean;
1050
- listOrbitals(): string[];
1051
- readSchema(): Promise<OrbitalSchema>;
1052
- writeSchema(schema: OrbitalSchema): Promise<void>;
1053
- readPlan(): Promise<PlanSnapshot>;
1054
- writePlan(plan: PlanSnapshot): Promise<void>;
1055
- archiveOrbital(name: string): Promise<void>;
1056
- }
1057
- /** Backs the session/* operators (9 ops). */
1058
- interface SessionContext {
1059
- readSpec(orbitalName: string): Promise<Orbital>;
1060
- writeSpec(orbitalName: string, spec: Orbital): Promise<void>;
1061
- readMemory(orbitalName: string): Promise<AgentMemoryRecord[]>;
1062
- writeMemory(orbitalName: string, memory: AgentMemoryRecord[]): Promise<void>;
1063
- readHistory(orbitalName: string): Promise<SessionHistoryEntry[]>;
1064
- appendHistory(orbitalName: string, entry: SessionHistoryEntry): Promise<void>;
1065
- readErrors(orbitalName: string): Promise<string[]>;
1066
- writeErrors(orbitalName: string, errors: string[]): Promise<void>;
1067
- readAnalysis(orbitalName: string): Promise<AnalysisResult>;
1068
- }
1069
- /** Backs the memory/* operators (3 ops). */
1070
- interface MemoryContext {
1071
- recall(query: string, limit?: number): AgentMemoryRecord[];
1072
- store(content: string, category?: string, strength?: number): Promise<string>;
1073
- list(category?: string): AgentMemoryRecord[];
1074
- }
1075
- /** Backs the trace/* operators (2 ops). */
1076
- interface TraceContext {
1077
- emit(event: string, payload?: EventPayloadValue): void;
1078
- log(message: string, level?: 'log' | 'warn' | 'error', data?: EventPayloadValue): void;
1079
- }
1080
- /** Backs the integration/* operators (3 ops). */
1081
- interface IntegrationContext {
1082
- http(method: string, url: string, body?: FieldValue, headers?: Record<string, string>): Promise<JsonValue>;
1083
- githubGetRepo(owner: string, repo: string): Promise<GitHubRepo>;
1084
- githubCreateIssue(owner: string, repo: string, title: string, body?: string): Promise<GitHubIssue>;
1085
- }
1086
-
1087
- /**
1088
- * Interaction Model Types
1089
- *
1090
- * Defines how users interact with entities in the application.
1091
- * Used to drive trait selection and UI slot usage.
1092
- *
1093
- * @packageDocumentation
1094
- */
1095
-
1096
- /**
1097
- * Create flow - how new items are created
1098
- */
1099
- type CreateFlow = 'modal' | 'page' | 'inline' | 'none';
1100
- /**
1101
- * Edit flow - how items are edited
1102
- */
1103
- type EditFlow = 'modal' | 'page' | 'inline' | 'none';
1104
- /**
1105
- * View flow - how item details are viewed
1106
- */
1107
- type ViewFlow = 'drawer' | 'page' | 'modal' | 'inline' | 'none';
1108
- /**
1109
- * Delete flow - how items are deleted
1110
- */
1111
- type DeleteFlow = 'confirm' | 'instant' | 'none';
1112
- /**
1113
- * List interaction - what happens when clicking list items
1114
- */
1115
- type ListInteraction = 'click-to-view' | 'click-to-edit' | 'inline-edit';
1116
- /**
1117
- * InteractionModel - defines how users interact with entities.
1118
- *
1119
- * This drives:
1120
- * - Which traits to attach (EntityManagement, ModalEdit, etc.)
1121
- * - How render_ui effects target slots (modal, drawer, page)
1122
- * - What UI patterns to use
1123
- */
1124
- interface InteractionModel {
1125
- /** How new items are created */
1126
- createFlow: CreateFlow;
1127
- /** How items are edited */
1128
- editFlow: EditFlow;
1129
- /** How item details are viewed */
1130
- viewFlow: ViewFlow;
1131
- /** How items are deleted */
1132
- deleteFlow: DeleteFlow;
1133
- /** What happens when clicking list items */
1134
- listInteraction?: ListInteraction;
1135
- /** Enable bulk actions (select multiple, delete all) */
1136
- bulkActions?: boolean;
1137
- /** Enable real-time updates */
1138
- realtime?: boolean;
1139
- }
1140
- declare const InteractionModelSchema: z.ZodObject<{
1141
- createFlow: z.ZodEnum<["modal", "page", "inline", "none"]>;
1142
- editFlow: z.ZodEnum<["modal", "page", "inline", "none"]>;
1143
- viewFlow: z.ZodEnum<["drawer", "page", "modal", "inline", "none"]>;
1144
- deleteFlow: z.ZodEnum<["confirm", "instant", "none"]>;
1145
- listInteraction: z.ZodOptional<z.ZodEnum<["click-to-view", "click-to-edit", "inline-edit"]>>;
1146
- bulkActions: z.ZodOptional<z.ZodBoolean>;
1147
- realtime: z.ZodOptional<z.ZodBoolean>;
1148
- }, "strip", z.ZodTypeAny, {
1149
- createFlow: "page" | "none" | "inline" | "modal";
1150
- editFlow: "page" | "none" | "inline" | "modal";
1151
- viewFlow: "page" | "none" | "inline" | "modal" | "drawer";
1152
- deleteFlow: "none" | "instant" | "confirm";
1153
- bulkActions?: boolean | undefined;
1154
- listInteraction?: "click-to-view" | "click-to-edit" | "inline-edit" | undefined;
1155
- realtime?: boolean | undefined;
1156
- }, {
1157
- createFlow: "page" | "none" | "inline" | "modal";
1158
- editFlow: "page" | "none" | "inline" | "modal";
1159
- viewFlow: "page" | "none" | "inline" | "modal" | "drawer";
1160
- deleteFlow: "none" | "instant" | "confirm";
1161
- bulkActions?: boolean | undefined;
1162
- listInteraction?: "click-to-view" | "click-to-edit" | "inline-edit" | undefined;
1163
- realtime?: boolean | undefined;
1164
- }>;
1165
- /**
1166
- * Default interaction models for each domain type
1167
- */
1168
- declare const DEFAULT_INTERACTION_MODELS: Record<string, InteractionModel>;
1169
- /**
1170
- * Gets the interaction model for a domain.
1171
- *
1172
- * Retrieves the appropriate interaction model configuration based on the
1173
- * specified domain. Falls back to the business model if no specific
1174
- * domain match is found.
1175
- *
1176
- * @param {string} domain - Domain name (e.g., 'healthcare', 'education')
1177
- * @returns {InteractionModel} Interaction model configuration
1178
- *
1179
- * @example
1180
- * getInteractionModelForDomain('healthcare'); // returns healthcare-specific model
1181
- * getInteractionModelForDomain('unknown'); // returns business fallback model
1182
- */
1183
- declare function getInteractionModelForDomain(domain: string): InteractionModel;
1184
- type InteractionModelInput = z.input<typeof InteractionModelSchema>;
1185
-
1186
- /**
1187
- * Pattern Type for Orbital Units
1188
- *
1189
- * Re-exports pattern type definitions from @almadar/core/patterns,
1190
- * which is the single source of truth for all pattern types.
1191
- *
1192
- * @packageDocumentation
1193
- */
1194
-
1195
- /**
1196
- * Zod schema for pattern types.
1197
- * Accepts any string - validation against full registry happens at runtime.
1198
- */
1199
- declare const PatternTypeSchema: z.ZodString;
1200
-
1201
- /**
1202
- * Changeset & Snapshot Types
1203
- *
1204
- * Unified types for schema change tracking, snapshots, and removal categorization.
1205
- * Used by @almadar/server for Firestore storage and by consumers for type safety.
1206
- */
1207
-
1208
- /**
1209
- * Value attached to a SchemaChange entry's `before` / `after`.
1210
- *
1211
- * Either a JSON-shaped LLM payload (`EventPayloadValue`), a single schema
1212
- * fragment (`Orbital`, `Trait`, `Entity`, `Page`, `OrbitalSchema`), or an
1213
- * array of such fragments. Mirrors the exact shapes the builder's changeset
1214
- * writers actually persist when adding/replacing a slice of the schema.
1215
- */
1216
- type ChangesetValue = EventPayloadValue | OrbitalSchema | Orbital | Trait | Entity | Page | Orbital[] | Trait[] | Entity[] | Page[];
1217
- /**
1218
- * A single change within a changeset.
1219
- */
1220
- interface SchemaChange {
1221
- id: string;
1222
- operation: 'add' | 'modify' | 'remove' | 'rename';
1223
- target: string;
1224
- path: (string | number)[];
1225
- before?: ChangesetValue;
1226
- after?: ChangesetValue;
1227
- description: string;
1228
- reason?: string;
1229
- dependsOn?: string[];
1230
- }
1231
- /**
1232
- * Author of a changeset.
1233
- */
1234
- interface ChangeAuthor {
1235
- type: 'agent' | 'user';
1236
- id?: string;
1237
- name?: string;
1238
- }
1239
- /**
1240
- * Summary statistics for a changeset.
1241
- */
1242
- interface ChangeSummary {
1243
- added: number;
1244
- modified: number;
1245
- removed: number;
1246
- description: string;
1247
- }
1248
- /**
1249
- * Complete changeset document.
1250
- * Stored at: users/{uid}/apps/{appId}/changesets/{changeSetId}
1251
- */
1252
- interface ChangeSetDocument {
1253
- id: string;
1254
- version: number;
1255
- timestamp: number;
1256
- source: 'requirements-agent' | 'builder-agent' | 'user' | 'auto-fix';
1257
- author: ChangeAuthor;
1258
- trigger?: string;
1259
- changes: SchemaChange[];
1260
- summary: ChangeSummary;
1261
- status: 'applied' | 'reverted' | 'pending';
1262
- description: string;
1263
- }
1264
- /**
1265
- * Schema snapshot document.
1266
- * Stored at: users/{uid}/apps/{appId}/snapshots/{snapshotId}
1267
- */
1268
- interface SnapshotDocument {
1269
- id: string;
1270
- timestamp: number;
1271
- schema: OrbitalSchema;
1272
- reason: string;
1273
- version?: number;
1274
- }
1275
- /**
1276
- * Removals categorized by severity.
1277
- */
1278
- interface CategorizedRemovals {
1279
- /** States, pages, entities — always require confirmation */
1280
- critical: SchemaChange[];
1281
- /** Fields, actions — auto-snapshotted */
1282
- standard: SchemaChange[];
1283
- /** Transitions, guards — tracked */
1284
- minor: SchemaChange[];
1285
- /** Implicit content removal within pages */
1286
- pageContentReductions: PageContentReduction[];
1287
- }
1288
- /**
1289
- * Detected reduction in page content (components, actions, displays removed).
1290
- */
1291
- interface PageContentReduction {
1292
- pageName: string;
1293
- componentsRemoved: number;
1294
- actionsRemoved: number;
1295
- displaysRemoved: number;
1296
- before: {
1297
- sections: number;
1298
- actions: number;
1299
- };
1300
- after: {
1301
- sections: number;
1302
- actions: number;
1303
- };
1304
- isSignificant: boolean;
1305
- }
1306
- /**
1307
- * History metadata stored in main app document for quick access.
1308
- */
1309
- interface HistoryMeta {
1310
- latestSnapshotId?: string;
1311
- latestChangeSetId?: string;
1312
- snapshotCount: number;
1313
- changeSetCount: number;
1314
- }
1315
- /**
1316
- * Validation metadata stored in main app document for quick access.
1317
- */
1318
- interface ValidationMeta {
1319
- errorCount: number;
1320
- warningCount: number;
1321
- validatedAt: number;
1322
- }
1323
- /**
1324
- * What kind of .orb concept changed between two schema versions.
1325
- * Used by canvas focus derivation, CLI narration, selective re-verification.
1326
- */
1327
- type SemanticChangeKind = 'orbital-added' | 'orbital-removed' | 'entity-fields-changed' | 'trait-added' | 'trait-removed' | 'state-machine-changed' | 'guard-changed' | 'effect-changed' | 'render-ui-changed' | 'event-wiring-changed' | 'page-changed' | 'behavior-composed';
1328
- /**
1329
- * A semantic change between two OrbitalSchema versions.
1330
- * Identifies WHAT concept changed and WHERE in the schema.
1331
- */
1332
- interface SemanticSchemaChange {
1333
- kind: SemanticChangeKind;
1334
- orbitalName: string;
1335
- traitName?: string;
1336
- transitionEvent?: string;
1337
- fieldName?: string;
1338
- }
1339
-
1340
- /**
1341
- * App-Level Types
1342
- *
1343
- * Types for app summaries, stats, and save operations.
1344
- */
1345
-
1346
- /**
1347
- * GitHub repository link metadata stored in Firestore.
1348
- * Enables GitHub as the source of truth for schema files.
1349
- */
1350
- interface GitHubLink {
1351
- repoUrl: string;
1352
- owner: string;
1353
- repo: string;
1354
- defaultBranch: string;
1355
- connectedAt: number;
1356
- schemaFile?: string;
1357
- }
1358
- /**
1359
- * Dashboard stats derived from schema.
1360
- */
1361
- interface StatsView {
1362
- states: number;
1363
- events: number;
1364
- pages: number;
1365
- entities: number;
1366
- transitions: number;
1367
- }
1368
- /**
1369
- * App summary for list views.
1370
- */
1371
- interface AppSummary {
1372
- id: string;
1373
- name: string;
1374
- description?: string;
1375
- updatedAt: number;
1376
- createdAt: number;
1377
- stats: StatsView;
1378
- domain?: {
1379
- category: string;
1380
- subDomain?: string;
1381
- };
1382
- /**
1383
- * Canonical domain classification + vocabulary projected onto the list
1384
- * view. Same shape as `OrbitalSchema.domainContext`.
1385
- */
1386
- domainContext?: DomainContext;
1387
- hasValidationErrors: boolean;
1388
- github?: GitHubLink;
1389
- }
1390
- /**
1391
- * Options for saving a schema.
1392
- */
1393
- interface SaveOptions {
1394
- confirmRemovals?: boolean;
1395
- snapshotReason?: string;
1396
- skipProtection?: boolean;
1397
- expectedVersion?: number;
1398
- source?: 'requirements-agent' | 'builder-agent' | 'manual';
1399
- }
1400
- /**
1401
- * Result of saving a schema.
1402
- */
1403
- interface SaveResult {
1404
- success: boolean;
1405
- requiresConfirmation?: boolean;
1406
- removals?: CategorizedRemovals;
1407
- error?: string;
1408
- snapshotId?: string;
1409
- }
1410
- /**
1411
- * Context attached to validation issues originating from LLM output.
1412
- * Mirrors the `LLMErrorContext` shapes used by `@almadar/validation`
1413
- * and the builder's fix-prompt pipeline.
1414
- */
1415
- interface LLMErrorContext {
1416
- /** Preview of the raw LLM output */
1417
- rawValuePreview?: string;
1418
- /** Expected type or structure */
1419
- expectedType?: string;
1420
- /** Actual type received */
1421
- actualType?: string;
1422
- /** Where the error originated */
1423
- source?: {
1424
- agent: 'requirements' | 'builder' | 'view-planner';
1425
- operation: string;
1426
- promptHash?: string;
1427
- };
1428
- tokenUsage?: {
1429
- prompt: number;
1430
- completion: number;
1431
- };
1432
- }
1433
- /**
1434
- * Validation issue with optional LLM context.
1435
- */
1436
- interface ValidationIssue {
1437
- code: string;
1438
- message: string;
1439
- path: (string | number)[];
1440
- severity: 'error' | 'warning' | 'info';
1441
- suggestion?: string;
1442
- llmContext?: LLMErrorContext;
1443
- }
1444
- /**
1445
- * Validation results.
1446
- */
1447
- interface ValidationResults {
1448
- errors: ValidationIssue[];
1449
- warnings: ValidationIssue[];
1450
- validatedAt: number;
1451
- }
1452
- /**
1453
- * Validation document stored in subcollection.
1454
- */
1455
- interface ValidationDocument {
1456
- errors: ValidationIssue[];
1457
- warnings: ValidationIssue[];
1458
- validatedAt: number;
1459
- }
1460
-
1461
- /**
1462
- * Service Contract Types
1463
- *
1464
- * Formalizes the two public surfaces of an Almadar service:
1465
- * 1. Call-Service Contract — what the .orb schema can invoke on the TypeScript package
1466
- * 2. Event Contract — what events enter/leave the service
1467
- *
1468
- * Plus internal-but-standardized patterns:
1469
- * 3. StoreContract — database abstraction boundary
1470
- * 4. LazyService — singleton lifecycle pattern
1471
- *
1472
- * @packageDocumentation
1473
- */
1474
-
1475
- /**
1476
- * All known service action names across all contracts.
1477
- * Kept in sync with `tools/almadar-service-sync/services-registry.json`.
1478
- *
1479
- * Persist operations are listed separately because they also appear
1480
- * as `EffectResult.action` for persist effects.
1481
- */
1482
- type PersistActionName = "create" | "update" | "delete" | "list" | "query";
1483
- /**
1484
- * Union of all service action names across the registered service contracts.
1485
- */
1486
- type ServiceActionName = PersistActionName | "get" | "getById" | "set" | "remove" | "size" | "generate" | "classify" | "extract" | "summarize" | "send" | "sendMessage" | "sendSMS" | "sendWhatsApp" | "authorize" | "revoke" | "token" | "refresh" | "userinfo" | "register" | "cloneRepo" | "commit" | "createBranch" | "createPR" | "getPRComments" | "pull" | "push" | "build" | "compile" | "compileSchema" | "run" | "validate" | "validateSchema" | "publish" | "enqueue" | "dequeue" | "cancel" | "upload" | "download" | "getSignedUrl" | "search" | "getIssue" | "listIssues" | "generateAll" | "generateDomainLanguage" | "generateFix" | "generateOrbitals" | "cancelGeneration" | "getGenerationHistory" | "recordGeneration" | "startSpan" | "endSpan" | "getSpan" | "recordMetric" | "getMetrics" | "increment" | "logs" | "addEvent" | "emit" | "findEmitters" | "findListeners" | "getListenerCounts" | "getChannel" | "subscribe" | "getUserPreferences" | "updateUserPreferences" | "getThreadHistory" | "listDocuments" | "fetchDocument" | "getVideo" | "createPaymentIntent" | "confirmPayment" | "refund" | "complete" | "fail" | "expire" | "resume" | "status" | "stop" | "lock" | "unlock" | "clear";
1487
- /**
1488
- * Action definition for a service contract.
1489
- *
1490
- * - `params` is bus-payload-shaped (`ServiceParams`): JSON-serializable
1491
- * key/value bag with optional nesting. Service contracts override this
1492
- * with stricter shapes via the generic position on `ServiceContract`.
1493
- *
1494
- * - `result` is JSON-serializable too (`EventPayloadValue`): a primitive,
1495
- * `null`/`undefined`, an array of values, or an `EventPayload` object.
1496
- * This is the same recursive shape the bus accepts when an effect's
1497
- * `success` event fires with the call-service result, so no boundary
1498
- * widening is needed when the runtime forwards the value.
1499
- */
1500
- interface ServiceAction {
1501
- params: ServiceParams;
1502
- result: EventPayloadValue;
1503
- }
1504
- /**
1505
- * What `["call-service", "name", "action", {...}]` actually calls at runtime.
1506
- * Each service defines its action map as a Record<string, ServiceAction>.
1507
- *
1508
- * @example
1509
- * ```typescript
1510
- * type LLMActions = {
1511
- * generate: {
1512
- * params: { userPrompt: string; model: string; maxTokens: number };
1513
- * result: { content: string; tokensUsed: number; latencyMs: number };
1514
- * };
1515
- * };
1516
- *
1517
- * class LLMService implements ServiceContract<LLMActions> {
1518
- * async execute(action, params) { ... }
1519
- * }
1520
- * ```
1521
- */
1522
- interface ServiceContract<Actions extends Record<string, ServiceAction>> {
1523
- execute<A extends keyof Actions & string>(action: A, params: Actions[A]["params"]): Promise<Actions[A]["result"]>;
1524
- }
1525
- /**
1526
- * Event contract — what events the service emits/listens with typed payloads.
1527
- * Derived from the `.orb` schema's `emits` and `listens` declarations.
1528
- *
1529
- * @example
1530
- * ```typescript
1531
- * type LLMEventMap = {
1532
- * AGENT_LLM_REQUEST: { requestId: string; prompt: string };
1533
- * LLM_RESPONSE: { requestId: string; content: string; tokensUsed: number };
1534
- * LLM_ERROR: { requestId: string; error: string };
1535
- * };
1536
- *
1537
- * const events: ServiceEvents<LLMEventMap> = getEventBus();
1538
- * events.emit('LLM_RESPONSE', { requestId: '1', content: '...', tokensUsed: 42 });
1539
- * ```
1540
- */
1541
- interface ServiceEvents<EventMap extends Record<string, EventPayload>> {
1542
- emit<E extends keyof EventMap & string>(event: E, payload: EventMap[E]): void;
1543
- on<E extends keyof EventMap & string>(event: E, handler: (payload: EventMap[E]) => void): () => void;
1544
- }
1545
- /**
1546
- * Create a typed view of an untyped EventBus. Wraps the raw EventBus
1547
- * with compile-time type checking while keeping runtime behavior identical.
1548
- *
1549
- * @example
1550
- * ```typescript
1551
- * type LLMEventMap = {
1552
- * LLM_RESPONSE: { requestId: string; content: string };
1553
- * LLM_ERROR: { requestId: string; error: string };
1554
- * };
1555
- *
1556
- * const typedBus = createTypedEventBus<LLMEventMap>(getServerEventBus());
1557
- * typedBus.emit('LLM_RESPONSE', { requestId: '1', content: '...' }); // type-safe
1558
- * typedBus.on('LLM_ERROR', (payload) => { payload.error; }); // payload is typed
1559
- * ```
1560
- */
1561
- /**
1562
- * Creates a typed event bus from an untyped bus implementation.
1563
- *
1564
- * This wrapper adds TypeScript type safety to event emission and listening.
1565
- * The generic `EventMap` defines the shape of all events and their payloads.
1566
- *
1567
- * @template EventMap - Type mapping event names to their payload types
1568
- * @param {Object} bus - Untyped event bus implementation
1569
- * @param {Function} bus.emit - Function to emit events
1570
- * @param {Function} bus.on - Function to listen to events
1571
- * @returns {ServiceEvents<EventMap>} Typed event bus interface
1572
- *
1573
- * @example
1574
- * interface MyEvents {
1575
- * 'user.created': { id: string; name: string };
1576
- * 'user.deleted': { id: string };
1577
- * }
1578
- *
1579
- * const typedBus = createTypedEventBus<MyEvents>(rawBus);
1580
- * typedBus.emit('user.created', { id: '123', name: 'Alice' });
1581
- */
1582
- declare function createTypedEventBus<EventMap extends Record<string, EventPayload>>(bus: {
1583
- emit(event: string, payload?: unknown, meta?: LogMeta): void;
1584
- on(event: string, handler: (payload: unknown, meta?: LogMeta) => void): () => void;
1585
- }): ServiceEvents<EventMap>;
1586
- /** Filter operator for store queries. */
1587
- type StoreFilterOp = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "contains";
1588
- /** A single filter clause for store queries. */
1589
- interface StoreFilter<T> {
1590
- field: keyof T & string;
1591
- op: StoreFilterOp;
1592
- value: unknown;
1593
- }
1594
- /**
1595
- * Database abstraction boundary. Services receive `StoreContract<T>`,
1596
- * not raw database clients. Swappable per database engine.
1597
- *
1598
- * @example
1599
- * ```typescript
1600
- * interface LLMRequest { id: string; prompt: string; status: string }
1601
- *
1602
- * class FirestoreLLMRequestStore implements StoreContract<LLMRequest> {
1603
- * async getById(id) { ... }
1604
- * async create(data) { ... }
1605
- * async update(id, data) { ... }
1606
- * async delete(id) { ... }
1607
- * async query(filters) { ... }
1608
- * }
1609
- * ```
1610
- */
1611
- interface StoreContract<T extends {
1612
- id: string;
1613
- }> {
1614
- getById(id: string): Promise<T | null>;
1615
- create(data: Omit<T, "id">): Promise<T>;
1616
- update(id: string, data: Partial<T>): Promise<T>;
1617
- delete(id: string): Promise<void>;
1618
- query(filters: StoreFilter<T>[]): Promise<T[]>;
1619
- }
1620
- /**
1621
- * Standardized singleton lifecycle. Replaces ad-hoc
1622
- * `let x = null; export function getX()` patterns.
1623
- *
1624
- * @example
1625
- * ```typescript
1626
- * const llmClient = createLazyService(() => new LLMClient({ apiKey: process.env.LLM_KEY }));
1627
- *
1628
- * // In request handler:
1629
- * const client = llmClient.get(); // created on first call, cached after
1630
- *
1631
- * // In test teardown:
1632
- * llmClient.reset(); // next get() creates a fresh instance
1633
- * ```
1634
- */
1635
- interface LazyService<T> {
1636
- /** Get the singleton instance (creates on first call). */
1637
- get(): T;
1638
- /** Reset the singleton (next get() creates fresh). For test isolation. */
1639
- reset(): void;
1640
- }
1641
- /**
1642
- * Create a lazy singleton from a factory function.
1643
- *
1644
- * Creates a service that lazily initializes on first access and caches the instance.
1645
- * Useful for expensive resources like database connections or API clients.
1646
- *
1647
- * @template T - The type of service to create
1648
- * @param {() => T} factory - Factory function that creates the service instance
1649
- * @returns {LazyService<T>} Lazy service with get() and reset() methods
1650
- *
1651
- * @example
1652
- * const dbService = createLazyService(() => new DatabaseClient(config));
1653
- * const db = dbService.get(); // Initializes on first call
1654
- */
1655
- declare function createLazyService<T>(factory: () => T): LazyService<T>;
1656
-
1657
- /**
1658
- * Transition source state specification.
1659
- * - string: Single state name (e.g., 'Idle')
1660
- * - '*': Wildcard - matches any current state
1661
- * - string[]: Array of states - matches any of the listed states
1662
- */
1663
- type TransitionFrom = string | '*' | string[];
1664
- interface ResolvedField {
1665
- name: string;
1666
- type: string;
1667
- tsType: string;
1668
- description?: string;
1669
- /** Field default — JSON-shaped, mirroring `EntityField.default`. */
1670
- default?: JsonValue;
1671
- required: boolean;
1672
- /** Validation constraints carried from the schema (enum whitelist). */
1673
- validation?: {
1674
- enum?: string[];
1675
- };
1676
- /** Enum values for enum or constrained string fields */
1677
- values?: string[];
1678
- /** Enum values (alias for values, for compatibility) */
1679
- enumValues?: string[];
1680
- /** Relation configuration for foreign key references */
1681
- relation?: {
1682
- entity: string;
1683
- cardinality?: string;
1684
- field?: string;
1685
- };
1686
- }
1687
- interface ResolvedEntity {
1688
- name: string;
1689
- description?: string;
1690
- icon?: string;
1691
- collection: string;
1692
- fields: ResolvedField[];
1693
- /** Whether this entity only exists in runtime (not persisted to Firestore) */
1694
- runtime?: boolean;
1695
- /** Whether this entity's state is shared across every bound trait (vs a per-trait copy). Orthogonal to `runtime`. */
1696
- shared?: boolean;
1697
- /** Whether this entity has pre-authored instances in the schema */
1698
- hasInstances?: boolean;
1699
- /** Pre-authored instances from the schema (seed data or static reference data) */
1700
- instances?: EntityRow[];
1701
- /** Default field values from schema (for spawning singletons) */
1702
- defaults?: Record<string, FieldValue>;
1703
- usedByTraits: string[];
1704
- usedByPages: string[];
1705
- }
1706
- interface ResolvedEntityBinding {
1707
- /** Binding name in code */
1708
- name: string;
1709
- /** Entity being bound */
1710
- entity: ResolvedEntity;
1711
- /** CRUD operations to generate */
1712
- operations: ('list' | 'get' | 'create' | 'update' | 'delete')[];
1713
- }
1714
- interface ResolvedTraitState {
1715
- name: string;
1716
- isInitial: boolean;
1717
- isFinal: boolean;
1718
- }
1719
- interface ResolvedTraitEvent {
1720
- key: string;
1721
- name: string;
1722
- payload?: Record<string, string>;
1723
- }
1724
- interface ResolvedTraitTransition {
1725
- /** Source state(s): string, '*' for wildcard, or array of states */
1726
- from: TransitionFrom;
1727
- to: string;
1728
- event: string;
1729
- guard?: SExpr;
1730
- effects: SExpr[];
1731
- }
1732
- interface ResolvedTraitGuard {
1733
- name: string;
1734
- condition: SExpr;
1735
- }
1736
- interface ResolvedTraitTick {
1737
- name: string;
1738
- /**
1739
- * `number` (ms), `'frame'`, a duration string (`'5s'`/`'1m'`/`'1h'`), or a
1740
- * 5-field cron expression (`'0 9 * * *'`) — `schema-to-ir.ts`'s
1741
- * `interval: tick.interval || 0` passes the source schema's raw
1742
- * `string | number` straight through with no normalization, so this must
1743
- * match that reality rather than the narrower `number | 'frame'` it used
1744
- * to declare (which made every non-'frame' string an unchecked cast at
1745
- * every consumer).
1746
- */
1747
- interval: number | string;
1748
- guard?: SExpr;
1749
- effects: SExpr[];
1750
- priority: number;
1751
- appliesTo: string[];
1752
- }
1753
- interface ResolvedTraitListener {
1754
- event: string;
1755
- triggers: string;
1756
- guard?: SExpr;
1757
- /** `with { ... }` payload rewrite: `{ targetField: SExpr }`, evaluated against the source payload. */
1758
- payloadMapping?: Record<string, SExpr>;
1759
- /** Source scoping (see `ListenSource` in types/trait). */
1760
- source?: ListenSource;
1761
- }
1762
- interface ResolvedTraitDataEntity {
1763
- name: string;
1764
- fields: ResolvedField[];
1765
- runtime: boolean;
1766
- singleton: boolean;
1767
- }
1768
- /**
1769
- * UI binding for interaction traits - maps states to presentations
1770
- */
1771
- interface ResolvedTraitUIBinding {
1772
- [stateName: string]: {
1773
- /** Presentation type: modal, drawer, popover, inline, confirm-dialog */
1774
- presentation: string;
1775
- /** Content pattern(s) to render */
1776
- content: AnyPatternConfig | AnyPatternConfig[];
1777
- /** Presentation props */
1778
- props?: {
1779
- size?: string;
1780
- position?: string;
1781
- title?: string;
1782
- closable?: boolean;
1783
- width?: string;
1784
- showProgress?: boolean;
1785
- step?: number;
1786
- totalSteps?: number;
1787
- };
1788
- };
1789
- }
1790
- /**
1791
- * Fully resolved trait - expanded from schema OR library.
1792
- * The compiler generates code from this structure universally,
1793
- * without knowing which specific trait it is.
1794
- */
1795
- interface ResolvedTrait {
1796
- /** Unique trait identifier */
1797
- name: string;
1798
- /** Human-readable description */
1799
- description?: string;
1800
- /** Where this trait came from */
1801
- source: 'schema' | 'library' | 'inline';
1802
- /** Category for organizing traits */
1803
- category?: 'lifecycle' | 'temporal' | 'validation' | 'notification' | 'integration' | 'interaction' | 'agent' | 'game-core' | 'game-character' | 'game-ai' | 'game-combat' | 'game-items' | 'game-cards' | 'game-board' | 'game-puzzle';
1804
- states: ResolvedTraitState[];
1805
- events: ResolvedTraitEvent[];
1806
- transitions: ResolvedTraitTransition[];
1807
- guards: ResolvedTraitGuard[];
1808
- ticks: ResolvedTraitTick[];
1809
- listens: ResolvedTraitListener[];
1810
- dataEntities: ResolvedTraitDataEntity[];
1811
- /**
1812
- * Atom-declared linked entity. The atom (e.g. std-pagination)
1813
- * declares which entity its `@entity.X` bindings resolve against
1814
- * (e.g. `PagedItem`). Distinct from the call-site rebind on
1815
- * `ResolvedTraitBinding.linkedEntity`, which a molecule may use
1816
- * to override the atom's default. Either side may be undefined
1817
- * for traits that don't bind any entity (pure interaction).
1818
- */
1819
- linkedEntity?: string;
1820
- /**
1821
- * The trait's DECLARED `config { }` schema (per-field
1822
- * `{ type, default? }`). Drives `@config.X` substitution: each
1823
- * field's `default` seeds the binding context behind any caller-
1824
- * supplied call-site `config: { ... }` override on the trait
1825
- * reference. Authored on the atom; flows through verbatim from
1826
- * `Trait.config`.
1827
- *
1828
- * (Caller-supplied call-site overrides live on the page-trait
1829
- * binding's `config: TraitConfig` — see `ResolvedTraitBinding`.)
1830
- */
1831
- config?: DeclaredTraitConfig;
1832
- ui?: ResolvedTraitUIBinding;
1833
- }
1834
- /**
1835
- * Trait binding on a page - links a resolved trait to the page
1836
- */
1837
- interface ResolvedTraitBinding {
1838
- /** Reference name */
1839
- ref?: string;
1840
- /** Fully resolved trait */
1841
- trait: ResolvedTrait;
1842
- /** Entity this trait operates on (if any) */
1843
- linkedEntity?: string;
1844
- /** Instance configuration */
1845
- config?: TraitConfig;
1846
- }
1847
- interface ResolvedPattern {
1848
- /** Pattern type (e.g., 'page-header', 'entity-list', 'game-canvas') */
1849
- type: string;
1850
- /** Pattern configuration */
1851
- config: AnyPatternConfig;
1852
- /** Shell component to use */
1853
- shellComponent?: string;
1854
- }
1855
- interface ResolvedSectionEvent {
1856
- event: string;
1857
- action: string;
1858
- target?: string;
1859
- }
1860
- interface ResolvedSection {
1861
- /** Section identifier */
1862
- id: string;
1863
- /** Resolved pattern */
1864
- pattern: ResolvedPattern;
1865
- /** Events emitted by this section */
1866
- events: ResolvedSectionEvent[];
1867
- /** Position in page layout */
1868
- position?: number;
1869
- /** Entity binding for this section */
1870
- binding?: ResolvedEntityBinding;
1871
- }
1872
- interface ResolvedNavigation {
1873
- event?: string;
1874
- from?: string;
1875
- to: string;
1876
- trigger?: string;
1877
- params?: Record<string, string>;
1878
- label?: string;
1879
- path?: string;
1880
- icon?: string;
1881
- }
1882
- interface ResolvedPage {
1883
- /** Page identifier */
1884
- name: string;
1885
- /** URL path */
1886
- path: string;
1887
- /** Feature folder name */
1888
- featureName: string;
1889
- /** Layout component */
1890
- layout?: string;
1891
- /** View type (dashboard, list, detail, create, edit) */
1892
- viewType?: 'dashboard' | 'list' | 'detail' | 'create' | 'edit';
1893
- /** Resolved sections */
1894
- sections: ResolvedSection[];
1895
- /** Resolved trait bindings */
1896
- traits: ResolvedTraitBinding[];
1897
- /** Entity data bindings */
1898
- entityBindings: ResolvedEntityBinding[];
1899
- /** Navigation wiring */
1900
- navigation: ResolvedNavigation[];
1901
- /** Singleton entities to spawn on this page (runtime singletons) */
1902
- singletonEntities: ResolvedEntity[];
1903
- }
1904
- /**
1905
- * Complete resolved IR - all references expanded
1906
- */
1907
- interface ResolvedIR {
1908
- /** App name */
1909
- appName: string;
1910
- /** App description */
1911
- description?: string;
1912
- /** App version */
1913
- version?: string;
1914
- /** All resolved entities (Map for lookup) */
1915
- entities: Map<string, ResolvedEntity>;
1916
- /** All resolved traits (Map for lookup) */
1917
- traits: Map<string, ResolvedTrait>;
1918
- /** All resolved pages (Map for lookup) */
1919
- pages: Map<string, ResolvedPage>;
1920
- /** Entity bindings (used for data hook generation) */
1921
- entityBindings: ResolvedEntityBinding[];
1922
- /** Raw data entities (used for instance data generation) */
1923
- rawEntities?: Entity[];
1924
- /** Generation timestamp */
1925
- generatedAt: string;
1926
- }
1927
- /**
1928
- * Create an empty resolved trait with defaults
1929
- */
1930
- declare function createEmptyResolvedTrait(name: string, source: 'schema' | 'library' | 'inline'): ResolvedTrait;
1931
- /**
1932
- * Create an empty resolved page with defaults
1933
- */
1934
- declare function createEmptyResolvedPage(name: string): ResolvedPage;
1935
- /**
1936
- * Infer TypeScript type from schema type
1937
- */
1938
- declare function inferTsType(schemaType: string): string;
1939
- /**
1940
- * Create a resolved field with TypeScript type inference
1941
- */
1942
- declare function createResolvedField(field: {
1943
- name: string;
1944
- type: string;
1945
- description?: string;
1946
- default?: JsonValue;
1947
- required?: boolean;
1948
- validation?: {
1949
- enum?: string[];
1950
- };
1951
- values?: string[];
1952
- }): ResolvedField;
1953
- /**
1954
- * Type guard to check if an object is a ResolvedIR.
1955
- *
1956
- * Validates that an unknown value conforms to the ResolvedIR structure.
1957
- * Checks for required properties and correct types. Used for runtime
1958
- * type checking and validation.
1959
- *
1960
- * @param {unknown} ir - Value to check
1961
- * @returns {boolean} True if value is ResolvedIR, false otherwise
1962
- *
1963
- * @example
1964
- * if (isResolvedIR(schema)) {
1965
- * // Type-safe access to ResolvedIR properties
1966
- * console.log('Valid IR:', schema.appName);
1967
- * }
1968
- */
1969
- declare function isResolvedIR(ir: RuntimeValue): ir is ResolvedIR;
1970
-
1971
- /**
1972
- * Context Extensions (framework concept)
1973
- *
1974
- * Open interface for consumer-supplied context that flows through guards,
1975
- * effects, and evaluation. Generated code imports `ContextExtensions`
1976
- * instead of `Record<string, unknown>` / `unknown` for the extensions bag,
1977
- * so downstream type-checking verifies that every read of a context key
1978
- * lines up with a declared interface member.
1979
- *
1980
- * Declaration-merging pattern — consumers augment this interface with
1981
- * their own optional fields:
1982
- *
1983
- * ```ts
1984
- * declare module '@almadar/core' {
1985
- * interface ContextExtensions {
1986
- * agent?: AgentContext;
1987
- * auth?: AuthContext;
1988
- * }
1989
- * }
1990
- * ```
1991
- *
1992
- * With no augmentation the interface is `{}` — `ctx.extensions.foo` is
1993
- * a type error, which is the desired behavior: if the codegen hits a
1994
- * context field that nobody declared, the consumer project is expected
1995
- * to add the declaration rather than widen to `unknown`.
1996
- *
1997
- * @packageDocumentation
1998
- */
1999
- interface ContextExtensions {
2000
- }
2001
-
2002
- /**
2003
- * Bus Event Types (framework concept)
2004
- *
2005
- * Canonical event shape for Almadar's cross-package event bus. Hoisted into
2006
- * `@almadar/core` so `@almadar/ui`, `@almadar/runtime`, and generated code
2007
- * all agree on the same structure. Replaces the previously divergent
2008
- * `KFlowEvent` (ui) and `RuntimeEvent` (runtime) definitions.
2009
- *
2010
- * @packageDocumentation
2011
- */
2012
-
2013
- /**
2014
- * Declared event key. A trait's event names (INIT, SAVE, CLOSE,
2015
- * CONFIRM_REMOVE, ...) flow through the orbital schema and the UI as
2016
- * strings; this alias marks "this string is a declared event key, not
2017
- * arbitrary text."
2018
- *
2019
- * Component props typed as `EventKey` are detected by the pattern-sync
2020
- * tool (`tools/almadar-pattern-sync/parser.ts`) via a TS-type lookup and
2021
- * marked as `kind: "event"` in the patterns registry
2022
- * (`@almadar/patterns`). Consumers of the registry — the Rust compiler's
2023
- * inline phase and the `@almadar/runtime` preprocess — read that marker
2024
- * to apply call-site `events: { OLD: NEW }` renames to render-ui trees
2025
- * without name-matching heuristics.
2026
- *
2027
- * Plain alias over `string`. Not branded because event keys originate
2028
- * from user data at runtime (orb schema literals, bus emits), so cast
2029
- * friction would buy nothing. The value of the alias is at the type
2030
- * surface — it's a marker the pattern-sync tool can find via
2031
- * `getSymbolAtLocation`.
2032
- */
2033
- type EventKey = string;
2034
- /**
2035
- * Phantom-typed brand for declarative bus-emit props on UI components.
2036
- *
2037
- * Used by component authors to BOTH mark a prop as a bus-event reference
2038
- * AND document the payload shape that the component will fire onto the
2039
- * bus when that prop is bound. Authors write:
2040
- *
2041
- * // Tabs.tsx
2042
- * export interface TabsProps {
2043
- * tabChangeEvent?: EventEmit<{ tabId: string }>;
2044
- * }
2045
- *
2046
- * Consumers see only the structural `string` (no UX impact: passing a
2047
- * literal `"TAB_CHANGED"` keeps working). The phantom `P` parameter
2048
- * carries the bus-payload schema at the type level for pattern-sync to
2049
- * extract.
2050
- *
2051
- * Pattern-sync (`tools/almadar-pattern-sync/parser.ts`) detects this
2052
- * brand via TS type-lookup (mirrors how it detects `EventKey`) and
2053
- * writes two registry fields per prop:
2054
- * - `kind: "event-ref"` — the discriminant rules read in lolo / orb
2055
- * validator to know "this prop's string value is a bus event name."
2056
- * - `emitPayloadSchema` — the structural shape of `P`, serialized as
2057
- * the same JSON-Schema-shaped record Almadar uses for trait
2058
- * `payloadSchema`. Validator rules cross-check this against the
2059
- * trait's declared `emits { EVENT { ... } }` payload to catch mismatches
2060
- * at parse / validate time instead of runtime.
2061
- *
2062
- * Example payload bus emission inside the component (no wrapper —
2063
- * `EventEmit<P>` erases to `string`):
2064
- *
2065
- * if (tabChangeEvent) eventBus.emit(`UI:${tabChangeEvent}`, { tabId });
2066
- *
2067
- * The brand is structurally an unused optional readonly property; TS
2068
- * never asks for it at construction, so authors and consumers never
2069
- * see it.
2070
- */
2071
- type EventEmit<P> = string & {
2072
- readonly __emitPayload?: P;
2073
- };
2074
- /**
2075
- * Phantom-typed brand for declarative bus-listen props on UI components.
2076
- *
2077
- * Mirror of `EventEmit<P>`. Used by future patterns where a UI component
2078
- * subscribes to a bus event and forwards its payload upward via prop
2079
- * (e.g. an editor pattern that listens for `EXTERNAL_RESET` and exposes
2080
- * the consumed payload to the parent). Pattern-sync detects this brand
2081
- * the same way as `EventEmit<P>` and writes:
2082
- * - `kind: "event-listen"` (or a sub-discriminant of `event-ref`)
2083
- * - `listenPayloadSchema` with the structural shape of `P`
2084
- *
2085
- * Validator rules use this to verify the trait the prop is bound to
2086
- * actually emits a payload of the expected shape.
2087
- *
2088
- * Reserved for symmetry; no @almadar/ui component uses it as of this
2089
- * commit. Add usages incrementally as patterns require them.
2090
- */
2091
- type EventListen<P> = string & {
2092
- readonly __listenPayload?: P;
2093
- };
2094
- /**
2095
- * Identifies the origin of a bus event. Used by cross-trait listeners to
2096
- * filter emits from specific orbitals, traits, transitions, or ticks.
2097
- *
2098
- * `transition` and `tick` are optional runtime-internal details; most
2099
- * consumers only care about `orbital` and `trait`.
2100
- */
2101
- interface BusEventSource {
2102
- orbital?: string;
2103
- /** V4 dual-carry id sibling of `orbital` — stable across an orbital rename. */
2104
- orbitalId?: OrbitalId;
2105
- trait?: string;
2106
- /** V4 dual-carry id sibling of `trait` — stable across a trait rename. */
2107
- traitId?: TraitId;
2108
- /** V4 dual-carry id of the emitted event — stable across an event rename. */
2109
- eventId?: EventId;
2110
- transition?: string;
2111
- tick?: string;
2112
- /**
2113
- * True when the orbital bridge re-broadcasts an event onto the bus
2114
- * (any source — both echoes of the dispatched event and server-side
2115
- * cascade emits via `(emit X)` / `fetch.emit.success`). Cross-trait
2116
- * listeners filter on this flag so the click-time qualified emit
2117
- * (which has no `fromBridge`) doesn't double-fire alongside the
2118
- * post-server bridge confirmation. See `dispatched` for the narrower
2119
- * "echo of the just-dispatched event" signal.
2120
- */
2121
- fromBridge?: boolean;
2122
- /**
2123
- * True ONLY for bridge echoes the receiving tab already processed, so
2124
- * the originating trait's self-subscription skips them instead of
2125
- * re-dispatching its own echo (infinite loop / double execution).
2126
- * Set by path 1 of useOrbitalBridge (compiled shell — echo of the
2127
- * just-dispatched event; server-side cascade emits there carry
2128
- * `fromBridge: true` but NOT `dispatched`, so they still reach the
2129
- * source trait's transition handler, e.g. `loading -> browsing` on a
2130
- * fetch's `emit.success`) and by ServerBridge's response-cascade
2131
- * re-emit (runtime path — every response entry echoes this tab's own
2132
- * dispatch, already delivered locally via the click-time qualified
2133
- * emit / bare-cascade subscription; cross-trait `listens` don't filter
2134
- * on this flag, so their delivery is unaffected). Push-leg events from
2135
- * OTHER tabs (multiplayer) are never stamped.
2136
- */
2137
- dispatched?: boolean;
2138
- /**
2139
- * The client that originated the dispatch whose effects emitted this
2140
- * event (from `OrbitalEventRequest.clientId`); absent for headless
2141
- * dispatches (ticks, circuit-router probes, walkers). The server-side
2142
- * listens fan-out skips client-originated cascade emits — under dual
2143
- * execution the originating client relays every cascade hop through the
2144
- * bridge itself, so the server dispatching the same hop double-ran it
2145
- * (one Send persisted two rows). Headless topology keeps the fan-out:
2146
- * there is no client to drive the circuit.
2147
- */
2148
- originClientId?: string;
2149
- }
2150
- /**
2151
- * An event flowing on the bus.
2152
- *
2153
- * The `source` field is structured so cross-trait listeners can match
2154
- * `event.source?.orbital === 'X' && event.source?.trait === 'Y'` without
2155
- * parsing a delimiter.
2156
- */
2157
- interface BusEvent {
2158
- /** Event type identifier (e.g., 'CartItemLoaded', 'TASK_COMPLETED') */
2159
- type: EventKey;
2160
- /** Optional structured payload */
2161
- payload?: EventPayload;
2162
- /** Timestamp when the event was emitted */
2163
- timestamp: number;
2164
- /** Optional origin info for filtering */
2165
- source?: BusEventSource;
2166
- }
2167
- /** Bus event listener callback. */
2168
- type BusEventListener = (event: BusEvent) => void;
2169
- /** Returned by `on()` / `once()` to detach a listener. */
2170
- type Unsubscribe = () => void;
2171
-
2172
- /**
2173
- * Verification Types (framework concept)
2174
- *
2175
- * The `window.__orbitalVerification` bridge is the single observation
2176
- * point Playwright-based verifiers (`orbital-verify`, `runtime-verify`,
2177
- * `@almadar-io/verify`) use to read runtime state out of a live app.
2178
- * Its shape was previously duplicated between `@almadar/ui`'s
2179
- * `verificationRegistry.ts` (producer) and `@almadar-io/verify`'s
2180
- * `state-bridge.ts` (consumer). Every added field had to be mirrored
2181
- * by hand; one side drifting silently broke the other.
2182
- *
2183
- * Hoisting the wire types into `@almadar/core` closes that gap the same
2184
- * way {@link BusEvent} closed the UI/runtime event-shape drift. The
2185
- * registry still owns the state machine, the schedule, and the window
2186
- * exposure — this module owns only the shapes both sides agree on.
2187
- *
2188
- * @packageDocumentation
2189
- */
2190
-
2191
- /**
2192
- * Outcome of a single verification check. `warn` is non-fatal in the
2193
- * overall pass/fail tally; `pending` means the check has been registered
2194
- * but not yet resolved.
2195
- */
2196
- type CheckStatus = "pass" | "fail" | "pending" | "warn";
2197
- interface VerificationCheck {
2198
- id: string;
2199
- label: string;
2200
- status: CheckStatus;
2201
- details?: string;
2202
- /** Timestamp (ms since epoch) when the status last changed. */
2203
- updatedAt: number;
2204
- }
2205
- /**
2206
- * Trace of a single effect as it ran on a transition. `args` are the
2207
- * effect tuple's trailing S-expressions; consumers narrow via `type`
2208
- * before inspecting.
2209
- */
2210
- interface EffectTrace {
2211
- type: string;
2212
- /** For fetch/persist effects: the entity the effect addresses. */
2213
- entityName?: string;
2214
- args: SExpr[];
2215
- status: "executed" | "failed" | "skipped";
2216
- error?: string;
2217
- durationMs?: number;
2218
- }
2219
- /** What the server returned for a forwarded event. */
2220
- interface ServerResponseTrace {
2221
- orbitalName: string;
2222
- success: boolean;
2223
- clientEffects: number;
2224
- dataEntities: Record<string, number>;
2225
- emittedEvents: string[];
2226
- error?: string;
2227
- timestamp: number;
2228
- }
2229
- interface TransitionTrace {
2230
- id: string;
2231
- traitName: string;
2232
- from: string;
2233
- to: string;
2234
- event: string;
2235
- guardExpression?: string;
2236
- guardResult?: boolean;
2237
- effects: EffectTrace[];
2238
- /** Populated when the event round-tripped to the server. */
2239
- serverResponse?: ServerResponseTrace;
2240
- timestamp: number;
2241
- }
2242
- interface BridgeHealth {
2243
- connected: boolean;
2244
- eventsForwarded: number;
2245
- eventsReceived: number;
2246
- lastError?: string;
2247
- lastHeartbeat: number;
2248
- }
2249
- interface VerificationSummary {
2250
- totalChecks: number;
2251
- passed: number;
2252
- failed: number;
2253
- warnings: number;
2254
- pending: number;
2255
- }
2256
- /**
2257
- * Per-trait state snapshot exposed to the verifier so it can assert
2258
- * that reducer data (populated by fetch/persist transitions) and the
2259
- * last dispatched payload land in the DOM correctly (VG4/VG6/VG11a/b/c).
2260
- *
2261
- * Mirrors what `useTraitStateMachine` / generated trait logic hooks
2262
- * keep internally, without the verifier having to parse rendered text.
2263
- */
2264
- interface TraitStateSnapshot {
2265
- /** Trait name as declared in the schema. */
2266
- traitName: string;
2267
- /** Current state machine state. */
2268
- currentState: string;
2269
- /** Declared state names for this trait (non-empty for healthy refs). */
2270
- states: string[];
2271
- /** Declared event keys for this trait (non-empty for healthy refs). */
2272
- events: string[];
2273
- /**
2274
- * Entity data keyed by entity name. Uses {@link EntityRow} — the
2275
- * canonical persisted-entity shape the server returns and the trait
2276
- * reducer stores. Consumers that need full field-level types can cast
2277
- * down to the generated entity (e.g. `data['CartItem'] as CartItem[]`).
2278
- * Snapshot-on-read; mutating the returned arrays does not affect the
2279
- * live reducer.
2280
- */
2281
- data: Record<string, EntityRow[]>;
2282
- /** Payload of the last event the state machine processed, if any. */
2283
- lastPayload?: EventPayload;
2284
- /**
2285
- * Last event the walker (or a UI click) dispatched into this trait.
2286
- * Used by VG11a to resolve `@payload.X` expected values.
2287
- */
2288
- lastEventDispatched?: {
2289
- event: string;
2290
- payload?: EventPayload;
2291
- source?: BusEventSource;
2292
- timestamp: number;
2293
- };
2294
- /**
2295
- * Bus events received from the server's `emittedEvents` cascade
2296
- * since the last user dispatch. VG4 compares the length against the
2297
- * number of `emit: { success/failure: ... }` entries on the
2298
- * triggering transition.
2299
- */
2300
- cascadeReceived: Array<{
2301
- event: string;
2302
- payload?: EventPayload;
2303
- timestamp: number;
2304
- }>;
2305
- }
2306
- interface VerificationSnapshot {
2307
- checks: VerificationCheck[];
2308
- transitions: TransitionTrace[];
2309
- bridge: BridgeHealth | null;
2310
- summary: VerificationSummary;
2311
- /**
2312
- * Per-trait reducer snapshots. Empty on older runtimes that predate
2313
- * the Foundation 1 expansion; non-empty once any trait hook has
2314
- * registered a snapshot getter.
2315
- */
2316
- traits: TraitStateSnapshot[];
2317
- }
2318
- /** Asset load status exposed for canvas-based game verification. */
2319
- type AssetLoadStatus = "loaded" | "failed" | "pending";
2320
- /**
2321
- * Entry recorded on the verification event log. The registry ring-buffers
2322
- * the log to the last `MAX_EVENT_LOG` entries (evicting the oldest, never
2323
- * the recent tail) so long runs don't grow unbounded — see
2324
- * `verificationRegistry` and `eventLogDropped`.
2325
- */
2326
- interface EventLogEntry {
2327
- type: string;
2328
- payload?: EventPayload;
2329
- timestamp: number;
2330
- }
2331
- /**
2332
- * A drawable descriptor as exposed over the verification bridge. The
2333
- * concrete `DrawableNode` union lives downstream in `@almadar/ui`
2334
- * (`lib/drawable/paintDispatch.ts`) and cannot be imported here without
2335
- * inverting the dependency axis; the bridge contract carries the `type`
2336
- * discriminant (`draw-sprite`, `draw-shape`, …) that verifiers narrow on.
2337
- */
2338
- interface DrawableDescriptor {
2339
- type: string;
2340
- }
2341
- /**
2342
- * The object attached to `window.__orbitalVerification`. Every optional
2343
- * member is wired up by a corresponding `bind*` / `register*` call on
2344
- * the registry (e.g. `bindEventBus` populates `sendEvent`). Consumers
2345
- * should null-check before calling — an older bundle might expose only
2346
- * the core readers.
2347
- */
2348
- interface OrbitalVerificationAPI {
2349
- getSnapshot: () => VerificationSnapshot;
2350
- getChecks: () => VerificationCheck[];
2351
- getTransitions: () => TransitionTrace[];
2352
- getBridge: () => BridgeHealth | null;
2353
- getSummary: () => VerificationSummary;
2354
- /** Wait for a specific event to be processed. Resolves to null on timeout. */
2355
- waitForTransition: (event: string, timeoutMs?: number) => Promise<TransitionTrace | null>;
2356
- /**
2357
- * Send an event into the runtime. Requires {@link bindEventBus} (in
2358
- * `@almadar/ui`) to have run at least once. Payload typed as
2359
- * {@link EventPayload} so callers can't slip non-bus-shaped data in.
2360
- *
2361
- * `traitScope` is the qualified `Orbital.Trait` (or `App.Trait`)
2362
- * scope that bus listeners subscribe under. The bridge constructs
2363
- * `UI:${traitScope}.${event}` and emits that on the bus, matching
2364
- * the codegen-emitted subscription keys (gap #13). When omitted,
2365
- * the legacy bare-prefix form `UI:${event}` is used — kept only
2366
- * for system-scope events like `UI:NOTIFY`; trait-driven dispatch
2367
- * MUST pass a `traitScope`.
2368
- */
2369
- sendEvent?: (event: string, payload?: EventPayload, traitScope?: string) => void;
2370
- /** Current state name for a given trait, if known. */
2371
- getTraitState?: (traitName: string) => string | undefined;
2372
- /** Per-trait reducer snapshots (VG4/VG6/VG11a/b/c). */
2373
- getTraitSnapshots?: () => TraitStateSnapshot[];
2374
- /** Canvas frame capture. Populated by game organisms on mount. */
2375
- captureFrame?: () => string | null;
2376
- /** Last neutral drawables list received by the active canvas host. */
2377
- getLastDrawables?: () => DrawableDescriptor[] | null;
2378
- /** Asset-url → load-status map. Populated by game organisms. */
2379
- assetStatus?: Record<string, AssetLoadStatus>;
2380
- /** Rolling event bus log. Populated by `bindEventBus`. */
2381
- eventLog?: EventLogEntry[];
2382
- /**
2383
- * Per-page-load nonce, set once when `bindEventBus` creates the log
2384
- * (and bumped by `clearEventLog`). A verifier reading the log across
2385
- * hermetic page reloads uses this — not the array length — to detect a
2386
- * reset: the length can coincidentally refill to the same count after a
2387
- * reload, which silently drops the post-reload delta. The epoch changing
2388
- * is the only reliable reset signal.
2389
- */
2390
- eventLogEpoch?: string;
2391
- /**
2392
- * Count of entries evicted from the FRONT of the ring-buffered log this
2393
- * page (see `MAX_EVENT_LOG`). The absolute index of `eventLog[i]` is
2394
- * `eventLogDropped + i`, so a verifier can cursor by absolute position
2395
- * even after eviction — the recent (driven) tail is never silently lost.
2396
- */
2397
- eventLogDropped?: number;
2398
- /** Clear the event log in place (also bumps `eventLogEpoch`). */
2399
- clearEventLog?: () => void;
2400
- }
2401
-
2402
- /**
2403
- * Canonical SSE event types for the Almadar agent wire.
2404
- *
2405
- * These events are emitted by the rabit runtime (internal package
2406
- * `@almadar-io/rabit`) and consumed by public SDK clients. Because the rabit
2407
- * package is private, the SDK-relevant subset of the event surface is hoisted
2408
- * here into `@almadar/core` so public consumers can type their `onEvent`
2409
- * callbacks without depending on a private package.
2410
- *
2411
- * Rules for this file:
2412
- * - Use only types already exported by `@almadar/core`.
2413
- * - Do not import from `@almadar-io/rabit` or any other private package.
2414
- * - Keep the discriminated union exhaustive over the included event types.
2415
- */
2416
-
2417
- type SSEEventType = 'start' | 'message' | 'tool_call' | 'tool_result' | 'todo_update' | 'todo_detail' | 'file_operation' | 'file_written' | 'schema_update' | 'generation_log' | 'subagent_event' | 'subagent_start' | 'subagent_progress' | 'subagent_complete' | 'interrupt' | 'error' | 'cancelled' | 'complete' | 'app_created' | 'schema_phase_validated' | 'schema_phase_update' | 'orbital_added' | 'orbital_schema_complete' | 'process_start' | 'process_complete' | 'process_error' | 'process_repair' | 'process_repair_complete' | 'params_repair_emitted' | 'changeset_recorded' | 'snapshot_created';
2418
- interface SSEEventBase {
2419
- type: SSEEventType;
2420
- timestamp: number;
2421
- }
2422
- interface StartEvent extends SSEEventBase {
2423
- type: 'start';
2424
- data: {
2425
- threadId: string;
2426
- skill: string;
2427
- workDir: string;
2428
- };
2429
- }
2430
- interface MessageEvent extends SSEEventBase {
2431
- type: 'message';
2432
- data: {
2433
- content: string;
2434
- role: 'assistant' | 'user' | 'system';
2435
- isComplete: boolean;
2436
- };
2437
- }
2438
- interface ToolCallEvent extends SSEEventBase {
2439
- type: 'tool_call';
2440
- data: {
2441
- tool: string;
2442
- args: ToolArgs;
2443
- };
2444
- }
2445
- interface ToolResultEvent extends SSEEventBase {
2446
- type: 'tool_result';
2447
- data: {
2448
- tool: string;
2449
- result: JsonValue;
2450
- success: boolean;
2451
- };
2452
- }
2453
- interface TodoUpdateEvent extends SSEEventBase {
2454
- type: 'todo_update';
2455
- data: {
2456
- todos: Array<{
2457
- id: string;
2458
- task: string;
2459
- status: 'pending' | 'in_progress' | 'completed';
2460
- }>;
2461
- };
2462
- }
2463
- type TodoActivityType = 'thinking' | 'tool_call' | 'tool_result' | 'code_change';
2464
- interface TodoDetailEvent extends SSEEventBase {
2465
- type: 'todo_detail';
2466
- data: {
2467
- todoId: string;
2468
- activityType: TodoActivityType;
2469
- content: string;
2470
- tool?: string;
2471
- args?: ToolArgs;
2472
- success?: boolean;
2473
- filePath?: string;
2474
- diff?: string;
2475
- };
2476
- }
2477
- interface FileOperationEvent extends SSEEventBase {
2478
- type: 'file_operation';
2479
- data: {
2480
- operation: 'ls' | 'read_file' | 'write_file' | 'edit_file';
2481
- path: string;
2482
- success: boolean;
2483
- };
2484
- }
2485
- interface FileWrittenEvent extends SSEEventBase {
2486
- type: 'file_written';
2487
- data: {
2488
- path: string;
2489
- fileType: 'schema' | 'orbital' | 'memory' | 'domain' | 'other';
2490
- orbitalName?: string;
2491
- };
2492
- }
2493
- interface SchemaUpdateEvent extends SSEEventBase {
2494
- type: 'schema_update';
2495
- data: {
2496
- appId: string;
2497
- version: number;
2498
- schema: OrbitalSchema;
2499
- isNew: boolean;
2500
- snapshotId?: string;
2501
- changesetId?: string;
2502
- };
2503
- }
2504
- interface GenerationLogEvent extends SSEEventBase {
2505
- type: 'generation_log';
2506
- data: {
2507
- level: 'info' | 'warn' | 'error' | 'debug';
2508
- message: string;
2509
- data?: JsonObject;
2510
- orbitalName?: string;
2511
- };
2512
- }
2513
- interface SubagentEvent extends SSEEventBase {
2514
- type: 'subagent_event';
2515
- data: {
2516
- orbitalName: string;
2517
- orbitalIndex: number;
2518
- totalOrbitals: number;
2519
- event: {
2520
- type: Exclude<SSEEventType, 'subagent_event'>;
2521
- data: JsonObject;
2522
- timestamp: number;
2523
- };
2524
- };
2525
- }
2526
- interface SubagentStartEvent extends SSEEventBase {
2527
- type: 'subagent_start';
2528
- data: {
2529
- subagentId: string;
2530
- name: string;
2531
- role: string;
2532
- orbitalName?: string;
2533
- parentId?: string;
2534
- task: string;
2535
- };
2536
- }
2537
- interface SubagentProgressEvent extends SSEEventBase {
2538
- type: 'subagent_progress';
2539
- data: {
2540
- subagentId: string;
2541
- orbitalName?: string;
2542
- message: string;
2543
- toolCall?: {
2544
- tool: string;
2545
- argsPreview?: string;
2546
- };
2547
- };
2548
- }
2549
- interface SubagentCompleteEvent extends SSEEventBase {
2550
- type: 'subagent_complete';
2551
- data: {
2552
- subagentId: string;
2553
- orbitalName?: string;
2554
- success: boolean;
2555
- durationMs: number;
2556
- summary?: string;
2557
- };
2558
- }
2559
- interface InterruptEvent extends SSEEventBase {
2560
- type: 'interrupt';
2561
- data: {
2562
- threadId: string;
2563
- actionRequests: Array<{
2564
- tool: string;
2565
- args: ToolArgs;
2566
- allowedDecisions: ('approve' | 'edit' | 'reject')[];
2567
- description?: string;
2568
- }>;
2569
- };
2570
- }
2571
- interface ErrorEvent extends SSEEventBase {
2572
- type: 'error';
2573
- data: {
2574
- error: string;
2575
- code?: string;
2576
- /** Orbital names that failed, when a generation run ends in failure. */
2577
- failedOrbitals?: string[];
2578
- /** Typed validate/failure lines backing `error` (same format as `cache_demoted.errors`). */
2579
- errors?: string[];
2580
- };
2581
- }
2582
- interface CancelledEvent extends SSEEventBase {
2583
- type: 'cancelled';
2584
- data: {
2585
- threadId: string;
2586
- message: string;
2587
- };
2588
- }
2589
- interface CompleteEvent extends SSEEventBase {
2590
- type: 'complete';
2591
- data: {
2592
- threadId: string;
2593
- skill: string;
2594
- workDir: string;
2595
- schemaGenerated: boolean;
2596
- appCompiled: boolean;
2597
- schema?: OrbitalSchema;
2598
- appId?: string;
2599
- schemaPersisted?: boolean;
2600
- snapshotId?: string;
2601
- changesetId?: string;
2602
- };
2603
- }
2604
- interface AppCreatedEvent extends SSEEventBase {
2605
- type: 'app_created';
2606
- data: {
2607
- appId: string;
2608
- name?: string;
2609
- orbitalCount?: number;
2610
- fromOrbitalPersistence?: boolean;
2611
- };
2612
- }
2613
- interface SchemaPhaseValidatedEvent extends SSEEventBase {
2614
- type: 'schema_phase_validated';
2615
- data: {
2616
- appId: string;
2617
- success: boolean;
2618
- errors?: JsonValue[];
2619
- };
2620
- }
2621
- interface SchemaPhaseUpdateEvent extends SSEEventBase {
2622
- type: 'schema_phase_update';
2623
- data: JsonObject;
2624
- }
2625
- interface OrbitalAddedEvent extends SSEEventBase {
2626
- type: 'orbital_added';
2627
- data: {
2628
- appId: string;
2629
- orbitalName: string;
2630
- orbitalIndex: number;
2631
- totalOrbitals: number;
2632
- isNew?: boolean;
2633
- orbitalSchema?: OrbitalDefinition;
2634
- };
2635
- }
2636
- interface OrbitalSchemaCompleteEvent extends SSEEventBase {
2637
- type: 'orbital_schema_complete';
2638
- data: {
2639
- appId: string;
2640
- totalOrbitals: number;
2641
- orbitalNames: string[];
2642
- };
2643
- }
2644
- interface ProcessStartEvent extends SSEEventBase {
2645
- type: 'process_start';
2646
- data: {
2647
- orbitalName: string;
2648
- method: 'deterministic' | 'llm';
2649
- behavior?: string;
2650
- };
2651
- }
2652
- interface ProcessCompleteEvent extends SSEEventBase {
2653
- type: 'process_complete';
2654
- data: {
2655
- orbitalName: string;
2656
- method: 'deterministic' | 'llm';
2657
- traitCount?: number;
2658
- transitionCount?: number;
2659
- duration?: number;
2660
- };
2661
- }
2662
- interface ProcessErrorEvent extends SSEEventBase {
2663
- type: 'process_error';
2664
- data: {
2665
- orbitalName: string;
2666
- method: 'deterministic' | 'llm';
2667
- error: string;
2668
- /** Typed validate/failure lines for this orbital (from `orbital_failed.errors`). */
2669
- errors?: string[];
2670
- };
2671
- }
2672
- interface ProcessRepairEvent extends SSEEventBase {
2673
- type: 'process_repair';
2674
- data: {
2675
- orbitalName: string;
2676
- errorCount: number;
2677
- attempt: number;
2678
- };
2679
- }
2680
- interface ProcessRepairCompleteEvent extends SSEEventBase {
2681
- type: 'process_repair_complete';
2682
- data: {
2683
- orbitalName: string;
2684
- };
2685
- }
2686
- interface ParamsRepairEmittedEvent extends SSEEventBase {
2687
- type: 'params_repair_emitted';
2688
- data: {
2689
- orbitalName: string;
2690
- attempt: number;
2691
- };
2692
- }
2693
- interface ChangesetRecordedEvent extends SSEEventBase {
2694
- type: 'changeset_recorded';
2695
- data: {
2696
- appId: string;
2697
- changesetId: string;
2698
- version: number;
2699
- trackingMode: 'initial' | 'update';
2700
- summary: {
2701
- added: number;
2702
- modified: number;
2703
- removed: number;
2704
- };
2705
- source?: string;
2706
- };
2707
- }
2708
- interface SnapshotCreatedEvent extends SSEEventBase {
2709
- type: 'snapshot_created';
2710
- data: {
2711
- appId: string;
2712
- snapshotId: string;
2713
- version: number;
2714
- reason: string;
2715
- };
2716
- }
2717
- type SSEEvent = StartEvent | MessageEvent | ToolCallEvent | ToolResultEvent | TodoUpdateEvent | TodoDetailEvent | FileOperationEvent | FileWrittenEvent | SchemaUpdateEvent | GenerationLogEvent | SubagentEvent | SubagentStartEvent | SubagentProgressEvent | SubagentCompleteEvent | InterruptEvent | ErrorEvent | CancelledEvent | CompleteEvent | AppCreatedEvent | SchemaPhaseValidatedEvent | SchemaPhaseUpdateEvent | OrbitalAddedEvent | OrbitalSchemaCompleteEvent | ProcessStartEvent | ProcessCompleteEvent | ProcessErrorEvent | ProcessRepairEvent | ProcessRepairCompleteEvent | ParamsRepairEmittedEvent | ChangesetRecordedEvent | SnapshotCreatedEvent;
2718
-
2719
- /**
2720
- * Living Orbital Schema — Golden Data Structure type system.
2721
- *
2722
- * The Living layer treats an `OrbitalSchema` as a heterogeneous attributed
2723
- * graph: every vertex (orbital, entity, trait, state, transition, page, field,
2724
- * event, effect, config-knob) carries a `SemanticAnnotation` + an embedding
2725
- * vector, and the whole object can embed / validate / compile / similarity-
2726
- * search / evolve itself. These are the canonical TYPE definitions shared by
2727
- * the masar (Python) implementation and any TS implementation (rabit, Phase 5);
2728
- * the numeric implementation lives outside @almadar/core.
2729
- *
2730
- * See `docs/Almadar_Masar_Golden_Data_Structure.md` §II/§III/§VIII. Existing
2731
- * core vocabulary is reused, never re-defined: `SchemaChange`/`SemanticChangeKind`
2732
- * (changeset.ts) back the evolution delta, `ValidationError`/`ValidationResult`
2733
- * (validation.ts) back `validate()`, and the per-vertex payloads ARE the existing
2734
- * structural types.
2735
- *
2736
- * @packageDocumentation
2737
- */
2738
-
2739
- /**
2740
- * Decision-kind tier for the annotation layer. SUPERSET of the validator-
2741
- * enforced `FactoryConfigTier` (`domain`/`policy`/`infra`/`presentation`/
2742
- * `internal`), adding `essential` and `customization` for non-knob (event)
2743
- * vertices that still carry the old vocabulary. Every `FactoryConfigTier`
2744
- * value must be a member so `widenTier` stays a valid identity widen.
2745
- */
2746
- type AnnotationTier = "essential" | "domain" | "policy" | "infra" | "presentation" | "customization" | "internal";
2747
- /** Widen a knob's `FactoryConfigTier` into the annotation-layer `AnnotationTier`. */
2748
- declare function widenTier(tier: FactoryConfigTier): AnnotationTier;
2749
- /**
2750
- * The natural-language metadata attached to every living vertex — the text that
2751
- * gets embedded for `similar()`/`match_intent()`. Today these four members live
2752
- * scattered inline across core types (`EntityField.description`/`synonyms`,
2753
- * `Event`/`TraitEventContract`.`description`/`synonyms`/`tier`,
2754
- * `FactoryConfigParam.label`/`description`/`synonyms`/`tier`); `SemanticAnnotation`
2755
- * is the uniform bundle of them, generalized to every vertex.
2756
- */
2757
- interface SemanticAnnotation {
2758
- description: string;
2759
- synonyms: string[];
2760
- label: string;
2761
- tier: AnnotationTier;
2762
- }
2763
- /**
2764
- * A dense semantic embedding. In-memory form is `Float32Array`; the at-rest
2765
- * JSON form (e.g. rabit's `knob-embeddings.json`) is `number[]`.
2766
- */
2767
- type SemanticVector = Float32Array;
2768
- /** A probability in `[0, 1]`. */
2769
- type Probability = number;
2770
- /** Whether a semantic gate's transition is open, closed, or ~0.5 ambiguous. */
2771
- type GateState = "open" | "closed" | "ambiguous";
2772
- /** The typed vertex kinds of the living attributed graph (§II.1 `V_*`). */
2773
- type VertexType = "orbital" | "entity" | "trait" | "state" | "transition" | "page" | "field" | "event" | "effect" | "value";
2774
- /**
2775
- * A stable, structural, embedding-independent vertex id (path style, e.g.
2776
- * `orb:Cart/trt:AddItem/st:Open`). Re-embedding never changes it.
2777
- */
2778
- type VertexId = string;
2779
- /** The typed directed edge kinds of the living attributed graph (§II.1 `E_*`). */
2780
- type EdgeType = "belongs_to" | "has_trait" | "has_state" | "has_transition" | "from_state" | "to_state" | "on_event" | "emits" | "listens" | "cross_orbital" | "has_effect" | "effect_seq" | "data_flow" | "ref_in_effect" | "has_page" | "has_field" | "ref";
2781
- /**
2782
- * An effect vertex's payload. Effects are positional S-expression tuples
2783
- * (`Effect`), so the synthesized coordinates (operator, owning transition,
2784
- * positional index) carry the addressing the raw tuple lacks.
2785
- */
2786
- interface EffectPayload {
2787
- sexpr: Effect;
2788
- operator: string;
2789
- transitionId: VertexId;
2790
- index: number;
2791
- }
2792
- /**
2793
- * A config-knob vertex's payload — joins a `Trait.config` dict key with its
2794
- * declaration (no single core type carries both).
2795
- */
2796
- interface KnobPayload {
2797
- name: string;
2798
- declaration: ConfigFieldDeclaration;
2799
- traitId: VertexId;
2800
- }
2801
- /** The union of every kind of vertex payload (the existing structural types). */
2802
- type VertexPayload = OrbitalDefinition | Entity | Trait | State | Transition | Page | EntityField | Event | EffectPayload | KnobPayload;
2803
- /**
2804
- * One vertex of the living graph: a structural payload plus its annotation and
2805
- * embedding. Identity is `id` (structural); annotation/embedding are derived.
2806
- */
2807
- interface LivingVertex<P extends VertexPayload = VertexPayload> {
2808
- id: VertexId;
2809
- vtype: VertexType;
2810
- payload: P;
2811
- annotation: SemanticAnnotation;
2812
- /** Lazily populated — undefined until the schema's `embed()` runs. */
2813
- embedding?: SemanticVector;
2814
- }
2815
- type LivingOrbital = LivingVertex<OrbitalDefinition>;
2816
- type LivingEntity = LivingVertex<Entity>;
2817
- type LivingTrait = LivingVertex<Trait>;
2818
- type LivingState = LivingVertex<State>;
2819
- type LivingTransition = LivingVertex<Transition>;
2820
- type LivingPage = LivingVertex<Page>;
2821
- type LivingField = LivingVertex<EntityField>;
2822
- type LivingEvent = LivingVertex<Event>;
2823
- type LivingEffect = LivingVertex<EffectPayload>;
2824
- type LivingValue = LivingVertex<KnobPayload>;
2825
- /**
2826
- * One directed edge. `via` carries the transition vertex for the ternary
2827
- * `has_transition(from, via, to)` decomposition; `seq` carries the ordering for
2828
- * `effect_seq`.
2829
- */
2830
- interface LivingEdge {
2831
- etype: EdgeType;
2832
- src: VertexId;
2833
- dst: VertexId;
2834
- via?: VertexId;
2835
- seq?: number;
2836
- }
2837
- /**
2838
- * A single evolution step over the living graph. `modified` reuses the canonical
2839
- * `SchemaChange` (changeset.ts) rather than inventing a parallel operation enum;
2840
- * `intent` is the natural-language delta that caused the change.
2841
- */
2842
- interface EvolutionDelta {
2843
- added: VertexId[];
2844
- removed: VertexId[];
2845
- modified: SchemaChange[];
2846
- intent: string;
2847
- }
2848
- /** One immutable entry in a living schema's evolution lineage (§6.2). */
2849
- interface LineageEntry {
2850
- root: string;
2851
- parent: string;
2852
- delta: EvolutionDelta;
2853
- intent: string;
2854
- time: number;
2855
- valid: boolean;
2856
- }
2857
- /** The result of simulating one effect's S-expression (§4.6) — pure, no I/O. */
2858
- interface EffectResult {
2859
- result: SExpr;
2860
- sideEffects: string[];
2861
- emittedEvents: string[];
2862
- }
2863
- /**
2864
- * The operation surface of a living orbital schema. This interface is the shared
2865
- * CONTRACT; the numeric implementation (embedding, cosine, validator shelling)
2866
- * is language-specific. `compile()` is the bridge back to the canonical
2867
- * `OrbitalSchema` (the ML surface — annotations beyond `description`, embeddings,
2868
- * gates — is stripped).
2869
- */
2870
- interface LivingOrbitalSchema {
2871
- orbitals: LivingOrbital[];
2872
- addOrbital(name: string): LivingOrbital;
2873
- removeOrbital(name: string): void;
2874
- getOrbital(name: string): LivingOrbital;
2875
- annotations: Map<VertexId, SemanticAnnotation>;
2876
- embeddings: Map<VertexId, SemanticVector>;
2877
- embed(): void;
2878
- compile(): OrbitalSchema;
2879
- validate(): ValidationResult;
2880
- similar(query: string | SemanticVector, k: number, type?: VertexType): LivingVertex[];
2881
- matchIntent(intent: string, threshold?: number): {
2882
- vertex: LivingVertex;
2883
- score: number;
2884
- }[];
2885
- predictConfig(intent: string, trait: Trait): Record<string, TraitConfigValue>;
2886
- predictPresence(intent: string): Set<string>;
2887
- suggestOrbital(intent: string): LivingOrbital[];
2888
- suggestEntity(intent: string): LivingEntity[];
2889
- suggestTrait(intent: string): LivingTrait[];
2890
- evolve(intentDelta: string): LivingOrbitalSchema;
2891
- compose(other: LivingOrbitalSchema): LivingOrbitalSchema;
2892
- repair(errors: ValidationError[]): LivingOrbitalSchema;
2893
- wireEvents(source: LivingEvent, target: LivingEvent): void;
2894
- findWiringGaps(): LivingEvent[];
2895
- simulateEffect(effect: LivingEffect, context: EvalContext): EffectResult;
2896
- simulateInteraction(effect: LivingEffect, path: string[]): {
2897
- event: LivingEvent;
2898
- payload: EventPayload;
2899
- };
2900
- traceDataFlow(transition: LivingTransition, inputEntity: LivingEntity): LivingEffect[];
2901
- evaluateGates(intentEmbedding: SemanticVector): Map<VertexId, GateState[]>;
2902
- sampleTrajectory(intentEmbedding: SemanticVector, steps: number): LivingVertex[];
2903
- lineage: LineageEntry[];
2904
- checkout(hash: string): LivingOrbitalSchema;
2905
- diff(hash1: string, hash2: string): EvolutionDelta;
2906
- }
2907
-
2908
- /**
2909
- * Parsed AST — LLM-emit relaxed views of the canonical orbital types.
2910
- *
2911
- * Every `Parsed*` type mirrors its canonical counterpart in this module
2912
- * (`Trait`, `StateMachine`, `Transition`, `State`, `Event`, `OrbitalDefinition`,
2913
- * `PageRefObject`, etc.) but loosens required fields to optional. The
2914
- * loosening exists for one reason: the LLM can emit a partial orbital
2915
- * (mid-stream, mid-tool-call, mid-LoLo lowering) and consumer code
2916
- * needs to walk it WITHOUT casting to the strict canonical type before
2917
- * every field access.
2918
- *
2919
- * Discipline:
2920
- *
2921
- * - **No `unknown`.** Every field has a concrete type, sourced from
2922
- * this same module where the type already exists (`EntityField`,
2923
- * `EntityPersistence`, `TraitCategory`, `TraitScope`, `SExpr`,
2924
- * `PageTraitRef`, `TraitEventContract`, `TraitEventListener`).
2925
- *
2926
- * - **No index signatures.** If the LLM emits a key the schema doesn't
2927
- * know about, the validator rejects it. The `Parsed*` types do not
2928
- * pretend to accept unknown keys at the type level.
2929
- *
2930
- * - **Required fields stay required.** `name` on `ParsedOrbital` is
2931
- * required because no orbital can exist without one. `name` /
2932
- * `linkedEntity` on `ParsedTrait` are required because the orbital
2933
- * compiler rejects traits missing either. Only fields the LLM
2934
- * legitimately omits during construction are optional.
2935
- *
2936
- * Use site: walkers that observe an orbital before it's fully
2937
- * validated. Construct it as `ParsedOrbital`, narrow to
2938
- * `OrbitalDefinition` after validation.
2939
- *
2940
- * @packageDocumentation
2941
- */
2942
-
2943
- /**
2944
- * Top-level orbital as the LLM emits it. Relaxed view of
2945
- * `OrbitalDefinition`: traits and pages may be partial, the domain
2946
- * context + design hints may be missing.
2947
- */
2948
- interface ParsedOrbital {
2949
- name: string;
2950
- entity: ParsedEntity;
2951
- traits: ParsedTrait[];
2952
- pages: ParsedPage[];
2953
- domainContext?: ParsedDomainContext;
2954
- design?: ParsedDesign;
2955
- }
2956
- /**
2957
- * Entity nucleus of an orbital. `name` + `fields` are required; the
2958
- * factory canonical defaults can fill `persistence` and `collection`
2959
- * when omitted.
2960
- */
2961
- interface ParsedEntity {
2962
- name: string;
2963
- fields: EntityField[];
2964
- persistence?: EntityPersistence;
2965
- collection?: string;
2966
- }
2967
- /**
2968
- * One trait on an orbital. `name` + `linkedEntity` are required (the
2969
- * compiler rejects either omission); state machine + scope + category
2970
- * are filled by defaults when the LLM doesn't specify them.
2971
- */
2972
- interface ParsedTrait {
2973
- name: string;
2974
- linkedEntity: string;
2975
- category?: TraitCategory;
2976
- scope?: TraitScope;
2977
- description?: string;
2978
- config?: ParsedTraitConfig;
2979
- emits?: ParsedEmitDeclaration[];
2980
- listens?: ParsedListenDeclaration[];
2981
- stateMachine?: ParsedStateMachine;
2982
- capabilities?: string[];
2983
- }
2984
- /**
2985
- * Trait `config { }` block — the LLM-emit shape carries each declared
2986
- * config key as a typed value drawn from the JSON primitive set. A
2987
- * stricter view (`DeclaredTraitConfig` in `trait.ts`) captures the
2988
- * authored field descriptors with type+default+label+tier metadata;
2989
- * `ParsedTraitConfig` is the in-flight value map.
2990
- */
2991
- type ParsedTraitConfig = {
2992
- [key: string]: string | number | boolean | null | ReadonlyArray<string | number | boolean | null>;
2993
- };
2994
- /**
2995
- * State-machine of a trait. Every field optional because the LLM may
2996
- * emit the trait header before its body. A canonical
2997
- * `StateMachine` (`state-machine.ts`) requires at least one state +
2998
- * one transition.
2999
- */
3000
- interface ParsedStateMachine {
3001
- states?: ParsedState[];
3002
- events?: ParsedEvent[];
3003
- transitions?: ParsedTransition[];
3004
- initial?: string;
3005
- }
3006
- /**
3007
- * One state of a `ParsedStateMachine`. Mirrors `State` from
3008
- * `state-machine.ts` with name optional during construction.
3009
- */
3010
- interface ParsedState {
3011
- name?: string;
3012
- isInitial?: boolean;
3013
- }
3014
- /**
3015
- * One event of a `ParsedStateMachine`. Mirrors `Event` from
3016
- * `state-machine.ts`. `payloadSchema` is the canonical shape — an
3017
- * array of `EntityField`s describing the event's payload.
3018
- */
3019
- interface ParsedEvent {
3020
- key?: string;
3021
- name?: string;
3022
- payloadSchema?: EntityField[];
3023
- }
3024
- /**
3025
- * One transition of a `ParsedStateMachine`. `effects` + `guard` use
3026
- * `SExpr` from `expression.ts` — the canonical S-expression shape the
3027
- * runtime evaluates.
3028
- */
3029
- interface ParsedTransition {
3030
- from?: string;
3031
- to?: string;
3032
- event?: string;
3033
- effects?: SExpr[];
3034
- guard?: SExpr;
3035
- }
3036
- /**
3037
- * Trait-emit declaration. Aliases `TraitEventContract` from
3038
- * `trait.ts` with every field optional. The canonical contract
3039
- * carries `event`, `scope`, `payload`; here all three are optional so
3040
- * an in-flight emit (just the name, no payload yet) types correctly.
3041
- */
3042
- interface ParsedEmitDeclaration {
3043
- event?: string;
3044
- scope?: 'internal' | 'external';
3045
- payload?: EntityField[];
3046
- }
3047
- /**
3048
- * Trait-listen declaration. Mirrors `TraitEventListener` from
3049
- * `trait.ts` with the source remap and trigger key optional.
3050
- */
3051
- interface ParsedListenDeclaration {
3052
- event?: string;
3053
- triggers?: string;
3054
- scope?: 'internal' | 'external';
3055
- payloadMapping?: {
3056
- [key: string]: SExpr;
3057
- };
3058
- }
3059
- /**
3060
- * One page entry on an orbital. Mirrors `PageRefObject` /
3061
- * `OrbitalPage`; `path` is the URL, `name` is the canonical
3062
- * identifier the molecule references.
3063
- */
3064
- interface ParsedPage {
3065
- path?: string;
3066
- name?: string;
3067
- primaryEntity?: string;
3068
- traits?: PageTraitRef[];
3069
- }
3070
- /**
3071
- * Domain-context decorations the analyzer attaches to an orbital
3072
- * (vocabulary, category, original request). Mirrors `DomainContext`
3073
- * from `domain.ts` for the fields used in the parsed-AST surface; the
3074
- * full `DomainContext` carries semantic-role overlays + custom-pattern
3075
- * maps too, which the LLM doesn't emit in this surface.
3076
- */
3077
- interface ParsedDomainContext {
3078
- request?: string;
3079
- category?: string;
3080
- vocabulary?: {
3081
- [key: string]: string;
3082
- };
3083
- }
3084
- /**
3085
- * Design hints (style + UX cues) the analyzer attaches. Mirrors
3086
- * `DesignPreferences` from `domain.ts`.
3087
- */
3088
- interface ParsedDesign {
3089
- style?: string;
3090
- uxHints?: {
3091
- [key: string]: string;
3092
- };
3093
- }
3094
-
3095
- export { ANONYMOUS_USER, type AgentCodeSearchResult, type AgentCompactResult, type AgentCompactStrategy, type AgentContext, type AgentGenerateOptions, type AgentMemoryCategory, type AgentMemoryRecord, type AnalysisOrbital, type AnalysisOrbitalParams, type AnalysisPageOverride, type AnalysisRename, type AnalysisResult, type AnnotationTier, type AppCreatedEvent, OrbitalSchema as AppSchema, type AppSummary, type AssetLoadStatus, BINDING_CONTEXT_RULES, BINDING_DOCS, BINDING_ROOTS, type BindingContext, type BindingRoot, BindingSchema, type BridgeHealth, type BuilderResult, type BusEvent, type BusEventListener, type BusEventSource, type CancelledEvent, type CategorizedRemovals, type ChangeAuthor, type ChangeSetDocument, type ChangeSummary, type ChangesetRecordedEvent, type ChangesetValue, type CheckStatus, type Clarification, type ClarificationCandidate, type ClarificationLevel, type CompleteEvent, type ComplexityAssessment, type ComposeAllResult, type ComposeChildrenResult, type ComposeOptions, ConfigFieldDeclaration, type ContextExtensions, type CreateFlow, DEFAULT_INTERACTION_MODELS, DEFAULT_VIEWER, DEV_TOKEN_PREFIX, DeclaredTraitConfig, type DeleteFlow, type DispatchUpdatesResult, DomainContext, type DrawableDescriptor, type EdgeType, type EditFlow, Effect, type EffectPayload, type EffectResult, type EffectTrace, Entity, EntityField, EntityPersistence, EntityRow, type ErrorEvent, EvalContext, Event, type EventEmit, EventId, type EventKey, type EventListen, type EventLogEntry, EventPayload, EventPayloadValue, type EvolutionDelta, type ExecutePlanResult, type ExtraTraitRef, FieldValue, type FileOperationEvent, type FileWrittenEvent, Orbital as FullOrbitalUnit, type GateState, type GenerationLogEvent, type GitHubIssue, type GitHubLink, type GitHubRepo, type HistoryMeta, type IntegrationContext, type InteractionModel, type InteractionModelInput, InteractionModelSchema, type InterruptEvent, JsonObject, JsonValue, KNOWN_VALIDATION_ERROR_CODES, type KnobPayload, type KnownValidationErrorCode, type LLMErrorContext, type LazyService, type LineageEntry, type ListInteraction, ListenSource, type LivingEdge, type LivingEffect, type LivingEntity, type LivingEvent, type LivingField, type LivingOrbital, type LivingOrbitalSchema, type LivingPage, type LivingState, type LivingTrait, type LivingTransition, type LivingValue, type LivingVertex, type LlmCallToolsResult, type LlmContext, type LlmMessage, type LlmTokenUsage, type LlmToolCall, type LlmToolDef, LogMeta, type LoloEmitResult, type MemoryContext, type MessageEvent, Orbital, type OrbitalAddedEvent, OrbitalDefinition, OrbitalId, OrbitalSchema, type OrbitalSchemaCompleteEvent, type OrbitalVerificationAPI, Page, type PageContentReduction, PageTraitRef, type ParamsRepairEmittedEvent, type ParsedDesign, type ParsedDomainContext, type ParsedEmitDeclaration, type ParsedEntity, type ParsedEvent, type ParsedListenDeclaration, type ParsedOrbital, type ParsedPage, type ParsedState, type ParsedStateMachine, type ParsedTrait, type ParsedTraitConfig, type ParsedTransition, PatternTypeSchema, type PersistActionName, type PlanSnapshot, type PlanSnapshotStatus, type PlannerResult, type Probability, type ProcessCompleteEvent, type ProcessErrorEvent, type ProcessRepairCompleteEvent, type ProcessRepairEvent, type ProcessStartEvent, RENDER_BINDING_MARKER, type RawUserClaims, type RenderBindingMarker, type RepairResult, type ResolvedEntity, type ResolvedEntityBinding, type ResolvedField, type ResolvedIR, type ResolvedNavigation, type ResolvedPage, type ResolvedPattern, type ResolvedSection, type ResolvedSectionEvent, type ResolvedTrait, type ResolvedTraitBinding, type ResolvedTraitDataEntity, type ResolvedTraitEvent, type ResolvedTraitGuard, type ResolvedTraitListener, type ResolvedTraitState, type ResolvedTraitTick, type ResolvedTraitTransition, type ResolvedTraitUIBinding, RuntimeValue, SExpr, type SSEEvent, type SSEEventBase, type SSEEventType, type SaveOptions, type SaveResult, type SchemaChange, type SchemaPhaseUpdateEvent, type SchemaPhaseValidatedEvent, type SchemaUpdateEvent, type SemanticAnnotation, type SemanticChangeKind, type SemanticSchemaChange, type SemanticVector, type ServerResponseTrace, type ServiceAction, type ServiceActionName, type ServiceCallResult, type ServiceContract, type ServiceEvents, ServiceParams, type SessionContext, type SessionHistoryEntry, type SnapshotCreatedEvent, type SnapshotDocument, type SpawnResult, type StartEvent, State, type StatsView, type StoreContract, type StoreFilter, type StoreFilterOp, type SubagentCompleteEvent, type SubagentEvent, type SubagentProgressEvent, type SubagentStartEvent, ThemeDefinition, type TodoActivityType, type TodoDetailEvent, type TodoUpdateEvent, ToolArgs, type ToolCallEvent, type ToolResultEvent, type TraceContext, Trait, TraitCategory, TraitConfig, TraitConfigValue, type TraitFieldRef, TraitFieldRefSchema, TraitId, TraitReference, type TraitStateSnapshot, Transition, type TransitionFrom, type TransitionTrace, type Unsubscribe, type UserContext, type ValidateResult, OrbitalDefinition as ValidatedOrbital, type ValidationDocument, type ValidationError, type ValidationErrorCode, type ValidationIssue, type ValidationMeta, type ValidationResult, type ValidationResults, type VerificationCheck, type VerificationSnapshot, type VerificationSummary, type VertexId, type VertexPayload, type VertexType, type ViewFlow, type WorkspaceContext, containsEntityBinding, containsPayloadBinding, createEmptyResolvedPage, createEmptyResolvedTrait, createLazyService, createResolvedField, createTypedEventBus, decodeDevIdentityToken, encodeDevIdentityToken, findPersonaInRoster, getBindingExamples, getInteractionModelForDomain, inferTsType, isKnownValidationErrorCode, isPlanSnapshot, isRenderBindingMarker, isResolvedIR, isSessionHistoryEntry, isTraitFieldRef, normalizeUserContext, personaFromIdentityRow, resolveDefaultViewer, resolvePersonaSpec, toBindingRoot, validateBindingInContext, widenTier };
1
+ export { A as AGENT_DOMAIN_CATEGORIES, f as ALLOWED_CUSTOM_COMPONENTS, g as AgentDomainCategory, h as AgentDomainCategorySchema, i as AllowedCustomComponent, O as AppSchema, C as ColorSlice, j as ColorSliceSchema, k as ColorTokens, l as ColorTokensSchema, m as ComputedEventContract, n as ComputedEventContractSchema, o as ComputedEventListener, p as ComputedEventListenerSchema, q as ConfigProvenanceRecord, r as ConfigProvenanceRecordSchema, s as CustomPatternDefinition, t as CustomPatternDefinitionInput, u as CustomPatternDefinitionSchema, v as CustomPatternMap, w as CustomPatternMapInput, x as CustomPatternMapSchema, D as DensitySlice, y as DensitySliceSchema, z as DensityTokens, B as DensityTokensSchema, F as DesignPreferences, G as DesignPreferencesInput, H as DesignPreferencesSchema, I as DesignTokens, J as DesignTokensInput, K as DesignTokensSchema, L as DomainCategory, M as DomainCategorySchema, N as DomainContext, Q as DomainContextInput, R as DomainContextSchema, S as DomainVocabulary, T as DomainVocabularySchema, V as ElevationSlice, W as ElevationSliceSchema, X as ElevationTokens, Y as ElevationTokensSchema, Z as EntityCall, _ as EntityCallSchema, E as EntityRef, $ as EntityRefSchema, a0 as EntityRefStringSchema, a1 as EntitySemanticRole, a2 as EntitySemanticRoleSchema, a3 as EventListener, a4 as EventListenerSchema, a5 as EventSemanticRole, a6 as EventSemanticRoleSchema, a7 as EventSource, a8 as EventSourceSchema, b as ExpectDeclaration, a9 as ExpectDeclarationSchema, aa as FullOrbitalUnit, ab as GameSubCategory, ac as GameSubCategorySchema, ad as GeometrySlice, ae as GeometrySliceSchema, af as GeometryTokens, ag as GeometryTokensSchema, ah as IconFamily, ai as IconFamilySchema, aj as IconographySlice, ak as IconographySliceSchema, al as IconographyTokens, am as IconographyTokensSchema, an as IllustrationSlice, ao as IllustrationSliceSchema, ap as IllustrationStyle, aq as IllustrationStyleSchema, ar as IllustrationTokens, as as IllustrationTokensSchema, at as MotionDurationKey, au as MotionDurationKeySchema, av as MotionDurationPalette, aw as MotionDurationPaletteSchema, ax as MotionEasingKey, ay as MotionEasingKeySchema, az as MotionEasingPalette, aA as MotionEasingPaletteSchema, aB as MotionIntent, aC as MotionIntentMap, aD as MotionIntentMapSchema, aE as MotionIntentSchema, aF as MotionSlice, aG as MotionSliceSchema, aH as MotionTokens, aI as MotionTokensSchema, aJ as NavItem, aK as NodeClassification, aL as NodeClassificationSchema, aa as Orbital, aM as OrbitalConfig, aN as OrbitalConfigInput, aO as OrbitalConfigSchema, a as OrbitalDefinition, aP as OrbitalDefinitionSchema, aQ as OrbitalInput, e as OrbitalPage, aR as OrbitalPageInput, aS as OrbitalPageSchema, aT as OrbitalPageStrictInput, aU as OrbitalPageStrictSchema, O as OrbitalSchema, aV as OrbitalSchemaInput, aW as OrbitalSchemaSchema, aX as OrbitalSchemaWithTraits, aY as OrbitalUnit, aZ as OrbitalUnitSchema, a_ as OrbitalZodSchema, c as Page, P as PageRef, d as PageRefObject, a$ as PageRefObjectSchema, b0 as PageRefSchema, b1 as PageRefStringSchema, b2 as PageSchema, b3 as PageTraitRef, b4 as PageTraitRefSchema, b5 as RelatedLink, b6 as RelatedLinkSchema, b7 as SchemaMetadata, b8 as SchemaMetadataSchema, b9 as SkinSpec, ba as SkinSpecSchema, bb as SpacingScale, bc as SpacingScaleSchema, bd as StateSemanticRole, be as StateSemanticRoleSchema, bf as SuggestedGuard, bg as SuggestedGuardSchema, bh as ThemeDefinition, bi as ThemeDefinitionSchema, bj as ThemeRef, bk as ThemeRefSchema, bl as ThemeRefStringSchema, bm as ThemeTokens, bn as ThemeTokensSchema, bo as ThemeVariant, bp as ThemeVariantSchema, bq as TypeIntent, br as TypeIntentMap, bs as TypeIntentMapSchema, bt as TypeIntentSchema, bu as TypeScale, bv as TypeScaleEntry, bw as TypeScaleEntrySchema, bx as TypeScaleSchema, by as TypeScaleTokens, bz as TypeScaleTokensSchema, bA as TypeSizeKey, bB as TypeSizeKeySchema, bC as TypeSlice, bD as TypeSliceSchema, bE as TypeSlot, bF as TypeSlotSchema, bG as TypeWeight, bH as TypeWeightSchema, bI as UXHints, bJ as UXHintsSchema, U as UseDeclaration, bK as UseDeclarationSchema, bL as UserPersona, bM as UserPersonaInput, bN as UserPersonaSchema, a as ValidatedOrbital, bO as ViewType, bP as ViewTypeSchema, bQ as isEntityCall, bR as isEntityReference, bS as isEntityReferenceAny, bT as isImportedTraitRef, bU as isOrbitalDefinition, bV as isPageReference, bW as isPageReferenceObject, bX as isPageReferenceString, bY as isThemeReference, bZ as parseEntityRef, b_ as parseImportedTraitRef, b$ as parseOrbitalSchema, c0 as parsePageRef, c1 as safeParseOrbitalSchema } from '../schema-CVTOy4at.js';
2
+ export { j as ANIMATION_NAMES, k as ASSET_ASPECTS, l as ASSET_DIMENSIONS, m as AgentEffect, n as AnimationDef, o as AnimationDefInput, p as AnimationDefSchema, q as AnimationName, r as AnimationNameSchema, s as ApplicationEffect, t as ArrayEntityField, u as Asset, v as AssetAspect, w as AssetAspectSchema, x as AssetCatalog, y as AssetCatalogEntry, z as AssetCatalogEntryInput, B as AssetCatalogEntrySchema, C as AssetCatalogSchema, D as AssetDimension, G as AssetDimensionSchema, H as AssetSchema, J as AssetUrl, K as AtomicEffect, L as BehaviorEffect, M as CAMERA_MODES, N as CallServiceConfig, Q as CallServiceEffect, V as Camera, W as CameraMode, X as CameraModeSchema, Y as CameraSchema, Z as CheckpointLoadEffect, _ as CheckpointSaveEffect, $ as ComposeEffect, a0 as DerefEffect, a1 as DespawnEffect, a2 as DoEffect, a3 as ENTITY_ROLES, c as Effect, a4 as EffectInput, a5 as EffectSchema, a6 as EmitConfig, a7 as EmitEffect, e as Entity, a8 as EntityData, E as EntityField, a9 as EntityFieldInput, aa as EntityFieldSchema, d as EntityId, ab as EntityIdSchema, a as EntityPersistence, ac as EntityPersistenceSchema, ad as EntityRole, ae as EntityRoleSchema, f as EntityRow, af as EntitySchema, ag as EntityWith, ah as EnumEntityField, ai as EvaluateConfig, aj as EvaluateEffect, b as EventId, ak as EventIdSchema, al as FIELD_TYPES, am as FetchEffect, an as FetchOptions, ao as FetchResult, ap as Field, aq as FieldSchema, ar as FieldType, as as FieldTypeSchema, F as FieldValue, at as ForwardConfig, au as ForwardEffect, av as IdForKind, aw as IdKind, I as IdentityLedger, ax as IdentityLedgerSchema, ay as LedgerEntry, az as LedgerEntrySchema, aA as LedgerKind, aB as LedgerKindSchema, aC as LlmEffect, aD as LogEffect, aE as McpServiceDef, aF as McpServiceDefSchema, aG as MemoryEffect, aH as NavigateEffect, aI as NnConfig, aJ as NnLayer, aK as NotifyEffect, aL as ObjectEntityField, aM as OrbitalEntity, aN as OrbitalEntityInput, aO as OrbitalEntitySchema, O as OrbitalId, aP as OrbitalIdSchema, aQ as OsEffect, aR as PATTERN_TYPES, P as PageId, aS as PageIdSchema, aT as PaletteEntryId, aU as PaletteEntryIdSchema, aV as PatternConfig, aY as PatternType, aZ as PersistData, a_ as PersistEffect, a$ as PersistEmitConfig, b0 as RefEffect, R as RelationConfig, b1 as RelationConfigSchema, b2 as RelationEntityField, h as RenderBinding, b3 as RenderChildrenMap, b4 as RenderItemLambda, i as RenderUIEffect, b5 as RenderUINode, b6 as ResolvedPatternProps, b7 as RestAuthConfig, b8 as RestAuthConfigSchema, b9 as RestServiceDef, ba as RestServiceDefSchema, bb as SEMANTIC_STRING_TYPES, bc as SERVICE_TYPES, bd as SHEET_PROJECTIONS, be as SPRITE_DIRECTIONS, bf as ScalarEntityField, bg as ScenePos, bh as ScenePosSchema, bi as SemanticAssetRef, bj as SemanticAssetRefInput, bk as SemanticAssetRefSchema, bl as SemanticStringType, g as ServiceDefinition, bm as ServiceDefinitionSchema, bn as ServiceId, bo as ServiceIdSchema, bp as ServiceParams, bq as ServiceParamsValue, S as ServiceRef, br as ServiceRefObject, bs as ServiceRefObjectSchema, bt as ServiceRefSchema, bu as ServiceRefStringSchema, bv as ServiceType, bw as ServiceTypeSchema, bx as SessionEffect, by as SetEffect, bz as SheetProjection, bA as SheetProjectionSchema, bB as SocketEvents, bC as SocketEventsSchema, bD as SocketServiceDef, bE as SocketServiceDefSchema, bF as SpawnEffect, bG as SpriteDirection, bH as SpriteDirectionSchema, bI as SpriteSheetAtlas, bJ as SpriteSheetAtlasInput, bK as SpriteSheetAtlasSchema, bL as SubTexture, bM as SubTextureSchema, bN as SwapEffect, bO as TextureAtlas, bP as TextureAtlasSchema, bQ as ThemeId, bR as ThemeIdSchema, bS as Tilesheet, bT as TilesheetSchema, bU as TraceEffect, bV as TrainConfig, bW as TrainEffect, T as TraitId, bX as TraitIdSchema, bY as TypedEffect, U as UISlot, bZ as UISlotSchema, b_ as UI_SLOTS, b$ as VISUAL_STYLES, c0 as ValidateEffect, c1 as VisualStyle, c2 as VisualStyleSchema, c3 as WatchEffect, c4 as WatchOptions, c5 as asEntityId, c6 as asEventId, c7 as asOrbitalId, c8 as asPageId, c9 as asPaletteEntryId, ca as asServiceId, cb as asThemeId, cc as asTraitId, cd as atomic, ce as callService, cf as createAssetKey, cg as deref, ch as deriveCollection, ci as despawn, cj as doEffects, ck as emit, cl as findService, cm as getDefaultAnimationsForRole, cn as getServiceNames, co as hasService, cp as idKindOf, cq as idPrefix, cr as isEffect, cs as isEmailValue, ct as isEntityId, cu as isEventId, cv as isFieldValue, cw as isMcpService, cx as isOrbitalId, cy as isPageId, cz as isPaletteEntryId, cA as isPhoneValue, cB as isRestService, cC as isRuntimeEntity, cD as isSExprEffect, cE as isSemanticStringType, cF as isSemanticStringValue, cG as isServiceId, cH as isServiceReference, cI as isServiceReferenceObject, cJ as isSocketService, cK as isThemeId, cL as isTraitId, cM as isUrlValue, cN as isUuidValue, cO as isValidPatternType, cP as ledgerCurName, cQ as ledgerRename, cR as ledgerResolveName, cS as mintId, cT as navigate, cU as notify, cV as parseAssetKey, cW as parseServiceRef, cX as persist, cY as persistenceModeAllowsOverrides, cZ as ref, c_ as renderUI, c$ as set, d0 as spawn, d1 as swap, d2 as validateAssetAnimations, d3 as watch } from '../effect-CK9fn56C.js';
3
+ export { C as CORE_BINDINGS, b as CoreBinding, c as EvalContext, a as EventPayload, d as EventPayloadValue, E as Expression, e as ExpressionInput, f as ExpressionSchema, g as JsonObject, J as JsonValue, L as LogMeta, h as LogMetaValue, P as ParsedBinding, R as RuntimeValue, S as SExpr, i as SExprAtom, j as SExprAtomSchema, k as SExprDataSchema, l as SExprInput, m as SExprObject, n as SExprSchema, T as ToolArgs, o as collectBindings, p as getArgs, q as getOperator, r as isBinding, s as isEventPayloadValue, t as isJsonArray, u as isJsonObject, v as isJsonPrimitive, w as isSExpr, x as isSExprAtom, y as isSExprCall, z as isValidBinding, A as parseBinding, B as sexpr, D as walkSExpr } from '../expression-Fk8bQWef.js';
4
+ export { A as ANONYMOUS_USER, f as AgentCodeSearchResult, g as AgentCompactResult, h as AgentCompactStrategy, i as AgentContext, j as AgentGenerateOptions, k as AgentMemoryCategory, l as AgentMemoryRecord, m as AnalysisOrbital, n as AnalysisOrbitalParams, o as AnalysisPageOverride, p as AnalysisRename, q as AnalysisResult, r as AnnotationTier, s as AppCreatedEvent, t as AppSummary, u as AssetLoadStatus, B as BINDING_CONTEXT_RULES, v as BINDING_DOCS, w as BINDING_ROOTS, x as BindingContext, y as BindingRoot, z as BindingSchema, D as BridgeHealth, E as BuilderResult, F as BusEvent, G as BusEventListener, H as BusEventSource, I as CancelledEvent, d as CategorizedRemovals, J as ChangeAuthor, K as ChangeSetDocument, L as ChangeSummary, M as ChangesetRecordedEvent, C as ChangesetValue, N as CheckStatus, O as Clarification, Q as ClarificationCandidate, T as ClarificationLevel, U as CompleteEvent, V as ComplexityAssessment, W as ComposeAllResult, X as ComposeChildrenResult, Y as ComposeOptions, Z as ContextExtensions, _ as CreateFlow, $ as DEFAULT_INTERACTION_MODELS, a0 as DEFAULT_VIEWER, a1 as DEV_TOKEN_PREFIX, a2 as DeleteFlow, a3 as DispatchUpdatesResult, a4 as DrawableDescriptor, a5 as EdgeType, a6 as EditFlow, a9 as EffectPayload, aa as EffectResult, ab as EffectTrace, ac as ErrorEvent, ad as EventEmit, ae as EventKey, af as EventListen, ag as EventLogEntry, ah as EvolutionDelta, ai as ExecutePlanResult, aj as ExtraTraitRef, ak as FileOperationEvent, al as FileWrittenEvent, am as GateState, an as GenerationLogEvent, ao as GitHubIssue, ap as GitHubLink, aq as GitHubRepo, ar as HistoryMeta, as as IntegrationContext, at as InteractionModel, au as InteractionModelInput, av as InteractionModelSchema, aw as InterruptEvent, ax as KNOWN_VALIDATION_ERROR_CODES, ay as KnobPayload, az as KnownValidationErrorCode, aA as LLMErrorContext, aB as LazyService, aC as LineageEntry, aD as ListInteraction, aE as LivingEdge, aF as LivingEffect, aG as LivingEntity, aH as LivingEvent, aI as LivingField, aJ as LivingOrbital, aK as LivingOrbitalSchema, aL as LivingPage, aM as LivingState, aN as LivingTrait, aO as LivingTransition, aP as LivingValue, aQ as LivingVertex, aR as LlmCallToolsResult, aS as LlmContext, aT as LlmMessage, aU as LlmTokenUsage, aV as LlmToolCall, aW as LlmToolDef, aX as LoloEmitResult, aY as MemoryContext, aZ as MessageEvent, a_ as OrbitalAddedEvent, a$ as OrbitalSchemaCompleteEvent, b0 as OrbitalVerificationAPI, P as PageContentReduction, b1 as ParamsRepairEmittedEvent, b2 as ParsedDesign, b3 as ParsedDomainContext, b4 as ParsedEmitDeclaration, b5 as ParsedEntity, b6 as ParsedEvent, b7 as ParsedListenDeclaration, b8 as ParsedOrbital, b9 as ParsedPage, ba as ParsedState, bb as ParsedStateMachine, bc as ParsedTrait, bd as ParsedTraitConfig, be as ParsedTransition, bf as PatternNode, bg as PatternTypeSchema, bh as PatternValue, bi as PersistActionName, bj as PlanSnapshot, bk as PlanSnapshotStatus, bl as PlannerResult, bm as Probability, bn as ProcessCompleteEvent, bo as ProcessErrorEvent, bp as ProcessRepairCompleteEvent, bq as ProcessRepairEvent, br as ProcessStartEvent, bs as RENDER_BINDING_MARKER, bt as RawUserClaims, bu as RenderBindingMarker, bz as RepairResult, a as ResolvedEntity, bA as ResolvedEntityBinding, bB as ResolvedField, R as ResolvedIR, bC as ResolvedNavigation, b as ResolvedPage, bD as ResolvedPattern, bE as ResolvedSection, bF as ResolvedSectionEvent, c as ResolvedTrait, bG as ResolvedTraitBinding, bH as ResolvedTraitDataEntity, bI as ResolvedTraitEvent, bJ as ResolvedTraitGuard, bK as ResolvedTraitListener, bL as ResolvedTraitState, bM as ResolvedTraitTick, bN as ResolvedTraitTransition, bO as ResolvedTraitUIBinding, bP as SSEEvent, bQ as SSEEventBase, bR as SSEEventType, bS as SaveOptions, bT as SaveResult, S as SchemaChange, bU as SchemaPhaseUpdateEvent, bV as SchemaPhaseValidatedEvent, bW as SchemaUpdateEvent, bX as SemanticAnnotation, bY as SemanticChangeKind, e as SemanticSchemaChange, bZ as SemanticVector, b_ as ServerResponseTrace, b$ as ServiceAction, c0 as ServiceActionName, c1 as ServiceCallResult, c2 as ServiceContract, c3 as ServiceEvents, c4 as SessionContext, c5 as SessionHistoryEntry, c6 as SnapshotCreatedEvent, c7 as SnapshotDocument, c8 as SpawnResult, c9 as StartEvent, ca as StatsView, cb as StoreContract, cc as StoreFilter, cd as StoreFilterOp, ce as SubagentCompleteEvent, cf as SubagentEvent, cg as SubagentProgressEvent, ch as SubagentStartEvent, ci as TodoActivityType, cj as TodoDetailEvent, ck as TodoUpdateEvent, cl as ToolCallEvent, cm as ToolResultEvent, cn as TraceContext, co as TraitFieldRef, cp as TraitFieldRefSchema, cq as TraitStateSnapshot, cr as TransitionFrom, cs as TransitionTrace, ct as Unsubscribe, cu as UserContext, cv as ValidateResult, cw as ValidationDocument, cx as ValidationError, cy as ValidationErrorCode, cz as ValidationIssue, cA as ValidationMeta, cB as ValidationResult, cC as ValidationResults, cD as VerificationCheck, cE as VerificationSnapshot, cF as VerificationSummary, cG as VertexId, cH as VertexPayload, cI as VertexType, cJ as ViewFlow, cK as WorkspaceContext, cM as containsEntityBinding, cN as containsPayloadBinding, cO as createEmptyResolvedPage, cP as createEmptyResolvedTrait, cQ as createLazyService, cR as createResolvedField, cS as createTypedEventBus, cT as decodeDevIdentityToken, cU as encodeDevIdentityToken, cV as findPersonaInRoster, cX as getBindingExamples, cY as getInteractionModelForDomain, cZ as inferTsType, c$ as isKnownValidationErrorCode, d0 as isPlanSnapshot, d1 as isRenderBindingMarker, d2 as isResolvedIR, d3 as isSessionHistoryEntry, d4 as isTraitFieldRef, d6 as normalizeUserContext, d7 as personaFromIdentityRow, da as resolveDefaultViewer, db as resolvePersonaSpec, dd as toBindingRoot, de as validateBindingInContext, df as widenTier } from '../index-DMUBu17o.js';
5
+ export { k as CONFIG_REF_EVENT_PATTERN, h as CallSiteConfig, i as CallSiteConfigEntry, C as ConfigFieldDeclaration, l as ConfigFieldDeclarationSchema, m as ConfigFieldItemsDeclaration, n as ConfigRefEventError, D as DeclaredTraitConfig, o as DeclaredTraitConfigSchema, p as EntityFieldContract, q as EntityFieldContractSchema, r as Event, s as EventInput, E as EventPayloadField, t as EventPayloadFieldSchema, u as EventSchema, v as EventScope, w as EventScopeSchema, G as Guard, x as GuardInput, y as GuardSchema, L as ListenSource, z as ListenSourceSchema, O as OrbitalTraitRef, A as OrbitalTraitRefSchema, P as PayloadField, B as PayloadFieldSchema, F as PresentationType, R as REFERENCE_CONFIG_TYPES, H as ReferenceConfigType, I as RequiredField, J as RequiredFieldSchema, K as SECRET_CONFIG_TYPES, M as SecretConfigType, S as State, N as StateInput, Q as StateMachine, U as StateMachineInput, V as StateMachineSchema, W as StateSchema, X as TickIntervalSchema, g as Trait, Y as TraitCategory, Z as TraitCategorySchema, b as TraitConfig, c as TraitConfigObject, _ as TraitConfigSchema, e as TraitConfigValue, $ as TraitConfigValueSchema, a0 as TraitDataEntity, a1 as TraitDataEntitySchema, f as TraitEntityField, a2 as TraitEntityFieldSchema, j as TraitEventContract, a3 as TraitEventContractSchema, T as TraitEventListener, a4 as TraitEventListenerSchema, a5 as TraitInput, d as TraitRef, a6 as TraitRefSchema, a as TraitReference, a7 as TraitReferenceInput, a8 as TraitReferenceSchema, a9 as TraitSchema, aa as TraitTick, ab as TraitTickSchema, ac as TraitUIBinding, ad as TraitUIBindingSchema, ae as Transition, af as TransitionInput, ag as TransitionSchema, ah as configRefEventKnob, ai as getTraitConfig, aj as getTraitName, ak as isCallSiteConfigDeclaration, al as isCircuitEvent, am as isInlineTrait, an as isReferenceConfigType, ao as isSecretConfigType, ap as normalizeCallSiteConfigToValues, aq as normalizeTraitRef, ar as resolveConfigRefEventName } from '../trait-BjPraUgs.js';
6
+ import 'zod';
7
+ import '../types-Dopw3s2O.js';
8
+ import '../builders.js';