@agentuity/runtime 0.1.12 → 0.1.14

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 (272) hide show
  1. package/package.json +8 -8
  2. package/src/_config.ts +13 -0
  3. package/src/_standalone.ts +167 -19
  4. package/src/index.ts +1 -0
  5. package/dist/_config.d.ts +0 -90
  6. package/dist/_config.d.ts.map +0 -1
  7. package/dist/_config.js +0 -135
  8. package/dist/_config.js.map +0 -1
  9. package/dist/_context.d.ts +0 -76
  10. package/dist/_context.d.ts.map +0 -1
  11. package/dist/_context.js +0 -147
  12. package/dist/_context.js.map +0 -1
  13. package/dist/_events.d.ts +0 -64
  14. package/dist/_events.d.ts.map +0 -1
  15. package/dist/_events.js +0 -92
  16. package/dist/_events.js.map +0 -1
  17. package/dist/_idle.d.ts +0 -7
  18. package/dist/_idle.d.ts.map +0 -1
  19. package/dist/_idle.js +0 -10
  20. package/dist/_idle.js.map +0 -1
  21. package/dist/_metadata.d.ts +0 -117
  22. package/dist/_metadata.d.ts.map +0 -1
  23. package/dist/_metadata.js +0 -246
  24. package/dist/_metadata.js.map +0 -1
  25. package/dist/_process-protection.d.ts +0 -25
  26. package/dist/_process-protection.d.ts.map +0 -1
  27. package/dist/_process-protection.js +0 -65
  28. package/dist/_process-protection.js.map +0 -1
  29. package/dist/_server.d.ts +0 -46
  30. package/dist/_server.d.ts.map +0 -1
  31. package/dist/_server.js +0 -85
  32. package/dist/_server.js.map +0 -1
  33. package/dist/_services.d.ts +0 -21
  34. package/dist/_services.d.ts.map +0 -1
  35. package/dist/_services.js +0 -248
  36. package/dist/_services.js.map +0 -1
  37. package/dist/_standalone.d.ts +0 -168
  38. package/dist/_standalone.d.ts.map +0 -1
  39. package/dist/_standalone.js +0 -441
  40. package/dist/_standalone.js.map +0 -1
  41. package/dist/_tokens.d.ts +0 -12
  42. package/dist/_tokens.d.ts.map +0 -1
  43. package/dist/_tokens.js +0 -96
  44. package/dist/_tokens.js.map +0 -1
  45. package/dist/_util.d.ts +0 -16
  46. package/dist/_util.d.ts.map +0 -1
  47. package/dist/_util.js +0 -54
  48. package/dist/_util.js.map +0 -1
  49. package/dist/_validation.d.ts +0 -89
  50. package/dist/_validation.d.ts.map +0 -1
  51. package/dist/_validation.js +0 -29
  52. package/dist/_validation.js.map +0 -1
  53. package/dist/_waituntil.d.ts +0 -18
  54. package/dist/_waituntil.d.ts.map +0 -1
  55. package/dist/_waituntil.js +0 -97
  56. package/dist/_waituntil.js.map +0 -1
  57. package/dist/agent.d.ts +0 -1210
  58. package/dist/agent.d.ts.map +0 -1
  59. package/dist/agent.js +0 -903
  60. package/dist/agent.js.map +0 -1
  61. package/dist/app.d.ts +0 -322
  62. package/dist/app.d.ts.map +0 -1
  63. package/dist/app.js +0 -160
  64. package/dist/app.js.map +0 -1
  65. package/dist/bun-s3-patch.d.ts +0 -37
  66. package/dist/bun-s3-patch.d.ts.map +0 -1
  67. package/dist/bun-s3-patch.js +0 -139
  68. package/dist/bun-s3-patch.js.map +0 -1
  69. package/dist/cors.d.ts +0 -42
  70. package/dist/cors.d.ts.map +0 -1
  71. package/dist/cors.js +0 -117
  72. package/dist/cors.js.map +0 -1
  73. package/dist/devmode.d.ts +0 -3
  74. package/dist/devmode.d.ts.map +0 -1
  75. package/dist/devmode.js +0 -167
  76. package/dist/devmode.js.map +0 -1
  77. package/dist/eval.d.ts +0 -91
  78. package/dist/eval.d.ts.map +0 -1
  79. package/dist/eval.js +0 -16
  80. package/dist/eval.js.map +0 -1
  81. package/dist/handlers/cron.d.ts +0 -47
  82. package/dist/handlers/cron.d.ts.map +0 -1
  83. package/dist/handlers/cron.js +0 -49
  84. package/dist/handlers/cron.js.map +0 -1
  85. package/dist/handlers/index.d.ts +0 -5
  86. package/dist/handlers/index.d.ts.map +0 -1
  87. package/dist/handlers/index.js +0 -5
  88. package/dist/handlers/index.js.map +0 -1
  89. package/dist/handlers/sse.d.ts +0 -91
  90. package/dist/handlers/sse.d.ts.map +0 -1
  91. package/dist/handlers/sse.js +0 -213
  92. package/dist/handlers/sse.js.map +0 -1
  93. package/dist/handlers/stream.d.ts +0 -52
  94. package/dist/handlers/stream.d.ts.map +0 -1
  95. package/dist/handlers/stream.js +0 -116
  96. package/dist/handlers/stream.js.map +0 -1
  97. package/dist/handlers/websocket.d.ts +0 -49
  98. package/dist/handlers/websocket.d.ts.map +0 -1
  99. package/dist/handlers/websocket.js +0 -143
  100. package/dist/handlers/websocket.js.map +0 -1
  101. package/dist/index.d.ts +0 -71
  102. package/dist/index.d.ts.map +0 -1
  103. package/dist/index.js +0 -58
  104. package/dist/index.js.map +0 -1
  105. package/dist/logger/console.d.ts +0 -70
  106. package/dist/logger/console.d.ts.map +0 -1
  107. package/dist/logger/console.js +0 -274
  108. package/dist/logger/console.js.map +0 -1
  109. package/dist/logger/index.d.ts +0 -3
  110. package/dist/logger/index.d.ts.map +0 -1
  111. package/dist/logger/index.js +0 -3
  112. package/dist/logger/index.js.map +0 -1
  113. package/dist/logger/internal.d.ts +0 -79
  114. package/dist/logger/internal.d.ts.map +0 -1
  115. package/dist/logger/internal.js +0 -133
  116. package/dist/logger/internal.js.map +0 -1
  117. package/dist/logger/logger.d.ts +0 -41
  118. package/dist/logger/logger.d.ts.map +0 -1
  119. package/dist/logger/logger.js +0 -2
  120. package/dist/logger/logger.js.map +0 -1
  121. package/dist/logger/user.d.ts +0 -8
  122. package/dist/logger/user.d.ts.map +0 -1
  123. package/dist/logger/user.js +0 -7
  124. package/dist/logger/user.js.map +0 -1
  125. package/dist/logger/util.d.ts +0 -11
  126. package/dist/logger/util.d.ts.map +0 -1
  127. package/dist/logger/util.js +0 -77
  128. package/dist/logger/util.js.map +0 -1
  129. package/dist/middleware.d.ts +0 -112
  130. package/dist/middleware.d.ts.map +0 -1
  131. package/dist/middleware.js +0 -507
  132. package/dist/middleware.js.map +0 -1
  133. package/dist/otel/config.d.ts +0 -19
  134. package/dist/otel/config.d.ts.map +0 -1
  135. package/dist/otel/config.js +0 -26
  136. package/dist/otel/config.js.map +0 -1
  137. package/dist/otel/console.d.ts +0 -33
  138. package/dist/otel/console.d.ts.map +0 -1
  139. package/dist/otel/console.js +0 -86
  140. package/dist/otel/console.js.map +0 -1
  141. package/dist/otel/exporters/index.d.ts +0 -4
  142. package/dist/otel/exporters/index.d.ts.map +0 -1
  143. package/dist/otel/exporters/index.js +0 -4
  144. package/dist/otel/exporters/index.js.map +0 -1
  145. package/dist/otel/exporters/jsonl-log-exporter.d.ts +0 -36
  146. package/dist/otel/exporters/jsonl-log-exporter.d.ts.map +0 -1
  147. package/dist/otel/exporters/jsonl-log-exporter.js +0 -103
  148. package/dist/otel/exporters/jsonl-log-exporter.js.map +0 -1
  149. package/dist/otel/exporters/jsonl-metric-exporter.d.ts +0 -40
  150. package/dist/otel/exporters/jsonl-metric-exporter.d.ts.map +0 -1
  151. package/dist/otel/exporters/jsonl-metric-exporter.js +0 -104
  152. package/dist/otel/exporters/jsonl-metric-exporter.js.map +0 -1
  153. package/dist/otel/exporters/jsonl-trace-exporter.d.ts +0 -36
  154. package/dist/otel/exporters/jsonl-trace-exporter.d.ts.map +0 -1
  155. package/dist/otel/exporters/jsonl-trace-exporter.js +0 -111
  156. package/dist/otel/exporters/jsonl-trace-exporter.js.map +0 -1
  157. package/dist/otel/fetch.d.ts +0 -12
  158. package/dist/otel/fetch.d.ts.map +0 -1
  159. package/dist/otel/fetch.js +0 -82
  160. package/dist/otel/fetch.js.map +0 -1
  161. package/dist/otel/http.d.ts +0 -16
  162. package/dist/otel/http.d.ts.map +0 -1
  163. package/dist/otel/http.js +0 -44
  164. package/dist/otel/http.js.map +0 -1
  165. package/dist/otel/logger.d.ts +0 -37
  166. package/dist/otel/logger.d.ts.map +0 -1
  167. package/dist/otel/logger.js +0 -268
  168. package/dist/otel/logger.js.map +0 -1
  169. package/dist/otel/otel.d.ts +0 -65
  170. package/dist/otel/otel.d.ts.map +0 -1
  171. package/dist/otel/otel.js +0 -261
  172. package/dist/otel/otel.js.map +0 -1
  173. package/dist/router.d.ts +0 -100
  174. package/dist/router.d.ts.map +0 -1
  175. package/dist/router.js +0 -163
  176. package/dist/router.js.map +0 -1
  177. package/dist/services/evalrun/composite.d.ts +0 -21
  178. package/dist/services/evalrun/composite.d.ts.map +0 -1
  179. package/dist/services/evalrun/composite.js +0 -26
  180. package/dist/services/evalrun/composite.js.map +0 -1
  181. package/dist/services/evalrun/http.d.ts +0 -24
  182. package/dist/services/evalrun/http.d.ts.map +0 -1
  183. package/dist/services/evalrun/http.js +0 -86
  184. package/dist/services/evalrun/http.js.map +0 -1
  185. package/dist/services/evalrun/index.d.ts +0 -5
  186. package/dist/services/evalrun/index.d.ts.map +0 -1
  187. package/dist/services/evalrun/index.js +0 -5
  188. package/dist/services/evalrun/index.js.map +0 -1
  189. package/dist/services/evalrun/json.d.ts +0 -21
  190. package/dist/services/evalrun/json.d.ts.map +0 -1
  191. package/dist/services/evalrun/json.js +0 -38
  192. package/dist/services/evalrun/json.js.map +0 -1
  193. package/dist/services/evalrun/local.d.ts +0 -19
  194. package/dist/services/evalrun/local.d.ts.map +0 -1
  195. package/dist/services/evalrun/local.js +0 -22
  196. package/dist/services/evalrun/local.js.map +0 -1
  197. package/dist/services/local/_db.d.ts +0 -4
  198. package/dist/services/local/_db.d.ts.map +0 -1
  199. package/dist/services/local/_db.js +0 -123
  200. package/dist/services/local/_db.js.map +0 -1
  201. package/dist/services/local/_router.d.ts +0 -3
  202. package/dist/services/local/_router.d.ts.map +0 -1
  203. package/dist/services/local/_router.js +0 -28
  204. package/dist/services/local/_router.js.map +0 -1
  205. package/dist/services/local/_util.d.ts +0 -18
  206. package/dist/services/local/_util.d.ts.map +0 -1
  207. package/dist/services/local/_util.js +0 -44
  208. package/dist/services/local/_util.js.map +0 -1
  209. package/dist/services/local/index.d.ts +0 -7
  210. package/dist/services/local/index.d.ts.map +0 -1
  211. package/dist/services/local/index.js +0 -7
  212. package/dist/services/local/index.js.map +0 -1
  213. package/dist/services/local/keyvalue.d.ts +0 -17
  214. package/dist/services/local/keyvalue.d.ts.map +0 -1
  215. package/dist/services/local/keyvalue.js +0 -125
  216. package/dist/services/local/keyvalue.js.map +0 -1
  217. package/dist/services/local/stream.d.ts +0 -12
  218. package/dist/services/local/stream.d.ts.map +0 -1
  219. package/dist/services/local/stream.js +0 -262
  220. package/dist/services/local/stream.js.map +0 -1
  221. package/dist/services/local/vector.d.ts +0 -17
  222. package/dist/services/local/vector.d.ts.map +0 -1
  223. package/dist/services/local/vector.js +0 -303
  224. package/dist/services/local/vector.js.map +0 -1
  225. package/dist/services/sandbox/http.d.ts +0 -13
  226. package/dist/services/sandbox/http.d.ts.map +0 -1
  227. package/dist/services/sandbox/http.js +0 -130
  228. package/dist/services/sandbox/http.js.map +0 -1
  229. package/dist/services/sandbox/index.d.ts +0 -2
  230. package/dist/services/sandbox/index.d.ts.map +0 -1
  231. package/dist/services/sandbox/index.js +0 -2
  232. package/dist/services/sandbox/index.js.map +0 -1
  233. package/dist/services/session/composite.d.ts +0 -21
  234. package/dist/services/session/composite.d.ts.map +0 -1
  235. package/dist/services/session/composite.js +0 -26
  236. package/dist/services/session/composite.js.map +0 -1
  237. package/dist/services/session/http.d.ts +0 -34
  238. package/dist/services/session/http.d.ts.map +0 -1
  239. package/dist/services/session/http.js +0 -80
  240. package/dist/services/session/http.js.map +0 -1
  241. package/dist/services/session/index.d.ts +0 -5
  242. package/dist/services/session/index.d.ts.map +0 -1
  243. package/dist/services/session/index.js +0 -5
  244. package/dist/services/session/index.js.map +0 -1
  245. package/dist/services/session/json.d.ts +0 -22
  246. package/dist/services/session/json.d.ts.map +0 -1
  247. package/dist/services/session/json.js +0 -35
  248. package/dist/services/session/json.js.map +0 -1
  249. package/dist/services/session/local.d.ts +0 -19
  250. package/dist/services/session/local.d.ts.map +0 -1
  251. package/dist/services/session/local.js +0 -23
  252. package/dist/services/session/local.js.map +0 -1
  253. package/dist/services/thread/local.d.ts +0 -20
  254. package/dist/services/thread/local.d.ts.map +0 -1
  255. package/dist/services/thread/local.js +0 -158
  256. package/dist/services/thread/local.js.map +0 -1
  257. package/dist/session.d.ts +0 -734
  258. package/dist/session.d.ts.map +0 -1
  259. package/dist/session.js +0 -1139
  260. package/dist/session.js.map +0 -1
  261. package/dist/validator.d.ts +0 -142
  262. package/dist/validator.d.ts.map +0 -1
  263. package/dist/validator.js +0 -149
  264. package/dist/validator.js.map +0 -1
  265. package/dist/web.d.ts +0 -8
  266. package/dist/web.d.ts.map +0 -1
  267. package/dist/web.js +0 -66
  268. package/dist/web.js.map +0 -1
  269. package/dist/workbench.d.ts +0 -17
  270. package/dist/workbench.d.ts.map +0 -1
  271. package/dist/workbench.js +0 -507
  272. package/dist/workbench.js.map +0 -1
package/dist/agent.d.ts DELETED
@@ -1,1210 +0,0 @@
1
- import { type KeyValueStorage, type StandardSchemaV1, type StreamStorage, type VectorStorage, type SandboxService, type InferInput, type InferOutput } from '@agentuity/core';
2
- import { type Tracer } from '@opentelemetry/api';
3
- import type { Context, MiddlewareHandler } from 'hono';
4
- import type { Handler } from 'hono/types';
5
- import { AGENT_RUNTIME } from './_config';
6
- import type { Logger } from './logger';
7
- import type { Eval, EvalFunction } from './eval';
8
- import type { Thread, Session } from './session';
9
- import type { AppState } from './index';
10
- export type AgentEventName = 'started' | 'completed' | 'errored';
11
- export type AgentEventCallback<TAgent extends Agent<any, any, any>> = ((eventName: 'started', agent: TAgent, context: AgentContext<any, any, any>) => Promise<void> | void) | ((eventName: 'completed', agent: TAgent, context: AgentContext<any, any, any>) => Promise<void> | void) | ((eventName: 'errored', agent: TAgent, context: AgentContext<any, any, any>, data: Error) => Promise<void> | void);
12
- /**
13
- * Runtime state container for agents and event listeners.
14
- * Isolates global state into context for better testing.
15
- */
16
- export interface AgentRuntimeState {
17
- agents: Map<string, Agent<any, any, any, any, any>>;
18
- agentConfigs: Map<string, unknown>;
19
- agentEventListeners: WeakMap<Agent<any, any, any, any, any>, Map<AgentEventName, Set<AgentEventCallback<any>>>>;
20
- }
21
- /**
22
- * Context object passed to every agent handler providing access to runtime services and state.
23
- *
24
- * @template TAgentRegistry - Registry of all available agents (auto-generated, strongly-typed)
25
- * @template TConfig - Agent-specific configuration type from setup function
26
- * @template TAppState - Application-wide state type from createApp
27
- *
28
- * @example
29
- * ```typescript
30
- * const agent = createAgent('my-agent', {
31
- * handler: async (ctx, input) => {
32
- * // Logging
33
- * ctx.logger.info('Processing request', { input });
34
- *
35
- * // Call another agent (import it directly)
36
- * import otherAgent from './other-agent';
37
- * const result = await otherAgent.run({ data: input });
38
- *
39
- * // Store data
40
- * await ctx.kv.set('key', { value: result });
41
- *
42
- * // Access config from setup
43
- * const cache = ctx.config.cache;
44
- *
45
- * // Background task
46
- * ctx.waitUntil(async () => {
47
- * await ctx.logger.info('Cleanup complete');
48
- * });
49
- *
50
- * return result;
51
- * }
52
- * });
53
- * ```
54
- */
55
- export interface AgentContext<_TAgentRegistry extends AgentRegistry = AgentRegistry, TConfig = unknown, TAppState = Record<string, never>> {
56
- /**
57
- * Internal runtime state (agents, configs, event listeners).
58
- * Stored with Symbol key to prevent accidental access.
59
- * Use getAgentRuntime(ctx) to access.
60
- * @internal
61
- */
62
- [AGENT_RUNTIME]: AgentRuntimeState;
63
- /**
64
- * Schedule a background task that continues after the response is sent.
65
- * Useful for cleanup, logging, or async operations that don't block the response.
66
- *
67
- * @param promise - Promise or function that returns void or Promise<void>
68
- *
69
- * @example
70
- * ```typescript
71
- * ctx.waitUntil(async () => {
72
- * await ctx.kv.set('processed', Date.now());
73
- * ctx.logger.info('Background task complete');
74
- * });
75
- * ```
76
- */
77
- waitUntil: (promise: Promise<void> | (() => void | Promise<void>)) => void;
78
- /**
79
- * Structured logger with OpenTelemetry integration.
80
- * Logs are automatically correlated with traces.
81
- *
82
- * @example
83
- * ```typescript
84
- * ctx.logger.info('Processing started', { userId: input.id });
85
- * ctx.logger.warn('Rate limit approaching', { remaining: 10 });
86
- * ctx.logger.error('Operation failed', { error: err.message });
87
- * ```
88
- */
89
- logger: Logger;
90
- /**
91
- * Unique session identifier for this request. Consistent across agent calls in the same session.
92
- */
93
- sessionId: string;
94
- /**
95
- * OpenTelemetry tracer for creating custom spans and tracking performance.
96
- *
97
- * @example
98
- * ```typescript
99
- * const span = ctx.tracer.startSpan('database-query');
100
- * try {
101
- * const result = await database.query();
102
- * span.setStatus({ code: SpanStatusCode.OK });
103
- * return result;
104
- * } finally {
105
- * span.end();
106
- * }
107
- * ```
108
- */
109
- tracer: Tracer;
110
- /**
111
- * Key-value storage for simple data persistence.
112
- *
113
- * @example
114
- * ```typescript
115
- * await ctx.kv.set('user:123', { name: 'Alice', age: 30 });
116
- * const user = await ctx.kv.get('user:123');
117
- * await ctx.kv.delete('user:123');
118
- * const keys = await ctx.kv.list('user:*');
119
- * ```
120
- */
121
- kv: KeyValueStorage;
122
- /**
123
- * Stream storage for real-time data streams and logs.
124
- *
125
- * @example
126
- * ```typescript
127
- * const stream = await ctx.stream.create('agent-logs');
128
- * await ctx.stream.write(stream.id, 'Processing step 1');
129
- * await ctx.stream.write(stream.id, 'Processing step 2');
130
- * ```
131
- */
132
- stream: StreamStorage;
133
- /**
134
- * Vector storage for embeddings and similarity search.
135
- *
136
- * @example
137
- * ```typescript
138
- * await ctx.vector.upsert('docs', [
139
- * { id: '1', values: [0.1, 0.2, 0.3], metadata: { text: 'Hello' } }
140
- * ]);
141
- * const results = await ctx.vector.query('docs', [0.1, 0.2, 0.3], { topK: 5 });
142
- * ```
143
- */
144
- vector: VectorStorage;
145
- /**
146
- * Sandbox service for creating and running isolated code execution environments.
147
- *
148
- * @example
149
- * ```typescript
150
- * // One-shot execution
151
- * const result = await ctx.sandbox.run({
152
- * command: {
153
- * exec: ['bun', 'run', 'index.ts'],
154
- * files: [{ path: 'index.ts', content: Buffer.from('console.log("hello")') }]
155
- * }
156
- * });
157
- * console.log('Exit:', result.exitCode);
158
- *
159
- * // Interactive sandbox
160
- * const sandbox = await ctx.sandbox.create({
161
- * resources: { memory: '1Gi', cpu: '1000m' }
162
- * });
163
- * await sandbox.execute({ command: ['bun', 'init'] });
164
- * await sandbox.execute({ command: ['bun', 'add', 'zod'] });
165
- * await sandbox.destroy();
166
- * ```
167
- */
168
- sandbox: SandboxService;
169
- /**
170
- * In-memory state storage scoped to the current request.
171
- * Use for passing data between middleware and handlers.
172
- *
173
- * @example
174
- * ```typescript
175
- * ctx.state.set('startTime', Date.now());
176
- * const duration = Date.now() - (ctx.state.get('startTime') as number);
177
- * ```
178
- */
179
- state: Map<string, unknown>;
180
- /**
181
- * Thread information for multi-turn conversations.
182
- */
183
- thread: Thread;
184
- /**
185
- * Session information for the current request.
186
- */
187
- session: Session;
188
- /**
189
- * Agent-specific configuration returned from the setup function.
190
- * Type is inferred from your setup function's return value.
191
- *
192
- * @example
193
- * ```typescript
194
- * createAgent({
195
- * setup: async () => ({ cache: new Map(), db: await connectDB() }),
196
- * handler: async (ctx, input) => {
197
- * ctx.config.cache.set('key', 'value'); // Strongly typed!
198
- * await ctx.config.db.query('SELECT * FROM users');
199
- * }
200
- * });
201
- * ```
202
- */
203
- config: TConfig;
204
- /**
205
- * Application-wide state returned from createApp setup function.
206
- * Shared across all agents in the application.
207
- *
208
- * @example
209
- * ```typescript
210
- * const app = createApp({
211
- * setup: async () => ({ db: await connectDB(), redis: await connectRedis() })
212
- * });
213
- *
214
- * // Later in any agent:
215
- * handler: async (ctx, input) => {
216
- * await ctx.app.db.query('SELECT 1');
217
- * await ctx.app.redis.set('key', 'value');
218
- * }
219
- * ```
220
- */
221
- app: TAppState;
222
- /**
223
- * Metadata about the currently executing agent.
224
- * Provides access to the agent's id, name, and other properties.
225
- *
226
- * @example
227
- * ```typescript
228
- * handler: async (ctx, input) => {
229
- * // Use agent ID for namespaced state keys
230
- * const stateKey = `${ctx.current.id}_counter`;
231
- * await ctx.thread.state.set(stateKey, value);
232
- *
233
- * // Log agent info
234
- * ctx.logger.info('Running agent', { name: ctx.current.name });
235
- * }
236
- * ```
237
- */
238
- current: AgentMetadata;
239
- /**
240
- * Authentication context when request is authenticated.
241
- * Available when auth middleware is configured on the Hono app.
242
- *
243
- * Will be `null` for:
244
- * - Unauthenticated requests
245
- * - Cron jobs
246
- * - Agent-to-agent calls without auth propagation
247
- *
248
- * @example
249
- * ```typescript
250
- * handler: async (ctx, input) => {
251
- * if (!ctx.auth) {
252
- * return { error: 'Please sign in' };
253
- * }
254
- *
255
- * // Access user info
256
- * const user = await ctx.auth.getUser();
257
- * ctx.logger.info(`Request from ${user.email}`);
258
- *
259
- * // Check organization role
260
- * if (await ctx.auth.hasOrgRole('admin')) {
261
- * // Admin-only logic
262
- * }
263
- *
264
- * return { userId: user.id };
265
- * }
266
- * ```
267
- */
268
- auth: import('@agentuity/auth').AuthInterface | null;
269
- }
270
- type InternalAgentMetadata = {
271
- /**
272
- * the unique name for the agent (user-provided).
273
- */
274
- name: string;
275
- /**
276
- * the unique identifier for this project, agent and deployment.
277
- */
278
- id: string;
279
- /**
280
- * the unique identifier for this agent across multiple deployments
281
- */
282
- agentId: string;
283
- /**
284
- * the relative path to the agent from the root project directory.
285
- */
286
- filename: string;
287
- /**
288
- * a unique version for the agent. computed as the SHA256 contents of the file.
289
- */
290
- version: string;
291
- /**
292
- * the source code for the input schema.
293
- */
294
- inputSchemaCode?: string;
295
- /**
296
- * the source code for the output schema.
297
- */
298
- outputSchemaCode?: string;
299
- };
300
- type ExternalAgentMetadata = {
301
- /**
302
- * the human readable description for the agent
303
- */
304
- description?: string;
305
- };
306
- export type AgentMetadata = InternalAgentMetadata & ExternalAgentMetadata;
307
- /**
308
- * Configuration object for creating an agent evaluation function.
309
- *
310
- * @template TInput - Input schema type from the agent
311
- * @template TOutput - Output schema type from the agent
312
- */
313
- export interface CreateEvalConfig<TInput extends StandardSchemaV1 | undefined = any, TOutput extends StandardSchemaV1 | undefined = any> {
314
- /**
315
- * Optional description of what this evaluation does.
316
- *
317
- * @example
318
- * ```typescript
319
- * description: 'Ensures output is greater than zero'
320
- * ```
321
- */
322
- description?: string;
323
- /**
324
- * Evaluation handler function that tests the agent's behavior.
325
- * Return true if the evaluation passes, false if it fails.
326
- *
327
- * @param run - Evaluation run context containing input and metadata
328
- * @param result - The output from the agent handler
329
- * @returns Boolean indicating pass/fail, or evaluation result object
330
- *
331
- * @example
332
- * ```typescript
333
- * handler: async (run, result) => {
334
- * // Assert that output is positive
335
- * if (result <= 0) {
336
- * return false; // Evaluation failed
337
- * }
338
- * return true; // Evaluation passed
339
- * }
340
- * ```
341
- *
342
- * @example
343
- * ```typescript
344
- * // With detailed result
345
- * handler: async (run, result) => {
346
- * const passed = result.length > 5;
347
- * return {
348
- * passed,
349
- * score: passed ? 1.0 : 0.0,
350
- * message: passed ? 'Output length is valid' : 'Output too short'
351
- * };
352
- * }
353
- * ```
354
- */
355
- handler: EvalFunction<TInput extends StandardSchemaV1 ? InferOutput<TInput> : undefined, TOutput extends StandardSchemaV1 ? InferOutput<TOutput> : undefined>;
356
- }
357
- export type PresetEvalConfig<TInput extends StandardSchemaV1 | undefined = any, TOutput extends StandardSchemaV1 | undefined = any> = CreateEvalConfig<TInput, TOutput> & {
358
- name: string;
359
- };
360
- type CreateEvalMethod<TInput extends StandardSchemaV1 | undefined = any, TOutput extends StandardSchemaV1 | undefined = any> = {
361
- (config: PresetEvalConfig<TInput, TOutput>): Eval<TInput, TOutput>;
362
- (name: string, config: CreateEvalConfig<TInput, TOutput>): Eval<TInput, TOutput>;
363
- };
364
- /**
365
- * Validator function type with method overloads for different validation scenarios.
366
- * Provides type-safe validation middleware that integrates with Hono's type system.
367
- *
368
- * This validator automatically validates incoming JSON request bodies using StandardSchema-compatible
369
- * schemas (Zod, Valibot, ArkType, etc.) and provides full TypeScript type inference for validated data
370
- * accessible via `c.req.valid('json')`.
371
- *
372
- * The validator returns 400 Bad Request with validation error details if validation fails.
373
- *
374
- * @template TInput - Agent's input schema type (StandardSchemaV1 or undefined)
375
- * @template _TOutput - Agent's output schema type (reserved for future output validation)
376
- *
377
- * @example Basic usage with agent's schema
378
- * ```typescript
379
- * router.post('/', agent.validator(), async (c) => {
380
- * const data = c.req.valid('json'); // Fully typed from agent's input schema
381
- * return c.json(data);
382
- * });
383
- * ```
384
- *
385
- * @example Override with custom input schema
386
- * ```typescript
387
- * router.post('/custom', agent.validator({ input: z.object({ id: z.string() }) }), async (c) => {
388
- * const data = c.req.valid('json'); // Typed as { id: string }
389
- * return c.json(data);
390
- * });
391
- * ```
392
- */
393
- export interface AgentValidator<TInput extends StandardSchemaV1 | undefined, _TOutput extends StandardSchemaV1 | undefined> {
394
- /**
395
- * Validates using the agent's input schema (no override).
396
- * Returns Hono middleware handler that validates JSON request body.
397
- *
398
- * @returns Middleware handler with type inference for validated data
399
- *
400
- * @example
401
- * ```typescript
402
- * // Agent has schema: { input: z.object({ name: z.string() }) }
403
- * router.post('/', agent.validator(), async (c) => {
404
- * const data = c.req.valid('json'); // { name: string }
405
- * return c.json({ received: data.name });
406
- * });
407
- * ```
408
- */
409
- (): TInput extends StandardSchemaV1 ? Handler<any, any, {
410
- in: {};
411
- out: {
412
- json: InferInput<TInput>;
413
- };
414
- }> : Handler<any, any, any>;
415
- /**
416
- * Output-only validation override.
417
- * Validates only the response body (no input validation).
418
- *
419
- * Useful for GET routes or routes where input validation is handled elsewhere.
420
- * The middleware validates the JSON response body and throws 500 Internal Server Error
421
- * if validation fails.
422
- *
423
- * @template TOverrideOutput - Custom output schema type
424
- * @param override - Object containing output schema
425
- * @returns Middleware handler that validates response output
426
- *
427
- * @example GET route with output validation
428
- * ```typescript
429
- * router.get('/', agent.validator({ output: z.array(z.object({ id: z.string() })) }), async (c) => {
430
- * // Returns array of objects - validated against schema
431
- * return c.json([{ id: '123' }, { id: '456' }]);
432
- * });
433
- * ```
434
- */
435
- <TOverrideOutput extends StandardSchemaV1>(override: {
436
- output: TOverrideOutput;
437
- }): Handler<any, any, {
438
- in: {};
439
- out: {
440
- json: InferOutput<TOverrideOutput>;
441
- };
442
- }>;
443
- /**
444
- * Validates with custom input and optional output schemas (POST/PUT/PATCH/DELETE).
445
- * Overrides the agent's schema for this specific route.
446
- *
447
- * @template TOverrideInput - Custom input schema type
448
- * @template TOverrideOutput - Optional custom output schema type
449
- * @param override - Object containing input (required) and output (optional) schemas
450
- * @returns Middleware handler with type inference from custom schemas
451
- *
452
- * @example Custom input schema
453
- * ```typescript
454
- * router.post('/users', agent.validator({
455
- * input: z.object({ email: z.string().email(), name: z.string() })
456
- * }), async (c) => {
457
- * const data = c.req.valid('json'); // { email: string, name: string }
458
- * return c.json({ id: '123', ...data });
459
- * });
460
- * ```
461
- *
462
- * @example Custom input and output schemas
463
- * ```typescript
464
- * router.post('/convert', agent.validator({
465
- * input: z.string(),
466
- * output: z.number()
467
- * }), async (c) => {
468
- * const data = c.req.valid('json'); // string
469
- * return c.json(123);
470
- * });
471
- * ```
472
- */
473
- <TOverrideInput extends StandardSchemaV1, TOverrideOutput extends StandardSchemaV1 | undefined = undefined>(override: {
474
- input: TOverrideInput;
475
- output?: TOverrideOutput;
476
- }): Handler<any, any, {
477
- in: {};
478
- out: {
479
- json: InferInput<TOverrideInput>;
480
- };
481
- }>;
482
- }
483
- /**
484
- * Agent instance type returned by createAgent().
485
- * Represents a fully configured agent with metadata, handler, lifecycle hooks, and event listeners.
486
- *
487
- * @template TInput - Input schema type (StandardSchemaV1 or undefined)
488
- * @template TOutput - Output schema type (StandardSchemaV1 or undefined)
489
- * @template TStream - Whether the agent returns a stream (true/false)
490
- * @template TConfig - Agent-specific configuration type from setup function
491
- * @template TAppState - Application state type from createApp
492
- *
493
- * @example
494
- * ```typescript
495
- * const agent = createAgent({
496
- * metadata: { name: 'My Agent' },
497
- * schema: { input: z.string(), output: z.number() },
498
- * handler: async (ctx, input) => input.length
499
- * });
500
- *
501
- * // Access agent properties
502
- * console.log(agent.metadata.name); // "My Agent"
503
- *
504
- * // Add event listeners
505
- * agent.addEventListener('started', (eventName, agent, ctx) => {
506
- * console.log('Agent started:', ctx.sessionId);
507
- * });
508
- *
509
- * // Create evals for testing
510
- * const eval1 = agent.createEval('check-positive', {
511
- * description: 'Ensures result is greater than 5',
512
- * handler: async (run, result) => {
513
- * return result > 5; // Assert output is greater than 5
514
- * }
515
- * });
516
- * ```
517
- */
518
- export type Agent<TInput extends StandardSchemaV1 | undefined = any, TOutput extends StandardSchemaV1 | undefined = any, TStream extends boolean = false, TConfig = unknown, TAppState = Record<string, never>> = {
519
- /**
520
- * Agent metadata including name, description, id, version, and filename.
521
- */
522
- metadata: AgentMetadata;
523
- /**
524
- * The main handler function that processes agent requests.
525
- * Gets AgentContext from AsyncLocalStorage, receives validated input, returns output or stream.
526
- */
527
- handler: (...args: any[]) => any | Promise<any>;
528
- /**
529
- * Creates a type-safe validation middleware for routes using StandardSchema validation.
530
- *
531
- * This method validates incoming JSON request bodies against the agent's **input schema**
532
- * and optionally validates outgoing JSON responses against the **output schema**.
533
- * Provides full TypeScript type inference for validated input data accessible via `c.req.valid('json')`.
534
- *
535
- * **Validation behavior:**
536
- * - **Input**: Validates request JSON body, returns 400 Bad Request on failure
537
- * - **Output**: Validates response JSON body (if output schema provided), throws 500 on failure
538
- * - Passes validated input data to handler via `c.req.valid('json')`
539
- * - Full TypeScript type inference for validated input data
540
- *
541
- * **Supported schema libraries:**
542
- * - Zod (z.object, z.string, etc.)
543
- * - Valibot (v.object, v.string, etc.)
544
- * - ArkType (type({ ... }))
545
- * - Any StandardSchema-compatible library
546
- *
547
- * **Method overloads:**
548
- * - `agent.validator()` - Validates using agent's input/output schemas
549
- * - `agent.validator({ output: schema })` - Output-only validation (no input validation)
550
- * - `agent.validator({ input: schema })` - Custom input schema override (skips agent's output validation)
551
- * - `agent.validator({ input: schema, output: schema })` - Both input and output validated
552
- *
553
- * @returns Hono middleware handler with proper type inference
554
- *
555
- * @example Automatic validation using agent's schema
556
- * ```typescript
557
- * // Agent defined with: schema: { input: z.object({ name: z.string(), age: z.number() }) }
558
- * router.post('/', agent.validator(), async (c) => {
559
- * const data = c.req.valid('json'); // Fully typed: { name: string, age: number }
560
- * return c.json({ greeting: `Hello ${data.name}, age ${data.age}` });
561
- * });
562
- * ```
563
- *
564
- * @example Override with custom schema per-route
565
- * ```typescript
566
- * router.post('/email', agent.validator({
567
- * input: z.object({ email: z.string().email() })
568
- * }), async (c) => {
569
- * const data = c.req.valid('json'); // Typed as { email: string }
570
- * return c.json({ sent: data.email });
571
- * });
572
- * ```
573
- *
574
- * @example Works with any StandardSchema library
575
- * ```typescript
576
- * import * as v from 'valibot';
577
- *
578
- * router.post('/valibot', agent.validator({
579
- * input: v.object({ count: v.number() })
580
- * }), async (c) => {
581
- * const data = c.req.valid('json'); // Typed correctly
582
- * return c.json({ count: data.count });
583
- * });
584
- * ```
585
- *
586
- * @example Validation error response (400)
587
- * ```typescript
588
- * // Request: { "name": "Bob" } (missing 'age')
589
- * // Response: {
590
- * // "error": "Validation failed",
591
- * // "message": "age: Invalid input: expected number, received undefined",
592
- * // "issues": [{ "message": "...", "path": ["age"] }]
593
- * // }
594
- * ```
595
- */
596
- validator: AgentValidator<TInput, TOutput>;
597
- /**
598
- * Array of evaluation functions created via agent.createEval().
599
- * Used for testing and validating agent behavior.
600
- */
601
- evals?: Eval[];
602
- /**
603
- * Create an evaluation function for testing this agent.
604
- * Evals can assert correctness of agent input/output during test runs.
605
- *
606
- * @param config - Eval configuration
607
- * @param config.metadata - Optional eval metadata (name, description)
608
- * @param config.handler - Eval handler function receiving run context and result
609
- *
610
- * @example
611
- * ```typescript
612
- * const agent = createAgent({
613
- * schema: { input: z.string(), output: z.number() },
614
- * handler: async (ctx, input) => input.length
615
- * });
616
- *
617
- * // Create eval to validate output
618
- * agent.createEval('check-positive', {
619
- * description: 'Ensures output is a positive number',
620
- * handler: async (run, result) => {
621
- * return result > 0; // Assert output is positive
622
- * }
623
- * });
624
- * ```
625
- */
626
- createEval: CreateEvalMethod<TInput, TOutput>;
627
- /**
628
- * Optional setup function called once when app starts.
629
- * Returns agent-specific configuration available via ctx.config.
630
- */
631
- setup?: (app: TAppState) => Promise<TConfig> | TConfig;
632
- /**
633
- * Optional shutdown function called when app stops.
634
- * Receives app state and agent config for cleanup.
635
- */
636
- shutdown?: (app: TAppState, config: TConfig) => Promise<void> | void;
637
- /**
638
- * Register an event listener for when the agent starts execution.
639
- *
640
- * @param eventName - Must be 'started'
641
- * @param callback - Function called when agent execution begins
642
- *
643
- * @example
644
- * ```typescript
645
- * agent.addEventListener('started', (eventName, agent, ctx) => {
646
- * console.log(`${agent.metadata.name} started at ${new Date()}`);
647
- * });
648
- * ```
649
- */
650
- addEventListener(eventName: 'started', callback: (eventName: 'started', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>) => Promise<void> | void): void;
651
- /**
652
- * Register an event listener for when the agent completes successfully.
653
- *
654
- * @param eventName - Must be 'completed'
655
- * @param callback - Function called when agent execution completes
656
- *
657
- * @example
658
- * ```typescript
659
- * agent.addEventListener('completed', (eventName, agent, ctx) => {
660
- * console.log(`${agent.metadata.name} completed successfully`);
661
- * });
662
- * ```
663
- */
664
- addEventListener(eventName: 'completed', callback: (eventName: 'completed', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>) => Promise<void> | void): void;
665
- /**
666
- * Register an event listener for when the agent throws an error.
667
- *
668
- * @param eventName - Must be 'errored'
669
- * @param callback - Function called when agent execution fails
670
- *
671
- * @example
672
- * ```typescript
673
- * agent.addEventListener('errored', (eventName, agent, ctx, error) => {
674
- * console.error(`${agent.metadata.name} failed:`, error.message);
675
- * });
676
- * ```
677
- */
678
- addEventListener(eventName: 'errored', callback: (eventName: 'errored', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>, data: Error) => Promise<void> | void): void;
679
- /**
680
- * Remove a previously registered 'started' event listener.
681
- *
682
- * @param eventName - Must be 'started'
683
- * @param callback - The callback function to remove
684
- */
685
- removeEventListener(eventName: 'started', callback: (eventName: 'started', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>) => Promise<void> | void): void;
686
- /**
687
- * Remove a previously registered 'completed' event listener.
688
- *
689
- * @param eventName - Must be 'completed'
690
- * @param callback - The callback function to remove
691
- */
692
- removeEventListener(eventName: 'completed', callback: (eventName: 'completed', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>) => Promise<void> | void): void;
693
- /**
694
- * Remove a previously registered 'errored' event listener.
695
- *
696
- * @param eventName - Must be 'errored'
697
- * @param callback - The callback function to remove
698
- */
699
- removeEventListener(eventName: 'errored', callback: (eventName: 'errored', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>, data: Error) => Promise<void> | void): void;
700
- } & (TInput extends StandardSchemaV1 ? {
701
- inputSchema: TInput;
702
- } : {
703
- inputSchema?: never;
704
- }) & (TOutput extends StandardSchemaV1 ? {
705
- outputSchema: TOutput;
706
- } : {
707
- outputSchema?: never;
708
- }) & (TStream extends true ? {
709
- stream: true;
710
- } : {
711
- stream?: false;
712
- });
713
- type InferSchemaInput<T> = T extends StandardSchemaV1 ? InferOutput<T> : never;
714
- type InferStreamOutput<TOutput, TStream extends boolean> = TStream extends true ? TOutput extends StandardSchemaV1 ? ReadableStream<InferOutput<TOutput>> : ReadableStream<unknown> : TOutput extends StandardSchemaV1 ? InferOutput<TOutput> : void;
715
- type SchemaInput<TSchema> = TSchema extends {
716
- input: infer I;
717
- } ? I : undefined;
718
- type SchemaOutput<TSchema> = TSchema extends {
719
- output: infer O;
720
- } ? O : undefined;
721
- type SchemaStream<TSchema> = TSchema extends {
722
- stream: infer S;
723
- } ? S extends boolean ? S : false : false;
724
- type SchemaHandlerReturn<TSchema> = SchemaStream<TSchema> extends true ? SchemaOutput<TSchema> extends StandardSchemaV1 ? ReadableStream<InferOutput<SchemaOutput<TSchema>>> : ReadableStream<unknown> : SchemaOutput<TSchema> extends StandardSchemaV1 ? InferOutput<SchemaOutput<TSchema>> : void;
725
- type AgentHandlerFromConfig<TSchema, TSetupReturn, TAppState = AppState> = SchemaInput<TSchema> extends infer I ? I extends StandardSchemaV1 ? (ctx: AgentContext<any, TSetupReturn, TAppState>, input: InferOutput<I>) => Promise<SchemaHandlerReturn<TSchema>> | SchemaHandlerReturn<TSchema> : (ctx: AgentContext<any, TSetupReturn, TAppState>) => Promise<SchemaHandlerReturn<TSchema>> | SchemaHandlerReturn<TSchema> : (ctx: AgentContext<any, TSetupReturn, TAppState>) => Promise<SchemaHandlerReturn<TSchema>> | SchemaHandlerReturn<TSchema>;
726
- /**
727
- * Configuration object for creating an agent with automatic type inference.
728
- *
729
- * Passed as the second parameter to createAgent(name, config).
730
- *
731
- * @template TSchema - Schema definition object containing optional input, output, and stream properties
732
- * @template TConfig - Function type that returns agent-specific configuration from setup
733
- *
734
- * @example
735
- * ```typescript
736
- * const agent = createAgent('greeting', {
737
- * description: 'Generates personalized greetings',
738
- * schema: {
739
- * input: z.object({ name: z.string(), age: z.number() }),
740
- * output: z.string()
741
- * },
742
- * handler: async (ctx, { name, age }) => {
743
- * return `Hello, ${name}! You are ${age} years old.`;
744
- * }
745
- * });
746
- * ```
747
- */
748
- export interface CreateAgentConfig<TSchema extends {
749
- input?: StandardSchemaV1;
750
- output?: StandardSchemaV1;
751
- stream?: boolean;
752
- } | undefined = undefined, TConfig extends (app: AppState) => any = any> {
753
- /**
754
- * Optional schema validation using Zod or any StandardSchemaV1 compatible library.
755
- *
756
- * @example
757
- * ```typescript
758
- * schema: {
759
- * input: z.object({ name: z.string(), age: z.number() }),
760
- * output: z.string(),
761
- * stream: false
762
- * }
763
- * ```
764
- */
765
- schema?: TSchema;
766
- /**
767
- * Optional description of what this agent does, visible in the Agentuity platform.
768
- *
769
- * @example
770
- * ```typescript
771
- * description: 'Returns personalized greetings'
772
- * ```
773
- */
774
- description?: string;
775
- /**
776
- * Optional metadata object (typically injected by build plugin during compilation).
777
- * Contains agent identification and versioning information.
778
- *
779
- * @internal - Usually populated by build tooling, not manually set
780
- */
781
- metadata?: Partial<AgentMetadata>;
782
- /**
783
- * Optional async function called once on app startup to initialize agent-specific resources.
784
- * The returned value is available in the handler via `ctx.config`.
785
- *
786
- * @param app - Application state from createApp setup function
787
- * @returns Agent-specific configuration object
788
- *
789
- * @example
790
- * ```typescript
791
- * setup: async (app) => {
792
- * const cache = new Map();
793
- * const db = await connectDB();
794
- * return { cache, db };
795
- * }
796
- * ```
797
- */
798
- setup?: TConfig;
799
- /**
800
- * The main agent logic that processes requests.
801
- * Receives AgentContext and validated input (if schema.input is defined), returns output or stream.
802
- *
803
- * @param ctx - Agent context with logger, storage, and other runtime services
804
- * @param input - Validated input (only present if schema.input is defined)
805
- * @returns Output matching schema.output type, or ReadableStream if schema.stream is true
806
- *
807
- * @example
808
- * ```typescript
809
- * handler: async (ctx, { name, age }) => {
810
- * ctx.logger.info(`Processing for ${name}`);
811
- * await ctx.kv.set('lastUser', name);
812
- * return `Hello, ${name}! You are ${age} years old.`;
813
- * }
814
- * ```
815
- */
816
- handler: AgentHandlerFromConfig<TSchema, TConfig extends (app: AppState) => infer R ? Awaited<R> : undefined, AppState>;
817
- /**
818
- * Optional async cleanup function called on app shutdown.
819
- * Use this to close connections, flush buffers, etc.
820
- *
821
- * @param app - Application state from createApp
822
- * @param config - Agent config returned from setup function
823
- *
824
- * @example
825
- * ```typescript
826
- * shutdown: async (app, config) => {
827
- * await config.db.close();
828
- * config.cache.clear();
829
- * }
830
- * ```
831
- */
832
- shutdown?: (app: AppState, config: TConfig extends (app: AppState) => infer R ? Awaited<R> : undefined) => Promise<void> | void;
833
- }
834
- /**
835
- * The public interface returned by createAgent().
836
- * Provides methods to run the agent, create evaluations, and manage event listeners.
837
- *
838
- * @template TInput - Input schema type (StandardSchemaV1 or undefined if no input)
839
- * @template TOutput - Output schema type (StandardSchemaV1 or undefined if no output)
840
- * @template TStream - Whether the agent returns a stream (true/false)
841
- *
842
- * @example
843
- * ```typescript
844
- * const agent = createAgent('greeting', {
845
- * schema: {
846
- * input: z.object({ name: z.string() }),
847
- * output: z.string()
848
- * },
849
- * handler: async (ctx, { name }) => `Hello, ${name}!`
850
- * });
851
- *
852
- * // Run the agent
853
- * const result = await agent.run({ name: 'Alice' });
854
- *
855
- * // Create evaluation
856
- * const evalDef = agent.createEval('greeting-accuracy', {
857
- * description: 'Checks if greeting includes the user name',
858
- * handler: async (ctx, input, output) => {
859
- * return { score: output.includes(input.name) ? 1 : 0 };
860
- * }
861
- * });
862
- *
863
- * // Listen to events
864
- * agent.addEventListener('completed', async (eventName, agent, context) => {
865
- * console.log('Agent completed successfully');
866
- * });
867
- * ```
868
- */
869
- export interface AgentRunner<TInput extends StandardSchemaV1 | undefined = any, TOutput extends StandardSchemaV1 | undefined = any, TStream extends boolean = false> {
870
- /** Agent metadata (id, name, description, etc.) */
871
- metadata: AgentMetadata;
872
- /**
873
- * Execute the agent with validated input.
874
- * If agent has no input schema, call with no arguments.
875
- * If agent has input schema, pass validated input object.
876
- *
877
- * @example
878
- * ```typescript
879
- * // Agent with input
880
- * const result = await agent.run({ name: 'Alice' });
881
- *
882
- * // Agent without input
883
- * const result = await agent.run();
884
- * ```
885
- */
886
- run: undefined extends TInput ? () => Promise<InferStreamOutput<Exclude<TOutput, undefined>, TStream>> : (input: InferSchemaInput<Exclude<TInput, undefined>>) => Promise<InferStreamOutput<Exclude<TOutput, undefined>, TStream>>;
887
- /**
888
- * Create Hono validator middleware for this agent.
889
- * Automatically validates request input against the agent's schema.
890
- *
891
- * @example
892
- * ```typescript
893
- * import myAgent from './my-agent';
894
- * router.post('/', myAgent.validator(), async (c) => {
895
- * const data = c.req.valid('json'); // Fully typed!
896
- * return c.json(await myAgent.run(data));
897
- * });
898
- * ```
899
- */
900
- validator: AgentValidator<TInput, TOutput>;
901
- /** Input schema (if defined) */
902
- inputSchema?: TInput;
903
- /** Output schema (if defined) */
904
- outputSchema?: TOutput;
905
- /** Whether agent returns a stream */
906
- stream?: TStream;
907
- /**
908
- * Create an evaluation for this agent.
909
- * Evaluations run automatically after the agent completes.
910
- *
911
- * @example
912
- * ```typescript
913
- * const accuracyEval = agent.createEval('accuracy', {
914
- * description: 'Validates output length is non-zero',
915
- * handler: async (ctx, input, output) => ({
916
- * score: output.length > 0 ? 1 : 0,
917
- * metadata: { outputLength: output.length }
918
- * })
919
- * });
920
- * ```
921
- */
922
- createEval: CreateEvalMethod<TInput, TOutput>;
923
- /**
924
- * Add event listener for 'started' or 'completed' events.
925
- * Listeners fire sequentially in the order they were added.
926
- *
927
- * @param eventName - 'started' or 'completed'
928
- * @param callback - Function to call when event fires
929
- *
930
- * @example
931
- * ```typescript
932
- * agent.addEventListener('started', async (eventName, agent, context) => {
933
- * context.logger.info('Agent execution started');
934
- * });
935
- * ```
936
- */
937
- addEventListener(eventName: 'started' | 'completed', callback: (eventName: 'started' | 'completed', agent: Agent<TInput, TOutput, TStream, any, any>, context: AgentContext<any, any, any>) => Promise<void> | void): void;
938
- /**
939
- * Add event listener for 'errored' event.
940
- * Fires when agent handler throws an error.
941
- *
942
- * @param eventName - 'errored'
943
- * @param callback - Function to call when error occurs
944
- *
945
- * @example
946
- * ```typescript
947
- * agent.addEventListener('errored', async (eventName, agent, context, error) => {
948
- * context.logger.error('Agent failed', { error: error.message });
949
- * });
950
- * ```
951
- */
952
- addEventListener(eventName: 'errored', callback: (eventName: 'errored', agent: Agent<TInput, TOutput, TStream, any, any>, context: AgentContext<any, any, any>, error: Error) => Promise<void> | void): void;
953
- /**
954
- * Remove event listener for 'started' or 'completed' events.
955
- *
956
- * @param eventName - 'started' or 'completed'
957
- * @param callback - The same callback function that was added
958
- */
959
- removeEventListener(eventName: 'started' | 'completed', callback: (eventName: 'started' | 'completed', agent: Agent<TInput, TOutput, TStream, any, any>, context: AgentContext<any, any, any>) => Promise<void> | void): void;
960
- /**
961
- * Remove event listener for 'errored' event.
962
- *
963
- * @param eventName - 'errored'
964
- * @param callback - The same callback function that was added
965
- */
966
- removeEventListener(eventName: 'errored', callback: (eventName: 'errored', agent: Agent<TInput, TOutput, TStream, any, any>, context: AgentContext<any, any, any>, error: Error) => Promise<void> | void): void;
967
- }
968
- /**
969
- * Get the global runtime state (for production use).
970
- * In tests, use TestAgentContext which has isolated runtime state.
971
- */
972
- export declare function getGlobalRuntimeState(): AgentRuntimeState;
973
- /**
974
- * Get the runtime state from an AgentContext.
975
- * @internal
976
- */
977
- export declare function getAgentRuntime(ctx: AgentContext<any, any, any>): AgentRuntimeState;
978
- /**
979
- * Union type of all registered agent names.
980
- * Falls back to `string` when no agents are registered (before augmentation).
981
- * After augmentation, this becomes a strict union of agent names for full type safety.
982
- */
983
- export type AgentName = keyof AgentRegistry extends never ? string : keyof AgentRegistry;
984
- /**
985
- * Agent registry interface.
986
- * This interface is augmented by generated code to provide strongly-typed agent access.
987
- */
988
- export interface AgentRegistry {
989
- }
990
- export declare const registerAgent: (name: AgentName, agent: Agent<any, any, any, any, any>) => void;
991
- export declare const setAgentConfig: (name: AgentName, config: unknown) => void;
992
- export declare const getAgentConfig: (name: AgentName) => unknown;
993
- /**
994
- * Configuration object for creating an agent with explicit type parameters.
995
- *
996
- * @template TInput - Input schema type (StandardSchemaV1 or undefined)
997
- * @template TOutput - Output schema type (StandardSchemaV1 or undefined)
998
- * @template TStream - Whether agent returns a stream (true/false)
999
- * @template TConfig - Type returned by setup function
1000
- * @template TAppState - Custom app state type from createApp
1001
- */
1002
- export interface CreateAgentConfigExplicit<TInput extends StandardSchemaV1 | undefined = undefined, TOutput extends StandardSchemaV1 | undefined = undefined, TStream extends boolean = false, TConfig = unknown, TAppState = AppState> {
1003
- /**
1004
- * Optional schema validation.
1005
- *
1006
- * @example
1007
- * ```typescript
1008
- * schema: {
1009
- * input: z.object({ name: z.string() }),
1010
- * output: z.string(),
1011
- * stream: false,
1012
- * }
1013
- * ```
1014
- */
1015
- schema?: {
1016
- /** Input validation schema */
1017
- input?: TInput;
1018
- /** Output validation schema */
1019
- output?: TOutput;
1020
- /** Whether the agent returns a ReadableStream */
1021
- stream?: TStream;
1022
- };
1023
- /**
1024
- * Optional description of what this agent does.
1025
- *
1026
- * @example
1027
- * ```typescript
1028
- * description: 'Does something useful'
1029
- * ```
1030
- */
1031
- description?: string;
1032
- /**
1033
- * Optional metadata object (typically injected by build plugin during compilation).
1034
- * Contains agent identification and versioning information.
1035
- *
1036
- * @internal - Usually populated by build tooling, not manually set
1037
- */
1038
- metadata?: Partial<AgentMetadata>;
1039
- /**
1040
- * Optional setup function receiving app state, returns agent config.
1041
- * The returned value is available in the handler via `ctx.config`.
1042
- *
1043
- * @param app - Application state from createApp
1044
- * @returns Agent-specific configuration
1045
- *
1046
- * @example
1047
- * ```typescript
1048
- * setup: async (app) => ({ cache: new Map() })
1049
- * ```
1050
- */
1051
- setup?: (app: TAppState) => Promise<TConfig> | TConfig;
1052
- /**
1053
- * Optional cleanup function called on app shutdown.
1054
- *
1055
- * @param app - Application state from createApp
1056
- * @param config - Agent config returned from setup
1057
- *
1058
- * @example
1059
- * ```typescript
1060
- * shutdown: async (app, config) => {
1061
- * config.cache.clear();
1062
- * }
1063
- * ```
1064
- */
1065
- shutdown?: (app: TAppState, config: TConfig) => Promise<void> | void;
1066
- /**
1067
- * Agent handler function.
1068
- * Type is automatically inferred based on schema definitions.
1069
- *
1070
- * @param ctx - Agent context
1071
- * @param input - Validated input (only present if schema.input is defined)
1072
- * @returns Output or ReadableStream based on schema
1073
- *
1074
- * @example
1075
- * ```typescript
1076
- * handler: async (ctx, input) => {
1077
- * return `Hello, ${input.name}!`;
1078
- * }
1079
- * ```
1080
- */
1081
- handler: TInput extends StandardSchemaV1 ? TStream extends true ? TOutput extends StandardSchemaV1 ? (c: AgentContext<any, TConfig, TAppState>, input: InferOutput<TInput>) => Promise<ReadableStream<InferOutput<TOutput>>> | ReadableStream<InferOutput<TOutput>> : (c: AgentContext<any, TConfig, TAppState>, input: InferOutput<TInput>) => Promise<ReadableStream<unknown>> | ReadableStream<unknown> : TOutput extends StandardSchemaV1 ? (c: AgentContext<any, TConfig, TAppState>, input: InferOutput<TInput>) => Promise<InferOutput<TOutput>> | InferOutput<TOutput> : (c: AgentContext<any, TConfig, TAppState>, input: InferOutput<TInput>) => Promise<void> | void : TStream extends true ? TOutput extends StandardSchemaV1 ? (c: AgentContext<any, TConfig, TAppState>) => Promise<ReadableStream<InferOutput<TOutput>>> | ReadableStream<InferOutput<TOutput>> : (c: AgentContext<any, TConfig, TAppState>) => Promise<ReadableStream<unknown>> | ReadableStream<unknown> : TOutput extends StandardSchemaV1 ? (c: AgentContext<any, TConfig, TAppState>) => Promise<InferOutput<TOutput>> | InferOutput<TOutput> : (c: AgentContext<any, TConfig, TAppState>) => Promise<void> | void;
1082
- }
1083
- /**
1084
- * Creates an agent with schema validation and lifecycle hooks.
1085
- *
1086
- * This is the recommended way to create agents with automatic type inference from schemas.
1087
- *
1088
- * @template TSchema - Schema definition object containing optional input, output, and stream properties
1089
- * @template TConfig - Function type that returns agent-specific configuration from setup
1090
- *
1091
- * @param name - Unique agent name (must be unique within the project)
1092
- * @param config - Agent configuration object
1093
- *
1094
- * @returns AgentRunner with a run method for executing the agent
1095
- *
1096
- * @example
1097
- * ```typescript
1098
- * const agent = createAgent('greeting-agent', {
1099
- * description: 'Returns personalized greetings',
1100
- * schema: {
1101
- * input: z.object({ name: z.string(), age: z.number() }),
1102
- * output: z.string()
1103
- * },
1104
- * handler: async (ctx, { name, age }) => {
1105
- * ctx.logger.info(`Processing greeting for ${name}`);
1106
- * return `Hello, ${name}! You are ${age} years old.`;
1107
- * }
1108
- * });
1109
- *
1110
- * // Call the agent directly
1111
- * const result = await agent.run({ name: 'Alice', age: 30 });
1112
- * ```
1113
- */
1114
- export declare function createAgent<TSchema extends {
1115
- input?: StandardSchemaV1;
1116
- output?: StandardSchemaV1;
1117
- stream?: boolean;
1118
- } | undefined = undefined, TConfig extends (app: AppState) => any = any>(name: string, config: CreateAgentConfig<TSchema, TConfig>): AgentRunner<SchemaInput<TSchema>, SchemaOutput<TSchema>, SchemaStream<TSchema>>;
1119
- /**
1120
- * Creates an agent with explicit generic type parameters.
1121
- *
1122
- * Use this overload when you need explicit control over types or working with custom app state.
1123
- *
1124
- * @template TInput - Input schema type (StandardSchemaV1 or undefined)
1125
- * @template TOutput - Output schema type (StandardSchemaV1 or undefined)
1126
- * @template TStream - Whether agent returns a stream (true/false)
1127
- * @template TConfig - Type returned by setup function
1128
- * @template TAppState - Custom app state type from createApp
1129
- *
1130
- * @param name - Unique agent name (must be unique within the project)
1131
- * @param config - Agent configuration object
1132
- *
1133
- * @returns AgentRunner with explicit types and a run method
1134
- *
1135
- * @example
1136
- * ```typescript
1137
- * interface MyAppState { db: Database }
1138
- * interface MyConfig { cache: Map<string, any> }
1139
- *
1140
- * const agent = createAgent<
1141
- * z.ZodObject<any>, // TInput
1142
- * z.ZodString, // TOutput
1143
- * false // TStream
1144
- * >('custom-agent', {
1145
- * setup: async (app) => ({ cache: new Map() }),
1146
- * handler: async (ctx, input) => {
1147
- * const db = ctx.app.db;
1148
- * const cache = ctx.config.cache;
1149
- * return 'result';
1150
- * }
1151
- * });
1152
- * ```
1153
- */
1154
- export declare function createAgent<TInput extends StandardSchemaV1 | undefined = undefined, TOutput extends StandardSchemaV1 | undefined = undefined, TStream extends boolean = false, TConfig = unknown, TAppState = AppState>(name: string, config: CreateAgentConfigExplicit<TInput, TOutput, TStream, TConfig, TAppState>): AgentRunner<TInput, TOutput, TStream>;
1155
- /**
1156
- * Populate the agents object with all registered agents
1157
- * Keys are converted to camelCase to match the generated TypeScript types
1158
- */
1159
- export declare const populateAgentsRegistry: (ctx: Context) => any;
1160
- export declare const createAgentMiddleware: (agentName: AgentName | "") => MiddlewareHandler;
1161
- export declare const getAgents: () => Map<string, Agent<any, any, any, any, any>>;
1162
- export declare const runAgentSetups: (appState: AppState) => Promise<void>;
1163
- export declare const runAgentShutdowns: (appState: AppState) => Promise<void>;
1164
- /**
1165
- * Run an agent within a specific AgentContext.
1166
- * Sets up AsyncLocalStorage with the provided context and executes the agent.
1167
- *
1168
- * This is the recommended way to test agents in unit tests. It automatically:
1169
- * - Registers the agent in the runtime state so event listeners fire
1170
- * - Sets up AsyncLocalStorage so getAgentContext() works inside the agent
1171
- * - Handles both agents with input and agents without input
1172
- *
1173
- * **Use cases:**
1174
- * - Unit testing agents with TestAgentContext
1175
- * - Running agents outside HTTP request flow
1176
- * - Custom agent execution environments
1177
- * - Testing event listeners and evaluations
1178
- *
1179
- * @template TInput - Type of the input parameter
1180
- * @template TOutput - Type of the return value
1181
- *
1182
- * @param ctx - The AgentContext to use (typically TestAgentContext in tests)
1183
- * @param agent - The AgentRunner to execute (returned from createAgent)
1184
- * @param input - Input data (required if agent has input schema, omit otherwise)
1185
- *
1186
- * @returns Promise resolving to the agent's output
1187
- *
1188
- * @example
1189
- * ```typescript
1190
- * import { runInAgentContext, TestAgentContext } from '@agentuity/runtime/test';
1191
- *
1192
- * test('greeting agent', async () => {
1193
- * const ctx = new TestAgentContext();
1194
- * const result = await runInAgentContext(ctx, greetingAgent, {
1195
- * name: 'Alice',
1196
- * age: 30
1197
- * });
1198
- * expect(result).toBe('Hello, Alice! You are 30 years old.');
1199
- * });
1200
- *
1201
- * test('no-input agent', async () => {
1202
- * const ctx = new TestAgentContext();
1203
- * const result = await runInAgentContext(ctx, statusAgent);
1204
- * expect(result).toEqual({ status: 'ok' });
1205
- * });
1206
- * ```
1207
- */
1208
- export declare function runInAgentContext<TInput, TOutput>(ctx: AgentContext<any, any, any>, agent: AgentRunner<any, any, any>, input?: TInput): Promise<TOutput>;
1209
- export {};
1210
- //# sourceMappingURL=agent.d.ts.map