@alvin0/ai-agent-sdk-core 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -1
- package/dist/agent/accounting/ledger.js +1 -1
- package/dist/agent/accounting/ledger.js.map +1 -1
- package/dist/agent/accounting/report.d.ts +1 -1
- package/dist/agent/define/definition.d.ts +27 -6
- package/dist/agent/define/definition.d.ts.map +1 -1
- package/dist/agent/define/definition.js +1 -1
- package/dist/agent/define/definition.js.map +1 -1
- package/dist/agent/define/session/accounting.js +1 -1
- package/dist/agent/define/session/accounting.js.map +1 -1
- package/dist/agent/define/session/model-config.js +1 -1
- package/dist/agent/define/session/model-config.js.map +1 -1
- package/dist/agent/define/session/types.d.ts +6 -3
- package/dist/agent/define/session/types.d.ts.map +1 -1
- package/dist/agent/define/session.d.ts +25 -2
- package/dist/agent/define/session.d.ts.map +1 -1
- package/dist/agent/define/session.js +1 -1
- package/dist/agent/define/session.js.map +1 -1
- package/dist/agent/loop/admission.js +2 -0
- package/dist/agent/loop/admission.js.map +1 -0
- package/dist/agent/loop/events.d.ts +4 -0
- package/dist/agent/loop/events.d.ts.map +1 -1
- package/dist/agent/loop/program.js +2 -0
- package/dist/agent/loop/program.js.map +1 -0
- package/dist/agent/loop/run-turn.d.ts.map +1 -1
- package/dist/agent/loop/run-turn.js +1 -1
- package/dist/agent/loop/run-turn.js.map +1 -1
- package/dist/agent/loop/schedule.d.ts.map +1 -1
- package/dist/agent/loop/schedule.js +2 -2
- package/dist/agent/loop/schedule.js.map +1 -1
- package/dist/agent/loop/tool-call-support.js +2 -0
- package/dist/agent/loop/tool-call-support.js.map +1 -0
- package/dist/agent/loop/turn/config.js +1 -1
- package/dist/agent/loop/turn/config.js.map +1 -1
- package/dist/agent/loop/turn/hooks.js +1 -1
- package/dist/agent/loop/turn/hooks.js.map +1 -1
- package/dist/agent/loop/turn/model-request-boundary.js +2 -0
- package/dist/agent/loop/turn/model-request-boundary.js.map +1 -0
- package/dist/agent/loop/turn/model-round.js +1 -1
- package/dist/agent/loop/turn/model-round.js.map +1 -1
- package/dist/agent/loop/turn/step-projection.js +2 -0
- package/dist/agent/loop/turn/step-projection.js.map +1 -0
- package/dist/agent/loop/turn/types.d.ts +6 -0
- package/dist/agent/loop/turn/types.d.ts.map +1 -1
- package/dist/agent/memory/compaction.d.ts.map +1 -1
- package/dist/agent/memory/compaction.js +1 -1
- package/dist/agent/memory/compaction.js.map +1 -1
- package/dist/agent/memory/context-optimizer.d.ts +61 -0
- package/dist/agent/memory/context-optimizer.d.ts.map +1 -0
- package/dist/agent/memory/context-optimizer.js +4 -0
- package/dist/agent/memory/context-optimizer.js.map +1 -0
- package/dist/agent/memory/memory.js +1 -1
- package/dist/agent/memory/memory.js.map +1 -1
- package/dist/agent/mode/run-agent.d.ts +15 -1
- package/dist/agent/mode/run-agent.d.ts.map +1 -1
- package/dist/agent/mode/run-agent.js +2 -2
- package/dist/agent/mode/run-agent.js.map +1 -1
- package/dist/agent/skill/provider/snapshot.js +1 -1
- package/dist/agent/team/managed.d.ts +33 -64
- package/dist/agent/team/managed.d.ts.map +1 -1
- package/dist/agent/team/managed.js +6 -3
- package/dist/agent/team/managed.js.map +1 -1
- package/dist/agent/team/team.d.ts +2 -0
- package/dist/agent/team/team.d.ts.map +1 -1
- package/dist/agent/team/team.js +1 -1
- package/dist/agent/team/team.js.map +1 -1
- package/dist/agent/team/types.d.ts +1 -0
- package/dist/agent/team/types.d.ts.map +1 -1
- package/dist/agent/tool/action-fusion.d.ts +30 -0
- package/dist/agent/tool/action-fusion.d.ts.map +1 -0
- package/dist/agent/tool/action-fusion.js +2 -0
- package/dist/agent/tool/action-fusion.js.map +1 -0
- package/dist/agent/tool/capture.js +1 -1
- package/dist/agent/tool/capture.js.map +1 -1
- package/dist/agent/tool/definition.d.ts +8 -0
- package/dist/agent/tool/definition.d.ts.map +1 -1
- package/dist/agent/tool/definition.js.map +1 -1
- package/dist/agent/tool/evidence-reducer.d.ts +41 -0
- package/dist/agent/tool/evidence-reducer.d.ts.map +1 -0
- package/dist/agent/tool/evidence-reducer.js +7 -0
- package/dist/agent/tool/evidence-reducer.js.map +1 -0
- package/dist/agent/tool/nested.d.ts +117 -0
- package/dist/agent/tool/nested.d.ts.map +1 -0
- package/dist/agent/tool/nested.js +2 -0
- package/dist/agent/tool/nested.js.map +1 -0
- package/dist/agent/tool/output-budget.d.ts.map +1 -1
- package/dist/agent/tool/output-budget.js +2 -2
- package/dist/agent/tool/output-budget.js.map +1 -1
- package/dist/agent/tool/output-schema.js +2 -0
- package/dist/agent/tool/output-schema.js.map +1 -0
- package/dist/agent/tool/pipeline.d.ts +7 -0
- package/dist/agent/tool/pipeline.d.ts.map +1 -1
- package/dist/agent/tool/pipeline.js +2 -2
- package/dist/agent/tool/pipeline.js.map +1 -1
- package/dist/agent/tool/program-results.js +2 -0
- package/dist/agent/tool/program-results.js.map +1 -0
- package/dist/agent.d.ts +6 -2
- package/dist/agent.js +1 -1
- package/dist/composition/agent/definition.js +1 -1
- package/dist/composition/agent/definition.js.map +1 -1
- package/dist/composition/agent/options.js +1 -1
- package/dist/composition/agent/options.js.map +1 -1
- package/dist/composition/agent/session.js +1 -1
- package/dist/composition/agent/session.js.map +1 -1
- package/dist/composition/agent/types.d.ts +17 -10
- package/dist/composition/agent/types.d.ts.map +1 -1
- package/dist/composition/runtime/owner.js +1 -1
- package/dist/composition/runtime/owner.js.map +1 -1
- package/dist/composition/runtime/types.d.ts +7 -1
- package/dist/composition/runtime/types.d.ts.map +1 -1
- package/dist/composition/tool-source/snapshot.js +1 -1
- package/dist/contract/adapter.d.ts +1 -1
- package/dist/contract/call-config.d.ts +8 -1
- package/dist/contract/call-config.d.ts.map +1 -1
- package/dist/contract/call-config.js +1 -1
- package/dist/contract/call-config.js.map +1 -1
- package/dist/contract/generate-options.d.ts +5 -0
- package/dist/contract/generate-options.d.ts.map +1 -1
- package/dist/contract/model-info.d.ts +26 -7
- package/dist/contract/model-info.d.ts.map +1 -1
- package/dist/errors/model-error.d.ts +0 -1
- package/dist/errors/model-error.d.ts.map +1 -1
- package/dist/errors/model-error.js +1 -1
- package/dist/errors/model-error.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +1 -1
- package/dist/memory.d.ts +2 -1
- package/dist/memory.js +1 -1
- package/dist/observability/bus.js +1 -1
- package/dist/observation/report.d.ts +11 -0
- package/dist/observation/report.d.ts.map +1 -1
- package/dist/observation/report.js.map +1 -1
- package/dist/primitives/version.d.ts +1 -1
- package/dist/primitives/version.js +1 -1
- package/dist/primitives/version.js.map +1 -1
- package/dist/provider.d.ts +1 -1
- package/dist/runtime/model-call-handle.js +1 -1
- package/dist/runtime/model-call-handle.js.map +1 -1
- package/dist/runtime/model-metadata.js +1 -1
- package/dist/runtime/model-metadata.js.map +1 -1
- package/dist/runtime/model-stream.js +1 -1
- package/dist/runtime/model-stream.js.map +1 -1
- package/dist/runtime/registry.d.ts +7 -1
- package/dist/runtime/registry.d.ts.map +1 -1
- package/dist/runtime/registry.js +1 -1
- package/dist/runtime/registry.js.map +1 -1
- package/dist/tools.d.ts +4 -1
- package/dist/tools.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-info.d.ts","names":[],"sources":["../../src/contract/model-info.ts"],"mappings":";;;;;UAWiB;;EAEf;;EAEA;;;UAIe;EACf;EACA;EACA;;;KAIU,gBAAgB,uBAAuB;;;;;;;;UASlC;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;;;EAQA,2BAA2B;;EAE3B,4BAA4B;;EAE5B,uBAAuB;;;
|
|
1
|
+
{"version":3,"file":"model-info.d.ts","names":[],"sources":["../../src/contract/model-info.ts"],"mappings":";;;;;UAWiB;;EAEf;;EAEA;;;UAIe;EACf;EACA;EACA;;;KAIU,gBAAgB,uBAAuB;;;;;;;;UASlC;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;;;EAQA,2BAA2B;;EAE3B,4BAA4B;;EAE5B,uBAAuB;;;;;;;;;;;UAYR;;WAEN;;WAEA;;WAEA,2BAA2B;;;UAIrB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;;UAIe;;EAEf,IAAI;;EAEJ;;EAEA;;;;;;;;;;UAWe;;EAEf,kBAAkB;;;UAIH,0BAA0B;;EAEzC,UAAU;;EAEV;;EAEA;;EAEA,YAAY;;KAGF;UAEK;WACN,SAAS;WACT;;UAGM;WACN,UAAU;WACV,OAAO;WACP;WACA,iBAAiB;WACjB;WACA;WACA;WACA,QAAQ"}
|
|
@@ -72,7 +72,6 @@ declare const REGISTRY_ERROR_CODES: Readonly<{
|
|
|
72
72
|
readonly INVALID_ADAPTER: 'INVALID_ADAPTER';
|
|
73
73
|
readonly INVALID_CATALOG: 'INVALID_CATALOG';
|
|
74
74
|
readonly INVALID_MODEL_INFO: 'INVALID_MODEL_INFO';
|
|
75
|
-
readonly UNSUPPORTED_REASONING_EFFORT: 'UNSUPPORTED_REASONING_EFFORT';
|
|
76
75
|
readonly UNSUPPORTED_NATIVE_TOOL: 'UNSUPPORTED_NATIVE_TOOL';
|
|
77
76
|
readonly OUTPUT_TOKEN_LIMIT_EXCEEDED: 'OUTPUT_TOKEN_LIMIT_EXCEEDED';
|
|
78
77
|
readonly INVALID_PREPARED_CALL: 'INVALID_PREPARED_CALL';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-error.d.ts","names":[],"sources":["../../src/errors/model-error.ts"],"mappings":";;;;;UAiBiB,0BAA0B;;EAEzC;;EAEA;;EAEA,YAAY;;;;;;;;;;cAWD,mBAAmB;;WAErB,SAAS;;;;;;EAOlB,YAAY,iBAAiB,cAAc,UAAU;;;;;;;;;;cAyC1C,mBAAiB;;WAEtB;;WAEM;;WAEJ;;WAEC;;WAEE;;WAEF;;WAES;;WAED;;WAEG;;WAEL;;WAEM;;WAED;;WAEX;;;cAIE,sBAAoB;WACnB;WACO;WACF;WACA;WACG;
|
|
1
|
+
{"version":3,"file":"model-error.d.ts","names":[],"sources":["../../src/errors/model-error.ts"],"mappings":";;;;;UAiBiB,0BAA0B;;EAEzC;;EAEA;;EAEA,YAAY;;;;;;;;;;cAWD,mBAAmB;;WAErB,SAAS;;;;;;EAOlB,YAAY,iBAAiB,cAAc,UAAU;;;;;;;;;;cAyC1C,mBAAiB;;WAEtB;;WAEM;;WAEJ;;WAEC;;WAEE;;WAEF;;WAES;;WAED;;WAEG;;WAEL;;WAEM;;WAED;;WAEX;;;cAIE,sBAAoB;WACnB;WACO;WACF;WACA;WACG;WACK;WACI;WACN;WACA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{AgentSdkError as e}from"./agent-sdk-error.js";var t=class extends e{failure;constructor(e,t,n){if(typeof e!=`string`||e.length===0)throw Error(`ModelError message must be a non-empty string`);if(typeof t!=`string`||t.length===0)throw Error(`ModelError code must be a non-empty string`);if(n?.status!==void 0&&(!Number.isInteger(n.status)||n.status<100||n.status>599))throw Error(`ModelError status must be an integer from 100 through 599`);if(n?.providerRetryAfterMs!==void 0&&(!Number.isFinite(n.providerRetryAfterMs)||n.providerRetryAfterMs<=0))throw Error(`ModelError providerRetryAfterMs must be a positive finite number`);if(n?.requestId!==void 0&&(typeof n.requestId!=`string`||n.requestId.length===0))throw Error(`ModelError requestId must be a non-empty string`);super(e,t,n),this.name=`ModelError`,this.failure=Object.freeze({message:e,code:t,...n?.status===void 0?{}:{status:n.status},...n?.providerRetryAfterMs===void 0?{}:{providerRetryAfterMs:n.providerRetryAfterMs},...n?.requestId===void 0?{}:{requestId:n.requestId}})}};const n=Object.freeze({AUTH:`AUTH`,RATE_LIMIT:`RATE_LIMIT`,SERVER:`SERVER`,TIMEOUT:`TIMEOUT`,TRANSPORT:`TRANSPORT`,ABORTED:`ABORTED`,TEARDOWN_TIMEOUT:`MODEL_TEARDOWN_TIMEOUT`,INVALID_REQUEST:`INVALID_REQUEST`,MALFORMED_RESPONSE:`MALFORMED_RESPONSE`,STREAM_CLOSED:`STREAM_CLOSED`,UNSUPPORTED_CONTENT:`UNSUPPORTED_CONTENT`,UNSUPPORTED_OPTION:`UNSUPPORTED_OPTION`,UNKNOWN:`UNKNOWN`}),r=Object.freeze({NO_ADAPTER:`NO_ADAPTER`,DUPLICATE_ADAPTER:`DUPLICATE_ADAPTER`,INVALID_ADAPTER:`INVALID_ADAPTER`,INVALID_CATALOG:`INVALID_CATALOG`,INVALID_MODEL_INFO:`INVALID_MODEL_INFO`,
|
|
1
|
+
import{AgentSdkError as e}from"./agent-sdk-error.js";var t=class extends e{failure;constructor(e,t,n){if(typeof e!=`string`||e.length===0)throw Error(`ModelError message must be a non-empty string`);if(typeof t!=`string`||t.length===0)throw Error(`ModelError code must be a non-empty string`);if(n?.status!==void 0&&(!Number.isInteger(n.status)||n.status<100||n.status>599))throw Error(`ModelError status must be an integer from 100 through 599`);if(n?.providerRetryAfterMs!==void 0&&(!Number.isFinite(n.providerRetryAfterMs)||n.providerRetryAfterMs<=0))throw Error(`ModelError providerRetryAfterMs must be a positive finite number`);if(n?.requestId!==void 0&&(typeof n.requestId!=`string`||n.requestId.length===0))throw Error(`ModelError requestId must be a non-empty string`);super(e,t,n),this.name=`ModelError`,this.failure=Object.freeze({message:e,code:t,...n?.status===void 0?{}:{status:n.status},...n?.providerRetryAfterMs===void 0?{}:{providerRetryAfterMs:n.providerRetryAfterMs},...n?.requestId===void 0?{}:{requestId:n.requestId}})}};const n=Object.freeze({AUTH:`AUTH`,RATE_LIMIT:`RATE_LIMIT`,SERVER:`SERVER`,TIMEOUT:`TIMEOUT`,TRANSPORT:`TRANSPORT`,ABORTED:`ABORTED`,TEARDOWN_TIMEOUT:`MODEL_TEARDOWN_TIMEOUT`,INVALID_REQUEST:`INVALID_REQUEST`,MALFORMED_RESPONSE:`MALFORMED_RESPONSE`,STREAM_CLOSED:`STREAM_CLOSED`,UNSUPPORTED_CONTENT:`UNSUPPORTED_CONTENT`,UNSUPPORTED_OPTION:`UNSUPPORTED_OPTION`,UNKNOWN:`UNKNOWN`}),r=Object.freeze({NO_ADAPTER:`NO_ADAPTER`,DUPLICATE_ADAPTER:`DUPLICATE_ADAPTER`,INVALID_ADAPTER:`INVALID_ADAPTER`,INVALID_CATALOG:`INVALID_CATALOG`,INVALID_MODEL_INFO:`INVALID_MODEL_INFO`,UNSUPPORTED_NATIVE_TOOL:`UNSUPPORTED_NATIVE_TOOL`,OUTPUT_TOKEN_LIMIT_EXCEEDED:`OUTPUT_TOKEN_LIMIT_EXCEEDED`,INVALID_PREPARED_CALL:`INVALID_PREPARED_CALL`,REGISTRATION_DISPOSED:`REGISTRATION_DISPOSED`});export{n as MODEL_ERROR_CODES,t as ModelError,r as REGISTRY_ERROR_CODES};
|
|
2
2
|
//# sourceMappingURL=model-error.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-error.js","names":[],"sources":["../../src/errors/model-error.ts"],"sourcesContent":["/**\n * The error adapters throw, and the codes they classify failures into.\n *\n * {@link ModelError} validates its own inputs and exposes a frozen serializable\n * twin ({@link ModelFailure}). The pairing is the point: a live `Error` is what\n * you throw, and a plain data object is what you log, persist, or send across a\n * process boundary Ean `Error` does not survive `structuredClone` or JSON with\n * its class intact.\n *\n * @module ai-agent-sdk/core/errors/model-error\n */\n\nimport type { ProviderRequestId } from '../primitives/brand.ts'\nimport { AgentSdkError } from './agent-sdk-error.ts'\nimport type { ModelFailure } from './failure.ts'\n\n/** Structured provider facts and cause accepted by {@link ModelError}. */\nexport interface ModelErrorOptions extends ErrorOptions {\n /** Valid HTTP status observed at the provider boundary. */\n status?: number\n /** Positive finite provider-requested delay in milliseconds. */\n providerRetryAfterMs?: number\n /** Non-empty opaque provider request id. */\n requestId?: ProviderRequestId\n}\n\n/**\n * Typed error for model-call failures, carrying a stable `code` from the shared\n * taxonomy plus the serializable {@link failure} twin.\n *\n * The constructor validates rather than trusts. An out-of-range `status` or a\n * negative `providerRetryAfterMs` means an adapter misread a header, and letting\n * that through would put a retry to sleep for a nonsense duration.\n */\nexport class ModelError extends AgentSdkError {\n /** Serializable facts retained beside this live Error. */\n readonly failure: ModelFailure\n\n /**\n * @param message - non-empty human-readable failure summary.\n * @param code - non-empty stable provider-neutral machine code.\n * @param options - optional cause and validated serializable provider facts.\n */\n constructor(message: string, code: string, options?: ModelErrorOptions) {\n if (typeof message !== 'string' || message.length === 0) {\n throw new Error('ModelError message must be a non-empty string')\n }\n if (typeof code !== 'string' || code.length === 0) {\n throw new Error('ModelError code must be a non-empty string')\n }\n if (options?.status !== undefined\n && (!Number.isInteger(options.status) || options.status < 100 || options.status > 599)) {\n throw new Error('ModelError status must be an integer from 100 through 599')\n }\n if (options?.providerRetryAfterMs !== undefined\n && (!Number.isFinite(options.providerRetryAfterMs) || options.providerRetryAfterMs <= 0)) {\n throw new Error('ModelError providerRetryAfterMs must be a positive finite number')\n }\n if (options?.requestId !== undefined\n && (typeof options.requestId !== 'string' || options.requestId.length === 0)) {\n throw new Error('ModelError requestId must be a non-empty string')\n }\n super(message, code, options)\n this.name = 'ModelError'\n this.failure = Object.freeze({\n message,\n code,\n ...options?.status === undefined ? {} : { status: options.status },\n ...options?.providerRetryAfterMs === undefined\n ? {}\n : { providerRetryAfterMs: options.providerRetryAfterMs },\n ...options?.requestId === undefined ? {} : { requestId: options.requestId },\n })\n }\n}\n\n/**\n * Codes produced at the provider boundary.\n *\n * Exported as a frozen object rather than a TS enum so that a third-party\n * adapter can emit its own code without this union having to know about it.\n * Retry eligibility is decided by policy against these values, never by the\n * adapter that assigns them Esee `retry-policy.ts`.\n */\nexport const MODEL_ERROR_CODES = Object.freeze({\n /** Credentials were rejected (401/403). */\n AUTH: 'AUTH',\n /** Transient request-rate limiting (429). */\n RATE_LIMIT: 'RATE_LIMIT',\n /** Provider-side fault (5xx). */\n SERVER: 'SERVER',\n /** The provider stopped producing output for longer than the idle bound. */\n TIMEOUT: 'TIMEOUT',\n /** The request never completed at the network layer. */\n TRANSPORT: 'TRANSPORT',\n /** The caller's signal aborted the request. */\n ABORTED: 'ABORTED',\n /** An adapter ignored cancellation and may still own live work. */\n TEARDOWN_TIMEOUT: 'MODEL_TEARDOWN_TIMEOUT',\n /** The provider rejected the request as malformed (400/413). */\n INVALID_REQUEST: 'INVALID_REQUEST',\n /** A well-formed response could not be parsed. */\n MALFORMED_RESPONSE: 'MALFORMED_RESPONSE',\n /** The response body ended before its terminating sentinel. */\n STREAM_CLOSED: 'STREAM_CLOSED',\n /** The request carried content the selected model cannot accept. */\n UNSUPPORTED_CONTENT: 'UNSUPPORTED_CONTENT',\n /** The request set an option this provider has no equivalent for. */\n UNSUPPORTED_OPTION: 'UNSUPPORTED_OPTION',\n /** Nothing classified it; treated as non-retryable. */\n UNKNOWN: 'UNKNOWN',\n} as const)\n\n/** Registry-level codes, raised before any provider I/O happens. */\nexport const REGISTRY_ERROR_CODES = Object.freeze({\n NO_ADAPTER: 'NO_ADAPTER',\n DUPLICATE_ADAPTER: 'DUPLICATE_ADAPTER',\n INVALID_ADAPTER: 'INVALID_ADAPTER',\n INVALID_CATALOG: 'INVALID_CATALOG',\n INVALID_MODEL_INFO: 'INVALID_MODEL_INFO',\n
|
|
1
|
+
{"version":3,"file":"model-error.js","names":[],"sources":["../../src/errors/model-error.ts"],"sourcesContent":["/**\n * The error adapters throw, and the codes they classify failures into.\n *\n * {@link ModelError} validates its own inputs and exposes a frozen serializable\n * twin ({@link ModelFailure}). The pairing is the point: a live `Error` is what\n * you throw, and a plain data object is what you log, persist, or send across a\n * process boundary Ean `Error` does not survive `structuredClone` or JSON with\n * its class intact.\n *\n * @module ai-agent-sdk/core/errors/model-error\n */\n\nimport type { ProviderRequestId } from '../primitives/brand.ts'\nimport { AgentSdkError } from './agent-sdk-error.ts'\nimport type { ModelFailure } from './failure.ts'\n\n/** Structured provider facts and cause accepted by {@link ModelError}. */\nexport interface ModelErrorOptions extends ErrorOptions {\n /** Valid HTTP status observed at the provider boundary. */\n status?: number\n /** Positive finite provider-requested delay in milliseconds. */\n providerRetryAfterMs?: number\n /** Non-empty opaque provider request id. */\n requestId?: ProviderRequestId\n}\n\n/**\n * Typed error for model-call failures, carrying a stable `code` from the shared\n * taxonomy plus the serializable {@link failure} twin.\n *\n * The constructor validates rather than trusts. An out-of-range `status` or a\n * negative `providerRetryAfterMs` means an adapter misread a header, and letting\n * that through would put a retry to sleep for a nonsense duration.\n */\nexport class ModelError extends AgentSdkError {\n /** Serializable facts retained beside this live Error. */\n readonly failure: ModelFailure\n\n /**\n * @param message - non-empty human-readable failure summary.\n * @param code - non-empty stable provider-neutral machine code.\n * @param options - optional cause and validated serializable provider facts.\n */\n constructor(message: string, code: string, options?: ModelErrorOptions) {\n if (typeof message !== 'string' || message.length === 0) {\n throw new Error('ModelError message must be a non-empty string')\n }\n if (typeof code !== 'string' || code.length === 0) {\n throw new Error('ModelError code must be a non-empty string')\n }\n if (options?.status !== undefined\n && (!Number.isInteger(options.status) || options.status < 100 || options.status > 599)) {\n throw new Error('ModelError status must be an integer from 100 through 599')\n }\n if (options?.providerRetryAfterMs !== undefined\n && (!Number.isFinite(options.providerRetryAfterMs) || options.providerRetryAfterMs <= 0)) {\n throw new Error('ModelError providerRetryAfterMs must be a positive finite number')\n }\n if (options?.requestId !== undefined\n && (typeof options.requestId !== 'string' || options.requestId.length === 0)) {\n throw new Error('ModelError requestId must be a non-empty string')\n }\n super(message, code, options)\n this.name = 'ModelError'\n this.failure = Object.freeze({\n message,\n code,\n ...options?.status === undefined ? {} : { status: options.status },\n ...options?.providerRetryAfterMs === undefined\n ? {}\n : { providerRetryAfterMs: options.providerRetryAfterMs },\n ...options?.requestId === undefined ? {} : { requestId: options.requestId },\n })\n }\n}\n\n/**\n * Codes produced at the provider boundary.\n *\n * Exported as a frozen object rather than a TS enum so that a third-party\n * adapter can emit its own code without this union having to know about it.\n * Retry eligibility is decided by policy against these values, never by the\n * adapter that assigns them Esee `retry-policy.ts`.\n */\nexport const MODEL_ERROR_CODES = Object.freeze({\n /** Credentials were rejected (401/403). */\n AUTH: 'AUTH',\n /** Transient request-rate limiting (429). */\n RATE_LIMIT: 'RATE_LIMIT',\n /** Provider-side fault (5xx). */\n SERVER: 'SERVER',\n /** The provider stopped producing output for longer than the idle bound. */\n TIMEOUT: 'TIMEOUT',\n /** The request never completed at the network layer. */\n TRANSPORT: 'TRANSPORT',\n /** The caller's signal aborted the request. */\n ABORTED: 'ABORTED',\n /** An adapter ignored cancellation and may still own live work. */\n TEARDOWN_TIMEOUT: 'MODEL_TEARDOWN_TIMEOUT',\n /** The provider rejected the request as malformed (400/413). */\n INVALID_REQUEST: 'INVALID_REQUEST',\n /** A well-formed response could not be parsed. */\n MALFORMED_RESPONSE: 'MALFORMED_RESPONSE',\n /** The response body ended before its terminating sentinel. */\n STREAM_CLOSED: 'STREAM_CLOSED',\n /** The request carried content the selected model cannot accept. */\n UNSUPPORTED_CONTENT: 'UNSUPPORTED_CONTENT',\n /** The request set an option this provider has no equivalent for. */\n UNSUPPORTED_OPTION: 'UNSUPPORTED_OPTION',\n /** Nothing classified it; treated as non-retryable. */\n UNKNOWN: 'UNKNOWN',\n} as const)\n\n/** Registry-level codes, raised before any provider I/O happens. */\nexport const REGISTRY_ERROR_CODES = Object.freeze({\n NO_ADAPTER: 'NO_ADAPTER',\n DUPLICATE_ADAPTER: 'DUPLICATE_ADAPTER',\n INVALID_ADAPTER: 'INVALID_ADAPTER',\n INVALID_CATALOG: 'INVALID_CATALOG',\n INVALID_MODEL_INFO: 'INVALID_MODEL_INFO',\n UNSUPPORTED_NATIVE_TOOL: 'UNSUPPORTED_NATIVE_TOOL',\n OUTPUT_TOKEN_LIMIT_EXCEEDED: 'OUTPUT_TOKEN_LIMIT_EXCEEDED',\n INVALID_PREPARED_CALL: 'INVALID_PREPARED_CALL',\n REGISTRATION_DISPOSED: 'REGISTRATION_DISPOSED',\n} as const)\n"],"mappings":"qDAkCA,IAAa,EAAb,cAAgC,CAAc,CAE5C,QAOA,YAAY,EAAiB,EAAc,EAA6B,CACtE,GAAI,OAAO,GAAY,UAAY,EAAQ,SAAW,EACpD,MAAU,MAAM,+CAA+C,EAEjE,GAAI,OAAO,GAAS,UAAY,EAAK,SAAW,EAC9C,MAAU,MAAM,4CAA4C,EAE9D,GAAI,GAAS,SAAW,IAAA,KAClB,CAAC,OAAO,UAAU,EAAQ,MAAM,GAAK,EAAQ,OAAS,KAAO,EAAQ,OAAS,KAClF,MAAU,MAAM,2DAA2D,EAE7E,GAAI,GAAS,uBAAyB,IAAA,KAChC,CAAC,OAAO,SAAS,EAAQ,oBAAoB,GAAK,EAAQ,sBAAwB,GACtF,MAAU,MAAM,kEAAkE,EAEpF,GAAI,GAAS,YAAc,IAAA,KACrB,OAAO,EAAQ,WAAc,UAAY,EAAQ,UAAU,SAAW,GAC1E,MAAU,MAAM,iDAAiD,EAEnE,MAAM,EAAS,EAAM,CAAO,EAC5B,KAAK,KAAO,aACZ,KAAK,QAAU,OAAO,OAAO,CAC3B,UACA,OACA,GAAG,GAAS,SAAW,IAAA,GAAY,CAAC,EAAI,CAAE,OAAQ,EAAQ,MAAO,EACjE,GAAG,GAAS,uBAAyB,IAAA,GACjC,CAAC,EACD,CAAE,qBAAsB,EAAQ,oBAAqB,EACzD,GAAG,GAAS,YAAc,IAAA,GAAY,CAAC,EAAI,CAAE,UAAW,EAAQ,SAAU,CAC5E,CAAC,CACH,CACF,EAUA,MAAa,EAAoB,OAAO,OAAO,CAE7C,KAAM,OAEN,WAAY,aAEZ,OAAQ,SAER,QAAS,UAET,UAAW,YAEX,QAAS,UAET,iBAAkB,yBAElB,gBAAiB,kBAEjB,mBAAoB,qBAEpB,cAAe,gBAEf,oBAAqB,sBAErB,mBAAoB,qBAEpB,QAAS,SACX,CAAU,EAGG,EAAuB,OAAO,OAAO,CAChD,WAAY,aACZ,kBAAmB,oBACnB,gBAAiB,kBACjB,gBAAiB,kBACjB,mBAAoB,qBACpB,wBAAyB,0BACzB,4BAA6B,8BAC7B,sBAAuB,wBACvB,sBAAuB,uBACzB,CAAU"}
|
package/dist/index.d.ts
CHANGED
|
@@ -13,9 +13,9 @@ import { EndProviderAttemptInput, ModelCallHandle, ModelCallObservationError, Mo
|
|
|
13
13
|
import { A2AMessageSource, AgentMessageSource, AssistantMessage, AssistantProvenance, Message, MessageSource, MessageSourceMap, ModelMessageSource, ToolMessageSource, ToolResultMessage, ToolResultMessageInput, UserMessage, createAssistantMessage, createMessage, createTextMessage, createToolResultMessage, createUserMessage, freezeMessage } from "./message/message.js";
|
|
14
14
|
import { ModelToolSchema, NativeImageGenerationTool, NativeToolName, NativeToolSchema, NativeToolSchemaMap, NativeWebSearchTool, ToolChoice, ToolSchema, WebSearchLocation, isNativeToolSchema } from "./contract/tool.js";
|
|
15
15
|
import { JsonSchemaOutputFormat, ModelOutputFormat, TextOutputFormat } from "./contract/output-format.js";
|
|
16
|
-
import { GenerateOptions } from "./contract/generate-options.js";
|
|
17
16
|
import { SupportSafeError } from "./support-safe/error.js";
|
|
18
|
-
import { ModelCatalogOptions, ModelCatalogSnapshot, ModelCatalogState, ModelContext, ModelInfo, ModelModality, ModelModalityMap, ModelReasoningInfo, ProviderInfo, ReasoningEffortInfo, ResolvedModelInfo } from "./contract/model-info.js";
|
|
17
|
+
import { ModelCatalogOptions, ModelCatalogSnapshot, ModelCatalogState, ModelContext, ModelInfo, ModelModality, ModelModalityMap, ModelReasoningInfo, ProviderInfo, ReasoningEffortInfo, ResolvedModelInfo, RuntimeDefaults } from "./contract/model-info.js";
|
|
18
|
+
import { GenerateOptions } from "./contract/generate-options.js";
|
|
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";
|
|
@@ -48,6 +48,7 @@ import { AgentInput } from "./agent/define/session/types.js";
|
|
|
48
48
|
import { MemoryBinding, MemoryCommitInput, MemoryCommitResult, MemoryLoadResult, MemoryScope, MemoryStore, MemoryStoreDefinition, MemoryStoreOptions } from "./agent/memory/persistence-types.js";
|
|
49
49
|
import { estimateContextTokens, estimateMessageTokens } from "./agent/memory/token-estimator.js";
|
|
50
50
|
import { selectCompactablePrefix } from "./agent/memory/surface-compaction.js";
|
|
51
|
+
import { ContextMilestone, ContextOptimizationMetrics, ContextOptimizerOptions, createContextOptimizer } from "./agent/memory/context-optimizer.js";
|
|
51
52
|
import { RuntimeSchema, defineToolFromSchema } from "./agent/tool/schema.js";
|
|
52
53
|
import { ToolExecutionBackend, ToolExecutionCapabilities, ToolExecutionRequest, ToolExecutionStore, ToolOperation, ToolOperationClaim, createToolExecutionInterceptor, localToolExecutionBackend } from "./agent/tool/execution.js";
|
|
53
54
|
import { RuntimeProviderInfo } from "./composition/provider/types.js";
|
|
@@ -70,4 +71,4 @@ import { defineMemoryStore } from "./composition/memory/definition.js";
|
|
|
70
71
|
import { defineSkillProviderPlugin } from "./agent/skill/provider/definition.js";
|
|
71
72
|
import { defineObservationExporter } from "./composition/exporter/definition.js";
|
|
72
73
|
import { CONTEXT_SECTION_ID_PATTERN, CONTEXT_SECTION_INVALID, MAX_CONTEXT_SECTION_TEXT_BYTES, defineContextSection } from "./agent/context/section.js";
|
|
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 };
|
|
74
|
+
export { type A2AMessageSource, APP_IDENTITY, type ActivatedSkillSnapshot, type AdapterRegistrationHandle, type AgentCompactionConfig, type AgentCompactionOptions, type AgentDefinition, type AgentDefinitionInput, type AgentDefinitionOverrides, type AgentInput, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, type AgentMessageSource, type AgentRuntime, type AgentRuntimeOptions, AgentSdkError, type AgentSkillOptions, type AgentTeamMemberInput, type AlwaysRetryPolicyConfig, type ApiKeyCheck, type ApiKeyRejection, type AppIdentity, type ApprovalBroker, type ApprovalDecision, type ApprovalRequest, type ApprovalStateStore, type AssistantMessage, type AssistantProvenance, type AssistantTextPhase, type AttemptUsageReport, type BackoffConfig, BlockAssembler, type Branded, COMPACTION_INSTRUCTION, CONTEXT_SECTION_ID_PATTERN, CONTEXT_SECTION_INVALID, CONTEXT_WINDOW_EXCEEDED_CODE, type CallConfig, type CallConfigAdapterDefaults, type CapabilityIdentityConflict, type CaptureReceipt, type CloneAgentOverrides, type CompactionResult, type ContentBlock, type ContentBlockMap, type ContentBlockType, ContextCompactor, type ContextCompactorOptions, type ContextMilestone, type ContextOptimizationMetrics, type ContextOptimizerOptions, type ContextSection, type ContextSectionResolveInput, type ContextSectionScope, type ContextSectionState, type ContextToolTouch, type CorrelationContext, type DefinedAgent, type DeliveryMode, type DiagnosticSnapshot, type DispatchState, type DocumentBlock, type DocumentMediaType, type DocumentSource, EMPTY_RESPONSE_CODE, type EmbeddingManyResult, type EmbeddingModelHandle, type EmbeddingModelOptions, type EmbeddingResult, type EmbeddingUsageReport, type EndProviderAttemptInput, type FinishReason, type FinishReasonMap, type GenerateOptions, INVALID_CREDENTIAL_CODE, type ImageBlock, type ImageDetail, type ImageMediaType, type ImageSource, type InteractiveApprovalBroker, type InteractiveApprovalBrokerOptions, type InteractiveUserInputBroker, type InteractiveUserInputBrokerOptions, type JsonObject, type JsonSchemaOutputFormat, type JsonValue, type LogLevel, MAX_CONTEXT_SECTION_TEXT_BYTES, MAX_SKILL_DESCRIPTION_CHARS, MAX_SKILL_ID_CHARS, MAX_SKILL_INSTRUCTIONS_CHARS, MAX_SKILL_NAME_CHARS, MAX_SKILL_RESOURCE_CHARS, MAX_SKILL_RESOURCE_PATH_CHARS, MAX_TIMER_DELAY_MS, MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION, MISSING_CREDENTIAL_CODE, MODEL_ERROR_CODES, type MemoryBinding, type MemoryCommitInput, type MemoryCommitResult, type MemoryLoadResult, type MemoryScope, type MemoryStore, type MemoryStoreDefinition, type MemoryStoreOptions, type Message, MessageId, type MessageSource, type MessageSourceMap, ModelAdapter, type ModelCallHandle, ModelCallObservationError, type ModelCallReport, type ModelCatalogOptions, type ModelCatalogSnapshot, type ModelCatalogState, type ModelContext, ModelError, type ModelErrorOptions, type ModelFailure, type ModelInfo, type ModelInvocationContext, type ModelMessageSource, type ModelModality, type ModelModalityMap, type ModelOutputFormat, type ModelProviderPlugin, type ModelProviderRegistrar, type ModelReasoningInfo, ModelRegistry, type ModelRegistryOptions, type ModelToolSchema, NOOP_OBSERVATION_PORT, type NativeImageGenerationTool, type NativeToolCallBlock, type NativeToolName, type NativeToolSchema, type NativeToolSchemaMap, type NativeWebSearchTool, type NormalRetryPolicyConfig, OBSERVATION_ERROR_CODES, OBSERVATION_EXPORTER_API_VERSION, type ObservationBoundary, type ObservationDeliveryAck, type ObservationDeliveryBatch, type ObservationDeliverySummary, type ObservationEvent, type ObservationEventName, type ObservationExportItem, type ObservationExporterPlugin, type ObservationExporterPluginDefinition, type ObservationPhase, type ObservationPort, type ObservationPriority, type ObservationResource, type ObservationResourceInput, type ObservationRunScope, type ObservationSpan, type ObservationSpanName, type OpenObservationSpanInput, type OperationStatus, PLUGIN_ERROR_CODES, PluginError, type PluginRegistrationHandle, type PreparedAdapterCall, type PreparedCall, type ProviderAttemptHandle, type ProviderInfo, ProviderRequestId, type ProviderRetryScheduledInput, QUOTA_EXCEEDED_CODE, REGISTRY_ERROR_CODES, type ReasoningBlock, ReasoningEffortId, type ReasoningEffortInfo, type ReplayEnvelope, type ResolvedAgentSkillOptions, type ResolvedAlwaysRetryPolicy, type ResolvedModelInfo, type ResolvedNormalRetryPolicy, type ResolvedRetryBackoff, type ResolvedRetryPolicy, type RetryAttempt, type RetryPolicyConfig, type RunReport, type RunTerminalRecord, type RuntimeAgent, type RuntimeAgentBindingInput, type RuntimeAgentDefinition, type RuntimeAgentDefinitionInput, type RuntimeAgentInvocationOptions, type RuntimeAgentLimits, type RuntimeAgentResponse, type RuntimeAgentRunEvent, type RuntimeAgentRunEventContext, type RuntimeAgentRunHandle, type RuntimeAgentSession, type RuntimeAgentSessionOptions, type RuntimeAgentSessionSnapshot, type RuntimeAgentTeam, type RuntimeAgentTeamEvent, type RuntimeAgentTeamOptions, type RuntimeCloseReport, type RuntimeDefaults, type RuntimeModelCatalogSnapshot, type RuntimeObservationExporterRegistration, type RuntimeObservationResourceInput, type RuntimeOwnerObservabilityOptions, type RuntimeProviderInfo, type RuntimeSchema, type RuntimeSkillCandidate, type RuntimeSkillLookupOptions, type RuntimeSkillSource, SDK_VERSION, SKILL_ERROR_CODES, SKILL_ID_PATTERN, SKILL_PROVIDER_API_VERSION, SKILL_TOOL_NAMES, type SafeErrorRecord, type SdkLogger, type SkillCandidate, SkillCatalog, type SkillCatalogOptions, type SkillCatalogSnapshot, type SkillDefinition, type SkillDefinitionInput, type SkillInvocationPolicy, type SkillLookupOptions, type SkillProvider, type SkillProviderDefinition, type SkillProviderListOptions, type SkillProviderPlugin, type SkillProviderPluginDefinition, type SkillReference, type SkillResourceBase, type SkillResourceSummary, type SkillSource, type SkillSummary, type SpanId, type StartProviderAttemptInput, type StreamChunk, type StreamMiddleware, type SupportSafeError, type TextAnnotation, type TextAnnotationMap, type TextBlock, type TextOutputFormat, type TokenUsage, type ToolCallBlock, ToolCallId, type ToolChoice, type ToolDefinition, type ToolExecutionBackend, type ToolExecutionCapabilities, type ToolExecutionRequest, type ToolExecutionStore, type ToolMessageSource, type ToolOperation, type ToolOperationClaim, type ToolResultBlock, type ToolResultMessage, type ToolResultMessageInput, type ToolRunContext, type ToolSchema, type TraceId, type UrlCitationAnnotation, type UsageAdditionResult, type UsageCounters, type UsageCoverage, type UsageValidationResult, type UserInputAnswer, type UserInputBroker, type UserInputDecision, type UserInputOption, type UserInputQuestion, type UserInputRequest, type UserInputResponse, type UserMessage, type WebSearchLocation, type WithRetryOptions, addUsageCounters, assertNever, assertUsableApiKey, attributionHeaders, backoffDelayMs, callConfigEquals, classifyUsageCoverage, cloneAgent, contentHasDocument, contentHasImage, createAgentRuntime, createApprovalBroker, createApprovalRequest, createAssistantMessage, createContextOptimizer, createCoreSpan, createMessage, createObservationRunScope, createOperationId, createSkillTools, createSpanId, createTextMessage, createToolExecutionInterceptor, createToolResultMessage, createTraceId, createUserInputBroker, createUserMessage, deepFreeze, defineAgent, defineContextSection, defineMemoryStore, defineObservationExporter, defineSkill, defineSkillProvider, defineSkillProviderPlugin, defineTool, defineToolFromSchema, detachedFrozen, disabledDeliverySummary, errorChain, estimateContextTokens, estimateMessageTokens, fixedApprovalBroker, fixedUserInputBroker, freezeCorrelation, freezeMessage, hasUsageCounters, isAgentSdkError, isContextWindowExceededError, isJsonValue, isNativeToolSchema, isQuotaExceededError, isRetryable, isSpanId, isTraceId, localToolExecutionBackend, normalizeApiKey, normalizeModelFailure, possiblyBilledAttemptsWithoutUsage, projectDocumentsForTextModel, projectImagesForTextModel, renderSkillCatalog, resolveCompactionConfig, resolveMemoryConfig, resolveRetryPolicy, resolveSkillOptions, safeErrorRecord, selectCompactablePrefix, snapshotObservationSpan, textOnlyDocumentText, textOnlyImageText, traceparent, userAgent, validObservationSpan, validateCandidate, validateCaptureReceipt, validateSkillId, validateSkillResourcePath, validateSkillSource, validateUsageCounters, waitForSettlement, withApprovalPersistence, withIdleTimeout, withRetry };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{MessageId as e,ProviderRequestId as t,ReasoningEffortId as n,ToolCallId as r}from"./primitives/brand.js";import{deepFreeze as i}from"./primitives/freeze.js";import{isJsonValue as a}from"./primitives/json.js";import{assertNever as o}from"./primitives/never.js";import{detachedFrozen as s}from"./primitives/snapshot.js";import{SDK_VERSION as c}from"./primitives/version.js";import{waitForSettlement as l}from"./async/settlement.js";import{createObservationRunScope as u,createOperationId as d,createSpanId as f,createTraceId as p,freezeCorrelation as m,isSpanId as h,isTraceId as g,traceparent as _}from"./observation/context.js";import{safeErrorRecord as v}from"./observation/event.js";import{NOOP_OBSERVATION_PORT as y,createCoreSpan as b,disabledDeliverySummary as x,snapshotObservationSpan as S,validObservationSpan as C,validateCaptureReceipt as w}from"./observation/port.js";import{AgentSdkError as T,CONTEXT_WINDOW_EXCEEDED_CODE as E,EMPTY_RESPONSE_CODE as D,INVALID_CREDENTIAL_CODE as O,MISSING_CREDENTIAL_CODE as k,QUOTA_EXCEEDED_CODE as A,errorChain as j,isAgentSdkError as M,isContextWindowExceededError as N,isQuotaExceededError as P}from"./errors/agent-sdk-error.js";import{ModelCallObservationError as F,OBSERVATION_ERROR_CODES as I}from"./observation/report.js";import{addUsageCounters as L,classifyUsageCoverage as R,hasUsageCounters as z,possiblyBilledAttemptsWithoutUsage as B,validateUsageCounters as V}from"./observation/usage.js";import{PLUGIN_ERROR_CODES as H,PluginError as U}from"./plugin/provider-plugin.js";import{MODEL_ERROR_CODES as W,ModelError as G,REGISTRY_ERROR_CODES as K}from"./errors/model-error.js";import{normalizeModelFailure as q}from"./errors/failure.js";import{createAssistantMessage as J,createMessage as Y,createTextMessage as X,createToolResultMessage as Z,createUserMessage as Q,freezeMessage as $}from"./message/message.js";import{contentHasDocument as ee,contentHasImage as te,projectDocumentsForTextModel as ne,projectImagesForTextModel as re,textOnlyDocumentText as ie,textOnlyImageText as ae}from"./message/projection.js";import{BlockAssembler as oe}from"./stream/assembler.js";import{withIdleTimeout as se}from"./stream/idle-timeout.js";import{ModelAdapter as ce}from"./contract/adapter.js";import{callConfigEquals as le}from"./contract/call-config.js";import{MAX_TIMER_DELAY_MS as ue,backoffDelayMs as de,isRetryable as fe,resolveRetryPolicy as pe}from"./contract/retry-policy.js";import{isNativeToolSchema as me}from"./contract/tool.js";import{ModelRegistry as he}from"./runtime/registry.js";import{withRetry as ge}from"./runtime/with-retry.js";import{assertUsableApiKey as _e,normalizeApiKey as ve}from"./http/api-key.js";import{APP_IDENTITY as ye,attributionHeaders as be,userAgent as xe}from"./http/attribution.js";import{AgentMemory as Se,resolveMemoryConfig as Ce}from"./agent/memory/memory.js";import{estimateContextTokens as we,estimateMessageTokens as Te}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as Ee}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as De,ContextCompactor as Oe}from"./agent/memory/compaction.js";import{resolveCompactionConfig as ke}from"./agent/memory/compaction-config.js";import{MEMORY_ERROR_CODES as
|
|
1
|
+
import{MessageId as e,ProviderRequestId as t,ReasoningEffortId as n,ToolCallId as r}from"./primitives/brand.js";import{deepFreeze as i}from"./primitives/freeze.js";import{isJsonValue as a}from"./primitives/json.js";import{assertNever as o}from"./primitives/never.js";import{detachedFrozen as s}from"./primitives/snapshot.js";import{SDK_VERSION as c}from"./primitives/version.js";import{waitForSettlement as l}from"./async/settlement.js";import{createObservationRunScope as u,createOperationId as d,createSpanId as f,createTraceId as p,freezeCorrelation as m,isSpanId as h,isTraceId as g,traceparent as _}from"./observation/context.js";import{safeErrorRecord as v}from"./observation/event.js";import{NOOP_OBSERVATION_PORT as y,createCoreSpan as b,disabledDeliverySummary as x,snapshotObservationSpan as S,validObservationSpan as C,validateCaptureReceipt as w}from"./observation/port.js";import{AgentSdkError as T,CONTEXT_WINDOW_EXCEEDED_CODE as E,EMPTY_RESPONSE_CODE as D,INVALID_CREDENTIAL_CODE as O,MISSING_CREDENTIAL_CODE as k,QUOTA_EXCEEDED_CODE as A,errorChain as j,isAgentSdkError as M,isContextWindowExceededError as N,isQuotaExceededError as P}from"./errors/agent-sdk-error.js";import{ModelCallObservationError as F,OBSERVATION_ERROR_CODES as I}from"./observation/report.js";import{addUsageCounters as L,classifyUsageCoverage as R,hasUsageCounters as z,possiblyBilledAttemptsWithoutUsage as B,validateUsageCounters as V}from"./observation/usage.js";import{PLUGIN_ERROR_CODES as H,PluginError as U}from"./plugin/provider-plugin.js";import{MODEL_ERROR_CODES as W,ModelError as G,REGISTRY_ERROR_CODES as K}from"./errors/model-error.js";import{normalizeModelFailure as q}from"./errors/failure.js";import{createAssistantMessage as J,createMessage as Y,createTextMessage as X,createToolResultMessage as Z,createUserMessage as Q,freezeMessage as $}from"./message/message.js";import{contentHasDocument as ee,contentHasImage as te,projectDocumentsForTextModel as ne,projectImagesForTextModel as re,textOnlyDocumentText as ie,textOnlyImageText as ae}from"./message/projection.js";import{BlockAssembler as oe}from"./stream/assembler.js";import{withIdleTimeout as se}from"./stream/idle-timeout.js";import{ModelAdapter as ce}from"./contract/adapter.js";import{callConfigEquals as le}from"./contract/call-config.js";import{MAX_TIMER_DELAY_MS as ue,backoffDelayMs as de,isRetryable as fe,resolveRetryPolicy as pe}from"./contract/retry-policy.js";import{isNativeToolSchema as me}from"./contract/tool.js";import{ModelRegistry as he}from"./runtime/registry.js";import{withRetry as ge}from"./runtime/with-retry.js";import{assertUsableApiKey as _e,normalizeApiKey as ve}from"./http/api-key.js";import{APP_IDENTITY as ye,attributionHeaders as be,userAgent as xe}from"./http/attribution.js";import{AgentMemory as Se,resolveMemoryConfig as Ce}from"./agent/memory/memory.js";import{estimateContextTokens as we,estimateMessageTokens as Te}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as Ee}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as De,ContextCompactor as Oe}from"./agent/memory/compaction.js";import{resolveCompactionConfig as ke}from"./agent/memory/compaction-config.js";import{defineTool as Ae}from"./agent/tool/definition.js";import{createContextOptimizer as je}from"./agent/memory/context-optimizer.js";import{MEMORY_ERROR_CODES as Me,MEMORY_STORE_API_VERSION as Ne}from"./composition/memory/config.js";import{defineMemoryStore as Pe}from"./composition/memory/definition.js";import{MAX_SKILL_DESCRIPTION_CHARS as Fe,MAX_SKILL_ID_CHARS as Ie,MAX_SKILL_INSTRUCTIONS_CHARS as Le,MAX_SKILL_NAME_CHARS as Re,MAX_SKILL_RESOURCE_CHARS as ze,MAX_SKILL_RESOURCE_PATH_CHARS as Be,SKILL_ID_PATTERN as Ve,defineSkill as He,defineSkillProvider as Ue,validateCandidate as We,validateSkillId as Ge,validateSkillResourcePath as Ke,validateSkillSource as qe}from"./agent/skill/definition.js";import{SKILL_ERROR_CODES as Je,SKILL_PROVIDER_API_VERSION as Ye}from"./agent/skill/provider/config.js";import{defineSkillProviderPlugin as Xe}from"./agent/skill/provider/definition.js";import{SkillCatalog as Ze}from"./agent/skill/catalog.js";import{SKILL_TOOL_NAMES as Qe,createSkillTools as $e,renderSkillCatalog as et,resolveSkillOptions as tt}from"./agent/skill/tools.js";import{OBSERVATION_EXPORTER_API_VERSION as nt}from"./composition/exporter/types.js";import{CONTEXT_SECTION_ID_PATTERN as rt,CONTEXT_SECTION_INVALID as it,MAX_CONTEXT_SECTION_TEXT_BYTES as at,defineContextSection as ot}from"./agent/context/section.js";import{createApprovalBroker as st,createApprovalRequest as ct,fixedApprovalBroker as lt,withApprovalPersistence as ut}from"./agent/tool/approval.js";import{createAgentRuntime as dt}from"./composition/runtime/public.js";import{cloneAgent as ft,defineAgent as pt}from"./composition/agent/author.js";import{defineObservationExporter as mt}from"./composition/exporter/definition.js";import{createUserInputBroker as ht,fixedUserInputBroker as gt}from"./agent/mode/user-input.js";import{defineToolFromSchema as _t}from"./agent/tool/schema.js";import{createToolExecutionInterceptor as vt,localToolExecutionBackend as yt}from"./agent/tool/execution.js";export{ye as APP_IDENTITY,Se as AgentMemory,T as AgentSdkError,oe as BlockAssembler,De as COMPACTION_INSTRUCTION,rt as CONTEXT_SECTION_ID_PATTERN,it as CONTEXT_SECTION_INVALID,E as CONTEXT_WINDOW_EXCEEDED_CODE,Oe as ContextCompactor,D as EMPTY_RESPONSE_CODE,O as INVALID_CREDENTIAL_CODE,at as MAX_CONTEXT_SECTION_TEXT_BYTES,Fe as MAX_SKILL_DESCRIPTION_CHARS,Ie as MAX_SKILL_ID_CHARS,Le as MAX_SKILL_INSTRUCTIONS_CHARS,Re as MAX_SKILL_NAME_CHARS,ze as MAX_SKILL_RESOURCE_CHARS,Be as MAX_SKILL_RESOURCE_PATH_CHARS,ue as MAX_TIMER_DELAY_MS,Me as MEMORY_ERROR_CODES,Ne as MEMORY_STORE_API_VERSION,k as MISSING_CREDENTIAL_CODE,W as MODEL_ERROR_CODES,e as MessageId,ce as ModelAdapter,F as ModelCallObservationError,G as ModelError,he as ModelRegistry,y as NOOP_OBSERVATION_PORT,I as OBSERVATION_ERROR_CODES,nt as OBSERVATION_EXPORTER_API_VERSION,H as PLUGIN_ERROR_CODES,U as PluginError,t as ProviderRequestId,A as QUOTA_EXCEEDED_CODE,K as REGISTRY_ERROR_CODES,n as ReasoningEffortId,c as SDK_VERSION,Je as SKILL_ERROR_CODES,Ve as SKILL_ID_PATTERN,Ye as SKILL_PROVIDER_API_VERSION,Qe as SKILL_TOOL_NAMES,Ze as SkillCatalog,r as ToolCallId,L as addUsageCounters,o as assertNever,_e as assertUsableApiKey,be as attributionHeaders,de as backoffDelayMs,le as callConfigEquals,R as classifyUsageCoverage,ft as cloneAgent,ee as contentHasDocument,te as contentHasImage,dt as createAgentRuntime,st as createApprovalBroker,ct as createApprovalRequest,J as createAssistantMessage,je as createContextOptimizer,b as createCoreSpan,Y as createMessage,u as createObservationRunScope,d as createOperationId,$e as createSkillTools,f as createSpanId,X as createTextMessage,vt as createToolExecutionInterceptor,Z as createToolResultMessage,p as createTraceId,ht as createUserInputBroker,Q as createUserMessage,i as deepFreeze,pt as defineAgent,ot as defineContextSection,Pe as defineMemoryStore,mt as defineObservationExporter,He as defineSkill,Ue as defineSkillProvider,Xe as defineSkillProviderPlugin,Ae as defineTool,_t as defineToolFromSchema,s as detachedFrozen,x as disabledDeliverySummary,j as errorChain,we as estimateContextTokens,Te as estimateMessageTokens,lt as fixedApprovalBroker,gt as fixedUserInputBroker,m as freezeCorrelation,$ as freezeMessage,z as hasUsageCounters,M as isAgentSdkError,N as isContextWindowExceededError,a as isJsonValue,me as isNativeToolSchema,P as isQuotaExceededError,fe as isRetryable,h as isSpanId,g as isTraceId,yt as localToolExecutionBackend,ve as normalizeApiKey,q as normalizeModelFailure,B as possiblyBilledAttemptsWithoutUsage,ne as projectDocumentsForTextModel,re as projectImagesForTextModel,et as renderSkillCatalog,ke as resolveCompactionConfig,Ce as resolveMemoryConfig,pe as resolveRetryPolicy,tt as resolveSkillOptions,v as safeErrorRecord,Ee as selectCompactablePrefix,S as snapshotObservationSpan,ie as textOnlyDocumentText,ae as textOnlyImageText,_ as traceparent,xe as userAgent,C as validObservationSpan,We as validateCandidate,w as validateCaptureReceipt,Ge as validateSkillId,Ke as validateSkillResourcePath,qe as validateSkillSource,V as validateUsageCounters,l as waitForSettlement,ut as withApprovalPersistence,se as withIdleTimeout,ge as withRetry};
|
package/dist/memory.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { AgentMemory, AgentMemoryConfig, AgentMemoryConfigInput, AgentMemoryItem
|
|
|
5
5
|
import { MemoryBinding, MemoryCommitInput, MemoryCommitResult, MemoryLoadResult, MemoryScope, MemoryStore, MemoryStoreDefinition, MemoryStoreOptions } from "./agent/memory/persistence-types.js";
|
|
6
6
|
import { estimateContextTokens, estimateMessageTokens } from "./agent/memory/token-estimator.js";
|
|
7
7
|
import { selectCompactablePrefix } from "./agent/memory/surface-compaction.js";
|
|
8
|
+
import { ContextMilestone, ContextOptimizationMetrics, ContextOptimizerOptions, createContextOptimizer } from "./agent/memory/context-optimizer.js";
|
|
8
9
|
import { MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION } from "./composition/memory/config.js";
|
|
9
10
|
import { defineMemoryStore } from "./composition/memory/definition.js";
|
|
10
|
-
export { type AgentCompactionConfig, type AgentCompactionOptions, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, COMPACTION_INSTRUCTION, type CompactionResult, ContextCompactor, type ContextCompactorOptions, MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION, type MemoryBinding, type MemoryCommitInput, type MemoryCommitResult, type MemoryLoadResult, type MemoryScope, type MemoryStore, type MemoryStoreDefinition, type MemoryStoreOptions, type SdkLogger, defineMemoryStore, estimateContextTokens, estimateMessageTokens, resolveCompactionConfig, resolveMemoryConfig, selectCompactablePrefix };
|
|
11
|
+
export { type AgentCompactionConfig, type AgentCompactionOptions, AgentMemory, type AgentMemoryConfig, type AgentMemoryConfigInput, type AgentMemoryItem, type AgentMemoryKind, type AgentMemorySeed, type AgentMemorySnapshot, COMPACTION_INSTRUCTION, type CompactionResult, ContextCompactor, type ContextCompactorOptions, type ContextMilestone, type ContextOptimizationMetrics, type ContextOptimizerOptions, MEMORY_ERROR_CODES, MEMORY_STORE_API_VERSION, type MemoryBinding, type MemoryCommitInput, type MemoryCommitResult, type MemoryLoadResult, type MemoryScope, type MemoryStore, type MemoryStoreDefinition, type MemoryStoreOptions, type SdkLogger, createContextOptimizer, defineMemoryStore, estimateContextTokens, estimateMessageTokens, resolveCompactionConfig, resolveMemoryConfig, selectCompactablePrefix };
|
package/dist/memory.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AgentMemory as e,resolveMemoryConfig as t}from"./agent/memory/memory.js";import{estimateContextTokens as n,estimateMessageTokens as r}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as i}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as a,ContextCompactor as o}from"./agent/memory/compaction.js";import{resolveCompactionConfig as s}from"./agent/memory/compaction-config.js";import{MEMORY_ERROR_CODES as
|
|
1
|
+
import{AgentMemory as e,resolveMemoryConfig as t}from"./agent/memory/memory.js";import{estimateContextTokens as n,estimateMessageTokens as r}from"./agent/memory/token-estimator.js";import{selectCompactablePrefix as i}from"./agent/memory/surface-compaction.js";import{COMPACTION_INSTRUCTION as a,ContextCompactor as o}from"./agent/memory/compaction.js";import{resolveCompactionConfig as s}from"./agent/memory/compaction-config.js";import{createContextOptimizer as c}from"./agent/memory/context-optimizer.js";import{MEMORY_ERROR_CODES as l,MEMORY_STORE_API_VERSION as u}from"./composition/memory/config.js";import{defineMemoryStore as d}from"./composition/memory/definition.js";export{e as AgentMemory,a as COMPACTION_INSTRUCTION,o as ContextCompactor,l as MEMORY_ERROR_CODES,u as MEMORY_STORE_API_VERSION,c as createContextOptimizer,d as defineMemoryStore,n as estimateContextTokens,r as estimateMessageTokens,s as resolveCompactionConfig,t as resolveMemoryConfig,i as selectCompactablePrefix};
|
|
@@ -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.3`,...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.5`,...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
|
|
@@ -75,6 +75,17 @@ interface ModelInvocationContext {
|
|
|
75
75
|
readonly observation?: ObservationPort;
|
|
76
76
|
/** Safe SDK/service/runtime identity copied onto nested provider operations. */
|
|
77
77
|
readonly resource?: ObservationResource;
|
|
78
|
+
/** Stable code-owned agent identity (`AgentDefinition.id`), when this call belongs to one. */
|
|
79
|
+
readonly agentId?: string;
|
|
80
|
+
/**
|
|
81
|
+
* Extra headers/body fields for this agent's provider requests
|
|
82
|
+
* (`AgentDefinitionInput.providerOptions`), when this call belongs to an
|
|
83
|
+
* agent that configured one.
|
|
84
|
+
*/
|
|
85
|
+
readonly providerOptions?: {
|
|
86
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
87
|
+
readonly body?: Readonly<Record<string, unknown>>;
|
|
88
|
+
};
|
|
78
89
|
readonly correlation?: Partial<CorrelationContext>;
|
|
79
90
|
readonly terminalCheckpointOwner?: 'model-call' | 'agent-run';
|
|
80
91
|
/** Shared sequence/monotonic scope when this call belongs to a larger agent run. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"report.d.ts","names":[],"sources":["../../src/observation/report.ts"],"mappings":";;;;;;;;UAQiB;WACN;WACA,SAAS;WACT;WACA,QAAQ;WACR;;WAEA;;WAEA;WACA;WACA,QAAQ;WACR;WACA;WACA;WACA;;WAEA,gBAAgB;WAChB,UAAU;WACV,UAAU;WACV,YAAY;WACZ,mBAAmB;WACnB;WACA;WACA,UAAU;WACV,QAAQ;;UAGF,wBAAwB,cAAc;WAC5C;WACA;WACA,QAAQ,QAAQ;;;UAIV;WACN;WACA;WACA;;WAEA;;;UAIM;WACN,QAAQ;WACR,eAAe;WACf,WAAW;;WAEX;WACA;WACA;;WAEA,QAAQ;;;UAIF;WACN;WACA;WACA;;;UAIM;WACN;WACA;WACA;EACT,IAAI,OAAO,0BAA0B;;UAGtB;WACN,cAAc;;WAEd,WAAW;
|
|
1
|
+
{"version":3,"file":"report.d.ts","names":[],"sources":["../../src/observation/report.ts"],"mappings":";;;;;;;;UAQiB;WACN;WACA,SAAS;WACT;WACA,QAAQ;WACR;;WAEA;;WAEA;WACA;WACA,QAAQ;WACR;WACA;WACA;WACA;;WAEA,gBAAgB;WAChB,UAAU;WACV,UAAU;WACV,YAAY;WACZ,mBAAmB;WACnB;WACA;WACA,UAAU;WACV,QAAQ;;UAGF,wBAAwB,cAAc;WAC5C;WACA;WACA,QAAQ,QAAQ;;;UAIV;WACN;WACA;WACA;;WAEA;;;UAIM;WACN,QAAQ;WACR,eAAe;WACf,WAAW;;WAEX;WACA;WACA;;WAEA,QAAQ;;;UAIF;WACN;WACA;WACA;;;UAIM;WACN;WACA;WACA;EACT,IAAI,OAAO,0BAA0B;;UAGtB;WACN,cAAc;;WAEd,WAAW;;WAEX;;;;;;WAMA;aACE,UAAU,SAAS;aACnB,OAAO,SAAS;;WAElB,cAAc,QAAQ;WACtB;;WAEA,QAAQ;;WAER,SAAS;;WAET;;;;;WAKA,wBACP,OAAO,2BACP,SAAS,gBACN,QAAQ;WACJ,uBAAuB,OAAO;;cAG5B,yBAAuB;WACf;WACD;WACA;WACH;WACA;WACE;WACL;WACG;WACa;WACA;WACL;WACR;WACC;WACD;WACS;;cAGb,kCAAkC;WACpC;WACA;WACA,SAAS;WACT,QAAQ;EAEjB,YAAY,iBAAiB,QAAQ,iBAAiB,UAAU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"report.js","names":[],"sources":["../../src/observation/report.ts"],"sourcesContent":["import type { StreamChunk } from '../stream/chunk.ts'\nimport { AgentSdkError } from '../errors/agent-sdk-error.ts'\nimport type { CorrelationContext, ObservationRunScope, SpanId, TraceId } from './context.ts'\nimport type { ObservationResource, OperationStatus, SafeErrorRecord } from './event.ts'\nimport type { ObservationDeliverySummary, ObservationPort } from './port.ts'\nimport type { AttemptUsageReport, DispatchState, UsageCounters, UsageCoverage } from './usage.ts'\nimport type { SdkLogger } from '../logging/types.ts'\n\nexport interface ModelCallReport {\n readonly runId: string\n readonly traceId: TraceId\n readonly modelCallId: string\n readonly spanId: SpanId\n readonly provider: string\n /** Provider family independently of the selected route, when installed as a plugin. */\n readonly providerFamily?: string\n /** Exact plugin installation that owned the selected route. */\n readonly providerPluginId?: string\n readonly model: string\n readonly status: OperationStatus\n readonly startedAt: string\n readonly endedAt: string\n readonly durationMs: number\n readonly finishReason?: string\n /** Logical dispatch state, retained even when an adapter did not expose physical attempts. */\n readonly dispatchState?: DispatchState\n readonly coverage: UsageCoverage\n readonly reported: UsageCounters\n readonly estimated?: UsageCounters\n readonly attempts: readonly AttemptUsageReport[]\n readonly possiblyBilledAttemptsWithoutUsage: number\n readonly authoritative: boolean\n readonly delivery: ObservationDeliverySummary\n readonly error?: SafeErrorRecord\n}\n\nexport interface ModelCallHandle extends AsyncIterable<StreamChunk> {\n readonly runId: string\n readonly modelCallId: string\n readonly report: Promise<ModelCallReport>\n}\n\n/** Safe facts known immediately before one physical provider dispatch. */\nexport interface StartProviderAttemptInput {\n readonly provider: string\n readonly model: string\n readonly method: string\n /** Scheme, host, and explicit non-default port only; never a path or query. */\n readonly origin: string\n}\n\n/** Terminal facts supplied by a transport after exactly one dispatch boundary. */\nexport interface EndProviderAttemptInput {\n readonly status: OperationStatus\n readonly dispatchState: DispatchState\n readonly reported?: UsageCounters\n /** False for a provisional snapshot, even when every counter is present. */\n readonly usageFinal?: boolean\n readonly httpStatus?: number\n readonly providerRequestId?: string\n /** Must already be safe for support reports; raw response bodies are forbidden. */\n readonly error?: SafeErrorRecord\n}\n\n/** Safe scheduling facts between two physical provider attempts. */\nexport interface ProviderRetryScheduledInput {\n readonly nextAttemptNumber: number\n readonly delayMs: number\n readonly failureCode: string\n}\n\n/** One physical provider-attempt lifecycle owned by the model-call handle. */\nexport interface ProviderAttemptHandle {\n readonly attemptId: string\n readonly attemptNumber: number\n readonly traceparent: string\n end(input: EndProviderAttemptInput): AttemptUsageReport\n}\n\nexport interface ModelInvocationContext {\n readonly observation?: ObservationPort\n /** Safe SDK/service/runtime identity copied onto nested provider operations. */\n readonly resource?: ObservationResource\n readonly correlation?: Partial<CorrelationContext>\n readonly terminalCheckpointOwner?: 'model-call' | 'agent-run'\n /** Shared sequence/monotonic scope when this call belongs to a larger agent run. */\n readonly scope?: ObservationRunScope\n /** Always present on AgentRuntime calls; optional for preserved low-level callers. */\n readonly logger?: SdkLogger\n /** Declares that the adapter will report the real network boundary itself. */\n readonly declareProviderAttemptAccounting?: () => void\n /**\n * Internal transport accounting boundary. HTTP providers call this immediately\n * before dispatch; audit mode may reject before any network request is invoked.\n */\n readonly startProviderAttempt?: (\n input: StartProviderAttemptInput,\n signal?: AbortSignal,\n ) => Promise<ProviderAttemptHandle>\n readonly recordProviderRetry?: (input: ProviderRetryScheduledInput) => void\n}\n\nexport const OBSERVATION_ERROR_CODES = Object.freeze({\n AUDIT_UNAVAILABLE: 'OBSERVABILITY_AUDIT_UNAVAILABLE',\n CAPTURE_REJECTED: 'OBSERVABILITY_CAPTURE_REJECTED',\n PROCESSOR_FAILED: 'OBSERVABILITY_PROCESSOR_FAILED',\n EXPORT_FAILED: 'OBSERVABILITY_EXPORT_FAILED',\n FLUSH_TIMEOUT: 'OBSERVABILITY_FLUSH_TIMEOUT',\n JOURNAL_CORRUPT: 'OBSERVABILITY_JOURNAL_CORRUPT',\n JOURNAL_IO: 'OBSERVABILITY_JOURNAL_IO',\n BROWSER_QUOTA: 'OBSERVABILITY_BROWSER_QUOTA',\n OTEL_PROVIDER_UNCONFIGURED: 'OTEL_PROVIDER_UNCONFIGURED',\n OPERATION_TERMINAL_MISSING: 'OPERATION_TERMINAL_MISSING',\n LEDGER_LIMIT_EXCEEDED: 'LEDGER_LIMIT_EXCEEDED',\n USAGE_MISSING: 'USAGE_MISSING',\n USAGE_REQUIRED: 'USAGE_REQUIRED',\n USAGE_INVALID: 'USAGE_INVALID',\n USAGE_COUNTER_OVERFLOW: 'USAGE_COUNTER_OVERFLOW',\n} as const)\n\nexport class ModelCallObservationError extends AgentSdkError {\n readonly runId: string\n readonly modelCallId: string\n readonly traceId: TraceId\n readonly report: ModelCallReport\n\n constructor(message: string, report: ModelCallReport, options?: ErrorOptions) {\n super(message, OBSERVATION_ERROR_CODES.AUDIT_UNAVAILABLE, options)\n this.name = 'ModelCallObservationError'\n this.runId = report.runId\n this.modelCallId = report.modelCallId\n this.traceId = report.traceId\n this.report = report\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"report.js","names":[],"sources":["../../src/observation/report.ts"],"sourcesContent":["import type { StreamChunk } from '../stream/chunk.ts'\nimport { AgentSdkError } from '../errors/agent-sdk-error.ts'\nimport type { CorrelationContext, ObservationRunScope, SpanId, TraceId } from './context.ts'\nimport type { ObservationResource, OperationStatus, SafeErrorRecord } from './event.ts'\nimport type { ObservationDeliverySummary, ObservationPort } from './port.ts'\nimport type { AttemptUsageReport, DispatchState, UsageCounters, UsageCoverage } from './usage.ts'\nimport type { SdkLogger } from '../logging/types.ts'\n\nexport interface ModelCallReport {\n readonly runId: string\n readonly traceId: TraceId\n readonly modelCallId: string\n readonly spanId: SpanId\n readonly provider: string\n /** Provider family independently of the selected route, when installed as a plugin. */\n readonly providerFamily?: string\n /** Exact plugin installation that owned the selected route. */\n readonly providerPluginId?: string\n readonly model: string\n readonly status: OperationStatus\n readonly startedAt: string\n readonly endedAt: string\n readonly durationMs: number\n readonly finishReason?: string\n /** Logical dispatch state, retained even when an adapter did not expose physical attempts. */\n readonly dispatchState?: DispatchState\n readonly coverage: UsageCoverage\n readonly reported: UsageCounters\n readonly estimated?: UsageCounters\n readonly attempts: readonly AttemptUsageReport[]\n readonly possiblyBilledAttemptsWithoutUsage: number\n readonly authoritative: boolean\n readonly delivery: ObservationDeliverySummary\n readonly error?: SafeErrorRecord\n}\n\nexport interface ModelCallHandle extends AsyncIterable<StreamChunk> {\n readonly runId: string\n readonly modelCallId: string\n readonly report: Promise<ModelCallReport>\n}\n\n/** Safe facts known immediately before one physical provider dispatch. */\nexport interface StartProviderAttemptInput {\n readonly provider: string\n readonly model: string\n readonly method: string\n /** Scheme, host, and explicit non-default port only; never a path or query. */\n readonly origin: string\n}\n\n/** Terminal facts supplied by a transport after exactly one dispatch boundary. */\nexport interface EndProviderAttemptInput {\n readonly status: OperationStatus\n readonly dispatchState: DispatchState\n readonly reported?: UsageCounters\n /** False for a provisional snapshot, even when every counter is present. */\n readonly usageFinal?: boolean\n readonly httpStatus?: number\n readonly providerRequestId?: string\n /** Must already be safe for support reports; raw response bodies are forbidden. */\n readonly error?: SafeErrorRecord\n}\n\n/** Safe scheduling facts between two physical provider attempts. */\nexport interface ProviderRetryScheduledInput {\n readonly nextAttemptNumber: number\n readonly delayMs: number\n readonly failureCode: string\n}\n\n/** One physical provider-attempt lifecycle owned by the model-call handle. */\nexport interface ProviderAttemptHandle {\n readonly attemptId: string\n readonly attemptNumber: number\n readonly traceparent: string\n end(input: EndProviderAttemptInput): AttemptUsageReport\n}\n\nexport interface ModelInvocationContext {\n readonly observation?: ObservationPort\n /** Safe SDK/service/runtime identity copied onto nested provider operations. */\n readonly resource?: ObservationResource\n /** Stable code-owned agent identity (`AgentDefinition.id`), when this call belongs to one. */\n readonly agentId?: string\n /**\n * Extra headers/body fields for this agent's provider requests\n * (`AgentDefinitionInput.providerOptions`), when this call belongs to an\n * agent that configured one.\n */\n readonly providerOptions?: {\n readonly headers?: Readonly<Record<string, string>>\n readonly body?: Readonly<Record<string, unknown>>\n }\n readonly correlation?: Partial<CorrelationContext>\n readonly terminalCheckpointOwner?: 'model-call' | 'agent-run'\n /** Shared sequence/monotonic scope when this call belongs to a larger agent run. */\n readonly scope?: ObservationRunScope\n /** Always present on AgentRuntime calls; optional for preserved low-level callers. */\n readonly logger?: SdkLogger\n /** Declares that the adapter will report the real network boundary itself. */\n readonly declareProviderAttemptAccounting?: () => void\n /**\n * Internal transport accounting boundary. HTTP providers call this immediately\n * before dispatch; audit mode may reject before any network request is invoked.\n */\n readonly startProviderAttempt?: (\n input: StartProviderAttemptInput,\n signal?: AbortSignal,\n ) => Promise<ProviderAttemptHandle>\n readonly recordProviderRetry?: (input: ProviderRetryScheduledInput) => void\n}\n\nexport const OBSERVATION_ERROR_CODES = Object.freeze({\n AUDIT_UNAVAILABLE: 'OBSERVABILITY_AUDIT_UNAVAILABLE',\n CAPTURE_REJECTED: 'OBSERVABILITY_CAPTURE_REJECTED',\n PROCESSOR_FAILED: 'OBSERVABILITY_PROCESSOR_FAILED',\n EXPORT_FAILED: 'OBSERVABILITY_EXPORT_FAILED',\n FLUSH_TIMEOUT: 'OBSERVABILITY_FLUSH_TIMEOUT',\n JOURNAL_CORRUPT: 'OBSERVABILITY_JOURNAL_CORRUPT',\n JOURNAL_IO: 'OBSERVABILITY_JOURNAL_IO',\n BROWSER_QUOTA: 'OBSERVABILITY_BROWSER_QUOTA',\n OTEL_PROVIDER_UNCONFIGURED: 'OTEL_PROVIDER_UNCONFIGURED',\n OPERATION_TERMINAL_MISSING: 'OPERATION_TERMINAL_MISSING',\n LEDGER_LIMIT_EXCEEDED: 'LEDGER_LIMIT_EXCEEDED',\n USAGE_MISSING: 'USAGE_MISSING',\n USAGE_REQUIRED: 'USAGE_REQUIRED',\n USAGE_INVALID: 'USAGE_INVALID',\n USAGE_COUNTER_OVERFLOW: 'USAGE_COUNTER_OVERFLOW',\n} as const)\n\nexport class ModelCallObservationError extends AgentSdkError {\n readonly runId: string\n readonly modelCallId: string\n readonly traceId: TraceId\n readonly report: ModelCallReport\n\n constructor(message: string, report: ModelCallReport, options?: ErrorOptions) {\n super(message, OBSERVATION_ERROR_CODES.AUDIT_UNAVAILABLE, options)\n this.name = 'ModelCallObservationError'\n this.runId = report.runId\n this.modelCallId = report.modelCallId\n this.traceId = report.traceId\n this.report = report\n }\n}\n"],"mappings":"6DAiHA,MAAa,EAA0B,OAAO,OAAO,CACnD,kBAAmB,kCACnB,iBAAkB,iCAClB,iBAAkB,iCAClB,cAAe,8BACf,cAAe,8BACf,gBAAiB,gCACjB,WAAY,2BACZ,cAAe,8BACf,2BAA4B,6BAC5B,2BAA4B,6BAC5B,sBAAuB,wBACvB,cAAe,gBACf,eAAgB,iBAChB,cAAe,gBACf,uBAAwB,wBAC1B,CAAU,EAEV,IAAa,EAAb,cAA+C,CAAc,CAC3D,MACA,YACA,QACA,OAEA,YAAY,EAAiB,EAAyB,EAAwB,CAC5E,MAAM,EAAS,EAAwB,kBAAmB,CAAO,EACjE,KAAK,KAAO,4BACZ,KAAK,MAAQ,EAAO,MACpB,KAAK,YAAc,EAAO,YAC1B,KAAK,QAAU,EAAO,QACtB,KAAK,OAAS,CAChB,CACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region src/primitives/version.d.ts
|
|
2
2
|
/** Package version injected as a Web-standard literal; release tooling updates this file. */
|
|
3
|
-
declare const SDK_VERSION = "0.1.
|
|
3
|
+
declare const SDK_VERSION = "0.1.5";
|
|
4
4
|
//#endregion
|
|
5
5
|
export { SDK_VERSION };
|
|
6
6
|
//# sourceMappingURL=version.d.ts.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=`0.1.
|
|
1
|
+
const e=`0.1.5`;export{e as SDK_VERSION};
|
|
2
2
|
//# sourceMappingURL=version.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","names":[],"sources":["../../src/primitives/version.ts"],"sourcesContent":["/** Package version injected as a Web-standard literal; release tooling updates this file. */\nexport const SDK_VERSION = '0.1.
|
|
1
|
+
{"version":3,"file":"version.js","names":[],"sources":["../../src/primitives/version.ts"],"sourcesContent":["/** Package version injected as a Web-standard literal; release tooling updates this file. */\nexport const SDK_VERSION = '0.1.5'\n"],"mappings":"AACA,MAAa,EAAc"}
|
package/dist/provider.d.ts
CHANGED
|
@@ -5,8 +5,8 @@ import { UsageCounters } from "./observation/usage.js";
|
|
|
5
5
|
import { SdkLogger } from "./logging/types.js";
|
|
6
6
|
import { EndProviderAttemptInput, ModelInvocationContext, ProviderAttemptHandle, StartProviderAttemptInput } from "./observation/report.js";
|
|
7
7
|
import { ModelToolSchema, NativeImageGenerationTool, NativeToolName, NativeToolSchema, NativeToolSchemaMap, NativeWebSearchTool, ToolChoice, WebSearchLocation } from "./contract/tool.js";
|
|
8
|
-
import { GenerateOptions } from "./contract/generate-options.js";
|
|
9
8
|
import { ModelInfo, ModelModality, ModelReasoningInfo, ProviderInfo, ResolvedModelInfo } from "./contract/model-info.js";
|
|
9
|
+
import { GenerateOptions } from "./contract/generate-options.js";
|
|
10
10
|
import { ResolvedRetryPolicy, RetryPolicyConfig } from "./contract/retry-policy.js";
|
|
11
11
|
import { ModelAdapter, PreparedAdapterCall } from "./contract/adapter.js";
|
|
12
12
|
import { AdapterRegistrationHandle, ModelProviderPlugin, ModelProviderRegistrar, StreamMiddleware } from "./plugin/provider-plugin.js";
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{deepFreeze as e}from"../primitives/freeze.js";import{createObservationRunScope as t,createOperationId as n,isSpanId as r,isTraceId as i}from"../observation/context.js";import{safeErrorRecord as a}from"../observation/event.js";import{NOOP_OBSERVATION_PORT as o,createCoreSpan as s,disabledDeliverySummary as c,snapshotObservationSpan as l,validateCaptureReceipt as u}from"../observation/port.js";import{AgentSdkError as d}from"../errors/agent-sdk-error.js";import{ModelCallObservationError as f,OBSERVATION_ERROR_CODES as p}from"../observation/report.js";import{addUsageCounters as m,classifyUsageCoverage as h,possiblyBilledAttemptsWithoutUsage as g,validateUsageCounters as _}from"../observation/usage.js";const v=new WeakMap;function y(){return globalThis.performance?.now()??Date.now()}function b(e,n,r){if(r!==void 0)return r;let i=v.get(e);i||(i=new Map,v.set(e,i));let a=i.get(n);return a||(a=t(),i.set(n,a)),a}function x(e,t){if(e.reason.kind!==`error`&&e.reason.kind!==`aborted`)return;let n=e.reason.failure;return Object.freeze({type:`ModelError`,message:e.reason.kind===`aborted`?`model call was aborted; inspect the stable code for classification`:`model call failed; inspect the stable code and provider request ID`,code:n.code,...t===void 0?{}:{retryable:t(n.code)},...n.status===void 0?{}:{status:n.status}})}function S(e){return e===`remote-acknowledged`?2:+(e===`local-durable`)}function C(e,t,n){n&&(t.status===`accepted`?e.accepted+=1:e.rejected+=1,t.status===`accepted`&&S(t.boundary)>S(e.reached)&&(e.reached=t.boundary))}function w(t,n,r){if(t===o)return c();let i=n===`operational`?`none`:S(r.reached)>0?r.reached:`local-durable`;return e({mode:n,requiredBoundary:i,reachedBoundary:r.reached,complete:r.rejected===0&&r.pending===0&&S(r.reached)>=S(i),acceptedCritical:r.accepted,rejectedCritical:r.rejected,pendingCritical:r.pending,...r.lastFailure===void 0?{}:{lastFailure:r.lastFailure}})}function T(e){if(!(!e||!i(e.traceId)||!r(e.spanId)||typeof e.runId!=`string`||e.runId.length===0))return{traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId===null||r(e.parentSpanId)?e.parentSpanId:null,runId:e.runId,...e.conversationId===void 0?{}:{conversationId:e.conversationId},...e.turnId===void 0?{}:{turnId:e.turnId},...e.modelCallId===void 0?{}:{modelCallId:e.modelCallId},...e.attemptId===void 0?{}:{attemptId:e.attemptId},...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},...e.providerRequestId===void 0?{}:{providerRequestId:e.providerRequestId},...e.sessionId===void 0?{}:{sessionId:e.sessionId}}}function E(e,t,n){try{let r=l(e.openSpan(t));if(r&&r.correlation.runId===t.runId&&r.correlation.modelCallId===t.correlation?.modelCallId){let e=!1;return Object.freeze({correlation:r.correlation,traceparent:r.traceparent,end(t,i,o){if(!e){e=!0;try{r.end(t,i,o)}catch(e){n.lastFailure=a(e)}}}})}n.lastFailure=Object.freeze({type:`ObservationSpanError`,message:`observation backend returned an invalid or mismatched span identity`,code:p.OTEL_PROVIDER_UNCONFIGURED})}catch(e){n.lastFailure=a(e)}return s(t)}function D(t){let r=t.context??{},i=t.context?.correlation,s=typeof i?.runId==`string`&&i.runId.length>0?i.runId:n(),c=typeof i?.modelCallId==`string`&&i.modelCallId.length>0?i.modelCallId:n(),l=b(r,s,t.context?.scope),v=new Date().toISOString(),S=y(),D=t.context?.observation??t.defaultObservation??o,O={accepted:0,rejected:0,pending:0,reached:`none`},k=`operational`;try{let e=D.mode;if(e!==`operational`&&e!==`reliable`&&e!==`audit`)throw TypeError(`observation delivery mode is invalid`);k=e}catch(e){O.lastFailure=a(e)}let A=T(i),j=E(D,{name:`sdk.model.call`,runId:s,...A===void 0?{}:{parent:A},correlation:{modelCallId:c,...i?.conversationId===void 0?{}:{conversationId:i.conversationId},...i?.turnId===void 0?{}:{turnId:i.turnId},...i?.sessionId===void 0?{}:{sessionId:i.sessionId}},startedAt:v,monotonicMs:l.monotonicMs()},O),M=(r,i)=>e({schemaVersion:1,eventId:n(),sequence:l.nextSequence(),name:`sdk.model.call`,phase:r,occurredAt:new Date().toISOString(),monotonicMs:l.monotonicMs(),priority:`critical`,resource:t.resource,correlation:j.correlation,data:i}),N=e=>{try{let t=u(D.capture(e),e.eventId);C(O,t,e.priority===`critical`)}catch(t){O.rejected+=+(e.priority===`critical`),O.lastFailure=a(t)}},P=[],F=new Set,I=1,L=!1;function R(r){N(e({schemaVersion:1,eventId:n(),sequence:l.nextSequence(),name:`sdk.provider.retry.scheduled`,phase:`point`,occurredAt:new Date().toISOString(),monotonicMs:l.monotonicMs(),priority:`critical`,resource:t.resource,correlation:j.correlation,data:{nextAttemptNumber:r.nextAttemptNumber,delayMs:r.delayMs,failureCode:r.failureCode}}))}async function z(r,i){let o=I++,f=n(),m=new Date().toISOString(),h=y(),g=E(D,{name:`sdk.provider.attempt`,runId:s,parent:j.correlation,correlation:{modelCallId:c,attemptId:f},startedAt:m,monotonicMs:l.monotonicMs()},O),v=e({schemaVersion:1,eventId:n(),sequence:l.nextSequence(),name:`sdk.provider.attempt`,phase:`start`,occurredAt:m,monotonicMs:l.monotonicMs(),priority:`critical`,resource:t.resource,correlation:g.correlation,data:{provider:r.provider,model:r.model,attemptNumber:o,method:r.method,origin:r.origin,dispatchState:`not-sent`}});if(k===`audit`){O.pending+=1;try{let e=D.checkpoint?await D.checkpoint(v,i):Object.freeze({eventId:v.eventId,status:`rejected`,durable:!1,boundary:`none`,reason:`exporter-unavailable`}),t=u(e,v.eventId);if(--O.pending,C(O,t,!0),t.status!==`accepted`||!t.durable)throw t.status===`accepted`&&(O.rejected+=1),O.lastFailure=Object.freeze({type:`ObservationCheckpointError`,message:`provider-attempt audit checkpoint was ${t.status}`,code:p.CAPTURE_REJECTED}),g.end(`rejected`,new Date().toISOString(),l.monotonicMs()),new d(`audit observation is unavailable before provider dispatch`,p.AUDIT_UNAVAILABLE)}catch(e){throw O.pending>0&&--O.pending,e instanceof d&&e.code===p.AUDIT_UNAVAILABLE||(O.rejected+=1,O.lastFailure=a(e),g.end(`rejected`,new Date().toISOString(),l.monotonicMs())),e instanceof d&&e.code===p.AUDIT_UNAVAILABLE?e:new d(`audit observation is unavailable before provider dispatch`,p.AUDIT_UNAVAILABLE,{cause:e})}}else N(v);let b,x=i=>{if(b!==void 0)return b;let a=new Date().toISOString(),s=y(),c=_(i.reported,!0),u=i.dispatchState===`not-sent`?`not-applicable`:c.complete&&i.usageFinal!==!1?`complete`:Object.keys(c.reported).length>0?`partial`:`missing`,d=c.invalidFields.length>0||c.overflow?Object.freeze({type:`UsageValidationError`,message:c.overflow?`provider attempt usage counters overflowed safe integer validation`:`provider attempt usage contained invalid fields: ${c.invalidFields.join(`, `)}`,code:c.overflow?p.USAGE_COUNTER_OVERFLOW:p.USAGE_INVALID}):void 0,v=i.error??d,S=Math.max(0,s-h);g.end(i.status,a,l.monotonicMs());let C=i.providerRequestId===void 0?g.correlation:e({...g.correlation,providerRequestId:i.providerRequestId});return N(e({schemaVersion:1,eventId:n(),sequence:l.nextSequence(),name:`sdk.provider.attempt`,phase:`end`,occurredAt:a,monotonicMs:l.monotonicMs(),priority:`critical`,resource:t.resource,correlation:C,data:{status:i.status,durationMs:S,origin:r.origin,dispatchState:i.dispatchState,coverage:u,reported:{...c.reported},...i.httpStatus===void 0?{}:{httpStatus:i.httpStatus},...i.providerRequestId===void 0?{}:{providerRequestId:i.providerRequestId},...v===void 0?{}:{error:{...v}}}})),b=e({attemptId:f,spanId:g.correlation.spanId,attemptNumber:o,status:i.status,startedAt:m,endedAt:a,durationMs:S,dispatchState:i.dispatchState,coverage:u,reported:c.reported,origin:r.origin,...i.httpStatus===void 0?{}:{httpStatus:i.httpStatus},...i.providerRequestId===void 0?{}:{providerRequestId:i.providerRequestId},...v===void 0?{}:{error:v}}),P.push(b),F.delete(x),b};return F.add(x),Object.freeze({attemptId:f,attemptNumber:o,traceparent:g.traceparent,end:x})}let B=Object.freeze({observation:D,resource:t.resource,correlation:j.correlation,terminalCheckpointOwner:t.context?.terminalCheckpointOwner??`model-call`,scope:l,...t.context?.logger===void 0?{}:{logger:t.context.logger},declareProviderAttemptAccounting:()=>{L=!0},startProviderAttempt:z,recordProviderRetry:R});N(M(`start`,{provider:t.options.provider,model:t.options.model,operation:`stream`}));let V=()=>{},H=new Promise(e=>{V=e}),U=!1,W=!1,G=`unknown`,K,q,J,Y=async()=>{if(U)return{report:await H,auditFailure:!1};U=!0;let n=new Date().toISOString(),r=y();G===`unknown`&&(q??=Object.freeze({type:`OperationTerminalError`,message:`model call closed without a terminal finish reason`,code:p.OPERATION_TERMINAL_MISSING}));for(let e of[...F])e({status:G===`aborted`?`aborted`:`unknown`,dispatchState:t.dispatchState()===`not-sent`?`not-sent`:`unknown`,...q===void 0?{}:{error:q}});try{j.end(G,n,l.monotonicMs())}catch(e){O.lastFailure=a(e)}let i=J===void 0?void 0:_(J,!0),o=!t.routePresent||t.dispatchState()===`not-sent`,d=P.length>0||L?h(P):i===void 0?o?`not-applicable`:`missing`:i.complete?`complete`:`partial`;i&&(i.invalidFields.length>0||i.overflow)?q??=Object.freeze({type:`UsageValidationError`,message:i.overflow?`provider usage counters overflowed safe integer aggregation`:`provider usage contained invalid fields: ${i.invalidFields.join(`, `)}`,code:i.overflow?p.USAGE_COUNTER_OVERFLOW:p.USAGE_INVALID}):d===`missing`&&q===void 0&&(q=Object.freeze({type:`UsageMissingError`,message:`model call may have been dispatched but no provider usage was reported`,code:p.USAGE_MISSING}));let f=Math.max(0,r-S),b=P.length===0?void 0:m(P.map(e=>e.reported)),x=b?.overflow===!0||i?.overflow===!0;x&&(q??=Object.freeze({type:`UsageValidationError`,message:`provider usage counters overflowed safe integer aggregation`,code:p.USAGE_COUNTER_OVERFLOW}));let T=b?.counters??i?.reported??{},E=M(`end`,{status:G,durationMs:f,...K===void 0?{}:{finishReason:K},dispatchState:P.at(-1)?.dispatchState??(t.dispatchState()===`not-sent`?`not-sent`:`unknown`),coverage:d,reported:{...T},attemptCount:P.length}),A=!1;if((B.terminalCheckpointOwner??`model-call`)===`model-call`&&k!==`operational`){O.pending+=1;try{let e=D.checkpoint?await D.checkpoint(E):Object.freeze({eventId:E.eventId,status:`rejected`,durable:!1,boundary:`none`,reason:`exporter-unavailable`}),t=u(e,E.eventId);--O.pending,C(O,t,!0),(t.status!==`accepted`||!t.durable)&&(A=k===`audit`,O.lastFailure=Object.freeze({type:`ObservationCheckpointError`,message:`terminal observation checkpoint was ${t.status}`,code:p.CAPTURE_REJECTED}))}catch(e){--O.pending,O.rejected+=1,O.lastFailure=a(e),A=k===`audit`}}else N(E);let I=e({runId:s,traceId:j.correlation.traceId,modelCallId:c,spanId:j.correlation.spanId,provider:t.options.provider,...t.providerFamily===void 0?{}:{providerFamily:t.providerFamily},...t.providerPluginId===void 0?{}:{providerPluginId:t.providerPluginId},model:t.options.model,status:G,startedAt:v,endedAt:n,durationMs:f,...K===void 0?{}:{finishReason:K},dispatchState:P.at(-1)?.dispatchState??(t.dispatchState()===`not-sent`?`not-sent`:`unknown`),coverage:d,reported:T,attempts:[...P].sort((e,t)=>e.attemptNumber-t.attemptNumber),possiblyBilledAttemptsWithoutUsage:P.length>0?g(P):+(d===`missing`||d===`partial`),authoritative:(d===`complete`||d===`not-applicable`)&&!x,delivery:w(D,k,O),...q===void 0?{}:{error:q}});return V(I),{report:I,auditFailure:A}},X=async function*(){let e,n=!1,r;try{for(e=t.stream(B)[Symbol.asyncIterator]();;){let r=await e.next();if(r.done){n=!0;break}let i=r.value;i.type===`usage`&&(J=i.usage),i.type===`finish`&&(K=i.reason.kind,G=i.reason.kind===`aborted`?`aborted`:i.reason.kind===`error`?`error`:`success`,q=x(i,t.isRetryable)),yield i}}catch(e){throw r=e,G=t.options.signal?.aborted===!0?`aborted`:`error`,q=a(e),e}finally{if(!n){r===void 0&&(G=`aborted`);let t=e?.return?.bind(e);if(t)try{await t()}catch(e){q??=a(e)}}let t=await Y();if(t.auditFailure)throw new f(`audit observation checkpoint failed after model-call finalization`,t.report)}};return Object.freeze({runId:s,modelCallId:c,report:H,[Symbol.asyncIterator](){return W?(async function*(){throw Error(`a model call handle can only be iterated once`)})():(W=!0,X())}})}export{D as createModelCallHandle};
|
|
1
|
+
import{deepFreeze as e}from"../primitives/freeze.js";import{createObservationRunScope as t,createOperationId as n,isSpanId as r,isTraceId as i}from"../observation/context.js";import{safeErrorRecord as a}from"../observation/event.js";import{NOOP_OBSERVATION_PORT as o,createCoreSpan as s,disabledDeliverySummary as c,snapshotObservationSpan as l,validateCaptureReceipt as u}from"../observation/port.js";import{AgentSdkError as d}from"../errors/agent-sdk-error.js";import{ModelCallObservationError as f,OBSERVATION_ERROR_CODES as p}from"../observation/report.js";import{addUsageCounters as m,classifyUsageCoverage as h,possiblyBilledAttemptsWithoutUsage as g,validateUsageCounters as _}from"../observation/usage.js";const v=new WeakMap;function y(){return globalThis.performance?.now()??Date.now()}function b(e,n,r){if(r!==void 0)return r;let i=v.get(e);i||(i=new Map,v.set(e,i));let a=i.get(n);return a||(a=t(),i.set(n,a)),a}function x(e,t){if(e.reason.kind!==`error`&&e.reason.kind!==`aborted`)return;let n=e.reason.failure;return Object.freeze({type:`ModelError`,message:n.message,code:n.code,...t===void 0?{}:{retryable:t(n.code)},...n.status===void 0?{}:{status:n.status}})}function S(e){return e===`remote-acknowledged`?2:+(e===`local-durable`)}function C(e,t,n){n&&(t.status===`accepted`?e.accepted+=1:e.rejected+=1,t.status===`accepted`&&S(t.boundary)>S(e.reached)&&(e.reached=t.boundary))}function w(t,n,r){if(t===o)return c();let i=n===`operational`?`none`:S(r.reached)>0?r.reached:`local-durable`;return e({mode:n,requiredBoundary:i,reachedBoundary:r.reached,complete:r.rejected===0&&r.pending===0&&S(r.reached)>=S(i),acceptedCritical:r.accepted,rejectedCritical:r.rejected,pendingCritical:r.pending,...r.lastFailure===void 0?{}:{lastFailure:r.lastFailure}})}function T(e){if(!(!e||!i(e.traceId)||!r(e.spanId)||typeof e.runId!=`string`||e.runId.length===0))return{traceId:e.traceId,spanId:e.spanId,parentSpanId:e.parentSpanId===null||r(e.parentSpanId)?e.parentSpanId:null,runId:e.runId,...e.conversationId===void 0?{}:{conversationId:e.conversationId},...e.turnId===void 0?{}:{turnId:e.turnId},...e.modelCallId===void 0?{}:{modelCallId:e.modelCallId},...e.attemptId===void 0?{}:{attemptId:e.attemptId},...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},...e.providerRequestId===void 0?{}:{providerRequestId:e.providerRequestId},...e.sessionId===void 0?{}:{sessionId:e.sessionId}}}function E(e,t,n){try{let r=l(e.openSpan(t));if(r&&r.correlation.runId===t.runId&&r.correlation.modelCallId===t.correlation?.modelCallId){let e=!1;return Object.freeze({correlation:r.correlation,traceparent:r.traceparent,end(t,i,o){if(!e){e=!0;try{r.end(t,i,o)}catch(e){n.lastFailure=a(e)}}}})}n.lastFailure=Object.freeze({type:`ObservationSpanError`,message:`observation backend returned an invalid or mismatched span identity`,code:p.OTEL_PROVIDER_UNCONFIGURED})}catch(e){n.lastFailure=a(e)}return s(t)}function D(t){let r=t.context??{},i=t.context?.correlation,s=typeof i?.runId==`string`&&i.runId.length>0?i.runId:n(),c=typeof i?.modelCallId==`string`&&i.modelCallId.length>0?i.modelCallId:n(),l=b(r,s,t.context?.scope),v=new Date().toISOString(),S=y(),D=t.context?.observation??t.defaultObservation??o,O={accepted:0,rejected:0,pending:0,reached:`none`},k=`operational`;try{let e=D.mode;if(e!==`operational`&&e!==`reliable`&&e!==`audit`)throw TypeError(`observation delivery mode is invalid`);k=e}catch(e){O.lastFailure=a(e)}let A=T(i),j=E(D,{name:`sdk.model.call`,runId:s,...A===void 0?{}:{parent:A},correlation:{modelCallId:c,...i?.conversationId===void 0?{}:{conversationId:i.conversationId},...i?.turnId===void 0?{}:{turnId:i.turnId},...i?.sessionId===void 0?{}:{sessionId:i.sessionId}},startedAt:v,monotonicMs:l.monotonicMs()},O),M=(r,i)=>e({schemaVersion:1,eventId:n(),sequence:l.nextSequence(),name:`sdk.model.call`,phase:r,occurredAt:new Date().toISOString(),monotonicMs:l.monotonicMs(),priority:`critical`,resource:t.resource,correlation:j.correlation,data:i}),N=e=>{try{let t=u(D.capture(e),e.eventId);C(O,t,e.priority===`critical`)}catch(t){O.rejected+=+(e.priority===`critical`),O.lastFailure=a(t)}},P=[],F=new Set,I=1,L=!1;function R(r){N(e({schemaVersion:1,eventId:n(),sequence:l.nextSequence(),name:`sdk.provider.retry.scheduled`,phase:`point`,occurredAt:new Date().toISOString(),monotonicMs:l.monotonicMs(),priority:`critical`,resource:t.resource,correlation:j.correlation,data:{nextAttemptNumber:r.nextAttemptNumber,delayMs:r.delayMs,failureCode:r.failureCode}}))}async function z(r,i){let o=I++,f=n(),m=new Date().toISOString(),h=y(),g=E(D,{name:`sdk.provider.attempt`,runId:s,parent:j.correlation,correlation:{modelCallId:c,attemptId:f},startedAt:m,monotonicMs:l.monotonicMs()},O),v=e({schemaVersion:1,eventId:n(),sequence:l.nextSequence(),name:`sdk.provider.attempt`,phase:`start`,occurredAt:m,monotonicMs:l.monotonicMs(),priority:`critical`,resource:t.resource,correlation:g.correlation,data:{provider:r.provider,model:r.model,attemptNumber:o,method:r.method,origin:r.origin,dispatchState:`not-sent`}});if(k===`audit`){O.pending+=1;try{let e=D.checkpoint?await D.checkpoint(v,i):Object.freeze({eventId:v.eventId,status:`rejected`,durable:!1,boundary:`none`,reason:`exporter-unavailable`}),t=u(e,v.eventId);if(--O.pending,C(O,t,!0),t.status!==`accepted`||!t.durable)throw t.status===`accepted`&&(O.rejected+=1),O.lastFailure=Object.freeze({type:`ObservationCheckpointError`,message:`provider-attempt audit checkpoint was ${t.status}`,code:p.CAPTURE_REJECTED}),g.end(`rejected`,new Date().toISOString(),l.monotonicMs()),new d(`audit observation is unavailable before provider dispatch`,p.AUDIT_UNAVAILABLE)}catch(e){throw O.pending>0&&--O.pending,e instanceof d&&e.code===p.AUDIT_UNAVAILABLE||(O.rejected+=1,O.lastFailure=a(e),g.end(`rejected`,new Date().toISOString(),l.monotonicMs())),e instanceof d&&e.code===p.AUDIT_UNAVAILABLE?e:new d(`audit observation is unavailable before provider dispatch`,p.AUDIT_UNAVAILABLE,{cause:e})}}else N(v);let b,x=i=>{if(b!==void 0)return b;let a=new Date().toISOString(),s=y(),c=_(i.reported,!0),u=i.dispatchState===`not-sent`?`not-applicable`:c.complete&&i.usageFinal!==!1?`complete`:Object.keys(c.reported).length>0?`partial`:`missing`,d=c.invalidFields.length>0||c.overflow?Object.freeze({type:`UsageValidationError`,message:c.overflow?`provider attempt usage counters overflowed safe integer validation`:`provider attempt usage contained invalid fields: ${c.invalidFields.join(`, `)}`,code:c.overflow?p.USAGE_COUNTER_OVERFLOW:p.USAGE_INVALID}):void 0,v=i.error??d,S=Math.max(0,s-h);g.end(i.status,a,l.monotonicMs());let C=i.providerRequestId===void 0?g.correlation:e({...g.correlation,providerRequestId:i.providerRequestId});return N(e({schemaVersion:1,eventId:n(),sequence:l.nextSequence(),name:`sdk.provider.attempt`,phase:`end`,occurredAt:a,monotonicMs:l.monotonicMs(),priority:`critical`,resource:t.resource,correlation:C,data:{status:i.status,durationMs:S,origin:r.origin,dispatchState:i.dispatchState,coverage:u,reported:{...c.reported},...i.httpStatus===void 0?{}:{httpStatus:i.httpStatus},...i.providerRequestId===void 0?{}:{providerRequestId:i.providerRequestId},...v===void 0?{}:{error:{...v}}}})),b=e({attemptId:f,spanId:g.correlation.spanId,attemptNumber:o,status:i.status,startedAt:m,endedAt:a,durationMs:S,dispatchState:i.dispatchState,coverage:u,reported:c.reported,origin:r.origin,...i.httpStatus===void 0?{}:{httpStatus:i.httpStatus},...i.providerRequestId===void 0?{}:{providerRequestId:i.providerRequestId},...v===void 0?{}:{error:v}}),P.push(b),F.delete(x),b};return F.add(x),Object.freeze({attemptId:f,attemptNumber:o,traceparent:g.traceparent,end:x})}let B=Object.freeze({observation:D,resource:t.resource,correlation:j.correlation,terminalCheckpointOwner:t.context?.terminalCheckpointOwner??`model-call`,scope:l,...t.context?.logger===void 0?{}:{logger:t.context.logger},...t.context?.agentId===void 0?{}:{agentId:t.context.agentId},...t.context?.providerOptions===void 0?{}:{providerOptions:t.context.providerOptions},declareProviderAttemptAccounting:()=>{L=!0},startProviderAttempt:z,recordProviderRetry:R});N(M(`start`,{provider:t.options.provider,model:t.options.model,operation:`stream`}));let V=()=>{},H=new Promise(e=>{V=e}),U=!1,W=!1,G=`unknown`,K,q,J,Y=async()=>{if(U)return{report:await H,auditFailure:!1};U=!0;let n=new Date().toISOString(),r=y();G===`unknown`&&(q??=Object.freeze({type:`OperationTerminalError`,message:`model call closed without a terminal finish reason`,code:p.OPERATION_TERMINAL_MISSING}));for(let e of[...F])e({status:G===`aborted`?`aborted`:`unknown`,dispatchState:t.dispatchState()===`not-sent`?`not-sent`:`unknown`,...q===void 0?{}:{error:q}});try{j.end(G,n,l.monotonicMs())}catch(e){O.lastFailure=a(e)}let i=J===void 0?void 0:_(J,!0),o=!t.routePresent||t.dispatchState()===`not-sent`,d=P.length>0||L?h(P):i===void 0?o?`not-applicable`:`missing`:i.complete?`complete`:`partial`;i&&(i.invalidFields.length>0||i.overflow)?q??=Object.freeze({type:`UsageValidationError`,message:i.overflow?`provider usage counters overflowed safe integer aggregation`:`provider usage contained invalid fields: ${i.invalidFields.join(`, `)}`,code:i.overflow?p.USAGE_COUNTER_OVERFLOW:p.USAGE_INVALID}):d===`missing`&&q===void 0&&(q=Object.freeze({type:`UsageMissingError`,message:`model call may have been dispatched but no provider usage was reported`,code:p.USAGE_MISSING}));let f=Math.max(0,r-S),b=P.length===0?void 0:m(P.map(e=>e.reported)),x=b?.overflow===!0||i?.overflow===!0;x&&(q??=Object.freeze({type:`UsageValidationError`,message:`provider usage counters overflowed safe integer aggregation`,code:p.USAGE_COUNTER_OVERFLOW}));let T=b?.counters??i?.reported??{},E=M(`end`,{status:G,durationMs:f,...K===void 0?{}:{finishReason:K},dispatchState:P.at(-1)?.dispatchState??(t.dispatchState()===`not-sent`?`not-sent`:`unknown`),coverage:d,reported:{...T},attemptCount:P.length}),A=!1;if((B.terminalCheckpointOwner??`model-call`)===`model-call`&&k!==`operational`){O.pending+=1;try{let e=D.checkpoint?await D.checkpoint(E):Object.freeze({eventId:E.eventId,status:`rejected`,durable:!1,boundary:`none`,reason:`exporter-unavailable`}),t=u(e,E.eventId);--O.pending,C(O,t,!0),(t.status!==`accepted`||!t.durable)&&(A=k===`audit`,O.lastFailure=Object.freeze({type:`ObservationCheckpointError`,message:`terminal observation checkpoint was ${t.status}`,code:p.CAPTURE_REJECTED}))}catch(e){--O.pending,O.rejected+=1,O.lastFailure=a(e),A=k===`audit`}}else N(E);let I=e({runId:s,traceId:j.correlation.traceId,modelCallId:c,spanId:j.correlation.spanId,provider:t.options.provider,...t.providerFamily===void 0?{}:{providerFamily:t.providerFamily},...t.providerPluginId===void 0?{}:{providerPluginId:t.providerPluginId},model:t.options.model,status:G,startedAt:v,endedAt:n,durationMs:f,...K===void 0?{}:{finishReason:K},dispatchState:P.at(-1)?.dispatchState??(t.dispatchState()===`not-sent`?`not-sent`:`unknown`),coverage:d,reported:T,attempts:[...P].sort((e,t)=>e.attemptNumber-t.attemptNumber),possiblyBilledAttemptsWithoutUsage:P.length>0?g(P):+(d===`missing`||d===`partial`),authoritative:(d===`complete`||d===`not-applicable`)&&!x,delivery:w(D,k,O),...q===void 0?{}:{error:q}});return V(I),{report:I,auditFailure:A}},X=async function*(){let e,n=!1,r;try{for(e=t.stream(B)[Symbol.asyncIterator]();;){let r=await e.next();if(r.done){n=!0;break}let i=r.value;i.type===`usage`&&(J=i.usage),i.type===`finish`&&(K=i.reason.kind,G=i.reason.kind===`aborted`?`aborted`:i.reason.kind===`error`?`error`:`success`,q=x(i,t.isRetryable)),yield i}}catch(e){throw r=e,G=t.options.signal?.aborted===!0?`aborted`:`error`,q=a(e),e}finally{if(!n){r===void 0&&(G=`aborted`);let t=e?.return?.bind(e);if(t)try{await t()}catch(e){q??=a(e)}}let t=await Y();if(t.auditFailure)throw new f(`audit observation checkpoint failed after model-call finalization`,t.report)}};return Object.freeze({runId:s,modelCallId:c,report:H,[Symbol.asyncIterator](){return W?(async function*(){throw Error(`a model call handle can only be iterated once`)})():(W=!0,X())}})}export{D as createModelCallHandle};
|
|
2
2
|
//# sourceMappingURL=model-call-handle.js.map
|