concevent-ai-agent-sdk 1.0.5 → 2.0.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.
- package/README.md +516 -2
- package/dist/core/agent.d.ts.map +1 -1
- package/dist/core/agent.js +151 -66
- package/dist/core/agent.js.map +1 -1
- package/dist/core/errors.d.ts +1 -1
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +4 -1
- package/dist/core/errors.js.map +1 -1
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +1 -0
- package/dist/core/index.js.map +1 -1
- package/dist/core/logger.d.ts +2 -0
- package/dist/core/logger.d.ts.map +1 -1
- package/dist/core/logger.js +8 -0
- package/dist/core/logger.js.map +1 -1
- package/dist/core/middleware.d.ts +55 -0
- package/dist/core/middleware.d.ts.map +1 -0
- package/dist/core/middleware.js +125 -0
- package/dist/core/middleware.js.map +1 -0
- package/dist/core/orchestrator.d.ts +31 -0
- package/dist/core/orchestrator.d.ts.map +1 -0
- package/dist/core/orchestrator.js +206 -0
- package/dist/core/orchestrator.js.map +1 -0
- package/dist/core/response-format.d.ts +44 -0
- package/dist/core/response-format.d.ts.map +1 -0
- package/dist/core/response-format.js +107 -0
- package/dist/core/response-format.js.map +1 -0
- package/dist/core/retry.d.ts +76 -0
- package/dist/core/retry.d.ts.map +1 -0
- package/dist/core/retry.js +164 -0
- package/dist/core/retry.js.map +1 -0
- package/dist/core/summarization.d.ts.map +1 -1
- package/dist/core/summarization.js +21 -3
- package/dist/core/summarization.js.map +1 -1
- package/dist/core/tool-executor.d.ts +6 -5
- package/dist/core/tool-executor.d.ts.map +1 -1
- package/dist/core/tool-executor.js +36 -11
- package/dist/core/tool-executor.js.map +1 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/types/config.d.ts +88 -1
- package/dist/types/config.d.ts.map +1 -1
- package/dist/types/config.js +4 -0
- package/dist/types/config.js.map +1 -1
- package/dist/types/events.d.ts +24 -1
- package/dist/types/events.d.ts.map +1 -1
- package/dist/types/events.js.map +1 -1
- package/dist/types/index.d.ts +5 -3
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/types/middleware.d.ts +115 -0
- package/dist/types/middleware.d.ts.map +1 -0
- package/dist/types/middleware.js +2 -0
- package/dist/types/middleware.js.map +1 -0
- package/dist/types/orchestrator.d.ts +61 -0
- package/dist/types/orchestrator.d.ts.map +1 -0
- package/dist/types/orchestrator.js +2 -0
- package/dist/types/orchestrator.js.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
const LOG_PREFIX = '[AI-Agent-SDK:Middleware]';
|
|
2
|
+
/**
|
|
3
|
+
* Executes middleware hooks in registration order (first registered = first executed).
|
|
4
|
+
* Provides a clean API for running middleware at various points in the agent lifecycle.
|
|
5
|
+
*/
|
|
6
|
+
export class MiddlewareExecutor {
|
|
7
|
+
middlewares;
|
|
8
|
+
constructor(middlewares = []) {
|
|
9
|
+
this.middlewares = middlewares;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Returns true if any middleware is registered.
|
|
13
|
+
*/
|
|
14
|
+
hasMiddleware() {
|
|
15
|
+
return this.middlewares.length > 0;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Execute beforeChat hooks in order.
|
|
19
|
+
* Each middleware can modify the message before passing to the next.
|
|
20
|
+
*
|
|
21
|
+
* @param ctx - The before chat context
|
|
22
|
+
* @returns The potentially modified message
|
|
23
|
+
*/
|
|
24
|
+
async executeBeforeChat(ctx) {
|
|
25
|
+
let message = ctx.message;
|
|
26
|
+
for (const middleware of this.middlewares) {
|
|
27
|
+
if (middleware.beforeChat) {
|
|
28
|
+
try {
|
|
29
|
+
message = await middleware.beforeChat({ ...ctx, message });
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
console.error(`${LOG_PREFIX} ${middleware.name} beforeChat error:`, error);
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return message;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Execute afterChat hooks in order.
|
|
41
|
+
* Each middleware can modify the result before passing to the next.
|
|
42
|
+
*
|
|
43
|
+
* @param ctx - The after chat context
|
|
44
|
+
* @returns The potentially modified result
|
|
45
|
+
*/
|
|
46
|
+
async executeAfterChat(ctx) {
|
|
47
|
+
let result = ctx.result;
|
|
48
|
+
for (const middleware of this.middlewares) {
|
|
49
|
+
if (middleware.afterChat) {
|
|
50
|
+
try {
|
|
51
|
+
result = await middleware.afterChat({ ...ctx, result });
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
console.error(`${LOG_PREFIX} ${middleware.name} afterChat error:`, error);
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Execute beforeToolCall hooks in order.
|
|
63
|
+
* Each middleware can modify the tool call before passing to the next.
|
|
64
|
+
*
|
|
65
|
+
* @param ctx - The before tool call context
|
|
66
|
+
* @returns The potentially modified tool call
|
|
67
|
+
*/
|
|
68
|
+
async executeBeforeToolCall(ctx) {
|
|
69
|
+
let toolCall = ctx.toolCall;
|
|
70
|
+
for (const middleware of this.middlewares) {
|
|
71
|
+
if (middleware.beforeToolCall) {
|
|
72
|
+
try {
|
|
73
|
+
toolCall = await middleware.beforeToolCall({ ...ctx, toolCall });
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
console.error(`${LOG_PREFIX} ${middleware.name} beforeToolCall error:`, error);
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return toolCall;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Execute afterToolCall hooks in order.
|
|
85
|
+
* Each middleware can modify the result before passing to the next.
|
|
86
|
+
*
|
|
87
|
+
* @param ctx - The after tool call context
|
|
88
|
+
* @returns The potentially modified function call result
|
|
89
|
+
*/
|
|
90
|
+
async executeAfterToolCall(ctx) {
|
|
91
|
+
let result = ctx.result;
|
|
92
|
+
for (const middleware of this.middlewares) {
|
|
93
|
+
if (middleware.afterToolCall) {
|
|
94
|
+
try {
|
|
95
|
+
result = await middleware.afterToolCall({ ...ctx, result });
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
console.error(`${LOG_PREFIX} ${middleware.name} afterToolCall error:`, error);
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Execute onError hooks in order.
|
|
107
|
+
* These are for observation only and do not modify the error.
|
|
108
|
+
*
|
|
109
|
+
* @param ctx - The error context
|
|
110
|
+
*/
|
|
111
|
+
async executeOnError(ctx) {
|
|
112
|
+
for (const middleware of this.middlewares) {
|
|
113
|
+
if (middleware.onError) {
|
|
114
|
+
try {
|
|
115
|
+
await middleware.onError(ctx);
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
// Log but don't throw - onError hooks should not break the error flow
|
|
119
|
+
console.error(`${LOG_PREFIX} ${middleware.name} onError handler failed:`, error);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
//# sourceMappingURL=middleware.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../src/core/middleware.ts"],"names":[],"mappings":"AAWA,MAAM,UAAU,GAAG,2BAA2B,CAAC;AAE/C;;;GAGG;AACH,MAAM,OAAO,kBAAkB;IACZ,WAAW,CAAe;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AC,cAAc,CAAC,GAAiB;QACpC,KAAK,MAAM,UAAU,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YAC1C,IAAI,UAAU,CAAC,OAAO,EAAE,CAAC;gBACvB,IAAI,CAAC;oBACH,MAAM,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;gBAChC,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,sEAAsE;oBACtE,OAAO,CAAC,KAAK,CAAC,GAAG,UAAU,IAAI,UAAU,CAAC,IAAI,0BAA0B,EAAE,KAAK,CAAC,CAAC;gBACnF,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;CACF"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { OrchestratorConfig, OrchestratorAgent } from '../types/orchestrator.js';
|
|
2
|
+
/**
|
|
3
|
+
* Creates an orchestrator agent that can delegate work to specialized sub-agents.
|
|
4
|
+
*
|
|
5
|
+
* The orchestrator automatically generates tools for each sub-agent, allowing the
|
|
6
|
+
* underlying LLM to route requests based on agent descriptions. Sub-agents operate
|
|
7
|
+
* statelessly—the orchestrator is responsible for providing necessary context.
|
|
8
|
+
*
|
|
9
|
+
* @param config - Configuration for the orchestrator agent
|
|
10
|
+
* @returns An OrchestratorAgent instance
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* const codeAgent = createAgent({ ... });
|
|
15
|
+
* const researchAgent = createAgent({ ... });
|
|
16
|
+
*
|
|
17
|
+
* const orchestrator = createOrchestratorAgent({
|
|
18
|
+
* apiKey: 'your-api-key',
|
|
19
|
+
* model: 'openai/gpt-4',
|
|
20
|
+
* systemPrompts: [], // Additional prompts (orchestrator prompt is auto-injected)
|
|
21
|
+
* subAgents: [
|
|
22
|
+
* { agent: codeAgent, name: 'code_expert', description: 'Handles coding tasks' },
|
|
23
|
+
* { agent: researchAgent, name: 'researcher', description: 'Researches topics' },
|
|
24
|
+
* ],
|
|
25
|
+
* });
|
|
26
|
+
*
|
|
27
|
+
* const result = await orchestrator.chat('Write a function to sort an array', context);
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export declare function createOrchestratorAgent(config: OrchestratorConfig): OrchestratorAgent;
|
|
31
|
+
//# sourceMappingURL=orchestrator.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orchestrator.d.ts","sourceRoot":"","sources":["../../src/core/orchestrator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,iBAAiB,EAClB,MAAM,0BAA0B,CAAC;AA2HlC;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,kBAAkB,GAAG,iBAAiB,CA0GrF"}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { createAgent } from './agent.js';
|
|
2
|
+
import { AgentError } from './errors.js';
|
|
3
|
+
import { logger } from './logger.js';
|
|
4
|
+
/**
|
|
5
|
+
* Symbol used to mark an agent as an orchestrator.
|
|
6
|
+
* Used to prevent nested orchestrators.
|
|
7
|
+
*/
|
|
8
|
+
const ORCHESTRATOR_MARKER = Symbol.for('concevent.orchestrator');
|
|
9
|
+
/**
|
|
10
|
+
* Type guard to check if an agent is an orchestrator.
|
|
11
|
+
*/
|
|
12
|
+
function isOrchestratorAgent(agent) {
|
|
13
|
+
return ORCHESTRATOR_MARKER in agent;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Creates a tool definition that delegates to a sub-agent.
|
|
17
|
+
* The tool allows the orchestrator to invoke the sub-agent with a message.
|
|
18
|
+
*/
|
|
19
|
+
function createSubAgentTool(definition, callbacks) {
|
|
20
|
+
return {
|
|
21
|
+
declaration: {
|
|
22
|
+
name: definition.name,
|
|
23
|
+
description: definition.description,
|
|
24
|
+
parametersJsonSchema: {
|
|
25
|
+
type: 'object',
|
|
26
|
+
properties: {
|
|
27
|
+
message: {
|
|
28
|
+
type: 'string',
|
|
29
|
+
description: 'The complete message to send to this agent. Include all necessary context since the agent has no prior conversation history.',
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
required: ['message'],
|
|
33
|
+
additionalProperties: false,
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
executor: async (args, context) => {
|
|
37
|
+
const message = args.message;
|
|
38
|
+
logger.subAgentStart(definition.name, message);
|
|
39
|
+
// Fire onSubAgentStart callback
|
|
40
|
+
callbacks?.onSubAgentStart?.({
|
|
41
|
+
agentName: definition.name,
|
|
42
|
+
message,
|
|
43
|
+
});
|
|
44
|
+
try {
|
|
45
|
+
// Clear sub-agent history to ensure stateless execution
|
|
46
|
+
definition.agent.clearHistory();
|
|
47
|
+
// Delegate to the sub-agent
|
|
48
|
+
const result = await definition.agent.chat(message, context, {
|
|
49
|
+
// Forward abort handling
|
|
50
|
+
onAborted: callbacks?.onAborted,
|
|
51
|
+
// Forward error handling
|
|
52
|
+
onError: callbacks?.onError,
|
|
53
|
+
});
|
|
54
|
+
logger.subAgentComplete(definition.name, result.iterations);
|
|
55
|
+
// Fire onSubAgentComplete callback
|
|
56
|
+
callbacks?.onSubAgentComplete?.({
|
|
57
|
+
agentName: definition.name,
|
|
58
|
+
result,
|
|
59
|
+
});
|
|
60
|
+
// Return the sub-agent's response message for the orchestrator to synthesize
|
|
61
|
+
return result.message;
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
logger.error(`Sub-agent "${definition.name}" failed`, error);
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
parallel: definition.parallel ?? false,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Generates the system prompt for the orchestrator.
|
|
73
|
+
* Explains the orchestrator's role and lists available sub-agents.
|
|
74
|
+
*/
|
|
75
|
+
function generateOrchestratorSystemPrompt(subAgents) {
|
|
76
|
+
const agentList = subAgents.map((def) => `- **${def.name}**: ${def.description}`).join('\n');
|
|
77
|
+
return `You are an orchestrator agent responsible for routing tasks to specialized sub-agents.
|
|
78
|
+
|
|
79
|
+
## Your Role
|
|
80
|
+
- Analyze incoming requests and determine which sub-agent(s) are best suited to handle them.
|
|
81
|
+
- Delegate work by calling the appropriate sub-agent tool(s).
|
|
82
|
+
- When delegating, provide COMPLETE context in your message since sub-agents have no prior conversation history.
|
|
83
|
+
- Synthesize responses from sub-agents into coherent final answers.
|
|
84
|
+
- You may call multiple sub-agents if a task requires different specializations.
|
|
85
|
+
|
|
86
|
+
## Available Sub-Agents
|
|
87
|
+
${agentList}
|
|
88
|
+
|
|
89
|
+
## Guidelines
|
|
90
|
+
1. Always include all necessary context when delegating to a sub-agent.
|
|
91
|
+
2. If a task can be handled by multiple agents, choose the most specialized one.
|
|
92
|
+
3. For complex tasks, break them down and delegate parts to appropriate agents.
|
|
93
|
+
4. Combine and summarize sub-agent responses into a unified response for the user.
|
|
94
|
+
5. If no sub-agent is suitable for a request, explain what you can help with.`;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Creates an orchestrator agent that can delegate work to specialized sub-agents.
|
|
98
|
+
*
|
|
99
|
+
* The orchestrator automatically generates tools for each sub-agent, allowing the
|
|
100
|
+
* underlying LLM to route requests based on agent descriptions. Sub-agents operate
|
|
101
|
+
* statelessly—the orchestrator is responsible for providing necessary context.
|
|
102
|
+
*
|
|
103
|
+
* @param config - Configuration for the orchestrator agent
|
|
104
|
+
* @returns An OrchestratorAgent instance
|
|
105
|
+
*
|
|
106
|
+
* @example
|
|
107
|
+
* ```typescript
|
|
108
|
+
* const codeAgent = createAgent({ ... });
|
|
109
|
+
* const researchAgent = createAgent({ ... });
|
|
110
|
+
*
|
|
111
|
+
* const orchestrator = createOrchestratorAgent({
|
|
112
|
+
* apiKey: 'your-api-key',
|
|
113
|
+
* model: 'openai/gpt-4',
|
|
114
|
+
* systemPrompts: [], // Additional prompts (orchestrator prompt is auto-injected)
|
|
115
|
+
* subAgents: [
|
|
116
|
+
* { agent: codeAgent, name: 'code_expert', description: 'Handles coding tasks' },
|
|
117
|
+
* { agent: researchAgent, name: 'researcher', description: 'Researches topics' },
|
|
118
|
+
* ],
|
|
119
|
+
* });
|
|
120
|
+
*
|
|
121
|
+
* const result = await orchestrator.chat('Write a function to sort an array', context);
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
export function createOrchestratorAgent(config) {
|
|
125
|
+
const { subAgents, systemPrompts, ...restConfig } = config;
|
|
126
|
+
// Validate no nested orchestrators
|
|
127
|
+
for (const definition of subAgents) {
|
|
128
|
+
if (isOrchestratorAgent(definition.agent)) {
|
|
129
|
+
throw new AgentError('NESTED_ORCHESTRATOR_NOT_ALLOWED', `Sub-agent "${definition.name}" is an orchestrator. Nested orchestrators are not allowed.`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
// Validate unique agent names
|
|
133
|
+
const names = new Set();
|
|
134
|
+
for (const definition of subAgents) {
|
|
135
|
+
if (names.has(definition.name)) {
|
|
136
|
+
throw new AgentError('GENERIC_ERROR', `Duplicate sub-agent name: "${definition.name}". Each sub-agent must have a unique name.`);
|
|
137
|
+
}
|
|
138
|
+
names.add(definition.name);
|
|
139
|
+
}
|
|
140
|
+
// We need to create tools that capture callbacks, but callbacks are passed per-chat call.
|
|
141
|
+
// So we create a mutable reference that gets updated on each chat call.
|
|
142
|
+
let currentCallbacks;
|
|
143
|
+
// Generate delegation tools for each sub-agent
|
|
144
|
+
const subAgentTools = subAgents.map((definition) => {
|
|
145
|
+
// Create a wrapper that uses the current callbacks
|
|
146
|
+
const baseToolDef = createSubAgentTool(definition, undefined);
|
|
147
|
+
return {
|
|
148
|
+
...baseToolDef,
|
|
149
|
+
executor: async (args, context) => {
|
|
150
|
+
// Create tool with current callbacks
|
|
151
|
+
const toolWithCallbacks = createSubAgentTool(definition, currentCallbacks);
|
|
152
|
+
return toolWithCallbacks.executor(args, context);
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
});
|
|
156
|
+
// Generate orchestrator system prompt
|
|
157
|
+
const orchestratorSystemPrompt = generateOrchestratorSystemPrompt(subAgents);
|
|
158
|
+
// Combine orchestrator prompt with user-provided prompts
|
|
159
|
+
const combinedSystemPrompts = [orchestratorSystemPrompt, ...systemPrompts];
|
|
160
|
+
// Create the underlying agent with generated tools
|
|
161
|
+
const underlyingAgent = createAgent({
|
|
162
|
+
...restConfig,
|
|
163
|
+
systemPrompts: combinedSystemPrompts,
|
|
164
|
+
tools: subAgentTools,
|
|
165
|
+
});
|
|
166
|
+
// Create the orchestrator agent wrapper
|
|
167
|
+
const orchestratorAgent = {
|
|
168
|
+
async chat(message, context, callbacks) {
|
|
169
|
+
// Update current callbacks for sub-agent tools to use
|
|
170
|
+
currentCallbacks = callbacks;
|
|
171
|
+
try {
|
|
172
|
+
return await underlyingAgent.chat(message, context, callbacks);
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
currentCallbacks = undefined;
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
abort() {
|
|
179
|
+
underlyingAgent.abort();
|
|
180
|
+
},
|
|
181
|
+
getHistory() {
|
|
182
|
+
return underlyingAgent.getHistory();
|
|
183
|
+
},
|
|
184
|
+
setHistory(history) {
|
|
185
|
+
underlyingAgent.setHistory(history);
|
|
186
|
+
},
|
|
187
|
+
clearHistory() {
|
|
188
|
+
underlyingAgent.clearHistory();
|
|
189
|
+
},
|
|
190
|
+
getTokenUsage() {
|
|
191
|
+
return underlyingAgent.getTokenUsage();
|
|
192
|
+
},
|
|
193
|
+
getSubAgents() {
|
|
194
|
+
return [...subAgents];
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
// Mark as orchestrator to prevent nesting
|
|
198
|
+
Object.defineProperty(orchestratorAgent, ORCHESTRATOR_MARKER, {
|
|
199
|
+
value: true,
|
|
200
|
+
enumerable: false,
|
|
201
|
+
writable: false,
|
|
202
|
+
configurable: false,
|
|
203
|
+
});
|
|
204
|
+
return orchestratorAgent;
|
|
205
|
+
}
|
|
206
|
+
//# sourceMappingURL=orchestrator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orchestrator.js","sourceRoot":"","sources":["../../src/core/orchestrator.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,WAAW,EAAc,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC;;;GAGG;AACH,MAAM,mBAAmB,GAAG,MAAM,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;AAEjE;;GAEG;AACH,SAAS,mBAAmB,CAAC,KAAY;IACvC,OAAO,mBAAmB,IAAI,KAAK,CAAC;AACtC,CAAC;AAED;;;GAGG;AACH,SAAS,kBAAkB,CACzB,UAA2B,EAC3B,SAA0B;IAE1B,OAAO;QACL,WAAW,EAAE;YACX,IAAI,EAAE,UAAU,CAAC,IAAI;YACrB,WAAW,EAAE,UAAU,CAAC,WAAW;YACnC,oBAAoB,EAAE;gBACpB,IAAI,EAAE,QAAQ;gBACd,UAAU,EAAE;oBACV,OAAO,EAAE;wBACP,IAAI,EAAE,QAAQ;wBACd,WAAW,EACT,8HAA8H;qBACjI;iBACF;gBACD,QAAQ,EAAE,CAAC,SAAS,CAAC;gBACrB,oBAAoB,EAAE,KAAK;aAC5B;SACF;QACD,QAAQ,EAAE,KAAK,EACb,IAA6B,EAC7B,OAA4B,EACX,EAAE;YACnB,MAAM,OAAO,GAAG,IAAI,CAAC,OAAiB,CAAC;YAEvC,MAAM,CAAC,aAAa,CAAC,UAAU,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;YAE/C,gCAAgC;YAChC,SAAS,EAAE,eAAe,EAAE,CAAC;gBAC3B,SAAS,EAAE,UAAU,CAAC,IAAI;gBAC1B,OAAO;aACR,CAAC,CAAC;YAEH,IAAI,CAAC;gBACH,wDAAwD;gBACxD,UAA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openai';
|
|
2
|
+
import type { ZodType, ZodError } from 'zod';
|
|
3
|
+
import type { ResponseFormatConfig } from '../types/config.js';
|
|
4
|
+
/**
|
|
5
|
+
* Result of response validation.
|
|
6
|
+
*/
|
|
7
|
+
export type ValidationResult<T> = {
|
|
8
|
+
success: true;
|
|
9
|
+
data: T;
|
|
10
|
+
} | {
|
|
11
|
+
success: false;
|
|
12
|
+
error: ZodError;
|
|
13
|
+
rawResponse: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Converts SDK ResponseFormatConfig to OpenAI API response_format parameter.
|
|
17
|
+
*/
|
|
18
|
+
export declare function buildResponseFormat(config?: ResponseFormatConfig): OpenAI.Chat.Completions.ChatCompletionCreateParams['response_format'];
|
|
19
|
+
/**
|
|
20
|
+
* Parses and validates a JSON response against a Zod schema.
|
|
21
|
+
*
|
|
22
|
+
* @param response - The raw response string from the API
|
|
23
|
+
* @param schema - The Zod schema to validate against
|
|
24
|
+
* @returns ValidationResult with either parsed data or error details
|
|
25
|
+
*/
|
|
26
|
+
export declare function validateResponse<T>(response: string, schema: ZodType<T>): ValidationResult<T>;
|
|
27
|
+
/**
|
|
28
|
+
* Formats a validation error for inclusion in a retry prompt.
|
|
29
|
+
*/
|
|
30
|
+
export declare function formatValidationError(error: ZodError): string;
|
|
31
|
+
/**
|
|
32
|
+
* Checks if a response format config requires JSON parsing/validation.
|
|
33
|
+
*/
|
|
34
|
+
export declare function requiresJsonParsing(config?: ResponseFormatConfig): boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Checks if a response format config has a schema for validation.
|
|
37
|
+
*/
|
|
38
|
+
export declare function hasSchema(config?: ResponseFormatConfig): config is {
|
|
39
|
+
type: 'json_schema';
|
|
40
|
+
schema: ZodType<unknown>;
|
|
41
|
+
name?: string;
|
|
42
|
+
strict?: boolean;
|
|
43
|
+
};
|
|
44
|
+
//# sourceMappingURL=response-format.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"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JsonSchema } from 'zod-to-json-schema';
|
|
2
|
+
/**
|
|
3
|
+
* Converts SDK ResponseFormatConfig to OpenAI API response_format parameter.
|
|
4
|
+
*/
|
|
5
|
+
export function buildResponseFormat(config) {
|
|
6
|
+
if (!config) {
|
|
7
|
+
return undefined;
|
|
8
|
+
}
|
|
9
|
+
switch (config.type) {
|
|
10
|
+
case 'text':
|
|
11
|
+
return { type: 'text' };
|
|
12
|
+
case 'json_object':
|
|
13
|
+
return { type: 'json_object' };
|
|
14
|
+
case 'json_schema': {
|
|
15
|
+
const jsonSchema = zodToJsonSchema(config.schema, {
|
|
16
|
+
$refStrategy: 'none',
|
|
17
|
+
target: 'openApi3',
|
|
18
|
+
});
|
|
19
|
+
// Remove $schema property as OpenAI doesn't accept it
|
|
20
|
+
if ('$schema' in jsonSchema) {
|
|
21
|
+
delete jsonSchema['$schema'];
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
type: 'json_schema',
|
|
25
|
+
json_schema: {
|
|
26
|
+
name: config.name ?? 'response',
|
|
27
|
+
schema: jsonSchema,
|
|
28
|
+
strict: config.strict ?? true,
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
default:
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Parses and validates a JSON response against a Zod schema.
|
|
38
|
+
*
|
|
39
|
+
* @param response - The raw response string from the API
|
|
40
|
+
* @param schema - The Zod schema to validate against
|
|
41
|
+
* @returns ValidationResult with either parsed data or error details
|
|
42
|
+
*/
|
|
43
|
+
export function validateResponse(response, schema) {
|
|
44
|
+
let parsed;
|
|
45
|
+
try {
|
|
46
|
+
parsed = JSON.parse(response);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
// Return a synthetic ZodError for JSON parse failures
|
|
50
|
+
const issues = [
|
|
51
|
+
{
|
|
52
|
+
code: 'custom',
|
|
53
|
+
path: [],
|
|
54
|
+
message: `Invalid JSON: ${response.slice(0, 100)}${response.length > 100 ? '...' : ''}`,
|
|
55
|
+
},
|
|
56
|
+
];
|
|
57
|
+
const parseError = {
|
|
58
|
+
issues,
|
|
59
|
+
name: 'ZodError',
|
|
60
|
+
get errors() {
|
|
61
|
+
return issues;
|
|
62
|
+
},
|
|
63
|
+
format: () => ({}),
|
|
64
|
+
flatten: () => ({ formErrors: [], fieldErrors: {} }),
|
|
65
|
+
isEmpty: false,
|
|
66
|
+
addIssue: () => { },
|
|
67
|
+
addIssues: () => { },
|
|
68
|
+
};
|
|
69
|
+
return {
|
|
70
|
+
success: false,
|
|
71
|
+
error: parseError,
|
|
72
|
+
rawResponse: response,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
const result = schema.safeParse(parsed);
|
|
76
|
+
if (result.success) {
|
|
77
|
+
return { success: true, data: result.data };
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
success: false,
|
|
81
|
+
error: result.error,
|
|
82
|
+
rawResponse: response,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Formats a validation error for inclusion in a retry prompt.
|
|
87
|
+
*/
|
|
88
|
+
export function formatValidationError(error) {
|
|
89
|
+
const issues = error.issues.map((issue) => {
|
|
90
|
+
const path = issue.path.length > 0 ? `at "${issue.path.join('.')}"` : 'at root';
|
|
91
|
+
return `- ${path}: ${issue.message}`;
|
|
92
|
+
});
|
|
93
|
+
return `The previous response did not match the required schema:\n${issues.join('\n')}\n\nPlease provide a valid response.`;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Checks if a response format config requires JSON parsing/validation.
|
|
97
|
+
*/
|
|
98
|
+
export function requiresJsonParsing(config) {
|
|
99
|
+
return config?.type === 'json_object' || config?.type === 'json_schema';
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Checks if a response format config has a schema for validation.
|
|
103
|
+
*/
|
|
104
|
+
export function hasSchema(config) {
|
|
105
|
+
return config?.type === 'json_schema';
|
|
106
|
+
}
|
|
107
|
+
//# sourceMappingURL=response-format.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"response-format.js","sourceRoot":"","sources":["../../src/core/response-format.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAUrD;;GAEG;AACH,MAAM,UAAU,mBAAmB,CACjC,MAA6B;IAE7B,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,QAAQ,MAAM,CAAC,IAAI,EAAE,CAAC;QACpB,KAAK,MAAM;YACT,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC;QAE1B,KAAK,aAAa;YAChB,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC;QAEjC,KAAK,aAAa,CAAC,CAAC,CAAC;YACnB,MAAM,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,MAAM,EAAE;gBAChD,YAAY,EAAE,MAAM;gBACpB,MAAM,EAAE,UAAU;aACnB,CAAC,CAAC;YAEH,sDAAsD;YACtD,IAAI,SAAS,IAAI,UAAU,EAAE,CAAC;gBAC5B,OAAQ,UAAsC,CAAC,SAAS,CAAC,CAAC;YAC5D,CAAC;YAED,OAAO;gBACL,IAAI,EAAE,aAAa;gBACnB,WAAW,EAAE;oBACX,IAAI,EAAE,MAAM,CAAC,IAAI,IAAI,UAAU;oBAC/B,MAAM,EAAE,UAAqC;oBAC7C,MAAM,EAAE,MAAM,CAAC,MAAM,IAAI,IAAI;iBAC9B;aACF,CAAC;QACJ,CAAC;QAED;YACE,OAAO,SAAS,CAAC;IACrB,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAI,QAAgB,EAAE,MAAkB;IACtE,IAAI,MAAe,CAAC;IAEpB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;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C,CAAC,KAAK,EAAE,EAAE;QACxC,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC;QAChF,OAAO,KAAK,IAAI,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC;IACvC,CAAC,CAAC,CAAC;IAEH,OAAO,6DAA6D,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,sCAAsC,CAAC;AAC9H,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAA6B;IAC/D,OAAO,MAAM,EAAE,IAAI,KAAK,aAAa,IAAI,MAAM,EAAE,IAAI,KAAK,aAAa,CAAC;AAC1E,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,SAAS,CACvB,MAA6B;IAE7B,OAAO,MAAM,EAAE,IAAI,KAAK,aAAa,CAAC;AACxC,CAAC"}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { RetryConfig } from '../types/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Information about a retry attempt passed to callbacks.
|
|
4
|
+
*/
|
|
5
|
+
export interface RetryAttemptInfo {
|
|
6
|
+
/** Current attempt number (1-based) */
|
|
7
|
+
attempt: number;
|
|
8
|
+
/** Maximum number of attempts configured */
|
|
9
|
+
maxAttempts: number;
|
|
10
|
+
/** The error that triggered the retry */
|
|
11
|
+
error: Error;
|
|
12
|
+
/** Delay in milliseconds before the next attempt */
|
|
13
|
+
delayMs: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Options for the executeWithRetry function.
|
|
17
|
+
*/
|
|
18
|
+
export interface ExecuteWithRetryOptions {
|
|
19
|
+
/** Retry configuration */
|
|
20
|
+
config?: RetryConfig;
|
|
21
|
+
/** AbortSignal to cancel the operation */
|
|
22
|
+
abortSignal?: AbortSignal;
|
|
23
|
+
/** Callback invoked before each retry attempt */
|
|
24
|
+
onRetry?: (info: RetryAttemptInfo) => void;
|
|
25
|
+
/** Custom function to determine if an error is retryable */
|
|
26
|
+
isRetryable?: (error: Error) => boolean;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Resolves retry configuration with defaults.
|
|
30
|
+
*/
|
|
31
|
+
export declare function resolveRetryConfig(config?: RetryConfig): Required<RetryConfig>;
|
|
32
|
+
/**
|
|
33
|
+
* Calculates the delay for a retry attempt using exponential backoff with jitter.
|
|
34
|
+
* @param attempt - The attempt number (1-based, so first retry is attempt 2)
|
|
35
|
+
* @param config - Resolved retry configuration
|
|
36
|
+
* @returns Delay in milliseconds
|
|
37
|
+
*/
|
|
38
|
+
export declare function calculateRetryDelay(attempt: number, config: Required<RetryConfig>): number;
|
|
39
|
+
/**
|
|
40
|
+
* Extracts HTTP status code from an error if available.
|
|
41
|
+
* Works with OpenAI SDK errors and standard HTTP errors.
|
|
42
|
+
*/
|
|
43
|
+
export declare function getErrorStatusCode(error: Error): number | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* Extracts Retry-After header value from an error if available.
|
|
46
|
+
* Returns the delay in milliseconds, or undefined if not present.
|
|
47
|
+
*/
|
|
48
|
+
export declare function getRetryAfterMs(error: Error): number | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* Sleeps for a specified duration, respecting abort signals.
|
|
51
|
+
* @param ms - Duration in milliseconds
|
|
52
|
+
* @param abortSignal - Optional abort signal to cancel the sleep
|
|
53
|
+
* @returns Promise that resolves after the delay or rejects if aborted
|
|
54
|
+
*/
|
|
55
|
+
export declare function sleep(ms: number, abortSignal?: AbortSignal): Promise<void>;
|
|
56
|
+
/**
|
|
57
|
+
* Executes an async function with retry logic using exponential backoff.
|
|
58
|
+
*
|
|
59
|
+
* @param fn - The async function to execute
|
|
60
|
+
* @param options - Retry options including config, abort signal, and callbacks
|
|
61
|
+
* @returns The result of the function if successful
|
|
62
|
+
* @throws The last error if all retry attempts fail
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```typescript
|
|
66
|
+
* const result = await executeWithRetry(
|
|
67
|
+
* () => apiCall(),
|
|
68
|
+
* {
|
|
69
|
+
* config: { maxAttempts: 3, baseDelayMs: 1000 },
|
|
70
|
+
* onRetry: (info) => console.log(`Retry ${info.attempt}/${info.maxAttempts}`),
|
|
71
|
+
* }
|
|
72
|
+
* );
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
export declare function executeWithRetry<T>(fn: () => Promise<T>, options?: ExecuteWithRetryOptions): Promise<T>;
|
|
76
|
+
//# sourceMappingURL=retry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry.d.ts","sourceRoot":"","sources":["../../src/core/retry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AASrD;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,uCAAuC;IACvC,OAAO,EAAE,MAAM,CAAC;IAChB,4CAA4C;IAC5C,WAAW,EAAE,MAAM,CAAC;IACpB,yCAAyC;IACzC,KAAK,EAAE,KAAK,CAAC;IACb,oDAAoD;IACpD,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC,0BAA0B;IAC1B,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,0CAA0C;IAC1C,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,iDAAiD;IACjD,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAC3C,4DAA4D;IAC5D,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,OAAO,CAAC;CACzC;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAC,CAO9E;AAED;;;;;GAKG;AACH,wBAAgB,mB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