@alvin0/ai-agent-sdk-core 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/dist/agent/define/session/model-config.js +1 -1
  2. package/dist/agent/define/session/model-config.js.map +1 -1
  3. package/dist/agent/define/session/types.d.ts +21 -0
  4. package/dist/agent/define/session/types.d.ts.map +1 -1
  5. package/dist/agent/define/session.d.ts +2 -0
  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/history/validation.js +1 -1
  10. package/dist/agent/history/validation.js.map +1 -1
  11. package/dist/agent/loop/events.d.ts +5 -0
  12. package/dist/agent/loop/events.d.ts.map +1 -1
  13. package/dist/agent/loop/schedule.js +1 -1
  14. package/dist/agent/loop/schedule.js.map +1 -1
  15. package/dist/agent/loop/turn/model-round.js +1 -1
  16. package/dist/agent/loop/turn/model-round.js.map +1 -1
  17. package/dist/agent/loop/turn/types.d.ts +2 -0
  18. package/dist/agent/loop/turn/types.d.ts.map +1 -1
  19. package/dist/agent/loop/turn/validation.js +1 -1
  20. package/dist/agent/loop/turn/validation.js.map +1 -1
  21. package/dist/agent/memory/compaction.d.ts +10 -1
  22. package/dist/agent/memory/compaction.d.ts.map +1 -1
  23. package/dist/agent/memory/compaction.js +2 -2
  24. package/dist/agent/memory/compaction.js.map +1 -1
  25. package/dist/agent/memory/token-estimator.js +1 -1
  26. package/dist/agent/memory/token-estimator.js.map +1 -1
  27. package/dist/agent/mode/run-agent.js +1 -1
  28. package/dist/agent/mode/run-agent.js.map +1 -1
  29. package/dist/composition/agent/options.js +1 -1
  30. package/dist/composition/agent/options.js.map +1 -1
  31. package/dist/composition/agent/session.js +1 -1
  32. package/dist/composition/agent/session.js.map +1 -1
  33. package/dist/composition/agent/types.d.ts +43 -1
  34. package/dist/composition/agent/types.d.ts.map +1 -1
  35. package/dist/composition/common/errors.d.ts.map +1 -1
  36. package/dist/composition/common/errors.js +1 -1
  37. package/dist/composition/common/errors.js.map +1 -1
  38. package/dist/composition/embedding/activation.js +2 -0
  39. package/dist/composition/embedding/activation.js.map +1 -0
  40. package/dist/composition/embedding/cache.js +2 -0
  41. package/dist/composition/embedding/cache.js.map +1 -0
  42. package/dist/composition/embedding/definition.d.ts +7 -0
  43. package/dist/composition/embedding/definition.d.ts.map +1 -0
  44. package/dist/composition/embedding/definition.js +2 -0
  45. package/dist/composition/embedding/definition.js.map +1 -0
  46. package/dist/composition/embedding/handle.js +2 -0
  47. package/dist/composition/embedding/handle.js.map +1 -0
  48. package/dist/composition/embedding/limiter.js +2 -0
  49. package/dist/composition/embedding/limiter.js.map +1 -0
  50. package/dist/composition/embedding/manager.js +2 -0
  51. package/dist/composition/embedding/manager.js.map +1 -0
  52. package/dist/composition/embedding/observation.js +2 -0
  53. package/dist/composition/embedding/observation.js.map +1 -0
  54. package/dist/composition/embedding/planner.js +2 -0
  55. package/dist/composition/embedding/planner.js.map +1 -0
  56. package/dist/composition/embedding/plugin-types.d.ts +48 -0
  57. package/dist/composition/embedding/plugin-types.d.ts.map +1 -0
  58. package/dist/composition/embedding/plugin-types.js +2 -0
  59. package/dist/composition/embedding/plugin-types.js.map +1 -0
  60. package/dist/composition/embedding/preflight.js +2 -0
  61. package/dist/composition/embedding/preflight.js.map +1 -0
  62. package/dist/composition/embedding/registry.js +2 -0
  63. package/dist/composition/embedding/registry.js.map +1 -0
  64. package/dist/composition/embedding/retry.js +2 -0
  65. package/dist/composition/embedding/retry.js.map +1 -0
  66. package/dist/composition/embedding/usage.js +2 -0
  67. package/dist/composition/embedding/usage.js.map +1 -0
  68. package/dist/composition/lifecycle/types.d.ts +5 -1
  69. package/dist/composition/lifecycle/types.d.ts.map +1 -1
  70. package/dist/composition/lifecycle/types.js +1 -1
  71. package/dist/composition/lifecycle/types.js.map +1 -1
  72. package/dist/composition/preflight.js +1 -1
  73. package/dist/composition/preflight.js.map +1 -1
  74. package/dist/composition/provider/activation.js +1 -1
  75. package/dist/composition/provider/activation.js.map +1 -1
  76. package/dist/composition/provider/model-selection.js +1 -1
  77. package/dist/composition/provider/model-selection.js.map +1 -1
  78. package/dist/composition/provider/preflight.js +1 -1
  79. package/dist/composition/provider/preflight.js.map +1 -1
  80. package/dist/composition/runtime/owner.js +1 -1
  81. package/dist/composition/runtime/owner.js.map +1 -1
  82. package/dist/composition/runtime/public.js +1 -1
  83. package/dist/composition/runtime/public.js.map +1 -1
  84. package/dist/composition/runtime/types.d.ts +25 -2
  85. package/dist/composition/runtime/types.d.ts.map +1 -1
  86. package/dist/composition/startup.js +1 -1
  87. package/dist/composition/startup.js.map +1 -1
  88. package/dist/composition/team/options.js +1 -1
  89. package/dist/composition/team/options.js.map +1 -1
  90. package/dist/composition/team/runtime.js +1 -1
  91. package/dist/composition/team/runtime.js.map +1 -1
  92. package/dist/composition/team/types.d.ts +3 -0
  93. package/dist/composition/team/types.d.ts.map +1 -1
  94. package/dist/contract/generate-options.d.ts +2 -0
  95. package/dist/contract/generate-options.d.ts.map +1 -1
  96. package/dist/contract/model-info.d.ts +12 -2
  97. package/dist/contract/model-info.d.ts.map +1 -1
  98. package/dist/embedding/adapter.d.ts +104 -0
  99. package/dist/embedding/adapter.d.ts.map +1 -0
  100. package/dist/embedding/adapter.js +2 -0
  101. package/dist/embedding/adapter.js.map +1 -0
  102. package/dist/embedding/catalog.d.ts +82 -0
  103. package/dist/embedding/catalog.d.ts.map +1 -0
  104. package/dist/embedding/catalog.js +2 -0
  105. package/dist/embedding/catalog.js.map +1 -0
  106. package/dist/embedding/errors.d.ts +98 -0
  107. package/dist/embedding/errors.d.ts.map +1 -0
  108. package/dist/embedding/errors.js +2 -0
  109. package/dist/embedding/errors.js.map +1 -0
  110. package/dist/embedding/handle.d.ts +76 -0
  111. package/dist/embedding/handle.d.ts.map +1 -0
  112. package/dist/embedding/limits.d.ts +47 -0
  113. package/dist/embedding/limits.d.ts.map +1 -0
  114. package/dist/embedding/limits.js +2 -0
  115. package/dist/embedding/limits.js.map +1 -0
  116. package/dist/embedding/profile.d.ts +89 -0
  117. package/dist/embedding/profile.d.ts.map +1 -0
  118. package/dist/embedding/profile.js +2 -0
  119. package/dist/embedding/profile.js.map +1 -0
  120. package/dist/embedding/purpose.d.ts +37 -0
  121. package/dist/embedding/purpose.d.ts.map +1 -0
  122. package/dist/embedding/request.d.ts +54 -0
  123. package/dist/embedding/request.d.ts.map +1 -0
  124. package/dist/embedding/request.js +2 -0
  125. package/dist/embedding/request.js.map +1 -0
  126. package/dist/embedding/result.d.ts +50 -0
  127. package/dist/embedding/result.d.ts.map +1 -0
  128. package/dist/embedding/usage.d.ts +64 -0
  129. package/dist/embedding/usage.d.ts.map +1 -0
  130. package/dist/embedding/usage.js +2 -0
  131. package/dist/embedding/usage.js.map +1 -0
  132. package/dist/embedding/validation.d.ts +68 -0
  133. package/dist/embedding/validation.d.ts.map +1 -0
  134. package/dist/embedding/validation.js +2 -0
  135. package/dist/embedding/validation.js.map +1 -0
  136. package/dist/embedding.d.ts +12 -0
  137. package/dist/embedding.js +1 -0
  138. package/dist/index.d.ts +6 -3
  139. package/dist/index.js +1 -1
  140. package/dist/message/content.d.ts +71 -1
  141. package/dist/message/content.d.ts.map +1 -1
  142. package/dist/message/projection.d.ts +28 -2
  143. package/dist/message/projection.d.ts.map +1 -1
  144. package/dist/message/projection.js +1 -1
  145. package/dist/message/projection.js.map +1 -1
  146. package/dist/observability/bus.js +1 -1
  147. package/dist/observation/event.d.ts +1 -1
  148. package/dist/observation/event.d.ts.map +1 -1
  149. package/dist/observation/event.js.map +1 -1
  150. package/dist/observation/port.d.ts +1 -1
  151. package/dist/observation/port.d.ts.map +1 -1
  152. package/dist/observation/port.js.map +1 -1
  153. package/dist/observation/privacy.js +1 -1
  154. package/dist/observation/privacy.js.map +1 -1
  155. package/dist/observation/report.d.ts +2 -0
  156. package/dist/observation/report.d.ts.map +1 -1
  157. package/dist/observation/report.js.map +1 -1
  158. package/dist/primitives/version.d.ts +1 -1
  159. package/dist/primitives/version.js +1 -1
  160. package/dist/primitives/version.js.map +1 -1
  161. package/dist/provider.d.ts +3 -1
  162. package/dist/provider.js +1 -1
  163. package/dist/runtime/model-call-handle.js +1 -1
  164. package/dist/runtime/model-call-handle.js.map +1 -1
  165. package/dist/runtime/model-metadata.js +1 -1
  166. package/dist/runtime/model-metadata.js.map +1 -1
  167. package/dist/runtime/model-stream.js +1 -1
  168. package/dist/runtime/model-stream.js.map +1 -1
  169. package/dist/runtime/registry.js +1 -1
  170. package/dist/runtime/with-retry.d.ts.map +1 -1
  171. package/dist/runtime/with-retry.js +1 -1
  172. package/dist/runtime/with-retry.js.map +1 -1
  173. package/dist/stream/assembler.d.ts.map +1 -1
  174. package/dist/stream/assembler.js +1 -1
  175. package/dist/stream/assembler.js.map +1 -1
  176. package/dist/stream/chunk.d.ts +6 -0
  177. package/dist/stream/chunk.d.ts.map +1 -1
  178. package/package.json +6 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.js","names":[],"sources":["../../src/embedding/validation.ts"],"sourcesContent":["/**\n * Pre-dispatch request validation and provider-response validation.\n *\n * Two rules shape everything here:\n *\n * 1. **Declared-only rejection (DD-6).** A check rejects ONLY when the matching\n * catalog capability makes a positive claim and the value violates it. An\n * `unknown` capability states nothing, so it can never become a reason to\n * reject — that is what keeps a model id outside the catalog usable\n * (Requirements 9.1, 9.2, 10.3).\n * 2. **Zero provider attempts.** Every failure raised by\n * {@link validatePreDispatch} happens before the first `Physical_Batch` is\n * dispatched, and carries `itemIndexes` plus the applied `limit` so a caller\n * can re-chunk the offending inputs instead of the whole call (Requirement 3.6).\n *\n * `estimateTokens` is deliberately NOT defined in this module. The length check\n * reads `prepared.limits.estimateTokens` — the exact function the batch planner\n * uses — so a split and a length check can never disagree about the size of the\n * same text.\n *\n * @module ai-agent-sdk/core/embedding/validation\n */\n\nimport type { PreparedEmbeddingCall } from './adapter.ts'\nimport { EMBEDDING_ERROR_CODES, EmbeddingError } from './errors.ts'\nimport type { EmbeddingCapability } from './catalog.ts'\nimport type { EmbeddingProfile, EmbeddingSpaceId } from './profile.ts'\nimport { isSpaceCompatible } from './profile.ts'\nimport type { EmbeddingPurpose } from './purpose.ts'\nimport type { EmbeddingBatchRequest, EmbeddingItem, EmbeddingTruncation } from './request.ts'\nimport type { EmbeddingBatchResult } from './result.ts'\n\n/** The two legal {@link EmbeddingPurpose} values, as a runtime guard set. */\nconst VALID_PURPOSES: readonly string[] = Object.freeze([\n 'retrieval-query',\n 'retrieval-document',\n])\n\n/**\n * One `Logical_Call` as it stands just before the first dispatch.\n *\n * Deliberately NOT an {@link EmbeddingBatchRequest}: validation runs once per\n * logical call, over ALL items, before any batch exists.\n */\nexport interface PreDispatchRequest {\n readonly purpose: EmbeddingPurpose\n /** Every item of the logical call, in input order. */\n readonly items: readonly EmbeddingItem[]\n /** Caller-requested width; absent means the model default. */\n readonly dimensions?: number\n /** Resolved truncation preference. */\n readonly truncation: EmbeddingTruncation\n /** Space the caller demands; incompatibility is a rejection. */\n readonly expectedSpace?: EmbeddingSpaceId\n /**\n * The profile behind {@link expectedSpace}, when the caller has it.\n *\n * Present ⇒ compatibility is decided by {@link isSpaceCompatible}; absent ⇒ by\n * canonical `Space_Id` equality. Both answer the same question, since the\n * `Space_Id` is derived from exactly the components that decide compatibility.\n */\n readonly expectedProfile?: EmbeddingProfile\n /**\n * Whether the route has a truncation parameter at all.\n *\n * `'unsupported'` is the route positively stating the provider exposes no such\n * parameter, which is the only state that rejects `truncation: 'allow'`.\n * `'unknown'` never rejects.\n */\n readonly truncationSupport?: EmbeddingCapability<boolean>\n}\n\n/** Concatenated effective text of one item, in content-part order. */\nfunction itemText(item: EmbeddingItem): string {\n let text = ''\n for (const part of item.contentParts) {\n if (part.type === 'text') text += part.text\n }\n return text\n}\n\n/** Rejects a purpose outside the two declared values (Requirement 7.2). */\nfunction checkPurpose(request: PreDispatchRequest, prepared: PreparedEmbeddingCall): void {\n if (VALID_PURPOSES.includes(request.purpose)) return\n throw new EmbeddingError(\n 'Embedding purpose must be \"retrieval-query\" or \"retrieval-document\"',\n EMBEDDING_ERROR_CODES.REQUEST_INVALID,\n routeFacts(prepared),\n )\n}\n\n/**\n * Rejects an empty call, an item with no content parts, and an item whose\n * effective text is empty. All three are malformed at the SDK boundary, not\n * questions for the provider.\n */\nfunction checkItems(request: PreDispatchRequest, prepared: PreparedEmbeddingCall): void {\n if (request.items.length === 0) {\n throw new EmbeddingError(\n 'Embedding request carries no input values',\n EMBEDDING_ERROR_CODES.REQUEST_INVALID,\n routeFacts(prepared),\n )\n }\n const empty: number[] = []\n for (const item of request.items) {\n if (item.contentParts.length === 0 || itemText(item).length === 0) empty.push(item.index)\n }\n if (empty.length > 0) {\n throw new EmbeddingError(\n `Embedding input is empty at ${empty.length} item(s)`,\n EMBEDDING_ERROR_CODES.REQUEST_INVALID,\n { ...routeFacts(prepared), itemIndexes: empty },\n )\n }\n}\n\n/**\n * Rejects a requested width the route declares it does not offer.\n *\n * A non-integer or non-positive width is malformed regardless of the catalog; a\n * width outside a `supported` list is a capability violation. When the catalog\n * says `unknown`, the width goes to the provider unchallenged (DD-6).\n */\nfunction checkDimensions(request: PreDispatchRequest, prepared: PreparedEmbeddingCall): void {\n const requested = request.dimensions\n if (requested === undefined) return\n if (!Number.isInteger(requested) || requested <= 0) {\n throw new EmbeddingError(\n 'Embedding dimensions must be a positive integer',\n EMBEDDING_ERROR_CODES.REQUEST_INVALID,\n routeFacts(prepared),\n )\n }\n const declared = prepared.model.dimensions\n if (declared.state !== 'supported') return\n if (declared.value.includes(requested)) return\n throw new EmbeddingError(\n `Embedding model does not support ${requested} dimensions`,\n EMBEDDING_ERROR_CODES.DIMENSIONS_UNSUPPORTED,\n routeFacts(prepared),\n )\n}\n\n/**\n * Rejects inputs longer than a DECLARED per-input token ceiling.\n *\n * The estimate comes from `prepared.limits.estimateTokens`, the planner's own\n * function. The check runs only when `maxInputTokens` is `supported`: with an\n * `unknown` ceiling there is no bound to measure against, and the estimator's\n * batching fallbacks are not a claim the provider made.\n */\nfunction checkInputLength(request: PreDispatchRequest, prepared: PreparedEmbeddingCall): void {\n const declared = prepared.model.maxInputTokens\n if (declared.state !== 'supported') return\n const limit = declared.value\n if (!Number.isFinite(limit) || limit <= 0) return\n const oversized: number[] = []\n for (const item of request.items) {\n if (prepared.limits.estimateTokens(itemText(item)) > limit) oversized.push(item.index)\n }\n if (oversized.length === 0) return\n throw new EmbeddingError(\n `Embedding input exceeds the declared limit of ${limit} tokens`,\n EMBEDDING_ERROR_CODES.INPUT_TOO_LARGE,\n { ...routeFacts(prepared), itemIndexes: oversized, limit },\n )\n}\n\n/**\n * Rejects a call whose vectors would not land in the space the caller expects.\n *\n * Compatibility is the declared identity's business, never a comparison of\n * dimension counts or model names.\n */\nfunction checkSpace(request: PreDispatchRequest, prepared: PreparedEmbeddingCall): void {\n const expected = request.expectedSpace\n const expectedProfile = request.expectedProfile\n if (expected === undefined && expectedProfile === undefined) return\n const compatible =\n expectedProfile === undefined\n ? expected === prepared.spaceId\n : isSpaceCompatible(expectedProfile, prepared.profile)\n if (compatible) return\n throw new EmbeddingError(\n 'Expected embedding space is incompatible with the prepared call',\n EMBEDDING_ERROR_CODES.SPACE_INCOMPATIBLE,\n { ...routeFacts(prepared), space: prepared.spaceId },\n )\n}\n\n/**\n * Rejects `truncation: 'allow'` on a route that states it has no truncation\n * parameter. Accepting it would mean promising a behaviour nothing on the wire\n * can express (Requirement 9.7).\n */\nfunction checkTruncation(request: PreDispatchRequest, prepared: PreparedEmbeddingCall): void {\n if (request.truncation !== 'allow') return\n if (request.truncationSupport?.state !== 'unsupported') return\n throw new EmbeddingError(\n 'Provider route exposes no truncation parameter',\n EMBEDDING_ERROR_CODES.TRUNCATION_UNSUPPORTED,\n routeFacts(prepared),\n )\n}\n\n/** Route identity attached to every failure, omitted rather than left `undefined`. */\nfunction routeFacts(prepared: PreparedEmbeddingCall): { provider: string; model: string } {\n return { provider: prepared.model.provider, model: prepared.model.id }\n}\n\n/**\n * Validates one `Logical_Call` against the SAME `PreparedEmbeddingCall` that will\n * dispatch it, BEFORE any `Physical_Batch` goes out.\n *\n * Every rejection here happens with 0 `Provider_Attempt`. Checks run cheapest\n * first, so a malformed request never pays for token estimation.\n *\n * @param request - the logical call as resolved from the caller.\n * @param prepared - the generation whose metadata, profile and limits will be used.\n * @throws EmbeddingError with a code from `EMBEDDING_ERROR_CODES` on any violation.\n */\nexport function validatePreDispatch(\n request: PreDispatchRequest,\n prepared: PreparedEmbeddingCall,\n): void {\n checkPurpose(request, prepared)\n checkItems(request, prepared)\n checkDimensions(request, prepared)\n checkTruncation(request, prepared)\n checkSpace(request, prepared)\n // Last: the only check that walks every input's text.\n checkInputLength(request, prepared)\n}\n\n/** Rejects a vector count that does not match the batch that was sent. */\nfunction checkVectorCount(\n batch: EmbeddingBatchRequest,\n result: EmbeddingBatchResult,\n): void {\n if (result.vectors.length === batch.items.length) return\n throw new EmbeddingError(\n `Provider returned ${result.vectors.length} vectors for ${batch.items.length} inputs`,\n EMBEDDING_ERROR_CODES.VECTOR_COUNT_MISMATCH,\n { provider: batch.provider, model: batch.model },\n )\n}\n\n/**\n * Rejects an index set that is not a permutation of the batch's item indexes.\n *\n * Duplicates, gaps and out-of-range values all land here: without a bijection,\n * restoring input order would be guesswork.\n */\nfunction checkVectorIndexes(\n batch: EmbeddingBatchRequest,\n result: EmbeddingBatchResult,\n): void {\n const expected = new Set(batch.items.map(item => item.index))\n const seen = new Set<number>()\n for (const vector of result.vectors) {\n if (!Number.isInteger(vector.index) || !expected.has(vector.index) || seen.has(vector.index)) {\n throw new EmbeddingError(\n 'Provider returned a duplicate, missing or out-of-range vector index',\n EMBEDDING_ERROR_CODES.VECTOR_INDEX_INVALID,\n { provider: batch.provider, model: batch.model },\n )\n }\n seen.add(vector.index)\n }\n}\n\n/** Rejects a non-array payload, `NaN`, and `Infinity`: never silently repaired. */\nfunction checkVectorValues(\n batch: EmbeddingBatchRequest,\n result: EmbeddingBatchResult,\n): void {\n for (const vector of result.vectors) {\n if (!Array.isArray(vector.values)) {\n throw new EmbeddingError(\n 'Provider returned a vector whose values are not an array',\n EMBEDDING_ERROR_CODES.RESPONSE_MALFORMED,\n { provider: batch.provider, model: batch.model, itemIndexes: [vector.index] },\n )\n }\n // Array.prototype.some skips holes; adapters can return sparse JS arrays.\n for (const value of vector.values) {\n if (typeof value === 'number' && Number.isFinite(value)) continue\n throw new EmbeddingError(\n 'Provider returned a vector containing a non-finite value',\n EMBEDDING_ERROR_CODES.VECTOR_VALUE_INVALID,\n { provider: batch.provider, model: batch.model, itemIndexes: [vector.index] },\n )\n }\n }\n}\n\n/**\n * Rejects a width that differs from the REQUESTED one.\n *\n * Only checked when the request named a width: with no request there is nothing\n * the provider contradicted, and the SDK never slices or pads to fit.\n */\nfunction checkVectorWidth(\n batch: EmbeddingBatchRequest,\n result: EmbeddingBatchResult,\n): void {\n const expected = batch.dimensions\n if (expected === undefined) return\n for (const vector of result.vectors) {\n if (vector.values.length === expected) continue\n throw new EmbeddingError(\n `Provider returned a ${vector.values.length}-dimensional vector, expected ${expected}`,\n EMBEDDING_ERROR_CODES.VECTOR_DIMENSIONS_MISMATCH,\n {\n provider: batch.provider,\n model: batch.model,\n itemIndexes: [vector.index],\n limit: expected,\n },\n )\n }\n}\n\n/**\n * Rejects a truncation report the caller never authorised.\n *\n * `truncated: true` under `truncation: 'reject'` means the provider shortened an\n * input the caller asked to have refused instead — a contract break, not data.\n */\nfunction checkTruncationReports(\n batch: EmbeddingBatchRequest,\n result: EmbeddingBatchResult,\n): void {\n if (batch.truncation !== 'reject') return\n const truncated = result.vectors.filter(vector => vector.truncated === true)\n if (truncated.length === 0) return\n throw new EmbeddingError(\n 'Provider reported truncation although truncation was rejected',\n EMBEDDING_ERROR_CODES.RESPONSE_MALFORMED,\n {\n provider: batch.provider,\n model: batch.model,\n itemIndexes: truncated.map(vector => vector.index),\n },\n )\n}\n\n/**\n * Validates one `Provider_Attempt`'s response against the batch that produced it.\n *\n * Order is fixed — count, indexes, values, width, truncation reports — so the\n * SAME malformed response yields the SAME code across providers, which is what\n * lets one contract-test suite run against all of them. Nothing here infers or\n * repairs: a response that breaks the contract is a protocol error.\n *\n * @param batch - the physical batch that was dispatched.\n * @param result - what the adapter parsed out of exactly one provider attempt.\n * @throws EmbeddingError with a vector- or response-level code on any violation.\n */\nexport function validateBatchResult(\n batch: EmbeddingBatchRequest,\n result: EmbeddingBatchResult,\n): void {\n checkVectorCount(batch, result)\n checkVectorIndexes(batch, result)\n checkVectorValues(batch, result)\n checkVectorWidth(batch, result)\n checkTruncationReports(batch, result)\n}\n"],"mappings":"yHAiCA,MAAM,EAAoC,OAAO,OAAO,CACtD,kBACA,oBACF,CAAC,EAqCD,SAAS,EAAS,EAA6B,CAC7C,IAAI,EAAO,GACX,IAAK,IAAM,KAAQ,EAAK,aAClB,EAAK,OAAS,SAAQ,GAAQ,EAAK,MAEzC,OAAO,CACT,CAGA,SAAS,EAAa,EAA6B,EAAuC,CACpF,MAAe,SAAS,EAAQ,OAAO,EAC3C,MAAM,IAAI,EACR,sEACA,EAAsB,gBACtB,EAAW,CAAQ,CACrB,CACF,CAOA,SAAS,EAAW,EAA6B,EAAuC,CACtF,GAAI,EAAQ,MAAM,SAAW,EAC3B,MAAM,IAAI,EACR,4CACA,EAAsB,gBACtB,EAAW,CAAQ,CACrB,EAEF,IAAM,EAAkB,CAAC,EACzB,IAAK,IAAM,KAAQ,EAAQ,OACrB,EAAK,aAAa,SAAW,GAAK,EAAS,CAAI,CAAC,CAAC,SAAW,IAAG,EAAM,KAAK,EAAK,KAAK,EAE1F,GAAI,EAAM,OAAS,EACjB,MAAM,IAAI,EACR,+BAA+B,EAAM,OAAO,UAC5C,EAAsB,gBACtB,CAAE,GAAG,EAAW,CAAQ,EAAG,YAAa,CAAM,CAChD,CAEJ,CASA,SAAS,EAAgB,EAA6B,EAAuC,CAC3F,IAAM,EAAY,EAAQ,WAC1B,GAAI,IAAc,IAAA,GAAW,OAC7B,GAAI,CAAC,OAAO,UAAU,CAAS,GAAK,GAAa,EAC/C,MAAM,IAAI,EACR,kDACA,EAAsB,gBACtB,EAAW,CAAQ,CACrB,EAEF,IAAM,EAAW,EAAS,MAAM,WAC5B,KAAS,QAAU,aACnB,GAAS,MAAM,SAAS,CAAS,EACrC,MAAM,IAAI,EACR,oCAAoC,EAAU,aAC9C,EAAsB,uBACtB,EAAW,CAAQ,CACrB,CACF,CAUA,SAAS,EAAiB,EAA6B,EAAuC,CAC5F,IAAM,EAAW,EAAS,MAAM,eAChC,GAAI,EAAS,QAAU,YAAa,OACpC,IAAM,EAAQ,EAAS,MACvB,GAAI,CAAC,OAAO,SAAS,CAAK,GAAK,GAAS,EAAG,OAC3C,IAAM,EAAsB,CAAC,EAC7B,IAAK,IAAM,KAAQ,EAAQ,MACrB,EAAS,OAAO,eAAe,EAAS,CAAI,CAAC,EAAI,GAAO,EAAU,KAAK,EAAK,KAAK,EAEnF,KAAU,SAAW,EACzB,MAAM,IAAI,EACR,iDAAiD,EAAM,SACvD,EAAsB,gBACtB,CAAE,GAAG,EAAW,CAAQ,EAAG,YAAa,EAAW,OAAM,CAC3D,CACF,CAQA,SAAS,EAAW,EAA6B,EAAuC,CACtF,IAAM,EAAW,EAAQ,cACnB,EAAkB,EAAQ,gBAC5B,QAAa,IAAA,IAAa,IAAoB,IAAA,KAEhD,MAAoB,IAAA,GAChB,IAAa,EAAS,QACtB,EAAkB,EAAiB,EAAS,OAAO,GAEzD,MAAM,IAAI,EACR,kEACA,EAAsB,mBACtB,CAAE,GAAG,EAAW,CAAQ,EAAG,MAAO,EAAS,OAAQ,CACrD,CACF,CAOA,SAAS,EAAgB,EAA6B,EAAuC,CACvF,KAAQ,aAAe,SACvB,EAAQ,mBAAmB,QAAU,cACzC,MAAM,IAAI,EACR,iDACA,EAAsB,uBACtB,EAAW,CAAQ,CACrB,CACF,CAGA,SAAS,EAAW,EAAsE,CACxF,MAAO,CAAE,SAAU,EAAS,MAAM,SAAU,MAAO,EAAS,MAAM,EAAG,CACvE,CAaA,SAAgB,EACd,EACA,EACM,CACN,EAAa,EAAS,CAAQ,EAC9B,EAAW,EAAS,CAAQ,EAC5B,EAAgB,EAAS,CAAQ,EACjC,EAAgB,EAAS,CAAQ,EACjC,EAAW,EAAS,CAAQ,EAE5B,EAAiB,EAAS,CAAQ,CACpC,CAGA,SAAS,EACP,EACA,EACM,CACF,KAAO,QAAQ,SAAW,EAAM,MAAM,OAC1C,MAAM,IAAI,EACR,qBAAqB,EAAO,QAAQ,OAAO,eAAe,EAAM,MAAM,OAAO,SAC7E,EAAsB,sBACtB,CAAE,SAAU,EAAM,SAAU,MAAO,EAAM,KAAM,CACjD,CACF,CAQA,SAAS,EACP,EACA,EACM,CACN,IAAM,EAAW,IAAI,IAAI,EAAM,MAAM,IAAI,GAAQ,EAAK,KAAK,CAAC,EACtD,EAAO,IAAI,IACjB,IAAK,IAAM,KAAU,EAAO,QAAS,CACnC,GAAI,CAAC,OAAO,UAAU,EAAO,KAAK,GAAK,CAAC,EAAS,IAAI,EAAO,KAAK,GAAK,EAAK,IAAI,EAAO,KAAK,EACzF,MAAM,IAAI,EACR,sEACA,EAAsB,qBACtB,CAAE,SAAU,EAAM,SAAU,MAAO,EAAM,KAAM,CACjD,EAEF,EAAK,IAAI,EAAO,KAAK,CACvB,CACF,CAGA,SAAS,EACP,EACA,EACM,CACN,IAAK,IAAM,KAAU,EAAO,QAAS,CACnC,GAAI,CAAC,MAAM,QAAQ,EAAO,MAAM,EAC9B,MAAM,IAAI,EACR,2DACA,EAAsB,mBACtB,CAAE,SAAU,EAAM,SAAU,MAAO,EAAM,MAAO,YAAa,CAAC,EAAO,KAAK,CAAE,CAC9E,EAGF,IAAK,IAAM,KAAS,EAAO,OACrB,YAAO,GAAU,UAAY,OAAO,SAAS,CAAK,GACtD,MAAM,IAAI,EACR,2DACA,EAAsB,qBACtB,CAAE,SAAU,EAAM,SAAU,MAAO,EAAM,MAAO,YAAa,CAAC,EAAO,KAAK,CAAE,CAC9E,CAEJ,CACF,CAQA,SAAS,EACP,EACA,EACM,CACN,IAAM,EAAW,EAAM,WACnB,OAAa,IAAA,GACjB,KAAK,IAAM,KAAU,EAAO,QACtB,KAAO,OAAO,SAAW,EAC7B,MAAM,IAAI,EACR,uBAAuB,EAAO,OAAO,OAAO,gCAAgC,IAC5E,EAAsB,2BACtB,CACE,SAAU,EAAM,SAChB,MAAO,EAAM,MACb,YAAa,CAAC,EAAO,KAAK,EAC1B,MAAO,CACT,CACF,CACF,CACF,CAQA,SAAS,EACP,EACA,EACM,CACN,GAAI,EAAM,aAAe,SAAU,OACnC,IAAM,EAAY,EAAO,QAAQ,OAAO,GAAU,EAAO,YAAc,EAAI,EACvE,KAAU,SAAW,EACzB,MAAM,IAAI,EACR,gEACA,EAAsB,mBACtB,CACE,SAAU,EAAM,SAChB,MAAO,EAAM,MACb,YAAa,EAAU,IAAI,GAAU,EAAO,KAAK,CACnD,CACF,CACF,CAcA,SAAgB,EACd,EACA,EACM,CACN,EAAiB,EAAO,CAAM,EAC9B,EAAmB,EAAO,CAAM,EAChC,EAAkB,EAAO,CAAM,EAC/B,EAAiB,EAAO,CAAM,EAC9B,EAAuB,EAAO,CAAM,CACtC"}
@@ -0,0 +1,12 @@
1
+ import { EmbeddingNormalization, EmbeddingPostProcessing, EmbeddingProfile, EmbeddingProfileInput, EmbeddingRepresentation, EmbeddingSpaceId, defaultEmbeddingProfile, deriveSpaceId, isSpaceCompatible } from "./embedding/profile.js";
2
+ import { EmbeddingPurpose, EmbeddingPurposeHandling } from "./embedding/purpose.js";
3
+ import { EmbeddingCapability, EmbeddingInputType, EmbeddingModelInfo, ResolvedEmbeddingModelInfo, unknownEmbeddingModel } from "./embedding/catalog.js";
4
+ import { EMBEDDING_BATCH_DEFAULTS, ResolvedEmbeddingBatchLimits, estimateTokens, resolveBatchLimits } from "./embedding/limits.js";
5
+ import { DEFAULT_EMBEDDING_TRUNCATION, EmbeddingBatchRequest, EmbeddingContentPart, EmbeddingItem, EmbeddingTruncation } from "./embedding/request.js";
6
+ import { EmbeddingCounterKey, EmbeddingTokenUsage, EmbeddingUsageReport, EmbeddingUsageStatus, EmbeddingUsageValidation, classifyEmbeddingUsageStatus, hasEmbeddingUsage, validateEmbeddingUsage } from "./embedding/usage.js";
7
+ import { EmbeddingBatchResult, EmbeddingManyResult, EmbeddingResult, EmbeddingVector, EmbeddingWarning } from "./embedding/result.js";
8
+ import { EmbeddingAdapter, PrepareEmbeddingOptions, PreparedEmbeddingCall } from "./embedding/adapter.js";
9
+ import { EmbedManyInput, EmbedOneInput, EmbeddingCacheEntry, EmbeddingCacheOptions, EmbeddingCacheStore, EmbeddingModelHandle, EmbeddingModelOptions } from "./embedding/handle.js";
10
+ import { EMBEDDING_ERROR_CODES, EmbeddingError, EmbeddingErrorCode, EmbeddingErrorOptions } from "./embedding/errors.js";
11
+ import { PreDispatchRequest, validateBatchResult, validatePreDispatch } from "./embedding/validation.js";
12
+ export { DEFAULT_EMBEDDING_TRUNCATION, EMBEDDING_BATCH_DEFAULTS, EMBEDDING_ERROR_CODES, type EmbedManyInput, type EmbedOneInput, EmbeddingAdapter, type EmbeddingBatchRequest, type EmbeddingBatchResult, type EmbeddingCacheEntry, type EmbeddingCacheOptions, type EmbeddingCacheStore, type EmbeddingCapability, type EmbeddingContentPart, type EmbeddingCounterKey, EmbeddingError, type EmbeddingErrorCode, type EmbeddingErrorOptions, type EmbeddingInputType, type EmbeddingItem, type EmbeddingManyResult, type EmbeddingModelHandle, type EmbeddingModelInfo, type EmbeddingModelOptions, type EmbeddingNormalization, type EmbeddingPostProcessing, type EmbeddingProfile, type EmbeddingProfileInput, type EmbeddingPurpose, type EmbeddingPurposeHandling, type EmbeddingRepresentation, type EmbeddingResult, type EmbeddingSpaceId, type EmbeddingTokenUsage, type EmbeddingTruncation, type EmbeddingUsageReport, type EmbeddingUsageStatus, type EmbeddingUsageValidation, type EmbeddingVector, type EmbeddingWarning, type PreDispatchRequest, type PrepareEmbeddingOptions, type PreparedEmbeddingCall, type ResolvedEmbeddingBatchLimits, type ResolvedEmbeddingModelInfo, classifyEmbeddingUsageStatus, defaultEmbeddingProfile, deriveSpaceId, estimateTokens, hasEmbeddingUsage, isSpaceCompatible, resolveBatchLimits, unknownEmbeddingModel, validateBatchResult, validateEmbeddingUsage, validatePreDispatch };
@@ -0,0 +1 @@
1
+ import{EMBEDDING_ERROR_CODES as e,EmbeddingError as t}from"./embedding/errors.js";import{DEFAULT_EMBEDDING_TRUNCATION as n}from"./embedding/request.js";import{defaultEmbeddingProfile as r,deriveSpaceId as i,isSpaceCompatible as a}from"./embedding/profile.js";import{validateBatchResult as o,validatePreDispatch as s}from"./embedding/validation.js";import{EMBEDDING_BATCH_DEFAULTS as c,estimateTokens as l,resolveBatchLimits as u}from"./embedding/limits.js";import{classifyEmbeddingUsageStatus as d,hasEmbeddingUsage as f,validateEmbeddingUsage as p}from"./embedding/usage.js";import{unknownEmbeddingModel as m}from"./embedding/catalog.js";import{EmbeddingAdapter as h}from"./embedding/adapter.js";export{n as DEFAULT_EMBEDDING_TRUNCATION,c as EMBEDDING_BATCH_DEFAULTS,e as EMBEDDING_ERROR_CODES,h as EmbeddingAdapter,t as EmbeddingError,d as classifyEmbeddingUsageStatus,r as defaultEmbeddingProfile,i as deriveSpaceId,l as estimateTokens,f as hasEmbeddingUsage,a as isSpaceCompatible,u as resolveBatchLimits,m as unknownEmbeddingModel,o as validateBatchResult,p as validateEmbeddingUsage,s as validatePreDispatch};
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Branded, MessageId, ProviderRequestId, ReasoningEffortId, ToolCallId } from "./primitives/brand.js";
2
2
  import { ModelFailure, normalizeModelFailure } from "./errors/failure.js";
3
3
  import { JsonObject, JsonValue, isJsonValue } from "./primitives/json.js";
4
- import { AssistantTextPhase, ContentBlock, ContentBlockMap, ContentBlockType, ImageBlock, ImageDetail, ImageMediaType, ImageSource, NativeToolCallBlock, ReasoningBlock, TextAnnotation, TextAnnotationMap, TextBlock, ToolCallBlock, ToolResultBlock, UrlCitationAnnotation } from "./message/content.js";
4
+ import { AssistantTextPhase, ContentBlock, ContentBlockMap, ContentBlockType, DocumentBlock, DocumentMediaType, DocumentSource, ImageBlock, ImageDetail, ImageMediaType, ImageSource, NativeToolCallBlock, ReasoningBlock, TextAnnotation, TextAnnotationMap, TextBlock, ToolCallBlock, ToolResultBlock, UrlCitationAnnotation } from "./message/content.js";
5
5
  import { FinishReason, FinishReasonMap, ReplayEnvelope, StreamChunk, TokenUsage } from "./stream/chunk.js";
6
6
  import { AgentSdkError, CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, INVALID_CREDENTIAL_CODE, MISSING_CREDENTIAL_CODE, QUOTA_EXCEEDED_CODE, errorChain, isAgentSdkError, isContextWindowExceededError, isQuotaExceededError } from "./errors/agent-sdk-error.js";
7
7
  import { CorrelationContext, ObservationRunScope, SpanId, TraceId, createObservationRunScope, createOperationId, createSpanId, createTraceId, freezeCorrelation, isSpanId, isTraceId, traceparent } from "./observation/context.js";
@@ -19,7 +19,7 @@ import { ModelCatalogOptions, ModelCatalogSnapshot, ModelCatalogState, ModelCont
19
19
  import { AlwaysRetryPolicyConfig, BackoffConfig, MAX_TIMER_DELAY_MS, NormalRetryPolicyConfig, ResolvedAlwaysRetryPolicy, ResolvedNormalRetryPolicy, ResolvedRetryBackoff, ResolvedRetryPolicy, RetryPolicyConfig, backoffDelayMs, isRetryable, resolveRetryPolicy } from "./contract/retry-policy.js";
20
20
  import { ModelAdapter, PreparedAdapterCall } from "./contract/adapter.js";
21
21
  import { CallConfig, CallConfigAdapterDefaults, callConfigEquals } from "./contract/call-config.js";
22
- import { contentHasImage, projectImagesForTextModel, textOnlyImageText } from "./message/projection.js";
22
+ import { contentHasDocument, contentHasImage, projectDocumentsForTextModel, projectImagesForTextModel, textOnlyDocumentText, textOnlyImageText } from "./message/projection.js";
23
23
  import { deepFreeze } from "./primitives/freeze.js";
24
24
  import { assertNever } from "./primitives/never.js";
25
25
  import { detachedFrozen } from "./primitives/snapshot.js";
@@ -55,6 +55,9 @@ import { OBSERVATION_EXPORTER_API_VERSION, ObservationExporterPlugin, Observatio
55
55
  import { RuntimeAgent, RuntimeAgentBindingInput, RuntimeAgentDefinition, RuntimeAgentDefinitionInput, RuntimeAgentInvocationOptions, RuntimeAgentLimits, RuntimeAgentResponse, RuntimeAgentRunEvent, RuntimeAgentRunEventContext, RuntimeAgentRunHandle, RuntimeAgentSession, RuntimeAgentSessionOptions, RuntimeAgentSessionSnapshot } from "./composition/agent/types.js";
56
56
  import { cloneAgent, defineAgent } from "./composition/agent/author.js";
57
57
  import { CapabilityIdentityConflict } from "./errors/capability-identity.js";
58
+ import { EmbeddingUsageReport } from "./embedding/usage.js";
59
+ import { EmbeddingManyResult, EmbeddingResult } from "./embedding/result.js";
60
+ import { EmbeddingModelHandle, EmbeddingModelOptions } from "./embedding/handle.js";
58
61
  import { RuntimeModelCatalogSnapshot } from "./composition/model-catalog/types.js";
59
62
  import { AgentTeamMemberInput, RuntimeAgentTeam, RuntimeAgentTeamEvent, RuntimeAgentTeamOptions } from "./composition/team/types.js";
60
63
  import { AgentRuntime, AgentRuntimeOptions, DiagnosticSnapshot, RuntimeCloseReport, RuntimeObservationResourceInput, RuntimeOwnerObservabilityOptions } from "./composition/runtime/types.js";
@@ -67,4 +70,4 @@ import { defineMemoryStore } from "./composition/memory/definition.js";
67
70
  import { defineSkillProviderPlugin } from "./agent/skill/provider/definition.js";
68
71
  import { defineObservationExporter } from "./composition/exporter/definition.js";
69
72
  import { CONTEXT_SECTION_ID_PATTERN, CONTEXT_SECTION_INVALID, MAX_CONTEXT_SECTION_TEXT_BYTES, defineContextSection } from "./agent/context/section.js";
70
- 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 ContextSection, type ContextSectionResolveInput, type ContextSectionScope, type ContextSectionState, type ContextToolTouch, type CorrelationContext, type DefinedAgent, type DeliveryMode, type DiagnosticSnapshot, type DispatchState, EMPTY_RESPONSE_CODE, 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 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, contentHasImage, createAgentRuntime, createApprovalBroker, createApprovalRequest, createAssistantMessage, 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, projectImagesForTextModel, renderSkillCatalog, resolveCompactionConfig, resolveMemoryConfig, resolveRetryPolicy, resolveSkillOptions, safeErrorRecord, selectCompactablePrefix, snapshotObservationSpan, textOnlyImageText, traceparent, userAgent, validObservationSpan, validateCandidate, validateCaptureReceipt, validateSkillId, validateSkillResourcePath, validateSkillSource, validateUsageCounters, waitForSettlement, withApprovalPersistence, withIdleTimeout, withRetry };
73
+ 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 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 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, 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 };
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{contentHasImage as ee,projectImagesForTextModel as te,textOnlyImageText as ne}from"./message/projection.js";import{BlockAssembler as re}from"./stream/assembler.js";import{withIdleTimeout as ie}from"./stream/idle-timeout.js";import{ModelAdapter as ae}from"./contract/adapter.js";import{callConfigEquals as oe}from"./contract/call-config.js";import{MAX_TIMER_DELAY_MS as se,backoffDelayMs as ce,isRetryable as le,resolveRetryPolicy as ue}from"./contract/retry-policy.js";import{isNativeToolSchema as de}from"./contract/tool.js";import{ModelRegistry as fe}from"./runtime/registry.js";import{withRetry as pe}from"./runtime/with-retry.js";import{assertUsableApiKey as me,normalizeApiKey as he}from"./http/api-key.js";import{APP_IDENTITY as ge,attributionHeaders as _e,userAgent as ve}from"./http/attribution.js";import{AgentMemory as ye,resolveMemoryConfig as be}from"./agent/memory/memory.js";import{estimateContextTokens as xe,estimateMessageTokens as Se}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as Ce}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as we,ContextCompactor as Te}from"./agent/memory/compaction.js";import{resolveCompactionConfig as Ee}from"./agent/memory/compaction-config.js";import{MEMORY_ERROR_CODES as De,MEMORY_STORE_API_VERSION as Oe}from"./composition/memory/config.js";import{defineMemoryStore as ke}from"./composition/memory/definition.js";import{MAX_SKILL_DESCRIPTION_CHARS as Ae,MAX_SKILL_ID_CHARS as je,MAX_SKILL_INSTRUCTIONS_CHARS as Me,MAX_SKILL_NAME_CHARS as Ne,MAX_SKILL_RESOURCE_CHARS as Pe,MAX_SKILL_RESOURCE_PATH_CHARS as Fe,SKILL_ID_PATTERN as Ie,defineSkill as Le,defineSkillProvider as Re,validateCandidate as ze,validateSkillId as Be,validateSkillResourcePath as Ve,validateSkillSource as He}from"./agent/skill/definition.js";import{SKILL_ERROR_CODES as Ue,SKILL_PROVIDER_API_VERSION as We}from"./agent/skill/provider/config.js";import{defineSkillProviderPlugin as Ge}from"./agent/skill/provider/definition.js";import{SkillCatalog as Ke}from"./agent/skill/catalog.js";import{defineTool as qe}from"./agent/tool/definition.js";import{SKILL_TOOL_NAMES as Je,createSkillTools as Ye,renderSkillCatalog as Xe,resolveSkillOptions as Ze}from"./agent/skill/tools.js";import{OBSERVATION_EXPORTER_API_VERSION as Qe}from"./composition/exporter/types.js";import{CONTEXT_SECTION_ID_PATTERN as $e,CONTEXT_SECTION_INVALID as et,MAX_CONTEXT_SECTION_TEXT_BYTES as tt,defineContextSection as nt}from"./agent/context/section.js";import{createApprovalBroker as rt,createApprovalRequest as it,fixedApprovalBroker as at,withApprovalPersistence as ot}from"./agent/tool/approval.js";import{createAgentRuntime as st}from"./composition/runtime/public.js";import{cloneAgent as ct,defineAgent as lt}from"./composition/agent/author.js";import{defineObservationExporter as ut}from"./composition/exporter/definition.js";import{createUserInputBroker as dt,fixedUserInputBroker as ft}from"./agent/mode/user-input.js";import{defineToolFromSchema as pt}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as mt,localToolExecutionBackend as ht}from"./agent/tool/execution.js";export{ge as APP_IDENTITY,ye as AgentMemory,T as AgentSdkError,re as BlockAssembler,we as COMPACTION_INSTRUCTION,$e as CONTEXT_SECTION_ID_PATTERN,et as CONTEXT_SECTION_INVALID,E as CONTEXT_WINDOW_EXCEEDED_CODE,Te as ContextCompactor,D as EMPTY_RESPONSE_CODE,O as INVALID_CREDENTIAL_CODE,tt as MAX_CONTEXT_SECTION_TEXT_BYTES,Ae as MAX_SKILL_DESCRIPTION_CHARS,je as MAX_SKILL_ID_CHARS,Me as MAX_SKILL_INSTRUCTIONS_CHARS,Ne as MAX_SKILL_NAME_CHARS,Pe as MAX_SKILL_RESOURCE_CHARS,Fe as MAX_SKILL_RESOURCE_PATH_CHARS,se as MAX_TIMER_DELAY_MS,De as MEMORY_ERROR_CODES,Oe as MEMORY_STORE_API_VERSION,k as MISSING_CREDENTIAL_CODE,W as MODEL_ERROR_CODES,e as MessageId,ae as ModelAdapter,F as ModelCallObservationError,G as ModelError,fe as ModelRegistry,y as NOOP_OBSERVATION_PORT,I as OBSERVATION_ERROR_CODES,Qe 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,Ue as SKILL_ERROR_CODES,Ie as SKILL_ID_PATTERN,We as SKILL_PROVIDER_API_VERSION,Je as SKILL_TOOL_NAMES,Ke as SkillCatalog,r as ToolCallId,L as addUsageCounters,o as assertNever,me as assertUsableApiKey,_e as attributionHeaders,ce as backoffDelayMs,oe as callConfigEquals,R as classifyUsageCoverage,ct as cloneAgent,ee as contentHasImage,st as createAgentRuntime,rt as createApprovalBroker,it as createApprovalRequest,J as createAssistantMessage,b as createCoreSpan,Y as createMessage,u as createObservationRunScope,d as createOperationId,Ye as createSkillTools,f as createSpanId,X as createTextMessage,mt as createToolExecutionInterceptor,Z as createToolResultMessage,p as createTraceId,dt as createUserInputBroker,Q as createUserMessage,i as deepFreeze,lt as defineAgent,nt as defineContextSection,ke as defineMemoryStore,ut as defineObservationExporter,Le as defineSkill,Re as defineSkillProvider,Ge as defineSkillProviderPlugin,qe as defineTool,pt as defineToolFromSchema,s as detachedFrozen,x as disabledDeliverySummary,j as errorChain,xe as estimateContextTokens,Se as estimateMessageTokens,at as fixedApprovalBroker,ft as fixedUserInputBroker,m as freezeCorrelation,$ as freezeMessage,z as hasUsageCounters,M as isAgentSdkError,N as isContextWindowExceededError,a as isJsonValue,de as isNativeToolSchema,P as isQuotaExceededError,le as isRetryable,h as isSpanId,g as isTraceId,ht as localToolExecutionBackend,he as normalizeApiKey,q as normalizeModelFailure,B as possiblyBilledAttemptsWithoutUsage,te as projectImagesForTextModel,Xe as renderSkillCatalog,Ee as resolveCompactionConfig,be as resolveMemoryConfig,ue as resolveRetryPolicy,Ze as resolveSkillOptions,v as safeErrorRecord,Ce as selectCompactablePrefix,S as snapshotObservationSpan,ne as textOnlyImageText,_ as traceparent,ve as userAgent,C as validObservationSpan,ze as validateCandidate,w as validateCaptureReceipt,Be as validateSkillId,Ve as validateSkillResourcePath,He as validateSkillSource,V as validateUsageCounters,l as waitForSettlement,ot as withApprovalPersistence,ie as withIdleTimeout,pe 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{MEMORY_ERROR_CODES as Ae,MEMORY_STORE_API_VERSION as je}from"./composition/memory/config.js";import{defineMemoryStore as Me}from"./composition/memory/definition.js";import{MAX_SKILL_DESCRIPTION_CHARS as Ne,MAX_SKILL_ID_CHARS as Pe,MAX_SKILL_INSTRUCTIONS_CHARS as Fe,MAX_SKILL_NAME_CHARS as Ie,MAX_SKILL_RESOURCE_CHARS as Le,MAX_SKILL_RESOURCE_PATH_CHARS as Re,SKILL_ID_PATTERN as ze,defineSkill as Be,defineSkillProvider as Ve,validateCandidate as He,validateSkillId as Ue,validateSkillResourcePath as We,validateSkillSource as Ge}from"./agent/skill/definition.js";import{SKILL_ERROR_CODES as Ke,SKILL_PROVIDER_API_VERSION as qe}from"./agent/skill/provider/config.js";import{defineSkillProviderPlugin as Je}from"./agent/skill/provider/definition.js";import{SkillCatalog as Ye}from"./agent/skill/catalog.js";import{defineTool as Xe}from"./agent/tool/definition.js";import{SKILL_TOOL_NAMES as Ze,createSkillTools as Qe,renderSkillCatalog as $e,resolveSkillOptions as et}from"./agent/skill/tools.js";import{OBSERVATION_EXPORTER_API_VERSION as tt}from"./composition/exporter/types.js";import{CONTEXT_SECTION_ID_PATTERN as nt,CONTEXT_SECTION_INVALID as rt,MAX_CONTEXT_SECTION_TEXT_BYTES as it,defineContextSection as at}from"./agent/context/section.js";import{createApprovalBroker as ot,createApprovalRequest as st,fixedApprovalBroker as ct,withApprovalPersistence as lt}from"./agent/tool/approval.js";import{createAgentRuntime as ut}from"./composition/runtime/public.js";import{cloneAgent as dt,defineAgent as ft}from"./composition/agent/author.js";import{defineObservationExporter as pt}from"./composition/exporter/definition.js";import{createUserInputBroker as mt,fixedUserInputBroker as ht}from"./agent/mode/user-input.js";import{defineToolFromSchema as gt}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as _t,localToolExecutionBackend as vt}from"./agent/tool/execution.js";export{ye as APP_IDENTITY,Se as AgentMemory,T as AgentSdkError,oe as BlockAssembler,De as COMPACTION_INSTRUCTION,nt as CONTEXT_SECTION_ID_PATTERN,rt as CONTEXT_SECTION_INVALID,E as CONTEXT_WINDOW_EXCEEDED_CODE,Oe as ContextCompactor,D as EMPTY_RESPONSE_CODE,O as INVALID_CREDENTIAL_CODE,it as MAX_CONTEXT_SECTION_TEXT_BYTES,Ne as MAX_SKILL_DESCRIPTION_CHARS,Pe as MAX_SKILL_ID_CHARS,Fe as MAX_SKILL_INSTRUCTIONS_CHARS,Ie as MAX_SKILL_NAME_CHARS,Le as MAX_SKILL_RESOURCE_CHARS,Re as MAX_SKILL_RESOURCE_PATH_CHARS,ue as MAX_TIMER_DELAY_MS,Ae as MEMORY_ERROR_CODES,je 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,tt 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,Ke as SKILL_ERROR_CODES,ze as SKILL_ID_PATTERN,qe as SKILL_PROVIDER_API_VERSION,Ze as SKILL_TOOL_NAMES,Ye 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,dt as cloneAgent,ee as contentHasDocument,te as contentHasImage,ut as createAgentRuntime,ot as createApprovalBroker,st as createApprovalRequest,J as createAssistantMessage,b as createCoreSpan,Y as createMessage,u as createObservationRunScope,d as createOperationId,Qe as createSkillTools,f as createSpanId,X as createTextMessage,_t as createToolExecutionInterceptor,Z as createToolResultMessage,p as createTraceId,mt as createUserInputBroker,Q as createUserMessage,i as deepFreeze,ft as defineAgent,at as defineContextSection,Me as defineMemoryStore,pt as defineObservationExporter,Be as defineSkill,Ve as defineSkillProvider,Je as defineSkillProviderPlugin,Xe as defineTool,gt as defineToolFromSchema,s as detachedFrozen,x as disabledDeliverySummary,j as errorChain,we as estimateContextTokens,Te as estimateMessageTokens,ct as fixedApprovalBroker,ht 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,vt as localToolExecutionBackend,ve as normalizeApiKey,q as normalizeModelFailure,B as possiblyBilledAttemptsWithoutUsage,ne as projectDocumentsForTextModel,re as projectImagesForTextModel,$e as renderSkillCatalog,ke as resolveCompactionConfig,Ce as resolveMemoryConfig,pe as resolveRetryPolicy,et 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,He as validateCandidate,w as validateCaptureReceipt,Ue as validateSkillId,We as validateSkillResourcePath,Ge as validateSkillSource,V as validateUsageCounters,l as waitForSettlement,lt as withApprovalPersistence,se as withIdleTimeout,ge as withRetry};
@@ -67,6 +67,75 @@ interface ImageBlock {
67
67
  source: ImageSource;
68
68
  detail?: ImageDetail;
69
69
  }
70
+ /**
71
+ * Document media types every supported provider accepts as a first-class file.
72
+ *
73
+ * PDF only, deliberately. All three provider families document PDF as a native
74
+ * vision-backed input; the other types each provider accepts are different per
75
+ * provider, and admitting them here would let a request typecheck against a
76
+ * provider that rejects it. A caller with a DOCX extracts text and sends text.
77
+ */
78
+ type DocumentMediaType = 'application/pdf';
79
+ /**
80
+ * Where a document's bytes come from.
81
+ *
82
+ * Identical variants to {@link ImageSource}, and not by coincidence: OpenAI
83
+ * Responses (`input_file`), Anthropic Messages (`document`), and Gemini
84
+ * Interactions (`document`) each accept inline base64, a remote URL, and a
85
+ * provider-side uploaded file id.
86
+ */
87
+ type DocumentSource = {
88
+ kind: 'base64';
89
+ mediaType: DocumentMediaType;
90
+ data: string;
91
+ } | {
92
+ kind: 'url';
93
+ url: string;
94
+ } | {
95
+ kind: 'file';
96
+ fileId: string;
97
+ };
98
+ /**
99
+ * A document (PDF), valid in user content and echoed in assistant content.
100
+ *
101
+ * Providers read a PDF with vision, not plain text extraction: each page is
102
+ * rasterized alongside its extracted text, so charts and tables survive. That is
103
+ * also why a document is its own block rather than sugar over {@link ImageBlock}
104
+ * — the provider owns the page splitting, and doing it here would lose the text
105
+ * layer.
106
+ */
107
+ interface DocumentBlock {
108
+ type: 'document';
109
+ source: DocumentSource;
110
+ /**
111
+ * Display file name.
112
+ *
113
+ * Required on the wire by OpenAI for inline base64, which infers the type from
114
+ * the extension. Adapters substitute a neutral default when it is absent, so
115
+ * setting it is optional here but always worth doing.
116
+ */
117
+ filename?: string;
118
+ /** Short human title for the document, when the provider surfaces one. */
119
+ title?: string;
120
+ /**
121
+ * Page count, when the caller knows it.
122
+ *
123
+ * LOCAL metadata: no provider accepts it on the wire, and no adapter sends it.
124
+ * It exists because providers bill a PDF per page, so this is the one fact that
125
+ * lets the context estimator cost a document accurately instead of assuming.
126
+ * Absent it, the estimator falls back to a documented assumption.
127
+ */
128
+ pages?: number;
129
+ /** Extra context about the document, passed through where supported. */
130
+ context?: string;
131
+ /**
132
+ * Ask the provider to emit verifiable citations into this document.
133
+ *
134
+ * Honored only by providers with a native citation feature; ignored elsewhere
135
+ * rather than emulated, because a fabricated page reference is worse than none.
136
+ */
137
+ citations?: boolean;
138
+ }
70
139
  /** A tool the provider ran internally, such as web search or image generation. */
71
140
  interface NativeToolCallBlock {
72
141
  type: 'native-tool-call';
@@ -112,6 +181,7 @@ interface ContentBlockMap {
112
181
  'text': TextBlock;
113
182
  'reasoning': ReasoningBlock;
114
183
  'image': ImageBlock;
184
+ 'document': DocumentBlock;
115
185
  'native-tool-call': NativeToolCallBlock;
116
186
  'tool-call': ToolCallBlock;
117
187
  'tool-result': ToolResultBlock;
@@ -121,5 +191,5 @@ type ContentBlockType = keyof ContentBlockMap;
121
191
  /** Any known content block. Switch on `type` and fall through unknowns. */
122
192
  type ContentBlock = ContentBlockMap[ContentBlockType];
123
193
  //#endregion
124
- export { AssistantTextPhase, ContentBlock, ContentBlockMap, ContentBlockType, ImageBlock, ImageDetail, ImageMediaType, ImageSource, NativeToolCallBlock, ReasoningBlock, TextAnnotation, TextAnnotationMap, TextBlock, ToolCallBlock, ToolResultBlock, UrlCitationAnnotation };
194
+ export { AssistantTextPhase, ContentBlock, ContentBlockMap, ContentBlockType, DocumentBlock, DocumentMediaType, DocumentSource, ImageBlock, ImageDetail, ImageMediaType, ImageSource, NativeToolCallBlock, ReasoningBlock, TextAnnotation, TextAnnotationMap, TextBlock, ToolCallBlock, ToolResultBlock, UrlCitationAnnotation };
125
195
  //# sourceMappingURL=content.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"content.d.ts","names":[],"sources":["../../src/message/content.ts"],"mappings":";;;;KAgBY;;UAGK;EACf;EACA;;EAEA,QAAQ;;EAER,uBAAuB;;UAGR;EACf;EACA;EACA;EACA;EACA;;EAEA;;UAGe;EACf,gBAAgB;;KAGN,iBAAiB,wBAAwB;;;;;;;;;;UAWpC;EACf;EACA;;EAEA;;;KAIU;;;;;;;;KASA;EACN;EAAgB,WAAW;EAAgB;;EAC3C;EAAa;;EACb;EAAc;;KAER;;UAGK;EACf;EACA,QAAQ;EACR,SAAS;;;UAIM;EACf;;EAEA;;EAEA;EACA;EACA,YAAY;;EAEZ,SAAS;;EAET;;;UAIe;EACf;;EAEA,IAAI;EACJ;;;;;;;;;EASA;;;UAIe;EACf;EACA,YAAY;EACZ,SAAS;EACT;;;;;;UAOe;EACf,QAAQ;EACR,aAAa;EACb,SAAS;EACT,oBAAoB;EACpB,aAAa;EACb,eAAe;;;KAIL,yBAAyB;;KAGzB,eAAe,gBAAgB"}
1
+ {"version":3,"file":"content.d.ts","names":[],"sources":["../../src/message/content.ts"],"mappings":";;;;KAgBY;;UAGK;EACf;EACA;;EAEA,QAAQ;;EAER,uBAAuB;;UAGR;EACf;EACA;EACA;EACA;EACA;;EAEA;;UAGe;EACf,gBAAgB;;KAGN,iBAAiB,wBAAwB;;;;;;;;;;UAWpC;EACf;EACA;;EAEA;;;KAIU;;;;;;;;KASA;EACN;EAAgB,WAAW;EAAgB;;EAC3C;EAAa;;EACb;EAAc;;KAER;;UAGK;EACf;EACA,QAAQ;EACR,SAAS;;;;;;;;;;KAWC;;;;;;;;;KAUA;EACN;EAAgB,WAAW;EAAmB;;EAC9C;EAAa;;EACb;EAAc;;;;;;;;;;;UAWH;EACf;EACA,QAAQ;;;;;;;;EAQR;;EAEA;;;;;;;;;EASA;;EAEA;;;;;;;EAOA;;;UAIe;EACf;;EAEA;;EAEA;EACA;EACA,YAAY;;EAEZ,SAAS;;EAET;;;UAIe;EACf;;EAEA,IAAI;EACJ;;;;;;;;;EASA;;;UAIe;EACf;EACA,YAAY;EACZ,SAAS;EACT;;;;;;UAOe;EACf,QAAQ;EACR,aAAa;EACb,SAAS;EACT,YAAY;EACZ,oBAAoB;EACpB,aAAa;EACb,eAAe;;;KAIL,yBAAyB;;KAGzB,eAAe,gBAAgB"}
@@ -1,4 +1,4 @@
1
- import { ContentBlock, ImageBlock } from "./content.js";
1
+ import { ContentBlock, DocumentBlock, ImageBlock } from "./content.js";
2
2
  import { Message } from "./message.js";
3
3
  //#region src/message/projection.d.ts
4
4
  /**
@@ -10,6 +10,13 @@ import { Message } from "./message.js";
10
10
  * @returns true when at least one image block is present at any depth.
11
11
  */
12
12
  declare function contentHasImage(content: readonly ContentBlock[]): boolean;
13
+ /**
14
+ * Whether any block in this content is (or contains) a document.
15
+ *
16
+ * @param content - the blocks to inspect.
17
+ * @returns true when at least one document block is present at any depth.
18
+ */
19
+ declare function contentHasDocument(content: readonly ContentBlock[]): boolean;
13
20
  /**
14
21
  * The deterministic text that stands in for one omitted image.
15
22
  *
@@ -20,6 +27,16 @@ declare function contentHasImage(content: readonly ContentBlock[]): boolean;
20
27
  * @returns model-visible replacement text.
21
28
  */
22
29
  declare function textOnlyImageText(block: ImageBlock): string;
30
+ /**
31
+ * The deterministic text that stands in for one omitted document.
32
+ *
33
+ * Deterministic for the same prompt-caching reason as {@link textOnlyImageText}.
34
+ * Prefers the file name when one was supplied, because "report-q3.pdf" tells the
35
+ * model far more about what it is missing than a media type does.
36
+ * @param block - the document being replaced.
37
+ * @returns model-visible replacement text.
38
+ */
39
+ declare function textOnlyDocumentText(block: DocumentBlock): string;
23
40
  /**
24
41
  * Project every image in a message list into text.
25
42
  *
@@ -29,6 +46,15 @@ declare function textOnlyImageText(block: ImageBlock): string;
29
46
  * @returns an equivalent list whose images have become text.
30
47
  */
31
48
  declare function projectImagesForTextModel(messages: readonly Message[]): readonly Message[];
49
+ /**
50
+ * Project every document in a message list into text.
51
+ *
52
+ * Returns the SAME array identity when nothing changed, on the same terms as
53
+ * {@link projectImagesForTextModel}.
54
+ * @param messages - the conversation as assembled.
55
+ * @returns an equivalent list whose documents have become text.
56
+ */
57
+ declare function projectDocumentsForTextModel(messages: readonly Message[]): readonly Message[];
32
58
  //#endregion
33
- export { contentHasImage, projectImagesForTextModel, textOnlyImageText };
59
+ export { contentHasDocument, contentHasImage, projectDocumentsForTextModel, projectImagesForTextModel, textOnlyDocumentText, textOnlyImageText };
34
60
  //# sourceMappingURL=projection.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"projection.d.ts","names":[],"sources":["../../src/message/projection.ts"],"mappings":";;;;;;;;;;;iBAyBgB,gBAAgB,kBAAkB;;;;;;;;;;iBAelC,kBAAkB,OAAO;;;;;;;;;iBA6BzB,0BACd,mBAAmB,qBACT"}
1
+ {"version":3,"file":"projection.d.ts","names":[],"sources":["../../src/message/projection.ts"],"mappings":";;;;;;;;;;;iBAqCgB,gBAAgB,kBAAkB;;;;;;;iBAUlC,mBAAmB,kBAAkB;;;;;;;;;;iBAarC,kBAAkB,OAAO;;;;;;;;;;iBAgBzB,qBAAqB,OAAO;;;;;;;;;iBAgD5B,0BACd,mBAAmB,qBACT;;;;;;;;;iBAYI,6BACd,mBAAmB,qBACT"}
@@ -1,2 +1,2 @@
1
- import{freezeMessage as e}from"./message.js";function t(e){return e.some(e=>e.type===`image`||(e.type===`tool-result`||e.type===`native-tool-call`)&&t(e.content))}function n(e){return`[image omitted: the selected model does not accept image input (${e.source.kind===`url`?e.source.url:e.source.kind===`file`?e.source.fileId:e.source.mediaType})]`}function r(e){return e.map(e=>e.type===`image`?{type:`text`,text:n(e)}:(e.type===`tool-result`||e.type===`native-tool-call`)&&t(e.content)?{...e,content:r(e.content)}:e)}function i(n){let i=!1,a=n.map(n=>t(n.content)?(i=!0,e({...n,content:r(n.content)})):n);return i?a:n}export{t as contentHasImage,i as projectImagesForTextModel,n as textOnlyImageText};
1
+ import{freezeMessage as e}from"./message.js";function t(e,n){return e.some(e=>e.type===n||(e.type===`tool-result`||e.type===`native-tool-call`)&&t(e.content,n))}function n(e){return t(e,`image`)}function r(e){return t(e,`document`)}function i(e){return`[image omitted: the selected model does not accept image input (${e.source.kind===`url`?e.source.url:e.source.kind===`file`?e.source.fileId:e.source.mediaType})]`}function a(e){return`[document omitted: the selected model does not accept document input (${e.filename??(e.source.kind===`url`?e.source.url:e.source.kind===`file`?e.source.fileId:e.source.mediaType)})]`}function o(e,n,r){return e.map(e=>e.type===n?{type:`text`,text:r(e)}:(e.type===`tool-result`||e.type===`native-tool-call`)&&t(e.content,n)?{...e,content:o(e.content,n,r)}:e)}function s(n,r,i){let a=!1,s=n.map(n=>t(n.content,r)?(a=!0,e({...n,content:o(n.content,r,i)})):n);return a?s:n}function c(e){return s(e,`image`,e=>i(e))}function l(e){return s(e,`document`,e=>a(e))}export{r as contentHasDocument,n as contentHasImage,l as projectDocumentsForTextModel,c as projectImagesForTextModel,a as textOnlyDocumentText,i as textOnlyImageText};
2
2
  //# sourceMappingURL=projection.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"projection.js","names":[],"sources":["../../src/message/projection.ts"],"sourcesContent":["/**\n * Content inspection and the text-only-model projection.\n *\n * Why the projection exists: conversation history outlives any single model\n * choice. A user attaches an image, the conversation continues, and later the\n * caller switches to a cheaper text-only model  Eor a summarizer runs on the same\n * history. Sending the image would be rejected by the provider, and silently\n * deleting it would leave the model reading a conversation that references\n * something invisible. Replacing it with a deterministic textual stand-in keeps\n * the history coherent and the request valid.\n *\n * @module ai-agent-sdk/core/message/projection\n */\n\nimport type { ContentBlock, ImageBlock } from './content.ts'\nimport { freezeMessage, type Message } from './message.ts'\n\n/**\n * Whether any block in this content is (or contains) an image.\n *\n * Recurses into tool results, because a tool that returns a screenshot puts the\n * image one level down where a shallow scan would miss it.\n * @param content - the blocks to inspect.\n * @returns true when at least one image block is present at any depth.\n */\nexport function contentHasImage(content: readonly ContentBlock[]): boolean {\n return content.some(block => block.type === 'image'\n || ((block.type === 'tool-result' || block.type === 'native-tool-call')\n && contentHasImage(block.content)))\n}\n\n/**\n * The deterministic text that stands in for one omitted image.\n *\n * Deterministic on purpose: a stable string keeps the request prefix\n * byte-identical across turns, which is what lets provider prompt caching keep\n * working on the unchanged part of a long history.\n * @param block - the image being replaced.\n * @returns model-visible replacement text.\n */\nexport function textOnlyImageText(block: ImageBlock): string {\n const detail = block.source.kind === 'url'\n ? block.source.url\n : block.source.kind === 'file' ? block.source.fileId : block.source.mediaType\n return `[image omitted: the selected model does not accept image input (${detail})]`\n}\n\n/** Replace image blocks with their textual stand-in, recursing into tool results. */\nfunction projectContent(content: readonly ContentBlock[]): ContentBlock[] {\n return content.map((block) => {\n if (block.type === 'image') {\n return { type: 'text', text: textOnlyImageText(block) } satisfies ContentBlock\n }\n if ((block.type === 'tool-result' || block.type === 'native-tool-call')\n && contentHasImage(block.content)) {\n return { ...block, content: projectContent(block.content) } satisfies ContentBlock\n }\n return block\n })\n}\n\n/**\n * Project every image in a message list into text.\n *\n * Returns the SAME array identity when nothing changed, so callers can use a\n * reference check to skip re-freezing and re-cloning an untouched history.\n * @param messages - the conversation as assembled.\n * @returns an equivalent list whose images have become text.\n */\nexport function projectImagesForTextModel(\n messages: readonly Message[],\n): readonly Message[] {\n let changed = false\n const projected = messages.map((message) => {\n if (!contentHasImage(message.content)) return message\n changed = true\n return freezeMessage({ ...message, content: projectContent(message.content) })\n })\n return changed ? projected : messages\n}\n"],"mappings":"6CAyBA,SAAgB,EAAgB,EAA2C,CACzE,OAAO,EAAQ,KAAK,GAAS,EAAM,OAAS,UACrC,EAAM,OAAS,eAAiB,EAAM,OAAS,qBAC/C,EAAgB,EAAM,OAAO,CAAE,CACxC,CAWA,SAAgB,EAAkB,EAA2B,CAI3D,MAAO,mEAHQ,EAAM,OAAO,OAAS,MACjC,EAAM,OAAO,IACb,EAAM,OAAO,OAAS,OAAS,EAAM,OAAO,OAAS,EAAM,OAAO,UACW,GACnF,CAGA,SAAS,EAAe,EAAkD,CACxE,OAAO,EAAQ,IAAK,GACd,EAAM,OAAS,QACV,CAAE,KAAM,OAAQ,KAAM,EAAkB,CAAK,CAAE,GAEnD,EAAM,OAAS,eAAiB,EAAM,OAAS,qBAC/C,EAAgB,EAAM,OAAO,EACzB,CAAE,GAAG,EAAO,QAAS,EAAe,EAAM,OAAO,CAAE,EAErD,CACR,CACH,CAUA,SAAgB,EACd,EACoB,CACpB,IAAI,EAAU,GACR,EAAY,EAAS,IAAK,GACzB,EAAgB,EAAQ,OAAO,GACpC,EAAU,GACH,EAAc,CAAE,GAAG,EAAS,QAAS,EAAe,EAAQ,OAAO,CAAE,CAAC,GAF/B,CAG/C,EACD,OAAO,EAAU,EAAY,CAC/B"}
1
+ {"version":3,"file":"projection.js","names":[],"sources":["../../src/message/projection.ts"],"sourcesContent":["/**\n * Content inspection and the text-only-model projection.\n *\n * Why the projection exists: conversation history outlives any single model\n * choice. A user attaches an image or a PDF, the conversation continues, and\n * later the caller switches to a cheaper text-only model Eor a summarizer runs on\n * the same history. Sending the attachment would be rejected by the provider, and\n * silently deleting it would leave the model reading a conversation that\n * references something invisible. Replacing it with a deterministic textual\n * stand-in keeps the history coherent and the request valid.\n *\n * @module ai-agent-sdk/core/message/projection\n */\n\nimport type { ContentBlock, ContentBlockType, DocumentBlock, ImageBlock } from './content.ts'\nimport { freezeMessage, type Message } from './message.ts'\n\n/**\n * Whether any block in this content is (or contains) a block of one type.\n *\n * Recurses into tool results, because a tool that returns a screenshot or a\n * generated PDF puts it one level down where a shallow scan would miss it.\n */\nfunction contentHasType(content: readonly ContentBlock[], type: ContentBlockType): boolean {\n return content.some(block => block.type === type\n || ((block.type === 'tool-result' || block.type === 'native-tool-call')\n && contentHasType(block.content, type)))\n}\n\n/**\n * Whether any block in this content is (or contains) an image.\n *\n * Recurses into tool results, because a tool that returns a screenshot puts the\n * image one level down where a shallow scan would miss it.\n * @param content - the blocks to inspect.\n * @returns true when at least one image block is present at any depth.\n */\nexport function contentHasImage(content: readonly ContentBlock[]): boolean {\n return contentHasType(content, 'image')\n}\n\n/**\n * Whether any block in this content is (or contains) a document.\n *\n * @param content - the blocks to inspect.\n * @returns true when at least one document block is present at any depth.\n */\nexport function contentHasDocument(content: readonly ContentBlock[]): boolean {\n return contentHasType(content, 'document')\n}\n\n/**\n * The deterministic text that stands in for one omitted image.\n *\n * Deterministic on purpose: a stable string keeps the request prefix\n * byte-identical across turns, which is what lets provider prompt caching keep\n * working on the unchanged part of a long history.\n * @param block - the image being replaced.\n * @returns model-visible replacement text.\n */\nexport function textOnlyImageText(block: ImageBlock): string {\n const detail = block.source.kind === 'url'\n ? block.source.url\n : block.source.kind === 'file' ? block.source.fileId : block.source.mediaType\n return `[image omitted: the selected model does not accept image input (${detail})]`\n}\n\n/**\n * The deterministic text that stands in for one omitted document.\n *\n * Deterministic for the same prompt-caching reason as {@link textOnlyImageText}.\n * Prefers the file name when one was supplied, because \"report-q3.pdf\" tells the\n * model far more about what it is missing than a media type does.\n * @param block - the document being replaced.\n * @returns model-visible replacement text.\n */\nexport function textOnlyDocumentText(block: DocumentBlock): string {\n const detail = block.filename ?? (block.source.kind === 'url'\n ? block.source.url\n : block.source.kind === 'file' ? block.source.fileId : block.source.mediaType)\n return `[document omitted: the selected model does not accept document input (${detail})]`\n}\n\n/** Replace blocks of one type with their textual stand-in, recursing into tool results. */\nfunction projectContent(\n content: readonly ContentBlock[],\n type: ContentBlockType,\n replacement: (block: ContentBlock) => string,\n): ContentBlock[] {\n return content.map((block) => {\n if (block.type === type) {\n return { type: 'text', text: replacement(block) } satisfies ContentBlock\n }\n if ((block.type === 'tool-result' || block.type === 'native-tool-call')\n && contentHasType(block.content, type)) {\n return { ...block, content: projectContent(block.content, type, replacement) } satisfies ContentBlock\n }\n return block\n })\n}\n\n/** Project every block of one type in a message list into text. */\nfunction projectForTextModel(\n messages: readonly Message[],\n type: ContentBlockType,\n replacement: (block: ContentBlock) => string,\n): readonly Message[] {\n let changed = false\n const projected = messages.map((message) => {\n if (!contentHasType(message.content, type)) return message\n changed = true\n return freezeMessage({ ...message, content: projectContent(message.content, type, replacement) })\n })\n return changed ? projected : messages\n}\n\n/**\n * Project every image in a message list into text.\n *\n * Returns the SAME array identity when nothing changed, so callers can use a\n * reference check to skip re-freezing and re-cloning an untouched history.\n * @param messages - the conversation as assembled.\n * @returns an equivalent list whose images have become text.\n */\nexport function projectImagesForTextModel(\n messages: readonly Message[],\n): readonly Message[] {\n return projectForTextModel(messages, 'image', block => textOnlyImageText(block as ImageBlock))\n}\n\n/**\n * Project every document in a message list into text.\n *\n * Returns the SAME array identity when nothing changed, on the same terms as\n * {@link projectImagesForTextModel}.\n * @param messages - the conversation as assembled.\n * @returns an equivalent list whose documents have become text.\n */\nexport function projectDocumentsForTextModel(\n messages: readonly Message[],\n): readonly Message[] {\n return projectForTextModel(messages, 'document', block => textOnlyDocumentText(block as DocumentBlock))\n}\n"],"mappings":"6CAuBA,SAAS,EAAe,EAAkC,EAAiC,CACzF,OAAO,EAAQ,KAAK,GAAS,EAAM,OAAS,IACrC,EAAM,OAAS,eAAiB,EAAM,OAAS,qBAC/C,EAAe,EAAM,QAAS,CAAI,CAAE,CAC7C,CAUA,SAAgB,EAAgB,EAA2C,CACzE,OAAO,EAAe,EAAS,OAAO,CACxC,CAQA,SAAgB,EAAmB,EAA2C,CAC5E,OAAO,EAAe,EAAS,UAAU,CAC3C,CAWA,SAAgB,EAAkB,EAA2B,CAI3D,MAAO,mEAHQ,EAAM,OAAO,OAAS,MACjC,EAAM,OAAO,IACb,EAAM,OAAO,OAAS,OAAS,EAAM,OAAO,OAAS,EAAM,OAAO,UACW,GACnF,CAWA,SAAgB,EAAqB,EAA8B,CAIjE,MAAO,yEAHQ,EAAM,WAAa,EAAM,OAAO,OAAS,MACpD,EAAM,OAAO,IACb,EAAM,OAAO,OAAS,OAAS,EAAM,OAAO,OAAS,EAAM,OAAO,WACiB,GACzF,CAGA,SAAS,EACP,EACA,EACA,EACgB,CAChB,OAAO,EAAQ,IAAK,GACd,EAAM,OAAS,EACV,CAAE,KAAM,OAAQ,KAAM,EAAY,CAAK,CAAE,GAE7C,EAAM,OAAS,eAAiB,EAAM,OAAS,qBAC/C,EAAe,EAAM,QAAS,CAAI,EAC9B,CAAE,GAAG,EAAO,QAAS,EAAe,EAAM,QAAS,EAAM,CAAW,CAAE,EAExE,CACR,CACH,CAGA,SAAS,EACP,EACA,EACA,EACoB,CACpB,IAAI,EAAU,GACR,EAAY,EAAS,IAAK,GACzB,EAAe,EAAQ,QAAS,CAAI,GACzC,EAAU,GACH,EAAc,CAAE,GAAG,EAAS,QAAS,EAAe,EAAQ,QAAS,EAAM,CAAW,CAAE,CAAC,GAF7C,CAGpD,EACD,OAAO,EAAU,EAAY,CAC/B,CAUA,SAAgB,EACd,EACoB,CACpB,OAAO,EAAoB,EAAU,QAAS,GAAS,EAAkB,CAAmB,CAAC,CAC/F,CAUA,SAAgB,EACd,EACoB,CACpB,OAAO,EAAoB,EAAU,WAAY,GAAS,EAAqB,CAAsB,CAAC,CACxG"}
@@ -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.0`,...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.1`,...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
@@ -20,7 +20,7 @@ interface ObservationResource {
20
20
  readonly environment?: string;
21
21
  readonly attributes?: Readonly<Record<string, JsonValue>>;
22
22
  }
23
- type ObservationEventName = 'sdk.agent.run' | 'sdk.agent.turn' | 'sdk.model.call' | 'sdk.provider.attempt' | 'sdk.provider.retry.scheduled' | 'sdk.tool.call' | 'sdk.compaction' | 'sdk.hook.call' | 'sdk.user.input.wait' | 'sdk.skill.operation' | 'sdk.memory.operation' | 'sdk.credential.operation' | 'sdk.integration.request' | 'sdk.observer.failure' | 'sdk.exporter.state' | 'sdk.log';
23
+ type ObservationEventName = 'sdk.agent.run' | 'sdk.agent.turn' | 'sdk.model.call' | 'sdk.embedding.call' | 'sdk.embedding.batch' | 'sdk.provider.attempt' | 'sdk.provider.retry.scheduled' | 'sdk.tool.call' | 'sdk.compaction' | 'sdk.hook.call' | 'sdk.user.input.wait' | 'sdk.skill.operation' | 'sdk.memory.operation' | 'sdk.credential.operation' | 'sdk.integration.request' | 'sdk.observer.failure' | 'sdk.exporter.state' | 'sdk.log';
24
24
  interface ObservationEvent<Name extends ObservationEventName = ObservationEventName, Data extends JsonObject = JsonObject> {
25
25
  readonly schemaVersion: 1;
26
26
  readonly eventId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"event.d.ts","names":[],"sources":["../../src/observation/event.ts"],"mappings":";;;KAGY;KACA;KACA;UAEK;WACN;WACA;WACA;WACA,aAAa,SAAS,eAAe;;UAG/B;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA,aAAa,SAAS,eAAe;;KAGpC;UAkBK,iBACf,aAAa,uBAAuB,sBACpC,aAAa,aAAa;WAEjB;WACA;WACA;WACA,MAAM;WACN,OAAO;WACP;WACA;WACA,UAAU;WACV,UAAU;WACV,aAAa;WACb,MAAM;;UAGA;WACN;WACA;WACA;WACA;WACA;WACA;WACA;;;iBA6BK,gBAAgB,gBAAgB,yBAAuB"}
1
+ {"version":3,"file":"event.d.ts","names":[],"sources":["../../src/observation/event.ts"],"mappings":";;;KAGY;KACA;KACA;UAEK;WACN;WACA;WACA;WACA,aAAa,SAAS,eAAe;;UAG/B;WACN;WACA;WACA;WACA;WACA;WACA;WACA;WACA,aAAa,SAAS,eAAe;;KAGpC;UAoBK,iBACf,aAAa,uBAAuB,sBACpC,aAAa,aAAa;WAEjB;WACA;WACA;WACA,MAAM;WACN,OAAO;WACP;WACA;WACA,UAAU;WACV,UAAU;WACV,aAAa;WACb,MAAM;;UAGA;WACN;WACA;WACA;WACA;WACA;WACA;WACA;;;iBA6BK,gBAAgB,gBAAgB,yBAAuB"}
@@ -1 +1 @@
1
- {"version":3,"file":"event.js","names":[],"sources":["../../src/observation/event.ts"],"sourcesContent":["import type { JsonObject, JsonValue } from '../primitives/json.ts'\nimport type { CorrelationContext } from './context.ts'\n\nexport type ObservationPriority = 'critical' | 'normal' | 'verbose'\nexport type ObservationPhase = 'start' | 'end' | 'point'\nexport type OperationStatus = 'success' | 'error' | 'aborted' | 'rejected' | 'unknown'\n\nexport interface ObservationResourceInput {\n readonly serviceName?: string\n readonly serviceVersion?: string\n readonly environment?: string\n readonly attributes?: Readonly<Record<string, JsonValue>>\n}\n\nexport interface ObservationResource {\n readonly sdkName: 'ai-agent-sdk'\n readonly sdkVersion: string\n readonly serviceName?: string\n readonly serviceVersion?: string\n readonly runtime: 'browser' | 'edge' | 'node' | 'unknown'\n readonly runtimeId?: string\n readonly environment?: string\n readonly attributes?: Readonly<Record<string, JsonValue>>\n}\n\nexport type ObservationEventName =\n | 'sdk.agent.run'\n | 'sdk.agent.turn'\n | 'sdk.model.call'\n | 'sdk.provider.attempt'\n | 'sdk.provider.retry.scheduled'\n | 'sdk.tool.call'\n | 'sdk.compaction'\n | 'sdk.hook.call'\n | 'sdk.user.input.wait'\n | 'sdk.skill.operation'\n | 'sdk.memory.operation'\n | 'sdk.credential.operation'\n | 'sdk.integration.request'\n | 'sdk.observer.failure'\n | 'sdk.exporter.state'\n | 'sdk.log'\n\nexport interface ObservationEvent<\n Name extends ObservationEventName = ObservationEventName,\n Data extends JsonObject = JsonObject,\n> {\n readonly schemaVersion: 1\n readonly eventId: string\n readonly sequence: number\n readonly name: Name\n readonly phase: ObservationPhase\n readonly occurredAt: string\n readonly monotonicMs: number\n readonly priority: ObservationPriority\n readonly resource: ObservationResource\n readonly correlation: CorrelationContext\n readonly data: Data\n}\n\nexport interface SafeErrorRecord {\n readonly type: string\n readonly message: string\n readonly code?: string\n readonly retryable?: boolean\n readonly status?: number\n readonly causeTypes?: readonly string[]\n readonly stack?: string\n}\n\nfunction boundedUnknownMessage(value: unknown): string {\n try {\n const rendered = typeof value === 'string' ? value : String(value)\n return rendered.slice(0, 2_048)\n } catch {\n return '<unrenderable value>'\n }\n}\n\nfunction safeRead(value: object, key: PropertyKey): unknown {\n try {\n return Reflect.get(value, key)\n } catch {\n return undefined\n }\n}\n\nfunction isError(value: unknown): value is Error {\n try {\n return value instanceof Error\n } catch {\n return false\n }\n}\n\n/** Converts thrown values without retaining bodies, credentials, or stacks by default. */\nexport function safeErrorRecord(value: unknown, includeStack = false): SafeErrorRecord {\n if (!isError(value)) return Object.freeze({ type: typeof value, message: boundedUnknownMessage(value) })\n const source = value as object\n const causeTypes: string[] = []\n let cause = safeRead(source, 'cause')\n const seen = new Set<unknown>()\n while (cause !== undefined && cause !== null && !seen.has(cause)) {\n seen.add(cause)\n const causeIsError = isError(cause)\n const causeName = causeIsError ? safeRead(cause, 'name') : undefined\n causeTypes.push(typeof causeName === 'string' && causeName.length > 0 ? causeName : causeIsError ? 'Error' : typeof cause)\n cause = causeIsError ? safeRead(cause, 'cause') : undefined\n }\n const name = safeRead(source, 'name')\n const message = safeRead(source, 'message')\n const code = safeRead(source, 'code')\n const retryable = safeRead(source, 'retryable')\n const status = safeRead(source, 'status')\n const stack = includeStack ? safeRead(source, 'stack') : undefined\n return Object.freeze({\n type: typeof name === 'string' && name.length > 0 ? name : 'Error',\n message: boundedUnknownMessage(message),\n ...typeof code === 'string' && code.length > 0 ? { code } : {},\n ...typeof retryable === 'boolean' ? { retryable } : {},\n ...typeof status === 'number' && Number.isInteger(status) ? { status } : {},\n ...causeTypes.length > 0 ? { causeTypes: Object.freeze(causeTypes) } : {},\n ...typeof stack === 'string' ? { stack } : {},\n })\n}\n"],"mappings":"AAsEA,SAAS,EAAsB,EAAwB,CACrD,GAAI,CAEF,OADiB,OAAO,GAAU,SAAW,EAAQ,OAAO,CAAK,EAAA,CACjD,MAAM,EAAG,IAAK,CAChC,MAAQ,CACN,MAAO,sBACT,CACF,CAEA,SAAS,EAAS,EAAe,EAA2B,CAC1D,GAAI,CACF,OAAO,QAAQ,IAAI,EAAO,CAAG,CAC/B,MAAQ,CACN,MACF,CACF,CAEA,SAAS,EAAQ,EAAgC,CAC/C,GAAI,CACF,OAAO,aAAiB,KAC1B,MAAQ,CACN,MAAO,EACT,CACF,CAGA,SAAgB,EAAgB,EAAgB,EAAe,GAAwB,CACrF,GAAI,CAAC,EAAQ,CAAK,EAAG,OAAO,OAAO,OAAO,CAAE,KAAM,OAAO,EAAO,QAAS,EAAsB,CAAK,CAAE,CAAC,EACvG,IAAM,EAAS,EACT,EAAuB,CAAC,EAC1B,EAAQ,EAAS,EAAQ,OAAO,EAC9B,EAAO,IAAI,IACjB,KAAO,GAAiC,MAAQ,CAAC,EAAK,IAAI,CAAK,GAAG,CAChE,EAAK,IAAI,CAAK,EACd,IAAM,EAAe,EAAQ,CAAK,EAC5B,EAAY,EAAe,EAAS,EAAO,MAAM,EAAI,IAAA,GAC3D,EAAW,KAAK,OAAO,GAAc,UAAY,EAAU,OAAS,EAAI,EAAY,EAAe,QAAU,OAAO,CAAK,EACzH,EAAQ,EAAe,EAAS,EAAO,OAAO,EAAI,IAAA,EACpD,CACA,IAAM,EAAO,EAAS,EAAQ,MAAM,EAC9B,EAAU,EAAS,EAAQ,SAAS,EACpC,EAAO,EAAS,EAAQ,MAAM,EAC9B,EAAY,EAAS,EAAQ,WAAW,EACxC,EAAS,EAAS,EAAQ,QAAQ,EAClC,EAAQ,EAAe,EAAS,EAAQ,OAAO,EAAI,IAAA,GACzD,OAAO,OAAO,OAAO,CACnB,KAAM,OAAO,GAAS,UAAY,EAAK,OAAS,EAAI,EAAO,QAC3D,QAAS,EAAsB,CAAO,EACtC,GAAG,OAAO,GAAS,UAAY,EAAK,OAAS,EAAI,CAAE,MAAK,EAAI,CAAC,EAC7D,GAAG,OAAO,GAAc,UAAY,CAAE,WAAU,EAAI,CAAC,EACrD,GAAG,OAAO,GAAW,UAAY,OAAO,UAAU,CAAM,EAAI,CAAE,QAAO,EAAI,CAAC,EAC1E,GAAG,EAAW,OAAS,EAAI,CAAE,WAAY,OAAO,OAAO,CAAU,CAAE,EAAI,CAAC,EACxE,GAAG,OAAO,GAAU,SAAW,CAAE,OAAM,EAAI,CAAC,CAC9C,CAAC,CACH"}
1
+ {"version":3,"file":"event.js","names":[],"sources":["../../src/observation/event.ts"],"sourcesContent":["import type { JsonObject, JsonValue } from '../primitives/json.ts'\nimport type { CorrelationContext } from './context.ts'\n\nexport type ObservationPriority = 'critical' | 'normal' | 'verbose'\nexport type ObservationPhase = 'start' | 'end' | 'point'\nexport type OperationStatus = 'success' | 'error' | 'aborted' | 'rejected' | 'unknown'\n\nexport interface ObservationResourceInput {\n readonly serviceName?: string\n readonly serviceVersion?: string\n readonly environment?: string\n readonly attributes?: Readonly<Record<string, JsonValue>>\n}\n\nexport interface ObservationResource {\n readonly sdkName: 'ai-agent-sdk'\n readonly sdkVersion: string\n readonly serviceName?: string\n readonly serviceVersion?: string\n readonly runtime: 'browser' | 'edge' | 'node' | 'unknown'\n readonly runtimeId?: string\n readonly environment?: string\n readonly attributes?: Readonly<Record<string, JsonValue>>\n}\n\nexport type ObservationEventName =\n | 'sdk.agent.run'\n | 'sdk.agent.turn'\n | 'sdk.model.call'\n | 'sdk.embedding.call'\n | 'sdk.embedding.batch'\n | 'sdk.provider.attempt'\n | 'sdk.provider.retry.scheduled'\n | 'sdk.tool.call'\n | 'sdk.compaction'\n | 'sdk.hook.call'\n | 'sdk.user.input.wait'\n | 'sdk.skill.operation'\n | 'sdk.memory.operation'\n | 'sdk.credential.operation'\n | 'sdk.integration.request'\n | 'sdk.observer.failure'\n | 'sdk.exporter.state'\n | 'sdk.log'\n\nexport interface ObservationEvent<\n Name extends ObservationEventName = ObservationEventName,\n Data extends JsonObject = JsonObject,\n> {\n readonly schemaVersion: 1\n readonly eventId: string\n readonly sequence: number\n readonly name: Name\n readonly phase: ObservationPhase\n readonly occurredAt: string\n readonly monotonicMs: number\n readonly priority: ObservationPriority\n readonly resource: ObservationResource\n readonly correlation: CorrelationContext\n readonly data: Data\n}\n\nexport interface SafeErrorRecord {\n readonly type: string\n readonly message: string\n readonly code?: string\n readonly retryable?: boolean\n readonly status?: number\n readonly causeTypes?: readonly string[]\n readonly stack?: string\n}\n\nfunction boundedUnknownMessage(value: unknown): string {\n try {\n const rendered = typeof value === 'string' ? value : String(value)\n return rendered.slice(0, 2_048)\n } catch {\n return '<unrenderable value>'\n }\n}\n\nfunction safeRead(value: object, key: PropertyKey): unknown {\n try {\n return Reflect.get(value, key)\n } catch {\n return undefined\n }\n}\n\nfunction isError(value: unknown): value is Error {\n try {\n return value instanceof Error\n } catch {\n return false\n }\n}\n\n/** Converts thrown values without retaining bodies, credentials, or stacks by default. */\nexport function safeErrorRecord(value: unknown, includeStack = false): SafeErrorRecord {\n if (!isError(value)) return Object.freeze({ type: typeof value, message: boundedUnknownMessage(value) })\n const source = value as object\n const causeTypes: string[] = []\n let cause = safeRead(source, 'cause')\n const seen = new Set<unknown>()\n while (cause !== undefined && cause !== null && !seen.has(cause)) {\n seen.add(cause)\n const causeIsError = isError(cause)\n const causeName = causeIsError ? safeRead(cause, 'name') : undefined\n causeTypes.push(typeof causeName === 'string' && causeName.length > 0 ? causeName : causeIsError ? 'Error' : typeof cause)\n cause = causeIsError ? safeRead(cause, 'cause') : undefined\n }\n const name = safeRead(source, 'name')\n const message = safeRead(source, 'message')\n const code = safeRead(source, 'code')\n const retryable = safeRead(source, 'retryable')\n const status = safeRead(source, 'status')\n const stack = includeStack ? safeRead(source, 'stack') : undefined\n return Object.freeze({\n type: typeof name === 'string' && name.length > 0 ? name : 'Error',\n message: boundedUnknownMessage(message),\n ...typeof code === 'string' && code.length > 0 ? { code } : {},\n ...typeof retryable === 'boolean' ? { retryable } : {},\n ...typeof status === 'number' && Number.isInteger(status) ? { status } : {},\n ...causeTypes.length > 0 ? { causeTypes: Object.freeze(causeTypes) } : {},\n ...typeof stack === 'string' ? { stack } : {},\n })\n}\n"],"mappings":"AAwEA,SAAS,EAAsB,EAAwB,CACrD,GAAI,CAEF,OADiB,OAAO,GAAU,SAAW,EAAQ,OAAO,CAAK,EAAA,CACjD,MAAM,EAAG,IAAK,CAChC,MAAQ,CACN,MAAO,sBACT,CACF,CAEA,SAAS,EAAS,EAAe,EAA2B,CAC1D,GAAI,CACF,OAAO,QAAQ,IAAI,EAAO,CAAG,CAC/B,MAAQ,CACN,MACF,CACF,CAEA,SAAS,EAAQ,EAAgC,CAC/C,GAAI,CACF,OAAO,aAAiB,KAC1B,MAAQ,CACN,MAAO,EACT,CACF,CAGA,SAAgB,EAAgB,EAAgB,EAAe,GAAwB,CACrF,GAAI,CAAC,EAAQ,CAAK,EAAG,OAAO,OAAO,OAAO,CAAE,KAAM,OAAO,EAAO,QAAS,EAAsB,CAAK,CAAE,CAAC,EACvG,IAAM,EAAS,EACT,EAAuB,CAAC,EAC1B,EAAQ,EAAS,EAAQ,OAAO,EAC9B,EAAO,IAAI,IACjB,KAAO,GAAiC,MAAQ,CAAC,EAAK,IAAI,CAAK,GAAG,CAChE,EAAK,IAAI,CAAK,EACd,IAAM,EAAe,EAAQ,CAAK,EAC5B,EAAY,EAAe,EAAS,EAAO,MAAM,EAAI,IAAA,GAC3D,EAAW,KAAK,OAAO,GAAc,UAAY,EAAU,OAAS,EAAI,EAAY,EAAe,QAAU,OAAO,CAAK,EACzH,EAAQ,EAAe,EAAS,EAAO,OAAO,EAAI,IAAA,EACpD,CACA,IAAM,EAAO,EAAS,EAAQ,MAAM,EAC9B,EAAU,EAAS,EAAQ,SAAS,EACpC,EAAO,EAAS,EAAQ,MAAM,EAC9B,EAAY,EAAS,EAAQ,WAAW,EACxC,EAAS,EAAS,EAAQ,QAAQ,EAClC,EAAQ,EAAe,EAAS,EAAQ,OAAO,EAAI,IAAA,GACzD,OAAO,OAAO,OAAO,CACnB,KAAM,OAAO,GAAS,UAAY,EAAK,OAAS,EAAI,EAAO,QAC3D,QAAS,EAAsB,CAAO,EACtC,GAAG,OAAO,GAAS,UAAY,EAAK,OAAS,EAAI,CAAE,MAAK,EAAI,CAAC,EAC7D,GAAG,OAAO,GAAc,UAAY,CAAE,WAAU,EAAI,CAAC,EACrD,GAAG,OAAO,GAAW,UAAY,OAAO,UAAU,CAAM,EAAI,CAAE,QAAO,EAAI,CAAC,EAC1E,GAAG,EAAW,OAAS,EAAI,CAAE,WAAY,OAAO,OAAO,CAAU,CAAE,EAAI,CAAC,EACxE,GAAG,OAAO,GAAU,SAAW,CAAE,OAAM,EAAI,CAAC,CAC9C,CAAC,CACH"}
@@ -12,7 +12,7 @@ interface CaptureReceipt {
12
12
  }
13
13
  /** Validate an untrusted observer receipt before using it for delivery claims. */
14
14
  declare function validateCaptureReceipt(value: unknown, eventId: string): CaptureReceipt;
15
- type ObservationSpanName = 'sdk.agent.run' | 'sdk.agent.turn' | 'sdk.model.call' | 'sdk.provider.attempt' | 'sdk.tool.call' | 'sdk.compaction' | 'sdk.hook.call' | 'sdk.user.input.wait' | 'sdk.skill.operation' | 'sdk.memory.operation' | 'sdk.credential.operation' | 'sdk.integration.request';
15
+ type ObservationSpanName = 'sdk.agent.run' | 'sdk.agent.turn' | 'sdk.model.call' | 'sdk.embedding.call' | 'sdk.embedding.batch' | 'sdk.provider.attempt' | 'sdk.tool.call' | 'sdk.compaction' | 'sdk.hook.call' | 'sdk.user.input.wait' | 'sdk.skill.operation' | 'sdk.memory.operation' | 'sdk.credential.operation' | 'sdk.integration.request';
16
16
  interface OpenObservationSpanInput {
17
17
  readonly name: ObservationSpanName;
18
18
  readonly runId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"port.d.ts","names":[],"sources":["../../src/observation/port.ts"],"mappings":";;;KAIY;KACA;UAEK;WACN;WACA;WACA;WACA,UAAU;WACV;;;iBAaK,uBAAuB,gBAAgB,kBAAkB;KAqC7D;UAcK;WACN,MAAM;WACN;WACA,SAAS;WACT,cAAc,KAAK,QAAQ;WAC3B;WACA;;UAGM;WACN,aAAa;WACb;EACT,IAAI,QAAQ,iBAAiB,iBAAiB;;UAG/B;WACN,MAAM;EACf,SAAS,OAAO,2BAA2B;EAC3C,QAAQ,OAAO,mBAAmB;EAClC,YAAY,OAAO,kBAAkB,SAAS,cAAc,QAAQ;;UAGrD;WACN,MAAM;WACN,kBAAkB;WAClB,iBAAiB;WACjB;WACA;WACA;WACA;WACA,cAAc;;iBAGT,eAAe,OAAO,2BAA2B;UAmBvD,gCAAgC;WAC/B,KAAK;;;iBAoBA,wBAAwB,iBAAiB;iBAmCzC,qBAAqB,iBAAiB,SAAS;iBAI/C,2BAA2B;cAY9B,uBAAuB"}
1
+ {"version":3,"file":"port.d.ts","names":[],"sources":["../../src/observation/port.ts"],"mappings":";;;KAIY;KACA;UAEK;WACN;WACA;WACA;WACA,UAAU;WACV;;;iBAaK,uBAAuB,gBAAgB,kBAAkB;KAqC7D;UAgBK;WACN,MAAM;WACN;WACA,SAAS;WACT,cAAc,KAAK,QAAQ;WAC3B;WACA;;UAGM;WACN,aAAa;WACb;EACT,IAAI,QAAQ,iBAAiB,iBAAiB;;UAG/B;WACN,MAAM;EACf,SAAS,OAAO,2BAA2B;EAC3C,QAAQ,OAAO,mBAAmB;EAClC,YAAY,OAAO,kBAAkB,SAAS,cAAc,QAAQ;;UAGrD;WACN,MAAM;WACN,kBAAkB;WAClB,iBAAiB;WACjB;WACA;WACA;WACA;WACA,cAAc;;iBAGT,eAAe,OAAO,2BAA2B;UAmBvD,gCAAgC;WAC/B,KAAK;;;iBAoBA,wBAAwB,iBAAiB;iBAmCzC,qBAAqB,iBAAiB,SAAS;iBAI/C,2BAA2B;cAY9B,uBAAuB"}