agentic-api 2.0.26 → 2.0.314

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 (90) hide show
  1. package/README.md +224 -60
  2. package/dist/src/agents/agents.example.js +21 -22
  3. package/dist/src/agents/authentication.js +1 -2
  4. package/dist/src/agents/prompts.d.ts +5 -4
  5. package/dist/src/agents/prompts.js +42 -87
  6. package/dist/src/agents/reducer.core.d.ts +24 -2
  7. package/dist/src/agents/reducer.core.js +125 -35
  8. package/dist/src/agents/reducer.loaders.d.ts +55 -1
  9. package/dist/src/agents/reducer.loaders.js +114 -1
  10. package/dist/src/agents/reducer.types.d.ts +45 -2
  11. package/dist/src/agents/semantic.js +1 -2
  12. package/dist/src/agents/simulator.d.ts +4 -0
  13. package/dist/src/agents/simulator.executor.d.ts +5 -1
  14. package/dist/src/agents/simulator.executor.js +41 -9
  15. package/dist/src/agents/simulator.js +86 -28
  16. package/dist/src/agents/simulator.prompts.d.ts +3 -2
  17. package/dist/src/agents/simulator.prompts.js +52 -78
  18. package/dist/src/agents/simulator.types.d.ts +20 -5
  19. package/dist/src/agents/simulator.utils.d.ts +7 -2
  20. package/dist/src/agents/simulator.utils.js +33 -11
  21. package/dist/src/agents/system.js +1 -2
  22. package/dist/src/execute.d.ts +17 -3
  23. package/dist/src/execute.js +156 -158
  24. package/dist/src/index.d.ts +1 -1
  25. package/dist/src/index.js +1 -1
  26. package/dist/src/{princing.openai.d.ts → pricing.llm.d.ts} +6 -0
  27. package/dist/src/pricing.llm.js +234 -0
  28. package/dist/src/prompts.d.ts +13 -4
  29. package/dist/src/prompts.js +221 -114
  30. package/dist/src/rag/embeddings.d.ts +36 -18
  31. package/dist/src/rag/embeddings.js +125 -128
  32. package/dist/src/rag/index.d.ts +5 -5
  33. package/dist/src/rag/index.js +14 -17
  34. package/dist/src/rag/parser.d.ts +2 -1
  35. package/dist/src/rag/parser.js +11 -14
  36. package/dist/src/rag/rag.examples.d.ts +27 -0
  37. package/dist/src/rag/rag.examples.js +151 -0
  38. package/dist/src/rag/rag.manager.d.ts +383 -0
  39. package/dist/src/rag/rag.manager.js +1378 -0
  40. package/dist/src/rag/types.d.ts +128 -12
  41. package/dist/src/rag/types.js +100 -1
  42. package/dist/src/rag/usecase.d.ts +37 -0
  43. package/dist/src/rag/usecase.js +96 -7
  44. package/dist/src/rules/git/git.e2e.helper.js +1 -0
  45. package/dist/src/rules/git/git.health.d.ts +57 -0
  46. package/dist/src/rules/git/git.health.js +281 -1
  47. package/dist/src/rules/git/index.d.ts +2 -2
  48. package/dist/src/rules/git/index.js +12 -1
  49. package/dist/src/rules/git/repo.d.ts +117 -0
  50. package/dist/src/rules/git/repo.js +536 -0
  51. package/dist/src/rules/git/repo.tools.d.ts +22 -1
  52. package/dist/src/rules/git/repo.tools.js +50 -1
  53. package/dist/src/rules/types.d.ts +16 -14
  54. package/dist/src/rules/utils.matter.d.ts +0 -4
  55. package/dist/src/rules/utils.matter.js +26 -7
  56. package/dist/src/scrapper.d.ts +15 -22
  57. package/dist/src/scrapper.js +57 -110
  58. package/dist/src/stategraph/index.d.ts +1 -1
  59. package/dist/src/stategraph/stategraph.d.ts +31 -2
  60. package/dist/src/stategraph/stategraph.js +93 -6
  61. package/dist/src/stategraph/stategraph.storage.js +4 -0
  62. package/dist/src/stategraph/types.d.ts +22 -0
  63. package/dist/src/types.d.ts +4 -2
  64. package/dist/src/types.js +1 -1
  65. package/dist/src/usecase.d.ts +11 -2
  66. package/dist/src/usecase.js +27 -35
  67. package/dist/src/utils.d.ts +32 -18
  68. package/dist/src/utils.js +60 -126
  69. package/package.json +7 -2
  70. package/dist/src/agents/digestor.test.d.ts +0 -1
  71. package/dist/src/agents/digestor.test.js +0 -45
  72. package/dist/src/agents/reducer.example.d.ts +0 -28
  73. package/dist/src/agents/reducer.example.js +0 -118
  74. package/dist/src/agents/reducer.process.d.ts +0 -16
  75. package/dist/src/agents/reducer.process.js +0 -143
  76. package/dist/src/agents/reducer.tools.d.ts +0 -29
  77. package/dist/src/agents/reducer.tools.js +0 -157
  78. package/dist/src/agents/simpleExample.d.ts +0 -3
  79. package/dist/src/agents/simpleExample.js +0 -38
  80. package/dist/src/agents/system-review.d.ts +0 -5
  81. package/dist/src/agents/system-review.js +0 -181
  82. package/dist/src/agents/systemReview.d.ts +0 -4
  83. package/dist/src/agents/systemReview.js +0 -22
  84. package/dist/src/princing.openai.js +0 -54
  85. package/dist/src/rag/tools.d.ts +0 -76
  86. package/dist/src/rag/tools.js +0 -196
  87. package/dist/src/rules/user.mapper.d.ts +0 -61
  88. package/dist/src/rules/user.mapper.js +0 -160
  89. package/dist/src/rules/utils/slug.d.ts +0 -22
  90. package/dist/src/rules/utils/slug.js +0 -35
@@ -53,7 +53,8 @@ function loadScenario(ticketPath) {
53
53
  }
54
54
  /**
55
55
  * Construire SimulationScenario à partir d'un ticket PRSolver (rétrocompatibilité)
56
- * Permet de surcharger tous les champs avec custom (testGoals, testEnd, testPersona, testQuery, testResult, testError)
56
+ * Permet de surcharger tous les champs avec custom
57
+ * Note: Cette fonction retourne un scenario SANS query - il faut la passer séparément à executeSimulation
57
58
  */
58
59
  function buildScenarioFromTicket(ticketPath, clientType, persona = simulator_prompts_1.PERSONA_PATIENT, // PERSONA_PATIENT | PERSONA_PRESSE | PERSONA_ENERVE
59
60
  custom // Surcharge optionnelle de tous les champs
@@ -61,27 +62,48 @@ custom // Surcharge optionnelle de tous les champs
61
62
  const { ticketMarkdown, ticketId } = loadScenario(ticketPath);
62
63
  // Scenario par défaut complet
63
64
  const defaultScenario = {
64
- testGoals: `Valider les Objectifs de PRSolver pour ticket ${ticketId}`,
65
- testEnd: 'Agent termine avec salutations (état 5_cloture)',
66
- testPersona: persona,
67
- testQuery: `Je suis le client (demandeur '${clientType}') du ticket en ANNEXE. Démarre la conversation exactement comme décrit dans l'ANNEXE.
65
+ goals: `Valider les Objectifs de PRSolver pour ticket ${ticketId}. Agent termine avec salutations (état 5_cloture)`,
66
+ persona: persona,
67
+ result: 'done:boolean, error:string, description:string'
68
+ };
69
+ const query = `Je suis le client (demandeur '${clientType}') du ticket en ANNEXE. Démarre la conversation exactement comme décrit dans l'ANNEXE.
68
70
  ## ANNEXE - Ticket ${ticketId}
69
71
  \`\`\`
70
72
  ${ticketMarkdown}
71
73
  \`\`\`
72
- `,
73
- testResult: 'done:boolean, error:string, description:string'
74
- };
74
+ `;
75
75
  // Merger avec custom
76
- return { ...defaultScenario, ...custom };
76
+ return {
77
+ scenario: { ...defaultScenario, ...custom },
78
+ query
79
+ };
77
80
  }
78
81
  /**
79
82
  * Construire SimulationScenario générique directement
83
+ * Supporte l'ancien format (testGoals, testEnd, etc.) pour rétrocompatibilité
80
84
  */
81
85
  function buildGenericScenario(scenario) {
86
+ // Gérer la rétrocompatibilité avec l'ancien format
87
+ if (scenario.testGoals || scenario.testEnd || scenario.testError) {
88
+ // Ancien format détecté - conversion vers le nouveau format
89
+ let goals = scenario.testGoals || '';
90
+ if (scenario.testEnd) {
91
+ goals += `\nCONDITION DE FIN: ${scenario.testEnd}`;
92
+ }
93
+ if (scenario.testError) {
94
+ goals += `\nERREUR FATALE: ${scenario.testError}`;
95
+ }
96
+ return {
97
+ goals: goals.trim(),
98
+ persona: scenario.testPersona || scenario.persona || '',
99
+ result: scenario.testResult || scenario.result || '{"success": boolean, "error": string, "description": string}',
100
+ // Garder testQuery pour extraction ultérieure
101
+ testQuery: scenario.testQuery
102
+ };
103
+ }
104
+ // Nouveau format - juste ajouter un result par défaut si manquant
82
105
  return {
83
106
  ...scenario,
84
- // Assurer le format par défaut si pas spécifié
85
- testResult: scenario.testResult || 'done:boolean, error:string, description:string'
107
+ result: scenario.result || '{"success": boolean, "error": string, "description": string}'
86
108
  };
87
109
  }
@@ -1,13 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.system = void 0;
4
- const execute_1 = require("../execute");
5
4
  const utils_1 = require("../utils");
6
5
  const prompts_1 = require("./prompts");
7
6
  exports.system = {
8
7
  name: "systemReview",
9
8
  human: true,
10
- model: (0, execute_1.modelConfig)("MEDIUM"),
9
+ model: "MEDIUM",
11
10
  publicDescription: "Agent chargé d'analyser le contenu d'un prompt système et de présenter ses remarques",
12
11
  instructions: prompts_1.systemReviewPrompt,
13
12
  tools: [],
@@ -1,6 +1,7 @@
1
1
  import { AgentConfig, AgenticContext, AgentModel, ExecuteAgentResult, Feedback, ExecutionResult } from "./types";
2
2
  import { Writable } from "stream";
3
3
  import { AgentStateGraph } from "./stategraph";
4
+ export declare const DummyWritable: any;
4
5
  export declare function modelConfig(model: string, custom?: any): AgentModel;
5
6
  export declare function sendFeedback(params: Feedback): void;
6
7
  export interface ReadCompletionsStreamOptions {
@@ -8,7 +9,7 @@ export interface ReadCompletionsStreamOptions {
8
9
  discussion: any;
9
10
  agentConfig: AgentConfig;
10
11
  agents: AgentConfig[];
11
- agentName: string;
12
+ discussionRootAgent: string;
12
13
  stdout: Writable;
13
14
  session: AgenticContext;
14
15
  final: any;
@@ -19,19 +20,22 @@ export declare function readCompletionsStream(params: ReadCompletionsStreamOptio
19
20
  /**
20
21
  * Parameters for executing an agent set
21
22
  * @interface ExecuteAgentSetParams
22
- * @property {OpenAI} openai - OpenAI client instance
23
23
  * @property {string} query - User query to process
24
24
  * @property {string} home - Name of the agent to start with
25
25
  * @property {Writable} stdout - Stream to write output to
26
+ * @property {any[]} [messages] - Messages to add to the conversation
26
27
  * @property {boolean} [verbose] - Whether to log verbose debug information
27
- * @property {number} [maxSteps] - Maximum number of steps to execute
28
28
  */
29
29
  export interface ExecuteAgentSetParams {
30
30
  enrichWithMemory?: (role: string, agent: AgentConfig, context: AgenticContext) => Promise<string>;
31
31
  query: string;
32
32
  home?: string;
33
+ model?: string;
33
34
  stdout: Writable;
35
+ messages?: any[];
34
36
  verbose?: boolean;
37
+ json?: boolean;
38
+ schema?: any;
35
39
  debug?: boolean;
36
40
  }
37
41
  /**
@@ -47,3 +51,13 @@ export interface ExecuteAgentSetParams {
47
51
  */
48
52
  export declare function executeAgentSet(agentSet: AgentConfig[], context: AgenticContext, params: ExecuteAgentSetParams): Promise<ExecutionResult>;
49
53
  export declare function executeAgent(agentSet: AgentConfig[], params: ExecuteAgentSetParams): Promise<ExecuteAgentResult>;
54
+ /**
55
+ * Executes a simple query without agent orchestration or tool handling
56
+ *
57
+ * This is the simplest level of execution - just sends a query to the LLM
58
+ * and returns the response. No tools, no agent transfers, no complex logic.
59
+ *
60
+ * @param params - Execution parameters including query and model config
61
+ * @returns Promise<ExecuteAgentResult> - Simple result with usage and content
62
+ */
63
+ export declare function executeQuery(params: ExecuteAgentSetParams): Promise<ExecuteAgentResult>;
@@ -1,112 +1,25 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DummyWritable = void 0;
3
4
  exports.modelConfig = modelConfig;
4
5
  exports.sendFeedback = sendFeedback;
5
6
  exports.readCompletionsStream = readCompletionsStream;
6
7
  exports.executeAgentSet = executeAgentSet;
7
8
  exports.executeAgent = executeAgent;
8
- const princing_openai_1 = require("./princing.openai");
9
+ exports.executeQuery = executeQuery;
9
10
  const types_1 = require("./types");
10
11
  const utils_1 = require("./utils");
11
12
  const stategraph_1 = require("./stategraph");
13
+ const pricing_llm_1 = require("./pricing.llm");
14
+ exports.DummyWritable = {
15
+ write: () => { }
16
+ };
12
17
  function modelConfig(model, custom) {
13
18
  const defaultOptions = Object.assign({
14
19
  stream_options: { "include_usage": true },
15
20
  }, custom || {});
16
- const mapping = {
17
- "LOW-fast": {
18
- temperature: 1,
19
- frequency_penalty: 0.0,
20
- presence_penalty: 0.0,
21
- model: "gpt-5-nano",
22
- reasoning_effort: "minimal",
23
- verbosity: "low",
24
- stream: true
25
- },
26
- "LOW": {
27
- temperature: 1,
28
- frequency_penalty: 0.0,
29
- presence_penalty: 0.0,
30
- model: "gpt-5-nano",
31
- reasoning_effort: "medium",
32
- verbosity: "low",
33
- stream: true
34
- },
35
- "MEDIUM-fast": {
36
- temperature: 1,
37
- frequency_penalty: 0.0,
38
- presence_penalty: 0.0,
39
- model: "gpt-5-mini",
40
- reasoning_effort: "minimal",
41
- verbosity: "low",
42
- stream: true
43
- },
44
- "LOW-4.1": {
45
- temperature: .2,
46
- frequency_penalty: 0.0,
47
- presence_penalty: 0.0,
48
- model: "gpt-4.1-nano",
49
- stream: true
50
- },
51
- "MEDIUM-4.1-mini": {
52
- temperature: .2,
53
- frequency_penalty: 0.0,
54
- presence_penalty: 0.0,
55
- model: "gpt-4.1-mini",
56
- stream: true
57
- },
58
- "MEDIUM-4.1": {
59
- temperature: .2,
60
- frequency_penalty: 0.0,
61
- presence_penalty: 0.0,
62
- model: "gpt-4.1",
63
- stream: true
64
- },
65
- "MEDIUM": {
66
- temperature: 1,
67
- frequency_penalty: 0.0,
68
- presence_penalty: 0.0,
69
- model: "gpt-5-mini",
70
- reasoning_effort: "low",
71
- verbosity: "low",
72
- stream: true
73
- },
74
- "HIGH-fast": {
75
- model: "gpt-5",
76
- reasoning_effort: "minimal",
77
- verbosity: "low",
78
- temperature: 1,
79
- stream: true
80
- },
81
- "HIGH-low": {
82
- model: "gpt-5",
83
- reasoning_effort: "low",
84
- verbosity: "low",
85
- stream: true
86
- },
87
- "HIGH-medium": {
88
- model: "gpt-5",
89
- reasoning_effort: "medium",
90
- verbosity: "low",
91
- stream: true
92
- },
93
- "SEARCH": {
94
- temperature: 0.2,
95
- frequency_penalty: 0.0,
96
- presence_penalty: 0.0,
97
- model: "gpt-4o-mini-search-preview",
98
- web_search_options: {
99
- user_location: {
100
- type: "approximate",
101
- approximate: {
102
- country: "CH",
103
- city: "Geneva",
104
- region: "Geneva",
105
- },
106
- },
107
- },
108
- },
109
- };
21
+ // Get mapping based on provider
22
+ const mapping = (0, pricing_llm_1.LLM)((0, utils_1.openaiInstance)());
110
23
  const options = Object.assign(mapping[model], defaultOptions);
111
24
  return options;
112
25
  }
@@ -129,13 +42,13 @@ async function readCompletionsStream(params) {
129
42
  const openai = (0, utils_1.openaiInstance)();
130
43
  //
131
44
  // set default context here
132
- const { stateGraph, discussion, agentConfig, agents, agentName, stdout, final, session, verbose } = params;
133
- const model = agentConfig.model.model;
45
+ const { stateGraph, discussion, agentConfig, agents, discussionRootAgent, stdout, final, session, verbose } = params;
46
+ const model = modelConfig(agentConfig.model).model;
134
47
  const accumulatedFunctionCall = final.choices[0]?.message.tool_calls || [];
135
48
  const content = final.choices[0]?.message.content;
136
49
  let thinking = false;
137
50
  let localResult = (0, types_1.enrichExecutionResult)({
138
- runId: `${agentName}-${Date.now()}`,
51
+ runId: `${discussionRootAgent}-${Date.now()}`,
139
52
  startQuery: '',
140
53
  actions: [],
141
54
  lastMessage: '',
@@ -143,8 +56,8 @@ async function readCompletionsStream(params) {
143
56
  moreThinkin: false,
144
57
  });
145
58
  // Accumulate cost in the discussion usage
146
- (0, princing_openai_1.accumulateCost)(discussion.usage, model, final.usage);
147
- stateGraph.updateTokens(agentName, {
59
+ (0, pricing_llm_1.accumulateCost)(discussion.usage, model, final.usage);
60
+ stateGraph.updateTokens(discussionRootAgent, {
148
61
  prompt: final.usage?.prompt_tokens || 0,
149
62
  completion: final.usage?.completion_tokens || 0,
150
63
  total: final.usage?.total_tokens || 0,
@@ -155,7 +68,7 @@ async function readCompletionsStream(params) {
155
68
  if (content) {
156
69
  if (verbose)
157
70
  console.log("✅ Agent (1): 🌶️🌶️🌶️ save content:", content?.length);
158
- stateGraph.push(agentName, { role: "assistant", content });
71
+ stateGraph.push(discussionRootAgent, { role: "assistant", content });
159
72
  }
160
73
  // Si le modèle décide d'appeler une fonction (par exemple "transferAgents")
161
74
  for (const functionCall of accumulatedFunctionCall) {
@@ -177,7 +90,7 @@ async function readCompletionsStream(params) {
177
90
  // {content, usage} {did_transfer}
178
91
  thinking = functionCallResult.thinking;
179
92
  if (functionCallResult.usage) {
180
- stateGraph.updateTokens(agentName, {
93
+ stateGraph.updateTokens(discussionRootAgent, {
181
94
  prompt: functionCallResult.usage.prompt || 0,
182
95
  completion: functionCallResult.usage.completion || 0,
183
96
  total: functionCallResult.usage.total || 0,
@@ -185,51 +98,33 @@ async function readCompletionsStream(params) {
185
98
  });
186
99
  }
187
100
  if (functionCallResult.did_transfer) {
188
- // record transfer action
189
- localResult.actions.push({
190
- action: 'transfert',
191
- content: functionCallResult.destination_agent || currentAgentRef.name,
192
- feedback: functionCallResult.feedback,
193
- });
194
101
  if (verbose)
195
- console.log("✅ Agent transfer response:", functionCallResult.source_agent, ' call function ', functionCall.function.name, '::to', functionCallResult.destination_agent, ' transfer done ✅');
102
+ console.log("✅ Agent transfer response:", functionCallResult.source_agent, '::to', functionCallResult.destination_agent, '::with', functionCallResult.content, ' transfer done ✅');
196
103
  // Mise à jour du message système avec les nouvelles instructions du nouvel agent courant
197
104
  const transferredAgent = agents.find(a => a.name === currentAgentRef.name) || agentConfig;
198
105
  const instructions = transferredAgent.instructions;
199
- const enrichedInstructions = await params.enrichWithMemory?.("system", transferredAgent, session);
200
- stateGraph.set(agentName, instructions + '\n' + enrichedInstructions);
201
- // Ajout de la réponse de l'appel de fonction dans le contexte conversationnel
202
- const message = functionCallResult.content ?? `Le transfert vers l'agent "${transferredAgent.name}" a été effectué, Tu dois répondre immédiatement à la question.`;
203
- stateGraph.push(agentName, {
204
- role: "assistant",
205
- content: message,
206
- name: functionCallResult.name
207
- });
208
- // Immediately surface the tool confirmation to the user output
209
- // feedback or message?
210
- if (message) {
211
- stdout.write(message + "\n");
106
+ const enrichedInstructions = (await params.enrichWithMemory?.("system", transferredAgent, session)) || '';
107
+ // Set préserve le trail existant via updateSystemMessage()
108
+ stateGraph.set(discussionRootAgent, instructions + '\n' + enrichedInstructions);
109
+ //
110
+ // Display only explicit content to stdout (usually empty for silent transfers)
111
+ if (functionCallResult.content) {
112
+ stdout.write(functionCallResult.content + "\n");
212
113
  }
213
114
  }
214
115
  //
215
116
  // other function call have a result
216
117
  else if (functionCallResult.content) {
217
- // record tool action
218
- localResult.actions.push({
219
- action: functionCall?.function?.name,
220
- content: functionCallResult.content || '',
221
- feedback: functionCallResult.feedback,
222
- });
223
118
  // console.log("✅ Agent tool response:",agentConfig.name,'::',functionCall.function.name, ' with content',functionCallResult.content);
224
- stateGraph.push(agentName, {
119
+ stateGraph.push(discussionRootAgent, {
225
120
  role: "assistant",
226
121
  content: functionCallResult.content,
227
122
  name: functionCallResult.name
228
123
  });
229
124
  }
230
125
  //
231
- // send user feedback
232
- if (functionCallResult.feedback) {
126
+ // send user feedback (if not already sent via addStep for transfer)
127
+ if (functionCallResult.feedback && !functionCallResult.did_transfer) {
233
128
  sendFeedback({
234
129
  agent: agentConfig.name,
235
130
  stdout,
@@ -242,15 +137,15 @@ async function readCompletionsStream(params) {
242
137
  // Réactualisation de la liste des outils pour le nouvel agent courant
243
138
  const currentAgent = agents.find(a => a.name === currentAgentRef.name) || agentConfig;
244
139
  const tools = currentAgent?.tools || [];
245
- const followUpOptions = Object.assign({}, currentAgent?.model);
140
+ const followUpOptions = Object.assign({}, modelConfig(currentAgent.model));
246
141
  followUpOptions.messages = discussion.messages;
247
- //
248
- // always force HIGH model for follow up
249
- followUpOptions.model = currentAgent.model.model;
250
142
  if (tools.length > 0) {
251
143
  followUpOptions.tools = tools;
252
144
  followUpOptions.tool_choice = "auto";
253
145
  }
146
+ // console.log("✅ DEBUG followUpOptions (tools):",currentAgentRef.name,'\n',JSON.stringify(followUpOptions,null,2));
147
+ // console.log("✅ DEBUG followUpOptions (tools):",currentAgentRef.name,tools.length, tools[0]?.function?.parameters?.properties?.destination_agent);
148
+ // console.log("✅ DEBUG followUpOptions (system):",discussion.messages[0]?.content);
254
149
  // if(!functionCallResult.did_transfer) {
255
150
  // followUpOptions.tool_choice = "none";
256
151
  // }
@@ -264,6 +159,16 @@ async function readCompletionsStream(params) {
264
159
  }
265
160
  }
266
161
  const final = await followUpStream.finalChatCompletion();
162
+ //
163
+ // ✅ addStep APRÈS la réponse de l'agent (pour avoir le trail complet au prochain tour)
164
+ if (functionCallResult.feedback) {
165
+ stateGraph.addStep(discussionRootAgent, {
166
+ tool: functionCallResult.name,
167
+ context: functionCallResult.context || '',
168
+ reason: functionCallResult.feedback,
169
+ id: functionCallResult.id
170
+ });
171
+ }
267
172
  // console.log("✅ DEBUG followUpOptions (OUT content):",final.choices[0]?.message.content);
268
173
  // console.log("✅ DEBUG followUpOptions (OUT tool_calls):",final.choices[0]?.message.tool_calls);
269
174
  //
@@ -275,7 +180,7 @@ async function readCompletionsStream(params) {
275
180
  discussion,
276
181
  agentConfig: currentAgent,
277
182
  agents,
278
- agentName,
183
+ discussionRootAgent, // ✅ Renommé de agentName pour clarté
279
184
  stdout,
280
185
  final,
281
186
  session,
@@ -283,10 +188,16 @@ async function readCompletionsStream(params) {
283
188
  enrichWithMemory: params.enrichWithMemory
284
189
  });
285
190
  localResult = (0, types_1.executionResultMerge)(localResult, partial);
191
+ // ✅ Convertir steps en actions avant de retourner
192
+ localResult.actions = stateGraph.steps(discussionRootAgent).map(step => ({
193
+ action: step.tool,
194
+ content: step.context,
195
+ feedback: step.reason
196
+ }));
286
197
  return localResult;
287
198
  }
288
199
  // Accumulate final cost
289
- stateGraph.updateTokens(agentName, {
200
+ stateGraph.updateTokens(discussionRootAgent, {
290
201
  prompt: final.usage?.prompt_tokens || 0,
291
202
  completion: final.usage?.completion_tokens || 0,
292
203
  total: final.usage?.total_tokens || 0,
@@ -308,14 +219,20 @@ async function readCompletionsStream(params) {
308
219
  await params.enrichWithMemory?.("assistant", currentAgent, session);
309
220
  // if(verbose) console.log("✅ Agent (OUT):",currentAgent.name, 'with content length',!!content);
310
221
  if (content) {
311
- stateGraph.push(agentName, { role: "assistant", content });
222
+ stateGraph.push(discussionRootAgent, { role: "assistant", content });
312
223
  }
313
224
  if (content?.includes('<continue>')) {
314
225
  localResult.moreThinkin = true;
315
- return localResult;
316
226
  }
317
- return localResult;
318
227
  }
228
+ //
229
+ // ✅ Convertir steps en actions une seule fois avant de retourner
230
+ const allSteps = stateGraph.steps(discussionRootAgent);
231
+ localResult.actions = allSteps.map(step => ({
232
+ action: step.tool,
233
+ content: step.context,
234
+ feedback: step.reason
235
+ }));
319
236
  return localResult;
320
237
  }
321
238
  /**
@@ -333,15 +250,15 @@ async function executeAgentSet(agentSet, context, params) {
333
250
  const { query, verbose } = params;
334
251
  const openai = (0, utils_1.openaiInstance)();
335
252
  const agents = (0, utils_1.injectTransferTools)(agentSet);
336
- const home = params.home || agents[0].name;
253
+ // 🔑 CLÉ DE DISCUSSION: Agent racine qui sert de point d'entrée
254
+ // Cette clé reste FIXE même après des transferts, permettant de garder l'historique unifié
255
+ const discussionRootAgent = params.home || agents[0].name;
337
256
  // 🎯 Récupération du StateGraph depuis le context (qui contient session, user, credential, etc.)
338
257
  const stateGraph = (0, stategraph_1.sessionStateGraphGet)(context);
339
- // 📍 Agent spécialisé (persistant) vs Agent contextuel (temporaire)
340
- const specializedAgent = home;
341
- const discussion = stateGraph.createOrRestore(specializedAgent);
342
- let currentAgent = (0, stategraph_1.getSpecializedAgent)(discussion) || specializedAgent;
343
- // Référence mutable pour handleTransferCall
344
- const currentAgentRef = { name: currentAgent };
258
+ // 📍 Créer ou restaurer la discussion pour cet agent racine
259
+ const discussion = stateGraph.createOrRestore(discussionRootAgent);
260
+ // 🔄 Agent courant: peut différer de l'agent racine après des transferts
261
+ let currentAgent = (0, stategraph_1.getSpecializedAgent)(discussion) || discussionRootAgent;
345
262
  // Trouver la config de l'agent courant
346
263
  const currentAgentConfig = agents.find(a => a.name === currentAgent);
347
264
  discussion.description = currentAgentConfig?.publicDescription;
@@ -360,7 +277,7 @@ async function executeAgentSet(agentSet, context, params) {
360
277
  // Handle two-shot prompting: if instructions is an array, use the first part as a system message
361
278
  const enrichedInstructions = await params.enrichWithMemory?.("system", currentAgentConfig, context);
362
279
  const instructions = currentAgentConfig.instructions + '\n' + enrichedInstructions;
363
- stateGraph.set(specializedAgent, instructions);
280
+ stateGraph.set(discussionRootAgent, instructions);
364
281
  }
365
282
  else {
366
283
  // enrich the user query with memory as User
@@ -368,7 +285,7 @@ async function executeAgentSet(agentSet, context, params) {
368
285
  }
369
286
  // Append the user's query to the session-specific messages
370
287
  // input: `${getMemoryString(relevantMemories)}\n${input}`,
371
- stateGraph.push(specializedAgent, { role: "user", content: enrichedQuery });
288
+ stateGraph.push(discussionRootAgent, { role: "user", content: enrichedQuery });
372
289
  // Les outils (définition des fonctions) disponibles par l'agent courant
373
290
  const tools = currentAgentConfig.tools;
374
291
  // console.log('--- DBG toolLogic (1)',currentAgentConfig, currentAgentConfig?.toolLogic);
@@ -377,7 +294,7 @@ async function executeAgentSet(agentSet, context, params) {
377
294
  }
378
295
  // let shots = 1;
379
296
  let result = (0, types_1.enrichExecutionResult)({
380
- runId: `${specializedAgent}-${Date.now()}`,
297
+ runId: `${discussionRootAgent}-${Date.now()}`,
381
298
  startQuery: query,
382
299
  actions: [],
383
300
  lastMessage: '',
@@ -385,7 +302,8 @@ async function executeAgentSet(agentSet, context, params) {
385
302
  moreThinkin: false,
386
303
  });
387
304
  do {
388
- const options = Object.assign({}, currentAgentConfig?.model);
305
+ const model = modelConfig(currentAgentConfig.model);
306
+ const options = Object.assign({}, model);
389
307
  options.messages = discussion.messages;
390
308
  if (tools.length > 0) {
391
309
  options.tools = tools;
@@ -419,7 +337,7 @@ async function executeAgentSet(agentSet, context, params) {
419
337
  discussion,
420
338
  agentConfig: currentAgentConfig,
421
339
  agents,
422
- agentName: specializedAgent,
340
+ discussionRootAgent, // ✅ CLÉ de discussion
423
341
  stdout: params.stdout,
424
342
  session: context,
425
343
  final,
@@ -427,6 +345,11 @@ async function executeAgentSet(agentSet, context, params) {
427
345
  enrichWithMemory: params.enrichWithMemory,
428
346
  });
429
347
  result = (0, types_1.executionResultMerge)(result, partial);
348
+ result.actions = stateGraph.steps(discussionRootAgent).map(step => ({
349
+ action: step.tool,
350
+ content: step.context,
351
+ feedback: step.reason
352
+ }));
430
353
  // Handle two-shot prompting: if instructions is an array, send the second part as a user message
431
354
  // This allows for more complex agent behavior by providing additional context or instructions
432
355
  // after the initial response, similar to chain-of-thought prompting
@@ -456,7 +379,7 @@ async function executeAgentSet(agentSet, context, params) {
456
379
  return result;
457
380
  }
458
381
  async function executeAgent(agentSet, params) {
459
- const { query, verbose } = params;
382
+ const { query, verbose, debug } = params;
460
383
  const openai = (0, utils_1.openaiInstance)();
461
384
  const agent = agentSet.find(a => a.name === params.home);
462
385
  if (!agent) {
@@ -475,13 +398,17 @@ async function executeAgent(agentSet, params) {
475
398
  let maxIterations = 10; // Prevent infinite loops
476
399
  let iterations = 0;
477
400
  if (verbose) {
478
- console.log('--- DBG executeAgent (simple):', agent.name);
401
+ console.log('--- DBG executeAgent:', agent.name);
479
402
  console.log('--- DBG query:', `${query?.substring(0, 100)}...`);
480
403
  }
404
+ if (debug) {
405
+ console.log('--- DBG executeAgent-system:', agent.instructions);
406
+ console.log('--- DBG executeAgent-user:', query);
407
+ }
481
408
  // Execute the agent with tool call handling loop
482
409
  while (iterations < maxIterations) {
483
410
  iterations++;
484
- const options = Object.assign({}, agent.model);
411
+ const options = Object.assign({}, modelConfig(agent.model));
485
412
  options.messages = messages;
486
413
  const tools = agent.tools || [];
487
414
  if (tools.length > 0) {
@@ -489,7 +416,7 @@ async function executeAgent(agentSet, params) {
489
416
  options.tool_choice = "auto";
490
417
  }
491
418
  if (verbose) {
492
- console.log('--- DBG executeAgent (simple):', agent.name, 'iterations:', iterations, '\n', messages.length, '\n---', messages[messages.length - 1]?.content);
419
+ console.log('--- DBG executeAgent:', agent.name, 'iterations:', iterations, '\n', messages.length, '\n---', messages[messages.length - 1]?.content);
493
420
  }
494
421
  const stream = await openai.beta.chat.completions.stream(options);
495
422
  // Stream the response
@@ -501,8 +428,8 @@ async function executeAgent(agentSet, params) {
501
428
  }
502
429
  const final = await stream.finalChatCompletion();
503
430
  // Update usage and state
504
- const model = agent.model?.model;
505
- (0, princing_openai_1.accumulateCost)(usage, model, final.usage);
431
+ const model = modelConfig(agent.model).model;
432
+ (0, pricing_llm_1.accumulateCost)(usage, model, final.usage);
506
433
  state = final.id;
507
434
  // Add assistant response to messages
508
435
  const content = final.choices[0]?.message.content;
@@ -562,3 +489,74 @@ async function executeAgent(agentSet, params) {
562
489
  state
563
490
  };
564
491
  }
492
+ /**
493
+ * Executes a simple query without agent orchestration or tool handling
494
+ *
495
+ * This is the simplest level of execution - just sends a query to the LLM
496
+ * and returns the response. No tools, no agent transfers, no complex logic.
497
+ *
498
+ * @param params - Execution parameters including query and model config
499
+ * @returns Promise<ExecuteAgentResult> - Simple result with usage and content
500
+ */
501
+ async function executeQuery(params) {
502
+ const { query, verbose } = params;
503
+ // Get OpenAI/Grok instance
504
+ const openai = (0, utils_1.openaiInstance)();
505
+ // Use default model configuration if no home agent specified
506
+ const modelName = params.model || params.home || "LOW-fast";
507
+ const model = modelConfig(modelName);
508
+ const more = {};
509
+ if (params.json) {
510
+ more.response_format = { type: "json_object" };
511
+ }
512
+ if (params.schema) {
513
+ more.response_format = { type: "json_object", schema: params.schema };
514
+ }
515
+ if (verbose) {
516
+ console.log('--- DBG query:', modelName, `${query?.substring(0, 100)}...`);
517
+ }
518
+ // Simple message array - no system prompt, just the user query
519
+ const messages = params.messages || [];
520
+ messages.push({ role: "user", content: query });
521
+ let usage = { prompt: 0, completion: 0, total: 0, cost: 0 };
522
+ let state = '';
523
+ try {
524
+ // Create completion options
525
+ const options = Object.assign({}, model, more);
526
+ options.messages = messages;
527
+ if (verbose) {
528
+ console.log('--- DBG executeQuery options:', JSON.stringify(options, null, 2));
529
+ }
530
+ // Execute the query
531
+ const stream = await openai.beta.chat.completions.stream(options);
532
+ // Stream the response
533
+ for await (const chunk of stream) {
534
+ const delta = chunk.choices[0]?.delta;
535
+ if (delta?.content && params.stdout) {
536
+ params.stdout.write(delta?.content);
537
+ }
538
+ }
539
+ const final = await stream.finalChatCompletion();
540
+ // Update usage and state
541
+ (0, pricing_llm_1.accumulateCost)(usage, model.model, final.usage);
542
+ state = final.id || '';
543
+ // Get the response content
544
+ const content = final.choices[0]?.message.content || '';
545
+ if (verbose) {
546
+ console.log('--- DBG executeQuery completed, usage:', usage);
547
+ }
548
+ return {
549
+ usage,
550
+ content,
551
+ messages: [
552
+ ...messages,
553
+ { role: "assistant", content }
554
+ ],
555
+ state
556
+ };
557
+ }
558
+ catch (error) {
559
+ console.error('❌ executeQuery failed:', error);
560
+ throw error;
561
+ }
562
+ }
@@ -6,7 +6,7 @@ export * from './utils';
6
6
  export * from './types';
7
7
  export * from './stategraph';
8
8
  export * from './execute';
9
- export * from './princing.openai';
9
+ export * from './pricing.llm';
10
10
  export * from './scrapper';
11
11
  export * from './agents/reducer';
12
12
  export * from './agents/semantic';