@agentuity/runtime 0.0.69 → 0.0.70

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 (95) hide show
  1. package/AGENTS.md +88 -10
  2. package/README.md +0 -2
  3. package/dist/_config.d.ts +16 -0
  4. package/dist/_config.d.ts.map +1 -1
  5. package/dist/_config.js +16 -0
  6. package/dist/_config.js.map +1 -1
  7. package/dist/_context.d.ts +17 -15
  8. package/dist/_context.d.ts.map +1 -1
  9. package/dist/_context.js +17 -8
  10. package/dist/_context.js.map +1 -1
  11. package/dist/_server.d.ts.map +1 -1
  12. package/dist/_server.js +23 -14
  13. package/dist/_server.js.map +1 -1
  14. package/dist/_services.d.ts.map +1 -1
  15. package/dist/_services.js +2 -29
  16. package/dist/_services.js.map +1 -1
  17. package/dist/_validation.d.ts +3 -3
  18. package/dist/_validation.d.ts.map +1 -1
  19. package/dist/_validation.js.map +1 -1
  20. package/dist/agent.d.ts +289 -107
  21. package/dist/agent.d.ts.map +1 -1
  22. package/dist/agent.js +206 -149
  23. package/dist/agent.js.map +1 -1
  24. package/dist/app.d.ts +6 -18
  25. package/dist/app.d.ts.map +1 -1
  26. package/dist/app.js +1 -1
  27. package/dist/app.js.map +1 -1
  28. package/dist/eval.d.ts +4 -4
  29. package/dist/eval.d.ts.map +1 -1
  30. package/dist/index.d.ts +2 -1
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +1 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/otel/config.d.ts.map +1 -1
  35. package/dist/otel/config.js +5 -2
  36. package/dist/otel/config.js.map +1 -1
  37. package/dist/otel/console.d.ts +10 -6
  38. package/dist/otel/console.d.ts.map +1 -1
  39. package/dist/otel/console.js +31 -13
  40. package/dist/otel/console.js.map +1 -1
  41. package/dist/otel/logger.d.ts.map +1 -1
  42. package/dist/otel/logger.js +0 -19
  43. package/dist/otel/logger.js.map +1 -1
  44. package/dist/otel/otel.d.ts +2 -1
  45. package/dist/otel/otel.d.ts.map +1 -1
  46. package/dist/otel/otel.js +28 -15
  47. package/dist/otel/otel.js.map +1 -1
  48. package/dist/services/local/_db.d.ts.map +1 -1
  49. package/dist/services/local/_db.js +1 -22
  50. package/dist/services/local/_db.js.map +1 -1
  51. package/dist/services/local/_router.d.ts.map +1 -1
  52. package/dist/services/local/_router.js +0 -32
  53. package/dist/services/local/_router.js.map +1 -1
  54. package/dist/services/local/index.d.ts +0 -1
  55. package/dist/services/local/index.d.ts.map +1 -1
  56. package/dist/services/local/index.js +0 -1
  57. package/dist/services/local/index.js.map +1 -1
  58. package/dist/session.d.ts +2 -2
  59. package/dist/validator.d.ts +140 -0
  60. package/dist/validator.d.ts.map +1 -0
  61. package/dist/validator.js +146 -0
  62. package/dist/validator.js.map +1 -0
  63. package/dist/workbench.d.ts.map +1 -1
  64. package/dist/workbench.js +38 -29
  65. package/dist/workbench.js.map +1 -1
  66. package/package.json +6 -6
  67. package/src/_config.ts +19 -0
  68. package/src/_context.ts +25 -31
  69. package/src/_server.ts +26 -14
  70. package/src/_services.ts +0 -28
  71. package/src/_validation.ts +3 -7
  72. package/src/agent.ts +555 -348
  73. package/src/app.ts +5 -18
  74. package/src/eval.ts +6 -6
  75. package/src/index.ts +2 -1
  76. package/src/otel/config.ts +5 -2
  77. package/src/otel/console.ts +34 -20
  78. package/src/otel/logger.ts +0 -18
  79. package/src/otel/otel.ts +43 -29
  80. package/src/services/local/_db.ts +1 -27
  81. package/src/services/local/_router.ts +0 -46
  82. package/src/services/local/index.ts +0 -1
  83. package/src/session.ts +2 -2
  84. package/src/validator.ts +277 -0
  85. package/src/workbench.ts +38 -32
  86. package/dist/agent.validator.test.d.ts +0 -2
  87. package/dist/agent.validator.test.d.ts.map +0 -1
  88. package/dist/agent.validator.test.js +0 -508
  89. package/dist/agent.validator.test.js.map +0 -1
  90. package/dist/services/local/objectstore.d.ts +0 -19
  91. package/dist/services/local/objectstore.d.ts.map +0 -1
  92. package/dist/services/local/objectstore.js +0 -117
  93. package/dist/services/local/objectstore.js.map +0 -1
  94. package/src/agent.validator.test.ts +0 -587
  95. package/src/services/local/objectstore.ts +0 -177
package/dist/agent.d.ts CHANGED
@@ -1,31 +1,40 @@
1
- import { type KeyValueStorage, type ObjectStorage, type StandardSchemaV1, type StreamStorage, type VectorStorage } from '@agentuity/core';
1
+ import { type KeyValueStorage, type StandardSchemaV1, type StreamStorage, type VectorStorage, type InferOutput } from '@agentuity/core';
2
2
  import { type Tracer } from '@opentelemetry/api';
3
3
  import type { Context, MiddlewareHandler } from 'hono';
4
4
  import type { Handler } from 'hono/types';
5
+ import { AGENT_RUNTIME } from './_config';
5
6
  import type { Logger } from './logger';
6
- import type { Eval, EvalFunction, ExternalEvalMetadata } from './eval';
7
+ import type { Eval, EvalFunction } from './eval';
7
8
  import type { Thread, Session } from './session';
8
9
  import type { AppState } from './index';
9
10
  export type AgentEventName = 'started' | 'completed' | 'errored';
10
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
+ }
11
21
  /**
12
22
  * Context object passed to every agent handler providing access to runtime services and state.
13
23
  *
14
24
  * @template TAgentRegistry - Registry of all available agents (auto-generated, strongly-typed)
15
- * @template TCurrent - Current agent runner type
16
- * @template TParent - Parent agent runner type (if called from another agent)
17
25
  * @template TConfig - Agent-specific configuration type from setup function
18
26
  * @template TAppState - Application-wide state type from createApp
19
27
  *
20
28
  * @example
21
29
  * ```typescript
22
- * const agent = createAgent({
30
+ * const agent = createAgent('my-agent', {
23
31
  * handler: async (ctx, input) => {
24
32
  * // Logging
25
33
  * ctx.logger.info('Processing request', { input });
26
34
  *
27
- * // Call another agent
28
- * const result = await ctx.agent.otherAgent.run({ data: input });
35
+ * // Call another agent (import it directly)
36
+ * import otherAgent from './other-agent';
37
+ * const result = await otherAgent.run({ data: input });
29
38
  *
30
39
  * // Store data
31
40
  * await ctx.kv.set('key', { value: result });
@@ -43,7 +52,14 @@ export type AgentEventCallback<TAgent extends Agent<any, any, any>> = ((eventNam
43
52
  * });
44
53
  * ```
45
54
  */
46
- export interface AgentContext<TAgentRegistry extends AgentRegistry = AgentRegistry, TCurrent extends AgentRunner<any, any, any> | undefined = AgentRunner<any, any, any> | undefined, TParent extends AgentRunner<any, any, any> | undefined = AgentRunner<any, any, any> | undefined, TConfig = unknown, TAppState = Record<string, never>> {
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;
47
63
  /**
48
64
  * Schedule a background task that continues after the response is sent.
49
65
  * Useful for cleanup, logging, or async operations that don't block the response.
@@ -59,30 +75,6 @@ export interface AgentContext<TAgentRegistry extends AgentRegistry = AgentRegist
59
75
  * ```
60
76
  */
61
77
  waitUntil: (promise: Promise<void> | (() => void | Promise<void>)) => void;
62
- /**
63
- * Registry of all agents in the application. Strongly-typed and auto-generated.
64
- * Use to call other agents from within your handler.
65
- *
66
- * @example
67
- * ```typescript
68
- * const emailResult = await ctx.agent.email.run({ to: 'user@example.com' });
69
- * const smsResult = await ctx.agent.sms.run({ phone: '+1234567890' });
70
- * ```
71
- */
72
- agent: TAgentRegistry;
73
- /**
74
- * Information about the currently executing agent.
75
- */
76
- current: TCurrent;
77
- /**
78
- * Information about the parent agent (if this agent was called by another agent).
79
- * Use ctx.agent.parentName for strongly-typed access.
80
- */
81
- parent: TParent;
82
- /**
83
- * Name of the current agent being executed.
84
- */
85
- agentName: AgentName;
86
78
  /**
87
79
  * Structured logger with OpenTelemetry integration.
88
80
  * Logs are automatically correlated with traces.
@@ -127,18 +119,6 @@ export interface AgentContext<TAgentRegistry extends AgentRegistry = AgentRegist
127
119
  * ```
128
120
  */
129
121
  kv: KeyValueStorage;
130
- /**
131
- * Object storage for files and blobs (S3-compatible).
132
- *
133
- * @example
134
- * ```typescript
135
- * await ctx.objectstore.put('images/photo.jpg', buffer);
136
- * const file = await ctx.objectstore.get('images/photo.jpg');
137
- * await ctx.objectstore.delete('images/photo.jpg');
138
- * const objects = await ctx.objectstore.list('images/');
139
- * ```
140
- */
141
- objectstore: ObjectStorage;
142
122
  /**
143
123
  * Stream storage for real-time data streams and logs.
144
124
  *
@@ -218,13 +198,13 @@ export interface AgentContext<TAgentRegistry extends AgentRegistry = AgentRegist
218
198
  }
219
199
  type InternalAgentMetadata = {
220
200
  /**
221
- * the unique identifier for this project, agent and deployment.
201
+ * the unique name for the agent (user-provided).
222
202
  */
223
- id: string;
203
+ name: string;
224
204
  /**
225
- * the unique identifier for this project and agent across multiple deployments.
205
+ * the unique identifier for this project, agent and deployment.
226
206
  */
227
- identifier: string;
207
+ id: string;
228
208
  /**
229
209
  * the unique identifier for this agent across multiple deployments
230
210
  */
@@ -247,10 +227,6 @@ type InternalAgentMetadata = {
247
227
  outputSchemaCode?: string;
248
228
  };
249
229
  type ExternalAgentMetadata = {
250
- /**
251
- * the human readable name for the agent.
252
- */
253
- name: string;
254
230
  /**
255
231
  * the human readable description for the agent
256
232
  */
@@ -260,22 +236,19 @@ type AgentMetadata = InternalAgentMetadata & ExternalAgentMetadata;
260
236
  /**
261
237
  * Configuration object for creating an agent evaluation function.
262
238
  *
263
- * @template TInput - Input schema type from the parent agent
264
- * @template TOutput - Output schema type from the parent agent
239
+ * @template TInput - Input schema type from the agent
240
+ * @template TOutput - Output schema type from the agent
265
241
  */
266
242
  export interface CreateEvalConfig<TInput extends StandardSchemaV1 | undefined = any, TOutput extends StandardSchemaV1 | undefined = any> {
267
243
  /**
268
- * Optional metadata for the evaluation function.
244
+ * Optional description of what this evaluation does.
269
245
  *
270
246
  * @example
271
247
  * ```typescript
272
- * metadata: {
273
- * name: 'Validate positive output',
274
- * description: 'Ensures output is greater than zero'
275
- * }
248
+ * description: 'Ensures output is greater than zero'
276
249
  * ```
277
250
  */
278
- metadata?: Partial<ExternalEvalMetadata>;
251
+ description?: string;
279
252
  /**
280
253
  * Evaluation handler function that tests the agent's behavior.
281
254
  * Return true if the evaluation passes, false if it fails.
@@ -308,9 +281,9 @@ export interface CreateEvalConfig<TInput extends StandardSchemaV1 | undefined =
308
281
  * }
309
282
  * ```
310
283
  */
311
- handler: EvalFunction<TInput extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TInput> : undefined, TOutput extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TOutput> : undefined>;
284
+ handler: EvalFunction<TInput extends StandardSchemaV1 ? InferOutput<TInput> : undefined, TOutput extends StandardSchemaV1 ? InferOutput<TOutput> : undefined>;
312
285
  }
313
- type CreateEvalMethod<TInput extends StandardSchemaV1 | undefined = any, TOutput extends StandardSchemaV1 | undefined = any> = (config: CreateEvalConfig<TInput, TOutput>) => Eval<TInput, TOutput>;
286
+ type CreateEvalMethod<TInput extends StandardSchemaV1 | undefined = any, TOutput extends StandardSchemaV1 | undefined = any> = (name: string, config: CreateEvalConfig<TInput, TOutput>) => Eval<TInput, TOutput>;
314
287
  /**
315
288
  * Validator function type with method overloads for different validation scenarios.
316
289
  * Provides type-safe validation middleware that integrates with Hono's type system.
@@ -359,7 +332,7 @@ export interface AgentValidator<TInput extends StandardSchemaV1 | undefined, _TO
359
332
  (): TInput extends StandardSchemaV1 ? Handler<any, any, {
360
333
  in: {};
361
334
  out: {
362
- json: StandardSchemaV1.InferOutput<TInput>;
335
+ json: InferOutput<TInput>;
363
336
  };
364
337
  }> : Handler<any, any, any>;
365
338
  /**
@@ -387,7 +360,7 @@ export interface AgentValidator<TInput extends StandardSchemaV1 | undefined, _TO
387
360
  }): Handler<any, any, {
388
361
  in: {};
389
362
  out: {
390
- json: StandardSchemaV1.InferOutput<TOverrideOutput>;
363
+ json: InferOutput<TOverrideOutput>;
391
364
  };
392
365
  }>;
393
366
  /**
@@ -426,7 +399,7 @@ export interface AgentValidator<TInput extends StandardSchemaV1 | undefined, _TO
426
399
  }): Handler<any, any, {
427
400
  in: {};
428
401
  out: {
429
- json: StandardSchemaV1.InferOutput<TOverrideInput>;
402
+ json: InferOutput<TOverrideInput>;
430
403
  };
431
404
  }>;
432
405
  }
@@ -457,7 +430,8 @@ export interface AgentValidator<TInput extends StandardSchemaV1 | undefined, _TO
457
430
  * });
458
431
  *
459
432
  * // Create evals for testing
460
- * const eval1 = agent.createEval({
433
+ * const eval1 = agent.createEval('check-positive', {
434
+ * description: 'Ensures result is greater than 5',
461
435
  * handler: async (run, result) => {
462
436
  * return result > 5; // Assert output is greater than 5
463
437
  * }
@@ -471,9 +445,9 @@ export type Agent<TInput extends StandardSchemaV1 | undefined = any, TOutput ext
471
445
  metadata: AgentMetadata;
472
446
  /**
473
447
  * The main handler function that processes agent requests.
474
- * Receives AgentContext and validated input, returns output or stream.
448
+ * Gets AgentContext from AsyncLocalStorage, receives validated input, returns output or stream.
475
449
  */
476
- handler: (ctx: AgentContext<any, any, any, TConfig, TAppState>, ...args: any[]) => any | Promise<any>;
450
+ handler: (...args: any[]) => any | Promise<any>;
477
451
  /**
478
452
  * Creates a type-safe validation middleware for routes using StandardSchema validation.
479
453
  *
@@ -564,8 +538,8 @@ export type Agent<TInput extends StandardSchemaV1 | undefined = any, TOutput ext
564
538
  * });
565
539
  *
566
540
  * // Create eval to validate output
567
- * agent.createEval({
568
- * metadata: { name: 'Check positive output' },
541
+ * agent.createEval('check-positive', {
542
+ * description: 'Ensures output is a positive number',
569
543
  * handler: async (run, result) => {
570
544
  * return result > 0; // Assert output is positive
571
545
  * }
@@ -596,7 +570,7 @@ export type Agent<TInput extends StandardSchemaV1 | undefined = any, TOutput ext
596
570
  * });
597
571
  * ```
598
572
  */
599
- addEventListener(eventName: 'started', callback: (eventName: 'started', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, any, any, TConfig, TAppState>) => Promise<void> | void): void;
573
+ addEventListener(eventName: 'started', callback: (eventName: 'started', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>) => Promise<void> | void): void;
600
574
  /**
601
575
  * Register an event listener for when the agent completes successfully.
602
576
  *
@@ -610,7 +584,7 @@ export type Agent<TInput extends StandardSchemaV1 | undefined = any, TOutput ext
610
584
  * });
611
585
  * ```
612
586
  */
613
- addEventListener(eventName: 'completed', callback: (eventName: 'completed', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, any, any, TConfig, TAppState>) => Promise<void> | void): void;
587
+ addEventListener(eventName: 'completed', callback: (eventName: 'completed', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>) => Promise<void> | void): void;
614
588
  /**
615
589
  * Register an event listener for when the agent throws an error.
616
590
  *
@@ -624,28 +598,28 @@ export type Agent<TInput extends StandardSchemaV1 | undefined = any, TOutput ext
624
598
  * });
625
599
  * ```
626
600
  */
627
- addEventListener(eventName: 'errored', callback: (eventName: 'errored', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, any, any, TConfig, TAppState>, data: Error) => Promise<void> | void): void;
601
+ addEventListener(eventName: 'errored', callback: (eventName: 'errored', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>, data: Error) => Promise<void> | void): void;
628
602
  /**
629
603
  * Remove a previously registered 'started' event listener.
630
604
  *
631
605
  * @param eventName - Must be 'started'
632
606
  * @param callback - The callback function to remove
633
607
  */
634
- removeEventListener(eventName: 'started', callback: (eventName: 'started', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, any, any, TConfig, TAppState>) => Promise<void> | void): void;
608
+ removeEventListener(eventName: 'started', callback: (eventName: 'started', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>) => Promise<void> | void): void;
635
609
  /**
636
610
  * Remove a previously registered 'completed' event listener.
637
611
  *
638
612
  * @param eventName - Must be 'completed'
639
613
  * @param callback - The callback function to remove
640
614
  */
641
- removeEventListener(eventName: 'completed', callback: (eventName: 'completed', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, any, any, TConfig, TAppState>) => Promise<void> | void): void;
615
+ removeEventListener(eventName: 'completed', callback: (eventName: 'completed', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>) => Promise<void> | void): void;
642
616
  /**
643
617
  * Remove a previously registered 'errored' event listener.
644
618
  *
645
619
  * @param eventName - Must be 'errored'
646
620
  * @param callback - The callback function to remove
647
621
  */
648
- removeEventListener(eventName: 'errored', callback: (eventName: 'errored', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, any, any, TConfig, TAppState>, data: Error) => Promise<void> | void): void;
622
+ removeEventListener(eventName: 'errored', callback: (eventName: 'errored', agent: Agent<TInput, TOutput, TStream, TConfig, TAppState>, context: AgentContext<any, TConfig, TAppState>, data: Error) => Promise<void> | void): void;
649
623
  } & (TInput extends StandardSchemaV1 ? {
650
624
  inputSchema: TInput;
651
625
  } : {
@@ -659,8 +633,8 @@ export type Agent<TInput extends StandardSchemaV1 | undefined = any, TOutput ext
659
633
  } : {
660
634
  stream?: false;
661
635
  });
662
- type InferSchemaInput<T> = T extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<T> : never;
663
- type InferStreamOutput<TOutput, TStream extends boolean> = TStream extends true ? TOutput extends StandardSchemaV1 ? ReadableStream<StandardSchemaV1.InferOutput<TOutput>> : ReadableStream<unknown> : TOutput extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TOutput> : void;
636
+ type InferSchemaInput<T> = T extends StandardSchemaV1 ? InferOutput<T> : never;
637
+ type InferStreamOutput<TOutput, TStream extends boolean> = TStream extends true ? TOutput extends StandardSchemaV1 ? ReadableStream<InferOutput<TOutput>> : ReadableStream<unknown> : TOutput extends StandardSchemaV1 ? InferOutput<TOutput> : void;
664
638
  type SchemaInput<TSchema> = TSchema extends {
665
639
  input: infer I;
666
640
  } ? I : undefined;
@@ -670,13 +644,29 @@ type SchemaOutput<TSchema> = TSchema extends {
670
644
  type SchemaStream<TSchema> = TSchema extends {
671
645
  stream: infer S;
672
646
  } ? S extends boolean ? S : false : false;
673
- type SchemaHandlerReturn<TSchema> = SchemaStream<TSchema> extends true ? SchemaOutput<TSchema> extends StandardSchemaV1 ? ReadableStream<StandardSchemaV1.InferOutput<SchemaOutput<TSchema>>> : ReadableStream<unknown> : SchemaOutput<TSchema> extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<SchemaOutput<TSchema>> : void;
674
- type AgentHandlerFromConfig<TSchema, TSetupReturn, TAppState = AppState> = SchemaInput<TSchema> extends infer I ? I extends StandardSchemaV1 ? (ctx: AgentContext<any, any, any, TSetupReturn, TAppState>, input: StandardSchemaV1.InferOutput<I>) => Promise<SchemaHandlerReturn<TSchema>> | SchemaHandlerReturn<TSchema> : (ctx: AgentContext<any, any, any, TSetupReturn, TAppState>) => Promise<SchemaHandlerReturn<TSchema>> | SchemaHandlerReturn<TSchema> : (ctx: AgentContext<any, any, any, TSetupReturn, TAppState>) => Promise<SchemaHandlerReturn<TSchema>> | SchemaHandlerReturn<TSchema>;
647
+ 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;
648
+ 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>;
675
649
  /**
676
650
  * Configuration object for creating an agent with automatic type inference.
677
651
  *
652
+ * Passed as the second parameter to createAgent(name, config).
653
+ *
678
654
  * @template TSchema - Schema definition object containing optional input, output, and stream properties
679
655
  * @template TConfig - Function type that returns agent-specific configuration from setup
656
+ *
657
+ * @example
658
+ * ```typescript
659
+ * const agent = createAgent('greeting', {
660
+ * description: 'Generates personalized greetings',
661
+ * schema: {
662
+ * input: z.object({ name: z.string(), age: z.number() }),
663
+ * output: z.string()
664
+ * },
665
+ * handler: async (ctx, { name, age }) => {
666
+ * return `Hello, ${name}! You are ${age} years old.`;
667
+ * }
668
+ * });
669
+ * ```
680
670
  */
681
671
  export interface CreateAgentConfig<TSchema extends {
682
672
  input?: StandardSchemaV1;
@@ -697,17 +687,21 @@ export interface CreateAgentConfig<TSchema extends {
697
687
  */
698
688
  schema?: TSchema;
699
689
  /**
700
- * Agent metadata visible in the Agentuity platform.
690
+ * Optional description of what this agent does, visible in the Agentuity platform.
701
691
  *
702
692
  * @example
703
693
  * ```typescript
704
- * metadata: {
705
- * name: 'Greeting Agent',
706
- * description: 'Returns personalized greetings'
707
- * }
694
+ * description: 'Returns personalized greetings'
708
695
  * ```
709
696
  */
710
- metadata: ExternalAgentMetadata;
697
+ description?: string;
698
+ /**
699
+ * Optional metadata object (typically injected by build plugin during compilation).
700
+ * Contains agent identification and versioning information.
701
+ *
702
+ * @internal - Usually populated by build tooling, not manually set
703
+ */
704
+ metadata?: Partial<AgentMetadata>;
711
705
  /**
712
706
  * Optional async function called once on app startup to initialize agent-specific resources.
713
707
  * The returned value is available in the handler via `ctx.config`.
@@ -760,10 +754,150 @@ export interface CreateAgentConfig<TSchema extends {
760
754
  */
761
755
  shutdown?: (app: AppState, config: TConfig extends (app: AppState) => infer R ? Awaited<R> : undefined) => Promise<void> | void;
762
756
  }
757
+ /**
758
+ * The public interface returned by createAgent().
759
+ * Provides methods to run the agent, create evaluations, and manage event listeners.
760
+ *
761
+ * @template TInput - Input schema type (StandardSchemaV1 or undefined if no input)
762
+ * @template TOutput - Output schema type (StandardSchemaV1 or undefined if no output)
763
+ * @template TStream - Whether the agent returns a stream (true/false)
764
+ *
765
+ * @example
766
+ * ```typescript
767
+ * const agent = createAgent('greeting', {
768
+ * schema: {
769
+ * input: z.object({ name: z.string() }),
770
+ * output: z.string()
771
+ * },
772
+ * handler: async (ctx, { name }) => `Hello, ${name}!`
773
+ * });
774
+ *
775
+ * // Run the agent
776
+ * const result = await agent.run({ name: 'Alice' });
777
+ *
778
+ * // Create evaluation
779
+ * const evalDef = agent.createEval('greeting-accuracy', {
780
+ * description: 'Checks if greeting includes the user name',
781
+ * handler: async (ctx, input, output) => {
782
+ * return { score: output.includes(input.name) ? 1 : 0 };
783
+ * }
784
+ * });
785
+ *
786
+ * // Listen to events
787
+ * agent.addEventListener('completed', async (eventName, agent, context) => {
788
+ * console.log('Agent completed successfully');
789
+ * });
790
+ * ```
791
+ */
763
792
  export interface AgentRunner<TInput extends StandardSchemaV1 | undefined = any, TOutput extends StandardSchemaV1 | undefined = any, TStream extends boolean = false> {
793
+ /** Agent metadata (id, name, description, etc.) */
764
794
  metadata: AgentMetadata;
795
+ /**
796
+ * Execute the agent with validated input.
797
+ * If agent has no input schema, call with no arguments.
798
+ * If agent has input schema, pass validated input object.
799
+ *
800
+ * @example
801
+ * ```typescript
802
+ * // Agent with input
803
+ * const result = await agent.run({ name: 'Alice' });
804
+ *
805
+ * // Agent without input
806
+ * const result = await agent.run();
807
+ * ```
808
+ */
765
809
  run: undefined extends TInput ? () => Promise<InferStreamOutput<Exclude<TOutput, undefined>, TStream>> : (input: InferSchemaInput<Exclude<TInput, undefined>>) => Promise<InferStreamOutput<Exclude<TOutput, undefined>, TStream>>;
810
+ /**
811
+ * Create Hono validator middleware for this agent.
812
+ * Automatically validates request input against the agent's schema.
813
+ *
814
+ * @example
815
+ * ```typescript
816
+ * import myAgent from './my-agent';
817
+ * router.post('/', myAgent.validator(), async (c) => {
818
+ * const data = c.req.valid('json'); // Fully typed!
819
+ * return c.json(await myAgent.run(data));
820
+ * });
821
+ * ```
822
+ */
823
+ validator: AgentValidator<TInput, TOutput>;
824
+ /** Input schema (if defined) */
825
+ inputSchema?: TInput;
826
+ /** Output schema (if defined) */
827
+ outputSchema?: TOutput;
828
+ /** Whether agent returns a stream */
829
+ stream?: TStream;
830
+ /**
831
+ * Create an evaluation for this agent.
832
+ * Evaluations run automatically after the agent completes.
833
+ *
834
+ * @example
835
+ * ```typescript
836
+ * const accuracyEval = agent.createEval('accuracy', {
837
+ * description: 'Validates output length is non-zero',
838
+ * handler: async (ctx, input, output) => ({
839
+ * score: output.length > 0 ? 1 : 0,
840
+ * metadata: { outputLength: output.length }
841
+ * })
842
+ * });
843
+ * ```
844
+ */
845
+ createEval: CreateEvalMethod<TInput, TOutput>;
846
+ /**
847
+ * Add event listener for 'started' or 'completed' events.
848
+ * Listeners fire sequentially in the order they were added.
849
+ *
850
+ * @param eventName - 'started' or 'completed'
851
+ * @param callback - Function to call when event fires
852
+ *
853
+ * @example
854
+ * ```typescript
855
+ * agent.addEventListener('started', async (eventName, agent, context) => {
856
+ * context.logger.info('Agent execution started');
857
+ * });
858
+ * ```
859
+ */
860
+ addEventListener(eventName: 'started' | 'completed', callback: (eventName: 'started' | 'completed', agent: Agent<TInput, TOutput, TStream, any, any>, context: AgentContext<any, any, any>) => Promise<void> | void): void;
861
+ /**
862
+ * Add event listener for 'errored' event.
863
+ * Fires when agent handler throws an error.
864
+ *
865
+ * @param eventName - 'errored'
866
+ * @param callback - Function to call when error occurs
867
+ *
868
+ * @example
869
+ * ```typescript
870
+ * agent.addEventListener('errored', async (eventName, agent, context, error) => {
871
+ * context.logger.error('Agent failed', { error: error.message });
872
+ * });
873
+ * ```
874
+ */
875
+ addEventListener(eventName: 'errored', callback: (eventName: 'errored', agent: Agent<TInput, TOutput, TStream, any, any>, context: AgentContext<any, any, any>, error: Error) => Promise<void> | void): void;
876
+ /**
877
+ * Remove event listener for 'started' or 'completed' events.
878
+ *
879
+ * @param eventName - 'started' or 'completed'
880
+ * @param callback - The same callback function that was added
881
+ */
882
+ removeEventListener(eventName: 'started' | 'completed', callback: (eventName: 'started' | 'completed', agent: Agent<TInput, TOutput, TStream, any, any>, context: AgentContext<any, any, any>) => Promise<void> | void): void;
883
+ /**
884
+ * Remove event listener for 'errored' event.
885
+ *
886
+ * @param eventName - 'errored'
887
+ * @param callback - The same callback function that was added
888
+ */
889
+ removeEventListener(eventName: 'errored', callback: (eventName: 'errored', agent: Agent<TInput, TOutput, TStream, any, any>, context: AgentContext<any, any, any>, error: Error) => Promise<void> | void): void;
766
890
  }
891
+ /**
892
+ * Get the global runtime state (for production use).
893
+ * In tests, use TestAgentContext which has isolated runtime state.
894
+ */
895
+ export declare function getGlobalRuntimeState(): AgentRuntimeState;
896
+ /**
897
+ * Get the runtime state from an AgentContext.
898
+ * @internal
899
+ */
900
+ export declare function getAgentRuntime(ctx: AgentContext<any, any, any>): AgentRuntimeState;
767
901
  /**
768
902
  * Union type of all registered agent names.
769
903
  * Falls back to `string` when no agents are registered (before augmentation).
@@ -810,17 +944,21 @@ export interface CreateAgentConfigExplicit<TInput extends StandardSchemaV1 | und
810
944
  stream?: TStream;
811
945
  };
812
946
  /**
813
- * Agent metadata.
947
+ * Optional description of what this agent does.
814
948
  *
815
949
  * @example
816
950
  * ```typescript
817
- * metadata: {
818
- * name: 'My Agent',
819
- * description: 'Does something useful'
820
- * }
951
+ * description: 'Does something useful'
821
952
  * ```
822
953
  */
823
- metadata: ExternalAgentMetadata;
954
+ description?: string;
955
+ /**
956
+ * Optional metadata object (typically injected by build plugin during compilation).
957
+ * Contains agent identification and versioning information.
958
+ *
959
+ * @internal - Usually populated by build tooling, not manually set
960
+ */
961
+ metadata?: Partial<AgentMetadata>;
824
962
  /**
825
963
  * Optional setup function receiving app state, returns agent config.
826
964
  * The returned value is available in the handler via `ctx.config`.
@@ -863,7 +1001,7 @@ export interface CreateAgentConfigExplicit<TInput extends StandardSchemaV1 | und
863
1001
  * }
864
1002
  * ```
865
1003
  */
866
- handler: TInput extends StandardSchemaV1 ? TStream extends true ? TOutput extends StandardSchemaV1 ? (c: AgentContext<any, any, any, TConfig, TAppState>, input: StandardSchemaV1.InferOutput<TInput>) => Promise<ReadableStream<StandardSchemaV1.InferOutput<TOutput>>> | ReadableStream<StandardSchemaV1.InferOutput<TOutput>> : (c: AgentContext<any, any, any, TConfig, TAppState>, input: StandardSchemaV1.InferOutput<TInput>) => Promise<ReadableStream<unknown>> | ReadableStream<unknown> : TOutput extends StandardSchemaV1 ? (c: AgentContext<any, any, any, TConfig, TAppState>, input: StandardSchemaV1.InferOutput<TInput>) => Promise<StandardSchemaV1.InferOutput<TOutput>> | StandardSchemaV1.InferOutput<TOutput> : (c: AgentContext<any, any, any, TConfig, TAppState>, input: StandardSchemaV1.InferOutput<TInput>) => Promise<void> | void : TStream extends true ? TOutput extends StandardSchemaV1 ? (c: AgentContext<any, any, any, TConfig, TAppState>) => Promise<ReadableStream<StandardSchemaV1.InferOutput<TOutput>>> | ReadableStream<StandardSchemaV1.InferOutput<TOutput>> : (c: AgentContext<any, any, any, TConfig, TAppState>) => Promise<ReadableStream<unknown>> | ReadableStream<unknown> : TOutput extends StandardSchemaV1 ? (c: AgentContext<any, any, any, TConfig, TAppState>) => Promise<StandardSchemaV1.InferOutput<TOutput>> | StandardSchemaV1.InferOutput<TOutput> : (c: AgentContext<any, any, any, TConfig, TAppState>) => Promise<void> | void;
1004
+ 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;
867
1005
  }
868
1006
  /**
869
1007
  * Creates an agent with schema validation and lifecycle hooks.
@@ -873,17 +1011,15 @@ export interface CreateAgentConfigExplicit<TInput extends StandardSchemaV1 | und
873
1011
  * @template TSchema - Schema definition object containing optional input, output, and stream properties
874
1012
  * @template TConfig - Function type that returns agent-specific configuration from setup
875
1013
  *
1014
+ * @param name - Unique agent name (must be unique within the project)
876
1015
  * @param config - Agent configuration object
877
1016
  *
878
- * @returns Agent instance that can be registered with the runtime
1017
+ * @returns AgentRunner with a run method for executing the agent
879
1018
  *
880
1019
  * @example
881
1020
  * ```typescript
882
- * const agent = createAgent({
883
- * metadata: {
884
- * name: 'Greeting Agent',
885
- * description: 'Returns personalized greetings'
886
- * },
1021
+ * const agent = createAgent('greeting-agent', {
1022
+ * description: 'Returns personalized greetings',
887
1023
  * schema: {
888
1024
  * input: z.object({ name: z.string(), age: z.number() }),
889
1025
  * output: z.string()
@@ -893,13 +1029,16 @@ export interface CreateAgentConfigExplicit<TInput extends StandardSchemaV1 | und
893
1029
  * return `Hello, ${name}! You are ${age} years old.`;
894
1030
  * }
895
1031
  * });
1032
+ *
1033
+ * // Call the agent directly
1034
+ * const result = await agent.run({ name: 'Alice', age: 30 });
896
1035
  * ```
897
1036
  */
898
1037
  export declare function createAgent<TSchema extends {
899
1038
  input?: StandardSchemaV1;
900
1039
  output?: StandardSchemaV1;
901
1040
  stream?: boolean;
902
- } | undefined = undefined, TConfig extends (app: AppState) => any = any>(config: CreateAgentConfig<TSchema, TConfig>): Agent<SchemaInput<TSchema>, SchemaOutput<TSchema>, SchemaStream<TSchema>, TConfig extends (app: AppState) => infer R ? Awaited<R> : undefined, AppState>;
1041
+ } | undefined = undefined, TConfig extends (app: AppState) => any = any>(name: string, config: CreateAgentConfig<TSchema, TConfig>): AgentRunner<SchemaInput<TSchema>, SchemaOutput<TSchema>, SchemaStream<TSchema>>;
903
1042
  /**
904
1043
  * Creates an agent with explicit generic type parameters.
905
1044
  *
@@ -911,9 +1050,10 @@ export declare function createAgent<TSchema extends {
911
1050
  * @template TConfig - Type returned by setup function
912
1051
  * @template TAppState - Custom app state type from createApp
913
1052
  *
1053
+ * @param name - Unique agent name (must be unique within the project)
914
1054
  * @param config - Agent configuration object
915
1055
  *
916
- * @returns Agent instance with explicit types
1056
+ * @returns AgentRunner with explicit types and a run method
917
1057
  *
918
1058
  * @example
919
1059
  * ```typescript
@@ -923,11 +1063,8 @@ export declare function createAgent<TSchema extends {
923
1063
  * const agent = createAgent<
924
1064
  * z.ZodObject<any>, // TInput
925
1065
  * z.ZodString, // TOutput
926
- * false, // TStream
927
- * MyConfig, // TConfig
928
- * MyAppState // TAppState
929
- * >({
930
- * metadata: { name: 'Custom Agent' },
1066
+ * false // TStream
1067
+ * >('custom-agent', {
931
1068
  * setup: async (app) => ({ cache: new Map() }),
932
1069
  * handler: async (ctx, input) => {
933
1070
  * const db = ctx.app.db;
@@ -937,7 +1074,7 @@ export declare function createAgent<TSchema extends {
937
1074
  * });
938
1075
  * ```
939
1076
  */
940
- export declare function createAgent<TInput extends StandardSchemaV1 | undefined = undefined, TOutput extends StandardSchemaV1 | undefined = undefined, TStream extends boolean = false, TConfig = unknown, TAppState = AppState>(config: CreateAgentConfigExplicit<TInput, TOutput, TStream, TConfig, TAppState>): Agent<TInput, TOutput, TStream, TConfig, TAppState>;
1077
+ 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>;
941
1078
  /**
942
1079
  * Populate the agents object with all registered agents
943
1080
  * Keys are converted to camelCase to match the generated TypeScript types
@@ -947,5 +1084,50 @@ export declare const createAgentMiddleware: (agentName: AgentName | "") => Middl
947
1084
  export declare const getAgents: () => Map<string, Agent<any, any, any, any, any>>;
948
1085
  export declare const runAgentSetups: (appState: AppState) => Promise<void>;
949
1086
  export declare const runAgentShutdowns: (appState: AppState) => Promise<void>;
1087
+ /**
1088
+ * Run an agent within a specific AgentContext.
1089
+ * Sets up AsyncLocalStorage with the provided context and executes the agent.
1090
+ *
1091
+ * This is the recommended way to test agents in unit tests. It automatically:
1092
+ * - Registers the agent in the runtime state so event listeners fire
1093
+ * - Sets up AsyncLocalStorage so getAgentContext() works inside the agent
1094
+ * - Handles both agents with input and agents without input
1095
+ *
1096
+ * **Use cases:**
1097
+ * - Unit testing agents with TestAgentContext
1098
+ * - Running agents outside HTTP request flow
1099
+ * - Custom agent execution environments
1100
+ * - Testing event listeners and evaluations
1101
+ *
1102
+ * @template TInput - Type of the input parameter
1103
+ * @template TOutput - Type of the return value
1104
+ *
1105
+ * @param ctx - The AgentContext to use (typically TestAgentContext in tests)
1106
+ * @param agent - The AgentRunner to execute (returned from createAgent)
1107
+ * @param input - Input data (required if agent has input schema, omit otherwise)
1108
+ *
1109
+ * @returns Promise resolving to the agent's output
1110
+ *
1111
+ * @example
1112
+ * ```typescript
1113
+ * import { runInAgentContext, TestAgentContext } from '@agentuity/runtime/test';
1114
+ *
1115
+ * test('greeting agent', async () => {
1116
+ * const ctx = new TestAgentContext();
1117
+ * const result = await runInAgentContext(ctx, greetingAgent, {
1118
+ * name: 'Alice',
1119
+ * age: 30
1120
+ * });
1121
+ * expect(result).toBe('Hello, Alice! You are 30 years old.');
1122
+ * });
1123
+ *
1124
+ * test('no-input agent', async () => {
1125
+ * const ctx = new TestAgentContext();
1126
+ * const result = await runInAgentContext(ctx, statusAgent);
1127
+ * expect(result).toEqual({ status: 'ok' });
1128
+ * });
1129
+ * ```
1130
+ */
1131
+ export declare function runInAgentContext<TInput, TOutput>(ctx: AgentContext<any, any, any>, agent: AgentRunner<any, any, any>, input?: TInput): Promise<TOutput>;
950
1132
  export {};
951
1133
  //# sourceMappingURL=agent.d.ts.map