@just-every/ensemble 0.1.24 → 0.1.26

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.
@@ -0,0 +1,119 @@
1
+ import { ToolFunction, ToolCall, StreamEvent, ResponseInput } from '../types.js';
2
+ export declare enum ToolCallAction {
3
+ EXECUTE = "execute",
4
+ SKIP = "skip",
5
+ HALT = "halt",
6
+ DEFER = "defer",
7
+ RETRY = "retry",
8
+ REPLACE = "replace"
9
+ }
10
+ export interface ExecutionMetrics {
11
+ duration: number;
12
+ tokenCount: number;
13
+ toolCallCount: number;
14
+ modelCalls: number;
15
+ errors: number;
16
+ retries?: number;
17
+ timestamp: number;
18
+ }
19
+ export interface RequestContext {
20
+ shouldContinue: boolean;
21
+ metadata: Record<string, any>;
22
+ toolCallCount: number;
23
+ turnCount: number;
24
+ startTime: number;
25
+ messages: ResponseInput;
26
+ halt(): void;
27
+ pause(): void;
28
+ resume(): void;
29
+ setMetadata(key: string, value: any): void;
30
+ getMetadata<T = any>(key: string): T | undefined;
31
+ addMessage(message: any): void;
32
+ getHistory(): ResponseInput;
33
+ agent?: any;
34
+ isPaused: boolean;
35
+ isHalted: boolean;
36
+ }
37
+ export interface EnhancedToolFunction extends ToolFunction {
38
+ category?: 'control' | 'utility' | 'meta' | 'custom' | string;
39
+ priority?: number;
40
+ sideEffects?: boolean;
41
+ agentId?: string;
42
+ requiresContext?: string[];
43
+ maxExecutions?: number;
44
+ cooldown?: number;
45
+ timeout?: number;
46
+ dependsOn?: string[];
47
+ conflicts?: string[];
48
+ }
49
+ export interface ToolHandler {
50
+ context?: any;
51
+ onToolCall?: (toolCall: ToolCall, context: any) => Promise<ToolCallAction | {
52
+ action: ToolCallAction;
53
+ replacement?: any;
54
+ }>;
55
+ onToolComplete?: (toolCall: ToolCall, result: any, context: any) => Promise<void>;
56
+ onToolError?: (toolCall: ToolCall, error: Error, context: any) => Promise<any>;
57
+ executor?: (tool: ToolFunction, args: any, context: any) => Promise<any>;
58
+ executionMode?: 'sequential' | 'parallel' | 'batch';
59
+ errorStrategy?: 'throw' | 'return-error' | 'retry' | 'custom';
60
+ retryConfig?: {
61
+ maxAttempts?: number;
62
+ backoff?: 'linear' | 'exponential';
63
+ initialDelay?: number;
64
+ };
65
+ }
66
+ export interface LoopConfig {
67
+ maxIterations?: number;
68
+ maxDuration?: number;
69
+ continueCondition?: (context: RequestContext) => boolean | Promise<boolean>;
70
+ onIteration?: (iteration: number, context: RequestContext) => Promise<void>;
71
+ breakOnError?: boolean;
72
+ resetToolCount?: boolean;
73
+ }
74
+ export interface ToolResultTransformer {
75
+ transform?: (toolName: string, result: any, context: any) => any;
76
+ augment?: (toolName: string, result: any, metrics: ExecutionMetrics) => any;
77
+ format?: (toolName: string, result: any) => string;
78
+ validate?: (toolName: string, result: any) => boolean | {
79
+ valid: boolean;
80
+ error?: string;
81
+ };
82
+ }
83
+ export type ToolChoiceStrategy = (callCount: number, turnCount: number, context: any) => 'none' | 'auto' | 'required' | {
84
+ type: 'function';
85
+ function: {
86
+ name: string;
87
+ };
88
+ };
89
+ export interface EnhancedRequestOptions {
90
+ toolHandler?: ToolHandler;
91
+ toolCategories?: string[];
92
+ toolFilter?: (tool: ToolFunction) => boolean;
93
+ toolPriority?: (tools: ToolFunction[]) => ToolFunction[];
94
+ loop?: boolean | LoopConfig;
95
+ maxToolCalls?: number;
96
+ maxToolCallsPerTurn?: number;
97
+ toolChoiceStrategy?: ToolChoiceStrategy;
98
+ toolResultTransformer?: ToolResultTransformer;
99
+ allowedEvents?: string[];
100
+ eventEmitter?: (event: StreamEvent, context: any) => void | Promise<void>;
101
+ onStreamComplete?: (response: any, context: any) => Promise<boolean>;
102
+ cacheToolResults?: boolean;
103
+ parallelExecution?: number;
104
+ debug?: boolean | {
105
+ logToolCalls?: boolean;
106
+ logToolResults?: boolean;
107
+ logMessages?: boolean;
108
+ logMetrics?: boolean;
109
+ };
110
+ }
111
+ export declare function createRequestContext(initialData?: Partial<RequestContext>): RequestContext;
112
+ export declare function isLoopConfig(value: boolean | LoopConfig): value is LoopConfig;
113
+ export declare function normalizeToolChoice(choice: ReturnType<ToolChoiceStrategy>): 'none' | 'auto' | 'required' | {
114
+ type: 'function';
115
+ function: {
116
+ name: string;
117
+ };
118
+ };
119
+ //# sourceMappingURL=tool_types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool_types.d.ts","sourceRoot":"","sources":["../../types/tool_types.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAKjF,oBAAY,cAAc;IACtB,OAAO,YAAY;IACnB,IAAI,SAAS;IACb,IAAI,SAAS;IACb,KAAK,UAAU;IACf,KAAK,UAAU;IACf,OAAO,YAAY;CACtB;AAKD,MAAM,WAAW,gBAAgB;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACrB;AAKD,MAAM,WAAW,cAAc;IAE3B,cAAc,EAAE,OAAO,CAAC;IACxB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAG9B,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAGlB,QAAQ,EAAE,aAAa,CAAC;IAGxB,IAAI,IAAI,IAAI,CAAC;IACb,KAAK,IAAI,IAAI,CAAC;IACd,MAAM,IAAI,IAAI,CAAC;IACf,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,GAAG,IAAI,CAAC;IAC3C,WAAW,CAAC,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,MA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Y,CAAC,EAAE,OAAO,CAAC;QACvB,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,UAAU,CAAC,EAAE,OAAO,CAAC;KACxB,CAAC;CACL;AAKD,wBAAgB,oBAAoB,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,cAAc,CA+C1F;AAKD,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,UAAU,GAAG,KAAK,IAAI,UAAU,CAE7E;AAKD,wBAAgB,mBAAmB,CAC/B,MAAM,EAAE,UAAU,CAAC,kBAAkB,CAAC,GACvC,MAAM,GAAG,MAAM,GAAG,UAAU,GAAG;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,QAAQ,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,CAKjF"}
@@ -0,0 +1,55 @@
1
+ export var ToolCallAction;
2
+ (function (ToolCallAction) {
3
+ ToolCallAction["EXECUTE"] = "execute";
4
+ ToolCallAction["SKIP"] = "skip";
5
+ ToolCallAction["HALT"] = "halt";
6
+ ToolCallAction["DEFER"] = "defer";
7
+ ToolCallAction["RETRY"] = "retry";
8
+ ToolCallAction["REPLACE"] = "replace";
9
+ })(ToolCallAction || (ToolCallAction = {}));
10
+ export function createRequestContext(initialData) {
11
+ const context = {
12
+ shouldContinue: true,
13
+ metadata: {},
14
+ toolCallCount: 0,
15
+ turnCount: 0,
16
+ startTime: Date.now(),
17
+ messages: [],
18
+ isPaused: false,
19
+ isHalted: false,
20
+ ...initialData,
21
+ halt() {
22
+ this.shouldContinue = false;
23
+ this.isHalted = true;
24
+ },
25
+ pause() {
26
+ this.isPaused = true;
27
+ },
28
+ resume() {
29
+ this.isPaused = false;
30
+ },
31
+ setMetadata(key, value) {
32
+ this.metadata[key] = value;
33
+ },
34
+ getMetadata(key) {
35
+ return this.metadata[key];
36
+ },
37
+ addMessage(message) {
38
+ this.messages.push(message);
39
+ },
40
+ getHistory() {
41
+ return [...this.messages];
42
+ }
43
+ };
44
+ return context;
45
+ }
46
+ export function isLoopConfig(value) {
47
+ return typeof value === 'object' && value !== null;
48
+ }
49
+ export function normalizeToolChoice(choice) {
50
+ if (typeof choice === 'string') {
51
+ return choice;
52
+ }
53
+ return choice;
54
+ }
55
+ //# sourceMappingURL=tool_types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool_types.js","sourceRoot":"","sources":["../../types/tool_types.ts"],"names":[],"mappings":"AAUA,MAAM,CAAN,IAAY,cAOX;AAPD,WAAY,cAAc;IACtB,qCAAmB,CAAA;IACnB,+BAAa,CAAA;IACb,+BAAa,CAAA;IACb,iCAAe,CAAA;IACf,iCAAe,CAAA;IACf,qCAAmB,CAAA;AACvB,CAAC,EAPW,cAAc,KAAd,cAAc,QAOzB;AAoLD,MAAM,UAAU,oBAAoB,CAAC,WAAqC;IACtE,MAAM,OAAO,GAAmB;QAE5B,cAAc,EAAE,IAAI;QACpB,QAAQ,EAAE,EAAE;QACZ,aAAa,EAAE,CAAC;QAChB,SAAS,EAAE,CAAC;QACZ,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;QACrB,QAAQ,EAAE,EAAE;QACZ,QAAQ,EAAE,KAAK;QACf,QAAQ,EAAE,KAAK;QAGf,GAAG,WAAW;QAGd,IAAI;YACA,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC;YAC5B,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACzB,CAAC;QAED,KAAK;YACD,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;QACzB,CAAC;QAED,MAAM;YACF,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;QAC1B,CAAC;QAED,WAAW,CAAC,GAAW,EAAE,KAAU;YAC/B,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;QAC/B,CAAC;QAED,WAAW,CAAU,GAAW;YAC5B,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAM,CAAC;QACnC,CAAC;QAED,UAAU,CAAC,OAAY;YACnB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAChC,CAAC;QAED,UAAU;YACN,OAAO,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC9B,CAAC;KACJ,CAAC;IAEF,OAAO,OAAO,CAAC;AACnB,CAAC;AAKD,MAAM,UAAU,YAAY,CAAC,KAA2B;IACpD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC;AACvD,CAAC;AAKD,MAAM,UAAU,mBAAmB,CAC/B,MAAsC;IAEtC,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC7B,OAAO,MAAM,CAAC;IAClB,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { EnsembleStreamEvent, ResponseInput, RequestOptions as BaseRequestOptions, ModelSettings, ToolFunction, ModelClassID, EnsembleAgent } from './types.js';
2
+ import { EnhancedRequestOptions } from './types/tool_types.js';
3
+ import { MessageHistory } from './utils/message_history.js';
4
+ declare class RequestAgent implements EnsembleAgent {
5
+ agent_id: string;
6
+ modelSettings?: ModelSettings;
7
+ modelClass?: ModelClassID;
8
+ private tools;
9
+ constructor(options: BaseRequestOptions);
10
+ getTools(): Promise<ToolFunction[]>;
11
+ }
12
+ interface UnifiedRequestOptions extends BaseRequestOptions, Partial<EnhancedRequestOptions> {
13
+ useEnhancedMode?: boolean;
14
+ messageHistory?: MessageHistory;
15
+ }
16
+ export declare function unifiedRequest(model: string, messages: ResponseInput, options?: UnifiedRequestOptions): AsyncGenerator<EnsembleStreamEvent>;
17
+ export { RequestAgent, UnifiedRequestOptions };
18
+ //# sourceMappingURL=unified_request.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unified_request.d.ts","sourceRoot":"","sources":["../unified_request.ts"],"names":[],"mappings":"AAIA,OAAO,EACH,mBAAmB,EACnB,aAAa,EAEb,cAAc,IAAI,kBAAkB,EACpC,aAAa,EACb,YAAY,EACZ,YAAY,EACZ,aAAa,EAChB,MAAM,YAAY,CAAC;AACpB,OAAO,EACH,sBAAsB,EAIzB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAI5D,cAAM,YAAa,YAAW,aAAa;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,UAAU,CAAC,EAAE,YAAY,CAAC;IAC1B,OAAO,CAAC,KAAK,CAAiB;gBAElB,OAAO,EAAE,kBAAkB;IAOjC,QAAQ,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;CAG5C;AAGD,UAAU,qBAAsB,SAAQ,kBAAkB,EAAE,OAAO,CAAC,sBAAsB,CAAC;IAEvF,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,cAAc,CAAC,EAAE,cAAc,CAAC;CACnC;AAKD,wBAAuB,cAAc,CACjC,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,aAAa,EACvB,OAAO,GAAE,qBAA0B,GACpC,cAAc,CAAC,mBAAmB,CAAC,CAwErC;AAiRD,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,CAAC"}
@@ -0,0 +1,222 @@
1
+ import { createRequestContext, ToolCallAction } from './types/tool_types.js';
2
+ import { getModelProvider } from './model_providers/model_provider.js';
3
+ import { MessageHistory } from './utils/message_history.js';
4
+ import { EnsembleErrorHandler } from './utils/error_handler.js';
5
+ class RequestAgent {
6
+ agent_id;
7
+ modelSettings;
8
+ modelClass;
9
+ tools;
10
+ constructor(options) {
11
+ this.agent_id = options.agentId || 'ensemble';
12
+ this.modelSettings = options.modelSettings;
13
+ this.modelClass = options.modelClass;
14
+ this.tools = options.tools || [];
15
+ }
16
+ async getTools() {
17
+ return this.tools;
18
+ }
19
+ }
20
+ export async function* unifiedRequest(model, messages, options = {}) {
21
+ const useEnhanced = options.useEnhancedMode ||
22
+ options.toolHandler ||
23
+ options.loop ||
24
+ options.toolCategories ||
25
+ options.toolFilter ||
26
+ options.toolResultTransformer;
27
+ const history = options.messageHistory || new MessageHistory(messages, {
28
+ compactToolCalls: true,
29
+ preserveSystemMessages: true
30
+ });
31
+ const context = useEnhanced ? createRequestContext({
32
+ messages: history.getMessages()
33
+ }) : undefined;
34
+ try {
35
+ let iteration = 0;
36
+ const maxIterations = getMaxIterations(options);
37
+ while (true) {
38
+ if (!(await shouldContinue(context, iteration, maxIterations, options))) {
39
+ break;
40
+ }
41
+ const currentMessages = history.getMessages();
42
+ const result = await executeRound(model, currentMessages, options, context, history, iteration);
43
+ for (const event of result.events) {
44
+ yield event;
45
+ }
46
+ if (result.done || (!options.loop && !result.hasToolCalls)) {
47
+ break;
48
+ }
49
+ iteration++;
50
+ }
51
+ if (options.debug) {
52
+ yield createMetricsEvent(context, history);
53
+ }
54
+ }
55
+ catch (error) {
56
+ yield EnsembleErrorHandler.toStreamEvent(error);
57
+ }
58
+ finally {
59
+ yield {
60
+ type: 'stream_end',
61
+ timestamp: new Date().toISOString()
62
+ };
63
+ }
64
+ }
65
+ async function executeRound(model, messages, options, context, history, iteration) {
66
+ const events = [];
67
+ const collectedToolCalls = [];
68
+ const toolResults = [];
69
+ let messageContent = '';
70
+ let hasMessage = false;
71
+ const provider = getModelProvider(model);
72
+ const roundOptions = { ...options };
73
+ if (iteration > 0 && !options.toolChoiceStrategy) {
74
+ if (roundOptions.modelSettings?.tool_choice) {
75
+ roundOptions.modelSettings = { ...roundOptions.modelSettings };
76
+ delete roundOptions.modelSettings.tool_choice;
77
+ }
78
+ }
79
+ const agent = new RequestAgent(roundOptions);
80
+ if (options.toolChoiceStrategy && context) {
81
+ const toolChoice = options.toolChoiceStrategy(context.toolCallCount, context.turnCount, context);
82
+ agent.modelSettings = {
83
+ ...agent.modelSettings,
84
+ tool_choice: toolChoice
85
+ };
86
+ }
87
+ const stream = provider.createResponseStream(model, messages, agent);
88
+ for await (const event of stream) {
89
+ if (options.allowedEvents && !options.allowedEvents.includes(event.type)) {
90
+ continue;
91
+ }
92
+ if (options.eventEmitter) {
93
+ await options.eventEmitter(event, context);
94
+ }
95
+ events.push(event);
96
+ switch (event.type) {
97
+ case 'message_complete':
98
+ if ('content' in event) {
99
+ messageContent = event.content;
100
+ hasMessage = true;
101
+ }
102
+ break;
103
+ case 'tool_start':
104
+ if ('tool_calls' in event && event.tool_calls) {
105
+ const processedCalls = await processToolCalls(event.tool_calls, options, context);
106
+ collectedToolCalls.push(...processedCalls.calls);
107
+ toolResults.push(...processedCalls.results);
108
+ }
109
+ break;
110
+ case 'error':
111
+ if (context) {
112
+ context.halt();
113
+ }
114
+ break;
115
+ }
116
+ }
117
+ if (hasMessage || collectedToolCalls.length > 0) {
118
+ history.addAssistantResponse(messageContent, collectedToolCalls.map((call, i) => ({
119
+ ...call,
120
+ result: toolResults[i]?.output
121
+ })));
122
+ }
123
+ if (context) {
124
+ context.messages = history.getMessages();
125
+ context.toolCallCount += collectedToolCalls.length;
126
+ }
127
+ return {
128
+ events,
129
+ done: context?.isHalted || false,
130
+ hasToolCalls: collectedToolCalls.length > 0
131
+ };
132
+ }
133
+ async function processToolCalls(toolCalls, options, context) {
134
+ const processedCalls = [];
135
+ const results = [];
136
+ for (const toolCall of toolCalls) {
137
+ if (options.toolHandler?.onToolCall) {
138
+ const action = await options.toolHandler.onToolCall(toolCall, options.toolHandler.context || context);
139
+ if (action === ToolCallAction.SKIP) {
140
+ continue;
141
+ }
142
+ if (action === ToolCallAction.HALT && context) {
143
+ context.halt();
144
+ break;
145
+ }
146
+ }
147
+ processedCalls.push(toolCall);
148
+ try {
149
+ let result;
150
+ if (options.processToolCall) {
151
+ result = await options.processToolCall([toolCall]);
152
+ }
153
+ else if (options.toolHandler?.executor) {
154
+ const tool = options.tools?.find(t => t.definition.function.name === toolCall.function.name);
155
+ if (tool) {
156
+ result = await options.toolHandler.executor(tool, JSON.parse(toolCall.function.arguments || '{}'), options.toolHandler.context || context);
157
+ }
158
+ }
159
+ else if (options.tools) {
160
+ const tool = options.tools.find(t => t.definition.function.name === toolCall.function.name);
161
+ if (tool && 'function' in tool) {
162
+ result = await tool.function(JSON.parse(toolCall.function.arguments || '{}'));
163
+ }
164
+ }
165
+ if (result !== undefined && options.toolResultTransformer?.transform) {
166
+ result = options.toolResultTransformer.transform(toolCall.function.name, result, options.toolHandler?.context || context);
167
+ }
168
+ results.push({
169
+ id: toolCall.id,
170
+ call_id: toolCall.call_id || toolCall.id,
171
+ output: typeof result === 'string' ? result : JSON.stringify(result)
172
+ });
173
+ if (options.toolHandler?.onToolComplete) {
174
+ await options.toolHandler.onToolComplete(toolCall, result, options.toolHandler.context || context);
175
+ }
176
+ }
177
+ catch (error) {
178
+ let errorResult = `Tool execution failed: ${error}`;
179
+ if (options.toolHandler?.onToolError) {
180
+ errorResult = await options.toolHandler.onToolError(toolCall, error, options.toolHandler.context || context) || errorResult;
181
+ }
182
+ results.push({
183
+ id: toolCall.id,
184
+ call_id: toolCall.call_id || toolCall.id,
185
+ output: errorResult
186
+ });
187
+ }
188
+ }
189
+ return { calls: processedCalls, results };
190
+ }
191
+ async function shouldContinue(context, iteration, maxIterations, options) {
192
+ if (context?.isHalted)
193
+ return false;
194
+ if (iteration >= maxIterations)
195
+ return false;
196
+ if (options.loop && typeof options.loop === 'object' && options.loop.continueCondition) {
197
+ return await Promise.resolve(options.loop.continueCondition(context));
198
+ }
199
+ return true;
200
+ }
201
+ function getMaxIterations(options) {
202
+ if (!options.loop)
203
+ return 1;
204
+ if (typeof options.loop === 'boolean')
205
+ return options.loop ? Infinity : 1;
206
+ return options.loop.maxIterations || Infinity;
207
+ }
208
+ function createMetricsEvent(context, history) {
209
+ return {
210
+ type: 'system_update',
211
+ data: {
212
+ type: 'metrics',
213
+ messageCount: history.count(),
214
+ toolCallCount: context?.toolCallCount || 0,
215
+ duration: context ? Date.now() - context.startTime : 0,
216
+ summary: history.getSummary()
217
+ },
218
+ timestamp: new Date().toISOString()
219
+ };
220
+ }
221
+ export { RequestAgent };
222
+ //# sourceMappingURL=unified_request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"unified_request.js","sourceRoot":"","sources":["../unified_request.ts"],"names":[],"mappings":"AAcA,OAAO,EAGH,oBAAoB,EACpB,cAAc,EACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAa,MAAM,0BAA0B,CAAC;AAG3E,MAAM,YAAY;IACd,QAAQ,CAAS;IACjB,aAAa,CAAiB;IAC9B,UAAU,CAAgB;IAClB,KAAK,CAAiB;IAE9B,YAAY,OAA2B;QACnC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,OAAO,IAAI,UAAU,CAAC;QAC9C,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC;QAC3C,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;QACrC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,QAAQ;QACV,OAAO,IAAI,CAAC,KAAK,CAAC;IACtB,CAAC;CACJ;AAYD,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,cAAc,CACjC,KAAa,EACb,QAAuB,EACvB,UAAiC,EAAE;IAGnC,MAAM,WAAW,GAAG,OAAO,CAAC,eAAe;QACvC,OAAO,CAAC,WAAW;QACnB,OAAO,CAAC,IAAI;QACZ,OAAO,CAAC,cAAc;QACtB,OAAO,CAAC,UAAU;QAClB,OAAO,CAAC,qBAAqB,CAAC;IAGlC,MAAM,OAAO,GAAG,OAAO,CAAC,cAAc,IAAI,IAAI,cAAc,CAAC,QAAQ,EAAE;QACnE,gBAAgB,EAAE,IAAI;QACtB,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EDED",
7
+ TOOL_NOT_FOUND = "TOOL_NOT_FOUND",
8
+ TOOL_EXECUTION_FAILED = "TOOL_EXECUTION_FAILED",
9
+ TOOL_TIMEOUT = "TOOL_TIMEOUT",
10
+ TOOL_VALIDATION_FAILED = "TOOL_VALIDATION_FAILED",
11
+ MAX_TOOL_CALLS_EXCEEDED = "MAX_TOOL_CALLS_EXCEEDED",
12
+ LOOP_TIMEOUT = "LOOP_TIMEOUT",
13
+ INVALID_REQUEST = "INVALID_REQUEST",
14
+ UNKNOWN_ERROR = "UNKNOWN_ERROR"
15
+ }
16
+ export interface EnsembleError extends Error {
17
+ code: ErrorCode;
18
+ details?: any;
19
+ recoverable?: boolean;
20
+ retry?: {
21
+ attempts: number;
22
+ delay: number;
23
+ };
24
+ }
25
+ export declare class EnsembleErrorHandler {
26
+ private static retryDelays;
27
+ static createError(code: ErrorCode, message: string, details?: any, recoverable?: boolean): EnsembleError;
28
+ static handleWithRetry<T>(operation: () => Promise<T>, maxRetries?: number, isRetryable?: (error: any) => boolean): Promise<T>;
29
+ static isRetryableError(error: any): boolean;
30
+ static toStreamEvent(error: any): EnsembleStreamEvent;
31
+ static getUserMessage(error: any): string;
32
+ }
33
+ //# sourceMappingURL=error_handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error_handler.d.ts","sourceRoot":"","sources":["../../utils/error_handler.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAElD,oBAAY,SAAS;IAEjB,kBAAkB,uBAAuB;IACzC,oBAAoB,yBAAyB;IAC7C,mBAAmB,wBAAwB;IAC3C,uBAAuB,4BAA4B;IAGnD,cAAc,mBAAmB;IACjC,qBAAqB,0BAA0B;IAC/C,YAAY,iBAAiB;IAC7B,sBAAsB,2BAA2B;IAGjD,uBAAuB,4BAA4B;IACnD,YAAY,iBAAiB;IAC7B,eAAe,oBAAoB;IAGnC,aAAa,kBAAkB;CAClC;AAED,MAAM,WAAW,aAAc,SAAQ,KAAK;IACxC,IAAI,EAAE,SAAS,CAAC;IAChB,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,KAAK,CAAC,EAAE;QACJ,QAAQ,EAAE,MAAM,CAAC;QACjB,KAAK,EAAE,MAAM,CAAC;KACjB,CAAC;CACL;AAED,qBAAa,oBAAoB;IAC7B,OAAO,CAAC,MAAM,CAAC,WAAW,CAA4B;IAKtD,MAAM,CAAC,WAAW,CACd,IAAI,EAAE,SAAS,EACf,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,GAAG,EACb,WAAW,UAAQ,GACpB,aAAa;WAWH,eAAe,CAAC,CAAC,EAC1B,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAC3B,UAAU,SAAI,EACd,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,OAAO,GACtC,OAAO,CAAC,CAAC,CAAC;IA6Bb,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE,GAAG,GAAG,OAAO;IAoB5C,MAAM,CAAC,aAAa,CAAC,KAAK,EAAE,GAAG,GAAG,mBAAmB;IAgBrD,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,GAAG,GAAG,MAAM;CAgB5C"}
@@ -0,0 +1,84 @@
1
+ export var ErrorCode;
2
+ (function (ErrorCode) {
3
+ ErrorCode["PROVIDER_NOT_FOUND"] = "PROVIDER_NOT_FOUND";
4
+ ErrorCode["PROVIDER_AUTH_FAILED"] = "PROVIDER_AUTH_FAILED";
5
+ ErrorCode["PROVIDER_RATE_LIMIT"] = "PROVIDER_RATE_LIMIT";
6
+ ErrorCode["PROVIDER_QUOTA_EXCEEDED"] = "PROVIDER_QUOTA_EXCEEDED";
7
+ ErrorCode["TOOL_NOT_FOUND"] = "TOOL_NOT_FOUND";
8
+ ErrorCode["TOOL_EXECUTION_FAILED"] = "TOOL_EXECUTION_FAILED";
9
+ ErrorCode["TOOL_TIMEOUT"] = "TOOL_TIMEOUT";
10
+ ErrorCode["TOOL_VALIDATION_FAILED"] = "TOOL_VALIDATION_FAILED";
11
+ ErrorCode["MAX_TOOL_CALLS_EXCEEDED"] = "MAX_TOOL_CALLS_EXCEEDED";
12
+ ErrorCode["LOOP_TIMEOUT"] = "LOOP_TIMEOUT";
13
+ ErrorCode["INVALID_REQUEST"] = "INVALID_REQUEST";
14
+ ErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
15
+ })(ErrorCode || (ErrorCode = {}));
16
+ export class EnsembleErrorHandler {
17
+ static retryDelays = [1000, 2000, 4000, 8000];
18
+ static createError(code, message, details, recoverable = false) {
19
+ const error = new Error(message);
20
+ error.code = code;
21
+ error.details = details;
22
+ error.recoverable = recoverable;
23
+ return error;
24
+ }
25
+ static async handleWithRetry(operation, maxRetries = 3, isRetryable) {
26
+ let lastError;
27
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
28
+ try {
29
+ return await operation();
30
+ }
31
+ catch (error) {
32
+ lastError = error;
33
+ const shouldRetry = isRetryable ? isRetryable(error) :
34
+ this.isRetryableError(error);
35
+ if (!shouldRetry || attempt === maxRetries) {
36
+ throw error;
37
+ }
38
+ const delay = this.retryDelays[Math.min(attempt, this.retryDelays.length - 1)];
39
+ await new Promise(resolve => setTimeout(resolve, delay));
40
+ }
41
+ }
42
+ throw lastError;
43
+ }
44
+ static isRetryableError(error) {
45
+ if (error?.code) {
46
+ return [
47
+ ErrorCode.PROVIDER_RATE_LIMIT,
48
+ ErrorCode.TOOL_TIMEOUT,
49
+ ErrorCode.PROVIDER_QUOTA_EXCEEDED
50
+ ].includes(error.code);
51
+ }
52
+ if (error?.status) {
53
+ return [429, 502, 503, 504].includes(error.status);
54
+ }
55
+ return false;
56
+ }
57
+ static toStreamEvent(error) {
58
+ const ensembleError = error;
59
+ return {
60
+ type: 'error',
61
+ error: error.message || 'Unknown error',
62
+ code: ensembleError.code,
63
+ details: ensembleError.details,
64
+ recoverable: ensembleError.recoverable,
65
+ timestamp: new Date().toISOString()
66
+ };
67
+ }
68
+ static getUserMessage(error) {
69
+ const ensembleError = error;
70
+ switch (ensembleError.code) {
71
+ case ErrorCode.PROVIDER_AUTH_FAILED:
72
+ return 'Authentication failed. Please check your API key.';
73
+ case ErrorCode.PROVIDER_RATE_LIMIT:
74
+ return 'Rate limit exceeded. Please try again later.';
75
+ case ErrorCode.TOOL_NOT_FOUND:
76
+ return `Tool "${ensembleError.details?.toolName}" not found.`;
77
+ case ErrorCode.MAX_TOOL_CALLS_EXCEEDED:
78
+ return 'Maximum number of tool calls exceeded.';
79
+ default:
80
+ return error.message || 'An unexpected error occurred.';
81
+ }
82
+ }
83
+ }
84
+ //# sourceMappingURL=error_handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error_handler.js","sourceRoot":"","sources":["../../utils/error_handler.ts"],"names":[],"mappings":"AAMA,MAAM,CAAN,IAAY,SAoBX;AApBD,WAAY,SAAS;IAEjB,sDAAyC,CAAA;IACzC,0DAA6C,CAAA;IAC7C,wDAA2C,CAAA;IAC3C,gEAAmD,CAAA;IAGnD,8CAAiC,CAAA;IACjC,4DAA+C,CAAA;IAC/C,0CAA6B,CAAA;IAC7B,8DAAiD,CAAA;IAGjD,gEAAmD,CAAA;IACnD,0CAA6B,CAAA;IAC7B,gDAAmC,CAAA;IAGnC,4CAA+B,CAAA;AACnC,CAAC,EApBW,SAAS,KAAT,SAAS,QAoBpB;AAYD,MAAM,OAAO,oBAAoB;IACrB,MAAM,CAAC,WAAW,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAKtD,MAAM,CAAC,WAAW,CACd,IAAe,EACf,OAAe,EACf,OAAa,EACb,WAAW,GAAG,KAAK;QAEnB,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,OAAO,CAAkB,CAAC;QAClD,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC;QAClB,KAAK,CAAC,OAAO,GAA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AAE,MAAM,EAAE,CAAC;YAChB,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QACvD,CAAC;QAED,OAAO,KAAK,CAAC;IACjB,CAAC;IAKD,MAAM,CAAC,aAAa,CAAC,KAAU;QAC3B,MAAM,aAAa,GAAG,KAAsB,CAAC;QAE7C,OAAO;YACH,IAAI,EAAE,OAAO;YACb,KAAK,EAAE,KAAK,CAAC,OAAO,IAAI,eAAe;YACvC,IAAI,EAAE,aAAa,CAAC,IAAI;YACxB,OAAO,EAAE,aAAa,CAAC,OAAO;YAC9B,WAAW,EAAE,aAAa,CAAC,WAAW;YACtC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;SACf,CAAC;IAC7B,CAAC;IAKD,MAAM,CAAC,cAAc,CAAC,KAAU;QAC5B,MAAM,aAAa,GAAG,KAAsB,CAAC;QAE7C,QAAQ,aAAa,CAAC,IAAI,EAAE,CAAC;YACzB,KAAK,SAAS,CAAC,oBAAoB;gBAC/B,OAAO,mDAAmD,CAAC;YAC/D,KAAK,SAAS,CAAC,mBAAmB;gBAC9B,OAAO,8CAA8C,CAAC;YAC1D,KAAK,SAAS,CAAC,cAAc;gBACzB,OAAO,SAAS,aAAa,CAAC,OAAO,EAAE,QAAQ,cAAc,CAAC;YAClE,KAAK,SAAS,CAAC,uBAAuB;gBAClC,OAAO,wCAAwC,CAAC;YACpD;gBACI,OAAO,KAAK,CAAC,OAAO,IAAI,+BAA+B,CAAC;QAChE,CAAC;IACL,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { ResponseInput } from '../types.js';
2
+ export interface MessageHistoryOptions {
3
+ maxMessages?: number;
4
+ maxTokens?: number;
5
+ preserveSystemMessages?: boolean;
6
+ compactToolCalls?: boolean;
7
+ }
8
+ export declare class MessageHistory {
9
+ private messages;
10
+ private options;
11
+ constructor(initialMessages?: ResponseInput, options?: MessageHistoryOptions);
12
+ add(message: any): void;
13
+ addMany(messages: any[]): void;
14
+ addAssistantResponse(content: string, toolCalls?: any[]): void;
15
+ getMessages(): ResponseInput;
16
+ count(): number;
17
+ clear(): void;
18
+ private trim;
19
+ private compactToolCalls;
20
+ getSummary(): string;
21
+ findLast(predicate: (msg: any) => boolean): any | undefined;
22
+ lastAssistantHadToolCalls(): boolean;
23
+ }
24
+ //# sourceMappingURL=message_history.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"message_history.d.ts","sourceRoot":"","sources":["../../utils/message_history.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C,MAAM,WAAW,qBAAqB;IAClC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,qBAAa,cAAc;IACvB,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,OAAO,CAAwB;gBAE3B,eAAe,GAAE,aAAkB,EAAE,OAAO,GAAE,qBAA0B;IAapF,GAAG,CAAC,OAAO,EAAE,GAAG,GAAG,IAAI;IAQvB,OAAO,CAAC,QAAQ,EAAE,GAAG,EAAE,GAAG,IAAI;IAQ9B,oBAAoB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,GAAG,EAAE,GAAG,IAAI;IAsC9D,WAAW,IAAI,aAAa;IAO5B,KAAK,IAAI,MAAM;IAOf,KAAK,IAAI,IAAI;IAUb,OAAO,CAAC,IAAI;IAqBZ,OAAO,CAAC,gBAAgB;IAmCxB,UAAU,IAAI,MAAM;IA4BpB,QAAQ,CAAC,SAAS,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,OAAO,GAAG,GAAG,GAAG,SAAS;IAY3D,yBAAyB,IAAI,OAAO;CA2BvC"}