@almadar/runtime 2.6.2 → 3.0.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,5 +1,5 @@
1
1
  import { Router } from 'express';
2
- import { I as IEventBus, f as RuntimeEvent, e as EventListener, U as Unsubscribe, T as TraitDefinition, R as RuntimeConfig, h as TransitionObserver, g as TraitState, i as TransitionResult, E as EffectHandlers } from './types-DYcUvi4H.js';
2
+ import { I as IEventBus, g as RuntimeEvent, f as EventListener, U as Unsubscribe, T as TraitDefinition, R as RuntimeConfig, i as TransitionObserver, h as TraitState, j as TransitionResult, E as EvaluationContextExtensions, a as EffectHandlers } from './types-CM6txTNy.js';
3
3
  import { EventPayload, EntityRow, OrbitalSchema, Orbital, Trait, OrbitalDefinition, Entity, TraitTick } from '@almadar/core';
4
4
 
5
5
  /**
@@ -126,6 +126,11 @@ interface ProcessEventOptions {
126
126
  * When true, log warnings when bindings resolve to undefined. (RCG-01)
127
127
  */
128
128
  strictBindings?: boolean;
129
+ /**
130
+ * Additional fields to spread onto EvaluationContext for guard evaluation.
131
+ * Used to inject module contexts (e.g., { agent: AgentContext }).
132
+ */
133
+ contextExtensions?: EvaluationContextExtensions;
129
134
  }
130
135
  /**
131
136
  * Process an event through a trait's state machine.
@@ -238,6 +243,48 @@ declare class StateMachineManager {
238
243
  resetAll(): void;
239
244
  }
240
245
 
246
+ /**
247
+ * LocalPersistenceAdapter - Filesystem CRUD for `persistence: "local"` entities.
248
+ *
249
+ * One directory per entity type, one JSON file per instance.
250
+ * Language-level feature: benefits all .orb programs, not just the agent.
251
+ * Offline-first apps, CLI tools, config managers, local databases all use it.
252
+ *
253
+ * @packageDocumentation
254
+ */
255
+
256
+ /**
257
+ * Filesystem-backed persistence adapter.
258
+ *
259
+ * Storage layout:
260
+ * ```
261
+ * {root}/
262
+ * {entityType}/
263
+ * {id}.json
264
+ * ```
265
+ */
266
+ declare class LocalPersistenceAdapter implements PersistenceAdapter {
267
+ private readonly root;
268
+ constructor(root: string);
269
+ private entityDir;
270
+ private filePath;
271
+ create(entityType: string, data: EntityRow): Promise<{
272
+ id: string;
273
+ }>;
274
+ update(entityType: string, id: string, data: EntityRow): Promise<void>;
275
+ delete(entityType: string, id: string): Promise<void>;
276
+ getById(entityType: string, id: string): Promise<EntityRow | null>;
277
+ list(entityType: string): Promise<EntityRow[]>;
278
+ /**
279
+ * Remove all data for an entity type.
280
+ */
281
+ clear(entityType: string): Promise<void>;
282
+ /**
283
+ * Remove all local data.
284
+ */
285
+ clearAll(): Promise<void>;
286
+ }
287
+
241
288
  /**
242
289
  * External Orbital Loader
243
290
  *
@@ -702,6 +749,17 @@ interface OrbitalServerRuntimeConfig {
702
749
  * Default: true
703
750
  */
704
751
  namespaceEvents?: boolean;
752
+ /**
753
+ * Root directory for `persistence: "local"` entities.
754
+ * Default: ~/.orb/data/
755
+ */
756
+ localStorageRoot?: string;
757
+ /**
758
+ * Additional fields to spread onto every EvaluationContext.
759
+ * Use this to inject module contexts (e.g., { agent: AgentContext }).
760
+ * The evaluator dispatches agent/* operators to ctx.agent.
761
+ */
762
+ contextExtensions?: EvaluationContextExtensions;
705
763
  }
706
764
  /**
707
765
  * Adapter for persisting entity data
@@ -727,6 +785,7 @@ declare class OrbitalServerRuntime {
727
785
  private entitySharingMap;
728
786
  private eventNamespaceMap;
729
787
  private osHandlers;
788
+ private localPersistence;
730
789
  constructor(config?: OrbitalServerRuntimeConfig);
731
790
  /**
732
791
  * Register an OrbitalSchema for execution.
@@ -906,4 +965,4 @@ declare class OrbitalServerRuntime {
906
965
  */
907
966
  declare function createOrbitalServerRuntime(config?: OrbitalServerRuntimeConfig): OrbitalServerRuntime;
908
967
 
909
- export { type EntitySharingMap as E, type LoaderConfig as L, type OrbitalEventRequest as O, type PersistenceAdapter as P, type RegisteredOrbital as R, StateMachineManager as S, EventBus as a, type EventNamespaceMap as b, type OrbitalEventResponse as c, type OrbitalServerRuntimeConfig as d, type PreprocessOptions as e, type PreprocessResult as f, type PreprocessedSchema as g, type ProcessEventOptions as h, type RuntimeOrbital as i, type RuntimeOrbitalSchema as j, type RuntimeTrait as k, createInitialTraitState as l, findInitialState as m, findTransition as n, getIsolatedCollectionName as o, getNamespacedEvent as p, isNamespacedEvent as q, normalizeEventKey as r, parseNamespacedEvent as s, preprocessSchema as t, processEvent as u, type EffectResult as v, OrbitalServerRuntime as w, type RuntimeTraitTick as x, createOrbitalServerRuntime as y };
968
+ export { type EntitySharingMap as E, type LoaderConfig as L, type OrbitalEventRequest as O, type PersistenceAdapter as P, type RegisteredOrbital as R, StateMachineManager as S, EventBus as a, type EventNamespaceMap as b, type OrbitalEventResponse as c, type OrbitalServerRuntimeConfig as d, type PreprocessOptions as e, type PreprocessResult as f, type PreprocessedSchema as g, type ProcessEventOptions as h, type RuntimeOrbital as i, type RuntimeOrbitalSchema as j, type RuntimeTrait as k, createInitialTraitState as l, findInitialState as m, findTransition as n, getIsolatedCollectionName as o, getNamespacedEvent as p, isNamespacedEvent as q, normalizeEventKey as r, parseNamespacedEvent as s, preprocessSchema as t, processEvent as u, type EffectResult as v, LocalPersistenceAdapter as w, OrbitalServerRuntime as x, type RuntimeTraitTick as y, createOrbitalServerRuntime as z };
@@ -1,4 +1,4 @@
1
1
  import 'express';
2
- export { v as EffectResult, L as LoaderConfig, O as OrbitalEventRequest, c as OrbitalEventResponse, w as OrbitalServerRuntime, d as OrbitalServerRuntimeConfig, P as PersistenceAdapter, R as RegisteredOrbital, i as RuntimeOrbital, j as RuntimeOrbitalSchema, k as RuntimeTrait, x as RuntimeTraitTick, y as createOrbitalServerRuntime } from './OrbitalServerRuntime-BlR7TM23.js';
3
- import './types-DYcUvi4H.js';
2
+ export { v as EffectResult, L as LoaderConfig, w as LocalPersistenceAdapter, O as OrbitalEventRequest, c as OrbitalEventResponse, x as OrbitalServerRuntime, d as OrbitalServerRuntimeConfig, P as PersistenceAdapter, R as RegisteredOrbital, i as RuntimeOrbital, j as RuntimeOrbitalSchema, k as RuntimeTrait, y as RuntimeTraitTick, z as createOrbitalServerRuntime } from './OrbitalServerRuntime-QXgOGiS8.js';
3
+ import './types-CM6txTNy.js';
4
4
  import '@almadar/core';
@@ -1,12 +1,86 @@
1
- import { EventBus, createUnifiedLoader, preprocessSchema, StateMachineManager, createContextFromBindings, EffectExecutor } from './chunk-ESNML4B4.js';
1
+ import { EventBus, createUnifiedLoader, preprocessSchema, StateMachineManager, createContextFromBindings, EffectExecutor } from './chunk-HIM4HJAN.js';
2
+ import './chunk-PZ5AY32C.js';
2
3
  import { Router } from 'express';
4
+ import * as fs from 'fs';
5
+ import fs__default from 'fs';
6
+ import path from 'path';
3
7
  import { evaluateGuard, evaluate } from '@almadar/evaluator';
4
- import { isInlineTrait } from '@almadar/core';
8
+ import { isInlineTrait, isEntityCall } from '@almadar/core';
5
9
  import { faker } from '@faker-js/faker';
6
- import * as fs from 'fs';
7
10
  import * as net from 'net';
8
11
  import { execSync } from 'child_process';
9
12
 
13
+ var LocalPersistenceAdapter = class {
14
+ root;
15
+ constructor(root) {
16
+ this.root = root;
17
+ fs__default.mkdirSync(root, { recursive: true });
18
+ }
19
+ entityDir(entityType) {
20
+ const dir = path.join(this.root, entityType.toLowerCase());
21
+ fs__default.mkdirSync(dir, { recursive: true });
22
+ return dir;
23
+ }
24
+ filePath(entityType, id) {
25
+ return path.join(this.entityDir(entityType), `${id}.json`);
26
+ }
27
+ async create(entityType, data) {
28
+ const id = data.id || `${entityType.toLowerCase()}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
29
+ const record = { ...data, id };
30
+ const filePath = this.filePath(entityType, id);
31
+ fs__default.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
32
+ return { id };
33
+ }
34
+ async update(entityType, id, data) {
35
+ const filePath = this.filePath(entityType, id);
36
+ let existing = { id };
37
+ if (fs__default.existsSync(filePath)) {
38
+ existing = JSON.parse(fs__default.readFileSync(filePath, "utf-8"));
39
+ }
40
+ const merged = { ...existing, ...data, id };
41
+ fs__default.writeFileSync(filePath, JSON.stringify(merged, null, 2), "utf-8");
42
+ }
43
+ async delete(entityType, id) {
44
+ const filePath = this.filePath(entityType, id);
45
+ if (fs__default.existsSync(filePath)) {
46
+ fs__default.unlinkSync(filePath);
47
+ }
48
+ }
49
+ async getById(entityType, id) {
50
+ const filePath = this.filePath(entityType, id);
51
+ if (!fs__default.existsSync(filePath)) return null;
52
+ return JSON.parse(fs__default.readFileSync(filePath, "utf-8"));
53
+ }
54
+ async list(entityType) {
55
+ const dir = this.entityDir(entityType);
56
+ if (!fs__default.existsSync(dir)) return [];
57
+ const files = fs__default.readdirSync(dir).filter((f) => f.endsWith(".json"));
58
+ const results = [];
59
+ for (const file of files) {
60
+ const content = fs__default.readFileSync(path.join(dir, file), "utf-8");
61
+ results.push(JSON.parse(content));
62
+ }
63
+ return results;
64
+ }
65
+ /**
66
+ * Remove all data for an entity type.
67
+ */
68
+ async clear(entityType) {
69
+ const dir = path.join(this.root, entityType.toLowerCase());
70
+ if (fs__default.existsSync(dir)) {
71
+ fs__default.rmSync(dir, { recursive: true, force: true });
72
+ }
73
+ }
74
+ /**
75
+ * Remove all local data.
76
+ */
77
+ async clearAll() {
78
+ if (fs__default.existsSync(this.root)) {
79
+ fs__default.rmSync(this.root, { recursive: true, force: true });
80
+ fs__default.mkdirSync(this.root, { recursive: true });
81
+ }
82
+ }
83
+ };
10
84
  var MockPersistenceAdapter = class {
11
85
  stores = /* @__PURE__ */ new Map();
12
86
  schemas = /* @__PURE__ */ new Map();
@@ -563,6 +637,7 @@ var OrbitalServerRuntime = class {
563
637
  entitySharingMap = {};
564
638
  eventNamespaceMap = {};
565
639
  osHandlers = null;
640
+ localPersistence = null;
566
641
  constructor(config = {}) {
567
642
  this.config = {
568
643
  mode: "mock",
@@ -591,6 +666,9 @@ var OrbitalServerRuntime = class {
591
666
  } else {
592
667
  this.persistence = config.persistence || new InMemoryPersistence();
593
668
  }
669
+ if (config.localStorageRoot) {
670
+ this.localPersistence = new LocalPersistenceAdapter(config.localStorageRoot);
671
+ }
594
672
  this.osHandlers = createOsHandlers({
595
673
  emitEvent: (type, payload) => this.eventBus.emit(type, payload)
596
674
  });
@@ -757,9 +835,24 @@ var OrbitalServerRuntime = class {
757
835
  listens: t.listens
758
836
  };
759
837
  });
760
- const manager = new StateMachineManager(traitDefs);
838
+ const manager = new StateMachineManager(traitDefs, {
839
+ contextExtensions: this.config.contextExtensions
840
+ });
761
841
  const entityRef = orbital.entity;
762
- const entity = typeof entityRef === "string" ? { name: entityRef, fields: [] } : entityRef;
842
+ let entity;
843
+ if (typeof entityRef === "string") {
844
+ entity = { name: entityRef, fields: [] };
845
+ } else if (isEntityCall(entityRef)) {
846
+ const fallbackName = entityRef.name ?? entityRef.extends.replace(/\.entity$/, "");
847
+ entity = {
848
+ name: fallbackName,
849
+ fields: entityRef.fields ?? [],
850
+ ...entityRef.persistence ? { persistence: entityRef.persistence } : {},
851
+ ...entityRef.collection ? { collection: entityRef.collection } : {}
852
+ };
853
+ } else {
854
+ entity = entityRef;
855
+ }
763
856
  this.orbitals.set(orbital.name, {
764
857
  schema: orbital,
765
858
  entity,
@@ -957,7 +1050,7 @@ var OrbitalServerRuntime = class {
957
1050
  entity,
958
1051
  payload: {},
959
1052
  state: registered.manager.getState(traitName)?.currentState || "unknown"
960
- });
1053
+ }, false, this.config.contextExtensions);
961
1054
  const guardPasses = evaluateGuard(
962
1055
  tick.guard,
963
1056
  ctx
@@ -1434,7 +1527,7 @@ var OrbitalServerRuntime = class {
1434
1527
  current,
1435
1528
  entity: entityData,
1436
1529
  payload
1437
- });
1530
+ }, false, this.config.contextExtensions);
1438
1531
  let newData;
1439
1532
  if (Array.isArray(transform)) {
1440
1533
  const result = evaluate(
@@ -1487,7 +1580,8 @@ var OrbitalServerRuntime = class {
1487
1580
  handlers,
1488
1581
  bindings: bindingsRef ?? {},
1489
1582
  context: contextRef ?? { traitName, state: "unknown", transition: "unknown" },
1490
- debug: this.config.debug
1583
+ debug: this.config.debug,
1584
+ contextExtensions: this.config.contextExtensions
1491
1585
  });
1492
1586
  for (const innerEffect of atomicEffects) {
1493
1587
  if (atomicFailed) break;
@@ -1516,8 +1610,8 @@ var OrbitalServerRuntime = class {
1516
1610
  renderUI: (slot, pattern, props, priority) => {
1517
1611
  clientEffects.push(["render-ui", slot, pattern, props, priority]);
1518
1612
  },
1519
- navigate: (path, params) => {
1520
- clientEffects.push(["navigate", path, params]);
1613
+ navigate: (path2, params) => {
1614
+ clientEffects.push(["navigate", path2, params]);
1521
1615
  },
1522
1616
  notify: (message, type) => {
1523
1617
  if (this.config.debug) {
@@ -1555,7 +1649,8 @@ var OrbitalServerRuntime = class {
1555
1649
  handlers,
1556
1650
  bindings,
1557
1651
  context,
1558
- debug: this.config.debug
1652
+ debug: this.config.debug,
1653
+ contextExtensions: this.config.contextExtensions
1559
1654
  });
1560
1655
  await executor.executeAll(effects);
1561
1656
  }
@@ -1891,6 +1986,6 @@ function createOrbitalServerRuntime(config) {
1891
1986
  return new OrbitalServerRuntime(config);
1892
1987
  }
1893
1988
 
1894
- export { OrbitalServerRuntime, createOrbitalServerRuntime };
1989
+ export { LocalPersistenceAdapter, OrbitalServerRuntime, createOrbitalServerRuntime };
1895
1990
  //# sourceMappingURL=OrbitalServerRuntime.js.map
1896
1991
  //# sourceMappingURL=OrbitalServerRuntime.js.map