@aigne/core 1.72.0-beta.9 → 1.72.0

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 (78) hide show
  1. package/CHANGELOG.md +342 -0
  2. package/lib/cjs/agents/agent.d.ts +5 -0
  3. package/lib/cjs/agents/agent.js +5 -0
  4. package/lib/cjs/agents/ai-agent.d.ts +41 -5
  5. package/lib/cjs/agents/ai-agent.js +89 -29
  6. package/lib/cjs/agents/chat-model.d.ts +3 -0
  7. package/lib/cjs/agents/chat-model.js +18 -1
  8. package/lib/cjs/agents/image-model.js +1 -1
  9. package/lib/cjs/agents/model.d.ts +3 -3
  10. package/lib/cjs/agents/model.js +2 -2
  11. package/lib/cjs/agents/video-model.js +1 -1
  12. package/lib/cjs/aigne/context.js +1 -3
  13. package/lib/cjs/prompt/agent-session.d.ts +115 -5
  14. package/lib/cjs/prompt/agent-session.js +746 -83
  15. package/lib/cjs/prompt/compact/compactor.js +4 -0
  16. package/lib/cjs/prompt/compact/session-memory-extractor.d.ts +7 -0
  17. package/lib/cjs/prompt/compact/session-memory-extractor.js +143 -0
  18. package/lib/cjs/prompt/compact/types.d.ts +257 -0
  19. package/lib/cjs/prompt/compact/types.js +35 -1
  20. package/lib/cjs/prompt/compact/user-memory-extractor.d.ts +7 -0
  21. package/lib/cjs/prompt/compact/user-memory-extractor.js +124 -0
  22. package/lib/cjs/prompt/prompt-builder.js +3 -3
  23. package/lib/cjs/prompt/skills/afs/agent-skill/agent-skill.d.ts +2 -0
  24. package/lib/cjs/prompt/skills/afs/agent-skill/agent-skill.js +6 -0
  25. package/lib/cjs/prompt/skills/afs/agent-skill/skill-loader.d.ts +1 -2
  26. package/lib/cjs/prompt/skills/afs/agent-skill/skill-loader.js +14 -26
  27. package/lib/cjs/prompt/skills/afs/list.d.ts +2 -0
  28. package/lib/cjs/prompt/skills/afs/list.js +9 -1
  29. package/lib/cjs/prompt/skills/afs/read.d.ts +3 -1
  30. package/lib/cjs/prompt/skills/afs/read.js +5 -0
  31. package/lib/cjs/utils/mcp-utils.js +1 -1
  32. package/lib/cjs/utils/token-estimator.js +1 -1
  33. package/lib/cjs/utils/type-utils.js +0 -1
  34. package/lib/dts/agents/agent.d.ts +5 -0
  35. package/lib/dts/agents/ai-agent.d.ts +41 -5
  36. package/lib/dts/agents/chat-model.d.ts +3 -0
  37. package/lib/dts/agents/model.d.ts +3 -3
  38. package/lib/dts/prompt/agent-session.d.ts +115 -5
  39. package/lib/dts/prompt/compact/session-memory-extractor.d.ts +7 -0
  40. package/lib/dts/prompt/compact/types.d.ts +257 -0
  41. package/lib/dts/prompt/compact/user-memory-extractor.d.ts +7 -0
  42. package/lib/dts/prompt/skills/afs/agent-skill/agent-skill.d.ts +2 -0
  43. package/lib/dts/prompt/skills/afs/agent-skill/skill-loader.d.ts +1 -2
  44. package/lib/dts/prompt/skills/afs/list.d.ts +2 -0
  45. package/lib/dts/prompt/skills/afs/read.d.ts +3 -1
  46. package/lib/esm/agents/agent.d.ts +5 -0
  47. package/lib/esm/agents/agent.js +5 -0
  48. package/lib/esm/agents/ai-agent.d.ts +41 -5
  49. package/lib/esm/agents/ai-agent.js +89 -29
  50. package/lib/esm/agents/chat-model.d.ts +3 -0
  51. package/lib/esm/agents/chat-model.js +18 -1
  52. package/lib/esm/agents/image-model.js +1 -1
  53. package/lib/esm/agents/model.d.ts +3 -3
  54. package/lib/esm/agents/model.js +2 -2
  55. package/lib/esm/agents/video-model.js +1 -1
  56. package/lib/esm/aigne/context.js +2 -4
  57. package/lib/esm/prompt/agent-session.d.ts +115 -5
  58. package/lib/esm/prompt/agent-session.js +744 -84
  59. package/lib/esm/prompt/compact/compactor.js +4 -0
  60. package/lib/esm/prompt/compact/session-memory-extractor.d.ts +7 -0
  61. package/lib/esm/prompt/compact/session-memory-extractor.js +139 -0
  62. package/lib/esm/prompt/compact/types.d.ts +257 -0
  63. package/lib/esm/prompt/compact/types.js +34 -0
  64. package/lib/esm/prompt/compact/user-memory-extractor.d.ts +7 -0
  65. package/lib/esm/prompt/compact/user-memory-extractor.js +120 -0
  66. package/lib/esm/prompt/prompt-builder.js +3 -3
  67. package/lib/esm/prompt/skills/afs/agent-skill/agent-skill.d.ts +2 -0
  68. package/lib/esm/prompt/skills/afs/agent-skill/agent-skill.js +6 -0
  69. package/lib/esm/prompt/skills/afs/agent-skill/skill-loader.d.ts +1 -2
  70. package/lib/esm/prompt/skills/afs/agent-skill/skill-loader.js +13 -24
  71. package/lib/esm/prompt/skills/afs/list.d.ts +2 -0
  72. package/lib/esm/prompt/skills/afs/list.js +9 -1
  73. package/lib/esm/prompt/skills/afs/read.d.ts +3 -1
  74. package/lib/esm/prompt/skills/afs/read.js +5 -0
  75. package/lib/esm/utils/mcp-utils.js +1 -1
  76. package/lib/esm/utils/token-estimator.js +1 -1
  77. package/lib/esm/utils/type-utils.js +0 -1
  78. package/package.json +6 -6
@@ -39,6 +39,7 @@ const agent_yaml_js_1 = require("../loader/agent-yaml.js");
39
39
  const schema_js_1 = require("../loader/schema.js");
40
40
  const prompt_builder_js_1 = require("../prompt/prompt-builder.js");
41
41
  const structured_stream_instructions_js_1 = require("../prompt/prompts/structured-stream-instructions.js");
42
+ const agent_skill_js_1 = require("../prompt/skills/afs/agent-skill/agent-skill.js");
42
43
  const fastq = __importStar(require("../utils/queue.js"));
43
44
  const stream_utils_js_1 = require("../utils/stream-utils.js");
44
45
  const structured_stream_extractor_js_1 = require("../utils/structured-stream-extractor.js");
@@ -125,7 +126,7 @@ class AIAgent extends agent_js_1.Agent {
125
126
  static schema({ filepath }) {
126
127
  const instructionsSchema = (0, schema_js_1.getInstructionsSchema)({ filepath });
127
128
  const nestAgentSchema = (0, agent_yaml_js_1.getNestAgentSchema)({ filepath });
128
- return (0, schema_js_1.camelizeSchema)(zod_1.z.object({
129
+ const schema = (0, schema_js_1.camelizeSchema)(zod_1.z.object({
129
130
  instructions: (0, schema_js_1.optionalize)(instructionsSchema),
130
131
  inputKey: (0, schema_js_1.optionalize)(zod_1.z.string()),
131
132
  outputKey: (0, schema_js_1.optionalize)(zod_1.z.string()),
@@ -136,28 +137,75 @@ class AIAgent extends agent_js_1.Agent {
136
137
  keepTextInToolUses: (0, schema_js_1.optionalize)(zod_1.z.boolean()),
137
138
  catchToolsError: (0, schema_js_1.optionalize)(zod_1.z.boolean()),
138
139
  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
+ session: (0, schema_js_1.optionalize)((0, schema_js_1.camelizeSchema)(zod_1.z.object({
140
141
  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),
142
+ sessionMemory: (0, schema_js_1.optionalize)((0, schema_js_1.camelizeSchema)(zod_1.z.object({
143
+ mode: (0, schema_js_1.optionalize)(zod_1.z.enum(["auto", "disabled"])),
144
+ memoryRatio: (0, schema_js_1.optionalize)(zod_1.z.number().min(0).max(1)),
145
+ queryLimit: (0, schema_js_1.optionalize)(zod_1.z.number().int().min(0)),
146
+ async: (0, schema_js_1.optionalize)(zod_1.z.boolean()),
147
+ extractor: (0, schema_js_1.optionalize)(nestAgentSchema),
148
+ }))),
149
+ userMemory: (0, schema_js_1.optionalize)((0, schema_js_1.camelizeSchema)(zod_1.z.object({
150
+ mode: (0, schema_js_1.optionalize)(zod_1.z.enum(["auto", "disabled"])),
151
+ memoryRatio: (0, schema_js_1.optionalize)(zod_1.z.number().min(0).max(1)),
152
+ queryLimit: (0, schema_js_1.optionalize)(zod_1.z.number().int().min(0)),
153
+ async: (0, schema_js_1.optionalize)(zod_1.z.boolean()),
154
+ extractor: (0, schema_js_1.optionalize)(nestAgentSchema),
155
+ }))),
156
+ compact: (0, schema_js_1.optionalize)((0, schema_js_1.camelizeSchema)(zod_1.z.object({
157
+ mode: (0, schema_js_1.optionalize)(zod_1.z.enum(["auto", "disabled"])),
158
+ maxTokens: zod_1.z.number().int().min(0).optional(),
159
+ keepRecentRatio: (0, schema_js_1.optionalize)(zod_1.z.number().min(0).max(1)),
160
+ async: (0, schema_js_1.optionalize)(zod_1.z.boolean()),
161
+ compactor: (0, schema_js_1.optionalize)(nestAgentSchema),
162
+ }))),
145
163
  }))),
146
164
  }));
165
+ return schema;
147
166
  }
148
167
  static async load(options) {
149
168
  const schema = AIAgent.schema(options);
150
169
  const valid = await schema.parseAsync(options.parsed);
170
+ // Load nested agents from session config if present
171
+ const sessionCompactor = valid.session?.compact?.compactor
172
+ ? await options.options?.loadNestAgent(options.filepath, valid.session.compact.compactor, options.options)
173
+ : undefined;
174
+ const sessionMemoryExtractor = valid.session?.sessionMemory?.extractor
175
+ ? await options.options?.loadNestAgent(options.filepath, valid.session.sessionMemory.extractor, options.options)
176
+ : undefined;
177
+ const userMemoryExtractor = valid.session?.userMemory?.extractor
178
+ ? await options.options?.loadNestAgent(options.filepath, valid.session.userMemory.extractor, options.options)
179
+ : undefined;
180
+ // Build session configuration with loaded agents
181
+ const sessionConfig = valid.session
182
+ ? {
183
+ ...valid.session,
184
+ compact: valid.session.compact
185
+ ? {
186
+ ...valid.session.compact,
187
+ compactor: sessionCompactor,
188
+ }
189
+ : undefined,
190
+ sessionMemory: valid.session.sessionMemory
191
+ ? {
192
+ ...valid.session.sessionMemory,
193
+ extractor: sessionMemoryExtractor,
194
+ }
195
+ : undefined,
196
+ userMemory: valid.session.userMemory
197
+ ? {
198
+ ...valid.session.userMemory,
199
+ extractor: userMemoryExtractor,
200
+ }
201
+ : undefined,
202
+ }
203
+ : undefined;
151
204
  return new AIAgent({
152
205
  ...options.parsed,
153
206
  ...valid,
154
207
  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
- },
208
+ session: sessionConfig,
161
209
  });
162
210
  }
163
211
  /**
@@ -198,7 +246,7 @@ class AIAgent extends agent_js_1.Agent {
198
246
  this.memoryAgentsAsTools = options.memoryAgentsAsTools;
199
247
  this.memoryPromptTemplate = options.memoryPromptTemplate;
200
248
  this.useMemoriesFromContext = options.useMemoriesFromContext;
201
- this.compact = options.compact;
249
+ this.session = options.session;
202
250
  if (typeof options.catchToolsError === "boolean")
203
251
  this.catchToolsError = options.catchToolsError;
204
252
  this.structuredStreamMode = options.structuredStreamMode;
@@ -314,7 +362,10 @@ class AIAgent extends agent_js_1.Agent {
314
362
  * which outputs structured data in YAML format within <metadata> tags.
315
363
  */
316
364
  customStructuredStreamInstructions;
317
- compact;
365
+ /**
366
+ * Agent session configuration
367
+ */
368
+ session;
318
369
  get inputSchema() {
319
370
  let schema = super.inputSchema;
320
371
  if (this.inputKey) {
@@ -400,16 +451,27 @@ class AIAgent extends agent_js_1.Agent {
400
451
  if (content.length) {
401
452
  const message = { role: "agent", content };
402
453
  yield { progress: { event: "message", message } };
403
- await session.appendCurrentMessages(message);
454
+ await session.appendCurrentMessages(message, options);
404
455
  }
405
456
  }
406
- if (toolCalls?.length) {
457
+ const toolCallsWithTools = toolCalls?.map((call) => {
458
+ const tool = toolsMap.get(call.function.name);
459
+ if (!tool)
460
+ throw new Error(`Tool not found: ${call.function.name}`);
461
+ return {
462
+ ...call,
463
+ tool,
464
+ };
465
+ });
466
+ if (toolCallsWithTools?.length) {
407
467
  if (this.keepTextInToolUses !== true) {
408
468
  yield { delta: { json: { [outputKey]: "" } } };
409
469
  }
410
470
  else {
411
471
  yield { delta: { text: { [outputKey]: "\n\n" } } };
412
472
  }
473
+ const toolCallMessage = { role: "agent", toolCalls };
474
+ yield { progress: { event: "message", message: toolCallMessage } };
413
475
  const executedToolCalls = [];
414
476
  let error;
415
477
  const queue = fastq.promise(async ({ tool, call }) => {
@@ -426,40 +488,38 @@ class AIAgent extends agent_js_1.Agent {
426
488
  },
427
489
  };
428
490
  });
429
- executedToolCalls.push({ call, output });
491
+ executedToolCalls.push({ call, tool, output });
430
492
  }
431
493
  catch (e) {
432
494
  error = e;
433
495
  queue.killAndDrain();
434
496
  }
435
497
  }, this.toolCallsConcurrency || 1);
436
- const message = { role: "agent", toolCalls };
437
- yield { progress: { event: "message", message } };
438
- await session.appendCurrentMessages(message);
439
498
  // Execute tools
440
- for (const call of toolCalls) {
441
- const tool = toolsMap.get(call.function.name);
442
- if (!tool)
443
- throw new Error(`Tool not found: ${call.function.name}`);
444
- queue.push({ tool, call });
499
+ for (const call of toolCallsWithTools) {
500
+ queue.push({ tool: call.tool, call });
445
501
  }
446
502
  await queue.drained();
447
503
  if (error)
448
504
  throw error;
505
+ const toolResultMessages = [];
449
506
  // Continue LLM function calling loop if any tools were executed
450
507
  if (executedToolCalls.length) {
451
- for (const { call, output } of executedToolCalls) {
508
+ for (const { call, tool, output } of executedToolCalls) {
509
+ const isAgentSkill = !output.isError && tool instanceof agent_skill_js_1.AgentSkill ? true : undefined;
510
+ const text = await tool.formatOutput(output);
452
511
  const message = {
453
512
  role: "tool",
454
513
  toolCallId: call.id,
455
- content: JSON.stringify(output),
514
+ content: [{ type: "text", text, isAgentSkill }],
456
515
  };
457
516
  yield { progress: { event: "message", message: message } };
458
- await session.appendCurrentMessages(message);
517
+ toolResultMessages.push(message);
459
518
  }
460
519
  const transferOutput = executedToolCalls.find((i) => (0, types_js_1.isTransferAgentOutput)(i.output))?.output;
461
520
  if (transferOutput)
462
521
  return transferOutput;
522
+ await session.appendCurrentMessages([toolCallMessage, ...toolResultMessages], options);
463
523
  continue;
464
524
  }
465
525
  }
@@ -476,7 +536,7 @@ class AIAgent extends agent_js_1.Agent {
476
536
  if (!(0, type_utils_js_1.isEmpty)(result)) {
477
537
  yield { delta: { json: result } };
478
538
  }
479
- await session.endMessage(result, options);
539
+ await session.endMessage(result, undefined, options);
480
540
  return;
481
541
  }
482
542
  }
@@ -57,7 +57,9 @@ export declare abstract class ChatModel extends Model<ChatModelInput, ChatModelO
57
57
  getModelCapabilities(): {
58
58
  supportsParallelToolCalls: boolean;
59
59
  };
60
+ getModelOptions(input: Message, options: AgentInvokeOptions): Promise<ChatModelInputOptions>;
60
61
  private validateToolNames;
62
+ countTokens(input: ChatModelInput): Promise<number>;
61
63
  /**
62
64
  * Normalizes tool names to ensure compatibility with language models
63
65
  *
@@ -226,6 +228,7 @@ export type TextContent = {
226
228
  type: "text";
227
229
  text: string;
228
230
  isThinking?: boolean;
231
+ isAgentSkill?: boolean;
229
232
  /**
230
233
  * Cache control marker (only supported by Claude)
231
234
  *
@@ -40,6 +40,7 @@ const zod_from_json_schema_1 = require("zod-from-json-schema");
40
40
  const schema_js_1 = require("../loader/schema.js");
41
41
  const json_schema_js_1 = require("../utils/json-schema.js");
42
42
  const logger_js_1 = require("../utils/logger.js");
43
+ const token_estimator_js_1 = require("../utils/token-estimator.js");
43
44
  const type_utils_js_1 = require("../utils/type-utils.js");
44
45
  const agent_js_1 = require("./agent.js");
45
46
  const model_js_1 = require("./model.js");
@@ -117,6 +118,19 @@ class ChatModel extends model_js_1.Model {
117
118
  supportsParallelToolCalls: this.supportsParallelToolCalls,
118
119
  };
119
120
  }
121
+ async getModelOptions(input, options) {
122
+ const modelOptions = (await super.getModelOptions(input, options));
123
+ return {
124
+ ...modelOptions,
125
+ cacheConfig: {
126
+ ...modelOptions.cacheConfig,
127
+ autoBreakpoints: {
128
+ ...modelOptions.cacheConfig?.autoBreakpoints,
129
+ lastMessage: modelOptions.cacheConfig?.autoBreakpoints?.lastMessage ?? true,
130
+ },
131
+ },
132
+ };
133
+ }
120
134
  validateToolNames(tools) {
121
135
  for (const tool of tools ?? []) {
122
136
  if (!/^[a-zA-Z0-9_]+$/.test(tool.function.name)) {
@@ -124,6 +138,9 @@ class ChatModel extends model_js_1.Model {
124
138
  }
125
139
  }
126
140
  }
141
+ async countTokens(input) {
142
+ return (0, token_estimator_js_1.estimateTokens)(JSON.stringify(input));
143
+ }
127
144
  /**
128
145
  * Normalizes tool names to ensure compatibility with language models
129
146
  *
@@ -238,7 +255,7 @@ class ChatModel extends model_js_1.Model {
238
255
  const files = zod_1.z.array(model_js_1.fileUnionContentSchema).parse(output.files);
239
256
  output = {
240
257
  ...output,
241
- files: await Promise.all(files.map((file) => this.transformFileType(input.outputFileType, file, options))),
258
+ files: await Promise.all(files.map((file) => this.transformFileType(input.outputFileType, file))),
242
259
  };
243
260
  }
244
261
  // Remove fields with `null` value for validation
@@ -70,7 +70,7 @@ class ImageModel extends model_js_1.Model {
70
70
  const images = zod_1.z.array(model_js_1.fileUnionContentSchema).parse(output.images);
71
71
  output = {
72
72
  ...output,
73
- images: await Promise.all(images.map((image) => this.transformFileType(input.outputFileType, image, options))),
73
+ images: await Promise.all(images.map((image) => this.transformFileType(input.outputFileType, image))),
74
74
  };
75
75
  }
76
76
  return super.processAgentOutput(input, output, options);
@@ -17,9 +17,9 @@ export declare abstract class Model<I extends Message = any, O extends Message =
17
17
  */
18
18
  getModelOptions(input: Message, options: AgentInvokeOptions): Promise<Record<string, unknown>>;
19
19
  protected preprocess(input: I, options: AgentInvokeOptions): Promise<void>;
20
- transformFileType(fileType: "file", data: FileUnionContent, options: AgentInvokeOptions): Promise<FileContent>;
21
- transformFileType(fileType: "local" | undefined, data: FileUnionContent, options: AgentInvokeOptions): Promise<LocalContent>;
22
- transformFileType(fileType: FileType | undefined, data: FileUnionContent, options: AgentInvokeOptions): Promise<FileUnionContent>;
20
+ transformFileType(fileType: "file", data: FileUnionContent): Promise<FileContent>;
21
+ transformFileType(fileType: "local" | undefined, data: FileUnionContent): Promise<LocalContent>;
22
+ transformFileType(fileType: FileType | undefined, data: FileUnionContent): Promise<FileUnionContent>;
23
23
  static getFileExtension(type: string): Promise<string | undefined>;
24
24
  static getMimeType(filename: string): Promise<string | undefined>;
25
25
  downloadFile(url: string): Promise<Response>;
@@ -89,13 +89,13 @@ class Model extends agent_js_1.Agent {
89
89
  Object.assign(input, { modelOptions: await this.getModelOptions(input, options) });
90
90
  return super.preprocess(input, options);
91
91
  }
92
- async transformFileType(fileType = "local", data, options) {
92
+ async transformFileType(fileType = "local", data) {
93
93
  if (fileType === data.type)
94
94
  return data;
95
95
  const common = (0, type_utils_js_1.pick)(data, "filename", "mimeType");
96
96
  switch (fileType) {
97
97
  case "local": {
98
- const dir = index_js_1.nodejs.path.join(index_js_1.nodejs.os.tmpdir(), options.context.id);
98
+ const dir = index_js_1.nodejs.path.join(index_js_1.nodejs.os.tmpdir(), (0, uuid_1.v7)());
99
99
  await index_js_1.nodejs.fs.mkdir(dir, { recursive: true });
100
100
  const ext = await Model.getFileExtension(data.mimeType || data.filename || "");
101
101
  const id = (0, uuid_1.v7)();
@@ -43,7 +43,7 @@ class VideoModel extends model_js_1.Model {
43
43
  const videos = zod_1.z.array(model_js_1.fileUnionContentSchema).parse(output.videos);
44
44
  output = {
45
45
  ...output,
46
- videos: await Promise.all(videos.map((video) => this.transformFileType(input.outputFileType, video, options))),
46
+ videos: await Promise.all(videos.map((video) => this.transformFileType(input.outputFileType, video))),
47
47
  };
48
48
  }
49
49
  return super.processAgentOutput(input, output, options);
@@ -347,11 +347,9 @@ class AIGNEContextShared {
347
347
  }
348
348
  }
349
349
  const stream = await activeAgent.invoke(input, {
350
- hooks: options.hooks,
350
+ ...(0, type_utils_js_1.pick)(options, "hooks", "model", "imageModel", "caller"),
351
351
  context,
352
352
  streaming: true,
353
- model: options.model,
354
- imageModel: options.imageModel,
355
353
  });
356
354
  for await (const value of stream) {
357
355
  if ((0, agent_js_1.isAgentResponseDelta)(value)) {
@@ -1,17 +1,36 @@
1
1
  import type { AFS } from "@aigne/afs";
2
2
  import type { AgentInvokeOptions } from "../agents/agent.js";
3
3
  import type { ChatModelInputMessage } from "../agents/chat-model.js";
4
- import { type CompactConfig, type CompactContent, type EntryContent } from "./compact/types.js";
5
- export type { CompactConfig, CompactContent, EntryContent };
4
+ import { type CompactConfig, type SessionMemoryConfig, type SessionMode, type UserMemoryConfig } from "./compact/types.js";
5
+ export * from "./compact/types.js";
6
6
  export interface AgentSessionOptions {
7
7
  sessionId: string;
8
8
  userId?: string;
9
9
  agentId?: string;
10
10
  afs?: AFS;
11
+ /**
12
+ * Session mode
13
+ * - "auto": Enable history recording, compaction, and memory extraction
14
+ * - "disabled": Disable all session features (history, compaction, memory)
15
+ *
16
+ * **Should be "disabled" for internal utility agents** (extractors, compactors, etc.)
17
+ * to avoid recursive memory extraction and unnecessary overhead.
18
+ *
19
+ * @default DEFAULT_SESSION_MODE ("auto")
20
+ */
21
+ mode?: SessionMode;
11
22
  /**
12
23
  * Compaction configuration
13
24
  */
14
25
  compact?: CompactConfig;
26
+ /**
27
+ * Session memory configuration
28
+ */
29
+ sessionMemory?: SessionMemoryConfig;
30
+ /**
31
+ * User memory configuration
32
+ */
33
+ userMemory?: UserMemoryConfig;
15
34
  }
16
35
  export declare class AgentSession {
17
36
  readonly sessionId: string;
@@ -19,15 +38,36 @@ export declare class AgentSession {
19
38
  readonly agentId?: string;
20
39
  private afs?;
21
40
  private historyModulePath?;
41
+ private mode;
22
42
  private compactConfig;
43
+ private sessionMemoryConfig;
44
+ private userMemoryConfig;
23
45
  private runtimeState;
24
46
  private initialized?;
25
47
  private compactionPromise?;
48
+ private sessionMemoryUpdatePromise?;
49
+ private userMemoryUpdatePromise?;
26
50
  constructor(options: AgentSessionOptions);
51
+ /**
52
+ * Check if memory extraction is enabled
53
+ * Memory extraction requires mode to be "auto" AND AFS history module to be available
54
+ */
55
+ private get isMemoryEnabled();
27
56
  setSystemMessages(...messages: ChatModelInputMessage[]): Promise<void>;
28
57
  getMessages(): Promise<ChatModelInputMessage[]>;
58
+ /**
59
+ * Format user memory facts into a system message
60
+ * Applies token budget limit to ensure memory injection fits within constraints
61
+ */
62
+ private formatUserMemory;
63
+ /**
64
+ * Format session memory facts into a system message
65
+ * Applies token budget limit to ensure memory injection fits within constraints
66
+ */
67
+ private formatSessionMemory;
68
+ private formatMemoryTemplate;
29
69
  startMessage(input: unknown, message: ChatModelInputMessage, options: AgentInvokeOptions): Promise<void>;
30
- endMessage(output: unknown, options: AgentInvokeOptions): Promise<void>;
70
+ endMessage(output: unknown, message: ChatModelInputMessage | undefined, options: AgentInvokeOptions): Promise<void>;
31
71
  /**
32
72
  * Manually trigger compaction
33
73
  */
@@ -36,9 +76,13 @@ export declare class AgentSession {
36
76
  * Internal method that performs the actual compaction
37
77
  */
38
78
  private doCompact;
79
+ private compactCurrentEntry;
80
+ private maybeCompactCurrentEntry;
39
81
  private maybeAutoCompact;
40
82
  /**
41
- * Estimate token count for an array of messages
83
+ * Estimate token count for messages
84
+ * Applies singleMessageLimit to each text block individually
85
+ * Non-text tokens (images, tool calls) are always counted in full
42
86
  */
43
87
  private estimateMessagesTokens;
44
88
  /**
@@ -46,8 +90,74 @@ export declare class AgentSession {
46
90
  * Each batch will not exceed the specified maxTokens
47
91
  */
48
92
  private splitIntoBatches;
49
- appendCurrentMessages(...messages: ChatModelInputMessage[]): Promise<void>;
93
+ appendCurrentMessages(messages: ChatModelInputMessage | ChatModelInputMessage[], options: AgentInvokeOptions): Promise<void>;
94
+ /**
95
+ * Truncate text content to fit within target token limit
96
+ * @param text The text to truncate
97
+ * @param currentTokens Current token count of the text
98
+ * @param targetTokens Target token count after truncation
99
+ * @returns Truncated text
100
+ */
101
+ private truncateText;
102
+ private truncateLargeMessage;
50
103
  private ensureInitialized;
51
104
  private initialize;
105
+ /**
106
+ * Load session memory facts
107
+ * @returns Array of memory fact entries for the current session
108
+ */
109
+ private loadSessionMemory;
110
+ /**
111
+ * Load user memory facts
112
+ * @returns Array of memory fact entries for the current user
113
+ */
114
+ private loadUserMemory;
115
+ /**
116
+ * Load session history including compact content and history entries
117
+ * @returns Object containing history compact and history entries
118
+ */
119
+ private loadSessionHistory;
120
+ /**
121
+ * Manually trigger session memory update
122
+ */
123
+ updateSessionMemory(options: AgentInvokeOptions): Promise<void>;
124
+ private maybeAutoUpdateSessionMemory;
125
+ private maybeAutoUpdateUserMemory;
126
+ /**
127
+ * Internal method that performs the actual session memory update
128
+ */
129
+ private doUpdateSessionMemory;
130
+ /**
131
+ * Manually trigger user memory update
132
+ */
133
+ updateUserMemory(options: AgentInvokeOptions): Promise<void>;
134
+ /**
135
+ * Internal method that performs the actual user memory extraction
136
+ */
137
+ private doUpdateUserMemory;
138
+ /**
139
+ * Find Agent Skill content from a single message
140
+ * @param msg - Message to search in
141
+ * @returns The skill content text if found, undefined otherwise
142
+ */
143
+ private findSkillContentInMessage;
144
+ /**
145
+ * Find the last Agent Skill from a list of messages
146
+ * @param messages - Messages to search through
147
+ * @returns The last Agent Skill found, or undefined if none found
148
+ */
149
+ private findLastAgentSkillFromMessages;
150
+ /**
151
+ * Find the last Agent Skill from a list of history entries
152
+ * @param entries - History entries to search through
153
+ * @returns The last Agent Skill found, or undefined if none found
154
+ */
155
+ private findLastAgentSkill;
52
156
  private initializeDefaultCompactor;
157
+ private initializeDefaultSessionMemoryExtractor;
158
+ private initializeDefaultUserMemoryExtractor;
159
+ private get maxTokens();
160
+ private get keepRecentRatio();
161
+ private get keepRecentTokens();
162
+ private get singleMessageLimit();
53
163
  }