@aigne/core 1.72.0-beta.6 → 1.72.0-beta.8

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 (68) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/lib/cjs/agents/agent.d.ts +23 -27
  3. package/lib/cjs/agents/agent.js +16 -8
  4. package/lib/cjs/agents/ai-agent.d.ts +20 -4
  5. package/lib/cjs/agents/ai-agent.js +47 -55
  6. package/lib/cjs/agents/chat-model.d.ts +1 -0
  7. package/lib/cjs/agents/image-model.d.ts +4 -4
  8. package/lib/cjs/agents/mcp-agent.d.ts +2 -2
  9. package/lib/cjs/agents/video-model.d.ts +4 -4
  10. package/lib/cjs/index.d.ts +1 -0
  11. package/lib/cjs/index.js +1 -0
  12. package/lib/cjs/loader/index.d.ts +2 -2
  13. package/lib/cjs/memory/recorder.d.ts +4 -4
  14. package/lib/cjs/memory/retriever.d.ts +4 -4
  15. package/lib/cjs/prompt/agent-session.d.ts +53 -0
  16. package/lib/cjs/prompt/agent-session.js +341 -0
  17. package/lib/cjs/prompt/compact/compactor.d.ts +7 -0
  18. package/lib/cjs/prompt/compact/compactor.js +48 -0
  19. package/lib/cjs/prompt/compact/types.d.ts +79 -0
  20. package/lib/cjs/prompt/compact/types.js +19 -0
  21. package/lib/cjs/prompt/context/afs/history.d.ts +5 -1
  22. package/lib/cjs/prompt/context/afs/history.js +3 -2
  23. package/lib/cjs/prompt/context/afs/index.js +8 -1
  24. package/lib/cjs/prompt/prompt-builder.d.ts +11 -9
  25. package/lib/cjs/prompt/prompt-builder.js +77 -117
  26. package/lib/cjs/prompt/template.d.ts +16 -16
  27. package/lib/dts/agents/agent.d.ts +23 -27
  28. package/lib/dts/agents/ai-agent.d.ts +20 -4
  29. package/lib/dts/agents/chat-model.d.ts +1 -0
  30. package/lib/dts/agents/image-model.d.ts +4 -4
  31. package/lib/dts/agents/mcp-agent.d.ts +2 -2
  32. package/lib/dts/agents/video-model.d.ts +4 -4
  33. package/lib/dts/index.d.ts +1 -0
  34. package/lib/dts/loader/index.d.ts +2 -2
  35. package/lib/dts/memory/recorder.d.ts +4 -4
  36. package/lib/dts/memory/retriever.d.ts +4 -4
  37. package/lib/dts/prompt/agent-session.d.ts +53 -0
  38. package/lib/dts/prompt/compact/compactor.d.ts +7 -0
  39. package/lib/dts/prompt/compact/types.d.ts +79 -0
  40. package/lib/dts/prompt/context/afs/history.d.ts +5 -1
  41. package/lib/dts/prompt/prompt-builder.d.ts +11 -9
  42. package/lib/dts/prompt/template.d.ts +16 -16
  43. package/lib/esm/agents/agent.d.ts +23 -27
  44. package/lib/esm/agents/agent.js +16 -8
  45. package/lib/esm/agents/ai-agent.d.ts +20 -4
  46. package/lib/esm/agents/ai-agent.js +47 -55
  47. package/lib/esm/agents/chat-model.d.ts +1 -0
  48. package/lib/esm/agents/image-model.d.ts +4 -4
  49. package/lib/esm/agents/mcp-agent.d.ts +2 -2
  50. package/lib/esm/agents/video-model.d.ts +4 -4
  51. package/lib/esm/index.d.ts +1 -0
  52. package/lib/esm/index.js +1 -0
  53. package/lib/esm/loader/index.d.ts +2 -2
  54. package/lib/esm/memory/recorder.d.ts +4 -4
  55. package/lib/esm/memory/retriever.d.ts +4 -4
  56. package/lib/esm/prompt/agent-session.d.ts +53 -0
  57. package/lib/esm/prompt/agent-session.js +304 -0
  58. package/lib/esm/prompt/compact/compactor.d.ts +7 -0
  59. package/lib/esm/prompt/compact/compactor.js +44 -0
  60. package/lib/esm/prompt/compact/types.d.ts +79 -0
  61. package/lib/esm/prompt/compact/types.js +16 -0
  62. package/lib/esm/prompt/context/afs/history.d.ts +5 -1
  63. package/lib/esm/prompt/context/afs/history.js +3 -2
  64. package/lib/esm/prompt/context/afs/index.js +8 -1
  65. package/lib/esm/prompt/prompt-builder.d.ts +11 -9
  66. package/lib/esm/prompt/prompt-builder.js +78 -118
  67. package/lib/esm/prompt/template.d.ts +16 -16
  68. package/package.json +4 -4
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.72.0-beta.8](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.72.0-beta.7...core-v1.72.0-beta.8) (2025-12-31)
4
+
5
+
6
+ ### Features
7
+
8
+ * add session compact support for AIAgent ([#863](https://github.com/AIGNE-io/aigne-framework/issues/863)) ([9010918](https://github.com/AIGNE-io/aigne-framework/commit/9010918cd3f18b02b5c60ddc9ed5c34b568d0b28))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **core:** ensure data consistency in async compact mode and load all history entries ([25c7840](https://github.com/AIGNE-io/aigne-framework/commit/25c78406b48f8789a19d59b6d2c82ff859f0113b))
14
+
15
+
16
+ ### Dependencies
17
+
18
+ * The following workspace dependencies were updated
19
+ * dependencies
20
+ * @aigne/afs bumped to 1.4.0-beta.5
21
+ * @aigne/afs-history bumped to 1.2.0-beta.5
22
+
23
+ ## [1.72.0-beta.7](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.72.0-beta.6...core-v1.72.0-beta.7) (2025-12-26)
24
+
25
+
26
+ ### Features
27
+
28
+ * **core:** add session history support ([#858](https://github.com/AIGNE-io/aigne-framework/issues/858)) ([28a070e](https://github.com/AIGNE-io/aigne-framework/commit/28a070ed33b821d1fd344b899706d817ca992b9f))
29
+
30
+
31
+ ### Dependencies
32
+
33
+ * The following workspace dependencies were updated
34
+ * dependencies
35
+ * @aigne/afs bumped to 1.4.0-beta.4
36
+ * @aigne/afs-history bumped to 1.2.0-beta.4
37
+
3
38
  ## [1.72.0-beta.6](https://github.com/AIGNE-io/aigne-framework/compare/core-v1.72.0-beta.5...core-v1.72.0-beta.6) (2025-12-25)
4
39
 
5
40
 
@@ -9,7 +9,7 @@ import type { Memory, MemoryAgent } from "../memory/memory.js";
9
9
  import type { MemoryRecorderInput } from "../memory/recorder.js";
10
10
  import type { MemoryRetrieverInput } from "../memory/retriever.js";
11
11
  import { type Nullish, type PromiseOrValue, type XOr } from "../utils/type-utils.js";
12
- import type { ChatModel } from "./chat-model.js";
12
+ import type { ChatModel, ChatModelInputMessage } from "./chat-model.js";
13
13
  import type { GuideRailAgent, GuideRailAgentOutput } from "./guide-rail-agent.js";
14
14
  import type { ImageModel } from "./image-model.js";
15
15
  import { type GetterSchema, type TransferAgentOutput } from "./types.js";
@@ -118,7 +118,6 @@ export interface AgentOptions<I extends Message = Message, O extends Message = M
118
118
  * agentSucceed, or agentFailed
119
119
  */
120
120
  disableEvents?: boolean;
121
- historyConfig?: Agent["historyConfig"];
122
121
  /**
123
122
  * One or more memory agents this agent can use
124
123
  */
@@ -211,15 +210,15 @@ export declare abstract class Agent<I extends Message = any, O extends Message =
211
210
  parsed: object;
212
211
  }): Promise<Agent<I, O>>;
213
212
  constructor(options?: AgentOptions<I, O>);
213
+ afs?: AFS;
214
+ tag?: string;
214
215
  /**
215
216
  * List of memories this agent can use
216
217
  *
217
218
  * @deprecated use afs instead
218
219
  */
219
220
  readonly memories: MemoryAgent[];
220
- afs?: AFS;
221
221
  asyncMemoryRecord?: boolean;
222
- tag?: string;
223
222
  /**
224
223
  * Maximum number of memory items to retrieve
225
224
  */
@@ -349,11 +348,6 @@ export declare abstract class Agent<I extends Message = any, O extends Message =
349
348
  * agentSucceed, or agentFailed
350
349
  */
351
350
  private disableEvents?;
352
- historyConfig?: {
353
- disabled?: boolean;
354
- maxTokens?: number;
355
- maxItems?: number;
356
- };
357
351
  private subscriptions;
358
352
  /**
359
353
  * Attach agent to context:
@@ -455,7 +449,9 @@ export declare abstract class Agent<I extends Message = any, O extends Message =
455
449
  * @param options Invocation options
456
450
  * @returns Final processed output
457
451
  */
458
- protected processAgentOutput(input: I, output: Exclude<AgentResponse<O>, AgentResponseStream<O>>, options: AgentInvokeOptions): Promise<O>;
452
+ protected processAgentOutput(input: I, output: Exclude<AgentResponse<O>, AgentResponseStream<O>>, { messages, ...options }: AgentInvokeOptions & {
453
+ messages?: ChatModelInputMessage[];
454
+ }): Promise<O>;
459
455
  /**
460
456
  * Process errors that occur during agent execution
461
457
  *
@@ -785,29 +781,29 @@ export interface AgentResponseProgress {
785
781
  error: Error;
786
782
  } | {
787
783
  event: "message";
788
- role: "user" | "agent";
789
- message: ({
790
- type: "text";
791
- content: string;
792
- } | {
793
- type: "thinking";
794
- thoughts: string;
795
- } | {
796
- type: "tool_use";
797
- toolUseId: string;
798
- name: string;
799
- input: unknown;
800
- } | {
801
- type: "tool_result";
802
- toolUseId: string;
803
- content: unknown;
804
- })[];
784
+ message: ChatModelInputMessage;
805
785
  }) & Omit<AgentEvent, "agent"> & {
806
786
  agent: {
807
787
  name: string;
808
788
  };
809
789
  };
810
790
  }
791
+ export type AgentResponseProgressMessageItem = {
792
+ type: "text";
793
+ content: string;
794
+ } | {
795
+ type: "thinking";
796
+ thoughts: string;
797
+ } | {
798
+ type: "tool_use";
799
+ toolUseId: string;
800
+ name: string;
801
+ input: unknown;
802
+ } | {
803
+ type: "tool_result";
804
+ toolUseId: string;
805
+ content: unknown;
806
+ };
811
807
  export declare function isAgentResponseProgress<T>(chunk: AgentResponseChunk<T>): chunk is AgentResponseProgress;
812
808
  /**
813
809
  * Creates a text delta for streaming responses
@@ -152,7 +152,6 @@ class Agent {
152
152
  if (options.skills?.length)
153
153
  this.skills.push(...options.skills.map(functionToAgent));
154
154
  this.disableEvents = options.disableEvents;
155
- this.historyConfig = options.historyConfig;
156
155
  if (Array.isArray(options.memory)) {
157
156
  this.memories.push(...options.memory);
158
157
  }
@@ -179,15 +178,15 @@ class Agent {
179
178
  : options.retryOnError;
180
179
  this.guideRails = options.guideRails;
181
180
  }
181
+ afs;
182
+ tag;
182
183
  /**
183
184
  * List of memories this agent can use
184
185
  *
185
186
  * @deprecated use afs instead
186
187
  */
187
188
  memories = [];
188
- afs;
189
189
  asyncMemoryRecord;
190
- tag;
191
190
  /**
192
191
  * Maximum number of memory items to retrieve
193
192
  */
@@ -332,7 +331,6 @@ class Agent {
332
331
  * agentSucceed, or agentFailed
333
332
  */
334
333
  disableEvents;
335
- historyConfig;
336
334
  subscriptions = [];
337
335
  /**
338
336
  * Attach agent to context:
@@ -463,11 +461,15 @@ class Agent {
463
461
  : (0, stream_utils_js_1.isAsyncGenerator)(response)
464
462
  ? (0, stream_utils_js_1.asyncGeneratorToReadableStream)(response)
465
463
  : (0, stream_utils_js_1.objectToAgentResponseStream)(response);
464
+ const messages = [];
466
465
  for await (const chunk of stream) {
467
466
  (0, stream_utils_js_1.mergeAgentResponseChunk)(output, chunk);
468
467
  yield chunk;
468
+ if (isAgentResponseProgress(chunk) && chunk.progress.event === "message") {
469
+ messages.push(chunk.progress.message);
470
+ }
469
471
  }
470
- let result = await this.processAgentOutput(input, output, options);
472
+ let result = await this.processAgentOutput(input, output, { ...options, messages });
471
473
  if (attempt > 0) {
472
474
  result = { ...result, $meta: { ...result.$meta, retries: attempt } };
473
475
  }
@@ -564,7 +566,7 @@ class Agent {
564
566
  * @param options Invocation options
565
567
  * @returns Final processed output
566
568
  */
567
- async processAgentOutput(input, output, options) {
569
+ async processAgentOutput(input, output, { messages, ...options }) {
568
570
  const { context } = options;
569
571
  if (!(0, type_utils_js_1.isRecord)(output)) {
570
572
  throw new Error(`expect to return a record type such as {result: ...}, but got (${typeof output}): ${output}`);
@@ -576,8 +578,14 @@ class Agent {
576
578
  const o = await this.callHooks(["onSuccess", "onEnd"], { input, output: finalOutput }, options);
577
579
  if (o?.output)
578
580
  finalOutput = o.output;
579
- if (this.historyConfig?.disabled !== true)
580
- this.afs?.emit("agentSucceed", { input, output: finalOutput });
581
+ this.afs?.emit("agentSucceed", {
582
+ agentId: this.name,
583
+ userId: context.userContext.userId,
584
+ sessionId: context.userContext.sessionId,
585
+ input,
586
+ output: finalOutput,
587
+ messages,
588
+ });
581
589
  if (!this.disableEvents)
582
590
  context.emit("agentSucceed", { agent: this, output: finalOutput });
583
591
  return finalOutput;
@@ -1,4 +1,8 @@
1
1
  import { type ZodObject, type ZodType, z } from "zod";
2
+ import { type NestAgentSchema } from "../loader/agent-yaml.js";
3
+ import type { AgentLoadOptions } from "../loader/index.js";
4
+ import { type Instructions } from "../loader/schema.js";
5
+ import type { CompactConfig } from "../prompt/agent-session.js";
2
6
  import { PromptBuilder } from "../prompt/prompt-builder.js";
3
7
  import { Agent, type AgentInvokeOptions, type AgentOptions, type AgentProcessAsyncGenerator, type AgentProcessResult, type Message } from "./agent.js";
4
8
  import type { ChatModel, ChatModelInput } from "./chat-model.js";
@@ -23,8 +27,6 @@ export interface AIAgentOptions<I extends Message = Message, O extends Message =
23
27
  * more complex prompt templates
24
28
  */
25
29
  instructions?: string | PromptBuilder;
26
- autoReorderSystemMessages?: boolean;
27
- autoMergeSystemMessages?: boolean;
28
30
  /**
29
31
  * Pick a message from input to use as the user's message
30
32
  */
@@ -124,6 +126,20 @@ export interface AIAgentOptions<I extends Message = Message, O extends Message =
124
126
  */
125
127
  memoryPromptTemplate?: string;
126
128
  useMemoriesFromContext?: boolean;
129
+ compact?: CompactConfig;
130
+ }
131
+ export interface AIAgentLoadSchema {
132
+ instructions?: Instructions;
133
+ inputKey?: string;
134
+ inputFileKey?: string;
135
+ outputKey?: string;
136
+ outputFileKey?: string;
137
+ toolChoice?: AIAgentToolChoice;
138
+ toolCallsConcurrency?: number;
139
+ keepTextInToolUses?: boolean;
140
+ compact?: Omit<CompactConfig, "compactor"> & {
141
+ compactor?: NestAgentSchema;
142
+ };
127
143
  }
128
144
  /**
129
145
  * Tool choice options for AI agents
@@ -194,6 +210,7 @@ export declare class AIAgent<I extends Message = any, O extends Message = any> e
194
210
  static load<I extends Message = any, O extends Message = any>(options: {
195
211
  filepath: string;
196
212
  parsed: object;
213
+ options?: AgentLoadOptions;
197
214
  }): Promise<Agent<I, O>>;
198
215
  /**
199
216
  * Create an AIAgent with the specified options
@@ -225,8 +242,6 @@ export declare class AIAgent<I extends Message = any, O extends Message = any> e
225
242
  * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-prompt-builder}
226
243
  */
227
244
  instructions: PromptBuilder;
228
- autoReorderSystemMessages?: boolean;
229
- autoMergeSystemMessages?: boolean;
230
245
  /**
231
246
  * Pick a message from input to use as the user's message
232
247
  */
@@ -322,6 +337,7 @@ export declare class AIAgent<I extends Message = any, O extends Message = any> e
322
337
  metadataEnd: string;
323
338
  parse: (raw: string) => object;
324
339
  };
340
+ compact?: CompactConfig;
325
341
  get inputSchema(): ZodType<I>;
326
342
  /**
327
343
  * Process an input message and generate a response
@@ -35,10 +35,10 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.AIAgent = exports.aiAgentOptionsSchema = exports.aiAgentToolChoiceSchema = exports.AIAgentToolChoice = exports.DEFAULT_OUTPUT_FILE_KEY = exports.DEFAULT_OUTPUT_KEY = void 0;
37
37
  const zod_1 = require("zod");
38
+ const agent_yaml_js_1 = require("../loader/agent-yaml.js");
38
39
  const schema_js_1 = require("../loader/schema.js");
39
40
  const prompt_builder_js_1 = require("../prompt/prompt-builder.js");
40
41
  const structured_stream_instructions_js_1 = require("../prompt/prompts/structured-stream-instructions.js");
41
- const template_js_1 = require("../prompt/template.js");
42
42
  const fastq = __importStar(require("../utils/queue.js"));
43
43
  const stream_utils_js_1 = require("../utils/stream-utils.js");
44
44
  const structured_stream_extractor_js_1 = require("../utils/structured-stream-extractor.js");
@@ -124,10 +124,9 @@ class AIAgent extends agent_js_1.Agent {
124
124
  tag = "AIAgent";
125
125
  static schema({ filepath }) {
126
126
  const instructionsSchema = (0, schema_js_1.getInstructionsSchema)({ filepath });
127
+ const nestAgentSchema = (0, agent_yaml_js_1.getNestAgentSchema)({ filepath });
127
128
  return (0, schema_js_1.camelizeSchema)(zod_1.z.object({
128
129
  instructions: (0, schema_js_1.optionalize)(instructionsSchema),
129
- autoReorderSystemMessages: (0, schema_js_1.optionalize)(zod_1.z.boolean()),
130
- autoMergeSystemMessages: (0, schema_js_1.optionalize)(zod_1.z.boolean()),
131
130
  inputKey: (0, schema_js_1.optionalize)(zod_1.z.string()),
132
131
  outputKey: (0, schema_js_1.optionalize)(zod_1.z.string()),
133
132
  inputFileKey: (0, schema_js_1.optionalize)(zod_1.z.string()),
@@ -137,6 +136,13 @@ class AIAgent extends agent_js_1.Agent {
137
136
  keepTextInToolUses: (0, schema_js_1.optionalize)(zod_1.z.boolean()),
138
137
  catchToolsError: (0, schema_js_1.optionalize)(zod_1.z.boolean()),
139
138
  structuredStreamMode: (0, schema_js_1.optionalize)(zod_1.z.boolean()),
139
+ compact: (0, schema_js_1.camelizeSchema)((0, schema_js_1.optionalize)(zod_1.z.object({
140
+ mode: (0, schema_js_1.optionalize)(zod_1.z.enum(["auto", "disabled"])),
141
+ maxTokens: zod_1.z.number().int().min(0).optional(),
142
+ keepRecentRatio: (0, schema_js_1.optionalize)(zod_1.z.number().min(0).max(1)),
143
+ async: (0, schema_js_1.optionalize)(zod_1.z.boolean()),
144
+ compactor: (0, schema_js_1.optionalize)(nestAgentSchema),
145
+ }))),
140
146
  }));
141
147
  }
142
148
  static async load(options) {
@@ -146,6 +152,12 @@ class AIAgent extends agent_js_1.Agent {
146
152
  ...options.parsed,
147
153
  ...valid,
148
154
  instructions: valid.instructions && (0, schema_js_1.instructionsToPromptBuilder)(valid.instructions),
155
+ compact: {
156
+ ...valid.compact,
157
+ compactor: valid.compact?.compactor
158
+ ? await options.options?.loadNestAgent(options.filepath, valid.compact.compactor, options.options)
159
+ : undefined,
160
+ },
149
161
  });
150
162
  }
151
163
  /**
@@ -175,8 +187,6 @@ class AIAgent extends agent_js_1.Agent {
175
187
  typeof options.instructions === "string"
176
188
  ? prompt_builder_js_1.PromptBuilder.from(options.instructions)
177
189
  : (options.instructions ?? new prompt_builder_js_1.PromptBuilder());
178
- this.autoReorderSystemMessages = options.autoReorderSystemMessages ?? true;
179
- this.autoMergeSystemMessages = options.autoMergeSystemMessages ?? true;
180
190
  this.inputKey = options.inputKey;
181
191
  this.inputFileKey = options.inputFileKey;
182
192
  this.outputKey = options.outputKey || exports.DEFAULT_OUTPUT_KEY;
@@ -188,6 +198,7 @@ class AIAgent extends agent_js_1.Agent {
188
198
  this.memoryAgentsAsTools = options.memoryAgentsAsTools;
189
199
  this.memoryPromptTemplate = options.memoryPromptTemplate;
190
200
  this.useMemoriesFromContext = options.useMemoriesFromContext;
201
+ this.compact = options.compact;
191
202
  if (typeof options.catchToolsError === "boolean")
192
203
  this.catchToolsError = options.catchToolsError;
193
204
  this.structuredStreamMode = options.structuredStreamMode;
@@ -213,8 +224,6 @@ class AIAgent extends agent_js_1.Agent {
213
224
  * {@includeCode ../../test/agents/ai-agent.test.ts#example-ai-agent-prompt-builder}
214
225
  */
215
226
  instructions;
216
- autoReorderSystemMessages;
217
- autoMergeSystemMessages;
218
227
  /**
219
228
  * Pick a message from input to use as the user's message
220
229
  */
@@ -305,6 +314,7 @@ class AIAgent extends agent_js_1.Agent {
305
314
  * which outputs structured data in YAML format within <metadata> tags.
306
315
  */
307
316
  customStructuredStreamInstructions;
317
+ compact;
308
318
  get inputSchema() {
309
319
  let schema = super.inputSchema;
310
320
  if (this.inputKey) {
@@ -331,7 +341,7 @@ class AIAgent extends agent_js_1.Agent {
331
341
  const model = this.model || options.model || options.context.model;
332
342
  if (!model)
333
343
  throw new Error("model is required to run AIAgent");
334
- const { toolAgents, ...modelInput } = await this.instructions.build({
344
+ const { toolAgents, session, userMessage, ...modelInput } = await this.instructions.build({
335
345
  ...options,
336
346
  agent: this,
337
347
  input,
@@ -340,23 +350,23 @@ class AIAgent extends agent_js_1.Agent {
340
350
  modelInput.modelOptions = await model.getModelOptions(input, options);
341
351
  const toolsMap = new Map(toolAgents?.map((i) => [i.name, i]));
342
352
  if (this.toolChoice === "router") {
343
- return yield* this._processRouter(input, model, modelInput, options, toolsMap);
353
+ return yield* this._processRouter(input, model, { messages: [...(await session.getMessages()), userMessage], ...modelInput }, options, toolsMap);
344
354
  }
345
- const toolCallMessages = [];
346
- const outputKey = this.outputKey;
347
355
  const inputMessage = this.inputKey ? input[this.inputKey] : undefined;
348
356
  if (inputMessage) {
349
357
  yield {
350
358
  progress: {
351
359
  event: "message",
352
- role: "user",
353
- message: [{ type: "text", content: inputMessage }],
360
+ message: { role: "user", content: [{ type: "text", text: inputMessage }] },
354
361
  },
355
362
  };
356
363
  }
364
+ await session.startMessage(input, userMessage, options);
365
+ // const toolCallMessages: ChatModelInputMessage[] = [];
366
+ const outputKey = this.outputKey;
357
367
  for (;;) {
358
368
  const modelOutput = {};
359
- let stream = await this.invokeChildAgent(model, { ...modelInput, messages: modelInput.messages.concat(toolCallMessages) }, { ...options, streaming: true });
369
+ let stream = await this.invokeChildAgent(model, { messages: await session.getMessages(), ...modelInput }, { ...options, streaming: true });
360
370
  if (this.structuredStreamMode) {
361
371
  const { metadataStart, metadataEnd, parse } = this.customStructuredStreamInstructions || structured_stream_instructions_js_1.STRUCTURED_STREAM_INSTRUCTIONS;
362
372
  stream = stream.pipeThrough(new structured_stream_extractor_js_1.ExtractMetadataTransform({ start: metadataStart, end: metadataEnd, parse }));
@@ -379,15 +389,19 @@ class AIAgent extends agent_js_1.Agent {
379
389
  }
380
390
  }
381
391
  const { toolCalls, json, text, thoughts, files } = modelOutput;
382
- if (text) {
383
- yield {
384
- progress: { event: "message", role: "agent", message: [{ type: "text", content: text }] },
385
- };
386
- }
387
- if (thoughts) {
388
- yield {
389
- progress: { event: "message", role: "agent", message: [{ type: "thinking", thoughts }] },
390
- };
392
+ if (text || thoughts) {
393
+ const content = [];
394
+ if (thoughts) {
395
+ content.push({ type: "text", text: thoughts, isThinking: true });
396
+ }
397
+ if (text) {
398
+ content.push({ type: "text", text });
399
+ }
400
+ if (content.length) {
401
+ const message = { role: "agent", content };
402
+ yield { progress: { event: "message", message } };
403
+ await session.appendCurrentMessages(message);
404
+ }
391
405
  }
392
406
  if (toolCalls?.length) {
393
407
  if (this.keepTextInToolUses !== true) {
@@ -419,25 +433,14 @@ class AIAgent extends agent_js_1.Agent {
419
433
  queue.killAndDrain();
420
434
  }
421
435
  }, this.toolCallsConcurrency || 1);
436
+ const message = { role: "agent", toolCalls };
437
+ yield { progress: { event: "message", message } };
438
+ await session.appendCurrentMessages(message);
422
439
  // Execute tools
423
440
  for (const call of toolCalls) {
424
441
  const tool = toolsMap.get(call.function.name);
425
442
  if (!tool)
426
443
  throw new Error(`Tool not found: ${call.function.name}`);
427
- yield {
428
- progress: {
429
- event: "message",
430
- role: "agent",
431
- message: [
432
- {
433
- type: "tool_use",
434
- name: call.function.name,
435
- input: call.function.arguments,
436
- toolUseId: call.id,
437
- },
438
- ],
439
- },
440
- };
441
444
  queue.push({ tool, call });
442
445
  }
443
446
  await queue.drained();
@@ -446,24 +449,17 @@ class AIAgent extends agent_js_1.Agent {
446
449
  // Continue LLM function calling loop if any tools were executed
447
450
  if (executedToolCalls.length) {
448
451
  for (const { call, output } of executedToolCalls) {
449
- yield {
450
- progress: {
451
- event: "message",
452
- role: "agent",
453
- message: [
454
- {
455
- type: "tool_result",
456
- toolUseId: call.id,
457
- content: output,
458
- },
459
- ],
460
- },
452
+ const message = {
453
+ role: "tool",
454
+ toolCallId: call.id,
455
+ content: JSON.stringify(output),
461
456
  };
457
+ yield { progress: { event: "message", message: message } };
458
+ await session.appendCurrentMessages(message);
462
459
  }
463
460
  const transferOutput = executedToolCalls.find((i) => (0, types_js_1.isTransferAgentOutput)(i.output))?.output;
464
461
  if (transferOutput)
465
462
  return transferOutput;
466
- toolCallMessages.push(await template_js_1.AgentMessageTemplate.from(undefined, executedToolCalls.map(({ call }) => call)).format(), ...(await Promise.all(executedToolCalls.map(({ call, output }) => template_js_1.ToolMessageTemplate.from(output, call.id).format()))));
467
463
  continue;
468
464
  }
469
465
  }
@@ -480,11 +476,7 @@ class AIAgent extends agent_js_1.Agent {
480
476
  if (!(0, type_utils_js_1.isEmpty)(result)) {
481
477
  yield { delta: { json: result } };
482
478
  }
483
- if (text) {
484
- yield {
485
- progress: { event: "message", role: "agent", message: [{ type: "text", content: text }] },
486
- };
487
- }
479
+ await session.endMessage(result, options);
488
480
  return;
489
481
  }
490
482
  }
@@ -225,6 +225,7 @@ export type ChatModelInputMessageContent = string | UnionContent[];
225
225
  export type TextContent = {
226
226
  type: "text";
227
227
  text: string;
228
+ isThinking?: boolean;
228
229
  /**
229
230
  * Cache control marker (only supported by Claude)
230
231
  *
@@ -91,7 +91,6 @@ export declare const imageModelInputSchema: z.ZodObject<{
91
91
  }, "strip", z.ZodTypeAny, {
92
92
  prompt: string;
93
93
  modelOptions?: Record<string, unknown> | undefined;
94
- outputFileType?: "local" | "url" | "file" | undefined;
95
94
  image?: ({
96
95
  type: "url";
97
96
  url: string;
@@ -109,10 +108,10 @@ export declare const imageModelInputSchema: z.ZodObject<{
109
108
  mimeType?: string | undefined;
110
109
  })[] | undefined;
111
110
  n?: number | undefined;
111
+ outputFileType?: "local" | "file" | "url" | undefined;
112
112
  }, {
113
113
  prompt: string;
114
114
  modelOptions?: Record<string, unknown> | undefined;
115
- outputFileType?: "local" | "url" | "file" | undefined;
116
115
  image?: ({
117
116
  type: "url";
118
117
  url: string;
@@ -130,6 +129,7 @@ export declare const imageModelInputSchema: z.ZodObject<{
130
129
  mimeType?: string | undefined;
131
130
  })[] | undefined;
132
131
  n?: number | undefined;
132
+ outputFileType?: "local" | "file" | "url" | undefined;
133
133
  }>;
134
134
  export interface ImageModelOutput extends Message {
135
135
  images: FileUnionContent[];
@@ -232,6 +232,7 @@ export declare const imageModelOutputSchema: z.ZodObject<{
232
232
  filename?: string | undefined;
233
233
  mimeType?: string | undefined;
234
234
  })[];
235
+ model?: string | undefined;
235
236
  usage?: {
236
237
  inputTokens: number;
237
238
  outputTokens: number;
@@ -240,7 +241,6 @@ export declare const imageModelOutputSchema: z.ZodObject<{
240
241
  cacheReadInputTokens?: number | undefined;
241
242
  creditPrefix?: "$" | "€" | "¥" | undefined;
242
243
  } | undefined;
243
- model?: string | undefined;
244
244
  }, {
245
245
  images: ({
246
246
  type: "url";
@@ -258,6 +258,7 @@ export declare const imageModelOutputSchema: z.ZodObject<{
258
258
  filename?: string | undefined;
259
259
  mimeType?: string | undefined;
260
260
  })[];
261
+ model?: string | undefined;
261
262
  usage?: {
262
263
  inputTokens: number;
263
264
  outputTokens: number;
@@ -266,5 +267,4 @@ export declare const imageModelOutputSchema: z.ZodObject<{
266
267
  cacheReadInputTokens?: number | undefined;
267
268
  creditPrefix?: "$" | "€" | "¥" | undefined;
268
269
  } | undefined;
269
- model?: string | undefined;
270
270
  }>;
@@ -64,12 +64,12 @@ export declare class MCPAgent extends Agent {
64
64
  args: ZodType<string[] | undefined, z.ZodTypeDef, string[] | undefined>;
65
65
  }, "strip", z.ZodTypeAny, {
66
66
  url?: string | undefined;
67
- args?: string[] | undefined;
68
67
  command?: string | undefined;
68
+ args?: string[] | undefined;
69
69
  }, {
70
70
  url?: string | undefined;
71
- args?: string[] | undefined;
72
71
  command?: string | undefined;
72
+ args?: string[] | undefined;
73
73
  }>;
74
74
  static load<I extends Message = any, O extends Message = any>(options: {
75
75
  filepath: string;
@@ -94,7 +94,6 @@ export declare const videoModelInputSchema: z.ZodObject<{
94
94
  prompt: string;
95
95
  model?: string | undefined;
96
96
  modelOptions?: Record<string, unknown> | undefined;
97
- outputFileType?: "local" | "url" | "file" | undefined;
98
97
  image?: {
99
98
  type: "url";
100
99
  url: string;
@@ -111,13 +110,13 @@ export declare const videoModelInputSchema: z.ZodObject<{
111
110
  filename?: string | undefined;
112
111
  mimeType?: string | undefined;
113
112
  } | undefined;
113
+ outputFileType?: "local" | "file" | "url" | undefined;
114
114
  size?: string | undefined;
115
115
  seconds?: string | undefined;
116
116
  }, {
117
117
  prompt: string;
118
118
  model?: string | undefined;
119
119
  modelOptions?: Record<string, unknown> | undefined;
120
- outputFileType?: "local" | "url" | "file" | undefined;
121
120
  image?: {
122
121
  type: "url";
123
122
  url: string;
@@ -134,6 +133,7 @@ export declare const videoModelInputSchema: z.ZodObject<{
134
133
  filename?: string | undefined;
135
134
  mimeType?: string | undefined;
136
135
  } | undefined;
136
+ outputFileType?: "local" | "file" | "url" | undefined;
137
137
  size?: string | undefined;
138
138
  seconds?: string | undefined;
139
139
  }>;
@@ -240,6 +240,7 @@ export declare const videoModelOutputSchema: z.ZodObject<{
240
240
  filename?: string | undefined;
241
241
  mimeType?: string | undefined;
242
242
  })[];
243
+ model?: string | undefined;
243
244
  usage?: {
244
245
  inputTokens: number;
245
246
  outputTokens: number;
@@ -248,7 +249,6 @@ export declare const videoModelOutputSchema: z.ZodObject<{
248
249
  cacheReadInputTokens?: number | undefined;
249
250
  creditPrefix?: "$" | "€" | "¥" | undefined;
250
251
  } | undefined;
251
- model?: string | undefined;
252
252
  seconds?: number | undefined;
253
253
  }, {
254
254
  videos: ({
@@ -267,6 +267,7 @@ export declare const videoModelOutputSchema: z.ZodObject<{
267
267
  filename?: string | undefined;
268
268
  mimeType?: string | undefined;
269
269
  })[];
270
+ model?: string | undefined;
270
271
  usage?: {
271
272
  inputTokens: number;
272
273
  outputTokens: number;
@@ -275,6 +276,5 @@ export declare const videoModelOutputSchema: z.ZodObject<{
275
276
  cacheReadInputTokens?: number | undefined;
276
277
  creditPrefix?: "$" | "€" | "¥" | undefined;
277
278
  } | undefined;
278
- model?: string | undefined;
279
279
  seconds?: number | undefined;
280
280
  }>;
@@ -13,6 +13,7 @@ export * from "./agents/user-agent.js";
13
13
  export * from "./agents/video-model.js";
14
14
  export * from "./aigne/index.js";
15
15
  export * from "./memory/index.js";
16
+ export * from "./prompt/agent-session.js";
16
17
  export * from "./prompt/prompt-builder.js";
17
18
  export * from "./prompt/template.js";
18
19
  export * from "./utils/json-utils.js";
package/lib/cjs/index.js CHANGED
@@ -29,6 +29,7 @@ __exportStar(require("./agents/user-agent.js"), exports);
29
29
  __exportStar(require("./agents/video-model.js"), exports);
30
30
  __exportStar(require("./aigne/index.js"), exports);
31
31
  __exportStar(require("./memory/index.js"), exports);
32
+ __exportStar(require("./prompt/agent-session.js"), exports);
32
33
  __exportStar(require("./prompt/prompt-builder.js"), exports);
33
34
  __exportStar(require("./prompt/template.js"), exports);
34
35
  __exportStar(require("./utils/json-utils.js"), exports);