@myagentroam/agent 0.14.5 → 0.14.7

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.
@@ -1,4 +1,3 @@
1
- import { AgentError } from '../error.js';
2
1
  import { type AgentModelConfiguration } from './configuration.js';
3
2
  import type { ModelAdapter, ModelEvent, ModelRequest } from './contracts.js';
4
3
  export declare class AnthropicMessagesAdapter implements ModelAdapter {
@@ -7,7 +6,6 @@ export declare class AnthropicMessagesAdapter implements ModelAdapter {
7
6
  start(request: ModelRequest, signal: AbortSignal): AsyncIterable<ModelEvent>;
8
7
  private startAttempt;
9
8
  }
10
- export declare function isAnthropicRecoverableStreamError(error: unknown): error is AgentError;
11
9
  export declare function anthropicMessages(messages: ModelRequest['messages'], images?: ModelRequest['images'], tools?: ModelRequest['tools'], modelId?: string, automaticCache?: boolean, cachePrefixMessages?: number): {
12
10
  role: string;
13
11
  content: unknown;
@@ -8,8 +8,10 @@ import { AgentError } from '../error.js';
8
8
  import { acquireModelCredential, modelCredentialSensitiveValues } from '../network/credential-runtime.js';
9
9
  import { assertInlineMediaBudget } from './inline-media-budget.js';
10
10
  import { resolveModelDefaultReasoningEffort } from './configuration.js';
11
- import { isRetryableUpstreamOverloadCode, number, parseSse, redactResponseHeader, responseRedactor, record, text, observeModelStreamEvent, modelStreamEventObservedAt } from './sse.js';
12
- import { fetchModelResponse, modelRetryMaxAttempts, isRetryableModelRequestError, isRetryableModelTransportError, modelRetryDelay, waitForModelRetry } from './http.js';
11
+ import { classifyMessagesError } from './errors/anthropic-messages.js';
12
+ import { isRecoverableModelError, modelRetryAfter, RecoverableModelError } from './errors/common.js';
13
+ import { number, parseSse, redactResponseHeader, responseRedactor, record, text, observeModelStreamEvent, modelStreamEventObservedAt } from './sse.js';
14
+ import { fetchModelResponse, modelRetryMaxAttempts, isRetryableModelTransportError, modelRetryDelay, waitForModelRetry } from './http.js';
13
15
  import { anthropicThinkingBlock, assertAnthropicThinkingBudget } from './anthropic-thinking.js';
14
16
  import { resolveModelTextBlocks } from './text-blocks.js';
15
17
  import { reportModelAttempt } from './attempt-diagnostics.js';
@@ -38,7 +40,7 @@ export class AnthropicMessagesAdapter {
38
40
  continuation: false,
39
41
  credentialReason: 'REQUEST'
40
42
  };
41
- // Buffer non-semantic events until a semantic event makes this attempt non-retryable.
43
+ // Buffer the prelude until recovery must be handed to the Runtime instead of replayed here.
42
44
  const prelude = [];
43
45
  let sawSemanticEvent = false;
44
46
  let firstSemanticEventType;
@@ -73,9 +75,13 @@ export class AnthropicMessagesAdapter {
73
75
  return;
74
76
  }
75
77
  catch (error) {
76
- const retryable = isRetryableModelRequestError(error) || isAnthropicRecoverableStreamError(error);
77
- const willRetry = !signal.aborted && !sawSemanticEvent && retryable && attempt + 1 < maxAttempts;
78
- const delayMs = willRetry ? modelRetryDelay(retryAfter(error), attempt) : undefined;
78
+ const retryable = isRecoverableModelError(error);
79
+ const willRetry = !signal.aborted &&
80
+ (!sawSemanticEvent || request.retryState !== undefined) &&
81
+ retryable &&
82
+ attempt + 1 < maxAttempts;
83
+ const retryAfter = retryable ? modelRetryAfter(error) : null;
84
+ const delayMs = willRetry ? modelRetryDelay(retryAfter, attempt) : undefined;
79
85
  await reportModelAttempt(request, {
80
86
  ...attemptDiagnostic,
81
87
  state: 'FAILED',
@@ -89,9 +95,13 @@ export class AnthropicMessagesAdapter {
89
95
  ? {}
90
96
  : { retryDelayMs: delayMs, retryReason: 'STREAM' })
91
97
  });
92
- if (!willRetry)
98
+ if (delayMs === undefined)
93
99
  throw error;
94
- await waitForModelRetry(retryAfter(error), attempt, signal, delayMs);
100
+ if (sawSemanticEvent) {
101
+ retryState.retryDelayMs = delayMs;
102
+ throw error;
103
+ }
104
+ await waitForModelRetry(retryAfter, attempt, signal, delayMs);
95
105
  }
96
106
  }
97
107
  }
@@ -430,13 +440,13 @@ export class AnthropicMessagesAdapter {
430
440
  const redact = responseRedactor(modelCredentialSensitiveValues(credential));
431
441
  const code = boundedError(redact(text(upstream.code) ?? text(upstream.type) ?? ''), 80);
432
442
  const message = boundedError(redact(text(upstream.message) ?? ''), 1_000);
433
- const retryable = isRetryableUpstreamOverloadCode(code);
434
- throw new AgentError(code ?? 'MAR_AGENT_MODEL_PROTOCOL_ERROR', message ?? 'Anthropic Messages request failed.', retryable
443
+ const retryable = classifyMessagesError({ source: 'sse', code, message })?.action === 'retry';
444
+ const ErrorType = retryable ? RecoverableModelError : AgentError;
445
+ throw new ErrorType(code ?? 'MAR_AGENT_MODEL_PROTOCOL_ERROR', message ?? 'Anthropic Messages request failed.', retryable
435
446
  ? {
436
447
  details: {
437
448
  retryAfter: redactResponseHeader(response.headers.get('retry-after'), modelCredentialSensitiveValues(credential))
438
- },
439
- retryable: true
449
+ }
440
450
  }
441
451
  : {});
442
452
  }
@@ -444,8 +454,7 @@ export class AnthropicMessagesAdapter {
444
454
  yield observeModelStreamEvent({ type: 'unknown', nativeType: type }, modelStreamEventObservedAt(raw));
445
455
  }
446
456
  if (terminal === undefined)
447
- throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Anthropic Messages stream ended without a terminal event.', {
448
- retryable: true,
457
+ throw new RecoverableModelError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Anthropic Messages stream ended without a terminal event.', {
449
458
  details: {
450
459
  reason: 'ANTHROPIC_MESSAGES_EARLY_EOF',
451
460
  retryAfter: redactResponseHeader(response.headers.get('retry-after'), modelCredentialSensitiveValues(credential))
@@ -455,15 +464,14 @@ export class AnthropicMessagesAdapter {
455
464
  }
456
465
  async function* parseAnthropicSse(response, signal, sensitiveValues) {
457
466
  try {
458
- yield* parseSse(response, signal, undefined, undefined, sensitiveValues);
467
+ yield* parseSse(response, signal, undefined, undefined, sensitiveValues, classifyMessagesError);
459
468
  }
460
469
  catch (cause) {
461
470
  if (response.ok &&
462
471
  !signal.aborted &&
463
472
  (isRetryableModelTransportError(cause) ||
464
473
  (cause instanceof AgentError && cause.details?.reason === 'MODEL_STREAM_IDLE_TIMEOUT')))
465
- throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Anthropic Messages stream was interrupted.', {
466
- retryable: true,
474
+ throw new RecoverableModelError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Anthropic Messages stream was interrupted.', {
467
475
  details: {
468
476
  reason: 'ANTHROPIC_MESSAGES_EARLY_EOF',
469
477
  retryAfter: redactResponseHeader(response.headers.get('retry-after'), sensitiveValues)
@@ -510,16 +518,6 @@ function isSemanticEvent(event) {
510
518
  return false;
511
519
  return event.type !== 'response.started' && event.type !== 'usage';
512
520
  }
513
- export function isAnthropicRecoverableStreamError(error) {
514
- return (error instanceof AgentError &&
515
- error.retryable &&
516
- (isRetryableUpstreamOverloadCode(error.code) ||
517
- error.details?.reason === 'ANTHROPIC_MESSAGES_EARLY_EOF'));
518
- }
519
- function retryAfter(error) {
520
- const value = error.details?.retryAfter;
521
- return typeof value === 'string' ? value : null;
522
- }
523
521
  function inputTokenCount(value) {
524
522
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
525
523
  }
@@ -0,0 +1,2 @@
1
+ import { type UpstreamModelError } from './chain.js';
2
+ export declare function classifyMessagesError(facts: UpstreamModelError): import("./chain.js").ModelErrorDecision<import("./chain.js").ModelErrorAction> | undefined;
@@ -0,0 +1,7 @@
1
+ import { classifyModelError } from './chain.js';
2
+ import { httpStatusRetryRule, streamCapacityRule } from './common.js';
3
+ import { kimiErrorRules } from './rules/kimi.js';
4
+ const messagesErrorRules = [...kimiErrorRules, streamCapacityRule, httpStatusRetryRule];
5
+ export function classifyMessagesError(facts) {
6
+ return classifyModelError(messagesErrorRules, facts);
7
+ }
@@ -0,0 +1,24 @@
1
+ /** An ordered, side-effect-free chain over facts normalized by the protocol adapter. */
2
+ export type ModelErrorAction = 'retry' | 'fail' | 'refreshCredential' | 'resetContinuation';
3
+ export interface ModelErrorDecision<Action extends ModelErrorAction = ModelErrorAction> {
4
+ readonly id: string;
5
+ readonly action: Action;
6
+ readonly reason?: string;
7
+ /** Preserve an existing error diagnostic without authorizing a replay. */
8
+ readonly reportedRetryable?: true;
9
+ }
10
+ export interface ModelErrorRule<Facts, Action extends ModelErrorAction = ModelErrorAction> extends ModelErrorDecision<Action> {
11
+ readonly matches: (facts: Facts) => boolean;
12
+ }
13
+ export interface UpstreamModelError {
14
+ readonly source: 'http' | 'sse' | 'websocket';
15
+ readonly status?: number | undefined;
16
+ readonly code?: string | undefined;
17
+ readonly message?: string | undefined;
18
+ }
19
+ export interface ContinuationErrorFacts {
20
+ readonly resetContinuation: boolean;
21
+ readonly code: string;
22
+ readonly message: string;
23
+ }
24
+ export declare function classifyModelError<Facts, Action extends ModelErrorAction>(rules: readonly ModelErrorRule<Facts, Action>[], facts: Facts): ModelErrorDecision<Action> | undefined;
@@ -0,0 +1,3 @@
1
+ export function classifyModelError(rules, facts) {
2
+ return rules.find((rule) => rule.matches(facts));
3
+ }
@@ -0,0 +1,12 @@
1
+ import { AgentError } from '../../error.js';
2
+ import { type ModelErrorRule, type UpstreamModelError } from './chain.js';
3
+ export declare function isRetryableModelHttpStatus(status: number): boolean;
4
+ export declare const streamCapacityRule: ModelErrorRule<UpstreamModelError>;
5
+ export declare const httpStatusRetryRule: ModelErrorRule<UpstreamModelError>;
6
+ export declare function classifyHttpError(facts: UpstreamModelError): import("./chain.js").ModelErrorDecision<import("./chain.js").ModelErrorAction> | undefined;
7
+ /** Private classification carried from the protocol boundary without exposing rule metadata. */
8
+ export declare class RecoverableModelError extends AgentError {
9
+ constructor(code: string, message: string, options?: ConstructorParameters<typeof AgentError>[2]);
10
+ }
11
+ export declare function isRecoverableModelError(error: unknown): error is AgentError;
12
+ export declare function modelRetryAfter(error: AgentError): string | null;
@@ -0,0 +1,56 @@
1
+ import { AgentError } from '../../error.js';
2
+ import { classifyModelError } from './chain.js';
3
+ const RETRYABLE_HTTP_STATUSES = new Set([408, 409, 429, 500, 502, 503, 504]);
4
+ const TRANSIENT_CAPACITY_CODES = new Set([
5
+ 'rate_limit_error',
6
+ 'overloaded_error',
7
+ 'api_overloaded',
8
+ 'server_is_overloaded',
9
+ 'system_cpu_overloaded',
10
+ 'resource_exhausted',
11
+ 'temporarily_unavailable',
12
+ 'service_unavailable'
13
+ ]);
14
+ export function isRetryableModelHttpStatus(status) {
15
+ return RETRYABLE_HTTP_STATUSES.has(status);
16
+ }
17
+ function isTransientCapacityCode(code) {
18
+ return TRANSIENT_CAPACITY_CODES.has(code.toLowerCase());
19
+ }
20
+ export const streamCapacityRule = {
21
+ id: 'common.stream-capacity',
22
+ action: 'retry',
23
+ matches: ({ source, code }) => source !== 'http' && code !== undefined && isTransientCapacityCode(code)
24
+ };
25
+ export const httpStatusRetryRule = {
26
+ id: 'common.http-status',
27
+ action: 'retry',
28
+ matches: ({ source, status }) => source === 'http' && status !== undefined && isRetryableModelHttpStatus(status)
29
+ };
30
+ const httpErrorRules = [httpStatusRetryRule];
31
+ export function classifyHttpError(facts) {
32
+ return classifyModelError(httpErrorRules, facts);
33
+ }
34
+ /** Private classification carried from the protocol boundary without exposing rule metadata. */
35
+ export class RecoverableModelError extends AgentError {
36
+ constructor(code, message, options) {
37
+ super(code, message, { ...options, retryable: true });
38
+ }
39
+ }
40
+ export function isRecoverableModelError(error) {
41
+ if (error instanceof RecoverableModelError)
42
+ return true;
43
+ if (!(error instanceof AgentError) || !error.retryable)
44
+ return false;
45
+ const { reason, status } = error.details ?? {};
46
+ // Transport and Runtime errors, and the existing closed capacity contract for model adapters.
47
+ return (reason === 'MODEL_PROGRESS_TIMEOUT' ||
48
+ reason === 'MODEL_CONNECTION_TIMEOUT' ||
49
+ reason === 'MODEL_TRANSPORT_FAILURE' ||
50
+ (typeof status === 'number' && isRetryableModelHttpStatus(status)) ||
51
+ isTransientCapacityCode(error.code));
52
+ }
53
+ export function modelRetryAfter(error) {
54
+ const value = error.details?.retryAfter;
55
+ return typeof value === 'string' ? value : null;
56
+ }
@@ -0,0 +1,9 @@
1
+ import type { AgentError } from '../../error.js';
2
+ import { type UpstreamModelError } from './chain.js';
3
+ export declare function classifyResponsesError(facts: UpstreamModelError): import("./chain.js").ModelErrorDecision<import("./chain.js").ModelErrorAction> | undefined;
4
+ interface FallbackEligibility {
5
+ readonly resetContinuation: boolean;
6
+ readonly refreshCredential: boolean;
7
+ }
8
+ export declare function classifyResponsesFallback(error: AgentError, eligibility: FallbackEligibility): import("./chain.js").ModelErrorDecision<"refreshCredential" | "resetContinuation"> | undefined;
9
+ export {};
@@ -0,0 +1,37 @@
1
+ import { classifyModelError } from './chain.js';
2
+ import { httpStatusRetryRule, streamCapacityRule } from './common.js';
3
+ import { openAiContinuationErrorRule, openAiStreamErrorRules } from './rules/openai.js';
4
+ import { xAiContinuationErrorRule } from './rules/xai.js';
5
+ const responsesErrorRules = [
6
+ {
7
+ id: 'responses.websocket-connection-limit',
8
+ action: 'retry',
9
+ reason: 'OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT',
10
+ matches: ({ source, code }) => source === 'websocket' && code?.trim().toLowerCase() === 'websocket_connection_limit_reached'
11
+ },
12
+ ...openAiStreamErrorRules,
13
+ streamCapacityRule,
14
+ httpStatusRetryRule
15
+ ];
16
+ export function classifyResponsesError(facts) {
17
+ return classifyModelError(responsesErrorRules, facts);
18
+ }
19
+ const fallbackRules = [
20
+ openAiContinuationErrorRule,
21
+ xAiContinuationErrorRule,
22
+ {
23
+ id: 'responses.unauthorized',
24
+ action: 'refreshCredential',
25
+ matches: ({ refreshCredential, status, code }) => refreshCredential && (status === undefined ? code === 'unauthorized' : status === 401)
26
+ }
27
+ ];
28
+ export function classifyResponsesFallback(error, eligibility) {
29
+ const status = typeof error.details?.status === 'number' ? error.details.status : undefined;
30
+ return classifyModelError(fallbackRules, {
31
+ ...eligibility,
32
+ resetContinuation: eligibility.resetContinuation && (status === undefined || [400, 404, 410].includes(status)),
33
+ status,
34
+ code: error.code.toLowerCase(),
35
+ message: error.message.toLowerCase().replaceAll('`', '')
36
+ });
37
+ }
@@ -0,0 +1,2 @@
1
+ import type { ModelErrorRule, UpstreamModelError } from '../chain.js';
2
+ export declare const kimiErrorRules: readonly ModelErrorRule<UpstreamModelError>[];
@@ -0,0 +1,11 @@
1
+ export const kimiErrorRules = [
2
+ {
3
+ id: 'kimi-code.concurrent-request-limit',
4
+ action: 'retry',
5
+ // Kimi documents this as 429; Messages-compatible endpoints also emit it as SSE or 403.
6
+ matches: ({ source, status, code, message }) => (source === 'sse' || (source === 'http' && status === 403)) &&
7
+ code === 'permission_error' &&
8
+ message ===
9
+ "You've reached your concurrent request limit. Please wait for your ongoing requests to finish and try again."
10
+ }
11
+ ];
@@ -0,0 +1,3 @@
1
+ import type { ContinuationErrorFacts, ModelErrorRule, UpstreamModelError } from '../chain.js';
2
+ export declare const openAiStreamErrorRules: readonly ModelErrorRule<UpstreamModelError>[];
3
+ export declare const openAiContinuationErrorRule: ModelErrorRule<ContinuationErrorFacts, 'resetContinuation'>;
@@ -0,0 +1,54 @@
1
+ import { isRetryableModelHttpStatus } from '../common.js';
2
+ const TRANSIENT_ACCESS_CHECK_CODE = 'invalid_request_error';
3
+ const TRANSIENT_ACCESS_CHECK_MESSAGE = 'Unable to verify Daybreak Blue access. Please try again.';
4
+ const PREFIXED_ACCESS_CHECK_MESSAGE = `${TRANSIENT_ACCESS_CHECK_CODE}: ${TRANSIENT_ACCESS_CHECK_MESSAGE}`;
5
+ export const openAiStreamErrorRules = [
6
+ {
7
+ id: 'openai.responses-server-error',
8
+ action: 'retry',
9
+ // An upstream response-stream failure, not a local protocol parsing error.
10
+ matches: ({ source, code }) => source !== 'http' && code === 'server_error'
11
+ },
12
+ {
13
+ id: 'openai.responses-transient-access-check',
14
+ action: 'retry',
15
+ matches: ({ source, code, message, status }) => source !== 'http' &&
16
+ code === TRANSIENT_ACCESS_CHECK_CODE &&
17
+ (message === TRANSIENT_ACCESS_CHECK_MESSAGE ||
18
+ // A code-prefixed summary was recoverable only with an explicit transient status.
19
+ (status !== undefined &&
20
+ isRetryableModelHttpStatus(status) &&
21
+ message === PREFIXED_ACCESS_CHECK_MESSAGE))
22
+ },
23
+ {
24
+ id: 'openai.responses-prefixed-access-check',
25
+ action: 'fail',
26
+ reportedRetryable: true,
27
+ matches: ({ source, code, message }) => source !== 'http' &&
28
+ code === TRANSIENT_ACCESS_CHECK_CODE &&
29
+ message === PREFIXED_ACCESS_CHECK_MESSAGE
30
+ }
31
+ ];
32
+ export const openAiContinuationErrorRule = {
33
+ id: 'openai.responses-invalid-reference',
34
+ action: 'resetContinuation',
35
+ matches: ({ resetContinuation, code, message }) => resetContinuation && isInvalidResponsesReference(code.trim(), message)
36
+ };
37
+ function isInvalidResponsesReference(code, message) {
38
+ if (code === 'previous_response_not_found' || code === 'invalid_previous_response_id')
39
+ return true;
40
+ if (code === 'unsupported_parameter' || code === 'unsupported_previous_response_id')
41
+ return message.includes('previous_response_id');
42
+ // Explicit auth, permission and overload codes cannot become continuation errors.
43
+ return ((code === 'invalid_request_error' ||
44
+ code === 'api_error' ||
45
+ code === 'mar_agent_model_protocol_error') &&
46
+ message.includes('previous_response_id') &&
47
+ (message.includes('invalid') ||
48
+ message.includes('not found') ||
49
+ message.includes('does not exist') ||
50
+ message.includes('expired') ||
51
+ message.includes('not supported') ||
52
+ message.includes('unsupported') ||
53
+ message.includes('unavailable')));
54
+ }
@@ -0,0 +1,2 @@
1
+ import type { ContinuationErrorFacts, ModelErrorRule } from '../chain.js';
2
+ export declare const xAiContinuationErrorRule: ModelErrorRule<ContinuationErrorFacts, 'resetContinuation'>;
@@ -0,0 +1,8 @@
1
+ export const xAiContinuationErrorRule = {
2
+ id: 'xai.responses-missing-reference',
3
+ action: 'resetContinuation',
4
+ // Grok WSS can return a gRPC-prefixed missing reference; HTTP may return a plain error.
5
+ matches: ({ resetContinuation, code, message }) => resetContinuation &&
6
+ ['api_error', 'mar_agent_model_protocol_error'].includes(code.trim()) &&
7
+ /^(?:(?:mar_agent_model_protocol_error|api_error): )?(?:grpc error: )?response with id=\S+ not found[.!]?$/u.test(message)
8
+ };
@@ -1,13 +1,10 @@
1
1
  export { isRetryableTransportError as isRetryableModelTransportError } from '../network/transport-error.js';
2
- import { AgentError } from '../error.js';
3
2
  import { connectSocks5Target as connectTransportSocks5Target, type HttpRequestInit } from '../network/http.js';
4
3
  import type { ModelRetryState } from './contracts.js';
5
- export declare const MAX_MODEL_ATTEMPTS = 8;
4
+ export declare const MAX_MODEL_ATTEMPTS = 5;
6
5
  export declare function modelRetryMaxAttempts(state: ModelRetryState): number;
7
6
  export type { HttpAttempt, HttpRequestInit } from '../network/http.js';
8
7
  export declare function connectSocks5Target(input: Parameters<typeof connectTransportSocks5Target>[0]): ReturnType<typeof connectTransportSocks5Target>;
9
8
  export declare function fetchModelResponse(url: string, init: HttpRequestInit, signal: AbortSignal, attempts?: number, connectionTimeoutMs?: number): Promise<Response>;
10
9
  export declare function modelRetryDelay(retryAfter: string | null, attempt: number): number;
11
10
  export declare function waitForModelRetry(retryAfter: string | null, attempt: number, signal: AbortSignal, delayMs?: number): Promise<void>;
12
- export declare function isRetryableModelHttpStatus(status: number): boolean;
13
- export declare function isRetryableModelRequestError(error: unknown): error is AgentError;
@@ -3,14 +3,14 @@ export { isRetryableTransportError as isRetryableModelTransportError } from '../
3
3
  import { setTimeout as delay } from 'node:timers/promises';
4
4
  import { AgentError } from '../error.js';
5
5
  import { connectSocks5Target as connectTransportSocks5Target, fetchWithConnectionTimeout, hasErrorCode, isModelHttpAttempt } from '../network/http.js';
6
- export const MAX_MODEL_ATTEMPTS = 8;
6
+ import { isRetryableModelHttpStatus } from './errors/common.js';
7
+ export const MAX_MODEL_ATTEMPTS = 5;
7
8
  export function modelRetryMaxAttempts(state) {
8
9
  const maximum = state.maxAttempts ?? MAX_MODEL_ATTEMPTS;
9
10
  if (!Number.isInteger(maximum) || maximum < 1 || maximum > MAX_MODEL_ATTEMPTS)
10
11
  throw new AgentError('MAR_AGENT_MODEL_CONFIG_INVALID', `Model attempts must be between 1 and ${MAX_MODEL_ATTEMPTS}.`);
11
12
  return maximum;
12
13
  }
13
- const RETRYABLE_STATUS = new Set([408, 409, 429, 500, 502, 503, 504]);
14
14
  const DEFAULT_MODEL_CONNECTION_TIMEOUT_MS = 30_000;
15
15
  export async function connectSocks5Target(input) {
16
16
  try {
@@ -80,7 +80,7 @@ export async function fetchModelResponse(url, init, signal, attempts = MAX_MODEL
80
80
  await waitForModelRetry(null, attempt, signal);
81
81
  continue;
82
82
  }
83
- if (!RETRYABLE_STATUS.has(response.status) || attempt + 1 >= attempts)
83
+ if (!isRetryableModelHttpStatus(response.status) || attempt + 1 >= attempts)
84
84
  return response;
85
85
  const retryAfter = response.headers.get('retry-after');
86
86
  await response.body?.cancel().catch(() => undefined);
@@ -94,18 +94,6 @@ export function modelRetryDelay(retryAfter, attempt) {
94
94
  export async function waitForModelRetry(retryAfter, attempt, signal, delayMs = modelRetryDelay(retryAfter, attempt)) {
95
95
  await delay(delayMs, undefined, { signal });
96
96
  }
97
- export function isRetryableModelHttpStatus(status) {
98
- return RETRYABLE_STATUS.has(status);
99
- }
100
- export function isRetryableModelRequestError(error) {
101
- return (error instanceof AgentError &&
102
- error.retryable &&
103
- (error.details?.reason === 'MODEL_PROGRESS_TIMEOUT' ||
104
- error.details?.reason === 'MODEL_CONNECTION_TIMEOUT' ||
105
- error.details?.reason === 'MODEL_TRANSPORT_FAILURE' ||
106
- (typeof error.details?.status === 'number' &&
107
- isRetryableModelHttpStatus(error.details.status))));
108
- }
109
97
  function retryAfterDelay(value) {
110
98
  if (value !== null) {
111
99
  const seconds = Number(value);
@@ -1,11 +1,8 @@
1
1
  export { openAiInput } from './responses-request.js';
2
- import { AgentError } from '../error.js';
3
2
  import { type AgentModelConfiguration, type ModelCredential, type ModelCredentialAcquireReason } from './configuration.js';
4
3
  import WebSocket from 'ws';
5
4
  import type { ModelAdapter, ModelAttemptDiagnostic, ModelEvent, ModelRequest, ModelTurnSession } from './contracts.js';
6
5
  import { ResponsesSessionCache, type ResponsesRequestBody, type ResponsesSessionState } from './responses-session-cache.js';
7
- export declare const OPENAI_RESPONSES_EARLY_EOF_REASON = "OPENAI_RESPONSES_EARLY_EOF";
8
- export declare const OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT_REASON = "OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT";
9
6
  interface PreparedResponsesRequest {
10
7
  readonly inputItemCount: number;
11
8
  readonly fullBody: ResponsesRequestBody;
@@ -57,4 +54,3 @@ declare class OpenAiResponsesTurnSession implements ModelTurnSession {
57
54
  }): Promise<WebSocket>;
58
55
  private connectWebSocket;
59
56
  }
60
- export declare function isOpenAiResponsesRecoverableStreamError(error: unknown): error is AgentError;
@@ -8,16 +8,17 @@ import { createHash, randomUUID } from 'node:crypto';
8
8
  import { describeAgentError, AgentError } from '../error.js';
9
9
  import { assertInlineMediaBudget } from './inline-media-budget.js';
10
10
  import WebSocket from 'ws';
11
- import { isRetryableUpstreamOverloadCode, number, parseSse, parseResponseJson, redactResponseHeader, responseRedactor, record, text, observeModelStreamEvent, modelStreamEventObservedAt } from './sse.js';
12
- import { connectSocks5Target, fetchModelResponse, isRetryableModelHttpStatus, isRetryableModelTransportError, modelRetryMaxAttempts, isRetryableModelRequestError, modelRetryDelay, waitForModelRetry } from './http.js';
11
+ import { isRecoverableModelError, modelRetryAfter, RecoverableModelError } from './errors/common.js';
12
+ import { classifyResponsesError, classifyResponsesFallback } from './errors/openai-responses.js';
13
+ import { number, parseSse, parseResponseJson, redactResponseHeader, responseRedactor, record, text, observeModelStreamEvent, modelStreamEventObservedAt } from './sse.js';
14
+ import { connectSocks5Target, fetchModelResponse, isRetryableModelTransportError, modelRetryMaxAttempts, modelRetryDelay, waitForModelRetry } from './http.js';
13
15
  import { acquireModelCredential, appendModelCredentialHeaders, modelCredentialSensitiveValues } from './runtime-credential.js';
14
16
  import { reportModelAttempt } from './attempt-diagnostics.js';
15
17
  import { productUserAgent } from '../network/product-user-agent.js';
16
18
  import { ResponsesSessionCache, clearResponsesContinuation, invalidateResponsesWebSocket, terminateWebSocket } from './responses-session-cache.js';
17
19
  const WEBSOCKET_IDLE_TIMEOUT_MS = 180_000;
18
20
  const WEBSOCKET_SEND_FRAME_BYTES = 1024 * 1024;
19
- export const OPENAI_RESPONSES_EARLY_EOF_REASON = 'OPENAI_RESPONSES_EARLY_EOF';
20
- export const OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT_REASON = 'OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT';
21
+ const OPENAI_RESPONSES_EARLY_EOF_REASON = 'OPENAI_RESPONSES_EARLY_EOF';
21
22
  const X_CODEX_TURN_STATE = 'x-codex-turn-state';
22
23
  export class OpenAiResponsesAdapter {
23
24
  #cache = new ResponsesSessionCache();
@@ -171,46 +172,47 @@ export class OpenAiResponsesAdapter {
171
172
  if (!signal.aborted &&
172
173
  attemptNumber < maxAttempts &&
173
174
  !sawSemanticEvent &&
174
- useContinuation &&
175
- !invalidContinuationFallbackUsed &&
176
- isInvalidPreviousResponseError(error)) {
177
- invalidContinuationFallbackUsed = true;
178
- useContinuation = false;
179
- requestBody = prepared.fullBody;
180
- turn.restartProviderTurn();
181
- credentialReason = 'RECONNECT';
182
- await reportFailure(true, {
183
- retryDelayMs: 0,
184
- retryReason: 'INVALID_CONTINUATION'
185
- });
186
- continue;
187
- }
188
- if (!signal.aborted &&
189
- attemptNumber < maxAttempts &&
190
- !sawSemanticEvent &&
191
- !unauthorizedRetryUsed &&
192
- this.configuration.credentialProvider !== undefined &&
193
- isModelAuthenticationFailure(error)) {
194
- const revision = credentialRevision(error);
195
- if (revision !== undefined)
196
- await this.configuration.credentialProvider.invalidate(revision);
197
- unauthorizedRetryUsed = true;
198
- credentialReason = 'UNAUTHORIZED';
199
- await reportFailure(true, {
200
- retryDelayMs: 0,
201
- retryReason: 'UNAUTHORIZED'
175
+ error instanceof AgentError) {
176
+ const credentialProvider = this.configuration.credentialProvider;
177
+ const fallback = classifyResponsesFallback(error, {
178
+ resetContinuation: useContinuation && !invalidContinuationFallbackUsed,
179
+ refreshCredential: credentialProvider !== undefined && !unauthorizedRetryUsed
202
180
  });
203
- continue;
181
+ if (fallback?.action === 'resetContinuation') {
182
+ invalidContinuationFallbackUsed = true;
183
+ useContinuation = false;
184
+ requestBody = prepared.fullBody;
185
+ turn.restartProviderTurn();
186
+ credentialReason = 'RECONNECT';
187
+ await reportFailure(true, {
188
+ retryDelayMs: 0,
189
+ retryReason: 'INVALID_CONTINUATION'
190
+ });
191
+ continue;
192
+ }
193
+ if (fallback?.action === 'refreshCredential') {
194
+ const revision = credentialRevision(error);
195
+ if (revision !== undefined)
196
+ await credentialProvider?.invalidate(revision);
197
+ unauthorizedRetryUsed = true;
198
+ credentialReason = 'UNAUTHORIZED';
199
+ await reportFailure(true, {
200
+ retryDelayMs: 0,
201
+ retryReason: 'UNAUTHORIZED'
202
+ });
203
+ continue;
204
+ }
204
205
  }
205
206
  const willRetry = !(signal.aborted ||
206
207
  (sawSemanticEvent && request.retryState === undefined) ||
207
- !(isRetryableModelRequestError(error) || isOpenAiResponsesRecoverableStreamError(error)) ||
208
+ !isRecoverableModelError(error) ||
208
209
  attemptNumber >= maxAttempts);
209
210
  if (!willRetry) {
210
211
  await reportFailure(false);
211
212
  throw error;
212
213
  }
213
- const delayMs = modelRetryDelay(retryAfter(error), attempt);
214
+ const retryAfter = modelRetryAfter(error);
215
+ const delayMs = modelRetryDelay(retryAfter, attempt);
214
216
  await reportFailure(true, {
215
217
  retryDelayMs: delayMs,
216
218
  retryReason: 'STREAM'
@@ -227,7 +229,7 @@ export class OpenAiResponsesAdapter {
227
229
  requestBody = prepared.fullBody;
228
230
  if (error instanceof AgentError && error.details?.transport === 'WEBSOCKET')
229
231
  turn.invalidateWebSocket();
230
- await waitForModelRetry(retryAfter(error), attempt, signal, delayMs);
232
+ await waitForModelRetry(retryAfter, attempt, signal, delayMs);
231
233
  }
232
234
  }
233
235
  }
@@ -282,7 +284,7 @@ export class OpenAiResponsesAdapter {
282
284
  catch (error) {
283
285
  if (this.configuration.responsesTransport?.transport === 'WEBSOCKET')
284
286
  turn.invalidateWebSocket();
285
- throw withCredentialRevision(withResponsesAttemptDetails(error, continuation, this.configuration.responsesTransport?.transport), latestCredentialRevision);
287
+ throw withResponsesAttemptDetails(error, continuation, this.configuration.responsesTransport?.transport, latestCredentialRevision);
286
288
  }
287
289
  let completed = false;
288
290
  const functionCalls = new Map();
@@ -549,26 +551,29 @@ export class OpenAiResponsesAdapter {
549
551
  text(event.error) ??
550
552
  ''), 1_000);
551
553
  const status = upstreamHttpStatus(event.status, topLevel.status, record(event.response).status, nested.status);
552
- const connectionLimit = this.configuration.responsesTransport?.transport === 'WEBSOCKET' &&
553
- isWebSocketConnectionLimitCode(code);
554
- const retryable = connectionLimit || isRetryableResponsesUpstreamError(code, message);
555
- throw new AgentError(code ?? 'MAR_AGENT_MODEL_PROTOCOL_ERROR', message ?? 'OpenAI Responses request failed.', {
554
+ const websocket = this.configuration.responsesTransport?.transport === 'WEBSOCKET';
555
+ const decision = classifyResponsesError({
556
+ source: websocket ? 'websocket' : 'sse',
557
+ status,
558
+ code,
559
+ message
560
+ });
561
+ const recoverable = decision?.action === 'retry';
562
+ const retryable = recoverable || decision?.reportedRetryable === true;
563
+ const ErrorType = recoverable ? RecoverableModelError : AgentError;
564
+ throw new ErrorType(code ?? 'MAR_AGENT_MODEL_PROTOCOL_ERROR', message ?? 'OpenAI Responses request failed.', {
565
+ retryable,
556
566
  details: {
557
567
  ...(status === undefined ? {} : { status }),
558
- ...(connectionLimit
559
- ? { reason: OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT_REASON }
560
- : {}),
568
+ ...(decision?.reason === undefined ? {} : { reason: decision.reason }),
561
569
  ...(retryable
562
570
  ? {
563
571
  retryAfter: redactResponseHeader(response?.headers.get('retry-after'), diagnosticSecrets)
564
572
  }
565
573
  : {}),
566
574
  continuation,
567
- ...(this.configuration.responsesTransport?.transport === 'WEBSOCKET'
568
- ? { transport: 'WEBSOCKET' }
569
- : {})
570
- },
571
- ...(retryable ? { retryable: true } : {})
575
+ ...(websocket ? { transport: 'WEBSOCKET' } : {})
576
+ }
572
577
  });
573
578
  }
574
579
  else if (!isNonSemanticOpenAiResponsesEvent(type))
@@ -578,10 +583,10 @@ export class OpenAiResponsesAdapter {
578
583
  catch (error) {
579
584
  if (this.configuration.responsesTransport?.transport === 'WEBSOCKET')
580
585
  turn.invalidateWebSocket();
581
- throw withCredentialRevision(withResponsesAttemptDetails(error, continuation, this.configuration.responsesTransport?.transport), latestCredentialRevision);
586
+ throw withResponsesAttemptDetails(error, continuation, this.configuration.responsesTransport?.transport, latestCredentialRevision);
582
587
  }
583
588
  if (!completed)
584
- throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses stream ended without a terminal event.', {
589
+ throw new RecoverableModelError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses stream ended without a terminal event.', {
585
590
  details: {
586
591
  reason: OPENAI_RESPONSES_EARLY_EOF_REASON,
587
592
  retryAfter: redactResponseHeader(response?.headers.get('retry-after'), diagnosticSecrets),
@@ -589,8 +594,7 @@ export class OpenAiResponsesAdapter {
589
594
  ...(this.configuration.responsesTransport?.transport === 'WEBSOCKET'
590
595
  ? { transport: 'WEBSOCKET' }
591
596
  : {})
592
- },
593
- retryable: true
597
+ }
594
598
  });
595
599
  }
596
600
  }
@@ -996,17 +1000,16 @@ function turnStateFromEvent(event) {
996
1000
  }
997
1001
  async function* parseOpenAiResponsesSse(response, signal, continuation, sensitiveValues) {
998
1002
  try {
999
- yield* parseSse(response, signal, undefined, undefined, sensitiveValues);
1003
+ yield* parseSse(response, signal, undefined, undefined, sensitiveValues, classifyResponsesError);
1000
1004
  }
1001
1005
  catch (cause) {
1002
1006
  if (response.ok && !signal.aborted && isRetryableOpenAiStreamReadError(cause))
1003
- throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses stream was interrupted.', {
1007
+ throw new RecoverableModelError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses stream was interrupted.', {
1004
1008
  details: {
1005
1009
  reason: OPENAI_RESPONSES_EARLY_EOF_REASON,
1006
1010
  retryAfter: redactResponseHeader(response.headers.get('retry-after'), sensitiveValues),
1007
1011
  continuation
1008
1012
  },
1009
- retryable: true,
1010
1013
  cause
1011
1014
  });
1012
1015
  throw cause;
@@ -1054,13 +1057,12 @@ async function* webSocketResponseEvents(input) {
1054
1057
  // a separate model-error classification. The shared attempt budget still bounds
1055
1058
  // retries; this policy does not shrink the request or guarantee recovery.
1056
1059
  if (!terminal && !input.signal.aborted)
1057
- throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses WebSocket closed before a terminal event.', {
1060
+ throw new RecoverableModelError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses WebSocket closed before a terminal event.', {
1058
1061
  details: {
1059
1062
  reason: OPENAI_RESPONSES_EARLY_EOF_REASON,
1060
1063
  transport: 'WEBSOCKET',
1061
1064
  continuation: input.continuation
1062
- },
1063
- retryable: true
1065
+ }
1064
1066
  });
1065
1067
  }
1066
1068
  finally {
@@ -1134,10 +1136,11 @@ async function waitForWebSocketOpen(socket, signal, sensitiveValues) {
1134
1136
  const status = response.statusCode ?? 0;
1135
1137
  response.resume();
1136
1138
  terminateWebSocket(socket);
1137
- const retryable = status !== 401 && isRetryableModelHttpStatus(status);
1139
+ const retryable = classifyResponsesError({ source: 'http', status })?.action === 'retry';
1140
+ const ErrorType = retryable ? RecoverableModelError : AgentError;
1138
1141
  const retryAfter = response.headers['retry-after'];
1139
1142
  const retryAfterValue = Array.isArray(retryAfter) ? retryAfter[0] : retryAfter;
1140
- reject(new AgentError(status === 401 ? 'MAR_AGENT_MODEL_AUTH_FAILED' : 'MAR_AGENT_MODEL_CONNECTION_FAILED', status === 401
1143
+ reject(new ErrorType(status === 401 ? 'MAR_AGENT_MODEL_AUTH_FAILED' : 'MAR_AGENT_MODEL_CONNECTION_FAILED', status === 401
1141
1144
  ? 'OpenAI Responses WebSocket authentication failed.'
1142
1145
  : 'OpenAI Responses WebSocket handshake failed.', {
1143
1146
  details: {
@@ -1146,8 +1149,7 @@ async function waitForWebSocketOpen(socket, signal, sensitiveValues) {
1146
1149
  ...(retryAfterValue === undefined
1147
1150
  ? {}
1148
1151
  : { retryAfter: redactResponseHeader(retryAfterValue, sensitiveValues) })
1149
- },
1150
- ...(retryable ? { retryable: true } : {})
1152
+ }
1151
1153
  }));
1152
1154
  });
1153
1155
  signal.addEventListener('abort', abort, { once: true });
@@ -1287,9 +1289,8 @@ function webSocketMessages(socket, signal, closed) {
1287
1289
  }
1288
1290
  function webSocketIdleError(socket) {
1289
1291
  terminateWebSocket(socket);
1290
- return new AgentError('MAR_AGENT_MODEL_TIMEOUT', 'OpenAI Responses WebSocket was idle for too long.', {
1291
- details: { reason: OPENAI_RESPONSES_EARLY_EOF_REASON, transport: 'WEBSOCKET' },
1292
- retryable: true
1292
+ return new RecoverableModelError('MAR_AGENT_MODEL_TIMEOUT', 'OpenAI Responses WebSocket was idle for too long.', {
1293
+ details: { reason: OPENAI_RESPONSES_EARLY_EOF_REASON, transport: 'WEBSOCKET' }
1293
1294
  });
1294
1295
  }
1295
1296
  function isWebSocketNonProgressEvent(value) {
@@ -1349,12 +1350,11 @@ function webSocketReceiveError(cause) {
1349
1350
  return new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', code === 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'
1350
1351
  ? 'Model response exceeded the size limit.'
1351
1352
  : 'Model WebSocket protocol is invalid.', { cause });
1352
- return new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses WebSocket was interrupted.', {
1353
+ return new RecoverableModelError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'OpenAI Responses WebSocket was interrupted.', {
1353
1354
  details: {
1354
1355
  reason: OPENAI_RESPONSES_EARLY_EOF_REASON,
1355
1356
  transport: 'WEBSOCKET'
1356
1357
  },
1357
- retryable: true,
1358
1358
  cause
1359
1359
  });
1360
1360
  }
@@ -1383,40 +1383,12 @@ const NON_SEMANTIC_OPENAI_RESPONSES_EVENTS = new Set([
1383
1383
  'response.reasoning_summary_part.done',
1384
1384
  'responsesapi.websocket_timing'
1385
1385
  ]);
1386
- function isRetryableResponsesUpstreamError(code, message) {
1387
- // Responses server_error reports upstream response-stream processing failure, not a
1388
- // local protocol parse failure or generic overload. Reuse bounded recovery without
1389
- // guaranteeing success or inferring a particular upstream service/proxy or root cause.
1390
- if (code === 'server_error')
1391
- return true;
1392
- if (isRetryableUpstreamOverloadCode(code))
1393
- return true;
1394
- if (code !== 'invalid_request_error')
1395
- return false;
1396
- // Exact compatibility exception, not a general access/authentication retry rule.
1397
- const summary = message?.startsWith(`${code}: `) ? message.slice(code.length + 2) : message;
1398
- return summary === 'Unable to verify Daybreak Blue access. Please try again.';
1399
- }
1400
- export function isOpenAiResponsesRecoverableStreamError(error) {
1401
- return (error instanceof AgentError &&
1402
- error.retryable &&
1403
- (error.details?.reason === OPENAI_RESPONSES_EARLY_EOF_REASON ||
1404
- error.details?.reason === OPENAI_RESPONSES_WEBSOCKET_CONNECTION_LIMIT_REASON ||
1405
- isRetryableResponsesUpstreamError(error.code, error.message)));
1406
- }
1407
- function isWebSocketConnectionLimitCode(code) {
1408
- return code?.trim().toLowerCase() === 'websocket_connection_limit_reached';
1409
- }
1410
1386
  function isRetryableOpenAiStreamReadError(error) {
1411
1387
  return (isRetryableModelTransportError(error) ||
1412
1388
  (error instanceof AgentError &&
1413
1389
  error.code === 'MAR_AGENT_MODEL_TIMEOUT' &&
1414
1390
  error.details?.reason === 'MODEL_STREAM_IDLE_TIMEOUT'));
1415
1391
  }
1416
- function retryAfter(error) {
1417
- const value = error.details?.retryAfter;
1418
- return typeof value === 'string' ? value : null;
1419
- }
1420
1392
  function openAiResponsesAttemptError(error) {
1421
1393
  const diagnostic = describeAgentError(error, 'MAR_AGENT_MODEL_ATTEMPT_FAILED');
1422
1394
  const causeCode = deepestCauseCode(error);
@@ -1500,38 +1472,21 @@ function responsesHeaders(credential, promptCacheKey, turnState) {
1500
1472
  headers.set(X_CODEX_TURN_STATE, turnState);
1501
1473
  return appendModelCredentialHeaders(headers, credential, RESERVED_CREDENTIAL_HEADERS);
1502
1474
  }
1503
- function withCredentialRevision(error, revision) {
1504
- if (!(error instanceof AgentError) || revision === undefined)
1505
- return error;
1506
- const prefix = `${error.code}: `;
1507
- return new AgentError(error.code, error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message, {
1508
- details: { ...error.details, credentialRevision: revision },
1509
- retryable: error.retryable,
1510
- cause: error
1511
- });
1512
- }
1513
- function withResponsesAttemptDetails(error, continuation, transport) {
1475
+ function withResponsesAttemptDetails(error, continuation, transport, revision) {
1514
1476
  if (!(error instanceof AgentError))
1515
1477
  return error;
1516
- const prefix = `${error.code}: `;
1517
- return new AgentError(error.code, error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message, {
1478
+ const ErrorType = error instanceof RecoverableModelError ? RecoverableModelError : AgentError;
1479
+ return new ErrorType(error.code, error.publicMessage, {
1518
1480
  details: {
1519
1481
  ...error.details,
1520
1482
  continuation,
1521
- ...(transport === 'WEBSOCKET' ? { transport: 'WEBSOCKET' } : {})
1483
+ ...(transport === 'WEBSOCKET' ? { transport: 'WEBSOCKET' } : {}),
1484
+ ...(revision === undefined ? {} : { credentialRevision: revision })
1522
1485
  },
1523
1486
  retryable: error.retryable,
1524
1487
  cause: error
1525
1488
  });
1526
1489
  }
1527
- function isModelAuthenticationFailure(error) {
1528
- if (!(error instanceof AgentError))
1529
- return false;
1530
- if (typeof error.details?.status === 'number')
1531
- return error.details.status === 401;
1532
- const code = error.code.toLowerCase();
1533
- return code === 'unauthorized';
1534
- }
1535
1490
  function credentialRevision(error) {
1536
1491
  const revision = error.details?.credentialRevision;
1537
1492
  return typeof revision === 'number' && Number.isSafeInteger(revision) && revision >= 0
@@ -1563,48 +1518,3 @@ function optionalRolloutBudgetUnits(value) {
1563
1518
  return units;
1564
1519
  throw new AgentError('MAR_AGENT_MODEL_PROTOCOL_ERROR', 'Provider rollout budget units are invalid.');
1565
1520
  }
1566
- function isInvalidPreviousResponseError(error) {
1567
- if (!(error instanceof AgentError))
1568
- return false;
1569
- const status = error.details?.status;
1570
- if (typeof status === 'number' && ![400, 404, 410].includes(status))
1571
- return false;
1572
- return isInvalidPreviousResponseFields(error.code, error.message);
1573
- }
1574
- function isInvalidPreviousResponseFields(code, message) {
1575
- const normalizedCode = code?.trim().toLowerCase();
1576
- // OpenAI Responses and compatible providers use these missing-reference codes.
1577
- if (normalizedCode === 'previous_response_not_found' ||
1578
- normalizedCode === 'invalid_previous_response_id')
1579
- return true;
1580
- const normalizedMessage = message?.toLowerCase().replaceAll('`', '') ?? '';
1581
- // xAI/Grok WSS uses api_error with a gRPC prefix; HTTP may return a plain
1582
- // error string, normalized by the SSE boundary to MAR_AGENT_MODEL_PROTOCOL_ERROR.
1583
- // Do not treat account/model lookup failures as a missing response reference.
1584
- if ((normalizedCode === 'api_error' ||
1585
- normalizedCode === 'mar_agent_model_protocol_error' ||
1586
- normalizedCode === undefined) &&
1587
- /^(?:(?:mar_agent_model_protocol_error|api_error): )?(?:grpc error: )?response with id=\S+ not found[.!]?$/u.test(normalizedMessage))
1588
- return true;
1589
- // Compatibility gateways use these unsupported-parameter discriminators.
1590
- if ((normalizedCode === 'unsupported_parameter' ||
1591
- normalizedCode === 'unsupported_previous_response_id') &&
1592
- normalizedMessage.includes('previous_response_id'))
1593
- return true;
1594
- // OpenAI-style request errors and generic compatibility envelopes may only
1595
- // name the rejected parameter. Explicit auth, permission, overload or other
1596
- // error codes take precedence even when their message mentions continuation.
1597
- if (normalizedCode !== undefined &&
1598
- normalizedCode !== 'invalid_request_error' &&
1599
- normalizedCode !== 'api_error' &&
1600
- normalizedCode !== 'mar_agent_model_protocol_error')
1601
- return false;
1602
- return (normalizedMessage.includes('previous_response_id') &&
1603
- (normalizedMessage.includes('invalid') ||
1604
- normalizedMessage.includes('not found') ||
1605
- normalizedMessage.includes('does not exist') ||
1606
- normalizedMessage.includes('expired') ||
1607
- normalizedMessage.includes('not supported') ||
1608
- normalizedMessage.includes('unsupported') ||
1609
- normalizedMessage.includes('unavailable')));
1610
- }
@@ -1,22 +1,19 @@
1
1
  import { AgentError } from '../error.js';
2
- import { isAnthropicRecoverableStreamError } from './anthropic-messages.js';
3
- import { isRetryableModelRequestError, modelRetryMaxAttempts, waitForModelRetry } from './http.js';
4
- import { isOpenAiResponsesRecoverableStreamError } from './openai-responses.js';
2
+ import { isRecoverableModelError, modelRetryAfter } from './errors/common.js';
3
+ import { modelRetryMaxAttempts, waitForModelRetry } from './http.js';
5
4
  /** Retry only classified recoverable failures within the attempt budget; never retry cancellation. */
6
5
  export async function recoverModelStream(error, retryState, signal) {
7
6
  if (signal.aborted ||
8
7
  !((error instanceof AgentError &&
9
8
  error.code === 'MAR_AGENT_MODEL_OUTPUT_INCOMPLETE' &&
10
9
  error.retryable) ||
11
- isRetryableModelRequestError(error) ||
12
- isOpenAiResponsesRecoverableStreamError(error) ||
13
- isAnthropicRecoverableStreamError(error)) ||
10
+ isRecoverableModelError(error)) ||
14
11
  retryState.attempts >= modelRetryMaxAttempts(retryState))
15
12
  return false;
16
13
  const delayMs = retryState.retryDelayMs;
17
14
  delete retryState.retryDelayMs;
18
15
  try {
19
- await waitForModelRetry(typeof error.details?.retryAfter === 'string' ? error.details.retryAfter : null, retryState.attempts - 1, signal, delayMs);
16
+ await waitForModelRetry(modelRetryAfter(error), retryState.attempts - 1, signal, delayMs);
20
17
  }
21
18
  catch (error) {
22
19
  signal.throwIfAborted();
@@ -1,10 +1,10 @@
1
+ import type { ModelErrorDecision, UpstreamModelError } from './errors/chain.js';
1
2
  export declare function observeModelStreamEvent<const T>(value: T, observedAt: number | undefined): T;
2
3
  export declare function modelStreamEventObservedAt(value: unknown): number | undefined;
3
- export declare function parseSse(response: Response, signal: AbortSignal, maxBytes?: number, idleTimeoutMs?: number, sensitiveValues?: readonly string[]): AsyncIterable<unknown>;
4
+ export declare function parseSse(response: Response, signal: AbortSignal, maxBytes?: number, idleTimeoutMs?: number, sensitiveValues?: readonly string[], classifyError?: (facts: UpstreamModelError) => ModelErrorDecision | undefined): AsyncIterable<unknown>;
4
5
  export declare function parseResponseJson(value: string, message: string): unknown;
5
6
  export declare function redactResponseHeader(value: string | null | undefined, sensitiveValues: readonly string[], limit?: number): string | null;
6
7
  export declare function responseRedactor(sensitiveValues: readonly string[]): (value: string) => string;
7
- export declare function isRetryableUpstreamOverloadCode(code: string | undefined): boolean;
8
8
  export declare function record(value: unknown): Record<string, unknown>;
9
9
  export declare function text(value: unknown): string | undefined;
10
10
  export declare function number(value: unknown): number | undefined;
package/dist/model/sse.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { AgentError } from '../error.js';
2
- import { isRetryableModelHttpStatus } from './http.js';
2
+ import { classifyHttpError, RecoverableModelError } from './errors/common.js';
3
3
  /**
4
4
  * Decodes bounded SSE responses and shares safe JSON/header diagnostics with adapters.
5
5
  * The parser owns its reader; adapters own credentials, retries, and request cancellation.
@@ -14,12 +14,19 @@ export function observeModelStreamEvent(value, observedAt) {
14
14
  export function modelStreamEventObservedAt(value) {
15
15
  return typeof value === 'object' && value !== null ? streamEventObservedAt.get(value) : undefined;
16
16
  }
17
- export async function* parseSse(response, signal, maxBytes = 16 * 1024 * 1024, idleTimeoutMs = DEFAULT_MODEL_STREAM_IDLE_TIMEOUT_MS, sensitiveValues = []) {
17
+ export async function* parseSse(response, signal, maxBytes = 16 * 1024 * 1024, idleTimeoutMs = DEFAULT_MODEL_STREAM_IDLE_TIMEOUT_MS, sensitiveValues = [], classifyError = classifyHttpError) {
18
18
  if (!response.ok) {
19
19
  const redact = responseRedactor(sensitiveValues);
20
20
  const body = redact(await readResponseText(response, signal, maxBytes, idleTimeoutMs));
21
21
  const header = (name, limit) => redactResponseHeader(response.headers.get(name), sensitiveValues, limit);
22
22
  const upstream = upstreamError(body);
23
+ const decision = classifyError({
24
+ source: 'http',
25
+ status: response.status,
26
+ code: upstream?.code,
27
+ message: upstream?.message
28
+ });
29
+ const ErrorType = decision?.action === 'retry' ? RecoverableModelError : AgentError;
23
30
  const code = upstream?.code ??
24
31
  (response.status === 401 || response.status === 403
25
32
  ? 'MAR_AGENT_MODEL_AUTH_FAILED'
@@ -28,7 +35,7 @@ export async function* parseSse(response, signal, maxBytes = 16 * 1024 * 1024, i
28
35
  : response.status === 408 || response.status === 504
29
36
  ? 'MAR_AGENT_MODEL_TIMEOUT'
30
37
  : 'MAR_AGENT_MODEL_PROTOCOL_ERROR');
31
- throw new AgentError(code, upstream?.message ?? `Model endpoint returned HTTP ${response.status}.`, {
38
+ throw new ErrorType(code, upstream?.message ?? `Model endpoint returned HTTP ${response.status}.`, {
32
39
  details: {
33
40
  status: response.status,
34
41
  body: body.slice(0, 4096),
@@ -36,8 +43,7 @@ export async function* parseSse(response, signal, maxBytes = 16 * 1024 * 1024, i
36
43
  contentType: header('content-type', 256),
37
44
  requestId: header('x-request-id', 256) ?? header('request-id', 256),
38
45
  retryAfter: header('retry-after', 128)
39
- },
40
- retryable: isRetryableModelHttpStatus(response.status)
46
+ }
41
47
  });
42
48
  }
43
49
  if (response.body === null)
@@ -253,21 +259,6 @@ function upstreamError(body) {
253
259
  const message = bounded(text(error.message), 1_000);
254
260
  return message === undefined ? undefined : { ...(code === undefined ? {} : { code }), message };
255
261
  }
256
- const RETRYABLE_UPSTREAM_OVERLOAD_CODES = new Set([
257
- 'rate_limit_error',
258
- 'overloaded_error',
259
- 'api_overloaded',
260
- 'server_is_overloaded',
261
- 'system_cpu_overloaded',
262
- 'resource_exhausted',
263
- 'temporarily_unavailable',
264
- 'service_unavailable'
265
- ]);
266
- // Closed set of transient upstream capacity/overload error codes; never grows into a
267
- // vendor-specific or free-text error classification table.
268
- export function isRetryableUpstreamOverloadCode(code) {
269
- return code !== undefined && RETRYABLE_UPSTREAM_OVERLOAD_CODES.has(code.toLowerCase());
270
- }
271
262
  function bounded(value, maximum) {
272
263
  if (value === undefined)
273
264
  return undefined;
package/dist/sdk/agent.js CHANGED
@@ -22,7 +22,7 @@ export async function createAgent(options) {
22
22
  }
23
23
  /** Package-internal seam for deterministic adapter tests; not a package export. */
24
24
  export async function createAgentWithAdapter(options, adapterFactory) {
25
- const resolvedModels = resolveAgentModels(options.models);
25
+ const resolvedModels = resolveAgentModels(options.models, options.defaultModelId);
26
26
  let { models, defaultModelId } = resolvedModels;
27
27
  let modelGeneration = 0;
28
28
  const { credentialProviders } = resolvedModels;
@@ -99,7 +99,7 @@ export declare class SessionExecution {
99
99
  readonly compact: CompactCoordinator;
100
100
  readonly compactRequests: CompactRequests;
101
101
  readonly context: SessionExecutionContext;
102
- private resultPromise;
102
+ private readonly completion;
103
103
  private readonly modelResources;
104
104
  private eventTail;
105
105
  private terminalAdmitted;
@@ -163,7 +163,7 @@ export declare class SessionExecution {
163
163
  readonly finalize: (failed: boolean) => Promise<void>;
164
164
  readonly settle: (status: ExecutionResult['status']) => void;
165
165
  }): void;
166
- join(): Promise<ExecutionResult> | undefined;
166
+ join(): Promise<ExecutionResult>;
167
167
  handle(): InternalExecutionHandle;
168
168
  cancel(reason?: unknown): void;
169
169
  }
@@ -59,7 +59,8 @@ export class SessionExecution {
59
59
  compact = new CompactCoordinator();
60
60
  compactRequests;
61
61
  context;
62
- resultPromise;
62
+ // Synchronous admission observers can join before start runs the workflow.
63
+ completion = Promise.withResolvers();
63
64
  modelResources;
64
65
  eventTail = Promise.resolve();
65
66
  terminalAdmitted = false;
@@ -399,11 +400,13 @@ export class SessionExecution {
399
400
  await input.finalize(failed);
400
401
  }
401
402
  });
402
- this.resultPromise = result;
403
403
  void result.then((outcome) => input.settle(outcome.status), () => input.settle('failed'));
404
+ // Forward the result after registering settlement, even if no caller awaits it.
405
+ void this.completion.promise.catch(() => undefined);
406
+ this.completion.resolve(result);
404
407
  }
405
408
  join() {
406
- return this.resultPromise;
409
+ return this.completion.promise;
407
410
  }
408
411
  handle() {
409
412
  const persistedEvents = () => this.persistedTerminal;
@@ -416,7 +419,7 @@ export class SessionExecution {
416
419
  [Symbol.asyncIterator]: () => this.events[Symbol.asyncIterator](),
417
420
  result: () => {
418
421
  this.events.discardIfUnobserved();
419
- return this.resultPromise;
422
+ return this.join();
420
423
  },
421
424
  cancel: () => this.cancel(new AgentError('MAR_AGENT_CANCELLED', 'Execution was cancelled.'))
422
425
  };
@@ -203,9 +203,6 @@ export class SessionRuntime {
203
203
  execution.cancel();
204
204
  }
205
205
  joinExecutions() {
206
- return Promise.allSettled([...this.#executions.values()].flatMap((execution) => {
207
- const result = execution.join();
208
- return result === undefined ? [] : [result];
209
- }));
206
+ return Promise.allSettled([...this.#executions.values()].map((execution) => execution.join()));
210
207
  }
211
208
  }
@@ -612,10 +612,10 @@ export class JsonlSessionStore {
612
612
  const source = this.#shared.index.sessions.find((item) => item.id === sourceSessionId);
613
613
  if (!source)
614
614
  throw new AgentError('MAR_AGENT_SESSION_NOT_FOUND', 'Session was not found.');
615
- if (source.storage?.encoding !== 2)
615
+ if (input.boundaryTurnId !== null && source.storage?.encoding !== 2)
616
616
  await preflightV1Session(sourceRoot);
617
617
  await this.#ensureRootV2();
618
- const records = await this.#readRecords(sourceSessionId);
618
+ const records = input.boundaryTurnId === null ? [] : await this.#readRecords(sourceSessionId, source);
619
619
  let publicationConfirmed = false;
620
620
  return await forkSessionOperation(source, records, input, sourceRoot, this.#sessionDirectory(sourceSessionId), {
621
621
  begin: async (target) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myagentroam/agent",
3
- "version": "0.14.5",
3
+ "version": "0.14.7",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/myagentroam/mar.git",