@agentuity/runtime 0.0.95 → 0.0.97

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.
Files changed (72) hide show
  1. package/AGENTS.md +3 -1
  2. package/dist/_events.d.ts +64 -0
  3. package/dist/_events.d.ts.map +1 -0
  4. package/dist/_events.js +92 -0
  5. package/dist/_events.js.map +1 -0
  6. package/dist/_idle.d.ts +1 -1
  7. package/dist/_idle.d.ts.map +1 -1
  8. package/dist/_idle.js +2 -16
  9. package/dist/_idle.js.map +1 -1
  10. package/dist/_server.d.ts +30 -13
  11. package/dist/_server.d.ts.map +1 -1
  12. package/dist/_server.js +39 -572
  13. package/dist/_server.js.map +1 -1
  14. package/dist/_services.d.ts.map +1 -1
  15. package/dist/_services.js +4 -2
  16. package/dist/_services.js.map +1 -1
  17. package/dist/_standalone.d.ts.map +1 -1
  18. package/dist/_standalone.js +2 -1
  19. package/dist/_standalone.js.map +1 -1
  20. package/dist/agent.d.ts.map +1 -1
  21. package/dist/agent.js +13 -17
  22. package/dist/agent.js.map +1 -1
  23. package/dist/app.d.ts +58 -171
  24. package/dist/app.d.ts.map +1 -1
  25. package/dist/app.js +119 -218
  26. package/dist/app.js.map +1 -1
  27. package/dist/index.d.ts +11 -2
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +18 -3
  30. package/dist/index.js.map +1 -1
  31. package/dist/middleware.d.ts +29 -0
  32. package/dist/middleware.d.ts.map +1 -0
  33. package/dist/middleware.js +200 -0
  34. package/dist/middleware.js.map +1 -0
  35. package/dist/router.d.ts.map +1 -1
  36. package/dist/router.js +5 -2
  37. package/dist/router.js.map +1 -1
  38. package/dist/services/local/vector.d.ts.map +1 -1
  39. package/dist/services/local/vector.js +3 -2
  40. package/dist/services/local/vector.js.map +1 -1
  41. package/dist/services/thread/local.d.ts +20 -0
  42. package/dist/services/thread/local.d.ts.map +1 -0
  43. package/dist/services/thread/local.js +76 -0
  44. package/dist/services/thread/local.js.map +1 -0
  45. package/dist/session.d.ts +60 -8
  46. package/dist/session.d.ts.map +1 -1
  47. package/dist/session.js +186 -54
  48. package/dist/session.js.map +1 -1
  49. package/dist/web.d.ts +8 -0
  50. package/dist/web.d.ts.map +1 -0
  51. package/dist/web.js +66 -0
  52. package/dist/web.js.map +1 -0
  53. package/dist/workbench.d.ts +2 -0
  54. package/dist/workbench.d.ts.map +1 -1
  55. package/dist/workbench.js +192 -39
  56. package/dist/workbench.js.map +1 -1
  57. package/package.json +10 -10
  58. package/src/_events.ts +142 -0
  59. package/src/_idle.ts +2 -18
  60. package/src/_server.ts +48 -681
  61. package/src/_services.ts +4 -2
  62. package/src/_standalone.ts +2 -1
  63. package/src/agent.ts +11 -14
  64. package/src/app.ts +164 -246
  65. package/src/index.ts +42 -4
  66. package/src/middleware.ts +252 -0
  67. package/src/router.ts +6 -2
  68. package/src/services/local/vector.ts +3 -2
  69. package/src/services/thread/local.ts +106 -0
  70. package/src/session.ts +238 -59
  71. package/src/web.ts +75 -0
  72. package/src/workbench.ts +226 -38
package/dist/app.d.ts CHANGED
@@ -1,12 +1,9 @@
1
- /** biome-ignore-all lint/suspicious/noExplicitAny: any are ok */
2
- import { type Env as HonoEnv, Hono } from 'hono';
1
+ import { type Env as HonoEnv } from 'hono';
3
2
  import type { cors } from 'hono/cors';
4
- import type { BunWebSocketData } from 'hono/bun';
5
3
  import type { Logger } from './logger';
6
4
  import type { Meter, Tracer } from '@opentelemetry/api';
7
5
  import type { KeyValueStorage, SessionEventProvider, EvalRunEventProvider, StreamStorage, VectorStorage, SessionStartEvent } from '@agentuity/core';
8
6
  import type { Email } from './io/email';
9
- import type { Agent, AgentContext } from './agent';
10
7
  import type { ThreadProvider, SessionProvider, Session, Thread } from './session';
11
8
  import type WaitUntilHandler from './_waituntil';
12
9
  export interface WorkbenchInstance {
@@ -97,170 +94,74 @@ export interface PrivateVariables {
97
94
  export interface Env<TAppState = Record<string, never>> extends HonoEnv {
98
95
  Variables: Variables<TAppState>;
99
96
  }
100
- type AppEventMap<TAppState = Record<string, never>> = {
101
- 'agent.started': [Agent<any, any, any, any, TAppState>, AgentContext<any, any, TAppState>];
102
- 'agent.completed': [Agent<any, any, any, any, TAppState>, AgentContext<any, any, TAppState>];
103
- 'agent.errored': [
104
- Agent<any, any, any, any, TAppState>,
105
- AgentContext<any, any, TAppState>,
106
- Error
107
- ];
108
- 'session.started': [Session];
109
- 'session.completed': [Session];
110
- 'thread.created': [Thread];
111
- 'thread.destroyed': [Thread];
112
- };
113
- type AppEventCallback<K extends keyof AppEventMap<any>, TAppState = Record<string, never>> = (eventName: K, ...args: AppEventMap<TAppState>[K]) => void | Promise<void>;
114
97
  /**
115
- * Main application instance created by createApp().
116
- * Provides access to the router, server, logger, and app state.
117
- *
118
- * @template TAppState - The type of application state returned from setup function
119
- *
120
- * @example
121
- * ```typescript
122
- * const app = await createApp({
123
- * setup: async () => ({ db: await connectDB() })
124
- * });
125
- *
126
- * // Access state
127
- * console.log(app.state.db);
128
- *
129
- * // Add routes
130
- * app.router.get('/health', (c) => c.text('OK'));
131
- *
132
- * // Listen to events
133
- * app.addEventListener('agent.started', (eventName, agent, ctx) => {
134
- * console.log(`Agent ${agent.metadata.name} started`);
135
- * });
136
- * ```
98
+ * Get the global app instance (stub for backwards compatibility)
99
+ * Returns null in Vite-native architecture
137
100
  */
138
- export declare class App<TAppState = Record<string, never>> {
101
+ export declare function getApp(): null;
102
+ export { fireEvent } from './_events';
103
+ import type { AppEventMap } from './_events';
104
+ /**
105
+ * Simple server interface for backwards compatibility
106
+ */
107
+ export interface Server {
139
108
  /**
140
- * The Hono router instance for defining routes.
109
+ * The server URL (e.g., "http://localhost:3500")
141
110
  */
142
- readonly router: Hono<Env<TAppState>>;
111
+ url: string;
112
+ }
113
+ export interface AppResult<TAppState = Record<string, never>> {
143
114
  /**
144
- * The Bun server instance.
115
+ * The application state returned from setup
145
116
  */
146
- readonly server: Bun.Server<BunWebSocketData>;
117
+ state: TAppState;
147
118
  /**
148
- * The application logger instance.
119
+ * Shutdown function to call when server stops
149
120
  */
150
- readonly logger: Logger;
121
+ shutdown?: (state: TAppState) => Promise<void> | void;
151
122
  /**
152
- * The application state returned from the setup function.
153
- * Available in all agents via ctx.app.
123
+ * App configuration (for middleware setup)
154
124
  */
155
- readonly state: TAppState;
156
- private eventListeners;
157
- constructor(state: TAppState, router: Hono<Env<TAppState>>, server: Bun.Server<BunWebSocketData>);
125
+ config?: AppConfig<TAppState>;
158
126
  /**
159
- * Register an event listener for application lifecycle events.
160
- *
161
- * Available events:
162
- * - `agent.started` - Fired when an agent begins execution
163
- * - `agent.completed` - Fired when an agent completes successfully
164
- * - `agent.errored` - Fired when an agent throws an error
165
- * - `session.started` - Fired when a new session starts
166
- * - `session.completed` - Fired when a session completes
167
- * - `thread.created` - Fired when a thread is created
168
- * - `thread.destroyed` - Fired when a thread is destroyed
169
- *
170
- * @param eventName - The event name to listen for
171
- * @param callback - The callback function to execute when the event fires
172
- *
173
- * @example
174
- * ```typescript
175
- * app.addEventListener('agent.started', (eventName, agent, ctx) => {
176
- * console.log(`${agent.metadata.name} started for session ${ctx.sessionId}`);
177
- * });
178
- *
179
- * app.addEventListener('agent.errored', (eventName, agent, ctx, error) => {
180
- * console.error(`${agent.metadata.name} failed:`, error.message);
181
- * });
182
- *
183
- * app.addEventListener('session.started', (eventName, session) => {
184
- * console.log(`New session: ${session.id}`);
185
- * });
186
- * ```
127
+ * The router instance (for backwards compatibility)
187
128
  */
188
- addEventListener<K extends keyof AppEventMap<TAppState>>(eventName: K, callback: AppEventCallback<K, TAppState>): void;
129
+ router: import('hono').Hono<Env<TAppState>>;
189
130
  /**
190
- * Remove a previously registered event listener.
191
- *
192
- * @param eventName - The event name to stop listening for
193
- * @param callback - The callback function to remove
194
- *
195
- * @example
196
- * ```typescript
197
- * const handler = (eventName, agent, ctx) => {
198
- * console.log('Agent started:', agent.metadata.name);
199
- * };
200
- *
201
- * app.addEventListener('agent.started', handler);
202
- * // Later...
203
- * app.removeEventListener('agent.started', handler);
204
- * ```
131
+ * Server information (for backwards compatibility)
205
132
  */
206
- removeEventListener<K extends keyof AppEventMap<TAppState>>(eventName: K, callback: AppEventCallback<K, TAppState>): void;
133
+ server: Server;
207
134
  /**
208
- * Manually fire an application event.
209
- * Typically used internally by the runtime, but can be used for custom events.
210
- *
211
- * @param eventName - The event name to fire
212
- * @param args - The arguments to pass to event listeners
213
- *
214
- * @example
215
- * ```typescript
216
- * // Fire a session completed event
217
- * await app.fireEvent('session.completed', session);
218
- * ```
135
+ * Logger instance (for backwards compatibility)
219
136
  */
220
- fireEvent<K extends keyof AppEventMap<TAppState>>(eventName: K, ...args: AppEventMap<TAppState>[K]): Promise<void>;
137
+ logger: Logger;
138
+ /**
139
+ * Add an event listener for app events
140
+ */
141
+ addEventListener<K extends keyof AppEventMap<TAppState>>(eventName: K, callback: (eventName: K, ...args: AppEventMap<TAppState>[K]) => void | Promise<void>): void;
142
+ /**
143
+ * Remove an event listener for app events
144
+ */
145
+ removeEventListener<K extends keyof AppEventMap<TAppState>>(eventName: K, callback: (eventName: K, ...args: AppEventMap<TAppState>[K]) => void | Promise<void>): void;
221
146
  }
222
147
  /**
223
- * Get the global app instance.
224
- * Returns null if createApp() has not been called yet.
225
- *
226
- * @returns The global App instance or null
227
- *
228
- * @example
229
- * ```typescript
230
- * const app = getApp();
231
- * if (app) {
232
- * console.log('Server running on port:', app.server.port);
233
- * }
234
- * ```
235
- */
236
- export declare function getApp(): App<any> | null;
237
- /**
238
- * Creates a new Agentuity application with optional lifecycle hooks and service configuration.
239
- *
240
- * This is the main entry point for creating an Agentuity app. The app will:
241
- * 1. Run the setup function (if provided) to initialize app state
242
- * 2. Start the Bun server
243
- * 3. Make the app state available in all agents via ctx.app
148
+ * Create an Agentuity application with lifecycle management.
244
149
  *
245
- * @template TAppState - The type of application state returned from setup function
150
+ * In Vite-native architecture:
151
+ * - This only handles setup/shutdown lifecycle
152
+ * - Router creation and middleware are handled by the generated entry file
153
+ * - Server is managed by Vite (dev) or Bun.serve (prod)
246
154
  *
247
- * @param config - Optional application configuration
248
- * @param config.setup - Function to initialize app state, runs before server starts
249
- * @param config.shutdown - Function to clean up resources when server stops
250
- * @param config.cors - CORS configuration for HTTP routes
251
- * @param config.services - Override default storage and service providers
252
- *
253
- * @returns Promise resolving to App instance with running server
155
+ * @template TAppState - Type of application state from setup()
254
156
  *
255
157
  * @example
256
158
  * ```typescript
257
- * // Simple app with no state
258
- * const app = await createApp();
159
+ * // app.ts
160
+ * import { createApp } from '@agentuity/runtime';
259
161
  *
260
- * // App with database connection
261
162
  * const app = await createApp({
262
163
  * setup: async () => {
263
- * const db = await connectDatabase();
164
+ * const db = await connectDB();
264
165
  * return { db };
265
166
  * },
266
167
  * shutdown: async (state) => {
@@ -268,37 +169,23 @@ export declare function getApp(): App<any> | null;
268
169
  * }
269
170
  * });
270
171
  *
271
- * // Access state in agents
272
- * const agent = createAgent('user-query', {
273
- * handler: async (ctx, input) => {
274
- * const db = ctx.app.db; // Strongly typed!
275
- * return db.query('SELECT * FROM users');
276
- * }
277
- * });
278
- *
279
- * // App with custom services
280
- * const app = await createApp({
281
- * services: {
282
- * useLocal: true, // Use local in-memory storage for development
283
- * }
284
- * });
172
+ * // Access state in agents via ctx.app.db
285
173
  * ```
286
174
  */
287
- export declare function createApp<TAppState = Record<string, never>>(config?: AppConfig<TAppState>): Promise<App<TAppState>>;
175
+ export declare function createApp<TAppState = Record<string, never>>(config?: AppConfig<TAppState>): Promise<AppResult<TAppState>>;
288
176
  /**
289
- * Fire a global application event.
290
- * Convenience function that calls fireEvent on the global app instance.
291
- *
292
- * @param eventName - The event name to fire
293
- * @param args - The arguments to pass to event listeners
294
- *
295
- * @example
296
- * ```typescript
297
- * // Fire from anywhere in your app
298
- * await fireEvent('session.started', session);
299
- * await fireEvent('agent.completed', agent, ctx);
300
- * ```
177
+ * Get the global app state
178
+ * Used by generated entry file and middleware
179
+ */
180
+ export declare function getAppState<TAppState = any>(): TAppState;
181
+ /**
182
+ * Get the global app config
183
+ * Used by generated entry file for middleware setup
184
+ */
185
+ export declare function getAppConfig<TAppState = any>(): AppConfig<TAppState> | undefined;
186
+ /**
187
+ * Run the global shutdown function
188
+ * Called by generated entry file on cleanup
301
189
  */
302
- export declare function fireEvent<K extends keyof AppEventMap<any>>(eventName: K, ...args: AppEventMap<any>[K]): Promise<void>;
303
- export {};
190
+ export declare function runShutdown(): Promise<void>;
304
191
  //# sourceMappingURL=app.d.ts.map
package/dist/app.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AACA,iEAAiE;AACjE,OAAO,EAAE,KAAK,GAAG,IAAI,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACjD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAEvC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,KAAK,EACX,eAAe,EACf,oBAAoB,EACpB,oBAAoB,EACpB,aAAa,EACb,aAAa,EACb,iBAAiB,EACjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAClF,OAAO,KAAK,gBAAgB,MAAM,cAAc,CAAC;AAGjD,MAAM,WAAW,iBAAiB;IACjC,MAAM,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,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CAExD;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,SAAS,GAAG,GAAG,KAAK,SAAS,CAAC,SAAS,CAAC,GAAG,SAAS,CAEhF;AAED;;;GAGG;AACH,wBAAsB,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAMjD"}
package/dist/app.js CHANGED
@@ -1,195 +1,32 @@
1
- /* eslint-disable @typescript-eslint/no-explicit-any */
2
- /** biome-ignore-all lint/suspicious/noExplicitAny: any are ok */
3
- import { Hono } from 'hono';
4
- import { createServer, getLogger } from './_server';
5
- import { internal } from './logger/internal';
6
1
  /**
7
- * Main application instance created by createApp().
8
- * Provides access to the router, server, logger, and app state.
9
- *
10
- * @template TAppState - The type of application state returned from setup function
11
- *
12
- * @example
13
- * ```typescript
14
- * const app = await createApp({
15
- * setup: async () => ({ db: await connectDB() })
16
- * });
17
- *
18
- * // Access state
19
- * console.log(app.state.db);
20
- *
21
- * // Add routes
22
- * app.router.get('/health', (c) => c.text('OK'));
23
- *
24
- * // Listen to events
25
- * app.addEventListener('agent.started', (eventName, agent, ctx) => {
26
- * console.log(`Agent ${agent.metadata.name} started`);
27
- * });
28
- * ```
29
- */
30
- export class App {
31
- /**
32
- * The Hono router instance for defining routes.
33
- */
34
- router;
35
- /**
36
- * The Bun server instance.
37
- */
38
- server;
39
- /**
40
- * The application logger instance.
41
- */
42
- logger;
43
- /**
44
- * The application state returned from the setup function.
45
- * Available in all agents via ctx.app.
46
- */
47
- state;
48
- eventListeners = new Map();
49
- constructor(state, router, server) {
50
- this.state = state;
51
- this.router = router;
52
- this.server = server;
53
- this.logger = getLogger();
54
- setGlobalApp(this);
55
- }
56
- /**
57
- * Register an event listener for application lifecycle events.
58
- *
59
- * Available events:
60
- * - `agent.started` - Fired when an agent begins execution
61
- * - `agent.completed` - Fired when an agent completes successfully
62
- * - `agent.errored` - Fired when an agent throws an error
63
- * - `session.started` - Fired when a new session starts
64
- * - `session.completed` - Fired when a session completes
65
- * - `thread.created` - Fired when a thread is created
66
- * - `thread.destroyed` - Fired when a thread is destroyed
67
- *
68
- * @param eventName - The event name to listen for
69
- * @param callback - The callback function to execute when the event fires
70
- *
71
- * @example
72
- * ```typescript
73
- * app.addEventListener('agent.started', (eventName, agent, ctx) => {
74
- * console.log(`${agent.metadata.name} started for session ${ctx.sessionId}`);
75
- * });
76
- *
77
- * app.addEventListener('agent.errored', (eventName, agent, ctx, error) => {
78
- * console.error(`${agent.metadata.name} failed:`, error.message);
79
- * });
80
- *
81
- * app.addEventListener('session.started', (eventName, session) => {
82
- * console.log(`New session: ${session.id}`);
83
- * });
84
- * ```
85
- */
86
- addEventListener(eventName, callback) {
87
- let callbacks = this.eventListeners.get(eventName);
88
- if (!callbacks) {
89
- callbacks = new Set();
90
- this.eventListeners.set(eventName, callbacks);
91
- }
92
- callbacks.add(callback);
93
- }
94
- /**
95
- * Remove a previously registered event listener.
96
- *
97
- * @param eventName - The event name to stop listening for
98
- * @param callback - The callback function to remove
99
- *
100
- * @example
101
- * ```typescript
102
- * const handler = (eventName, agent, ctx) => {
103
- * console.log('Agent started:', agent.metadata.name);
104
- * };
105
- *
106
- * app.addEventListener('agent.started', handler);
107
- * // Later...
108
- * app.removeEventListener('agent.started', handler);
109
- * ```
110
- */
111
- removeEventListener(eventName, callback) {
112
- const callbacks = this.eventListeners.get(eventName);
113
- if (!callbacks)
114
- return;
115
- callbacks.delete(callback);
116
- }
117
- /**
118
- * Manually fire an application event.
119
- * Typically used internally by the runtime, but can be used for custom events.
120
- *
121
- * @param eventName - The event name to fire
122
- * @param args - The arguments to pass to event listeners
123
- *
124
- * @example
125
- * ```typescript
126
- * // Fire a session completed event
127
- * await app.fireEvent('session.completed', session);
128
- * ```
129
- */
130
- async fireEvent(eventName, ...args) {
131
- const callbacks = this.eventListeners.get(eventName);
132
- if (!callbacks || callbacks.size === 0)
133
- return;
134
- for (const callback of callbacks) {
135
- try {
136
- await callback(eventName, ...args);
137
- }
138
- catch (error) {
139
- // Log but don't re-throw - event listener errors should not crash the server
140
- internal.error(`Error in app event listener for '${eventName}':`, error);
141
- }
142
- }
143
- }
144
- }
145
- let globalApp = null;
146
- function setGlobalApp(app) {
147
- globalApp = app;
148
- }
149
- /**
150
- * Get the global app instance.
151
- * Returns null if createApp() has not been called yet.
152
- *
153
- * @returns The global App instance or null
154
- *
155
- * @example
156
- * ```typescript
157
- * const app = getApp();
158
- * if (app) {
159
- * console.log('Server running on port:', app.server.port);
160
- * }
161
- * ```
2
+ * Get the global app instance (stub for backwards compatibility)
3
+ * Returns null in Vite-native architecture
162
4
  */
163
5
  export function getApp() {
164
- return globalApp;
6
+ return null;
165
7
  }
8
+ // Re-export event functions from _events
9
+ export { fireEvent } from './_events';
10
+ import { addEventListener as globalAddEventListener, removeEventListener as globalRemoveEventListener, } from './_events';
11
+ import { getLogger, getRouter } from './_server';
166
12
  /**
167
- * Creates a new Agentuity application with optional lifecycle hooks and service configuration.
13
+ * Create an Agentuity application with lifecycle management.
168
14
  *
169
- * This is the main entry point for creating an Agentuity app. The app will:
170
- * 1. Run the setup function (if provided) to initialize app state
171
- * 2. Start the Bun server
172
- * 3. Make the app state available in all agents via ctx.app
15
+ * In Vite-native architecture:
16
+ * - This only handles setup/shutdown lifecycle
17
+ * - Router creation and middleware are handled by the generated entry file
18
+ * - Server is managed by Vite (dev) or Bun.serve (prod)
173
19
  *
174
- * @template TAppState - The type of application state returned from setup function
175
- *
176
- * @param config - Optional application configuration
177
- * @param config.setup - Function to initialize app state, runs before server starts
178
- * @param config.shutdown - Function to clean up resources when server stops
179
- * @param config.cors - CORS configuration for HTTP routes
180
- * @param config.services - Override default storage and service providers
181
- *
182
- * @returns Promise resolving to App instance with running server
20
+ * @template TAppState - Type of application state from setup()
183
21
  *
184
22
  * @example
185
23
  * ```typescript
186
- * // Simple app with no state
187
- * const app = await createApp();
24
+ * // app.ts
25
+ * import { createApp } from '@agentuity/runtime';
188
26
  *
189
- * // App with database connection
190
27
  * const app = await createApp({
191
28
  * setup: async () => {
192
- * const db = await connectDatabase();
29
+ * const db = await connectDB();
193
30
  * return { db };
194
31
  * },
195
32
  * shutdown: async (state) => {
@@ -197,51 +34,115 @@ export function getApp() {
197
34
  * }
198
35
  * });
199
36
  *
200
- * // Access state in agents
201
- * const agent = createAgent('user-query', {
202
- * handler: async (ctx, input) => {
203
- * const db = ctx.app.db; // Strongly typed!
204
- * return db.query('SELECT * FROM users');
205
- * }
206
- * });
207
- *
208
- * // App with custom services
209
- * const app = await createApp({
210
- * services: {
211
- * useLocal: true, // Use local in-memory storage for development
212
- * }
213
- * });
37
+ * // Access state in agents via ctx.app.db
214
38
  * ```
215
39
  */
216
40
  export async function createApp(config) {
217
- const initializer = async () => {
218
- // Run setup if provided
219
- if (config?.setup) {
220
- return config.setup();
221
- }
222
- else {
223
- return {};
224
- }
41
+ // Run setup to get app state
42
+ const state = config?.setup ? await config.setup() : {};
43
+ // Store state and config globally for generated entry file to access
44
+ globalThis.__AGENTUITY_APP_STATE__ = state;
45
+ globalThis.__AGENTUITY_APP_CONFIG__ = config;
46
+ // Store shutdown function for cleanup
47
+ const shutdown = config?.shutdown;
48
+ if (shutdown) {
49
+ globalThis.__AGENTUITY_SHUTDOWN__ = shutdown;
50
+ }
51
+ // Return a logger proxy that lazily resolves to the global logger
52
+ // This is necessary because Vite bundling inlines and reorders module code,
53
+ // causing app.ts to execute before entry file sets the global logger.
54
+ // The proxy ensures logger works correctly when actually used (in handlers/callbacks).
55
+ const logger = {
56
+ trace: (...args) => {
57
+ const gl = getLogger();
58
+ if (gl)
59
+ gl.trace(...args);
60
+ },
61
+ debug: (...args) => {
62
+ const gl = getLogger();
63
+ if (gl)
64
+ gl.debug(...args);
65
+ },
66
+ info: (...args) => {
67
+ const gl = getLogger();
68
+ if (gl)
69
+ gl.info(...args);
70
+ else
71
+ console.log('[INFO]', ...args);
72
+ },
73
+ warn: (...args) => {
74
+ const gl = getLogger();
75
+ if (gl)
76
+ gl.warn(...args);
77
+ else
78
+ console.warn('[WARN]', ...args);
79
+ },
80
+ error: (...args) => {
81
+ const gl = getLogger();
82
+ if (gl)
83
+ gl.error(...args);
84
+ else
85
+ console.error('[ERROR]', ...args);
86
+ },
87
+ fatal: (...args) => {
88
+ const gl = getLogger();
89
+ if (gl)
90
+ return gl.fatal(...args);
91
+ // Fallback: log to console but let the real logger handle exit
92
+ console.error('[FATAL]', ...args);
93
+ throw new Error('Fatal error');
94
+ },
95
+ child: (bindings) => {
96
+ const gl = getLogger();
97
+ return gl ? gl.child(bindings) : logger;
98
+ },
99
+ };
100
+ // Create server info from environment
101
+ const port = process.env.PORT || '3500';
102
+ const server = {
103
+ url: `http://127.0.0.1:${port}`,
104
+ };
105
+ // Get router from global (set by entry file before app.ts import)
106
+ // In dev mode, router may not be available during bundling
107
+ const globalRouter = getRouter();
108
+ if (!globalRouter) {
109
+ throw new Error('Router is not available. Ensure router is initialized before calling createApp(). This typically happens during bundling or when the entry file has not properly set up the router.');
110
+ }
111
+ const router = globalRouter;
112
+ return {
113
+ state,
114
+ shutdown,
115
+ config,
116
+ router,
117
+ server,
118
+ logger,
119
+ addEventListener: globalAddEventListener,
120
+ removeEventListener: globalRemoveEventListener,
225
121
  };
226
- const router = new Hono();
227
- const [server, state] = await createServer(router, initializer, config);
228
- return new App(state, router, server);
229
122
  }
230
123
  /**
231
- * Fire a global application event.
232
- * Convenience function that calls fireEvent on the global app instance.
233
- *
234
- * @param eventName - The event name to fire
235
- * @param args - The arguments to pass to event listeners
236
- *
237
- * @example
238
- * ```typescript
239
- * // Fire from anywhere in your app
240
- * await fireEvent('session.started', session);
241
- * await fireEvent('agent.completed', agent, ctx);
242
- * ```
124
+ * Get the global app state
125
+ * Used by generated entry file and middleware
126
+ */
127
+ export function getAppState() {
128
+ return globalThis.__AGENTUITY_APP_STATE__ || {};
129
+ }
130
+ /**
131
+ * Get the global app config
132
+ * Used by generated entry file for middleware setup
133
+ */
134
+ export function getAppConfig() {
135
+ return globalThis.__AGENTUITY_APP_CONFIG__;
136
+ }
137
+ /**
138
+ * Run the global shutdown function
139
+ * Called by generated entry file on cleanup
243
140
  */
244
- export async function fireEvent(eventName, ...args) {
245
- await globalApp?.fireEvent(eventName, ...args);
141
+ export async function runShutdown() {
142
+ const shutdown = globalThis.__AGENTUITY_SHUTDOWN__;
143
+ if (shutdown) {
144
+ const state = getAppState();
145
+ await shutdown(state);
146
+ }
246
147
  }
247
148
  //# sourceMappingURL=app.js.map