@alvin0/ai-agent-sdk-core 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +6 -0
  2. package/dist/agent/define/session/config.js +1 -1
  3. package/dist/agent/define/session/config.js.map +1 -1
  4. package/dist/agent/define/session/types.d.ts +14 -0
  5. package/dist/agent/define/session/types.d.ts.map +1 -1
  6. package/dist/agent/define/session.d.ts.map +1 -1
  7. package/dist/agent/define/session.js +1 -1
  8. package/dist/agent/define/session.js.map +1 -1
  9. package/dist/agent/loop/events.d.ts +24 -1
  10. package/dist/agent/loop/events.d.ts.map +1 -1
  11. package/dist/agent/loop/run-turn.d.ts.map +1 -1
  12. package/dist/agent/loop/run-turn.js +1 -1
  13. package/dist/agent/loop/run-turn.js.map +1 -1
  14. package/dist/agent/loop/schedule.d.ts +5 -0
  15. package/dist/agent/loop/schedule.d.ts.map +1 -1
  16. package/dist/agent/loop/schedule.js +1 -1
  17. package/dist/agent/loop/schedule.js.map +1 -1
  18. package/dist/agent/loop/turn/config.js +1 -1
  19. package/dist/agent/loop/turn/config.js.map +1 -1
  20. package/dist/agent/loop/turn/model-request-boundary.js +1 -1
  21. package/dist/agent/loop/turn/model-request-boundary.js.map +1 -1
  22. package/dist/agent/loop/turn/model-round.js +1 -1
  23. package/dist/agent/loop/turn/model-round.js.map +1 -1
  24. package/dist/agent/loop/turn/types.d.ts +35 -2
  25. package/dist/agent/loop/turn/types.d.ts.map +1 -1
  26. package/dist/agent/loop/types.d.ts +16 -0
  27. package/dist/agent/loop/types.d.ts.map +1 -1
  28. package/dist/agent/mode/run-agent.d.ts +9 -0
  29. package/dist/agent/mode/run-agent.d.ts.map +1 -1
  30. package/dist/agent/mode/run-agent.js +2 -2
  31. package/dist/agent/mode/run-agent.js.map +1 -1
  32. package/dist/agent/mode/user-input.d.ts.map +1 -1
  33. package/dist/agent/mode/user-input.js +1 -1
  34. package/dist/agent/mode/user-input.js.map +1 -1
  35. package/dist/agent/team/managed.d.ts.map +1 -1
  36. package/dist/agent/team/managed.js +1 -1
  37. package/dist/agent/team/managed.js.map +1 -1
  38. package/dist/agent/tool/capture.js +1 -1
  39. package/dist/agent/tool/capture.js.map +1 -1
  40. package/dist/agent/tool/definition.d.ts +7 -0
  41. package/dist/agent/tool/definition.d.ts.map +1 -1
  42. package/dist/agent/tool/definition.js.map +1 -1
  43. package/dist/agent.js +1 -1
  44. package/dist/composition/agent/public-event.d.ts +19 -0
  45. package/dist/composition/agent/public-event.d.ts.map +1 -0
  46. package/dist/composition/agent/public-event.js +2 -0
  47. package/dist/composition/agent/public-event.js.map +1 -0
  48. package/dist/composition/agent/session.js +1 -1
  49. package/dist/composition/agent/session.js.map +1 -1
  50. package/dist/composition/agent/types.d.ts +11 -1
  51. package/dist/composition/agent/types.d.ts.map +1 -1
  52. package/dist/composition/embedding/retry.js +1 -1
  53. package/dist/composition/embedding/retry.js.map +1 -1
  54. package/dist/embedding/errors.d.ts +5 -1
  55. package/dist/embedding/errors.d.ts.map +1 -1
  56. package/dist/embedding/errors.js +1 -1
  57. package/dist/embedding/errors.js.map +1 -1
  58. package/dist/index.d.ts +2 -1
  59. package/dist/index.js +1 -1
  60. package/dist/observability/bus.js +1 -1
  61. package/dist/primitives/version.d.ts +1 -1
  62. package/dist/primitives/version.js +1 -1
  63. package/dist/primitives/version.js.map +1 -1
  64. package/dist/runtime/registry.js +1 -1
  65. package/dist/runtime/with-retry.d.ts +15 -0
  66. package/dist/runtime/with-retry.d.ts.map +1 -1
  67. package/dist/runtime/with-retry.js +1 -1
  68. package/dist/runtime/with-retry.js.map +1 -1
  69. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"retry.js","names":[],"sources":["../../../src/composition/embedding/retry.ts"],"sourcesContent":["/**\n * The ONE retry layer for embedding.\n *\n * `Embedding_Runtime` owns retry; an `Embedding_Adapter` performs exactly one\n * `Provider_Attempt` per `embedBatch()` call and never retries inside\n * (Requirement 4.3). Keeping retry here is what makes a `Provider_Attempt`\n * countable: the number of attempts a caller is billed for equals the number of\n * times this file called the adapter.\n *\n * Four facts drive every branch below:\n *\n * 1. **Only unsuccessful batches are retried.** A batch that reached\n * `succeeded` is removed from every later retry pass of the same\n * `Logical_Call` — its vectors already exist, and re-sending it would be a\n * second charge for a result we hold (Requirement 4.7). The ledger enforces\n * this structurally: a terminal state is never re-entered.\n * 2. **Dispatch state comes from the transport, it is not re-derived.**\n * `Http_Transport` sets `dispatchState = 'unknown'` immediately before\n * `fetch` and only raises it to `'sent'` once a response exists, so this file\n * reads the value the transport reported through `attempt.end` instead of\n * guessing from the shape of the error. When nothing reported a state, the\n * record stays `'unknown'`: only the transport is in a position to claim\n * `'not-sent'`, and a timeout in particular is never that (Requirement 4.8).\n * 3. **No fallback model.** A failure of the primary model propagates to the\n * caller. Fallback is only ever configured within a group sharing one\n * `compatibilityIdentity`, and that condition is checked when the handle is\n * built, not after a failure has happened (Requirements 6.6, 6.7).\n * 4. **Order is not this file's business.** Vectors are handed back per batch and\n * the caller writes them at `item.index`, so retries and out-of-order\n * settlement cannot disturb output order (Requirement 4.6).\n *\n * Concurrency lives in `limiter.ts`; this file drives one batch at a time and is\n * composed underneath it.\n *\n * @module ai-agent-sdk/core/composition/embedding/retry\n */\n\nimport {\n backoffDelayMs,\n resolveRetryPolicy,\n type ResolvedRetryPolicy,\n} from '../../contract/retry-policy.ts'\nimport { EMBEDDING_ERROR_CODES, EmbeddingError } from '../../embedding/errors.ts'\nimport type { EmbeddingBatchRequest } from '../../embedding/request.ts'\nimport type { EmbeddingBatchResult, EmbeddingVector, EmbeddingWarning } from '../../embedding/result.ts'\nimport { normalizeModelFailure, type ModelFailure } from '../../errors/failure.ts'\nimport { MODEL_ERROR_CODES } from '../../errors/model-error.ts'\nimport type {\n EndProviderAttemptInput,\n ModelInvocationContext,\n ProviderAttemptHandle,\n} from '../../observation/report.ts'\nimport type { AttemptUsageReport, DispatchState } from '../../observation/usage.ts'\n\n/**\n * Lifecycle of one `Physical_Batch` inside a single `Logical_Call`.\n *\n * `succeeded` and `failed` are terminal. That is the whole mechanism behind\n * Requirement 4.7: retry only ever considers a batch that is not yet terminal.\n */\nexport type BatchState =\n | { readonly phase: 'pending' }\n | { readonly phase: 'in-flight'; readonly attempt: number }\n | { readonly phase: 'succeeded'; readonly vectors: readonly EmbeddingVector[] }\n | {\n readonly phase: 'failed'\n readonly error: EmbeddingError\n readonly retryable: boolean\n /** As reported by the transport; `'unknown'` whenever nothing reported. */\n readonly dispatch: DispatchState\n }\n\n/** One retry that is about to be waited out, for logging and metrics. */\nexport interface EmbeddingRetryAttempt {\n readonly provider: string\n readonly model: string\n /** Plan coordinate of the batch being retried. */\n readonly batchIndex: number\n /** 1-based retry number. */\n readonly attempt: number\n /** Retry ceiling, or `undefined` under an `always` policy. */\n readonly maxRetries: number | undefined\n /** Stable code of the failure being recovered from. */\n readonly failureCode: string\n /** Dispatch state the transport reported for the failed attempt. */\n readonly dispatch: DispatchState\n readonly delayMs: number\n}\n\n/** What one `Provider_Attempt` on a batch left behind. */\nexport interface EmbeddingAttemptRecord {\n /** 1-based attempt number within this batch. */\n readonly attempt: number\n readonly outcome: 'success' | 'failure'\n /** From the transport, never re-derived (Requirement 4.8). */\n readonly dispatch: DispatchState\n /** Stable failure code, absent on success. */\n readonly failureCode?: string\n}\n\n/** Everything a `Logical_Call` needs to know about one settled batch. */\nexport interface EmbeddingBatchOutcome {\n readonly batchIndex: number\n /** Input indexes this batch carried, in `Logical_Call` numbering. */\n readonly itemIndexes: readonly number[]\n /** Terminal state: `succeeded` or `failed`. */\n readonly state: BatchState\n /** `Provider_Attempt`s spent, retries included (Requirement 16.6). */\n readonly attempts: number\n /** One record per adapter call, in order. */\n readonly attemptRecords: readonly EmbeddingAttemptRecord[]\n /**\n * Raw provider usage evidence from the attempt that settled the batch.\n *\n * `unknown` on purpose: proving it is a usage shape belongs to\n * `validateEmbeddingUsage`, and absence must never become a zero.\n */\n readonly usage?: unknown\n readonly providerRequestId?: string\n readonly warnings: readonly EmbeddingWarning[]\n}\n\n/** Dispatch surface of a `Prepared_Embedding_Call`; the ledger needs nothing else. */\nexport interface EmbeddingBatchDispatcher {\n embedBatch(\n batch: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchResult>\n}\n\n/** Knobs for {@link createEmbeddingRetryLedger}. */\nexport interface EmbeddingRetryOptions {\n /** Route policy; omission takes the shared SDK defaults. */\n readonly policy?: ResolvedRetryPolicy\n /** Sample in `[0, 1)` for jitter; injectable so tests can be deterministic. */\n readonly random?: () => number\n /** Caller signal or runtime `close()`; an abort is never a transient fault. */\n readonly signal?: AbortSignal\n /** Invocation context; wrapped so transport-reported dispatch states are observed. */\n readonly context?: ModelInvocationContext\n /** Observe each scheduled retry. Failures in the observer are swallowed. */\n readonly onRetry?: (attempt: EmbeddingRetryAttempt) => void\n /** Sleep hook; resolves `false` when the signal fired first. Injectable for tests. */\n readonly sleep?: (delayMs: number, signal?: AbortSignal) => Promise<boolean>\n}\n\n/**\n * Per-`Logical_Call` retry driver and state ledger.\n *\n * One ledger per `Logical_Call`, shared across every batch of that call, which\n * is what lets it guarantee that a `succeeded` batch is never dispatched again.\n */\nexport interface EmbeddingRetryLedger {\n /**\n * Dispatch one `Physical_Batch` and retry it until it settles.\n *\n * Resolves with a terminal outcome instead of throwing, because only the\n * caller knows whether a failed batch should abandon the whole call or leave\n * the batches that already succeeded intact. There is no fallback model: a\n * failure here is the failure the caller sees.\n *\n * @param context - overrides the ledger's context for this batch only. One\n * ledger spans the whole `Logical_Call` while observation is per-batch, so this\n * is how an attempt gets parented under the batch that provoked it. The\n * override is wrapped for dispatch-state observation exactly like the\n * ledger-wide context, so nothing about Requirement 4.8 changes.\n */\n dispatch(\n batchIndex: number,\n request: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchOutcome>\n /** Current state of one batch; `pending` for a batch never dispatched. */\n stateOf(batchIndex: number): BatchState\n /** Immutable view of every batch state seen so far. */\n states(): ReadonlyMap<number, BatchState>\n}\n\nconst PENDING: BatchState = Object.freeze({ phase: 'pending' as const })\n\n/** Codes that mean \"the caller stopped this\", never \"the provider wobbled\". */\nfunction isAbortCode(code: string): boolean {\n return code === MODEL_ERROR_CODES.ABORTED || code === EMBEDDING_ERROR_CODES.ABORTED\n}\n\n/**\n * Turn any thrown value into an {@link EmbeddingError} without losing its code.\n *\n * An `EmbeddingError` from the adapter passes through untouched: it already\n * carries `itemIndexes` and `limit`, and re-wrapping would drop exactly the\n * facts a caller needs to re-chunk the offending inputs. Anything else keeps its\n * normalized stable code — a rate limit stays `MODEL_RATE_LIMIT` so the retry\n * allow-list still recognises it.\n */\nfunction asEmbeddingError(\n value: unknown,\n failure: ModelFailure,\n request: EmbeddingBatchRequest,\n): EmbeddingError {\n if (value instanceof EmbeddingError) return value\n return new EmbeddingError(failure.message, failure.code, {\n cause: value,\n provider: request.provider,\n model: request.model,\n itemIndexes: request.items.map(item => item.index),\n })\n}\n\n/** Sleep, resolving early and reporting `false` if the signal aborts first. */\nfunction cancellableDelay(delayMs: number, signal?: AbortSignal): Promise<boolean> {\n if (signal?.aborted === true) return Promise.resolve(false)\n return new Promise((resolve) => {\n const onAbort = (): void => {\n clearTimeout(timer)\n resolve(false)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve(true)\n }, delayMs)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/** Honour a sane provider-requested `retry-after`, else local bounded backoff. */\nfunction delayFor(\n policy: ResolvedRetryPolicy,\n failure: ModelFailure,\n attempt: number,\n random: () => number,\n): number | 'give-up' {\n const requested = failure.providerRetryAfterMs\n if (requested !== undefined && Number.isFinite(requested) && requested > 0) {\n if (requested <= policy.maxDelayMs) return requested\n // The provider asked for longer than this policy will wait. Under a bounded\n // policy that is a refusal: sleeping less than asked just earns another rate\n // limit. An `always` policy has nowhere to give up to.\n return policy.mode === 'always' ? backoffDelayMs(policy, attempt, random) : 'give-up'\n }\n return backoffDelayMs(policy, attempt, random)\n}\n\n/**\n * Wrap an invocation context so the dispatch state the TRANSPORT reports is\n * captured, rather than inferred from the error afterwards.\n *\n * The wrapper is transparent: it forwards `startProviderAttempt` untouched and\n * only tees the `dispatchState` passed to `attempt.end`. When a context has no\n * attempt accounting there is nothing to observe, and the record stays\n * `'unknown'` — that is the honest answer, and it is the answer Requirement 4.8\n * demands for a timeout.\n */\nfunction observeDispatchState(\n context: ModelInvocationContext | undefined,\n sink: (state: DispatchState) => void,\n): ModelInvocationContext | undefined {\n const start = context?.startProviderAttempt\n if (context === undefined || start === undefined) return context\n return {\n ...context,\n startProviderAttempt: async (input, signal): Promise<ProviderAttemptHandle> => {\n const handle = await start(input, signal)\n return {\n attemptId: handle.attemptId,\n attemptNumber: handle.attemptNumber,\n traceparent: handle.traceparent,\n end: (end: EndProviderAttemptInput): AttemptUsageReport => {\n sink(end.dispatchState)\n return handle.end(end)\n },\n }\n },\n }\n}\n\n/**\n * Create the retry ledger for one `Logical_Call`.\n *\n * An `always` policy without a signal is rejected here rather than at the first\n * failure: unbounded retry is bounded only by cancellation, so a call that\n * cannot be cancelled would never terminate.\n */\nexport function createEmbeddingRetryLedger(\n dispatcher: EmbeddingBatchDispatcher,\n options: EmbeddingRetryOptions = {},\n): EmbeddingRetryLedger {\n const policy = options.policy ?? resolveRetryPolicy(undefined, 'embedding.retryPolicy')\n if (policy.mode === 'always' && options.signal === undefined) {\n throw new EmbeddingError(\n 'an always retry policy requires an AbortSignal',\n EMBEDDING_ERROR_CODES.CONFIGURATION_INVALID,\n )\n }\n const random = options.random ?? Math.random\n const sleep = options.sleep ?? cancellableDelay\n const states = new Map<number, BatchState>()\n\n /**\n * Whether either signal has fired.\n *\n * A function rather than an inline check so the answer is re-read after every\n * `await`: a signal that aborts while a request is in flight is precisely the\n * case that matters.\n */\n const cancelled = (request: EmbeddingBatchRequest): boolean =>\n options.signal?.aborted === true || request.signal?.aborted === true\n\n const abortedOutcome = (\n batchIndex: number,\n request: EmbeddingBatchRequest,\n records: readonly EmbeddingAttemptRecord[],\n error: EmbeddingError,\n dispatch: DispatchState,\n ): EmbeddingBatchOutcome => {\n const state: BatchState = Object.freeze({\n phase: 'failed' as const,\n error,\n // An abort is the caller's decision, so it is terminal by definition.\n retryable: false,\n dispatch,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes: Object.freeze(request.items.map(item => item.index)),\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n warnings: Object.freeze([]),\n })\n }\n\n return {\n stateOf(batchIndex: number): BatchState {\n return states.get(batchIndex) ?? PENDING\n },\n\n states(): ReadonlyMap<number, BatchState> {\n return new Map(states)\n },\n\n async dispatch(\n batchIndex: number,\n request: EmbeddingBatchRequest,\n batchContext?: ModelInvocationContext,\n ): Promise<EmbeddingBatchOutcome> {\n const invocationContext = batchContext ?? options.context\n const existing = states.get(batchIndex)\n if (existing !== undefined && existing.phase === 'succeeded') {\n // Requirement 4.7 as an invariant rather than a convention: a batch whose\n // vectors are already held is never handed to the provider again.\n throw new EmbeddingError(\n `embedding batch ${batchIndex} already succeeded and must not be dispatched again`,\n EMBEDDING_ERROR_CODES.CONFIGURATION_INVALID,\n { provider: request.provider, model: request.model },\n )\n }\n\n const itemIndexes = Object.freeze(request.items.map(item => item.index))\n const records: EmbeddingAttemptRecord[] = []\n let retries = 0\n\n for (;;) {\n const attemptNumber = records.length + 1\n // Report the abort before spending an attempt on a call already cancelled.\n if (cancelled(request)) {\n return abortedOutcome(\n batchIndex,\n request,\n records,\n new EmbeddingError(\n 'embedding call aborted before dispatch',\n EMBEDDING_ERROR_CODES.ABORTED,\n { provider: request.provider, model: request.model, itemIndexes: [...itemIndexes] },\n ),\n // No adapter call was ever made on this pass, which the runtime knows\n // first-hand. Once an attempt HAS been made, the runtime stops\n // claiming anything and leaves the state `unknown`.\n records.length === 0 ? 'not-sent' : 'unknown',\n )\n }\n\n states.set(batchIndex, Object.freeze({ phase: 'in-flight' as const, attempt: attemptNumber }))\n\n // Reported by the transport through `attempt.end`; unreported stays unknown.\n let reportedDispatch: DispatchState | undefined\n const context = observeDispatchState(invocationContext, (state) => {\n reportedDispatch = state\n })\n\n let result: EmbeddingBatchResult\n try {\n result = await dispatcher.embedBatch(request, context)\n } catch (error: unknown) {\n const failure = normalizeModelFailure(error)\n const dispatch = reportedDispatch ?? 'unknown'\n records.push(Object.freeze({\n attempt: attemptNumber,\n outcome: 'failure' as const,\n dispatch,\n failureCode: failure.code,\n }))\n\n const embeddingError = asEmbeddingError(error, failure, request)\n if (cancelled(request) || isAbortCode(failure.code)) {\n return abortedOutcome(batchIndex, request, records, embeddingError, dispatch)\n }\n\n const eligible = policy.mode === 'always'\n || (policy.retryableCodes.includes(failure.code) && retries < policy.maxRetries)\n const delayMs = eligible ? delayFor(policy, failure, retries + 1, random) : 'give-up'\n if (!eligible || delayMs === 'give-up') {\n const state: BatchState = Object.freeze({\n phase: 'failed' as const,\n error: embeddingError,\n // `retryable` describes the failure, not the budget: a rate limit\n // that ran out of attempts is still a retryable KIND of failure,\n // and a caller deciding whether to re-run later needs that apart\n // from \"this call gave up\".\n retryable: policy.mode === 'always' || policy.retryableCodes.includes(failure.code),\n dispatch,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes,\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n warnings: Object.freeze([]),\n })\n }\n\n retries += 1\n invocationContext?.recordProviderRetry?.({\n nextAttemptNumber: retries + 1,\n delayMs,\n failureCode: failure.code,\n })\n try {\n options.onRetry?.({\n provider: request.provider,\n model: request.model,\n batchIndex,\n attempt: retries,\n maxRetries: policy.mode === 'normal' ? policy.maxRetries : undefined,\n failureCode: failure.code,\n dispatch,\n delayMs,\n })\n } catch {\n // Metrics and logging observers do not own request availability.\n }\n\n if (!await sleep(delayMs, options.signal ?? request.signal)) {\n return abortedOutcome(\n batchIndex,\n request,\n records,\n new EmbeddingError(\n 'embedding call aborted while waiting to retry',\n EMBEDDING_ERROR_CODES.ABORTED,\n { provider: request.provider, model: request.model, itemIndexes: [...itemIndexes], cause: error },\n ),\n dispatch,\n )\n }\n continue\n }\n\n // A response exists, so the request reached the provider. The transport's\n // own report still wins when it made one.\n const dispatch = reportedDispatch ?? 'sent'\n records.push(Object.freeze({\n attempt: attemptNumber,\n outcome: 'success' as const,\n dispatch,\n }))\n const state: BatchState = Object.freeze({\n phase: 'succeeded' as const,\n vectors: result.vectors,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes,\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n // Absent usage is left absent: the aggregator downgrades coverage\n // rather than counting an unreported batch as zero tokens.\n ...(result.usage === undefined ? {} : { usage: result.usage }),\n ...(result.providerRequestId === undefined\n ? {}\n : { providerRequestId: result.providerRequestId }),\n warnings: Object.freeze([...(result.warnings ?? [])]),\n })\n }\n },\n }\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"retry.js","names":[],"sources":["../../../src/composition/embedding/retry.ts"],"sourcesContent":["/**\n * The ONE retry layer for embedding.\n *\n * `Embedding_Runtime` owns retry; an `Embedding_Adapter` performs exactly one\n * `Provider_Attempt` per `embedBatch()` call and never retries inside\n * (Requirement 4.3). Keeping retry here is what makes a `Provider_Attempt`\n * countable: the number of attempts a caller is billed for equals the number of\n * times this file called the adapter.\n *\n * Four facts drive every branch below:\n *\n * 1. **Only unsuccessful batches are retried.** A batch that reached\n * `succeeded` is removed from every later retry pass of the same\n * `Logical_Call` — its vectors already exist, and re-sending it would be a\n * second charge for a result we hold (Requirement 4.7). The ledger enforces\n * this structurally: a terminal state is never re-entered.\n * 2. **Dispatch state comes from the transport, it is not re-derived.**\n * `Http_Transport` sets `dispatchState = 'unknown'` immediately before\n * `fetch` and only raises it to `'sent'` once a response exists, so this file\n * reads the value the transport reported through `attempt.end` instead of\n * guessing from the shape of the error. When nothing reported a state, the\n * record stays `'unknown'`: only the transport is in a position to claim\n * `'not-sent'`, and a timeout in particular is never that (Requirement 4.8).\n * 3. **No fallback model.** A failure of the primary model propagates to the\n * caller. Fallback is only ever configured within a group sharing one\n * `compatibilityIdentity`, and that condition is checked when the handle is\n * built, not after a failure has happened (Requirements 6.6, 6.7).\n * 4. **Order is not this file's business.** Vectors are handed back per batch and\n * the caller writes them at `item.index`, so retries and out-of-order\n * settlement cannot disturb output order (Requirement 4.6).\n *\n * Concurrency lives in `limiter.ts`; this file drives one batch at a time and is\n * composed underneath it.\n *\n * @module ai-agent-sdk/core/composition/embedding/retry\n */\n\nimport {\n backoffDelayMs,\n resolveRetryPolicy,\n type ResolvedRetryPolicy,\n} from '../../contract/retry-policy.ts'\nimport { EMBEDDING_ERROR_CODES, EmbeddingError } from '../../embedding/errors.ts'\nimport type { EmbeddingBatchRequest } from '../../embedding/request.ts'\nimport type { EmbeddingBatchResult, EmbeddingVector, EmbeddingWarning } from '../../embedding/result.ts'\nimport { normalizeModelFailure, type ModelFailure } from '../../errors/failure.ts'\nimport { MODEL_ERROR_CODES } from '../../errors/model-error.ts'\nimport type {\n EndProviderAttemptInput,\n ModelInvocationContext,\n ProviderAttemptHandle,\n} from '../../observation/report.ts'\nimport type { AttemptUsageReport, DispatchState } from '../../observation/usage.ts'\n\n/**\n * Lifecycle of one `Physical_Batch` inside a single `Logical_Call`.\n *\n * `succeeded` and `failed` are terminal. That is the whole mechanism behind\n * Requirement 4.7: retry only ever considers a batch that is not yet terminal.\n */\nexport type BatchState =\n | { readonly phase: 'pending' }\n | { readonly phase: 'in-flight'; readonly attempt: number }\n | { readonly phase: 'succeeded'; readonly vectors: readonly EmbeddingVector[] }\n | {\n readonly phase: 'failed'\n readonly error: EmbeddingError\n readonly retryable: boolean\n /** As reported by the transport; `'unknown'` whenever nothing reported. */\n readonly dispatch: DispatchState\n }\n\n/** One retry that is about to be waited out, for logging and metrics. */\nexport interface EmbeddingRetryAttempt {\n readonly provider: string\n readonly model: string\n /** Plan coordinate of the batch being retried. */\n readonly batchIndex: number\n /** 1-based retry number. */\n readonly attempt: number\n /** Retry ceiling, or `undefined` under an `always` policy. */\n readonly maxRetries: number | undefined\n /** Stable code of the failure being recovered from. */\n readonly failureCode: string\n /** Dispatch state the transport reported for the failed attempt. */\n readonly dispatch: DispatchState\n readonly delayMs: number\n}\n\n/** What one `Provider_Attempt` on a batch left behind. */\nexport interface EmbeddingAttemptRecord {\n /** 1-based attempt number within this batch. */\n readonly attempt: number\n readonly outcome: 'success' | 'failure'\n /** From the transport, never re-derived (Requirement 4.8). */\n readonly dispatch: DispatchState\n /** Stable failure code, absent on success. */\n readonly failureCode?: string\n}\n\n/** Everything a `Logical_Call` needs to know about one settled batch. */\nexport interface EmbeddingBatchOutcome {\n readonly batchIndex: number\n /** Input indexes this batch carried, in `Logical_Call` numbering. */\n readonly itemIndexes: readonly number[]\n /** Terminal state: `succeeded` or `failed`. */\n readonly state: BatchState\n /** `Provider_Attempt`s spent, retries included (Requirement 16.6). */\n readonly attempts: number\n /** One record per adapter call, in order. */\n readonly attemptRecords: readonly EmbeddingAttemptRecord[]\n /**\n * Raw provider usage evidence from the attempt that settled the batch.\n *\n * `unknown` on purpose: proving it is a usage shape belongs to\n * `validateEmbeddingUsage`, and absence must never become a zero.\n */\n readonly usage?: unknown\n readonly providerRequestId?: string\n readonly warnings: readonly EmbeddingWarning[]\n}\n\n/** Dispatch surface of a `Prepared_Embedding_Call`; the ledger needs nothing else. */\nexport interface EmbeddingBatchDispatcher {\n embedBatch(\n batch: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchResult>\n}\n\n/** Knobs for {@link createEmbeddingRetryLedger}. */\nexport interface EmbeddingRetryOptions {\n /** Route policy; omission takes the shared SDK defaults. */\n readonly policy?: ResolvedRetryPolicy\n /** Sample in `[0, 1)` for jitter; injectable so tests can be deterministic. */\n readonly random?: () => number\n /** Caller signal or runtime `close()`; an abort is never a transient fault. */\n readonly signal?: AbortSignal\n /** Invocation context; wrapped so transport-reported dispatch states are observed. */\n readonly context?: ModelInvocationContext\n /** Observe each scheduled retry. Failures in the observer are swallowed. */\n readonly onRetry?: (attempt: EmbeddingRetryAttempt) => void\n /** Sleep hook; resolves `false` when the signal fired first. Injectable for tests. */\n readonly sleep?: (delayMs: number, signal?: AbortSignal) => Promise<boolean>\n}\n\n/**\n * Per-`Logical_Call` retry driver and state ledger.\n *\n * One ledger per `Logical_Call`, shared across every batch of that call, which\n * is what lets it guarantee that a `succeeded` batch is never dispatched again.\n */\nexport interface EmbeddingRetryLedger {\n /**\n * Dispatch one `Physical_Batch` and retry it until it settles.\n *\n * Resolves with a terminal outcome instead of throwing, because only the\n * caller knows whether a failed batch should abandon the whole call or leave\n * the batches that already succeeded intact. There is no fallback model: a\n * failure here is the failure the caller sees.\n *\n * @param context - overrides the ledger's context for this batch only. One\n * ledger spans the whole `Logical_Call` while observation is per-batch, so this\n * is how an attempt gets parented under the batch that provoked it. The\n * override is wrapped for dispatch-state observation exactly like the\n * ledger-wide context, so nothing about Requirement 4.8 changes.\n */\n dispatch(\n batchIndex: number,\n request: EmbeddingBatchRequest,\n context?: ModelInvocationContext,\n ): Promise<EmbeddingBatchOutcome>\n /** Current state of one batch; `pending` for a batch never dispatched. */\n stateOf(batchIndex: number): BatchState\n /** Immutable view of every batch state seen so far. */\n states(): ReadonlyMap<number, BatchState>\n}\n\nconst PENDING: BatchState = Object.freeze({ phase: 'pending' as const })\n\n/** Codes that mean \"the caller stopped this\", never \"the provider wobbled\". */\nfunction isAbortCode(code: string): boolean {\n return code === MODEL_ERROR_CODES.ABORTED || code === EMBEDDING_ERROR_CODES.ABORTED\n}\n\n/**\n * Turn any thrown value into an {@link EmbeddingError} without losing its code.\n *\n * An `EmbeddingError` from the adapter passes through untouched: it already\n * carries `itemIndexes` and `limit`, and re-wrapping would drop exactly the\n * facts a caller needs to re-chunk the offending inputs. Anything else keeps its\n * normalized stable code — a rate limit stays `MODEL_RATE_LIMIT` so the retry\n * allow-list still recognises it.\n */\nfunction asEmbeddingError(\n value: unknown,\n failure: ModelFailure,\n request: EmbeddingBatchRequest,\n): EmbeddingError {\n if (value instanceof EmbeddingError) return value\n return new EmbeddingError(failure.message, failure.code, {\n cause: value,\n ...failure.status === undefined ? {} : { status: failure.status },\n ...failure.providerRetryAfterMs === undefined ? {} : { providerRetryAfterMs: failure.providerRetryAfterMs },\n ...failure.requestId === undefined ? {} : { requestId: failure.requestId },\n provider: request.provider,\n model: request.model,\n itemIndexes: request.items.map(item => item.index),\n })\n}\n\n/** Sleep, resolving early and reporting `false` if the signal aborts first. */\nfunction cancellableDelay(delayMs: number, signal?: AbortSignal): Promise<boolean> {\n if (signal?.aborted === true) return Promise.resolve(false)\n return new Promise((resolve) => {\n const onAbort = (): void => {\n clearTimeout(timer)\n resolve(false)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve(true)\n }, delayMs)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\n/** Honour a sane provider-requested `retry-after`, else local bounded backoff. */\nfunction delayFor(\n policy: ResolvedRetryPolicy,\n failure: ModelFailure,\n attempt: number,\n random: () => number,\n): number | 'give-up' {\n const requested = failure.providerRetryAfterMs\n if (requested !== undefined && Number.isFinite(requested) && requested > 0) {\n if (requested <= policy.maxDelayMs) return requested\n // The provider asked for longer than this policy will wait. Under a bounded\n // policy that is a refusal: sleeping less than asked just earns another rate\n // limit. An `always` policy has nowhere to give up to.\n return policy.mode === 'always' ? backoffDelayMs(policy, attempt, random) : 'give-up'\n }\n return backoffDelayMs(policy, attempt, random)\n}\n\n/**\n * Wrap an invocation context so the dispatch state the TRANSPORT reports is\n * captured, rather than inferred from the error afterwards.\n *\n * The wrapper is transparent: it forwards `startProviderAttempt` untouched and\n * only tees the `dispatchState` passed to `attempt.end`. When a context has no\n * attempt accounting there is nothing to observe, and the record stays\n * `'unknown'` — that is the honest answer, and it is the answer Requirement 4.8\n * demands for a timeout.\n */\nfunction observeDispatchState(\n context: ModelInvocationContext | undefined,\n sink: (state: DispatchState) => void,\n): ModelInvocationContext | undefined {\n const start = context?.startProviderAttempt\n if (context === undefined || start === undefined) return context\n return {\n ...context,\n startProviderAttempt: async (input, signal): Promise<ProviderAttemptHandle> => {\n const handle = await start(input, signal)\n return {\n attemptId: handle.attemptId,\n attemptNumber: handle.attemptNumber,\n traceparent: handle.traceparent,\n end: (end: EndProviderAttemptInput): AttemptUsageReport => {\n sink(end.dispatchState)\n return handle.end(end)\n },\n }\n },\n }\n}\n\n/**\n * Create the retry ledger for one `Logical_Call`.\n *\n * An `always` policy without a signal is rejected here rather than at the first\n * failure: unbounded retry is bounded only by cancellation, so a call that\n * cannot be cancelled would never terminate.\n */\nexport function createEmbeddingRetryLedger(\n dispatcher: EmbeddingBatchDispatcher,\n options: EmbeddingRetryOptions = {},\n): EmbeddingRetryLedger {\n const policy = options.policy ?? resolveRetryPolicy(undefined, 'embedding.retryPolicy')\n if (policy.mode === 'always' && options.signal === undefined) {\n throw new EmbeddingError(\n 'an always retry policy requires an AbortSignal',\n EMBEDDING_ERROR_CODES.CONFIGURATION_INVALID,\n )\n }\n const random = options.random ?? Math.random\n const sleep = options.sleep ?? cancellableDelay\n const states = new Map<number, BatchState>()\n\n /**\n * Whether either signal has fired.\n *\n * A function rather than an inline check so the answer is re-read after every\n * `await`: a signal that aborts while a request is in flight is precisely the\n * case that matters.\n */\n const cancelled = (request: EmbeddingBatchRequest): boolean =>\n options.signal?.aborted === true || request.signal?.aborted === true\n\n const abortedOutcome = (\n batchIndex: number,\n request: EmbeddingBatchRequest,\n records: readonly EmbeddingAttemptRecord[],\n error: EmbeddingError,\n dispatch: DispatchState,\n ): EmbeddingBatchOutcome => {\n const state: BatchState = Object.freeze({\n phase: 'failed' as const,\n error,\n // An abort is the caller's decision, so it is terminal by definition.\n retryable: false,\n dispatch,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes: Object.freeze(request.items.map(item => item.index)),\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n warnings: Object.freeze([]),\n })\n }\n\n return {\n stateOf(batchIndex: number): BatchState {\n return states.get(batchIndex) ?? PENDING\n },\n\n states(): ReadonlyMap<number, BatchState> {\n return new Map(states)\n },\n\n async dispatch(\n batchIndex: number,\n request: EmbeddingBatchRequest,\n batchContext?: ModelInvocationContext,\n ): Promise<EmbeddingBatchOutcome> {\n const invocationContext = batchContext ?? options.context\n const existing = states.get(batchIndex)\n if (existing !== undefined && existing.phase === 'succeeded') {\n // Requirement 4.7 as an invariant rather than a convention: a batch whose\n // vectors are already held is never handed to the provider again.\n throw new EmbeddingError(\n `embedding batch ${batchIndex} already succeeded and must not be dispatched again`,\n EMBEDDING_ERROR_CODES.CONFIGURATION_INVALID,\n { provider: request.provider, model: request.model },\n )\n }\n\n const itemIndexes = Object.freeze(request.items.map(item => item.index))\n const records: EmbeddingAttemptRecord[] = []\n let retries = 0\n\n for (;;) {\n const attemptNumber = records.length + 1\n // Report the abort before spending an attempt on a call already cancelled.\n if (cancelled(request)) {\n return abortedOutcome(\n batchIndex,\n request,\n records,\n new EmbeddingError(\n 'embedding call aborted before dispatch',\n EMBEDDING_ERROR_CODES.ABORTED,\n { provider: request.provider, model: request.model, itemIndexes: [...itemIndexes] },\n ),\n // No adapter call was ever made on this pass, which the runtime knows\n // first-hand. Once an attempt HAS been made, the runtime stops\n // claiming anything and leaves the state `unknown`.\n records.length === 0 ? 'not-sent' : 'unknown',\n )\n }\n\n states.set(batchIndex, Object.freeze({ phase: 'in-flight' as const, attempt: attemptNumber }))\n\n // Reported by the transport through `attempt.end`; unreported stays unknown.\n let reportedDispatch: DispatchState | undefined\n const context = observeDispatchState(invocationContext, (state) => {\n reportedDispatch = state\n })\n\n let result: EmbeddingBatchResult\n try {\n result = await dispatcher.embedBatch(request, context)\n } catch (error: unknown) {\n const failure = normalizeModelFailure(error)\n const dispatch = reportedDispatch ?? 'unknown'\n records.push(Object.freeze({\n attempt: attemptNumber,\n outcome: 'failure' as const,\n dispatch,\n failureCode: failure.code,\n }))\n\n const embeddingError = asEmbeddingError(error, failure, request)\n if (cancelled(request) || isAbortCode(failure.code)) {\n return abortedOutcome(batchIndex, request, records, embeddingError, dispatch)\n }\n\n const eligible = policy.mode === 'always'\n || (policy.retryableCodes.includes(failure.code) && retries < policy.maxRetries)\n const delayMs = eligible ? delayFor(policy, failure, retries + 1, random) : 'give-up'\n if (!eligible || delayMs === 'give-up') {\n const state: BatchState = Object.freeze({\n phase: 'failed' as const,\n error: embeddingError,\n // `retryable` describes the failure, not the budget: a rate limit\n // that ran out of attempts is still a retryable KIND of failure,\n // and a caller deciding whether to re-run later needs that apart\n // from \"this call gave up\".\n retryable: policy.mode === 'always' || policy.retryableCodes.includes(failure.code),\n dispatch,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes,\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n warnings: Object.freeze([]),\n })\n }\n\n retries += 1\n invocationContext?.recordProviderRetry?.({\n nextAttemptNumber: retries + 1,\n delayMs,\n failureCode: failure.code,\n })\n try {\n options.onRetry?.({\n provider: request.provider,\n model: request.model,\n batchIndex,\n attempt: retries,\n maxRetries: policy.mode === 'normal' ? policy.maxRetries : undefined,\n failureCode: failure.code,\n dispatch,\n delayMs,\n })\n } catch {\n // Metrics and logging observers do not own request availability.\n }\n\n if (!await sleep(delayMs, options.signal ?? request.signal)) {\n return abortedOutcome(\n batchIndex,\n request,\n records,\n new EmbeddingError(\n 'embedding call aborted while waiting to retry',\n EMBEDDING_ERROR_CODES.ABORTED,\n { provider: request.provider, model: request.model, itemIndexes: [...itemIndexes], cause: error },\n ),\n dispatch,\n )\n }\n continue\n }\n\n // A response exists, so the request reached the provider. The transport's\n // own report still wins when it made one.\n const dispatch = reportedDispatch ?? 'sent'\n records.push(Object.freeze({\n attempt: attemptNumber,\n outcome: 'success' as const,\n dispatch,\n }))\n const state: BatchState = Object.freeze({\n phase: 'succeeded' as const,\n vectors: result.vectors,\n })\n states.set(batchIndex, state)\n return Object.freeze({\n batchIndex,\n itemIndexes,\n state,\n attempts: records.length,\n attemptRecords: Object.freeze([...records]),\n // Absent usage is left absent: the aggregator downgrades coverage\n // rather than counting an unreported batch as zero tokens.\n ...(result.usage === undefined ? {} : { usage: result.usage }),\n ...(result.providerRequestId === undefined\n ? {}\n : { providerRequestId: result.providerRequestId }),\n warnings: Object.freeze([...(result.warnings ?? [])]),\n })\n }\n },\n }\n}\n"],"mappings":"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"}
@@ -1,4 +1,6 @@
1
+ import { ModelFailure } from "../errors/failure.js";
1
2
  import { AgentSdkError } from "../errors/agent-sdk-error.js";
3
+ import { ModelErrorOptions } from "../errors/model-error.js";
2
4
  import { EmbeddingSpaceId } from "./profile.js";
3
5
  //#region src/embedding/errors.d.ts
4
6
  /**
@@ -44,7 +46,7 @@ declare const EMBEDDING_ERROR_CODES: Readonly<{
44
46
  /** Any value of {@link EMBEDDING_ERROR_CODES}; a foreign adapter may still use its own `string`. */
45
47
  type EmbeddingErrorCode = typeof EMBEDDING_ERROR_CODES[keyof typeof EMBEDDING_ERROR_CODES];
46
48
  /** Structured embedding facts and cause accepted by {@link EmbeddingError}. */
47
- interface EmbeddingErrorOptions extends ErrorOptions {
49
+ interface EmbeddingErrorOptions extends ModelErrorOptions {
48
50
  /**
49
51
  * Zero-based indexes of the request items this failure belongs to.
50
52
  *
@@ -76,6 +78,8 @@ interface EmbeddingErrorOptions extends ErrorOptions {
76
78
  * out of errors and traces alike.
77
79
  */
78
80
  declare class EmbeddingError extends AgentSdkError {
81
+ /** Validated provider facts survive the embedding wrapper and normalization. */
82
+ readonly failure: ModelFailure;
79
83
  /** Request item indexes this failure belongs to, when input-specific. */
80
84
  readonly itemIndexes?: readonly number[];
81
85
  /** The applied limit, when the failure is a limit violation. */
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/embedding/errors.ts"],"mappings":";;;;;;;;;;;cA2Ba,uBAAqB;;WAEf;;WAEA;;WAEO;;WAEP;;WAEG;;WAEC;;WAEG;;WAED;;WAED;;WAEA;;WAEM;;WAER;;WAEX;;WAEc;;WAEd;;;KAIC,4BAA4B,mCAAmC;;UAG1D,8BAA8B;;;;;;;EAO7C;;EAEA;;EAEA;;EAEA;;EAEA,QAAQ;;;;;;;;;;;;;;;;cAiBG,uBAAuB;;WAEzB;;WAEA;;WAEA;;WAEA;;WAEA,QAAQ;;;;;;EAOjB,YAAY,iBAAiB,cAAc,UAAU"}
1
+ {"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/embedding/errors.ts"],"mappings":";;;;;;;;;;;;;cA6Ba,uBAAqB;;WAEf;;WAEA;;WAEO;;WAEP;;WAEG;;WAEC;;WAEG;;WAED;;WAED;;WAEA;;WAEM;;WAER;;WAEX;;WAEc;;WAEd;;;KAIC,4BAA4B,mCAAmC;;UAG1D,8BAA8B;;;;;;;EAO7C;;EAEA;;EAEA;;EAEA;;EAEA,QAAQ;;;;;;;;;;;;;;;;cAiBG,uBAAuB;;WAEzB,SAAS;;WAET;;WAEA;;WAEA;;WAEA;;WAEA,QAAQ;;;;;;EAOjB,YAAY,iBAAiB,cAAc,UAAU"}
@@ -1,2 +1,2 @@
1
- import{AgentSdkError as e}from"../errors/agent-sdk-error.js";const t=Object.freeze({ADAPTER_MISSING:`EMBEDDING_ADAPTER_MISSING`,REQUEST_INVALID:`EMBEDDING_REQUEST_INVALID`,DIMENSIONS_UNSUPPORTED:`EMBEDDING_DIMENSIONS_UNSUPPORTED`,INPUT_TOO_LARGE:`EMBEDDING_INPUT_TOO_LARGE`,SPACE_INCOMPATIBLE:`EMBEDDING_SPACE_INCOMPATIBLE`,PURPOSE_UNSUPPORTED:`EMBEDDING_PURPOSE_UNSUPPORTED`,TRUNCATION_UNSUPPORTED:`EMBEDDING_TRUNCATION_UNSUPPORTED`,VECTOR_COUNT_MISMATCH:`EMBEDDING_VECTOR_COUNT_MISMATCH`,VECTOR_INDEX_INVALID:`EMBEDDING_VECTOR_INDEX_INVALID`,VECTOR_VALUE_INVALID:`EMBEDDING_VECTOR_VALUE_INVALID`,VECTOR_DIMENSIONS_MISMATCH:`EMBEDDING_VECTOR_DIMENSIONS_MISMATCH`,RESPONSE_MALFORMED:`EMBEDDING_RESPONSE_MALFORMED`,ABORTED:`EMBEDDING_ABORTED`,CONFIGURATION_INVALID:`EMBEDDING_CONFIGURATION_INVALID`,UNKNOWN:`EMBEDDING_UNKNOWN`});var n=class extends e{itemIndexes;limit;provider;model;space;constructor(e,t,n){if(typeof e!=`string`||e.length===0)throw Error(`EmbeddingError message must be a non-empty string`);if(typeof t!=`string`||t.length===0)throw Error(`EmbeddingError code must be a non-empty string`);if(n?.itemIndexes!==void 0&&(!Array.isArray(n.itemIndexes)||n.itemIndexes.some(e=>!Number.isInteger(e)||e<0)))throw Error(`EmbeddingError itemIndexes must be an array of non-negative integers`);if(n?.limit!==void 0&&(!Number.isFinite(n.limit)||n.limit<=0))throw Error(`EmbeddingError limit must be a positive finite number`);if(n?.provider!==void 0&&(typeof n.provider!=`string`||n.provider.length===0))throw Error(`EmbeddingError provider must be a non-empty string`);if(n?.model!==void 0&&(typeof n.model!=`string`||n.model.length===0))throw Error(`EmbeddingError model must be a non-empty string`);if(n?.space!==void 0&&(typeof n.space!=`string`||n.space.length===0))throw Error(`EmbeddingError space must be a non-empty string`);super(e,t,n),this.name=`EmbeddingError`,n?.itemIndexes!==void 0&&(this.itemIndexes=Object.freeze([...n.itemIndexes])),n?.limit!==void 0&&(this.limit=n.limit),n?.provider!==void 0&&(this.provider=n.provider),n?.model!==void 0&&(this.model=n.model),n?.space!==void 0&&(this.space=n.space)}};export{t as EMBEDDING_ERROR_CODES,n as EmbeddingError};
1
+ import{AgentSdkError as e}from"../errors/agent-sdk-error.js";import{ModelError as t}from"../errors/model-error.js";const n=Object.freeze({ADAPTER_MISSING:`EMBEDDING_ADAPTER_MISSING`,REQUEST_INVALID:`EMBEDDING_REQUEST_INVALID`,DIMENSIONS_UNSUPPORTED:`EMBEDDING_DIMENSIONS_UNSUPPORTED`,INPUT_TOO_LARGE:`EMBEDDING_INPUT_TOO_LARGE`,SPACE_INCOMPATIBLE:`EMBEDDING_SPACE_INCOMPATIBLE`,PURPOSE_UNSUPPORTED:`EMBEDDING_PURPOSE_UNSUPPORTED`,TRUNCATION_UNSUPPORTED:`EMBEDDING_TRUNCATION_UNSUPPORTED`,VECTOR_COUNT_MISMATCH:`EMBEDDING_VECTOR_COUNT_MISMATCH`,VECTOR_INDEX_INVALID:`EMBEDDING_VECTOR_INDEX_INVALID`,VECTOR_VALUE_INVALID:`EMBEDDING_VECTOR_VALUE_INVALID`,VECTOR_DIMENSIONS_MISMATCH:`EMBEDDING_VECTOR_DIMENSIONS_MISMATCH`,RESPONSE_MALFORMED:`EMBEDDING_RESPONSE_MALFORMED`,ABORTED:`EMBEDDING_ABORTED`,CONFIGURATION_INVALID:`EMBEDDING_CONFIGURATION_INVALID`,UNKNOWN:`EMBEDDING_UNKNOWN`});var r=class extends e{failure;itemIndexes;limit;provider;model;space;constructor(e,n,r){if(typeof e!=`string`||e.length===0)throw Error(`EmbeddingError message must be a non-empty string`);if(typeof n!=`string`||n.length===0)throw Error(`EmbeddingError code must be a non-empty string`);if(r?.itemIndexes!==void 0&&(!Array.isArray(r.itemIndexes)||r.itemIndexes.some(e=>!Number.isInteger(e)||e<0)))throw Error(`EmbeddingError itemIndexes must be an array of non-negative integers`);if(r?.limit!==void 0&&(!Number.isFinite(r.limit)||r.limit<=0))throw Error(`EmbeddingError limit must be a positive finite number`);if(r?.provider!==void 0&&(typeof r.provider!=`string`||r.provider.length===0))throw Error(`EmbeddingError provider must be a non-empty string`);if(r?.model!==void 0&&(typeof r.model!=`string`||r.model.length===0))throw Error(`EmbeddingError model must be a non-empty string`);if(r?.space!==void 0&&(typeof r.space!=`string`||r.space.length===0))throw Error(`EmbeddingError space must be a non-empty string`);let i=new t(e,n,r).failure;super(e,n,r),this.name=`EmbeddingError`,this.failure=i,r?.itemIndexes!==void 0&&(this.itemIndexes=Object.freeze([...r.itemIndexes])),r?.limit!==void 0&&(this.limit=r.limit),r?.provider!==void 0&&(this.provider=r.provider),r?.model!==void 0&&(this.model=r.model),r?.space!==void 0&&(this.space=r.space)}};export{n as EMBEDDING_ERROR_CODES,r as EmbeddingError};
2
2
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../../src/embedding/errors.ts"],"sourcesContent":["/**\n * The stable embedding failure taxonomy, and the error the embedding layers throw.\n *\n * Codes here are owned by two layers only: `Embedding_Runtime` before dispatch\n * (dimensions, limits, space, configuration) and `Embedding_Adapter` when it\n * validates a response (vector count, index, values, width). Transport-level\n * faults keep using `MODEL_ERROR_CODES`, so a caller can tell \"the provider is\n * rate limiting us\" apart from \"the provider returned a vector of the wrong\n * width\" without parsing any message.\n *\n * Both provider adapters emit the SAME codes for mapping, dimensions and vector\n * faults. That is what lets one contract-test suite run against both.\n *\n * @module ai-agent-sdk/core/embedding/errors\n */\n\nimport { AgentSdkError } from '../errors/agent-sdk-error.ts'\nimport type { EmbeddingSpaceId } from './profile.ts'\n\n/**\n * Codes produced by the embedding contract and runtime.\n *\n * A frozen object rather than a TS enum, matching `MODEL_ERROR_CODES`, so a\n * third-party embedding adapter can emit its own code without this union having\n * to know about it. Values are prefixed `EMBEDDING_` because they travel beside\n * generation codes in the same failure envelopes.\n */\nexport const EMBEDDING_ERROR_CODES = Object.freeze({\n /** No `Embedding_Adapter` is registered for the requested route/model. */\n ADAPTER_MISSING: 'EMBEDDING_ADAPTER_MISSING',\n /** Malformed at the SDK boundary: missing purpose, empty values, empty item. */\n REQUEST_INVALID: 'EMBEDDING_REQUEST_INVALID',\n /** `dimensions` is not among the widths the route declares support for. */\n DIMENSIONS_UNSUPPORTED: 'EMBEDDING_DIMENSIONS_UNSUPPORTED',\n /** Input exceeds the declared max input tokens; carries `itemIndexes` and `limit`. */\n INPUT_TOO_LARGE: 'EMBEDDING_INPUT_TOO_LARGE',\n /** The expected `Space_Id` is incompatible with the `Prepared_Embedding_Call`. */\n SPACE_INCOMPATIBLE: 'EMBEDDING_SPACE_INCOMPATIBLE',\n /** The route has no way to express this purpose and the caller demands the distinction. */\n PURPOSE_UNSUPPORTED: 'EMBEDDING_PURPOSE_UNSUPPORTED',\n /** The caller asked for truncation but the provider has no equivalent parameter. */\n TRUNCATION_UNSUPPORTED: 'EMBEDDING_TRUNCATION_UNSUPPORTED',\n /** The response carried a different number of vectors than inputs sent. */\n VECTOR_COUNT_MISMATCH: 'EMBEDDING_VECTOR_COUNT_MISMATCH',\n /** A vector index is duplicated, missing, or out of range. */\n VECTOR_INDEX_INVALID: 'EMBEDDING_VECTOR_INDEX_INVALID',\n /** A vector contains `NaN` or `Infinity`. */\n VECTOR_VALUE_INVALID: 'EMBEDDING_VECTOR_VALUE_INVALID',\n /** A vector's width differs from the requested `dimensions`. */\n VECTOR_DIMENSIONS_MISMATCH: 'EMBEDDING_VECTOR_DIMENSIONS_MISMATCH',\n /** The response does not satisfy the embedding contract structurally. */\n RESPONSE_MALFORMED: 'EMBEDDING_RESPONSE_MALFORMED',\n /** The caller's signal or a runtime close aborted the call. */\n ABORTED: 'EMBEDDING_ABORTED',\n /** Invalid handle configuration: cache enabled without scope, fallback outside the group. */\n CONFIGURATION_INVALID: 'EMBEDDING_CONFIGURATION_INVALID',\n /** Nothing in this taxonomy classified the embedding failure. */\n UNKNOWN: 'EMBEDDING_UNKNOWN',\n} as const)\n\n/** Any value of {@link EMBEDDING_ERROR_CODES}; a foreign adapter may still use its own `string`. */\nexport type EmbeddingErrorCode = typeof EMBEDDING_ERROR_CODES[keyof typeof EMBEDDING_ERROR_CODES]\n\n/** Structured embedding facts and cause accepted by {@link EmbeddingError}. */\nexport interface EmbeddingErrorOptions extends ErrorOptions {\n /**\n * Zero-based indexes of the request items this failure belongs to.\n *\n * Present only when the fault is attributable to specific inputs, which is\n * what lets a caller drop or re-chunk those items instead of the whole call.\n */\n itemIndexes?: readonly number[]\n /** The limit that was applied, when the failure is a limit violation. */\n limit?: number\n /** Provider id of the route that produced the failure. */\n provider?: string\n /** Model id of the route that produced the failure. */\n model?: string\n /** The embedding space involved, when the failure concerns space compatibility. */\n space?: EmbeddingSpaceId\n}\n\n/**\n * Typed error for embedding failures, carrying a stable `code` plus the facts a\n * caller needs to act without re-deriving them.\n *\n * The constructor validates rather than trusts: `itemIndexes` must be\n * non-negative integers and `limit` a positive finite number. A negative index\n * or a `limit` of `-1` means a caller upstream miscomputed a bound, and letting\n * it through would surface a nonsense limit in a message that reads as\n * authoritative. Indexes are copied and frozen so the array cannot be mutated\n * after the error is thrown.\n *\n * No field carries raw input text or vector values: redaction rules keep those\n * out of errors and traces alike.\n */\nexport class EmbeddingError extends AgentSdkError {\n /** Request item indexes this failure belongs to, when input-specific. */\n readonly itemIndexes?: readonly number[]\n /** The applied limit, when the failure is a limit violation. */\n readonly limit?: number\n /** Provider id of the failing route. */\n readonly provider?: string\n /** Model id of the failing route. */\n readonly model?: string\n /** The embedding space involved in the failure. */\n readonly space?: EmbeddingSpaceId\n\n /**\n * @param message - non-empty human-readable failure summary, free of credentials and raw input.\n * @param code - non-empty stable machine code, normally from {@link EMBEDDING_ERROR_CODES}.\n * @param options - optional cause and validated embedding facts.\n */\n constructor(message: string, code: string, options?: EmbeddingErrorOptions) {\n if (typeof message !== 'string' || message.length === 0) {\n throw new Error('EmbeddingError message must be a non-empty string')\n }\n if (typeof code !== 'string' || code.length === 0) {\n throw new Error('EmbeddingError code must be a non-empty string')\n }\n if (options?.itemIndexes !== undefined\n && (!Array.isArray(options.itemIndexes)\n || options.itemIndexes.some(index => !Number.isInteger(index) || index < 0))) {\n throw new Error('EmbeddingError itemIndexes must be an array of non-negative integers')\n }\n if (options?.limit !== undefined\n && (!Number.isFinite(options.limit) || options.limit <= 0)) {\n throw new Error('EmbeddingError limit must be a positive finite number')\n }\n if (options?.provider !== undefined\n && (typeof options.provider !== 'string' || options.provider.length === 0)) {\n throw new Error('EmbeddingError provider must be a non-empty string')\n }\n if (options?.model !== undefined\n && (typeof options.model !== 'string' || options.model.length === 0)) {\n throw new Error('EmbeddingError model must be a non-empty string')\n }\n if (options?.space !== undefined\n && (typeof options.space !== 'string' || options.space.length === 0)) {\n throw new Error('EmbeddingError space must be a non-empty string')\n }\n super(message, code, options)\n this.name = 'EmbeddingError'\n if (options?.itemIndexes !== undefined) {\n this.itemIndexes = Object.freeze([...options.itemIndexes])\n }\n if (options?.limit !== undefined) this.limit = options.limit\n if (options?.provider !== undefined) this.provider = options.provider\n if (options?.model !== undefined) this.model = options.model\n if (options?.space !== undefined) this.space = options.space\n }\n}\n"],"mappings":"6DA2BA,MAAa,EAAwB,OAAO,OAAO,CAEjD,gBAAiB,4BAEjB,gBAAiB,4BAEjB,uBAAwB,mCAExB,gBAAiB,4BAEjB,mBAAoB,+BAEpB,oBAAqB,gCAErB,uBAAwB,mCAExB,sBAAuB,kCAEvB,qBAAsB,iCAEtB,qBAAsB,iCAEtB,2BAA4B,uCAE5B,mBAAoB,+BAEpB,QAAS,oBAET,sBAAuB,kCAEvB,QAAS,mBACX,CAAU,EAsCV,IAAa,EAAb,cAAoC,CAAc,CAEhD,YAEA,MAEA,SAEA,MAEA,MAOA,YAAY,EAAiB,EAAc,EAAiC,CAC1E,GAAI,OAAO,GAAY,UAAY,EAAQ,SAAW,EACpD,MAAU,MAAM,mDAAmD,EAErE,GAAI,OAAO,GAAS,UAAY,EAAK,SAAW,EAC9C,MAAU,MAAM,gDAAgD,EAElE,GAAI,GAAS,cAAgB,IAAA,KACvB,CAAC,MAAM,QAAQ,EAAQ,WAAW,GACjC,EAAQ,YAAY,KAAK,GAAS,CAAC,OAAO,UAAU,CAAK,GAAK,EAAQ,CAAC,GAC5E,MAAU,MAAM,sEAAsE,EAExF,GAAI,GAAS,QAAU,IAAA,KACjB,CAAC,OAAO,SAAS,EAAQ,KAAK,GAAK,EAAQ,OAAS,GACxD,MAAU,MAAM,uDAAuD,EAEzE,GAAI,GAAS,WAAa,IAAA,KACpB,OAAO,EAAQ,UAAa,UAAY,EAAQ,SAAS,SAAW,GACxE,MAAU,MAAM,oDAAoD,EAEtE,GAAI,GAAS,QAAU,IAAA,KACjB,OAAO,EAAQ,OAAU,UAAY,EAAQ,MAAM,SAAW,GAClE,MAAU,MAAM,iDAAiD,EAEnE,GAAI,GAAS,QAAU,IAAA,KACjB,OAAO,EAAQ,OAAU,UAAY,EAAQ,MAAM,SAAW,GAClE,MAAU,MAAM,iDAAiD,EAEnE,MAAM,EAAS,EAAM,CAAO,EAC5B,KAAK,KAAO,iBACR,GAAS,cAAgB,IAAA,KAC3B,KAAK,YAAc,OAAO,OAAO,CAAC,GAAG,EAAQ,WAAW,CAAC,GAEvD,GAAS,QAAU,IAAA,KAAW,KAAK,MAAQ,EAAQ,OACnD,GAAS,WAAa,IAAA,KAAW,KAAK,SAAW,EAAQ,UACzD,GAAS,QAAU,IAAA,KAAW,KAAK,MAAQ,EAAQ,OACnD,GAAS,QAAU,IAAA,KAAW,KAAK,MAAQ,EAAQ,MACzD,CACF"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../../src/embedding/errors.ts"],"sourcesContent":["/**\n * The stable embedding failure taxonomy, and the error the embedding layers throw.\n *\n * Codes here are owned by two layers only: `Embedding_Runtime` before dispatch\n * (dimensions, limits, space, configuration) and `Embedding_Adapter` when it\n * validates a response (vector count, index, values, width). Transport-level\n * faults keep using `MODEL_ERROR_CODES`, so a caller can tell \"the provider is\n * rate limiting us\" apart from \"the provider returned a vector of the wrong\n * width\" without parsing any message.\n *\n * Both provider adapters emit the SAME codes for mapping, dimensions and vector\n * faults. That is what lets one contract-test suite run against both.\n *\n * @module ai-agent-sdk/core/embedding/errors\n */\n\nimport { AgentSdkError } from '../errors/agent-sdk-error.ts'\nimport { ModelError, type ModelErrorOptions } from '../errors/model-error.ts'\nimport type { ModelFailure } from '../errors/failure.ts'\nimport type { EmbeddingSpaceId } from './profile.ts'\n\n/**\n * Codes produced by the embedding contract and runtime.\n *\n * A frozen object rather than a TS enum, matching `MODEL_ERROR_CODES`, so a\n * third-party embedding adapter can emit its own code without this union having\n * to know about it. Values are prefixed `EMBEDDING_` because they travel beside\n * generation codes in the same failure envelopes.\n */\nexport const EMBEDDING_ERROR_CODES = Object.freeze({\n /** No `Embedding_Adapter` is registered for the requested route/model. */\n ADAPTER_MISSING: 'EMBEDDING_ADAPTER_MISSING',\n /** Malformed at the SDK boundary: missing purpose, empty values, empty item. */\n REQUEST_INVALID: 'EMBEDDING_REQUEST_INVALID',\n /** `dimensions` is not among the widths the route declares support for. */\n DIMENSIONS_UNSUPPORTED: 'EMBEDDING_DIMENSIONS_UNSUPPORTED',\n /** Input exceeds the declared max input tokens; carries `itemIndexes` and `limit`. */\n INPUT_TOO_LARGE: 'EMBEDDING_INPUT_TOO_LARGE',\n /** The expected `Space_Id` is incompatible with the `Prepared_Embedding_Call`. */\n SPACE_INCOMPATIBLE: 'EMBEDDING_SPACE_INCOMPATIBLE',\n /** The route has no way to express this purpose and the caller demands the distinction. */\n PURPOSE_UNSUPPORTED: 'EMBEDDING_PURPOSE_UNSUPPORTED',\n /** The caller asked for truncation but the provider has no equivalent parameter. */\n TRUNCATION_UNSUPPORTED: 'EMBEDDING_TRUNCATION_UNSUPPORTED',\n /** The response carried a different number of vectors than inputs sent. */\n VECTOR_COUNT_MISMATCH: 'EMBEDDING_VECTOR_COUNT_MISMATCH',\n /** A vector index is duplicated, missing, or out of range. */\n VECTOR_INDEX_INVALID: 'EMBEDDING_VECTOR_INDEX_INVALID',\n /** A vector contains `NaN` or `Infinity`. */\n VECTOR_VALUE_INVALID: 'EMBEDDING_VECTOR_VALUE_INVALID',\n /** A vector's width differs from the requested `dimensions`. */\n VECTOR_DIMENSIONS_MISMATCH: 'EMBEDDING_VECTOR_DIMENSIONS_MISMATCH',\n /** The response does not satisfy the embedding contract structurally. */\n RESPONSE_MALFORMED: 'EMBEDDING_RESPONSE_MALFORMED',\n /** The caller's signal or a runtime close aborted the call. */\n ABORTED: 'EMBEDDING_ABORTED',\n /** Invalid handle configuration: cache enabled without scope, fallback outside the group. */\n CONFIGURATION_INVALID: 'EMBEDDING_CONFIGURATION_INVALID',\n /** Nothing in this taxonomy classified the embedding failure. */\n UNKNOWN: 'EMBEDDING_UNKNOWN',\n} as const)\n\n/** Any value of {@link EMBEDDING_ERROR_CODES}; a foreign adapter may still use its own `string`. */\nexport type EmbeddingErrorCode = typeof EMBEDDING_ERROR_CODES[keyof typeof EMBEDDING_ERROR_CODES]\n\n/** Structured embedding facts and cause accepted by {@link EmbeddingError}. */\nexport interface EmbeddingErrorOptions extends ModelErrorOptions {\n /**\n * Zero-based indexes of the request items this failure belongs to.\n *\n * Present only when the fault is attributable to specific inputs, which is\n * what lets a caller drop or re-chunk those items instead of the whole call.\n */\n itemIndexes?: readonly number[]\n /** The limit that was applied, when the failure is a limit violation. */\n limit?: number\n /** Provider id of the route that produced the failure. */\n provider?: string\n /** Model id of the route that produced the failure. */\n model?: string\n /** The embedding space involved, when the failure concerns space compatibility. */\n space?: EmbeddingSpaceId\n}\n\n/**\n * Typed error for embedding failures, carrying a stable `code` plus the facts a\n * caller needs to act without re-deriving them.\n *\n * The constructor validates rather than trusts: `itemIndexes` must be\n * non-negative integers and `limit` a positive finite number. A negative index\n * or a `limit` of `-1` means a caller upstream miscomputed a bound, and letting\n * it through would surface a nonsense limit in a message that reads as\n * authoritative. Indexes are copied and frozen so the array cannot be mutated\n * after the error is thrown.\n *\n * No field carries raw input text or vector values: redaction rules keep those\n * out of errors and traces alike.\n */\nexport class EmbeddingError extends AgentSdkError {\n /** Validated provider facts survive the embedding wrapper and normalization. */\n readonly failure: ModelFailure\n /** Request item indexes this failure belongs to, when input-specific. */\n readonly itemIndexes?: readonly number[]\n /** The applied limit, when the failure is a limit violation. */\n readonly limit?: number\n /** Provider id of the failing route. */\n readonly provider?: string\n /** Model id of the failing route. */\n readonly model?: string\n /** The embedding space involved in the failure. */\n readonly space?: EmbeddingSpaceId\n\n /**\n * @param message - non-empty human-readable failure summary, free of credentials and raw input.\n * @param code - non-empty stable machine code, normally from {@link EMBEDDING_ERROR_CODES}.\n * @param options - optional cause and validated embedding facts.\n */\n constructor(message: string, code: string, options?: EmbeddingErrorOptions) {\n if (typeof message !== 'string' || message.length === 0) {\n throw new Error('EmbeddingError message must be a non-empty string')\n }\n if (typeof code !== 'string' || code.length === 0) {\n throw new Error('EmbeddingError code must be a non-empty string')\n }\n if (options?.itemIndexes !== undefined\n && (!Array.isArray(options.itemIndexes)\n || options.itemIndexes.some(index => !Number.isInteger(index) || index < 0))) {\n throw new Error('EmbeddingError itemIndexes must be an array of non-negative integers')\n }\n if (options?.limit !== undefined\n && (!Number.isFinite(options.limit) || options.limit <= 0)) {\n throw new Error('EmbeddingError limit must be a positive finite number')\n }\n if (options?.provider !== undefined\n && (typeof options.provider !== 'string' || options.provider.length === 0)) {\n throw new Error('EmbeddingError provider must be a non-empty string')\n }\n if (options?.model !== undefined\n && (typeof options.model !== 'string' || options.model.length === 0)) {\n throw new Error('EmbeddingError model must be a non-empty string')\n }\n if (options?.space !== undefined\n && (typeof options.space !== 'string' || options.space.length === 0)) {\n throw new Error('EmbeddingError space must be a non-empty string')\n }\n const failure = new ModelError(message, code, options).failure\n super(message, code, options)\n this.name = 'EmbeddingError'\n this.failure = failure\n if (options?.itemIndexes !== undefined) {\n this.itemIndexes = Object.freeze([...options.itemIndexes])\n }\n if (options?.limit !== undefined) this.limit = options.limit\n if (options?.provider !== undefined) this.provider = options.provider\n if (options?.model !== undefined) this.model = options.model\n if (options?.space !== undefined) this.space = options.space\n }\n}\n"],"mappings":"mHA6BA,MAAa,EAAwB,OAAO,OAAO,CAEjD,gBAAiB,4BAEjB,gBAAiB,4BAEjB,uBAAwB,mCAExB,gBAAiB,4BAEjB,mBAAoB,+BAEpB,oBAAqB,gCAErB,uBAAwB,mCAExB,sBAAuB,kCAEvB,qBAAsB,iCAEtB,qBAAsB,iCAEtB,2BAA4B,uCAE5B,mBAAoB,+BAEpB,QAAS,oBAET,sBAAuB,kCAEvB,QAAS,mBACX,CAAU,EAsCV,IAAa,EAAb,cAAoC,CAAc,CAEhD,QAEA,YAEA,MAEA,SAEA,MAEA,MAOA,YAAY,EAAiB,EAAc,EAAiC,CAC1E,GAAI,OAAO,GAAY,UAAY,EAAQ,SAAW,EACpD,MAAU,MAAM,mDAAmD,EAErE,GAAI,OAAO,GAAS,UAAY,EAAK,SAAW,EAC9C,MAAU,MAAM,gDAAgD,EAElE,GAAI,GAAS,cAAgB,IAAA,KACvB,CAAC,MAAM,QAAQ,EAAQ,WAAW,GACjC,EAAQ,YAAY,KAAK,GAAS,CAAC,OAAO,UAAU,CAAK,GAAK,EAAQ,CAAC,GAC5E,MAAU,MAAM,sEAAsE,EAExF,GAAI,GAAS,QAAU,IAAA,KACjB,CAAC,OAAO,SAAS,EAAQ,KAAK,GAAK,EAAQ,OAAS,GACxD,MAAU,MAAM,uDAAuD,EAEzE,GAAI,GAAS,WAAa,IAAA,KACpB,OAAO,EAAQ,UAAa,UAAY,EAAQ,SAAS,SAAW,GACxE,MAAU,MAAM,oDAAoD,EAEtE,GAAI,GAAS,QAAU,IAAA,KACjB,OAAO,EAAQ,OAAU,UAAY,EAAQ,MAAM,SAAW,GAClE,MAAU,MAAM,iDAAiD,EAEnE,GAAI,GAAS,QAAU,IAAA,KACjB,OAAO,EAAQ,OAAU,UAAY,EAAQ,MAAM,SAAW,GAClE,MAAU,MAAM,iDAAiD,EAEnE,IAAM,EAAU,IAAI,EAAW,EAAS,EAAM,CAAO,CAAC,CAAC,QACvD,MAAM,EAAS,EAAM,CAAO,EAC5B,KAAK,KAAO,iBACZ,KAAK,QAAU,EACX,GAAS,cAAgB,IAAA,KAC3B,KAAK,YAAc,OAAO,OAAO,CAAC,GAAG,EAAQ,WAAW,CAAC,GAEvD,GAAS,QAAU,IAAA,KAAW,KAAK,MAAQ,EAAQ,OACnD,GAAS,WAAa,IAAA,KAAW,KAAK,SAAW,EAAQ,UACzD,GAAS,QAAU,IAAA,KAAW,KAAK,MAAQ,EAAQ,OACnD,GAAS,QAAU,IAAA,KAAW,KAAK,MAAQ,EAAQ,MACzD,CACF"}
package/dist/index.d.ts CHANGED
@@ -69,6 +69,7 @@ import { APP_IDENTITY, AppIdentity, attributionHeaders, userAgent } from "./http
69
69
  import { MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION } from "./composition/memory/config.js";
70
70
  import { defineMemoryStore } from "./composition/memory/definition.js";
71
71
  import { defineSkillProviderPlugin } from "./agent/skill/provider/definition.js";
72
+ import { PublicRuntimeAgentRunEvent, withoutRunReport } from "./composition/agent/public-event.js";
72
73
  import { defineObservationExporter } from "./composition/exporter/definition.js";
73
74
  import { CONTEXT_SECTION_ID_PATTERN, CONTEXT_SECTION_INVALID, MAX_CONTEXT_SECTION_TEXT_BYTES, defineContextSection } from "./agent/context/section.js";
74
- export { type A2AMessageSource, APP_IDENTITY, type ActivatedSkillSnapshot, type AdapterRegistrationHandle, type AgentCompactionConfig, type AgentCompactionOptions, type AgentDefinition, type AgentDefinitionInput, type AgentDefinitionOverrides, type AgentInput, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, type AgentMessageSource, type AgentRuntime, type AgentRuntimeOptions, AgentSdkError, type AgentSkillOptions, type AgentTeamMemberInput, type AlwaysRetryPolicyConfig, type ApiKeyCheck, type ApiKeyRejection, type AppIdentity, type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AssistantMessage, type AssistantProvenance, type AssistantTextPhase, type AttemptUsageReport, type BackoffConfig, BlockAssembler, type Branded, COMPACTION_INSTRUCTION, CONTEXT_SECTION_ID_PATTERN, CONTEXT_SECTION_INVALID, CONTEXT_WINDOW_EXCEEDED_CODE, type CallConfig, type CallConfigAdapterDefaults, type CapabilityIdentityConflict, type CaptureReceipt, type CloneAgentOverrides, type CompactionResult, type ContentBlock, type ContentBlockMap, type ContentBlockType, ContextCompactor, type ContextCompactorOptions, type ContextMilestone, type ContextOptimizationMetrics, type ContextOptimizerOptions, type ContextSection, type ContextSectionResolveInput, type ContextSectionScope, type ContextSectionState, type ContextToolTouch, type CorrelationContext, type DefinedAgent, type DeliveryMode, type DiagnosticSnapshot, type DispatchState, type DocumentBlock, type DocumentMediaType, type DocumentSource, EMPTY_RESPONSE_CODE, type EmbeddingManyResult, type EmbeddingModelHandle, type EmbeddingModelOptions, type EmbeddingResult, type EmbeddingUsageReport, type EndProviderAttemptInput, type FinishReason, type FinishReasonMap, type GenerateOptions, INVALID_CREDENTIAL_CODE, type ImageBlock, type ImageDetail, type ImageMediaType, type ImageSource, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type InteractiveUserInputBroker, type InteractiveUserInputBrokerOptions, type JsonObject, type JsonSchemaOutputFormat, type JsonValue, type LogLevel, MAX_CONTEXT_SECTION_TEXT_BYTES, MAX_SKILL_DESCRIPTION_CHARS, MAX_SKILL_ID_CHARS, MAX_SKILL_INSTRUCTIONS_CHARS, MAX_SKILL_NAME_CHARS, MAX_SKILL_RESOURCE_CHARS, MAX_SKILL_RESOURCE_PATH_CHARS, MAX_TIMER_DELAY_MS, MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION, MISSING_CREDENTIAL_CODE, MODEL_ERROR_CODES, type MemoryBinding, type MemoryCommitInput, type MemoryCommitResult, type MemoryLoadResult, type MemoryScope, type MemoryStore, type MemoryStoreDefinition, type MemoryStoreOptions, type Message, MessageId, type MessageSource, type MessageSourceMap, ModelAdapter, type ModelCallHandle, ModelCallObservationError, type ModelCallReport, type ModelCatalogOptions, type ModelCatalogSnapshot, type ModelCatalogState, type ModelContext, ModelError, type ModelErrorOptions, type ModelFailure, type ModelInfo, type ModelInvocationContext, type ModelMessageSource, type ModelModality, type ModelModalityMap, type ModelOutputFormat, type ModelProviderPlugin, type ModelProviderRegistrar, type ModelReasoningInfo, ModelRegistry, type ModelRegistryOptions, type ModelToolSchema, NOOP_OBSERVATION_PORT, type NativeImageGenerationTool, type NativeToolCallBlock, type NativeToolName, type NativeToolSchema, type NativeToolSchemaMap, type NativeWebSearchTool, type NormalRetryPolicyConfig, OBSERVATION_ERROR_CODES, OBSERVATION_EXPORTER_API_VERSION, type ObservationBoundary, type ObservationDeliveryAck, type ObservationDeliveryBatch, type ObservationDeliverySummary, type ObservationEvent, type ObservationEventName, type ObservationExportItem, type ObservationExporterPlugin, type ObservationExporterPluginDefinition, type ObservationPhase, type ObservationPort, type ObservationPriority, type ObservationResource, type ObservationResourceInput, type ObservationRunScope, type ObservationSpan, type ObservationSpanName, type OpenObservationSpanInput, type OperationStatus, PLUGIN_ERROR_CODES, PluginError, type PluginRegistrationHandle, type PreparedAdapterCall, type PreparedCall, type ProviderAttemptHandle, type ProviderInfo, ProviderRequestId, type ProviderRetryScheduledInput, QUOTA_EXCEEDED_CODE, REGISTRY_ERROR_CODES, type ReasoningBlock, ReasoningEffortId, type ReasoningEffortInfo, type ReplayEnvelope, type ResolvedAgentSkillOptions, type ResolvedAlwaysRetryPolicy, type ResolvedModelInfo, type ResolvedNormalRetryPolicy, type ResolvedRetryBackoff, type ResolvedRetryPolicy, type RetryAttempt, type RetryPolicyConfig, type RunReport, type RunTerminalRecord, type RuntimeAgent, type RuntimeAgentBindingInput, type RuntimeAgentDefinition, type RuntimeAgentDefinitionInput, type RuntimeAgentInvocationOptions, type RuntimeAgentLimits, type RuntimeAgentResponse, type RuntimeAgentRunEvent, type RuntimeAgentRunEventContext, type RuntimeAgentRunHandle, type RuntimeAgentSession, type RuntimeAgentSessionOptions, type RuntimeAgentSessionSnapshot, type RuntimeAgentTeam, type RuntimeAgentTeamEvent, type RuntimeAgentTeamOptions, type RuntimeCloseReport, type RuntimeDefaults, type RuntimeModelCatalogSnapshot, type RuntimeObservationExporterRegistration, type RuntimeObservationResourceInput, type RuntimeOwnerObservabilityOptions, type RuntimeProviderInfo, type RuntimeSchema, type RuntimeSkillCandidate, type RuntimeSkillLookupOptions, type RuntimeSkillSource, SDK_VERSION, SKILL_ERROR_CODES, SKILL_ID_PATTERN, SKILL_PROVIDER_API_VERSION, SKILL_TOOL_NAMES, type SafeErrorRecord, type SdkLogger, type SkillCandidate, SkillCatalog, type SkillCatalogOptions, type SkillCatalogSnapshot, type SkillDefinition, type SkillDefinitionInput, type SkillInvocationPolicy, type SkillLookupOptions, type SkillProvider, type SkillProviderDefinition, type SkillProviderListOptions, type SkillProviderPlugin, type SkillProviderPluginDefinition, type SkillReference, type SkillResourceBase, type SkillResourceSummary, type SkillSource, type SkillSummary, type SpanId, type StartProviderAttemptInput, type StreamChunk, type StreamMiddleware, type SupportSafeError, type TextAnnotation, type TextAnnotationMap, type TextBlock, type TextOutputFormat, type TokenUsage, type ToolCallBlock, ToolCallId, type ToolChoice, type ToolDefinition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionRequest, type ToolExecutionStore, type ToolMessageSource, type ToolOperation, type ToolOperationClaim, type ToolResultBlock, type ToolResultMessage, type ToolResultMessageInput, type ToolRunContext, type ToolSchema, type TraceId, type UrlCitationAnnotation, type UsageAdditionResult, type UsageCounters, type UsageCoverage, type UsageValidationResult, type UserInputAnswer, type UserInputBroker, type UserInputDecision, type UserInputOption, type UserInputQuestion, type UserInputRequest, type UserInputResponse, type UserMessage, type WebSearchLocation, type WithRetryOptions, addUsageCounters, assertNever, assertUsableApiKey, attributionHeaders, backoffDelayMs, callConfigEquals, classifyUsageCoverage, cloneAgent, contentHasDocument, contentHasImage, createAgentRuntime, createApprovalBroker, createApprovalRequest, createAssistantMessage, createContextOptimizer, createCoreSpan, createMessage, createObservationRunScope, createOperationId, createSkillTools, createSpanId, createTextMessage, createToolExecutionInterceptor, createToolResultMessage, createTraceId, createUserInputBroker, createUserMessage, deepFreeze, defineAgent, defineContextSection, defineMemoryStore, defineObservationExporter, defineSkill, defineSkillProvider, defineSkillProviderPlugin, defineTool, defineToolFromSchema, detachedFrozen, disabledDeliverySummary, errorChain, estimateContextTokens, estimateMessageTokens, fixedApprovalBroker, fixedUserInputBroker, freezeCorrelation, freezeMessage, hasUsageCounters, isAgentSdkError, isContextWindowExceededError, isJsonValue, isNativeToolSchema, isQuotaExceededError, isRetryable, isSpanId, isTraceId, localToolExecutionBackend, normalizeApiKey, normalizeModelFailure, possiblyBilledAttemptsWithoutUsage, projectDocumentsForTextModel, projectImagesForTextModel, renderSkillCatalog, resolveCompactionConfig, resolveMemoryConfig, resolveRetryPolicy, resolveSkillOptions, safeErrorRecord, selectCompactablePrefix, snapshotObservationSpan, textOnlyDocumentText, textOnlyImageText, traceparent, userAgent, validObservationSpan, validateCandidate, validateCaptureReceipt, validateSkillId, validateSkillResourcePath, validateSkillSource, validateUsageCounters, waitForSettlement, withApprovalPersistence, withIdleTimeout, withRetry };
75
+ export { type A2AMessageSource, APP_IDENTITY, type ActivatedSkillSnapshot, type AdapterRegistrationHandle, type AgentCompactionConfig, type AgentCompactionOptions, type AgentDefinition, type AgentDefinitionInput, type AgentDefinitionOverrides, type AgentInput, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, type AgentMessageSource, type AgentRuntime, type AgentRuntimeOptions, AgentSdkError, type AgentSkillOptions, type AgentTeamMemberInput, type AlwaysRetryPolicyConfig, type ApiKeyCheck, type ApiKeyRejection, type AppIdentity, type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AssistantMessage, type AssistantProvenance, type AssistantTextPhase, type AttemptUsageReport, type BackoffConfig, BlockAssembler, type Branded, COMPACTION_INSTRUCTION, CONTEXT_SECTION_ID_PATTERN, CONTEXT_SECTION_INVALID, CONTEXT_WINDOW_EXCEEDED_CODE, type CallConfig, type CallConfigAdapterDefaults, type CapabilityIdentityConflict, type CaptureReceipt, type CloneAgentOverrides, type CompactionResult, type ContentBlock, type ContentBlockMap, type ContentBlockType, ContextCompactor, type ContextCompactorOptions, type ContextMilestone, type ContextOptimizationMetrics, type ContextOptimizerOptions, type ContextSection, type ContextSectionResolveInput, type ContextSectionScope, type ContextSectionState, type ContextToolTouch, type CorrelationContext, type DefinedAgent, type DeliveryMode, type DiagnosticSnapshot, type DispatchState, type DocumentBlock, type DocumentMediaType, type DocumentSource, EMPTY_RESPONSE_CODE, type EmbeddingManyResult, type EmbeddingModelHandle, type EmbeddingModelOptions, type EmbeddingResult, type EmbeddingUsageReport, type EndProviderAttemptInput, type FinishReason, type FinishReasonMap, type GenerateOptions, INVALID_CREDENTIAL_CODE, type ImageBlock, type ImageDetail, type ImageMediaType, type ImageSource, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type InteractiveUserInputBroker, type InteractiveUserInputBrokerOptions, type JsonObject, type JsonSchemaOutputFormat, type JsonValue, type LogLevel, MAX_CONTEXT_SECTION_TEXT_BYTES, MAX_SKILL_DESCRIPTION_CHARS, MAX_SKILL_ID_CHARS, MAX_SKILL_INSTRUCTIONS_CHARS, MAX_SKILL_NAME_CHARS, MAX_SKILL_RESOURCE_CHARS, MAX_SKILL_RESOURCE_PATH_CHARS, MAX_TIMER_DELAY_MS, MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION, MISSING_CREDENTIAL_CODE, MODEL_ERROR_CODES, type MemoryBinding, type MemoryCommitInput, type MemoryCommitResult, type MemoryLoadResult, type MemoryScope, type MemoryStore, type MemoryStoreDefinition, type MemoryStoreOptions, type Message, MessageId, type MessageSource, type MessageSourceMap, ModelAdapter, type ModelCallHandle, ModelCallObservationError, type ModelCallReport, type ModelCatalogOptions, type ModelCatalogSnapshot, type ModelCatalogState, type ModelContext, ModelError, type ModelErrorOptions, type ModelFailure, type ModelInfo, type ModelInvocationContext, type ModelMessageSource, type ModelModality, type ModelModalityMap, type ModelOutputFormat, type ModelProviderPlugin, type ModelProviderRegistrar, type ModelReasoningInfo, ModelRegistry, type ModelRegistryOptions, type ModelToolSchema, NOOP_OBSERVATION_PORT, type NativeImageGenerationTool, type NativeToolCallBlock, type NativeToolName, type NativeToolSchema, type NativeToolSchemaMap, type NativeWebSearchTool, type NormalRetryPolicyConfig, OBSERVATION_ERROR_CODES, OBSERVATION_EXPORTER_API_VERSION, type ObservationBoundary, type ObservationDeliveryAck, type ObservationDeliveryBatch, type ObservationDeliverySummary, type ObservationEvent, type ObservationEventName, type ObservationExportItem, type ObservationExporterPlugin, type ObservationExporterPluginDefinition, type ObservationPhase, type ObservationPort, type ObservationPriority, type ObservationResource, type ObservationResourceInput, type ObservationRunScope, type ObservationSpan, type ObservationSpanName, type OpenObservationSpanInput, type OperationStatus, PLUGIN_ERROR_CODES, PluginError, type PluginRegistrationHandle, type PreparedAdapterCall, type PreparedCall, type ProviderAttemptHandle, type ProviderInfo, ProviderRequestId, type ProviderRetryScheduledInput, type PublicRuntimeAgentRunEvent, QUOTA_EXCEEDED_CODE, REGISTRY_ERROR_CODES, type ReasoningBlock, ReasoningEffortId, type ReasoningEffortInfo, type ReplayEnvelope, type ResolvedAgentSkillOptions, type ResolvedAlwaysRetryPolicy, type ResolvedModelInfo, type ResolvedNormalRetryPolicy, type ResolvedRetryBackoff, type ResolvedRetryPolicy, type RetryAttempt, type RetryPolicyConfig, type RunReport, type RunTerminalRecord, type RuntimeAgent, type RuntimeAgentBindingInput, type RuntimeAgentDefinition, type RuntimeAgentDefinitionInput, type RuntimeAgentInvocationOptions, type RuntimeAgentLimits, type RuntimeAgentResponse, type RuntimeAgentRunEvent, type RuntimeAgentRunEventContext, type RuntimeAgentRunHandle, type RuntimeAgentSession, type RuntimeAgentSessionOptions, type RuntimeAgentSessionSnapshot, type RuntimeAgentTeam, type RuntimeAgentTeamEvent, type RuntimeAgentTeamOptions, type RuntimeCloseReport, type RuntimeDefaults, type RuntimeModelCatalogSnapshot, type RuntimeObservationExporterRegistration, type RuntimeObservationResourceInput, type RuntimeOwnerObservabilityOptions, type RuntimeProviderInfo, type RuntimeSchema, type RuntimeSkillCandidate, type RuntimeSkillLookupOptions, type RuntimeSkillSource, SDK_VERSION, SKILL_ERROR_CODES, SKILL_ID_PATTERN, SKILL_PROVIDER_API_VERSION, SKILL_TOOL_NAMES, type SafeErrorRecord, type SdkLogger, type SkillCandidate, SkillCatalog, type SkillCatalogOptions, type SkillCatalogSnapshot, type SkillDefinition, type SkillDefinitionInput, type SkillInvocationPolicy, type SkillLookupOptions, type SkillProvider, type SkillProviderDefinition, type SkillProviderListOptions, type SkillProviderPlugin, type SkillProviderPluginDefinition, type SkillReference, type SkillResourceBase, type SkillResourceSummary, type SkillSource, type SkillSummary, type SpanId, type StartProviderAttemptInput, type StreamChunk, type StreamMiddleware, type SupportSafeError, type TextAnnotation, type TextAnnotationMap, type TextBlock, type TextOutputFormat, type TokenUsage, type ToolCallBlock, ToolCallId, type ToolChoice, type ToolDefinition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionRequest, type ToolExecutionStore, type ToolMessageSource, type ToolOperation, type ToolOperationClaim, type ToolResultBlock, type ToolResultMessage, type ToolResultMessageInput, type ToolRunContext, type ToolSchema, type TraceId, type UrlCitationAnnotation, type UsageAdditionResult, type UsageCounters, type UsageCoverage, type UsageValidationResult, type UserInputAnswer, type UserInputBroker, type UserInputDecision, type UserInputOption, type UserInputQuestion, type UserInputRequest, type UserInputResponse, type UserMessage, type WebSearchLocation, type WithRetryOptions, addUsageCounters, assertNever, assertUsableApiKey, attributionHeaders, backoffDelayMs, callConfigEquals, classifyUsageCoverage, cloneAgent, contentHasDocument, contentHasImage, createAgentRuntime, createApprovalBroker, createApprovalRequest, createAssistantMessage, createContextOptimizer, createCoreSpan, createMessage, createObservationRunScope, createOperationId, createSkillTools, createSpanId, createTextMessage, createToolExecutionInterceptor, createToolResultMessage, createTraceId, createUserInputBroker, createUserMessage, deepFreeze, defineAgent, defineContextSection, defineMemoryStore, defineObservationExporter, defineSkill, defineSkillProvider, defineSkillProviderPlugin, defineTool, defineToolFromSchema, detachedFrozen, disabledDeliverySummary, errorChain, estimateContextTokens, estimateMessageTokens, fixedApprovalBroker, fixedUserInputBroker, freezeCorrelation, freezeMessage, hasUsageCounters, isAgentSdkError, isContextWindowExceededError, isJsonValue, isNativeToolSchema, isQuotaExceededError, isRetryable, isSpanId, isTraceId, localToolExecutionBackend, normalizeApiKey, normalizeModelFailure, possiblyBilledAttemptsWithoutUsage, projectDocumentsForTextModel, projectImagesForTextModel, renderSkillCatalog, resolveCompactionConfig, resolveMemoryConfig, resolveRetryPolicy, resolveSkillOptions, safeErrorRecord, selectCompactablePrefix, snapshotObservationSpan, textOnlyDocumentText, textOnlyImageText, traceparent, userAgent, validObservationSpan, validateCandidate, validateCaptureReceipt, validateSkillId, validateSkillResourcePath, validateSkillSource, validateUsageCounters, waitForSettlement, withApprovalPersistence, withIdleTimeout, withRetry, withoutRunReport };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{MessageId as e,ProviderRequestId as t,ReasoningEffortId as n,ToolCallId as r}from"./primitives/brand.js";import{deepFreeze as i}from"./primitives/freeze.js";import{isJsonValue as a}from"./primitives/json.js";import{assertNever as o}from"./primitives/never.js";import{detachedFrozen as s}from"./primitives/snapshot.js";import{SDK_VERSION as c}from"./primitives/version.js";import{waitForSettlement as l}from"./async/settlement.js";import{createObservationRunScope as u,createOperationId as d,createSpanId as f,createTraceId as p,freezeCorrelation as m,isSpanId as h,isTraceId as g,traceparent as _}from"./observation/context.js";import{safeErrorRecord as v}from"./observation/event.js";import{NOOP_OBSERVATION_PORT as y,createCoreSpan as b,disabledDeliverySummary as x,snapshotObservationSpan as S,validObservationSpan as C,validateCaptureReceipt as w}from"./observation/port.js";import{AgentSdkError as T,CONTEXT_WINDOW_EXCEEDED_CODE as E,EMPTY_RESPONSE_CODE as D,INVALID_CREDENTIAL_CODE as O,MISSING_CREDENTIAL_CODE as k,QUOTA_EXCEEDED_CODE as A,errorChain as j,isAgentSdkError as M,isContextWindowExceededError as N,isQuotaExceededError as P}from"./errors/agent-sdk-error.js";import{ModelCallObservationError as F,OBSERVATION_ERROR_CODES as I}from"./observation/report.js";import{addUsageCounters as L,classifyUsageCoverage as R,hasUsageCounters as z,possiblyBilledAttemptsWithoutUsage as B,validateUsageCounters as V}from"./observation/usage.js";import{PLUGIN_ERROR_CODES as H,PluginError as U}from"./plugin/provider-plugin.js";import{MODEL_ERROR_CODES as W,ModelError as G,REGISTRY_ERROR_CODES as K}from"./errors/model-error.js";import{normalizeModelFailure as q}from"./errors/failure.js";import{createAssistantMessage as J,createMessage as Y,createTextMessage as X,createToolResultMessage as Z,createUserMessage as Q,freezeMessage as $}from"./message/message.js";import{contentHasDocument as ee,contentHasImage as te,projectDocumentsForTextModel as ne,projectImagesForTextModel as re,textOnlyDocumentText as ie,textOnlyImageText as ae}from"./message/projection.js";import{BlockAssembler as oe}from"./stream/assembler.js";import{withIdleTimeout as se}from"./stream/idle-timeout.js";import{ModelAdapter as ce}from"./contract/adapter.js";import{callConfigEquals as le}from"./contract/call-config.js";import{MAX_TIMER_DELAY_MS as ue,backoffDelayMs as de,isRetryable as fe,resolveRetryPolicy as pe}from"./contract/retry-policy.js";import{isNativeToolSchema as me}from"./contract/tool.js";import{ModelRegistry as he}from"./runtime/registry.js";import{withRetry as ge}from"./runtime/with-retry.js";import{assertUsableApiKey as _e,normalizeApiKey as ve}from"./http/api-key.js";import{APP_IDENTITY as ye,attributionHeaders as be,userAgent as xe}from"./http/attribution.js";import{AgentMemory as Se,resolveMemoryConfig as Ce}from"./agent/memory/memory.js";import{estimateContextTokens as we,estimateMessageTokens as Te}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as Ee}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as De,ContextCompactor as Oe}from"./agent/memory/compaction.js";import{resolveCompactionConfig as ke}from"./agent/memory/compaction-config.js";import{defineTool as Ae}from"./agent/tool/definition.js";import{createContextOptimizer as je}from"./agent/memory/context-optimizer.js";import{MEMORY_ERROR_CODES as Me,MEMORY_STORE_API_VERSION as Ne}from"./composition/memory/config.js";import{defineMemoryStore as Pe}from"./composition/memory/definition.js";import{MAX_SKILL_DESCRIPTION_CHARS as Fe,MAX_SKILL_ID_CHARS as Ie,MAX_SKILL_INSTRUCTIONS_CHARS as Le,MAX_SKILL_NAME_CHARS as Re,MAX_SKILL_RESOURCE_CHARS as ze,MAX_SKILL_RESOURCE_PATH_CHARS as Be,SKILL_ID_PATTERN as Ve,defineSkill as He,defineSkillProvider as Ue,validateCandidate as We,validateSkillId as Ge,validateSkillResourcePath as Ke,validateSkillSource as qe}from"./agent/skill/definition.js";import{SKILL_ERROR_CODES as Je,SKILL_PROVIDER_API_VERSION as Ye}from"./agent/skill/provider/config.js";import{defineSkillProviderPlugin as Xe}from"./agent/skill/provider/definition.js";import{SkillCatalog as Ze}from"./agent/skill/catalog.js";import{SKILL_TOOL_NAMES as Qe,createSkillTools as $e,renderSkillCatalog as et,resolveSkillOptions as tt}from"./agent/skill/tools.js";import{OBSERVATION_EXPORTER_API_VERSION as nt}from"./composition/exporter/types.js";import{CONTEXT_SECTION_ID_PATTERN as rt,CONTEXT_SECTION_INVALID as it,MAX_CONTEXT_SECTION_TEXT_BYTES as at,defineContextSection as ot}from"./agent/context/section.js";import{createApprovalBroker as st,createApprovalRequest as ct,fixedApprovalBroker as lt,withApprovalPersistence as ut}from"./agent/tool/approval.js";import{createAgentRuntime as dt}from"./composition/runtime/public.js";import{cloneAgent as ft,defineAgent as pt}from"./composition/agent/author.js";import{defineObservationExporter as mt}from"./composition/exporter/definition.js";import{createUserInputBroker as ht,fixedUserInputBroker as gt}from"./agent/mode/user-input.js";import{defineToolFromSchema as _t}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as vt,localToolExecutionBackend as yt}from"./agent/tool/execution.js";export{ye as APP_IDENTITY,Se as AgentMemory,T as AgentSdkError,oe as BlockAssembler,De as COMPACTION_INSTRUCTION,rt as CONTEXT_SECTION_ID_PATTERN,it as CONTEXT_SECTION_INVALID,E as CONTEXT_WINDOW_EXCEEDED_CODE,Oe as ContextCompactor,D as EMPTY_RESPONSE_CODE,O as INVALID_CREDENTIAL_CODE,at as MAX_CONTEXT_SECTION_TEXT_BYTES,Fe as MAX_SKILL_DESCRIPTION_CHARS,Ie as MAX_SKILL_ID_CHARS,Le as MAX_SKILL_INSTRUCTIONS_CHARS,Re as MAX_SKILL_NAME_CHARS,ze as MAX_SKILL_RESOURCE_CHARS,Be as MAX_SKILL_RESOURCE_PATH_CHARS,ue as MAX_TIMER_DELAY_MS,Me as MEMORY_ERROR_CODES,Ne as MEMORY_STORE_API_VERSION,k as MISSING_CREDENTIAL_CODE,W as MODEL_ERROR_CODES,e as MessageId,ce as ModelAdapter,F as ModelCallObservationError,G as ModelError,he as ModelRegistry,y as NOOP_OBSERVATION_PORT,I as OBSERVATION_ERROR_CODES,nt as OBSERVATION_EXPORTER_API_VERSION,H as PLUGIN_ERROR_CODES,U as PluginError,t as ProviderRequestId,A as QUOTA_EXCEEDED_CODE,K as REGISTRY_ERROR_CODES,n as ReasoningEffortId,c as SDK_VERSION,Je as SKILL_ERROR_CODES,Ve as SKILL_ID_PATTERN,Ye as SKILL_PROVIDER_API_VERSION,Qe as SKILL_TOOL_NAMES,Ze as SkillCatalog,r as ToolCallId,L as addUsageCounters,o as assertNever,_e as assertUsableApiKey,be as attributionHeaders,de as backoffDelayMs,le as callConfigEquals,R as classifyUsageCoverage,ft as cloneAgent,ee as contentHasDocument,te as contentHasImage,dt as createAgentRuntime,st as createApprovalBroker,ct as createApprovalRequest,J as createAssistantMessage,je as createContextOptimizer,b as createCoreSpan,Y as createMessage,u as createObservationRunScope,d as createOperationId,$e as createSkillTools,f as createSpanId,X as createTextMessage,vt as createToolExecutionInterceptor,Z as createToolResultMessage,p as createTraceId,ht as createUserInputBroker,Q as createUserMessage,i as deepFreeze,pt as defineAgent,ot as defineContextSection,Pe as defineMemoryStore,mt as defineObservationExporter,He as defineSkill,Ue as defineSkillProvider,Xe as defineSkillProviderPlugin,Ae as defineTool,_t as defineToolFromSchema,s as detachedFrozen,x as disabledDeliverySummary,j as errorChain,we as estimateContextTokens,Te as estimateMessageTokens,lt as fixedApprovalBroker,gt as fixedUserInputBroker,m as freezeCorrelation,$ as freezeMessage,z as hasUsageCounters,M as isAgentSdkError,N as isContextWindowExceededError,a as isJsonValue,me as isNativeToolSchema,P as isQuotaExceededError,fe as isRetryable,h as isSpanId,g as isTraceId,yt as localToolExecutionBackend,ve as normalizeApiKey,q as normalizeModelFailure,B as possiblyBilledAttemptsWithoutUsage,ne as projectDocumentsForTextModel,re as projectImagesForTextModel,et as renderSkillCatalog,ke as resolveCompactionConfig,Ce as resolveMemoryConfig,pe as resolveRetryPolicy,tt as resolveSkillOptions,v as safeErrorRecord,Ee as selectCompactablePrefix,S as snapshotObservationSpan,ie as textOnlyDocumentText,ae as textOnlyImageText,_ as traceparent,xe as userAgent,C as validObservationSpan,We as validateCandidate,w as validateCaptureReceipt,Ge as validateSkillId,Ke as validateSkillResourcePath,qe as validateSkillSource,V as validateUsageCounters,l as waitForSettlement,ut as withApprovalPersistence,se as withIdleTimeout,ge as withRetry};
1
+ import{MessageId as e,ProviderRequestId as t,ReasoningEffortId as n,ToolCallId as r}from"./primitives/brand.js";import{deepFreeze as i}from"./primitives/freeze.js";import{isJsonValue as a}from"./primitives/json.js";import{assertNever as o}from"./primitives/never.js";import{detachedFrozen as s}from"./primitives/snapshot.js";import{SDK_VERSION as c}from"./primitives/version.js";import{waitForSettlement as l}from"./async/settlement.js";import{createObservationRunScope as u,createOperationId as d,createSpanId as f,createTraceId as p,freezeCorrelation as m,isSpanId as h,isTraceId as g,traceparent as _}from"./observation/context.js";import{safeErrorRecord as v}from"./observation/event.js";import{NOOP_OBSERVATION_PORT as y,createCoreSpan as b,disabledDeliverySummary as x,snapshotObservationSpan as S,validObservationSpan as C,validateCaptureReceipt as w}from"./observation/port.js";import{AgentSdkError as T,CONTEXT_WINDOW_EXCEEDED_CODE as E,EMPTY_RESPONSE_CODE as D,INVALID_CREDENTIAL_CODE as O,MISSING_CREDENTIAL_CODE as k,QUOTA_EXCEEDED_CODE as A,errorChain as j,isAgentSdkError as M,isContextWindowExceededError as N,isQuotaExceededError as P}from"./errors/agent-sdk-error.js";import{ModelCallObservationError as F,OBSERVATION_ERROR_CODES as I}from"./observation/report.js";import{addUsageCounters as L,classifyUsageCoverage as R,hasUsageCounters as z,possiblyBilledAttemptsWithoutUsage as B,validateUsageCounters as V}from"./observation/usage.js";import{PLUGIN_ERROR_CODES as H,PluginError as U}from"./plugin/provider-plugin.js";import{MODEL_ERROR_CODES as W,ModelError as G,REGISTRY_ERROR_CODES as K}from"./errors/model-error.js";import{normalizeModelFailure as q}from"./errors/failure.js";import{createAssistantMessage as J,createMessage as Y,createTextMessage as X,createToolResultMessage as Z,createUserMessage as Q,freezeMessage as $}from"./message/message.js";import{contentHasDocument as ee,contentHasImage as te,projectDocumentsForTextModel as ne,projectImagesForTextModel as re,textOnlyDocumentText as ie,textOnlyImageText as ae}from"./message/projection.js";import{BlockAssembler as oe}from"./stream/assembler.js";import{withIdleTimeout as se}from"./stream/idle-timeout.js";import{ModelAdapter as ce}from"./contract/adapter.js";import{callConfigEquals as le}from"./contract/call-config.js";import{MAX_TIMER_DELAY_MS as ue,backoffDelayMs as de,isRetryable as fe,resolveRetryPolicy as pe}from"./contract/retry-policy.js";import{isNativeToolSchema as me}from"./contract/tool.js";import{ModelRegistry as he}from"./runtime/registry.js";import{withRetry as ge}from"./runtime/with-retry.js";import{assertUsableApiKey as _e,normalizeApiKey as ve}from"./http/api-key.js";import{APP_IDENTITY as ye,attributionHeaders as be,userAgent as xe}from"./http/attribution.js";import{AgentMemory as Se,resolveMemoryConfig as Ce}from"./agent/memory/memory.js";import{estimateContextTokens as we,estimateMessageTokens as Te}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as Ee}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as De,ContextCompactor as Oe}from"./agent/memory/compaction.js";import{resolveCompactionConfig as ke}from"./agent/memory/compaction-config.js";import{defineTool as Ae}from"./agent/tool/definition.js";import{createContextOptimizer as je}from"./agent/memory/context-optimizer.js";import{MEMORY_ERROR_CODES as Me,MEMORY_STORE_API_VERSION as Ne}from"./composition/memory/config.js";import{defineMemoryStore as Pe}from"./composition/memory/definition.js";import{MAX_SKILL_DESCRIPTION_CHARS as Fe,MAX_SKILL_ID_CHARS as Ie,MAX_SKILL_INSTRUCTIONS_CHARS as Le,MAX_SKILL_NAME_CHARS as Re,MAX_SKILL_RESOURCE_CHARS as ze,MAX_SKILL_RESOURCE_PATH_CHARS as Be,SKILL_ID_PATTERN as Ve,defineSkill as He,defineSkillProvider as Ue,validateCandidate as We,validateSkillId as Ge,validateSkillResourcePath as Ke,validateSkillSource as qe}from"./agent/skill/definition.js";import{SKILL_ERROR_CODES as Je,SKILL_PROVIDER_API_VERSION as Ye}from"./agent/skill/provider/config.js";import{defineSkillProviderPlugin as Xe}from"./agent/skill/provider/definition.js";import{SkillCatalog as Ze}from"./agent/skill/catalog.js";import{SKILL_TOOL_NAMES as Qe,createSkillTools as $e,renderSkillCatalog as et,resolveSkillOptions as tt}from"./agent/skill/tools.js";import{OBSERVATION_EXPORTER_API_VERSION as nt}from"./composition/exporter/types.js";import{CONTEXT_SECTION_ID_PATTERN as rt,CONTEXT_SECTION_INVALID as it,MAX_CONTEXT_SECTION_TEXT_BYTES as at,defineContextSection as ot}from"./agent/context/section.js";import{createApprovalBroker as st,createApprovalRequest as ct,fixedApprovalBroker as lt,withApprovalPersistence as ut}from"./agent/tool/approval.js";import{createUserInputBroker as dt,fixedUserInputBroker as ft}from"./agent/mode/user-input.js";import{createAgentRuntime as pt}from"./composition/runtime/public.js";import{withoutRunReport as mt}from"./composition/agent/public-event.js";import{cloneAgent as ht,defineAgent as gt}from"./composition/agent/author.js";import{defineObservationExporter as _t}from"./composition/exporter/definition.js";import{defineToolFromSchema as vt}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as yt,localToolExecutionBackend as bt}from"./agent/tool/execution.js";export{ye as APP_IDENTITY,Se as AgentMemory,T as AgentSdkError,oe as BlockAssembler,De as COMPACTION_INSTRUCTION,rt as CONTEXT_SECTION_ID_PATTERN,it as CONTEXT_SECTION_INVALID,E as CONTEXT_WINDOW_EXCEEDED_CODE,Oe as ContextCompactor,D as EMPTY_RESPONSE_CODE,O as INVALID_CREDENTIAL_CODE,at as MAX_CONTEXT_SECTION_TEXT_BYTES,Fe as MAX_SKILL_DESCRIPTION_CHARS,Ie as MAX_SKILL_ID_CHARS,Le as MAX_SKILL_INSTRUCTIONS_CHARS,Re as MAX_SKILL_NAME_CHARS,ze as MAX_SKILL_RESOURCE_CHARS,Be as MAX_SKILL_RESOURCE_PATH_CHARS,ue as MAX_TIMER_DELAY_MS,Me as MEMORY_ERROR_CODES,Ne as MEMORY_STORE_API_VERSION,k as MISSING_CREDENTIAL_CODE,W as MODEL_ERROR_CODES,e as MessageId,ce as ModelAdapter,F as ModelCallObservationError,G as ModelError,he as ModelRegistry,y as NOOP_OBSERVATION_PORT,I as OBSERVATION_ERROR_CODES,nt as OBSERVATION_EXPORTER_API_VERSION,H as PLUGIN_ERROR_CODES,U as PluginError,t as ProviderRequestId,A as QUOTA_EXCEEDED_CODE,K as REGISTRY_ERROR_CODES,n as ReasoningEffortId,c as SDK_VERSION,Je as SKILL_ERROR_CODES,Ve as SKILL_ID_PATTERN,Ye as SKILL_PROVIDER_API_VERSION,Qe as SKILL_TOOL_NAMES,Ze as SkillCatalog,r as ToolCallId,L as addUsageCounters,o as assertNever,_e as assertUsableApiKey,be as attributionHeaders,de as backoffDelayMs,le as callConfigEquals,R as classifyUsageCoverage,ht as cloneAgent,ee as contentHasDocument,te as contentHasImage,pt as createAgentRuntime,st as createApprovalBroker,ct as createApprovalRequest,J as createAssistantMessage,je as createContextOptimizer,b as createCoreSpan,Y as createMessage,u as createObservationRunScope,d as createOperationId,$e as createSkillTools,f as createSpanId,X as createTextMessage,yt as createToolExecutionInterceptor,Z as createToolResultMessage,p as createTraceId,dt as createUserInputBroker,Q as createUserMessage,i as deepFreeze,gt as defineAgent,ot as defineContextSection,Pe as defineMemoryStore,_t as defineObservationExporter,He as defineSkill,Ue as defineSkillProvider,Xe as defineSkillProviderPlugin,Ae as defineTool,vt as defineToolFromSchema,s as detachedFrozen,x as disabledDeliverySummary,j as errorChain,we as estimateContextTokens,Te as estimateMessageTokens,lt as fixedApprovalBroker,ft as fixedUserInputBroker,m as freezeCorrelation,$ as freezeMessage,z as hasUsageCounters,M as isAgentSdkError,N as isContextWindowExceededError,a as isJsonValue,me as isNativeToolSchema,P as isQuotaExceededError,fe as isRetryable,h as isSpanId,g as isTraceId,bt as localToolExecutionBackend,ve as normalizeApiKey,q as normalizeModelFailure,B as possiblyBilledAttemptsWithoutUsage,ne as projectDocumentsForTextModel,re as projectImagesForTextModel,et as renderSkillCatalog,ke as resolveCompactionConfig,Ce as resolveMemoryConfig,pe as resolveRetryPolicy,tt as resolveSkillOptions,v as safeErrorRecord,Ee as selectCompactablePrefix,S as snapshotObservationSpan,ie as textOnlyDocumentText,ae as textOnlyImageText,_ as traceparent,xe as userAgent,C as validObservationSpan,We as validateCandidate,w as validateCaptureReceipt,Ge as validateSkillId,Ke as validateSkillResourcePath,qe as validateSkillSource,V as validateUsageCounters,l as waitForSettlement,ut as withApprovalPersistence,se as withIdleTimeout,ge as withRetry,mt as withoutRunReport};
@@ -1,2 +1,2 @@
1
- import{deepFreeze as e}from"../primitives/freeze.js";import"../primitives/version.js";import{createObservationRunScope as t,createOperationId as n}from"../observation/context.js";import{safeErrorRecord as r}from"../observation/event.js";import{createCoreSpan as i,snapshotObservationSpan as a}from"../observation/port.js";import{sanitizeObservationEvent as o,serializedEventBytes as s}from"../observation/privacy.js";import{createBusLogger as c}from"./logger.js";const l={none:0,"local-durable":1,"remote-acknowledged":2},u=new Set([`ABORT_ERR`,`ECONNREFUSED`,`ECONNRESET`,`EHOSTUNREACH`,`ENETUNREACH`,`ETIMEDOUT`,`OBSERVABILITY_EXPORT_FAILED`,`OBSERVABILITY_FLUSH_TIMEOUT`,`OBSERVABILITY_PROCESSOR_FAILED`,`OTEL_PROVIDER_UNCONFIGURED`]),d=/^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,63})$/,f=new Set([`none`,`metadata`,`redacted`,`full`]),p=new Set([`trace`,`debug`,`info`,`warn`,`error`,`fatal`]);function m(e,t){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`${t} must be a positive safe integer`);return e}function h(t,n){let i=r(t);return e({type:[`AbortError`,`Error`,`RangeError`,`TypeError`].includes(i.type)?i.type:`Error`,message:n,...i.code!==void 0&&u.has(i.code)?{code:i.code}:{},...i.retryable===void 0?{}:{retryable:i.retryable},...i.status===void 0?{}:{status:i.status}})}function g(e,t,n=`none`,r){return Object.freeze({eventId:e,status:t,durable:t===`accepted`&&n!==`none`,boundary:n,...r===void 0?{}:{reason:r}})}function _(e){try{let t=Reflect.get(e,`eventId`);return typeof t==`string`&&t.length>0?t:n()}catch{return n()}}function v(e){let t=`none`;for(let n of e)n.requirement===`required`&&l[n.boundary]>l[t]&&(t=n.boundary);return t}function y(e,t){let n=new Set;for(let r of t){let t=r.exporter?.id;if(typeof t!=`string`||!d.test(t))throw TypeError(`observation exporter id must be a safe 1-64 character identifier`);if(n.has(t))throw TypeError(`duplicate observation exporter id: ${t}`);if(n.add(t),r.requirement!==`required`&&r.requirement!==`best-effort`)throw TypeError(`observation exporter ${t} has an invalid requirement`);if(!(r.boundary in l))throw TypeError(`observation exporter ${t} has an invalid boundary`);let i=r.exporter.supportedBoundaries??[`none`];if(typeof r.exporter.export!=`function`)throw TypeError(`observation exporter ${t} has no export function`);if(!i.includes(r.boundary))throw TypeError(`observation exporter ${t} does not support ${r.boundary}`);if(e===`operational`&&r.requirement===`required`)throw TypeError(`operational observation exporters must be best-effort`)}if(e!==`operational`&&!t.some(e=>e.requirement===`required`&&e.boundary!==`none`))throw TypeError(`${e} observability requires a durable required exporter`);return Object.freeze(t.map(e=>Object.freeze({...e})))}function b(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(new DOMException(`observation deadline exceeded`,`TimeoutError`)),e),i=()=>n.abort(t?.reason??new DOMException(`observation aborted`,`AbortError`));return t?.aborted===!0?i():t?.addEventListener(`abort`,i,{once:!0}),{signal:n.signal,clear(){clearTimeout(r),t?.removeEventListener(`abort`,i)}}}function x(e,t){return t.aborted?Promise.reject(t.reason??Error(`observation aborted`)):new Promise((n,r)=>{let i=()=>{a(),r(t.reason??Error(`observation aborted`))},a=()=>t.removeEventListener(`abort`,i);t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})})}function S(e){try{let t=e.reason;return typeof t==`object`&&!!t&&Reflect.get(t,`name`)===`TimeoutError`}catch{return!1}}function C(e){return Object.freeze({complete:e.complete,exportedEvents:e.exportedEvents,pendingEvents:e.pendingEvents,rejectedCritical:e.rejectedCritical,timedOut:e.timedOut})}function w(e,t){return e.eventId===t.eventId&&e.sequence===t.sequence&&e.name===t.name&&e.phase===t.phase&&e.occurredAt===t.occurredAt&&e.monotonicMs===t.monotonicMs&&e.priority===t.priority&&JSON.stringify(e.resource)===JSON.stringify(t.resource)&&JSON.stringify(e.correlation)===JSON.stringify(t.correlation)}var T=class{mode;resource;registrations;processors;options;queue=[];queueBytes=0;closing=!1;closed=!1;shutdownPromise;flushChain=Promise.resolve();protectedFailures=new Set;healthScope=t();healthRunId=n();healthCorrelation=i({name:`sdk.integration.request`,runId:this.healthRunId,startedAt:new Date().toISOString(),monotonicMs:this.healthScope.monotonicMs()}).correlation;counters={accepted:0,exported:0,droppedVerbose:0,droppedNormal:0,criticalRejected:0,processorFailures:0,exporterFailures:0,flushTimeouts:0,requiredFailure:!1};constructor(t){if(this.mode=t.mode??`operational`,![`operational`,`reliable`,`audit`].includes(this.mode))throw TypeError(`invalid observation mode`);this.resource=e({sdkName:`ai-agent-sdk`,sdkVersion:t.resource?.sdkVersion??`0.1.7`,...t.resource?.serviceName===void 0?{}:{serviceName:t.resource.serviceName},...t.resource?.serviceVersion===void 0?{}:{serviceVersion:t.resource.serviceVersion},runtime:t.resource?.runtime??`unknown`}),this.registrations=y(this.mode,t.exporters??[]);let n=new Set;for(let e of t.processors??[]){if(typeof e.id!=`string`||!d.test(e.id))throw TypeError(`processor id must be a safe 1-64 character identifier`);if(n.has(e.id))throw TypeError(`duplicate observation processor id: ${e.id}`);if(typeof e.transform!=`function`)throw TypeError(`observation processor ${e.id} is invalid`);n.add(e.id)}if(this.processors=Object.freeze([...t.processors??[]]),!f.has(t.content??`none`))throw TypeError(`invalid observation content policy`);if(!p.has(t.minimumLogLevel??`info`))throw TypeError(`invalid minimum log level`);let r=new Set;for(let e of t.redactors??[]){if(typeof e.id!=`string`||!d.test(e.id)||typeof e.redact!=`function`)throw TypeError(`invalid observation content redactor`);if(r.has(e.id))throw TypeError(`duplicate observation redactor id: ${e.id}`);r.add(e.id)}this.options={content:t.content??`none`,includeErrorStacks:t.includeErrorStacks??!1,minimumLogLevel:t.minimumLogLevel??`info`,maxQueueEvents:m(t.maxQueueEvents??1e4,`maxQueueEvents`),maxQueueBytes:m(t.maxQueueBytes??16777216,`maxQueueBytes`),maxBatchEvents:m(t.maxBatchEvents??256,`maxBatchEvents`),maxBatchBytes:m(t.maxBatchBytes??524288,`maxBatchBytes`),flushTimeoutMs:m(t.flushTimeoutMs??1e4,`flushTimeoutMs`),shutdownTimeoutMs:m(t.shutdownTimeoutMs??3e4,`shutdownTimeoutMs`),redactors:Object.freeze([...t.redactors??[]]),...t.onHealthChange===void 0?{}:{onHealthChange:t.onHealthChange},...t.openSpan===void 0?{}:{openSpan:t.openSpan}}}openSpan(e){let t=this.options.openSpan;if(t===void 0)return i(e);try{let n=a(t(e));if(n!==void 0)return n;this.counters.processorFailures++,this.recordFailure(`span:invalid`,TypeError(`invalid span`),`observation span backend returned an invalid span`,!1)}catch(e){this.counters.processorFailures++,this.recordFailure(`span:throw`,e,`observation span backend failed`,!1)}return i(e)}capture(e){let t=_(e);if(this.closing||this.closed)return g(t,`rejected`,`none`,`closed`);let n;try{n=this.prepareEvent(e,!1)}catch(e){return this.counters.processorFailures++,this.counters.lastFailure=h(e,`observation processor failed`),this.notifyHealth(),this.recordFailure(`processor:capture`,e,`observation processor failed`,!0),g(t,`rejected`,`none`,`processor-failed`)}let r=this.enqueue(n,!1);return r.status===`accepted`?this.stageExporters(n,r):r}async checkpoint(e,t){let n=this.capture(e);if(n.status!==`accepted`||this.mode===`operational`)return n;let r=this.queue.find(e=>e.event.eventId===n.eventId)?.event;if(r===void 0)return g(n.eventId,`rejected`,`none`,`exporter-unavailable`);let i=new Set(this.queue.filter(e=>e.event.priority===`critical`&&e.event.correlation.runId===r.correlation.runId&&e.event.sequence<=r.sequence).map(e=>e.event.eventId));return(await this.scheduleFlush(i,this.options.flushTimeoutMs,t)).requiredComplete?g(n.eventId,`accepted`,v(this.registrations)):g(n.eventId,`rejected`,`none`,`exporter-unavailable`)}logger(e){return c({minimumLevel:this.options.minimumLogLevel,resource:this.resource,emit:e=>{this.capture(e)}},e)}health(){let t=this.closed?`closed`:this.counters.requiredFailure||this.counters.criticalRejected>0||this.counters.flushTimeouts>0?`failed`:this.counters.processorFailures>0||this.counters.exporterFailures>0||this.counters.droppedVerbose>0||this.counters.droppedNormal>0?`degraded`:`healthy`;return e({state:t,queuedEvents:this.queue.length,queuedBytes:this.queueBytes,accepted:this.counters.accepted,exported:this.counters.exported,droppedVerbose:this.counters.droppedVerbose,droppedNormal:this.counters.droppedNormal,criticalRejected:this.counters.criticalRejected,processorFailures:this.counters.processorFailures,exporterFailures:this.counters.exporterFailures,flushTimeouts:this.counters.flushTimeouts,...this.counters.lastExportAt===void 0?{}:{lastExportAt:this.counters.lastExportAt},...this.counters.lastFailure===void 0?{}:{lastFailure:this.counters.lastFailure}})}flush(e){if(this.closed||this.closing)throw TypeError(`observability is closed`);return this.scheduleFlush(new Set(this.queue.map(e=>e.event.eventId)),this.options.flushTimeoutMs,e).then(C)}shutdown(e){if(this.shutdownPromise!==void 0)return this.shutdownPromise;this.closing=!0;let t=new Set(this.queue.map(e=>e.event.eventId));return this.shutdownPromise=(async()=>{let n=b(this.options.shutdownTimeoutMs,e),r;try{r=C(await this.scheduleFlush(t,this.options.shutdownTimeoutMs,n.signal));for(let e of[...this.registrations].reverse()){let t=e.exporter.shutdown;if(t!==void 0)try{await x(Promise.resolve(t.call(e.exporter,n.signal)),n.signal)}catch(t){this.recordExporterFailure(e,t,!1),r=Object.freeze({...r,complete:!1})}}}finally{n.clear(),this.closed=!0,this.notifyHealth()}return r})(),this.shutdownPromise}prepareEvent(e,t){let n={content:this.options.content,redactors:this.options.redactors??[],includeErrorStacks:this.options.includeErrorStacks},r=o(e,n);if(t)return r;for(let e of this.processors){let t=e.transform(r);if(t===void 0)throw TypeError(`observation processor ${e.id} returned undefined`);let i=o(t,n);if(!w(r,i))throw TypeError(`observation processor ${e.id} changed the immutable event envelope`);r=i}return r}enqueue(e,t){let n=s(e);return n>this.options.maxBatchBytes||n>this.options.maxQueueBytes||!this.makeCapacity(n,t)?(!t&&e.priority===`critical`&&this.counters.criticalRejected++,t||(this.counters.lastFailure=h(RangeError(`capacity`),`observation queue capacity exhausted`),this.notifyHealth()),g(e.eventId,`rejected`,`none`,`capacity`)):(this.queue.push({event:e,bytes:n,protected:t,pending:new Set(this.registrations.map(e=>e.exporter.id))}),this.queueBytes+=n,this.counters.accepted++,this.notifyHealth(),g(e.eventId,`accepted`))}stageExporters(e,t){let n=this.queue.find(t=>t.event.eventId===e.eventId);if(n===void 0)return g(e.eventId,`rejected`,`none`,`exporter-unavailable`);let r=!1;for(let t of this.registrations){let i=t.exporter.stage;if(i!==void 0)try{let n=i.call(t.exporter,e);n!==void 0&&Promise.resolve(n).catch(()=>void 0)}catch(i){if(this.recordExporterFailure(t,i,!1),n.pending.delete(t.exporter.id),r=!0,t.requirement===`required`)return this.removeEntry(n,!1),e.priority===`critical`&&this.counters.criticalRejected++,this.notifyHealth(),g(e.eventId,`rejected`,`none`,`exporter-unavailable`)}}return r&&n.pending.size===0&&this.removeEntry(n,!1),t}makeCapacity(e,t){for(;this.queue.length+1>this.options.maxQueueEvents||this.queueBytes+e>this.options.maxQueueBytes;){let e=this.queue.findIndex(e=>e.event.priority===`verbose`);if(e===-1&&(e=this.queue.findIndex(e=>e.event.priority===`normal`)),e===-1)return!1;let[n]=this.queue.splice(e,1);if(n===void 0)return!1;this.queueBytes-=n.bytes,t||(n.event.priority===`verbose`?this.counters.droppedVerbose++:this.counters.droppedNormal++)}return!0}scheduleFlush(e,t,n){let r,i,a=new Promise((e,t)=>{r=e,i=t}),o=async()=>{try{r(await this.flushInternal(e,t,n))}catch(e){i(e)}};return this.flushChain=this.flushChain.then(o,o),a}async flushInternal(t,r,i){let a=this.counters.exported,o=b(r,i),s=!1,c=!1;try{if(this.registrations.length===0)for(let e of[...this.queue])t.has(e.event.eventId)&&this.removeEntry(e,!1);for(let r of this.registrations)for(;;){let i=this.queue.filter(e=>t.has(e.event.eventId)&&e.pending.has(r.exporter.id));if(i.length===0)break;let a=[],l=0;for(let e of i){if(a.length>=this.options.maxBatchEvents||l+e.bytes>this.options.maxBatchBytes)break;a.push(e),l+=e.bytes}if(a.length===0)break;let u=e({schemaVersion:1,batchId:n(),createdAt:new Date().toISOString(),events:a.map(e=>e.event)}),d;try{if(d=await x(Promise.resolve(r.exporter.export(u,o.signal)),o.signal),d.batchId!==u.batchId||d.accepted!==!0)throw TypeError(`observation exporter ${r.exporter.id} returned an invalid acknowledgment`)}catch(e){if(s=!0,c||=S(o.signal),this.recordExporterFailure(r,e,!0),r.requirement===`best-effort`)for(let e of a)e.pending.delete(r.exporter.id),e.pending.size===0&&this.removeEntry(e,!1);break}this.counters.lastExportAt=new Date().toISOString();for(let e of a)e.pending.delete(r.exporter.id),e.pending.size===0&&this.removeEntry(e,!0);this.notifyHealth()}}finally{S(o.signal)&&(c=!0,this.counters.flushTimeouts++,this.counters.lastFailure=h(o.signal.reason,`observation flush timed out`),this.notifyHealth()),o.clear()}let l=this.queue.filter(e=>t.has(e.event.eventId)),u=this.registrations.filter(e=>e.requirement===`required`).map(e=>e.exporter.id),d=l.every(e=>u.every(t=>!e.pending.has(t)));return Object.freeze({complete:!s&&!c&&l.length===0,requiredComplete:d,exportedEvents:this.counters.exported-a,pendingEvents:l.length,rejectedCritical:this.counters.criticalRejected,timedOut:c})}removeEntry(e,t){let n=this.queue.indexOf(e);n!==-1&&(this.queue.splice(n,1),this.queueBytes-=e.bytes,t&&this.counters.exported++)}recordExporterFailure(e,t,n){this.counters.exporterFailures++,e.requirement===`required`&&(this.counters.requiredFailure=!0),this.counters.lastFailure=h(t,`observation exporter failed`),this.notifyHealth(),n&&this.recordFailure(`exporter:${e.exporter.id}`,t,`observation exporter failed`,!0)}recordFailure(e,t,r,i){if(this.counters.lastFailure=h(t,r),this.notifyHealth(),!(!i||this.protectedFailures.has(e)||this.closing||this.closed)){this.protectedFailures.add(e);try{let t=this.prepareEvent({schemaVersion:1,eventId:n(),sequence:this.healthScope.nextSequence(),name:`sdk.observer.failure`,phase:`point`,occurredAt:new Date().toISOString(),monotonicMs:this.healthScope.monotonicMs(),priority:`critical`,resource:this.resource,correlation:this.healthCorrelation,data:{observerId:e,failureKind:`contained`,count:1,error:{...this.counters.lastFailure}}},!0);this.enqueue(t,!0)}catch{}}}notifyHealth(){let e=this.options.onHealthChange;if(e!==void 0)try{e(this.health())}catch{}}};function E(e={}){return new T(e)}export{E as createObservability};
1
+ import{deepFreeze as e}from"../primitives/freeze.js";import"../primitives/version.js";import{createObservationRunScope as t,createOperationId as n}from"../observation/context.js";import{safeErrorRecord as r}from"../observation/event.js";import{createCoreSpan as i,snapshotObservationSpan as a}from"../observation/port.js";import{sanitizeObservationEvent as o,serializedEventBytes as s}from"../observation/privacy.js";import{createBusLogger as c}from"./logger.js";const l={none:0,"local-durable":1,"remote-acknowledged":2},u=new Set([`ABORT_ERR`,`ECONNREFUSED`,`ECONNRESET`,`EHOSTUNREACH`,`ENETUNREACH`,`ETIMEDOUT`,`OBSERVABILITY_EXPORT_FAILED`,`OBSERVABILITY_FLUSH_TIMEOUT`,`OBSERVABILITY_PROCESSOR_FAILED`,`OTEL_PROVIDER_UNCONFIGURED`]),d=/^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,63})$/,f=new Set([`none`,`metadata`,`redacted`,`full`]),p=new Set([`trace`,`debug`,`info`,`warn`,`error`,`fatal`]);function m(e,t){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`${t} must be a positive safe integer`);return e}function h(t,n){let i=r(t);return e({type:[`AbortError`,`Error`,`RangeError`,`TypeError`].includes(i.type)?i.type:`Error`,message:n,...i.code!==void 0&&u.has(i.code)?{code:i.code}:{},...i.retryable===void 0?{}:{retryable:i.retryable},...i.status===void 0?{}:{status:i.status}})}function g(e,t,n=`none`,r){return Object.freeze({eventId:e,status:t,durable:t===`accepted`&&n!==`none`,boundary:n,...r===void 0?{}:{reason:r}})}function _(e){try{let t=Reflect.get(e,`eventId`);return typeof t==`string`&&t.length>0?t:n()}catch{return n()}}function v(e){let t=`none`;for(let n of e)n.requirement===`required`&&l[n.boundary]>l[t]&&(t=n.boundary);return t}function y(e,t){let n=new Set;for(let r of t){let t=r.exporter?.id;if(typeof t!=`string`||!d.test(t))throw TypeError(`observation exporter id must be a safe 1-64 character identifier`);if(n.has(t))throw TypeError(`duplicate observation exporter id: ${t}`);if(n.add(t),r.requirement!==`required`&&r.requirement!==`best-effort`)throw TypeError(`observation exporter ${t} has an invalid requirement`);if(!(r.boundary in l))throw TypeError(`observation exporter ${t} has an invalid boundary`);let i=r.exporter.supportedBoundaries??[`none`];if(typeof r.exporter.export!=`function`)throw TypeError(`observation exporter ${t} has no export function`);if(!i.includes(r.boundary))throw TypeError(`observation exporter ${t} does not support ${r.boundary}`);if(e===`operational`&&r.requirement===`required`)throw TypeError(`operational observation exporters must be best-effort`)}if(e!==`operational`&&!t.some(e=>e.requirement===`required`&&e.boundary!==`none`))throw TypeError(`${e} observability requires a durable required exporter`);return Object.freeze(t.map(e=>Object.freeze({...e})))}function b(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(new DOMException(`observation deadline exceeded`,`TimeoutError`)),e),i=()=>n.abort(t?.reason??new DOMException(`observation aborted`,`AbortError`));return t?.aborted===!0?i():t?.addEventListener(`abort`,i,{once:!0}),{signal:n.signal,clear(){clearTimeout(r),t?.removeEventListener(`abort`,i)}}}function x(e,t){return t.aborted?Promise.reject(t.reason??Error(`observation aborted`)):new Promise((n,r)=>{let i=()=>{a(),r(t.reason??Error(`observation aborted`))},a=()=>t.removeEventListener(`abort`,i);t.addEventListener(`abort`,i,{once:!0}),e.then(e=>{a(),n(e)},e=>{a(),r(e)})})}function S(e){try{let t=e.reason;return typeof t==`object`&&!!t&&Reflect.get(t,`name`)===`TimeoutError`}catch{return!1}}function C(e){return Object.freeze({complete:e.complete,exportedEvents:e.exportedEvents,pendingEvents:e.pendingEvents,rejectedCritical:e.rejectedCritical,timedOut:e.timedOut})}function w(e,t){return e.eventId===t.eventId&&e.sequence===t.sequence&&e.name===t.name&&e.phase===t.phase&&e.occurredAt===t.occurredAt&&e.monotonicMs===t.monotonicMs&&e.priority===t.priority&&JSON.stringify(e.resource)===JSON.stringify(t.resource)&&JSON.stringify(e.correlation)===JSON.stringify(t.correlation)}var T=class{mode;resource;registrations;processors;options;queue=[];queueBytes=0;closing=!1;closed=!1;shutdownPromise;flushChain=Promise.resolve();protectedFailures=new Set;healthScope=t();healthRunId=n();healthCorrelation=i({name:`sdk.integration.request`,runId:this.healthRunId,startedAt:new Date().toISOString(),monotonicMs:this.healthScope.monotonicMs()}).correlation;counters={accepted:0,exported:0,droppedVerbose:0,droppedNormal:0,criticalRejected:0,processorFailures:0,exporterFailures:0,flushTimeouts:0,requiredFailure:!1};constructor(t){if(this.mode=t.mode??`operational`,![`operational`,`reliable`,`audit`].includes(this.mode))throw TypeError(`invalid observation mode`);this.resource=e({sdkName:`ai-agent-sdk`,sdkVersion:t.resource?.sdkVersion??`0.1.9`,...t.resource?.serviceName===void 0?{}:{serviceName:t.resource.serviceName},...t.resource?.serviceVersion===void 0?{}:{serviceVersion:t.resource.serviceVersion},runtime:t.resource?.runtime??`unknown`}),this.registrations=y(this.mode,t.exporters??[]);let n=new Set;for(let e of t.processors??[]){if(typeof e.id!=`string`||!d.test(e.id))throw TypeError(`processor id must be a safe 1-64 character identifier`);if(n.has(e.id))throw TypeError(`duplicate observation processor id: ${e.id}`);if(typeof e.transform!=`function`)throw TypeError(`observation processor ${e.id} is invalid`);n.add(e.id)}if(this.processors=Object.freeze([...t.processors??[]]),!f.has(t.content??`none`))throw TypeError(`invalid observation content policy`);if(!p.has(t.minimumLogLevel??`info`))throw TypeError(`invalid minimum log level`);let r=new Set;for(let e of t.redactors??[]){if(typeof e.id!=`string`||!d.test(e.id)||typeof e.redact!=`function`)throw TypeError(`invalid observation content redactor`);if(r.has(e.id))throw TypeError(`duplicate observation redactor id: ${e.id}`);r.add(e.id)}this.options={content:t.content??`none`,includeErrorStacks:t.includeErrorStacks??!1,minimumLogLevel:t.minimumLogLevel??`info`,maxQueueEvents:m(t.maxQueueEvents??1e4,`maxQueueEvents`),maxQueueBytes:m(t.maxQueueBytes??16777216,`maxQueueBytes`),maxBatchEvents:m(t.maxBatchEvents??256,`maxBatchEvents`),maxBatchBytes:m(t.maxBatchBytes??524288,`maxBatchBytes`),flushTimeoutMs:m(t.flushTimeoutMs??1e4,`flushTimeoutMs`),shutdownTimeoutMs:m(t.shutdownTimeoutMs??3e4,`shutdownTimeoutMs`),redactors:Object.freeze([...t.redactors??[]]),...t.onHealthChange===void 0?{}:{onHealthChange:t.onHealthChange},...t.openSpan===void 0?{}:{openSpan:t.openSpan}}}openSpan(e){let t=this.options.openSpan;if(t===void 0)return i(e);try{let n=a(t(e));if(n!==void 0)return n;this.counters.processorFailures++,this.recordFailure(`span:invalid`,TypeError(`invalid span`),`observation span backend returned an invalid span`,!1)}catch(e){this.counters.processorFailures++,this.recordFailure(`span:throw`,e,`observation span backend failed`,!1)}return i(e)}capture(e){let t=_(e);if(this.closing||this.closed)return g(t,`rejected`,`none`,`closed`);let n;try{n=this.prepareEvent(e,!1)}catch(e){return this.counters.processorFailures++,this.counters.lastFailure=h(e,`observation processor failed`),this.notifyHealth(),this.recordFailure(`processor:capture`,e,`observation processor failed`,!0),g(t,`rejected`,`none`,`processor-failed`)}let r=this.enqueue(n,!1);return r.status===`accepted`?this.stageExporters(n,r):r}async checkpoint(e,t){let n=this.capture(e);if(n.status!==`accepted`||this.mode===`operational`)return n;let r=this.queue.find(e=>e.event.eventId===n.eventId)?.event;if(r===void 0)return g(n.eventId,`rejected`,`none`,`exporter-unavailable`);let i=new Set(this.queue.filter(e=>e.event.priority===`critical`&&e.event.correlation.runId===r.correlation.runId&&e.event.sequence<=r.sequence).map(e=>e.event.eventId));return(await this.scheduleFlush(i,this.options.flushTimeoutMs,t)).requiredComplete?g(n.eventId,`accepted`,v(this.registrations)):g(n.eventId,`rejected`,`none`,`exporter-unavailable`)}logger(e){return c({minimumLevel:this.options.minimumLogLevel,resource:this.resource,emit:e=>{this.capture(e)}},e)}health(){let t=this.closed?`closed`:this.counters.requiredFailure||this.counters.criticalRejected>0||this.counters.flushTimeouts>0?`failed`:this.counters.processorFailures>0||this.counters.exporterFailures>0||this.counters.droppedVerbose>0||this.counters.droppedNormal>0?`degraded`:`healthy`;return e({state:t,queuedEvents:this.queue.length,queuedBytes:this.queueBytes,accepted:this.counters.accepted,exported:this.counters.exported,droppedVerbose:this.counters.droppedVerbose,droppedNormal:this.counters.droppedNormal,criticalRejected:this.counters.criticalRejected,processorFailures:this.counters.processorFailures,exporterFailures:this.counters.exporterFailures,flushTimeouts:this.counters.flushTimeouts,...this.counters.lastExportAt===void 0?{}:{lastExportAt:this.counters.lastExportAt},...this.counters.lastFailure===void 0?{}:{lastFailure:this.counters.lastFailure}})}flush(e){if(this.closed||this.closing)throw TypeError(`observability is closed`);return this.scheduleFlush(new Set(this.queue.map(e=>e.event.eventId)),this.options.flushTimeoutMs,e).then(C)}shutdown(e){if(this.shutdownPromise!==void 0)return this.shutdownPromise;this.closing=!0;let t=new Set(this.queue.map(e=>e.event.eventId));return this.shutdownPromise=(async()=>{let n=b(this.options.shutdownTimeoutMs,e),r;try{r=C(await this.scheduleFlush(t,this.options.shutdownTimeoutMs,n.signal));for(let e of[...this.registrations].reverse()){let t=e.exporter.shutdown;if(t!==void 0)try{await x(Promise.resolve(t.call(e.exporter,n.signal)),n.signal)}catch(t){this.recordExporterFailure(e,t,!1),r=Object.freeze({...r,complete:!1})}}}finally{n.clear(),this.closed=!0,this.notifyHealth()}return r})(),this.shutdownPromise}prepareEvent(e,t){let n={content:this.options.content,redactors:this.options.redactors??[],includeErrorStacks:this.options.includeErrorStacks},r=o(e,n);if(t)return r;for(let e of this.processors){let t=e.transform(r);if(t===void 0)throw TypeError(`observation processor ${e.id} returned undefined`);let i=o(t,n);if(!w(r,i))throw TypeError(`observation processor ${e.id} changed the immutable event envelope`);r=i}return r}enqueue(e,t){let n=s(e);return n>this.options.maxBatchBytes||n>this.options.maxQueueBytes||!this.makeCapacity(n,t)?(!t&&e.priority===`critical`&&this.counters.criticalRejected++,t||(this.counters.lastFailure=h(RangeError(`capacity`),`observation queue capacity exhausted`),this.notifyHealth()),g(e.eventId,`rejected`,`none`,`capacity`)):(this.queue.push({event:e,bytes:n,protected:t,pending:new Set(this.registrations.map(e=>e.exporter.id))}),this.queueBytes+=n,this.counters.accepted++,this.notifyHealth(),g(e.eventId,`accepted`))}stageExporters(e,t){let n=this.queue.find(t=>t.event.eventId===e.eventId);if(n===void 0)return g(e.eventId,`rejected`,`none`,`exporter-unavailable`);let r=!1;for(let t of this.registrations){let i=t.exporter.stage;if(i!==void 0)try{let n=i.call(t.exporter,e);n!==void 0&&Promise.resolve(n).catch(()=>void 0)}catch(i){if(this.recordExporterFailure(t,i,!1),n.pending.delete(t.exporter.id),r=!0,t.requirement===`required`)return this.removeEntry(n,!1),e.priority===`critical`&&this.counters.criticalRejected++,this.notifyHealth(),g(e.eventId,`rejected`,`none`,`exporter-unavailable`)}}return r&&n.pending.size===0&&this.removeEntry(n,!1),t}makeCapacity(e,t){for(;this.queue.length+1>this.options.maxQueueEvents||this.queueBytes+e>this.options.maxQueueBytes;){let e=this.queue.findIndex(e=>e.event.priority===`verbose`);if(e===-1&&(e=this.queue.findIndex(e=>e.event.priority===`normal`)),e===-1)return!1;let[n]=this.queue.splice(e,1);if(n===void 0)return!1;this.queueBytes-=n.bytes,t||(n.event.priority===`verbose`?this.counters.droppedVerbose++:this.counters.droppedNormal++)}return!0}scheduleFlush(e,t,n){let r,i,a=new Promise((e,t)=>{r=e,i=t}),o=async()=>{try{r(await this.flushInternal(e,t,n))}catch(e){i(e)}};return this.flushChain=this.flushChain.then(o,o),a}async flushInternal(t,r,i){let a=this.counters.exported,o=b(r,i),s=!1,c=!1;try{if(this.registrations.length===0)for(let e of[...this.queue])t.has(e.event.eventId)&&this.removeEntry(e,!1);for(let r of this.registrations)for(;;){let i=this.queue.filter(e=>t.has(e.event.eventId)&&e.pending.has(r.exporter.id));if(i.length===0)break;let a=[],l=0;for(let e of i){if(a.length>=this.options.maxBatchEvents||l+e.bytes>this.options.maxBatchBytes)break;a.push(e),l+=e.bytes}if(a.length===0)break;let u=e({schemaVersion:1,batchId:n(),createdAt:new Date().toISOString(),events:a.map(e=>e.event)}),d;try{if(d=await x(Promise.resolve(r.exporter.export(u,o.signal)),o.signal),d.batchId!==u.batchId||d.accepted!==!0)throw TypeError(`observation exporter ${r.exporter.id} returned an invalid acknowledgment`)}catch(e){if(s=!0,c||=S(o.signal),this.recordExporterFailure(r,e,!0),r.requirement===`best-effort`)for(let e of a)e.pending.delete(r.exporter.id),e.pending.size===0&&this.removeEntry(e,!1);break}this.counters.lastExportAt=new Date().toISOString();for(let e of a)e.pending.delete(r.exporter.id),e.pending.size===0&&this.removeEntry(e,!0);this.notifyHealth()}}finally{S(o.signal)&&(c=!0,this.counters.flushTimeouts++,this.counters.lastFailure=h(o.signal.reason,`observation flush timed out`),this.notifyHealth()),o.clear()}let l=this.queue.filter(e=>t.has(e.event.eventId)),u=this.registrations.filter(e=>e.requirement===`required`).map(e=>e.exporter.id),d=l.every(e=>u.every(t=>!e.pending.has(t)));return Object.freeze({complete:!s&&!c&&l.length===0,requiredComplete:d,exportedEvents:this.counters.exported-a,pendingEvents:l.length,rejectedCritical:this.counters.criticalRejected,timedOut:c})}removeEntry(e,t){let n=this.queue.indexOf(e);n!==-1&&(this.queue.splice(n,1),this.queueBytes-=e.bytes,t&&this.counters.exported++)}recordExporterFailure(e,t,n){this.counters.exporterFailures++,e.requirement===`required`&&(this.counters.requiredFailure=!0),this.counters.lastFailure=h(t,`observation exporter failed`),this.notifyHealth(),n&&this.recordFailure(`exporter:${e.exporter.id}`,t,`observation exporter failed`,!0)}recordFailure(e,t,r,i){if(this.counters.lastFailure=h(t,r),this.notifyHealth(),!(!i||this.protectedFailures.has(e)||this.closing||this.closed)){this.protectedFailures.add(e);try{let t=this.prepareEvent({schemaVersion:1,eventId:n(),sequence:this.healthScope.nextSequence(),name:`sdk.observer.failure`,phase:`point`,occurredAt:new Date().toISOString(),monotonicMs:this.healthScope.monotonicMs(),priority:`critical`,resource:this.resource,correlation:this.healthCorrelation,data:{observerId:e,failureKind:`contained`,count:1,error:{...this.counters.lastFailure}}},!0);this.enqueue(t,!0)}catch{}}}notifyHealth(){let e=this.options.onHealthChange;if(e!==void 0)try{e(this.health())}catch{}}};function E(e={}){return new T(e)}export{E as createObservability};
2
2
  //# sourceMappingURL=bus.js.map
@@ -1,6 +1,6 @@
1
1
  //#region src/primitives/version.d.ts
2
2
  /** Package version injected as a Web-standard literal; release tooling updates this file. */
3
- declare const SDK_VERSION = "0.1.7";
3
+ declare const SDK_VERSION = "0.1.9";
4
4
  //#endregion
5
5
  export { SDK_VERSION };
6
6
  //# sourceMappingURL=version.d.ts.map
@@ -1,2 +1,2 @@
1
- const e=`0.1.7`;export{e as SDK_VERSION};
1
+ const e=`0.1.9`;export{e as SDK_VERSION};
2
2
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/primitives/version.ts"],"sourcesContent":["/** Package version injected as a Web-standard literal; release tooling updates this file. */\nexport const SDK_VERSION = '0.1.7'\n"],"mappings":"AACA,MAAa,EAAc"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../../src/primitives/version.ts"],"sourcesContent":["/** Package version injected as a Web-standard literal; release tooling updates this file. */\nexport const SDK_VERSION = '0.1.9'\n"],"mappings":"AACA,MAAa,EAAc"}
@@ -1,2 +1,2 @@
1
- import{deepFreeze as e}from"../primitives/freeze.js";import"../primitives/version.js";import{PLUGIN_ERROR_CODES as t,PluginError as n}from"../plugin/provider-plugin.js";import{ModelError as r,REGISTRY_ERROR_CODES as i}from"../errors/model-error.js";import{callConfigEquals as a}from"../contract/call-config.js";import{resolveRetryPolicy as o}from"../contract/retry-policy.js";import{createModelCallHandle as s}from"./model-call-handle.js";import{normalizeResolvedModelInfo as c,resolveCallWithModelInfo as l,validateCatalogModels as u,validateModelCatalogSnapshot as d}from"./model-metadata.js";import{streamAdapter as f}from"./model-stream.js";function p(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return!1;let t;try{t=Reflect.get(e,`then`)}catch{return!0}if(typeof t!=`function`)return!1;try{Promise.resolve(e).catch(()=>{})}catch{}return!0}function m(e){try{return p(e())?TypeError(`plugin cleanup must be synchronous`):void 0}catch(e){return e}}var h=class{adapters=new Map;middleware=[];listeners=new Set;plugins=new Map;maxCatalogModels;maxCatalogBytes;observation;observationResource;defaults;constructor(t={}){this.maxCatalogModels=g(t.maxCatalogModels??2048,`maxCatalogModels`),this.maxCatalogBytes=g(t.maxCatalogBytes??4194304,`maxCatalogBytes`),this.observation=t.observation,this.defaults=_(t.defaults??{}),this.observationResource=e(t.observationResource??{sdkName:`ai-agent-sdk`,sdkVersion:`0.1.7`,runtime:`unknown`})}install(e){let a=typeof e?.id==`string`?e.id:``,o=(e,r,i=[])=>{let o=[...r===void 0?[]:[r],...i],s=o.length<=1?o[0]:AggregateError(o,`plugin ${a} install cleanup failed`);throw new n(e,t.INSTALL_FAILED,a,s===void 0?void 0:{cause:s})};(a.trim().length===0||a!==a.trim())&&o(`plugin id must be a non-empty trimmed string`),this.plugins.has(a)&&o(`plugin "${a}" is already installed`),(typeof e.displayName!=`string`||e.displayName.trim().length===0)&&o(`plugin "${a}" displayName must be non-empty`),typeof e.setup!=`function`&&o(`plugin "${a}" setup must be a function`);let s=e.family??a;(typeof s!=`string`||s.trim().length===0||s!==s.trim())&&o(`plugin "${a}" family must be a non-empty trimmed string`);let c=Object.freeze({pluginId:a,family:s}),l=[],u=[],d=!0,f={registerAdapter:(e,t)=>{if(d||o(`plugin "${a}" staging registrar is closed`),e.length===0)throw new r(`an adapter must register at least one provider route`,i.INVALID_ADAPTER);let n={active:!0,routes:[...e],adapter:t},s=new Set(l.filter(e=>e.active).flatMap(e=>e.routes));for(let t of e)if(s.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);this.prepareRoutes(e,t,new Set,c),l.push(n);let u=(()=>{d&&(n.active=!1)});return u.replace=e=>{if(!d||!n.active)throw new r(`a disposed staged registration cannot replace routes`,i.REGISTRATION_DISPOSED);let a=new Set(l.filter(e=>e.active&&e!==n).flatMap(e=>e.routes));for(let t of e)if(a.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);this.prepareRoutes(e,t,new Set,c),n.routes=[...e]},u},use:e=>{if(d||o(`plugin "${a}" staging registrar is closed`),typeof e!=`function`)throw TypeError(`plugin middleware must be a function`);let t={active:!0,middleware:e};return u.push(t),()=>{d&&(t.active=!1)}}},h;try{let t=e.setup(f);p(t)&&o(`plugin "${a}" setup must be synchronous`),t!==void 0&&typeof t!=`function`&&o(`plugin "${a}" setup must be synchronous and return void or cleanup`),h=typeof t==`function`?t:void 0}catch(e){if(e instanceof n&&e.code===t.INSTALL_FAILED)throw e;o(`plugin "${a}" setup failed`,e)}finally{d=!1}let g=[],_=new Set;try{for(let e of l)if(e.active){for(let t of e.routes){if(_.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);_.add(t)}g.push(...this.prepareRoutes(e.routes,e.adapter,new Set,c))}}catch(e){let t=[];if(h){let e=m(h);e!==void 0&&t.push(e)}o(`plugin "${a}" commit validation failed`,e,t)}let v=u.filter(e=>e.active).map(e=>e.middleware);for(let e of g)this.adapters.set(e.provider.id,e);this.middleware.push(...v);let y={routes:_,registrations:g,middleware:v,...h===void 0?{}:{cleanup:h}};this.plugins.set(a,y),this.emitAdaptersUpdated();let b=!1,x=(()=>{if(b)return;b=!0,this.plugins.delete(a);for(let e of y.registrations)this.adapters.get(e.provider.id)===e&&this.adapters.delete(e.provider.id);for(let e=y.middleware.length-1;e>=0;e--){let t=y.middleware[e],n=t===void 0?-1:this.middleware.lastIndexOf(t);n>=0&&this.middleware.splice(n,1)}this.emitAdaptersUpdated();let e=[];if(y.cleanup){let t=m(y.cleanup);t!==void 0&&e.push(t)}if(e.length>0)throw new n(`plugin "${a}" cleanup failed`,t.CLEANUP_FAILED,a,{cause:AggregateError(e,`plugin "${a}" cleanup failed`)})});return Object.defineProperty(x,"pluginId",{value:a,enumerable:!0}),x}registerAdapter(e,t){if(e.length===0)throw new r(`an adapter must register at least one provider route`,i.INVALID_ADAPTER);let n=new Set,a=!1;this.commitRoutes(n,this.prepareRoutes(e,t,n));let o=(()=>{if(!a){a=!0;for(let e of n)this.adapters.delete(e);n.clear(),this.emitAdaptersUpdated()}});return o.replace=e=>{if(a)throw new r(`a disposed adapter registration cannot replace its routes`,i.REGISTRATION_DISPOSED);this.commitRoutes(n,this.prepareRoutes(e,t,n))},o}prepareRoutes(e,t,n,a){let s=new Set,c=[];for(let l of e){if(typeof l!=`string`||l.length===0)throw new r(`adapter provider route names must be non-empty strings`,i.INVALID_ADAPTER);if(s.has(l)||this.adapters.has(l)&&!n.has(l))throw new r(`an adapter for provider route "${l}" is already registered`,i.DUPLICATE_ADAPTER);let e=t.providerInfo(l);if(typeof e.id!=`string`||e.id!==l||typeof e.name!=`string`||e.name.length===0)throw new r(`adapter metadata for route "${l}" must preserve its id and carry a non-empty name`,i.INVALID_ADAPTER);s.add(l),c.push({adapter:t,provider:{id:e.id,name:e.name},...a===void 0?{}:a,retryPolicy:t.providerRetryPolicy(l)??o(void 0,`provider "${l}" retryPolicy`)})}return c}commitRoutes(e,t){for(let t of e)this.adapters.delete(t);e.clear();for(let n of t)this.adapters.set(n.provider.id,n),e.add(n.provider.id);this.emitAdaptersUpdated()}use(e){return this.middleware.push(e),()=>{let t=this.middleware.indexOf(e);t>=0&&this.middleware.splice(t,1)}}onAdaptersUpdated(e){return this.listeners.add(e),()=>void this.listeners.delete(e)}emitAdaptersUpdated(){for(let e of[...this.listeners])try{e()}catch{}}listProviders(){return[...this.adapters.values()].map(({provider:e})=>({...e}))}async listModels(e,t){let n=await this.registration(e).adapter.listModels(e,t);return u(e,n,this.maxCatalogModels,this.maxCatalogBytes)}async modelCatalog(e,t={}){let n=await this.registration(e).adapter.modelCatalog(e,t);return d(e,n,this.maxCatalogModels,this.maxCatalogBytes)}async resolveModelInfo(e,t,n){let r=this.registration(e),i=await r.adapter.resolveModel(e,t,n);return c(r.provider.id,t,i,this.maxCatalogBytes,this.defaults)}retryPolicy(e){return this.registration(e).retryPolicy}async prepareCall(t,n,o){let s=this.registration(t.provider),u=await s.adapter.prepareCall(t.provider,t.model,n,o),d=c(s.provider.id,t.model,u.model,this.maxCatalogBytes,this.defaults),f=l(t,d,this.defaults),p=e(structuredClone(f.config)),m=f.context===void 0?void 0:e(structuredClone(f.context)),h=e({...t.maxTokens===void 0&&p.maxTokens!==void 0?{maxTokens:!0}:{}}),g=!1,_=e(structuredClone(d));return Object.freeze({config:p,model:_,retryPolicy:s.retryPolicy,adapterDefaults:h,...m===void 0?{}:{context:m},...f.inputModalities===void 0?{}:{inputModalities:Object.freeze([...f.inputModalities])},stream:(e,t=o)=>{if(g)throw new r(`a prepared call can only be dispatched once`,i.INVALID_PREPARED_CALL);if(!a(e,p))throw new r(`prepared call config changed before adapter dispatch`,i.INVALID_PREPARED_CALL);return g=!0,this.dispatch(e,t,{registration:s,config:p,modelInfo:d,dispatch:(e,t)=>u.stream(e,t)})}})}stream(e,t){return this.dispatch(e,t)}dispatch(e,t,n){let r=`not-sent`,i=n?.registration??this.adapters.get(e.provider);return s({options:e,...i?.family===void 0?{}:{providerFamily:i.family},...i?.pluginId===void 0?{}:{providerPluginId:i.pluginId},...i===void 0?{}:{isRetryable:e=>i.retryPolicy.mode===`always`||i.retryPolicy.retryableCodes.includes(e)},...t===void 0?{}:{context:t},...this.observation===void 0?{}:{defaultObservation:this.observation},resource:this.observationResource,routePresent:n!==void 0||this.adapters.has(e.provider),dispatchState:()=>r,stream:t=>this.dispatchRaw(e,t,()=>{r=`unknown`},n)})}dispatchRaw(e,t,n,r){let i=[...this.middleware],a=()=>{let a=()=>f({options:e,context:t,onDispatch:n,maxCatalogBytes:this.maxCatalogBytes,defaults:this.defaults,registration:e=>this.registration(e),registeredAdapter:e=>this.adapters.get(e)?.adapter,...r===void 0?{}:{prepared:r}});for(let n=i.length-1;n>=0;n--){let r=i[n];if(r===void 0)continue;let o=a;a=()=>r(e,o,t)}return a()};return{async*[Symbol.asyncIterator](){yield*a()}}}registration(e){let t=this.adapters.get(e);if(t===void 0)throw new r(`no adapter registered for provider route "${e}"`,i.NO_ADAPTER);return t}};function g(e,t){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`ModelRegistry ${t} must be a positive safe integer`);return e}function _(t){if(t.contextWindow!==void 0&&g(t.contextWindow,`defaults.contextWindow`),t.maxTokens!==void 0&&g(t.maxTokens,`defaults.maxTokens`),t.inputModalities!==void 0&&(t.inputModalities.length===0||new Set(t.inputModalities).size!==t.inputModalities.length))throw RangeError(`ModelRegistry defaults.inputModalities must be non-empty and unique`);return e({...t.contextWindow===void 0?{}:{contextWindow:t.contextWindow},...t.maxTokens===void 0?{}:{maxTokens:t.maxTokens},...t.inputModalities===void 0?{}:{inputModalities:[...t.inputModalities]}})}export{h as ModelRegistry};
1
+ import{deepFreeze as e}from"../primitives/freeze.js";import"../primitives/version.js";import{PLUGIN_ERROR_CODES as t,PluginError as n}from"../plugin/provider-plugin.js";import{ModelError as r,REGISTRY_ERROR_CODES as i}from"../errors/model-error.js";import{callConfigEquals as a}from"../contract/call-config.js";import{resolveRetryPolicy as o}from"../contract/retry-policy.js";import{createModelCallHandle as s}from"./model-call-handle.js";import{normalizeResolvedModelInfo as c,resolveCallWithModelInfo as l,validateCatalogModels as u,validateModelCatalogSnapshot as d}from"./model-metadata.js";import{streamAdapter as f}from"./model-stream.js";function p(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return!1;let t;try{t=Reflect.get(e,`then`)}catch{return!0}if(typeof t!=`function`)return!1;try{Promise.resolve(e).catch(()=>{})}catch{}return!0}function m(e){try{return p(e())?TypeError(`plugin cleanup must be synchronous`):void 0}catch(e){return e}}var h=class{adapters=new Map;middleware=[];listeners=new Set;plugins=new Map;maxCatalogModels;maxCatalogBytes;observation;observationResource;defaults;constructor(t={}){this.maxCatalogModels=g(t.maxCatalogModels??2048,`maxCatalogModels`),this.maxCatalogBytes=g(t.maxCatalogBytes??4194304,`maxCatalogBytes`),this.observation=t.observation,this.defaults=_(t.defaults??{}),this.observationResource=e(t.observationResource??{sdkName:`ai-agent-sdk`,sdkVersion:`0.1.9`,runtime:`unknown`})}install(e){let a=typeof e?.id==`string`?e.id:``,o=(e,r,i=[])=>{let o=[...r===void 0?[]:[r],...i],s=o.length<=1?o[0]:AggregateError(o,`plugin ${a} install cleanup failed`);throw new n(e,t.INSTALL_FAILED,a,s===void 0?void 0:{cause:s})};(a.trim().length===0||a!==a.trim())&&o(`plugin id must be a non-empty trimmed string`),this.plugins.has(a)&&o(`plugin "${a}" is already installed`),(typeof e.displayName!=`string`||e.displayName.trim().length===0)&&o(`plugin "${a}" displayName must be non-empty`),typeof e.setup!=`function`&&o(`plugin "${a}" setup must be a function`);let s=e.family??a;(typeof s!=`string`||s.trim().length===0||s!==s.trim())&&o(`plugin "${a}" family must be a non-empty trimmed string`);let c=Object.freeze({pluginId:a,family:s}),l=[],u=[],d=!0,f={registerAdapter:(e,t)=>{if(d||o(`plugin "${a}" staging registrar is closed`),e.length===0)throw new r(`an adapter must register at least one provider route`,i.INVALID_ADAPTER);let n={active:!0,routes:[...e],adapter:t},s=new Set(l.filter(e=>e.active).flatMap(e=>e.routes));for(let t of e)if(s.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);this.prepareRoutes(e,t,new Set,c),l.push(n);let u=(()=>{d&&(n.active=!1)});return u.replace=e=>{if(!d||!n.active)throw new r(`a disposed staged registration cannot replace routes`,i.REGISTRATION_DISPOSED);let a=new Set(l.filter(e=>e.active&&e!==n).flatMap(e=>e.routes));for(let t of e)if(a.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);this.prepareRoutes(e,t,new Set,c),n.routes=[...e]},u},use:e=>{if(d||o(`plugin "${a}" staging registrar is closed`),typeof e!=`function`)throw TypeError(`plugin middleware must be a function`);let t={active:!0,middleware:e};return u.push(t),()=>{d&&(t.active=!1)}}},h;try{let t=e.setup(f);p(t)&&o(`plugin "${a}" setup must be synchronous`),t!==void 0&&typeof t!=`function`&&o(`plugin "${a}" setup must be synchronous and return void or cleanup`),h=typeof t==`function`?t:void 0}catch(e){if(e instanceof n&&e.code===t.INSTALL_FAILED)throw e;o(`plugin "${a}" setup failed`,e)}finally{d=!1}let g=[],_=new Set;try{for(let e of l)if(e.active){for(let t of e.routes){if(_.has(t))throw new r(`an adapter for provider route "${t}" is already staged`,i.DUPLICATE_ADAPTER);_.add(t)}g.push(...this.prepareRoutes(e.routes,e.adapter,new Set,c))}}catch(e){let t=[];if(h){let e=m(h);e!==void 0&&t.push(e)}o(`plugin "${a}" commit validation failed`,e,t)}let v=u.filter(e=>e.active).map(e=>e.middleware);for(let e of g)this.adapters.set(e.provider.id,e);this.middleware.push(...v);let y={routes:_,registrations:g,middleware:v,...h===void 0?{}:{cleanup:h}};this.plugins.set(a,y),this.emitAdaptersUpdated();let b=!1,x=(()=>{if(b)return;b=!0,this.plugins.delete(a);for(let e of y.registrations)this.adapters.get(e.provider.id)===e&&this.adapters.delete(e.provider.id);for(let e=y.middleware.length-1;e>=0;e--){let t=y.middleware[e],n=t===void 0?-1:this.middleware.lastIndexOf(t);n>=0&&this.middleware.splice(n,1)}this.emitAdaptersUpdated();let e=[];if(y.cleanup){let t=m(y.cleanup);t!==void 0&&e.push(t)}if(e.length>0)throw new n(`plugin "${a}" cleanup failed`,t.CLEANUP_FAILED,a,{cause:AggregateError(e,`plugin "${a}" cleanup failed`)})});return Object.defineProperty(x,"pluginId",{value:a,enumerable:!0}),x}registerAdapter(e,t){if(e.length===0)throw new r(`an adapter must register at least one provider route`,i.INVALID_ADAPTER);let n=new Set,a=!1;this.commitRoutes(n,this.prepareRoutes(e,t,n));let o=(()=>{if(!a){a=!0;for(let e of n)this.adapters.delete(e);n.clear(),this.emitAdaptersUpdated()}});return o.replace=e=>{if(a)throw new r(`a disposed adapter registration cannot replace its routes`,i.REGISTRATION_DISPOSED);this.commitRoutes(n,this.prepareRoutes(e,t,n))},o}prepareRoutes(e,t,n,a){let s=new Set,c=[];for(let l of e){if(typeof l!=`string`||l.length===0)throw new r(`adapter provider route names must be non-empty strings`,i.INVALID_ADAPTER);if(s.has(l)||this.adapters.has(l)&&!n.has(l))throw new r(`an adapter for provider route "${l}" is already registered`,i.DUPLICATE_ADAPTER);let e=t.providerInfo(l);if(typeof e.id!=`string`||e.id!==l||typeof e.name!=`string`||e.name.length===0)throw new r(`adapter metadata for route "${l}" must preserve its id and carry a non-empty name`,i.INVALID_ADAPTER);s.add(l),c.push({adapter:t,provider:{id:e.id,name:e.name},...a===void 0?{}:a,retryPolicy:t.providerRetryPolicy(l)??o(void 0,`provider "${l}" retryPolicy`)})}return c}commitRoutes(e,t){for(let t of e)this.adapters.delete(t);e.clear();for(let n of t)this.adapters.set(n.provider.id,n),e.add(n.provider.id);this.emitAdaptersUpdated()}use(e){return this.middleware.push(e),()=>{let t=this.middleware.indexOf(e);t>=0&&this.middleware.splice(t,1)}}onAdaptersUpdated(e){return this.listeners.add(e),()=>void this.listeners.delete(e)}emitAdaptersUpdated(){for(let e of[...this.listeners])try{e()}catch{}}listProviders(){return[...this.adapters.values()].map(({provider:e})=>({...e}))}async listModels(e,t){let n=await this.registration(e).adapter.listModels(e,t);return u(e,n,this.maxCatalogModels,this.maxCatalogBytes)}async modelCatalog(e,t={}){let n=await this.registration(e).adapter.modelCatalog(e,t);return d(e,n,this.maxCatalogModels,this.maxCatalogBytes)}async resolveModelInfo(e,t,n){let r=this.registration(e),i=await r.adapter.resolveModel(e,t,n);return c(r.provider.id,t,i,this.maxCatalogBytes,this.defaults)}retryPolicy(e){return this.registration(e).retryPolicy}async prepareCall(t,n,o){let s=this.registration(t.provider),u=await s.adapter.prepareCall(t.provider,t.model,n,o),d=c(s.provider.id,t.model,u.model,this.maxCatalogBytes,this.defaults),f=l(t,d,this.defaults),p=e(structuredClone(f.config)),m=f.context===void 0?void 0:e(structuredClone(f.context)),h=e({...t.maxTokens===void 0&&p.maxTokens!==void 0?{maxTokens:!0}:{}}),g=!1,_=e(structuredClone(d));return Object.freeze({config:p,model:_,retryPolicy:s.retryPolicy,adapterDefaults:h,...m===void 0?{}:{context:m},...f.inputModalities===void 0?{}:{inputModalities:Object.freeze([...f.inputModalities])},stream:(e,t=o)=>{if(g)throw new r(`a prepared call can only be dispatched once`,i.INVALID_PREPARED_CALL);if(!a(e,p))throw new r(`prepared call config changed before adapter dispatch`,i.INVALID_PREPARED_CALL);return g=!0,this.dispatch(e,t,{registration:s,config:p,modelInfo:d,dispatch:(e,t)=>u.stream(e,t)})}})}stream(e,t){return this.dispatch(e,t)}dispatch(e,t,n){let r=`not-sent`,i=n?.registration??this.adapters.get(e.provider);return s({options:e,...i?.family===void 0?{}:{providerFamily:i.family},...i?.pluginId===void 0?{}:{providerPluginId:i.pluginId},...i===void 0?{}:{isRetryable:e=>i.retryPolicy.mode===`always`||i.retryPolicy.retryableCodes.includes(e)},...t===void 0?{}:{context:t},...this.observation===void 0?{}:{defaultObservation:this.observation},resource:this.observationResource,routePresent:n!==void 0||this.adapters.has(e.provider),dispatchState:()=>r,stream:t=>this.dispatchRaw(e,t,()=>{r=`unknown`},n)})}dispatchRaw(e,t,n,r){let i=[...this.middleware],a=()=>{let a=()=>f({options:e,context:t,onDispatch:n,maxCatalogBytes:this.maxCatalogBytes,defaults:this.defaults,registration:e=>this.registration(e),registeredAdapter:e=>this.adapters.get(e)?.adapter,...r===void 0?{}:{prepared:r}});for(let n=i.length-1;n>=0;n--){let r=i[n];if(r===void 0)continue;let o=a;a=()=>r(e,o,t)}return a()};return{async*[Symbol.asyncIterator](){yield*a()}}}registration(e){let t=this.adapters.get(e);if(t===void 0)throw new r(`no adapter registered for provider route "${e}"`,i.NO_ADAPTER);return t}};function g(e,t){if(!Number.isSafeInteger(e)||e<1)throw RangeError(`ModelRegistry ${t} must be a positive safe integer`);return e}function _(t){if(t.contextWindow!==void 0&&g(t.contextWindow,`defaults.contextWindow`),t.maxTokens!==void 0&&g(t.maxTokens,`defaults.maxTokens`),t.inputModalities!==void 0&&(t.inputModalities.length===0||new Set(t.inputModalities).size!==t.inputModalities.length))throw RangeError(`ModelRegistry defaults.inputModalities must be non-empty and unique`);return e({...t.contextWindow===void 0?{}:{contextWindow:t.contextWindow},...t.maxTokens===void 0?{}:{maxTokens:t.maxTokens},...t.inputModalities===void 0?{}:{inputModalities:[...t.inputModalities]}})}export{h as ModelRegistry};
2
2
  //# sourceMappingURL=registry.js.map
@@ -28,6 +28,21 @@ interface WithRetryOptions {
28
28
  onRetry?: (attempt: RetryAttempt) => void;
29
29
  /** Maximum wait while closing an unsuccessful attempt. Defaults to 30s. */
30
30
  teardownTimeoutMs?: number;
31
+ /**
32
+ * Keep an attempt retryable while it has only streamed reasoning.
33
+ *
34
+ * Reasoning models open a reasoning block before any answer, so by default
35
+ * the retry window closes there and a provider failure while the model is
36
+ * still thinking cannot be retried. With this on, reasoning chunks are held
37
+ * back until the first answer or tool chunk (or the end), then released in
38
+ * order; a failure before that discards them and retries cleanly, so the
39
+ * consumer never sees a failed attempt's reasoning twice. The cost is that
40
+ * reasoning is not shown live. `true` holds up to 4096 chunks; past the cap
41
+ * the attempt is forwarded as usual and retry stops applying.
42
+ */
43
+ bufferReasoningPrefix?: boolean | {
44
+ readonly maxChunks: number;
45
+ };
31
46
  }
32
47
  /**
33
48
  * Wrap an adapter so eligible transient failures are retried with bounded
@@ -1 +1 @@
1
- {"version":3,"file":"with-retry.d.ts","names":[],"sources":["../../src/runtime/with-retry.ts"],"mappings":";;;;;UAkCiB;;WAEN;;WAEA;;WAEA;;WAEA,SAAS;;WAET;;;UAIM;;;;;EAKf,SAAS;;EAET;;EAEA,WAAW,SAAS;;EAEpB;;;;;;;;;;;;iBAqTc,UAAU,SAAS,cAAc,UAAS,mBAAwB"}
1
+ {"version":3,"file":"with-retry.d.ts","names":[],"sources":["../../src/runtime/with-retry.ts"],"mappings":";;;;;UAkCiB;;WAEN;;WAEA;;WAEA;;WAEA,SAAS;;WAET;;;UAIM;;;;;EAKf,SAAS;;EAET;;EAEA,WAAW,SAAS;;EAEpB;;;;;;;;;;;;;EAaA;aAA6C;;;;;;;;;;;;;iBA+W/B,UAAU,SAAS,cAAc,UAAS,mBAAwB"}
@@ -1,2 +1,2 @@
1
- import{waitForSettlement as e}from"../async/settlement.js";import{MODEL_ERROR_CODES as t,ModelError as n}from"../errors/model-error.js";import{normalizeModelFailure as r}from"../errors/failure.js";import{ModelAdapter as i}from"../contract/adapter.js";import{backoffDelayMs as a,resolveRetryPolicy as o}from"../contract/retry-policy.js";function s(e,t,n,r){let i=t.providerRetryAfterMs;return i!==void 0&&Number.isFinite(i)&&i>0?i<=e.maxDelayMs?i:e.mode===`always`?a(e,n,r):`give-up`:a(e,n,r)}function c(e,t){return t?.aborted===!0?Promise.resolve(!1):new Promise(n=>{let r=()=>{clearTimeout(i),n(!1)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!0)},e);t?.addEventListener(`abort`,r,{once:!0})})}var l=class extends i{inner;options;constructor(e,t){super(),this.inner=e,this.options=t}providerInfo(e){return this.inner.providerInfo(e)}providerRetryPolicy(e){return this.inner.providerRetryPolicy(e)}listModels(e){return this.inner.listModels(e)}resolveModel(e,t,n){return this.inner.resolveModel(e,t,n)}async prepareCall(e,t,n,r){let i=await this.inner.prepareCall(e,t,n,r),a=this.policyFor(e);return{model:i.model,stream:(e,t=r)=>this.retryStream(e,e=>i.stream(e,t),a,t)}}stream(e,t){return this.retryStream(e,e=>this.inner.stream(e,t),this.policyFor(e.provider),t)}policyFor(e){return this.options.policy===void 0?this.inner.providerRetryPolicy(e)??o(void 0,`withRetry("${e}").policy`):o(this.options.policy,`withRetry("${e}").policy`)}async*retryStream(e,n,r,i){if(r.mode===`always`&&e.signal===void 0){yield{type:`finish`,reason:{kind:`error`,failure:{message:`an always retry policy requires an AbortSignal or deadline`,code:t.INVALID_REQUEST}}};return}let a=this.options.random??Math.random,o=0;for(;;){let l=yield*this.runAttempt(e,n);if(l.kind===`forward`){yield*l.chunks;return}let u=l.failure;if(e.signal?.aborted===!0||u.code===t.ABORTED){yield{type:`finish`,reason:{kind:`aborted`,failure:u}};return}if(!(r.mode===`always`||r.retryableCodes.includes(u.code)&&o<r.maxRetries)){yield{type:`finish`,reason:{kind:`error`,failure:u}};return}let d=s(r,u,o+1,a);if(d===`give-up`){yield{type:`finish`,reason:{kind:`error`,failure:u}};return}o+=1,i?.recordProviderRetry?.({nextAttemptNumber:o+1,delayMs:d,failureCode:u.code});try{this.options.onRetry?.({provider:e.provider,attempt:o,maxRetries:r.mode===`normal`?r.maxRetries:void 0,failure:u,delayMs:d})}catch{}if(!await c(d,e.signal)){yield{type:`finish`,reason:{kind:`aborted`,failure:{message:`model call aborted while waiting to retry`,code:t.ABORTED}}};return}}}async*runAttempt(e,n){let i;try{i=n(e)[Symbol.asyncIterator]()}catch(e){return{kind:`retryable`,failure:r(e)}}let a;try{for(a=await i.next();!a.done&&a.value.type===`usage-progress`;){let e=!1;try{yield a.value,e=!0}finally{e||await f(i,this.options.teardownTimeoutMs??3e4)}a=await i.next()}}catch(e){return await f(i,this.options.teardownTimeoutMs??3e4),{kind:`retryable`,failure:r(e)}}if(a.done===!0)return{kind:`retryable`,failure:{message:`the adapter produced no chunks`,code:t.UNKNOWN}};let o=a.value;return o.type===`finish`&&o.reason.kind===`error`?(await f(i,this.options.teardownTimeoutMs??3e4),{kind:`retryable`,failure:o.reason.failure}):{kind:`forward`,chunks:d(o,i,this.options.teardownTimeoutMs??3e4)}}};function u(e,t){if(!Number.isFinite(e)||e<=0)throw RangeError(`${t} must be a positive finite number`);return e}async function*d(e,t,n){let r=!1;try{for(yield e;;){let e=await t.next();if(e.done===!0){r=!0;return}yield e.value}}finally{r||await f(t,n)}}async function f(r,i){let a=r.return?.();if(a!==void 0&&!await e(Promise.resolve(a),u(i,`withRetry teardownTimeoutMs`)))throw new n(`retry attempt teardown exceeded ${i}ms`,t.TEARDOWN_TIMEOUT)}function p(e,t={}){return new l(e,t)}export{p as withRetry};
1
+ import{waitForSettlement as e}from"../async/settlement.js";import{MODEL_ERROR_CODES as t,ModelError as n}from"../errors/model-error.js";import{normalizeModelFailure as r}from"../errors/failure.js";import{ModelAdapter as i}from"../contract/adapter.js";import{backoffDelayMs as a,resolveRetryPolicy as o}from"../contract/retry-policy.js";function s(e,t,n,r){let i=t.providerRetryAfterMs;return i!==void 0&&Number.isFinite(i)&&i>0?i<=e.maxDelayMs?i:e.mode===`always`?a(e,n,r):`give-up`:a(e,n,r)}function c(e,t){return t?.aborted===!0?Promise.resolve(!1):new Promise(n=>{let r=()=>{clearTimeout(i),n(!1)},i=setTimeout(()=>{t?.removeEventListener(`abort`,r),n(!0)},e);t?.addEventListener(`abort`,r,{once:!0})})}var l=class extends i{inner;options;constructor(e,t){super(),this.inner=e,this.options=t}providerInfo(e){return this.inner.providerInfo(e)}providerRetryPolicy(e){return this.inner.providerRetryPolicy(e)}listModels(e){return this.inner.listModels(e)}resolveModel(e,t,n){return this.inner.resolveModel(e,t,n)}async prepareCall(e,t,n,r){let i=await this.inner.prepareCall(e,t,n,r),a=this.policyFor(e);return{model:i.model,stream:(e,t=r)=>this.retryStream(e,e=>i.stream(e,t),a,t)}}stream(e,t){return this.retryStream(e,e=>this.inner.stream(e,t),this.policyFor(e.provider),t)}policyFor(e){return this.options.policy===void 0?this.inner.providerRetryPolicy(e)??o(void 0,`withRetry("${e}").policy`):o(this.options.policy,`withRetry("${e}").policy`)}async*retryStream(e,n,r,i){if(r.mode===`always`&&e.signal===void 0){yield{type:`finish`,reason:{kind:`error`,failure:{message:`an always retry policy requires an AbortSignal or deadline`,code:t.INVALID_REQUEST}}};return}let a=this.options.random??Math.random,o=0;for(;;){let l=yield*this.runAttempt(e,n);if(l.kind===`forward`){yield*l.chunks;return}let u=l.failure;if(e.signal?.aborted===!0||u.code===t.ABORTED){yield{type:`finish`,reason:{kind:`aborted`,failure:u}};return}if(!(r.mode===`always`||r.retryableCodes.includes(u.code)&&o<r.maxRetries)){yield{type:`finish`,reason:{kind:`error`,failure:u}};return}let d=s(r,u,o+1,a);if(d===`give-up`){yield{type:`finish`,reason:{kind:`error`,failure:u}};return}o+=1,i?.recordProviderRetry?.({nextAttemptNumber:o+1,delayMs:d,failureCode:u.code});try{this.options.onRetry?.({provider:e.provider,attempt:o,maxRetries:r.mode===`normal`?r.maxRetries:void 0,failure:u,delayMs:d})}catch{}if(!await c(d,e.signal)){yield{type:`finish`,reason:{kind:`aborted`,failure:{message:`model call aborted while waiting to retry`,code:t.ABORTED}}};return}}}async*runAttempt(e,n){let i=d(this.options.bufferReasoningPrefix),a;try{a=n(e)[Symbol.asyncIterator]()}catch(e){return{kind:`retryable`,failure:r(e)}}let o;try{for(o=await a.next();!o.done&&o.value.type===`usage-progress`;){let e=!1;try{yield o.value,e=!0}finally{e||await m(a,this.options.teardownTimeoutMs??3e4)}o=await a.next()}}catch(e){return await m(a,this.options.teardownTimeoutMs??3e4),{kind:`retryable`,failure:r(e)}}if(o.done===!0)return{kind:`retryable`,failure:{message:`the adapter produced no chunks`,code:t.UNKNOWN}};let s=o.value;if(s.type===`finish`&&s.reason.kind===`error`)return await m(a,this.options.teardownTimeoutMs??3e4),{kind:`retryable`,failure:s.reason.failure};let c=[];if(i>0){let e=new Set,t=!1;try{for(;f(s,e)&&c.length<i;){c.push(s);let e=await a.next();for(;!e.done&&e.value.type===`usage-progress`;){let t=!1;try{yield e.value,t=!0}finally{t||await m(a,this.options.teardownTimeoutMs??3e4)}e=await a.next()}if(e.done===!0){t=!0;break}if(s=e.value,s.type===`finish`&&s.reason.kind===`error`)return await m(a,this.options.teardownTimeoutMs??3e4),{kind:`retryable`,failure:s.reason.failure}}}catch(e){return await m(a,this.options.teardownTimeoutMs??3e4),{kind:`retryable`,failure:r(e)}}if(t)return{kind:`forward`,chunks:p(c,void 0,a,this.options.teardownTimeoutMs??3e4)}}return{kind:`forward`,chunks:p(c,s,a,this.options.teardownTimeoutMs??3e4)}}};function u(e,t){if(!Number.isFinite(e)||e<=0)throw RangeError(`${t} must be a positive finite number`);return e}function d(e){if(e===void 0||e===!1)return 0;if(e===!0)return 4096;if(!Number.isSafeInteger(e.maxChunks)||e.maxChunks<1)throw RangeError(`bufferReasoningPrefix.maxChunks must be a positive safe integer`);return e.maxChunks}function f(e,t){return e.type===`reasoning-delta`?!0:e.type===`block-start`&&e.blockType===`reasoning`?(t.add(e.index),!0):e.type===`block-end`&&(e.block.type===`reasoning`||t.has(e.index))}async function*p(e,t,n,r){let i=!1;try{for(let t of e)yield t;for(t!==void 0&&(yield t);;){let e=await n.next();if(e.done===!0){i=!0;return}yield e.value}}finally{i||await m(n,r)}}async function m(r,i){let a=r.return?.();if(a!==void 0&&!await e(Promise.resolve(a),u(i,`withRetry teardownTimeoutMs`)))throw new n(`retry attempt teardown exceeded ${i}ms`,t.TEARDOWN_TIMEOUT)}function h(e,t={}){return new l(e,t)}export{h as withRetry};
2
2
  //# sourceMappingURL=with-retry.js.map