@almadar/server 2.0.1 → 2.0.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,174 @@
1
+ /**
2
+ * Server Service Contracts
3
+ *
4
+ * Type-safe contract definitions for the three main services
5
+ * callable from .orb schemas via `["call-service", ...]`.
6
+ *
7
+ * Each contract maps action names to their params/result types,
8
+ * and the corresponding `ServiceContract<Actions>` type ensures
9
+ * the runtime `execute(action, params)` call is fully typed.
10
+ *
11
+ * @packageDocumentation
12
+ */
13
+ import type { ServiceContract, ServiceEvents } from '@almadar/core';
14
+ /** Actions available on the data service (CRUD over collections). */
15
+ export type DataServiceActions = {
16
+ list: {
17
+ params: {
18
+ collection: string;
19
+ };
20
+ result: {
21
+ items: unknown[];
22
+ };
23
+ };
24
+ getById: {
25
+ params: {
26
+ collection: string;
27
+ id: string;
28
+ };
29
+ result: {
30
+ item: unknown | null;
31
+ };
32
+ };
33
+ create: {
34
+ params: {
35
+ collection: string;
36
+ data: Record<string, unknown>;
37
+ };
38
+ result: {
39
+ item: unknown;
40
+ };
41
+ };
42
+ update: {
43
+ params: {
44
+ collection: string;
45
+ id: string;
46
+ data: Record<string, unknown>;
47
+ };
48
+ result: {
49
+ item: unknown | null;
50
+ };
51
+ };
52
+ delete: {
53
+ params: {
54
+ collection: string;
55
+ id: string;
56
+ };
57
+ result: {
58
+ deleted: boolean;
59
+ };
60
+ };
61
+ };
62
+ /** Typed contract for the data service. */
63
+ export type DataServiceContract = ServiceContract<DataServiceActions>;
64
+ /** Actions available on the event bus service. */
65
+ export type EventBusActions = {
66
+ emit: {
67
+ params: {
68
+ event: string;
69
+ payload?: unknown;
70
+ };
71
+ result: {
72
+ delivered: number;
73
+ };
74
+ };
75
+ getListenerCounts: {
76
+ params: Record<string, never>;
77
+ result: {
78
+ counts: Record<string, number>;
79
+ };
80
+ };
81
+ };
82
+ /** Typed contract for the event bus service. */
83
+ export type EventBusServiceContract = ServiceContract<EventBusActions>;
84
+ /** Shape of a discovered service instance. */
85
+ interface DiscoveredService {
86
+ name: string;
87
+ instanceId: string;
88
+ host: string;
89
+ port: number;
90
+ }
91
+ /** Actions available on the service discovery service. */
92
+ export type ServiceDiscoveryActions = {
93
+ register: {
94
+ params: {
95
+ name: string;
96
+ instanceId: string;
97
+ host: string;
98
+ port: number;
99
+ emits: string[];
100
+ listens: string[];
101
+ };
102
+ result: {
103
+ registered: boolean;
104
+ };
105
+ };
106
+ findListeners: {
107
+ params: {
108
+ event: string;
109
+ };
110
+ result: {
111
+ services: DiscoveredService[];
112
+ };
113
+ };
114
+ findEmitters: {
115
+ params: {
116
+ event: string;
117
+ };
118
+ result: {
119
+ services: DiscoveredService[];
120
+ };
121
+ };
122
+ };
123
+ /** Typed contract for the service discovery service. */
124
+ export type ServiceDiscoveryContract = ServiceContract<ServiceDiscoveryActions>;
125
+ /** Events emitted by entity CRUD operations. */
126
+ export type EntityCrudEventMap = {
127
+ [K in `${string}_CREATED`]: Record<string, unknown>;
128
+ } & {
129
+ [K in `${string}_UPDATED`]: Record<string, unknown>;
130
+ } & {
131
+ [K in `${string}_DELETED`]: Record<string, unknown>;
132
+ };
133
+ /** Events emitted/consumed by the server infrastructure. */
134
+ export type ServerEventMap = {
135
+ /** Emitted when a service instance registers with ServiceDiscovery. */
136
+ SERVICE_REGISTERED: {
137
+ name: string;
138
+ instanceId: string;
139
+ host: string;
140
+ port: number;
141
+ };
142
+ /** Emitted when a service instance deregisters or expires. */
143
+ SERVICE_DEREGISTERED: {
144
+ name: string;
145
+ instanceId: string;
146
+ reason: 'explicit' | 'expired';
147
+ };
148
+ /** Emitted when a service health check fails. */
149
+ SERVICE_HEALTH_FAILED: {
150
+ name: string;
151
+ instanceId: string;
152
+ error: string;
153
+ };
154
+ /** Emitted when the distributed event bus connects. */
155
+ TRANSPORT_CONNECTED: {
156
+ instanceId: string;
157
+ transport: string;
158
+ };
159
+ /** Emitted when the distributed event bus disconnects. */
160
+ TRANSPORT_DISCONNECTED: {
161
+ instanceId: string;
162
+ reason: string;
163
+ };
164
+ };
165
+ /** Typed event emitter for server events. */
166
+ export type ServerServiceEvents = ServiceEvents<ServerEventMap>;
167
+ /** All server service contracts keyed by service name. */
168
+ export type ServerServiceContracts = {
169
+ data: DataServiceContract;
170
+ eventBus: EventBusServiceContract;
171
+ serviceDiscovery: ServiceDiscoveryContract;
172
+ };
173
+ export {};
174
+ //# sourceMappingURL=contracts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contracts.d.ts","sourceRoot":"","sources":["../src/contracts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAMpE,qEAAqE;AACrE,MAAM,MAAM,kBAAkB,GAAG;IAC/B,IAAI,EAAE;QACJ,MAAM,EAAE;YAAE,UAAU,EAAE,MAAM,CAAA;SAAE,CAAC;QAC/B,MAAM,EAAE;YAAE,KAAK,EAAE,OAAO,EAAE,CAAA;SAAE,CAAC;KAC9B,CAAC;IACF,OAAO,EAAE;QACP,MAAM,EAAE;YAAE,UAAU,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAA;SAAE,CAAC;QAC3C,MAAM,EAAE;YAAE,IAAI,EAAE,OAAO,GAAG,IAAI,CAAA;SAAE,CAAC;KAClC,CAAC;IACF,MAAM,EAAE;QACN,MAAM,EAAE;YAAE,UAAU,EAAE,MAAM,CAAC;YAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;SAAE,CAAC;QAC9D,MAAM,EAAE;YAAE,IAAI,EAAE,OAAO,CAAA;SAAE,CAAC;KAC3B,CAAC;IACF,MAAM,EAAE;QACN,MAAM,EAAE;YAAE,UAAU,EAAE,MAAM,CAAC;YAAC,EAAE,EAAE,MAAM,CAAC;YAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA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AA;AACnD,IAAA,OAAO,OAAO,KAAA,KAAU,UAAA,GAAa,KAAA,CAAM,IAAA,CAAK,SAAS,CAAA,GAAI,KAAA;AAAA,EAC/D;AACF,CAAC,CAAA;;;AC9GD,IAAI,aAAA,GAAsC,IAAA;AAKnC,SAAS,gBAAA,GAAkC;AAChD,EAAA,IAAI,CAAC,aAAA,EAAe;AAClB,IAAA,aAAA,GAAgB,IAAI,aAAA,CAAc;AAAA,MAChC,EAAA;AAAA,MACA,eAAA,EAAiB,oBAAA;AAAA,MACjB,kBAAA,EAAoB,uBAAA;AAAA,MACpB,qBAAA,EAAuB,0BAAA;AAAA,MACvB,kBAAA,EAAoB,uBAAA;AAAA,MACpB,oBAAA,EAAsB,yBAAA;AAAA,MACtB,kBAAA,EAAoB,uBAAA;AAAA,MACpB,qBAAA,EAAuB,0BAAA;AAAA,MACvB,yBAAA,EAA2B;AAAA,KAC5B,CAAA;AAAA,EACH;AACA,EAAA,OAAO,aAAA;AACT;AAKO,SAAS,kBAAA,GAA2B;AACzC,EAAA,aAAA,GAAgB,IAAA;AAClB","file":"memory.js","sourcesContent":["/**\n * Database Accessors & Initialization\n *\n * This module provides:\n * - `initializeFirebase()` — convenience function to init Firebase from env vars\n * - `getFirestore()`, `getAuth()` — accessors for Firebase services\n * - `db` — lazy Firestore proxy (no eager initialization)\n *\n * The consuming application MUST call `initializeFirebase()` or\n * `admin.initializeApp()` before using any Firebase-dependent features.\n */\n\nimport admin from 'firebase-admin';\n\n/**\n * Initialize Firebase Admin SDK from environment variables.\n *\n * Reads: FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_PRIVATE_KEY,\n * FIREBASE_SERVICE_ACCOUNT_PATH, FIRESTORE_EMULATOR_HOST\n *\n * Safe to call multiple times — returns existing app if already initialized.\n */\nexport function initializeFirebase(): admin.app.App {\n // Already initialized — return existing app\n if (admin.apps.length > 0) {\n return admin.app();\n }\n\n const projectId = process.env.FIREBASE_PROJECT_ID;\n const emulatorHost = process.env.FIRESTORE_EMULATOR_HOST;\n\n // Emulator mode — no credentials needed\n if (emulatorHost) {\n const app = admin.initializeApp({\n projectId: projectId || 'demo-project',\n });\n console.log(`Firebase Admin initialized for emulator: ${emulatorHost}`);\n return app;\n }\n\n // Service account file\n const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;\n if (serviceAccountPath) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const serviceAccount = require(serviceAccountPath);\n return admin.initializeApp({\n credential: admin.credential.cert(serviceAccount),\n projectId,\n });\n }\n\n // Inline credentials\n const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;\n const privateKey = process.env.FIREBASE_PRIVATE_KEY;\n if (projectId && clientEmail && privateKey) {\n return admin.initializeApp({\n credential: admin.credential.cert({\n projectId,\n clientEmail,\n privateKey: privateKey.replace(/\\\\n/g, '\\n'),\n }),\n projectId,\n });\n }\n\n // Application default credentials (Cloud Run, etc.)\n if (projectId) {\n return admin.initializeApp({\n credential: admin.credential.applicationDefault(),\n projectId,\n });\n }\n\n throw new Error(\n '@almadar/server: Cannot initialize Firebase — no credentials found. ' +\n 'Set FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY, ' +\n 'or FIREBASE_SERVICE_ACCOUNT_PATH, or FIRESTORE_EMULATOR_HOST.'\n );\n}\n\n/**\n * Get the initialized Firebase app.\n * Throws if Firebase Admin SDK has not been initialized.\n */\nfunction getApp(): admin.app.App {\n if (admin.apps.length === 0) {\n throw new Error(\n '@almadar/server: Firebase Admin SDK is not initialized. ' +\n 'Call initializeFirebase() or admin.initializeApp() before using @almadar/server.'\n );\n }\n return admin.app();\n}\n\n/**\n * Get Firestore instance from the pre-initialized Firebase app.\n */\nexport function getFirestore(): admin.firestore.Firestore {\n return getApp().firestore();\n}\n\n/**\n * Get Firebase Auth instance from the pre-initialized Firebase app.\n */\nexport function getAuth(): admin.auth.Auth {\n return getApp().auth();\n}\n\n// Re-export admin for convenience\nexport { admin };\n\n/**\n * Lazy Firestore proxy — resolves on first property access, not at import time.\n * This prevents the \"Firebase not initialized\" error during module loading.\n */\nexport const db = new Proxy({} as admin.firestore.Firestore, {\n get(_target, prop, receiver) {\n const firestore = getFirestore();\n const value = Reflect.get(firestore, prop, receiver);\n return typeof value === 'function' ? value.bind(firestore) : value;\n },\n});\n","/**\n * Memory Manager Singleton\n *\n * Provides Firestore-backed memory management for DeepAgent.\n *\n * @packageDocumentation\n */\n\nimport { MemoryManager } from '@almadar/agent';\nimport { db } from '../lib/db.js';\n\nlet memoryManager: MemoryManager | null = null;\n\n/**\n * Get or create the MemoryManager singleton\n */\nexport function getMemoryManager(): MemoryManager {\n if (!memoryManager) {\n memoryManager = new MemoryManager({\n db,\n usersCollection: 'agent_memory_users',\n projectsCollection: 'agent_memory_projects',\n generationsCollection: 'agent_memory_generations',\n patternsCollection: 'agent_memory_patterns',\n interruptsCollection: 'agent_memory_interrupts',\n feedbackCollection: 'agent_memory_feedback',\n checkpointsCollection: 'agent_memory_checkpoints',\n toolPreferencesCollection: 'agent_memory_tool_preferences',\n });\n }\n return memoryManager;\n}\n\n/**\n * Reset the MemoryManager (useful for testing)\n */\nexport function resetMemoryManager(): void {\n memoryManager = null;\n}\n"]}
1
+ {"version":3,"sources":["../../src/lib/db.ts","../../src/deepagent/memory.ts"],"names":[],"mappings":";;;;AAoFA,SAAS,MAAA,GAAwB;AAC/B,EAAA,IAAI,KAAA,CAAM,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF;AACA,EAAA,OAAO,MAAM,GAAA,EAAI;AACnB;AAKO,SAAS,YAAA,GAA0C;AACxD,EAAA,OAAO,MAAA,GAAS,SAAA,EAAU;AAC5B;AAgBO,IAAM,EAAA,GAAK,IAAI,KAAA,CAAM,EAAC,EAAgC;AAAA,EAC3D,GAAA,CAAI,OAAA,EAAS,IAAA,EAAM,QAAA,EAAU;AAC3B,IAAA,MAAM,YAAY,YAAA,EAAa;AAC/B,IAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,GAAA,CAAI,SAAA,EAAW,MAAM,QAAQ,CAAA;AACnD,IAAA,OAAO,OAAO,KAAA,KAAU,UAAA,GAAa,KAAA,CAAM,IAAA,CAAK,SAAS,CAAA,GAAI,KAAA;AAAA,EAC/D;AACF,CAAC,CAAA;;;AC9GD,IAAI,aAAA,GAAsC,IAAA;AAKnC,SAAS,gBAAA,GAAkC;AAChD,EAAA,IAAI,CAAC,aAAA,EAAe;AAClB,IAAA,aAAA,GAAgB,IAAI,aAAA,CAAc;AAAA,MAChC,EAAA;AAAA,MACA,eAAA,EAAiB,oBAAA;AAAA,MACjB,kBAAA,EAAoB,uBAAA;AAAA,MACpB,qBAAA,EAAuB,0BAAA;AAAA,MACvB,kBAAA,EAAoB,uBAAA;AAAA,MACpB,oBAAA,EAAsB,yBAAA;AAAA,MACtB,kBAAA,EAAoB,uBAAA;AAAA,MACpB,qBAAA,EAAuB,0BAAA;AAAA,MACvB,yBAAA,EAA2B;AAAA,KAC5B,CAAA;AAAA,EACH;AACA,EAAA,OAAO,aAAA;AACT;AAKO,SAAS,kBAAA,GAA2B;AACzC,EAAA,aAAA,GAAgB,IAAA;AAClB","file":"memory.js","sourcesContent":["/**\n * Database Accessors & Initialization\n *\n * This module provides:\n * - `initializeFirebase()` — convenience function to init Firebase from env vars\n * - `getFirestore()`, `getAuth()` — accessors for Firebase services\n * - `db` — lazy Firestore proxy (no eager initialization)\n *\n * The consuming application MUST call `initializeFirebase()` or\n * `admin.initializeApp()` before using any Firebase-dependent features.\n */\n\nimport admin from 'firebase-admin';\n\n/**\n * Initialize Firebase Admin SDK from environment variables.\n *\n * Reads: FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_PRIVATE_KEY,\n * FIREBASE_SERVICE_ACCOUNT_PATH, FIRESTORE_EMULATOR_HOST\n *\n * Safe to call multiple times — returns existing app if already initialized.\n */\nexport function initializeFirebase(): admin.app.App {\n // Already initialized — return existing app\n if (admin.apps.length > 0) {\n return admin.app();\n }\n\n const projectId = process.env.FIREBASE_PROJECT_ID;\n const emulatorHost = process.env.FIRESTORE_EMULATOR_HOST;\n\n // Emulator mode — no credentials needed\n if (emulatorHost) {\n const app = admin.initializeApp({\n projectId: projectId || 'demo-project',\n });\n console.log(`Firebase Admin initialized for emulator: ${emulatorHost}`);\n return app;\n }\n\n // Service account file\n const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;\n if (serviceAccountPath) {\n // Dynamic require for JSON service account file at runtime\n const serviceAccount = require(serviceAccountPath) as Record<string, unknown>;\n return admin.initializeApp({\n credential: admin.credential.cert(serviceAccount),\n projectId,\n });\n }\n\n // Inline credentials\n const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;\n const privateKey = process.env.FIREBASE_PRIVATE_KEY;\n if (projectId && clientEmail && privateKey) {\n return admin.initializeApp({\n credential: admin.credential.cert({\n projectId,\n clientEmail,\n privateKey: privateKey.replace(/\\\\n/g, '\\n'),\n }),\n projectId,\n });\n }\n\n // Application default credentials (Cloud Run, etc.)\n if (projectId) {\n return admin.initializeApp({\n credential: admin.credential.applicationDefault(),\n projectId,\n });\n }\n\n throw new Error(\n '@almadar/server: Cannot initialize Firebase — no credentials found. ' +\n 'Set FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY, ' +\n 'or FIREBASE_SERVICE_ACCOUNT_PATH, or FIRESTORE_EMULATOR_HOST.'\n );\n}\n\n/**\n * Get the initialized Firebase app.\n * Throws if Firebase Admin SDK has not been initialized.\n */\nfunction getApp(): admin.app.App {\n if (admin.apps.length === 0) {\n throw new Error(\n '@almadar/server: Firebase Admin SDK is not initialized. ' +\n 'Call initializeFirebase() or admin.initializeApp() before using @almadar/server.'\n );\n }\n return admin.app();\n}\n\n/**\n * Get Firestore instance from the pre-initialized Firebase app.\n */\nexport function getFirestore(): admin.firestore.Firestore {\n return getApp().firestore();\n}\n\n/**\n * Get Firebase Auth instance from the pre-initialized Firebase app.\n */\nexport function getAuth(): admin.auth.Auth {\n return getApp().auth();\n}\n\n// Re-export admin for convenience\nexport { admin };\n\n/**\n * Lazy Firestore proxy — resolves on first property access, not at import time.\n * This prevents the \"Firebase not initialized\" error during module loading.\n */\nexport const db = new Proxy({} as admin.firestore.Firestore, {\n get(_target, prop, receiver) {\n const firestore = getFirestore();\n const value = Reflect.get(firestore, prop, receiver);\n return typeof value === 'function' ? value.bind(firestore) : value;\n },\n});\n","/**\n * Memory Manager Singleton\n *\n * Provides Firestore-backed memory management for DeepAgent.\n *\n * @packageDocumentation\n */\n\nimport { MemoryManager } from '@almadar/agent';\nimport { db } from '../lib/db.js';\n\nlet memoryManager: MemoryManager | null = null;\n\n/**\n * Get or create the MemoryManager singleton\n */\nexport function getMemoryManager(): MemoryManager {\n if (!memoryManager) {\n memoryManager = new MemoryManager({\n db,\n usersCollection: 'agent_memory_users',\n projectsCollection: 'agent_memory_projects',\n generationsCollection: 'agent_memory_generations',\n patternsCollection: 'agent_memory_patterns',\n interruptsCollection: 'agent_memory_interrupts',\n feedbackCollection: 'agent_memory_feedback',\n checkpointsCollection: 'agent_memory_checkpoints',\n toolPreferencesCollection: 'agent_memory_tool_preferences',\n });\n }\n return memoryManager;\n}\n\n/**\n * Reset the MemoryManager (useful for testing)\n */\nexport function resetMemoryManager(): void {\n memoryManager = null;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/db.ts","../../src/deepagent/memory.ts","../../src/deepagent/session.ts"],"names":[],"mappings":";;;;AAoFA,SAAS,MAAA,GAAwB;AAC/B,EAAA,IAAI,KAAA,CAAM,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF;AACA,EAAA,OAAO,MAAM,GAAA,EAAI;AACnB;AAKO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AAAA,MAChC,gBAAA,EAAkB;AAAA,QAChB,SAAA,EAAW,IAAA;AAAA,QACX,kBAAA,EAAoB,EAAA;AAAA,QACpB,QAAA,EAAU;AAAA;AACZ,KACD,CAAA;AAAA,EACH;AACA,EAAA,OAAO,cAAA;AACT;AAKO,SAAS,mBAAA,GAA4B;AAC1C,EAAA,cAAA,GAAiB,IAAA;AACnB","file":"session.js","sourcesContent":["/**\n * Database Accessors & Initialization\n *\n * This module provides:\n * - `initializeFirebase()` — convenience function to init Firebase from env vars\n * - `getFirestore()`, `getAuth()` — accessors for Firebase services\n * - `db` — lazy Firestore proxy (no eager initialization)\n *\n * The consuming application MUST call `initializeFirebase()` or\n * `admin.initializeApp()` before using any Firebase-dependent features.\n */\n\nimport admin from 'firebase-admin';\n\n/**\n * Initialize Firebase Admin SDK from environment variables.\n *\n * Reads: FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_PRIVATE_KEY,\n * FIREBASE_SERVICE_ACCOUNT_PATH, FIRESTORE_EMULATOR_HOST\n *\n * Safe to call multiple times — returns existing app if already initialized.\n */\nexport function initializeFirebase(): admin.app.App {\n // Already initialized — return existing app\n if (admin.apps.length > 0) {\n return admin.app();\n }\n\n const projectId = process.env.FIREBASE_PROJECT_ID;\n const emulatorHost = process.env.FIRESTORE_EMULATOR_HOST;\n\n // Emulator mode — no credentials needed\n if (emulatorHost) {\n const app = admin.initializeApp({\n projectId: projectId || 'demo-project',\n });\n console.log(`Firebase Admin initialized for emulator: ${emulatorHost}`);\n return app;\n }\n\n // Service account file\n const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;\n if (serviceAccountPath) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const serviceAccount = require(serviceAccountPath);\n return admin.initializeApp({\n credential: admin.credential.cert(serviceAccount),\n projectId,\n });\n }\n\n // Inline credentials\n const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;\n const privateKey = process.env.FIREBASE_PRIVATE_KEY;\n if (projectId && clientEmail && privateKey) {\n return admin.initializeApp({\n credential: admin.credential.cert({\n projectId,\n clientEmail,\n privateKey: privateKey.replace(/\\\\n/g, '\\n'),\n }),\n projectId,\n });\n }\n\n // Application default credentials (Cloud Run, etc.)\n if (projectId) {\n return admin.initializeApp({\n credential: admin.credential.applicationDefault(),\n projectId,\n });\n }\n\n throw new Error(\n '@almadar/server: Cannot initialize Firebase — no credentials found. ' +\n 'Set FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY, ' +\n 'or FIREBASE_SERVICE_ACCOUNT_PATH, or FIRESTORE_EMULATOR_HOST.'\n );\n}\n\n/**\n * Get the initialized Firebase app.\n * Throws if Firebase Admin SDK has not been initialized.\n */\nfunction getApp(): admin.app.App {\n if (admin.apps.length === 0) {\n throw new Error(\n '@almadar/server: Firebase Admin SDK is not initialized. ' +\n 'Call initializeFirebase() or admin.initializeApp() before using @almadar/server.'\n );\n }\n return admin.app();\n}\n\n/**\n * Get Firestore instance from the pre-initialized Firebase app.\n */\nexport function getFirestore(): admin.firestore.Firestore {\n return getApp().firestore();\n}\n\n/**\n * Get Firebase Auth instance from the pre-initialized Firebase app.\n */\nexport function getAuth(): admin.auth.Auth {\n return getApp().auth();\n}\n\n// Re-export admin for convenience\nexport { admin };\n\n/**\n * Lazy Firestore proxy — resolves on first property access, not at import time.\n * This prevents the \"Firebase not initialized\" error during module loading.\n */\nexport const db = new Proxy({} as admin.firestore.Firestore, {\n get(_target, prop, receiver) {\n const firestore = getFirestore();\n const value = Reflect.get(firestore, prop, receiver);\n return typeof value === 'function' ? value.bind(firestore) : value;\n },\n});\n","/**\n * Memory Manager Singleton\n *\n * Provides Firestore-backed memory management for DeepAgent.\n *\n * @packageDocumentation\n */\n\nimport { MemoryManager } from '@almadar/agent';\nimport { db } from '../lib/db.js';\n\nlet memoryManager: MemoryManager | null = null;\n\n/**\n * Get or create the MemoryManager singleton\n */\nexport function getMemoryManager(): MemoryManager {\n if (!memoryManager) {\n memoryManager = new MemoryManager({\n db,\n usersCollection: 'agent_memory_users',\n projectsCollection: 'agent_memory_projects',\n generationsCollection: 'agent_memory_generations',\n patternsCollection: 'agent_memory_patterns',\n interruptsCollection: 'agent_memory_interrupts',\n feedbackCollection: 'agent_memory_feedback',\n checkpointsCollection: 'agent_memory_checkpoints',\n toolPreferencesCollection: 'agent_memory_tool_preferences',\n });\n }\n return memoryManager;\n}\n\n/**\n * Reset the MemoryManager (useful for testing)\n */\nexport function resetMemoryManager(): void {\n memoryManager = null;\n}\n","/**\n * Session Manager Singleton\n *\n * Provides Firestore-backed session management with full GAP features.\n *\n * @packageDocumentation\n */\n\nimport { SessionManager } from '@almadar/agent';\nimport { db } from '../lib/db.js';\nimport { getMemoryManager } from './memory.js';\nimport type { FirestoreDb } from '@almadar/agent';\n\nlet sessionManager: SessionManager | null = null;\n\n/**\n * Adapter to make Firebase Firestore compatible with @almadar/agent FirestoreDb interface\n */\nfunction createFirestoreAdapter(firestore: typeof db): FirestoreDb {\n return firestore as unknown as FirestoreDb;\n}\n\n/**\n * Get or create the SessionManager singleton\n */\nexport function getSessionManager(): SessionManager {\n if (!sessionManager) {\n sessionManager = new SessionManager({\n mode: 'firestore',\n firestoreDb: createFirestoreAdapter(db),\n memoryManager: getMemoryManager(), // Enable GAP-002D\n compactionConfig: {\n maxTokens: 150000,\n keepRecentMessages: 10,\n strategy: 'last',\n },\n });\n }\n return sessionManager;\n}\n\n/**\n * Reset the SessionManager (useful for testing)\n */\nexport function resetSessionManager(): void {\n sessionManager = null;\n}\n"]}
1
+ {"version":3,"sources":["../../src/lib/db.ts","../../src/deepagent/memory.ts","../../src/deepagent/session.ts"],"names":[],"mappings":";;;;AAoFA,SAAS,MAAA,GAAwB;AAC/B,EAAA,IAAI,KAAA,CAAM,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF;AACA,EAA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AAA,MACtC,eAAe,gBAAA,EAAiB;AAAA;AAAA,MAChC,gBAAA,EAAkB;AAAA,QAChB,SAAA,EAAW,IAAA;AAAA,QACX,kBAAA,EAAoB,EAAA;AAAA,QACpB,QAAA,EAAU;AAAA;AACZ,KACD,CAAA;AAAA,EACH;AACA,EAAA,OAAO,cAAA;AACT;AAKO,SAAS,mBAAA,GAA4B;AAC1C,EAAA,cAAA,GAAiB,IAAA;AACnB","file":"session.js","sourcesContent":["/**\n * Database Accessors & Initialization\n *\n * This module provides:\n * - `initializeFirebase()` — convenience function to init Firebase from env vars\n * - `getFirestore()`, `getAuth()` — accessors for Firebase services\n * - `db` — lazy Firestore proxy (no eager initialization)\n *\n * The consuming application MUST call `initializeFirebase()` or\n * `admin.initializeApp()` before using any Firebase-dependent features.\n */\n\nimport admin from 'firebase-admin';\n\n/**\n * Initialize Firebase Admin SDK from environment variables.\n *\n * Reads: FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_PRIVATE_KEY,\n * FIREBASE_SERVICE_ACCOUNT_PATH, FIRESTORE_EMULATOR_HOST\n *\n * Safe to call multiple times — returns existing app if already initialized.\n */\nexport function initializeFirebase(): admin.app.App {\n // Already initialized — return existing app\n if (admin.apps.length > 0) {\n return admin.app();\n }\n\n const projectId = process.env.FIREBASE_PROJECT_ID;\n const emulatorHost = process.env.FIRESTORE_EMULATOR_HOST;\n\n // Emulator mode — no credentials needed\n if (emulatorHost) {\n const app = admin.initializeApp({\n projectId: projectId || 'demo-project',\n });\n console.log(`Firebase Admin initialized for emulator: ${emulatorHost}`);\n return app;\n }\n\n // Service account file\n const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;\n if (serviceAccountPath) {\n // Dynamic require for JSON service account file at runtime\n const serviceAccount = require(serviceAccountPath) as Record<string, unknown>;\n return admin.initializeApp({\n credential: admin.credential.cert(serviceAccount),\n projectId,\n });\n }\n\n // Inline credentials\n const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;\n const privateKey = process.env.FIREBASE_PRIVATE_KEY;\n if (projectId && clientEmail && privateKey) {\n return admin.initializeApp({\n credential: admin.credential.cert({\n projectId,\n clientEmail,\n privateKey: privateKey.replace(/\\\\n/g, '\\n'),\n }),\n projectId,\n });\n }\n\n // Application default credentials (Cloud Run, etc.)\n if (projectId) {\n return admin.initializeApp({\n credential: admin.credential.applicationDefault(),\n projectId,\n });\n }\n\n throw new Error(\n '@almadar/server: Cannot initialize Firebase — no credentials found. ' +\n 'Set FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY, ' +\n 'or FIREBASE_SERVICE_ACCOUNT_PATH, or FIRESTORE_EMULATOR_HOST.'\n );\n}\n\n/**\n * Get the initialized Firebase app.\n * Throws if Firebase Admin SDK has not been initialized.\n */\nfunction getApp(): admin.app.App {\n if (admin.apps.length === 0) {\n throw new Error(\n '@almadar/server: Firebase Admin SDK is not initialized. ' +\n 'Call initializeFirebase() or admin.initializeApp() before using @almadar/server.'\n );\n }\n return admin.app();\n}\n\n/**\n * Get Firestore instance from the pre-initialized Firebase app.\n */\nexport function getFirestore(): admin.firestore.Firestore {\n return getApp().firestore();\n}\n\n/**\n * Get Firebase Auth instance from the pre-initialized Firebase app.\n */\nexport function getAuth(): admin.auth.Auth {\n return getApp().auth();\n}\n\n// Re-export admin for convenience\nexport { admin };\n\n/**\n * Lazy Firestore proxy — resolves on first property access, not at import time.\n * This prevents the \"Firebase not initialized\" error during module loading.\n */\nexport const db = new Proxy({} as admin.firestore.Firestore, {\n get(_target, prop, receiver) {\n const firestore = getFirestore();\n const value = Reflect.get(firestore, prop, receiver);\n return typeof value === 'function' ? value.bind(firestore) : value;\n },\n});\n","/**\n * Memory Manager Singleton\n *\n * Provides Firestore-backed memory management for DeepAgent.\n *\n * @packageDocumentation\n */\n\nimport { MemoryManager } from '@almadar/agent';\nimport { db } from '../lib/db.js';\n\nlet memoryManager: MemoryManager | null = null;\n\n/**\n * Get or create the MemoryManager singleton\n */\nexport function getMemoryManager(): MemoryManager {\n if (!memoryManager) {\n memoryManager = new MemoryManager({\n db,\n usersCollection: 'agent_memory_users',\n projectsCollection: 'agent_memory_projects',\n generationsCollection: 'agent_memory_generations',\n patternsCollection: 'agent_memory_patterns',\n interruptsCollection: 'agent_memory_interrupts',\n feedbackCollection: 'agent_memory_feedback',\n checkpointsCollection: 'agent_memory_checkpoints',\n toolPreferencesCollection: 'agent_memory_tool_preferences',\n });\n }\n return memoryManager;\n}\n\n/**\n * Reset the MemoryManager (useful for testing)\n */\nexport function resetMemoryManager(): void {\n memoryManager = null;\n}\n","/**\n * Session Manager Singleton\n *\n * Provides Firestore-backed session management with full GAP features.\n *\n * @packageDocumentation\n */\n\nimport { SessionManager } from '@almadar/agent';\nimport { db } from '../lib/db.js';\nimport { getMemoryManager } from './memory.js';\nimport type { FirestoreDb } from '@almadar/agent';\n\nlet sessionManager: SessionManager | null = null;\n\n/**\n * Adapter to make Firebase Firestore compatible with @almadar/agent FirestoreDb interface\n */\nfunction createFirestoreAdapter(firestore: typeof db): FirestoreDb {\n return firestore as unknown as FirestoreDb;\n}\n\n/**\n * Get or create the SessionManager singleton\n */\nexport function getSessionManager(): SessionManager {\n if (!sessionManager) {\n sessionManager = new SessionManager({\n mode: 'firestore',\n firestoreDb: createFirestoreAdapter(db),\n memoryManager: getMemoryManager(), // Enable GAP-002D\n compactionConfig: {\n maxTokens: 150000,\n keepRecentMessages: 10,\n strategy: 'last',\n },\n });\n }\n return sessionManager;\n}\n\n/**\n * Reset the SessionManager (useful for testing)\n */\nexport function resetSessionManager(): void {\n sessionManager = null;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/lib/db.ts","../../src/deepagent/memory.ts","../../src/deepagent/session.ts","../../src/deepagent/skill-agent.ts"],"names":["memoryManager"],"mappings":";;;;AAoFA,SAAS,MAAA,GAAwB;AAC/B,EAAA,IAAI,KAAA,CAAM,IAAA,CAAK,MAAA,KAAW,CA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AAA,CAAQ,MAAA;AAAA;AAAA,MAChB,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,aAAa,mBAAA,CAAoB;AAAA;AAAA,KAClC,CAAA;AAGD,IAAA,IAAI,OAAO,QAAA,EAAU;AACnB,MAAA,SAAA,CAAU,sBAAA,CAAuB,MAAA,CAAO,QAAA,EAAU,OAAA,CAAQ,MAAM,CAAA;AAAA,IAClE;AAGA,IAAA,aAAA,CAAc,WAAA,CAAY;AAAA,MACxB,IAAA,EAAM,eAAA;AAAA,MACN,WAAW,MAAA,CAAO,QAAA;AAAA,MAClB,QAAQ,OAAA,CAAQ,MAAA;AAAA,MAChB,OAAA,EAAS,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA;AAAM,KACjC,CAAA;AAED,IAAA,OAAO,MAAA;AAAA,EACT,SAAS,KAAA,EAAO;AACd,IAAA,aAAA,CAAc,WAAA,CAAY,OAAA,CAAQ,QAAA,IAAY,KAAA,EAAO,KAAc,CAAA;AACnE,IAAA,MAAM,KAAA;AAAA,EACR;AACF","file":"skill-agent.js","sourcesContent":["/**\n * Database Accessors & Initialization\n *\n * This module provides:\n * - `initializeFirebase()` — convenience function to init Firebase from env vars\n * - `getFirestore()`, `getAuth()` — accessors for Firebase services\n * - `db` — lazy Firestore proxy (no eager initialization)\n *\n * The consuming application MUST call `initializeFirebase()` or\n * `admin.initializeApp()` before using any Firebase-dependent features.\n */\n\nimport admin from 'firebase-admin';\n\n/**\n * Initialize Firebase Admin SDK from environment variables.\n *\n * Reads: FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_PRIVATE_KEY,\n * FIREBASE_SERVICE_ACCOUNT_PATH, FIRESTORE_EMULATOR_HOST\n *\n * Safe to call multiple times — returns existing app if already initialized.\n */\nexport function initializeFirebase(): admin.app.App {\n // Already initialized — return existing app\n if (admin.apps.length > 0) {\n return admin.app();\n }\n\n const projectId = process.env.FIREBASE_PROJECT_ID;\n const emulatorHost = process.env.FIRESTORE_EMULATOR_HOST;\n\n // Emulator mode — no credentials needed\n if (emulatorHost) {\n const app = admin.initializeApp({\n projectId: projectId || 'demo-project',\n });\n console.log(`Firebase Admin initialized for emulator: ${emulatorHost}`);\n return app;\n }\n\n // Service account file\n const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;\n if (serviceAccountPath) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const serviceAccount = require(serviceAccountPath);\n return admin.initializeApp({\n credential: admin.credential.cert(serviceAccount),\n projectId,\n });\n }\n\n // Inline credentials\n const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;\n const privateKey = process.env.FIREBASE_PRIVATE_KEY;\n if (projectId && clientEmail && privateKey) {\n return admin.initializeApp({\n credential: admin.credential.cert({\n projectId,\n clientEmail,\n privateKey: privateKey.replace(/\\\\n/g, '\\n'),\n }),\n projectId,\n });\n }\n\n // Application default credentials (Cloud Run, etc.)\n if (projectId) {\n return admin.initializeApp({\n credential: admin.credential.applicationDefault(),\n projectId,\n });\n }\n\n throw new Error(\n '@almadar/server: Cannot initialize Firebase — no credentials found. ' +\n 'Set FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY, ' +\n 'or FIREBASE_SERVICE_ACCOUNT_PATH, or FIRESTORE_EMULATOR_HOST.'\n );\n}\n\n/**\n * Get the initialized Firebase app.\n * Throws if Firebase Admin SDK has not been initialized.\n */\nfunction getApp(): admin.app.App {\n if (admin.apps.length === 0) {\n throw new Error(\n '@almadar/server: Firebase Admin SDK is not initialized. ' +\n 'Call initializeFirebase() or admin.initializeApp() before using @almadar/server.'\n );\n }\n return admin.app();\n}\n\n/**\n * Get Firestore instance from the pre-initialized Firebase app.\n */\nexport function getFirestore(): admin.firestore.Firestore {\n return getApp().firestore();\n}\n\n/**\n * Get Firebase Auth instance from the pre-initialized Firebase app.\n */\nexport function getAuth(): admin.auth.Auth {\n return getApp().auth();\n}\n\n// Re-export admin for convenience\nexport { admin };\n\n/**\n * Lazy Firestore proxy — resolves on first property access, not at import time.\n * This prevents the \"Firebase not initialized\" error during module loading.\n */\nexport const db = new Proxy({} as admin.firestore.Firestore, {\n get(_target, prop, receiver) {\n const firestore = getFirestore();\n const value = Reflect.get(firestore, prop, receiver);\n return typeof value === 'function' ? value.bind(firestore) : value;\n },\n});\n","/**\n * Memory Manager Singleton\n *\n * Provides Firestore-backed memory management for DeepAgent.\n *\n * @packageDocumentation\n */\n\nimport { MemoryManager } from '@almadar/agent';\nimport { db } from '../lib/db.js';\n\nlet memoryManager: MemoryManager | null = null;\n\n/**\n * Get or create the MemoryManager singleton\n */\nexport function getMemoryManager(): MemoryManager {\n if (!memoryManager) {\n memoryManager = new MemoryManager({\n db,\n usersCollection: 'agent_memory_users',\n projectsCollection: 'agent_memory_projects',\n generationsCollection: 'agent_memory_generations',\n patternsCollection: 'agent_memory_patterns',\n interruptsCollection: 'agent_memory_interrupts',\n feedbackCollection: 'agent_memory_feedback',\n checkpointsCollection: 'agent_memory_checkpoints',\n toolPreferencesCollection: 'agent_memory_tool_preferences',\n });\n }\n return memoryManager;\n}\n\n/**\n * Reset the MemoryManager (useful for testing)\n */\nexport function resetMemoryManager(): void {\n memoryManager = null;\n}\n","/**\n * Session Manager Singleton\n *\n * Provides Firestore-backed session management with full GAP features.\n *\n * @packageDocumentation\n */\n\nimport { SessionManager } from '@almadar/agent';\nimport { db } from '../lib/db.js';\nimport { getMemoryManager } from './memory.js';\nimport type { FirestoreDb } from '@almadar/agent';\n\nlet sessionManager: SessionManager | null = null;\n\n/**\n * Adapter to make Firebase Firestore compatible with @almadar/agent FirestoreDb interface\n */\nfunction createFirestoreAdapter(firestore: typeof db): FirestoreDb {\n return firestore as unknown as FirestoreDb;\n}\n\n/**\n * Get or create the SessionManager singleton\n */\nexport function getSessionManager(): SessionManager {\n if (!sessionManager) {\n sessionManager = new SessionManager({\n mode: 'firestore',\n firestoreDb: createFirestoreAdapter(db),\n memoryManager: getMemoryManager(), // Enable GAP-002D\n compactionConfig: {\n maxTokens: 150000,\n keepRecentMessages: 10,\n strategy: 'last',\n },\n });\n }\n return sessionManager;\n}\n\n/**\n * Reset the SessionManager (useful for testing)\n */\nexport function resetSessionManager(): void {\n sessionManager = null;\n}\n","/**\n * Skill Agent Factory\n *\n * Creates DeepAgent instances with full GAP feature integration.\n *\n * @packageDocumentation\n */\n\nimport {\n createSkillAgent,\n getObservabilityCollector,\n getMultiUserManager,\n createWorkflowToolWrapper,\n type SkillAgentOptions,\n type SkillAgentResult,\n} from '@almadar/agent';\nimport { getMemoryManager } from './memory.js';\nimport { getSessionManager } from './session.js';\n\ninterface ServerSkillAgentOptions extends SkillAgentOptions {\n /** User ID from Firebase Auth */\n userId: string;\n /** App/Project ID for context */\n appId?: string;\n}\n\n/**\n * Create a skill agent with full server-side GAP integration\n */\nexport async function createServerSkillAgent(\n options: ServerSkillAgentOptions,\n): Promise<SkillAgentResult> {\n const memoryManager = getMemoryManager();\n const sessionManager = getSessionManager();\n const observability = getObservabilityCollector();\n const multiUser = getMultiUserManager();\n\n // Check access if resuming existing session\n if (options.threadId) {\n const access = multiUser.canAccessSession(options.threadId, {\n userId: options.userId,\n roles: ['user'],\n });\n if (!access.allowed) {\n throw new Error(`Access denied: ${access.reason}`);\n }\n }\n\n // Start observability\n observability.startSession(options.threadId ?? 'new', options.userId);\n\n // Create workflow tool wrapper for retry/telemetry (always enabled)\n const workflowToolWrapper = createWorkflowToolWrapper({\n maxRetries: 2,\n enableTelemetry: true,\n timeoutMs: 300000, // 5 minutes\n });\n\n try {\n const result = await createSkillAgent({\n ...options,\n memoryManager, // GAP-001: Enable memory\n userId: options.userId, // GAP-002D: Session → Memory sync\n appId: options.appId,\n toolWrapper: workflowToolWrapper.wrap, // Always use workflow wrapper for reliability\n });\n\n // Assign ownership for new sessions\n if (result.threadId) {\n multiUser.assignSessionOwnership(result.threadId, options.userId);\n }\n\n // Record successful creation\n observability.recordEvent({\n type: 'session_start',\n sessionId: result.threadId,\n userId: options.userId,\n payload: { skill: options.skill },\n });\n\n return result;\n } catch (error) {\n observability.recordError(options.threadId ?? 'new', error as Error);\n throw error;\n }\n}\n\n// Re-export for convenience\nexport { getMemoryManager, getSessionManager };\n"]}
1
+ {"version":3,"sources":["../../src/lib/db.ts","../../src/deepagent/memory.ts","../../src/deepagent/session.ts","../../src/deepagent/skill-agent.ts"],"names":["memoryManager"],"mappings":";;;;AAoFA,SAAS,MAAA,GAAwB;AAC/B,EAAA,IAAI,KAAA,CAAM,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG;AAC3B,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF;AACA,EAAA,OAAO,MAAM,GAAA,EAAI;AACnB;AAKO,SAAS,YAAA,GAA0C;AACxD,EAAA,OAAO,MAAA,GAAS,SAAA,EAAU;AAC5B;AAgBO,IAAM,EAAA,GAAK,IAAI,KAAA,CAAM,EAAC,EAAgC;AAAA,EAC3D,GAAA,CAAI,OAAA,EAAS,IAAA,EAAM,QAAA,EAAU;AAC3B,IAAA,MAAM,YAAY,YAAA,EAAa;AAC/B,IAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,GAAA,CAAI,SAAA,EAAW,MAAM,QAAQ,CAAA;AACnD,IAAA,OAAO,OAAO,KAAA,KAAU,UAAA,GAAa,KAAA,CAAM,IAAA,CAAK,SAAS,CAAA,GAAI,KAAA;AAAA,EAC/D;AACF,CAAC,CAAA;;;AC9GD,IAAI,aAAA,GAAsC,IAAA;AAKnC,SAAS,gBAAA,GAAkC;AAChD,EAAA,IAAI,CAAC,aAAA,EAAe;AAClB,IAAA,aAAA,GAAgB,IAAI,aAAA,CAAc;AAAA,MAChC,EAAA;AAAA,MACA,eAAA,EAAiB,oBAAA;AAAA,MACjB,kBAAA,EAAoB,uBAAA;AAAA,MACpB,qBAAA,EAAuB,0BAAA;AAAA,MACvB,kBAAA,EAAoB,uBAAA;AAAA,MACpB,oBAAA,EAAsB,yBAAA;AAAA,M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A,IAAY,KAAA,EAAO,QAAQ,MAAM,CAAA;AAGpE,EAAA,MAAM,sBAAsB,yBAAA,CAA0B;AAAA,IACpD,UAAA,EAAY,CAAA;AAAA,IACZ,eAAA,EAAiB,IAAA;AAAA,IACjB,SAAA,EAAW;AAAA;AAAA,GACZ,CAAA;AAED,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,MAAM,gBAAA,CAAiB;AAAA,MACpC,GAAG,OAAA;AAAA,MACH,aAAA,EAAAA,cAAAA;AAAA;AAAA,MACA,QAAQ,OAAA,CAAQ,MAAA;AAAA;AAAA,MAChB,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,aAAa,mBAAA,CAAoB;AAAA;AAAA,KAClC,CAAA;AAGD,IAAA,IAAI,OAAO,QAAA,EAAU;AACnB,MAAA,SAAA,CAAU,sBAAA,CAAuB,MAAA,CAAO,QAAA,EAAU,OAAA,CAAQ,MAAM,CAAA;AAAA,IAClE;AAGA,IAAA,aAAA,CAAc,WAAA,CAAY;AAAA,MACxB,IAAA,EAAM,eAAA;AAAA,MACN,WAAW,MAAA,CAAO,QAAA;AAAA,MAClB,QAAQ,OAAA,CAAQ,MAAA;AAAA,MAChB,OAAA,EAAS,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA;AAAM,KACjC,CAAA;AAED,IAAA,OAAO,MAAA;AAAA,EACT,SAAS,KAAA,EAAO;AACd,IAAA,aAAA,CAAc,WAAA,CAAY,OAAA,CAAQ,QAAA,IAAY,KAAA,EAAO,KAAc,CAAA;AACnE,IAAA,MAAM,KAAA;AAAA,EACR;AACF","file":"skill-agent.js","sourcesContent":["/**\n * Database Accessors & Initialization\n *\n * This module provides:\n * - `initializeFirebase()` — convenience function to init Firebase from env vars\n * - `getFirestore()`, `getAuth()` — accessors for Firebase services\n * - `db` — lazy Firestore proxy (no eager initialization)\n *\n * The consuming application MUST call `initializeFirebase()` or\n * `admin.initializeApp()` before using any Firebase-dependent features.\n */\n\nimport admin from 'firebase-admin';\n\n/**\n * Initialize Firebase Admin SDK from environment variables.\n *\n * Reads: FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, FIREBASE_PRIVATE_KEY,\n * FIREBASE_SERVICE_ACCOUNT_PATH, FIRESTORE_EMULATOR_HOST\n *\n * Safe to call multiple times — returns existing app if already initialized.\n */\nexport function initializeFirebase(): admin.app.App {\n // Already initialized — return existing app\n if (admin.apps.length > 0) {\n return admin.app();\n }\n\n const projectId = process.env.FIREBASE_PROJECT_ID;\n const emulatorHost = process.env.FIRESTORE_EMULATOR_HOST;\n\n // Emulator mode — no credentials needed\n if (emulatorHost) {\n const app = admin.initializeApp({\n projectId: projectId || 'demo-project',\n });\n console.log(`Firebase Admin initialized for emulator: ${emulatorHost}`);\n return app;\n }\n\n // Service account file\n const serviceAccountPath = process.env.FIREBASE_SERVICE_ACCOUNT_PATH;\n if (serviceAccountPath) {\n // Dynamic require for JSON service account file at runtime\n const serviceAccount = require(serviceAccountPath) as Record<string, unknown>;\n return admin.initializeApp({\n credential: admin.credential.cert(serviceAccount),\n projectId,\n });\n }\n\n // Inline credentials\n const clientEmail = process.env.FIREBASE_CLIENT_EMAIL;\n const privateKey = process.env.FIREBASE_PRIVATE_KEY;\n if (projectId && clientEmail && privateKey) {\n return admin.initializeApp({\n credential: admin.credential.cert({\n projectId,\n clientEmail,\n privateKey: privateKey.replace(/\\\\n/g, '\\n'),\n }),\n projectId,\n });\n }\n\n // Application default credentials (Cloud Run, etc.)\n if (projectId) {\n return admin.initializeApp({\n credential: admin.credential.applicationDefault(),\n projectId,\n });\n }\n\n throw new Error(\n '@almadar/server: Cannot initialize Firebase — no credentials found. ' +\n 'Set FIREBASE_PROJECT_ID + FIREBASE_CLIENT_EMAIL + FIREBASE_PRIVATE_KEY, ' +\n 'or FIREBASE_SERVICE_ACCOUNT_PATH, or FIRESTORE_EMULATOR_HOST.'\n );\n}\n\n/**\n * Get the initialized Firebase app.\n * Throws if Firebase Admin SDK has not been initialized.\n */\nfunction getApp(): admin.app.App {\n if (admin.apps.length === 0) {\n throw new Error(\n '@almadar/server: Firebase Admin SDK is not initialized. ' +\n 'Call initializeFirebase() or admin.initializeApp() before using @almadar/server.'\n );\n }\n return admin.app();\n}\n\n/**\n * Get Firestore instance from the pre-initialized Firebase app.\n */\nexport function getFirestore(): admin.firestore.Firestore {\n return getApp().firestore();\n}\n\n/**\n * Get Firebase Auth instance from the pre-initialized Firebase app.\n */\nexport function getAuth(): admin.auth.Auth {\n return getApp().auth();\n}\n\n// Re-export admin for convenience\nexport { admin };\n\n/**\n * Lazy Firestore proxy — resolves on first property access, not at import time.\n * This prevents the \"Firebase not initialized\" error during module loading.\n */\nexport const db = new Proxy({} as admin.firestore.Firestore, {\n get(_target, prop, receiver) {\n const firestore = getFirestore();\n const value = Reflect.get(firestore, prop, receiver);\n return typeof value === 'function' ? value.bind(firestore) : value;\n },\n});\n","/**\n * Memory Manager Singleton\n *\n * Provides Firestore-backed memory management for DeepAgent.\n *\n * @packageDocumentation\n */\n\nimport { MemoryManager } from '@almadar/agent';\nimport { db } from '../lib/db.js';\n\nlet memoryManager: MemoryManager | null = null;\n\n/**\n * Get or create the MemoryManager singleton\n */\nexport function getMemoryManager(): MemoryManager {\n if (!memoryManager) {\n memoryManager = new MemoryManager({\n db,\n usersCollection: 'agent_memory_users',\n projectsCollection: 'agent_memory_projects',\n generationsCollection: 'agent_memory_generations',\n patternsCollection: 'agent_memory_patterns',\n interruptsCollection: 'agent_memory_interrupts',\n feedbackCollection: 'agent_memory_feedback',\n checkpointsCollection: 'agent_memory_checkpoints',\n toolPreferencesCollection: 'agent_memory_tool_preferences',\n });\n }\n return memoryManager;\n}\n\n/**\n * Reset the MemoryManager (useful for testing)\n */\nexport function resetMemoryManager(): void {\n memoryManager = null;\n}\n","/**\n * Session Manager Singleton\n *\n * Provides Firestore-backed session management with full GAP features.\n *\n * @packageDocumentation\n */\n\nimport { SessionManager } from '@almadar/agent';\nimport { db } from '../lib/db.js';\nimport { getMemoryManager } from './memory.js';\nimport type { FirestoreDb } from '@almadar/agent';\n\nlet sessionManager: SessionManager | null = null;\n\n/**\n * Adapter to make Firebase Firestore compatible with @almadar/agent FirestoreDb interface\n */\nfunction createFirestoreAdapter(firestore: typeof db): FirestoreDb {\n return firestore as unknown as FirestoreDb;\n}\n\n/**\n * Get or create the SessionManager singleton\n */\nexport function getSessionManager(): SessionManager {\n if (!sessionManager) {\n sessionManager = new SessionManager({\n mode: 'firestore',\n firestoreDb: createFirestoreAdapter(db),\n memoryManager: getMemoryManager(), // Enable GAP-002D\n compactionConfig: {\n maxTokens: 150000,\n keepRecentMessages: 10,\n strategy: 'last',\n },\n });\n }\n return sessionManager;\n}\n\n/**\n * Reset the SessionManager (useful for testing)\n */\nexport function resetSessionManager(): void {\n sessionManager = null;\n}\n","/**\n * Skill Agent Factory\n *\n * Creates DeepAgent instances with full GAP feature integration.\n *\n * @packageDocumentation\n */\n\nimport {\n createSkillAgent,\n getObservabilityCollector,\n getMultiUserManager,\n createWorkflowToolWrapper,\n type SkillAgentOptions,\n type SkillAgentResult,\n} from '@almadar/agent';\nimport { getMemoryManager } from './memory.js';\nimport { getSessionManager } from './session.js';\n\ninterface ServerSkillAgentOptions extends SkillAgentOptions {\n /** User ID from Firebase Auth */\n userId: string;\n /** App/Project ID for context */\n appId?: string;\n}\n\n/**\n * Create a skill agent with full server-side GAP integration\n */\nexport async function createServerSkillAgent(\n options: ServerSkillAgentOptions,\n): Promise<SkillAgentResult> {\n const memoryManager = getMemoryManager();\n const sessionManager = getSessionManager();\n const observability = getObservabilityCollector();\n const multiUser = getMultiUserManager();\n\n // Check access if resuming existing session\n if (options.threadId) {\n const access = multiUser.canAccessSession(options.threadId, {\n userId: options.userId,\n roles: ['user'],\n });\n if (!access.allowed) {\n throw new Error(`Access denied: ${access.reason}`);\n }\n }\n\n // Start observability\n observability.startSession(options.threadId ?? 'new', options.userId);\n\n // Create workflow tool wrapper for retry/telemetry (always enabled)\n const workflowToolWrapper = createWorkflowToolWrapper({\n maxRetries: 2,\n enableTelemetry: true,\n timeoutMs: 300000, // 5 minutes\n });\n\n try {\n const result = await createSkillAgent({\n ...options,\n memoryManager, // GAP-001: Enable memory\n userId: options.userId, // GAP-002D: Session → Memory sync\n appId: options.appId,\n toolWrapper: workflowToolWrapper.wrap, // Always use workflow wrapper for reliability\n });\n\n // Assign ownership for new sessions\n if (result.threadId) {\n multiUser.assignSessionOwnership(result.threadId, options.userId);\n }\n\n // Record successful creation\n observability.recordEvent({\n type: 'session_start',\n sessionId: result.threadId,\n userId: options.userId,\n payload: { skill: options.skill },\n });\n\n return result;\n } catch (error) {\n observability.recordError(options.threadId ?? 'new', error as Error);\n throw error;\n }\n}\n\n// Re-export for convenience\nexport { getMemoryManager, getSessionManager };\n"]}
package/dist/index.d.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  */
13
13
  export { env } from './lib/env.js';
14
14
  export { logger } from './lib/logger.js';
15
- export { EventBus, serverEventBus, emitEntityEvent, type EventLogEntry } from './lib/eventBus.js';
15
+ export { EventBus, getServerEventBus, resetServerEventBus, emitEntityEvent, type EventLogEntry } from './lib/eventBus.js';
16
16
  export { DistributedEventBus, InMemoryTransport, RedisTransport, type IEventBusTransport, type TransportMessage, type TransportReceiver, type RedisTransportOptions, } from './lib/eventBusTransport.js';
17
17
  export { EventPersistence, InMemoryEventStore, type PersistedEvent, type EventQuery, type EventPersistenceOptions, type IEventStore, } from './lib/eventPersistence.js';
18
18
  export { debugEventsRouter } from './lib/debugRouter.js';
@@ -21,8 +21,8 @@ export { setupEventBroadcast, getWebSocketServer, closeWebSocketServer, getConne
21
21
  export { errorHandler, notFoundHandler, asyncHandler, AppError, NotFoundError, ValidationError, UnauthorizedError, ForbiddenError, ConflictError, } from './middleware/errorHandler.js';
22
22
  export { validateBody, validateQuery, validateParams } from './middleware/validation.js';
23
23
  export { authenticateFirebase } from './middleware/authenticateFirebase.js';
24
- export { mockDataService, MockDataService, type FieldSchema, type EntitySchema, } from './services/MockDataService.js';
25
- export { dataService, seedMockData, type DataService, type EntitySeedConfig, type PaginationOptions, type PaginatedResult, } from './services/DataService.js';
24
+ export { MockDataService, getMockDataService, resetMockDataService, type FieldSchema, type EntitySchema, } from './services/MockDataService.js';
25
+ export { getDataService, resetDataService, seedMockData, type DataService, type EntitySeedConfig, type PaginationOptions, type PaginatedResult, } from './services/DataService.js';
26
26
  export { toFirestoreFormat, fromFirestoreFormat, SchemaStore, SnapshotStore, ChangeSetStore, ValidationStore, SchemaProtectionService, } from './stores/index.js';
27
27
  export { parseQueryFilters, applyFiltersToQuery, extractPaginationParams, type ParsedFilter, type FirestoreWhereFilterOp, type PaginationParams, } from './utils/queryFilters.js';
28
28
  export { getMemoryManager, resetMemoryManager, } from './deepagent/memory.js';
@@ -31,5 +31,6 @@ export { createServerSkillAgent, getMemoryManager as getAgentMemoryManager, getS
31
31
  export { multiUserMiddleware, verifyFirebaseAuth, } from './middleware/multi-user.js';
32
32
  export { setupStateSyncWebSocket } from './websocket/state-sync.js';
33
33
  export { ServiceDiscovery, InMemoryServiceRegistry, type ServiceRegistration, type ServiceRegistryOptions, type IServiceRegistry, } from './lib/serviceDiscovery.js';
34
+ export type { DataServiceActions, DataServiceContract, EventBusActions, EventBusServiceContract, ServiceDiscoveryActions, ServiceDiscoveryContract, ServerServiceContracts, } from './contracts.js';
34
35
  export { default as observabilityRouter } from './routes/observability.js';
35
36
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AACnC,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,eAAe,EAAE,KAAK,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClG,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB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AI,sBAAsB,GAC5C,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EACL,mBAAmB,EACnB,kBAAkB,GACnB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAGpE,OAAO,EACL,gBAAgB,EAChB,uBAAuB,EACvB,KAAK,mBAAmB,EACxB,KAAK,sBAAsB,EAC3B,KAAK,gBAAgB,GACtB,MAAM,2BAA2B,CAAC;AAGnC,YAAY,EACV,kBAAkB,EAClB,mBAAmB,EACnB,eAAe,EACf,uBAAuB,EACvB,uBAAuB,EACvB,wBAAwB,EACxB,sBAAsB,GACvB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,MAAM,2BAA2B,CAAC"}
package/dist/index.js CHANGED
@@ -169,12 +169,22 @@ var EventBus = class {
169
169
  this.eventLog.length = 0;
170
170
  }
171
171
  };
172
- var serverEventBus = new EventBus({
173
- debug: process.env.NODE_ENV === "development"
174
- });
172
+ var _serverEventBus = null;
173
+ function getServerEventBus() {
174
+ if (!_serverEventBus) {
175
+ _serverEventBus = new EventBus({
176
+ debug: process.env.NODE_ENV === "development"
177
+ });
178
+ }
179
+ return _serverEventBus;
180
+ }
181
+ function resetServerEventBus() {
182
+ _serverEventBus?.clear();
183
+ _serverEventBus = null;
184
+ }
175
185
  function emitEntityEvent(entityType, action, payload) {
176
186
  const eventType = `${entityType.toUpperCase()}_${action}`;
177
- serverEventBus.emit(eventType, payload, { orbital: entityType });
187
+ getServerEventBus().emit(eventType, payload, { orbital: entityType });
178
188
  }
179
189
 
180
190
  // src/lib/eventBusTransport.ts
@@ -449,15 +459,15 @@ function debugEventsRouter() {
449
459
  }
450
460
  router2.get("/event-log", (_req, res) => {
451
461
  const limit = parseInt(String(_req.query.limit) || "50", 10);
452
- const events = serverEventBus.getRecentEvents(limit);
462
+ const events = getServerEventBus().getRecentEvents(limit);
453
463
  res.json({ count: events.length, events });
454
464
  });
455
465
  router2.delete("/event-log", (_req, res) => {
456
- serverEventBus.clearEventLog();
466
+ getServerEventBus().clearEventLog();
457
467
  res.json({ cleared: true });
458
468
  });
459
469
  router2.get("/listeners", (_req, res) => {
460
- const counts = serverEventBus.getListenerCounts();
470
+ const counts = getServerEventBus().getListenerCounts();
461
471
  const total = Object.values(counts).reduce((sum, n) => sum + n, 0);
462
472
  res.json({ total, events: counts });
463
473
  });
@@ -550,7 +560,7 @@ function setupEventBroadcast(server, path = "/ws/events") {
550
560
  const message = JSON.parse(data.toString());
551
561
  logger.debug(`[WebSocket] Received from ${clientId}:`, message);
552
562
  if (message.type && message.payload) {
553
- serverEventBus.emit(message.type, message.payload, {
563
+ getServerEventBus().emit(message.type, message.payload, {
554
564
  orbital: "client",
555
565
  entity: clientId
556
566
  });
@@ -566,7 +576,7 @@ function setupEventBroadcast(server, path = "/ws/events") {
566
576
  logger.error(`[WebSocket] Client error:`, error);
567
577
  });
568
578
  });
569
- serverEventBus.on("*", (event) => {
579
+ getServerEventBus().on("*", (event) => {
570
580
  if (!wss) return;
571
581
  const typedEvent = event;
572
582
  const message = JSON.stringify({
@@ -1037,7 +1047,17 @@ var MockDataService = class {
1037
1047
  return store.size;
1038
1048
  }
1039
1049
  };
1040
- var mockDataService = new MockDataService();
1050
+ var _mockDataService = null;
1051
+ function getMockDataService() {
1052
+ if (!_mockDataService) {
1053
+ _mockDataService = new MockDataService();
1054
+ }
1055
+ return _mockDataService;
1056
+ }
1057
+ function resetMockDataService() {
1058
+ _mockDataService?.clearAll();
1059
+ _mockDataService = null;
1060
+ }
1041
1061
 
1042
1062
  // src/utils/queryFilters.ts
1043
1063
  var OPERATOR_MAP = {
@@ -1174,7 +1194,7 @@ function applyFilterCondition(value, operator, filterValue) {
1174
1194
  }
1175
1195
  var MockDataServiceAdapter = class {
1176
1196
  async list(collection) {
1177
- return mockDataService.list(collection);
1197
+ return getMockDataService().list(collection);
1178
1198
  }
1179
1199
  async listPaginated(collection, options = {}) {
1180
1200
  const {
@@ -1186,7 +1206,7 @@ var MockDataServiceAdapter = class {
1186
1206
  sortOrder = "asc",
1187
1207
  filters
1188
1208
  } = options;
1189
- let items = mockDataService.list(collection);
1209
+ let items = getMockDataService().list(collection);
1190
1210
  if (filters && filters.length > 0) {
1191
1211
  items = items.filter((item) => {
1192
1212
  const record = item;
@@ -1226,16 +1246,48 @@ var MockDataServiceAdapter = class {
1226
1246
  return { data, total, page, pageSize, totalPages };
1227
1247
  }
1228
1248
  async getById(collection, id) {
1229
- return mockDataService.getById(collection, id);
1249
+ return getMockDataService().getById(collection, id);
1230
1250
  }
1231
1251
  async create(collection, data) {
1232
- return mockDataService.create(collection, data);
1252
+ return getMockDataService().create(collection, data);
1233
1253
  }
1234
1254
  async update(collection, id, data) {
1235
- return mockDataService.update(collection, id, data);
1255
+ return getMockDataService().update(collection, id, data);
1236
1256
  }
1237
1257
  async delete(collection, id) {
1238
- return mockDataService.delete(collection, id);
1258
+ return getMockDataService().delete(collection, id);
1259
+ }
1260
+ async query(collection, filters) {
1261
+ let items = getMockDataService().list(collection);
1262
+ for (const filter of filters) {
1263
+ items = items.filter((item) => {
1264
+ const value = item[filter.field];
1265
+ return applyFilterCondition(value, filter.op, filter.value);
1266
+ });
1267
+ }
1268
+ return items;
1269
+ }
1270
+ getStore(collection) {
1271
+ const adapter = this;
1272
+ return {
1273
+ async getById(id) {
1274
+ return adapter.getById(collection, id);
1275
+ },
1276
+ async create(data) {
1277
+ return adapter.create(collection, data);
1278
+ },
1279
+ async update(id, data) {
1280
+ const result = await adapter.update(collection, id, data);
1281
+ if (!result) throw new Error(`Entity ${id} not found in ${collection}`);
1282
+ return result;
1283
+ },
1284
+ async delete(id) {
1285
+ adapter.delete(collection, id);
1286
+ },
1287
+ async query(filters) {
1288
+ return adapter.query(collection, filters);
1289
+ }
1290
+ };
1239
1291
  }
1240
1292
  };
1241
1293
  var FirebaseDataService = class {
@@ -1345,6 +1397,51 @@ var FirebaseDataService = class {
1345
1397
  await docRef.delete();
1346
1398
  return true;
1347
1399
  }
1400
+ async query(collection, filters) {
1401
+ let query = db.collection(collection);
1402
+ const memoryFilters = [];
1403
+ for (const filter of filters) {
1404
+ if (["==", "!=", "<", "<=", ">", ">=", "in", "not-in"].includes(filter.op)) {
1405
+ query = query.where(filter.field, filter.op, filter.value);
1406
+ } else {
1407
+ memoryFilters.push(filter);
1408
+ }
1409
+ }
1410
+ const snapshot = await query.get();
1411
+ let items = snapshot.docs.map((doc) => ({
1412
+ id: doc.id,
1413
+ ...doc.data()
1414
+ }));
1415
+ for (const filter of memoryFilters) {
1416
+ items = items.filter((item) => {
1417
+ const value = item[filter.field];
1418
+ return applyFilterCondition(value, filter.op, filter.value);
1419
+ });
1420
+ }
1421
+ return items;
1422
+ }
1423
+ getStore(collection) {
1424
+ const svc = this;
1425
+ return {
1426
+ async getById(id) {
1427
+ return svc.getById(collection, id);
1428
+ },
1429
+ async create(data) {
1430
+ return svc.create(collection, data);
1431
+ },
1432
+ async update(id, data) {
1433
+ const result = await svc.update(collection, id, data);
1434
+ if (!result) throw new Error(`Entity ${id} not found in ${collection}`);
1435
+ return result;
1436
+ },
1437
+ async delete(id) {
1438
+ await svc.delete(collection, id);
1439
+ },
1440
+ async query(filters) {
1441
+ return svc.query(collection, filters);
1442
+ }
1443
+ };
1444
+ }
1348
1445
  };
1349
1446
  function createDataService() {
1350
1447
  if (env.USE_MOCK_DATA) {
@@ -1354,7 +1451,16 @@ function createDataService() {
1354
1451
  logger.info("[DataService] Using FirebaseDataService");
1355
1452
  return new FirebaseDataService();
1356
1453
  }
1357
- var dataService = createDataService();
1454
+ var _dataService = null;
1455
+ function getDataService() {
1456
+ if (!_dataService) {
1457
+ _dataService = createDataService();
1458
+ }
1459
+ return _dataService;
1460
+ }
1461
+ function resetDataService() {
1462
+ _dataService = null;
1463
+ }
1358
1464
  function seedMockData(entities) {
1359
1465
  if (!env.USE_MOCK_DATA) {
1360
1466
  logger.info("[DataService] Mock mode disabled, skipping seed");
@@ -1362,7 +1468,7 @@ function seedMockData(entities) {
1362
1468
  }
1363
1469
  logger.info("[DataService] Seeding mock data...");
1364
1470
  for (const entity of entities) {
1365
- mockDataService.seed(entity.name, entity.fields, entity.seedCount);
1471
+ getMockDataService().seed(entity.name, entity.fields, entity.seedCount);
1366
1472
  }
1367
1473
  logger.info("[DataService] Mock data seeding complete");
1368
1474
  }
@@ -2265,6 +2371,6 @@ router.get("/active-sessions", async (req, res) => {
2265
2371
  });
2266
2372
  var observability_default = router;
2267
2373
 
2268
- export { AppError, ChangeSetStore, ConflictError, DistributedEventBus, EventBus, EventPersistence, ForbiddenError, InMemoryEventStore, InMemoryServiceRegistry, InMemoryTransport, MockDataService, NotFoundError, RedisTransport, SchemaProtectionService, SchemaStore, ServiceDiscovery, SnapshotStore, UnauthorizedError, ValidationError, ValidationStore, applyFiltersToQuery, asyncHandler, authenticateFirebase, closeWebSocketServer, createServerSkillAgent, dataService, db, debugEventsRouter, emitEntityEvent, env, errorHandler, extractPaginationParams, fromFirestoreFormat, getMemoryManager as getAgentMemoryManager, getSessionManager as getAgentSessionManager, getAuth, getConnectedClientCount, getFirestore, getMemoryManager, getSessionManager, getWebSocketServer, initializeFirebase, logger, mockDataService, multiUserMiddleware, notFoundHandler, observability_default as observabilityRouter, parseQueryFilters, resetMemoryManager, resetSessionManager, seedMockData, serverEventBus, setupEventBroadcast, setupStateSyncWebSocket, toFirestoreFormat, validateBody, validateParams, validateQuery, verifyFirebaseAuth };
2374
+ export { AppError, ChangeSetStore, ConflictError, DistributedEventBus, EventBus, EventPersistence, ForbiddenError, InMemoryEventStore, InMemoryServiceRegistry, InMemoryTransport, MockDataService, NotFoundError, RedisTransport, SchemaProtectionService, SchemaStore, ServiceDiscovery, SnapshotStore, UnauthorizedError, ValidationError, ValidationStore, applyFiltersToQuery, asyncHandler, authenticateFirebase, closeWebSocketServer, createServerSkillAgent, db, debugEventsRouter, emitEntityEvent, env, errorHandler, extractPaginationParams, fromFirestoreFormat, getMemoryManager as getAgentMemoryManager, getSessionManager as getAgentSessionManager, getAuth, getConnectedClientCount, getDataService, getFirestore, getMemoryManager, getMockDataService, getServerEventBus, getSessionManager, getWebSocketServer, initializeFirebase, logger, multiUserMiddleware, notFoundHandler, observability_default as observabilityRouter, parseQueryFilters, resetDataService, resetMemoryManager, resetMockDataService, resetServerEventBus, resetSessionManager, seedMockData, setupEventBroadcast, setupStateSyncWebSocket, toFirestoreFormat, validateBody, validateParams, validateQuery, verifyFirebaseAuth };
2269
2375
  //# sourceMappingURL=index.js.map
2270
2376
  //# sourceMappingURL=index.js.map