@agnt5/sdk 0.2.1
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 +183 -0
- package/dist/__tests__/integration/helpers.d.ts +41 -0
- package/dist/__tests__/integration/helpers.d.ts.map +1 -0
- package/dist/__tests__/integration/helpers.js +78 -0
- package/dist/__tests__/integration/helpers.js.map +1 -0
- package/dist/agent.d.ts +260 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +493 -0
- package/dist/agent.js.map +1 -0
- package/dist/async-context.d.ts +57 -0
- package/dist/async-context.d.ts.map +1 -0
- package/dist/async-context.js +52 -0
- package/dist/async-context.js.map +1 -0
- package/dist/batch.d.ts +116 -0
- package/dist/batch.d.ts.map +1 -0
- package/dist/batch.js +98 -0
- package/dist/batch.js.map +1 -0
- package/dist/chat.d.ts +137 -0
- package/dist/chat.d.ts.map +1 -0
- package/dist/chat.js +278 -0
- package/dist/chat.js.map +1 -0
- package/dist/client.d.ts +394 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +757 -0
- package/dist/client.js.map +1 -0
- package/dist/context.d.ts +47 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +244 -0
- package/dist/context.js.map +1 -0
- package/dist/errors.d.ts +148 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +201 -0
- package/dist/errors.js.map +1 -0
- package/dist/eval.d.ts +242 -0
- package/dist/eval.d.ts.map +1 -0
- package/dist/eval.js +452 -0
- package/dist/eval.js.map +1 -0
- package/dist/event-emitter.d.ts +28 -0
- package/dist/event-emitter.d.ts.map +1 -0
- package/dist/event-emitter.js +79 -0
- package/dist/event-emitter.js.map +1 -0
- package/dist/events.d.ts +285 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +256 -0
- package/dist/events.js.map +1 -0
- package/dist/function.d.ts +61 -0
- package/dist/function.d.ts.map +1 -0
- package/dist/function.js +78 -0
- package/dist/function.js.map +1 -0
- package/dist/index.d.ts +67 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +80 -0
- package/dist/index.js.map +1 -0
- package/dist/lm.d.ts +301 -0
- package/dist/lm.d.ts.map +1 -0
- package/dist/lm.js +283 -0
- package/dist/lm.js.map +1 -0
- package/dist/logging.d.ts +68 -0
- package/dist/logging.d.ts.map +1 -0
- package/dist/logging.js +165 -0
- package/dist/logging.js.map +1 -0
- package/dist/mcp-server.d.ts +98 -0
- package/dist/mcp-server.d.ts.map +1 -0
- package/dist/mcp-server.js +307 -0
- package/dist/mcp-server.js.map +1 -0
- package/dist/mcp.d.ts +73 -0
- package/dist/mcp.d.ts.map +1 -0
- package/dist/mcp.js +224 -0
- package/dist/mcp.js.map +1 -0
- package/dist/memory.d.ts +234 -0
- package/dist/memory.d.ts.map +1 -0
- package/dist/memory.js +609 -0
- package/dist/memory.js.map +1 -0
- package/dist/platform-adapters.d.ts +121 -0
- package/dist/platform-adapters.d.ts.map +1 -0
- package/dist/platform-adapters.js +174 -0
- package/dist/platform-adapters.js.map +1 -0
- package/dist/platform-context.d.ts +55 -0
- package/dist/platform-context.d.ts.map +1 -0
- package/dist/platform-context.js +196 -0
- package/dist/platform-context.js.map +1 -0
- package/dist/retry-utils.d.ts +169 -0
- package/dist/retry-utils.d.ts.map +1 -0
- package/dist/retry-utils.js +304 -0
- package/dist/retry-utils.js.map +1 -0
- package/dist/sandbox.d.ts +103 -0
- package/dist/sandbox.d.ts.map +1 -0
- package/dist/sandbox.js +168 -0
- package/dist/sandbox.js.map +1 -0
- package/dist/schema-utils.d.ts +250 -0
- package/dist/schema-utils.d.ts.map +1 -0
- package/dist/schema-utils.js +444 -0
- package/dist/schema-utils.js.map +1 -0
- package/dist/scorer.d.ts +130 -0
- package/dist/scorer.d.ts.map +1 -0
- package/dist/scorer.js +211 -0
- package/dist/scorer.js.map +1 -0
- package/dist/state.d.ts +92 -0
- package/dist/state.d.ts.map +1 -0
- package/dist/state.js +151 -0
- package/dist/state.js.map +1 -0
- package/dist/tool.d.ts +120 -0
- package/dist/tool.d.ts.map +1 -0
- package/dist/tool.js +215 -0
- package/dist/tool.js.map +1 -0
- package/dist/tracing.d.ts +82 -0
- package/dist/tracing.d.ts.map +1 -0
- package/dist/tracing.js +206 -0
- package/dist/tracing.js.map +1 -0
- package/dist/types.d.ts +139 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/worker.d.ts +111 -0
- package/dist/worker.d.ts.map +1 -0
- package/dist/worker.js +944 -0
- package/dist/worker.js.map +1 -0
- package/dist/workflow-utils.d.ts +257 -0
- package/dist/workflow-utils.d.ts.map +1 -0
- package/dist/workflow-utils.js +370 -0
- package/dist/workflow-utils.js.map +1 -0
- package/dist/workflow.d.ts +78 -0
- package/dist/workflow.d.ts.map +1 -0
- package/dist/workflow.js +138 -0
- package/dist/workflow.js.map +1 -0
- package/package.json +86 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Retry and backoff utilities for durable execution.
|
|
3
|
+
*
|
|
4
|
+
* This module provides utilities for parsing retry policies, calculating backoff delays,
|
|
5
|
+
* and executing functions with retry logic.
|
|
6
|
+
*/
|
|
7
|
+
import type { RetryPolicy, BackoffPolicy, Context } from './types.js';
|
|
8
|
+
/**
|
|
9
|
+
* Default retry policy configuration
|
|
10
|
+
*/
|
|
11
|
+
export declare const DEFAULT_RETRY_POLICY: Required<RetryPolicy>;
|
|
12
|
+
/**
|
|
13
|
+
* Default backoff policy configuration
|
|
14
|
+
*/
|
|
15
|
+
export declare const DEFAULT_BACKOFF_POLICY: Required<BackoffPolicy>;
|
|
16
|
+
/**
|
|
17
|
+
* Parse retry configuration from various forms.
|
|
18
|
+
*
|
|
19
|
+
* @param retries - Can be:
|
|
20
|
+
* - number: max_attempts (e.g., 5)
|
|
21
|
+
* - RetryPolicy: complete configuration
|
|
22
|
+
* - undefined: use default
|
|
23
|
+
* @returns Complete RetryPolicy
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```typescript
|
|
27
|
+
* parseRetryPolicy(5) // { maxAttempts: 5, initialIntervalMs: 1000, maxIntervalMs: 60000 }
|
|
28
|
+
* parseRetryPolicy({ maxAttempts: 3, initialIntervalMs: 2000 })
|
|
29
|
+
* parseRetryPolicy(undefined) // Uses defaults
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare function parseRetryPolicy(retries?: number | RetryPolicy): Required<RetryPolicy>;
|
|
33
|
+
/**
|
|
34
|
+
* Parse backoff configuration from various forms.
|
|
35
|
+
*
|
|
36
|
+
* @param backoff - Can be:
|
|
37
|
+
* - string: backoff type ("constant", "linear", "exponential")
|
|
38
|
+
* - BackoffPolicy: complete configuration
|
|
39
|
+
* - undefined: use default
|
|
40
|
+
* @returns Complete BackoffPolicy
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* parseBackoffPolicy('exponential') // { type: 'exponential', multiplier: 2.0 }
|
|
45
|
+
* parseBackoffPolicy({ type: 'linear', multiplier: 1.5 })
|
|
46
|
+
* parseBackoffPolicy(undefined) // Uses defaults
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
export declare function parseBackoffPolicy(backoff?: string | BackoffPolicy): Required<BackoffPolicy>;
|
|
50
|
+
/**
|
|
51
|
+
* Calculate backoff delay in milliseconds based on attempt number.
|
|
52
|
+
*
|
|
53
|
+
* @param attempt - Current attempt number (0-indexed)
|
|
54
|
+
* @param retryPolicy - Retry configuration
|
|
55
|
+
* @param backoffPolicy - Backoff configuration
|
|
56
|
+
* @param jitter - Add jitter to prevent thundering herd (default: true)
|
|
57
|
+
* @returns Delay in milliseconds
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```typescript
|
|
61
|
+
* // Exponential backoff: 1s → 2s → 4s → 8s
|
|
62
|
+
* calculateBackoffDelay(0, policy, { type: 'exponential', multiplier: 2.0 }) // ~1000ms
|
|
63
|
+
* calculateBackoffDelay(1, policy, { type: 'exponential', multiplier: 2.0 }) // ~2000ms
|
|
64
|
+
* calculateBackoffDelay(2, policy, { type: 'exponential', multiplier: 2.0 }) // ~4000ms
|
|
65
|
+
*
|
|
66
|
+
* // With jitter (adds randomness ±25%)
|
|
67
|
+
* calculateBackoffDelay(1, policy, backoff, true) // ~1500ms - 2500ms
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export declare function calculateBackoffDelay(attempt: number, retryPolicy: Required<RetryPolicy>, backoffPolicy: Required<BackoffPolicy>, jitter?: boolean): number;
|
|
71
|
+
/**
|
|
72
|
+
* Custom retry predicate function type.
|
|
73
|
+
* Return true to retry, false to abort.
|
|
74
|
+
*/
|
|
75
|
+
export type RetryPredicate = (error: Error, attempt: number) => boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Options for executeWithRetry
|
|
78
|
+
*/
|
|
79
|
+
export interface ExecuteWithRetryOptions {
|
|
80
|
+
/** Retry policy (attempts, intervals) */
|
|
81
|
+
retryPolicy?: number | RetryPolicy;
|
|
82
|
+
/** Backoff policy (type, multiplier) */
|
|
83
|
+
backoffPolicy?: string | BackoffPolicy;
|
|
84
|
+
/** Add jitter to backoff delays (default: true) */
|
|
85
|
+
jitter?: boolean;
|
|
86
|
+
/** Custom predicate to determine if retry should happen */
|
|
87
|
+
retryPredicate?: RetryPredicate;
|
|
88
|
+
/** Context for logging (optional) */
|
|
89
|
+
context?: Context;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Execute a function with retry logic.
|
|
93
|
+
*
|
|
94
|
+
* @param fn - The async function to execute
|
|
95
|
+
* @param options - Retry configuration options
|
|
96
|
+
* @returns Result of successful execution
|
|
97
|
+
* @throws RetryError if all retry attempts fail
|
|
98
|
+
*
|
|
99
|
+
* @example
|
|
100
|
+
* ```typescript
|
|
101
|
+
* // Simple retry with defaults (3 attempts, exponential backoff)
|
|
102
|
+
* const result = await executeWithRetry(async () => {
|
|
103
|
+
* return await fetchData();
|
|
104
|
+
* });
|
|
105
|
+
*
|
|
106
|
+
* // Custom retry policy
|
|
107
|
+
* const result = await executeWithRetry(
|
|
108
|
+
* async () => await processData(),
|
|
109
|
+
* {
|
|
110
|
+
* retryPolicy: { maxAttempts: 5, initialIntervalMs: 2000 },
|
|
111
|
+
* backoffPolicy: 'linear',
|
|
112
|
+
* jitter: true,
|
|
113
|
+
* }
|
|
114
|
+
* );
|
|
115
|
+
*
|
|
116
|
+
* // With custom retry predicate
|
|
117
|
+
* const result = await executeWithRetry(
|
|
118
|
+
* async () => await callAPI(),
|
|
119
|
+
* {
|
|
120
|
+
* retryPolicy: 3,
|
|
121
|
+
* retryPredicate: (error, attempt) => {
|
|
122
|
+
* // Only retry on network errors
|
|
123
|
+
* return error.message.includes('ECONNREFUSED');
|
|
124
|
+
* },
|
|
125
|
+
* }
|
|
126
|
+
* );
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
export declare function executeWithRetry<T>(fn: () => Promise<T>, options?: ExecuteWithRetryOptions): Promise<T>;
|
|
130
|
+
/**
|
|
131
|
+
* Create a retry wrapper function for repeated use.
|
|
132
|
+
*
|
|
133
|
+
* @param options - Retry configuration options
|
|
134
|
+
* @returns Function that executes with retry logic
|
|
135
|
+
*
|
|
136
|
+
* @example
|
|
137
|
+
* ```typescript
|
|
138
|
+
* const retryableFetch = createRetryWrapper({
|
|
139
|
+
* retryPolicy: 5,
|
|
140
|
+
* backoffPolicy: 'exponential',
|
|
141
|
+
* });
|
|
142
|
+
*
|
|
143
|
+
* const data1 = await retryableFetch(() => fetch('/api/data1'));
|
|
144
|
+
* const data2 = await retryableFetch(() => fetch('/api/data2'));
|
|
145
|
+
* ```
|
|
146
|
+
*/
|
|
147
|
+
export declare function createRetryWrapper(options?: ExecuteWithRetryOptions): <T>(fn: () => Promise<T>) => Promise<T>;
|
|
148
|
+
/**
|
|
149
|
+
* Retry with timeout - execute with retry logic and overall timeout.
|
|
150
|
+
*
|
|
151
|
+
* @param fn - The async function to execute
|
|
152
|
+
* @param timeoutMs - Maximum time to spend retrying (in milliseconds)
|
|
153
|
+
* @param options - Retry configuration options
|
|
154
|
+
* @returns Result of successful execution
|
|
155
|
+
* @throws TimeoutError if timeout is exceeded
|
|
156
|
+
* @throws RetryError if all retry attempts fail
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* ```typescript
|
|
160
|
+
* // Retry for up to 30 seconds
|
|
161
|
+
* const result = await executeWithRetryAndTimeout(
|
|
162
|
+
* async () => await processData(),
|
|
163
|
+
* 30000, // 30 seconds
|
|
164
|
+
* { retryPolicy: 10 }
|
|
165
|
+
* );
|
|
166
|
+
* ```
|
|
167
|
+
*/
|
|
168
|
+
export declare function executeWithRetryAndTimeout<T>(fn: () => Promise<T>, timeoutMs: number, options?: ExecuteWithRetryOptions): Promise<T>;
|
|
169
|
+
//# sourceMappingURL=retry-utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry-utils.d.ts","sourceRoot":"","sources":["../src/retry-utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAGtE;;GAEG;AACH,eAAO,MAAM,oBAAoB,EAAE,QAAQ,CAAC,WAAW,CAItD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,sBAAsB,EAAE,QAAQ,CAAC,aAAa,CAG1D,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,WAAW,GAAG,QAAQ,CAAC,WAAW,CAAC,CAqBtF;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,aAAa,GAAG,QAAQ,CAAC,aAAa,CAAC,CAwB5F;AAED;;;;;;;;;;;;;;;;;;;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/**
|
|
2
|
+
* Retry and backoff utilities for durable execution.
|
|
3
|
+
*
|
|
4
|
+
* This module provides utilities for parsing retry policies, calculating backoff delays,
|
|
5
|
+
* and executing functions with retry logic.
|
|
6
|
+
*/
|
|
7
|
+
import { RetryError } from './errors.js';
|
|
8
|
+
/**
|
|
9
|
+
* Default retry policy configuration
|
|
10
|
+
*/
|
|
11
|
+
export const DEFAULT_RETRY_POLICY = {
|
|
12
|
+
maxAttempts: 3,
|
|
13
|
+
initialIntervalMs: 1000, // 1 second
|
|
14
|
+
maxIntervalMs: 60000, // 60 seconds
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Default backoff policy configuration
|
|
18
|
+
*/
|
|
19
|
+
export const DEFAULT_BACKOFF_POLICY = {
|
|
20
|
+
type: 'exponential',
|
|
21
|
+
multiplier: 2.0,
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Parse retry configuration from various forms.
|
|
25
|
+
*
|
|
26
|
+
* @param retries - Can be:
|
|
27
|
+
* - number: max_attempts (e.g., 5)
|
|
28
|
+
* - RetryPolicy: complete configuration
|
|
29
|
+
* - undefined: use default
|
|
30
|
+
* @returns Complete RetryPolicy
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```typescript
|
|
34
|
+
* parseRetryPolicy(5) // { maxAttempts: 5, initialIntervalMs: 1000, maxIntervalMs: 60000 }
|
|
35
|
+
* parseRetryPolicy({ maxAttempts: 3, initialIntervalMs: 2000 })
|
|
36
|
+
* parseRetryPolicy(undefined) // Uses defaults
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export function parseRetryPolicy(retries) {
|
|
40
|
+
if (retries === undefined || retries === null) {
|
|
41
|
+
return DEFAULT_RETRY_POLICY;
|
|
42
|
+
}
|
|
43
|
+
if (typeof retries === 'number') {
|
|
44
|
+
return {
|
|
45
|
+
...DEFAULT_RETRY_POLICY,
|
|
46
|
+
maxAttempts: retries,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
if (typeof retries === 'object') {
|
|
50
|
+
return {
|
|
51
|
+
maxAttempts: retries.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,
|
|
52
|
+
initialIntervalMs: retries.initialIntervalMs ?? DEFAULT_RETRY_POLICY.initialIntervalMs,
|
|
53
|
+
maxIntervalMs: retries.maxIntervalMs ?? DEFAULT_RETRY_POLICY.maxIntervalMs,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
throw new TypeError(`retries must be number or RetryPolicy, got ${typeof retries}`);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Parse backoff configuration from various forms.
|
|
60
|
+
*
|
|
61
|
+
* @param backoff - Can be:
|
|
62
|
+
* - string: backoff type ("constant", "linear", "exponential")
|
|
63
|
+
* - BackoffPolicy: complete configuration
|
|
64
|
+
* - undefined: use default
|
|
65
|
+
* @returns Complete BackoffPolicy
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```typescript
|
|
69
|
+
* parseBackoffPolicy('exponential') // { type: 'exponential', multiplier: 2.0 }
|
|
70
|
+
* parseBackoffPolicy({ type: 'linear', multiplier: 1.5 })
|
|
71
|
+
* parseBackoffPolicy(undefined) // Uses defaults
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
export function parseBackoffPolicy(backoff) {
|
|
75
|
+
if (backoff === undefined || backoff === null) {
|
|
76
|
+
return DEFAULT_BACKOFF_POLICY;
|
|
77
|
+
}
|
|
78
|
+
if (typeof backoff === 'string') {
|
|
79
|
+
const type = backoff.toLowerCase();
|
|
80
|
+
if (type !== 'constant' && type !== 'linear' && type !== 'exponential') {
|
|
81
|
+
throw new TypeError(`backoff type must be "constant", "linear", or "exponential", got "${backoff}"`);
|
|
82
|
+
}
|
|
83
|
+
return {
|
|
84
|
+
...DEFAULT_BACKOFF_POLICY,
|
|
85
|
+
type,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
if (typeof backoff === 'object') {
|
|
89
|
+
return {
|
|
90
|
+
type: backoff.type ?? DEFAULT_BACKOFF_POLICY.type,
|
|
91
|
+
multiplier: backoff.multiplier ?? DEFAULT_BACKOFF_POLICY.multiplier,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
throw new TypeError(`backoff must be string or BackoffPolicy, got ${typeof backoff}`);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Calculate backoff delay in milliseconds based on attempt number.
|
|
98
|
+
*
|
|
99
|
+
* @param attempt - Current attempt number (0-indexed)
|
|
100
|
+
* @param retryPolicy - Retry configuration
|
|
101
|
+
* @param backoffPolicy - Backoff configuration
|
|
102
|
+
* @param jitter - Add jitter to prevent thundering herd (default: true)
|
|
103
|
+
* @returns Delay in milliseconds
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* ```typescript
|
|
107
|
+
* // Exponential backoff: 1s → 2s → 4s → 8s
|
|
108
|
+
* calculateBackoffDelay(0, policy, { type: 'exponential', multiplier: 2.0 }) // ~1000ms
|
|
109
|
+
* calculateBackoffDelay(1, policy, { type: 'exponential', multiplier: 2.0 }) // ~2000ms
|
|
110
|
+
* calculateBackoffDelay(2, policy, { type: 'exponential', multiplier: 2.0 }) // ~4000ms
|
|
111
|
+
*
|
|
112
|
+
* // With jitter (adds randomness ±25%)
|
|
113
|
+
* calculateBackoffDelay(1, policy, backoff, true) // ~1500ms - 2500ms
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
export function calculateBackoffDelay(attempt, retryPolicy, backoffPolicy, jitter = true) {
|
|
117
|
+
let delayMs;
|
|
118
|
+
switch (backoffPolicy.type) {
|
|
119
|
+
case 'constant':
|
|
120
|
+
delayMs = retryPolicy.initialIntervalMs;
|
|
121
|
+
break;
|
|
122
|
+
case 'linear':
|
|
123
|
+
delayMs = retryPolicy.initialIntervalMs * (attempt + 1);
|
|
124
|
+
break;
|
|
125
|
+
case 'exponential':
|
|
126
|
+
delayMs = retryPolicy.initialIntervalMs * Math.pow(backoffPolicy.multiplier, attempt);
|
|
127
|
+
break;
|
|
128
|
+
default:
|
|
129
|
+
throw new Error(`Unknown backoff type: ${backoffPolicy.type}`);
|
|
130
|
+
}
|
|
131
|
+
// Cap at max_interval_ms
|
|
132
|
+
delayMs = Math.min(delayMs, retryPolicy.maxIntervalMs);
|
|
133
|
+
// Add jitter (±25% randomness) to prevent thundering herd
|
|
134
|
+
if (jitter) {
|
|
135
|
+
const jitterFactor = 0.25;
|
|
136
|
+
const randomFactor = 1.0 + (Math.random() * 2.0 - 1.0) * jitterFactor;
|
|
137
|
+
delayMs = Math.floor(delayMs * randomFactor);
|
|
138
|
+
}
|
|
139
|
+
return delayMs;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Default retry predicate - always retry unless it's a specific non-retryable error
|
|
143
|
+
*/
|
|
144
|
+
const defaultRetryPredicate = (error, _attempt) => {
|
|
145
|
+
// Import here to avoid circular dependency
|
|
146
|
+
const errorName = error.constructor.name;
|
|
147
|
+
// Don't retry these errors
|
|
148
|
+
const nonRetryableErrors = [
|
|
149
|
+
'ValidationError',
|
|
150
|
+
'RunError',
|
|
151
|
+
'TimeoutError',
|
|
152
|
+
'AuthorizationError',
|
|
153
|
+
];
|
|
154
|
+
return !nonRetryableErrors.includes(errorName);
|
|
155
|
+
};
|
|
156
|
+
/**
|
|
157
|
+
* Execute a function with retry logic.
|
|
158
|
+
*
|
|
159
|
+
* @param fn - The async function to execute
|
|
160
|
+
* @param options - Retry configuration options
|
|
161
|
+
* @returns Result of successful execution
|
|
162
|
+
* @throws RetryError if all retry attempts fail
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* ```typescript
|
|
166
|
+
* // Simple retry with defaults (3 attempts, exponential backoff)
|
|
167
|
+
* const result = await executeWithRetry(async () => {
|
|
168
|
+
* return await fetchData();
|
|
169
|
+
* });
|
|
170
|
+
*
|
|
171
|
+
* // Custom retry policy
|
|
172
|
+
* const result = await executeWithRetry(
|
|
173
|
+
* async () => await processData(),
|
|
174
|
+
* {
|
|
175
|
+
* retryPolicy: { maxAttempts: 5, initialIntervalMs: 2000 },
|
|
176
|
+
* backoffPolicy: 'linear',
|
|
177
|
+
* jitter: true,
|
|
178
|
+
* }
|
|
179
|
+
* );
|
|
180
|
+
*
|
|
181
|
+
* // With custom retry predicate
|
|
182
|
+
* const result = await executeWithRetry(
|
|
183
|
+
* async () => await callAPI(),
|
|
184
|
+
* {
|
|
185
|
+
* retryPolicy: 3,
|
|
186
|
+
* retryPredicate: (error, attempt) => {
|
|
187
|
+
* // Only retry on network errors
|
|
188
|
+
* return error.message.includes('ECONNREFUSED');
|
|
189
|
+
* },
|
|
190
|
+
* }
|
|
191
|
+
* );
|
|
192
|
+
* ```
|
|
193
|
+
*/
|
|
194
|
+
export async function executeWithRetry(fn, options = {}) {
|
|
195
|
+
const retryPolicy = parseRetryPolicy(options.retryPolicy);
|
|
196
|
+
const backoffPolicy = parseBackoffPolicy(options.backoffPolicy);
|
|
197
|
+
const jitter = options.jitter ?? true;
|
|
198
|
+
const retryPredicate = options.retryPredicate ?? defaultRetryPredicate;
|
|
199
|
+
const context = options.context;
|
|
200
|
+
let lastError;
|
|
201
|
+
for (let attempt = 0; attempt < retryPolicy.maxAttempts; attempt++) {
|
|
202
|
+
try {
|
|
203
|
+
const result = await fn();
|
|
204
|
+
return result;
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
lastError = error;
|
|
208
|
+
// Log error if context provided
|
|
209
|
+
if (context) {
|
|
210
|
+
context.logger.warn(`Execution failed (attempt ${attempt + 1}/${retryPolicy.maxAttempts}): ${lastError.message}`);
|
|
211
|
+
}
|
|
212
|
+
// Check if we should retry
|
|
213
|
+
const shouldRetry = retryPredicate(lastError, attempt);
|
|
214
|
+
if (!shouldRetry) {
|
|
215
|
+
if (context) {
|
|
216
|
+
context.logger.error(`Non-retryable error encountered: ${lastError.message}`);
|
|
217
|
+
}
|
|
218
|
+
throw lastError;
|
|
219
|
+
}
|
|
220
|
+
// If this was the last attempt, throw RetryError
|
|
221
|
+
if (attempt === retryPolicy.maxAttempts - 1) {
|
|
222
|
+
throw new RetryError(`Execution failed after ${retryPolicy.maxAttempts} attempts: ${lastError.message}`, retryPolicy.maxAttempts, lastError);
|
|
223
|
+
}
|
|
224
|
+
// Calculate backoff delay
|
|
225
|
+
const delayMs = calculateBackoffDelay(attempt, retryPolicy, backoffPolicy, jitter);
|
|
226
|
+
if (context) {
|
|
227
|
+
context.logger.info(`Retrying in ${delayMs}ms...`);
|
|
228
|
+
}
|
|
229
|
+
// Wait before next attempt
|
|
230
|
+
await new Promise(resolve => setTimeout(resolve, delayMs));
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
// Should never reach here, but for type safety
|
|
234
|
+
throw new RetryError(`Execution failed after ${retryPolicy.maxAttempts} attempts`, retryPolicy.maxAttempts, lastError);
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Create a retry wrapper function for repeated use.
|
|
238
|
+
*
|
|
239
|
+
* @param options - Retry configuration options
|
|
240
|
+
* @returns Function that executes with retry logic
|
|
241
|
+
*
|
|
242
|
+
* @example
|
|
243
|
+
* ```typescript
|
|
244
|
+
* const retryableFetch = createRetryWrapper({
|
|
245
|
+
* retryPolicy: 5,
|
|
246
|
+
* backoffPolicy: 'exponential',
|
|
247
|
+
* });
|
|
248
|
+
*
|
|
249
|
+
* const data1 = await retryableFetch(() => fetch('/api/data1'));
|
|
250
|
+
* const data2 = await retryableFetch(() => fetch('/api/data2'));
|
|
251
|
+
* ```
|
|
252
|
+
*/
|
|
253
|
+
export function createRetryWrapper(options = {}) {
|
|
254
|
+
return async (fn) => {
|
|
255
|
+
return executeWithRetry(fn, options);
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Retry with timeout - execute with retry logic and overall timeout.
|
|
260
|
+
*
|
|
261
|
+
* @param fn - The async function to execute
|
|
262
|
+
* @param timeoutMs - Maximum time to spend retrying (in milliseconds)
|
|
263
|
+
* @param options - Retry configuration options
|
|
264
|
+
* @returns Result of successful execution
|
|
265
|
+
* @throws TimeoutError if timeout is exceeded
|
|
266
|
+
* @throws RetryError if all retry attempts fail
|
|
267
|
+
*
|
|
268
|
+
* @example
|
|
269
|
+
* ```typescript
|
|
270
|
+
* // Retry for up to 30 seconds
|
|
271
|
+
* const result = await executeWithRetryAndTimeout(
|
|
272
|
+
* async () => await processData(),
|
|
273
|
+
* 30000, // 30 seconds
|
|
274
|
+
* { retryPolicy: 10 }
|
|
275
|
+
* );
|
|
276
|
+
* ```
|
|
277
|
+
*/
|
|
278
|
+
export async function executeWithRetryAndTimeout(fn, timeoutMs, options = {}) {
|
|
279
|
+
const startTime = Date.now();
|
|
280
|
+
// Wrap the predicate to check timeout
|
|
281
|
+
const originalPredicate = options.retryPredicate ?? defaultRetryPredicate;
|
|
282
|
+
const timeoutPredicate = (error, attempt) => {
|
|
283
|
+
const elapsed = Date.now() - startTime;
|
|
284
|
+
if (elapsed >= timeoutMs) {
|
|
285
|
+
return false; // Don't retry if timeout exceeded
|
|
286
|
+
}
|
|
287
|
+
return originalPredicate(error, attempt);
|
|
288
|
+
};
|
|
289
|
+
try {
|
|
290
|
+
return await executeWithRetry(fn, {
|
|
291
|
+
...options,
|
|
292
|
+
retryPredicate: timeoutPredicate,
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
catch (error) {
|
|
296
|
+
const elapsed = Date.now() - startTime;
|
|
297
|
+
if (elapsed >= timeoutMs) {
|
|
298
|
+
const { TimeoutError } = await import('./errors.js');
|
|
299
|
+
throw new TimeoutError(`Execution timed out after ${timeoutMs}ms`, timeoutMs, 'executeWithRetryAndTimeout');
|
|
300
|
+
}
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
//# sourceMappingURL=retry-utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"retry-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E,CAAC;YACzB,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,MAAM,CAAC,aAAa,CAAC,CAAC;YACrD,MAAM,IAAI,YAAY,CAAC,6BAA6B,SAAS,IAAI,EAAE,SAAS,EAAE,4BAA4B,CAAC,CAAC;QAC9G,CAAC;QACD,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sandbox — secure code execution and file I/O.
|
|
3
|
+
*
|
|
4
|
+
* Wraps the native Rust sandbox bindings, supporting both remote (HTTP)
|
|
5
|
+
* and embedded (WASM) backends. The backend is selected automatically
|
|
6
|
+
* based on available configuration.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { Sandbox } from '@agnt5/sdk';
|
|
11
|
+
*
|
|
12
|
+
* const sandbox = new Sandbox({ endpoint: 'http://localhost:8080' });
|
|
13
|
+
* const result = await sandbox.executeCode('console.log("hello")', 'javascript');
|
|
14
|
+
* console.log(result.stdout); // "hello"
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
export interface SandboxOptions {
|
|
18
|
+
/** Backend selection: "remote", "wasm", or "auto" (default). */
|
|
19
|
+
backend?: string;
|
|
20
|
+
/** HTTP endpoint for remote backend. */
|
|
21
|
+
endpoint?: string;
|
|
22
|
+
/** Sandbox instance ID. */
|
|
23
|
+
sandboxId?: string;
|
|
24
|
+
/** API key for remote auth. */
|
|
25
|
+
apiKey?: string;
|
|
26
|
+
/** Bearer token for remote auth. */
|
|
27
|
+
bearerToken?: string;
|
|
28
|
+
/** Request timeout in seconds (default: 300). */
|
|
29
|
+
timeoutSecs?: number;
|
|
30
|
+
/** Path to QuickJS WASI binary (for wasm backend). */
|
|
31
|
+
quickjsWasmPath?: string;
|
|
32
|
+
}
|
|
33
|
+
export interface ExecuteCodeResult {
|
|
34
|
+
stdout: string;
|
|
35
|
+
stderr: string;
|
|
36
|
+
exitCode: number;
|
|
37
|
+
executionTimeMs: number;
|
|
38
|
+
error?: string;
|
|
39
|
+
}
|
|
40
|
+
export interface WriteFileResult {
|
|
41
|
+
success: boolean;
|
|
42
|
+
path: string;
|
|
43
|
+
size: number;
|
|
44
|
+
error?: string;
|
|
45
|
+
}
|
|
46
|
+
export interface ReadFileResult {
|
|
47
|
+
path: string;
|
|
48
|
+
content: Buffer;
|
|
49
|
+
size: number;
|
|
50
|
+
isDir: boolean;
|
|
51
|
+
error?: string;
|
|
52
|
+
}
|
|
53
|
+
export interface FileInfo {
|
|
54
|
+
name: string;
|
|
55
|
+
path: string;
|
|
56
|
+
size: number;
|
|
57
|
+
isDir: boolean;
|
|
58
|
+
mode: number;
|
|
59
|
+
modTime: number;
|
|
60
|
+
}
|
|
61
|
+
export interface ListFilesResult {
|
|
62
|
+
path: string;
|
|
63
|
+
total: number;
|
|
64
|
+
files: FileInfo[];
|
|
65
|
+
error?: string;
|
|
66
|
+
}
|
|
67
|
+
export interface HealthResult {
|
|
68
|
+
status: string;
|
|
69
|
+
sandboxId: string;
|
|
70
|
+
uptimeMs: number;
|
|
71
|
+
backendKind: string;
|
|
72
|
+
error?: string;
|
|
73
|
+
}
|
|
74
|
+
export interface SandboxCapabilities {
|
|
75
|
+
languages: string[];
|
|
76
|
+
supportsCommands: boolean;
|
|
77
|
+
supportsGit: boolean;
|
|
78
|
+
supportsPreviewUrl: boolean;
|
|
79
|
+
supportsStreaming: boolean;
|
|
80
|
+
supportsSnapshots: boolean;
|
|
81
|
+
hasNetworkAccess: boolean;
|
|
82
|
+
}
|
|
83
|
+
export declare class Sandbox {
|
|
84
|
+
private inner;
|
|
85
|
+
constructor(options?: SandboxOptions);
|
|
86
|
+
/** Active backend type ("remote" or "wasm"). */
|
|
87
|
+
get backend(): string;
|
|
88
|
+
/** Execute code in a sandboxed environment. */
|
|
89
|
+
executeCode(code: string, language?: string, timeoutMs?: number): Promise<ExecuteCodeResult>;
|
|
90
|
+
/** Write a file into the sandbox workspace. */
|
|
91
|
+
writeFile(path: string, content: Buffer | string): Promise<WriteFileResult>;
|
|
92
|
+
/** Read a file from the sandbox workspace. */
|
|
93
|
+
readFile(path: string): Promise<ReadFileResult>;
|
|
94
|
+
/** Delete a file or directory from the sandbox workspace. */
|
|
95
|
+
deleteFile(path: string, recursive?: boolean): Promise<boolean>;
|
|
96
|
+
/** List files in the sandbox workspace. */
|
|
97
|
+
listFiles(path?: string, recursive?: boolean): Promise<ListFilesResult>;
|
|
98
|
+
/** Check sandbox health and status. */
|
|
99
|
+
health(): Promise<HealthResult>;
|
|
100
|
+
/** Query sandbox capabilities (languages, features). */
|
|
101
|
+
capabilities(): SandboxCapabilities;
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=sandbox.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sandbox.d.ts","sourceRoot":"","sources":["../src/sandbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAQH,MAAM,WAAW,cAAc;IAC7B,gEAAgE;IAChE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wCAAwC;IACxC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,2BAA2B;IAC3B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,+BAA+B;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oCAAoC;IACpC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iDAAiD;IACjD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,sDAAsD;IACtD,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,CAAC;IACjB,eAAe,EAAE,MAAM,CAAC;IACxB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,E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