@almadar/runtime 2.6.2 → 2.7.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-CvYnmqkg.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-CJYMN0d3.js';
3
+ import './types-CvYnmqkg.js';
4
4
  import '@almadar/core';
@@ -1,12 +1,85 @@
1
- import { EventBus, createUnifiedLoader, preprocessSchema, StateMachineManager, createContextFromBindings, EffectExecutor } from './chunk-ESNML4B4.js';
1
+ import { EventBus, createUnifiedLoader, preprocessSchema, StateMachineManager, createContextFromBindings, EffectExecutor } from './chunk-ZYH3XSOL.js';
2
2
  import { Router } from 'express';
3
+ import * as fs from 'fs';
4
+ import fs__default from 'fs';
5
+ import path from 'path';
3
6
  import { evaluateGuard, evaluate } from '@almadar/evaluator';
4
7
  import { isInlineTrait } from '@almadar/core';
5
8
  import { faker } from '@faker-js/faker';
6
- import * as fs from 'fs';
7
9
  import * as net from 'net';
8
10
  import { execSync } from 'child_process';
9
11
 
12
+ var LocalPersistenceAdapter = class {
13
+ root;
14
+ constructor(root) {
15
+ this.root = root;
16
+ fs__default.mkdirSync(root, { recursive: true });
17
+ }
18
+ entityDir(entityType) {
19
+ const dir = path.join(this.root, entityType.toLowerCase());
20
+ fs__default.mkdirSync(dir, { recursive: true });
21
+ return dir;
22
+ }
23
+ filePath(entityType, id) {
24
+ return path.join(this.entityDir(entityType), `${id}.json`);
25
+ }
26
+ async create(entityType, data) {
27
+ const id = data.id || `${entityType.toLowerCase()}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
28
+ const record = { ...data, id };
29
+ const filePath = this.filePath(entityType, id);
30
+ fs__default.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
31
+ return { id };
32
+ }
33
+ async update(entityType, id, data) {
34
+ const filePath = this.filePath(entityType, id);
35
+ let existing = { id };
36
+ if (fs__default.existsSync(filePath)) {
37
+ existing = JSON.parse(fs__default.readFileSync(filePath, "utf-8"));
38
+ }
39
+ const merged = { ...existing, ...data, id };
40
+ fs__default.writeFileSync(filePath, JSON.stringify(merged, null, 2), "utf-8");
41
+ }
42
+ async delete(entityType, id) {
43
+ const filePath = this.filePath(entityType, id);
44
+ if (fs__default.existsSync(filePath)) {
45
+ fs__default.unlinkSync(filePath);
46
+ }
47
+ }
48
+ async getById(entityType, id) {
49
+ const filePath = this.filePath(entityType, id);
50
+ if (!fs__default.existsSync(filePath)) return null;
51
+ return JSON.parse(fs__default.readFileSync(filePath, "utf-8"));
52
+ }
53
+ async list(entityType) {
54
+ const dir = this.entityDir(entityType);
55
+ if (!fs__default.existsSync(dir)) return [];
56
+ const files = fs__default.readdirSync(dir).filter((f) => f.endsWith(".json"));
57
+ const results = [];
58
+ for (const file of files) {
59
+ const content = fs__default.readFileSync(path.join(dir, file), "utf-8");
60
+ results.push(JSON.parse(content));
61
+ }
62
+ return results;
63
+ }
64
+ /**
65
+ * Remove all data for an entity type.
66
+ */
67
+ async clear(entityType) {
68
+ const dir = path.join(this.root, entityType.toLowerCase());
69
+ if (fs__default.existsSync(dir)) {
70
+ fs__default.rmSync(dir, { recursive: true, force: true });
71
+ }
72
+ }
73
+ /**
74
+ * Remove all local data.
75
+ */
76
+ async clearAll() {
77
+ if (fs__default.existsSync(this.root)) {
78
+ fs__default.rmSync(this.root, { recursive: true, force: true });
79
+ fs__default.mkdirSync(this.root, { recursive: true });
80
+ }
81
+ }
82
+ };
10
83
  var MockPersistenceAdapter = class {
11
84
  stores = /* @__PURE__ */ new Map();
12
85
  schemas = /* @__PURE__ */ new Map();
@@ -563,6 +636,7 @@ var OrbitalServerRuntime = class {
563
636
  entitySharingMap = {};
564
637
  eventNamespaceMap = {};
565
638
  osHandlers = null;
639
+ localPersistence = null;
566
640
  constructor(config = {}) {
567
641
  this.config = {
568
642
  mode: "mock",
@@ -591,6 +665,9 @@ var OrbitalServerRuntime = class {
591
665
  } else {
592
666
  this.persistence = config.persistence || new InMemoryPersistence();
593
667
  }
668
+ if (config.localStorageRoot) {
669
+ this.localPersistence = new LocalPersistenceAdapter(config.localStorageRoot);
670
+ }
594
671
  this.osHandlers = createOsHandlers({
595
672
  emitEvent: (type, payload) => this.eventBus.emit(type, payload)
596
673
  });
@@ -757,7 +834,9 @@ var OrbitalServerRuntime = class {
757
834
  listens: t.listens
758
835
  };
759
836
  });
760
- const manager = new StateMachineManager(traitDefs);
837
+ const manager = new StateMachineManager(traitDefs, {
838
+ contextExtensions: this.config.contextExtensions
839
+ });
761
840
  const entityRef = orbital.entity;
762
841
  const entity = typeof entityRef === "string" ? { name: entityRef, fields: [] } : entityRef;
763
842
  this.orbitals.set(orbital.name, {
@@ -957,7 +1036,7 @@ var OrbitalServerRuntime = class {
957
1036
  entity,
958
1037
  payload: {},
959
1038
  state: registered.manager.getState(traitName)?.currentState || "unknown"
960
- });
1039
+ }, false, this.config.contextExtensions);
961
1040
  const guardPasses = evaluateGuard(
962
1041
  tick.guard,
963
1042
  ctx
@@ -1434,7 +1513,7 @@ var OrbitalServerRuntime = class {
1434
1513
  current,
1435
1514
  entity: entityData,
1436
1515
  payload
1437
- });
1516
+ }, false, this.config.contextExtensions);
1438
1517
  let newData;
1439
1518
  if (Array.isArray(transform)) {
1440
1519
  const result = evaluate(
@@ -1487,7 +1566,8 @@ var OrbitalServerRuntime = class {
1487
1566
  handlers,
1488
1567
  bindings: bindingsRef ?? {},
1489
1568
  context: contextRef ?? { traitName, state: "unknown", transition: "unknown" },
1490
- debug: this.config.debug
1569
+ debug: this.config.debug,
1570
+ contextExtensions: this.config.contextExtensions
1491
1571
  });
1492
1572
  for (const innerEffect of atomicEffects) {
1493
1573
  if (atomicFailed) break;
@@ -1516,8 +1596,8 @@ var OrbitalServerRuntime = class {
1516
1596
  renderUI: (slot, pattern, props, priority) => {
1517
1597
  clientEffects.push(["render-ui", slot, pattern, props, priority]);
1518
1598
  },
1519
- navigate: (path, params) => {
1520
- clientEffects.push(["navigate", path, params]);
1599
+ navigate: (path2, params) => {
1600
+ clientEffects.push(["navigate", path2, params]);
1521
1601
  },
1522
1602
  notify: (message, type) => {
1523
1603
  if (this.config.debug) {
@@ -1555,7 +1635,8 @@ var OrbitalServerRuntime = class {
1555
1635
  handlers,
1556
1636
  bindings,
1557
1637
  context,
1558
- debug: this.config.debug
1638
+ debug: this.config.debug,
1639
+ contextExtensions: this.config.contextExtensions
1559
1640
  });
1560
1641
  await executor.executeAll(effects);
1561
1642
  }
@@ -1891,6 +1972,6 @@ function createOrbitalServerRuntime(config) {
1891
1972
  return new OrbitalServerRuntime(config);
1892
1973
  }
1893
1974
 
1894
- export { OrbitalServerRuntime, createOrbitalServerRuntime };
1975
+ export { LocalPersistenceAdapter, OrbitalServerRuntime, createOrbitalServerRuntime };
1895
1976
  //# sourceMappingURL=OrbitalServerRuntime.js.map
1896
1977
  //# sourceMappingURL=OrbitalServerRuntime.js.map