@statelyai/agent 2.0.0-next.2 → 2.0.0-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as ai from 'ai';
2
2
  import { generateText, streamText, LanguageModel, CoreMessage, GenerateTextResult, LanguageModelV1, CoreTool } from 'ai';
3
- import { EventObject, AnyStateMachine, AnyEventObject, ActorRefLike, SnapshotFrom, EventFrom, PromiseActorLogic, ActorLogic, TransitionSnapshot, Values, StateValue, Actor, Subscription, ObservableActorLogic } from 'xstate';
3
+ import { AnyStateMachine, AnyEventObject, ActorRefLike, SnapshotFrom, EventFrom, PromiseActorLogic, ActorLogic, TransitionSnapshot, Values, StateValue, EventObject, Actor, Subscription, ObservableActorLogic } from 'xstate';
4
4
  import { SomeZodObject, ZodType, TypeOf } from 'zod';
5
5
 
6
6
  type ZodEventMapping = {
@@ -12,12 +12,16 @@ type ZodContextMapping = {
12
12
 
13
13
  type GenerateTextOptions = Parameters<typeof generateText>[0];
14
14
  type StreamTextOptions = Parameters<typeof streamText>[0];
15
- type CostFunction<TEvent extends EventObject> = (path: AgentPath<TEvent>) => number;
16
- type AgentDecideInput<TEvent extends EventObject> = Omit<AgentGenerateTextOptions, 'prompt' | 'tools'> & {
15
+ type CostFunction<TAgent extends AnyAgent> = (path: AgentPath<TAgent>) => number;
16
+ type AgentDecideInput<TAgent extends AnyAgent> = Omit<AgentGenerateTextOptions<TAgent>, 'prompt' | 'tools'> & {
17
17
  /**
18
18
  * The currently observed state.
19
19
  */
20
- state: ObservedState;
20
+ state: ObservedState<TAgent>;
21
+ /**
22
+ * The context to provide in the prompt to the agent. This overrides the `state.context`.
23
+ */
24
+ context?: Record<string, any>;
21
25
  /**
22
26
  * The goal for the agent to accomplish.
23
27
  * The agent will make a decision based on this goal.
@@ -33,34 +37,31 @@ type AgentDecideInput<TEvent extends EventObject> = Omit<AgentGenerateTextOption
33
37
  * is interacting with.
34
38
  */
35
39
  machine?: AnyStateMachine;
36
- /**
37
- * The previous decision made by the agent.
38
- */
39
- prevDecision?: AgentDecision<TEvent>;
40
40
  /**
41
41
  * The total cost of the path to the goal state.
42
42
  */
43
- costFunction?: CostFunction<TEvent>;
43
+ costFunction?: CostFunction<TAgent>;
44
44
  /**
45
45
  * The maximum number of attempts to make a decision.
46
46
  * Defaults to 2.
47
47
  */
48
48
  maxAttempts?: number;
49
49
  };
50
- type AgentStep<TEvent extends EventObject> = {
50
+ type AgentStep<TAgent extends AnyAgent> = {
51
51
  /** The event to take */
52
- event: TEvent;
52
+ event: EventFromAgent<TAgent>;
53
53
  /** The next expected state after taking the event */
54
- state: ObservedState | undefined;
54
+ state: ObservedState<TAgent> | undefined;
55
55
  };
56
- type AgentPath<TEvent extends EventObject> = {
56
+ type AgentPath<TAgent extends AnyAgent> = {
57
57
  /** The expected ending state of the path */
58
- state: ObservedState | undefined;
58
+ state: ObservedState<TAgent> | undefined;
59
59
  /** The steps to reach the ending state */
60
- steps: Array<AgentStep<TEvent>>;
60
+ steps: Array<AgentStep<TAgent>>;
61
61
  weight?: number;
62
62
  };
63
- type AgentDecision<TEvent extends EventObject> = {
63
+ type AgentDecision<TAgent extends AnyAgent> = {
64
+ id: string;
64
65
  /**
65
66
  * The strategy used to generate the decision
66
67
  */
@@ -69,17 +70,17 @@ type AgentDecision<TEvent extends EventObject> = {
69
70
  /**
70
71
  * The ending state of the decision.
71
72
  */
72
- goalState: ObservedState | undefined;
73
+ goalState: ObservedState<TAgent> | undefined;
73
74
  /**
74
75
  * The next event that the agent decided needs to occur to achieve the `goal`.
75
76
  *
76
77
  * This next event is chosen from the
77
78
  */
78
- nextEvent: TEvent | undefined;
79
+ nextEvent: EventFromAgent<TAgent> | undefined;
79
80
  /**
80
81
  * The paths that the agent can take to achieve the goal.
81
82
  */
82
- paths: AgentPath<TEvent>[];
83
+ paths: AgentPath<TAgent>[];
83
84
  episodeId: string;
84
85
  timestamp: number;
85
86
  };
@@ -91,17 +92,13 @@ interface TransitionData {
91
92
  };
92
93
  target?: any;
93
94
  }
94
- type PromptTemplate<TEvents extends EventObject> = (data: {
95
+ type PromptTemplate<TAgent extends AnyAgent> = (data: {
95
96
  goal: string;
96
97
  /**
97
98
  * The observed state
98
99
  */
99
- state?: ObservedState;
100
- /**
101
- * The context to provide.
102
- * This overrides the observed state.context, if provided.
103
- */
104
- context?: any;
100
+ stateValue?: any;
101
+ context?: Record<string, any>;
105
102
  /**
106
103
  * The state machine model of the observed environment
107
104
  */
@@ -117,20 +114,25 @@ type PromptTemplate<TEvents extends EventObject> = (data: {
117
114
  observations?: AgentObservation<any>[];
118
115
  feedback?: AgentFeedback[];
119
116
  messages?: AgentMessage[];
120
- decisions?: AgentDecision<TEvents>[];
117
+ decisions?: AgentDecision<TAgent>[];
121
118
  }) => string;
122
- type AgentStrategy<T extends AnyAgent> = (agent: T, input: AgentDecideInput<EventsFromAgent<T>>) => Promise<AgentDecision<EventsFromAgent<T>> | undefined>;
123
- type AgentInteractInput<T extends AnyAgent> = Omit<AgentDecideOptions<T>, 'state'>;
124
- type AgentDecideOptions<T extends AnyAgent> = {
119
+ type AgentStrategy<TAgent extends AnyAgent> = (agent: TAgent, input: AgentDecideInput<EventFromAgent<TAgent>>) => Promise<AgentDecision<TAgent> | undefined>;
120
+ type AgentInteractInput<T extends AnyAgent> = Omit<AgentDecideOptions<T>, 'state'> & {
121
+ state?: never;
122
+ };
123
+ type AgentDecideOptions<TAgent extends AnyAgent> = {
125
124
  goal: string;
126
- state: ObservedState;
125
+ state: ObservedState<TAgent>;
126
+ /**
127
+ * The context to provide in the prompt to the agent. This overrides the `state.context`.
128
+ */
127
129
  context?: Record<string, any>;
128
130
  machine?: AnyStateMachine;
129
131
  model?: LanguageModel;
130
132
  execute?: (event: AnyEventObject) => Promise<void>;
131
- strategy?: AgentStrategy<T>;
133
+ strategy?: AgentStrategy<TAgent>;
132
134
  events?: ZodEventMapping;
133
- allowedEvents?: Array<EventsFromAgent<T>['type']>;
135
+ allowedEvents?: Array<EventFromAgent<TAgent>['type']>;
134
136
  /**
135
137
  * The maximum number of times the agent will attempt to make a decision.
136
138
  * Defaults to 2.
@@ -138,8 +140,9 @@ type AgentDecideOptions<T extends AnyAgent> = {
138
140
  maxAttempts?: number;
139
141
  } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt'>;
140
142
  interface AgentFeedback {
141
- goal: string;
142
143
  observationId: string;
144
+ score: number;
145
+ comment: string | undefined;
143
146
  /**
144
147
  * The message correlation that the feedback is relevant for
145
148
  */
@@ -148,9 +151,10 @@ interface AgentFeedback {
148
151
  episodeId: string;
149
152
  }
150
153
  interface AgentFeedbackInput {
151
- goal: string;
152
154
  observationId: string;
153
- attributes: Record<string, any>;
155
+ score: number;
156
+ comment?: string;
157
+ attributes?: Record<string, any>;
154
158
  timestamp?: number;
155
159
  }
156
160
  type AgentMessage = CoreMessage & {
@@ -216,6 +220,7 @@ type AgentMessageInput = CoreMessage & {
216
220
  };
217
221
  interface AgentObservation<TActor extends ActorRefLike> {
218
222
  id: string;
223
+ goal?: string;
219
224
  prevState: SnapshotFrom<TActor> | undefined;
220
225
  event: EventFrom<TActor> | undefined;
221
226
  state: SnapshotFrom<TActor>;
@@ -223,21 +228,22 @@ interface AgentObservation<TActor extends ActorRefLike> {
223
228
  episodeId: string;
224
229
  timestamp: number;
225
230
  }
226
- interface AgentObservationInput {
231
+ interface AgentObservationInput<TAgent extends AnyAgent> {
227
232
  id?: string;
228
- prevState?: ObservedState;
233
+ prevState?: ObservedState<TAgent>;
229
234
  event?: AnyEventObject;
230
- state: ObservedState;
235
+ state: ObservedState<TAgent>;
231
236
  machine?: AnyStateMachine;
232
237
  timestamp?: number;
238
+ goal: string | undefined;
233
239
  }
234
240
  type AgentDecisionInput = {
235
241
  goal: string;
236
242
  model?: LanguageModel;
237
243
  context?: Record<string, any>;
238
244
  } & Omit<Parameters<typeof generateText>[0], 'model' | 'tools' | 'prompt'>;
239
- type AgentDecisionLogic<TEvents extends EventObject> = PromiseActorLogic<AgentDecision<TEvents> | undefined, AgentDecisionInput | string>;
240
- type AgentEmitted<TEvents extends EventObject> = {
245
+ type AgentDecisionLogic<TAgent extends AnyAgent> = PromiseActorLogic<AgentDecision<TAgent> | undefined, AgentDecisionInput | string>;
246
+ type AgentEmitted<TAgent extends AnyAgent> = {
241
247
  type: 'feedback';
242
248
  feedback: AgentFeedback;
243
249
  } | {
@@ -248,9 +254,9 @@ type AgentEmitted<TEvents extends EventObject> = {
248
254
  message: AgentMessage;
249
255
  } | {
250
256
  type: 'decision';
251
- decision: AgentDecision<TEvents>;
257
+ decision: AgentDecision<TAgent>;
252
258
  };
253
- type AgentLogic<TEvents extends EventObject> = ActorLogic<TransitionSnapshot<AgentMemoryContext>, {
259
+ type AgentLogic<TAgent extends AnyAgent> = ActorLogic<TransitionSnapshot<AgentMemoryContext<TAgent>>, {
254
260
  type: 'agent.feedback';
255
261
  feedback: AgentFeedback;
256
262
  } | {
@@ -261,29 +267,29 @@ type AgentLogic<TEvents extends EventObject> = ActorLogic<TransitionSnapshot<Age
261
267
  message: AgentMessage;
262
268
  } | {
263
269
  type: 'agent.decision';
264
- decision: AgentDecision<TEvents>;
270
+ decision: AgentDecision<TAgent>;
265
271
  }, any, // TODO: input
266
- any, AgentEmitted<TEvents>>;
267
- type EventsFromZodEventMapping<TEventSchemas extends ZodEventMapping> = Values<{
272
+ any, AgentEmitted<TAgent>>;
273
+ type EventsFromZodEventMapping<TEventSchemas extends ZodEventMapping> = Compute<Values<{
268
274
  [K in keyof TEventSchemas & string]: {
269
275
  type: K;
270
276
  } & TypeOf<TEventSchemas[K]>;
271
- }>;
277
+ }>>;
272
278
  type ContextFromZodContextMapping<TContextSchema extends ZodContextMapping> = {
273
279
  [K in keyof TContextSchema & string]: TypeOf<TContextSchema[K]>;
274
280
  };
275
281
  type AnyAgent = Agent<any, any, any, any>;
276
282
  type FromAgent<T> = T | ((agent: AnyAgent) => T | Promise<T>);
277
- type CommonTextOptions = {
283
+ type CommonTextOptions<TAgent extends AnyAgent> = {
278
284
  prompt: FromAgent<string>;
279
285
  model?: LanguageModel;
280
- context?: Record<string, any>;
281
286
  messages?: FromAgent<CoreMessage[]>;
282
287
  template?: PromptTemplate<any>;
288
+ context?: Record<string, any>;
283
289
  };
284
- type AgentGenerateTextOptions = Omit<GenerateTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
285
- type AgentStreamTextOptions = Omit<StreamTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions;
286
- interface ObservedState {
290
+ type AgentGenerateTextOptions<TAgent extends AnyAgent> = Omit<GenerateTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions<TAgent>;
291
+ type AgentStreamTextOptions<TAgent extends AnyAgent> = Omit<StreamTextOptions, 'model' | 'prompt' | 'messages'> & CommonTextOptions<TAgent>;
292
+ interface ObservedState<TAgent extends AnyAgent> {
287
293
  /**
288
294
  * The current state value of the state machine, e.g.
289
295
  * `"loading"` or `"processing"` or `"ready"`
@@ -292,32 +298,32 @@ interface ObservedState {
292
298
  /**
293
299
  * Additional contextual data related to the current state
294
300
  */
295
- context?: Record<string, unknown>;
301
+ context?: ContextFromAgent<TAgent>;
296
302
  }
297
303
  type ObservedStateFrom<TActor extends ActorRefLike> = Pick<SnapshotFrom<TActor>, 'value' | 'context'>;
298
- type AgentMemoryContext = {
299
- observations: AgentObservation<any>[];
304
+ type AgentMemoryContext<TAgent extends AnyAgent> = {
305
+ observations: AgentObservation<TAgent>[];
300
306
  messages: AgentMessage[];
301
- decisions: AgentDecision<any>[];
307
+ decisions: AgentDecision<TAgent>[];
302
308
  feedback: AgentFeedback[];
303
309
  };
304
- interface AgentLongTermMemory {
305
- get<K extends keyof AgentMemoryContext>(key: K): Promise<AgentMemoryContext[K]>;
306
- append<K extends keyof AgentMemoryContext>(key: K, item: AgentMemoryContext[K][0]): Promise<void>;
307
- set<K extends keyof AgentMemoryContext>(key: K, items: AgentMemoryContext[K]): Promise<void>;
310
+ interface AgentLongTermMemory<TAgent extends AnyAgent> {
311
+ get<K extends keyof AgentMemoryContext<TAgent>>(key: K): Promise<AgentMemoryContext<TAgent>[K]>;
312
+ append<K extends keyof AgentMemoryContext<TAgent>>(key: K, item: AgentMemoryContext<TAgent>[K][0]): Promise<void>;
313
+ set<K extends keyof AgentMemoryContext<TAgent>>(key: K, items: AgentMemoryContext<TAgent>[K]): Promise<void>;
308
314
  }
309
315
  type Compute<A extends any> = {
310
316
  [K in keyof A]: A[K];
311
317
  } & unknown;
312
318
  type MaybePromise<T> = T | Promise<T>;
313
- type EventsFromAgent<T extends AnyAgent> = T extends Agent<infer _, infer __, infer TEvents, infer ___> ? TEvents : never;
319
+ type EventFromAgent<T extends AnyAgent> = T extends Agent<infer _, infer __, infer TEvents, infer ___> ? TEvents : never;
314
320
  type TypesFromAgent<T extends AnyAgent> = T extends Agent<infer TContextSchema, infer TEventSchema> ? {
315
321
  context: ContextFromZodContextMapping<TContextSchema>;
316
322
  events: EventsFromZodEventMapping<TEventSchema>;
317
323
  } : never;
318
324
  type ContextFromAgent<T extends AnyAgent> = T extends Agent<infer TContextSchema, infer _TEventSchema> ? ContextFromZodContextMapping<TContextSchema> : never;
319
325
 
320
- declare function createAgent<const TContextSchema extends ZodContextMapping, const TEventSchemas extends ZodEventMapping, TEvents extends EventObject = EventsFromZodEventMapping<TEventSchemas>, TContext = ContextFromZodContextMapping<TContextSchema>>({ id, description: description, model, events, context, episodeId, strategy, logic, }: {
326
+ declare function createAgent<const TContextSchema extends ZodContextMapping, const TEventSchemas extends ZodEventMapping, TEvents extends EventObject = EventsFromZodEventMapping<TEventSchemas>, TContext = ContextFromZodContextMapping<TContextSchema>, TAgent extends AnyAgent = Agent<TContextSchema, TEventSchemas>>({ id, description: description, model, events, context, episodeId, strategy, logic, }: {
321
327
  /**
322
328
  * The unique identifier for the agent.
323
329
  *
@@ -348,15 +354,15 @@ declare function createAgent<const TContextSchema extends ZodContextMapping, con
348
354
  /**
349
355
  * A function that retrieves the agent's long term memory
350
356
  */
351
- getMemory?: (agent: Agent<TContextSchema, TEventSchemas>) => AgentLongTermMemory;
357
+ getMemory?: (agent: Agent<TContextSchema, TEventSchemas>) => AgentLongTermMemory<TAgent>;
352
358
  /**
353
359
  * Agent logic
354
360
  */
355
- logic?: AgentLogic<TEvents>;
361
+ logic?: AgentLogic<TAgent>;
356
362
  model: LanguageModel;
357
363
  episodeId?: string;
358
364
  }): Agent<TContextSchema, TEventSchemas>;
359
- declare class Agent<const TContextSchema extends ZodContextMapping, const TEventSchemas extends ZodEventMapping, TEvents extends EventObject = EventsFromZodEventMapping<TEventSchemas>, TContext = ContextFromZodContextMapping<TContextSchema>> extends Actor<AgentLogic<TEvents>> {
365
+ declare class Agent<const TContextSchema extends ZodContextMapping, const TEventSchemas extends ZodEventMapping, TEvents extends EventObject = EventsFromZodEventMapping<TEventSchemas>, TContext = ContextFromZodContextMapping<TContextSchema>> extends Actor<AgentLogic<any>> {
360
366
  /**
361
367
  * The name of the agent. All agents with the same name are related and
362
368
  * able to share experiences (observations, feedback) with each other.
@@ -371,10 +377,10 @@ declare class Agent<const TContextSchema extends ZodContextMapping, const TEvent
371
377
  context?: TContextSchema;
372
378
  strategy: AgentStrategy<Agent<TContextSchema, TEventSchemas>>;
373
379
  model: LanguageModel;
374
- memory: AgentLongTermMemory | undefined;
380
+ memory: AgentLongTermMemory<this> | undefined;
375
381
  defaultOptions: AgentDecideOptions<AnyAgent> | undefined;
376
382
  constructor({ logic, id, name, description, model, events, context, episodeId, strategy, }: {
377
- logic: AgentLogic<TEvents>;
383
+ logic: AgentLogic<any>;
378
384
  id?: string;
379
385
  name?: string;
380
386
  description?: string;
@@ -434,24 +440,25 @@ declare class Agent<const TContextSchema extends ZodContextMapping, const TEvent
434
440
  };
435
441
  getMessages(): AgentMessage[];
436
442
  addFeedback(feedbackInput: AgentFeedbackInput): {
443
+ comment: string | undefined;
437
444
  attributes: {
438
445
  [x: string]: any;
439
446
  };
440
447
  timestamp: number;
441
448
  episodeId: string;
442
- goal: string;
443
449
  observationId: string;
450
+ score: number;
444
451
  };
445
452
  /**
446
453
  * Retrieves feedback from the agent's short-term (local) memory.
447
454
  */
448
455
  getFeedback(): AgentFeedback[];
449
- addObservation(observationInput: AgentObservationInput): AgentObservation<any>;
456
+ addObservation(observationInput: AgentObservationInput<this>): AgentObservation<any>;
450
457
  /**
451
458
  * Retrieves observations from the agent's short-term (local) memory.
452
459
  */
453
460
  getObservations(): AgentObservation<any>[];
454
- addDecision(decision: AgentDecision<TEvents>): void;
461
+ addDecision(decision: AgentDecision<this>): void;
455
462
  /**
456
463
  * Retrieves strategies from the agent's short-term (local) memory.
457
464
  */
@@ -511,18 +518,18 @@ declare class Agent<const TContextSchema extends ZodContextMapping, const TEvent
511
518
  * - The `machine` (e.g. a state machine) that specifies what can happen next
512
519
  * - Additional `context`
513
520
  */
514
- decide(opts: AgentDecideOptions<this>): Promise<AgentDecision<EventsFromAgent<this>> | undefined>;
521
+ decide(opts: AgentDecideOptions<this>): Promise<AgentDecision<this> | undefined>;
515
522
  }
516
523
 
517
- declare function fromTextStream<T extends AnyAgent>(agent: T, options?: AgentStreamTextOptions): ObservableActorLogic<{
524
+ declare function fromTextStream<TAgent extends AnyAgent>(agent: TAgent, options?: AgentStreamTextOptions<TAgent>): ObservableActorLogic<{
518
525
  textDelta: string;
519
- }, Omit<AgentStreamTextOptions, 'context'> & {
520
- context?: AgentStreamTextOptions['context'];
526
+ }, Omit<AgentStreamTextOptions<TAgent>, 'context'> & {
527
+ context?: Record<string, any>;
521
528
  }>;
522
- declare function fromText<T extends AnyAgent>(agent: T, options?: AgentGenerateTextOptions): PromiseActorLogic<GenerateTextResult<Record<string, CoreTool<any, any>>>, Omit<AgentGenerateTextOptions, 'context'> & {
523
- context?: AgentGenerateTextOptions['context'];
529
+ declare function fromText<TAgent extends AnyAgent>(agent: TAgent, options?: AgentGenerateTextOptions<TAgent>): PromiseActorLogic<GenerateTextResult<Record<string, CoreTool<any, any>>>, Omit<AgentGenerateTextOptions<TAgent>, 'context'> & {
530
+ context?: Record<string, any>;
524
531
  }>;
525
532
 
526
- declare function fromDecision<T extends AnyAgent>(agent: T, defaultInput?: AgentDecideInput<EventsFromAgent<T>>): AgentDecisionLogic<any>;
533
+ declare function fromDecision<T extends AnyAgent>(agent: T, defaultInput?: AgentDecideInput<EventFromAgent<T>>): AgentDecisionLogic<any>;
527
534
 
528
- export { type AgentDecideInput, type AgentDecideOptions, type AgentDecision, type AgentDecisionInput, type AgentDecisionLogic, type AgentEmitted, type AgentFeedback, type AgentFeedbackInput, type AgentGenerateTextOptions, type AgentInteractInput, type AgentLogic, type AgentLongTermMemory, type AgentMemoryContext, type AgentMessage, type AgentMessageInput, type AgentObservation, type AgentObservationInput, type AgentPath, type AgentStep, type AgentStrategy, type AgentStreamTextOptions, type AnyAgent, type CommonTextOptions, type Compute, type ContextFromAgent, type ContextFromZodContextMapping, type CostFunction, type EventsFromAgent, type EventsFromZodEventMapping, type FromAgent, type GenerateTextOptions, type LanguageModelV1TextPart, type LanguageModelV1ToolCallPart, type MaybePromise, type ObservedState, type ObservedStateFrom, type PromptTemplate, type StreamTextOptions, type TransitionData, type TypesFromAgent, createAgent, fromDecision, fromText, fromTextStream };
535
+ export { type AgentDecideInput, type AgentDecideOptions, type AgentDecision, type AgentDecisionInput, type AgentDecisionLogic, type AgentEmitted, type AgentFeedback, type AgentFeedbackInput, type AgentGenerateTextOptions, type AgentInteractInput, type AgentLogic, type AgentLongTermMemory, type AgentMemoryContext, type AgentMessage, type AgentMessageInput, type AgentObservation, type AgentObservationInput, type AgentPath, type AgentStep, type AgentStrategy, type AgentStreamTextOptions, type AnyAgent, type CommonTextOptions, type Compute, type ContextFromAgent, type ContextFromZodContextMapping, type CostFunction, type EventFromAgent, type EventsFromZodEventMapping, type FromAgent, type GenerateTextOptions, type LanguageModelV1TextPart, type LanguageModelV1ToolCallPart, type MaybePromise, type ObservedState, type ObservedStateFrom, type PromptTemplate, type StreamTextOptions, type TransitionData, type TypesFromAgent, createAgent, fromDecision, fromText, fromTextStream };
package/dist/index.js CHANGED
@@ -128,6 +128,7 @@ var import_ai = require("ai");
128
128
  // src/templates/defaultText.ts
129
129
  var defaultTextTemplate = (data) => {
130
130
  const preamble = [
131
+ data.stateValue ? wrapInXml("stateValue", JSON.stringify(data.stateValue)) : void 0,
131
132
  data.context ? wrapInXml("context", JSON.stringify(data.context)) : void 0
132
133
  ].filter(Boolean).join("\n");
133
134
  return `
@@ -244,12 +245,16 @@ async function agentDecide(agent, options) {
244
245
  let attempts = 0;
245
246
  const maxAttempts = resolvedOptions.maxAttempts ?? 2;
246
247
  let decision;
248
+ const minimalState = {
249
+ value: state.value,
250
+ context: state.context
251
+ };
247
252
  while (attempts++ < maxAttempts) {
248
253
  decision = await strategy(agent, {
249
254
  model,
250
255
  goal,
251
256
  events: filteredEventSchemas,
252
- state,
257
+ state: minimalState,
253
258
  machine,
254
259
  messages,
255
260
  // TODO: fix UIMessage thing
@@ -275,14 +280,9 @@ function fromDecision(agent, defaultInput) {
275
280
  ...defaultInput,
276
281
  ...inputObject
277
282
  };
278
- const state = {
279
- value: snapshot.value,
280
- context: resolvedInput.context
281
- };
282
283
  const decision = await agentDecide(agent, {
283
284
  machine: parentRef.logic,
284
285
  state: snapshot,
285
- context: resolvedInput.context,
286
286
  execute: async (event) => {
287
287
  parentRef.send(event);
288
288
  },
@@ -350,21 +350,13 @@ async function simpleStrategy(agent, input) {
350
350
  return void 0;
351
351
  }
352
352
  const prompt = simpleStrategyPromptTemplate({
353
- context: input.context,
353
+ stateValue: input.state.value,
354
+ context: input.context ?? input.state.context,
354
355
  goal: input.goal
355
356
  });
356
357
  const messages = await getMessages(agent, prompt, input);
357
358
  const model = input.model ? agent.wrap(input.model) : agent.model;
358
- const {
359
- state,
360
- context,
361
- machine,
362
- prevDecision,
363
- events,
364
- goal,
365
- model: _,
366
- ...rest
367
- } = input;
359
+ const { state, machine, events, goal, model: _, ...rest } = input;
368
360
  const machineState = input.machine && input.state ? input.machine.resolveState({
369
361
  ...input.state,
370
362
  context: input.state.context ?? {}
@@ -391,6 +383,7 @@ async function simpleStrategy(agent, input) {
391
383
  return void 0;
392
384
  }
393
385
  return {
386
+ id: randomId(),
394
387
  strategy: "simple",
395
388
  goal: input.goal,
396
389
  goalState: input.state,
@@ -609,6 +602,7 @@ var Agent = class extends import_xstate4.Actor {
609
602
  addFeedback(feedbackInput) {
610
603
  const feedback = {
611
604
  ...feedbackInput,
605
+ comment: feedbackInput.comment ?? void 0,
612
606
  attributes: { ...feedbackInput.attributes },
613
607
  timestamp: feedbackInput.timestamp ?? Date.now(),
614
608
  episodeId: this.episodeId
@@ -668,15 +662,16 @@ var Agent = class extends import_xstate4.Actor {
668
662
  const agent = this;
669
663
  async function handleObservation(observationInput) {
670
664
  const observation = agent.addObservation(observationInput);
671
- const input = getInput?.(observation);
672
- if (input) {
673
- const res = await agentDecide(agent, {
665
+ const interactInput = getInput?.(observation);
666
+ if (interactInput) {
667
+ const decision = await agentDecide(agent, {
674
668
  machine,
675
669
  state: observation.state,
676
- ...input
670
+ ...interactInput
677
671
  });
678
- if (res?.nextEvent) {
679
- actorRef.send(res.nextEvent);
672
+ if (decision?.nextEvent) {
673
+ decision.nextEvent["_decision"] = decision.id;
674
+ actorRef.send(decision.nextEvent);
680
675
  }
681
676
  }
682
677
  prevState = observationInput.state;
@@ -686,11 +681,14 @@ var Agent = class extends import_xstate4.Actor {
686
681
  if (!subscribed || inspEvent.actorRef !== actorRef || inspEvent.type !== "@xstate.snapshot") {
687
682
  return;
688
683
  }
684
+ const decisionId = inspEvent.event["_decision"];
685
+ const decision = decisionId ? agent.getDecisions().find((d) => d.id === decisionId) : void 0;
689
686
  const observationInput = {
690
687
  event: inspEvent.event,
691
688
  prevState,
692
689
  state: inspEvent.snapshot,
693
- machine: actorRef.src
690
+ machine: actorRef.src,
691
+ goal: decision?.goal
694
692
  };
695
693
  await handleObservation(observationInput);
696
694
  }
@@ -700,7 +698,8 @@ var Agent = class extends import_xstate4.Actor {
700
698
  prevState: void 0,
701
699
  event: void 0,
702
700
  state: actorRef.getSnapshot(),
703
- machine: actorRef.src
701
+ machine: actorRef.src,
702
+ goal: void 0
704
703
  });
705
704
  }
706
705
  return {
@@ -718,11 +717,14 @@ var Agent = class extends import_xstate4.Actor {
718
717
  if (inspEvent.actorRef !== actorRef || inspEvent.type !== "@xstate.snapshot") {
719
718
  return;
720
719
  }
720
+ const decisionId = inspEvent.event["_decision"];
721
+ const decision = decisionId ? this.getDecisions().find((d) => d.id === decisionId) : void 0;
721
722
  const observationInput = {
722
723
  event: inspEvent.event,
723
724
  prevState,
724
725
  state: inspEvent.snapshot,
725
- machine: actorRef.src
726
+ machine: actorRef.src,
727
+ goal: decision?.goal
726
728
  };
727
729
  prevState = observationInput.state;
728
730
  this.addObservation(observationInput);
package/dist/index.mjs CHANGED
@@ -95,6 +95,7 @@ import {
95
95
  // src/templates/defaultText.ts
96
96
  var defaultTextTemplate = (data) => {
97
97
  const preamble = [
98
+ data.stateValue ? wrapInXml("stateValue", JSON.stringify(data.stateValue)) : void 0,
98
99
  data.context ? wrapInXml("context", JSON.stringify(data.context)) : void 0
99
100
  ].filter(Boolean).join("\n");
100
101
  return `
@@ -215,12 +216,16 @@ async function agentDecide(agent, options) {
215
216
  let attempts = 0;
216
217
  const maxAttempts = resolvedOptions.maxAttempts ?? 2;
217
218
  let decision;
219
+ const minimalState = {
220
+ value: state.value,
221
+ context: state.context
222
+ };
218
223
  while (attempts++ < maxAttempts) {
219
224
  decision = await strategy(agent, {
220
225
  model,
221
226
  goal,
222
227
  events: filteredEventSchemas,
223
- state,
228
+ state: minimalState,
224
229
  machine,
225
230
  messages,
226
231
  // TODO: fix UIMessage thing
@@ -246,14 +251,9 @@ function fromDecision(agent, defaultInput) {
246
251
  ...defaultInput,
247
252
  ...inputObject
248
253
  };
249
- const state = {
250
- value: snapshot.value,
251
- context: resolvedInput.context
252
- };
253
254
  const decision = await agentDecide(agent, {
254
255
  machine: parentRef.logic,
255
256
  state: snapshot,
256
- context: resolvedInput.context,
257
257
  execute: async (event) => {
258
258
  parentRef.send(event);
259
259
  },
@@ -321,21 +321,13 @@ async function simpleStrategy(agent, input) {
321
321
  return void 0;
322
322
  }
323
323
  const prompt = simpleStrategyPromptTemplate({
324
- context: input.context,
324
+ stateValue: input.state.value,
325
+ context: input.context ?? input.state.context,
325
326
  goal: input.goal
326
327
  });
327
328
  const messages = await getMessages(agent, prompt, input);
328
329
  const model = input.model ? agent.wrap(input.model) : agent.model;
329
- const {
330
- state,
331
- context,
332
- machine,
333
- prevDecision,
334
- events,
335
- goal,
336
- model: _,
337
- ...rest
338
- } = input;
330
+ const { state, machine, events, goal, model: _, ...rest } = input;
339
331
  const machineState = input.machine && input.state ? input.machine.resolveState({
340
332
  ...input.state,
341
333
  context: input.state.context ?? {}
@@ -362,6 +354,7 @@ async function simpleStrategy(agent, input) {
362
354
  return void 0;
363
355
  }
364
356
  return {
357
+ id: randomId(),
365
358
  strategy: "simple",
366
359
  goal: input.goal,
367
360
  goalState: input.state,
@@ -582,6 +575,7 @@ var Agent = class extends Actor {
582
575
  addFeedback(feedbackInput) {
583
576
  const feedback = {
584
577
  ...feedbackInput,
578
+ comment: feedbackInput.comment ?? void 0,
585
579
  attributes: { ...feedbackInput.attributes },
586
580
  timestamp: feedbackInput.timestamp ?? Date.now(),
587
581
  episodeId: this.episodeId
@@ -641,15 +635,16 @@ var Agent = class extends Actor {
641
635
  const agent = this;
642
636
  async function handleObservation(observationInput) {
643
637
  const observation = agent.addObservation(observationInput);
644
- const input = getInput?.(observation);
645
- if (input) {
646
- const res = await agentDecide(agent, {
638
+ const interactInput = getInput?.(observation);
639
+ if (interactInput) {
640
+ const decision = await agentDecide(agent, {
647
641
  machine,
648
642
  state: observation.state,
649
- ...input
643
+ ...interactInput
650
644
  });
651
- if (res?.nextEvent) {
652
- actorRef.send(res.nextEvent);
645
+ if (decision?.nextEvent) {
646
+ decision.nextEvent["_decision"] = decision.id;
647
+ actorRef.send(decision.nextEvent);
653
648
  }
654
649
  }
655
650
  prevState = observationInput.state;
@@ -659,11 +654,14 @@ var Agent = class extends Actor {
659
654
  if (!subscribed || inspEvent.actorRef !== actorRef || inspEvent.type !== "@xstate.snapshot") {
660
655
  return;
661
656
  }
657
+ const decisionId = inspEvent.event["_decision"];
658
+ const decision = decisionId ? agent.getDecisions().find((d) => d.id === decisionId) : void 0;
662
659
  const observationInput = {
663
660
  event: inspEvent.event,
664
661
  prevState,
665
662
  state: inspEvent.snapshot,
666
- machine: actorRef.src
663
+ machine: actorRef.src,
664
+ goal: decision?.goal
667
665
  };
668
666
  await handleObservation(observationInput);
669
667
  }
@@ -673,7 +671,8 @@ var Agent = class extends Actor {
673
671
  prevState: void 0,
674
672
  event: void 0,
675
673
  state: actorRef.getSnapshot(),
676
- machine: actorRef.src
674
+ machine: actorRef.src,
675
+ goal: void 0
677
676
  });
678
677
  }
679
678
  return {
@@ -691,11 +690,14 @@ var Agent = class extends Actor {
691
690
  if (inspEvent.actorRef !== actorRef || inspEvent.type !== "@xstate.snapshot") {
692
691
  return;
693
692
  }
693
+ const decisionId = inspEvent.event["_decision"];
694
+ const decision = decisionId ? this.getDecisions().find((d) => d.id === decisionId) : void 0;
694
695
  const observationInput = {
695
696
  event: inspEvent.event,
696
697
  prevState,
697
698
  state: inspEvent.snapshot,
698
- machine: actorRef.src
699
+ machine: actorRef.src,
700
+ goal: decision?.goal
699
701
  };
700
702
  prevState = observationInput.state;
701
703
  this.addObservation(observationInput);