agentic-api 2.0.646 → 2.0.885

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 (59) hide show
  1. package/dist/src/agents/prompts.d.ts +2 -3
  2. package/dist/src/agents/prompts.js +21 -118
  3. package/dist/src/agents/reducer.loaders.d.ts +103 -1
  4. package/dist/src/agents/reducer.loaders.js +164 -2
  5. package/dist/src/agents/reducer.types.d.ts +34 -3
  6. package/dist/src/agents/simulator.d.ts +32 -2
  7. package/dist/src/agents/simulator.executor.d.ts +15 -5
  8. package/dist/src/agents/simulator.executor.js +134 -67
  9. package/dist/src/agents/simulator.js +251 -8
  10. package/dist/src/agents/simulator.prompts.d.ts +55 -10
  11. package/dist/src/agents/simulator.prompts.js +305 -61
  12. package/dist/src/agents/simulator.types.d.ts +62 -1
  13. package/dist/src/agents/simulator.types.js +5 -0
  14. package/dist/src/agents/subagent.d.ts +128 -0
  15. package/dist/src/agents/subagent.js +231 -0
  16. package/dist/src/agents/worker.executor.d.ts +48 -0
  17. package/dist/src/agents/worker.executor.js +152 -0
  18. package/dist/src/execute/helpers.d.ts +3 -0
  19. package/dist/src/execute/helpers.js +222 -16
  20. package/dist/src/execute/responses.js +81 -55
  21. package/dist/src/execute/shared.d.ts +5 -0
  22. package/dist/src/execute/shared.js +27 -0
  23. package/dist/src/index.d.ts +2 -1
  24. package/dist/src/index.js +3 -1
  25. package/dist/src/llm/openai.js +8 -1
  26. package/dist/src/llm/pricing.js +2 -0
  27. package/dist/src/llm/xai.js +11 -6
  28. package/dist/src/prompts.d.ts +14 -0
  29. package/dist/src/prompts.js +41 -1
  30. package/dist/src/rag/rag.manager.d.ts +18 -3
  31. package/dist/src/rag/rag.manager.js +114 -12
  32. package/dist/src/rag/types.d.ts +3 -1
  33. package/dist/src/rules/git/git.e2e.helper.js +51 -4
  34. package/dist/src/rules/git/git.health.js +89 -56
  35. package/dist/src/rules/git/index.d.ts +2 -2
  36. package/dist/src/rules/git/index.js +22 -5
  37. package/dist/src/rules/git/repo.d.ts +64 -6
  38. package/dist/src/rules/git/repo.js +572 -141
  39. package/dist/src/rules/git/repo.pr.d.ts +11 -18
  40. package/dist/src/rules/git/repo.pr.js +82 -94
  41. package/dist/src/rules/git/repo.tools.d.ts +5 -0
  42. package/dist/src/rules/git/repo.tools.js +6 -1
  43. package/dist/src/rules/types.d.ts +0 -2
  44. package/dist/src/rules/utils.matter.js +1 -5
  45. package/dist/src/scrapper.d.ts +138 -25
  46. package/dist/src/scrapper.js +538 -160
  47. package/dist/src/stategraph/stategraph.d.ts +6 -2
  48. package/dist/src/stategraph/stategraph.js +21 -6
  49. package/dist/src/stategraph/types.d.ts +14 -6
  50. package/dist/src/types.d.ts +22 -0
  51. package/dist/src/utils.d.ts +24 -0
  52. package/dist/src/utils.js +84 -86
  53. package/package.json +3 -2
  54. package/dist/src/agents/semantic.d.ts +0 -4
  55. package/dist/src/agents/semantic.js +0 -19
  56. package/dist/src/execute/legacy.d.ts +0 -46
  57. package/dist/src/execute/legacy.js +0 -460
  58. package/dist/src/pricing.llm.d.ts +0 -5
  59. package/dist/src/pricing.llm.js +0 -14
@@ -0,0 +1,231 @@
1
+ "use strict";
2
+ /**
3
+ * SubAgent — Injection et introspection des sub-agents
4
+ *
5
+ * Toutes les fonctions liées au pattern subAgent<Name> :
6
+ * - subAgentInjectTools() : génère les tools subAgent<Name> pour le parent
7
+ * - subAgentExtractCapabilities() : résumé des capacités (1ère ligne de chaque tool description)
8
+ * - SUBAGENT_TOOL_PARAMS : schéma paramètres par défaut (query, context, goal)
9
+ *
10
+ * Séparation parent-facing vs subAgent-facing :
11
+ * - Parent-facing : publicDescription + capabilities + params schema (vu par le parent LLM)
12
+ * - SubAgent-facing : instructions internes (graph, routage, contrat — défini côté serveur)
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.SUBAGENT_OUTPUT_SCHEMA = exports.SUBAGENT_REQUIRED_PARAMS = exports.SUBAGENT_TOOL_PARAMS = void 0;
16
+ exports.parseSubAgentOutputContent = parseSubAgentOutputContent;
17
+ exports.subAgentExtractCapabilities = subAgentExtractCapabilities;
18
+ exports.subAgentComposeMission = subAgentComposeMission;
19
+ exports.subAgentInjectTools = subAgentInjectTools;
20
+ // ============================================================================
21
+ // SUBAGENT_TOOL_PARAMS — schéma par défaut (query, context, goal)
22
+ // ============================================================================
23
+ /**
24
+ * Paramètres par défaut du tool subAgent<Name>.
25
+ * Descriptions génériques et courtes (best practice OpenAI).
26
+ * Les exemples domaine sont dans publicDescription de chaque subAgent.
27
+ */
28
+ exports.SUBAGENT_TOOL_PARAMS = {
29
+ query: {
30
+ type: 'string',
31
+ description: 'Question utilisateur ou intention normalisée.',
32
+ },
33
+ context: {
34
+ type: 'string',
35
+ description: 'Entités pré-résolues par le parent (nom, entité, IDs). Vide si rien pré-résolu.',
36
+ },
37
+ goal: {
38
+ type: 'string',
39
+ description: 'Livrable attendu — condition d\'arrêt du sub-agent.',
40
+ },
41
+ };
42
+ exports.SUBAGENT_REQUIRED_PARAMS = ['query', 'context', 'goal'];
43
+ /**
44
+ * Schéma de sortie générique des sous-agents.
45
+ * Les `items` sont sérialisés en chaînes JSON pour rester compatibles avec
46
+ * le mode `json_schema strict` tout en conservant une structure métier libre.
47
+ */
48
+ exports.SUBAGENT_OUTPUT_SCHEMA = {
49
+ type: 'object',
50
+ additionalProperties: false,
51
+ required: ['status', 'items', 'meta', 'control'],
52
+ properties: {
53
+ status: {
54
+ type: 'string',
55
+ enum: ['ok', 'empty', 'error']
56
+ },
57
+ items: {
58
+ type: 'array',
59
+ items: {
60
+ type: 'string'
61
+ }
62
+ },
63
+ meta: {
64
+ type: 'object',
65
+ additionalProperties: false,
66
+ required: ['resolved', 'notFound', 'knowledge_found'],
67
+ properties: {
68
+ resolved: {
69
+ type: 'array',
70
+ items: { type: 'string' }
71
+ },
72
+ notFound: {
73
+ type: 'array',
74
+ items: { type: 'string' }
75
+ },
76
+ knowledge_found: {
77
+ type: 'string',
78
+ enum: ['no', 'yes', 'partial', 'conflict']
79
+ }
80
+ }
81
+ },
82
+ control: {
83
+ type: 'object',
84
+ additionalProperties: false,
85
+ required: ['can_retry'],
86
+ properties: {
87
+ can_retry: { type: 'boolean' }
88
+ }
89
+ }
90
+ }
91
+ };
92
+ function parseSubAgentOutputContent(content) {
93
+ try {
94
+ const parsed = JSON.parse(content);
95
+ if (!parsed || typeof parsed !== 'object') {
96
+ return null;
97
+ }
98
+ if (!['ok', 'empty', 'error'].includes(parsed.status)) {
99
+ return null;
100
+ }
101
+ if (!Array.isArray(parsed.items) || !parsed.items.every((item) => typeof item === 'string')) {
102
+ return null;
103
+ }
104
+ const meta = parsed.meta;
105
+ if (!meta
106
+ || !Array.isArray(meta.resolved)
107
+ || !meta.resolved.every((value) => typeof value === 'string')
108
+ || !Array.isArray(meta.notFound)
109
+ || !meta.notFound.every((value) => typeof value === 'string')
110
+ || !['no', 'yes', 'partial', 'conflict'].includes(meta.knowledge_found)) {
111
+ return null;
112
+ }
113
+ const control = parsed.control;
114
+ if (!control || typeof control.can_retry !== 'boolean') {
115
+ return null;
116
+ }
117
+ return {
118
+ status: parsed.status,
119
+ items: parsed.items,
120
+ meta: {
121
+ resolved: meta.resolved,
122
+ notFound: meta.notFound,
123
+ knowledge_found: meta.knowledge_found
124
+ },
125
+ control: {
126
+ can_retry: control.can_retry
127
+ }
128
+ };
129
+ }
130
+ catch {
131
+ return null;
132
+ }
133
+ }
134
+ // ============================================================================
135
+ // subAgentExtractCapabilities — parent-facing
136
+ // ============================================================================
137
+ /**
138
+ * Extrait les capacités d'un agent depuis ses tools.
139
+ * Prend la 1ère ligne de chaque `function.description`.
140
+ */
141
+ function subAgentExtractCapabilities(agents, name) {
142
+ const agent = agents.find(a => a.name === name) ?? agents[0];
143
+ if (!agent?.tools?.length)
144
+ return '';
145
+ return agent.tools
146
+ .filter(t => t.function?.name && t.function?.description)
147
+ .map(t => {
148
+ const fn = t.function;
149
+ const firstLine = fn.description.trim().split('\n')[0];
150
+ return `- ${fn.name}: ${firstLine}`;
151
+ })
152
+ .join('\n');
153
+ }
154
+ // ============================================================================
155
+ // subAgentComposeMission — convertit les args du tool en mission texte
156
+ // ============================================================================
157
+ /**
158
+ * Compose la mission envoyée au sub-agent depuis les arguments du tool.
159
+ * Supporte les deux formats (ancien triplet et nouveau query/context/goal).
160
+ */
161
+ function subAgentComposeMission(args) {
162
+ //
163
+ // Nouveau format (query, context, goal)
164
+ if (args.query != null || args.goal != null) {
165
+ const parts = [];
166
+ if (args.query)
167
+ parts.push(`## Question\n${args.query}`);
168
+ if (args.context)
169
+ parts.push(`## Contexte\n${args.context}`);
170
+ if (args.goal)
171
+ parts.push(`## Livrable\n${args.goal}`);
172
+ return parts.join('\n\n');
173
+ }
174
+ //
175
+ // Ancien format (subject, context, expected_result) — rétro-compatibilité
176
+ const { subject, context, expected_result } = args;
177
+ return `## Sujet\n${subject}\n\n## Contexte\n${context}\n\n## Résultat attendu\n${expected_result}`;
178
+ }
179
+ // ============================================================================
180
+ // subAgentInjectTools — parent-facing
181
+ // ============================================================================
182
+ /**
183
+ * Injecte un tool `subAgent<Name>` par sub-agent déclaré dans `agentDef.subAgents`.
184
+ *
185
+ * Le schéma des paramètres provient de :
186
+ * 1. `subAgent.subAgentToolParams` (override spécifique)
187
+ * 2. `SUBAGENT_TOOL_PARAMS` (défaut: query, context, goal)
188
+ */
189
+ function subAgentInjectTools(agentDefs) {
190
+ const subAgentRegistry = [];
191
+ const processedAgents = agentDefs.map(agentDef => {
192
+ const subAgents = (agentDef.subAgents ?? []);
193
+ if (subAgents.length === 0)
194
+ return agentDef;
195
+ const tools = agentDef.tools ? [...agentDef.tools] : [];
196
+ subAgents.forEach(subAgent => {
197
+ const toolName = `subAgent${subAgent.name.charAt(0).toUpperCase()}${subAgent.name.slice(1)}`;
198
+ if (tools.find(t => t.function.name === toolName)) {
199
+ return;
200
+ }
201
+ const capabilities = subAgentExtractCapabilities([subAgent], subAgent.name);
202
+ const subAgentTool = {
203
+ type: 'function',
204
+ function: {
205
+ name: toolName,
206
+ description: `Délègue une mission au sub-agent ${subAgent.name}.
207
+ ${subAgent.publicDescription ?? ''}
208
+ ${capabilities ? `\nCapacités :\n${capabilities}` : ''}
209
+ Le sub-agent s'arrête dès que le goal est satisfait.`,
210
+ parameters: {
211
+ type: 'object',
212
+ properties: { ...exports.SUBAGENT_TOOL_PARAMS },
213
+ required: exports.SUBAGENT_REQUIRED_PARAMS,
214
+ additionalProperties: false
215
+ },
216
+ strict: true
217
+ }
218
+ };
219
+ tools.push(subAgentTool);
220
+ if (subAgent.instructions && !subAgentRegistry.find(x => x.name === subAgent.name)) {
221
+ subAgentRegistry.push(subAgent);
222
+ }
223
+ });
224
+ return {
225
+ ...agentDef,
226
+ tools,
227
+ subAgents: subAgents.map(({ name, publicDescription }) => ({ name, publicDescription }))
228
+ };
229
+ });
230
+ return [...processedAgents, ...subAgentRegistry];
231
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @fileoverview Pont WorkerJob → AgentSimulator(mode: worker) → ToolContractOutput
3
+ *
4
+ * Utilise l'infrastructure existante du simulateur adaptée en mode worker.
5
+ * Le contrat de retour suit ToolContractOutput<WorkerOutputV1>.
6
+ */
7
+ import { WorkerJob } from './reducer.loaders';
8
+ import { JobEvent } from './job.runner';
9
+ import { AgenticContext, ToolContractOutput } from '../types';
10
+ /**
11
+ * Données du deliverable Worker — le T de ToolContractOutput<T>
12
+ */
13
+ export interface WorkerDeliverable {
14
+ /** Le résultat complet de la mission */
15
+ deliverable: string;
16
+ /** Résumé court de ce qui a été accompli */
17
+ summary: string;
18
+ /** Temps total en ms */
19
+ duration: number;
20
+ /** Contrat JSON natif minimal pour intégrations API/UI */
21
+ result: WorkerOutputV1;
22
+ }
23
+ /**
24
+ * Contrat JSON natif minimal du Worker.
25
+ */
26
+ export interface WorkerOutputV1 {
27
+ version: 'worker_output_v1';
28
+ status: 'completed' | 'partial' | 'failed';
29
+ summary: string;
30
+ deliverable: string;
31
+ runId: string;
32
+ error?: string;
33
+ }
34
+ /**
35
+ * Exécute un WorkerJob via AgentSimulator en mode worker
36
+ *
37
+ * Callable depuis : Discussion (tool), Cron, Job, API
38
+ * Retourne ToolContractOutput<WorkerOutputV1>
39
+ *
40
+ * @param workerJob - WorkerJob avec positionDescription + agent + maxIterations
41
+ * @param query - La demande/question de job (premier message envoyé à l'Agent)
42
+ * @param agentContext - Contexte réel (RAG, session, credentials — déjà initialisé)
43
+ * @param options - Options additionnelles
44
+ */
45
+ export declare function executeWorkerJob(workerJob: WorkerJob, query: string, agentContext: AgenticContext, options?: {
46
+ extend?: boolean;
47
+ onEvent?: (event: JobEvent) => void;
48
+ }): Promise<ToolContractOutput<WorkerOutputV1>>;
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ /**
3
+ * @fileoverview Pont WorkerJob → AgentSimulator(mode: worker) → ToolContractOutput
4
+ *
5
+ * Utilise l'infrastructure existante du simulateur adaptée en mode worker.
6
+ * Le contrat de retour suit ToolContractOutput<WorkerOutputV1>.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.executeWorkerJob = executeWorkerJob;
10
+ const simulator_1 = require("./simulator");
11
+ // ============================================================================
12
+ // Exécution standalone — multi-source
13
+ // ============================================================================
14
+ /**
15
+ * Exécute un WorkerJob via AgentSimulator en mode worker
16
+ *
17
+ * Callable depuis : Discussion (tool), Cron, Job, API
18
+ * Retourne ToolContractOutput<WorkerOutputV1>
19
+ *
20
+ * @param workerJob - WorkerJob avec positionDescription + agent + maxIterations
21
+ * @param query - La demande/question de job (premier message envoyé à l'Agent)
22
+ * @param agentContext - Contexte réel (RAG, session, credentials — déjà initialisé)
23
+ * @param options - Options additionnelles
24
+ */
25
+ async function executeWorkerJob(workerJob, query, agentContext, options) {
26
+ const toWorkerOutput = (params) => ({
27
+ version: 'worker_output_v1',
28
+ status: params.status,
29
+ summary: params.summary,
30
+ deliverable: params.deliverable,
31
+ runId: params.runId ?? workerJob.id,
32
+ ...(params.error ? { error: params.error } : {})
33
+ });
34
+ try {
35
+ const isVerbose = workerJob.verbose;
36
+ //
37
+ // Créer le simulateur en mode worker
38
+ // - agents : [agent de production]
39
+ // - positionDescription : position description / cahier des charges (injecté dans WORKER_INTERNAL_PROMPT)
40
+ // - mode : 'worker' → WORKER_INTERNAL_PROMPT au lieu de GENERIC_SIMULATOR_PROMPT
41
+ const simulatorConfig = {
42
+ agents: [workerJob.agent],
43
+ start: workerJob.agent.name,
44
+ verbose: isVerbose,
45
+ mode: 'worker',
46
+ positionDescription: workerJob.positionDescription,
47
+ personaResult: workerJob.personaResult,
48
+ workerModel: workerJob.workerModel,
49
+ agentModel: workerJob.agentModel
50
+ };
51
+ const simulator = new simulator_1.AgentSimulator(simulatorConfig);
52
+ //
53
+ // Mode verbose : stream chaque message avec emoji par rôle
54
+ const ROLE_EMOJI = {
55
+ user: '🤖 Worker ',
56
+ assistant: '🧠 Agent ',
57
+ system: '⚙️ System ',
58
+ };
59
+ const verboseOnMessage = isVerbose
60
+ ? (msg) => {
61
+ const emoji = ROLE_EMOJI[msg.role] ?? `❓ ${msg.role}`;
62
+ const preview = msg.content.length > 400
63
+ ? msg.content.slice(0, 400) + '…'
64
+ : msg.content;
65
+ console.log(`\n${emoji}: ${preview}`);
66
+ }
67
+ : undefined;
68
+ // Exécuter le job via simulator.runJob()
69
+ // - query : la demande de job (premier message à l'Agent)
70
+ // - positionDescription : déjà dans le system prompt du Worker LLM
71
+ const result = await simulator.runJob({
72
+ query,
73
+ maxIterations: workerJob.maxIterations,
74
+ agentContext,
75
+ jobId: workerJob.id,
76
+ description: workerJob.description,
77
+ onMessage: verboseOnMessage
78
+ });
79
+ if (result.success) {
80
+ const output = toWorkerOutput({
81
+ status: 'completed',
82
+ summary: result.summary,
83
+ deliverable: result.deliverable,
84
+ runId: result.execution?.runId
85
+ });
86
+ return {
87
+ status: 'ok',
88
+ items: [output],
89
+ meta: {
90
+ jobId: workerJob.id,
91
+ query,
92
+ confidence: result.confidence,
93
+ iterations: result.iterations,
94
+ maxIterations: result.maxIterations,
95
+ usage: result.execution?.usage,
96
+ ...(options?.extend ? { messages: result.messages } : {})
97
+ },
98
+ control: {
99
+ can_retry: false
100
+ }
101
+ };
102
+ }
103
+ //
104
+ // Job échoué ou timeout
105
+ const output = toWorkerOutput({
106
+ status: result.error?.includes('Max iterations reached') ? 'partial' : 'failed',
107
+ summary: result.summary || 'Worker execution failed',
108
+ deliverable: result.deliverable,
109
+ runId: result.execution?.runId,
110
+ error: result.error
111
+ });
112
+ return {
113
+ status: 'error',
114
+ meta: {
115
+ jobId: workerJob.id,
116
+ query,
117
+ iterations: result.iterations,
118
+ maxIterations: result.maxIterations,
119
+ duration: result.duration,
120
+ result: output,
121
+ ...(options?.extend ? { messages: result.messages } : {})
122
+ },
123
+ control: {
124
+ can_retry: true,
125
+ error_code: 'WORKER_FAILED',
126
+ next_hint: result.error
127
+ }
128
+ };
129
+ }
130
+ catch (error) {
131
+ const errorMessage = error?.message || 'Unknown worker exception';
132
+ const output = toWorkerOutput({
133
+ status: 'failed',
134
+ summary: 'Worker execution exception',
135
+ deliverable: '',
136
+ error: errorMessage
137
+ });
138
+ return {
139
+ status: 'error',
140
+ meta: {
141
+ jobId: workerJob.id,
142
+ query,
143
+ result: output
144
+ },
145
+ control: {
146
+ can_retry: true,
147
+ error_code: 'WORKER_EXCEPTION',
148
+ next_hint: errorMessage
149
+ }
150
+ };
151
+ }
152
+ }
@@ -1,5 +1,7 @@
1
+ import { ParsedFunctionToolCall } from 'openai/resources/beta/chat/completions';
1
2
  import { AgentStateGraph } from '../stategraph';
2
3
  import { AgentConfig, AgenticContext, ExecutionAction } from '../types';
4
+ import { SubAgentCallResult } from '../agents/subagent';
3
5
  /**
4
6
  * OPTIM: Accumule l'usage des tokens et met à jour stateGraph + discussion.usage
5
7
  *
@@ -30,6 +32,7 @@ export declare function accumulateUsageTokens(stateGraph: AgentStateGraph, discu
30
32
  * @returns Array d'actions pour ExecutionResult
31
33
  */
32
34
  export declare function stepsToActions(stateGraph: AgentStateGraph, agentName: string): ExecutionAction[];
35
+ export declare function handleSubAgentCall(stateGraph: AgentStateGraph, agents: AgentConfig[], functionCallParams: ParsedFunctionToolCall, context: AgenticContext): Promise<SubAgentCallResult>;
33
36
  /**
34
37
  * OPTIM: Traite tous les tool calls en batch et retourne les résultats
35
38
  *