@almadar/std 14.43.1 → 14.43.3

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.
@@ -0,0 +1,175 @@
1
+ import { OrbitalSchema, EntityField, EntityPersistence, OrbitalDefinition } from '@almadar/core';
2
+ import { O as OrbitalParamsManifest } from '../dispatch-x-qHdw0V.js';
3
+ export { P as ParamFieldDescriptor } from '../dispatch-x-qHdw0V.js';
4
+ import { MakeTraitRefOpts } from '@almadar/core/builders';
5
+ import '@almadar/core/types';
6
+
7
+ /**
8
+ * `extractManifest(orb)` — derive the typed `OrbitalParamsManifest[]` from a
9
+ * resolved `.orb`, one entry per orbital. The result has the exact same
10
+ * shape the codegen `regenerate-std-ts.mjs` emits as `*OrbitalManifest`
11
+ * literals.
12
+ *
13
+ * Pure data → data. No I/O. No behavior-specific branching.
14
+ *
15
+ * Used by:
16
+ * - `scripts/regenerate-std-ts.mjs` — emits the manifest as a TS literal.
17
+ * - The promotion server (Phase B) — stores `manifests[]` alongside the orb.
18
+ *
19
+ * @packageDocumentation
20
+ */
21
+
22
+ /**
23
+ * Produce one `OrbitalParamsManifest` per orbital in the orb. The orb's
24
+ * top-level `name` is the behavior name (e.g. `std-embedded-dashboard`);
25
+ * each orbital's `name` is the orbital name (e.g. `DashboardOrbital`).
26
+ */
27
+ declare function extractManifest(orb: OrbitalSchema): readonly OrbitalParamsManifest[];
28
+
29
+ /**
30
+ * Factory-runtime — typed shapes.
31
+ *
32
+ * The factory runtime is the data-driven equivalent of the per-behavior TS
33
+ * factories generated by `scripts/regenerate-std-ts.mjs`. The script bakes
34
+ * the same overlay logic into each emitted factory; the runtime form lifts it
35
+ * out so team-published behaviors (Firestore-stored, not code-published) can
36
+ * flow through the identical code path.
37
+ *
38
+ * Reference: `docs/Almadar_Studio_SDK.md` §7.4.
39
+ *
40
+ * @packageDocumentation
41
+ */
42
+
43
+ /**
44
+ * The override surface for a single imported trait. Mirrors `.lolo`'s native
45
+ * trait-composition surface 1:1 (see SDK doc §7.4 + the generated
46
+ * `traitOverrides` types in each std factory). `effects` is intentionally
47
+ * NOT exposed — that's atom-owned (use `listens` via a sibling trait to
48
+ * react to atom events).
49
+ */
50
+ type OrbitalTraitOverride = Pick<MakeTraitRefOpts, 'config' | 'linkedEntity' | 'events' | 'name' | 'emitsScope' | 'listens'>;
51
+ /**
52
+ * Strongly-typed params accepted by `applyParamsToOrb`. Same shape as every
53
+ * generated per-orbital `*Params` interface (the codegen narrows
54
+ * `traitOverrides`'s key type to that orbital's `traitNames`; the runtime
55
+ * form keeps it open and validates the keys against the manifest at call
56
+ * time).
57
+ */
58
+ interface OrbitalFactoryParams {
59
+ /** Extra fields appended to the canonical entity (caller wins on name collision). */
60
+ readonly fields?: readonly EntityField[];
61
+ /** URL path override for the orbital's first page. */
62
+ readonly pagePath?: string;
63
+ /** Override the canonical entity persistence mode. */
64
+ readonly persistence?: EntityPersistence;
65
+ /** Rename the canonical entity (PascalCase singular, ≤32 chars). */
66
+ readonly entityName?: string;
67
+ /** Override the derived collection key (defaults to plural-of-entityName). */
68
+ readonly collection?: string;
69
+ /** Per-imported-trait overrides, keyed on the trait's canonical `name`. */
70
+ readonly traitOverrides?: Readonly<Record<string, OrbitalTraitOverride | undefined>>;
71
+ }
72
+ /**
73
+ * Discriminated failure shape for params validation against a manifest. Each
74
+ * variant carries the smallest information needed for an actionable error
75
+ * message — never a raw thrown `Error`.
76
+ */
77
+ type ParamValidationError = {
78
+ readonly kind: 'unknown-key';
79
+ readonly key: string;
80
+ } | {
81
+ readonly kind: 'unknown-trait-override';
82
+ readonly trait: string;
83
+ readonly allowed: readonly string[];
84
+ } | {
85
+ readonly kind: 'not-object';
86
+ readonly received: string;
87
+ } | {
88
+ readonly kind: 'trait-overrides-not-object';
89
+ readonly received: string;
90
+ };
91
+ /** Discriminated result type for validation. Caller never widens. */
92
+ type ParamValidationResult = {
93
+ readonly ok: true;
94
+ readonly params: OrbitalFactoryParams;
95
+ } | {
96
+ readonly ok: false;
97
+ readonly error: ParamValidationError;
98
+ };
99
+
100
+ /**
101
+ * `applyParamsToOrb` — pure runtime overlay function. Equivalent to the body
102
+ * the codegen `regenerate-std-ts.mjs` emits inline for every std factory
103
+ * (`scripts/regenerate-std-ts.mjs:612-737`), lifted out so that:
104
+ * 1. team-published behaviors (Firestore-stored) can dispatch through the
105
+ * same overlay as std behaviors;
106
+ * 2. std factories *can* (future cleanup) collapse to a one-line wrapper
107
+ * calling this function.
108
+ *
109
+ * Reference: `docs/Almadar_Studio_SDK.md` §7.4.2.
110
+ *
111
+ * Pure data → data. No I/O.
112
+ *
113
+ * @packageDocumentation
114
+ */
115
+
116
+ /**
117
+ * Structural validation of caller-supplied params against the manifest.
118
+ * Rejects unknown top-level keys and unknown `traitOverrides` keys (the
119
+ * latter against the manifest's `traitNames` allow-list).
120
+ *
121
+ * `raw: object` is the minimum-typed input: callers must already have
122
+ * narrowed from JSON / LLM output to a plain object. The discriminated
123
+ * result lifts callers into the typed `OrbitalFactoryParams` on success.
124
+ */
125
+ declare function validateOrbitalFactoryParams(manifest: OrbitalParamsManifest, raw: object): ParamValidationResult;
126
+ /**
127
+ * The overlay. Resolves the effective entity name + collection, calls
128
+ * `makeOrbitalWithUses` with the rewritten data, then applies the params'
129
+ * trait/page overrides post-hoc — exactly mirroring the codegen emit at
130
+ * `scripts/regenerate-std-ts.mjs:612-737`.
131
+ *
132
+ * `_manifest` is accepted for parity with the future dispatcher signature
133
+ * but is unused in this overlay — the manifest is consumed by
134
+ * `validateOrbitalFactoryParams` upstream. Kept on the signature so std
135
+ * factories can collapse to one-line wrappers without an arg-shape change.
136
+ */
137
+ declare function applyParamsToOrb(orb: OrbitalSchema, orbitalName: string, _manifest: OrbitalParamsManifest, params: OrbitalFactoryParams): OrbitalDefinition;
138
+
139
+ /**
140
+ * `applyParamsToWholeOrb` — pure runtime overlay for an ENTIRE stored orb.
141
+ *
142
+ * Companion to `applyParamsToOrb` (single-orbital). Where `applyParamsToOrb`
143
+ * materialises one orbital from a multi-orbital schema, this function applies
144
+ * the same overlay to every orbital in the schema by joining each orbital to
145
+ * its matching manifest entry from `manifests[]`. Returns a new
146
+ * `OrbitalSchema` with the rebuilt orbitals.
147
+ *
148
+ * Used by team-behavior dispatch on the LLM-loop seam (`call_behavior` tool
149
+ * in @almadar/agent): the LLM emits `call_behavior('team/<name>@<v>', params)`,
150
+ * std-import returns undefined, the agent's `extra.dispatchWhole` port runs
151
+ * this function over the Firestore-stored record's `{ orb, manifests }`.
152
+ *
153
+ * Reference: `docs/Almadar_Studio_SDK.md` §7.4.4.
154
+ *
155
+ * Pure data → data. No I/O.
156
+ *
157
+ * @packageDocumentation
158
+ */
159
+
160
+ /**
161
+ * Apply `params` to every orbital in `orb` that has a matching manifest in
162
+ * `manifests[]`. Orbitals with no manifest are passed through unchanged —
163
+ * the storage convention is one manifest per orbital, so a missing manifest
164
+ * indicates a stored orbital we don't know how to parameterise (rare; the
165
+ * promote path writes manifests for every orbital it knows).
166
+ *
167
+ * @param orb The full team-behavior schema as stored.
168
+ * @param manifests Per-orbital param manifests; joined to orbitals by name.
169
+ * @param params One shared params bag applied to every parameterised
170
+ * orbital. Mirrors the std whole-behavior factories'
171
+ * convention of a single `params` argument.
172
+ */
173
+ declare function applyParamsToWholeOrb(orb: OrbitalSchema, manifests: readonly OrbitalParamsManifest[], params: OrbitalFactoryParams): OrbitalSchema;
174
+
175
+ export { type OrbitalFactoryParams, OrbitalParamsManifest, type OrbitalTraitOverride, type ParamValidationError, type ParamValidationResult, applyParamsToOrb, applyParamsToWholeOrb, extractManifest, validateOrbitalFactoryParams };
@@ -0,0 +1,256 @@
1
+ import { makeOrbitalWithUses, makePageRef, makeTraitRef } from '@almadar/core/builders';
2
+
3
+ // factory-runtime/extract-manifest.ts
4
+ var STATIC_PARAM_FIELDS = [
5
+ {
6
+ name: "fields",
7
+ type: "EntityField[]",
8
+ description: "Extra fields appended to the canonical entity."
9
+ },
10
+ {
11
+ name: "pagePath",
12
+ type: "string",
13
+ description: "URL override for the orbital first page."
14
+ },
15
+ {
16
+ name: "persistence",
17
+ type: "'persistent' | 'runtime' | 'singleton' | 'instance' | 'local'",
18
+ description: "Override the canonical entity persistence mode."
19
+ },
20
+ {
21
+ name: "entityName",
22
+ type: "string",
23
+ description: "Rename the canonical entity. PascalCase singular, \u226432 chars. Threads through every trait's linkedEntity binding; compiler rewrites @Entity.x refs."
24
+ },
25
+ {
26
+ name: "collection",
27
+ type: "string",
28
+ description: "Override derived collection key. Defaults to plural(entityName).toLowerCase()."
29
+ },
30
+ {
31
+ name: "traitOverrides",
32
+ type: "Partial<Record<TraitName, { config?, linkedEntity?, events?, name?, emitsScope?, listens? }>>",
33
+ description: ".lolo's native trait-composition surface 1:1: per-imported-trait config, linkedEntity, events, name, emitsScope, listens. effects is excluded (atom-owned; use listens via a sibling trait)."
34
+ }
35
+ ];
36
+ function splitTraits(traits) {
37
+ const refTraitNames = [];
38
+ const inlineTraitNames = [];
39
+ for (const t of traits) {
40
+ if (!t || typeof t !== "object") continue;
41
+ const tName = typeof t.name === "string" ? t.name : null;
42
+ if (!tName) continue;
43
+ if (typeof t.ref === "string") {
44
+ refTraitNames.push(tName);
45
+ } else {
46
+ inlineTraitNames.push(tName);
47
+ }
48
+ }
49
+ return { refTraitNames, inlineTraitNames };
50
+ }
51
+ function extractManifest(orb) {
52
+ const behaviorName = orb.name;
53
+ return orb.orbitals.map((orbital) => {
54
+ const { refTraitNames, inlineTraitNames } = splitTraits(orbital.traits);
55
+ return {
56
+ organism: behaviorName,
57
+ orbitalName: orbital.name,
58
+ paramFields: STATIC_PARAM_FIELDS,
59
+ traitNames: refTraitNames,
60
+ inlineTraitNames
61
+ };
62
+ });
63
+ }
64
+ function validateOrbitalFactoryParams(manifest, raw) {
65
+ if (raw === null || Array.isArray(raw)) {
66
+ return {
67
+ ok: false,
68
+ error: { kind: "not-object", received: Array.isArray(raw) ? "array" : "null" }
69
+ };
70
+ }
71
+ const ALLOWED_KEYS = /* @__PURE__ */ new Set([
72
+ "fields",
73
+ "pagePath",
74
+ "persistence",
75
+ "entityName",
76
+ "collection",
77
+ "traitOverrides"
78
+ ]);
79
+ for (const key of Object.keys(raw)) {
80
+ if (!ALLOWED_KEYS.has(key)) {
81
+ return { ok: false, error: { kind: "unknown-key", key } };
82
+ }
83
+ }
84
+ const candidate = raw;
85
+ if (candidate.traitOverrides !== void 0) {
86
+ const to = candidate.traitOverrides;
87
+ if (to === null || typeof to !== "object" || Array.isArray(to)) {
88
+ return {
89
+ ok: false,
90
+ error: {
91
+ kind: "trait-overrides-not-object",
92
+ received: Array.isArray(to) ? "array" : typeof to
93
+ }
94
+ };
95
+ }
96
+ const allowed = new Set(manifest.traitNames);
97
+ for (const traitName of Object.keys(to)) {
98
+ if (!allowed.has(traitName)) {
99
+ return {
100
+ ok: false,
101
+ error: {
102
+ kind: "unknown-trait-override",
103
+ trait: traitName,
104
+ allowed: manifest.traitNames
105
+ }
106
+ };
107
+ }
108
+ }
109
+ }
110
+ return { ok: true, params: candidate };
111
+ }
112
+ function assertResolvedEntity(entity, orbitalName, orbName) {
113
+ if (typeof entity === "string") {
114
+ throw new Error(
115
+ `applyParamsToOrb: orbital "${orbitalName}" in orb "${orbName}" has an unresolved entity reference (string form). Pass a resolved .orb.`
116
+ );
117
+ }
118
+ if ("extends" in entity) {
119
+ throw new Error(
120
+ `applyParamsToOrb: orbital "${orbitalName}" in orb "${orbName}" has an unresolved EntityCall ("extends" form). Pass a resolved .orb.`
121
+ );
122
+ }
123
+ return entity;
124
+ }
125
+ function findOrbitalOrThrow(orb, orbitalName) {
126
+ const orbital = orb.orbitals.find((o) => o.name === orbitalName);
127
+ if (!orbital) {
128
+ throw new Error(
129
+ `applyParamsToOrb: orbital "${orbitalName}" not found in orb "${orb.name}". Available: ${orb.orbitals.map((o) => o.name).join(", ")}`
130
+ );
131
+ }
132
+ return orbital;
133
+ }
134
+ function buildEntity(ctx, effectiveName, effectiveCollection, params) {
135
+ const canonicalFields = Array.isArray(ctx.canonicalEntity.fields) ? ctx.canonicalEntity.fields : [];
136
+ const extras = params.fields ?? [];
137
+ let mergedFields;
138
+ if (extras.length === 0) {
139
+ mergedFields = canonicalFields;
140
+ } else {
141
+ const extraNames = new Set(extras.map((f) => f.name));
142
+ mergedFields = [
143
+ ...canonicalFields.filter((f) => !extraNames.has(f.name)),
144
+ ...extras
145
+ ];
146
+ }
147
+ const entity = {
148
+ name: effectiveName,
149
+ persistence: params.persistence ?? ctx.canonicalEntity.persistence,
150
+ fields: [...mergedFields]
151
+ };
152
+ if (effectiveCollection !== void 0) {
153
+ entity.collection = effectiveCollection;
154
+ }
155
+ return entity;
156
+ }
157
+ function isTraitReferenceObject(t) {
158
+ if (t === null || typeof t !== "object") return false;
159
+ if (!("ref" in t)) return false;
160
+ return typeof t.ref === "string";
161
+ }
162
+ function isPageRefObject(p) {
163
+ if (p === null || typeof p !== "object") return false;
164
+ if (!("ref" in p)) return false;
165
+ return typeof p.ref === "string";
166
+ }
167
+ function rebuildTraits(ctx, effectiveEntityName, traits) {
168
+ return traits.map((t) => {
169
+ if (!isTraitReferenceObject(t)) {
170
+ return t;
171
+ }
172
+ const rewrittenLinkedEntity = t.linkedEntity === ctx.canonicalEntityName ? effectiveEntityName : t.linkedEntity;
173
+ const opts = {
174
+ ...t,
175
+ linkedEntity: rewrittenLinkedEntity
176
+ };
177
+ return makeTraitRef(opts);
178
+ });
179
+ }
180
+ function rebuildPages(ctx, effectiveEntityName, pages) {
181
+ if (!pages) return [];
182
+ return pages.map((p) => {
183
+ if (!isPageRefObject(p)) {
184
+ return p;
185
+ }
186
+ const rewrittenLinkedEntity = p.linkedEntity === ctx.canonicalEntityName ? effectiveEntityName : p.linkedEntity;
187
+ const opts = {
188
+ ...p,
189
+ linkedEntity: rewrittenLinkedEntity
190
+ };
191
+ return makePageRef(opts);
192
+ });
193
+ }
194
+ function applyParamsToOrb(orb, orbitalName, _manifest, params) {
195
+ const orbital = findOrbitalOrThrow(orb, orbitalName);
196
+ const canonicalEntity = assertResolvedEntity(orbital.entity, orbitalName, orb.name);
197
+ const canonicalEntityName = canonicalEntity.name;
198
+ const effectiveEntityName = params.entityName ?? canonicalEntityName;
199
+ const effectiveCollection = typeof canonicalEntity.collection === "string" ? params.collection ?? (params.entityName ? `${params.entityName.toLowerCase()}s` : canonicalEntity.collection) : params.collection;
200
+ const ctx = { canonicalEntityName, canonicalEntity };
201
+ const built = makeOrbitalWithUses({
202
+ name: orbital.name,
203
+ uses: orbital.uses ?? [],
204
+ entity: buildEntity(ctx, effectiveEntityName, effectiveCollection, params),
205
+ traits: rebuildTraits(ctx, effectiveEntityName, orbital.traits),
206
+ pages: rebuildPages(ctx, effectiveEntityName, orbital.pages)
207
+ });
208
+ if (built.traits && params.traitOverrides !== void 0) {
209
+ built.traits = built.traits.map((t) => {
210
+ if (!isTraitReferenceObject(t) || typeof t.name !== "string") return t;
211
+ const override = params.traitOverrides?.[t.name];
212
+ if (!override) return t;
213
+ const merged = { ...t };
214
+ if (override.config !== void 0) {
215
+ merged.config = { ...t.config ?? {}, ...override.config };
216
+ }
217
+ if (override.linkedEntity !== void 0) merged.linkedEntity = override.linkedEntity;
218
+ if (override.events !== void 0) {
219
+ merged.events = { ...t.events ?? {}, ...override.events };
220
+ }
221
+ if (override.name !== void 0) merged.name = override.name;
222
+ if (override.emitsScope !== void 0) merged.emitsScope = override.emitsScope;
223
+ if (override.listens !== void 0) merged.listens = override.listens;
224
+ return merged;
225
+ });
226
+ }
227
+ if (built.pages && params.pagePath !== void 0) {
228
+ built.pages = built.pages.map((p, idx) => {
229
+ if (!isPageRefObject(p) || idx !== 0) return p;
230
+ return { ...p, path: params.pagePath };
231
+ });
232
+ }
233
+ return built;
234
+ }
235
+
236
+ // factory-runtime/apply-params-to-whole-orb.ts
237
+ function applyParamsToWholeOrb(orb, manifests, params) {
238
+ const manifestByOrbital = /* @__PURE__ */ new Map();
239
+ for (const m of manifests) {
240
+ manifestByOrbital.set(m.orbitalName, m);
241
+ }
242
+ const rebuilt = [];
243
+ for (const orbital of orb.orbitals) {
244
+ const manifest = manifestByOrbital.get(orbital.name);
245
+ if (!manifest) {
246
+ rebuilt.push(orbital);
247
+ continue;
248
+ }
249
+ rebuilt.push(applyParamsToOrb(orb, orbital.name, manifest, params));
250
+ }
251
+ return { ...orb, orbitals: rebuilt };
252
+ }
253
+
254
+ export { applyParamsToOrb, applyParamsToWholeOrb, extractManifest, validateOrbitalFactoryParams };
255
+ //# sourceMappingURL=index.js.map
256
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../factory-runtime/extract-manifest.ts","../../factory-runtime/apply-params-to-orb.ts","../../factory-runtime/apply-params-to-whole-orb.ts"],"names":[],"mappings":";;;AA0BA,IAAM,mBAAA,GAAuD;AAAA,EAC3D;AAAA,IACE,IAAA,EAAM,QAAA;AAAA,IACN,IAAA,EAAM,eAAA;AAAA,IACN,WAAA,EAAa;AAAA,GACf;AAAA,EACA;AAAA,IACE,IAAA,EAAM,UAAA;AAAA,IACN,IAAA,EAAM,QAAA;AAAA,IACN,WAAA,EAAa;AAAA,GACf;AAAA,EACA;AAAA,IACE,IAAA,EAAM,aAAA;AAAA,IACN,IAAA,EAAM,+DAAA;AAAA,IACN,WAAA,EAAa;AAAA,GACf;AAAA,EACA;AAAA,IACE,IAAA,EAAM,YAAA;AAAA,IACN,IAAA,EAAM,QAAA;AAAA,IACN,WAAA,EACE;AAAA,GACJ;AAAA,EACA;AAAA,IACE,IAAA,EAAM,YAAA;AAAA,IACN,IAAA,EAAM,QAAA;AAAA,IACN,WAAA,EACE;AAAA,GACJ;AAAA,EACA;AAAA,IACE,IAAA,EAAM,gBAAA;AAAA,IACN,IAAA,EAAM,+FAAA;AAAA,IACN,WAAA,EACE;AAAA;AAEN,CAAA;AAOA,SAAS,YAAY,MAAA,EAAkE;AACrF,EAAA,MAAM,gBAA0B,EAAC;AACjC,EAAA,MAAM,mBAA6B,EAAC;AACpC,EAAA,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,iBAAA,uBAAwB,GAAA,EAAmC;AACjE,EAAA,KAAA,MAAW,KAAK,SAAA,EAAW;AACzB,IAAA,iBAAA,CAAkB,GAAA,CAAI,CAAA,CAAE,WAAA,EAAa,CAAC,CAAA;AAAA,EACxC;AACA,EAAA,MAAM,UAA+B,EAAC;AACtC,EAAA,KAAA,MAAW,OAAA,IAAW,IAAI,QAAA,EAAU;AAClC,IAAA,MAAM,QAAA,GAAW,iBAAA,CAAkB,GAAA,CAAI,OAAA,CAAQ,IAAI,CAAA;AACnD,IAAA,IAAI,CAAC,QAAA,EAAU;AACb,MAAA,OAAA,CAAQ,KAAK,OAAO,CAAA;AACpB,MAAA;AAAA,IACF;AACA,IAAA,OAAA,CAAQ,KAAK,gBAAA,CAAiB,GAAA,EAAK,QAAQ,IAAA,EAAM,QAAA,EAAU,MAAM,CAAC,CAAA;AAAA,EACpE;AACA,EAAA,OAAO,EAAE,GAAG,GAAA,EAAK,QAAA,EAAU,OAAA,EAAQ;AACrC","file":"index.js","sourcesContent":["/**\n * `extractManifest(orb)` — derive the typed `OrbitalParamsManifest[]` from a\n * resolved `.orb`, one entry per orbital. The result has the exact same\n * shape the codegen `regenerate-std-ts.mjs` emits as `*OrbitalManifest`\n * literals.\n *\n * Pure data → data. No I/O. No behavior-specific branching.\n *\n * Used by:\n * - `scripts/regenerate-std-ts.mjs` — emits the manifest as a TS literal.\n * - The promotion server (Phase B) — stores `manifests[]` alongside the orb.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalSchema, TraitReference } from '@almadar/core';\nimport type {\n OrbitalParamsManifest,\n ParamFieldDescriptor,\n} from '../behaviors/functions/dispatch.js';\n\n/**\n * Canonical param-field descriptors. Static across all factories — every\n * orbital accepts the same six knobs (the codegen emits this exact list\n * verbatim into every generated manifest).\n */\nconst STATIC_PARAM_FIELDS: readonly ParamFieldDescriptor[] = [\n {\n name: 'fields',\n type: 'EntityField[]',\n description: 'Extra fields appended to the canonical entity.',\n },\n {\n name: 'pagePath',\n type: 'string',\n description: 'URL override for the orbital first page.',\n },\n {\n name: 'persistence',\n type: \"'persistent' | 'runtime' | 'singleton' | 'instance' | 'local'\",\n description: 'Override the canonical entity persistence mode.',\n },\n {\n name: 'entityName',\n type: 'string',\n description:\n \"Rename the canonical entity. PascalCase singular, ≤32 chars. Threads through every trait's linkedEntity binding; compiler rewrites @Entity.x refs.\",\n },\n {\n name: 'collection',\n type: 'string',\n description:\n 'Override derived collection key. Defaults to plural(entityName).toLowerCase().',\n },\n {\n name: 'traitOverrides',\n type: 'Partial<Record<TraitName, { config?, linkedEntity?, events?, name?, emitsScope?, listens? }>>',\n description:\n \".lolo's native trait-composition surface 1:1: per-imported-trait config, linkedEntity, events, name, emitsScope, listens. effects is excluded (atom-owned; use listens via a sibling trait).\",\n },\n] as const;\n\ninterface SplitTraits {\n readonly refTraitNames: readonly string[];\n readonly inlineTraitNames: readonly string[];\n}\n\nfunction splitTraits(traits: OrbitalSchema['orbitals'][number]['traits']): SplitTraits {\n const refTraitNames: string[] = [];\n const inlineTraitNames: string[] = [];\n for (const t of traits) {\n if (!t || typeof t !== 'object') continue;\n const tName = typeof (t as TraitReference).name === 'string'\n ? (t as TraitReference).name\n : null;\n if (!tName) continue;\n if (typeof (t as TraitReference).ref === 'string') {\n refTraitNames.push(tName);\n } else {\n inlineTraitNames.push(tName);\n }\n }\n return { refTraitNames, inlineTraitNames };\n}\n\n/**\n * Produce one `OrbitalParamsManifest` per orbital in the orb. The orb's\n * top-level `name` is the behavior name (e.g. `std-embedded-dashboard`);\n * each orbital's `name` is the orbital name (e.g. `DashboardOrbital`).\n */\nexport function extractManifest(orb: OrbitalSchema): readonly OrbitalParamsManifest[] {\n const behaviorName = orb.name;\n return orb.orbitals.map((orbital) => {\n const { refTraitNames, inlineTraitNames } = splitTraits(orbital.traits);\n return {\n organism: behaviorName,\n orbitalName: orbital.name,\n paramFields: STATIC_PARAM_FIELDS,\n traitNames: refTraitNames,\n inlineTraitNames,\n };\n });\n}\n","/**\n * `applyParamsToOrb` — pure runtime overlay function. Equivalent to the body\n * the codegen `regenerate-std-ts.mjs` emits inline for every std factory\n * (`scripts/regenerate-std-ts.mjs:612-737`), lifted out so that:\n * 1. team-published behaviors (Firestore-stored) can dispatch through the\n * same overlay as std behaviors;\n * 2. std factories *can* (future cleanup) collapse to a one-line wrapper\n * calling this function.\n *\n * Reference: `docs/Almadar_Studio_SDK.md` §7.4.2.\n *\n * Pure data → data. No I/O.\n *\n * @packageDocumentation\n */\n\nimport type {\n Entity,\n EntityField,\n OrbitalDefinition,\n OrbitalEntity,\n OrbitalSchema,\n PageRefObject,\n TraitReference,\n} from '@almadar/core';\nimport type {\n MakePageRefOpts,\n MakeTraitRefOpts,\n} from '@almadar/core/builders';\nimport {\n makeOrbitalWithUses,\n makePageRef,\n makeTraitRef,\n} from '@almadar/core/builders';\nimport type { OrbitalParamsManifest } from '../behaviors/functions/dispatch.js';\nimport type {\n OrbitalFactoryParams,\n OrbitalTraitOverride,\n ParamValidationResult,\n} from './types.js';\n\n/**\n * Structural validation of caller-supplied params against the manifest.\n * Rejects unknown top-level keys and unknown `traitOverrides` keys (the\n * latter against the manifest's `traitNames` allow-list).\n *\n * `raw: object` is the minimum-typed input: callers must already have\n * narrowed from JSON / LLM output to a plain object. The discriminated\n * result lifts callers into the typed `OrbitalFactoryParams` on success.\n */\nexport function validateOrbitalFactoryParams(\n manifest: OrbitalParamsManifest,\n raw: object,\n): ParamValidationResult {\n if (raw === null || Array.isArray(raw)) {\n return {\n ok: false,\n error: { kind: 'not-object', received: Array.isArray(raw) ? 'array' : 'null' },\n };\n }\n\n const ALLOWED_KEYS = new Set<string>([\n 'fields',\n 'pagePath',\n 'persistence',\n 'entityName',\n 'collection',\n 'traitOverrides',\n ]);\n for (const key of Object.keys(raw)) {\n if (!ALLOWED_KEYS.has(key)) {\n return { ok: false, error: { kind: 'unknown-key', key } };\n }\n }\n\n // raw is a plain object whose keys are restricted to OrbitalFactoryParams\n // keys; assert the shape now (no widening to follow). Field-level type\n // checks live downstream — the orbital validator catches malformed\n // EntityField / TraitConfig at the lolo / orbital-rust layer.\n const candidate = raw as OrbitalFactoryParams;\n if (candidate.traitOverrides !== undefined) {\n const to = candidate.traitOverrides;\n if (to === null || typeof to !== 'object' || Array.isArray(to)) {\n return {\n ok: false,\n error: {\n kind: 'trait-overrides-not-object',\n received: Array.isArray(to) ? 'array' : typeof to,\n },\n };\n }\n const allowed = new Set<string>(manifest.traitNames);\n for (const traitName of Object.keys(to)) {\n if (!allowed.has(traitName)) {\n return {\n ok: false,\n error: {\n kind: 'unknown-trait-override',\n trait: traitName,\n allowed: manifest.traitNames,\n },\n };\n }\n }\n }\n\n return { ok: true, params: candidate };\n}\n\ninterface OverlayContext {\n readonly canonicalEntityName: string;\n readonly canonicalEntity: OrbitalEntity;\n}\n\n/**\n * `orbital.entity` is `EntityRef = Entity | string | EntityCall`. For the\n * overlay we require a fully-resolved inline `OrbitalEntity` (the script\n * runs against resolved `.orb`s where every entity has been materialized).\n * Strings and `EntityCall` shapes mean the caller passed an unresolved orb.\n */\nfunction assertResolvedEntity(\n entity: OrbitalSchema['orbitals'][number]['entity'],\n orbitalName: string,\n orbName: string,\n): OrbitalEntity {\n if (typeof entity === 'string') {\n throw new Error(\n `applyParamsToOrb: orbital \"${orbitalName}\" in orb \"${orbName}\" has an unresolved entity reference (string form). Pass a resolved .orb.`,\n );\n }\n if ('extends' in entity) {\n throw new Error(\n `applyParamsToOrb: orbital \"${orbitalName}\" in orb \"${orbName}\" has an unresolved EntityCall (\"extends\" form). Pass a resolved .orb.`,\n );\n }\n return entity;\n}\n\nfunction findOrbitalOrThrow(\n orb: OrbitalSchema,\n orbitalName: string,\n): OrbitalSchema['orbitals'][number] {\n const orbital = orb.orbitals.find((o) => o.name === orbitalName);\n if (!orbital) {\n throw new Error(\n `applyParamsToOrb: orbital \"${orbitalName}\" not found in orb \"${orb.name}\". Available: ${orb.orbitals\n .map((o) => o.name)\n .join(', ')}`,\n );\n }\n return orbital;\n}\n\nfunction buildEntity(\n ctx: OverlayContext,\n effectiveName: string,\n effectiveCollection: string | undefined,\n params: OrbitalFactoryParams,\n): Entity {\n const canonicalFields: readonly EntityField[] = Array.isArray(ctx.canonicalEntity.fields)\n ? ctx.canonicalEntity.fields\n : [];\n\n // Caller-wins merge: drop canonical entries whose name appears in\n // params.fields, then concat the extras. Prevents ORB_E_DUPLICATE_FIELD\n // when the analyzer hallucinates a canonical-named field as an \"extra\".\n const extras: readonly EntityField[] = params.fields ?? [];\n let mergedFields: readonly EntityField[];\n if (extras.length === 0) {\n mergedFields = canonicalFields;\n } else {\n const extraNames = new Set(extras.map((f) => f.name));\n mergedFields = [\n ...canonicalFields.filter((f) => !extraNames.has(f.name)),\n ...extras,\n ];\n }\n\n const entity: Entity = {\n name: effectiveName,\n persistence: params.persistence ?? ctx.canonicalEntity.persistence,\n fields: [...mergedFields],\n };\n if (effectiveCollection !== undefined) {\n entity.collection = effectiveCollection;\n }\n return entity;\n}\n\ntype TraitOrInline = OrbitalSchema['orbitals'][number]['traits'][number];\ntype PageOrRef = NonNullable<OrbitalSchema['orbitals'][number]['pages']>[number];\n\nfunction isTraitReferenceObject(t: TraitOrInline): t is TraitReference {\n // Narrow guard. `t` comes from `orbital.traits` which is a union of\n // `TraitReference | (inline trait shape)`. The codegen emits the same\n // structural test before rewriting `linkedEntity`.\n if (t === null || typeof t !== 'object') return false;\n if (!('ref' in t)) return false;\n return typeof t.ref === 'string';\n}\n\nfunction isPageRefObject(p: PageOrRef): p is PageRefObject {\n if (p === null || typeof p !== 'object') return false;\n if (!('ref' in p)) return false;\n return typeof p.ref === 'string';\n}\n\nfunction rebuildTraits(\n ctx: OverlayContext,\n effectiveEntityName: string,\n traits: OrbitalSchema['orbitals'][number]['traits'],\n): OrbitalDefinition['traits'] {\n return traits.map((t) => {\n if (!isTraitReferenceObject(t)) {\n return t;\n }\n const rewrittenLinkedEntity =\n t.linkedEntity === ctx.canonicalEntityName ? effectiveEntityName : t.linkedEntity;\n // Cast widens `TraitReference.effects: Record<string, unknown[]>` to the\n // narrower `MakeTraitRefOpts.effects: Record<string, SExpr[]>` — same\n // runtime data, looser typing on the schema side. Not `as unknown as`.\n const opts: MakeTraitRefOpts = {\n ...t,\n linkedEntity: rewrittenLinkedEntity,\n } as MakeTraitRefOpts;\n return makeTraitRef(opts);\n });\n}\n\nfunction rebuildPages(\n ctx: OverlayContext,\n effectiveEntityName: string,\n pages: OrbitalSchema['orbitals'][number]['pages'],\n): NonNullable<OrbitalDefinition['pages']> {\n if (!pages) return [];\n return pages.map((p) => {\n if (!isPageRefObject(p)) {\n return p;\n }\n const rewrittenLinkedEntity =\n p.linkedEntity === ctx.canonicalEntityName ? effectiveEntityName : p.linkedEntity;\n const opts: MakePageRefOpts = {\n ...p,\n linkedEntity: rewrittenLinkedEntity,\n } as MakePageRefOpts;\n return makePageRef(opts);\n });\n}\n\n/**\n * The overlay. Resolves the effective entity name + collection, calls\n * `makeOrbitalWithUses` with the rewritten data, then applies the params'\n * trait/page overrides post-hoc — exactly mirroring the codegen emit at\n * `scripts/regenerate-std-ts.mjs:612-737`.\n *\n * `_manifest` is accepted for parity with the future dispatcher signature\n * but is unused in this overlay — the manifest is consumed by\n * `validateOrbitalFactoryParams` upstream. Kept on the signature so std\n * factories can collapse to one-line wrappers without an arg-shape change.\n */\nexport function applyParamsToOrb(\n orb: OrbitalSchema,\n orbitalName: string,\n _manifest: OrbitalParamsManifest,\n params: OrbitalFactoryParams,\n): OrbitalDefinition {\n const orbital = findOrbitalOrThrow(orb, orbitalName);\n const canonicalEntity = assertResolvedEntity(orbital.entity, orbitalName, orb.name);\n const canonicalEntityName = canonicalEntity.name;\n const effectiveEntityName = params.entityName ?? canonicalEntityName;\n const effectiveCollection =\n typeof canonicalEntity.collection === 'string'\n ? (params.collection ??\n (params.entityName\n ? `${params.entityName.toLowerCase()}s`\n : canonicalEntity.collection))\n : params.collection;\n\n const ctx: OverlayContext = { canonicalEntityName, canonicalEntity };\n\n const built = makeOrbitalWithUses({\n name: orbital.name,\n uses: orbital.uses ?? [],\n entity: buildEntity(ctx, effectiveEntityName, effectiveCollection, params),\n traits: rebuildTraits(ctx, effectiveEntityName, orbital.traits),\n pages: rebuildPages(ctx, effectiveEntityName, orbital.pages),\n });\n\n if (built.traits && params.traitOverrides !== undefined) {\n built.traits = built.traits.map((t) => {\n if (!isTraitReferenceObject(t) || typeof t.name !== 'string') return t;\n const override: OrbitalTraitOverride | undefined = params.traitOverrides?.[t.name];\n if (!override) return t;\n const merged: TraitReference = { ...t };\n if (override.config !== undefined) {\n merged.config = { ...(t.config ?? {}), ...override.config };\n }\n if (override.linkedEntity !== undefined) merged.linkedEntity = override.linkedEntity;\n if (override.events !== undefined) {\n merged.events = { ...(t.events ?? {}), ...override.events };\n }\n if (override.name !== undefined) merged.name = override.name;\n if (override.emitsScope !== undefined) merged.emitsScope = override.emitsScope;\n if (override.listens !== undefined) merged.listens = override.listens;\n return merged;\n });\n }\n\n if (built.pages && params.pagePath !== undefined) {\n built.pages = built.pages.map((p, idx) => {\n if (!isPageRefObject(p) || idx !== 0) return p;\n return { ...p, path: params.pagePath } as PageRefObject;\n });\n }\n\n return built;\n}\n","/**\n * `applyParamsToWholeOrb` — pure runtime overlay for an ENTIRE stored orb.\n *\n * Companion to `applyParamsToOrb` (single-orbital). Where `applyParamsToOrb`\n * materialises one orbital from a multi-orbital schema, this function applies\n * the same overlay to every orbital in the schema by joining each orbital to\n * its matching manifest entry from `manifests[]`. Returns a new\n * `OrbitalSchema` with the rebuilt orbitals.\n *\n * Used by team-behavior dispatch on the LLM-loop seam (`call_behavior` tool\n * in @almadar/agent): the LLM emits `call_behavior('team/<name>@<v>', params)`,\n * std-import returns undefined, the agent's `extra.dispatchWhole` port runs\n * this function over the Firestore-stored record's `{ orb, manifests }`.\n *\n * Reference: `docs/Almadar_Studio_SDK.md` §7.4.4.\n *\n * Pure data → data. No I/O.\n *\n * @packageDocumentation\n */\n\nimport type { OrbitalDefinition, OrbitalSchema } from '@almadar/core';\nimport type { OrbitalParamsManifest } from '../behaviors/functions/dispatch.js';\nimport type { OrbitalFactoryParams } from './types.js';\nimport { applyParamsToOrb } from './apply-params-to-orb.js';\n\n/**\n * Apply `params` to every orbital in `orb` that has a matching manifest in\n * `manifests[]`. Orbitals with no manifest are passed through unchanged —\n * the storage convention is one manifest per orbital, so a missing manifest\n * indicates a stored orbital we don't know how to parameterise (rare; the\n * promote path writes manifests for every orbital it knows).\n *\n * @param orb The full team-behavior schema as stored.\n * @param manifests Per-orbital param manifests; joined to orbitals by name.\n * @param params One shared params bag applied to every parameterised\n * orbital. Mirrors the std whole-behavior factories'\n * convention of a single `params` argument.\n */\nexport function applyParamsToWholeOrb(\n orb: OrbitalSchema,\n manifests: readonly OrbitalParamsManifest[],\n params: OrbitalFactoryParams,\n): OrbitalSchema {\n const manifestByOrbital = new Map<string, OrbitalParamsManifest>();\n for (const m of manifests) {\n manifestByOrbital.set(m.orbitalName, m);\n }\n const rebuilt: OrbitalDefinition[] = [];\n for (const orbital of orb.orbitals) {\n const manifest = manifestByOrbital.get(orbital.name);\n if (!manifest) {\n rebuilt.push(orbital);\n continue;\n }\n rebuilt.push(applyParamsToOrb(orb, orbital.name, manifest, params));\n }\n return { ...orb, orbitals: rebuilt };\n}\n"]}